From 1c5568ba7779727606b8fd5e55a020cb93fcff63 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Wed, 6 May 2026 23:14:43 +0200 Subject: [PATCH 001/516] Initial draft for CGP v0.7.1 blog post --- blog/2026-05-10-v0.7.1-release.md | 96 +++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 blog/2026-05-10-v0.7.1-release.md diff --git a/blog/2026-05-10-v0.7.1-release.md b/blog/2026-05-10-v0.7.1-release.md new file mode 100644 index 00000000..60a31702 --- /dev/null +++ b/blog/2026-05-10-v0.7.1-release.md @@ -0,0 +1,96 @@ +--- +authors: [soares] +tags: [release] +--- + +# CGP v0.7.1 - Grouping components with namespaces and paths + +**CGP v0.7.1** has been released, and it comes with major ergonomic improvements to manage CGP components at scale. In this blog post, we will explore the problems with managing CGP components, and how the new namespace feature in CGP v0.7.1 helps solve the problem. + +{/* truncate */} + +## The challenges of scaling CGP + +Up until now, one of main challenges of using CGP is on the boilerplate of using `delegate_components!` to wire CGP providers, especially as the number of CGP components grow within an application. When there are too many entries inside `delegate_components!`, developers quickly get lost on what they should pay attention to, and it gives the impression that the application becomes too complex. + +To demonstrate the challenge, we will make use of a simple web application as an example. Suppose that we want to build a simple social media web app, we could use CGP to define modular traits to expose simple CRUD capabilities for managing users and posts. A simplified version of the traits would look something like follows: + +```rust +#[cgp_component(UserManager)] +pub trait CanManageUser { + fn create_user(&self, username: &str, email: &Email) -> Result; + + fn get_user(&self, user_id: &UserId) -> Result; + + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; +} + +#[cgp_component(PostManager)] +pub trait CanManagePost { + fn create_post(&self, title: &str, content: &str) -> Result; + + fn get_post(&self, post_id: &PostId) -> Result; + + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; + + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; +} +``` + +Our trait definitions are as straightforward as vanilla trait definitions, aside from the use of `#[cgp_component]` to turn them into CGP traits. The main advantage is that we can now define context-generic implementations for the traits. For example, we can implement production-ready providers as follows: + +```rust +#[cgp_impl(new ProductionUserManager)] +impl UserManager { + fn create_user( + &self, + #[implicit] database: &Database, + username: &str, + email: &Email, + ) -> Result { + // ... + } + + fn get_user(&self, #[implicit] database: &Database, user_id: &UserId) -> Result { + // ... + } + + fn update_user_data( + &self, + #[implicit] database: &Database, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + // ... + } +} + +#[cgp_impl(new ProductionPostManager)] +impl PostManager { + fn create_post( + &self, + #[implicit] database: &Database, + title: &str, + content: &str, + ) -> Result { + // ... + } + + fn get_post(&self, #[implicit] database: &Database, post_id: &PostId) -> Result { + // ... + } + + fn update_post( + &self, + #[implicit] database: &Database, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + // ... + } + + fn delete_post(&self, #[implicit] database: &Database, post_id: &PostId) -> Result<(), Error> { + // ... + } +} +``` From 4e120d55dfa3ee401e50d82e4327241d0d6599d3 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Wed, 6 May 2026 23:26:45 +0200 Subject: [PATCH 002/516] More draft --- blog/2026-05-10-v0.7.1-release.md | 40 ++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/blog/2026-05-10-v0.7.1-release.md b/blog/2026-05-10-v0.7.1-release.md index 60a31702..2f7b00b5 100644 --- a/blog/2026-05-10-v0.7.1-release.md +++ b/blog/2026-05-10-v0.7.1-release.md @@ -13,6 +13,8 @@ tags: [release] Up until now, one of main challenges of using CGP is on the boilerplate of using `delegate_components!` to wire CGP providers, especially as the number of CGP components grow within an application. When there are too many entries inside `delegate_components!`, developers quickly get lost on what they should pay attention to, and it gives the impression that the application becomes too complex. +### An example social media web app + To demonstrate the challenge, we will make use of a simple web application as an example. Suppose that we want to build a simple social media web app, we could use CGP to define modular traits to expose simple CRUD capabilities for managing users and posts. A simplified version of the traits would look something like follows: ```rust @@ -51,7 +53,11 @@ impl UserManager { // ... } - fn get_user(&self, #[implicit] database: &Database, user_id: &UserId) -> Result { + fn get_user( + &self, + #[implicit] database: &Database, + user_id: &UserId, + ) -> Result { // ... } @@ -76,7 +82,11 @@ impl PostManager { // ... } - fn get_post(&self, #[implicit] database: &Database, post_id: &PostId) -> Result { + fn get_post( + &self, + #[implicit] database: &Database, + post_id: &PostId, + ) -> Result { // ... } @@ -89,8 +99,32 @@ impl PostManager { // ... } - fn delete_post(&self, #[implicit] database: &Database, post_id: &PostId) -> Result<(), Error> { + fn delete_post( + &self, + #[implicit] database: &Database, + post_id: &PostId, + ) -> Result<(), Error> { // ... } } ``` + +Our production provider implementations are not coupled with any concrete application context, and CGP allows us to reuse it on any application context that provides the required dependencies, such as the `Database` field. + +With this minimal settings, the configuration for our production application is straightforward, and can be written as follows: + +```rust +#[derive(HasField)] +pub struct ProductionApp { + pub database: Database, +} + +delegate_and_check_components! { + ProductionApp { + UserManagerComponent: ProductionUserManager, + PostManagerComponent: ProductionPostManager, + } +} +``` + +With just two lines of configurations, we have managed to configure our `ProductionApp` to use the `ProductionUserManager` and the `ProductionPostManager` providers that we have defined, without tightly coupling the implementations with the `ProductionApp` context. From d0bc4561cbce4de65d3bd5522a624b731333b4b1 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Thu, 7 May 2026 23:36:26 +0200 Subject: [PATCH 003/516] More draft --- blog/2026-05-10-v0.7.1-release.md | 220 ++++++++++++++++++++++++++++-- 1 file changed, 206 insertions(+), 14 deletions(-) diff --git a/blog/2026-05-10-v0.7.1-release.md b/blog/2026-05-10-v0.7.1-release.md index 2f7b00b5..34359b0d 100644 --- a/blog/2026-05-10-v0.7.1-release.md +++ b/blog/2026-05-10-v0.7.1-release.md @@ -42,11 +42,11 @@ pub trait CanManagePost { Our trait definitions are as straightforward as vanilla trait definitions, aside from the use of `#[cgp_component]` to turn them into CGP traits. The main advantage is that we can now define context-generic implementations for the traits. For example, we can implement production-ready providers as follows: ```rust -#[cgp_impl(new ProductionUserManager)] +#[cgp_impl(new PostgresUserManager)] impl UserManager { fn create_user( &self, - #[implicit] database: &Database, + #[implicit] database: &PostgresDb, username: &str, email: &Email, ) -> Result { @@ -55,7 +55,7 @@ impl UserManager { fn get_user( &self, - #[implicit] database: &Database, + #[implicit] database: &PostgresDb, user_id: &UserId, ) -> Result { // ... @@ -63,7 +63,7 @@ impl UserManager { fn update_user_data( &self, - #[implicit] database: &Database, + #[implicit] database: &PostgresDb, user_id: &UserId, user_data: &UserData, ) -> Result<(), Error> { @@ -71,11 +71,11 @@ impl UserManager { } } -#[cgp_impl(new ProductionPostManager)] +#[cgp_impl(new PostgresPostManager)] impl PostManager { fn create_post( &self, - #[implicit] database: &Database, + #[implicit] database: &PostgresDb, title: &str, content: &str, ) -> Result { @@ -84,7 +84,7 @@ impl PostManager { fn get_post( &self, - #[implicit] database: &Database, + #[implicit] database: &PostgresDb, post_id: &PostId, ) -> Result { // ... @@ -92,7 +92,7 @@ impl PostManager { fn update_post( &self, - #[implicit] database: &Database, + #[implicit] database: &PostgresDb, post_id: &PostId, content: &str, ) -> Result<(), Error> { @@ -101,7 +101,7 @@ impl PostManager { fn delete_post( &self, - #[implicit] database: &Database, + #[implicit] database: &PostgresDb, post_id: &PostId, ) -> Result<(), Error> { // ... @@ -109,22 +109,214 @@ impl PostManager { } ``` -Our production provider implementations are not coupled with any concrete application context, and CGP allows us to reuse it on any application context that provides the required dependencies, such as the `Database` field. +Our production provider implementations are not coupled with any concrete application context, and CGP allows us to reuse it on any application context that provides the required dependencies, such as the PostgreSQL `database` field. + +CGP also enables us to define other context-generic provider implementations for the traits, such as an `SqliteUserManager` and `SqlitePostManager` that implements the queries using SQLite instead of PostgreSQL. With this minimal settings, the configuration for our production application is straightforward, and can be written as follows: ```rust #[derive(HasField)] pub struct ProductionApp { - pub database: Database, + pub database: PostgresDb, } delegate_and_check_components! { ProductionApp { - UserManagerComponent: ProductionUserManager, - PostManagerComponent: ProductionPostManager, + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + } +} +``` + +With just two lines of configurations, we have managed to configure our `ProductionApp` to use the `PostgresUserManager` and the `PostgresPostManager` providers that we have defined, without tightly coupling the implementations with the `ProductionApp` context. + +### Filtering usernames and post messages + +Our base implementation of `PostgresUserManager` and `PostgresPostManager` only have a single dependency to the PostgreSQL database. But as the application grows, the methods may require additional dependencies to implement more features. + +For example, we may want to ban certain words in the username, or detect and reject spam messages when creating a post. With the earlier traits, we may implement those functionalities as follows: + +```rust +#[cgp_component(UsernameCensor)] +pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; +} + +#[cgp_component(SpamMessageDetector)] +pub trait CanDetectSpamMessage { + fn message_is_spam(&self, message: &str) -> Probability; +} + +#[cgp_impl(new PostgresUserManager)] +#[uses(CanCensorUsername)] +impl UserManager { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername) + } + + // ... + } + + // ... +} + +#[cgp_impl(new PostgresPostManager)] +#[uses(CanDetectSpamMessage)] +impl PostManager { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + if self.message_is_spam(content) > Probability::new(0.8) { + return Err(Error::InvalidMessage) + } + + // ... + } + + // ... +} +``` + +In the above example, we introduce two new CGP traits, `UsernameCensor` and `SpamMessageDetector`, to be used by `PostgresUserManager` and `PostgresPostManager`. The providers make use of the probability scores returned by the filters to determine whether to reject the creation of a user or post. + +In production, the implementation of features like spam filters may employ sophisticated setup, such as using AI or a cloud service provider. But in testing environments, we may want to make use of simplified setup to test the other parts of the application more quickly. With CGP, we can do so by defining two separate contexts such as follows: + +```rust +pub struct ProductionApp { + pub database: PostgresDb, + // ... +} + +delegate_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: AiUserCensor, + SpamMessageDetectorComponent: AiSpamMessageDetector, + } +} + +pub struct TestApp { + pub database: PostgresDb, + // ... +} + +delegate_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: DummyUserCensor, + SpamMessageDetectorComponent: DummySpamMessageDetector, + } +} +``` + +In the example above, we have a `ProductionApp` that is used in production, and a `TestApp` that is used for testing. Both `ProductionApp` and `TestApp` make use of the same PostgreSQL database backend, and thus they reuse the same `PostgresUserManager` and `PostgresPostManager` providers. But `ProductionApp` uses providers that make use of AI to detect spam and censored usernames, while `TestApp` uses dummy implementation that performs detection with simple string pattern matching. + +As we can see, CGP makes it easy to organically extend the dependency tree of an application context. However, with the transitive dependencies, we now have 4 items listed in 2 contexts, resulting in 8 wiring configuration entries. + +### Fine grained traits + +If we look carefully at the implementation of `PostgresUserManager`, we can notice that the trait `CanCensorUsername` is not really needed by `get_user` and `update_user_data`. Similarly, in `PostgresPostManager`, the trait `CanDetectSpamMessage` is not needed by `get_post`, `update_post`, and `delete_post`. + +In practice, the accumulation of dependencies like `CanDetectSpamMessage` can quickly pile up in trait implementations, especially when the number of trait methods increases. The long list of dependencies can make it harder to maintain and test the implementations. + +As the application grows, pressure will increase on how to better organize which method belongs to which trait. For example, we may need to decide whether a `get_user_profile_picture` method should belong to the `UserManager` trait. Furthermore, when a method involves multiple domains, such as `get_user_posts`, it is not clear whether they should be placed in `UserManager` or `PostManager`. + +In more advanced use cases, we may also want to make use of CGP to isolate capabilities that can be used in a piece of code. For example, since user deletion is very destructive, we may not want to expose a `delete_user` method to all code that have access to `UserManager`. + +One of the simple but powerful design patterns that is enabled by CGP is that we can break down monolithic trait definitions like `UserManager` into *fine-grained traits* that each contains only one or a handful of items. For example: + +```rust +#[cgp_component(UserCreator)] +pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; +} + +#[cgp_component(UserGetter)] +pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; +} + +#[cgp_component(UserUpdater)] +pub trait CanUpdateUser { + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; +} +``` + +With the fine grained traits, it becomes much easier for us to isolate the dependencies and only expose them to implementations that really need them. For example, the `CanCensorUsername` consumer trait can now be imported in the `UserCreator` implementation: + +```rust +#[cgp_impl(new CreateUserWithPostgres)] +#[uses(CanCensorUsername)] +impl UserCreator { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername) + } + + // ... + } +} + +#[cgp_impl(new GetUserWithPostgres)] +impl UserGetter { + fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { + // ... } } ``` -With just two lines of configurations, we have managed to configure our `ProductionApp` to use the `ProductionUserManager` and the `ProductionPostManager` providers that we have defined, without tightly coupling the implementations with the `ProductionApp` context. +Instead of having a monolithic `PostgresUserManager` provider, we now have fine grained providers like `CreateUserWithPostgres` and `GetUserWithPostgres` that implement each fine grained trait separately. We can also see that the dependency to `CanCensorUsername` is only present in the implementation of `CreateUserWithPostgres`, while other providers like `GetUserWithPostgres` can work fine without requiring that trait to be implemented by the context. + +### Higher-order providers + +Another key advantage of using fine grained traits is that we can now easily define *higher-order providers* that wrap around other provider implementations. For example, we can extra the logic of banning censored username into a separate provider like follows: + +```rust +#[cgp_impl(new FilterCensoredUsername)] +#[uses(CanCensorUsername)] +#[use_provider(InnerCreator: UserCreator)] +impl UserCreator { + fn create_user(&self, username: &str, email: &Email) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + InnerCreator::create_user(self, username, email) + } +} + +#[cgp_impl(new CreateUserWithPostgres)] +impl UserCreator { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + // ... + } +} +``` + +In the example above, we introduce a higher-order provider called `FilterCensoredUsername`, which can wrap around an inner provider for `UserCreator`. It would reject a call to `create_user` based on the result from `CanCensorUsername`. Otherwise, it forwards the call to the inner provider. + +With this separation of concern, we can now remove the dependency on `CanCensorUsername` from `CreateUserWithPostgres`, which can now focus purely on constructing the SQL insert query. Instead of always filtering the username, the logic becomes composable, allowing the concrete context to choose either just `CreateUserWithPostgres` or the combined `FilterCensoredUsername` provider to handle user creation. + +This separation of concern also allows logic like `FilterCensoredUsername` to be reused with other inner providers. For example, suppose that we also have a separate `CreateUserWithSqlite` provider that can be used by a local-first application. We can now enable the filtering of user creation using `FilterCensoredUsername`. From 02ea39a1a79893e5a135fa876475c4f28518abb2 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 8 May 2026 22:12:27 +0200 Subject: [PATCH 004/516] Finish challenges section --- blog/2026-05-10-v0.7.1-release.md | 160 ++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) diff --git a/blog/2026-05-10-v0.7.1-release.md b/blog/2026-05-10-v0.7.1-release.md index 34359b0d..327c2c4b 100644 --- a/blog/2026-05-10-v0.7.1-release.md +++ b/blog/2026-05-10-v0.7.1-release.md @@ -320,3 +320,163 @@ In the example above, we introduce a higher-order provider called `FilterCensore With this separation of concern, we can now remove the dependency on `CanCensorUsername` from `CreateUserWithPostgres`, which can now focus purely on constructing the SQL insert query. Instead of always filtering the username, the logic becomes composable, allowing the concrete context to choose either just `CreateUserWithPostgres` or the combined `FilterCensoredUsername` provider to handle user creation. This separation of concern also allows logic like `FilterCensoredUsername` to be reused with other inner providers. For example, suppose that we also have a separate `CreateUserWithSqlite` provider that can be used by a local-first application. We can now enable the filtering of user creation using `FilterCensoredUsername`. + +### Too much wiring with fine grained traits + +As we can see, the use of fine grained traits and higher order providers allows us to nicely decompose and decouple the dependencies that each trait needs. However, the main issue with this approach is that the boilerplate for wiring the components become significantly more verbose. For instance, the wiring for `ProductionApp` would become: + +```rust +delegate_components! { + ProductionApp { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + PostCreatorComponent: + FilterSpamMessage, + PostGetterComponent: + GetPostWithPostgres, + PostUpdaterComponent: + UpdatePostWithPostgres, + PostDeleterComponent: + DeletePostWithPostgres, + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } +} +``` + +Compared to before, there are now 9 component entries in `ProductionApp`, as compared to the list of 4 components earlier. And given that this example only include minimal features, it is not uncommon for real world applications to have dozens if not hundreds of component wirings if fine grained traits are used. + +This presents a significant challenge to spread the adoption of CGP. To the eyes of an untrained developers, the hundreds of lines of component wirings are noise that brings confusion on what `ProductionApp` really implements. + +If we consider the principles of good programming practices, the real problem with the code above is that too much information are presented at once. What we need is to group the component wirings back into smaller sub-units, so that they can be read and understood piece by piece. + +For example, we could group the user-related traits together as follows: + +```rust +delegate_components! { + new PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + } +} +``` + +With the code above, we define an *aggregated provider* called `PostgresUserComponents` which encapsulates all user-related CGP traits. Since this standalone definition only contains 3 entries, it is much more manageable to understand what this aggregated provider implements. + +Similarly, we can define a `PostgresPostComponents` to group all post-related CGP traits, and a `ContentFilterComponents` to group the username and spam message filters. + +### The challenges of grouping delegate component keys + +However, before the current v0.7.1 release, even though we have ways to group CGP component wirings, there lacked good developer experience for using these aggregated providers at the top-level component wiring. For example, the component wiring for `ProductionApp` can at best be simplified into: + +```rust +delegate_components! { + ProductionApp { + [ + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + ]: + PostgresUserComponents, + [ + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + ]: + PostgresPostComponents, + [ + UsernameCensorComponent, + SpamMessageDetectorComponent, + ]: + ContentFilterComponents, + } +} +``` + +In the code above, we make use of the array notation to forward a group of keys, such as `UserCreatorComponent`, `UserGetterComponent`, and `UserUpdaterComponent`, all to the same aggregated provider, i.e. `PostgresUserComponents`. + +The problem we have here is that CGP had no way encapsulate the group of component keys used in the wiring. What we really wanted is to express something like follows: + +```rust +delegate_components! { + ProductionApp { + ???: // all user components + PostgresUserComponents, + ???: // all post components + PostgresPostComponents, + ???: // all content filter components + ContentFilterComponents, + } +} +``` + +However, due to how CGP internally makes use of the trait system, it is not possible to directly express something like *"implement `DelegateComponent` for these list of types"* with Rust's existing trait system. + +The closest technique that CGP could use is to use macros to expand the identifier, such as: + +```rust +delegate_components! { + ProductionApp { + all_user_components!(): + PostgresUserComponents, + all_post_components!(): + PostgresPostComponents, + all_content_filter_components!(): + ContentFilterComponents, + } +} +``` + +where the macros like `all_user_components!()` expand into `[UserCreatorComponent, UserGetterComponent, UserUpdaterComponent]`. But even this wouldn't work, because Rust macros are expanded lazily, meaning that `delegate_components!` could only see the unexpanded literal `all_user_components!()`, and thus cannot properly desugar the entries. + +Furthermore, there is no easy way for CGP to generate macros like `all_user_components!()` for the user. That is, there are limited support in Rust's macro system to allow macros to generate and export new macros. + +### The problems with CGP presets + +Since the early days of the project, we have experimented with various ways to work around the limitations of Rust macros, and implemented a [**preset system**](/blog/hypershell-release#cgp-presets) system to group a collection of component wirings together to form a preset. However, there are many issues with providing a good developer experience through CGP presets. + +With CGP presets, we could define a `PostgresUserComponents` preset like follows: + +```rust +cgp_preset! { + PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + } +} +``` + +and then use the components by inheriting it in `ProductionApp`: + +```rust +#[cgp_inherit(PostgresUserComponents)] +pub struct ProductionApp { /* ... */ } + +delegate_components! { + ProductionApp { + // No need to delegate entries in PostgresUserComponents + // ... + } +} +``` + +However, the biggest limitation of CGP presets is that it supports only a single-inheritance-like hierarchy of components. This means that since `ProductionApp` has "inherited" `PostgresUserComponents`, it cannot also inherit another preset like `PostgresPostComponents` due to the coherence restrictions in Rust. + +We have also experimented on a multiple-inheritance-like feature with CGP presets using macros. However, the lack of eager macro evaluation and hygenic bindings of imports make it tedious to use the feature. + +## Introducing CGP namespaces and paths From 80b149c3ab72d9acf3880b1f1db1ec6ecfd5e9b7 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 8 May 2026 23:12:12 +0200 Subject: [PATCH 005/516] Add intro to CGP namespaces --- blog/2026-05-10-v0.7.1-release.md | 56 +++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/blog/2026-05-10-v0.7.1-release.md b/blog/2026-05-10-v0.7.1-release.md index 327c2c4b..43423ea8 100644 --- a/blog/2026-05-10-v0.7.1-release.md +++ b/blog/2026-05-10-v0.7.1-release.md @@ -480,3 +480,59 @@ However, the biggest limitation of CGP presets is that it supports only a single We have also experimented on a multiple-inheritance-like feature with CGP presets using macros. However, the lack of eager macro evaluation and hygenic bindings of imports make it tedious to use the feature. ## Introducing CGP namespaces and paths + +Fortunately, with CGP v0.7.1, we have managed to solve the long-standing problem and devise a way to group component keys through a new feature called **namespaces**. + +The way CGP namespaces work is as follows. For each CGP component definition, we can define a namespace prefix like follows: + +```rust +#[cgp_component(UserCreator)] +#[namespace(@app.core.user)] +pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; +} +``` + +In the code above, we add a new `#[namespace]` attribute to the `UserCreator` component, with a prefix `@app.core.user`. This prefix acts as the new group "key" that we will use later in `delegate_components!`. + +CGP allows the same namespace prefix to be used by multiple traits. For example, we can also apply the `@app.core.user` prefix to `UserGetter`, and similarly to `UserUpdater`: + +```rust +#[cgp_component(UserGetter)] +#[namespace(@app.core.user)] +pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; +} +``` + +Similarly, we can assign the prefix `@app.core.post` to `PostCreator`, and other post-related traits: + +```rust +#[cgp_component(PostCreator)] +#[namespace(@app.core.post)] +pub trait CanCreatePost { + fn create_post(&self, title: &str, content: &str) -> Result; +} +``` + +We would also assign the prefix `@app.core.content_filter` to `UsernameCensor` and `SpamMessageDetector`. + +After assigning the namespace prefixes, we can now use them to bulk delegate the CGP components in the top-level wiring for `ProductionApp`: + +```rust +delegate_components! { + ProductionApp { + namespace default; + + @app.core.user: PostgresUserComponents, + @app.core.post: PostgresPostComponents, + @app.extra.content_filter: ContentFilterComponents, + } +} +``` + +Compared to before, our new definition for `ProductionApp` becomes significantly shorter and concise. Since namespace is an opt-in feature, we explicitly enable it using the `namespace` keyword inside the `delegate_components!` block. The `default` namespace is used here, but as we will see in later sections, it is also possible to define custom namespaces and assign different prefixes to CGP components. + +Following that, a delegate key like `@app.core.user` implicitly forwards all implementation of the user-related CGP traits to the aggregated provider `PostgresUserComponents`. Similarly, the next two entries delegate the corresponding CGP components to the respective aggregated providers. + +CGP namespaces allows us to group CGP component keys into a hierarchy of prefixes. This in turns allows us to cleanly encapsulate group of CGP components, and break down the wiring configuration into smaller parts. From 012cf0c3ad0d8e732f3d3ce7320b8541b89a1142 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 8 May 2026 23:32:37 +0200 Subject: [PATCH 006/516] Add hierarchical delegation section --- blog/2026-05-10-v0.7.1-release.md | 84 ++++++++++++++++++++++++++++--- 1 file changed, 78 insertions(+), 6 deletions(-) diff --git a/blog/2026-05-10-v0.7.1-release.md b/blog/2026-05-10-v0.7.1-release.md index 43423ea8..5140da03 100644 --- a/blog/2026-05-10-v0.7.1-release.md +++ b/blog/2026-05-10-v0.7.1-release.md @@ -371,9 +371,9 @@ delegate_components! { } ``` -With the code above, we define an *aggregated provider* called `PostgresUserComponents` which encapsulates all user-related CGP traits. Since this standalone definition only contains 3 entries, it is much more manageable to understand what this aggregated provider implements. +With the code above, we define an *aggregated provider* called `PostgresUserComponents` which encapsulates all PostgreSQL-based user-related providers. Since this standalone definition only contains 3 entries, it is much more manageable to understand what this aggregated provider implements. -Similarly, we can define a `PostgresPostComponents` to group all post-related CGP traits, and a `ContentFilterComponents` to group the username and spam message filters. +Similarly, we can define a `PostgresPostComponents` to group all PostgreSQL-based post-related providers, and a `AiContentFilterComponents` to group the AI-based username and spam message filter providers. ### The challenges of grouping delegate component keys @@ -399,7 +399,7 @@ delegate_components! { UsernameCensorComponent, SpamMessageDetectorComponent, ]: - ContentFilterComponents, + AiContentFilterComponents, } } ``` @@ -416,7 +416,7 @@ delegate_components! { ???: // all post components PostgresPostComponents, ???: // all content filter components - ContentFilterComponents, + AiContentFilterComponents, } } ``` @@ -433,7 +433,7 @@ delegate_components! { all_post_components!(): PostgresPostComponents, all_content_filter_components!(): - ContentFilterComponents, + AiContentFilterComponents, } } ``` @@ -526,7 +526,7 @@ delegate_components! { @app.core.user: PostgresUserComponents, @app.core.post: PostgresPostComponents, - @app.extra.content_filter: ContentFilterComponents, + @app.extra.content_filter: AiContentFilterComponents, } } ``` @@ -535,4 +535,76 @@ Compared to before, our new definition for `ProductionApp` becomes significantly Following that, a delegate key like `@app.core.user` implicitly forwards all implementation of the user-related CGP traits to the aggregated provider `PostgresUserComponents`. Similarly, the next two entries delegate the corresponding CGP components to the respective aggregated providers. +### Hierarchical delegation + CGP namespaces allows us to group CGP component keys into a hierarchy of prefixes. This in turns allows us to cleanly encapsulate group of CGP components, and break down the wiring configuration into smaller parts. + +CGP allows us to not only group components into prefixes, but also group child prefixes using the parent prefixes. In the earlier example, the prefix `@app.core.user` has a parent prefix `@app.core`, which in turns has a parent prefix `@app`. And since the prefix `@app.core.post` also has `@app.core` as its parent prefix, this means that we can group both group of components together using `@app.core`. + +With this, we can for example define an aggregated provider for all core components for the application, like: + +```rust +delegate_components! { + new PostgresCoreComponents { + namespace default; + + @app.core.user: PostgresUserComponents, + @app.core.post: PostgresPostComponents, + // other core components + } +} + +delegate_components! { + new ProductionExtraComponents { + namespace default; + + @app.extra.content_filter: AiContentFilterComponents, + // other extra components + } +} +``` + +With these intermediary aggregated providers, our top-level wiring for `ProductionApp` is now reduced to just: + +```rust +delegate_components! { + ProductionApp { + namespace default; + + @app.core: PostgresCoreComponents, + @app.extra: ProductionExtraComponents, + } +} +``` + +A key benefit for this hierarchical separation is that it also becomes much easier to distinguish the difference in behavior of different contexts. For example, if we see a definition of `TestApp` as follows: + +```rust +delegate_components! { + TestApp { + namespace default; + + @app.core: PostgresCoreComponents, + @app.extra: DummyExtraComponents, + } +} +``` + +We can easily deduce from the definition that `TestApp` uses the same PostgreSQL-based core components, but replace the non-essential extra components like content filter with dummy implementations to speed up the tests. + +Similarly, if we see another definition of `LocalApp` like: + +```rust +delegate_components! { + LocalApp { + namespace default; + + @app.core: SqliteCoreComponents, + @app.extra: ProductionExtraComponents, + } +} +``` + +We know that all PostgreSQL-specific core logic has been replaced by an SQLite-specific database backend. + +If we were to define the same 3 contexts without namespaces, the difference in developer experience is stark. A new developer would need to scan through the dozens of lines of component wirings between the 3 contexts. Worse yet, the component wirings may be defined in different orders, making it extremely difficult to compare using humen eyes. From 3b5dfd777f2bdbbb99fe42f0f4113846d5ba6a98 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 25 Jul 2026 23:51:47 +0200 Subject: [PATCH 007/516] Renumber the namespace draft to v0.8.0, and add AGENTS.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The namespace release was begun as v0.7.1, when the feature was expected to be a minor addition. It grew to need a component-path system, the `open` statement, per-type defaults, and the removal of the preset mechanism it replaces, so the release was renumbered to v0.8.0. Rename the draft announcement to match and update the version references in its title and body. Set an explicit slug on the post. Without one Docusaurus publishes under a dated path — the rename alone would have produced /blog/2026/05/10/v0.8.0-release rather than the flat URL every other release post uses. The post's date remains a placeholder and must be set to the real release date before it ships. Add AGENTS.md for agents working in this repository. It points at the knowledge base as the source of truth for every page, and states the rules that repository cannot state from here: published pages may never link into the internal base, code is verified against the current `cgp` release and never copied from an older post, public prose follows the communication strategy, and a dated blog post is not rewritten into agreement with the current library. It is not part of the built site, so it may reference internal material freely. Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 146 ++++++++++++++++++ ...elease.md => 2026-05-10-v0.8.0-release.md} | 9 +- 2 files changed, 151 insertions(+), 4 deletions(-) create mode 100644 AGENTS.md rename blog/{2026-05-10-v0.7.1-release.md => 2026-05-10-v0.8.0-release.md} (98%) diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..1c15d307 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,146 @@ +# AGENTS.md — the CGP website + +This repository is the public website for Context-Generic Programming, published at +. Everything in `docs/`, `blog/`, and `src/pages/` is read by Rust +developers evaluating CGP, most of whom have never heard of the project's internal documentation. That +audience governs every rule below. + +**Before writing or revising any page, read the knowledge base's documentation for it.** This +repository is deliberately thin on context: it holds the published prose and nothing about where that +prose came from, how current it is, or how it should be framed. All of that lives in the +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base), whose +[`website/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/website) section carries +one document per page here — one per blog post, one per tutorial series, and one covering the site's +configuration and standalone pages. Find the document for the page you are about to touch, read it, +follow its links, and only then write. + +## Finding the knowledge base + +Look for the checkout at `../cgp-knowledge-base` first; the CGP repositories are expected to sit side +by side under one parent directory, and a local checkout reflects work that has not been pushed. When +it is absent, read the files from + on the `main` branch. + +The sibling repositories worth knowing about are the same ones the knowledge base lists: +[`cgp`](https://github.com/contextgeneric/cgp) is the library and the ground truth for any code claim, +[`cargo-cgp`](https://github.com/contextgeneric/cargo-cgp) is the error toolchain, +[`cgp-skills`](https://github.com/contextgeneric/cgp-skills) is the source of the agent skill this +site inlines under `docs/ai/`, and [`hypershell`](https://github.com/contextgeneric/hypershell) and +[`cgp-serde`](https://github.com/contextgeneric/cgp-serde) are the projects built with CGP. + +## Never link from a published page into the knowledge base + +The knowledge base is internal documentation written for AI agents. It records unfinished work, known +defects, and vocabulary that assumes a loaded agent skill, and it is not written for the public. A +link from a page here into it would expose material intended for a different audience and would be +useless to any reader who does not have that repository. + +A published page may link only to public resources: other pages on this site, the +[`cgp` repository](https://github.com/contextgeneric/cgp) and its siblings, +[docs.rs](https://docs.rs/cgp), [crates.io](https://crates.io/crates/cgp), the +[CGP Patterns book](https://patterns.contextgeneric.dev/), and ordinary external sources. + +This file is the exception, because it is not published — Docusaurus renders `docs/`, `blog/`, and +`src/pages/`, and a repository-root Markdown file is never part of the built site. So it may point at +internal material freely, and that is precisely its job. + +## Verify every code snippet against the current library + +Any Rust that appears on a page must compile against the current `cgp` release. Check it against the +[`cgp` source](https://github.com/contextgeneric/cgp) or its tests, and load the CGP agent skill +before writing CGP code, so that the snippet uses the idioms the library currently prefers rather than +ones that merely still parse. + +**Never copy current syntax out of an existing blog post on this site.** Almost every post predates +the current release, and the drift is not cosmetic — posts from as recently as 2026 show +`#[cgp_context]`, `cgp_preset!`, `#[cgp_inherit]`, `HasCgpProvider`, the `Async` trait, `ProvideType`, +`symbol!`, and inside-out `#[cgp_provider]` implementations, none of which are current. The knowledge +base's document for each post lists exactly what is stale in it, and its +[`releases/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/releases) section carries +a removal ledger that dates every renamed or deleted construct in one table. The safest source of +verified snippets is the knowledge base's +[`examples/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/examples) directory, +which exists partly to be quoted. + +## Consult the communication strategy before writing public prose + +Everything published here is public writing about CGP, and how CGP is presented is a settled matter +rather than an open one. The knowledge base's +[`communication-strategy/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/communication-strategy) +section fixes the audience model, the vocabulary, the framing of each claim, and the playbook for each +kind of artifact — the launch post, the tutorial, the landing page, the talk, the thread, the +comparison. Read the document that matches what you are writing before outlining it, not after +drafting it. + +The rule that governs all of it: **honesty is the strategy**. Never publish an invented benchmark, +adoption number, or quotation. Never disparage another crate, language, or community to make CGP look +better; naming where a simpler tool is the right choice is an asset, not a concession. And concede the +genuine costs — the learning curve, the verbose diagnostics, the young ecosystem — wherever a reader +would look for them, because this audience is unusually good at detecting what is being left out. + +## Do not rewrite published blog posts + +A blog post is dated. A release announcement records what a release did at the time, and editing its +snippets into current syntax would make it claim that an old version shipped features it did not. Leave +published posts as they stand, even when their code no longer compiles. + +When a post is genuinely misleading, the remedies are a short dated note at the top pointing to current +material, or a new post that supersedes it — both decisions for a human to make, not defaults to apply. +The one exception is a post that was published unfinished; the knowledge base's document for such a +post says so explicitly, and ordinary editing applies to it again. + +Pages under `docs/` are the opposite case. They describe CGP as it is now, carry no date, and should be +corrected in place with no changelog note and no record of what they used to say. + +## How the site is built + +This is a stock [Docusaurus](https://docusaurus.io/) installation, and keeping it stock is a deliberate +decision recorded in the [new-website post](https://contextgeneric.dev/blog/new-website): no plugins, +no React beyond the landing page, so that effort goes into Markdown rather than theming. An agent +adding site machinery is working against a stated policy and should raise it rather than assume it. + +Run `yarn start` for a live-reloading dev server and `yarn build` to produce the static output. +Deployment runs from the GitHub Actions workflows in `.github/`, publishing to GitHub Pages under the +domain fixed by `static/CNAME`. + +Three configuration details matter when editing. `onBrokenLinks` is set to `throw`, so a dangling +internal link fails the build — a change that renames or moves a page must fix every reference to it in +the same change. The docs sidebar is autogenerated from the directory tree, so a page's position comes +from its `sidebar_position` front matter and its directory's `_category_.json`, never from a +hand-maintained list. And the **announcement bar** in `docusaurus.config.ts` is hardcoded rather than +derived from the newest post, so it must be updated by hand with every release announcement. + +## Content conventions + +Blog posts live at `blog/-.md`, or in a directory with an `index.md` when the post +carries images. Front matter sets `authors: [soares]`, one or more tags from the fixed set in +`blog/tags.yml` (`release`, `deepdive`, `walkthrough`), and usually an explicit `slug`. A +`{/* truncate */}` marker must separate the excerpt from the body, or the build warns. Note that the +existing release slugs are inconsistent — dash-separated versions through v0.6.1, dotted from v0.7.0 — +so match a new post to its neighbours rather than assuming one rule. + +Docs pages set `sidebar_position` and are grouped by directory, with each directory's label and +position in its `_category_.json`. The `docs/ai/` tree is a **published copy** of the agent skill from +[`cgp-skills`](https://github.com/contextgeneric/cgp-skills); never fix the skill by editing the copy — +correct it upstream and re-inline the result, or the two versions diverge. + +The `notes/` directory is working material rather than site content: a local mirror of the +[Diátaxis](https://diataxis.fr/) documentation framework, and a research note comparing CGP's implicit +arguments to Scala's implicit parameters. Nothing in it is published, and the Diátaxis material is +third-party text kept for reference — read it for guidance on which of the four documentation kinds a +new page should be, but do not edit it and do not copy from it into a page. + +## Committing + +Make git commits **only when explicitly asked**, and treat each such request as authorizing exactly one +commit of the changes then in the working tree. Do not commit as a side effect of finishing a task, do +not bring commits up unprompted, and do not treat one request as turning on automatic committing. +Always commit on the current branch rather than creating or switching one. + +## Update the knowledge base in the same change + +A page added or substantially changed here needs its knowledge-base document added or revised in the +same change. That document is the only place a page's provenance is recorded — which internal material +it rests on, how current its code is, and what a future revision must preserve — so a page without one +has no recorded history, and a stale one actively misleads the next agent. When the knowledge-base +checkout is not present, say plainly what needs updating there so the work is not silently dropped. diff --git a/blog/2026-05-10-v0.7.1-release.md b/blog/2026-05-10-v0.8.0-release.md similarity index 98% rename from blog/2026-05-10-v0.7.1-release.md rename to blog/2026-05-10-v0.8.0-release.md index 5140da03..e0815687 100644 --- a/blog/2026-05-10-v0.7.1-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -1,11 +1,12 @@ --- +slug: 'v0.8.0-release' authors: [soares] tags: [release] --- -# CGP v0.7.1 - Grouping components with namespaces and paths +# CGP v0.8.0 - Grouping components with namespaces and paths -**CGP v0.7.1** has been released, and it comes with major ergonomic improvements to manage CGP components at scale. In this blog post, we will explore the problems with managing CGP components, and how the new namespace feature in CGP v0.7.1 helps solve the problem. +**CGP v0.8.0** has been released, and it comes with major ergonomic improvements to manage CGP components at scale. In this blog post, we will explore the problems with managing CGP components, and how the new namespace feature in CGP v0.8.0 helps solve the problem. {/* truncate */} @@ -377,7 +378,7 @@ Similarly, we can define a `PostgresPostComponents` to group all PostgreSQL-base ### The challenges of grouping delegate component keys -However, before the current v0.7.1 release, even though we have ways to group CGP component wirings, there lacked good developer experience for using these aggregated providers at the top-level component wiring. For example, the component wiring for `ProductionApp` can at best be simplified into: +However, before the current v0.8.0 release, even though we have ways to group CGP component wirings, there lacked good developer experience for using these aggregated providers at the top-level component wiring. For example, the component wiring for `ProductionApp` can at best be simplified into: ```rust delegate_components! { @@ -481,7 +482,7 @@ We have also experimented on a multiple-inheritance-like feature with CGP preset ## Introducing CGP namespaces and paths -Fortunately, with CGP v0.7.1, we have managed to solve the long-standing problem and devise a way to group component keys through a new feature called **namespaces**. +Fortunately, with CGP v0.8.0, we have managed to solve the long-standing problem and devise a way to group component keys through a new feature called **namespaces**. The way CGP namespaces work is as follows. For each CGP component definition, we can define a namespace prefix like follows: From a872bc19c7e436ad885c9b3b98be3f040fd6e93c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 1 Aug 2026 21:47:02 +0200 Subject: [PATCH 008/516] Add the AI disclaimer page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CGP uses AI at four levels that differ from each other, and the project had disclosed that only once, in the new-website post, which described the answer as uniform at a time when it was. It is not: the same project ships agent-written reference documentation, agent-revised blog drafts and tutorials, an agent-written toolchain and test suite, and a library the author designs and writes by hand. The page leads with the principle rather than the list, because four levels without one read as four excuses. Two questions decide how much an agent writes — whether the artifact becomes part of the reader's program, and whether it can be checked cheaply against something already true — and they point the same way, so the closer something sits to code a reader compiles, the more of it is hand-written. Four sections then run from most AI to least. Documentation is the longest, because it is the only level whose trustworthiness rests on a process rather than on a person: the knowledge base, the rule that source outranks every document, claims read out of code and tests and expansion snapshots rather than recalled, and the per-commit model trailers that make the whole arrangement checkable. Blog posts and tutorials invert the order, the author drafting and an agent revising. Tooling and tests are covered by one rule, that neither becomes part of a reader's program. The library section states that the design is entirely the author's, and separates that from macro implementation work he directs and shares. Two claims are worded to survive a reader checking them, since both otherwise flatten into something disprovable in a minute. The review claim says plainly that the seventy per-construct reference pages are not each read line by line, and why that is defensible, rather than implying uniform review. And the library section separates what CGP *is* from how a macro is implemented, because the `cgp` repository's Co-Authored-By trailers refute a blunter version. Each level ends on its own honest limit, a short Responsibility section carries the page's single sentence in the author's voice, and the page applies its own rule to itself with a provenance note at the foot. Record the link exception in AGENTS.md. This page links the knowledge base repository, which the never-link rule otherwise forbids, because the base is the subject it discloses and the argument cannot be made while hiding the record. The exception covers this page and the repository's front door only. Custom heading ids were removed after the build rejected them: this site's MDX setup parses `{#id}` as an expression. The seven section headings are therefore link targets whose anchors come from their text, and every page carrying a provenance note will link one of them. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01JW5brG8AAcXcorMm6NFUqv --- AGENTS.md | 9 +++ docs/ai/disclaimer.md | 146 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 docs/ai/disclaimer.md diff --git a/AGENTS.md b/AGENTS.md index 1c15d307..da96c72d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,6 +40,15 @@ A published page may link only to public resources: other pages on this site, th [docs.rs](https://docs.rs/cgp), [crates.io](https://crates.io/crates/cgp), the [CGP Patterns book](https://patterns.contextgeneric.dev/), and ordinary external sources. +**One published page is a sanctioned exception, and only one.** `docs/ai/disclaimer.md` links to the +knowledge base repository, because the base is the subject it discloses: the page's argument is that +CGP's documentation is written against a public record whose rules and history a reader can go and +check, and that argument cannot be made while hiding the record. Neither reason behind the rule applies +there — the link is a public GitHub URL that resolves for anyone, and exposing the material is the +point rather than an accident. The exception covers the repository's front door only, never a path into +a particular file, since a reader following a deep link lands in prose written for agents. Do not +"correct" that page's link, and do not extend the exception to any other page. + This file is the exception, because it is not published — Docusaurus renders `docs/`, `blog/`, and `src/pages/`, and a repository-root Markdown file is never part of the built site. So it may point at internal material freely, and that is precisely its job. diff --git a/docs/ai/disclaimer.md b/docs/ai/disclaimer.md new file mode 100644 index 00000000..667806f4 --- /dev/null +++ b/docs/ai/disclaimer.md @@ -0,0 +1,146 @@ +--- +sidebar_position: 2 +sidebar_label: AI Disclaimer +--- + +# How AI Is Used in the CGP Project + +CGP is built with substantial help from AI coding agents, and how much help varies a great deal from +one part of the project to another. This page says which parts, and why the line falls where it does, +so that you can decide for yourself how much weight to give each. + +The short version is that **the CGP library is designed and written by hand, while most of the +documentation around it is written by agents from a public knowledge base that is checked against the +library's source.** Everything else sits somewhere between those two, and the sections below take each +part in turn, starting where AI does the most. + +## Why the levels differ + +Two questions decide how much of any given artifact an agent writes, and they point the same way. + +**Does it become part of your program?** Code you add as a dependency and compile into your own project +is code you inherit, and you cannot easily audit it at the moment you need it to be right. Code that +merely runs *on* your project — a command-line tool, a test suite — is judged on its results, and you +can stop using it without touching anything you wrote. + +**Can it be checked against something that is already true?** A sentence about what a macro generates +can be checked against the macro. A test can be checked by running it. A *design* cannot be checked +against anything, because it is the thing everything else is checked against. + +So the closer something sits to the code you compile, the more of it is written by hand; and the more +cheaply it can be verified against a ground truth, the more of it an agent writes. + +## Documentation and reference pages + +Most of the written material about CGP — the construct reference, the explanations, the guides, and the +error catalog — is written by AI agents rather than by hand. + +What makes that workable is not the agents but the arrangement around them, and that arrangement is +public, so it can be inspected rather than taken on trust. All of this material is developed first in +the [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base), a separate repository +that holds the project's documentation along with the rules an agent must follow to write it. The +website pages are then derived from what is recorded there. + +**The knowledge base answers to the source code.** Its governing rule is that the source in each +repository is the single source of truth, ranking above any document and above the agent skill built +from it. So a claim about what a macro expands to, which identifier it generates, or which syntax it +accepts is not written from an agent's recollection — it is read out of the code, out of the test +suite, or out of the expansion snapshots that pin what each macro emits. When several descriptions of +one behavior disagree, the disagreement is treated as a defect and the code wins. + +Two further rules keep it from drifting. Documentation changes in the same change as the behavior it +describes, rather than in a follow-up, on the principle that a document describing behavior the library +no longer has is worse than no document at all, because the next reader will trust it. And each +document describes only how things work now, so a page is corrected in place rather than accumulating +notes about what used to be true. + +**The history is public too, and it is specific.** Every commit to the knowledge base records which +model contributed to it in a `Co-Authored-By` trailer. If you want to know how a particular sentence +about `#[cgp_component]` came to exist, you can read the rule that produced it and the commit that +landed it. That is a stronger claim than any assurance this page could make, which is why the knowledge +base is public in the first place. + +**What the human author does is set the rules and read what matters.** He decides what gets written and +in what order, sets the conventions the agents work under, reads in full the pages that carry the +project's argument — the front page, the explanation pages, the reference index, this page, and every +blog post — and is answerable for all of it. + +**The honest limit:** that review is not uniform, and it would be easy to imply otherwise. The roughly +seventy per-construct reference pages are not each read line by line. They are a mechanical port of +documents already written and verified against the source, into a fixed template, so the risk they +carry is a wrong expansion rather than a wrong argument — and a wrong expansion is caught by checking +the source, which is what the knowledge base's rules exist to enforce. Review where judgement matters, +verification against the source everywhere: that is the actual arrangement, and it is worth knowing +precisely rather than approximately. + +## Blog posts and tutorials + +These work the other way round. **The author writes the draft; an agent revises it against the +knowledge base.** The argument, the judgement about what is worth saying, the concessions, and the +voice all originate with him, and the agent's job is to improve the prose and to check the code and +claims against what the knowledge base records. + +The ordering is the whole difference, and it is worth stating because "AI-assisted" otherwise covers +both this and the section above. A blog post is the author's argument, improved; a reference page is an +agent's writing, governed. Those are not the same thing. + +**The honest limit:** a revised draft is still the author's claim, and revision does not make a wrong +argument right. Note also that this describes how posts and tutorials are written now — the site's +older text was refined with LLM assistance more broadly, as +[the post about this website](/blog/2026/02/21/new-website) describes. + +## Tooling and tests + +[`cargo-cgp`](https://github.com/contextgeneric/cargo-cgp), the toolchain that makes CGP's compiler +errors readable, is mostly written by agents, and CGP's test suite is largely maintained by them. + +One rule gates both: **neither becomes part of your program.** A cargo subcommand runs *on* a project +and is never a dependency of it, so you are exposed to its behavior rather than to its source — and its +behavior is pinned by a snapshot test suite that either matches or does not. A test is the same case in +a sharper form, because a test is self-verifying against the real library: a wrong test fails loudly +rather than misleading quietly. + +The test suite also has a positive reason rather than merely a permissive one. Exhaustively exercising +every syntax form a procedural macro accepts is large, mechanical, high-value work that one person +writing in their own time will never finish, and the library is better tested for having an agent do +it. + +**The honest limit:** `cargo-cgp` is an early pre-release, and a bug in a tool is still a bug. It +reshapes the error classes it recognizes and passes the rest through as the compiler wrote them. + +## The CGP library + +**The design of every CGP construct and interface is the author's, and the library is written almost +entirely by hand.** This is the code you import and compile, and it is where the ground truth runs out: +there is nothing to check a design against, because the design is what everything else is checked +against. + +AI is used here too, and it would be misleading to imply otherwise. It is used to verify correctness, +to review code quality, and to work through the implementation of the procedural macros. The +[`cgp` repository's](https://github.com/contextgeneric/cgp) commit history records this in the same +`Co-Authored-By` trailers the knowledge base uses, and some of those commits touch the macros — so the +distinction that matters is not whether an agent has ever contributed a line, but which decisions are +whose. + +That distinction is this: **what CGP *is*** — every construct, every interface, and every decision +about how the pieces fit together — **is the author's work**, while **how a given macro is +implemented** is work he directs, reviews, and frequently shares. The first is what you are adopting +when you adopt CGP. The second is an implementation detail, held to the same standard as any other code +in the library. + +## Responsibility + +None of the above transfers responsibility. Everything published under CGP's name is the project's, and +an error in it is the project's error rather than an agent's — and as CGP's author, I would rather you +told me about one than worked around it. + +## How pages are marked + +Pages written with AI assistance carry a short note at the foot, linking back to the section here that +describes how they were made. That note goes on pages written from now on. Older pages do not carry one +and have not been retrofitted with one, because attaching a provenance note to a page without first +establishing what is actually true of it would be a guess rather than a disclosure. + +--- + +*This page was written by an AI agent from the [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base) and reviewed by the author — see [Documentation and reference pages](#documentation-and-reference-pages).* From 20e5cec0328ed58e14abe642534d95aa13f8ed7e Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 1 Aug 2026 22:14:00 +0200 Subject: [PATCH 009/516] Scaffold the construct reference, and write its first three pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds docs/reference/, the site's canonical per-construct reference: a hand-written index, seventy-five construct pages grouped into the seven subdirectories that mirror what a construct is, and a page for the compile errors CGP produces after expansion. Every page is scaffolded with its one-line description and a notice saying it is unwritten, and the index links all of them. The completeness obligation is against the index rather than the prose, so no construct is missing from the site while the port proceeds, and no page written later has to be retrofitted into the grouping. Four consolidations take eighty-five internal documents to seventy-five pages, and because a reader who arrives knowing a consolidated name would otherwise fail to find it, the index ends with a table mapping every absorbed name — `#[cgp_new_provider]`, `CgpVariant`, `UseFieldRef`, `Void`, and the rest — to the page that owns it. Three pages are written in full: `#[cgp_component]`, `#[cgp_impl]`, and `delegate_components!`. They follow the six-section layered descent, so a reader who has finished one tutorial gets what they need from the first two sections and an advanced reader continues into the expansion, with the formal grammar in a collapsed block so nobody meets EBNF by accident. Their When to reach for it sections are where the internal guides on writing providers and sizing a component reach the public site, since those have no public home of their own. Two verification steps rather than one. Every snippet was compiled against cgp 0.8.0-alpha with a check_components! assertion per wired context, which is what confirms the wiring resolves rather than merely parses — covering the shared example, the higher-order provider, the `#[cgp_impl(Self)]` form, `#[use_type]` on a component, the generic table, `open`, and the aggregate provider. And every expansion was checked with `cargo cgp expand` rather than copied from the internal document, which is the draft check most easily skipped and the section most likely to be wrong without it. Concept links are summarised inline rather than linked, because the explanation tier does not exist yet and a dangling link is worse than a sentence. They become links when those pages land. Sidebar labels carry no backticks: a sidebar_label is plain text rather than Markdown, so `#[cgp_impl]` would render its backticks visibly in the navigation. The backticks stay in each page's heading, where they render. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01JW5brG8AAcXcorMm6NFUqv --- docs/reference/_category_.json | 8 + docs/reference/attributes/_category_.json | 8 + docs/reference/attributes/derive_delegate.md | 15 + docs/reference/attributes/extend.md | 15 + docs/reference/attributes/extend_where.md | 15 + docs/reference/attributes/implicit.md | 15 + docs/reference/attributes/use_provider.md | 15 + docs/reference/attributes/use_type.md | 15 + docs/reference/attributes/uses.md | 15 + docs/reference/components/_category_.json | 8 + docs/reference/components/can_raise_error.md | 15 + docs/reference/components/computer.md | 15 + docs/reference/components/handler.md | 15 + docs/reference/components/has_error_type.md | 15 + docs/reference/components/has_runtime.md | 15 + docs/reference/components/has_type.md | 15 + docs/reference/components/producer.md | 15 + docs/reference/components/runner.md | 15 + docs/reference/components/try_computer.md | 15 + docs/reference/derives/_category_.json | 8 + docs/reference/derives/derive_build_field.md | 15 + docs/reference/derives/derive_cgp_data.md | 15 + .../reference/derives/derive_extract_field.md | 15 + docs/reference/derives/derive_from_variant.md | 15 + docs/reference/derives/derive_has_field.md | 15 + docs/reference/derives/derive_has_fields.md | 15 + docs/reference/errors.md | 14 + docs/reference/index.md | 198 +++++++++ docs/reference/macros/_category_.json | 8 + docs/reference/macros/async_trait.md | 15 + docs/reference/macros/blanket_trait.md | 15 + docs/reference/macros/cgp_auto_dispatch.md | 15 + docs/reference/macros/cgp_auto_getter.md | 15 + docs/reference/macros/cgp_component.md | 346 ++++++++++++++++ docs/reference/macros/cgp_computer.md | 15 + docs/reference/macros/cgp_fn.md | 15 + docs/reference/macros/cgp_getter.md | 15 + docs/reference/macros/cgp_impl.md | 330 +++++++++++++++ docs/reference/macros/cgp_namespace.md | 15 + docs/reference/macros/cgp_producer.md | 15 + docs/reference/macros/cgp_provider.md | 15 + docs/reference/macros/cgp_type.md | 15 + docs/reference/macros/check_components.md | 15 + .../macros/delegate_and_check_components.md | 15 + docs/reference/macros/delegate_components.md | 376 ++++++++++++++++++ docs/reference/macros/path.md | 15 + docs/reference/macros/product.md | 15 + docs/reference/macros/sum.md | 15 + docs/reference/macros/symbol.md | 15 + docs/reference/providers/_category_.json | 8 + docs/reference/providers/chain_getters.md | 15 + .../providers/dispatch_combinators.md | 15 + docs/reference/providers/error_providers.md | 15 + .../providers/handler_combinators.md | 15 + docs/reference/providers/monad_providers.md | 15 + docs/reference/providers/redirect_lookup.md | 15 + docs/reference/providers/use_context.md | 15 + docs/reference/providers/use_default.md | 15 + docs/reference/providers/use_delegate.md | 15 + .../reference/providers/use_delegated_type.md | 15 + docs/reference/providers/use_field.md | 15 + docs/reference/providers/use_type.md | 15 + docs/reference/providers/with_provider.md | 15 + docs/reference/traits/_category_.json | 8 + docs/reference/traits/can_use_component.md | 15 + docs/reference/traits/cast.md | 15 + docs/reference/traits/default_namespace.md | 15 + docs/reference/traits/delegate_component.md | 15 + docs/reference/traits/extract_field.md | 15 + docs/reference/traits/from_variant.md | 15 + docs/reference/traits/has_builder.md | 15 + docs/reference/traits/has_field.md | 15 + docs/reference/traits/has_fields.md | 15 + docs/reference/traits/is_provider_for.md | 15 + docs/reference/traits/map_type.md | 15 + docs/reference/traits/monad.md | 15 + docs/reference/traits/optional_fields.md | 15 + docs/reference/traits/product_ops.md | 15 + docs/reference/traits/static_format.md | 15 + docs/reference/types/_category_.json | 8 + docs/reference/types/field.md | 15 + docs/reference/types/index.md | 15 + docs/reference/types/life.md | 15 + docs/reference/types/mref.md | 15 + docs/reference/types/type_level_spines.md | 15 + 85 files changed, 2408 insertions(+) create mode 100644 docs/reference/_category_.json create mode 100644 docs/reference/attributes/_category_.json create mode 100644 docs/reference/attributes/derive_delegate.md create mode 100644 docs/reference/attributes/extend.md create mode 100644 docs/reference/attributes/extend_where.md create mode 100644 docs/reference/attributes/implicit.md create mode 100644 docs/reference/attributes/use_provider.md create mode 100644 docs/reference/attributes/use_type.md create mode 100644 docs/reference/attributes/uses.md create mode 100644 docs/reference/components/_category_.json create mode 100644 docs/reference/components/can_raise_error.md create mode 100644 docs/reference/components/computer.md create mode 100644 docs/reference/components/handler.md create mode 100644 docs/reference/components/has_error_type.md create mode 100644 docs/reference/components/has_runtime.md create mode 100644 docs/reference/components/has_type.md create mode 100644 docs/reference/components/producer.md create mode 100644 docs/reference/components/runner.md create mode 100644 docs/reference/components/try_computer.md create mode 100644 docs/reference/derives/_category_.json create mode 100644 docs/reference/derives/derive_build_field.md create mode 100644 docs/reference/derives/derive_cgp_data.md create mode 100644 docs/reference/derives/derive_extract_field.md create mode 100644 docs/reference/derives/derive_from_variant.md create mode 100644 docs/reference/derives/derive_has_field.md create mode 100644 docs/reference/derives/derive_has_fields.md create mode 100644 docs/reference/errors.md create mode 100644 docs/reference/index.md create mode 100644 docs/reference/macros/_category_.json create mode 100644 docs/reference/macros/async_trait.md create mode 100644 docs/reference/macros/blanket_trait.md create mode 100644 docs/reference/macros/cgp_auto_dispatch.md create mode 100644 docs/reference/macros/cgp_auto_getter.md create mode 100644 docs/reference/macros/cgp_component.md create mode 100644 docs/reference/macros/cgp_computer.md create mode 100644 docs/reference/macros/cgp_fn.md create mode 100644 docs/reference/macros/cgp_getter.md create mode 100644 docs/reference/macros/cgp_impl.md create mode 100644 docs/reference/macros/cgp_namespace.md create mode 100644 docs/reference/macros/cgp_producer.md create mode 100644 docs/reference/macros/cgp_provider.md create mode 100644 docs/reference/macros/cgp_type.md create mode 100644 docs/reference/macros/check_components.md create mode 100644 docs/reference/macros/delegate_and_check_components.md create mode 100644 docs/reference/macros/delegate_components.md create mode 100644 docs/reference/macros/path.md create mode 100644 docs/reference/macros/product.md create mode 100644 docs/reference/macros/sum.md create mode 100644 docs/reference/macros/symbol.md create mode 100644 docs/reference/providers/_category_.json create mode 100644 docs/reference/providers/chain_getters.md create mode 100644 docs/reference/providers/dispatch_combinators.md create mode 100644 docs/reference/providers/error_providers.md create mode 100644 docs/reference/providers/handler_combinators.md create mode 100644 docs/reference/providers/monad_providers.md create mode 100644 docs/reference/providers/redirect_lookup.md create mode 100644 docs/reference/providers/use_context.md create mode 100644 docs/reference/providers/use_default.md create mode 100644 docs/reference/providers/use_delegate.md create mode 100644 docs/reference/providers/use_delegated_type.md create mode 100644 docs/reference/providers/use_field.md create mode 100644 docs/reference/providers/use_type.md create mode 100644 docs/reference/providers/with_provider.md create mode 100644 docs/reference/traits/_category_.json create mode 100644 docs/reference/traits/can_use_component.md create mode 100644 docs/reference/traits/cast.md create mode 100644 docs/reference/traits/default_namespace.md create mode 100644 docs/reference/traits/delegate_component.md create mode 100644 docs/reference/traits/extract_field.md create mode 100644 docs/reference/traits/from_variant.md create mode 100644 docs/reference/traits/has_builder.md create mode 100644 docs/reference/traits/has_field.md create mode 100644 docs/reference/traits/has_fields.md create mode 100644 docs/reference/traits/is_provider_for.md create mode 100644 docs/reference/traits/map_type.md create mode 100644 docs/reference/traits/monad.md create mode 100644 docs/reference/traits/optional_fields.md create mode 100644 docs/reference/traits/product_ops.md create mode 100644 docs/reference/traits/static_format.md create mode 100644 docs/reference/types/_category_.json create mode 100644 docs/reference/types/field.md create mode 100644 docs/reference/types/index.md create mode 100644 docs/reference/types/life.md create mode 100644 docs/reference/types/mref.md create mode 100644 docs/reference/types/type_level_spines.md diff --git a/docs/reference/_category_.json b/docs/reference/_category_.json new file mode 100644 index 00000000..ddf34ddc --- /dev/null +++ b/docs/reference/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Reference", + "position": 5, + "link": { + "type": "doc", + "id": "reference/index" + } +} diff --git a/docs/reference/attributes/_category_.json b/docs/reference/attributes/_category_.json new file mode 100644 index 00000000..fc17a26e --- /dev/null +++ b/docs/reference/attributes/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Attributes", + "position": 2, + "link": { + "type": "generated-index", + "description": "The modifier attributes that refine what a definition macro generates. They are options consumed by a host macro rather than macros in their own right." + } +} diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md new file mode 100644 index 00000000..471f6793 --- /dev/null +++ b/docs/reference/attributes/derive_delegate.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[derive_delegate]' +--- + +# `#[derive_delegate]` + +Generate the `UseDelegate` dispatcher impl for a component. Superseded by the `open` statement. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md new file mode 100644 index 00000000..76409d23 --- /dev/null +++ b/docs/reference/attributes/extend.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[extend]' +--- + +# `#[extend]` + +Add supertrait bounds to a generated trait. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md new file mode 100644 index 00000000..08cb341a --- /dev/null +++ b/docs/reference/attributes/extend_where.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[extend_where]' +--- + +# `#[extend_where]` + +Add `where` predicates to a generated trait's own definition. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md new file mode 100644 index 00000000..e825bfbf --- /dev/null +++ b/docs/reference/attributes/implicit.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[implicit]' +--- + +# `#[implicit]` + +Source a function argument from a same-named field on the context. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md new file mode 100644 index 00000000..3e7427cc --- /dev/null +++ b/docs/reference/attributes/use_provider.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[use_provider]' +--- + +# `#[use_provider]` + +Complete an inner provider's bound in a higher-order provider. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md new file mode 100644 index 00000000..7ddd4701 --- /dev/null +++ b/docs/reference/attributes/use_type.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[use_type]' +--- + +# `#[use_type]` + +Import an abstract associated type and write it as a bare name. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md new file mode 100644 index 00000000..961cda61 --- /dev/null +++ b/docs/reference/attributes/uses.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[uses]' +--- + +# `#[uses]` + +Import the capabilities a provider depends on, reading like a `use` statement. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/_category_.json b/docs/reference/components/_category_.json new file mode 100644 index 00000000..58b1ac25 --- /dev/null +++ b/docs/reference/components/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Built-in components", + "position": 4, + "link": { + "type": "generated-index", + "description": "The components CGP ships with \u2014 each a consumer trait, a provider trait, and a wiring key \u2014 that your application wires like any component it defines itself." + } +} diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md new file mode 100644 index 00000000..7a3d4cdf --- /dev/null +++ b/docs/reference/components/can_raise_error.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'CanRaiseError & CanWrapError' +--- + +# `CanRaiseError` & `CanWrapError` + +Raise a source error into the context's error type, and attach detail to it. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/computer.md b/docs/reference/components/computer.md new file mode 100644 index 00000000..39040065 --- /dev/null +++ b/docs/reference/components/computer.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Computer & CanCompute' +--- + +# `Computer` & `CanCompute` + +The synchronous, infallible transform, with its by-reference and async variants. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/handler.md b/docs/reference/components/handler.md new file mode 100644 index 00000000..65bf1f04 --- /dev/null +++ b/docs/reference/components/handler.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Handler & CanHandle' +--- + +# `Handler` & `CanHandle` + +The general async, fallible, error-aware computation component. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md new file mode 100644 index 00000000..b362128c --- /dev/null +++ b/docs/reference/components/has_error_type.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'HasErrorType' +--- + +# `HasErrorType` + +The abstract error type every fallible CGP capability names. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md new file mode 100644 index 00000000..c60fe30e --- /dev/null +++ b/docs/reference/components/has_runtime.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'HasRuntime & HasRuntimeType' +--- + +# `HasRuntime` & `HasRuntimeType` + +The abstract runtime type and the accessor that reaches it. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md new file mode 100644 index 00000000..88142c95 --- /dev/null +++ b/docs/reference/components/has_type.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'HasType & TypeProvider' +--- + +# `HasType` & `TypeProvider` + +CGP's built-in abstract-type component. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/producer.md b/docs/reference/components/producer.md new file mode 100644 index 00000000..b977b20e --- /dev/null +++ b/docs/reference/components/producer.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Producer & CanProduce' +--- + +# `Producer` & `CanProduce` + +The input-free production component. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md new file mode 100644 index 00000000..f4875489 --- /dev/null +++ b/docs/reference/components/runner.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'CanRun & CanSendRun' +--- + +# `CanRun` & `CanSendRun` + +The task-running components. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/components/try_computer.md b/docs/reference/components/try_computer.md new file mode 100644 index 00000000..20fc90cc --- /dev/null +++ b/docs/reference/components/try_computer.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'TryComputer & CanTryCompute' +--- + +# `TryComputer` & `CanTryCompute` + +The fallible computer. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/derives/_category_.json b/docs/reference/derives/_category_.json new file mode 100644 index 00000000..8d8545d2 --- /dev/null +++ b/docs/reference/derives/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Derives", + "position": 3, + "link": { + "type": "generated-index", + "description": "The `#[derive(...)]` macros that generate field access and the extensible-data machinery for your structs and enums." + } +} diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md new file mode 100644 index 00000000..18b2b79f --- /dev/null +++ b/docs/reference/derives/derive_build_field.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[derive(BuildField)]' +--- + +# `#[derive(BuildField)]` + +Builder support for a record. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md new file mode 100644 index 00000000..307a3dbf --- /dev/null +++ b/docs/reference/derives/derive_cgp_data.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[derive(CgpData)], CgpRecord & CgpVariant' +--- + +# `#[derive(CgpData)]`, `CgpRecord` & `CgpVariant` + +The extensible-data derives: the umbrella and its struct and enum faces. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md new file mode 100644 index 00000000..a36c1882 --- /dev/null +++ b/docs/reference/derives/derive_extract_field.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[derive(ExtractField)]' +--- + +# `#[derive(ExtractField)]` + +Extractor support for a variant. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md new file mode 100644 index 00000000..6124b3e5 --- /dev/null +++ b/docs/reference/derives/derive_from_variant.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[derive(FromVariant)]' +--- + +# `#[derive(FromVariant)]` + +Generic construction of an enum from one of its named variants. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md new file mode 100644 index 00000000..df0cc58e --- /dev/null +++ b/docs/reference/derives/derive_has_field.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[derive(HasField)]' +--- + +# `#[derive(HasField)]` + +Per-field accessors keyed by a type-level tag. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md new file mode 100644 index 00000000..50416de6 --- /dev/null +++ b/docs/reference/derives/derive_has_fields.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[derive(HasFields)]' +--- + +# `#[derive(HasFields)]` + +The whole-struct or whole-enum field-list view. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/errors.md b/docs/reference/errors.md new file mode 100644 index 00000000..bd274782 --- /dev/null +++ b/docs/reference/errors.md @@ -0,0 +1,14 @@ +--- +sidebar_label: 'Compile errors' +sidebar_position: 90 +--- + +# Compile errors + +The errors CGP produces after macro expansion, grouped by what went wrong: a dependency a provider needs and the context does not supply, a wiring table that does not resolve, and a shorthand that lowered into something the compiler rejects. + +:::info Not written yet + +This page is still being written. In the meantime, run [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) in place of `cargo check`: it un-hides the root cause the default trait solver suppresses and leads with it, for the error classes it recognizes. + +::: diff --git a/docs/reference/index.md b/docs/reference/index.md new file mode 100644 index 00000000..7afc51fc --- /dev/null +++ b/docs/reference/index.md @@ -0,0 +1,198 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Reference + +This is the complete reference for every CGP construct: what each one is for, when to reach for it, +how to write it, and what it generates. It is the place to look when you already know the name of the +thing you need. + +If you are still learning CGP, the [tutorials](/docs/tutorials/hello) are the better starting point. +This section assumes you know what a component and a provider are, and it explains constructs one at a +time rather than building an idea up. + +## Start with these six + +Most CGP code uses a small number of constructs over and over. If you read nothing else here, read +these. + +| Construct | What it does | +|---|---| +| [`#[cgp_component]`](./macros/cgp_component.md) | Turns a trait into a component that can have many implementations | +| [`#[cgp_impl]`](./macros/cgp_impl.md) | Writes one of those implementations | +| [`delegate_components!`](./macros/delegate_components.md) | Chooses which implementation a given type uses | +| [`check_components!`](./macros/check_components.md) | Verifies that choice at compile time | +| [`#[cgp_fn]`](./macros/cgp_fn.md) | Defines a capability that only ever needs one implementation | +| [`#[implicit]`](./attributes/implicit.md) | Reads a value out of the context as if it were a function argument | + +The first four are the full component cycle: define, implement, wire, verify. The last two are how +most code avoids needing that cycle at all — reach for them first, and climb to a full component when +a capability genuinely needs a second implementation. + +## By what you are trying to do + +The rest of the reference is grouped by the job a construct does rather than by what kind of thing it +is. If you know which *file* you want rather than which job, the sidebar groups the same pages by kind +— macros, attributes, derives, and so on. + +### Define a capability, and implement it + +[`#[cgp_component]`](./macros/cgp_component.md) is the foundational macro, turning one trait into the +consumer trait callers use and the provider trait implementations target. A provider is then written +with [`#[cgp_impl]`](./macros/cgp_impl.md), which keeps `self` and the consumer method signatures; +[`#[cgp_provider]`](./macros/cgp_provider.md) is the lower-level form underneath it, which you will +read in generated code more often than you write. When a capability needs only one implementation and +no wiring at all, [`#[cgp_fn]`](./macros/cgp_fn.md) builds it straight from a function, and +[`#[blanket_trait]`](./macros/blanket_trait.md) does the same from a trait with default methods. +[`#[async_trait]`](./macros/async_trait.md) is how a CGP trait declares an `async fn`. + +### Wire a type to the implementations it uses + +[`delegate_components!`](./macros/delegate_components.md) builds the table that maps each component to +its provider, and [`check_components!`](./macros/check_components.md) asserts that the table is +complete and every dependency behind it is satisfied. +[`delegate_and_check_components!`](./macros/delegate_and_check_components.md) does both at once, which +suits simple wiring and getting started. Two providers appear in tables constantly: +[`UseContext`](./providers/use_context.md), which routes back through the context's own +implementation, and [`UseDefault`](./providers/use_default.md), which selects a component's default +method bodies. Underneath it all is [`DelegateComponent`](./traits/delegate_component.md), the trait +the table is made of. + +### Read values out of the context + +An [`#[implicit]`](./attributes/implicit.md) argument is the default way to read a field: it looks like +an ordinary function parameter and is filled from a same-named field on the context. The field access +itself comes from [`#[derive(HasField)]`](./derives/derive_has_field.md) and the +[`HasField`](./traits/has_field.md) trait. + +Getter traits are the sparing alternative, for the cases an implicit argument cannot reach. +[`#[cgp_auto_getter]`](./macros/cgp_auto_getter.md) generates one from the method name; +[`#[cgp_getter]`](./macros/cgp_getter.md) makes the getter a full component so the field it reads is +chosen by wiring, through [`UseField` and its siblings](./providers/use_field.md). +[`ChainGetters`](./providers/chain_getters.md) reaches a field on a nested context, and +[`MRef`](./types/mref.md) is the return type of a getter that may lend or produce its value. + +### Declare what an implementation needs + +These attributes state a provider's dependencies where the implementation lives, so they never appear +in the interface callers see. [`#[uses]`](./attributes/uses.md) imports the capabilities it depends on, +[`#[use_provider]`](./attributes/use_provider.md) does the same for an inner provider in a +higher-order provider, and [`#[extend]`](./attributes/extend.md) and +[`#[extend_where]`](./attributes/extend_where.md) add bounds to a generated trait rather than to its +implementation. + +### Let each context choose a type + +[`#[cgp_type]`](./macros/cgp_type.md) defines an abstract-type component — an error type, a runtime, a +scalar — that each context fills in by wiring the component to +[`UseType`](./providers/use_type.md), or to +[`UseDelegatedType`](./providers/use_delegated_type.md) to resolve it through a table. Generic code +names such a type by importing it with [`#[use_type]`](./attributes/use_type.md), which is a different +thing from the `UseType` provider despite the shared name. All of it rests on +[`HasType`](./components/has_type.md), CGP's built-in abstract-type component, and +[`WithProvider`](./providers/with_provider.md) is the adapter that lets a foundational provider stand +in as a named component's. + +### Handle errors + +[`HasErrorType`](./components/has_error_type.md) gives a context one shared error type, and +[`CanRaiseError` and `CanWrapError`](./components/can_raise_error.md) construct it from a source error +and attach detail. The interchangeable strategies that satisfy them — `RaiseFrom`, `ReturnError`, +`DebugError`, and the rest — are the [error providers](./providers/error_providers.md). + +### Compute things + +The handler family models computation along three axes: synchronous or async, fallible or not, taking +an input or not. [`Computer`](./components/computer.md) is the plain synchronous transform, +[`TryComputer`](./components/try_computer.md) adds fallibility, +[`Handler`](./components/handler.md) is the general async and fallible case, and +[`Producer`](./components/producer.md) is the input-free one. +[`CanRun`](./components/runner.md) runs tasks and [`HasRuntime`](./components/has_runtime.md) supplies +the runtime they run on. + +Providers in this family are written from plain functions with +[`#[cgp_computer]`](./macros/cgp_computer.md) and [`#[cgp_producer]`](./macros/cgp_producer.md), and +composed with the [handler combinators](./providers/handler_combinators.md), the +[dispatch combinators](./providers/dispatch_combinators.md), and the +[monad providers](./providers/monad_providers.md) built on the +[monad traits](./traits/monad.md). [`#[cgp_auto_dispatch]`](./macros/cgp_auto_dispatch.md) generates a +dispatching handler from a per-type trait. + +### Work with a type's structure + +These let generic code build and read structs and enums by their fields and variants without naming +the concrete type. [`#[derive(CgpData)]`](./derives/derive_cgp_data.md) is the umbrella derive, and its +individual slices are [`HasFields`](./derives/derive_has_fields.md), +[`BuildField`](./derives/derive_build_field.md), +[`ExtractField`](./derives/derive_extract_field.md), and +[`FromVariant`](./derives/derive_from_variant.md). + +The traits behind them are [`HasFields`](./traits/has_fields.md), the builder family in +[`HasBuilder`](./traits/has_builder.md), the extractor family in +[`ExtractField`](./traits/extract_field.md), [`FromVariant`](./traits/from_variant.md), the presence +markers of [`MapType`](./traits/map_type.md), the list algebra of +[`AppendProduct`](./traits/product_ops.md), the structural +[casts](./traits/cast.md), and the [optional-field extensions](./traits/optional_fields.md). Each entry +in a shape is a [`Field`](./types/field.md). + +### Keep large wiring manageable + +[`cgp_namespace!`](./macros/cgp_namespace.md) defines a reusable, inheritable wiring table that many +contexts can join, which is how top-level wiring stays short as component counts grow. It works +through [`RedirectLookup`](./providers/redirect_lookup.md), which re-routes a lookup along a +[`Path!`](./macros/path.md), together with the +[`DefaultNamespace`](./traits/default_namespace.md) traits that resolve inherited and per-type +defaults. The `open` statement of [`delegate_components!`](./macros/delegate_components.md) is a +lightweight special case of the same mechanism, and it supersedes the older +[`UseDelegate`](./providers/use_delegate.md) tables and the +[`#[derive_delegate]`](./attributes/derive_delegate.md) attribute that generates them. + +### Understand a generated type or an error + +These are the type-level building blocks the rest of CGP is made of. You mostly write them through +sugar — [`Symbol!`](./macros/symbol.md) for a field name, [`Product!`](./macros/product.md) for a list, +[`Sum!`](./macros/sum.md) for its dual, [`Path!`](./macros/path.md) for a route — and only need to +recognize [what they expand into](./types/type_level_spines.md) when it appears in an error message. +[`Index`](./types/index.md) tags a tuple field and [`Life`](./types/life.md) lifts a lifetime into a +type, while [`StaticFormat`](./traits/static_format.md) turns type-level strings back into runtime +data. + +When wiring fails, three traits are what you will see named: +[`DelegateComponent`](./traits/delegate_component.md), +[`IsProviderFor`](./traits/is_provider_for.md), which is what makes a missing dependency show up by +name, and [`CanUseComponent`](./traits/can_use_component.md), which is what a check asserts. The +[compile errors](./errors.md) page covers the recurring failures and how to read them. + +## Looking for a name you don't see? + +A few constructs are documented alongside a close relative rather than on a page of their own, because +they are chosen together and separate pages would make you collate them. If you arrived knowing one of +these names, this is where it lives. + +| Looking for | It's on | +|---|---| +| `#[cgp_new_provider]` | [`#[cgp_provider]`](./macros/cgp_provider.md) | +| `#[derive(CgpRecord)]`, `#[derive(CgpVariant)]` | [`#[derive(CgpData)]`](./derives/derive_cgp_data.md) | +| `UseFieldRef`, `UseFields` | [`UseField`](./providers/use_field.md) | +| `WithType`, `WithField`, `WithContext` | [`WithProvider`](./providers/with_provider.md) | +| `Cons`, `Nil`, `Either`, `Void`, `Chars`, `PathCons` | [Type-level spines](./types/type_level_spines.md) | +| `HasFieldMut`, `FieldGetter` | [`HasField`](./traits/has_field.md) | +| `ConcatProduct`, `MapFields` | [`AppendProduct`](./traits/product_ops.md) | +| `CanDowncast`, `CanBuildFrom` | [`CanUpcast`](./traits/cast.md) | +| `StaticString`, `ConcatPath` | [`StaticFormat`](./traits/static_format.md) | +| `ComposeHandlers`, `PipeHandlers`, `ReturnInput`, `Promote*` | [Handler combinators](./providers/handler_combinators.md) | +| `MatchWithHandlers`, `ExtractFieldAndHandle` | [Dispatch combinators](./providers/dispatch_combinators.md) | +| `PipeMonadic`, `BindOk`, `BindErr` | [Monad providers](./providers/monad_providers.md) | +| `RaiseFrom`, `ReturnError`, `DebugError`, `DisplayError` | [Error providers](./providers/error_providers.md) | +| `#[impl_generics(...)]` | [`#[cgp_fn]`](./macros/cgp_fn.md) | +| `#[prefix(...)]` | [`cgp_namespace!`](./macros/cgp_namespace.md) | +| `#[default_impl(...)]` | [`DefaultNamespace`](./traits/default_namespace.md) | +| `#[check_providers(...)]`, `#[check_params(...)]` | [`check_components!`](./macros/check_components.md) | + +## This reference is still being written + +Most pages here are placeholders at present, and each one says so. The construct list is complete — +every construct the `cgp` crate exports has a page, or a named place on a page it shares — so nothing +is missing from this index even where the page behind it is not yet filled in. diff --git a/docs/reference/macros/_category_.json b/docs/reference/macros/_category_.json new file mode 100644 index 00000000..fab498e8 --- /dev/null +++ b/docs/reference/macros/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Macros", + "position": 1, + "link": { + "type": "generated-index", + "description": "The procedural macros you invoke directly: the ones that define components and providers, the ones that wire and check them, and the ones that build type-level values." + } +} diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md new file mode 100644 index 00000000..b3a7a26a --- /dev/null +++ b/docs/reference/macros/async_trait.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[async_trait]' +--- + +# `#[async_trait]` + +Rewrite a trait's `async fn` declarations into the lint-clean `-> impl Future` form CGP's async methods use. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md new file mode 100644 index 00000000..a7b27b23 --- /dev/null +++ b/docs/reference/macros/blanket_trait.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[blanket_trait]' +--- + +# `#[blanket_trait]` + +Generate a blanket impl from a trait with default methods and supertrait dependencies. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md new file mode 100644 index 00000000..473e936f --- /dev/null +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[cgp_auto_dispatch]' +--- + +# `#[cgp_auto_dispatch]` + +Generate a handler that dispatches over an extensible-data input from a per-type trait. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md new file mode 100644 index 00000000..3760dc7a --- /dev/null +++ b/docs/reference/macros/cgp_auto_getter.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[cgp_auto_getter]' +--- + +# `#[cgp_auto_getter]` + +Define a getter as a blanket impl over `HasField`, keyed by the method name. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md new file mode 100644 index 00000000..b7197915 --- /dev/null +++ b/docs/reference/macros/cgp_component.md @@ -0,0 +1,346 @@ +--- +sidebar_label: '#[cgp_component]' +--- + +# `#[cgp_component]` + +Turn a trait into a component: the consumer trait callers use, the provider trait implementations +target, and the key that wires them together. + +## What it's for + +An ordinary Rust [trait](https://doc.rust-lang.org/book/ch10-02-traits.html) can have only one +implementation per type. That is usually what you want, and it is what lets the compiler resolve a +`where T: Display` bound without anyone naming an implementation — but it means a capability with +several plausible implementations has nowhere to put them. A type either sends real email or records +it for a test; it cannot do both, and choosing between them means editing the impl rather than +choosing at the point of use. + +`#[cgp_component]` splits that one trait into two, so that *using* a capability and *implementing* it +stop being the same act: + +- The **consumer trait** is what callers write — `context.area()`. It keeps the name and shape you + gave it. +- The **provider trait** is what implementations target. It is the same interface with `Self` moved + into an explicit type parameter, so an implementation is written for a small named type of its own + rather than for the type the capability is about. + +Because each implementation now targets its own name, any number of them can coexist. A **provider** +is one of those names — a zero-sized type such as `RectangleArea` that exists only to identify an +implementation. A concrete type then picks the provider it wants through +[`delegate_components!`](./delegate_components.md), and generated glue routes calls on the consumer +trait to the provider that was picked. The whole choice is resolved during compilation and compiles +down to a direct call. + +The macro also emits a **component name** — a marker type such as `AreaCalculatorComponent` — which is +the key wiring uses. You will see it in every `delegate_components!` entry and in most compiler +errors, so it is worth recognizing even though you never write its definition. + +## When to reach for it, and when not + +Reach for `#[cgp_component]` when a capability genuinely needs **more than one implementation, and the +choice belongs to the type using it.** That is the case it exists for, and its machinery is not free: +a component is a trait, a second trait, a marker type, and a line of wiring per type. + +Prefer something simpler when you can. + +- **One implementation, ever.** Use [`#[cgp_fn]`](./cgp_fn.md) instead. It builds the capability + straight from a function, needs no wiring at all, and keeps working unchanged if a second + implementation ever arrives — so it is the right starting point rather than a lesser one. +- **One implementation per type, chosen globally.** That is what a plain Rust trait already does well. + Reach for a component when two *different* applications must make different choices for the same + type, or when the implementations must overlap in a way the compiler rejects. +- **A closed set of variants with fixed operations.** An `enum` and a `match` are clearer than any + machinery. + +There is also a finer line worth knowing: a capability may genuinely need several implementations +while each individual implementation serves exactly one type. In that case you can implement the +consumer trait directly on each concrete type, as you would any Rust trait, and skip providers +entirely. Named providers earn their place once a second type wants the *same* implementation, or once +an implementation should compose with a wrapper. + +### How many items should a component have? + +A component trait is an ordinary trait. It takes as many methods, associated types, and associated +consts as any other, and every one of them is reproduced on the provider trait — CGP's own +[`CanCompute`](../components/computer.md) declares an associated `Output` beside its method. There is +no cap. + +What to group is a judgement rather than a rule, and the useful question is: **everything in one +component is answered by one provider choice.** Items a single choice settles belong together — a +method and the associated type it returns, or several field reads one getter provider answers by name. +Items that separate choices settle are better apart, because grouping them costs reuse: every provider +then carries the union of the dependencies of all the methods, a wrapper must forward the methods it +has no opinion about, and a type that needs only part of the surface must still supply the rest. + +The usual sign of a component that has grown past one decision is a consumer trait named after a noun +rather than a verb — `Shape` carrying `area`, `perimeter`, `scale`, and `rotate`. It compiles, but very +little of it is reusable. A good check before committing: could a second type plausibly reuse one of +this trait's providers *whole*? If not, implement the trait directly on the concrete type and skip the +machinery. + +## Using it + +Apply the attribute to a trait definition and give it the provider trait's name. The simplest form is +a bare identifier: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +`CanCalculateArea` is the consumer trait and `AreaCalculator` is the provider trait. The naming +convention is worth following: a consumer trait reads as a verb (`CanDoSomething`) and a provider trait +as a noun (`SomethingDoer`, or `…Provider` when no noun fits). + +When you need more control, the macro accepts a key/value form instead: + +```rust +#[cgp_component { + name: AreaCalculatorComponent, + provider: AreaCalculator, + context: Context, +}] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +Each key has a default and only `provider` is required — passing a bare identifier is shorthand for +setting it alone. + +| Key | What it sets | Default | +|---|---|---| +| `provider` | The provider trait's name | *required* | +| `name` | The component marker type | The provider name plus `Component` | +| `context` | The identifier used for the generated context type parameter | `__Context__` | + +The `context` default is deliberately unusual so that it cannot collide with a type parameter of your +own. + +### Supertraits, and importing an abstract type + +When a component depends on a type another component supplies — most often the error type from +[`HasErrorType`](../components/has_error_type.md) — import it with +[`#[use_type]`](../attributes/use_type.md) rather than writing the supertrait and the qualified path by +hand. The attribute adds the supertrait *and* rewrites a bare `Error` in your signatures to its fully +qualified form: + +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} +``` + +For a supertrait with no associated type to import, use [`#[extend(...)]`](../attributes/extend.md) in +preference to native `: Supertrait` syntax — `#[extend(HasName)]` reads as importing a capability, +where `pub trait CanGreet: HasName` reads as inheritance, which is not what a CGP supertrait is. An +associated type the trait declares *itself* is not imported and stays written as `Self::Output`. + +One further companion attribute exists: [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) +generates dispatch impls for a component generic over a parameter. It is superseded by the `open` +statement of [`delegate_components!`](./delegate_components.md) and is mostly something you read in +existing code rather than write. + +## Examples + +A component, a provider for it, and a type that wires the two together: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +fn print_area(rect: &Rectangle) { + println!("area = {}", rect.area()); +} +``` + +`rect.area()` is an ordinary method call on the consumer trait. It resolves through `Rectangle`'s +table, which maps `AreaCalculatorComponent` to `RectangleArea`, and `RectangleArea::area` reads the two +fields to compute the result. Swapping the provider in that one wiring line changes what `rect.area()` +does, and nothing else in the program changes. + +## Under the hood + +:::note Advanced + +This section shows the code the macro generates. You do not need it to use `#[cgp_component]`, but +CGP's constructs are macros, and reading what one produces is the fastest way to understand a compiler +error that names a type you did not write. Running `cargo cgp expand` prints the same thing for your +own code. + +::: + +From this input: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +the macro emits five items. First, the **consumer trait**, unchanged: + +```rust +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +Second, the **provider trait**: the same interface with `Self` replaced by a leading `Context` type +parameter and every `self`/`Self` rewritten to `context`/`Context`. Its +[`IsProviderFor`](../traits/is_provider_for.md) supertrait is what makes an unmet dependency report +itself by name rather than as a bare "trait not implemented"; its third argument is a tuple of the +component's extra type parameters, empty here: + +```rust +pub trait AreaCalculator: + IsProviderFor +{ + fn area(context: &Context) -> f64; +} +``` + +Third, the **consumer blanket impl**, the bridge that lets callers write `context.area()`: any context +implementing the provider trait *for itself* gets the consumer trait. + +```rust +impl CanCalculateArea for Context +where + Context: AreaCalculator, +{ + fn area(&self) -> f64 { + Context::area(self) + } +} +``` + +Fourth, the **provider blanket impl**, which is what makes wiring work: anything that delegates this +component through [`DelegateComponent`](../traits/delegate_component.md) inherits the provider trait +from whatever it delegates to. + +```rust +impl AreaCalculator for Provider +where + Provider: DelegateComponent + + IsProviderFor, + Provider::Delegate: AreaCalculator, +{ + fn area(context: &Context) -> f64 { + Provider::Delegate::area(context) + } +} +``` + +The `IsProviderFor` bound sits on `Provider` itself rather than on `Provider::Delegate`. That is what +threads a provider's dependencies down the delegation chain so they still appear in an error message. + +Fifth, the **component marker**, the key wiring uses: + +```rust +pub struct AreaCalculatorComponent; +``` + +Beyond those five, the macro emits the standard provider impls that let the component participate in +CGP's usual patterns: a [`UseContext`](../providers/use_context.md) impl, so the provider trait can be +satisfied by routing back through the context's own implementation; a +[`RedirectLookup`](../providers/redirect_lookup.md) impl, which is what the `open` statement and +[namespaces](./cgp_namespace.md) resolve through; and a +[`UseDelegate`](../providers/use_delegate.md) impl for each +[`#[derive_delegate(...)]`](../attributes/derive_delegate.md) attribute present. + +Two details of the real output differ from the listings above, and both trip people up when reading an +error. The generated parameters carry **reserved names** — the context is literally `__Context__` +unless you override it, and the provider parameter is `__Provider__`; the readable `Context` and +`Provider` here are for legibility only. And a component with its own type parameters, such as +`CanCalculateArea`, appends them *after* the context in the provider trait and groups them into +the `IsProviderFor` parameter tuple: `IsProviderFor`. + +
+Formal grammar + +The attribute argument is either a bare provider name or a comma-separated set of keyed values, in the +Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpComponentArgs -> ProviderName + | KeyValueArg ( `,` KeyValueArg )* `,`? + +ProviderName -> IDENTIFIER + +KeyValueArg -> `name` `:` ComponentName + | `provider` `:` IDENTIFIER + | `context` `:` IDENTIFIER + +ComponentName -> IDENTIFIER GenericArgs? +``` + +`ProviderName` is shorthand for setting `provider` alone. In the key/value form each key may appear at +most once, in any order, and `provider` is required. `IDENTIFIER` is a Rust identifier token, and +`GenericArgs` is the Rust grammar's `< … >` argument list — so the component name may carry generic +parameters while the provider name may not. The attribute delimiter — `(...)` for the bare form, +`{...}` for the key/value form — is ordinary Rust attribute syntax and does not change how the +arguments inside are parsed. + +
+ +## Gotchas + +**A const generic parameter on the trait is rejected**, with a compile error. A component's extra +parameters are recorded as a tuple of *types* in the `IsProviderFor` supertrait, and CGP's wiring +dispatches on types rather than values, so a const value has nowhere to live in that machinery. + +An associated `const` *item* is unaffected — `const LIMIT: u64;` as a trait member is an +[associated const](https://doc.rust-lang.org/reference/items/associated-items.html), not a generic +parameter, and a provider supplies it in the ordinary way. Naming your own associated const from +*inside* a [`#[cgp_impl]`](./cgp_impl.md) body has a wrinkle of its own, covered in that page's +Gotchas. + +## Related constructs + +- [`#[cgp_impl]`](./cgp_impl.md) — the idiomatic way to write a provider for a component. +- [`#[cgp_provider]`](./cgp_provider.md) — the lower-level provider form it desugars to. +- [`#[cgp_fn]`](./cgp_fn.md) — the lighter alternative when one implementation is enough. +- [`delegate_components!`](./delegate_components.md) — wires a component to a provider on a type. +- [`check_components!`](./check_components.md) — verifies that wiring at compile time. +- [`#[cgp_type]`](./cgp_type.md) — the specialized form for a component that supplies a type. +- [`#[cgp_getter]`](./cgp_getter.md) — the specialized form for a component that reads a field. +- [`#[use_type]`](../attributes/use_type.md), [`#[extend]`](../attributes/extend.md), and + [`#[derive_delegate]`](../attributes/derive_delegate.md) — attributes that change what it generates. + +## Source + +- Entry point: [`cgp_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_component.rs) +- Implementation: [`types/cgp_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md new file mode 100644 index 00000000..cc64bf6a --- /dev/null +++ b/docs/reference/macros/cgp_computer.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[cgp_computer]' +--- + +# `#[cgp_computer]` + +Define a `Computer` provider from a plain function. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md new file mode 100644 index 00000000..dd9469f4 --- /dev/null +++ b/docs/reference/macros/cgp_fn.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[cgp_fn]' +--- + +# `#[cgp_fn]` + +Define a single-implementation capability as a blanket-impl trait, straight from a function. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md new file mode 100644 index 00000000..ef405259 --- /dev/null +++ b/docs/reference/macros/cgp_getter.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[cgp_getter]' +--- + +# `#[cgp_getter]` + +Define a getter as a full component, so the field it reads is chosen by wiring rather than by its name. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md new file mode 100644 index 00000000..5411f844 --- /dev/null +++ b/docs/reference/macros/cgp_impl.md @@ -0,0 +1,330 @@ +--- +sidebar_label: '#[cgp_impl]' +--- + +# `#[cgp_impl]` + +Write a provider using consumer-trait syntax, keeping `self`, `Self`, and the method signatures you +already know. + +## What it's for + +A [provider trait](./cgp_component.md) is shaped inside-out compared with the trait it came from. The +original `Self` has moved into an explicit leading type parameter, the implementation targets a small +marker type rather than the type the capability is about, and the method receiver is a plain parameter. +Written by hand it looks like this: + +```rust +impl AreaCalculator for RectangleArea +where + Context: HasDimensions, +{ + fn area(context: &Context) -> f64 { + context.width() * context.height() + } +} +``` + +Every part of that is correct, and almost every part of it is unfamiliar. The trait carries a +parameter you did not write, `Self` is a type with no values, and there is no `self` anywhere — which +obscures the simple thing that is actually going on: this is an implementation of `CanCalculateArea`. + +`#[cgp_impl]` gives you back the familiar shape. Write the implementation as though you were +implementing the consumer trait directly, with `self` and `Self` and the signatures from the original +trait, and put the provider's name in the attribute: + +```rust +#[cgp_impl(new RectangleArea)] +impl AreaCalculator +where + Self: HasDimensions, +{ + fn area(&self) -> f64 { + self.width() * self.height() + } +} +``` + +The macro performs the rewrite for you. **This is the form to write**; the inside-out one is what it +desugars to and what you will meet in generated code. + +One fact the convenience must not hide: **inside a `#[cgp_impl]` block, `self` and `Self` mean the +context, not the provider.** The provider is a type-level name with no fields and no value — it is +never constructed, and there is nothing in it to read. The macro rewrites `self` to the context value +and `Self` to the context type precisely because the context is the only thing that exists when the +method runs. + +## When to reach for it, and when not + +**Write providers with `#[cgp_impl]`.** It is the recommended form, and the two constructs that could +replace it are narrower than they look — one is the raw shape it desugars to, the other is for +capabilities that need no provider at all. + +Prefer the unqualified header `impl AreaCalculator`, with no `for Context`, and let the macro insert +the context parameter. That is what makes a provider read like an ordinary trait impl. Name the context +explicitly — `impl AreaCalculator for Context` — only when you actually need to say something +about it that the sugar cannot express, such as a lifetime or a higher-ranked bound. + +Reach for something else in three cases. + +- **You need the inside-out shape itself.** [`#[cgp_provider]`](./cgp_provider.md) and + `#[cgp_new_provider]` are the raw forms. Write one when you must state a bound the sugar cannot, or + when implementing a provider trait on a concrete type rather than a generic one. Otherwise, read + them and write `#[cgp_impl]`. +- **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain + function with no component, no provider, and no wiring. +- **You want to implement the consumer trait directly on one concrete type.** Use the + [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly) below, which keeps the + companion attributes while emitting an ordinary impl. + +## Using it + +Apply the attribute to an `impl` block. Its argument names the provider, and has three parts of which +only the name is required. + +```rust +#[cgp_impl(new RectangleArea)] +impl AreaCalculator +where + Self: HasDimensions, +{ + fn area(&self) -> f64 { + self.width() * self.height() + } +} +``` + +| Part | Meaning | +|---|---| +| `new` | Optional. Also emits `pub struct RectangleArea;`, so you need not declare the provider separately. | +| provider name | Required. The type that takes the `Self` position in the generated provider impl. | +| `: ComponentType` | Optional. Overrides the component used in the generated [`IsProviderFor`](../traits/is_provider_for.md) impl. Defaults to the provider trait's name plus `Component`. | + +Without `new`, the provider struct must already exist — a wiring entry naming a struct nothing +declares is a common and confusing first error. + +A provider may be generic. Parameters go in the attribute and in the impl generics together, which is +how a higher-order provider takes an inner provider: + +```rust +#[cgp_impl(new ScaledAreaCalculator)] +#[use_provider(InnerCalculator: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + let base_area = InnerCalculator::area(self); + base_area * scale_factor * scale_factor + } +} +``` + +### Companion attributes + +Several attributes are processed on a `#[cgp_impl]` block before the rewrite happens, and together +they are how an idiomatic provider states what it needs. + +- [`#[implicit]`](../attributes/implicit.md) on a parameter removes it from the signature and fills it + from a same-named field on the context. +- [`#[uses(...)]`](../attributes/uses.md) adds the capabilities the provider depends on, reading like + a `use` statement instead of a hand-written `where Self: Trait` clause. +- [`#[use_type(Trait.Type)]`](../attributes/use_type.md) imports an abstract type and rewrites its + occurrences to fully qualified form. +- [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound in a + higher-order provider. +- [`#[default_impl(...)]`](../traits/default_namespace.md) registers the provider as a namespace's + per-type default. + +### Implementing the consumer trait directly + +Naming `Self` as the provider bypasses the rewrite entirely and emits the block unchanged as an +ordinary consumer-trait impl on a concrete type. This form requires the `for Context` clause, and it is +useful when you want a hand-written impl while still applying the companion attributes. Because no +provider struct is generated, `new` and the component override have no effect. + +```rust +#[cgp_impl(Self)] +#[use_provider(RectangleArea: AreaCalculator)] +impl CanCalculateArea for Rectangle { + fn area(&self) -> f64 { + RectangleArea::area(self) + } +} +``` + +## Examples + +The most idiomatic form of a provider reads almost like a plain function. Given the `AreaCalculator` +component: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} +``` + +The two `#[implicit]` parameters are removed from the signature and replaced by reads of the `width` +and `height` fields, so the provider requires a context that has them. The `new` keyword defines +`RectangleArea`. A concrete type then wires the component and calls through it: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +fn print_area(rect: &Rectangle) { + println!("area = {}", rect.area()); +} +``` + +## Under the hood + +:::note Advanced + +This section shows what the macro generates. You do not need it to write a provider, but the rewrite is +worth seeing once — most confusing errors in a provider body are explained by it. `cargo cgp expand` +prints the same thing for your own code. + +::: + +`#[cgp_impl]` desugars to [`#[cgp_provider]`](./cgp_provider.md). It moves the context type to the +leading position of the provider trait, swaps the provider name into the `Self` position, and rewrites +every `self`/`Self`. From this input, with the context named explicitly for clarity: + +```rust +#[cgp_impl(new ValueToString)] +impl FooProvider for Context { + fn foo(&self, value: u32) -> String { + value.to_string() + } +} +``` + +the macro produces the provider impl, an `IsProviderFor` impl, and — because `new` was given — the +provider struct: + +```rust +impl FooProvider for ValueToString { + fn foo(__context__: &Context, value: u32) -> String { + value.to_string() + } +} + +impl IsProviderFor for ValueToString {} + +pub struct ValueToString; +``` + +Three things changed. The trait gained `Context` as its leading argument; the `Self` type became the +provider; and `&self` became the explicit parameter `__context__: &Context`. The receiver identifier is +the snake-cased context type wrapped in double underscores, so both `Context` and the default +`__Context__` become `__context__`. Every `self` in a body is rewritten to that identifier, and every +`Self` to the context type. + +When `for Context` is omitted the only difference is that the inserted parameter is `__Context__`. The +earlier `RectangleArea` example is exactly equivalent to writing it out: + +```rust +#[cgp_new_provider] +impl<__Context__> AreaCalculator<__Context__> for RectangleArea +where + __Context__: HasDimensions, +{ + fn area(__context__: &__Context__) -> f64 { + __context__.width() * __context__.height() + } +} +``` + +The generated `IsProviderFor` impl copies the provider impl's signature, drops the body, and keeps the +`where` clause — which is how the provider's dependencies are captured for error reporting. Its +arguments are the component name, the context, and a tuple of any remaining provider-trait parameters, +so a provider for `ComputerRef` gets +`IsProviderFor`. + +**The rewrite is scoped to the block's own method bodies.** An item nested *inside* a body — a local +`struct` with its own impl, a helper `fn`, an inline `trait` — introduces a fresh `self`/`Self` that +belongs to that item, exactly as in ordinary Rust, and the macro leaves it alone. Closures, which +capture the enclosing `self`, are rewritten like any other expression. + +
+Formal grammar + +The attribute argument names the provider, optionally preceded by `new` and followed by a +component-type override, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpImplArgs -> `new`? ProviderType ( `:` ComponentType )? + +ProviderType -> Type +ComponentType -> Type +``` + +`ProviderType` is the type taking the `Self` position of the generated impl: a plain provider name, a +generic provider such as `ScaledAreaCalculator`, or the literal `Self` for the +passthrough form. `ComponentType` overrides the component in the generated `IsProviderFor` impl, +defaulting to the provider trait's name plus `Component`. Both are Rust `Type` productions. + +
+ +## Gotchas + +**A provider's own associated const or type is awkward to name inside its body**, and this follows +directly from the rewrite. A component may declare associated items alongside its methods, and a +provider supplies them in the `#[cgp_impl]` block as usual — but `Self::LIMIT` in a method body does +*not* resolve to the const the block just defined, because `Self` has been rewritten to the context. +The error reads: + +```text +error[E0599]: no associated function or constant named `LIMIT` found for type parameter `__Context__` +``` + +Name it through the provider trait instead, which the rewrite turns into the correct qualified path: + +```rust +>::LIMIT +``` + +The consumer side is unaffected — a wired context reads the same const as `::LIMIT`. + +**One nesting case escapes the scoping rule.** An item written inside a `macro!( … )` invocation has +its `self`/`Self` rewritten too, because a token-level rewrite cannot see the scope the macro will +eventually create. + +## Related constructs + +- [`#[cgp_component]`](./cgp_component.md) — defines the component this implements. +- [`#[cgp_provider]`](./cgp_provider.md) — the lower-level form `#[cgp_impl]` desugars to. +- [`#[cgp_fn]`](./cgp_fn.md) — the lighter alternative when one implementation is enough. +- [`delegate_components!`](./delegate_components.md) — wires the provider onto a type. +- [`check_components!`](./check_components.md) — verifies the wiring resolves. +- [`#[implicit]`](../attributes/implicit.md), [`#[uses]`](../attributes/uses.md), + [`#[use_type]`](../attributes/use_type.md), [`#[use_provider]`](../attributes/use_provider.md), + [`#[default_impl]`](../traits/default_namespace.md) — the companion attributes. + +## Source + +- Entry point: [`cgp_impl.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_impl.rs) +- Implementation: [`types/cgp_impl/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_impl/) +- The `self`/`Self` rewrite: [`visitors/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/visitors/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md new file mode 100644 index 00000000..6bcfd843 --- /dev/null +++ b/docs/reference/macros/cgp_namespace.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'cgp_namespace!' +--- + +# `cgp_namespace!` + +Define a reusable, inheritable wiring table that many contexts can join. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md new file mode 100644 index 00000000..66a111fd --- /dev/null +++ b/docs/reference/macros/cgp_producer.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[cgp_producer]' +--- + +# `#[cgp_producer]` + +Define a `Producer` provider from an input-free function. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md new file mode 100644 index 00000000..04b141c3 --- /dev/null +++ b/docs/reference/macros/cgp_provider.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' +--- + +# `#[cgp_provider]` & `#[cgp_new_provider]` + +Implement a provider trait directly, in the inside-out shape the sugar desugars to — with or without declaring the provider struct. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md new file mode 100644 index 00000000..92ff925e --- /dev/null +++ b/docs/reference/macros/cgp_type.md @@ -0,0 +1,15 @@ +--- +sidebar_label: '#[cgp_type]' +--- + +# `#[cgp_type]` + +Define an abstract-type component, whose concrete type each context chooses for itself. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md new file mode 100644 index 00000000..c0787027 --- /dev/null +++ b/docs/reference/macros/check_components.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'check_components!' +--- + +# `check_components!` + +Assert at compile time that a context can actually use each component it wires. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md new file mode 100644 index 00000000..438c0f3d --- /dev/null +++ b/docs/reference/macros/delegate_and_check_components.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'delegate_and_check_components!' +--- + +# `delegate_and_check_components!` + +Wire a context and check that wiring in one macro. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md new file mode 100644 index 00000000..003e55ef --- /dev/null +++ b/docs/reference/macros/delegate_components.md @@ -0,0 +1,376 @@ +--- +sidebar_label: 'delegate_components!' +--- + +# `delegate_components!` + +Build a context's wiring table, naming the provider that implements each of its components. + +## What it's for + +[`#[cgp_component]`](./cgp_component.md) separates the trait callers use from the trait +implementations target, which leaves one question open: for a given type, *which* implementation +supplies the behavior? `delegate_components!` answers it. You give it a type and a list of entries — +the component name as the key, the chosen provider as the value — and it records that choice on the +type. + +```rust +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +The mental model is a **table**: a compact list saying which implementation supplies each capability. +It is worth being precise about one thing, because the analogy invites the wrong conclusion. This looks +like an object's method table, but it is resolved entirely at compile time — the keys and values are +types, the lookup happens during trait resolution, and the result monomorphizes to a direct call. +There is no table in the compiled program, no dynamic dispatch, and nothing in the binary for a +provider you did not choose. + +The type this table is attached to is a **context**: the type that owns the wiring. Often it is a type +standing for your whole application, whose job is to carry choices rather than data — `struct App;` +with no fields is a perfectly good context. Sometimes, as above, it is the data type itself. + +A macro is worth having here because each entry expands to two impls rather than one. Besides the +[`DelegateComponent`](../traits/delegate_component.md) impl that stores the choice, the macro emits an +[`IsProviderFor`](../traits/is_provider_for.md) impl that forwards the chosen provider's own +dependencies back through the table — which is what makes a missing transitive requirement produce a +usable error instead of a dead end. + +## When to reach for it, and when not + +Use `delegate_components!` whenever a context needs to choose providers, which is any time you use +[`#[cgp_component]`](./cgp_component.md) at all. The real decision is not whether to wire but **how to +check the wiring**, because CGP's wiring is *lazy*: a table with a missing or wrong entry still +compiles, and the failure only surfaces later, where the capability is used. + +- **Pair it with [`check_components!`](./check_components.md)** for anything beyond simple wiring. A + separate check gives you full control over what is asserted — concrete parameters for generic keys, + per-provider layers, and opened or namespaced wiring — which is why larger codebases keep the two + macros apart. +- **Use [`delegate_and_check_components!`](./delegate_and_check_components.md)** when you are getting + started or the wiring is plain `Component: Provider` entries. It fuses the two so the check cannot be + forgotten. +- **Use plain `delegate_components!` with no check** for an **aggregate provider** — the + `new`-keyword form below. That target is a provider other contexts delegate to rather than a context + in its own right, so the fused macro's check would fail spuriously on it. + +The one thing not to do is leave a context's wiring unchecked. Which macro you use to check it scales +with how complicated the wiring is; that it is checked somehow does not. + +## Using it + +The macro takes a target type and a brace-delimited list of `Key: Value` entries. + +```rust +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +### Defining the target at the same time + +A leading `new` keyword makes the macro declare the target struct as well. + +```rust +delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } +} +``` + +This is how you build an **aggregate provider**: a zero-sized provider whose only job is to hold a +table dispatching each component to a sub-provider, so that other contexts can delegate a whole group +of components to it as one unit. An aggregate provider is a *provider*, not a context — it forwards +each component's provider trait onward and never implements one with itself in the context position. +That is why it must be wired with plain `delegate_components!` and never with +[`delegate_and_check_components!`](./delegate_and_check_components.md). + +### One provider for several components + +A bracketed list on the key side expands to one entry per name: + +```rust +delegate_components! { + MyComponents { + [ + FooComponent, + BarComponent, + ]: FooBarProvider, + BazComponent: BazProvider, + } +} +``` + +### One table for a family of types + +A leading generic list makes the whole table generic, wiring every instantiation at once: + +```rust +delegate_components! { + MyContext { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +### Choosing a provider per type: the `open` statement + +When a component is generic over a type parameter, you usually want a different provider for each +value of it. The `open` statement folds those per-value entries straight into the context's own table. +A leading `open …;` header opens one or more components, and `@`-path entries then assign a provider +per key: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +The `open` header **must come first**, before any plain `Component: Provider` entries, or the macro +fails to parse. Braces are optional when opening a single component, so `open AreaCalculatorComponent;` +and `open { AreaCalculatorComponent };` are the same; the braced list is only needed to open several at +once. A key may share one provider across several values with the array shorthand on its final segment, +`@AreaCalculatorComponent.[Rectangle, Circle]: SomeProvider`, and may carry generics, +`@SomeComponent.<'a, T> &'a T: SomeProvider`. + +`open` needs no extra attribute on the component: it works through the +[`RedirectLookup`](../providers/redirect_lookup.md) impl that every `#[cgp_component]` already +generates. It is a lightweight special case of the full [namespace](./cgp_namespace.md) feature, suited +to a context wiring its own components directly, and it does not combine with a joined namespace where +the component carries a `#[prefix(...)]`. + +:::info Legacy — read, don't write + +Older code dispatches the same way by nesting a table inside a +[`UseDelegate`](../providers/use_delegate.md) value: + +```rust +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +This still works, and you will meet it — including in CGP's own error and handler components, which +are defined with [`#[derive_delegate]`](../attributes/derive_delegate.md). The `open` statement above +achieves the same dispatch with no separate table type and no wrapper, and is preferred for new code. + +::: + +### Namespace statements + +Beyond entries and `open`, the table body accepts the statement forms that opt a context into a +[`cgp_namespace!`](./cgp_namespace.md): a leading `namespace SomeNamespace;` header that forwards +unwired lookups through that namespace, `@`-path keys targeting a route rather than a bare component +name, and `for in SomeTable { … }` loops that pull entries from another table. These are +described on the namespace page, where they are most often written. + +The macro accepts **no attributes** on the table or on any key, and rejects any it finds rather than +ignoring them. Attribute-driven variants such as `#[check_params(...)]` and `#[skip_check]` belong to +[`delegate_and_check_components!`](./delegate_and_check_components.md). + +## Examples + +A component, a provider, and a context wired to use it: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +fn print_area(rect: &Rectangle) { + println!("area = {}", rect.area()); +} +``` + +The payoff is what happens when you change one line. Wiring a second context to a different provider +gives two types that answer `area()` differently, with no change to any code that calls it: + +```rust +delegate_components! { + Square { + AreaCalculatorComponent: SquareArea, + } +} +``` + +## Under the hood + +:::note Advanced + +This section shows the impls each entry expands to. You do not need them to wire a context, but they +are what a wiring error names, so reading one makes those errors much easier to follow. +`cargo cgp expand` prints the same thing for your own code. + +::: + +Each entry becomes a pair of impls. From the single-entry table above, first the +`DelegateComponent` impl that records the choice: + +```rust +impl DelegateComponent for Rectangle { + type Delegate = RectangleArea; +} +``` + +That impl alone is the whole lookup. The provider blanket impl generated by +[`#[cgp_component]`](./cgp_component.md) reads it, so `Rectangle` inherits `AreaCalculator` +from `RectangleArea`, and the consumer blanket impl then gives `Rectangle` the `CanCalculateArea` trait. +The hand-written equivalent of one wiring entry is exactly that block. + +Second, the `IsProviderFor` impl that forwards the provider's requirements: + +```rust +impl<__Context__, __Params__> + IsProviderFor for Rectangle +where + RectangleArea: IsProviderFor, +{} +``` + +This is why missing dependencies stay diagnosable. `RectangleArea`'s own `IsProviderFor` impl carries +the `where` bounds it needs, so an unsatisfied requirement flows back through this forwarding impl to +the point of use. Note that these parameters are literally named `__Context__` and `__Params__` in the +emitted code. + +The array syntax simply repeats the pair per key. A table with `[FooComponent, BarComponent]: +FooBarProvider` and `BazComponent: BazProvider` yields three `DelegateComponent` impls and three +matching `IsProviderFor` impls. + +The `open` statement expands to a redirect plus per-value entries stored on the context itself. The +header wires the component to a `RedirectLookup` rooted at the component name inside `MyApp`'s own +table: + +```rust +impl DelegateComponent for MyApp { + type Delegate = RedirectLookup>; +} +``` + +Each `@AreaCalculatorComponent.Rectangle: RectangleArea` entry then stores its provider in that same +table under a path key, so `MyApp` gains +`DelegateComponent>>` with +`Delegate = RectangleArea`. The [`RedirectLookup`](../providers/redirect_lookup.md) impl appends the +dispatch parameter onto the path and reads the result back, so `MyApp: CanCalculateArea` +resolves to `RectangleArea`. The legacy nested-table form keys on the same parameter; the difference is +only that its per-value entries live in a separate table type. + +
+Formal grammar + +In the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +DelegateComponents -> Generics? `new`? TargetType `{` TableBody `}` + +TargetType -> Type + +TableBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? + +Statement -> OpenStmt | NamespaceStmt | ForStmt + +OpenStmt -> `open` ( `{` Type ( `,` Type )* `,`? `}` | Type ) `;` + +Mapping -> Key `:` ProviderValue + | Key `->` ProviderValue + | Key `=>` Path + +Key -> SingleKey | MultiKey | PathKey +SingleKey -> Generics? Type +MultiKey -> `[` SingleKey ( `,` SingleKey )* `,`? `]` +PathKey -> Generics? Path + +ProviderValue -> Type + | IDENTIFIER `<` `new` TargetType `{` TableBody `}` `>` + +Path -> `@` PathSegment ( `.` PathSegment )* +``` + +A leading `Generics` list makes the table generic over the target; `new` additionally emits the target +struct. Each `Mapping` uses one of three operators: `:` maps a key to a provider, which is the common +form, while `->` delegates to the value's own entry for that key and `=>` redirects along an `@`-path; +the latter two belong to the namespace machinery. A `Key` may be a single type, a bracketed list +expanding to one entry per name, or an `@`-path. An `OpenStmt` may omit its braces when opening exactly +one component. `NamespaceStmt`, `ForStmt`, and the `Path` segment rules are defined under +[`cgp_namespace!`](./cgp_namespace.md) and [`Path!`](./path.md). The macro accepts no attributes +anywhere and rejects any it finds. + +
+ +## Gotchas + +**Wiring is lazy.** A table with a missing entry, or one naming a provider whose own dependencies are +unmet, still compiles. The failure appears later, at the place the capability is used, often as a long +error naming types you did not write. This is the single most common source of confusion with CGP, and +the answer is to check the table — see [`check_components!`](./check_components.md) — and to run +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) in place of `cargo check`, which leads +with the root cause for the classes it recognizes. + +**The `open` header must lead the block.** Placing it after a plain `Component: Provider` entry is a +parse error rather than a semantic one, so the message will not point at the real problem. + +**Naming a provider struct that does not exist** is easy to do when a provider was written with +[`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared separately. The error +names an unresolved type rather than anything about wiring. + +## Related constructs + +- [`#[cgp_component]`](./cgp_component.md) — defines the components this table wires. +- [`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_provider]`](./cgp_provider.md) — write the providers it + names. +- [`check_components!`](./check_components.md) — asserts the table is complete and resolvable. +- [`delegate_and_check_components!`](./delegate_and_check_components.md) — wires and checks together. +- [`DelegateComponent`](../traits/delegate_component.md) and + [`IsProviderFor`](../traits/is_provider_for.md) — the traits each entry expands into. +- [`RedirectLookup`](../providers/redirect_lookup.md) — what `open` resolves through. +- [`UseDelegate`](../providers/use_delegate.md) — the legacy dispatch form `open` supersedes. +- [`cgp_namespace!`](./cgp_namespace.md) — reusable tables, for wiring that outgrows one context. +- [`UseField`](../providers/use_field.md) — the usual value for a field-backed getter. + +## Source + +- Entry point: [`delegate_components.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/delegate_components.rs) +- Implementation: [`types/delegate_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md new file mode 100644 index 00000000..ec6a48f5 --- /dev/null +++ b/docs/reference/macros/path.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Path!' +--- + +# `Path!` + +A type-level path, used by namespaces and redirected lookups. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md new file mode 100644 index 00000000..8bd24740 --- /dev/null +++ b/docs/reference/macros/product.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Product! & product!' +--- + +# `Product!` & `product!` + +A type-level list and its value-level counterpart. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md new file mode 100644 index 00000000..1633213b --- /dev/null +++ b/docs/reference/macros/sum.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Sum!' +--- + +# `Sum!` + +A type-level sum, the dual of `Product!`. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md new file mode 100644 index 00000000..5c6c0c31 --- /dev/null +++ b/docs/reference/macros/symbol.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Symbol!' +--- + +# `Symbol!` + +A type-level string, used as a field-name tag. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/_category_.json b/docs/reference/providers/_category_.json new file mode 100644 index 00000000..881aec3b --- /dev/null +++ b/docs/reference/providers/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Providers", + "position": 5, + "link": { + "type": "generated-index", + "description": "The zero-sized provider types that appear in wiring tables. They carry no runtime value and exist only at the type level." + } +} diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md new file mode 100644 index 00000000..6cc81be3 --- /dev/null +++ b/docs/reference/providers/chain_getters.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'ChainGetters' +--- + +# `ChainGetters` + +Compose getters to reach a field on a nested context. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/dispatch_combinators.md b/docs/reference/providers/dispatch_combinators.md new file mode 100644 index 00000000..abee38df --- /dev/null +++ b/docs/reference/providers/dispatch_combinators.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Dispatch combinators' +--- + +# Dispatch combinators + +The variant-matching and record-assembling providers that route extensible data to handlers. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/error_providers.md b/docs/reference/providers/error_providers.md new file mode 100644 index 00000000..a96610fa --- /dev/null +++ b/docs/reference/providers/error_providers.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Error providers' +--- + +# Error providers + +`RaiseFrom`, `ReturnError`, `DebugError`, and the other backends behind the error components. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/handler_combinators.md b/docs/reference/providers/handler_combinators.md new file mode 100644 index 00000000..dba91b96 --- /dev/null +++ b/docs/reference/providers/handler_combinators.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Handler combinators' +--- + +# Handler combinators + +`ComposeHandlers`, `PipeHandlers`, `ReturnInput`, and the `Promote*` lifts. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/monad_providers.md b/docs/reference/providers/monad_providers.md new file mode 100644 index 00000000..22478277 --- /dev/null +++ b/docs/reference/providers/monad_providers.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Monad providers' +--- + +# Monad providers + +`PipeMonadic`, `BindOk`, `BindErr`, and the identity/ok/err monad markers. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md new file mode 100644 index 00000000..c580257d --- /dev/null +++ b/docs/reference/providers/redirect_lookup.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'RedirectLookup' +--- + +# `RedirectLookup` + +Re-route a component lookup along a type-level path. The mechanism behind namespaces and `open`. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md new file mode 100644 index 00000000..e8a07f05 --- /dev/null +++ b/docs/reference/providers/use_context.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'UseContext' +--- + +# `UseContext` + +Satisfy a provider trait by routing back through the context's own consumer impl. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md new file mode 100644 index 00000000..bd6983e7 --- /dev/null +++ b/docs/reference/providers/use_default.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'UseDefault' +--- + +# `UseDefault` + +Select a component's default method bodies. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md new file mode 100644 index 00000000..6b544d90 --- /dev/null +++ b/docs/reference/providers/use_delegate.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'UseDelegate' +--- + +# `UseDelegate` + +Dispatch on a generic parameter through an inner table. Superseded by the `open` statement. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md new file mode 100644 index 00000000..fe352b75 --- /dev/null +++ b/docs/reference/providers/use_delegated_type.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'UseDelegatedType' +--- + +# `UseDelegatedType` + +Resolve an abstract type through a lookup table instead of fixing it. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md new file mode 100644 index 00000000..ed4a0d15 --- /dev/null +++ b/docs/reference/providers/use_field.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'UseField, UseFieldRef & UseFields' +--- + +# `UseField`, `UseFieldRef` & `UseFields` + +The field-backed getter providers, and how to choose between them. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md new file mode 100644 index 00000000..8d0ecbf1 --- /dev/null +++ b/docs/reference/providers/use_type.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'UseType' +--- + +# `UseType` + +Supply a concrete type for an abstract-type component. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md new file mode 100644 index 00000000..949bdc2d --- /dev/null +++ b/docs/reference/providers/with_provider.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'WithProvider' +--- + +# `WithProvider` + +Adapt a foundational provider into a named component, with its `WithType`/`WithField`/`WithContext` aliases. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/_category_.json b/docs/reference/traits/_category_.json new file mode 100644 index 00000000..d0a1fe9f --- /dev/null +++ b/docs/reference/traits/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Traits", + "position": 6, + "link": { + "type": "generated-index", + "description": "The capability and mechanism traits the macros expand into \u2014 rarely written by hand, but worth understanding when reading generated code or a compiler error." + } +} diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/can_use_component.md new file mode 100644 index 00000000..7ed51213 --- /dev/null +++ b/docs/reference/traits/can_use_component.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'CanUseComponent' +--- + +# `CanUseComponent` + +The context-side check that a context both wires a component and satisfies its provider. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/cast.md b/docs/reference/traits/cast.md new file mode 100644 index 00000000..c15560d5 --- /dev/null +++ b/docs/reference/traits/cast.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'CanUpcast, CanDowncast & CanBuildFrom' +--- + +# `CanUpcast`, `CanDowncast` & `CanBuildFrom` + +Structural casts between records and between variants. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md new file mode 100644 index 00000000..bbbf4fa2 --- /dev/null +++ b/docs/reference/traits/default_namespace.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'DefaultNamespace & DefaultImpls' +--- + +# `DefaultNamespace` & `DefaultImpls` + +The namespace default-resolution traits, and `#[default_impl(...)]`. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/delegate_component.md new file mode 100644 index 00000000..2c694fb6 --- /dev/null +++ b/docs/reference/traits/delegate_component.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'DelegateComponent' +--- + +# `DelegateComponent` + +The per-context type-level table mapping a component key to its provider. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md new file mode 100644 index 00000000..d02dbf54 --- /dev/null +++ b/docs/reference/traits/extract_field.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'ExtractField' +--- + +# `ExtractField` + +The incremental-extractor trait family behind the extensible visitor pattern. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md new file mode 100644 index 00000000..e26ab8a5 --- /dev/null +++ b/docs/reference/traits/from_variant.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'FromVariant' +--- + +# `FromVariant` + +Generic construction of an enum from a named variant. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/has_builder.md b/docs/reference/traits/has_builder.md new file mode 100644 index 00000000..ba8f3e42 --- /dev/null +++ b/docs/reference/traits/has_builder.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'HasBuilder' +--- + +# `HasBuilder` + +The incremental-builder trait family behind the extensible builder pattern. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/has_field.md new file mode 100644 index 00000000..900c705e --- /dev/null +++ b/docs/reference/traits/has_field.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'HasField' +--- + +# `HasField` + +Tag-keyed field access, with `HasFieldMut` and the provider-side `FieldGetter`. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/has_fields.md new file mode 100644 index 00000000..e12a12c9 --- /dev/null +++ b/docs/reference/traits/has_fields.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'HasFields' +--- + +# `HasFields` + +The whole-shape field representation and its conversions. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/is_provider_for.md b/docs/reference/traits/is_provider_for.md new file mode 100644 index 00000000..c8af3cf9 --- /dev/null +++ b/docs/reference/traits/is_provider_for.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'IsProviderFor' +--- + +# `IsProviderFor` + +The marker supertrait that makes a provider's missing dependency show up by name. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md new file mode 100644 index 00000000..d17a2843 --- /dev/null +++ b/docs/reference/traits/map_type.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'MapType' +--- + +# `MapType` + +The present, absent, and void type-mapping markers and their transforms. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/monad.md b/docs/reference/traits/monad.md new file mode 100644 index 00000000..f16507d0 --- /dev/null +++ b/docs/reference/traits/monad.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Monad traits' +--- + +# Monad traits + +`MonadicTrans`, `MonadicBind`, `LiftValue`, and `ContainsValue`. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/optional_fields.md b/docs/reference/traits/optional_fields.md new file mode 100644 index 00000000..05f3a4cd --- /dev/null +++ b/docs/reference/traits/optional_fields.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Optional-field traits' +--- + +# Optional-field traits + +The builder and extractor traits for optional and defaulted fields. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/product_ops.md b/docs/reference/traits/product_ops.md new file mode 100644 index 00000000..85a8c426 --- /dev/null +++ b/docs/reference/traits/product_ops.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'AppendProduct, ConcatProduct & MapFields' +--- + +# `AppendProduct`, `ConcatProduct` & `MapFields` + +The type-level operations over product lists. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md new file mode 100644 index 00000000..7b12bc91 --- /dev/null +++ b/docs/reference/traits/static_format.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'StaticFormat, StaticString & ConcatPath' +--- + +# `StaticFormat`, `StaticString` & `ConcatPath` + +Recovering type-level strings and paths back into runtime data. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/types/_category_.json b/docs/reference/types/_category_.json new file mode 100644 index 00000000..ceb69b4c --- /dev/null +++ b/docs/reference/types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Type-level types", + "position": 7, + "link": { + "type": "generated-index", + "description": "The type-level building blocks the rest of CGP is constructed from." + } +} diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md new file mode 100644 index 00000000..d38c63cd --- /dev/null +++ b/docs/reference/types/field.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Field' +--- + +# `Field` + +A value paired with its type-level name tag. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md new file mode 100644 index 00000000..1f3c0646 --- /dev/null +++ b/docs/reference/types/index.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Index' +--- + +# `Index` + +A type-level natural number, used to tag tuple-struct fields. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md new file mode 100644 index 00000000..7dc4392f --- /dev/null +++ b/docs/reference/types/life.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Life' +--- + +# `Life` + +A lifetime lifted into a type. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md new file mode 100644 index 00000000..632bbc12 --- /dev/null +++ b/docs/reference/types/mref.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'MRef' +--- + +# `MRef` + +An owned-or-borrowed getter value. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: diff --git a/docs/reference/types/type_level_spines.md b/docs/reference/types/type_level_spines.md new file mode 100644 index 00000000..a7b6636c --- /dev/null +++ b/docs/reference/types/type_level_spines.md @@ -0,0 +1,15 @@ +--- +sidebar_label: 'Type-level spines' +--- + +# Type-level spines + +`Cons`/`Nil`, `Either`/`Void`, `Chars`, and `PathCons` — the lists the sugar expands into. + +:::info Not written yet + +This reference page is still being written. Until it lands, the +[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, +and `cargo cgp expand` will show you what it generates in your own code. + +::: From 4494448ed3a73034ebe6430124fd6296083bda5b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 10:53:56 +0200 Subject: [PATCH 010/516] Scaffold the concepts section, and revise the written reference pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a public Concepts section at docs/concepts/, one page per document in the knowledge base's concepts catalog — eighteen pages plus a hand-written index. Every page is scaffolded with its summary and a stub notice, so no idea is missing from the site even where the prose is unwritten, and one page is written in full as the model for the rest: Consumer and provider traits, which opens on the vanilla App/TestApp arrangement working before showing that nothing can be factored out of it. The section sits between Tutorials and Reference. Eighteen pages ahead of the tutorials would read as the theory CGP demands before a line of code, which the curated four-page tier this replaces would not have. Two revisions to the reference pages. An admonition's title moves to a heading on its own line, since the inline `:::note Advanced` form does not render as intended here; this reaches the scaffolded stubs too, which carried the same defect. And "When to reach for it, and when not" moves below the examples, so the judgement lands after the reader has seen the construct in use rather than before. Both snippets on the written page are compiled rather than eyeballed: the CGP listing against cgp 0.8.0-alpha with a check_components! per context, and the two vanilla listings through rustc to confirm one compiles and the other is E0119. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01HYb8eTVWU4N1ahqA2du34d --- docs/ai/_category_.json | 2 +- docs/concepts/_category_.json | 8 + docs/concepts/abstract-types.md | 19 ++ docs/concepts/aggregate-providers.md | 18 ++ docs/concepts/check-traits.md | 19 ++ docs/concepts/coherence.md | 19 ++ docs/concepts/consumer-and-provider-traits.md | 273 ++++++++++++++++++ docs/concepts/dispatching.md | 19 ++ docs/concepts/extensible-records.md | 18 ++ docs/concepts/extensible-variants.md | 19 ++ docs/concepts/handlers.md | 19 ++ docs/concepts/higher-order-providers.md | 19 ++ docs/concepts/impl-side-dependencies.md | 19 ++ docs/concepts/implicit-arguments.md | 18 ++ docs/concepts/index.md | 70 +++++ docs/concepts/modular-error-handling.md | 19 ++ docs/concepts/modularity-hierarchy.md | 19 ++ docs/concepts/monadic-handlers.md | 19 ++ docs/concepts/namespaces.md | 19 ++ docs/concepts/send-bounds.md | 19 ++ docs/concepts/type-level-dsls.md | 19 ++ docs/reference/attributes/derive_delegate.md | 4 +- docs/reference/attributes/extend.md | 4 +- docs/reference/attributes/extend_where.md | 4 +- docs/reference/attributes/implicit.md | 4 +- docs/reference/attributes/use_provider.md | 4 +- docs/reference/attributes/use_type.md | 4 +- docs/reference/attributes/uses.md | 4 +- docs/reference/components/can_raise_error.md | 4 +- docs/reference/components/computer.md | 4 +- docs/reference/components/handler.md | 4 +- docs/reference/components/has_error_type.md | 4 +- docs/reference/components/has_runtime.md | 4 +- docs/reference/components/has_type.md | 4 +- docs/reference/components/producer.md | 4 +- docs/reference/components/runner.md | 4 +- docs/reference/components/try_computer.md | 4 +- docs/reference/derives/derive_build_field.md | 4 +- docs/reference/derives/derive_cgp_data.md | 4 +- .../reference/derives/derive_extract_field.md | 4 +- docs/reference/derives/derive_from_variant.md | 4 +- docs/reference/derives/derive_has_field.md | 4 +- docs/reference/derives/derive_has_fields.md | 4 +- docs/reference/errors.md | 4 +- docs/reference/macros/async_trait.md | 4 +- docs/reference/macros/blanket_trait.md | 4 +- docs/reference/macros/cgp_auto_dispatch.md | 4 +- docs/reference/macros/cgp_auto_getter.md | 4 +- docs/reference/macros/cgp_component.md | 90 +++--- docs/reference/macros/cgp_computer.md | 4 +- docs/reference/macros/cgp_fn.md | 4 +- docs/reference/macros/cgp_getter.md | 4 +- docs/reference/macros/cgp_impl.md | 50 ++-- docs/reference/macros/cgp_namespace.md | 4 +- docs/reference/macros/cgp_producer.md | 4 +- docs/reference/macros/cgp_provider.md | 4 +- docs/reference/macros/cgp_type.md | 4 +- docs/reference/macros/check_components.md | 4 +- .../macros/delegate_and_check_components.md | 4 +- docs/reference/macros/delegate_components.md | 51 ++-- docs/reference/macros/path.md | 4 +- docs/reference/macros/product.md | 4 +- docs/reference/macros/sum.md | 4 +- docs/reference/macros/symbol.md | 4 +- docs/reference/providers/chain_getters.md | 4 +- .../providers/dispatch_combinators.md | 4 +- docs/reference/providers/error_providers.md | 4 +- .../providers/handler_combinators.md | 4 +- docs/reference/providers/monad_providers.md | 4 +- docs/reference/providers/redirect_lookup.md | 4 +- docs/reference/providers/use_context.md | 4 +- docs/reference/providers/use_default.md | 4 +- docs/reference/providers/use_delegate.md | 4 +- .../reference/providers/use_delegated_type.md | 4 +- docs/reference/providers/use_field.md | 4 +- docs/reference/providers/use_type.md | 4 +- docs/reference/providers/with_provider.md | 4 +- docs/reference/traits/can_use_component.md | 4 +- docs/reference/traits/cast.md | 4 +- docs/reference/traits/default_namespace.md | 4 +- docs/reference/traits/delegate_component.md | 4 +- docs/reference/traits/extract_field.md | 4 +- docs/reference/traits/from_variant.md | 4 +- docs/reference/traits/has_builder.md | 4 +- docs/reference/traits/has_field.md | 4 +- docs/reference/traits/has_fields.md | 4 +- docs/reference/traits/is_provider_for.md | 4 +- docs/reference/traits/map_type.md | 4 +- docs/reference/traits/monad.md | 4 +- docs/reference/traits/optional_fields.md | 4 +- docs/reference/traits/product_ops.md | 4 +- docs/reference/traits/static_format.md | 4 +- docs/reference/types/field.md | 4 +- docs/reference/types/index.md | 4 +- docs/reference/types/life.md | 4 +- docs/reference/types/mref.md | 4 +- docs/reference/types/type_level_spines.md | 4 +- 97 files changed, 991 insertions(+), 165 deletions(-) create mode 100644 docs/concepts/_category_.json create mode 100644 docs/concepts/abstract-types.md create mode 100644 docs/concepts/aggregate-providers.md create mode 100644 docs/concepts/check-traits.md create mode 100644 docs/concepts/coherence.md create mode 100644 docs/concepts/consumer-and-provider-traits.md create mode 100644 docs/concepts/dispatching.md create mode 100644 docs/concepts/extensible-records.md create mode 100644 docs/concepts/extensible-variants.md create mode 100644 docs/concepts/handlers.md create mode 100644 docs/concepts/higher-order-providers.md create mode 100644 docs/concepts/impl-side-dependencies.md create mode 100644 docs/concepts/implicit-arguments.md create mode 100644 docs/concepts/index.md create mode 100644 docs/concepts/modular-error-handling.md create mode 100644 docs/concepts/modularity-hierarchy.md create mode 100644 docs/concepts/monadic-handlers.md create mode 100644 docs/concepts/namespaces.md create mode 100644 docs/concepts/send-bounds.md create mode 100644 docs/concepts/type-level-dsls.md diff --git a/docs/ai/_category_.json b/docs/ai/_category_.json index df9a1b38..4aab1dbb 100644 --- a/docs/ai/_category_.json +++ b/docs/ai/_category_.json @@ -1,6 +1,6 @@ { "label": "AI Assisted Development", - "position": 4, + "position": 6, "link": { "type": "generated-index" } diff --git a/docs/concepts/_category_.json b/docs/concepts/_category_.json new file mode 100644 index 00000000..3aa120fc --- /dev/null +++ b/docs/concepts/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Concepts", + "position": 4, + "link": { + "type": "doc", + "id": "concepts/index" + } +} diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md new file mode 100644 index 00000000..bf8c323e --- /dev/null +++ b/docs/concepts/abstract-types.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Abstract types' +sidebar_position: 5 +--- + +# Abstract types + +Naming a type in generic code — an error type, a scalar, a runtime — and letting each context decide +what it actually is. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md new file mode 100644 index 00000000..7232010f --- /dev/null +++ b/docs/concepts/aggregate-providers.md @@ -0,0 +1,18 @@ +--- +sidebar_label: 'Aggregate providers' +sidebar_position: 8 +--- + +# Aggregate providers + +Bundling a group of wiring choices into one reusable provider that other contexts adopt as a unit. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md new file mode 100644 index 00000000..7bd35a2d --- /dev/null +++ b/docs/concepts/check-traits.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Checking your wiring' +sidebar_position: 6 +--- + +# Checking your wiring + +Why a wiring mistake still compiles, and how a compile-time assertion turns the resulting error into +one that names the real cause. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md new file mode 100644 index 00000000..499f75d8 --- /dev/null +++ b/docs/concepts/coherence.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Bypassing coherence' +sidebar_position: 1 +--- + +# Bypassing coherence + +Rust allows one implementation of a trait per type. Why that rule exists, what it costs, and how +CGP writes many implementations and lets each context pick the one it wants. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md new file mode 100644 index 00000000..bf84946e --- /dev/null +++ b/docs/concepts/consumer-and-provider-traits.md @@ -0,0 +1,273 @@ +--- +sidebar_label: 'Consumer and provider traits' +sidebar_position: 2 +--- + +# Consumer and provider traits + +One trait definition in CGP becomes two traits: a **consumer trait** that callers use, and a +**provider trait** that implementations target. This page explains why the split exists, what each +half is for, and how a plain method call finds its way from one to the other. It ends with what the +arrangement costs, which is the part worth reading before adopting it. + +## What an ordinary Rust trait does, and where it stops + +A Rust trait joins two jobs that are usually the same job. The type that implements `Display` is the +type callers format, and that identity is what lets the compiler resolve a `where T: Display` bound +without anyone naming an implementation — it looks the type up, finds the one implementation, and is +done. Almost all Rust code wants exactly this, which is why the language is built around it. + +The consequence is that a trait offers one implementation per type, and that limit shows up sooner +than it sounds. Consider an application that sends email, with a test harness that must not: + +```rust +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + +pub struct App { + pub smtp_server: String, +} + +pub struct TestApp { + pub sent_emails: RefCell>, +} + +impl CanSendEmail for App { + fn send_email(&self, to: &str, body: &str) { + // open a connection to self.smtp_server and send + } +} + +impl CanSendEmail for TestApp { + fn send_email(&self, to: &str, body: &str) { + self.sent_emails.borrow_mut().push(format!("{to}: {body}")); + } +} +``` + +This compiles, and it is worth noticing that it already does what you want: two application types, +two behaviours, no CGP anywhere. `App` and `TestApp` here are types that stand for a whole +application — their job is to carry the choices and the data the program needs, not to be operated +on. That shape is legal Rust and nothing about it is unusual. + +What fails is *sharing*. As soon as you try to lift a body out into something reusable — so that a +second application could adopt the SMTP behaviour without copying it — the two implementations +collide: + +```rust +impl CanSendEmail for T { /* over SMTP */ } +impl CanSendEmail for T { /* record it */ } // error[E0119] +``` + +The compiler rejects the second impl because a type could satisfy both bounds, and it has no +principled way to choose. So the arrangement above survives, but every application must hand-write +every body, and nothing can be factored out. It is available and unrewarding, which is why almost +nobody builds on it — and it is exactly the gap CGP fills. + +## Splitting one trait in two + +CGP's move is to stop implementing the trait for the type the capability is about. A single +definition produces two traits with the two jobs pulled apart: + +- The **consumer trait** is the caller's view. It keeps the original name, the original `self` + receiver, and the original signatures, so a caller writes `app.send_email(..)` as before. +- The **provider trait** is the implementer's view. It is the same interface with `Self` moved out + into an explicit leading `Context` type parameter, and every `self` rewritten to `context`. + +For the example above, the pair is: + +```rust +// what callers use +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + +// what implementations target +pub trait EmailSender { + fn send_email(context: &Context, to: &str, body: &str); +} +``` + +Moving `Self` is the whole trick. An implementation no longer says "this type sends email"; it says +"this *named implementation* sends email, for any context". The name is a small type the +implementing crate declares for the purpose: + +```rust +impl EmailSender for SendViaSmtp { /* ... */ } +impl EmailSender for RecordEmails { /* ... */ } +``` + +Both compile, and any number more would. There is no overlap, because each `impl` has a different +`Self`. There is no orphan-rule problem either, because that `Self` is a type the crate writing the +impl owns — which means a crate can add behaviour for a type it did not define. Neither rule was +repealed; the implementations simply stopped being the kind of thing the rules are about. The wider +argument for why that is a fair trade is [Bypassing coherence](./coherence.md). + +## A provider is a name, not a value + +A **provider** is one of those named implementations — `SendViaSmtp`, `RecordEmails`. It is a +zero-sized type that exists only to be named. Nothing constructs it, nothing stores it, and there is +no field in it to read; at runtime it does not exist at all. + +That has one consequence worth fixing in mind before reading any provider code. Inside a provider, +`self` and `Self` refer to the **context** — the application type the method is running against — +never to the provider. When you write a provider with +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl), the macro keeps `self` in the source and rewrites +it to the context underneath, precisely because the context is the only value that exists when the +method runs. + +## How a call finds its provider + +Two pieces connect the halves: a table on the context that names its choice, and a pair of generated +implementations that follow it. + +The table is what a context writes. It maps each component to the provider that should implement it, +and it is the one place a choice is recorded: + +```rust +delegate_components! { App { EmailSenderComponent: SendViaSmtp } } +delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } +``` + +`EmailSenderComponent` is a marker type generated alongside the two traits, used purely as the key. +The table itself is a set of trait implementations rather than a runtime structure — the lookup is +performed by the compiler, and nothing survives into the program. + +The two generated implementations then chain through it. The first says that any context which +implements the *provider* trait for itself gets the *consumer* trait, which is what makes +`app.send_email(..)` a legal call: + +```rust +impl CanSendEmail for Context +where + Context: EmailSender, +{ + fn send_email(&self, to: &str, body: &str) { + Context::send_email(self, to, body) + } +} +``` + +The second says that anything with a table entry for this component inherits the provider trait from +whatever the entry names: + +```rust +impl EmailSender for Provider +where + Provider: DelegateComponent, + Provider::Delegate: EmailSender, +{ + fn send_email(context: &Context, to: &str, body: &str) { + Provider::Delegate::send_email(context, to, body) + } +} +``` + +Put together, `app.send_email("a@b.c", "hi")` resolves in three steps. `App` implements +`CanSendEmail` because it implements `EmailSender` for itself; it implements `EmailSender` +because its table maps `EmailSenderComponent` to `SendViaSmtp`; and `SendViaSmtp` implements +`EmailSender` directly. Every step is trait resolution, so the finished call is a direct call to +`SendViaSmtp::send_email` — no lookup happens while the program runs, and a provider no context uses +never reaches the binary. + +The real generated code carries one more piece: the provider trait has +[`IsProviderFor`](/docs/reference/traits/is_provider_for) as a supertrait, and every provider +implements it under the same bounds it needs. That marker exists solely so that when a context is +missing something a provider requires, the compiler can name the missing requirement instead of +reporting that the provider trait is not implemented. It is never written by hand. + +## Writing it + +In practice you write neither trait by hand. [`#[cgp_component]`](/docs/reference/macros/cgp_component) +generates the pair, the marker, and the two blanket implementations from one trait definition, and +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) lets a provider be written in the consumer trait's +shape — keeping `self` and the original signatures — and rewrites it into the provider form: + +```rust +use cgp::prelude::*; + +#[cgp_component(EmailSender)] +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + +#[cgp_impl(new SendViaSmtp)] +impl EmailSender { + fn send_email(&self, #[implicit] smtp_server: &str, to: &str, body: &str) { + // open a connection to `smtp_server` and send the message + } +} + +#[cgp_impl(new RecordEmails)] +impl EmailSender { + fn send_email(&self, #[implicit] sent_emails: &RefCell>, to: &str, body: &str) { + sent_emails.borrow_mut().push(format!("{to}: {body}")); + } +} + +#[derive(HasField)] +pub struct App { + pub smtp_server: String, +} + +#[derive(HasField)] +pub struct TestApp { + pub sent_emails: RefCell>, +} + +delegate_components! { App { EmailSenderComponent: SendViaSmtp } } +delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } +``` + +Two details of that listing are worth pointing out. The +[`#[implicit]`](/docs/reference/attributes/implicit) arguments are how each provider reaches into its +context: they read a same-named field and disappear from the method's public signature, so +`app.send_email(to, body)` still takes two arguments. And the two providers depend on *different* +fields — `SendViaSmtp` needs an `smtp_server`, `RecordEmails` needs somewhere to record — with +neither requirement appearing in `CanSendEmail`. That is +[impl-side dependency injection](./impl-side-dependencies.md), and it is what stops a context paying +for the needs of implementations it did not choose. + +A consumer trait remains an ordinary Rust trait throughout. Nothing stops a context from implementing +it directly, exactly as in the very first listing on this page, and skipping providers and wiring +entirely. The split is something you opt into for the capabilities that need more than one +implementation, not a replacement for how traits already work. + +## What it costs + +**It is more machinery than a plain trait.** One capability becomes two traits, a marker type, and a +line of wiring per context. For a capability with a single implementation, that is pure overhead — +write a plain trait, or reach for [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), which builds a +capability from a function with no component and no wiring at all. + +**Wiring is checked lazily.** A table with a missing entry, or one naming a provider whose own +requirements the context cannot meet, still compiles; the failure surfaces later, wherever the +capability is finally used, and the error can be long. This is real, and it has an answer: +[`check_components!`](/docs/reference/macros/check_components) forces the check at the wiring line so +the error names the actual gap, and `cargo cgp check` reshapes the recognized failures to lead with +the root cause. Neither makes the raw diagnostics pleasant — see +[Checking your wiring](./check-traits.md) for what to expect. + +**There is a hop between the call and the code that runs.** `app.send_email(..)` no longer points at +one body you can jump to. Unlike runtime dispatch the indirection is fully resolved at compile time +and never ambiguous, and the wiring table is a single greppable place naming exactly one provider per +component — but it is a hop, and a reader unfamiliar with the codebase has to follow it. + +## Where to go next + +[Bypassing coherence](./coherence.md) is the argument underneath this page: why Rust's rule exists, +why it is correct, and why scoping it per context is a fair trade rather than a loophole. +[Impl-side dependencies](./impl-side-dependencies.md) develops the other half of what makes providers +reusable — how an implementation states what it needs without the interface carrying it. + +To write this rather than read about it, the [Area calculation tutorial](/docs/tutorials/area-calculation/) +builds the same split up from plain functions, and calls providers by name before any wiring exists. +For the exact syntax and the full generated code, the reference pages for +[`#[cgp_component]`](/docs/reference/macros/cgp_component), +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl), and +[`delegate_components!`](/docs/reference/macros/delegate_components) are the complete account. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md new file mode 100644 index 00000000..df3699ae --- /dev/null +++ b/docs/concepts/dispatching.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Dispatching' +sidebar_position: 15 +--- + +# Dispatching + +Routing each field of a record, or the current variant of an enum, to the handler responsible for +it. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md new file mode 100644 index 00000000..c3bd7de6 --- /dev/null +++ b/docs/concepts/extensible-records.md @@ -0,0 +1,18 @@ +--- +sidebar_label: 'Extensible records' +sidebar_position: 13 +--- + +# Extensible records + +Building and reading a struct through the names of its fields, without naming the struct. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md new file mode 100644 index 00000000..9a5b46b8 --- /dev/null +++ b/docs/concepts/extensible-variants.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Extensible variants' +sidebar_position: 14 +--- + +# Extensible variants + +Constructing and matching an enum through the names of its variants, with exhaustiveness still +checked by the compiler. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md new file mode 100644 index 00000000..0964f97a --- /dev/null +++ b/docs/concepts/handlers.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Handlers' +sidebar_position: 11 +--- + +# Handlers + +The family of computation components, and the three axes — synchronous or async, fallible or not, +taking an input or not — that tell them apart. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md new file mode 100644 index 00000000..181a9ab9 --- /dev/null +++ b/docs/concepts/higher-order-providers.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Higher-order providers' +sidebar_position: 7 +--- + +# Higher-order providers + +Providers parameterized by other providers, so one implementation can be expressed in terms of +another. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md new file mode 100644 index 00000000..99c52e69 --- /dev/null +++ b/docs/concepts/impl-side-dependencies.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Impl-side dependencies' +sidebar_position: 3 +--- + +# Impl-side dependencies + +Declaring what an implementation needs in the implementation itself, so the requirement never +reaches the callers of the interface. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md new file mode 100644 index 00000000..f8bb425e --- /dev/null +++ b/docs/concepts/implicit-arguments.md @@ -0,0 +1,18 @@ +--- +sidebar_label: 'Implicit arguments' +sidebar_position: 4 +--- + +# Implicit arguments + +Writing a provider as an ordinary function whose arguments are filled from fields of the context. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/index.md b/docs/concepts/index.md new file mode 100644 index 00000000..3d6395b7 --- /dev/null +++ b/docs/concepts/index.md @@ -0,0 +1,70 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Concepts + +This section explains the ideas behind CGP: why it is built the way it is, what each of its ideas +actually does, and where the boundaries of each one lie. It is written to be read away from a +keyboard — there is nothing here to follow along with, and nothing to install first. + +It sits between the other two halves of the documentation. The [tutorials](/docs/tutorials/hello) +teach by building something, so they show a construct at the moment it is needed and move on. The +[reference](/docs/reference/) explains one construct completely, for a reader who already knows the +name of the thing they want. A concept page answers the question neither of those is shaped for: +*why does CGP work this way, and when is it the right thing to reach for?* Each page names the +constructs it involves and links to the reference for their exact syntax, rather than repeating it. + +## Where to start + +**Read [Bypassing coherence](./coherence.md) first if you want to know why CGP exists.** It explains +the rule in Rust's trait system that allows only one implementation per type, why that rule is +correct, what it costs in practice, and the move CGP makes to work around it without giving up what +the rule buys. Almost everything else here is downstream of it. + +**Read [Consumer and provider traits](./consumer-and-provider-traits.md) first if you want to know +how CGP works.** It covers the trait split at the centre of the design — one trait you call, another +you implement — and how a call finds its way from one to the other. + +**Read [How much CGP to use](./modularity-hierarchy.md) first if you are deciding whether to adopt +it.** It lays out the range from an ordinary Rust trait to fully wired components as a ladder, and +argues for climbing no higher than a problem requires. + +## The ideas, grouped + +The pages below are ordered in the sidebar roughly as a reader meets them, and grouped here by what +they are about. + +**The foundation** is the coherence problem and CGP's answer to it. +[Bypassing coherence](./coherence.md) states the problem; +[Consumer and provider traits](./consumer-and-provider-traits.md) is the mechanism that solves it. + +**Dependency injection** is how an implementation gets what it needs without the interface carrying +it. [Impl-side dependencies](./impl-side-dependencies.md) is the general idea; +[Implicit arguments](./implicit-arguments.md) is how it looks for a value read from a field, and +[Abstract types](./abstract-types.md) is how it looks for a type the context chooses. + +**Composition and scale** cover what happens as a program grows. +[Checking your wiring](./check-traits.md) explains why a wiring mistake compiles and how to make it +fail loudly instead. [Higher-order providers](./higher-order-providers.md) build one implementation +out of another, [Aggregate providers](./aggregate-providers.md) bundle a group of choices into one, +and [Namespaces](./namespaces.md) keep a large wiring table readable. + +**Applied ideas** are the places CGP's machinery is put to a specific use. +[Modular error handling](./modular-error-handling.md) separates the error type from how errors are +built. [Handlers](./handlers.md) and [Monadic handlers](./monadic-handlers.md) model computation as +components that compose. [Extensible records](./extensible-records.md), +[Extensible variants](./extensible-variants.md), and [Dispatching](./dispatching.md) let generic code +work over the shape of a struct or an enum. [Type-level DSLs](./type-level-dsls.md) push that as far +as it goes, turning a small language into types the compiler interprets. + +**Two pages stand slightly apart.** [Recovering `Send` bounds](./send-bounds.md) is a workaround for a +gap in stable Rust rather than a CGP idea, and it matters as soon as an async CGP task is spawned. +[How much CGP to use](./modularity-hierarchy.md) is a decision guide rather than an explanation, and +it is the page to reach for when the question is how far to go. + +## This section is still being written + +Most pages here are placeholders at present, and each one says so. The list of ideas is complete, so +nothing is missing from this index even where the page behind it is not yet filled in. diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md new file mode 100644 index 00000000..85236214 --- /dev/null +++ b/docs/concepts/modular-error-handling.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Modular error handling' +sidebar_position: 10 +--- + +# Modular error handling + +The error type, how a foreign error becomes it, and what detail it carries: three choices a context +makes independently of the code that fails. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md new file mode 100644 index 00000000..c2963e6e --- /dev/null +++ b/docs/concepts/modularity-hierarchy.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'How much CGP to use' +sidebar_position: 18 +--- + +# How much CGP to use + +The ladder from a plain trait to fully wired components, and how to settle at the lowest rung that +solves the problem in front of you. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md new file mode 100644 index 00000000..12423dc1 --- /dev/null +++ b/docs/concepts/monadic-handlers.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Monadic handlers' +sidebar_position: 12 +--- + +# Monadic handlers + +Chaining handlers into a pipeline that stops at the first step producing a result the chain should +return. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md new file mode 100644 index 00000000..8fca5fe4 --- /dev/null +++ b/docs/concepts/namespaces.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Namespaces' +sidebar_position: 9 +--- + +# Namespaces + +Reusable, inheritable wiring tables that keep a context's own table short as the number of +components grows. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md new file mode 100644 index 00000000..3cabe9e8 --- /dev/null +++ b/docs/concepts/send-bounds.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Recovering Send bounds' +sidebar_position: 17 +--- + +# Recovering `Send` bounds + +Restoring the guarantee an async trait method drops, so the future it returns can be spawned on a +multi-threaded runtime. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md new file mode 100644 index 00000000..eee6b0d0 --- /dev/null +++ b/docs/concepts/type-level-dsls.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 'Type-level DSLs' +sidebar_position: 16 +--- + +# Type-level DSLs + +Encoding a small language as Rust types and interpreting it during compilation, with no interpreter +left at runtime. + +:::info + +### Not written yet + +This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best +place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it +rests on. + +::: diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 471f6793..47ed1929 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -6,7 +6,9 @@ sidebar_label: '#[derive_delegate]' Generate the `UseDelegate` dispatcher impl for a component. Superseded by the `open` statement. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 76409d23..5e414eda 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -6,7 +6,9 @@ sidebar_label: '#[extend]' Add supertrait bounds to a generated trait. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 08cb341a..4c6a1b28 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -6,7 +6,9 @@ sidebar_label: '#[extend_where]' Add `where` predicates to a generated trait's own definition. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index e825bfbf..de0866ab 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -6,7 +6,9 @@ sidebar_label: '#[implicit]' Source a function argument from a same-named field on the context. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 3e7427cc..c65d2c85 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -6,7 +6,9 @@ sidebar_label: '#[use_provider]' Complete an inner provider's bound in a higher-order provider. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 7ddd4701..b19fba5b 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -6,7 +6,9 @@ sidebar_label: '#[use_type]' Import an abstract associated type and write it as a bare name. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 961cda61..21f789e7 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -6,7 +6,9 @@ sidebar_label: '#[uses]' Import the capabilities a provider depends on, reading like a `use` statement. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md index 7a3d4cdf..d08431cc 100644 --- a/docs/reference/components/can_raise_error.md +++ b/docs/reference/components/can_raise_error.md @@ -6,7 +6,9 @@ sidebar_label: 'CanRaiseError & CanWrapError' Raise a source error into the context's error type, and attach detail to it. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/computer.md b/docs/reference/components/computer.md index 39040065..b8852ad4 100644 --- a/docs/reference/components/computer.md +++ b/docs/reference/components/computer.md @@ -6,7 +6,9 @@ sidebar_label: 'Computer & CanCompute' The synchronous, infallible transform, with its by-reference and async variants. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/handler.md b/docs/reference/components/handler.md index 65bf1f04..2cda0010 100644 --- a/docs/reference/components/handler.md +++ b/docs/reference/components/handler.md @@ -6,7 +6,9 @@ sidebar_label: 'Handler & CanHandle' The general async, fallible, error-aware computation component. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index b362128c..687a317a 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -6,7 +6,9 @@ sidebar_label: 'HasErrorType' The abstract error type every fallible CGP capability names. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index c60fe30e..3f40f140 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -6,7 +6,9 @@ sidebar_label: 'HasRuntime & HasRuntimeType' The abstract runtime type and the accessor that reaches it. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index 88142c95..6781aea2 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -6,7 +6,9 @@ sidebar_label: 'HasType & TypeProvider' CGP's built-in abstract-type component. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/producer.md b/docs/reference/components/producer.md index b977b20e..aa18f026 100644 --- a/docs/reference/components/producer.md +++ b/docs/reference/components/producer.md @@ -6,7 +6,9 @@ sidebar_label: 'Producer & CanProduce' The input-free production component. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index f4875489..9464d03d 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -6,7 +6,9 @@ sidebar_label: 'CanRun & CanSendRun' The task-running components. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/components/try_computer.md b/docs/reference/components/try_computer.md index 20fc90cc..f2560218 100644 --- a/docs/reference/components/try_computer.md +++ b/docs/reference/components/try_computer.md @@ -6,7 +6,9 @@ sidebar_label: 'TryComputer & CanTryCompute' The fallible computer. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 18b2b79f..8d745db2 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -6,7 +6,9 @@ sidebar_label: '#[derive(BuildField)]' Builder support for a record. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 307a3dbf..1831459a 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -6,7 +6,9 @@ sidebar_label: '#[derive(CgpData)], CgpRecord & CgpVariant' The extensible-data derives: the umbrella and its struct and enum faces. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index a36c1882..a4c5596e 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -6,7 +6,9 @@ sidebar_label: '#[derive(ExtractField)]' Extractor support for a variant. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 6124b3e5..41addb49 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -6,7 +6,9 @@ sidebar_label: '#[derive(FromVariant)]' Generic construction of an enum from one of its named variants. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index df0cc58e..9c48d108 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -6,7 +6,9 @@ sidebar_label: '#[derive(HasField)]' Per-field accessors keyed by a type-level tag. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 50416de6..5d0ef368 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -6,7 +6,9 @@ sidebar_label: '#[derive(HasFields)]' The whole-struct or whole-enum field-list view. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/errors.md b/docs/reference/errors.md index bd274782..6e1f4bd3 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -7,7 +7,9 @@ sidebar_position: 90 The errors CGP produces after macro expansion, grouped by what went wrong: a dependency a provider needs and the context does not supply, a wiring table that does not resolve, and a shorthand that lowered into something the compiler rejects. -:::info Not written yet +:::info + +### Not written yet This page is still being written. In the meantime, run [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) in place of `cargo check`: it un-hides the root cause the default trait solver suppresses and leads with it, for the error classes it recognizes. diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index b3a7a26a..396b63b6 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -6,7 +6,9 @@ sidebar_label: '#[async_trait]' Rewrite a trait's `async fn` declarations into the lint-clean `-> impl Future` form CGP's async methods use. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index a7b27b23..e27f62c9 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -6,7 +6,9 @@ sidebar_label: '#[blanket_trait]' Generate a blanket impl from a trait with default methods and supertrait dependencies. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 473e936f..c3b39c53 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -6,7 +6,9 @@ sidebar_label: '#[cgp_auto_dispatch]' Generate a handler that dispatches over an extensible-data input from a per-type trait. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 3760dc7a..36409ee6 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -6,7 +6,9 @@ sidebar_label: '#[cgp_auto_getter]' Define a getter as a blanket impl over `HasField`, keyed by the method name. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index b7197915..84dde12e 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -36,49 +36,6 @@ The macro also emits a **component name** — a marker type such as `AreaCalcula the key wiring uses. You will see it in every `delegate_components!` entry and in most compiler errors, so it is worth recognizing even though you never write its definition. -## When to reach for it, and when not - -Reach for `#[cgp_component]` when a capability genuinely needs **more than one implementation, and the -choice belongs to the type using it.** That is the case it exists for, and its machinery is not free: -a component is a trait, a second trait, a marker type, and a line of wiring per type. - -Prefer something simpler when you can. - -- **One implementation, ever.** Use [`#[cgp_fn]`](./cgp_fn.md) instead. It builds the capability - straight from a function, needs no wiring at all, and keeps working unchanged if a second - implementation ever arrives — so it is the right starting point rather than a lesser one. -- **One implementation per type, chosen globally.** That is what a plain Rust trait already does well. - Reach for a component when two *different* applications must make different choices for the same - type, or when the implementations must overlap in a way the compiler rejects. -- **A closed set of variants with fixed operations.** An `enum` and a `match` are clearer than any - machinery. - -There is also a finer line worth knowing: a capability may genuinely need several implementations -while each individual implementation serves exactly one type. In that case you can implement the -consumer trait directly on each concrete type, as you would any Rust trait, and skip providers -entirely. Named providers earn their place once a second type wants the *same* implementation, or once -an implementation should compose with a wrapper. - -### How many items should a component have? - -A component trait is an ordinary trait. It takes as many methods, associated types, and associated -consts as any other, and every one of them is reproduced on the provider trait — CGP's own -[`CanCompute`](../components/computer.md) declares an associated `Output` beside its method. There is -no cap. - -What to group is a judgement rather than a rule, and the useful question is: **everything in one -component is answered by one provider choice.** Items a single choice settles belong together — a -method and the associated type it returns, or several field reads one getter provider answers by name. -Items that separate choices settle are better apart, because grouping them costs reuse: every provider -then carries the union of the dependencies of all the methods, a wrapper must forward the methods it -has no opinion about, and a type that needs only part of the surface must still supply the rest. - -The usual sign of a component that has grown past one decision is a consumer trait named after a noun -rather than a verb — `Shape` carrying `area`, `perimeter`, `scale`, and `rotate`. It compiles, but very -little of it is reusable. A good check before committing: could a second type plausibly reuse one of -this trait's providers *whole*? If not, implement the trait directly on the concrete type and skip the -machinery. - ## Using it Apply the attribute to a trait definition and give it the provider trait's name. The simplest form is @@ -187,9 +144,54 @@ table, which maps `AreaCalculatorComponent` to `RectangleArea`, and `RectangleAr fields to compute the result. Swapping the provider in that one wiring line changes what `rect.area()` does, and nothing else in the program changes. +## When to reach for it, and when not + +Reach for `#[cgp_component]` when a capability genuinely needs **more than one implementation, and the +choice belongs to the type using it.** That is the case it exists for, and its machinery is not free: +a component is a trait, a second trait, a marker type, and a line of wiring per type. + +Prefer something simpler when you can. + +- **One implementation, ever.** Use [`#[cgp_fn]`](./cgp_fn.md) instead. It builds the capability + straight from a function, needs no wiring at all, and keeps working unchanged if a second + implementation ever arrives — so it is the right starting point rather than a lesser one. +- **One implementation per type, chosen globally.** That is what a plain Rust trait already does well. + Reach for a component when two *different* applications must make different choices for the same + type, or when the implementations must overlap in a way the compiler rejects. +- **A closed set of variants with fixed operations.** An `enum` and a `match` are clearer than any + machinery. + +There is also a finer line worth knowing: a capability may genuinely need several implementations +while each individual implementation serves exactly one type. In that case you can implement the +consumer trait directly on each concrete type, as you would any Rust trait, and skip providers +entirely. Named providers earn their place once a second type wants the *same* implementation, or once +an implementation should compose with a wrapper. + +### How many items should a component have? + +A component trait is an ordinary trait. It takes as many methods, associated types, and associated +consts as any other, and every one of them is reproduced on the provider trait — CGP's own +[`CanCompute`](../components/computer.md) declares an associated `Output` beside its method. There is +no cap. + +What to group is a judgement rather than a rule, and the useful question is: **everything in one +component is answered by one provider choice.** Items a single choice settles belong together — a +method and the associated type it returns, or several field reads one getter provider answers by name. +Items that separate choices settle are better apart, because grouping them costs reuse: every provider +then carries the union of the dependencies of all the methods, a wrapper must forward the methods it +has no opinion about, and a type that needs only part of the surface must still supply the rest. + +The usual sign of a component that has grown past one decision is a consumer trait named after a noun +rather than a verb — `Shape` carrying `area`, `perimeter`, `scale`, and `rotate`. It compiles, but very +little of it is reusable. A good check before committing: could a second type plausibly reuse one of +this trait's providers *whole*? If not, implement the trait directly on the concrete type and skip the +machinery. + ## Under the hood -:::note Advanced +:::note + +### Advanced This section shows the code the macro generates. You do not need it to use `#[cgp_component]`, but CGP's constructs are macros, and reading what one produces is the fastest way to understand a compiler diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index cc64bf6a..80647a6a 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -6,7 +6,9 @@ sidebar_label: '#[cgp_computer]' Define a `Computer` provider from a plain function. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index dd9469f4..0d0e7dc0 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -6,7 +6,9 @@ sidebar_label: '#[cgp_fn]' Define a single-implementation capability as a blanket-impl trait, straight from a function. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index ef405259..3d11fe6f 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -6,7 +6,9 @@ sidebar_label: '#[cgp_getter]' Define a getter as a full component, so the field it reads is chosen by wiring rather than by its name. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 5411f844..00a51d2e 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -54,29 +54,6 @@ never constructed, and there is nothing in it to read. The macro rewrites `self` and `Self` to the context type precisely because the context is the only thing that exists when the method runs. -## When to reach for it, and when not - -**Write providers with `#[cgp_impl]`.** It is the recommended form, and the two constructs that could -replace it are narrower than they look — one is the raw shape it desugars to, the other is for -capabilities that need no provider at all. - -Prefer the unqualified header `impl AreaCalculator`, with no `for Context`, and let the macro insert -the context parameter. That is what makes a provider read like an ordinary trait impl. Name the context -explicitly — `impl AreaCalculator for Context` — only when you actually need to say something -about it that the sugar cannot express, such as a lifetime or a higher-ranked bound. - -Reach for something else in three cases. - -- **You need the inside-out shape itself.** [`#[cgp_provider]`](./cgp_provider.md) and - `#[cgp_new_provider]` are the raw forms. Write one when you must state a bound the sugar cannot, or - when implementing a provider trait on a concrete type rather than a generic one. Otherwise, read - them and write `#[cgp_impl]`. -- **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain - function with no component, no provider, and no wiring. -- **You want to implement the consumer trait directly on one concrete type.** Use the - [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly) below, which keeps the - companion attributes while emitting an ordinary impl. - ## Using it Apply the attribute to an `impl` block. Its argument names the provider, and has three parts of which @@ -193,9 +170,34 @@ fn print_area(rect: &Rectangle) { } ``` +## When to reach for it, and when not + +**Write providers with `#[cgp_impl]`.** It is the recommended form, and the two constructs that could +replace it are narrower than they look — one is the raw shape it desugars to, the other is for +capabilities that need no provider at all. + +Prefer the unqualified header `impl AreaCalculator`, with no `for Context`, and let the macro insert +the context parameter. That is what makes a provider read like an ordinary trait impl. Name the context +explicitly — `impl AreaCalculator for Context` — only when you actually need to say something +about it that the sugar cannot express, such as a lifetime or a higher-ranked bound. + +Reach for something else in three cases. + +- **You need the inside-out shape itself.** [`#[cgp_provider]`](./cgp_provider.md) and + `#[cgp_new_provider]` are the raw forms. Write one when you must state a bound the sugar cannot, or + when implementing a provider trait on a concrete type rather than a generic one. Otherwise, read + them and write `#[cgp_impl]`. +- **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain + function with no component, no provider, and no wiring. +- **You want to implement the consumer trait directly on one concrete type.** Use the + [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which keeps the companion + attributes while emitting an ordinary impl. + ## Under the hood -:::note Advanced +:::note + +### Advanced This section shows what the macro generates. You do not need it to write a provider, but the rewrite is worth seeing once — most confusing errors in a provider body are explained by it. `cargo cgp expand` diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 6bcfd843..60f91973 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -6,7 +6,9 @@ sidebar_label: 'cgp_namespace!' Define a reusable, inheritable wiring table that many contexts can join. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 66a111fd..aa41022c 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -6,7 +6,9 @@ sidebar_label: '#[cgp_producer]' Define a `Producer` provider from an input-free function. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 04b141c3..82985e51 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -6,7 +6,9 @@ sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' Implement a provider trait directly, in the inside-out shape the sugar desugars to — with or without declaring the provider struct. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 92ff925e..c1b9a69b 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -6,7 +6,9 @@ sidebar_label: '#[cgp_type]' Define an abstract-type component, whose concrete type each context chooses for itself. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index c0787027..421ca32a 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -6,7 +6,9 @@ sidebar_label: 'check_components!' Assert at compile time that a context can actually use each component it wires. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 438c0f3d..25537997 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -6,7 +6,9 @@ sidebar_label: 'delegate_and_check_components!' Wire a context and check that wiring in one macro. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 003e55ef..5ff0623e 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -39,27 +39,6 @@ A macro is worth having here because each entry expands to two impls rather than dependencies back through the table — which is what makes a missing transitive requirement produce a usable error instead of a dead end. -## When to reach for it, and when not - -Use `delegate_components!` whenever a context needs to choose providers, which is any time you use -[`#[cgp_component]`](./cgp_component.md) at all. The real decision is not whether to wire but **how to -check the wiring**, because CGP's wiring is *lazy*: a table with a missing or wrong entry still -compiles, and the failure only surfaces later, where the capability is used. - -- **Pair it with [`check_components!`](./check_components.md)** for anything beyond simple wiring. A - separate check gives you full control over what is asserted — concrete parameters for generic keys, - per-provider layers, and opened or namespaced wiring — which is why larger codebases keep the two - macros apart. -- **Use [`delegate_and_check_components!`](./delegate_and_check_components.md)** when you are getting - started or the wiring is plain `Component: Provider` entries. It fuses the two so the check cannot be - forgotten. -- **Use plain `delegate_components!` with no check** for an **aggregate provider** — the - `new`-keyword form below. That target is a provider other contexts delegate to rather than a context - in its own right, so the fused macro's check would fail spuriously on it. - -The one thing not to do is leave a context's wiring unchecked. Which macro you use to check it scales -with how complicated the wiring is; that it is checked somehow does not. - ## Using it The macro takes a target type and a brace-delimited list of `Key: Value` entries. @@ -151,7 +130,9 @@ generates. It is a lightweight special case of the full [namespace](./cgp_namesp to a context wiring its own components directly, and it does not combine with a joined namespace where the component carries a `#[prefix(...)]`. -:::info Legacy — read, don't write +:::info + +### Legacy — read, don't write Older code dispatches the same way by nesting a table inside a [`UseDelegate`](../providers/use_delegate.md) value: @@ -233,9 +214,33 @@ delegate_components! { } ``` +## When to reach for it, and when not + +Use `delegate_components!` whenever a context needs to choose providers, which is any time you use +[`#[cgp_component]`](./cgp_component.md) at all. The real decision is not whether to wire but **how to +check the wiring**, because CGP's wiring is *lazy*: a table with a missing or wrong entry still +compiles, and the failure only surfaces later, where the capability is used. + +- **Pair it with [`check_components!`](./check_components.md)** for anything beyond simple wiring. A + separate check gives you full control over what is asserted — concrete parameters for generic keys, + per-provider layers, and opened or namespaced wiring — which is why larger codebases keep the two + macros apart. +- **Use [`delegate_and_check_components!`](./delegate_and_check_components.md)** when you are getting + started or the wiring is plain `Component: Provider` entries. It fuses the two so the check cannot be + forgotten. +- **Use plain `delegate_components!` with no check** for an **aggregate provider** — the + [`new`-keyword form](#defining-the-target-at-the-same-time). That target is a provider other contexts + delegate to rather than a context in its own right, so the fused macro's check would fail spuriously + on it. + +The one thing not to do is leave a context's wiring unchecked. Which macro you use to check it scales +with how complicated the wiring is; that it is checked somehow does not. + ## Under the hood -:::note Advanced +:::note + +### Advanced This section shows the impls each entry expands to. You do not need them to wire a context, but they are what a wiring error names, so reading one makes those errors much easier to follow. diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index ec6a48f5..c4792110 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -6,7 +6,9 @@ sidebar_label: 'Path!' A type-level path, used by namespaces and redirected lookups. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 8bd24740..54aa6c74 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -6,7 +6,9 @@ sidebar_label: 'Product! & product!' A type-level list and its value-level counterpart. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 1633213b..17927a3f 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -6,7 +6,9 @@ sidebar_label: 'Sum!' A type-level sum, the dual of `Product!`. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 5c6c0c31..91bff976 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -6,7 +6,9 @@ sidebar_label: 'Symbol!' A type-level string, used as a field-name tag. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 6cc81be3..77172dd4 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -6,7 +6,9 @@ sidebar_label: 'ChainGetters' Compose getters to reach a field on a nested context. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/dispatch_combinators.md b/docs/reference/providers/dispatch_combinators.md index abee38df..efd1e902 100644 --- a/docs/reference/providers/dispatch_combinators.md +++ b/docs/reference/providers/dispatch_combinators.md @@ -6,7 +6,9 @@ sidebar_label: 'Dispatch combinators' The variant-matching and record-assembling providers that route extensible data to handlers. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/error_providers.md b/docs/reference/providers/error_providers.md index a96610fa..9fff4727 100644 --- a/docs/reference/providers/error_providers.md +++ b/docs/reference/providers/error_providers.md @@ -6,7 +6,9 @@ sidebar_label: 'Error providers' `RaiseFrom`, `ReturnError`, `DebugError`, and the other backends behind the error components. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/handler_combinators.md b/docs/reference/providers/handler_combinators.md index dba91b96..61000dec 100644 --- a/docs/reference/providers/handler_combinators.md +++ b/docs/reference/providers/handler_combinators.md @@ -6,7 +6,9 @@ sidebar_label: 'Handler combinators' `ComposeHandlers`, `PipeHandlers`, `ReturnInput`, and the `Promote*` lifts. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/monad_providers.md b/docs/reference/providers/monad_providers.md index 22478277..ac118a16 100644 --- a/docs/reference/providers/monad_providers.md +++ b/docs/reference/providers/monad_providers.md @@ -6,7 +6,9 @@ sidebar_label: 'Monad providers' `PipeMonadic`, `BindOk`, `BindErr`, and the identity/ok/err monad markers. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index c580257d..c68e4e91 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -6,7 +6,9 @@ sidebar_label: 'RedirectLookup' Re-route a component lookup along a type-level path. The mechanism behind namespaces and `open`. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index e8a07f05..12d0ec1d 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -6,7 +6,9 @@ sidebar_label: 'UseContext' Satisfy a provider trait by routing back through the context's own consumer impl. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index bd6983e7..9d53bf3f 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -6,7 +6,9 @@ sidebar_label: 'UseDefault' Select a component's default method bodies. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 6b544d90..8a0ef815 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -6,7 +6,9 @@ sidebar_label: 'UseDelegate' Dispatch on a generic parameter through an inner table. Superseded by the `open` statement. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index fe352b75..7e3d7264 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -6,7 +6,9 @@ sidebar_label: 'UseDelegatedType' Resolve an abstract type through a lookup table instead of fixing it. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index ed4a0d15..e0ad48d7 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -6,7 +6,9 @@ sidebar_label: 'UseField, UseFieldRef & UseFields' The field-backed getter providers, and how to choose between them. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index 8d0ecbf1..a8a27098 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -6,7 +6,9 @@ sidebar_label: 'UseType' Supply a concrete type for an abstract-type component. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 949bdc2d..87318084 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -6,7 +6,9 @@ sidebar_label: 'WithProvider' Adapt a foundational provider into a named component, with its `WithType`/`WithField`/`WithContext` aliases. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/can_use_component.md index 7ed51213..42690116 100644 --- a/docs/reference/traits/can_use_component.md +++ b/docs/reference/traits/can_use_component.md @@ -6,7 +6,9 @@ sidebar_label: 'CanUseComponent' The context-side check that a context both wires a component and satisfies its provider. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/cast.md b/docs/reference/traits/cast.md index c15560d5..6e73d892 100644 --- a/docs/reference/traits/cast.md +++ b/docs/reference/traits/cast.md @@ -6,7 +6,9 @@ sidebar_label: 'CanUpcast, CanDowncast & CanBuildFrom' Structural casts between records and between variants. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md index bbbf4fa2..7b86197e 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/default_namespace.md @@ -6,7 +6,9 @@ sidebar_label: 'DefaultNamespace & DefaultImpls' The namespace default-resolution traits, and `#[default_impl(...)]`. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/delegate_component.md index 2c694fb6..40c7b331 100644 --- a/docs/reference/traits/delegate_component.md +++ b/docs/reference/traits/delegate_component.md @@ -6,7 +6,9 @@ sidebar_label: 'DelegateComponent' The per-context type-level table mapping a component key to its provider. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md index d02dbf54..c3433f25 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/extract_field.md @@ -6,7 +6,9 @@ sidebar_label: 'ExtractField' The incremental-extractor trait family behind the extensible visitor pattern. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md index e26ab8a5..b256c0a5 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/from_variant.md @@ -6,7 +6,9 @@ sidebar_label: 'FromVariant' Generic construction of an enum from a named variant. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/has_builder.md b/docs/reference/traits/has_builder.md index ba8f3e42..22371e87 100644 --- a/docs/reference/traits/has_builder.md +++ b/docs/reference/traits/has_builder.md @@ -6,7 +6,9 @@ sidebar_label: 'HasBuilder' The incremental-builder trait family behind the extensible builder pattern. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/has_field.md index 900c705e..90b8e22b 100644 --- a/docs/reference/traits/has_field.md +++ b/docs/reference/traits/has_field.md @@ -6,7 +6,9 @@ sidebar_label: 'HasField' Tag-keyed field access, with `HasFieldMut` and the provider-side `FieldGetter`. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/has_fields.md index e12a12c9..cb80650a 100644 --- a/docs/reference/traits/has_fields.md +++ b/docs/reference/traits/has_fields.md @@ -6,7 +6,9 @@ sidebar_label: 'HasFields' The whole-shape field representation and its conversions. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/is_provider_for.md b/docs/reference/traits/is_provider_for.md index c8af3cf9..aca350d5 100644 --- a/docs/reference/traits/is_provider_for.md +++ b/docs/reference/traits/is_provider_for.md @@ -6,7 +6,9 @@ sidebar_label: 'IsProviderFor' The marker supertrait that makes a provider's missing dependency show up by name. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index d17a2843..1f5cdcbf 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -6,7 +6,9 @@ sidebar_label: 'MapType' The present, absent, and void type-mapping markers and their transforms. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/monad.md b/docs/reference/traits/monad.md index f16507d0..01932f93 100644 --- a/docs/reference/traits/monad.md +++ b/docs/reference/traits/monad.md @@ -6,7 +6,9 @@ sidebar_label: 'Monad traits' `MonadicTrans`, `MonadicBind`, `LiftValue`, and `ContainsValue`. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/optional_fields.md b/docs/reference/traits/optional_fields.md index 05f3a4cd..ef515f49 100644 --- a/docs/reference/traits/optional_fields.md +++ b/docs/reference/traits/optional_fields.md @@ -6,7 +6,9 @@ sidebar_label: 'Optional-field traits' The builder and extractor traits for optional and defaulted fields. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/product_ops.md b/docs/reference/traits/product_ops.md index 85a8c426..32d1d076 100644 --- a/docs/reference/traits/product_ops.md +++ b/docs/reference/traits/product_ops.md @@ -6,7 +6,9 @@ sidebar_label: 'AppendProduct, ConcatProduct & MapFields' The type-level operations over product lists. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md index 7b12bc91..9db2a207 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/static_format.md @@ -6,7 +6,9 @@ sidebar_label: 'StaticFormat, StaticString & ConcatPath' Recovering type-level strings and paths back into runtime data. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index d38c63cd..c9f3ef30 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -6,7 +6,9 @@ sidebar_label: 'Field' A value paired with its type-level name tag. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index 1f3c0646..bd8b1ff1 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -6,7 +6,9 @@ sidebar_label: 'Index' A type-level natural number, used to tag tuple-struct fields. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index 7dc4392f..34b4fd71 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -6,7 +6,9 @@ sidebar_label: 'Life' A lifetime lifted into a type. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 632bbc12..8779979f 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -6,7 +6,9 @@ sidebar_label: 'MRef' An owned-or-borrowed getter value. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, diff --git a/docs/reference/types/type_level_spines.md b/docs/reference/types/type_level_spines.md index a7b6636c..e80154fb 100644 --- a/docs/reference/types/type_level_spines.md +++ b/docs/reference/types/type_level_spines.md @@ -6,7 +6,9 @@ sidebar_label: 'Type-level spines' `Cons`/`Nil`, `Either`/`Void`, `Chars`, and `PathCons` — the lists the sugar expands into. -:::info Not written yet +:::info + +### Not written yet This reference page is still being written. Until it lands, the [`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, From e760e61bd9c18035e585de33ebb1fb498d36bd08 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 11:03:04 +0200 Subject: [PATCH 011/516] Write the #[cgp_fn] reference page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fourth written page of the construct reference, and the first ported under the revised section order. Its weight sits in one place: where a generic and a where clause each land. That split is most of what there is to learn about the macro, so it gets a table and a subsection of its own for #[impl_generics], which is also where the internal guide on naming a type dependency reaches the public site. "When to reach for it" frames the macro as the default starting point rather than a lesser form of a component, and names the three constructs that displace it. Nothing in the expansion or the error messages is transcribed. Every form was compiled against cgp 0.8.0-alpha and read back through `cargo cgp expand --lib --item`, and each of the three gotchas quotes the message the compiler actually printed — including that the same #[impl_generics] mistake gives E0425 for a bare `Db` and E0433 for a path like `Db::Row`. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01HYb8eTVWU4N1ahqA2du34d --- docs/reference/macros/cgp_fn.md | 344 +++++++++++++++++++++++++++++++- 1 file changed, 339 insertions(+), 5 deletions(-) diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 0d0e7dc0..5631c2c6 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -6,12 +6,346 @@ sidebar_label: '#[cgp_fn]' Define a single-implementation capability as a blanket-impl trait, straight from a function. -:::info +## What it's for -### Not written yet +`#[cgp_fn]` is the smallest amount of CGP that does anything useful. You write a plain function, mark +the values it needs from the context, and the macro turns it into a capability that every type with +those fields gets automatically: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +Any struct with a `width` and a `height` can now call `.rectangle_area()`. There is no component to +define, no provider to name, and no wiring table anywhere — the macro emits a trait and one blanket +implementation covering every context that satisfies the field requirements. + +That is the trade it makes, and it is worth being explicit about. A +[`#[cgp_component]`](./cgp_component.md) supports many interchangeable implementations, one chosen per +context, and charges for it in ceremony. `#[cgp_fn]` supports exactly one implementation — the +function body — and charges nothing. For the large share of capabilities that have one natural +definition, that is the better deal, which is why `#[cgp_fn]` is the recommended place to start rather +than a lesser form of the real thing. + +It is also the gentlest introduction to CGP, because nothing in it is unfamiliar. A reader who +understands functions and arguments can write a working capability without first meeting trait bounds, +blanket implementations, or type-level field names. All of that stays behind an +[`#[implicit]`](../attributes/implicit.md) parameter that looks like an ordinary one. + +## Using it + +Apply the attribute to a free function whose first parameter is `self`. The function name becomes the +method name, and its PascalCase form becomes the trait name — `rectangle_area` generates a +`RectangleArea` trait with a `rectangle_area` method. + +Pass an identifier to override the trait name, which is useful when a verb-style name reads better +than the function's: + +```rust +#[cgp_fn(CanCalculateRectangleArea)] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +The receiver may be `&self` or `&mut self`. A `&mut self` function can take a mutable implicit +argument and write through it. + +### Implicit arguments + +An [`#[implicit]`](../attributes/implicit.md) parameter is removed from the method's signature and +filled from a same-named field on the context instead. The parameter's *name* is the field name, and +its *type* decides how the field is read: an owned type is cloned out, a `&str` is borrowed from a +`String` field, and a plain `&T` is borrowed with no conversion. The full set of forms — including +options, slices, and the mutable variants — is on the [`#[implicit]`](../attributes/implicit.md) page. + +Because these parameters disappear from the signature, `rectangle_area` above is called with no +arguments at all: `rect.rectangle_area()`. + +### Generics, and where each bound lands + +A `#[cgp_fn]` splits its generics and its `where` clause deliberately, and knowing which goes where is +most of what there is to learn about the macro. + +| You write | It lands on | +|---|---| +| A generic parameter on the function | Both the trait and the impl | +| A `where` clause on the function | The impl only | +| [`#[impl_generics(T: Bound)]`](#a-type-the-caller-should-not-name) | The impl only | +| [`#[extend_where(...)]`](../attributes/extend_where.md) | Both the trait and the impl | + +The default — generics on both, `where` clause on the impl alone — is what keeps a capability's +requirements out of sight of its callers. A caller bounds on the clean trait, and the constraints the +body actually needs stay one level down on the implementation: + +```rust +#[cgp_fn] +pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar +where + Scalar: Mul + Copy, +{ + factor * factor +} +``` + +`Scale` is the trait; `Scalar: Mul + Copy` appears only on the impl. + +#### A type the caller should not name + +When the function needs a type that should be inferred rather than chosen — a database handle, a +displayable value — declare it with `#[impl_generics(...)]`. The parameter goes on the impl alone, so +the trait stays unparameterized and no caller mentions it: + +```rust +#[cgp_fn] +#[impl_generics(Name: Display)] +pub fn describe(&self, #[implicit] name: &Name) -> String { + format!("{name}") +} +``` + +`Describe` has no type parameter. A context becomes eligible purely by carrying a `name` field of some +`Display` type, and the type is resolved from that field. + +The cost is that the type is concealed rather than named. It exists only where a value of it flows +through an implicit argument, so nothing else can refer to it — including this function's own +signature. Naming it in a return type or an explicit parameter does not compile, as the +[Gotchas](#gotchas) explain. When the type must be nameable, or when two capabilities have to agree +that they mean the same type, promote it to an abstract type with [`#[cgp_type]`](./cgp_type.md) and +import it with [`#[use_type]`](../attributes/use_type.md). + +### Companion attributes + +Several attributes shape what the macro generates, and together they are how a `#[cgp_fn]` states what +it depends on. + +- [`#[uses(...)]`](../attributes/uses.md) imports the capabilities the body calls on `self`, reading + like a `use` statement rather than a hand-written `where Self: Trait` bound. It accepts ordinary Rust + traits as readily as CGP ones. +- [`#[use_type(Trait.Type)]`](../attributes/use_type.md) imports an abstract type so the signature can + name it bare, and adds the owning trait as a supertrait. +- [`#[extend(...)]`](../attributes/extend.md) adds a capability supertrait to the generated trait. Here + it is the *only* way to add one, since a `where` clause in a `#[cgp_fn]` is an implementation detail + rather than part of the interface. +- [`#[extend_where(...)]`](../attributes/extend_where.md) puts a predicate on the generated trait's own + `where` clause, for a bound callers need to see. +- [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound when the + function delegates to one. +- [`#[async_trait]`](./async_trait.md) goes directly beneath `#[cgp_fn]` on an `async fn`. It is copied + onto both generated items, so the trait ends up declaring a lint-clean `-> impl Future`. + +## Examples + +Two capabilities, the second built on the first, and a context that gets both without wiring anything: + +```rust +use cgp::prelude::*; + +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} + +#[cgp_fn] +#[uses(RectangleArea)] +pub fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 { + self.rectangle_area() * scale_factor * scale_factor +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, +} + +pub fn report(rect: &Rectangle) { + println!("base area = {}", rect.rectangle_area()); + println!("scaled area = {}", rect.scaled_rectangle_area()); +} +``` + +`scaled_rectangle_area` calls `self.rectangle_area()` because `#[uses(RectangleArea)]` declared the +dependency; it does not know or care how that capability is implemented. `Rectangle` derives +[`HasField`](../derives/derive_has_field.md) and happens to carry the three fields the two functions +read, which is its entire qualification — there is no `delegate_components!` anywhere in this program, +and adding one would change nothing. + +## When to reach for it, and when not + +**Reach for `#[cgp_fn]` first.** When a capability has one natural definition, this is the form to +write, and starting here costs nothing if that changes later: the trait keeps its name and its method, +so promoting it to a [`#[cgp_component]`](./cgp_component.md) leaves every call site untouched. What +you add at that point is the component, a named provider, and a line of wiring per context. + +Reach for something else in three cases. + +- **The capability needs a second implementation, chosen per context.** That is what + [`#[cgp_component]`](./cgp_component.md) is for, and no amount of `#[cgp_fn]` will get you there — + its blanket impl already covers every context, so there is nowhere for an alternative to live. +- **The dependencies are traits rather than fields.** [`#[blanket_trait]`](./blanket_trait.md) builds + the same kind of single-implementation, no-wiring capability from a trait with supertraits and + default method bodies. Reach for it when what the body needs is other capabilities; reach for + `#[cgp_fn]` when what it needs is values. +- **A generic must vary per call.** A generic parameter here goes on the trait rather than the method, + so it is fixed by whatever satisfies the bounds for a given context rather than chosen at each call + site. A capability that genuinely needs a per-call type parameter wants a hand-written blanket impl + or a component. + +One decision inside the macro is worth making deliberately rather than by default: **where a type the +body needs should live.** Start with `#[impl_generics]` while the type only ever flows through implicit +arguments — it is shorter, needs no wiring, and reads as "this works with any `database` field of a +compatible type". Climb to an [abstract type](./cgp_type.md) when the type must appear in the +capability's own signature, or when two capabilities must agree that they mean the same one. What to +avoid in both cases is a plain generic parameter on the function, which lands on the trait and makes +every caller — and every intermediate capability built on it — declare the parameter and repeat its +bounds whether they touch it or not. + +## Under the hood + +:::note + +### Advanced + +This section shows the two items the macro generates. You do not need them to use `#[cgp_fn]`, but they +are what an unsatisfied field requirement names, so reading one makes those errors much easier to +follow. `cargo cgp expand` prints the same thing for your own code. ::: + +`#[cgp_fn]` emits exactly two items: the trait carrying the method, and a blanket impl of it for a +generic context. From this input: + +```rust +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +the macro produces the trait with the implicit parameters stripped from the signature, and the impl +with those parameters turned into [`HasField`](../traits/has_field.md) bounds and `let` bindings at the +top of the body: + +```rust +pub trait RectangleArea { + fn rectangle_area(&self) -> f64; +} + +impl<__Context__> RectangleArea for __Context__ +where + Self: HasField + + HasField, +{ + fn rectangle_area(&self) -> f64 { + let width: f64 = self + .get_field(PhantomData::) + .clone(); + let height: f64 = self + .get_field(PhantomData::) + .clone(); + + width * height + } +} +``` + +Three details of the real output are worth recognizing. The context type parameter is literally +`__Context__`, a reserved name chosen so it cannot collide with one of yours, and it is referred to as +`Self` inside the impl. [`Symbol!("width")`](./symbol.md) is a type-level string standing for the field +name — the compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and +`cargo cgp expand` resugars it back to this. And the `.clone()` is what an *owned* implicit argument +compiles to; a `&str` argument ends in `.as_str()` instead, and a plain `&T` in nothing at all. + +The generics split shows up in the same impl. Given the `scale` function above, the generic goes on +both items while the function's `where` bound stays on the impl, ordered *before* the implicit field +bounds — attribute-contributed predicates always come first, and the implicit ones are appended last: + +```rust +pub trait Scale { + fn scale(&self) -> Scalar; +} + +impl<__Context__, Scalar> Scale for __Context__ +where + Scalar: Mul + Copy, + Self: HasField, +{ + fn scale(&self) -> Scalar { /* ... */ } +} +``` + +The companion attributes layer into these same two items. `#[uses(Trait)]` adds a `Self: Trait` +predicate to the impl; `#[extend(Trait)]` adds it to the impl *and* to the trait's supertraits; +`#[extend_where(P)]` adds `P` to both `where` clauses; `#[impl_generics(T: Bound)]` inserts `T: Bound` +into the impl's generic list alone; and `#[use_type(Trait.Type)]` adds the supertrait and rewrites +every bare mention of the type into its fully qualified form. + +
+Formal grammar + +The attribute argument is a single optional trait name, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpFnArgs -> TraitName? + +TraitName -> IDENTIFIER +``` + +When the argument is omitted, the trait name defaults to the function name converted to PascalCase. The +`#[implicit]` markers on parameters and the companion attributes are separate attributes with grammars +of their own, documented on their own pages. + +
+ +## Gotchas + +**A function with implicit arguments must take `self` first.** Without a receiver there is no context +to read a field from, and the macro says so rather than emitting a bound that fails later: + +```text +error: The first argument of a function with implicit arguments must be `self` +``` + +**A mutable implicit argument must be the only one.** Reading a field mutably borrows the whole context +exclusively, so it cannot coexist with any other field read. Immutable implicit arguments carry no such +restriction and combine freely, in any number: + +```text +error: a `&mut` implicit argument must be the only implicit argument, since its mutable + borrow of the context conflicts with reading any other field +``` + +**An `#[impl_generics]` parameter cannot appear in the capability's own signature.** Only the generated +impl declares it, so naming it in a return type or an explicit parameter leaves it unresolved in the +trait. The spelling decides which error you get, which is why the same mistake shows up two ways: a +bare `Db` gives `error[E0425]: cannot find type 'Db' in this scope`, and a path such as `Db::Row` gives +`error[E0433]: use of undeclared type 'Db'`. Both mean the same thing — either the type belongs out of +the signature, or it needs to be an [abstract type](./cgp_type.md) rather than an inferred impl +parameter. + +## Related constructs + +- [`#[implicit]`](../attributes/implicit.md) — fills a parameter from a context field. +- [`#[uses]`](../attributes/uses.md), [`#[use_type]`](../attributes/use_type.md), + [`#[extend]`](../attributes/extend.md), [`#[extend_where]`](../attributes/extend_where.md), and + [`#[use_provider]`](../attributes/use_provider.md) — the attributes that shape what it generates. +- [`#[cgp_component]`](./cgp_component.md) — the step up, for when one implementation is not enough. +- [`#[blanket_trait]`](./blanket_trait.md) — the same idea built from a trait rather than a function. +- [`#[cgp_impl]`](./cgp_impl.md) — shares the `#[implicit]` mechanism, for writing a component's provider. +- [`#[derive(HasField)]`](../derives/derive_has_field.md) — what a context derives to satisfy the bounds. +- [`#[async_trait]`](./async_trait.md) — how an `async fn` capability is declared. + +## Source + +- Entry point: [`cgp_fn.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_fn.rs) +- Implementation: [`types/cgp_fn/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_fn/) +- Implicit arguments: [`types/implicits/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/implicits/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* From 427d268d995722a777882ec29519563847e5cbac Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 11:10:48 +0200 Subject: [PATCH 012/516] Correct two wrong claims, and route between the two indexes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A review pass against the compiler and the built site found two statements that were not true. #[cgp_fn] does not require a receiver. The page said to apply the attribute to a function whose first parameter is `self`, while its own Gotchas said the receiver is required only when a parameter is #[implicit] — and the Gotchas were right. Compiling the no-receiver, no-implicit form shows it is accepted and yields an associated function. The concept page showed a provider blanket impl missing the IsProviderFor bound the macro actually generates, because the listing came from the internal document rather than from cargo cgp expand. Restore the bound, and rework the paragraph after it to explain what the reader has just seen rather than introducing the marker from nowhere. Add the reserved-name caveat the reference page carries and this one lacked. Two smaller things. The Concepts index sent readers to "start here" pages that are stubs, with the caveat only at the foot, so move it above the routing. And the two indexes only linked one way: the reference now points at the concepts for a reader who wants why rather than what. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01HYb8eTVWU4N1ahqA2du34d --- docs/concepts/consumer-and-provider-traits.md | 20 +++++++++++++------ docs/concepts/index.md | 14 ++++++++----- docs/reference/index.md | 4 +++- docs/reference/macros/cgp_fn.md | 12 ++++++++--- 4 files changed, 35 insertions(+), 15 deletions(-) diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index bf84946e..c0aec261 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -155,7 +155,8 @@ whatever the entry names: ```rust impl EmailSender for Provider where - Provider: DelegateComponent, + Provider: DelegateComponent + + IsProviderFor, Provider::Delegate: EmailSender, { fn send_email(context: &Context, to: &str, body: &str) { @@ -171,11 +172,18 @@ because its table maps `EmailSenderComponent` to `SendViaSmtp`; and `SendViaSmtp `SendViaSmtp::send_email` — no lookup happens while the program runs, and a provider no context uses never reaches the binary. -The real generated code carries one more piece: the provider trait has -[`IsProviderFor`](/docs/reference/traits/is_provider_for) as a supertrait, and every provider -implements it under the same bounds it needs. That marker exists solely so that when a context is -missing something a provider requires, the compiler can name the missing requirement instead of -reporting that the provider trait is not implemented. It is never written by hand. +The one piece of that listing not yet explained is +[`IsProviderFor`](/docs/reference/traits/is_provider_for), which also rides on the provider trait as a +supertrait. Every provider implements it under exactly the bounds it needs, and requiring it here is +what carries those bounds back down the chain — so when a context is missing something a provider +requires, the compiler can name the missing requirement instead of reporting only that the provider +trait is not implemented. It is generated, never written by hand. + +Two cosmetic liberties in the listings above are worth knowing before you read a real error message. +The generated type parameters carry reserved names — the context is `__Context__` and the provider +`__Provider__` — and the delegate is spelled out in full as +`<__Provider__ as DelegateComponent>::Delegate`. `Context`, `Provider`, and +`Provider::Delegate` here are for legibility; `cargo cgp expand` will show you the real thing. ## Writing it diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 3d6395b7..0b0fd8c7 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -16,6 +16,15 @@ name of the thing they want. A concept page answers the question neither of thos *why does CGP work this way, and when is it the right thing to reach for?* Each page names the constructs it involves and links to the reference for their exact syntax, rather than repeating it. +:::info + +### Still being written + +The list of ideas below is complete, so nothing is missing from this index — but most of the pages +behind it are placeholders for now, and each one says so when you open it. + +::: + ## Where to start **Read [Bypassing coherence](./coherence.md) first if you want to know why CGP exists.** It explains @@ -63,8 +72,3 @@ as it goes, turning a small language into types the compiler interprets. gap in stable Rust rather than a CGP idea, and it matters as soon as an async CGP task is spawned. [How much CGP to use](./modularity-hierarchy.md) is a decision guide rather than an explanation, and it is the page to reach for when the question is how far to go. - -## This section is still being written - -Most pages here are placeholders at present, and each one says so. The list of ideas is complete, so -nothing is missing from this index even where the page behind it is not yet filled in. diff --git a/docs/reference/index.md b/docs/reference/index.md index 7afc51fc..be2aa073 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -11,7 +11,9 @@ thing you need. If you are still learning CGP, the [tutorials](/docs/tutorials/hello) are the better starting point. This section assumes you know what a component and a provider are, and it explains constructs one at a -time rather than building an idea up. +time rather than building an idea up. When a page here tells you *what* a construct does and you want +to know *why* CGP works that way, the [concepts](/docs/concepts/) are where each idea is explained on +its own. ## Start with these six diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 5631c2c6..e97e119a 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -37,9 +37,15 @@ blanket implementations, or type-level field names. All of that stays behind an ## Using it -Apply the attribute to a free function whose first parameter is `self`. The function name becomes the -method name, and its PascalCase form becomes the trait name — `rectangle_area` generates a -`RectangleArea` trait with a `rectangle_area` method. +Apply the attribute to a free function. The function name becomes the method name, and its PascalCase +form becomes the trait name — `rectangle_area` generates a `RectangleArea` trait with a +`rectangle_area` method. + +Almost every `#[cgp_fn]` takes `self` as its first parameter, because reading a field from the context +is most of what these functions do, and a receiver is *required* the moment any parameter is +`#[implicit]`. Omitting it is accepted, and produces a trait whose item is an associated function +rather than a method; it is rarely what you want here, since a function that reads nothing from its +context computes the same answer for every context that gets it. Pass an identifier to override the trait name, which is useful when a verb-style name reads better than the function's: From bfae899f6a8037860af0fd2493e58a4745293d9b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 11:40:09 +0200 Subject: [PATCH 013/516] Revise the written reference and concept pages against the compiler MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A review of everything written so far, checked against the compiler rather than against the internal documents, found one wrong expansion, three misquoted diagnostics, and four places the pages had drifted from their own writing guide. The expansion error is in delegate_components!. An `open` statement's per-value entry does not lower to a key ending in `Nil`; it lowers to an impl generic over a `__Wildcard__` tail, which is what lets the entry match any path beginning with that component and dispatch type rather than a path of one exact length. Show the real impl and say what the wildcard buys, and take the header's redirect target from `cargo cgp expand` as well, which resugars it to `Path!(@Component)` while leaving the per-entry key a raw spine — so one expansion prints the same kind of type two ways, which is worth saying rather than quietly normalizing. The three diagnostics were each quoted from memory rather than from a run. #[cgp_fn] gave E0433's span label as its headline, where both spellings report the same headline and only the code differs; #[cgp_impl] truncated E0599 before "in the current scope"; and #[cgp_component] described its const-generic rejection without quoting the macro's own message, which its sibling pages do quote. Four guide items. #[cgp_fn] leans on "blanket implementation" in its summary and its first paragraph and never linked one, so it now links the source the Hello World tutorial already uses. #[cgp_fn] and #[cgp_impl] used "context" as load-bearing vocabulary above the advanced line with no gloss, where delegate_components! glosses it properly — and on #[cgp_impl] that word sits in the page's single most important sentence. delegate_components! named DelegateComponent and IsProviderFor in What it's for, addressed to a reader whose only prior exposure teaches no wiring at all; the reasoning survives without the names, so they now appear first where they are explained. And both indexes lacked the provenance note the other five pages carry, the no-note rule covering scaffolded stubs rather than hand-written prose. Also harmonize how the two indexes admit to being unfinished. The reference buried it at the foot, 170 lines below a claim to be the complete reference; it now leads with the same admonition the concepts index uses. And repair an inline code span split across a line break. Every snippet on all seven pages was compiled against cgp 0.8.0-alpha with a check_components! assertion per wired context, every expansion re-read through `cargo cgp expand --lib --item`, and every quoted error reproduced — including the receiverless #[cgp_fn], the &mut implicit restriction, the associated-const workaround, and the E0119 the concept page turns on. Co-Authored-By: Claude Opus 5 (1M context) --- docs/concepts/consumer-and-provider-traits.md | 1 + docs/concepts/index.md | 4 ++ docs/reference/index.md | 16 ++++-- docs/reference/macros/cgp_component.md | 12 +++-- docs/reference/macros/cgp_fn.md | 24 ++++++--- docs/reference/macros/cgp_impl.md | 10 ++-- docs/reference/macros/delegate_components.md | 52 +++++++++++++------ 7 files changed, 83 insertions(+), 36 deletions(-) diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index c0aec261..f8b3d82e 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -194,6 +194,7 @@ shape — keeping `self` and the original signatures — and rewrites it into th ```rust use cgp::prelude::*; +use core::cell::RefCell; #[cgp_component(EmailSender)] pub trait CanSendEmail { diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 0b0fd8c7..87a2e600 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -72,3 +72,7 @@ as it goes, turning a small language into types the compiler interprets. gap in stable Rust rather than a CGP idea, and it matters as soon as an async CGP task is spawned. [How much CGP to use](./modularity-hierarchy.md) is a decision guide rather than an explanation, and it is the page to reach for when the question is how far to go. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/index.md b/docs/reference/index.md index be2aa073..2bb0786c 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -15,6 +15,16 @@ time rather than building an idea up. When a page here tells you *what* a constr to know *why* CGP works that way, the [concepts](/docs/concepts/) are where each idea is explained on its own. +:::info + +### Still being written + +The construct list below is complete — every construct the `cgp` crate exports has a page, or a named +place on a page it shares — so nothing is missing from this index. Most of the pages behind it are +placeholders for now, and each one says so when you open it. + +::: + ## Start with these six Most CGP code uses a small number of constructs over and over. If you read nothing else here, read @@ -193,8 +203,6 @@ these names, this is where it lives. | `#[default_impl(...)]` | [`DefaultNamespace`](./traits/default_namespace.md) | | `#[check_providers(...)]`, `#[check_params(...)]` | [`check_components!`](./macros/check_components.md) | -## This reference is still being written +--- -Most pages here are placeholders at present, and each one says so. The construct list is complete — -every construct the `cgp` crate exports has a page, or a named place on a page it shares — so nothing -is missing from this index even where the page behind it is not yet filled in. +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 84dde12e..869606c1 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -316,9 +316,15 @@ arguments inside are parsed. ## Gotchas -**A const generic parameter on the trait is rejected**, with a compile error. A component's extra -parameters are recorded as a tuple of *types* in the `IsProviderFor` supertrait, and CGP's wiring -dispatches on types rather than values, so a const value has nowhere to live in that machinery. +**A const generic parameter on the trait is rejected**, by the macro rather than by the compiler: + +```text +error: const generic parameters are not supported on CGP component traits +``` + +A component's extra parameters are recorded as a tuple of *types* in the `IsProviderFor` supertrait, and +CGP's wiring dispatches on types rather than values, so a const value has nowhere to live in that +machinery. An associated `const` *item* is unaffected — `const LIMIT: u64;` as a trait member is an [associated const](https://doc.rust-lang.org/reference/items/associated-items.html), not a generic diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index e97e119a..a87f4c70 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -9,8 +9,9 @@ Define a single-implementation capability as a blanket-impl trait, straight from ## What it's for `#[cgp_fn]` is the smallest amount of CGP that does anything useful. You write a plain function, mark -the values it needs from the context, and the macro turns it into a capability that every type with -those fields gets automatically: +the values it needs from the **context** — the type the capability runs against, which supplies those +values as its fields — and the macro turns it into a capability that every type with those fields gets +automatically: ```rust #[cgp_fn] @@ -20,8 +21,9 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> ``` Any struct with a `width` and a `height` can now call `.rectangle_area()`. There is no component to -define, no provider to name, and no wiring table anywhere — the macro emits a trait and one blanket -implementation covering every context that satisfies the field requirements. +define, no provider to name, and no wiring table anywhere — the macro emits a trait and one +[blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) +covering every context that satisfies the field requirements. That is the trade it makes, and it is worth being explicit about. A [`#[cgp_component]`](./cgp_component.md) supports many interchangeable implementations, one chosen per @@ -328,10 +330,16 @@ error: a `&mut` implicit argument must be the only implicit argument, since its **An `#[impl_generics]` parameter cannot appear in the capability's own signature.** Only the generated impl declares it, so naming it in a return type or an explicit parameter leaves it unresolved in the -trait. The spelling decides which error you get, which is why the same mistake shows up two ways: a -bare `Db` gives `error[E0425]: cannot find type 'Db' in this scope`, and a path such as `Db::Row` gives -`error[E0433]: use of undeclared type 'Db'`. Both mean the same thing — either the type belongs out of -the signature, or it needs to be an [abstract type](./cgp_type.md) rather than an inferred impl +trait. Both spellings report the same headline: + +```text +error[E0425]: cannot find type `Db` in this scope +``` + +What differs is the code, and that is the part worth noticing, since it is what you are likely to search +for. A bare `Db` reports `E0425` as above; a qualified path such as `Db::Row` reports `E0433`, whose span +is labelled *use of undeclared type `Db`* instead. Both mean the same thing — either the type belongs out +of the signature, or it needs to be an [abstract type](./cgp_type.md) rather than an inferred impl parameter. ## Related constructs diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 00a51d2e..c06c5d8c 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -49,10 +49,10 @@ The macro performs the rewrite for you. **This is the form to write**; the insid desugars to and what you will meet in generated code. One fact the convenience must not hide: **inside a `#[cgp_impl]` block, `self` and `Self` mean the -context, not the provider.** The provider is a type-level name with no fields and no value — it is -never constructed, and there is nothing in it to read. The macro rewrites `self` to the context value -and `Self` to the context type precisely because the context is the only thing that exists when the -method runs. +context — the type this implementation runs against — and not the provider.** The provider is a +type-level name with no fields and no value: it is never constructed, and there is nothing in it to +read. The macro rewrites `self` to the context value and `Self` to the context type precisely because +the context is the only thing that exists when the method runs. ## Using it @@ -295,7 +295,7 @@ provider supplies them in the `#[cgp_impl]` block as usual — but `Self::LIMIT` The error reads: ```text -error[E0599]: no associated function or constant named `LIMIT` found for type parameter `__Context__` +error[E0599]: no associated function or constant named `LIMIT` found for type parameter `__Context__` in the current scope ``` Name it through the provider trait instead, which the rewrite turns into the correct qualified path: diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 5ff0623e..5b8b4b40 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -33,11 +33,10 @@ The type this table is attached to is a **context**: the type that owns the wiri standing for your whole application, whose job is to carry choices rather than data — `struct App;` with no fields is a perfectly good context. Sometimes, as above, it is the data type itself. -A macro is worth having here because each entry expands to two impls rather than one. Besides the -[`DelegateComponent`](../traits/delegate_component.md) impl that stores the choice, the macro emits an -[`IsProviderFor`](../traits/is_provider_for.md) impl that forwards the chosen provider's own +A macro is worth having here because each entry expands to two impls rather than one. Besides the impl +that stores the choice, the macro emits a second one that forwards the chosen provider's own dependencies back through the table — which is what makes a missing transitive requirement produce a -usable error instead of a dead end. +usable error instead of a dead end. [Under the hood](#under-the-hood) shows both. ## Using it @@ -249,7 +248,7 @@ are what a wiring error names, so reading one makes those errors much easier to ::: Each entry becomes a pair of impls. From the single-entry table above, first the -`DelegateComponent` impl that records the choice: +[`DelegateComponent`](../traits/delegate_component.md) impl that records the choice: ```rust impl DelegateComponent for Rectangle { @@ -262,7 +261,8 @@ That impl alone is the whole lookup. The provider blanket impl generated by from `RectangleArea`, and the consumer blanket impl then gives `Rectangle` the `CanCalculateArea` trait. The hand-written equivalent of one wiring entry is exactly that block. -Second, the `IsProviderFor` impl that forwards the provider's requirements: +Second, the [`IsProviderFor`](../traits/is_provider_for.md) impl that forwards the provider's +requirements: ```rust impl<__Context__, __Params__> @@ -277,9 +277,9 @@ the `where` bounds it needs, so an unsatisfied requirement flows back through th the point of use. Note that these parameters are literally named `__Context__` and `__Params__` in the emitted code. -The array syntax simply repeats the pair per key. A table with `[FooComponent, BarComponent]: -FooBarProvider` and `BazComponent: BazProvider` yields three `DelegateComponent` impls and three -matching `IsProviderFor` impls. +The array syntax simply repeats the pair per key. A table pairing +`[FooComponent, BarComponent]` with `FooBarProvider`, alongside a `BazComponent: BazProvider` entry, +yields three `DelegateComponent` impls and three matching `IsProviderFor` impls. The `open` statement expands to a redirect plus per-value entries stored on the context itself. The header wires the component to a `RedirectLookup` rooted at the component name inside `MyApp`'s own @@ -287,17 +287,37 @@ table: ```rust impl DelegateComponent for MyApp { - type Delegate = RedirectLookup>; + type Delegate = RedirectLookup; } ``` Each `@AreaCalculatorComponent.Rectangle: RectangleArea` entry then stores its provider in that same -table under a path key, so `MyApp` gains -`DelegateComponent>>` with -`Delegate = RectangleArea`. The [`RedirectLookup`](../providers/redirect_lookup.md) impl appends the -dispatch parameter onto the path and reads the result back, so `MyApp: CanCalculateArea` -resolves to `RectangleArea`. The legacy nested-table form keys on the same parameter; the difference is -only that its per-value entries live in a separate table type. +table under a path key: + +```rust +impl<__Wildcard__> + DelegateComponent>> + for MyApp +{ + type Delegate = RectangleArea; +} +``` + +The [`RedirectLookup`](../providers/redirect_lookup.md) impl appends the dispatch parameter onto the +path and reads the result back, so `MyApp: CanCalculateArea` resolves to `RectangleArea`. + +The tail of that key is a **generic `__Wildcard__` parameter rather than `Nil`**, and that is what makes +it work: the entry matches any path *beginning* with this component and this dispatch type, whatever the +lookup appends after it, so one entry answers the redirect without having to predict the exact length of +the path reaching it. + +One presentational quirk is worth knowing before you compare these listings against your own expansion. +Both paths above are [`PathCons`](../types/type_level_spines.md) lists, but `cargo cgp expand` prints +them differently — it resugars the header's redirect target to [`Path!`](./path.md) form while leaving +the per-entry key as the raw spine — so the same kind of type appears in two spellings in one expansion. + +The legacy nested-table form keys on the same parameter; the difference is only that its per-value +entries live in a separate table type.
Formal grammar From eb4974651b547a3a9b17bde19ec503ff72de04bd Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 12:21:11 +0200 Subject: [PATCH 014/516] Write the seven attribute reference pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `attributes/` is the first reference group finished end to end: `#[implicit]`, `#[uses]`, `#[use_type]`, `#[use_provider]`, `#[extend]`, `#[extend_where]`, and `#[derive_delegate]`, each on the six-section layered descent with its formal grammar collapsed where it has custom syntax. Two of them say something different from what the internal reference they were ported from says, because verifying beat transcribing. `#[use_provider]` does not take a comma-separated list of provider-and-trait pairs. The comma is a parse error — after the first trait the parser is continuing that provider's bounds, so `+` joins several bounds on one provider and several providers take one stacked attribute each. Not even a trailing comma parses. That makes this attribute the exception to the one-attribute-comma-separated convention `#[uses]` and `#[use_type]` do follow, which is worth saying plainly since the habit transfers wrongly. `#[extend_where]` does not hand its predicate to callers. A trait's `where` clause is a precondition they must prove, not a bound elaborated to whoever holds the trait, so a caller generic over the parameter still writes it — the page had to be rewritten around what the promotion actually buys, which is that an unsatisfiable requirement is caught where the trait is named. Left on the impl alone, `Ctx: Scale` compiles in silence and nothing complains until a concrete context is supplied. That silence is the thing the attribute removes. `#[derive_delegate]` leads with the deprecation rather than burying it, and shows the `open` wiring beside its own so the replacement is one diff away. Also correct the index's framing for this group. It introduced all four dependency attributes with "so they never appear in the interface callers see", which is false for `#[extend]` and `#[extend_where]` — appearing there is their entire purpose. The section now divides them by whether the requirement stays private to the implementation. Every snippet compiles against cgp 0.8.0-alpha with a `check_components!` assertion per wired context; every expansion was read back through `cargo cgp expand`; and all fourteen quoted diagnostics were reproduced, including the `#[use_type]` grounding-cycle message, the four `#[implicit]` rejections, and the `E0119` from wiring one component through two dispatch mechanisms. Co-Authored-By: Claude Opus 5 (1M context) --- docs/reference/attributes/derive_delegate.md | 272 +++++++++++++- docs/reference/attributes/extend.md | 229 +++++++++++- docs/reference/attributes/extend_where.md | 215 ++++++++++- docs/reference/attributes/implicit.md | 263 ++++++++++++- docs/reference/attributes/use_provider.md | 276 +++++++++++++- docs/reference/attributes/use_type.md | 366 ++++++++++++++++++- docs/reference/attributes/uses.md | 227 +++++++++++- docs/reference/index.md | 13 +- 8 files changed, 1817 insertions(+), 44 deletions(-) diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 47ed1929..8ff76ad5 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -8,10 +8,274 @@ Generate the `UseDelegate` dispatcher impl for a component. Superseded by the `o :::info -### Not written yet +### Legacy — read, don't write -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[derive_delegate]` and the [`UseDelegate`](../providers/use_delegate.md) provider it generates are the +older way to choose an implementation per type. A component no longer needs this attribute to be +dispatched on a type parameter: the `open` statement of +[`delegate_components!`](../macros/delegate_components.md) does the same job through machinery every +component already has, with no separate table and no wrapper. + +**Prefer `open` for anything new.** This page is here because you will meet the older form — including in +CGP's own error and handler components, which are still defined with this attribute — and because a +component that keeps it stays compatible with existing wiring. It is expected to be deprecated once +`open` is shown to cover every dispatch case. + +::: + +## What it's for + +A component generic over a type parameter usually wants a different implementation per value of it: +`Rectangle` handled one way, `Circle` another. Something has to look at the type and pick, and written by +hand that dispatcher is an implementation of the provider trait that reads a lookup table, finds the entry +for the type, and forwards every method to it — mechanical code, identical in shape for every component, +differing only in which parameter is the key. + +`#[derive_delegate]` generates it: + +```rust +#[cgp_component(AreaCalculator)] +#[derive_delegate(UseDelegate)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} +``` + +A **context** — the type the capability runs against, which owns the wiring — then points the component at +[`UseDelegate`](../providers/use_delegate.md) over a table naming one implementation per shape, and the +generated dispatcher does the lookup. + +The reason the `open` statement replaced this is that the indirection turned out to be unnecessary. Every +[`#[cgp_component]`](../macros/cgp_component.md) already generates a +[`RedirectLookup`](../providers/redirect_lookup.md) impl, and `open` routes through that instead — so the +per-type entries live on the context itself, there is no second table type to name, and the component +needs no attribute at all. + +## Using it + +`#[derive_delegate]` takes a wrapper type parameterized by the trait generic to dispatch on: + +```rust +#[derive_delegate(UseDelegate)] +``` + +`UseDelegate` is the type that will carry the lookup table, and `Shape` is the trait parameter used as the +key. The key may also be a parenthesized tuple when the table should be keyed on more than one parameter at +once: + +```rust +#[derive_delegate(UseDelegate<(Code, Input)>)] +``` + +**To dispatch on several parameters independently, repeat the attribute**, one per dispatcher. Each names +its own wrapper type, and only the parameter in that wrapper's brackets is used as its key — the rest flow +through unchanged: + +```rust +#[cgp_component(Computer)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +pub trait CanCompute { + type Output; + + fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; +} +``` + +`UseDelegate` is the wrapper CGP provides, but the machinery is not tied to it. Any struct of the same +shape works, which is how a second, independent dispatcher is added — a user-defined +`pub struct UseInputDelegate(pub PhantomData);` is all the second line above +needs. + +The attribute belongs on a [`#[cgp_component]`](../macros/cgp_component.md) trait and only makes sense for +one that has generic parameters. + +## Examples + +A dispatching component, two implementations, and a context that routes each shape to its own: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +#[derive_delegate(UseDelegate)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle { pub width: f64, pub height: f64 } +pub struct Circle { pub radius: f64 } + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height + } +} + +#[cgp_impl(new CircleArea)] +impl AreaCalculator { + fn area(&self, shape: &Circle) -> f64 { + core::f64::consts::PI * shape.radius * shape.radius + } +} +``` + +The wiring names the wrapper and defines its table in place: + +```rust +pub struct MyApp; + +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +`MyApp` now implements `CanCalculateArea` through `RectangleArea` and +`CanCalculateArea` through `CircleArea`. + +**The same result without the attribute** is what to write instead. Drop `#[derive_delegate]` from the +component and let the context open it: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +No wrapper, no second table type, and nothing on the component. The two forms dispatch on the same +parameter and resolve to the same implementations. + +## When to reach for it, and when not + +**Do not add `#[derive_delegate]` to a new component.** Use the `open` statement of +[`delegate_components!`](../macros/delegate_components.md), which needs no attribute and no table type. +That is the recommendation without qualification for new code. + +Three situations still involve it, and only the first is a reason to write it. + +- **Keeping compatibility with existing wiring.** The attribute is what makes + `UseDelegate` wiring possible, so removing it from a published component is a breaking + change for any downstream user who wires that way. Removing it is still the right direction, but it is a + breaking change to schedule rather than a cleanup to slip in. +- **A dispatcher `open` cannot express.** `open` resolves through the `RedirectLookup` impl a component + generates, which keys on the parameter that impl dispatches on. A *second*, independently keyed + dispatcher — the `UseInputDelegate` case above — has no `open` equivalent, so a component wanting + one still declares it here. +- **Reading existing code.** CGP's own error and handler components are defined with this attribute, so + `UseDelegate` tables appear in wiring you did not write. Understanding the form matters more than being + able to author it. + +## Under the hood + +:::note + +### Advanced + +This section shows the dispatcher the attribute generates. You do not need it to use `#[derive_delegate]`, +but it is what a failed per-type lookup names in an error, and seeing it explains why `open` was able to +replace it. `cargo cgp expand` prints the same thing for your own code. ::: + +Each `#[derive_delegate]` adds one provider impl to everything +[`#[cgp_component]`](../macros/cgp_component.md) already emits. It is the ordinary forwarding shape, except +that the lookup key is the dispatch parameter rather than the component name. From the `AreaCalculator` +example: + +```rust +impl<__Context__, Shape, __Components__, __Delegate__> + AreaCalculator<__Context__, Shape> for UseDelegate<__Components__> +where + __Components__: DelegateComponent<(Shape), Delegate = __Delegate__>, + __Delegate__: AreaCalculator<__Context__, Shape>, +{ + fn area(__context__: &__Context__, shape: &Shape) -> f64 { + __Delegate__::area(__context__, shape) + } +} +``` + +Reading it back: `UseDelegate` is a provider for any `Shape` whose entry in `Components` +names something that is itself a provider for that `Shape`, and the method simply forwards. The +`Components` type is the inner table, and [`DelegateComponent`](../traits/delegate_component.md) is the +same trait ordinary wiring is made of — which is why the table is written with +[`delegate_components!`](../macros/delegate_components.md) like any other. + +Two details of the real output are worth recognizing. **The key is wrapped in a tuple**, as +`DelegateComponent<(Shape), …>`, so that a single-parameter key and a multi-parameter one compose +uniformly — a `UseDelegate<(Code, Input)>` declaration produces `DelegateComponent<(Code, Input), …>` with +no other change. And the generics carry reserved names: the table is `__Components__` and the looked-up +entry `__Delegate__`, alongside the provider trait's own `__Context__`. + +**A component's supertraits ride along into the dispatcher.** The provider trait records each supertrait as +a `Context:` predicate, and because the dispatcher reuses the provider trait's generics that predicate +appears here too — so a component declaring an error type through +[`#[use_type]`](use_type.md) yields a dispatcher whose `where` clause also requires +`__Context__: HasErrorType`. + +When several `#[derive_delegate]` attributes are present, one impl is generated per attribute, each keyed +on its own parameter and otherwise identical. The two are independent, so a context may dispatch on either +or nest one table inside the other. + +## Gotchas + +**The key must be a generic parameter the trait actually declares.** The attribute names it by identifier, +so a parameter that is not in scope on the trait is reported as an unresolved type rather than as anything +about dispatch: + +```text +error[E0425]: cannot find type `Shape` in this scope + | + | #[derive_delegate(UseDelegate)] + | ^^^^^ not found in this scope +``` + +The usual cause is putting the attribute on a component that has no type parameter to dispatch on, where +there is nothing for it to do. + +**One component gets one dispatch mechanism.** Wiring the same component both with `open` and with a +`UseDelegate` table is a coherence conflict, because each produces its own table entry for that key: + +```text +error[E0119]: conflicting implementations of trait `DelegateComponent` + for type `App` + | + | open AreaCalculatorComponent; + | ----------------------- first implementation here +``` + +Pick one per component. The related restriction is that `open` does not combine with a joined namespace +where the component carries a `#[prefix(...)]`: its lookups are already routed under that path, so the +per-type entries have to be written with the full prefixed path instead. + +## Related constructs + +- [`delegate_components!`](../macros/delegate_components.md) — its `open` statement is the replacement, and + its nested-table form is what this attribute enables. +- [`UseDelegate`](../providers/use_delegate.md) — the provider the generated impl is written for. +- [`RedirectLookup`](../providers/redirect_lookup.md) — what `open` resolves through instead. +- [`#[cgp_component]`](../macros/cgp_component.md) — the host, and the source of the provider trait. +- [`DelegateComponent`](../traits/delegate_component.md) — the table trait the lookup reads. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — the full form of the mechanism `open` is a special case of. + +## Source + +- Parsing and the generated impl: [`types/attributes/derive_delegate/attribute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/derive_delegate/attribute.rs) +- Emission: [`types/cgp_component/evaluated/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_component/evaluated/item.rs) +- The provider: [`providers/use_delegate.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_delegate.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 5e414eda..13751d52 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -4,14 +4,231 @@ sidebar_label: '#[extend]' # `#[extend]` -Add supertrait bounds to a generated trait. +Add a capability as a supertrait of a generated trait, so callers can rely on it too. -:::info +## What it's for -### Not written yet +`#[extend]` declares that a capability is part of what a trait *guarantees*, rather than something its +implementation happens to need. Where [`#[uses]`](uses.md) adds a private requirement, `#[extend]` adds a +supertrait: every **context** implementing the trait — every type the capability runs against — must also +satisfy it, and every caller may rely on it. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +#[extend(HasName)] +``` + +The clearest way to hold the pair apart is that **`#[extend]` is the `pub use` to `#[uses]`'s `use`**. +Both take the same syntax and both read as imports, but one imports a capability for the implementation's +own use and keeps it out of sight, while the other re-exports it as part of the contract. + +That framing is also why `#[extend]` is preferred over Rust's native supertrait syntax on a +[`#[cgp_component]`](../macros/cgp_component.md). Writing `pub trait CanGreet: HasName` reads as +inheritance from a parent — an is-a relationship, which is not what a CGP supertrait is. `#[extend(HasName)]` +reads as importing a capability the trait passes on, which is what is actually happening. The two generate +the same trait, so this is a choice about how the definition reads. + +On [`#[cgp_fn]`](../macros/cgp_fn.md) the attribute is not merely preferred but necessary. A `where` clause +written on a `#[cgp_fn]` is treated as an implementation detail and never reaches the generated trait, so +there is no way to spell a supertrait by hand — `#[extend]` is the only mechanism for one. + +## Using it + +`#[extend(...)]` takes a comma-separated list of trait bounds, each becoming a supertrait of the generated +trait: + +```rust +#[extend(HasName, HasTitle)] +``` + +Each entry names a trait, optionally with type arguments. Several may be listed in one attribute or spread +across attributes, and they accumulate — prefer one attribute carrying the whole list, as with +[`#[uses]`](uses.md). + +The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on +[`#[cgp_component]`](../macros/cgp_component.md). It is **not** available on +[`#[cgp_impl]`](../macros/cgp_impl.md), which has no trait definition of its own to attach a supertrait to +— the supertraits belong to the component's trait, and a provider states its private needs with +[`#[uses]`](uses.md) instead. + +### When the supertrait supplies a type + +If the reason for the supertrait is that the trait's signatures name a type the other component provides — +an error type, a scalar, a runtime — reach for [`#[use_type]`](use_type.md) instead. It adds the supertrait +*and* rewrites bare mentions of the type into their fully qualified form, so the signature reads +`Result` rather than `Result::Error>`: + +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} +``` + +`#[extend]` is therefore for a **capability** supertrait — one whose methods matter and whose associated +types the signatures do not name. + +## Examples + +A `#[cgp_fn]` capability that guarantees two getters alongside its own method: + +```rust +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_auto_getter] +pub trait HasTitle { + fn title(&self) -> &str; +} + +#[cgp_fn] +#[extend(HasName, HasTitle)] +pub fn full_label(&self) -> String { + format!("{} {}", self.title(), self.name()) +} +``` + +The body can call both getters, and so can anyone holding a `T: FullLabel` — which is the difference from +`#[uses]`. A function that takes a labelled value can format its name without asking for `HasName` +separately. + +On a component the effect is on the consumer trait, and the supertrait becomes part of the capability: + +```rust +#[cgp_component(Greeter)] +#[extend(HasName)] +pub trait CanGreet { + fn greet(&self); +} +``` + +`CanGreet` now means "can greet, and can tell you its name". Every provider may rely on the name being +available, and so may every caller. + +## When to reach for it, and when not + +**Reach for `#[extend]` when callers of the trait should be able to rely on the capability too**, and for +a capability supertrait on a `#[cgp_component]` in preference to native `:` syntax. Reach for something +else in three cases, and the choice turns on where the requirement should be visible. + +- **The implementation needs it privately.** Use [`#[uses]`](uses.md). This is the common case by a wide + margin: most dependencies are the implementation's business, and putting one on the trait forces it on + every context and every caller whether they touch it or not. +- **The signatures name a type it supplies.** Use [`#[use_type]`](use_type.md), which adds the supertrait + and removes the qualified paths. +- **The requirement is a predicate rather than a supertrait** — a bound on a generic parameter rather than + on `Self`. Use [`#[extend_where]`](extend_where.md), which puts it on the generated trait's own `where` + clause. + +There is a cost worth weighing before promoting anything. A supertrait widens the contract permanently: it +cannot later be narrowed without breaking every implementor, and it demands the capability from contexts +that only ever call the one method the trait actually declares. Prefer `#[uses]` unless callers genuinely +need the guarantee. + +## Under the hood + +:::note + +### Advanced + +This section shows where the bound is placed. You do not need it to use `#[extend]`, but the placement is +the entire difference from `#[uses]`, so seeing both is what makes the pair make sense. +`cargo cgp expand` prints the same thing for your own code. ::: + +On a `#[cgp_fn]`, each entry lands in **two** places: as a supertrait of the generated trait, and as a +`Self:` predicate on the generated implementation. From this input: + +```rust +#[cgp_fn] +#[extend(HasName, HasTitle)] +pub fn full_label(&self) -> String { + format!("{} {}", self.title(), self.name()) +} +``` + +the macro emits: + +```rust +pub trait FullLabel: HasName + HasTitle { + fn full_label(&self) -> String; +} + +impl<__Context__> FullLabel for __Context__ +where + Self: HasName + HasTitle, +{ + fn full_label(&self) -> String { /* ... */ } +} +``` + +The supertrait is what callers see; the predicate on the implementation is what lets the body call the +methods. Compare [`#[uses]`](uses.md), which emits only the second of those two, leaving the trait +declaration bare — that single difference is the whole of the distinction. + +On a `#[cgp_component]` the supertrait goes on the consumer trait, and it also joins the `where` clause of +the generated consumer blanket implementation, since that implementation can only apply where the +supertrait holds: + +```rust +pub trait CanGreet: HasName { + fn greet(&self); +} + +impl<__Context__> CanGreet for __Context__ +where + __Context__: HasName, + __Context__: Greeter<__Context__>, +{ + fn greet(&self) { + __Context__::greet(self) + } +} +``` + +Here the result is exactly what `pub trait CanGreet: HasName` would have produced, so on a component +`#[extend]` generates nothing the language cannot already spell. It remains the preferred form for the +reason given above: it presents the bound as an import rather than as inheritance, and it keeps the +`use`/`pub use` pairing with `#[uses]` reading consistently across both macros. + +## Gotchas + +**On a `#[cgp_impl]` the attribute is not recognized at all**, rather than being accepted and ignored. +Nothing consumes it, so it falls through to the compiler as an unknown attribute: + +```text +error: cannot find attribute `extend` in this scope +``` + +Expect a second error alongside it, because the bound was never added: the body's calls to the capability +then fail with `E0599`, reporting that the method exists but its trait bounds were not satisfied. Both +errors have the same cause — move the requirement to [`#[uses]`](uses.md), or onto the component's trait +where supertraits belong. + +**A supertrait cannot be narrowed later.** Because every implementor and every caller may now rely on it, +removing an entry from `#[extend]` is a breaking change in a way removing one from `#[uses]` is not. This +is the practical reason to default to `#[uses]`. + +## Related constructs + +- [`#[uses]`](uses.md) — the same syntax as a private bound on the implementation; the usual choice. +- [`#[extend_where]`](extend_where.md) — a predicate on the generated trait rather than a supertrait. +- [`#[use_type]`](use_type.md) — preferred when the supertrait exists to supply a type. +- [`#[cgp_fn]`](../macros/cgp_fn.md) — where `#[extend]` is the only way to declare a supertrait. +- [`#[cgp_component]`](../macros/cgp_component.md) — where it is preferred over native `:` syntax. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — defines the getter capabilities most often extended. + +## Source + +- Parsing: [`types/attributes/function.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/function.rs) +- On `#[cgp_fn]`: [`types/cgp_fn/preprocessed.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_fn/preprocessed.rs) +- On `#[cgp_component]`: [`types/attributes/cgp_component_attributes.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/cgp_component_attributes.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 4c6a1b28..a24aee0a 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -4,14 +4,217 @@ sidebar_label: '#[extend_where]' # `#[extend_where]` -Add `where` predicates to a generated trait's own definition. +Add `where` predicates to a generated trait's own definition, not just to its implementation. -:::info +## What it's for -### Not written yet +A [`#[cgp_fn]`](../macros/cgp_fn.md) treats the `where` clause you write on the function as an +implementation detail: the bounds land on the generated implementation and never appear on the generated +trait. That default is what keeps a capability's requirements out of sight of its callers, and it is right +almost always. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +What it costs is that an unsatisfiable requirement becomes invisible. A bound on the implementation only +decides *where the implementation applies*, so naming the capability for a type that can never satisfy it +is not an error — it is a bound nobody can prove, accepted quietly, and the complaint arrives later and +somewhere else. `#[extend_where]` moves the predicate onto the trait, where it becomes a condition of +naming the trait at all: + +```rust +#[extend_where(Scalar: Clone)] +``` + +The distinction is worth being exact about, because it is easy to get backwards. Promoting a predicate does +**not** hand it to callers — a trait's `where` clause is a precondition they must prove, not a guarantee +they receive, so a caller naming the trait still writes the bound themselves. What promotion buys is that +they are *made* to, and that getting it wrong is reported against the trait rather than deferred. + +It is the `where`-clause sibling of [`#[extend]`](extend.md). Both put a requirement into the trait's +public interface; they differ in position, and in what the reader gets. `#[extend]` adds a **supertrait** — +a bound on `Self`, which callers do receive by elaboration. `#[extend_where]` adds a **predicate**, which +can bound anything, most usefully one of the trait's own generic parameters, which a supertrait cannot +reach. + +## Using it + +`#[extend_where(...)]` takes a comma-separated list of full `where`-clause predicates: + +```rust +#[extend_where(Scalar: Clone)] +``` + +Unlike [`#[uses]`](uses.md) and [`#[extend]`](extend.md), whose entries are trait bounds attached to `Self`, +these are arbitrary predicates — a bound on any type in scope, including an associated-type equality, a +higher-ranked bound, or a lifetime bound. Each is added to the generated trait's `where` clause verbatim, +and kept on the implementation as well. + +**`#[extend_where]` is supported only on [`#[cgp_fn]`](../macros/cgp_fn.md).** It has no meaning on +[`#[cgp_impl]`](../macros/cgp_impl.md) or [`#[cgp_component]`](../macros/cgp_component.md), because in +those the `where` clause you write is already part of the definition — there is nothing to promote, so +write the bound as an ordinary `where` clause directly. + +## Examples + +A generic capability whose parameter carries a bound that belongs to the contract: + +```rust +use cgp::prelude::*; +use core::ops::Mul; + +#[cgp_fn] +#[extend_where(Scalar: Clone)] +pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar +where + Scalar: Mul, +{ + factor.clone() * factor +} +``` + +Two bounds, two destinations. `Scalar: Clone` is promoted onto the trait, so it is checked wherever +`Scale` is named. `Scalar: Mul` stays on the implementation, because multiplying +is how *this* body happens to compute a scale and no use site needs to know it. + +What the promotion changes is visible at the boundary. A caller naming the capability for a type that +cannot satisfy it is rejected where the bound is written, and told which trait demanded it: + +```rust +pub struct NoClone; + +pub fn scale_it(ctx: &Ctx) -> NoClone +where + Ctx: Scale, // error[E0277]: the trait bound `NoClone: Clone` is not satisfied +{ + ctx.scale() +} +``` + +**Leave `Clone` on the implementation instead and that same function compiles**, with no diagnostic at +all — `Ctx: Scale` is simply a bound no type can ever prove, and nothing says so until somebody +tries to call `scale_it` with a concrete context. That silence is what the attribute exists to remove. + +A caller who *can* satisfy the predicate states it as usual, and there is no way around stating it: + +```rust +pub fn scale_it(ctx: &Ctx) -> Scalar +where + Ctx: Scale, + Scalar: Clone, +{ + ctx.scale() +} +``` + +## When to reach for it, and when not + +**Reach for `#[extend_where]` when a predicate is part of what the capability means**, and you want it +enforced where the trait is named rather than silently narrowing which contexts the implementation covers. +That is a real but uncommon need, and the default of leaving bounds on the implementation is right for +almost everything. + +The useful test is who the bound is *about*. A bound describing how the body computes its answer belongs on +the implementation. A bound describing what the capability requires of its own type parameters — something +that would be part of the signature if you were writing the trait by hand — belongs on the trait. + +Three neighbours cover what this attribute should not be used for. + +- **A bound on `Self`** is a supertrait, so use [`#[extend]`](extend.md). `#[extend_where]` can express it, + but a supertrait reads as what it is, and unlike a predicate it *is* handed to callers by elaboration. +- **A private requirement** — the overwhelmingly common case — belongs in the function's own `where` clause, + or in [`#[uses]`](uses.md) when it is a capability. +- **An abstract type pinned to a concrete one** is [`#[use_type]`](use_type.md)'s equality form, which adds + the bound and lets the signature name the type as a bare word. + +Do not reach for it to spare callers a bound: it has the opposite effect. If the goal is that holding the +capability should imply something, that is what a supertrait does, and the bound has to be on `Self` for it +to work. + +## Under the hood + +:::note + +### Advanced + +This section shows where each predicate lands, and in what order. You do not need it to use +`#[extend_where]`, but the ordering explains a long `where` clause that otherwise looks arbitrary. +`cargo cgp expand` prints the same thing for your own code. ::: + +Each predicate is added to the generated trait's `where` clause, and also kept on the implementation so the +body can rely on it. From the `scale` example above: + +```rust +pub trait Scale +where + Scalar: Clone, +{ + fn scale(&self) -> Scalar; +} + +impl<__Context__, Scalar> Scale for __Context__ +where + Scalar: Mul, + Scalar: Clone, + Self: HasField, +{ + fn scale(&self) -> Scalar { /* ... */ } +} +``` + +The trait carries only the promoted predicate; the function's own bound is absent from it, which is the +default this attribute overrides. + +The implementation carries three, and their **order is fixed**: the function's own `where` clause first, +then whatever the attributes contribute, then the [`HasField`](../traits/has_field.md) bounds from +[`#[implicit]`](implicit.md) arguments, which are always appended last. That order is worth knowing when +reading a long `where` clause in an expansion, since it tells you where each bound came from. + +The context parameter is literally `__Context__` in the emitted code and appears as `Self` inside the +implementation. + +## Gotchas + +**A promoted predicate does not reach callers as a guarantee.** This is the mistake the attribute most +invites: because `#[extend]` gives callers its supertrait, it is natural to assume `#[extend_where]` gives +them its predicate. It does not. Naming a trait whose `where` clause is unproven is an error against the +bound, so a caller generic over the parameter must state the predicate too: + +```text +error[E0277]: the trait bound `Scalar: Clone` is not satisfied + | + | Ctx: Scale, + | ^^^^^^^^^^^^^ the trait `Clone` is not implemented for `Scalar` + | +note: required by a bound in `Scale` +``` + +Adding `Scalar: Clone` to the caller's own `where` clause is the fix, and is expected rather than a +workaround. + +**On any host other than `#[cgp_fn]` the attribute is not recognized**, rather than accepted and ignored. +Nothing consumes it, so it reaches the compiler as an unknown attribute: + +```text +error: cannot find attribute `extend_where` in this scope +``` + +On a [`#[cgp_component]`](../macros/cgp_component.md) or [`#[cgp_impl]`](../macros/cgp_impl.md) the fix is +to delete the attribute and write the predicate in the definition's own `where` clause, where it already +has the effect this attribute exists to produce elsewhere. + +## Related constructs + +- [`#[extend]`](extend.md) — the supertrait sibling, and the one callers do receive. +- [`#[uses]`](uses.md) — a private capability bound on the implementation. +- [`#[use_type]`](use_type.md) — for pinning an abstract type, which this could express but should not. +- [`#[cgp_fn]`](../macros/cgp_fn.md) — the only host, and the reason the attribute exists. +- [`#[implicit]`](implicit.md) — contributes the bounds that always sort last. + +## Source + +- Parsing: [`types/attributes/function.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/function.rs) +- Injection into both `where` clauses: [`types/cgp_fn/preprocessed.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_fn/preprocessed.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index de0866ab..248a24ad 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -6,12 +6,265 @@ sidebar_label: '#[implicit]' Source a function argument from a same-named field on the context. -:::info +## What it's for -### Not written yet +Reading a value out of the surrounding type is most of what CGP code does, and `#[implicit]` is what +makes it look like an ordinary function parameter. You mark a parameter, and it disappears from the +signature callers see — the value is read from a field of the same name on the **context**, the type the +capability runs against: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +`rect.rectangle_area()` takes no arguments. Any type carrying a `width` and a `height` can call it. + +The alternative, without the attribute, is to declare that the context has those fields and then fetch +each one by hand — which means meeting a field-access trait, a type-level name for each field, and a +`PhantomData` tag before writing a single line of the calculation. `#[implicit]` keeps all of that behind +a parameter that reads as `width: f64`, and the parameter's *name* is what names the field. + +That is why it is the recommended way to read a context's own field, and why it is usually the first +piece of CGP anyone writes. Nothing about it is unfamiliar: a reader who understands functions and +arguments can write a working capability and meet the machinery later, when they have a reason to care. + +## Using it + +`#[implicit]` is a bare marker on a typed parameter. It takes no arguments in any form, and a list or +name-value spelling is rejected rather than ignored: + +```rust +fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +It is meaningful inside the two macros that rewrite a function body into an implementation — +[`#[cgp_fn]`](../macros/cgp_fn.md) and the methods of a [`#[cgp_impl]`](../macros/cgp_impl.md) block. It +is not a macro of its own, so it does nothing on an ordinary function. + +Three rules constrain where it may appear. The function must take `self` first, since the field is read +from `self`. The parameter must be a bare identifier rather than a destructuring or `mut` pattern — to +get a mutable local, clone the value inside the body. And a **mutable** implicit argument must be the +only implicit argument on its function and requires a `&mut self` receiver, because reading a field +mutably borrows the whole context exclusively and cannot coexist with any other field read. Immutable +arguments carry no such restriction and combine freely, in any number, on either receiver. + +### How the parameter's type decides the read + +The parameter's type is what the body works with, and the macro inserts whatever conversion bridges it to +the stored field. This is the whole of the mapping: + +| The parameter's type | The field's type | How it is read | +|---|---|---| +| An owned type — `f64`, `String`, a tuple, an array | the same type | by reference, then `.clone()` | +| `&T` | `T` | by reference, no conversion | +| `&str` | `String` | `.as_str()` | +| `&[T]` | anything `AsRef<[T]>` | `.as_ref()` | +| `Option<&T>` | `Option` | `.as_ref()` | +| `Option<&str>` | `Option` | `.as_deref()` | +| `&mut T` | `T` | mutably, no conversion | +| `&mut [T]` | anything `AsMut<[T]>` | `.as_mut()` | +| `Option<&mut T>` | `Option` | `.as_mut()` | +| `Option<&mut str>` | `Option` | `.as_deref_mut()` | + +Two of those rows are worth reading twice. `&str` is the case most often wanted and least obvious: the +field is a `String`, and the argument borrows from it, so a context never has to store a `&str`. And an +owned parameter *clones* — cheap for an `f64`, less so for a large `String`, which is a reason to take +`&str` or `&T` wherever the body only needs to read. + +Mutability follows the *argument's* type rather than the receiver's. An argument carrying a `&mut` reads +mutably; every other argument reads through a shared borrow, even on a `&mut self` method. + +The same rules govern the getter traits, so learning them once covers everywhere CGP reads a field. + +## Examples + +A complete capability, and a context that qualifies for it by having the right fields: + +```rust +use cgp::prelude::*; + +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +pub fn print_area(rect: &Rectangle) { + println!("area = {}", rect.rectangle_area()); +} +``` + +`Rectangle` derives [`HasField`](../derives/derive_has_field.md), which is its entire qualification. +There is no wiring anywhere in this program. + +Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) provider the attribute behaves identically, and mixes +freely with the method's real arguments — the implicit ones vanish from the signature while `to` and +`body` remain: + +```rust +#[cgp_impl(new SendViaSmtp)] +impl EmailSender { + fn send_email(&self, #[implicit] smtp_server: &str, to: &str, body: &str) { + // connect to `smtp_server` and send the message + } +} +``` + +Callers still write `app.send_email(to, body)`. What the provider needs from its context — an +`smtp_server` field, here borrowed as a `&str` from a `String` — never appears in the trait everyone else +calls. + +## When to reach for it, and when not + +**Reach for `#[implicit]` by default whenever a provider needs a value from its own context.** It is the +shortest form, it introduces no new declaration, and it uses the same field access a getter would, so a +getter trait declared only to read a field adds a name without buying anything. + +That covers more ground than it first appears. An implicit argument reads a plain `&T` by reference with +no clone, so it suits a large value as well as a small one; and a field that several providers each need +is simply declared as the same implicit argument in each of them, which costs nothing and keeps every +provider's requirements visible where the provider is written. + +A **getter trait** earns its keep in the three cases an implicit argument cannot reach. + +- **The field is on a different type.** An implicit argument reads only from `self`, so a value living on + a request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type — + there is no `self` field to read. +- **The accessor must be a named capability.** When other code depends on "this context can tell you its + name" rather than on a field, that dependency needs a trait to point at, importable with + [`#[uses]`](uses.md) or usable as a supertrait. +- **The getter carries a type inferred from the field.** A getter may declare an associated type and + return it, which keeps the type abstract for callers in a way a concrete parameter cannot. + +For those, use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md), which generates the getter from the +method name. [`#[cgp_getter]`](../macros/cgp_getter.md) goes further still and is genuinely advanced: +reach for it only when the *field a getter reads* should be chosen per context at wiring time. + +## Under the hood + +:::note + +### Advanced + +This section shows what the attribute injects. You do not need it to use `#[implicit]`, but an +unsatisfied field requirement names the generated bound rather than your parameter, so reading one makes +those errors much easier to follow. `cargo cgp expand` prints the same thing for your own code. ::: + +Each marked parameter becomes two things: a field bound on the generated implementation, and a `let` +binding at the top of the body. From this input: + +```rust +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +the parameters are stripped from the trait's method and reappear as +[`HasField`](../traits/has_field.md) bounds and reads: + +```rust +pub trait RectangleArea { + fn rectangle_area(&self) -> f64; +} + +impl<__Context__> RectangleArea for __Context__ +where + Self: HasField + + HasField, +{ + fn rectangle_area(&self) -> f64 { + let width: f64 = self + .get_field(PhantomData::) + .clone(); + let height: f64 = self + .get_field(PhantomData::) + .clone(); + + width * height + } +} +``` + +The bindings are inserted in argument order, ahead of every original statement, so the names are in scope +for the whole body. [`Symbol!("width")`](../macros/symbol.md) is a type-level string standing for the +field name; the compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and +`cargo cgp expand` resugars it back. The context parameter is literally `__Context__`, a reserved name +chosen so it cannot collide with one of yours. + +Two shapes in the table above generate something other than a `Value = T` equality, which is worth +recognizing because it reads oddly at first. A slice argument bounds the *associated type* instead, so +`&[u8]` emits `HasField + 'static>` — any field whose value can be +viewed as a `[u8]` qualifies, rather than one exact type. And every mutable form swaps the trait as well +as the accessor: `&mut u64` emits `HasFieldMut` and reads through +`get_field_mut`. + +Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the rewrite is the same, with the bounds joining +that provider's `where` clause instead. + +## Gotchas + +**The attribute takes no arguments**, and says so rather than ignoring what it was given: + +```text +error: `#[implicit]` does not take any arguments; write it as a bare `#[implicit]` +``` + +**The parameter must be a plain identifier.** A destructuring pattern reports `Expected an identifier`, +and a `mut` binding is rejected with the fix in the message: + +```text +error: Mutable variables are not allowed in implicit arguments. (Explicitly clone a `&` reference if you + want a mutable local copy of the value) +``` + +**A function with implicit arguments must take `self` first**, since there is otherwise no context to +read from: + +```text +error: The first argument of a function with implicit arguments must be `self` +``` + +**A mutable argument needs a `&mut self` receiver, and must be the only implicit argument.** The two +mistakes report separately: + +```text +error: &mut self is required for mutable field reference `& mut u64` + +error: a `&mut` implicit argument must be the only implicit argument, since its mutable + borrow of the context conflicts with reading any other field +``` + +## Related constructs + +- [`#[cgp_fn]`](../macros/cgp_fn.md) — the usual host, turning a function into a capability. +- [`#[cgp_impl]`](../macros/cgp_impl.md) — the other host, for a component's provider. +- [`#[derive(HasField)]`](../derives/derive_has_field.md) — what a context derives to qualify. +- [`HasField`](../traits/has_field.md) — the trait the generated bounds are written against. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — the getter form, for the cases above. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — a getter whose source field is chosen by wiring. +- [`#[uses]`](uses.md) — imports a capability rather than a value. +- [`#[use_type]`](use_type.md) — imports a type rather than a value; the third of the three. +- [`Symbol!`](../macros/symbol.md) — the type-level field name the bounds are keyed on. + +## Source + +- Parsing: [`functions/implicits/parse.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/implicits/parse.rs) +- Bounds and bindings: [`types/implicits/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/implicits/) +- Access-mode mapping: [`functions/field/parse.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/field/parse.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index c65d2c85..a3cc2582 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -4,14 +4,278 @@ sidebar_label: '#[use_provider]' # `#[use_provider]` -Complete an inner provider's bound in a higher-order provider. +Depend on another implementation by name, without writing the context argument its bound requires. -:::info +## What it's for -### Not written yet +An implementation can be parameterized by *another* implementation — a wrapper that scales whatever an +inner calculator produces, a retry layer over whatever performs the request. Declaring that dependency +means bounding the inner one, and the bound has a surprise in it. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +A [provider trait](../macros/cgp_component.md) is not shaped like the trait it came from: the original +`Self` has moved into an explicit leading type parameter for the **context**, the type the implementation +runs against. So while callers write `CanCalculateArea`, an implementation depending on another one has to +write `AreaCalculator` — with a context argument that has no counterpart in the consumer trait, and +that a reader will not expect: + +```rust +where + InnerCalculator: AreaCalculator, +``` + +`#[use_provider]` lets you leave that argument off. You write the bound as though the provider trait had +the same shape as the trait it came from, and the macro fills the context in: + +```rust +#[use_provider(InnerCalculator: AreaCalculator)] +``` + +That is the whole of what it does, and knowing the boundary matters: **it completes and inserts a bound, +and it does not touch the body.** The inner implementation is still invoked as an associated function with +the context passed explicitly — `InnerCalculator::area(self)` — because that is what the provider trait's +method actually takes. The attribute removes the surprise from the bound; the call site keeps it. + +## Using it + +`#[use_provider(...)]` takes a provider, a colon, and the trait bounds it must satisfy: + +```rust +#[use_provider(InnerCalculator: AreaCalculator)] +``` + +`InnerCalculator` is the provider — usually a generic parameter of the implementation — and +`AreaCalculator` is the provider trait whose context argument is filled in. The trait may carry further +arguments of its own after the context slot, and those are preserved in order behind the inserted context. + +Two forms cover more than one bound, and which you need depends on what is being multiplied. + +**One provider, several traits — join them with `+`:** + +```rust +#[use_provider(Inner: AreaCalculator + PerimeterCalculator)] +``` + +**Several providers — one attribute each, stacked:** + +```rust +#[use_provider(A: AreaCalculator)] +#[use_provider(P: PerimeterCalculator)] +``` + +Stacking is the intended form here rather than a fallback, because a comma-separated list of +provider-and-trait pairs is *not* accepted — see [Gotchas](#gotchas). This differs from +[`#[uses]`](uses.md) and [`#[use_type]`](use_type.md), where commas are the preferred way to carry several +entries, so it is worth remembering as the exception. + +`#[use_provider]` is accepted on [`#[cgp_impl]`](../macros/cgp_impl.md) and on +[`#[cgp_fn]`](../macros/cgp_fn.md), and it works the same way on both. + +## Examples + +The archetypal use is a wrapper parameterized by whatever it wraps. Given a component and a plain +implementation of it: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} +``` + +a scaling wrapper takes the inner implementation as a parameter, declares it with `#[use_provider]`, and +calls it by name: + +```rust +#[cgp_impl(new ScaledArea)] +#[use_provider(InnerCalculator: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + let base_area = InnerCalculator::area(self); + base_area * scale_factor * scale_factor + } +} +``` + +A context then composes the two when it wires the component, and `ScaledArea` computes a +rectangle's area and scales it: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: ScaledArea, + } +} +``` + +Because the wrapper never names a particular inner implementation, the same `ScaledArea` composes over any +of them — and composition is a type, so `type ScaledRectangle = ScaledArea;` is a complete +way to name the combination. + +The attribute is also useful for depending on one *specific* implementation rather than a parameter, which +is what a [`#[cgp_fn]`](../macros/cgp_fn.md) does when it wants a named implementation instead of whatever +the context has wired: + +```rust +#[cgp_fn] +#[use_provider(RectangleArea: AreaCalculator)] +pub fn rect_area(&self) -> f64 { + RectangleArea::area(self) +} +``` + +## When to reach for it, and when not + +**Use `#[use_provider]` whenever an implementation depends on another implementation by name**, in +preference to writing the context argument by hand. That is the recommendation, and the explicit +`Inner: AreaCalculator` form is what to read rather than write. + +The choice against its neighbours is about *what* is being depended on, and one of the distinctions is +easy to miss because both spellings compile. + +- **A capability of the context** is [`#[uses]`](uses.md). That bound is on `Self`; this one is on a + separate provider type, which is why `#[uses]` has no context argument to fill in. +- **Whatever the context already chose** needs no attribute at all. Calling `self.area()` in the body + routes through the context's own wiring, which is a *different dispatch* from + `InnerCalculator::area(self)` — the first asks the context, the second names an implementation + statically. Reach for `#[use_provider]` only when you want the second. +- **A choice made per type rather than fixed** is dispatch rather than parameterization, so it belongs in + the wiring: the `open` statement of [`delegate_components!`](../macros/delegate_components.md) maps each + type to its own implementation. + +One ergonomic option is worth knowing when writing the provider struct by hand: giving the parameter a +default of [`UseContext`](../providers/use_context.md) — `pub struct IterSum(...)` — +makes an unparameterized `IterSum` fall back to the context's own wiring, so the wrapper can be dropped in +without naming a base case. + +## Under the hood + +:::note + +### Advanced + +This section shows the bound the attribute produces. You do not need it to use `#[use_provider]`, but the +inserted argument is exactly what an unsatisfied inner dependency names in an error, so it is worth seeing +once. `cargo cgp expand` prints the same thing for your own code. ::: + +The attribute inserts the context type as the provider trait's leading argument and appends the completed +bound to the `where` clause. Nothing else changes — the body is emitted as written. From the `ScaledArea` +example: + +```rust +#[cgp_impl(new ScaledArea)] +#[use_provider(InnerCalculator: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } +} +``` + +the macro emits the provider implementation with the argument filled in: + +```rust +impl<__Context__, InnerCalculator> AreaCalculator<__Context__> + for ScaledArea +where + __Context__: HasField, + InnerCalculator: AreaCalculator<__Context__>, +{ + fn area(__context__: &__Context__) -> f64 { + let scale_factor: f64 = __context__ + .get_field(PhantomData::) + .clone(); + + InnerCalculator::area(__context__) * scale_factor * scale_factor + } +} +``` + +The `Self` you wrote in the attribute is the context, so it appears as `__Context__` here — the reserved +name the surrounding macro inserted. Writing `#[use_provider(InnerCalculator: AreaCalculator)]` is +therefore exactly equivalent to writing `where InnerCalculator: AreaCalculator` by hand. + +On a [`#[cgp_fn]`](../macros/cgp_fn.md) the same insertion happens, and because that macro's +implementation is written *for* the context the bound reads with `Self` directly: + +```rust +impl<__Context__> RectArea for __Context__ +where + RectangleArea: AreaCalculator, +{ + fn rect_area(&self) -> f64 { + RectangleArea::area(self) + } +} +``` + +Note that the body is untouched in both. The call stays `InnerCalculator::area(__context__)`, passing the +context as the first argument, because that is the shape the provider trait's method has. + +## Gotchas + +**A comma-separated list of pairs is not accepted.** Writing two providers in one attribute is a parse +error, because after the first trait the parser is looking for a `+` to continue that provider's bounds: + +```text +error: expected `+` + | + | #[use_provider(A: AreaCalculator, P: PerimeterCalculator)] + | ^ +``` + +Use one attribute per provider instead. This is the opposite of the convention for +[`#[uses]`](uses.md) and [`#[use_type]`](use_type.md), which do take comma-separated lists, so the habit +transfers wrongly. + +**The provider and the trait are both required.** There is no bare form naming a provider alone, and +omitting the bound reports the missing colon: + +```text +error: expected `:` + | + | #[use_provider(RectangleArea)] + | ^ +``` + +**There is no call-site rewriting.** The attribute never turns `self.area()` into +`InnerCalculator::area(self)`, so a body that calls the method on `self` compiles but does something +different: it dispatches through the context's own wiring rather than through the parameter. When the +intent is to use the inner implementation, spell out the associated-function call. + +## Related constructs + +- [`#[cgp_impl]`](../macros/cgp_impl.md) and [`#[cgp_fn]`](../macros/cgp_fn.md) — the two hosts. +- [`#[cgp_component]`](../macros/cgp_component.md) — generates the provider trait whose argument is filled in. +- [`#[uses]`](uses.md) — the counterpart for a bound on the context rather than on a provider. +- [`UseContext`](../providers/use_context.md) — the usual default for an inner-provider parameter. +- [`delegate_components!`](../macros/delegate_components.md) — where a composed wrapper is wired. +- [`check_components!`](../macros/check_components.md) — its `#[check_providers(...)]` form checks each + layer of a nested stack separately, which is how a broken layer is localized. + +## Source + +- Parsing and bound completion: [`types/attributes/use_provider/attribute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/use_provider/attribute.rs) +- Collection: [`types/attributes/cgp_impl_attributes.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/cgp_impl_attributes.rs) + and [`types/attributes/function.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/function.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index b19fba5b..ff176ffa 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -6,12 +6,368 @@ sidebar_label: '#[use_type]' Import an abstract associated type and write it as a bare name. -:::info +## What it's for -### Not written yet +Generic CGP code constantly needs a type it does not choose — an error type, a scalar, a database handle — +supplied by the **context**, the type the code runs against. Such a type lives as an +[associated type](https://doc.rust-lang.org/reference/items/associated-items.html) on another trait, and +Rust requires every mention of it to be written out in full: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +fn load(&self, path: &str) -> Result::Error>; +``` + +That is correct and almost unreadable, and it has to be repeated at every occurrence — the return type, +each argument, each local binding. `#[use_type]` imports the type once so the signature can name it +plainly: + +```rust +#[use_type(HasErrorType.Error)] +``` + +With that in place the same method reads `-> Result`, and the macro expands each bare +`Error` back into the qualified path while adding the bound that makes it available. The bare name behaves +like an ordinary type in your source and resolves to the associated type in the output. + +Reading better is the obvious benefit; the less obvious one is that the qualified form composes where a +bare one cannot. Because the macro always emits `::Type`, one import can be defined in +terms of another, a type can be pulled from a parameter rather than from `Self`, and two abstract types can +be constrained to be the same — none of which you can express by writing a bare identifier and hoping. +Those are the [advanced forms](#importing-from-another-type) below. + +## Using it + +Apply `#[use_type]` beside the macro it modifies, naming a trait and the associated type to import: + +```rust +#[use_type(HasScalarType.Scalar)] +``` + +The part before the `.` is the trait and the identifier after it is the type. The **separator is a dot, +not `::`**, and that is deliberate: it leaves `::` free for the trait's own path, so +`#[use_type(errors::HasErrorType.Error)]` imports from a trait named by path and +`#[use_type(HasFooType.Foo)]` imports from a particular generic instantiation. + +By default the type is projected from `Self`, so `Scalar` expands to `::Scalar`. + +The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md), +[`#[cgp_impl]`](../macros/cgp_impl.md), and [`#[cgp_component]`](../macros/cgp_component.md). + +### Importing several types + +Separate entries with commas, and **prefer one attribute carrying the whole list**, since it reads as a +single import list: + +```rust +#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasErrorType.Error)] +``` + +Several types from the same trait go in a braced group, and any entry may be renamed with `as` to give it +a local alias: + +```rust +#[use_type(HasFooType.{Foo, Bar as Baz})] +``` + +Stacking several `#[use_type]` attributes behaves identically, because every attribute's entries are +collected into one list before any of them is resolved — so an alias declared in one is available to +another regardless of which comes first. Reach for a second attribute only when there is a reason. + +### Pinning a type to a concrete one + +An `= Type` clause imports the type *and* constrains it, which is how a provider says "this only works when +the error type is `AppError`": + +```rust +#[use_type(HasErrorType.{Error = AppError})] +``` + +That emits `Self: HasErrorType` in place of the plain bound. The right-hand side is +itself substituted, so it may name another import — which is how two abstract types are tied together: + +```rust +#[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})] +``` + +The pin is an implementation-side constraint, so it is **rejected on +[`#[cgp_component]`](../macros/cgp_component.md)**, whose trait definition has nowhere to put it. + +### Importing from another type + +A trailing `in Context` clause changes what the type is projected from, so an import can reach a type on a +parameter rather than on `Self`: + +```rust +#[use_type(HasScalarType.Scalar in Types)] +``` + +`Scalar` now expands to `::Scalar`. The clause scopes over the whole entry, so a +braced group projects every type in it against the same target, and because `in` is a reserved word it can +never be mistaken for a type name. + +This is also the form that lets an import parameterize the trait it comes from. An alias may appear in +another entry's `in` clause *or* in its trait arguments, and the macro resolves the chain for you: + +```rust +#[use_type(HasDbType.Db, HasPoolType.Pool)] +``` + +Here `Pool` is projected from `HasPoolType<::Db>`. Such chains may be written in any +order — see [Under the hood](#under-the-hood) — provided they do not form a cycle. + +## Examples + +One abstract scalar threaded through a component and a provider, with neither writing `Self::` anywhere: + +```rust +use cgp::prelude::*; +use core::ops::Mul; + +#[cgp_type] +pub trait HasScalarType { + type Scalar: Clone + Mul; +} + +#[cgp_component(AreaCalculator)] +#[use_type(HasScalarType.Scalar)] +pub trait CanCalculateArea { + fn area(&self) -> Scalar; +} + +#[cgp_impl(new RectangleArea)] +#[use_type(HasScalarType.Scalar)] +impl AreaCalculator { + fn area(&self, #[implicit] width: Scalar, #[implicit] height: Scalar) -> Scalar { + width * height + } +} +``` + +The component gains `HasScalarType` as a supertrait and the provider gains it as a bound, and every +`Scalar` in both becomes the same qualified projection — so the fields the provider reads and the value it +returns are guaranteed to agree on whatever scalar the context chose. + +A context supplies the concrete type by wiring, and nothing above changes: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + ScalarTypeProviderComponent: UseType, + AreaCalculatorComponent: RectangleArea, + } +} +``` + +The most common use of all is an error type, where the import saves a projection in every fallible +signature: + +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} +``` + +## When to reach for it, and when not + +**Use `#[use_type]` whenever a definition names an abstract type another component supplies.** It is the +recommended form, and a hand-written supertrait plus `Self::`-qualified paths is what to read rather than +write. + +Two neighbours cover requirements that are not types, and one construct is what `#[use_type]` imports +*from*. + +- **A capability** is [`#[uses]`](uses.md) for a private bound or [`#[extend]`](extend.md) for a + supertrait. Reach for `#[extend]` specifically when the supertrait's methods are what matter and its + associated types are not named in your signatures — that is the case `#[use_type]` has nothing to + rewrite. +- **A value from a field** is an [`#[implicit]`](implicit.md) argument. +- **The type itself** is declared with [`#[cgp_type]`](../macros/cgp_type.md) and bound to a concrete type + by wiring the component to [`UseType`](../providers/use_type.md). Note that the `UseType` *provider* + and this *attribute* are different things despite the shared name: the provider supplies a type to a + context, and the attribute imports one into a definition. + +There is one boundary worth stating plainly, because getting it wrong produces a confusing error. A +construct's **own** associated type is not imported and stays qualified as `Self::Output`. `#[use_type]` +rewrites only the names it was given, so a local type written bare resolves to nothing. A mixed signature +such as `Result` is therefore correct and idiomatic — the local type qualified, the +imported one bare. + +Finally, prefer an inferred parameter over an abstract type when the type only ever flows through values +the body reads: [`#[impl_generics]`](../macros/cgp_fn.md) on a `#[cgp_fn]` is shorter and needs no wiring. +Climb to an abstract type when the type must be named in the capability's own signature, or when two +capabilities have to agree that they mean the same one. + +## Under the hood + +:::note + +### Advanced + +This section shows the three steps the attribute performs and what each one touches. You do not need it to +use `#[use_type]`, but the substitution has edges worth knowing, and an unmet import names the generated +bound rather than your import. `cargo cgp expand` prints the same thing for your own code. ::: + +`#[use_type]` runs before the surrounding macro, in three steps: it **grounds** each import's own type +positions, **substitutes** every matching bare identifier, then **adds the bound**. + +From this input: + +```rust +#[cgp_fn] +#[use_type(HasScalarType.Scalar)] +pub fn area(&self, #[implicit] width: Scalar, #[implicit] height: Scalar) -> Scalar { + width * height +} +``` + +the effective result is: + +```rust +pub trait Area: HasScalarType { + fn area(&self) -> ::Scalar; +} + +impl<__Context__> Area for __Context__ +where + Self: HasField::Scalar> + + HasField::Scalar>, + Self: HasScalarType, +{ + fn area(&self) -> ::Scalar { /* ... */ } +} +``` + +**Where the bound lands depends on the target.** When the type is projected from `Self` it becomes a +*supertrait* of the generated trait, and also a `where` bound on the implementation. When an `in Context` +clause names some other type, a supertrait of `Self` would be wrong, so the macro adds a plain +`Context: Trait` predicate — to the implementation, and on `#[cgp_fn]` and `#[cgp_component]` to the +generated trait's own `where` clause as well, since the trait's signatures now mention the projection and +would not otherwise be well-formed. A plain unbounded `` on your function is therefore enough: + +```rust +pub trait AreaOf +where + Types: HasScalarType, +{ + fn area_of(&self) -> ::Scalar; +} +``` + +An equality pin is the exception: it stays on the implementation and is never added to the trait. + +**What substitution touches.** The rewrite matches a single-segment type path with no arguments whose +identifier is an imported name or alias, anywhere it appears — a return type, an argument, a `where` +predicate, a local binding. It also reaches an alias used to *qualify* a path, so `Transaction::begin()` +becomes `<::Transaction>::begin()`, since `::Assoc::method` is +not valid syntax. + +The one position left alone is a **bare alias in expression position**, which names a value — something an +abstract type can never be. So an alias sharing its name with a unit struct still constructs the struct: + +```rust +let value = Marker; // stays the unit struct `Marker` +let typed: Marker = todo!(); // becomes ::Marker +``` + +**Grounding, and why order does not matter.** Each import is resolved against the imports it *depends on* +rather than the ones written before it, so every arrangement of the same entries produces the same +substitutions and the same bounds. Only the order the bounds are listed in follows the source. A chain like +`#[use_type(HasC.C in B, HasB.B in A, HasA.A)]` grounds exactly as its front-to-back spelling does, +and two imports may share one target as readily as chain through it. What has no valid order is a +**cycle** — see the Gotchas. + +
+Formal grammar + +The tokens inside `#[use_type(...)]`, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +UseTypeArgs -> UseTypeSpec ( `,` UseTypeSpec )* `,`? + +UseTypeSpec -> TraitPath `.` TypeItems ( `in` ContextPath )? + +ContextPath -> TypePath +TraitPath -> TypePath + +TypeItems -> UseTypeIdent + | `{` UseTypeIdent ( `,` UseTypeIdent )* `,`? `}` + +UseTypeIdent -> IDENTIFIER ( `as` IDENTIFIER )? ( `=` Type )? +``` + +`TraitPath` and `ContextPath` are ordinary Rust `TypePath`s, whose final segment may carry generic +arguments; their `::` segments belong to the path, while the `.` after the trait begins the +associated-type list. An omitted `in ContextPath` defaults the target to `Self`. In each `UseTypeIdent` +the leading `IDENTIFIER` is the associated type's own name, `as` gives it a local alias to write in +signatures, and `= Type` pins it with an equality bound — accepted on `#[cgp_fn]` and `#[cgp_impl]`, +rejected on `#[cgp_component]`. + +
+ +## Gotchas + +**Two imports may not share a name or alias.** The substitution could only pick one, so a collision is +rejected rather than resolved: + +```text +error: Multiple abstract types cannot share the same identifier or alias +``` + +**Imports may not resolve through one another in a cycle.** An `in` clause or a trait argument may name +another import only if the resulting chain is acyclic, and the message names the loop: + +```text +error: cannot ground `#[use_type]` imports: they resolve through one another in a cycle `B` -> `A` -> `B`. +An `in Context` clause or a trait argument may name another import's alias only if the resulting chain is +acyclic, since a cycle has no valid grounding order. +``` + +A self-referential import such as `#[use_type(HasAType.A in A)]` is the degenerate case and reports the +same way. + +**An equality pin is rejected on a component trait**, since a trait definition cannot carry an +implementation-side constraint: + +```text +error: Type equality constraints cannot be used in component trait definition +``` + +Pin the type on the provider with [`#[cgp_impl]`](../macros/cgp_impl.md) instead, or on a +[`#[cgp_fn]`](../macros/cgp_fn.md). + +**A construct's own associated type must stay qualified.** Writing a local `type Output` as a bare +`Output` leaves an identifier the substitution has no entry for, so it resolves to nothing. Write +`Self::Output`, and do not list it in a `#[use_type]` attribute. + +## Related constructs + +- [`#[cgp_type]`](../macros/cgp_type.md) — declares the abstract-type component this imports from. +- [`UseType`](../providers/use_type.md) — the provider a context wires to supply the concrete type; a + different thing from this attribute despite the name. +- [`HasType`](../components/has_type.md) — the built-in abstract-type component underneath. +- [`#[uses]`](uses.md) — imports a capability rather than a type. +- [`#[extend]`](extend.md) — adds a supertrait without rewriting any type names. +- [`#[implicit]`](implicit.md) — imports a value from a field. +- [`#[cgp_fn]`](../macros/cgp_fn.md), [`#[cgp_impl]`](../macros/cgp_impl.md), and + [`#[cgp_component]`](../macros/cgp_component.md) — the three hosts. + +## Source + +- Parsing: [`types/attributes/use_type/attribute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/use_type/attribute.rs) +- Grounding, substitution and bounds: [`types/attributes/use_type/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/use_type/) +- The substitution pass: [`visitors/substitute_abstract_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/visitors/substitute_abstract_type.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 21f789e7..41e09431 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -4,14 +4,229 @@ sidebar_label: '#[uses]' # `#[uses]` -Import the capabilities a provider depends on, reading like a `use` statement. +Import the capabilities an implementation depends on, reading like a `use` statement. -:::info +## What it's for -### Not written yet +An implementation usually calls capabilities defined elsewhere, and to do so it has to require that the +**context** — the type it runs against — provides them. Written out, that requirement is a bound on +`Self`: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +where + Self: RectangleArea, +``` + +Bounding `Self` is unusual in everyday Rust and reads as machinery rather than as intent. `#[uses]` says +the same thing in the register the code is actually in: + +```rust +#[uses(RectangleArea)] +``` + +That reads as *this implementation uses the `RectangleArea` capability*, which is what a `use` statement +means for a name, and the body can then call `self.rectangle_area()` as though the capability had been +imported. + +The two forms generate exactly the same bound, so nothing is gained or lost mechanically. What changes is +that the dependency list stops looking like a constraint the author had to satisfy and starts looking like +a list of what the code needs — which is the reason `#[uses]` is the recommended form and a hand-written +`where Self: Trait` is what you meet in older code. + +One property of that bound is worth naming, because it is the whole point of putting the dependency on +the implementation. It lands on the implementation *only*, never on the trait, so a caller who bounds on +the capability never sees it and never has to repeat it. What an implementation needs is its own business. + +## Using it + +`#[uses(...)]` takes a comma-separated list of bounds, each becoming a `Self:` predicate on the generated +implementation: + +```rust +#[uses(RectangleArea, CanCalculateArea)] +``` + +Each entry is a capability, optionally with type arguments — a bare `RectangleArea` becomes +`Self: RectangleArea`, and `CanCompute` becomes `Self: CanCompute`. + +**The trait need not be a CGP construct.** `#[uses(Display)]` and `#[uses(AsRef<[u8]>)]` are accepted and +preferred over the equivalent hand-written clause: the attribute only cares that the bound is one a +context can satisfy, so an ordinary Rust trait imports exactly as a capability does. + +**Prefer one attribute carrying every dependency** — `#[uses(RectangleArea, Display)]` — since a single +list reads as a single set of requirements. Entries may also be split across several `#[uses(...)]` +attributes on the same item and they accumulate into one bound, but reach for a second attribute only +when there is a reason rather than by default. + +`#[uses(...)]` is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on +[`#[cgp_impl]`](../macros/cgp_impl.md). In both it imports into the thing being defined, and it does not +care how the imported capability was itself produced. + +### Bounds beyond the simple form + +The idiomatic entry is a plain `Trait`, because the attribute is meant to read as an import. An +entry may nonetheless be any bound a `where` clause accepts — an associated-type equality such as +`HasErrorType`, a higher-ranked bound, a lifetime bound — and it lands on the +`where` clause verbatim. + +Use that generality sparingly, and prefer a more specific tool where one exists. To pin an abstract type +to a concrete one, [`#[use_type]`](use_type.md)'s equality form +`#[use_type(HasErrorType.{Error = anyhow::Error})]` adds the same bound *and* lets the signature name the +type as a bare `Error`. To put a bound on the generated trait rather than only on its implementation, use +[`#[extend]`](extend.md) for a supertrait or [`#[extend_where]`](extend_where.md) for a predicate. + +## Examples + +A capability built on top of a component, without knowing which provider supplies it: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_fn] +#[uses(CanCalculateArea)] +pub fn scaled_area(&self, #[implicit] scale_factor: f64) -> f64 { + self.area() * scale_factor * scale_factor +} +``` + +`#[uses(CanCalculateArea)]` is what makes `self.area()` legal. The dependency is on the *consumer* trait +rather than on any particular provider, so every context that can calculate an area gets `scaled_area` +regardless of how it does so — and a context that swaps its area provider keeps `scaled_area` working +unchanged. + +The same attribute inside a provider, this time importing a plain function-style capability: + +```rust +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} + +#[cgp_impl(new RectangleAreaCalculator)] +#[uses(RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + self.rectangle_area() + } +} +``` + +This provider is a two-line adapter: it satisfies the `AreaCalculator` component by deferring to whatever +`rectangle_area` computes. Any context with the fields that capability needs can wire it. + +## When to reach for it, and when not + +**Use `#[uses]` for every capability dependency**, in preference to writing the `Self:` bound by hand. +That is the recommendation, and the hand-written form is what to read rather than write. + +The distinction that decides between `#[uses]` and its neighbours is *what* is being depended on and +*where the requirement should be visible*. + +- **A value from the context** is not a capability. Use an [`#[implicit]`](implicit.md) argument, which + reads a field directly rather than routing through a trait. +- **A type from the context** is imported with [`#[use_type]`](use_type.md), which adds the bound and + additionally lets the signature write the type as a bare name instead of a qualified path. +- **An inner provider** in a higher-order provider needs [`#[use_provider]`](use_provider.md), because a + provider trait carries a context argument that `#[uses]` would not fill in. +- **A requirement callers should see** belongs on the trait rather than on the implementation: + [`#[extend]`](extend.md) makes it a supertrait, and [`#[extend_where]`](extend_where.md) a predicate. + `#[uses]` is for what the implementation needs privately, which is the `use` to their `pub use`. + +## Under the hood + +:::note + +### Advanced + +This section shows what the attribute injects. You do not need it to use `#[uses]`, but it is a short +rewrite and seeing it once explains why the bound never appears on the trait. `cargo cgp expand` prints +the same thing for your own code. ::: + +Every entry becomes one `Self`-anchored predicate on the generated implementation, joined with `+`, and +nothing else changes. From this input: + +```rust +#[cgp_fn] +#[uses(BaseArea, Display)] +pub fn describe_area(&self) -> String { + format!("{} for {}", self.base_area(), self) +} +``` + +the trait is emitted exactly as it would have been without the attribute, and the implementation carries +the imports: + +```rust +pub trait DescribeArea { + fn describe_area(&self) -> String; +} + +impl<__Context__> DescribeArea for __Context__ +where + Self: BaseArea + Display, +{ + fn describe_area(&self) -> String { /* ... */ } +} +``` + +That asymmetry is the mechanism, not a detail: `DescribeArea` is what callers name, and it says nothing +about `BaseArea` or `Display`, so a caller bounding on it inherits no requirement to pass on. Writing +`#[uses(BaseArea, Display)]` is therefore exactly equivalent to writing +`where Self: BaseArea + Display` on the function, and the two desugar identically. + +Entries split across stacked `#[uses(...)]` attributes are collected before the bound is built, so +`#[uses(BaseArea)]` above `#[uses(Display)]` produces the same single predicate shown above. The context +parameter is literally `__Context__` in the emitted code, and appears as `Self` inside the implementation. + +Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the behaviour is the same, with the predicates +appended to that provider's `where` clause — which is also where they are picked up by the generated +[`IsProviderFor`](../traits/is_provider_for.md) impl, so an unmet import is reported by name rather than +as a bare missing implementation. + +## Gotchas + +**Naming a provider trait instead of a consumer trait does not work**, and this is the most likely way to +reach for `#[uses]` when [`#[use_provider]`](use_provider.md) is what you wanted. A provider trait carries +an explicit context parameter, and `#[uses]` does not fill it in, so the bound is incomplete: + +```text +error[E0107]: missing generics for trait `AreaCalculator` + | + | #[uses(AreaCalculator)] + | ^^^^^^^^^^^^^^ expected 1 generic argument + | +note: trait defined here, with 1 generic parameter: `__Context__` +``` + +The `__Context__` in that note is the giveaway. Depend on the **consumer** trait — +`#[uses(CanCalculateArea)]` — when what you want is "whatever this context has wired", which is almost +always the case. Use [`#[use_provider]`](use_provider.md) when you genuinely mean a named implementation, +and it will supply the missing argument. + +## Related constructs + +- [`#[cgp_fn]`](../macros/cgp_fn.md) and [`#[cgp_impl]`](../macros/cgp_impl.md) — the two hosts. +- [`#[extend]`](extend.md) — the same syntax, but as a public supertrait rather than a private bound. +- [`#[extend_where]`](extend_where.md) — a predicate on the generated trait's own `where` clause. +- [`#[use_type]`](use_type.md) — imports a type rather than a capability, and rewrites its uses. +- [`#[use_provider]`](use_provider.md) — imports an inner provider, filling in its context argument. +- [`#[implicit]`](implicit.md) — imports a value from a field rather than a capability. +- [`#[cgp_component]`](../macros/cgp_component.md) — defines the capabilities most often imported. + +## Source + +- Parsing: [`types/attributes/uses.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/uses.rs) +- Collection: [`types/attributes/function.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/function.rs) + and [`types/attributes/cgp_impl_attributes.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/cgp_impl_attributes.rs) +- Injection: [`types/cgp_fn/preprocessed.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_fn/preprocessed.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/index.md b/docs/reference/index.md index 2bb0786c..1641a28a 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -88,12 +88,13 @@ chosen by wiring, through [`UseField` and its siblings](./providers/use_field.md ### Declare what an implementation needs -These attributes state a provider's dependencies where the implementation lives, so they never appear -in the interface callers see. [`#[uses]`](./attributes/uses.md) imports the capabilities it depends on, -[`#[use_provider]`](./attributes/use_provider.md) does the same for an inner provider in a -higher-order provider, and [`#[extend]`](./attributes/extend.md) and -[`#[extend_where]`](./attributes/extend_where.md) add bounds to a generated trait rather than to its -implementation. +These attributes state what an implementation needs, and they divide by whether the requirement stays +private to it. [`#[uses]`](./attributes/uses.md) imports the capabilities the body depends on and +[`#[use_provider]`](./attributes/use_provider.md) does the same for an inner provider in a higher-order +provider — both landing on the implementation alone, so a caller never sees them. Where a requirement +should instead be part of what the trait promises, [`#[extend]`](./attributes/extend.md) adds it as a +supertrait and [`#[extend_where]`](./attributes/extend_where.md) as a predicate on the generated trait +itself. ### Let each context choose a type From 861c5e2d6d25060d1837093fba2b6c2489b94eb5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 12:41:02 +0200 Subject: [PATCH 015/516] Review the written reference and concept pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A review of all fourteen written pages against the compiler and against their own writing guides, after reading the communication strategy, the concepts, and the macro and attribute references they are ported from. One claim was wrong, and it originated here rather than upstream. `#[cgp_impl]` gave "implementing a provider trait on a concrete type" as a reason to drop to `#[cgp_provider]`, and it is not one: the concrete-context form compiles under `#[cgp_impl]`, pins the provider to that context, and passes a check. Replace it with the real reason — a provider struct the attribute cannot declare, either carrying a default generic parameter or shared by several impls — and say in `Using it` that a named context may be concrete, keeping it distinct from the `#[cgp_impl(Self)]` form it resembles. The internal reference now records the form too, since its absence there is what let the guess stand. One snippet did not compile. `delegate_components!`'s payoff example wired `Square` to `SquareArea` with neither ever defined, against the rule that snippets are compiled rather than eyeballed. It now carries the provider and the struct, and its closing sentence no longer contradicts itself by claiming only the wiring line differs when the providers differ too. One diagnostic was quoted from half the output. Wiring a component through two dispatch mechanisms reports `E0119` twice, for `IsProviderFor` first and then `DelegateComponent`; `#[derive_delegate]` quoted only the second, so a reader comparing against their own build meets a different headline first. Name both, and say why the second is the readable one. Four guide items. `#[cgp_component]` and `#[extend_where]` used "context" with no gloss above the advanced line — the convention `site-structure.md` calls the one most easily dropped — and on `#[cgp_component]` the word appeared only as `context.area()` in a bullet whose own example calls `rect.area()`. `#[cgp_impl]` named `IsProviderFor` in its `Using it` table, addressed to a reader who has met no machinery yet; the row's meaning survives without it and the trait is already explained below the line. And the concept page used "component" as known vocabulary from the wiring section on, so it now carries the plain-language definition the vocabulary list prescribes. Smaller things. The reference index linked `HasFields` to a derive and to a trait in adjacent paragraphs, so the derives now read as `#[derive(...)]` and the traits paragraph says what it is a list of; it also gains the handler variants a reader arrives holding — `ComputerRef`, `AsyncComputer`, `HandlerRef` — and rows for `CanSendRun`, `CanWrapError`, and `HasRuntimeType`. The concept page's first listing gains the `RefCell` import its later one has, and links `cargo cgp check` where it recommends it, as the reference page already does. Sixteen quoted diagnostics and snippets were reproduced verbatim against cgp 0.8.0-alpha, including the four `#[implicit]` rejections, the `#[use_type]` grounding cycle, the `#[uses]` E0107 with its `__Context__` note, the `#[impl_generics]` E0425/E0433 pair, and both concept-page listings under a `check_components!` assertion per context. Every replacement snippet compiles. The site builds, so every link on the revised pages resolves, and no page links into the knowledge base. Co-Authored-By: Claude Opus 5 (1M context) --- docs/concepts/consumer-and-provider-traits.md | 12 ++++++---- docs/reference/attributes/derive_delegate.md | 8 ++++++- docs/reference/attributes/extend_where.md | 9 +++---- docs/reference/index.md | 23 +++++++++++------- docs/reference/macros/cgp_component.md | 7 +++--- docs/reference/macros/cgp_impl.md | 24 ++++++++++++------- docs/reference/macros/delegate_components.md | 21 ++++++++++++++-- 7 files changed, 73 insertions(+), 31 deletions(-) diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index f8b3d82e..73ce1b06 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -21,6 +21,8 @@ The consequence is that a trait offers one implementation per type, and that lim than it sounds. Consider an application that sends email, with a test harness that must not: ```rust +use core::cell::RefCell; + pub trait CanSendEmail { fn send_email(&self, to: &str, body: &str); } @@ -122,8 +124,9 @@ method runs. Two pieces connect the halves: a table on the context that names its choice, and a pair of generated implementations that follow it. -The table is what a context writes. It maps each component to the provider that should implement it, -and it is the one place a choice is recorded: +The table is what a context writes. It maps each **component** — one capability, defined once, that +implementations can be wired for — to the provider that should supply it, and it is the one place a +choice is recorded: ```rust delegate_components! { App { EmailSenderComponent: SendViaSmtp } } @@ -254,8 +257,9 @@ capability from a function with no component and no wiring at all. requirements the context cannot meet, still compiles; the failure surfaces later, wherever the capability is finally used, and the error can be long. This is real, and it has an answer: [`check_components!`](/docs/reference/macros/check_components) forces the check at the wiring line so -the error names the actual gap, and `cargo cgp check` reshapes the recognized failures to lead with -the root cause. Neither makes the raw diagnostics pleasant — see +the error names the actual gap, and +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reshapes the recognized failures to +lead with the root cause. Neither makes the raw diagnostics pleasant — see [Checking your wiring](./check-traits.md) for what to expect. **There is a hop between the call and the code that runs.** `app.send_email(..)` no longer points at diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 8ff76ad5..f397c094 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -246,7 +246,10 @@ The usual cause is putting the attribute on a component that has no type paramet there is nothing for it to do. **One component gets one dispatch mechanism.** Wiring the same component both with `open` and with a -`UseDelegate` table is a coherence conflict, because each produces its own table entry for that key: +`UseDelegate` table is a coherence conflict, because each produces its own table entry for that key. A +wiring entry expands to two impls, and both of them collide, so the conflict is reported twice — once +for `IsProviderFor` and once for `DelegateComponent`. The second is the readable one, since its trait +argument names the component at issue: ```text error[E0119]: conflicting implementations of trait `DelegateComponent` @@ -254,6 +257,9 @@ error[E0119]: conflicting implementations of trait `DelegateComponent AreaCalculator for Context` — only when you actually need to say something about it that the sugar cannot express, such as a lifetime or a higher-ranked bound. +That named context may be a *concrete* type rather than a parameter — `impl AreaCalculator for Rectangle` +— which writes a provider serving only that one context. Keep it distinct from the +[`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which looks similar and does +something else: this one still produces a named provider that a context wires like any other, and that +one produces no provider at all. + Reach for something else in three cases. -- **You need the inside-out shape itself.** [`#[cgp_provider]`](./cgp_provider.md) and - `#[cgp_new_provider]` are the raw forms. Write one when you must state a bound the sugar cannot, or - when implementing a provider trait on a concrete type rather than a generic one. Otherwise, read - them and write `#[cgp_impl]`. +- **The provider struct has to be declared separately.** [`#[cgp_provider]`](./cgp_provider.md) is the + raw form for that case, and `new` is what you drop: a struct carrying a default generic parameter, + such as `pub struct IterSum(PhantomData);`, cannot be declared by the + attribute, and neither can one shared by several impls. Write the struct, then annotate each impl. - **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain function with no component, no provider, and no wiring. - **You want to implement the consumer trait directly on one concrete type.** Use the diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 5b8b4b40..4a49f709 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -202,10 +202,22 @@ fn print_area(rect: &Rectangle) { } ``` -The payoff is what happens when you change one line. Wiring a second context to a different provider -gives two types that answer `area()` differently, with no change to any code that calls it: +The payoff is what happens when a second context wants the same capability answered differently. It +writes its own provider and its own table entry, and no code that calls `area()` changes: ```rust +#[cgp_impl(new SquareArea)] +impl AreaCalculator { + fn area(&self, #[implicit] side: f64) -> f64 { + side * side + } +} + +#[derive(HasField)] +pub struct Square { + pub side: f64, +} + delegate_components! { Square { AreaCalculatorComponent: SquareArea, @@ -213,6 +225,11 @@ delegate_components! { } ``` +`Rectangle` and `Square` now both implement `CanCalculateArea`, through different providers reading +different fields — and a function generic over `CanCalculateArea` serves both without knowing that any +of it happened. Each context's choice stays one greppable line, which is the whole of what a reader has +to find to know which implementation runs. + ## When to reach for it, and when not Use `delegate_components!` whenever a context needs to choose providers, which is any time you use From abad4ace944db9089795816d1387c7555948b4f3 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 13:29:15 +0200 Subject: [PATCH 016/516] Write the remaining sixteen macro reference pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `macros/` is now complete, taking the reference to twenty-seven written pages plus the index alongside `attributes/`. Forty-eight stubs remain, all in `derives/`, `components/`, `providers/`, `traits/`, and `types/`. The pages are `#[cgp_provider]` (consolidated with `#[cgp_new_provider]`), `#[cgp_type]`, `#[cgp_getter]`, `#[cgp_auto_getter]`, `check_components!`, `delegate_and_check_components!`, `cgp_namespace!`, `#[cgp_computer]`, `#[cgp_producer]`, `#[cgp_auto_dispatch]`, `#[blanket_trait]`, `#[async_trait]`, `Symbol!`, `Product!`/`product!`, `Sum!`, and `Path!`. Each follows the six-section layered descent, with the formal grammar collapsed where the macro has custom syntax — and deliberately absent on `#[async_trait]`, `#[cgp_auto_dispatch]`, and `#[cgp_auto_getter]`, the three whose invocation is a plain Rust item. Verifying rather than transcribing changed five of these pages and corrected five claims in the knowledge base they were ported from, which are landing separately. What the compiler contradicted here: `ErrorTypeProviderComponent` is not in the prelude, so both handler pages' examples were broken until they imported it from `cgp::core::error`; a `#[cgp_producer]` returning a `Result` is not interpreted as fallible, so its `try_compute` hands back `Ok(Err(..))`, a success carrying an error that short-circuits nothing; and `#[async_trait]`'s example could not compile at all, having been ported with `anyhow` and an AWS client, so it is now self-contained. A review pass over the finished group then found four more things wrong, three of them mine. `#[cgp_type]` claimed its associated-type bound is enforced at the wiring line. It is not: wiring `UseType` against a `type Scalar: Copy` declaration compiles, and the failure surfaces only at a `check_components!`, whose primary span is the component name rather than the offending entry. Three statements across *Using it*, *Examples*, and *Gotchas* said otherwise. The page now tells the same lazy-wiring story as the rest of the reference, which is the more useful lesson. `#[cgp_provider]` listed "a bound the sugar cannot spell" as a reason to prefer the raw form. `#[cgp_impl]` with an explicit context expresses `for<'a> &'a Context: IntoIterator` without difficulty, so that reason is not real — the same class of plausible-but-unverified claim this page's predecessor was corrected for last round. It is replaced by what the evidence supports: the struct declaration is the only reason, and the two cases that look like they need the raw impl do not. Two *Gotchas* described the wrong error. A generic component checked without parameters does not complain about the parameters; the check is emitted with an empty tuple and the result is an ordinary unsatisfied-wiring error that never mentions them, which is the whole hazard. Both `check_components!` and `delegate_and_check_components!` now say so and quote it. And `delegate_components!` — reviewed last round — still carried the absolute "would fail spuriously" claim about the aggregate-provider check that was corrected in three other places. Now consistent. Six further failures were upgraded from described to quoted, per the convention that a documented failure shows what the compiler produced: the `Path!` sigil, the two `#[cgp_auto_dispatch]` rejections, the `UseField` type mismatch, the duplicate check-trait name, and the `Product!`-in-expression-position parse error. Every example compiles against cgp 0.8.0-alpha with a `check_components!` assertion per wired context; every expansion was read back through `cargo cgp expand`, which is what surfaced the augmented `IsProviderFor` clause and the `#[cgp_computer]` promotion tables; and every quoted diagnostic was reproduced. The site builds, so every link resolves, and no page links into the knowledge base. Co-Authored-By: Claude Opus 5 (1M context) --- docs/reference/macros/async_trait.md | 267 +++++++++++- docs/reference/macros/blanket_trait.md | 307 ++++++++++++- docs/reference/macros/cgp_auto_dispatch.md | 276 +++++++++++- docs/reference/macros/cgp_auto_getter.md | 317 +++++++++++++- docs/reference/macros/cgp_computer.md | 298 ++++++++++++- docs/reference/macros/cgp_getter.md | 319 +++++++++++++- docs/reference/macros/cgp_namespace.md | 402 +++++++++++++++++- docs/reference/macros/cgp_producer.md | 271 +++++++++++- docs/reference/macros/cgp_provider.md | 365 +++++++++++++++- docs/reference/macros/cgp_type.md | 324 +++++++++++++- docs/reference/macros/check_components.md | 388 ++++++++++++++++- .../macros/delegate_and_check_components.md | 348 ++++++++++++++- docs/reference/macros/delegate_components.md | 5 +- docs/reference/macros/path.md | 239 ++++++++++- docs/reference/macros/product.md | 219 +++++++++- docs/reference/macros/sum.md | 192 ++++++++- docs/reference/macros/symbol.md | 236 +++++++++- 17 files changed, 4690 insertions(+), 83 deletions(-) diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 396b63b6..0e101121 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -6,12 +6,269 @@ sidebar_label: '#[async_trait]' Rewrite a trait's `async fn` declarations into the lint-clean `-> impl Future` form CGP's async methods use. -:::info +## What it's for -### Not written yet +Writing a bare `async fn` inside a trait compiles on stable Rust, and the compiler warns about it. The +`async_fn_in_trait` lint fires because the future such a method returns is *opaque*: a caller working through +the trait cannot name it, so they cannot require anything of it — most importantly that it is `Send`. The +hand-written way to silence the lint is to declare the method as a future-returning function instead, which +is correct and obscures the intent: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +fn fetch(&self, id: &str) -> impl Future, String>>; +``` + +`#[async_trait]` lets you write the natural form and performs that rewrite mechanically: + +```rust +#[async_trait] +pub trait CanFetch { + async fn fetch(&self, id: &str) -> Result, String>; +} +``` + +The trait reads as async code, and the declaration the compiler sees is the lint-clean one. + +**The rewrite is a plain desugaring, not a framework.** Unlike the widely-used `async-trait` crate, nothing +here boxes the future or allocates: it is return-position `impl Trait` in traits, so the future is exactly the +one the body produces and the call costs what a hand-written future-returning method costs. That is why the +macro is used throughout CGP wherever a capability is asynchronous — it is simply how an async method is +spelled. + +One thing it does *not* do is add a `Send` bound, and that omission has consequences the moment a future is +spawned. It is covered under [Gotchas](#gotchas). + +## Using it + +Apply the attribute to a trait definition. It takes no arguments — tokens in the argument position are +ignored, so it is always written bare: + +```rust +#[async_trait] +pub trait CanFetch { + async fn fetch(&self, id: &str) -> Result, String>; +} +``` + +Only methods declared `async` are touched. Non-async methods, associated types, and associated constants in +the same trait pass through unchanged, so a trait can mix them freely. + +### Ordering with a host macro + +When stacked with another macro, the order follows what that macro needs, and the two cases differ. + +With [`#[cgp_component]`](./cgp_component.md), put `#[async_trait]` **outermost**, so it rewrites the trait +before the component macro reads it: + +```rust +#[async_trait] +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> Result, String>; +} +``` + +With [`#[cgp_fn]`](./cgp_fn.md), which *generates* the trait from a function, put it **below** `#[cgp_fn]` on +the `async fn`. `#[cgp_fn]` copies the attribute onto both items it generates: + +```rust +#[cgp_fn] +#[async_trait] +pub async fn fetch_storage_object( + &self, + #[implicit] storage_client: &Client, + object_id: &str, +) -> Result, String> { + /* ... */ +} +``` + +## Examples + +The common case is declaring an asynchronous component. The consumer trait carries the attribute so its method +is a clean declaration, and each provider implements it with an ordinary `async fn` body: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; + +#[async_trait] +#[cgp_component(StorageObjectFetcher)] +#[use_type(HasErrorType.Error)] +pub trait CanFetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> Result, Error>; +} + +#[cgp_impl(new FetchFromBucket)] +#[use_type(HasErrorType.Error)] +impl StorageObjectFetcher { + async fn fetch_storage_object( + &self, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> Result, Error> { + // await a real client here + Ok(format!("{bucket_id}/{object_id}").into_bytes()) + } +} + +#[derive(HasField)] +pub struct App { + pub bucket_id: String, +} + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + StorageObjectFetcherComponent: FetchFromBucket, + } +} +``` + +Notice the provider needs no `#[async_trait]` of its own. An `async fn` is already legal in an impl block — +only a trait *declaration* trips the lint — so the provider keeps the natural body while the trait carries the +rewritten signature, and the two agree because an `async fn` desugars to exactly such a future-returning +method. + +## When to reach for it, and when not + +**Use `#[async_trait]` on every CGP trait with an async method.** There is no judgement to make here: it is +how an async method is declared, and the alternative is either a lint warning or writing the `impl Future` +signature by hand. + +The decisions worth making are around it rather than about it. + +- **Do not put it on an impl block.** It is accepted there and does nothing, since the rewrite only applies to + trait definitions. Harmless, but it suggests a misunderstanding of where the lint comes from. +- **Reach for the `Send`-recovery pattern when a future is spawned**, not for a different macro. No attribute + can add the bound, for the reason in the [Gotchas](#gotchas). +- **Consider whether the capability needs to be async at all.** The [handler family](./cgp_computer.md) has + synchronous members, and the [promotion combinators](../providers/handler_combinators.md) lift a synchronous + provider into an async one where a caller needs it — so a computation that does no I/O is better declared + synchronous and promoted than declared async out of habit. +- **Reach for the `async-trait` crate instead only if you need `dyn` compatibility.** Boxing is what makes an + async trait object-safe, and this macro deliberately does not box. CGP resolves providers statically, so it + does not need `dyn`; a codebase that does for other reasons is outside what this macro is for. + +## Under the hood + +:::note + +### Advanced + +This section shows the rewrite. It is the simplest expansion in CGP, and worth seeing once because it explains +why a provider needs no attribute of its own. `cargo cgp expand` prints the same thing for your own code. ::: + +For each `async` method the macro removes the `async` keyword and wraps the return type in +`impl ::core::future::Future`. A method with no return arrow is treated as returning `()`. From +this input: + +```rust +#[async_trait] +pub trait CanFetch { + async fn fetch(&self, id: &str) -> Result, String>; + async fn run(&self); + fn sync_method(&self) -> u8; +} +``` + +the macro emits: + +```rust +pub trait CanFetch { + fn fetch( + &self, + id: &str, + ) -> impl ::core::future::Future, String>>; + fn run(&self) -> impl ::core::future::Future; + fn sync_method(&self) -> u8; +} +``` + +Three things to read off it. The `Output` is the original return type verbatim. The bodiless `run` picked up +`Output = ()`. And `sync_method` was left completely alone, which is what lets a trait mix async and +synchronous methods. + +**The macro rewrites only trait definitions.** Applied to anything else — most importantly an `impl` block — +it returns the tokens unchanged. That passthrough is what makes the composition work: an `async fn` is legal in +an impl already, so the provider's body stays as written while the trait's declaration carries the future +type, and the `async fn` satisfies it because that is precisely what an `async fn` desugars to. + +The composition with [`#[cgp_fn]`](./cgp_fn.md) shows both halves at once. `#[cgp_fn]` first produces a trait +and a blanket impl, attaching `#[async_trait]` to each: + +```rust +#[async_trait] +pub trait FetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> Result, String>; +} + +#[async_trait] +impl<__Context__> FetchStorageObject for __Context__ +where + Self: HasField, +{ + async fn fetch_storage_object(&self, object_id: &str) -> Result, String> { + let storage_client: &Client = + self.get_field(PhantomData::); + /* ... */ + } +} +``` + +`#[async_trait]` then runs on both. On the trait it rewrites the declaration; on the impl it is a no-op, so +the `async fn` body survives intact. + +## Gotchas + +**The generated future carries no `Send` bound**, and this is the limitation that matters in practice. Because +the rewrite produces a bare `impl Future`, the future is `Send` only when the concrete future +happens to be, and the trait does not require it — so code that spawns the future onto a multi-threaded, +work-stealing executor cannot express what it needs through this trait. + +The bound you would want to write is Return Type Notation — `App: CanFetch` — which is not +stabilized, so it cannot be written today. The workaround is to declare a second, ordinary trait whose method +spells `+ Send` on its return type directly, and to implement it for each concrete context. That pattern is +mechanical but unavoidable; the opacity that makes the rewrite zero-cost is the same opacity that hides the +auto-traits. + +**A default-bodied async method is mishandled.** The macro rewrites the *signature* and never the body, so a +method with a default gets its `async` stripped and its return type changed while the body stays a plain +expression: + +```text +error[E0277]: `{integer}` is not a future +``` + +That error names the body's type rather than the rewrite that caused it. In practice this is rarely hit, +because async trait methods are almost always declarations with the behaviour supplied by a provider — but a +default-bodied `async fn` inside an `#[async_trait]` trait is not supported. Wrap the body in an +`async { … }` block by hand, or move it to a provider. + +**Attribute arguments are silently ignored.** `#[async_trait(anything)]` is accepted and discarded rather than +rejected, so a typo'd option gives no feedback. Always write it bare. + +**On an impl block it does nothing**, which is correct but can mislead. Seeing it on a provider suggests the +provider needed it; it did not, and removing it changes nothing. + +## Related constructs + +- [`#[cgp_component]`](./cgp_component.md) — the usual host, with `#[async_trait]` placed outermost. +- [`#[cgp_fn]`](./cgp_fn.md) — the other host, with `#[async_trait]` placed beneath it. +- [`#[cgp_impl]`](./cgp_impl.md) — where a provider writes an ordinary `async fn` body and needs no attribute. +- [`Handler`](../components/handler.md) — CGP's built-in async, fallible component, declared this way. +- [`#[cgp_computer]`](./cgp_computer.md) — where an `async` function selects the async base trait. +- [Handler combinators](../providers/handler_combinators.md) — the promotions that lift a synchronous provider + into an async one. + +## Source + +- Entry point: [`cgp-async-macro/src/lib.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-async-macro/src/lib.rs) +- The rewrite: [`impl_async.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-async-macro/src/impl_async.rs) +- Prelude re-export: [`cgp-core/src/prelude.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/main/cgp-core/src/prelude.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index e27f62c9..cec256ad 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -6,12 +6,309 @@ sidebar_label: '#[blanket_trait]' Generate a blanket impl from a trait with default methods and supertrait dependencies. -:::info +## What it's for -### Not written yet +The pattern CGP is built on is an **extension trait**: a trait with a clean interface whose +[blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) carries the +real requirements in its `where` clause. A trait declared `FooBar: Foo + Bar` with a default `foo_bar` method +exposes only `foo_bar` to callers, while the `Foo + Bar` requirements live on the impl — so any type +satisfying them gains the capability, and nobody calling `foo_bar` has to know or repeat what it needed. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +That is worth doing rather than writing a generic function, because a function's `where` clause propagates: +every generic caller repeats it, and so does every caller of *those*. Hiding the requirement on an impl stops +the cascade at one level. + +Written by hand the pattern is repetitive. You state the supertraits twice — once on the trait, once on the +impl — and copy each default body across. `#[blanket_trait]` lets you write the trait once and generates the +impl: + +```rust +#[blanket_trait] +pub trait FooBar: Foo + Bar { + fn foo_bar(&self) { + self.foo(); + self.bar(); + } +} +``` + +**This is not a CGP component.** There is no consumer/provider split, no component marker, and no wiring — +just an ordinary Rust trait and an ordinary blanket impl. It is the tool for a capability with exactly one +definition, where you want extension-trait ergonomics without committing to the component machinery. When a +second implementation becomes necessary, the trait can be promoted to a +[`#[cgp_component]`](./cgp_component.md). + +## Using it + +`#[blanket_trait]` is **not exported by the prelude**, so it needs an explicit import: + +```rust +use cgp::prelude::*; +use cgp::core::macros::blanket_trait; +``` + +Apply it to a trait definition. Every method and constant must have a default, since those defaults are what +the generated impl forwards, and the trait's supertraits become the dependencies the impl requires: + +```rust +#[blanket_trait] +pub trait FooBar: Foo + Bar { + fn foo_bar(&self) { + self.foo(); + self.bar(); + } +} +``` + +The attribute takes an optional identifier naming the generic **context** type — the type the capability runs +against — in the generated impl. Omitted, it is the reserved `__Context__`, chosen so it cannot collide with +one of your own type parameters: + +```rust +#[blanket_trait(Ctx)] +pub trait FooBar: Foo + Bar { /* ... */ } +``` + +The trait may carry generic parameters, which are copied onto the impl, and associated types, which get the +special treatment described next. + +### Lifting an associated type out of a supertrait + +An associated type on the trait becomes a fresh generic parameter on the impl, bound through the supertrait's +associated-type equality. This is one of the pattern's main uses — re-exporting a supertrait's type under a +local name: + +```rust +#[blanket_trait] +pub trait HasFooTypeAtBar: HasFooTypeAt { + type FooBar: Clone; +} +``` + +A context implementing `HasFooTypeAt` gets `HasFooTypeAtBar` automatically, with `FooBar` resolved to +whatever its `Foo` was. Bounds on the associated type move onto the lifted parameter, so `Clone` above becomes +a requirement on that underlying type. Associated types need no default — the macro supplies the assignment +itself. + +## Examples + +An extension trait hiding two dependencies behind one method: + +```rust +use cgp::prelude::*; +use cgp::core::macros::blanket_trait; + +pub trait Foo { + fn foo(&self); +} + +pub trait Bar { + fn bar(&self); +} + +#[blanket_trait] +pub trait FooBar: Foo + Bar { + fn foo_bar(&self) { + self.foo(); + self.bar(); + } +} + +pub struct Ctx; + +impl Foo for Ctx { + fn foo(&self) {} +} + +impl Bar for Ctx { + fn bar(&self) {} +} + +pub fn run(ctx: &Ctx) { + ctx.foo_bar(); // available because Ctx: Foo + Bar +} +``` + +`Ctx` never mentions `FooBar`. It implements `Foo` and `Bar`, and the generated blanket impl supplies +`foo_bar` — while a caller of `foo_bar` sees a one-method interface and is shielded from the requirement +entirely. + +The degenerate case is useful too. A trait with no methods becomes a trait alias in all but name, which is a +tidy way to bundle a set of bounds under one shorter name: + +```rust +#[blanket_trait] +pub trait FooBar: Foo + Bar {} +``` + +Any type that is `Foo + Bar` is now `FooBar`, and a signature can say so in one word. + +## When to reach for it, and when not + +**Reach for `#[blanket_trait]` when a capability has one definition and its dependencies are other traits.** +That last clause is the real discriminator, and it is what separates this macro from its closest neighbour. + +- **[`#[cgp_fn]`](./cgp_fn.md) when the dependencies are context *fields*.** Both macros produce a + single-implementation capability with a blanket impl and no wiring, so the choice is about the input. + `#[cgp_fn]` derives the trait and body from a function, reading values through + [`#[implicit]`](../attributes/implicit.md) arguments; `#[blanket_trait]` takes a trait with supertraits and + default bodies. Values point to `#[cgp_fn]`, capabilities point here. +- **[`#[cgp_component]`](./cgp_component.md) when a second implementation is needed.** A blanket impl covers + every type satisfying its bounds, which leaves nowhere for an alternative to live. Promoting later is + cheap — the trait keeps its name and method — so starting here costs nothing if that changes. +- **A trait alias, when one exists.** The empty-body form above is a workaround for a language feature Rust + does not have on stable; it is the right workaround, but do not reach for the macro if a plain supertrait + bound reads fine at the use site. +- **Nothing at all, for a plain generic function.** If the requirement genuinely belongs in the signature + and no caller is generic over the type, a function with a `where` clause is simpler and the propagation + problem never arises. + +One caution specific to this construct: a blanket impl is **coherence-visible**, so it competes with any +other impl of the same trait. That is why the pattern admits exactly one definition, and why two +`#[blanket_trait]` traits whose bounds can both hold for one type cannot both cover that type for the same +trait. Needing that is the signal to move to a component. + +## Under the hood + +:::note + +### Advanced + +This section shows the two items the macro emits. You do not need them to use `#[blanket_trait]`, but the +associated-type lifting is genuinely surprising the first time, and knowing what the impl requires makes an +"unsatisfied bound" error much easier to read. `cargo cgp expand` prints the same thing for your own code. ::: + +The macro emits the trait and a blanket impl over a generic context. From the method example: + +```rust +#[blanket_trait] +pub trait FooBar: Foo + Bar { + fn foo_bar(&self) { + self.foo(); + self.bar(); + } +} +``` + +it produces the trait **unchanged, default body included**, plus the impl whose `where` clause carries the +supertraits as the hidden dependency: + +```rust +pub trait FooBar: Foo + Bar { + fn foo_bar(&self) { + self.foo(); + self.bar(); + } +} + +impl<__Context__> FooBar for __Context__ +where + __Context__: Foo + Bar, +{ + fn foo_bar(&self) { + self.foo(); + self.bar(); + } +} +``` + +The body appears twice — once as the trait's default and once in the impl — and that is what the macro +actually emits rather than a simplification. The impl is what supplies the method for every qualifying type; +the retained default is harmless, and a type implementing the trait by hand can still rely on it. + +A trait with no methods generates an empty impl, which is the trait-alias form: + +```rust +impl<__Context__> FooBar for __Context__ +where + __Context__: Foo + Bar, +{} +``` + +Associated types are where the expansion earns its keep. Each becomes a new generic parameter on the impl, +the supertrait's equality bound is rewritten to name that parameter, and the impl assigns it back: + +```rust +pub trait HasFooTypeAtBar: HasFooTypeAt { + type FooBar: Clone; +} + +impl<__Context__, FooBar> HasFooTypeAtBar for __Context__ +where + __Context__: HasFooTypeAt, + FooBar: Clone, +{ + type FooBar = FooBar; +} +``` + +Reading it back: the impl applies to any context whose `HasFooTypeAt::Foo` is some `FooBar` that is +`Clone`, and re-exposes that type under the local name. The declared bound moved from the associated type onto +the lifted parameter, which is what makes it a requirement on the *underlying* type rather than an assertion +about the alias. + +Associated constants are forwarded like methods — their default expressions become the impl's definitions. A +method or constant with no usable default is an error, since the macro has nothing to forward. + +
+Formal grammar + +The attribute argument is a single optional context name, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +BlanketTraitArgs -> ContextName? + +ContextName -> IDENTIFIER +``` + +Omitted, the generic context type in the generated impl is the reserved identifier `__Context__`; a given +`IDENTIFIER` overrides that name. + +
+ +## Gotchas + +**The macro is not in the prelude.** `use cgp::prelude::*;` does not bring it into scope, and the failure is +reported as an unknown attribute rather than as a missing import: + +```text +error: cannot find attribute `blanket_trait` in this scope +``` + +Add `use cgp::core::macros::blanket_trait;`. This is the one macro on this page's family that needs it — +`#[cgp_fn]`, `#[cgp_component]`, and the rest are all re-exported by the prelude. + +**A method without a default body is an error.** The macro forwards defaults into the impl, so a bare +declaration leaves it nothing to emit. This is the opposite of an ordinary trait, where a bodiless method is +the normal case. + +**The trait keeps its default bodies.** The expansion does not strip them, so each body appears both on the +trait and in the impl. Harmless, but worth knowing when reading an expansion and wondering whether the macro +duplicated something by mistake. + +**The blanket impl blocks any hand-written impl of the same trait.** Because it covers every type satisfying +its bounds, implementing the trait manually for a type that also satisfies them is a coherence conflict. +Where a type needs different behaviour, the trait wants to be a [component](./cgp_component.md) instead. + +## Related constructs + +- [`#[cgp_fn]`](./cgp_fn.md) — the same single-implementation, no-wiring shape, built from a function whose + dependencies are fields rather than traits. +- [`#[cgp_component]`](./cgp_component.md) — the step up, when one implementation is not enough. +- [`#[cgp_auto_getter]`](./cgp_auto_getter.md) — the same constraint-hiding applied to reading a field. +- [`HasField`](../traits/has_field.md) — what value-level dependency injection is built on. +- [`#[uses]`](../attributes/uses.md) — how a CGP provider declares the trait dependencies a supertrait + declares here. + +## Source + +- Entry point: [`blanket_trait.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/blanket_trait.rs) +- Implementation: [`types/blanket_trait.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/blanket_trait.rs) +- The `Self`-to-parameter rewriting for associated types: [`visitors/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/visitors/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index c3b39c53..bb3811c2 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -6,12 +6,278 @@ sidebar_label: '#[cgp_auto_dispatch]' Generate a handler that dispatches over an extensible-data input from a per-type trait. -:::info +## What it's for -### Not written yet +`#[cgp_auto_dispatch]` answers a common shape: **you have a trait with one implementation per type, and you +want it to work on an enum of those types too.** -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} +``` + +Implement `HasArea` for `Circle` and for `Rectangle`, and an `enum Shape` holding those two gets `HasArea` +as well — dispatching to whichever variant it currently holds. No `match` is written anywhere. + +Without the macro you would either hand-write that `match` per method, or wire up the +[dispatch combinators](../providers/dispatch_combinators.md) yourself: a matcher, a per-variant handler, and +the field-extraction machinery between them. The macro does exactly that wiring, so what you write is the +trait, its per-type impls, and a derive on the enum. + +**Its value is narrower than it looks, and worth naming precisely.** It fits when the per-variant behaviour +is *exactly* "call the same trait method on the payload". The moment a variant needs different handling, or +the dispatch should be chosen by a **context** — the type the capability runs against — rather than fixed on +the enum, the combinators are what you want directly. This is the convenient front end to +[dispatching](../providers/dispatch_combinators.md), not a replacement for it. + +## Using it + +Write the attribute above a trait definition. It takes no arguments: + +```rust +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} +``` + +The trait may have generic parameters and supertraits. Each method may take `self` by value, by shared +reference, or by mutable reference; may take further value or reference arguments; and may be `async`. + +Two restrictions are enforced when the macro expands: + +- **Every trait item must be a method.** Associated types and constants are rejected. +- **A method may not have non-lifetime generic parameters.** Lifetimes are fine. The reason is in the + [Gotchas](#gotchas), and it is a real limitation rather than an oversight. + +Each method must have a `self` receiver, since the receiver is the enum value being matched. + +The enum also has to be made extensible, with [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or the +narrower variant derives, so the machinery can take it apart one variant at a time. + +## Examples + +A per-type trait made to work on an enum of those types: + +```rust +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { pub radius: f64 } +pub struct Rectangle { pub width: f64, pub height: f64 } + +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} + +impl HasArea for Circle { + fn area(&self) -> f64 { + core::f64::consts::PI * self.radius * self.radius + } +} + +impl HasArea for Rectangle { + fn area(&self) -> f64 { + self.width * self.height + } +} +``` + +`Shape` now implements `HasArea` too: + +```rust +let shape = Shape::Rectangle(Rectangle { width: 2.0, height: 2.0 }); +assert_eq!(shape.area(), 4.0); +``` + +**Every variant's payload must implement the trait**, and that requirement is checked: forgetting an impl for +one variant is a compile error where the enum's method is used. That is the same exhaustiveness a hand-written +`match` gives, recovered for a generic matcher — and adding a variant to the enum without an impl for it +breaks the build rather than silently falling through. + +Mutating and argument-taking methods dispatch the same way, so one trait can mix them: + +```rust +#[cgp_auto_dispatch] +pub trait CanScale { + fn scale(&mut self, factor: f64); +} + +impl CanScale for Circle { + fn scale(&mut self, factor: f64) { self.radius *= factor; } +} + +impl CanScale for Rectangle { + fn scale(&mut self, factor: f64) { + self.width *= factor; + self.height *= factor; + } +} + +let mut shape = Shape::Circle(Circle { radius: 1.0 }); +shape.scale(2.0); +``` + +## When to reach for it, and when not + +**Reach for it when an existing per-type trait should also work on an enum of those types, unchanged.** That +is the case it is built for, and within it there is nothing shorter. + +Reach for something else in four situations. + +- **The behaviour differs per variant.** The macro generates one handler that calls the same method on every + payload. When a variant needs something else, use the + [dispatch combinators](../providers/dispatch_combinators.md) directly and name a handler per variant. +- **The dispatch should be a wired component.** The generated impl is fixed on the enum, with a unit context + and a unit code, so a context cannot override how one variant is handled. Wiring + `MatchWithValueHandlers` into a context's own component is what gives that control. +- **A method needs to be generic.** Not supported, and not fixable by rearranging — see the + [Gotchas](#gotchas). +- **The trait needs an associated type or const.** Also rejected. A trait carrying either is not a dispatch + trait in this sense; give the enum a component of its own instead. + +One framing worth keeping: this macro is about **retrofitting** a trait onto an enum. If you are designing +the operation from scratch and expect contexts to configure it, start with a +[`#[cgp_component]`](./cgp_component.md) and the combinators, and you will not need this. + +## Under the hood + +:::note + +### Advanced + +This section shows what the macro generates. You do not need it to use `#[cgp_auto_dispatch]`, but the +generated bound is what an unmet variant impl is reported against, so reading it once makes that error +legible. `cargo cgp expand` prints the same thing for your own code. ::: + +The macro keeps the trait unchanged and appends two kinds of item: one per-method computer, and one blanket +impl of the trait for a fresh enum parameter. + +For each method it emits a free function turned into a provider by +[`#[cgp_computer]`](./cgp_computer.md), named `Compute` plus the method name in PascalCase: + +```rust +#[cgp_computer(ComputeArea)] +fn area<'__a__, __Variants__: HasArea>(__Variants__: &'__a__ __Variants__) -> f64 { + __Variants__.area() +} +``` + +The body just calls the trait method on the payload, which is what makes the per-variant handler "invoke +`HasArea::area` on whatever this variant holds". It is bound by `__Variants__: HasArea` so it applies to every +payload type implementing the trait, and borrows through a fresh `'__a__` lifetime to mirror the `&self` +receiver. + +Then the enum-level blanket impl, which wires a matcher over the whole enum: + +```rust +impl<__Variants__> HasArea for __Variants__ +where + MatchWithValueHandlersRef: + for<'__a__> Computer<(), (), &'__a__ __Variants__, Output = f64>, + __Variants__: HasExtractor, +{ + fn area(&self) -> f64 { + MatchWithValueHandlersRef::::compute( + &(), + PhantomData::<()>, + self, + ) + } +} +``` + +Three things are worth reading off that. The matcher is invoked with a **unit context and unit code** — +`&()` and `PhantomData::<()>` — because the per-variant logic depends only on the payload, which is exactly +why a context cannot influence it. The `__Variants__: HasExtractor` bound is what requires the enum to be +extensible. And **the first `where` bound is where a missing variant impl is reported**: it says the matcher +must be a `Computer` over this enum, which holds only if every variant's payload can be handled. + +Which matcher is chosen depends on the method's receiver and argument list, and every choice comes from the +value-handler family so the per-variant computer receives the bare payload: + +| Receiver | No extra arguments | With arguments | +|---|---|---| +| `&self` | `MatchWithValueHandlersRef` | `MatchFirstWithValueHandlersRef` | +| `&mut self` | `MatchWithValueHandlersMut` | `MatchFirstWithValueHandlersMut` | +| `self` | `MatchWithValueHandlers` | `MatchFirstWithValueHandlers` | + +With arguments, the receiver and the arguments are bundled into the matcher's input as a tuple: + +```rust +// where MatchFirstWithValueHandlersRef: +// for<'__a__> Computer<(), (), (&'__a__ __Variants__, (f64, f64)), Output = bool> +fn contains(&self, arg_0: f64, arg_1: f64) -> bool { + MatchFirstWithValueHandlersRef::::compute( + &(), + PhantomData::<()>, + (self, (arg_0, arg_1)), + ) +} +``` + +An `async` method selects the `AsyncComputer` form of the bound and the call instead of `Computer`, and awaits +the result. + +## Gotchas + +**A trait method cannot be generic**, and the macro explains why in the message itself: + +```text +error: Dispatch trait methods cannot contain non-lifetime generic parameters due to the lack of + quantified constraints in Rust +``` + +The blanket impl would need a quantified bound — "for every instantiation of the method's type parameter, +every variant's payload satisfies it" — and Rust has no way to write that. A method that must be generic has +to be handled with the [dispatch combinators](../providers/dispatch_combinators.md) directly. Lifetime +parameters are fine. + +**Associated types and consts are rejected.** Every trait item must be a method: + +```text +error: Only function items are allowed in a dispatch trait +``` + +**The enum must derive the extensible-data machinery.** Without +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or the variant derives, the `HasExtractor` bound fails +and the error names that trait rather than the missing derive. + +**A missing variant impl is reported at the use site, against the matcher.** Forgetting `HasArea for Circle` +does not fail where the impl should have been; it fails where `shape.area()` is called, as an unsatisfied +bound on `MatchWithValueHandlersRef`. The variant that is missing is somewhere in the chain +rather than in the headline. + +**The generated impl is a blanket impl over every type**, not just your enum. That is what lets it cover any +extensible enum whose payloads implement the trait — and it means the trait cannot also be implemented by +hand for some other type without colliding with it. + +## Related constructs + +- [Dispatch combinators](../providers/dispatch_combinators.md) — the matchers this wires, and what to use + directly for anything it cannot express. +- [`#[cgp_computer]`](./cgp_computer.md) — how each per-variant handler is emitted. +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — what the enum needs to be dispatchable. +- [`Computer`](../components/computer.md) — the component the generated bound is written against. +- [`ExtractField`](../traits/extract_field.md) — the extractor family the matching walks. +- [`#[cgp_component]`](./cgp_component.md) — the better starting point when contexts should configure the + operation. + +## Source + +- Entry point: [`entrypoints/cgp_auto_dispatch.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_auto_dispatch.rs) +- The matchers it generates: [`cgp-dispatch/src/providers/matchers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-dispatch/src/providers/matchers/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 36409ee6..d51be312 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -6,12 +6,319 @@ sidebar_label: '#[cgp_auto_getter]' Define a getter as a blanket impl over `HasField`, keyed by the method name. -:::info +## What it's for -### Not written yet +`#[cgp_auto_getter]` publishes a context field as a named, reusable accessor. You write a trait of getter +methods, and the macro implements it for every **context** — the type the capability runs against, which +supplies the values it needs as its fields — that happens to carry fields of the matching names: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} +``` + +Any struct with a `name: String` field now implements `HasName`, and `self.name()` works. Nothing is +wired and no impl is written: the macro emits one +[blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) +covering every qualifying context, keyed on each method's own name. + +What it hides is the field-access trait CGP reads fields through, which is precise and unpleasant to write +by hand — a bound naming the field as a type-level string, and a `PhantomData` tag at every read. Being +able to state the same thing as `fn name(&self) -> &str;` is the point. + +**Reach for it sparingly.** For the ordinary case — a provider reading a field of its own context — an +[`#[implicit]`](../attributes/implicit.md) argument does the same job with no trait to declare, using the +same field access and the same conversion rules, so a getter trait declared only to read a field adds a +name and buys nothing. What a getter trait *does* buy is a capability other code can depend on by name, +and the three cases where that matters are in +[When to reach for it](#when-to-reach-for-it-and-when-not). + +## Using it + +Apply the attribute to a trait definition. It takes no arguments. The body is getter methods, each taking +`&self` or `&mut self` and returning a reference: + +```rust +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} +``` + +A trait may declare several methods, and each maps independently to its own field: + +```rust +#[cgp_auto_getter] +pub trait HasDimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; +} +``` + +**The method name is the field name.** That is the whole convention, and also the construct's one real +limitation — a context must expose a field of exactly that name. + +### How the return type decides the read + +The return type controls how the field is read, and several shorthands exist so the signature stays +natural. The field's type is inferred from what you return: + +| The method returns | The field's type | How it is read | +|---|---|---| +| `&T` | `T` | by reference, no conversion | +| `&str` | `String` | `.as_str()` | +| `&[T]` | anything `AsRef<[T]>` | `.as_ref()` | +| `Option<&T>` | `Option` | `.as_ref()` | +| `Option<&str>` | `Option` | `.as_deref()` | +| An owned type — `f64`, `String`, a tuple, an array | the same type | by reference, then `.clone()` | + +A `&mut self` receiver reads mutably, and each reference form has a mutable mirror: `&mut T`, `&mut [T]` +through `AsMut<[T]>`, `Option<&mut T>` via `.as_mut()`, and `Option<&mut str>` via `.as_deref_mut()`. + +The `&str` row is the one most often wanted and least obvious: the context stores a `String` and the +getter hands out a borrow of it, so no context ever has to hold a `&str`. **These are the same rules an +[`#[implicit]`](../attributes/implicit.md) argument follows**, so learning them once covers everywhere CGP +reads a field. + +### A type inferred from the field + +A getter may declare a single associated type and return it, which keeps the type abstract for callers +while letting the context's field decide it: + +```rust +#[cgp_auto_getter] +pub trait HasName { + type Name: Display; + + fn name(&self) -> &Self::Name; +} +``` + +The bound is enforced on whatever the field holds. When an associated type is present the trait must +contain **exactly one** getter method, whose return type is `&Self::AssocType` — there is only one field +for the type to be inferred from. + +## Examples + +A getter trait and a context that satisfies it by having the right field: + +```rust +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +pub fn greet(person: &Person) { + println!("Hello, {}!", person.name()); +} +``` + +`Person` derives [`HasField`](../derives/derive_has_field.md), which is its entire qualification — the +blanket impl applies automatically, with no wiring anywhere in the program. + +The reason to declare the trait at all is that other code can now *require* it. A provider states the +dependency by name and never mentions a field: + +```rust +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} +``` + +Any context with a `name` field satisfies `HasName` and therefore satisfies `GreetHello`. A context that +stores the name elsewhere can implement the trait by hand instead, which the blanket impl does not +prevent: + +```rust +pub struct Employee { + pub full_name: String, +} + +impl HasName for Employee { + fn name(&self) -> &str { + &self.full_name + } +} +``` + +That hand-written impl is worth seeing, because it shows the trait is an ordinary Rust trait. The macro's +only job was to save you writing the body. + +## When to reach for it, and when not + +**Prefer an [`#[implicit]`](../attributes/implicit.md) argument, and reach for a getter trait only when one +cannot do the job.** An implicit argument reads a field of the provider's own context as an ordinary +parameter — no trait, no declaration, the same access rules — so it covers the common read directly, +including a field several providers each consume, declared as the same implicit argument in each. + +A getter trait earns its keep in three cases an implicit argument cannot reach. + +- **The field lives on another type.** An implicit argument reads only from `self`, so a value held by a + request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type — + `Request: HasBasicAuthHeader`. There is no `self` field to read. +- **The accessor must be a named capability.** When other code depends on "this context can tell you its + name" rather than on a field, that dependency needs a trait to point at, importable with + [`#[uses]`](../attributes/uses.md) or usable as a supertrait via [`#[extend]`](../attributes/extend.md). +- **The getter carries a type inferred from the field.** The associated-type form above keeps the type + abstract for callers in a way a concrete implicit parameter cannot. + +Between the two getter macros the line is narrow and worth stating plainly. + +- **`#[cgp_auto_getter]` is the default getter.** One blanket impl, no wiring, field name fixed to the + method name. +- **[`#[cgp_getter]`](./cgp_getter.md) is the advanced one**, and not a general upgrade. Reach for it only + when a context needs to choose *which field* the getter reads — a different name per context, or an + implementation selected by wiring. That control costs a line of wiring per context, and most getters do + not want it. + +So the ordering is: implicit argument by default, `#[cgp_auto_getter]` for the three cases above, and +`#[cgp_getter]` only for per-context field choice. + +## Under the hood + +:::note + +### Advanced + +This section shows the blanket impl the macro generates. You do not need it to use `#[cgp_auto_getter]`, +but an unsatisfied getter names the generated bound rather than your method, so reading one makes that +error much easier to follow. `cargo cgp expand` prints the same thing for your own code. ::: + +The macro re-emits the trait unchanged and adds one blanket impl over a generic context. From this input: + +```rust +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} +``` + +it produces the trait verbatim plus: + +```rust +impl<__Context__> HasName for __Context__ +where + __Context__: HasField, +{ + fn name(&self) -> &str { + self.get_field(PhantomData::).as_str() + } +} +``` + +Three things to recognize. The context parameter is literally `__Context__`, a reserved name chosen so it +cannot collide with one of yours. [`Symbol!("name")`](./symbol.md) is a type-level string standing for the +field name — the compiler prints its expanded `Symbol<4, Chars<'n', …>>` form in errors, and +`cargo cgp expand` resugars it back to this. And because the return type is `&str`, the bound asks for a +`String` field and the body appends `.as_str()`, which is the conversion table in action. + +A trait with several methods produces one predicate and one body per field, all in the same impl: + +```rust +impl<__Context__> HasDimensions for __Context__ +where + __Context__: HasField, + __Context__: HasField, +{ + fn width(&self) -> &f64 { + self.get_field(PhantomData::) + } + + fn height(&self) -> &f64 { + self.get_field(PhantomData::) + } +} +``` + +The associated-type form lifts the type into an extra generic parameter on the impl and binds it through +the field's value, which is what lets the field decide it: + +```rust +impl<__Context__, Name> HasName for __Context__ +where + Name: Display, + __Context__: HasField, +{ + type Name = Name; + + fn name(&self) -> &Self::Name { + self.get_field(PhantomData::) + } +} +``` + +The declared bound moves onto that parameter, so `Display` is required of whatever the field holds. Note +that the field tag still comes from the **method** name rather than from the associated type's. + +## Gotchas + +**The field name is fixed to the method name.** A context storing the value under any other name does not +satisfy the trait, and because the failure is an unmet bound on a blanket impl the method reads as missing +rather than the field: + +```text +error[E0599]: the method `name` exists for reference `&Person`, but its trait bounds were not satisfied +``` + +Either rename the field, implement the trait by hand, or use [`#[cgp_getter]`](./cgp_getter.md), which +exists precisely to decouple the two. + +**An associated type forces a single method**, since the type is inferred from one field and two getters +give it nothing to choose between: + +```text +error: if associated type is defined, exactly one getter method must be defined +``` + +**The macro takes no arguments.** Unlike its sibling [`#[cgp_getter]`](./cgp_getter.md) there is no +provider trait to name, because no component is generated, and an argument is rejected rather than +ignored: + +```text +error: #[cgp_auto_getter] does not accept any attribute argument +``` + +**The trait still has to be in scope to call its method.** That is ordinary Rust, but it surprises readers +here, because nothing else about the getter had to be declared — a missing `use` reports the method as not +found rather than the trait as not imported. + +## Related constructs + +- [`#[implicit]`](../attributes/implicit.md) — the default way to read a field, and the form to prefer. +- [`#[cgp_getter]`](./cgp_getter.md) — the wireable counterpart, for per-context field choice. +- [`#[derive(HasField)]`](../derives/derive_has_field.md) — what a context derives to qualify. +- [`HasField`](../traits/has_field.md) — the trait the generated bound is written against. +- [`Symbol!`](./symbol.md) — the type-level field name the bound is keyed on. +- [`#[uses]`](../attributes/uses.md) — how a provider depends on a getter by name. +- [`#[cgp_type]`](./cgp_type.md) — for an abstract type standing on its own rather than inferred from a + field. + +## Source + +- Entry point: [`cgp_auto_getter.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_auto_getter.rs) +- Implementation: [`types/cgp_auto_getter/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_auto_getter/) +- Getter parsing and the return-type shorthands: [`functions/getter/parse.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/getter/parse.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 80647a6a..b62e5362 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -6,12 +6,300 @@ sidebar_label: '#[cgp_computer]' Define a `Computer` provider from a plain function. -:::info +## What it's for -### Not written yet +CGP models computation as a family of components varying along three axes — synchronous or async, fallible +or not, taking an input or not. A provider in that family is a struct with one or more impls threading a +**context** (the type the capability runs against, which supplies the values it needs as its fields), a +phantom `Code` tag, and an `Input`. Written by hand for a computation as small as "add two numbers", that is +disproportionate ceremony. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[cgp_computer]` lets you write just the computation: + +```rust +#[cgp_computer] +fn add(a: u64, b: u64) -> u64 { + a + b +} +``` + +From that the macro produces the provider struct `Add`, an impl of the right base trait, and — the part +worth understanding — the wiring that makes the *same function* answer the whole family. `Add` satisfies +`compute`, `try_compute`, `compute_async`, and `handle`, along with their by-reference forms, without you +implementing any of them. + +That last property is what the macro is really for. The family exists so a provider can declare exactly the +capabilities it has, and the [promotion combinators](../providers/handler_combinators.md) exist so a simpler +provider can stand in where a more capable one is expected — an infallible computation is a fallible one +that never fails, a synchronous one is an async one that never awaits. `#[cgp_computer]` picks the narrowest +base that fits your function and wires the promotions for the rest, so you write one body and get every +shape. + +## Using it + +Apply the attribute to a free function. It takes an optional provider name: + +```rust +#[cgp_computer] +fn add(a: u64, b: u64) -> u64 { + a + b +} + +#[cgp_computer(MyAdder)] +fn add(a: u64, b: u64) -> u64 { + a + b +} +``` + +Omitted, the provider struct takes the function name in PascalCase — `add` becomes `Add`. Given, the +argument is used verbatim. + +The function's shape decides everything else: + +- **Its parameters become the input.** Several parameters are collected into one tuple, so + `fn add(a: u64, b: u64)` has input `(u64, u64)`. +- **Its return type becomes the output.** +- **It must not take `self`.** A handler provider has no receiver; the context is supplied separately by + the handler machinery. +- **It may be `async`**, and it may return a `Result`. Those two choices are what select the base trait. +- **Its generics and `where` clause carry over** to the generated impl, so the provider can itself be + generic. + +### What the two axes select + +The macro reads `async`-ness and `Result`-ness independently, and each combination picks a base trait and a +promotion bundle: + +| Your function | Base trait | Promotion bundle | +|---|---|---| +| `fn f(..) -> T` | `Computer` | `PromoteComputer` | +| `fn f(..) -> Result` | `Computer` | `PromoteTryComputer` | +| `async fn f(..) -> T` | `AsyncComputer` | `PromoteAsyncComputer` | +| `async fn f(..) -> Result` | `AsyncComputer` | `PromoteHandler` | + +The `Result` row is worth reading twice. The base trait stays `Computer` — its `Output` is simply the +`Result` type as written — and what changes is the *bundle*, which is what makes `try_compute` and `handle` +surface the `Ok`/`Err` outcome as success or failure rather than handing back a `Result` as a plain value. + +## Examples + +One function, every shape. The context here only has to supply the error type the fallible members need: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{Computer, TryComputer, AsyncComputer, Handler}; + +#[cgp_computer] +fn add(a: u64, b: u64) -> u64 { + a + b +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} + +// All four are answered by the single `add` definition: +// Add::compute(&App, PhantomData::<()>, (1, 2)) == 3 +// Add::try_compute(&App, PhantomData::<()>, (1, 2)) == Ok(3) +// Add::compute_async(&App, PhantomData::<()>, (1, 2)) resolves to 3 +// Add::handle(&App, PhantomData::<()>, (1, 2)) resolves to Ok(3) +``` + +Because the function returns a plain `u64`, the fallible forms always succeed. Switching it to return a +`Result` changes which bundle is wired and therefore what those forms mean, with no change at the call +sites: + +```rust +#[cgp_computer] +fn add_with_error(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "Overflow".to_string()) +} +``` + +Now `try_compute` and `handle` propagate the `Err` when the addition overflows. + +A generic function carries its parameters and bounds onto the provider, so one definition covers every type +that satisfies them: + +```rust +#[cgp_computer] +pub fn add_generic>(a: T, b: T) -> T { + a + b +} +``` + +## When to reach for it, and when not + +**Reach for `#[cgp_computer]` when a step in a pipeline is naturally a function.** That is the case it +exists for, and it is the shortest route into the handler family. + +- **Use [`#[cgp_producer]`](./cgp_producer.md) when the computation takes no input.** A constant, or a value + drawn from the context alone. It is the input-free sibling and produces a `Producer`. +- **Write the provider by hand with [`#[cgp_impl]`](./cgp_impl.md) when the body needs the context.** This + is the real boundary. A `#[cgp_computer]` function has no receiver and no access to the context, so it can + only transform its inputs. The moment the computation needs a field, an abstract type, or another + capability, it wants a provider impl of `Computer` or `Handler` written with `#[cgp_impl]`, where `self` is + the context and [`#[implicit]`](../attributes/implicit.md) and [`#[uses]`](../attributes/uses.md) work + normally. +- **Use [`#[cgp_fn]`](./cgp_fn.md) when what you want is a capability on the context, not a pipeline step.** + The two look similar and differ in what they produce: `#[cgp_fn]` gives a trait a context implements, + called as `self.thing()`; `#[cgp_computer]` gives a *provider* that gets wired into a handler component and + composed with combinators. If you are not building a pipeline, `#[cgp_fn]` is what you want. +- **Wire the [handler combinators](../providers/handler_combinators.md) directly for composition.** The macro + produces one step; `PipeHandlers` and friends chain them. + +One thing not to do is reach for the handler family because a capability happens to transform a value. The +family earns its keep when computations are *composed* — piped, dispatched on a `Code` tag, promoted between +variants. A single transform with one caller is a method. + +## Under the hood + +:::note + +### Advanced + +This section shows the three items the macro emits, and how the promotion wiring makes one function answer +the whole family. You do not need it to use `#[cgp_computer]`, but the delegation block is unusual enough +that seeing it once explains a lot of handler errors. `cargo cgp expand` prints the same thing for your own +code. ::: + +The macro emits the function unchanged, a provider impl of the base trait, and a +[`delegate_components!`](./delegate_components.md) block wiring the rest of the family. From this input: + +```rust +#[cgp_computer] +fn add(a: u64, b: u64) -> u64 { + a + b +} +``` + +it produces the base impl, with the parameters collected into a tuple that the method destructures back +apart: + +```rust +#[cgp_new_provider] +impl<__Context__, __Code__> Computer<__Context__, __Code__, (u64, u64)> for Add { + type Output = u64; + + fn compute( + _context: &__Context__, + _code: PhantomData<__Code__>, + (arg_0, arg_1): (u64, u64), + ) -> Self::Output { + add(arg_0, arg_1) + } +} +``` + +[`#[cgp_new_provider]`](./cgp_provider.md) is what declares `pub struct Add;` and derives the +[`IsProviderFor`](../traits/is_provider_for.md) impl — whose parameter tuple here is +`(__Code__, (u64, u64))`, the code tag and the input. The context and code parameters are introduced under +the reserved names `__Context__` and `__Code__`, and the body ignores both. + +Then the promotion wiring, which is the interesting half: + +```rust +delegate_components! { + Add { + [ + ComputerRefComponent, + TryComputerComponent, + TryComputerRefComponent, + AsyncComputerComponent, + AsyncComputerRefComponent, + HandlerComponent, + HandlerRefComponent, + ] -> + PromoteComputer, + } +} +``` + +Note the **`->` operator** rather than `:`. It delegates each key to *the value's own entry for that key* +rather than to the value itself, so `Add` inherits whatever `PromoteComputer` resolves each component +to — and [`PromoteComputer`](../providers/handler_combinators.md) is itself a table of single-step promoters. +`ComputerComponent` is absent from the list because `Add` implements it directly. + +The other three combinations differ only in which base trait is implemented and which bundle is named. An +`async` function implements `AsyncComputer` instead, its method is `compute_async` and awaits the call, and +it delegates a smaller set — `AsyncComputerRefComponent`, `HandlerComponent`, `HandlerRefComponent` — since +the synchronous members are not derivable from an async base. A `Result`-returning function keeps its base +trait and swaps the bundle to `PromoteTryComputer` or, when also async, `PromoteHandler`. + +Generics flow through to the impl, appended *ahead* of the introduced `__Context__` and `__Code__` +parameters, so `add_generic` yields a provider generic over `T` carrying the `T: Add` bound. A +reference parameter is preserved too: `fn to_string_ref(value: &V) -> String` becomes a +`Computer` whose input tuple is `(&V)`, and the bundle's by-reference entries make it serve the `…Ref` +components. + +
+Formal grammar + +The attribute argument is a single optional provider name, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpComputerArgs -> ProviderName? + +ProviderName -> IDENTIFIER +``` + +Omitted, the provider struct takes the function name converted to PascalCase; a given `IDENTIFIER` is used +verbatim. The annotated function is plain Rust, and the macro reads its parameters, return type, +`async`-ness, generics, and `where` clause to choose the base trait and promotion bundle as described above. + +
+ +## Gotchas + +**The function cannot reach the context.** There is no receiver and no context parameter in scope, so +`#[implicit]` arguments and `#[uses]` have nothing to attach to. A computation that needs anything from its +context is a provider impl written with [`#[cgp_impl]`](./cgp_impl.md), not a `#[cgp_computer]`. + +**Several parameters become one tuple input.** That is invisible when the provider is wired into a pipeline +that supplies the tuple, and very visible when calling the provider directly: +`Add::compute(&App, PhantomData::<()>, (1, 2))` takes one argument, not two. A single-parameter function's +input is `(T)`, which Rust treats as plain `T`. + +**The fallible forms need an error type on the context.** `try_compute` and `handle` name the context's +abstract error, so a context wiring the provider without an +[`ErrorTypeProviderComponent`](../components/has_error_type.md) fails on those members while `compute` works +fine — an error about the error type, arriving only for part of the family. Note also that the wiring key is +**not in the prelude**: it has to be imported from `cgp::core::error`, and forgetting that reports the +component as an unresolved type rather than as a missing import. + +**A `Result` return changes the bundle, not the base trait.** The `Computer` impl's `Output` *is* the +`Result`, so `compute` hands back a `Result` as an ordinary value while `try_compute` treats its `Err` as +failure. Both are available on the same provider, and which one a pipeline uses decides whether an error +short-circuits. + +## Related constructs + +- [`#[cgp_producer]`](./cgp_producer.md) — the input-free sibling, producing a `Producer`. +- [`Computer`](../components/computer.md) — the base component, with its by-reference and async variants. +- [`Handler`](../components/handler.md) and [`TryComputer`](../components/try_computer.md) — the more capable + members the promotions reach. +- [Handler combinators](../providers/handler_combinators.md) — the `Promote*` bundles this wires, plus + `PipeHandlers` and `ComposeHandlers` for composing steps. +- [`#[cgp_impl]`](./cgp_impl.md) — for a handler provider that needs its context. +- [`#[cgp_fn]`](./cgp_fn.md) — for a capability on the context rather than a pipeline step. +- [`#[cgp_new_provider]`](./cgp_provider.md) — what the generated impl is emitted through. +- [`#[cgp_auto_dispatch]`](./cgp_auto_dispatch.md) — generates per-variant computers from a trait. + +## Source + +- Entry point: [`entrypoints/cgp_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_computer.rs) +- `Result`-versus-value detection: [`parse/maybe_result.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/parse/maybe_result.rs) +- The base traits: [`cgp-handler/src/components/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/components/) +- The promotion bundles: [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 3d11fe6f..06b242e0 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -6,12 +6,321 @@ sidebar_label: '#[cgp_getter]' Define a getter as a full component, so the field it reads is chosen by wiring rather than by its name. -:::info +## What it's for -### Not written yet +[`#[cgp_auto_getter]`](./cgp_auto_getter.md) ties a getter to a field of the same name: declare +`fn name(&self) -> &str` and every context with a `name` field satisfies it. That is the right trade almost +always, and it has one hard edge — a context that stores the value under a different name cannot use the +getter at all. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[cgp_getter]` removes that coupling by making the getter a real component. The **context** — the type +the capability runs against, which supplies the values it needs as its fields — then says in its wiring +which field the getter should read: + +```rust +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} +``` + +`Person::name()` now returns the `first_name` field. The method is still called `name`; the field it reads +has moved into the wiring, where a context can change it without touching the trait or any code that calls +it. + +**This is an advanced tool, not the next step up from `#[cgp_auto_getter]`.** What you pay for the +decoupling is a line of wiring per context, and what you get is only useful when a context genuinely needs +to control which field is read, or to supply the value some way other than reading a field. Most getters +want neither. The [When to reach for it](#when-to-reach-for-it-and-when-not) section draws the line. + +## Using it + +Apply the attribute to a getter trait, exactly as with [`#[cgp_auto_getter]`](./cgp_auto_getter.md). The +same method forms are accepted — `&self` and `&mut self` receivers, and the `&str`, `&[T]`, `Option<&T>`, +`Option<&str>`, owned, and associated-type return shorthands, with their +[access rules](./cgp_auto_getter.md#how-the-return-type-decides-the-read) unchanged: + +```rust +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} +``` + +Because `#[cgp_getter]` builds on [`#[cgp_component]`](./cgp_component.md), it needs a provider trait name +and derives one from the **trait** name: a leading `Has` is stripped and `Getter` appended, so `HasName` +yields the provider trait `NameGetter` and the marker `NameGetterComponent`. The macro is therefore at its +most ergonomic when getter traits follow the `Has{Field}` convention. + +Pass an identifier to override it, as with `#[cgp_component]`: + +```rust +#[cgp_getter(GetName)] +pub trait HasName { + fn name(&self) -> &str; +} +``` + +Here the provider trait is `GetName` and the component `GetNameComponent`. The keyed +`name` / `provider` / `context` form works too; only the default for `provider` differs from +`#[cgp_component]`. + +### What a context can wire it to + +Three providers come out of the macro, and which you name decides where the value comes from. + +| Wire it to | The getter reads | +|---|---| +| [`UseField`](../providers/use_field.md) | the field named `f`, whatever the method is called | +| `UseFields` | the field named after each method — the `#[cgp_auto_getter]` behaviour, as a provider | +| [`WithProvider

`](../providers/with_provider.md) | whatever the field-getter provider `P` supplies | + +`UseField` is the one to reach for, and the reason the construct exists. `UseFields` is useful when a +trait has several methods and the names all happen to match, and it is the only one of the three that +works for a multi-method trait — the other two presuppose a single field. + +A `#[cgp_getter]` trait can also be implemented directly on a concrete context, like any Rust trait, when +a particular context wants neither wiring nor a field. + +## Examples + +The case `#[cgp_auto_getter]` cannot express: the trait method is `name`, and the context stores the value +in `first_name`. + +```rust +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} + +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} + +pub fn greet(person: &Person) { + println!("Hello, {}!", person.name()); +} +``` + +`person.name()` returns `first_name`, because the wiring said so. A second context can store it under yet +another name and wire accordingly, with `HasName` and every caller unchanged — which is the whole +difference from the blanket-impl getter. + +Where the names *do* line up, `UseFields` gives the auto-getter behaviour without giving up the component: + +```rust +delegate_components! { + Employee { + NameGetterComponent: UseFields, + } +} +``` + +And a context that computes the value rather than storing it implements the consumer trait directly, +skipping both the wiring and the field: + +```rust +pub struct Anonymous; + +impl HasName for Anonymous { + fn name(&self) -> &str { + "anonymous" + } +} +``` + +That last form is worth seeing, because it shows a `#[cgp_getter]` trait is an ordinary component whose +consumer trait can be implemented like any Rust trait. + +## When to reach for it, and when not + +**Do not reach for `#[cgp_getter]` by default.** Among the three ways to read a value from a context it is +the last resort, and the ordering is worth holding whole: + +1. **An [`#[implicit]`](../attributes/implicit.md) argument** for a provider reading a field of its own + context. No trait, no wiring — this covers most reads. +2. **[`#[cgp_auto_getter]`](./cgp_auto_getter.md)** when the accessor has to exist as a *named + capability* other code depends on, when the field lives on another type, or when the getter carries a + type inferred from the field. One blanket impl, still no wiring. +3. **`#[cgp_getter]`** only when a context must control *how the getter is satisfied*. + +That third condition is narrow, and it has two real forms. One is a **field name that differs per +context** — the same capability reading `first_name` on one type and `display_name` on another. The other +is a context that supplies the value **some way other than a plain field read**, through +`WithProvider` or a hand-written impl, while other contexts still read a field. + +Reach for something else in these cases. + +- **Every context stores the field under the method's name.** Then the wiring line is pure ceremony: + `#[cgp_auto_getter]` gives the same result with nothing to wire, and wiring `UseFields` here is a sign + the component was not needed. +- **Only one provider reads the value.** An `#[implicit]` argument is shorter and keeps the requirement + where the provider is written. +- **The value is a *type* rather than a value.** [`#[cgp_type]`](./cgp_type.md) is the abstract-type + component, and `UseType` is its counterpart to this construct's `UseField`. +- **The trait has several methods and you want per-context field choice for each.** `UseField` handles one + field, so a multi-method getter wired this way has to go through `UseFields` or a hand-written provider. + Splitting into one component per field is usually the better answer. + +## Under the hood + +:::note + +### Advanced + +This section shows the getter-specific providers the macro adds. You do not need them to use +`#[cgp_getter]`, but the `UseField` impl is what makes the field name a wiring decision, and seeing it +explains why the tag is a parameter here and a fixed value in the auto-getter. `cargo cgp expand` prints +the same thing for your own code. ::: + +`#[cgp_getter]` emits everything [`#[cgp_component]`](./cgp_component.md) would — the consumer trait, the +provider trait, the two blanket impls, the marker, and the standard +[`UseContext`](../providers/use_context.md) and [`RedirectLookup`](../providers/redirect_lookup.md) +impls — then adds the getter providers below. `UseFields` is always emitted; `UseField` and `WithProvider` +only when the trait has exactly one method, since both presuppose a single field. + +The important addition is the **`UseField` impl**, which is what decouples the field from the method name. +From this trait: + +```rust +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} +``` + +the macro generates: + +```rust +impl<__Context__, __Tag__> NameGetter<__Context__> for UseField<__Tag__> +where + __Context__: HasField<__Tag__, Value = String>, +{ + fn name(__context__: &__Context__) -> &str { + __context__.get_field(PhantomData::<__Tag__>).as_str() + } +} +``` + +**`__Tag__` is a free generic parameter**, and that is the entire difference from +[`#[cgp_auto_getter]`](./cgp_auto_getter.md), whose blanket impl hard-codes the tag to +`Symbol!("name")`. Here the tag is whatever the wiring supplies, so `UseField` +reads `first_name`. The `&str` shorthand behaves identically in both: the bound asks for a `String` and the +body appends `.as_str()`. + +Next is the `UseFields` impl, which is the auto-getter's behaviour expressed as a provider — the tag fixed +to each method's own name: + +```rust +impl<__Context__> NameGetter<__Context__> for UseFields +where + __Context__: HasField, +{ + fn name(__context__: &__Context__) -> &str { + __context__.get_field(PhantomData::).as_str() + } +} +``` + +Last is a [`WithProvider`](../providers/with_provider.md) impl, which adapts a general field-getter +provider into this component, so the value need not come from a field read at all: + +```rust +impl<__Context__, __Provider__> NameGetter<__Context__> for WithProvider<__Provider__> +where + __Provider__: FieldGetter<__Context__, NameGetterComponent, Value = String>, +{ + fn name(__context__: &__Context__) -> &str { + __Provider__::get_field(__context__, PhantomData::).as_str() + } +} +``` + +Each of these is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl carrying the +same bounds, so a missing field is reported by name when the component is checked. + +

+Formal grammar + +The attribute argument is the same grammar as [`#[cgp_component]`](./cgp_component.md)'s, in the Rust +Reference's [notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpGetterArgs -> CgpComponentArgs // see #[cgp_component] +``` + +A bare provider name, or the keyed `name` / `provider` / `context` form. The only difference from +`#[cgp_component]` is the default applied when `provider` is omitted: rather than being required, it is +derived from the trait name by stripping a leading `Has` and appending `Getter`, so `HasName` yields +`NameGetter`. Every other key and default behaves as documented there. + +
+ +## Gotchas + +**A multi-method trait gets no `UseField` provider.** Both `UseField` and `WithProvider` are emitted only +for a single-method trait, because each supplies one field. Wiring a two-method getter to +`UseField` therefore reports the provider as not being a provider for the component, +with the tag expanded into its raw spine: + +```text +error[E0277]: the trait bound `UseField>>: IsProviderFor<..., ...>` + is not satisfied +``` + +Nothing in that says the trait had too many methods, which is the actual cause. Use `UseFields`, or split +the trait into one component per field. + +**The provider name is derived by stripping `Has`.** `HasName` yields `NameGetterComponent`, so a trait +*not* named `Has…` produces a component whose name may surprise you — `Dimensions` yields +`DimensionsGetterComponent`. Pass the name explicitly when the convention does not fit. + +**Wiring `UseFields` everywhere means the component was unnecessary.** If no context ever names a +different field, [`#[cgp_auto_getter]`](./cgp_auto_getter.md) does the same job with no wiring at all, and +the component is a line per context of pure overhead. + +**The field's type still has to match the return type's rule.** `UseField` on a getter +returning `&str` requires `first_name` to be a `String`; a `&'static str` field does not qualify, because the +tag chose the field and not the conversion: + +```text +error[E0271]: type mismatch resolving `

>>>::Value == String` +``` + +The `Symbol<10, …>` in that message is `first_name` with its length in bytes — worth being able to read, since +the tag is what tells you which field the mismatch is about. + +## Related constructs + +- [`#[cgp_auto_getter]`](./cgp_auto_getter.md) — the blanket-impl getter, and the one to prefer. +- [`#[implicit]`](../attributes/implicit.md) — the default way to read a field, ahead of either getter. +- [`UseField`](../providers/use_field.md) — the provider that makes the field name a wiring decision, with + `UseFieldRef` and `UseFields` alongside it. +- [`#[cgp_component]`](./cgp_component.md) — the macro this extends, and the source of the naming rules. +- [`#[derive(HasField)]`](../derives/derive_has_field.md) and [`HasField`](../traits/has_field.md) — the + field access underneath. +- [`Symbol!`](./symbol.md) — the type-level field name a wiring entry supplies. +- [`WithProvider`](../providers/with_provider.md) — the adapter for a value that does not come from a field. +- [`#[cgp_type]`](./cgp_type.md) — the same idea for a type rather than a value. + +## Source + +- Entry point: [`cgp_getter.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_getter.rs) +- Implementation: [`types/cgp_getter/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_getter/) +- Getter parsing, shared with `#[cgp_auto_getter]`: [`functions/getter/parse.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/getter/parse.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 60f91973..88636b86 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -6,12 +6,404 @@ sidebar_label: 'cgp_namespace!' Define a reusable, inheritable wiring table that many contexts can join. -:::info +## What it's for -### Not written yet +With [`delegate_components!`](./delegate_components.md) alone, every **context** — the type the capability +runs against, which supplies the values it needs as its fields — spells out its own wiring entry by entry. +Two contexts that should share the same providers repeat the same lines, and a table grows with the number +of components until the wiring is the largest thing in the file. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`cgp_namespace!` lifts a table out of any one context and gives it a name, so other contexts can adopt it: + +```rust +cgp_namespace! { + new AppNamespace { + // shared wiring lives here + } +} +``` + +A context then **joins** it with one line inside its own table, after which every lookup it does not wire +directly falls through to the namespace. Its own entries win, so a namespace behaves like a base +configuration each context specializes — most of the wiring for free, and a handful of overrides where they +matter. + +That inherit-and-override behaviour is why **a namespace is how CGP expresses presets.** There is no +separate preset construct: a library publishes a namespace of sensible defaults, an application joins it and +changes the few entries it cares about. Namespaces can also inherit from one another, so a base can be +extended into a richer one that every downstream context picks up. + +One structural point saves confusion later: **a namespace is not a context.** It is a trait — named after +the namespace — carrying a `Delegate` associated type and implemented once per key. Nothing instantiates it, +and it holds no wiring of its own at the context level; it only says where a lookup should go next. + +## Using it + +The body resembles a [`delegate_components!`](./delegate_components.md) table with an optional header. The +`new` keyword tells the macro to emit the namespace's trait and its backing struct: + +```rust +cgp_namespace! { + new MyNamespace { + FooProviderComponent => + @MyFooComponent, + } +} +``` + +Omit `new` only when the trait and struct are already declared elsewhere. + +### The two entry forms + +A namespace body accepts two kinds of entry, and they do different things. + +| Entry | Meaning | +|---|---| +| `Key => @path` | **Redirect.** Asked for `Key`, look up `@path` instead. The provider is decided wherever the path lands. | +| `Key: Provider` | **Bind.** Asked for `Key`, resolve straight to `Provider`, as in `delegate_components!`. | + +Redirection is what makes namespaces composable: because a lookup is keyed by a *path* rather than a bare +component name, a whole subtree can be rerouted at once, and a more specific path takes precedence over an +inherited one. Paths are written with the `@` sigil as dotted sequences — `@MyFooComponent`, +`@app.ErrorRaiserComponent`, `@cgp.core.error` — where lowercase segments become type-level strings and +capitalized segments name types. [`Path!`](./path.md) covers the syntax in full. + +### Inheriting from a parent + +Name a parent after a colon in the header, and the child resolves everything the parent does plus its own +entries: + +```rust +cgp_namespace! { + new ExtendedNamespace: BaseNamespace { + @cgp.core.error => + @app, + } +} +``` + +The parent may itself be parameterized. The child's entries layer on top, and a path-rewriting entry like +the one above reroutes a whole subtree of the parent's namespace rather than a single component. + +### The other two halves: registering, and joining + +Defining a namespace is only a third of the pattern. A component **registers into** one with the +`#[prefix(...)]` attribute on its trait, which puts that component's lookups under a path: + +```rust +#[cgp_component(ShowImpl)] +#[prefix(@show in AppNamespace)] +pub trait CanShow { + fn show(&self) -> String; +} +``` + +A context **joins** one with a `namespace` header inside its own table, after which unwired lookups forward +through it: + +```rust +delegate_components! { + MyApp { + namespace AppNamespace; + + @show.ShowImplComponent: ShowWithDebug, + } +} +``` + +A third statement form, `for in SomeTable { … }`, reads each entry of another lookup table and +emits one mapping per entry — which is how per-type defaults are pulled in wholesale. + +## Examples + +A complete namespace, end to end: a component registered under a prefix, a namespace to hold the route, and +a context that joins it and supplies the provider at the prefixed path. + +```rust +use cgp::prelude::*; + +#[cgp_component(ShowImpl)] +#[prefix(@show in AppNamespace)] +pub trait CanShow { + fn show(&self) -> String; +} + +#[cgp_impl(new ShowWithDebug)] +#[uses(core::fmt::Debug)] +impl ShowImpl { + fn show(&self) -> String { + format!("{:?}", self) + } +} + +cgp_namespace! { + new AppNamespace {} +} + +#[derive(Debug)] +pub struct MyApp; + +delegate_components! { + MyApp { + namespace AppNamespace; + + @show.ShowImplComponent: ShowWithDebug, + } +} + +check_components! { + MyApp { + ShowImplComponent, + } +} +``` + +Reading the resolution: `MyApp.show()` looks up `ShowImplComponent`, finds no direct entry, falls through to +`AppNamespace`, which redirects to the path `@show.ShowImplComponent` — and `MyApp`'s own table binds that +path to `ShowWithDebug`. **The division of labour is the point.** The namespace owns the *route*; the context +owns the *provider*. A second context joins the same namespace and supplies a different provider at the same +path, with nothing duplicated between them. + +Inheritance composes the same way. `ExtendedNamespace` resolves everything its parent does, so a context +joining the child inherits the whole chain: + +```rust +cgp_namespace! { new BaseNamespace {} } + +cgp_namespace! { new ExtendedNamespace: BaseNamespace {} } + +delegate_components! { + MyApp { + namespace ExtendedNamespace; + + @show.ShowImplComponent: ShowWithDebug, + } +} +``` + +## When to reach for it, and when not + +**Reach for a namespace when the same wiring is repeated across contexts, or when a top-level table has +grown too long to read.** Those are the two problems it solves, and below that threshold it costs more than +it saves — a namespace adds a layer of indirection between a component and its provider, which is one more +hop for a reader tracing what runs. + +Three lighter tools cover most cases, and it is worth knowing where each stops. + +- **A plain [`delegate_components!`](./delegate_components.md) table** is right while each context's wiring + is short and not shared. Most applications never outgrow this. +- **The [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement)** is the + lightweight special case of the same path machinery, for dispatching *one* component on its type parameter + directly on a context. It needs no namespace, no prefix, and no shared table — reach for it when the goal + is per-type dispatch rather than shared wiring. +- **An [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time)** — the + `new`-keyword bundle — packages a group of wirings that contexts adopt by *delegating* named components to + it, rather than by joining and inheriting. It is the more direct mechanism and the better choice for a + small, explicitly-delegated bundle. A namespace earns its extra machinery when there are many components, + when inheritance is wanted, or when a library is publishing defaults for applications it does not know + about. + +Two things a namespace is *not* for. It will not make a single context's wiring shorter on its own — the +entries still have to exist somewhere. And it is not how one component gets per-type dispatch, which is +`open`'s job; the two do not combine on the same component, as the [Gotchas](#gotchas) explain. + +## Under the hood + +:::note + +### Advanced + +This section shows the trait and impls a namespace becomes. You do not need them to use one, but namespace +failures are reported in terms of these types, and the resolution is far easier to follow once you have seen +that a namespace is a trait with one associated type. `cargo cgp expand` prints the same thing for your own +code. ::: + +`cgp_namespace!` emits, in order, an optional backing struct, an optional lookup trait, and one impl of that +trait per entry — plus one inheritance impl when a parent is named. From this input: + +```rust +cgp_namespace! { + new MyNamespace { + FooProviderComponent => + @MyFooComponent, + } +} +``` + +the `new` keyword emits a struct whose name wraps the namespace's, then the trait, which carries the table as +a parameter and a single associated type: + +```rust +pub struct __MyNamespaceComponents; + +pub trait MyNamespace<__Table__> { + type Delegate; +} +``` + +Each `=>` entry becomes an impl of that trait **for the key**, whose `Delegate` is a +[`RedirectLookup`](../providers/redirect_lookup.md) aiming the table at the entry's path: + +```rust +impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { + type Delegate = RedirectLookup<__Table__, Path!(@MyFooComponent)>; +} +``` + +Read it back as: `MyNamespace`'s delegate for `FooProviderComponent` is "look up the path `MyFooComponent` +inside whatever `__Table__` is". The namespace names no provider — it only reroutes, so the provider is +decided wherever the path finally lands. A `:` entry skips the indirection and maps the key straight to a +provider, one impl per key when the array form is used. + +`#[prefix(...)]` is the other side of this, and it generates an impl of exactly the same shape. From +`#[prefix(@show in AppNamespace)]` on a `CanShow` component: + +```rust +impl<__Components__> AppNamespace<__Components__> for ShowImplComponent { + type Delegate = RedirectLookup<__Components__, Path!(@show.ShowImplComponent)>; +} +``` + +So the component contributes its own route into the namespace, under the prefix, ending at its own component +name. That is why a joining context binds `@show.ShowImplComponent` rather than the bare component. A +component may carry several `#[prefix]` attributes to register into several namespaces. + +When a parent is named, the macro prepends a blanket impl forwarding every key the parent resolves: + +```rust +impl<__Table__, __Key__, __Value__> ExtendedNamespace<__Table__> for __Key__ +where + __Key__: BaseNamespace<__ExtendedNamespaceComponents>, + __Key__: BaseNamespace<__Table__, Delegate = __Value__>, +{ + type Delegate = __Value__; +} +``` + +For any key the parent resolves, the child resolves it to the same value. The child's own entries are emitted +after this impl and win where their keys are more specific. + +Two naming details appear verbatim in errors and are worth recognizing: the table parameter is literally +`__Table__`, and the inheritance impl uses `__Key__` and `__Value__`. And every `@` path is a +[type-level list](../types/type_level_spines.md) built by [`Path!`](./path.md) — `expand` resugars it to +`Path!(@…)` form, while a raw compiler error prints the underlying spine. + +

+Formal grammar + +The body is a header and a table, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpNamespace -> Generics? `new`? NamespaceName ( `:` ParentNamespace )? `{` NamespaceBody `}` + +NamespaceName -> IDENTIFIER GenericArgs? +ParentNamespace -> TypePath GenericArgs? + +NamespaceBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? +``` + +The `Mapping` production is [`delegate_components!`](./delegate_components.md)'s — most often `=>` to an +`@`-`Path`, or `:` to a provider. The `:` between `NamespaceName` and `ParentNamespace` is the inheritance +colon, distinct from a mapping's. `NamespaceName` becomes both a trait and, with `new`, a struct. + +This macro also owns the two statement forms a context's table uses to join a namespace: + +```ebnf +Statement -> NamespaceStmt | ForStmt + +NamespaceStmt -> `namespace` IDENTIFIER `;` + +ForStmt -> `for` `<` IDENTIFIER `,` IDENTIFIER `>` `in` TypePath WhereClause? + `{` ( NormalMapping ( `,` NormalMapping )* `,`? )? `}` + +NormalMapping -> Key `:` ProviderValue +``` + +A `NamespaceStmt` forwards every unwired lookup through the named namespace. A `ForStmt` binds a key variable +and a provider variable, reads each entry of the table named after `in`, and emits one mapping per entry; its +optional `WhereClause` is merged into every impl the loop generates. Like `delegate_components!`, the body +accepts **no attributes** on any entry and rejects any it finds. + +
+ +## Gotchas + +**A context cannot override a path its namespace itself terminates.** Joining with `namespace N;` emits a +blanket `DelegateComponent` impl covering every path `N` resolves, so a direct entry for one of those paths +is a second impl for the same key and the compiler rejects the overlap with `E0119`. Overriding works only on +a path the namespace *routes to* without binding — which is why the example above has the namespace own the +route and the context own the provider. A path the namespace binds with a `:` entry or a `#[default_impl]` +has to be changed in the namespace instead. The same restriction stops a child namespace from redefining a +key its parent binds. + +**Joining two namespaces on one context conflicts**, for the same reason — two blanket forwarding impls each +covering every key: + +```text +error[E0119]: conflicting implementations of trait `DelegateComponent<_>` for type `App` +``` + +A bare-key `for` loop (`for in Table { Key: Value }`) alongside a `namespace` join collides the +same way, which is why a loop's key is normally embedded in a path — `@app.SomeComponent.Key: Value`. + +**`open` does not combine with a prefixed component in a joined namespace.** Once a component's lookups are +routed under a prefix, `open` — which roots the route at the bare component name — no longer reaches those +entries. Write the per-value entries with the full prefixed path instead. + +**A cyclic parent chain and a self-inheriting namespace fail differently.** Two namespaces inheriting each +other make the forwarding impl's `where` clause loop, and the compiler rejects it eagerly at both +definitions: + +```text +error[E0275]: overflow evaluating the requirement `__Key__: A<__BComponents>` +note: required for `__Key__` to implement `B<__AComponents>` +``` + +A namespace inheriting *itself* — `new A: A {}` — does not overflow. It produces a forwarding impl whose +value parameter nothing can determine: + +```text +error[E0207]: the type parameter `__Value__` is not constrained by the impl trait, self type, or predicates +``` + +Both mean the inheritance chain is not acyclic, but only the first says so recognizably. + +**A registered component with no provider bound anywhere still compiles.** If a `#[prefix]` routes a component +into a namespace and nothing ever binds a provider at its path, the redirect lands on an empty slot and the +context compiles regardless. Only a [`check_components!`](./check_components.md) reports it, and what it +reports is the *path* failing to resolve rather than a provider being absent: + +```text +error[E0277]: the trait bound `PathCons>, ...>: AppNamespace<...>` + is not satisfied +``` + +The `Symbol<4, …>` is the prefix — `show` — so the message is saying "this route is not something the +namespace resolves". This is the lazy-wiring problem in namespace clothing, and the answer is the same: check +the context. + +## Related constructs + +- [`delegate_components!`](./delegate_components.md) — where a context joins a namespace, and the source of + the shared table grammar. +- [`Path!`](./path.md) — the `@`-path syntax namespace entries and `#[prefix]` use. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the provider every redirect resolves through. +- [`DefaultNamespace`](../traits/default_namespace.md) — inherited and per-type default resolution, + including `#[default_impl(...)]`. +- [`#[cgp_component]`](./cgp_component.md) — the host of the `#[prefix(...)]` attribute. +- [`DelegateComponent`](../traits/delegate_component.md) — the per-key table a redirect finally walks. +- [`check_components!`](./check_components.md) — the only thing that catches a route bound to nothing. + +## Source + +- Entry point: [`cgp_namespace.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_namespace.rs) +- Implementation: [`types/namespace/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/namespace/) +- The `#[prefix(...)]` attribute: [`types/attributes/prefix.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/prefix.rs) +- Runtime traits and `RedirectLookup`: [`cgp-component/src/namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index aa41022c..ac38af40 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -6,12 +6,273 @@ sidebar_label: '#[cgp_producer]' Define a `Producer` provider from an input-free function. -:::info +## What it's for -### Not written yet +`#[cgp_producer]` is for the degenerate member of the handler family: a computation that takes no input and +yields a value from nothing. A constant, a default, a seed for a pipeline. It is the input-free sibling of +[`#[cgp_computer]`](./cgp_computer.md), and like that macro it lets you write a plain function and have the +provider synthesized for you: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +#[cgp_producer] +fn magic_number() -> u64 { + 42 +} +``` + +That produces the provider struct `MagicNumber` and an impl of [`Producer`](../components/producer.md), the +family member whose method takes only a **context** — the type the capability runs against — and a phantom +`Code` tag, with no input value at all. + +The reason it is worth a macro of its own is what happens next. **A producer can stand in for any handler**, +because a handler that ignores its input is just a producer with an unused parameter. So the macro wires the +generated provider into every member of the family, and one function definition answers `produce`, +`compute`, `try_compute`, `compute_async`, `handle`, and their by-reference forms — every one of them +yielding the same value regardless of what it is handed. + +## Using it + +Apply the attribute to a free function. It takes an optional provider name: + +```rust +#[cgp_producer] +fn magic_number() -> u64 { + 42 +} + +#[cgp_producer(TheAnswer)] +fn magic_number() -> u64 { + 42 +} +``` + +Omitted, the provider struct takes the function name in PascalCase — `magic_number` becomes `MagicNumber`. +Given, the argument is used verbatim. The function's return type becomes the producer's output. + +**The function is constrained tightly, to exactly what a producer can be.** All three restrictions are +enforced at expansion time with their own messages: + +| Restriction | Why | +|---|---| +| No parameters, and no `self` | A producer takes no input and has no receiver. | +| Not `async` | The producer trait is synchronous. | +| No generic parameters | There is nothing to infer them from. | + +That third restriction is the one most likely to bite, and it is the sharpest difference from +[`#[cgp_computer]`](./cgp_computer.md), which carries generics through happily. A producer has no input, so a +type parameter would be determined by nothing at all. + +## Examples + +One function, read back through every shape the family offers: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{Producer, Computer, TryComputer, Handler}; + +#[cgp_producer] +pub fn magic_number() -> u64 { + 42 +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} + +// The single `magic_number` definition answers every shape, all yielding 42: +// MagicNumber::produce(&App, PhantomData::<()>) == 42 +// MagicNumber::compute(&App, PhantomData::<()>, &()) == 42 +// MagicNumber::try_compute(&App, PhantomData::<()>, &()) == Ok(42) +// MagicNumber::handle(&App, PhantomData::<()>, &()) resolves to Ok(42) +``` + +The computer and handler forms accept an input argument and discard it, since the underlying producer takes +none. The error type wired into `App` is what lets the fallible forms build their `Result`; the produced +value is always `Ok`. + +The typical use is as the first step of a pipeline, where a producer seeds the value the later steps +transform: + +```rust +delegate_components! { + App { + ComputerComponent: + PipeHandlers, + } +} +``` + +## When to reach for it, and when not + +**Reach for `#[cgp_producer]` when a pipeline step needs no input.** That is the whole of its remit, and +within it there is nothing simpler. + +- **Use [`#[cgp_computer]`](./cgp_computer.md) as soon as there is an input**, even a trivial one. It is the + same macro with the restrictions lifted, and it handles generics, `async`, and `Result` returns. +- **Write the provider by hand with [`#[cgp_impl]`](./cgp_impl.md) when the value comes from the context.** + This is the boundary that matters. A `#[cgp_producer]` function has no receiver, so it cannot read a field, + name an abstract type, or call a capability — it can only return something it computes from nothing. A + producer that draws on its context is an impl of `Producer` written with `#[cgp_impl]`, where `self` is the + context and [`#[implicit]`](../attributes/implicit.md) works normally. **In practice that covers most + producers**, which makes this macro narrower than it first looks: it is for constants and pure seeds. +- **Use [`ReturnInput`](../providers/handler_combinators.md) rather than a producer that ignores its input.** + If the goal is to pass a value through a pipeline unchanged, that combinator says so directly. +- **Do not reach for the handler family at all for a plain constant.** A `const` or a function is clearer + unless the value is genuinely being composed into a pipeline or dispatched on a `Code` tag. + +## Under the hood + +:::note + +### Advanced + +This section shows the three items the macro emits. You do not need them to use `#[cgp_producer]`, but the +delegation block is what makes one function answer eight components, and it differs from +[`#[cgp_computer]`](./cgp_computer.md)'s in a way worth noticing. `cargo cgp expand` prints the same thing for +your own code. ::: + +The macro emits the function unchanged, a provider impl of [`Producer`](../components/producer.md), and a +[`delegate_components!`](./delegate_components.md) block wiring the whole family. From this input: + +```rust +#[cgp_producer] +pub fn magic_number() -> u64 { + 42 +} +``` + +it produces the base impl, whose method ignores both of its parameters and simply calls the function: + +```rust +#[cgp_new_provider] +impl<__Context__, __Code__> Producer<__Context__, __Code__> for MagicNumber { + type Output = u64; + + fn produce(_context: &__Context__, _code: PhantomData<__Code__>) -> Self::Output { + magic_number() + } +} +``` + +[`#[cgp_new_provider]`](./cgp_provider.md) declares `pub struct MagicNumber;` and derives the +[`IsProviderFor`](../traits/is_provider_for.md) impl, whose parameter tuple here holds just the code tag. The +context and code parameters carry the reserved names `__Context__` and `__Code__`. + +Then the wiring, which reaches **all eight** other components: + +```rust +delegate_components! { + MagicNumber { + [ + ComputerComponent, + ComputerRefComponent, + TryComputerComponent, + TryComputerRefComponent, + AsyncComputerComponent, + AsyncComputerRefComponent, + HandlerComponent, + HandlerRefComponent, + ]: + PromoteProducer, + } +} +``` + +Two things differ from `#[cgp_computer]`'s block. `ComputerComponent` **is** in the list, because a producer +does not implement it directly — a computer takes an input and the producer has none, so the promotion is +what discards it. And the operator is **`:`** rather than `->`, delegating each component straight to +[`PromoteProducer`](../providers/handler_combinators.md) rather than to that bundle's own entry for the +key. `PromoteProducer` then wires `ComputerComponent` to a promoter that drops the input and calls `produce`, +and derives the remaining members from there. + +**Unlike `#[cgp_computer]`, the expansion has no variation.** Because the function cannot be async, cannot be +generic, and is not inspected for a `Result` return, there is exactly one base trait and one bundle for every +`#[cgp_producer]` — the output type is taken as written, whether or not it happens to be a `Result`. + +
+Formal grammar + +The attribute argument is a single optional provider name, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpProducerArgs -> ProviderName? + +ProviderName -> IDENTIFIER +``` + +Omitted, the provider struct takes the function name converted to PascalCase; a given `IDENTIFIER` is used +verbatim. The annotated function is plain Rust, constrained to a producer's shape — no parameters, no +`async`, no generics — as described in [Using it](#using-it). + +
+ +## Gotchas + +**All three shape restrictions have their own message**, so the macro tells you which one you broke: + +```text +error: Producer functions cannot have parameters +error: Producer functions cannot be async +error: Producer functions must have empty generic parameters +``` + +For the first two, [`#[cgp_computer]`](./cgp_computer.md) is the macro that accepts them. For the third there +is no macro alternative — write the provider by hand. + +**The function cannot reach the context**, so a producer that needs a field or an abstract type is not +expressible this way at all. That rules out most real producers, which is worth knowing before reaching for +the macro: write an impl of `Producer` with [`#[cgp_impl]`](./cgp_impl.md) instead. + +**A `Result` return is not interpreted**, and this is the sharpest trap on the page. Unlike +`#[cgp_computer]`, the macro does not inspect the output for fallibility, so a `#[cgp_producer]` returning +`Result` produces a `Producer` whose `Output` *is* that `Result` — and the fallible members wrap it +again rather than treating it as failure: + +```text +producer produce = Err("nope") +producer try_compute = Ok(Err("nope")) +``` + +That `Ok(Err(..))` is a success carrying an error, so it short-circuits nothing and a pipeline downstream +keeps going. If the production can genuinely fail, write a `TryComputer` or `Handler` provider by hand +instead. + +**The fallible forms still need an error type on the context.** `try_compute` and `handle` name the context's +abstract error, so a context lacking an +[`ErrorTypeProviderComponent`](../components/has_error_type.md) fails on those members while `produce` and +`compute` work. Note also that the wiring key is **not in the prelude** — it has to be imported from +`cgp::core::error`, and forgetting that reports the component as an unresolved type rather than as a missing +import. + +## Related constructs + +- [`#[cgp_computer]`](./cgp_computer.md) — the sibling for a computation that takes an input. +- [`Producer`](../components/producer.md) — the base component this implements. +- [Handler combinators](../providers/handler_combinators.md) — `PromoteProducer`, which this wires, plus + `ReturnInput` and `PipeHandlers`. +- [`Computer`](../components/computer.md) and [`Handler`](../components/handler.md) — the members the + promotion reaches. +- [`#[cgp_impl]`](./cgp_impl.md) — for a producer that needs its context, which is most of them. +- [`#[cgp_new_provider]`](./cgp_provider.md) — what the generated impl is emitted through. +- [`HasErrorType`](../components/has_error_type.md) — what the fallible forms require of a context. + +## Source + +- Entry point: [`entrypoints/cgp_producer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_producer.rs) +- The `Producer` trait: [`components/produce.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/produce.rs) +- The `PromoteProducer` bundle: [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 82985e51..1bd3e517 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -4,14 +4,367 @@ sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' # `#[cgp_provider]` & `#[cgp_new_provider]` -Implement a provider trait directly, in the inside-out shape the sugar desugars to — with or without declaring the provider struct. +Implement a provider trait directly, in the inside-out shape the sugar desugars to — with or without +declaring the provider struct. -:::info +## What it's for -### Not written yet +A provider trait is not shaped like the trait it came from. [`#[cgp_component]`](./cgp_component.md) +moves the original `Self` into an explicit leading type parameter for the **context** — the type the +capability runs against, which supplies the values it needs as its fields — and an implementation +targets a small named struct instead. Written out, a provider looks like this: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +impl AreaCalculator for RectangleArea +where + Context: HasDimensions, +{ + fn area(context: &Context) -> f64 { + context.width() * context.height() + } +} +``` + +That impl is correct on its own but incomplete. CGP requires a provider to *also* implement a marker +trait under exactly the same conditions, so that a context missing something the provider needs gets an +error naming the missing thing rather than a bare "trait not implemented". Written by hand, that means +duplicating the generics and the whole `where` clause, and keeping the two copies in step forever. + +`#[cgp_provider]` writes the second impl for you. You write only the real one, and the macro derives +its companion from it — same generics, same bounds, body stripped. The dependencies cannot drift out +of sync, because they are read off the impl rather than restated. + +`#[cgp_new_provider]` is the same macro with one addition: it also declares +`pub struct RectangleArea;`, so a provider that does not exist yet can be introduced in one block. + +**Neither is the form to write for a new provider.** [`#[cgp_impl]`](./cgp_impl.md) expresses the same +implementation in the consumer trait's shape — keeping `self`, `Self`, and the original signatures — +and desugars to exactly these two macros. Read this page to understand generated code and the narrow +cases the sugar cannot reach; write `#[cgp_impl]` the rest of the time. + +## Using it + +Apply the attribute to an `impl` block that implements a provider trait for a provider struct. The impl +is ordinary Rust: the trait carries the context as its leading type argument, the `Self` type is the +provider, and methods take the context as a plain parameter rather than as a receiver. + +```rust +#[cgp_provider] +impl AreaCalculator for RectangleArea +where + Context: HasDimensions, +{ + fn area(context: &Context) -> f64 { + context.width() * context.height() + } +} +``` + +Which of the two you use depends only on whether the struct already exists. + +| Macro | The provider struct | +|---|---| +| `#[cgp_provider]` | Must already be declared. | +| `#[cgp_new_provider]` | Declared by the macro. Must *not* be declared separately. | + +Both accept the same single optional argument: the **component type** to use in the generated marker +impl. Omitted, it defaults to the provider trait's name plus `Component`, so implementing +`AreaCalculator` targets `AreaCalculatorComponent`. Pass it explicitly when the trait's name does not +follow that convention: + +```rust +#[cgp_provider(RunnerComponent)] +impl Runner for RunWithFooBar +where + Context: CanFetchFoo + CanFetchBar, +{ + fn run(context: &Context, _code: PhantomData) -> Result<(), Context::Error> { + /* ... */ + } +} +``` + +### The struct `#[cgp_new_provider]` declares + +The struct's shape is taken from the `Self` type of the impl. A plain name yields a unit struct. A +generic provider yields a tuple struct holding a +[`PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html) over its parameters, so +that the parameters are bound: + +```rust +// from `... for RectangleArea` +pub struct RectangleArea; + +// from `... for SpawnAndRun` +pub struct SpawnAndRun(pub ::core::marker::PhantomData); +``` + +This is also the limit of what the attribute form can express, and the reason `#[cgp_provider]` still +has a job: a struct that needs a **default** generic parameter — the common +`pub struct IterSum(PhantomData);` shape a higher-order provider uses so it +can fall back to the context's own wiring — has to be written by hand, and so does one shared by +several impls. + +## Examples + +A complete provider with its struct declared separately, which is what `#[cgp_provider]` is for: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_auto_getter] +pub trait HasDimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; +} + +pub struct RectangleArea; + +#[cgp_provider] +impl AreaCalculator for RectangleArea +where + Context: HasDimensions, +{ + fn area(context: &Context) -> f64 { + context.width() * context.height() + } +} +``` + +A context wires it exactly as it would any provider, and the derived marker impl is what makes a +missing `width` field report itself as a missing field: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +The same provider with `#[cgp_new_provider]` drops the separate declaration and nothing else: + +```rust +#[cgp_new_provider] +impl AreaCalculator for RectangleArea +where + Context: HasDimensions, +{ + fn area(context: &Context) -> f64 { + context.width() * context.height() + } +} +``` + +And the same provider once more, in the form to actually write — where the context parameter is +inserted for you and the body keeps `self`: + +```rust +#[cgp_impl(new RectangleArea)] +#[uses(HasDimensions)] +impl AreaCalculator { + fn area(&self) -> f64 { + self.width() * self.height() + } +} +``` + +All three produce the same three items. The difference is only how much of the machinery is visible in +the source. + +## When to reach for it, and when not + +**Write [`#[cgp_impl]`](./cgp_impl.md) instead, by default.** It produces the identical output from +source that reads like an ordinary trait impl, which is why it is the recommended form and these two +are mostly what you *read* — in generated code, in a desugaring, and in CGP's own crates. + +Three cases genuinely call for the raw form. + +- **The struct cannot be declared by an attribute.** A default generic parameter, as in + `pub struct IterSum(PhantomData);`, or a struct several impls share. Write + the struct, then annotate each impl with `#[cgp_provider]`. +- **Reading, rather than writing.** A confusing provider error names types from this shape, and + `cargo cgp expand` prints it. Recognizing the form is most of what this page is for. + +**That first reason is narrower than it may seem, and it is worth saying what is *not* on the list.** +`#[cgp_impl]`'s explicit form — `impl AreaCalculator for Context` — reaches further than the +unqualified one, and covers cases that look like they would need the raw impl: a higher-ranked bound such +as `for<'a> &'a Context: IntoIterator` is expressible there, and so is pinning the provider to a single +concrete context with `impl AreaCalculator for Rectangle`. So the bound you want is very likely writable +in `#[cgp_impl]`; reach for `#[cgp_provider]` when the *struct* is the problem, not the bound. + +Between the two macros the choice is mechanical: `#[cgp_new_provider]` when the provider is new, +`#[cgp_provider]` when the struct already exists. There is no other difference, and using the wrong one +is a duplicate-definition error rather than anything subtle. + +## Under the hood + +:::note + +### Advanced + +This section shows the impls the macros emit. You do not need them to write a provider, but this is the +shape `#[cgp_impl]` desugars *to*, so reading it once explains most confusing provider errors. +`cargo cgp expand` prints the same thing for your own code. ::: + +`#[cgp_provider]` emits two items: your impl, passed through unchanged, and a marker impl derived from +it. From this input: + +```rust +#[cgp_provider] +impl ComputerRef for FirstNameToString +where + Context: HasField, +{ + type Output = String; + + fn compute_ref(context: &Context, _code: PhantomData, _input: &Input) -> String { + context.get_field(PhantomData).to_string() + } +} +``` + +the macro adds: + +```rust +impl IsProviderFor + for FirstNameToString +where + Context: HasField, +{} +``` + +The derived impl is your impl with the body and associated types removed and the trait swapped. It +keeps the same generic parameters and the same bounds, so it holds under precisely the conditions the +real impl holds — which is the whole point, since +[`IsProviderFor`](../traits/is_provider_for.md) is what a check evaluates to find out *why* a provider +does not apply. + +Its three trait arguments are assembled from the provider trait's own. The first is the **component** +(`ComputerRefComponent`, the default derived from the trait name, or whatever the attribute argument +said). The second is the **context**, taken from the provider trait's leading argument. The third is a +**tuple of every remaining parameter** — `(Code, Input)` here, and the empty `()` for a provider trait +that takes nothing but a context. + +**One bound is rewritten rather than copied**, and it is the mechanism that makes a nested provider +stack diagnosable. A bound naming *this component's provider trait* — the inner-provider bound of a +[higher-order provider](../attributes/use_provider.md) — gains its marker counterpart alongside it: + +```rust +#[cgp_new_provider] +impl AreaCalculator for Scaled +where + Inner: AreaCalculator, +{ + fn area(context: &Context) -> f64 { Inner::area(context) * 2.0 } +} +``` + +derives a marker impl whose clause carries both: + +```rust +impl IsProviderFor for Scaled +where + Inner: IsProviderFor + AreaCalculator, +{} +``` + +That added bound is what carries a requirement from the *inner* provider outward through the wrapper, +so a field missing three layers down still reaches the context where the component is checked. Bounds +of any other kind — an ordinary `Context: Clone`, a consumer-trait bound such as +`Context: CanPerimeter` — are copied verbatim, without a counterpart. + +`#[cgp_new_provider]` emits the same two items plus the struct, whose shape follows the `Self` type as +described [above](#the-struct-cgp_new_provider-declares). + +
+Formal grammar + +The attribute argument of either macro is a single optional component type, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpProviderArgs -> ComponentType? + +ComponentType -> Type +``` + +Omitted, the component defaults to the provider trait's name plus `Component`; given, that `Type` is +substituted into the first position of the generated marker impl. `Type` is the Rust type production. +The struct declaration that distinguishes `#[cgp_new_provider]` is implied by the macro name and is not +written in the argument. + +
+ +## Gotchas + +**`#[cgp_new_provider]` fails if the struct already exists**, which is the usual result of converting +one macro to the other and forgetting to delete the declaration: + +```text +error[E0428]: the name `RectangleArea` is defined multiple times +``` + +**The component argument is not checked against the trait.** Passing a component that does not belong +to the provider trait you are implementing produces a marker impl for the wrong key, so the provider +silently fails to satisfy the wiring that names it — the error appears at the wiring site, saying the +provider is not a provider for that component. Omit the argument unless the trait's name genuinely +departs from the `{Trait}Component` convention. + +**A provider's own associated const or type still needs qualifying**, though for a different reason than +in [`#[cgp_impl]`](./cgp_impl.md#gotchas). Here `Self` really is the provider and nothing rewrites it — +but the provider struct is also a perfectly good context, so the consumer blanket impl gives it the +*consumer* trait as well, and both traits declare the item. `Self::LIMIT` is therefore ambiguous rather +than missing: + +```text +error[E0034]: multiple applicable items in scope + | + | fn allowed(_context: &Context) -> bool { Self::LIMIT > 0 } + | ^^^^^ multiple `LIMIT` found + | +note: candidate #1 is defined in an impl of the trait `RateLimiter` for the type `AllowUnderLimit` +note: candidate #2 is defined in an impl of the trait `CanRateLimit` for the type `__Context__` +``` + +Name the provider trait to disambiguate — `>::LIMIT` — which works here +because `Self` is the provider. The `#[cgp_impl]` form needs +`>::LIMIT` instead, since there `Self` is the context. Either way +the consumer side is unaffected: a wired context reads `::LIMIT`. + +## Related constructs + +- [`#[cgp_impl]`](./cgp_impl.md) — the form to write, which desugars to these two. +- [`#[cgp_component]`](./cgp_component.md) — defines the provider trait being implemented. +- [`IsProviderFor`](../traits/is_provider_for.md) — the marker trait the macro derives, and why. +- [`delegate_components!`](./delegate_components.md) — wires a provider onto a context. +- [`check_components!`](./check_components.md) — evaluates the derived marker to report a missing + dependency by name. +- [`#[use_provider]`](../attributes/use_provider.md) — the higher-order-provider bound whose marker + counterpart the macro adds. +- [`UseContext`](../providers/use_context.md) — the usual default for a hand-written provider struct's + inner parameter. + +## Source + +- Entry points: [`cgp_provider.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_provider.rs) + and [`cgp_new_provider.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_new_provider.rs) +- Implementation: [`types/cgp_provider/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_provider/) +- The marker derivation: [`types/provider_impl.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/provider_impl.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index c1b9a69b..674b51f0 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -6,12 +6,326 @@ sidebar_label: '#[cgp_type]' Define an abstract-type component, whose concrete type each context chooses for itself. -:::info +## What it's for -### Not written yet +Generic code often has to name a type it should not choose. A fallible operation returns *some* error, a +geometry routine computes in *some* scalar, a storage layer holds *some* connection handle — and code +written once for many applications cannot decide which. Rust's answer is an +[associated type](https://doc.rust-lang.org/reference/items/associated-items.html): declare +`trait HasScalarType { type Scalar; }`, and code written against it says `Self::Scalar` while leaving the +actual type open. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +An abstract type in CGP is exactly that trait and nothing more exotic. What `#[cgp_type]` adds is the +ability to fill the slot by **wiring** rather than by writing an impl. Without it, giving a context a +concrete scalar means writing a provider by hand — a whole impl whose only content is +`type Scalar = f64;`. Since every abstract-type provider has that same trivial shape, `#[cgp_type]` +generates it once and for all, so a **context** — the type the capability runs against, which supplies +the values and types it needs — names the concrete type directly in its wiring table: + +```rust +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } +} +``` + +That is the payoff: `App` now implements `HasScalarType` with `Scalar = f64`, and no provider was written +anywhere. The arrangement mirrors what [`#[cgp_getter]`](./cgp_getter.md) does for values — one +general-purpose provider, parameterized by the thing the context wants to supply. + +Two consequences are worth having early. Because the type is chosen per context, two applications can +pick differently from the same generic code. And because the trait is an ordinary Rust trait, a context +can skip the wiring entirely and write `impl HasScalarType for App { type Scalar = f64; }` — barely +longer, and the clearest way to see that nothing unusual is happening. + +## Using it + +Apply the attribute to a trait containing **exactly one associated type and no methods**: + +```rust +#[cgp_type] +pub trait HasScalarType { + type Scalar; +} +``` + +Like [`#[cgp_component]`](./cgp_component.md), the component needs a provider trait name, and +`#[cgp_type]` derives one. **The default is keyed off the associated type's name, not the trait's** — +`type Scalar` yields the provider trait `ScalarTypeProvider` and the marker +`ScalarTypeProviderComponent`. This is worth fixing in mind, because every other macro derives its +default from the trait name. + +Pass an identifier to override it, exactly as with `#[cgp_component]`: + +```rust +#[cgp_type(ProvideScalar)] +pub trait HasScalarType { + type Scalar; +} +``` + +The keyed form works here too, so `name`, `provider`, and `context` can each be set explicitly. Only the +default for `provider` differs. + +### Bounds on the associated type + +A bound on the associated type is carried everywhere the type appears, and enforced on whatever concrete +type a context picks: + +```rust +#[cgp_type] +pub trait HasScalarType { + type Scalar: Copy; +} +``` + +A context whose wiring names a type that does not satisfy the bound is rejected — `UseType` here, +since `String` is not `Copy` — so the bound is written once on the declaration and enforced against every +context's choice. + +**It is enforced lazily, though, like all CGP wiring.** The `delegate_components!` entry naming +`UseType` compiles on its own; the failure appears only once a +[`check_components!`](./check_components.md) forces the question, or the type is finally used. The bound is a +real constraint, not a wiring-site guard. + +## Examples + +An abstract scalar, a context that supplies it, and generic code that never names a concrete type: + +```rust +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar: Copy; +} + +pub struct App; + +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } +} + +pub fn zero() -> Context::Scalar +where + Context: HasScalarType, + Context::Scalar: Default, +{ + Default::default() +} +``` + +`App` implements `HasScalarType` with `Scalar = f64` through the generated +[`UseType`](../providers/use_type.md) impl, and the `check_components!` block is what confirms `f64` satisfies +the `Copy` bound. + +The point compounds when several pieces of code share one type. Because the type lives on a trait the +context implements, everything that mentions a scalar refers to the *same* `Self::Scalar`, so one wiring +line fixes it for all of them: + +```rust +#[cgp_component(AreaCalculator)] +#[use_type(HasScalarType.Scalar)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> Scalar; +} +``` + +Here `Rectangle` and `Circle` carry no scalar type of their own — the context computing their areas does, +and changing its `UseType` to `UseType` changes the scalar for every shape at once. The bare +`Scalar` in that signature is [`#[use_type]`](../attributes/use_type.md) at work, which is how an +abstract type is *imported* wherever it is used. + +Direct implementation stays available, and is often clearer for a single context: + +```rust +impl HasScalarType for App { + type Scalar = f64; +} +``` + +## When to reach for it, and when not + +**Reach for `#[cgp_type]` whenever generic code has to name a type the context should choose.** The error +type is the canonical instance — CGP's own [`HasErrorType`](../components/has_error_type.md) is defined +exactly this way, which is why every fallible capability can say `Error` and mean whatever the +application picked. + +The decision worth making deliberately is **whether the type needs to be abstract at all**, because +there is a cheaper option covering more ground than it looks. + +- **Prefer an inferred impl parameter while the type only flows through values.** If the type appears + solely because a provider reads a field of it, + [`#[impl_generics]`](./cgp_fn.md#a-type-the-caller-should-not-name) on a `#[cgp_fn]` puts a parameter on + the implementation alone. Nothing is wired, nothing is declared, and a context qualifies just by + carrying a field of a compatible type. +- **Climb to an abstract type when the type must be nameable.** Two things force it: the capability's own + signature has to mention the type, or two capabilities have to agree they mean the *same* type. An + inferred parameter can do neither, since it exists only where a value of it passes through. +- **Never thread it as a generic parameter on the capability.** A parameter is an input the caller + supplies, so it lands in every intermediate signature whether that layer touches the type or not. An + abstract type is determined by the context and propagates nowhere. That difference is what the + construct is really buying, and it is why a context can decide a dozen types without any signature + growing. +- **Use plain [`#[cgp_component]`](./cgp_component.md) when the trait carries methods.** `#[cgp_type]` is + only for a trait whose entire content is one associated type. A trait with a method *and* a type it + produces is an ordinary component — CGP's own `CanCompute` is that shape. + +One alternative looks like this construct and is not. A getter written with +[`#[cgp_auto_getter]`](./cgp_auto_getter.md) may declare an associated type and return it, inferring it +from the field. When the type's only job is to be a getter's return type, that is shorter and needs no +wiring; `#[cgp_type]` is for a type that stands on its own. + +## Under the hood + +:::note + +### Advanced + +This section shows what the macro generates. You do not need it to use `#[cgp_type]`, but the `UseType` +impl is the piece that makes wiring a type possible, and seeing it explains why no provider has to be +written. `cargo cgp expand` prints the same thing for your own code. ::: + +`#[cgp_type]` emits everything [`#[cgp_component]`](./cgp_component.md) would, then adds two provider +impls of its own. The component half is the familiar shape — consumer trait, provider trait, two blanket +impls, marker, and the standard [`UseContext`](../providers/use_context.md) and +[`RedirectLookup`](../providers/redirect_lookup.md) impls — differing only in that every blanket impl +forwards an *associated type* rather than a method: + +```rust +pub trait ScalarTypeProvider<__Context__>: + IsProviderFor +{ + type Scalar: Copy; +} +``` + +The first addition is the **`UseType` impl**, and it is the heart of the macro. It implements the provider +trait for `UseType` by setting the abstract type to the generic parameter: + +```rust +impl ScalarTypeProvider<__Context__> for UseType +where + Scalar: Copy, +{ + type Scalar = Scalar; +} +``` + +Read it as: `UseType` is a provider that supplies `T`. Wiring a context's component to `UseType` +therefore gives it `Scalar = f64` with nothing written. Note the declaration's `Copy` bound copied into +the impl's `where` clause — that is what turns an unsuitable concrete type into an error where the wiring +names it. + +The second addition is a [`WithProvider`](../providers/with_provider.md) impl, which adapts CGP's +foundational abstract-type machinery into this component: + +```rust +impl<__Provider__, Scalar, __Context__> ScalarTypeProvider<__Context__> + for WithProvider<__Provider__> +where + Scalar: Copy, + __Provider__: TypeProvider<__Context__, ScalarTypeProviderComponent, Type = Scalar>, +{ + type Scalar = Scalar; +} +``` + +[`HasType` / `TypeProvider`](../components/has_type.md) is CGP's single built-in abstract-type component, +and `UseType` is itself a `TypeProvider`. This impl is what lets one `UseType` satisfy both the +built-in component and any `#[cgp_type]` component you declare, instead of needing a separate provider +per component. + +Each generated provider impl is paired with a matching +[`IsProviderFor`](../traits/is_provider_for.md) impl carrying the same bounds, as everywhere else. + +
+Formal grammar + +The attribute argument is the same grammar as [`#[cgp_component]`](./cgp_component.md)'s, in the Rust +Reference's [notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CgpTypeArgs -> CgpComponentArgs // see #[cgp_component] +``` + +A bare provider name, or the keyed `name` / `provider` / `context` form. The only difference from +`#[cgp_component]` is the default applied when `provider` is omitted: rather than being required, it is +derived from the **associated type's** name plus `TypeProvider`, so `type Scalar;` yields +`ScalarTypeProvider`. Every other key and default behaves as documented there. + +
+ +## Gotchas + +**The trait must contain exactly one associated type and nothing else.** A method beside the type, a +second type, or no type at all all report the same thing: + +```text +error: type trait should contain exactly one associated type item +``` + +A trait that genuinely needs a method alongside a type it produces is an ordinary +[`#[cgp_component]`](./cgp_component.md). + +**The associated type may not be generic or carry a `where` clause**, since the `UseType` impl supplies +one concrete type per wiring and has nowhere to put either: + +```text +error: generic associated type and where clause are not supported +``` + +**The default provider name comes from the type, not the trait.** `HasScalarType` declaring +`type Scalar` yields `ScalarTypeProviderComponent`, not `HasScalarTypeComponent` — so a wiring entry +guessed from the trait name names a component that does not exist, and the error is an unresolved type +rather than anything about wiring. + +**A bound on the type is not enforced at the wiring line.** Wiring `UseType` for a type declared +`Copy` compiles; nothing complains until a check evaluates the lookup, and then the primary span is the +component name in the `check_components!` block rather than the offending wiring entry: + +```text +error[E0277]: the trait bound `String: Copy` is not satisfied + --> src/main.rs:5:27 + | +5 | check_components! { App { ScalarTypeProviderComponent } } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` + | +note: required for `UseType` to implement `IsProviderFor` + | +2 | #[cgp_type] pub trait HasScalarType { type Scalar: Copy; } + | ^^^^^^^^^^^ ---- unsatisfied trait bound introduced here +``` + +The offending type and the declaration that demanded the bound are both in the notes rather than the +headline, so read downward. **Without a check the mistake is silent**, which is the ordinary consequence of +[lazy wiring](./delegate_components.md#gotchas) rather than anything specific to abstract types. + +## Related constructs + +- [`#[cgp_component]`](./cgp_component.md) — the general macro this specializes. +- [`UseType`](../providers/use_type.md) — the provider a context wires to supply the concrete type. +- [`#[use_type]`](../attributes/use_type.md) — imports an abstract type so its name can be written bare; + a different construct from the `UseType` provider despite the shared name. +- [`HasType`](../components/has_type.md) — CGP's built-in abstract-type component, which this builds on. +- [`HasErrorType`](../components/has_error_type.md) — the canonical abstract type, defined this way. +- [`UseDelegatedType`](../providers/use_delegated_type.md) — resolves the type through a table rather than + fixing it. +- [`WithProvider`](../providers/with_provider.md) — the adapter the second generated impl is for. +- [`#[cgp_getter]`](./cgp_getter.md) — the value-level counterpart, using `UseField` where this uses + `UseType`. + +## Source + +- Entry point: [`cgp_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_type.rs) +- Implementation: [`types/cgp_type/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_type/item.rs) +- Runtime `HasType`, `TypeProvider`, and `UseType`: [`cgp-type/src/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-type/src/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 421ca32a..ff5719c8 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -6,12 +6,390 @@ sidebar_label: 'check_components!' Assert at compile time that a context can actually use each component it wires. -:::info +## What it's for -### Not written yet +**CGP's wiring is lazy, and this macro is the answer to that.** When +[`delegate_components!`](./delegate_components.md) records that a **context** — the type the capability +runs against, which supplies the values it needs as its fields — delegates a component to some provider, +nothing checks that the provider can do the job. The entry is stored as a type-level fact and believed. +Whether the chosen provider's own requirements hold *for this context* is a separate question, and it is +not asked until something tries to use the component. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +So a context can look completely wired, compile, and still be broken. Every entry is accepted, the struct +compiles, the module compiles — and then the first call to the capability fails, often in a file far from +the mistake. + +`check_components!` forces the question at a line you choose: + +```rust +check_components! { + Person { + GreeterComponent, + } +} +``` + +That block has no runtime existence. It compiles if `Person` really can use the component and fails if it +cannot, at the wiring site rather than wherever the capability first gets called. + +The second thing it buys is a *readable* failure, and that is the part worth understanding. Asking the +obvious question — "does `Person` implement `CanGreet`?" — makes the compiler report only the last link in +the chain, typically that some provider does not implement its provider trait, with no word about why. The +macro instead routes the assertion through [`CanUseComponent`](../traits/can_use_component.md), which holds +only when the context both delegates the component *and* the chosen provider's real bounds are satisfied. +Because those bounds ride explicitly on a marker trait, the compiler evaluates them and names the one that +failed — a missing `name` field surfaces as a missing `name` field, not as an opaque "trait not +implemented". + +## Using it + +The macro takes one or more check tables. Each is a context type followed by a brace-delimited list of the +components to verify on it: + +```rust +check_components! { + Person { + GreeterComponent, + } +} +``` + +Several tables may appear in one invocation, each with its own context type and attributes. + +### Components with generic parameters + +A component taking type parameters needs them supplied, because a check must name something concrete to +verify. Parameters go after a colon — one bare, several as a tuple, mirroring how the provider trait groups +them: + +```rust +check_components! { + MyApp { + AreaCalculatorComponent: Rectangle, // one parameter + TransformCalculatorComponent: (Rectangle, f64), // two, as a tuple + } +} +``` + +Bracketing either side expands to the **cartesian product**, so a set of components can be checked against +a set of parameters in one line: + +```rust +check_components! { + MyApp { + [AreaCalculatorComponent, RotatorComponent]: [Rectangle, Circle], + } +} +``` + +That is four checks from one entry. A table may also carry a leading `<...>` generic list and a trailing +`where` clause, to introduce and constrain generics the checked parameters use. + +### Naming the check trait + +The macro derives a trait name of the form `__Check{Context}` — `__CheckPerson` — from the **final segment** +of the context's path, so `some_mod::Person` also yields `__CheckPerson`. Override it with +`#[check_trait(Name)]` on the table, which is what you need when two tables in one module would otherwise +collide: + +```rust +check_components! { + #[check_trait(CheckPersonGreeting)] + Person { + GreeterComponent, + } +} +``` + +Note that [`delegate_and_check_components!`](./delegate_and_check_components.md) derives +`__CanUse{Context}` instead — deliberately different, so both macros can be used once each in one module +without a clash. + +### Checking each provider instead of the context + +A `#[check_providers(...)]` attribute changes *what* is asserted. Rather than asking whether the context can +use the component, it asserts that each listed provider is a provider for that context, one independent impl +per provider: + +```rust +check_components! { + #[check_trait(CheckScaledProviders)] + #[check_providers( + RectangleArea, + ScaledArea, + )] + ScaledRectangle { + AreaCalculatorComponent, + } +} +``` + +**This is how a broken layer of a nested provider stack is localized**, and it is the main reason to keep +`check_components!` separate from the wiring. A dependency missing only from the outer wrapper fails the +wrapper's line alone, while one missing from the inner provider fails both — so the pattern of failures +tells you which layer to look at. It must list at least one provider, and may appear at most once per table. + +## Examples + +A check that catches a real mistake. The provider needs a `name` field, and the context has the wrong field +name: + +```rust +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, // GreetHello needs `name` +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} + +check_components! { + Person { + GreeterComponent, + } +} +``` + +The `delegate_components!` block compiles on its own, because wiring is lazy. The `check_components!` block +does not — and it fails *here*, naming the missing field, rather than at some later `person.greet()` in +another file. + +A generic component supplies its parameters, and the bracketed form checks several at once: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } +} +``` + +This verifies `MyApp: CanCalculateArea` and `MyApp: CanCalculateArea` in one table. + +## When to reach for it, and when not + +**Every context's wiring should be checked somehow.** That is the rule without exceptions; which macro does +it is what scales. + +- **Use a standalone `check_components!` for anything past simple wiring.** It is the form advanced + codebases keep, because it is the only one with full control: concrete parameters for generic keys, + `#[check_providers(...)]` for per-layer checks, and coverage of wiring the fused macro's derivation cannot + read — the `open` statement, `@`-path keys, and [namespaces](./cgp_namespace.md). +- **Use [`delegate_and_check_components!`](./delegate_and_check_components.md) while getting started, or for + plain `Component: Provider` tables.** It fuses wiring and checking so the check cannot be forgotten, + which is what a newcomer needs. Its derivation understands only the plain entry form. +- **Do not check an [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time) as + though it were a context.** A `new`-keyword bundle is delegated *to*; it has no fields and never stands in + the context position, so a context-side check on it asks the wrong question. Verify it through a real + context that delegates to it, or with `#[check_providers(...)]` against a real context. The + [Gotchas](#gotchas) show what happens if you try. + +One limit is worth stating plainly: **not every unsatisfied bound is a component.** A provider may depend on +an ordinary Rust trait, and there is no component to name in a table for that — the check will still surface +the unsatisfied bound, but you cannot ask for it directly. + +## Under the hood + +:::note + +### Advanced + +This section shows what a check table expands to. You do not need it to write one, but knowing that a check +is an empty impl explains both why it costs nothing at runtime and why its errors read the way they do. +`cargo cgp expand` prints the same thing for your own code. ::: + +A check table expands to one marker trait plus one empty impl per entry. The trait's supertrait *is* the +assertion; the impl has nothing of its own to prove, so it compiles exactly when the supertrait holds. From +this input: + +```rust +check_components! { + Person { + GreeterComponent, + } +} +``` + +the macro emits: + +```rust +trait __CheckPerson<__Component__, __Params__: ?Sized>: + CanUseComponent<__Component__, __Params__> +{} + +impl __CheckPerson for Person {} +``` + +The impl holds only if `Person: CanUseComponent`, which in turn requires that `Person` +delegates the component and that its delegate satisfies [`IsProviderFor`](../traits/is_provider_for.md) for +`Person`. That indirection is the entire point: because the marker carries the provider's real bounds, an +unmet one is reported specifically rather than as a bare missing implementation. The generic parameters are +literally `__Component__` and `__Params__` in the emitted code. + +Generic parameters land in the `__Params__` slot — one directly, several as a tuple: + +```rust +impl __CheckMyApp for MyApp {} +impl __CheckMyApp for MyApp {} +``` + +The bracketed forms expand to the product before any impl is emitted, so +`[AreaCalculatorComponent, RotatorComponent]: [Rectangle, Circle]` yields four impls. A table's own generics +and `where` clause are merged into every impl it produces, so +`<'a, I> Context where I: Clone { FooComponent: &'a I }` becomes +`impl<'a, I> __CheckContext for Context where I: Clone {}`. + +The `#[check_providers(...)]` form changes both the supertrait and the implementing type. The assertion +becomes `IsProviderFor` with the context *fixed*, and the impls are written for each provider: + +```rust +trait CheckScaledProviders<__Component__, __Params__: ?Sized>: + IsProviderFor<__Component__, ScaledRectangle, __Params__> +{} + +impl CheckScaledProviders for RectangleArea {} +impl CheckScaledProviders for ScaledArea {} +``` + +Because each provider is checked on its own line, the failures localize: a dependency the inner provider +lacks fails both impls, while one only the wrapper needs fails the wrapper's alone. + +
+Formal grammar + +The input is one or more check tables, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +CheckComponents -> CheckTable+ + +CheckTable -> TableAttr* Generics? ContextType WhereClause? `{` CheckEntries `}` + +TableAttr -> `#` `[` `check_trait` `(` IDENTIFIER `)` `]` + | `#` `[` `check_providers` `(` Type ( `,` Type )* `,`? `)` `]` + +ContextType -> Type + +CheckEntries -> ( CheckEntry ( `,` CheckEntry )* `,`? )? + +CheckEntry -> CheckKey ( `:` CheckValue )? + +CheckKey -> Type + | `[` Type ( `,` Type )* `,`? `]` + +CheckValue -> CheckParam + | `[` CheckParam ( `,` CheckParam )* `,`? `]` + +CheckParam -> Generics? Type +``` + +One invocation may carry several `CheckTable`s. `#[check_trait(...)]` overrides the derived +`__Check{Context}` name, and `#[check_providers(...)]` switches the assertion to the listed providers. A +`CheckEntry`'s value is omitted for a component with no generic parameters; when present, a bracketed +`CheckKey` or `CheckValue` expands to the cartesian product. `Generics`, `WhereClause`, and `Type` are Rust +grammar productions. + +
+ +## Gotchas + +**A check on an aggregate provider asks the wrong question, and how it fails depends on the provider.** A +`new`-keyword bundle is not a context, so a context-side check demands that the *bundle* satisfy the leaf +provider's dependencies. If that provider has none, the check passes vacuously and proves nothing. If it +needs anything from its context — a field, a type — the check fails, blaming the bundle: + +```text +error[E0277]: the trait bound `GeometryComponents: CanUseComponent` + is not satisfied +note: required for `RectangleArea` to implement + `IsProviderFor` +``` + +Nothing there says the target was never meant to be a context. Wire the bundle with plain +[`delegate_components!`](./delegate_components.md) and check it through a real context instead. + +**A component with generic parameters cannot be checked without them, and the error does not say so.** +Omitting the value emits a check with an empty parameter tuple, which a component expecting a `Shape` can +never satisfy — so what you get is an ordinary unsatisfied-wiring complaint that never mentions the +parameters: + +```text +error[E0277]: the trait bound `App: CanUseComponent` is not satisfied +``` + +That looks identical to a genuinely broken wiring. If a check fails on a generic component and the wiring +looks right, the missing value is the first thing to suspect. + +**`#[check_providers(...)]` must list at least one provider**, and is rejected rather than treated as a +no-op: + +```text +error: `#[check_providers(...)]` requires at least one provider type. +``` + +**Two tables in one module can collide on the derived name.** The name comes from the context's *last* path +segment, so `a::Person` and `b::Person` both derive `__CheckPerson` — and so do two tables for the same +context: + +```text +error[E0428]: the name `__CheckPerson` is defined multiple times +``` + +Use `#[check_trait(...)]` on one of them. + +**A passing check is not a claim that the capability is correct**, only that it resolves. It proves the +provider was found and its dependencies are satisfiable — not that the provider does what you meant. + +## Related constructs + +- [`delegate_components!`](./delegate_components.md) — the wiring this verifies. +- [`delegate_and_check_components!`](./delegate_and_check_components.md) — wires and checks in one step, for + simple tables. +- [`CanUseComponent`](../traits/can_use_component.md) — the assertion the default form makes. +- [`IsProviderFor`](../traits/is_provider_for.md) — what `#[check_providers]` asserts, and what carries a + provider's real bounds. +- [`DelegateComponent`](../traits/delegate_component.md) — the lazily-accepted table entry that makes a check + necessary. +- [`#[cgp_component]`](./cgp_component.md) — defines the components a table names. +- [`#[use_provider]`](../attributes/use_provider.md) — builds the nested stacks `#[check_providers]` exists + to localize. + +## Source + +- Entry point: [`check_components.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/check_components.rs) +- Implementation: [`types/check_components/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/check_components/) +- Runtime traits: [`cgp-component/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-component/src/traits/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 25537997..f32ed8e5 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -6,12 +6,350 @@ sidebar_label: 'delegate_and_check_components!' Wire a context and check that wiring in one macro. -:::info +## What it's for -### Not written yet +CGP's wiring is [lazy](./delegate_components.md#gotchas): a +[`delegate_components!`](./delegate_components.md) entry is accepted without verifying that the provider it +names can actually satisfy the component, so a **context** — the type the capability runs against, which +supplies the values it needs as its fields — can compile while being broken. The fix is a +[`check_components!`](./check_components.md) block, and the problem with the fix is that keeping it in step +with the wiring is manual. Add a delegation, remember to add its check. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`delegate_and_check_components!` removes that bookkeeping by deriving the checks from the delegations: + +```rust +delegate_and_check_components! { + MyContext { + NameTypeProviderComponent: UseType, + NameGetterComponent: UseField, + } +} +``` + +Every entry is wired *and* proven, in one place, with nothing to keep in sync. What it emits is exactly what +writing both macros by hand would emit. + +**It is aimed at simple wiring and at getting started, not at being the default everywhere.** Its value is +that a newcomer cannot forget the check and then meet the confusing errors lazy wiring produces. The +derivation understands only the plain `Component: Provider` form, though, so a codebase whose wiring grows +past that keeps the two macros separate — the reasons are in +[When to reach for it](#when-to-reach-for-it-and-when-not). + +## Using it + +The macro takes the same table shape as [`delegate_components!`](./delegate_components.md) — an optional +generic list and `new` keyword, a target type, and brace-delimited `Key: Value` entries — plus a few +attributes governing the checking half: + +```rust +delegate_and_check_components! { + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } +} +``` + +Every delegated component is checked unless explicitly opted out, so the default is "wire it and prove it +works". + +### Naming the check trait + +The derived trait is named `__CanUse{Context}` — `__CanUseScaledRectangle`. That deliberately differs from +the `__Check{Context}` name [`check_components!`](./check_components.md) derives, so both macros can be used +once each in the same module without colliding. Override it with a table-level `#[check_trait(Name)]`: + +```rust +delegate_and_check_components! { + #[check_trait(TestScaledRectangle)] + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } +} +``` + +### Components with generic parameters + +A component with type parameters needs `#[check_params(...)]` on its entry. The delegation half does not +need them — its impl is generic over them — but the check half must name something concrete, and the macro +cannot infer what from the delegation alone: + +```rust +delegate_and_check_components! { + MyApp { + #[check_params( + Rectangle, + Circle, + )] + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +The same single-versus-tuple convention as `check_components!` applies: one parameter bare, several as a +tuple. + +### Skipping one entry's check + +`#[skip_check]` wires an entry and generates no check for it, for a component verified elsewhere. It saves +splitting out a second plain `delegate_components!` block just to leave one component unchecked: + +```rust +delegate_and_check_components! { + ScaledRectangle { + #[skip_check] + AreaCalculatorComponent: ScaledArea, + } +} +``` + +The two per-entry attributes are **mutually exclusive**, and at most one may appear on a given key. + +## Examples + +The intended use — a straightforward context, wired and proven together: + +```rust +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct MyContext { + pub name: String, +} + +delegate_and_check_components! { + MyContext { + NameGetterComponent: UseField, + } +} +``` + +If `MyContext` were missing the `name` field, the derived check would fail here, naming the missing field, +rather than letting the gap survive to some later call to `name()`. + +Mixing checked and skipped entries lets a nested delegation be verified more precisely elsewhere while the +rest is checked inline: + +```rust +delegate_and_check_components! { + ScaledRectangle { + AreaCalculatorComponent: + ScaledArea, + + #[skip_check] + TransformCalculatorComponent: + ComplexTransform, + } +} + +check_components! { + #[check_providers(RectangleArea, ComplexTransform)] + ScaledRectangle { + TransformCalculatorComponent, + } +} +``` + +That pairing is the usual reason to reach for `#[skip_check]`: the fused derivation can only check the +context, and a nested stack is better checked per layer. + +## When to reach for it, and when not + +**Reach for it while getting started, and for tables that are plain `Component: Provider` entries.** It is +the form that makes forgetting a check impossible, which is worth more than the control it gives up when the +wiring is simple. + +**Keep the two macros separate once the wiring is not simple.** The derivation reads delegation keys, so +there are three things it cannot do, and each is a reason a larger codebase writes +[`delegate_components!`](./delegate_components.md) and [`check_components!`](./check_components.md) apart: + +- **Per-layer checks.** Only a standalone block can use `#[check_providers(...)]`, which is what localizes a + broken layer of a nested provider stack. +- **Generic-parameter dispatch.** The `open` statement and `@`-path keys wire a provider per type; the + derivation cannot tell which concrete types to check, so those entries need a standalone block naming them. +- **[Namespaces](./cgp_namespace.md).** A `namespace` header brings in components the table never names, so a + derived check covers only the entries written directly and says nothing about what was inherited. + +**One case makes this macro wrong rather than merely unnecessary: an +[aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time).** A `new`-keyword bundle +is a provider other contexts delegate *to*, never a context itself — it has no fields and never stands in the +context position — so the derived context-side check asks a question that does not apply to it. Wire a bundle +with plain `delegate_components!`. The [Gotchas](#gotchas) show what the failure looks like, and why it is +easy to misread. + +The invariant across all of this is that a context's wiring is checked *somehow*. This macro is the +beginner-proof way to guarantee that for simple contexts; the two separate macros are the way that scales. + +## Under the hood + +:::note + +### Advanced + +This section shows both halves of what the macro emits. You do not need it to use the macro, but seeing that +the output is literally the two macros concatenated is what makes a later move to separate blocks +uneventful. `cargo cgp expand` prints the same thing for your own code. ::: + +The macro emits the delegation impls exactly as [`delegate_components!`](./delegate_components.md) would, +then appends a check trait and one impl per non-skipped entry exactly as +[`check_components!`](./check_components.md) would. From this input: + +```rust +delegate_and_check_components! { + #[check_trait(CheckMyContext)] + MyContext { + NameTypeProviderComponent: UseType, + NameGetterComponent: UseField, + } +} +``` + +the wiring half is a [`DelegateComponent`](../traits/delegate_component.md) impl plus an +[`IsProviderFor`](../traits/is_provider_for.md) forwarding impl per entry: + +```rust +impl DelegateComponent for MyContext { + type Delegate = UseType; +} +impl<__Context__, __Params__> + IsProviderFor for MyContext +where + UseType: IsProviderFor, +{} +``` + +and the same pair again for `NameGetterComponent`. Then the checking half — a marker trait aliasing +[`CanUseComponent`](../traits/can_use_component.md), with one empty impl per delegated component: + +```rust +trait CheckMyContext<__Component__, __Params__: ?Sized>: + CanUseComponent<__Component__, __Params__> +{} + +impl CheckMyContext for MyContext {} +impl CheckMyContext for MyContext {} +``` + +Without the `#[check_trait(...)]` override the trait would be `__CanUseMyContext`. The whole output is +identical to a `delegate_components!` block followed by a `check_components!` block whose trait carries the +`__CanUse{Context}` name — which is why moving to separate blocks later changes nothing about what is +checked. + +A `#[check_params(...)]` entry expands its parameters into the `__Params__` slot, one check impl per listed +parameter, while its single delegation impl stays generic over them: + +```rust +impl __CanUseMyApp for MyApp {} +impl __CanUseMyApp for MyApp {} +``` + +A `#[skip_check]` entry contributes its delegation impls and no check impl — present in the first half, +absent from the second. + +A generic table threads its generics through both halves, so ` MyContext { … }` yields +`impl DelegateComponent<…> for MyContext` alongside +`impl __CanUseMyContext<…, ()> for MyContext {}`. A key carrying its own generics is bound on the +derived check the same way, so ` BarGetterAtComponent: UseField` checks as +`impl __CanUse…, ()> for MyContext {}`. + +
+Formal grammar + +The body is [`delegate_components!`](./delegate_components.md)'s table shape plus the check attributes, in the +Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +DelegateAndCheck -> TableAttr* Generics? `new`? TargetType `{` TableBody `}` + +TableAttr -> `#` `[` `check_trait` `(` IDENTIFIER `)` `]` + +TableBody -> Statement* ( CheckedMapping ( `,` CheckedMapping )* `,`? )? + +CheckedMapping -> EntryAttr? Mapping // Mapping, Key, ProviderValue, Statement + // — see delegate_components! + +EntryAttr -> `#` `[` `check_params` `(` Type ( `,` Type )* `,`? `)` `]` + | `#` `[` `skip_check` `]` +``` + +The `Mapping`, `Key`, `ProviderValue`, and `Statement` productions are exactly +[`delegate_components!`](./delegate_components.md)'s; only the attributes differ. The table-level +`#[check_trait(...)]` overrides the derived `__CanUse{Context}` name. Each mapping may carry at most one +`EntryAttr`, and the two are mutually exclusive: `#[check_params(...)]` supplies the parameters a generic +component's check needs, and `#[skip_check]` wires the entry with no check at all. + +
+ +## Gotchas + +**Used on an aggregate provider, this macro reports a failure that describes nothing real.** A `new`-keyword +bundle is not a context, so the derived check asks whether the *bundle* satisfies the leaf provider's +dependencies. When the bundled provider needs nothing, the check passes and proves nothing; when it needs +anything from its context, the check fails and blames the bundle: + +```text +error[E0277]: the trait bound `GeometryComponents: CanUseComponent` + is not satisfied +note: required for `RectangleArea` to implement + `IsProviderFor` +``` + +Neither outcome is informative, and neither says the target was never meant to be a context. Use plain +[`delegate_components!`](./delegate_components.md) for a bundle. + +**The two per-entry attributes cannot be combined**, and the macro says so rather than picking one: + +```text +error: Expected at most one `#[check_params]` or `#[skip_check]` attribute +``` + +**A generic component without `#[check_params(...)]` cannot be checked, and the error does not say so.** The +delegation succeeds; the derived check is emitted with an empty parameter tuple, which a component expecting a +type parameter can never satisfy. What surfaces is an ordinary unsatisfied-marker complaint against the +provider: + +```text +error[E0277]: the trait bound `RectArea: IsProviderFor` is not satisfied +``` + +Nothing in it mentions the missing parameters, so it reads like a broken provider rather than an incomplete +check. Add `#[check_params(...)]`, or move the entry to a standalone +[`check_components!`](./check_components.md). + +**An inherited or opened component is not covered.** A `namespace` header or an `open` statement is accepted +in the table, but the derivation only produces checks for entries it can read as `Component: Provider` — so a +table using either is *partly* checked, with no warning about the rest. Add a standalone +[`check_components!`](./check_components.md) for those. + +## Related constructs + +- [`delegate_components!`](./delegate_components.md) — the wiring half, and what to use alone for a bundle. +- [`check_components!`](./check_components.md) — the checking half, and the form to use once wiring grows. +- [`CanUseComponent`](../traits/can_use_component.md) — the assertion the derived check makes. +- [`DelegateComponent`](../traits/delegate_component.md) and + [`IsProviderFor`](../traits/is_provider_for.md) — the impls each entry expands into. +- [`#[cgp_component]`](./cgp_component.md) — defines the components a table wires. +- [`cgp_namespace!`](./cgp_namespace.md) — inherited wiring, which the derivation does not cover. +- [`UseField`](../providers/use_field.md) and [`UseType`](../providers/use_type.md) — the providers the + examples wire. + +## Source + +- Entry point: [`delegate_and_check_components.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/delegate_and_check_components.rs) +- Implementation: [`types/delegate_and_check_components/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_and_check_components/) +- The two reused tables: [`types/delegate_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/) + and [`types/check_components/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/check_components/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 4a49f709..b9816ba0 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -246,8 +246,9 @@ compiles, and the failure only surfaces later, where the capability is used. forgotten. - **Use plain `delegate_components!` with no check** for an **aggregate provider** — the [`new`-keyword form](#defining-the-target-at-the-same-time). That target is a provider other contexts - delegate to rather than a context in its own right, so the fused macro's check would fail spuriously - on it. + delegate to rather than a context in its own right, so a context-side check on it asks the wrong + question: it either passes vacuously or blames the bundle for requirements a real context would have + met. Verify it through a context that delegates to it instead. The one thing not to do is leave a context's wiring unchecked. Which macro you use to check it scales with how complicated the wiring is; that it is checked somehow does not. diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index c4792110..bc20425c 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -6,12 +6,241 @@ sidebar_label: 'Path!' A type-level path, used by namespaces and redirected lookups. -:::info +## What it's for -### Not written yet +`Path!(@a.B.c)` builds a type-level **route** — a list of segments naming a way through nested wiring tables. +Read left to right, each segment narrows a lookup one step: through a namespace, through a prefix, down to a +component key. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +CGP needs such routes because [namespaces](./cgp_namespace.md) resolve lookups by path rather than by bare +component name, which is what lets a whole subtree be rerouted at once and a single inherited entry be shadowed +without disturbing the rest. Written as the underlying spine those routes are unreadable — +`PathCons<…, PathCons<…, Nil>>` nested several deep — so `Path!` lets one be written the way it reads: + +```rust +Path!(@app.error.ErrorRaiserComponent) +``` + +It is the path-shaped sibling of CGP's other type-level construction macros. Where +[`Symbol!`](./symbol.md) turns a literal into a type-level string and [`Product!`](./product.md) and +[`Sum!`](./sum.md) build record and variant lists, `Path!` builds the routing list, sharing their right-nested, +`Nil`-terminated shape. + +**You will more often write the syntax than the macro.** The same `@`-path form is embedded directly in +[`cgp_namespace!`](./cgp_namespace.md) entries, in `#[prefix(...)]` attributes, and in the `@`-path keys of +[`delegate_components!`](./delegate_components.md) — and that is where paths are normally written. The bare +macro is for the occasional case where a route needs naming as a type on its own. + +## Using it + +`Path!` takes a single `@`-prefixed path of one or more dot-separated segments. The leading `@` is required — it +is the sigil marking the body as a path rather than a plain type — and at least one segment must follow: + +```rust +Path!(@app) +Path!(@app.error) +Path!(@app.error.ErrorRaiserComponent) +``` + +### How a segment is encoded + +Each segment is parsed as a type, and **its first character decides how it is treated**. This is the one rule +worth learning, because it is what lets a path mix names and types without any extra syntax: + +| The segment | Becomes | +|---|---| +| A single lowercase identifier — `app`, `error` | a [`Symbol`](./symbol.md) type-level string | +| A capitalized name — `ErrorRaiserComponent` | that named type | +| A primitive type name — `u32`, `bool`, `str` | that type, *not* a symbol | + +So lowercase segments read as namespace and prefix names, capitalized ones as component keys or marker types, +and the primitive exception keeps `@u32` meaning the type `u32` rather than the string `"u32"`. Mixing is +normal: `@my_app.ShowImplComponent` interleaves a symbol and a component. + +This is the same convention [namespaces](./cgp_namespace.md) describe for their `@`-paths, because it is +literally the same parser. + +## Examples + +Used directly, `Path!` names a route that a [`RedirectLookup`](../providers/redirect_lookup.md) resolves against +a table: + +```rust +use cgp::prelude::*; + +type ErrorRoute = Path!(@app.error.ErrorRaiserComponent); +// ErrorRoute = PathCons>> +``` + +In practice the same syntax appears embedded rather than through the bare macro. A namespace entry redirects a +component along a path: + +```rust +cgp_namespace! { + new MyNamespace { + FooProviderComponent => + @MyFooComponent, + } +} +``` + +and a `#[prefix(...)]` attribute registers a component under one: + +```rust +#[cgp_component(ShowImpl)] +#[prefix(@show in AppNamespace)] +pub trait CanShow { + fn show(&self) -> String; +} +``` + +and a wiring table keys an entry on one: + +```rust +delegate_components! { + MyApp { + namespace AppNamespace; + + @show.ShowImplComponent: ShowWithDebug, + } +} +``` + +All four build the same kind of list. The macro and the embedded syntax are two places to write it, not two +different things. + +## When to reach for it, and when not + +**Write the `@`-path syntax wherever a namespace or a wiring key asks for a route**, and reach for the bare +`Path!` macro only when a route needs to be a named type on its own — which is rare. + +- **Prefer the embedded form.** A namespace entry, a `#[prefix]`, or an `@`-path wiring key is where a route + belongs, and each accepts the syntax directly. Naming a `type SomeRoute = Path!(…)` and using it indirectly + usually makes the wiring harder to follow rather than easier. +- **Never hand-write the spine.** `PathCons>` is what the macro expands to, + and writing it out is longer and identical in meaning. +- **Reach for the [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement) + rather than constructing paths yourself** when the goal is per-type dispatch on one component. `open` builds + the route for you, and its `@Component.Key` entries are the paths — you write the keys, not the routing. +- **Do not use `Path!` as a general type-level list.** [`Product!`](./product.md) is the list for a sequence of + types; `Path!` differs in its segment-classification rule, which exists to serve routing and would be + surprising anywhere else. + +## Under the hood + +:::note + +### Advanced + +This section shows the spine the macro builds. You do not need it to use `Path!`, but a namespace failure prints +the expanded path, so recognizing the shape is what lets you read which route came up empty. +`cargo cgp expand` resugars it back for your own code. ::: + +`Path!` expands to a right-nested chain of `PathCons` terminated by `Nil`, with each segment encoded by the +lowercase-versus-capitalized rule: + +```rust +// before +Path!(@app.error.ErrorRaiserComponent) + +// after — readable form +PathCons< + Symbol!("app"), + PathCons< + Symbol!("error"), + PathCons, + >, +> +``` + +The macro parses the segments after the `@` into a list and folds them right to left onto `Nil`, wrapping each in +a `PathCons` whose tail is the accumulated rest. A single-segment path is therefore `PathCons`. + +**A lowercase segment nests a second spine inside the first**, which is why a fully-expanded path is longer than +it looks: the `Symbol` is itself a `Chars`/`Nil` chain, so `@app` desugars all the way down to + +```rust +PathCons>>>, Nil> +``` + +That is what a raw compiler error prints, and it is the main reason this section is worth reading once. The +segment-classification rule is visible in the result: `@MyComp` gives `PathCons` with no `Symbol` +in it, and `@u32` gives `PathCons` rather than treating the primitive as a name. + +The same fold drives the embedded forms. A [`cgp_namespace!`](./cgp_namespace.md) redirect +`FooProviderComponent => @MyFooComponent` produces a +`RedirectLookup<__Table__, PathCons>`, and `#[prefix(@show in AppNamespace)]` on a +`CanShow` component produces a `PathCons>` — the prefix +followed by the component's own key. + +One presentational note: `cargo cgp expand` resugars a path back to `Path!(@…)` form in most positions, but not +uniformly — an `open` statement's per-entry key comes back as a raw `PathCons` spine while its header's redirect +target is resugared. Seeing the same kind of type in two spellings in one expansion is expected rather than a +sign that they differ. + +
+Formal grammar + +The input is a leading `@` followed by one or more dot-separated segments, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +PathInput -> `@` PathSegment ( `.` PathSegment )* + +PathSegment -> Type +``` + +The leading `` `@` `` is required and at least one segment must follow. Each `PathSegment` is parsed as a Rust +`Type`, but its encoding is decided semantically: a single lowercase identifier that is not a primitive type name +becomes a `Symbol` type-level string, while every other segment — a capitalized name or a primitive — is kept as +the named type. This same grammar is what [`cgp_namespace!`](./cgp_namespace.md) entries and `#[prefix(...)]` +attributes embed, where it appears as the `Path` production. + +
+ +## Gotchas + +**The leading `@` is not optional**, and the macro says exactly what it wanted: + +```text +error: expected `@` +``` + +**Case decides meaning, silently.** `@app` and `@App` are entirely different segments — a type-level string +versus a named type — and both are valid, so a capitalization slip produces a path that compiles and routes +somewhere else. The failure surfaces later as a lookup that resolves to nothing, with no hint that the cause was +a capital letter. + +**A lowercase primitive is the type, not a string.** `@u32`, `@bool`, and `@str` name those types. That is +almost always what you want, and it means a path segment cannot be the *string* `"u32"` through this syntax. + +**A path that routes nowhere still compiles.** A route is just a type; nothing checks that anything is bound at +its end. An unbound route is reported only when a [`check_components!`](./check_components.md) evaluates the +lookup, as an unsatisfied bound naming the expanded path — which is why namespace mistakes tend to surface at +the check rather than at the definition. + +## Related constructs + +- [`cgp_namespace!`](./cgp_namespace.md) — where paths are mostly written, in entries and `#[prefix]` + attributes. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the provider that resolves a path against a table. +- [`delegate_components!`](./delegate_components.md) — `@`-path keys and the `open` statement that builds routes + for you. +- [`Symbol!`](./symbol.md) — what a lowercase segment becomes. +- [Type-level spines](../types/type_level_spines.md) — the `PathCons` chain the expansion builds. +- [`Product!`](./product.md) and [`Sum!`](./sum.md) — the sibling construction macros, sharing the fold shape. +- [`DelegateComponent`](../traits/delegate_component.md) — the per-key table a resolved path finally reads. + +## Source + +- Entry point: [`path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/path.rs) +- Parsing and the fold: [`types/path/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/path/) +- Runtime `PathCons`: [`types/path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/path.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 54aa6c74..bee8f56a 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -6,12 +6,221 @@ sidebar_label: 'Product! & product!' A type-level list and its value-level counterpart. -:::info +## What it's for -### Not written yet +`Product![A, B, C]` represents an ordered sequence of types as a single type. CGP uses it to describe the +*shape* of a struct — the list of its fields, in order, as one type that generic code can reason about. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +It is sometimes called an anonymous product type, because like a tuple it holds several things at once. The +difference from a tuple is the one that matters: a `Product!` is built from a recursive spine that generic code +can take apart **one element at a time**: + +```rust +Product![u32, String, bool] +``` + +That recursion is what makes structural, field-by-field operations possible at all. Because a struct's fields +are exposed as a single list type through [`HasFields`](../traits/has_fields.md), a provider can be written +once to walk, transform, or rebuild *any* struct's fields without naming the concrete struct — by recursing +over the list. A plain tuple cannot be decomposed that way in generic code; the recursive list can. + +The lowercase `product![a, b, c]` is the value-level half. `Product!` produces a *type* and is used in type +position — associated types, bounds, aliases — while `product!` produces a *value* of the matching type and is +used in expression position, mirroring Rust's own split between a struct type and a struct literal. + +**You mostly read these rather than write them.** A struct's field list is generated by +[`#[derive(HasFields)]`](../derives/derive_has_fields.md); where you write `Product!` by hand is in a handler +pipeline, listing the steps to run in order. + +## Using it + +Both macros take a comma-separated list, which may be empty, and a trailing comma is allowed: + +```rust +Product![u32, String, bool] // a type +product![1u32, "hi".to_string(), true] // a value of that type +Product![] // the empty list type +``` + +The element lists line up positionally, so the value `product!` builds has exactly the type `Product!` builds +over the corresponding element types. + +`Product!` is used wherever a type is expected and `product!` wherever a value is expected. Nothing else about +them varies — there are no options and no attributes. + +## Examples + +The commonest appearance by far is the field list a struct derives, where each element pairs a field name with +its type: + +```rust +use cgp::prelude::*; + +#[derive(HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} + +// generated: +// impl HasFields for Person { +// type Fields = Product![ +// Field, +// Field, +// ]; +// } +``` + +The names are [`Symbol!`](./symbol.md) type-level strings and each entry is a [`Field`](../types/field.md), so +the whole `Product!` is a complete type-level description of `Person`'s layout. Generic code walks that list to +build or read a `Person` without being written against `Person`. + +Where you write `Product!` yourself is a handler pipeline, where the list *is* the program — the steps run +left to right: + +```rust +delegate_components! { + MyContext { + ComputerComponent: + PipeHandlers, + Add, + Multiply, + ]>, + } +} +``` + +A standalone list and a matching value can also be written directly, which is mostly useful for illustration: + +```rust +type Row = Product![u32, String, bool]; +let row: Row = product![1, "hi".to_string(), true]; +``` + +## When to reach for it, and when not + +**Write `Product!` when a construct asks for a type-level list**, which in practice means a handler pipeline or +a provider list. Everywhere else it is generated for you. + +- **Never hand-write the spine.** `Cons>` is what `Product!` expands to, and writing it out is + strictly worse — longer, harder to change, and identical in meaning. The same holds for + [`Sum!`](./sum.md)'s spine. +- **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for a struct's shape** rather than declaring + the list yourself. Writing it by hand means restating the struct, and the two will disagree eventually. +- **Use a tuple when nothing generic consumes it.** A `Product!` earns its keep only where code recurses over + the list; for a fixed group of values passed between known functions, a tuple or a struct is clearer and + needs no machinery. +- **Use [`Sum!`](./sum.md) for a choice rather than a collection.** `Product!` holds a value for *every* + element; `Sum!` holds one for exactly *one*. They are duals, and mixing them up produces a type error rather + than a subtle bug. + +## Under the hood + +:::note + +### Advanced + +This section shows the spine both macros build. You do not need it to use them, but the expanded form is what a +compiler error prints, so recognizing it is what makes those errors readable. `cargo cgp expand` resugars it +back for your own code. ::: + +`Product!` expands to a right-nested chain of `Cons`, terminated by `Nil`: + +```rust +// before +Product![A, B, C] + +// after +Cons>> +``` + +Both building blocks are ordinary types. `Cons` is a tuple struct holding the first element and the +rest of the list — `Cons(pub Head, pub Tail)` — and `Nil` is a unit struct terminating it. Chaining +through the tail gives a list of any length, and the empty `Product![]` is simply `Nil`. The macro builds the +chain by folding the elements right to left onto `Nil`. + +`product!` folds identically but produces a value, using `Cons`'s tuple-struct constructor: + +```rust +// before +product![a, b, c] + +// after +Cons(a, Cons(b, Cons(c, Nil))) +``` + +Because `Cons` is a real struct and `Nil` a real unit struct, the result is an ordinary owned value whose type +is exactly what `Product!` builds over the same elements' types. There is no magic layer between the two +macros — they are the same fold at two levels. + +**What this means for reading errors**: a mismatched field list is reported as a mismatch between two `Cons` +chains, and the position where they diverge is the field that differs. An error mentioning +`Cons>` where you expected three fields is telling you the third entry is missing. + +
+Formal grammar + +Both macros take a possibly-empty comma-separated list, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +ProductInput -> ( Type ( `,` Type )* `,`? )? + +ProductExpr -> ( Expression ( `,` Expression )* `,`? )? +``` + +`ProductInput` is the grammar of the type macro `Product!`, used in type position; `ProductExpr` is the +grammar of the value macro `product!`, used in expression position. `Type` and `Expression` are the Rust +grammar's productions. Both lists may be empty — `Product![]`, `product![]` — or carry a trailing comma, and +they line up positionally so a `product!` value has the type the corresponding `Product!` builds. + +
+ +## Gotchas + +**`Product!` and `product!` differ only in case, and the compiler's complaint will not say so.** Using the +type macro in expression position fails inside the macro's own parser, which is expecting a type — so the +message is a list of type-position tokens with no hint that the lowercase macro was wanted: + +```text +error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, + square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime +``` + +**A one-element list is not a wrapper.** `Product![T]` is `Cons`, which is a distinct type from `T` — +so a pipeline of one step still needs the list, and unwrapping it is a type error rather than a no-op. + +**The empty list is `Nil`, a real value.** That is the difference from [`Sum!`](./sum.md), whose empty form is +the uninhabited `Void`. An empty record exists; an empty choice cannot. + +**Element order is part of the type.** `Product![A, B]` and `Product![B, A]` are unrelated types. For a field +list this matters less than it sounds, because the entries are name-tagged +[`Field`](../types/field.md)s and the operations that consume them match on names — but for a handler pipeline +the order *is* the execution order. + +## Related constructs + +- [`Sum!`](./sum.md) — the dual, for a choice among types rather than a collection of them. +- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` types the expansion builds. +- [`Field`](../types/field.md) — what the entries usually are, pairing a name with a type. +- [`Symbol!`](./symbol.md) — the name half of a `Field` entry. +- [`HasFields`](../traits/has_fields.md) — the trait that exposes a struct's shape as one of these lists. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates that list for you. +- [`AppendProduct`](../traits/product_ops.md) — the operations that combine and transform these lists. +- [Handler combinators](../providers/handler_combinators.md) — where `Product!` is written by hand, as a + pipeline. + +## Source + +- Entry points: [`product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/product.rs) +- The type form's fold: [`types/product/product_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/product/product_type.rs) +- The value form's fold: [`types/product/product_expr.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/product/product_expr.rs) +- Runtime types: [`types/cons.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/cons.rs) + and [`types/nil.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/nil.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 17927a3f..309c0a84 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -6,12 +6,194 @@ sidebar_label: 'Sum!' A type-level sum, the dual of `Product!`. -:::info +## What it's for -### Not written yet +`Sum![A, B, C]` represents a *choice* among several types as a single type. CGP uses it to describe the shape +of an **enum** — the list of its variants — the way [`Product!`](./product.md) describes the fields of a +struct. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +The pairing is exact and worth holding onto. A `Product!` holds a value for **every** element at once, which is +a record. A `Sum!` holds a value for exactly **one** element, which is a tagged union: + +```rust +Sum![u32, String, bool] +``` + +Like its dual it is built from a recursive spine, and that recursion is what makes variant-by-variant +operations possible. Because an enum's variants are exposed as a single sum type through +[`HasFields`](../traits/has_fields.md), a provider can be written once to match on, dispatch over, or construct +*any* enum's variants without naming the concrete enum — by walking the nested branches. This is the basis for +CGP's extensible-variant machinery, where each variant is handled by descending the chain rather than by +writing a `match` against a fixed enum. + +**You essentially never write `Sum!` by hand.** An enum's variant list is generated by +[`#[derive(HasFields)]`](../derives/derive_has_fields.md) or the extensible-data derives; the value of knowing +the construct is being able to read it in an expansion or an error. + +## Using it + +The macro takes a comma-separated list of types, which may be empty, and a trailing comma is allowed. It is +used wherever a type is expected: + +```rust +Sum![u32, String, bool] +Sum![] // the empty sum +``` + +Each listed type is one possible variant, and a value of the sum type carries exactly one of them. There are no +options and no value-level counterpart — unlike [`Product!`](./product.md), which has `product!`, a sum value is +constructed through the variant machinery rather than by a literal. + +## Examples + +The primary appearance is the variant list an enum derives, where each branch pairs a variant name with its +payload: + +```rust +use cgp::prelude::*; + +#[derive(HasFields)] +pub enum Shape { + Circle(f64), + Rectangle { width: f64, height: f64 }, +} + +// generated (schematically): +// impl HasFields for Shape { +// type Fields = Sum![ +// Field, +// Field, +// Field, +// ]>, +// ]; +// } +``` + +Two things to notice. The variant names are [`Symbol!`](./symbol.md) type-level strings, exactly as field names +are. And a struct-like variant nests a [`Product!`](./product.md) of its own fields — so an enum's full shape is +a sum of variants whose payloads may themselves be records. Generic code walks the `Sum!` to find which variant +a value holds, then walks the nested `Product!` to reach that variant's fields. + +A standalone sum can be written directly, which is mostly useful for illustration: + +```rust +type Token = Sum![u32, String, bool]; +``` + +## When to reach for it, and when not + +**Let the derives write it.** That is the honest recommendation for this construct: unlike +[`Product!`](./product.md), which you write by hand for handler pipelines, `Sum!` has no everyday hand-written +use. + +- **Use [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or + [`#[derive(HasFields)]`](../derives/derive_has_fields.md) on the enum**, which generates the list from the + variants you already declared. Writing it out means restating the enum, and the two will drift. +- **Never hand-write the spine.** `Either>` is what `Sum!` expands to, and writing it out is + longer and identical in meaning. +- **Use [`Product!`](./product.md) for a collection rather than a choice.** They are duals: every element + versus exactly one. A type error is the usual consequence of confusing them, which is at least loud. +- **Use a plain `enum` and `match` when the variant set is closed and known.** The machinery earns its keep + when independent code has to handle variants it did not define, or when the variant set is open. For a fixed + enum consumed in one place, a `match` is clearer and free. + +## Under the hood + +:::note + +### Advanced + +This section shows the spine the macro builds, and why its terminator differs from `Product!`'s. You do not need +it to use `Sum!`, but the difference explains the exhaustiveness guarantee that the extensible-variant +machinery rests on. `cargo cgp expand` resugars it back for your own code. ::: + +`Sum!` expands to a right-nested chain of `Either`, terminated by `Void`: + +```rust +// before +Sum![A, B, C] + +// after +Either>> +``` + +The two building blocks differ from the product spine in being *branching* rather than pairing. +`Either` is an enum with two cases: `Left(Head)` selects the head type, and `Right(Tail)` defers to +the rest of the chain. So a value of `Either>>` is `Left` for an `A`, +`Right(Left(..))` for a `B`, and `Right(Right(Left(..)))` for a `C`. + +The terminator is `Void`, an **empty enum that can never be constructed**, and choosing it rather than `Nil` is +the load-bearing decision here. Reaching the `Void` position would mean the value matched none of the listed +types, which is impossible — so the type system knows the chain is exhausted. An empty `Sum![]` is therefore +just `Void`: a type with no values. + +That is precisely the asymmetry with [`Product!`](./product.md). A product terminates in `Nil` because an empty +record is a perfectly good value; a sum terminates in `Void` because an empty choice is *uninhabited*, there +being nothing to pick. `Void` functions as the never type, used here to close a sum off. + +**Why it matters beyond tidiness**: this is what gives generic variant handling compile-time exhaustiveness +without a wildcard arm. As each variant is ruled out, the remaining type shrinks toward `Void`, and code that +has handled every variant is left holding a value that cannot exist — which the compiler accepts discharging +with no fallback case. Add a variant to the enum without handling it, and the remainder becomes inhabited +again, so the code stops compiling. The same guarantee a concrete `match` gives, recovered for generic code. + +The macro builds the chain by folding the element types right to left onto `Void`. + +
+Formal grammar + +The input is a possibly-empty comma-separated list of types, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +SumInput -> ( Type ( `,` Type )* `,`? )? +``` + +`Type` is the Rust grammar's type production, and the list may be empty (`Sum![]`) or carry a trailing comma. +The macro is used in type position, and each listed type is one possible variant of the sum. + +
+ +## Gotchas + +**The empty sum is uninhabited, not empty-but-usable.** `Sum![]` is `Void`, so a function claiming to return one +can never return at all. That is deliberate and occasionally useful, but it is not the analogue of an empty +collection. + +**A one-element sum is still a wrapper.** `Sum![T]` is `Either`, a distinct type from `T`, so it needs +constructing and destructuring like any other. + +**Variant order is part of the type.** `Sum![A, B]` and `Sum![B, A]` are unrelated. In practice the entries are +name-tagged [`Field`](../types/field.md)s and the operations match on names, so this bites less than it might — +but the *types* are still different, and a cast between two enums works through the name matching rather than +by position. + +**A derivable enum's variants must each hold exactly one unnamed field.** That is a restriction of the +extensible-data derives rather than of `Sum!` itself, and it is why richer payloads are wrapped in a dedicated +struct: the variant's payload type has to be a single nameable type for the sum entry to carry it. + +## Related constructs + +- [`Product!`](./product.md) — the dual, for a collection rather than a choice. +- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` types the expansion builds. +- [`Field`](../types/field.md) — what the branches usually are, pairing a variant name with its payload. +- [`Symbol!`](./symbol.md) — the name half of a branch. +- [`HasFields`](../traits/has_fields.md) — the trait exposing an enum's shape as one of these sums. +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — the derive that generates it, with the variant + machinery. +- [`FromVariant`](../traits/from_variant.md) and [`ExtractField`](../traits/extract_field.md) — constructing and + taking apart a variant generically. +- [`CanUpcast`](../traits/cast.md) — converting between two enums that share variants. + +## Source + +- Entry point: [`sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/sum.rs) +- The fold onto `Void`: [`types/sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/sum.rs) +- Runtime `Either` and `Void`: [`cgp-field/src/types/sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/sum.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 91bff976..33229a98 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -6,12 +6,238 @@ sidebar_label: 'Symbol!' A type-level string, used as a field-name tag. -:::info +## What it's for -### Not written yet +CGP needs field *names* to be types. Reading a field goes through +[`HasField`](../traits/has_field.md), where `Tag` identifies which field is meant — so to look up a field +called `name`, something has to stand in for the string `"name"` at the type level. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`Symbol!("name")` is that something. It produces a distinct type whose whole identity is the characters it +encodes: two invocations with the same string are the same type, and two with different strings are different +types. + +```rust +HasField +``` + +Encoding a string as a type is what lets field access take part in trait resolution. A **context** — the type +the capability runs against, which supplies the values it needs as its fields — can carry a +`HasField` impl and a `HasField` impl side by side, and the compiler +picks the right one from the tag alone. Nothing is compared at runtime, because there is nothing at runtime: +the tag exists only during compilation. + +**You rarely write it by hand.** [`#[implicit]`](../attributes/implicit.md) arguments, +[`#[cgp_auto_getter]`](./cgp_auto_getter.md), and [`#[derive(HasField)]`](../derives/derive_has_field.md) all +generate the tag from a name you already wrote. Where `Symbol!` shows up explicitly is in a wiring entry that +names a field — `UseField` — and where it shows up unavoidably is in compiler errors, +which is the main reason to be able to read it. + +## Using it + +The macro takes a single string literal and is used wherever a type is expected — in trait bounds, in +associated-type positions, and inside a `PhantomData` tag: + +```rust +Symbol!("name") +Symbol!("first_name") +Symbol!("") +``` + +Any valid string literal is accepted, including the empty string and multi-byte Unicode +(`Symbol!("世界")`). Most often it appears inside a field bound: + +```rust +Self: HasField +``` + +### The tag for a tuple field + +A tuple-struct field has no name, so it cannot be keyed by a string. +[`#[derive(HasField)]`](../derives/derive_has_field.md) tags those with [`Index`](../types/index.md) instead — +`Index<0>`, `Index<1>` — which encodes a number at the type level the way `Symbol!` encodes a string. A field +is keyed by `Symbol!` when it has a name and by `Index` when it has only a position. + +### Raw identifiers + +A field written as a raw identifier is tagged by its *logical* name, with the `r#` stripped: a field `r#type` +is tagged `Symbol!("type")`. The macro itself performs no stripping — it takes the literal verbatim — so +`Symbol!("type")` is the tag that matches, and `Symbol!("r#type")` would be a different tag matching nothing. + +## Examples + +The everyday appearance is a wiring entry that points a getter at a particular field: + +```rust +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} + +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} +``` + +`Symbol!("first_name")` is what tells [`UseField`](../providers/use_field.md) which field to read. This is the +one place a reader routinely writes the macro themselves. + +It also appears in a hand-written field bound, which is what the ergonomic constructs generate for you: + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData::)); + } +} +``` + +Written idiomatically that provider would use an [`#[implicit]`](../attributes/implicit.md) argument and no +`Symbol!` would be visible at all — which is the point of the ergonomic surface, and why this form is worth +recognizing rather than writing. + +A type-level string can also be turned back into a runtime string, which is occasionally useful for +diagnostics: + +```rust +let s = ::default(); +assert_eq!(s.to_string(), "hello"); +``` + +## When to reach for it, and when not + +**Write `Symbol!` when a wiring entry has to name a field**, and let the macros produce it everywhere else. +That is the honest summary: the construct is load-bearing and mostly generated. + +- **Use an [`#[implicit]`](../attributes/implicit.md) argument to read a field.** The parameter's name becomes + the tag, so you never type one. +- **Use [`#[cgp_auto_getter]`](./cgp_auto_getter.md) for a named accessor.** The method name becomes the tag. +- **Write `Symbol!` explicitly with [`UseField`](../providers/use_field.md)**, where the whole point is that + the field name is a wiring decision rather than fixed to a method name. This is its main hand-written use. +- **Use [`Index`](../types/index.md) for a tuple field**, not a `Symbol!` of `"0"`. They are different types + and the derive generates the former. + +Two things it is not. It is **not a runtime string** — there is no `&str` inside it, and the `Display` impl +above reconstructs the text from the type rather than reading a stored value. And it is **not a general +type-level string facility** to build programs out of; it exists to key field and variant lookups, and the +[`StaticFormat`](../traits/static_format.md) traits are what recover text from one when that is genuinely +needed. + +## Under the hood + +:::note + +### Advanced + +This section shows what the macro expands to. You do not need it to use `Symbol!`, but the expanded form is +exactly what a compiler error prints, so reading it once turns an intimidating error into a legible one. +`cargo cgp expand` resugars it back for your own code. ::: + +`Symbol!("...")` expands to a `Symbol` type wrapping a `Chars` chain that spells the string one character at a +time: + +```rust +// before +Symbol!("abc") + +// after +Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>> +``` + +Two type constructors do the work. `Chars` is one character paired with the rest of +the string; chained through its tail and terminated by `Nil`, it forms a +[type-level list](../types/type_level_spines.md) of characters — the same shape as +[`Product!`](./product.md)'s `Cons`/`Nil` spine, specialized so the head is a `const char` rather than a type. +`Symbol` then wraps that list together with a length. + +**The `LEN` parameter is the part most likely to surprise**, and it exists to work around a limit in stable +Rust: the length of a `Chars` chain cannot be computed inside a const-generic context, so the macro +precomputes it and bakes it in. The value is the string's **byte** length, not its character count: + +```rust +Symbol!("abc") // Symbol<3, Chars<'a', ...>> — 3 bytes, 3 chars +Symbol!("世界你好") // Symbol<12, Chars<'世', ...>> — 12 bytes, 4 chars +``` + +The character list has one `Chars` node per Unicode scalar value, so those two numbers disagree for any +non-ASCII string. `LEN` is there so length-dependent code can read the size off the type instead of recursing +through the list. + +The expansion is built by folding the characters right to left onto `Nil` and wrapping the result, so the empty +string `Symbol!("")` becomes `Symbol<0, Nil>`. + +**What this means for reading errors** is the practical payoff. A missing field on a context is reported +against the expanded tag, so an error mentioning +`HasField>>>` is telling you the field `width` is missing. Counting the +characters is enough to decode it, and `cargo cgp check` resugars the common cases. + +
+Formal grammar + +The input is a single string literal, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +SymbolInput -> STRING_LITERAL +``` + +`STRING_LITERAL` is the Rust string-literal token, so any valid string literal is accepted — including the +empty string and multi-byte Unicode. The macro is used in type position, and this single literal is the whole +of its input. + +
+ +## Gotchas + +**The `LEN` in an expanded `Symbol` is bytes, not characters.** For ASCII the two coincide, which is why the +distinction only shows up on non-ASCII field names — where the number will not match the visible character +count and the `Chars` chain will be shorter than `LEN`. + +**A raw-identifier field is tagged without the `r#`.** `Symbol!("r#type")` and `Symbol!("type")` are different +types, and the derive generates the second, so the first matches nothing. + +**Two spellings of the same field are different tags.** `Symbol!("first_name")` and `Symbol!("firstName")` are +unrelated types, and a mismatch reports as a missing `HasField` bound rather than as a typo. This is the usual +cause of a getter that "should" work. + +**It is a type, so it goes in type position.** Writing `Symbol!("name")` where a value is expected does not +work; the `PhantomData::` form is how the tag is passed to `get_field`, and the tag is the +type argument rather than the value. + +## Related constructs + +- [`Index`](../types/index.md) — the position-keyed tag for tuple-struct fields. +- [`HasField`](../traits/has_field.md) — what a tag is looked up through. +- [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates one tag per named field. +- [`#[implicit]`](../attributes/implicit.md) — generates the tag from an argument name. +- [`#[cgp_auto_getter]`](./cgp_auto_getter.md) — generates it from a method name. +- [`UseField`](../providers/use_field.md) — where the tag is written by hand, as a wiring decision. +- [Type-level spines](../types/type_level_spines.md) — the `Chars`/`Nil` chain the expansion builds. +- [`Product!`](./product.md) and [`Sum!`](./sum.md) — the record and variant lists whose entries carry these + tags. +- [`StaticFormat`](../traits/static_format.md) — recovering runtime text from a type-level string. + +## Source + +- Entry point: [`symbol.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/symbol.rs) +- The character fold and `LEN` computation: [`types/field/symbol.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/field/symbol.rs) +- Runtime types: [`types/symbol.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/symbol.rs) + and [`types/chars.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/chars.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* From e961c94461a5b32ed90103d0d898cb7ddb70dd7f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 13:47:01 +0200 Subject: [PATCH 017/516] Write Bypassing coherence and How much CGP to use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two of the four pages the homepage offloads to, taking the Concepts tier to three written. Between them they now cover every route the section's index advertises as a starting point — why CGP exists, how it works, and whether to adopt it — so that index no longer sends a reader to a placeholder, which was the tier's most visible defect. They were chosen as a pair for that reason. E2 picks itself as the highest-value page unwritten and the homepage's most frequent destination; E4 over E3 because E2 with E3 would have left the evaluator's route still pointing at a stub. They are also opposite in kind, so writing both exercised both of the shapes the guide specifies. *Bypassing coherence* follows the guide's five movements — the trait system as dependency injection, why transitive resolution needs a globally unique answer, what that guarantee costs, the marker-struct workaround developers arrive at on their own, then `Self` becoming a type the implementing crate owns — plus the sixth movement that builds the application-context shape out of plain Rust, and both transitions the guide says must not be left silent. It states plainly that both coherence rules are correct before working around either, and earns the sentence it exists for: coherence is not repealed, it is scoped. The strongest framing in it is the guide's own — coherence does not forbid the application-context shape, it makes it not worth building, so CGP's contribution is constructive rather than permissive. *How much CGP to use* is a decision guide rather than an essay: a rule of thumb, an eight-row alternatives table where every row concedes where the other tool wins, four cases where CGP is simply the wrong tool, and the two questions readers actually arrive with, answered without predicting they will want a second context later. The three shapes are posed as two questions rather than a taxonomy, and the agent-support note sits beside the costs, framed as making three of them smaller rather than absent and explicitly moving no boundary. A review pass then found a gap in that page's own remit: titled *How much CGP to use*, it answered only *whether* — plain trait versus CGP, and which shape — and never how far to climb inside CGP, which its summary line and the index both promise. It now carries a five-step progression from `#[cgp_fn]` to reusable wiring, each step framed as a response to a problem already hit, with higher-order providers and namespaces named as the two most often reached for early. That was a real hole in the site's guidance, since the reference's twenty-seven *When to reach for it* sections each argue this locally and nothing central said where the ceiling is. Two smaller review fixes. *Bypassing coherence* offered only a link to the `check-traits` stub for its laziness cost, so a reader following the one route out of that paragraph met a placeholder; it now leads with `check_components!` and `cargo cgp check`, both live, and keeps the concept link as the fuller account. And two claims were inflated beyond what can be supported — that the hand-rolled workaround is reinvented by people who have never heard of CGP, and that climbing too high is the *commonest* way a codebase gets worse. Both are now the smaller, supportable claim. Every snippet compiles against cgp 0.8.0-alpha with a `check_components!` assertion per wired context, and all four quoted errors — the `E0119` from two overlapping blanket impls, the `E0117` from a wholly foreign impl, the `E0119` from factoring an application's impls into a blanket one — are what the compiler reports. The two contexts in the coherence example first produced identical output, since `to_string` and `as_ref` agree on a `String`, which made the whole point invisible; the second provider now hex-encodes, so they visibly differ. The site builds, no page links into the knowledge base, and both pages are on the author's read-before-publication list. Co-Authored-By: Claude Opus 5 (1M context) --- docs/concepts/coherence.md | 315 +++++++++++++++++++++++++- docs/concepts/modularity-hierarchy.md | 207 ++++++++++++++++- 2 files changed, 506 insertions(+), 16 deletions(-) diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 499f75d8..a76f78d3 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -5,15 +5,314 @@ sidebar_position: 1 # Bypassing coherence -Rust allows one implementation of a trait per type. Why that rule exists, what it costs, and how -CGP writes many implementations and lets each context pick the one it wants. +Rust allows one implementation of a trait per type. Why that rule exists, what it costs, and how CGP +writes many implementations and lets each context pick the one it wants. -:::info +This page answers *why can't Rust do this already?* It builds up what the trait system gives you, shows +what that costs when you want two implementations of one thing, and ends on the move CGP makes — which is +smaller than it first appears, and does not throw the rule away. It is the longest page in this section, +and everything else here is downstream of it. -### Not written yet +## The trait system is already a dependency-injection mechanism -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +Start with what Rust does well, because the rule that gets in the way later is the same rule that makes +this work. -::: +When you write a generic function with a bound, you are asking the compiler to find an implementation for +you: + +```rust +pub fn describe(value: &T) -> String { + format!("{value}") +} +``` + +Nobody passes `Display` in. The caller writes `describe(&42)` and the compiler goes looking for +`impl Display for i32`, finds it, and wires it up. That is dependency injection, done by the type system +at compile time, and it is so ordinary in Rust that it rarely gets called that. + +The part worth noticing is that it works **transitively**. If `describe` calls something that itself +needs a bound, and that needs another, the compiler resolves the whole chain without a single caller +naming any of it. You can add a requirement four layers deep and callers four layers up are unaffected. +That property is what makes Rust's generics composable rather than a bookkeeping exercise. + +## That only works because every lookup finds the same answer + +Transitive resolution depends on something easy to overlook: when the compiler looks up `Display for i32`, +it must get the same answer no matter where it asks from. If one crate could see one implementation and +another crate a different one, the same generic function would mean different things depending on who +called it, and a program combining both would be incoherent — two halves compiled against +irreconcilable answers. + +**Coherence is the property that guarantees this**, and Rust enforces it with two rules. + +The **overlap rule** forbids two implementations that could both apply to the same type. Given a trait you +own and two blanket implementations, the compiler rejects the second: + +```rust +pub trait CanEncode { + fn encode(&self) -> Vec; +} + +// Legal on its own. +impl CanEncode for T { + fn encode(&self) -> Vec { self.to_string().into_bytes() } +} + +// error[E0119]: conflicting implementations of trait `CanEncode` +impl> CanEncode for T { + fn encode(&self) -> Vec { self.as_ref().to_vec() } +} +``` + +`String` satisfies both bounds, so the compiler would have no principled way to choose — and "pick +whichever is in scope" is exactly the incoherence the rule exists to prevent. + +The **orphan rule** forbids implementing a trait for a type unless your crate owns one of the two. +Neither `Display` nor `Vec` is yours, so this is rejected: + +```rust +// error[E0117]: only traits defined in the current crate can be implemented +// for types defined outside of the crate +impl Display for Vec { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { /* ... */ } +} +``` + +Without it, two unrelated crates could each add their own `Display for Vec`, and any program +depending on both would be unbuildable — with neither crate at fault. + +**Both rules are correct.** They are not conservatism or an unfinished corner of the language; they are +what you pay for transitive resolution, and the trade is a good one. Any account of CGP that opens by +calling coherence a limitation has the argument backwards. + +## What the guarantee costs + +The price is that some perfectly reasonable code is unwritable, and the two rules bite in different ways. + +The overlap rule costs you **alternative implementations**. In the encoding example above, the author knows +exactly which implementation they want for which type — the ambiguity is the compiler's, not theirs — and +there is no way to say so. The trait admits one blanket implementation, full stop. + +The orphan rule costs you **reach**. A crate that wants to add a capability to another crate's type has to +wrap it in a newtype and re-expose everything it still needs, which is boilerplate with no upside and a +type your callers now have to know about. + +These are felt sharply enough that Rust developers build their own escape. The pattern is to stop +implementing the trait for the interesting type and implement it for a marker type you own instead, with a +helper trait tying the two together — three or four extra lines of plumbing, arrived at independently and +written up by developers working around the overlap rule on their own. **If you have written that, you have +written CGP's central mechanism by hand**, and the rest of this page is about what it looks like made +first-class. + +## The move: make `Self` a type you own + +CGP's first move is to take the type coherence ranges over — the `Self` of the implementation — and make +it something the implementing crate always owns. + +One trait definition becomes two. The **consumer trait** keeps the original shape, so callers write +`app.encode(&value)` as before. The **provider trait** is the same interface with `Self` moved out into an +explicit parameter, and an implementation targets a small named type of its own: + +```rust +#[cgp_component(Encoder)] +pub trait CanEncodeValue { + fn encode(&self, value: &Value) -> Vec; +} + +#[cgp_impl(new EncodeWithDisplay)] +impl Encoder +where + Value: Display, +{ + fn encode(&self, value: &Value) -> Vec { value.to_string().into_bytes() } +} + +#[cgp_impl(new EncodeAsHex)] +impl Encoder +where + Value: AsRef<[u8]>, +{ + fn encode(&self, value: &Value) -> Vec { /* hex-encode the bytes */ } +} +``` + +**Both compile.** They are the same two bodies the compiler rejected a moment ago, with the same +overlapping bounds, and there is no conflict — because each one's `Self` is a different type +(`EncodeWithDisplay`, `EncodeAsHex`) that this crate declared for the purpose. Any number more would also +compile. The orphan rule does not enter either, since that `Self` is always local, which is how a crate +adds a capability to a type it did not define. + +Neither rule was repealed. The implementations simply stopped being the kind of thing the rules are +about. [Consumer and provider traits](./consumer-and-provider-traits.md) works through the mechanics of +the split and how a call finds its way across it. + +## Coherence comes back, one context at a time + +Making implementations incoherent would be useless if it also made *use* incoherent. A caller still needs +`app.encode(&value)` to mean one definite thing. + +So the second move reintroduces coherence at a smaller scale. Instead of one global choice per trait, each +**context** — a type you define to stand for one set of choices — names exactly one implementation, in a +small table: + +```rust +delegate_components! { + ApiServer { + open EncoderComponent; + @EncoderComponent.String: EncodeWithDisplay, + } +} + +delegate_components! { + Firmware { + open EncoderComponent; + @EncoderComponent.String: EncodeAsHex, + } +} +``` + +`ApiServer` encodes a `String` as its text and `Firmware` as hexadecimal: + +```text +ApiServer: hi +Firmware: 6869 +``` + +Within either context the choice is unambiguous, so resolution is coherent; between them it differs, with +no conflict, because the lookup is keyed on the context. The insight is that incoherence is only wanted +when *writing* implementations. When using them, what you want is many independent local scopes, each +internally consistent. + +**Coherence is not repealed — it is scoped.** That sentence is the whole page in eight words. + +## Where the freedom actually comes from + +Here is the part most easily misread, and it is worth slowing down for: **the escape happens when `Self` +becomes a type you own, not when a parameter appears.** + +A scope is one context type, so the number of independent choices a program can make is the number of +context types it can define. Wire a capability onto `Vec` — data, and not yours — and you get exactly +one answer for the whole program, because there is one `Vec`. Coherence was narrowed, not removed. +Wire it onto `ApiServer` and `Firmware`, types you declared, and you get as many answers as you care to +declare types. + +Which is why the two contexts above are `ApiServer` and `Firmware` rather than `Vec` wired twice. The +second is impossible; the first is the point. + +### The shape this depends on + +That leaves one thing to build, because it is a shape vanilla Rust gives you no reason to have imagined: +**a type whose whole job is to stand for an application.** + +Start from the fact that it is perfectly ordinary Rust. Two application types, one value type, two +encodings, no CGP anywhere: + +```rust +pub trait CanEncodeValue { + fn encode(&self, value: &Value) -> Vec; +} + +pub struct ApiServer; +pub struct Firmware; + +impl CanEncodeValue> for ApiServer { + fn encode(&self, v: &Vec) -> Vec { /* one encoding */ } +} + +impl CanEncodeValue> for Firmware { + fn encode(&self, v: &Vec) -> Vec { /* another */ } +} +``` + +This compiles, and it already does something useful — per-application encoding of the same type, with +nothing exotic involved. Note that both structs have **no fields at all**. `struct ApiServer;` is a +complete and legitimate type here, because its entire purpose is to be a name the implementations hang +off. An empty struct with traits on it is otherwise close to unreadable, which is why it is worth saying +outright. + +Now try to make it scale. Add a third value type, then a fourth, and you are hand-writing a body per +`(application, type)` pair. So you do the obvious thing and factor the shared logic into a blanket +implementation — and the overlap rule is waiting: + +```rust +impl CanEncodeValue for ApiServer { /* ... */ } + +// error[E0119]: conflicting implementations of trait `CanEncodeValue<_>` +// for type `ApiServer` +impl> CanEncodeValue for ApiServer { /* ... */ } +``` + +**So the shape is available and unrewarding.** It works, and nothing can be shared, so it dies at three +types and nobody carries it in their repertoire. That is why "application context" tends to land as an +unfamiliar noun rather than a familiar arrangement: readers have not built it, because until now there was +no reason to. + +This is the strongest form of the payoff, and it is worth stating precisely. **Coherence does not forbid +this shape — it makes it not worth building.** CGP's contribution is therefore constructive rather than +permissive: it does not merely escape a rule, it makes an available shape worth using. Named providers +replace the hand-written bodies, and a per-pair decision becomes a line in a table. + +### Two shifts worth marking + +Reading this page you have crossed two lines that nothing in the code announces, and both are worth +naming, since they are where readers most often lose track of what a context is. + +The first is the one with no signal at all. Until the application example, the wired type was **the data** +— the `String` being encoded, the `Vec`. From there it became a type you define to stand for your +application. No signature changed and no parameter appeared, yet `Self` stopped being data. That change +alone is what escapes coherence, because you can define as many application types as you like and only one +`String`. The vocabulary for the two is a **value context** and an **environmental context**. + +The second is visible in the code. An environmental context can already decide for itself; to let it decide +for a type you *do not own*, the value moves out of `Self` and becomes a parameter — which is exactly what +`CanEncodeValue` did. A capability about `Self` is **self-targeted**; one about a parameter that +`Self` merely decides for is **parameter-targeted**. + +## What it costs + +**It is more machinery than one trait.** A component is two traits, a marker type, and a wiring line per +context. For a capability with one implementation that is pure overhead, and a plain trait is the right +tool — [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the CGP construct for that case, and it needs no +wiring at all. + +**Uniqueness is per context, not global.** This is a real limit rather than a technicality. When a program +genuinely needs one answer program-wide — a single consistent `Ord` for a map key, where two orderings in +one program would corrupt the map — per-context choice is the wrong shape, and a coherent trait is safer. +CGP does not make coherence optional; it moves where the single answer is decided. + +**The choice is explicit, and that cuts both ways.** Nothing is inferred. A context that has not named a +provider does not get a default, and adding a capability means adding a line. That is the property the +whole design rests on, and it is also more to write and read than a trait with one implementation. + +**Wiring is checked lazily.** A table naming a provider whose requirements the context cannot meet still +compiles; the failure appears later, where the capability is used, and can be long. +[`check_components!`](/docs/reference/macros/check_components) forces it to the wiring line and names the +actual missing requirement, and +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) leads with the root cause for the classes +it recognizes. [Checking your wiring](./check-traits.md) is the fuller account. + +## Where to go next + +[How much CGP to use](./modularity-hierarchy.md) is the page to read next if this argument landed, because +a reader who has just been told coherence can be escaped needs to hear immediately that most code should +not bother. It lays out the range from a plain trait to fully wired components and argues for climbing no +higher than a problem needs. + +[Consumer and provider traits](./consumer-and-provider-traits.md) develops the trait split this page +introduced — what each half is for, and how a method call crosses between them. + +To see it working rather than argued, the [Hello World tutorial](/docs/tutorials/hello) is five minutes and +one durable idea, and the [Area calculation series](/docs/tutorials/area-calculation/) builds the split up +from plain functions. For the constructs themselves, +[`#[cgp_component]`](/docs/reference/macros/cgp_component) generates the pair, +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) writes a provider, and +[`delegate_components!`](/docs/reference/macros/delegate_components) is the table. + +The fullest public account of why coherence exists is the +[RustLab 2025 talk](/blog/rustlab-2025-coherence), which spends its first third establishing that the rule +is correct before working around it. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index c2963e6e..13463d92 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -5,15 +5,206 @@ sidebar_position: 18 # How much CGP to use -The ladder from a plain trait to fully wired components, and how to settle at the lowest rung that -solves the problem in front of you. +The ladder from a plain trait to fully wired components, and how to settle at the lowest rung that solves +the problem in front of you. -:::info +This page is a decision guide rather than an explanation, so it is short and meant to be acted on. It gives +one rule of thumb, works through the alternatives you are actually choosing between, names the cases where +CGP is simply the wrong tool, and ends with which of its shapes to reach for. If you are still deciding +whether CGP is for you at all, this is the page to read. -### Not written yet +## The rule of thumb -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +**Use CGP when a capability needs more than one implementation and the choice belongs to the context — not +before.** -::: +Almost everything follows from that. Most code has one implementation of most things, and for that code a +plain trait is not a compromise, it is the right answer. CGP is a rung you climb to deliberately, and the +useful question is never "is CGP good" but "CGP, or the thing already in place?". + +## What you are choosing between + +Each row concedes where the alternative wins, because in most rows it does. + +| The alternative | Prefer it when | Reach for CGP when | +|---|---|---| +| **A plain trait or generic** | A capability has one implementation, or one per type with a single global choice. **This is most code.** | The implementations multiply, the choice must differ per context, or threading a generic through every layer has started to hurt. | +| **A direct impl on the context** | A provider would have exactly one user. Two contexts that each have their own single implementation need no providers and no wiring at all. | A second context wants the *same* implementation, or the implementation should compose with a wrapper. | +| **An enum** | The variant set is small, closed, and known, with fixed operations. A `match` is clearer than any machinery. | The variant set is open, or independent modules must each contribute one. | +| **`dyn Trait`** | The set of implementations is not known until runtime. That openness is exactly what CGP gives up. | The set *is* known at build time, and you want the decoupling without the dispatch cost. | +| **A dependency-injection crate** | You specifically want a container's lifecycle and object-graph semantics. | You want compile-time-checked, reflection-free injection — which is the traits-and-generics approach, not a framework. | +| **A generic-programming library such as `frunk`** | A one-off manipulation of a heterogeneous list. The lighter, focused library is less to learn and enough. | The structural machinery is part of a larger component-and-wiring design. | +| **A hand-rolled macro** | The generation is narrow and local. | You notice you are reinventing marker types plus a helper trait — which is CGP's own mechanism. | +| **Waiting for a language feature** | A first-class facility would serve better and you can afford to wait. Rust's effects and reflection work is pursuing ground CGP covers. | You need the capability now, on stable Rust. CGP is complementary to what the language is building rather than a bet against it. | + +That last row is worth taking seriously rather than reading as a formality. Some of what CGP does is +plausibly better as a language feature eventually, and a project that can wait should. + +## Where CGP is the wrong tool + +Four cases are not trade-offs. Naming them is more useful than any argument in CGP's favour. + +**Runtime dynamism.** CGP cannot give you plugins loaded at startup, heterogeneous collections, or +redefinition while the program runs. Its wiring is fixed at build time. That lives on the runtime side, +where `dyn Trait` and the dynamic languages remain right. + +**Exactly one implementation.** A capability with one definition belongs in a plain trait. If you want it +to read like CGP anyway, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds it from a function with no +component, no provider, and no wiring — and it keeps working unchanged if a second implementation ever +arrives. + +**A small closed set of variants.** An enum and a `match` are clearer, faster to read, and free. + +**One instance program-wide.** When a program genuinely wants a single globally consistent answer — one +`Ord` for a map key, where two orderings in one program would corrupt the map — per-context choice is the +wrong shape. Coherent traits are safer, and this is the limit of CGP's central bargain. + +## "I only have one application — what does this buy me?" + +This is the question most people reach in their first week, looking at the single context their codebase +contains, and it deserves a straight answer rather than a prediction about the future. + +**Concede the obvious part first: with one context, the swappability payoff is not available.** Every +wiring line has one plausible value and every provider one user. Nothing about that is going to feel +worthwhile, and being told you will want a second context later asks you to spend now for a benefit you +cannot check. + +Three things do pay with one context. + +- **Overlapping implementations Rust rejects outright.** These multiply along the *target types* one + application touches, not along its contexts — so a single application with several types to encode, + serialize, or validate already has more than one implementation to place. That is + [bypassing coherence](./coherence.md), and it needs no second context at all. +- **The orphan-rule escape.** Adding a capability to a type from another crate needs one context and a + foreign type. No newtype wrapper, and no second application. +- **Dependencies declared where the implementation is.** A `&self` method on a concrete struct may read any + field and call any other method, so nothing short of reading the body tells you what it depends on. A + provider's declared requirements *are* that answer, and the compiler enforces them. This is worth + something in one context and more in each one added. + +And then the second context you probably already have: **the test harness.** It is the cheapest one to +justify and the one nobody argues about. + +**If none of that applies, the honest recommendation is to stay put.** A codebase with one application, no +capability needing more than one implementation, and no foreign type to extend is one where CGP's central +bargain does not pay. Reach for `#[cgp_fn]` alone, or nothing. + +## "Won't I end up with a context per configuration?" + +Partly justified, and the answer is composition rather than reassurance. Separating every axis really would +multiply — four independent binary choices would mean sixteen types. + +CGP does not ask you to separate an axis you do not need separated, and it composes with the patterns that +collapse one. A generic parameter on the context struct keeps a single type across several database +engines. An enum keeps a single type for a choice made from configuration at runtime. A context holds +either of those and wires its components normally. + +What a real application lands on is separation for the axis where a wrong combination must be +**impossible** — a mock client must never reach production — and collapse for everything else. CGP decides +which variations are worth their own type; the tools you already use handle the ones that are not. + +There is a payoff here worth naming if you are writing a library. An enum you expose for supported backends +is normally a ceiling on what downstream users can have: a new variant means a pull request or a fork. When +the context-generic code is written against capabilities rather than against the enum, a downstream crate +defines its own wider enum and its own context and reuses everything, with nothing to petition for. + +## Which shape to reach for + +CGP's code comes in three shapes, and readers sometimes resist being taught three where they expected one. +They are not three levels of sophistication — each answers a different question, and two questions settle +which you are in. + +**Is the capability about the data, or about the application?** About the data means the wired type *is* the +thing being operated on — `Rectangle: CanCalculateArea`. About the application means the wired type is one +you define to carry choices, often with no fields at all. + +**Does it concern a type you do not own, which different applications must treat differently?** If so, that +type moves out of `Self` and becomes a parameter. If not, targeting `Self` is enough. + +| Answers | The shape | What it gives you | +|---|---|---| +| About the data | **Retrofit** | Alternative implementations for an existing type, without changing its trait. One choice per type, program-wide. | +| About the application | **Application** | One choice per context you define — and you can define as many as you like. | +| About a foreign type, differing per application | **Fully modular** | One choice per context *per target type*. | + +**The application shape is where most CGP code lives**, which is worth stating plainly so that the most +elaborate shape does not read as the intended destination. A capability about the application — send an +email, query a user, run the server — wired per application, with no type parameter anywhere, is the +ordinary case. + +## How far to go inside CGP + +Deciding to use CGP is not the last decision. Its constructs form a progression, and the same rule applies +inside as outside: **stop at the lowest step that solves the problem in front of you.** Each step below is a +response to something you have already hit, not a level to reach. + +1. **A capability from a function.** [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) — one implementation, no + component, no wiring. Most capabilities never need more, and starting here costs nothing later: the trait + keeps its name and method, so promoting it leaves every call site untouched. +2. **A component.** [`#[cgp_component]`](/docs/reference/macros/cgp_component) with a provider and a + [wiring table](/docs/reference/macros/delegate_components) — when a second implementation is real, not + anticipated. Add [`check_components!`](/docs/reference/macros/check_components) at the same time; the + wiring is checked lazily and an unchecked table is the main source of confusing errors. +3. **Per-type dispatch.** The `open` statement, when one component needs a different provider per value of a + type parameter. This is the point at which the target moves out of `Self`, so it arrives with the + fully-modular shape rather than before it. +4. **Providers composed from providers.** + [Higher-order providers](/docs/reference/attributes/use_provider) — when one implementation should be + expressed in terms of another rather than chosen alongside it. Genuinely useful, and the step most often + taken too early: if nothing is being wrapped, there is nothing for it to do. +5. **Reusable wiring.** An [aggregate provider](/docs/reference/macros/delegate_components) for a small + bundle several contexts delegate to, or [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) when + wiring repeats across many contexts or a table has outgrown reading. Both add a hop between a component + and its provider, so neither pays until the repetition is real. + +**Steps 2 and 3 are where most CGP code sits.** Steps 4 and 5 answer scale and composition specifically, and +reaching for either before the problem exists is how a CGP codebase ends up harder to read than the one it +replaced — the machinery is real either way, and only pays when something is actually being shared or +wrapped. + +## What it costs + +**Every rung above a plain trait costs syntax and indirection.** Two traits, a marker type, and a wiring +line per context, plus a hop between a call and the code that runs. The wiring table is a single greppable +place naming exactly one provider per component, and it is still a hop a reader has to follow. + +**Diagnostics are the sharpest cost, and honesty here matters more than elsewhere.** A mis-wired context can +produce a wall of generated types. [`check_components!`](/docs/reference/macros/check_components) forces the +failure to the wiring line and names the actual missing requirement, and +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) un-hides the root cause the default trait +solver suppresses and leads with it. Both help substantially. Neither makes the raw output pleasant, and the +tool is a `v0.1.0-alpha` that reshapes the classes it recognizes rather than all of them. **Dramatically +better and actively improving, not solved.** + +**Compile-time cost goes up.** CGP does more work at compile time, and no number is quoted here that could +not be cited. The honest reframing is that resolution costing at compile time is resolution that would +otherwise cost at runtime or not be checked at all. + +**There is a learning curve.** The first useful thing — a capability written as a function, used with no +wiring — needs only ordinary Rust knowledge, so the first step is small. The curve past it is real. + +Three of those costs — the learning curve, decoding the diagnostics, and the volume of wiring to write and +read — are mechanical work over a vocabulary that is written down, which is the kind of thing a coding +assistant handles well. CGP publishes an [agent skill](https://github.com/contextgeneric/cgp-skills) that +teaches one that vocabulary, and a reader who already works with an assistant can attach it and judge for +themselves within the hour. It makes those three costs **smaller, not absent**: the diagnostics are still +verbose, the vocabulary still has to be learned by whoever reviews the code, and none of it moves any +boundary on this page. A codebase that will only ever have one application still belongs on `#[cgp_fn]` +alone, regardless of who writes the wiring. + +## Where to go next + +[Bypassing coherence](./coherence.md) is the argument behind the rule of thumb: why Rust allows one +implementation per type, and what CGP does about it. Read it if the question is *why* rather than *whether*. + +[Consumer and provider traits](./consumer-and-provider-traits.md) covers the mechanism the upper rungs are +built on, and closes with the same costs stated for that construct specifically. + +If the answer here was "not yet", [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the whole of what you +need — a capability from a function, no wiring, nothing to reverse later. If it was "yes", +the [Area calculation series](/docs/tutorials/area-calculation/) climbs the rungs in order, and +[`#[cgp_component]`](/docs/reference/macros/cgp_component) is where the component machinery starts. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* From c4b001787835887307aee9d05e477f0ba05f474a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 14:12:20 +0200 Subject: [PATCH 018/516] Review the written Concepts pages against their guide MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A review pass over the four written pages of the Concepts tier — the index and the three prose pages — checking them against the explanation guide, the communication strategy, and the compiler. Every snippet was recompiled against cgp 0.8.0-alpha with a `check_components!` assertion per wired context, every quoted error re-run, the two generated blanket impls on *Consumer and provider traits* re-derived with `cargo cgp expand`, and the coherence page's output block produced by actually running it. The substantive finding is on *Bypassing coherence*, and it is the defect the guide warns about by name. *The move* claimed its CGP block held "the same two bodies the compiler rejected a moment ago" — but the trait had silently changed from `CanEncode`, with the value in `Self`, to `CanEncodeValue`. That is exactly the shape change the guide says must be narrated rather than smuggled, and a reader comparing two versions of one program reads any unexplained difference as sleight of hand. Worse, the closing *Two shifts worth marking* then mislocated the crossing, saying the wired type was the data "until the application example" when it had been `ApiServer` and `Firmware` for two sections by then. The parameter move is now named where it happens, the parity claim is narrowed to what the two listings genuinely share — the same two overlapping bounds — and the closing section is rewritten as *Naming the two shapes*, attaching each qualifier to code the page has already shown rather than to a recollection of it. That also satisfies the guide's instruction to introduce the qualifiers at the transition each explains rather than as a glossary. The same page gains continuity with the front page. It now uses `EncodeAsText`, the name the homepage hero and the component-shape guide both use, instead of a third variant; and its plain-Rust application example runs on `String` like the rest of the page rather than switching to `Vec`, so one running example carries from the hero through the whole argument. The vanilla listing is also now introduced as the section's own CGP arrangement with the CGP taken back out, which is what makes it land. Two expectation-setters were false and are corrected: coherence claimed to be "the longest page in this section", which is fragile and only marginally true, and *How much CGP to use* opened by calling itself short at roughly 2,400 words. Both now describe their shape rather than their size. The `cargo cgp check` concession names `v0.1.0-alpha` on the two pages that omitted it, which `vocabulary.md` makes mandatory in the same breath as the claim, and which one of the three pages was already doing. Smaller accuracy fixes. The consumer trait no longer "keeps the original shape" in a listing where the trait gained a parameter. The reinvented-workaround claim is singular, matching the single citation in `evidence.md`. The provider trait printed on *Consumer and provider traits* omits its `IsProviderFor` supertrait, which is now disclosed alongside the other listing liberties rather than asserted two paragraphs later as though it had been shown. `open` no longer claims the target always moves out of `Self`, since the error components dispatch on a selector. Two links now point where their text says. And the index's "between the other two halves" counted three things as two. One reference page is corrected in the same change, because it carried a claim the concept work disproved: `delegate_components!` said an aggregate provider "never implements one with itself in the context position". A bundle of context-agnostic providers demonstrably does, which is precisely why a check on it can pass vacuously. The site builds, and no page links into the knowledge base. Co-Authored-By: Claude Opus 5 (1M context) --- docs/concepts/coherence.md | 95 +++++++++++-------- docs/concepts/consumer-and-provider-traits.md | 13 ++- docs/concepts/index.md | 2 +- docs/concepts/modularity-hierarchy.md | 23 ++--- docs/reference/macros/delegate_components.md | 7 +- 5 files changed, 78 insertions(+), 62 deletions(-) diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index a76f78d3..bc468ea4 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -9,9 +9,9 @@ Rust allows one implementation of a trait per type. Why that rule exists, what i writes many implementations and lets each context pick the one it wants. This page answers *why can't Rust do this already?* It builds up what the trait system gives you, shows -what that costs when you want two implementations of one thing, and ends on the move CGP makes — which is -smaller than it first appears, and does not throw the rule away. It is the longest page in this section, -and everything else here is downstream of it. +what that costs when you want two implementations of one thing, works through the move CGP makes — which +is smaller than it first appears, and does not throw the rule away — and closes on what that move costs in +turn. It is a long page, and it is the one everything else in this section is downstream of. ## The trait system is already a dependency-injection mechanism @@ -100,8 +100,8 @@ type your callers now have to know about. These are felt sharply enough that Rust developers build their own escape. The pattern is to stop implementing the trait for the interesting type and implement it for a marker type you own instead, with a -helper trait tying the two together — three or four extra lines of plumbing, arrived at independently and -written up by developers working around the overlap rule on their own. **If you have written that, you have +helper trait tying the two together — three or four extra lines of plumbing, arrived at and written up +independently by a Rust developer working around the overlap rule. **If you have written that, you have written CGP's central mechanism by hand**, and the rest of this page is about what it looks like made first-class. @@ -110,9 +110,10 @@ first-class. CGP's first move is to take the type coherence ranges over — the `Self` of the implementation — and make it something the implementing crate always owns. -One trait definition becomes two. The **consumer trait** keeps the original shape, so callers write -`app.encode(&value)` as before. The **provider trait** is the same interface with `Self` moved out into an -explicit parameter, and an implementation targets a small named type of its own: +One trait definition becomes two. The **consumer trait** is the caller's view, keeping the ordinary `self` +receiver so that calling the capability is still a method call. The **provider trait** is the same +interface with `Self` moved out into an explicit parameter, and an implementation targets a small named +type of its own: ```rust #[cgp_component(Encoder)] @@ -120,7 +121,7 @@ pub trait CanEncodeValue { fn encode(&self, value: &Value) -> Vec; } -#[cgp_impl(new EncodeWithDisplay)] +#[cgp_impl(new EncodeAsText)] impl Encoder where Value: Display, @@ -137,16 +138,22 @@ where } ``` -**Both compile.** They are the same two bodies the compiler rejected a moment ago, with the same -overlapping bounds, and there is no conflict — because each one's `Self` is a different type -(`EncodeWithDisplay`, `EncodeAsHex`) that this crate declared for the purpose. Any number more would also -compile. The orphan rule does not enter either, since that `Self` is always local, which is how a crate -adds a capability to a type it did not define. +**Both compile.** They carry the same two overlapping bounds the compiler rejected a moment ago — +`Display` and `AsRef<[u8]>`, still overlapping on `String` — and there is no conflict, because each one's +`Self` is now a different type (`EncodeAsText`, `EncodeAsHex`) that this crate declared for the purpose. +Any number more would also compile. The orphan rule does not enter either, since that `Self` is always +local, which is how a crate adds a capability to a type it did not define. Neither rule was repealed. The implementations simply stopped being the kind of thing the rules are about. [Consumer and provider traits](./consumer-and-provider-traits.md) works through the mechanics of the split and how a call finds its way across it. +One other thing changed in that listing, and it is worth naming rather than leaving you to spot it: the +value being encoded moved out of `Self` and into a `Value` parameter, so the trait is now +`CanEncodeValue` rather than `CanEncode`. That is a second move, not part of the first, and it is +what leaves `Self` free to be something other than the data. What it is free to be, and why that turns +out to matter more than the parameter does, is the next two sections. + ## Coherence comes back, one context at a time Making implementations incoherent would be useless if it also made *use* incoherent. A caller still needs @@ -160,7 +167,7 @@ small table: delegate_components! { ApiServer { open EncoderComponent; - @EncoderComponent.String: EncodeWithDisplay, + @EncoderComponent.String: EncodeAsText, } } @@ -192,12 +199,12 @@ Here is the part most easily misread, and it is worth slowing down for: **the es becomes a type you own, not when a parameter appears.** A scope is one context type, so the number of independent choices a program can make is the number of -context types it can define. Wire a capability onto `Vec` — data, and not yours — and you get exactly -one answer for the whole program, because there is one `Vec`. Coherence was narrowed, not removed. +context types it can define. Wire a capability onto `String` — data, and not yours — and you get exactly +one answer for the whole program, because there is one `String`. Coherence was narrowed, not removed. Wire it onto `ApiServer` and `Firmware`, types you declared, and you get as many answers as you care to declare types. -Which is why the two contexts above are `ApiServer` and `Firmware` rather than `Vec` wired twice. The +Which is why the two contexts above are `ApiServer` and `Firmware` rather than `String` wired twice. The second is impossible; the first is the point. ### The shape this depends on @@ -205,8 +212,8 @@ second is impossible; the first is the point. That leaves one thing to build, because it is a shape vanilla Rust gives you no reason to have imagined: **a type whose whole job is to stand for an application.** -Start from the fact that it is perfectly ordinary Rust. Two application types, one value type, two -encodings, no CGP anywhere: +Start from the fact that it is perfectly ordinary Rust. It is the arrangement from two sections ago with +the CGP taken back out: two application types, one value type, two encodings, and nothing exotic. ```rust pub trait CanEncodeValue { @@ -216,20 +223,19 @@ pub trait CanEncodeValue { pub struct ApiServer; pub struct Firmware; -impl CanEncodeValue> for ApiServer { - fn encode(&self, v: &Vec) -> Vec { /* one encoding */ } +impl CanEncodeValue for ApiServer { + fn encode(&self, value: &String) -> Vec { /* as text */ } } -impl CanEncodeValue> for Firmware { - fn encode(&self, v: &Vec) -> Vec { /* another */ } +impl CanEncodeValue for Firmware { + fn encode(&self, value: &String) -> Vec { /* as hexadecimal */ } } ``` -This compiles, and it already does something useful — per-application encoding of the same type, with -nothing exotic involved. Note that both structs have **no fields at all**. `struct ApiServer;` is a -complete and legitimate type here, because its entire purpose is to be a name the implementations hang -off. An empty struct with traits on it is otherwise close to unreadable, which is why it is worth saying -outright. +This compiles, and it already does something useful: per-application encoding of the same type. Note that +both structs have **no fields at all**. `struct ApiServer;` is a complete and legitimate type here, +because its entire purpose is to be a name the implementations hang off. An empty struct with traits on it +is otherwise close to unreadable, which is why it is worth saying outright. Now try to make it scale. Add a third value type, then a fourth, and you are hand-writing a body per `(application, type)` pair. So you do the obvious thing and factor the shared logic into a blanket @@ -253,21 +259,25 @@ this shape — it makes it not worth building.** CGP's contribution is therefore permissive: it does not merely escape a rule, it makes an available shape worth using. Named providers replace the hand-written bodies, and a per-pair decision becomes a line in a table. -### Two shifts worth marking +### Naming the two shapes -Reading this page you have crossed two lines that nothing in the code announces, and both are worth -naming, since they are where readers most often lose track of what a context is. +Two distinctions have been doing quiet work above, and naming them is what keeps "context" from becoming a +word you cannot pin down — it is where readers most often lose track. -The first is the one with no signal at all. Until the application example, the wired type was **the data** -— the `String` being encoded, the `Vec`. From there it became a type you define to stand for your -application. No signature changed and no parameter appeared, yet `Self` stopped being data. That change -alone is what escapes coherence, because you can define as many application types as you like and only one -`String`. The vocabulary for the two is a **value context** and an **environmental context**. +The first crossing had no signal at all. In the `CanEncode` listing further up, the wired type was **the +data**: `impl CanEncode for T` puts the thing being encoded in `Self`, exactly as `impl Display for String` +does, and that is the shape essentially every Rust trait is in. From *The move* onward the wired type has +been `ApiServer` or `Firmware` — types you define, holding no data, existing to carry choices. No signature +announced the change and no parameter marked it, yet `Self` stopped being data. The vocabulary is a +**value context** for the first and an **environmental context** for the second, and this is the crossing +that escapes coherence: you can define as many application types as you like, and there is only one +`String`. -The second is visible in the code. An environmental context can already decide for itself; to let it decide -for a type you *do not own*, the value moves out of `Self` and becomes a parameter — which is exactly what -`CanEncodeValue` did. A capability about `Self` is **self-targeted**; one about a parameter that -`Self` merely decides for is **parameter-targeted**. +The second crossing is visible in the code. A capability about `Self` is **self-targeted** — `CanEncode`, +as first written here. Moving the value into a parameter makes it **parameter-targeted**: +`CanEncodeValue` is about the `Value`, and `Self` only decides for it. An environmental context can +already choose for itself without that parameter; what the parameter adds is the ability to choose for a +type you *do not own*. ## What it costs @@ -290,7 +300,8 @@ compiles; the failure appears later, where the capability is used, and can be lo [`check_components!`](/docs/reference/macros/check_components) forces it to the wiring line and names the actual missing requirement, and [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) leads with the root cause for the classes -it recognizes. [Checking your wiring](./check-traits.md) is the fuller account. +it recognizes — a `v0.1.0-alpha` that reshapes the core wiring errors rather than all of them. +[Checking your wiring](./check-traits.md) is the fuller account. ## Where to go next diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index 73ce1b06..ce1fb7f8 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -7,7 +7,7 @@ sidebar_position: 2 One trait definition in CGP becomes two traits: a **consumer trait** that callers use, and a **provider trait** that implementations target. This page explains why the split exists, what each -half is for, and how a plain method call finds its way from one to the other. It ends with what the +half is for, and how a plain method call finds its way from one to the other. It closes on what the arrangement costs, which is the part worth reading before adopting it. ## What an ordinary Rust trait does, and where it stops @@ -182,11 +182,13 @@ what carries those bounds back down the chain — so when a context is missing s requires, the compiler can name the missing requirement instead of reporting only that the provider trait is not implemented. It is generated, never written by hand. -Two cosmetic liberties in the listings above are worth knowing before you read a real error message. -The generated type parameters carry reserved names — the context is `__Context__` and the provider +Three liberties in the listings above are worth knowing before you read a real error message. The +generated type parameters carry reserved names — the context is `__Context__` and the provider `__Provider__` — and the delegate is spelled out in full as `<__Provider__ as DelegateComponent>::Delegate`. `Context`, `Provider`, and -`Provider::Delegate` here are for legibility; `cargo cgp expand` will show you the real thing. +`Provider::Delegate` here are for legibility. And the provider trait printed earlier on this page omitted +its `IsProviderFor` supertrait, which the real `EmailSender<__Context__>` carries. `cargo cgp expand` will +show you all of it as the macros actually emit it. ## Writing it @@ -259,7 +261,8 @@ capability is finally used, and the error can be long. This is real, and it has [`check_components!`](/docs/reference/macros/check_components) forces the check at the wiring line so the error names the actual gap, and [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reshapes the recognized failures to -lead with the root cause. Neither makes the raw diagnostics pleasant — see +lead with the root cause, though it is a `v0.1.0-alpha` and covers the core wiring errors rather than +every class. Neither makes the raw diagnostics pleasant — see [Checking your wiring](./check-traits.md) for what to expect. **There is a hop between the call and the code that runs.** `app.send_email(..)` no longer points at diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 87a2e600..6bf58f18 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -9,7 +9,7 @@ This section explains the ideas behind CGP: why it is built the way it is, what actually does, and where the boundaries of each one lie. It is written to be read away from a keyboard — there is nothing here to follow along with, and nothing to install first. -It sits between the other two halves of the documentation. The [tutorials](/docs/tutorials/hello) +It sits alongside the other two parts of the documentation. The [tutorials](/docs/tutorials/hello) teach by building something, so they show a construct at the moment it is needed and move on. The [reference](/docs/reference/) explains one construct completely, for a reader who already knows the name of the thing they want. A concept page answers the question neither of those is shaped for: diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index 13463d92..6585ee72 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -8,10 +8,10 @@ sidebar_position: 18 The ladder from a plain trait to fully wired components, and how to settle at the lowest rung that solves the problem in front of you. -This page is a decision guide rather than an explanation, so it is short and meant to be acted on. It gives -one rule of thumb, works through the alternatives you are actually choosing between, names the cases where -CGP is simply the wrong tool, and ends with which of its shapes to reach for. If you are still deciding -whether CGP is for you at all, this is the page to read. +This page is a decision guide rather than an explanation, so it is written to be acted on rather than read +straight through: a rule of thumb first, then the alternatives you are actually choosing between, the cases +where CGP is simply the wrong tool, which of its shapes to reach for, and how far to go once you are inside +it. If you are still deciding whether CGP is for you at all, this is the page to read. ## The rule of thumb @@ -145,13 +145,14 @@ response to something you have already hit, not a level to reach. [wiring table](/docs/reference/macros/delegate_components) — when a second implementation is real, not anticipated. Add [`check_components!`](/docs/reference/macros/check_components) at the same time; the wiring is checked lazily and an unchecked table is the main source of confusing errors. -3. **Per-type dispatch.** The `open` statement, when one component needs a different provider per value of a - type parameter. This is the point at which the target moves out of `Self`, so it arrives with the - fully-modular shape rather than before it. -4. **Providers composed from providers.** - [Higher-order providers](/docs/reference/attributes/use_provider) — when one implementation should be - expressed in terms of another rather than chosen alongside it. Genuinely useful, and the step most often - taken too early: if nothing is being wrapped, there is nothing for it to do. +3. **Per-type dispatch.** The [`open` statement](/docs/reference/macros/delegate_components), when one + component needs a different provider per value of a type parameter. A type has moved out of `Self` into + a parameter by this point, so it usually arrives with the fully-modular shape rather than before it. +4. **Providers composed from providers.** A provider that takes another provider as a parameter and builds + on it, declared with [`#[use_provider]`](/docs/reference/attributes/use_provider) — when one + implementation should be expressed in terms of another rather than chosen alongside it. Genuinely + useful, and the step most often taken too early: if nothing is being wrapped, there is nothing for it to + do. 5. **Reusable wiring.** An [aggregate provider](/docs/reference/macros/delegate_components) for a small bundle several contexts delegate to, or [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) when wiring repeats across many contexts or a table has outgrown reading. Both add a hop between a component diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index b9816ba0..4681f83c 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -66,9 +66,10 @@ delegate_components! { This is how you build an **aggregate provider**: a zero-sized provider whose only job is to hold a table dispatching each component to a sub-provider, so that other contexts can delegate a whole group of components to it as one unit. An aggregate provider is a *provider*, not a context — it forwards -each component's provider trait onward and never implements one with itself in the context position. -That is why it must be wired with plain `delegate_components!` and never with -[`delegate_and_check_components!`](./delegate_and_check_components.md). +each component's provider trait onward, and no call ever resolves with the bundle in the context +position. That is why it must be wired with plain `delegate_components!` and never with +[`delegate_and_check_components!`](./delegate_and_check_components.md), whose check asks whether the +bundle can use each component *as* a context and so proves nothing either way. ### One provider for several components From 6c84f1bc617b7549980a36c0f5975bc3b878a21d Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 14:23:41 +0200 Subject: [PATCH 019/516] Add a crate holding the compiled counterparts of the site's code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every snippet on the site is verified once, by the agent that wrote it, and then the verification evaporates. The next agent to revise that page has no way to tell a snippet that still compiles from one that stopped, short of rebuilding the program from the page — which is the work the first agent already did. `example-code/` keeps it. The crate is not part of the site. Docusaurus never sees it, no page links it, and readers are not meant to find it; the audience is the agent revising a page. Its layout mirrors `docs/` one file per page with the name in `snake_case`, so `docs/concepts/coherence.md` is answered by `src/concepts/coherence.rs`, and inside a file there is one module per heading of the page, in the page's order. A page showing no code gets no file. Duplication between files is wanted rather than tolerated: each file has to answer for its page alone, so a reader comparing the two never follows an import to see what the page said. It is filled in **lazily**. A page gets its file when someone writes, revises, or reviews it, so a missing file means nobody has been through that page yet rather than that the page is unverified. This commit therefore carries only the two pages of this session's Concepts review that show Rust — *Bypassing coherence* and *Consumer and provider traits*. *How much CGP to use* and the section index show none and get no module. `docs/reference/macros/delegate_components.md` was touched this session too, but only one prose sentence and none of its snippets, so giving it a file would claim a verification that was never done. Four things the README fixes as conventions, each because the alternative is a check that quietly proves nothing. A page shows the shape of a program and the crate shows a program, so **elided bodies are filled in, each with a comment saying the page elided it**. That makes the difference legible: a body that differs is expected, and a signature, bound, attribute, or wiring line that differs is a defect in one side or the other. **Code a page deliberately rejects is a `compile_fail` doctest** — the two overlap-rule blocks and the orphan-rule block, which cannot be code in a crate that must compile. Their bodies are filled in too, and for a sharper reason: a `/* ... */` body fails on its own, so the doctest would have passed while proving nothing about the error the page quotes. The README states the limit rather than implying a guarantee, because it was tested: rustdoc accepts an error code after the annotation and does **not** enforce it, so a doctest claiming `E0117` around a snippet that fails with `E0119` passes. What these genuinely catch is the regression that matters, a rejected snippet the compiler has started accepting. **A listing of *generated* code can only be shape-checked here.** The two blanket impls on *Consumer and provider traits* are rebuilt by hand into a working component, which shows the listing is structurally sound and says nothing about whether its text is current; `cargo cgp expand` stays the authority on that, as it already is for the reference port. And **tests pin what a page asserts beyond compiling**. The coherence page quotes an output block, so a test asserts `hi` and `6869`; the consumer/provider page claims its implicit arguments leave `send_email(to, body)` at two arguments, so a test calls it that way. Every wired context carries a `check_components!` assertion, which is what proves wiring resolves rather than merely parses. `cargo test` is green with no warnings, and the site builds unchanged. The pin is `cgp = "0.8.0-alpha"`, which resolves from crates.io today and joins the tutorials' pin on the release checklist. Co-Authored-By: Claude Opus 5 (1M context) --- example-code/.gitignore | 2 + example-code/Cargo.toml | 11 + example-code/README.md | 87 +++++++ example-code/src/concepts/coherence.rs | 201 +++++++++++++++ .../concepts/consumer_and_provider_traits.rs | 237 ++++++++++++++++++ example-code/src/concepts/mod.rs | 8 + example-code/src/lib.rs | 22 ++ 7 files changed, 568 insertions(+) create mode 100644 example-code/.gitignore create mode 100644 example-code/Cargo.toml create mode 100644 example-code/README.md create mode 100644 example-code/src/concepts/coherence.rs create mode 100644 example-code/src/concepts/consumer_and_provider_traits.rs create mode 100644 example-code/src/concepts/mod.rs create mode 100644 example-code/src/lib.rs diff --git a/example-code/.gitignore b/example-code/.gitignore new file mode 100644 index 00000000..4fffb2f8 --- /dev/null +++ b/example-code/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml new file mode 100644 index 00000000..14e695a1 --- /dev/null +++ b/example-code/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "cgp-website-example-code" +version = "0.0.0" +edition = "2021" +publish = false +description = "Compiled counterparts of the code shown on contextgeneric.dev. Not part of the site." + +[dependencies] +cgp = "0.8.0-alpha" + +[workspace] diff --git a/example-code/README.md b/example-code/README.md new file mode 100644 index 00000000..e4309440 --- /dev/null +++ b/example-code/README.md @@ -0,0 +1,87 @@ +# Website example code + +This crate holds compiled counterparts of the code shown on . **It is not +part of the website.** Nothing here is rendered, linked, or served, no page refers to it, and readers +are not meant to find it. It exists for the agent revising a documentation page, so that the code on +that page can be checked against something the compiler has agreed to rather than read and hoped for. + +Run it from this directory: + +```sh +cargo test # the full check: the code compiles, and the rejected snippets still fail +cargo check # the fast check: the code compiles +``` + +## The layout mirrors `docs/` + +One file per page, at the matching path with the file name in `snake_case`: + +| Page | File | +|---|---| +| `docs/concepts/coherence.md` | `src/concepts/coherence.rs` | +| `docs/concepts/consumer-and-provider-traits.md` | `src/concepts/consumer_and_provider_traits.rs` | + +A page that shows no code gets no file — `docs/concepts/modularity-hierarchy.md` is prose and tables, +so it has no module here, and neither does a section index. + +Inside a file, **one module per heading of the page**, named after that heading and in the page's +order, so a snippet can be found from where it sits on the page rather than by searching. Where two +consecutive headings are really one program, one module covers both and says so. + +**Duplication between files is expected and wanted.** Each file answers for one page on its own, so a +scenario two pages share is written out twice rather than factored into a helper that neither page +shows. A reader comparing a page against its file should never have to follow an import to see what +the page said. + +## What "matches" means + +A page shows the shape of a program; this crate shows a program. The two differ in ways that are +correct, and confusing an expected difference for a defect wastes more time than the check saves. + +**Expected, and not a defect.** A body the page elides as `/* ... */` is filled in here, and every +such fill-in carries a comment saying the page elided it. Imports the page omits are present. +Types the page names without declaring — a provider it has not introduced yet, a context it +introduces two sections later — are declared. `check_components!` assertions are added for every +wired context, since that is what proves the wiring resolves rather than merely parses, and pages do +not show them. Tests are added where a page quotes an output or makes a claim worth pinning. + +**A defect, in one or the other.** Anything else: a signature, a trait bound, an attribute, a derive, +a wiring line, a provider name, an item that exists on one side and not the other. When they +disagree, find out which is wrong rather than assuming — the crate is checked by the compiler and the +page is not, so the page is the likelier culprit, but a stale file here is worse than no file. + +## Code a page deliberately rejects + +Several pages show code the compiler refuses, quoting the error as the point of the snippet. That +code cannot live in the crate, so it is carried as a `compile_fail` doctest in the module for its +section, with the quoted error code in a comment. + +Two limits are worth knowing. **`compile_fail` does not check *which* error is produced** — rustdoc +accepts an error code after the annotation but does not enforce it, so a snippet that starts failing +for an unrelated reason still passes. What the doctest genuinely catches is the regression that +matters: a snippet the page calls rejected that the compiler has started accepting. And **a body the +page elides has to be filled in for these too**, so that the quoted error is the only thing wrong +with the snippet — an empty `/* ... */` body would fail on its own and the doctest would pass while +proving nothing. + +## Generated code + +Two of these pages show what a macro *generates*, in simplified form. A hand-rolled rendering of such +a listing — as `concepts::consumer_and_provider_traits::how_a_call_finds_its_provider` carries — is a +weaker check than the rest of this crate: it shows the listing is structurally sound, not that its +text is current. **The authority on what a macro emits is `cargo cgp expand --lib --item …`**, run +against the crate the page's example lives in. Check the text with `expand`; check the shape here. + +## Adding a file + +Files are added **lazily**: when a page that shows code is written, or revised, or reviewed, its file +is created or brought back into agreement in the same change. There is no obligation to backfill +pages nobody is working on, and a missing file means only that nobody has been through that page yet. + +Adding one means creating it at the mirrored path, registering it in the parent `mod.rs`, adding a +row to the table above, and leaving `cargo test` green. + +## The `cgp` version + +The crate pins `cgp = "0.8.0-alpha"`, which is what resolves from crates.io today. Re-pin it to +`"0.8.0"` when that release ships, alongside the version pins in the tutorials. diff --git a/example-code/src/concepts/coherence.rs b/example-code/src/concepts/coherence.rs new file mode 100644 index 00000000..ec49bbcc --- /dev/null +++ b/example-code/src/concepts/coherence.rs @@ -0,0 +1,201 @@ +//! Code from `docs/concepts/coherence.md` — *Bypassing coherence*. +//! +//! Module names follow the page's headings. Code the page **rejects** — the blocks whose comment +//! quotes an `error[E…]` — is carried as a `compile_fail` doctest rather than as code, since the +//! crate could not compile otherwise; each one records the code the compiler actually reports. + +/// ## The trait system is already a dependency-injection mechanism +pub mod trait_system_as_dependency_injection { + use core::fmt::Display; + + pub fn describe(value: &T) -> String { + format!("{value}") + } + + #[test] + fn the_caller_names_no_implementation() { + assert_eq!(describe(&42), "42"); + } +} + +/// ## That only works because every lookup finds the same answer +/// +/// Both blocks in this section are rejected by the compiler, which is the point of showing them, so +/// neither can be code in this crate. The bodies the page elides are filled in below so that the +/// quoted error is the *only* thing wrong with each — a `/* ... */` body would fail on its own and +/// the doctest would pass for the wrong reason. +/// +/// The overlap rule. `String` is both `Display` and `AsRef<[u8]>`: +/// +/// ```compile_fail +/// use core::fmt::Display; +/// +/// pub trait CanEncode { +/// fn encode(&self) -> Vec; +/// } +/// +/// // Legal on its own. +/// impl CanEncode for T { +/// fn encode(&self) -> Vec { self.to_string().into_bytes() } +/// } +/// +/// // error[E0119]: conflicting implementations of trait `CanEncode` +/// impl> CanEncode for T { +/// fn encode(&self) -> Vec { self.as_ref().to_vec() } +/// } +/// ``` +/// +/// The orphan rule. Neither `Display` nor `Vec` belongs to this crate: +/// +/// ```compile_fail +/// use core::fmt::{self, Display, Formatter}; +/// +/// // error[E0117]: only traits defined in the current crate can be implemented +/// // for types defined outside of the crate +/// impl Display for Vec { +/// fn fmt(&self, f: &mut Formatter) -> fmt::Result { Ok(()) } +/// } +/// ``` +pub mod every_lookup_finds_the_same_answer {} + +/// ## The move: make `Self` a type you own +/// +/// … together with **## Coherence comes back, one context at a time**, which wires the component +/// this section defines. The page splits them across two headings; they are one program. +pub mod the_move { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_component(Encoder)] + pub trait CanEncodeValue { + fn encode(&self, value: &Value) -> Vec; + } + + #[cgp_impl(new EncodeAsText)] + impl Encoder + where + Value: Display, + { + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() + } + } + + #[cgp_impl(new EncodeAsHex)] + impl Encoder + where + Value: AsRef<[u8]>, + { + // The page elides this body as `/* hex-encode the bytes */`. + fn encode(&self, value: &Value) -> Vec { + value + .as_ref() + .iter() + .flat_map(|byte| format!("{byte:02x}").into_bytes()) + .collect() + } + } + + // The page uses these two contexts without declaring them, since by that point it has only + // introduced the word "context". + pub struct ApiServer; + pub struct Firmware; + + delegate_components! { + ApiServer { + open EncoderComponent; + @EncoderComponent.String: EncodeAsText, + } + } + + delegate_components! { + Firmware { + open EncoderComponent; + @EncoderComponent.String: EncodeAsHex, + } + } + + mod check_api_server { + use super::*; + check_components! { ApiServer { EncoderComponent: String } } + } + + mod check_firmware { + use super::*; + check_components! { Firmware { EncoderComponent: String } } + } + + /// The page quotes the output of this in a ```` ```text ```` block, so the two lines are pinned + /// here rather than left to be re-derived by eye. + #[test] + fn the_two_contexts_encode_the_same_string_differently() { + let value = "hi".to_owned(); + + assert_eq!( + String::from_utf8(ApiServer.encode(&value)).unwrap(), + "hi", // ApiServer: hi + ); + assert_eq!( + String::from_utf8(Firmware.encode(&value)).unwrap(), + "6869", // Firmware: 6869 + ); + } +} + +/// ### The shape this depends on +/// +/// The arrangement of [`the_move`] with the CGP taken back out: two application types, one value +/// type, two encodings, and no CGP at all. It compiles, which is the section's whole point. +pub mod the_shape_this_depends_on { + pub trait CanEncodeValue { + fn encode(&self, value: &Value) -> Vec; + } + + pub struct ApiServer; + pub struct Firmware; + + impl CanEncodeValue for ApiServer { + // The page elides this body as `/* as text */`. + fn encode(&self, value: &String) -> Vec { + value.clone().into_bytes() + } + } + + impl CanEncodeValue for Firmware { + // The page elides this body as `/* as hexadecimal */`. + fn encode(&self, value: &String) -> Vec { + value + .as_bytes() + .iter() + .flat_map(|byte| format!("{byte:02x}").into_bytes()) + .collect() + } + } +} + +/// ### The shape this depends on — where it stops scaling +/// +/// The second block of that section: factoring the shared logic into a blanket implementation runs +/// into the overlap rule, this time on an application type. Rejected, so it is a doctest. +/// +/// ```compile_fail +/// use core::fmt::Display; +/// +/// pub trait CanEncodeValue { +/// fn encode(&self, value: &Value) -> Vec; +/// } +/// +/// pub struct ApiServer; +/// +/// impl CanEncodeValue for ApiServer { +/// fn encode(&self, value: &V) -> Vec { value.to_string().into_bytes() } +/// } +/// +/// // error[E0119]: conflicting implementations of trait `CanEncodeValue<_>` +/// // for type `ApiServer` +/// impl> CanEncodeValue for ApiServer { +/// fn encode(&self, value: &V) -> Vec { value.as_ref().to_vec() } +/// } +/// ``` +pub mod the_shape_stops_scaling {} diff --git a/example-code/src/concepts/consumer_and_provider_traits.rs b/example-code/src/concepts/consumer_and_provider_traits.rs new file mode 100644 index 00000000..9d05e931 --- /dev/null +++ b/example-code/src/concepts/consumer_and_provider_traits.rs @@ -0,0 +1,237 @@ +//! Code from `docs/concepts/consumer-and-provider-traits.md` — *Consumer and provider traits*. +//! +//! Module names follow the page's headings. Code the page **rejects** is carried as a +//! `compile_fail` doctest, and the two listings the page presents as *generated* code are rebuilt by +//! hand in [`how_a_call_finds_its_provider`], which is a weaker check than it looks — see the note +//! there. + +/// ## What an ordinary Rust trait does, and where it stops +/// +/// The arrangement the page opens on: two application types, two behaviours, no CGP. It compiles, +/// which is what the paragraph after it says. +/// +/// The section's second block does not, and is the reason the first one does not scale. The two +/// marker traits it bounds on are undeclared on the page, so they are declared here; without them +/// the failure would be an unresolved name rather than the overlap it is meant to show: +/// +/// ```compile_fail +/// pub trait CanSendEmail { +/// fn send_email(&self, to: &str, body: &str); +/// } +/// +/// pub trait HasSmtpConfig {} +/// pub trait HasRecordedEmails {} +/// +/// impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } +/// impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } // error[E0119] +/// ``` +pub mod what_an_ordinary_rust_trait_does { + use core::cell::RefCell; + + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + pub struct App { + pub smtp_server: String, + } + + pub struct TestApp { + pub sent_emails: RefCell>, + } + + impl CanSendEmail for App { + fn send_email(&self, to: &str, body: &str) { + // open a connection to self.smtp_server and send + } + } + + impl CanSendEmail for TestApp { + fn send_email(&self, to: &str, body: &str) { + self.sent_emails.borrow_mut().push(format!("{to}: {body}")); + } + } +} + +/// ## Splitting one trait in two +/// +/// The trait pair written out by hand, and two implementations targeting named types. The page +/// elides both bodies as `/* ... */`, which would leave the impls empty and the required method +/// missing, so they are filled in here. +pub mod splitting_one_trait_in_two { + // what callers use + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + // what implementations target + pub trait EmailSender { + fn send_email(context: &Context, to: &str, body: &str); + } + + // The page names these two providers without declaring them. + pub struct SendViaSmtp; + pub struct RecordEmails; + + impl EmailSender for SendViaSmtp { + fn send_email(context: &Context, to: &str, body: &str) {} + } + + impl EmailSender for RecordEmails { + fn send_email(context: &Context, to: &str, body: &str) {} + } +} + +/// ## How a call finds its provider +/// +/// The section's three listings — the wiring table, the consumer blanket impl, and the provider +/// blanket impl — assembled into one program. Because the last two are what `#[cgp_component]` +/// *generates*, they are written by hand here rather than derived, which is the point: the page +/// claims a component is these pieces, and a hand-rolled component built from exactly them resolves +/// a call and passes a check. +/// +/// **This proves the listings are structurally sound, not that they are textually current.** The +/// authority on what the macro emits is `cargo cgp expand --lib --item …`, which is also what the +/// page's own note about reserved names and the spelled-out delegate refers to. Check the text +/// against `expand`; check the shape against this module. +pub mod how_a_call_finds_its_provider { + use cgp::prelude::*; + + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + pub trait EmailSender { + fn send_email(context: &Context, to: &str, body: &str); + } + + // The key. The page calls it "a marker type generated alongside the two traits". + pub struct EmailSenderComponent; + + pub struct SendViaSmtp; + pub struct RecordEmails; + + impl EmailSender for SendViaSmtp { + fn send_email(context: &Context, to: &str, body: &str) {} + } + + impl EmailSender for RecordEmails { + fn send_email(context: &Context, to: &str, body: &str) {} + } + + // Generated for every provider, and not shown on the page, which says only that it is + // "generated, never written by hand". Without it the provider blanket impl below has an + // unsatisfiable bound. + impl IsProviderFor for SendViaSmtp {} + impl IsProviderFor for RecordEmails {} + + pub struct App; + pub struct TestApp; + + delegate_components! { App { EmailSenderComponent: SendViaSmtp } } + delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } + + // The first generated implementation: a context that implements the provider trait for itself + // gets the consumer trait. + impl CanSendEmail for Context + where + Context: EmailSender, + { + fn send_email(&self, to: &str, body: &str) { + Context::send_email(self, to, body) + } + } + + // The second: anything with a table entry inherits the provider trait from what the entry names. + impl EmailSender for Provider + where + Provider: DelegateComponent + + IsProviderFor, + Provider::Delegate: EmailSender, + { + fn send_email(context: &Context, to: &str, body: &str) { + Provider::Delegate::send_email(context, to, body) + } + } + + /// The three-step resolution the page traces, asserted as a bound rather than described. + #[test] + fn a_call_resolves_through_the_table() { + fn resolves() {} + + resolves::(); + resolves::(); + + App.send_email("a@b.c", "hi"); + } +} + +/// ## Writing it +/// +/// The same component as [`how_a_call_finds_its_provider`], written the way it is actually written: +/// the two traits, the marker, and both blanket impls come from `#[cgp_component]`, and each +/// provider is a `#[cgp_impl]` block in consumer-trait shape. +pub mod writing_it { + use core::cell::RefCell; + + use cgp::prelude::*; + + #[cgp_component(EmailSender)] + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + #[cgp_impl(new SendViaSmtp)] + impl EmailSender { + fn send_email(&self, #[implicit] smtp_server: &str, to: &str, body: &str) { + // open a connection to `smtp_server` and send the message + } + } + + #[cgp_impl(new RecordEmails)] + impl EmailSender { + fn send_email( + &self, + #[implicit] sent_emails: &RefCell>, + to: &str, + body: &str, + ) { + sent_emails.borrow_mut().push(format!("{to}: {body}")); + } + } + + #[derive(HasField)] + pub struct App { + pub smtp_server: String, + } + + #[derive(HasField)] + pub struct TestApp { + pub sent_emails: RefCell>, + } + + delegate_components! { App { EmailSenderComponent: SendViaSmtp } } + delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } + + mod check_app { + use super::*; + check_components! { App { EmailSenderComponent } } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { EmailSenderComponent } } + } + + /// The page's claim that the implicit arguments leave the public signature alone, so + /// `app.send_email(to, body)` still takes two arguments. + #[test] + fn each_provider_reads_a_different_field_and_neither_reaches_the_signature() { + let test_app = TestApp { + sent_emails: RefCell::new(Vec::new()), + }; + test_app.send_email("a@b.c", "hi"); + + assert_eq!(test_app.sent_emails.borrow().as_slice(), ["a@b.c: hi"]); + } +} diff --git a/example-code/src/concepts/mod.rs b/example-code/src/concepts/mod.rs new file mode 100644 index 00000000..f03cd4d2 --- /dev/null +++ b/example-code/src/concepts/mod.rs @@ -0,0 +1,8 @@ +//! Code from the pages under `docs/concepts/`, one module per page. +//! +//! Three of the eighteen pages in that section are written, and two of those three show code. +//! *How much CGP to use* (`modularity-hierarchy.md`) shows none — it is a decision guide built from +//! prose and tables — so it has no module here, and neither does the section index. + +pub mod coherence; +pub mod consumer_and_provider_traits; diff --git a/example-code/src/lib.rs b/example-code/src/lib.rs new file mode 100644 index 00000000..48d03dba --- /dev/null +++ b/example-code/src/lib.rs @@ -0,0 +1,22 @@ +//! Compiled counterparts of the code shown on . +//! +//! This crate is **not part of the website**. Nothing here is rendered, linked, or served, and no +//! page refers to it. It exists so that an agent revising a documentation page can check the code on +//! that page against something the compiler has agreed to, instead of reading the snippet and hoping. +//! +//! The layout mirrors the `docs/` tree one file per page: the code on +//! `docs/concepts/consumer-and-provider-traits.md` lives in +//! `src/concepts/consumer_and_provider_traits.rs`, and so on for every page that shows code. Pages +//! that show none get no file. Duplication between files is expected and wanted — each file answers +//! for one page, so a shared example is written out again rather than factored into a helper that +//! neither page shows. +//! +//! See `README.md` for how to use it, what "matches" means when a page elides a body, and the rules +//! for adding a file. + +// A page shows the shape of a program rather than a whole one, so its code is full of items nothing +// calls and parameters nothing reads once an elided body is filled in. Those warnings would be noise +// here; a warning that means something — an unused import, an unreachable pattern — still fires. +#![allow(dead_code, unused_variables)] + +pub mod concepts; From 066005e58bf91a9d9183223d5b876d016624c7c6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 15:02:38 +0200 Subject: [PATCH 020/516] Write the remaining fifteen Concepts pages, and their compiled code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The explanation tier is complete: eighteen pages plus the index, one per idea in the internal concepts catalog. The index loses its *Still being written* notice, and the section stops being a catalogue of placeholders with three essays in it. The fifteen are the three faces of dependency injection (impl-side dependencies, implicit arguments, abstract types), the lazy-wiring answer (checking your wiring), composition and scale (higher-order providers, aggregate providers, namespaces), the applied families (modular error handling, handlers, monadic handlers), the shape-generic group (extensible records, extensible variants, dispatching), and the two that stand apart (type-level DSLs, recovering `Send` bounds). Each follows the guide: an opening naming the page's question and saying where it ends, the argument in its own headings with code as illustration, and the two fixed closing sections — *What it costs*, then *Where to go next*. Project voice throughout, and every page explains what Rust already does before improving on it. Several rest on that harder than the shape requires, because it is where they are most likely to go wrong: *impl-side dependencies* opens on a plain blanket impl and says outright that a reader who has used `Itertools` has used the mechanism; *extensible variants* frames the expression problem before any derive; *recovering `Send` bounds* is explicitly about a gap in stable Rust that CGP happens to meet sooner than most code. **Every page that shows code now has a compiled counterpart in `example-code/`, seventeen files in all, so `docs/concepts/` is the first section the crate covers in full.** That is what turned this from transcription into verification, and it caught four things. The compiler rejected the natural namespace example. A context joining a namespace and overriding one of its entries does not compile: joining generates a forwarding impl covering every key the namespace answers, so a direct entry for a **bound** key overlaps it and is rejected with `E0119`. Only a path the namespace routes to *without* binding is available to a context. The page is built around that rule rather than around the intuition it breaks, teaches namespace design as the question *what varies?*, and carries both rejected forms as `compile_fail` doctests. The internal concept document had the wrong version and is corrected separately. `#[check_providers]` is a table-level attribute, not a per-entry one. *Abstract types* claimed a bad `UseType` was "rejected at the wiring line". Wiring `UseType` against a `Copy`-bounded scalar compiles; the bound is checked lazily like every other wiring choice and surfaces through `check_components!`. The claim contradicted *Checking your wiring* two pages later, and the corrected version makes the better point. *Dispatching* claimed a matcher cannot be named directly in its table and presented a wrapper provider as unavoidable. Naming `MatchWithValueHandlers` directly works; the wrapper is what a *recursive* shape needs, where a variant's payload is the enum again. The example is simpler for dropping it, and the cost section now describes the case that actually pays it. Three pages lean on real compiler output rather than describing it. *Checking your wiring* follows one broken context through three stages — the unchecked `E0599` that never names the missing field, the checked `CanUseComponent` error that names it as a type-level character list, and `cargo cgp check`'s `[CGP-E001]` root-cause tree naming `sent_emails` — which is the whole page. *Aggregate providers* shows both halves of the checking trap, including the silent one, as a doctest that compiles beside one that does not. *Extensible records* pins "finalizing early does not compile". Every wired context in the crate carries a `check_components!` assertion, except where the question is wrong to ask: the aggregate-provider bundles, the hand-rolled component in `consumer_and_provider_traits` that has no `#[cgp_component]` to check, and two error-scaffolding tables whose behaviour the tests exercise directly. `cargo test` in `example-code/` is green — 43 unit tests, 13 `compile_fail` doctests, no warnings — and the site builds with no broken links. Co-Authored-By: Claude Opus 5 (1M context) --- docs/concepts/abstract-types.md | 182 ++++++++- docs/concepts/aggregate-providers.md | 161 +++++++- docs/concepts/check-traits.md | 218 +++++++++- docs/concepts/dispatching.md | 122 +++++- docs/concepts/extensible-records.md | 132 +++++- docs/concepts/extensible-variants.md | 142 ++++++- docs/concepts/handlers.md | 170 +++++++- docs/concepts/higher-order-providers.md | 183 ++++++++- docs/concepts/impl-side-dependencies.md | 270 ++++++++++++- docs/concepts/implicit-arguments.md | 173 +++++++- docs/concepts/index.md | 9 - docs/concepts/modular-error-handling.md | 180 ++++++++- docs/concepts/monadic-handlers.md | 111 ++++- docs/concepts/namespaces.md | 208 +++++++++- docs/concepts/send-bounds.md | 136 ++++++- docs/concepts/type-level-dsls.md | 144 ++++++- example-code/Cargo.toml | 3 + example-code/README.md | 12 +- example-code/src/concepts/abstract_types.rs | 187 +++++++++ .../src/concepts/aggregate_providers.rs | 237 +++++++++++ example-code/src/concepts/check_traits.rs | 165 ++++++++ example-code/src/concepts/dispatching.rs | 127 ++++++ .../src/concepts/extensible_records.rs | 99 +++++ .../src/concepts/extensible_variants.rs | 147 +++++++ example-code/src/concepts/handlers.rs | 200 +++++++++ .../src/concepts/higher_order_providers.rs | 296 ++++++++++++++ .../src/concepts/impl_side_dependencies.rs | 251 ++++++++++++ .../src/concepts/implicit_arguments.rs | 197 +++++++++ example-code/src/concepts/mod.rs | 21 +- .../src/concepts/modular_error_handling.rs | 214 ++++++++++ example-code/src/concepts/monadic_handlers.rs | 118 ++++++ example-code/src/concepts/namespaces.rs | 380 ++++++++++++++++++ example-code/src/concepts/send_bounds.rs | 101 +++++ example-code/src/concepts/type_level_dsls.rs | 90 +++++ 34 files changed, 5281 insertions(+), 105 deletions(-) create mode 100644 example-code/src/concepts/abstract_types.rs create mode 100644 example-code/src/concepts/aggregate_providers.rs create mode 100644 example-code/src/concepts/check_traits.rs create mode 100644 example-code/src/concepts/dispatching.rs create mode 100644 example-code/src/concepts/extensible_records.rs create mode 100644 example-code/src/concepts/extensible_variants.rs create mode 100644 example-code/src/concepts/handlers.rs create mode 100644 example-code/src/concepts/higher_order_providers.rs create mode 100644 example-code/src/concepts/impl_side_dependencies.rs create mode 100644 example-code/src/concepts/implicit_arguments.rs create mode 100644 example-code/src/concepts/modular_error_handling.rs create mode 100644 example-code/src/concepts/monadic_handlers.rs create mode 100644 example-code/src/concepts/namespaces.rs create mode 100644 example-code/src/concepts/send_bounds.rs create mode 100644 example-code/src/concepts/type_level_dsls.rs diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index bf8c323e..1ba72b3e 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -8,12 +8,182 @@ sidebar_position: 5 Naming a type in generic code — an error type, a scalar, a runtime — and letting each context decide what it actually is. -:::info +This page answers *how does code name a type it does not choose?* It starts from the ordinary Rust +feature that already does this, shows what CGP adds to it, and works through the two things abstract +types buy: a type several pieces of code can agree on, and signatures that stop growing. It closes on +the costs, which are mostly about what an abstract type is *not*. -### Not written yet +## Rust already has this -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +An abstract type in CGP is an ordinary associated type, and it is worth starting there because it means +half of what follows is a feature you already use: -::: +```rust +pub trait HasScalarType { + type Scalar: Copy; +} + +impl HasScalarType for HighPrecision { + type Scalar = f64; +} + +impl HasScalarType for Embedded { + type Scalar = f32; +} +``` + +Generic code names `Context::Scalar` and never commits to `f32` or `f64`. Each type answers for itself, +the compiler resolves the answer where a concrete type is known, and nothing costs anything at runtime. +That is the whole idea, and CGP does not replace it — a context can implement an abstract-type trait +directly, exactly as above, and everything else on this page still works. + +What is worth noticing is the *direction*. A generic parameter is an input the caller supplies; an +associated type is an output the implementing type determines. That difference is small in one function +and decides how a codebase ages, which the last section of this page is about. + +## Choosing the type by wiring + +What CGP adds is that the choice can be made in the same place as every other choice a context makes. +[`#[cgp_type]`](/docs/reference/macros/cgp_type) turns an abstract-type trait into a component: + +```rust +#[cgp_type] +pub trait HasScalarType { + type Scalar: Copy; +} +``` + +and a context then names its concrete type in its wiring table rather than in a hand-written impl: + +```rust +delegate_components! { + HighPrecision { + ScalarTypeProviderComponent: UseType, + } +} + +delegate_components! { + Embedded { + ScalarTypeProviderComponent: UseType, + } +} +``` + +`UseType` says "the type is `f64`", and that is all it says — every abstract type is answered the +same trivial way, so `#[cgp_type]` generates that answer once and a context supplies the type as an +argument to it. The bound on the associated type is carried through and enforced on whatever the context +chooses: wiring `UseType` against a `Copy` scalar is an error reading +`the trait bound String: Copy is not satisfied`. Like every other wiring choice it is +[checked lazily](./check-traits.md), so that error appears where the component is checked or used rather +than on the wiring line itself. + +This is a small win on its own. What it buys is that a context's type choices sit beside its behaviour +choices, in one table, rather than being scattered across `impl` blocks — and that a type can be chosen +by something more interesting than a fixed answer, since `UseType` is just one provider among the +ones a component can be wired to. + +## One type, agreed on by everything that needs it + +The idea compounds as soon as more than one piece of code needs the same type, because they all name the +*same* `Self::Scalar` and the context fixes it once. + +That matters most when the code that needs the type is generic over something else entirely. A shape +calculator works over rectangles, circles, and whatever else, and none of those shapes should have to +carry a scalar type or agree with the others about one: + +```rust +#[cgp_component(ShapeAreaCalculator)] +#[use_type(HasScalarType.Scalar)] +pub trait CanCalculateShapeArea { + fn shape_area(&self, shape: &Shape) -> Scalar; +} +``` + +`Rectangle` declares nothing. The application declares the scalar, every shape interoperates through it, +and switching the application from `UseType` to `UseType` changes the arithmetic for every +shape at once. The application here is a type standing for the program rather than a piece of data — +`struct App;` with no fields is a complete one — which is the shape most CGP code is in. + +The `#[use_type(HasScalarType.Scalar)]` line is what lets the signature say `Scalar` instead of +`::Scalar`. It imports the type and adds the requirement in one line, and it +reads like a `use` for a type because that is what it is. + +## The canonical one: a context's error type + +The abstract type CGP leans on hardest is the error type, and it is the clearest case of code naming +something it refuses to choose: + +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} + +#[cgp_impl(new LoadOrFail)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + return Err(Self::raise_error("empty path".to_owned())); + } + Ok(format!("contents of {path}")) + } +} +``` + +`LoadOrFail` fails, and never learns what failing means in this application. The context decides — +`anyhow::Error`, a domain enum, a plain `String` — and every fallible provider in that context refers to +the same one, so errors compose instead of needing conversion at each boundary. +[Modular error handling](./modular-error-handling.md) is the page for what else follows from that. + +## Two things called `UseType` + +One collision is worth naming before you meet it in a compiler error, because the two are complementary +and easy to conflate. **`UseType` is a provider**: it goes in a wiring table and says what a +context's abstract type is. **`#[use_type(...)]` is an attribute**: it goes on a definition and imports +somebody's abstract type so the code can name it as a bare alias. + +A context uses the first; code that consumes an abstract type uses the second. They appear in the same +program constantly and never in the same position. + +## What it costs + +**It is deferral, not encapsulation.** An abstract type leaves the choice open; it does not hide the +answer. Once a context wires `UseType`, code with that context in hand sees `f64` and can do +anything `f64` allows. If the goal is that callers must *not* know the representation, that is Rust's +module privacy, and an abstract type is the wrong tool for it — a distinction worth being precise about +with anyone arriving from ML modules. + +**A bound on the associated type is the only thing generic code can rely on.** `type Scalar: Copy` means +generic code can copy a scalar and nothing else — no arithmetic, no comparison, unless those bounds are +declared too. Adding one later is a change every context has to satisfy, so the bounds are worth +thinking about when the trait is written. + +**The type is one per context, not one per use.** All the code in a context sharing one `Error` is the +point, and it is also a constraint: a context needing two genuinely different error types needs two +components, or two contexts. + +**And it is another thing that can be left unwired.** A context that never names its error type compiles +until something needs one, at which point the failure is a missing type rather than a missing field, and +looks much the same. [`check_components!`](/docs/reference/macros/check_components) catches it at the +wiring line, like everything else. + +## Where to go next + +[Impl-side dependencies](./impl-side-dependencies.md) puts this page in its place: an abstract type is +the type-shaped version of a requirement stated on the implementation, beside the capability leg and the +value leg. [Implicit arguments](./implicit-arguments.md) is that value leg. + +[Modular error handling](./modular-error-handling.md) develops the canonical case at length — the error +type, how a foreign error becomes it, and what detail it carries, as three separate choices. + +For the constructs, [`#[cgp_type]`](/docs/reference/macros/cgp_type) defines an abstract-type component, +[`UseType`](/docs/reference/providers/use_type) supplies the concrete type in a wiring table, +[`#[use_type]`](/docs/reference/attributes/use_type) imports one into a definition, and +[`HasType`](/docs/reference/components/has_type) is the built-in component the rest is built on. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index 7232010f..4cddd955 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -7,12 +7,161 @@ sidebar_position: 8 Bundling a group of wiring choices into one reusable provider that other contexts adopt as a unit. -:::info +This page answers *how do several contexts share a set of choices without repeating them?* It shows the +bundle, traces a call through it to establish the one fact everything else follows from, and ends on the +rule about checking, which is the only place a bundle behaves unlike anything else. It closes on when to +reach for the heavier alternative instead. -### Not written yet +## A table whose target is not a context -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +A wiring table usually belongs to a context. It does not have to. -::: +Add `new` and the table gets a fresh type of its own: + +```rust +delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } +} +``` + +`GeometryComponents` is an **aggregate provider**: a zero-sized type whose entire content is that table. +Nothing constructs it, it holds no data, and it does not stand for an application. It is a name for a +group of decisions, so that the decisions can be adopted together. + +A context then takes the whole group in one line: + +```rust +delegate_components! { + Rectangle { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: GeometryComponents, + } +} +``` + +`Rectangle` now has both capabilities, and the choices behind them live in one place. Change the bundle +and every context using it changes with it. + +## The context stays the context + +Everything else on this page follows from one fact, and tracing a call is the quickest way to establish +it. When `rectangle.area()` resolves: + +- `Rectangle` gets the capability because it implements the provider trait *for itself*; +- it implements that because its table sends the component to `GeometryComponents`; +- and `GeometryComponents` implements it because *its* table sends the component to `RectangleArea`. + +At every step the context is `Rectangle`. `GeometryComponents` only ever appears as the thing being +delegated to. So when `RectangleArea` reads a `width`, it reads it from `Rectangle` — the bundle has no +`width`, is never asked for one, and would not be consulted if it had one. + +That is what makes a bundle a *provider* rather than a context: it is something delegated **to**, never +something used **as**. Bundles nest for the same reason — a table entry may name another table, and +resolution walks each in turn while the context argument stays fixed on the real context at the end of +the chain. + +## Checking a bundle asks the wrong question + +There is one place a bundle behaves unlike anything else, and it is worth knowing before you meet it. + +**Never wire a bundle with the fused +[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components).** That macro +derives a check asking whether the target can *use* each component as a context. For a bundle that is a +question about a role it never plays, so the answer carries no information — and which answer comes back +depends on what is inside: + +- If the bundled providers need nothing from their context, they implement the capability for *every* + context, the bundle included. The check passes. It has proved nothing, and it looks like it has. +- If a bundled provider needs a field or a type, the check fails, reporting that `GeometryComponents` + does not have a `width` — blaming the bundle for something the real context would have supplied. + +The silent case is the dangerous one. Wire a bundle with plain +[`delegate_components!`](/docs/reference/macros/delegate_components) and let it be verified where the +question means something. + +## Verifying one properly + +A bundle is checked through a context that uses it. Checking `Rectangle` walks the whole chain — through +the bundle's table, down to `RectangleArea`'s requirements, against `Rectangle`'s fields — so a gap +several bundles deep still surfaces: + +```rust +check_components! { + Rectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } +} +``` + +When the bundle itself needs pinning down — usually to find which layer of a nested stack is broken — +the [`#[check_providers]`](/docs/reference/macros/check_components) form asserts the provider-side +question instead, naming the bundle *for a concrete context*: + +```rust +check_components! { + #[check_providers( + RectangleArea, + GeometryComponents, + )] + Rectangle { + AreaCalculatorComponent, + } +} +``` + +Both routes go through a real context. Neither treats the bundle as one. + +## When a namespace is the better tool + +A bundle and a [namespace](./namespaces.md) both package reusable wiring, and they differ in how a +context takes it on. + +A context adopts a bundle by **delegating named components to it** — `[A, B]: TheBundle` — so the +context spells out which components come from where. That is direct, obvious to read, and it scales +linearly: twenty components from a bundle means twenty names in the brackets. + +A context adopts a namespace by **joining it**, after which everything it does not wire itself falls +through, and a direct entry overrides just that key. That is what you want once the count is large or +the defaults should be inherited and selectively replaced. + +Reach for a bundle when the group is small and you want the delegation visible. Reach for a namespace +when the table has outgrown reading, or when a library is publishing defaults for applications to +customize. + +## What it costs + +**It adds a hop.** Finding what answers a capability now means reading two tables instead of one, and +nested bundles mean more. The wiring is still explicit and still greppable, and it is one more step +between the call and the code. + +**It pays only when the repetition is real.** A bundle used by one context is a table split in two for +nothing. The threshold is a second context wanting the same group, not the anticipation of one. + +**It is the construct whose checking rule is a genuine trap**, per the section above, and the failure +mode is a check that passes. Nothing in the code marks a bundle as different from a context — both are +`delegate_components!` on a type — so the distinction has to be held by the person writing it. + +**And the type name carries no clue.** `GeometryComponents` is a struct like any other; only its usage +says it is a bundle. Naming the group rather than a thing — `…Components` — is the convention that keeps +it legible. + +## Where to go next + +[Namespaces](./namespaces.md) is the heavier sibling, and the one to read if the reason you are here is +a table that has grown too long. [Consumer and provider traits](./consumer-and-provider-traits.md) is +where the provider-versus-context distinction this page rests on comes from, and +[Checking your wiring](./check-traits.md) covers both check forms in full. + +For the constructs, [`delegate_components!`](/docs/reference/macros/delegate_components) defines and +consumes a bundle through its `new` keyword and its array-key form, and +[`check_components!`](/docs/reference/macros/check_components) carries `#[check_providers]`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index 7bd35a2d..f363698b 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -8,12 +8,218 @@ sidebar_position: 6 Why a wiring mistake still compiles, and how a compile-time assertion turns the resulting error into one that names the real cause. -:::info +This page answers *why did my mistake not fail where I made it?* It follows one broken context through +three stages — unchecked, checked, and checked through the error toolchain — quoting what the compiler +actually reports at each. It closes on what checking does not fix, which is the honest version of CGP's +most-cited cost. -### Not written yet +## A context can be wrong and still compile -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +Wiring records a choice. It does not verify one. -::: +Here is an application wired to a provider that records outgoing email, and an application that has +nowhere to record it: + +```rust +#[cgp_impl(new RecordEmails)] +impl EmailSender { + fn send_email(&self, #[implicit] sent_emails: &RefCell>, to: &str, body: &str) { + sent_emails.borrow_mut().push(format!("{to}: {body}")); + } +} + +#[derive(HasField)] +pub struct BrokenApp { + pub smtp_server: String, +} + +delegate_components! { BrokenApp { EmailSenderComponent: RecordEmails } } +``` + +`RecordEmails` needs a `sent_emails` field. `BrokenApp` has a `smtp_server`. **This compiles**, and it +is meant to: the table stores "this key points to this provider" as a type-level fact, and nothing has +asked yet whether the provider's own requirements hold for this particular context. + +That laziness is not an oversight. It is what lets a provider be written once against every possible +context, lets a bundle of wiring be reused by applications the bundle has never heard of, and lets a +table be assembled from pieces that never meet. Checking each entry as it was written would mean every +entry knowing its final context, which is the coupling the whole design exists to avoid. + +The price is that a context can look finished and be broken. + +## Where the failure surfaces instead + +The question gets asked the first time something uses the capability, which may be in another module, +another crate, or a test somebody runs next week. And the answer arrives in a form that does not name +the problem: + +```text +error[E0599]: the method `send_email` exists for reference `&BrokenApp`, + but its trait bounds were not satisfied + | + | pub struct BrokenApp { pub smtp_server: String } + | -------------------- doesn't satisfy `BrokenApp: CanSendEmail` + | or `BrokenApp: EmailSender` + | +note: the following trait bounds were not satisfied: + `BrokenApp: EmailSender` +``` + +Read it closely and it says only that the capability is unavailable, restated twice. The word +`sent_emails` does not appear. Neither does anything about a field. The compiler answered the question +it was asked — *does this type have this method?* — and the reasoning that produced "no" was discarded +on the way out. + +This is the single worst experience CGP offers a newcomer, and it is worth being blunt that it is what +a mis-wire looks like by default. + +## Asking the question at a line you chose + +A **check** forces the same question early, at the wiring, where you can see it. It is not a new +mechanism — the plain-Rust form is a trait that demands something and an impl with nothing in it: + +```rust +trait CanUseApp: CanSendEmail {} +impl CanUseApp for App {} +``` + +The impl has nothing to prove on its own, so it compiles exactly when `App: CanSendEmail` holds and +fails otherwise. Put it beside the table and a latent gap becomes an error on a known line. + +[`check_components!`](/docs/reference/macros/check_components) writes that for you, from a list of the +components to verify: + +```rust +check_components! { + BrokenApp { + EmailSenderComponent, + } +} +``` + +But the important part is not the convenience. A check asserts something *stronger* than the consumer +trait, and that is what changes the error. Asking "does `BrokenApp` implement `CanSendEmail`?" gets the +answer above. Asking "can `BrokenApp` use this component?" makes the compiler evaluate the provider's +actual requirements and report the one that failed: + +```text +error[E0277]: the trait bound `BrokenApp: CanUseComponent` + is not satisfied + | +help: the trait `HasField>>>>>` + is not implemented for `BrokenApp` + but trait `HasField>>>>>` + is implemented for it + | +note: required for `RecordEmails` to implement + `IsProviderFor` +``` + +The cause is in there now. A field is missing, one *is* present, and the provider that wanted it is +named. Two things still stand between that and a usable message: the field names are spelled as +type-level character lists — `sent_emails` and `smtp_server`, one character per layer — and the headline +is about a trait nobody wrote. + +## Reading it through the toolchain + +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) runs in place of `cargo check` and +reshapes the classes it recognizes. On the same code: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanSendEmail` is not implemented + for context `BrokenApp` + | + = note: root cause: [CGP-E106] missing field `sent_emails` on `BrokenApp` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanSendEmail` for context `BrokenApp` + └─ [CGP-E102] provider trait impl `EmailSender` with context `BrokenApp` + for provider `RecordEmails` + └─ [CGP-E106] missing field `sent_emails` on `BrokenApp` +``` + +Missing field `sent_emails` on `BrokenApp`, and the path that wanted it. That is the mistake, in the +words you would use to describe it. + +The tool does more than reformat: for the worst class it turns on the compiler's next-generation trait +solver to recover a cause the default solver discards entirely, which is why the first error on this +page had nothing to reshape. It is a `v0.1.0-alpha`, it covers the core wiring errors rather than every +class, and some — orphan-rule failures among them — still pass through as the compiler wrote them. +Dramatically better and actively improving, not solved. + +## Checking a stack one layer at a time + +When providers are built from other providers, checking the context tells you *something* is broken and +not which layer. A variant of the check asserts against each provider rather than against the context: + +```rust +check_components! { + #[check_providers( + RectangleArea, + ScaledArea, + )] + App { + AreaCalculatorComponent, + } +} +``` + +Each provider is now verified on its own line. A requirement missing from the inner `RectangleArea` +fails on both lines, since the outer one needs it too; one missing only from the wrapper fails on the +wrapper alone. The difference between those two shapes is how you find the layer at fault, and it is the +practical tool for debugging a [higher-order provider](./higher-order-providers.md). + +## What to check, and when to fuse it + +The rule that does not bend is that a context's wiring is checked **somehow**. Which macro does it +scales with how complicated the wiring is. + +For a starter context, or a table of plain `Component: Provider` entries, +[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) does both at +once, so the check cannot be forgotten and cannot drift from the table. Its reach stops at that basic +form: it cannot derive checks for per-type dispatch, for namespaced wiring, or for individual provider +layers, because those need parameters or provider names it has no way to infer. + +For anything past that, keep the two apart. A standalone check is where concrete parameters for a +generic component go, where `#[check_providers]` goes, and where opened or namespaced wiring is +verified. + +One case is not a matter of taste: **never fuse the check onto a +[bundle of wiring](./aggregate-providers.md)**. A bundle is a provider other contexts delegate to, not a +context, so a context-side check on it asks a question it was never meant to answer — and gets an answer +that means nothing either way. It passes vacuously when the bundled providers need nothing from their +context, and fails blaming the bundle when any of them does. Verify a bundle through a context that +delegates to it. + +## What it costs + +**A check is something you write.** Nothing generates it from the table unless you fuse the two, so a +component nobody listed is a component nobody verified. In practice the discipline is to add the check +when the context is created, not when it breaks. + +**It moves the error; it does not shrink it.** The output above is better because it names the cause, +not because it is short. A context wired wrong in several places reports several failures, and one deep +mistake reaching many providers can report at each of them. + +**A check verifies wiring, not everything.** Some of what a provider needs is an ordinary Rust trait +rather than a CGP component, and a bound like `Value: Display` failing looks like any other unsatisfied +bound. There is nothing CGP-specific to route it through. + +**And the raw diagnostics remain verbose** for anyone not running the toolchain, which is why this page +quotes all three stages rather than only the last. A reader who meets stage one with no idea stages two +and three exist is the reader CGP loses. + +## Where to go next + +[Impl-side dependencies](./impl-side-dependencies.md) is why the requirement was hidden in the first +place — the design decision this page pays for. [Higher-order providers](./higher-order-providers.md) is +where per-layer checking earns its keep, and [Aggregate providers](./aggregate-providers.md) is the case +where the context-side check is the wrong one. + +For the constructs, [`check_components!`](/docs/reference/macros/check_components) carries every form +including `#[check_providers]` and per-component parameters, and +[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) is the fused +version for basic wiring. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index df3699ae..6fbee863 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -8,12 +8,122 @@ sidebar_position: 15 Routing each field of a record, or the current variant of an enum, to the handler responsible for it. -:::info +This page answers *what actually runs the per-variant and per-field handlers?* It is the layer that +turns [extensible records](./extensible-records.md) and +[extensible variants](./extensible-variants.md) into working code, and it assumes both. It covers the +two directions, the guarantee each carries, and the shortcut for the common case. It closes on the costs, +including the one piece of ceremony that appears once the data is recursive. -### Not written yet +## Two directions, one idea -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +The extensible-data machinery can take an enum apart one variant at a time and can assemble a record one +field at a time. Neither decides *what to do* with each piece. Dispatching is that decision: a +type-level list of handlers, one per element, run as an ordinary +[handler provider](./handlers.md). -::: +It runs in two directions, and they are mirror images. + +**Matching** consumes a sum. The value is converted into its extractor, and the handlers are tried in +turn until one matches — so the list stops at the first success. **Building** produces a product. The +builder starts empty, and every handler runs, each setting one field — so the list runs to the end. + +Both come out as `Computer` or `Handler` providers, which is the point: a dispatcher goes anywhere a +computation goes. It can be wired to a context, nested inside another dispatcher to handle a group of +variants with a sub-matcher, or chained with other combinators. + +## Matching, and why it is exhaustive + +The matcher is a chain of attempts, sequenced by the ok monad from +[monadic handlers](./monadic-handlers.md): each step returns success or a remainder, the chain +short-circuits on the first success, and a miss threads the narrowed remainder forward. + +Wiring it means naming a handler per payload type, plus an entry routing the enum itself to the matcher: + +```rust +delegate_components! { + App { + ComputerComponent: UseInputDelegate< + new AreaComponents { + Shape: MatchWithValueHandlers, + Circle: CircleArea, + Rectangle: RectangleArea, + } + >, + } +} +``` + +`app.compute(code, shape)` now reaches `CircleArea` or `RectangleArea` according to the variant in hand, +and no code anywhere contains a `match` over `Shape`. + +Exhaustiveness survives the indirection, for the reason +[extensible variants](./extensible-variants.md) gives: each failed attempt rules out one variant in the +type, so after the last handler the remainder is uninhabited and is discharged by a `match` with no +arms. Add a variant without a handler and the remainder becomes inhabited again, so the code stops +compiling. The dispatcher proves it covered everything. + +## Building, and why it is complete + +The mirror image applies to a record. The builder threads a partial record through the handler list, +each one computing and setting a field, with later handlers able to read fields already set. At the end +the record is finalized into the concrete struct. + +The guarantee is the mirror image too: finalizing is available only when every field is present, so a +builder missing a handler cannot finalize and does not compile. A matcher proves it covered every +variant; a builder proves it filled every field. + +This is the machinery under the [extensible builder](./extensible-records.md) — the dispatcher is what +runs each subsystem's provider and merges the outputs. + +## The shortcut for the common case + +Much of the time the per-variant logic is an ordinary Rust trait with one implementation per payload +type, and setting up a dispatcher by hand for that is disproportionate. +`#[cgp_auto_dispatch]` generates the wiring instead: + +```rust +#[cgp_auto_dispatch] +pub trait CanDescribe { + fn describe(&self) -> String; +} +``` + +Implement `CanDescribe` for `Circle` and for `Rectangle`, and any enum whose variants all implement it +gets it too — `shape.describe()` works with no wiring, no combinator named, and no `match`. It is the +form to reach for first, and the rest of this page is what it is doing underneath. + +## What it costs + +**A recursive shape needs an extra hop written by hand.** The table above names the matcher directly, +which works because a `Shape` never contains another `Shape`. When a variant's payload *is* the enum +again — an expression language, a tree — the matcher dispatches back through the same component, and a +thin wrapper provider has to sit between the enum's entry and the matcher to break the resolution cycle. +It is ceremony with no conceptual content, and it is the piece of a hand-wired dispatcher most likely to +puzzle a reader. + +**A missing handler reports as a shape, not as a name.** The failure is an unsatisfiable bound over a +partial-variant or partial-record type, which is accurate about what is missing and does not say +"`Rectangle` has no handler". + +**There is one hop per element.** Each variant tried is a resolution step, and the whole chain is +resolved at compile time — so this costs compile time rather than run time, and a wide enum +dispatched at many types is somewhere that cost shows. + +**And a `match` is still usually right.** Dispatching pays when the shape is not known where the logic is +written, or when handlers must be contributed independently. For a closed enum handled in one place, the +language's own construct is clearer and free. + +## Where to go next + +[Extensible variants](./extensible-variants.md) and [extensible records](./extensible-records.md) are +the two halves this operates on, and both are worth reading first. +[Handlers](./handlers.md) is the interface every dispatcher and every per-element handler speaks, and +[monadic handlers](./monadic-handlers.md) is the chaining the matcher is built from. + +For the constructs, [the dispatch combinators](/docs/reference/providers/dispatch_combinators) is the +catalogue of matchers, builders, and per-element adapters, and +[`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch) is the shortcut above. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index c3bd7de6..00630c0b 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -7,12 +7,132 @@ sidebar_position: 13 Building and reading a struct through the names of its fields, without naming the struct. -:::info +This page answers *how does code assemble a struct it does not know the type of?* It shows what a +struct becomes when its shape is a type, how a value is built one field at a time with the compiler +tracking what is still missing, and the pattern that follows — independent pieces of a program each +contributing part of a whole. It closes on the opt-in requirement, which is the honest limit of all of +this. -### Not written yet +## What a closed struct cannot do -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +A Rust struct is closed against incremental construction. A struct literal names the concrete type and +supplies every field at once, so building one is something a single place has to do — and that place +grows a line for every subsystem the program acquires: -::: +```rust +let app = App { + database: connect_to_database()?, + http_client: build_http_client()?, + metrics: start_metrics()?, + // …and every future subsystem edits this same expression +}; +``` + +Everything about that is fine until the subsystems want to be independent of each other and of `App`. +A database module that could build its own piece without knowing what it is a piece *of* would be +reusable across applications; written this way it cannot be, because the only thing that can name a +field of `App` is code that names `App`. + +## A struct as a list of named fields + +The move is to give the shape a type. `#[derive(CgpData)]` gives a struct a description of itself that +generic code can read: + +```rust +#[derive(CgpData)] +pub struct DatabaseClient { + pub url: String, + pub pool_size: u32, +} +``` + +Its shape is now available as a type-level list — one entry per field, each pairing the field's name +with the field's type: + +```rust +Product![Field, Field] +``` + +`Symbol!("url")` is the field name lifted into a type, which is what makes matching *by name* something +the trait system can do. Nothing here is inspected at run time; the list exists during compilation and +is gone afterwards. This is the same field-name-as-type idea behind an +[implicit argument](./implicit-arguments.md), scaled from one field to a whole struct. + +## Built one field at a time, checked all the way + +With the shape available, a value can be assembled by parts that never meet. Building goes through a +**partial record** — a companion type carrying, per field, whether that field is present yet: + +```rust +let app: App = App::builder() + .build_from(database) + .build_from(http) + .finalize_build(); +``` + +`builder()` produces the partial record with every field absent. Each `build_from` merges a smaller +struct's fields into it, matching them by name and flipping each from absent to present. The types +change at every step, tracking what has been filled in. + +That tracking is the whole safety argument. `finalize_build` exists **only** for the configuration with +every field present, so finalizing early is not a runtime panic or a `None` — it does not compile: + +```rust +// `http_timeout` has never been set, so there is no `finalize_build` to call. +let app: App = App::builder() + .build_from(DatabaseConfig { database: "postgres://…".to_owned() }) + .finalize_build(); +``` + +And because presence is tracked per field rather than by position, the order the pieces arrive in does +not matter. + +## The pattern this is for + +What the machinery buys is the **extensible builder**: each subsystem is a provider producing its own +small struct, knowing nothing about the target or about its siblings, and a dispatcher runs them all and +merges the outputs into the whole. + +The list of contributors is then wiring, so swapping a subsystem is a line, and a second application +built from a different mix of the same providers is another table. What guarantees the mix is complete +is the same thing as above — if the providers between them do not supply every field, the build does not +finalize and the code does not compile. + +The dispatcher is one of the [dispatch combinators](./dispatching.md), which is where the general form +of "run a handler per field" lives. + +## What it costs + +**Only types that opted in.** All of this works on a struct that derives the shape. A struct from +another crate that has not is invisible to it — which is the honest difference between this and runtime +reflection, and the thing to say first when someone reads "generic over any type's structure". + +**Fields match by name and type, with nothing checking intent.** Two subsystems that both produce a +`timeout: u32` are producing the same field as far as merging is concerned. That is what makes the +decoupling work, and it means a rename in one place silently stops matching in another. + +**The error messages are the worst in CGP.** A missing field surfaces as an unsatisfiable bound over a +partial record whose type spells out every field and its presence marker. It is accurate, it is long, +and there is no version of it that reads like "you forgot `http_timeout`" without the toolchain's help. + +**And it is a lot of machinery for a constructor.** An application assembled in one place, by code that +is allowed to know the type, should be assembled with a struct literal. This earns its keep when the +contributors must not know the whole — a plugin set, a framework building a user's type, several +applications sharing subsystems. + +## Where to go next + +[Extensible variants](./extensible-variants.md) is the dual: an enum as a sum of named variants, with +the same tracking used for exhaustiveness instead of completeness. [Dispatching](./dispatching.md) is +what runs a handler per field and assembles the result, and is the page that makes the builder pattern +above concrete. + +For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) is the umbrella +derive, [`HasFields`](/docs/reference/traits/has_fields) is the whole-shape view, +[`HasBuilder`](/docs/reference/traits/has_builder) is the builder family, and +[`Field`](/docs/reference/types/field) and [`Symbol!`](/docs/reference/macros/symbol) are the pieces a +shape is made of. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 9a5b46b8..a8c9cbd9 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -8,12 +8,142 @@ sidebar_position: 14 Constructing and matching an enum through the names of its variants, with exhaustiveness still checked by the compiler. -:::info +This page answers *how does code handle an enum whose variants it does not know?* It is the dual of +[extensible records](./extensible-records.md) and assumes it. It shows the shape of an enum as a type, +the trick that keeps exhaustiveness checked without a wildcard, and the conversions between enums that +share variants. It closes on the one restriction the derive imposes. -### Not written yet +## The problem a `match` bakes in -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +A concrete `enum` plus a `match` puts the full set of variants into every function that consumes it. Add +a variant and every `match` has to change; that is Rust's exhaustiveness check doing its job, and it is +usually what you want. -::: +It stops being what you want at exactly two moments. When new variants should be addable **without +editing the code that handles the others** — a plugin adding a message kind, a downstream crate +extending an expression language. And when a variant is defined **upstream**, where handling it means +forking rather than extending. + +This is the [expression problem](https://en.wikipedia.org/wiki/Expression_problem), and the usual +trade is that you can add variants easily or add operations easily, never both. Extensible variants +decouple each variant's handling from the enum itself so that both are additions. + +## An enum as a list of named variants + +The move is the same as for a record: give the shape a type. Where a record is a *product* of named +fields, an enum is a *sum* of named variants: + +```rust +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +```rust +Sum![Field, Field] +``` + +Each entry pairs the variant's name, lifted into a type, with its payload. Generic code can now be +written against "an enum containing a `Circle` variant" rather than against `Shape`. + +## Exhaustiveness without a wildcard + +Taking a value apart runs through a **partial variant**, and this is where the design earns its keep. + +The value is first converted into a form in which every variant is still possible. Then each variant is +tried in turn: if the value is that variant, its payload comes out; if not, what comes back is a +*remainder* — the same value, with that one variant ruled out **in the type**. + +Each miss therefore narrows the type. After every variant has been tried, the remainder is a type that +rules out everything, and a type that rules out everything is uninhabited: a value that cannot exist. +The final step discharges it with a `match` that has no arms, which is sound precisely because there is +nothing to handle. No wildcard arm, no `unreachable!()`. + +And the guarantee is the one a concrete `match` gives. Add a variant to the enum without handling it and +the final remainder becomes inhabited again, so the code stops compiling until the new variant is +covered — recovered for generic code that never named the enum. + +## One handler, many enums + +Put together, a per-variant handler set is written once and applied to any enum whose variants it +covers: + +```rust +#[cgp_computer] +pub fn field_to_string(Field { value, .. }: Field) -> String +where + Value: Display, +{ + value.to_string() +} + +delegate_components! { + App { + ComputerComponent: MatchWithFieldHandlers, + } +} +``` + +`App` can now stringify a two-variant `Reading` and a three-variant `ExtendedReading` through the same +wiring, with no arm added anywhere — because the handler is written against a variant, not against an +enum. That is the **extensible visitor**: the logic for each variant lives on its own, and a dispatcher +routes a value to whichever one matches. [Dispatching](./dispatching.md) is the page for the dispatcher +itself. + +## Enums that share variants convert for free + +Because variants are matched by name, two enums with overlapping variants interconvert with no +hand-written conversion. + +**Widening always succeeds** — every variant of the narrow enum has a home in the wide one: + +```rust +let wide: ExtendedReading = narrow.upcast(PhantomData::); +``` + +**Narrowing may not**, so it returns a `Result`, with the failure carrying a remainder that can be tried +against another candidate: + +```rust +let narrow: Result = wide.downcast(PhantomData::); +``` + +Widening is also how a provider constructs a value using only the variants it knows about: build a small +local enum, lift it into the full one. That is the variant-side counterpart of reading a field through a +getter — code touching part of a shape without naming the whole. + +## What it costs + +**One unnamed field per variant.** A derivable enum must be a sum of products: each variant holds +exactly one unnamed payload. A richer variant wraps its data in a dedicated struct — which is why the +example above is `Circle(Circle)` rather than `Circle { radius: u64 }`. It is a real constraint on how +the enum is written, and it is the first thing anyone hits. + +**Only types that opted in**, as with records. An enum from a crate that has not derived the shape is +invisible to all of this. + +**The errors are long, and this is where they are longest.** An unhandled variant surfaces as a bound on +a partial-variant type spelling out every variant and its presence marker. It is the accurate report of +"you did not cover everything", and it does not read like one. + +**And a closed enum with fixed operations should stay one.** A `match` is clearer, faster to read, and +free. This pays when the variant set is genuinely open, or when independent modules must each contribute +one — not when an enum merely has several variants. + +## Where to go next + +[Extensible records](./extensible-records.md) is the other half, and worth reading first if the shape +type above was unfamiliar. [Dispatching](./dispatching.md) is the machinery that runs a handler per +variant, and [Type-level DSLs](./type-level-dsls.md) is the largest thing this pattern builds — a +language whose terms are types and whose interpreter is the trait system. + +For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) is the umbrella +derive, [`ExtractField`](/docs/reference/traits/extract_field) is the extractor family behind the +narrowing, [`FromVariant`](/docs/reference/traits/from_variant) constructs a variant generically, and +[the casts](/docs/reference/traits/cast) are `CanUpcast` and `CanDowncast`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 0964f97a..53e74080 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -8,12 +8,170 @@ sidebar_position: 11 The family of computation components, and the three axes — synchronous or async, fallible or not, taking an input or not — that tell them apart. -:::info +This page answers *why does CGP ship a dozen computation components instead of one?* It gives the shape +they share, the three axes that separate them, the promotion that means you only ever write the +simplest one, and how a pipeline becomes a wiring entry. It closes on when a plain function is the +better answer. -### Not written yet +## Computation as something a context decides -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +Most CGP components are capabilities an application has: send email, query a user, load a file. The +handler family is for a different thing — a *computation* the application performs on a value, where +the interesting question is not "can it" but "which one, and composed how". -::: +Everything in the family shares one shape: + +> given a context, a `Code` tag, and an `Input`, produce an `Output`. + +The `Code` is a phantom type carrying no data. Its job is to let one context host many different +computations, each keyed by a distinct tag, so wiring can dispatch on it. The `Output` is an +*associated* type rather than a parameter, so the provider decides what a given `Code` and `Input` +produce and downstream wiring reads that decision back. + +That is the whole model. The family exists because computations differ along a few axes, and forcing +every one into the most general signature would make a pure function claim capabilities it does not +have. + +## Three axes, and the names that encode them + +**Synchronous or asynchronous.** A synchronous member returns immediately; an asynchronous one returns +a future and carries `Async` in its name — `AsyncComputer` beside `Computer`. + +**Infallible or fallible.** A fallible member returns a `Result` against the context's +[abstract error type](./modular-error-handling.md), and carries `Try` — `TryComputer` beside `Computer`. + +**Owned or borrowed input.** A `*Ref` variant takes `&Input` where the base takes `Input`, for a +computation that only reads its argument. + +Cross those and you get the members that are documented separately: +[`Computer`](/docs/reference/components/computer) is the pure synchronous corner, +[`TryComputer`](/docs/reference/components/try_computer) the fallible synchronous one, and +[`Handler`](/docs/reference/components/handler) — async *and* fallible — the general workhorse, which is +why it needs no qualifier. [`Producer`](/docs/reference/components/producer) sits slightly apart: a +computation with no input at all, producing a value from the context and a tag. + +The point of the spread is that a provider declares exactly the capabilities it has. A function adding +two numbers is a `Computer`, and nothing about it should mention futures or errors. + +## Write the weakest one; the rest come free + +Which raises the obvious objection: if wiring wants a `Handler` and you wrote a `Computer`, have you +picked wrong? No — the inclusions between the axes are real (an infallible computation is a fallible one +that never fails, a synchronous one is an async one that never awaits) and CGP encodes each as a +combinator that lifts a provider from one member into another. + +The practical result is that one definition answers the whole family: + +```rust +#[cgp_computer] +fn add(a: u64, b: u64) -> u64 { + a + b +} +``` + +`Add` is now callable as `compute`, `try_compute`, `compute_async`, and `handle`, plus their +by-reference forms. A body that returns a `Result` promotes the same way, with its error path surfacing +through the fallible members: + +```rust +#[cgp_computer] +fn checked_add(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "overflow".to_owned()) +} +``` + +So the rule when writing is simply: **write the weakest member that fits, and let the wiring ask for +whatever it needs.** You do not have to predict which one a caller will want. + +## A pipeline is a wiring entry + +Because every member is an ordinary component, composing computations is composing providers — and the +combinators that do it are [higher-order providers](./higher-order-providers.md), so a whole chain has a +name and lives in a table: + +```rust +delegate_components! { + App { + ComputerComponent: PipeHandlers< + Product![ + Multiply, + Add, + Multiply, + ] + >, + } +} +``` + +`PipeHandlers` runs the stages left to right, threading each output into the next input. Each stage here +reads one field from the context and folds it into the running value, so `app.compute(…, 5)` evaluates +`((5 * foo) + bar) * baz` — and the shape of the computation is a line of wiring rather than a function +body. Changing the order, dropping a stage, or swapping one for another is an edit to a type. + +`ComposeHandlers` nests rather than chains, `ReturnInput` passes a value through, and the `Promote*` +adapters are the lifts from the previous section made explicit. They are catalogued together in +[handler combinators](/docs/reference/providers/handler_combinators). + +## Many computations on one context + +The `Code` tag is what stops a context being limited to one computation per member of the family. Two +tags, two providers, one table: + +```rust +delegate_components! { + App { + open ComputerComponent; + + @ComputerComponent.Doubled.i64: ComputeDoubled, + @ComputerComponent.Negated.i64: ComputeNegated, + } +} +``` + +`App.compute(PhantomData::, 21)` and `App.compute(PhantomData::, 21)` reach different +providers. Dispatch can key on the `Input` type as readily as on the `Code`, which is what +[dispatching](./dispatching.md) over extensible data uses, and what makes a program written as types +interpretable — see [type-level DSLs](./type-level-dsls.md). + +## What it costs + +**The `PhantomData` at every call site.** `app.compute(PhantomData::<()>, input)` is the price of the +tag being a type. For a context with one computation it is pure ceremony, and it is what most makes +handler code look unlike ordinary Rust. + +**The family is a lot of names to hold.** Twelve or so components across three axes, plus the promotion +combinators, is more surface than any other part of CGP. The mitigation is the rule above — write the +weakest member and ignore the rest — but reading someone else's handler wiring means knowing which +member each name belongs to. + +**A pipeline in a type is harder to debug than a function body.** There is no line to step through and +no place to add a print. A wrong stage shows up as a type mismatch between two providers, phrased in +terms of an `Output` associated type, and localizing it means the per-layer checks from +[checking your wiring](./check-traits.md). + +**And most computations should stay functions.** This family earns its keep when the *steps* need to be +chosen by wiring — when different contexts run different pipelines, or a program is data. A computation +with one implementation is a function, and [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is how to write +one that still reads its inputs from a context. + +## Where to go next + +[Monadic handlers](./monadic-handlers.md) is the next thing a pipeline needs: what happens when a stage +produces a result the chain should stop on. [Dispatching](./dispatching.md) is the family applied to the +shape of a record or an enum, and [Type-level DSLs](./type-level-dsls.md) is what it becomes when the +`Code` tag carries a whole program. + +[Higher-order providers](./higher-order-providers.md) is the mechanism the combinators are built from, +and worth reading first if `PipeHandlers` looked like new machinery. + +For the constructs, [`Computer`](/docs/reference/components/computer), +[`TryComputer`](/docs/reference/components/try_computer), +[`Handler`](/docs/reference/components/handler), and +[`Producer`](/docs/reference/components/producer) are the corners; +[`#[cgp_computer]`](/docs/reference/macros/cgp_computer) and +[`#[cgp_producer]`](/docs/reference/macros/cgp_producer) build a provider from a function; and +[handler combinators](/docs/reference/providers/handler_combinators) is the full catalogue. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index 181a9ab9..17f2316e 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -8,12 +8,183 @@ sidebar_position: 7 Providers parameterized by other providers, so one implementation can be expressed in terms of another. -:::info +This page answers *how does one implementation build on another without choosing which one?* It shows +the shape, the one piece of syntax that makes it look strange, and the two things it buys — composition +without a context, and a wrapper that falls back to whatever the context already decided. It closes on +why this is the step most often taken too early. -### Not written yet +## Choosing is not the only thing you can do with a provider -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +Wiring picks one implementation from several. That covers a lot, and it does not cover the case where +what you want is *the same transformation over any of them*. -::: +A scaled area is that case. Scaling knows how to multiply by a factor squared; it does not know how to +compute an area, and there is no reason for it to. The base calculation is not something the wrapper +should choose — it is something the wrapper should take: + +```rust +#[cgp_impl(new ScaledArea)] +#[use_provider(Inner: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale: f64) -> f64 { + let base = Inner::area(self); + base * scale * scale + } +} +``` + +`ScaledArea` is a **higher-order provider**: a provider with another provider as a parameter, bound to +supply part of the work. Wiring `ScaledArea` reads as "compute the rectangle area, then +scale it", and `ScaledArea` reuses the same scaling over a different base: + +```rust +delegate_components! { ScaledRectangle { AreaCalculatorComponent: ScaledArea } } +delegate_components! { ScaledCircle { AreaCalculatorComponent: ScaledArea } } +``` + +This is passing a function to a function, done in types. And because a provider is a name rather than a +value, nesting them costs nothing at runtime — the composition is resolved during compilation and what +executes is a direct call. + +## The extra ``, and the attribute that fills it in + +One detail makes these look stranger than they are, and it is worth meeting deliberately rather than in +an error message. + +A provider trait carries the context as an explicit parameter — that is what the +[trait split](./consumer-and-provider-traits.md) does. So when a wrapper requires its inner provider to +implement the same capability, the requirement has to name that context slot: + +```rust +#[cgp_impl(new ScaledArea)] +impl AreaCalculator +where + Inner: AreaCalculator, +{ + fn area(&self, #[implicit] scale: f64) -> f64 { + Inner::area(self) * scale * scale + } +} +``` + +`AreaCalculator` has no counterpart in the consumer trait a reader has been looking at, so it +arrives as an unexplained argument. [`#[use_provider]`](/docs/reference/attributes/use_provider) exists +to remove it: write `Inner: AreaCalculator` and the attribute supplies the ``, which is the whole +of what it does. That is the version in the first snippet, and it is the one to write. + +What the attribute does *not* do is change the call. `Inner::area(self)` stays as it is — the inner +provider is invoked as an associated function with the context passed explicitly, because that is the +shape the provider trait actually has. It is the one place in a well-written provider where the trait +split is still visible, and trying to make it read as `self.area()` would be calling the context's own +wiring, which is a different thing entirely. + +## Composition without a context to name + +The quiet payoff is that composing two providers costs nothing to declare: + +```rust +pub type ScaledScaledRectangleArea = ScaledArea>; +``` + +A type alias, with no bounds on it at all. Compare what composing two constrained generic functions +normally takes — the composed signature restating both sets of constraints, in Rust as much as in +Haskell. Here the requirements are discharged where a context wires the stack, not where the stack is +written, so a composition is just a name for a shape and can be published, reused, and further wrapped +without accumulating a `where` clause. + +## Falling back to what the context already decided + +A wrapper often wants a default: use whatever the context is already wired to, unless told otherwise. +[`UseContext`](/docs/reference/providers/use_context) is the provider that means exactly that, and a +default parameter makes it the fallback: + +```rust +pub struct SumAreas(pub PhantomData); + +#[cgp_impl(SumAreas)] +#[use_provider(Inner: ShapeAreaCalculator)] +impl ShapeAreaCalculator> { + fn shape_area(&self, shapes: &Vec) -> f64 { + shapes.iter().map(|shape| Inner::shape_area(self, shape)).sum() + } +} +``` + +Written unparameterized in a table, `SumAreas` means `SumAreas`, so summing a collection +asks the context how to measure each element: + +```rust +delegate_components! { + App { + open ShapeAreaCalculatorComponent; + + @ShapeAreaCalculatorComponent.Rectangle: RectangleArea, + @ShapeAreaCalculatorComponent. Vec: SumAreas, + } +} +``` + +Naming an inner provider instead — `SumAreas` — pins that step regardless of what the +context would have said, which is how one entry overrides a nested decision without disturbing the rest +of the table. The default only exists when the provider is declared with an explicit struct; one +declared inline by the attribute has no parameter to default. + +## Not every generic provider is one of these + +A provider with a type parameter is not automatically higher-order, and the distinction is worth +keeping because most generic providers are the other kind: + +```rust +#[cgp_impl(new GetName)] +impl NameGetter +where + Self: HasField, +{ + fn name(&self) -> &str { + self.get_field(PhantomData::) + } +} +``` + +`Tag` here is a field name, used as a key. Nothing is delegated to it, nothing implements a capability +on its behalf, and none of the machinery on this page applies. What makes a provider higher-order is +that a parameter is *bound to a provider trait* and invoked to do part of the work. + +## What it costs + +**It is the step most often taken too early.** A provider that is not wrapping anything has nothing to +gain from a parameter, and adding one buys a type argument at every wiring site, a bound to get right, +and a call form that reads unlike the rest of the code. Reach for this when one implementation should +genuinely be expressed in terms of another — not when it merely could be. + +**A failure names the stack, not the layer.** Checking a context tells you `ScaledArea` +does not work; it does not say which half is at fault. The +[`#[check_providers]`](/docs/reference/macros/check_components) form fixes that by asserting against +each layer separately, and a nested stack is the main reason it exists — but it is another thing to +remember, and without it a deep stack is genuinely hard to debug. + +**Compile-time work grows with depth.** Each layer is another round of trait resolution, and a stack +that is several deep and instantiated at many types is one of the places CGP's compile-time cost is most +visible. + +**And the call form leaks.** `Inner::area(self)` is the one construct here that still reads +inside-out, and no attribute hides it. It is a small tax on every higher-order provider written. + +## Where to go next + +[Aggregate providers](./aggregate-providers.md) is the other thing a provider parameter is confused +with: bundling several wiring choices under one name, which composes tables rather than behaviour. +[Checking your wiring](./check-traits.md) covers the per-layer check this page needs. + +[Handlers](./handlers.md) is where composition of this kind is the whole point — a family of +computation components whose combinators are higher-order providers, chained into pipelines. + +For the constructs, [`#[use_provider]`](/docs/reference/attributes/use_provider) completes the inner +bound, [`UseContext`](/docs/reference/providers/use_context) is the fallback, +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) writes the provider, and +[`delegate_components!`](/docs/reference/macros/delegate_components) carries the `open` statement the +last example uses. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index 99c52e69..b44214f7 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -8,12 +8,270 @@ sidebar_position: 3 Declaring what an implementation needs in the implementation itself, so the requirement never reaches the callers of the interface. -:::info +This page answers *how does an implementation say what it needs, without every caller having to know?* +It starts from a technique already available in ordinary Rust, shows why CGP is built on it, and works +through the three kinds of thing an implementation can ask its context for. It closes on what the +arrangement costs, which is mostly paid in error messages. -### Not written yet +## What a `where` clause costs the callers above it -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +A generic function that needs something says so in its signature, and that is the whole difficulty: -::: +```rust +pub trait HasName { + fn name(&self) -> &str; +} + +pub fn greet(context: &Context) -> String +where + Context: HasName, +{ + format!("Hello, {}!", context.name()) +} +``` + +Nothing is wrong with this until something calls it. A caller that is itself generic cannot satisfy +`Context: HasName` on its own, so it has to demand the same thing from *its* caller: + +```rust +pub fn greet_twice(context: &Context) -> String +where + Context: HasName, +{ + format!("{} {}", greet(context), greet(context)) +} +``` + +`greet_twice` never touches a name. It declares the requirement because the function it calls does, and +the function above `greet_twice` will declare it for the same reason. Add a requirement four layers +down and every layer above grows a bound it has no interest in — which is why a mature generic API +tends to accumulate signatures nobody can read, and why adding a dependency deep in a library is a +change that reaches its users. + +## Moving the requirement onto the implementation + +Rust already has the answer, and most Rust programmers have used it without naming it. Put the logic in +a **blanket implementation** — one `impl` covering every type that meets a bound — and the requirement +moves out of the interface and onto the implementation: + +```rust +pub trait CanGreet { + fn greet(&self) -> String; +} + +impl CanGreet for Context +where + Context: HasName, +{ + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } +} +``` + +`CanGreet` mentions nothing. Any type with a `name` gets `greet` for free, and a caller says only what +it actually uses: + +```rust +pub fn greet_twice(context: &Context) -> String +where + Context: CanGreet, +{ + format!("{} {}", context.greet(), context.greet()) +} +``` + +The requirement did not disappear — the compiler still checks it, at the point where a concrete type +meets the impl. What changed is that it stopped being part of the contract. That is an **impl-side +dependency**: something an implementation needs, stated where the implementation lives rather than +where the interface is declared. + +This is the construct CGP is built out of, which is worth saying plainly, because it makes the +foundation something you already have. If you have used `Itertools` or `StreamExt`, you have used a +blanket impl over every `Iterator` or every `Stream` — that is why a method appears on a type whose +author never wrote it. What CGP adds is not the mechanism but the ability to have more than one of them +and choose between them. + +## Two providers, two sets of requirements, one interface + +The payoff arrives once a capability has more than one implementation, because each one asks for +something different and the interface still says nothing. + +Two ways of sending email need entirely different things from the application. One needs a server +address; the other needs somewhere to record what it would have sent: + +```rust +#[cgp_component(EmailSender)] +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + +#[cgp_impl(new SendViaSmtp)] +#[uses(HasSmtpServer)] +impl EmailSender { + fn send_email(&self, to: &str, body: &str) { + // open a connection to `self.smtp_server()` and send + } +} + +#[cgp_impl(new RecordEmails)] +#[uses(HasSentEmails)] +impl EmailSender { + fn send_email(&self, to: &str, body: &str) { + self.sent_emails().borrow_mut().push(format!("{to}: {body}")); + } +} +``` + +`#[uses(...)]` is how a provider declares a capability it needs. It reads like an import, and that is +the right way to take it: the provider is saying *this code relies on the context being able to do +this*. Underneath it becomes a bound on the implementation, exactly as in the blanket impl above. + +The consequence is worth stating precisely. `CanSendEmail` has no idea that SMTP servers exist. A +function bounded on it accepts both applications, even though they satisfy it for reasons that have +nothing in common: + +```rust +pub fn notify(context: &Context) +where + Context: CanSendEmail, +{ + context.send_email("a@b.c", "hi"); +} +``` + +Both examples here wire a type standing for an application — `App` for production, `TestApp` for a test +harness — rather than a piece of data. That is where most CGP code lives, and it is what makes the +point land: the two applications differ in what they can supply, and the interface between them and +`notify` does not record the difference. + +## The three things an implementation can ask for + +Everything above is one kind of requirement — a capability. There are three, they all work the same +way, and each has a syntax that keeps the bound out of sight. + +**A capability** is what `#[uses]` declares, as above. It covers other CGP capabilities and ordinary +Rust traits alike: `#[uses(AsRef<[u8]>)]` is as valid as `#[uses(HasSmtpServer)]`. + +**A value** is a field the implementation reads, and it is declared by writing it as an argument: + +```rust +#[cgp_impl(new GreetByName)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} +``` + +The `name` argument is not passed by the caller. It is read from a `name` field on the context, the +requirement is generated from the argument's name and type and lands on the implementation, and +`greet()` still takes nothing from the outside. [Implicit arguments](./implicit-arguments.md) develops +this one. + +**A type** is the third, and it is the one that buys the most, because what it displaces is not a +leaked bound but a leaked *parameter*. + +## Type dependencies, and why they need no parameter + +Suppose a job runner should not commit to an error type, a runtime, or a storage backend. The ordinary +way to leave a type open is a generic parameter, and a parameter is an **input**: the caller supplies +it, so it has to appear in the signature. + +```rust +pub fn run_job(store: &S, runtime: &R) -> Result<(), E> +where + E: From + From, + R: Runtime, + S: Store, +{ + // This layer touches none of the three. +} +``` + +This is the leak from the first section, and worse, because a parameter *cannot* be moved onto an impl. +It is part of the interface by construction. Every intermediate function that merely passes a value +along declares all three and repeats their bounds, and adding a fourth open type is a breaking change +for every caller. + +An **abstract type** inverts the direction. Rather than the caller supplying the type, the context +determines it — it is an associated type on a trait the context implements, so an implementation can +name it without anyone choosing it at a call site: + +```rust +#[cgp_component(JobRunner)] +#[use_type(HasErrorType.Error)] +pub trait CanRunJob { + fn run_job(&self) -> Result<(), Error>; +} +``` + +`#[use_type(HasErrorType.Error)]` imports the context's error type and lets the signature name it as a +bare `Error`. The intermediate layer then has nothing to declare at all: + +```rust +#[cgp_fn] +#[uses(CanRunJob)] +#[use_type(HasErrorType.Error)] +pub fn run_jobs(&self) -> Result<(), Error> { + self.run_job()?; + self.run_job() +} +``` + +A parameter is an input and propagates everywhere; an abstract type is an output and propagates +nowhere. That asymmetry is why a CGP codebase can keep accumulating type dependencies without its +signatures growing: **the number of types a context decides can rise freely, because deciding is not +passing.** [Abstract types](./abstract-types.md) is the page for that half. + +One thing to be accurate about: when a capability's own signature names the type, the owning trait does +become part of the contract — `CanRunJob` really does imply `HasErrorType`. But a caller bounding on +`CanRunJob` gets that implication for free, never restates it, and names the type only if it handles +one. Compare `trait CanRunJob`, which forces `` onto every caller and every caller's caller +whether they touch an error or not. The bound is on the implementation; the parameter would be on +everyone. + +## What it costs + +**A hidden requirement is hidden from you too.** The point of all this is that `CanSendEmail` does not +say what its implementations need — which also means reading the interface tells you nothing about what +a context must supply. The answer is in the provider, and finding it means knowing which provider the +context wired. + +**The requirement is checked late.** Nothing verifies that a context can satisfy the provider it named +until something uses the capability, so a context can be wired wrong and still compile. That is +[lazy wiring](./check-traits.md), and it is the source of CGP's least pleasant errors. + +**When it does fail, the error is about a bound you did not write.** A missing `name` field surfaces as +an unsatisfied field bound naming a type-level spelling of the field name, several layers from the line +that caused it. [`check_components!`](/docs/reference/macros/check_components) forces the failure to the +wiring line and names the actual gap, and +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) leads with the root cause for the +classes it recognizes — a `v0.1.0-alpha` covering the core wiring errors rather than all of them. Both +help substantially; neither makes the raw output pleasant. + +**And it is more machinery than a plain function needs.** For a capability with one implementation, the +blanket impl in the second section is the whole of what is useful here, and it is ordinary Rust. +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) writes exactly that from a function, with no component and +no wiring. + +## Where to go next + +The three legs each have a page. [Implicit arguments](./implicit-arguments.md) is the value leg, where a +context field arrives as a function parameter. [Abstract types](./abstract-types.md) is the type leg, +and the one that changes how a codebase's signatures age. + +[Consumer and provider traits](./consumer-and-provider-traits.md) is the other half of what a component +is: this page covers how an implementation states what it needs, and that one covers how a call reaches +the implementation at all. [Checking your wiring](./check-traits.md) takes up the cost above — why the +check is late, and what to do about it. + +For the constructs themselves, [`#[uses]`](/docs/reference/attributes/uses) declares a capability, +[`#[implicit]`](/docs/reference/attributes/implicit) a value, and +[`#[use_type]`](/docs/reference/attributes/use_type) a type; +[`#[blanket_trait]`](/docs/reference/macros/blanket_trait) generates the plain-Rust blanket impl this +page starts from. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index f8bb425e..6670124e 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -7,12 +7,173 @@ sidebar_position: 4 Writing a provider as an ordinary function whose arguments are filled from fields of the context. -:::info +This page answers *how does an implementation get a value out of its context, without that becoming a +thing to learn?* It shows what reading a field costs when spelled out, the argument that replaces it, +and the rules deciding how the value arrives. It closes on where an implicit argument stops working and +a getter is the right tool instead. -### Not written yet +## What reading a field costs, spelled out -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +A provider almost always needs data from its context, and the underlying mechanism is a trait keyed by +the field's name lifted into a type: -::: +```rust +#[cgp_impl(new GreetByName)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) -> String { + let name = self.get_field(PhantomData::); + format!("Hello, {name}!") + } +} +``` + +This works, and everything in it is doing something. `Symbol!("name")` is the field's name as a type, so +one trait can describe every field rather than needing one trait per field. `PhantomData` carries that +type to the call so inference knows which field is meant. The bound is an +[impl-side dependency](./impl-side-dependencies.md), which is why the capability's own trait says +nothing about names. + +It is also four unfamiliar things stacked in front of a one-line function, and a reader meeting them +before they have a reason to care about type-level tags will conclude that CGP *is* that. The value the +provider wants is a `String` called `name`; nothing in the paragraph above is about that. + +## The same provider, written as a function + +An **implicit argument** says the same thing as a parameter: + +```rust +#[cgp_impl(new GreetByName)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} +``` + +The argument is not passed by anyone. `#[implicit]` removes it from the method's public signature, adds +the field requirement to the implementation, and binds the value at the top of the body — so a caller +still writes `app.greet()` with no arguments, and the body reads a plain local. + +Nothing was hidden that was not already hidden. The bound, the tag, and the read are the same three +things; what changed is that the author writes the name of the value they want and the macro derives +the rest from it. Someone who understands functions and arguments can write a complete provider without +meeting a type-level anything, which is why this is the recommended way to read a context field and the +on-ramp most introductions to CGP should use. + +## A capability from a function alone + +Combined with [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), an implicit argument gets you a working CGP +capability with no trait, no provider, and no wiring line: + +```rust +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +Any context with a `width` and a `height` can now call `rectangle_area()`. That is the whole program — +there is no component to define and nothing to choose, because this capability has one implementation +and needs none. It is the smallest useful thing CGP does, and the right place to start a codebase that +may never need more. + +## The declared type decides how the field is read + +The type on the argument says what the body wants, and the macro inserts whatever bridges it to the +field the context stores. Three cases cover nearly everything: + +```rust +#[cgp_fn] +pub fn describe( + &self, + // Owned: read by reference and cloned, so the context keeps its field. + #[implicit] name: String, + // `&str`: backed by a `String` field, borrowed rather than cloned. + #[implicit] title: &str, + // Any other borrow: taken as it stands. + #[implicit] tags: &Vec, +) -> String { + format!("{title} {name} {tags:?}") +} +``` + +The rule of thumb is that the declared type is what the body works with and the conversion is the +macro's problem. Prefer a borrow where the body only reads — `&str` over `String` — since that is free +while an owned argument clones. Further forms exist for options and slices, and they are enumerated on +the [`#[implicit]`](/docs/reference/attributes/implicit) reference page rather than here. + +These are the same rules a getter follows, so learning them once covers both. + +## When a getter trait is still the right thing + +An implicit argument reads from the provider's own `self`. That covers every value a provider wants +from its own context — including one that several providers each read, declared as the same argument in +each — so it is the default, and a getter trait is the exception. + +Three cases fall outside it. The value may live on a **type other than the context**, where there is no +`self` field to read and the requirement is a bound on that other type: + +```rust +#[cgp_impl(new AuthenticateByHeader)] +impl RequestAuthenticator +where + Request: HasAuthHeader, +{ + fn authenticate(&self, request: &Request) -> bool { + request.auth_header().starts_with("Bearer ") + } +} +``` + +`HasAuthHeader` there is a getter on `Request`, not on the application, and no implicit argument can +express that. The accessor may also need to exist as a **named capability** that other code depends on +through `#[uses(...)]` or a supertrait — a name is something you can require, and an argument is not. Or +the getter may carry an **associated type inferred from the field**, so callers stay generic over what +the value actually is. + +Outside those three, prefer the argument. A getter trait declared only so a provider can read a field of +its own context is a trait, an impl, and an import bought for nothing. + +## What it costs + +**The field name is part of the interface, silently.** Renaming a struct field breaks every provider +whose argument was named after it, and the failure surfaces as a missing-field error at whatever site +forces the check rather than at the rename. Nothing in the struct definition marks the coupling. + +**The requirement is invisible at the call site.** `app.greet()` gives no hint that the context must +carry a `name`. That is the point — it is what keeps the requirement off the interface — and it is also +why the answer to "what does this context need?" lives in the providers it wired rather than in the +traits it implements. + +**Matching by name is looser than matching by type.** Two unrelated values with the same name and type +are the same implicit argument as far as the machinery is concerned, so a context that happens to have a +field called `name` satisfies a provider written for something else. In practice that is what makes the +mechanism so cheap; it is still worth knowing that nobody is checking your intent. + +**The clone is real.** An owned argument copies the field on every call. Usually that is nothing, and on +a large value in a hot path it is not — declare a borrow. + +## Where to go next + +[Impl-side dependencies](./impl-side-dependencies.md) is the general idea an implicit argument is one leg +of: a requirement stated on the implementation rather than on the interface. +[Abstract types](./abstract-types.md) is the third leg, where what the implementation needs is a type +rather than a value. + +To write this rather than read about it, the [Hello World tutorial](/docs/tutorials/hello) reaches an +implicit argument within its first few minutes, and the +[Area calculation series](/docs/tutorials/area-calculation/) builds up from plain functions of exactly +this shape. + +For the constructs, [`#[implicit]`](/docs/reference/attributes/implicit) carries the full list of +accepted forms and access rules, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the no-wiring +capability, [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter) is the getter to reach for in +the three cases above, and [`HasField`](/docs/reference/traits/has_field) is the trait underneath all of +them. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 6bf58f18..7d2855ea 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -16,15 +16,6 @@ name of the thing they want. A concept page answers the question neither of thos *why does CGP work this way, and when is it the right thing to reach for?* Each page names the constructs it involves and links to the reference for their exact syntax, rather than repeating it. -:::info - -### Still being written - -The list of ideas below is complete, so nothing is missing from this index — but most of the pages -behind it are placeholders for now, and each one says so when you open it. - -::: - ## Where to start **Read [Bypassing coherence](./coherence.md) first if you want to know why CGP exists.** It explains diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index 85236214..ede9d24b 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -8,12 +8,180 @@ sidebar_position: 10 The error type, how a foreign error becomes it, and what detail it carries: three choices a context makes independently of the code that fails. -:::info +This page answers *how does fallible code avoid committing to an error type?* It separates the three +decisions error handling actually contains, shows a provider that makes none of them, and ends with the +same pattern applied to an application's own error vocabulary. It closes on where the separation stops +paying. -### Not written yet +## Why the error type is the hard one -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +Every fallible function has to return *something*, and generic code has no business deciding what. A +provider parsing a port number does not know whether the application wants `anyhow::Error`, a domain +enum, or a plain string — and hard-coding any of them commits every caller in every application to that +choice. -::: +The usual answers each cost something. A concrete error type in a library is a decision imposed on +users. A generic `` parameter is an input the caller supplies, so it lands in every intermediate +signature along with its bounds, which is the leak [impl-side dependencies](./impl-side-dependencies.md) +describes. Converting by hand at each boundary is the boilerplate error-handling crates exist to remove, +and it comes back the moment the boundary is generic. + +What makes this tractable is noticing that "error handling" is not one decision but three, and that they +are independent: + +- **what the error type is** — a type the context names; +- **how a foreign error becomes it** — `ParseIntError`, `io::Error`, a `String` from a domain rule; +- **what detail is attached** as it propagates. + +CGP makes each of the three a wiring choice, and the code that fails makes none of them. + +## Code that fails without knowing what failing means + +The capability names its error abstractly, and the provider raises into it: + +```rust +#[cgp_component(PortParser)] +#[use_type(HasErrorType.Error)] +pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; +} + +#[cgp_impl(new ParsePortFromStr)] +#[uses(CanRaiseError, CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + let parsed: u32 = raw.parse().map_err(Self::raise_error)?; + + if parsed > u16::MAX as u32 { + return Err(Self::raise_error(format!("port {parsed} out of range"))); + } + + Ok(parsed as u16) + } +} +``` + +`Error` is the context's [abstract type](./abstract-types.md), imported by `#[use_type]`. +`Self::raise_error` turns a concrete failure into it, and the `#[uses]` line declares which failures +this provider raises — two of them, a parse error and a string — as requirements on the implementation, +not on the interface. A caller bounding on `CanParsePort` learns none of it. + +`raise_error` is called on the *type* rather than on a value, because constructing an error is something +the context knows how to do rather than something a particular value does. + +## Three sources, three strategies, one table + +The context supplies the answers, and the second and third decisions are made per source error type: + +```rust +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + PortParserComponent: ParsePortFromStr, + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } +} +``` + +Three lines, three decisions. The error type is `String`. A raised `String` is converted straight +through with `From`. A `ParseIntError` is formatted with `Debug` into a `String` — and then handed back +to the context's own `String` route, which is what makes the two compose rather than each needing to +know the final type. + +That last point is what the per-source dispatch buys. A real application raises a dozen unrelated +failures, and most of them want the same treatment; naming a strategy per source type lets the +interesting ones differ without a match arm anywhere. CGP ships the strategies as ordinary providers — +`RaiseFrom` for a `From` conversion, `DebugError` and `DisplayError` for formatting, `ReturnError` when +the source already is the error type, `RaiseInfallible` for a step that cannot fail — and they stay +generic over whatever error type the context chose. + +## Changing the answer changes nothing else + +Because the decisions are separate, moving to a different error type is a change to the table: + +```rust +delegate_components! { + StrictApp { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + PortParserComponent: ParsePortFromStr, + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } +} +``` + +`ParsePortFromStr` is the same provider, unmodified and un-recompiled in any meaningful sense. It never +named `String`, so nothing in it referred to the thing that changed. Swapping `anyhow` for `eyre`, or a +prototype's `String` for a real domain type, is this edit. + +Concrete backends come as separate crates for the same reason — `cgp-error-anyhow` and its siblings each +supply a type-setting provider and the raisers that go with it, so the dependency on `anyhow` lives in +the wiring rather than in any code that fails. + +## An application's own error vocabulary + +None of this is confined to CGP's built-in components, and the clearest sign of that is defining your +own. A service that wants every failure to carry an HTTP status declares a capability for it: + +```rust +#[cgp_component(HttpErrorRaiser)] +#[use_type(HasErrorType.Error)] +pub trait CanRaiseHttpError { + fn raise_http_error(code: Code, detail: Detail) -> Error; +} +``` + +`ErrUnauthorized` and `ErrNotFound` are empty structs standing for status codes, and a provider per code +builds the concrete error. A handler deep in the request pipeline then writes + +```rust +Self::raise_http_error(ErrUnauthorized, "you must first login") +``` + +and knows neither the status number nor the error type. The two are decided in the table, in the same +place as everything else the application decides — which is the whole pattern, applied to a vocabulary +the built-in components know nothing about. + +## What it costs + +**The imports are not in the prelude, deliberately.** `HasErrorType` and `CanRaiseError` are, but the +wiring keys live under `cgp::core::error` and the strategy providers under `cgp::extra::error`. That is +a real papercut the first time, and it is the price of the error components not being forced on code +that does not use them. + +**Three decisions means three ways to be under-wired.** A context can name an error type and forget a +raiser for a source some provider raises, and it compiles until something raises one. +[`check_components!`](/docs/reference/macros/check_components) is what catches it, as with any other +wiring. + +**The error type is one per context.** Everything in a context agreeing on one `Error` is what lets +errors compose without conversion; it also means a context genuinely needing two unrelated error types +needs two components or two contexts. + +**And it does not decide what a good error is.** CGP makes the type swappable and the construction +routable. Whether your errors carry useful context, whether they are matchable, whether the messages +help — all of that is the same design problem it always was, and none of it is answered by wiring. + +## Where to go next + +[Abstract types](./abstract-types.md) is the mechanism the error type rests on, and worth reading first +if `#[use_type]` above was unfamiliar. [Impl-side dependencies](./impl-side-dependencies.md) is why the +`#[uses(CanRaiseError<…>)]` line does not reach callers, and +[Dispatching](./dispatching.md) is the general form of the per-source routing. + +For the constructs, [`HasErrorType`](/docs/reference/components/has_error_type) is the abstract error +type, [`CanRaiseError`](/docs/reference/components/can_raise_error) covers raising and wrapping, and +[the error providers](/docs/reference/providers/error_providers) is the catalogue of strategies with the +bound each one places on the context. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index 12423dc1..33c46c02 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -8,12 +8,111 @@ sidebar_position: 12 Chaining handlers into a pipeline that stops at the first step producing a result the chain should return. -:::info +This page answers *how does a pipeline handle a step that should end it?* It is short, and it assumes +[handlers](./handlers.md). It shows where plain composition stops working, what a monad supplies that +fixes it, and the three CGP ships. It closes on when this is more machinery than a `?` operator. -### Not written yet +## Where plain composition stops -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +Chaining handlers works by feeding each output into the next input, which is right exactly when every +step always wants to continue. -::: +The moment a step can produce a value meaning *stop, this is the answer*, it is wrong. Take a +computation that can overflow: + +```rust +#[cgp_computer] +pub fn increment(value: u8) -> Result { + value.checked_add(1).ok_or("overflow") +} +``` + +Chaining two of these plainly does not even compile: the first produces a `Result` and the second +wants a `u8`. And forcing the types to line up would be worse than the type error, because the later +steps would run on a value they were never meant to see. + +`Result` is the familiar case, and the shape is more general than `Result`. Any output type carrying two +possibilities — one to carry on with, one to return immediately — has the same problem. + +## What a monad supplies + +A **monad**, in this setting, is a small answer to three questions about an output type: which case +threads forward into the next step, which case short-circuits out as the final result, and how a plain +value is lifted back into the type. Nothing more abstract than that is needed to read this page. + +Given those answers, a list of handlers can be composed so each step runs only on the "continue" branch +of the one before, and a "stop" value flows untouched to the end: + +```rust +PipeMonadic:: +``` + +Starting from `1` this produces `Ok(4)`. Starting from `253` the third step overflows, so the pipeline's +output is `Err("overflow")` and the remaining steps do not run. That is the `?` operator, expressed as a +type. + +## The three CGP ships + +**The err monad** continues on `Ok` and short-circuits on `Err` — the `?`-style early return above, +where the first failure wins. It is the one most pipelines want. + +**The ok monad** is its mirror: it continues on `Err` and stops on `Ok`. That sounds backwards until you +want a chain of attempts where the first *success* ends it — a lookup tried against several sources, a +parser trying alternatives. + +**The identity monad** never short-circuits and threads every value forward, which recovers plain +composition. It exists so that "no short-circuiting" is a choice you make rather than a different +combinator you reach for, and it is what a `Result`-producing chain almost never wants. + +They also stack, so a pipeline over a nested `Result, F>` can short-circuit on the outer +error while threading the inner result. + +## It is still just a provider + +The pipeline that comes out is an ordinary provider for the [handler family](./handlers.md), so it goes +in a table like anything else and nothing downstream knows a monad was involved: + +```rust +delegate_components! { + App { + ComputerComponent: PipeMonadic, + } +} +``` + +The whole construction lives in types — the monad is a zero-sized marker, the handler list is a +type-level list, and the pipeline carries no runtime value — so the only branching at run time is the +branching the logic actually asked for. + +## What it costs + +**It is a word that scares people, for something small.** "Monad" here means the three answers in the +section above and nothing else: no laws to check, no `do` notation, no theory required. It is still a +word that will cost you a reader, and a piece of CGP writing is usually better off describing the +behaviour than naming it. + +**A `?` in a function body is simpler, and usually right.** This pays when the *steps are chosen by +wiring* — when different contexts run different chains, or the chain is assembled from parts that do not +know each other. When the steps are fixed, write a function and use `?`. + +**The type errors are among CGP's worst.** A stage whose output does not match the next stage's input +fails inside the monad machinery, in terms of `Output` associated types and monad traits, and the +message rarely names the stage. Building a long pipeline one stage at a time is the practical defence. + +**And nesting monads compounds that.** A stacked monad over a nested `Result` is expressive and is the +point at which a reader who has followed everything else will stop being able to predict what the +pipeline does. + +## Where to go next + +[Handlers](./handlers.md) is the family this composes, and the page to read first if `PipeMonadic` above +looked like it came from nowhere. [Dispatching](./dispatching.md) is the other big user of the ok monad: +matching an enum variant is a chain of attempts where the first success ends it. + +For the constructs, [monad providers](/docs/reference/providers/monad_providers) carries `PipeMonadic`, +the three markers, and the per-step `BindOk` / `BindErr` forms, and +[the monad traits](/docs/reference/traits/monad) is the layer defining what a monad is here. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index 8fca5fe4..7d5f87f8 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -8,12 +8,208 @@ sidebar_position: 9 Reusable, inheritable wiring tables that keep a context's own table short as the number of components grows. -:::info +This page answers *how does wiring stay readable once there is a lot of it?* It shows what a table +looks like when it has outgrown its usefulness, the routing that fixes it, and the one rule that +decides how a namespace has to be designed — a rule most people discover from a compiler error. It +closes on when the lighter alternative is the better buy. -### Not written yet +## When a table stops being readable -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +Wiring is meant to be the one place a context's choices are visible. That works while the table is +short, and stops working when two contexts want almost the same table: -::: +```rust +delegate_components! { + App { + GreeterComponent: GreetHello, + FarewellComponent: SayGoodbye, + AnnouncerComponent: AnnounceLoudly, + } +} + +delegate_components! { + TestApp { + GreeterComponent: GreetQuietly, + FarewellComponent: SayGoodbye, + AnnouncerComponent: AnnounceLoudly, + } +} +``` + +Two entries out of three are duplicated, and nothing records that they are meant to stay the same. +Scale that to the thirty components a real application accumulates and the interesting difference — +one line — is buried in twenty-nine identical ones, which is the opposite of what the table was for. + +A **namespace** is a table lifted out of any one context and given a name, so that contexts can share +it. + +## Lookups follow a path + +The mechanism that makes sharing work is that a namespace resolves **paths** rather than bare +component names. A component registers itself at a path, and the path is a *route* rather than an +answer: + +```rust +cgp_namespace! { new AppNamespace {} } + +#[cgp_component(Greeter)] +#[prefix(@app.GreeterComponent in AppNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} +``` + +`AppNamespace` now knows that anything asking for this capability should look under +`@app.GreeterComponent`. It does not know what it will find there. A context joins the namespace and +supplies the answer at that path: + +```rust +delegate_components! { + App { + namespace AppNamespace; + + @app.GreeterComponent: GreetHello, + } +} +``` + +The `namespace` line makes everything `App` does not wire itself fall through to `AppNamespace`. +Routing through paths rather than flat keys is also what lets a whole group be redirected at once and +what makes inheritance possible, since a path has structure a name does not. + +On its own this is more machinery for the same result. What it buys arrives next. + +## Binding what is shared, leaving open what varies + +A namespace can also **bind** a path — supply the provider itself, rather than routing to it. That is +what turns it into a set of defaults: + +```rust +cgp_namespace! { + new AppDefaults: AppNamespace { + @app.FarewellComponent: SayGoodbye, + } +} +``` + +`AppDefaults` inherits the routing from `AppNamespace` and answers the farewell path itself. A context +joining it supplies only what is left: + +```rust +delegate_components! { App { namespace AppDefaults; @app.GreeterComponent: GreetHello } } +delegate_components! { TestApp { namespace AppDefaults; @app.GreeterComponent: GreetQuietly } } +``` + +The two contexts now differ by exactly the thing that differs between them. Everything they share is +stated once, in a place that can be published by a library and adopted by applications that library has +never heard of. + +## A bound entry cannot be overridden + +Here is the rule, and it is worth learning from this page rather than from the error: +**once a namespace binds a key, no one downstream can rebind it. Only a path the namespace leaves open +is available to a context.** + +The natural thing to reach for — "the namespace sets this, I want something different" — does not +compile: + +```rust +cgp_namespace! { + new AppDefaults { + GreeterComponent: GreetHello, + } +} + +// error[E0119]: conflicting implementations of trait +// `DelegateComponent` for type `TestApp` +delegate_components! { + TestApp { + namespace AppDefaults; + + GreeterComponent: GreetQuietly, + } +} +``` + +The same rejection catches a child namespace redefining a key it inherits. The reason is coherence +rather than policy: joining a namespace generates an implementation covering *every* key the namespace +answers, and a specific entry for one of those keys overlaps it. The compiler cannot see that you meant +the specific one to win. + +So a namespace is designed around the question *what varies?*, and this is the practical shape: +**bind what every context agrees on, and leave open what any context might need to differ on.** Where a +key varies, do not bind it in the shared namespace at all — inherit and bind it per configuration +instead: + +```rust +cgp_namespace! { new ProductionDefaults: AppDefaults { @app.GreeterComponent: GreetHello } } +cgp_namespace! { new TestDefaults: AppDefaults { @app.GreeterComponent: GreetQuietly } } +``` + +Each child binds the open path rather than overriding a bound one, and a context becomes a single line +naming which configuration it is. + +## Namespaces are how CGP does presets + +There is no separate preset construct, and no `cgp_preset!` to look for. A preset — a curated bundle of +defaults you adopt and then adjust — is exactly the inherit-and-adjust behaviour above, so a namespace +*is* one. + +The same machinery serves a much smaller case. Dispatching a single component per type, with the +`open` statement, is path routing applied to one component on one context: + +```rust +delegate_components! { + App { + open EncoderComponent; + + @EncoderComponent.String: EncodeAsText, + } +} +``` + +`open` roots a route at the bare component name and puts the per-type entries in the context's own +table, with no shared namespace involved. It is the lightweight end of the same mechanism, and it is +what most code uses — which is why [bypassing coherence](./coherence.md) and +[dispatching](./dispatching.md) can use it without mentioning namespaces at all. + +The two do not combine for the same component: once a component is registered behind a namespace +prefix, `open` would root the route at the wrong place, and the full prefixed path is what reaches its +entries. + +## What it costs + +**The design decision comes first, and it is hard to revise.** Which keys a namespace binds and which +it leaves open is fixed by the rule above, and changing your mind means changing the namespace — which +reaches every context that joined it. A bundle of wiring is easier to get wrong here than anywhere else +in CGP, because the mistake is not visible until a context wants to differ. + +**It is another hop, and a less obvious one.** With an +[aggregate provider](./aggregate-providers.md) the context says which components come from the bundle. +With a namespace it says nothing — everything not wired locally falls through — so answering "where +does this capability come from?" means knowing the namespace and its parents. + +**Paths are a second vocabulary.** `@app.GreeterComponent` is a type-level path, and it appears in +error messages spelled out at length. The toolchain resugars it for the classes it recognizes; the raw +form is still what a plain `cargo check` shows. + +**And it pays only at scale.** For three components shared by two contexts, the duplication at the top +of this page is fine and a namespace is not worth its cost. The threshold is a table that has outgrown +reading, or a library publishing defaults for applications to adopt. + +## Where to go next + +[Aggregate providers](./aggregate-providers.md) is the lighter way to package reusable wiring, and the +right one until a table is genuinely long. [Bypassing coherence](./coherence.md) and +[Dispatching](./dispatching.md) both use the `open` form of path routing without needing anything on +this page. + +For the constructs, [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) defines a namespace and +carries the `#[prefix(...)]` registration attribute, +[`delegate_components!`](/docs/reference/macros/delegate_components) carries the `namespace` and `open` +statements, [`RedirectLookup`](/docs/reference/providers/redirect_lookup) is the provider doing the +routing, and [`Path!`](/docs/reference/macros/path) is the path type underneath. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index 3cabe9e8..d4be05ea 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -8,12 +8,136 @@ sidebar_position: 17 Restoring the guarantee an async trait method drops, so the future it returns can be spawned on a multi-threaded runtime. -:::info +This page answers *why will my async CGP handler not spawn?* It is short, and it is about a gap in +stable Rust rather than about CGP — CGP just meets it sooner than most code does. It explains where the +guarantee goes, the bound that would fix it and does not exist yet, and the workaround. It closes on +what that workaround costs, which is repetition. -### Not written yet +## Where the guarantee goes -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +An async method in a CGP trait is declared with `#[async_trait]`, which rewrites it into a method +returning `impl Future`: -::: +```rust +#[cgp_component(ApiHandler)] +#[async_trait] +pub trait CanHandleApi { + type Response; + + async fn handle_api(&self, _api: PhantomData) -> Self::Response; +} +``` + +That rewrite is faithful and costs nothing — no boxing, no allocation. It also drops every auto-trait +bound. The returned future is `Send` when the concrete future the body produces happens to be, and a +caller working through the trait has no way to *require* it. + +The opacity is the trade. Return-position `impl Trait` is zero-cost precisely because the caller does +not see the concrete type, and the future's `Send`-ness is part of what is hidden. + +## Why that matters, and what you cannot write + +It matters the moment the future is spawned. A work-stealing runtime — the default Tokio runtime an Axum +server runs on — may move a task between threads while it is suspended, so every future it drives must +be `Send`. A generic handler awaiting `handle_api` produces a task that is `Send` only if that future +is. + +For a *concrete* context the compiler checks this itself. For a generic one it cannot, because the fact +in question is the one the trait refuses to expose. + +The bound you want has a name and is not stable: + +```rust +// Not available on stable Rust: +fn spawn_handler(app: App) +where + App: CanHandleApi + Send + 'static, +{ +} +``` + +Return Type Notation — `handle_api(..): Send` — says exactly the right thing: whatever arguments the +method is called with, its future is `Send`. It is not stabilized, so this cannot be written in +production code today. + +## Recovering it with a second trait + +The workaround is to declare an ordinary trait whose method spells the bound out in its own return type, +where the notation is not needed: + +```rust +pub trait CanHandleApiSend: CanHandleApi + Send + Sync +where + Self::Response: Send, +{ + fn handle_api_send(&self, api: PhantomData) + -> impl Future + Send; +} +``` + +`CanHandleApiSend` is **not a component**. It adds nothing to any wiring table and has no providers; it +exists to carry a stronger signature. It inherits the whole capability from `CanHandleApi` as a +supertrait, additionally requires the response and the context to be `Send`, and writes `+ Send` on the +future directly. + +A spawning caller can now say what it needs, in one bound with no missing notation: + +```rust +where + App: CanHandleApiSend, +``` + +## Why the implementation cannot be generic + +The obvious next step is one blanket implementation covering every context that already handles the API. +It does not compile, and the reason is worth following, because it is the same gap wearing a disguise. + +Such an impl would wrap `self.handle_api(..)` in an `async` block, and that block is `Send` only if the +future it awaits is. For a generic `App` and `Api` the awaited future is an opaque `impl Future` whose +auto-traits are unknown — so the impl cannot prove its own `+ Send` return type. A generic blanket impl +*is* Return Type Notation, and it is blocked for the same reason. + +Dropping to a concrete context and a concrete API closes it: + +```rust +impl CanHandleApiSend for MockApp { + async fn handle_api_send(&self, api: PhantomData) -> u64 { + self.handle_api(api).await + } +} +``` + +Now `Self` is a fixed type and `Api` is a fixed marker, so the call resolves through the wiring to a +concrete provider producing a concrete future — and the compiler computes that future's auto-traits and +finds it `Send`. No annotation is needed, because `Send` is inferred structurally for a known type. + +Each of these impls is mechanical: forward, and await. Each is also a *proof*, accepted only because at +this instantiation the future really is `Send`. + +## What it costs + +**One impl per context per API.** That is the price of the missing notation, and it is the whole cost: +where RTN would have allowed a single generic impl, this needs one for every pair. A service with eight +endpoints and two contexts writes sixteen forwarding bodies. + +**It is boilerplate that cannot be abstracted away**, since abstracting it is what does not compile. A +macro could generate it, and the impls would still be there. + +**And it is a second trait to keep in step.** Adding a method to the capability means adding it here +too, and nothing enforces that the two stay aligned beyond the supertrait. + +The one consolation is that the whole thing disappears when Return Type Notation stabilizes. This is a +workaround with a known expiry, not a design. + +## Where to go next + +[Handlers](./handlers.md) is the family whose futures most often need this, since it is where CGP's +async I/O lives. [Consumer and provider traits](./consumer-and-provider-traits.md) explains the wiring +the concrete impl forwards through, which is what makes the resolved future a concrete, checkable type. + +For the constructs, [`#[async_trait]`](/docs/reference/macros/async_trait) is the rewrite that drops the +bound, and its own page records the same gap from the macro's side. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index eee6b0d0..ff401a95 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -8,12 +8,144 @@ sidebar_position: 16 Encoding a small language as Rust types and interpreting it during compilation, with no interpreter left at runtime. -:::info +This page answers *what happens when the `Code` tag carries a whole program?* It is the furthest thing +CGP's pieces are put to, and it assumes [handlers](./handlers.md). It shows a small language built from +types, why separating its syntax from its meaning is the point, and how a third party extends it. It +closes on the boundary — the programs this cannot express. -### Not written yet +## A program that is a type -This page is still being written. Until it lands, the [tutorials](/docs/tutorials/hello) are the best -place to meet this idea in working code, and the [reference](/docs/reference/) covers the constructs it -rests on. +The [handler family](./handlers.md) threads a phantom `Code` tag so one context can host many +computations. Nothing says the tag has to be small. -::: +Make it the program: + +```rust +pub struct Literal; +pub struct Add(pub PhantomData<(Left, Right)>); +pub struct Multiply(pub PhantomData<(Left, Right)>); +``` + +Three structs with no data and no methods. They exist to be *named in a type*, and nesting them writes a +program: + +```rust +type Program = Multiply, Literal<3>>, Literal<4>>; +``` + +That is `(2 + 3) * 4` as a type. It is the language's **abstract syntax**, and — this is the whole idea — +it says nothing at all about what any of it means. + +For a real language the fragments carry more: a +[`Product!`](/docs/reference/macros/product) list for a pipeline of stages, a +[`Symbol!`](/docs/reference/macros/symbol) where a string literal would go, since a `&str` value cannot +appear where only types are allowed. + +## The meaning is a set of providers + +Meaning arrives separately, one provider per fragment, each matching its own shape of `Code`: + +```rust +#[cgp_new_provider] +impl Computer, ()> for EvalAdd +where + Context: CanCompute + CanCompute, +{ + type Output = u64; + + fn compute(context: &Context, _code: PhantomData>, _input: ()) -> u64 { + context.compute(PhantomData::, ()) + context.compute(PhantomData::, ()) + } +} +``` + +`EvalAdd` interprets *any* addition, whatever its operands, and it evaluates them by asking the context +— which is what makes the recursion work and what keeps the provider from knowing the rest of the +language. Its requirements say only "the context can evaluate my operands". + +The context then assembles the language, one row per fragment: + +```rust +delegate_components! { + Interpreter { + open ComputerComponent; + + @ComputerComponent.Literal.(): EvalLiteral, + @ComputerComponent.Add.(): EvalAdd, + @ComputerComponent.Multiply.(): EvalMultiply, + } +} +``` + +And running a program is one call: + +```rust +Interpreter.compute(PhantomData::, ()) // 20 +``` + +Because the keys are types with structure, a single row captures a whole family of programs — every +`Add<_, _>` there will ever be. A value-level lookup table cannot do that. + +## What the separation buys + +There is no parser, no syntax tree walked at run time, and no dispatch loop. **Type checking the call +is the interpretation**: the compiler resolves the wiring recursively through the program's structure, +and what is left in the binary is the arithmetic. + +The more interesting consequence is that syntax and meaning vary independently. + +**One program, several meanings.** A second context wiring the same fragments to different providers +interprets the same program differently — evaluate it, pretty-print it, cost it, run it against a test +double. Nothing in the program changes, because the program never said what it meant. + +**One meaning, extended syntax.** A crate that does not own the language defines a new fragment and a +provider for it, and a context that wants both wires both. The base language is not patched, forked, or +even recompiled — the extension is a row. That is the [expression problem](./extensible-variants.md) +answered on the syntax side, and it is why a DSL built this way can have third-party dialects. + +At scale the rows themselves become a [namespace](./namespaces.md), so a context joins a language rather +than listing its fragments, and an extension is a namespace inheriting the base. + +## A readable surface is optional + +A procedural macro can sit on top, turning an infix pipe into a nested type or a string literal into a +`Symbol!`. Such a macro does shallow token rewriting and emits the same types a programmer could write +by hand. + +Keeping it that thin is deliberate: because the macro carries no meaning, the language stays fully +usable and fully extensible without it, and the grammar can evolve without touching either the macro or +the interpreters. + +## What it costs + +**The program must be known at compile time.** This is the boundary, and it is absolute. A script read +from a file, a pipeline configured at startup, a user-supplied expression — none of them can be a type. +If programs arrive at run time you need a runtime interpreter, and this technique is not one. + +**The diagnostics are the worst CGP produces.** A malformed program is a trait-resolution failure over a +deeply nested type, reported in terms of the whole program rather than the fragment at fault. Checks +localize it and the toolchain reshapes what it recognizes; a badly nested program is still hard reading. + +**Compile times feel it.** Every fragment of every program is resolution work, and a large program +instantiated several ways is where CGP's compile-time cost is most visible. + +**And it is the most advanced thing here.** Everything else in this section is worth reaching for +routinely. This is worth reaching for when a language is genuinely the right shape for a problem — +build pipelines, protocol descriptions, shell-like scripting — and when the programs are fixed when the +binary is. + +## Where to go next + +[Handlers](./handlers.md) is the family this rests on, and the page to read first. +[Dispatching](./dispatching.md) is the same routing applied to data rather than to programs, and +[namespaces](./namespaces.md) is how a language is packaged once it outgrows a table. + +For the constructs, [`Computer`](/docs/reference/components/computer) and +[`Handler`](/docs/reference/components/handler) are the interpreter interfaces, +[`delegate_components!`](/docs/reference/macros/delegate_components) carries the `open` statement and +generic path keys, and [`Product!`](/docs/reference/macros/product) and +[`Symbol!`](/docs/reference/macros/symbol) are how a real language carries lists and strings. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index 14e695a1..b0cc285b 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -8,4 +8,7 @@ description = "Compiled counterparts of the code shown on contextgeneric.dev. No [dependencies] cgp = "0.8.0-alpha" +[dev-dependencies] +futures = "0.3" + [workspace] diff --git a/example-code/README.md b/example-code/README.md index e4309440..55268a0a 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -16,10 +16,16 @@ cargo check # the fast check: the code compiles One file per page, at the matching path with the file name in `snake_case`: -| Page | File | +| Section | Coverage | |---|---| -| `docs/concepts/coherence.md` | `src/concepts/coherence.rs` | -| `docs/concepts/consumer-and-provider-traits.md` | `src/concepts/consumer_and_provider_traits.rs` | +| `docs/concepts/` | complete — sixteen files under `src/concepts/`, one per page that shows code | +| `docs/reference/` | none yet | +| `docs/tutorials/` | none yet | +| front page, orientation pages | none yet | + +Within a covered section the mapping is mechanical: `docs/concepts/coherence.md` is answered by +`src/concepts/coherence.rs`, and `docs/concepts/consumer-and-provider-traits.md` by +`src/concepts/consumer_and_provider_traits.rs`. A page that shows no code gets no file — `docs/concepts/modularity-hierarchy.md` is prose and tables, so it has no module here, and neither does a section index. diff --git a/example-code/src/concepts/abstract_types.rs b/example-code/src/concepts/abstract_types.rs new file mode 100644 index 00000000..d31195a1 --- /dev/null +++ b/example-code/src/concepts/abstract_types.rs @@ -0,0 +1,187 @@ +//! Code from `docs/concepts/abstract-types.md` — *Abstract types*. + +/// ## An associated type is already this, in ordinary Rust +pub mod an_associated_type_is_already_this { + pub trait HasScalarType { + type Scalar: Copy; + } + + pub struct HighPrecision; + pub struct Embedded; + + impl HasScalarType for HighPrecision { + type Scalar = f64; + } + + impl HasScalarType for Embedded { + type Scalar = f32; + } + + // Generic code names the type without fixing it. + pub fn double(scalar: Context::Scalar) -> Context::Scalar + where + Context: HasScalarType, + Context::Scalar: core::ops::Add, + { + scalar + scalar + } +} + +/// ## Choosing the type by wiring +pub mod choosing_the_type_by_wiring { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Copy; + } + + pub struct HighPrecision; + pub struct Embedded; + + delegate_components! { + HighPrecision { + ScalarTypeProviderComponent: UseType, + } + } + + delegate_components! { + Embedded { + ScalarTypeProviderComponent: UseType, + } + } + + mod check_high_precision { + use super::*; + check_components! { HighPrecision { ScalarTypeProviderComponent } } + } + + mod check_embedded { + use super::*; + check_components! { Embedded { ScalarTypeProviderComponent } } + } + + #[test] + fn each_context_answers_with_its_own_type() { + fn size_of_scalar() -> usize { + core::mem::size_of::() + } + + assert_eq!(size_of_scalar::(), 8); + assert_eq!(size_of_scalar::(), 4); + } +} + +/// ## One type, agreed on by everything that needs it +/// +/// The shapes carry no scalar type of their own. The context supplies one, and every capability +/// that mentions it means the same type. +pub mod one_type_agreed_on_by_everything { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Copy; + } + + #[cgp_component(ShapeAreaCalculator)] + #[use_type(HasScalarType.Scalar)] + pub trait CanCalculateShapeArea { + fn shape_area(&self, shape: &Shape) -> Scalar; + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(new RectangleArea)] + #[use_type(HasScalarType.{Scalar = f64})] + impl ShapeAreaCalculator { + fn shape_area(&self, shape: &Rectangle) -> Scalar { + shape.width * shape.height + } + } + + pub struct App; + + delegate_components! { + App { + // An `open` statement has to lead the table, before any plain entry. + open ShapeAreaCalculatorComponent; + + ScalarTypeProviderComponent: UseType, + @ShapeAreaCalculatorComponent.Rectangle: RectangleArea, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ScalarTypeProviderComponent, + ShapeAreaCalculatorComponent: Rectangle, + } + } + } + + #[test] + fn the_shape_never_names_a_scalar() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + assert_eq!(App.shape_area(&rectangle), 12.0); + } +} + +/// ## The canonical one: a context's error type +pub mod the_canonical_one_an_error_type { + // The error component's wiring keys and its backend providers are deliberately not in the + // prelude, so they are imported by name. + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self, path: &str) -> Result; + } + + #[cgp_impl(new LoadOrFail)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + return Err(Self::raise_error("empty path".to_owned())); + } + Ok(format!("contents of {path}")) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + LoaderComponent: LoadOrFail, + @ErrorRaiserComponent.String: RaiseFrom, + } + } + + mod check_app { + use super::*; + check_components! { App { LoaderComponent } } + } + + #[test] + fn the_provider_never_names_the_concrete_error() { + assert_eq!(App.load("a.txt").unwrap(), "contents of a.txt"); + assert_eq!(App.load("").unwrap_err(), "empty path"); + } +} diff --git a/example-code/src/concepts/aggregate_providers.rs b/example-code/src/concepts/aggregate_providers.rs new file mode 100644 index 00000000..0f4535e4 --- /dev/null +++ b/example-code/src/concepts/aggregate_providers.rs @@ -0,0 +1,237 @@ +//! Code from `docs/concepts/aggregate-providers.md` — *Aggregate providers*. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[cgp_impl(new RectanglePerimeter)] +impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } +} + +/// ## A table whose target is not a context +/// +/// The `new` keyword declares the struct and gives it a table. Nothing here is a context. +pub mod a_table_that_is_not_a_context { + use cgp::prelude::*; + + use super::*; + + delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } + } + + /// ## How a context uses one + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: GeometryComponents, + } + } + + // The bundle is verified here — through a real context, which is the only place the question + // means anything. + mod check_rectangle { + use super::*; + check_components! { + Rectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } + } + } + + #[test] + fn the_context_stays_the_context_all_the_way_down() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + // `RectangleArea` reads `width` and `height` from `Rectangle`, not from the bundle. + assert_eq!(rectangle.area(), 12.0); + assert_eq!(rectangle.perimeter(), 14.0); + } +} + +/// ## Bundles nest +pub mod bundles_nest { + use cgp::prelude::*; + + use super::*; + + delegate_components! { + new BaseGeometry { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } + } + + // A second bundle that takes everything from the first and overrides nothing yet. The delegate + // of an entry is allowed to be another table rather than a leaf provider. + delegate_components! { + new ExtendedGeometry { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: BaseGeometry, + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: ExtendedGeometry, + } + } + + mod check_rectangle { + use super::*; + check_components! { + Rectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } + } + } + + #[test] + fn resolution_walks_each_table_in_turn() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + assert_eq!(rectangle.area(), 12.0); + } +} + +/// ## Checking a bundle asks the wrong question +/// +/// A context-side check on a bundle asks whether the *bundle* can use the component as a context, +/// which is a role it never plays. Which way that goes wrong depends on what is bundled, and one of +/// the two ways is silent. +/// +/// The silent one. `AlwaysOne` needs nothing from its context, so it implements the provider trait +/// for every context including the bundle — the check passes and proves nothing: +/// +/// ```rust +/// use cgp::prelude::*; +/// +/// #[cgp_component(AreaCalculator)] +/// pub trait CanCalculateArea { +/// fn area(&self) -> f64; +/// } +/// +/// #[cgp_impl(new AlwaysOne)] +/// impl AreaCalculator { +/// fn area(&self) -> f64 { 1.0 } +/// } +/// +/// delegate_and_check_components! { +/// new GeometryComponents { +/// AreaCalculatorComponent: AlwaysOne, +/// } +/// } +/// ``` +/// +/// The loud one. `RectangleArea` needs fields, and the check demands them of the bundle: +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[cgp_component(AreaCalculator)] +/// pub trait CanCalculateArea { +/// fn area(&self) -> f64; +/// } +/// +/// #[cgp_impl(new RectangleArea)] +/// impl AreaCalculator { +/// fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { width * height } +/// } +/// +/// // error[E0277]: the trait bound +/// // `GeometryComponents: CanUseComponent` +/// // is not satisfied +/// delegate_and_check_components! { +/// new GeometryComponents { +/// AreaCalculatorComponent: RectangleArea, +/// } +/// } +/// ``` +pub mod checking_a_bundle_asks_the_wrong_question {} + +/// ## Checking the bundle on its own, correctly +/// +/// `#[check_providers]` asserts the provider-side question — is this a provider for that context — +/// which is the one the bundle's role calls for. +pub mod checking_the_bundle_correctly { + use cgp::prelude::*; + + use super::*; + + delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: GeometryComponents, + } + } + + mod check_the_bundle_for_a_real_context { + use super::*; + check_components! { + #[check_providers( + RectangleArea, + GeometryComponents, + )] + Rectangle { + AreaCalculatorComponent, + } + } + } +} diff --git a/example-code/src/concepts/check_traits.rs b/example-code/src/concepts/check_traits.rs new file mode 100644 index 00000000..1328a9e8 --- /dev/null +++ b/example-code/src/concepts/check_traits.rs @@ -0,0 +1,165 @@ +//! Code from `docs/concepts/check-traits.md` — *Checking your wiring*. + +/// ## A context can be wrong and still compile +/// +/// `RecordEmails` needs a `sent_emails` field and `BrokenApp` has none. Every line here compiles, +/// because nothing has asked whether the provider's requirements hold for this context yet. +pub mod a_context_can_be_wrong_and_still_compile { + use core::cell::RefCell; + + use cgp::prelude::*; + + #[cgp_component(EmailSender)] + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + #[cgp_impl(new RecordEmails)] + impl EmailSender { + fn send_email(&self, #[implicit] sent_emails: &RefCell>, to: &str, body: &str) { + sent_emails.borrow_mut().push(format!("{to}: {body}")); + } + } + + #[derive(HasField)] + pub struct BrokenApp { + pub smtp_server: String, + } + + // Accepted. The table records a choice; it does not verify one. + delegate_components! { BrokenApp { EmailSenderComponent: RecordEmails } } +} + +/// ## Where the failure surfaces instead +/// +/// Calling the capability is the first thing that forces the question, so the error arrives at the +/// call rather than at the wiring — and names a field requirement the caller never wrote. +/// +/// ```compile_fail +/// use cgp_website_example_code::concepts::check_traits::a_context_can_be_wrong_and_still_compile::*; +/// +/// fn main() { +/// let app = BrokenApp { smtp_server: "localhost".to_owned() }; +/// app.send_email("a@b.c", "hi"); +/// } +/// ``` +/// +/// A check placed beside the wiring forces the same question at a line you chose. This one fails, +/// which is the point of it: +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// use cgp_website_example_code::concepts::check_traits::a_context_can_be_wrong_and_still_compile::*; +/// +/// check_components! { +/// BrokenApp { +/// EmailSenderComponent, +/// } +/// } +/// ``` +pub mod where_the_failure_surfaces {} + +/// ## A check is an empty impl of a trait that demands something +/// +/// The hand-written form, so the generated one is not mysterious: a trait whose supertrait is the +/// requirement, and an impl with nothing in it. +pub mod a_check_is_an_empty_impl { + use cgp::prelude::*; + + #[cgp_component(EmailSender)] + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + #[cgp_impl(new RecordEmails)] + impl EmailSender { + fn send_email(&self, #[implicit] sent_emails: &Vec, to: &str, body: &str) {} + } + + #[derive(HasField)] + pub struct App { + pub sent_emails: Vec, + } + + delegate_components! { App { EmailSenderComponent: RecordEmails } } + + // The plain-Rust version: nothing to prove in the body, so it compiles exactly when the + // supertrait holds. + trait CanUseApp: CanSendEmail {} + impl CanUseApp for App {} + + // What `check_components!` writes instead, which reports the missing requirement rather than + // only that the capability is unavailable. + mod generated_form { + use super::*; + check_components! { + App { + EmailSenderComponent, + } + } + } +} + +/// ## Checking a stack one layer at a time +/// +/// `#[check_providers]` asserts against each provider rather than against the context, so a broken +/// layer of a nested stack errors on its own line. +pub mod checking_a_stack_one_layer_at_a_time { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(new ScaledArea)] + #[use_provider(Inner: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale: f64) -> f64 { + Inner::area(self) * scale * scale + } + } + + #[derive(HasField)] + pub struct App { + pub width: f64, + pub height: f64, + pub scale: f64, + } + + delegate_components! { + App { + AreaCalculatorComponent: ScaledArea, + } + } + + mod check_each_layer { + use super::*; + check_components! { + #[check_providers( + RectangleArea, + ScaledArea, + )] + App { + AreaCalculatorComponent, + } + } + } + + #[test] + fn the_stack_resolves() { + let app = App { + width: 3.0, + height: 4.0, + scale: 2.0, + }; + assert_eq!(app.area(), 48.0); + } +} diff --git a/example-code/src/concepts/dispatching.rs b/example-code/src/concepts/dispatching.rs new file mode 100644 index 00000000..10814bf5 --- /dev/null +++ b/example-code/src/concepts/dispatching.rs @@ -0,0 +1,127 @@ +//! Code from `docs/concepts/dispatching.md` — *Dispatching*. + +/// ## Matching: one handler per variant +pub mod matching_one_handler_per_variant { + use core::convert::Infallible; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::dispatch::MatchWithValueHandlers; + use cgp::extra::handler::{ComputerComponent, UseInputDelegate}; + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_computer] + pub fn circle_area(circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + + #[cgp_computer] + pub fn rectangle_area(rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + + ComputerComponent: UseInputDelegate< + // The whole enum routes to the matcher; each variant's payload routes to its own + // handler. No indirection is needed here — a *recursive* language, where a + // variant's payload contains the enum again, is the case that needs a thin + // wrapper between the two to break the resolution cycle. + new AreaComponents { + Shape: MatchWithValueHandlers, + Circle: CircleArea, + Rectangle: RectangleArea, + } + >, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: [((), Shape), ((), Circle), ((), Rectangle)], + } + } + } + + #[test] + fn the_value_reaches_the_handler_for_its_variant() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!( + app.compute(code, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), + 12.0, + ); + + let circle_area = app.compute(code, Shape::Circle(Circle { radius: 1.0 })); + assert!((circle_area - core::f64::consts::PI).abs() < 1e-9); + } +} + +/// ## The same idea from a per-type trait +/// +/// When the per-variant logic is an ordinary trait with one impl per payload type, +/// `#[cgp_auto_dispatch]` generates the matcher wiring rather than making it something to write. +pub mod the_same_idea_from_a_per_type_trait { + use cgp::prelude::*; + + #[cgp_auto_dispatch] + pub trait CanDescribe { + fn describe(&self) -> String; + } + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + impl CanDescribe for Circle { + fn describe(&self) -> String { + format!("circle of radius {}", self.radius) + } + } + + impl CanDescribe for Rectangle { + fn describe(&self) -> String { + format!("{}x{} rectangle", self.width, self.height) + } + } + + #[test] + fn the_enum_gains_the_trait_from_its_variants() { + let shape = Shape::Circle(Circle { radius: 2.0 }); + assert_eq!(shape.describe(), "circle of radius 2"); + } +} diff --git a/example-code/src/concepts/extensible_records.rs b/example-code/src/concepts/extensible_records.rs new file mode 100644 index 00000000..cf018580 --- /dev/null +++ b/example-code/src/concepts/extensible_records.rs @@ -0,0 +1,99 @@ +//! Code from `docs/concepts/extensible-records.md` — *Extensible records*. + +/// ## A struct as a list of named fields +pub mod a_struct_as_a_list_of_named_fields { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct DatabaseClient { + pub url: String, + pub pool_size: u32, + } + + /// The derive gives the struct a type-level description of its own shape. Naming it here is + /// what pins the claim the page makes about it. + #[test] + fn the_shape_is_a_type() { + fn assert_shape() + where + T: HasFields, Field]>, + { + } + + assert_shape::(); + } +} + +/// ## Building one field at a time +pub mod building_one_field_at_a_time { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct App { + pub database: String, + pub http_timeout: u32, + pub feature_flag: bool, + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct DatabaseConfig { + pub database: String, + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct HttpConfig { + pub http_timeout: u32, + pub feature_flag: bool, + } + + #[test] + fn independent_pieces_merge_into_a_whole() { + use cgp::core::field::impls::CanBuildFrom; + + let database = DatabaseConfig { + database: "postgres://…".to_owned(), + }; + + let http = HttpConfig { + http_timeout: 30, + feature_flag: true, + }; + + let app: App = App::builder() + .build_from(database) + .build_from(http) + .finalize_build(); + + assert_eq!(app.http_timeout, 30); + assert!(app.feature_flag); + } +} + +/// ## Finalizing early does not compile +/// +/// The partial record tracks which fields are present, and the operation that turns it back into +/// the struct exists only at the all-present configuration. +/// +/// ```compile_fail +/// use cgp::core::field::impls::CanBuildFrom; +/// use cgp::prelude::*; +/// +/// #[derive(CgpData)] +/// pub struct App { +/// pub database: String, +/// pub http_timeout: u32, +/// } +/// +/// #[derive(CgpData)] +/// pub struct DatabaseConfig { +/// pub database: String, +/// } +/// +/// fn main() { +/// // `http_timeout` has never been set, so there is no `finalize_build` to call. +/// let _app: App = App::builder() +/// .build_from(DatabaseConfig { database: "postgres://…".to_owned() }) +/// .finalize_build(); +/// } +/// ``` +pub mod finalizing_early_does_not_compile {} diff --git a/example-code/src/concepts/extensible_variants.rs b/example-code/src/concepts/extensible_variants.rs new file mode 100644 index 00000000..bae62333 --- /dev/null +++ b/example-code/src/concepts/extensible_variants.rs @@ -0,0 +1,147 @@ +//! Code from `docs/concepts/extensible-variants.md` — *Extensible variants*. + +/// ## An enum as a list of named variants +pub mod an_enum_as_a_list_of_named_variants { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct Circle { + pub radius: u64, + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct Rectangle { + pub width: u64, + pub height: u64, + } + + /// The shape of an enum is a *sum* of named variants, where a record's was a product of named + /// fields. + #[test] + fn the_shape_is_a_type() { + fn assert_shape() + where + T: HasFields< + Fields = Sum![ + Field, + Field, + ], + >, + { + } + + assert_shape::(); + } +} + +/// ## One handler per variant, dispatched by name +pub mod one_handler_per_variant { + use core::convert::Infallible; + use core::fmt::Display; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::dispatch::MatchWithFieldHandlers; + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum Reading { + Temperature(u64), + Label(String), + } + + // The enum gained a third variant and this handler did not change. + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum ExtendedReading { + Temperature(u64), + Label(String), + Flag(bool), + } + + #[cgp_computer] + pub fn field_to_string(Field { value, .. }: Field) -> String + where + Value: Display, + { + value.to_string() + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ComputerComponent: MatchWithFieldHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: [((), Reading), ((), ExtendedReading)], + } + } + } + + #[test] + fn the_same_handler_serves_two_enums() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(app.compute(code, Reading::Temperature(21)), "21"); + assert_eq!(app.compute(code, Reading::Label("north".to_owned())), "north"); + + // The wider enum works through the same wiring, with no new arm anywhere. + assert_eq!(app.compute(code, ExtendedReading::Flag(true)), "true"); + } +} + +/// ## Widening and narrowing between enums that share variants +pub mod widening_and_narrowing { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum Reading { + Temperature(u64), + Label(String), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum ExtendedReading { + Temperature(u64), + Label(String), + Flag(bool), + } + + #[test] + fn a_narrow_value_lifts_into_a_wider_enum() { + use cgp::core::field::impls::CanUpcast; + + let narrow = Reading::Temperature(21); + let wide: ExtendedReading = narrow.upcast(PhantomData::); + + assert_eq!(wide, ExtendedReading::Temperature(21)); + } + + #[test] + fn narrowing_succeeds_only_for_a_variant_the_target_has() { + use cgp::core::field::impls::CanDowncast; + + let wide = ExtendedReading::Label("north".to_owned()); + let narrow: Result = wide.downcast(PhantomData::); + assert_eq!(narrow.ok(), Some(Reading::Label("north".to_owned()))); + + let wide = ExtendedReading::Flag(true); + let narrow: Result = wide.downcast(PhantomData::); + assert!(narrow.is_err()); + } +} diff --git a/example-code/src/concepts/handlers.rs b/example-code/src/concepts/handlers.rs new file mode 100644 index 00000000..6ae4a4c9 --- /dev/null +++ b/example-code/src/concepts/handlers.rs @@ -0,0 +1,200 @@ +//! Code from `docs/concepts/handlers.md` — *Handlers*. + +/// ## One function, the whole family +/// +/// A synchronous, infallible function becomes a provider callable as every member of the family, +/// because CGP promotes the weaker variants into the stronger ones. +pub mod one_function_the_whole_family { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + #[cgp_computer] + fn add(a: u64, b: u64) -> u64 { + a + b + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + } + } + + #[test] + fn the_same_definition_answers_four_components() { + use futures::executor::block_on; + + let app = App; + + assert_eq!(Add::compute(&app, PhantomData::<()>, (1, 2)), 3); + assert_eq!(Add::try_compute(&app, PhantomData::<()>, (1, 2)), Ok(3)); + assert_eq!(block_on(Add::compute_async(&app, PhantomData::<()>, (1, 2))), 3); + assert_eq!(block_on(Add::handle(&app, PhantomData::<()>, (1, 2))), Ok(3)); + } +} + +/// ## A fallible function, promoted the same way +pub mod a_fallible_function { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + #[cgp_computer] + fn checked_add(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "overflow".to_owned()) + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + } + } + + #[test] + fn the_error_path_surfaces_through_the_fallible_members() { + let app = App; + + assert_eq!(CheckedAdd::try_compute(&app, PhantomData::<()>, (1, 2)), Ok(3)); + assert_eq!( + CheckedAdd::try_compute(&app, PhantomData::<()>, (u64::MAX, 1)), + Err("overflow".to_owned()), + ); + } +} + +/// ## A pipeline is a wiring entry +pub mod a_pipeline_is_a_wiring_entry { + use core::marker::PhantomData; + + use cgp::extra::handler::{Computer, ComputerComponent, PipeHandlers}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Multiply + where + Context: HasField, + { + type Output = u64; + + fn compute(context: &Context, _code: PhantomData, input: u64) -> u64 { + input * context.get_field(PhantomData) + } + } + + #[cgp_new_provider] + impl Computer for Add + where + Context: HasField, + { + type Output = u64; + + fn compute(context: &Context, _code: PhantomData, input: u64) -> u64 { + input + context.get_field(PhantomData) + } + } + + #[derive(HasField)] + pub struct App { + pub foo: u64, + pub bar: u64, + pub baz: u64, + } + + delegate_components! { + App { + ComputerComponent: PipeHandlers< + Product![ + Multiply, + Add, + Multiply, + ] + >, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), u64), + } + } + } + + #[test] + fn the_stages_run_left_to_right() { + use cgp::extra::handler::CanCompute; + + let app = App { + foo: 2, + bar: 3, + baz: 4, + }; + + // ((5 * 2) + 3) * 4 + assert_eq!(app.compute(PhantomData::<()>, 5u64), 52); + } +} + +/// ## The `Code` tag is what lets one context host many handlers +pub mod the_code_tag_hosts_many_handlers { + use core::marker::PhantomData; + + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + pub struct Doubled; + pub struct Negated; + + #[cgp_new_provider] + impl Computer for ComputeDoubled { + type Output = i64; + + fn compute(_context: &Context, _code: PhantomData, input: i64) -> i64 { + input * 2 + } + } + + #[cgp_new_provider] + impl Computer for ComputeNegated { + type Output = i64; + + fn compute(_context: &Context, _code: PhantomData, input: i64) -> i64 { + -input + } + } + + pub struct App; + + delegate_components! { + App { + open ComputerComponent; + + @ComputerComponent.Doubled.i64: ComputeDoubled, + @ComputerComponent.Negated.i64: ComputeNegated, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: [(Doubled, i64), (Negated, i64)], + } + } + } + + #[test] + fn two_computations_on_one_context() { + use cgp::extra::handler::CanCompute; + + assert_eq!(App.compute(PhantomData::, 21i64), 42); + assert_eq!(App.compute(PhantomData::, 21i64), -21); + } +} diff --git a/example-code/src/concepts/higher_order_providers.rs b/example-code/src/concepts/higher_order_providers.rs new file mode 100644 index 00000000..dd6a8089 --- /dev/null +++ b/example-code/src/concepts/higher_order_providers.rs @@ -0,0 +1,296 @@ +//! Code from `docs/concepts/higher-order-providers.md` — *Higher-order providers*. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[cgp_impl(new CircleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] radius: f64) -> f64 { + core::f64::consts::PI * radius * radius + } +} + +/// ## The bound the inner provider carries +/// +/// Written out, so the extra `` is visible before the attribute hides it. +pub mod the_bound_written_out { + use cgp::prelude::*; + + use super::{AreaCalculator, AreaCalculatorComponent, RectangleArea}; + + #[cgp_impl(new ScaledArea)] + impl AreaCalculator + where + Inner: AreaCalculator, + { + fn area(&self, #[implicit] scale: f64) -> f64 { + Inner::area(self) * scale * scale + } + } + + #[derive(HasField)] + pub struct App { + pub width: f64, + pub height: f64, + pub scale: f64, + } + + delegate_components! { + App { + AreaCalculatorComponent: ScaledArea, + } + } + + mod check_app { + use super::*; + check_components! { App { AreaCalculatorComponent } } + } +} + +/// ## The same provider with the bound completed for you +pub mod the_bound_completed_for_you { + use cgp::prelude::*; + + use super::{AreaCalculator, AreaCalculatorComponent, CircleArea, RectangleArea}; + + #[cgp_impl(new ScaledArea)] + #[use_provider(Inner: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale: f64) -> f64 { + let base = Inner::area(self); + base * scale * scale + } + } + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale: f64, + } + + #[derive(HasField)] + pub struct ScaledCircle { + pub radius: f64, + pub scale: f64, + } + + // The same wrapper over two different base cases. + delegate_components! { + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } + } + + delegate_components! { + ScaledCircle { + AreaCalculatorComponent: ScaledArea, + } + } + + mod check_rectangle { + use super::*; + check_components! { ScaledRectangle { AreaCalculatorComponent } } + } + + mod check_circle { + use super::*; + check_components! { ScaledCircle { AreaCalculatorComponent } } + } + + #[test] + fn one_wrapper_over_two_base_cases() { + use crate::concepts::higher_order_providers::CanCalculateArea; + + let rectangle = ScaledRectangle { + width: 3.0, + height: 4.0, + scale: 2.0, + }; + assert_eq!(rectangle.area(), 48.0); + + let circle = ScaledCircle { + radius: 1.0, + scale: 3.0, + }; + assert!((circle.area() - core::f64::consts::PI * 9.0).abs() < 1e-9); + } +} + +/// ## Composing without naming a context +/// +/// Two wrappers stacked, and the whole stack given a name. The alias carries no bounds at all: the +/// requirements are discharged where the context wires it, not where the composition is written. +pub mod composing_without_naming_a_context { + use cgp::prelude::*; + + use super::the_bound_completed_for_you::ScaledArea; + use super::{AreaCalculatorComponent, RectangleArea}; + + pub type ScaledScaledRectangleArea = ScaledArea>; + + #[derive(HasField)] + pub struct App { + pub width: f64, + pub height: f64, + pub scale: f64, + } + + delegate_components! { + App { + AreaCalculatorComponent: ScaledScaledRectangleArea, + } + } + + mod check_app { + use super::*; + check_components! { App { AreaCalculatorComponent } } + } + + #[test] + fn the_stack_composes_in_types() { + use crate::concepts::higher_order_providers::CanCalculateArea; + + let app = App { + width: 3.0, + height: 4.0, + scale: 2.0, + }; + // 12 scaled twice: 12 * 4 * 4 + assert_eq!(app.area(), 192.0); + } +} + +/// ## Falling back to whatever the context already wired +/// +/// A provider declared with an explicit struct can default its inner parameter to `UseContext`, +/// which routes the inner step back through the context's own table. +pub mod falling_back_to_the_context { + use core::marker::PhantomData; + + use cgp::prelude::*; + + #[cgp_component(ShapeAreaCalculator)] + pub trait CanCalculateShapeArea { + fn shape_area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(new RectangleArea)] + impl ShapeAreaCalculator { + fn shape_area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height + } + } + + // The default is what makes the unparameterized `SumAreas` mean `SumAreas`, and it + // needs an explicit struct declaration to be written down. + pub struct SumAreas(pub PhantomData); + + #[cgp_impl(SumAreas)] + #[use_provider(Inner: ShapeAreaCalculator)] + impl ShapeAreaCalculator> { + fn shape_area(&self, shapes: &Vec) -> f64 { + shapes.iter().map(|shape| Inner::shape_area(self, shape)).sum() + } + } + + pub struct App; + + delegate_components! { + App { + open ShapeAreaCalculatorComponent; + + @ShapeAreaCalculatorComponent.Rectangle: RectangleArea, + // No inner provider named, so the per-element lookup goes back through this table and + // finds the `Rectangle` entry above. + @ShapeAreaCalculatorComponent. Vec: SumAreas, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ShapeAreaCalculatorComponent: [Rectangle, Vec], + } + } + } + + #[test] + fn the_inner_step_resolves_through_the_context() { + let shapes = vec![ + Rectangle { + width: 3.0, + height: 4.0, + }, + Rectangle { + width: 1.0, + height: 2.0, + }, + ]; + assert_eq!(App.shape_area(&shapes), 14.0); + } +} + +/// ## Not every generic provider is a higher-order one +/// +/// `GetName` is generic, and its parameter is a field name rather than a provider — nothing is +/// delegated to, so none of the machinery above applies. +pub mod not_every_generic_provider { + use cgp::prelude::*; + + #[cgp_component(NameGetter)] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_impl(new GetName)] + impl NameGetter + where + Self: HasField, + { + fn name(&self) -> &str { + self.get_field(PhantomData::) + } + } + + #[derive(HasField)] + pub struct App { + pub first_name: String, + } + + delegate_components! { + App { + NameGetterComponent: GetName, + } + } + + mod check_app { + use super::*; + check_components! { App { NameGetterComponent } } + } + + #[test] + fn the_parameter_is_a_field_name() { + let app = App { + first_name: "Ada".to_owned(), + }; + assert_eq!(app.name(), "Ada"); + } +} diff --git a/example-code/src/concepts/impl_side_dependencies.rs b/example-code/src/concepts/impl_side_dependencies.rs new file mode 100644 index 00000000..e1f2891f --- /dev/null +++ b/example-code/src/concepts/impl_side_dependencies.rs @@ -0,0 +1,251 @@ +//! Code from `docs/concepts/impl-side-dependencies.md` — *Impl-side dependencies*. + +/// ## What a `where` clause costs the callers above it +pub mod what_a_where_clause_costs { + pub trait HasName { + fn name(&self) -> &str; + } + + pub fn greet(context: &Context) -> String + where + Context: HasName, + { + format!("Hello, {}!", context.name()) + } + + // The bound propagates. This function never touches a name, and declares the requirement anyway. + pub fn greet_twice(context: &Context) -> String + where + Context: HasName, + { + format!("{} {}", greet(context), greet(context)) + } +} + +/// ## Moving the requirement onto the implementation +pub mod moving_the_requirement { + pub trait HasName { + fn name(&self) -> &str; + } + + pub trait CanGreet { + fn greet(&self) -> String; + } + + impl CanGreet for Context + where + Context: HasName, + { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } + } + + // `HasName` is nowhere in this signature, and nothing above it will mention one either. + pub fn greet_twice(context: &Context) -> String + where + Context: CanGreet, + { + format!("{} {}", context.greet(), context.greet()) + } +} + +/// ## Two providers, two sets of requirements, one interface +pub mod two_providers_two_requirements { + use core::cell::RefCell; + + use cgp::prelude::*; + + #[cgp_component(EmailSender)] + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + #[cgp_auto_getter] + pub trait HasSmtpServer { + fn smtp_server(&self) -> &str; + } + + #[cgp_auto_getter] + pub trait HasSentEmails { + fn sent_emails(&self) -> &RefCell>; + } + + #[cgp_impl(new SendViaSmtp)] + #[uses(HasSmtpServer)] + impl EmailSender { + fn send_email(&self, to: &str, body: &str) { + let _ = (self.smtp_server(), to, body); + } + } + + #[cgp_impl(new RecordEmails)] + #[uses(HasSentEmails)] + impl EmailSender { + fn send_email(&self, to: &str, body: &str) { + self.sent_emails().borrow_mut().push(format!("{to}: {body}")); + } + } + + #[derive(HasField)] + pub struct App { + pub smtp_server: String, + } + + #[derive(HasField)] + pub struct TestApp { + pub sent_emails: RefCell>, + } + + delegate_components! { App { EmailSenderComponent: SendViaSmtp } } + delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } + + mod check_app { + use super::*; + check_components! { App { EmailSenderComponent } } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { EmailSenderComponent } } + } + + /// Neither requirement reaches a caller: this function bounds on the capability alone, and it + /// accepts both contexts even though they satisfy it for entirely different reasons. + pub fn notify(context: &Context) + where + Context: CanSendEmail, + { + context.send_email("a@b.c", "hi"); + } + + #[test] + fn one_bound_accepts_both_contexts() { + let test_app = TestApp { + sent_emails: RefCell::new(Vec::new()), + }; + notify(&test_app); + notify(&App { + smtp_server: "localhost".to_owned(), + }); + + assert_eq!(test_app.sent_emails.borrow().as_slice(), ["a@b.c: hi"]); + } +} + +/// ## The three things an implementation can ask for +/// +/// The value leg. The field requirement is generated from the argument name and lands on the impl. +pub mod the_value_leg { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetByName)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { App { GreeterComponent: GreetByName } } + + mod check_app { + use super::*; + check_components! { App { GreeterComponent } } + } +} + +/// ## Type dependencies, and why they need no parameter +/// +/// The shape a type dependency takes when it is a parameter: an input the caller supplies, so every +/// intermediate signature carries it whether or not it touches one. +pub mod the_type_leg_as_a_parameter { + pub trait Store { + type Error; + } + + pub trait Runtime { + type Error; + } + + pub fn run_job(store: &S, runtime: &R) -> Result<(), E> + where + E: From + From, + R: Runtime, + S: Store, + { + // This layer touches none of the three. + Ok(()) + } + + // And the layer above declares them again, for the same reason: it touches none of them either. + pub fn run_jobs(store: &S, runtime: &R) -> Result<(), E> + where + E: From + From, + R: Runtime, + S: Store, + { + run_job(store, runtime) + } +} + +/// ## Type dependencies, and why they need no parameter +/// +/// The same dependency as an abstract type: an output the context determines, so it is named where +/// it is used and nowhere else. +pub mod the_type_leg_as_an_abstract_type { + // The error component's wiring key is deliberately not in the prelude. + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + #[cgp_component(JobRunner)] + #[use_type(HasErrorType.Error)] + pub trait CanRunJob { + fn run_job(&self) -> Result<(), Error>; + } + + #[cgp_impl(new RunJobOnce)] + #[use_type(HasErrorType.Error)] + impl JobRunner { + fn run_job(&self) -> Result<(), Error> { + Ok(()) + } + } + + // The intermediate layer names no error type, no runtime, and no store. + #[cgp_fn] + #[uses(CanRunJob)] + #[use_type(HasErrorType.Error)] + pub fn run_jobs(&self) -> Result<(), Error> { + self.run_job()?; + self.run_job() + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + JobRunnerComponent: RunJobOnce, + } + } + + mod check_app { + use super::*; + check_components! { App { JobRunnerComponent } } + } + + #[test] + fn the_context_decides_the_error_type_and_no_layer_names_it() { + assert!(App.run_jobs().is_ok()); + } +} diff --git a/example-code/src/concepts/implicit_arguments.rs b/example-code/src/concepts/implicit_arguments.rs new file mode 100644 index 00000000..6c1c6dda --- /dev/null +++ b/example-code/src/concepts/implicit_arguments.rs @@ -0,0 +1,197 @@ +//! Code from `docs/concepts/implicit-arguments.md` — *Implicit arguments*. + +/// ## Reading a field, spelled out +/// +/// What an implicit argument stands in for: a field requirement declared by hand and a read that +/// carries a type-level tag. +pub mod reading_a_field_spelled_out { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetByName)] + impl Greeter + where + Self: HasField, + { + fn greet(&self) -> String { + let name = self.get_field(PhantomData::); + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { App { GreeterComponent: GreetByName } } + + mod check_app { + use super::*; + check_components! { App { GreeterComponent } } + } +} + +/// ## The same provider as a function taking arguments +pub mod the_same_provider_as_a_function { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetByName)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { App { GreeterComponent: GreetByName } } + + mod check_app { + use super::*; + check_components! { App { GreeterComponent } } + } + + /// The argument is gone from the public signature: `greet()` still takes nothing. + #[test] + fn the_implicit_argument_does_not_reach_the_caller() { + let app = App { + name: "World".to_owned(), + }; + assert_eq!(app.greet(), "Hello, World!"); + } +} + +/// ## A capability from a function alone +/// +/// `#[cgp_fn]` needs no trait, no provider, and no wiring — the blanket impl applies to any context +/// carrying the fields. +pub mod a_capability_from_a_function_alone { + use cgp::prelude::*; + + #[cgp_fn] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[test] + fn any_context_with_the_fields_has_the_capability() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + assert_eq!(rectangle.rectangle_area(), 12.0); + } +} + +/// ## The declared type decides how the field is read +pub mod the_declared_type_decides_the_read { + use cgp::prelude::*; + + #[cgp_fn] + pub fn describe( + &self, + // Owned: read by reference and cloned, so the context keeps its field. + #[implicit] name: String, + // `&str`: backed by a `String` field, borrowed rather than cloned. + #[implicit] title: &str, + // Any other borrow: taken as it stands. + #[implicit] tags: &Vec, + ) -> String { + format!("{title} {name} {tags:?}") + } + + #[derive(HasField)] + pub struct App { + pub name: String, + pub title: String, + pub tags: Vec, + } + + #[test] + fn the_context_keeps_its_fields() { + let app = App { + name: "Ada".to_owned(), + title: "Dr".to_owned(), + tags: vec!["admin".to_owned()], + }; + + assert_eq!(app.describe(), r#"Dr Ada ["admin"]"#); + // Still there — the owned argument was cloned out. + assert_eq!(app.name, "Ada"); + } +} + +/// ## When a getter trait is still the right thing +/// +/// The case an implicit argument cannot reach: the value lives on a type other than the provider's +/// own context, so there is no `self` field to read and the requirement is a bound on that other +/// type. +pub mod when_a_getter_is_still_right { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasAuthHeader { + fn auth_header(&self) -> &str; + } + + #[cgp_component(RequestAuthenticator)] + pub trait CanAuthenticate { + fn authenticate(&self, request: &Request) -> bool; + } + + #[cgp_impl(new AuthenticateByHeader)] + impl RequestAuthenticator + where + Request: HasAuthHeader, + { + fn authenticate(&self, request: &Request) -> bool { + request.auth_header().starts_with("Bearer ") + } + } + + #[derive(HasField)] + pub struct Request { + pub auth_header: String, + } + + pub struct App; + + delegate_components! { + App { + open RequestAuthenticatorComponent; + @RequestAuthenticatorComponent.Request: AuthenticateByHeader, + } + } + + mod check_app { + use super::*; + check_components! { App { RequestAuthenticatorComponent: Request } } + } + + #[test] + fn the_getter_is_a_bound_on_the_request_not_on_the_context() { + let request = Request { + auth_header: "Bearer t".to_owned(), + }; + assert!(App.authenticate(&request)); + } +} diff --git a/example-code/src/concepts/mod.rs b/example-code/src/concepts/mod.rs index f03cd4d2..a4faa64e 100644 --- a/example-code/src/concepts/mod.rs +++ b/example-code/src/concepts/mod.rs @@ -1,8 +1,23 @@ //! Code from the pages under `docs/concepts/`, one module per page. //! -//! Three of the eighteen pages in that section are written, and two of those three show code. -//! *How much CGP to use* (`modularity-hierarchy.md`) shows none — it is a decision guide built from -//! prose and tables — so it has no module here, and neither does the section index. +//! All eighteen pages of that section are written, and the seventeen that show code have a module here. +//! The two that show none — the section index, and *How much CGP to use*, which is a decision guide +//! built from prose and tables — do not. +pub mod abstract_types; +pub mod aggregate_providers; +pub mod check_traits; pub mod coherence; pub mod consumer_and_provider_traits; +pub mod dispatching; +pub mod extensible_records; +pub mod extensible_variants; +pub mod handlers; +pub mod higher_order_providers; +pub mod impl_side_dependencies; +pub mod implicit_arguments; +pub mod modular_error_handling; +pub mod monadic_handlers; +pub mod namespaces; +pub mod send_bounds; +pub mod type_level_dsls; diff --git a/example-code/src/concepts/modular_error_handling.rs b/example-code/src/concepts/modular_error_handling.rs new file mode 100644 index 00000000..56cd1005 --- /dev/null +++ b/example-code/src/concepts/modular_error_handling.rs @@ -0,0 +1,214 @@ +//! Code from `docs/concepts/modular-error-handling.md` — *Modular error handling*. + +/// ## Code that fails without knowing what failing means +pub mod code_that_fails_without_knowing { + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::prelude::*; + + #[cgp_component(PortParser)] + #[use_type(HasErrorType.Error)] + pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; + } + + #[cgp_impl(new ParsePortFromStr)] + #[uses(CanRaiseError, CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + let parsed: u32 = raw.parse().map_err(Self::raise_error)?; + + if parsed > u16::MAX as u32 { + return Err(Self::raise_error(format!("port {parsed} out of range"))); + } + + Ok(parsed as u16) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + PortParserComponent: ParsePortFromStr, + + // Two source errors, two strategies. A `String` is already the error type, so it is + // converted through `From`; a parse error is formatted with `Debug` and forwarded back + // through the `String` entry above. + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } + } + + mod check_app { + use super::*; + check_components! { App { PortParserComponent } } + } + + #[test] + fn one_capability_two_error_routes() { + assert_eq!(App.parse_port("8080").unwrap(), 8080); + + // Raised as a `String`, converted straight through. + assert_eq!( + App.parse_port("70000").unwrap_err(), + "port 70000 out of range" + ); + + // Raised as a `ParseIntError`, formatted and then routed through the `String` entry. + assert!(App.parse_port("http").unwrap_err().contains("ParseIntError")); + } +} + +/// ## The same providers under a different error type +/// +/// Nothing about `ParsePortFromStr` changes. The context names a different type and different +/// strategies, and every provider in it follows. +pub mod the_same_providers_under_a_different_error_type { + use core::fmt::Debug; + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::DebugError; + use cgp::prelude::*; + + use super::code_that_fails_without_knowing::{ParsePortFromStr, PortParserComponent}; + + #[derive(Debug)] + pub struct AppError { + pub message: String, + } + + impl From for AppError { + fn from(message: String) -> Self { + AppError { message } + } + } + + pub struct StrictApp; + + delegate_components! { + StrictApp { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + PortParserComponent: ParsePortFromStr, + + @ErrorRaiserComponent.String: cgp::extra::error::RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } + } + + mod check_strict_app { + use super::*; + check_components! { StrictApp { PortParserComponent } } + } + + #[test] + fn the_provider_did_not_change() { + use super::code_that_fails_without_knowing::CanParsePort; + + let error: AppError = StrictApp.parse_port("70000").unwrap_err(); + assert_eq!(error.message, "port 70000 out of range"); + } +} + +/// ## An application's own error capability +/// +/// Nothing about the pattern is confined to CGP's built-in components. A service that wants every +/// failure to carry a status code declares its own, and wires it the same way. +pub mod an_applications_own_error_capability { + use core::fmt::Display; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + pub struct ErrUnauthorized; + pub struct ErrNotFound; + + #[derive(Debug, PartialEq)] + pub struct HttpError { + pub status: u16, + pub message: String, + } + + #[cgp_component(HttpErrorRaiser)] + #[use_type(HasErrorType.Error)] + pub trait CanRaiseHttpError { + fn raise_http_error(code: Code, detail: Detail) -> Error; + } + + #[cgp_impl(new UnauthorizedError)] + #[use_type(HasErrorType.{Error = HttpError})] + impl HttpErrorRaiser + where + Detail: Display, + { + fn raise_http_error(_code: ErrUnauthorized, detail: Detail) -> Error { + HttpError { + status: 401, + message: detail.to_string(), + } + } + } + + #[cgp_impl(new NotFoundError)] + #[use_type(HasErrorType.{Error = HttpError})] + impl HttpErrorRaiser + where + Detail: Display, + { + fn raise_http_error(_code: ErrNotFound, detail: Detail) -> Error { + HttpError { + status: 404, + message: detail.to_string(), + } + } + } + + pub struct App; + + delegate_components! { + App { + open HttpErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + + @HttpErrorRaiserComponent.ErrUnauthorized.Detail: UnauthorizedError, + @HttpErrorRaiserComponent.ErrNotFound.Detail: NotFoundError, + } + } + + mod check_app { + use super::*; + check_components! { + App { + HttpErrorRaiserComponent: [ + (ErrUnauthorized, &'static str), + (ErrNotFound, &'static str), + ], + } + } + } + + #[test] + fn a_handler_never_names_the_status_code() { + let error = >::raise_http_error( + ErrUnauthorized, + "you must first login", + ); + assert_eq!( + error, + HttpError { + status: 401, + message: "you must first login".to_owned(), + } + ); + } +} diff --git a/example-code/src/concepts/monadic_handlers.rs b/example-code/src/concepts/monadic_handlers.rs new file mode 100644 index 00000000..9dd65265 --- /dev/null +++ b/example-code/src/concepts/monadic_handlers.rs @@ -0,0 +1,118 @@ +//! Code from `docs/concepts/monadic-handlers.md` — *Monadic handlers*. + +use cgp::extra::monad::monadic::err::ErrMonadic; +use cgp::extra::monad::providers::PipeMonadic; +use cgp::prelude::*; + +/// A fallible step: succeeds with the next value, or reports an overflow. +#[cgp_computer] +pub fn increment(value: u8) -> Result { + value.checked_add(1).ok_or("overflow") +} + +/// ## Plain composition is wrong for a fallible step +/// +/// Three steps under the identity monad: the `Result` is threaded forward untouched, so the second +/// step receives a `Result` rather than the value inside it and the chain never short-circuits. +/// Written out, the type mismatch is what stops this compiling — which is the honest form of "plain +/// composition does not fit". +/// +/// ```compile_fail +/// use cgp::extra::handler::PipeHandlers; +/// use cgp::prelude::*; +/// use cgp_website_example_code::concepts::monadic_handlers::Increment; +/// +/// fn main() { +/// // `Increment` produces `Result` and the next `Increment` wants a `u8`. +/// let _ = PipeHandlers::::compute(&(), PhantomData::<()>, 1u8); +/// } +/// ``` +pub mod plain_composition_is_wrong {} + +/// ## Chaining through the err monad +pub mod chaining_through_the_err_monad { + #[test] + fn the_first_error_becomes_the_output() { + use super::{ErrMonadic, Increment, PipeMonadic}; + use cgp::prelude::*; + + let context = (); + let code = PhantomData::<()>; + + // Three successful steps. + assert_eq!( + PipeMonadic::::compute( + &context, code, 1u8, + ), + Ok(4), + ); + + // The third step overflows, and the remaining steps do not run. + assert_eq!( + PipeMonadic::::compute( + &context, code, 253u8, + ), + Err("overflow"), + ); + } +} + +/// ## The identity monad recovers plain composition +pub mod the_identity_monad_recovers_plain_composition { + use cgp::prelude::*; + + #[cgp_computer] + pub fn double(value: u8) -> u8 { + value * 2 + } + + #[test] + fn nothing_short_circuits() { + use cgp::extra::monad::monadic::ident::IdentMonadic; + use cgp::extra::monad::providers::PipeMonadic; + + assert_eq!( + PipeMonadic::::compute( + &(), + PhantomData::<()>, + 3u8, + ), + 12, + ); + } +} + +/// ## A pipeline is still an ordinary provider +/// +/// The composed chain is wired like any other computation, so nothing downstream knows a monad was +/// involved. +pub mod a_pipeline_is_still_a_provider { + use cgp::extra::handler::ComputerComponent; + + use super::*; + + pub struct App; + + delegate_components! { + App { + ComputerComponent: PipeMonadic, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), u8), + } + } + } + + #[test] + fn the_context_just_computes() { + use cgp::extra::handler::CanCompute; + + assert_eq!(App.compute(PhantomData::<()>, 1u8), Ok(3)); + assert_eq!(App.compute(PhantomData::<()>, 254u8), Err("overflow")); + } +} diff --git a/example-code/src/concepts/namespaces.rs b/example-code/src/concepts/namespaces.rs new file mode 100644 index 00000000..6ba9b6a0 --- /dev/null +++ b/example-code/src/concepts/namespaces.rs @@ -0,0 +1,380 @@ +//! Code from `docs/concepts/namespaces.md` — *Namespaces*. + +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_component(Farewell)] +pub trait CanSayGoodbye { + fn goodbye(&self) -> String; +} + +#[cgp_component(Announcer)] +pub trait CanAnnounce { + fn announce(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +#[cgp_impl(new GreetQuietly)] +impl Greeter { + fn greet(&self) -> String { + "hello".to_owned() + } +} + +#[cgp_impl(new SayGoodbye)] +impl Farewell { + fn goodbye(&self) -> String { + "Goodbye!".to_owned() + } +} + +#[cgp_impl(new AnnounceLoudly)] +impl Announcer { + fn announce(&self) -> String { + "NOW SERVING".to_owned() + } +} + +/// ## Repeating a table across contexts +/// +/// The problem the rest of the page is about: two contexts wanting almost the same set of choices, +/// with nothing in the code to say so. +pub mod repeating_a_table { + use cgp::prelude::*; + + use super::*; + + pub struct App; + pub struct TestApp; + + delegate_components! { + App { + GreeterComponent: GreetHello, + FarewellComponent: SayGoodbye, + AnnouncerComponent: AnnounceLoudly, + } + } + + delegate_components! { + TestApp { + GreeterComponent: GreetQuietly, + FarewellComponent: SayGoodbye, + AnnouncerComponent: AnnounceLoudly, + } + } + + mod check_app { + use super::*; + check_components! { + App { + GreeterComponent, + FarewellComponent, + AnnouncerComponent, + } + } + } +} + +/// ## Routing a component through a path +/// +/// A namespace resolves *paths* rather than bare component names, and a component registers itself +/// at one. Nothing is decided yet: the path is a route, and something further along supplies the +/// provider. +pub mod routing_a_component_through_a_path { + use cgp::prelude::*; + + cgp_namespace! { new AppNamespace {} } + + #[cgp_component(Greeter)] + #[prefix(@app.GreeterComponent in AppNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + pub struct App; + + delegate_components! { + App { + namespace AppNamespace; + + @app.GreeterComponent: GreetHello, + } + } + + mod check_app { + use super::*; + check_components! { App { GreeterComponent } } + } + + #[test] + fn the_lookup_walks_the_path() { + assert_eq!(App.greet(), "Hello!"); + } +} + +/// ## Binding what is shared, leaving open what varies +/// +/// The preset shape. `AppDefaults` binds the leaf every context agrees on and leaves the varying +/// one unbound, so a context supplies one entry and inherits the rest. +pub mod binding_what_is_shared { + use cgp::prelude::*; + + cgp_namespace! { new AppNamespace {} } + + #[cgp_component(Greeter)] + #[prefix(@app.GreeterComponent in AppNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_component(Farewell)] + #[prefix(@app.FarewellComponent in AppNamespace)] + pub trait CanSayGoodbye { + fn goodbye(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + #[cgp_impl(new GreetQuietly)] + impl Greeter { + fn greet(&self) -> String { + "hello".to_owned() + } + } + + #[cgp_impl(new SayGoodbye)] + impl Farewell { + fn goodbye(&self) -> String { + "Goodbye!".to_owned() + } + } + + cgp_namespace! { + new AppDefaults: AppNamespace { + @app.FarewellComponent: SayGoodbye, + } + } + + pub struct App; + pub struct TestApp; + + delegate_components! { + App { + namespace AppDefaults; + + @app.GreeterComponent: GreetHello, + } + } + + delegate_components! { + TestApp { + namespace AppDefaults; + + @app.GreeterComponent: GreetQuietly, + } + } + + mod check_app { + use super::*; + check_components! { App { GreeterComponent, FarewellComponent } } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { GreeterComponent, FarewellComponent } } + } + + #[test] + fn the_contexts_differ_by_one_line() { + assert_eq!(App.greet(), "Hello!"); + assert_eq!(TestApp.greet(), "hello"); + + assert_eq!(App.goodbye(), "Goodbye!"); + assert_eq!(TestApp.goodbye(), "Goodbye!"); + } +} + +/// ## A bound entry is not overridable +/// +/// The rule that decides how a namespace is designed, and the error it produces when broken. Both +/// blocks are rejected. +/// +/// A context re-wiring a key its namespace binds: +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[cgp_component(Greeter)] +/// pub trait CanGreet { fn greet(&self) -> String; } +/// +/// #[cgp_impl(new GreetHello)] +/// impl Greeter { fn greet(&self) -> String { "Hello!".to_owned() } } +/// +/// #[cgp_impl(new GreetQuietly)] +/// impl Greeter { fn greet(&self) -> String { "hello".to_owned() } } +/// +/// cgp_namespace! { +/// new AppDefaults { +/// GreeterComponent: GreetHello, +/// } +/// } +/// +/// pub struct TestApp; +/// +/// // error[E0119]: conflicting implementations of trait +/// // `DelegateComponent` for type `TestApp` +/// delegate_components! { +/// TestApp { +/// namespace AppDefaults; +/// +/// GreeterComponent: GreetQuietly, +/// } +/// } +/// ``` +/// +/// And a child namespace redefining a key it inherits: +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[cgp_component(Greeter)] +/// pub trait CanGreet { fn greet(&self) -> String; } +/// +/// #[cgp_impl(new GreetHello)] +/// impl Greeter { fn greet(&self) -> String { "Hello!".to_owned() } } +/// +/// #[cgp_impl(new GreetQuietly)] +/// impl Greeter { fn greet(&self) -> String { "hello".to_owned() } } +/// +/// cgp_namespace! { +/// new BaseDefaults { +/// GreeterComponent: GreetHello, +/// } +/// } +/// +/// // error[E0119]: conflicting implementations of trait `QuietDefaults<_>` +/// // for type `GreeterComponent` +/// cgp_namespace! { +/// new QuietDefaults: BaseDefaults { +/// GreeterComponent: GreetQuietly, +/// } +/// } +/// ``` +pub mod a_bound_entry_is_not_overridable {} + +/// ## One namespace per configuration +/// +/// The arrangement the rule above points to: the base describes the structure and binds nothing +/// that varies, and each inheriting namespace binds one configuration. +pub mod one_namespace_per_configuration { + use cgp::prelude::*; + + cgp_namespace! { new AppNamespace {} } + + #[cgp_component(Greeter)] + #[prefix(@app.GreeterComponent in AppNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_component(Farewell)] + #[prefix(@app.FarewellComponent in AppNamespace)] + pub trait CanSayGoodbye { + fn goodbye(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + #[cgp_impl(new GreetQuietly)] + impl Greeter { + fn greet(&self) -> String { + "hello".to_owned() + } + } + + #[cgp_impl(new SayGoodbye)] + impl Farewell { + fn goodbye(&self) -> String { + "Goodbye!".to_owned() + } + } + + // Shared structure. The greeter path is deliberately left open. + cgp_namespace! { + new AppDefaults: AppNamespace { + @app.FarewellComponent: SayGoodbye, + } + } + + // One configuration each, binding the open path rather than overriding a bound one. + cgp_namespace! { + new ProductionDefaults: AppDefaults { + @app.GreeterComponent: GreetHello, + } + } + + cgp_namespace! { + new TestDefaults: AppDefaults { + @app.GreeterComponent: GreetQuietly, + } + } + + pub struct App; + pub struct TestApp; + + delegate_components! { + App { + namespace ProductionDefaults; + } + } + + delegate_components! { + TestApp { + namespace TestDefaults; + } + } + + mod check_app { + use super::*; + check_components! { App { GreeterComponent, FarewellComponent } } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { GreeterComponent, FarewellComponent } } + } + + #[test] + fn a_context_is_now_one_line() { + assert_eq!(App.greet(), "Hello!"); + assert_eq!(TestApp.greet(), "hello"); + assert_eq!(App.goodbye(), "Goodbye!"); + } +} diff --git a/example-code/src/concepts/send_bounds.rs b/example-code/src/concepts/send_bounds.rs new file mode 100644 index 00000000..1bf885e2 --- /dev/null +++ b/example-code/src/concepts/send_bounds.rs @@ -0,0 +1,101 @@ +//! Code from `docs/concepts/send-bounds.md` — *Recovering `Send` bounds*. + +use core::future::Future; + +use cgp::prelude::*; + +#[cgp_component(ApiHandler)] +#[async_trait] +pub trait CanHandleApi { + type Response; + + async fn handle_api(&self, _api: PhantomData) -> Self::Response; +} + +pub struct QueryBalance; + +#[cgp_impl(new HandleQueryBalance)] +impl ApiHandler { + type Response = u64; + + async fn handle_api(&self, _api: PhantomData) -> u64 { + 100 + } +} + +pub struct MockApp; + +delegate_components! { + MockApp { + open ApiHandlerComponent; + + @ApiHandlerComponent.QueryBalance: HandleQueryBalance, + } +} + +mod check_mock_app { + use super::*; + check_components! { + MockApp { + ApiHandlerComponent: QueryBalance, + } + } +} + +/// ## The bound a spawning caller needs, and cannot write +/// +/// A work-stealing executor requires the future it drives to be `Send`. A caller generic over the +/// context cannot say so, because the future's auto-traits are hidden behind the trait boundary — +/// the notation for it, Return Type Notation, is not stable. +/// +/// ```compile_fail +/// use core::marker::PhantomData; +/// use cgp_website_example_code::concepts::send_bounds::*; +/// +/// // Not available on stable Rust. +/// fn spawn_handler(app: App) +/// where +/// App: CanHandleApi + Send + 'static, +/// { +/// } +/// ``` +pub mod the_bound_a_caller_cannot_write {} + +/// ## The trait that states the bound directly +/// +/// An ordinary trait — not a component — whose method spells `+ Send` on its return type, which +/// sidesteps the missing notation. +pub trait CanHandleApiSend: CanHandleApi + Send + Sync +where + Self::Response: Send, +{ + fn handle_api_send(&self, api: PhantomData) + -> impl Future + Send; +} + +/// The implementation has to be concrete. At a fixed context and a fixed API the call resolves to a +/// concrete provider producing a concrete future, and the compiler works out for itself that it is +/// `Send`. +impl CanHandleApiSend for MockApp { + async fn handle_api_send(&self, api: PhantomData) -> u64 { + self.handle_api(api).await + } +} + +/// ## What the recovered bound buys +/// +/// A caller can now demand the `Send` future by name. +pub fn requires_a_send_future(app: &App) +where + App: CanHandleApiSend, + App::Response: Send, +{ + let future = app.handle_api_send(PhantomData::); + fn assert_send(_: &T) {} + assert_send(&future); +} + +#[test] +fn the_concrete_impl_satisfies_the_bound() { + requires_a_send_future::(&MockApp); +} diff --git a/example-code/src/concepts/type_level_dsls.rs b/example-code/src/concepts/type_level_dsls.rs new file mode 100644 index 00000000..606d3b16 --- /dev/null +++ b/example-code/src/concepts/type_level_dsls.rs @@ -0,0 +1,90 @@ +//! Code from `docs/concepts/type-level-dsls.md` — *Type-level DSLs*. + +use core::marker::PhantomData; + +use cgp::extra::handler::{Computer, ComputerComponent}; +use cgp::prelude::*; + +/// ## The syntax is types +/// +/// Each fragment of the language is a struct with no data. Its parameters carry the program's +/// structure, and nesting them is how a program is written. +pub struct Literal; +pub struct Add(pub PhantomData<(Left, Right)>); +pub struct Multiply(pub PhantomData<(Left, Right)>); + +/// ## One provider per fragment is the interpreter +/// +/// Each provider matches one shape of `Code` and says what it means. Nothing about the fragment +/// itself decided that. +#[cgp_new_provider] +impl Computer, ()> for EvalLiteral { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData>, _input: ()) -> u64 { + N + } +} + +#[cgp_new_provider] +impl Computer, ()> for EvalAdd +where + Context: CanCompute + CanCompute, +{ + type Output = u64; + + fn compute(context: &Context, _code: PhantomData>, _input: ()) -> u64 { + context.compute(PhantomData::, ()) + context.compute(PhantomData::, ()) + } +} + +#[cgp_new_provider] +impl Computer, ()> for EvalMultiply +where + Context: CanCompute + CanCompute, +{ + type Output = u64; + + fn compute(context: &Context, _code: PhantomData>, _input: ()) -> u64 { + context.compute(PhantomData::, ()) * context.compute(PhantomData::, ()) + } +} + +use cgp::extra::handler::CanCompute; + +/// ## A context assembles the language +/// +/// Each row maps one fragment shape to its interpreter. Adding a fragment is adding a row. +pub struct Interpreter; + +delegate_components! { + Interpreter { + open ComputerComponent; + + @ComputerComponent.Literal.(): EvalLiteral, + @ComputerComponent.Add.(): EvalAdd, + @ComputerComponent.Multiply.(): EvalMultiply, + } +} + +mod check_interpreter { + use super::*; + check_components! { + Interpreter { + ComputerComponent: [ + (Literal<2>, ()), + (Add, Literal<3>>, ()), + (Multiply, Literal<3>>, Literal<4>>, ()), + ], + } + } +} + +/// ## Running a program is type checking it +#[test] +fn the_program_is_a_type_and_the_answer_is_computed_at_compile_time() { + // (2 + 3) * 4 + type Program = Multiply, Literal<3>>, Literal<4>>; + + assert_eq!(Interpreter.compute(PhantomData::, ()), 20); +} From b3e091fdb0f94867afebd75754f121eb8865baa1 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 15:44:55 +0200 Subject: [PATCH 021/516] Cover the whole delegate_components! grammar, with compiled code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The reference page for `delegate_components!` documented four of the macro's forms and left the rest to a line of grammar. It now takes the body along its three axes — the three operators, the three key forms, the two value forms — plus the three statements, and states that they all combine in one block. The `->` and `=>` operators get worked examples rather than a grammar footnote, and the two `@`-path grouping forms are separated: `[…]` holds alternatives for one segment and may be followed by more path, `{…}` holds whole tails and ends it. The layered descent is intact. Nothing moved up out of *Under the hood*; the advanced forms are ordered later on the page rather than dropped, which is the [coverage rule](https://github.com/contextgeneric/cgp-knowledge-base) this page was the occasion for. `cgp_namespace!` and `delegate_and_check_components!` now say which of the shared grammar they support and what happens where they do not. The namespace body parses everything a `delegate_components!` table does, and one reused form — the nested-table value — parses and then fails with `E0425`, which the page shows because the message names a missing type and reads like a typo. The fused check macro gains a table of what is wired versus what is checked: it derives a check only from a mapping keyed on a component name, so path keys, `=>` redirects, and every statement are wired and left silently unchecked. **`docs/reference/` gets its first `example-code` file**, so every form the page shows is compiled with a `check_components!` assertion per wired context and the rejected snippet is a `compile_fail` doctest. That is what turned this from transcription into verification, and it caught the page's own claim back: the legacy nested-table form does not resolve without `#[derive_delegate(UseDelegate)]` on the component, which neither page had said — it is the concrete difference from `open`, whose redirect every component already generates. Co-Authored-By: Claude Opus 5 (1M context) --- docs/reference/macros/cgp_namespace.md | 78 ++- .../macros/delegate_and_check_components.md | 40 +- docs/reference/macros/delegate_components.md | 414 ++++++++++-- example-code/README.md | 2 +- example-code/src/lib.rs | 1 + .../reference/macros/delegate_components.rs | 631 ++++++++++++++++++ example-code/src/reference/macros/mod.rs | 3 + example-code/src/reference/mod.rs | 6 + 8 files changed, 1086 insertions(+), 89 deletions(-) create mode 100644 example-code/src/reference/macros/delegate_components.rs create mode 100644 example-code/src/reference/macros/mod.rs create mode 100644 example-code/src/reference/mod.rs diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 88636b86..f79aff64 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -68,6 +68,27 @@ inherited one. Paths are written with the `@` sigil as dotted sequences — `@My `@app.ErrorRaiserComponent`, `@cgp.core.error` — where lowercase segments become type-level strings and capitalized segments name types. [`Path!`](./path.md) covers the syntax in full. +### The rest of the body grammar + +**A namespace body is parsed by the same code as a +[`delegate_components!`](./delegate_components.md) table**, so everything that macro accepts parses here: +all three operators, all three key forms — including bracketed list keys and `@`-path keys with their +`[…]` and `{…}` groups — per-key generics, and the leading `open`, `namespace`, and `for` statements. That +page documents each of them; what follows is only what differs here. + +What differs is what an entry becomes. A `delegate_components!` entry records a choice *for a context*; a +namespace entry records where a lookup for a key should *go next*, for any context that later joins. That +is why the two forms in the table above are the ones worth writing, and why the others are mostly not: + +- **`->` direct delegation** still projects through the *value's* own table, so it names a concrete table + inside a definition that is meant to be table-generic. +- **`open Component;`** is accepted and generates exactly what `Component => @Component,` generates — + occasionally a convenient spelling for rooting a component's route at its own name. +- **`namespace Other;`** is accepted, but inheritance is written with the `: ParentNamespace` header + above. That is the form overriding and the cycle diagnostics are defined in terms of. +- **A nested table value** — `UseDelegate` — parses and then fails to compile. See + [Gotchas](#gotchas). + ### Inheriting from a parent Name a parent after a colon in the header, and the child resolves everything the parent does plus its own @@ -305,27 +326,19 @@ ParentNamespace -> TypePath GenericArgs? NamespaceBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? ``` -The `Mapping` production is [`delegate_components!`](./delegate_components.md)'s — most often `=>` to an -`@`-`Path`, or `:` to a provider. The `:` between `NamespaceName` and `ParentNamespace` is the inheritance -colon, distinct from a mapping's. `NamespaceName` becomes both a trait and, with `new`, a struct. - -This macro also owns the two statement forms a context's table uses to join a namespace: - -```ebnf -Statement -> NamespaceStmt | ForStmt - -NamespaceStmt -> `namespace` IDENTIFIER `;` +`NamespaceBody` is [`delegate_components!`](./delegate_components.md)'s `TableBody` production unchanged, +so its `Statement` and `Mapping` rules — every operator, every key form, every value form — are defined on +that page rather than restated here. The two a namespace normally uses are `=>` to an `@`-path and `:` to a +provider. The `:` between `NamespaceName` and `ParentNamespace` is the inheritance colon, distinct from a +mapping's. `NamespaceName` becomes both a trait and, with `new`, a struct. -ForStmt -> `for` `<` IDENTIFIER `,` IDENTIFIER `>` `in` TypePath WhereClause? - `{` ( NormalMapping ( `,` NormalMapping )* `,`? )? `}` - -NormalMapping -> Key `:` ProviderValue -``` - -A `NamespaceStmt` forwards every unwired lookup through the named namespace. A `ForStmt` binds a key variable -and a provider variable, reads each entry of the table named after `in`, and emits one mapping per entry; its -optional `WhereClause` is merged into every impl the loop generates. Like `delegate_components!`, the body -accepts **no attributes** on any entry and rejects any it finds. +Two of the three statement forms in that shared production exist for this macro, because their job is +joining a context's table to a namespace. A `NamespaceStmt` — `namespace SomeNamespace;` — forwards every +unwired lookup through the named namespace. A `ForStmt` — +`for in SomeTable where … { … }` — binds a key variable and a provider variable, reads each +entry of the table named after `in`, and emits one mapping per entry; its body admits only the `:` form, +and its optional `where` clause is merged into every impl the loop generates. Like +`delegate_components!`, the body accepts **no attributes** on any entry and rejects any it finds.
@@ -371,6 +384,31 @@ error[E0207]: the type parameter `__Value__` is not constrained by the impl trai Both mean the inheritance chain is not acyclic, but only the first says so recognizably. +**A nested table inside a namespace entry parses and then fails to compile.** The +[`UseDelegate`](./delegate_components.md#the-two-value-forms) value is accepted by the +parser, but `cgp_namespace!` — unlike `delegate_components!` — never lifts the inner table out into its own +struct and impls, so the entry ends up naming a type nothing declares: + +```rust +cgp_namespace! { + new NestedNs { + FooProviderComponent: + UseDelegate, + } +} +``` + +```text +error[E0425]: cannot find type `FooTable` in this scope +``` + +The message names the missing table rather than the unsupported form, so it reads like a typo. Declare the +table in its own `delegate_components! { new FooTable { … } }` block and bind the key to +`UseDelegate` — or, since the nested form is legacy anyway, leave per-type dispatch to the +context and its [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement). + **A registered component with no provider bound anywhere still compiles.** If a `#[prefix]` routes a component into a namespace and nothing ever binds a provider at its path, the redirect lands on an empty slot and the context compiles regardless. Only a [`check_components!`](./check_components.md) reports it, and what it diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index f32ed8e5..88eedc06 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -31,7 +31,7 @@ writing both macros by hand would emit. **It is aimed at simple wiring and at getting started, not at being the default everywhere.** Its value is that a newcomer cannot forget the check and then meet the confusing errors lazy wiring produces. The -derivation understands only the plain `Component: Provider` form, though, so a codebase whose wiring grows +derivation understands only a mapping keyed on a component *name*, though, so a codebase whose wiring grows past that keeps the two macros separate — the reasons are in [When to reach for it](#when-to-reach-for-it-and-when-not). @@ -108,6 +108,34 @@ delegate_and_check_components! { The two per-entry attributes are **mutually exclusive**, and at most one may appear on a given key. +### What is wired, and what is checked + +**The wiring half accepts every form [`delegate_components!`](./delegate_components.md) accepts** — all +three operators, all three key forms including grouped `@`-paths, per-key generics, nested table values, +and the `open`, `namespace`, and `for` statements. Read that page for the grammar; the delegation is +literally the same evaluation. + +**The checking half reads only some of it, and the gap is silent.** Check entries come from the delegation +*keys*, and only a key that names a component can become one: + +| Form | Wired | Checked | +|---|---|---| +| `Component: Provider` | yes | yes | +| `Component -> Table` | yes | yes | +| `[A, B]: Provider` | yes | yes, one per name | +| `@path.Key: Provider` | yes | **no** | +| `Component => @path` | yes | **no** | +| `open` / `namespace` / `for` | yes | **no** | + +Nothing warns about the rows that are not checked: the block compiles, the wiring is correct, and those +components simply go unverified. That silence is the practical reason to split the macros once a table uses +more than plain entries — a standalone [`check_components!`](./check_components.md) block can name the +concrete parameters an opened component needs and cover what a namespace brought in. + +Attributes are accepted only where they mean something. `#[check_params(...)]` and `#[skip_check]` attach +to the table's single and list keys; on an `@`-path key, or inside a `for` loop, they are rejected outright +rather than read and ignored. + ## Examples The intended use — a straightforward context, wired and proven together: @@ -326,10 +354,12 @@ Nothing in it mentions the missing parameters, so it reads like a broken provide check. Add `#[check_params(...)]`, or move the entry to a standalone [`check_components!`](./check_components.md). -**An inherited or opened component is not covered.** A `namespace` header or an `open` statement is accepted -in the table, but the derivation only produces checks for entries it can read as `Component: Provider` — so a -table using either is *partly* checked, with no warning about the rest. Add a standalone -[`check_components!`](./check_components.md) for those. +**An inherited, opened, or redirected component is not covered.** A `namespace` header, an `open` +statement, an `@`-path key, and a `=>` redirect are all accepted in the table and all wired, but the +derivation only produces checks for entries keyed on a component name — so a table using any of them is +*partly* checked, with no warning about the rest. The +[coverage table above](#what-is-wired-and-what-is-checked) says which is which; add a standalone +[`check_components!`](./check_components.md) for the rest. ## Related constructs diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 4681f83c..c25e99d5 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -40,7 +40,16 @@ usable error instead of a dead end. [Under the hood](#under-the-hood) shows both ## Using it -The macro takes a target type and a brace-delimited list of `Key: Value` entries. +The macro takes a target type and a brace-delimited body. The body holds any number of **statements** +followed by any number of **mappings**, and a mapping is a **key**, an **operator**, and a **value** — +three choices you make independently. There are three operators, three key forms, two value forms, and +three statements, and this section takes them in that order. + +**Every one of these forms combines with the others inside a single block.** A table routinely opens a +component for per-type dispatch, joins a namespace, and still maps plain component names to providers +alongside them. The only ordering rule is that statements come first. + +The simplest table needs none of that: ```rust delegate_components! { @@ -71,9 +80,79 @@ position. That is why it must be wired with plain `delegate_components!` and nev [`delegate_and_check_components!`](./delegate_and_check_components.md), whose check asks whether the bundle can use each component *as* a context and so proves nothing either way. -### One provider for several components +### One table for a family of types + +A leading generic list makes the whole table generic, wiring every instantiation at once: + +```rust +delegate_components! { + MyContext { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +### The three operators + +The operator between a key and its value decides what the entry resolves to. The parser accepts any +operator against any key form; which pairings are actually worth writing is noted below. + +| Operator | Reads as | The entry resolves to | +|---|---|---| +| `Key: Provider` | **Name a provider** | that provider, exactly as written | +| `Key -> Table` | **Delegate directly** | whatever `Table`'s own entry for `Key` holds | +| `Key => @path` | **Redirect** | wherever the path lands, resolved later | + +`:` is what nearly all wiring uses, and the rest of this page's examples assume it unless they say +otherwise. + +**`->` is direct delegation.** Instead of naming a provider it forwards the lookup one hop into another +table, and the macro adds a bound requiring that the named table actually has an entry for that key. It +is how one table adopts a single choice from another rather than repeating it: + +```rust +delegate_components! { + new BarComponents { + Index<0>: + FooComponents, // the provider *is* FooComponents + Index<1> -> + FooComponents, // the provider is whatever FooComponents wires for Index<1> + } +} +``` + +Those two lines are worth reading against each other, because the difference is easy to miss. The `:` +entry hands the whole lookup to `FooComponents`; the `->` entry reaches into `FooComponents`'s table +and copies out the one value it holds for that key. + +**`=>` is redirection.** It sends the lookup along a type-level [path](./path.md) rather than to a +provider, so the provider is decided wherever the path finally lands. On a context, that path names a +slot in the context's own table, so several components can be pointed at one shared slot and answered +from a single entry: + +```rust +delegate_components! { + App { + [BarProviderComponent, BazProviderComponent] => + @shared, + + @shared: DummyImpl, + } +} +``` + +This is also the mechanism the `open` statement below is built on: `open AreaCalculatorComponent;` is +another spelling of `AreaCalculatorComponent => @AreaCalculatorComponent,` and generates the same impl. +Its other use is rerouting a whole path *prefix* at once, which is a [namespace](./cgp_namespace.md) +concern more than a per-context one. + +### The three key forms -A bracketed list on the key side expands to one entry per name: +**A single key** is one component name, and may carry generics of its own — ` BazKey: BazProvider` +adds a parameter to just that entry. + +**A list key** is a bracketed list, expanding to one entry per name so several components share one +value: ```rust delegate_components! { @@ -87,18 +166,96 @@ delegate_components! { } ``` -### One table for a family of types +Each bracketed element is a full key, so an element may carry its own generics — in +`[BarKey, BazKey]: BarValue` only the second key introduces `T2`. The list is a +key form rather than an operator, so `[A, B] -> SomeTable` and `[A, B] => @somewhere` are as legal as +`[A, B]: Provider`; the first adopts several of another table's entries at once, the second points +several components at one shared slot. + +**A path key** is an `@`-prefixed route rather than a bare name, and it addresses a slot behind a +redirect: the per-value slots an `open` statement opens, or the prefixed routes a +[namespace](./cgp_namespace.md) registers. `@AreaCalculatorComponent.Rectangle: RectangleArea` stores +`RectangleArea` where the `AreaCalculatorComponent` redirect lands when the dispatch type is +`Rectangle`. Segments follow [`Path!`](./path.md)'s convention — a lowercase, non-primitive identifier +becomes a type-level string, anything else names a type — and a segment may carry generics, as in +`@SomeComponent.<'a, T> &'a T: SomeProvider`. -A leading generic list makes the whole table generic, wiring every instantiation at once: +Two grouping forms fan one path key out into several, and **they are not interchangeable**: + +- **`[…]` groups alternatives for one segment**, and the path may continue after it. + `@app.[FooComponent, BarComponent].[u64, String]: DummyImpl` writes four entries — the cartesian + product of the two groups. +- **`{…}` groups whole remainders**, and ends the path. Its elements may be different lengths and may + nest further groups, which is what lets one entry cover routes of different shapes. ```rust delegate_components! { - MyContext { - AreaCalculatorComponent: RectangleArea, + App { + namespace ExtendedNamespace; + + @app.{ + ErrorRaiserComponent.{&'static str, String}, + ErrorWrapperComponent, + }: RaiseFrom, + } +} +``` + +The shorthand worth remembering is that `[…]` is a choice *within* a segment and `{…}` is a choice *of +tails*. + +### The two value forms + +A value is normally just a type: the provider, or the table a `->` forwards into. One other form +exists, and it is legacy. + +:::info + +### Legacy — read, don't write + +Older code dispatches per type by nesting a table inside a +[`UseDelegate`](../providers/use_delegate.md) value: + +```rust +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +Three details of the form are easy to miss. The inner braces hold a **full table body**, so an inner +table accepts everything an outer one does, nesting included. The **wrapper is not fixed to +`UseDelegate`** — any single-parameter wrapper type is accepted, which is how a component dispatched on +a tuple of parameters gets wired to a matching `UseDelegate2`. And the **inner table's name may carry +generics**, which a per-entry generic on the outer key threads into: + +```rust +delegate_components! { + new MyComponents { + BarKey: UseDelegate { + BazKey: BazValue, + }>, } } ``` +One prerequisite is not visible in either snippet: **the component must carry +[`#[derive_delegate(UseDelegate)]`](../attributes/derive_delegate.md)**, which generates the +dispatch impl the wrapper resolves through. Leave it off and the table still expands, then fails at the +check with an unsatisfied `IsProviderFor` that never mentions the missing attribute. + +This still works, and you will meet it — including in CGP's own error and handler +components, which are defined with `#[derive_delegate]`. The `open` statement below achieves the same +dispatch with no separate table type, no wrapper, and nothing added to the component, and is preferred +for new code. + +::: + ### Choosing a provider per type: the `open` statement When a component is generic over a type parameter, you usually want a different provider for each @@ -117,12 +274,9 @@ delegate_components! { } ``` -The `open` header **must come first**, before any plain `Component: Provider` entries, or the macro -fails to parse. Braces are optional when opening a single component, so `open AreaCalculatorComponent;` -and `open { AreaCalculatorComponent };` are the same; the braced list is only needed to open several at -once. A key may share one provider across several values with the array shorthand on its final segment, -`@AreaCalculatorComponent.[Rectangle, Circle]: SomeProvider`, and may carry generics, -`@SomeComponent.<'a, T> &'a T: SomeProvider`. +Braces are optional when opening a single component, so `open AreaCalculatorComponent;` and +`open { AreaCalculatorComponent };` are the same; the braced list is needed to open several at once, +and a braceless header naming more than one component is rejected. `open` needs no extra attribute on the component: it works through the [`RedirectLookup`](../providers/redirect_lookup.md) impl that every `#[cgp_component]` already @@ -130,41 +284,48 @@ generates. It is a lightweight special case of the full [namespace](./cgp_namesp to a context wiring its own components directly, and it does not combine with a joined namespace where the component carries a `#[prefix(...)]`. -:::info +### The namespace statements -### Legacy — read, don't write +Two further statements opt a context into a [`cgp_namespace!`](./cgp_namespace.md), and both are +described in full on that page, where they are most often written. -Older code dispatches the same way by nesting a table inside a -[`UseDelegate`](../providers/use_delegate.md) value: +**`namespace SomeNamespace;`** joins the namespace, so every lookup the table does not wire directly +falls through to it. **`for in SomeTable { … }`** reads each entry of another lookup table +and emits one mapping per entry, which is how per-type defaults are adopted wholesale; its body holds +only `:` mappings, and an optional `where` clause on the loop constrains the entries it wires. + +### Statements come first + +**Every statement must precede every mapping.** Putting one after a mapping is a *parse* error, so the +message names the unexpected token rather than the ordering rule. Beyond that there is no restriction: +several statements may appear in any order, and they mix freely with the mappings that follow. ```rust delegate_components! { - MyApp { - AreaCalculatorComponent: - UseDelegate, + App { + open AreaCalculatorComponent; + + BarProviderComponent -> BarBundle, + + [BazProviderComponent, QuuxProviderComponent]: DummyBaz, + + @AreaCalculatorComponent.{Rectangle, Circle}: + ShapeArea, + + @AreaCalculatorComponent.[Square, Triangle]: + PolygonArea, } } ``` -This still works, and you will meet it — including in CGP's own error and handler components, which -are defined with [`#[derive_delegate]`](../attributes/derive_delegate.md). The `open` statement above -achieves the same dispatch with no separate table type and no wrapper, and is preferred for new code. +Read as a whole, that is still one table. Every line lowers to the same pair of impls; the forms differ +only in how many entries a line produces and in what each entry resolves to. -::: +### Attributes -### Namespace statements - -Beyond entries and `open`, the table body accepts the statement forms that opt a context into a -[`cgp_namespace!`](./cgp_namespace.md): a leading `namespace SomeNamespace;` header that forwards -unwired lookups through that namespace, `@`-path keys targeting a route rather than a bare component -name, and `for in SomeTable { … }` loops that pull entries from another table. These are -described on the namespace page, where they are most often written. - -The macro accepts **no attributes** on the table or on any key, and rejects any it finds rather than -ignoring them. Attribute-driven variants such as `#[check_params(...)]` and `#[skip_check]` belong to +The macro accepts **no attributes** anywhere — not on the table, not on a key, not on a key inside a +`for` loop or a nested table — and rejects any it finds rather than ignoring them. Attribute-driven +variants such as `#[check_params(...)]` and `#[skip_check]` belong to [`delegate_and_check_components!`](./delegate_and_check_components.md). ## Examples @@ -231,6 +392,22 @@ different fields — and a function generic over `CanCalculateArea` serves both of it happened. Each context's choice stays one greppable line, which is the whole of what a reader has to find to know which implementation runs. +When one context needs a different provider *per type* rather than one provider outright, it opens the +component and fills the slots: + +```rust +pub struct MyApp; + +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.{Circle, Ellipse}: CurveArea, + } +} +``` + ## When to reach for it, and when not Use `delegate_components!` whenever a context needs to choose providers, which is any time you use @@ -244,13 +421,21 @@ compiles, and the failure only surfaces later, where the capability is used. macros apart. - **Use [`delegate_and_check_components!`](./delegate_and_check_components.md)** when you are getting started or the wiring is plain `Component: Provider` entries. It fuses the two so the check cannot be - forgotten. + forgotten. It accepts this whole grammar, but it derives checks only from mappings keyed on a + component *name*, so opened, redirected, and namespaced entries are wired and left unchecked with no + warning. - **Use plain `delegate_components!` with no check** for an **aggregate provider** — the [`new`-keyword form](#defining-the-target-at-the-same-time). That target is a provider other contexts delegate to rather than a context in its own right, so a context-side check on it asks the wrong question: it either passes vacuously or blames the bundle for requirements a real context would have met. Verify it through a context that delegates to it instead. +Two choices inside the table are worth naming as well. Prefer the **`open` statement** over the legacy +nested `UseDelegate` table for per-type dispatch: it needs no separate table type and no wrapper. And +reach for a **[namespace](./cgp_namespace.md)** rather than a longer table once the same wiring is +repeated across contexts, or once one table has grown too long to read — below that threshold, the +extra hop costs more than it saves. + The one thing not to do is leave a context's wiring unchecked. Which macro you use to check it scales with how complicated the wiring is; that it is checked somehow does not. @@ -296,11 +481,32 @@ the `where` bounds it needs, so an unsatisfied requirement flows back through th the point of use. Note that these parameters are literally named `__Context__` and `__Params__` in the emitted code. -The array syntax simply repeats the pair per key. A table pairing -`[FooComponent, BarComponent]` with `FooBarProvider`, alongside a `BazComponent: BazProvider` entry, -yields three `DelegateComponent` impls and three matching `IsProviderFor` impls. +**Every other form on this page lowers to that same pair.** What a form changes is how many pairs one +line produces and what the `Delegate` type is. + +**A list key repeats the pair per name.** A table pairing `[FooComponent, BarComponent]` with +`FooBarProvider`, alongside a `BazComponent: BazProvider` entry, yields three `DelegateComponent` impls +and three matching `IsProviderFor` impls. + +**A `->` mapping projects through the value's table**, and adds the bound that makes the projection +well-formed: + +```rust +impl DelegateComponent> for BarComponents +where + FooComponents: DelegateComponent>, +{ + type Delegate = >>::Delegate; +} +``` + +**A `=>` mapping wires a [`RedirectLookup`](../providers/redirect_lookup.md)** over the table and the +path. Against a plain key the path is complete, so `FooProviderComponent => @MyFooComponent` gives +`RedirectLookup`. Against a path key, both sides instead end in a shared +wildcard parameter, so an entry like `@cgp.core.error => @app` rewrites one path prefix to another and +passes everything beyond it through unchanged. -The `open` statement expands to a redirect plus per-value entries stored on the context itself. The +**The `open` statement** expands to a redirect plus per-value entries stored on the context itself. The header wires the component to a `RedirectLookup` rooted at the component name inside `MyApp`'s own table: @@ -310,8 +516,9 @@ impl DelegateComponent for MyApp { } ``` -Each `@AreaCalculatorComponent.Rectangle: RectangleArea` entry then stores its provider in that same -table under a path key: +which is byte-for-byte what `AreaCalculatorComponent => @AreaCalculatorComponent,` produces. Each +`@AreaCalculatorComponent.Rectangle: RectangleArea` entry then stores its provider in that same table +under a path key: ```rust impl<__Wildcard__> @@ -335,8 +542,32 @@ Both paths above are [`PathCons`](../types/type_level_spines.md) lists, but `car them differently — it resugars the header's redirect target to [`Path!`](./path.md) form while leaving the per-entry key as the raw spine — so the same kind of type appears in two spellings in one expansion. -The legacy nested-table form keys on the same parameter; the difference is only that its per-value -entries live in a separate table type. +**A grouped path key expands to the cartesian product**, one impl pair per combination, each keyed on a +full prefix ending in `__Wildcard__`. So +`@app.[FooProviderComponent, BarProviderComponent].[u64, String]: DummyImpl` emits four pairs, and a +braced group does the same with whole tails rather than single segments, producing keys of different +lengths. + +**A nested-table value lifts its inner table out** into its own definition, wiring the outer entry to +`UseDelegate` over the generated type — so the legacy form is equivalent to writing two separate +`delegate_components!` blocks, the inner one carrying `new`. Its per-value entries key on the same +parameter `open` keys on; the difference is only that they live in a separate table type. + +**The two namespace statements** share one lowering: an impl generic over a `__Key__` and a `__Value__`, +bounded on the namespace trait with a `Delegate = __Value__` binding, which is what makes the namespace's +answer the context's answer. A bare `namespace DefaultNamespace;` produces the blanket form: + +```rust +impl<__Key__, __Value__> DelegateComponent<__Key__> for App +where + __Key__: DefaultNamespace, +{ + type Delegate = __Value__; +} +``` + +A `for` loop produces the same shape once per mapping in its body, plus any predicates its `where` +clause adds.
Formal grammar @@ -354,29 +585,56 @@ Statement -> OpenStmt | NamespaceStmt | ForStmt OpenStmt -> `open` ( `{` Type ( `,` Type )* `,`? `}` | Type ) `;` -Mapping -> Key `:` ProviderValue +NamespaceStmt -> `namespace` IDENTIFIER `;` + +ForStmt -> `for` `<` IDENTIFIER `,` IDENTIFIER `>` `in` TypePath WhereClause? + `{` ( NormalMapping ( `,` NormalMapping )* `,`? )? `}` + +Mapping -> NormalMapping | Key `->` ProviderValue - | Key `=>` Path + | Key `=>` PathValue + +NormalMapping -> Key `:` ProviderValue Key -> SingleKey | MultiKey | PathKey SingleKey -> Generics? Type MultiKey -> `[` SingleKey ( `,` SingleKey )* `,`? `]` -PathKey -> Generics? Path +PathKey -> Generics? `@` PathHead + +PathHead -> PathSegment ( `.` PathHead )? + | `[` PathSegment ( `,` PathSegment )* `,`? `]` ( `.` PathHead )? + | `{` PathHead ( `,` PathHead )* `,`? `}` + +PathSegment -> Generics? Type + +PathValue -> `@` PathSegment ( `.` PathSegment )* ProviderValue -> Type - | IDENTIFIER `<` `new` TargetType `{` TableBody `}` `>` + | IDENTIFIER `<` `new` InnerTable `>` -Path -> `@` PathSegment ( `.` PathSegment )* +InnerTable -> IDENTIFIER GenericArgs? `{` TableBody `}` ``` A leading `Generics` list makes the table generic over the target; `new` additionally emits the target -struct. Each `Mapping` uses one of three operators: `:` maps a key to a provider, which is the common -form, while `->` delegates to the value's own entry for that key and `=>` redirects along an `@`-path; -the latter two belong to the namespace machinery. A `Key` may be a single type, a bracketed list -expanding to one entry per name, or an `@`-path. An `OpenStmt` may omit its braces when opening exactly -one component. `NamespaceStmt`, `ForStmt`, and the `Path` segment rules are defined under -[`cgp_namespace!`](./cgp_namespace.md) and [`Path!`](./path.md). The macro accepts no attributes -anywhere and rejects any it finds. +struct. The operator choice is independent of the key form: `:` maps a key to a provider, `->` delegates +to the value's own entry for that key, and `=>` redirects along a path. `NormalMapping` is named +separately because a `ForStmt` body admits only that form. + +The two grouping forms inside a `PathHead` differ in what they group and in whether the path may +continue. A bracketed group holds alternative segments for one position and may be followed by `.` and +more path; a braced group holds alternative whole remainders and terminates the path, which is why only +the braced form can nest. Both fan out to the cartesian product with the rest of the path. A `PathValue` +— the right-hand side of a `=>` — admits no groups and is [`Path!`](./path.md)'s own production. + +A `ProviderValue`'s nested-table form carries a full `TableBody`, so an inner table accepts every form +an outer one does. An `InnerTable` is an identifier with an optional generic list rather than a full +`TargetType` — a nested table always names a fresh struct the macro declares — and that list is +bound-free; put the bound on the entry's own generics instead. A bound written on the inner table is +rejected as `expected ','`, because the value parser tries the nested-table form speculatively and then +falls back to reading the whole value as a plain type. An `OpenStmt` may omit its braces when opening exactly one component. Every +`Statement` precedes every `Mapping`. `NamespaceStmt` and `ForStmt` are described under +[`cgp_namespace!`](./cgp_namespace.md). The macro accepts no attributes anywhere and rejects any it +finds.
@@ -389,31 +647,61 @@ the answer is to check the table — see [`check_components!`](./check_component [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) in place of `cargo check`, which leads with the root cause for the classes it recognizes. -**The `open` header must lead the block.** Placing it after a plain `Component: Provider` entry is a -parse error rather than a semantic one, so the message will not point at the real problem. +**Statements must lead the block**, and getting it wrong produces a misleading message. Once the +statements are consumed the parser expects only mappings, so it reads the `open` keyword as a *key* and +then complains about the component name where it wanted an operator: + +```text +error: expected `:` +``` + +The caret sits on the component being opened, so the message blames it rather than the misplaced +`open`, and never mentions the ordering rule. + +**`[…]` and `{…}` in a path are not the same group.** A bracketed group holds alternatives for one +segment and may be followed by more path; a braced group holds whole tails and ends the path. So +`@FooProviderComponent.{String, u32}.bool: DummyFoo` does not parse, and the message says nothing about +groups — it reports the trailing `.bool` sitting where the operator should be: + +```text +error: expected `:` +``` + +Use a bracketed group when the path must continue past the alternatives, and a braced group only at the +end. **Naming a provider struct that does not exist** is easy to do when a provider was written with [`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared separately. The error names an unresolved type rather than anything about wiring. +**Two entries claiming one key conflict**, and the compiler reports it as a coherence error rather than +as a wiring one. This covers the obvious duplicate, an `open` header colliding with an explicit mapping +for the same component, and a generic ` Wrapper` entry overlapping a specific `Wrapper` one. +The same applies to a direct entry for a path a joined namespace itself binds — see +[`cgp_namespace!`](./cgp_namespace.md#gotchas). + ## Related constructs - [`#[cgp_component]`](./cgp_component.md) — defines the components this table wires. - [`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_provider]`](./cgp_provider.md) — write the providers it names. - [`check_components!`](./check_components.md) — asserts the table is complete and resolvable. -- [`delegate_and_check_components!`](./delegate_and_check_components.md) — wires and checks together. +- [`delegate_and_check_components!`](./delegate_and_check_components.md) — wires and checks together, + for the plain entries. - [`DelegateComponent`](../traits/delegate_component.md) and [`IsProviderFor`](../traits/is_provider_for.md) — the traits each entry expands into. -- [`RedirectLookup`](../providers/redirect_lookup.md) — what `open` resolves through. +- [`RedirectLookup`](../providers/redirect_lookup.md) — what `open` and `=>` resolve through. +- [`Path!`](./path.md) — the path syntax behind `@`-keys and `=>` values. - [`UseDelegate`](../providers/use_delegate.md) — the legacy dispatch form `open` supersedes. -- [`cgp_namespace!`](./cgp_namespace.md) — reusable tables, for wiring that outgrows one context. +- [`cgp_namespace!`](./cgp_namespace.md) — reusable tables, for wiring that outgrows one context; it + reuses this macro's whole body grammar. - [`UseField`](../providers/use_field.md) — the usual value for a field-backed getter. ## Source - Entry point: [`delegate_components.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/delegate_components.rs) - Implementation: [`types/delegate_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/) +- Path keys and their grouping forms: [`types/path/path_head.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/path/path_head.rs) --- diff --git a/example-code/README.md b/example-code/README.md index 55268a0a..06b24e8e 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -19,7 +19,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — sixteen files under `src/concepts/`, one per page that shows code | -| `docs/reference/` | none yet | +| `docs/reference/` | `macros/delegate_components.md` only — the section is being filled in lazily | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/src/lib.rs b/example-code/src/lib.rs index 48d03dba..e83fd207 100644 --- a/example-code/src/lib.rs +++ b/example-code/src/lib.rs @@ -20,3 +20,4 @@ #![allow(dead_code, unused_variables)] pub mod concepts; +pub mod reference; diff --git a/example-code/src/reference/macros/delegate_components.rs b/example-code/src/reference/macros/delegate_components.rs new file mode 100644 index 00000000..d3504d8f --- /dev/null +++ b/example-code/src/reference/macros/delegate_components.rs @@ -0,0 +1,631 @@ +//! Code from `docs/reference/macros/delegate_components.md` — *`delegate_components!`*. + +/// ## What it's for +/// +/// The page opens on the single-entry table. The component, the provider, and the context it wires +/// are shown further down the page under *Examples*; they are declared here so the opening snippet +/// has something to name. +pub mod what_its_for { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } +} + +/// ## Defining the target at the same time +/// +/// The aggregate-provider bundle. `PerimeterCalculator` and its provider are named by the page +/// without being introduced, so they are declared here. +/// +/// No `check_components!` block appears: the page's own point is that a context-side check on a +/// bundle asks the wrong question. The wiring is verified through `MyApp` below instead. +pub mod defining_the_target_at_the_same_time { + use cgp::prelude::*; + + use super::what_its_for::{AreaCalculatorComponent, RectangleArea}; + + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + #[cgp_impl(new RectanglePerimeter)] + impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } + } + + delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } + } + + /// A real context delegating to the bundle, which is how a bundle is actually verified. + #[derive(HasField)] + pub struct MyApp { + pub width: f64, + pub height: f64, + } + + delegate_components! { + MyApp { + [AreaCalculatorComponent, PerimeterCalculatorComponent]: GeometryComponents, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } + } +} + +/// ## One table for a family of types +/// +/// The page shows only the `delegate_components!` block; the generic context it wires is declared +/// here so the table has a target. +pub mod one_table_for_a_family_of_types { + use core::marker::PhantomData; + + use cgp::prelude::*; + + use super::what_its_for::{AreaCalculatorComponent, RectangleArea}; + + pub struct MyContext(pub PhantomData); + + delegate_components! { + MyContext { + AreaCalculatorComponent: RectangleArea, + } + } +} + +/// ## The three operators +/// +/// The `:`-versus-`->` pair the page contrasts. `FooComponents` is named by the page without being +/// introduced, so it is declared here with the two entries the `->` line reaches into. +pub mod the_three_operators { + use cgp::prelude::*; + + delegate_components! { + new FooComponents { + Index<0>: u64, + Index<1>: String, + } + } + + delegate_components! { + new BarComponents { + Index<0>: + FooComponents, // the provider *is* FooComponents + Index<1> -> + FooComponents, // the provider is whatever FooComponents wires for Index<1> + } + } + + /// The `=>` snippet from the same section: two components pointed at one shared slot. + /// + /// `Bar`, `Baz`, and `DummyImpl` are named by the page without being introduced. + #[cgp_component(BarProvider)] + pub trait Bar { + fn bar(&self); + } + + #[cgp_component(BazProvider)] + pub trait Baz { + fn baz(&self); + } + + #[cgp_impl(new DummyImpl)] + impl BarProvider { + fn bar(&self) {} + } + + #[cgp_impl(DummyImpl)] + impl BazProvider { + fn baz(&self) {} + } + + pub struct App; + + delegate_components! { + App { + [BarProviderComponent, BazProviderComponent] => + @shared, + + @shared: DummyImpl, + } + } + + check_components! { + App { + BarProviderComponent, + BazProviderComponent, + } + } +} + +/// ## The three key forms +/// +/// The list-key table, plus the single key carrying its own generics that the surrounding prose +/// mentions inline. The components and providers are named by the page without being introduced. +/// +/// The page's `{…}`-group snippet is not reproduced here: it wires `ExtendedNamespace` and the error +/// components, which belong to the `cgp_namespace!` page. The two grouping forms are exercised +/// against a local component under [`choosing_a_provider_per_type_the_open_statement`] instead. +pub mod the_three_key_forms { + use core::marker::PhantomData; + + use cgp::prelude::*; + + #[cgp_component(FooProvider)] + pub trait Foo { + fn foo(&self); + } + + #[cgp_component(BarProvider)] + pub trait Bar { + fn bar(&self); + } + + #[cgp_component(BazProvider)] + pub trait Baz { + fn baz(&self); + } + + #[cgp_impl(new FooBarProvider)] + impl FooProvider { + fn foo(&self) {} + } + + #[cgp_impl(FooBarProvider)] + impl BarProvider { + fn bar(&self) {} + } + + #[cgp_impl(new BazProvider2)] + impl BazProvider { + fn baz(&self) {} + } + + delegate_components! { + new MyComponents { + [ + FooProviderComponent, + BarProviderComponent, + ]: FooBarProvider, + BazProviderComponent: BazProvider2, + } + } + + /// The ` BazKey: BazProvider` shape the prose names: a key carrying its own generic + /// parameter, which the key must mention or the generated impl leaves it unconstrained. The + /// page also says a bracketed element may carry generics, so one does here. + /// + /// The key types are declared rather than derived, since a generic key is a type-level lookup + /// key rather than a `#[cgp_component]` marker, which is never generic. + pub struct FooKey(pub PhantomData); + pub struct BarKey(pub PhantomData); + pub struct BazKey(pub PhantomData<(T1, T2)>); + pub struct FooValue; + pub struct BarValue(pub PhantomData); + + delegate_components! { + + GenericKeyComponents { + FooKey: FooValue, + [ + BarKey, + BazKey, + ]: + BarValue, + } + } + + pub struct GenericKeyComponents; +} + +/// ## The two value forms +/// +/// The legacy nested-table value, in both shapes the page's admonition shows: the plain +/// `UseDelegate` dispatch table, and the form whose inner table name carries generics +/// threaded in from a per-entry `` on the outer key. +/// +/// The page names `AreaCalculatorComponents`, `RectangleArea`, and `CircleArea` for the first and +/// `BarKey`/`BarValue`/`BazKey`/`BazValue` for the second; all are declared here. The keys are plain +/// types rather than component markers, which is what an inner dispatch table is keyed on. +pub mod the_two_value_forms { + use core::marker::PhantomData; + + use cgp::prelude::*; + + // `#[derive_delegate]` is what generates the `UseDelegate` dispatch impl, and the legacy form + // does not resolve without it — which is the concrete difference the page draws between this + // form and the `open` statement, whose redirect every `#[cgp_component]` already generates. + #[cgp_component(AreaCalculator)] + #[derive_delegate(UseDelegate)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle; + pub struct Circle; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 0.0 + } + } + + #[cgp_impl(new CircleArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 0.0 + } + } + + pub struct MyApp; + + delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } + } + + /// The generic inner table: the entry's `` reaches the outer key, the wrapper, and the + /// generated `struct BarValue;` alike. + pub struct BarKey(pub PhantomData); + pub struct BazKey; + pub struct BazValue(pub PhantomData); + + delegate_components! { + new GenericInnerComponents { + BarKey: UseDelegate { + BazKey: BazValue, + }>, + } + } +} + +/// ## Choosing a provider per type: the `open` statement +/// +/// The `open` header with its per-value path keys, extended to cover both grouping forms and a +/// generic path segment — the three path-key shapes the section describes. The page shows them +/// against `AreaCalculator`; the shapes are the point, so one component carries all of them here. +pub mod choosing_a_provider_per_type_the_open_statement { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle; + pub struct Circle; + pub struct Ellipse; + pub struct Square; + pub struct Triangle; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 0.0 + } + } + + #[cgp_impl(CurveArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 0.0 + } + } + + pub struct CurveArea; + + #[cgp_impl(PolygonArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 0.0 + } + } + + pub struct PolygonArea; + + pub struct MyApp; + + delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CurveArea, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } + } + + /// The braced group, the bracketed group, and a segment carrying its own generics, on one + /// context — the forms the *three key forms* section contrasts. + pub struct GroupedApp; + + delegate_components! { + GroupedApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.{Circle, Ellipse}: + CurveArea, + + @AreaCalculatorComponent.[Square, Triangle]: + PolygonArea, + + @AreaCalculatorComponent.<'a, T> &'a T: + RectangleArea, + } + } + + check_components! { + GroupedApp { + AreaCalculatorComponent: [ + Circle, + Ellipse, + Square, + Triangle, + <'a> &'a Rectangle, + ], + } + } +} + +/// ## Statements come first +/// +/// The combined block, which is the page's demonstration that the forms mix. `BarBundle` and the +/// providers are named by the page without being introduced. +pub mod statements_come_first { + use cgp::prelude::*; + + use super::choosing_a_provider_per_type_the_open_statement::{ + AreaCalculatorComponent, Circle, PolygonArea, Rectangle, Square, Triangle, + }; + + #[cgp_component(BarProvider)] + pub trait Bar { + fn bar(&self); + } + + #[cgp_component(BazProvider)] + pub trait Baz { + fn baz(&self); + } + + #[cgp_component(QuuxProvider)] + pub trait Quux { + fn quux(&self); + } + + #[cgp_impl(new DummyBar)] + impl BarProvider { + fn bar(&self) {} + } + + #[cgp_impl(new DummyBaz)] + impl BazProvider { + fn baz(&self) {} + } + + #[cgp_impl(DummyBaz)] + impl QuuxProvider { + fn quux(&self) {} + } + + delegate_components! { + new BarBundle { + BarProviderComponent: DummyBar, + } + } + + /// The page names `ShapeArea` and `PolygonArea` as the two shape providers; `ShapeArea` is + /// declared here and `PolygonArea` is reused from the `open` section. + #[cgp_impl(new ShapeArea)] + impl super::choosing_a_provider_per_type_the_open_statement::AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 0.0 + } + } + + pub struct App; + + delegate_components! { + App { + open AreaCalculatorComponent; + + BarProviderComponent -> BarBundle, + + [BazProviderComponent, QuuxProviderComponent]: DummyBaz, + + @AreaCalculatorComponent.{Rectangle, Circle}: + ShapeArea, + + @AreaCalculatorComponent.[Square, Triangle]: + PolygonArea, + } + } + + check_components! { + App { + AreaCalculatorComponent: [Rectangle, Circle, Square, Triangle], + BarProviderComponent, + BazProviderComponent, + QuuxProviderComponent, + } + } +} + +/// ## Examples +/// +/// The two-context payoff the page builds to: the same capability answered differently by two +/// contexts, and a generic function serving both. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + pub fn print_area(rect: &Rectangle) { + println!("area = {}", rect.area()); + } + + #[cgp_impl(new SquareArea)] + impl AreaCalculator { + fn area(&self, #[implicit] side: f64) -> f64 { + side * side + } + } + + #[derive(HasField)] + pub struct Square { + pub side: f64, + } + + delegate_components! { + Square { + AreaCalculatorComponent: SquareArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + check_components! { + #[check_trait(__CheckSquare2)] + Square { + AreaCalculatorComponent, + } + } + + /// The page's claim that one generic function serves both contexts. + pub fn total_area(shapes: &[&dyn Fn() -> f64]) -> f64 { + shapes.iter().map(|f| f()).sum() + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn each_context_answers_through_its_own_provider() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + let square = Square { side: 5.0 }; + + assert_eq!(rectangle.area(), 12.0); + assert_eq!(square.area(), 25.0); + } + } +} + +/// ## Gotchas +/// +/// The page's rejected snippet: a braced path group followed by more path. A braced group holds +/// whole tails and therefore ends the path, so the trailing `.bool` sits where the mapping's +/// operator should be and the macro reports `expected ':'`. +/// +/// The bracketed form, which the page offers as the fix, is exercised above under +/// [`choosing_a_provider_per_type_the_open_statement`]. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[cgp_component(FooProvider)] +/// pub trait Foo { +/// fn foo(&self, value: &T); +/// } +/// +/// #[cgp_impl(new DummyFoo)] +/// impl FooProvider { +/// fn foo(&self, _value: &T) {} +/// } +/// +/// pub struct App; +/// +/// // error: expected `:` +/// delegate_components! { +/// App { +/// open FooProviderComponent; +/// +/// @FooProviderComponent.{String, u32}.bool: DummyFoo, +/// } +/// } +/// ``` +pub mod gotchas {} diff --git a/example-code/src/reference/macros/mod.rs b/example-code/src/reference/macros/mod.rs new file mode 100644 index 00000000..b992d150 --- /dev/null +++ b/example-code/src/reference/macros/mod.rs @@ -0,0 +1,3 @@ +//! Code from the pages under `docs/reference/macros/`. + +pub mod delegate_components; diff --git a/example-code/src/reference/mod.rs b/example-code/src/reference/mod.rs new file mode 100644 index 00000000..ce833e2c --- /dev/null +++ b/example-code/src/reference/mod.rs @@ -0,0 +1,6 @@ +//! Code from the pages under `docs/reference/`, one module per page. +//! +//! The section is filled in lazily, so the modules here are the pages someone has written, revised, +//! or reviewed rather than the section's full inventory. + +pub mod macros; From 1aac8062eba7d731a1969bb162624149930142fd Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 16:01:36 +0200 Subject: [PATCH 022/516] Drop the nested-table gotcha from `cgp_namespace!` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The page warned that a nested `UseDelegate` value in a namespace body parses and then fails with `E0425`, and offered two ways around it. The library no longer drops the inner table, so the warning describes nothing a reader can hit. The form is now listed among the shared body grammar as one that works, with the reason to reach for it: the dispatch table lives in the namespace, so every context joining inherits the per-type wiring without restating it. It still needs `#[derive_delegate]` on the component, as the legacy form does anywhere, which the entry says rather than leaving to be discovered. Co-Authored-By: Claude Opus 5 (1M context) --- docs/reference/macros/cgp_namespace.md | 31 ++++---------------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index f79aff64..cdbcbebd 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -86,8 +86,10 @@ is why the two forms in the table above are the ones worth writing, and why the occasionally a convenient spelling for rooting a component's route at its own name. - **`namespace Other;`** is accepted, but inheritance is written with the `: ParentNamespace` header above. That is the form overriding and the cycle diagnostics are defined in terms of. -- **A nested table value** — `UseDelegate` — parses and then fails to compile. See - [Gotchas](#gotchas). +- **A nested table value** — `UseDelegate` — works, and is the one legacy form with a + reason to live in a namespace: the macro lifts the inner table out into its own struct and impls, so + every context joining the namespace inherits the per-type dispatch without restating it. It still + needs [`#[derive_delegate]`](../attributes/derive_delegate.md) on the component, as it does anywhere. ### Inheriting from a parent @@ -384,31 +386,6 @@ error[E0207]: the type parameter `__Value__` is not constrained by the impl trai Both mean the inheritance chain is not acyclic, but only the first says so recognizably. -**A nested table inside a namespace entry parses and then fails to compile.** The -[`UseDelegate`](./delegate_components.md#the-two-value-forms) value is accepted by the -parser, but `cgp_namespace!` — unlike `delegate_components!` — never lifts the inner table out into its own -struct and impls, so the entry ends up naming a type nothing declares: - -```rust -cgp_namespace! { - new NestedNs { - FooProviderComponent: - UseDelegate, - } -} -``` - -```text -error[E0425]: cannot find type `FooTable` in this scope -``` - -The message names the missing table rather than the unsupported form, so it reads like a typo. Declare the -table in its own `delegate_components! { new FooTable { … } }` block and bind the key to -`UseDelegate` — or, since the nested form is legacy anyway, leave per-type dispatch to the -context and its [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement). - **A registered component with no provider bound anywhere still compiles.** If a `#[prefix]` routes a component into a namespace and nothing ever binds a provider at its path, the redirect lands on an empty slot and the context compiles regardless. Only a [`check_components!`](./check_components.md) reports it, and what it From e2de57df45fa7abe2cc5d0a9a52684d1563a83b3 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 16:26:45 +0200 Subject: [PATCH 023/516] Publish the agent skill from its own repository, not a copy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The AI section carried the skill inlined into `index.md` by hand, and it had gone a whole release stale: a v0.7.0 text teaching `#[use_type(Trait::Type)]` with `::`, nested `UseDelegate` tables as the way to dispatch, no namespaces, and no mention of `cargo-cgp`. A hand-copied skill was always going to drift, because nothing connects the copy to its source but somebody remembering. `cgp-skills` is now a submodule at `docs/ai/skills/cgp-skills`, and every published page is a symlink into it — `SKILL.md` and one page per file under `cgp/references/`. The site serves the skill's own bytes at a pinned revision, so the page cannot say something the skill does not. `index.md` keeps only what is ours to write: what the skill is for, how to install it, and a plain statement that it teaches the assistant rather than the reader, with anyone actually learning CGP routed to the tutorials and concepts instead. Three settings depart from stock Docusaurus, each forced by publishing markdown this repository does not own. `markdown.format` is `detect`, so `.md` parses as CommonMark and only `.mdx` as MDX. The skill is plain markdown written by a repository with no reason to know about MDX, and MDX reads an autolink like `` as a JSX tag and fails the build. Nothing else is affected: no page on this site uses MDX-only syntax, so no existing rendering changes. A one-function plugin sets webpack's `resolve.symlinks` to `false`. Resolved to its real path, a symlinked page no longer matches the metadata the docs plugin registered against the symlink, and all sixteen die at render with `Cannot read properties of undefined (reading 'id')`. The docs plugin excludes `**/cgp-skills/**`, so the submodule's README and `AGENTS.md` do not become pages. And both workflows check out with `submodules: recursive`, without which the build fails on missing files. Two consequences are known and accepted. The skill cites the knowledge base by deep GitHub URL about ninety times, which is deliberate — these pages are prose written for agents and the index says so before a reader reaches them. And Docusaurus anchors only `h2`/`h3`, so the sections of the three files that use `#` for headings get no anchor and no table-of-contents entry; fixing that means demoting headings upstream, which is the skill's shape to decide. Co-Authored-By: Claude Opus 5 (1M context) --- .github/workflows/deploy.yaml | 3 + .github/workflows/test-deploy.yaml | 3 + .gitmodules | 3 + docs/ai/skills/SKILL.md | 1 + docs/ai/skills/cgp-skills | 1 + docs/ai/skills/index.md | 2274 +---------------- docs/ai/skills/references/abstract-types.md | 1 + docs/ai/skills/references/checking.md | 1 + docs/ai/skills/references/components.md | 1 + docs/ai/skills/references/error-extraction.md | 1 + docs/ai/skills/references/error-handling.md | 1 + docs/ai/skills/references/extensible-data.md | 1 + .../references/functions-and-getters.md | 1 + docs/ai/skills/references/handlers.md | 1 + .../references/higher-order-providers.md | 1 + docs/ai/skills/references/macro-grammar.md | 1 + docs/ai/skills/references/modern-idioms.md | 1 + .../skills/references/modularity-hierarchy.md | 193 +- docs/ai/skills/references/namespaces.md | 1 + .../references/type-level-primitives.md | 1 + docs/ai/skills/references/wiring.md | 1 + docusaurus.config.ts | 33 + 22 files changed, 98 insertions(+), 2427 deletions(-) create mode 100644 .gitmodules create mode 120000 docs/ai/skills/SKILL.md create mode 160000 docs/ai/skills/cgp-skills create mode 120000 docs/ai/skills/references/abstract-types.md create mode 120000 docs/ai/skills/references/checking.md create mode 120000 docs/ai/skills/references/components.md create mode 120000 docs/ai/skills/references/error-extraction.md create mode 120000 docs/ai/skills/references/error-handling.md create mode 120000 docs/ai/skills/references/extensible-data.md create mode 120000 docs/ai/skills/references/functions-and-getters.md create mode 120000 docs/ai/skills/references/handlers.md create mode 120000 docs/ai/skills/references/higher-order-providers.md create mode 120000 docs/ai/skills/references/macro-grammar.md create mode 120000 docs/ai/skills/references/modern-idioms.md mode change 100644 => 120000 docs/ai/skills/references/modularity-hierarchy.md create mode 120000 docs/ai/skills/references/namespaces.md create mode 120000 docs/ai/skills/references/type-level-primitives.md create mode 120000 docs/ai/skills/references/wiring.md diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index 2c234450..113b6d21 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -15,6 +15,9 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 + # The skill pages under docs/ai/skills/ are symlinks into the + # cgp-skills submodule; without it the build fails on missing files. + submodules: recursive - uses: actions/setup-node@v4 with: node-version: 20 diff --git a/.github/workflows/test-deploy.yaml b/.github/workflows/test-deploy.yaml index 1393d076..285ba682 100644 --- a/.github/workflows/test-deploy.yaml +++ b/.github/workflows/test-deploy.yaml @@ -15,6 +15,9 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 + # The skill pages under docs/ai/skills/ are symlinks into the + # cgp-skills submodule; without it the build fails on missing files. + submodules: recursive - uses: actions/setup-node@v4 with: node-version: 20 diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..dace63f4 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "cgp-skills"] + path = docs/ai/skills/cgp-skills + url = https://github.com/contextgeneric/cgp-skills.git diff --git a/docs/ai/skills/SKILL.md b/docs/ai/skills/SKILL.md new file mode 120000 index 00000000..a71bbb56 --- /dev/null +++ b/docs/ai/skills/SKILL.md @@ -0,0 +1 @@ +cgp-skills/cgp/SKILL.md \ No newline at end of file diff --git a/docs/ai/skills/cgp-skills b/docs/ai/skills/cgp-skills new file mode 160000 index 00000000..e0f72c2d --- /dev/null +++ b/docs/ai/skills/cgp-skills @@ -0,0 +1 @@ +Subproject commit e0f72c2d0e93367aa8f8f6ecd69624f539254f08 diff --git a/docs/ai/skills/index.md b/docs/ai/skills/index.md index 231020d3..aac6d9cf 100644 --- a/docs/ai/skills/index.md +++ b/docs/ai/skills/index.md @@ -2,2255 +2,59 @@ sidebar_position: 1 --- -# CGP Skills +# CGP's Agent Skill -## Using Agent Skills to Learn CGP +CGP publishes an [agent skill](https://agentskills.io/): a set of Markdown files that teach an LLM +coding assistant how to read, write, and debug CGP code. It lives in the +[**cgp-skills** repository](https://github.com/contextgeneric/cgp-skills), and the pages in this +section are that skill, published here unchanged. -This page provides [**agent skills**](https://agentskills.io/) for [Context-Generic Programming (CGP)](https://contextgeneric.dev/) in Rust. These skills are designed to teach LLM-based coding agents about CGP concepts and best practices, enabling them to provide better assistance when writing CGP code. +## What it is for -You can use the skills from the [cgp-skills repository](https://github.com/contextgeneric/cgp-skills) to enhance your LLM coding assistant with comprehensive knowledge of CGP. The simplest way to use the skill is to download the [`SKILL.md`](https://raw.githubusercontent.com/contextgeneric/cgp-skills/refs/heads/main/cgp/SKILL.md) file and attach it to the context window of any LLM of your choice before asking questions. +An assistant that has not met CGP treats it as ordinary Rust and gets the wiring wrong: it reaches for +a plain trait impl where a provider belongs, or writes a `delegate_components!` table it cannot then +explain. The skill supplies the missing vocabulary — consumer and provider traits, wiring, impl-side +dependencies — along with the code each macro expands to and how to read the errors CGP produces. -The skill content is provided inline throughout the rest of this document for your reference, allowing you to understand the concepts that are taught to the LLM agent. +That is a narrow claim, and it is worth keeping narrow. The skill teaches the assistant, not you. It +does not make CGP simpler, and an assistant using it still writes code you have to review. ---- - -## Introduction - -CGP is a modular programming paradigm that provides workaround on the coherence restrictions in Rust. You can write multiple overlapping or orphan trait implementations implementations in CGP, and then wire them through a concrete context. - -## Blanket Traits - -CGP evolves from the use of blanket trait implementations, also commonly called extension traits. This is widely used in Rust today with examples like `StreamExt` and `IterTools`. But CGP takes this concept and pushes it much further. - -The core idea of CGP is that we can use the `where` clause of a blanket trait impl to hide the constraints needed from the trait interface. - -For example, given: - -```rust -pub trait CanGreet { - fn greet(&self); -} - -pub trait HasName { - fn name(&self) -> &str; -} - -impl CanGreet for Context -where - Context: HasName, -{ - fn greet(&self) { - println!("Hello, {}!", self.name()); - } -} -``` - -The blanket implementation of `CanGreet` above hides the `HasName` dependency from the trait interface. - -This concept of hiding constraints inside blanket impls is also known as **impl-side dependencies**, or dependency injection. - -Blanket traits are preferred over generic functions, because they provide cleaner interface and don't require the caller to specify all constraints, in case if the caller is also generic. - -For example, if `CanGreet` is defined as a generic function instead: - -```rust -pub fn greet(context: &Context) -where - Context: HasName, -{ - println!("Hello, {}!", context.name()); -} -``` - -then the all transitive callers of `greet` would also need to specify the `Context: HasName` constraint, which can be tedious to manage. - -Note that blanket traits are not CGP components, but it is commonly used together with CGP. In particular, it is preferred to start writing generic code as blanket traits instead of generic functions first. And then if there is a need for multiple alternative implementations, we can easily convert the blanket trait into a CGP component later. - -## Prelude - -Almost all CGP constructs are imported through the prelude: - -```rust -use cgp::prelude::*; -``` - -The prelude should be imported in all Rust modules that use CGP constructs. You can omit the import of prelude inside example code blocks within documentation. - -The current version of CGP is v0.7.0. All explanation on this document is based on this version. - -## `#[cgp_component]` Macro - -The `#[cgp_component]` macro is used to enable CGP capabilities on a trait. For example: - -```rust -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self) -> f64; -} -``` - -The original trait, i.e. `CanCalculateArea`, is now called a **consumer trait**. A CGP consumer trait is typically named in the verb format, e.g. `CanDoSomething`. - -We also call the fully expanded constructs a CGP trait, or a CGP component. For example, the full constructs can be called the `AreaCalculator` component. - -## Provider Traits - -The argument to `#[cgp_component]` is the name of the **provider trait**, which is generated by the macro as follows: - -```rust -pub trait AreaCalculator { - fn area(context: &Context) -> f64; -} -``` - -In the provider trait, the original `Self` type is moved to an explicit generic parameter called `Context`. - -All references to the original `self` or `Self` are converted to refer to `context` or `Context`. - -The new `Self` position in the provider trait will be implemented by unique and dummy provider types, which will act as the provider's name. - -A CGP provider trait is typically named in the noun format, e.g. `SomethingDoer`. When no suitable postfix is avaiable, the `Provider` postfix is used instead, e.g. `SomethingProvider`. - -For example, one can write a blanket implementation for `AreaCalculator` as follows: - -```rust -pub struct RectangleArea; - -impl AreaCalculator for RectangleArea -where - Context: HasRectangleFields, -{ - fn area(context: &Context) -> f64 { - context.width() * context.height() - } -} -``` - -The provider name `RectangleArea` is defined as a local dummy struct. - -The implementation of `AreaCalculator` can be generic over any `Context` type that implements `HasRectangleFields`. - -The usual coherence restrictions don't apply, because the `Self` type `RectangleArea` is owned by the same crate. This allows any number of such blanket provider trait implementations to be defined in any crate. - -Note that the provider value, i.e. the `self` value, is not used anywhere in the provider trait implementation. This means that the provider struct is effectively a type-level-only entity, with no usable value at runtime. - -It is a common mistake to attempt to define fields in the provider struct, and attempt to pass or access it during runtime. Such fields will not be accessible at runtime. - -## Component Name - -The macro generates a component name type with a `Component` postfix, i.e.: - -```rust -pub struct AreaCalculatorComponent; -``` - -The macro also generates blanket implementations to allow delegation of the implementation of a consumer or provider trait to a different provider, which will be explained later. - -## `IsProviderFor` Trait - -CGP uses `IsProviderFor` as a hack to force the Rust compiler to show the appropriate error message when there is an unsatisfied dependency: - -```rust -pub trait IsProviderFor {} -``` - -The trait is used as a dummy marker trait that can be trivially implemented, but is deliberately implemented with additional constraints to capture the dependencies to be shown in compile errors. - -The earlier example provider trait definition for `AreaCalculator` was a simplification, the actual definition is: - -```rust -pub trait AreaCalculator: IsProviderFor { - fn area(context: &Context) -> f64; -} -``` - -The first argument to `IsProviderFor` is the component name, i.e. `AreaCalculatorComponent`. The second argument is the `Context` type. The third argument captures any additional generic parameters as a tuple. - -When implementing a provider trait, the provider also needs to implement `IsProviderFor` with the same constraints it uses to implement the provider trait. For example: - -```rust -impl IsProviderFor for RectangleArea -where - Context: HasRectangleFields, -{} -``` - -This will ensure that if a concrete context does not implement `HasRectangleFields`, the error will show the missing dependency via `IsProviderFor`. - -## `#[cgp_provider]` Macro - -The `#[cgp_provider]` macro removes the need to manually implement `IsProviderFor`, by auto generating the implementation from the provider impl. - -The `#[cgp_new_provider]` macro has the same behavior as `#[cgp_provider]`, but also defines the provider struct automatically. - -For example, the following: - -```rust -#[cgp_new_provider] -impl AreaCalculator for RectangleArea -where - Context: HasRectangleFields, -{ ... } -``` - -is the same as: - -```rust -pub struct RectangleArea; - -#[cgp_provider] -impl AreaCalculator for RectangleArea -where - Context: HasRectangleFields, -{ ... } -``` - -which is then desugared to: - -```rust -impl AreaCalculator for RectangleArea -where - Context: HasRectangleFields, -{ ... } - -impl IsProviderFor for RectangleArea -where - Context: HasRectangleFields, -{} -``` - -Whenever possible, avoid mentioning `IsProviderFor` to the user, and use the simplified provider trait definition. - -When error messages say that `IsProviderFor` is not implemented, translate it to mean that the provider trait is not implemented. - -## `#[cgp_impl]` Macro - -The `#[cgp_impl]` macro further simplify the definition of provider implementations, to make it look less confusing to readers. - -For example: - -```rust -#[cgp_impl(new RectangleArea)] -impl AreaCalculator for Context -where - Self: HasRectangleFields, -{ - fn area(&self) -> f64 { - self.width() * self.height() - } -} -``` - -is the same as: - -```rust -#[cgp_new_provider] -impl AreaCalculator for RectangleArea -where - Context: HasRectangleFields, -{ - fn area(context: &Context) -> f64 { - context.width() * context.height() - } -} -``` - -The `Context` parameter in `#[cgp_impl]` is in the same `Self` position as the consumer trait, to make it look like blanket implementations. - -The provider name is specified in the attribute argument for `#[cgp_impl]`. An optional `new` keyword can be given to automatically define the provider struct. - -The macro also allows the use of `self` and `Self` to refer to the generic `Context` value and type. - -Behind the scenes, the `#[cgp_impl]` macro desugars to `#[cgp_provider]` by moving the `Context` type back to the first generic parameter of the provider trait, and use the given provider name type as the `Self` type. Behind the scenes, all references to `self` or `Self` are automatically converted by `#[cgp_impl]` back to refer to the explicit `context` or `Context`. - -As previously noted, the `Self` type and `self` value inside `#[cgp_impl]` refers to the `Context` type, *not* the provider struct. There is no provider value accessible during runtime. - -When the provider implementation targets a generic `Context` type, the `for Context` part can be omitted, and the macro will automatically insert the generic parameter. For example, the earlier example can be further simplified as: - -```rust -#[cgp_impl(new RectangleArea)] -impl AreaCalculator -where - Self: HasRectangleFields, -{ - fn area(&self) -> f64 { - self.width() * self.height() - } -} -``` - -The omission of the generic `Context` improves the ergonomic of CGP, as it makes the code looks like OOP class implementation with no generics involved. - -Whenever possible, use `#[cgp_impl]` to write and explain provider implementations, and omit the generic `Context` type. Avoid showing the user `#[cgp_provider]` or `IsProviderFor`, unless they are needed to explain the internal mechanics of CGP. - -## `DelegateComponent` Trait - -The `DelegateComponent` trait is defined as follows: - -```rust -pub trait DelegateComponent { - type Delegate; -} -``` - -This is mainly used to turn a type implementing `DelegateComponent` into a type-level table. - -The `Component` generic parameter acts as the "key" type, and the `Delegate` associated type acts as the "value" type to be read from the type-level table. - -For example, given the following: - -```rust -impl DelegateComponent for MyComponents { - type Delegate = Bar; -} -``` - -The code above "sets" the entry `Foo` in the `MyComponents` table to have `Bar` as the "value" type. - -## Provider Trait Delegation - -The `#[cgp_component]` macro generates a blanket implementation for the provider trait for the example `CanCalculateArea` component earlier: - -```rust -impl AreaCalculatorProvider for Provider -where - Provider: DelegateComponent, - Provider::Delegate: AreaCalculatorProvider + IsProviderFor, -{ - fn area(context: &Context) -> f64 { - Context::Delegate::area(context) - } -} -``` - -Essentially, this allows a provider to delegate the implementation of a provider trait to another provider. - - -The blanket implementation use `Provider` as the type-level table. The blanket implementation essentially uses the generated `AreaCalculatorComponent` struct as a key, and reads the entry stored on `Provider`'s type-level table. - -If the `Delegate` "value" type implements the provider trait `AreaCalculator` for the `Context` type, then `Provider` would automatically also implement the `AreaCalculator` through the blanket implementation. - -The blanket implementation implements the method and other trait items by forwarding them to the delegated provider. - -The additional `IsProviderFor` constraint is used to forward the constraints in the provider trait implementation down the delegation chain. - -If possible, avoid showing the `IsProviderFor` constraint when explaining to the user the high level concepts. Whenever possible, do not show the user the generated blanket implementation for the provider trait. Instead explain using high-level concepts like table lookup. - -## Consumer Trait Delegation - -The `#[cgp_component]` macro generates the following blanket implementation for the example `CanCalculateArea` component earlier: - -```rust -impl CanCalculateArea for Context -where - Context: AreaCalculator, -{ - fn area(&self) -> f64 { - Context::area(self) - } -} -``` - -Essentially, a `Context` type implements the consumer trait `CanCalculateArea`, if it implements the provider trait `AreaCalculator` for itself as the context type. - -When `DelegateComponent` is used on a `Context` type, it implements the provider trait for the `Context` type if the delegated provider implements the provider trait for the `Context` type. This makes `Context` its own provider. The blanket implementation of the consumer trait then uses that blanket provider trait implementation to implement the consumer trait for the `Context` type. - -Following the earlier example, this allows the consumer trait to be defined on a custom context such as follows: - -```rust -pub struct Rectangle { - pub width: f64, - pub height: f64, -} - -impl HasRectangleFields for Rectangle { - fn width(&self) -> f64 { - self.width - } - - fn height(&self) -> f64 { - self.height - } -} - -impl DelegateComponent for Rectangle { - type Delegate = RectangleArea; -} -``` - -The example `Rectangle` struct above implements `HasRectangleFields`, and then delegate the implementation of `CanCalculateArea` to the `RectangleArea` provider. - -This is done by implementing `DelegateComponent` with `AreaCalculatorComponent` used as the "key", and `RectangleArea` used as the "value" for `Rectangle`'s type-level table. - -With that, `Rectangle` now implements `AreaCalculator` through the blanket implementation of the provider trait. After that, it implements `CanCalculateArea` through the blanket implementation of the consumer trait. - -Whenever possible, do not show the user the generated blanket implementation for the consumer trait. Instead explain using high-level concepts like table lookup. - -## `delegate_components!` Macro - -The `delegate_components!` macro is commonly used to simplify the definition of type-level tables through the `DelegateComponent` trait. - -For example, given the following: - -```rust -delegate_components! { - Rectangle { - AreaCalculatorComponent: - RectangleArea, - } -} -``` - -would generate the following `DelegateComponent` and `IsProviderFor` implementation: - -```rust -impl DelegateComponent for Rectangle { - type Delegate = RectangleArea; -} - -impl IsProviderFor for Rectangle -where - RectangleArea: IsProviderFor -{} -``` - -The first argument to `delegate_components!`, i.e. `Rectangle`, designates the target type where the type-level table is defined, or which the `DelegateComponent` trait will be implemented by. - -The `IsProviderFor` implementation helps the propagation of the provider trait constraints. This allows a provider to implement a provider trait through `delegate_components!`, and at the same time keep track of the dependencies. - -Whenever possible, try to avoid mentioning the generation of the `IsProviderFor` implementation inside `delegate_components!`. - -## Explicit Delegation - -It is possible to skip the use of `delegate_components!`, and implement the consumer trait directly on the concrete context. - -For example, given the following: - -```rust -delegate_components! { - Rectangle { - AreaCalculatorComponent: - RectangleArea, - } -} -``` - -we can instead write: - -```rust -impl HasArea for Rectangle { - fn area(&self) -> f64 { - >::area(self) - } -} -``` - -The manual delegation is much more verbose, but it is much easier to understand as compared to the use of `delegate_components!`, `DelegateComponent`, and the blanket implementations. - -When explaining the concepts behind `delegate_components!`, we can use the explicit delegation to demonstrate what the code effectively does, without requiring the reader to fully understand the trait machinery behind CGP. - -## Direct Implementation of Consumer Trait - -Aside from explicit delegation, the user can always implement a consumer trait directly on a concrete context, if they don't care about code reuse: - -```rust -impl HasArea for Rectangle { - fn area(&self) -> f64 { - self.width * self.height - } -} -``` - -It is important to highlight the possibility of directly implementing a consumer trait. This demonstrates that CGP traits are superset of vanilla Rust traits. And if the user prefers, they can always use or implement it like a regular Rust trait. - -### Array Syntax in `delegate_components!` - -The `delegate_components!` macro also supports array syntax, in case when multiple type-level keys map to the same value. For example: - -```rust -delegate_components! { - MyComponents { - [ - FooComponent, - BarComponent, - ]: - FooBarProvider, - BazComponent: - BazProvider, - } -} -``` - -is the same as: - -```rust -delegate_components! { - MyComponents { - FooComponent: - FooBarProvider, - BarComponent: - FooBarProvider, - BazComponent: - BazProvider, - } -} -``` - -which is eventually desugared to: - -```rust -impl DelegateComponent for MyComponents { - type Delegate = FooBarProvider; -} - -impl DelegateComponent for MyComponents { - type Delegate = FooBarProvider; -} - -impl DelegateComponent for MyComponents { - type Delegate = BazProvider; -} -``` - -### `new` in `delegate_components!` - -The `delegate_components!` macro supports an optional `new` keyword in front of the target table type, to automatically define the type for the user. For example: - -```rust -delegate_components! { - new MyComponents { - FooComponent: - FooBarProvider, - ... - } -} -``` - -would also generate a `struct MyComponents;` definition. - -Whenever possible, do not show the user the use of the `DelegateComponent` trait. Instead explain to them using high level concepts, such as that a type-level table is constructed for `MyComponents` using `delegate_components!`. - -## Type-Level List - -CGP commonly uses type-level lists, a.k.a product types, to represent a list of types. - -A type-level list is defined as `Product![A, B, C]`, which is desugared as: - -```rust -π>> -``` - -or in a human-readable form: - - -```rust -Cons>> -``` - -The types `Cons` and `Nil` are defined as: - -```rust -pub struct π(pub Head, pub Tail); -pub struct ε; -pub use {ε as Nil, π as Cons}; -``` - -The greek alphabets like `π` and `ε` are used to shorten the representation of these types when displayed by the Rust compiler in places like error messages. - -Whenever possible, you should prefer the syntactic sugar forms like `Product!` or the human readable forms like `Cons`. - -## Type-Level Strings - -CGP uses type-level strings to represent field names as types, in the form of `Symbol!("string value")`. - -The macro desugars a type-level string like `Symbol!("abc")` into follows: - -```rust -ψ<3, ζ<'a', ζ<'b', ζ<'c', ε>>>> -``` - -or in a readable form: - -```rust -Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>> -``` - -The types `Symbol` and `Chars` are defined as: - -```rust -pub struct ζ(pub PhantomData); -pub struct ψ(pub PhantomData); -pub use {ψ as Symbol, ζ as Chars}; -``` - -The `Chars` type is essentially a short hand for defining a type-level list of characters. - -The `Symbol` type is used to compute the string length at compile time. This is to workaround the lack of const-generics evaluation in stable Rust. - -## `Index` Type - -CGP supports use of type-level natural numbers through the `Index` type, a.k.a. `δ`, which is defined as: - -```rust -pub struct δ; -pub use δ as Index; -``` - -The `Index` type can be used to represent indices as types, such as `Index<0>`, `δ<1>`. - -## `HasField` Trait - -The most basic use case for CGP is for dependency injection of getting values from the context. This is done through the `HasField` trait, which is defined as follows: - -```rust -pub trait HasField { - type Value; - - fn get_field(&self, _tag: PhantomData) -> &Self::Value; -} -``` - -The `Tag` type is used to refer to a field in a struct, such as `Symbol!("name")` or `Index<0>`. - -The `_tag` parameter with `PhantomData` type is used to assist type inference to inform the Rust compiler of the `Tag` type, in case when multiple `HasField` implementations are in scope. - -The `HasField` trait can be automatically derived. For example: - -```rust -#[derive(HasField)] -pub struct Rectangle { - pub width: f64, - pub height: f64, -} -``` - -will generate the following `HasField` impls: - -```rust -impl HasField for Rectangle { - type Value = f64; - - fn value(&self, _tag: PhantomData) -> &f64 { - &self.width - } -} - -impl HasField for Rectangle { - type Value = f64; - - fn value(&self, _tag: PhantomData) -> &f64 { - &self.height - } -} -``` - -The `HasField` trait can also derived for structs with unnamed fields, and uses `Index` to refer to the field indices. For example: - -```rust -#[derive(HasField)] -pub struct Rectangle(f64, f64); -``` - -will generate: - -```rust -impl HasField> for Rectangle { - type Value = f64; - - fn value(&self, _tag: PhantomData>) -> &f64 { - &self.0 - } -} - -impl HasField> for Rectangle { - type Value = f64; - - fn value(&self, _tag: PhantomData>) -> &f64 { - &self.1 - } -} -``` - -## Dependency Injection - -CGP leverages Rust's trait system to enable dependency injection, also called impl-side dependencies. - -The dependency injection is done in the form of constraints specified only in the `where` clause of `impl` blocks, but not in the trait definition. - -For example, given: - -```rust -#[cgp_component(Greeter)] -pub trait CanGreet { - fn greet(&self); -} -``` - -Using `HasField`, one can perform dependency injection to retrieve a string value from the context, and implement a `Greeter` provider as follows: - -```rust -pub struct GreetHello; - -impl Greeter for GreetHello -where - Context: HasField, -{ - fn greet(context: &Context) { - println!("Hello, {}!", context.get_field(PhantomData)); - } -} -``` - -This allows `CanGreet` to be implemented on any concrete context struct that derives `HasField` and contains a `name` field of type `String`. For example: - -```rust -#[derive(HasField)] -pub struct Person { - pub name: String, -} - -delegate_components! { - Person { - GreeterComponent: - GreetHello, - } -} -``` - -The dependency injection technique can also be used in vanilla Rust traits with blanket implementations, such as: - -```rust -pub trait CanGreet { - fn greet(&self); -} - -impl Greeter for Context -where - Context: HasField, -{ - fn greet(&self) { - println!("Hello, {}!", self.get_field(PhantomData)); - } -} -``` - -This is commonly used to hide the constraints of one implementation behind a trait interface, without using `#[cgp_component]` to enable multiple alternative implementations. This is useful to simplify the learning curve of CGP, as users can mostly work with vanilla Rust traits. - -## `#[cgp_auto_getter]` Macro - -`#[cgp_auto_getter]` macro provides additional abstraction on top of `HasField`, so that users don't need to understand the internals of `HasField`. - -For example, given: - -```rust -#[cgp_auto_getter] -pub trait HasName { - fn name(&self) -> &String; -} -``` - -the macro would generate the following blanket implementation: - -```rust -impl HasName for Context -where - Context: HasField, -{ - fn name(&self) -> &str { - self.get_field(PhantomData).as_str() - } -} -``` - -The `#[cgp_auto_getter]` macro generates blanket impls that use `HasField` implementations with the field name as the `Tag` type, and the return type as the `Value` type. - -The macro supports short hand for several return types such as `&str`, to make the `name` method more ergonomic. So we can rewrite the same trait to return `&str` instead of `&String`: - -```rust -#[cgp_auto_getter] -pub trait HasName { - fn name(&self) -> &str; -} -``` - -### Explicit Getter Implementation - -A getter trait can always be implemented manually, if the concrete struct do not derive `HasField` or don't contain the relevant field. - -For example, instead of implementing `HasName` automatically: - -```rust -#[derive(HasField)] -pub struct Person { - pub name: String -} -``` - -one can opt to not derive `HasField` and implement `Name` explicitly: - -```rust -pub struct Person { - pub name: String -} - -pub trait HasName for Person { - fn name(&self) -> &str; -} -``` - -The explicit getter implementation is much more verbose, especially when a context contains many fields. However, it is also much more easier to understand and does not require the user to understand the advanced trait machinery with `HasField` and blanket implementations. - -The explicit getter implementation can be used to explain the equivalent effect when both `#[cgp_auto_getter]` and `#[derive(HasField)]` are used. - -It is also important to highlight the possibility of explicit getter implementation, to avoid misunderstanding from the user that CGP getter traits are somehow more magical than vanilla Rust traits. - -The explicit implementation demonstrates that the only purpose for `#[cgp_auto_getter]` is to save the user from writing some boilerplate. But they can always write such boilerplate if that is their preference. - -## `#[cgp_getter]` Macro - -The `#[cgp_getter]` macro is an extension to `#[cgp_component]` that provides similar feature as `#[cgp_auto_getter]`, but allows the getter field to be customized through CGP. - -For example, given: - -```rust -#[cgp_getter] -pub trait HasName { - fn name(&self) -> &str; -} -``` - -is the same as writing: - -```rust -#[cgp_component(NameGetter)] -pub trait HasName { - fn name(&self) -> &str; -} -``` - -but also has the following `UseField` provider implemented: - -```rust -#[cgp_impl(UseField)] -impl NameGetter for Context -where - Context: HasField, -{ - fn name(&self) -> &str { - self.get_field(PhantomData) - } -} -``` - -Similar to `#[cgp_auto_getter]`, a `#[cgp_getter]` trait can also be directly implemented on a concrete context. - -## `UseField` Pattern - -CGP defines the `UseField` type as a general target for implementing getter providers by `#[cgp_getter]`. - -The `UseField` provider accepts a generic `Tag` parameter that represents the name of the field from the context to be used to implement the getter. - -The `Tag` in `UseField` can use a different name as the getter method, allowing greater flexibility than `#[cgp_auto_getter]` which always require the context to have a field with the exact same name. - -For example, one can have the following wiring: - -```rust -#[derive(HasField)] -pub struct Person { - pub first_name: String, -} - -delegate_components! { - Person { - NameGetterComponent: - UseField, - } -} -``` - -the example `UseField` provider will use the `first_name` field in `Person` to implement the `NameGetter::name`. - -Whenever possible, explain the `UseField` provider by saying that it implements the getter trait by reading from the context the field name specified. For example, `Person` implements `HasName` using its `first_name` field. - -## Implicit Arguments - -CGP supports implicit arguments for implementations to automatically retrieve field values from a context. For example: - -```rust -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self) -> f64; -} - -#[cgp_impl(new RectangleArea)] -impl AreaCalculator { - fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height - } -} -``` - -The function arguments with `#[implicit]` are automatically extracted and removed from the function signature, and the code desugars to the following: - -```rust -#[cgp_impl(new RectangleArea)] -impl AreaCalculator -where - Self: HasField - + HasField, -{ - fn area(&self) -> f64 { - let width: f64 = self.get_field(PhantomData::).clone(); - let height: f64 = self.get_field(PhantomData::).clone(); - - width * height - } -} -``` - -The semantics of implicit arguments follows the same pattern as `#[cgp_auto_getter]`. For example, `.clone()` is automatically added to implicit arguments with owned values, and `.as_str()` is automatically added to implicit arguments with with `&str` type. - -When writing basic CGP code, it is strongly recommended to use implicit arguments whenever possible. This allows the user to write code that looks more like normal Rust code, without the need to understand the underlying trait machinery of `HasField` and getter traits. - -On the other hand, `#[cgp_auto_getter]` and `#[cgp_getter]` are better suited for more advanced use cases, such as when field access happening in the middle of a function body. `#[cgp_auto_getter]` also reduces the boilerplate when the same fields are repeatedly accessed in multiple functions. - -## `#[cgp_fn]` Macro - -The `#[cgp_fn]` macro supports the use of implicit arguments in plain Rust function syntax, and desugars the code into blanket implementations. For example: - -```rust -#[cgp_fn] -fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height -} -``` - -desugars to: - -```rust -pub trait RectangleArea { - fn area(&self) -> f64; -} - -impl RectangleArea for Context -where - Self: HasField - + HasField, -{ - fn area(&self) -> f64 { - let width: f64 = self.get_field(PhantomData::).clone(); - let height: f64 = self.get_field(PhantomData::).clone(); - - width * height - } -} -``` - -This significantly improves the ergonomic and reduces the boilerplate of defining blanket trait implementations. `#[cgp_fn]` exposes the simplest CGP concepts, and only requires the user to understand plain Rust functions to get started. - -Whenever possible, prefer to use `#[cgp_fn]` over `#[cgp_component]` and `#[cgp_impl]` to explain basic CGP concepts. Then main difference is that `#[cgp_fn]` only allows single implementation, while `#[cgp_component]` allows multiple implementations but requires additional wiring step. - -### Custom trait name for `#[cgp_fn]` - -`#[cgp_fn]` accepts an optional attribute argument to specify the name of the generated trait. If unspecified, it would use the function name in PascalCase as the trait name. For example, the earlier example is equivalent to: - -```rust -#[cgp_fn(RectangleArea)] -fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height -} -``` - -We can for example change the trait name to `CanCalculateRectangleArea`: - -```rust -#[cgp_fn(CanCalculateRectangleArea)] -fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height -} -``` - -and the generated trait would be: - -```rust -pub trait CanCalculateRectangleArea { - fn rectangle_area(&self) -> f64; -} -``` - -## Generics and `where` clause in `#[cgp_fn]` - -By default, all generic parameters of the function in `#[cgp_fn]` are moved to the generated trait and impl, and the `where` clause is moved to the impl block only. For example: - -```rust -#[cgp_fn] -pub fn rectangle_area( - &self, - #[implicit] width: Scalar, - #[implicit] height: Scalar, -) -> Scalar -where - Scalar: Mul, -{ - width * height -} -``` - -desugars to: - -```rust -pub trait RectangleArea { - fn rectangle_area(&self) -> Scalar; -} - -impl RectangleArea for Context -where - Self: HasField - + HasField, - Scalar: Mul + Clone, -{ - fn rectangle_area(&self) -> Scalar { - let width: Scalar = self.get_field(PhantomData::).clone(); - let height: Scalar = self.get_field(PhantomData::).clone(); - - width * height - } -} -``` - -- The `Scalar: Clone` bound is in the impl-generics, so it is included in both the trait and impl. -- The `Scalar: Mul` bound is only in the `where` clause of the impl. It is an impl-side dependency that is not included in the trait definition. - -`#[cgp_fn]` specifically do not support the use of generics in the desugared trait method. This is because such use is relatively uncommon in CGP. And even when the need arises, it is considered advanced use case that is better written as explicit blanket implementations, instead of using `#[cgp_fn]`. - -## `#[uses]` Attribute - -The `#[uses]` attribute can be used in both `#[cgp_fn]` and `#[cgp_impl]` to add simple `where` trait bounds to the `Self` context. - -For example, given: - -```rust -#[cgp_fn] -fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height -} - -#[cgp_fn] -#[uses(RectangleArea)] -fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 { - self.rectangle_area() * scale_factor * scale_factor -} -``` - -The `scaled_rectangle_area` function is equivalent to: - -```rust -#[cgp_fn] -fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 -where - Self: RectangleArea, -{ - self.rectangle_area() * scale_factor * scale_factor -} -``` - -which both desugars to: - -```rust -pub trait ScaledRectangleArea { - fn scaled_rectangle_area(&self) -> f64; -} - -impl ScaledRectangleArea for Context -where - Self: HasField - + RectangleArea, -{ - fn scaled_rectangle_area(&self) -> f64 { - let scale_factor: f64 = self.get_field(PhantomData::).clone(); - - self.rectangle_area() * scale_factor * scale_factor - } -} -``` - -It is highly recommended to use `#[uses]` over explicit `where` clauses on `Self`, especially when writing basic CGP code. This makes the code looks more like a `use` import statement, which "imports" the dependencies like `RectangleArea` to be used in the function body. - -This is more intuitive to the use of `where` clause with `Self`, which is often much less intuitive to users who are new to Rust, let alone CGP. - -The `#[uses]` attribute can be used to import CGP constructs defined with both `#[cgp_fn]` and `#[cgp_component]`. For example: - -```rust -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self) -> f64; -} - -#[cgp_fn] -#[uses(CanCalculateArea)] -pub fn scaled_area(&self, #[implicit] scale_factor: f64) -> f64 { - self.area() * scale_factor * scale_factor -} -``` - -This enables scaled area calculation for any context that implements `CanCalculateArea`, regardless of which `AreaCalculator` provider is wired with the context. - -Conversely, `#[cgp_impl]` can also use `#[uses]` to import dependencies from other `#[cgp_fn]` or `#[cgp_component]` constructs. For example: - -```rust -#[cgp_fn] -fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height -} - -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self) -> f64; -} - -#[cgp_impl(new RectangleAreaCalculator)] -#[uses(RectangleArea)] -impl AreaCalculator { - fn area(&self) -> f64 { - self.rectangle_area() - } -} -``` - -The `#[uses]` attribute is specifically designed to look like a `use` statement, and so it support simplified trait bounds syntax in the form `TraitIdent`. This means that one cannot write more complex bounds like ones that contain associated type equality in it. Instead, if these are needed, they should be written as explicit `where` clauses in the function body. - -## `#[extend]` Attribute - -The `#[extend]` attribute can be used in both `#[cgp_fn]` and `#[cgp_component]` to include the given trait bounds as the super traits of the generated trait. For example, given: - -```rust -pub trait HasScalarType { - type Scalar: Clone + Mul; -} - -#[cgp_fn] -#[extend(HasScalarType)] -fn rectangle_area( - &self, - #[implicit] width: Self::Scalar, - #[implicit] height: Self::Scalar, -) -> Self::Scalar { - width * height -} -``` - -would be desugared to: - -```rust -pub trait RectangleArea: HasScalarType { - fn rectangle_area(&self) -> Self::Scalar; -} - -impl RectangleArea for Context -where - Self: HasField - + HasField - + HasScalarType, -{ - fn rectangle_area(&self) -> Self::Scalar { - let width: Self::Scalar = self.get_field(PhantomData::).clone(); - let height: Self::Scalar = self.get_field(PhantomData::).clone(); - - width * height - } -} -``` - -Note that `#[extend]` is the only way to add supertrait bounds to `#[cgp_fn]`. This is because the `where` clauses in the function body are treated as impl-side dependencies, and thus are hidden from the generated trait definition. - -`#[extend]` can also be used with `#[cgp_component]` to add supertrait bounds to the generated consumer trait. For example: - -```rust -#[cgp_component(AreaCalculator)] -#[extend(HasScalarType)] -pub trait CanCalculateArea { - fn area(&self) -> Self::Scalar; -} -``` - -is equivalent to: - -```rust -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea: HasScalarType { - fn area(&self) -> Self::Scalar; -} -``` - -The choice of whether to use `#[extend]` or the normal Rust syntax for super traits is mostly a matter of style. The normal Rust syntax is more concise, but `#[extend]` enables gradual transition to supertraits to users who are getting started with `#[cgp_fn]` and are not yet familiar with Rust's trait system. - -This is because many Rust developers are not familiar with the supertrait concept, and the appearance of many supertrait bounds can look intimidating. On the other hand, `#[extend]` can be explained as being the `pub use` equivalent of the `#[uses]` attribute, which has a more direct correspondance to the vanilla `use` statement in Rust. - -## `#[extend_where]` Attribute - -The `#[extend_where]` attribute can be used in `#[cgp_fn]` to add `where` clauses to the generated trait definition. For example: - -```rust -#[cgp_fn] -#[extend_where(Scalar: Clone)] -fn rectangle_area( - &self, - #[implicit] width: Scalar, - #[implicit] height: Scalar, -) -> Scalar -where - Scalar: Mul, -{ - width * height -} -``` - -would produce the following trait definition: - -```rust -pub trait RectangleArea -where - Scalar: Clone, -{ - fn rectangle_area(&self) -> Scalar; -} -``` - -`#[extend_where]` is not supported in `#[cgp_impl]` or `#[cgp_component]`, because the `where` clauses in these constructs are already part of the trait definition, and thus can be directly written in the normal Rust syntax. - -## Abstract Types - -- CGP supports abstract types by defining associated types in CGP traits. For example: - -```rust -#[cgp_component(NameTypeProviderComponent)] -pub trait HasNameType { - type Name; -} -``` - -- The abstract type can be used in another trait interface as the super trait, such as: - -```rust -#[cgp_auto_getter] -pub trait HasName: HasNameType { - fn name(&self) -> &Self::Name; -} -``` - -## `#[cgp_type]` Macro - -- CGP provides the `#[cgp_type]` macro that can be used in place of `#[cgp_component]` to define abstract type traits. -- For example, the `HasNameType` trait can be redefined as: - -```rust -#[cgp_type] -pub trait HasNameType { - type Name; -} -``` - -- If no provider name is given in `#[cgp_type]`, a default provider name with the type name plus `TypeProvider` postfix is used. So the above code is the same as: - -```rust -#[cgp_type(NameTypeProvider)] -pub trait HasNameType { - type Name; -} -``` - -- `#[cgp_type]` has the same base behavior as `#[cgp_component]`, but generates additional constructs such as a blanket implementation for `UseType`: - -```rust -#[cgp_impl(UseType)] -impl NameTypeProvider { - type Name = Name; -} -``` - -## `UseType` Provider - -- The `UseType` struct is defined by CGP, which is implemented by providers that use `#[cgp_type]` as a design pattern: - -```rust -pub struct UseType(pub PhantomData); -``` - -- The `UseType` pattern allows a concrete context to implement an abstract type by delegating it to `UseType`. For example: - -```rust -delegate_components! { - Person { - NameTypeProviderComponent: - UseType, - } -} -``` - -would implement `HasNameType` for `Person` with `Name` being implemented as `String`. - -## Direct Implementation Type Traits - -- An abstract type can always be directly implemented on a concrete context through its consumer trait. -- For example, instead of using `UseType`, we can implement `HasNameType` as follows: - -```rust -impl HasNameType for Person { - type Name = String; -} -``` - -- The direct implementation of a type trait is not much more verbose than the indirect implementation through `delegate_components!` and `UseType`. So it may be preferred especially for simple use cases. -- For users who are new to CGP, it is preferred to always show a direct implementation of the type traits. This helps the user to understand that CGP abstract types are nothing more than vanilla Rust traits that contain associated types. - -## Abstract Type in Getter Traits - -- When a getter trait contains only one getter method, it can define a local associated type and use it as the return type of the getter method. For example: - -```rust -#[cgp_auto_getter] -pub trait HasName { - type Name; - - fn name(&self) -> &Self::Name; -} -``` - -- This allows the abstract `Name` type to be automatically inferred based on the `name` field of the concrete context. -- This approach is useful when the only purpose of the abstract type is to be used as the return type of the getter method, but not anywhere else. - -## Abstract Type import with `#[use_type]` - -The `#[use_type]` attribute can be used as a more idiomatic way to import abstract types in `#[cgp_fn]`, `#[cgp_impl]`, and `#[cgp_component]`. For example, given: - -```rust -pub trait HasScalarType { - type Scalar: Clone + Mul; -} - -#[cgp_fn] -#[use_type(HasScalarType::Scalar)] -fn rectangle_area( - &self, - #[implicit] width: Scalar, - #[implicit] height: Scalar, -) -> Scalar -{ - width * height -} -``` - -The code would be desugared to: - -```rust -pub trait RectangleArea: HasScalarType { - fn rectangle_area(&self) -> ::Scalar; -} - -impl RectangleArea for Context -where - Self: HasField::Scalar> - + HasField::Scalar> - + HasScalarType, -{ - fn rectangle_area(&self) -> ::Scalar { - let width: ::Scalar = - self.get_field(PhantomData::).clone(); - - let height: ::Scalar = - self.get_field(PhantomData::).clone(); - - width * height - } -} -``` - -Compared to just including an abstract type in the trait bound or supertrait, `#[use_type]` replaces all occurrences of the abstract type identifier and replaces it with the fully qualified syntax `::Type`. This significantly reduces the boilerplate of adding prefixes like `Self::` to every occurrence of the abstract type. +## Using it -The fully qualified syntax also avoids any potential ambiguity. In particular, it allows nested associated types to be used without needing the user to specify the fully qualified syntax themselves. +The quickest way is to hand your assistant the main file. Download +[`SKILL.md`](https://raw.githubusercontent.com/contextgeneric/cgp-skills/refs/heads/main/cgp/SKILL.md) +and attach it to the context window of whichever model you use. -`#[use_type]` can also be used in both `#[cgp_impl]` and `#[cgp_component]` to import abstract types in the same way. For example: +For everyday work, install the whole skill rather than the one file. Clone the repository and point +your assistant's skills directory at it, so the sub-skills load on demand instead of all at once: -```rust -#[cgp_component(AreaCalculator)] -#[use_type(HasScalarType::Scalar)] -pub trait CanCalculateArea { - fn area(&self) -> Scalar; -} - -#[cgp_impl(new RectangleArea)] -#[use_type(HasScalarType::Scalar)] -impl AreaCalculator { - fn area(&self, #[implicit] width: Scalar, #[implicit] height: Scalar) -> Scalar { - width * height - } -} -``` - -would first be desugared to the following, before the rest of the desugaring process: - -```rust -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea: HasScalarType { - fn area(&self) -> ::Scalar; -} - -#[cgp_impl(new RectangleArea)] -impl AreaCalculator -where - Self: HasScalarType, -{ - fn area( - &self, - #[implicit] width: ::Scalar, - #[implicit] height: ::Scalar, - ) -> ::Scalar { - width * height - } -} -``` - -Whenever possible, it is strongly recommended to always use `#[use_type]` to import abstract types, for all use cases in `#[cgp_fn]`, `#[cgp_impl]`, and `#[cgp_component]`. This significantly reduces the boilerplate of using abstract types, and makes the code much more readable. - -It also enables better syntax extension in the future, which would require explicit use of `#[use_type]` to get the necessary metadata for the syntax extension to work. - -## Higher Order Providers - -Higher order providers is a CGP design pattern that allows providers to accept other providers as generic parameters. - -For example, with the `CanCalculateArea` trait: - -```rust -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self) -> f64; -} -``` - -we can define a higher order provider `ScaledArea` as follows: - -```rust -#[cgp_impl(ScaledArea)] -impl AreaCalculator -where - InnerCalculator: AreaCalculator, -{ - fn area(&self, #[implicit] scale_factor: f64) -> f64 { - InnerCalculator::area(self) * scale_factor * scale_factor - } -} -``` - -The behavior of the inner area calculation is now determined by the `InnerCalculator` generic parameter, instead of the context. - -## `#[use_provider]` Attribute - -The `#[use_provider]` attribute can be used to improve the ergonomics of using higher order providers, by hiding the `Self` parameter at the first position of the generic parameter of the provider trait. - -For example, the earlier `ScaledArea` provider can be rewritten as: - -```rust -#[cgp_impl(ScaledArea)] -#[use_provider(InnerCalculator: AreaCalculator)] -impl AreaCalculator -{ - fn area(&self, #[implicit] scale_factor: f64) -> f64 { - #[use_provider(InnerCalculator)] self.area() * scale_factor * scale_factor - } -} -``` - -The outer `#[use_provider]` attribute automatically adds the `Self` parameter to the generic parameter of `InnerCalculator`, so that the user only needs to write `InnerCalculator: AreaCalculator` instead of `InnerCalculator: AreaCalculator`. The trait bound is then added to the `where` clause of the impl block. - -The inner `#[use_provider]` attribute accepts a `Provider` type and can be applied on a method call expression. It converts the expression from the form `receiver.method(args)` to `Provider::method(receiver, args)`, so that the method call is dispatched to the specified provider instead of through the context. - -It is strongly recommended to always use `#[use_provider]` when implementing higher order providers, as it significantly reduces the boilerplate of writing higher order providers, and makes the code much more readable. Without it, the reader may be confused by the extra `Self` generic parameter at the first position of the provider trait, which breaks the illusion that the provider trait appears the same as the consumer trait. - -## Non-higher-order providers with generic parameters - -Note that not all providers that contain generic parameters are higher order providers. They only become higher order providers when the generic parameters are used with provider trait constraints in the `where` clause. - -For example, the following provider is not a higher order provider: - -```rust -#[cgp_impl(new GetName)] -impl NameGetter -where - Self: HasField, -{ - fn name(&self) -> &str { - self.get_field(PhantomData) - } -} -``` - -The code above uses the `UseField` pattern, where the `Tag` type is used as the field name to access the corresponding field value via `HasField`. But since there is no constraint for `Tag` to implement any provider trait, the provider `GetName` is not a higher order provider. - -## Generic Parameters - -CGP traits can also contain generic parameters, for example: - -```rust -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self, shape: &Shape) -> f64; -} -``` - -defines a further modularized version of the earlier `CanCalculateArea` trait, where the area calculation is done on the generic `Shape` parameter instead of the context. - -When the provider trait is generated, the generic parameters are appended after the `Context` parameter. For example: - -```rust -pub trait AreaCalculator: IsProviderFor { - fn area(context: &Context, shape: &Shape) -> f64; -} -``` - -In the `IsProviderFor` supertrait, all generic parameters a grouped together into a tuple and placed in the last `Params` position. - -When the trait contains lifetime generic parameters, they are wrapped in the `Life` type, which lifts lifetimes into types: - -```rust -pub struct Life<'a>(pub PhantomData<*mut &'a ()>); -``` - -## `UseDelegate` Provider - -For traits containing generic parameters, the `#[cgp_component]` macro supports additional option to generate `UseDelegate` providers that dispatch providers based on the generic type using an inner type-level table. - -For example, given: - -```rust -#[cgp_component { - provider: AreaCalculator, - derive_delegate: UseDelegate, -}] -pub trait CanCalculateArea { - fn area(&self, shape: &Shape) -> f64; -} -``` - -The following provider will be generated: - -```rust -#[cgp_impl(UseDelegate)] -impl AreaCalculator -where - Components: DelegateComponent, - Components::Delegate: AreaCalculator, -{ - fn area(&self, shape: &Shape) -> f64 { - Components::Delegate::area(self, shape) - } -} -``` - -Only the generic type specified in `UseDelegate`'s generic parameter will be used as the key. For example, the `UseDelegate` provider above dispatches based on `Shape` alone. - -The `UseDelegate` type is defined by CGP, but one can define and use other delegate providers in similar ways. For example: - -```rust -pub struct UseInputDelegate(pub PhantomData); - -#[cgp_component { - provider: Computer, - derive_delegate: [ - UseDelegate, - UseInputDelegate, - ], -}] -pub trait CanCompute { - type Output; - - fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; -} -``` - -the `CanCompute` trait above defines two delegate providers. The default `UseDelegate` provider dispatches based on the `Code` type, while the local `UseInputDelegate` provider dispatches based on the `Input` type. - -## Nested Table Definition - -`delegate_components!` supports defining nested type-level tables within the outer table definition. - -For example: - -```rust -delegate_components! { - MyApp { - AreaCalculatorComponent: - UseDelegate, - ... - } -} -``` - -is the same as: - -```rust -delegate_components! { - MyApp { - AreaCalculatorComponent: - UseDelegate, - ... - } -} - -delegate_components! { - new AreaCalculatorComponents { - Rectangle: - RectangleArea, - Circle: - CircleArea, - ... - } -} -``` - -The example above helps `MyApp` implement `CanCalculateArea` by delegating to the `Rectangle` provider, and `CanCalculateArea` to `CircleArea`, via the `UseDelegate` provider using `AreaCalculatorComponents` as the inner lookup table based on the `Shape` type. - -## Cross-Context Dependencies - -When the main target of a trait is a generic parameter instead of a context, like: - -```rust -#[cgp_component(AreaOfShapeCalculator)] -pub trait CanCalculateAreaOfShape { - fn area(&self, shape: &Shape) -> f64; -} -``` - -This allows multiple `Shape` contexts to share dependencies through a common `Context` type. - -For example, we can introduce a `Scalar` type that is shared by all shapes: - -```rust -#[cgp_type] -pub trait HasScalarType { - type Scalar: Float; -} - -#[cgp_component(AreaOfShapeCalculator)] -pub trait CanCalculateAreaOfShape: HasScalarType { - fn area(&self, shape: &Shape) -> Self::Scalar; -} -``` - -- This way, individual shape types like `Rectangle` and `Circle` do not need to implement `HasScalarType`, or worry about all shapes using the same `Scalar` type to interop with each others. - -- The common context type can also provide value-level dependency injection, such as: - -```rust -#[cgp_auto_getter] -pub trait HasGlobalScaleFactor: HasScalarType { - fn global_scale_factor(&self) -> Self::Scalar; -} - -#[cgp_impl(new GloballyScaledArea)] -impl AreaCalculator -where - Self: HasGlobalScaleFactor, - InnerCalculator: AreaCalculator, -{ - fn area(&self, shape: &Shape) -> f64 { - InnerCalculator::area(self, shape) * self.global_scale_factor() - } -} -``` - -This way, a global scale factor can be stored in the common context, and not have to have the value replicated in all shape values. - -The common context can also provide lazy binding of provider implementations, so that each shape type may bind to different provider in different concrete contexts. For example: - -```rust -pub struct BaseApp; - -delegate_components! { - BaseApp { - ScaleFactorTypeProviderComponent: - UseType, - AreaOfShapeCalculatorComponent: - UseDelegate, - } -} - -#[derive(HasField)] -pub struct ScaledApp { - pub global_scale_factor: f64, -} - -delegate_components! { - BaseApp { - ScaleFactorTypeProviderComponent: - UseType, - AreaOfShapeCalculatorComponent: - UseDelegate, - Circle: - GloballyScaledArea, - }>, - } -} -``` - -In the above example, the `Rectangle` type would have an unscaled area implementation with `BaseApp`, but a globally scaled area implementation with `ScaledApp`. - -## `UseContext` Provider - -- CGP defines a special `UseContext` provider that is automatically implemented for all CGP traits that are defined with macros like `#[cgp_component]`: - -```rust -struct UseContext; -``` - -- For example, the `UseContext` implementation generated for `CanCalculateArea` is as follows: - -```rust -#[cgp_impl(UseContext)] -impl AreaOfShapeCalculator -where - Self: CanCalculateAreaOfShape, -{ - fn area(&self, shape: &Shape) -> Self::Scalar { - self.area(shape) - } -} -``` - -There is a duality between `UseContext` and the blanket implementation of consumer traits. Whereas the blanket implementation of the `CanCalculateArea` consumer trait uses a delegated provider that implements `AreaCalculator` to implement `CanCalculateArea`, the `UseContext` provider implements the `AreaCalculator` provider trait using `CanCalculateArea` implemented by the context. - -However, trying to delegate a consumer trait to `UseContext` would create a circular dependency, resulting in compile-time errors. - -### `UseContext` as Default in Higher Order Providers - -A higher order provider may be configured to use `UseContext` as the default inner provider, so that the default provider wired in the context is used when no explicit provider is specified. - -For example, we can define an `IterSumArea` higher-order provider that uses `UseContext` as a default inner provider: - -```rust -pub struct IterSumArea(pub PhantomData); - -#[cgp_impl(IterSumArea)] -impl AreaCalculator -where - Self: HasScalarType, - for<'a> &'a Shape: IntoIterator - InnerCalculator: AreaCalculator, -{ - fn area(&self, shapes: &Shape) -> Self::Scalar { - let mut total = Self::Scalar::default(); - for shape in shapes.into_iter() { - total += InnerCalculator::area(self, shape); - } - total - } -} -``` - -The struct definition of `IterSumArea` is defined with `UseContext` being a default generic parameter for `InnerCalculator`. - -This way, when no explicit provider is specified, `IterSumArea` would just use the wiring in the context to calculate the area for the inner shape. - -The inner provider can be overridden to enable static binding that does not require routing through the main context. This can be useful for simplifying the wiring on the main context, or for overridding the existing wiring in the main context. - -Note that the default `UseContext` provider is only applicable for higher order providers with explicit struct definitions that contain the default generic parameter. Otherwise, there is no default provider involved, and the inner provider must always be specified explicitly. - -## Check Traits - -The CGP component wiring is lazy, i.e. when a `DelegateComponent` impl is defined, the type system doesn't check whether the corresponding traits are truly implemented by a context with all transitive dependencies satisfied. - -When a consumer trait is used with a context, but there are unsatisfied dependencies, the compiler will produce short error messages that are difficult to debug and identify the root cause. - -To ensure that a consumer is implemented by a context, we implement check traits to assert at compile time that the wiring is complete. - -For example, given: - -```rust -#[cgp_auto_getter] -pub trait HasName { - fn name(&self) -> &str; -} - -#[cgp_component(Greeter)] -pub trait CanGreet { - fn greet(&self); -} - -#[cgp_impl(new GreetHello)] -impl Greeter -where - Self: HasName, -{ - fn greet(&self) { - println!("Hello, {}!", self.name()); - } -} - -#[derive(HasField)] -pub struct Person { - pub first_name: String, -} - -delegate_components! { - Person { - GreeterComponent: - GreetHello, - } -} -``` - -The `Person` struct above incorrectly contains a `first_name` field, instead of the `name` field expected by `GreetHello` via `HasName`. - -We can write a check trait to check whether `Person` implements `CanGreet` as follows: - -```rust -trait CanUsePerson: CanGreet {} -impl CanUsePerson for Person {} -``` - -A check trait like `CanUsePerson` is a dummy trait that includes the dependencies that we want to check as its super trait. - -The check trait contains an empty body that can be trivially implemented if all the supertrait constraints are satisfied. - -We then implement the check trait for the context type that we want to check. If the type also implements all the supertraits, then the implementation is successful and the test passes. - -## `CanUseComponent` Trait - -It is insufficient to use check traits alone in case when a check fails. This is because Rust would not produce sufficient details in the error message to help inform us on what dependency is missing. - -For example, the `CanUsePerson` check earlier only output a vague error that tells us `GreetHello: Greeter` is not implemented, without telling us why. - -We can use check traits together with `CanUseComponent` as their supertraits to force the Rust compiler to show more error details. - -The `CanUseComponent` trait is a check trait defined as follows: - -```rust -pub trait CanUseComponent {} - -impl CanUseComponent for Context -where - Context: DelegateComponent, - Context::Delegate: IsProviderFor, -{} -``` - -`CanUseComponent` for a CGP component is automatically implemented for a context, if a context delegates the component to a provider, and the provider implements the provider trait for that context. - -The check is done via `IsProviderFor`, to ensure that the compiler generates appropriate error messages when there is any unsatisfied constraint. Without `IsProviderFor`, Rust would conceal the indirect errors and only show that the provider trait is not implemented without providing further details. - -## `check_components!` Macro - -Additionally, instead of defining the check traits manually, we can use `check_components!` to simplify the definition of the compile time tests. - -The `check_components!` macro generates code that checks the CGP wiring of components using `CanUseComponent`. - -The static check is written with `check_components!` as follow: - -```rust -check_components! { - Person { - GreeterComponent, - } -} -``` - -Behind the scenes, the macro desugars the code above to: - -```rust -trait __CheckPerson: CanUseComponent {} -impl __CheckPerson for Person {} -``` - -The check trait `__CheckPerson` is defined as a local alias trait to check the implementation of `CanUseComponent` with the same parameters. The name of the check trait follows `__Check{Context}` format, where `Context` is the target context type being checked. - -For each `Component` listed in `check_components!`, an impl block for `__CheckPerson` is defined. - -The example implementation `__CheckPerson` is implemented only if: - - `Person` implements `CanUseComponent`. - - `Person`'s delegate for `GreeterComponent`, `GreetHello`, implements `IsProviderFor`. - -Recall that `#[cgp_impl]` or `#[cgp_provider]` generates the implementation of `GreetHello: IsProviderFor` with the same constraints required for `GreetHello` to implement `Greeter`. - -Since the `name` field is missing, the compiler reports the error that `HasField` is not implemented for `Person`. The root cause is often hidden among many other non-essential messages, and types such as `symbol!("name")` are expanded into their Greek alphabets form. - -### Specifying check trait name - -The name of the generated check trait can be overridden using a `#[check_trait] attribute. For example: - -```rust -check_components! { - #[check_trait(CanUsePerson)] - Person { - GreeterComponent, - } -} -``` - -would generate a check trait of the name `CanUsePerson` instead of `__CheckPerson`. - -This is mainly useful when there are multiple use of `check_components!` in the same module, which would result in name conflict for the default check trait name. - -### Generic Parameters in `check_components!` - -`check_components!` can be used with CGP traits containing generic parameters. For example, given: - -```rust -#[cgp_component(AreaOfShapeCalculator)] -pub trait CanCalculateAreaOfShape { - fn area(&self, shape: &Shape) -> f64; -} -``` - -and the following check: - -```rust -check_components! { - MyApp { - AreaOfShapeCalculatorComponent: - Rectangle, - } -} -``` - -would be desugared to: - -```rust -trait __CheckMyApp: - CanUseComponent -{ -} - -impl __CheckMyApp for MyApp {} -``` - -which would check for the implementation of `MyApp: CanCalculateAreaOfShape`. - -## Multiple Generic Parameters in `check_components!` - -When there are more than one generic parameters, they are grouped into a tuple and placed in `Params`. For example, given: - -```rust -#[cgp_component(AreaOfShapeCalculator)] -pub trait CanCalculateAreaOfShape { - fn area(&self, shape: &Shape) -> Scalar; -} -``` - -and the following check: - -```rust -check_components! { - MyApp { - AreaOfShapeCalculatorComponent: - (Rectangle, f64), - } -} -``` - -would be desugared to: - -```rust -trait __CheckMyApp: - CanUseComponent -{ -} - -impl __CheckMyApp for MyApp {} -``` - -which would check for the implementation of `MyApp: CanCalculateAreaOfShape`. - -## Array Syntax in `check_components!` - -When we want to check the implementation of a CGP component with multiple generic parameters, we can use the array syntax to group them together. For example: - -```rust -check_components! { - MyApp { - AreaCalculatorComponent: [ - Rectangle, - Circle, - ], - } -} -``` - -is the same as writing: - -```rust -check_components! { - MyApp { - AreaCalculatorComponent: - Rectangle, - AreaCalculatorComponent: - Circle, - } -} -``` - -We can also group by the `Component` key instead of the generic `Param`. For example: - -```rust -check_components! { - MyApp { - [ - AreaCalculatorComponent, - RotatorComponent, - ]: Rectangle, - } -} -``` - -We can also group by both `Component` and `Param`. For example: - -```rust -check_components! { - MyApp { - [ - AreaCalculatorComponent, - RotatorComponent, - ]: [ - Rectangle, - Circle, - ], - } -} -``` - -would be the same as writing: - - -```rust -check_components! { - MyApp { - AreaCalculatorComponent: Rectangle, - RotatorComponent: Rectangle, - AreaCalculatorComponent: Circle, - RotatorComponent: Circle, - } -} -``` - -### `#[check_providers]` attribute - -The `check_components!` macro supports the use of `#[check_providers]` attribute to implement the check of component implementation on specific providers. For example: - -```rust -check_components! { - #[check_trait(CheckScaledRectangleProviders)] - #[check_providers( - RectangleAreaCalculator, - ScaledAreaCalculator, - )] - ScaledRectangle { - AreaCalculatorComponent, - } -} -``` - -Would implement checks that both `RectangleAreaCalculator` and `ScaledAreaCalculator` implement `AreaCalculator`. - -The generated code for `#[check_providers]` is as follows: - -```rust -trait CheckScaledRectangleProviders<__Component__, __Params__: ?Sized>: - IsProviderFor<__Component__, ScaledRectangle, __Params__> -{ -} - -impl CheckScaledRectangleProviders for RectangleAreaCalculator {} - -impl CheckScaledRectangleProviders - for ScaledAreaCalculator -{} -``` - -Compared to non-provider checks, the check trait has `IsProviderFor` as its supertrait, and the impl blocks are implemented for the provider types instead of the context type. - -The provider checks are especially useful for the case of checking higher order providers, where each of the provider implementation can be checked separately. - -For example, if the missing dependency affects `RectangleAreaCalculator`, then the check above would show errors on both `RectangleAreaCalculator` and `ScaledAreaCalculator`. But if the missing dependency affects only `ScaledAreaCalculator`, then the check above would only show error on `ScaledAreaCalculator`, which can help narrow down the root cause. - -## `delegate_and_check_components!` Macro - -The `delegate_and_check_components!` macro combines both the use of `delegate_components!` and `check_components!` into a single macro, so that every delegation is automatically checked without needing to write a separate `check_components!` block. - -For example, given the following: - -```rust -delegate_and_check_components! { - ScaledRectangle { - AreaCalculatorComponent: - ScaledAreaCalculator, - } -} -``` - -is equivalent to writing: - -```rust -delegate_components! { - ScaledRectangle { - AreaCalculatorComponent: - ScaledAreaCalculator, - } -} - -check_components! { - #[check_trait(__CanUseScaledRectangle)] - ScaledRectangle { - AreaCalculatorComponent, - } -} -``` - -The default name of the check trait generated by `delegate_and_check_components!` is `__CanUse{Context}`. This is different from the default name of the check trait generated by `check_components!`, which is `__Check{Context}`, so that both macros can be called at most once in the same module without name conflict. - -The check trait name can also be overridden by using `#[check_trait]` attribute: - -```rust -delegate_and_check_components! { - #[check_trait(TestScaledRectangle)] - ScaledRectangle { - AreaCalculatorComponent: - ScaledAreaCalculator, - } -} -``` - -It is recommended to use `delegate_and_check_components!` over `delegate_components!` in the main context wiring, so that the wiring is always checked and any error can be caught as early as possible. - -On the other hand, `delegate_components!` alone can be still be used for building intermediary provider tables that group multiple providers together. - -`delegate_components!` may also be used in more complex cases, such as when complex higher order providers or generic parameters are involved. In those cases, checking the use on separate `check_components!` block may be more flexible. - -### Specifying generic parameters with `#[check_params]` - -When delegating a CGP trait with generic parameters, a `#[check_params]` attribute is required to specify the generic parameters for the check. - -For example, given: - -```rust -#[cgp_component(AreaOfShapeCalculator)] -pub trait CanCalculateAreaOfShape { - fn area(&self, shape: &Shape) -> f64; -} -``` - -The parameters would need to be specified, so that the checks can be done on the specified paramters: - -```rust -delegate_and_check_components! { - MyApp { - #[check_params( - Rectangle, - Circle, - )] - AreaOfShapeCalculatorComponent: - UseDelegate, - } -} -``` - -Without `#[check_params]`, the generated check trait would check for the implementation of `CanUseComponent`, which would not be satisfied since the generic parameter for `CanCalculateAreaOfShape` is missing. - -## Skipping checks with `#[skip_check]` - -We can also skip checks for specific components by using `#[skip_check]` attribute. For example: - - -```rust -delegate_and_check_components! { - ScaledRectangle { - #[skip_check] - AreaCalculatorComponent: - ScaledAreaCalculator, - } -} +```sh +git clone https://github.com/contextgeneric/cgp-skills.git ``` -This is mainly useful for the case when the check for that component is specifically done separately. With `#[skip_check]`, one don't need to define another `delegate_components!` block just to wire components without checks. +The layout follows the convention the tooling expects: `cgp/SKILL.md` is the entry point, and +`cgp/references/` holds one file per area — components, wiring, checking, handlers, and the rest. The +entry point is a complete primer on its own, and it tells the assistant which reference to open for +the construct in front of it. -## Modularity Hierarchy +## Reading it yourself -The [reference for modularity hierarchy](references/modularity-hierarchy.md) summarizes the modularity hierarchy of the use of CGP and vanilla Rust constructs, using the `Serialize` trait from `serde` as the base example. +Nothing stops you, and the skill is written plainly enough to follow. But it is written *for a machine +reader*: it is dense, it repeats itself where repetition helps an assistant, and it assumes a reader +who wants exhaustive rules rather than a gentle path through them. -## Debugging Techniques +If you are learning CGP, the [Tutorials](/docs/tutorials/hello) start from a working program and the +[Concepts](/docs/concepts) pages take one idea at a time. Come back here when you want to see exactly +what your assistant has been told. -When compile errors are shown for a failed component wiring, try to identify the root cause by walking through the transitive dependencies shown within the error messages. +## What is published here -When you suspect that a required CGP component is not implemented for a context, try include that component in `check_components!` so that the error can be narrowed down. +The pages below are the skill's own files, served from the `cgp-skills` repository as a submodule +pinned to one revision. Nothing here is retyped or summarised — a page is the skill's own bytes — but it +is a *snapshot*, and the repository moves first. Treat the repository as canonical, and raise any issue +or correction there. -Note that not all trait are necessarily CGP component. An unsatisfied dependency can also be just regular trait or blanket trait. These dependencies cannot be verified via `check_components!`. - -## General Instructions for LLMs - -When interacting with the user, assume that the user only has basic Rust programming experience and is not familiar with any concept in CGP. - -Only provide further explanation for CGP concepts if the user asks for the specific explanation. Otherwise, assume that the user already understand the CGP concepts used in the code. - -When the user asks you to explain CGP concepts: - - You should assume that the user is not familiar with advanced Rust concepts, including generics, traits, blanket implementations, and the coherence problem. - - You should assume that the user is not familiar with functional programming and type-level programming concepts. So try to explain concepts like type-level tables, lists, or string, using more familiar OOP concepts, such as v-table lookup. - - Use full sentences and explain CGP concepts in ways that are approachable and engaging to beginners. You should include additional explanation for advanced concepts such as generics when applicable. - -When the user ask to explain a specific wiring in `delegate_components!`, always lookup the definition of the components and providers to give more details in your explanation. For example, if the user asks you to explain the following code: - -```rust -delegate_components! { - Person { - GretterComponent: - GreetHello, - } -} -``` - -you should look up for the definitions of `GreetComponent` and `GreetHello`. This includes finding out what are the names of the consumer trait and provider trait for `GreetComponent`, and the trait or impl body. - -When the user asks about the implementation details of a provider, always perform lookup on the original definition, and also the definition of all dependencies that the provider uses. For example, if the user asks you to explain the following: - -```rust -#[cgp_impl(GreetHello)] -impl Greeter for Context -where - Context: HasName, -{ - fn greet(&self) { - println!("Hello, {}!", self.name()); - } -} -``` - -you should lookup for the definition of `Greeter` and `HasName`, and include the details of those definitions in your explanation. - -When the user asks about how a provider is implemented for a context, also perform lookup based on the specific wiring for the context, and find out what other providers that implementation is linked to. For example, if you need to explain `GreetHello`, and you find the following wiring: - -```rust -delegate_components! { - Person { - NameGetterComponent: - UseField<"person_name">, - GretterComponent: - GreetHello, - } -} -``` +--- -then you should explain that for the `Person` context, since `NameGetterComponent` is wired to `UseField<"person_name">`, so when `println!("Hello, {}!", self.name())` is called from `GreetHello`, the value from `person_name` field will be returned from `self.name()`. +*This page was written by an AI agent from the CGP knowledge base — see +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/ai/skills/references/abstract-types.md b/docs/ai/skills/references/abstract-types.md new file mode 120000 index 00000000..1dcc0850 --- /dev/null +++ b/docs/ai/skills/references/abstract-types.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/abstract-types.md \ No newline at end of file diff --git a/docs/ai/skills/references/checking.md b/docs/ai/skills/references/checking.md new file mode 120000 index 00000000..ba2fb78e --- /dev/null +++ b/docs/ai/skills/references/checking.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/checking.md \ No newline at end of file diff --git a/docs/ai/skills/references/components.md b/docs/ai/skills/references/components.md new file mode 120000 index 00000000..1be8ff5e --- /dev/null +++ b/docs/ai/skills/references/components.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/components.md \ No newline at end of file diff --git a/docs/ai/skills/references/error-extraction.md b/docs/ai/skills/references/error-extraction.md new file mode 120000 index 00000000..a9f87756 --- /dev/null +++ b/docs/ai/skills/references/error-extraction.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/error-extraction.md \ No newline at end of file diff --git a/docs/ai/skills/references/error-handling.md b/docs/ai/skills/references/error-handling.md new file mode 120000 index 00000000..49935b1e --- /dev/null +++ b/docs/ai/skills/references/error-handling.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/error-handling.md \ No newline at end of file diff --git a/docs/ai/skills/references/extensible-data.md b/docs/ai/skills/references/extensible-data.md new file mode 120000 index 00000000..a60d2eb9 --- /dev/null +++ b/docs/ai/skills/references/extensible-data.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/extensible-data.md \ No newline at end of file diff --git a/docs/ai/skills/references/functions-and-getters.md b/docs/ai/skills/references/functions-and-getters.md new file mode 120000 index 00000000..40e7e3b9 --- /dev/null +++ b/docs/ai/skills/references/functions-and-getters.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/functions-and-getters.md \ No newline at end of file diff --git a/docs/ai/skills/references/handlers.md b/docs/ai/skills/references/handlers.md new file mode 120000 index 00000000..5ceb91b5 --- /dev/null +++ b/docs/ai/skills/references/handlers.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/handlers.md \ No newline at end of file diff --git a/docs/ai/skills/references/higher-order-providers.md b/docs/ai/skills/references/higher-order-providers.md new file mode 120000 index 00000000..a7fac975 --- /dev/null +++ b/docs/ai/skills/references/higher-order-providers.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/higher-order-providers.md \ No newline at end of file diff --git a/docs/ai/skills/references/macro-grammar.md b/docs/ai/skills/references/macro-grammar.md new file mode 120000 index 00000000..6116f1cf --- /dev/null +++ b/docs/ai/skills/references/macro-grammar.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/macro-grammar.md \ No newline at end of file diff --git a/docs/ai/skills/references/modern-idioms.md b/docs/ai/skills/references/modern-idioms.md new file mode 120000 index 00000000..fb39eb5f --- /dev/null +++ b/docs/ai/skills/references/modern-idioms.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/modern-idioms.md \ No newline at end of file diff --git a/docs/ai/skills/references/modularity-hierarchy.md b/docs/ai/skills/references/modularity-hierarchy.md deleted file mode 100644 index 26bd8340..00000000 --- a/docs/ai/skills/references/modularity-hierarchy.md +++ /dev/null @@ -1,192 +0,0 @@ -# Modularity Hierarchy - -This section summarizes the modularity hierarchy of the use of CGP and vanilla Rust constructs, using the `Serialize` trait from `serde` as the base example. - -## One Implementation per Interface - -Generic functions and blanket implementations allow the definition of exactly one implementation of the interface they define. - -Example generic function: - -```rust -pub fn serialize_bytes, S: Serializer>(value: &Value, serializer: S) -> Result { ... } -``` - -Blanket traits have the same limitations, but improve the ergonomic of generic functions by hiding the constraints behind the trait impl: - -```rust -pub trait CanSerializeBytes { - fn serialize_bytes(&self, serializer: S) -> Result; -} - -impl> CanSerializeBytes for Value { - fn serialize_bytes(&self, serializer: S) -> Result { ... } -} -``` - -## One Unique Implementation per Type per Interface - -Vanilla Rust traits allows multiple implementations to share the same interface, but the coherence restrictions allows at most one unique implementation per type for the interface they define. - -Example: - -```rust -pub trait Serialize { - fn serialize(&self, serializer: S) -> Result -} - -impl Serialize for Vec { - fn serialize(&self, serializer: S) -> Result { - self.serialize_bytes(serializer) - } -} - -impl<'a> Serialize for &'a [u8] { - fn serialize(&self, serializer: S) -> Result { - self.serialize_bytes(serializer) - } -} -``` - -The above example requires two explicit implementations of `Serialize` for `Vec` and `&[u8]`, even though both implementations share the same logic. - -However, the method implementation body can make use of explicit implementations earlier such as `CanSerializeBytes` to create reusable building blocks outside of the trait system. - -## Multiple Implementations per Type per Interface, Globally Unique Wiring per Type - -Basic CGP techniques can be applied on vanilla Rust traits to streamline the reuse of common implementation logic through provider traits. - -Example: - -```rust -#[cgp_component(ValueSerializer)] -pub trait Serialize { - fn serialize(&self, serializer: S) -> Result -} - -#[cgp_impl(new SerializeBytes)] -impl> ValueSerializer for Value { - fn serialize_bytes(&self, serializer: S) -> Result { ... } -} - -delegate_components! { - Vec { - ValueSerializerComponent: SerializeBytes, - } -} - -delegate_components! { - <'a> &'a [u8] { - ValueSerializerComponent: SerializeBytes, - } -} -``` - -The main advantage of this base approach is that the original `Serialize` trait is extended without modification to the original interface. This provides backward compatibility with existing Rust traits that are already widely used. - -A type can still implements `Serialize` directly without needing to opt in to use CGP for everything. - -The use of the `ValueSerializer` provider trait removes the need to write explicit interfaces like `CanSerializeBytes`. - -The use of `delegate_components!` removes the need to manually forward the method implementation through explicit method calls. - -The main limitation is that some coherence restrictions still apply. If we have an explicit `delegate_components!` wiring of `Vec` to `SerializeBytes`, then we cannot have a separate overlapping implementation or wiring for a generic `Vec`. - -The `Serialize` implementation for a type like `Vec` cannot be easily overridden for a specific context, such as to serialize a custom `Vec` field in a struct as hex string instead of bytes. - -The orphan rules still apply, so the use of `delegate_components!` cannot be applied to `Vec` outside of a crate that owns either `Serialize` or `Vec`. - -## Multiple Implementations per Type per Interface, Unique Wiring per Type per Context - -CGP supports full decoupling of an implementation from the type being implemented, by adding an explicit context parameter to configure the wiring of multiple types within the context. - -For example, the `Serialize` trait is changed to `CanSerializeValue`, with the original `Self` type moved to become an explicit `Value` parameter: - -```rust -#[cgp_component { - provider: ValueSerializer, - derive_delegate: UseDelegate, -}] -pub trait CanSerializeValue { - fn serialize(&self, value: &Value, serializer: S) -> Result - where - S: serde::Serializer; -} - -delegate_components! { - new MyAppA { - ValueSerializerComponent: - UseDelegate: SerializeBytes, - Vec: SerializeIterator, - ... - }>, - } -} - -delegate_components! { - new MyAppB { - ValueSerializerComponent: - UseDelegate: SerializeHex, - Vec: SerializeIterator, - ... - }>, - } -} -``` - -This allows explicit context types like `MyAppA` and `MyAppB` to be defined with different providers chosen for a type like `Vec`. - -The orphan rules no longer apply, so a context like `MyAppA` can wire the implementation of `Vec`, even if the crate don't own `CanSerializeValue` or `Vec`, as long as the crate owns the context `AppA`. - -The coherence restrictions are almost fully lifted, since the orphan wiring of a type like `Vec` means that we don't need to commit to a global implementation for `Vec` up front. - -The main disadvantage is that the trait needs to be modified to add an explicit context parameter for wiring. - -Furthermore, explicit wiring must be specified for all types used within a context, which can be tedious. - -## Multiple Implementations per Type per Interface, Explicit Wiring Per Type per Provider - -The use of higher order providers together with `UseContext` allows the wiring of the implementation of a type to be overridden within a provider, without routing it through the context. - -For example: - -```rust -pub struct SerializeIteratorWith(pub PhantomData); - -#[cgp_impl(SerializeIteratorWith)] -impl ValueSerializer for Context -where - for<'a> &'a Value: IntoIterator, - Provider: for<'a> ValueSerializer::Item>, -{ - fn serialize(&self, value: &Value, serializer: S) -> Result - where - S: serde::Serializer, - { ... } -} - -delegate_components! { - new MyAppA { - ValueSerializerComponent: - UseDelegate: SerializeBytes, - Vec>: SerializeIteratorWith, - Vec: SerializeIteratorWith, - [ - u8, - u64, - ]: - UseSerde, - ... - }>, - } -} -``` - -In the above example, the serialization of `Vec>` would serialize the inner `Vec` as hex strings, while other `Vec` would still be serialized as bytes. - -The default parameter allows the inner item serializer to be routed through the context as usual, if no overridding is required. The example `Vec` serialization would still go through the context, which result in `UseSerde` being used to serialize the `u64` items. - -This patterns allows further fine grained control of the wiring implementations that can be overridden locally on a per-provider basis, as compared a more "global" wiring at the per-context level. diff --git a/docs/ai/skills/references/modularity-hierarchy.md b/docs/ai/skills/references/modularity-hierarchy.md new file mode 120000 index 00000000..f534e9ce --- /dev/null +++ b/docs/ai/skills/references/modularity-hierarchy.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/modularity-hierarchy.md \ No newline at end of file diff --git a/docs/ai/skills/references/namespaces.md b/docs/ai/skills/references/namespaces.md new file mode 120000 index 00000000..395ca3f9 --- /dev/null +++ b/docs/ai/skills/references/namespaces.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/namespaces.md \ No newline at end of file diff --git a/docs/ai/skills/references/type-level-primitives.md b/docs/ai/skills/references/type-level-primitives.md new file mode 120000 index 00000000..a9f05118 --- /dev/null +++ b/docs/ai/skills/references/type-level-primitives.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/type-level-primitives.md \ No newline at end of file diff --git a/docs/ai/skills/references/wiring.md b/docs/ai/skills/references/wiring.md new file mode 120000 index 00000000..d5645fa3 --- /dev/null +++ b/docs/ai/skills/references/wiring.md @@ -0,0 +1 @@ +../cgp-skills/cgp/references/wiring.md \ No newline at end of file diff --git a/docusaurus.config.ts b/docusaurus.config.ts index 50bc1d27..5ff1c027 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -27,6 +27,17 @@ const config: Config = { onBrokenLinks: 'throw', + // Parse `.md` as CommonMark and `.mdx` as MDX, rather than treating every file + // as MDX. The skill pages under `docs/ai/skills/` are symlinks into the + // `cgp-skills` submodule — plain markdown written for coding agents, by a + // repository that has no reason to know about MDX — and MDX would read an + // autolink like `` as a JSX tag and fail the build. No page + // on this site uses MDX-only syntax (imports, exports, or JSX components), so + // nothing else changes: admonitions and raw HTML work under both. + markdown: { + format: 'detect', + }, + // Even if you don't use internationalization, you can use this field to set // useful metadata like html lang. For example, if your site is Chinese, you // may want to replace "en" with "zh-Hans". @@ -35,6 +46,22 @@ const config: Config = { locales: ['en'], }, + plugins: [ + // Keep webpack from resolving a symlink to its real path. The skill pages + // under `docs/ai/skills/` are symlinks into the `cgp-skills` submodule, whose + // real path sits outside `docs/`; resolved, the compiled module no longer + // matches the metadata the docs plugin registered for the symlink, and every + // such page fails to render with `Cannot read properties of undefined`. + function resolveSymlinkedDocs() { + return { + name: 'resolve-symlinked-docs', + configureWebpack() { + return {resolve: {symlinks: false}}; + }, + }; + }, + ], + presets: [ [ '@docusaurus/preset-classic', @@ -42,6 +69,12 @@ const config: Config = { docs: { showLastUpdateTime: true, sidebarPath: './sidebars.ts', + // The `cgp-skills` submodule is checked out inside `docs/ai/skills/` so + // the skill pages can symlink to it from next door. Its own files are the + // source, not pages: the ones we publish are reached through those + // symlinks, and the rest (README, AGENTS, sibling-projects) are not site + // content at all. + exclude: ['**/cgp-skills/**'], // Please change this to your repo. // Remove this to remove the "edit this page" links. editUrl: From 0a6c66ae70a3ddc7bd1babcc162fe93717b59c81 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 16:36:22 +0200 Subject: [PATCH 024/516] Sync the skill snapshot to its heading fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Advances the `cgp-skills` pin to `82caa3d`, which gives `SKILL.md` and `macro-grammar.md` a single top-level heading each. The rendering consequence is the point of the bump. The site anchors `h2` and `h3` only, so the fourteen and ten `#` sections those two files used to carry were unanchored, missing from their tables of contents, and unlinkable — and `SKILL.md`'s own cross-reference to *Sub-skills* was the broken anchor this build had been warning about since the section was published. `SKILL.md` now renders thirty-one anchored headings against eighteen before, `macro-grammar.md` twenty-four, and the build reports no broken anchors. Nothing here changed but the pointer; the pages are symlinks and carry no content of their own. Co-Authored-By: Claude Opus 5 (1M context) --- docs/ai/skills/cgp-skills | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ai/skills/cgp-skills b/docs/ai/skills/cgp-skills index e0f72c2d..82caa3d4 160000 --- a/docs/ai/skills/cgp-skills +++ b/docs/ai/skills/cgp-skills @@ -1 +1 @@ -Subproject commit e0f72c2d0e93367aa8f8f6ecd69624f539254f08 +Subproject commit 82caa3d40149dcb3d8ddebd4b3ce2c66ad5069bf From 2ab95ce1e555456038d3cbba5a12d7b6f4348ff2 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 16:55:55 +0200 Subject: [PATCH 025/516] Add the cargo-cgp section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The site had no page for the error toolchain at all, which left its most consequential recommendation unmakeable: every argument that CGP's diagnostics are survivable rests on a tool a reader could not read about here. Five pages now sit in a top-level category beside the reference — beside rather than inside, because every reference page answers "what does this construct mean" and these answer "how do I run this". The overview leads on the problem rather than the tool, and its argument is one mistake shown twice: a context that lost the field its provider reads, first as plain `cargo check` reports it — a `Chars` spine spelling the field name one character per type parameter — and then as `cargo cgp check` does, naming the missing field in English over the dependency chain that demanded it. It also makes the point the tool is easiest to undersell on: the substantive job is *un-hiding* rather than reshaping, because the default trait solver never names the failing bound in CGP's worst class, so the answer is absent from the output rather than buried in it. `check` and `expand` get a page each, since a reader arrives wanting one of them. `installation` opens with a table matching what a reader *has* to the path they should take, and includes the agent-skill route with what the skill actually instructs — check before debugging, ask before installing, mention Nix only when it is present. `troubleshooting` opens with a symptom index, because a reader arrives holding an error message and nothing else. **Every command was run and every output pasted rather than remembered.** That is also how the one wrong claim in this section was caught before publishing: a draft repeated the internal reference's statement that `expand` answers `--help` itself, and it does not — it forwards, and `--item` appears nowhere in cargo's help, which makes the flag undiscoverable and is an argument for documenting it rather than evidence the tool already does. The AI category moves from position 6 to 7 so the tool sits directly after the reference, which is where the information architecture places it. The two pages that show Rust are backed in `example-code/src/cargo_cgp/`: the broken program the check page runs the tool on is a `compile_fail` doctest, the fixed one the expand page expands is a live module with a test. Co-Authored-By: Claude Opus 5 (1M context) --- docs/ai/_category_.json | 2 +- docs/cargo-cgp/_category_.json | 8 + docs/cargo-cgp/check.md | 178 ++++++++++++++++++++ docs/cargo-cgp/expand.md | 180 ++++++++++++++++++++ docs/cargo-cgp/index.md | 127 ++++++++++++++ docs/cargo-cgp/installation.md | 190 +++++++++++++++++++++ docs/cargo-cgp/troubleshooting.md | 242 +++++++++++++++++++++++++++ example-code/README.md | 1 + example-code/src/cargo_cgp/check.rs | 44 +++++ example-code/src/cargo_cgp/expand.rs | 52 ++++++ example-code/src/cargo_cgp/mod.rs | 11 ++ example-code/src/lib.rs | 1 + 12 files changed, 1035 insertions(+), 1 deletion(-) create mode 100644 docs/cargo-cgp/_category_.json create mode 100644 docs/cargo-cgp/check.md create mode 100644 docs/cargo-cgp/expand.md create mode 100644 docs/cargo-cgp/index.md create mode 100644 docs/cargo-cgp/installation.md create mode 100644 docs/cargo-cgp/troubleshooting.md create mode 100644 example-code/src/cargo_cgp/check.rs create mode 100644 example-code/src/cargo_cgp/expand.rs create mode 100644 example-code/src/cargo_cgp/mod.rs diff --git a/docs/ai/_category_.json b/docs/ai/_category_.json index 4aab1dbb..826f60f3 100644 --- a/docs/ai/_category_.json +++ b/docs/ai/_category_.json @@ -1,6 +1,6 @@ { "label": "AI Assisted Development", - "position": 6, + "position": 7, "link": { "type": "generated-index" } diff --git a/docs/cargo-cgp/_category_.json b/docs/cargo-cgp/_category_.json new file mode 100644 index 00000000..b839d716 --- /dev/null +++ b/docs/cargo-cgp/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "cargo-cgp", + "position": 6, + "link": { + "type": "doc", + "id": "cargo-cgp/index" + } +} diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md new file mode 100644 index 00000000..d19b5219 --- /dev/null +++ b/docs/cargo-cgp/check.md @@ -0,0 +1,178 @@ +--- +sidebar_position: 3 +--- + +# Check + +`cargo cgp check` stands in for `cargo check` and re-presents CGP's wiring errors with their root cause +first. + +```sh +cargo cgp check +``` + +Run it from anywhere inside a cargo package or workspace that uses `cgp`. Everything after `check` is +forwarded verbatim to `cargo check`, so the flags you already use work unchanged: + +```sh +cargo cgp check --workspace +cargo cgp check -p my-crate +cargo cgp check --all-targets +``` + +## A worked example + +Here is a complete program with one mistake in it. `RectangleArea` reads a `height` field through an +[`#[implicit]`](/docs/reference/attributes/implicit) argument, and `Rectangle` does not have one — +someone removed it, or never added it. + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} +``` + +Running the tool on it: + +```text +$ cargo cgp check + +error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` + --> src/lib.rs:28:9 + | +28 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + └─ [CGP-E106] missing field `height` on `Rectangle` + +For more information about this error, try `rustc --explain E0277`. +``` + +**Read the `root cause:` line first.** It names the fix — add a `height: f64` field to `Rectangle`, or +stop reading one. The tree beneath it is the chain of obligations that demanded it, read top to bottom: +the context has to implement the consumer trait, which means its wired provider has to be a provider +for that context, which means the context has to have the field. + +For comparison, the same mistake under plain `cargo check`: + +```text +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` +``` + +The field name is in there, one character per type parameter. That is the class of message the tool +exists to turn into a sentence. + +## Reading the output + +The output is ordinary rustc and cargo diagnostics, with the errors the tool recognizes rewritten. +A rewritten message carries a short code in square brackets: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` +``` + +The `[CGP-Exxx]` code names one class of CGP mistake. Codes appear in two places and mean slightly +different things: the one in the **headline** classifies the error, and the ones in the **root-cause +tree** label each link in the chain. In the example above, `CGP-E001` is "a context does not implement +a consumer trait", `CGP-E106` is "a required field is missing", and `CGP-E101`/`CGP-E102` are the +consumer and provider impls in between. + +The compiler's own code is always kept — `E0277` here — so `rustc --explain` still works and nothing is +reclassified away from rustc. The CGP code rides inside the message as a tag on the sentence it +classifies. **Errors the tool does not recognize pass through exactly as the compiler wrote them.** + +## What a check does differently + +Three deliberate differences from `cargo check`, all handled for you: + +- **It compiles under the tool's pinned nightly**, not your project's toolchain, so the diagnostics are + reproducible and the embedded compiler matches the driver. Your project's toolchain is untouched. +- **It turns on the next-generation trait solver.** This is the substantive one: the default solver + *hides* the failing bound in CGP's worst error class, reporting only that a method's bounds were not + satisfied. The new solver names the bound, which is what makes a root cause available to print. +- **It builds into `target/cgp`** rather than your project's `target/`, so a check never invalidates + your normal build cache and vice versa. + +Pass `--target-dir` (or set `CARGO_TARGET_DIR`) to send the artifacts elsewhere. + +Because those are settings the tool chooses, a check is a diagnostic pass rather than a reproduction of +your own `cargo check` — the same relationship Clippy has to your build. + +## Flags are cargo's, not the tool's + +The tool appends your arguments to `cargo check` and lets cargo own them. Three consequences are worth +knowing: + +- Every `cargo check` flag behaves exactly as it does normally, because that is literally what runs. +- **cargo validates them, not cargo-cgp**, so an unknown flag produces cargo's error + (`error: unexpected argument '--nope' found`) rather than a cargo-cgp message. +- `cargo cgp check --help` prints *cargo's* help and exits **without running a check**, since `--help` + is forwarded like anything else. + +The one flag the tool inspects is `--target-dir`, and only to decide whether to supply its own default. + +## In your editor + +Rust Analyzer can run the check on save. It is two words and must emit JSON, so wire it through +`check.overrideCommand` rather than `check.command`: + +```json +"rust-analyzer.check.overrideCommand": [ + "cargo", "cgp", "check", "--workspace", "--all-targets", "--message-format=json" +] +``` + +The transformed diagnostics are rendered as rustc JSON, which cargo wraps and the editor parses, so the +rewritten messages appear inline. The isolated `target/cgp` directory earns its keep here too: the +editor's checking does not contend with your own builds. + +## When it will not help + +**A check only reports what your code asks the compiler to prove.** CGP's wiring is lazy, so a context +that is never checked and never used produces no error at all — from this tool or any other. Pair your +wiring with [`check_components!`](/docs/reference/macros/check_components), which is what forces a +missing dependency to surface at the wiring site instead of at some distant call. + +**Some classes still pass through raw.** The tool is a `v0.1.0-alpha` that reshapes the core wiring +errors; orphan-rule violations, among others, arrive as the compiler wrote them. + +If the command itself will not run, see [Troubleshooting](./troubleshooting.md). + +--- + +*This page was written by an AI agent from the CGP knowledge base; its example and both outputs were +produced by running the tool — see +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md new file mode 100644 index 00000000..44f98f57 --- /dev/null +++ b/docs/cargo-cgp/expand.md @@ -0,0 +1,180 @@ +--- +sidebar_position: 4 +--- + +# Expand + +`cargo cgp expand` prints your crate as the compiler sees it after macro expansion, so you can read +what a CGP macro actually generated instead of reasoning about what it probably generated. + +```sh +cargo cgp expand --lib +``` + +:::note + +`expand` landed after the published `v0.1.0-alpha`, so an install from crates.io does not carry it yet. +Get it from the Nix flake with the tag dropped +(`nix run github:contextgeneric/cargo-cgp -- expand --lib`) or from a source build — see +[Installation](./installation.md#expand-is-newer-than-the-published-release). `cargo cgp check` is +unaffected. + +::: + +## What it looks like + +Taking the `Rectangle` context from the [Check](./check.md) page, once its missing field is restored: + +```sh +cargo cgp expand --lib --item Rectangle +``` + +```rust +pub struct Rectangle { + pub width: f64, + pub height: f64, +} +impl HasField for Rectangle { + type Value = f64; + fn get_field( + &self, + key: ::core::marker::PhantomData, + ) -> &Self::Value { + &self.width + } +} +impl HasFieldMut for Rectangle { + fn get_field_mut( + &mut self, + key: ::core::marker::PhantomData, + ) -> &mut Self::Value { + &mut self.width + } +} +// … the same pair again for `height` … +impl DelegateComponent for Rectangle { + type Delegate = RectangleArea; +} +impl< + __Context__, + __Params__, +> IsProviderFor for Rectangle +where + RectangleArea: IsProviderFor, +{} +impl __CheckRectangle for Rectangle {} +``` + +Everything a reader needs in order to follow a wiring error is visible there: the field accessors +`#[derive(HasField)]` produced, the one-line table entry `delegate_components!` produced, the +forwarding impl that carries the provider's requirements, and the assertion `check_components!` added. + +## Narrowing with `--item` + +A whole crate's expansion is long — for the tiny example above, 148 lines against 49 for the one item. +`--item` takes a `::`-separated path naming something *inside* the crate, and what you get depends on +what you name: + +```sh +cargo cgp expand --lib --item shapes # a module: its contents +cargo cgp expand --lib --item shapes::Rectangle # a type: its declaration and every impl for it +cargo cgp expand --lib --item AreaCalculator # a trait: its definition and every impl of it +``` + +A leading `crate::` is accepted, so `--item crate::contexts::app` and `--item contexts::app` are the +same request. + +**The trait form is usually the one you want on CGP code**, because a component's generated items *are* +impls. Naming a component's *provider* trait gives you the provider trait, the delegation blanket impl, +the `UseContext` impl, and each wired provider's impl of it — the whole resolution path in one listing. +Naming the *consumer* trait gives just that trait and its routing blanket. The type form is the +companion, and is what the example above uses. + +If the path matches nothing, the tool says so rather than falling back to a whole-crate dump: + +```text +error: no module or item matched `NoSuchThing` +note: the path names a module or item inside the crate being expanded, as in `contexts::app`; + a leading `crate::` is accepted too +``` + +## Choosing a target + +`expand` expands exactly one target, and arguments are forwarded to `cargo rustc`, so target selection +is cargo's. A package with both a library and a binary therefore needs to be told which: + +```sh +cargo cgp expand --lib +cargo cgp expand --bin my-app +cargo cgp expand -p my-crate --lib +``` + +Without one, cargo declines with *"extra arguments to `rustc` can only be passed to one target"*. That +is worth knowing before your first run, because the message is cargo's and does not mention `expand`. + +Output goes to stdout, so it redirects and pipes like anything else: + +```sh +cargo cgp expand --lib > expanded.rs +cargo cgp expand --lib | rg 'Symbol!' +``` + +`cargo cgp expand --help` forwards like everything else, so what you get is `cargo rustc`'s own help — +which does **not** mention `--item`, since that flag is the tool's rather than cargo's. This page is +where you learn it exists. + +## Why not `cargo-expand` + +`cargo-expand` is the general tool and it works on CGP code. The reason to reach for this one is that +CGP's generated code is dominated by *type-level constructs*, and a general expander prints them as the +compiler stores them. + +**A field name is the clearest case.** CGP encodes it as a type-level string — one type parameter per +character. Expanded generically, the `height` tag above reads: + +```text +Symbol<6, Chars<'h', Chars<'e', Chars<'i', Chars<'g', Chars<'h', Chars<'t', Nil>>>>>>> +``` + +`cargo cgp expand` resugars it back to `Symbol!("height")`, which is what you wrote. It does the same +for the rest of the vocabulary — a pipeline reads `Product![StepOne, StepTwo]` rather than a `Cons` +spine, and a namespace key reads `Path!(@app.GreeterComponent)`. On a page of wiring the difference is +between a listing you can read and one you have to decode. + +Two smaller differences follow from the same purpose. **`--item` understands Rust items** — asking for +a trait gives you every impl *of* it, which is the shape a CGP question actually takes, rather than a +textual filter. And **the `cgp::macro_prelude::` qualifier is stripped**, which makes the output far +easier to read at the cost of not being compilable — see below. + +## What to expect from the output + +**Every macro is expanded, not only CGP's.** `#[derive(Debug)]` and `println!` appear in their +generated form too. The CGP-specific part is the resugaring, not the selection. + +**The output is for reading, not compiling.** Stripping the `cgp::macro_prelude::` qualifier is what +makes it legible, and it also means you cannot paste the result back into your crate and expect it to +build. + +**`expand` is not a check.** Compilation stops as soon as the macros are expanded, so no type analysis +runs and no CGP diagnostic is produced. A malformed macro invocation still fails, because that happens +during expansion — but a wiring mistake does not surface here at all. That is exactly what makes it +useful mid-debugging: it works on a crate that does not type-check. For the wiring mistake itself, use +[`cargo cgp check`](./check.md). + +## When to reach for it + +Four situations, all of them cases where the answer is in the generated code rather than in a message: + +- **A diagnostic names a type you did not write** — `IsProviderFor`, a `PathCons` key, a `__Context__` + parameter — and you want to see the impl it came from. +- **A wiring table does not resolve** and you want its real `DelegateComponent` keys and values rather + than inferring them from the table's syntax. +- **You are unsure what a construct emits** — the exact `where` clauses of a provider impl, whether a + getter's blanket impl needs the field you think it does. +- **Two forms differ and only one compiles.** Expand both and diff; the delta is the bug. + +--- + +*This page was written by an AI agent from the CGP knowledge base; its example output was produced by +running the tool — see +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md new file mode 100644 index 00000000..2212eac5 --- /dev/null +++ b/docs/cargo-cgp/index.md @@ -0,0 +1,127 @@ +--- +sidebar_position: 1 +--- + +# cargo-cgp + +`cargo-cgp` is CGP's error toolchain: a cargo subcommand that stands in for `cargo check` and presents +CGP's compiler errors root cause first, plus a second command that shows the ordinary Rust your macros +generate. + +## The problem it solves + +CGP's wiring is **lazy**. A `delegate_components!` entry is accepted without checking that the provider +it names can actually do the job, so a context with a missing field or an unmet dependency compiles +fine and fails somewhere else entirely — usually at the first call to the capability, in a message +about types you never wrote. + +Here is the whole of a mistake: a `Rectangle` that lost its `height` field while a provider still reads +it. + +```rust +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, +} +``` + +Under plain `cargo check`, with the mistake pinned to the wiring site by +[`check_components!`](/docs/reference/macros/check_components), this is what comes back: + +```text +error[E0277]: the trait bound `Rectangle: HasField>>` is not satisfied + | +28 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` +``` + +The answer is in there — the field is spelled out one character per type parameter — but you have to +decode a `Chars` spine to read it, and this is the *good* case, where a check forced the failure to the +wiring site. + +`cargo cgp check` reports the same mistake like this: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` + --> src/lib.rs:28:9 + | +28 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + └─ [CGP-E106] missing field `height` on `Rectangle` +``` + +Same error, same `E0277`, same span. What changed is that the cause is named in English on the second +line, and the chain that demanded it is drawn out beneath. + +## How it does that + +Two things, and the first matters more than the reshaping. + +**It un-hides causes the compiler suppresses.** The worst class of CGP error is not verbose but +*incomplete*: the default trait solver stops at "the trait bounds were not satisfied" without ever +naming the bound that failed, so the answer is absent from the output rather than buried in it. +`cargo cgp check` compiles under Rust's next-generation trait solver, which reports the real missing +bound — and that is what makes a root cause available to print at all. + +**It rewrites the classes it recognizes.** Where the tool knows the shape of a CGP failure, it leads +with the cause, draws the dependency chain as a tree, and stamps the message with a `[CGP-Exxx]` code +naming the class. The compiler's own code is always kept, so `rustc --explain E0277` still works and +nothing is reclassified away from rustc. + +## The two commands + +[**`cargo cgp check`**](./check.md) stands in for `cargo check` when you hit or expect a wiring error. +Everything after `check` is forwarded to cargo, so the flags you already use work unchanged. + +[**`cargo cgp expand`**](./expand.md) prints what your CGP macros generated, with CGP's type-level +constructs spelled the way you wrote them — a field tag reads `Symbol!("height")` rather than the +six-level `Chars` spine above. It is how you answer "what did that macro actually produce?" rather than +reasoning about what it probably produced. + +## What it is not + +**It is optional, and it is not a build tool.** CGP is an ordinary library that compiles on **stable +Rust 1.89 or newer**, so `cargo build`, `cargo run`, and `cargo test` work on a CGP project unchanged +and should stay as they are. There is no `cargo cgp build` or `cargo cgp test`. Reach for +`cargo cgp check` when you want a wiring error made readable, and plain `cargo check` when you do not. + +**It is a diagnostic pass rather than a reproduction of your own build.** A check runs under the tool's +pinned nightly, turns on the next-generation solver, and builds into a separate `target/cgp` directory, +so it neither adopts your project's toolchain nor disturbs its build cache — much as Clippy runs under +its own settings. + +**It is a `v0.1.0-alpha`, and the honest description is *dramatically better, not solved*.** The tool +reshapes the core wiring errors and passes everything else through as the compiler wrote it, so some +classes — orphan-rule violations among them — still arrive raw. If you hit one, the +[reference](/docs/reference) and [`check_components!`](/docs/reference/macros/check_components) are +still the tools that localize it. + +## Next + +- [Installation](./installation.md) — cargo, Nix, running it without installing, or asking your coding + assistant to set it up. +- [Check](./check.md) — running it, reading the output, and wiring it into your editor. +- [Expand](./expand.md) — seeing through the macros, and why it is not `cargo-expand`. +- [Troubleshooting](./troubleshooting.md) — matching an error to its cause when the tool itself will not + run. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the tool's own +output — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md new file mode 100644 index 00000000..12e6c38a --- /dev/null +++ b/docs/cargo-cgp/installation.md @@ -0,0 +1,190 @@ +--- +sidebar_position: 2 +--- + +# Installation + +`cargo-cgp` is two binaries plus one exact nightly compiler, and installing it means getting all three +in place and matched. The `cargo-cgp` front-end is the subcommand you type; the `cargo-cgp-driver` it +calls links the compiler's internals, so it has to be built against the nightly it embeds. + +You never type that nightly date, and **your own project never adopts it** — the tool forces its +toolchain only for its own check, and your project keeps whatever it already uses for ordinary builds. + +## Which path to use + +| You have | Use | Why | +|---|---|---| +| rustup | [cargo](#with-cargo) | Installs a small front-end, then provisions the rest for you | +| Nix | [Nix](#with-nix) | Builds both binaries against the pinned nightly; no rustup needed | +| Nix, and want to try it once | [without installing](#without-installing) | Runs from the flake in place | +| A coding assistant | [the agent skill](#let-your-coding-assistant-do-it) | It detects the tool is missing and offers to install it | + +## With cargo + +Two commands, and the first is one you can type from memory because it carries no version in it: + +```sh +cargo install cargo-cgp +cargo cgp setup +``` + +They divide the work deliberately. `cargo install cargo-cgp` builds the front-end, which has no +compiler linkage and so installs under whatever toolchain you already have. `cargo cgp setup` then does +everything heavyweight: it installs the pinned nightly with its `rustc-dev` and `llvm-tools` +components, builds the driver against that exact nightly, and places it beside the front-end. `setup` +needs rustup, since that is what it manages toolchains through. + +You run `setup` once, and again only when the tool tells you to. Before each check the front-end runs a +fast read-only preflight; if the driver is missing, the toolchain absent, or the two out of step, it +stops and names `cargo cgp setup` as the fix rather than doing slow or stateful work behind your back. + +## With Nix + +The flake builds both binaries against the pinned nightly and wraps them so they run without rustup — +so a machine with only Nix can run the tool, and the project you check needs no toolchain of its own. + +```sh +nix profile install github:contextgeneric/cargo-cgp +``` + +Append a released tag to pin an exact version rather than the default branch, which is the form to +prefer when you want the install reproducible: + +```sh +nix profile install github:contextgeneric/cargo-cgp/v0.1.0-alpha +``` + +## Without installing + +To try the tool on a project without putting anything on your `PATH`, run the flake's default app from +that project's directory. Everything after `--` is forwarded to the check: + +```sh +cd /path/to/your/project +nix run github:contextgeneric/cargo-cgp -- check +``` + +This is also the form to use in CI. Add a `/v0.1.0-alpha` suffix to pin the release, or leave it off to +track the default branch. + +To pin the tool inside another project's own flake, take its `packages.default`: + +```nix +inputs.cargo-cgp.url = "github:contextgeneric/cargo-cgp/v0.1.0-alpha"; +# then, in a devShell or CI derivation: +# packages = [ cargo-cgp.packages.${system}.default ]; +``` + +## Let your coding assistant do it + +If you work with an LLM assistant that has [CGP's agent skill](/docs/ai/skills) loaded, you do not have +to drive this yourself. The skill tells the assistant to check whether `cargo-cgp` is available before +debugging any CGP compile error, to recommend it when it is missing, and to prefer it over plain +`cargo check` when diagnosing a wiring failure. Asking your assistant to set up CGP tooling is enough. + +Two things the skill is deliberately careful about, so you are not surprised: + +- **It asks before installing.** Provisioning a nightly toolchain and building a compiler-linked driver + is heavy, so the skill instructs the assistant to get your approval rather than run `setup` on its + own. +- **It prefers cargo, and only mentions Nix if you have it.** The skill reaches for the Nix path when a + `nix` command or a `flake.nix` is actually present, and otherwise does not bring it up. + +## Checking what you have + +```sh +cargo cgp +``` + +With no subcommand, the front-end prints its version and the commands it accepts. **Read the command +list rather than the version number**, because the two can disagree: a build from the default branch +still reports the released version while carrying commands that release does not have. If `expand` is +absent from the list, see the note below. + +The driver has its own version query, which loads the compiler library before printing and so doubles +as a check that it can run at all: + +```sh +cargo-cgp-driver --version +``` + +On success it prints three lines — its own version, the `pinned-toolchain:` it needs, and the +`built-against-rustc:` compiler it was built with. That first pair is the fastest way to see which +nightly a driver actually wants. + +:::note + +### `expand` is newer than the published release + +`cargo cgp expand` landed after `v0.1.0-alpha` was tagged, so an install from crates.io does not carry +it — `cargo cgp check` is unaffected. Until the next release, get it from the flake with the tag +dropped, which tracks the default branch: + +```sh +nix run github:contextgeneric/cargo-cgp -- expand --lib +``` + +or from a [source build](#from-source). + +::: + +## From source + +To run the current code, clone and build. The repository's own `rust-toolchain.toml` selects the right +nightly automatically: + +```sh +git clone https://github.com/contextgeneric/cargo-cgp +cd cargo-cgp +cargo build +``` + +Then run the freshly built front-end against another project, pointing it at the built driver and +skipping the preflight: + +```sh +CARGO_CGP_NO_MANAGE=1 CARGO_CGP_DRIVER=$PWD/target/debug/cargo-cgp-driver \ + /path/to/cargo-cgp/target/debug/cargo-cgp check +``` + +For most from-source use the Nix flake is easier, because it wires these overrides for you. + +## Updating + +On the cargo path, one command: + +```sh +cargo cgp update +``` + +It reads the crates.io index, stays within your current release channel — a stable install never jumps +to a pre-release, and a pre-release install stays on pre-releases — and does nothing if you are already +current. When there is something newer it reinstalls the front-end and re-runs `setup` so the driver and +toolchain move with it. On Windows the running binary cannot replace itself, so `update` prints the two +commands to run by hand instead. + +On the Nix path there is no `cargo cgp update`: upgrade the profile (`nix profile upgrade`), or run +`nix flake update cargo-cgp` where you pinned it as an input. + +## Uninstalling + +There is no `cargo cgp uninstall`; you remove the binaries with whatever placed them. + +```sh +nix profile remove cargo-cgp # Nix path +cargo uninstall cargo-cgp cargo-cgp-driver # cargo path — both, since setup installed the driver +``` + +Neither removes the pinned nightly, because another tool may still want that dated toolchain. Remove it +by hand only when nothing else needs it; its name is the `pinned-toolchain:` line of +`cargo-cgp-driver --version`: + +```sh +rustup toolchain uninstall +``` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the tool — see +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md new file mode 100644 index 00000000..69f668ed --- /dev/null +++ b/docs/cargo-cgp/troubleshooting.md @@ -0,0 +1,242 @@ +--- +sidebar_position: 5 +--- + +# Troubleshooting + +`cargo-cgp` is two binaries plus one exact nightly compiler, held together by a sibling-path lookup and +a couple of environment variables. When it will not run, the fault sits at one of those seams. This +page maps the error you see to the seam it came from. + +## Start with the symptom index + +Match the distinctive fragment of your error, then read the section. + +| Error fragment | Cause | Section | +|---|---|---| +| `unknown cargo-cgp subcommand` | wrong invocation | [The command itself fails](#the-command-itself-fails) | +| `could not find Cargo.toml` | run outside a cargo package | [The command itself fails](#the-command-itself-fails) | +| `is cargo on PATH?` | cargo missing from `PATH` | [The command itself fails](#the-command-itself-fails) | +| `failed to run the cargo-cgp-driver at …` | driver missing | [The driver cannot be found](#the-driver-cannot-be-found) | +| `could not execute process` … `(never executed)` | driver path wrong | [The driver cannot be found](#the-driver-cannot-be-found) | +| `error while loading shared libraries: librustc_driver-…` | library path unset, or toolchain mismatch | [The driver cannot load the compiler](#the-driver-cannot-load-the-compiler) | +| `--print sysroot` failed with `exit status: 127` | Nix install shadowed by a same-version rustup toolchain | [A Nix install fails its sysroot probe](#a-nix-install-fails-its-sysroot-probe) | +| `the pinned toolchain is not installed` | nightly absent | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `could not run under toolchain …` | driver built against another nightly | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `out of lockstep` / `now provides` | front-end and driver disagree | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `rustup was not found on PATH` | no rustup for `setup` | [Provisioning fails](#provisioning-fails) | + +## Isolating the failure + +Two probes narrow almost anything before you read further. + +**First, ask the driver for its version.** It loads the compiler library before printing, so this +doubles as a test that it can run at all: + +```sh +cargo-cgp-driver --version +``` + +If that fails, the problem is the driver or its library path, not the front-end — jump to +[The driver cannot load the compiler](#the-driver-cannot-load-the-compiler). On success it prints the +`pinned-toolchain:` it needs and the `built-against-rustc:` it was built with, which is the fastest way +to see which nightly a given driver actually wants. + +**Then run the check verbosely:** + +```sh +cargo cgp check -v +``` + +Each `Running …` line showing a `cargo-cgp-driver … rustc …` command is the driver being invoked. An +error *before* those lines is a front-end or preflight problem; an error *from* one of them is a driver +or compiler problem. + +## The command itself fails + +The simplest failures never reach the driver. An unknown or missing subcommand is reported with the +list of what is accepted: + +```text +cargo-cgp: unknown cargo-cgp subcommand `frobnicate` (expected `check`, `expand`, `setup`, or `update`) +``` + +If your build lists only three and omits `expand`, that is not a fault — it predates that command. See +[Installation](./installation.md#expand-is-newer-than-the-published-release). + +Running outside a cargo package produces cargo's error rather than the tool's, because the front-end +forwards to `cargo check`: + +```text +error: could not find `Cargo.toml` in `/some/dir` or any parent directory +``` + +Run it from inside the package or workspace you mean to check. And if cargo is not on `PATH` at all, +the front-end says so while trying to launch the build: + +```text +failed to run `cargo check` (is cargo on PATH?) +``` + +## The driver cannot be found + +The front-end looks for the driver **beside itself**, in the same directory, unless `CARGO_CGP_DRIVER` +says otherwise. When it is missing, the message depends on whether the preflight is running. + +Normally the preflight catches it and names the fix: + +```text +cargo-cgp: failed to run the cargo-cgp-driver at /path/to/cargo-cgp-driver: No such file or directory (os error 2) + +Run `cargo cgp setup`. +``` + +With the preflight skipped — the from-source and Nix paths set `CARGO_CGP_NO_MANAGE` — the bad path +reaches cargo instead, which reports a wrapper it could not execute: + +```text +error: could not execute process `/path/to/cargo-cgp-driver …/rustc -vV` (never executed) + +Caused by: + No such file or directory (os error 2) +``` + +Either way, make the driver reachable: run `cargo cgp setup` to reinstall it beside the front-end, point +`CARGO_CGP_DRIVER` at the real binary (for a source build, `target/debug/cargo-cgp-driver`), or run +through the Nix flake, which places both binaries together. + +## The driver cannot load the compiler + +This is the most common failure and the most confusing, because the driver aborts *before its own code +runs* and the message comes from the operating system's loader: + +```text +cargo-cgp-driver: error while loading shared libraries: librustc_driver-c29d28819724b6fa.so: +cannot open shared object file: No such file or directory +``` + +The driver links `librustc_driver-.so` from the nightly it was built against, and that hash is +fixed at build time. The loader cannot find *that exact library*, for one of two reasons. + +**The library path is not set.** You ran the driver directly, without the search-path setup the +front-end normally provides. A Nix-built driver has the path baked into its wrapper and never hits +this; a from-source driver run by hand does. Supply the pinned toolchain's `lib` directory — +`DYLD_FALLBACK_LIBRARY_PATH` on macOS, `LD_LIBRARY_PATH` elsewhere: + +```sh +SYSROOT=$(rustc --print sysroot) # under the pinned toolchain +LD_LIBRARY_PATH=$SYSROOT/lib cargo-cgp-driver --version +``` + +**Or the path is set to the wrong toolchain.** The exact library is absent because the active toolchain +is not the one the driver was built against — the driver wants a dated nightly, the environment offers +stable: + +```text +error: process didn't exit successfully: `…/cargo-cgp-driver …/stable/…/rustc -vV` (exit status: 127) +--- stderr +…/cargo-cgp-driver: error while loading shared libraries: librustc_driver-c29d28819724b6fa.so +``` + +A normal install forces the right nightly for you. If you are running unmanaged, either make the pinned +nightly active — work inside the `cargo-cgp` checkout, whose `rust-toolchain.toml` selects it, or set +`RUSTUP_TOOLCHAIN` — or use the Nix flake, which forces the matching nightly from any directory. + +## A Nix install fails its sysroot probe + +A Nix-installed tool can fail before compiling anything, on the query it makes to locate the +toolchain's libraries: + +```text +cargo-cgp: `/nix/store/…-rust-minimal-…/bin/rustc --print sysroot` failed with status exit status: 127: + +rustc: error while loading shared libraries: libz.so.1: cannot open shared object file +``` + +Two things make this one recognizable: **the same command run by hand succeeds**, and it fails only in +*some* projects. Both follow from one cause — a foreign toolchain's library directory reaching the Nix +toolchain's binaries. Invoked as `cargo cgp`, the entry point is rustup's `cargo` shim, which exports +the project's active toolchain's `lib` directory to everything it spawns, and the loader searches that +ahead of the binary's own path. + +Whether it matters depends on the project, because a rustc shared library is named for its Rust version +rather than a content hash. A project on a *different* version collides with nothing. A project pinning +the **same** version as the tool's own nightly has a library with exactly the name the Nix `rustc` is +looking for, so it wins the lookup — and being a non-Nix build, it then wants a system `libz.so.1` the +Nix loader cannot resolve. The failure therefore appears in whichever project happens to track the same +Rust version as the tool, which is the opposite of the intuition that a closely matched toolchain is +the safe case. + +The fix ships in the flake, whose wrapper puts the pinned toolchain's `lib` first. Upgrade the install +(`nix profile upgrade cargo-cgp`, or remove and re-add it). To confirm the diagnosis before upgrading, +run the probe with that directory in front — it should succeed where the bare command failed: + +```sh +NIX_RUSTC=/nix/store/…-rust-minimal-…/bin/rustc +LD_LIBRARY_PATH=$(dirname "$NIX_RUSTC")/../lib "$NIX_RUSTC" --print sysroot +``` + +A rustup-managed install does not hit this. + +## The preflight rejects the setup + +Before each check the front-end verifies the toolchain and the driver, read-only. Every failure names +`cargo cgp setup` as the fix, and the messages tell the cases apart. + +The pinned nightly is not installed: + +```text +cargo-cgp: toolchain `nightly-2026-07-16` is not available (exit status: 1) + +The pinned toolchain is not installed. Run `cargo cgp setup`. +``` + +The toolchain is there, but the driver cannot run under it — almost always a driver built against a +different nightly: + +```text +cargo-cgp: the cargo-cgp-driver could not run under toolchain `nightly-2026-07-16` +(it was likely built against a different nightly). Run `cargo cgp setup`. +``` + +The driver runs but the two are out of lockstep — a partial upgrade, or a stale binary earlier on +`PATH`: + +```text +the installed cargo-cgp-driver is version 0.1.0, but this cargo-cgp is 0.2.0 (the two are out of lockstep) + +Run `cargo cgp setup`. +``` + +Every one of these is resolved by `cargo cgp setup`, which reinstalls the pinned toolchain and rebuilds +the driver against it. If you are deliberately running an unprovisioned build, set `CARGO_CGP_NO_MANAGE` +to skip the preflight — but then keeping the toolchain matched is your responsibility, per +[the section above](#the-driver-cannot-load-the-compiler). + +## Provisioning fails + +`cargo cgp setup` manages toolchains through rustup, so on a machine without it the command stops +plainly rather than failing obscurely: + +```text +rustup was not found on PATH; cargo-cgp requires rustup to manage toolchains +``` + +Install through the [Nix flake](./installation.md#with-nix) instead, which provisions the toolchain at +build time and needs no rustup. + +## Still stuck? + +The root cause of most of these is a single thing: **a mismatch between the nightly the driver embeds +and the toolchain present when it runs.** Several different-looking errors trace back to it, so if you +are between sections, run `cargo-cgp-driver --version` and compare its `pinned-toolchain:` line against +`rustc --version` in the directory where the check fails. + +Failures that are not covered here are worth reporting on the +[issue tracker](https://github.com/contextgeneric/cargo-cgp/issues), with the output of +`cargo cgp check -v` and `cargo-cgp-driver --version`. + +--- + +*This page was written by an AI agent from the CGP knowledge base — see +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/example-code/README.md b/example-code/README.md index 06b24e8e..67dcf6d6 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -20,6 +20,7 @@ One file per page, at the matching path with the file name in `snake_case`: |---|---| | `docs/concepts/` | complete — sixteen files under `src/concepts/`, one per page that shows code | | `docs/reference/` | `macros/delegate_components.md` only — the section is being filled in lazily | +| `docs/cargo-cgp/` | complete — the two pages that show Rust, under `src/cargo_cgp/` | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/src/cargo_cgp/check.rs b/example-code/src/cargo_cgp/check.rs new file mode 100644 index 00000000..ebead929 --- /dev/null +++ b/example-code/src/cargo_cgp/check.rs @@ -0,0 +1,44 @@ +//! Code from `docs/cargo-cgp/check.md` — *Check*, and the excerpt of it on the section index. +//! +//! The page's whole program is the mistake: `RectangleArea` reads a `height` field through an +//! `#[implicit]` argument and `Rectangle` does not have one. It therefore cannot be a module, and is +//! carried as a `compile_fail` doctest. +//! +//! What the doctest guards is narrow but real: that the snippet the page calls broken is still broken. +//! It does **not** verify which diagnostic comes out — rustdoc does not enforce that — and it says +//! nothing at all about the `cargo cgp check` output the page quotes beside it. That output was +//! produced by running the tool, and re-running it is the only way to re-verify it. +//! +//! ```compile_fail +//! use cgp::prelude::*; +//! +//! #[cgp_component(AreaCalculator)] +//! pub trait CanCalculateArea { +//! fn area(&self) -> f64; +//! } +//! +//! #[cgp_impl(new RectangleArea)] +//! impl AreaCalculator { +//! fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { +//! width * height +//! } +//! } +//! +//! // The mistake: no `height` field, though the provider reads one. +//! #[derive(HasField)] +//! pub struct Rectangle { +//! pub width: f64, +//! } +//! +//! delegate_components! { +//! Rectangle { +//! AreaCalculatorComponent: RectangleArea, +//! } +//! } +//! +//! check_components! { +//! Rectangle { +//! AreaCalculatorComponent, +//! } +//! } +//! ``` diff --git a/example-code/src/cargo_cgp/expand.rs b/example-code/src/cargo_cgp/expand.rs new file mode 100644 index 00000000..60c35a54 --- /dev/null +++ b/example-code/src/cargo_cgp/expand.rs @@ -0,0 +1,52 @@ +//! Code from `docs/cargo-cgp/expand.md` — *Expand*. +//! +//! The same program as [`super::check`] with its missing `height` field restored, which is the state +//! the page expands. The listing the page shows is *generated* code, so this file can only confirm the +//! program it was generated from still compiles and wires up; the authority on the listing's text is +//! `cargo cgp expand --lib --item Rectangle`, which is how it was produced. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_wiring_resolves() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + assert_eq!(rectangle.area(), 12.0); + } +} diff --git a/example-code/src/cargo_cgp/mod.rs b/example-code/src/cargo_cgp/mod.rs new file mode 100644 index 00000000..fa78588b --- /dev/null +++ b/example-code/src/cargo_cgp/mod.rs @@ -0,0 +1,11 @@ +//! Code from the pages under `docs/cargo-cgp/`. +//! +//! Two of the five pages show Rust. `installation.md` and `troubleshooting.md` are shell commands and +//! quoted diagnostics, so they have no file here. +//! +//! Both pages that do show Rust show the *same* program, once broken and once fixed, because that is +//! the point being made: `check.md` runs the tool on the broken one, and `expand.md` expands the fixed +//! one. The broken version cannot be a module, so it is a `compile_fail` doctest. + +pub mod check; +pub mod expand; diff --git a/example-code/src/lib.rs b/example-code/src/lib.rs index e83fd207..ad406dbd 100644 --- a/example-code/src/lib.rs +++ b/example-code/src/lib.rs @@ -19,5 +19,6 @@ // here; a warning that means something — an unused import, an unreachable pattern — still fires. #![allow(dead_code, unused_variables)] +pub mod cargo_cgp; pub mod concepts; pub mod reference; From 6c9e6642ac055039f4f042adfbdcd98356462f40 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 20:40:19 +0200 Subject: [PATCH 026/516] Close the same reference gaps, and link the Concepts tier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The public counterpart of the knowledge-base pass: the eleven forms and rules the parsers accept that no page documented, applied to the twenty-seven written pages under `docs/reference/`. The getter pages gain the non-`self` typed-reference receiver and the optional `PhantomData` argument; both access-mode tables gain `MRef<'_, T>`; `#[cgp_component]` gains `#[prefix]`, the supertrait-to-context lowering, the default method body that travels to the provider trait — and so explains `UseDefault` — and a `Life<'a>` table for the params tuple. `#[cgp_impl]` gains the associated-type exemption and loses the half-wrong claim that a provider's own associated *type* is awkward to name. `#[cgp_provider]` gains the argument split, the four refused inputs, and two Gotchas. `check_components!` gains the `?Sized` reason and the two empty bracketed forms; `delegate_and_check_components!` gains the attribute merge on a list key and the two forms that quietly check nothing. Five attribute pages gain the formal grammar the template requires. The Concepts tier has landed, so the recorded convention that no reference page links it is retired: every page now closes with a short *The ideas behind it* list beneath *Related constructs*, and the two `cargo cgp check` links that pointed at GitHub point at the site's own tooling section. The index's name-lookup table gains ten rows and loses a misattribution — `#[check_params]` and `#[skip_check]` belong to `delegate_and_check_components!`. Every claim is checked against the parsers or a snapshot the compiler produced; the build passes with no broken links or anchors. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_011BfN1sjgaBAA2sEVqVNeig --- docs/reference/attributes/derive_delegate.md | 29 ++++ docs/reference/attributes/extend.md | 22 +++ docs/reference/attributes/extend_where.md | 24 +++ docs/reference/attributes/implicit.md | 26 +++- docs/reference/attributes/use_provider.md | 32 ++++ docs/reference/attributes/use_type.md | 5 + docs/reference/attributes/uses.md | 24 +++ docs/reference/errors.md | 2 +- docs/reference/index.md | 12 +- docs/reference/macros/async_trait.md | 7 + docs/reference/macros/blanket_trait.md | 14 +- docs/reference/macros/cgp_auto_dispatch.md | 7 + docs/reference/macros/cgp_auto_getter.md | 48 +++++- docs/reference/macros/cgp_component.md | 146 +++++++++++++++--- docs/reference/macros/cgp_computer.md | 5 + docs/reference/macros/cgp_fn.md | 21 ++- docs/reference/macros/cgp_getter.md | 14 +- docs/reference/macros/cgp_impl.md | 45 +++++- docs/reference/macros/cgp_namespace.md | 18 +++ docs/reference/macros/cgp_producer.md | 5 + docs/reference/macros/cgp_provider.md | 43 +++++- docs/reference/macros/cgp_type.md | 11 ++ docs/reference/macros/check_components.md | 26 +++- .../macros/delegate_and_check_components.md | 44 +++++- docs/reference/macros/delegate_components.md | 46 ++++-- docs/reference/macros/path.md | 5 + docs/reference/macros/product.md | 5 + docs/reference/macros/sum.md | 5 + docs/reference/macros/symbol.md | 4 + 29 files changed, 630 insertions(+), 65 deletions(-) diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index f397c094..ecb79151 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -90,6 +90,30 @@ needs. The attribute belongs on a [`#[cgp_component]`](../macros/cgp_component.md) trait and only makes sense for one that has generic parameters. +
+Formal grammar + +The attribute argument is a wrapper name and the parameters to key on, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +DeriveDelegateArgs -> Wrapper `<` KeyParams `>` + +Wrapper -> IDENTIFIER + +KeyParams -> IDENTIFIER + | `(` IDENTIFIER ( `,` IDENTIFIER )* `,`? `)` +``` + +Both parts are required. `Wrapper` is a bare identifier rather than a path, so a wrapper reached through a +module path has to be imported first. `KeyParams` are **identifiers**, not types: each must name a generic +parameter the trait declares, and a type expression such as `Vec` in that position does not parse. The +parenthesized form must list at least one parameter — an empty `()` is rejected with *expect non-empty +tuple list of identifiers in use_delegate_spec* — and a single parameter written bare is keyed the same way +a one-element tuple would be. The attribute may be repeated, once per dispatcher. + +
+ ## Examples A dispatching component, two implementations, and a context that routes each shape to its own: @@ -276,6 +300,11 @@ per-type entries have to be written with the full prefixed path instead. - [`DelegateComponent`](../traits/delegate_component.md) — the table trait the lookup reads. - [`cgp_namespace!`](../macros/cgp_namespace.md) — the full form of the mechanism `open` is a special case of. +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — the per-type routing this attribute is the legacy + mechanism for. + ## Source - Parsing and the generated impl: [`types/attributes/derive_delegate/attribute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/derive_delegate/attribute.rs) diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 13751d52..1dda4a04 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -196,6 +196,23 @@ Here the result is exactly what `pub trait CanGreet: HasName` would have produce reason given above: it presents the bound as an import rather than as inheritance, and it keeps the `use`/`pub use` pairing with `#[uses]` reading consistently across both macros. +
+Formal grammar + +The attribute argument is a comma-separated list of bounds, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +ExtendArgs -> TypeParamBound ( `,` TypeParamBound )* `,`? +``` + +This is the same production [`#[uses]`](uses.md) accepts — the Rust grammar's own bound, so a lifetime, a +`?Sized`, or an associated-type equality parses as readily as a plain trait name. The list may be empty, +and the attribute may be repeated, with every occurrence's entries collected together. What differs +between the two attributes is not the grammar but where the bounds land. + +
+ ## Gotchas **On a `#[cgp_impl]` the attribute is not recognized at all**, rather than being accepted and ignored. @@ -223,6 +240,11 @@ is the practical reason to default to `#[uses]`. - [`#[cgp_component]`](../macros/cgp_component.md) — where it is preferred over native `:` syntax. - [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — defines the getter capabilities most often extended. +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the distinction between a + requirement callers see and one they do not. + ## Source - Parsing: [`types/attributes/function.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/function.rs) diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 0a78d1bf..2e8d9dda 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -173,6 +173,25 @@ reading a long `where` clause in an expansion, since it tells you where each bou The context parameter is literally `__Context__` in the emitted code and appears as `Self` inside the implementation. +
+Formal grammar + +The attribute argument is a comma-separated list of `where` predicates, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +ExtendWhereArgs -> WherePredicate ( `,` WherePredicate )* `,`? +``` + +`WherePredicate` is the Rust grammar's own production — the thing that appears between the commas of a +`where` clause — which is what separates this attribute from [`#[uses]`](uses.md) and +[`#[extend]`](extend.md). Those take a *bound* and always attach it to `Self`; a predicate names its own +subject, so `#[extend_where(Self::Output: Clone)]` and `#[extend_where(for<'a> &'a T: IntoIterator)]` are +both expressible here and neither is expressible there. The list may be empty and the attribute may be +repeated. + +
+ ## Gotchas **A promoted predicate does not reach callers as a guarantee.** This is the mistake the attribute most @@ -211,6 +230,11 @@ has the effect this attribute exists to produce elsewhere. - [`#[cgp_fn]`](../macros/cgp_fn.md) — the only host, and the reason the attribute exists. - [`#[implicit]`](implicit.md) — contributes the bounds that always sort last. +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a `#[cgp_fn]`'s own `where` + clause stays off its trait by default. + ## Source - Parsing: [`types/attributes/function.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/function.rs) diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 248a24ad..9976e8bd 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -70,14 +70,22 @@ the stored field. This is the whole of the mapping: | `&mut [T]` | anything `AsMut<[T]>` | `.as_mut()` | | `Option<&mut T>` | `Option` | `.as_mut()` | | `Option<&mut str>` | `Option` | `.as_deref_mut()` | +| [`MRef<'a, T>`](../types/mref.md) | `T` | by reference, wrapped as `MRef::Ref(…)` | -Two of those rows are worth reading twice. `&str` is the case most often wanted and least obvious: the -field is a `String`, and the argument borrows from it, so a context never has to store a `&str`. And an +Three of those rows are worth reading twice. `&str` is the case most often wanted and least obvious: the +field is a `String`, and the argument borrows from it, so a context never has to store a `&str`. An owned parameter *clones* — cheap for an `f64`, less so for a large `String`, which is a reason to take -`&str` or `&T` wherever the body only needs to read. +`&str` or `&T` wherever the body only needs to read. And `MRef` is the owned-or-borrowed form: it reads a +plain `T` field, hands the body a value that may be either, and is the one reference-shaped row with no +mutable counterpart. Mutability follows the *argument's* type rather than the receiver's. An argument carrying a `&mut` reads -mutably; every other argument reads through a shared borrow, even on a `&mut self` method. +mutably; every other argument — an `MRef` included — reads through a shared borrow, even on a `&mut self` +method. + +The `MRef` row is matched by *shape* rather than by resolving the name: a single-segment `MRef` with one +lifetime argument and one type argument. Anything else spelled `MRef` falls into the owned row and is +cloned, which is the one place a small change to the type silently changes the read. The same rules govern the getter traits, so learning them once covers everywhere CGP reads a field. @@ -212,7 +220,10 @@ as the accessor: `&mut u64` emits `HasFieldMut` `get_field_mut`. Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the rewrite is the same, with the bounds joining -that provider's `where` clause instead. +that provider's `where` clause instead — and with one addition that only a multi-method block can show: +the bounds are collected across *every* method and de-duplicated, so two methods each taking +`#[implicit] name: &str` add one `HasField` bound rather than two. The +`let` bindings are still emitted per method, since each body needs its own. ## Gotchas @@ -259,6 +270,11 @@ error: a `&mut` implicit argument must be the only implicit argument, since its - [`#[use_type]`](use_type.md) — imports a type rather than a value; the third of the three. - [`Symbol!`](../macros/symbol.md) — the type-level field name the bounds are keyed on. +The ideas behind it: + +- [Implicit arguments](/docs/concepts/implicit-arguments) — the idea in full, and why it is the + default way to reach a context's field. + ## Source - Parsing: [`functions/implicits/parse.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/implicits/parse.rs) diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index a3cc2582..50a2c261 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -229,6 +229,33 @@ where Note that the body is untouched in both. The call stays `InnerCalculator::area(__context__)`, passing the context as the first argument, because that is the shape the provider trait's method has. +
+Formal grammar + +The attribute argument is one provider and the provider traits it must satisfy, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +UseProviderArgs -> ProviderType `:` ProviderBound ( `+` ProviderBound )* + +ProviderType -> Type +ProviderBound -> TypePath GenericArgs? +``` + +Both parts are required. `ProviderType` names the generic parameter the inner provider occupies, and each +`ProviderBound` is the provider trait to require of it — written *without* its leading context argument, +which the attribute inserts. + +Two restrictions follow from those productions and account for every parse failure this attribute +produces. **`ProviderBound` is a path with plain generic arguments**, not a full `TypeParamBound`, so a +turbofish or an associated-type binding in that position does not parse; a bound of that shape belongs in +the block's own `where` clause. And **the argument holds exactly one provider**, because the `+`-separated +bound list runs to the end of the attribute — a comma after the first pair lands where a `+` was expected. +That makes this attribute the one exception to the comma-separated convention its siblings follow: bind +several inner providers by stacking one attribute each. See [Gotchas](#gotchas). + +
+ ## Gotchas **A comma-separated list of pairs is not accepted.** Writing two providers in one attribute is a parse @@ -270,6 +297,11 @@ intent is to use the inner implementation, spell out the associated-function cal - [`check_components!`](../macros/check_components.md) — its `#[check_providers(...)]` form checks each layer of a nested stack separately, which is how a broken layer is localized. +The ideas behind it: + +- [Higher-order providers](/docs/concepts/higher-order-providers) — the pattern this attribute + exists to make writable. + ## Source - Parsing and bound completion: [`types/attributes/use_provider/attribute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/use_provider/attribute.rs) diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index ff176ffa..998ac6a4 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -362,6 +362,11 @@ Pin the type on the provider with [`#[cgp_impl]`](../macros/cgp_impl.md) instead - [`#[cgp_fn]`](../macros/cgp_fn.md), [`#[cgp_impl]`](../macros/cgp_impl.md), and [`#[cgp_component]`](../macros/cgp_component.md) — the three hosts. +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — the idea behind the types this attribute + imports. + ## Source - Parsing: [`types/attributes/use_type/attribute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/use_type/attribute.rs) diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 41e09431..0883237e 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -190,6 +190,25 @@ appended to that provider's `where` clause — which is also where they are pick [`IsProviderFor`](../traits/is_provider_for.md) impl, so an unmet import is reported by name rather than as a bare missing implementation. +
+Formal grammar + +The attribute argument is a comma-separated list of bounds, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +UsesArgs -> TypeParamBound ( `,` TypeParamBound )* `,`? +``` + +`TypeParamBound` is the Rust grammar's own bound production, which is wider than the plain `Trait` +this attribute is normally written with: a lifetime, a `?Sized`, and an associated-type equality such as +`HasErrorType` all parse. The list may be empty, and the attribute may be repeated — +entries from every occurrence are collected into one `Self:` predicate. The commas separate *bounds*, so +`#[uses(A, B)]` and `#[uses(A)] #[uses(B)]` are the same thing; the single-attribute form is the one to +write. + +
+ ## Gotchas **Naming a provider trait instead of a consumer trait does not work**, and this is the most likely way to @@ -220,6 +239,11 @@ and it will supply the missing argument. - [`#[implicit]`](implicit.md) — imports a value from a field rather than a capability. - [`#[cgp_component]`](../macros/cgp_component.md) — defines the capabilities most often imported. +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — what an imported capability + becomes, and why callers never see it. + ## Source - Parsing: [`types/attributes/uses.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/uses.rs) diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 6e1f4bd3..d48111e0 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -11,6 +11,6 @@ The errors CGP produces after macro expansion, grouped by what went wrong: a dep ### Not written yet -This page is still being written. In the meantime, run [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) in place of `cargo check`: it un-hides the root cause the default trait solver suppresses and leads with it, for the error classes it recognizes. +This page is still being written. In the meantime, run [`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`: it un-hides the root cause the default trait solver suppresses and leads with it, for the error classes it recognizes. ::: diff --git a/docs/reference/index.md b/docs/reference/index.md index fd976be2..db23c753 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -206,10 +206,20 @@ these names, this is where it lives. | `MatchWithHandlers`, `ExtractFieldAndHandle` | [Dispatch combinators](./providers/dispatch_combinators.md) | | `PipeMonadic`, `BindOk`, `BindErr` | [Monad providers](./providers/monad_providers.md) | | `RaiseFrom`, `ReturnError`, `DebugError`, `DisplayError` | [Error providers](./providers/error_providers.md) | +| `UseDelegatedType`, `WithDelegatedType` | [`UseDelegatedType`](./providers/use_delegated_type.md) and [`WithProvider`](./providers/with_provider.md) | +| `UseInputDelegate` | [Handler combinators](./providers/handler_combinators.md) | +| `RaiseInfallible`, `DiscardDetail`, `PanicOnError` | [Error providers](./providers/error_providers.md) | +| `ComputerRef`, `AsyncComputer`, `TryComputerRef`, `HandlerRef` | the page for the component they vary — [`Computer`](./components/computer.md), [`TryComputer`](./components/try_computer.md), [`Handler`](./components/handler.md) | +| `BuildField`, `UpdateField`, `FinalizeBuild` | [`HasBuilder`](./traits/has_builder.md) | +| `HasExtractor`, `FinalizeExtract` | [`ExtractField`](./traits/extract_field.md) | +| `IsPresent`, `IsNothing` | [`MapType`](./traits/map_type.md) | +| `MonadicTrans`, `MonadicBind`, `LiftValue`, `ContainsValue` | [Monad traits](./traits/monad.md) | +| `product!` (the value-level form) | [`Product!`](./macros/product.md) | | `#[impl_generics(...)]` | [`#[cgp_fn]`](./macros/cgp_fn.md) | | `#[prefix(...)]` | [`cgp_namespace!`](./macros/cgp_namespace.md) | | `#[default_impl(...)]` | [`DefaultNamespace`](./traits/default_namespace.md) | -| `#[check_providers(...)]`, `#[check_params(...)]` | [`check_components!`](./macros/check_components.md) | +| `#[check_trait(...)]`, `#[check_providers(...)]` | [`check_components!`](./macros/check_components.md) | +| `#[check_params(...)]`, `#[skip_check]` | [`delegate_and_check_components!`](./macros/delegate_and_check_components.md) | --- diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 0e101121..d01c9355 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -263,6 +263,13 @@ provider needed it; it did not, and removing it changes nothing. - [Handler combinators](../providers/handler_combinators.md) — the promotions that lift a synchronous provider into an async one. +The ideas behind it: + +- [Recovering `Send` bounds](/docs/concepts/send-bounds) — why the future this rewrite produces + carries no `Send` bound, and how to get one back. +- [Handlers](/docs/concepts/handlers) — the component family whose async members are declared this + way. + ## Source - Entry point: [`cgp-async-macro/src/lib.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-async-macro/src/lib.rs) diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index cec256ad..13533fa2 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -283,7 +283,12 @@ Add `use cgp::core::macros::blanket_trait;`. This is the one macro on this page' **A method without a default body is an error.** The macro forwards defaults into the impl, so a bare declaration leaves it nothing to emit. This is the opposite of an ordinary trait, where a bodiless method is -the normal case. +the normal case. The same holds for a constant, and the two say so distinctly — *function item require +implementation block* and *const item require implementation expression*. + +**Only methods, associated types, and associated constants are accepted.** A trait item of any other kind — +a macro invocation in the body, say — is refused with *unsupported trait item*, because the macro has to +mirror each item into the impl and knows only those three shapes. **The trait keeps its default bodies.** The expansion does not strip them, so each body appears both on the trait and in the impl. Harmless, but worth knowing when reading an expansion and wondering whether the macro @@ -303,6 +308,13 @@ Where a type needs different behaviour, the trait wants to be a [component](./cg - [`#[uses]`](../attributes/uses.md) — how a CGP provider declares the trait dependencies a supertrait declares here. +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the idea this macro automates — + requirements that live on the impl rather than the interface. +- [How much CGP to use](/docs/concepts/modularity-hierarchy) — where a blanket trait sits between a + plain trait and a full component. + ## Source - Entry point: [`blanket_trait.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/blanket_trait.rs) diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index bb3811c2..84320137 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -273,6 +273,13 @@ hand for some other type without colliding with it. - [`#[cgp_component]`](./cgp_component.md) — the better starting point when contexts should configure the operation. +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data input to a handler per + variant. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum representation the dispatch + walks. + ## Source - Entry point: [`entrypoints/cgp_auto_dispatch.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_auto_dispatch.rs) diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index d51be312..a82c6740 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -72,6 +72,7 @@ natural. The field's type is inferred from what you return: | `&[T]` | anything `AsRef<[T]>` | `.as_ref()` | | `Option<&T>` | `Option` | `.as_ref()` | | `Option<&str>` | `Option` | `.as_deref()` | +| [`MRef<'_, T>`](../types/mref.md) | `T` | by reference, wrapped as `MRef::Ref(…)` | | An owned type — `f64`, `String`, a tuple, an array | the same type | by reference, then `.clone()` | A `&mut self` receiver reads mutably, and each reference form has a mutable mirror: `&mut T`, `&mut [T]` @@ -80,7 +81,45 @@ through `AsMut<[T]>`, `Option<&mut T>` via `.as_mut()`, and `Option<&mut str>` v The `&str` row is the one most often wanted and least obvious: the context stores a `String` and the getter hands out a borrow of it, so no context ever has to hold a `&str`. **These are the same rules an [`#[implicit]`](../attributes/implicit.md) argument follows**, so learning them once covers everywhere CGP -reads a field. +reads a field — with one difference worth holding onto. A getter takes its mutability from the +**receiver**, while an implicit argument takes it from the *argument's type*. So +`fn name(&mut self) -> &mut String` reads mutably because of the `&mut self`, whereas +`#[implicit] name: &String` on a `&mut self` method still reads through a shared borrow. + +### Reading a field of another type + +The first argument need not be `self`. A typed reference stands in for it, which is how a getter reaches +a field on something the context only *names*: + +```rust +#[cgp_auto_getter] +pub trait HasFooBar: HasFooType + HasBarType { + fn foo_bar(foo: &Self::Foo) -> &Self::Bar; +} +``` + +The generated bound now falls on `Self::Foo` rather than on the context, and the method is called as an +associated function — `App::foo_bar(&foo)`. `Self` inside the argument and return types is rewritten to +the context, and `&` versus `&mut` decides the access mode exactly as a receiver would. + +**This is the one getter shape an [`#[implicit]`](../attributes/implicit.md) argument cannot reach**, +because there is no `self` field to read — which makes it the clearest case for declaring a getter at +all. + +### An optional `PhantomData` argument + +A getter method may take one further argument, and it must be a `PhantomData`: + +```rust +#[cgp_auto_getter] +pub trait HasFoo { + fn foo(&self, _tag: PhantomData) -> &Foo; +} +``` + +It is forwarded to the generated method untouched and plays no part in the field lookup; it is there so a +getter can carry a type-level argument in its signature. Anything else in that position is rejected with +*only PhantomData is allowed as second argument*, and a third argument is rejected outright. ### A type inferred from the field @@ -313,6 +352,13 @@ found rather than the trait as not imported. - [`#[cgp_type]`](./cgp_type.md) — for an abstract type standing on its own rather than inferred from a field. +The ideas behind it: + +- [Implicit arguments](/docs/concepts/implicit-arguments) — the lighter way to read a field, and why + a getter is the exception. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why the field requirement stays + off the trait interface. + ## Source - Entry point: [`cgp_auto_getter.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_auto_getter.rs) diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 1ea47f3f..c572b929 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -78,13 +78,22 @@ setting it alone. The `context` default is deliberately unusual so that it cannot collide with a type parameter of your own. -### Supertraits, and importing an abstract type +### Companion attributes + +Four attributes may be written above the trait, beside `#[cgp_component]`, and each changes what the +macro generates. Any of them may be repeated, and the first three also accept a comma-separated list +inside one attribute. + +| Attribute | What it adds | +|---|---| +| [`#[use_type(Trait.Type)]`](../attributes/use_type.md) | Imports an abstract type: adds the supertrait *and* rewrites the bare name in your signatures | +| [`#[extend(Trait)]`](../attributes/extend.md) | Adds a supertrait with no type to import | +| [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) | Generates dispatch impls for a component generic over a parameter | +| [`#[prefix(@path in Namespace)]`](./cgp_namespace.md) | Registers the component into a namespace under a type-level path | When a component depends on a type another component supplies — most often the error type from -[`HasErrorType`](../components/has_error_type.md) — import it with -[`#[use_type]`](../attributes/use_type.md) rather than writing the supertrait and the qualified path by -hand. The attribute adds the supertrait *and* rewrites a bare `Error` in your signatures to its fully -qualified form: +[`HasErrorType`](../components/has_error_type.md) — import it with `#[use_type]` rather than writing +the supertrait and the qualified path by hand: ```rust #[cgp_component(Loader)] @@ -94,15 +103,27 @@ pub trait CanLoad { } ``` -For a supertrait with no associated type to import, use [`#[extend(...)]`](../attributes/extend.md) in -preference to native `: Supertrait` syntax — `#[extend(HasName)]` reads as importing a capability, -where `pub trait CanGreet: HasName` reads as inheritance, which is not what a CGP supertrait is. An +One form of `#[use_type]` is refused here. The equality form +`#[use_type(HasScalarType.{Scalar = f64})]`, which pins an imported type to a concrete one, belongs to +a provider that has decided the type rather than to the definition every provider has to satisfy, so +the macro rejects it with *Type equality constraints cannot be used in component trait definition*. +Every other form of the attribute works on a component exactly as it does elsewhere. + +For a supertrait with no associated type to import, use `#[extend(...)]` in preference to native +`: Supertrait` syntax — `#[extend(HasName)]` reads as importing a capability, where +`pub trait CanGreet: HasName` reads as inheritance, which is not what a CGP supertrait is. An associated type the trait declares *itself* is not imported and stays written as `Self::Output`. -One further companion attribute exists: [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) -generates dispatch impls for a component generic over a parameter. It is superseded by the `open` -statement of [`delegate_components!`](./delegate_components.md) and is mostly something you read in -existing code rather than write. +`#[derive_delegate(...)]` is superseded by the `open` statement of +[`delegate_components!`](./delegate_components.md) and is mostly something you read in existing code +rather than write. + +Three attributes that look like they belong here do not, and the error is confusing enough to be worth +naming: `#[uses(...)]`, `#[extend_where(...)]`, and `#[use_provider(...)]` are read by +[`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_fn]`](./cgp_fn.md) but not by `#[cgp_component]`. None of +them is an attribute in its own right, so writing one here leaves a name nothing can resolve — see +[Gotchas](#gotchas). The equivalent of `#[uses]` on a component is a supertrait, written with +`#[extend]`. ## Examples @@ -232,6 +253,40 @@ pub trait AreaCalculator: } ``` +`IsProviderFor` *replaces* the supertrait list rather than joining it. Any supertrait the consumer +trait had — written natively, or added by `#[extend]` or `#[use_type]` — becomes a `where` predicate +on the context instead, which follows from the `Self`-to-`Context` move: a supertrait constrains the +type the capability is about, and on the provider side that type is the context parameter. So +`#[extend(HasName)]` on a `CanGreet` component produces: + +```rust +pub trait Greeter: IsProviderFor +where + Context: HasName, +{ + fn greet(context: &Context); +} +``` + +That predicate is added to every emitted item that mentions the context — the two blanket impls below and +the `UseContext` and `RedirectLookup` impls further down each gain their own `Context: HasName` — since +none of them can apply where the supertrait does not hold. + +**A method may carry a default body, and the body moves to the provider trait.** This is the other thing +the `Self`-to-`Context` move reaches, and it is worth knowing because it is what lets a provider inherit a +default at all. Given `fn greet(&self) -> String { format!("Hello, {}!", self.name()) }` on the consumer +trait, the provider trait gets `fn greet(context: &Context) -> String { format!("Hello, {}!", context.name()) }` +— rewritten, and still a default. The consumer trait keeps its copy too, so the body appears twice in an +expansion. + +That is what makes an **empty provider impl** meaningful, and it is how +[`UseDefault`](../providers/use_default.md) works: + +```rust +#[cgp_impl(UseDefault)] +impl Greeter for Context {} +``` + Third, the **consumer blanket impl**, the bridge that lets callers write `context.area()`: any context implementing the provider trait *for itself* gets the consumer trait. @@ -272,20 +327,47 @@ Fifth, the **component marker**, the key wiring uses: pub struct AreaCalculatorComponent; ``` -Beyond those five, the macro emits the standard provider impls that let the component participate in -CGP's usual patterns: a [`UseContext`](../providers/use_context.md) impl, so the provider trait can be -satisfied by routing back through the context's own implementation; a -[`RedirectLookup`](../providers/redirect_lookup.md) impl, which is what the `open` statement and -[namespaces](./cgp_namespace.md) resolve through; and a -[`UseDelegate`](../providers/use_delegate.md) impl for each -[`#[derive_delegate(...)]`](../attributes/derive_delegate.md) attribute present. +Those five are emitted in the order consumer trait, consumer impl, provider trait, provider impl, +marker — the listings above pair each trait with the impl that routes to it, which reads better than +the order they actually appear in. + +Beyond the five, the macro emits the provider impls that let the component participate in CGP's usual +patterns. Two are always emitted, and two are one per attribute: + +- A [`UseContext`](../providers/use_context.md) impl, so the provider trait can be satisfied by + routing back through the context's own implementation. Its only bound is + `Context: CanCalculateArea`, and each method forwards to the consumer method. +- A [`RedirectLookup`](../providers/redirect_lookup.md) impl, which is what the `open` statement and + [namespaces](./cgp_namespace.md) resolve through. +- One [`UseDelegate`](../providers/use_delegate.md) impl per + [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) attribute. +- One namespace impl per [`#[prefix(@path in Namespace)]`](./cgp_namespace.md) attribute, binding the + component's key inside that namespace to a redirect down the given path. + +The `RedirectLookup` impl is where a component's own type parameters earn a place in a path, and it is +what makes `@AreaCalculatorComponent.Rectangle` resolve. For a component with type parameters the +impl does not look the incoming path up directly: it appends the parameters to it first, so a lookup +that arrives at `AreaCalculatorComponent` carrying no path ends up looking for `Rectangle`. Only +*type* parameters take part — a lifetime or a const parameter cannot key a path and is left out. Two details of the real output differ from the listings above, and both trip people up when reading an error. The generated parameters carry **reserved names** — the context is literally `__Context__` unless you override it, and the provider parameter is `__Provider__`; the readable `Context` and -`Provider` here are for legibility only. And a component with its own type parameters, such as -`CanCalculateArea`, appends them *after* the context in the provider trait and groups them into -the `IsProviderFor` parameter tuple: `IsProviderFor`. +`Provider` here are for legibility only. And a component with parameters of its own appends them +*after* the context in the provider trait — except lifetimes, which Rust requires to lead — and groups +them into the `IsProviderFor` parameter tuple. That tuple holds types, so a lifetime is lifted into +[`Life<'a>`](../types/life.md): + +| Component | Provider trait | `IsProviderFor` params | +|---|---|---| +| `CanCalculateArea` | `AreaCalculator<__Context__>` | `()` | +| `CanCalculateArea` | `AreaCalculator<__Context__, Shape>` | `(Shape)` | +| `CanEncode` | `Encoder<__Context__, Value, Format>` | `(Value, Format)` | +| `HasReference<'a, T>` | `ReferenceGetter<'a, __Context__, T>` | `(Life<'a>, T)` | + +Bounds and defaults are dropped from the tuple, which names the parameters positionally and nothing +more. A const parameter has no place in it at all, which is why the macro rejects one — see +[Gotchas](#gotchas).
Formal grammar @@ -333,6 +415,18 @@ parameter, and a provider supplies it in the ordinary way. Naming your own assoc *inside* a [`#[cgp_impl]`](./cgp_impl.md) body has a wrinkle of its own, covered in that page's Gotchas. +**The attribute must be applied to a trait.** A struct, an enum, or a free function is refused at +parse time with an error naming the trait the macro expected, rather than being lowered into code that +fails to compile later. + +**A misplaced companion attribute is reported by the compiler, not by the macro — and reported several +times.** An attribute `#[cgp_component]` does not recognize rides through onto *every* item the macro +generates: the consumer trait, the provider trait, and the impls built from each. For `#[allow(...)]` or +a doc comment that is exactly what you want. For `#[uses(HasName)]` written above a component trait it +means one *cannot find attribute* resolution error per generated item, none of which mentions +`#[cgp_component]`. Read the repetition as the signal: it is the same error a typo in an attribute name +gives, so the fix is to move the attribute rather than to add an import. + ## Related constructs - [`#[cgp_impl]`](./cgp_impl.md) — the idiomatic way to write a provider for a component. @@ -345,6 +439,14 @@ Gotchas. - [`#[use_type]`](../attributes/use_type.md), [`#[extend]`](../attributes/extend.md), and [`#[derive_delegate]`](../attributes/derive_delegate.md) — attributes that change what it generates. +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the trait split this + macro creates, developed at length. +- [Bypassing coherence](/docs/concepts/coherence) — why the split exists at all. +- [How much CGP to use](/docs/concepts/modularity-hierarchy) — when a component is the right rung, + and when it is more than the problem needs. + ## Source - Entry point: [`cgp_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_component.rs) diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index b62e5362..4ede48a5 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -293,6 +293,11 @@ short-circuits. - [`#[cgp_new_provider]`](./cgp_provider.md) — what the generated impl is emitted through. - [`#[cgp_auto_dispatch]`](./cgp_auto_dispatch.md) — generates per-variant computers from a trait. +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family this provider joins, across its sync, + fallible, and input-free axes. + ## Source - Entry point: [`entrypoints/cgp_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_computer.rs) diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index a87f4c70..f02db2ed 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -289,8 +289,18 @@ where The companion attributes layer into these same two items. `#[uses(Trait)]` adds a `Self: Trait` predicate to the impl; `#[extend(Trait)]` adds it to the impl *and* to the trait's supertraits; `#[extend_where(P)]` adds `P` to both `where` clauses; `#[impl_generics(T: Bound)]` inserts `T: Bound` -into the impl's generic list alone; and `#[use_type(Trait.Type)]` adds the supertrait and rewrites -every bare mention of the type into its fully qualified form. +into the impl's generic list alone — its argument is a comma-separated list of ordinary generic +parameters, so a lifetime or a const parameter is accepted there too; and +`#[use_type(Trait.Type)]` adds the supertrait and rewrites every bare mention of the type into its +fully qualified form. The implicit-argument bounds are appended +last, after whatever the attributes contributed. + +Two smaller placements are worth knowing because neither is visible in the source you wrote. **The +function's visibility becomes the trait's**, and the method inside the impl is left inherited — so +`pub fn rectangle_area` yields `pub trait RectangleArea`, and a private `fn` yields a private trait +usable only in its own module. And **an attribute the macro does not recognize is copied onto both +items**, which is what lets `#[allow(...)]`, `#[doc]`, or a doc comment ride through and apply to the +trait and the impl alike.
Formal grammar @@ -354,6 +364,13 @@ parameter. - [`#[derive(HasField)]`](../derives/derive_has_field.md) — what a context derives to satisfy the bounds. - [`#[async_trait]`](./async_trait.md) — how an `async fn` capability is declared. +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the `where`-clause injection + this macro is built on. +- [How much CGP to use](/docs/concepts/modularity-hierarchy) — the ladder this sits at the bottom + of. + ## Source - Entry point: [`cgp_fn.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_fn.rs) diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 06b242e0..d4f7e89d 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -37,9 +37,12 @@ want neither. The [When to reach for it](#when-to-reach-for-it-and-when-not) sec ## Using it Apply the attribute to a getter trait, exactly as with [`#[cgp_auto_getter]`](./cgp_auto_getter.md). The -same method forms are accepted — `&self` and `&mut self` receivers, and the `&str`, `&[T]`, `Option<&T>`, -`Option<&str>`, owned, and associated-type return shorthands, with their -[access rules](./cgp_auto_getter.md#how-the-return-type-decides-the-read) unchanged: +same method forms are accepted — every receiver shape, including a +[typed reference to another type](./cgp_auto_getter.md#reading-a-field-of-another-type) in place of +`self` and an [optional `PhantomData` argument](./cgp_auto_getter.md#an-optional-phantomdata-argument); +and the `&str`, `&[T]`, `Option<&T>`, `Option<&str>`, `MRef<'_, T>`, owned, and associated-type return +shorthands, with their [access rules](./cgp_auto_getter.md#how-the-return-type-decides-the-read) +unchanged. The two macros share one parser, so a method the one accepts the other does too: ```rust #[cgp_getter] @@ -315,6 +318,11 @@ the tag is what tells you which field the mismatch is about. - [`WithProvider`](../providers/with_provider.md) — the adapter for a value that does not come from a field. - [`#[cgp_type]`](./cgp_type.md) — the same idea for a type rather than a value. +The ideas behind it: + +- [Implicit arguments](/docs/concepts/implicit-arguments) — the default way to read a field, and why + this is the advanced fallback. + ## Source - Entry point: [`cgp_getter.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_getter.rs) diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 56c37843..4ded4256 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -109,7 +109,19 @@ they are how an idiomatic provider states what it needs. - [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound in a higher-order provider. - [`#[default_impl(...)]`](../traits/default_namespace.md) registers the provider as a namespace's - per-type default. + per-type default, for use with [`cgp_namespace!`](./cgp_namespace.md). + +Each may be repeated. All except `#[use_provider]` also take a comma-separated list inside one +attribute, which is the form to prefer — `#[uses(HasName, CanRaiseError)]` reads as one +dependency list. `#[use_provider]` is the exception because its own argument already ends in a bound +list, so a second pair after a comma has nowhere to go; write one attribute per inner provider. + +Three attributes that appear on other CGP macros are not read here. `#[extend]`, `#[extend_where]`, +and `#[impl_generics]` all act on a *generated trait definition*, which a provider impl does not have, +so they belong to [`#[cgp_fn]`](./cgp_fn.md) and — for `#[extend]` — +[`#[cgp_component]`](./cgp_component.md). Writing one here leaves a name nothing resolves; see +[Gotchas](#gotchas). An impl-side bound that really is impl-side goes in the block's own `where` +clause, which passes through untouched. ### Implementing the consumer trait directly @@ -266,6 +278,13 @@ arguments are the component name, the context, and a tuple of any remaining prov so a provider for `ComputerRef` gets `IsProviderFor`. +**An associated type the block declares is exempt.** `Self::Output` in a provider that supplies +`type Output` is left alone, because the macro gathers the block's own associated-type names first and +skips any `Self::` path starting with one. That is what it has to do: in the emitted impl `Self` is the +provider struct, which is the type that declares `Output`, so the path resolves as written. Every +other `Self` in the block is still rewritten — including one naming an abstract type the *context* +supplies. Associated consts are not covered by the exemption; see [Gotchas](#gotchas). + **The rewrite is scoped to the block's own method bodies.** An item nested *inside* a body — a local `struct` with its own impl, a helper `fn`, an inline `trait` — introduces a fresh `self`/`Self` that belongs to that item, exactly as in ordinary Rust, and the macro leaves it alone. Closures, which @@ -294,11 +313,10 @@ defaulting to the provider trait's name plus `Component`. Both are Rust `Type` p ## Gotchas -**A provider's own associated const or type is awkward to name inside its body**, and this follows -directly from the rewrite. A component may declare associated items alongside its methods, and a -provider supplies them in the `#[cgp_impl]` block as usual — but `Self::LIMIT` in a method body does -*not* resolve to the const the block just defined, because `Self` has been rewritten to the context. -The error reads: +**A provider's own associated const is awkward to name inside its body**, and this follows directly +from the rewrite. The exemption described above covers associated *types* only, so a provider that +declares `const LIMIT: u64 = 100;` cannot then write `Self::LIMIT` in a method body: that `Self` is +rewritten to the context, which has no such const. The error reads: ```text error[E0599]: no associated function or constant named `LIMIT` found for type parameter `__Context__` in the current scope @@ -314,7 +332,13 @@ The consumer side is unaffected — a wired context reads the same const as ` Path `in` NamespacePath + +NamespacePath -> TypePath GenericArgs? +``` + +`Path` is [`Path!`](./path.md)'s own `@`-prefixed dotted production, so its segments take no generics and +neither grouping form is accepted — one attribute registers under exactly one prefix, and the attribute +is repeated to register into several namespaces. `NamespacePath` may itself be parameterized. +
## Gotchas @@ -412,6 +425,11 @@ the context. - [`DelegateComponent`](../traits/delegate_component.md) — the per-key table a redirect finally walks. - [`check_components!`](./check_components.md) — the only thing that catches a route bound to nothing. +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — the idea in full, including why presets need no separate + construct. + ## Source - Entry point: [`cgp_namespace.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_namespace.rs) diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index ac38af40..328b6287 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -267,6 +267,11 @@ import. - [`#[cgp_new_provider]`](./cgp_provider.md) — what the generated impl is emitted through. - [`HasErrorType`](../components/has_error_type.md) — what the fallible forms require of a context. +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family, and where the input-free member + fits. + ## Source - Entry point: [`entrypoints/cgp_producer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_producer.rs) diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 1bd3e517..31327494 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -255,9 +255,16 @@ does not apply. Its three trait arguments are assembled from the provider trait's own. The first is the **component** (`ComputerRefComponent`, the default derived from the trait name, or whatever the attribute argument -said). The second is the **context**, taken from the provider trait's leading argument. The third is a -**tuple of every remaining parameter** — `(Code, Input)` here, and the empty `()` for a provider trait -that takes nothing but a context. +said). The second is the **context**. The third is a **tuple of everything left over** — `(Code, Input)` +here, and the empty `()` for a provider trait that takes nothing but a context. + +Two rules decide that split, and they only become visible on a provider trait that carries a +[lifetime](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html). The context is the first +*type* argument rather than the first argument, because Rust puts lifetime arguments first and a +lifetime cannot be a context. And a lifetime is lifted into [`Life<'a>`](../types/life.md) to occupy +its slot in the tuple, which holds types. A provider for `ReferenceGetter<'a, Context, T>` therefore +derives `IsProviderFor, T)>`, keeping the order the +arguments were written in. **One bound is rewritten rather than copied**, and it is the mechanism that makes a nested provider stack diagnosable. A bound naming *this component's provider trait* — the inner-provider bound of a @@ -290,6 +297,16 @@ of any other kind — an ordinary `Context: Clone`, a consumer-trait bound such `#[cgp_new_provider]` emits the same two items plus the struct, whose shape follows the `Self` type as described [above](#the-struct-cgp_new_provider-declares). +### Input the macros refuse + +Four shapes are rejected at expansion rather than lowered into code that fails later, and both macros +reject the same four. An **inherent impl**, with no trait, has no provider trait to read the component +and context from. A **provider trait with no type argument** leaves nothing to be the context. A +**const argument** in the provider trait's argument list has nowhere to live in the type-only params +tuple — this is about the *trait's* arguments, not about a const generic on the provider struct, which +passes through untouched. And an item that is not an `impl` is refused outright. Each message names +what was missing. +
Formal grammar @@ -318,6 +335,19 @@ one macro to the other and forgetting to delete the declaration: error[E0428]: the name `RectangleArea` is defined multiple times ``` +**`new` is not part of this attribute's grammar.** `#[cgp_provider(new RectangleArea)]` does not +declare the struct — it fails to parse, because the argument holds a component type and nothing else. +Which macro you invoke is what decides whether the struct is declared, so use +`#[cgp_new_provider]`. The `new` keyword you may have seen belongs to +[`#[cgp_impl]`](./cgp_impl.md#using-it). + +**A higher-order provider over a lifetime-carrying component loses the inner marker bound.** The +rewrite above finds the context by reading the inner bound's first argument, and on a component with a +lifetime that argument is the lifetime — so no counterpart is built and the bound is copied as-is. The +stack compiles and runs correctly; what is lost is the propagation, so a dependency unmet inside the +inner provider no longer surfaces at the outer one, and `#[check_providers(...)]` cannot say which +layer of such a stack is at fault. Components without lifetime parameters are unaffected. + **The component argument is not checked against the trait.** Passing a component that does not belong to the provider trait you are implementing produces a marker impl for the wrong key, so the provider silently fails to satisfy the wiring that names it — the error appears at the wiring site, saying the @@ -358,6 +388,13 @@ the consumer side is unaffected: a wired context reads `::L - [`UseContext`](../providers/use_context.md) — the usual default for a hand-written provider struct's inner parameter. +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the shape these two + macros write out longhand. +- [Higher-order providers](/docs/concepts/higher-order-providers) — the stacks whose inner bound the + marker derivation augments. + ## Source - Entry points: [`cgp_provider.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_provider.rs) diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 674b51f0..14db1b09 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -244,6 +244,12 @@ per component. Each generated provider impl is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl carrying the same bounds, as everywhere else. +A bound that names the type it constrains is rewritten rather than refused. Declaring +`type Scalar: Mul + Clone;` leaves the bound as written on the two traits, where +`Self::Scalar` still means what it says — but the copy landing on the `UseType` and `WithProvider` impls +becomes `Scalar: Mul + Clone`, with every `Self::Scalar` replaced by the free parameter. +Copied unchanged it would have named an associated type of the wrong `Self`. +
Formal grammar @@ -320,6 +326,11 @@ headline, so read downward. **Without a check the mistake is silent**, which is - [`#[cgp_getter]`](./cgp_getter.md) — the value-level counterpart, using `UseField` where this uses `UseType`. +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — why a context choosing its own type propagates + nowhere, unlike a parameter. + ## Source - Entry point: [`cgp_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_type.rs) diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index ff5719c8..2e87a0a8 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -256,6 +256,11 @@ delegates the component and that its delegate satisfies [`IsProviderFor`](../tra unmet one is reported specifically rather than as a bare missing implementation. The generic parameters are literally `__Component__` and `__Params__` in the emitted code. +`__Params__` carries a `?Sized` bound, and that is load-bearing rather than defensive: a component's +parameter may be an unsized type, so a table checking a component declared over `str` — +`ReferenceGetterComponent: (Life<'a>, str)` — would be rejected before the assertion was even evaluated +without it. + Generic parameters land in the `__Params__` slot — one directly, several as a tuple: ```rust @@ -305,20 +310,28 @@ CheckEntries -> ( CheckEntry ( `,` CheckEntry )* `,`? )? CheckEntry -> CheckKey ( `:` CheckValue )? CheckKey -> Type - | `[` Type ( `,` Type )* `,`? `]` + | `[` ( Type ( `,` Type )* `,`? )? `]` CheckValue -> CheckParam - | `[` CheckParam ( `,` CheckParam )* `,`? `]` + | `[` ( CheckParam ( `,` CheckParam )* `,`? )? `]` CheckParam -> Generics? Type ``` -One invocation may carry several `CheckTable`s. `#[check_trait(...)]` overrides the derived +One invocation may carry several `CheckTable`s, written one after another with no separator — which is how +a module checks two contexts from one block. Both `TableAttr`s are optional, each may appear at most once, +and any other attribute is rejected by name rather than ignored. `#[check_trait(...)]` overrides the derived `__Check{Context}` name, and `#[check_providers(...)]` switches the assertion to the listed providers. A `CheckEntry`'s value is omitted for a component with no generic parameters; when present, a bracketed -`CheckKey` or `CheckValue` expands to the cartesian product. `Generics`, `WhereClause`, and `Type` are Rust +`CheckKey` or `CheckValue` expands to the cartesian product. A `CheckParam` may carry its own generic list, +which is merged with the table's before the impl is emitted. `Generics`, `WhereClause`, and `Type` are Rust grammar productions. +Both bracketed lists accept **zero** elements, and the two empty forms behave differently. An empty value +list — `FooComponent: []` — falls back to the no-parameter check, exactly as omitting the colon would. An +empty *key* list — `[]: Rectangle` — produces no entries at all, so the line silently checks nothing; there +is no diagnostic, and it is worth a second look if a table appears to pass without doing anything. +
## Gotchas @@ -384,6 +397,11 @@ provider was found and its dependencies are satisfiable — not that the provide - [`#[use_provider]`](../attributes/use_provider.md) — builds the nested stacks `#[check_providers]` exists to localize. +The ideas behind it: + +- [Checking your wiring](/docs/concepts/check-traits) — why wiring is lazy, and one broken context + followed through three stages of diagnosis. + ## Source - Entry point: [`check_components.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/check_components.rs) diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 88eedc06..5e4e1295 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -106,7 +106,44 @@ delegate_and_check_components! { } ``` -The two per-entry attributes are **mutually exclusive**, and at most one may appear on a given key. +The two per-entry attributes are **mutually exclusive**, and at most one may appear on a given key. A +second one is rejected, as is any other attribute, and `#[skip_check]` takes no arguments. + +### Attributes on a list key merge + +A bracketed key may carry a check attribute of its own *and* have attributes on the names inside it, and +the two are combined per element rather than one winning. An absent attribute defers to the present one, +two `#[check_params]` lists concatenate, and two `#[skip_check]`s stay a skip: + +```rust +delegate_and_check_components! { + MyApp { + #[check_params(Rectangle)] + [ + #[check_params(Circle)] + AreaCalculatorComponent, + RotatorComponent, + ]: ShapeProvider, + } +} +``` + +`AreaCalculatorComponent` is checked against `Rectangle` and `Circle`; `RotatorComponent` against +`Rectangle` alone. The one combination refused is a `#[skip_check]` merged with a `#[check_params]`, since +they ask for opposite things: + +```text +error: cannot combine #[skip_check] with #[check_params] +``` + +### Two forms that quietly check nothing + +An **empty** `#[check_params()]` has no parameters to iterate over, so it skips the entry exactly as +`#[skip_check]` would, without saying so. Write `#[skip_check]` when that is what you mean. + +A key carrying **only generics** is the opposite case and is easy to assume away: it *is* still checked, +with its generics bound on the check impl and unit parameters. ` FooKey: FooProvider` derives +`impl __CanUseContext, ()> for Context {}`, which is what keeps `I` from appearing unbound. ### What is wired, and what is checked @@ -373,6 +410,11 @@ derivation only produces checks for entries keyed on a component name — so a t - [`UseField`](../providers/use_field.md) and [`UseType`](../providers/use_type.md) — the providers the examples wire. +The ideas behind it: + +- [Checking your wiring](/docs/concepts/check-traits) — the lazy-wiring problem this macro exists to + make unforgettable. + ## Source - Entry point: [`delegate_and_check_components.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/delegate_and_check_components.rs) diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index c25e99d5..3d2151d2 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -601,18 +601,20 @@ SingleKey -> Generics? Type MultiKey -> `[` SingleKey ( `,` SingleKey )* `,`? `]` PathKey -> Generics? `@` PathHead -PathHead -> PathSegment ( `.` PathHead )? - | `[` PathSegment ( `,` PathSegment )* `,`? `]` ( `.` PathHead )? +PathHead -> KeySegment ( `.` PathHead )? + | `[` KeySegment ( `,` KeySegment )* `,`? `]` ( `.` PathHead )? | `{` PathHead ( `,` PathHead )* `,`? `}` -PathSegment -> Generics? Type +KeySegment -> Generics? PathSegment PathValue -> `@` PathSegment ( `.` PathSegment )* +PathSegment -> Type + ProviderValue -> Type | IDENTIFIER `<` `new` InnerTable `>` -InnerTable -> IDENTIFIER GenericArgs? `{` TableBody `}` +InnerTable -> IDENTIFIER BoundFreeGenerics? `{` TableBody `}` ``` A leading `Generics` list makes the table generic over the target; `new` additionally emits the target @@ -623,18 +625,26 @@ separately because a `ForStmt` body admits only that form. The two grouping forms inside a `PathHead` differ in what they group and in whether the path may continue. A bracketed group holds alternative segments for one position and may be followed by `.` and more path; a braced group holds alternative whole remainders and terminates the path, which is why only -the braced form can nest. Both fan out to the cartesian product with the rest of the path. A `PathValue` -— the right-hand side of a `=>` — admits no groups and is [`Path!`](./path.md)'s own production. +the braced form can nest. Both fan out to the cartesian product with the rest of the path. + +The three segment productions differ in what they permit, which is why they are named apart. A +`KeySegment` — inside a `PathKey` — may carry its own generic list, and the parameters of every segment +along one path are merged onto that entry's impls. A `PathSegment` — inside a `PathValue`, the +right-hand side of a `=>` — carries none, and admits no groups; it is [`Path!`](./path.md)'s own +production, which is what keeps the two in step. And every `Generics` list on a key is an impl-position +list, so a bound is accepted (` BazKey: BazProvider`) and a parameter *default* is not — +`` fails with `invalid impl generics syntax`. A `ProviderValue`'s nested-table form carries a full `TableBody`, so an inner table accepts every form an outer one does. An `InnerTable` is an identifier with an optional generic list rather than a full -`TargetType` — a nested table always names a fresh struct the macro declares — and that list is -bound-free; put the bound on the entry's own generics instead. A bound written on the inner table is -rejected as `expected ','`, because the value parser tries the nested-table form speculatively and then -falls back to reading the whole value as a plain type. An `OpenStmt` may omit its braces when opening exactly one component. Every -`Statement` precedes every `Mapping`. `NamespaceStmt` and `ForStmt` are described under -[`cgp_namespace!`](./cgp_namespace.md). The macro accepts no attributes anywhere and rejects any it -finds. +`TargetType` — a nested table always names a fresh struct the macro declares — and its +`BoundFreeGenerics` is a definition-position list: no bounds, no defaults, and a `const` parameter +written as the bare name. Put a bound on the entry's own generics instead. A bound written on the inner +table is rejected as `expected ','`, because the value parser tries the nested-table form speculatively +and then falls back to reading the whole value as a plain type. An `OpenStmt` may omit its braces when +opening exactly one component. Every `Statement` precedes every `Mapping`. `NamespaceStmt` and +`ForStmt` are described under [`cgp_namespace!`](./cgp_namespace.md). The macro accepts no attributes +anywhere and rejects any it finds.
@@ -644,7 +654,7 @@ finds. unmet, still compiles. The failure appears later, at the place the capability is used, often as a long error naming types you did not write. This is the single most common source of confusion with CGP, and the answer is to check the table — see [`check_components!`](./check_components.md) — and to run -[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) in place of `cargo check`, which leads +[`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`, which leads with the root cause for the classes it recognizes. **Statements must lead the block**, and getting it wrong produces a misleading message. Once the @@ -697,6 +707,14 @@ The same applies to a direct entry for a path a joined namespace itself binds reuses this macro's whole body grammar. - [`UseField`](../providers/use_field.md) — the usual value for a field-backed getter. +The ideas behind it: + +- [Bypassing coherence](/docs/concepts/coherence) — why a context chooses its providers through a + table rather than through impls. +- [Aggregate providers](/docs/concepts/aggregate-providers) — the `new`-keyword bundle, and why it + is a provider rather than a context. +- [Checking your wiring](/docs/concepts/check-traits) — what makes an unchecked table a problem. + ## Source - Entry point: [`delegate_components.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/delegate_components.rs) diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index bc20425c..50bbcf8e 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -235,6 +235,11 @@ the check rather than at the definition. - [`Product!`](./product.md) and [`Sum!`](./sum.md) — the sibling construction macros, sharing the fold shape. - [`DelegateComponent`](../traits/delegate_component.md) — the per-key table a resolved path finally reads. +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — where paths are actually written, and what a route is + for. + ## Source - Entry point: [`path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/path.rs) diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index bee8f56a..33467717 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -213,6 +213,11 @@ the order *is* the execution order. - [Handler combinators](../providers/handler_combinators.md) — where `Product!` is written by hand, as a pipeline. +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — the record representation this list is + the spine of. + ## Source - Entry points: [`product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/product.rs) diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 309c0a84..22869942 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -188,6 +188,11 @@ struct: the variant's payload type has to be a single nameable type for the sum taking apart a variant generically. - [`CanUpcast`](../traits/cast.md) — converting between two enums that share variants. +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — the variant representation this list + is the spine of. + ## Source - Entry point: [`sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/sum.rs) diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 33229a98..eab9baa6 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -231,6 +231,10 @@ type argument rather than the value. tags. - [`StaticFormat`](../traits/static_format.md) — recovering runtime text from a type-level string. +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where field-name tags are used at scale. + ## Source - Entry point: [`symbol.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/symbol.rs) From 5646dc62443ea0c48244ec3f9d51789b17d17aa8 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 20:54:11 +0200 Subject: [PATCH 027/516] Write the compile-errors reference page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces the stub at `docs/reference/errors.md`. The sixteen internal error-class documents become one page rather than sixteen, because sixteen public pages would be a category no reader scans, and it is organized by the internal catalog's own hidden-versus-surfaced axis: the same mistake yields a message with the cause in it or a message with the cause absent, depending on whether a check or a method call found it. That distinction is stated once, early, and everything else follows from it. Because a reader arrives holding an error rather than a topic, the page opens on a lookup table keyed on what they have — a rustc code plus a message shape — routing to sixteen sections in four groups: dependency failures, a lookup that finds nothing, structural wiring conflicts, and macro-lowering failures. Every quoted diagnostic is read out of a `cargo-cgp` UI fixture's blessed `.cgp.stderr` or `.rust.stderr` rather than reconstructed, which is what lets the page's central demonstration be shown rather than asserted: the checked and the method-call routes to one mistake produce byte-identical recovered output. Two things the page carries that no internal document does. `CGP-E012`–`E016` — a capability used without `#[uses]`, an inner provider used without `#[use_provider]`, and three consumer-versus-provider-trait confusions — are first-week mistakes the tool rewrites but the error catalog has no classes for, so they are documented here from the tool's own catalog; the gap is recorded on the internal side. And the `[CGP-Exxx]` code tables land here because nothing on the site listed the codes and the catalog defining them is not linkable from a public page. `example-code/src/reference/errors.rs` pins the page's one program in both directions: a live module proving the wiring block compiles — which the page asserts in bold, and which therefore omits the `check_components!` this crate otherwise adds to every wired context — plus `compile_fail` doctests for the checked and the hidden failure. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_011BfN1sjgaBAA2sEVqVNeig --- docs/reference/errors.md | 664 ++++++++++++++++++++++++++- example-code/src/reference/errors.rs | 147 ++++++ example-code/src/reference/mod.rs | 1 + 3 files changed, 807 insertions(+), 5 deletions(-) create mode 100644 example-code/src/reference/errors.rs diff --git a/docs/reference/errors.md b/docs/reference/errors.md index d48111e0..6e51377e 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -5,12 +5,666 @@ sidebar_position: 90 # Compile errors -The errors CGP produces after macro expansion, grouped by what went wrong: a dependency a provider needs and the context does not supply, a wiring table that does not resolve, and a shorthand that lowered into something the compiler rejects. +The errors CGP produces after macro expansion, and how to read each one back to the mistake behind it. -:::info +CGP's macros expand to ordinary Rust, so most mistakes are not caught by a macro at all. They are caught +by the compiler afterwards, checking code you did not write — which is why a CGP error can name types +that appear nowhere in your source. This page is the catalog of those failures: what each one looks +like, whether the message contains the real cause, and what to change. -### Not written yet +It is meant to be looked up rather than read through. If you have an error in front of you, start from +[Find your error](#find-your-error). -This page is still being written. In the meantime, run [`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`: it un-hides the root cause the default trait solver suppresses and leads with it, for the error classes it recognizes. +## Run the checker first -::: +**Before decoding anything, run [`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`.** +It rewrites the classes it recognizes to lead with the cause, and for the worst class it recovers a +cause that plain `cargo check` discards entirely. Every "what you see" example below is its real output. + +It is a `v0.1.0-alpha` and does not reshape everything. Where a class passes through as the compiler +wrote it, this page says so and shows the raw form instead. + +## The one distinction that explains everything + +**The same mistake produces two completely different errors depending on how you run into it**, and +knowing which one you are looking at decides whether there is a cause in the message to find at all. + +CGP wiring is lazy: [`delegate_components!`](./macros/delegate_components.md) records that a **context** +— the type the capability runs against, which supplies the values it needs as its fields — uses some +provider, and nothing checks that the provider's own requirements hold. That check happens later, and +*how* it happens decides what you see. + +- **Surfaced.** When a [`check_components!`](./macros/check_components.md) block forces the question, the + compiler proves the obligation outright and names the bound that failed. The cause is in the message. +- **Hidden.** When you instead call the method on the context, the compiler sees a blanket impl among + several candidates, abandons it, and reports only that the method's bounds were not satisfied. The + cause is **absent** — not buried. Reading harder will not find it. + +This is why the standard first move on a confusing CGP error is to add a check at the wiring site: it +converts a hidden error into a surfaced one. `cargo cgp check` does the equivalent for you, which is why +both forms produce the same output through the tool. + +## Find your error + +Match the compiler's code and the shape of the message. + +| What the compiler says | Usually means | Section | +|---|---|---| +| `E0599` method exists but its trait bounds were not satisfied | A provider's dependency is unmet, reached by a method call | [A dependency is not met](#a-dependency-is-not-met) | +| `E0599` no associated function found for type parameter | An inner provider called but never imported | [Using something you did not declare](#using-something-you-did-not-declare) | +| `E0277` … `CanUseComponent` is not satisfied | A checked component's provider is missing something | [A dependency is not met](#a-dependency-is-not-met) | +| `E0277` the trait bound `f64: Eq` is not satisfied | An ordinary Rust bound on a wired type | [When the missing bound is an ordinary Rust trait](#when-the-missing-bound-is-an-ordinary-rust-trait) | +| `E0277` … `PathCons<…>: SomeNamespace<…>` is not satisfied | A namespace path nothing binds | [Nothing is wired there](#nothing-is-wired-there) | +| `E0277` the size for values of type `[u8]` cannot be known | A field-type shorthand lowered to an unsized type | [A field-type shorthand with no rule](#a-field-type-shorthand-with-no-rule) | +| `E0271` type mismatch resolving `<… as …>::Assoc == …` | A type pinned one way and wired another | [When two decisions disagree about a type](#when-two-decisions-disagree-about-a-type) | +| `E0119` conflicting implementations | Two wiring entries claim one key | [The wiring itself does not compile](#the-wiring-itself-does-not-compile) | +| `E0428` the name … is defined multiple times | A generated name declared twice | [Two entries claim one key](#two-entries-claim-one-key) | +| `E0275` overflow evaluating the requirement | A wiring or inheritance cycle | [A lookup that never terminates](#a-lookup-that-never-terminates) | +| `E0210` / `E0117` orphan rule | Registering into a namespace you do not own | [Registering into a namespace you do not own](#registering-into-a-namespace-you-do-not-own) | +| `E0207` type parameter is not constrained | A per-entry generic that never reaches the key | [A generic that reaches nothing](#a-generic-that-reaches-nothing) | +| `E0107` trait takes N generic arguments but N+1 supplied | A consumer trait written where a provider trait belongs | [Naming the wrong half of a component](#naming-the-wrong-half-of-a-component) | +| `E0433` / `E0425` cannot find type | A name the generated code cannot see | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | +| `E0576` cannot find associated type … in trait | A `#[use_type]` import with a wrong name | [An imported type that does not exist](#an-imported-type-that-does-not-exist) | +| `E0404` expected trait, found type parameter | An abstract type named after its own bound | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | + +## A dependency is not met + +This is the most common CGP failure by a wide margin: a provider needs something from its context, and +the context does not supply it. + +```rust +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + let _ = self.name(); + } +} + +#[derive(HasField)] +pub struct Person { + pub age: u8, // no `name` field, so `Person` cannot satisfy `HasName` +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} +``` + +That block **compiles**. Nothing has asked yet whether `GreetHello` can do its job here. + +### What you see + +Through the tool, both routes to the failure give the same answer. Checking it: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanGreet` is not implemented for context `Person` + --> src/main.rs:56:9 + | +56 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E106] missing field `name` on `Person` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanGreet` for context `Person` + └─ [CGP-E102] provider trait impl `Greeter` with context `Person` for provider `GreetHello` + └─ [CGP-E105] trait impl `HasName` for `Person` + └─ [CGP-E106] missing field `name` on `Person` +``` + +**Read the `root cause:` line and stop.** It names the fix. The tree beneath it is the chain of +obligations that demanded it, read top to bottom: the context must implement the consumer trait, so its +wired provider must be a provider for that context, so the context must have the field. + +Calling `person.greet()` instead of checking produces the identical note under an `E0599`. That recovery +is the single largest thing the tool does. + +### What the raw compiler says + +Without the tool the two routes diverge sharply. The **checked** form is readable: an `E0277` on +`CanUseComponent`, with a `help:` note naming the missing `HasField` and a +`required for …` chain building outward from it. The cause sits early, in that `help:` note, rather than +at the end. + +The **method-call** form is the one to learn to recognize, because there is nothing in it to find: + +```text +error[E0599]: the method `greet` exists for struct `Person`, but its trait bounds were not satisfied + | + | pub struct Person { + | ----------------- method `greet` not found for this struct because it doesn't satisfy + | `Person: CanGreet` or `Person: Greeter` + | + | Person { age: 0 }.greet(); + | ^^^^^ this is an associated function, not a method +``` + +It names the traits it could not satisfy and stops. `HasName` and the missing field appear nowhere. The +"this is an associated function, not a method" line is an artifact of how a provider trait is generated +— the suggestion to write `Person::greet()` is wrong, and it is noise rather than a clue. + +The suppression is a [long-standing compiler limitation](https://github.com/rust-lang/rust/issues/61661) +rather than a CGP quirk: with a blanket impl among the candidates, rustc declines to expand which +`where` bound made it inapplicable. + +### The fix + +Give the context what the provider needs — add the `name` field, or wire the getter to a field that +exists. If you are looking at the hidden form, add a check at the wiring site first: + +```rust +check_components! { + Person { + GreeterComponent, + } +} +``` + +### When the derive is missing entirely + +A variant worth knowing, because the fix differs and the usual landmark disappears. If the struct *has* +the field but never derived [`HasField`](./derives/derive_has_field.md), it implements the accessor for +nothing at all — and the tool reports that as one cause rather than one per field: + +```text + = help: make sure that `#[derive(HasField)]` is used for `Person` + = note: root cause: [CGP-E108] accessor trait `HasField` with field `name` is not implemented for `Person` +``` + +In the raw output the tell is an absence. A genuinely missing field draws a "but trait +`HasField` is implemented for it" hint pointing at the nearest field; a missing derive +cannot, because no field is implemented. + +### When the missing bound is an ordinary Rust trait + +A provider's dependency may be a plain Rust trait rather than a CGP capability — `Scalar: Eq`, +`Item: Ord` — unmet by the type the context wired. Here the tool deliberately keeps rustc's own headline, +because it was already the clearest statement, and tidies only the frames beneath it: + +```text +error[E0277]: the trait bound `f64: Eq` is not satisfied + --> src/main.rs:59:9 + | +59 | ScalarEqualityComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Eq` is not implemented for `f64` + | + = note: this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCompareScalars` for context `App` + └─ [CGP-E102] provider trait impl `ScalarEquality` with context `App` for provider `CompareScalars` + └─ the trait bound `f64: Eq` is not satisfied +``` + +This is the one class here with no `[CGP-Exxx]` headline, and the absence is deliberate. + +The fix is not to wire a component or add a field but to satisfy the trait: wire the abstract type to +something that implements it, implement it for a type you own, or relax the provider's bound if it asked +for more than it needed. One connective step is left to you — the message names `f64`, not the +`ScalarTypeProviderComponent: UseType` line that chose it. + +### When two decisions disagree about a type + +A provider can *pin* an [abstract type](./macros/cgp_type.md) to a concrete one while the context wires +that same abstract type to something else. The trait half of the bound still holds, so the compiler +reports a projection mismatch rather than a missing impl: + +```text +error[E0271]: [CGP-E017] expected the abstract type `Scalar` of `HasScalarType` on `Rectangle` to be `f64`, but found `u32` + | + = help: wire `ScalarTypeProviderComponent` to `UseType` in the wiring for `Rectangle`, or + change the provider to work with `u32` +``` + +Both halves of the disagreement are named, and the `help:` names the wiring line to change. The raw +`E0271` is much worse: it states only what was *required*, never what the context supplied, and puts its +caret on the `#[cgp_type]` attribute that declared the type — nowhere near either decision. + +The same shape appears one level down, when a *field's* type is expressed through an abstract type +(`#[implicit] database: &Pool`). The tool then gives the requirement in both forms — +`Pool<::Db>` followed by `(Pool)` — because the projection says where the +requirement came from and the reduced type is what you compare the field against. + +### When the provider is a stack + +With a [higher-order provider](./attributes/use_provider.md) the question is which layer to fix, and the +tool answers it in the shape of the tree. An inner-layer failure shows **two** provider hops: + +```text + = note: root cause: [CGP-E106] missing field `base_area` on `Rectangle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `ScaledArea` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `BaseArea` + └─ [CGP-E105] trait impl `HasBaseArea` for `Rectangle` + └─ [CGP-E106] missing field `base_area` on `Rectangle` +``` + +An outer-layer failure shows **one**, with the inner provider never named. Either way the wiring is +correct and the fix is to supply the field; the depth only tells you which layer wanted it. + +When a stack is deep enough that this is still awkward, the `#[check_providers(...)]` form of +[`check_components!`](./macros/check_components.md) asserts each layer separately, so a dependency +missing only from the wrapper fails on its line alone. + +### When one mistake prints many errors + +A dependency several components share, left unmet, fails at every one of them. Raw `cargo check` prints +one block per affected provider — three chained components over one missing field produce **six** — and +only some of them reach the cause. + +The tool collapses the whole cascade into one block naming every affected consumer over a single tree: + +```text +error[E0277]: [CGP-E001] the consumer traits `CanBaz`, `CanBar`, and `CanFoo` are not implemented for context `App` + | +85 | BazComponent, + | ^^^^^^^^^^^^ +86 | BarComponent, + | ^^^^^^^^^^^^ +87 | FooComponent, + | ^^^^^^^^^^^^ + | + = note: root cause: [CGP-E106] missing field `name` on `App` +``` + +Fix the one cause and all of it disappears together. + +On the raw output the rule for finding that cause is structural rather than positional: **look for a +block whose `help:` names a concrete missing item** — a field, a type — rather than another provider +trait. Blocks naming `SomeProvider: SomeTrait` are consequences. Two habits help besides: check one +suspect component in its own `check_components!` block, or comment entries out until the failure moves. + +## Nothing is wired there + +A neighbouring failure that reads like a dependency problem but is not: no provider is found *at all*, +rather than one being found whose requirements fail. + +The common case is a component registered into a [namespace](./macros/cgp_namespace.md) under a path that +nothing ever binds — a `#[prefix]` routes the lookup somewhere, and no `#[default_impl]`, namespace entry, +or direct wiring puts a provider there: + +```text + = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `@app.GreeterComponent` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanGreet` for context `App` + └─ [CGP-E104] redirect lookup to `@app.GreeterComponent` in `App` + └─ [CGP-E107] context `App` does not contain any delegate entry for `@app.GreeterComponent` +``` + +The same `[CGP-E107]` leaf covers a component the context simply never wired. The path is resugared to +its `@app.GreeterComponent` form, which is the largest readability win here — raw `rustc` prints it as a +`PathCons>, _>` spine. + +In the raw output this class is unusual in that the cause **is** the primary error rather than a note +below it: an `E0277` saying a `PathCons<…>` path does not implement the namespace trait. A `Self` that is +a path or a `RedirectLookup` rather than a provider struct always means the lookup failed, not a +provider's dependencies. One landmark reads like a contradiction and is in fact the diagnosis — a `help:` +listing the component *markers* the namespace does resolve, yours among them, tells you the registration +worked and only the leaf binding is missing. + +Reached by a method call instead of a check, this hides exactly as any other dependency does. + +**The fix** is to bind a provider at the path: a `#[default_impl(@app.GreeterComponent in Namespace)]` on +the provider, a namespace body entry, or a direct line on the context — whichever matches where the +wiring belongs. When the path itself is wrong, reconcile the prefix and the binding so they name the same +one. + +## The wiring itself does not compile + +These are structural failures. The compiler reports a definite code and points at both offending lines, +so there is no cause to hunt for — the difficulty is only mapping the message back to the wiring +decision. + +### Two entries claim one key + +The same component wired twice, a generic table overlapping a specific one, an `open` header colliding +with an explicit mapping, or a provider name declared twice. CGP lowers each block independently and +cannot see the collision, so the compiler catches it: + +```text +error[E0119]: [CGP-E004] duplicate wiring for component `GreeterComponent` on `Person` + | +31 | GreeterComponent: GreetHello, + | ---------------- first implementation here +... +38 | GreeterComponent: GreetGoodbye, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `Person` +``` + +Two carets, two lines to reconcile. Related codes cover the neighbouring shapes: `[CGP-E007]` for an +`open` header colliding with an explicit entry, `[CGP-E008]` for the same key redirected twice. + +Two things are worth knowing when reading the raw form. A context-wiring entry generates *two* impls, so +one duplicate prints a **pair** of `E0119`s — one conflict, not two. And a blanket-versus-specific +collision often carries a "downstream crates may implement …" note: that is the compiler explaining that +coherence must allow for impls a future crate could add, not a second problem. + +A duplicate **name** rather than a duplicate key is an `E0428` instead, and passes through uncoded — it +already points precisely at both definitions. + +### Joining more than one namespace + +A context can forward through exactly one namespace. Two `namespace` headers — or one header plus a `for` +loop whose key is bare rather than embedded in a path — each produce a blanket impl covering every key, +and the two overlap: + +```text +error[E0119]: [CGP-E006] only one namespace can be used for each target type in `delegate_components!`, but `App` uses both `NamespaceA` and `NamespaceB` + | +52 | namespace NamespaceA; + | ---------- first implementation here +53 | namespace NamespaceB; + | ^^^^^^^^^^ conflicting implementation for `App` +``` + +**The fix** is inheritance rather than joining: define one namespace that inherits the others +(`cgp_namespace! { new Combined: NamespaceA { … } }`) and join that one. For the `for`-loop form, put the +loop's key inside a path so it keys one route instead of all of them. + +### Overriding something a namespace already binds + +A namespace's entries are defaults, but only a path it *routes to* without *terminating* can be +overridden. A path the namespace itself binds is already covered by its blanket impl: + +```text +error[E0119]: [CGP-E005] `App` cannot wire `@app.GreeterComponent.*` that is already set through `AppNamespace` + | +55 | namespace AppNamespace; + | ------------ first implementation here +57 | @app.GreeterComponent: GreetBye, + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` +``` + +**The fix** follows one rule: *a bound namespace entry cannot be overridden.* Leave the leaf path +unclaimed in the namespace so the context can supply it, or change the binding in the namespace itself. + +The same mistake one level up — a child namespace redefining a key it inherits — produces a bare +`conflicting implementations of trait ChildNs<_> for type GreeterComponent`, which the tool does not yet +rewrite. The tell is that the conflicting *self type* is a component marker rather than a context. The +fix there is to leave the key unbound in the base so each child can bind it. + +### Registering into a namespace you do not own + +Rust's orphan rule forbids implementing a foreign trait for a foreign type, and a namespace registration +is exactly such an impl when both the namespace and the key belong to other crates: + +```text +error[E0210]: [CGP-E011] cannot register the foreign path `@app.AnnouncerComponent` into the foreign namespace `AppNamespace` + | +26 | #[cgp_impl(new AnnounceQuietly)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: own one end of the wiring: key it on a component defined in this crate, or register it + from the crate that defines `AppNamespace` +``` + +**The fix** is in the `help:`: own one end. Key the registration on a local component, register it from +the namespace's own crate, or — to extend a foreign namespace — define a new local namespace that +*inherits* it rather than re-opening it, which is orphan-safe because every emitted impl is then for your +own trait. + +### A lookup that never terminates + +Wiring a component to [`UseContext`](./providers/use_context.md) when the context's only source of that +component *is* that wiring makes the lookup chase its own tail: + +```text +error[E0275]: [CGP-E010] the wiring for the consumer trait `CanGreet` on context `Person` never resolves — the lookup recurses without terminating + | + = help: a lookup that recurses usually means the component is delegated back to the context itself — + e.g. wired to `UseContext` with no direct implementation of the consumer trait — so wire a + real provider, or implement the consumer trait directly on the context +``` + +Raw `rustc` gives an `E0275` overflow with a note chain you can read the loop out of, plus a stock +"consider increasing the recursion limit" suggestion. **Ignore that suggestion**: a true cycle does not +terminate at any depth, so no limit is high enough. + +Reached by a method call rather than a check, a cycle does not overflow at all — it hides as the ordinary +`E0599`, with nothing to say a cycle was the reason. + +**A related cycle sits at namespace definitions rather than at a use site.** Namespaces whose parent +chain loops (`A: B` with `B: A`, or `A: A`) fail *eagerly*, with an `E0275` on each `cgp_namespace!` +block, because the cycle lives in the `where` clause of a generated impl the compiler checks on sight. +Two things are unusual about it. Under `cargo cgp check`'s next-generation solver the code **compiles +clean** and nothing is reported — the one class where the tool shows you *less* than plain `cargo check`. +And the wiring is wrong regardless: break the loop so the parent chain forms a tree, factoring shared +entries into a third base namespace both inherit from. + +### A generic that reaches nothing + +A per-entry generic must reach the *key*, where `DelegateComponent>` binds it. One that appears +only in the provider value binds nothing: + +```text +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates + | +39 | GreeterComponent: GreetWith, + | ^ unconstrained type parameter +``` + +This passes through unrewritten, and it does not need much — the caret is on the parameter. The message +speaks in impl terms, though, where the actionable reading is a wiring one: **the generic has to appear +in the key** (` SomeKey: …`), not only in the value. Expect the same error twice, once per +generated position; both name the same ``. + +## A macro lowered something the compiler rejects + +Here the failure is not in the wiring at all but in what a macro turned your input into. These are +generally the clearest errors in the catalog, and most pass through unrewritten because the raw message +already leads with the cause. + +### An imported type that does not exist + +[`#[use_type]`](./attributes/use_type.md) works by substitution and cannot see which associated types a +trait declares, so a wrong name is lowered faithfully and caught by name resolution: + +```text +error[E0576]: cannot find associated type `Scalr` in trait `HasScalarType` + | +21 | type Scalar; + | ------------ similarly named associated type `Scalar` defined here +... +26 | pub fn get_scalar(&self) -> Scalr { + | ^^^^^ +``` + +The caret lands on the name *you* wrote — the macro copies the identifier's span onto the rewritten path +— and the `help:` usually supplies the spelling. Nothing to decode. + +### A name the generated code cannot see + +`#[impl_generics]` adds a parameter to the generated *impl* alone, so the generated trait cannot see it. +Naming it in the signature, which stays on the trait, refers to nothing: + +```text +error[E0433]: cannot find type `Db` in this scope + | +37 | pub fn fetch_row(&self, #[implicit] database: &Pool) -> Db::Row { + | ^^ use of undeclared type `Db` +``` + +The `&Pool` argument is fine — that one is stripped into a field bound on the impl, where `Db` *is* in +scope. The `Db::Row` return type is not. **The fix** is a choice the macro cannot make for you: promote +the type to an [abstract type](./macros/cgp_type.md) so it can be named everywhere, or keep +`#[impl_generics]` and stop naming it. A bare unresolved name with no path context reports as `E0425` +instead, so grep for both. + +A sibling has the opposite cause — the name resolves, to the wrong thing. Naming an abstract type after +the trait that bounds it makes the bound resolve to the type being declared: + +```text +error[E0404]: expected trait, found type parameter `Database` + | +22 | pub trait Database: Sized { + | -------- you might have meant to refer to this trait +... +34 | type Database: Database; + | -------- ^^^^^^^^ not a trait +``` + +Both halves are named, so the message explains itself once read. Name them apart — `Db` reads better for +an abstract database type anyway. + +### A field-type shorthand with no rule + +The getter and implicit-argument macros recognize a small set of field-type shorthands — `Option<&T>`, +`&[T]`, `&str`. A *combination* they have no rule for is lowered by whichever rule matches first, and the +result can be a type that is not well-formed. `Option<&[u8]>` lowers to a bound naming the unsized +`Option<[u8]>`: + +```text +error[E0277]: the size for values of type `[u8]` cannot be known at compilation time + | +18 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `[u8]` +note: required by an implicit `Sized` bound in `Option` +``` + +Two things make this harder to read than it looks. The caret is on the macro attribute rather than on any +type you wrote, because the offending type is synthesized. And a second `E0599` on `as_ref` usually +follows — derived noise from the same unsized type, pointing at nothing new. + +**The fix** is a shape a single shorthand supports: `Option>`, or `Option<&'static [u8]>`, or a +hand-written getter naming whatever type the field actually has. The shorthands compose only where the +result is `Sized`. + +## Using something you did not declare + +A group with one cause: the body of a [`#[cgp_fn]`](./macros/cgp_fn.md) or +[`#[cgp_impl]`](./macros/cgp_impl.md) becomes a blanket impl over a generated context parameter, so +anything the body calls must be *declared* as a bound on it. Rust's raw errors here are unhelpful because +they talk about that generated parameter; the tool names the missing declaration instead. + +**A capability used without `#[uses]`:** + +```text +error[E0599]: [CGP-E012] the capability `GetCount` is used but not declared as a dependency + | +44 | format!("{} ({})", self.get_name(), self.get_count()) + | ^^^^^^^^^ + | + = help: declare it as a dependency with `#[uses(GetCount)]` +``` + +**An inner provider used without `#[use_provider]`:** + +```text +error[E0599]: [CGP-E016] the inner provider `InnerCalculator` is used but not imported + | +22 | InnerCalculator::area(self) * scale_factor * scale_factor + | ^^^^ + | + = help: import it with `#[use_provider(InnerCalculator: AreaCalculator)]` +``` + +In both cases rustc's own suggestion is worse than useless: it leaks the generated `__Context__` +parameter, and for the second it proposes the *consumer* trait, which is the wrong fix. + +### Naming the wrong half of a component + +A component has two traits, and a provider implements the *provider* one. Writing the consumer trait +where the provider trait belongs gives it one generic argument too many, because the macro inserts the +context: + +```text +error[E0107]: [CGP-E013] `CanCalculateArea` is a consumer trait, but a `#[cgp_impl]` provider must implement its provider trait `AreaCalculator` + | +9 | impl CanCalculateArea { + | ^^^^^^^^^^^^^^^^ + | + = help: change the impl header to target the provider trait: `impl AreaCalculator` (not `impl CanCalculateArea`) +``` + +Untranslated, this one mistake produces a burst of `E0425`/`E0107`/`E0186`/`E0207` errors plus a +downstream check failure, none of which names the cause. Two neighbours share the shape: `[CGP-E015]` is +the same confusion in a `#[use_provider]` bound, and `[CGP-E014]` is `#[cgp_impl]` applied to a trait that +is not a component at all — where the fix is to make it one, or to write a plain `impl`. + +## The `[CGP-Exxx]` codes + +A code tags one class of CGP mistake. The compiler's own code is always kept beside it, so +`rustc --explain` still works and nothing is reclassified away from rustc. + +Codes appear in two places and mean different things. A code in the **headline** classifies the error; a +code in the **root-cause tree** labels one link in the chain. + +### Headline codes + +| Code | Means | +|---|---| +| `CGP-E001` | A context does not implement a consumer trait | +| `CGP-E002` | A provider does not implement its provider trait for the context | +| `CGP-E003` | A field is present but has the wrong type | +| `CGP-E004` | The same key wired twice | +| `CGP-E005` | Wiring a key a namespace already binds | +| `CGP-E006` | More than one namespace joined on one context | +| `CGP-E007` | An `open` redirect colliding with an explicit entry | +| `CGP-E008` | The same key redirected twice | +| `CGP-E009` | A non-component trait — a wrapper, or a `#[cgp_fn]` capability — blocked by a CGP dependency | +| `CGP-E010` | The wiring recurses without terminating | +| `CGP-E011` | An orphan-rule namespace registration | +| `CGP-E012` | A capability used but not declared with `#[uses]` | +| `CGP-E013` | A consumer trait named in a provider impl header | +| `CGP-E014` | `#[cgp_impl]` applied to a trait that is not a component | +| `CGP-E015` | A consumer trait named in an inner-provider bound | +| `CGP-E016` | An inner provider used but not imported | +| `CGP-E017` | An abstract type wired differently from what a provider pinned | + +### Dependency-tree codes + +| Code | Means | +|---|---| +| `CGP-E101` | A hop through a context's consumer-trait impl | +| `CGP-E102` | A hop through a provider's provider-trait impl | +| `CGP-E104` | A hop through a namespace or `open` redirect | +| `CGP-E105` | A hop through any other trait | +| `CGP-E106` | **Leaf:** a field is genuinely absent | +| `CGP-E107` | **Leaf:** the context wires nothing for a component or path | +| `CGP-E108` | **Leaf:** the field exists but `#[derive(HasField)]` is missing | +| `CGP-E109` | **Leaf:** the field has the wrong type | +| `CGP-E110` | **Leaf:** a provider's own dispatch table is missing an entry | +| `CGP-E111` | **Leaf:** something wired where a provider belongs is not a provider | +| `CGP-E112` | **Leaf:** an associated type differs from what was required | +| `CGP-E201` | The root-cause lead for an ordinary Rust trait bound | + +A tree entry that merely passes a non-CGP message through in rustc's own words is left uncoded. +`CGP-E103` was retired rather than reassigned, so the rest stay stable. + +## Related constructs + +- [`check_components!`](./macros/check_components.md) — turns a hidden failure into a surfaced one, and + the first thing to reach for. +- [`delegate_components!`](./macros/delegate_components.md) — the wiring nearly every error here is about. +- [`IsProviderFor`](./traits/is_provider_for.md) — the marker that carries a provider's requirements into + a diagnostic; the reason a checked error names the cause at all. +- [`CanUseComponent`](./traits/can_use_component.md) — what a check asserts. +- [`cargo cgp check`](/docs/cargo-cgp/check) — the tool every rewritten output on this page came from. +- [`Symbol!`](./macros/symbol.md) — the type-level field name whose raw `Chars<…>` spine the tool + resugars. + +The ideas behind it: + +- [Checking your wiring](/docs/concepts/check-traits) — why wiring is lazy, and one broken context + followed through unchecked, checked, and checked through the toolchain. +- [Bypassing coherence](/docs/concepts/coherence) — the mechanism behind the `E0119` and orphan-rule + failures above. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/example-code/src/reference/errors.rs b/example-code/src/reference/errors.rs new file mode 100644 index 00000000..9fd491b5 --- /dev/null +++ b/example-code/src/reference/errors.rs @@ -0,0 +1,147 @@ +//! Code from `docs/reference/errors.md` — *Compile errors*. +//! +//! Almost every block on that page is compiler *output* rather than Rust, so only one section shows +//! a program. That section carries the page's whole point in two halves that must both stay true: +//! the wiring compiles on its own, and the same wiring fails the moment a check asks the question. +//! Each half is pinned separately below, since a page claiming "this compiles, that does not" is +//! wrong if either half moves. + +/// ## A dependency is not met +/// +/// The page's one program: `GreetHello` needs a `name` field through +/// [`HasName`](https://contextgeneric.dev/docs/reference/macros/cgp_auto_getter), and `Person` has +/// only `age`. +/// +/// **This module is the "that block compiles" claim.** The page says so in bold, because it is the +/// whole reason the error arrives later and somewhere else: `delegate_components!` records the +/// choice without proving the provider can honour it. If this module ever stops compiling, wiring +/// has stopped being lazy and the page's framing is wrong. +/// +/// Deliberately **no `check_components!` here**, departing from this crate's usual rule of adding +/// one per wired context — the check is exactly what the page withholds until the next section, and +/// adding it would make this module fail. +pub mod a_dependency_is_not_met { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); + } + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_impl(new GreetHello)] + #[uses(HasName)] + impl Greeter { + fn greet(&self) { + let _ = self.name(); + } + } + + #[derive(HasField)] + pub struct Person { + pub age: u8, // no `name` field, so `Person` cannot satisfy `HasName` + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } +} + +/// ### The fix +/// +/// The other half: the same wiring, with the check the page adds to force the failure to the wiring +/// site. The page quotes the resulting `E0277` — `[CGP-E001]` through the toolchain — so the +/// snippet is carried as a `compile_fail` doctest. +/// +/// The program is repeated in full rather than importing the module above, because a doctest is +/// compiled as its own crate and because the page shows it whole. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[cgp_component(Greeter)] +/// pub trait CanGreet { +/// fn greet(&self); +/// } +/// +/// #[cgp_auto_getter] +/// pub trait HasName { +/// fn name(&self) -> &str; +/// } +/// +/// #[cgp_impl(new GreetHello)] +/// #[uses(HasName)] +/// impl Greeter { +/// fn greet(&self) { +/// let _ = self.name(); +/// } +/// } +/// +/// #[derive(HasField)] +/// pub struct Person { +/// pub age: u8, +/// } +/// +/// delegate_components! { +/// Person { +/// GreeterComponent: GreetHello, +/// } +/// } +/// +/// // error[E0277]: [CGP-E001] the consumer trait `CanGreet` is not implemented for +/// // context `Person` +/// // root cause: [CGP-E106] missing field `name` on `Person` +/// check_components! { +/// Person { +/// GreeterComponent, +/// } +/// } +/// ``` +/// +/// And the hidden half of the same mistake, which the page contrasts against the checked one: no +/// check anywhere, the failure reached by calling the method instead. The compiler reports `E0599` +/// and names nothing about the missing field. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[cgp_component(Greeter)] +/// pub trait CanGreet { +/// fn greet(&self); +/// } +/// +/// #[cgp_auto_getter] +/// pub trait HasName { +/// fn name(&self) -> &str; +/// } +/// +/// #[cgp_impl(new GreetHello)] +/// #[uses(HasName)] +/// impl Greeter { +/// fn greet(&self) { +/// let _ = self.name(); +/// } +/// } +/// +/// #[derive(HasField)] +/// pub struct Person { +/// pub age: u8, +/// } +/// +/// delegate_components! { +/// Person { +/// GreeterComponent: GreetHello, +/// } +/// } +/// +/// // error[E0599]: the method `greet` exists for struct `Person`, but its trait bounds +/// // were not satisfied +/// Person { age: 0 }.greet(); +/// ``` +pub mod the_fix {} diff --git a/example-code/src/reference/mod.rs b/example-code/src/reference/mod.rs index ce833e2c..90784c4a 100644 --- a/example-code/src/reference/mod.rs +++ b/example-code/src/reference/mod.rs @@ -3,4 +3,5 @@ //! The section is filled in lazily, so the modules here are the pages someone has written, revised, //! or reviewed rather than the section's full inventory. +pub mod errors; pub mod macros; From ee9cae16244754bd28ec583854472b762427890a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 21:53:16 +0200 Subject: [PATCH 028/516] Write the derives reference pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fill in the six pages under `docs/reference/derives/`, completing the third group of the construct reference after `macros/` and `attributes/`. Each follows the guide's six-section layered descent in the project voice, with `context` glossed on first use and no grammar section, since all six derives are argument-free. Coverage is enumerated against the parsers rather than against the internal documents, which is what surfaced the material the internal reference had not recorded: the four enum variant shapes `#[derive(HasFields)]` accepts and no other derive does, the unit struct and the fieldless record, and the seven variant names an enum cannot use. Every page has a compiled counterpart in `example-code`, and that is what earned its keep here — three claims were wrong on the page and invisible to a reader. `build_from` needs `#[derive(HasFields)]` on its *source*, not just the builder; a `__Partial…` companion carries none of the input's attributes, so an `assert_eq!` over an extraction result does not compile; and seven variant names collide with the associated types the derives generate. Each is now a Gotcha, and the rejected cases are `compile_fail` doctests rather than prose. Expansions are checked against `cargo cgp expand` and show the reserved identifiers a reader will meet in an error — `__F0__`, `'__a__`, `__T__` — rather than readable stand-ins. Link the new pages from where the constructs are mentioned elsewhere: both extensible-data concept pages, the `expand` tooling page, and the Hello World tutorial, which linked nothing into the reference before. Correct the variants concept, which stated the single-payload restriction as belonging to the shape rather than to construction and deconstruction. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_018n2krDG9WF1HD9aA1aMASX --- docs/cargo-cgp/expand.md | 6 +- docs/concepts/extensible-records.md | 10 +- docs/concepts/extensible-variants.md | 16 +- docs/reference/derives/derive_build_field.md | 363 ++++++++++++++- docs/reference/derives/derive_cgp_data.md | 429 +++++++++++++++++- .../reference/derives/derive_extract_field.md | 381 +++++++++++++++- docs/reference/derives/derive_from_variant.md | 251 +++++++++- docs/reference/derives/derive_has_field.md | 316 ++++++++++++- docs/reference/derives/derive_has_fields.md | 359 ++++++++++++++- docs/tutorials/hello.md | 4 +- .../reference/derives/derive_build_field.rs | 258 +++++++++++ .../src/reference/derives/derive_cgp_data.rs | 219 +++++++++ .../reference/derives/derive_extract_field.rs | 228 ++++++++++ .../reference/derives/derive_from_variant.rs | 177 ++++++++ .../src/reference/derives/derive_has_field.rs | 192 ++++++++ .../reference/derives/derive_has_fields.rs | 218 +++++++++ example-code/src/reference/derives/mod.rs | 8 + example-code/src/reference/mod.rs | 1 + 18 files changed, 3395 insertions(+), 41 deletions(-) create mode 100644 example-code/src/reference/derives/derive_build_field.rs create mode 100644 example-code/src/reference/derives/derive_cgp_data.rs create mode 100644 example-code/src/reference/derives/derive_extract_field.rs create mode 100644 example-code/src/reference/derives/derive_from_variant.rs create mode 100644 example-code/src/reference/derives/derive_has_field.rs create mode 100644 example-code/src/reference/derives/derive_has_fields.rs create mode 100644 example-code/src/reference/derives/mod.rs diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 44f98f57..e7258ea5 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -66,8 +66,10 @@ impl __CheckRectangle for Rectangle {} ``` Everything a reader needs in order to follow a wiring error is visible there: the field accessors -`#[derive(HasField)]` produced, the one-line table entry `delegate_components!` produced, the -forwarding impl that carries the provider's requirements, and the assertion `check_components!` added. +[`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) produced, the one-line table entry +[`delegate_components!`](/docs/reference/macros/delegate_components) produced, the forwarding impl that +carries the provider's requirements, and the assertion +[`check_components!`](/docs/reference/macros/check_components) added. ## Narrowing with `--item` diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index 00630c0b..f8218e6d 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -35,8 +35,9 @@ field of `App` is code that names `App`. ## A struct as a list of named fields -The move is to give the shape a type. `#[derive(CgpData)]` gives a struct a description of itself that -generic code can read: +The move is to give the shape a type. +[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) gives a struct a description of itself +that generic code can read: ```rust #[derive(CgpData)] @@ -128,7 +129,10 @@ what runs a handler per field and assembles the result, and is the page that mak above concrete. For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) is the umbrella -derive, [`HasFields`](/docs/reference/traits/has_fields) is the whole-shape view, +derive and its slices are [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) for reading +one field, [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) for the whole shape, and +[`#[derive(BuildField)]`](/docs/reference/derives/derive_build_field) for the builder. +[`HasFields`](/docs/reference/traits/has_fields) is the whole-shape view those produce, [`HasBuilder`](/docs/reference/traits/has_builder) is the builder family, and [`Field`](/docs/reference/types/field) and [`Symbol!`](/docs/reference/macros/symbol) are the pieces a shape is made of. diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index a8c9cbd9..3b6d12ae 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -30,7 +30,8 @@ decouple each variant's handling from the enum itself so that both are additions ## An enum as a list of named variants -The move is the same as for a record: give the shape a type. Where a record is a *product* of named +The move is the same as for a record: give the shape a type with +[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data). Where a record is a *product* of named fields, an enum is a *sum* of named variants: ```rust @@ -119,7 +120,11 @@ getter — code touching part of a shape without naming the whole. **One unnamed field per variant.** A derivable enum must be a sum of products: each variant holds exactly one unnamed payload. A richer variant wraps its data in a dedicated struct — which is why the example above is `Circle(Circle)` rather than `Circle { radius: u64 }`. It is a real constraint on how -the enum is written, and it is the first thing anyone hits. +the enum is written, and it is the first thing anyone hits. The constraint comes from constructing and +deconstructing rather than from the shape itself: +[`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) accepts every variant shape, so an +enum that cannot take the full family can still have a structural representation — just no generic +constructor and no extractor. **Only types that opted in**, as with records. An enum from a crate that has not derived the shape is invisible to all of this. @@ -140,8 +145,11 @@ variant, and [Type-level DSLs](./type-level-dsls.md) is the largest thing this p language whose terms are types and whose interpreter is the trait system. For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) is the umbrella -derive, [`ExtractField`](/docs/reference/traits/extract_field) is the extractor family behind the -narrowing, [`FromVariant`](/docs/reference/traits/from_variant) constructs a variant generically, and +derive and its slices are [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) for the +whole shape, [`#[derive(ExtractField)]`](/docs/reference/derives/derive_extract_field) for the +narrowing, and [`#[derive(FromVariant)]`](/docs/reference/derives/derive_from_variant) for construction +by name. [`ExtractField`](/docs/reference/traits/extract_field) is the extractor family those produce, +[`FromVariant`](/docs/reference/traits/from_variant) constructs a variant generically, and [the casts](/docs/reference/traits/cast) are `CanUpcast` and `CanDowncast`. --- diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 8d745db2..299f486c 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -6,12 +6,365 @@ sidebar_label: '#[derive(BuildField)]' Builder support for a record. -:::info +## What it's for -### Not written yet +A struct literal has to be written in one place that names the concrete type and supplies every field at +once. That is usually what you want — and it is exactly wrong when the fields come from several independent +places, none of which should know the whole type. A hand-written constructor that grows a parameter per +subsystem becomes the one file every change has to edit. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[derive(BuildField)]` replaces it with a builder whose completeness is tracked **in the type**. The derive +generates a companion struct that starts out with every field absent, and each step fills one field in and +returns a value of a *different* type — one where that field is now present. Only the all-present type can be +turned back into the real struct: + +```rust +let person = Person::builder() // nothing set yet + .build_field(PhantomData::, first) + .build_field(PhantomData::, last) + .finalize_build(); // every field set: closes +``` + +Delete either middle line and this does not compile. There is no runtime check, no `Option` per field, and no +panic path — `finalize_build` simply does not exist for a value with a field still missing. What a +conventional builder catches at run time, this catches while you are typing. + +The other half of the payoff is that steps are decoupled. Because each `build_field` names its field by a +type-level tag rather than by calling a method on the concrete type, generic code can fill in a field of a +struct it does not know, and two independent implementations can each contribute part of one value. + +## Using it + +The macro is a plain derive on a struct. It takes no arguments and has no helper attributes: + +```rust +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +Each named field becomes a [`Symbol!`](../macros/symbol.md) tag and its declared type becomes the value that +tag holds. A tuple struct works the same way with positional tags: a field at position `N` is keyed by +[`Index`](../types/index.md), so its builder step is +`build_field(PhantomData::>, value)`. Generic parameters, lifetimes, and a `where` clause are +carried onto the companion type and every generated impl. + +A fieldless struct is the degenerate case rather than an error. Its companion type takes no parameters at all, +so there is exactly one configuration of it and `builder()` is immediately finalizable — the presence tracking +has nothing to track. + +The derive parses a struct, so applying it to an enum fails at parse time. The enum counterparts are +[`#[derive(ExtractField)]`](./derive_extract_field.md) for taking one apart and +[`#[derive(FromVariant)]`](./derive_from_variant.md) for constructing one. + +### What it does *not* generate + +This is the point of deriving it alone, so it is worth being explicit. `#[derive(BuildField)]` emits the +builder and nothing else — **no** `HasField` accessors on your struct and **no** whole-shape representation. +Those come from [`#[derive(HasField)]`](./derive_has_field.md) and +[`#[derive(HasFields)]`](./derive_has_fields.md), and the umbrella +[`#[derive(CgpData)]`](./derive_cgp_data.md) includes all three. + +So a struct that derives only `BuildField` can be *built* generically and not *read* generically. That is +occasionally exactly right — an output type a pipeline assembles and hands back — and it is why the slice +exists. + +### The three ways to fill a field + +The builder is driven through methods that come from the library rather than from the derive, and there are +three of them. + +**`build_field`** sets one absent field to a value, which is the step shown above. + +**`build_from`** copies every field the target and a source record share, in one step. It comes from +`CanBuildFrom` — documented with the other [structural casts](../traits/cast.md) — and is imported from +`cgp::core::field::impls`: + +```rust +Employee::builder() + .build_from(person) // first_name + last_name at once + .build_field(PhantomData::, id) + .finalize_build() +``` + +**The source of a `build_from` needs [`#[derive(HasFields)]`](./derive_has_fields.md) as well**, and this +is the easiest thing on this page to get wrong. `build_from` walks the *source's* field list to know what +to copy, and that list is what `HasFields` provides — so a source deriving only `BuildField` has a builder +of its own and still cannot be merged into anything. The target needs only this derive. + +**`take_field`** goes the other way: it removes a field that is already present, handing back the value +alongside a builder with that field absent again. It is the reverse of `build_field` and comes from +`TakeField`, which unlike the rest of the family is **not in the prelude** — import it from +`cgp::core::field::traits` when calling it directly. Most code meets it indirectly, since it is what +`build_from` uses to pull each field out of the source. + +Two more methods bracket the process. `builder()` produces the empty builder, and `into_builder()` goes the +other way, turning a finished struct into an all-present builder so its fields can be redistributed. + +## Examples + +The clearest use is extending one record into a larger one. Both structs derive the builder, and the smaller +one's fields move across in a single step: + +```rust +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +// The source of a `build_from` needs its field list too, so it derives `HasFields` as well. +#[derive(HasFields, BuildField)] +pub struct FooBar { + pub foo: u64, + pub bar: String, +} + +#[derive(BuildField)] +pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, +} + +fn extend(foo_bar: FooBar) -> FooBarBaz { + FooBarBaz::builder() + .build_from(foo_bar) // sets foo + bar + .build_field(PhantomData::, true) // sets baz + .finalize_build() +} +``` + +`FooBarBaz` does not mention `FooBar` and `FooBar` does not mention `FooBarBaz`. They share two field names, +matched at the type level, which is the whole coupling between them. + +A field that has been set can be read back out mid-build, because the companion type gains a `HasField` impl +per field that is in scope only once that field is present: + +```rust +let partial = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()); + +assert_eq!(partial.get_field(PhantomData::), "Alice"); +``` + +Asking for `last_name` there would not compile, since that field's accessor is not in scope until it is set. + +And a finished value can be taken apart and put back together, which is what generic code redistributing +fields does: + +```rust +use cgp::core::field::traits::TakeField; + +let builder = person.into_builder(); // all fields present + +let (first_name, remainder) = builder.take_field(PhantomData::); +// `remainder` is now missing first_name, so it cannot be finalized + +let person = remainder + .build_field(PhantomData::, first_name) + .finalize_build(); // all present again +``` + +## When to reach for it, and when not + +**Derive `BuildField` when a struct is assembled by code that does not know the whole struct.** That is the +case it exists for, and it is a narrower case than "this struct has several fields". + +- **Reach for it when independent parts of a program each contribute fields.** This is the extensible + builder pattern: one implementation per subsystem, each producing a small struct, merged into a target + whose fields the compiler checks are all supplied. +- **Reach for it when the type being built is itself generic.** Code that builds "whatever record these + contributions add up to" needs a builder addressed by tags rather than by method names. +- **Do not reach for it for a struct you construct with a literal.** A struct literal is already checked for + completeness, reads better, and generates nothing. This derive buys the *decoupling*, and if there is + nothing to decouple it is pure cost. +- **Do not reach for it in place of a conventional builder** with defaults and validation. It tracks presence + and nothing else: it has no notion of a default value, no way to run a check at finalize time, and no + optional field unless you make the field's own type optional. The + [optional-field extensions](../traits/optional_fields.md) cover the defaulted and optional cases, and a + hand-written builder remains the better fit when the logic is the point. + +Between this derive and its neighbours the choice is about how much of the machinery you want. + +- **[`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpRecord)]`](./derive_cgp_data.md)** if the + struct also needs per-field reads or a whole-shape representation, which is the common case. Those include + this output. +- **`#[derive(BuildField)]` alone** when the struct is only ever built generically and never read + generically. + +## Under the hood + +:::note + +### Advanced + +This section shows what the derive generates. You do not need it to use `#[derive(BuildField)]`, but the +companion type appears by name in every builder error, so recognizing it turns "no method named +`finalize_build`" into a legible message. `cargo cgp expand` prints the same thing for your own code, with +the tags resugared. ::: + +The derive centres on a companion struct named `__Partial{Name}`. It is your struct with one +[`MapType`](../traits/map_type.md) parameter added per field, and each field's type wrapped in that +parameter's projection. The marker decides how the field is stored: `IsPresent` maps `T` to `T`, `IsNothing` +maps it to `()`, and `IsVoid` maps it to the uninhabited `Void`. From: + +```rust +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +it emits: + +```rust +pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { + pub first_name: <__F0__ as MapType>::Map, + pub last_name: <__F1__ as MapType>::Map, +} +``` + +Around that struct come the entry and exit points, and the pair of them is the whole safety argument: + +```rust +impl HasBuilder for Person { + type Builder = __PartialPerson; // the empty builder + fn builder() -> Self::Builder { + __PartialPerson { first_name: (), last_name: () } + } +} + +impl IntoBuilder for Person { + type Builder = __PartialPerson; // a finished value, as a builder + // ... +} + +impl<__F0__: MapType, __F1__: MapType> PartialData for __PartialPerson<__F0__, __F1__> { + type Target = Person; // any configuration targets Person +} + +impl FinalizeBuild for __PartialPerson { // only at all-present + fn finalize_build(self) -> Self::Target { + Person { first_name: self.first_name, last_name: self.last_name } + } +} +``` + +Then, per field, an `UpdateField` impl — the primitive everything else is built from. It moves one field's +marker to a new state, returning the old value alongside the rebuilt companion: + +```rust +impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> + UpdateField for __PartialPerson<__M1__, __F1__> +{ + type Value = String; + type Mapper = __M1__; // the field's marker before the change + type Output = __PartialPerson<__M2__, __F1__>; // and after: only this field moved + // ... +} +``` + +And, per field, a `HasField` impl on the companion that is in scope only when that field's marker is +`IsPresent`, which is what lets a set field be read back mid-build: + +```rust +impl<__F1__: MapType> HasField for __PartialPerson { + type Value = String; + // ... +} +``` + +**Neither `BuildField` nor `TakeField` is generated.** Both are blanket impls in the library over the +`UpdateField` above, in opposite directions, which is why `UpdateField` — the general form, parameterized by +the marker to move *to* — is what the derive actually writes: + +- `BuildField` covers `UpdateField`, the absent-to-present move. So + `build_field` is `update_field` in that one direction. +- `TakeField` covers `UpdateField`, the present-to-absent move. + +`FinalizeBuild` is likewise a library trait; the derive supplies only the all-present impl of it. + +Two properties of the companion follow from how it is built — the derive clones your struct and renames it. +It **keeps your visibility**, yours and each field's, so a `pub struct` yields a `pub struct __PartialPerson` +with `pub` fields. But it **carries none of your attributes**: those are cleared, so a +`#[derive(Debug, Clone)]` on the record does not reach the companion. That is not an oversight — a field's +type is the projection `<__F0__ as MapType>::Map`, so a derived `Debug` would need bounds the macro has no +way to state — but it does mean a half-built value cannot be printed. + +Each generated impl is aimed at the token it came from: a per-field impl at its field, a whole-struct impl at +the struct name. + +## Gotchas + +**`finalize_build` missing is the expected error, not a bug.** A field left unset means the all-present impl +does not apply, and the compiler reports a missing method rather than a missing field. Read it as "some field +is still absent" and check the companion type in the error for which marker is `IsNothing`. + +**The companion cannot be printed or cloned.** Its attributes are cleared, so no `Debug`, no `Clone`, no +`PartialEq`, whatever the original struct derives. Read a set field through the companion's `HasField` impl +instead. + +**`build_from` needs `HasFields` on the source, not just `BuildField`.** Deriving only this macro on both +structs looks symmetric and does not work: `build_from` reads the source's field list, and only +[`#[derive(HasFields)]`](./derive_has_fields.md) provides one. The error names an unsatisfied `HasFields` +bound on the source type. + +**`TakeField` is not in the prelude.** Import it from `cgp::core::field::traits` to call `take_field` +directly. `CanBuildFrom`, which provides `build_from`, comes from `cgp::core::field::impls`. + +**There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible default +still has to be set explicitly, unless you reach for the +[optional-field extensions](../traits/optional_fields.md). + +**A tuple struct's steps are keyed by position.** Use `PhantomData::>`, not a `Symbol!` of the +number. + +**Field order does not matter, but field *names* are the whole interface.** `build_from` matches by name, so +renaming a field in one struct silently stops it being copied from the other — the result is a +`finalize_build` that no longer resolves, reported at the finalize rather than at the rename. + +**It does not accept an enum.** The enum counterparts are +[`#[derive(ExtractField)]`](./derive_extract_field.md) and +[`#[derive(FromVariant)]`](./derive_from_variant.md). + +## Related constructs + +- [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this slice. +- [`#[derive(HasField)]`](./derive_has_field.md) — per-field access on the original struct, which this derive + does not generate. +- [`#[derive(HasFields)]`](./derive_has_fields.md) — the whole-shape representation, which this derive does + not generate either. +- [`#[derive(ExtractField)]`](./derive_extract_field.md) — the enum analogue: incremental deconstruction + rather than construction. +- [`HasBuilder`](../traits/has_builder.md) — the builder trait family, including `UpdateField`, `BuildField`, + `TakeField`, and `FinalizeBuild`. +- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers the companion is + parameterized by. +- [`CanUpcast`](../traits/cast.md) — where `CanBuildFrom` and its `build_from` are documented. +- [Optional fields](../traits/optional_fields.md) — defaulted and optional fields, which the plain builder + does not model. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that run several builder + implementations and merge their outputs. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records, and the extensible builder + pattern this derive is the foundation of. + +## Source + +- Entry point: [`derive_build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_build_field.rs) +- Codegen: [`cgp_data/derive_builder/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_builder) +- Traits: [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs), + [`update_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/update_field.rs), + [`take_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/take_field.rs), + and [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 1831459a..f33ae38f 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -6,12 +6,431 @@ sidebar_label: '#[derive(CgpData)], CgpRecord & CgpVariant' The extensible-data derives: the umbrella and its struct and enum faces. -:::info +## What it's for -### Not written yet +A plain Rust struct or enum is opaque to generic code. There is no way to refer to "the `first_name` field" +or "the `Circle` variant" through a type parameter, so anything that must work across several data types ends +up written once per type. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[derive(CgpData)]` is the one-line answer: it turns a struct or an enum into **extensible data**, a type +whose fields or variants generic code can name, read, construct, and take apart without ever mentioning the +concrete type. It is the umbrella derive, and what it generates depends entirely on what it is applied to. + +On a **struct** it produces the record machinery: per-field access, the whole-shape field list, and an +incremental builder that assembles a value one field at a time. On an **enum** it produces the variant +machinery: the whole-shape variant list, a constructor per variant, and an incremental extractor that peels +variants off one at a time. + +The two things this buys are worth naming separately, because together they are what "extensible" means +here. The **representation** view describes the type as a list of named entries, which is what lets one +implementation serialize any record or dispatch over any enum. The **incremental** view adds a companion type +that tracks, in its own type parameters, which fields are present or which variants are still possible — so a +half-built value and a finished one are *different types*, and using one where the other belongs is a compile +error rather than a runtime panic. + +`#[derive(CgpRecord)]` and `#[derive(CgpVariant)]` are the same thing restricted to one shape. They run the +same code and produce the same output; the only difference is that each refuses the shape it is not for. + +## Using it + +All three derives take no arguments and have no helper attributes. `CgpData` accepts a struct or an enum; the +other two accept exactly one: + +```rust +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +Naming follows the family's rules: a named struct field or a variant is keyed by +[`Symbol!`](../macros/symbol.md), and a positional field of a tuple struct by +[`Index`](../types/index.md). Generic parameters, lifetimes, and a `where` clause are carried onto +everything generated, including the companion types. + +### Choosing among the three + +The three are interchangeable wherever the shape allows, so the choice is about what you want the code to +say. + +- **`#[derive(CgpData)]`** is the default. Use it unless you have a reason not to. +- **`#[derive(CgpRecord)]`** says "this is always a struct" and rejects anything else at parse time. +- **`#[derive(CgpVariant)]`** says "this is always an enum", likewise. + +There is no output difference to weigh: `CgpData` on a struct emits what `CgpRecord` emits, and `CgpData` on +an enum emits what `CgpVariant` emits. Reach for a shape-specific one when the name earns its keep as +documentation, or when you want the error for a wrong shape to arrive at the derive rather than further in. + +### The struct requirements + +Every struct shape is accepted. A named-field struct is keyed by field name, a tuple struct by position, and +a fieldless struct is the degenerate case rather than an error — its companion type takes no parameters at +all, so `builder()` is immediately finalizable because there is nothing to track. + +### The enum requirement + +**Every variant must carry exactly one unnamed payload.** This is the family's one real restriction, and it +comes from the two slices that take an enum apart: each has to name a single type per variant, and a unit, +multi-field, or struct-style variant gives it none or several. Such a variant fails with +`Expected variant to contain exactly one unnamed field`, and there is no way to opt one variant out — an enum +that mixes shapes cannot take these derives at all. + +The fix is to wrap the richer payload in its own struct, so the variant's value stays a single nameable type: + +```rust +// rejected: a struct-style variant has no single payload type +pub enum Shape { + Circle { radius: f64 }, +} + +// accepted: the payload is one named type +pub struct Circle { + pub radius: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), +} +``` + +That is idiomatic rather than a workaround — the payload struct usually wants to be a type in its own right, +and it can derive `CgpData` too, which is how a nested shape becomes reachable. + +One escape hatch is worth knowing: [`#[derive(HasFields)]`](./derive_has_fields.md) accepts **all four** +variant shapes, because it only describes a variant rather than deconstructing it. So an enum with mixed +variants can still have a structural representation; what it cannot have is the generic constructor or the +extractor. A variantless enum, meanwhile, is accepted and degenerates the same way a fieldless struct does. + +## Examples + +The record side is most useful for assembling one struct out of pieces. Because both structs derive the +machinery, a builder can copy every shared field from another record in one step and fill in the rest: + +```rust +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +#[derive(CgpData)] +pub struct Employee { + pub employee_id: u64, + pub first_name: String, + pub last_name: String, +} + +fn promote(person: Person, id: u64) -> Employee { + Employee::builder() // every field absent + .build_from(person) // first_name + last_name now present + .build_field(PhantomData::, id) + .finalize_build() // all present: this is where it closes +} +``` + +Neither struct knows about the other. They share two field *names*, and the names are matched at the type +level, so `build_from` moves those fields across and leaves `employee_id` for the caller. Remove the +`build_field` line and this stops compiling, because `finalize_build` only exists once every field is present. + +The variant side is most useful for matching generically with a guaranteed-exhaustive end. Each extraction +either yields the payload or hands back a *remainder* whose type has that variant ruled out: + +```rust +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); // no variants left, so this cannot fail + rect.width * rect.height + } + } +} +``` + +There is no wildcard arm and no `unreachable!()`. After the second extraction the remainder's type has both +variants ruled out, which makes it uninhabited, and `finalize_extract_result` is what discharges a value that +cannot exist. Add a third variant to `Shape` and this function stops compiling until it is handled — the same +guarantee a concrete `match` gives, recovered for code that never names the enum. + +## When to reach for it, and when not + +**Reach for one of these derives when generic code has to work over the type's own structure.** That is the +test, and it is narrower than it sounds. Most types in a CGP program want +[`#[derive(HasField)]`](./derive_has_field.md) and nothing more, because most of what implementations need +from a context — the type a capability runs against, which supplies values as its fields — is to read one +value out of it. + +The cases that do earn it are specific. + +- **A record assembled from independent pieces.** When several parts of a program each contribute part of a + struct and no one place should know the whole type, that is the extensible builder pattern and this is what + it runs on. +- **An enum handled one variant at a time by independent code.** When variants and the operations over them + both need to grow without editing each other, this is the extensible visitor pattern. +- **A framework over any user type.** A serializer, a validator, or a mapper written once against the shape + rather than once per type. + +And the cases that do not: + +- **A closed enum with fixed operations.** A `match` is clearer than any machinery, and it already gives + exhaustiveness. Reach for the variant derives when the variant set is open or independent modules must each + contribute one. +- **A struct whose fields are only ever read.** [`#[derive(HasField)]`](./derive_has_field.md) is the whole + answer, and it is one impl pair per field rather than a companion type and a dozen impls. +- **A one-off structural manipulation.** A lighter generic-programming library is a better fit than adopting + this family for a single conversion. + +When you want only part of the output, the family splits along the lines you would expect, and deriving the +slice is the cheaper choice: [`#[derive(HasField)]`](./derive_has_field.md) for the getters, +[`#[derive(HasFields)]`](./derive_has_fields.md) for the representation, +[`#[derive(BuildField)]`](./derive_build_field.md) for the record builder, +[`#[derive(ExtractField)]`](./derive_extract_field.md) for the extractor, and +[`#[derive(FromVariant)]`](./derive_from_variant.md) for the variant constructors. The umbrella is the right +call once you want most of them. + +One honest cost: this is the heaviest derive in CGP. It generates a companion type and, for an enum, two of +them, plus an impl per field or variant on top of the whole-type impls. That is compile-time work, and the +generated types appear by name in error messages. It buys guarantees a runtime builder cannot give, and it is +not free. + +## Under the hood + +:::note + +### Advanced + +This section shows what the derives generate. You do not need it to use them, but the companion types appear +by name in compiler errors, so recognizing one turns an intimidating error into a legible one. +`cargo cgp expand` prints the same thing for your own code, with the tags resugared. ::: + +`#[derive(CgpData)]` dispatches on the shape of its input and then runs one of two fixed sequences. Nothing +about the umbrella is special: `#[derive(CgpRecord)]` enters the first sequence directly and +`#[derive(CgpVariant)]` the second, which is why all three agree on their output. + +### The record expansion + +For a struct, the derive emits three groups in order. From: + +```rust +#[derive(CgpData)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +it first emits the **per-field access** — a `HasField` and a `HasFieldMut` impl per field, exactly what +[`#[derive(HasField)]`](./derive_has_field.md) produces on its own. Then the **representation**, exposing the +struct as a product of named entries with conversions in both directions, which is +[`#[derive(HasFields)]`](./derive_has_fields.md)'s output: + +```rust +impl HasFields for Person { + type Fields = Product![ + Field, + Field, + ]; +} + +// plus HasFieldsRef, FromFields, ToFields, ToFieldsRef +``` + +Then the **builder**, which is [`#[derive(BuildField)]`](./derive_build_field.md)'s output and where the +companion type appears. Each field's type is wrapped in a [`MapType`](../traits/map_type.md) marker, so a +field can be present (`IsPresent`, holding the value) or absent (`IsNothing`, holding `()`): + +```rust +pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { + pub first_name: <__F0__ as MapType>::Map, + pub last_name: <__F1__ as MapType>::Map, +} + +impl HasBuilder for Person { + type Builder = __PartialPerson; // the empty builder + // ... +} + +impl FinalizeBuild for __PartialPerson { + // ... only at all-present +} +``` + +That pair of impls is the whole safety argument: `builder()` starts at all-absent, each `build_field` flips +one marker, and `finalize_build` exists only at all-present, so finalizing early is a missing impl rather than +a runtime check. The per-field `UpdateField` impls that move a marker, and the `HasField` impls on the +companion that let a set field be read back, follow. + +### The variant expansion + +For an enum, the derive emits three groups too, but a different three. From: + +```rust +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +it first emits the **representation** over a sum rather than a product: + +```rust +impl HasFields for Shape { + type Fields = Sum![ + Field, + Field, + ]; +} + +// plus HasFieldsRef, FromFields, ToFields, ToFieldsRef +``` + +Then the **constructors**, one per variant, which is +[`#[derive(FromVariant)]`](./derive_from_variant.md)'s output: + +```rust +impl FromVariant for Shape { + type Value = Circle; + + fn from_variant(_tag: PhantomData, value: Circle) -> Self { + Self::Circle(value) + } +} +``` + +Then the **extractor**, which is [`#[derive(ExtractField)]`](./derive_extract_field.md)'s output and where two +companion enums appear — `__PartialShape` for owned extraction and `__PartialRefShape` for borrowed. A +variant's payload is wrapped in a marker that is either `IsPresent` or `IsVoid`, the latter mapping it to the +uninhabited `Void`: + +```rust +pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { + Circle(<__F0__ as MapType>::Map), + Rectangle(<__F1__ as MapType>::Map), +} + +impl HasExtractor for Shape { + type Extractor = __PartialShape; // every variant still possible + // ... +} + +impl FinalizeExtract for __PartialShape { // nothing left: uninhabited + // ... +} +``` + +Note the asymmetry with the record side, which is the detail most worth carrying away: **a record uses +`IsNothing` for a field that is not there, and a variant uses `IsVoid` for one that has been ruled out.** +`IsNothing` maps a type to `()`, which is inhabited; `IsVoid` maps it to `Void`, which is not. That is exactly +why extraction ends the way it does — once every variant is `IsVoid` the whole companion enum is uninhabited, +so a value of it cannot exist and can be discharged to produce anything. + +The companion names are reserved: `__Partial{Name}` and, for the borrowed extractor, `__PartialRef{Name}`. +They keep the original type's visibility, so a `pub` struct or enum yields a `pub` companion. + +Each generated impl is aimed at the token it came from — a per-field impl at its field, a per-variant impl at +its variant, a whole-type impl at the type name — so a conflict with a hand-written impl underlines that token +rather than the whole derive. + +## Gotchas + +**Every variant needs exactly one unnamed payload.** A unit, multi-field, or struct-style variant fails, with +no per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in the family that +accepts all four shapes, so it is what an enum with mixed variants gets. + +**The companion type carries none of your attributes.** The derive clears them, so a +`#[derive(Debug, Clone)]` on the record does not reach `__Partial{Name}` and a partially-built value can be +neither printed nor cloned. Read a set field back through the companion's `HasField` impl instead. + +**A tuple struct's builder is keyed by position.** Its companion exposes `UpdateField, _>` rather +than symbol-keyed impls, so `build_field` takes `PhantomData::>`. + +**A single-field tuple struct's representation is the inner type directly**, not a one-element product — the +newtype special case described on the [`HasFields`](./derive_has_fields.md) page, which the record path +inherits. + +**Absence is spelled differently on the two sides.** `IsNothing` for a missing record field, `IsVoid` for a +ruled-out variant, and they are not interchangeable. An error mentioning the wrong one usually means record +and variant machinery have been crossed. + +**Seven variant names are reserved on an enum.** Because the generated impls name their associated types +through `Self::…`, a variant called `Fields`, `FieldsRef`, `Value`, `Remainder`, `Extractor`, `ExtractorRef`, +or `ExtractorMut` makes that path ambiguous and the derive fails with `ambiguous associated item`, headlined at +the derive. Whether the message also names the variant depends on which part collided: the representation and +constructor impls are generated for your enum and point a note at the real variant, while the extractor's are +generated for the companion enums and point back at the derive. Renaming the variant is the fix. Record field names are unaffected, +since a field is not in the same namespace as an associated type. + +**The degenerate shapes compile.** A fieldless struct yields a parameterless companion whose `builder()` is +immediately finalizable, and a variantless enum yields bare companion enums. Neither is an error, and neither +does anything useful. + +**These are the heaviest derives in CGP.** One `#[derive(CgpData)]` on a five-field struct generates a +companion type and roughly twenty impls. If only part of the output is wanted, derive the slice. + +## Related constructs + +- [`#[derive(HasField)]`](./derive_has_field.md) — the per-field access slice, on its own. +- [`#[derive(HasFields)]`](./derive_has_fields.md) — the representation slice, on its own, and the only one + that accepts every variant shape. +- [`#[derive(BuildField)]`](./derive_build_field.md) — the record builder slice, on its own. +- [`#[derive(ExtractField)]`](./derive_extract_field.md) — the extractor slice, on its own. +- [`#[derive(FromVariant)]`](./derive_from_variant.md) — the variant constructors, on their own. +- [`HasBuilder`](../traits/has_builder.md) — the builder trait family the record side generates impls for. +- [`ExtractField`](../traits/extract_field.md) — the extractor trait family the variant side generates impls + for. +- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers the companion types are + parameterized by. +- [`CanUpcast`](../traits/cast.md) — converting between two types whose shapes overlap, built on this + machinery. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that route a record or a + variant to per-entry handlers. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — the struct half, and the extensible builder + pattern. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum half, and the extensible visitor + pattern. +- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to a handler per field or + variant. + +## Source + +- Entry points: [`cgp_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_data.rs), + [`cgp_record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_record.rs), + and [`cgp_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_variant.rs) +- Shape dispatch: [`cgp_data/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/item.rs) +- Record and variant codegen: [`cgp_data/record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/record.rs) + and [`cgp_data/variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/variant.rs) +- Runtime traits: [`cgp-field/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-field/src/traits) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index a4c5596e..a060f19d 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -6,12 +6,383 @@ sidebar_label: '#[derive(ExtractField)]' Extractor support for a variant. -:::info +## What it's for -### Not written yet +A `match` on an enum is checked for exhaustiveness, which is one of Rust's best properties — and it only +works where the concrete enum is named. Code that is generic over the enum cannot write a `match`, so it +falls back on a wildcard arm and an `unreachable!()`, which is precisely the guarantee you wanted to keep. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[derive(ExtractField)]` recovers it. It lets an enum be taken apart one variant at a time, and it tracks +which variants are still possible **in the type**. Each attempt either yields the payload or hands back a +*remainder* whose type has that variant ruled out: + +```rust +match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => /* it was a Circle */, + Err(remainder) => /* it wasn't; `remainder` can no longer be a Circle */, +} +``` + +Keep going and the remainder narrows each time. Once every variant has been ruled out, the remainder's type +is **uninhabited** — a value of it cannot exist — and that is what closes the chain with no wildcard arm and +no panic path. Add a variant to the enum and the final remainder becomes inhabited again, so the code stops +compiling until the new variant is handled. The exhaustiveness check survives, for code that never names the +enum. + +The mirror image on the struct side is [`#[derive(BuildField)]`](./derive_build_field.md), which tracks which +fields are present rather than which variants are possible. Both are what "extensible" means in +[extensible data](/docs/concepts/extensible-variants): the type carries the progress, so the compiler +checks it. + +## Using it + +The macro is a plain derive on an enum. It takes no arguments and has no helper attributes: + +```rust +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +Each variant's name becomes a [`Symbol!`](../macros/symbol.md) tag and its payload type becomes the value +that tag yields. Generic parameters, lifetimes, and a `where` clause are carried onto both companion types and +every generated impl. + +### Every variant needs exactly one unnamed payload + +**This is the derive's one requirement, and it is strict.** Extraction has to name a single type per variant, +so a unit variant, a multi-field tuple variant, and a struct-style variant all fail with +`Expected variant to contain exactly one unnamed field`. There is no way to opt one variant out, so an enum +that mixes shapes cannot derive the extractor at all. + +The fix is to give the payload its own struct: + +```rust +// rejected: no single payload type +pub enum Shape { + Circle { radius: f64 }, + Empty, +} + +// accepted +pub struct Circle { + pub radius: f64, +} + +pub struct Empty; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Empty(Empty), +} +``` + +That is idiomatic rather than a concession — the payload usually deserves to be a type, and it can derive the +extensible-data machinery itself. Note that even a fieldless case has to be given a payload struct, since a +bare `Empty` is a unit variant. + +If you want the enum described structurally without deriving the extractor, +[`#[derive(HasFields)]`](./derive_has_fields.md) accepts all four variant shapes. A variantless enum is +accepted here too, and degenerates: the companion enums take no parameters at all. + +The derive parses an enum, so applying it to a struct fails at parse time. The struct analogue is +[`#[derive(BuildField)]`](./derive_build_field.md). + +### What it does *not* generate + +Deriving this slice alone gives you deconstruction and nothing else — **no** whole-shape representation and +**no** generic constructors. Those come from [`#[derive(HasFields)]`](./derive_has_fields.md) and +[`#[derive(FromVariant)]`](./derive_from_variant.md), and the umbrella +[`#[derive(CgpData)]`](./derive_cgp_data.md) includes all three. So an enum deriving only `ExtractField` is +taken apart generically but still constructed with its ordinary `Shape::Circle(..)` constructor. + +### The three extractors + +The derive generates three ways in, differing only in how the payload is held. + +**`to_extractor()`** consumes the value and yields payloads by value. This is the one most code uses. + +**`extractor_ref()`** borrows, so each payload comes out as a shared reference and the original value is +untouched. Use it for a read-only operation over an enum you do not own. + +**`extractor_mut()`** borrows mutably, so a payload can be modified in place. + +All three then drive the same `extract_field` chain, and `from_extractor` converts an owned extractor back +into the enum. + +## Examples + +The chain reads as a sequence of attempts, each handling one variant, with the last one closed by +`finalize_extract_result`: + +```rust +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); // remainder is now empty; this cannot fail + rect.width * rect.height + } + } +} +``` + +The second `extract_field` returns a `Result` whose error type is uninhabited, so +`finalize_extract_result` collapses it to the value with nothing to handle. That is not a convention — it is +the type. Try to finalize after only the first extraction and it does not compile, because `Rectangle` is +still possible. + +Reading through a borrow leaves the value intact: + +```rust +let radius = shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok(); +``` + +And the mutable form modifies a payload in place: + +```rust +if let Ok(circle) = shape + .extractor_mut() + .extract_field(PhantomData::) +{ + circle.radius = 5.0; +} +``` + +In practice you rarely write these chains by hand. The +[dispatch combinators](../providers/dispatch_combinators.md) build them for you from a set of per-variant +implementations, which is the extensible visitor pattern — a chain like the one above, generated, with one +implementation per variant chosen by wiring. + +## When to reach for it, and when not + +**Derive an extractor when independent code has to handle one variant each, or when the code doing the +matching cannot name the enum.** Those are the two cases, and outside them a `match` wins on every count. + +- **Reach for it for the extensible visitor pattern.** When variants and the operations over them both need + to grow without editing each other, per-variant implementations plus a dispatcher is what this derive is + for. +- **Reach for it when the enum is a type parameter.** Generic code cannot `match`, so the extractor is the + only route to an exhaustiveness guarantee. +- **Do not reach for it for a closed enum with fixed operations.** A `match` is shorter, reads better, + already gives exhaustiveness, and generates nothing. This derive is not an improvement on `match`; it is + what you use when `match` is unavailable. +- **Do not reach for it to test which variant a value holds.** `matches!` or an `if let` answers that in one + line. The extractor's value is in the *chain* and what the chain proves. + +Between this derive and its neighbours: + +- **[`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpVariant)]`](./derive_cgp_data.md)** if the + enum also needs a structural representation or generic construction, which is the common case — those + include this output. +- **`#[derive(ExtractField)]` alone** when the enum is only ever deconstructed generically. +- **[`#[derive(FromVariant)]`](./derive_from_variant.md)** is the opposite direction, and the two are often + wanted together. + +One honest limit: the single-payload requirement is real friction. An enum whose variants carry no payload, +or several, has to be restructured before it can take this derive, and that restructuring reaches every +construction site. It is worth doing when the visitor pattern is the goal and not worth doing to satisfy a +derive you did not need. + +## Under the hood + +:::note + +### Advanced + +This section shows what the derive generates. You do not need it to use `#[derive(ExtractField)]`, but the +companion enums appear by name in every extraction error, so recognizing one turns an intimidating error into +a legible message. `cargo cgp expand` prints the same thing for your own code, with the tags resugared. ::: + +The derive centres on **two** companion enums. `__Partial{Name}` is your enum with one +[`MapType`](../traits/map_type.md) parameter added per variant and each payload wrapped in that parameter's +projection, where `IsPresent` keeps the payload and `IsVoid` maps it to the uninhabited `Void`. +`__PartialRef{Name}` adds a reserved `'__a__` lifetime and a second marker that selects a shared or a mutable borrow of each +payload. From: + +```rust +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +it emits: + +```rust +pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { + Circle(<__F0__ as MapType>::Map), + Rectangle(<__F1__ as MapType>::Map), +} + +pub enum __PartialRefShape<'__a__, __R__: MapTypeRef, __F0__: MapType, __F1__: MapType> { + Circle(<__F0__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Circle>>), + Rectangle(<__F1__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Rectangle>>), +} +``` + +Around them come the three entry points and the exit. `HasExtractor` yields an owned extractor with every +variant present; the borrowed pair yield the ref enum with the borrow marker fixed to `IsRef` or `IsMut`: + +```rust +impl HasExtractor for Shape { + type Extractor = __PartialShape; // every variant still possible + // to_extractor / from_extractor map each concrete variant across, and back +} + +impl HasExtractorRef for Shape { + type ExtractorRef<'__a__> = __PartialRefShape<'__a__, IsRef, IsPresent, IsPresent> + where + Self: '__a__; + // ... +} + +// plus HasExtractorMut over __PartialRefShape<'__a__, IsMut, IsPresent, IsPresent> +``` + +The exit is the impl the whole design turns on. It exists only for the all-`IsVoid` configuration, and +because that configuration is uninhabited its body is an empty `match` — which is why it can claim to return +*any* type: + +```rust +impl FinalizeExtract for __PartialShape { + fn finalize_extract<__T__>(self) -> __T__ { + match self {} + } +} +``` + +Then, per variant, an `ExtractField` impl in scope only when that variant's marker is `IsPresent`. It returns +`Ok` on a match and, on a miss, an `Err` whose type has that one marker flipped to `IsVoid`: + +```rust +impl<__F1__: MapType> ExtractField for __PartialShape { + type Value = Circle; + type Remainder = __PartialShape; // Circle ruled out; __F1__ untouched + + fn extract_field(self, _: PhantomData) -> Result { + match self { + __PartialShape::Circle(value) => Ok(value), + __PartialShape::Rectangle(value) => Err(__PartialShape::Rectangle(value)), + } + } +} +``` + +Note that only the extracted variant's marker changes — the rest stay generic, which is what lets the +extractions happen in any order. The same impls are emitted over the ref enum, so a borrowed chain narrows +identically. + +`FinalizeExtract` and its companion `FinalizeExtractResult` are library traits; the derive supplies only the +all-void impl. `FinalizeExtractResult` is what `finalize_extract_result` calls to collapse a +`Result` into `T`. + +**The variantless enum is genuinely special-cased**, and the reason is a Rust subtlety worth knowing. Such an +enum borrows nothing, so the ref companion is emitted as a bare empty enum with neither the lifetime nor the +borrow marker — leaving them in would make both unused parameters. And every borrowed accessor matches +`*self` rather than `self`, because a reference is always considered inhabited even when its target is not, so +`match self {}` on a `&Self` would be rejected as non-exhaustive. + +Each generated impl is aimed at the token it came from: a per-variant impl at its variant, a whole-enum impl +at the enum name. The companion enums are cloned from yours, so their tokens already carry meaningful spans. + +## Gotchas + +**Every variant must carry exactly one unnamed payload.** A unit, multi-field, or struct-style variant fails, +with no per-variant opt-out. Wrap the payload in its own struct — including for a case that carries nothing, +which still needs a payload type. [`#[derive(HasFields)]`](./derive_has_fields.md) is the derive that accepts +all four shapes. + +**Absence here is `IsVoid`, not `IsNothing`.** The record side uses `IsNothing`, which maps a type to `()` +and is inhabited; a ruled-out variant uses `IsVoid`, which maps to the uninhabited `Void`. That difference is +load-bearing rather than cosmetic — it is why a fully-narrowed remainder cannot exist and can be discharged. +An error naming the wrong marker usually means record and variant machinery have been crossed. + +**Five variant names are reserved, and using one does not compile.** The generated impls write +`Self::Value`, `Self::Remainder`, `Self::Extractor`, `Self::ExtractorRef`, and `Self::ExtractorMut` to name +their associated types, so a variant with any of those names makes the path ambiguous. The compiler reports +`ambiguous associated item`, and this is the opaque one in the family: both the headline *and* the +"could refer to the variant defined here" note land on the derive, so nothing in the output names the +variant to rename. That is because these impls are generated for the companion enums rather than for +yours. Check your variant names against the five above. Renaming the variant is the fix. [`#[derive(HasFields)]`](./derive_has_fields.md) reserves `Fields` +and `FieldsRef` for the same reason, so an enum deriving the whole family should avoid all seven. + +**A remainder carries none of the enum's attributes.** Like the record side's companion, the partial enums +are generated without your derives, so a `Result` cannot be compared or printed as a +whole. Reach for `.ok()`, `.is_ok()`, or a `match` rather than `assert_eq!` on the result. + +**`FinalizeExtractResult` is not in the prelude.** Import it from `cgp::core::field::traits` to call +`finalize_extract_result`. + +**Finalizing early does not compile, and the error names the companion.** The all-void impl does not apply +while any marker is still `IsPresent`, so the compiler reports a missing method. Read the companion type in +the message to see which variants are still possible. + +**The order of extraction is free but the set is not.** Each step only changes its own variant's marker, so +you may extract in any order — but you must extract *every* variant before the remainder can be finalized. + +**Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the reason +to prefer the [dispatch combinators](../providers/dispatch_combinators.md), which derive the chain from the +enum's own variant list rather than repeating it at each site. + +**It does not accept a struct.** The struct analogue is +[`#[derive(BuildField)]`](./derive_build_field.md). + +## Related constructs + +- [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this slice. +- [`#[derive(FromVariant)]`](./derive_from_variant.md) — the opposite direction, generic construction, which + this derive does not generate. +- [`#[derive(HasFields)]`](./derive_has_fields.md) — the whole-shape representation, which this derive does + not generate either, and the one derive that accepts every variant shape. +- [`#[derive(BuildField)]`](./derive_build_field.md) — the struct analogue: incremental construction rather + than deconstruction. +- [`ExtractField`](../traits/extract_field.md) — the extractor trait family, including `HasExtractor`, + `FinalizeExtract`, and `FinalizeExtractResult`. +- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsVoid` markers the companion enums are parameterized + by. +- [`CanUpcast`](../traits/cast.md) — upcasting and downcasting between enums, which reuse this recursion. +- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain an enum's shape is built + from. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build an extraction chain + for you, one implementation per variant. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — partial variants, the exhaustiveness argument, + and the extensible visitor pattern. +- [Dispatching](/docs/concepts/dispatching) — routing a variant to the implementation that handles it. + +## Source + +- Entry point: [`derive_extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_extract_field.rs) +- Codegen: [`cgp_data/derive_extractor/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_extractor) +- Traits: [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) + and [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type_ref.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 41addb49..57ef5dcc 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -6,12 +6,253 @@ sidebar_label: '#[derive(FromVariant)]' Generic construction of an enum from one of its named variants. -:::info +## What it's for -### Not written yet +`Shape::Circle(circle)` names two things: the enum, and the variant. That is fine at a concrete call site and +useless to code that knows neither — a routine that has been handed a value and told which variant to wrap it +in cannot write that expression. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[derive(FromVariant)]` gives it a way to. The derive adds one constructor per variant, addressed by the +variant's *name as a type*, so the choice of variant becomes a parameter rather than syntax: + +```rust +Shape::from_variant(PhantomData::, circle) +``` + +That call is equivalent to `Shape::Circle(circle)`. The difference is that the tag can come from a type +parameter, so one function can build whichever variant it was asked for, of whichever enum. + +**This is the simplest derive in the extensible-data family.** It generates no companion type, no state +tracking, and no traits of its own — just a constructor per variant. It is the counterpart to +[`#[derive(ExtractField)]`](./derive_extract_field.md), which takes a variant out; this one puts a variant in. + +## Using it + +The macro is a plain derive on an enum. It takes no arguments and has no helper attributes: + +```rust +use cgp::prelude::*; + +#[derive(FromVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +Each variant's name becomes a [`Symbol!`](../macros/symbol.md) tag and its payload type becomes the +constructor's value type. Generic parameters, lifetimes, and a `where` clause are carried onto every generated +impl. + +### Every variant needs exactly one unnamed payload + +**The derive shares the extractor's one requirement.** A constructor has to take a single value, so a unit +variant, a multi-field tuple variant, and a struct-style variant all fail with +`Expected variant to contain exactly one unnamed field`. There is no per-variant opt-out, so an enum that +mixes shapes cannot take this derive. + +Wrapping the payload in its own struct is the fix, and it is what idiomatic CGP enums do anyway: + +```rust +pub struct Circle { + pub radius: f64, +} + +#[derive(FromVariant)] +pub enum Shape { + Circle(Circle), +} +``` + +If the enum only needs to be *described* rather than constructed, +[`#[derive(HasFields)]`](./derive_has_fields.md) accepts all four variant shapes instead. A variantless enum +is accepted here and simply produces no impls. + +The derive parses an enum, so applying it to a struct fails at parse time. The struct analogue — setting one +field of a value being assembled — is [`#[derive(BuildField)]`](./derive_build_field.md). + +### What it does *not* generate + +Deriving this slice alone gives you construction and nothing else: **no** whole-shape representation and +**no** extractor. Those come from [`#[derive(HasFields)]`](./derive_has_fields.md) and +[`#[derive(ExtractField)]`](./derive_extract_field.md), and the umbrella +[`#[derive(CgpData)]`](./derive_cgp_data.md) includes all three. + +## Examples + +The capability is a function that stays generic over the variant it builds: + +```rust +use cgp::prelude::*; + +#[derive(FromVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn wrap(tag: PhantomData, value: >::Value) -> Shape +where + Shape: FromVariant, +{ + Shape::from_variant(tag, value) +} +``` + +One `wrap` builds either variant, and its payload type is *derived from the tag* rather than fixed: + +```rust +let circle = wrap(PhantomData::, Circle { radius: 2.0 }); +let rect = wrap(PhantomData::, Rectangle { width: 3.0, height: 4.0 }); +``` + +No hand-written function can do that, because `Shape::Circle` and `Shape::Rectangle` are different +expressions taking different types. + +Where this earns its keep in practice is building a value using only the variants an implementation knows +about, then widening it. A routine that only produces two of a large enum's variants declares a small local +enum, constructs into that, and lifts the result into the full type with an upcast: + +```rust +let expr = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); +``` + +The upcast always succeeds, because every variant of the smaller enum has a home in the larger one. That is +the construction-side counterpart of reading a field through a getter: the implementation names only what it +needs, and the widening is checked. Upcasting is documented with the other +[structural casts](../traits/cast.md), and it is built on the same per-variant machinery as this derive. + +## When to reach for it, and when not + +**Derive it when code that does not name a variant has to construct one.** That is the whole test, and it is +a narrower need than deconstruction — most code decides which variant to build at a site that can just name +it. + +- **Reach for it when the variant is chosen by a type parameter.** A routine parameterized over the variant + it produces has no other option. +- **Reach for it to make a smaller enum upcastable into a larger one.** Casting between enums is built on + these constructors, so this derive is what lets an implementation work in a narrow local enum and widen the + result. +- **Do not reach for it for an ordinary constructor call.** `Shape::Circle(circle)` is shorter, clearer, and + generates nothing. This derive adds a *second* way to do the same thing, for callers that cannot use the + first. +- **Do not derive it alone if you also want to take the enum apart**, which is the usual case — reach for + [`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpVariant)]`](./derive_cgp_data.md), which + bundle construction, deconstruction, and the representation. + +Between the constructor and the extractor the split is exactly what the names say: this derive puts a value +into an enum, [`#[derive(ExtractField)]`](./derive_extract_field.md) gets one out, and they are commonly +derived together because a generic pipeline usually does both. + +## Under the hood + +:::note + +### Advanced + +This section shows what the derive generates. You do not need it to use `#[derive(FromVariant)]`, and this is +the shortest expansion in the family — it is worth reading once because the impls appear by name in errors +about generic construction. `cargo cgp expand` prints the same thing for your own code, with the tags +resugared. ::: + +The derive emits **one impl per variant and nothing else** — no companion type, no markers, no state. From: + +```rust +#[derive(FromVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +it produces: + +```rust +impl FromVariant for Shape { + type Value = Circle; + + fn from_variant(_tag: PhantomData, value: Self::Value) -> Self { + Self::Circle(value) + } +} + +impl FromVariant for Shape { + type Value = Rectangle; + + fn from_variant(_tag: PhantomData, value: Self::Value) -> Self { + Self::Rectangle(value) + } +} +``` + +Each body is the plain constructor call. What the impl adds is that the *choice* between them is now a type +argument, and that the payload type is reachable as `>::Value` — which is what lets +a generic signature name it without knowing which variant is in play. + +The `PhantomData` parameter carries no value. It exists so a call site can say which impl it means when +several are in scope, which is why the tag is passed as `PhantomData::` rather than +inferred. + +The [`FromVariant`](../traits/from_variant.md) trait itself is defined in the library; the derive supplies only +these per-variant impls. Each is aimed at the variant it came from, so a conflict with a hand-written impl +underlines that variant rather than the whole `#[derive(FromVariant)]`. + +## Gotchas + +**Every variant must carry exactly one unnamed payload**, the same requirement the extractor has, with no +per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the derive that accepts all four +shapes. + +**The tag has to be written out, not inferred.** `Shape::from_variant(PhantomData::, value)` +needs the turbofish, because nothing in the value determines which variant to build when two variants could +share a payload type. + +**Two variants with the same payload type are still distinguishable, and only by the tag.** That is the reason +for the previous point, and it means a mistyped tag is a missing-impl error rather than a type mismatch. + +**A variant name is a `Symbol!` of its identifier, matched exactly.** `Symbol!("Circle")` and +`Symbol!("circle")` are unrelated types, so a case slip reports as an unsatisfied `FromVariant` bound. + +**A variant named `Value` does not compile.** The generated body writes `Self::Value` to name the payload +type, and a variant of that name makes the path ambiguous — the compiler reports +`ambiguous associated item` with its headline on the derive and a note pointing at the offending variant. `Value` is the only name +this derive reserves; the [extractor](./derive_extract_field.md) reserves several more, so an enum taking +both should avoid all of them. Renaming the variant is the fix. + +**A variantless enum produces nothing**, silently. The derive succeeds and emits no impls, which is correct +and, as with the other empty shapes, means a mistake shows up later rather than here. + +**It does not accept a struct.** The struct-side analogue is +[`#[derive(BuildField)]`](./derive_build_field.md). + +## Related constructs + +- [`#[derive(ExtractField)]`](./derive_extract_field.md) — the reverse operation, taking a variant out + rather than putting one in; commonly derived alongside this one. +- [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this slice. +- [`#[derive(HasFields)]`](./derive_has_fields.md) — the whole-shape representation, which this derive does + not generate, and the only derive that accepts every variant shape. +- [`#[derive(BuildField)]`](./derive_build_field.md) — the struct analogue: setting one field rather than + choosing one variant. +- [`FromVariant`](../traits/from_variant.md) — the trait this generates impls of. +- [`Symbol!`](../macros/symbol.md) — the tag that names a variant. +- [`CanUpcast`](../traits/cast.md) — widening a smaller enum into a larger one, built on these constructors. +- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain the constructed variants + correspond to. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — construction by name, and building through a + small local enum before widening. + +## Source + +- Entry point: [`derive_from_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_from_variant.rs) +- Codegen: [`cgp_data/derive_from_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_from_variant.rs) +- Trait: [`from_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_variant.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 9c48d108..c9c23185 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -6,12 +6,318 @@ sidebar_label: '#[derive(HasField)]' Per-field accessors keyed by a type-level tag. -:::info +## What it's for -### Not written yet +An implementation written against a **context** — the type the capability runs against, which supplies the +values it needs as its fields — cannot name that context's concrete type. It is generic over it, so +`self.name` is not something it can write. Yet reading a field out of the context is the most common thing +such an implementation does. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[derive(HasField)]` is what closes that gap. It gives each of a struct's fields a *type-level name*, so an +implementation can ask for "a `String` field called `name`" as an ordinary trait bound and receive the field +without knowing what type it came from: + +```rust +Self: HasField +``` + +Any struct that derives `HasField` and happens to have such a field satisfies that bound. Nothing is matched +by string at runtime — [`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler resolves the +lookup during compilation and the read compiles down to a direct field access. + +**You will derive this constantly and almost never name `HasField` by hand.** It is the foundation the +ergonomic surface stands on: an [`#[implicit]`](../attributes/implicit.md) argument, a +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method, and a [`UseField`](../providers/use_field.md) +wiring entry all generate the bound above from a name you already wrote. What you write is the derive on the +struct. + +## Using it + +The macro is a plain derive on a struct. It takes no arguments and has no helper attributes: + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, + pub age: u8, +} +``` + +It accepts any struct shape. What differs between them is only how each field's tag is computed. + +### Named fields + +A named field is keyed by [`Symbol!`](../macros/symbol.md), the type-level string of its identifier. The +struct above gains access keyed by `Symbol!("name")` and `Symbol!("age")`. + +A field written as a [raw identifier](https://doc.rust-lang.org/reference/identifiers.html) is keyed by its +*logical* name, with the `r#` stripped — a field `r#type` is keyed by `Symbol!("type")`, not +`Symbol!("r#type")`. The generated accessor still borrows the real field. + +### Tuple fields + +A tuple field has no name, so it is keyed by [`Index`](../types/index.md), the type-level number of its +position: + +```rust +#[derive(HasField)] +pub struct Rectangle(pub f64, pub f64); +``` + +`Rectangle` gains access keyed by `Index<0>` and `Index<1>`. A tuple field is never keyed by a `Symbol!` of +its position — `Index<0>` and `Symbol!("0")` are different types. + +### Unit structs + +A unit struct has no fields, so there is nothing to key. The derive accepts it and emits nothing at all +rather than reporting an error: + +```rust +#[derive(HasField)] +pub struct App; +``` + +This is worth knowing because it is silent. Deriving `HasField` on a fieldless context is harmless and does +nothing, which is the right outcome — such a context carries choices rather than data — but it also means a +mistake that leaves a struct fieldless produces no complaint here, only an unsatisfied bound later. + +### Generic structs + +Generic parameters, lifetimes, and a `where` clause are all carried onto the generated access, so a generic +struct works with no extra ceremony: + +```rust +#[derive(HasField)] +pub struct Wrapper { + pub value: T, +} +``` + +`Wrapper` gains access keyed by `Symbol!("value")` whose value type is `T`, for every `T`. + +### What it does not accept + +The derive parses its input as a struct, so applying it to an enum or a union fails at parse time. The +whole-shape view of a struct *or* an enum is a different derive, +[`#[derive(HasFields)]`](./derive_has_fields.md) — note the plural — and the two are frequently derived +together. + +## Examples + +An implementation states the field it needs as a bound, and the derive is what lets a concrete context +satisfy it. First the implementation, asking for a `String` field called `name`: + +```rust +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData::)); + } +} +``` + +Then a context that derives the access and chooses that implementation: + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} +``` + +Because `Person` derives `HasField`, it satisfies exactly the bound `GreetHello` requires, so +`person.greet()` compiles and prints the person's name. Remove the `name` field and the wiring stops +compiling — the requirement is checked, not assumed. + +**Written idiomatically, none of that bound is visible.** The same read is an +[`#[implicit]`](../attributes/implicit.md) argument, which looks like an ordinary function parameter: + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } +} +``` + +That version generates the same `HasField` bound and the same field read. The explicit form above is what +you *read* — in generated code, in a compiler error — rather than what you write. + +Field access also passes through smart pointers with no extra derive. `Box` and any newtype that +dereferences to `Person` resolve a field read to the inner struct, so wrapping a context does not break the +implementations that read from it. + +## When to reach for it, and when not + +**Derive it on every context whose fields an implementation reads.** There is little judgement here: the +derive is how a struct's fields become visible to the trait system, it costs one line, and every construct +that reads a field needs it. A context that derives nothing can still be wired and can still implement +consumer traits — it just cannot supply values. + +What *is* a judgement call is how you read the field once the derive is in place, and the ordering is +settled. + +- **Use an [`#[implicit]`](../attributes/implicit.md) argument by default.** It reads a field of the + implementation's own context as a plain parameter, with no trait to declare. This covers the common case, + including a field that several implementations each read. +- **Use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) when the read needs to be a named + capability**, when the field lives on a type other than the context, or when the getter should carry a + type inferred from the field — the three cases an implicit argument cannot reach. +- **Write the `HasField` bound by hand only when neither fits**, which is rare. When you do, remember it is + an ordinary trait bound and can carry `Value = T` to pin the field's type. +- **Reach for [`#[derive(HasFields)]`](./derive_has_fields.md) instead when code must process the whole + shape** rather than one named field — serializing a struct, folding over its fields, building it + generically. The two answer different questions and are often derived together. + +One thing this derive is not: it is **not** what makes a struct an extensible record. It gives indexed +access to fields that already exist. Building a struct up field by field is +[`#[derive(BuildField)]`](./derive_build_field.md), and the umbrella that includes both is +[`#[derive(CgpData)]`](./derive_cgp_data.md). + +## Under the hood + +:::note + +### Advanced + +This section shows what the derive generates. You do not need it to use `#[derive(HasField)]`, but a missing +field is reported against the generated bound with the tag fully expanded, so reading one expansion makes +that error legible. `cargo cgp expand` prints the same thing for your own code, with the tags resugared. ::: + +The derive leaves the struct definition untouched and adds **two impls per field** — a read accessor and a +mutable one. From this input: + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, + pub age: u8, +} +``` + +it produces, for each field, the field's type as the associated `Value` and a body that simply borrows it: + +```rust +impl HasField for Person { + type Value = String; + + fn get_field(&self, key: PhantomData) -> &Self::Value { + &self.name + } +} + +impl HasFieldMut for Person { + fn get_field_mut(&mut self, key: PhantomData) -> &mut Self::Value { + &mut self.name + } +} + +// and the same pair for `age`, with `Value = u8` +``` + +The `PhantomData` parameter carries no value. It exists so a call site can say *which* field it means +when several `HasField` impls are in scope, which is what `PhantomData::` at a call site is +doing. [`HasFieldMut`](../traits/has_field.md) extends `HasField` with `get_field_mut`; it is always +generated alongside the read accessor, whether or not anything uses it. + +A tuple struct produces the same shape with a positional tag: + +```rust +impl HasField> for Rectangle { + type Value = f64; + + fn get_field(&self, key: PhantomData>) -> &Self::Value { + &self.0 + } +} +``` + +A generic struct has its parameters split into impl-position generics, type arguments, and a `where` clause +and threaded onto every impl, so `struct Wrapper { value: T }` yields +`impl HasField for Wrapper` with `Value = T`. A struct lifetime carries through the +same way, and a borrowed field type is kept verbatim as `Value`. + +**The smart-pointer behaviour comes from the library, not the derive.** `HasField` and `HasFieldMut` carry +blanket impls for any type whose [`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) target +implements them, which is what lets `Box` resolve a field read to the inner struct. Those blanket +impls are marked so the compiler does not suggest them in a diagnostic, which keeps a missing-field error +pointed at the struct that lacks the field rather than at the pointer. + +Each generated impl is also aimed at the field it came from, so a compiler error about one field's access — +a conflict with a hand-written impl, or the "but the trait is implemented for" hint inside a missing-field +error — underlines that field rather than the whole `#[derive(HasField)]`. + +## Gotchas + +**A unit struct produces nothing, silently.** There is no field to key, so the derive succeeds and emits no +impls. That is correct, but it means the mistake surfaces later, as an unsatisfied `HasField` bound at a +wiring site rather than as a complaint on the struct. + +**Two spellings of a field name are unrelated types.** `Symbol!("first_name")` and `Symbol!("firstName")` +have nothing to do with each other, and a mismatch is reported as a missing `HasField` bound rather than as +a typo. This is the usual cause of a read that "should" work. + +**A raw-identifier field is tagged without the `r#`.** The tag for `r#type` is `Symbol!("type")`, so +`Symbol!("r#type")` matches nothing. + +**A tuple field is keyed by `Index`, never by a `Symbol!` of the number.** `Index<0>` and `Symbol!("0")` +are different types, and only the first is generated. + +**The mutable accessor is always generated.** There is no way to derive read-only access. If a field must +not be mutated by an implementation, that is a matter of what the implementations declare rather than +something this derive can restrict. + +**It does not accept an enum.** `#[derive(HasField)]` parses a struct. The plural +[`#[derive(HasFields)]`](./derive_has_fields.md) is the one that takes both, and the near-identical names +are easy to confuse. + +## Related constructs + +- [`#[derive(HasFields)]`](./derive_has_fields.md) — the whole-shape counterpart, commonly derived + alongside this one. +- [`HasField`](../traits/has_field.md) — the trait this generates, with `HasFieldMut` and the provider-side + `FieldGetter`. +- [`Symbol!`](../macros/symbol.md) — the tag for a named field. +- [`Index`](../types/index.md) — the tag for a tuple field. +- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to read a field, generating the bound for + you. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — a named accessor over the same access. +- [`UseField`](../providers/use_field.md) — where a field name becomes a wiring decision. +- [`ChainGetters`](../providers/chain_getters.md) — reaching a field on a nested context. +- [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this one. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on the + implementation rather than in the interface. +- [Extensible records](/docs/concepts/extensible-records) — treating a struct as a product of named fields. + +## Source + +- Entry point: [`derive_has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_has_field.rs) +- Codegen: [`cgp_data/derive_has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_field.rs) +- Traits: [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) + and [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 5d0ef368..aa6d23c5 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -6,12 +6,361 @@ sidebar_label: '#[derive(HasFields)]' The whole-struct or whole-enum field-list view. -:::info +## What it's for -### Not written yet +Some code needs one field of a type. Other code needs the *shape* of the type: every field, its name, and +its type, so it can walk them. A serializer, a validator, a builder that merges two structs, a dispatcher +that routes an enum to a handler per variant — none of these can be written against one field at a time, and +none of them can name the concrete type either. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`#[derive(HasFields)]` gives a type that shape as a single associated type. Where +[`#[derive(HasField)]`](./derive_has_field.md) — singular — answers "give me *this* field", +`HasFields` answers "describe *all* of them at once": + +```rust +type Fields = Product![ + Field, + Field, +]; +``` + +That is the whole struct written as a type: a [`Product!`](../macros/product.md) list with one +[`Field`](../types/field.md) entry per field, each pairing a value type with its type-level name. For an +enum it is a [`Sum!`](../macros/sum.md) instead — the same idea for a choice rather than a combination. Code +that is generic over the shape recurses over that list, and everything is resolved during compilation. + +The derive also generates the conversions that move values in and out of the representation, which is what +makes it a two-way door rather than a description. Generic code can take a concrete value apart into its +anonymous shape, work on it, and put a concrete value back together. + +## Using it + +The macro is a plain derive that takes no arguments and has no helper attributes. Unlike its singular +sibling it accepts **both structs and enums**: + +```rust +#[derive(HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} + +#[derive(HasFields)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +For a struct the shape is a product; for an enum it is a sum. Naming follows the same rules everywhere: a +named field or a variant is keyed by [`Symbol!`](../macros/symbol.md), a positional field by +[`Index`](../types/index.md). Applying the derive to anything other than a struct or an enum is a +compile error. + +### Struct shapes + +Every struct shape is accepted, and three of the four are what you would predict from the field tags alone. + +- A **named-field struct** becomes a product of `Field` entries, in declaration order. +- A **multi-field tuple struct** becomes a product keyed by `Index`. +- A **unit struct** becomes the empty product `Nil`. A fieldless struct is a valid, if trivial, record and + round-trips through the representation like any other. +- A **single-field tuple struct** — a newtype — is the special case: its `Fields` is the inner type + *directly*, not wrapped in a one-element product. + +The newtype case is worth pausing on, because it is the one that will surprise you. `struct Wrapper(String)` +has `Fields = String`, not `Product![Field, String>]`. The rationale is that a newtype is a +transparent wrapper and generic code almost always wants to see through it, but the practical effect is that +adding a second field to a newtype changes its `Fields` type in shape rather than in length. + +### Variant shapes + +**This is the one derive in the extensible-data family that places no restriction on an enum's variant +shapes.** The derives that take an enum *apart* — +[`#[derive(ExtractField)]`](./derive_extract_field.md) and +[`#[derive(FromVariant)]`](./derive_from_variant.md), and therefore +[`#[derive(CgpData)]`](./derive_cgp_data.md) — require every variant to carry exactly one unnamed payload, +because each has to name a single type per variant. `HasFields` only *describes* a variant, so it accepts +all four shapes and nests that variant's own fields as a product inside its `Field` entry: + +```rust +#[derive(HasFields)] +pub enum Shape { + Empty, + Circle(u32), + Rectangle(u32, u32), + Triangle { base: u32, height: u32 }, +} +``` + +Each variant maps by the same rules a struct's fields do: + +| Variant | Its entry in the sum | +|---|---| +| `Empty` | `Field` | +| `Circle(u32)` | `Field` | +| `Rectangle(u32, u32)` | `Field, u32>, Field, u32>]>` | +| `Triangle { base, height }` | `Field, Field]>` | + +So a unit variant becomes the empty product, a newtype variant passes its payload straight through — the +same special case as a newtype struct, applied inside a variant — a multi-field tuple variant becomes an +`Index`-keyed product, and a named-field variant becomes a `Symbol!`-keyed one. All four round-trip through +the conversions. + +The consequence is worth stating plainly, because it decides which derive to reach for: **an enum with mixed +variant shapes can have a structural representation but no generic constructor or extractor.** +`#[derive(HasFields)]` succeeds on the enum above; `#[derive(CgpData)]` on the same enum would not. + +### Generic types + +Generic parameters, lifetimes, and a `where` clause are carried onto every generated impl. A borrowed field +type appears verbatim in the shape, and the borrowed view of the shape layers its own borrow on top of it — +a field of type `&'a Name` appears as `&'__a &'a Name` in the borrowed form, where `'__a` is the reserved lifetime the derive introduces. + +## Examples + +Deriving `HasFields` alongside [`HasField`](./derive_has_field.md) is the common pairing, giving one struct +both indexed and structural access: + +```rust +use cgp::prelude::*; + +#[derive(HasField, HasFields)] +pub struct Config { + pub host: String, + pub port: u16, +} +``` + +`Config::Fields` is now `Product![Field, Field]`, and a value +round-trips through it: + +```rust +let config = Config { host: "localhost".to_owned(), port: 8080 }; + +let fields = config.to_fields(); // Config -> the product +let config_again = Config::from_fields(fields); // the product -> Config +``` + +There is a borrowing form too, which is what read-only generic code uses so it does not have to consume the +value: + +```rust +let config = Config { host: "localhost".to_owned(), port: 8080 }; + +let fields_ref = config.to_fields_ref(); // borrows each field in place +``` + +An enum's shape is a sum rather than a product, and the same conversions apply: + +```rust +#[derive(HasFields)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +`Shape::Fields` is `Sum![Field, Field]`. + +What generic code does with this is bound on the shape rather than on the type. An implementation that works +for any record writes `where Self: HasFields` and recurses over `Self::Fields`, so it applies to `Config`, +to `Person`, and to a struct declared in another crate that happens to derive the same thing. + +## When to reach for it, and when not + +**Reach for `#[derive(HasFields)]` when code must process a type's whole shape, and for +[`#[derive(HasField)]`](./derive_has_field.md) when it needs one named field.** That is the whole +distinction, and the two are complementary rather than ranked — most types that need both derive both, in one +`#[derive(...)]`. + +The finer question is whether to derive it on its own or take the umbrella. + +- **Derive `HasFields` alone** when the type only needs to be *described* and converted — a payload being + serialized, a struct being read structurally, an enum whose shape a dispatcher inspects. This is also the + only choice available for an enum with mixed variant shapes. +- **Reach for [`#[derive(CgpData)]`](./derive_cgp_data.md)** when the type also needs to be built up field + by field or taken apart variant by variant, since that derive includes this one plus the incremental + machinery. If you find yourself deriving `HasFields`, `HasField`, and + [`BuildField`](./derive_build_field.md) together, the umbrella is the shorter way to say it. +- **Do not derive it speculatively.** It generates five impls and a representation type per use, and a type + nothing processes structurally gains nothing from having a shape. Deriving `HasField` for value reads is + the far more common need. + +One misreading to head off: **this is not runtime reflection.** A type has a shape only because it opted in +with a derive, there is nothing to query at runtime, and the shape is a type rather than data. What that +buys is that generic code over it is checked when written and costs nothing when run; what it costs is that +a type you do not own and cannot patch has no shape at all. + +## Under the hood + +:::note + +### Advanced + +This section shows what the derive generates. You do not need it to use `#[derive(HasFields)]`, but the +`Fields` type appears verbatim in compiler errors about structural code, so reading one expansion makes +those errors legible. `cargo cgp expand` prints the same thing for your own code, with the tags resugared. ::: + +The derive leaves the type definition untouched and emits **five impls**: the shape, the borrowed shape, and +three conversions. From a named-field struct: + +```rust +#[derive(HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} +``` + +the two shape impls name the product and the same product with each value borrowed: + +```rust +impl HasFields for Person { + type Fields = Product![ + Field, + Field, + ]; +} + +impl HasFieldsRef for Person { + type FieldsRef<'__a> = Product![ + Field, + Field, + ] + where + Self: '__a; +} +``` + +and the three conversions move values between `Person` and that product: + +```rust +impl ToFields for Person { + fn to_fields(self) -> Self::Fields { + Cons(self.name.into(), Cons(self.age.into(), Nil)) + } +} + +impl FromFields for Person { + fn from_fields(Cons(name, Cons(age, Nil)): Self::Fields) -> Self { + Self { name: name.value, age: age.value } + } +} + +impl ToFieldsRef for Person { + fn to_fields_ref<'__a>(&'__a self) -> Self::FieldsRef<'__a> + where + Self: '__a, + { + Cons((&self.name).into(), Cons((&self.age).into(), Nil)) + } +} +``` + +`Product![A, B]` is sugar for `Cons>`, which is why the bodies build a `Cons` chain — the +[type-level spines](../types/type_level_spines.md) page covers that shape, and it is what you will see +printed in an error. + +An enum's shape is the dual: an [`Either`](../types/type_level_spines.md) chain terminated by `Void` rather +than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name: + +```rust +impl HasFields for Shape { + type Fields = Either< + Field, + Either, Void>, + >; +} +``` + +The conversions match each concrete variant onto its arm and back. The four variant shapes described above +all fall out of one rule rather than being special-cased: each variant's own fields go through the same +product construction a struct's fields do, which is why a unit variant lands on `Nil`, a newtype variant on +its payload type, and the two multi-field shapes on `Index`- and `Symbol!`-keyed products. + +The empty shapes come from the same construction. A unit struct's `Fields` is `Nil`: + +```rust +impl HasFields for Unit { + type Fields = Nil; +} +``` + +and a variantless enum's is `Void`, with its borrowed conversions matching the uninhabited value through an +empty `match`. + +Each generated impl is aimed at the type name the user wrote, so a conflict with a hand-written `HasFields` +impl underlines the struct or enum rather than the whole `#[derive(HasFields)]`. + +## Gotchas + +**A newtype's `Fields` is the inner type, not a one-element product.** `struct Wrapper(String)` has +`Fields = String`. Generic code written against `Cons, _>, Nil>` will not match it, and +adding a second field changes the shape rather than lengthening it. + +**A named-field variant is not a newtype variant.** `Circle { radius: f64 }` carries a one-entry product, +while `Circle(Circle)` carries its payload type directly. The two read almost alike and produce different +shapes. + +**Accepting every variant shape is specific to this derive.** An enum with a unit, multi-field, or +struct-style variant takes `#[derive(HasFields)]` and rejects `#[derive(CgpData)]`, +`#[derive(CgpVariant)]`, `#[derive(ExtractField)]`, and `#[derive(FromVariant)]`. If you want the whole +family, wrap each richer payload in its own struct so every variant has a single nameable type. + +**The borrowed shape layers borrows rather than collapsing them.** A field already of type `&'a Name` +appears as `&'__a &'a Name` in the borrowed form, which is correct and occasionally surprising in an error +message. `'__a` is the reserved name the derive introduces so it cannot collide with a lifetime of yours. + +**Field order is declaration order, and it is part of the type.** Two structs with the same field names in +different orders have different `Fields` types. Structural conversions that match on names cope with that; +code written against a literal `Cons` chain does not. + +**Two variant names are reserved, and using one does not compile.** The generated impls write +`Self::Fields` and `Self::FieldsRef`, so an enum with a variant called `Fields` or `FieldsRef` makes the path +ambiguous. The compiler reports `ambiguous associated item` with its headline on the derive, and a note +pointing at the offending variant — so following the note tells you which one to rename. The [extractor](./derive_extract_field.md) and +[constructor](./derive_from_variant.md) derives reserve five more names, so an enum taking the whole family +should avoid all seven. + +**It is a different derive from the singular one.** `#[derive(HasField)]` gives per-field access and takes +only structs; `#[derive(HasFields)]` gives the whole shape and takes structs and enums. The names differ by +one letter and the outputs do not overlap. + +## Related constructs + +- [`#[derive(HasField)]`](./derive_has_field.md) — the singular counterpart, per-field access, commonly + derived alongside this one. +- [`HasFields`](../traits/has_fields.md) — the traits this generates and the conversions between a value + and its shape. +- [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this one plus the + incremental machinery. +- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a struct and an enum + shape are built from. +- [`Field`](../types/field.md) — one entry: a value paired with its type-level name. +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that name an entry. +- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains the + sugar expands to. +- [`AppendProduct`](../traits/product_ops.md) — operations over a shape once you have one. +- [`CanUpcast`](../traits/cast.md) — converting between two types whose shapes overlap. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields, and + what generic code does with one. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum half, and the expression problem it + addresses. + +## Source + +- Entry point: [`derive_has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_has_fields.rs) +- Codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) +- Traits: [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs), + [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs), + and [`from_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_fields.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/tutorials/hello.md b/docs/tutorials/hello.md index 109905ec..bb40c832 100644 --- a/docs/tutorials/hello.md +++ b/docs/tutorials/hello.md @@ -50,7 +50,7 @@ pub struct Person { } ``` -To enable CGP functions to access the fields of a context, we use `#[derive(HasField)]` to derive the necessary CGP traits that power the generic field access machinery. In practice, this means the `greet` function will be able to find the `name` field automatically, without any further wiring on our part. +To enable CGP functions to access the fields of a context, we use [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) to derive the necessary CGP traits that power the generic field access machinery. In practice, this means the `greet` function will be able to find the `name` field automatically, without any further wiring on our part. With the `Person` struct defined, we can call the `greet` method on it with no additional work: @@ -170,7 +170,7 @@ When walking through the desugared Rust code, you might wonder: since `Greet` re The answer is yes for the simplified desugared code shown above. But CGP actually employs a more generalized trait called `HasField` that works universally across all possible structs. This means there is **no need** to specifically generate a `HasName` trait to be used by `Greet`, or to implement it manually for `Person`. -The full explanation of how `HasField` works is beyond the scope of this tutorial. The general idea, however, is that a `HasField` instance is implemented for every field inside a struct that uses `#[derive(HasField)]`. Traits like `Greet` then use this to access a specific field by its field name. In practice, this means that `Greet` and `Person` can be defined in entirely different crates without knowing anything about each other. When they are imported together in a third crate, `Greet` will still be automatically implemented for `Person`. +The full explanation of how `HasField` works is beyond the scope of this tutorial — the [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) reference page covers it in full. The general idea, however, is that a `HasField` instance is implemented for every field inside a struct that uses `#[derive(HasField)]`. Traits like `Greet` then use this to access a specific field by its field name. In practice, this means that `Greet` and `Person` can be defined in entirely different crates without knowing anything about each other. When they are imported together in a third crate, `Greet` will still be automatically implemented for `Person`. ## Conclusion diff --git a/example-code/src/reference/derives/derive_build_field.rs b/example-code/src/reference/derives/derive_build_field.rs new file mode 100644 index 00000000..1fff72ec --- /dev/null +++ b/example-code/src/reference/derives/derive_build_field.rs @@ -0,0 +1,258 @@ +//! Code from `docs/reference/derives/derive_build_field.md` — *`#[derive(BuildField)]`*. +//! +//! The page's *Under the hood* section shows the companion struct and its impls; those are not +//! repeated here, since re-declaring them beside the derive would be a coherence conflict and +//! `cargo cgp expand` is the check on that section. What this file pins is that each of the page's +//! snippets runs, and that the incomplete build it says will not compile does not. + +/// ## What it's for +/// +/// The opening builder chain. The page shows it against `Person`, which it declares under *Using it*. +pub mod what_its_for { + use cgp::prelude::*; + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + pub fn build(first: String, last: String) -> Person { + Person::builder() + .build_field(PhantomData::, first) + .build_field(PhantomData::, last) + .finalize_build() + } + + #[test] + fn test_build() { + assert_eq!( + build("Alice".to_owned(), "Anderson".to_owned()), + Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + } + ); + } +} + +/// The page's central claim, as a rejected snippet: dropping a `build_field` line means +/// `finalize_build` does not resolve, because its impl exists only at the all-present configuration. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[derive(BuildField)] +/// pub struct Person { +/// pub first_name: String, +/// pub last_name: String, +/// } +/// +/// let person: Person = Person::builder() +/// .build_field(PhantomData::, "Alice".to_owned()) +/// .finalize_build(); +/// ``` +pub mod rejected_incomplete_build {} + +/// The page's other rejected case: a field's accessor on the companion is in scope only once that +/// field is present, so reading an unset one does not compile. The error arrives as a type mismatch +/// on the tag rather than as a missing method, because the only applicable `HasField` impl is the one +/// for the field that *is* present. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[derive(BuildField)] +/// pub struct Person { +/// pub first_name: String, +/// pub last_name: String, +/// } +/// +/// let partial = Person::builder() +/// .build_field(PhantomData::, "Alice".to_owned()); +/// +/// let _ = partial.get_field(PhantomData::); +/// ``` +pub mod rejected_read_of_an_unset_field {} + +/// The page's third rejected case: `build_from` walks the *source's* field list, so a source deriving +/// only `BuildField` cannot be merged into anything. The error is an unsatisfied `HasFields` bound on +/// the source type. +/// +/// ```compile_fail +/// use cgp::core::field::impls::CanBuildFrom; +/// use cgp::prelude::*; +/// +/// #[derive(BuildField)] +/// pub struct FooBar { +/// pub foo: u64, +/// pub bar: String, +/// } +/// +/// #[derive(BuildField)] +/// pub struct FooBarBaz { +/// pub foo: u64, +/// pub bar: String, +/// pub baz: bool, +/// } +/// +/// let source = FooBar { foo: 1, bar: "bar".to_owned() }; +/// +/// let _ = FooBarBaz::builder() +/// .build_from(source) +/// .build_field(PhantomData::, true) +/// .finalize_build(); +/// ``` +pub mod rejected_build_from_without_has_fields {} + +/// ## Using it +/// +/// The shapes the page lists: a named-field struct, a tuple struct keyed by position, and the +/// fieldless struct whose `builder()` is immediately finalizable. +pub mod using_it { + use cgp::prelude::*; + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct Pair(pub u32, pub u32); + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct NoConfig {} + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct Generic { + pub value: T, + } + + #[test] + fn test_a_tuple_struct_is_keyed_by_position() { + let pair: Pair = Pair::builder() + .build_field(PhantomData::>, 3) + .build_field(PhantomData::>, 4) + .finalize_build(); + + assert_eq!(pair, Pair(3, 4)); + } + + #[test] + fn test_a_fieldless_struct_finalizes_immediately() { + let config: NoConfig = NoConfig::builder().finalize_build(); + + assert_eq!(config, NoConfig {}); + } + + #[test] + fn test_generics_are_carried_onto_the_companion() { + let generic: Generic = Generic::builder() + .build_field(PhantomData::, 42) + .finalize_build(); + + assert_eq!(generic, Generic { value: 42 }); + } +} + +/// ## Examples +/// +/// The three snippets the page shows in order: extending one record into a larger one, reading a set +/// field back out mid-build, and taking a field out and putting it back. +pub mod examples { + use cgp::core::field::impls::CanBuildFrom; + use cgp::prelude::*; + + // `build_from` recurses over the *source's* field list, so the source needs `HasFields` as + // well as the builder. The page says so under *The three ways to fill a field*. + #[derive(HasFields, BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + pub fn extend(foo_bar: FooBar) -> FooBarBaz { + FooBarBaz::builder() + .build_from(foo_bar) + .build_field(PhantomData::, true) + .finalize_build() + } + + #[test] + fn test_extend() { + let foo_bar = FooBar { + foo: 1, + bar: "bar".to_owned(), + }; + + assert_eq!( + extend(foo_bar), + FooBarBaz { + foo: 1, + bar: "bar".to_owned(), + baz: true, + } + ); + } + + #[test] + fn test_read_a_set_field_mid_build() { + let partial = + Person::builder().build_field(PhantomData::, "Alice".to_owned()); + + assert_eq!( + partial.get_field(PhantomData::), + "Alice" + ); + } + + #[test] + fn test_take_a_field_out_and_put_it_back() { + // `TakeField` is the one trait in the family that is not in the prelude. + use cgp::core::field::traits::TakeField; + + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + }; + + let builder = person.into_builder(); + + let (first_name, remainder) = builder.take_field(PhantomData::); + assert_eq!(first_name, "Alice"); + + let person = remainder + .build_field(PhantomData::, first_name) + .finalize_build(); + + assert_eq!( + person, + Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + } + ); + } +} diff --git a/example-code/src/reference/derives/derive_cgp_data.rs b/example-code/src/reference/derives/derive_cgp_data.rs new file mode 100644 index 00000000..37fb2789 --- /dev/null +++ b/example-code/src/reference/derives/derive_cgp_data.rs @@ -0,0 +1,219 @@ +//! Code from `docs/reference/derives/derive_cgp_data.md` — *`#[derive(CgpData)]`, `CgpRecord` & +//! `CgpVariant`*. +//! +//! The page's *Under the hood* section shows the impls and companion types the derives generate; +//! those are not repeated here, since re-declaring them beside the derive would be a coherence +//! conflict and `cargo cgp expand` is the check on that section. What this file pins is the accepted +//! and rejected shapes, and that the two worked examples run. + +/// ## Using it +/// +/// The two inputs the page opens on, the shape-specific faces, and the shapes the page says are +/// accepted. The one it says is rejected is a doctest in the module below this one. +pub mod using_it { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq)] + pub struct Circle { + pub radius: u32, + } + + #[derive(Debug, Eq, PartialEq)] + pub struct Rectangle { + pub width: u32, + pub height: u32, + } + + #[derive(CgpData)] + #[derive(Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(CgpData)] + #[derive(Debug, Eq, PartialEq)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + /// The shape-specific faces, which the page says emit what the umbrella emits. + #[derive(CgpRecord)] + #[derive(Debug, Eq, PartialEq)] + pub struct RecordFace { + pub value: u32, + } + + #[derive(CgpVariant)] + #[derive(Debug, Eq, PartialEq)] + pub enum VariantFace { + One(Circle), + } + + /// The degenerate struct shape: a parameterless companion, so `builder()` finalizes at once. + #[derive(CgpData)] + #[derive(Debug, Eq, PartialEq)] + pub struct NoConfig {} + + /// A tuple struct, whose builder steps are keyed by position rather than by name. + #[derive(CgpData)] + #[derive(Debug, Eq, PartialEq)] + pub struct Pair(pub u32, pub u32); + + #[test] + fn test_the_degenerate_record_finalizes_immediately() { + let config: NoConfig = NoConfig::builder().finalize_build(); + + assert_eq!(config, NoConfig {}); + } + + #[test] + fn test_a_tuple_records_builder_is_keyed_by_position() { + let pair: Pair = Pair::builder() + .build_field(PhantomData::>, 3) + .build_field(PhantomData::>, 4) + .finalize_build(); + + assert_eq!(pair, Pair(3, 4)); + } + + #[test] + fn test_the_record_face_delivers_all_three_slices() { + let record: RecordFace = RecordFace::builder() + .build_field(PhantomData::, 7) + .finalize_build(); + + // The getter slice. + assert_eq!(*record.get_field(PhantomData::), 7); + + // The representation slice. + assert_eq!( + RecordFace::from_fields(record.to_fields()), + RecordFace { value: 7 } + ); + } + + #[test] + fn test_the_variant_face_constructs_by_tag() { + let variant = + VariantFace::from_variant(PhantomData::, Circle { radius: 2 }); + + assert_eq!(variant, VariantFace::One(Circle { radius: 2 })); + } +} + +/// The page's rejected snippet: a struct-style variant has no single payload type, so the derive +/// refuses it. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[derive(CgpData)] +/// pub enum Shape { +/// Circle { radius: f64 }, +/// } +/// ``` +pub mod rejected_struct_style_variant {} + +/// ## Examples +/// +/// The record half: `promote`, which merges one record into another's builder. +pub mod examples_record { + use cgp::core::field::impls::CanBuildFrom; + use cgp::prelude::*; + + #[derive(CgpData)] + #[derive(Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(CgpData)] + #[derive(Debug, Eq, PartialEq)] + pub struct Employee { + pub employee_id: u64, + pub first_name: String, + pub last_name: String, + } + + pub fn promote(person: Person, id: u64) -> Employee { + Employee::builder() + .build_from(person) + .build_field(PhantomData::, id) + .finalize_build() + } + + #[test] + fn test_promote() { + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + }; + + assert_eq!( + promote(person, 1), + Employee { + employee_id: 1, + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + } + ); + } +} + +/// ## Examples +/// +/// The variant half: `area`, an extraction chain closed with no wildcard arm. The page names `Circle` +/// and `Rectangle` without declaring them, so they are declared here. +pub mod examples_variant { + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::prelude::*; + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn area(shape: Shape) -> f64 { + match shape + .to_extractor() + .extract_field(PhantomData::) + { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width * rect.height + } + } + } + + #[test] + fn test_area_of_each_variant() { + assert_eq!( + area(Shape::Circle(Circle { radius: 1.0 })), + core::f64::consts::PI + ); + + assert_eq!( + area(Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + })), + 12.0 + ); + } +} diff --git a/example-code/src/reference/derives/derive_extract_field.rs b/example-code/src/reference/derives/derive_extract_field.rs new file mode 100644 index 00000000..4fd4ccfd --- /dev/null +++ b/example-code/src/reference/derives/derive_extract_field.rs @@ -0,0 +1,228 @@ +//! Code from `docs/reference/derives/derive_extract_field.md` — *`#[derive(ExtractField)]`*. +//! +//! The page's *Under the hood* section shows the two companion enums and their impls; those are not +//! repeated here, since re-declaring them beside the derive would be a coherence conflict and +//! `cargo cgp expand` is the check on that section. What this file pins is the accepted and rejected +//! shapes, the three extractors, and the exhaustiveness claim in both directions. + +/// ## What it's for +/// +/// The opening extraction, and the payload types the page names without declaring. +pub mod what_its_for { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq)] + pub struct Circle { + pub radius: u32, + } + + #[derive(Debug, Eq, PartialEq)] + pub struct Rectangle { + pub width: u32, + pub height: u32, + } + + #[derive(ExtractField)] + #[derive(Debug, Eq, PartialEq)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + #[test] + fn test_one_attempt_yields_or_narrows() { + // A match: the payload comes out. + let hit = Shape::Circle(Circle { radius: 2 }) + .to_extractor() + .extract_field(PhantomData::); + assert!(hit.is_ok()); + + // A miss: the remainder comes back, and `Circle` is now ruled out in its type. + let miss = Shape::Rectangle(Rectangle { + width: 3, + height: 4, + }) + .to_extractor() + .extract_field(PhantomData::); + assert!(miss.is_err()); + } +} + +/// ## Using it +/// +/// The accepted enum, the payload-struct rewrite the page recommends — including for a case that +/// carries nothing — and the variantless enum the page says degenerates. +pub mod using_it { + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + /// The page's point that even a fieldless case needs a payload struct, since a bare `Empty` is a + /// unit variant and would be refused. + #[derive(Debug, PartialEq)] + pub struct Empty; + + #[derive(ExtractField)] + #[derive(Debug, PartialEq)] + pub enum Shape { + Circle(Circle), + Empty(Empty), + } + + #[derive(ExtractField)] + pub enum Never {} + + #[derive(ExtractField)] + pub enum Generic { + Item(T), + } + + #[test] + fn test_a_payload_struct_stands_in_for_a_unit_variant() { + // A remainder carries none of the enum's attributes, so it is neither `Debug` nor + // `PartialEq` — the result is unwrapped rather than compared whole. + let extracted = Shape::Empty(Empty) + .to_extractor() + .extract_field(PhantomData::) + .ok(); + + assert_eq!(extracted, Some(Empty)); + } + + #[test] + fn test_generics_are_carried_onto_the_companions() { + let extracted = Generic::Item(42_u32) + .to_extractor() + .extract_field(PhantomData::); + + assert_eq!(extracted.ok(), Some(42)); + } +} + +/// The page's rejected snippet: a struct-style variant and a unit variant both fail, because +/// extraction has to name one payload type per variant. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[derive(ExtractField)] +/// pub enum Shape { +/// Circle { radius: f64 }, +/// Empty, +/// } +/// ``` +pub mod rejected_variant_shapes {} + +/// ## Examples +/// +/// The three snippets the page shows: the owned chain closed with `finalize_extract_result`, the +/// borrowed read, and the mutable modification. +pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; + 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)] + #[derive(Debug, PartialEq)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn area(shape: Shape) -> f64 { + match shape + .to_extractor() + .extract_field(PhantomData::) + { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width * rect.height + } + } + } + + #[test] + fn test_area_reaches_both_variants() { + assert_eq!( + area(Shape::Circle(Circle { radius: 1.0 })), + core::f64::consts::PI + ); + + assert_eq!( + area(Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + })), + 12.0 + ); + } + + #[test] + fn test_a_borrowed_read_leaves_the_value_intact() { + let shape = Shape::Circle(Circle { radius: 2.0 }); + + let radius = shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok(); + + assert_eq!(radius, Some(2.0)); + assert_eq!(shape, Shape::Circle(Circle { radius: 2.0 })); + } + + #[test] + fn test_a_mutable_extraction_modifies_in_place() { + let mut shape = Shape::Circle(Circle { radius: 2.0 }); + + if let Ok(circle) = shape + .extractor_mut() + .extract_field(PhantomData::) + { + circle.radius = 5.0; + } + + assert_eq!(shape, Shape::Circle(Circle { radius: 5.0 })); + } +} + +/// The page's claim that finalizing before every variant has been tried does not compile, because the +/// remainder is still inhabited. +/// +/// ```compile_fail +/// use cgp::core::field::traits::FinalizeExtractResult; +/// use cgp::prelude::*; +/// +/// pub struct Circle { pub radius: f64 } +/// pub struct Rectangle { pub width: f64, pub height: f64 } +/// +/// #[derive(ExtractField)] +/// pub enum Shape { +/// Circle(Circle), +/// Rectangle(Rectangle), +/// } +/// +/// let shape = Shape::Circle(Circle { radius: 1.0 }); +/// +/// let _ = shape +/// .to_extractor() +/// .extract_field(PhantomData::) +/// .finalize_extract_result(); +/// ``` +pub mod rejected_premature_finalize {} diff --git a/example-code/src/reference/derives/derive_from_variant.rs b/example-code/src/reference/derives/derive_from_variant.rs new file mode 100644 index 00000000..62100666 --- /dev/null +++ b/example-code/src/reference/derives/derive_from_variant.rs @@ -0,0 +1,177 @@ +//! Code from `docs/reference/derives/derive_from_variant.md` — *`#[derive(FromVariant)]`*. +//! +//! The page's *Under the hood* section shows the per-variant impls; those are not repeated here, since +//! re-declaring them beside the derive would be a coherence conflict and `cargo cgp expand` is the +//! check on that section. What this file pins is that the tag-generic constructor works, and the two +//! shapes the page says are rejected. + +/// ## What it's for +/// +/// The opening claim: `from_variant` with a tag is the same construction as naming the variant. +pub mod what_its_for { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq)] + pub struct Circle { + pub radius: u32, + } + + #[derive(Debug, Eq, PartialEq)] + pub struct Rectangle { + pub width: u32, + pub height: u32, + } + + #[derive(FromVariant)] + #[derive(Debug, Eq, PartialEq)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + #[test] + fn test_the_tagged_call_equals_the_named_one() { + let by_tag = Shape::from_variant(PhantomData::, Circle { radius: 2 }); + + assert_eq!(by_tag, Shape::Circle(Circle { radius: 2 })); + } +} + +/// ## Using it +/// +/// The accepted enum, a generic one, and the variantless enum the page says produces no impls. +pub mod using_it { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq)] + pub struct Circle { + pub radius: u32, + } + + #[derive(FromVariant)] + #[derive(Debug, Eq, PartialEq)] + pub enum Shape { + Circle(Circle), + } + + #[derive(FromVariant)] + #[derive(Debug, Eq, PartialEq)] + pub enum Generic { + Item(T), + } + + #[derive(FromVariant)] + pub enum Never {} + + #[test] + fn test_generics_are_carried_onto_every_impl() { + let value = Generic::from_variant(PhantomData::, 42_u32); + + assert_eq!(value, Generic::Item(42)); + } +} + +/// The page's rejected snippet: a struct-style variant has no single payload type for the constructor +/// to take. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[derive(FromVariant)] +/// pub enum Shape { +/// Circle { radius: f64 }, +/// } +/// ``` +pub mod rejected_struct_style_variant {} + +/// ## Examples +/// +/// The `wrap` function the page shows: one function that builds either variant, staying generic over +/// the tag and naming its payload type through the trait. +pub mod examples { + 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(FromVariant)] + #[derive(Debug, PartialEq)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn wrap(tag: PhantomData, value: >::Value) -> Shape + where + Shape: FromVariant, + { + Shape::from_variant(tag, value) + } + + #[test] + fn test_one_function_builds_either_variant() { + let circle = wrap(PhantomData::, Circle { radius: 2.0 }); + assert_eq!(circle, Shape::Circle(Circle { radius: 2.0 })); + + let rect = wrap( + PhantomData::, + Rectangle { + width: 3.0, + height: 4.0, + }, + ); + assert_eq!( + rect, + Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }) + ); + } +} + +/// ## Examples +/// +/// The upcast the page closes on: construct into a small local enum, then widen. The page shows one +/// line from the expression-interpreter scenario, so the surrounding types are declared here. +pub mod examples_upcast { + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct Ident(pub String); + + #[derive(Debug, PartialEq)] + pub struct Literal(pub u64); + + /// The narrow enum an implementation constructs into. + #[derive(CgpData)] + #[derive(Debug, PartialEq)] + pub enum LispSubExpr { + Ident(Ident), + } + + /// The full enum it is widened into. + #[derive(CgpData)] + #[derive(Debug, PartialEq)] + pub enum LispExpr { + Ident(Ident), + Literal(Literal), + } + + #[test] + fn test_upcast_from_the_narrow_enum() { + use cgp::core::field::impls::CanUpcast; + + let ident = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); + + assert_eq!(ident, LispExpr::Ident(Ident("+".to_owned()))); + } +} diff --git a/example-code/src/reference/derives/derive_has_field.rs b/example-code/src/reference/derives/derive_has_field.rs new file mode 100644 index 00000000..23809e6f --- /dev/null +++ b/example-code/src/reference/derives/derive_has_field.rs @@ -0,0 +1,192 @@ +//! Code from `docs/reference/derives/derive_has_field.md` — *`#[derive(HasField)]`*. +//! +//! The page's *Under the hood* section shows the impls the derive generates. Those are not repeated +//! here: re-declaring them beside the derive that emits them would be a coherence conflict, so the +//! only honest check on that section is `cargo cgp expand`. What this file pins is every input shape +//! the page says is accepted, and that the generated access actually resolves. + +/// ## What it's for +/// +/// The page opens on the bound an implementation writes. The component and the context are shown +/// further down under *Examples*; they are declared here so the opening bound has something to hold. +pub mod what_its_for { + use cgp::prelude::*; + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + // The bound the page shows, exercised as a standalone function rather than left as prose. + pub fn read_name(context: &Context) -> &String + where + Context: HasField, + { + context.get_field(PhantomData::) + } + + #[test] + fn test_bound_resolves_for_a_deriving_struct() { + let person = Person { + name: "Alice".to_owned(), + }; + + assert_eq!(read_name(&person), "Alice"); + } +} + +/// ## Using it +/// +/// The four struct shapes the page lists, in the order it lists them: named fields, a raw-identifier +/// field, tuple fields, a unit struct, and a generic struct. The unit struct is the one whose whole +/// point is that it compiles and emits nothing. +pub mod using_it { + use cgp::prelude::*; + + #[derive(HasField)] + pub struct Person { + pub name: String, + pub age: u8, + } + + #[derive(HasField)] + pub struct Entry { + pub r#type: String, + } + + #[derive(HasField)] + pub struct Rectangle(pub f64, pub f64); + + #[derive(HasField)] + pub struct App; + + #[derive(HasField)] + pub struct Wrapper { + pub value: T, + } + + #[test] + fn test_named_fields_are_keyed_by_symbol() { + let person = Person { + name: "Alice".to_owned(), + age: 30, + }; + + assert_eq!(person.get_field(PhantomData::), "Alice"); + assert_eq!(*person.get_field(PhantomData::), 30); + } + + #[test] + fn test_a_raw_identifier_field_drops_the_prefix() { + let entry = Entry { + r#type: "text".to_owned(), + }; + + // `Symbol!("type")`, not `Symbol!("r#type")` — the page's rule. + assert_eq!(entry.get_field(PhantomData::), "text"); + } + + #[test] + fn test_tuple_fields_are_keyed_by_index() { + let rectangle = Rectangle(3.0, 4.0); + + assert_eq!(*rectangle.get_field(PhantomData::>), 3.0); + assert_eq!(*rectangle.get_field(PhantomData::>), 4.0); + } + + #[test] + fn test_generic_parameters_are_carried_through() { + let wrapper = Wrapper { value: 42_u32 }; + + assert_eq!(*wrapper.get_field(PhantomData::), 42); + } +} + +/// ## Examples +/// +/// Both forms the page shows of one provider: the explicit `HasField` bound, and the `#[implicit]` +/// argument that generates the same bound. Two components are declared rather than one, since the +/// page shows the second form as a replacement for the first and one context cannot wire both. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); + } + + #[cgp_impl(new GreetHello)] + impl Greeter + where + Self: HasField, + { + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData::)); + } + } + + #[cgp_impl(new GreetHelloImplicit)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + /// The `#[implicit]` form, wired on its own context so the two providers do not collide. + #[derive(HasField)] + pub struct ImplicitPerson { + pub name: String, + } + + delegate_components! { + ImplicitPerson { + GreeterComponent: GreetHelloImplicit, + } + } + + check_components! { + ImplicitPerson { + GreeterComponent, + } + } + + #[test] + fn test_both_forms_greet() { + Person { + name: "World".to_owned(), + } + .greet(); + + ImplicitPerson { + name: "World".to_owned(), + } + .greet(); + } + + /// The page's claim that field access passes through a smart pointer with no extra derive. + #[test] + fn test_access_through_a_box() { + let boxed: Box = Box::new(Person { + name: "Alice".to_owned(), + }); + + assert_eq!(boxed.get_field(PhantomData::), "Alice"); + } +} diff --git a/example-code/src/reference/derives/derive_has_fields.rs b/example-code/src/reference/derives/derive_has_fields.rs new file mode 100644 index 00000000..462286c9 --- /dev/null +++ b/example-code/src/reference/derives/derive_has_fields.rs @@ -0,0 +1,218 @@ +//! Code from `docs/reference/derives/derive_has_fields.md` — *`#[derive(HasFields)]`*. +//! +//! The page's *Under the hood* section shows the five impls the derive generates; those are not +//! repeated here, since re-declaring them beside the derive would be a coherence conflict and +//! `cargo cgp expand` is the check on that section. What this file pins is the `Fields` type the page +//! claims for each input shape, asserted by round-tripping a value through it. + +/// ## What it's for +/// +/// The `Fields` type the page opens on, checked by naming it explicitly. +pub mod what_its_for { + use cgp::prelude::*; + + #[derive(Clone, Debug, Eq, PartialEq)] + #[derive(HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + // The page writes this type out; asserting the equality is what checks it. + pub type ExpectedFields = + Product![Field, Field]; + + pub fn assert_fields(fields: ::Fields) -> ExpectedFields { + fields + } + + #[test] + fn test_round_trip() { + let person1 = Person { + name: "Alice".to_owned(), + age: 30, + }; + + let fields = person1.clone().to_fields(); + let person2 = Person::from_fields(fields); + + assert_eq!(person1, person2); + } +} + +/// ## Using it +/// +/// Every struct and enum shape the page lists. The four struct shapes come first, then the four +/// variant shapes in the single enum the page uses for them. +pub mod using_it { + use cgp::prelude::*; + + #[derive(Clone, Debug, Eq, PartialEq)] + #[derive(HasFields)] + pub struct Named { + pub name: String, + pub age: u8, + } + + #[derive(Clone, Debug, Eq, PartialEq)] + #[derive(HasFields)] + pub struct Tuple(pub u32, pub u32); + + #[derive(Clone, Debug, Eq, PartialEq)] + #[derive(HasFields)] + pub struct Unit; + + /// The newtype special case: `Fields` is the inner type directly. + #[derive(Clone, Debug, Eq, PartialEq)] + #[derive(HasFields)] + pub struct Newtype(pub String); + + #[derive(Clone, Debug, Eq, PartialEq)] + #[derive(HasFields)] + pub struct Generic { + pub value: T, + } + + /// The four variant shapes, all accepted by this derive and by no other in the family. + #[derive(Clone, Debug, Eq, PartialEq)] + #[derive(HasFields)] + pub enum Shape { + Empty, + Circle(u32), + Rectangle(u32, u32), + Triangle { base: u32, height: u32 }, + } + + // The `Fields` type the page's table claims for each variant, written out so the compiler checks + // the mapping rather than the reader checking it by eye. + pub type ExpectedShapeFields = Sum![ + Field, + Field, + Field, u32>, Field, u32>]>, + Field< + Symbol!("Triangle"), + Product![Field, Field], + >, + ]; + + pub fn assert_shape_fields(fields: ::Fields) -> ExpectedShapeFields { + fields + } + + #[test] + fn test_a_unit_struct_has_the_empty_product() { + let unit1 = Unit; + + let fields = unit1.clone().to_fields(); + assert_eq!(fields, Nil); + + assert_eq!(Unit::from_fields(fields), unit1); + } + + #[test] + fn test_a_newtype_passes_its_inner_type_through() { + let newtype1 = Newtype("Alice".to_owned()); + + // Not a one-element product: the field list *is* the `String`. + let fields: String = newtype1.clone().to_fields(); + assert_eq!(fields, "Alice"); + + assert_eq!(Newtype::from_fields(fields), newtype1); + } + + #[test] + fn test_every_struct_shape_round_trips() { + let named = Named { + name: "Alice".to_owned(), + age: 30, + }; + assert_eq!(Named::from_fields(named.clone().to_fields()), named); + + let tuple = Tuple(3, 4); + assert_eq!(Tuple::from_fields(tuple.clone().to_fields()), tuple); + + let generic = Generic { value: 42_u32 }; + assert_eq!(Generic::from_fields(generic.clone().to_fields()), generic); + } + + #[test] + fn test_every_variant_shape_round_trips() { + for shape in [ + Shape::Empty, + Shape::Circle(2), + Shape::Rectangle(3, 4), + Shape::Triangle { + base: 6, + height: 5, + }, + ] { + assert_eq!(Shape::from_fields(shape.clone().to_fields()), shape); + } + } +} + +/// ## Examples +/// +/// The `Config` pairing the page shows, the borrowed form, and the enum whose shape is a sum. +pub mod examples { + use cgp::prelude::*; + + #[derive(Clone, Debug, Eq, PartialEq)] + #[derive(HasField, HasFields)] + pub struct Config { + pub host: String, + pub port: u16, + } + + /// The payload types the page names without declaring. + #[derive(Clone, Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + #[derive(Clone, Debug, PartialEq)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(Clone, Debug, PartialEq)] + #[derive(HasFields)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + /// The page's closing claim: generic code bounds on the shape rather than on the type, so one + /// function applies to any record that derives it. The page does not show a recursion, so this + /// stops at naming the shape. + pub fn shape_of(value: T) -> T::Fields + where + T: HasFields + ToFields, + { + value.to_fields() + } + + #[test] + fn test_the_page_snippets() { + let config = Config { + host: "localhost".to_owned(), + port: 8080, + }; + + let fields = config.clone().to_fields(); + let config_again = Config::from_fields(fields); + assert_eq!(config, config_again); + + // The borrowing form, which reads without consuming. + let fields_ref = config.to_fields_ref(); + assert_eq!(fields_ref.0.value, &"localhost".to_owned()); + } + + #[test] + fn test_an_enums_shape_is_a_sum() { + let shape = Shape::Circle(Circle { radius: 2.0 }); + + assert_eq!(Shape::from_fields(shape.clone().to_fields()), shape); + } +} diff --git a/example-code/src/reference/derives/mod.rs b/example-code/src/reference/derives/mod.rs new file mode 100644 index 00000000..848651ac --- /dev/null +++ b/example-code/src/reference/derives/mod.rs @@ -0,0 +1,8 @@ +//! Code from the pages under `docs/reference/derives/`. + +pub mod derive_build_field; +pub mod derive_cgp_data; +pub mod derive_extract_field; +pub mod derive_from_variant; +pub mod derive_has_field; +pub mod derive_has_fields; diff --git a/example-code/src/reference/mod.rs b/example-code/src/reference/mod.rs index 90784c4a..90c90522 100644 --- a/example-code/src/reference/mod.rs +++ b/example-code/src/reference/mod.rs @@ -3,5 +3,6 @@ //! The section is filled in lazily, so the modules here are the pages someone has written, revised, //! or reviewed rather than the section's full inventory. +pub mod derives; pub mod errors; pub mod macros; From a4eb403278c1d8c4613a7f6aaee5359e28ba03ea Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 22:25:38 +0200 Subject: [PATCH 029/516] Write the traits reference pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fill in the fifteen pages under `docs/reference/traits/`, completing the fourth group of the construct reference and taking the section to forty-eight of seventy-five. Each follows the guide's six-section layered descent in the project voice, with `context` glossed on first use where the word appears and no grammar section, since a trait has no custom syntax. The group divides into the three wiring traits, the two field-access pages, the record and variant families, the type-level machinery, and the four that stand alone. Because these are traits a reader bounds against rather than macros they invoke, each page's *Using it* section answers a question the derives pages did not have to: where the trait is imported from. That turned out to be the group's most load-bearing fact — thirty of the sixty-three traits and markers covered here are not in the prelude, and four internal documents had examples missing exactly those imports. Each page now states the path, and the pages for the harder cases say plainly what is *not* reachable: `StaticFormat` cannot be named through the `cgp` crate at all, and `IsOwned` is a marker nothing in CGP selects. Two corrections reach the prose rather than an import line. The `DefaultImpls` traits put the instance type in the `Self` position and the component in a leading parameter, against what their parameter names suggest, so that page leads with the rule the attribute follows instead of the trait's signature. And `ExtractField`'s page makes the `IsNothing`-versus-`IsVoid` distinction explicit, because a record's absent field is inhabited while a variant's ruled-out one is not — which is the whole reason an extractor can discharge its remainder with an empty `match` and a builder needs an all-present impl. Four pages carry a compiled counterpart in `example-code`, covering the ones that show code a compiler can check; a page that only displays a trait definition gets none, since re-declaring the trait would check nothing about CGP. Writing them caught the `Path!` syntax error the internal document had. Two rejected cases the `HasBuilder` page states are `compile_fail` doctests rather than claims. Also link `IsProviderFor` and `DelegateComponent` from the `expand` tooling page, which mentioned both in prose with no target, and correct the reference index, which still said most pages behind it were placeholders. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_018n2krDG9WF1HD9aA1aMASX --- docs/cargo-cgp/expand.md | 6 +- docs/reference/index.md | 5 +- docs/reference/traits/can_use_component.md | 223 +++++++++++- docs/reference/traits/cast.md | 245 ++++++++++++- docs/reference/traits/default_namespace.md | 284 ++++++++++++++- docs/reference/traits/delegate_component.md | 263 +++++++++++++- docs/reference/traits/extract_field.md | 292 +++++++++++++++- docs/reference/traits/from_variant.md | 210 +++++++++++- docs/reference/traits/has_builder.md | 324 +++++++++++++++++- docs/reference/traits/has_field.md | 292 +++++++++++++++- docs/reference/traits/has_fields.md | 286 +++++++++++++++- docs/reference/traits/is_provider_for.md | 251 +++++++++++++- docs/reference/traits/map_type.md | 245 ++++++++++++- docs/reference/traits/monad.md | 209 ++++++++++- docs/reference/traits/optional_fields.md | 293 +++++++++++++++- docs/reference/traits/product_ops.md | 259 +++++++++++++- docs/reference/traits/static_format.md | 212 +++++++++++- example-code/src/reference/mod.rs | 1 + example-code/src/reference/traits/cast.rs | 106 ++++++ .../src/reference/traits/has_builder.rs | 134 ++++++++ example-code/src/reference/traits/mod.rs | 12 + .../src/reference/traits/product_ops.rs | 88 +++++ .../src/reference/traits/static_format.rs | 44 +++ 23 files changed, 4205 insertions(+), 79 deletions(-) create mode 100644 example-code/src/reference/traits/cast.rs create mode 100644 example-code/src/reference/traits/has_builder.rs create mode 100644 example-code/src/reference/traits/mod.rs create mode 100644 example-code/src/reference/traits/product_ops.rs create mode 100644 example-code/src/reference/traits/static_format.rs diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index e7258ea5..b29be5de 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -167,9 +167,11 @@ useful mid-debugging: it works on a crate that does not type-check. For the wiri Four situations, all of them cases where the answer is in the generated code rather than in a message: -- **A diagnostic names a type you did not write** — `IsProviderFor`, a `PathCons` key, a `__Context__` +- **A diagnostic names a type you did not write** — + [`IsProviderFor`](/docs/reference/traits/is_provider_for), a `PathCons` key, a `__Context__` parameter — and you want to see the impl it came from. -- **A wiring table does not resolve** and you want its real `DelegateComponent` keys and values rather +- **A wiring table does not resolve** and you want its real + [`DelegateComponent`](/docs/reference/traits/delegate_component) keys and values rather than inferring them from the table's syntax. - **You are unsure what a construct emits** — the exact `where` clauses of a provider impl, whether a getter's blanket impl needs the field you think it does. diff --git a/docs/reference/index.md b/docs/reference/index.md index db23c753..d6b7230f 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -20,8 +20,9 @@ its own. ### Still being written The construct list below is complete — every construct the `cgp` crate exports has a page, or a named -place on a page it shares — so nothing is missing from this index. Most of the pages behind it are -placeholders for now, and each one says so when you open it. +place on a page it shares — so nothing is missing from this index. The macros, attributes, derives, and +traits are written; the components, providers, and type-level pages are still placeholders, and each one +says so when you open it. ::: diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/can_use_component.md index 42690116..0b203c46 100644 --- a/docs/reference/traits/can_use_component.md +++ b/docs/reference/traits/can_use_component.md @@ -6,12 +6,225 @@ sidebar_label: 'CanUseComponent' The context-side check that a context both wires a component and satisfies its provider. -:::info +## What it's for -### Not written yet +CGP's wiring is lazy: writing a wiring line does not check that the chosen implementation's own requirements +are met. That check happens the first time the capability is actually called, which is usually somewhere far +from the wiring and produces a bad error when it fails. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`CanUseComponent` is the bound that forces the check early, and it exists because the obvious way of asking +does not work. Asking "does this **context** — the type the capability runs against — implement the consumer +trait?" makes the compiler report the outermost unmet bound, usually a bare "the provider does not implement +the provider trait", and hide the reasoning behind it. The root cause, often one absent field, never appears. + +`CanUseComponent` reframes the same question along a path the compiler will explain. It holds when two things +hold together: + +- the context **delegates** the component — it has a [`DelegateComponent`](./delegate_component.md) entry; +- the delegated provider **is a valid provider** for that exact context and parameters — it satisfies + [`IsProviderFor`](./is_provider_for.md). + +Because `IsProviderFor` carries the provider's real `where` bounds, requiring it forces the compiler to +evaluate and report them. The error that was hidden becomes visible, at the wiring site. + +**You never name this trait.** It is what [`check_components!`](../macros/check_components.md) asserts, and the +reason that macro produces a legible error instead of a cascade. + +## Using it + +The trait is in the prelude. It is empty, and its entire meaning lives in a single blanket impl: + +```rust +pub trait CanUseComponent {} + +impl CanUseComponent for Context +where + Context: DelegateComponent, + Context::Delegate: IsProviderFor, +{ +} +``` + +`Self` is the context being checked, `Component` is the component-name marker, and `Params` collects the +component's extra generic parameters — filled by the same rule +[`IsProviderFor`](./is_provider_for.md) uses: one parameter directly, several as a tuple, `()` when there are +none. + +### Asserting it + +You assert it through a macro. A [`check_components!`](../macros/check_components.md) table reduces to one +impl of a private check trait per entry, whose supertrait is this bound, so the impl compiles only if the +bound holds: + +```rust +check_components! { + Person { + GreeterComponent, + } +} +``` + +Writing the bound by hand is legal and occasionally useful when probing one case: + +```rust +fn assert_wiring() +where + Person: CanUseComponent, +{} +``` + +For a component with parameters the check table carries them, which is the same `Params` slot: +`GreeterComponent: Rectangle` for one, `(Rectangle, f64)` for several. + +## Examples + +The trait's value is what happens when the check fails. Here a provider needs a `name` field and the context +has a differently-named one: + +```rust +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, // not `name` +} + +delegate_components! { + Person { GreeterComponent: GreetHello } +} + +check_components! { + Person { GreeterComponent } +} +``` + +The check forces `Person: CanUseComponent`. Resolving it needs +`Person: DelegateComponent`, which the wiring supplies, and +`GreetHello: IsProviderFor`, which fails because `GreetHello` needs `HasName` +and `Person` has no `name` field. The compiler reports the absent field **here**, at the check, rather than at +some later `person.greet()`. + +Rename the field to `name` and the block compiles and produces nothing — a passing check is a successful +build, with nothing added to the binary. + +## When to reach for it, and when not + +**Reach for [`check_components!`](../macros/check_components.md); it is what reaches for this trait.** The one +non-negotiable is that a context's wiring gets checked *somehow* — lazy wiring means an unchecked context can +compile and fail later. Which macro does it is a matter of scale. + +- **[`delegate_and_check_components!`](../macros/delegate_and_check_components.md)** fuses wiring and checking, + which suits basic wiring and getting started. It derives a check only for plain `Component: Provider` + entries. +- **Separate [`check_components!`](../macros/check_components.md)** is what larger wiring wants, because it + gives control over *what* is checked: concrete parameters for a generic component, checks over opened or + namespaced wiring, and `#[check_providers(...)]` per provider layer. +- **`#[check_providers(...)]`** switches the assertion from this trait to + [`IsProviderFor`](./is_provider_for.md) on named providers. Reach for it when a + [higher-order provider](/docs/concepts/higher-order-providers) stack fails and you need to know *which + layer*, which a context-side check cannot tell you. + +One case makes a context-side check actively wrong rather than merely unnecessary: **a provider bundle.** A +[`delegate_components!`](../macros/delegate_components.md) block with a leading `new` declares a provider that +other contexts delegate to, not a context. Asserting `CanUseComponent` on it asks whether the bundle can use +each component *as a context* — a role it never plays — so the answer is uninformative either way. It passes +vacuously when the bundled providers need nothing from their context, and fails blaming the bundle when any of +them needs something the real context would have supplied. Wire a bundle with plain +`delegate_components!` and let a real context's check verify it, or assert `IsProviderFor` on it directly. + +Finally, not every unmet bound is a component. Some are ordinary or blanket traits, and no check macro can +verify those — they surface as themselves. + +## Under the hood + +:::note + +### Advanced + +This section shows how the two bounds distinguish the two ways wiring goes wrong. You do not need it to write +a check, but it is what tells you whether to add a wiring line or supply a dependency. ::: + +The blanket impl *is* the behaviour, and its two bounds fail differently — which is the practical payoff. + +**The first bound failing means the wiring is absent.** `Context: DelegateComponent` is unmet when +the context never wired the component, and the [`DelegateComponent`](./delegate_component.md) diagnostic +reports a missing table entry. The fix is a wiring line. + +**The second bound failing means the wiring is incomplete.** `Context::Delegate: IsProviderFor<…>` is unmet +when the component *is* wired but the chosen provider's own requirements are not satisfied, and the error is +that provider's unsatisfied `where` clause carried up through the marker. The fix is to supply the dependency. + +Reading which bound failed is therefore the first thing to do with the error. The trait is the mirror image of +[`IsProviderFor`](./is_provider_for.md): the same readability-restoring question, indexed on the context +(`Self = Context`) rather than on the provider (`Self = Provider`). One starts from "the context delegates and +its delegate is valid"; the other from "this specific provider is valid". + +[`check_components!`](../macros/check_components.md) consumes it by emitting a private check trait whose +supertrait is this bound, then one empty impl of that trait per checked entry. Each impl compiles only if its +supertrait holds, so the table is an assertion. Because it produces no values, a successful build *is* the +passing test. + +## Gotchas + +**It is not the consumer trait.** `Person: CanUseComponent` holding is not the same +statement as `Person: CanGreet`, even though in practice one follows the other. The check exists precisely +because the two questions produce different diagnostics. + +**Do not assert it on a provider bundle.** The question is meaningless there, and worse, it can pass +vacuously — so a green check on a bundle proves nothing. This is why +[`delegate_and_check_components!`](../macros/delegate_and_check_components.md) is wrong for a bundle. + +**`Params` follows the tuple rule.** One parameter directly, several as a tuple, `()` for none. A hand-written +assertion that gets this wrong reports as an unsatisfied bound rather than an arity error. + +**A passing check is not a passing test of behaviour.** It proves the wiring resolves and the dependencies +exist. It says nothing about whether the provider does the right thing. + +**Checking costs compile time and nothing else.** The trait is empty and the impls are empty; nothing reaches +the binary. The cost is trait resolution at build time, which is the trade the check exists to make. + +## Related constructs + +- [`check_components!`](../macros/check_components.md) — the macro that asserts this trait; what you write. +- [`delegate_and_check_components!`](../macros/delegate_and_check_components.md) — wires and checks at once, + for basic wiring. +- [`DelegateComponent`](./delegate_component.md) — the first of the two bounds: the context must delegate. +- [`IsProviderFor`](./is_provider_for.md) — the second bound, and the provider-indexed counterpart of this + trait. +- [`#[cgp_component]`](../macros/cgp_component.md) — defines the components being checked. +- [Compile errors](../errors.md) — the shapes these checks produce, and how to read them. + +The ideas behind it: + +- [Check traits](/docs/concepts/check-traits) — why wiring is lazy, and what a compile-time assertion buys. +- [Higher-order providers](/docs/concepts/higher-order-providers) — the case where a context-side check is not + enough. + +## Source + +- Trait and its blanket impl: [`can_use_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/can_use_component.rs) +- The checks that assert it: [`check_components/table.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/check_components/table.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/cast.md b/docs/reference/traits/cast.md index 6e73d892..7d0acf54 100644 --- a/docs/reference/traits/cast.md +++ b/docs/reference/traits/cast.md @@ -6,12 +6,247 @@ sidebar_label: 'CanUpcast, CanDowncast & CanBuildFrom' Structural casts between records and between variants. -:::info +## What it's for -### Not written yet +Two types that share a subset of named fields or variants can be converted into one another with no +hand-written `From` or `TryFrom` impl. Once a type's shape is a type-level list — which +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) makes it — conversion becomes a matter of routing each +named entry to the matching slot in the target, and the routing is derived from the names. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +Four traits cover the directions that routing can take. + +**`CanUpcast`** widens an enum: a value of a narrow enum whose variants are a subset of a wider one's is lifted +into the wider one. It **always succeeds**, because every source variant has a home in the target. + +**`CanDowncast`** narrows: it tries to convert a wide enum into a smaller one, succeeding only if the value's +current variant exists in the target, and otherwise handing back a *remainder* so the caller can try another +target. + +**`CanDowncastFields`** is that same narrowing one level down, called on a remainder rather than on an enum — so +several candidate targets can be tried in sequence. + +**`CanBuildFrom`** is the record counterpart: it fills a target's builder with whatever fields it shares with a +source, leaving the rest of the target to be supplied separately. + +## Using it + +**None of the four is in the prelude.** Import them from `cgp::core::field::impls`: + +```rust +use cgp::core::field::impls::{CanBuildFrom, CanDowncast, CanDowncastFields, CanUpcast}; +``` + +You will also want `core::marker::PhantomData` in scope, since every one of them names its target with a +`PhantomData` argument rather than a turbofish on the method. + +### The variant casts + +```rust +pub trait CanUpcast { + fn upcast(self, _tag: PhantomData) -> Target; +} + +pub trait CanDowncast { + type Remainder; + fn downcast(self, _tag: PhantomData) -> Result; +} + +pub trait CanDowncastFields { + type Remainder; + fn downcast_fields(self, _tag: PhantomData) -> Result; +} +``` + +`upcast` returns the target directly because it cannot fail. `downcast` returns a `Result` whose error is the +source's extractor with the attempted variants removed — which is what `downcast_fields` is then called on. The +difference between the two downcasts is only the starting point: `downcast` converts the enum to an extractor +first, while `downcast_fields` takes one it is already given. + +### The record cast + +```rust +pub trait CanBuildFrom { + type Output; + fn build_from(self, source: Source) -> Self::Output; +} +``` + +It is implemented for a **builder**, not for the target type, which is why it is written +`Target::builder().build_from(source)`. The result is the updated builder, so several sources can be absorbed in +sequence before finalizing. + +**The source of a `build_from` needs [`HasFields`](./has_fields.md)** as well as a builder, because the recursion +walks the source's field list to know what to copy. The target needs only its builder. + +## Examples + +Two independently-defined enums that share variant names interconvert with no manual impl: + +```rust +use cgp::core::field::impls::{CanDowncast, CanUpcast}; +use cgp::prelude::*; +use core::marker::PhantomData; + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum FooBar { + Foo(u64), + Bar(String), +} + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), +} + +// upcast always succeeds: every FooBar variant exists in FooBarBaz +let wide = FooBar::Foo(1).upcast(PhantomData::); +assert_eq!(wide, FooBarBaz::Foo(1)); + +// downcast succeeds for a shared variant +assert_eq!( + FooBarBaz::Bar("hi".to_owned()).downcast(PhantomData::).ok(), + Some(FooBar::Bar("hi".to_owned())), +); + +// and fails for one the target lacks +assert_eq!(FooBarBaz::Baz(true).downcast(PhantomData::).ok(), None); +``` + +`CanBuildFrom` assembles one struct from several smaller ones: + +```rust +use cgp::core::field::impls::CanBuildFrom; + +#[derive(CgpData)] pub struct FooBar { pub foo: u64, pub bar: String } +#[derive(CgpData)] pub struct Baz { pub baz: bool } +#[derive(CgpData)] pub struct FooBarBaz { pub foo: u64, pub bar: String, pub baz: bool } + +let combined: FooBarBaz = FooBarBaz::builder() + .build_from(FooBar { foo: 1, bar: "bar".to_owned() }) + .build_from(Baz { baz: true }) + .finalize_build(); +``` + +Neither source names the target and the target names neither source. They share field *names*, matched at the +type level, and that is the whole coupling. + +## When to reach for it, and when not + +**Reach for a cast when two shapes genuinely overlap and you would otherwise write the conversion by hand.** +That is the case these exist for, and it is narrower than "I have two similar types". + +- **`upcast`** when an implementation works in a small local enum and the result must be widened. This is the + common use, and it is the construction-side counterpart of reading one field through a getter: name only what + you need, and let the widening be checked. +- **`downcast` then `downcast_fields`** when a value must be tried against several candidate targets in turn. + Reach for the pair together — the first starts the chain and the second continues it on each remainder. +- **`build_from`** when a record is assembled from independent pieces. This is the extensible builder pattern's + merge step. +- **Prefer a plain `From` impl** when the two types are yours, the conversion is one you would write once, and + nothing about it needs to be generic. A hand-written `From` is clearer, has no requirements on either type, and + generates nothing — these casts earn their keep when the conversion must be *derived* from names rather than + written. +- **Prefer a `match`** for a one-off narrowing of a concrete enum. `downcast` pays off when the target is a type + parameter or when the chain of candidates is long. + +One boundary worth stating: these are **compile-time, name-driven, and opt-in**. Both types must derive the +shape, the names must match exactly, and nothing is inspected at run time. A type from a crate that has not +derived the machinery cannot participate at all. + +## Under the hood + +:::note + +### Advanced + +This section shows the three recursions. You do not need it to call a cast, but it explains why a downcast hands +back a remainder rather than an `Option`, and why the two downcast traits both exist. ::: + +All three are driven by a recursion over a [`HasFields`](./has_fields.md) shape, and *which* shape is what +distinguishes them. + +**`CanUpcast` recurses over the source's variants.** It converts the source to its extractor, then walks the +source's own field list, pulling each variant out with [`ExtractField`](./extract_field.md) and rebuilding it into +the target with [`FromVariant`](./from_variant.md). Because every source variant is guaranteed to exist in a wider +target, the walk is total — and the extractor left at the end is uninhabited, discharged with +[`FinalizeExtract`](./extract_field.md). That totality is why `upcast` returns the target directly instead of a +`Result`. + +**The downcasts recurse over the *target's* variants instead.** For each `Field` in +`Target::Fields`, the implementation tries pulling that variant out of the source extractor: on success it rebuilds +the target and returns `Ok`; on failure it threads the shrunken remainder into the next attempt. If no target +variant matches, the terminal `Void` impl returns the whole remainder as `Err`. + +That threading is the reason for two traits rather than one. `CanDowncast` starts by calling `to_extractor` on the +enum, while `CanDowncastFields` operates on an extractor it is handed — which is exactly the `Remainder` a prior +`downcast` returned. So chaining candidates is `downcast` followed by `downcast_fields` on each remainder, and the +remainder type narrows at every step just as it does in a hand-written +[extraction chain](./extract_field.md). + +**`CanBuildFrom` recurses over the source's field product.** For each field the source exposes, it uses +[`TakeField`](./has_builder.md) to remove that value from the source and [`BuildField`](./has_builder.md) to write +it into the target builder, threading both the shrinking source and the growing builder through. When the source's +fields run out, the builder is returned — not finalized, which is what lets a second `build_from` follow. + +One asymmetry in the source is worth knowing if you read it: the extractor recursion, `FieldsExtractor`, is +public, while the builder recursion `FieldsBuilder` is private. So the former can appear by name in a diagnostic +and be named in a bound; the latter cannot. + +## Gotchas + +**None of the four is in the prelude.** Import from `cgp::core::field::impls`. This is the first thing that goes +wrong. + +**`build_from` needs [`HasFields`](./has_fields.md) on the source, not just a builder.** Deriving only +`BuildField` on both looks symmetric and does not compile; the error is an unsatisfied `HasFields` bound on the +source type. + +**`build_from` is called on the builder, not the target.** `Target::builder().build_from(source)`, and the result +is a builder you still have to finalize. + +**A downcast returns a remainder, not an `Option`.** `.ok()` discards it, which is fine for a single attempt and +wrong if you meant to try another target — that remainder is the input to `downcast_fields`. + +**Names must match exactly, and a mismatch is a compile error rather than a runtime miss.** Renaming a variant or +field in one type silently removes it from the overlap, and the failure surfaces as an unsatisfied bound +wherever the cast is written. + +**A remainder carries none of the enum's attributes**, so a `Result` is neither `Debug` nor +`PartialEq` — comparing one whole does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. + +**An upcast is total only if the target really is wider.** If the target lacks one of the source's variants there +is no impl, and the error is an unsatisfied bound rather than a runtime failure — which is the guarantee, but it +reads as a puzzling missing-impl message until you check the variant lists. + +## Related constructs + +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — generates the shapes and machinery all four consume. +- [`HasFields`](./has_fields.md) — the shape each recursion walks, and what a `build_from` source needs. +- [`ExtractField`](./extract_field.md) and [`FromVariant`](./from_variant.md) — the primitives the variant casts + route through. +- [`HasBuilder`](./has_builder.md) — the `TakeField`/`BuildField` pair the record cast routes through. +- [Optional fields](./optional_fields.md) — `CanBuildWithDefault`, which chains `build_from` into a defaulted + finalize. +- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` and `Cons`/`Nil` chains being walked. +- [`Symbol!`](../macros/symbol.md) — the tags the matching is done on. +- [Dispatch combinators](../providers/dispatch_combinators.md) — where casting meets per-variant routing. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — upcasting and downcasting between enums. +- [Extensible records](/docs/concepts/extensible-records) — merging records through a builder. + +## Source + +- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs) — + `CanUpcast`, `CanDowncast`, `CanDowncastFields`, and the `FieldsExtractor` recursion +- [`build_from.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/build_from.rs) + — `CanBuildFrom` and its `FieldsBuilder` recursion + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md index 7b86197e..bb18de66 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/default_namespace.md @@ -6,12 +6,286 @@ sidebar_label: 'DefaultNamespace & DefaultImpls' The namespace default-resolution traits, and `#[default_impl(...)]`. -:::info +## What it's for -### Not written yet +A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the type +the capability runs against — can opt into and then selectively override. Resolving one of those defaults means +asking: *for this key, what does the namespace delegate to?* -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +These three traits are what answer that question. They are plain key-to-value lookups, one `Delegate` associated +type each, differing only in how many types take part in the key: + +```rust +pub trait DefaultNamespace { + type Delegate; +} + +pub trait DefaultImpls1 { + type Delegate; +} + +pub trait DefaultImpls2 { + type Delegate; +} +``` + +`DefaultNamespace` keys a default on the component alone. `DefaultImpls1` adds one further type — the shape for a +*per-type* default, where the same component resolves differently for `String` than for `u64`. `DefaultImpls2` +does the same under a pair. + +Three traits rather than one variadic trait because each fixes the key's arity at the type level, which is what +lets the projection `>` resolve cleanly. + +**You name these only in two places**: the namespace header of a wiring block, and the target of a +`for … in` loop. The macros generate the impls and the forwarding — so this page is mostly about reading what +they generate, and about one detail that is genuinely easy to get backwards. + +## Using it + +`DefaultNamespace` is in the prelude. **`DefaultImpls1` and `DefaultImpls2` are not** — import them from +`cgp::core::component`, and you will need to, because the generated impl references the trait by name. + +```rust +use cgp::core::component::DefaultImpls1; +``` + +`Self` is the key being looked up, `Components` is the table the lookup runs against — threaded through so one key +can resolve differently per context — and `Delegate` is the resolved value. There is no method and no data; +resolving a default *is* projecting `Delegate` from the matching impl, exactly as with +[`DelegateComponent`](./delegate_component.md). + +### The one thing to get right + +**The parameter names `T`, `T1`, and `T2` are misleading about which position holds what.** For +`DefaultNamespace` the `Self` key is the component name, as you would expect. For the two `DefaultImpls` +variants it is the other way round: **`Self` is the instance type, and the component name is a leading +parameter.** Registering `ShowString` as the `String` default for `ShowImplComponent` emits: + +```rust +impl DefaultImpls1 for String { + type Delegate = ShowString; +} +``` + +`Self` is `String`; the trait's `T` parameter is filled by `ShowImplComponent`. + +The rule that actually governs this comes from the attribute rather than the trait, and once you have it the +positions stop being surprising. `#[default_impl(Key in NamespacePath)]` makes **`Key` the impl's `Self`** and +appends the table parameter to whatever `NamespacePath` names — so the leading arguments are simply whatever you +wrote inside the path. The same rule is why the `for … in` loop's bound reads +`T: DefaultImpls1`, with the loop variable in the `Self` position. + +### Registering a default + +`#[default_impl(...)]` on a [`#[cgp_impl]`](../macros/cgp_impl.md) provider registers it as a default: + +```rust +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { /* … */ } +``` + +The registration impl carries only the parameters naming the key and provider, plus the table — **never the +provider's own `where` clause**. A provider whose bounds come from `#[use_type]`, `#[uses]`, `#[implicit]`, or +`#[use_provider]` registers cleanly, because those bounds stay on the provider's impl and its +[`IsProviderFor`](./is_provider_for.md) and are checked when a real context resolves it. + +### Consuming defaults + +A context joins a namespace with a header and pulls per-type defaults with a loop: + +```rust +delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + } +} +``` + +The header forwards `App`'s unwired lookups through the namespace; the loop wires each `T` that has a default. The +loop variable must appear in the key, or it is unconstrained and the impl is rejected. + +## Examples + +The whole chain, from a provider declaring itself a default to a context pulling it in and overriding one entry: + +```rust +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; +use core::fmt::Display; + +#[cgp_component(ShowImpl)] +#[prefix(@test in DefaultNamespace)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} +``` + +Then the context: + +```rust +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + @test.ShowImplComponent.u64: ShowWithDisplay, // overrides the inherited default + } +} +``` + +The loop wires every type with a registered default by projecting +`T: DefaultImpls1`, and the direct `u64` line shadows whatever the +namespace would otherwise supply for that one type — the inheritance-with-override shape presets rely on. + +A whole namespace can also be the loop target: + +```rust +cgp_namespace! { + new DefaultShowComponents { + [String, u64]: ShowWithDisplay, + } +} +``` + +Pointing `for in DefaultShowComponents { … }` at this wires the listed types through the same +projection. + +## When to reach for it, and when not + +**Write [`cgp_namespace!`](../macros/cgp_namespace.md) and the wiring statements; name these traits only where the +syntax requires it.** They appear in a `namespace` header, in a `for … in` target, and in a `#[default_impl]` +attribute — and nowhere else in ordinary code. + +- **Use `DefaultNamespace`** for a namespace whose defaults are per component, which is the common case and what + [`#[prefix(...)]`](../macros/cgp_namespace.md) registers into. +- **Use `DefaultImpls1`** for a per-type default, where one component resolves differently per type. This is what + `#[default_impl]` is usually pointed at. +- **Use `DefaultImpls2`** for a two-type key. It works, and it is the one member of the family that nothing in the + library itself emits or consumes — a provided extension point rather than a construct the generated code relies + on. +- **Define your own namespace trait instead** when you want a named table of your own; + [`cgp_namespace!`](../macros/cgp_namespace.md) generates one, and `#[default_impl]` accepts any path, so these + three are conveniences rather than the only options. +- **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. A namespace + buys reuse and inheritance at the cost of one more indirection to follow when reading, and a short + [`delegate_components!`](../macros/delegate_components.md) block needs neither. + +One constraint decides where a `#[default_impl]` may be *written*, and it is Rust's orphan rule rather than +anything CGP chose. The emitted impl is `impl Namespace<..> for Key`, so a crate may register a default when it +owns either the namespace trait or the key type. For an unprefixed component the key is the component's own +marker, so a downstream crate owning the component can register into a foreign namespace. For a +[`#[prefix]`](../macros/cgp_namespace.md)-ed component the key is a path built from `cgp`-owned types plus the +marker, so the impl is orphan-legal **only in the namespace's own crate**. Wiring that must live downstream goes +in the namespace body of the crate that owns it instead. + +## Under the hood + +:::note + +### Advanced + +This section shows what the header and the loop generate. You do not need it to use a namespace, but it explains +how a direct entry can shadow an inherited default without conflicting with it. ::: + +A `namespace N;` header does not emit one entry — it emits a **blanket** +[`DelegateComponent`](./delegate_component.md) impl on the context that forwards every key through the namespace: + +```rust +impl DelegateComponent for App +where + Key: N, +{ + type Delegate = Value; +} +``` + +paired with the matching [`IsProviderFor`](./is_provider_for.md) forwarding so dependencies stay diagnosable. + +**That blanket is what makes override work.** A directly-wired entry is a *concrete* impl for one key, and a +concrete impl is more specific than the blanket, so it resolves first — shadowing the inherited default for that +key and leaving the rest untouched. Two *concrete* entries for one key would conflict; a concrete entry against a +blanket does not. + +A `for in DefaultImpls1 { … }` loop emits a `DelegateComponent` impl whose `where` +clause projects the default: + +```rust +where T: DefaultImpls1 +``` + +Read it as: for each type `T` that has a default, wire that key to the projected `Provider`. Because the loop +variables appear only in that bound and in the key, the key must mention `T` — otherwise the parameter is +unconstrained and the compiler rejects the impl. + +Inheritance composes on top. A namespace declared `new Child: Parent { … }` emits a blanket impl forwarding any +key the parent resolves, so the child resolves everything the parent does plus its own entries — and a context's +direct entry still shadows either. All of it is projections, resolved at compile time, with nothing at run time. + +## Gotchas + +**`DefaultImpls1` and `DefaultImpls2` are not in the prelude.** Import from `cgp::core::component`. +`DefaultNamespace` is. + +**`Self` is the instance type for the `DefaultImpls` variants, not the component.** The parameter names suggest +otherwise. Read `#[default_impl(Key in Path)]` as "`Key` becomes `Self`" and the positions follow. + +**A `for … in` loop's key must mention the loop variable.** Otherwise the parameter is unconstrained and the +impl is rejected with `E0207` — which reads as a puzzling error about a generic parameter rather than about the +loop. + +**`#[default_impl]` on a prefixed component is confined to the namespace's crate.** The orphan rule decides this, +so a downstream default for a prefixed component is not something to work around — put the wiring in the +namespace body instead. + +**A namespace default is a fallback, not an assignment.** It resolves only for keys the context does not wire +directly, which is the intent, and it means a stray direct entry can silently shadow a default you expected to +apply. + +**`DefaultImpls2` has no user inside CGP.** It is reachable and tested, but nothing in the library emits or +consumes it — so there is no generated code to pattern-match against when using it. + +## Related constructs + +- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. +- [`delegate_components!`](../macros/delegate_components.md) — carries the `namespace` header and the `for … in` + loop that consume these traits. +- [`DelegateComponent`](./delegate_component.md) — what a namespace header forwards *into*. +- [`IsProviderFor`](./is_provider_for.md) — forwarded alongside, so dependency errors stay readable. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value, re-routing along a path. +- [`Path!`](../macros/path.md) — the paths a prefixed key is built from. +- [`#[cgp_impl]`](../macros/cgp_impl.md) — the host of the `#[default_impl]` attribute. + +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style configuration. + +## Source + +- The three traits: [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) +- The namespace macro: [`types/namespace/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/namespace) +- The `#[default_impl]` attribute: [`attributes/default_impl/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/default_impl) +- The header and loop codegen: [`delegate_component/statement/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/statement) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/delegate_component.md index 40c7b331..4c4ffe23 100644 --- a/docs/reference/traits/delegate_component.md +++ b/docs/reference/traits/delegate_component.md @@ -6,12 +6,265 @@ sidebar_label: 'DelegateComponent' The per-context type-level table mapping a component key to its provider. -:::info +## What it's for -### Not written yet +Wiring a **context** — the type the capability runs against, which supplies the values it needs as its +fields — means recording which implementation it uses for each capability. `DelegateComponent` is the trait +that record is made of. One impl is one entry: -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +```rust +impl DelegateComponent for App { + type Delegate = GreetHello; +} +``` + +Read that as *"in `App`'s table, the entry at `GreeterComponent` is `GreetHello`."* The key is a type, the +value is a type, and the whole lookup happens while the compiler is type-checking — which is why the +"table" costs nothing at runtime and compiles down to a direct call. + +**You will almost never write this by hand.** [`delegate_components!`](../macros/delegate_components.md) +generates one impl per line of its body, and that macro is what you write. What makes the trait worth a +page is that it appears by name in compiler errors, and that reading it is how you understand what wiring +*is*: not a registry, not a lookup at startup, but a set of trait impls the compiler resolves. + +One thing to notice early, because it explains why the trait is so general: **the key does not have to be a +component name.** When it is, the entry makes the context inherit the component's provider trait. When it +is any other type — a shape, a tag, a path segment — the same trait is just a lookup table that a provider +walks. One trait covers both, which is why it underlies both ordinary wiring and the inner dispatch tables. + +## Using it + +The trait is in the prelude, so `use cgp::prelude::*;` is enough to name it. It carries one associated type +and no methods: + +```rust +pub trait DelegateComponent { + type Delegate; +} +``` + +`Self` is the table — the context or the provider bundle that owns the entry. `Key` is what is being looked +up, and it is `?Sized` so that an unsized marker can serve as one. `Delegate` is the value stored there. +There is nothing else: no method, no data, no runtime representation. + +### Setting an entry, and reading one + +There are only two operations, and both are ordinary Rust rather than anything CGP-specific. + +**Setting** an entry is writing the impl, which in practice means writing a +[`delegate_components!`](../macros/delegate_components.md) line. **Reading** one is bounding on the trait +and projecting the associated type: + +```rust +fn provider_for() -> PhantomData<>::Delegate> +where + Table: DelegateComponent, +{ + PhantomData +} +``` + +The bound is the "get"; `
>::Delegate` is the value it returns. Because Rust +forbids two impls of one trait for the same `Self` and `Key`, each key maps to exactly one value — which is +what makes this a map rather than a relation, and what makes a duplicate wiring entry a coherence error +rather than a silent overwrite. + +### What can be a key + +The key's type decides what the entry *means*, and there are three shapes in practice. + +A **component name** — `GreeterComponent`, `AreaCalculatorComponent` — is the ordinary case. An entry keyed +this way is read by the blanket impl that [`#[cgp_component]`](../macros/cgp_component.md) generates, which +concludes that the context has the component's provider trait, and from there its consumer trait. + +An **arbitrary type** — a shape, a tag — makes the table a plain dispatch map with no provider trait +attached. This is what the nested tables inside [`UseDelegate`](../providers/use_delegate.md) are, and what +the `open` statement's per-key entries resolve through. + +A **type-level path** — a [`PathCons`](../types/type_level_spines.md) list built by +[`Path!`](../macros/path.md) — is how namespaces key their entries, so a lookup walks one segment at a time. +[`RedirectLookup`](../providers/redirect_lookup.md) is the provider that performs that walk. + +### What owns a table + +`Self` is not always a context. A [`delegate_components!`](../macros/delegate_components.md) block with a +leading `new` declares a provider bundle that owns its own table, so several contexts can delegate a whole +group of components to it as one unit. Resolution is shallow — one read yields the immediate `Delegate` — +and chaining happens when that delegate is itself a table, which is exactly what a bundle is. + +## Examples + +The single wired component is the whole idea. Given a component and a provider: + +```rust +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) { + println!("Hello!"); + } +} +``` + +a context wires it in one line: + +```rust +pub struct App; + +delegate_components! { + App { + GreeterComponent: GreetHello, + } +} +``` + +and that line is exactly one `DelegateComponent` impl: + +```rust +impl DelegateComponent for App { + type Delegate = GreetHello; +} +``` + +From there the generated blanket impls take over: because `App` delegates `GreeterComponent`, it gets the +`Greeter` provider trait, and because it has that, it gets `CanGreet` — so `app.greet()` compiles. Swap +`GreetHello` for another provider and only that one line changes. + +An arbitrary-key table looks identical and means something different. The nested-table syntax builds a +dispatch map keyed on shapes: + +```rust +delegate_components! { + new AreaComponents { + Rectangle: RectangleArea, + Circle: CircleArea, + } +} +``` + +`AreaComponents` now has `DelegateComponent` and `DelegateComponent` entries. No provider +trait attaches to either; they are data that a [`UseDelegate`](../providers/use_delegate.md) provider reads +at dispatch time to pick `RectangleArea` or `CircleArea` for the shape it was asked about. + +## When to reach for it, and when not + +**Write [`delegate_components!`](../macros/delegate_components.md), not `DelegateComponent`.** That is the +honest summary of this page: the trait is what you read, and the macro is what you write. The macro also +emits the [`IsProviderFor`](./is_provider_for.md) forwarding impl beside each entry, which is what keeps a +missing dependency diagnosable — so a hand-written `DelegateComponent` impl gets you the wiring and loses +the error message. + +There are two narrow reasons to name the trait yourself. + +- **Reading an entry in generic code.** A provider that must resolve a key itself — a dispatcher, a + higher-order provider walking a table — bounds on `DelegateComponent` and projects `Delegate`. This + is the one legitimate hand-written use, and it is a *read*. +- **Recognizing it in an error.** `the trait bound App: DelegateComponent is not + satisfied` means the context never wired that component. That is the most common wiring error there is, + and knowing the trait is how you read it. + +And the alternative to reach for instead: **implement the consumer trait directly on the context** when a +capability has exactly one implementation for it. A CGP consumer trait is an ordinary trait, so +`impl CanGreet for App { … }` is legal and needs no table entry at all. Wiring earns its keep when the +implementation is one of several, or is shared, or should compose with a wrapper. + +## Under the hood + +:::note + +### Advanced + +This section shows how the generated code reads the table. You do not need it to wire a context, but the +trait's name appears in wiring errors and the routing explains why a call resolves the way it does. +`cargo cgp expand` prints the impls for your own code. ::: + +The trait is the plainest thing in CGP — one associated type, no method — so the interesting part is what +reads it. The provider blanket impl generated by [`#[cgp_component]`](../macros/cgp_component.md) is the +reader, and its body is itself a table lookup: it bounds the provider on `DelegateComponent` +and forwards each method to `>::Delegate`. So the "routing" is +literally the projection, and the call it forwards to is resolved statically and inlined. + +The trait carries a diagnostic attribute that shapes the error when a lookup misses: + +```rust +#[diagnostic::on_unimplemented( + message = "{Self} does not contain any DelegateComponent entry for {Key}", + note = "You might want to implement the provider trait for {Key} on {Self}" +)] +pub trait DelegateComponent { + type Delegate; +} +``` + +That message is why an unwired component reports as a missing *entry* rather than as an opaque unimplemented +trait — one of the few places CGP can improve a diagnostic without a tool. + +Two further facts about the generated impls are worth carrying away. Each entry is emitted **alongside** an +[`IsProviderFor`](./is_provider_for.md) impl that forwards the chosen provider's requirements, so the entry +is both resolvable and checkable; the pair is what +[`CanUseComponent`](./can_use_component.md) then combines into a single assertion. And a namespace's +`namespace N;` header emits not one entry but a *blanket* `DelegateComponent` impl that forwards every key +through the namespace, which is how a context inherits a whole table while still letting a direct entry +shadow one key. + +## Gotchas + +**A missing entry and an unsatisfied provider are different errors.** `DelegateComponent` not implemented +means the component was never wired. A wired component whose provider's dependencies are unmet fails +elsewhere, through [`IsProviderFor`](./is_provider_for.md). Reading which one you have tells you whether to +add a wiring line or supply a dependency. + +**Two entries for the same key is a coherence error, not an override.** Wiring one component twice on one +context reports `E0119` conflicting implementations. A namespace *can* be shadowed by a direct entry, +because the namespace side is a blanket impl rather than a second concrete one — but two concrete entries +always conflict. + +**`Self` is not always a context.** A provider bundle declared with `new` owns a table too, and reading an +error that names one as the table's `Self` does not mean something is being used as a context. + +**A hand-written impl loses the diagnostics.** It wires correctly and silently gives up the `IsProviderFor` +forwarding that makes a missing transitive dependency readable. Use the macro. + +**The table is resolved at compile time, in full.** There is no runtime map to inspect, no way to add an +entry dynamically, and no cost per call. If you are looking for a place to register something at startup, +this is not it — and that is the point. + +## Related constructs + +- [`delegate_components!`](../macros/delegate_components.md) — the macro that generates these impls; what + you write instead of the trait. +- [`#[cgp_component]`](../macros/cgp_component.md) — generates the blanket impl that reads the table. +- [`IsProviderFor`](./is_provider_for.md) — emitted beside each entry so a missing dependency stays + readable. +- [`CanUseComponent`](./can_use_component.md) — combines a delegation and a valid provider into one + assertion. +- [`check_components!`](../macros/check_components.md) — asserts that combination. +- [`UseDelegate`](../providers/use_delegate.md) — reads an arbitrary-key table for per-type dispatch. +- [`RedirectLookup`](../providers/redirect_lookup.md) — walks path-keyed entries; the namespace mechanism. +- [`DefaultNamespace`](./default_namespace.md) — the lookup traits a `namespace` header forwards through. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the split this table + connects. +- [Bypassing coherence](/docs/concepts/coherence) — why the choice is recorded per context at all. +- [Aggregate providers](/docs/concepts/aggregate-providers) — a table owned by a provider rather than a + context. + +## Source + +- Trait: [`delegate_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/delegate_component.rs) +- Entry codegen: [`delegate_component/mapping/eval.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/delegate_component/mapping/eval.rs) +- The blanket impl that reads it: [`cgp_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md index c3433f25..0a83db3e 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/extract_field.md @@ -6,12 +6,294 @@ sidebar_label: 'ExtractField' The incremental-extractor trait family behind the extensible visitor pattern. -:::info +## What it's for -### Not written yet +A `match` on a concrete enum is checked for exhaustiveness. Code that is generic over the enum cannot write +one, so it falls back on a wildcard arm and an `unreachable!()` — losing exactly the guarantee you wanted. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +This family recovers it. An enum is taken apart one variant at a time, and **the still-possible variants are +tracked in the type**. Each attempt either yields the payload or hands back a *remainder* whose type has that +variant ruled out: + +```rust +match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => /* it was a Circle */, + Err(remainder) => /* it wasn't; `remainder` can no longer be a Circle */, +} +``` + +Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** — a +value of it cannot exist — and that is what closes the chain with no wildcard and no panic path. Add a variant +to the enum and the final remainder becomes inhabited again, so the code stops compiling until it is handled. + +The family is the mirror of the [builder](./has_builder.md): a builder tracks which fields are *present*, an +extractor tracks which variants are still *possible*. The impls come from +[`#[derive(ExtractField)]`](../derives/derive_extract_field.md), which generates the partial companion enums +they operate on. + +## Using it + +Most of the family is in the prelude — `HasExtractor`, `HasExtractorRef`, `HasExtractorMut`, `ExtractField`, +`FinalizeExtract`. The exception is **`FinalizeExtractResult`, which is not**; import it from +`cgp::core::field::traits`, and you will want it, because it is what closes a chain. + +### The three accessors + +They differ only in ownership, and picking the right one is most of using the family: + +```rust +pub trait HasExtractor { + type Extractor; + fn to_extractor(self) -> Self::Extractor; + fn from_extractor(extractor: Self::Extractor) -> Self; +} + +pub trait HasExtractorRef { + type ExtractorRef<'a> where Self: 'a; + fn extractor_ref(&self) -> Self::ExtractorRef<'_>; +} + +pub trait HasExtractorMut { + type ExtractorMut<'a> where Self: 'a; + fn extractor_mut(&mut self) -> Self::ExtractorMut<'_>; +} +``` + +`to_extractor` **consumes** the value and yields owned payloads; `from_extractor` reverses it for a value that +was not matched. `extractor_ref` borrows, so payloads come out as shared references and the original survives. +`extractor_mut` borrows mutably, so a payload can be changed in place. + +### The extraction + +```rust +pub trait ExtractField { + type Value; + type Remainder; + fn extract_field(self, _tag: PhantomData) -> Result; +} +``` + +`Ok` carries the payload; `Err` carries the same extractor with this one variant ruled out. The impl exists +only while the requested variant is still possible, so attempting the same variant twice is a compile error +rather than a guaranteed miss. + +### The finish + +```rust +pub trait FinalizeExtract { + fn finalize_extract(self) -> T; +} + +pub trait FinalizeExtractResult { + type Output; + fn finalize_extract_result(self) -> Self::Output; +} +``` + +`finalize_extract` returns *any* type, which is sound only because there is no value to return it from — it is +implemented for the uninhabited [`Void`](../types/type_level_spines.md), for `Infallible`, and for the +all-ruled-out configuration of a partial enum. + +`finalize_extract_result` is the one you actually call. It collapses the `Result` from the last extraction, +and it is implemented for any `Result` whose error half can be finalized: + +```rust +impl FinalizeExtractResult for Result +where + E: FinalizeExtract, +{ + type Output = T; + // Ok(value) => value, Err(remainder) => remainder.finalize_extract() +} +``` + +## Examples + +The chain reads as a sequence of attempts, each handling one variant, closed by +`finalize_extract_result`: + +```rust +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + // `remainder` now has Circle ruled out + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); // uninhabited; cannot fail + rect.width * rect.height + } + } +} +``` + +After the second extraction both variants are ruled out, so the remainder's type is uninhabited and +`finalize_extract_result` is accepted with no wildcard arm. That is not a convention — it is the type. Try to +finalize after only the first extraction and it does not compile. + +Reading through a borrow leaves the value intact: + +```rust +let radius = shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok(); +``` + +and the mutable form changes a payload in place: + +```rust +if let Ok(circle) = shape + .extractor_mut() + .extract_field(PhantomData::) +{ + circle.radius = 5.0; +} +``` + +**In practice you rarely write these chains.** The +[dispatch combinators](../providers/dispatch_combinators.md) build them from a set of per-variant +implementations, which is the extensible visitor pattern — a chain exactly like the one above, generated, with +one implementation per variant chosen by wiring. + +## When to reach for it, and when not + +**Reach for the family when independent code handles one variant each, or when the matching code cannot name +the enum.** Outside those two cases a `match` wins on every count: shorter, clearer, already exhaustive, and it +generates nothing. This is not an improvement on `match`; it is what you use where `match` is unavailable. + +- **Bound on `HasExtractor` + `ExtractField`** to write a routine that deconstructs an enum it does not name. +- **Pick the accessor by ownership**, and prefer the weakest that works: `extractor_ref` for a read-only + operation over a value you do not own, `extractor_mut` to mutate a payload, `to_extractor` only when you + genuinely want to consume. +- **Do not use it to test which variant a value holds.** `matches!` or an `if let` answers that in a line. The + family's value is in the *chain* and what the chain proves. +- **Reach for the [dispatch combinators](../providers/dispatch_combinators.md) rather than writing the chain**, + since they derive it from the enum's own variant list instead of repeating it at each site — which is what + keeps "add a variant" from breaking every call site by hand. + +The construction counterpart is [`FromVariant`](./from_variant.md), and the two are commonly wanted together +because a generic pipeline usually takes a value apart and puts one back. The struct analogue of the whole +family is [`HasBuilder`](./has_builder.md). + +## Under the hood + +:::note + +### Advanced + +This section shows how the exhaustiveness argument works. You do not need it to use the family, but the partial +enums appear by name in every extraction error, and the `IsVoid`-versus-`IsNothing` distinction is the one thing +here that genuinely surprises people. ::: + +The derive generates a companion enum with one [`MapType`](./map_type.md) parameter per variant, each payload +wrapped in that parameter's projection: + +```rust +pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { + Circle(<__F0__ as MapType>::Map), + Rectangle(<__F1__ as MapType>::Map), +} +``` + +`to_extractor` starts at the all-`IsPresent` configuration, where every variant is still possible. Each +`extract_field` impl is in scope only while its variant's marker is `IsPresent`; on a miss it returns the +remainder with that one marker flipped to `IsVoid`, leaving the rest generic — which is why extractions may +happen in any order. + +**The exhaustiveness argument turns on what `IsVoid` maps to.** It maps a payload to the uninhabited `Void`, so +once every marker is `IsVoid` every arm of the partial enum holds a `Void` and the whole type is uninhabited. +The derive supplies a `FinalizeExtract` impl on exactly that configuration, and it is sound only because the +value cannot exist: + +```rust +impl FinalizeExtract for __PartialShape { + fn finalize_extract<__T__>(self) -> __T__ { + match self {} // no arms to write + } +} +``` + +So a caller reaches `finalize_extract` only after trying every variant, and the compiler accepts the discharge +with no fallback. + +**This is where the record and variant families diverge, and the difference is load-bearing.** 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 exactly why a builder needs an explicit all-present `FinalizeBuild` impl while an extractor can +discharge its remainder with an empty `match`. + +The borrowed accessors use the same partial enum with an extra [`MapTypeRef`](./map_type.md) parameter fixed to +`IsRef` or `IsMut`, mapping each payload slot to a shared or mutable reference — so a value can be matched +without being moved, and the narrowing works identically. + +## Gotchas + +**`FinalizeExtractResult` is not in the prelude.** Import it from `cgp::core::field::traits`. Without it there +is no `finalize_extract_result` in scope and the chain has no clean ending. + +**Absence is `IsVoid` here and `IsNothing` in a builder, and they are not interchangeable.** An error naming the +wrong one usually means record and variant machinery have been crossed. + +**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`, so the compiler reports a missing method. Read the type in the message to +see which variants remain. + +**A remainder carries none of the enum's attributes.** The partial enums are generated without your derives, so +a `Result` is neither `Debug` nor `PartialEq` however the enum is derived — `assert_eq!` on +the whole result does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. + +**Order is free but the set is not.** Each step changes only its own variant's marker, so extractions may be +written in any order — but every variant must be tried before the remainder can be finalized. + +**Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the reason to +prefer the [dispatch combinators](../providers/dispatch_combinators.md). + +**Five enum variant names are reserved**, because the generated impls name their associated types through +`Self::…`. The [derive's page](../derives/derive_extract_field.md) lists them. + +## Related constructs + +- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the partial enums and every impl + here. +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this family with the shape and the + constructors. +- [`FromVariant`](./from_variant.md) — the construction counterpart, commonly derived alongside. +- [`HasBuilder`](./has_builder.md) — the struct analogue, and where the `IsNothing`/`IsVoid` contrast comes from. +- [`MapType`](./map_type.md) — the `IsPresent`/`IsVoid` markers and the `MapTypeRef` borrow markers. +- [`HasFields`](./has_fields.md) — the variant shape the casts and dispatchers walk. +- [`CanUpcast`](./cast.md) — upcasting and downcasting, built on this recursion. +- [Type-level spines](../types/type_level_spines.md) — `Either`/`Void`, where the uninhabited terminator comes + from. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build the chain for you. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — partial variants, the exhaustiveness argument, + and the extensible visitor pattern. +- [Dispatching](/docs/concepts/dispatching) — routing a variant to the implementation that handles it. + +## Source + +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) + — every trait on this page +- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs) + — `PartialData`, which the partial enums also implement +- [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) + — the `IsRef`/`IsMut` borrow markers + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md index b256c0a5..506a3fe4 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/from_variant.md @@ -6,12 +6,212 @@ sidebar_label: 'FromVariant' Generic construction of an enum from a named variant. -:::info +## What it's for -### Not written yet +`Shape::Circle(circle)` names two things: the enum and the variant. That is fine where both are known and +useless to code that knows neither — a routine handed a payload and told which variant to wrap it in cannot +write that expression. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`FromVariant` gives it a way to. The variant is selected by its *name as a type*, so the choice becomes a +parameter rather than syntax: + +```rust +Shape::from_variant(PhantomData::, circle) +``` + +That call is exactly `Shape::Circle(circle)`. The difference is that the tag can come from a type parameter, so +one function can build whichever variant it was asked for, on whatever enum implements the trait for that tag. + +**This is the smallest trait in the extensible-data family.** There is no companion type, no state, and nothing +to track — building a single variant has no intermediate states. It is the construction counterpart to +[`ExtractField`](./extract_field.md)'s deconstruction, and the impls come from +[`#[derive(FromVariant)]`](../derives/derive_from_variant.md), one per variant. + +## Using it + +The trait is in the prelude. It carries the payload type as an associated `Value` and one associated function: + +```rust +pub trait FromVariant { + type Value; + + fn from_variant(_tag: PhantomData, value: Self::Value) -> Self; +} +``` + +`Tag` is the variant's name as a [`Symbol!`](../macros/symbol.md) type-level string, `Value` is that variant's +payload type, and `from_variant` wraps a payload into the enum. The `PhantomData` argument carries no +data; it exists so a caller can pick which variant to build when several impls — one per variant — are in scope +on the same enum. + +The trait is implemented once per variant, each impl fixing its own `Tag` and `Value`, so **choosing the impl +*is* choosing the variant**. + +### Naming the payload type generically + +The associated `Value` is what makes a generic signature possible: a function that does not know the variant +still needs to name the type it takes. Project it through the trait: + +```rust +fn wrap(tag: PhantomData, value: >::Value) -> Shape +where + Shape: FromVariant, +{ + Shape::from_variant(tag, value) +} +``` + +`>::Value` is the payload type *derived from the tag*. Without it there would be +nothing to write in the parameter position, which is the whole reason the trait carries an associated type +rather than taking the payload as a second parameter. + +## Examples + +One `wrap` builds either variant, and its payload type follows the tag: + +```rust +use cgp::prelude::*; + +#[derive(FromVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn wrap(tag: PhantomData, value: >::Value) -> Shape +where + Shape: FromVariant, +{ + Shape::from_variant(tag, value) +} + +let circle = wrap(PhantomData::, Circle { radius: 2.0 }); +let rect = wrap( + PhantomData::, + Rectangle { width: 3.0, height: 4.0 }, +); +``` + +No hand-written function can do that, because `Shape::Circle` and `Shape::Rectangle` are different expressions +taking different types. + +Where this earns its keep in practice is **building through a narrow enum and widening**. A routine that only +produces some of a large enum's variants declares a small local enum, constructs into that, and lifts the +result: + +```rust +use cgp::core::field::impls::CanUpcast; + +let ident = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); +``` + +The upcast always succeeds, because every variant of the smaller enum has a home in the larger one — and it is +`FromVariant` that rebuilds each variant into the target. That is the construction-side counterpart of reading +a field through a getter: the implementation names only what it needs, and the widening is checked. +Upcasting is documented with the other [structural casts](./cast.md). + +## When to reach for it, and when not + +**Bound on `FromVariant` when the variant to build is decided by a type parameter.** That is the whole test, +and it is narrower than the extractor's, because most code decides which variant to build at a site that can +simply name it. + +- **Bound on it in a routine parameterized over the variant it produces.** There is no alternative. +- **Derive it to make a smaller enum upcastable into a larger one.** Casting between enums is built on these + constructors, so this is what lets an implementation work in a narrow local enum and widen the result. +- **Do not reach for it for an ordinary constructor call.** `Shape::Circle(circle)` is shorter, clearer, and + generates nothing. The trait adds a *second* way to do the same thing, for callers that cannot use the first. +- **Do not derive it alone if you also take the enum apart**, which is the usual case — reach for + [`#[derive(CgpData)]`](../derives/derive_cgp_data.md), which bundles construction, deconstruction, and the + shape. + +The split with its counterpart is exactly what the names say: this trait puts a value *into* an enum, +[`ExtractField`](./extract_field.md) gets one *out*. For structs, the analogous field-setting primitive is +[`BuildField`](./has_builder.md). + +## Under the hood + +:::note + +### Advanced + +This section shows what the derive emits. It is the shortest expansion in the family, and worth reading once +because the impls appear by name in errors about generic construction. ::: + +The derive emits **one impl per variant and nothing else**: + +```rust +impl FromVariant for Shape { + type Value = Circle; + + fn from_variant(_tag: PhantomData, value: Self::Value) -> Self { + Self::Circle(value) + } +} + +impl FromVariant for Shape { + type Value = Rectangle; + + fn from_variant(_tag: PhantomData, value: Self::Value) -> Self { + Self::Rectangle(value) + } +} +``` + +Each body is the plain constructor call, and there is no intermediate type, no marker, and no validation beyond +the type system's own check that the payload matches. Because the impls are distinguished *only* by their `Tag` +parameter, resolving a `from_variant` call comes down to which `Symbol!` the caller names — the compiler picks +the matching impl and inlines it to the corresponding constructor. So the generic call costs exactly what the +concrete one does. + +The trait itself is defined in the library; the derive supplies only these per-variant impls. Each is aimed at +the variant it came from, so a conflict with a hand-written impl underlines that variant rather than the whole +derive. + +## Gotchas + +**The tag must be written out, not inferred.** `Shape::from_variant(PhantomData::, value)` +needs the turbofish, because nothing in the value determines the variant when two variants could share a payload +type. + +**Two variants with the same payload type are distinguishable only by tag.** That is the reason for the previous +point, and it means a mistyped tag is a missing-impl error rather than a type mismatch. + +**A variant name is matched exactly.** `Symbol!("Circle")` and `Symbol!("circle")` are unrelated types, so a +case slip reports as an unsatisfied `FromVariant` bound. + +**A variant named `Value` does not compile**, because the generated signature names the payload as +`Self::Value`. The [derive's page](../derives/derive_from_variant.md) covers this with the family's other +reserved names. + +**Every variant needs exactly one unnamed payload**, which is the derive's requirement rather than the trait's — +a unit, multi-field, or struct-style variant cannot be given a single `Value`. Wrap the payload in its own +struct. + +## Related constructs + +- [`#[derive(FromVariant)]`](../derives/derive_from_variant.md) — generates the per-variant impls; what you + write. +- [`ExtractField`](./extract_field.md) — the reverse operation, and the trait most often derived alongside. +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this with the extractor and the shape. +- [`HasBuilder`](./has_builder.md) — the struct analogue: setting one field rather than choosing one variant. +- [`Symbol!`](../macros/symbol.md) — the tag that names a variant. +- [`CanUpcast`](./cast.md) — widening a narrow enum into a wider one, built on these constructors. +- [`HasFields`](./has_fields.md) — the variant shape a cast walks while rebuilding. +- [Dispatch combinators](../providers/dispatch_combinators.md) — where variant construction meets routing. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — construction by name, and building through a + small local enum before widening. + +## Source + +- Trait: [`from_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_variant.rs) +- Derive codegen: [`cgp_data/derive_from_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_from_variant.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/has_builder.md b/docs/reference/traits/has_builder.md index 22371e87..85ec21e2 100644 --- a/docs/reference/traits/has_builder.md +++ b/docs/reference/traits/has_builder.md @@ -6,12 +6,326 @@ sidebar_label: 'HasBuilder' The incremental-builder trait family behind the extensible builder pattern. -:::info +## What it's for -### Not written yet +A struct literal supplies every field at once, in one place that names the type. This family is for the case +where that is impossible: the fields come from several independent places, none of which should know the whole +struct, and the result must still be checked at compile time. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +The family's defining idea is that **field presence lives in the type**. A half-built value is a *different +type* from a finished one, and the trait that turns a partial value back into the concrete struct is +implemented only for the fully-present configuration. So finalizing early is a missing impl rather than a +runtime panic: + +```rust +let person = Person::builder() // every field absent + .build_field(PhantomData::, first) + .build_field(PhantomData::, last) + .finalize_build(); // all present: this resolves +``` + +Delete a middle line and this does not compile. + +Everything here reduces to **one primitive**, `UpdateField`, which changes one field's storage from one state +to another. `BuildField` and `TakeField` are the two directions of that change, and `HasBuilder`/`IntoBuilder` +and `FinalizeBuild` are the entry and exit points. The impls come from +[`#[derive(BuildField)]`](../derives/derive_build_field.md), which also generates the partial companion type +they all operate on. + +## Using it + +Most of the family is in the prelude — `HasBuilder`, `IntoBuilder`, `UpdateField`, `BuildField`, +`PartialData`, `FinalizeBuild`. The exception is **`TakeField`, which is not**; import it from +`cgp::core::field::traits` when you call `take_field` directly. + +### The entry points + +Two traits obtain a partial value to build into, differing in where they start: + +```rust +pub trait HasBuilder { + type Builder; + fn builder() -> Self::Builder; +} + +pub trait IntoBuilder { + type Builder; + fn into_builder(self) -> Self::Builder; +} +``` + +`HasBuilder::builder()` gives a partial value with **every field absent**. `IntoBuilder::into_builder(self)` +goes the other way, turning an existing value into a partial one with **every field present** — which is what +you want when redistributing a struct's fields rather than assembling one. + +### The primitive + +`UpdateField` is what everything else is built from. It moves the field named by `Tag` from its +current marker to the new marker `M`, both [`MapType`](./map_type.md) markers, and returns the old value +alongside the rebuilt partial value: + +```rust +pub trait UpdateField { + type Value; + type Mapper: MapType; // the field's marker before the update + type Output; // the partial value with the field now in state M + + fn update_field( + self, + _tag: PhantomData, + value: M::Map, + ) -> (::Map, Self::Output); +} +``` + +The `Map<…>` wrappers are the field's value *as stored* under each marker: `IsPresent` stores the value +itself, `IsNothing` stores `()`. So setting an absent field takes the real value in and hands `()` back, and +removing a present one takes `()` in and hands the real value back. + +### The two directions + +`BuildField` and `TakeField` are blanket impls over that primitive, each pinning one transition: + +```rust +pub trait BuildField { + type Value; + type Output; + fn build_field(self, _tag: PhantomData, value: Self::Value) -> Self::Output; +} + +pub trait TakeField { + type Value; + type Remainder; + fn take_field(self, _tag: PhantomData) -> (Self::Value, Self::Remainder); +} +``` + +`BuildField` is the `IsNothing → IsPresent` direction — set a currently-absent field — and `TakeField` is +`IsPresent → IsNothing` — remove a currently-present one. Because each requires a specific starting marker, the +compiler rejects building a field that is already set or taking one that is absent. + +### The exit + +```rust +pub trait PartialData { + type Target; +} + +pub trait FinalizeBuild: PartialData { + fn finalize_build(self) -> Self::Target; +} +``` + +`PartialData::Target` names the struct being built and is implemented for **every** configuration, which is how +generic builder code knows the destination before the build is complete. `FinalizeBuild` is implemented for +**only** the all-present configuration, which is the safety argument in one line. + +## Examples + +The everyday shape is `builder()`, some `build_field` calls, and `finalize_build`, with `build_from` copying +every shared field from another record in one step: + +```rust +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +// `build_from` walks the *source's* field list, so the source needs `HasFields` too. +#[derive(HasFields, BuildField)] +pub struct FooBar { + pub foo: u64, + pub bar: String, +} + +#[derive(BuildField)] +pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, +} + +fn extend(foo_bar: FooBar) -> FooBarBaz { + FooBarBaz::builder() // all absent + .build_from(foo_bar) // foo, bar now present + .build_field(PhantomData::, true) // baz now present + .finalize_build() // only the all-present impl applies +} +``` + +Every line changes the partial *type*, and the last one type-checks only because every marker has reached +present. Reorder them so `finalize_build` runs before `baz` is set and it is a compile error. + +The reverse direction takes a finished value apart and puts it back, which is what generic code +redistributing fields does: + +```rust +use cgp::core::field::traits::TakeField; + +let builder = person.into_builder(); // all present + +let (first_name, remainder) = builder.take_field(PhantomData::); +// `remainder` is missing first_name, so it cannot be finalized + +let person = remainder + .build_field(PhantomData::, first_name) + .finalize_build(); // all present again +``` + +A field that has been set can also be read back mid-build, because the derive emits a +[`HasField`](./has_field.md) impl on the partial type gated on presence: + +```rust +let partial = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()); + +assert_eq!(partial.get_field(PhantomData::), "Alice"); +``` + +Asking for `last_name` there would not compile. + +## When to reach for it, and when not + +**Use the methods; bound on the traits only in generic code.** In concrete code you call `builder()`, +`build_field`, and `finalize_build` and never name a trait. The traits matter when you write code that is +generic over the record being built — which is the extensible builder pattern, and the reason the family exists. + +- **Bound on `HasBuilder` + `BuildField` + `FinalizeBuild`** to write a routine that assembles some record it + does not name. +- **Bound on `PartialData`** when you need the destination type mid-build, before the value is complete. +- **Bound on `UpdateField` directly** only for an operation neither `BuildField` nor `TakeField` covers — such + as a transition to or from `IsOptional`, which is what the + [optional-field extensions](./optional_fields.md) do. +- **Do not reach for any of it for a struct you build with a literal.** A literal is already checked for + completeness, reads better, and generates nothing. This family buys *decoupling*, and with nothing to + decouple it is pure cost. + +Two boundaries are worth stating plainly. This is **not a conventional builder**: it tracks presence and +nothing else — no defaults, no validation at finalize, no optional field unless the field's own type is +optional. The [optional-field extensions](./optional_fields.md) cover the defaulted and optional cases, and a +hand-written builder remains better when the *logic* is the point. And the enum counterparts are a different +family: [`ExtractField`](./extract_field.md) for taking a value apart and +[`FromVariant`](./from_variant.md) for constructing one. + +## Under the hood + +:::note + +### Advanced + +This section shows how presence is encoded and why finalizing early fails. You do not need it to use the +builder, but the partial type appears by name in every builder error, so recognizing it turns "no method named +`finalize_build`" into a legible message. ::: + +The derive generates a companion struct — `__Partial{Name}` — that is your struct with one +[`MapType`](./map_type.md) parameter added per field and each field's type wrapped in that parameter's +projection: + +```rust +pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { + pub first_name: <__F0__ as MapType>::Map, + pub last_name: <__F1__ as MapType>::Map, +} +``` + +The marker in each position decides the storage: `IsPresent` holds the value, `IsNothing` holds `()`, `IsVoid` +holds the uninhabited `Void`. Then the two impls that make the whole thing safe: + +```rust +impl HasBuilder for Person { + type Builder = __PartialPerson; // the empty builder + // ... +} + +impl FinalizeBuild for __PartialPerson { // only at all-present + // ... +} +``` + +`builder()` starts at all-absent, each `build_field` flips one marker, and `finalize_build` exists only at +all-present. There is no check to run — the impl simply is not there for an incomplete value. + +The per-field `UpdateField` impl is what does the flipping, and note that only the named field's marker moves +while the rest stay generic — which is why fields can be built in any order: + +```rust +impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> + UpdateField for __PartialPerson<__M1__, __F1__> +{ + type Value = String; + type Mapper = __M1__; // the marker before + type Output = __PartialPerson<__M2__, __F1__>; // and after + // ... +} +``` + +**Neither `BuildField` nor `TakeField` is generated.** Both are library blanket impls over that one +`UpdateField`, in opposite directions — `BuildField` over +`UpdateField` and `TakeField` over +`UpdateField` — which is why `UpdateField`, the general form, is what the +derive actually writes. `FinalizeBuild` is likewise a library subtrait of `PartialData`; the derive supplies +only its all-present impl. + +`TakeField` is also the trait behind bulk merging: `CanBuildFrom`'s `build_from` recurses over the source's +field list, taking each field out and building it into the target. + +## Gotchas + +**`TakeField` is not in the prelude.** Import it from `cgp::core::field::traits`. `CanBuildFrom`, which +provides `build_from`, comes from `cgp::core::field::impls`. + +**`build_from` needs [`HasFields`](./has_fields.md) on the *source*.** It walks the source's field list to know +what to copy, so a source deriving only `BuildField` cannot be merged into anything. The target needs only the +builder. This is the easiest thing here to get wrong, because deriving the same thing on both looks symmetric. + +**"No method named `finalize_build`" is the expected error for an incomplete build.** A missing field means the +all-present impl does not apply, so the compiler reports a missing method rather than a missing field. Read the +partial type in the message to see which marker is still `IsNothing`. + +**The partial type cannot be printed or cloned.** The derive clears the original's attributes, so no `Debug`, +no `Clone`, whatever the record derives. Read a set field through the partial type's +[`HasField`](./has_field.md) impl instead. + +**There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible default +still has to be set, unless you reach for the [optional-field extensions](./optional_fields.md). + +**Field *names* are the whole interface for merging.** `build_from` matches by name, so renaming a field in one +struct silently stops it being copied — and the failure surfaces at `finalize_build`, not at the rename. + +## Related constructs + +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the partial type and every impl here. +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this family with the field access and the + shape. +- [`MapType`](./map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers presence is encoded in. +- [`HasField`](./has_field.md) — how a set field is read back off a partial value. +- [`HasFields`](./has_fields.md) — the shape `build_from` walks, and what a merge source needs. +- [`CanUpcast`](./cast.md) — where `CanBuildFrom` and `build_from` are documented. +- [Optional fields](./optional_fields.md) — defaulted and optional finalization, layered on `UpdateField`. +- [`ExtractField`](./extract_field.md) and [`FromVariant`](./from_variant.md) — the enum counterparts. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that run several builder + implementations and merge their outputs. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder + pattern. + +## Source + +- [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs) + — `HasBuilder`, `IntoBuilder` +- [`update_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/update_field.rs) + — `UpdateField`, the primitive +- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs) + — `BuildField`, `FinalizeBuild` +- [`take_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/take_field.rs) + — `TakeField` +- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs) + — `PartialData` +- [`build_from.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/build_from.rs) + — `CanBuildFrom` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/has_field.md index 90b8e22b..85a1ba6e 100644 --- a/docs/reference/traits/has_field.md +++ b/docs/reference/traits/has_field.md @@ -6,12 +6,294 @@ sidebar_label: 'HasField' Tag-keyed field access, with `HasFieldMut` and the provider-side `FieldGetter`. -:::info +## What it's for -### Not written yet +An implementation written against a **context** — the type the capability runs against, which supplies the +values it needs as its fields — is generic over that context and cannot name its concrete type. So it cannot +write `self.name`. Yet reading a value out of the context is the commonest thing such an implementation does. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`HasField` is the trait that closes the gap. The field's *name* becomes a type, and the implementation +asks for it as an ordinary trait bound: + +```rust +Self: HasField +``` + +Any context with a matching field satisfies that bound. Nothing is compared by string at runtime — +[`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler resolves which field is meant and the read +compiles to a direct field access. + +This is the foundation the whole ergonomic surface stands on. An +[`#[implicit]`](../attributes/implicit.md) argument, a [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) +method, and a [`UseField`](../providers/use_field.md) wiring entry all generate this bound from a name you +already wrote. **You will read `HasField` far more often than you write it**, and the impls themselves come +from [`#[derive(HasField)]`](../derives/derive_has_field.md). + +## Using it + +Everything on this page except `MapField` and `FieldMapper` is in the prelude, so `use cgp::prelude::*;` is +enough for the common cases. The family divides into a consumer side you bound against and a provider side +that gets wired. + +### The consumer side + +`HasField` carries the field's type as an associated `Value` and hands back a reference: + +```rust +pub trait HasField { + type Value; + + fn get_field(&self, _tag: PhantomData) -> &Self::Value; +} +``` + +The `PhantomData` argument carries nothing. It exists so a call site can say *which* field it means when +several impls are in scope, which is why reads are written `self.get_field(PhantomData::)`. + +A named field is keyed by [`Symbol!("field_name")`](../macros/symbol.md); a tuple field by +[`Index`](../types/index.md). + +`HasFieldMut` is the mutable extension, a supertrait of `HasField`: + +```rust +pub trait HasFieldMut: HasField { + fn get_field_mut(&mut self, tag: PhantomData) -> &mut Self::Value; +} +``` + +Both carry diagnostic notes pointing a reader at +[`#[derive(HasField)]`](../derives/derive_has_field.md) when the bound is unsatisfied, so a missing field reads +as a missing derive rather than an opaque trait failure. + +### The provider side + +Field access can be *wired* rather than only implemented on the context, which needs the provider-trait shape: +the context as an explicit argument instead of `&self`. + +```rust +pub trait FieldGetter { + type Value; + + fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value; +} + +pub trait MutFieldGetter: FieldGetter { + fn get_field_mut(context: &mut Context, tag: PhantomData) -> &mut Self::Value; +} +``` + +This is the ordinary consumer/provider duality: you *bound* against `HasField`, and you *wire* +`FieldGetter`. [`UseField`](../providers/use_field.md) is the provider that implements it by reading a named +field, and it is what [`#[cgp_getter]`](../macros/cgp_getter.md) targets. + +### The lifetime helpers + +`MapField` and `FieldMapper` are the two members **not** in the prelude — import them from +`cgp::core::field::traits`. They exist for one reason, and it is a lifetime-inference problem rather than a +capability: chaining `context.get_field().get_field()` would force the intermediate `Value` to be `'static`. +Passing a closure instead lets the compiler infer the right lifetime: + +```rust +pub trait MapField: HasField { + fn map_field( + &self, + _tag: PhantomData, + mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, + ) -> &T; +} + +pub trait FieldMapper: FieldGetter { + fn map_field( + context: &Context, + _tag: PhantomData, + mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, + ) -> &T; +} +``` + +You will not normally call either. [`ChainGetters`](../providers/chain_getters.md) is what uses `map_field`, +which is how a getter reaches a field on a nested context. + +## Examples + +An implementation states the field it needs and reads it: + +```rust +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData::)); + } +} + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} +``` + +`Person` derives the access, so it satisfies exactly the bound `GreetHello` requires and the wiring compiles. + +**Written idiomatically, none of that bound is visible.** The same read is an +[`#[implicit]`](../attributes/implicit.md) argument: + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } +} +``` + +which generates the identical bound and the identical read. The explicit form above is what you meet in an +error message or an expansion, not what you type. + +Field access also passes through smart pointers with no extra work, because the trait carries a `Deref` +forwarding impl: + +```rust +let boxed: Box = Box::new(Person { name: "Alice".to_owned() }); + +assert_eq!(boxed.get_field(PhantomData::), "Alice"); +``` + +## When to reach for it, and when not + +**Bound against `HasField` only when the ergonomic constructs cannot do the job**, which is rarely. The +ordering is settled and worth following. + +- **Use an [`#[implicit]`](../attributes/implicit.md) argument by default.** It reads a field of the + implementation's own context as a plain parameter, generating this bound for you. It covers the common case, + including a field several implementations each read. +- **Use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md)** when the read must be a *named* capability, + when the field lives on a type other than the context, or when the getter should carry a type inferred from + the field — the three cases an implicit argument cannot reach. +- **Use [`#[cgp_getter]`](../macros/cgp_getter.md) with [`UseField`](../providers/use_field.md)** only when a + context needs to choose *which* field the getter reads. That is the advanced case and costs a wiring line + per context. +- **Write the bound by hand** when none of those fit — a bound on a type that is not `Self`, say. It is an + ordinary trait bound, and `Value = T` pins the field's type. + +Two neighbours are easy to confuse with it. [`HasFields`](./has_fields.md) — plural — is the whole-shape view, +for code that must process *every* field rather than one named one; the two are complementary and often +derived together. And `FieldGetter` is not an alternative to `HasField` but its provider-side mirror: you do +not choose between them, you bound against one and wire the other. + +## Under the hood + +:::note + +### Advanced + +This section shows the blanket impls that make the access compose. You do not need it to read a field, but a +missing field is reported against the generated bound with the tag fully expanded, so recognizing the shape +makes that error legible. ::: + +The per-field impls come almost entirely from +[`#[derive(HasField)]`](../derives/derive_has_field.md). What the trait module itself supplies is the blanket +impls that let the access compose, and there are four worth knowing. + +**Smart-pointer forwarding.** `HasField` is implemented for any type whose +[`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) target implements it, so a `Box` or a +newtype resolves a read to the inner struct. `HasFieldMut` carries the analogous `DerefMut` impl, with the +target additionally bounded `'static`. Both are marked so the compiler does **not** suggest them in a +diagnostic — which is what keeps a missing-field error pointed at the struct that lacks the field rather than +at the pointer. + +**`UseContext` as a field getter.** The provider side connects to wiring through one impl: `UseContext` +implements `FieldGetter` for any context that already has the field, delegating straight through. + +```rust +impl FieldGetter for UseContext +where + Context: HasField, +{ + type Value = Field; + + fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value { + context.get_field(PhantomData) + } +} +``` + +**The lifetime helpers are free.** `MapField` is a blanket impl for every `HasField` whose tag is `'static`, +and `FieldMapper` for every `FieldGetter` with the getter and tag `'static`. So every getter gains +`map_field` without anyone implementing it, which is what [`ChainGetters`](../providers/chain_getters.md) +relies on. + +## Gotchas + +**Two spellings of a name are unrelated types.** `Symbol!("first_name")` and `Symbol!("firstName")` have +nothing to do with each other, and a mismatch reports as a missing `HasField` bound rather than as a typo. +This is the usual cause of a read that "should" work. + +**`MapField` and `FieldMapper` are not in the prelude.** Import them from `cgp::core::field::traits`. Every +other trait on this page is in the prelude. + +**A tuple field is keyed by [`Index`](../types/index.md), never by a `Symbol!` of the number.** `Index<0>` +and `Symbol!("0")` are different types. + +**The mutable accessor is not separately opt-in.** `#[derive(HasField)]` always emits `HasFieldMut` beside +`HasField`, so there is no derive-level way to make a field read-only. Restricting mutation is a matter of +what the implementations declare. + +**`Value` is an associated type, so it can be pinned or left open.** Writing +`HasField` alone accepts a field of any type; adding `Value = String` requires that type. +Omitting it when you meant to pin it produces an inference failure further along rather than at the bound. + +**The `PhantomData` argument is required and carries the tag.** `self.get_field(PhantomData)` works only where +inference can determine the tag from context; at an ambiguous site write `PhantomData::`. + +## Related constructs + +- [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates the per-field impls; what a context + writes. +- [`HasFields`](./has_fields.md) — the plural, whole-shape counterpart. +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that key a field. +- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to read a field. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../macros/cgp_getter.md) — getter + traits over the same access. +- [`UseField`](../providers/use_field.md) — the provider-side implementation of `FieldGetter`. +- [`ChainGetters`](../providers/chain_getters.md) — composes getters through `map_field` to reach a nested + field. +- [`HasBuilder`](./has_builder.md) — where `HasField` reappears on a partial record, gated on presence. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on the + implementation rather than the interface. +- [Implicit arguments](/docs/concepts/implicit-arguments) — the ergonomic surface built on this trait. + +## Source + +- [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) + — `HasField`, `FieldGetter`, the `Deref` forwarding, and the `UseContext` impl +- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs) + — `HasFieldMut`, `MutFieldGetter`, the `DerefMut` forwarding +- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs) + — `MapField` and `FieldMapper` +- [`use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs) + — the `UseField` provider + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/has_fields.md index cb80650a..7331a667 100644 --- a/docs/reference/traits/has_fields.md +++ b/docs/reference/traits/has_fields.md @@ -6,12 +6,288 @@ sidebar_label: 'HasFields' The whole-shape field representation and its conversions. -:::info +## What it's for -### Not written yet +Some code needs one field of a type. Other code needs the *shape* — every field, its name, and its type — so +it can walk them: a serializer, a validator, a builder that merges two structs, a dispatcher that routes an +enum to a handler per variant. None of those can be written one field at a time, and none can name the +concrete type either. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`HasFields` gives a type that shape as a single associated type. Where [`HasField`](./has_field.md) — +singular — answers *"give me this field"*, `HasFields` answers *"describe all of them at once"*: + +```rust +type Fields = Product![ + Field, + Field, +]; +``` + +That is the struct written as a type: a [`Product!`](../macros/product.md) list with one +[`Field`](../types/field.md) entry per field, each pairing a value type with its type-level name. For an enum +it is a [`Sum!`](../macros/sum.md) instead — the same idea for a choice rather than a combination. + +Four companion traits turn that description into a two-way door. `HasFieldsRef` names the borrowed shape, and +`ToFields`, `FromFields`, and `ToFieldsRef` convert between a concrete value and it — so generic code can take +a value apart, work on the anonymous form, and put a concrete value back together. + +**The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md).** What you write is the +derive; what you bound against is the trait. + +## Using it + +All five traits are in the prelude. Two name a shape and three convert to or from it. + +### The shape traits + +```rust +pub trait HasFields { + type Fields; +} + +pub trait HasFieldsRef { + type FieldsRef<'a> + where + Self: 'a; +} +``` + +`Fields` is the owned shape and `FieldsRef<'a>` the same shape with each value borrowed for `'a`. Both are +associated types and nothing else — there is no method, because describing a type is not an operation. + +The shape's construction follows one rule everywhere: a named field or variant is keyed by +[`Symbol!`](../macros/symbol.md), a positional field by [`Index`](../types/index.md), a struct becomes a +`Cons`/`Nil` product, and an enum becomes an `Either`/`Void` sum. A single-field tuple struct is the one +special case — its `Fields` is the inner type directly rather than a one-element product — and the +[derive's page](../derives/derive_has_fields.md) covers that and the other shapes in full. + +### The conversion traits + +Each supertraits one of the two shape traits and adds a single method: + +```rust +pub trait ToFields: HasFields { + fn to_fields(self) -> Self::Fields; +} + +pub trait FromFields: HasFields { + fn from_fields(fields: Self::Fields) -> Self; +} + +pub trait ToFieldsRef: HasFieldsRef { + fn to_fields_ref<'a>(&'a self) -> Self::FieldsRef<'a> + where + Self: 'a; +} +``` + +`to_fields` **consumes** the value to produce the owned shape, `from_fields` consumes the shape to rebuild the +value, and `to_fields_ref` **borrows** — which is the one to reach for when the original value must survive. + +### Bounding on the shape + +The point of all this is a bound. Generic code writes `T: HasFields` and recurses over `T::Fields`, so it +applies to any type that derives the shape — including one declared in another crate: + +```rust +fn shape_of(value: T) -> T::Fields +where + T: HasFields + ToFields, +{ + value.to_fields() +} +``` + +Which of the five to require depends on what the code does: `HasFields` alone to *name* the shape, +`ToFields`/`FromFields` to move owned values through it, `ToFieldsRef` to read without consuming. + +## Examples + +Deriving it alongside [`HasField`](./has_field.md) is the common pairing, giving one struct both indexed and +structural access: + +```rust +use cgp::prelude::*; + +#[derive(Clone, Debug, Eq, PartialEq, HasField, HasFields)] +pub struct Config { + pub host: String, + pub port: u16, +} +``` + +`Config::Fields` is now `Product![Field, Field]`, and a value +round-trips through it: + +```rust +let config = Config { host: "localhost".to_owned(), port: 8080 }; + +let fields = config.clone().to_fields(); // Config -> the product +let config_again = Config::from_fields(fields); // the product -> Config + +assert_eq!(config, config_again); +``` + +The borrowing form leaves the value intact, which is what read-only generic code uses: + +```rust +let fields_ref = config.to_fields_ref(); + +assert_eq!(fields_ref.0.value, &"localhost".to_owned()); +``` + +An enum's shape is a sum rather than a product, and the same conversions apply: + +```rust +#[derive(HasFields)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +giving `Sum![Field, Field]`. + +## When to reach for it, and when not + +**Bound on `HasFields` when code must process a type's whole shape; bound on +[`HasField`](./has_field.md) when it needs one named field.** That is the entire distinction, and the two are +complementary rather than ranked — most types that need both derive both in one `#[derive(...)]`. + +The finer question is which of the five to require, and being precise pays because each one narrows what a +caller must supply. + +- **`HasFields` alone** when the code only names the shape — a `where` clause, an associated-type projection, + a type-level computation like those in [`AppendProduct`](./product_ops.md). +- **`ToFields` and `FromFields`** when values move through the shape in both directions, which is what a + structural conversion needs. +- **`ToFieldsRef`** when the value must not be consumed. Requiring `ToFields` where a borrow would do forces + callers to clone. + +Two things this is not. It is **not runtime reflection**: a type has a shape only because it opted in with a +derive, there is nothing to query at run time, and the shape is a type rather than data. What that buys is +static checking and no runtime cost; what it costs is that a foreign type you cannot patch has no shape at +all. And it is **not the whole extensible-data story** — the shape describes a type, while building one up +field by field or taking one apart variant by variant is the +[builder](./has_builder.md) and [extractor](./extract_field.md) families, bundled with this one by +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). + +## Under the hood + +:::note + +### Advanced + +This section shows what the shape expands to. You do not need it to bound on the trait, but the `Fields` type +appears verbatim in compiler errors about structural code, so reading one makes those errors legible. +`cargo cgp expand` prints it resugared for your own code. ::: + +The trait module defines only the bare trait shapes; all five impls come from +[`#[derive(HasFields)]`](../derives/derive_has_fields.md). The load-bearing part is what the derive puts in +`Fields`, and the sugar hides one level of structure: + +```rust +impl HasFields for Person { + type Fields = Product![ + Field, + Field, + ]; +} +``` + +`Product![A, B]` is `Cons>`, so the conversions build and match a `Cons` chain: + +```rust +impl ToFields for Person { + fn to_fields(self) -> Self::Fields { + Cons(self.name.into(), Cons(self.age.into(), Nil)) + } +} + +impl FromFields for Person { + fn from_fields(Cons(name, Cons(age, Nil)): Self::Fields) -> Self { + Self { name: name.value, age: age.value } + } +} +``` + +That `Cons` spine is what an error message prints, and the +[type-level spines](../types/type_level_spines.md) page covers reading it. + +The borrowed shape uses a reserved lifetime name, `'__a`, so it cannot collide with a lifetime of yours: + +```rust +impl HasFieldsRef for Person { + type FieldsRef<'__a> = Product![ + Field, + Field, + ] + where + Self: '__a; +} +``` + +An enum's shape is the dual — an `Either` chain terminated by `Void` rather than a `Cons` chain terminated by +`Nil` — with each arm tagged by the variant name and carrying that variant's own fields as a nested product. +The two conversions match each concrete variant onto its arm and back. + +`from_fields` and `to_fields` round-trip through the identical `Fields` type, so generic code can decompose, +transform, and rebuild with the shapes lining up by construction rather than by check. + +## Gotchas + +**`HasFields` and [`HasField`](./has_field.md) differ by one letter and do not overlap.** The plural is the +whole shape and takes structs and enums; the singular is per-field access and takes only structs. Their +derives are likewise distinct. + +**`to_fields` consumes the value.** Reach for `to_fields_ref` when you need to keep it. This is the commonest +surprise, because the two read alike. + +**A newtype's shape is the inner type, not a one-element product.** `struct Wrapper(String)` has +`Fields = String`. Generic code written against a `Cons` chain will not match it — the +[derive's page](../derives/derive_has_fields.md) has the rule and the other shapes. + +**Field order is declaration order and is part of the type.** Two structs with the same names in different +orders have different `Fields` types. Name-driven conversions cope; code written against a literal `Cons` +chain does not. + +**The borrowed shape layers borrows rather than collapsing them.** A field already of type `&'a Name` appears +as `&'__a &'a Name` in `FieldsRef`, which is correct and occasionally surprising in an error. + +**Two enum variant names are reserved.** A variant called `Fields` or `FieldsRef` collides with these +associated types and the derive fails; the [derive's page](../derives/derive_has_fields.md) lists it with the +other reserved names. + +## Related constructs + +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates all five impls; what you write. +- [`HasField`](./has_field.md) — the singular counterpart, per-field access. +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this with the builder and extractor. +- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a shape is built from. +- [`Field`](../types/field.md) — one entry: a value paired with its type-level name. +- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. +- [`AppendProduct`](./product_ops.md) — the operations that compute new shapes from old ones. +- [`CanUpcast`](./cast.md) — conversions between two types whose shapes overlap, driven by this one. +- [`HasBuilder`](./has_builder.md) and [`ExtractField`](./extract_field.md) — building and deconstructing, + rather than describing. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum half, and the expression problem. + +## Source + +- [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs) + — `HasFields`, `HasFieldsRef` +- [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs) + — `ToFields`, `ToFieldsRef` +- [`from_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_fields.rs) + — `FromFields` +- Derive codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/is_provider_for.md b/docs/reference/traits/is_provider_for.md index aca350d5..efb791a4 100644 --- a/docs/reference/traits/is_provider_for.md +++ b/docs/reference/traits/is_provider_for.md @@ -6,12 +6,253 @@ sidebar_label: 'IsProviderFor' The marker supertrait that makes a provider's missing dependency show up by name. -:::info +## What it's for -### Not written yet +An implementation in CGP states what it needs from its **context** — the type the capability runs against — +in its own `where` clause: a field, an abstract type, another capability. When one of those requirements is +not met, you want the compiler to say *which*. Left to itself, it will not. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +The reason is a specific behaviour of Rust's diagnostics. Asking "does this provider implement the provider +trait?" has two candidate answers in scope — the blanket impl that routes through the wiring table, and the +implementation you wrote — and when more than one impl could apply, Rust reports only that none matched and +withholds the per-candidate reasoning, because it cannot know which one you meant. The real cause, often a +single absent field, never appears. + +`IsProviderFor` is a second path to the same question that Rust *will* explain. It is an empty marker trait, +and the macros implement it for a provider under **exactly the same** `where` bounds as the provider trait +itself. Every generated provider trait carries it as a supertrait, so asking whether a provider satisfies +`IsProviderFor` forces the compiler to evaluate those bounds — and because that question has only one +candidate impl, no blanket competing with it, the compiler commits to it and reports precisely which +constraint failed. + +**This is invisible plumbing until you read an error.** You never write it and never call it. What it buys is +the difference between "the trait is not implemented" and "the field `name` is missing on `App`", and it is +the mechanism [`check_components!`](../macros/check_components.md) leans on to produce the second. + +## Using it + +The trait is in the prelude, so `use cgp::prelude::*;` names it. It is empty, with three parameters: + +```rust +pub trait IsProviderFor {} +``` + +The four types together identify one provider-trait implementation. `Self` is the **provider** whose validity +is asserted. `Component` is the component-name marker, the same key the wiring table uses. `Context` is the +context the provider trait is implemented for. `Params` collects the component's own extra generic +parameters. + +### How `Params` is filled + +This is the only part with a rule worth memorizing, and it is what a hand-written assertion gets wrong. + +- A component with **no** parameters uses the default, `()`. +- A component with **one** parameter passes it directly — `IsProviderFor`. +- A component with **several** groups them into a tuple — `IsProviderFor`. +- A **lifetime** parameter is lifted into [`Life<'a>`](../types/life.md), because the tuple holds types and a + lifetime cannot sit there directly. + +### Asserting it + +You do not implement the trait; you occasionally *assert* it, which is a `where` bound on an empty function: + +```rust +fn assert_provider() +where + GreetHello: IsProviderFor, +{} +``` + +That holds exactly when `GreetHello`'s dependencies are satisfied for `App`. In practice you write this +through the `#[check_providers(...)]` form of [`check_components!`](../macros/check_components.md) rather +than by hand — which is the tool for localizing a failure inside a stack of +[higher-order providers](/docs/concepts/higher-order-providers), where checking the context tells you a layer +is broken but not which one. + +## Examples + +The trait is something you observe. A provider that needs a field gets a matching marker impl automatically: + +```rust +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} +``` + +`#[cgp_impl]` emits the `Greeter` impl *and* an `IsProviderFor` impl for +`GreetHello`, both guarded by the same `Self: HasName` bound. Now wire it onto a context that cannot satisfy +that bound: + +```rust +#[derive(HasField)] +pub struct App { + pub first_name: String, // not `name` +} + +delegate_components! { + App { GreeterComponent: GreetHello } +} + +check_components! { + App { GreeterComponent } +} +``` + +The check forces `App: CanUseComponent`, which routes through +`GreetHello: IsProviderFor`, whose `where` clause names the `HasName` +requirement — so the error names the absent field, at the wiring site. Remove the `check_components!` block +and the same mistake surfaces far away, at whatever calls `app.greet()`, as a much worse message. + +## When to reach for it, and when not + +**Do not reach for it. Recognize it.** There is no case in ordinary CGP code where you write +`IsProviderFor`: the provider macros emit the impl, `#[cgp_component]` emits the supertrait link, and +[`delegate_components!`](../macros/delegate_components.md) emits the forwarding. What you do with it is read +it in an error and, occasionally, assert it through a check. + +Two situations do put its name in your hands, and both are about diagnosis rather than construction. + +- **Localizing a broken layer in a higher-order provider stack.** Checking the context proves *something* + in the stack is unsatisfied. `#[check_providers(...)]` asserts `IsProviderFor` on each named provider + instead, so a dependency missing only from the outer wrapper errors on its line alone while one missing + from the inner provider errors on both — which pins the layer. +- **Reading a `[CGP-Exxx]` diagnostic.** `cargo cgp check` names this trait in the dependency chain it + renders, and knowing that a frame means "this provider's requirements, for this context" is what makes + the chain readable. + +If you find yourself wanting to implement it by hand, the thing you actually want is +[`#[cgp_provider]`](../macros/cgp_provider.md) or [`#[cgp_impl]`](../macros/cgp_impl.md) on the impl block — +the trait's own diagnostic says so, which is the one case where a missing marker impl is the reported +problem rather than the hidden one. + +## Under the hood + +:::note + +### Advanced + +This section shows where the three generated pieces come from. You do not need it to write CGP, but every +non-trivial wiring error names this trait, and the three-part chain is what those errors are walking. +`cargo cgp expand` prints all three for your own code. ::: + +`IsProviderFor` appears in three places, and together they form the chain an error travels along. + +**First, the supertrait link.** [`#[cgp_component]`](../macros/cgp_component.md) emits every provider trait +with the marker as a supertrait, so for a component `CanGetFooAt` the provider trait reads: + +```rust +pub trait FooGetterAt: + IsProviderFor +{ /* … */ } +``` + +This is what binds a provider's dependency set to the marker: using the provider trait *requires* +establishing `IsProviderFor` first, so probing the marker is equivalent to probing the provider trait. + +**Second, the per-provider impl.** [`#[cgp_provider]`](../macros/cgp_provider.md) and +[`#[cgp_impl]`](../macros/cgp_impl.md) emit an empty impl beside the provider trait impl, carrying identical +bounds: + +```rust +impl Greeter for GreetHello +where + Context: HasName, +{ /* … */ } + +impl IsProviderFor for GreetHello +where + Context: HasName, +{} +``` + +Identical `where` clauses mean the marker is satisfiable exactly when the provider trait is — which is the +whole trick. + +**Third, the table forwarding.** [`delegate_components!`](../macros/delegate_components.md) emits, for each +entry, an impl on the table that forwards to the delegated provider's marker: + +```rust +impl IsProviderFor for AppComponents +where + GreetHello: IsProviderFor, +{} +``` + +Because this is an explicit impl rather than a blanket, the compiler follows it and surfaces everything +`GreetHello` requires. It is also what carries requirements *across layers*: when a provider bundle delegates +to another bundle, each forwards to the next, so a dependency unmet several tables deep still propagates back +to where the component is checked. + +One refinement is worth knowing, because it is what makes `#[check_providers]` able to localize a layer: the +clause the provider macros derive is **augmented rather than copied**. A bound naming the component's own +provider trait gains its marker counterpart, which is the mechanism that carries an inner provider's +requirements outward through a higher-order stack. + +## Gotchas + +**`Params` grouping is the usual mistake in a hand-written assertion.** One parameter goes in directly, two +or more as a tuple, none as `()`. Getting it wrong reports as an unsatisfied bound on a trait you did not +expect, rather than as a helpful arity error. + +**A lifetime parameter becomes [`Life<'a>`](../types/life.md) in the tuple.** It cannot appear as a bare +lifetime in a type position, so it is lifted. + +**A missing marker impl usually means a missing attribute.** If the compiler says a provider does not +implement `IsProviderFor`, the likeliest cause is a provider-trait impl written without +[`#[cgp_provider]`](../macros/cgp_provider.md) — the trait's own diagnostic note says exactly this. + +**Read it as "because", not as "instead".** `GreetHello: IsProviderFor<…> is not satisfied` does not mean the +marker is the problem; it means the provider trait is not implemented *because* the named dependency is +missing. The useful part of the message is the constraint underneath. + +**It is empty, so satisfying it costs nothing.** There is no method, no data, and nothing in the binary. The +only effect is the compile-time obligation its `where` clause imposes. + +**A higher-order provider with a lifetime loses the propagation.** The inner-provider bound of such a stack +gets no marker counterpart when the component carries a lifetime, because the rewrite reads the bound's first +generic argument as the context and finds a lifetime there. The stack still compiles and runs; what is lost +is the propagation that lets `#[check_providers]` localize a broken layer. + +## Related constructs + +- [`#[cgp_component]`](../macros/cgp_component.md) — attaches the marker as a supertrait on every provider + trait. +- [`#[cgp_impl]`](../macros/cgp_impl.md) and [`#[cgp_provider]`](../macros/cgp_provider.md) — emit the + per-provider impl beside the provider trait impl. +- [`delegate_components!`](../macros/delegate_components.md) — emits the forwarding impl at each table entry. +- [`DelegateComponent`](./delegate_component.md) — the table those entries live in. +- [`CanUseComponent`](./can_use_component.md) — the context-indexed counterpart, which requires this of the + delegate. +- [`check_components!`](../macros/check_components.md) — forces both; its `#[check_providers(...)]` form + asserts this trait directly. +- [Compile errors](../errors.md) — how the resulting diagnostics read, and what the tool makes of them. + +The ideas behind it: + +- [Check traits](/docs/concepts/check-traits) — why wiring is lazy and how an assertion makes its failures + readable. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the `where`-clause requirements this + trait re-exposes. + +## Source + +- Trait: [`is_provider.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/is_provider.rs) +- Supertrait link and per-provider impl: [`cgp_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component) +- Table forwarding: [`delegate_component/mapping/eval.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/delegate_component/mapping/eval.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index 1f5cdcbf..b845d5c2 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -6,12 +6,247 @@ sidebar_label: 'MapType' The present, absent, and void type-mapping markers and their transforms. -:::info +## What it's for -### Not written yet +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. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`MapType` is that marker's trait, and it has one member: + +```rust +pub trait MapType { + type Map; +} +``` + +`Map` names the storage type the marker assigns to a field whose value type is `T`. So `IsPresent::Map` +is `String`, and `IsNothing::Map` is `()`. **The marker is the field's state, expressed as a type.** + +That is what lets the [builder](./has_builder.md) and [extractor](./extract_field.md) 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. + +Three companions complete the picture. `MapTypeRef` does the same job for borrowed views, where the wrapping +also introduces a lifetime. `TransformMap` and `TransformMapFields` are the value-level side: they carry the +functions that actually convert a field from one wrapping to another. + +## Using it + +The four `MapType` markers and two of the three `MapTypeRef` markers are in the prelude. **`IsOptional` and +`IsOwned` are not** — import them from `cgp::core::field::impls`. `TransformMap` and `TransformMapFields` are +not in the prelude either; they come from `cgp::core::field::traits`. + +### The `MapType` markers + +Four markers cover the states a field passes through: + +```rust +impl MapType for IsPresent { type Map = T; } // the field holds its value +impl MapType for IsNothing { type Map = (); } // the field is absent +impl MapType for IsVoid { type Map = Void; } // the case is impossible +impl MapType for IsOptional { type Map = Option; } // 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** — which is exactly how an extractor discharges its remainder +with an empty `match`. Records use the first, variants the second. + +### The `MapTypeRef` markers + +`MapTypeRef` threads a lifetime, so the marker decides not just presence but how the value is held: + +```rust +pub trait MapTypeRef { + type Map<'a, T: 'a>: 'a; +} + +impl MapTypeRef for IsRef { type Map<'a, T: 'a> = &'a T; } +impl MapTypeRef for IsMut { type Map<'a, T: 'a> = &'a mut T; } +impl MapTypeRef for IsOwned { type Map<'a, T: 'a> = T; } +``` + +A borrowed extractor combines both families: one outer `MapTypeRef` marker shared across all fields, and one +`MapType` marker per field, so a field's storage is `MapType::Map>`. `HasExtractorRef` +fixes the outer marker to `IsRef` and `HasExtractorMut` to `IsMut`. + +**`IsOwned` has no consumer in CGP.** No derive emits it and no provider resolves against it — it is available +for a borrowed view that holds its payloads by value, and at present that view exists only if you write it +yourself. + +### The transforms + +`MapType` only names storage types. `TransformMap` carries the *function* that converts a value from one +wrapping to another: + +```rust +pub trait TransformMap { + fn transform_mapped(value: M1::Map) -> M2::Map; +} +``` + +`TransformMapFields` lifts such a transform across a whole partial record, walking the target's +[`HasFields`](./has_fields.md) shape field by field: + +```rust +pub trait TransformMapFields { + type Output; + + fn transform_map_fields(self) -> Self::Output; +} +``` + +This is the pair to reach for when you need to re-mark every field at once — which is what the +[optional-field extensions](./optional_fields.md) are built from. + +## Examples + +You mostly meet the markers inside the partial types that +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) generates, where a builder's type reads +`__PartialPerson` and tells you at a glance which fields are set. + +The transforms, though, are directly useful. A marker that fills absent fields from `Default` is one impl per +source state: + +```rust +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::TransformMap; +use cgp::prelude::*; + +pub struct FillDefaults; + +impl TransformMap for FillDefaults { + fn transform_mapped(value: T) -> T { + value + } +} + +impl TransformMap for FillDefaults { + fn transform_mapped(_value: ()) -> T { + T::default() + } +} + +impl TransformMap for FillDefaults { + fn transform_mapped(value: Option) -> T { + value.unwrap_or_default() + } +} +``` + +Read that as three cases of one rule: a present field passes through, an absent one becomes its default, and an +optional one becomes its contents or the default. Because all three target `IsPresent`, applying it through +`transform_map_fields` leaves every field present — which is precisely the configuration +[`FinalizeBuild`](./has_builder.md) accepts, turning a partially-built record into a finalizable one. + +That is not hypothetical: it is how `CanFinalizeWithDefault` in the +[optional-field extensions](./optional_fields.md) works, and reading it here is the shortest route to +understanding that layer. + +## When to reach for it, and when not + +**You will name the markers far more often than the traits.** `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 traits themselves have 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`** to define a new per-field conversion, as `FillDefaults` above does. This is the + extension point of the whole scheme, and it is genuinely usable: one impl per source marker, and + `transform_map_fields` applies it everywhere. +- **Do not implement `MapType` for a new marker** expecting the derives to use it. The generated partial types + are parameterized over markers, but only the four standard ones have transforms and finalize impls behind + them; a fifth marker is a type with no machinery attached. +- **Reach for the [optional-field extensions](./optional_fields.md) rather than writing the transform yourself** + 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 uniformly to +every entry of a type-level list, and lives with the [product operations](./product_ops.md). + +## Under the hood + +:::note + +### Advanced + +This section shows how the transform recursion works. You do not need it to read a marker in an error, but it is +what the optional-field layer is made of. ::: + +`TransformMapFields` is implemented for any [`PartialData`](./has_builder.md) and walks the target's +[`HasFields`](./has_fields.md) product one entry at a time. For each `Field` it uses +[`UpdateField`](./has_builder.md) **twice**: it takes the field out — replacing its marker with `IsNothing` and +reading what the marker was — applies `Transform::transform_mapped` to convert the value into the +`TargetMap` wrapping, then writes it back under `TargetMap`. + +So the result type has every field re-marked to `TargetMap`, with the values converted accordingly. Two things +follow from that construction, and both explain limits you might otherwise trip over. The transform must have an +impl for **every** source marker a field might currently be in, or the walk does not resolve — which is why +`FillDefaults` above needs three impls rather than one. And the recursion is driven by the *target's* shape, so +it re-marks exactly the fields the concrete struct declares. + +The markers themselves are zero-sized and carry no data. Nothing here has a runtime representation: a `MapType` +impl is a type-level function, and the only values that exist are the field values being wrapped or unwrapped. + +## Gotchas + +**`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. + +**`IsOptional` and `IsOwned` are not in the prelude.** Import them from `cgp::core::field::impls`. The other +five markers are. + +**`IsOwned` is unused by CGP.** It is a legal `MapTypeRef` marker with no consumer, so selecting it means +writing the machinery that uses it yourself. + +**`MapType` and `MapFields` are different traits.** `MapType` is one marker naming one field's storage; +[`MapFields`](./product_ops.md) applies a marker across a whole list. The names are close and the jobs are not. + +**A new marker gets you a type and nothing else.** Implementing `MapType` is easy; the derives' finalize and +transform impls are written against the standard markers, so a custom one has no machinery behind it. + +**`TransformMap` needs an impl per source state.** Writing only the `IsNothing` case leaves the recursion +unresolvable for a record with any field already present, and the error names the missing `TransformMap` impl +rather than the field. + +## Related constructs + +- [`HasBuilder`](./has_builder.md) — uses `IsPresent`/`IsNothing` to track which fields are filled. +- [`ExtractField`](./extract_field.md) — uses `IsPresent`/`IsVoid` to track which variants remain, and + `MapTypeRef` for its borrowed forms. +- [Optional fields](./optional_fields.md) — the layer built from `TransformMap` and `IsOptional`. +- [`MapFields`](./product_ops.md) — applies one marker across a whole type-level list. +- [`HasFields`](./has_fields.md) — the shape `TransformMapFields` walks. +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — generates the partial types these markers + parameterize. +- [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — presence tracking on a partial record. +- [Extensible variants](/docs/concepts/extensible-variants) — possibility tracking on a partial variant. + +## Source + +- [`map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type.rs) + and [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type_ref.rs) + — the two traits +- [`impls/map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type.rs) + — `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` +- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) + — `IsRef`, `IsMut`, `IsOwned` +- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs) + — `TransformMap`, `TransformMapFields` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monad.md b/docs/reference/traits/monad.md index 01932f93..4c6913ad 100644 --- a/docs/reference/traits/monad.md +++ b/docs/reference/traits/monad.md @@ -6,12 +6,211 @@ sidebar_label: 'Monad traits' `MonadicTrans`, `MonadicBind`, `LiftValue`, and `ContainsValue`. -:::info +## What it's for -### Not written yet +A [monadic pipeline](/docs/concepts/monadic-handlers) chains a list of steps where each step may either continue +or short-circuit — the familiar `?`-style behaviour, expressed as composable providers rather than as syntax. To +build one, the machinery needs to know three things about the monad it is running under: which branch of an +output continues, which branch stops, and how values move between them. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +A monad in CGP is a zero-sized marker — `IdentMonadic`, `OkMonadic`, `ErrMonadic`, and their transformer forms — +and these four traits are what give that marker meaning. Each answers one of the separable questions: + +- **`MonadicBind`** — given a continuation, what provider runs one bind step? +- **`ContainsValue`** — for a given output type, what value sits beneath this monad's wrapper? +- **`LiftValue`** — how does a value get back *into* that output type? +- **`MonadicTrans`** — how does this monad stack on top of another? + +Keeping them apart is what lets one marker serve all four roles, and what lets monads stack by composing their +implementations. + +**These are plain capability traits, not CGP components.** They have no generated provider trait, no +`…Component` marker, and are never wired through +[`delegate_components!`](../macros/delegate_components.md) — the [monad providers](../providers/monad_providers.md) +consume them as ordinary trait bounds while folding a pipeline at compile time. + +## Using it + +**None of the four is in the prelude.** Import them from `cgp::extra::monad::traits`. In practice you will import +them only when *defining a monad of your own*; using the existing ones means naming +[`PipeMonadic`](../providers/monad_providers.md) and a marker in a wiring entry, with no trait in sight. + +### `MonadicBind` + +```rust +pub trait MonadicBind { + type Provider; +} +``` + +The parameter is the continuation — the handler that should run on the continue branch — and the associated type +is the bind provider that wraps it. For the base monads this resolves to a `BindOk` or `BindErr` provider; for +`IdentMonadic` it is the continuation unchanged, which is what makes the identity monad free. + +### `ContainsValue` + +```rust +pub trait ContainsValue { + type Value; +} +``` + +`Output` is the full output type a step produces; `Value` is what is carried in the branch this monad threads +forward. A continuation consumes that value, or a deeper monad layer unwraps it further. + +### `LiftValue` + +```rust +pub trait LiftValue { + type Output; + + fn lift_value(value: Value) -> Self::Output; + fn lift_output(output: Output) -> Self::Output; +} +``` + +Two methods for the two branches a bind step takes. `lift_value` wraps a bare value from the continue or +short-circuit branch into the final output; `lift_output` re-wraps a value already in the inner shape, forwarding +a continuation's computed result. + +### `MonadicTrans` + +```rust +pub trait MonadicTrans { + type M; +} +``` + +`M` is the base monad being transformed and the associated `M` is the resulting stack. This is what lets +`OkMonadic` be written as `OkMonadicTrans` when a pipeline operates over a nested result, layering +one behaviour on top of another. + +## Examples + +The traits are consumed rather than called, so the thing to read is what each marker's impls *say* — because that +is what decides how a pipeline behaves. + +**`IdentMonadic` implements all four as identities**, which is why it threads every value forward and never +short-circuits. `MonadicTrans` returns `M` unchanged, `MonadicBind` returns `Provider` unchanged, +`ContainsValue::Value` is `T`, and `LiftValue` is the identity in both directions. A pipeline under +`IdentMonadic` is therefore just function composition. + +**`ErrMonadic` and `OkMonadic` are mirror images over a `Result`**, and the mirroring is the whole design: + +| | continue branch | short-circuits on | +|---|---|---| +| `ErrMonadic` | `Ok` | `Err` | +| `OkMonadic` | `Err` | `Ok` | + +For `ErrMonadic`, `ContainsValue>::Value` is `T` — the `Ok` payload threads forward — and +`lift_value` is `Ok`. For `OkMonadic` the roles swap: `Value` is `E` and `lift_value` is `Err`. So `ErrMonadic` is +the ordinary `?` behaviour, and `OkMonadic` is the inverted one that runs until something succeeds — useful for a +fallback chain. + +**The transformer forms delegate one layer down.** `OkMonadicTrans` and `ErrMonadicTrans` implement the same +traits by peeling their own `Result` layer and handing the rest to `M`, requiring +`M: ContainsValue>`. Their `MonadicTrans` impls compose, so a stack like +`OkMonadicTrans` resolves layer by layer — which is how monads reach arbitrary depth over nested +result types. + +## When to reach for it, and when not + +**Reach for the [monad providers](../providers/monad_providers.md), not these traits.** Building a pipeline means +wiring `PipeMonadic` with a monad marker and a handler list; the traits are what that provider bounds on +internally. + +The one real reason to name them is **defining a new monad**. If you need short-circuiting over a type that is not +`Result` — an `Option`, a custom two-branch enum — implementing the four traits for a new marker is the supported +extension point, and the mirror-image `OkMonadic`/`ErrMonadic` pair is the model to copy. + +And the alternatives to prefer when you do *not* need short-circuiting: + +- **[Handler combinators](../providers/handler_combinators.md)** — `ComposeHandlers` and `PipeHandlers` chain + handlers without a branch. If every step in your pipeline runs unconditionally, these are simpler and you should + not involve a monad at all. +- **Ordinary `?` in one provider body** — if the whole chain lives in a single implementation, Rust's own operator + is clearer than any composition. The monadic providers earn their keep when the *steps are separately wired*, so + each application can swap or reorder them. +- **[`TryComputer`](../components/try_computer.md) or [`Handler`](../components/handler.md)** — for a single + fallible step, the fallible members of the handler family already carry the error, and no pipeline is needed. + +## Under the hood + +:::note + +### Advanced + +This section shows how a pipeline is folded from these traits. You do not need it to use a monad, but it is what +makes the division into four traits look inevitable rather than arbitrary. ::: + +The traits divide the way they do because building a pipeline needs three separable decisions, taken at different +times. + +**Folding the list** is `MonadicTrans` and `MonadicBind`. `PipeMonadic` walks the handler list and, for each step, +asks the monad to turn the continuation built so far into a bind step. `MonadicTrans` is what applies one monad as +a transformer over another while doing so, which is how a stacked monad is resolved before any binding happens. + +**Running one step** is `ContainsValue` and `LiftValue`. The `BindOk` and `BindErr` providers use them in their +[`Computer`](../components/computer.md) and `AsyncComputer` impls: `ContainsValue` says what the underlying value +beneath the wrapper is, so the step knows what to hand the continuation, and `LiftValue` puts a result back into +the output type — `lift_value` for the branch that short-circuits, `lift_output` for the branch that forwarded to +the continuation. + +**Stacking** is `MonadicTrans` again, applied to the monads rather than to the handlers. Because the transformer +forms implement `ContainsValue` and `LiftValue` by delegating to the base monad, a two-layer stack unwraps two +`Result` layers in order, and an *n*-layer stack unwraps *n* — with no code specific to any depth. + +Pipelines built this way implement the [`Computer`](../components/computer.md) family, so they slot into the same +wiring as any other handler. The whole fold happens during trait resolution; a monadic pipeline is not a runtime +structure. + +## Gotchas + +**None of the four is in the prelude.** Import from `cgp::extra::monad::traits`. + +**`OkMonadic` short-circuits on `Ok`, not on `Err`.** The naming reads as "the monad *for* `Ok`" and means "the +monad whose continue branch is `Err`". `ErrMonadic` is the one that behaves like `?`. Getting these the wrong way +round produces a pipeline that runs exactly when you expected it to stop. + +**These are not components and cannot be wired.** There is no `…Component` marker, so they never appear in a +[`delegate_components!`](../macros/delegate_components.md) block. What gets wired is the provider that consumes +them. + +**A stack must be written in layer order.** `OkMonadicTrans` and `ErrMonadicTrans` unwrap +their `Result` layers in opposite orders and are not interchangeable. + +**`LiftValue` has two methods for a reason.** Implementing `lift_output` as `lift_value` — or forgetting the +distinction — collapses the two branches and silently changes what a pipeline does on a short-circuit. + +**A new monad needs all four traits, plus the transformer form to stack.** Implementing three of them yields a +marker that works in some positions and fails to resolve in others, with an error naming the missing trait rather +than the gap. + +## Related constructs + +- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the monad markers; + what you actually wire. +- [Handler combinators](../providers/handler_combinators.md) — `ComposeHandlers` and `PipeHandlers`, composition + without a short-circuit branch. +- [`Computer`](../components/computer.md) — the component family a monadic pipeline implements. +- [`TryComputer`](../components/try_computer.md) and [`Handler`](../components/handler.md) — the fallible members + a single step usually is. +- [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads compose. +- [Handlers](/docs/concepts/handlers) — the computation family these pipelines are built from. + +## Source + +- The traits: [`cgp-monad/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/traits) + — `monadic_trans.rs`, `bind.rs`, `lift.rs`, `value.rs` +- The per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) + — `ident.rs`, `ok.rs`, `err.rs` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional_fields.md b/docs/reference/traits/optional_fields.md index ef515f49..ea4e4d52 100644 --- a/docs/reference/traits/optional_fields.md +++ b/docs/reference/traits/optional_fields.md @@ -6,12 +6,295 @@ sidebar_label: 'Optional-field traits' The builder and extractor traits for optional and defaulted fields. -:::info +## What it's for -### Not written yet +The core [builder family](./has_builder.md) is deliberately strict: a partial record becomes its concrete struct +only once **every** field is set, because `FinalizeBuild` is implemented solely on the all-present +configuration. That strictness is what catches a missing field at compile time — and it is too rigid for a record +where some fields have sensible defaults, or are genuinely allowed to be absent. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +These traits relax it in two controlled ways, without giving up the machinery underneath. + +**Defaulted finalization** fills any unset field from `Default` on the way out, so a record can be completed +without setting everything. **Optional fields** re-mark every field as an `Option`, which makes absence a +*runtime* condition — fields can then be set and re-set freely, and finalizing either requires presence with an +error or falls back to defaults. + +The whole layer is composition rather than new mechanism. It reuses +[`UpdateField`](./has_builder.md) to move individual fields, [`TransformMapFields`](./map_type.md) to re-wrap a +whole record at once, and the [`MapType`](./map_type.md) markers `IsPresent`, `IsNothing`, and `IsOptional` to +name each state. Read it as a small set of transforms plus the entry points that drive them. + +## Using it + +**Nothing here is in the prelude.** Everything comes from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::{ + CanBuildWithDefault, CanFinalizeWithDefault, FinalizeOptional, HasOptionalBuilder, SetOptional, +}; +``` + +The traits divide into the two capabilities, plus the two transform markers that power them. + +### Defaulted finalization + +`CanFinalizeWithDefault` finalizes a partial record, defaulting whatever is unset: + +```rust +pub trait CanFinalizeWithDefault { + type Output; + fn finalize_with_default(self) -> Self::Output; +} +``` + +It is implemented for any partial value whose fields can be transformed to all-present, and its body is the +layer's core motion in one line: re-wrap every field to `IsPresent`, then call the ordinary +[`finalize_build`](./has_builder.md). The strict presence check still runs — it just always passes, because the +transform guaranteed presence first. + +`CanBuildWithDefault` is the one-call version that also copies from a source: + +```rust +pub trait CanBuildWithDefault { + fn build_with_default(source: Source) -> Self; +} +``` + +It chains `builder()`, [`build_from`](./cast.md), and `finalize_with_default`, which makes it the field-level +"widening cast" — turning a `Point2d` into a `Point3d` whose extra `z` is `0`, naming no field explicitly. + +### Optional fields + +`HasOptionalBuilder` starts a builder in which every field is already optional: + +```rust +pub trait HasOptionalBuilder { + type Builder; + fn optional_builder() -> Self::Builder; +} +``` + +`ToOptional` is the conversion it composes with, re-marking an existing partial value's every field to +`IsOptional`. `SetOptional` then sets one: + +```rust +pub trait SetOptional { + type Value; + fn set(self, _tag: PhantomData, value: Self::Value) -> Self; + fn set_optional( + self, + _tag: PhantomData, + value: Self::Value, + ) -> (Option, Self); +} +``` + +**The crucial detail is that both methods return `Self`.** The field's marker is `IsOptional` before *and* after, +so the builder's type does not change — which is what makes an optional field settable repeatedly, unlike the +core `build_field` that consumes an absent slot exactly once. `set` discards whatever it replaced; +`set_optional` hands it back. + +`FinalizeOptional` is the strict way out: + +```rust +pub trait FinalizeOptional: PartialData { + fn finalize_optional(self) -> Result; +} +``` + +It succeeds only if every field holds a value, and the error is the **first missing field's own name** as a +`&'static str` — so a caller learns which field was left unset. + +### The two transforms + +`TransformMapDefault` and `TransformOptional` are the [`TransformMap`](./map_type.md) markers that do the +per-field work. `TransformMapDefault` targets `IsPresent` — a present field passes through, an absent one becomes +its default, an optional one becomes its contents or the default. `TransformOptional` targets `IsOptional` — +present becomes `Some`, absent becomes `None`. You name these only when extending the layer. + +## Examples + +The optional workflow starts an all-optional builder, sets fields freely, and picks a finalize strategy at the +end: + +```rust +use cgp::extra::field::impls::{ + CanFinalizeWithDefault, FinalizeOptional, HasOptionalBuilder, SetOptional, +}; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +// Every field set: finalize_optional succeeds. +let builder = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .set(PhantomData::, 42); + +// Setting an already-set field hands back what it replaced. +let (replaced, builder) = builder.set_optional(PhantomData::, "bar".to_owned()); +assert_eq!(replaced, Some("foo".to_owned())); + +let context = builder.finalize_optional().unwrap(); +assert_eq!(context.foo, "bar"); +``` + +Leave a field unset and the two strategies diverge — which is the whole point of deferring the choice to the +finalize call: + +```rust +// finalize_with_default fills `bar` from Default +let context = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + +assert_eq!(context.bar, 0); +``` + +Had that used `finalize_optional`, it would have returned `Err("bar")` instead of defaulting. + +The defaulted-build path widens one record into another in a single call: + +```rust +use cgp::extra::field::impls::CanBuildWithDefault; + +#[derive(Debug, Clone, Eq, PartialEq, CgpData)] +struct Point2d { x: u64, y: u64 } + +#[derive(Debug, Clone, Eq, PartialEq, CgpData)] +struct Point3d { x: u64, y: u64, z: u64 } + +let point_3d = Point3d::build_with_default(Point2d { x: 1, y: 2 }); + +assert_eq!(point_3d, Point3d { x: 1, y: 2, z: 0 }); // z defaulted +``` + +## When to reach for it, and when not + +**Reach for this layer when the core builder's strictness is genuinely wrong for the record**, and stay on the +core builder otherwise. The strictness is a feature — it is what turns a missing field into a compile error — so +relaxing it should be a decision rather than a convenience. + +- **`finalize_with_default`** when unset fields have meaningful defaults and silence is the right outcome. +- **`finalize_optional`** when absence is an error you want to *report* rather than paper over. The two are the + same builder finalized differently, and the choice is made at the call site — so the same value can go either + way. +- **`optional_builder` and `set`** when fields must be settable in any order and more than once, which the core + `build_field` cannot do. +- **`build_with_default`** for a one-call widening from a narrower record. +- **Stay on the [core builder](./has_builder.md)** when every field is genuinely required. You lose the + compile-time completeness check by moving here, and that check is the reason the builder family exists. +- **Reach for a hand-written builder** when the *logic* is the point — validation at finalize, interdependent + fields, computed defaults that are not `Default::default()`. This layer models presence and defaulting, and + nothing else. + +One thing to notice about the trade: `finalize_optional` moves a missing field from a compile error to a +`Result`, and its error type is a `&'static str` field name rather than a structured value. That is enough to +report which field is missing and not enough to match on programmatically. + +## Under the hood + +:::note + +### Advanced + +This section shows how both paths reuse one recursion. It is the shortest explanation of why the defaulted and +optional workflows behave so symmetrically. ::: + +Both capabilities are the **same** [`transform_map_fields`](./map_type.md) recursion with a different marker, which +is why they mirror each other so exactly: + +```rust +impl CanFinalizeWithDefault for Builder +where + Builder: TransformMapFields, + Builder::Output: FinalizeBuild, +{ + type Output = Output; + + fn finalize_with_default(self) -> Output { + self.transform_map_fields().finalize_build() + } +} +``` + +`CanFinalizeWithDefault` drives `TransformMapDefault` toward `IsPresent`; `ToOptional` drives +`TransformOptional` toward `IsOptional`. Both walk the same field spine, both rebuild the partial type one field +at a time through [`UpdateField`](./has_builder.md), and neither changes a value's runtime layout beyond wrapping +or unwrapping an `Option` or substituting a default. + +`SetOptional` is the one that does *not* transform the whole record — it is a single `UpdateField` call writing +`Some(value)` into an `IsOptional` slot, with `Mapper = IsOptional, Output = Context` pinning the type unchanged +on both sides. That pinning is exactly what allows repeated sets. + +`FinalizeOptional` walks the target's [`HasFields`](./has_fields.md) spine itself rather than using a transform: +for each field it pulls the `Option` out with `UpdateField`, writes it back as `IsPresent` with +[`BuildField`](./has_builder.md) if it is `Some`, and returns `Err(Tag::VALUE)` — the field's name recovered as a +static string through [`StaticString`](./static_format.md) — the moment it finds a `None`. Only if every field +yields a value does it reach `finalize_build`. + +The strict, all-present `FinalizeBuild` from the core remains the **only** way a partial value becomes a concrete +struct. Everything here simply guarantees the all-present configuration is reached before it is invoked. + +## Gotchas + +**Nothing here is in the prelude.** Import from `cgp::extra::field::impls`. + +**`set` returns `Self`, so the builder's type never changes.** That is deliberate — it is what allows re-setting — +but it also means the type carries no record of *which* fields you have set, which is why finalizing has to check +at run time. + +**Moving to an optional builder gives up the compile-time completeness check.** With the core builder a missing +field is a compile error; here it is an `Err` or a silently substituted default. That is the trade, and it is +worth making consciously. + +**`finalize_optional`'s error is a `&'static str`.** It names the first missing field and is not a structured +error. It also reports only the first. + +**`finalize_with_default` needs `Default` on every field's type.** A field whose type has no `Default` makes the +transform unresolvable, and the error names the missing `TransformMap` impl rather than the field. + +**`build_with_default` requires the source to have a shape.** It chains [`build_from`](./cast.md), so the source +needs [`HasFields`](./has_fields.md) — the same requirement as any merge. + +**A field whose type is already `Option` is not the same as an `IsOptional` field.** The former is a value that +happens to be optional and must still be *set*; the latter is a builder slot that may be empty. Conflating them +produces an `Option>`. + +## Related constructs + +- [`HasBuilder`](./has_builder.md) — the core family this layer relaxes, and where `FinalizeBuild` and + `UpdateField` are documented. +- [`MapType`](./map_type.md) — `TransformMap`, `TransformMapFields`, and the `IsOptional` marker this layer runs + on. +- [`CanUpcast`](./cast.md) — where `CanBuildFrom` and `build_from` are documented. +- [`HasFields`](./has_fields.md) — the shape both the transform and `FinalizeOptional` walk. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the partial types these operate on, + also through [`#[derive(CgpData)]`](../derives/derive_cgp_data.md). +- [`StaticString`](./static_format.md) — how `FinalizeOptional` recovers a field's name as a string. +- [`ExtractField`](./extract_field.md) — the enum-side counterpart of the record machinery. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence fits. + +## Source + +- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs) + — `CanBuildWithDefault`, `CanFinalizeWithDefault`, `TransformMapDefault` +- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs) + — `HasOptionalBuilder`, `ToOptional`, `TransformOptional` +- [`set_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/set_optional.rs) + — `SetOptional` +- [`finalize_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/finalize_optional.rs) + — `FinalizeOptional` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/product_ops.md b/docs/reference/traits/product_ops.md index 32d1d076..5b9fb754 100644 --- a/docs/reference/traits/product_ops.md +++ b/docs/reference/traits/product_ops.md @@ -6,12 +6,261 @@ sidebar_label: 'AppendProduct, ConcatProduct & MapFields' The type-level operations over product lists. -:::info +## What it's for -### Not written yet +A struct's shape in CGP is a type-level list — a [`Product!`](../macros/product.md) of named fields — and an +enum's is the analogous [`Sum!`](../macros/sum.md). Code that processes such a shape generically often needs to +*compute a new shape from an old one*: add a field, splice two lists together, rewrite every entry the same way. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +These three traits are exactly those three computations, each a pure function from type lists to type lists: + +- **`AppendProduct`** adds one entry at the end. +- **`ConcatProduct`** splices a whole list onto the end. +- **`MapFields`** rewrites every entry through a [`MapType`](./map_type.md) marker. + +They are evaluated by the trait solver while the compiler type-checks, so they carry no runtime cost and impose +no ordering — there is nothing to run. They are the plumbing beneath the higher-level constructs: building a +record appends, merging two concatenates, and producing a partial-record representation maps a marker over every +field. + +**These are the least user-facing traits in the reference.** You will meet them if you write generic code over +shapes, and otherwise only in an error message from code that does. + +## Using it + +**None of the three is in the prelude.** Import them from `cgp::core::field::traits`, and note that the +[`MapType`](./map_type.md) marker `MapFields` takes may need its own import too — `IsPresent`, `IsNothing`, and +`IsVoid` are in the prelude while `IsOptional` is not. + +```rust +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::{AppendProduct, ConcatProduct, MapFields}; +``` + +Each trait exposes its result as an associated type and has no methods, because there is nothing to execute. + +### `AppendProduct` + +```rust +pub trait AppendProduct { + type Output; +} +``` + +It recurses down the `Cons` spine, rebuilding each node until it reaches `Nil`, where it inserts +`Cons`. Reading it: every existing entry is preserved in order, and the new one lands last. + +### `ConcatProduct` + +```rust +pub trait ConcatProduct { + type Output; +} +``` + +The same recursion, except that at `Nil` it substitutes the entire `Items` list rather than a single element. So +**append is the single-entry special case of concat**, which is the shortest way to hold both in mind. + +Both have `Nil` identities worth knowing: concatenating onto `Nil` yields the other list unchanged, and +concatenating `Nil` onto a list leaves it unchanged. + +### `MapFields` + +```rust +pub trait MapFields { + type Mapped; +} +``` + +`MapFields` is the transforming one, and the only one defined over **both** spines: it walks `Cons`/`Nil` for a +product and `Either`/`Void` for a sum, applying `Mapper::Map` to each entry. The list's length and order never +change; each entry type `T` becomes `Mapper::Map`. + +Which means the marker decides the whole effect. With `IsPresent` it is the identity; with `IsNothing` every +entry collapses to `()`; with `IsOptional` every entry becomes `Option<_>`; with `IsVoid` every entry becomes +uninhabited. + +## Examples + +Appending and concatenating compute new product types. The results are types, so the check is a type equality +rather than a value comparison: + +```rust +use cgp::core::field::traits::{AppendProduct, ConcatProduct}; +use cgp::prelude::*; + +type Base = Product![Field]; + +// one entry added at the end +type WithPort = >>::Output; +// = Product![Field, Field] + +// a whole list spliced on +type Extra = Product![Field]; +type Full = >::Output; +// = Product![host, port, tls] +``` + +`MapFields` rewrites every entry uniformly. Applying `IsOptional` turns a product of values into a product of +optionals — the shape a partial builder uses to track what is not yet filled: + +```rust +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::MapFields; + +type Fields = Product![String, u16, bool]; + +type Optional = >::Mapped; +// = Product![Option, Option, Option] +``` + +and the same marker applies over a sum, which is what lets one operation produce both a partial record and a +partial enum: + +```rust +type Variants = Sum![String, u16]; + +type OptionalVariants = >::Mapped; +// = Sum![Option, Option] +``` + +## When to reach for it, and when not + +**Reach for these when you are writing generic code that computes a shape**, and essentially never otherwise. +They are building blocks the extensible-data machinery uses; the machinery itself is what application code +touches. + +- **`AppendProduct` and `ConcatProduct`** when a routine must describe the shape it *will* produce — a builder + that adds a field, a merge that combines two records — in a signature or an associated type. +- **`MapFields`** when a routine must describe a uniformly re-wrapped shape, which is what a partial + representation is. +- **Use [`HasFields`](./has_fields.md) instead** if you only need a type's *existing* shape. These traits compute + new shapes; they are not how you obtain one. +- **Use the [builder](./has_builder.md) or [extractor](./extract_field.md) family instead** if you are moving + *values* through a shape. These three never touch a value — they only name types — so if you want something to + happen at run time, they are the wrong layer. + +One name worth disambiguating: `MapFields` applies one marker across a whole list, while +[`MapType`](./map_type.md) is a single marker naming one field's storage and `MapField` (singular, on the +[`HasField`](./has_field.md) page) is a lifetime helper for reading a nested field. Three similar names, three +unrelated jobs. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursions. They are short, and reading one makes the others obvious — which is the +quickest way to be able to predict what any of these traits will produce. ::: + +Each trait is a pair of impls: one for the spine's `Cons` node and one for its terminator. `AppendProduct` keeps +each head and rebuilds the tail, grafting a single-element list at the end: + +```rust +impl AppendProduct for Nil { + type Output = Cons; +} + +impl AppendProduct for Cons +where + Tail: AppendProduct, +{ + type Output = Cons; +} +``` + +`ConcatProduct` is character-for-character the same recursion with one line different — at `Nil` it substitutes +the whole list: + +```rust +impl ConcatProduct for Nil { + type Output = Items; // the only difference +} + +impl ConcatProduct for Cons +where + Tail: ConcatProduct, +{ + type Output = Cons; +} +``` + +That is the precise sense in which append is a special case of concat. + +`MapFields` transforms the head rather than preserving it, and this is the pair that exists twice — once for +each spine: + +```rust +impl MapFields for Cons +where + Mapper: MapType, + Rest: MapFields, +{ + type Mapped = Cons, Rest::Mapped>; +} + +impl MapFields for Nil { + type Mapped = Nil; +} +``` + +The `Either`/`Void` impls mirror these exactly, with `Either` for `Cons` and `Void` for `Nil`. Because the +recursion only ever replaces a head type, the spine's length and shape are structurally preserved — which is why +a mapped product is still a product of the same arity, and a mapped sum still a sum. + +All of this is resolved during type checking. There is no `fn` anywhere on this page. + +## Gotchas + +**None of the three is in the prelude.** Import from `cgp::core::field::traits`. This is the first thing that +goes wrong when reaching for them. + +**The result is an associated type, and the two names differ.** `AppendProduct` and `ConcatProduct` expose +`Output`; `MapFields` exposes `Mapped`. Reaching for the wrong one is a plain unresolved-associated-type error, +but the asymmetry is easy to forget. + +**`MapFields` covers both spines; the other two are product-only.** There is no `AppendSum`. Growing a sum is +not an operation this layer provides. + +**These compute types, not values.** A `MapFields` result type does not wrap anything at run time by +itself — something still has to build the wrapped values, which on a partial record is +[`TransformMapFields`](./map_type.md). + +**Order is preserved, and order is part of the type.** Appending to a product yields a *different* type from +prepending, and two products with the same entries in different orders are unrelated types. + +**A long list means a deep recursion.** These are trait-resolution recursions over the spine, so a very wide +struct costs compile time proportional to its width — one of the places CGP's compile-time cost actually comes +from. + +## Related constructs + +- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the sugar for the lists these operate on. +- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. +- [`HasFields`](./has_fields.md) — where a type's existing shape comes from. +- [`MapType`](./map_type.md) — the markers `MapFields` applies, and the neighbouring trait most easily confused + with it. +- [`Field`](../types/field.md) — the entries a field list is usually made of. +- [`HasBuilder`](./has_builder.md) and [`ExtractField`](./extract_field.md) — the families that move values + through the shapes these compute. +- [`CanUpcast`](./cast.md) — conversions that walk a shape rather than reshape it. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where computing a new shape is put to work. + +## Source + +- [`append_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/append_product.rs) + — `AppendProduct` +- [`concat_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/concat_product.rs) + — `ConcatProduct` +- [`map_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_fields.rs) + — `MapFields`, over both spines + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md index 9db2a207..40e7d1d3 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/static_format.md @@ -6,12 +6,214 @@ sidebar_label: 'StaticFormat, StaticString & ConcatPath' Recovering type-level strings and paths back into runtime data. -:::info +## What it's for -### Not written yet +CGP encodes field and variant names as *types* — a [`Symbol!`](../macros/symbol.md) is a length plus a character +list, one node per character — so that names can drive trait resolution. But a program eventually needs those +names as ordinary strings: to name a missing field in an error, to build a key, to render a path. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +These three traits close that loop, and they divide by *when* the recovery happens. + +**`StaticString`** recovers the string **eagerly**, as a compile-time `&'static str` constant computed by const +evaluation. This is the one to reach for: the decoded string is available wherever a `const` is, and it costs +nothing at run time. + +**`StaticFormat`** recovers it **lazily**, by writing into a formatter. It is what backs the `Display` impl on +`Symbol` and `Chars`, so a type-level string can be printed with `{}` or `to_string()`. + +**`ConcatPath`** works one level up, on paths rather than strings: a [`Path!`](../macros/path.md) is a type-level +list of segments, and joining two of them is splicing one list onto another. It is a pure type-level operation +with no runtime side at all. + +## Using it + +The three differ sharply in how reachable they are, and that is the first thing to know. + +**`ConcatPath` is in the prelude.** `use cgp::prelude::*;` names it. + +**`StaticString` is not** — import it from `cgp::core::field::traits`: + +```rust +pub trait StaticString { + const VALUE: &'static str; +} +``` + +`VALUE` is the decoded string as a constant. `Symbol` computes a `[u8; LEN]` byte array at +const-evaluation time by walking the character list and UTF-8-encoding each character, then validates those bytes +as UTF-8 and exposes the result. The `LEN` on a `Symbol` is the precomputed **byte** length that sizes that array +— which is why `Symbol!` records a byte length rather than a character count. + +**`StaticFormat` cannot be named through the `cgp` crate at all.** See the [Gotchas](#gotchas) below; in practice +you reach its effect through `Display` and never the trait. + +```rust +pub trait StaticFormat { + fn fmt(f: &mut Formatter<'_>) -> Result<(), fmt::Error>; +} +``` + +Note the absent `self`: there is no runtime value, only the type. It is implemented by recursion over the +character spine — each node writes its own character and defers to the tail, and the terminator writes nothing. + +**`ConcatPath`** joins two paths: + +```rust +pub trait ConcatPath { + type Output: ?Sized; +} +``` + +Both sides may be unsized, since path types are markers. It recurses over the path spine exactly as +[`ConcatProduct`](./product_ops.md) does over a product: each node keeps its head and concatenates onto the tail, +and the terminator becomes the other path — so the result is the first path's segments followed by the second's. + +## Examples + +A type-level string recovers both ways, and the two are worth seeing together because the choice between them is +the page's main decision: + +```rust +use cgp::core::field::traits::StaticString; +use cgp::prelude::*; + +// lazily, through Display — reconstructed at the point of formatting +let s = ::default(); +assert_eq!(s.to_string(), "hello"); + +// eagerly, as a compile-time constant +assert_eq!(::VALUE, "hello"); +``` + +Both round-trip multi-byte Unicode faithfully, and the empty symbol decodes to the empty string: + +```rust +assert_eq!(::VALUE, "世界你好"); +assert_eq!(::VALUE, ""); +``` + +`ConcatPath` composes two paths at the type level, which is the operation behind chaining nested accessors: + +```rust +type Outer = Path!(a.b); +type Inner = Path!(c.d); + +type Joined = >::Output; // the path a.b.c.d +``` + +Where `StaticString` shows up in real code is recovering a name for an error. The +[optional-field layer](./optional_fields.md)'s `finalize_optional` reports its missing field by returning +`Tag::VALUE` — the field's own name, as a static string, with no allocation. + +## When to reach for it, and when not + +**Reach for `StaticString` when you need a name as data, and for `Display` when you need it in a message.** That +is the whole decision. + +- **`StaticString`** for a constant, a key, a comparison, or anywhere the name is used more than once. It is + computed at compile time, so there is no per-call work, and it is the only one of the three that a + `cgp`-dependent crate can bound on. +- **`Display` / `to_string()`** for one-off formatting. Reaching for `StaticFormat` by name is not an option, and + is not needed — the `Display` impls are what it exists to power. +- **`ConcatPath`** when composing paths in generic code, which is nested-accessor territory. If you are writing a + path literally, [`Path!`](../macros/path.md) already gives you the whole thing and there is nothing to + concatenate. + +Two things none of these is for. They are **not a general string facility**: `Symbol!` exists to key field and +variant lookups, and building programs out of type-level strings is not what the encoding is for. And they are +**not how you read a field** — recovering a name tells you what a field is called, while +[`HasField`](./has_field.md) is what reads its value. + +## Under the hood + +:::note + +### Advanced + +This section shows the two recursions. The `StaticString` one is the more interesting, because it explains the +`LEN` parameter that otherwise looks redundant on every `Symbol`. ::: + +`StaticFormat` is the straightforward one. Each character node writes itself and defers: + +```rust +impl StaticFormat for Chars +where + Tail: StaticFormat, +{ + fn fmt(f: &mut Formatter<'_>) -> Result<(), fmt::Error> { + write!(f, "{CHAR}")?; + Tail::fmt(f) + } +} + +impl StaticFormat for Nil { /* writes nothing */ } +``` + +Because both `Symbol` and `Chars` implement `Display` by delegating to this, any type-level string can be +interpolated or turned into an owned `String`. + +`StaticString` is const evaluation rather than recursion at run time. It is a blanket impl over an internal +`StaticBytes` trait: `Symbol` computes a `[u8; LEN]` in a `const` block by walking the character list +and UTF-8-encoding each character into the array, and `StaticString::VALUE` then validates those bytes as UTF-8 +and exposes the `&'static str`. + +**That array is why `Symbol` carries a `LEN` at all.** A const-evaluated byte array must have a known size, and the +size cannot be computed from inside the const context by walking the list — so the macro precomputes it. It is a +*byte* length, which is what makes multi-byte Unicode round-trip correctly and why `LEN` disagrees with the +character count for any non-ASCII name. + +`ConcatPath` is a pure type-level computation evaluated during trait resolution, with the same two-impl shape as +[`ConcatProduct`](./product_ops.md). It never touches a value; it only names the combined path type, which a getter +then uses to descend. + +## Gotchas + +**`StaticFormat` cannot be named from the `cgp` crate.** It is `pub` in its own crate, but nothing re-exports it +onto a reachable path — `cgp::core` re-exports a different types crate, `cgp-base` is not a dependency of `cgp`, +and the prelude carries only its sibling `ConcatPath`. So a crate depending on `cgp` can use its *effect* through +`Display` but cannot bound on it, implement it, or name it. Treat it as an implementation detail of those `Display` +impls, and reach for `StaticString` when you want the decoded name. + +**`StaticString` is not in the prelude** while `ConcatPath` is — an asymmetry between two traits that do +neighbouring jobs. Import `StaticString` from `cgp::core::field::traits`. + +**`LEN` on a `Symbol` is bytes, not characters.** They coincide for ASCII, so the distinction only surfaces on a +non-ASCII name, where the number will not match the visible character count. + +**`VALUE` is a constant, so it is named through the trait.** Write `::VALUE`; there +is no method to call and no value to have. + +**`Display` reconstructs the string rather than reading a stored one.** There is no `&str` inside a `Symbol` — +`to_string()` walks the type. For a name used repeatedly, `StaticString::VALUE` is the cheaper choice. + +**`ConcatPath` produces a type, not a joined string.** It is path composition for trait resolution; if you want the +segments as text, decode the symbols. + +## Related constructs + +- [`Symbol!`](../macros/symbol.md) — the type-level string these decode, and where the `LEN` comes from. +- [`Path!`](../macros/path.md) — the path `ConcatPath` joins. +- [Type-level spines](../types/type_level_spines.md) — the `Chars` and path chains being walked. +- [`ConcatProduct`](./product_ops.md) — the product-level analogue of `ConcatPath`. +- [`HasField`](./has_field.md) — where the names being decoded are used as keys. +- [Optional fields](./optional_fields.md) — a real consumer, reporting a missing field by name. +- [`ChainGetters`](../providers/chain_getters.md) — nested accessors, the setting path composition serves. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where field-name types are put to work at scale. + +## Source + +- [`static_string.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/static_string.rs) + — `StaticString` and its const-evaluated UTF-8 decoding +- [`static_format.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/static_format.rs) + — `StaticFormat` and its character-list impls +- [`concat_path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/concat_path.rs) + — `ConcatPath` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/example-code/src/reference/mod.rs b/example-code/src/reference/mod.rs index 90c90522..3c799293 100644 --- a/example-code/src/reference/mod.rs +++ b/example-code/src/reference/mod.rs @@ -6,3 +6,4 @@ pub mod derives; pub mod errors; pub mod macros; +pub mod traits; diff --git a/example-code/src/reference/traits/cast.rs b/example-code/src/reference/traits/cast.rs new file mode 100644 index 00000000..3f4444ce --- /dev/null +++ b/example-code/src/reference/traits/cast.rs @@ -0,0 +1,106 @@ +//! Code from `docs/reference/traits/cast.md` — *`CanUpcast`, `CanDowncast` & `CanBuildFrom`*. +//! +//! The page's own snippets, run. What this file pins beyond "it compiles" is the import path — +//! none of the four traits is in the prelude — and the two claims the page makes about totality: +//! an upcast always succeeds, and a downcast against a variant the target lacks returns `Err`. + +/// ## Examples +/// +/// The two enums the page shows, and both directions of the variant cast. +pub mod examples_variant { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBar { + Foo(u64), + Bar(String), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), + } + + #[test] + fn test_upcast_always_succeeds() { + use cgp::core::field::impls::CanUpcast; + use core::marker::PhantomData; + + let wide = FooBar::Foo(1).upcast(PhantomData::); + + assert_eq!(wide, FooBarBaz::Foo(1)); + } + + #[test] + fn test_downcast_succeeds_for_a_shared_variant() { + use cgp::core::field::impls::CanDowncast; + use core::marker::PhantomData; + + assert_eq!( + FooBarBaz::Bar("hi".to_owned()) + .downcast(PhantomData::) + .ok(), + Some(FooBar::Bar("hi".to_owned())), + ); + } + + #[test] + fn test_downcast_fails_for_a_variant_the_target_lacks() { + use cgp::core::field::impls::CanDowncast; + use core::marker::PhantomData; + + assert_eq!( + FooBarBaz::Baz(true).downcast(PhantomData::).ok(), + None, + ); + } +} + +/// ## Examples +/// +/// The record cast: one struct assembled from two smaller ones. +pub mod examples_record { + use cgp::prelude::*; + + #[derive(CgpData)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[derive(CgpData)] + pub struct Baz { + pub baz: bool, + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + #[test] + fn test_build_from_two_sources() { + use cgp::core::field::impls::CanBuildFrom; + + let combined: FooBarBaz = FooBarBaz::builder() + .build_from(FooBar { + foo: 1, + bar: "bar".to_owned(), + }) + .build_from(Baz { baz: true }) + .finalize_build(); + + assert_eq!( + combined, + FooBarBaz { + foo: 1, + bar: "bar".to_owned(), + baz: true, + } + ); + } +} diff --git a/example-code/src/reference/traits/has_builder.rs b/example-code/src/reference/traits/has_builder.rs new file mode 100644 index 00000000..ebd2c8dc --- /dev/null +++ b/example-code/src/reference/traits/has_builder.rs @@ -0,0 +1,134 @@ +//! Code from `docs/reference/traits/has_builder.md` — *`HasBuilder`*. +//! +//! The page's three snippets, run: the `extend` merge, the `into_builder`/`take_field` round trip, +//! and reading a set field back off a partial value. The rejected cases the page states are +//! `compile_fail` doctests below, since a page that says something will not compile should be +//! checked on that rather than trusted. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::CanBuildFrom; + use cgp::prelude::*; + + // `build_from` walks the *source's* field list, so the source needs `HasFields` too. + #[derive(HasFields, BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + #[derive(BuildField)] + #[derive(Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + pub fn extend(foo_bar: FooBar) -> FooBarBaz { + FooBarBaz::builder() + .build_from(foo_bar) + .build_field(PhantomData::, true) + .finalize_build() + } + + #[test] + fn test_extend() { + assert_eq!( + extend(FooBar { + foo: 1, + bar: "bar".to_owned() + }), + FooBarBaz { + foo: 1, + bar: "bar".to_owned(), + baz: true, + } + ); + } + + #[test] + fn test_take_a_field_out_and_put_it_back() { + // `TakeField` is the one trait in the family that is not in the prelude. + use cgp::core::field::traits::TakeField; + + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + }; + + let builder = person.into_builder(); + + let (first_name, remainder) = builder.take_field(PhantomData::); + assert_eq!(first_name, "Alice"); + + let person = remainder + .build_field(PhantomData::, first_name) + .finalize_build(); + + assert_eq!( + person, + Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + } + ); + } + + #[test] + fn test_read_a_set_field_mid_build() { + let partial = + Person::builder().build_field(PhantomData::, "Alice".to_owned()); + + assert_eq!( + partial.get_field(PhantomData::), + "Alice" + ); + } +} + +/// The page's central claim: `finalize_build` exists only at the all-present configuration, so an +/// incomplete build does not resolve. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[derive(BuildField)] +/// pub struct Person { +/// pub first_name: String, +/// pub last_name: String, +/// } +/// +/// let person: Person = Person::builder() +/// .build_field(PhantomData::, "Alice".to_owned()) +/// .finalize_build(); +/// ``` +pub mod rejected_incomplete_build {} + +/// The page's other claim: a `build_from` source deriving only `BuildField` cannot be merged, because +/// the recursion needs the source's `HasFields` shape. +/// +/// ```compile_fail +/// use cgp::core::field::impls::CanBuildFrom; +/// use cgp::prelude::*; +/// +/// #[derive(BuildField)] +/// pub struct FooBar { pub foo: u64 } +/// +/// #[derive(BuildField)] +/// pub struct FooBaz { pub foo: u64, pub baz: bool } +/// +/// let _ = FooBaz::builder() +/// .build_from(FooBar { foo: 1 }) +/// .build_field(PhantomData::, true) +/// .finalize_build(); +/// ``` +pub mod rejected_build_from_without_has_fields {} diff --git a/example-code/src/reference/traits/mod.rs b/example-code/src/reference/traits/mod.rs new file mode 100644 index 00000000..161f1e3c --- /dev/null +++ b/example-code/src/reference/traits/mod.rs @@ -0,0 +1,12 @@ +//! Code from the pages under `docs/reference/traits/`. +//! +//! Several pages here document traits whose impls are all generated, or which are pure type-level +//! operations with no runtime side. Those get a file only where the page shows code a compiler can +//! check: a bound that must resolve, an import path that must exist, a conversion that must run. +//! Pages that only *display* a trait definition get no module, since re-declaring the trait would +//! check nothing about CGP. + +pub mod cast; +pub mod has_builder; +pub mod product_ops; +pub mod static_format; diff --git a/example-code/src/reference/traits/product_ops.rs b/example-code/src/reference/traits/product_ops.rs new file mode 100644 index 00000000..5d07c852 --- /dev/null +++ b/example-code/src/reference/traits/product_ops.rs @@ -0,0 +1,88 @@ +//! Code from `docs/reference/traits/product_ops.md` — *`AppendProduct`, `ConcatProduct` & +//! `MapFields`*. +//! +//! These are pure type-level functions, so the checks are type equalities: each `fn` coerces the +//! computed `Output`/`Mapped` type to the type the page says it produces, and the module compiles +//! only if the two are the same type. The page's import paths are checked by this file's `use` +//! lines — none of the three traits is in the prelude, nor is the `IsOptional` marker. + +/// ## Examples +/// +/// The append and concat snippets, as the page writes them. +pub mod examples_append_concat { + use cgp::core::field::traits::{AppendProduct, ConcatProduct}; + use cgp::prelude::*; + + pub type Base = Product![Field]; + + pub type WithPort = >>::Output; + + pub type Extra = Product![Field]; + + pub type Full = >::Output; + + /// The page's claim about `WithPort`. + pub fn assert_with_port( + fields: WithPort, + ) -> Product![Field, Field] { + fields + } + + /// The page's claim about `Full`. + pub fn assert_full( + fields: Full, + ) -> Product![ + Field, + Field, + Field, + ] { + fields + } + + /// The `Nil` identities the page states under *Using it*. + pub fn assert_left_identity(fields: >::Output) -> Base { + fields + } + + pub fn assert_right_identity(fields: >::Output) -> Base { + fields + } +} + +/// ## Examples +/// +/// The `MapFields` snippets — over a product, and over a sum with the same marker. +pub mod examples_map_fields { + use cgp::core::field::impls::IsOptional; + use cgp::core::field::traits::MapFields; + use cgp::prelude::*; + + pub type Fields = Product![String, u16, bool]; + + pub type Optional = >::Mapped; + + pub fn assert_optional( + fields: Optional, + ) -> Product![Option, Option, Option] { + fields + } + + pub type Variants = Sum![String, u16]; + + pub type OptionalVariants = >::Mapped; + + pub fn assert_optional_variants( + variants: OptionalVariants, + ) -> Sum![Option, Option] { + variants + } + + /// The page's claim that `IsPresent` is the identity, and that `IsNothing` collapses each entry. + pub fn assert_present(fields: >::Mapped) -> Fields { + fields + } + + pub fn assert_nothing(fields: >::Mapped) -> Product![(), (), ()] { + fields + } +} diff --git a/example-code/src/reference/traits/static_format.rs b/example-code/src/reference/traits/static_format.rs new file mode 100644 index 00000000..18cc1ce1 --- /dev/null +++ b/example-code/src/reference/traits/static_format.rs @@ -0,0 +1,44 @@ +//! Code from `docs/reference/traits/static_format.md` — *`StaticFormat`, `StaticString` & +//! `ConcatPath`*. +//! +//! The page's snippets, run. The load-bearing check here is the import path and reachability claim: +//! `StaticString` resolves from `cgp::core::field::traits` and `ConcatPath` from the prelude, while +//! `StaticFormat` is reachable only through `Display` — the page says the trait cannot be named from +//! the `cgp` crate, and the absence of any `use` for it below is that claim. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[test] + fn test_both_recovery_routes() { + use cgp::core::field::traits::StaticString; + + // lazily, through Display + let s = ::default(); + assert_eq!(s.to_string(), "hello"); + + // eagerly, as a compile-time constant + assert_eq!(::VALUE, "hello"); + } + + #[test] + fn test_multi_byte_and_empty() { + use cgp::core::field::traits::StaticString; + + assert_eq!(::VALUE, "世界你好"); + assert_eq!(::VALUE, ""); + } + + /// `ConcatPath` joins two paths at the type level. Paths are unsized markers, so there is no + /// value to build — naming the joined type and coercing it to the expected one is the check. + pub type Outer = Path!(@a.b); + pub type Inner = Path!(@c.d); + + pub type Joined = >::Output; + + #[allow(dead_code)] + pub fn assert_joined(path: PhantomData<&Joined>) -> PhantomData<&Path!(@a.b.c.d)> { + path + } +} From 82a5af691b1056a920261099c6a3c62c2d8a7b89 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 23:35:53 +0200 Subject: [PATCH 030/516] Split the derives and traits reference into one page per construct MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two groups went from 21 pages to 65, and the reference section from 75 to 120. Every publicly nameable derive and trait now has a page of its own, so no page title is a list of names: the four structural casts, the three product operations, the three string and path recoveries, the four monad traits, the seven builder traits, the six extractor traits, the eight optional-field traits, and the families around HasField, HasFields and MapType each split apart. No prose was discarded. Each page's material moved to the construct it belongs to, and where two pages would have repeated an explanation, one keeps it and the other links — CanDowncastFields defers its recursion to CanDowncast, and the record and variant expansions moved off the CgpData umbrella onto the two shape pages. Two constructs moved rather than split. #[default_impl(...)] was a second construct living on the DefaultNamespace page and now has its own page under attributes/, taking that group to 8. The MapType and MapTypeRef markers stayed with their traits, since they are types rather than constructs, and the index's lookup table routes a reader who arrives holding one. StaticFormat is reachable again, so the pages that said otherwise are wrong. cgp now re-exports cgp-base as cgp::core::base, which makes the trait importable from cgp::core::base::traits and can be bound on and implemented against — verified by compiling against the local checkout rather than reading the diff. static_format.md loses its warning admonition and gains the import; static_string.md and concat_path.md lose the mention. The mirror crate cannot pin the new import until v0.8.0 publishes, since it tracks the alpha, which predates the export. The example-code mirror splits with the pages: cast.rs became four files and product_ops.rs three, because a mirror file naming a page that no longer exists is worse than no file. The pages created around them are not mirrored yet. Also fixes the one snippet that used a non-prelude trait without showing its import, on derive_from_variant.md. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01PQ3tpcNckW7LS1zjPAxuSD --- docs/concepts/extensible-variants.md | 2 +- docs/concepts/monadic-handlers.md | 5 +- docs/reference/attributes/default_impl.md | 229 ++++++++++ docs/reference/derives/derive_build_field.md | 17 +- docs/reference/derives/derive_cgp_data.md | 412 +++++------------- docs/reference/derives/derive_cgp_record.md | 232 ++++++++++ docs/reference/derives/derive_cgp_variant.md | 274 ++++++++++++ .../reference/derives/derive_extract_field.md | 2 +- docs/reference/derives/derive_from_variant.md | 6 +- docs/reference/derives/derive_has_fields.md | 4 +- docs/reference/index.md | 52 +-- docs/reference/macros/product.md | 2 +- docs/reference/macros/sum.md | 2 +- docs/reference/traits/append_product.md | 159 +++++++ docs/reference/traits/build_field.md | 167 +++++++ docs/reference/traits/can_build_from.md | 156 +++++++ .../traits/can_build_with_default.md | 158 +++++++ docs/reference/traits/can_downcast.md | 155 +++++++ docs/reference/traits/can_downcast_fields.md | 155 +++++++ .../traits/can_finalize_with_default.md | 173 ++++++++ docs/reference/traits/can_upcast.md | 160 +++++++ docs/reference/traits/cast.md | 252 ----------- docs/reference/traits/concat_path.md | 144 ++++++ docs/reference/traits/concat_product.md | 152 +++++++ docs/reference/traits/contains_value.md | 147 +++++++ docs/reference/traits/default_impls1.md | 224 ++++++++++ docs/reference/traits/default_impls2.md | 178 ++++++++ docs/reference/traits/default_namespace.md | 260 ++++------- docs/reference/traits/extract_field.md | 292 +++++-------- docs/reference/traits/field_getter.md | 185 ++++++++ docs/reference/traits/field_mapper.md | 179 ++++++++ docs/reference/traits/finalize_build.md | 189 ++++++++ docs/reference/traits/finalize_extract.md | 166 +++++++ .../traits/finalize_extract_result.md | 171 ++++++++ docs/reference/traits/finalize_optional.md | 171 ++++++++ docs/reference/traits/from_fields.md | 164 +++++++ docs/reference/traits/from_variant.md | 4 +- docs/reference/traits/has_builder.md | 266 ++++------- docs/reference/traits/has_extractor.md | 183 ++++++++ docs/reference/traits/has_extractor_mut.md | 156 +++++++ docs/reference/traits/has_extractor_ref.md | 156 +++++++ docs/reference/traits/has_field.md | 212 ++++----- docs/reference/traits/has_field_mut.md | 167 +++++++ docs/reference/traits/has_fields.md | 263 ++++------- docs/reference/traits/has_fields_ref.md | 162 +++++++ docs/reference/traits/has_optional_builder.md | 176 ++++++++ docs/reference/traits/into_builder.md | 157 +++++++ docs/reference/traits/lift_value.md | 152 +++++++ docs/reference/traits/map_field.md | 181 ++++++++ docs/reference/traits/map_fields.md | 167 +++++++ docs/reference/traits/map_type.md | 247 ++++------- docs/reference/traits/map_type_ref.md | 181 ++++++++ docs/reference/traits/monad.md | 216 --------- docs/reference/traits/monadic_bind.md | 161 +++++++ docs/reference/traits/monadic_trans.md | 150 +++++++ docs/reference/traits/mut_field_getter.md | 146 +++++++ docs/reference/traits/optional_fields.md | 300 ------------- docs/reference/traits/partial_data.md | 151 +++++++ docs/reference/traits/product_ops.md | 266 ----------- docs/reference/traits/set_optional.md | 166 +++++++ docs/reference/traits/static_format.md | 205 ++++----- docs/reference/traits/static_string.md | 147 +++++++ docs/reference/traits/take_field.md | 163 +++++++ docs/reference/traits/to_fields.md | 164 +++++++ docs/reference/traits/to_fields_ref.md | 156 +++++++ docs/reference/traits/to_optional.md | 164 +++++++ docs/reference/traits/transform_map.md | 175 ++++++++ .../reference/traits/transform_map_default.md | 173 ++++++++ docs/reference/traits/transform_map_fields.md | 163 +++++++ docs/reference/traits/transform_optional.md | 166 +++++++ docs/reference/traits/update_field.md | 174 ++++++++ example-code/README.md | 2 +- .../src/reference/derives/derive_cgp_data.rs | 112 +---- .../reference/derives/derive_cgp_record.rs | 51 +++ .../reference/derives/derive_cgp_variant.rs | 74 ++++ example-code/src/reference/derives/mod.rs | 2 + .../src/reference/traits/append_product.rs | 29 ++ .../src/reference/traits/can_build_from.rs | 96 ++++ .../src/reference/traits/can_downcast.rs | 47 ++ .../reference/traits/can_downcast_fields.rs | 44 ++ .../src/reference/traits/can_upcast.rs | 33 ++ example-code/src/reference/traits/cast.rs | 106 ----- .../src/reference/traits/concat_path.rs | 20 + .../src/reference/traits/concat_product.rs | 39 ++ .../src/reference/traits/map_fields.rs | 41 ++ example-code/src/reference/traits/mod.rs | 13 +- .../src/reference/traits/product_ops.rs | 88 ---- .../src/reference/traits/static_format.rs | 46 +- .../src/reference/traits/static_string.rs | 29 ++ 89 files changed, 9623 insertions(+), 2881 deletions(-) create mode 100644 docs/reference/attributes/default_impl.md create mode 100644 docs/reference/derives/derive_cgp_record.md create mode 100644 docs/reference/derives/derive_cgp_variant.md create mode 100644 docs/reference/traits/append_product.md create mode 100644 docs/reference/traits/build_field.md create mode 100644 docs/reference/traits/can_build_from.md create mode 100644 docs/reference/traits/can_build_with_default.md create mode 100644 docs/reference/traits/can_downcast.md create mode 100644 docs/reference/traits/can_downcast_fields.md create mode 100644 docs/reference/traits/can_finalize_with_default.md create mode 100644 docs/reference/traits/can_upcast.md delete mode 100644 docs/reference/traits/cast.md create mode 100644 docs/reference/traits/concat_path.md create mode 100644 docs/reference/traits/concat_product.md create mode 100644 docs/reference/traits/contains_value.md create mode 100644 docs/reference/traits/default_impls1.md create mode 100644 docs/reference/traits/default_impls2.md create mode 100644 docs/reference/traits/field_getter.md create mode 100644 docs/reference/traits/field_mapper.md create mode 100644 docs/reference/traits/finalize_build.md create mode 100644 docs/reference/traits/finalize_extract.md create mode 100644 docs/reference/traits/finalize_extract_result.md create mode 100644 docs/reference/traits/finalize_optional.md create mode 100644 docs/reference/traits/from_fields.md create mode 100644 docs/reference/traits/has_extractor.md create mode 100644 docs/reference/traits/has_extractor_mut.md create mode 100644 docs/reference/traits/has_extractor_ref.md create mode 100644 docs/reference/traits/has_field_mut.md create mode 100644 docs/reference/traits/has_fields_ref.md create mode 100644 docs/reference/traits/has_optional_builder.md create mode 100644 docs/reference/traits/into_builder.md create mode 100644 docs/reference/traits/lift_value.md create mode 100644 docs/reference/traits/map_field.md create mode 100644 docs/reference/traits/map_fields.md create mode 100644 docs/reference/traits/map_type_ref.md delete mode 100644 docs/reference/traits/monad.md create mode 100644 docs/reference/traits/monadic_bind.md create mode 100644 docs/reference/traits/monadic_trans.md create mode 100644 docs/reference/traits/mut_field_getter.md delete mode 100644 docs/reference/traits/optional_fields.md create mode 100644 docs/reference/traits/partial_data.md delete mode 100644 docs/reference/traits/product_ops.md create mode 100644 docs/reference/traits/set_optional.md create mode 100644 docs/reference/traits/static_string.md create mode 100644 docs/reference/traits/take_field.md create mode 100644 docs/reference/traits/to_fields.md create mode 100644 docs/reference/traits/to_fields_ref.md create mode 100644 docs/reference/traits/to_optional.md create mode 100644 docs/reference/traits/transform_map.md create mode 100644 docs/reference/traits/transform_map_default.md create mode 100644 docs/reference/traits/transform_map_fields.md create mode 100644 docs/reference/traits/transform_optional.md create mode 100644 docs/reference/traits/update_field.md create mode 100644 example-code/src/reference/derives/derive_cgp_record.rs create mode 100644 example-code/src/reference/derives/derive_cgp_variant.rs create mode 100644 example-code/src/reference/traits/append_product.rs create mode 100644 example-code/src/reference/traits/can_build_from.rs create mode 100644 example-code/src/reference/traits/can_downcast.rs create mode 100644 example-code/src/reference/traits/can_downcast_fields.rs create mode 100644 example-code/src/reference/traits/can_upcast.rs delete mode 100644 example-code/src/reference/traits/cast.rs create mode 100644 example-code/src/reference/traits/concat_path.rs create mode 100644 example-code/src/reference/traits/concat_product.rs create mode 100644 example-code/src/reference/traits/map_fields.rs delete mode 100644 example-code/src/reference/traits/product_ops.rs create mode 100644 example-code/src/reference/traits/static_string.rs diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 3b6d12ae..9c01aa6d 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -150,7 +150,7 @@ whole shape, [`#[derive(ExtractField)]`](/docs/reference/derives/derive_extract_ narrowing, and [`#[derive(FromVariant)]`](/docs/reference/derives/derive_from_variant) for construction by name. [`ExtractField`](/docs/reference/traits/extract_field) is the extractor family those produce, [`FromVariant`](/docs/reference/traits/from_variant) constructs a variant generically, and -[the casts](/docs/reference/traits/cast) are `CanUpcast` and `CanDowncast`. +[the casts](/docs/reference/traits/can_upcast) are `CanUpcast` and [`CanDowncast`](/docs/reference/traits/can_downcast). --- diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index 33c46c02..3f441adf 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -111,7 +111,10 @@ matching an enum variant is a chain of attempts where the first success ends it. For the constructs, [monad providers](/docs/reference/providers/monad_providers) carries `PipeMonadic`, the three markers, and the per-step `BindOk` / `BindErr` forms, and -[the monad traits](/docs/reference/traits/monad) is the layer defining what a monad is here. +the four monad traits — [`MonadicBind`](/docs/reference/traits/monadic_bind), +[`ContainsValue`](/docs/reference/traits/contains_value), +[`LiftValue`](/docs/reference/traits/lift_value), and +[`MonadicTrans`](/docs/reference/traits/monadic_trans) — are the layer defining what a monad is here. --- diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md new file mode 100644 index 00000000..02503bb3 --- /dev/null +++ b/docs/reference/attributes/default_impl.md @@ -0,0 +1,229 @@ +--- +sidebar_label: '#[default_impl]' +--- + +# `#[default_impl(...)]` + +Register a provider as a namespace's default for a key. + +## What it's for + +A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the +type the capability runs against — can opt into and then selectively override. Ordinarily a namespace's +entries are written in its own body. `#[default_impl(...)]` lets a *provider* register itself instead, +at the point where it is defined: + +```rust +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { /* … */ } +``` + +Read that as: *`ShowString` is the default for `String`, in the `DefaultImpls1` +table.* A context that pulls that table in gets this provider without naming it. + +The value of registering at the definition is that the provider and its default sit together, so adding a +new per-type implementation is one place to edit rather than two. + +## Using it + +The attribute goes on a [`#[cgp_impl]`](../macros/cgp_impl.md) provider and takes one argument in two +parts, joined by the keyword `in`: + +```rust +#[default_impl(Key in NamespacePath)] +``` + +**`Key` becomes the emitted impl's `Self`**, and `NamespacePath` names the lookup trait plus whatever +leading arguments you write inside it. The table parameter is appended for you. So the example above +emits: + +```rust +impl DefaultImpls1 for String { + type Delegate = ShowString; +} +``` + +That rule is worth internalizing, because the trait's own parameter names suggest the opposite +arrangement — see [`DefaultImpls1`](../traits/default_impls1.md#the-one-thing-to-get-right). + +**The path may name any trait**, not only the three CGP ships. A trait of your own with the right shape +works identically, which is why [`DefaultImpls2`](../traits/default_impls2.md) needed no new construct to +be usable. + +The three built-in targets are [`DefaultNamespace`](../traits/default_namespace.md) for a component-only +key, [`DefaultImpls1`](../traits/default_impls1.md) for a per-type default — the usual choice — and +[`DefaultImpls2`](../traits/default_impls2.md) for a two-type key. + +
+Formal grammar + +The attribute argument is a key type, the keyword `in`, and a namespace path, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +DefaultImplArgs -> Type `in` TypePath +``` + +`Type` is the key that becomes the emitted impl's `Self`, and `TypePath` is the lookup trait with its +leading generic arguments written out — the table parameter is appended by the macro and must not be +given. The attribute takes exactly one such argument; it is neither comma-separated nor repeatable for +several tables on one provider. + +
+ +## Examples + +The whole chain, from a provider declaring itself a default to a context pulling it in: + +```rust +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; +use core::fmt::Display; + +#[cgp_component(ShowImpl)] +#[prefix(@test in DefaultNamespace)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} +``` + +Then the context: + +```rust +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + @test.ShowImplComponent.u64: ShowWithDisplay, // overrides the inherited default + } +} +``` + +**Environmental context, parameter-targeted** — `App` carries the wiring and the shown value is a +parameter. The loop wires every type with a registered default, and the direct `u64` line shadows +whatever the namespace would otherwise supply for that one type. + +## When to reach for it, and when not + +**Reach for it when a provider is the natural default for its key and you want that recorded where the +provider is written.** + +- **Write the entry in the namespace body instead** when the defaults belong together as a set, or when + the provider is one of several candidates and none is obviously *the* default. A + [`cgp_namespace!`](../macros/cgp_namespace.md) body reads as a table; scattered attributes do not. +- **Use it** when per-type defaults accumulate — a conversion, a formatter, a codec with one provider per + type — because then the alternative is a namespace body that has to be edited every time a type is + added. +- **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. + +**One constraint decides where the attribute may be written, and it is Rust's orphan rule rather than +anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, so a crate may register a default +when it owns either the namespace trait or the key type. For an unprefixed component the key is the +component's own marker, so a downstream crate owning the component can register into a foreign namespace. +For a [`#[prefix]`](../macros/cgp_namespace.md)-ed component the key is a path built from `cgp`-owned +types plus the marker, so the attribute is orphan-legal **only in the namespace's own crate**. Wiring +that must live downstream goes in the namespace body of the crate that owns it instead. + +## Under the hood + +:::note + +### Advanced + +This section shows what the attribute emits, and the one thing it deliberately leaves out. + +::: + +The attribute emits a single impl of the named lookup trait, for the key type: + +```rust +impl DefaultImpls1 for String { + type Delegate = ShowString; +} +``` + +The `Components` parameter is the table the lookup runs against, appended by the macro and left generic +so one registration serves every context. + +**The registration impl carries only the parameters naming the key and the provider, plus the table — +never the provider's own `where` clause.** That is deliberate and is what makes the attribute usable with +ordinary providers: a provider whose bounds come from [`#[use_type]`](./use_type.md), +[`#[uses]`](./uses.md), [`#[implicit]`](./implicit.md), or [`#[use_provider]`](./use_provider.md) +registers cleanly, because those bounds stay on the provider's impl and its +[`IsProviderFor`](../traits/is_provider_for.md) and are checked when a real context resolves it. + +Consumption is the mirror. A `for in DefaultImpls1 { … }` loop inside +[`delegate_components!`](../macros/delegate_components.md) emits a +[`DelegateComponent`](../traits/delegate_component.md) impl whose `where` clause projects the default: + +```rust +where T: DefaultImpls1 +``` + +Because the loop variables appear only in that bound and in the key, **the key must mention them** — or +the parameter is unconstrained and the impl is rejected with `E0207`. + +## Gotchas + +**`Key` becomes `Self`, not a parameter.** Read `#[default_impl(Key in Path)]` as "`Key` becomes `Self`" +and the trait's positions follow. The parameter names on +[`DefaultImpls1`](../traits/default_impls1.md) suggest otherwise. + +**Do not write the table parameter.** The macro appends it; supplying it yourself makes the path's arity +wrong. + +**On a prefixed component it is confined to the namespace's crate**, by the orphan rule. This is not +something to work around — put the wiring in the namespace body instead. + +**The lookup trait must be imported.** The emitted impl names it, so +[`DefaultImpls1`](../traits/default_impls1.md) and [`DefaultImpls2`](../traits/default_impls2.md) need +`use cgp::core::component::…`; [`DefaultNamespace`](../traits/default_namespace.md) is in the prelude. + +**It takes one argument and is not repeatable** for several tables on one provider. + +**A registered default is a fallback, not an assignment.** A context's direct entry silently shadows it. + +## Related constructs + +- [`DefaultImpls1`](../traits/default_impls1.md) — the usual target, and where the positional rule is + worked out. +- [`DefaultNamespace`](../traits/default_namespace.md) and + [`DefaultImpls2`](../traits/default_impls2.md) — the component-only and two-type targets. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and documents + `#[prefix(...)]`. +- [`delegate_components!`](../macros/delegate_components.md) — carries the `namespace` header and the + `for … in` loop that consume a registration. +- [`#[cgp_impl]`](../macros/cgp_impl.md) — the host this attribute goes on. +- [`IsProviderFor`](../traits/is_provider_for.md) — where a registered provider's real bounds are + checked. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value. + +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style + configuration. + +## Source + +- The attribute: [`attributes/default_impl/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/default_impl) +- The lookup traits: [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) +- Header and loop codegen: [`delegate_component/statement/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/statement) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 299f486c..2d560b9a 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -81,7 +81,7 @@ three of them. **`build_field`** sets one absent field to a value, which is the step shown above. **`build_from`** copies every field the target and a source record share, in one step. It comes from -`CanBuildFrom` — documented with the other [structural casts](../traits/cast.md) — and is imported from +[`CanBuildFrom`](../traits/can_build_from.md), and is imported from `cgp::core::field::impls`: ```rust @@ -183,8 +183,8 @@ case it exists for, and it is a narrower case than "this struct has several fiel - **Do not reach for it in place of a conventional builder** with defaults and validation. It tracks presence and nothing else: it has no notion of a default value, no way to run a check at finalize time, and no optional field unless you make the field's own type optional. The - [optional-field extensions](../traits/optional_fields.md) cover the defaulted and optional cases, and a - hand-written builder remains the better fit when the logic is the point. + [optional-field extensions](../traits/has_optional_builder.md) cover the defaulted and optional cases, + and a hand-written builder remains the better fit when the logic is the point. Between this derive and its neighbours the choice is about how much of the machinery you want. @@ -318,8 +318,8 @@ bound on the source type. directly. `CanBuildFrom`, which provides `build_from`, comes from `cgp::core::field::impls`. **There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible default -still has to be set explicitly, unless you reach for the -[optional-field extensions](../traits/optional_fields.md). +still has to be set explicitly, unless you reach for +[`CanFinalizeWithDefault`](../traits/can_finalize_with_default.md). **A tuple struct's steps are keyed by position.** Use `PhantomData::>`, not a `Symbol!` of the number. @@ -345,9 +345,10 @@ renaming a field in one struct silently stops it being copied from the other — `TakeField`, and `FinalizeBuild`. - [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers the companion is parameterized by. -- [`CanUpcast`](../traits/cast.md) — where `CanBuildFrom` and its `build_from` are documented. -- [Optional fields](../traits/optional_fields.md) — defaulted and optional fields, which the plain builder - does not model. +- [`CanBuildFrom`](../traits/can_build_from.md) — where `build_from` is documented. +- [`HasOptionalBuilder`](../traits/has_optional_builder.md) and + [`CanFinalizeWithDefault`](../traits/can_finalize_with_default.md) — optional and defaulted fields, + which the plain builder does not model. - [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that run several builder implementations and merge their outputs. diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index f33ae38f..4b54edf6 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -1,40 +1,32 @@ --- -sidebar_label: '#[derive(CgpData)], CgpRecord & CgpVariant' +sidebar_label: '#[derive(CgpData)]' --- -# `#[derive(CgpData)]`, `CgpRecord` & `CgpVariant` +# `#[derive(CgpData)]` -The extensible-data derives: the umbrella and its struct and enum faces. +The umbrella extensible-data derive, for a struct or an enum. ## What it's for -A plain Rust struct or enum is opaque to generic code. There is no way to refer to "the `first_name` field" -or "the `Circle` variant" through a type parameter, so anything that must work across several data types ends -up written once per type. +A plain Rust struct or enum is opaque to generic code. There is no way to refer to "the `first_name` +field" or "the `Circle` variant" through a type parameter, so anything that must work across several +data types ends up written once per type. -`#[derive(CgpData)]` is the one-line answer: it turns a struct or an enum into **extensible data**, a type -whose fields or variants generic code can name, read, construct, and take apart without ever mentioning the -concrete type. It is the umbrella derive, and what it generates depends entirely on what it is applied to. - -On a **struct** it produces the record machinery: per-field access, the whole-shape field list, and an -incremental builder that assembles a value one field at a time. On an **enum** it produces the variant -machinery: the whole-shape variant list, a constructor per variant, and an incremental extractor that peels -variants off one at a time. +`#[derive(CgpData)]` is the one-line answer: it turns a struct or an enum into **extensible data**, a +type whose fields or variants generic code can name, read, construct, and take apart without ever +mentioning the concrete type. It is the umbrella derive, and what it generates depends entirely on what +it is applied to — on a struct it emits the record machinery, on an enum the variant machinery. The two things this buys are worth naming separately, because together they are what "extensible" means here. The **representation** view describes the type as a list of named entries, which is what lets one -implementation serialize any record or dispatch over any enum. The **incremental** view adds a companion type -that tracks, in its own type parameters, which fields are present or which variants are still possible — so a -half-built value and a finished one are *different types*, and using one where the other belongs is a compile -error rather than a runtime panic. - -`#[derive(CgpRecord)]` and `#[derive(CgpVariant)]` are the same thing restricted to one shape. They run the -same code and produce the same output; the only difference is that each refuses the shape it is not for. +implementation serialize any record or dispatch over any enum. The **incremental** view adds a companion +type that tracks, in its own type parameters, which fields are present or which variants are still +possible — so a half-built value and a finished one are *different types*, and using one where the other +belongs is a compile error rather than a runtime panic. ## Using it -All three derives take no arguments and have no helper attributes. `CgpData` accepts a struct or an enum; the -other two accept exactly one: +The derive takes no arguments and has no helper attributes, and it accepts either shape: ```rust use cgp::prelude::*; @@ -57,165 +49,103 @@ Naming follows the family's rules: a named struct field or a variant is keyed by [`Index`](../types/index.md). Generic parameters, lifetimes, and a `where` clause are carried onto everything generated, including the companion types. -### Choosing among the three - -The three are interchangeable wherever the shape allows, so the choice is about what you want the code to -say. - -- **`#[derive(CgpData)]`** is the default. Use it unless you have a reason not to. -- **`#[derive(CgpRecord)]`** says "this is always a struct" and rejects anything else at parse time. -- **`#[derive(CgpVariant)]`** says "this is always an enum", likewise. - -There is no output difference to weigh: `CgpData` on a struct emits what `CgpRecord` emits, and `CgpData` on -an enum emits what `CgpVariant` emits. Reach for a shape-specific one when the name earns its keep as -documentation, or when you want the error for a wrong shape to arrive at the derive rather than further in. +### What each shape emits, and where it is documented -### The struct requirements +The derive dispatches on the shape of its input and then runs one of two fixed sequences. Those two +sequences are what the shape-specific derives run, so each is documented on its own page rather than +twice here: -Every struct shape is accepted. A named-field struct is keyed by field name, a tuple struct by position, and -a fieldless struct is the degenerate case rather than an error — its companion type takes no parameters at -all, so `builder()` is immediately finalizable because there is nothing to track. +| Applied to | It emits | Documented on | +|---|---|---| +| a struct | per-field access, the representation, and the builder | [`#[derive(CgpRecord)]`](./derive_cgp_record.md) | +| an enum | the representation, the constructors, and the extractor | [`#[derive(CgpVariant)]`](./derive_cgp_variant.md) | -### The enum requirement - -**Every variant must carry exactly one unnamed payload.** This is the family's one real restriction, and it -comes from the two slices that take an enum apart: each has to name a single type per variant, and a unit, -multi-field, or struct-style variant gives it none or several. Such a variant fails with -`Expected variant to contain exactly one unnamed field`, and there is no way to opt one variant out — an enum -that mixes shapes cannot take these derives at all. - -The fix is to wrap the richer payload in its own struct, so the variant's value stays a single nameable type: - -```rust -// rejected: a struct-style variant has no single payload type -pub enum Shape { - Circle { radius: f64 }, -} +Read the matching page for the shapes each accepts, the expansion in full, and the corner cases. The one +restriction worth knowing before you get there is on the enum side: **every variant must carry exactly +one unnamed payload**, and there is no per-variant opt-out. -// accepted: the payload is one named type -pub struct Circle { - pub radius: f64, -} +### Choosing among the three -#[derive(CgpData)] -pub enum Shape { - Circle(Circle), -} -``` +The three derives are interchangeable wherever the shape allows, so the choice is about what you want +the code to say. There is no output difference to weigh — `CgpData` on a struct emits exactly what +`CgpRecord` emits, and on an enum exactly what `CgpVariant` emits. -That is idiomatic rather than a workaround — the payload struct usually wants to be a type in its own right, -and it can derive `CgpData` too, which is how a nested shape becomes reachable. +- **`#[derive(CgpData)]`** is the default. Use it unless you have a reason not to. +- **[`#[derive(CgpRecord)]`](./derive_cgp_record.md)** says "this is always a struct" and rejects + anything else at parse time. +- **[`#[derive(CgpVariant)]`](./derive_cgp_variant.md)** says "this is always an enum", likewise. -One escape hatch is worth knowing: [`#[derive(HasFields)]`](./derive_has_fields.md) accepts **all four** -variant shapes, because it only describes a variant rather than deconstructing it. So an enum with mixed -variants can still have a structural representation; what it cannot have is the generic constructor or the -extractor. A variantless enum, meanwhile, is accepted and degenerates the same way a fieldless struct does. +Reach for a shape-specific one when the name earns its keep as documentation, or when you want the error +for a wrong shape to arrive at the derive rather than further in. ## Examples -The record side is most useful for assembling one struct out of pieces. Because both structs derive the -machinery, a builder can copy every shared field from another record in one step and fill in the rest: +One derive covers both halves of a program that builds records and takes enums apart: ```rust -use cgp::core::field::impls::CanBuildFrom; use cgp::prelude::*; #[derive(CgpData)] -pub struct Person { - pub first_name: String, - pub last_name: String, +pub struct Circle { + pub radius: f64, } #[derive(CgpData)] -pub struct Employee { - pub employee_id: u64, - pub first_name: String, - pub last_name: String, +pub struct Rectangle { + pub width: f64, + pub height: f64, } -fn promote(person: Person, id: u64) -> Employee { - Employee::builder() // every field absent - .build_from(person) // first_name + last_name now present - .build_field(PhantomData::, id) - .finalize_build() // all present: this is where it closes -} -``` - -Neither struct knows about the other. They share two field *names*, and the names are matched at the type -level, so `build_from` moves those fields across and leaves `employee_id` for the caller. Remove the -`build_field` line and this stops compiling, because `finalize_build` only exists once every field is present. - -The variant side is most useful for matching generically with a guaranteed-exhaustive end. Each extraction -either yields the payload or hands back a *remainder* whose type has that variant ruled out: - -```rust -use cgp::core::field::traits::FinalizeExtractResult; -use cgp::prelude::*; - #[derive(CgpData)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } - -fn area(shape: Shape) -> f64 { - match shape.to_extractor().extract_field(PhantomData::) { - Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, - Err(remainder) => { - let rect = remainder - .extract_field(PhantomData::) - .finalize_extract_result(); // no variants left, so this cannot fail - rect.width * rect.height - } - } -} ``` -There is no wildcard arm and no `unreachable!()`. After the second extraction the remainder's type has both -variants ruled out, which makes it uninhabited, and `finalize_extract_result` is what discharges a value that -cannot exist. Add a third variant to `Shape` and this function stops compiling until it is handled — the same -guarantee a concrete `match` gives, recovered for code that never names the enum. +`Circle` and `Rectangle` gain field access, a shape, and a builder; `Shape` gains a variant list, +constructors, and an extractor. Worked examples of each half are on the +[record](./derive_cgp_record.md#examples) and [variant](./derive_cgp_variant.md#examples) pages. ## When to reach for it, and when not -**Reach for one of these derives when generic code has to work over the type's own structure.** That is the -test, and it is narrower than it sounds. Most types in a CGP program want -[`#[derive(HasField)]`](./derive_has_field.md) and nothing more, because most of what implementations need -from a context — the type a capability runs against, which supplies values as its fields — is to read one -value out of it. +**Reach for one of these derives when generic code has to work over the type's own structure.** That is +the test, and it is narrower than it sounds. Most types in a CGP program want +[`#[derive(HasField)]`](./derive_has_field.md) and nothing more, because most of what implementations +need from a context — the type a capability runs against, which supplies values as its fields — is to +read one value out of it. The cases that do earn it are specific. -- **A record assembled from independent pieces.** When several parts of a program each contribute part of a - struct and no one place should know the whole type, that is the extensible builder pattern and this is what - it runs on. -- **An enum handled one variant at a time by independent code.** When variants and the operations over them - both need to grow without editing each other, this is the extensible visitor pattern. -- **A framework over any user type.** A serializer, a validator, or a mapper written once against the shape - rather than once per type. +- **A record assembled from independent pieces.** When several parts of a program each contribute part + of a struct and no one place should know the whole type, that is the extensible builder pattern and + this is what it runs on. +- **An enum handled one variant at a time by independent code.** When variants and the operations over + them both need to grow without editing each other, this is the extensible visitor pattern. +- **A framework over any user type.** A serializer, a validator, or a mapper written once against the + shape rather than once per type. And the cases that do not: - **A closed enum with fixed operations.** A `match` is clearer than any machinery, and it already gives - exhaustiveness. Reach for the variant derives when the variant set is open or independent modules must each - contribute one. -- **A struct whose fields are only ever read.** [`#[derive(HasField)]`](./derive_has_field.md) is the whole - answer, and it is one impl pair per field rather than a companion type and a dozen impls. -- **A one-off structural manipulation.** A lighter generic-programming library is a better fit than adopting - this family for a single conversion. - -When you want only part of the output, the family splits along the lines you would expect, and deriving the -slice is the cheaper choice: [`#[derive(HasField)]`](./derive_has_field.md) for the getters, + exhaustiveness. +- **A struct whose fields are only ever read.** [`#[derive(HasField)]`](./derive_has_field.md) is the + whole answer, and it is one impl pair per field rather than a companion type and a dozen impls. +- **A one-off structural manipulation.** A lighter generic-programming library is a better fit than + adopting this family for a single conversion. + +When you want only part of the output, the family splits along the lines you would expect, and deriving +the slice is the cheaper choice: [`#[derive(HasField)]`](./derive_has_field.md) for the getters, [`#[derive(HasFields)]`](./derive_has_fields.md) for the representation, [`#[derive(BuildField)]`](./derive_build_field.md) for the record builder, [`#[derive(ExtractField)]`](./derive_extract_field.md) for the extractor, and -[`#[derive(FromVariant)]`](./derive_from_variant.md) for the variant constructors. The umbrella is the right -call once you want most of them. +[`#[derive(FromVariant)]`](./derive_from_variant.md) for the variant constructors. The umbrella is the +right call once you want most of them. -One honest cost: this is the heaviest derive in CGP. It generates a companion type and, for an enum, two of -them, plus an impl per field or variant on top of the whole-type impls. That is compile-time work, and the -generated types appear by name in error messages. It buys guarantees a runtime builder cannot give, and it is -not free. +One honest cost: this is the heaviest derive in CGP. It generates a companion type and, for an enum, two +of them, plus an impl per field or variant on top of the whole-type impls. That is compile-time work, +and the generated types appear by name in error messages. It buys guarantees a runtime builder cannot +give, and it is not free. ## Under the hood @@ -223,194 +153,52 @@ not free. ### Advanced -This section shows what the derives generate. You do not need it to use them, but the companion types appear -by name in compiler errors, so recognizing one turns an intimidating error into a legible one. -`cargo cgp expand` prints the same thing for your own code, with the tags resugared. +This section covers only what the umbrella itself does. The expansions are on the two shape pages, +because that is where they belong once the derives are documented separately. ::: -`#[derive(CgpData)]` dispatches on the shape of its input and then runs one of two fixed sequences. Nothing -about the umbrella is special: `#[derive(CgpRecord)]` enters the first sequence directly and -`#[derive(CgpVariant)]` the second, which is why all three agree on their output. - -### The record expansion +Nothing about the umbrella is special. `#[derive(CgpData)]` inspects the item, dispatches on whether it +is a struct or an enum, and then runs exactly the same code path the matching shape-specific derive +runs — [`#[derive(CgpRecord)]`](./derive_cgp_record.md#under-the-hood) enters the first directly and +[`#[derive(CgpVariant)]`](./derive_cgp_variant.md#under-the-hood) the second. That shared dispatch is +why all three agree on their output, and why a claim about what `CgpData` emits is always a claim about +one of the other two. -For a struct, the derive emits three groups in order. From: - -```rust -#[derive(CgpData)] -pub struct Person { - pub first_name: String, - pub last_name: String, -} -``` - -it first emits the **per-field access** — a `HasField` and a `HasFieldMut` impl per field, exactly what -[`#[derive(HasField)]`](./derive_has_field.md) produces on its own. Then the **representation**, exposing the -struct as a product of named entries with conversions in both directions, which is -[`#[derive(HasFields)]`](./derive_has_fields.md)'s output: - -```rust -impl HasFields for Person { - type Fields = Product![ - Field, - Field, - ]; -} - -// plus HasFieldsRef, FromFields, ToFields, ToFieldsRef -``` - -Then the **builder**, which is [`#[derive(BuildField)]`](./derive_build_field.md)'s output and where the -companion type appears. Each field's type is wrapped in a [`MapType`](../traits/map_type.md) marker, so a -field can be present (`IsPresent`, holding the value) or absent (`IsNothing`, holding `()`): - -```rust -pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { - pub first_name: <__F0__ as MapType>::Map, - pub last_name: <__F1__ as MapType>::Map, -} - -impl HasBuilder for Person { - type Builder = __PartialPerson; // the empty builder - // ... -} - -impl FinalizeBuild for __PartialPerson { - // ... only at all-present -} -``` - -That pair of impls is the whole safety argument: `builder()` starts at all-absent, each `build_field` flips -one marker, and `finalize_build` exists only at all-present, so finalizing early is a missing impl rather than -a runtime check. The per-field `UpdateField` impls that move a marker, and the `HasField` impls on the -companion that let a set field be read back, follow. - -### The variant expansion - -For an enum, the derive emits three groups too, but a different three. From: - -```rust -#[derive(CgpData)] -pub enum Shape { - Circle(Circle), - Rectangle(Rectangle), -} -``` - -it first emits the **representation** over a sum rather than a product: - -```rust -impl HasFields for Shape { - type Fields = Sum![ - Field, - Field, - ]; -} - -// plus HasFieldsRef, FromFields, ToFields, ToFieldsRef -``` - -Then the **constructors**, one per variant, which is -[`#[derive(FromVariant)]`](./derive_from_variant.md)'s output: - -```rust -impl FromVariant for Shape { - type Value = Circle; - - fn from_variant(_tag: PhantomData, value: Circle) -> Self { - Self::Circle(value) - } -} -``` - -Then the **extractor**, which is [`#[derive(ExtractField)]`](./derive_extract_field.md)'s output and where two -companion enums appear — `__PartialShape` for owned extraction and `__PartialRefShape` for borrowed. A -variant's payload is wrapped in a marker that is either `IsPresent` or `IsVoid`, the latter mapping it to the -uninhabited `Void`: - -```rust -pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { - Circle(<__F0__ as MapType>::Map), - Rectangle(<__F1__ as MapType>::Map), -} - -impl HasExtractor for Shape { - type Extractor = __PartialShape; // every variant still possible - // ... -} - -impl FinalizeExtract for __PartialShape { // nothing left: uninhabited - // ... -} -``` - -Note the asymmetry with the record side, which is the detail most worth carrying away: **a record uses -`IsNothing` for a field that is not there, and a variant uses `IsVoid` for one that has been ruled out.** -`IsNothing` maps a type to `()`, which is inhabited; `IsVoid` maps it to `Void`, which is not. That is exactly -why extraction ends the way it does — once every variant is `IsVoid` the whole companion enum is uninhabited, -so a value of it cannot exist and can be discharged to produce anything. - -The companion names are reserved: `__Partial{Name}` and, for the borrowed extractor, `__PartialRef{Name}`. -They keep the original type's visibility, so a `pub` struct or enum yields a `pub` companion. - -Each generated impl is aimed at the token it came from — a per-field impl at its field, a per-variant impl at -its variant, a whole-type impl at the type name — so a conflict with a hand-written impl underlines that token -rather than the whole derive. +Applied to a union, all three fail: the family models products and sums, and a union is neither. ## Gotchas -**Every variant needs exactly one unnamed payload.** A unit, multi-field, or struct-style variant fails, with -no per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in the family that -accepts all four shapes, so it is what an enum with mixed variants gets. - -**The companion type carries none of your attributes.** The derive clears them, so a -`#[derive(Debug, Clone)]` on the record does not reach `__Partial{Name}` and a partially-built value can be -neither printed nor cloned. Read a set field back through the companion's `HasField` impl instead. - -**A tuple struct's builder is keyed by position.** Its companion exposes `UpdateField, _>` rather -than symbol-keyed impls, so `build_field` takes `PhantomData::>`. - -**A single-field tuple struct's representation is the inner type directly**, not a one-element product — the -newtype special case described on the [`HasFields`](./derive_has_fields.md) page, which the record path -inherits. - -**Absence is spelled differently on the two sides.** `IsNothing` for a missing record field, `IsVoid` for a -ruled-out variant, and they are not interchangeable. An error mentioning the wrong one usually means record -and variant machinery have been crossed. +**Which gotchas apply depends on the shape**, and the shape pages carry them: the +[record ones](./derive_cgp_record.md#gotchas) — the companion's cleared attributes, position-keyed tuple +builders, the newtype special case — and the [variant ones](./derive_cgp_variant.md#gotchas) — the +one-payload rule and the seven reserved variant names. Two are worth repeating here because they catch +people who reached for the umbrella without reading either. -**Seven variant names are reserved on an enum.** Because the generated impls name their associated types -through `Self::…`, a variant called `Fields`, `FieldsRef`, `Value`, `Remainder`, `Extractor`, `ExtractorRef`, -or `ExtractorMut` makes that path ambiguous and the derive fails with `ambiguous associated item`, headlined at -the derive. Whether the message also names the variant depends on which part collided: the representation and -constructor impls are generated for your enum and point a note at the real variant, while the extractor's are -generated for the companion enums and point back at the derive. Renaming the variant is the fix. Record field names are unaffected, -since a field is not in the same namespace as an associated type. +**Every enum variant needs exactly one unnamed payload.** A unit, multi-field, or struct-style variant +fails, with no per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in +the family that accepts all four shapes, so it is what an enum with mixed variants gets. -**The degenerate shapes compile.** A fieldless struct yields a parameterless companion whose `builder()` is -immediately finalizable, and a variantless enum yields bare companion enums. Neither is an error, and neither -does anything useful. +**Absence is spelled differently on the two sides.** `IsNothing` for a missing record field, `IsVoid` for +a ruled-out variant, and they are not interchangeable. An error mentioning the wrong one usually means +record and variant machinery have been crossed. **These are the heaviest derives in CGP.** One `#[derive(CgpData)]` on a five-field struct generates a companion type and roughly twenty impls. If only part of the output is wanted, derive the slice. ## Related constructs +- [`#[derive(CgpRecord)]`](./derive_cgp_record.md) and + [`#[derive(CgpVariant)]`](./derive_cgp_variant.md) — the two faces this dispatches to. - [`#[derive(HasField)]`](./derive_has_field.md) — the per-field access slice, on its own. -- [`#[derive(HasFields)]`](./derive_has_fields.md) — the representation slice, on its own, and the only one - that accepts every variant shape. +- [`#[derive(HasFields)]`](./derive_has_fields.md) — the representation slice, on its own, and the only + one that accepts every variant shape. - [`#[derive(BuildField)]`](./derive_build_field.md) — the record builder slice, on its own. - [`#[derive(ExtractField)]`](./derive_extract_field.md) — the extractor slice, on its own. - [`#[derive(FromVariant)]`](./derive_from_variant.md) — the variant constructors, on their own. -- [`HasBuilder`](../traits/has_builder.md) — the builder trait family the record side generates impls for. -- [`ExtractField`](../traits/extract_field.md) — the extractor trait family the variant side generates impls - for. -- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers the companion types are - parameterized by. -- [`CanUpcast`](../traits/cast.md) — converting between two types whose shapes overlap, built on this - machinery. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that route a record or a - variant to per-entry handlers. +- [`HasBuilder`](../traits/has_builder.md) and [`ExtractField`](../traits/extract_field.md) — the two + trait families the shapes generate impls for. +- [`MapType`](../traits/map_type.md) — the markers the companion types are parameterized by. The ideas behind it: @@ -423,9 +211,7 @@ The ideas behind it: ## Source -- Entry points: [`cgp_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_data.rs), - [`cgp_record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_record.rs), - and [`cgp_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_variant.rs) +- Entry point: [`cgp_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_data.rs) - Shape dispatch: [`cgp_data/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/item.rs) - Record and variant codegen: [`cgp_data/record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/record.rs) and [`cgp_data/variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/variant.rs) diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md new file mode 100644 index 00000000..dc43a45f --- /dev/null +++ b/docs/reference/derives/derive_cgp_record.md @@ -0,0 +1,232 @@ +--- +sidebar_label: '#[derive(CgpRecord)]' +--- + +# `#[derive(CgpRecord)]` + +The extensible-data derive for a struct. + +## What it's for + +A plain Rust struct is opaque to generic code. There is no way to refer to "the `first_name` field" +through a type parameter, so anything that must work across several structs ends up written once per +struct. + +`#[derive(CgpRecord)]` turns a struct into **extensible data**: a type whose fields generic code can +name, read, and assemble without ever mentioning the concrete type. It produces the whole record half +of the family in one line — per-field access, the whole-shape field list, and an incremental builder +that fills a value one field at a time. + +It is the struct-only face of [`#[derive(CgpData)]`](./derive_cgp_data.md). The two run the same code +and emit the same output on a struct; the difference is that this one **rejects an enum at parse +time**, so a type that is meant to stay a struct says so and the error arrives at the derive rather +than further along. + +## Using it + +The derive takes no arguments and has no helper attributes: + +```rust +use cgp::prelude::*; + +#[derive(CgpRecord)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +**Every struct shape is accepted.** A named-field struct is keyed by +[`Symbol!`](../macros/symbol.md), a tuple struct by [`Index`](../types/index.md), and a fieldless +struct is the degenerate case rather than an error — its companion type takes no parameters at all, so +`builder()` is immediately finalizable because there is nothing to track. + +Generic parameters, lifetimes, and a `where` clause are carried onto everything generated, including +the companion type. + +### What it generates + +Three groups, each of which is also available as a derive of its own when only part of the output is +wanted: + +| Group | The slice on its own | +|---|---| +| Per-field access — a `HasField` and a `HasFieldMut` impl per field | [`#[derive(HasField)]`](./derive_has_field.md) | +| The representation — the struct as a product of named entries, with conversions | [`#[derive(HasFields)]`](./derive_has_fields.md) | +| The builder — the partial companion type and the impls that fill it | [`#[derive(BuildField)]`](./derive_build_field.md) | + +## Examples + +The record machinery is most useful for assembling one struct out of pieces. Because both structs +derive it, a builder can copy every shared field from another record in one step and fill in the rest: + +```rust +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +#[derive(CgpRecord)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +#[derive(CgpRecord)] +pub struct Employee { + pub employee_id: u64, + pub first_name: String, + pub last_name: String, +} + +fn promote(person: Person, id: u64) -> Employee { + Employee::builder() // every field absent + .build_from(person) // first_name + last_name now present + .build_field(PhantomData::, id) + .finalize_build() // all present: this is where it closes +} +``` + +Neither struct knows about the other. They share two field *names*, matched at the type level, so +[`build_from`](../traits/can_build_from.md) moves those fields across and leaves `employee_id` for the +caller. Remove the `build_field` line and this stops compiling, because +[`finalize_build`](../traits/finalize_build.md) only exists once every field is present. + +## When to reach for it, and when not + +**Reach for it when generic code has to work over the struct's own structure**, and prefer +[`#[derive(CgpData)]`](./derive_cgp_data.md) unless naming the shape earns its keep as documentation. +The two are interchangeable on a struct, so this is a choice about what the code says rather than +about what it emits. + +- **Use `#[derive(CgpRecord)]`** to state that a type is always a struct, and to have a later change + to an enum fail at the derive rather than inside the generated code. +- **Use [`#[derive(CgpData)]`](./derive_cgp_data.md)** as the default, especially in a module where + structs and enums both take the derive. +- **Use [`#[derive(HasField)]`](./derive_has_field.md) alone** when the fields are only ever read. That + is most types in a CGP program, and it is one impl pair per field rather than a companion type and a + dozen impls. +- **Derive the slice you want** — [`HasFields`](./derive_has_fields.md) for the representation, + [`BuildField`](./derive_build_field.md) for the builder — when only part of the output is wanted. The + umbrella is the right call once you want most of them. + +The full argument for when a type earns the extensible-data machinery at all is on the +[umbrella page](./derive_cgp_data.md#when-to-reach-for-it-and-when-not). + +## Under the hood + +:::note + +### Advanced + +This section shows what the derive generates. You do not need it to use the derive, but the companion +type appears by name in every builder error, so recognizing one turns an intimidating error into a +legible one. `cargo cgp expand` prints the same thing for your own code, with the tags resugared. + +::: + +The derive emits three groups in order. From: + +```rust +#[derive(CgpRecord)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +it first emits the **per-field access** — a [`HasField`](../traits/has_field.md) and a +[`HasFieldMut`](../traits/has_field_mut.md) impl per field, exactly what +[`#[derive(HasField)]`](./derive_has_field.md) produces on its own. + +Then the **representation**, exposing the struct as a product of named entries with conversions in both +directions, which is [`#[derive(HasFields)]`](./derive_has_fields.md)'s output: + +```rust +impl HasFields for Person { + type Fields = Product![ + Field, + Field, + ]; +} + +// plus HasFieldsRef, FromFields, ToFields, ToFieldsRef +``` + +Then the **builder**, which is [`#[derive(BuildField)]`](./derive_build_field.md)'s output and where the +companion type appears. Each field's type is wrapped in a [`MapType`](../traits/map_type.md) marker, so +a field can be present (`IsPresent`, holding the value) or absent (`IsNothing`, holding `()`): + +```rust +pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { + pub first_name: <__F0__ as MapType>::Map, + pub last_name: <__F1__ as MapType>::Map, +} + +impl HasBuilder for Person { + type Builder = __PartialPerson; // the empty builder + // ... +} + +impl FinalizeBuild for __PartialPerson { + // ... only at all-present +} +``` + +That pair of impls is the whole safety argument: `builder()` starts at all-absent, each +[`build_field`](../traits/build_field.md) flips one marker, and +[`finalize_build`](../traits/finalize_build.md) exists only at all-present, so finalizing early is a +missing impl rather than a runtime check. The per-field [`UpdateField`](../traits/update_field.md) impls +that move a marker, and the `HasField` impls on the companion that let a set field be read back, follow. + +The companion is named `__Partial{Name}` and keeps the original type's visibility, so a `pub` struct +yields a `pub` companion. Each generated impl is aimed at the token it came from — a per-field impl at +its field, a whole-type impl at the type name — so a conflict with a hand-written impl underlines that +token rather than the whole derive. + +## Gotchas + +**The companion type carries none of your attributes.** The derive clears them, so a +`#[derive(Debug, Clone)]` on the record does not reach `__Partial{Name}` and a partially-built value can +be neither printed nor cloned. Read a set field back through the companion's +[`HasField`](../traits/has_field.md) impl instead. + +**A tuple struct's builder is keyed by position.** Its companion exposes `UpdateField, _>` +rather than symbol-keyed impls, so `build_field` takes `PhantomData::>`. + +**A single-field tuple struct's representation is the inner type directly**, not a one-element product — +the newtype special case described on the [`#[derive(HasFields)]`](./derive_has_fields.md) page, which +this derive inherits. + +**A fieldless struct compiles and does nothing useful.** It yields a parameterless companion whose +`builder()` is immediately finalizable. + +**An enum is rejected**, which is the point of the name. Reach for +[`#[derive(CgpVariant)]`](./derive_cgp_variant.md) or the umbrella. + +**This is one of the heaviest derives in CGP.** One of these on a five-field struct generates a +companion type and roughly twenty impls. If only part of the output is wanted, derive the slice. + +## Related constructs + +- [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella, which dispatches here for a struct. +- [`#[derive(CgpVariant)]`](./derive_cgp_variant.md) — the enum face. +- [`#[derive(HasField)]`](./derive_has_field.md), [`#[derive(HasFields)]`](./derive_has_fields.md), and + [`#[derive(BuildField)]`](./derive_build_field.md) — the three slices this emits. +- [`HasBuilder`](../traits/has_builder.md) — the builder family it generates impls for. +- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsNothing` markers the companion is + parameterized by. +- [`CanBuildFrom`](../traits/can_build_from.md) — merging one record into another's builder. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields, and + the extensible builder pattern. + +## Source + +- Entry point: [`cgp_record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_record.rs) +- Record codegen: [`cgp_data/record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/record.rs) +- Runtime traits: [`cgp-field/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-field/src/traits) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md new file mode 100644 index 00000000..a672c4b7 --- /dev/null +++ b/docs/reference/derives/derive_cgp_variant.md @@ -0,0 +1,274 @@ +--- +sidebar_label: '#[derive(CgpVariant)]' +--- + +# `#[derive(CgpVariant)]` + +The extensible-data derive for an enum. + +## What it's for + +A plain Rust enum is opaque to generic code. There is no way to refer to "the `Circle` variant" through +a type parameter, so anything that must work across several enums ends up written once per enum — and +the `match` that would make it exhaustive can only be written where the concrete enum is named. + +`#[derive(CgpVariant)]` turns an enum into **extensible data**: a type whose variants generic code can +name, construct, and take apart without ever mentioning the concrete type. It produces the whole +variant half of the family in one line — the whole-shape variant list, a constructor per variant, and an +incremental extractor that peels variants off one at a time while tracking which are still possible. + +It is the enum-only face of [`#[derive(CgpData)]`](./derive_cgp_data.md). The two run the same code and +emit the same output on an enum; the difference is that this one **rejects a struct at parse time**. + +## Using it + +The derive takes no arguments and has no helper attributes: + +```rust +use cgp::prelude::*; + +#[derive(CgpVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +Each variant is keyed by [`Symbol!`](../macros/symbol.md) of its name. Generic parameters, lifetimes, +and a `where` clause are carried onto everything generated, including the companion enums. + +### Every variant needs exactly one unnamed payload + +**This is the family's one real restriction.** It comes from the two slices that take an enum apart: +each has to name a single type per variant, and a unit, multi-field, or struct-style variant gives it +none or several. Such a variant fails with `Expected variant to contain exactly one unnamed field`, and +there is **no way to opt one variant out** — an enum that mixes shapes cannot take this derive at all. + +The fix is to wrap the richer payload in its own struct, so the variant's value stays a single nameable +type: + +```rust +// rejected: a struct-style variant has no single payload type +pub enum Shape { + Circle { radius: f64 }, +} + +// accepted: the payload is one named type +pub struct Circle { + pub radius: f64, +} + +#[derive(CgpVariant)] +pub enum Shape { + Circle(Circle), +} +``` + +That is idiomatic rather than a workaround — the payload struct usually wants to be a type in its own +right, and it can derive [`#[derive(CgpRecord)]`](./derive_cgp_record.md) too, which is how a nested +shape becomes reachable. + +One escape hatch is worth knowing: [`#[derive(HasFields)]`](./derive_has_fields.md) accepts **all four** +variant shapes, because it only describes a variant rather than deconstructing it. So an enum with mixed +variants can still have a structural representation; what it cannot have is the generic constructor or +the extractor. + +### What it generates + +Three groups, each of which is also available as a derive of its own: + +| Group | The slice on its own | +|---|---| +| The representation — the enum as a sum of named entries, with conversions | [`#[derive(HasFields)]`](./derive_has_fields.md) | +| The constructors — one per variant | [`#[derive(FromVariant)]`](./derive_from_variant.md) | +| The extractor — two partial companion enums and the impls that narrow them | [`#[derive(ExtractField)]`](./derive_extract_field.md) | + +## Examples + +The variant machinery is most useful for matching generically with a guaranteed-exhaustive end. Each +extraction either yields the payload or hands back a *remainder* whose type has that variant ruled out: + +```rust +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::prelude::*; + +#[derive(CgpVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); // no variants left, so this cannot fail + rect.width * rect.height + } + } +} +``` + +There is no wildcard arm and no `unreachable!()`. After the second extraction the remainder's type has +both variants ruled out, which makes it uninhabited, and +[`finalize_extract_result`](../traits/finalize_extract_result.md) is what discharges a value that cannot +exist. Add a third variant to `Shape` and this function stops compiling until it is handled — the same +guarantee a concrete `match` gives, recovered for code that never names the enum. + +## When to reach for it, and when not + +**Reach for it when generic code has to work over the enum's own structure**, and prefer +[`#[derive(CgpData)]`](./derive_cgp_data.md) unless naming the shape earns its keep as documentation. + +- **Use `#[derive(CgpVariant)]`** to state that a type is always an enum, and to have a later change to + a struct fail at the derive. +- **Use [`#[derive(CgpData)]`](./derive_cgp_data.md)** as the default. +- **Prefer a `match`** for a closed enum with fixed operations. It is clearer than any machinery and it + already gives exhaustiveness. Reach for the variant derives when the variant set is open, or when + independent modules must each contribute a variant or an operation over one. +- **Derive the slice you want** — [`FromVariant`](./derive_from_variant.md) alone if code only needs to + *construct*, [`ExtractField`](./derive_extract_field.md) alone if it only needs to deconstruct, + [`HasFields`](./derive_has_fields.md) alone for the shape, and it is the only one of the three that + accepts every variant shape. + +The full argument for when a type earns the extensible-data machinery at all is on the +[umbrella page](./derive_cgp_data.md#when-to-reach-for-it-and-when-not). + +## Under the hood + +:::note + +### Advanced + +This section shows what the derive generates and why the extraction chain can end without a wildcard. +You do not need it to use the derive, but the companion enums appear by name in every extraction error. +`cargo cgp expand` prints the same thing for your own code, with the tags resugared. + +::: + +The derive emits three groups in order. From: + +```rust +#[derive(CgpVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} +``` + +it first emits the **representation**, over a sum rather than a product: + +```rust +impl HasFields for Shape { + type Fields = Sum![ + Field, + Field, + ]; +} + +// plus HasFieldsRef, FromFields, ToFields, ToFieldsRef +``` + +Then the **constructors**, one per variant, which is +[`#[derive(FromVariant)]`](./derive_from_variant.md)'s output: + +```rust +impl FromVariant for Shape { + type Value = Circle; + + fn from_variant(_tag: PhantomData, value: Circle) -> Self { + Self::Circle(value) + } +} +``` + +Then the **extractor**, which is [`#[derive(ExtractField)]`](./derive_extract_field.md)'s output and +where two companion enums appear — `__PartialShape` for owned extraction and `__PartialRefShape` for +borrowed. A variant's payload is wrapped in a [`MapType`](../traits/map_type.md) marker that is either +`IsPresent` or `IsVoid`, the latter mapping it to the uninhabited `Void`: + +```rust +pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { + Circle(<__F0__ as MapType>::Map), + Rectangle(<__F1__ as MapType>::Map), +} + +impl HasExtractor for Shape { + type Extractor = __PartialShape; // every variant still possible + // ... +} + +impl FinalizeExtract for __PartialShape { // nothing left: uninhabited + // ... +} +``` + +**Note the asymmetry with the record side, which is the detail most worth carrying away: a record uses +`IsNothing` for a field that is not there, and a variant uses `IsVoid` for one that has been ruled out.** +`IsNothing` maps a type to `()`, which is inhabited; `IsVoid` maps it to `Void`, which is not. That is +exactly why extraction ends the way it does — once every variant is `IsVoid` the whole companion enum is +uninhabited, so a value of it cannot exist and can be discharged to produce anything. + +The companion names are reserved: `__Partial{Name}` and `__PartialRef{Name}`. They keep the original +type's visibility. Each generated impl is aimed at the token it came from, so a conflict with a +hand-written impl underlines that variant rather than the whole derive. + +## Gotchas + +**Every variant needs exactly one unnamed payload**, with no per-variant opt-out. +[`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in the family that accepts all four +shapes, so it is what an enum with mixed variants gets. + +**Seven variant names are reserved.** Because the generated impls name their associated types through +`Self::…`, a variant called `Fields`, `FieldsRef`, `Value`, `Remainder`, `Extractor`, `ExtractorRef`, or +`ExtractorMut` makes that path ambiguous and the derive fails with `ambiguous associated item`, headlined +at the derive. Whether the message also names the variant depends on which part collided: the +representation and constructor impls are generated for your enum and point a note at the real variant, +while the extractor's are generated for the companion enums and point back at the derive. Renaming the +variant is the fix. Record field names are unaffected, since a field is not in the same namespace as an +associated type. + +**The companion enums carry none of your attributes.** The derive clears them, so an extraction +remainder is neither `Debug` nor `PartialEq` however the enum is derived — `assert_eq!` over a +`Result` does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. + +**Absence is spelled differently on the two sides.** `IsVoid` for a ruled-out variant, `IsNothing` for a +missing record field, and they are not interchangeable. An error naming the wrong one usually means +record and variant machinery have been crossed. + +**A variantless enum compiles and does nothing useful.** It yields bare companion enums. + +**A struct is rejected**, which is the point of the name. Reach for +[`#[derive(CgpRecord)]`](./derive_cgp_record.md) or the umbrella. + +## Related constructs + +- [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella, which dispatches here for an enum. +- [`#[derive(CgpRecord)]`](./derive_cgp_record.md) — the struct face. +- [`#[derive(HasFields)]`](./derive_has_fields.md), [`#[derive(FromVariant)]`](./derive_from_variant.md), + and [`#[derive(ExtractField)]`](./derive_extract_field.md) — the three slices this emits. +- [`ExtractField`](../traits/extract_field.md) — the extractor family it generates impls for. +- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsVoid` markers the companions are parameterized + by. +- [`CanUpcast`](../traits/can_upcast.md) and [`CanDowncast`](../traits/can_downcast.md) — converting + between two enums whose variants overlap, built on this machinery. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that route a variant to + the implementation handling it. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — the enum half, and the extensible visitor + pattern. +- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to a handler per variant. + +## Source + +- Entry point: [`cgp_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_variant.rs) +- Variant codegen: [`cgp_data/variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/variant.rs) +- Runtime traits: [`cgp-field/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-field/src/traits) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index a060f19d..7d1549ba 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -364,7 +364,7 @@ enum's own variant list rather than repeating it at each site. `FinalizeExtract`, and `FinalizeExtractResult`. - [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsVoid` markers the companion enums are parameterized by. -- [`CanUpcast`](../traits/cast.md) — upcasting and downcasting between enums, which reuse this recursion. +- [`CanUpcast`](../traits/can_upcast.md) — upcasting and downcasting between enums, which reuse this recursion. - [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain an enum's shape is built from. - [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build an extraction chain diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 57ef5dcc..1d45e23b 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -114,13 +114,15 @@ about, then widening it. A routine that only produces two of a large enum's vari enum, constructs into that, and lifts the result into the full type with an upcast: ```rust +use cgp::core::field::impls::CanUpcast; // not in the prelude + let expr = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); ``` The upcast always succeeds, because every variant of the smaller enum has a home in the larger one. That is the construction-side counterpart of reading a field through a getter: the implementation names only what it needs, and the widening is checked. Upcasting is documented with the other -[structural casts](../traits/cast.md), and it is built on the same per-variant machinery as this derive. +[structural casts](../traits/can_upcast.md), and it is built on the same per-variant machinery as this derive. ## When to reach for it, and when not @@ -238,7 +240,7 @@ and, as with the other empty shapes, means a mistake shows up later rather than choosing one variant. - [`FromVariant`](../traits/from_variant.md) — the trait this generates impls of. - [`Symbol!`](../macros/symbol.md) — the tag that names a variant. -- [`CanUpcast`](../traits/cast.md) — widening a smaller enum into a larger one, built on these constructors. +- [`CanUpcast`](../traits/can_upcast.md) — widening a smaller enum into a larger one, built on these constructors. - [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain the constructed variants correspond to. diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index aa6d23c5..c887e103 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -343,8 +343,8 @@ one letter and the outputs do not overlap. - [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that name an entry. - [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains the sugar expands to. -- [`AppendProduct`](../traits/product_ops.md) — operations over a shape once you have one. -- [`CanUpcast`](../traits/cast.md) — converting between two types whose shapes overlap. +- [`AppendProduct`](../traits/append_product.md) — operations over a shape once you have one. +- [`CanUpcast`](../traits/can_upcast.md) — converting between two types whose shapes overlap. The ideas behind it: diff --git a/docs/reference/index.md b/docs/reference/index.md index d6b7230f..f28b49fe 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -132,28 +132,38 @@ Providers in this family are written from plain functions with [`#[cgp_computer]`](./macros/cgp_computer.md) and [`#[cgp_producer]`](./macros/cgp_producer.md), and composed with the [handler combinators](./providers/handler_combinators.md), the [dispatch combinators](./providers/dispatch_combinators.md), and the -[monad providers](./providers/monad_providers.md) built on the -[monad traits](./traits/monad.md). [`#[cgp_auto_dispatch]`](./macros/cgp_auto_dispatch.md) generates a -dispatching handler from a per-type trait. +[monad providers](./providers/monad_providers.md) built on the monad traits — +[`MonadicBind`](./traits/monadic_bind.md), [`ContainsValue`](./traits/contains_value.md), +[`LiftValue`](./traits/lift_value.md), and [`MonadicTrans`](./traits/monadic_trans.md). +[`#[cgp_auto_dispatch]`](./macros/cgp_auto_dispatch.md) generates a dispatching handler from a per-type +trait. ### Work with a type's structure These let generic code build and read structs and enums by their fields and variants without naming the concrete type. What a type opts in with is a derive: -[`#[derive(CgpData)]`](./derives/derive_cgp_data.md) is the umbrella one, and its individual slices are -[`#[derive(HasFields)]`](./derives/derive_has_fields.md), +[`#[derive(CgpData)]`](./derives/derive_cgp_data.md) is the umbrella one, with +[`#[derive(CgpRecord)]`](./derives/derive_cgp_record.md) and +[`#[derive(CgpVariant)]`](./derives/derive_cgp_variant.md) as its struct and enum faces, and its +individual slices are [`#[derive(HasFields)]`](./derives/derive_has_fields.md), [`#[derive(BuildField)]`](./derives/derive_build_field.md), [`#[derive(ExtractField)]`](./derives/derive_extract_field.md), and [`#[derive(FromVariant)]`](./derives/derive_from_variant.md). -Each of those generates a trait, and the traits are where the operations live: the whole-shape view in -[`HasFields`](./traits/has_fields.md), the builder family in -[`HasBuilder`](./traits/has_builder.md), the extractor family in -[`ExtractField`](./traits/extract_field.md), [`FromVariant`](./traits/from_variant.md), the presence -markers of [`MapType`](./traits/map_type.md), the list algebra of -[`AppendProduct`](./traits/product_ops.md), the structural -[casts](./traits/cast.md), and the [optional-field extensions](./traits/optional_fields.md). Each entry -in a shape is a [`Field`](./types/field.md). +Each of those generates traits, and the traits are where the operations live. The whole-shape view is +[`HasFields`](./traits/has_fields.md) with its conversions [`ToFields`](./traits/to_fields.md) and +[`FromFields`](./traits/from_fields.md); the builder family runs from +[`HasBuilder`](./traits/has_builder.md) through [`BuildField`](./traits/build_field.md) to +[`FinalizeBuild`](./traits/finalize_build.md); the extractor family runs from +[`HasExtractor`](./traits/has_extractor.md) through [`ExtractField`](./traits/extract_field.md) to +[`FinalizeExtract`](./traits/finalize_extract.md), with +[`FromVariant`](./traits/from_variant.md) constructing rather than deconstructing. Underneath sit the +presence markers of [`MapType`](./traits/map_type.md), the list algebra of +[`AppendProduct`](./traits/append_product.md), the structural casts +[`CanUpcast`](./traits/can_upcast.md) and [`CanBuildFrom`](./traits/can_build_from.md), and the +optional-field extensions starting at +[`HasOptionalBuilder`](./traits/has_optional_builder.md). Each entry in a shape is a +[`Field`](./types/field.md). ### Keep large wiring manageable @@ -174,8 +184,8 @@ sugar — [`Symbol!`](./macros/symbol.md) for a field name, [`Product!`](./macro [`Sum!`](./macros/sum.md) for its dual, [`Path!`](./macros/path.md) for a route — and only need to recognize [what they expand into](./types/type_level_spines.md) when it appears in an error message. [`Index`](./types/index.md) tags a tuple field and [`Life`](./types/life.md) lifts a lifetime into a -type, while [`StaticFormat`](./traits/static_format.md) turns type-level strings back into runtime -data. +type, while [`StaticString`](./traits/static_string.md) turns a type-level string back into runtime +data and [`ConcatPath`](./traits/concat_path.md) joins two paths. When wiring fails, three traits are what you will see named: [`DelegateComponent`](./traits/delegate_component.md), @@ -192,17 +202,12 @@ these names, this is where it lives. | Looking for | It's on | |---|---| | `#[cgp_new_provider]` | [`#[cgp_provider]`](./macros/cgp_provider.md) | -| `#[derive(CgpRecord)]`, `#[derive(CgpVariant)]` | [`#[derive(CgpData)]`](./derives/derive_cgp_data.md) | | `UseFieldRef`, `UseFields` | [`UseField`](./providers/use_field.md) | | `CanSendRun` | [`CanRun`](./components/runner.md) | | `CanWrapError` | [`CanRaiseError`](./components/can_raise_error.md) | | `HasRuntimeType` | [`HasRuntime`](./components/has_runtime.md) | | `WithType`, `WithField`, `WithContext` | [`WithProvider`](./providers/with_provider.md) | | `Cons`, `Nil`, `Either`, `Void`, `Chars`, `PathCons` | [Type-level spines](./types/type_level_spines.md) | -| `HasFieldMut`, `FieldGetter` | [`HasField`](./traits/has_field.md) | -| `ConcatProduct`, `MapFields` | [`AppendProduct`](./traits/product_ops.md) | -| `CanDowncast`, `CanBuildFrom` | [`CanUpcast`](./traits/cast.md) | -| `StaticString`, `ConcatPath` | [`StaticFormat`](./traits/static_format.md) | | `ComposeHandlers`, `PipeHandlers`, `ReturnInput`, `Promote*` | [Handler combinators](./providers/handler_combinators.md) | | `MatchWithHandlers`, `ExtractFieldAndHandle` | [Dispatch combinators](./providers/dispatch_combinators.md) | | `PipeMonadic`, `BindOk`, `BindErr` | [Monad providers](./providers/monad_providers.md) | @@ -211,14 +216,11 @@ these names, this is where it lives. | `UseInputDelegate` | [Handler combinators](./providers/handler_combinators.md) | | `RaiseInfallible`, `DiscardDetail`, `PanicOnError` | [Error providers](./providers/error_providers.md) | | `ComputerRef`, `AsyncComputer`, `TryComputerRef`, `HandlerRef` | the page for the component they vary — [`Computer`](./components/computer.md), [`TryComputer`](./components/try_computer.md), [`Handler`](./components/handler.md) | -| `BuildField`, `UpdateField`, `FinalizeBuild` | [`HasBuilder`](./traits/has_builder.md) | -| `HasExtractor`, `FinalizeExtract` | [`ExtractField`](./traits/extract_field.md) | -| `IsPresent`, `IsNothing` | [`MapType`](./traits/map_type.md) | -| `MonadicTrans`, `MonadicBind`, `LiftValue`, `ContainsValue` | [Monad traits](./traits/monad.md) | +| `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` | [`MapType`](./traits/map_type.md) | +| `IsRef`, `IsMut`, `IsOwned` | [`MapTypeRef`](./traits/map_type_ref.md) | | `product!` (the value-level form) | [`Product!`](./macros/product.md) | | `#[impl_generics(...)]` | [`#[cgp_fn]`](./macros/cgp_fn.md) | | `#[prefix(...)]` | [`cgp_namespace!`](./macros/cgp_namespace.md) | -| `#[default_impl(...)]` | [`DefaultNamespace`](./traits/default_namespace.md) | | `#[check_trait(...)]`, `#[check_providers(...)]` | [`check_components!`](./macros/check_components.md) | | `#[check_params(...)]`, `#[skip_check]` | [`delegate_and_check_components!`](./macros/delegate_and_check_components.md) | diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 33467717..fbf3f8d4 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -209,7 +209,7 @@ the order *is* the execution order. - [`Symbol!`](./symbol.md) — the name half of a `Field` entry. - [`HasFields`](../traits/has_fields.md) — the trait that exposes a struct's shape as one of these lists. - [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates that list for you. -- [`AppendProduct`](../traits/product_ops.md) — the operations that combine and transform these lists. +- [`AppendProduct`](../traits/append_product.md) — the operations that combine and transform these lists. - [Handler combinators](../providers/handler_combinators.md) — where `Product!` is written by hand, as a pipeline. diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 22869942..70f70086 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -186,7 +186,7 @@ struct: the variant's payload type has to be a single nameable type for the sum machinery. - [`FromVariant`](../traits/from_variant.md) and [`ExtractField`](../traits/extract_field.md) — constructing and taking apart a variant generically. -- [`CanUpcast`](../traits/cast.md) — converting between two enums that share variants. +- [`CanUpcast`](../traits/can_upcast.md) — converting between two enums that share variants. The ideas behind it: diff --git a/docs/reference/traits/append_product.md b/docs/reference/traits/append_product.md new file mode 100644 index 00000000..99fb23d4 --- /dev/null +++ b/docs/reference/traits/append_product.md @@ -0,0 +1,159 @@ +--- +sidebar_label: 'AppendProduct' +--- + +# `AppendProduct` + +Adding one entry to the end of a type-level product list. + +## What it's for + +A struct's shape in CGP is a type-level list — a [`Product!`](../macros/product.md) of named fields. +Code that processes such a shape generically sometimes needs to describe a *new* shape computed from an +old one: the shape a builder will have after one more field is set, say, or the shape a routine promises +to return. + +`AppendProduct` is that computation for a single entry. It takes a product and an item and names +the product with that item added **at the end**: + +```rust +pub trait AppendProduct { + type Output; +} +``` + +There is no method, because there is nothing to execute. The result is an associated type, evaluated by +the trait solver while the compiler type-checks, so it carries no runtime cost and imposes no ordering. + +**This is one of the least user-facing traits in the reference.** You meet it if you write generic code +over shapes, and otherwise only in an error message from code that does. + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::traits`: + +```rust +use cgp::core::field::traits::AppendProduct; +``` + +`Self` is the existing product, `Item` is the entry to add, and `Output` is the result. `Item` may be +unsized. Every existing entry is preserved in order, and the new one lands last. + +Appending onto `Nil` — the empty product — yields a one-element list, which is the recursion's base case +and occasionally useful to know when reading a bound. + +## Examples + +The results are types, so the check is a type equality rather than a value comparison: + +```rust +use cgp::core::field::traits::AppendProduct; +use cgp::prelude::*; + +type Base = Product![Field]; + +type WithPort = >>::Output; +// = Product![Field, Field] +``` + +In generic code the same thing appears as a bound whose projection names the routine's result shape: + +```rust +fn with_extra_field() -> >::Output +where + Fields: AppendProduct, +{ + todo!() +} +``` + +## When to reach for it, and when not + +**Reach for it when a routine must describe the shape it *will* produce** — in a signature, an associated +type, or a `where` clause — and essentially never otherwise. It is a building block the extensible-data +machinery uses; the machinery itself is what application code touches. + +- **Reach for [`ConcatProduct`](./concat_product.md)** to splice a whole list rather than one entry. + Append is its single-entry special case, so if you find yourself appending in a loop, you wanted + concat. +- **Use [`HasFields`](./has_fields.md) instead** if you only need a type's *existing* shape. This trait + computes new shapes; it is not how you obtain one. +- **Use the [builder](./has_builder.md) or [extractor](./extract_field.md) family instead** if you are + moving *values* through a shape. This never touches a value, so if you want something to happen at run + time, it is the wrong layer. + +There is no `AppendSum`. Growing a sum is not an operation this layer provides. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursion. It is four lines, and reading it makes +[`ConcatProduct`](./concat_product.md) obvious for free. + +::: + +The trait is a pair of impls, one for the spine's `Cons` node and one for its `Nil` terminator. Each head +is kept and the tail rebuilt, with a single-element list grafted on at the end: + +```rust +impl AppendProduct for Nil { + type Output = Cons; +} + +impl AppendProduct for Cons +where + Tail: AppendProduct, +{ + type Output = Cons; +} +``` + +Because the recursion only ever rebuilds the spine, order is structurally preserved — which is why +appending yields a *different* type from prepending, and why two products with the same entries in +different orders are unrelated types. + +All of this is resolved during type checking. There is no `fn` anywhere on this page. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::traits`. This is the first thing that goes +wrong when reaching for it. + +**The result is `Output`, while [`MapFields`](./map_fields.md) exposes `Mapped`.** The asymmetry between +the three product operations is easy to forget, and reaching for the wrong name is a plain +unresolved-associated-type error. + +**It is product-only.** There is no sum equivalent. + +**Order is part of the type.** Appending is not commutative with prepending, and nothing reorders a list +to make two shapes match. + +**A long list means a deep recursion.** This is trait resolution over the spine, so a very wide struct +costs compile time proportional to its width — one of the places CGP's compile-time cost actually comes +from. + +## Related constructs + +- [`ConcatProduct`](./concat_product.md) — the general form; append is its single-entry case. +- [`MapFields`](./map_fields.md) — rewriting every entry rather than adding one. +- [`Product!`](../macros/product.md) — the sugar for the lists this operates on. +- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` chain underneath. +- [`HasFields`](./has_fields.md) — where a type's existing shape comes from. +- [`Field`](../types/field.md) — the entries a field list is usually made of. +- [`HasBuilder`](./has_builder.md) — the family that moves values through the shapes this computes. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where computing a new shape is put to work. + +## Source + +- [`append_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/append_product.rs) + — `AppendProduct` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/build_field.md b/docs/reference/traits/build_field.md new file mode 100644 index 00000000..4f5f3f5a --- /dev/null +++ b/docs/reference/traits/build_field.md @@ -0,0 +1,167 @@ +--- +sidebar_label: 'BuildField' +--- + +# `BuildField` + +Setting one currently-absent field of a builder. + +## What it's for + +`BuildField` is the direction of the [builder family](./has_builder.md) you write most: take a partial +record with a field absent, supply the value, and get back a partial record with that field present. + +```rust +pub trait BuildField { + type Value; + type Output; + + fn build_field(self, _tag: PhantomData, value: Self::Value) -> Self::Output; +} +``` + +`Output` is a **different type** from `Self` — the same partial record with one marker flipped — which is +what makes the compiler track completeness. A chain of `build_field` calls walks through as many distinct +types as there are fields, and only the last one satisfies +[`FinalizeBuild`](./finalize_build.md). + +It pins one transition of the [`UpdateField`](./update_field.md) primitive: `IsNothing → IsPresent`. +Because it *requires* the starting marker to be `IsNothing`, **building a field that is already set is a +compile error**, not a silent overwrite. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +The `PhantomData` argument names the field, the same way a [`HasField`](./has_field.md) read does: +`PhantomData::` for a named field, `PhantomData::>` for a tuple-struct +position. `Value` is the field's declared type, so what you pass is an ordinary value with no wrapper. + +**Nothing implements it directly.** It is a library blanket impl over +[`UpdateField`](./update_field.md), so every field the derive generates an `UpdateField` impl for gains +`build_field` for free. + +## Examples + +The everyday chain, one call per field: + +```rust +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +let person = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .build_field(PhantomData::, "Chen".to_owned()) + .finalize_build(); +``` + +**Order does not matter**, because each impl constrains only its own field's marker and leaves the rest +generic. Setting `last_name` first compiles identically. + +Mixing it with a merge is the usual shape once more than one source contributes: + +```rust +use cgp::core::field::impls::CanBuildFrom; + +let employee = Employee::builder() + .build_from(person) // the shared fields + .build_field(PhantomData::, 7) // and the one it did not carry + .finalize_build(); +``` + +## When to reach for it, and when not + +**Call `build_field` in any code that fills a builder; bound on the trait when the code is generic over +the record.** + +- **Bound on [`HasBuilder`](./has_builder.md) + `BuildField` + [`FinalizeBuild`](./finalize_build.md)** + to write a routine that assembles a record it does not name. +- **Use [`CanBuildFrom`](./can_build_from.md)** to copy every shared field from another record at once, + rather than one `build_field` per field. +- **Use [`SetOptional`](./set_optional.md)** when a field must be settable more than once. `build_field` + consumes an absent slot exactly once by design; the optional layer is what relaxes that. +- **Use [`UpdateField`](./update_field.md)** for a transition this does not cover. +- **Prefer a struct literal** in concrete code that knows every field. + +## Under the hood + +:::note + +### Advanced + +This section shows why the trait is not generated. + +::: + +`BuildField` is a **library blanket impl** over [`UpdateField`](./update_field.md), pinning the target +marker to `IsPresent` and constraining the reported source marker to `IsNothing`: + +```rust +// conceptually: +// impl BuildField for Partial +// where Partial: UpdateField +``` + +The `Mapper = IsNothing` constraint is what does the checking. `Mapper` is an *output* of the primitive — +the marker the field was in — so constraining it selects only those partial types whose field is +currently absent. A field already set has `Mapper = IsPresent`, no impl matches, and the call fails to +resolve. + +`update_field` returns the old value alongside the new partial; `build_field` discards it, which is sound +because the old value under `IsNothing` is `()`. + +[`TakeField`](./take_field.md) is the mirror image — the same primitive with `IsNothing` as the target +and `Mapper = IsPresent` — which is why the two read as opposites and share every mechanism. + +## Gotchas + +**Building a field twice does not compile.** The second call finds `Mapper = IsPresent` and no impl. That +is the guarantee, and the error is a missing-method one rather than anything mentioning "already set". + +**`Output` is a different type from `Self`.** A builder cannot be stored in a variable of fixed type +across a chain, and it cannot be filled in a loop — the chain is unrolled by construction. + +**The error for an incomplete build arrives at `finalize_build`**, not here. Forgetting a field is only +detectable at the end, since any prefix of a chain is a legal partial value. + +**It sets, it does not overwrite.** For a settable-and-resettable field, reach for +[`SetOptional`](./set_optional.md). + +**The `PhantomData` argument carries the tag.** At a site where inference cannot determine it, write +`PhantomData::` in full. + +**Nothing implements it directly**, so an unsatisfied `BuildField` bound is really an unsatisfied +[`UpdateField`](./update_field.md) one — which is what the error names. + +## Related constructs + +- [`UpdateField`](./update_field.md) — the primitive this pins one direction of. +- [`TakeField`](./take_field.md) — the opposite direction. +- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — where a partial value comes + from. +- [`FinalizeBuild`](./finalize_build.md) — where a completed one goes. +- [`CanBuildFrom`](./can_build_from.md) — filling many fields from another record in one call. +- [`SetOptional`](./set_optional.md) — the settable-repeatedly counterpart. +- [`MapType`](./map_type.md) — the `IsNothing`/`IsPresent` markers this moves between. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the `UpdateField` impls behind + it. +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that name a field. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder + pattern. + +## Source + +- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs) + — `BuildField` and `FinalizeBuild` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/can_build_from.md b/docs/reference/traits/can_build_from.md new file mode 100644 index 00000000..ca03b67a --- /dev/null +++ b/docs/reference/traits/can_build_from.md @@ -0,0 +1,156 @@ +--- +sidebar_label: 'CanBuildFrom' +--- + +# `CanBuildFrom` + +Filling a builder with every field it shares with another record. + +## What it's for + +Assembling one struct out of several smaller ones means copying each shared field across by hand — a +line per field, repeated for every pair of types. `CanBuildFrom` derives that copying from the field +names instead. + +It is the record counterpart of the [variant casts](./can_upcast.md), and it differs from them in one +way that shapes how it is written: **it is implemented for a builder rather than for the target type**. +Calling it fills a partial value with whatever fields it shares with the source and hands the builder +back, so several sources can be absorbed in sequence before the result is finalized. + +That is the merge step of the extensible builder pattern: independent parts of a program each produce a +record, and the target absorbs all of them without any of them naming it. + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::impls`: + +```rust +use cgp::core::field::impls::CanBuildFrom; +``` + +```rust +pub trait CanBuildFrom { + type Output; + + fn build_from(self, source: Source) -> Self::Output; +} +``` + +`Self` is the builder, which is why the call reads `Target::builder().build_from(source)`. `Output` is +the updated builder — **not** the finished struct, which is what lets a second `build_from` follow. + +**The source needs [`HasFields`](./has_fields.md) as well as a builder**, because the recursion walks the +source's field list to know what to copy. The target needs only its builder. Deriving the same thing on +both looks symmetric and does not compile, which is the mistake this trait causes most often. + +## Examples + +Two independent records merged into a third, which names neither of them: + +```rust +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +#[derive(CgpData)] pub struct FooBar { pub foo: u64, pub bar: String } +#[derive(CgpData)] pub struct Baz { pub baz: bool } +#[derive(CgpData)] pub struct FooBarBaz { pub foo: u64, pub bar: String, pub baz: bool } + +let combined: FooBarBaz = FooBarBaz::builder() + .build_from(FooBar { foo: 1, bar: "bar".to_owned() }) + .build_from(Baz { baz: true }) + .finalize_build(); +``` + +Neither source names the target and the target names neither source. They share field *names*, matched +at the type level, and that is the whole coupling. + +Mixing a merge with an explicit field is the usual shape, since a source rarely covers everything: + +```rust +let employee = Employee::builder() + .build_from(person) // the shared fields + .build_field(PhantomData::, 7) // and the one it did not carry + .finalize_build(); +``` + +## When to reach for it, and when not + +**Reach for it when a record is assembled from independent pieces.** That is the extensible builder +pattern's merge step, and it is what the trait exists for. + +- **Prefer a struct literal** when one place knows every field. A literal is already checked for + completeness, reads better, and generates nothing. +- **Prefer a plain `From` impl** when the two types are yours and the conversion is one you would write + once. This trait earns its keep when the conversion must be *derived* from names rather than written. +- **Reach for [`CanBuildWithDefault`](./can_build_with_default.md)** when the target has fields the source + does not cover and their defaults are acceptable — it chains `builder()`, `build_from`, and a defaulted + finalize into one call. +- **Reach for [`CanUpcast`](./can_upcast.md)** for the enum analogue. + +One boundary worth stating: this is **compile-time, name-driven, and opt-in**. Both types must derive the +machinery, the names must match exactly, and nothing is inspected at run time. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursion, which is the record mirror of the variant casts'. + +::: + +`CanBuildFrom` **recurses over the source's field product.** For each field the source exposes, it uses +[`TakeField`](./take_field.md) to remove that value from the source and [`BuildField`](./build_field.md) +to write it into the target builder, threading both the shrinking source and the growing builder through +the walk. + +When the source's fields run out, the builder is returned — **not finalized**, which is exactly what +lets a second `build_from` follow, and why `Output` is a builder type rather than the target struct. + +One asymmetry in the source is worth knowing if you read it: this recursion, `FieldsBuilder`, is +**private**, while the variant casts' `FieldsExtractor` is public. So the extractor recursion can appear +by name in a diagnostic and be named in a bound; this one cannot. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::impls`. + +**The source needs [`HasFields`](./has_fields.md), not just a builder.** Deriving only +[`BuildField`](../derives/derive_build_field.md) on both structs looks symmetric and fails; the error is +an unsatisfied `HasFields` bound on the source type. + +**It is called on the builder, not the target.** `Target::builder().build_from(source)`, and the result +is a builder you still have to [finalize](./finalize_build.md). + +**Field names are the whole interface.** Renaming a field in one struct silently stops it being copied, +and the failure surfaces at `finalize_build` — a missing-method error — rather than at the rename. + +**A field the target lacks is not an error and not copied.** The walk matches on the target's slots, so +an extra field on the source is simply dropped. + +**It consumes the source.** There is no borrowing form. + +## Related constructs + +- [`HasBuilder`](./has_builder.md) — where a builder comes from, and the family this belongs to. +- [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) — the two primitives the recursion + routes through. +- [`FinalizeBuild`](./finalize_build.md) — how the resulting builder becomes a struct. +- [`HasFields`](./has_fields.md) — the shape the walk reads, and what the source must derive. +- [`CanBuildWithDefault`](./can_build_with_default.md) — merge plus a defaulted finalize, in one call. +- [`CanUpcast`](./can_upcast.md) — the enum counterpart. +- [`#[derive(CgpRecord)]`](../derives/derive_cgp_record.md) — what makes a struct eligible. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — merging records through a builder. + +## Source + +- [`build_from.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/build_from.rs) + — `CanBuildFrom` and its `FieldsBuilder` recursion + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/can_build_with_default.md b/docs/reference/traits/can_build_with_default.md new file mode 100644 index 00000000..1edd987c --- /dev/null +++ b/docs/reference/traits/can_build_with_default.md @@ -0,0 +1,158 @@ +--- +sidebar_label: 'CanBuildWithDefault' +--- + +# `CanBuildWithDefault` + +Widening one record into another in a single call. + +## What it's for + +Turning a narrow record into a wider one whose extra fields have sensible defaults is a three-step motion: +start a builder, copy the shared fields, default the rest. `CanBuildWithDefault` is that motion as one +call: + +```rust +pub trait CanBuildWithDefault { + fn build_with_default(source: Source) -> Self; +} +``` + +`Self` is the target record and `Source` the narrower one. **It is the field-level counterpart of an +[upcast](./can_upcast.md)** — turning a `Point2d` into a `Point3d` whose extra `z` is `0`, naming no field +explicitly. + +It chains [`builder()`](./has_builder.md), [`build_from`](./can_build_from.md), and +[`finalize_with_default`](./can_finalize_with_default.md), and it is worth reaching for precisely because +those three lines together read as plumbing. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::CanBuildWithDefault; +``` + +It is an **associated function**, called on the target: `Point3d::build_with_default(point_2d)`. + +Two requirements come from the steps it chains. **The source needs [`HasFields`](./has_fields.md)**, +because [`build_from`](./can_build_from.md) walks the source's field list — the same requirement any merge +carries. And **every field the source does not supply needs `Default`**, because the finalize fills them. + +## Examples + +Widening a record with no field named anywhere: + +```rust +use cgp::extra::field::impls::CanBuildWithDefault; +use cgp::prelude::*; + +#[derive(Debug, Clone, Eq, PartialEq, CgpData)] +struct Point2d { x: u64, y: u64 } + +#[derive(Debug, Clone, Eq, PartialEq, CgpData)] +struct Point3d { x: u64, y: u64, z: u64 } + +let point_3d = Point3d::build_with_default(Point2d { x: 1, y: 2 }); + +assert_eq!(point_3d, Point3d { x: 1, y: 2, z: 0 }); // z defaulted +``` + +Neither struct knows about the other. They share field *names*, matched at the type level, and `z` is +filled because `u64: Default`. + +Written out, the same thing is three calls: + +```rust +let point_3d: Point3d = Point3d::builder() + .build_from(Point2d { x: 1, y: 2 }) + .finalize_with_default(); +``` + +## When to reach for it, and when not + +**Reach for it for a one-call widening from a narrower record**, and reach for the pieces when anything +in between needs to happen. + +- **[`CanBuildFrom`](./can_build_from.md) plus an explicit finalize** when some fields must be set by + hand as well as copied. This trait offers no place to insert a `build_field`. +- **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when there is no source to merge from. +- **[`CanUpcast`](./can_upcast.md)** for the enum analogue — widening a variant set rather than a field + set. +- **A plain `From` impl** when both types are yours and the conversion is one you would write once. A + hand-written `From` is clearer, requires nothing of either type, and lets you choose values other than + `Default`. + +## Under the hood + +:::note + +### Advanced + +This section shows the composition, which is all there is to it. + +::: + +The impl chains the three steps and constrains each with a bound: + +```rust +// conceptually: +// Self: HasBuilder, +// Self::Builder: CanBuildFrom, +// >::Output: CanFinalizeWithDefault +// +// fn build_with_default(source: Source) -> Self { +// Self::builder().build_from(source).finalize_with_default() +// } +``` + +Each bound is where one of the requirements comes from: [`CanBuildFrom`](./can_build_from.md) brings the +[`HasFields`](./has_fields.md) obligation on the source, and +[`CanFinalizeWithDefault`](./can_finalize_with_default.md) brings the `Default` obligation on the +remaining fields — through a [`TransformMapFields`](./transform_map_fields.md) walk carrying +[`TransformMapDefault`](./transform_map_default.md). + +So an unsatisfied bound here is always really an unsatisfied bound one layer down, which is worth knowing +because the error names that layer rather than this trait. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**The source needs [`HasFields`](./has_fields.md), not just a builder.** Deriving only +[`BuildField`](../derives/derive_build_field.md) on both looks symmetric and fails — the same trap +[`CanBuildFrom`](./can_build_from.md) carries. + +**Every field the source does not supply needs `Default`.** The error names the missing +[`TransformMap`](./transform_map.md) impl rather than the field. + +**It is an associated function on the target.** `Point3d::build_with_default(source)`, not a method on +the source. + +**There is no place to set a field explicitly.** If one field needs a real value, use the three-call form. + +**A field the target lacks is silently dropped**, since the merge matches on the target's slots. + +## Related constructs + +- [`CanBuildFrom`](./can_build_from.md) — the merge step, and where the source's requirements come from. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the defaulting finalize step. +- [`HasBuilder`](./has_builder.md) — the builder it starts from. +- [`TransformMapDefault`](./transform_map_default.md) — the marker behind the defaulting. +- [`CanUpcast`](./can_upcast.md) — the enum analogue of widening. +- [`HasFields`](./has_fields.md) — what the source must derive. +- [`#[derive(CgpRecord)]`](../derives/derive_cgp_record.md) — what makes both records eligible. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — merging records through a builder. + +## Source + +- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs) + — `CanBuildWithDefault`, `CanFinalizeWithDefault`, and `TransformMapDefault` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/can_downcast.md b/docs/reference/traits/can_downcast.md new file mode 100644 index 00000000..10da5b24 --- /dev/null +++ b/docs/reference/traits/can_downcast.md @@ -0,0 +1,155 @@ +--- +sidebar_label: 'CanDowncast' +--- + +# `CanDowncast` + +Narrowing a wide enum into a smaller one, or handing back what is left. + +## What it's for + +Converting a wide enum into a narrower one is the direction that can fail: the value's current variant +may be one the target does not have. `CanDowncast` attempts that conversion, and what makes it more than +a fallible `From` is what it returns on failure. + +**A failed downcast hands back a *remainder* rather than an error.** The remainder is the same value with +the attempted variants ruled out *in its type*, so it can be tried against another target — and each +attempt narrows what remains. That is what lets a value be routed through a chain of candidate targets +with the compiler tracking, at every step, which variants are still possible. + +The narrowing counterpart of [`CanUpcast`](./can_upcast.md), which always succeeds because a wider target +has a home for everything. + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::impls`, with +`core::marker::PhantomData` for naming the target: + +```rust +use cgp::core::field::impls::CanDowncast; +use core::marker::PhantomData; +``` + +```rust +pub trait CanDowncast { + type Remainder; + + fn downcast(self, _tag: PhantomData) -> Result; +} +``` + +`Ok` carries the narrowed value. `Err` carries the source's extractor with the target's variants removed +— which is exactly what [`CanDowncastFields`](./can_downcast_fields.md) is called on to continue the +chain. `Self` is the wide enum, consumed. + +## Examples + +A downcast succeeds for a variant the target shares and fails for one it lacks: + +```rust +use cgp::core::field::impls::CanDowncast; +use cgp::prelude::*; +use core::marker::PhantomData; + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum FooBar { + Foo(u64), + Bar(String), +} + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), +} + +assert_eq!( + FooBarBaz::Bar("hi".to_owned()).downcast(PhantomData::).ok(), + Some(FooBar::Bar("hi".to_owned())), +); + +assert_eq!(FooBarBaz::Baz(true).downcast(PhantomData::).ok(), None); +``` + +`.ok()` is right for a single attempt and wrong when another target should be tried, because it throws +away the remainder that the next attempt needs. + +## When to reach for it, and when not + +**Reach for it when a value must be tried against a target the source may or may not fit**, and reach +for it *with* [`CanDowncastFields`](./can_downcast_fields.md) when there is more than one candidate: the +first starts the chain and the second continues it on each remainder. + +- **Prefer a `match`** for a one-off narrowing of a concrete enum. It is shorter and already exhaustive. + A downcast pays off when the target is a type parameter, or when the chain of candidates is long. +- **Prefer a plain `TryFrom` impl** when both types are yours and the conversion is one you would write + once. Nothing about a hand-written impl needs either type to derive anything. +- **Reach for [`CanUpcast`](./can_upcast.md)** for the widening direction, which cannot fail. +- **Reach for the [extractor family](./extract_field.md)** when you want to handle *every* variant rather + than convert to another enum. A downcast chain and an extraction chain narrow the same way; the + difference is whether each step produces another enum or a payload. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursion, and why the remainder is the shape it is. + +::: + +**The downcasts recurse over the *target's* variants**, which is the mirror image of +[`CanUpcast`](./can_upcast.md#under-the-hood) walking the source's. For each `Field` in +`Target::Fields`, the implementation tries pulling that variant out of the source extractor: on success +it rebuilds the target with [`FromVariant`](./from_variant.md) and returns `Ok`; on failure it threads the +shrunken remainder into the next attempt. If no target variant matches, the terminal `Void` impl returns +the whole remainder as `Err`. + +`CanDowncast` differs from [`CanDowncastFields`](./can_downcast_fields.md) only in where the walk starts: +this one calls [`to_extractor`](./has_extractor.md) on the enum first, while that one operates on an +extractor it is handed. That is the entire reason two traits exist rather than one, and it is what makes +chaining possible — the `Remainder` a `downcast` returns is precisely a `downcast_fields` input. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::impls`. + +**A downcast returns a remainder, not an `Option`.** `.ok()` discards it, which is fine for a single +attempt and wrong if you meant to try another target. + +**A remainder carries none of the enum's attributes**, so a `Result` is neither +`Debug` nor `PartialEq` — comparing one whole does not compile. Reach for `.ok()`, `.is_ok()`, or a +`match`. + +**Names and payload types must match exactly**, and a mismatch is a compile error rather than a runtime +miss: the variant simply drops out of the overlap. + +**The remainder's type is not the source enum.** It is a partial companion with markers, so it cannot be +stored where the original was. + +## Related constructs + +- [`CanDowncastFields`](./can_downcast_fields.md) — the continuation, called on each remainder. +- [`CanUpcast`](./can_upcast.md) — the widening direction, which cannot fail. +- [`CanBuildFrom`](./can_build_from.md) — the record counterpart of casting. +- [`ExtractField`](./extract_field.md) — the primitive each attempt uses, and the family that narrows the + same way to a payload. +- [`HasExtractor`](./has_extractor.md) — where the walk starts. +- [`FromVariant`](./from_variant.md) — how a matched variant is rebuilt into the target. +- [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) — what makes an enum eligible. +- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain underneath. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — upcasting and downcasting between enums. + +## Source + +- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs) — + `CanDowncast` and the `FieldsExtractor` recursion + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/can_downcast_fields.md b/docs/reference/traits/can_downcast_fields.md new file mode 100644 index 00000000..ae7365fa --- /dev/null +++ b/docs/reference/traits/can_downcast_fields.md @@ -0,0 +1,155 @@ +--- +sidebar_label: 'CanDowncastFields' +--- + +# `CanDowncastFields` + +Continuing a narrowing chain on a remainder. + +## What it's for + +[`CanDowncast`](./can_downcast.md) narrows an enum and, when it fails, hands back a *remainder* — the +same value with the attempted variants ruled out in its type. `CanDowncastFields` is what that remainder +is then passed to, so a value can be tried against a second target, a third, and so on. + +The two traits do the same narrowing and differ in one thing: **where the walk starts**. `CanDowncast` +is called on an enum and converts it to an extractor first; `CanDowncastFields` is called on an extractor +it is already given. Since a remainder *is* an extractor, that is exactly the shape a chain needs. + +**So the pair is the construct, and this half is never used alone.** A chain reads as one `downcast` +followed by one `downcast_fields` per additional candidate. + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::impls`, alongside `CanDowncast`, which +you will always be using with it: + +```rust +use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; +use core::marker::PhantomData; +``` + +```rust +pub trait CanDowncastFields { + type Remainder; + + fn downcast_fields(self, _tag: PhantomData) -> Result; +} +``` + +The signature is `CanDowncast`'s exactly. `Self` here is a remainder rather than an enum, and the +`Remainder` it returns is narrower again — so each call in a chain has a different, progressively +smaller `Self` type. + +## Examples + +Trying a value against two candidate targets in turn: + +```rust +use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; +use cgp::prelude::*; +use core::marker::PhantomData; + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), +} + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum JustFoo { + Foo(u64), +} + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum JustBar { + Bar(String), +} + +let value = FooBarBaz::Bar("hi".to_owned()); + +match value.downcast(PhantomData::) { + Ok(foo) => { /* it was a Foo */ } + Err(remainder) => { + // `remainder` can no longer be a Foo + let bar = remainder.downcast_fields(PhantomData::); + assert!(bar.is_ok()); + } +} +``` + +The first call starts the chain and the second continues it. Written the other way round — a second +`downcast` on the remainder — it does not compile, because a remainder is not an enum. + +## When to reach for it, and when not + +**Reach for it only as the continuation of a [`CanDowncast`](./can_downcast.md) chain.** It has no other +use: its `Self` is a remainder, and a remainder only ever comes from a prior downcast. + +- **Use one `downcast` and then one `downcast_fields` per further candidate.** That is the whole + pattern. +- **Prefer the [extractor family](./extract_field.md)** when what you want is the *payload* of whichever + variant is present rather than another enum. It narrows identically and ends with a checked, + wildcard-free discharge through [`FinalizeExtract`](./finalize_extract.md). +- **Prefer a `match`** when the enum is concrete and the candidates are few. A cast chain earns its keep + when the targets are type parameters or the chain is long. + +## Under the hood + +:::note + +### Advanced + +This section is one paragraph, because the recursion is +[`CanDowncast`](./can_downcast.md#under-the-hood)'s. + +::: + +Both traits walk the *target's* variant list, trying to pull each one out of the extractor they hold and +threading the shrunken remainder into the next attempt, with the terminal `Void` impl returning the whole +remainder as `Err`. The only difference is the entry point: `CanDowncast` calls +[`to_extractor`](./has_extractor.md) on an enum to obtain the extractor, and this trait takes one it is +handed. + +Because the remainder type narrows at every step, a chain's types are all distinct, and the compiler +knows at each point exactly which variants remain — the same narrowing a hand-written +[extraction chain](./extract_field.md) performs. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::impls`. + +**It cannot be called on an enum.** `Self` is an extractor. Start with +[`CanDowncast`](./can_downcast.md). + +**`.ok()` on an intermediate step ends the chain.** Discarding the remainder discards the input the next +attempt needs. + +**A remainder carries none of the enum's attributes**, so a `Result` holding one is neither `Debug` nor +`PartialEq`. + +**Each step has a different `Self` type**, so a chain cannot be written as a loop or collected into a +`Vec` of attempts — it is unrolled by construction. + +## Related constructs + +- [`CanDowncast`](./can_downcast.md) — the first step, and where the pair is explained in full. +- [`CanUpcast`](./can_upcast.md) — the widening direction. +- [`ExtractField`](./extract_field.md) — narrowing to a payload rather than to another enum. +- [`FinalizeExtract`](./finalize_extract.md) — how an exhausted remainder is discharged. +- [`HasExtractor`](./has_extractor.md) — what turns an enum into the extractor this operates on. +- [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) — what makes an enum eligible. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — partial variants and the narrowing chain. + +## Source + +- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs) — + `CanDowncastFields` and the `FieldsExtractor` recursion + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/can_finalize_with_default.md b/docs/reference/traits/can_finalize_with_default.md new file mode 100644 index 00000000..e3f488f9 --- /dev/null +++ b/docs/reference/traits/can_finalize_with_default.md @@ -0,0 +1,173 @@ +--- +sidebar_label: 'CanFinalizeWithDefault' +--- + +# `CanFinalizeWithDefault` + +Finalizing a partial record, filling whatever is unset from `Default`. + +## What it's for + +The core [builder family](./has_builder.md) refuses to finalize an incomplete record, which is what +catches a missing field at compile time. For a record where some fields have sensible defaults, that +strictness is the wrong shape. `CanFinalizeWithDefault` relaxes it: + +```rust +pub trait CanFinalizeWithDefault { + type Output; + + fn finalize_with_default(self) -> Self::Output; +} +``` + +Every field that is not set becomes `Default::default()`, and the result is the concrete struct. + +**The strict presence check still runs — it just always passes**, because the fields are re-marked to +`IsPresent` first. That is the layer's whole design in one sentence, and it is why the core +[`FinalizeBuild`](./finalize_build.md) remains the only route from a partial value to a struct. + +It is one of two endings for a partial builder, and the choice is made at the call site: + +| | a field left unset | +|---|---| +| `CanFinalizeWithDefault` | filled from `Default` | +| [`FinalizeOptional`](./finalize_optional.md) | `Err("field_name")` | + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::CanFinalizeWithDefault; +``` + +`Output` is the concrete struct. It applies to any partial value whose fields can be transformed to +all-present, which covers a core builder from [`builder()`](./has_builder.md) as well as an optional one +from [`optional_builder()`](./has_optional_builder.md). + +**Every unset field's type needs `Default`.** A field whose type has none makes the transform +unresolvable, and the error names the missing +[`TransformMap`](./transform_map.md) impl rather than the field. + +## Examples + +Filling a gap rather than reporting it: + +```rust +use cgp::extra::field::impls::{CanFinalizeWithDefault, HasOptionalBuilder, SetOptional}; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +let context = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + +assert_eq!(context.foo, "foo"); +assert_eq!(context.bar, 0); // defaulted +``` + +Had that used [`finalize_optional`](./finalize_optional.md), it would have returned `Err("bar")` instead +— which is the point of deferring the choice to the finalize call rather than to the builder. + +The one-call form that also copies from a source is +[`CanBuildWithDefault`](./can_build_with_default.md). + +## When to reach for it, and when not + +**Reach for it when unset fields have meaningful defaults and silence is the right outcome.** + +- **[`FinalizeOptional`](./finalize_optional.md)** when absence is an error worth reporting. The two are + the same builder finalized differently. +- **[`FinalizeBuild`](./finalize_build.md)** — the core builder — when every field is genuinely + required. A missing field is then a compile error, which is strictly stronger. +- **[`CanBuildWithDefault`](./can_build_with_default.md)** when the set fields come from another record + rather than from individual calls. It chains the merge and this finalize into one call. +- **A hand-written builder** when the defaults are computed rather than `Default::default()`, or when + finalizing should validate. This layer models presence and defaulting, and nothing else. + +## Under the hood + +:::note + +### Advanced + +This section shows the two-line body, which is the clearest statement of how the layer works. + +::: + +The whole impl is a transform followed by the ordinary finalize: + +```rust +impl CanFinalizeWithDefault for Builder +where + Builder: TransformMapFields, + Builder::Output: FinalizeBuild, +{ + type Output = Output; + + fn finalize_with_default(self) -> Output { + self.transform_map_fields().finalize_build() + } +} +``` + +Read the bounds together: the first says every field can be re-marked to `IsPresent` by +[`TransformMapDefault`](./transform_map_default.md), and the second says the result is then finalizable. + +Its mirror image is [`ToOptional`](./to_optional.md), which runs the same +[`TransformMapFields`](./transform_map_fields.md) walk with +[`TransformOptional`](./transform_optional.md) toward `IsOptional`. **Both capabilities are the same +recursion with a different marker**, which is why the defaulted and optional workflows behave so +symmetrically. + +Because the transform targets `IsPresent`, the value handed to `finalize_build` is at exactly the +configuration its single impl requires — so the strict check runs, and cannot fail. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**Every field's type needs `Default`.** A field whose type has none makes the transform unresolvable, and +the error names the missing [`TransformMap`](./transform_map.md) impl rather than the field — which is +the most confusing failure in this layer. + +**A defaulted field is silent.** Nothing distinguishes "set to zero" from "left unset" in the result, which +is the trade against [`FinalizeOptional`](./finalize_optional.md). + +**It gives up the compile-time completeness check** that the core builder provides. + +**It applies to a core builder too**, not only an optional one — an absent `IsNothing` field is +transformed as readily as a `None`. + +**It consumes the builder.** + +## Related constructs + +- [`FinalizeOptional`](./finalize_optional.md) — the other ending, reporting rather than filling. +- [`CanBuildWithDefault`](./can_build_with_default.md) — merge and default in one call. +- [`TransformMapDefault`](./transform_map_default.md) — the marker this drives. +- [`TransformMapFields`](./transform_map_fields.md) — the walk it runs. +- [`FinalizeBuild`](./finalize_build.md) — the strict impl it ultimately calls. +- [`HasOptionalBuilder`](./has_optional_builder.md) and [`ToOptional`](./to_optional.md) — the optional + entry points. +- [`HasBuilder`](./has_builder.md) — the core family this relaxes. +- [`MapType`](./map_type.md) — the markers the transform moves between. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence + fits. + +## Source + +- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs) + — `CanFinalizeWithDefault`, `CanBuildWithDefault`, and `TransformMapDefault` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/can_upcast.md b/docs/reference/traits/can_upcast.md new file mode 100644 index 00000000..b28c5570 --- /dev/null +++ b/docs/reference/traits/can_upcast.md @@ -0,0 +1,160 @@ +--- +sidebar_label: 'CanUpcast' +--- + +# `CanUpcast` + +Widening a narrow enum into a wider one that shares its variants. + +## What it's for + +Two enums defined independently can share variant names — a small `FooBar` and a larger `FooBarBaz`, +say. Converting the narrow one into the wide one is a conversion you could write by hand, and it is +pure boilerplate: one `match` arm per variant, rewrapping each payload under the same name. + +`CanUpcast` derives that conversion from the names instead. Once both enums expose their shape as a +type-level list — which [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) makes them — widening is a +matter of routing each source variant to the target's slot of the same name. + +**It always succeeds.** Every variant of the source has a home in the target, or the conversion does not +type-check at all, so `upcast` returns the target directly rather than a `Result`. That totality is the +difference between this trait and its narrowing counterpart, +[`CanDowncast`](./can_downcast.md). + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::impls`, and bring +`core::marker::PhantomData` into scope too, since the target is named with a `PhantomData` argument +rather than a turbofish on the method: + +```rust +use cgp::core::field::impls::CanUpcast; +use core::marker::PhantomData; +``` + +The trait itself is one method: + +```rust +pub trait CanUpcast { + fn upcast(self, _tag: PhantomData) -> Target; +} +``` + +`Self` is the narrow enum, consumed; `Target` is the wider one. Both must derive the extensible-data +machinery, and the target's variant set must include every one of the source's — matched by name and by +payload type. + +## Examples + +Two independently-defined enums that share variant names interconvert with no manual impl: + +```rust +use cgp::core::field::impls::CanUpcast; +use cgp::prelude::*; +use core::marker::PhantomData; + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum FooBar { + Foo(u64), + Bar(String), +} + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), +} + +let wide = FooBar::Foo(1).upcast(PhantomData::); + +assert_eq!(wide, FooBarBaz::Foo(1)); +``` + +Neither enum names the other. They share variant *names*, matched at the type level, and that is the +whole coupling. + +## When to reach for it, and when not + +**Reach for it when an implementation works in a small local enum and its result must be widened.** That +is the common use, and it is the construction-side counterpart of reading one field through a getter: +name only the variants you need, and let the widening be checked. + +- **Prefer a plain `From` impl** when both types are yours, the conversion is one you would write once, + and nothing about it needs to be generic. A hand-written `From` is clearer, requires nothing of either + type, and generates nothing. +- **Reach for [`CanDowncast`](./can_downcast.md)** for the other direction, which can fail and therefore + reads quite differently. +- **Reach for [`CanBuildFrom`](./can_build_from.md)** for the record analogue — merging a struct's fields + into another struct's builder. + +One boundary worth stating: this is **compile-time, name-driven, and opt-in**. Both enums must derive +the shape, the names must match exactly, and nothing is inspected at run time. An enum from a crate that +has not derived the machinery cannot participate at all. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursion. You do not need it to call `upcast`, but it explains why the widening +is total where a narrowing is not. + +::: + +`CanUpcast` **recurses over the source's variants**. It converts the source to its extractor with +[`HasExtractor`](./has_extractor.md), then walks the source's own field list, pulling each variant out +with [`ExtractField`](./extract_field.md) and rebuilding it into the target with +[`FromVariant`](./from_variant.md). + +Because every source variant is guaranteed to exist in a wider target, the walk is total — and the +extractor left at the end is uninhabited, discharged with [`FinalizeExtract`](./finalize_extract.md). +That is precisely why `upcast` returns the target directly instead of a `Result`. + +One detail from the source is worth knowing if you read it: the recursion driving this, +`FieldsExtractor`, is **public**, so it can appear by name in a diagnostic and be named in a bound. Its +record-side analogue `FieldsBuilder`, behind [`CanBuildFrom`](./can_build_from.md), is private. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::impls`. This is the first thing that goes +wrong. + +**An upcast is total only if the target really is wider.** If the target lacks one of the source's +variants there is no impl, and the failure is an unsatisfied bound rather than a runtime error — which is +the guarantee, but it reads as a puzzling missing-impl message until you check the variant lists. + +**Names must match exactly.** Renaming a variant in one enum silently removes it from the overlap, and +the failure surfaces wherever the cast is written rather than at the rename. + +**The payload types must match too.** A `Foo(u64)` does not upcast into a `Foo(u32)`; the tag and the +value type are both part of the entry. + +**It consumes the source.** There is no borrowing form. + +## Related constructs + +- [`CanDowncast`](./can_downcast.md) — the narrowing direction, which can fail. +- [`CanDowncastFields`](./can_downcast_fields.md) — narrowing continued on a remainder. +- [`CanBuildFrom`](./can_build_from.md) — the record counterpart. +- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) and + [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) — what makes an enum eligible. +- [`ExtractField`](./extract_field.md) and [`FromVariant`](./from_variant.md) — the two primitives the + recursion routes through. +- [`HasFields`](./has_fields.md) — the variant shape being walked. +- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain underneath. +- [Dispatch combinators](../providers/dispatch_combinators.md) — where casting meets per-variant routing. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — upcasting and downcasting between enums. + +## Source + +- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs) — + `CanUpcast` and the `FieldsExtractor` recursion + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/cast.md b/docs/reference/traits/cast.md deleted file mode 100644 index 7d0acf54..00000000 --- a/docs/reference/traits/cast.md +++ /dev/null @@ -1,252 +0,0 @@ ---- -sidebar_label: 'CanUpcast, CanDowncast & CanBuildFrom' ---- - -# `CanUpcast`, `CanDowncast` & `CanBuildFrom` - -Structural casts between records and between variants. - -## What it's for - -Two types that share a subset of named fields or variants can be converted into one another with no -hand-written `From` or `TryFrom` impl. Once a type's shape is a type-level list — which -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) makes it — conversion becomes a matter of routing each -named entry to the matching slot in the target, and the routing is derived from the names. - -Four traits cover the directions that routing can take. - -**`CanUpcast`** widens an enum: a value of a narrow enum whose variants are a subset of a wider one's is lifted -into the wider one. It **always succeeds**, because every source variant has a home in the target. - -**`CanDowncast`** narrows: it tries to convert a wide enum into a smaller one, succeeding only if the value's -current variant exists in the target, and otherwise handing back a *remainder* so the caller can try another -target. - -**`CanDowncastFields`** is that same narrowing one level down, called on a remainder rather than on an enum — so -several candidate targets can be tried in sequence. - -**`CanBuildFrom`** is the record counterpart: it fills a target's builder with whatever fields it shares with a -source, leaving the rest of the target to be supplied separately. - -## Using it - -**None of the four is in the prelude.** Import them from `cgp::core::field::impls`: - -```rust -use cgp::core::field::impls::{CanBuildFrom, CanDowncast, CanDowncastFields, CanUpcast}; -``` - -You will also want `core::marker::PhantomData` in scope, since every one of them names its target with a -`PhantomData` argument rather than a turbofish on the method. - -### The variant casts - -```rust -pub trait CanUpcast { - fn upcast(self, _tag: PhantomData) -> Target; -} - -pub trait CanDowncast { - type Remainder; - fn downcast(self, _tag: PhantomData) -> Result; -} - -pub trait CanDowncastFields { - type Remainder; - fn downcast_fields(self, _tag: PhantomData) -> Result; -} -``` - -`upcast` returns the target directly because it cannot fail. `downcast` returns a `Result` whose error is the -source's extractor with the attempted variants removed — which is what `downcast_fields` is then called on. The -difference between the two downcasts is only the starting point: `downcast` converts the enum to an extractor -first, while `downcast_fields` takes one it is already given. - -### The record cast - -```rust -pub trait CanBuildFrom { - type Output; - fn build_from(self, source: Source) -> Self::Output; -} -``` - -It is implemented for a **builder**, not for the target type, which is why it is written -`Target::builder().build_from(source)`. The result is the updated builder, so several sources can be absorbed in -sequence before finalizing. - -**The source of a `build_from` needs [`HasFields`](./has_fields.md)** as well as a builder, because the recursion -walks the source's field list to know what to copy. The target needs only its builder. - -## Examples - -Two independently-defined enums that share variant names interconvert with no manual impl: - -```rust -use cgp::core::field::impls::{CanDowncast, CanUpcast}; -use cgp::prelude::*; -use core::marker::PhantomData; - -#[derive(Debug, Eq, PartialEq, CgpData)] -pub enum FooBar { - Foo(u64), - Bar(String), -} - -#[derive(Debug, Eq, PartialEq, CgpData)] -pub enum FooBarBaz { - Foo(u64), - Bar(String), - Baz(bool), -} - -// upcast always succeeds: every FooBar variant exists in FooBarBaz -let wide = FooBar::Foo(1).upcast(PhantomData::); -assert_eq!(wide, FooBarBaz::Foo(1)); - -// downcast succeeds for a shared variant -assert_eq!( - FooBarBaz::Bar("hi".to_owned()).downcast(PhantomData::).ok(), - Some(FooBar::Bar("hi".to_owned())), -); - -// and fails for one the target lacks -assert_eq!(FooBarBaz::Baz(true).downcast(PhantomData::).ok(), None); -``` - -`CanBuildFrom` assembles one struct from several smaller ones: - -```rust -use cgp::core::field::impls::CanBuildFrom; - -#[derive(CgpData)] pub struct FooBar { pub foo: u64, pub bar: String } -#[derive(CgpData)] pub struct Baz { pub baz: bool } -#[derive(CgpData)] pub struct FooBarBaz { pub foo: u64, pub bar: String, pub baz: bool } - -let combined: FooBarBaz = FooBarBaz::builder() - .build_from(FooBar { foo: 1, bar: "bar".to_owned() }) - .build_from(Baz { baz: true }) - .finalize_build(); -``` - -Neither source names the target and the target names neither source. They share field *names*, matched at the -type level, and that is the whole coupling. - -## When to reach for it, and when not - -**Reach for a cast when two shapes genuinely overlap and you would otherwise write the conversion by hand.** -That is the case these exist for, and it is narrower than "I have two similar types". - -- **`upcast`** when an implementation works in a small local enum and the result must be widened. This is the - common use, and it is the construction-side counterpart of reading one field through a getter: name only what - you need, and let the widening be checked. -- **`downcast` then `downcast_fields`** when a value must be tried against several candidate targets in turn. - Reach for the pair together — the first starts the chain and the second continues it on each remainder. -- **`build_from`** when a record is assembled from independent pieces. This is the extensible builder pattern's - merge step. -- **Prefer a plain `From` impl** when the two types are yours, the conversion is one you would write once, and - nothing about it needs to be generic. A hand-written `From` is clearer, has no requirements on either type, and - generates nothing — these casts earn their keep when the conversion must be *derived* from names rather than - written. -- **Prefer a `match`** for a one-off narrowing of a concrete enum. `downcast` pays off when the target is a type - parameter or when the chain of candidates is long. - -One boundary worth stating: these are **compile-time, name-driven, and opt-in**. Both types must derive the -shape, the names must match exactly, and nothing is inspected at run time. A type from a crate that has not -derived the machinery cannot participate at all. - -## Under the hood - -:::note - -### Advanced - -This section shows the three recursions. You do not need it to call a cast, but it explains why a downcast hands -back a remainder rather than an `Option`, and why the two downcast traits both exist. - -::: - -All three are driven by a recursion over a [`HasFields`](./has_fields.md) shape, and *which* shape is what -distinguishes them. - -**`CanUpcast` recurses over the source's variants.** It converts the source to its extractor, then walks the -source's own field list, pulling each variant out with [`ExtractField`](./extract_field.md) and rebuilding it into -the target with [`FromVariant`](./from_variant.md). Because every source variant is guaranteed to exist in a wider -target, the walk is total — and the extractor left at the end is uninhabited, discharged with -[`FinalizeExtract`](./extract_field.md). That totality is why `upcast` returns the target directly instead of a -`Result`. - -**The downcasts recurse over the *target's* variants instead.** For each `Field` in -`Target::Fields`, the implementation tries pulling that variant out of the source extractor: on success it rebuilds -the target and returns `Ok`; on failure it threads the shrunken remainder into the next attempt. If no target -variant matches, the terminal `Void` impl returns the whole remainder as `Err`. - -That threading is the reason for two traits rather than one. `CanDowncast` starts by calling `to_extractor` on the -enum, while `CanDowncastFields` operates on an extractor it is handed — which is exactly the `Remainder` a prior -`downcast` returned. So chaining candidates is `downcast` followed by `downcast_fields` on each remainder, and the -remainder type narrows at every step just as it does in a hand-written -[extraction chain](./extract_field.md). - -**`CanBuildFrom` recurses over the source's field product.** For each field the source exposes, it uses -[`TakeField`](./has_builder.md) to remove that value from the source and [`BuildField`](./has_builder.md) to write -it into the target builder, threading both the shrinking source and the growing builder through. When the source's -fields run out, the builder is returned — not finalized, which is what lets a second `build_from` follow. - -One asymmetry in the source is worth knowing if you read it: the extractor recursion, `FieldsExtractor`, is -public, while the builder recursion `FieldsBuilder` is private. So the former can appear by name in a diagnostic -and be named in a bound; the latter cannot. - -## Gotchas - -**None of the four is in the prelude.** Import from `cgp::core::field::impls`. This is the first thing that goes -wrong. - -**`build_from` needs [`HasFields`](./has_fields.md) on the source, not just a builder.** Deriving only -`BuildField` on both looks symmetric and does not compile; the error is an unsatisfied `HasFields` bound on the -source type. - -**`build_from` is called on the builder, not the target.** `Target::builder().build_from(source)`, and the result -is a builder you still have to finalize. - -**A downcast returns a remainder, not an `Option`.** `.ok()` discards it, which is fine for a single attempt and -wrong if you meant to try another target — that remainder is the input to `downcast_fields`. - -**Names must match exactly, and a mismatch is a compile error rather than a runtime miss.** Renaming a variant or -field in one type silently removes it from the overlap, and the failure surfaces as an unsatisfied bound -wherever the cast is written. - -**A remainder carries none of the enum's attributes**, so a `Result` is neither `Debug` nor -`PartialEq` — comparing one whole does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. - -**An upcast is total only if the target really is wider.** If the target lacks one of the source's variants there -is no impl, and the error is an unsatisfied bound rather than a runtime failure — which is the guarantee, but it -reads as a puzzling missing-impl message until you check the variant lists. - -## Related constructs - -- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — generates the shapes and machinery all four consume. -- [`HasFields`](./has_fields.md) — the shape each recursion walks, and what a `build_from` source needs. -- [`ExtractField`](./extract_field.md) and [`FromVariant`](./from_variant.md) — the primitives the variant casts - route through. -- [`HasBuilder`](./has_builder.md) — the `TakeField`/`BuildField` pair the record cast routes through. -- [Optional fields](./optional_fields.md) — `CanBuildWithDefault`, which chains `build_from` into a defaulted - finalize. -- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` and `Cons`/`Nil` chains being walked. -- [`Symbol!`](../macros/symbol.md) — the tags the matching is done on. -- [Dispatch combinators](../providers/dispatch_combinators.md) — where casting meets per-variant routing. - -The ideas behind it: - -- [Extensible variants](/docs/concepts/extensible-variants) — upcasting and downcasting between enums. -- [Extensible records](/docs/concepts/extensible-records) — merging records through a builder. - -## Source - -- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs) — - `CanUpcast`, `CanDowncast`, `CanDowncastFields`, and the `FieldsExtractor` recursion -- [`build_from.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/build_from.rs) - — `CanBuildFrom` and its `FieldsBuilder` recursion - ---- - -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/concat_path.md b/docs/reference/traits/concat_path.md new file mode 100644 index 00000000..73cef5cf --- /dev/null +++ b/docs/reference/traits/concat_path.md @@ -0,0 +1,144 @@ +--- +sidebar_label: 'ConcatPath' +--- + +# `ConcatPath` + +Joining two type-level paths. + +## What it's for + +A [`Path!`](../macros/path.md) is a type-level list of segments — the route a namespaced component +lookup is redirected along, or the chain of field names a nested getter descends. Composing two such +routes means splicing one list onto the end of another, and `ConcatPath` is that operation: + +```rust +pub trait ConcatPath { + type Output: ?Sized; +} +``` + +There is no method and no value. It is a pure type-level computation resolved during trait resolution, +so it names the combined path type and nothing runs. + +It is the path-level analogue of [`ConcatProduct`](./concat_product.md), with the same two-impl +recursion over a different spine. + +## Using it + +**`ConcatPath` is in the prelude** — `use cgp::prelude::*;` names it, which makes it the one member of +the type-level recovery group that needs no import. Its two neighbours each need a different one: +[`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and +[`StaticFormat`](./static_format.md) — defined in the same crate as this trait — from +`cgp::core::base::traits`. + +`Self` is the first path and `Other` the second, and the result is the first's segments followed by the +second's. **Both sides may be unsized**, since path types are markers rather than types anything is +instantiated at. + +## Examples + +Two paths composed at the type level, which is the operation behind chaining nested accessors: + +```rust +use cgp::prelude::*; + +type Outer = Path!(@a.b); +type Inner = Path!(@c.d); + +type Joined = >::Output; // the path @a.b.c.d +``` + +Note the leading `@` — [`Path!`](../macros/path.md) requires it, and `Path!(a.b)` does not parse. + +In generic code the projection usually appears in a bound rather than a type alias, naming the route a +composed getter will take: + +```rust +fn descend() -> >::Output +where + Outer: ConcatPath, +{ + todo!() +} +``` + +## When to reach for it, and when not + +**Reach for it when composing paths in generic code**, which is nested-accessor territory. If you are +writing a path literally, [`Path!`](../macros/path.md) already gives you the whole thing and there is +nothing to concatenate. + +- **Use [`ChainGetters`](../providers/chain_getters.md)** rather than composing paths by hand when the + goal is reaching a field on a nested context. That provider is the construct this operation serves. +- **Use [`ConcatProduct`](./concat_product.md)** for field lists rather than paths. The two recursions + are the same shape over different spines and are not interchangeable. +- **Use [`StaticString`](./static_string.md)** if what you want is the segments as *text*. This produces + a type; decoding it means decoding each segment's symbol. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursion, which is [`ConcatProduct`](./concat_product.md#under-the-hood)'s over +the path spine. + +::: + +Two impls, one per spine node. Each node keeps its head segment and concatenates onto the tail; the +terminator becomes the other path outright: + +```rust +// at the terminator, the whole second path is substituted +// at a node, the head is kept and the tail recurses +``` + +So the result is the first path's segments followed by the second's, in order, with the cost of +resolution proportional to the first path's length. + +It never touches a value; it only names the combined path type, which a getter or a +[`RedirectLookup`](../providers/redirect_lookup.md) then uses to descend. + +## Gotchas + +**[`Path!`](../macros/path.md) requires a leading `@`.** `Path!(a.b)` does not parse; `Path!(@a.b)` does. +This is the most common way an otherwise-correct `ConcatPath` example fails to build. + +**It produces a type, not a joined string.** This is path composition for trait resolution. If you want +the segments as text, decode the symbols with [`StaticString`](./static_string.md). + +**Both sides may be unsized**, which is why the trait carries `?Sized` on the parameter and the output — +a detail worth noticing if you write a bound over it and get an unexpected `Sized` error. + +**It is in the prelude while [`StaticString`](./static_string.md) is not.** The asymmetry between two +neighbouring traits catches people importing one and assuming the other came with it. + +**Order is part of the type.** `@a.b` then `@c.d` is a different path from the reverse, and nothing +normalizes them. + +## Related constructs + +- [`Path!`](../macros/path.md) — the sugar for the paths this joins. +- [`PathCons`](../types/type_level_spines.md) — the spine underneath. +- [`ConcatProduct`](./concat_product.md) — the product-level analogue. +- [`StaticString`](./static_string.md) — recovering a segment's name as text. +- [`StaticFormat`](./static_format.md) — the lazy formatting counterpart. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the provider that follows a path. +- [`ChainGetters`](../providers/chain_getters.md) — nested accessors, the setting path composition + serves. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — where paths key a namespace's entries. + +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — reusable wiring tables and the paths that route into them. + +## Source + +- [`concat_path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/concat_path.rs) + — `ConcatPath` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/concat_product.md b/docs/reference/traits/concat_product.md new file mode 100644 index 00000000..138e23fe --- /dev/null +++ b/docs/reference/traits/concat_product.md @@ -0,0 +1,152 @@ +--- +sidebar_label: 'ConcatProduct' +--- + +# `ConcatProduct` + +Splicing one type-level product list onto the end of another. + +## What it's for + +Merging two records means merging their shapes, and the shapes are type-level lists — a +[`Product!`](../macros/product.md) of named fields each. `ConcatProduct` names the list you get by +following one product with another: + +```rust +pub trait ConcatProduct { + type Output; +} +``` + +There is no method, because there is nothing to execute. The result is an associated type evaluated by +the trait solver during type checking, so it costs nothing at run time. + +It is the general form of [`AppendProduct`](./append_product.md): **append is the single-entry special +case of concat**, and that is the shortest way to hold both in mind. + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::traits`: + +```rust +use cgp::core::field::traits::ConcatProduct; +``` + +`Self` is the first product, `Items` is the second, and `Output` is the first's entries followed by the +second's. Order is preserved on both sides. + +Two identities are worth knowing, because they let a generic bound resolve in the degenerate cases: +concatenating onto `Nil` yields the other list unchanged, and concatenating `Nil` onto a list leaves it +unchanged. + +## Examples + +The results are types, so the check is a type equality: + +```rust +use cgp::core::field::traits::{AppendProduct, ConcatProduct}; +use cgp::prelude::*; + +type Base = Product![Field]; + +type WithPort = >>::Output; + +type Extra = Product![Field]; + +type Full = >::Output; +// = Product![host, port, tls] +``` + +Which is the type-level counterpart of what [`CanBuildFrom`](./can_build_from.md) does with values: this +names the combined shape, that moves the fields into it. + +## When to reach for it, and when not + +**Reach for it when generic code must name the shape produced by combining two others** — a merge, a +routine that extends a record with a caller-supplied set of fields — and essentially never otherwise. + +- **Reach for [`AppendProduct`](./append_product.md)** for a single entry. It is the same recursion with + a one-element graft, and it reads better for the one-field case. +- **Use [`HasFields`](./has_fields.md) instead** if you only need a type's *existing* shape. +- **Use [`CanBuildFrom`](./can_build_from.md) instead** if you want the *values* merged rather than the + shapes named. This trait never touches a value. +- **Note that [`ConcatPath`](./concat_path.md) is the path-level analogue**, doing the same job for the + segment lists behind [`Path!`](../macros/path.md), with the same two-impl recursion. + +There is no `ConcatSum`. Combining two sums is not an operation this layer provides. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursion, which is [`AppendProduct`](./append_product.md#under-the-hood)'s with +one line changed. + +::: + +Two impls, one per spine node. Each head is kept and the tail rebuilt; at the terminator, the whole +second list is substituted: + +```rust +impl ConcatProduct for Nil { + type Output = Items; // the only difference from AppendProduct +} + +impl ConcatProduct for Cons +where + Tail: ConcatProduct, +{ + type Output = Cons; +} +``` + +Set `Items = Cons` and this is `AppendProduct` exactly, which is the precise sense in which +append is a special case. + +The recursion walks the *first* list only, so its cost is proportional to the left operand's length +rather than to the result's. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::traits`. + +**The result is `Output`, while [`MapFields`](./map_fields.md) exposes `Mapped`.** The asymmetry between +the three product operations is easy to forget. + +**It is product-only.** For paths, the analogue is [`ConcatPath`](./concat_path.md); for sums, there is +nothing. + +**Duplicate entries are not detected.** Concatenating two products that share a field name yields a list +with the name twice, which is a legal type and will fail later, at whatever consumes it, rather than +here. + +**Order is part of the type.** `A` then `B` is a different type from `B` then `A`, and nothing normalizes +them. + +**A long list means a deep recursion**, so concatenating two wide shapes costs compile time proportional +to the first one's width. + +## Related constructs + +- [`AppendProduct`](./append_product.md) — the single-entry case. +- [`MapFields`](./map_fields.md) — rewriting every entry rather than adding any. +- [`ConcatPath`](./concat_path.md) — the same operation over type-level paths. +- [`Product!`](../macros/product.md) — the sugar for the lists this operates on. +- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` chain underneath. +- [`CanBuildFrom`](./can_build_from.md) — merging the values whose shapes this combines. +- [`HasFields`](./has_fields.md) — where a type's existing shape comes from. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where computing a new shape is put to work. + +## Source + +- [`concat_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/concat_product.rs) + — `ConcatProduct` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/contains_value.md new file mode 100644 index 00000000..f09dc38c --- /dev/null +++ b/docs/reference/traits/contains_value.md @@ -0,0 +1,147 @@ +--- +sidebar_label: 'ContainsValue' +--- + +# `ContainsValue` + +Naming the value a monad threads forward out of a step's output. + +## What it's for + +A step in a [monadic pipeline](/docs/concepts/monadic-handlers) produces a wrapped output — a `Result`, +say — and the next step needs the value *inside* the wrapper for the branch that continues. Which half of +the wrapper that is depends on the monad, so it cannot be hard-coded. + +`ContainsValue` is where each monad answers it: + +```rust +pub trait ContainsValue { + type Value; +} +``` + +`Self` is the monad marker, `Output` is the full output type a step produces, and `Value` is what is +carried in the branch this monad threads forward. A continuation consumes that value, or a deeper monad +layer unwraps it further. + +It is one of four traits that give a monad marker its meaning, and it pairs with +[`LiftValue`](./lift_value.md): this one says how to get *out* of the output type, that one how to get +back *in*. The other two, [`MonadicBind`](./monadic_bind.md) and +[`MonadicTrans`](./monadic_trans.md), fold the pipeline rather than run a step of it. + +**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is +never wired. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::monad::traits`: + +```rust +use cgp::extra::monad::traits::ContainsValue; +``` + +You import it only when **defining a monad of your own**. There is no method — the trait is a type-level +projection from an output type to the value beneath the wrapper. + +## Examples + +What each marker's impl says is what decides how a pipeline behaves. + +**`IdentMonadic` is the identity**: `ContainsValue::Value` is `T`. Nothing is wrapped, so nothing is +unwrapped, and every value threads forward. + +**`ErrMonadic` and `OkMonadic` are mirror images over a `Result`**, and the mirroring is the whole design: + +| Monad | `ContainsValue>::Value` | continue branch | +|---|---|---| +| `ErrMonadic` | `T` | the `Ok` payload threads forward | +| `OkMonadic` | `E` | the `Err` payload threads forward | + +So under `ErrMonadic` a step's continuation receives the `Ok` payload — the ordinary `?` behaviour — and +under `OkMonadic` it receives the `Err` payload, which is the inverted, run-until-something-succeeds +behaviour. + +**The transformer forms peel one layer.** `OkMonadicTrans` and `ErrMonadicTrans` remove their own +`Result` layer and hand the rest to `M`, requiring `M: ContainsValue>`. A two-layer +stack therefore unwraps two `Result` layers in order, and an *n*-layer stack unwraps *n*, with no code +specific to any depth. + +## When to reach for it, and when not + +**Reach for the [monad providers](../providers/monad_providers.md), not this trait.** A pipeline is built +by wiring [`PipeMonadic`](../providers/monad_providers.md) with a marker and a handler list; this is what +the bind providers bound on internally. + +The one real reason to name it is **defining a new monad** — short-circuiting over an `Option`, or over a +custom two-branch enum. Implement it alongside [`LiftValue`](./lift_value.md), since the two are the pair +that runs a step and neither is useful without the other, and copy the mirror-image +`OkMonadic`/`ErrMonadic` pair as the model. + +If you do not need short-circuiting at all, the +[handler combinators](../providers/handler_combinators.md) chain steps without a branch and involve none +of this. + +## Under the hood + +:::note + +### Advanced + +This section shows where a bind step uses it. + +::: + +The [`BindOk` and `BindErr`](../providers/monad_providers.md) providers use `ContainsValue` in their +[`Computer`](../components/computer.md) and `AsyncComputer` impls. Running one bind step means: take the +step's output, ask the monad what value sits beneath its wrapper, and hand that to the continuation. This +trait is the second half of that sentence. + +[`LiftValue`](./lift_value.md) is then what puts a result back into the output type — `lift_value` for the +branch that short-circuits, `lift_output` for the branch that forwarded to the continuation. So the two +traits bracket one step: unwrap, run, re-wrap. + +Because the transformer forms implement it by delegating to the base monad, the unwrapping composes +without any depth-specific code. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::monad::traits`. + +**It is not a component and cannot be wired.** What gets wired is the provider that consumes it. + +**`OkMonadic`'s `Value` is the error half.** Under `OkMonadic`, `ContainsValue>::Value` is +`E`, not `T`. This is the single most confusing consequence of the naming, and it is deliberate: +`OkMonadic` is the monad that *stops* on `Ok`. + +**A stack must be written in layer order.** `OkMonadicTrans` and `ErrMonadicTrans` +unwrap their `Result` layers in opposite orders and are not interchangeable. + +**A new monad needs all four traits.** Implementing this one without [`LiftValue`](./lift_value.md) +yields a marker that can say what a value is and cannot put one back, so a pipeline fails to resolve at +the first step rather than at the definition. + +## Related constructs + +- [`LiftValue`](./lift_value.md) — the other half of running a step: getting back into the output type. +- [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md) — the two traits that fold + the pipeline rather than run a step. +- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the + markers; what you actually wire. +- [`Computer`](../components/computer.md) — the component family the bind providers implement. +- [`TryComputer`](../components/try_computer.md) and [`Handler`](../components/handler.md) — the fallible + members a single step usually is. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads + compose. + +## Source + +- [`value.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/value.rs) + — `ContainsValue` +- Per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/default_impls1.md b/docs/reference/traits/default_impls1.md new file mode 100644 index 00000000..67413a31 --- /dev/null +++ b/docs/reference/traits/default_impls1.md @@ -0,0 +1,224 @@ +--- +sidebar_label: 'DefaultImpls1' +--- + +# `DefaultImpls1` + +Resolving a namespace default keyed on a component *and* a type. + +## What it's for + +[`DefaultNamespace`](./default_namespace.md) keys a default on the component alone: one component, one +default provider. `DefaultImpls1` adds a second type to the key, which is what a **per-type default** +needs — the same component resolving differently for `String` than for `u64`: + +```rust +pub trait DefaultImpls1 { + type Delegate; +} +``` + +There is no method and no data. Resolving a default *is* projecting `Delegate` from the matching impl, +exactly as with [`DelegateComponent`](./delegate_component.md). + +Three traits exist rather than one variadic trait because each fixes the key's arity at the type level, +which is what lets the projection `>` resolve cleanly. +[`DefaultImpls2`](./default_impls2.md) is the two-type form. + +:::warning + +**The parameter names are misleading about which position holds what.** For this trait and its sibling, +**`Self` is the instance type and the component name is a leading parameter** — the opposite of +[`DefaultNamespace`](./default_namespace.md). The [next section](#the-one-thing-to-get-right) works it +out. + +::: + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::component`, and you will need to, because the +generated impl references the trait by name: + +```rust +use cgp::core::component::DefaultImpls1; +``` + +**You name it in two places**: the target of a `for … in` loop inside +[`delegate_components!`](../macros/delegate_components.md), and the +[`#[default_impl(...)]`](../attributes/default_impl.md) attribute that registers a provider as a default. +The macros generate the impls and the forwarding. + +### The one thing to get right + +Registering `ShowString` as the `String` default for `ShowImplComponent` emits: + +```rust +impl DefaultImpls1 for String { + type Delegate = ShowString; +} +``` + +`Self` is `String`; the trait's `T` parameter is filled by `ShowImplComponent`. + +The rule that governs this comes from the attribute rather than the trait, and once you have it the +positions stop being surprising. **`#[default_impl(Key in NamespacePath)]` makes `Key` the impl's +`Self`** and appends the table parameter to whatever `NamespacePath` names — so the leading arguments are +simply whatever you wrote inside the path. The same rule is why the `for … in` loop's bound reads +`T: DefaultImpls1`, with the loop variable in the `Self` position. + +## Examples + +The whole chain, from a provider declaring itself a default to a context pulling it in and overriding one +entry: + +```rust +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; +use core::fmt::Display; + +#[cgp_component(ShowImpl)] +#[prefix(@test in DefaultNamespace)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} +``` + +Then the context: + +```rust +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + @test.ShowImplComponent.u64: ShowWithDisplay, // overrides the inherited default + } +} +``` + +**Environmental context, parameter-targeted** — `App` carries the wiring and the shown value is a +parameter. The loop wires every type with a registered default by projecting +`T: DefaultImpls1`, and the direct `u64` line shadows +whatever the namespace would otherwise supply for that one type. + +A whole namespace can also be the loop target: + +```rust +cgp_namespace! { + new DefaultShowComponents { + [String, u64]: ShowWithDisplay, + } +} +``` + +Pointing `for in DefaultShowComponents { … }` at this wires the listed types through the +same projection. + +## When to reach for it, and when not + +**Use it for a per-type default, and reach for the simpler trait when the key is a component alone.** + +- **[`DefaultNamespace`](./default_namespace.md)** when one component has one default. That is the common + case, and it is what [`#[prefix(...)]`](../macros/cgp_namespace.md) registers into. +- **`DefaultImpls1`** when the same component resolves differently per type. This is what + [`#[default_impl]`](../attributes/default_impl.md) is usually pointed at. +- **[`DefaultImpls2`](./default_impls2.md)** for a two-type key. +- **Define your own namespace trait** when you want a named table of your own; + [`#[default_impl]`](../attributes/default_impl.md) accepts any path, so these three are conveniences + rather than the only options. + +**One constraint decides where a `#[default_impl]` may be written, and it is Rust's orphan rule rather +than anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, so a crate may register a +default when it owns either the namespace trait or the key type. For an unprefixed component the key is +the component's own marker, so a downstream crate owning the component can register into a foreign +namespace. For a [`#[prefix]`](../macros/cgp_namespace.md)-ed component the key is a path built from +`cgp`-owned types plus the marker, so the impl is orphan-legal **only in the namespace's own crate**. +Wiring that must live downstream goes in the namespace body of the crate that owns it instead. + +## Under the hood + +:::note + +### Advanced + +This section shows what the `for … in` loop generates. + +::: + +A `for in DefaultImpls1 { … }` loop emits a +[`DelegateComponent`](./delegate_component.md) impl whose `where` clause projects the default: + +```rust +where T: DefaultImpls1 +``` + +Read it as: for each type `T` that has a default, wire that key to the projected `Provider`. + +**Because the loop variables appear only in that bound and in the key, the key must mention `T`** — +otherwise the parameter is unconstrained and the compiler rejects the impl with `E0207`, which reads as a +puzzling error about a generic parameter rather than about the loop. + +The registration side is the mirror. [`#[default_impl]`](../attributes/default_impl.md) emits an impl of +this trait for the key type, carrying **only** the parameters naming the key and provider plus the table +— never the provider's own `where` clause. A provider whose bounds come from `#[use_type]`, `#[uses]`, +`#[implicit]`, or `#[use_provider]` therefore registers cleanly, because those bounds stay on the +provider's impl and its [`IsProviderFor`](./is_provider_for.md), and are checked when a real context +resolves it. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::component`. +[`DefaultNamespace`](./default_namespace.md) is. + +**`Self` is the instance type, not the component.** The parameter names suggest otherwise. Read +`#[default_impl(Key in Path)]` as "`Key` becomes `Self`" and the positions follow. + +**A `for … in` loop's key must mention the loop variable**, or the impl is rejected with `E0207`. + +**`#[default_impl]` on a prefixed component is confined to the namespace's crate**, by the orphan rule. +Put downstream wiring in the namespace body instead. + +**A default is a fallback, not an assignment.** A direct entry silently shadows it. + +**The registration impl carries none of the provider's bounds**, which is deliberate — they are checked +where the provider is used rather than where it is registered. + +## Related constructs + +- [`DefaultNamespace`](./default_namespace.md) — the one-key form, and the common case. +- [`DefaultImpls2`](./default_impls2.md) — the two-type form. +- [`#[default_impl(...)]`](../attributes/default_impl.md) — the attribute that emits impls of this trait. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. +- [`delegate_components!`](../macros/delegate_components.md) — carries the `for … in` loop. +- [`DelegateComponent`](./delegate_component.md) — what the loop ultimately writes. +- [`IsProviderFor`](./is_provider_for.md) — where a registered provider's real bounds are checked. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value. + +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style + configuration. + +## Source + +- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) + — the three lookup traits +- The `#[default_impl]` attribute: [`attributes/default_impl/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/default_impl) +- Header and loop codegen: [`delegate_component/statement/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/statement) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/default_impls2.md b/docs/reference/traits/default_impls2.md new file mode 100644 index 00000000..2874a954 --- /dev/null +++ b/docs/reference/traits/default_impls2.md @@ -0,0 +1,178 @@ +--- +sidebar_label: 'DefaultImpls2' +--- + +# `DefaultImpls2` + +Resolving a namespace default keyed on a component and *two* types. + +## What it's for + +[`DefaultImpls1`](./default_impls1.md) keys a namespace default on a component plus one type, which is +what a per-type default needs. `DefaultImpls2` is the same idea under a **pair** of types: + +```rust +pub trait DefaultImpls2 { + type Delegate; +} +``` + +There is no method and no data — resolving a default is projecting `Delegate` from the matching impl. + +Three traits exist rather than one variadic trait because each fixes the key's arity at the type level, +which is what lets the projection resolve cleanly. This is the widest of the three. + +:::warning + +**Nothing inside CGP emits or consumes it.** It is reachable and tested, and it is a provided extension +point rather than a construct the generated code relies on — so there is no library-generated example to +pattern-match against. The [next section](#using-it) shows what a use looks like. + +::: + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::component`: + +```rust +use cgp::core::component::DefaultImpls2; +``` + +The positional rule is [`DefaultImpls1`](./default_impls1.md#the-one-thing-to-get-right)'s, extended by +one: **`Self` is the key type and the leading parameters are whatever you wrote inside the namespace +path.** So `#[default_impl(Key in DefaultImpls2)]` emits + +```rust +impl DefaultImpls2 for Key { + type Delegate = /* the provider */; +} +``` + +Registration is [`#[default_impl(...)]`](../attributes/default_impl.md), which accepts an arbitrary +namespace path and therefore needed no new construct to support this trait. Consumption is a `for … in` +loop inside [`delegate_components!`](../macros/delegate_components.md), whose bound projects `Delegate` +the same way the one-type form does. + +## Examples + +A two-type key registered and then consumed: + +```rust +use cgp::core::component::DefaultImpls2; +use cgp::prelude::*; + +#[cgp_impl(new ConvertStringToU64)] +#[default_impl(String in DefaultImpls2)] +impl Converter { + fn convert(&self, value: &String) -> u64 { + value.parse().unwrap_or_default() + } +} +``` + +and a context pulling every registered pair in: + +```rust +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls2 { + @test.ConverterComponent.T: Provider, + } + } +} +``` + +**Environmental context, parameter-targeted.** The loop variable must still appear in the key, exactly as +for the one-type form. + +## When to reach for it, and when not + +**Reach for it when a default genuinely depends on two types**, and prefer the narrower forms otherwise — +each extra key position is one more thing a reader has to hold. + +- **[`DefaultNamespace`](./default_namespace.md)** when the key is the component alone. The common case. +- **[`DefaultImpls1`](./default_impls1.md)** when one further type decides the default. This is what + `#[default_impl]` is usually pointed at. +- **`DefaultImpls2`** when two do — a conversion keyed on source *and* target, say. +- **Define your own namespace trait** when the shape does not fit. + [`#[default_impl]`](../attributes/default_impl.md) accepts any path, so a trait of your own with + whatever arity you need works identically. Given that nothing in the library uses this one, a + purpose-named trait is often the clearer choice. + +The orphan-rule constraint on where a registration may be *written* is the same as for the one-type form, +and is worked out on [its page](./default_impls1.md#when-to-reach-for-it-and-when-not). + +## Under the hood + +:::note + +### Advanced + +This section is short, because the mechanism is +[`DefaultImpls1`](./default_impls1.md#under-the-hood)'s with one more parameter. + +::: + +A `for … in` loop emits a [`DelegateComponent`](./delegate_component.md) impl whose `where` clause +projects the default: + +```rust +where T: DefaultImpls2 +``` + +The loop variables appear only in that bound and in the key, so **the key must mention them** — otherwise +the parameter is unconstrained and the compiler rejects the impl with `E0207`. + +The registration impl carries only the parameters naming the key and provider plus the table, never the +provider's own `where` clause, so a provider with impl-side dependencies registers cleanly and its bounds +are checked when a real context resolves it. + +Because nothing in the library emits this trait, there is no generated code to compare against — the +impls you see are the ones you or the attribute wrote. + +## Gotchas + +**Nothing inside CGP uses it.** There is no generated code to pattern-match against, and no worked +library example. + +**It is not in the prelude.** Import from `cgp::core::component`. + +**`Self` is the key type, not the component.** The parameter names `T1` and `T2` suggest otherwise. Read +`#[default_impl(Key in Path)]` as "`Key` becomes `Self`". + +**A `for … in` loop's key must mention the loop variables**, or the impl is rejected with `E0207`. + +**A default is a fallback, not an assignment.** A direct entry silently shadows it. + +**Two keys are usually one key too many.** If the second type is fixed for a whole application, a +[`DefaultImpls1`](./default_impls1.md) default plus a wiring entry is easier to read. + +## Related constructs + +- [`DefaultImpls1`](./default_impls1.md) — the one-type form, and where the family's mechanics are + worked out. +- [`DefaultNamespace`](./default_namespace.md) — the component-only form. +- [`#[default_impl(...)]`](../attributes/default_impl.md) — the attribute that emits impls of this trait. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace. +- [`delegate_components!`](../macros/delegate_components.md) — carries the `for … in` loop. +- [`DelegateComponent`](./delegate_component.md) — what the loop ultimately writes. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value. + +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style + configuration. + +## Source + +- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) + — the three lookup traits +- The `#[default_impl]` attribute: [`attributes/default_impl/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/default_impl) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md index bb18de66..fbee1dce 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/default_namespace.md @@ -1,122 +1,62 @@ --- -sidebar_label: 'DefaultNamespace & DefaultImpls' +sidebar_label: 'DefaultNamespace' --- -# `DefaultNamespace` & `DefaultImpls` +# `DefaultNamespace` -The namespace default-resolution traits, and `#[default_impl(...)]`. +Resolving a namespace's default provider for a component. ## What it's for -A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the type -the capability runs against — can opt into and then selectively override. Resolving one of those defaults means -asking: *for this key, what does the namespace delegate to?* +A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the +type the capability runs against — can opt into and then selectively override. Resolving one of those +defaults means asking: *for this component, what does the namespace delegate to?* -These three traits are what answer that question. They are plain key-to-value lookups, one `Delegate` associated -type each, differing only in how many types take part in the key: +`DefaultNamespace` is what answers that: ```rust pub trait DefaultNamespace { type Delegate; } - -pub trait DefaultImpls1 { - type Delegate; -} - -pub trait DefaultImpls2 { - type Delegate; -} ``` -`DefaultNamespace` keys a default on the component alone. `DefaultImpls1` adds one further type — the shape for a -*per-type* default, where the same component resolves differently for `String` than for `u64`. `DefaultImpls2` -does the same under a pair. +`Self` is the component being looked up, `Components` is the table the lookup runs against — threaded +through so one key can resolve differently per context — and `Delegate` is the resolved provider. There +is no method and no data; resolving a default *is* projecting `Delegate` from the matching impl, exactly +as with [`DelegateComponent`](./delegate_component.md). -Three traits rather than one variadic trait because each fixes the key's arity at the type level, which is what -lets the projection `>` resolve cleanly. +It is the simplest of three lookup traits, keyed on the component alone. +[`DefaultImpls1`](./default_impls1.md) adds one further type for a *per-type* default, and +[`DefaultImpls2`](./default_impls2.md) does the same under a pair. -**You name these only in two places**: the namespace header of a wiring block, and the target of a -`for … in` loop. The macros generate the impls and the forwarding — so this page is mostly about reading what -they generate, and about one detail that is genuinely easy to get backwards. +**You name it in one place**: the `namespace` header of a wiring block. The macros generate the impls and +the forwarding, so this page is mostly about reading what they generate. ## Using it -`DefaultNamespace` is in the prelude. **`DefaultImpls1` and `DefaultImpls2` are not** — import them from -`cgp::core::component`, and you will need to, because the generated impl references the trait by name. - -```rust -use cgp::core::component::DefaultImpls1; -``` - -`Self` is the key being looked up, `Components` is the table the lookup runs against — threaded through so one key -can resolve differently per context — and `Delegate` is the resolved value. There is no method and no data; -resolving a default *is* projecting `Delegate` from the matching impl, exactly as with -[`DelegateComponent`](./delegate_component.md). - -### The one thing to get right - -**The parameter names `T`, `T1`, and `T2` are misleading about which position holds what.** For -`DefaultNamespace` the `Self` key is the component name, as you would expect. For the two `DefaultImpls` -variants it is the other way round: **`Self` is the instance type, and the component name is a leading -parameter.** Registering `ShowString` as the `String` default for `ShowImplComponent` emits: +**It is in the prelude**, so `use cgp::prelude::*;` is enough — unlike its two siblings, which are not. -```rust -impl DefaultImpls1 for String { - type Delegate = ShowString; -} -``` - -`Self` is `String`; the trait's `T` parameter is filled by `ShowImplComponent`. - -The rule that actually governs this comes from the attribute rather than the trait, and once you have it the -positions stop being surprising. `#[default_impl(Key in NamespacePath)]` makes **`Key` the impl's `Self`** and -appends the table parameter to whatever `NamespacePath` names — so the leading arguments are simply whatever you -wrote inside the path. The same rule is why the `for … in` loop's bound reads -`T: DefaultImpls1`, with the loop variable in the `Self` position. - -### Registering a default - -`#[default_impl(...)]` on a [`#[cgp_impl]`](../macros/cgp_impl.md) provider registers it as a default: - -```rust -#[cgp_impl(new ShowString)] -#[default_impl(String in DefaultImpls1)] -impl ShowImpl { /* … */ } -``` - -The registration impl carries only the parameters naming the key and provider, plus the table — **never the -provider's own `where` clause**. A provider whose bounds come from `#[use_type]`, `#[uses]`, `#[implicit]`, or -`#[use_provider]` registers cleanly, because those bounds stay on the provider's impl and its -[`IsProviderFor`](./is_provider_for.md) and are checked when a real context resolves it. - -### Consuming defaults - -A context joins a namespace with a header and pulls per-type defaults with a loop: +A context joins a namespace with a header inside +[`delegate_components!`](../macros/delegate_components.md): ```rust delegate_components! { App { namespace DefaultNamespace; - - for in DefaultImpls1 { - @test.ShowImplComponent.T: Provider, - } } } ``` -The header forwards `App`'s unwired lookups through the namespace; the loop wires each `T` that has a default. The -loop variable must appear in the key, or it is unconstrained and the impl is rejected. +after which every lookup `App` does not wire directly forwards through the namespace. A component +registers into one with the [`#[prefix(...)]`](../macros/cgp_namespace.md) attribute on its +`#[cgp_component]` trait. ## Examples -The whole chain, from a provider declaring itself a default to a context pulling it in and overriding one entry: +A component registered into the namespace, and a context joining it: ```rust -use cgp::core::component::DefaultImpls1; use cgp::prelude::*; -use core::fmt::Display; #[cgp_component(ShowImpl)] #[prefix(@test in DefaultNamespace)] @@ -124,77 +64,36 @@ pub trait Show { fn show(&self, value: &T) -> String; } -#[cgp_impl(new ShowString)] -#[default_impl(String in DefaultImpls1)] -impl ShowImpl { - fn show(&self, value: &String) -> String { - value.clone() - } -} -``` - -Then the context: - -```rust pub struct App; delegate_components! { App { namespace DefaultNamespace; - for in DefaultImpls1 { - @test.ShowImplComponent.T: Provider, - } - @test.ShowImplComponent.u64: ShowWithDisplay, // overrides the inherited default } } ``` -The loop wires every type with a registered default by projecting -`T: DefaultImpls1`, and the direct `u64` line shadows whatever the -namespace would otherwise supply for that one type — the inheritance-with-override shape presets rely on. - -A whole namespace can also be the loop target: - -```rust -cgp_namespace! { - new DefaultShowComponents { - [String, u64]: ShowWithDisplay, - } -} -``` - -Pointing `for in DefaultShowComponents { … }` at this wires the listed types through the same -projection. +**Environmental context, self-targeted.** The header forwards `App`'s unwired lookups through the +namespace, and the direct entry shadows whatever the namespace would otherwise supply for that one key — +the inheritance-with-override shape presets rely on. ## When to reach for it, and when not -**Write [`cgp_namespace!`](../macros/cgp_namespace.md) and the wiring statements; name these traits only where the -syntax requires it.** They appear in a `namespace` header, in a `for … in` target, and in a `#[default_impl]` -attribute — and nowhere else in ordinary code. - -- **Use `DefaultNamespace`** for a namespace whose defaults are per component, which is the common case and what - [`#[prefix(...)]`](../macros/cgp_namespace.md) registers into. -- **Use `DefaultImpls1`** for a per-type default, where one component resolves differently per type. This is what - `#[default_impl]` is usually pointed at. -- **Use `DefaultImpls2`** for a two-type key. It works, and it is the one member of the family that nothing in the - library itself emits or consumes — a provided extension point rather than a construct the generated code relies - on. +**Write [`cgp_namespace!`](../macros/cgp_namespace.md) and the wiring statements; name this trait only +where the syntax requires it.** It appears in a `namespace` header and nowhere else in ordinary code. + +- **Use `DefaultNamespace`** for a namespace whose defaults are per component, which is the common case + and what [`#[prefix(...)]`](../macros/cgp_namespace.md) registers into. +- **Use [`DefaultImpls1`](./default_impls1.md)** for a per-type default, where one component resolves + differently per type. - **Define your own namespace trait instead** when you want a named table of your own; - [`cgp_namespace!`](../macros/cgp_namespace.md) generates one, and `#[default_impl]` accepts any path, so these - three are conveniences rather than the only options. -- **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. A namespace - buys reuse and inheritance at the cost of one more indirection to follow when reading, and a short - [`delegate_components!`](../macros/delegate_components.md) block needs neither. - -One constraint decides where a `#[default_impl]` may be *written*, and it is Rust's orphan rule rather than -anything CGP chose. The emitted impl is `impl Namespace<..> for Key`, so a crate may register a default when it -owns either the namespace trait or the key type. For an unprefixed component the key is the component's own -marker, so a downstream crate owning the component can register into a foreign namespace. For a -[`#[prefix]`](../macros/cgp_namespace.md)-ed component the key is a path built from `cgp`-owned types plus the -marker, so the impl is orphan-legal **only in the namespace's own crate**. Wiring that must live downstream goes -in the namespace body of the crate that owns it instead. + [`cgp_namespace!`](../macros/cgp_namespace.md) generates one, so this is a convenience rather than the + only option. +- **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. A + namespace buys reuse and inheritance at the cost of one more indirection to follow when reading, and a + short [`delegate_components!`](../macros/delegate_components.md) block needs neither. ## Under the hood @@ -202,13 +101,13 @@ in the namespace body of the crate that owns it instead. ### Advanced -This section shows what the header and the loop generate. You do not need it to use a namespace, but it explains -how a direct entry can shadow an inherited default without conflicting with it. +This section shows what a `namespace` header generates, and why an override does not conflict with it. ::: A `namespace N;` header does not emit one entry — it emits a **blanket** -[`DelegateComponent`](./delegate_component.md) impl on the context that forwards every key through the namespace: +[`DelegateComponent`](./delegate_component.md) impl on the context that forwards every key through the +namespace: ```rust impl DelegateComponent for App @@ -219,72 +118,61 @@ where } ``` -paired with the matching [`IsProviderFor`](./is_provider_for.md) forwarding so dependencies stay diagnosable. +paired with the matching [`IsProviderFor`](./is_provider_for.md) forwarding so dependencies stay +diagnosable. -**That blanket is what makes override work.** A directly-wired entry is a *concrete* impl for one key, and a -concrete impl is more specific than the blanket, so it resolves first — shadowing the inherited default for that -key and leaving the rest untouched. Two *concrete* entries for one key would conflict; a concrete entry against a -blanket does not. +**That blanket is what makes override work.** A directly-wired entry is a *concrete* impl for one key, +and a concrete impl is more specific than the blanket, so it resolves first — shadowing the inherited +default for that key and leaving the rest untouched. Two *concrete* entries for one key would conflict; a +concrete entry against a blanket does not. -A `for in DefaultImpls1 { … }` loop emits a `DelegateComponent` impl whose `where` -clause projects the default: - -```rust -where T: DefaultImpls1 -``` - -Read it as: for each type `T` that has a default, wire that key to the projected `Provider`. Because the loop -variables appear only in that bound and in the key, the key must mention `T` — otherwise the parameter is -unconstrained and the compiler rejects the impl. - -Inheritance composes on top. A namespace declared `new Child: Parent { … }` emits a blanket impl forwarding any -key the parent resolves, so the child resolves everything the parent does plus its own entries — and a context's -direct entry still shadows either. All of it is projections, resolved at compile time, with nothing at run time. +Inheritance composes on top. A namespace declared `new Child: Parent { … }` emits a blanket impl +forwarding any key the parent resolves, so the child resolves everything the parent does plus its own +entries — and a context's direct entry still shadows either. All of it is projections, resolved at +compile time, with nothing at run time. ## Gotchas -**`DefaultImpls1` and `DefaultImpls2` are not in the prelude.** Import from `cgp::core::component`. -`DefaultNamespace` is. - -**`Self` is the instance type for the `DefaultImpls` variants, not the component.** The parameter names suggest -otherwise. Read `#[default_impl(Key in Path)]` as "`Key` becomes `Self`" and the positions follow. +**A namespace default is a fallback, not an assignment.** It resolves only for keys the context does not +wire directly, which is the intent, and it means a stray direct entry can silently shadow a default you +expected to apply. -**A `for … in` loop's key must mention the loop variable.** Otherwise the parameter is unconstrained and the -impl is rejected with `E0207` — which reads as a puzzling error about a generic parameter rather than about the -loop. +**`Self` is the component here**, as you would expect — but **not** in +[`DefaultImpls1`](./default_impls1.md) and [`DefaultImpls2`](./default_impls2.md), where the instance +type takes the `Self` position instead. The inconsistency is the family's sharpest edge. -**`#[default_impl]` on a prefixed component is confined to the namespace's crate.** The orphan rule decides this, -so a downstream default for a prefixed component is not something to work around — put the wiring in the -namespace body instead. +**It is in the prelude while its two siblings are not.** They come from `cgp::core::component`. -**A namespace default is a fallback, not an assignment.** It resolves only for keys the context does not wire -directly, which is the intent, and it means a stray direct entry can silently shadow a default you expected to -apply. +**There is no method.** Resolving a default is a type projection. -**`DefaultImpls2` has no user inside CGP.** It is reachable and tested, but nothing in the library emits or -consumes it — so there is no generated code to pattern-match against when using it. +**Registering into a foreign namespace is bound by the orphan rule** — see +[`DefaultImpls1`](./default_impls1.md#when-to-reach-for-it-and-when-not), where the +[`#[default_impl]`](../attributes/default_impl.md) attribute's placement constraint is worked out. ## Related constructs +- [`DefaultImpls1`](./default_impls1.md) and [`DefaultImpls2`](./default_impls2.md) — the per-type and + per-pair variants. +- [`#[default_impl(...)]`](../attributes/default_impl.md) — the attribute that registers a provider as a + default. - [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. -- [`delegate_components!`](../macros/delegate_components.md) — carries the `namespace` header and the `for … in` - loop that consume these traits. +- [`delegate_components!`](../macros/delegate_components.md) — carries the `namespace` header. - [`DelegateComponent`](./delegate_component.md) — what a namespace header forwards *into*. - [`IsProviderFor`](./is_provider_for.md) — forwarded alongside, so dependency errors stay readable. -- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value, re-routing along a path. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value, re-routing along a + path. - [`Path!`](../macros/path.md) — the paths a prefixed key is built from. -- [`#[cgp_impl]`](../macros/cgp_impl.md) — the host of the `#[default_impl]` attribute. The ideas behind it: -- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style configuration. +- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style + configuration. ## Source -- The three traits: [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) -- The namespace macro: [`types/namespace/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/namespace) -- The `#[default_impl]` attribute: [`attributes/default_impl/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/default_impl) -- The header and loop codegen: [`delegate_component/statement/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/statement) +- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) + — the three lookup traits +- Header and loop codegen: [`delegate_component/statement/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/statement) --- diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md index 0a83db3e..75004148 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/extract_field.md @@ -4,113 +4,57 @@ sidebar_label: 'ExtractField' # `ExtractField` -The incremental-extractor trait family behind the extensible visitor pattern. +Pulling one variant out of an extractor, or narrowing what remains. ## What it's for -A `match` on a concrete enum is checked for exhaustiveness. Code that is generic over the enum cannot write -one, so it falls back on a wildcard arm and an `unreachable!()` — losing exactly the guarantee you wanted. +A `match` on a concrete enum is checked for exhaustiveness. Code that is generic over the enum cannot +write one, so it falls back on a wildcard arm and an `unreachable!()` — losing exactly the guarantee you +wanted. -This family recovers it. An enum is taken apart one variant at a time, and **the still-possible variants are -tracked in the type**. Each attempt either yields the payload or hands back a *remainder* whose type has that -variant ruled out: - -```rust -match shape.to_extractor().extract_field(PhantomData::) { - Ok(circle) => /* it was a Circle */, - Err(remainder) => /* it wasn't; `remainder` can no longer be a Circle */, -} -``` - -Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** — a -value of it cannot exist — and that is what closes the chain with no wildcard and no panic path. Add a variant -to the enum and the final remainder becomes inhabited again, so the code stops compiling until it is handled. - -The family is the mirror of the [builder](./has_builder.md): a builder tracks which fields are *present*, an -extractor tracks which variants are still *possible*. The impls come from -[`#[derive(ExtractField)]`](../derives/derive_extract_field.md), which generates the partial companion enums -they operate on. - -## Using it - -Most of the family is in the prelude — `HasExtractor`, `HasExtractorRef`, `HasExtractorMut`, `ExtractField`, -`FinalizeExtract`. The exception is **`FinalizeExtractResult`, which is not**; import it from -`cgp::core::field::traits`, and you will want it, because it is what closes a chain. - -### The three accessors - -They differ only in ownership, and picking the right one is most of using the family: - -```rust -pub trait HasExtractor { - type Extractor; - fn to_extractor(self) -> Self::Extractor; - fn from_extractor(extractor: Self::Extractor) -> Self; -} - -pub trait HasExtractorRef { - type ExtractorRef<'a> where Self: 'a; - fn extractor_ref(&self) -> Self::ExtractorRef<'_>; -} - -pub trait HasExtractorMut { - type ExtractorMut<'a> where Self: 'a; - fn extractor_mut(&mut self) -> Self::ExtractorMut<'_>; -} -``` - -`to_extractor` **consumes** the value and yields owned payloads; `from_extractor` reverses it for a value that -was not matched. `extractor_ref` borrows, so payloads come out as shared references and the original survives. -`extractor_mut` borrows mutably, so a payload can be changed in place. - -### The extraction +`ExtractField` is the operation that recovers it. Each attempt either yields the payload or hands back a +*remainder* whose type has that variant ruled out: ```rust pub trait ExtractField { type Value; type Remainder; + fn extract_field(self, _tag: PhantomData) -> Result; } ``` -`Ok` carries the payload; `Err` carries the same extractor with this one variant ruled out. The impl exists -only while the requested variant is still possible, so attempting the same variant twice is a compile error -rather than a guaranteed miss. +`Ok` carries the payload; `Err` carries the same extractor with this one variant ruled out. **The impl +exists only while the requested variant is still possible**, so attempting the same variant twice is a +compile error rather than a guaranteed miss. -### The finish +Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** — +a value of it cannot exist — and [`FinalizeExtract`](./finalize_extract.md) is what closes the chain with +no wildcard and no panic path. Add a variant to the enum and the final remainder becomes inhabited again, +so the code stops compiling until it is handled. -```rust -pub trait FinalizeExtract { - fn finalize_extract(self) -> T; -} +The family is the mirror of the [builder](./has_builder.md): a builder tracks which fields are *present*, +an extractor tracks which variants are still *possible*. -pub trait FinalizeExtractResult { - type Output; - fn finalize_extract_result(self) -> Self::Output; -} -``` +## Using it -`finalize_extract` returns *any* type, which is sound only because there is no value to return it from — it is -implemented for the uninhabited [`Void`](../types/type_level_spines.md), for `Infallible`, and for the -all-ruled-out configuration of a partial enum. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. -`finalize_extract_result` is the one you actually call. It collapses the `Result` from the last extraction, -and it is implemented for any `Result` whose error half can be finalized: +`Self` is an extractor rather than the enum, so a chain begins by obtaining one — +[`to_extractor`](./has_extractor.md) to consume the value, [`extractor_ref`](./has_extractor_ref.md) to +borrow it, or [`extractor_mut`](./has_extractor_mut.md) to borrow it mutably. Which one you pick decides +whether the payloads come out owned, shared, or mutable; the narrowing is identical in all three. -```rust -impl FinalizeExtractResult for Result -where - E: FinalizeExtract, -{ - type Output = T; - // Ok(value) => value, Err(remainder) => remainder.finalize_extract() -} -``` +The `PhantomData` argument names the variant, keyed by [`Symbol!`](../macros/symbol.md) of its name. + +The impls come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md), also available +through [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) and +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). ## Examples The chain reads as a sequence of attempts, each handling one variant, closed by -`finalize_extract_result`: +[`finalize_extract_result`](./finalize_extract_result.md): ```rust use cgp::core::field::traits::FinalizeExtractResult; @@ -136,55 +80,37 @@ fn area(shape: Shape) -> f64 { } ``` -After the second extraction both variants are ruled out, so the remainder's type is uninhabited and -`finalize_extract_result` is accepted with no wildcard arm. That is not a convention — it is the type. Try to -finalize after only the first extraction and it does not compile. - -Reading through a borrow leaves the value intact: - -```rust -let radius = shape - .extractor_ref() - .extract_field(PhantomData::) - .map(|circle| circle.radius) - .ok(); -``` - -and the mutable form changes a payload in place: - -```rust -if let Ok(circle) = shape - .extractor_mut() - .extract_field(PhantomData::) -{ - circle.radius = 5.0; -} -``` +After the second extraction both variants are ruled out, so the remainder's type is uninhabited and the +finalize is accepted with no wildcard arm. That is not a convention — it is the type. Try to finalize +after only the first extraction and it does not compile. **In practice you rarely write these chains.** The [dispatch combinators](../providers/dispatch_combinators.md) build them from a set of per-variant -implementations, which is the extensible visitor pattern — a chain exactly like the one above, generated, with -one implementation per variant chosen by wiring. +implementations, which is the extensible visitor pattern: a chain exactly like the one above, generated, +with one implementation per variant chosen by wiring. ## When to reach for it, and when not -**Reach for the family when independent code handles one variant each, or when the matching code cannot name -the enum.** Outside those two cases a `match` wins on every count: shorter, clearer, already exhaustive, and it -generates nothing. This is not an improvement on `match`; it is what you use where `match` is unavailable. - -- **Bound on `HasExtractor` + `ExtractField`** to write a routine that deconstructs an enum it does not name. -- **Pick the accessor by ownership**, and prefer the weakest that works: `extractor_ref` for a read-only - operation over a value you do not own, `extractor_mut` to mutate a payload, `to_extractor` only when you - genuinely want to consume. -- **Do not use it to test which variant a value holds.** `matches!` or an `if let` answers that in a line. The - family's value is in the *chain* and what the chain proves. -- **Reach for the [dispatch combinators](../providers/dispatch_combinators.md) rather than writing the chain**, - since they derive it from the enum's own variant list instead of repeating it at each site — which is what - keeps "add a variant" from breaking every call site by hand. - -The construction counterpart is [`FromVariant`](./from_variant.md), and the two are commonly wanted together -because a generic pipeline usually takes a value apart and puts one back. The struct analogue of the whole -family is [`HasBuilder`](./has_builder.md). +**Reach for the family when independent code handles one variant each, or when the matching code cannot +name the enum.** Outside those two cases a `match` wins on every count: shorter, clearer, already +exhaustive, and it generates nothing. This is not an improvement on `match`; it is what you use where +`match` is unavailable. + +- **Bound on [`HasExtractor`](./has_extractor.md) + `ExtractField`** to write a routine that + deconstructs an enum it does not name. +- **Pick the accessor by ownership**, preferring the weakest that works: + [`extractor_ref`](./has_extractor_ref.md) for a read-only operation, + [`extractor_mut`](./has_extractor_mut.md) to mutate a payload, + [`to_extractor`](./has_extractor.md) only when you genuinely want to consume. +- **Do not use it to test which variant a value holds.** `matches!` or an `if let` answers that in a + line. The family's value is in the *chain* and what the chain proves. +- **Reach for the [dispatch combinators](../providers/dispatch_combinators.md) rather than writing the + chain**, since they derive it from the enum's own variant list instead of repeating it at each site — + which is what keeps "add a variant" from breaking every call site by hand. + +The construction counterpart is [`FromVariant`](./from_variant.md), and the two are commonly wanted +together because a generic pipeline usually takes a value apart and puts one back. The struct analogue of +the whole family is [`HasBuilder`](./has_builder.md). ## Under the hood @@ -192,14 +118,13 @@ family is [`HasBuilder`](./has_builder.md). ### Advanced -This section shows how the exhaustiveness argument works. You do not need it to use the family, but the partial -enums appear by name in every extraction error, and the `IsVoid`-versus-`IsNothing` distinction is the one thing -here that genuinely surprises people. +This section shows how narrowing is encoded. The partial enums appear by name in every extraction error, +so recognizing one makes those errors legible. ::: -The derive generates a companion enum with one [`MapType`](./map_type.md) parameter per variant, each payload -wrapped in that parameter's projection: +The derive generates a companion enum with one [`MapType`](./map_type.md) parameter per variant, each +payload wrapped in that parameter's projection: ```rust pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { @@ -208,91 +133,74 @@ pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { } ``` -`to_extractor` starts at the all-`IsPresent` configuration, where every variant is still possible. Each -`extract_field` impl is in scope only while its variant's marker is `IsPresent`; on a miss it returns the -remainder with that one marker flipped to `IsVoid`, leaving the rest generic — which is why extractions may -happen in any order. - -**The exhaustiveness argument turns on what `IsVoid` maps to.** It maps a payload to the uninhabited `Void`, so -once every marker is `IsVoid` every arm of the partial enum holds a `Void` and the whole type is uninhabited. -The derive supplies a `FinalizeExtract` impl on exactly that configuration, and it is sound only because the -value cannot exist: - -```rust -impl FinalizeExtract for __PartialShape { - fn finalize_extract<__T__>(self) -> __T__ { - match self {} // no arms to write - } -} -``` +[`to_extractor`](./has_extractor.md) starts at the all-`IsPresent` configuration, where every variant is +still possible. **Each `extract_field` impl is in scope only while its variant's marker is `IsPresent`**; +on a miss it returns the remainder with that one marker flipped to `IsVoid`, leaving the rest generic — +which is why extractions may happen in any order. -So a caller reaches `finalize_extract` only after trying every variant, and the compiler accepts the discharge -with no fallback. +That per-variant scoping is the mirror of [`BuildField`](./build_field.md)'s requirement that a field be +`IsNothing` before it can be set, and it is what makes a repeated attempt a compile error rather than a +guaranteed `Err`. -**This is where the record and variant families diverge, and the difference is load-bearing.** 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 exactly why a builder needs an explicit all-present `FinalizeBuild` impl while an extractor can -discharge its remainder with an empty `match`. +The exhaustiveness argument itself belongs to [`FinalizeExtract`](./finalize_extract.md), and turns on +`IsVoid` mapping a payload to the uninhabited `Void`. -The borrowed accessors use the same partial enum with an extra [`MapTypeRef`](./map_type.md) parameter fixed to -`IsRef` or `IsMut`, mapping each payload slot to a shared or mutable reference — so a value can be matched -without being moved, and the narrowing works identically. +The borrowed accessors use the same partial enum with an extra [`MapTypeRef`](./map_type_ref.md) +parameter fixed to `IsRef` or `IsMut`, so a value can be matched without being moved and the narrowing +works identically. ## Gotchas -**`FinalizeExtractResult` is not in the prelude.** Import it from `cgp::core::field::traits`. Without it there -is no `finalize_extract_result` in scope and the chain has no clean ending. +**`Self` is an extractor, not the enum.** A chain starts with [`to_extractor`](./has_extractor.md) or one +of its borrowing siblings. -**Absence is `IsVoid` here and `IsNothing` in a builder, and they are not interchangeable.** An error naming the -wrong one usually means record and variant machinery have been crossed. +**Attempting the same variant twice does not compile.** The marker is already `IsVoid`, so no impl +applies, reported as a missing method. -**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`, so the compiler reports a missing method. Read the type in the message to -see which variants remain. +**Absence is `IsVoid` here and `IsNothing` in a builder, and they are not interchangeable.** An error +naming the wrong one usually means record and variant machinery have been crossed. -**A remainder carries none of the enum's attributes.** The partial enums are generated without your derives, so -a `Result` is neither `Debug` nor `PartialEq` however the enum is derived — `assert_eq!` on -the whole result does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. +**A remainder carries none of the enum's attributes.** The partial enums are generated without your +derives, so a `Result` is neither `Debug` nor `PartialEq` however the enum is derived +— `assert_eq!` on the whole result does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. -**Order is free but the set is not.** Each step changes only its own variant's marker, so extractions may be -written in any order — but every variant must be tried before the remainder can be finalized. +**Order is free but the set is not.** Each step changes only its own variant's marker, so extractions may +be written in any order — but every variant must be tried before the remainder can be finalized. -**Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the reason to -prefer the [dispatch combinators](../providers/dispatch_combinators.md). +**Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the +reason to prefer the [dispatch combinators](../providers/dispatch_combinators.md). **Five enum variant names are reserved**, because the generated impls name their associated types through `Self::…`. The [derive's page](../derives/derive_extract_field.md) lists them. ## Related constructs -- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the partial enums and every impl - here. -- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this family with the shape and the - constructors. -- [`FromVariant`](./from_variant.md) — the construction counterpart, commonly derived alongside. -- [`HasBuilder`](./has_builder.md) — the struct analogue, and where the `IsNothing`/`IsVoid` contrast comes from. -- [`MapType`](./map_type.md) — the `IsPresent`/`IsVoid` markers and the `MapTypeRef` borrow markers. -- [`HasFields`](./has_fields.md) — the variant shape the casts and dispatchers walk. -- [`CanUpcast`](./cast.md) — upcasting and downcasting, built on this recursion. -- [Type-level spines](../types/type_level_spines.md) — `Either`/`Void`, where the uninhabited terminator comes - from. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build the chain for you. +- [`HasExtractor`](./has_extractor.md), [`HasExtractorRef`](./has_extractor_ref.md), and + [`HasExtractorMut`](./has_extractor_mut.md) — the three ways to obtain an extractor. +- [`FinalizeExtract`](./finalize_extract.md) and + [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. +- [`FromVariant`](./from_variant.md) — the construction counterpart. +- [`HasBuilder`](./has_builder.md) — the struct analogue of the whole family. +- [`MapType`](./map_type.md) — the `IsPresent`/`IsVoid` markers, and where the contrast with `IsNothing` + is explained. +- [`CanDowncast`](./can_downcast.md) — narrowing to another enum rather than to a payload, built on this. +- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the partial enums and every + impl here. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build the chain for + you. +- [Type-level spines](../types/type_level_spines.md) — `Either`/`Void`, where the uninhabited terminator + comes from. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — partial variants, the exhaustiveness argument, - and the extensible visitor pattern. +- [Extensible variants](/docs/concepts/extensible-variants) — partial variants, the exhaustiveness + argument, and the extensible visitor pattern. - [Dispatching](/docs/concepts/dispatching) — routing a variant to the implementation that handles it. ## Source - [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) - — every trait on this page -- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs) - — `PartialData`, which the partial enums also implement -- [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) - — the `IsRef`/`IsMut` borrow markers + — `ExtractField` and the rest of the family --- diff --git a/docs/reference/traits/field_getter.md b/docs/reference/traits/field_getter.md new file mode 100644 index 00000000..e4bde7b8 --- /dev/null +++ b/docs/reference/traits/field_getter.md @@ -0,0 +1,185 @@ +--- +sidebar_label: 'FieldGetter' +--- + +# `FieldGetter` + +The provider-side mirror of `HasField` — field access that gets wired. + +## What it's for + +[`HasField`](./has_field.md) is a bound an implementation states about its own context. Sometimes field +access should instead be **chosen by wiring**, so that a context decides which of its fields answers a +given getter. That needs the provider-trait shape: the context as an explicit type argument rather than +as `&self`. + +`FieldGetter` is that shape: + +```rust +pub trait FieldGetter { + type Value; + + fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value; +} +``` + +`Self` is the **provider** — a zero-sized marker carrying no data — while `Context` is the type the field +is read from. This is the ordinary consumer/provider duality applied to field access: **you bound against +[`HasField`](./has_field.md), and you wire `FieldGetter`**. They are not alternatives. + +[`UseField`](../providers/use_field.md) is the provider that implements it by reading a named field, and +it is what [`#[cgp_getter]`](../macros/cgp_getter.md) targets. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +You rarely name the trait directly. What you write is a wiring entry naming a provider that implements +it: + +```rust +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} +``` + +Reading it back: the getter component is answered by [`UseField`](../providers/use_field.md), which +implements `FieldGetter` by reading the `first_name` field — a field whose name need not match the +getter's method name, which is the whole point of wiring the access rather than deriving it. + +Writing a `FieldGetter` impl by hand is the escape hatch for a getter whose value is computed rather than +stored, and it is an ordinary trait impl on a marker type of your own. + +## Examples + +The wired form, where the field's name and the getter's name differ: + +```rust +use cgp::prelude::*; + +#[cgp_getter(NameGetter)] +pub trait HasName { + fn name(&self) -> &String; +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} + +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} +``` + +`person.name()` now returns the `first_name` field. **Value context, self-targeted.** + +A second context can answer the same getter from a different field by changing one wiring line, which is +what the provider-side shape buys and what a plain [`HasField`](./has_field.md) bound cannot express. + +## When to reach for it, and when not + +**Wire a `FieldGetter` only when a context must choose which field a getter reads**, which is the +advanced case. Everything else is better served higher up. + +- **Use an [`#[implicit]`](../attributes/implicit.md) argument** for a field an implementation reads from + its own context. It generates a [`HasField`](./has_field.md) bound and involves no provider at all. +- **Use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md)** when the read must be a named capability, + keyed by the method name. It generates a blanket impl over `HasField` and needs no wiring. +- **Use [`#[cgp_getter]`](../macros/cgp_getter.md)** when the source field must be chosen per context. + That is what makes the getter a full component with a `FieldGetter` provider trait, and it costs a + wiring line per context. +- **Reach for [`MutFieldGetter`](./mut_field_getter.md)** when the wired access must also mutate. + +Do not treat it as an alternative to [`HasField`](./has_field.md). One is what an implementation +requires; the other is what a context supplies. + +## Under the hood + +:::note + +### Advanced + +This section shows the impl that connects wiring to a context's own fields. + +::: + +The provider side connects to ordinary derived field access through one blanket impl: +[`UseContext`](../providers/use_context.md) implements `FieldGetter` for any context that already has the +field, delegating straight through. + +```rust +impl FieldGetter for UseContext +where + Context: HasField, +{ + type Value = Field; + + fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value { + context.get_field(PhantomData) + } +} +``` + +So wiring a getter to `UseContext` means "read the field of the same name off the context", which is the +behaviour [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) gives without any wiring. + +[`UseField`](../providers/use_field.md) is the more interesting provider: it fixes the tag at the +wiring site, so the field it reads is decided there rather than by the method's name. + +The lifetime-safe variant [`FieldMapper`](./field_mapper.md) is a blanket impl over every `FieldGetter` +with the getter and tag `'static`, which is what [`ChainGetters`](../providers/chain_getters.md) relies +on. + +## Gotchas + +**`Self` is the provider, not the context.** The context is the first type parameter. Reading the +signature the other way round is the usual confusion when meeting a provider trait, and it applies to +every provider trait rather than to this one specially. + +**It is not an alternative to [`HasField`](./has_field.md).** Bounding an implementation on `FieldGetter` +instead of `HasField` is almost always a mistake: the implementation wants a requirement on its context, +not a provider parameter. + +**The getter's method name and the field's name are independent once wired.** That is the feature, and it +means a reader cannot infer the field from the getter — the wiring line is the only place the answer +lives. + +**A getter wired to [`UseContext`](../providers/use_context.md) needs the field to exist under the +getter's own name**, since that impl keys on the tag it is given. + +**It returns a reference.** A getter that must produce an owned or computed value uses +[`MRef`](../types/mref.md) as its return type instead. + +## Related constructs + +- [`HasField`](./has_field.md) — the consumer side you bound against. +- [`MutFieldGetter`](./mut_field_getter.md) — the mutable extension of this trait. +- [`FieldMapper`](./field_mapper.md) — the lifetime-safe form, for nested access. +- [`UseField`](../providers/use_field.md) — the provider that implements it by reading a named field. +- [`UseContext`](../providers/use_context.md) — the provider that routes back through the context's own + fields. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that makes a getter a full component. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — the simpler getter, keyed by method name. +- [`ChainGetters`](../providers/chain_getters.md) — composing getters to reach a nested field. +- [`MRef`](../types/mref.md) — the owned-or-borrowed return type for a getter that may produce its value. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the duality this trait is + the field-access instance of. + +## Source + +- [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) + — `FieldGetter` and the `UseContext` impl +- [`use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs) + — the `UseField` provider + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field_mapper.md b/docs/reference/traits/field_mapper.md new file mode 100644 index 00000000..b4551426 --- /dev/null +++ b/docs/reference/traits/field_mapper.md @@ -0,0 +1,179 @@ +--- +sidebar_label: 'FieldMapper' +--- + +# `FieldMapper` + +The provider-side mirror of `MapField`. + +## What it's for + +[`MapField`](./map_field.md) reads through a field without forcing its type to be `'static`, by taking a +higher-ranked closure instead of returning the intermediate borrow. `FieldMapper` is the same operation +in provider-trait shape, with the context as an explicit type argument rather than as `&self`: + +```rust +pub trait FieldMapper: FieldGetter { + fn map_field( + context: &Context, + _tag: PhantomData, + mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, + ) -> &T; +} +``` + +`Self` is the provider; `Context` is the type being read from. It is a supertrait extension of +[`FieldGetter`](./field_getter.md), exactly as [`MapField`](./map_field.md) extends +[`HasField`](./has_field.md) — so the group's two-by-two shape holds here too: + +| | you bound against | you wire | +|---|---|---| +| plain read | [`HasField`](./has_field.md) | [`FieldGetter`](./field_getter.md) | +| read through | [`MapField`](./map_field.md) | `FieldMapper` | + +**This is the one [`ChainGetters`](../providers/chain_getters.md) actually uses**, because a chained +getter is a provider composing other providers rather than a method on a concrete type. + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::traits`: + +```rust +use cgp::core::field::traits::FieldMapper; +``` + +**Nobody implements it.** It is a blanket impl for every [`FieldGetter`](./field_getter.md) with the +getter and the tag `'static`, so every field-getter provider gains `map_field` for free — which is +precisely what makes chaining composable without each provider opting in. + +The `mapper` argument carries the same `for<'a>` binder as its consumer-side twin, and for the same +reason: it lets the returned borrow be tied to the field borrow rather than to a fixed lifetime. + +## Examples + +You meet it through a wiring line rather than a call. A getter that reaches a field on a nested context: + +```rust +use cgp::prelude::*; + +#[cgp_getter(NameGetter)] +pub trait HasName { + fn name(&self) -> &String; +} + +#[derive(HasField)] +pub struct Inner { + pub name: String, +} + +#[derive(HasField)] +pub struct Outer { + pub inner: Inner, +} + +delegate_components! { + Outer { + NameGetterComponent: ChainGetters>, + } +} +``` + +**Environmental context, self-targeted.** [`ChainGetters`](../providers/chain_getters.md) descends into +`inner` with `FieldMapper::map_field` and then applies the inner provider to what it finds — so +`outer.name()` resolves to `outer.inner.name` with no lifetime obligations leaking into either type. + +Calling it directly is possible and rarely what you want: + +```rust +use cgp::core::field::traits::FieldMapper; + +let name = >::map_field( + &outer, + PhantomData, + |inner| inner.get_field(PhantomData::), +); +``` + +## When to reach for it, and when not + +**Reach for [`ChainGetters`](../providers/chain_getters.md) rather than this trait.** It is the construct; +`FieldMapper` is the mechanism underneath it. + +- **Use [`ChainGetters`](../providers/chain_getters.md)** to reach a field on a nested context by wiring. +- **Use [`FieldGetter`](./field_getter.md)** when the wired access is a plain one-level read. +- **Use [`MapField`](./map_field.md)** when the descent happens on `self` rather than on a wired context + — the consumer-side twin. +- **Use an [`#[implicit]`](../attributes/implicit.md) argument** before any of them for a field of the + implementation's own context. + +Name it directly only when writing a getter provider of your own that must descend, and check first +whether composing the existing ones does the job. + +## Under the hood + +:::note + +### Advanced + +This section explains the two `'static` bounds and why they cost nothing. + +::: + +`FieldMapper` is a blanket impl over every [`FieldGetter`](./field_getter.md), with two `'static` bounds +that its consumer-side twin needs only one of: + +- the **tag** must be `'static`, which is free — a [`Symbol!`](../macros/symbol.md) or an + [`Index`](../types/index.md) is `'static` by construction; +- the **getter** — that is, `Self`, the provider — must be `'static`, which is also free, since a + provider is a zero-sized marker type with no lifetime parameters in the ordinary case. + +The field's *value* stays free of any bound, which is the whole point: it is the intermediate whose +lifetime the naive chained read could not express. + +[`ChainGetters`](../providers/chain_getters.md) composes descents by nesting `map_field` calls, one per +path segment, so an arbitrarily deep chain stays lifetime-correct. Because the impl is blanket, adding a +new getter provider makes it chainable with no extra work. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::traits`. +[`MapField`](./map_field.md) is the other non-prelude member of the group. + +**`Self` is the provider, not the context.** The context is the first type parameter and arrives as +`&Context` in the method. + +**The closure must be higher-ranked.** A closure capturing a reference of a particular lifetime will not +satisfy `for<'a>`, and the error talks about lifetime bounds rather than about the closure's body. + +**A provider with a non-`'static` parameter loses the blanket impl.** The bound on `Self` is free for an +ordinary zero-sized marker and not for one carrying a lifetime, which is a rare shape and a puzzling +failure when it happens. + +**It cannot map to an owned value.** The signature returns `&T`; a getter that must produce a value uses +[`MRef`](../types/mref.md). + +## Related constructs + +- [`MapField`](./map_field.md) — the consumer-side twin, and where the lifetime problem is explained in + full. +- [`FieldGetter`](./field_getter.md) — the supertrait, and the plain wired read. +- [`ChainGetters`](../providers/chain_getters.md) — the provider that uses this to descend. +- [`HasField`](./has_field.md) — the consumer side of field access. +- [`UseField`](../providers/use_field.md) and [`UseContext`](../providers/use_context.md) — the two + providers a chain is usually built from. +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags, `'static` by construction. +- [`MRef`](../types/mref.md) — the return type for a getter that may produce rather than lend. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the duality this trait is + an instance of. + +## Source + +- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs) + — `FieldMapper` and `MapField` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/finalize_build.md b/docs/reference/traits/finalize_build.md new file mode 100644 index 00000000..934a6737 --- /dev/null +++ b/docs/reference/traits/finalize_build.md @@ -0,0 +1,189 @@ +--- +sidebar_label: 'FinalizeBuild' +--- + +# `FinalizeBuild` + +Turning a fully-built partial record back into the concrete struct. + +## What it's for + +`FinalizeBuild` is where a build ends: + +```rust +pub trait FinalizeBuild: PartialData { + fn finalize_build(self) -> Self::Target; +} +``` + +What makes it the family's safety argument is not the method but **where the impl exists**. It is +implemented for exactly one configuration of a partial record — the one in which every field is +`IsPresent` — so calling it on an incomplete value is a *missing impl*, not a runtime check that fails: + +```rust +let person = Person::builder() + .build_field(PhantomData::, first) + .build_field(PhantomData::, last) + .finalize_build(); // resolves only here +``` + +Delete a middle line and this does not compile. There is nothing to run and nothing to panic — the method +is simply not in scope for a value with a field still absent. + +The destination type comes from its supertrait [`PartialData`](./partial_data.md), which every +configuration implements. That division is deliberate: **one names where you are going, the other says +you have arrived.** + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +`finalize_build` consumes the partial value and returns `Self::Target`. It takes no arguments — there is +nothing left to decide by the time it applies. + +Bounding on it is how generic builder code says it will produce a finished value: + +```rust +fn assemble(partial: Partial) -> Target +where + Partial: FinalizeBuild, +{ + partial.finalize_build() +} +``` + +The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md), which emits exactly one +per record. + +## Examples + +The ordinary ending of a build chain: + +```rust +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +let person = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .build_field(PhantomData::, "Chen".to_owned()) + .finalize_build(); +``` + +And the failure it exists to produce — omitting a field: + +```rust +// error: no method named `finalize_build` found for struct +// `__PartialPerson` +let person = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .finalize_build(); +``` + +**Read the partial type in the message to see which marker is still `IsNothing`.** That is the field you +forgot, and it is the only place the compiler names it. + +## When to reach for it, and when not + +**Call it at the end of every build; bound on it when the code is generic over the record.** + +- **Bound on [`HasBuilder`](./has_builder.md) + [`BuildField`](./build_field.md) + `FinalizeBuild`** to + write a routine that assembles a record it does not name. +- **Use [`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when unset fields should be filled + from `Default` rather than rejected. It re-marks every field to `IsPresent` and then calls this, so the + strict check still runs and always passes. +- **Use [`FinalizeOptional`](./finalize_optional.md)** when absence should be *reported* at run time + rather than caught at compile time. It returns a `Result` naming the first missing field. +- **Stay with `FinalizeBuild`** when every field is genuinely required. Moving to either of the other two + gives up the compile-time completeness check, which is the reason the family exists. + +## Under the hood + +:::note + +### Advanced + +This section shows the impl, and why the error reads the way it does. + +::: + +The derive emits one impl, with every marker fixed: + +```rust +impl FinalizeBuild for __PartialPerson { + // ... +} +``` + +Compare its supertrait, which leaves every marker generic: + +```rust +// impl PartialData for __PartialPerson { +// type Target = Person; +// } +``` + +So a partial value always knows its destination and only sometimes has a way to reach it. Because +`IsPresent::Map` is `T`, the all-present companion holds exactly the concrete struct's fields in the +same order, and the body is a field-by-field move with nothing to unwrap. + +**This is why the error is a missing method rather than a missing field.** Method resolution looks for +`finalize_build` on `__PartialPerson`, finds no impl, and reports that — the +compiler has no way to say "you forgot `last_name`", because nothing in the failed lookup mentions field +names. The marker list in the type is the diagnostic. + +The optional layer reaches this same impl rather than replacing it: +[`CanFinalizeWithDefault`](./can_finalize_with_default.md) runs a +[`TransformMapFields`](./transform_map_fields.md) to `IsPresent` first, so **the strict, all-present impl +remains the only way a partial value becomes a concrete struct.** + +## Gotchas + +**"No method named `finalize_build`" is the expected error for an incomplete build.** Read the partial +type in the message: the field whose marker is still `IsNothing` is the one missing. + +**It consumes the partial value**, so the builder cannot be reused afterwards. + +**It supertraits [`PartialData`](./partial_data.md)**, so naming both in a bound is redundant, and +`Target` is projected from the supertrait. + +**There is no fallible variant here.** Reporting absence at run time is +[`FinalizeOptional`](./finalize_optional.md), a different trait in a different crate. + +**A fieldless struct finalizes immediately.** Its companion has no markers, so `builder().finalize_build()` +compiles — legal and useless. + +**The enum side has its own ending.** [`FinalizeExtract`](./finalize_extract.md) discharges an exhausted +extractor, and it is sound for the opposite reason: the value cannot exist, rather than being complete. + +## Related constructs + +- [`PartialData`](./partial_data.md) — the supertrait naming the destination. +- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — where a partial value comes + from. +- [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) — what moves it between + configurations. +- [`UpdateField`](./update_field.md) — the primitive underneath both. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) and + [`FinalizeOptional`](./finalize_optional.md) — the two relaxed endings. +- [`MapType`](./map_type.md) — the `IsPresent` marker every field must reach. +- [`FinalizeExtract`](./finalize_extract.md) — the enum family's ending, sound for the opposite reason. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates this impl. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder + pattern. + +## Source + +- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs) + — `FinalizeBuild` and `BuildField` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/finalize_extract.md b/docs/reference/traits/finalize_extract.md new file mode 100644 index 00000000..4ecc8d17 --- /dev/null +++ b/docs/reference/traits/finalize_extract.md @@ -0,0 +1,166 @@ +--- +sidebar_label: 'FinalizeExtract' +--- + +# `FinalizeExtract` + +Discharging an extractor that has nothing left in it. + +## What it's for + +An [extraction chain](./extract_field.md) 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` is what turns +that fact into a usable ending: + +```rust +pub trait FinalizeExtract { + fn finalize_extract(self) -> T; +} +``` + +**It returns *any* type.** That looks unsound and is not, because there is no value to return it from: +the method can only be called on something that cannot exist, so its body is an empty `match` and no +execution path reaches it. + +That is what closes a generic match with **no wildcard arm and no `unreachable!()`**. It is the mirror of +[`FinalizeBuild`](./finalize_build.md), and the two are sound for opposite reasons: a build finalizes +because the value is *complete*, an extraction because the value is *impossible*. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +It is implemented for three things: the uninhabited [`Void`](../types/type_level_spines.md), the standard +`Infallible`, and the all-ruled-out configuration of a partial enum. Anything holding one of those can be +discharged. + +**You will usually call [`FinalizeExtractResult`](./finalize_extract_result.md) 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 come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md). + +## Examples + +Called directly, on a remainder held in hand: + +```rust +use cgp::prelude::*; + +match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => handle_circle(circle), + Err(remainder) => match remainder.extract_field(PhantomData::) { + Ok(rect) => handle_rectangle(rect), + Err(remainder) => remainder.finalize_extract(), // uninhabited: cannot be reached + }, +} +``` + +The last arm returns whatever the surrounding `match` needs, and the compiler accepts it because the +value being matched cannot exist. + +The same chain written with the `Result` helper is shorter and is what most code uses: + +```rust +use cgp::core::field::traits::FinalizeExtractResult; + +let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); +``` + +## When to reach for it, and when not + +**Reach for [`FinalizeExtractResult`](./finalize_extract_result.md) unless you already hold a +remainder.** The two do the same job at different points in the chain. + +- **[`FinalizeExtractResult`](./finalize_extract_result.md)** 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](../providers/dispatch_combinators.md)** rather than writing the chain at + all — they generate it from the enum's variant list, which is what 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 + +:::note + +### Advanced + +This section is the exhaustiveness argument in full, and it is the one part of the extractor family worth +reading closely. + +::: + +**Everything turns on what `IsVoid` maps to.** The [`MapType`](./map_type.md) marker `IsVoid` maps a +payload to the uninhabited [`Void`](../types/type_level_spines.md), 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: + +```rust +impl FinalizeExtract for __PartialShape { + fn finalize_extract<__T__>(self) -> __T__ { + match self {} // no arms to write + } +} +``` + +An empty `match` is legal precisely 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 with no fallback. + +**This is where the record and variant families diverge, and the difference is load-bearing.** 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 exactly why a builder needs an explicit all-present +[`FinalizeBuild`](./finalize_build.md) impl while an extractor can discharge its remainder with an empty +`match`. + +## Gotchas + +**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`, so the compiler reports a missing method. Read the type in +the message to see which variants remain. + +**It returns any type, which reads as unsound and is not.** The generic return is sound only because the +receiver is uninhabited; there is no value and no execution. + +**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](../providers/dispatch_combinators.md). + +**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. + +## Related constructs + +- [`FinalizeExtractResult`](./finalize_extract_result.md) — the form that closes a chain from a `Result`. +- [`ExtractField`](./extract_field.md) — the narrowing that leads here. +- [`HasExtractor`](./has_extractor.md) — where a chain begins. +- [`FinalizeBuild`](./finalize_build.md) — the record family's ending, sound for the opposite reason. +- [`MapType`](./map_type.md) — the `IsVoid` marker the argument rests on. +- [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. +- [`CanUpcast`](./can_upcast.md) — a cast whose total walk ends with this same discharge. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build the chain. +- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates this impl. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — the exhaustiveness argument, in full. + +## Source + +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) + — `FinalizeExtract` and the rest of the family + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/finalize_extract_result.md b/docs/reference/traits/finalize_extract_result.md new file mode 100644 index 00000000..c001ad57 --- /dev/null +++ b/docs/reference/traits/finalize_extract_result.md @@ -0,0 +1,171 @@ +--- +sidebar_label: 'FinalizeExtractResult' +--- + +# `FinalizeExtractResult` + +Collapsing the `Result` at the end of an extraction chain. + +## What it's for + +Every step of an [extraction chain](./extract_field.md) 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` is what says so: + +```rust +pub trait FinalizeExtractResult { + type Output; + + fn finalize_extract_result(self) -> Self::Output; +} +``` + +`Self` is the `Result`, and `Output` is the payload alone. It is implemented for any `Result` whose +error half can be discharged: + +```rust +impl FinalizeExtractResult for Result +where + E: FinalizeExtract, +{ + type Output = T; + // Ok(value) => value, Err(remainder) => remainder.finalize_extract() +} +``` + +**This is the one you actually call.** [`FinalizeExtract`](./finalize_extract.md) 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. + +## Using it + +**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 is what closes a chain: + +```rust +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: + +```rust +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); // no variants left, so this cannot fail + rect.width * rect.height + } + } +} +``` + +No `.unwrap()`, no `expect`, and no wildcard arm. The call compiles only because both variants have been +tried, which is what makes it a proof rather than an assertion. + +Calling it one step early does not compile: + +```rust +// error: the trait bound is not satisfied — Circle is still possible, +// so the remainder is inhabited and cannot be discharged +let rect = shape + .to_extractor() + .extract_field(PhantomData::) + .finalize_extract_result(); +``` + +## When to reach for it, and when not + +**Use it to close every hand-written extraction chain**, and prefer not writing the chain at all. + +- **`finalize_extract_result`** at the end of a chain, which is where the last `extract_field` left you + holding a `Result`. +- **[`FinalizeExtract`](./finalize_extract.md)** when a nested `match` has already unwrapped the + remainder out of its `Result`. +- **The [dispatch combinators](../providers/dispatch_combinators.md)** rather than a hand-written chain, + since they generate it from the enum's own variant list — which is what keeps "add a variant" from + breaking every call site. +- **`.ok()` or a `match`** when you are making a single attempt and do not intend to exhaust the enum. + Reaching for this trait then simply will not resolve. +- **A `match`** when the enum is concrete. + +## Under the hood + +:::note + +### Advanced + +This section is short: the trait is one blanket impl. + +::: + +The impl delegates to [`FinalizeExtract`](./finalize_extract.md) on the error half, which is where the +soundness argument lives — 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`](../types/type_level_spines.md). That is occasionally useful +outside the extractor family, for collapsing a `Result` that a signature required but that cannot fail. + +`Output` being an associated type rather than a generic is what lets the call sit at the end of a method +chain with nothing to annotate. + +## Gotchas + +**It is not in the prelude.** Import it from `cgp::core::field::traits`. Without it there is no +`finalize_extract_result` in scope and the chain has no clean ending — and the error is a +missing-method one, which reads as though the chain is wrong rather than the import missing. + +**Calling it early does not compile.** Any variant still possible leaves the remainder inhabited and the +bound unsatisfied. + +**It discards nothing and cannot panic.** Unlike `.unwrap()`, there is no runtime branch — 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`](./finalize_extract.md) — the underlying discharge, and the full exhaustiveness + argument. +- [`ExtractField`](./extract_field.md) — the narrowing that produces the `Result` this collapses. +- [`HasExtractor`](./has_extractor.md) — where a chain begins. +- [`FinalizeBuild`](./finalize_build.md) — the record family's ending. +- [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. +- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build the chain for + you. +- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — what makes an enum extractable. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — the exhaustiveness argument and the + extensible visitor pattern. + +## Source + +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) + — `FinalizeExtractResult` and the rest of the family + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/finalize_optional.md b/docs/reference/traits/finalize_optional.md new file mode 100644 index 00000000..5f95eed1 --- /dev/null +++ b/docs/reference/traits/finalize_optional.md @@ -0,0 +1,171 @@ +--- +sidebar_label: 'FinalizeOptional' +--- + +# `FinalizeOptional` + +Finalizing an optional builder, reporting the first missing field. + +## What it's for + +An [optional builder](./has_optional_builder.md) has given up the compile-time completeness check: every +field is `IsOptional`, so the type no longer records what has been set. Something has to check at run +time instead, and `FinalizeOptional` is the strict way to do it: + +```rust +pub trait FinalizeOptional: PartialData { + fn finalize_optional(self) -> Result; +} +``` + +It succeeds only if every field holds a value. The error is **the first missing field's own name**, as a +`&'static str` recovered from the field's type-level tag — so a caller learns which field was left unset +without any allocation. + +It is one of two endings for an optional builder, and the choice between them is made at the call site +rather than when the builder is created: + +| | a field left unset | +|---|---| +| `FinalizeOptional` | `Err("field_name")` | +| [`CanFinalizeWithDefault`](./can_finalize_with_default.md) | filled from `Default` | + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::FinalizeOptional; +``` + +It supertraits [`PartialData`](./partial_data.md), which is where `Target` — the concrete struct being +built — comes from. + +`Self` must be an optional builder, from +[`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md). + +## Examples + +The strict ending, succeeding and failing: + +```rust +use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +let context = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .set(PhantomData::, 42) + .finalize_optional() + .unwrap(); + +assert_eq!(context.foo, "foo"); +``` + +Leave `bar` unset and it reports the name: + +```rust +let result = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_optional(); + +assert_eq!(result.err(), Some("bar")); +``` + +## When to reach for it, and when not + +**Reach for it when absence is an error you want to *report* rather than paper over.** + +- **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when unset fields have meaningful + defaults and silence is the right outcome. The two are the same builder finalized differently, so the + same value can go either way. +- **[`FinalizeBuild`](./finalize_build.md)** — that is, the core builder — when every field is genuinely + required and set once. A missing field is then a *compile* error, which is strictly better than a + `Result` and is what you give up by moving to this layer. +- **A hand-written check** when the validation is more than presence: interdependent fields, ranges, + anything needing a structured error. + +One thing to notice about the trade: this moves a missing field from a compile error to a `Result`, and +the error type is a `&'static str` field name rather than a structured value. That is enough to report +which field is missing and not enough to match on programmatically. + +## Under the hood + +:::note + +### Advanced + +This section shows why this one walks the shape itself rather than using a transform. + +::: + +Unlike its defaulting sibling, `FinalizeOptional` does **not** go through +[`TransformMapFields`](./transform_map_fields.md). It walks the target's +[`HasFields`](./has_fields.md) spine directly, and the reason is that it has to be able to *stop*. + +For each field it pulls the `Option` out with [`UpdateField`](./update_field.md), and: + +- if it is `Some`, writes the value back as `IsPresent` with [`BuildField`](./build_field.md) and + continues; +- if it is `None`, returns `Err(Tag::VALUE)` immediately — the field's name recovered as a static string + through [`StaticString`](./static_string.md). + +Only if every field yields a value does the walk reach the all-present configuration and call +[`finalize_build`](./finalize_build.md). + +**The strict, all-present [`FinalizeBuild`](./finalize_build.md) remains the only way a partial value +becomes a concrete struct.** Everything in this layer simply guarantees that configuration is reached +before it is invoked — or reports why it could not be. + +That short-circuiting is also why only the *first* missing field is named: the walk stops at it rather +than collecting. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**The error is a `&'static str`.** It names the first missing field and is not a structured error, so it +cannot be matched on beyond string comparison. + +**It reports only the first.** A builder missing three fields yields one name. + +**It does not apply to a core builder.** The fields must be `IsOptional`; a core builder either +finalizes at compile time or does not. + +**It supertraits [`PartialData`](./partial_data.md)**, so `Target` is projected from there and naming +both in a bound is redundant. + +**Field order decides which name you get**, since the walk follows declaration order and stops at the +first `None`. + +## Related constructs + +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the other ending, filling gaps from + `Default`. +- [`HasOptionalBuilder`](./has_optional_builder.md) and [`ToOptional`](./to_optional.md) — where an + optional builder comes from. +- [`SetOptional`](./set_optional.md) — filling one. +- [`FinalizeBuild`](./finalize_build.md) — the strict impl this ultimately calls. +- [`PartialData`](./partial_data.md) — the supertrait naming the destination. +- [`StaticString`](./static_string.md) — how the missing field's name is recovered. +- [`UpdateField`](./update_field.md) and [`BuildField`](./build_field.md) — the primitives the walk uses. +- [`HasFields`](./has_fields.md) — the shape it walks. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence + fits. + +## Source + +- [`finalize_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/finalize_optional.rs) + — `FinalizeOptional` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/from_fields.md b/docs/reference/traits/from_fields.md new file mode 100644 index 00000000..2928de23 --- /dev/null +++ b/docs/reference/traits/from_fields.md @@ -0,0 +1,164 @@ +--- +sidebar_label: 'FromFields' +--- + +# `FromFields` + +Rebuilding a concrete value from its shape. + +## What it's for + +[`ToFields`](./to_fields.md) takes a value apart into an anonymous list of named entries. `FromFields` is +the return journey: + +```rust +pub trait FromFields: HasFields { + fn from_fields(fields: Self::Fields) -> Self; +} +``` + +It is what closes the loop for generic code: decompose a value, work on the entries without naming the +type, and put a concrete value back together at the end. Both directions go through the identical +`Fields` type, so **the shapes line up by construction rather than by check** — there is nothing to +validate and nothing that can fail. + +It is an associated function rather than a method, since there is no value to call it on. The call reads +`Person::from_fields(fields)`, or `T::from_fields(fields)` in generic code. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +It supertraits [`HasFields`](./has_fields.md), so bounding on `FromFields` gives you `Fields` as well. +The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md), which emits all five shape +traits together. + +The argument must be **exactly** `Self::Fields` — the same entries, the same tags, in the same order. A +shape that merely has the same field names in a different order is a different type and will not be +accepted, which is what makes the conversion total. + +## Examples + +Rebuilding after a round trip: + +```rust +use cgp::prelude::*; + +#[derive(Clone, Debug, Eq, PartialEq, HasFields)] +pub struct Config { + pub host: String, + pub port: u16, +} + +let config = Config { host: "localhost".to_owned(), port: 8080 }; + +let fields = config.clone().to_fields(); +let config_again = Config::from_fields(fields); + +assert_eq!(config, config_again); +``` + +In generic code it is the half that names the destination: + +```rust +fn rebuild(fields: T::Fields) -> T +where + T: FromFields, +{ + T::from_fields(fields) +} +``` + +An enum rebuilds the same way, from a [`Sum!`](../macros/sum.md) rather than a product — the arm that is +present becomes the variant that is constructed. + +## When to reach for it, and when not + +**Bound on it when generic code produces a concrete value from entries it has assembled or transformed.** +Pair it with [`ToFields`](./to_fields.md) for a round trip, and require only one of the two when only one +direction happens. + +- **[`ToFields`](./to_fields.md)** for the decomposition half. +- **[`HasFields`](./has_fields.md) alone** when the code names the shape and never builds a value. +- **The [builder family](./has_builder.md)** when the value is assembled *incrementally*, from pieces + arriving at different times. `from_fields` needs the whole shape at once, already complete; + [`HasBuilder`](./has_builder.md) tracks presence field by field and is what the extensible builder + pattern uses. +- **[`FromVariant`](./from_variant.md)** when an enum is built from *one* named variant rather than from + a whole shape. That is the far more common way to construct an enum generically. +- **A plain constructor** when the type is concrete. Nothing about `from_fields` improves on a struct + literal where one can be written. + +## Under the hood + +:::note + +### Advanced + +This section shows the generated impl, which is `to_fields` read backwards. + +::: + +The conversion destructures the `Cons` chain positionally and unwraps each entry's value: + +```rust +impl FromFields for Person { + fn from_fields(Cons(name, Cons(age, Nil)): Self::Fields) -> Self { + Self { name: name.value, age: age.value } + } +} +``` + +Note the pattern in the argument position: the shape is matched apart in the signature itself, one node +per field, terminated by `Nil`. Because the chain is built and matched in declaration order, this is the +exact inverse of [`to_fields`](./to_fields.md) — no lookup by name happens at run time, and the tags +exist only to make the types distinct. + +An enum's impl is the dual: a `match` over the `Either` chain, each arm reconstructing the corresponding +variant, with the `Void` terminator unreachable by construction. + +## Gotchas + +**It is an associated function, not a method.** Write `T::from_fields(fields)`; there is no receiver. + +**The shape must match exactly.** Same tags, same value types, same order. Two structs with identical +field names in different orders have unrelated `Fields` types, and the mismatch is reported against the +whole chain rather than against the field that moved. + +**A newtype's shape is the inner type**, not a one-element product, so `from_fields` on +`struct Wrapper(String)` takes a `String`. + +**It supertraits [`HasFields`](./has_fields.md)**, so naming both in a bound is redundant. + +**It cannot build a value incrementally.** The whole shape is required at once. Assembling from +independent pieces is [`HasBuilder`](./has_builder.md)'s job, and reaching for `from_fields` there means +constructing the complete product by hand first. + +**There is no borrowing counterpart.** [`ToFieldsRef`](./to_fields_ref.md) has no `FromFieldsRef`, because +a borrowed shape cannot yield an owned value. + +## Related constructs + +- [`ToFields`](./to_fields.md) — the reverse conversion, and the one usually written first. +- [`HasFields`](./has_fields.md) — the supertrait that names the shape. +- [`ToFieldsRef`](./to_fields_ref.md) and [`HasFieldsRef`](./has_fields_ref.md) — the borrowed half of + the family, which has no rebuild. +- [`FromVariant`](./from_variant.md) — constructing an enum from one named variant. +- [`HasBuilder`](./has_builder.md) — incremental assembly, as against this wholesale conversion. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl. +- [`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), and [`Field`](../types/field.md) — what + a shape is made of. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum half. + +## Source + +- [`from_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_fields.rs) + — `FromFields` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md index 506a3fe4..da5ceb20 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/from_variant.md @@ -108,7 +108,7 @@ let ident = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::, first) - .build_field(PhantomData::, last) - .finalize_build(); // all present: this resolves -``` - -Delete a middle line and this does not compile. - -Everything here reduces to **one primitive**, `UpdateField`, which changes one field's storage from one state -to another. `BuildField` and `TakeField` are the two directions of that change, and `HasBuilder`/`IntoBuilder` -and `FinalizeBuild` are the entry and exit points. The impls come from -[`#[derive(BuildField)]`](../derives/derive_build_field.md), which also generates the partial companion type -they all operate on. - -## Using it - -Most of the family is in the prelude — `HasBuilder`, `IntoBuilder`, `UpdateField`, `BuildField`, -`PartialData`, `FinalizeBuild`. The exception is **`TakeField`, which is not**; import it from -`cgp::core::field::traits` when you call `take_field` directly. - -### The entry points - -Two traits obtain a partial value to build into, differing in where they start: +A struct literal supplies every field at once, in one place that names the type. `HasBuilder` is the +entry point for the case where that is impossible: the fields come from several independent places, none +of which should know the whole struct, and the result must still be checked at compile time. ```rust pub trait HasBuilder { type Builder; - fn builder() -> Self::Builder; -} -pub trait IntoBuilder { - type Builder; - fn into_builder(self) -> Self::Builder; + fn builder() -> Self::Builder; } ``` -`HasBuilder::builder()` gives a partial value with **every field absent**. `IntoBuilder::into_builder(self)` -goes the other way, turning an existing value into a partial one with **every field present** — which is what -you want when redistributing a struct's fields rather than assembling one. - -### The primitive - -`UpdateField` is what everything else is built from. It moves the field named by `Tag` from its -current marker to the new marker `M`, both [`MapType`](./map_type.md) markers, and returns the old value -alongside the rebuilt partial value: +`builder()` hands back a partial value with **every field absent**. Filling it is +[`BuildField`](./build_field.md), and turning it back into the concrete struct is +[`FinalizeBuild`](./finalize_build.md) — which is implemented **only** for the fully-present +configuration, so finalizing early is a missing impl rather than a runtime panic: ```rust -pub trait UpdateField { - type Value; - type Mapper: MapType; // the field's marker before the update - type Output; // the partial value with the field now in state M - - fn update_field( - self, - _tag: PhantomData, - value: M::Map, - ) -> (::Map, Self::Output); -} +let person = Person::builder() // every field absent + .build_field(PhantomData::, first) + .build_field(PhantomData::, last) + .finalize_build(); // all present: this resolves ``` -The `Map<…>` wrappers are the field's value *as stored* under each marker: `IsPresent` stores the value -itself, `IsNothing` stores `()`. So setting an absent field takes the real value in and hands `()` back, and -removing a present one takes `()` in and hands the real value back. - -### The two directions +Delete a middle line and this does not compile. **Field presence lives in the type**, which is the +defining idea of the whole family. -`BuildField` and `TakeField` are blanket impls over that primitive, each pinning one transition: - -```rust -pub trait BuildField { - type Value; - type Output; - fn build_field(self, _tag: PhantomData, value: Self::Value) -> Self::Output; -} - -pub trait TakeField { - type Value; - type Remainder; - fn take_field(self, _tag: PhantomData) -> (Self::Value, Self::Remainder); -} -``` - -`BuildField` is the `IsNothing → IsPresent` direction — set a currently-absent field — and `TakeField` is -`IsPresent → IsNothing` — remove a currently-present one. Because each requires a specific starting marker, the -compiler rejects building a field that is already set or taking one that is absent. +## Using it -### The exit +**It is in the prelude**, so `use cgp::prelude::*;` is enough. -```rust -pub trait PartialData { - type Target; -} +`builder()` is an associated function with no receiver, called as `Person::builder()` or `T::builder()` +in generic code. `Builder` names the partial companion type the derive generated — you rarely write that +type, but it is what appears in an error when a build is incomplete. -pub trait FinalizeBuild: PartialData { - fn finalize_build(self) -> Self::Target; -} -``` +The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md), also available through +[`#[derive(CgpRecord)]`](../derives/derive_cgp_record.md) and +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). -`PartialData::Target` names the struct being built and is implemented for **every** configuration, which is how -generic builder code knows the destination before the build is complete. `FinalizeBuild` is implemented for -**only** the all-present configuration, which is the safety argument in one line. +**Its counterpart is [`IntoBuilder`](./into_builder.md)**, which starts from an existing value with every +field *present* rather than from nothing. The two differ only in where they begin, and the choice is +about whether you are assembling a record or redistributing one. ## Examples -The everyday shape is `builder()`, some `build_field` calls, and `finalize_build`, with `build_from` copying -every shared field from another record in one step: +The everyday shape is `builder()`, some `build_field` calls, and `finalize_build`, with +[`build_from`](./can_build_from.md) copying every shared field from another record in one step: ```rust use cgp::core::field::impls::CanBuildFrom; @@ -154,23 +85,7 @@ fn extend(foo_bar: FooBar) -> FooBarBaz { Every line changes the partial *type*, and the last one type-checks only because every marker has reached present. Reorder them so `finalize_build` runs before `baz` is set and it is a compile error. -The reverse direction takes a finished value apart and puts it back, which is what generic code -redistributing fields does: - -```rust -use cgp::core::field::traits::TakeField; - -let builder = person.into_builder(); // all present - -let (first_name, remainder) = builder.take_field(PhantomData::); -// `remainder` is missing first_name, so it cannot be finalized - -let person = remainder - .build_field(PhantomData::, first_name) - .finalize_build(); // all present again -``` - -A field that has been set can also be read back mid-build, because the derive emits a +A field that has been set can be read back mid-build, because the derive emits a [`HasField`](./has_field.md) impl on the partial type gated on presence: ```rust @@ -184,25 +99,23 @@ Asking for `last_name` there would not compile. ## When to reach for it, and when not -**Use the methods; bound on the traits only in generic code.** In concrete code you call `builder()`, -`build_field`, and `finalize_build` and never name a trait. The traits matter when you write code that is -generic over the record being built — which is the extensible builder pattern, and the reason the family exists. +**Call `builder()` freely in concrete code; bound on the trait only in generic code.** In concrete code +you call it and never name a trait. The bound matters when you write code that is generic over the +record being built — which is the extensible builder pattern, and the reason the family exists. -- **Bound on `HasBuilder` + `BuildField` + `FinalizeBuild`** to write a routine that assembles some record it - does not name. -- **Bound on `PartialData`** when you need the destination type mid-build, before the value is complete. -- **Bound on `UpdateField` directly** only for an operation neither `BuildField` nor `TakeField` covers — such - as a transition to or from `IsOptional`, which is what the - [optional-field extensions](./optional_fields.md) do. +- **Bound on `HasBuilder` + [`BuildField`](./build_field.md) + [`FinalizeBuild`](./finalize_build.md)** + to write a routine that assembles some record it does not name. +- **Use [`IntoBuilder`](./into_builder.md)** when you start from an existing value rather than from + nothing. - **Do not reach for any of it for a struct you build with a literal.** A literal is already checked for completeness, reads better, and generates nothing. This family buys *decoupling*, and with nothing to decouple it is pure cost. Two boundaries are worth stating plainly. This is **not a conventional builder**: it tracks presence and nothing else — no defaults, no validation at finalize, no optional field unless the field's own type is -optional. The [optional-field extensions](./optional_fields.md) cover the defaulted and optional cases, and a -hand-written builder remains better when the *logic* is the point. And the enum counterparts are a different -family: [`ExtractField`](./extract_field.md) for taking a value apart and +optional. The [optional-field extensions](./has_optional_builder.md) cover the defaulted and optional +cases, and a hand-written builder remains better when the *logic* is the point. And the enum counterparts +are a different family: [`ExtractField`](./extract_field.md) for taking a value apart and [`FromVariant`](./from_variant.md) for constructing one. ## Under the hood @@ -211,9 +124,9 @@ family: [`ExtractField`](./extract_field.md) for taking a value apart and ### Advanced -This section shows how presence is encoded and why finalizing early fails. You do not need it to use the -builder, but the partial type appears by name in every builder error, so recognizing it turns "no method named -`finalize_build`" into a legible message. +This section shows what `Builder` actually is, and why finalizing early fails. The partial type appears +by name in every builder error, so recognizing it turns "no method named `finalize_build`" into a legible +message. ::: @@ -228,83 +141,66 @@ pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { } ``` -The marker in each position decides the storage: `IsPresent` holds the value, `IsNothing` holds `()`, `IsVoid` -holds the uninhabited `Void`. Then the two impls that make the whole thing safe: +`HasBuilder` then fixes the starting configuration to all-absent: ```rust impl HasBuilder for Person { type Builder = __PartialPerson; // the empty builder // ... } - -impl FinalizeBuild for __PartialPerson { // only at all-present - // ... -} ``` -`builder()` starts at all-absent, each `build_field` flips one marker, and `finalize_build` exists only at -all-present. There is no check to run — the impl simply is not there for an incomplete value. - -The per-field `UpdateField` impl is what does the flipping, and note that only the named field's marker moves -while the rest stay generic — which is why fields can be built in any order: +and [`FinalizeBuild`](./finalize_build.md) exists only at the opposite end: ```rust -impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> - UpdateField for __PartialPerson<__M1__, __F1__> -{ - type Value = String; - type Mapper = __M1__; // the marker before - type Output = __PartialPerson<__M2__, __F1__>; // and after +impl FinalizeBuild for __PartialPerson { // ... } ``` -**Neither `BuildField` nor `TakeField` is generated.** Both are library blanket impls over that one -`UpdateField`, in opposite directions — `BuildField` over -`UpdateField` and `TakeField` over -`UpdateField` — which is why `UpdateField`, the general form, is what the -derive actually writes. `FinalizeBuild` is likewise a library subtrait of `PartialData`; the derive supplies -only its all-present impl. +That pair is the whole safety argument. `builder()` starts at all-absent, each +[`build_field`](./build_field.md) flips one marker, and there is no check to run at the end — the impl +simply is not there for an incomplete value. -`TakeField` is also the trait behind bulk merging: `CanBuildFrom`'s `build_from` recurses over the source's -field list, taking each field out and building it into the target. +Everything between the two ends reduces to one primitive, [`UpdateField`](./update_field.md), which is +what the derive actually writes; [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are +library blanket impls over it in opposite directions. ## Gotchas -**`TakeField` is not in the prelude.** Import it from `cgp::core::field::traits`. `CanBuildFrom`, which -provides `build_from`, comes from `cgp::core::field::impls`. +**"No method named `finalize_build`" is the expected error for an incomplete build.** A missing field +means the all-present impl does not apply, so the compiler reports a missing method rather than a missing +field. Read the partial type in the message to see which marker is still `IsNothing`. -**`build_from` needs [`HasFields`](./has_fields.md) on the *source*.** It walks the source's field list to know -what to copy, so a source deriving only `BuildField` cannot be merged into anything. The target needs only the -builder. This is the easiest thing here to get wrong, because deriving the same thing on both looks symmetric. - -**"No method named `finalize_build`" is the expected error for an incomplete build.** A missing field means the -all-present impl does not apply, so the compiler reports a missing method rather than a missing field. Read the -partial type in the message to see which marker is still `IsNothing`. - -**The partial type cannot be printed or cloned.** The derive clears the original's attributes, so no `Debug`, -no `Clone`, whatever the record derives. Read a set field through the partial type's +**The partial type cannot be printed or cloned.** The derive clears the original's attributes, so no +`Debug`, no `Clone`, whatever the record derives. Read a set field through the partial type's [`HasField`](./has_field.md) impl instead. -**There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible default -still has to be set, unless you reach for the [optional-field extensions](./optional_fields.md). +**There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible +default still has to be set, unless you reach for the +[optional-field extensions](./can_finalize_with_default.md). + +**`builder()` is an associated function.** There is no receiver, so it is `Person::builder()` rather than +anything called on a value. Starting from a value is [`IntoBuilder`](./into_builder.md). -**Field *names* are the whole interface for merging.** `build_from` matches by name, so renaming a field in one -struct silently stops it being copied — and the failure surfaces at `finalize_build`, not at the rename. +**A fieldless struct's builder is immediately finalizable**, since there is nothing to track. That is +legal and useless. ## Related constructs -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the partial type and every impl here. -- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this family with the field access and the - shape. -- [`MapType`](./map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers presence is encoded in. +- [`IntoBuilder`](./into_builder.md) — the other entry point, starting from a complete value. +- [`BuildField`](./build_field.md) — setting one absent field. +- [`TakeField`](./take_field.md) — the reverse, removing one present field. +- [`UpdateField`](./update_field.md) — the primitive both are built from. +- [`PartialData`](./partial_data.md) and [`FinalizeBuild`](./finalize_build.md) — naming the destination, + and reaching it. +- [`CanBuildFrom`](./can_build_from.md) — merging every shared field from another record. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the partial type and every impl + in the family. +- [`MapType`](./map_type.md) — the `IsPresent`/`IsNothing` markers presence is encoded in. - [`HasField`](./has_field.md) — how a set field is read back off a partial value. -- [`HasFields`](./has_fields.md) — the shape `build_from` walks, and what a merge source needs. -- [`CanUpcast`](./cast.md) — where `CanBuildFrom` and `build_from` are documented. -- [Optional fields](./optional_fields.md) — defaulted and optional finalization, layered on `UpdateField`. +- [Optional fields](./has_optional_builder.md) — defaulted and optional finalization. - [`ExtractField`](./extract_field.md) and [`FromVariant`](./from_variant.md) — the enum counterparts. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that run several builder - implementations and merge their outputs. The ideas behind it: @@ -314,17 +210,7 @@ The ideas behind it: ## Source - [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs) - — `HasBuilder`, `IntoBuilder` -- [`update_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/update_field.rs) - — `UpdateField`, the primitive -- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs) - — `BuildField`, `FinalizeBuild` -- [`take_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/take_field.rs) - — `TakeField` -- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs) - — `PartialData` -- [`build_from.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/build_from.rs) - — `CanBuildFrom` + — `HasBuilder` and `IntoBuilder` --- diff --git a/docs/reference/traits/has_extractor.md b/docs/reference/traits/has_extractor.md new file mode 100644 index 00000000..15d0dc7d --- /dev/null +++ b/docs/reference/traits/has_extractor.md @@ -0,0 +1,183 @@ +--- +sidebar_label: 'HasExtractor' +--- + +# `HasExtractor` + +Turning an enum into an extractor, and back. + +## What it's for + +[`ExtractField`](./extract_field.md) narrows an *extractor*, not an enum. `HasExtractor` is where one +comes from: + +```rust +pub trait HasExtractor { + type Extractor; + + fn to_extractor(self) -> Self::Extractor; + fn from_extractor(extractor: Self::Extractor) -> Self; +} +``` + +`to_extractor` **consumes** the value and yields an extractor whose payloads are owned, which is what a +chain needs when it will take a payload away. `from_extractor` reverses it, rebuilding the enum from an +extractor that was not narrowed — useful when a routine inspects a value and hands it back unchanged. + +It is the owning member of a group of three, and choosing between them is most of using the extractor +family: + +| | payloads come out as | the original | +|---|---|---| +| `HasExtractor` | owned | consumed | +| [`HasExtractorRef`](./has_extractor_ref.md) | `&T` | survives | +| [`HasExtractorMut`](./has_extractor_mut.md) | `&mut T` | survives, mutably borrowed | + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +`Extractor` names the partial companion enum at its all-possible configuration — every variant still +available. That is the type a chain starts from, and the type that appears in an error when a chain is +finalized too early. + +The impls come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md), also available +through [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) and +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). + +## Examples + +Starting a chain, which is what `to_extractor` is for: + +```rust +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width * rect.height + } + } +} +``` + +`from_extractor` is the less common half, and it round-trips an un-narrowed extractor: + +```rust +let extractor = shape.to_extractor(); +// ... inspect without extracting ... +let shape = Shape::from_extractor(extractor); +``` + +Note that this only works on an extractor still at the all-possible configuration. Once a variant has +been ruled out the type has changed, and there is no way back. + +## When to reach for it, and when not + +**Reach for `to_extractor` only when the chain will take payloads by value**, and prefer a borrowing +accessor otherwise — the weakest that works is the right one. + +- **[`HasExtractorRef`](./has_extractor_ref.md)** for a read-only operation over a value you do not own. + This is the common case, and requiring ownership where a borrow would do forces callers to clone or + give up their value. +- **[`HasExtractorMut`](./has_extractor_mut.md)** to change a payload in place. +- **`HasExtractor`** when the payload must be moved out — returned, stored, or handed on by value. +- **A `match`** when the enum is concrete. The family is for code that cannot name it. +- **The [dispatch combinators](../providers/dispatch_combinators.md)** rather than a hand-written chain, + since they derive it from the enum's variant list. + +## Under the hood + +:::note + +### Advanced + +This section shows what `Extractor` is. + +::: + +The derive generates a companion enum with one [`MapType`](./map_type.md) parameter per variant, and this +trait fixes the starting configuration to all-possible: + +```rust +pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { + Circle(<__F0__ as MapType>::Map), + Rectangle(<__F1__ as MapType>::Map), +} + +impl HasExtractor for Shape { + type Extractor = __PartialShape; // every variant still possible + // ... +} +``` + +Because `IsPresent::Map` is `T`, the all-possible companion holds exactly the enum's own payloads, so +`to_extractor` is a variant-for-variant move rather than a wrapping, and `from_extractor` is the same +move back. + +The companion also implements [`PartialData`](./partial_data.md), with `Target` naming the original enum +— which is how `from_extractor` knows what to rebuild, and the one trait the builder and extractor +families share directly. + +Narrowing from here is [`ExtractField`](./extract_field.md), and the chain ends at +[`FinalizeExtract`](./finalize_extract.md). + +## Gotchas + +**It consumes the value.** Reach for [`HasExtractorRef`](./has_extractor_ref.md) when the original must +survive. This is the commonest over-requirement in the family. + +**`from_extractor` only accepts an un-narrowed extractor.** Once a variant is ruled out the type is +different and there is no rebuild — which is correct, since the value may no longer be representable. + +**The extractor carries none of the enum's attributes.** The companion is generated without your derives, +so it is neither `Debug` nor `PartialEq` however the enum is derived. + +**`Extractor` is not the enum.** A signature that returns `Self::Extractor` is returning a companion +type, and naming it in a public API exposes a generated name. + +**Every variant must carry exactly one unnamed payload** for the derive to apply at all — the family's +one real restriction, covered on the +[derive's page](../derives/derive_extract_field.md). + +## Related constructs + +- [`ExtractField`](./extract_field.md) — what narrows the extractor this produces. +- [`HasExtractorRef`](./has_extractor_ref.md) and [`HasExtractorMut`](./has_extractor_mut.md) — the two + borrowing accessors. +- [`FinalizeExtract`](./finalize_extract.md) and + [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. +- [`FromVariant`](./from_variant.md) — constructing an enum from one named variant. +- [`PartialData`](./partial_data.md) — what names the enum a companion belongs to. +- [`MapType`](./map_type.md) — the `IsPresent`/`IsVoid` markers the companion is parameterized by. +- [`CanUpcast`](./can_upcast.md) and [`CanDowncast`](./can_downcast.md) — casts built on this recursion. +- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the companion and this + impl. +- [`HasBuilder`](./has_builder.md) — the struct analogue. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — partial variants and the extensible visitor + pattern. + +## Source + +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) + — `HasExtractor` and the rest of the family +- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs) + — `PartialData`, which the companions also implement + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/has_extractor_mut.md b/docs/reference/traits/has_extractor_mut.md new file mode 100644 index 00000000..24dd6d46 --- /dev/null +++ b/docs/reference/traits/has_extractor_mut.md @@ -0,0 +1,156 @@ +--- +sidebar_label: 'HasExtractorMut' +--- + +# `HasExtractorMut` + +Obtaining an extractor that can change a payload in place. + +## What it's for + +[`HasExtractorRef`](./has_extractor_ref.md) borrows an enum so its variants can be read without consuming +it. `HasExtractorMut` borrows it mutably, so a payload can be **changed in place**: + +```rust +pub trait HasExtractorMut { + type ExtractorMut<'a> + where + Self: 'a; + + fn extractor_mut(&mut self) -> Self::ExtractorMut<'_>; +} +``` + +Payloads come out as `&mut T`. The original survives, mutably borrowed for the duration, and the +narrowing works exactly as it does for the other two accessors — [`ExtractField`](./extract_field.md) +does not care how the payloads are held. + +It is the third of the group, and the one to reach for least often: + +| | payloads come out as | the original | +|---|---|---| +| [`HasExtractor`](./has_extractor.md) | owned | consumed | +| [`HasExtractorRef`](./has_extractor_ref.md) | `&T` | survives | +| `HasExtractorMut` | `&mut T` | survives, mutably borrowed | + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +`ExtractorMut<'a>` is a **generic associated type** with a `where Self: 'a` clause, and +`extractor_mut(&mut self)` returns one at the anonymous lifetime — so the call reads with no lifetime +written, and the borrow ends where the extractor is dropped. + +The impls come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md), alongside the owning +and shared-borrow accessors. + +## Examples + +Changing a payload without rebuilding the enum: + +```rust +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +if let Ok(circle) = shape + .extractor_mut() + .extract_field(PhantomData::) +{ + circle.radius = 5.0; +} + +// `shape` now holds the updated Circle +``` + +The payload arrives as `&mut Circle`, so the write lands in the original value. Written with +[`HasExtractor`](./has_extractor.md) instead, the same code would consume `shape` and have to rebuild it. + +## When to reach for it, and when not + +**Reach for it only when a payload must be mutated in place**, which is the narrowest of the three cases. + +- **[`HasExtractorRef`](./has_extractor_ref.md)** for a read. Requiring mutable access where a shared + borrow would do prevents a caller from holding any other reference to the value. +- **[`HasExtractor`](./has_extractor.md)** when the payload must be moved out. +- **`HasExtractorMut`** when the value stays where it is and one of its payloads changes. +- **A `match` on `&mut`** when the enum is concrete. `if let Shape::Circle(c) = &mut shape` does this in + a line, and the family is for code that cannot name the enum. +- **Consider returning a new value instead.** Much CGP code threads state through handler outputs rather + than mutating in place, which composes better with the [handler family](../components/handler.md). + +## Under the hood + +:::note + +### Advanced + +This section shows the marker that distinguishes it from the shared-borrow form. + +::: + +It uses the **same borrowed companion** as [`HasExtractorRef`](./has_extractor_ref.md#under-the-hood), +with the outer [`MapTypeRef`](./map_type_ref.md) marker fixed to `IsMut` rather than `IsRef`: + +```rust +// impl HasExtractorMut for Shape { +// type ExtractorMut<'a> = __PartialRefShape<'a, IsMut, IsPresent, IsPresent>; +// } +``` + +Since `IsMut::Map<'a, T>` is `&'a mut T`, every payload slot becomes a mutable reference while the +per-variant [`MapType`](./map_type.md) markers continue to track possibility. That is the whole +difference between the two borrowing accessors: one marker. + +There is no rebuild counterpart, and none is needed — the value was never taken apart, only borrowed. + +## Gotchas + +**It takes `&mut self`, so nothing else may borrow the value** for as long as the extractor lives. That is +ordinary borrow checking, but it surfaces as an error about the companion type, which reads as though the +machinery is at fault. + +**Payloads are `&mut T`, so a chain cannot move one out.** Taking ownership needs +[`HasExtractor`](./has_extractor.md). + +**There is no rebuild.** `from_extractor` belongs to the owning accessor alone. + +**The `where Self: 'a` clause propagates**, so a signature holding an `ExtractorMut<'a>` rarely elides +its lifetime cleanly. + +**The three extractors are three different types.** Code generic over "an extractor" must pick one or be +generic over the [`MapTypeRef`](./map_type_ref.md) marker too. + +**A remainder still carries none of the enum's attributes.** + +## Related constructs + +- [`HasExtractorRef`](./has_extractor_ref.md) — the shared-borrow accessor, and the one to prefer. +- [`HasExtractor`](./has_extractor.md) — the owning accessor, and where the group is compared. +- [`ExtractField`](./extract_field.md) — the narrowing, identical through a mutable borrow. +- [`FinalizeExtract`](./finalize_extract.md) and + [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. +- [`MapTypeRef`](./map_type_ref.md) — the `IsMut` marker this fixes. +- [`MapType`](./map_type.md) — the per-variant markers it composes with. +- [`HasFieldMut`](./has_field_mut.md) — the record side's mutable access. +- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the borrowed companion. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — matching a variant without consuming the + value. + +## Source + +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) + — `HasExtractorMut` and the rest of the family +- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) + — the `IsMut` marker + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/has_extractor_ref.md b/docs/reference/traits/has_extractor_ref.md new file mode 100644 index 00000000..36039f2e --- /dev/null +++ b/docs/reference/traits/has_extractor_ref.md @@ -0,0 +1,156 @@ +--- +sidebar_label: 'HasExtractorRef' +--- + +# `HasExtractorRef` + +Obtaining an extractor that borrows the value rather than consuming it. + +## What it's for + +[`HasExtractor`](./has_extractor.md) consumes an enum to produce an extractor with owned payloads. Code +that only *reads* a variant — checking it, measuring it, rendering it — should not have to give up the +value. `HasExtractorRef` is the borrowing accessor: + +```rust +pub trait HasExtractorRef { + type ExtractorRef<'a> + where + Self: 'a; + + fn extractor_ref(&self) -> Self::ExtractorRef<'_>; +} +``` + +Payloads come out as shared references and the original survives. **The narrowing works identically** — +[`ExtractField`](./extract_field.md) rules variants out of a borrowed extractor exactly as it does an +owned one, and the chain ends the same way. + +It is the weakest of the three accessors, so prefer it wherever it suffices. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +`ExtractorRef<'a>` is a **generic associated type** with a `where Self: 'a` clause, so the borrowed +extractor cannot outlive the value it came from. `extractor_ref(&self)` takes a shared borrow and returns +one at the anonymous lifetime, which is why the call reads with no lifetime written. + +The impls come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md), alongside the owning +and mutable accessors. + +## Examples + +Reading through a borrow leaves the value intact: + +```rust +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +let radius = shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok(); + +// `shape` is still usable here +``` + +The payload arrives as `&Circle`, so `circle.radius` reads through the borrow and nothing is moved. A +full chain narrows the same way, with each remainder also borrowing. + +## When to reach for it, and when not + +**Reach for it whenever the value must survive**, which is most read-only code over an enum. + +- **`HasExtractorRef`** for a read-only operation. Prefer it over consuming, since requiring ownership + narrows what a caller can pass for no benefit. +- **[`HasExtractorMut`](./has_extractor_mut.md)** to change a payload in place. +- **[`HasExtractor`](./has_extractor.md)** only when the payload must be moved out. +- **A `match`** when the enum is concrete. This family is for code that cannot name it. +- **[`ToFieldsRef`](./to_fields_ref.md)** when what you want is the value's borrowed *shape* rather than + a narrowing chain — the same borrow-rather-than-consume idea, applied to the whole-shape view. + +## Under the hood + +:::note + +### Advanced + +This section shows how the borrowed companion is built from the two marker families. + +::: + +The borrowed accessor uses the **same partial enum** as the owning one, with an extra +[`MapTypeRef`](./map_type_ref.md) parameter fixed to `IsRef`: + +```rust +// conceptually +// +// pub enum __PartialRefShape<'a, R: MapTypeRef, F0: MapType, F1: MapType> { +// Circle(F0::Map>), +// Rectangle(F1::Map>), +// } +// +// impl HasExtractorRef for Shape { +// type ExtractorRef<'a> = __PartialRefShape<'a, IsRef, IsPresent, IsPresent>; +// } +``` + +Read the nesting outward: the [`MapTypeRef`](./map_type_ref.md) marker decides *how* a payload is held — +`IsRef::Map<'a, T>` is `&'a T` — and the per-variant [`MapType`](./map_type.md) markers decide *whether* +it is still possible. The two axes are independent, which is precisely why narrowing behaves the same +through a borrow as through an owned value. + +There is no `from_extractor` counterpart here: a borrowed extractor cannot rebuild an owned enum, and the +original is still there anyway. + +## Gotchas + +**There is no rebuild.** [`HasExtractor`](./has_extractor.md)'s `from_extractor` has no borrowing +equivalent, which is rarely a problem since the value was never consumed. + +**Payloads are `&T`, so a chain cannot move one out.** A routine that must take ownership of a payload +needs [`HasExtractor`](./has_extractor.md). + +**The `where Self: 'a` clause propagates.** A signature that stores or returns `ExtractorRef<'a>` usually +has to spell the lifetime out rather than elide it. + +**A remainder still carries none of the enum's attributes**, so a `Result` holding one is neither `Debug` +nor `PartialEq`. + +**The borrowed and owned extractors are different types.** Code generic over "an extractor" has to pick +one, or be generic over the [`MapTypeRef`](./map_type_ref.md) marker as well. + +## Related constructs + +- [`HasExtractor`](./has_extractor.md) — the owning accessor, and where the group is compared. +- [`HasExtractorMut`](./has_extractor_mut.md) — the mutable accessor. +- [`ExtractField`](./extract_field.md) — the narrowing, identical through a borrow. +- [`FinalizeExtract`](./finalize_extract.md) and + [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. +- [`MapTypeRef`](./map_type_ref.md) — the `IsRef` marker this fixes. +- [`MapType`](./map_type.md) — the per-variant markers it composes with. +- [`ToFieldsRef`](./to_fields_ref.md) — the record side's borrow-rather-than-consume view. +- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the borrowed companion. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — matching a variant without consuming the + value. + +## Source + +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) + — `HasExtractorRef` and the rest of the family +- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) + — the `IsRef` marker + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/has_field.md index 85a1ba6e..2cb14a69 100644 --- a/docs/reference/traits/has_field.md +++ b/docs/reference/traits/has_field.md @@ -4,40 +4,35 @@ sidebar_label: 'HasField' # `HasField` -Tag-keyed field access, with `HasFieldMut` and the provider-side `FieldGetter`. +Reading a field by a type-level name, from a context you cannot name. ## What it's for -An implementation written against a **context** — the type the capability runs against, which supplies the -values it needs as its fields — is generic over that context and cannot name its concrete type. So it cannot -write `self.name`. Yet reading a value out of the context is the commonest thing such an implementation does. +An implementation written against a **context** — the type the capability runs against, which supplies +the values it needs as its fields — is generic over that context and cannot name its concrete type. So it +cannot write `self.name`. Yet reading a value out of the context is the commonest thing such an +implementation does. -`HasField` is the trait that closes the gap. The field's *name* becomes a type, and the implementation -asks for it as an ordinary trait bound: +`HasField` closes the gap. The field's *name* becomes a type, and the implementation asks for it as +an ordinary trait bound: ```rust Self: HasField ``` -Any context with a matching field satisfies that bound. Nothing is compared by string at runtime — -[`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler resolves which field is meant and the read -compiles to a direct field access. +Any context with a matching field satisfies that bound. Nothing is compared by string at run time — +[`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler resolves which field is meant and the +read compiles to a direct field access. This is the foundation the whole ergonomic surface stands on. An [`#[implicit]`](../attributes/implicit.md) argument, a [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method, and a [`UseField`](../providers/use_field.md) wiring entry all generate this bound from a name you -already wrote. **You will read `HasField` far more often than you write it**, and the impls themselves come -from [`#[derive(HasField)]`](../derives/derive_has_field.md). +already wrote. **You will read `HasField` far more often than you write it**, and the impls come from +[`#[derive(HasField)]`](../derives/derive_has_field.md). ## Using it -Everything on this page except `MapField` and `FieldMapper` is in the prelude, so `use cgp::prelude::*;` is -enough for the common cases. The family divides into a consumer side you bound against and a provider side -that gets wired. - -### The consumer side - -`HasField` carries the field's type as an associated `Value` and hands back a reference: +**It is in the prelude**, so `use cgp::prelude::*;` is enough. ```rust pub trait HasField { @@ -47,72 +42,24 @@ pub trait HasField { } ``` -The `PhantomData` argument carries nothing. It exists so a call site can say *which* field it means when -several impls are in scope, which is why reads are written `self.get_field(PhantomData::)`. +The `PhantomData` argument carries nothing. It exists so a call site can say *which* field it means +when several impls are in scope, which is why reads are written +`self.get_field(PhantomData::)`. A named field is keyed by [`Symbol!("field_name")`](../macros/symbol.md); a tuple field by [`Index`](../types/index.md). -`HasFieldMut` is the mutable extension, a supertrait of `HasField`: - -```rust -pub trait HasFieldMut: HasField { - fn get_field_mut(&mut self, tag: PhantomData) -> &mut Self::Value; -} -``` - -Both carry diagnostic notes pointing a reader at -[`#[derive(HasField)]`](../derives/derive_has_field.md) when the bound is unsatisfied, so a missing field reads -as a missing derive rather than an opaque trait failure. - -### The provider side - -Field access can be *wired* rather than only implemented on the context, which needs the provider-trait shape: -the context as an explicit argument instead of `&self`. - -```rust -pub trait FieldGetter { - type Value; - - fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value; -} - -pub trait MutFieldGetter: FieldGetter { - fn get_field_mut(context: &mut Context, tag: PhantomData) -> &mut Self::Value; -} -``` +`Value` is an associated type, so it can be pinned or left open: `HasField` alone accepts +a field of any type, while adding `Value = String` requires that type. -This is the ordinary consumer/provider duality: you *bound* against `HasField`, and you *wire* -`FieldGetter`. [`UseField`](../providers/use_field.md) is the provider that implements it by reading a named -field, and it is what [`#[cgp_getter]`](../macros/cgp_getter.md) targets. +The trait carries a diagnostic note pointing a reader at +[`#[derive(HasField)]`](../derives/derive_has_field.md) when the bound is unsatisfied, so a missing field +reads as a missing derive rather than an opaque trait failure. -### The lifetime helpers - -`MapField` and `FieldMapper` are the two members **not** in the prelude — import them from -`cgp::core::field::traits`. They exist for one reason, and it is a lifetime-inference problem rather than a -capability: chaining `context.get_field().get_field()` would force the intermediate `Value` to be `'static`. -Passing a closure instead lets the compiler infer the right lifetime: - -```rust -pub trait MapField: HasField { - fn map_field( - &self, - _tag: PhantomData, - mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, - ) -> &T; -} - -pub trait FieldMapper: FieldGetter { - fn map_field( - context: &Context, - _tag: PhantomData, - mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, - ) -> &T; -} -``` - -You will not normally call either. [`ChainGetters`](../providers/chain_getters.md) is what uses `map_field`, -which is how a getter reaches a field on a nested context. +**Four neighbours complete the picture**, each on its own page: [`HasFieldMut`](./has_field_mut.md) for +mutable access, [`FieldGetter`](./field_getter.md) for the provider-side mirror that gets wired, and +[`MapField`](./map_field.md) with [`FieldMapper`](./field_mapper.md) for the lifetime-safe form nested +accessors use. ## Examples @@ -148,7 +95,8 @@ delegate_components! { } ``` -`Person` derives the access, so it satisfies exactly the bound `GreetHello` requires and the wiring compiles. +`Person` derives the access, so it satisfies exactly the bound `GreetHello` requires and the wiring +compiles. **Value context, self-targeted** — the wired type is the data the capability runs against. **Written idiomatically, none of that bound is visible.** The same read is an [`#[implicit]`](../attributes/implicit.md) argument: @@ -162,8 +110,8 @@ impl Greeter { } ``` -which generates the identical bound and the identical read. The explicit form above is what you meet in an -error message or an expansion, not what you type. +which generates the identical bound and the identical read. The explicit form above is what you meet in +an error message or an expansion, not what you type. Field access also passes through smart pointers with no extra work, because the trait carries a `Deref` forwarding impl: @@ -180,21 +128,22 @@ assert_eq!(boxed.get_field(PhantomData::), "Alice"); ordering is settled and worth following. - **Use an [`#[implicit]`](../attributes/implicit.md) argument by default.** It reads a field of the - implementation's own context as a plain parameter, generating this bound for you. It covers the common case, - including a field several implementations each read. + implementation's own context as a plain parameter, generating this bound for you. It covers the common + case, including a field several implementations each read. - **Use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md)** when the read must be a *named* capability, - when the field lives on a type other than the context, or when the getter should carry a type inferred from - the field — the three cases an implicit argument cannot reach. -- **Use [`#[cgp_getter]`](../macros/cgp_getter.md) with [`UseField`](../providers/use_field.md)** only when a - context needs to choose *which* field the getter reads. That is the advanced case and costs a wiring line - per context. + when the field lives on a type other than the context, or when the getter should carry a type inferred + from the field — the three cases an implicit argument cannot reach. +- **Use [`#[cgp_getter]`](../macros/cgp_getter.md) with [`UseField`](../providers/use_field.md)** only + when a context needs to choose *which* field the getter reads. That is the advanced case and costs a + wiring line per context. - **Write the bound by hand** when none of those fit — a bound on a type that is not `Self`, say. It is an - ordinary trait bound, and `Value = T` pins the field's type. + ordinary trait bound. -Two neighbours are easy to confuse with it. [`HasFields`](./has_fields.md) — plural — is the whole-shape view, -for code that must process *every* field rather than one named one; the two are complementary and often -derived together. And `FieldGetter` is not an alternative to `HasField` but its provider-side mirror: you do -not choose between them, you bound against one and wire the other. +Three neighbours are easy to confuse with it. [`HasFields`](./has_fields.md) — plural — is the +whole-shape view, for code that must process *every* field rather than one named one; the two are +complementary and often derived together. [`HasFieldMut`](./has_field_mut.md) is the same access with +mutation, not an alternative. And [`FieldGetter`](./field_getter.md) is not an alternative either but the +provider-side mirror: you bound against `HasField` and wire `FieldGetter`. ## Under the hood @@ -202,25 +151,25 @@ not choose between them, you bound against one and wire the other. ### Advanced -This section shows the blanket impls that make the access compose. You do not need it to read a field, but a -missing field is reported against the generated bound with the tag fully expanded, so recognizing the shape -makes that error legible. +This section shows the blanket impls that make the access compose. You do not need it to read a field, +but a missing field is reported against the generated bound with the tag fully expanded, so recognizing +the shape makes that error legible. ::: The per-field impls come almost entirely from -[`#[derive(HasField)]`](../derives/derive_has_field.md). What the trait module itself supplies is the blanket -impls that let the access compose, and there are four worth knowing. +[`#[derive(HasField)]`](../derives/derive_has_field.md). What the trait module itself supplies is the +blanket impls that let the access compose, and two of them belong to this trait. **Smart-pointer forwarding.** `HasField` is implemented for any type whose -[`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) target implements it, so a `Box` or a -newtype resolves a read to the inner struct. `HasFieldMut` carries the analogous `DerefMut` impl, with the -target additionally bounded `'static`. Both are marked so the compiler does **not** suggest them in a -diagnostic — which is what keeps a missing-field error pointed at the struct that lacks the field rather than -at the pointer. +[`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) target implements it, so a `Box` or +a newtype resolves a read to the inner struct. It is marked so the compiler does **not** suggest it in a +diagnostic — which is what keeps a missing-field error pointed at the struct that lacks the field rather +than at the pointer. -**`UseContext` as a field getter.** The provider side connects to wiring through one impl: `UseContext` -implements `FieldGetter` for any context that already has the field, delegating straight through. +**`UseContext` as a field getter.** The provider side connects to wiring through one impl: +[`UseContext`](../providers/use_context.md) implements [`FieldGetter`](./field_getter.md) for any context +that already has the field, delegating straight through. ```rust impl FieldGetter for UseContext @@ -235,64 +184,55 @@ where } ``` -**The lifetime helpers are free.** `MapField` is a blanket impl for every `HasField` whose tag is `'static`, -and `FieldMapper` for every `FieldGetter` with the getter and tag `'static`. So every getter gains -`map_field` without anyone implementing it, which is what [`ChainGetters`](../providers/chain_getters.md) -relies on. +The remaining blanket impls belong to the neighbours: [`HasFieldMut`](./has_field_mut.md) carries the +`DerefMut` forwarding, and [`MapField`](./map_field.md) is free for every `HasField` whose tag is +`'static`. ## Gotchas **Two spellings of a name are unrelated types.** `Symbol!("first_name")` and `Symbol!("firstName")` have -nothing to do with each other, and a mismatch reports as a missing `HasField` bound rather than as a typo. -This is the usual cause of a read that "should" work. - -**`MapField` and `FieldMapper` are not in the prelude.** Import them from `cgp::core::field::traits`. Every -other trait on this page is in the prelude. +nothing to do with each other, and a mismatch reports as a missing `HasField` bound rather than as a +typo. This is the usual cause of a read that "should" work. -**A tuple field is keyed by [`Index`](../types/index.md), never by a `Symbol!` of the number.** `Index<0>` -and `Symbol!("0")` are different types. +**A tuple field is keyed by [`Index`](../types/index.md), never by a `Symbol!` of the number.** +`Index<0>` and `Symbol!("0")` are different types. -**The mutable accessor is not separately opt-in.** `#[derive(HasField)]` always emits `HasFieldMut` beside -`HasField`, so there is no derive-level way to make a field read-only. Restricting mutation is a matter of -what the implementations declare. +**`Value` can be pinned or left open.** Omitting `Value = T` when you meant to pin it produces an +inference failure further along rather than at the bound. -**`Value` is an associated type, so it can be pinned or left open.** Writing -`HasField` alone accepts a field of any type; adding `Value = String` requires that type. -Omitting it when you meant to pin it produces an inference failure further along rather than at the bound. +**The `PhantomData` argument is required and carries the tag.** `self.get_field(PhantomData)` works only +where inference can determine the tag from context; at an ambiguous site write +`PhantomData::`. -**The `PhantomData` argument is required and carries the tag.** `self.get_field(PhantomData)` works only where -inference can determine the tag from context; at an ambiguous site write `PhantomData::`. +**It returns a reference, always.** There is no owning read; cloning is the caller's business, and an +[`#[implicit]`](../attributes/implicit.md) argument is what inserts a `.clone()` for you when the +parameter is owned. ## Related constructs - [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates the per-field impls; what a context writes. +- [`HasFieldMut`](./has_field_mut.md) — the mutable extension. +- [`FieldGetter`](./field_getter.md) — the provider-side mirror that gets wired. +- [`MapField`](./map_field.md) — the lifetime-safe form for reaching into a nested value. - [`HasFields`](./has_fields.md) — the plural, whole-shape counterpart. - [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that key a field. - [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to read a field. -- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../macros/cgp_getter.md) — getter - traits over the same access. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../macros/cgp_getter.md) — + getter traits over the same access. - [`UseField`](../providers/use_field.md) — the provider-side implementation of `FieldGetter`. -- [`ChainGetters`](../providers/chain_getters.md) — composes getters through `map_field` to reach a nested - field. - [`HasBuilder`](./has_builder.md) — where `HasField` reappears on a partial record, gated on presence. The ideas behind it: -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on the - implementation rather than the interface. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on + the implementation rather than the interface. - [Implicit arguments](/docs/concepts/implicit-arguments) — the ergonomic surface built on this trait. ## Source - [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) — `HasField`, `FieldGetter`, the `Deref` forwarding, and the `UseContext` impl -- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs) - — `HasFieldMut`, `MutFieldGetter`, the `DerefMut` forwarding -- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs) - — `MapField` and `FieldMapper` -- [`use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs) - — the `UseField` provider --- diff --git a/docs/reference/traits/has_field_mut.md b/docs/reference/traits/has_field_mut.md new file mode 100644 index 00000000..2f3f35f0 --- /dev/null +++ b/docs/reference/traits/has_field_mut.md @@ -0,0 +1,167 @@ +--- +sidebar_label: 'HasFieldMut' +--- + +# `HasFieldMut` + +Mutable tag-keyed field access. + +## What it's for + +[`HasField`](./has_field.md) lets an implementation read a field of a context it cannot name, by keying +on the field's name as a type. `HasFieldMut` is the same access with mutation: it hands back a `&mut` +rather than a `&`, so an implementation can change a value in place. + +```rust +pub trait HasFieldMut: HasField { + fn get_field_mut(&mut self, tag: PhantomData) -> &mut Self::Value; +} +``` + +It is a **supertrait extension** rather than an alternative: `HasFieldMut` requires +`HasField`, and the field's type comes from that supertrait's `Value`. So bounding on the mutable +form gives you the read as well. + +**You do not opt into it.** [`#[derive(HasField)]`](../derives/derive_has_field.md) always emits +`HasFieldMut` beside `HasField`, so every derived field is mutably accessible and there is no +derive-level way to make one read-only. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +The call reads like its immutable sibling, with `PhantomData` naming the field: + +```rust +*context.get_field_mut(PhantomData::) += 1; +``` + +An implementation that mutates declares the bound on `Self` the same way it declares a read, and needs +`&mut self` on the method: + +```rust +Self: HasFieldMut +``` + +Like its supertrait it carries a diagnostic note pointing at +[`#[derive(HasField)]`](../derives/derive_has_field.md), so an unsatisfied bound reads as a missing +derive. + +## Examples + +An implementation that updates a counter on its context: + +```rust +use cgp::prelude::*; + +#[cgp_component(Counter)] +pub trait CanCount { + fn count(&mut self); +} + +#[cgp_impl(new IncrementCounter)] +impl Counter +where + Self: HasFieldMut, +{ + fn count(&mut self) { + *self.get_field_mut(PhantomData::) += 1; + } +} + +#[derive(HasField)] +pub struct App { + pub counter: u64, +} + +delegate_components! { + App { + CounterComponent: IncrementCounter, + } +} +``` + +**Environmental context, self-targeted** — `App` stands for the application and carries the wiring. + +Mutable access passes through a smart pointer too, via a `DerefMut` forwarding impl, so a +`Box` resolves the write to the inner struct. + +## When to reach for it, and when not + +**Bound on it only when the implementation genuinely writes**, and prefer the read-only bound otherwise. +Requiring mutation where none happens narrows what a caller can pass for no benefit — a context behind a +shared reference satisfies [`HasField`](./has_field.md) and not this. + +- **Use [`HasField`](./has_field.md)** whenever the value is only read. This is the overwhelmingly common + case. +- **Use an [`#[implicit]`](../attributes/implicit.md) argument** for a read, since it generates the + immutable bound for you and reads like an ordinary parameter. Implicit arguments cover mutable access + too, under the access rules on that page, which is the idiomatic route before reaching for this trait + by hand. +- **Reach for [`MutFieldGetter`](./mut_field_getter.md)** when the mutation must be *wired* rather than + bounded — the provider-side mirror of this trait. +- **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable and + threads state through handler outputs instead, which composes better with the + [handler family](../components/handler.md). + +## Under the hood + +:::note + +### Advanced + +One blanket impl belongs to this trait, and it mirrors its supertrait's. + +::: + +`HasFieldMut` is implemented for any type whose +[`DerefMut`](https://doc.rust-lang.org/std/ops/trait.DerefMut.html) target implements it, with the target +additionally bounded `'static`. That extra bound is the one asymmetry with +[`HasField`](./has_field.md#under-the-hood)'s `Deref` forwarding, and it is why a borrowed context inside +a smart pointer sometimes resolves the read and not the write. + +Like the immutable forwarding, it is marked so the compiler does **not** suggest it in a diagnostic, +which keeps a missing-field error pointed at the struct that lacks the field rather than at the pointer. + +The per-field impls themselves come from [`#[derive(HasField)]`](../derives/derive_has_field.md), one +`HasFieldMut` beside each `HasField`. + +## Gotchas + +**It is not separately opt-in.** The derive always emits it, so there is no way to expose a field as +read-only through the derive. Restricting mutation is a matter of what the implementations declare. + +**The `DerefMut` forwarding requires `'static` on the target**, where the `Deref` forwarding does not. A +context holding a borrowed value can therefore satisfy the read and not the write, and the error names +the lifetime rather than the field. + +**Bounding on it implies the read.** `Self: HasFieldMut` already gives `get_field`, so adding +`HasField` alongside is redundant. + +**`Value` lives on the supertrait.** Pin it as `HasFieldMut` — the associated +type is inherited, not redeclared. + +**A tuple field is keyed by [`Index`](../types/index.md)**, exactly as for the immutable form. + +## Related constructs + +- [`HasField`](./has_field.md) — the supertrait, and where the tag-keyed access is explained in full. +- [`MutFieldGetter`](./mut_field_getter.md) — the provider-side mirror of this trait. +- [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates both impls per field. +- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to reach a field, including mutably. +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that key a field. +- [`UseField`](../providers/use_field.md) — the provider that implements the wired form. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on + the implementation rather than the interface. + +## Source + +- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs) + — `HasFieldMut`, `MutFieldGetter`, and the `DerefMut` forwarding + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/has_fields.md index 7331a667..2fc0f77b 100644 --- a/docs/reference/traits/has_fields.md +++ b/docs/reference/traits/has_fields.md @@ -4,17 +4,26 @@ sidebar_label: 'HasFields' # `HasFields` -The whole-shape field representation and its conversions. +A type's whole shape, as a single type. ## What it's for -Some code needs one field of a type. Other code needs the *shape* — every field, its name, and its type — so -it can walk them: a serializer, a validator, a builder that merges two structs, a dispatcher that routes an -enum to a handler per variant. None of those can be written one field at a time, and none can name the -concrete type either. +Some code needs one field of a type. Other code needs the *shape* — every field, its name, and its type +— so it can walk them: a serializer, a validator, a builder that merges two structs, a dispatcher that +routes an enum to a handler per variant. None of those can be written one field at a time, and none can +name the concrete type either. -`HasFields` gives a type that shape as a single associated type. Where [`HasField`](./has_field.md) — -singular — answers *"give me this field"*, `HasFields` answers *"describe all of them at once"*: +`HasFields` gives a type that shape as a single associated type. Where +[`HasField`](./has_field.md) — singular — answers *"give me this field"*, `HasFields` answers +*"describe all of them at once"*: + +```rust +pub trait HasFields { + type Fields; +} +``` + +For `struct Person { name: String, age: u8 }` that is: ```rust type Fields = Product![ @@ -23,66 +32,28 @@ type Fields = Product![ ]; ``` -That is the struct written as a type: a [`Product!`](../macros/product.md) list with one -[`Field`](../types/field.md) entry per field, each pairing a value type with its type-level name. For an enum -it is a [`Sum!`](../macros/sum.md) instead — the same idea for a choice rather than a combination. - -Four companion traits turn that description into a two-way door. `HasFieldsRef` names the borrowed shape, and -`ToFields`, `FromFields`, and `ToFieldsRef` convert between a concrete value and it — so generic code can take -a value apart, work on the anonymous form, and put a concrete value back together. +The struct written as a type: a [`Product!`](../macros/product.md) list with one +[`Field`](../types/field.md) entry per field, each pairing a value type with its type-level name. For an +enum it is a [`Sum!`](../macros/sum.md) instead — the same idea for a choice rather than a combination. **The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md).** What you write is the derive; what you bound against is the trait. ## Using it -All five traits are in the prelude. Two name a shape and three convert to or from it. - -### The shape traits - -```rust -pub trait HasFields { - type Fields; -} - -pub trait HasFieldsRef { - type FieldsRef<'a> - where - Self: 'a; -} -``` - -`Fields` is the owned shape and `FieldsRef<'a>` the same shape with each value borrowed for `'a`. Both are -associated types and nothing else — there is no method, because describing a type is not an operation. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method, because describing a +type is not an operation — `Fields` is the whole trait. The shape's construction follows one rule everywhere: a named field or variant is keyed by -[`Symbol!`](../macros/symbol.md), a positional field by [`Index`](../types/index.md), a struct becomes a -`Cons`/`Nil` product, and an enum becomes an `Either`/`Void` sum. A single-field tuple struct is the one +[`Symbol!`](../macros/symbol.md), a positional field by [`Index`](../types/index.md), a struct becomes +a `Cons`/`Nil` product, and an enum becomes an `Either`/`Void` sum. A single-field tuple struct is the one special case — its `Fields` is the inner type directly rather than a one-element product — and the [derive's page](../derives/derive_has_fields.md) covers that and the other shapes in full. -### The conversion traits - -Each supertraits one of the two shape traits and adds a single method: - -```rust -pub trait ToFields: HasFields { - fn to_fields(self) -> Self::Fields; -} - -pub trait FromFields: HasFields { - fn from_fields(fields: Self::Fields) -> Self; -} - -pub trait ToFieldsRef: HasFieldsRef { - fn to_fields_ref<'a>(&'a self) -> Self::FieldsRef<'a> - where - Self: 'a; -} -``` - -`to_fields` **consumes** the value to produce the owned shape, `from_fields` consumes the shape to rebuild the -value, and `to_fields_ref` **borrows** — which is the one to reach for when the original value must survive. +**Four companions turn the description into a two-way door**, each on its own page: +[`HasFieldsRef`](./has_fields_ref.md) names the borrowed shape, and [`ToFields`](./to_fields.md), +[`FromFields`](./from_fields.md), and [`ToFieldsRef`](./to_fields_ref.md) convert between a concrete +value and it. This trait names the shape; those move values through it. ### Bounding on the shape @@ -90,21 +61,22 @@ The point of all this is a bound. Generic code writes `T: HasFields` and recurse applies to any type that derives the shape — including one declared in another crate: ```rust -fn shape_of(value: T) -> T::Fields +fn describe() -> &'static str where - T: HasFields + ToFields, + T: HasFields, { - value.to_fields() + // recurse over T::Fields + todo!() } ``` -Which of the five to require depends on what the code does: `HasFields` alone to *name* the shape, -`ToFields`/`FromFields` to move owned values through it, `ToFieldsRef` to read without consuming. +Require this trait alone when the code only *names* the shape; require one of the conversions when values +have to move through it. ## Examples -Deriving it alongside [`HasField`](./has_field.md) is the common pairing, giving one struct both indexed and -structural access: +Deriving it alongside [`HasField`](./has_field.md) is the common pairing, giving one struct both indexed +and structural access: ```rust use cgp::prelude::*; @@ -116,27 +88,10 @@ pub struct Config { } ``` -`Config::Fields` is now `Product![Field, Field]`, and a value -round-trips through it: - -```rust -let config = Config { host: "localhost".to_owned(), port: 8080 }; - -let fields = config.clone().to_fields(); // Config -> the product -let config_again = Config::from_fields(fields); // the product -> Config - -assert_eq!(config, config_again); -``` - -The borrowing form leaves the value intact, which is what read-only generic code uses: +`Config::Fields` is now `Product![Field, Field]`, which is +what a generic routine recurses over. -```rust -let fields_ref = config.to_fields_ref(); - -assert_eq!(fields_ref.0.value, &"localhost".to_owned()); -``` - -An enum's shape is a sum rather than a product, and the same conversions apply: +An enum's shape is a sum rather than a product: ```rust #[derive(HasFields)] @@ -148,27 +103,28 @@ pub enum Shape { giving `Sum![Field, Field]`. +**`HasFields` is the one member of the extensible-data family that accepts every variant shape** — unit, +tuple, multi-field, and struct-style — because it only *describes* a variant rather than deconstructing +it. The derives that take an enum apart need exactly one unnamed payload per variant; this one does not. + ## When to reach for it, and when not **Bound on `HasFields` when code must process a type's whole shape; bound on -[`HasField`](./has_field.md) when it needs one named field.** That is the entire distinction, and the two are -complementary rather than ranked — most types that need both derive both in one `#[derive(...)]`. - -The finer question is which of the five to require, and being precise pays because each one narrows what a -caller must supply. - -- **`HasFields` alone** when the code only names the shape — a `where` clause, an associated-type projection, - a type-level computation like those in [`AppendProduct`](./product_ops.md). -- **`ToFields` and `FromFields`** when values move through the shape in both directions, which is what a - structural conversion needs. -- **`ToFieldsRef`** when the value must not be consumed. Requiring `ToFields` where a borrow would do forces - callers to clone. - -Two things this is not. It is **not runtime reflection**: a type has a shape only because it opted in with a -derive, there is nothing to query at run time, and the shape is a type rather than data. What that buys is -static checking and no runtime cost; what it costs is that a foreign type you cannot patch has no shape at -all. And it is **not the whole extensible-data story** — the shape describes a type, while building one up -field by field or taking one apart variant by variant is the +[`HasField`](./has_field.md) when it needs one named field.** That is the entire distinction, and the two +are complementary rather than ranked — most types that need both derive both in one `#[derive(...)]`. + +- **`HasFields` alone** when the code only names the shape — a `where` clause, an associated-type + projection, a type-level computation like [`AppendProduct`](./append_product.md). +- **[`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md)** when values move through the + shape in both directions. +- **[`ToFieldsRef`](./to_fields_ref.md)** when the value must not be consumed. Requiring `ToFields` where + a borrow would do forces callers to clone. + +Two things this is not. It is **not runtime reflection**: a type has a shape only because it opted in +with a derive, there is nothing to query at run time, and the shape is a type rather than data. What that +buys is static checking and no runtime cost; what it costs is that a foreign type you cannot patch has no +shape at all. And it is **not the whole extensible-data story** — the shape describes a type, while +building one up field by field or taking one apart variant by variant is the [builder](./has_builder.md) and [extractor](./extract_field.md) families, bundled with this one by [`#[derive(CgpData)]`](../derives/derive_cgp_data.md). @@ -178,15 +134,15 @@ field by field or taking one apart variant by variant is the ### Advanced -This section shows what the shape expands to. You do not need it to bound on the trait, but the `Fields` type -appears verbatim in compiler errors about structural code, so reading one makes those errors legible. -`cargo cgp expand` prints it resugared for your own code. +This section shows what the shape expands to. You do not need it to bound on the trait, but the `Fields` +type appears verbatim in compiler errors about structural code, so reading one makes those errors +legible. `cargo cgp expand` prints it resugared for your own code. ::: -The trait module defines only the bare trait shapes; all five impls come from -[`#[derive(HasFields)]`](../derives/derive_has_fields.md). The load-bearing part is what the derive puts in -`Fields`, and the sugar hides one level of structure: +The trait module defines only the bare trait; every impl comes from +[`#[derive(HasFields)]`](../derives/derive_has_fields.md). The load-bearing part is what the derive puts +in `Fields`, and the sugar hides one level of structure: ```rust impl HasFields for Person { @@ -197,81 +153,54 @@ impl HasFields for Person { } ``` -`Product![A, B]` is `Cons>`, so the conversions build and match a `Cons` chain: +`Product![A, B]` is `Cons>`, so a `Fields` type in an error message is a `Cons` chain +rather than the sugar — the [type-level spines](../types/type_level_spines.md) page covers reading it. -```rust -impl ToFields for Person { - fn to_fields(self) -> Self::Fields { - Cons(self.name.into(), Cons(self.age.into(), Nil)) - } -} +An enum's shape is the dual: an `Either` chain terminated by `Void` rather than a `Cons` chain terminated +by `Nil`, with each arm tagged by the variant name and carrying that variant's own fields as a nested +product. -impl FromFields for Person { - fn from_fields(Cons(name, Cons(age, Nil)): Self::Fields) -> Self { - Self { name: name.value, age: age.value } - } -} -``` - -That `Cons` spine is what an error message prints, and the -[type-level spines](../types/type_level_spines.md) page covers reading it. - -The borrowed shape uses a reserved lifetime name, `'__a`, so it cannot collide with a lifetime of yours: - -```rust -impl HasFieldsRef for Person { - type FieldsRef<'__a> = Product![ - Field, - Field, - ] - where - Self: '__a; -} -``` - -An enum's shape is the dual — an `Either` chain terminated by `Void` rather than a `Cons` chain terminated by -`Nil` — with each arm tagged by the variant name and carrying that variant's own fields as a nested product. -The two conversions match each concrete variant onto its arm and back. - -`from_fields` and `to_fields` round-trip through the identical `Fields` type, so generic code can decompose, -transform, and rebuild with the shapes lining up by construction rather than by check. +Because a shape is a type rather than a value, nothing about this costs anything at run time. It exists +to give the trait solver something to recurse over. ## Gotchas -**`HasFields` and [`HasField`](./has_field.md) differ by one letter and do not overlap.** The plural is the -whole shape and takes structs and enums; the singular is per-field access and takes only structs. Their -derives are likewise distinct. - -**`to_fields` consumes the value.** Reach for `to_fields_ref` when you need to keep it. This is the commonest -surprise, because the two read alike. +**`HasFields` and [`HasField`](./has_field.md) differ by one letter and do not overlap.** The plural is +the whole shape and takes structs and enums; the singular is per-field access and takes only structs. +Their derives are likewise distinct. **A newtype's shape is the inner type, not a one-element product.** `struct Wrapper(String)` has `Fields = String`. Generic code written against a `Cons` chain will not match it — the [derive's page](../derives/derive_has_fields.md) has the rule and the other shapes. -**Field order is declaration order and is part of the type.** Two structs with the same names in different -orders have different `Fields` types. Name-driven conversions cope; code written against a literal `Cons` -chain does not. - -**The borrowed shape layers borrows rather than collapsing them.** A field already of type `&'a Name` appears -as `&'__a &'a Name` in `FieldsRef`, which is correct and occasionally surprising in an error. +**Field order is declaration order and is part of the type.** Two structs with the same names in +different orders have different `Fields` types. Name-driven conversions cope; code written against a +literal `Cons` chain does not. **Two enum variant names are reserved.** A variant called `Fields` or `FieldsRef` collides with these -associated types and the derive fails; the [derive's page](../derives/derive_has_fields.md) lists it with the -other reserved names. +associated types and the derive fails; the [derive's page](../derives/derive_has_fields.md) lists it with +the other reserved names. + +**There is no method.** `Fields` is a type. Getting a *value* in that shape is +[`ToFields`](./to_fields.md). ## Related constructs -- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates all five impls; what you write. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl and the four + companions'; what you write. +- [`HasFieldsRef`](./has_fields_ref.md) — the borrowed shape. +- [`ToFields`](./to_fields.md), [`FromFields`](./from_fields.md), and + [`ToFieldsRef`](./to_fields_ref.md) — the conversions between a value and its shape. - [`HasField`](./has_field.md) — the singular counterpart, per-field access. - [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this with the builder and extractor. -- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a shape is built from. +- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a shape is built + from. - [`Field`](../types/field.md) — one entry: a value paired with its type-level name. -- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. -- [`AppendProduct`](./product_ops.md) — the operations that compute new shapes from old ones. -- [`CanUpcast`](./cast.md) — conversions between two types whose shapes overlap, driven by this one. -- [`HasBuilder`](./has_builder.md) and [`ExtractField`](./extract_field.md) — building and deconstructing, - rather than describing. +- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains + underneath. +- [`AppendProduct`](./append_product.md) — the operations that compute new shapes from old ones. +- [`CanUpcast`](./can_upcast.md) and [`CanBuildFrom`](./can_build_from.md) — conversions between two + types whose shapes overlap, driven by this one. The ideas behind it: @@ -281,11 +210,7 @@ The ideas behind it: ## Source - [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs) - — `HasFields`, `HasFieldsRef` -- [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs) - — `ToFields`, `ToFieldsRef` -- [`from_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_fields.rs) - — `FromFields` + — `HasFields` and `HasFieldsRef` - Derive codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) --- diff --git a/docs/reference/traits/has_fields_ref.md b/docs/reference/traits/has_fields_ref.md new file mode 100644 index 00000000..e98db2d0 --- /dev/null +++ b/docs/reference/traits/has_fields_ref.md @@ -0,0 +1,162 @@ +--- +sidebar_label: 'HasFieldsRef' +--- + +# `HasFieldsRef` + +A type's whole shape, with every value borrowed. + +## What it's for + +[`HasFields`](./has_fields.md) describes a type as a list of named entries holding owned values. Code +that only *reads* a value should not have to consume it to walk its shape — a validator, a serializer, a +routine that inspects a struct and hands it back — so there is a second description in which every entry +holds a borrow instead: + +```rust +pub trait HasFieldsRef { + type FieldsRef<'a> + where + Self: 'a; +} +``` + +`FieldsRef<'a>` is the same shape as `Fields` with each value borrowed for `'a`. It is a **generic +associated type**, which is what lets one trait describe the shape at whatever lifetime a caller has. + +The two shape traits are independent rather than one extending the other, and that is deliberate: a type +may be described owned, borrowed, or both. What connects the borrowed description to a value is +[`ToFieldsRef`](./to_fields_ref.md). + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method — like its owned +counterpart, this trait only names a type. + +The `where Self: 'a` clause on the associated type is required and worth recognizing: it says the borrow +cannot outlive the value it describes, which every use site inherits. + +The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md), which emits this alongside +[`HasFields`](./has_fields.md) rather than as a separate opt-in. + +## Examples + +The borrowed shape of a struct pairs each name with a reference: + +```rust +use cgp::prelude::*; + +#[derive(HasField, HasFields)] +pub struct Config { + pub host: String, + pub port: u16, +} + +// Config::FieldsRef<'a> is +// Product![Field, Field] +``` + +Bounding on it is how generic read-only code names what it walks: + +```rust +fn inspect(value: &T) +where + T: HasFieldsRef + ToFieldsRef, +{ + let _fields = value.to_fields_ref(); + // walk the borrowed shape; `value` is untouched +} +``` + +Requiring [`ToFields`](./to_fields.md) there instead would force every caller to give up its value or +clone it. + +## When to reach for it, and when not + +**Bound on it when generic code reads a type's shape without consuming it**, and pair it with +[`ToFieldsRef`](./to_fields_ref.md), which is the only way to obtain a value in this shape. + +- **Use [`HasFields`](./has_fields.md)** when the code takes ownership — building, converting, + destructuring. +- **Use `HasFieldsRef` + [`ToFieldsRef`](./to_fields_ref.md)** when the original must survive. This is + the weaker requirement, so prefer it when it suffices. +- **Use [`HasField`](./has_field.md)** when only one named field is needed. The whole-shape traits are + for code that walks everything. + +Being precise about which of the five shape traits a routine requires pays, because each one narrows what +a caller must supply. + +## Under the hood + +:::note + +### Advanced + +This section shows the generated impl, and the reserved lifetime name in it. + +::: + +The derive emits the borrowed shape with a **reserved lifetime name**, `'__a`, so it cannot collide with +a lifetime of yours: + +```rust +impl HasFieldsRef for Person { + type FieldsRef<'__a> = Product![ + Field, + Field, + ] + where + Self: '__a; +} +``` + +The transformation is uniform: each entry's value type `T` becomes `&'__a T`, and the spine is otherwise +untouched — same length, same order, same tags. An enum's borrowed shape is the dual, an `Either` chain +whose arms carry borrowed payloads. + +Because the rewrite is per-entry rather than structural, **a field that is already a reference gains +another one**: a field of type `&'a Name` appears as `&'__a &'a Name`. That is correct, and it is the one +thing about this trait that surprises people in an error message. + +## Gotchas + +**A field that is already borrowed gets a second borrow.** `&'a Name` becomes `&'__a &'a Name` in +`FieldsRef`, which reads oddly in a diagnostic and is not a bug. + +**The `where Self: 'a` clause propagates.** Any bound naming `FieldsRef<'a>` inherits it, so a signature +that borrows the shape usually needs the lifetime spelled out rather than elided. + +**It is emitted by [`#[derive(HasFields)]`](../derives/derive_has_fields.md), not by a derive of its +own.** There is no `#[derive(HasFieldsRef)]`. + +**Naming the shape is not obtaining it.** [`ToFieldsRef`](./to_fields_ref.md) is the method half; this +trait has none. + +**Two enum variant names are reserved**, `Fields` and `FieldsRef`, because these associated types are +named through `Self::…` in the generated impls. The +[derive's page](../derives/derive_has_fields.md) lists them with the others. + +## Related constructs + +- [`HasFields`](./has_fields.md) — the owned shape, and where the family is explained in full. +- [`ToFieldsRef`](./to_fields_ref.md) — the conversion that produces a value in this shape. +- [`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md) — the owned conversions. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl. +- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a shape is built + from. +- [`Field`](../types/field.md) — one entry of a shape. +- [`MapTypeRef`](./map_type_ref.md) — the borrow markers the extractor family uses for the same job. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. + +## Source + +- [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs) + — `HasFieldsRef` and `HasFields` +- Derive codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/has_optional_builder.md b/docs/reference/traits/has_optional_builder.md new file mode 100644 index 00000000..68707922 --- /dev/null +++ b/docs/reference/traits/has_optional_builder.md @@ -0,0 +1,176 @@ +--- +sidebar_label: 'HasOptionalBuilder' +--- + +# `HasOptionalBuilder` + +Starting a builder in which every field is already optional. + +## What it's for + +The core [builder family](./has_builder.md) is deliberately strict: a field is set exactly once, and a +partial record becomes its concrete struct only when **every** field is present. That strictness is what +catches a missing field at compile time, and it is too rigid for a record whose fields arrive in an +unpredictable order, or more than once. + +`HasOptionalBuilder` is the entry point that relaxes it: + +```rust +pub trait HasOptionalBuilder { + type Builder; + + fn optional_builder() -> Self::Builder; +} +``` + +It hands back a partial value with every field marked `IsOptional` rather than `IsNothing` — so each +slot holds an `Option` and **absence becomes a runtime condition instead of a type-level one.** Fields +can then be set freely with [`SetOptional`](./set_optional.md), in any order and as many times as you +like, and the choice of how to end is deferred to the finalize call. + +It stands to [`HasBuilder`](./has_builder.md) as the optional layer stands to the core one: same +machinery, different starting marker. + +## Using it + +**It is not in the prelude.** Nothing in the optional-field layer is — import it from +`cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::HasOptionalBuilder; +``` + +`optional_builder()` is an associated function with no receiver: `Context::optional_builder()`. + +The impls are blanket ones over the core builder machinery, so any record deriving +[`#[derive(BuildField)]`](../derives/derive_build_field.md) — or +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — gets this for free. There is no separate derive. + +**Two endings are available**, and picking between them at the call site is the layer's real payoff: +[`FinalizeOptional`](./finalize_optional.md) requires every field and reports the first missing one, while +[`CanFinalizeWithDefault`](./can_finalize_with_default.md) fills unset fields from `Default`. + +## Examples + +An all-optional builder, set in any order and finalized strictly: + +```rust +use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +let builder = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .set(PhantomData::, 42); + +let context = builder.finalize_optional().unwrap(); + +assert_eq!(context.foo, "foo"); +``` + +Leave a field unset and the two endings diverge, which is the point of deferring the choice: + +```rust +use cgp::extra::field::impls::CanFinalizeWithDefault; + +let context = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + +assert_eq!(context.bar, 0); // defaulted +``` + +Had that used `finalize_optional`, it would have returned `Err("bar")` instead. + +## When to reach for it, and when not + +**Reach for it when fields must be settable in any order and more than once**, which the core +`build_field` cannot do — and stay on the core builder otherwise. + +- **[`HasBuilder`](./has_builder.md)** when every field is genuinely required and set once. You lose the + compile-time completeness check by moving here, and that check is the reason the builder family + exists. +- **`HasOptionalBuilder`** when the fields arrive unpredictably — parsed configuration, accumulated + defaults, a value assembled across several passes. +- **[`ToOptional`](./to_optional.md)** when you already hold a core builder and want to convert it rather + than start fresh. +- **A hand-written builder** when the *logic* is the point — validation at finalize, interdependent + fields, computed defaults that are not `Default::default()`. This layer models presence and defaulting, + and nothing else. + +## Under the hood + +:::note + +### Advanced + +This section shows that the entry point is a composition rather than new machinery. + +::: + +`optional_builder()` is [`HasBuilder`](./has_builder.md)'s `builder()` followed by +[`ToOptional`](./to_optional.md) — start at all-`IsNothing`, then re-mark every field to `IsOptional` +with a [`TransformMapFields`](./transform_map_fields.md) walk carrying the +[`TransformOptional`](./transform_optional.md) marker. + +So the resulting type is the same partial companion the core builder uses, at a configuration the core +builder never reaches on its own: + +```rust +// __PartialContext +``` + +Nothing about the companion type is special to this layer. What changes is the marker, and with it which +operations apply: [`SetOptional`](./set_optional.md) resolves where +[`BuildField`](./build_field.md) does not, and the strict +[`FinalizeBuild`](./finalize_build.md) does not resolve at all until a finalize has re-marked the fields +back to `IsPresent`. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::field::impls`, along with whatever else in the +layer you use. + +**Moving here gives up the compile-time completeness check.** With the core builder a missing field is a +compile error; here it is an `Err` or a silently substituted default. That is the trade, and it is worth +making consciously. + +**The builder's type does not record what you have set.** Every field stays `IsOptional` throughout, +which is what allows re-setting and is why finalizing has to check at run time. + +**`optional_builder()` is an associated function**, so it is `Context::optional_builder()` with no +receiver. + +**A field whose type is already `Option` is not the same as an `IsOptional` field.** The former is a +value that happens to be optional and must still be set; the latter is a builder slot that may be empty. +Conflating them produces an `Option>`. + +## Related constructs + +- [`SetOptional`](./set_optional.md) — setting a field on the builder this produces. +- [`FinalizeOptional`](./finalize_optional.md) — the strict ending, reporting the first missing field. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the defaulting ending. +- [`ToOptional`](./to_optional.md) — converting an existing core builder instead of starting fresh. +- [`HasBuilder`](./has_builder.md) — the core entry point this relaxes. +- [`MapType`](./map_type.md) — the `IsOptional` marker the layer runs on. +- [`TransformMapFields`](./transform_map_fields.md) — the walk that re-marks every field. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the machinery underneath. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence + fits. + +## Source + +- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs) + — `HasOptionalBuilder`, `ToOptional`, and `TransformOptional` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/into_builder.md b/docs/reference/traits/into_builder.md new file mode 100644 index 00000000..25ee5b53 --- /dev/null +++ b/docs/reference/traits/into_builder.md @@ -0,0 +1,157 @@ +--- +sidebar_label: 'IntoBuilder' +--- + +# `IntoBuilder` + +Turning a complete record into a partial one, with every field present. + +## What it's for + +[`HasBuilder`](./has_builder.md) starts from nothing: a partial value with every field absent, to be +filled. `IntoBuilder` starts from the other end: + +```rust +pub trait IntoBuilder { + type Builder; + + fn into_builder(self) -> Self::Builder; +} +``` + +`into_builder(self)` consumes an existing value and hands back a partial one with **every field +present**. That is what you want when *redistributing* a struct's fields rather than assembling one — +taking a value apart, moving some fields elsewhere, and rebuilding. + +The two entry points differ only in where they begin, and they produce the same kind of value: + +| | starting configuration | what it is for | +|---|---|---| +| [`HasBuilder`](./has_builder.md) | every field `IsNothing` | assembling a record from pieces | +| `IntoBuilder` | every field `IsPresent` | taking one apart and putting it back | + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +Unlike `builder()`, this one is a method taking `self`, so it is called on a value: +`person.into_builder()`. `Builder` names the same partial companion type +[`HasBuilder`](./has_builder.md) names, at the all-present configuration rather than the all-absent one. + +The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md), also available through +[`#[derive(CgpRecord)]`](../derives/derive_cgp_record.md) and +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). + +## Examples + +Taking a value apart and putting it back, which is the shape generic redistributing code has: + +```rust +use cgp::core::field::traits::TakeField; +use cgp::prelude::*; + +let builder = person.into_builder(); // all present + +let (first_name, remainder) = builder.take_field(PhantomData::); +// `remainder` is missing first_name, so it cannot be finalized + +let person = remainder + .build_field(PhantomData::, first_name) + .finalize_build(); // all present again +``` + +Note that a value straight out of `into_builder` is already finalizable — every marker is `IsPresent`, so +[`finalize_build`](./finalize_build.md) resolves immediately and the round trip is the identity. What +makes the trait useful is what happens in between. + +## When to reach for it, and when not + +**Reach for it when the starting point is a value rather than nothing**, which is the narrower of the two +entry points and the one that shows up in generic code more than in application code. + +- **Use [`HasBuilder`](./has_builder.md)** when assembling a record from independent pieces. That is the + common case and the one the extensible builder pattern is about. +- **Use `IntoBuilder`** when a complete value must be decomposed — to swap one field, to hand fields to + several destinations, to rebuild a record with one type changed. +- **Use [`ToFields`](./to_fields.md)** instead when what you want is the value's *shape* as a flat list + rather than a partial type you can fill. A partial value tracks presence; a `Fields` product does not. +- **Prefer a struct update expression** in concrete code. `Person { first_name, ..person }` does the + common case with no machinery, and this family is for code that cannot name the type. + +## Under the hood + +:::note + +### Advanced + +This section is short, because the companion type is +[`HasBuilder`](./has_builder.md#under-the-hood)'s. + +::: + +The derive generates one partial companion per record — `__Partial{Name}`, with a +[`MapType`](./map_type.md) parameter per field — and the two entry points differ only in the +configuration they name: + +```rust +impl HasBuilder for Person { + type Builder = __PartialPerson; // nothing set +} + +impl IntoBuilder for Person { + type Builder = __PartialPerson; // everything set +} +``` + +`into_builder` moves each field of the concrete struct into the corresponding slot of the companion, +which under `IsPresent` holds the value itself — so the conversion is a move rather than a wrap, and +nothing about the runtime representation changes. + +Because the result is at the all-present configuration, it satisfies +[`FinalizeBuild`](./finalize_build.md) immediately and [`TakeField`](./take_field.md) for every field, +which is exactly the pair a redistribution needs. + +## Gotchas + +**It consumes the value.** There is no borrowing form; use [`ToFieldsRef`](./to_fields_ref.md) if the +original must survive, bearing in mind that gives you a shape rather than a builder. + +**The result is already finalizable.** Calling `into_builder().finalize_build()` is the identity, which +is legal and pointless — the trait earns its keep only if something happens in between. + +**The partial type cannot be printed or cloned.** The derive clears the original's attributes, so a value +mid-redistribution has none of the record's own derives. + +**It is a method, where [`HasBuilder`](./has_builder.md)'s `builder()` is an associated function.** The +asymmetry is deliberate — one starts from a value and the other from nothing — and it catches people +writing `Person::into_builder()`. + +**Taking a field out makes the value unfinalizable until it is put back.** That is the guarantee, and it +means a redistribution that drops a field fails at `finalize_build` rather than where the field was +dropped. + +## Related constructs + +- [`HasBuilder`](./has_builder.md) — the other entry point, and where the family is explained in full. +- [`TakeField`](./take_field.md) — removing a present field, which is what this enables. +- [`BuildField`](./build_field.md) — putting one back. +- [`FinalizeBuild`](./finalize_build.md) — returning to the concrete struct. +- [`UpdateField`](./update_field.md) — the primitive underneath both directions. +- [`PartialData`](./partial_data.md) — what names the destination type mid-build. +- [`ToFields`](./to_fields.md) — the flat-shape alternative to a partial value. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates this impl. +- [`MapType`](./map_type.md) — the markers the configuration is written in. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder + pattern. + +## Source + +- [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs) + — `IntoBuilder` and `HasBuilder` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/lift_value.md new file mode 100644 index 00000000..874ace24 --- /dev/null +++ b/docs/reference/traits/lift_value.md @@ -0,0 +1,152 @@ +--- +sidebar_label: 'LiftValue' +--- + +# `LiftValue` + +Putting a value back into a monad's output type, on either branch. + +## What it's for + +A bind step in a [monadic pipeline](/docs/concepts/monadic-handlers) unwraps a value, runs a +continuation or short-circuits, and then has to produce the step's own output. Producing it means +wrapping something back up — and there are **two** things that might need wrapping, which is why this +trait has two methods rather than one: + +```rust +pub trait LiftValue { + type Output; + + fn lift_value(value: Value) -> Self::Output; + fn lift_output(output: Output) -> Self::Output; +} +``` + +`lift_value` wraps a bare value from the continue or short-circuit branch into the final output. +`lift_output` re-wraps a value already in the inner shape, forwarding a continuation's computed result. + +It is the counterpart of [`ContainsValue`](./contains_value.md): that one says how to get *out* of an +output type, this one how to get back *in*. Together they run one step; the other two monad traits, +[`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline instead. + +**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is +never wired. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::monad::traits`: + +```rust +use cgp::extra::monad::traits::LiftValue; +``` + +You import it only when **defining a monad of your own**. `Self` is the monad marker, `Value` is the bare +value, `Output` is the inner output being forwarded, and the associated `Output` is the step's final +output type. + +## Examples + +What each marker's impl says is what decides how a pipeline behaves. + +**`IdentMonadic` is the identity in both directions**: `LiftValue` returns `T` from both methods. +Nothing is wrapped, so a pipeline under it is plain function composition. + +**`ErrMonadic` and `OkMonadic` mirror each other** over a `Result`, and the `lift_value` constructor is +where the mirroring shows: + +| Monad | `lift_value` wraps with | continue branch | +|---|---|---| +| `ErrMonadic` | `Ok` | `Ok` | +| `OkMonadic` | `Err` | `Err` | + +So under `ErrMonadic` a bare value re-enters the pipeline as `Ok(value)` — the ordinary `?` behaviour — +and under `OkMonadic` as `Err(value)`. + +**Both methods matter, and conflating them changes behaviour silently.** `lift_value` is used where a +bare value is being wrapped for the first time; `lift_output` where a continuation has already produced +something in the inner shape and the step is passing it outward. Implementing the second as the first +collapses the two branches. + +## When to reach for it, and when not + +**Reach for the [monad providers](../providers/monad_providers.md), not this trait.** A pipeline is built +by wiring [`PipeMonadic`](../providers/monad_providers.md) with a marker and a handler list. + +The one real reason to name it is **defining a new monad**. Implement it alongside +[`ContainsValue`](./contains_value.md), since the two are the pair that runs a step, and take the +`OkMonadic`/`ErrMonadic` pair as the model — including their separate treatment of the two methods, which +is the part a first implementation usually gets wrong. + +If short-circuiting is not what you need, the [handler combinators](../providers/handler_combinators.md) +chain steps without a branch and involve none of this. + +## Under the hood + +:::note + +### Advanced + +This section shows where a bind step uses it. + +::: + +The [`BindOk` and `BindErr`](../providers/monad_providers.md) providers use `LiftValue` in their +[`Computer`](../components/computer.md) and `AsyncComputer` impls, as the closing half of a step whose +opening half is [`ContainsValue`](./contains_value.md). The step unwraps the incoming output, decides +whether to short-circuit, and then lifts: + +- on the **short-circuit** branch, the value never reached the continuation, so it is wrapped with + `lift_value`; +- on the **continue** branch, the continuation has already produced an inner output, so it is forwarded + with `lift_output`. + +That is the whole reason for two methods. A monad whose two methods agree — as `IdentMonadic`'s do — is +one where the distinction happens to be vacuous, not one where it does not exist. + +The transformer forms implement both by delegating to the base monad after handling their own layer, +which is what lets a stack lift through *n* layers with no depth-specific code. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::monad::traits`. + +**It is not a component and cannot be wired.** What gets wired is the provider that consumes it. + +**`lift_value` and `lift_output` are not the same method.** Implementing the second as the first — or +forgetting the distinction — collapses the two branches and silently changes what a pipeline does on a +short-circuit. This is the most likely defect in a hand-written monad. + +**`OkMonadic` lifts with `Err`.** Its continue branch is the error half, which follows from +[`ContainsValue`](./contains_value.md) and reads backwards until you have internalized the naming. + +**The associated `Output` is not the `Output` parameter.** The parameter is the inner output being +forwarded; the associated type is the step's own. They coincide for some monads and not for others. + +**A new monad needs all four traits**, plus the transformer form to stack. + +## Related constructs + +- [`ContainsValue`](./contains_value.md) — the other half of running a step: getting out of the output + type. +- [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md) — the two traits that fold + the pipeline rather than run a step. +- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the + markers; what you actually wire. +- [`Computer`](../components/computer.md) — the component family the bind providers implement. +- [Handler combinators](../providers/handler_combinators.md) — composition without a short-circuit + branch. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads + compose. + +## Source + +- [`lift.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/lift.rs) + — `LiftValue` +- Per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/map_field.md b/docs/reference/traits/map_field.md new file mode 100644 index 00000000..1e4a5a18 --- /dev/null +++ b/docs/reference/traits/map_field.md @@ -0,0 +1,181 @@ +--- +sidebar_label: 'MapField' +--- + +# `MapField` + +Reading through a field without forcing its type to be `'static`. + +## What it's for + +Chaining field reads looks like it should just work — read a field, then read a field of *that* — +and it does not, for a reason that is about lifetimes rather than about CGP. Writing +`context.get_field(..).get_field(..)` makes the intermediate `Value` outlive the borrow it came from, +which the compiler can only accept by requiring it to be `'static`. + +`MapField` sidesteps that by taking a closure instead of returning the intermediate: + +```rust +pub trait MapField: HasField { + fn map_field( + &self, + _tag: PhantomData, + mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, + ) -> &T; +} +``` + +The higher-ranked bound is the whole trick: the closure is required to work for *any* lifetime, so the +compiler can pick the caller's rather than demanding `'static`. + +**You will not normally call it.** [`ChainGetters`](../providers/chain_getters.md) is what uses +`map_field`, which is how a getter reaches a field on a nested context. + +## Using it + +**It is not in the prelude** — one of only two members of the `HasField` group that are not. Import it +from `cgp::core::field::traits`: + +```rust +use cgp::core::field::traits::MapField; +``` + +It is a supertrait extension of [`HasField`](./has_field.md), so bounding on it gives you the plain read +as well. The `mapper` argument is an ordinary closure; what makes it unusual is the `for<'a>` binder, +which means a closure that captures a reference of some *specific* lifetime will not satisfy it. + +**Nobody implements it.** It is a blanket impl for every `HasField` whose tag is `'static`, so every +field access gains `map_field` for free. + +## Examples + +Reaching a field of a field, which is the case the trait exists for: + +```rust +use cgp::core::field::traits::MapField; +use cgp::prelude::*; + +#[derive(HasField)] +pub struct Inner { + pub name: String, +} + +#[derive(HasField)] +pub struct Outer { + pub inner: Inner, +} + +let outer = Outer { inner: Inner { name: "Alice".to_owned() } }; + +let name: &String = outer.map_field( + PhantomData::, + |inner| inner.get_field(PhantomData::), +); + +assert_eq!(name, "Alice"); +``` + +The closure receives the borrowed `Inner` and returns a borrow *derived from it*, so no intermediate +outlives its source and no `'static` bound appears anywhere. + +In practice this is what a wiring line expresses instead: + +```rust +delegate_components! { + Outer { + NameGetterComponent: ChainGetters>, + } +} +``` + +which is the same descent, chosen at the wiring site rather than written at the call site. + +## When to reach for it, and when not + +**Reach for [`ChainGetters`](../providers/chain_getters.md) rather than this trait.** The provider is the +construct; `map_field` is the mechanism it is built from, and calling it by hand means writing at a call +site what the wiring could have decided. + +- **Use [`ChainGetters`](../providers/chain_getters.md)** to reach a field on a nested context. +- **Use [`HasField`](./has_field.md)** for a field of the context itself, which is the common case and + needs none of this. +- **Use an [`#[implicit]`](../attributes/implicit.md) argument** before either, since it covers every + same-context read. +- **Reach for [`FieldMapper`](./field_mapper.md)** when the same descent must happen on the provider + side, where the context is a type argument rather than `self`. + +Call `map_field` directly only when you are writing machinery of the same kind — a new getter provider, +say — and even then the existing ones usually compose. + +## Under the hood + +:::note + +### Advanced + +This section explains why the blanket impl needs a `'static` tag and the value does not. + +::: + +`MapField` is a blanket impl for every [`HasField`](./has_field.md) whose **tag** is `'static`: + +```rust +// for every Context: HasField, where Tag: 'static +``` + +The bound is on the *tag*, not on the value — and that is the point. A tag is a +[`Symbol!`](../macros/symbol.md) or an [`Index`](../types/index.md), both of which are `'static` by +construction, so the bound costs nothing. The value stays free, which is exactly what the naive chained +read could not achieve. + +Inside, the implementation reads the field once and hands the borrow to the mapper. Because the mapper +is higher-ranked over `'a`, its return borrow is tied to the field borrow rather than to any fixed +lifetime, and the result can be returned to the caller. + +[`ChainGetters`](../providers/chain_getters.md) composes descents by nesting these calls, one per +segment, so an arbitrarily deep path stays lifetime-correct with no `'static` anywhere in the chain. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::traits`. +[`FieldMapper`](./field_mapper.md) is the other non-prelude member of the group; everything else in it +is in the prelude. + +**The closure must be higher-ranked.** A closure that captures a reference with a particular lifetime +will not satisfy `for<'a>`, and the error talks about lifetime bounds rather than about the closure's +body — which is confusing the first time. + +**The mapper must return a borrow *derived from* its argument.** Returning a reference to something else +in scope does not satisfy the binder, which is the safety the design buys. + +**It cannot map to an owned value.** The signature returns `&T`. A getter that must produce a value uses +[`MRef`](../types/mref.md) instead. + +**`MapField` is not [`MapFields`](./map_fields.md) and not [`MapType`](./map_type.md).** Three similar +names: this one is a lifetime helper for reading a nested field, `MapFields` applies a marker across a +type-level list, and `MapType` names one field's storage on a partial type. + +## Related constructs + +- [`FieldMapper`](./field_mapper.md) — the provider-side mirror of this trait. +- [`HasField`](./has_field.md) — the supertrait, and the plain read. +- [`ChainGetters`](../providers/chain_getters.md) — the provider that uses `map_field` to descend. +- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to read a field of the context itself. +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags, which are `'static` by + construction. +- [`MRef`](../types/mref.md) — the return type for a getter that may produce rather than lend. +- [`MapFields`](./map_fields.md) and [`MapType`](./map_type.md) — the two similarly-named traits that do + something else. + +The ideas behind it: + +- [Implicit arguments](/docs/concepts/implicit-arguments) — the ergonomic surface over field access. + +## Source + +- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs) + — `MapField` and `FieldMapper` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/map_fields.md b/docs/reference/traits/map_fields.md new file mode 100644 index 00000000..a0acc690 --- /dev/null +++ b/docs/reference/traits/map_fields.md @@ -0,0 +1,167 @@ +--- +sidebar_label: 'MapFields' +--- + +# `MapFields` + +Rewriting every entry of a type-level list through one marker. + +## What it's for + +A partial record is the same record with every field's storage changed the same way — each value wrapped +in an `Option`, or replaced by `()`, or left alone. Describing that as a type means rewriting every entry +of the shape uniformly, and `MapFields` is that operation: + +```rust +pub trait MapFields { + type Mapped; +} +``` + +The list's length and order never change. Each entry type `T` becomes `Mapper::Map`, where the mapper +is a [`MapType`](./map_type.md) marker — so **the marker decides the whole effect**. With `IsPresent` it +is the identity; with `IsNothing` every entry collapses to `()`; with `IsOptional` every entry becomes +`Option<_>`; with `IsVoid` every entry becomes uninhabited. + +It is the transforming member of the three product operations, and the only one defined over **both** +spines: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum. That is what lets one +operation produce both a partial record and a partial enum. + +## Using it + +**It is not in the prelude**, and neither is `IsOptional`. Import the trait from +`cgp::core::field::traits` and any non-prelude marker from `cgp::core::field::impls`: + +```rust +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::MapFields; +``` + +`IsPresent`, `IsNothing`, and `IsVoid` are in the prelude; `IsOptional` is not. + +`Self` is the list, `Mapper` is the marker, and the result is `Mapped` — note the name, which differs +from the `Output` its two siblings expose. There is no method, because there is nothing to execute. + +## Examples + +Applying `IsOptional` turns a product of values into a product of optionals — the shape a partial builder +uses to track what is not yet filled: + +```rust +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::MapFields; +use cgp::prelude::*; + +type Fields = Product![String, u16, bool]; + +type Optional = >::Mapped; +// = Product![Option, Option, Option] +``` + +The same marker applies over a sum, which is what makes one operation serve both halves of the +extensible-data machinery: + +```rust +type Variants = Sum![String, u16]; + +type OptionalVariants = >::Mapped; +// = Sum![Option, Option] +``` + +## When to reach for it, and when not + +**Reach for it when generic code must name a uniformly re-wrapped shape**, which is what a partial +representation is — and essentially never otherwise. + +- **Reach for [`AppendProduct`](./append_product.md) or [`ConcatProduct`](./concat_product.md)** when the + shape grows rather than changing its wrapping. +- **Use [`TransformMapFields`](./transform_map_fields.md) instead** when you want the *values* re-wrapped + rather than the type named. This trait computes a type; nothing wraps anything at run time by itself. +- **Use [`HasFields`](./has_fields.md) instead** if you only need a type's existing shape. + +One name worth disambiguating, because three similar ones sit close together. `MapFields` applies one +marker across a whole list; [`MapType`](./map_type.md) is a single marker naming *one* field's storage; +and [`MapField`](./map_field.md) — singular, no *s* — is a lifetime helper for reading a nested field. +Three similar names, three unrelated jobs. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursion, which exists twice — once per spine. + +::: + +Like its two siblings, `MapFields` is a pair of impls per spine, one for the node and one for the +terminator. Unlike them, it *transforms* the head rather than preserving it: + +```rust +impl MapFields for Cons +where + Mapper: MapType, + Rest: MapFields, +{ + type Mapped = Cons, Rest::Mapped>; +} + +impl MapFields for Nil { + type Mapped = Nil; +} +``` + +The `Either`/`Void` impls mirror these exactly, with `Either` standing where `Cons` does and `Void` where +`Nil` does. Because the recursion only ever replaces a head *type*, the spine's length and shape are +structurally preserved — which is why a mapped product is still a product of the same arity, and a mapped +sum still a sum. + +All of it resolves during type checking, so a mapped shape is a name for a type rather than a +computation that runs. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::traits`, and remember that `IsOptional` +needs its own import from `cgp::core::field::impls`. + +**The result is `Mapped`, not `Output`.** [`AppendProduct`](./append_product.md) and +[`ConcatProduct`](./concat_product.md) both expose `Output`, and this one does not. + +**It computes types, not values.** A `MapFields` result does not wrap anything at run time — +something still has to build the wrapped values, which on a partial record is +[`TransformMapFields`](./transform_map_fields.md). + +**A marker with no `MapType` impl does not resolve**, and the error names the missing `MapType` bound +rather than the marker's role. + +**It is the only one of the three that covers sums.** There is no `AppendSum` or `ConcatSum`. + +**A long list means a deep recursion**, so mapping a wide shape costs compile time proportional to its +width. + +## Related constructs + +- [`MapType`](./map_type.md) — the markers this applies, and the trait most easily confused with it. +- [`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md) — the two operations + that grow a list rather than rewrite it. +- [`TransformMapFields`](./transform_map_fields.md) — the value-level counterpart, which actually converts + the fields. +- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the sugar for both spines. +- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains + underneath. +- [`HasFields`](./has_fields.md) — where a type's existing shape comes from. +- [`MapField`](./map_field.md) — the similarly-named lifetime helper, which does something else entirely. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — presence tracking on a partial record. +- [Extensible variants](/docs/concepts/extensible-variants) — possibility tracking on a partial variant. + +## Source + +- [`map_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_fields.rs) + — `MapFields`, over both spines + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index b845d5c2..fda2429d 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -4,14 +4,14 @@ sidebar_label: 'MapType' # `MapType` -The present, absent, and void type-mapping markers and their transforms. +The marker trait that decides how one field of a partial type is stored. ## What it's for 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. +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, and it has one member: @@ -21,28 +21,21 @@ pub trait MapType { } ``` -`Map` names the storage type the marker assigns to a field whose value type is `T`. So `IsPresent::Map` -is `String`, and `IsNothing::Map` is `()`. **The marker is the field's state, expressed as a type.** +`Map` names the storage type the marker assigns to a field whose value type is `T`. So +`IsPresent::Map` is `String`, and `IsNothing::Map` is `()`. **The marker is the field's +state, expressed as a type.** -That is what lets the [builder](./has_builder.md) and [extractor](./extract_field.md) 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. - -Three companions complete the picture. `MapTypeRef` does the same job for borrowed views, where the wrapping -also introduces a lifetime. `TransformMap` and `TransformMapFields` are the value-level side: they carry the -functions that actually convert a field from one wrapping to another. +That is what lets the [builder](./has_builder.md) and [extractor](./extract_field.md) 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. ## Using it -The four `MapType` markers and two of the three `MapTypeRef` markers are in the prelude. **`IsOptional` and -`IsOwned` are not** — import them from `cgp::core::field::impls`. `TransformMap` and `TransformMapFields` are -not in the prelude either; they come from `cgp::core::field::traits`. - -### The `MapType` markers - -Four markers cover the states a field passes through: +Four markers implement it, and they are the trait's whole public surface. **Three are in the prelude; +`IsOptional` is not** — import it from `cgp::core::field::impls`. ```rust impl MapType for IsPresent { type Map = T; } // the field holds its value @@ -51,58 +44,20 @@ impl MapType for IsVoid { type Map = Void; } // the case is impossib impl MapType for IsOptional { type Map = Option; } // 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** — which is exactly how an extractor discharges its remainder -with an empty `match`. Records use the first, variants the second. - -### The `MapTypeRef` markers - -`MapTypeRef` threads a lifetime, so the marker decides not just presence but how the value is held: - -```rust -pub trait MapTypeRef { - type Map<'a, T: 'a>: 'a; -} - -impl MapTypeRef for IsRef { type Map<'a, T: 'a> = &'a T; } -impl MapTypeRef for IsMut { type Map<'a, T: 'a> = &'a mut T; } -impl MapTypeRef for IsOwned { type Map<'a, T: 'a> = T; } -``` - -A borrowed extractor combines both families: one outer `MapTypeRef` marker shared across all fields, and one -`MapType` marker per field, so a field's storage is `MapType::Map>`. `HasExtractorRef` -fixes the outer marker to `IsRef` and `HasExtractorMut` to `IsMut`. - -**`IsOwned` has no consumer in CGP.** No derive emits it and no provider resolves against it — it is available -for a borrowed view that holds its payloads by value, and at present that view exists only if you write it -yourself. +**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** — which is exactly how an +extractor discharges its remainder with an empty `match`. Records use the first, variants the second. -### The transforms +`Map` is a **generic associated type**, so a bound naming it is written +`M: MapType = String>` when the storage must be pinned, and plain `M: MapType` when it need +not be. -`MapType` only names storage types. `TransformMap` carries the *function* that converts a value from one -wrapping to another: - -```rust -pub trait TransformMap { - fn transform_mapped(value: M1::Map) -> M2::Map; -} -``` - -`TransformMapFields` lifts such a transform across a whole partial record, walking the target's -[`HasFields`](./has_fields.md) shape field by field: - -```rust -pub trait TransformMapFields { - type Output; - - fn transform_map_fields(self) -> Self::Output; -} -``` - -This is the pair to reach for when you need to re-mark every field at once — which is what the -[optional-field extensions](./optional_fields.md) are built from. +**Three companions complete the picture**, each on its own page: [`MapTypeRef`](./map_type_ref.md) does +the same job for borrowed views, where the wrapping also introduces a lifetime, while +[`TransformMap`](./transform_map.md) and [`TransformMapFields`](./transform_map_fields.md) are the +value-level side, carrying the functions that actually convert a field from one wrapping to another. ## Examples @@ -110,65 +65,48 @@ You mostly meet the markers inside the partial types that [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) generates, where a builder's type reads `__PartialPerson` and tells you at a glance which fields are set. -The transforms, though, are directly useful. A marker that fills absent fields from `Default` is one impl per -source state: +Bounding on the trait is what generic partial-type machinery does: ```rust -use cgp::core::field::impls::IsOptional; -use cgp::core::field::traits::TransformMap; use cgp::prelude::*; -pub struct FillDefaults; - -impl TransformMap for FillDefaults { - fn transform_mapped(value: T) -> T { - value - } -} - -impl TransformMap for FillDefaults { - fn transform_mapped(_value: ()) -> T { - T::default() - } -} - -impl TransformMap for FillDefaults { - fn transform_mapped(value: Option) -> T { - value.unwrap_or_default() - } +fn storage_of(value: M::Map) -> M::Map +where + M: MapType, +{ + value } ``` -Read that as three cases of one rule: a present field passes through, an absent one becomes its default, and an -optional one becomes its contents or the default. Because all three target `IsPresent`, applying it through -`transform_map_fields` leaves every field present — which is precisely the configuration -[`FinalizeBuild`](./has_builder.md) accepts, turning a partially-built record into a finalizable one. +and a projection names one marker's storage directly: -That is not hypothetical: it is how `CanFinalizeWithDefault` in the -[optional-field extensions](./optional_fields.md) works, and reading it here is the shortest route to -understanding that layer. +```rust +// IsPresent::Map is String +// IsNothing::Map is () +// IsVoid::Map is Void +``` ## When to reach for it, and when not -**You will name the markers far more often than the traits.** `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. +**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 traits themselves have narrower uses. +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`** to define a new per-field conversion, as `FillDefaults` above does. This is the - extension point of the whole scheme, and it is genuinely usable: one impl per source marker, and - `transform_map_fields` applies it everywhere. -- **Do not implement `MapType` for a new marker** expecting the derives to use it. The generated partial types - are parameterized over markers, but only the four standard ones have transforms and finalize impls behind - them; a fifth marker is a type with no machinery attached. -- **Reach for the [optional-field extensions](./optional_fields.md) rather than writing the transform yourself** - if what you want is defaulted or optional finalization. Both already exist, built on exactly this. +- **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`](./transform_map.md)** 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 derives to use it. The generated partial + types are parameterized over markers, but only the four standard ones have transforms and finalize + impls behind them; a fifth marker is a type with no machinery attached. +- **Reach for the [optional-field layer](./has_optional_builder.md)** 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 uniformly to -every entry of a type-level list, and lives with the [product operations](./product_ops.md). +[`MapFields`](./map_fields.md) — 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 @@ -176,56 +114,56 @@ every entry of a type-level list, and lives with the [product operations](./prod ### Advanced -This section shows how the transform recursion works. You do not need it to read a marker in an error, but it is -what the optional-field layer is made of. +This section is short, because the trait is one associated type. ::: -`TransformMapFields` is implemented for any [`PartialData`](./has_builder.md) and walks the target's -[`HasFields`](./has_fields.md) product one entry at a time. For each `Field` it uses -[`UpdateField`](./has_builder.md) **twice**: it takes the field out — replacing its marker with `IsNothing` and -reading what the marker was — applies `Transform::transform_mapped` to convert the value into the -`TargetMap` wrapping, then writes it back under `TargetMap`. +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: -So the result type has every field re-marked to `TargetMap`, with the values converted accordingly. Two things -follow from that construction, and both explain limits you might otherwise trip over. The transform must have an -impl for **every** source marker a field might currently be in, or the walk does not resolve — which is why -`FillDefaults` above needs three impls rather than one. And the recursion is driven by the *target's* shape, so -it re-marks exactly the fields the concrete struct declares. +```rust +pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { + pub first_name: <__F0__ as MapType>::Map, + pub last_name: <__F1__ as MapType>::Map, +} +``` -The markers themselves are zero-sized and carry no data. Nothing here has a runtime representation: a `MapType` -impl is a type-level function, and the only values that exist are the field values being wrapped or unwrapped. +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`](./update_field.md) is what performs one such +transition on a value. ## Gotchas -**`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. - -**`IsOptional` and `IsOwned` are not in the prelude.** Import them from `cgp::core::field::impls`. The other -five markers are. +**`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. -**`IsOwned` is unused by CGP.** It is a legal `MapTypeRef` marker with no consumer, so selecting it means -writing the machinery that uses it yourself. +**`IsOptional` is not in the prelude.** Import it from `cgp::core::field::impls`. The other three +`MapType` markers are. -**`MapType` and `MapFields` are different traits.** `MapType` is one marker naming one field's storage; -[`MapFields`](./product_ops.md) applies a marker across a whole list. The names are close and the jobs are not. +**`MapType` and [`MapFields`](./map_fields.md) 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`](./map_field.md) — singular, no *s* — is a third, unrelated thing again. -**A new marker gets you a type and nothing else.** Implementing `MapType` is easy; the derives' finalize and -transform impls are written against the standard markers, so a custom one has no machinery behind it. +**A new marker gets you a type and nothing else.** Implementing `MapType` is easy; the derives' finalize +and transform impls are written against the standard markers, so a custom one has no machinery behind it. -**`TransformMap` needs an impl per source state.** Writing only the `IsNothing` case leaves the recursion -unresolvable for a record with any field already present, and the error names the missing `TransformMap` impl -rather than the field. +**`Map` is a generic associated type**, so pinning it in a bound needs the +`Map = String` form rather than a plain associated-type equality. ## Related constructs +- [`MapTypeRef`](./map_type_ref.md) — the same idea for borrowed views, with a lifetime. +- [`TransformMap`](./transform_map.md) — the per-field conversion function, and the extension point. +- [`TransformMapFields`](./transform_map_fields.md) — that conversion lifted across a whole record. - [`HasBuilder`](./has_builder.md) — uses `IsPresent`/`IsNothing` to track which fields are filled. -- [`ExtractField`](./extract_field.md) — uses `IsPresent`/`IsVoid` to track which variants remain, and - `MapTypeRef` for its borrowed forms. -- [Optional fields](./optional_fields.md) — the layer built from `TransformMap` and `IsOptional`. -- [`MapFields`](./product_ops.md) — applies one marker across a whole type-level list. -- [`HasFields`](./has_fields.md) — the shape `TransformMapFields` walks. +- [`ExtractField`](./extract_field.md) — uses `IsPresent`/`IsVoid` to track which variants remain. +- [`UpdateField`](./update_field.md) — the primitive that moves a field from one marker to another. +- [`MapFields`](./map_fields.md) — applies one marker across a whole type-level list. - [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — generates the partial types these markers parameterize. - [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. @@ -238,14 +176,9 @@ The ideas behind it: ## Source - [`map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type.rs) - and [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type_ref.rs) - — the two traits + — the trait - [`impls/map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type.rs) — `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` -- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) - — `IsRef`, `IsMut`, `IsOwned` -- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs) - — `TransformMap`, `TransformMapFields` --- diff --git a/docs/reference/traits/map_type_ref.md b/docs/reference/traits/map_type_ref.md new file mode 100644 index 00000000..8b73c327 --- /dev/null +++ b/docs/reference/traits/map_type_ref.md @@ -0,0 +1,181 @@ +--- +sidebar_label: 'MapTypeRef' +--- + +# `MapTypeRef` + +The marker trait deciding how a borrowed partial type holds its payloads. + +## What it's for + +[`MapType`](./map_type.md) decides whether a field of a partial type holds its value, nothing, or an +uninhabited type. A **borrowed** partial type needs a second decision on top: whether each payload is +held by shared reference, by mutable reference, or by value. That decision brings a lifetime with it, +which is why it needs its own trait: + +```rust +pub trait MapTypeRef { + type Map<'a, T: 'a>: 'a; +} +``` + +Three markers implement it: + +```rust +impl MapTypeRef for IsRef { type Map<'a, T: 'a> = &'a T; } +impl MapTypeRef for IsMut { type Map<'a, T: 'a> = &'a mut T; } +impl MapTypeRef for IsOwned { type Map<'a, T: 'a> = T; } +``` + +**The two families compose rather than compete.** A borrowed extractor carries one outer `MapTypeRef` +marker shared across all fields and one [`MapType`](./map_type.md) marker per field, so a field's storage +is `MapType::Map>`. [`HasExtractorRef`](./has_extractor_ref.md) fixes the outer +marker to `IsRef` and [`HasExtractorMut`](./has_extractor_mut.md) to `IsMut` — which is what lets a value +be matched without being moved, with the narrowing working identically. + +## Using it + +**`IsRef` and `IsMut` are in the prelude; `IsOwned` is not** — import it from `cgp::core::field::impls`. +The trait itself comes with the prelude. + +The associated type is generic over both a lifetime and a type, with `T: 'a` required and the result +bounded `'a`. That is more machinery than [`MapType`](./map_type.md)'s single-parameter `Map`, and it +is what makes the borrowed shape expressible at whatever lifetime a caller has. + +:::warning + +**`IsOwned` has no consumer in CGP.** No derive emits it and no provider resolves against it. It is +available for a borrowed view that holds its payloads by value, and at present that view exists only if +you write the machinery yourself. + +::: + +## Examples + +You meet these markers inside the borrowed companion types the derives generate. Reading a variant +through a shared borrow leaves the value intact: + +```rust +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +let radius = shape + .extractor_ref() // outer marker is IsRef + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok(); +``` + +and the mutable form changes a payload in place: + +```rust +if let Ok(circle) = shape + .extractor_mut() // outer marker is IsMut + .extract_field(PhantomData::) +{ + circle.radius = 5.0; +} +``` + +Neither call names a marker. What the markers do is decide the type the payload comes out as — `&Circle` +in the first case, `&mut Circle` in the second — while the per-field +[`MapType`](./map_type.md) markers track which variants are still possible. + +## When to reach for it, and when not + +**You will recognize these markers far more often than you name them**, and recognizing them is most of +what this page is for: an error mentioning `IsRef` is telling you the value is being read through +[`extractor_ref`](./has_extractor_ref.md) rather than consumed. + +- **Use [`HasExtractorRef`](./has_extractor_ref.md) or [`HasExtractorMut`](./has_extractor_mut.md)** + rather than naming a marker. They fix the outer marker for you, and they are the constructs this trait + serves. +- **Bound on `MapTypeRef`** only when writing generic machinery over a borrowed partial type's outer + marker. +- **Do not select `IsOwned` expecting it to work.** Nothing in CGP consumes it. +- **Use [`MapType`](./map_type.md)** for the per-field state, which is the decision this one sits beside + rather than replaces. +- **Use [`ToFieldsRef`](./to_fields_ref.md)** when what you want is the borrowed *shape* of a struct + rather than a borrowed extractor. That trait solves the same problem for the record side, without + markers. + +## Under the hood + +:::note + +### Advanced + +This section shows how the two marker families combine in one generated type. + +::: + +A borrowed companion enum carries the outer marker as an extra parameter alongside the per-variant ones, +and each payload slot projects through both: + +```rust +// conceptually, for `enum Shape { Circle(Circle), Rectangle(Rectangle) }` +// +// pub enum __PartialRefShape<'a, R: MapTypeRef, F0: MapType, F1: MapType> { +// Circle(F0::Map>), +// Rectangle(F1::Map>), +// } +``` + +Read the nesting outward: `R::Map<'a, T>` decides *how* the payload is held, and `F::Map<…>` decides +*whether* it is there at all. Fixing `R = IsRef` gives a shared-borrow extractor; flipping an `F` from +`IsPresent` to `IsVoid` rules that variant out. The two axes are independent, which is why narrowing +behaves identically through a borrow and through an owned value. + +The `T: 'a` bound and the `: 'a` bound on the associated type are what keep the projection well-formed: +a payload cannot be borrowed for longer than it lives, and the resulting storage type cannot outlive the +borrow either. + +## Gotchas + +**`IsOwned` is unused by CGP.** It is a legal marker with no consumer, so selecting it means writing the +machinery that uses it yourself. + +**`IsOwned` is not in the prelude.** Import it from `cgp::core::field::impls`. `IsRef` and `IsMut` are. + +**This is not [`MapType`](./map_type.md).** One decides presence per field, the other decides ownership +across the whole borrowed view, and a generated borrowed type carries both. An error naming the wrong one +usually means the owned and borrowed forms have been crossed. + +**The associated type takes a lifetime as well as a type.** A bound over it is more verbose than a +`MapType` bound, and eliding the lifetime rarely works. + +**A mutable extractor cannot coexist with another borrow of the same value**, which is ordinary borrow +checking rather than anything CGP adds — but it surfaces as an error about the companion type, which +reads as though the machinery is at fault. + +## Related constructs + +- [`MapType`](./map_type.md) — the per-field presence marker this composes with. +- [`HasExtractorRef`](./has_extractor_ref.md) and [`HasExtractorMut`](./has_extractor_mut.md) — the two + accessors that fix the outer marker. +- [`ExtractField`](./extract_field.md) — the narrowing that works identically through a borrow. +- [`ToFieldsRef`](./to_fields_ref.md) — the record side's answer to the same problem. +- [`HasFieldsRef`](./has_fields_ref.md) — the borrowed shape it produces. +- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the borrowed companion. +- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain underneath. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — matching a variant without consuming the + value. + +## Source + +- [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type_ref.rs) + — the trait +- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) + — `IsRef`, `IsMut`, `IsOwned` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monad.md b/docs/reference/traits/monad.md deleted file mode 100644 index 4c6913ad..00000000 --- a/docs/reference/traits/monad.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -sidebar_label: 'Monad traits' ---- - -# Monad traits - -`MonadicTrans`, `MonadicBind`, `LiftValue`, and `ContainsValue`. - -## What it's for - -A [monadic pipeline](/docs/concepts/monadic-handlers) chains a list of steps where each step may either continue -or short-circuit — the familiar `?`-style behaviour, expressed as composable providers rather than as syntax. To -build one, the machinery needs to know three things about the monad it is running under: which branch of an -output continues, which branch stops, and how values move between them. - -A monad in CGP is a zero-sized marker — `IdentMonadic`, `OkMonadic`, `ErrMonadic`, and their transformer forms — -and these four traits are what give that marker meaning. Each answers one of the separable questions: - -- **`MonadicBind`** — given a continuation, what provider runs one bind step? -- **`ContainsValue`** — for a given output type, what value sits beneath this monad's wrapper? -- **`LiftValue`** — how does a value get back *into* that output type? -- **`MonadicTrans`** — how does this monad stack on top of another? - -Keeping them apart is what lets one marker serve all four roles, and what lets monads stack by composing their -implementations. - -**These are plain capability traits, not CGP components.** They have no generated provider trait, no -`…Component` marker, and are never wired through -[`delegate_components!`](../macros/delegate_components.md) — the [monad providers](../providers/monad_providers.md) -consume them as ordinary trait bounds while folding a pipeline at compile time. - -## Using it - -**None of the four is in the prelude.** Import them from `cgp::extra::monad::traits`. In practice you will import -them only when *defining a monad of your own*; using the existing ones means naming -[`PipeMonadic`](../providers/monad_providers.md) and a marker in a wiring entry, with no trait in sight. - -### `MonadicBind` - -```rust -pub trait MonadicBind { - type Provider; -} -``` - -The parameter is the continuation — the handler that should run on the continue branch — and the associated type -is the bind provider that wraps it. For the base monads this resolves to a `BindOk` or `BindErr` provider; for -`IdentMonadic` it is the continuation unchanged, which is what makes the identity monad free. - -### `ContainsValue` - -```rust -pub trait ContainsValue { - type Value; -} -``` - -`Output` is the full output type a step produces; `Value` is what is carried in the branch this monad threads -forward. A continuation consumes that value, or a deeper monad layer unwraps it further. - -### `LiftValue` - -```rust -pub trait LiftValue { - type Output; - - fn lift_value(value: Value) -> Self::Output; - fn lift_output(output: Output) -> Self::Output; -} -``` - -Two methods for the two branches a bind step takes. `lift_value` wraps a bare value from the continue or -short-circuit branch into the final output; `lift_output` re-wraps a value already in the inner shape, forwarding -a continuation's computed result. - -### `MonadicTrans` - -```rust -pub trait MonadicTrans { - type M; -} -``` - -`M` is the base monad being transformed and the associated `M` is the resulting stack. This is what lets -`OkMonadic` be written as `OkMonadicTrans` when a pipeline operates over a nested result, layering -one behaviour on top of another. - -## Examples - -The traits are consumed rather than called, so the thing to read is what each marker's impls *say* — because that -is what decides how a pipeline behaves. - -**`IdentMonadic` implements all four as identities**, which is why it threads every value forward and never -short-circuits. `MonadicTrans` returns `M` unchanged, `MonadicBind` returns `Provider` unchanged, -`ContainsValue::Value` is `T`, and `LiftValue` is the identity in both directions. A pipeline under -`IdentMonadic` is therefore just function composition. - -**`ErrMonadic` and `OkMonadic` are mirror images over a `Result`**, and the mirroring is the whole design: - -| | continue branch | short-circuits on | -|---|---|---| -| `ErrMonadic` | `Ok` | `Err` | -| `OkMonadic` | `Err` | `Ok` | - -For `ErrMonadic`, `ContainsValue>::Value` is `T` — the `Ok` payload threads forward — and -`lift_value` is `Ok`. For `OkMonadic` the roles swap: `Value` is `E` and `lift_value` is `Err`. So `ErrMonadic` is -the ordinary `?` behaviour, and `OkMonadic` is the inverted one that runs until something succeeds — useful for a -fallback chain. - -**The transformer forms delegate one layer down.** `OkMonadicTrans` and `ErrMonadicTrans` implement the same -traits by peeling their own `Result` layer and handing the rest to `M`, requiring -`M: ContainsValue>`. Their `MonadicTrans` impls compose, so a stack like -`OkMonadicTrans` resolves layer by layer — which is how monads reach arbitrary depth over nested -result types. - -## When to reach for it, and when not - -**Reach for the [monad providers](../providers/monad_providers.md), not these traits.** Building a pipeline means -wiring `PipeMonadic` with a monad marker and a handler list; the traits are what that provider bounds on -internally. - -The one real reason to name them is **defining a new monad**. If you need short-circuiting over a type that is not -`Result` — an `Option`, a custom two-branch enum — implementing the four traits for a new marker is the supported -extension point, and the mirror-image `OkMonadic`/`ErrMonadic` pair is the model to copy. - -And the alternatives to prefer when you do *not* need short-circuiting: - -- **[Handler combinators](../providers/handler_combinators.md)** — `ComposeHandlers` and `PipeHandlers` chain - handlers without a branch. If every step in your pipeline runs unconditionally, these are simpler and you should - not involve a monad at all. -- **Ordinary `?` in one provider body** — if the whole chain lives in a single implementation, Rust's own operator - is clearer than any composition. The monadic providers earn their keep when the *steps are separately wired*, so - each application can swap or reorder them. -- **[`TryComputer`](../components/try_computer.md) or [`Handler`](../components/handler.md)** — for a single - fallible step, the fallible members of the handler family already carry the error, and no pipeline is needed. - -## Under the hood - -:::note - -### Advanced - -This section shows how a pipeline is folded from these traits. You do not need it to use a monad, but it is what -makes the division into four traits look inevitable rather than arbitrary. - -::: - -The traits divide the way they do because building a pipeline needs three separable decisions, taken at different -times. - -**Folding the list** is `MonadicTrans` and `MonadicBind`. `PipeMonadic` walks the handler list and, for each step, -asks the monad to turn the continuation built so far into a bind step. `MonadicTrans` is what applies one monad as -a transformer over another while doing so, which is how a stacked monad is resolved before any binding happens. - -**Running one step** is `ContainsValue` and `LiftValue`. The `BindOk` and `BindErr` providers use them in their -[`Computer`](../components/computer.md) and `AsyncComputer` impls: `ContainsValue` says what the underlying value -beneath the wrapper is, so the step knows what to hand the continuation, and `LiftValue` puts a result back into -the output type — `lift_value` for the branch that short-circuits, `lift_output` for the branch that forwarded to -the continuation. - -**Stacking** is `MonadicTrans` again, applied to the monads rather than to the handlers. Because the transformer -forms implement `ContainsValue` and `LiftValue` by delegating to the base monad, a two-layer stack unwraps two -`Result` layers in order, and an *n*-layer stack unwraps *n* — with no code specific to any depth. - -Pipelines built this way implement the [`Computer`](../components/computer.md) family, so they slot into the same -wiring as any other handler. The whole fold happens during trait resolution; a monadic pipeline is not a runtime -structure. - -## Gotchas - -**None of the four is in the prelude.** Import from `cgp::extra::monad::traits`. - -**`OkMonadic` short-circuits on `Ok`, not on `Err`.** The naming reads as "the monad *for* `Ok`" and means "the -monad whose continue branch is `Err`". `ErrMonadic` is the one that behaves like `?`. Getting these the wrong way -round produces a pipeline that runs exactly when you expected it to stop. - -**These are not components and cannot be wired.** There is no `…Component` marker, so they never appear in a -[`delegate_components!`](../macros/delegate_components.md) block. What gets wired is the provider that consumes -them. - -**A stack must be written in layer order.** `OkMonadicTrans` and `ErrMonadicTrans` unwrap -their `Result` layers in opposite orders and are not interchangeable. - -**`LiftValue` has two methods for a reason.** Implementing `lift_output` as `lift_value` — or forgetting the -distinction — collapses the two branches and silently changes what a pipeline does on a short-circuit. - -**A new monad needs all four traits, plus the transformer form to stack.** Implementing three of them yields a -marker that works in some positions and fails to resolve in others, with an error naming the missing trait rather -than the gap. - -## Related constructs - -- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the monad markers; - what you actually wire. -- [Handler combinators](../providers/handler_combinators.md) — `ComposeHandlers` and `PipeHandlers`, composition - without a short-circuit branch. -- [`Computer`](../components/computer.md) — the component family a monadic pipeline implements. -- [`TryComputer`](../components/try_computer.md) and [`Handler`](../components/handler.md) — the fallible members - a single step usually is. -- [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. - -The ideas behind it: - -- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads compose. -- [Handlers](/docs/concepts/handlers) — the computation family these pipelines are built from. - -## Source - -- The traits: [`cgp-monad/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/traits) - — `monadic_trans.rs`, `bind.rs`, `lift.rs`, `value.rs` -- The per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) - — `ident.rs`, `ok.rs`, `err.rs` - ---- - -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monadic_bind.md new file mode 100644 index 00000000..dcb5e64d --- /dev/null +++ b/docs/reference/traits/monadic_bind.md @@ -0,0 +1,161 @@ +--- +sidebar_label: 'MonadicBind' +--- + +# `MonadicBind` + +Turning a continuation into one bind step of a monadic pipeline. + +## What it's for + +A [monadic pipeline](/docs/concepts/monadic-handlers) chains steps where each may either continue or +short-circuit — the familiar `?`-style behaviour, expressed as composable providers rather than as +syntax. Folding such a pipeline means asking the monad, once per step: *given everything built so far, +what provider runs one bind?* + +`MonadicBind` is that question: + +```rust +pub trait MonadicBind { + type Provider; +} +``` + +`Self` is the monad marker. The parameter is the **continuation** — the handler that should run on the +continue branch — and the associated type is the **bind provider** that wraps it. For the base monads +this resolves to a [`BindOk` or `BindErr`](../providers/monad_providers.md) provider; for `IdentMonadic` +it is the continuation unchanged, which is what makes the identity monad free. + +It is one of four traits that give a monad marker its meaning, alongside +[`ContainsValue`](./contains_value.md), [`LiftValue`](./lift_value.md), and +[`MonadicTrans`](./monadic_trans.md). Keeping them apart is what lets one marker serve all four roles. + +**This is a plain capability trait, not a CGP component.** It has no generated provider trait, no +`…Component` marker, and is never wired through +[`delegate_components!`](../macros/delegate_components.md) — the +[monad providers](../providers/monad_providers.md) consume it as an ordinary trait bound while folding a +pipeline at compile time. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::monad::traits`: + +```rust +use cgp::extra::monad::traits::MonadicBind; +``` + +In practice you import it only when **defining a monad of your own**. Using the existing ones means +naming [`PipeMonadic`](../providers/monad_providers.md) and a marker in a wiring entry, with no trait in +sight. + +There is no method. The whole trait is a type-level function from a continuation to the provider that +binds it. + +## Examples + +The trait is consumed rather than called, so the thing to read is what each marker's impl *says* — +because that is what decides how a pipeline behaves. + +**`IdentMonadic` implements it as the identity**: `MonadicBind::Provider` is `Provider` +unchanged. Nothing wraps the continuation, nothing branches, and a pipeline under `IdentMonadic` is +therefore just function composition. + +**`ErrMonadic` and `OkMonadic` wrap the continuation in a bind provider**, and the two are mirror images +over a `Result`: + +| | continue branch | short-circuits on | bind provider | +|---|---|---|---| +| `ErrMonadic` | `Ok` | `Err` | `BindOk` | +| `OkMonadic` | `Err` | `Ok` | `BindErr` | + +So `ErrMonadic` gives the ordinary `?` behaviour, and `OkMonadic` the inverted one that runs until +something succeeds — useful for a fallback chain. + +**The transformer forms delegate one layer down.** `OkMonadicTrans` and `ErrMonadicTrans` bind their +own `Result` layer and hand the rest to `M`, which is how a stack reaches arbitrary depth. + +## When to reach for it, and when not + +**Reach for the [monad providers](../providers/monad_providers.md), not this trait.** Building a pipeline +means wiring `PipeMonadic` with a monad marker and a handler list; this is what that provider bounds on +internally. + +The one real reason to name it is **defining a new monad**, where you implement all four traits for a new +marker. Implementing this one alone yields a marker that folds a pipeline and then fails to resolve when a +step tries to run, because the running half is [`ContainsValue`](./contains_value.md) and +[`LiftValue`](./lift_value.md). + +And the alternatives to prefer when you do *not* need short-circuiting: + +- **[Handler combinators](../providers/handler_combinators.md)** — `ComposeHandlers` and `PipeHandlers` + chain handlers without a branch. If every step runs unconditionally, do not involve a monad at all. +- **Ordinary `?` in one provider body** — if the whole chain lives in a single implementation, Rust's own + operator is clearer than any composition. + +## Under the hood + +:::note + +### Advanced + +This section shows where the fold uses it. + +::: + +[`PipeMonadic`](../providers/monad_providers.md) walks the handler list and, for each step, asks the monad +to turn the continuation built so far into a bind step — which is this trait. Because the walk proceeds +from the end of the list backwards, `Provider` at each stage is everything that follows the current step, +and the result is a single nested provider by the time the list is exhausted. + +[`MonadicTrans`](./monadic_trans.md) is what applies one monad as a transformer over another while that +fold happens, so a stacked monad is resolved *before* any binding does. The pair is therefore the +list-folding half of the four traits, while [`ContainsValue`](./contains_value.md) and +[`LiftValue`](./lift_value.md) are the step-running half. + +The whole fold happens during trait resolution. A monadic pipeline is not a runtime structure, and the +provider it resolves to implements the [`Computer`](../components/computer.md) family like any other +handler. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::monad::traits`. + +**It is not a component and cannot be wired.** There is no `…Component` marker, so it never appears in a +[`delegate_components!`](../macros/delegate_components.md) block. What gets wired is the provider that +consumes it. + +**`OkMonadic` short-circuits on `Ok`, not on `Err`.** The naming reads as "the monad *for* `Ok`" and means +"the monad whose continue branch is `Err`". [`ErrMonadic`](../providers/monad_providers.md) is the one +that behaves like `?`. Getting these the wrong way round produces a pipeline that runs exactly when you +expected it to stop. + +**A new monad needs all four traits, plus the transformer form to stack.** Implementing three of them +yields a marker that works in some positions and fails to resolve in others, with an error naming the +missing trait rather than the gap. + +## Related constructs + +- [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) — the two traits that run one + bind step, where this one only builds it. +- [`MonadicTrans`](./monadic_trans.md) — stacking one monad on another during the same fold. +- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the monad + markers; what you actually wire. +- [Handler combinators](../providers/handler_combinators.md) — composition without a short-circuit + branch. +- [`Computer`](../components/computer.md) — the component family a monadic pipeline implements. +- [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads + compose. + +## Source + +- [`bind.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/bind.rs) + — `MonadicBind` +- Per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monadic_trans.md new file mode 100644 index 00000000..f3c45860 --- /dev/null +++ b/docs/reference/traits/monadic_trans.md @@ -0,0 +1,150 @@ +--- +sidebar_label: 'MonadicTrans' +--- + +# `MonadicTrans` + +Stacking one monad on top of another. + +## What it's for + +A [monadic pipeline](/docs/concepts/monadic-handlers) over a nested output — a `Result` inside a +`Result` — needs to peel more than one layer, and hard-coding a depth would give up the composability +the design exists for. `MonadicTrans` is how a monad is expressed as a *transformer* over another: + +```rust +pub trait MonadicTrans { + type M; +} +``` + +`Self` is the monad being applied, `M` is the base monad being transformed, and the associated `M` is the +resulting stack. That is what lets `OkMonadic` be written as `OkMonadicTrans` when a pipeline +operates over a nested result, layering one behaviour on top of another. + +It is one of four traits that give a monad marker its meaning, and it belongs with +[`MonadicBind`](./monadic_bind.md) as the pipeline-folding half: those two decide the *shape* of the +composed provider, while [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) run +each step. + +**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is +never wired. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::monad::traits`: + +```rust +use cgp::extra::monad::traits::MonadicTrans; +``` + +You import it only when **defining a monad of your own**, and specifically when giving it a transformer +form so it can stack. There is no method; the trait is a type-level function from a base monad to a +composed one. + +## Examples + +What each marker's impl says decides how deeply a pipeline can reach. + +**`IdentMonadic` returns `M` unchanged**, so applying it as a transformer changes nothing — which is what +makes it the neutral element of a stack as well as of a pipeline. + +**The transformer forms compose.** `OkMonadicTrans` and `ErrMonadicTrans` implement the running +traits by peeling their own `Result` layer and handing the rest to `M`, and their `MonadicTrans` impls +compose in the same order, so a stack like `OkMonadicTrans` resolves layer by layer: + +```rust +// conceptually: unwrap the outer Result the OkMonadic way, +// then hand the inner Result to ErrMonadic +type Stacked = OkMonadicTrans; +``` + +An *n*-layer stack unwraps *n* layers with no code specific to any depth, which is the whole payoff. + +**Layer order is meaningful.** `OkMonadicTrans` and `ErrMonadicTrans` unwrap their +`Result` layers in opposite orders and are not interchangeable. + +## When to reach for it, and when not + +**Reach for the [monad providers](../providers/monad_providers.md), not this trait.** Wiring +[`PipeMonadic`](../providers/monad_providers.md) with a marker — including a stacked one — is how a +pipeline is built. + +The reasons to name it are two, and both are narrow. + +- **Defining a new monad that should stack.** The three other traits give a marker meaning on its own; + this one is what lets it sit over another. A marker without it works as a base monad and cannot be a + transformer. +- **Reading a stacked marker in an error.** A resolution failure over a nested result usually names this + trait, and knowing it is the composition step rather than the running step is what tells you the + problem is the stack's shape rather than a step's types. + +If your pipeline runs over a single-layer output, you do not need a transformer at all — use the base +marker directly. + +## Under the hood + +:::note + +### Advanced + +This section shows where the fold uses it. + +::: + +`MonadicTrans` is applied to the **monads** rather than to the handlers, and it runs *before* any binding +does. [`PipeMonadic`](../providers/monad_providers.md) resolves the stacked monad first, then walks the +handler list asking [`MonadicBind`](./monadic_bind.md) to turn each continuation into a bind step. + +Because the transformer forms implement [`ContainsValue`](./contains_value.md) and +[`LiftValue`](./lift_value.md) by delegating to the base monad after handling their own layer, a +two-layer stack unwraps two `Result` layers in order and re-wraps them in reverse — and the same code +serves any depth. That is the sense in which stacking is composition rather than a special case: the +resolved stack is just another marker, and everything downstream treats it as one. + +The whole fold happens during trait resolution, so a stacked monadic pipeline is not a runtime structure. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::monad::traits`. + +**It is not a component and cannot be wired.** What gets wired is the provider that consumes it. + +**A stack must be written in layer order.** `OkMonadicTrans` and +`ErrMonadicTrans` are different monads, and swapping them produces a pipeline that +short-circuits on the wrong layer. + +**The associated type is also called `M`.** The trait's parameter and its associated type share a name, +which reads oddly in a projection like `>::M` and is easy to misread when +debugging a bound. + +**A base marker without this impl cannot be transformed.** The error names the missing `MonadicTrans` +bound rather than saying the marker is not stackable. + +**A new monad needs all four traits**, and this one only if it should stack. + +## Related constructs + +- [`MonadicBind`](./monadic_bind.md) — the other folding trait, which turns a continuation into a bind + step. +- [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) — the two traits that run one + step, where these two build the pipeline. +- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the + markers, including the transformer forms. +- [`Computer`](../components/computer.md) — the component family a monadic pipeline implements. +- [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads + compose. + +## Source + +- [`monadic_trans.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/monadic_trans.rs) + — `MonadicTrans` +- Per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/mut_field_getter.md b/docs/reference/traits/mut_field_getter.md new file mode 100644 index 00000000..b3a237b7 --- /dev/null +++ b/docs/reference/traits/mut_field_getter.md @@ -0,0 +1,146 @@ +--- +sidebar_label: 'MutFieldGetter' +--- + +# `MutFieldGetter` + +The provider-side mirror of `HasFieldMut` — wired field access that can mutate. + +## What it's for + +[`FieldGetter`](./field_getter.md) is field access in provider-trait shape, so that a context can choose +by wiring which field answers a getter. `MutFieldGetter` is the same thing with mutation: it hands back a +`&mut` rather than a `&`. + +```rust +pub trait MutFieldGetter: FieldGetter { + fn get_field_mut(context: &mut Context, tag: PhantomData) -> &mut Self::Value; +} +``` + +It stands to [`FieldGetter`](./field_getter.md) exactly as [`HasFieldMut`](./has_field_mut.md) stands to +[`HasField`](./has_field.md): a **supertrait extension** rather than an alternative, with the field's +type inherited from the supertrait's `Value`. `Self` is the provider; `Context` is the type being +mutated. + +Completing the square, the four traits divide on two axes — consumer versus provider, and read versus +write: + +| | you bound against | you wire | +|---|---|---| +| read | [`HasField`](./has_field.md) | [`FieldGetter`](./field_getter.md) | +| write | [`HasFieldMut`](./has_field_mut.md) | `MutFieldGetter` | + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +As with its immutable sibling you rarely name the trait. What you write is a wiring entry naming a +provider that implements it — [`UseField`](../providers/use_field.md) does, so a getter component wired +to `UseField` supports both the read and the write. + +Writing an impl by hand is the escape hatch for a provider whose mutable access is not a plain field +read, and it is an ordinary trait impl on a marker type of your own. Implementing it means implementing +[`FieldGetter`](./field_getter.md) too, since that is the supertrait. + +## Examples + +A getter component whose mutable access is chosen by wiring: + +```rust +use cgp::prelude::*; + +#[cgp_getter(CounterGetter)] +pub trait HasCounter { + fn counter(&self) -> &u64; +} + +#[derive(HasField)] +pub struct App { + pub request_count: u64, +} + +delegate_components! { + App { + CounterGetterComponent: UseField, + } +} +``` + +**Environmental context, self-targeted.** The getter reads `request_count` though it is named `counter`, +and because [`UseField`](../providers/use_field.md) implements `MutFieldGetter` as well, a provider that +holds `&mut App` can write through the same wiring. + +## When to reach for it, and when not + +**Wire it only when the mutable access must be chosen per context**, which is rarer than the read case +and rarer still than mutation generally. + +- **Use an [`#[implicit]`](../attributes/implicit.md) argument** for a field the implementation reaches + on its own context. The access rules on that page cover mutable access, and no provider is involved. +- **Use [`HasFieldMut`](./has_field_mut.md)** when the implementation should simply *require* mutable + access rather than have it wired. +- **Use [`FieldGetter`](./field_getter.md)** when the wired access is read-only, which is the common case + — requiring mutation narrows what a context can supply for no benefit. +- **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable and + threads state through handler outputs instead. + +## Under the hood + +:::note + +### Advanced + +This section is short, because the machinery is [`FieldGetter`](./field_getter.md#under-the-hood)'s. + +::: + +`MutFieldGetter` adds one method to its supertrait and no new resolution path: a provider that implements +[`FieldGetter`](./field_getter.md) and can also produce a `&mut` implements this too, and +[`UseField`](../providers/use_field.md) does for any context whose field is derived. + +The route from a wired getter back to a context's own fields runs through +[`HasFieldMut`](./has_field_mut.md), whose `DerefMut` forwarding carries the `'static` bound on the +target that its immutable counterpart does not — so a context behind a smart pointer holding borrowed +data can satisfy the wired read and not the wired write. + +## Gotchas + +**`Self` is the provider, not the context.** The context is the first type parameter, and it arrives as +`&mut Context` in the method rather than as `&mut self`. + +**Implementing it means implementing [`FieldGetter`](./field_getter.md).** It is a supertrait, so the +read half is not optional. + +**`Value` lives on the supertrait**, so pin it there rather than redeclaring it. + +**The `'static` bound behind `DerefMut` can bite.** A wired read that resolves and a wired write that +does not usually means the context is behind a smart pointer over borrowed data — see +[`HasFieldMut`](./has_field_mut.md#gotchas). + +**Requiring it where a read would do narrows the contexts that fit**, since a provider holding `&Context` +cannot satisfy it. + +## Related constructs + +- [`FieldGetter`](./field_getter.md) — the supertrait, and where the wired form is explained in full. +- [`HasFieldMut`](./has_field_mut.md) — the consumer side you bound against. +- [`HasField`](./has_field.md) — the read half of the consumer side. +- [`UseField`](../providers/use_field.md) — the provider that implements both halves. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that makes a getter a full component. +- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to reach a field. +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that key a field. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the duality this trait is + an instance of. + +## Source + +- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs) + — `MutFieldGetter`, `HasFieldMut`, and the `DerefMut` forwarding + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional_fields.md b/docs/reference/traits/optional_fields.md deleted file mode 100644 index ea4e4d52..00000000 --- a/docs/reference/traits/optional_fields.md +++ /dev/null @@ -1,300 +0,0 @@ ---- -sidebar_label: 'Optional-field traits' ---- - -# Optional-field traits - -The builder and extractor traits for optional and defaulted fields. - -## What it's for - -The core [builder family](./has_builder.md) is deliberately strict: a partial record becomes its concrete struct -only once **every** field is set, because `FinalizeBuild` is implemented solely on the all-present -configuration. That strictness is what catches a missing field at compile time — and it is too rigid for a record -where some fields have sensible defaults, or are genuinely allowed to be absent. - -These traits relax it in two controlled ways, without giving up the machinery underneath. - -**Defaulted finalization** fills any unset field from `Default` on the way out, so a record can be completed -without setting everything. **Optional fields** re-mark every field as an `Option`, which makes absence a -*runtime* condition — fields can then be set and re-set freely, and finalizing either requires presence with an -error or falls back to defaults. - -The whole layer is composition rather than new mechanism. It reuses -[`UpdateField`](./has_builder.md) to move individual fields, [`TransformMapFields`](./map_type.md) to re-wrap a -whole record at once, and the [`MapType`](./map_type.md) markers `IsPresent`, `IsNothing`, and `IsOptional` to -name each state. Read it as a small set of transforms plus the entry points that drive them. - -## Using it - -**Nothing here is in the prelude.** Everything comes from `cgp::extra::field::impls`: - -```rust -use cgp::extra::field::impls::{ - CanBuildWithDefault, CanFinalizeWithDefault, FinalizeOptional, HasOptionalBuilder, SetOptional, -}; -``` - -The traits divide into the two capabilities, plus the two transform markers that power them. - -### Defaulted finalization - -`CanFinalizeWithDefault` finalizes a partial record, defaulting whatever is unset: - -```rust -pub trait CanFinalizeWithDefault { - type Output; - fn finalize_with_default(self) -> Self::Output; -} -``` - -It is implemented for any partial value whose fields can be transformed to all-present, and its body is the -layer's core motion in one line: re-wrap every field to `IsPresent`, then call the ordinary -[`finalize_build`](./has_builder.md). The strict presence check still runs — it just always passes, because the -transform guaranteed presence first. - -`CanBuildWithDefault` is the one-call version that also copies from a source: - -```rust -pub trait CanBuildWithDefault { - fn build_with_default(source: Source) -> Self; -} -``` - -It chains `builder()`, [`build_from`](./cast.md), and `finalize_with_default`, which makes it the field-level -"widening cast" — turning a `Point2d` into a `Point3d` whose extra `z` is `0`, naming no field explicitly. - -### Optional fields - -`HasOptionalBuilder` starts a builder in which every field is already optional: - -```rust -pub trait HasOptionalBuilder { - type Builder; - fn optional_builder() -> Self::Builder; -} -``` - -`ToOptional` is the conversion it composes with, re-marking an existing partial value's every field to -`IsOptional`. `SetOptional` then sets one: - -```rust -pub trait SetOptional { - type Value; - fn set(self, _tag: PhantomData, value: Self::Value) -> Self; - fn set_optional( - self, - _tag: PhantomData, - value: Self::Value, - ) -> (Option, Self); -} -``` - -**The crucial detail is that both methods return `Self`.** The field's marker is `IsOptional` before *and* after, -so the builder's type does not change — which is what makes an optional field settable repeatedly, unlike the -core `build_field` that consumes an absent slot exactly once. `set` discards whatever it replaced; -`set_optional` hands it back. - -`FinalizeOptional` is the strict way out: - -```rust -pub trait FinalizeOptional: PartialData { - fn finalize_optional(self) -> Result; -} -``` - -It succeeds only if every field holds a value, and the error is the **first missing field's own name** as a -`&'static str` — so a caller learns which field was left unset. - -### The two transforms - -`TransformMapDefault` and `TransformOptional` are the [`TransformMap`](./map_type.md) markers that do the -per-field work. `TransformMapDefault` targets `IsPresent` — a present field passes through, an absent one becomes -its default, an optional one becomes its contents or the default. `TransformOptional` targets `IsOptional` — -present becomes `Some`, absent becomes `None`. You name these only when extending the layer. - -## Examples - -The optional workflow starts an all-optional builder, sets fields freely, and picks a finalize strategy at the -end: - -```rust -use cgp::extra::field::impls::{ - CanFinalizeWithDefault, FinalizeOptional, HasOptionalBuilder, SetOptional, -}; -use cgp::prelude::*; - -#[derive(CgpData)] -pub struct Context { - pub foo: String, - pub bar: u64, -} - -// Every field set: finalize_optional succeeds. -let builder = Context::optional_builder() - .set(PhantomData::, "foo".to_owned()) - .set(PhantomData::, 42); - -// Setting an already-set field hands back what it replaced. -let (replaced, builder) = builder.set_optional(PhantomData::, "bar".to_owned()); -assert_eq!(replaced, Some("foo".to_owned())); - -let context = builder.finalize_optional().unwrap(); -assert_eq!(context.foo, "bar"); -``` - -Leave a field unset and the two strategies diverge — which is the whole point of deferring the choice to the -finalize call: - -```rust -// finalize_with_default fills `bar` from Default -let context = Context::optional_builder() - .set(PhantomData::, "foo".to_owned()) - .finalize_with_default(); - -assert_eq!(context.bar, 0); -``` - -Had that used `finalize_optional`, it would have returned `Err("bar")` instead of defaulting. - -The defaulted-build path widens one record into another in a single call: - -```rust -use cgp::extra::field::impls::CanBuildWithDefault; - -#[derive(Debug, Clone, Eq, PartialEq, CgpData)] -struct Point2d { x: u64, y: u64 } - -#[derive(Debug, Clone, Eq, PartialEq, CgpData)] -struct Point3d { x: u64, y: u64, z: u64 } - -let point_3d = Point3d::build_with_default(Point2d { x: 1, y: 2 }); - -assert_eq!(point_3d, Point3d { x: 1, y: 2, z: 0 }); // z defaulted -``` - -## When to reach for it, and when not - -**Reach for this layer when the core builder's strictness is genuinely wrong for the record**, and stay on the -core builder otherwise. The strictness is a feature — it is what turns a missing field into a compile error — so -relaxing it should be a decision rather than a convenience. - -- **`finalize_with_default`** when unset fields have meaningful defaults and silence is the right outcome. -- **`finalize_optional`** when absence is an error you want to *report* rather than paper over. The two are the - same builder finalized differently, and the choice is made at the call site — so the same value can go either - way. -- **`optional_builder` and `set`** when fields must be settable in any order and more than once, which the core - `build_field` cannot do. -- **`build_with_default`** for a one-call widening from a narrower record. -- **Stay on the [core builder](./has_builder.md)** when every field is genuinely required. You lose the - compile-time completeness check by moving here, and that check is the reason the builder family exists. -- **Reach for a hand-written builder** when the *logic* is the point — validation at finalize, interdependent - fields, computed defaults that are not `Default::default()`. This layer models presence and defaulting, and - nothing else. - -One thing to notice about the trade: `finalize_optional` moves a missing field from a compile error to a -`Result`, and its error type is a `&'static str` field name rather than a structured value. That is enough to -report which field is missing and not enough to match on programmatically. - -## Under the hood - -:::note - -### Advanced - -This section shows how both paths reuse one recursion. It is the shortest explanation of why the defaulted and -optional workflows behave so symmetrically. - -::: - -Both capabilities are the **same** [`transform_map_fields`](./map_type.md) recursion with a different marker, which -is why they mirror each other so exactly: - -```rust -impl CanFinalizeWithDefault for Builder -where - Builder: TransformMapFields, - Builder::Output: FinalizeBuild, -{ - type Output = Output; - - fn finalize_with_default(self) -> Output { - self.transform_map_fields().finalize_build() - } -} -``` - -`CanFinalizeWithDefault` drives `TransformMapDefault` toward `IsPresent`; `ToOptional` drives -`TransformOptional` toward `IsOptional`. Both walk the same field spine, both rebuild the partial type one field -at a time through [`UpdateField`](./has_builder.md), and neither changes a value's runtime layout beyond wrapping -or unwrapping an `Option` or substituting a default. - -`SetOptional` is the one that does *not* transform the whole record — it is a single `UpdateField` call writing -`Some(value)` into an `IsOptional` slot, with `Mapper = IsOptional, Output = Context` pinning the type unchanged -on both sides. That pinning is exactly what allows repeated sets. - -`FinalizeOptional` walks the target's [`HasFields`](./has_fields.md) spine itself rather than using a transform: -for each field it pulls the `Option` out with `UpdateField`, writes it back as `IsPresent` with -[`BuildField`](./has_builder.md) if it is `Some`, and returns `Err(Tag::VALUE)` — the field's name recovered as a -static string through [`StaticString`](./static_format.md) — the moment it finds a `None`. Only if every field -yields a value does it reach `finalize_build`. - -The strict, all-present `FinalizeBuild` from the core remains the **only** way a partial value becomes a concrete -struct. Everything here simply guarantees the all-present configuration is reached before it is invoked. - -## Gotchas - -**Nothing here is in the prelude.** Import from `cgp::extra::field::impls`. - -**`set` returns `Self`, so the builder's type never changes.** That is deliberate — it is what allows re-setting — -but it also means the type carries no record of *which* fields you have set, which is why finalizing has to check -at run time. - -**Moving to an optional builder gives up the compile-time completeness check.** With the core builder a missing -field is a compile error; here it is an `Err` or a silently substituted default. That is the trade, and it is -worth making consciously. - -**`finalize_optional`'s error is a `&'static str`.** It names the first missing field and is not a structured -error. It also reports only the first. - -**`finalize_with_default` needs `Default` on every field's type.** A field whose type has no `Default` makes the -transform unresolvable, and the error names the missing `TransformMap` impl rather than the field. - -**`build_with_default` requires the source to have a shape.** It chains [`build_from`](./cast.md), so the source -needs [`HasFields`](./has_fields.md) — the same requirement as any merge. - -**A field whose type is already `Option` is not the same as an `IsOptional` field.** The former is a value that -happens to be optional and must still be *set*; the latter is a builder slot that may be empty. Conflating them -produces an `Option>`. - -## Related constructs - -- [`HasBuilder`](./has_builder.md) — the core family this layer relaxes, and where `FinalizeBuild` and - `UpdateField` are documented. -- [`MapType`](./map_type.md) — `TransformMap`, `TransformMapFields`, and the `IsOptional` marker this layer runs - on. -- [`CanUpcast`](./cast.md) — where `CanBuildFrom` and `build_from` are documented. -- [`HasFields`](./has_fields.md) — the shape both the transform and `FinalizeOptional` walk. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the partial types these operate on, - also through [`#[derive(CgpData)]`](../derives/derive_cgp_data.md). -- [`StaticString`](./static_format.md) — how `FinalizeOptional` recovers a field's name as a string. -- [`ExtractField`](./extract_field.md) — the enum-side counterpart of the record machinery. - -The ideas behind it: - -- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence fits. - -## Source - -- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs) - — `CanBuildWithDefault`, `CanFinalizeWithDefault`, `TransformMapDefault` -- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs) - — `HasOptionalBuilder`, `ToOptional`, `TransformOptional` -- [`set_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/set_optional.rs) - — `SetOptional` -- [`finalize_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/finalize_optional.rs) - — `FinalizeOptional` - ---- - -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/partial_data.md b/docs/reference/traits/partial_data.md new file mode 100644 index 00000000..c544977c --- /dev/null +++ b/docs/reference/traits/partial_data.md @@ -0,0 +1,151 @@ +--- +sidebar_label: 'PartialData' +--- + +# `PartialData` + +Naming the concrete type a partial value is on its way to becoming. + +## What it's for + +A partial record is a companion type — `__PartialPerson` — and generic code holding +one often needs to know what it will *become* before it is complete: to name the return type of a +routine, to state a bound, to decide what to do next. `PartialData` answers that: + +```rust +pub trait PartialData { + type Target; +} +``` + +`Target` is the concrete struct or enum the partial value corresponds to. **It is implemented for every +configuration**, complete or not, which is exactly what makes it useful: the destination is knowable from +the first `builder()` call, long before any field is set. + +That is the division of labour with [`FinalizeBuild`](./finalize_build.md), which is implemented **only** +at the all-present configuration. One says where you are going; the other says you have arrived. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method — naming a type is not +an operation. + +You bound on it when a signature must mention the destination while holding a partial value: + +```rust +fn describe(partial: Partial) -> &'static str +where + Partial: PartialData, +{ + core::any::type_name::() +} +``` + +The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md) for a record and +[`#[derive(ExtractField)]`](../derives/derive_extract_field.md) for an enum — **both** partial families +implement it, which is worth knowing because it is the one trait the builder and extractor sides share +directly. + +## Examples + +Its most visible use is as [`FinalizeBuild`](./finalize_build.md)'s supertrait, which is how a finalize +knows what to return: + +```rust +pub trait FinalizeBuild: PartialData { + fn finalize_build(self) -> Self::Target; +} +``` + +`Self::Target` in that signature comes from here. Without it the finalize would need its own associated +type, and the destination would be unnameable until the value was complete. + +The same appears in [`FinalizeOptional`](./finalize_optional.md), which returns +`Result` — again projecting the destination through this trait rather than +declaring one of its own. + +## When to reach for it, and when not + +**Bound on it when generic code needs the destination type mid-build**, and reach for the more specific +traits otherwise. + +- **[`FinalizeBuild`](./finalize_build.md)** when the value is complete and should become the struct. It + supertraits this, so bounding on both is redundant. +- **[`HasBuilder`](./has_builder.md)** when you have the concrete type and want a builder. That is the + opposite direction: `Person::Builder` from `Person`, rather than `Target` from a partial. +- **`PartialData`** when the code holds a partial value of unknown completeness and must name what it + belongs to — a signature, a `where` clause, an error message. +- **[`TransformMapFields`](./transform_map_fields.md)** requires it, which is the other place it shows up + in a bound rather than as a projection. + +## Under the hood + +:::note + +### Advanced + +This section explains why the trait is separate from the finalize. + +::: + +The derive emits one impl covering every configuration at once, by leaving the markers generic: + +```rust +// conceptually, for the record companion: +// impl PartialData for __PartialPerson { +// type Target = Person; +// } +``` + +Nothing about the markers is constrained, which is what makes the destination available at every step of +a build. Contrast [`FinalizeBuild`](./finalize_build.md), whose impl fixes every marker to `IsPresent`. + +Splitting the two is what lets generic builder code be written against a destination it can name while +still being *unable* to finalize prematurely — the type is known, the conversion is not available. A +single trait carrying both would have to choose one or the other. + +The enum side implements it identically on its extraction companions, with `Target` naming the original +enum, which is how [`HasExtractor`](./has_extractor.md)'s round trip knows what to rebuild. + +## Gotchas + +**It says nothing about completeness.** A `PartialData` bound is satisfied by an empty builder as readily +as by a full one. Requiring completeness is [`FinalizeBuild`](./finalize_build.md). + +**Both families implement it.** A `PartialData` bound admits an extraction remainder as well as a record +builder, which is occasionally what you want and occasionally too permissive. + +**[`FinalizeBuild`](./finalize_build.md) supertraits it**, so naming both in a bound is redundant. + +**`Target` is the original type, not the partial one.** Reading the projection the other way round is the +usual confusion when meeting it in an error. + +**It has no method.** Getting a value of `Target` is a finalize; this only names the type. + +## Related constructs + +- [`FinalizeBuild`](./finalize_build.md) — the subtrait that actually produces the target. +- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — the opposite direction, from + a concrete type to a partial one. +- [`UpdateField`](./update_field.md) — what moves a partial value between configurations. +- [`FinalizeOptional`](./finalize_optional.md) — the optional layer's finalize, which projects `Target` + the same way. +- [`TransformMapFields`](./transform_map_fields.md) — requires this bound. +- [`ExtractField`](./extract_field.md) — the enum family whose companions also implement it. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) and + [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generate the impls. +- [`MapType`](./map_type.md) — the markers a configuration is written in. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder + pattern. + +## Source + +- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs) + — `PartialData` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/product_ops.md b/docs/reference/traits/product_ops.md deleted file mode 100644 index 5b9fb754..00000000 --- a/docs/reference/traits/product_ops.md +++ /dev/null @@ -1,266 +0,0 @@ ---- -sidebar_label: 'AppendProduct, ConcatProduct & MapFields' ---- - -# `AppendProduct`, `ConcatProduct` & `MapFields` - -The type-level operations over product lists. - -## What it's for - -A struct's shape in CGP is a type-level list — a [`Product!`](../macros/product.md) of named fields — and an -enum's is the analogous [`Sum!`](../macros/sum.md). Code that processes such a shape generically often needs to -*compute a new shape from an old one*: add a field, splice two lists together, rewrite every entry the same way. - -These three traits are exactly those three computations, each a pure function from type lists to type lists: - -- **`AppendProduct`** adds one entry at the end. -- **`ConcatProduct`** splices a whole list onto the end. -- **`MapFields`** rewrites every entry through a [`MapType`](./map_type.md) marker. - -They are evaluated by the trait solver while the compiler type-checks, so they carry no runtime cost and impose -no ordering — there is nothing to run. They are the plumbing beneath the higher-level constructs: building a -record appends, merging two concatenates, and producing a partial-record representation maps a marker over every -field. - -**These are the least user-facing traits in the reference.** You will meet them if you write generic code over -shapes, and otherwise only in an error message from code that does. - -## Using it - -**None of the three is in the prelude.** Import them from `cgp::core::field::traits`, and note that the -[`MapType`](./map_type.md) marker `MapFields` takes may need its own import too — `IsPresent`, `IsNothing`, and -`IsVoid` are in the prelude while `IsOptional` is not. - -```rust -use cgp::core::field::impls::IsOptional; -use cgp::core::field::traits::{AppendProduct, ConcatProduct, MapFields}; -``` - -Each trait exposes its result as an associated type and has no methods, because there is nothing to execute. - -### `AppendProduct` - -```rust -pub trait AppendProduct { - type Output; -} -``` - -It recurses down the `Cons` spine, rebuilding each node until it reaches `Nil`, where it inserts -`Cons`. Reading it: every existing entry is preserved in order, and the new one lands last. - -### `ConcatProduct` - -```rust -pub trait ConcatProduct { - type Output; -} -``` - -The same recursion, except that at `Nil` it substitutes the entire `Items` list rather than a single element. So -**append is the single-entry special case of concat**, which is the shortest way to hold both in mind. - -Both have `Nil` identities worth knowing: concatenating onto `Nil` yields the other list unchanged, and -concatenating `Nil` onto a list leaves it unchanged. - -### `MapFields` - -```rust -pub trait MapFields { - type Mapped; -} -``` - -`MapFields` is the transforming one, and the only one defined over **both** spines: it walks `Cons`/`Nil` for a -product and `Either`/`Void` for a sum, applying `Mapper::Map` to each entry. The list's length and order never -change; each entry type `T` becomes `Mapper::Map`. - -Which means the marker decides the whole effect. With `IsPresent` it is the identity; with `IsNothing` every -entry collapses to `()`; with `IsOptional` every entry becomes `Option<_>`; with `IsVoid` every entry becomes -uninhabited. - -## Examples - -Appending and concatenating compute new product types. The results are types, so the check is a type equality -rather than a value comparison: - -```rust -use cgp::core::field::traits::{AppendProduct, ConcatProduct}; -use cgp::prelude::*; - -type Base = Product![Field]; - -// one entry added at the end -type WithPort = >>::Output; -// = Product![Field, Field] - -// a whole list spliced on -type Extra = Product![Field]; -type Full = >::Output; -// = Product![host, port, tls] -``` - -`MapFields` rewrites every entry uniformly. Applying `IsOptional` turns a product of values into a product of -optionals — the shape a partial builder uses to track what is not yet filled: - -```rust -use cgp::core::field::impls::IsOptional; -use cgp::core::field::traits::MapFields; - -type Fields = Product![String, u16, bool]; - -type Optional = >::Mapped; -// = Product![Option, Option, Option] -``` - -and the same marker applies over a sum, which is what lets one operation produce both a partial record and a -partial enum: - -```rust -type Variants = Sum![String, u16]; - -type OptionalVariants = >::Mapped; -// = Sum![Option, Option] -``` - -## When to reach for it, and when not - -**Reach for these when you are writing generic code that computes a shape**, and essentially never otherwise. -They are building blocks the extensible-data machinery uses; the machinery itself is what application code -touches. - -- **`AppendProduct` and `ConcatProduct`** when a routine must describe the shape it *will* produce — a builder - that adds a field, a merge that combines two records — in a signature or an associated type. -- **`MapFields`** when a routine must describe a uniformly re-wrapped shape, which is what a partial - representation is. -- **Use [`HasFields`](./has_fields.md) instead** if you only need a type's *existing* shape. These traits compute - new shapes; they are not how you obtain one. -- **Use the [builder](./has_builder.md) or [extractor](./extract_field.md) family instead** if you are moving - *values* through a shape. These three never touch a value — they only name types — so if you want something to - happen at run time, they are the wrong layer. - -One name worth disambiguating: `MapFields` applies one marker across a whole list, while -[`MapType`](./map_type.md) is a single marker naming one field's storage and `MapField` (singular, on the -[`HasField`](./has_field.md) page) is a lifetime helper for reading a nested field. Three similar names, three -unrelated jobs. - -## Under the hood - -:::note - -### Advanced - -This section shows the recursions. They are short, and reading one makes the others obvious — which is the -quickest way to be able to predict what any of these traits will produce. - -::: - -Each trait is a pair of impls: one for the spine's `Cons` node and one for its terminator. `AppendProduct` keeps -each head and rebuilds the tail, grafting a single-element list at the end: - -```rust -impl AppendProduct for Nil { - type Output = Cons; -} - -impl AppendProduct for Cons -where - Tail: AppendProduct, -{ - type Output = Cons; -} -``` - -`ConcatProduct` is character-for-character the same recursion with one line different — at `Nil` it substitutes -the whole list: - -```rust -impl ConcatProduct for Nil { - type Output = Items; // the only difference -} - -impl ConcatProduct for Cons -where - Tail: ConcatProduct, -{ - type Output = Cons; -} -``` - -That is the precise sense in which append is a special case of concat. - -`MapFields` transforms the head rather than preserving it, and this is the pair that exists twice — once for -each spine: - -```rust -impl MapFields for Cons -where - Mapper: MapType, - Rest: MapFields, -{ - type Mapped = Cons, Rest::Mapped>; -} - -impl MapFields for Nil { - type Mapped = Nil; -} -``` - -The `Either`/`Void` impls mirror these exactly, with `Either` for `Cons` and `Void` for `Nil`. Because the -recursion only ever replaces a head type, the spine's length and shape are structurally preserved — which is why -a mapped product is still a product of the same arity, and a mapped sum still a sum. - -All of this is resolved during type checking. There is no `fn` anywhere on this page. - -## Gotchas - -**None of the three is in the prelude.** Import from `cgp::core::field::traits`. This is the first thing that -goes wrong when reaching for them. - -**The result is an associated type, and the two names differ.** `AppendProduct` and `ConcatProduct` expose -`Output`; `MapFields` exposes `Mapped`. Reaching for the wrong one is a plain unresolved-associated-type error, -but the asymmetry is easy to forget. - -**`MapFields` covers both spines; the other two are product-only.** There is no `AppendSum`. Growing a sum is -not an operation this layer provides. - -**These compute types, not values.** A `MapFields` result type does not wrap anything at run time by -itself — something still has to build the wrapped values, which on a partial record is -[`TransformMapFields`](./map_type.md). - -**Order is preserved, and order is part of the type.** Appending to a product yields a *different* type from -prepending, and two products with the same entries in different orders are unrelated types. - -**A long list means a deep recursion.** These are trait-resolution recursions over the spine, so a very wide -struct costs compile time proportional to its width — one of the places CGP's compile-time cost actually comes -from. - -## Related constructs - -- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the sugar for the lists these operate on. -- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. -- [`HasFields`](./has_fields.md) — where a type's existing shape comes from. -- [`MapType`](./map_type.md) — the markers `MapFields` applies, and the neighbouring trait most easily confused - with it. -- [`Field`](../types/field.md) — the entries a field list is usually made of. -- [`HasBuilder`](./has_builder.md) and [`ExtractField`](./extract_field.md) — the families that move values - through the shapes these compute. -- [`CanUpcast`](./cast.md) — conversions that walk a shape rather than reshape it. - -The ideas behind it: - -- [Extensible records](/docs/concepts/extensible-records) — where computing a new shape is put to work. - -## Source - -- [`append_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/append_product.rs) - — `AppendProduct` -- [`concat_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/concat_product.rs) - — `ConcatProduct` -- [`map_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_fields.rs) - — `MapFields`, over both spines - ---- - -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/set_optional.md b/docs/reference/traits/set_optional.md new file mode 100644 index 00000000..df48b7ec --- /dev/null +++ b/docs/reference/traits/set_optional.md @@ -0,0 +1,166 @@ +--- +sidebar_label: 'SetOptional' +--- + +# `SetOptional` + +Setting one field of an optional builder, as many times as you like. + +## What it's for + +[`BuildField`](./build_field.md) sets an absent field and consumes the slot: the builder's type changes, +and setting the same field twice is a compile error. `SetOptional` is the optional layer's answer, and its +defining property is the opposite: + +```rust +pub trait SetOptional { + type Value; + + fn set(self, _tag: PhantomData, value: Self::Value) -> Self; + + fn set_optional( + self, + _tag: PhantomData, + value: Self::Value, + ) -> (Option, Self); +} +``` + +**Both methods return `Self`.** The field's marker is `IsOptional` before *and* after, so the builder's +type does not change — which is exactly what makes an optional field settable repeatedly. + +The two methods differ only in what they do with whatever was there: `set` discards it, and +`set_optional` hands it back. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::SetOptional; +``` + +`Self` must be an optional builder — one from +[`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md). Calling it on a +core builder does not resolve, because the field's marker is `IsNothing` rather than `IsOptional`. + +`Value` is the field's declared type, so what you pass is an ordinary value rather than an `Option`. +Setting a field to "absent" is not something this trait does; a field starts absent and stays so unless +set. + +## Examples + +Setting fields in any order, and re-setting one: + +```rust +use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +let builder = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .set(PhantomData::, 42); + +// Setting an already-set field hands back what it replaced. +let (replaced, builder) = builder.set_optional(PhantomData::, "bar".to_owned()); + +assert_eq!(replaced, Some("foo".to_owned())); + +let context = builder.finalize_optional().unwrap(); + +assert_eq!(context.foo, "bar"); +``` + +Because `set` returns `Self`, the calls chain exactly as core `build_field` calls do — the difference is +invisible at the call site and lives entirely in the type. + +## When to reach for it, and when not + +**Reach for it when a field may be set more than once, or when the order is not known.** That is the one +thing the core builder cannot express. + +- **[`BuildField`](./build_field.md)** when each field is set exactly once. The compile-time + completeness check it buys is the reason the core family exists. +- **`set`** when whatever was there should simply be replaced. +- **`set_optional`** when the previous value matters — merging, accumulating, warning on a duplicate. +- **[`CanBuildFrom`](./can_build_from.md)** when the values come from another record wholesale rather + than one at a time. + +## Under the hood + +:::note + +### Advanced + +This section shows why the type does not change, which is the trait's whole trick. + +::: + +`SetOptional` is a single [`UpdateField`](./update_field.md) call writing `Some(value)` into an +`IsOptional` slot, with both the source and target markers pinned to `IsOptional`: + +```rust +// conceptually: +// Partial: UpdateField +``` + +`Mapper = IsOptional` requires the field to already be in the optional state, and `Output = Partial` +pins the result to the same type on both sides. **That pinning is exactly what allows repeated sets** — +there is no marker to consume, so no impl becomes unavailable after the first call. + +Contrast [`BuildField`](./build_field.md#under-the-hood), which pins `Mapper = IsNothing` and a target of +`IsPresent`: its `Output` is a *different* type, which is what makes a second call fail to resolve. + +Since the primitive returns the old storage alongside the new value, `set_optional` simply exposes it and +`set` discards it. Under `IsOptional` that old storage is an `Option`, which is why the returned +value is optional even though the argument is not. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**It does not apply to a core builder.** The field must already be `IsOptional`, so start with +[`optional_builder()`](./has_optional_builder.md) or convert with [`to_optional()`](./to_optional.md). + +**The builder's type never changes, so it carries no record of what you have set.** That is deliberate — +it is what allows re-setting — and it is why finalizing has to check at run time. + +**`set_optional` returns `(previous, builder)`, in that order.** Reversing the binding is a type error, +and a confusing one in generic code. + +**The argument is a `Value`, not an `Option`.** There is no "unset" operation; a field left alone +stays absent. + +**A field whose type is already `Option` takes an `Option` here and is stored as +`Option>`.** The outer layer is the builder's presence tracking, and the two are easy to +conflate. + +## Related constructs + +- [`HasOptionalBuilder`](./has_optional_builder.md) — where an optional builder comes from. +- [`ToOptional`](./to_optional.md) — converting an existing builder into one. +- [`FinalizeOptional`](./finalize_optional.md) and + [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the two endings. +- [`BuildField`](./build_field.md) — the strict, set-once counterpart. +- [`UpdateField`](./update_field.md) — the primitive this is one call of. +- [`MapType`](./map_type.md) — the `IsOptional` marker it pins on both sides. +- [`CanBuildFrom`](./can_build_from.md) — filling many fields from another record. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence + fits. + +## Source + +- [`set_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/set_optional.rs) + — `SetOptional` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md index 40e7d1d3..b85fad95 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/static_format.md @@ -1,128 +1,107 @@ --- -sidebar_label: 'StaticFormat, StaticString & ConcatPath' +sidebar_label: 'StaticFormat' --- -# `StaticFormat`, `StaticString` & `ConcatPath` +# `StaticFormat` -Recovering type-level strings and paths back into runtime data. +Writing a type-level string into a formatter — the trait behind `Display` on `Symbol`. ## What it's for -CGP encodes field and variant names as *types* — a [`Symbol!`](../macros/symbol.md) is a length plus a character -list, one node per character — so that names can drive trait resolution. But a program eventually needs those -names as ordinary strings: to name a missing field in an error, to build a key, to render a path. +CGP encodes field and variant names as *types*, so a name can drive trait resolution. Printing one means +turning that type back into characters, and `StaticFormat` is the trait that does it **lazily**, by +writing into a formatter rather than producing a value: -These three traits close that loop, and they divide by *when* the recovery happens. - -**`StaticString`** recovers the string **eagerly**, as a compile-time `&'static str` constant computed by const -evaluation. This is the one to reach for: the decoded string is available wherever a `const` is, and it costs -nothing at run time. +```rust +pub trait StaticFormat { + fn fmt(f: &mut Formatter<'_>) -> Result<(), fmt::Error>; +} +``` -**`StaticFormat`** recovers it **lazily**, by writing into a formatter. It is what backs the `Display` impl on -`Symbol` and `Chars`, so a type-level string can be printed with `{}` or `to_string()`. +Note the absent `self`: there is no runtime value, only the type. It is implemented by recursion over the +character spine — each node writes its own character and defers to the tail, and the terminator writes +nothing. -**`ConcatPath`** works one level up, on paths rather than strings: a [`Path!`](../macros/path.md) is a type-level -list of segments, and joining two of them is splicing one list onto another. It is a pure type-level operation -with no runtime side at all. +**It is what backs the `Display` impls on `Symbol` and `Chars`**, which is how you usually meet it: a +type-level string can be printed with `{}` or `to_string()` because of this trait. ## Using it -The three differ sharply in how reachable they are, and that is the first thing to know. - -**`ConcatPath` is in the prelude.** `use cgp::prelude::*;` names it. - -**`StaticString` is not** — import it from `cgp::core::field::traits`: +**It is not in the prelude.** Import it from `cgp::core::base::traits`: ```rust -pub trait StaticString { - const VALUE: &'static str; -} +use cgp::core::base::traits::StaticFormat; ``` -`VALUE` is the decoded string as a constant. `Symbol` computes a `[u8; LEN]` byte array at -const-evaluation time by walking the character list and UTF-8-encoding each character, then validates those bytes -as UTF-8 and exposes the result. The `LEN` on a `Symbol` is the precomputed **byte** length that sizes that array -— which is why `Symbol!` records a byte length rather than a character count. +That module is where the base type-level crate is re-exported, and it is a different home from its +neighbours: [`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and +[`ConcatPath`](./concat_path.md) — which lives in the same crate as this trait — is in the prelude. +Three neighbouring traits, three different imports. -**`StaticFormat` cannot be named through the `cgp` crate at all.** See the [Gotchas](#gotchas) below; in practice -you reach its effect through `Display` and never the trait. +Most of the time you reach the effect rather than the trait. Any type-level string can be interpolated +or turned into an owned `String` with no import at all: ```rust -pub trait StaticFormat { - fn fmt(f: &mut Formatter<'_>) -> Result<(), fmt::Error>; -} -``` - -Note the absent `self`: there is no runtime value, only the type. It is implemented by recursion over the -character spine — each node writes its own character and defers to the tail, and the terminator writes nothing. +use cgp::prelude::*; -**`ConcatPath`** joins two paths: +let s = ::default(); -```rust -pub trait ConcatPath { - type Output: ?Sized; -} +assert_eq!(s.to_string(), "hello"); +assert_eq!(format!("field: {s}"), "field: hello"); ``` -Both sides may be unsized, since path types are markers. It recurses over the path spine exactly as -[`ConcatProduct`](./product_ops.md) does over a product: each node keeps its head and concatenates onto the tail, -and the terminator becomes the other path — so the result is the first path's segments followed by the second's. +The impls exist for `Chars` — the character spine — and for `Nil`, which terminates it, with `Symbol` +delegating to its inner list. Every type-level string therefore formats, including the empty one. ## Examples -A type-level string recovers both ways, and the two are worth seeing together because the choice between them is -the page's main decision: +Formatting is what a diagnostic or a log line wants, where the name appears once. A `Display` bound is +usually enough, and needs no import: ```rust -use cgp::core::field::traits::StaticString; use cgp::prelude::*; -// lazily, through Display — reconstructed at the point of formatting -let s = ::default(); -assert_eq!(s.to_string(), "hello"); +fn describe(_tag: core::marker::PhantomData) -> String { + format!("missing field `{}`", Tag::default()) +} -// eagerly, as a compile-time constant -assert_eq!(::VALUE, "hello"); +let message = describe(core::marker::PhantomData::); + +assert_eq!(message, "missing field `height`"); ``` -Both round-trip multi-byte Unicode faithfully, and the empty symbol decodes to the empty string: +Bounding on the trait itself is what you reach for when there is no *value* to call `Display` on — the +method is an associated function, so it writes a type's characters without one: ```rust -assert_eq!(::VALUE, "世界你好"); -assert_eq!(::VALUE, ""); +use cgp::core::base::traits::StaticFormat; + +fn write_name(f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + Tag::fmt(f) +} ``` -`ConcatPath` composes two paths at the type level, which is the operation behind chaining nested accessors: +For a name used more than once, the eager form is cheaper and is bounded differently again: ```rust -type Outer = Path!(a.b); -type Inner = Path!(c.d); +use cgp::core::field::traits::StaticString; -type Joined = >::Output; // the path a.b.c.d +assert_eq!(::VALUE, "height"); ``` -Where `StaticString` shows up in real code is recovering a name for an error. The -[optional-field layer](./optional_fields.md)'s `finalize_optional` reports its missing field by returning -`Tag::VALUE` — the field's own name, as a static string, with no allocation. - ## When to reach for it, and when not -**Reach for `StaticString` when you need a name as data, and for `Display` when you need it in a message.** That -is the whole decision. - -- **`StaticString`** for a constant, a key, a comparison, or anywhere the name is used more than once. It is - computed at compile time, so there is no per-call work, and it is the only one of the three that a - `cgp`-dependent crate can bound on. -- **`Display` / `to_string()`** for one-off formatting. Reaching for `StaticFormat` by name is not an option, and - is not needed — the `Display` impls are what it exists to power. -- **`ConcatPath`** when composing paths in generic code, which is nested-accessor territory. If you are writing a - path literally, [`Path!`](../macros/path.md) already gives you the whole thing and there is nothing to - concatenate. +**Reach for `Display` for one-off formatting, [`StaticString`](./static_string.md) for a name you use +more than once, and this trait only when you need to write characters without a value to hand.** -Two things none of these is for. They are **not a general string facility**: `Symbol!` exists to key field and -variant lookups, and building programs out of type-level strings is not what the encoding is for. And they are -**not how you read a field** — recovering a name tells you what a field is called, while -[`HasField`](./has_field.md) is what reads its value. +- **`Display` / `to_string()`** when the name goes straight into a message. This is what `StaticFormat` + exists to power, and it is the form to prefer. +- **[`StaticString`](./static_string.md)** for a constant, a key, or a comparison. It is computed at + compile time, so there is no per-call work. +- **`StaticFormat`** when a formatter has to be written into from a type with no value — implementing + `Display` for a wrapper over a type-level string, say. This is the narrow case, and it is why the + method takes no `self`. +- **[`ConcatPath`](./concat_path.md)** when the thing being composed is a path rather than a string. ## Under the hood @@ -130,12 +109,11 @@ variant lookups, and building programs out of type-level strings is not what the ### Advanced -This section shows the two recursions. The `StaticString` one is the more interesting, because it explains the -`LEN` parameter that otherwise looks redundant on every `Symbol`. +This section shows the recursion, which is the shorter of the two string recoveries. ::: -`StaticFormat` is the straightforward one. Each character node writes itself and defers: +Each character node writes itself and defers to the tail: ```rust impl StaticFormat for Chars @@ -152,67 +130,46 @@ impl StaticFormat for Nil { /* writes nothing */ } ``` Because both `Symbol` and `Chars` implement `Display` by delegating to this, any type-level string can be -interpolated or turned into an owned `String`. +interpolated or turned into an owned `String` — and the string is *reconstructed* on each call rather +than read out of storage, since there is no `&str` inside a `Symbol` to read. -`StaticString` is const evaluation rather than recursion at run time. It is a blanket impl over an internal -`StaticBytes` trait: `Symbol` computes a `[u8; LEN]` in a `const` block by walking the character list -and UTF-8-encoding each character into the array, and `StaticString::VALUE` then validates those bytes as UTF-8 -and exposes the `&'static str`. - -**That array is why `Symbol` carries a `LEN` at all.** A const-evaluated byte array must have a known size, and the -size cannot be computed from inside the const context by walking the list — so the macro precomputes it. It is a -*byte* length, which is what makes multi-byte Unicode round-trip correctly and why `LEN` disagrees with the -character count for any non-ASCII name. - -`ConcatPath` is a pure type-level computation evaluated during trait resolution, with the same two-impl shape as -[`ConcatProduct`](./product_ops.md). It never touches a value; it only names the combined path type, which a getter -then uses to descend. +That per-call reconstruction is the difference from [`StaticString`](./static_string.md), which does the +same decoding once, at compile time, into a `&'static str` constant. ## Gotchas -**`StaticFormat` cannot be named from the `cgp` crate.** It is `pub` in its own crate, but nothing re-exports it -onto a reachable path — `cgp::core` re-exports a different types crate, `cgp-base` is not a dependency of `cgp`, -and the prelude carries only its sibling `ConcatPath`. So a crate depending on `cgp` can use its *effect* through -`Display` but cannot bound on it, implement it, or name it. Treat it as an implementation detail of those `Display` -impls, and reach for `StaticString` when you want the decoded name. - -**`StaticString` is not in the prelude** while `ConcatPath` is — an asymmetry between two traits that do -neighbouring jobs. Import `StaticString` from `cgp::core::field::traits`. - -**`LEN` on a `Symbol` is bytes, not characters.** They coincide for ASCII, so the distinction only surfaces on a -non-ASCII name, where the number will not match the visible character count. +**It is not in the prelude, and its import differs from both its neighbours'.** This trait comes from +`cgp::core::base::traits`, [`StaticString`](./static_string.md) from `cgp::core::field::traits`, and +[`ConcatPath`](./concat_path.md) — defined in the same crate as this one — is in the prelude. Reaching for +the wrong module is the usual first failure. -**`VALUE` is a constant, so it is named through the trait.** Write `::VALUE`; there -is no method to call and no value to have. +**Prefer a `Display` bound where one will do.** Any code that only needs to *format* a type-level string +should require `Display`, which needs no import and is what the trait produces. -**`Display` reconstructs the string rather than reading a stored one.** There is no `&str` inside a `Symbol` — -`to_string()` walks the type. For a name used repeatedly, `StaticString::VALUE` is the cheaper choice. +**`Display` reconstructs the string on every call.** For a name used repeatedly, +[`StaticString`](./static_string.md)'s `VALUE` is the cheaper choice. -**`ConcatPath` produces a type, not a joined string.** It is path composition for trait resolution; if you want the -segments as text, decode the symbols. +**There is no `self`.** The trait's method is an associated function, because a type-level string has no +value — which is why the `Display` impl goes through a `Default`-constructed marker, and why a bound on +this trait is what you need when there is no value to construct. ## Related constructs -- [`Symbol!`](../macros/symbol.md) — the type-level string these decode, and where the `LEN` comes from. -- [`Path!`](../macros/path.md) — the path `ConcatPath` joins. -- [Type-level spines](../types/type_level_spines.md) — the `Chars` and path chains being walked. -- [`ConcatProduct`](./product_ops.md) — the product-level analogue of `ConcatPath`. +- [`StaticString`](./static_string.md) — the eager counterpart, and the one to reach for. +- [`ConcatPath`](./concat_path.md) — path composition, its reachable sibling in the same group. +- [`Symbol!`](../macros/symbol.md) — the type-level string being formatted. +- [Type-level spines](../types/type_level_spines.md) — the `Chars` chain being walked. - [`HasField`](./has_field.md) — where the names being decoded are used as keys. -- [Optional fields](./optional_fields.md) — a real consumer, reporting a missing field by name. -- [`ChainGetters`](../providers/chain_getters.md) — nested accessors, the setting path composition serves. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where field-name types are put to work at scale. +- [Extensible records](/docs/concepts/extensible-records) — where field-name types are put to work at + scale. ## Source -- [`static_string.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/static_string.rs) - — `StaticString` and its const-evaluated UTF-8 decoding - [`static_format.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/static_format.rs) — `StaticFormat` and its character-list impls -- [`concat_path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/concat_path.rs) - — `ConcatPath` --- diff --git a/docs/reference/traits/static_string.md b/docs/reference/traits/static_string.md new file mode 100644 index 00000000..5cfafd08 --- /dev/null +++ b/docs/reference/traits/static_string.md @@ -0,0 +1,147 @@ +--- +sidebar_label: 'StaticString' +--- + +# `StaticString` + +Recovering a type-level string as a compile-time `&'static str`. + +## What it's for + +CGP encodes field and variant names as *types* — a [`Symbol!`](../macros/symbol.md) is a length plus a +character list, one node per character — so that names can drive trait resolution. But a program +eventually needs those names as ordinary strings: to report a missing field, to build a key, to compare +against input. + +`StaticString` is how a name comes back out, and it does it **eagerly**: + +```rust +pub trait StaticString { + const VALUE: &'static str; +} +``` + +`VALUE` is the decoded string as a constant, computed by const evaluation rather than at run time. So the +string is available wherever a `const` is, costs nothing per use, and can be compared or stored freely. + +**This is the one of the three recovery traits to reach for.** Its sibling +[`StaticFormat`](./static_format.md) recovers a name lazily by writing into a formatter, which is what +backs `Display`; reach for it only where there is no value to format and no constant will do. + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::traits`: + +```rust +use cgp::core::field::traits::StaticString; +``` + +`VALUE` is an associated constant rather than a method, so it is named through the trait: +`::VALUE`. There is no value to have and nothing to call. + +The impl is a blanket one over `Symbol`, so every type-level string has it, including the +empty one. + +## Examples + +Decoding a symbol, and the eager-versus-lazy pair side by side: + +```rust +use cgp::core::field::traits::StaticString; +use cgp::prelude::*; + +// eagerly, as a compile-time constant +assert_eq!(::VALUE, "hello"); + +// lazily, through Display — reconstructed at the point of formatting +let s = ::default(); +assert_eq!(s.to_string(), "hello"); +``` + +Multi-byte Unicode round-trips faithfully, and the empty symbol decodes to the empty string: + +```rust +assert_eq!(::VALUE, "世界你好"); +assert_eq!(::VALUE, ""); +``` + +Where it shows up in real code is recovering a name for an error. The +[optional-field layer](./finalize_optional.md)'s `finalize_optional` reports its missing field by +returning `Tag::VALUE` — the field's own name, as a static string, with no allocation. + +## When to reach for it, and when not + +**Reach for `StaticString` when you need a name as data, and for `Display` when you need it in a +message.** That is the whole decision. + +- **`StaticString`** for a constant, a key, a comparison, or anywhere the name is used more than once. It + is computed at compile time, so there is no per-call work. +- **`Display` / `to_string()`** for one-off formatting, which is what + [`StaticFormat`](./static_format.md) powers. Bounding on that trait directly is for the narrow case + where there is no value to format. +- **[`ConcatPath`](./concat_path.md)** when the thing being composed is a path rather than a string. + +Two things this is not for. It is **not a general string facility**: [`Symbol!`](../macros/symbol.md) +exists to key field and variant lookups, and building programs out of type-level strings is not what the +encoding is for. And it is **not how you read a field** — recovering a name tells you what a field is +called, while [`HasField`](./has_field.md) is what reads its value. + +## Under the hood + +:::note + +### Advanced + +This section explains the `LEN` parameter that otherwise looks redundant on every `Symbol`. + +::: + +`StaticString` is const evaluation rather than a recursion at run time. It is a blanket impl over an +internal `StaticBytes` trait: `Symbol` computes a `[u8; LEN]` in a `const` block by walking +the character list and UTF-8-encoding each character into the array, and `VALUE` then validates those +bytes as UTF-8 and exposes the `&'static str`. + +**That array is why `Symbol` carries a `LEN` at all.** A const-evaluated byte array must have a known +size, and the size cannot be computed from inside the const context by walking the list — so the macro +precomputes it. It is a *byte* length, which is what makes multi-byte Unicode round-trip correctly and +why `LEN` disagrees with the visible character count for any non-ASCII name. + +## Gotchas + +**It is not in the prelude** while [`ConcatPath`](./concat_path.md) is — an asymmetry between two traits +that do neighbouring jobs. Import `StaticString` from `cgp::core::field::traits`. + +**`VALUE` is a constant, so it is named through the trait.** Write +`::VALUE`; there is no method to call. + +**`LEN` on a `Symbol` is bytes, not characters.** They coincide for ASCII, so the distinction only +surfaces on a non-ASCII name, where the number will not match the visible character count. + +**`Display` reconstructs the string rather than reading a stored one.** There is no `&str` inside a +`Symbol`, so `to_string()` walks the type. For a name used repeatedly, `VALUE` is the cheaper choice. + +**It decodes a symbol, not a path.** A [`Path!`](../macros/path.md) is a list of segments; decoding one +means decoding each segment's symbol. + +## Related constructs + +- [`StaticFormat`](./static_format.md) — the lazy counterpart, behind the `Display` impls. +- [`ConcatPath`](./concat_path.md) — the same recovery idea one level up, for paths. +- [`Symbol!`](../macros/symbol.md) — the type-level string this decodes, and where the `LEN` comes from. +- [Type-level spines](../types/type_level_spines.md) — the `Chars` chain being walked. +- [`HasField`](./has_field.md) — where the names being decoded are used as keys. +- [`FinalizeOptional`](./finalize_optional.md) — a real consumer, reporting a missing field by name. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where field-name types are put to work at + scale. + +## Source + +- [`static_string.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/static_string.rs) + — `StaticString` and its const-evaluated UTF-8 decoding + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/take_field.md b/docs/reference/traits/take_field.md new file mode 100644 index 00000000..48646c43 --- /dev/null +++ b/docs/reference/traits/take_field.md @@ -0,0 +1,163 @@ +--- +sidebar_label: 'TakeField' +--- + +# `TakeField` + +Removing one currently-present field from a builder. + +## What it's for + +`TakeField` is the reverse of [`BuildField`](./build_field.md): it removes a field that is currently set, +handing back the value and the partial record without it. + +```rust +pub trait TakeField { + type Value; + type Remainder; + + fn take_field(self, _tag: PhantomData) -> (Self::Value, Self::Remainder); +} +``` + +The value comes out owned; `Remainder` is the partial record with that one field's marker flipped back to +`IsNothing`, so it can no longer be finalized until the field is put back. + +It pins the `IsPresent → IsNothing` transition of the [`UpdateField`](./update_field.md) primitive, and +because it *requires* the starting marker to be `IsPresent`, **taking a field that is absent is a compile +error** rather than an `Option` you have to handle. + +Two things reach for it. Redistributing a record — [`into_builder`](./into_builder.md), take fields out, +put them somewhere else — and, far more often, [`CanBuildFrom`](./can_build_from.md), whose merge +recursion takes each field out of the source and builds it into the target. + +## Using it + +**It is not in the prelude** — the one member of the core builder family that is not. Import it from +`cgp::core::field::traits` when you call `take_field` directly: + +```rust +use cgp::core::field::traits::TakeField; +``` + +The `PhantomData` argument names the field, and the method returns a tuple: **the value first, the +remainder second.** + +**Nothing implements it directly.** It is a library blanket impl over +[`UpdateField`](./update_field.md), so every field the derive generates an `UpdateField` impl for gains +`take_field` for free. + +## Examples + +Taking a field out and putting it back, which is the shape generic redistributing code has: + +```rust +use cgp::core::field::traits::TakeField; +use cgp::prelude::*; + +let builder = person.into_builder(); // all present + +let (first_name, remainder) = builder.take_field(PhantomData::); +// `remainder` is missing first_name, so it cannot be finalized + +let person = remainder + .build_field(PhantomData::, first_name) + .finalize_build(); // all present again +``` + +Dropping the `build_field` line makes `finalize_build` fail to resolve, which is the guarantee: a field +taken out and not replaced cannot be forgotten silently. + +## When to reach for it, and when not + +**Reach for it when a complete value must be decomposed**, and remember that the common case — +merging one record into another — already uses it for you. + +- **Use [`CanBuildFrom`](./can_build_from.md)** to move every shared field from one record into another's + builder. It is this trait applied in a loop, written once. +- **Use `take_field`** when a *specific* field must be extracted from a partial value, typically after + [`into_builder`](./into_builder.md). +- **Use [`BuildField`](./build_field.md)** for the opposite direction. +- **Use [`ToFields`](./to_fields.md)** when the whole value should become a flat shape rather than a + partial record with one field missing. +- **Prefer ordinary destructuring** in concrete code. `let Person { first_name, .. } = person;` needs no + machinery, and this family is for code that cannot name the type. + +## Under the hood + +:::note + +### Advanced + +This section shows why the trait is not generated, and where it is really used. + +::: + +`TakeField` is a **library blanket impl** over [`UpdateField`](./update_field.md), the mirror image of +[`BuildField`](./build_field.md#under-the-hood): + +```rust +// conceptually: +// impl TakeField for Partial +// where Partial: UpdateField +``` + +The target marker is `IsNothing` and the constraint on the reported source marker is `IsPresent` — both +swapped relative to `BuildField`. Since `Mapper` is an *output* of the primitive, constraining it selects +only those partial types whose field is currently set. + +The primitive's signature is what makes one trait serve both directions: `update_field` takes the new +storage in and hands the old storage back, so under this transition it takes `()` in and hands the real +value back. + +**Its heaviest user is [`CanBuildFrom`](./can_build_from.md).** That recursion walks the source's field +list, taking each field out with `take_field` and writing it into the target with +[`build_field`](./build_field.md), threading the shrinking source and the growing target through — which +is why a merge needs [`HasFields`](./has_fields.md) on the source as well as a builder. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::traits`. Every other trait in the core +builder family is. + +**Taking an absent field does not compile.** The second take of the same field finds `Mapper = IsNothing` +and no impl, reported as a missing method rather than as anything about absence. + +**It returns `(value, remainder)`, in that order.** Reversing the binding is a type error, but a +confusing one when both are generic. + +**The remainder cannot be finalized.** That is the point, and it means a decomposition that loses a field +fails at [`finalize_build`](./finalize_build.md) rather than where the field was dropped. + +**`Remainder` is a different type from `Self`**, so a take cannot happen in a loop over a fixed-type +variable. + +**Nothing implements it directly**, so an unsatisfied `TakeField` bound surfaces as an unsatisfied +[`UpdateField`](./update_field.md) one. + +## Related constructs + +- [`BuildField`](./build_field.md) — the opposite direction. +- [`UpdateField`](./update_field.md) — the primitive both are built from. +- [`IntoBuilder`](./into_builder.md) — how a complete value becomes a partial one to take from. +- [`CanBuildFrom`](./can_build_from.md) — the merge that uses this internally. +- [`FinalizeBuild`](./finalize_build.md) — what a remainder cannot satisfy until the field is restored. +- [`HasBuilder`](./has_builder.md) — the family's entry point. +- [`MapType`](./map_type.md) — the `IsPresent`/`IsNothing` markers this moves between. +- [`ToFields`](./to_fields.md) — the flat-shape alternative to decomposing a partial value. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the `UpdateField` impls behind + it. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder + pattern. + +## Source + +- [`take_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/take_field.rs) + — `TakeField` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/to_fields.md b/docs/reference/traits/to_fields.md new file mode 100644 index 00000000..20b7ea98 --- /dev/null +++ b/docs/reference/traits/to_fields.md @@ -0,0 +1,164 @@ +--- +sidebar_label: 'ToFields' +--- + +# `ToFields` + +Taking a value apart into its shape. + +## What it's for + +[`HasFields`](./has_fields.md) *names* a type's shape. `ToFields` produces a value in it: + +```rust +pub trait ToFields: HasFields { + fn to_fields(self) -> Self::Fields; +} +``` + +That is what lets generic code stop working on a concrete struct and start working on an anonymous list +of named entries — the form a serializer walks, a converter rewrites, or a merge consumes. The +concrete type goes in; a [`Product!`](../macros/product.md) of [`Field`](../types/field.md) entries comes +out, or a [`Sum!`](../macros/sum.md) for an enum. + +**It consumes the value.** That is the difference from [`ToFieldsRef`](./to_fields_ref.md), and it is the +commonest surprise in the family, because the two read alike at a call site. + +The reverse direction is [`FromFields`](./from_fields.md), and the two round-trip through the identical +`Fields` type, so generic code can decompose, transform, and rebuild with the shapes lining up by +construction rather than by check. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +It supertraits [`HasFields`](./has_fields.md), so bounding on `ToFields` gives you `Fields` as well and +there is no need to name both — though writing `T: HasFields + ToFields` is common and harmless. + +The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md), which emits all five shape +traits together. + +## Examples + +A value round-tripping through its shape: + +```rust +use cgp::prelude::*; + +#[derive(Clone, Debug, Eq, PartialEq, HasFields)] +pub struct Config { + pub host: String, + pub port: u16, +} + +let config = Config { host: "localhost".to_owned(), port: 8080 }; + +let fields = config.clone().to_fields(); // Config -> the product +let config_again = Config::from_fields(fields); // the product -> Config + +assert_eq!(config, config_again); +``` + +The `clone()` is there only because the assertion compares against the original — `to_fields` would +otherwise have consumed it, which is exactly the point. + +In generic code the bound is what matters: + +```rust +fn shape_of(value: T) -> T::Fields +where + T: ToFields, +{ + value.to_fields() +} +``` + +## When to reach for it, and when not + +**Bound on it when generic code must consume a value and work on its entries**, and reach for the +borrowing form otherwise. + +- **[`ToFieldsRef`](./to_fields_ref.md)** when the value must survive. Requiring `ToFields` where a + borrow would do forces every caller to clone, which is the most common over-requirement in this + family. +- **[`FromFields`](./from_fields.md)** for the other direction, and both together for a round trip. +- **[`HasFields`](./has_fields.md) alone** when the code only *names* the shape and never holds a value + in it. +- **[`HasField`](./has_field.md)** when one named field is all that is wanted. Decomposing a whole struct + to read one entry is the wrong tool. +- **The [builder family](./has_builder.md)** when a value is assembled incrementally rather than + converted wholesale. `to_fields` is a single flat conversion; a builder tracks presence field by field. + +## Under the hood + +:::note + +### Advanced + +This section shows the generated impl, which is where the `Cons` spine becomes visible. + +::: + +`Product![A, B]` is `Cons>`, so the conversion builds a `Cons` chain, one node per field, +wrapping each value into its [`Field`](../types/field.md) entry: + +```rust +impl ToFields for Person { + fn to_fields(self) -> Self::Fields { + Cons(self.name.into(), Cons(self.age.into(), Nil)) + } +} +``` + +That chain is what an error message prints when structural code fails to resolve, and the +[type-level spines](../types/type_level_spines.md) page covers reading it. + +An enum's conversion is the dual: each concrete variant is matched onto its arm of an `Either` chain +terminated by `Void`, tagged with the variant name. + +Because the shape is built positionally from declaration order, `to_fields` and +[`from_fields`](./from_fields.md) are exact inverses by construction — there is no lookup, no matching by +name at run time, and nothing that can fail. + +## Gotchas + +**It consumes the value.** Reach for [`ToFieldsRef`](./to_fields_ref.md) when you need to keep it. This +is the commonest surprise in the family, because the two read alike. + +**Field order is declaration order and is part of the type.** Two structs with the same field names in +different orders produce unrelated `Fields` types, so a chain built from one will not satisfy the other. + +**A newtype's shape is the inner type**, not a one-element product, so `to_fields` on +`struct Wrapper(String)` yields a `String`. Generic code written against a `Cons` chain will not match +it. + +**It supertraits [`HasFields`](./has_fields.md)**, so a bound naming both is redundant rather than +wrong. + +**There is no fallible form.** The conversion cannot fail; anything that could is a different operation, +such as a [cast](./can_downcast.md). + +## Related constructs + +- [`HasFields`](./has_fields.md) — the supertrait that names the shape. +- [`FromFields`](./from_fields.md) — the reverse conversion. +- [`ToFieldsRef`](./to_fields_ref.md) — the borrowing form, which leaves the value intact. +- [`HasFieldsRef`](./has_fields_ref.md) — the shape that form produces. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl. +- [`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), and [`Field`](../types/field.md) — what + a shape is made of. +- [Type-level spines](../types/type_level_spines.md) — the `Cons` chain the conversion builds. +- [`HasBuilder`](./has_builder.md) — incremental assembly, as against this wholesale conversion. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. + +## Source + +- [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs) + — `ToFields` and `ToFieldsRef` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/to_fields_ref.md b/docs/reference/traits/to_fields_ref.md new file mode 100644 index 00000000..a7fba8fa --- /dev/null +++ b/docs/reference/traits/to_fields_ref.md @@ -0,0 +1,156 @@ +--- +sidebar_label: 'ToFieldsRef' +--- + +# `ToFieldsRef` + +Walking a value's shape without consuming it. + +## What it's for + +[`ToFields`](./to_fields.md) takes a value apart into its shape and consumes it in the process. Code that +only reads — a validator, a serializer, a routine that inspects a struct and hands it back — should not +have to. `ToFieldsRef` produces the **borrowed** shape instead: + +```rust +pub trait ToFieldsRef: HasFieldsRef { + fn to_fields_ref<'a>(&'a self) -> Self::FieldsRef<'a> + where + Self: 'a; +} +``` + +The original survives, and every entry in the result holds a reference rather than a value. + +**It is the weaker requirement, so prefer it wherever it suffices.** Bounding on +[`ToFields`](./to_fields.md) when a borrow would do forces every caller to give up ownership or clone, +which is the most common over-requirement in this family. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +It supertraits [`HasFieldsRef`](./has_fields_ref.md) rather than [`HasFields`](./has_fields.md), which +is the one structural difference from its owning counterpart: the borrowed shape and the owned shape are +named by two independent traits, and each conversion supertraits the one it produces. + +The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md), which emits all five shape +traits together. + +## Examples + +Reading a shape and keeping the value: + +```rust +use cgp::prelude::*; + +#[derive(HasField, HasFields)] +pub struct Config { + pub host: String, + pub port: u16, +} + +let config = Config { host: "localhost".to_owned(), port: 8080 }; + +let fields_ref = config.to_fields_ref(); + +assert_eq!(fields_ref.0.value, &"localhost".to_owned()); +``` + +`config` is still usable afterwards, which is the whole difference from +[`to_fields`](./to_fields.md). + +In generic code it is the bound that says "I will not take your value": + +```rust +fn inspect(value: &T) +where + T: ToFieldsRef, +{ + let _fields = value.to_fields_ref(); + // walk the borrowed entries +} +``` + +## When to reach for it, and when not + +**Bound on it whenever generic code reads a shape and the caller keeps the value** — which is most +read-only structural code. + +- **[`ToFields`](./to_fields.md)** when the code genuinely consumes: a conversion, a merge, a rebuild. +- **[`FromFields`](./from_fields.md)** for constructing a value, which has no borrowing counterpart — + a borrowed shape cannot yield an owned value. +- **[`HasFieldsRef`](./has_fields_ref.md) alone** when the code only *names* the borrowed shape. +- **[`HasField`](./has_field.md)** when one named field is all that is wanted. + +There is one thing this cannot do that [`ToFields`](./to_fields.md) can: hand the entries' values onward +by ownership. A routine that must move a field out of a struct needs the owning form. + +## Under the hood + +:::note + +### Advanced + +This section covers the lifetime plumbing, which is the only interesting part. + +::: + +The generated impl borrows each field and wraps it into the corresponding entry of the borrowed shape, +under the reserved lifetime name `'__a` that +[`HasFieldsRef`](./has_fields_ref.md#under-the-hood) declares: + +```rust +// each field is borrowed rather than moved: +// Cons((&self.name).into(), Cons((&self.age).into(), Nil)) +``` + +The `where Self: 'a` clause on both the trait method and the associated type is what keeps the result +tied to the borrow it came from, so the shape cannot outlive the value. + +One consequence follows from the rewrite being per-entry rather than structural: **a field that is +already a reference gains another one**, appearing as `&'__a &'a Name`. That is correct, and it is the +detail most likely to look wrong in an error message. + +An enum's borrowed conversion matches the concrete variant and produces the corresponding arm of the +borrowed sum, with the payload borrowed rather than moved — which is also how +[`HasExtractorRef`](./has_extractor_ref.md) reads a variant without consuming the value. + +## Gotchas + +**It supertraits [`HasFieldsRef`](./has_fields_ref.md), not [`HasFields`](./has_fields.md).** Bounding on +`ToFieldsRef` does not give you `Fields`; require both traits if the code needs both shapes. + +**A field that is already borrowed gets a second borrow** in the result, which is correct and surprising. + +**There is no `FromFieldsRef`.** The borrowed half of the family is read-only by construction. + +**The lifetime usually has to be spelled out.** A signature that returns or stores `FieldsRef<'a>` +inherits the `where Self: 'a` clause and rarely elides cleanly. + +**A newtype's borrowed shape is a borrow of the inner type**, not a one-element product — the same +special case the owned shape has. + +## Related constructs + +- [`HasFieldsRef`](./has_fields_ref.md) — the supertrait that names the borrowed shape. +- [`ToFields`](./to_fields.md) — the owning counterpart, which consumes the value. +- [`FromFields`](./from_fields.md) — rebuilding a value, which has no borrowing form. +- [`HasFields`](./has_fields.md) — the owned shape, and where the family is explained in full. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl. +- [`HasExtractorRef`](./has_extractor_ref.md) — the same borrow-rather-than-consume idea on the enum + side. +- [`Field`](../types/field.md) — one entry of a shape. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. + +## Source + +- [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs) + — `ToFieldsRef` and `ToFields` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/to_optional.md b/docs/reference/traits/to_optional.md new file mode 100644 index 00000000..a7cad73e --- /dev/null +++ b/docs/reference/traits/to_optional.md @@ -0,0 +1,164 @@ +--- +sidebar_label: 'ToOptional' +--- + +# `ToOptional` + +Re-marking every field of an existing builder as optional. + +## What it's for + +[`HasOptionalBuilder`](./has_optional_builder.md) starts an all-optional builder from nothing. +`ToOptional` is the conversion for the case where you already hold a partial value and want to relax it: + +```rust +pub trait ToOptional { + type Output; + + fn to_optional(self) -> Self::Output; +} +``` + +Every field is re-marked to `IsOptional`, whatever state it was in — a set field becomes `Some(value)`, +an absent one becomes `None` — and from there the value behaves like any other optional builder: +[`SetOptional`](./set_optional.md) applies, and either +[`FinalizeOptional`](./finalize_optional.md) or [`CanFinalizeWithDefault`](./can_finalize_with_default.md) +ends it. + +**It is the conversion `optional_builder()` is built from**, which is the shortest way to describe both: +one starts fresh and converts, the other converts something you already have. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::ToOptional; +``` + +`Output` is the same partial companion type with every marker set to `IsOptional`. There is nothing to +implement — the impl is a blanket one over +[`TransformMapFields`](./transform_map_fields.md), so any partial value whose fields can be re-marked +gets it. + +## Examples + +Relaxing a partly-filled core builder so the remaining fields can arrive in any order: + +```rust +use cgp::extra::field::impls::{FinalizeOptional, SetOptional, ToOptional}; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +let builder = Context::builder() + .build_field(PhantomData::, "foo".to_owned()) + .to_optional(); // foo is Some, bar is None + +let context = builder + .set(PhantomData::, 42) + .finalize_optional() + .unwrap(); + +assert_eq!(context.bar, 42); +``` + +The already-set `foo` survives the conversion as `Some("foo")`, which is what distinguishes this from +starting over with [`optional_builder()`](./has_optional_builder.md). + +Converting a *complete* value works too, by way of +[`into_builder`](./into_builder.md): + +```rust +let builder = context.into_builder().to_optional(); // every field Some +``` + +## When to reach for it, and when not + +**Reach for it when a builder already exists and its strictness has become the wrong shape.** + +- **[`HasOptionalBuilder`](./has_optional_builder.md)** when nothing has been built yet. + `optional_builder()` is `builder().to_optional()` and reads better. +- **`ToOptional`** when a core builder is partly filled — because a routine handed it to you, or because + the first few fields were known and the rest are not. +- **[`IntoBuilder`](./into_builder.md) then `to_optional`** to relax a complete value, typically before + overwriting some of its fields. +- **Stay on the [core builder](./has_builder.md)** if the remaining fields are known and set once. The + conversion costs the compile-time completeness check. + +## Under the hood + +:::note + +### Advanced + +This section shows the transform it drives. + +::: + +`ToOptional` is a [`TransformMapFields`](./transform_map_fields.md) walk carrying the +[`TransformOptional`](./transform_optional.md) marker, targeting `IsOptional`: + +```rust +// conceptually: +// self.transform_map_fields::() +``` + +That walk visits each field of the target's [`HasFields`](./has_fields.md) shape, uses +[`UpdateField`](./update_field.md) to take the field out and learn its current marker, applies the +transform, and writes it back under `IsOptional`. The transform's own impls are what decide the value: +`IsPresent` becomes `Some(value)`, `IsNothing` becomes `None`, and `IsOptional` passes through. + +Its mirror image is [`CanFinalizeWithDefault`](./can_finalize_with_default.md), which runs the same walk +with [`TransformMapDefault`](./transform_map_default.md) toward `IsPresent`. **Both capabilities are the +same recursion with a different marker**, which is why the defaulted and optional workflows behave so +symmetrically. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**It consumes the builder** and returns a differently-typed one, so the original binding is gone. + +**A field already set survives as `Some`.** It is not reset, which is the difference from +[`optional_builder()`](./has_optional_builder.md) and is easy to assume the other way round. + +**Converting gives up the compile-time completeness check** for the fields that were still absent — from +here a missing field is an `Err` or a default rather than a compile error. + +**It is not reversible.** There is no `from_optional`; getting back to a strict configuration means +finalizing, through [`FinalizeOptional`](./finalize_optional.md) or +[`CanFinalizeWithDefault`](./can_finalize_with_default.md). + +**A field whose type is already `Option` becomes `Option>`** in the slot. That is correct — +the outer layer is the builder's presence tracking — and reads confusingly in an error. + +## Related constructs + +- [`HasOptionalBuilder`](./has_optional_builder.md) — the entry point built from this conversion. +- [`SetOptional`](./set_optional.md) — setting a field once every marker is `IsOptional`. +- [`FinalizeOptional`](./finalize_optional.md) and + [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the two endings. +- [`TransformOptional`](./transform_optional.md) — the marker this walk carries. +- [`TransformMapFields`](./transform_map_fields.md) — the walk itself. +- [`IntoBuilder`](./into_builder.md) — how a complete value becomes a builder to convert. +- [`HasBuilder`](./has_builder.md) — the core family this relaxes. +- [`MapType`](./map_type.md) — the `IsOptional` marker. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence + fits. + +## Source + +- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs) + — `ToOptional`, `HasOptionalBuilder`, and `TransformOptional` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/transform_map.md b/docs/reference/traits/transform_map.md new file mode 100644 index 00000000..3c152ac3 --- /dev/null +++ b/docs/reference/traits/transform_map.md @@ -0,0 +1,175 @@ +--- +sidebar_label: 'TransformMap' +--- + +# `TransformMap` + +The per-field function that converts a value from one marker's storage to another's. + +## What it's for + +[`MapType`](./map_type.md) only names storage *types*: it says that an `IsNothing` field holds `()` and +an `IsPresent` field holds its value, and nothing about how you get from one to the other. +`TransformMap` carries that missing half — the actual function: + +```rust +pub trait TransformMap { + fn transform_mapped(value: M1::Map) -> M2::Map; +} +``` + +`Self` is a transform marker of your own naming; `M1` is the field's current state, `M2` the state it +should end in, and `T` the field's value type. So one impl answers one question: *given a field +currently in state `M1`, produce the same field in state `M2`.* + +**This is the extension point of the whole partial-type scheme**, and it is genuinely usable. Defining a +new way to re-mark a record means writing one impl per source state and then applying it with +[`TransformMapFields`](./transform_map_fields.md). + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::traits`, along with any non-prelude +marker you name — `IsOptional` comes from `cgp::core::field::impls`: + +```rust +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::TransformMap; +``` + +The trait is implemented on a **transform marker**, a zero-sized type you declare. It carries no data +and exists only to name the set of conversions, exactly as a provider does elsewhere in CGP. + +**A transform needs an impl for every source marker a field might currently be in.** That is the rule +that decides how many impls you write, and getting it wrong is the usual failure — the walk simply does +not resolve, and the error names the missing `TransformMap` impl rather than the field. + +## Examples + +A marker that fills absent fields from `Default` is one impl per source state: + +```rust +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::TransformMap; +use cgp::prelude::*; + +pub struct FillDefaults; + +impl TransformMap for FillDefaults { + fn transform_mapped(value: T) -> T { + value + } +} + +impl TransformMap for FillDefaults { + fn transform_mapped(_value: ()) -> T { + T::default() + } +} + +impl TransformMap for FillDefaults { + fn transform_mapped(value: Option) -> T { + value.unwrap_or_default() + } +} +``` + +Read that as three cases of one rule: a present field passes through, an absent one becomes its default, +and an optional one becomes its contents or the default. Note how each signature's argument type is the +source marker's `Map` — `T`, then `()`, then `Option` — which is what makes the three impls +non-overlapping. + +Because all three target `IsPresent`, applying `FillDefaults` through +[`transform_map_fields`](./transform_map_fields.md) leaves every field present, which is precisely the +configuration [`FinalizeBuild`](./finalize_build.md) accepts. + +**That is not hypothetical: it is how [`CanFinalizeWithDefault`](./can_finalize_with_default.md) works**, +and reading it here is the shortest route to understanding that layer. + +## When to reach for it, and when not + +**Implement it to define a new per-field conversion**, and reach for the existing layer otherwise. + +- **Use the [optional-field layer](./can_finalize_with_default.md)** if what you want is defaulted or + optional finalization. Both already exist, built on exactly this, and + [`TransformMapDefault`](./transform_map_default.md) and + [`TransformOptional`](./transform_optional.md) are the two markers it ships. +- **Implement `TransformMap`** for a conversion those do not cover — a validating transform, one that + logs, one that fills from something other than `Default`. +- **Use [`TransformMapFields`](./transform_map_fields.md)** to apply what you have written. This trait + converts one field; that one walks a whole record. +- **Do not implement [`MapType`](./map_type.md) for a new marker** and expect the derives to use it. A + fifth state marker has no machinery behind it; a new *transform* marker, by contrast, works + immediately. + +## Under the hood + +:::note + +### Advanced + +This section explains why the impls are shaped the way they are. + +::: + +The signature's argument and return types are **projections through the two markers**, so the concrete +types differ per impl even though the trait is the same. `TransformMap` has an +argument type of `::Map`, which normalizes to `()`, and a return type of `T`. +That is what lets three impls for one marker coexist without overlapping: they differ in `M1`. + +[`TransformMapFields`](./transform_map_fields.md) is what calls this. For each field of the target's +[`HasFields`](./has_fields.md) shape, it uses [`UpdateField`](./update_field.md) to take the field out — +learning the marker it was in — applies `Transform::transform_mapped`, and writes the result back under +the target marker. + +Two consequences follow from that construction, and both explain limits you might otherwise trip over. +The transform must have an impl for **every** source marker a field might currently be in, which is why +`FillDefaults` above needs three rather than one. And the walk is driven by the *target's* shape, so it +re-marks exactly the fields the concrete struct declares. + +Nothing here has a runtime representation beyond the field values themselves: the markers are zero-sized, +and `transform_mapped` is an associated function with no receiver. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::traits`. + +**It needs an impl per source state.** Writing only the `IsNothing` case leaves the recursion +unresolvable for a record with any field already present, and the error names the missing +`TransformMap` impl rather than the field that caused it. + +**The argument type is the source marker's projection**, not `T`. An impl from `IsNothing` takes `()`, +one from `IsOptional` takes `Option`. Writing `T` there is the most common mistake. + +**It converts one field.** Applying it to a record is +[`TransformMapFields`](./transform_map_fields.md)'s job. + +**A transform whose impls do not all target the same marker will not compose into a finalize.** The +layer's payoff comes from every field landing in one state, usually `IsPresent`. + +**It is an associated function, not a method.** There is no receiver; the marker exists only as a name. + +## Related constructs + +- [`TransformMapFields`](./transform_map_fields.md) — lifts this across a whole partial record. +- [`MapType`](./map_type.md) — the markers naming each state, and the trait this supplies the missing + half of. +- [`TransformMapDefault`](./transform_map_default.md) and [`TransformOptional`](./transform_optional.md) + — the two markers CGP ships, and the models to copy. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the capability built from the first of + them. +- [`UpdateField`](./update_field.md) — the primitive the walk uses to take a field out and write it back. +- [`FinalizeBuild`](./finalize_build.md) — what an all-`IsPresent` result is accepted by. +- [`HasFields`](./has_fields.md) — the shape the walk follows. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and how their states change. + +## Source + +- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs) + — `TransformMap` and `TransformMapFields` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/transform_map_default.md b/docs/reference/traits/transform_map_default.md new file mode 100644 index 00000000..3dc1a384 --- /dev/null +++ b/docs/reference/traits/transform_map_default.md @@ -0,0 +1,173 @@ +--- +sidebar_label: 'TransformMapDefault' +--- + +# `TransformMapDefault` + +The transform marker that makes every field present, defaulting whatever is not. + +## What it's for + +[`CanFinalizeWithDefault`](./can_finalize_with_default.md) works by re-marking every field of a partial +record to `IsPresent` and then calling the ordinary [`finalize_build`](./finalize_build.md). +`TransformMapDefault` is the marker that carries the per-field conversions making that possible. + +It is a zero-sized type implementing [`TransformMap`](./transform_map.md) three times, once per state a +field might currently be in — and reading those three impls is the shortest description of what the +defaulting layer does: + +| a field currently | becomes | +|---|---| +| `IsPresent` | itself, unchanged | +| `IsNothing` | `Default::default()` | +| `IsOptional` | its contents, or the default if `None` | + +All three target `IsPresent`, which is exactly the configuration +[`FinalizeBuild`](./finalize_build.md) accepts. + +**You name it only when extending the layer.** Using the defaulting workflow means calling +[`finalize_with_default`](./can_finalize_with_default.md) or +[`build_with_default`](./can_build_with_default.md), with no marker in sight. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::TransformMapDefault; +``` + +There is nothing to call. The marker exists to be named in a +[`TransformMapFields`](./transform_map_fields.md) bound, which is where a capability says *which* +conversion it drives: + +```rust +Builder: TransformMapFields +``` + +**Every field's type must implement `Default`** for the two filling impls to apply — which is where the +defaulting layer's one real requirement comes from. + +## Examples + +You meet it in a bound rather than at a call site. This is +[`CanFinalizeWithDefault`](./can_finalize_with_default.md)'s whole impl: + +```rust +use cgp::core::field::traits::TransformMapFields; +use cgp::extra::field::impls::TransformMapDefault; +use cgp::prelude::*; + +impl CanFinalizeWithDefault for Builder +where + Builder: TransformMapFields, + Builder::Output: FinalizeBuild, +{ + type Output = Output; + + fn finalize_with_default(self) -> Output { + self.transform_map_fields().finalize_build() + } +} +``` + +The marker is the first type argument, and swapping it for +[`TransformOptional`](./transform_optional.md) — with `IsOptional` as the target — is exactly how +[`ToOptional`](./to_optional.md) is written. **Same recursion, different marker.** + +Writing a marker of your own follows the same three-impl shape; the +[`TransformMap`](./transform_map.md#examples) page shows one. + +## When to reach for it, and when not + +**Name it only when writing a capability that drives the defaulting conversion.** Everything else is +served by the two capabilities already built on it. + +- **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** to finalize a partial record, defaulting + gaps. +- **[`CanBuildWithDefault`](./can_build_with_default.md)** to merge from a source and default the rest, in + one call. +- **Write your own [`TransformMap`](./transform_map.md) marker** for a conversion these do not cover — one + that validates, logs, or fills from something other than `Default`. +- **[`TransformOptional`](./transform_optional.md)** is its counterpart, targeting `IsOptional` instead. + +## Under the hood + +:::note + +### Advanced + +This section shows the three impls, which are the layer's actual content. + +::: + +The marker is zero-sized and carries no data. What it carries is three +[`TransformMap`](./transform_map.md) impls, distinguished by their source marker: + +```rust +impl TransformMap for TransformMapDefault { + fn transform_mapped(value: T) -> T { + value + } +} + +impl TransformMap for TransformMapDefault { + fn transform_mapped(_value: ()) -> T { + T::default() + } +} + +impl TransformMap for TransformMapDefault { + fn transform_mapped(value: Option) -> T { + value.unwrap_or_default() + } +} +``` + +Note that each argument type is the *source* marker's projection — `T`, then `()`, then `Option` — +which is what keeps the three from overlapping. And note that only two carry the `T: Default` bound: a +field already present needs no default, which is why a fully-set builder can be finalized this way +regardless of its field types. + +Three impls are needed rather than one because +[`TransformMapFields`](./transform_map_fields.md#under-the-hood) resolves a conversion per field from +whatever state that field is in, and a record may hold fields in all three states at once. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**Two of its three impls require `Default`.** A field whose type has none makes the walk unresolvable the +moment that field is unset, and the error names the missing `TransformMap` impl rather than the field. + +**It always targets `IsPresent`.** It cannot be used to reach any other configuration; that is +[`TransformOptional`](./transform_optional.md)'s job. + +**It is a marker, not a capability.** There is no method to call and nothing to wire — it is named in a +bound. + +**A defaulted field is indistinguishable from one set to the default value** in the result, which is the +trade against [`FinalizeOptional`](./finalize_optional.md). + +## Related constructs + +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the capability built directly on it. +- [`CanBuildWithDefault`](./can_build_with_default.md) — merge plus that finalize. +- [`TransformOptional`](./transform_optional.md) — the counterpart marker, targeting `IsOptional`. +- [`TransformMap`](./transform_map.md) — the trait it implements three times. +- [`TransformMapFields`](./transform_map_fields.md) — the walk that applies it. +- [`MapType`](./map_type.md) — the markers it converts between. +- [`FinalizeBuild`](./finalize_build.md) — what an all-`IsPresent` result is accepted by. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and how their states change. + +## Source + +- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs) + — `TransformMapDefault` and the capabilities built on it + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/transform_map_fields.md b/docs/reference/traits/transform_map_fields.md new file mode 100644 index 00000000..ad0c6045 --- /dev/null +++ b/docs/reference/traits/transform_map_fields.md @@ -0,0 +1,163 @@ +--- +sidebar_label: 'TransformMapFields' +--- + +# `TransformMapFields` + +Applying one per-field transform across a whole partial record. + +## What it's for + +[`TransformMap`](./transform_map.md) converts *one* field from one marker's storage to another's. +`TransformMapFields` lifts that conversion across an entire partial record, so every field is re-marked +in one call: + +```rust +pub trait TransformMapFields { + type Output; + + fn transform_map_fields(self) -> Self::Output; +} +``` + +`Self` is the partial value, `Transform` is the marker carrying the per-field functions, and `TargetMap` +is the [`MapType`](./map_type.md) marker every field should end in. `Output` is the partial type with +every field re-marked accordingly. + +**This is the motion the optional-field layer is made of.** Re-marking every field to `IsPresent` and +then calling the ordinary [`finalize_build`](./finalize_build.md) is exactly what +[`CanFinalizeWithDefault`](./can_finalize_with_default.md) does, and re-marking to `IsOptional` is what +[`ToOptional`](./to_optional.md) does. + +## Using it + +**It is not in the prelude.** Import it from `cgp::core::field::traits`: + +```rust +use cgp::core::field::traits::TransformMapFields; +``` + +It is implemented for any [`PartialData`](./partial_data.md) whose fields the transform can convert, so +there is nothing to implement — what you supply is the `Transform` marker, by writing +[`TransformMap`](./transform_map.md) impls for it. + +The two type parameters are usually inferred from the surrounding bound rather than written at a call +site, which is why the method reads as a bare `self.transform_map_fields()`. + +## Examples + +You reach it through the layer built on it far more often than directly. This is the whole body of +[`CanFinalizeWithDefault`](./can_finalize_with_default.md): + +```rust +use cgp::core::field::traits::TransformMapFields; +use cgp::prelude::*; + +impl CanFinalizeWithDefault for Builder +where + Builder: TransformMapFields, + Builder::Output: FinalizeBuild, +{ + type Output = Output; + + fn finalize_with_default(self) -> Output { + self.transform_map_fields().finalize_build() + } +} +``` + +Read the two bounds together: the first says every field can be re-marked to `IsPresent` by +`TransformMapDefault`, and the second says the result is then finalizable. The strict presence check +still runs — it just always passes, because the transform guaranteed presence first. + +Applying a transform of your own follows the same shape, with your marker in place of +`TransformMapDefault`. + +## When to reach for it, and when not + +**Bound on it when writing a capability that re-marks a whole record**, which is what extending the +optional-field layer means. + +- **Use [`CanFinalizeWithDefault`](./can_finalize_with_default.md) or + [`ToOptional`](./to_optional.md)** if what you want is one of the two conversions CGP already ships. +- **Write a [`TransformMap`](./transform_map.md) marker and apply it here** for a conversion they do not + cover. +- **Use [`UpdateField`](./update_field.md)** when a *single* field changes state. This trait is the + whole-record form, and reaching for it to change one field walks every other field for nothing. +- **Use [`MapFields`](./map_fields.md)** when you only need to *name* the re-marked shape as a type. + That trait computes the type; this one converts the values. + +## Under the hood + +:::note + +### Advanced + +This section shows the recursion and the two limits it explains. + +::: + +`TransformMapFields` walks the target's [`HasFields`](./has_fields.md) product one entry at a time. For +each `Field` it uses [`UpdateField`](./update_field.md) **twice**: it takes the field out — +replacing its marker with `IsNothing` and reading what the marker *was* — applies +`Transform::transform_mapped` to convert the value into the `TargetMap` wrapping, then writes it back +under `TargetMap`. + +So the result type has every field re-marked to `TargetMap`, with the values converted accordingly. Two +things follow from that construction, and both explain limits you might otherwise trip over. + +**The transform must have an impl for every source marker a field might currently be in**, or the walk +does not resolve — which is why a transform like `FillDefaults` needs three +[`TransformMap`](./transform_map.md) impls rather than one. + +**The recursion is driven by the target's shape**, so it re-marks exactly the fields the concrete struct +declares, in declaration order, and a field the shape does not mention is not visited at all. + +The intermediate `IsNothing` state is invisible from outside: it exists only between the two +`UpdateField` calls for one field, and no observable value is ever in a half-transformed configuration. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::core::field::traits`. + +**A missing [`TransformMap`](./transform_map.md) impl stops the whole walk.** The error names the missing +impl for one field's source marker, not the record, so it reads as being about a marker pair rather than +about the transform being incomplete. + +**`Output` is a partial type, not the finished struct.** Finalizing is still +[`FinalizeBuild`](./finalize_build.md)'s job — this trait only guarantees the configuration that impl +requires. + +**It walks every field.** For a single field's transition, [`UpdateField`](./update_field.md) is the +right tool. + +**It is [`MapFields`](./map_fields.md)'s value-level counterpart, and they are easy to confuse.** That +one computes a type; this one converts values and needs a transform to do it. + +**It requires [`PartialData`](./partial_data.md).** A plain struct is not a partial value; obtain one +with [`HasBuilder`](./has_builder.md) or [`IntoBuilder`](./into_builder.md) first. + +## Related constructs + +- [`TransformMap`](./transform_map.md) — the per-field conversion this lifts. +- [`MapType`](./map_type.md) — the markers naming each state. +- [`UpdateField`](./update_field.md) — the primitive the walk calls twice per field. +- [`PartialData`](./partial_data.md) — what a partial value is, and the bound this requires. +- [`FinalizeBuild`](./finalize_build.md) — what an all-`IsPresent` result is accepted by. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) and [`ToOptional`](./to_optional.md) — the + two capabilities built directly on this. +- [`MapFields`](./map_fields.md) — the type-level counterpart. +- [`HasFields`](./has_fields.md) — the shape the walk follows. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and how their states change. + +## Source + +- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs) + — `TransformMapFields` and `TransformMap` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/transform_optional.md b/docs/reference/traits/transform_optional.md new file mode 100644 index 00000000..7768a616 --- /dev/null +++ b/docs/reference/traits/transform_optional.md @@ -0,0 +1,166 @@ +--- +sidebar_label: 'TransformOptional' +--- + +# `TransformOptional` + +The transform marker that makes every field optional. + +## What it's for + +[`ToOptional`](./to_optional.md) re-marks every field of a partial record to `IsOptional`, so it can then +be set freely and finalized either way. `TransformOptional` is the marker carrying the per-field +conversions that make that possible. + +It is a zero-sized type implementing [`TransformMap`](./transform_map.md), and reading its impls is the +shortest description of what the optional conversion does: + +| a field currently | becomes | +|---|---| +| `IsPresent` | `Some(value)` | +| `IsNothing` | `None` | + +Both target `IsOptional`, which is the configuration [`SetOptional`](./set_optional.md) requires and the +one an optional builder lives at. + +**It is the exact mirror of [`TransformMapDefault`](./transform_map_default.md)**, which targets +`IsPresent` instead — same walk, different destination. That symmetry is why the defaulted and optional +workflows behave so alike. + +**You name it only when extending the layer.** Using the optional workflow means calling +[`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md), with no marker +in sight. + +## Using it + +**It is not in the prelude.** Import it from `cgp::extra::field::impls`: + +```rust +use cgp::extra::field::impls::TransformOptional; +``` + +There is nothing to call. The marker is named in a +[`TransformMapFields`](./transform_map_fields.md) bound, which is where a capability says which +conversion it drives: + +```rust +Builder: TransformMapFields +``` + +Unlike its defaulting counterpart, **it requires nothing of the field types** — wrapping a value in +`Some` and producing `None` need no `Default` and no other bound, which is why the optional path applies +to records the defaulting path does not. + +## Examples + +You meet it in the bound behind [`ToOptional`](./to_optional.md): + +```rust +use cgp::core::field::traits::TransformMapFields; +use cgp::extra::field::impls::TransformOptional; +use cgp::prelude::*; + +// conceptually: +// impl ToOptional for Builder +// where Builder: TransformMapFields +// { +// fn to_optional(self) -> Self::Output { +// self.transform_map_fields() +// } +// } +``` + +Swap the marker for [`TransformMapDefault`](./transform_map_default.md) and the target for `IsPresent`, +add a [`finalize_build`](./finalize_build.md), and you have +[`CanFinalizeWithDefault`](./can_finalize_with_default.md). The two capabilities differ by exactly that +much. + +Writing a marker of your own follows the same shape; the +[`TransformMap`](./transform_map.md#examples) page shows one with three impls. + +## When to reach for it, and when not + +**Name it only when writing a capability that drives the optional conversion.** + +- **[`ToOptional`](./to_optional.md)** to relax an existing partial value. +- **[`HasOptionalBuilder`](./has_optional_builder.md)** to start an all-optional builder, which is + `builder().to_optional()`. +- **[`TransformMapDefault`](./transform_map_default.md)** when the destination is `IsPresent` rather than + `IsOptional`. +- **Write your own [`TransformMap`](./transform_map.md) marker** for a conversion neither covers. + +## Under the hood + +:::note + +### Advanced + +This section shows why it needs fewer impls than its counterpart. + +::: + +The marker is zero-sized and carries [`TransformMap`](./transform_map.md) impls distinguished by their +source marker, each targeting `IsOptional`: + +```rust +// IsPresent -> IsOptional: wrap +// fn transform_mapped(value: T) -> Option { Some(value) } +// +// IsNothing -> IsOptional: nothing to wrap +// fn transform_mapped(_value: ()) -> Option { None } +``` + +Note what is absent: **no `Default` bound anywhere.** Its counterpart +[`TransformMapDefault`](./transform_map_default.md) needs one on two of its three impls, because filling +an absent field means producing a value from nothing. Producing `None` does not, so this conversion +applies to every field type. + +[`TransformMapFields`](./transform_map_fields.md#under-the-hood) is what applies it, visiting each field +of the target's [`HasFields`](./has_fields.md) shape and using +[`UpdateField`](./update_field.md) twice per field — once to take the value out and learn its marker, +once to write it back under `IsOptional`. + +The result is a partial value at a configuration the core builder never reaches on its own, which is what +makes [`SetOptional`](./set_optional.md) resolve and the strict +[`FinalizeBuild`](./finalize_build.md) not. + +## Gotchas + +**It is not in the prelude.** Import from `cgp::extra::field::impls`. + +**It always targets `IsOptional`.** Reaching `IsPresent` is +[`TransformMapDefault`](./transform_map_default.md)'s job. + +**It is a marker, not a capability.** There is no method and nothing to wire — it is named in a bound. + +**It requires nothing of the field types**, which is the one place the two markers genuinely differ in +what they can be applied to. + +**Converting gives up the compile-time completeness check**, since every field becomes optional whether +it was set or not. + +**A field whose type is already `Option` becomes `Option>`.** The outer layer is the +builder's presence tracking, and the two are easy to conflate in an error. + +## Related constructs + +- [`ToOptional`](./to_optional.md) — the conversion built directly on it. +- [`HasOptionalBuilder`](./has_optional_builder.md) — the entry point built on that. +- [`TransformMapDefault`](./transform_map_default.md) — the counterpart marker, targeting `IsPresent`. +- [`TransformMap`](./transform_map.md) — the trait it implements. +- [`TransformMapFields`](./transform_map_fields.md) — the walk that applies it. +- [`SetOptional`](./set_optional.md) — what the resulting configuration makes available. +- [`MapType`](./map_type.md) — the `IsOptional` marker it targets. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and how their states change. + +## Source + +- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs) + — `TransformOptional`, `ToOptional`, and `HasOptionalBuilder` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/update_field.md b/docs/reference/traits/update_field.md new file mode 100644 index 00000000..6b6d2829 --- /dev/null +++ b/docs/reference/traits/update_field.md @@ -0,0 +1,174 @@ +--- +sidebar_label: 'UpdateField' +--- + +# `UpdateField` + +The primitive that moves one field of a partial record between states. + +## What it's for + +Everything in the [builder family](./has_builder.md) reduces to one operation: change one field's storage +from one [`MapType`](./map_type.md) marker to another, and hand back what was there before. +`UpdateField` is that operation: + +```rust +pub trait UpdateField { + type Value; + type Mapper: MapType; // the field's marker before the update + type Output; // the partial value with the field now in state M + + fn update_field( + self, + _tag: PhantomData, + value: M::Map, + ) -> (::Map, Self::Output); +} +``` + +The `Map<…>` wrappers are the field's value *as stored* under each marker: `IsPresent` stores the value +itself, `IsNothing` stores `()`. So setting an absent field takes the real value in and hands `()` back, +and removing a present one takes `()` in and hands the real value back — one signature covering both +directions. + +**This is what the derive actually writes.** [`BuildField`](./build_field.md) and +[`TakeField`](./take_field.md) are library blanket impls over it, each pinning one transition, which is +why the general form is the one generated per field. + +## Using it + +**It is in the prelude**, so `use cgp::prelude::*;` is enough. + +Reading the associated types is most of using it. `Value` is the field's declared type, stripped of any +marker; `Mapper` is the marker the field was in *before* the call, which the impl reports rather than +requires; and `Output` is the partial type with that one field now in `M`. + +The `M` parameter is the target marker and is usually inferred from the value you pass — supplying a +`String` where the field's type is `String` means `M = IsPresent`, and supplying `()` means +`M = IsNothing`. + +The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md), one per field. + +## Examples + +You almost always reach it through the two directions rather than directly: + +```rust +use cgp::prelude::*; + +// BuildField: IsNothing -> IsPresent +let partial = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()); +``` + +Naming `UpdateField` yourself is for a transition neither direction covers — which in practice means one +involving `IsOptional`: + +```rust +// the shape SetOptional uses: IsOptional -> IsOptional, so the type does not change +let (previous, builder) = builder.update_field( + PhantomData::, + Some("Bob".to_owned()), +); +``` + +Because both markers are `IsOptional` here, `Output` is the same type as `Self` — which is exactly what +lets an optional field be set repeatedly, unlike the core `build_field` that consumes an absent slot once. + +## When to reach for it, and when not + +**Bound on it directly only for an operation neither [`BuildField`](./build_field.md) nor +[`TakeField`](./take_field.md) covers.** Those two are the common transitions and read far better at a +call site. + +- **[`BuildField`](./build_field.md)** for `IsNothing → IsPresent`, which is setting a field. +- **[`TakeField`](./take_field.md)** for `IsPresent → IsNothing`, which is removing one. +- **`UpdateField`** for anything else — a transition to or from `IsOptional`, which is what the + [optional-field extensions](./set_optional.md) do, or a transform's intermediate steps. +- **[`TransformMapFields`](./transform_map_fields.md)** when *every* field changes state rather than one. + It calls this twice per field internally, and reaching for `UpdateField` in a loop is re-implementing + it. + +## Under the hood + +:::note + +### Advanced + +This section shows the generated impl, and the detail that makes build order free. + +::: + +The derive emits one impl per field, and the key property is visible in the generics: **only the named +field's marker moves, while every other stays generic.** + +```rust +impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> + UpdateField for __PartialPerson<__M1__, __F1__> +{ + type Value = String; + type Mapper = __M1__; // the marker before + type Output = __PartialPerson<__M2__, __F1__>; // and after + // ... +} +``` + +`__M1__` is unconstrained, so the impl applies whatever state the field is currently in, and `__F1__` +passes through untouched. That is precisely why fields can be built in any order: no impl cares about the +other fields' states. + +`Mapper` being an *output* rather than an input is what lets the two directional traits pin a transition +by constraining it. [`BuildField`](./build_field.md) is a blanket impl over +`UpdateField` and [`TakeField`](./take_field.md) over +`UpdateField` — same primitive, opposite constraints. + +Nothing here changes a value's runtime layout beyond moving it in or out of the slot; the markers are +zero-sized and the wrapping is a type-level fiction. + +## Gotchas + +**`Mapper` is the state *before* the call, not after.** The name reads either way, and getting it +backwards makes a bound resolve to the wrong impl or none at all. + +**Both the argument and the returned value are marker projections**, so their concrete types depend on +`M` and `Mapper`. An impl from `IsNothing` returns `()`, one from `IsPresent` returns the value. + +**It returns a tuple**, old value first and new partial second. Ignoring the first with `_` is common and +fine, but the shape catches people expecting the builder alone. + +**It changes one field.** For a whole-record transition, use +[`TransformMapFields`](./transform_map_fields.md). + +**Reaching for it where [`BuildField`](./build_field.md) would do makes the code harder to read** for no +gain. The directional traits exist because they say what is happening. + +**A field not declared on the record has no impl**, and the error names the missing `UpdateField` bound +with the tag fully expanded rather than saying the field does not exist. + +## Related constructs + +- [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) — the two directions, as blanket + impls over this. +- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — where a partial value comes + from. +- [`FinalizeBuild`](./finalize_build.md) — where one ends up. +- [`MapType`](./map_type.md) — the markers a field moves between. +- [`TransformMapFields`](./transform_map_fields.md) — the whole-record form, which calls this twice per + field. +- [`SetOptional`](./set_optional.md) — a transition this covers and the directional traits do not. +- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the per-field impls. +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that name a field. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder + pattern. + +## Source + +- [`update_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/update_field.rs) + — `UpdateField` + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/example-code/README.md b/example-code/README.md index 67dcf6d6..b42a2220 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -19,7 +19,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — sixteen files under `src/concepts/`, one per page that shows code | -| `docs/reference/` | `macros/delegate_components.md` only — the section is being filled in lazily | +| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, and the `traits/` pages that show checkable code; the section is being filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `src/cargo_cgp/` | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/src/reference/derives/derive_cgp_data.rs b/example-code/src/reference/derives/derive_cgp_data.rs index 37fb2789..35a2ec72 100644 --- a/example-code/src/reference/derives/derive_cgp_data.rs +++ b/example-code/src/reference/derives/derive_cgp_data.rs @@ -1,10 +1,8 @@ -//! Code from `docs/reference/derives/derive_cgp_data.md` — *`#[derive(CgpData)]`, `CgpRecord` & -//! `CgpVariant`*. +//! Code from `docs/reference/derives/derive_cgp_data.md` — *`#[derive(CgpData)]`*. //! -//! The page's *Under the hood* section shows the impls and companion types the derives generate; -//! those are not repeated here, since re-declaring them beside the derive would be a coherence -//! conflict and `cargo cgp expand` is the check on that section. What this file pins is the accepted -//! and rejected shapes, and that the two worked examples run. +//! The umbrella page's own snippets. Its *Under the hood* section defers the two expansions to the +//! shape pages, so what this file pins is the accepted and rejected shapes, that the umbrella and the +//! two shape-specific faces agree on their output, and that the degenerate shapes compile. /// ## Using it /// @@ -115,105 +113,3 @@ pub mod using_it { /// } /// ``` pub mod rejected_struct_style_variant {} - -/// ## Examples -/// -/// The record half: `promote`, which merges one record into another's builder. -pub mod examples_record { - use cgp::core::field::impls::CanBuildFrom; - use cgp::prelude::*; - - #[derive(CgpData)] - #[derive(Debug, Eq, PartialEq)] - pub struct Person { - pub first_name: String, - pub last_name: String, - } - - #[derive(CgpData)] - #[derive(Debug, Eq, PartialEq)] - pub struct Employee { - pub employee_id: u64, - pub first_name: String, - pub last_name: String, - } - - pub fn promote(person: Person, id: u64) -> Employee { - Employee::builder() - .build_from(person) - .build_field(PhantomData::, id) - .finalize_build() - } - - #[test] - fn test_promote() { - let person = Person { - first_name: "Alice".to_owned(), - last_name: "Anderson".to_owned(), - }; - - assert_eq!( - promote(person, 1), - Employee { - employee_id: 1, - first_name: "Alice".to_owned(), - last_name: "Anderson".to_owned(), - } - ); - } -} - -/// ## Examples -/// -/// The variant half: `area`, an extraction chain closed with no wildcard arm. The page names `Circle` -/// and `Rectangle` without declaring them, so they are declared here. -pub mod examples_variant { - use cgp::core::field::traits::FinalizeExtractResult; - use cgp::prelude::*; - - pub struct Circle { - pub radius: f64, - } - - pub struct Rectangle { - pub width: f64, - pub height: f64, - } - - #[derive(CgpData)] - pub enum Shape { - Circle(Circle), - Rectangle(Rectangle), - } - - pub fn area(shape: Shape) -> f64 { - match shape - .to_extractor() - .extract_field(PhantomData::) - { - Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, - Err(remainder) => { - let rect = remainder - .extract_field(PhantomData::) - .finalize_extract_result(); - rect.width * rect.height - } - } - } - - #[test] - fn test_area_of_each_variant() { - assert_eq!( - area(Shape::Circle(Circle { radius: 1.0 })), - core::f64::consts::PI - ); - - assert_eq!( - area(Shape::Rectangle(Rectangle { - width: 3.0, - height: 4.0, - })), - 12.0 - ); - } -} diff --git a/example-code/src/reference/derives/derive_cgp_record.rs b/example-code/src/reference/derives/derive_cgp_record.rs new file mode 100644 index 00000000..0bb9b812 --- /dev/null +++ b/example-code/src/reference/derives/derive_cgp_record.rs @@ -0,0 +1,51 @@ +//! Code from `docs/reference/derives/derive_cgp_record.md` — *`#[derive(CgpRecord)]`*. +//! +//! The page's worked example, run. Written with `CgpRecord` rather than the umbrella, which is the +//! page's own claim that the two emit the same output on a struct. + +/// ## Examples +/// +/// The record half: `promote`, which merges one record into another's builder. +pub mod examples_record { + use cgp::core::field::impls::CanBuildFrom; + use cgp::prelude::*; + + #[derive(CgpRecord)] + #[derive(Debug, Eq, PartialEq)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(CgpRecord)] + #[derive(Debug, Eq, PartialEq)] + pub struct Employee { + pub employee_id: u64, + pub first_name: String, + pub last_name: String, + } + + pub fn promote(person: Person, id: u64) -> Employee { + Employee::builder() + .build_from(person) + .build_field(PhantomData::, id) + .finalize_build() + } + + #[test] + fn test_promote() { + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + }; + + assert_eq!( + promote(person, 1), + Employee { + employee_id: 1, + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + } + ); + } +} diff --git a/example-code/src/reference/derives/derive_cgp_variant.rs b/example-code/src/reference/derives/derive_cgp_variant.rs new file mode 100644 index 00000000..84246866 --- /dev/null +++ b/example-code/src/reference/derives/derive_cgp_variant.rs @@ -0,0 +1,74 @@ +//! Code from `docs/reference/derives/derive_cgp_variant.md` — *`#[derive(CgpVariant)]`*. +//! +//! The page's worked example, run, plus the shape it rejects. Written with `CgpVariant` rather than +//! the umbrella, which is the page's own claim that the two emit the same output on an enum. + +/// ## Using it +/// +/// The page's rejected snippet: a struct-style variant has no single payload type, so the derive +/// fails. Every variant must carry exactly one unnamed payload, with no per-variant opt-out. +/// +/// ```compile_fail +/// use cgp::prelude::*; +/// +/// #[derive(CgpVariant)] +/// pub enum Shape { +/// Circle { radius: f64 }, +/// } +/// ``` +pub mod rejected_struct_style_variant {} + +/// ## Examples +/// +/// `area`, an extraction chain closed with no wildcard arm. The page names `Circle` and `Rectangle` +/// without declaring them, so they are declared here. +pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; + use cgp::prelude::*; + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(CgpVariant)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn area(shape: Shape) -> f64 { + match shape + .to_extractor() + .extract_field(PhantomData::) + { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width * rect.height + } + } + } + + #[test] + fn test_area_of_each_variant() { + assert_eq!( + area(Shape::Circle(Circle { radius: 1.0 })), + core::f64::consts::PI + ); + + assert_eq!( + area(Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + })), + 12.0 + ); + } +} diff --git a/example-code/src/reference/derives/mod.rs b/example-code/src/reference/derives/mod.rs index 848651ac..21d921ac 100644 --- a/example-code/src/reference/derives/mod.rs +++ b/example-code/src/reference/derives/mod.rs @@ -2,6 +2,8 @@ pub mod derive_build_field; pub mod derive_cgp_data; +pub mod derive_cgp_record; +pub mod derive_cgp_variant; pub mod derive_extract_field; pub mod derive_from_variant; pub mod derive_has_field; diff --git a/example-code/src/reference/traits/append_product.rs b/example-code/src/reference/traits/append_product.rs new file mode 100644 index 00000000..69bbf549 --- /dev/null +++ b/example-code/src/reference/traits/append_product.rs @@ -0,0 +1,29 @@ +//! Code from `docs/reference/traits/append_product.md` — *`AppendProduct`*. +//! +//! A pure type-level function, so the check is a type equality: each `fn` coerces the computed +//! `Output` to the type the page says it produces, and the module compiles only if the two are the +//! same type. The `use` line checks the import path, since the trait is not in the prelude. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::AppendProduct; + use cgp::prelude::*; + + pub type Base = Product![Field]; + + pub type WithPort = >>::Output; + + /// The page's claim about `WithPort`. + pub fn assert_with_port( + fields: WithPort, + ) -> Product![Field, Field] { + fields + } + + /// The base case the page states under *Using it*: appending onto `Nil` yields a one-element list. + pub fn assert_nil_base_case( + fields: >>::Output, + ) -> Base { + fields + } +} diff --git a/example-code/src/reference/traits/can_build_from.rs b/example-code/src/reference/traits/can_build_from.rs new file mode 100644 index 00000000..660dba4a --- /dev/null +++ b/example-code/src/reference/traits/can_build_from.rs @@ -0,0 +1,96 @@ +//! Code from `docs/reference/traits/can_build_from.md` — *`CanBuildFrom`*. +//! +//! The page's snippets, run. Two claims are pinned beyond "it compiles": the import path, since the +//! trait is not in the prelude, and that `build_from` returns a *builder* rather than the target, so +//! a second merge and an explicit `build_field` can follow before `finalize_build`. + +/// ## Examples +/// +/// One struct assembled from two smaller ones. +pub mod examples_two_sources { + use cgp::prelude::*; + + #[derive(CgpData)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[derive(CgpData)] + pub struct Baz { + pub baz: bool, + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + #[test] + fn test_build_from_two_sources() { + use cgp::core::field::impls::CanBuildFrom; + + let combined: FooBarBaz = FooBarBaz::builder() + .build_from(FooBar { + foo: 1, + bar: "bar".to_owned(), + }) + .build_from(Baz { baz: true }) + .finalize_build(); + + assert_eq!( + combined, + FooBarBaz { + foo: 1, + bar: "bar".to_owned(), + baz: true, + } + ); + } +} + +/// ## Examples +/// +/// A merge mixed with an explicit field, which is the shape the page shows second. +pub mod examples_merge_and_set { + use cgp::prelude::*; + + #[derive(CgpData)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct Employee { + pub employee_id: u64, + pub first_name: String, + pub last_name: String, + } + + #[test] + fn test_merge_then_set() { + use cgp::core::field::impls::CanBuildFrom; + + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + }; + + let employee: Employee = Employee::builder() + .build_from(person) + .build_field(PhantomData::, 7) + .finalize_build(); + + assert_eq!( + employee, + Employee { + employee_id: 7, + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + } + ); + } +} diff --git a/example-code/src/reference/traits/can_downcast.rs b/example-code/src/reference/traits/can_downcast.rs new file mode 100644 index 00000000..20175d0c --- /dev/null +++ b/example-code/src/reference/traits/can_downcast.rs @@ -0,0 +1,47 @@ +//! Code from `docs/reference/traits/can_downcast.md` — *`CanDowncast`*. +//! +//! The page's snippets, run. What this pins is the import path — the trait is not in the prelude — +//! and the two halves of the page's claim: a downcast succeeds for a shared variant and returns a +//! remainder for one the target lacks. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBar { + Foo(u64), + Bar(String), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), + } + + #[test] + fn test_downcast_succeeds_for_a_shared_variant() { + use cgp::core::field::impls::CanDowncast; + use core::marker::PhantomData; + + assert_eq!( + FooBarBaz::Bar("hi".to_owned()) + .downcast(PhantomData::) + .ok(), + Some(FooBar::Bar("hi".to_owned())), + ); + } + + #[test] + fn test_downcast_fails_for_a_variant_the_target_lacks() { + use cgp::core::field::impls::CanDowncast; + use core::marker::PhantomData; + + assert_eq!( + FooBarBaz::Baz(true).downcast(PhantomData::).ok(), + None, + ); + } +} diff --git a/example-code/src/reference/traits/can_downcast_fields.rs b/example-code/src/reference/traits/can_downcast_fields.rs new file mode 100644 index 00000000..9b3ee041 --- /dev/null +++ b/example-code/src/reference/traits/can_downcast_fields.rs @@ -0,0 +1,44 @@ +//! Code from `docs/reference/traits/can_downcast_fields.md` — *`CanDowncastFields`*. +//! +//! The page's chain, run. The load-bearing check is that the second attempt is written with +//! `downcast_fields` rather than `downcast`: a remainder is an extractor rather than an enum, so the +//! two halves of the pair are not interchangeable. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum JustFoo { + Foo(u64), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum JustBar { + Bar(String), + } + + #[test] + fn test_a_chain_of_two_candidate_targets() { + use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; + use core::marker::PhantomData; + + let value = FooBarBaz::Bar("hi".to_owned()); + + match value.downcast(PhantomData::) { + Ok(_foo) => panic!("the value is not a Foo"), + Err(remainder) => { + let bar = remainder.downcast_fields(PhantomData::); + + assert!(bar.is_ok()); + } + } + } +} diff --git a/example-code/src/reference/traits/can_upcast.rs b/example-code/src/reference/traits/can_upcast.rs new file mode 100644 index 00000000..e254e5f1 --- /dev/null +++ b/example-code/src/reference/traits/can_upcast.rs @@ -0,0 +1,33 @@ +//! Code from `docs/reference/traits/can_upcast.md` — *`CanUpcast`*. +//! +//! The page's snippet, run. What this pins beyond "it compiles" is the import path — the trait is +//! not in the prelude — and the totality claim: an upcast into a wider enum always succeeds, so +//! `upcast` returns the target directly rather than a `Result`. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBar { + Foo(u64), + Bar(String), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), + } + + #[test] + fn test_upcast_always_succeeds() { + use cgp::core::field::impls::CanUpcast; + use core::marker::PhantomData; + + let wide = FooBar::Foo(1).upcast(PhantomData::); + + assert_eq!(wide, FooBarBaz::Foo(1)); + } +} diff --git a/example-code/src/reference/traits/cast.rs b/example-code/src/reference/traits/cast.rs deleted file mode 100644 index 3f4444ce..00000000 --- a/example-code/src/reference/traits/cast.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! Code from `docs/reference/traits/cast.md` — *`CanUpcast`, `CanDowncast` & `CanBuildFrom`*. -//! -//! The page's own snippets, run. What this file pins beyond "it compiles" is the import path — -//! none of the four traits is in the prelude — and the two claims the page makes about totality: -//! an upcast always succeeds, and a downcast against a variant the target lacks returns `Err`. - -/// ## Examples -/// -/// The two enums the page shows, and both directions of the variant cast. -pub mod examples_variant { - use cgp::prelude::*; - - #[derive(Debug, Eq, PartialEq, CgpData)] - pub enum FooBar { - Foo(u64), - Bar(String), - } - - #[derive(Debug, Eq, PartialEq, CgpData)] - pub enum FooBarBaz { - Foo(u64), - Bar(String), - Baz(bool), - } - - #[test] - fn test_upcast_always_succeeds() { - use cgp::core::field::impls::CanUpcast; - use core::marker::PhantomData; - - let wide = FooBar::Foo(1).upcast(PhantomData::); - - assert_eq!(wide, FooBarBaz::Foo(1)); - } - - #[test] - fn test_downcast_succeeds_for_a_shared_variant() { - use cgp::core::field::impls::CanDowncast; - use core::marker::PhantomData; - - assert_eq!( - FooBarBaz::Bar("hi".to_owned()) - .downcast(PhantomData::) - .ok(), - Some(FooBar::Bar("hi".to_owned())), - ); - } - - #[test] - fn test_downcast_fails_for_a_variant_the_target_lacks() { - use cgp::core::field::impls::CanDowncast; - use core::marker::PhantomData; - - assert_eq!( - FooBarBaz::Baz(true).downcast(PhantomData::).ok(), - None, - ); - } -} - -/// ## Examples -/// -/// The record cast: one struct assembled from two smaller ones. -pub mod examples_record { - use cgp::prelude::*; - - #[derive(CgpData)] - pub struct FooBar { - pub foo: u64, - pub bar: String, - } - - #[derive(CgpData)] - pub struct Baz { - pub baz: bool, - } - - #[derive(Debug, Eq, PartialEq, CgpData)] - pub struct FooBarBaz { - pub foo: u64, - pub bar: String, - pub baz: bool, - } - - #[test] - fn test_build_from_two_sources() { - use cgp::core::field::impls::CanBuildFrom; - - let combined: FooBarBaz = FooBarBaz::builder() - .build_from(FooBar { - foo: 1, - bar: "bar".to_owned(), - }) - .build_from(Baz { baz: true }) - .finalize_build(); - - assert_eq!( - combined, - FooBarBaz { - foo: 1, - bar: "bar".to_owned(), - baz: true, - } - ); - } -} diff --git a/example-code/src/reference/traits/concat_path.rs b/example-code/src/reference/traits/concat_path.rs new file mode 100644 index 00000000..ff503089 --- /dev/null +++ b/example-code/src/reference/traits/concat_path.rs @@ -0,0 +1,20 @@ +//! Code from `docs/reference/traits/concat_path.md` — *`ConcatPath`*. +//! +//! Paths are unsized markers, so there is no value to build: naming the joined type and coercing it +//! to the expected one is the check. The absence of any `use` beyond the prelude is the page's claim +//! that this trait, unlike its neighbours, is re-exported there. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + pub type Outer = Path!(@a.b); + pub type Inner = Path!(@c.d); + + pub type Joined = >::Output; + + #[allow(dead_code)] + pub fn assert_joined(path: PhantomData<&Joined>) -> PhantomData<&Path!(@a.b.c.d)> { + path + } +} diff --git a/example-code/src/reference/traits/concat_product.rs b/example-code/src/reference/traits/concat_product.rs new file mode 100644 index 00000000..e403f82e --- /dev/null +++ b/example-code/src/reference/traits/concat_product.rs @@ -0,0 +1,39 @@ +//! Code from `docs/reference/traits/concat_product.md` — *`ConcatProduct`*. +//! +//! A pure type-level function, so the check is a type equality. Besides the page's worked snippet +//! this pins the two `Nil` identities it states, and the import path, since the trait is not in the +//! prelude. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::{AppendProduct, ConcatProduct}; + use cgp::prelude::*; + + pub type Base = Product![Field]; + + pub type WithPort = >>::Output; + + pub type Extra = Product![Field]; + + pub type Full = >::Output; + + /// The page's claim about `Full`. + pub fn assert_full( + fields: Full, + ) -> Product![ + Field, + Field, + Field, + ] { + fields + } + + /// The `Nil` identities the page states under *Using it*. + pub fn assert_left_identity(fields: >::Output) -> Base { + fields + } + + pub fn assert_right_identity(fields: >::Output) -> Base { + fields + } +} diff --git a/example-code/src/reference/traits/map_fields.rs b/example-code/src/reference/traits/map_fields.rs new file mode 100644 index 00000000..2cddd1c1 --- /dev/null +++ b/example-code/src/reference/traits/map_fields.rs @@ -0,0 +1,41 @@ +//! Code from `docs/reference/traits/map_fields.md` — *`MapFields`*. +//! +//! A pure type-level function, so the check is a type equality. What this pins beyond the page's two +//! snippets is that the same marker applies over *both* spines — a product and a sum — and the two +//! import paths, since neither the trait nor the `IsOptional` marker is in the prelude. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::IsOptional; + use cgp::core::field::traits::MapFields; + use cgp::prelude::*; + + pub type Fields = Product![String, u16, bool]; + + pub type Optional = >::Mapped; + + pub fn assert_optional( + fields: Optional, + ) -> Product![Option, Option, Option] { + fields + } + + pub type Variants = Sum![String, u16]; + + pub type OptionalVariants = >::Mapped; + + pub fn assert_optional_variants( + variants: OptionalVariants, + ) -> Sum![Option, Option] { + variants + } + + /// The page's claim that `IsPresent` is the identity, and that `IsNothing` collapses each entry. + pub fn assert_present(fields: >::Mapped) -> Fields { + fields + } + + pub fn assert_nothing(fields: >::Mapped) -> Product![(), (), ()] { + fields + } +} diff --git a/example-code/src/reference/traits/mod.rs b/example-code/src/reference/traits/mod.rs index 161f1e3c..5a319fae 100644 --- a/example-code/src/reference/traits/mod.rs +++ b/example-code/src/reference/traits/mod.rs @@ -1,12 +1,19 @@ //! Code from the pages under `docs/reference/traits/`. //! -//! Several pages here document traits whose impls are all generated, or which are pure type-level +//! Many pages here document traits whose impls are all generated, or which are pure type-level //! operations with no runtime side. Those get a file only where the page shows code a compiler can //! check: a bound that must resolve, an import path that must exist, a conversion that must run. //! Pages that only *display* a trait definition get no module, since re-declaring the trait would //! check nothing about CGP. -pub mod cast; +pub mod append_product; +pub mod can_build_from; +pub mod can_downcast; +pub mod can_downcast_fields; +pub mod can_upcast; +pub mod concat_path; +pub mod concat_product; pub mod has_builder; -pub mod product_ops; +pub mod map_fields; pub mod static_format; +pub mod static_string; diff --git a/example-code/src/reference/traits/product_ops.rs b/example-code/src/reference/traits/product_ops.rs deleted file mode 100644 index 5d07c852..00000000 --- a/example-code/src/reference/traits/product_ops.rs +++ /dev/null @@ -1,88 +0,0 @@ -//! Code from `docs/reference/traits/product_ops.md` — *`AppendProduct`, `ConcatProduct` & -//! `MapFields`*. -//! -//! These are pure type-level functions, so the checks are type equalities: each `fn` coerces the -//! computed `Output`/`Mapped` type to the type the page says it produces, and the module compiles -//! only if the two are the same type. The page's import paths are checked by this file's `use` -//! lines — none of the three traits is in the prelude, nor is the `IsOptional` marker. - -/// ## Examples -/// -/// The append and concat snippets, as the page writes them. -pub mod examples_append_concat { - use cgp::core::field::traits::{AppendProduct, ConcatProduct}; - use cgp::prelude::*; - - pub type Base = Product![Field]; - - pub type WithPort = >>::Output; - - pub type Extra = Product![Field]; - - pub type Full = >::Output; - - /// The page's claim about `WithPort`. - pub fn assert_with_port( - fields: WithPort, - ) -> Product![Field, Field] { - fields - } - - /// The page's claim about `Full`. - pub fn assert_full( - fields: Full, - ) -> Product![ - Field, - Field, - Field, - ] { - fields - } - - /// The `Nil` identities the page states under *Using it*. - pub fn assert_left_identity(fields: >::Output) -> Base { - fields - } - - pub fn assert_right_identity(fields: >::Output) -> Base { - fields - } -} - -/// ## Examples -/// -/// The `MapFields` snippets — over a product, and over a sum with the same marker. -pub mod examples_map_fields { - use cgp::core::field::impls::IsOptional; - use cgp::core::field::traits::MapFields; - use cgp::prelude::*; - - pub type Fields = Product![String, u16, bool]; - - pub type Optional = >::Mapped; - - pub fn assert_optional( - fields: Optional, - ) -> Product![Option, Option, Option] { - fields - } - - pub type Variants = Sum![String, u16]; - - pub type OptionalVariants = >::Mapped; - - pub fn assert_optional_variants( - variants: OptionalVariants, - ) -> Sum![Option, Option] { - variants - } - - /// The page's claim that `IsPresent` is the identity, and that `IsNothing` collapses each entry. - pub fn assert_present(fields: >::Mapped) -> Fields { - fields - } - - pub fn assert_nothing(fields: >::Mapped) -> Product![(), (), ()] { - fields - } -} diff --git a/example-code/src/reference/traits/static_format.rs b/example-code/src/reference/traits/static_format.rs index 18cc1ce1..c265404c 100644 --- a/example-code/src/reference/traits/static_format.rs +++ b/example-code/src/reference/traits/static_format.rs @@ -1,44 +1,30 @@ -//! Code from `docs/reference/traits/static_format.md` — *`StaticFormat`, `StaticString` & -//! `ConcatPath`*. +//! Code from `docs/reference/traits/static_format.md` — *`StaticFormat`*. //! -//! The page's snippets, run. The load-bearing check here is the import path and reachability claim: -//! `StaticString` resolves from `cgp::core::field::traits` and `ConcatPath` from the prelude, while -//! `StaticFormat` is reachable only through `Display` — the page says the trait cannot be named from -//! the `cgp` crate, and the absence of any `use` for it below is that claim. +//! The page's central claim is a negative one: the trait cannot be named from the `cgp` crate, so its +//! effect is reachable only through `Display`. The absence of any `use` for it below is that claim, +//! and the bound in `describe` is the page's advice about what to require instead. /// ## Examples pub mod examples { use cgp::prelude::*; - #[test] - fn test_both_recovery_routes() { - use cgp::core::field::traits::StaticString; - - // lazily, through Display - let s = ::default(); - assert_eq!(s.to_string(), "hello"); - - // eagerly, as a compile-time constant - assert_eq!(::VALUE, "hello"); + pub fn describe(_tag: PhantomData) -> String { + format!("missing field `{}`", Tag::default()) } #[test] - fn test_multi_byte_and_empty() { - use cgp::core::field::traits::StaticString; + fn test_formatting_through_display() { + let s = ::default(); - assert_eq!(::VALUE, "世界你好"); - assert_eq!(::VALUE, ""); + assert_eq!(s.to_string(), "hello"); + assert_eq!(format!("field: {s}"), "field: hello"); } - /// `ConcatPath` joins two paths at the type level. Paths are unsized markers, so there is no - /// value to build — naming the joined type and coercing it to the expected one is the check. - pub type Outer = Path!(@a.b); - pub type Inner = Path!(@c.d); - - pub type Joined = >::Output; - - #[allow(dead_code)] - pub fn assert_joined(path: PhantomData<&Joined>) -> PhantomData<&Path!(@a.b.c.d)> { - path + #[test] + fn test_a_display_bound_is_what_generic_code_requires() { + assert_eq!( + describe(PhantomData::), + "missing field `height`", + ); } } diff --git a/example-code/src/reference/traits/static_string.rs b/example-code/src/reference/traits/static_string.rs new file mode 100644 index 00000000..381cc06e --- /dev/null +++ b/example-code/src/reference/traits/static_string.rs @@ -0,0 +1,29 @@ +//! Code from `docs/reference/traits/static_string.md` — *`StaticString`*. +//! +//! The page's snippets, run. The load-bearing check is the import path — the trait is not in the +//! prelude — and that the eager and lazy routes agree, including on multi-byte and empty symbols. + +/// ## Examples +pub mod examples { + #[test] + fn test_both_recovery_routes() { + use cgp::core::field::traits::StaticString; + use cgp::prelude::*; + + // eagerly, as a compile-time constant + assert_eq!(::VALUE, "hello"); + + // lazily, through Display + let s = ::default(); + assert_eq!(s.to_string(), "hello"); + } + + #[test] + fn test_multi_byte_and_empty() { + use cgp::core::field::traits::StaticString; + use cgp::prelude::*; + + assert_eq!(::VALUE, "世界你好"); + assert_eq!(::VALUE, ""); + } +} From d44901354bf76f9d92f8b74621479eac346f1afa Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 23:45:08 +0200 Subject: [PATCH 031/516] Mark the reference traits that a reader is never expected to write MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Many CGP traits exist for the proc macros to emit and the library's own recursions to consume. A reader meets the name in an expansion or an error message rather than in code they typed, and a page that documents such a trait the way it documents #[cgp_impl] misleads by omission: it reads as an instruction, and a reader who takes it as one goes looking for where to put something that was never theirs to put anywhere. Twenty-seven traits pages now open with a Generated machinery notice, in the position and shape the Legacy — read, don't write notice already uses on attributes/derive_delegate.md. Each says three things: that the reader is not expected to use the construct, which macro or provider produces or consumes it, and that the page therefore exists to explain what that macro emits. Where there is a narrow case in which the reader does name it — defining a monad of their own, writing a getter provider by hand — the notice says so rather than overclaiming. The line is whether the name appears in ordinary code, not whether the impls are generated. HasBuilder and ExtractField are just as generated, but a reader calls builder() and extract_field by name, so they carry no notice; TransformMap is documented as a genuine extension point, so it carries none either. Also corrects a link in the new notice on is_provider_for.md, which pointed at a cgp_new_provider page that does not exist — that macro is one of the two surviving consolidations and lives on cgp_provider.md. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01PQ3tpcNckW7LS1zjPAxuSD --- docs/reference/traits/append_product.md | 11 +++++++++++ docs/reference/traits/can_use_component.md | 12 ++++++++++++ docs/reference/traits/concat_path.md | 12 ++++++++++++ docs/reference/traits/concat_product.md | 11 +++++++++++ docs/reference/traits/contains_value.md | 11 +++++++++++ docs/reference/traits/default_impls1.md | 12 ++++++++++++ docs/reference/traits/default_impls2.md | 11 +++++++++++ docs/reference/traits/default_namespace.md | 13 +++++++++++++ docs/reference/traits/delegate_component.md | 12 ++++++++++++ docs/reference/traits/field_getter.md | 11 +++++++++++ docs/reference/traits/field_mapper.md | 10 ++++++++++ docs/reference/traits/has_fields_ref.md | 11 +++++++++++ docs/reference/traits/is_provider_for.md | 11 +++++++++++ docs/reference/traits/lift_value.md | 12 ++++++++++++ docs/reference/traits/map_field.md | 11 +++++++++++ docs/reference/traits/map_fields.md | 12 ++++++++++++ docs/reference/traits/map_type.md | 12 ++++++++++++ docs/reference/traits/map_type_ref.md | 11 +++++++++++ docs/reference/traits/monadic_bind.md | 11 +++++++++++ docs/reference/traits/monadic_trans.md | 11 +++++++++++ docs/reference/traits/mut_field_getter.md | 11 +++++++++++ docs/reference/traits/partial_data.md | 12 ++++++++++++ docs/reference/traits/static_format.md | 11 +++++++++++ docs/reference/traits/transform_map_default.md | 12 ++++++++++++ docs/reference/traits/transform_map_fields.md | 11 +++++++++++ docs/reference/traits/transform_optional.md | 11 +++++++++++ docs/reference/traits/update_field.md | 12 ++++++++++++ 27 files changed, 308 insertions(+) diff --git a/docs/reference/traits/append_product.md b/docs/reference/traits/append_product.md index 99fb23d4..e4574639 100644 --- a/docs/reference/traits/append_product.md +++ b/docs/reference/traits/append_product.md @@ -6,6 +6,17 @@ sidebar_label: 'AppendProduct' Adding one entry to the end of a type-level product list. +:::info + +### Generated machinery + +**You are not expected to use `AppendProduct` directly.** It is a type-level +operation the extensible-data machinery computes with — the builder and merge recursions are its callers +in practice. You will most likely meet it in an error message from code that walks a shape; this page +explains what it produces so that message is legible. + +::: + ## What it's for A struct's shape in CGP is a type-level list — a [`Product!`](../macros/product.md) of named fields. diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/can_use_component.md index 0b203c46..2bb238e8 100644 --- a/docs/reference/traits/can_use_component.md +++ b/docs/reference/traits/can_use_component.md @@ -6,6 +6,18 @@ sidebar_label: 'CanUseComponent' The context-side check that a context both wires a component and satisfies its provider. +:::info + +### Generated machinery + +**You are not expected to name `CanUseComponent` directly.** +[`check_components!`](../macros/check_components.md) and +[`delegate_and_check_components!`](../macros/delegate_and_check_components.md) generate the assertion +that uses it. What you write is the check; this page explains what a check actually asserts, so that its +failure is legible. + +::: + ## What it's for CGP's wiring is lazy: writing a wiring line does not check that the chosen implementation's own requirements diff --git a/docs/reference/traits/concat_path.md b/docs/reference/traits/concat_path.md index 73cef5cf..41882599 100644 --- a/docs/reference/traits/concat_path.md +++ b/docs/reference/traits/concat_path.md @@ -6,6 +6,18 @@ sidebar_label: 'ConcatPath' Joining two type-level paths. +:::info + +### Generated machinery + +**You are not expected to call `ConcatPath` directly.** +[`cgp_namespace!`](../macros/cgp_namespace.md) and [`RedirectLookup`](../providers/redirect_lookup.md) +use it to extend a route one segment at a time, and [`ChainGetters`](../providers/chain_getters.md) to +descend into a nested context. This page explains the operation, so that a composed path in an +expansion or an error message is legible. + +::: + ## What it's for A [`Path!`](../macros/path.md) is a type-level list of segments — the route a namespaced component diff --git a/docs/reference/traits/concat_product.md b/docs/reference/traits/concat_product.md index 138e23fe..749cf477 100644 --- a/docs/reference/traits/concat_product.md +++ b/docs/reference/traits/concat_product.md @@ -6,6 +6,17 @@ sidebar_label: 'ConcatProduct' Splicing one type-level product list onto the end of another. +:::info + +### Generated machinery + +**You are not expected to use `ConcatProduct` directly.** It is a type-level +operation the extensible-data machinery computes with, and you will most likely meet it in an error +message from code that walks a shape rather than in code you wrote. This page explains what it +produces. + +::: + ## What it's for Merging two records means merging their shapes, and the shapes are type-level lists — a diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/contains_value.md index f09dc38c..e074ef63 100644 --- a/docs/reference/traits/contains_value.md +++ b/docs/reference/traits/contains_value.md @@ -6,6 +6,17 @@ sidebar_label: 'ContainsValue' Naming the value a monad threads forward out of a step's output. +:::info + +### Generated machinery + +**You are not expected to name `ContainsValue`.** The +[bind providers](../providers/monad_providers.md) use it while running a step, and the monad markers CGP +ships already implement it. The one case for naming it is defining a monad of your own; otherwise this +page is here to explain how a step unwraps its input. + +::: + ## What it's for A step in a [monadic pipeline](/docs/concepts/monadic-handlers) produces a wrapped output — a `Result`, diff --git a/docs/reference/traits/default_impls1.md b/docs/reference/traits/default_impls1.md index 67413a31..d9f6a569 100644 --- a/docs/reference/traits/default_impls1.md +++ b/docs/reference/traits/default_impls1.md @@ -6,6 +6,18 @@ sidebar_label: 'DefaultImpls1' Resolving a namespace default keyed on a component *and* a type. +:::info + +### Generated machinery + +**You do not implement `DefaultImpls1`.** +[`#[default_impl(...)]`](../attributes/default_impl.md) emits the impls and a `for … in` statement inside +[`delegate_components!`](../macros/delegate_components.md) consumes them. You name the trait in those two +places only; this page explains what each of them emits, and the positional rule that is easy to get +backwards. + +::: + ## What it's for [`DefaultNamespace`](./default_namespace.md) keys a default on the component alone: one component, one diff --git a/docs/reference/traits/default_impls2.md b/docs/reference/traits/default_impls2.md index 2874a954..8940c45c 100644 --- a/docs/reference/traits/default_impls2.md +++ b/docs/reference/traits/default_impls2.md @@ -6,6 +6,17 @@ sidebar_label: 'DefaultImpls2' Resolving a namespace default keyed on a component and *two* types. +:::info + +### Generated machinery + +**You do not implement `DefaultImpls2`.** +[`#[default_impl(...)]`](../attributes/default_impl.md) emits the impls and a `for … in` statement +consumes them, exactly as for its one-type sibling. You name the trait in those two places only; this +page explains what they emit. + +::: + ## What it's for [`DefaultImpls1`](./default_impls1.md) keys a namespace default on a component plus one type, which is diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md index fbee1dce..3f343b35 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/default_namespace.md @@ -6,6 +6,19 @@ sidebar_label: 'DefaultNamespace' Resolving a namespace's default provider for a component. +:::info + +### Generated machinery + +**You do not implement `DefaultNamespace`.** +[`cgp_namespace!`](../macros/cgp_namespace.md) and its +[`#[prefix(...)]`](../macros/cgp_namespace.md) attribute emit the impls. You name the trait in exactly +one place — a `namespace` header inside +[`delegate_components!`](../macros/delegate_components.md) — and this page explains what that header +generates, including why a direct entry can shadow an inherited default without conflicting with it. + +::: + ## What it's for A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/delegate_component.md index 4c4ffe23..378a2e20 100644 --- a/docs/reference/traits/delegate_component.md +++ b/docs/reference/traits/delegate_component.md @@ -6,6 +6,18 @@ sidebar_label: 'DelegateComponent' The per-context type-level table mapping a component key to its provider. +:::info + +### Generated machinery + +**You are not expected to write `DelegateComponent` impls.** +[`delegate_components!`](../macros/delegate_components.md) emits one per entry of a wiring table, and +[`cgp_namespace!`](../macros/cgp_namespace.md) emits the blanket forwarding impls behind a namespace. +What you write is the table. This page explains what the table *becomes*, so that an expansion or a +wiring error naming this trait is legible. + +::: + ## What it's for Wiring a **context** — the type the capability runs against, which supplies the values it needs as its diff --git a/docs/reference/traits/field_getter.md b/docs/reference/traits/field_getter.md index e4bde7b8..e4689dd3 100644 --- a/docs/reference/traits/field_getter.md +++ b/docs/reference/traits/field_getter.md @@ -6,6 +6,17 @@ sidebar_label: 'FieldGetter' The provider-side mirror of `HasField` — field access that gets wired. +:::info + +### Generated machinery + +**You are not expected to implement `FieldGetter`.** +[`#[cgp_getter]`](../macros/cgp_getter.md) generates it as the getter's provider trait, and +[`UseField`](../providers/use_field.md) is the provider you wire to satisfy it. What you write is the +wiring entry; this page explains the shape that entry resolves through. + +::: + ## What it's for [`HasField`](./has_field.md) is a bound an implementation states about its own context. Sometimes field diff --git a/docs/reference/traits/field_mapper.md b/docs/reference/traits/field_mapper.md index b4551426..8d36e14f 100644 --- a/docs/reference/traits/field_mapper.md +++ b/docs/reference/traits/field_mapper.md @@ -6,6 +6,16 @@ sidebar_label: 'FieldMapper' The provider-side mirror of `MapField`. +:::info + +### Generated machinery + +**You will not call `map_field` yourself.** It is a blanket impl over every +[`FieldGetter`](./field_getter.md), and [`ChainGetters`](../providers/chain_getters.md) is its only +caller in practice. This page explains the mechanism a chained getter is built from. + +::: + ## What it's for [`MapField`](./map_field.md) reads through a field without forcing its type to be `'static`, by taking a diff --git a/docs/reference/traits/has_fields_ref.md b/docs/reference/traits/has_fields_ref.md index e98db2d0..5df16c65 100644 --- a/docs/reference/traits/has_fields_ref.md +++ b/docs/reference/traits/has_fields_ref.md @@ -6,6 +6,17 @@ sidebar_label: 'HasFieldsRef' A type's whole shape, with every value borrowed. +:::info + +### Generated machinery + +**You are not expected to implement `HasFieldsRef`.** +[`#[derive(HasFields)]`](../derives/derive_has_fields.md) emits it alongside the owned shape. What +generic code writes is a bound; this page explains the type the derive produces, including the reserved +lifetime name that shows up in an error message. + +::: + ## What it's for [`HasFields`](./has_fields.md) describes a type as a list of named entries holding owned values. Code diff --git a/docs/reference/traits/is_provider_for.md b/docs/reference/traits/is_provider_for.md index efb791a4..015d4af1 100644 --- a/docs/reference/traits/is_provider_for.md +++ b/docs/reference/traits/is_provider_for.md @@ -6,6 +6,17 @@ sidebar_label: 'IsProviderFor' The marker supertrait that makes a provider's missing dependency show up by name. +:::info + +### Generated machinery + +**You never write `IsProviderFor` yourself.** The provider macros — +[`#[cgp_impl]`](../macros/cgp_impl.md) and [`#[cgp_provider]`](../macros/cgp_provider.md), which also +covers `#[cgp_new_provider]` — derive it from the same `where` clause you already wrote. This page explains what they emit, because this trait is what a missing-dependency error +names, and reading that error is the reason to know it exists. + +::: + ## What it's for An implementation in CGP states what it needs from its **context** — the type the capability runs against — diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/lift_value.md index 874ace24..f688f703 100644 --- a/docs/reference/traits/lift_value.md +++ b/docs/reference/traits/lift_value.md @@ -6,6 +6,18 @@ sidebar_label: 'LiftValue' Putting a value back into a monad's output type, on either branch. +:::info + +### Generated machinery + +**You are not expected to name `LiftValue`.** The +[bind providers](../providers/monad_providers.md) use it while running a step, and the monad markers CGP +ships already implement it. The one case for naming it is defining a monad of your own; otherwise this +page is here to explain how a step produces its output — and why that takes two methods rather than +one. + +::: + ## What it's for A bind step in a [monadic pipeline](/docs/concepts/monadic-handlers) unwraps a value, runs a diff --git a/docs/reference/traits/map_field.md b/docs/reference/traits/map_field.md index 1e4a5a18..10c3fb70 100644 --- a/docs/reference/traits/map_field.md +++ b/docs/reference/traits/map_field.md @@ -6,6 +6,17 @@ sidebar_label: 'MapField' Reading through a field without forcing its type to be `'static`. +:::info + +### Generated machinery + +**You will not call `map_field` yourself.** It is a blanket impl that every +[`HasField`](./has_field.md) already has, and [`ChainGetters`](../providers/chain_getters.md) is what +uses it to descend into a nested context. This page explains the lifetime problem it exists to solve, +which is why reaching a nested field is a provider rather than two chained reads. + +::: + ## What it's for Chaining field reads looks like it should just work — read a field, then read a field of *that* — diff --git a/docs/reference/traits/map_fields.md b/docs/reference/traits/map_fields.md index a0acc690..993c3ce8 100644 --- a/docs/reference/traits/map_fields.md +++ b/docs/reference/traits/map_fields.md @@ -6,6 +6,18 @@ sidebar_label: 'MapFields' Rewriting every entry of a type-level list through one marker. +:::info + +### Generated machinery + +**You are not expected to use `MapFields` directly.** It is the type-level operation +behind a partial record's shape, computed by the machinery +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) generates. You will most likely meet it in an error +message; this page explains what it produces, and how it differs from the two similarly-named traits +beside it. + +::: + ## What it's for A partial record is the same record with every field's storage changed the same way — each value wrapped diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index fda2429d..c180e6b4 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -6,6 +6,18 @@ sidebar_label: '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 CGP, +and the partial types parameterized by them are generated by +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) 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. + +::: + ## What it's for CGP represents a half-built struct or a partly-extracted enum as a single type whose every field is diff --git a/docs/reference/traits/map_type_ref.md b/docs/reference/traits/map_type_ref.md index 8b73c327..dbe5f207 100644 --- a/docs/reference/traits/map_type_ref.md +++ b/docs/reference/traits/map_type_ref.md @@ -6,6 +6,17 @@ sidebar_label: 'MapTypeRef' The marker trait deciding how a borrowed partial type holds its payloads. +:::info + +### Generated machinery + +**You are not expected to implement `MapTypeRef`.** Its three markers are supplied +by CGP, and [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) generates the borrowed +companion that carries one. What you do with this trait is recognize its markers in an error; this page +explains what each one means and how it composes with the per-field markers. + +::: + ## What it's for [`MapType`](./map_type.md) decides whether a field of a partial type holds its value, nothing, or an diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monadic_bind.md index dcb5e64d..91ea4705 100644 --- a/docs/reference/traits/monadic_bind.md +++ b/docs/reference/traits/monadic_bind.md @@ -6,6 +6,17 @@ sidebar_label: 'MonadicBind' Turning a continuation into one bind step of a monadic pipeline. +:::info + +### Generated machinery + +**You are not expected to name `MonadicBind`.** +[`PipeMonadic`](../providers/monad_providers.md) bounds on it while folding a pipeline, and the monad +markers CGP ships already implement it. The one case for naming it is defining a monad of your own; +otherwise this page is here to explain how a pipeline is assembled. + +::: + ## What it's for A [monadic pipeline](/docs/concepts/monadic-handlers) chains steps where each may either continue or diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monadic_trans.md index f3c45860..7ebb04cc 100644 --- a/docs/reference/traits/monadic_trans.md +++ b/docs/reference/traits/monadic_trans.md @@ -6,6 +6,17 @@ sidebar_label: 'MonadicTrans' Stacking one monad on top of another. +:::info + +### Generated machinery + +**You are not expected to name `MonadicTrans`.** +[`PipeMonadic`](../providers/monad_providers.md) resolves a stacked monad through it before any binding +happens, and the transformer markers CGP ships already implement it. The one case for naming it is giving +a monad of your own a transformer form; otherwise this page is here to explain how monads stack. + +::: + ## What it's for A [monadic pipeline](/docs/concepts/monadic-handlers) over a nested output — a `Result` inside a diff --git a/docs/reference/traits/mut_field_getter.md b/docs/reference/traits/mut_field_getter.md index b3a237b7..4082be27 100644 --- a/docs/reference/traits/mut_field_getter.md +++ b/docs/reference/traits/mut_field_getter.md @@ -6,6 +6,17 @@ sidebar_label: 'MutFieldGetter' The provider-side mirror of `HasFieldMut` — wired field access that can mutate. +:::info + +### Generated machinery + +**You are not expected to implement `MutFieldGetter`.** +[`#[cgp_getter]`](../macros/cgp_getter.md) generates it alongside its supertrait, and +[`UseField`](../providers/use_field.md) satisfies both. What you write is the wiring entry; this page +explains what the mutable half of that entry provides. + +::: + ## What it's for [`FieldGetter`](./field_getter.md) is field access in provider-trait shape, so that a context can choose diff --git a/docs/reference/traits/partial_data.md b/docs/reference/traits/partial_data.md index c544977c..05badb54 100644 --- a/docs/reference/traits/partial_data.md +++ b/docs/reference/traits/partial_data.md @@ -6,6 +6,18 @@ sidebar_label: 'PartialData' Naming the concrete type a partial value is on its way to becoming. +:::info + +### Generated machinery + +**You are not expected to implement `PartialData`.** +[`#[derive(BuildField)]`](../derives/derive_build_field.md) and +[`#[derive(ExtractField)]`](../derives/derive_extract_field.md) emit it for every companion type they +generate. What you meet is the projection `Self::Target` in another trait's signature; this page explains +where that projection comes from. + +::: + ## What it's for A partial record is a companion type — `__PartialPerson` — and generic code holding diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md index b85fad95..99b28421 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/static_format.md @@ -6,6 +6,17 @@ sidebar_label: 'StaticFormat' Writing a type-level string into a formatter — the trait behind `Display` on `Symbol`. +:::info + +### Generated machinery + +**You are not expected to name `StaticFormat`.** It backs the `Display` impls on +`Symbol` and `Chars`, which is how a type-level string prints at all — so reach for `Display`, or for +[`StaticString`](./static_string.md) when you want a constant. This page explains the trait behind them, +and the narrow case where bounding on it is the answer. + +::: + ## What it's for CGP encodes field and variant names as *types*, so a name can drive trait resolution. Printing one means diff --git a/docs/reference/traits/transform_map_default.md b/docs/reference/traits/transform_map_default.md index 3dc1a384..2427985e 100644 --- a/docs/reference/traits/transform_map_default.md +++ b/docs/reference/traits/transform_map_default.md @@ -6,6 +6,18 @@ sidebar_label: 'TransformMapDefault' The transform marker that makes every field present, defaulting whatever is not. +:::info + +### Generated machinery + +**You are not expected to name `TransformMapDefault` directly.** It is the +marker [`CanFinalizeWithDefault`](./can_finalize_with_default.md) and +[`CanBuildWithDefault`](./can_build_with_default.md) drive, and calling one of those is what you write. +This page explains the three conversions behind them — which is also the model to copy if you write a +transform of your own. + +::: + ## What it's for [`CanFinalizeWithDefault`](./can_finalize_with_default.md) works by re-marking every field of a partial diff --git a/docs/reference/traits/transform_map_fields.md b/docs/reference/traits/transform_map_fields.md index ad0c6045..a90a1d75 100644 --- a/docs/reference/traits/transform_map_fields.md +++ b/docs/reference/traits/transform_map_fields.md @@ -6,6 +6,17 @@ sidebar_label: 'TransformMapFields' Applying one per-field transform across a whole partial record. +:::info + +### Generated machinery + +**You are not expected to call `transform_map_fields` directly.** It is the +recursion the optional-field layer is built from, and +[`CanFinalizeWithDefault`](./can_finalize_with_default.md) and [`ToOptional`](./to_optional.md) are what +you call. This page explains the walk, which is what makes those two behave so symmetrically. + +::: + ## What it's for [`TransformMap`](./transform_map.md) converts *one* field from one marker's storage to another's. diff --git a/docs/reference/traits/transform_optional.md b/docs/reference/traits/transform_optional.md index 7768a616..90ed2cc9 100644 --- a/docs/reference/traits/transform_optional.md +++ b/docs/reference/traits/transform_optional.md @@ -6,6 +6,17 @@ sidebar_label: 'TransformOptional' The transform marker that makes every field optional. +:::info + +### Generated machinery + +**You are not expected to name `TransformOptional` directly.** It is the +marker [`ToOptional`](./to_optional.md) and [`HasOptionalBuilder`](./has_optional_builder.md) drive, and +calling one of those is what you write. This page explains the conversion behind them, and why it needs +less of a field's type than its defaulting counterpart does. + +::: + ## What it's for [`ToOptional`](./to_optional.md) re-marks every field of a partial record to `IsOptional`, so it can then diff --git a/docs/reference/traits/update_field.md b/docs/reference/traits/update_field.md index 6b6d2829..68bcea1c 100644 --- a/docs/reference/traits/update_field.md +++ b/docs/reference/traits/update_field.md @@ -6,6 +6,18 @@ sidebar_label: 'UpdateField' The primitive that moves one field of a partial record between states. +:::info + +### Generated machinery + +**You are not expected to call `update_field` directly.** It is the per-field +primitive [`#[derive(BuildField)]`](../derives/derive_build_field.md) emits, and +[`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are the two directions you actually +call. This page explains the primitive, because it is what makes build order free and what the +optional-field layer reaches for when neither direction fits. + +::: + ## What it's for Everything in the [builder family](./has_builder.md) reduces to one operation: change one field's storage From 68175a323bfa0946df923981a01fd077a395410f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 2 Aug 2026 23:54:18 +0200 Subject: [PATCH 032/516] Restore the reference index's completeness, and honour the notice rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Splitting the derives and traits groups left thirty trait pages and attributes/default_impl.md unreachable from the reference index. The sidebar still listed them and the build still passed, so nothing looked wrong — but information-architecture.md makes the index the surface where every construct has an entry, and it had quietly stopped being one. The index now reaches all of them. The extensible-data families were too many to name in running prose without burying the job-grouped structure, so they get a table of the whole set — shape, builder, extractor, casts, optional fields, field state, and shape computation — while the field-access mirrors, the two DefaultImpls, #[default_impl], and StaticFormat are woven into the prose that already covers their job. The lookup table's opening also stops explaining itself as "constructs chosen together", which was the old granularity rule's reasoning, and states the current one: what remains there is markers, aliases, and component variants, none of which are separately constructs. Thirteen of the twenty-seven Generated machinery notices broke the rule that introduced them. Each asserted that a reader is not expected to use the construct while the page's own When to reach for it gave a real direct-use case a paragraph later. Each now names that case in a closing sentence, which is what the rule asks for and what keeps the notice from overclaiming. Two smaller repairs. concat_path.md's Under the hood held a code block containing only comments, where that section owes the exact expansion; it now shows the two impls, with the ?Sized detail that distinguishes the recursion from ConcatProduct's. And the mirror crate had drifted from the pages it mirrors: derive_cgp_record.rs kept a module named for the old combined page, and the rewritten CgpData umbrella page had an Examples section with no counterpart. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01PQ3tpcNckW7LS1zjPAxuSD --- docs/reference/index.md | 43 +++++++++++++++---- docs/reference/traits/append_product.md | 2 +- docs/reference/traits/concat_path.md | 22 +++++++--- docs/reference/traits/concat_product.md | 2 +- docs/reference/traits/field_getter.md | 2 +- docs/reference/traits/field_mapper.md | 2 +- docs/reference/traits/map_field.md | 2 +- docs/reference/traits/map_fields.md | 2 +- docs/reference/traits/map_type.md | 2 +- docs/reference/traits/map_type_ref.md | 2 +- docs/reference/traits/mut_field_getter.md | 2 +- docs/reference/traits/partial_data.md | 2 +- docs/reference/traits/transform_map_fields.md | 2 +- docs/reference/traits/transform_optional.md | 2 +- .../src/reference/derives/derive_cgp_data.rs | 40 +++++++++++++++++ .../reference/derives/derive_cgp_record.rs | 2 +- 16 files changed, 104 insertions(+), 27 deletions(-) diff --git a/docs/reference/index.md b/docs/reference/index.md index f28b49fe..3467b246 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -78,7 +78,13 @@ the table is made of. An [`#[implicit]`](./attributes/implicit.md) argument is the default way to read a field: it looks like an ordinary function parameter and is filled from a same-named field on the context. The field access itself comes from [`#[derive(HasField)]`](./derives/derive_has_field.md) and the -[`HasField`](./traits/has_field.md) trait. +[`HasField`](./traits/has_field.md) trait, whose mutable form is +[`HasFieldMut`](./traits/has_field_mut.md). Four further traits are the machinery underneath, generated +rather than written: [`FieldGetter`](./traits/field_getter.md) and +[`MutFieldGetter`](./traits/mut_field_getter.md) are the provider-side mirrors a getter component is +wired through, and [`MapField`](./traits/map_field.md) with +[`FieldMapper`](./traits/field_mapper.md) are what let a getter reach into a nested value without +forcing its type to be `'static`. Getter traits are the sparing alternative, for the cases an implicit argument cannot reach. [`#[cgp_auto_getter]`](./macros/cgp_auto_getter.md) generates one from the method name; @@ -165,14 +171,30 @@ optional-field extensions starting at [`HasOptionalBuilder`](./traits/has_optional_builder.md). Each entry in a shape is a [`Field`](./types/field.md). +Those families run to a good many traits, most of which you read rather than write. The table below is +the whole set, so that a name met in an expansion or an error message can be looked up from here. + +| Family | The traits in it | +|---|---| +| The shape | [`HasFields`](./traits/has_fields.md), [`HasFieldsRef`](./traits/has_fields_ref.md), [`ToFields`](./traits/to_fields.md), [`FromFields`](./traits/from_fields.md), [`ToFieldsRef`](./traits/to_fields_ref.md) | +| Building a record | [`HasBuilder`](./traits/has_builder.md), [`IntoBuilder`](./traits/into_builder.md), [`BuildField`](./traits/build_field.md), [`TakeField`](./traits/take_field.md), [`UpdateField`](./traits/update_field.md), [`PartialData`](./traits/partial_data.md), [`FinalizeBuild`](./traits/finalize_build.md) | +| Taking an enum apart | [`HasExtractor`](./traits/has_extractor.md), [`HasExtractorRef`](./traits/has_extractor_ref.md), [`HasExtractorMut`](./traits/has_extractor_mut.md), [`ExtractField`](./traits/extract_field.md), [`FinalizeExtract`](./traits/finalize_extract.md), [`FinalizeExtractResult`](./traits/finalize_extract_result.md), [`FromVariant`](./traits/from_variant.md) | +| Converting between shapes | [`CanUpcast`](./traits/can_upcast.md), [`CanDowncast`](./traits/can_downcast.md), [`CanDowncastFields`](./traits/can_downcast_fields.md), [`CanBuildFrom`](./traits/can_build_from.md) | +| Optional and defaulted fields | [`HasOptionalBuilder`](./traits/has_optional_builder.md), [`ToOptional`](./traits/to_optional.md), [`SetOptional`](./traits/set_optional.md), [`FinalizeOptional`](./traits/finalize_optional.md), [`CanFinalizeWithDefault`](./traits/can_finalize_with_default.md), [`CanBuildWithDefault`](./traits/can_build_with_default.md) | +| Field state, and changing it | [`MapType`](./traits/map_type.md), [`MapTypeRef`](./traits/map_type_ref.md), [`TransformMap`](./traits/transform_map.md), [`TransformMapFields`](./traits/transform_map_fields.md), [`TransformMapDefault`](./traits/transform_map_default.md), [`TransformOptional`](./traits/transform_optional.md) | +| Computing a shape | [`AppendProduct`](./traits/append_product.md), [`ConcatProduct`](./traits/concat_product.md), [`MapFields`](./traits/map_fields.md) | + ### Keep large wiring manageable [`cgp_namespace!`](./macros/cgp_namespace.md) defines a reusable, inheritable wiring table that many contexts can join, which is how top-level wiring stays short as component counts grow. It works through [`RedirectLookup`](./providers/redirect_lookup.md), which re-routes a lookup along a -[`Path!`](./macros/path.md), together with the -[`DefaultNamespace`](./traits/default_namespace.md) traits that resolve inherited and per-type -defaults. The `open` statement of [`delegate_components!`](./macros/delegate_components.md) is a +[`Path!`](./macros/path.md), together with the three lookup traits that resolve inherited and per-type +defaults — [`DefaultNamespace`](./traits/default_namespace.md) for a key that is a component alone, and +[`DefaultImpls1`](./traits/default_impls1.md) and [`DefaultImpls2`](./traits/default_impls2.md) when the +key carries one further type or two. A provider registers itself as one of those defaults with +[`#[default_impl(...)]`](./attributes/default_impl.md). The `open` statement of +[`delegate_components!`](./macros/delegate_components.md) is a lightweight special case of the same mechanism, and it supersedes the older [`UseDelegate`](./providers/use_delegate.md) tables and the [`#[derive_delegate]`](./attributes/derive_delegate.md) attribute that generates them. @@ -184,8 +206,10 @@ sugar — [`Symbol!`](./macros/symbol.md) for a field name, [`Product!`](./macro [`Sum!`](./macros/sum.md) for its dual, [`Path!`](./macros/path.md) for a route — and only need to recognize [what they expand into](./types/type_level_spines.md) when it appears in an error message. [`Index`](./types/index.md) tags a tuple field and [`Life`](./types/life.md) lifts a lifetime into a -type, while [`StaticString`](./traits/static_string.md) turns a type-level string back into runtime -data and [`ConcatPath`](./traits/concat_path.md) joins two paths. +type. Three traits turn those encodings back into runtime data: +[`StaticString`](./traits/static_string.md) decodes a type-level string into a constant, +[`StaticFormat`](./traits/static_format.md) writes one into a formatter and is what makes it printable +at all, and [`ConcatPath`](./traits/concat_path.md) joins two paths. When wiring fails, three traits are what you will see named: [`DelegateComponent`](./traits/delegate_component.md), @@ -195,9 +219,10 @@ name, and [`CanUseComponent`](./traits/can_use_component.md), which is what a ch ## Looking for a name you don't see? -A few constructs are documented alongside a close relative rather than on a page of their own, because -they are chosen together and separate pages would make you collate them. If you arrived knowing one of -these names, this is where it lives. +Almost every construct has a page of its own. The exceptions are names that are not separately +*constructs*: a **marker** is a type implementing a trait, an **alias** is another spelling of a +construct, and a **variant** of a component differs from it by one axis. Each is documented on the page +of the thing it belongs to. If you arrived knowing one of these names, this is where it lives. | Looking for | It's on | |---|---| diff --git a/docs/reference/traits/append_product.md b/docs/reference/traits/append_product.md index e4574639..807ff64b 100644 --- a/docs/reference/traits/append_product.md +++ b/docs/reference/traits/append_product.md @@ -13,7 +13,7 @@ Adding one entry to the end of a type-level product list. **You are not expected to use `AppendProduct` directly.** It is a type-level operation the extensible-data machinery computes with — the builder and merge recursions are its callers in practice. You will most likely meet it in an error message from code that walks a shape; this page -explains what it produces so that message is legible. +explains what it produces so that message is legible. The one case for naming it is generic code that must describe in a signature the shape it *will* produce. ::: diff --git a/docs/reference/traits/concat_path.md b/docs/reference/traits/concat_path.md index 41882599..fcbecd91 100644 --- a/docs/reference/traits/concat_path.md +++ b/docs/reference/traits/concat_path.md @@ -14,7 +14,7 @@ Joining two type-level paths. [`cgp_namespace!`](../macros/cgp_namespace.md) and [`RedirectLookup`](../providers/redirect_lookup.md) use it to extend a route one segment at a time, and [`ChainGetters`](../providers/chain_getters.md) to descend into a nested context. This page explains the operation, so that a composed path in an -expansion or an error message is legible. +expansion or an error message is legible. The one case for naming it is generic code that composes paths rather than writing one out. ::: @@ -99,14 +99,26 @@ the path spine. ::: -Two impls, one per spine node. Each node keeps its head segment and concatenates onto the tail; the -terminator becomes the other path outright: +Two impls, one per spine node. Each node keeps its head segment and rebuilds the tail; the terminator +becomes the other path outright: ```rust -// at the terminator, the whole second path is substituted -// at a node, the head is kept and the tail recurses +impl ConcatPath for PathCons +where + Tail: ConcatPath, +{ + type Output = PathCons>::Output>; +} + +impl ConcatPath for Nil { + type Output = Other; // the second path is substituted whole +} ``` +Note the `?Sized` on every parameter, including the associated type — that is what lets both operands +be the unsized markers a path is built from, and it is the one way this recursion differs from +[`ConcatProduct`](./concat_product.md)'s otherwise identical shape. + So the result is the first path's segments followed by the second's, in order, with the cost of resolution proportional to the first path's length. diff --git a/docs/reference/traits/concat_product.md b/docs/reference/traits/concat_product.md index 749cf477..6ad6ab96 100644 --- a/docs/reference/traits/concat_product.md +++ b/docs/reference/traits/concat_product.md @@ -13,7 +13,7 @@ Splicing one type-level product list onto the end of another. **You are not expected to use `ConcatProduct` directly.** It is a type-level operation the extensible-data machinery computes with, and you will most likely meet it in an error message from code that walks a shape rather than in code you wrote. This page explains what it -produces. +produces. The one case for naming it is generic code that must describe the shape produced by combining two others. ::: diff --git a/docs/reference/traits/field_getter.md b/docs/reference/traits/field_getter.md index e4689dd3..bc2d3bce 100644 --- a/docs/reference/traits/field_getter.md +++ b/docs/reference/traits/field_getter.md @@ -13,7 +13,7 @@ The provider-side mirror of `HasField` — field access that gets wired. **You are not expected to implement `FieldGetter`.** [`#[cgp_getter]`](../macros/cgp_getter.md) generates it as the getter's provider trait, and [`UseField`](../providers/use_field.md) is the provider you wire to satisfy it. What you write is the -wiring entry; this page explains the shape that entry resolves through. +wiring entry; this page explains the shape that entry resolves through. The one case for implementing it by hand is a getter whose value is computed rather than stored. ::: diff --git a/docs/reference/traits/field_mapper.md b/docs/reference/traits/field_mapper.md index 8d36e14f..96c71ad9 100644 --- a/docs/reference/traits/field_mapper.md +++ b/docs/reference/traits/field_mapper.md @@ -12,7 +12,7 @@ The provider-side mirror of `MapField`. **You will not call `map_field` yourself.** It is a blanket impl over every [`FieldGetter`](./field_getter.md), and [`ChainGetters`](../providers/chain_getters.md) is its only -caller in practice. This page explains the mechanism a chained getter is built from. +caller in practice. This page explains the mechanism a chained getter is built from. The one case for calling it directly is writing a getter provider of your own that has to descend. ::: diff --git a/docs/reference/traits/map_field.md b/docs/reference/traits/map_field.md index 10c3fb70..a2d8e9c2 100644 --- a/docs/reference/traits/map_field.md +++ b/docs/reference/traits/map_field.md @@ -13,7 +13,7 @@ Reading through a field without forcing its type to be `'static`. **You will not call `map_field` yourself.** It is a blanket impl that every [`HasField`](./has_field.md) already has, and [`ChainGetters`](../providers/chain_getters.md) is what uses it to descend into a nested context. This page explains the lifetime problem it exists to solve, -which is why reaching a nested field is a provider rather than two chained reads. +which is why reaching a nested field is a provider rather than two chained reads. The one case for calling it directly is writing a getter provider of your own that has to descend. ::: diff --git a/docs/reference/traits/map_fields.md b/docs/reference/traits/map_fields.md index 993c3ce8..9e6caae6 100644 --- a/docs/reference/traits/map_fields.md +++ b/docs/reference/traits/map_fields.md @@ -14,7 +14,7 @@ Rewriting every entry of a type-level list through one marker. behind a partial record's shape, computed by the machinery [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) generates. You will most likely meet it in an error message; this page explains what it produces, and how it differs from the two similarly-named traits -beside it. +beside it. The one case for naming it is generic code that must describe a uniformly re-wrapped shape. ::: diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index c180e6b4..c7b19ce3 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -14,7 +14,7 @@ The marker trait that decides how one field of a partial type is stored. and the partial types parameterized by them are generated by [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) 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. +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. ::: diff --git a/docs/reference/traits/map_type_ref.md b/docs/reference/traits/map_type_ref.md index dbe5f207..50b0d668 100644 --- a/docs/reference/traits/map_type_ref.md +++ b/docs/reference/traits/map_type_ref.md @@ -13,7 +13,7 @@ The marker trait deciding how a borrowed partial type holds its payloads. **You are not expected to implement `MapTypeRef`.** Its three markers are supplied by CGP, and [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) generates the borrowed companion that carries one. What you do with this trait is recognize its markers in an error; this page -explains what each one means and how it composes with the per-field markers. +explains what each one means and how it composes with the per-field markers. The one case for bounding on the trait is generic code of your own over a borrowed partial type's outer marker. ::: diff --git a/docs/reference/traits/mut_field_getter.md b/docs/reference/traits/mut_field_getter.md index 4082be27..81f3dfb4 100644 --- a/docs/reference/traits/mut_field_getter.md +++ b/docs/reference/traits/mut_field_getter.md @@ -13,7 +13,7 @@ The provider-side mirror of `HasFieldMut` — wired field access that can mutate **You are not expected to implement `MutFieldGetter`.** [`#[cgp_getter]`](../macros/cgp_getter.md) generates it alongside its supertrait, and [`UseField`](../providers/use_field.md) satisfies both. What you write is the wiring entry; this page -explains what the mutable half of that entry provides. +explains what the mutable half of that entry provides. The one case for implementing it by hand is a provider whose mutable access is not a plain field read. ::: diff --git a/docs/reference/traits/partial_data.md b/docs/reference/traits/partial_data.md index 05badb54..d55f0739 100644 --- a/docs/reference/traits/partial_data.md +++ b/docs/reference/traits/partial_data.md @@ -14,7 +14,7 @@ Naming the concrete type a partial value is on its way to becoming. [`#[derive(BuildField)]`](../derives/derive_build_field.md) and [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) emit it for every companion type they generate. What you meet is the projection `Self::Target` in another trait's signature; this page explains -where that projection comes from. +where that projection comes from. The one case for bounding on it is generic code that needs the destination type before the value is complete. ::: diff --git a/docs/reference/traits/transform_map_fields.md b/docs/reference/traits/transform_map_fields.md index a90a1d75..ce32df17 100644 --- a/docs/reference/traits/transform_map_fields.md +++ b/docs/reference/traits/transform_map_fields.md @@ -13,7 +13,7 @@ Applying one per-field transform across a whole partial record. **You are not expected to call `transform_map_fields` directly.** It is the recursion the optional-field layer is built from, and [`CanFinalizeWithDefault`](./can_finalize_with_default.md) and [`ToOptional`](./to_optional.md) are what -you call. This page explains the walk, which is what makes those two behave so symmetrically. +you call. This page explains the walk, which is what makes those two behave so symmetrically. The one case for bounding on it is writing a capability of your own that re-marks a whole record. ::: diff --git a/docs/reference/traits/transform_optional.md b/docs/reference/traits/transform_optional.md index 90ed2cc9..4c4c6e0e 100644 --- a/docs/reference/traits/transform_optional.md +++ b/docs/reference/traits/transform_optional.md @@ -13,7 +13,7 @@ The transform marker that makes every field optional. **You are not expected to name `TransformOptional` directly.** It is the marker [`ToOptional`](./to_optional.md) and [`HasOptionalBuilder`](./has_optional_builder.md) drive, and calling one of those is what you write. This page explains the conversion behind them, and why it needs -less of a field's type than its defaulting counterpart does. +less of a field's type than its defaulting counterpart does. The one case for naming it is writing a capability of your own that drives the optional conversion. ::: diff --git a/example-code/src/reference/derives/derive_cgp_data.rs b/example-code/src/reference/derives/derive_cgp_data.rs index 35a2ec72..86da8e9b 100644 --- a/example-code/src/reference/derives/derive_cgp_data.rs +++ b/example-code/src/reference/derives/derive_cgp_data.rs @@ -113,3 +113,43 @@ pub mod using_it { /// } /// ``` pub mod rejected_struct_style_variant {} + +/// ## Examples +/// +/// The umbrella page's own snippet: one derive covering both halves of a program. +pub mod examples { + use cgp::prelude::*; + + #[derive(CgpData)] + pub struct Circle { + pub radius: f64, + } + + #[derive(CgpData)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + #[test] + fn test_the_structs_gain_a_builder_and_the_enum_an_extractor() { + let circle: Circle = Circle::builder() + .build_field(PhantomData::, 1.0) + .finalize_build(); + + assert_eq!(circle.radius, 1.0); + + let shape = Shape::Circle(circle); + + assert!(shape + .to_extractor() + .extract_field(PhantomData::) + .is_ok()); + } +} diff --git a/example-code/src/reference/derives/derive_cgp_record.rs b/example-code/src/reference/derives/derive_cgp_record.rs index 0bb9b812..2e8da729 100644 --- a/example-code/src/reference/derives/derive_cgp_record.rs +++ b/example-code/src/reference/derives/derive_cgp_record.rs @@ -6,7 +6,7 @@ /// ## Examples /// /// The record half: `promote`, which merges one record into another's builder. -pub mod examples_record { +pub mod examples { use cgp::core::field::impls::CanBuildFrom; use cgp::prelude::*; From a0332708c704733aa2e51fd90f2a2b449ad833c2 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 22 Aug 2026 14:27:17 +0200 Subject: [PATCH 033/516] Rename What it's for to Overview, and rewrite cgp_component's section Rename the "What it's for" heading to "Overview" across all reference pages and their example-code doc comments, matching the knowledge base's updated writing guide. Rewrite the #[cgp_component] Overview itself: state the trait-preserved, macro-adds framing up front, explain the one-impl-per-type limit before naming the fix, and link out to the coherence and consumer/provider-trait explanation pages. Remove pseudo-cleft sentences, em dashes, and a few metaphors and passive constructions, following the base's new writing-styles guide. Co-Authored-By: Claude Sonnet 5 --- docs/reference/attributes/default_impl.md | 2 +- docs/reference/attributes/derive_delegate.md | 2 +- docs/reference/attributes/extend.md | 2 +- docs/reference/attributes/extend_where.md | 2 +- docs/reference/attributes/implicit.md | 2 +- docs/reference/attributes/use_provider.md | 2 +- docs/reference/attributes/use_type.md | 2 +- docs/reference/attributes/uses.md | 2 +- docs/reference/derives/derive_build_field.md | 2 +- docs/reference/derives/derive_cgp_data.md | 2 +- docs/reference/derives/derive_cgp_record.md | 2 +- docs/reference/derives/derive_cgp_variant.md | 2 +- .../reference/derives/derive_extract_field.md | 2 +- docs/reference/derives/derive_from_variant.md | 2 +- docs/reference/derives/derive_has_field.md | 2 +- docs/reference/derives/derive_has_fields.md | 2 +- docs/reference/macros/async_trait.md | 2 +- docs/reference/macros/blanket_trait.md | 2 +- docs/reference/macros/cgp_auto_dispatch.md | 2 +- docs/reference/macros/cgp_auto_getter.md | 2 +- docs/reference/macros/cgp_component.md | 73 +++++++++++-------- docs/reference/macros/cgp_computer.md | 2 +- docs/reference/macros/cgp_fn.md | 2 +- docs/reference/macros/cgp_getter.md | 2 +- docs/reference/macros/cgp_impl.md | 2 +- docs/reference/macros/cgp_namespace.md | 2 +- docs/reference/macros/cgp_producer.md | 2 +- docs/reference/macros/cgp_provider.md | 2 +- docs/reference/macros/cgp_type.md | 2 +- docs/reference/macros/check_components.md | 2 +- .../macros/delegate_and_check_components.md | 2 +- docs/reference/macros/delegate_components.md | 2 +- docs/reference/macros/path.md | 2 +- docs/reference/macros/product.md | 2 +- docs/reference/macros/sum.md | 2 +- docs/reference/macros/symbol.md | 2 +- docs/reference/traits/append_product.md | 2 +- docs/reference/traits/build_field.md | 2 +- docs/reference/traits/can_build_from.md | 2 +- .../traits/can_build_with_default.md | 2 +- docs/reference/traits/can_downcast.md | 2 +- docs/reference/traits/can_downcast_fields.md | 2 +- .../traits/can_finalize_with_default.md | 2 +- docs/reference/traits/can_upcast.md | 2 +- docs/reference/traits/can_use_component.md | 2 +- docs/reference/traits/concat_path.md | 2 +- docs/reference/traits/concat_product.md | 2 +- docs/reference/traits/contains_value.md | 2 +- docs/reference/traits/default_impls1.md | 2 +- docs/reference/traits/default_impls2.md | 2 +- docs/reference/traits/default_namespace.md | 2 +- docs/reference/traits/delegate_component.md | 2 +- docs/reference/traits/extract_field.md | 2 +- docs/reference/traits/field_getter.md | 2 +- docs/reference/traits/field_mapper.md | 2 +- docs/reference/traits/finalize_build.md | 2 +- docs/reference/traits/finalize_extract.md | 2 +- .../traits/finalize_extract_result.md | 2 +- docs/reference/traits/finalize_optional.md | 2 +- docs/reference/traits/from_fields.md | 2 +- docs/reference/traits/from_variant.md | 2 +- docs/reference/traits/has_builder.md | 2 +- docs/reference/traits/has_extractor.md | 2 +- docs/reference/traits/has_extractor_mut.md | 2 +- docs/reference/traits/has_extractor_ref.md | 2 +- docs/reference/traits/has_field.md | 2 +- docs/reference/traits/has_field_mut.md | 2 +- docs/reference/traits/has_fields.md | 2 +- docs/reference/traits/has_fields_ref.md | 2 +- docs/reference/traits/has_optional_builder.md | 2 +- docs/reference/traits/into_builder.md | 2 +- docs/reference/traits/is_provider_for.md | 2 +- docs/reference/traits/lift_value.md | 2 +- docs/reference/traits/map_field.md | 2 +- docs/reference/traits/map_fields.md | 2 +- docs/reference/traits/map_type.md | 2 +- docs/reference/traits/map_type_ref.md | 2 +- docs/reference/traits/monadic_bind.md | 2 +- docs/reference/traits/monadic_trans.md | 2 +- docs/reference/traits/mut_field_getter.md | 2 +- docs/reference/traits/partial_data.md | 2 +- docs/reference/traits/set_optional.md | 2 +- docs/reference/traits/static_format.md | 2 +- docs/reference/traits/static_string.md | 2 +- docs/reference/traits/take_field.md | 2 +- docs/reference/traits/to_fields.md | 2 +- docs/reference/traits/to_fields_ref.md | 2 +- docs/reference/traits/to_optional.md | 2 +- docs/reference/traits/transform_map.md | 2 +- .../reference/traits/transform_map_default.md | 2 +- docs/reference/traits/transform_map_fields.md | 2 +- docs/reference/traits/transform_optional.md | 2 +- docs/reference/traits/update_field.md | 2 +- .../reference/derives/derive_build_field.rs | 2 +- .../reference/derives/derive_extract_field.rs | 2 +- .../reference/derives/derive_from_variant.rs | 2 +- .../src/reference/derives/derive_has_field.rs | 2 +- .../reference/derives/derive_has_fields.rs | 2 +- .../reference/macros/delegate_components.rs | 2 +- 99 files changed, 142 insertions(+), 127 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 02503bb3..44eb3bc6 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -6,7 +6,7 @@ sidebar_label: '#[default_impl]' Register a provider as a namespace's default for a key. -## What it's for +## Overview A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the type the capability runs against — can opt into and then selectively override. Ordinarily a namespace's diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index ecb79151..7077f048 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -23,7 +23,7 @@ component that keeps it stays compatible with existing wiring. It is expected to ::: -## What it's for +## Overview A component generic over a type parameter usually wants a different implementation per value of it: `Rectangle` handled one way, `Circle` another. Something has to look at the type and pick, and written by diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 1dda4a04..5bd52dcc 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -6,7 +6,7 @@ sidebar_label: '#[extend]' Add a capability as a supertrait of a generated trait, so callers can rely on it too. -## What it's for +## Overview `#[extend]` declares that a capability is part of what a trait *guarantees*, rather than something its implementation happens to need. Where [`#[uses]`](uses.md) adds a private requirement, `#[extend]` adds a diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 2e8d9dda..e6f6e97d 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -6,7 +6,7 @@ sidebar_label: '#[extend_where]' Add `where` predicates to a generated trait's own definition, not just to its implementation. -## What it's for +## Overview A [`#[cgp_fn]`](../macros/cgp_fn.md) treats the `where` clause you write on the function as an implementation detail: the bounds land on the generated implementation and never appear on the generated diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 9976e8bd..da3b4eee 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -6,7 +6,7 @@ sidebar_label: '#[implicit]' Source a function argument from a same-named field on the context. -## What it's for +## Overview Reading a value out of the surrounding type is most of what CGP code does, and `#[implicit]` is what makes it look like an ordinary function parameter. You mark a parameter, and it disappears from the diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 50a2c261..754cca82 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -6,7 +6,7 @@ sidebar_label: '#[use_provider]' Depend on another implementation by name, without writing the context argument its bound requires. -## What it's for +## Overview An implementation can be parameterized by *another* implementation — a wrapper that scales whatever an inner calculator produces, a retry layer over whatever performs the request. Declaring that dependency diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 998ac6a4..5c09ac9f 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -6,7 +6,7 @@ sidebar_label: '#[use_type]' Import an abstract associated type and write it as a bare name. -## What it's for +## Overview Generic CGP code constantly needs a type it does not choose — an error type, a scalar, a database handle — supplied by the **context**, the type the code runs against. Such a type lives as an diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 0883237e..1f80f30f 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -6,7 +6,7 @@ sidebar_label: '#[uses]' Import the capabilities an implementation depends on, reading like a `use` statement. -## What it's for +## Overview An implementation usually calls capabilities defined elsewhere, and to do so it has to require that the **context** — the type it runs against — provides them. Written out, that requirement is a bound on diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 2d560b9a..371888a7 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -6,7 +6,7 @@ sidebar_label: '#[derive(BuildField)]' Builder support for a record. -## What it's for +## Overview A struct literal has to be written in one place that names the concrete type and supplies every field at once. That is usually what you want — and it is exactly wrong when the fields come from several independent diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 4b54edf6..a0175b31 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -6,7 +6,7 @@ sidebar_label: '#[derive(CgpData)]' The umbrella extensible-data derive, for a struct or an enum. -## What it's for +## Overview A plain Rust struct or enum is opaque to generic code. There is no way to refer to "the `first_name` field" or "the `Circle` variant" through a type parameter, so anything that must work across several diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index dc43a45f..cf359783 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -6,7 +6,7 @@ sidebar_label: '#[derive(CgpRecord)]' The extensible-data derive for a struct. -## What it's for +## Overview A plain Rust struct is opaque to generic code. There is no way to refer to "the `first_name` field" through a type parameter, so anything that must work across several structs ends up written once per diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index a672c4b7..3b557ac6 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -6,7 +6,7 @@ sidebar_label: '#[derive(CgpVariant)]' The extensible-data derive for an enum. -## What it's for +## Overview A plain Rust enum is opaque to generic code. There is no way to refer to "the `Circle` variant" through a type parameter, so anything that must work across several enums ends up written once per enum — and diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 7d1549ba..c950ddb4 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -6,7 +6,7 @@ sidebar_label: '#[derive(ExtractField)]' Extractor support for a variant. -## What it's for +## Overview A `match` on an enum is checked for exhaustiveness, which is one of Rust's best properties — and it only works where the concrete enum is named. Code that is generic over the enum cannot write a `match`, so it diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 1d45e23b..14948ca9 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -6,7 +6,7 @@ sidebar_label: '#[derive(FromVariant)]' Generic construction of an enum from one of its named variants. -## What it's for +## Overview `Shape::Circle(circle)` names two things: the enum, and the variant. That is fine at a concrete call site and useless to code that knows neither — a routine that has been handed a value and told which variant to wrap it diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index c9c23185..6cedfb80 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -6,7 +6,7 @@ sidebar_label: '#[derive(HasField)]' Per-field accessors keyed by a type-level tag. -## What it's for +## Overview An implementation written against a **context** — the type the capability runs against, which supplies the values it needs as its fields — cannot name that context's concrete type. It is generic over it, so diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index c887e103..2fd83c5d 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -6,7 +6,7 @@ sidebar_label: '#[derive(HasFields)]' The whole-struct or whole-enum field-list view. -## What it's for +## Overview Some code needs one field of a type. Other code needs the *shape* of the type: every field, its name, and its type, so it can walk them. A serializer, a validator, a builder that merges two structs, a dispatcher diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index d01c9355..0827402e 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -6,7 +6,7 @@ sidebar_label: '#[async_trait]' Rewrite a trait's `async fn` declarations into the lint-clean `-> impl Future` form CGP's async methods use. -## What it's for +## Overview Writing a bare `async fn` inside a trait compiles on stable Rust, and the compiler warns about it. The `async_fn_in_trait` lint fires because the future such a method returns is *opaque*: a caller working through diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 13533fa2..2bd6a6ee 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -6,7 +6,7 @@ sidebar_label: '#[blanket_trait]' Generate a blanket impl from a trait with default methods and supertrait dependencies. -## What it's for +## Overview The pattern CGP is built on is an **extension trait**: a trait with a clean interface whose [blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) carries the diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 84320137..b7ce68ca 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -6,7 +6,7 @@ sidebar_label: '#[cgp_auto_dispatch]' Generate a handler that dispatches over an extensible-data input from a per-type trait. -## What it's for +## Overview `#[cgp_auto_dispatch]` answers a common shape: **you have a trait with one implementation per type, and you want it to work on an enum of those types too.** diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index a82c6740..80b25243 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -6,7 +6,7 @@ sidebar_label: '#[cgp_auto_getter]' Define a getter as a blanket impl over `HasField`, keyed by the method name. -## What it's for +## Overview `#[cgp_auto_getter]` publishes a context field as a named, reusable accessor. You write a trait of getter methods, and the macro implements it for every **context** — the type the capability runs against, which diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index c572b929..3c5a303b 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -7,35 +7,50 @@ sidebar_label: '#[cgp_component]' Turn a trait into a component: the consumer trait callers use, the provider trait implementations target, and the key that wires them together. -## What it's for - -An ordinary Rust [trait](https://doc.rust-lang.org/book/ch10-02-traits.html) can have only one -implementation per type. That is usually what you want, and it is what lets the compiler resolve a -`where T: Display` bound without anyone naming an implementation — but it means a capability with -several plausible implementations has nowhere to put them. A type either sends real email or records -it for a test; it cannot do both, and choosing between them means editing the impl rather than -choosing at the point of use. - -`#[cgp_component]` splits that one trait into two, so that *using* a capability and *implementing* it -stop being the same act: - -- The **consumer trait** is what callers write — `rect.area()`. It keeps the name and shape you gave - it. -- The **provider trait** is what implementations target. It is the same interface with `Self` moved - into an explicit type parameter, so an implementation is written for a small named type of its own - rather than for the type the capability is about. - -Because each implementation now targets its own name, any number of them can coexist. A **provider** -is one of those names — a zero-sized type such as `RectangleArea` that exists only to identify an -implementation. A **context** — the type the capability runs against, which supplies the values it -needs as its fields — then picks the provider it wants through -[`delegate_components!`](./delegate_components.md), and generated glue routes calls on the consumer -trait to the provider that was picked. The whole choice is resolved during compilation and compiles -down to a direct call. - -The macro also emits a **component name** — a marker type such as `AreaCalculatorComponent` — which is -the key wiring uses. You will see it in every `delegate_components!` entry and in most compiler -errors, so it is worth recognizing even though you never write its definition. +## Overview + +`#[cgp_component]` can be applied to any Rust trait definition to give that trait the full set of +CGP's capabilities. Applying it takes nothing away: the trait you wrote keeps working exactly as it +did, now under the name CGP calls the **consumer trait**, and every call site that already uses it +keeps compiling unchanged. The macro adds a matching **provider trait** for implementations to target, +a small marker type called the **component** that names the capability for wiring, and a pair of +[**blanket implementations**](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) +that connect the three without requiring you to write them. + +`#[cgp_component]` makes it possible to define several overlapping implementations of one capability +at once. An ordinary Rust trait does not allow this. A +[trait](https://doc.rust-lang.org/book/ch10-02-traits.html) can have only one implementation per +type, a rule called [coherence](/docs/concepts/coherence). That rule is usually the right one: it lets +the compiler resolve a `where T: Display` bound without anyone naming which implementation applies. +But it also means a capability with several plausible implementations has nowhere to put the +alternatives. A type can send real email or record it for a test, never both at once, and switching +between the two means editing the impl itself rather than choosing between them at the point of use. + +`#[cgp_component]` solves that by splitting the one trait into two: the +[consumer and provider traits](/docs/concepts/consumer-and-provider-traits), so that *using* a +capability and *implementing* it stop being the same act. + +- The **consumer trait** is the trait callers write, such as `rect.area()`. It is your original + trait, kept exactly as you wrote it. +- An implementation targets the **provider trait** instead. It repeats the same methods with `Self` + moved into an explicit type parameter, so you write an implementation for a small named type of its + own rather than for the type the capability is actually about. + +Moving `Self` out of the way lets more than one implementation coexist: each one now targets its own +small type instead of competing for the single `Self` slot every plain trait has. A **provider** is +one of those targets: a zero-sized type such as `RectangleArea` that carries no data of its own and +exists only to name one implementation. The type the capability actually runs against is called the +**context**. It supplies whatever values an implementation needs as its own fields, then picks the +provider it wants through [`delegate_components!`](./delegate_components.md), and the generated +blanket implementations route a call on the consumer trait through to that choice automatically. None +of this costs anything at runtime. Wiring fixes the provider once, at compile time, and the compiler +turns the call into a direct, statically-dispatched call, exactly as if you had written the +implementation yourself. + +The macro's last piece is the **component** itself, a marker type such as `AreaCalculatorComponent` +that names the capability and is the key `delegate_components!` wires against. You will meet it in +every wiring entry and in most compiler errors that involve this capability, so you should be able to +recognize it immediately, even though you never write its definition yourself. ## Using it diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 4ede48a5..83aa6117 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -6,7 +6,7 @@ sidebar_label: '#[cgp_computer]' Define a `Computer` provider from a plain function. -## What it's for +## Overview CGP models computation as a family of components varying along three axes — synchronous or async, fallible or not, taking an input or not. A provider in that family is a struct with one or more impls threading a diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index f02db2ed..7fce1bea 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -6,7 +6,7 @@ sidebar_label: '#[cgp_fn]' Define a single-implementation capability as a blanket-impl trait, straight from a function. -## What it's for +## Overview `#[cgp_fn]` is the smallest amount of CGP that does anything useful. You write a plain function, mark the values it needs from the **context** — the type the capability runs against, which supplies those diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index d4f7e89d..dde7d791 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -6,7 +6,7 @@ sidebar_label: '#[cgp_getter]' Define a getter as a full component, so the field it reads is chosen by wiring rather than by its name. -## What it's for +## Overview [`#[cgp_auto_getter]`](./cgp_auto_getter.md) ties a getter to a field of the same name: declare `fn name(&self) -> &str` and every context with a `name` field satisfies it. That is the right trade almost diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 4ded4256..938d6d58 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -7,7 +7,7 @@ sidebar_label: '#[cgp_impl]' Write a provider using consumer-trait syntax, keeping `self`, `Self`, and the method signatures you already know. -## What it's for +## Overview A [provider trait](./cgp_component.md) is shaped inside-out compared with the trait it came from. The original `Self` has moved into an explicit leading type parameter, the implementation targets a small diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index ce77370c..0fd9829b 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -6,7 +6,7 @@ sidebar_label: 'cgp_namespace!' Define a reusable, inheritable wiring table that many contexts can join. -## What it's for +## Overview With [`delegate_components!`](./delegate_components.md) alone, every **context** — the type the capability runs against, which supplies the values it needs as its fields — spells out its own wiring entry by entry. diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 328b6287..a251d136 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -6,7 +6,7 @@ sidebar_label: '#[cgp_producer]' Define a `Producer` provider from an input-free function. -## What it's for +## Overview `#[cgp_producer]` is for the degenerate member of the handler family: a computation that takes no input and yields a value from nothing. A constant, a default, a seed for a pipeline. It is the input-free sibling of diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 31327494..61f72f5f 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -7,7 +7,7 @@ sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' Implement a provider trait directly, in the inside-out shape the sugar desugars to — with or without declaring the provider struct. -## What it's for +## Overview A provider trait is not shaped like the trait it came from. [`#[cgp_component]`](./cgp_component.md) moves the original `Self` into an explicit leading type parameter for the **context** — the type the diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 14db1b09..08c14b52 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -6,7 +6,7 @@ sidebar_label: '#[cgp_type]' Define an abstract-type component, whose concrete type each context chooses for itself. -## What it's for +## Overview Generic code often has to name a type it should not choose. A fallible operation returns *some* error, a geometry routine computes in *some* scalar, a storage layer holds *some* connection handle — and code diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 2e87a0a8..45af85d8 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -6,7 +6,7 @@ sidebar_label: 'check_components!' Assert at compile time that a context can actually use each component it wires. -## What it's for +## Overview **CGP's wiring is lazy, and this macro is the answer to that.** When [`delegate_components!`](./delegate_components.md) records that a **context** — the type the capability diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 5e4e1295..4c846719 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -6,7 +6,7 @@ sidebar_label: 'delegate_and_check_components!' Wire a context and check that wiring in one macro. -## What it's for +## Overview CGP's wiring is [lazy](./delegate_components.md#gotchas): a [`delegate_components!`](./delegate_components.md) entry is accepted without verifying that the provider it diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 3d2151d2..d04fab35 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -6,7 +6,7 @@ sidebar_label: 'delegate_components!' Build a context's wiring table, naming the provider that implements each of its components. -## What it's for +## Overview [`#[cgp_component]`](./cgp_component.md) separates the trait callers use from the trait implementations target, which leaves one question open: for a given type, *which* implementation diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 50bbcf8e..7b8379da 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -6,7 +6,7 @@ sidebar_label: 'Path!' A type-level path, used by namespaces and redirected lookups. -## What it's for +## Overview `Path!(@a.B.c)` builds a type-level **route** — a list of segments naming a way through nested wiring tables. Read left to right, each segment narrows a lookup one step: through a namespace, through a prefix, down to a diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index fbf3f8d4..c6082081 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -6,7 +6,7 @@ sidebar_label: 'Product! & product!' A type-level list and its value-level counterpart. -## What it's for +## Overview `Product![A, B, C]` represents an ordered sequence of types as a single type. CGP uses it to describe the *shape* of a struct — the list of its fields, in order, as one type that generic code can reason about. diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 70f70086..d60d3305 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -6,7 +6,7 @@ sidebar_label: 'Sum!' A type-level sum, the dual of `Product!`. -## What it's for +## Overview `Sum![A, B, C]` represents a *choice* among several types as a single type. CGP uses it to describe the shape of an **enum** — the list of its variants — the way [`Product!`](./product.md) describes the fields of a diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index eab9baa6..d1c31258 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -6,7 +6,7 @@ sidebar_label: 'Symbol!' A type-level string, used as a field-name tag. -## What it's for +## Overview CGP needs field *names* to be types. Reading a field goes through [`HasField`](../traits/has_field.md), where `Tag` identifies which field is meant — so to look up a field diff --git a/docs/reference/traits/append_product.md b/docs/reference/traits/append_product.md index 807ff64b..0eb79792 100644 --- a/docs/reference/traits/append_product.md +++ b/docs/reference/traits/append_product.md @@ -17,7 +17,7 @@ explains what it produces so that message is legible. The one case for naming it ::: -## What it's for +## Overview A struct's shape in CGP is a type-level list — a [`Product!`](../macros/product.md) of named fields. Code that processes such a shape generically sometimes needs to describe a *new* shape computed from an diff --git a/docs/reference/traits/build_field.md b/docs/reference/traits/build_field.md index 4f5f3f5a..b5769a05 100644 --- a/docs/reference/traits/build_field.md +++ b/docs/reference/traits/build_field.md @@ -6,7 +6,7 @@ sidebar_label: 'BuildField' Setting one currently-absent field of a builder. -## What it's for +## Overview `BuildField` is the direction of the [builder family](./has_builder.md) you write most: take a partial record with a field absent, supply the value, and get back a partial record with that field present. diff --git a/docs/reference/traits/can_build_from.md b/docs/reference/traits/can_build_from.md index ca03b67a..626969c3 100644 --- a/docs/reference/traits/can_build_from.md +++ b/docs/reference/traits/can_build_from.md @@ -6,7 +6,7 @@ sidebar_label: 'CanBuildFrom' Filling a builder with every field it shares with another record. -## What it's for +## Overview Assembling one struct out of several smaller ones means copying each shared field across by hand — a line per field, repeated for every pair of types. `CanBuildFrom` derives that copying from the field diff --git a/docs/reference/traits/can_build_with_default.md b/docs/reference/traits/can_build_with_default.md index 1edd987c..7eea1570 100644 --- a/docs/reference/traits/can_build_with_default.md +++ b/docs/reference/traits/can_build_with_default.md @@ -6,7 +6,7 @@ sidebar_label: 'CanBuildWithDefault' Widening one record into another in a single call. -## What it's for +## Overview Turning a narrow record into a wider one whose extra fields have sensible defaults is a three-step motion: start a builder, copy the shared fields, default the rest. `CanBuildWithDefault` is that motion as one diff --git a/docs/reference/traits/can_downcast.md b/docs/reference/traits/can_downcast.md index 10da5b24..568fe4db 100644 --- a/docs/reference/traits/can_downcast.md +++ b/docs/reference/traits/can_downcast.md @@ -6,7 +6,7 @@ sidebar_label: 'CanDowncast' Narrowing a wide enum into a smaller one, or handing back what is left. -## What it's for +## Overview Converting a wide enum into a narrower one is the direction that can fail: the value's current variant may be one the target does not have. `CanDowncast` attempts that conversion, and what makes it more than diff --git a/docs/reference/traits/can_downcast_fields.md b/docs/reference/traits/can_downcast_fields.md index ae7365fa..8f27f11c 100644 --- a/docs/reference/traits/can_downcast_fields.md +++ b/docs/reference/traits/can_downcast_fields.md @@ -6,7 +6,7 @@ sidebar_label: 'CanDowncastFields' Continuing a narrowing chain on a remainder. -## What it's for +## Overview [`CanDowncast`](./can_downcast.md) narrows an enum and, when it fails, hands back a *remainder* — the same value with the attempted variants ruled out in its type. `CanDowncastFields` is what that remainder diff --git a/docs/reference/traits/can_finalize_with_default.md b/docs/reference/traits/can_finalize_with_default.md index e3f488f9..53888e99 100644 --- a/docs/reference/traits/can_finalize_with_default.md +++ b/docs/reference/traits/can_finalize_with_default.md @@ -6,7 +6,7 @@ sidebar_label: 'CanFinalizeWithDefault' Finalizing a partial record, filling whatever is unset from `Default`. -## What it's for +## Overview The core [builder family](./has_builder.md) refuses to finalize an incomplete record, which is what catches a missing field at compile time. For a record where some fields have sensible defaults, that diff --git a/docs/reference/traits/can_upcast.md b/docs/reference/traits/can_upcast.md index b28c5570..c44fc040 100644 --- a/docs/reference/traits/can_upcast.md +++ b/docs/reference/traits/can_upcast.md @@ -6,7 +6,7 @@ sidebar_label: 'CanUpcast' Widening a narrow enum into a wider one that shares its variants. -## What it's for +## Overview Two enums defined independently can share variant names — a small `FooBar` and a larger `FooBarBaz`, say. Converting the narrow one into the wide one is a conversion you could write by hand, and it is diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/can_use_component.md index 2bb238e8..7f266541 100644 --- a/docs/reference/traits/can_use_component.md +++ b/docs/reference/traits/can_use_component.md @@ -18,7 +18,7 @@ failure is legible. ::: -## What it's for +## Overview CGP's wiring is lazy: writing a wiring line does not check that the chosen implementation's own requirements are met. That check happens the first time the capability is actually called, which is usually somewhere far diff --git a/docs/reference/traits/concat_path.md b/docs/reference/traits/concat_path.md index fcbecd91..e25c2136 100644 --- a/docs/reference/traits/concat_path.md +++ b/docs/reference/traits/concat_path.md @@ -18,7 +18,7 @@ expansion or an error message is legible. The one case for naming it is generic ::: -## What it's for +## Overview A [`Path!`](../macros/path.md) is a type-level list of segments — the route a namespaced component lookup is redirected along, or the chain of field names a nested getter descends. Composing two such diff --git a/docs/reference/traits/concat_product.md b/docs/reference/traits/concat_product.md index 6ad6ab96..47df9d51 100644 --- a/docs/reference/traits/concat_product.md +++ b/docs/reference/traits/concat_product.md @@ -17,7 +17,7 @@ produces. The one case for naming it is generic code that must describe the shap ::: -## What it's for +## Overview Merging two records means merging their shapes, and the shapes are type-level lists — a [`Product!`](../macros/product.md) of named fields each. `ConcatProduct` names the list you get by diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/contains_value.md index e074ef63..887ae8c8 100644 --- a/docs/reference/traits/contains_value.md +++ b/docs/reference/traits/contains_value.md @@ -17,7 +17,7 @@ page is here to explain how a step unwraps its input. ::: -## What it's for +## Overview A step in a [monadic pipeline](/docs/concepts/monadic-handlers) produces a wrapped output — a `Result`, say — and the next step needs the value *inside* the wrapper for the branch that continues. Which half of diff --git a/docs/reference/traits/default_impls1.md b/docs/reference/traits/default_impls1.md index d9f6a569..90a4c102 100644 --- a/docs/reference/traits/default_impls1.md +++ b/docs/reference/traits/default_impls1.md @@ -18,7 +18,7 @@ backwards. ::: -## What it's for +## Overview [`DefaultNamespace`](./default_namespace.md) keys a default on the component alone: one component, one default provider. `DefaultImpls1` adds a second type to the key, which is what a **per-type default** diff --git a/docs/reference/traits/default_impls2.md b/docs/reference/traits/default_impls2.md index 8940c45c..724944d8 100644 --- a/docs/reference/traits/default_impls2.md +++ b/docs/reference/traits/default_impls2.md @@ -17,7 +17,7 @@ page explains what they emit. ::: -## What it's for +## Overview [`DefaultImpls1`](./default_impls1.md) keys a namespace default on a component plus one type, which is what a per-type default needs. `DefaultImpls2` is the same idea under a **pair** of types: diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md index 3f343b35..3284f15f 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/default_namespace.md @@ -19,7 +19,7 @@ generates, including why a direct entry can shadow an inherited default without ::: -## What it's for +## Overview A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the type the capability runs against — can opt into and then selectively override. Resolving one of those diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/delegate_component.md index 378a2e20..dadccb5b 100644 --- a/docs/reference/traits/delegate_component.md +++ b/docs/reference/traits/delegate_component.md @@ -18,7 +18,7 @@ wiring error naming this trait is legible. ::: -## What it's for +## Overview Wiring a **context** — the type the capability runs against, which supplies the values it needs as its fields — means recording which implementation it uses for each capability. `DelegateComponent` is the trait diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md index 75004148..0aab3c3c 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/extract_field.md @@ -6,7 +6,7 @@ sidebar_label: 'ExtractField' Pulling one variant out of an extractor, or narrowing what remains. -## What it's for +## Overview A `match` on a concrete enum is checked for exhaustiveness. Code that is generic over the enum cannot write one, so it falls back on a wildcard arm and an `unreachable!()` — losing exactly the guarantee you diff --git a/docs/reference/traits/field_getter.md b/docs/reference/traits/field_getter.md index bc2d3bce..a712c005 100644 --- a/docs/reference/traits/field_getter.md +++ b/docs/reference/traits/field_getter.md @@ -17,7 +17,7 @@ wiring entry; this page explains the shape that entry resolves through. The one ::: -## What it's for +## Overview [`HasField`](./has_field.md) is a bound an implementation states about its own context. Sometimes field access should instead be **chosen by wiring**, so that a context decides which of its fields answers a diff --git a/docs/reference/traits/field_mapper.md b/docs/reference/traits/field_mapper.md index 96c71ad9..3d05a094 100644 --- a/docs/reference/traits/field_mapper.md +++ b/docs/reference/traits/field_mapper.md @@ -16,7 +16,7 @@ caller in practice. This page explains the mechanism a chained getter is built f ::: -## What it's for +## Overview [`MapField`](./map_field.md) reads through a field without forcing its type to be `'static`, by taking a higher-ranked closure instead of returning the intermediate borrow. `FieldMapper` is the same operation diff --git a/docs/reference/traits/finalize_build.md b/docs/reference/traits/finalize_build.md index 934a6737..4a7f76b4 100644 --- a/docs/reference/traits/finalize_build.md +++ b/docs/reference/traits/finalize_build.md @@ -6,7 +6,7 @@ sidebar_label: 'FinalizeBuild' Turning a fully-built partial record back into the concrete struct. -## What it's for +## Overview `FinalizeBuild` is where a build ends: diff --git a/docs/reference/traits/finalize_extract.md b/docs/reference/traits/finalize_extract.md index 4ecc8d17..90a52091 100644 --- a/docs/reference/traits/finalize_extract.md +++ b/docs/reference/traits/finalize_extract.md @@ -6,7 +6,7 @@ sidebar_label: 'FinalizeExtract' Discharging an extractor that has nothing left in it. -## What it's for +## Overview An [extraction chain](./extract_field.md) 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` is what turns diff --git a/docs/reference/traits/finalize_extract_result.md b/docs/reference/traits/finalize_extract_result.md index c001ad57..6399ee43 100644 --- a/docs/reference/traits/finalize_extract_result.md +++ b/docs/reference/traits/finalize_extract_result.md @@ -6,7 +6,7 @@ sidebar_label: 'FinalizeExtractResult' Collapsing the `Result` at the end of an extraction chain. -## What it's for +## Overview Every step of an [extraction chain](./extract_field.md) 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 diff --git a/docs/reference/traits/finalize_optional.md b/docs/reference/traits/finalize_optional.md index 5f95eed1..29fdc66c 100644 --- a/docs/reference/traits/finalize_optional.md +++ b/docs/reference/traits/finalize_optional.md @@ -6,7 +6,7 @@ sidebar_label: 'FinalizeOptional' Finalizing an optional builder, reporting the first missing field. -## What it's for +## Overview An [optional builder](./has_optional_builder.md) has given up the compile-time completeness check: every field is `IsOptional`, so the type no longer records what has been set. Something has to check at run diff --git a/docs/reference/traits/from_fields.md b/docs/reference/traits/from_fields.md index 2928de23..abc4f7bc 100644 --- a/docs/reference/traits/from_fields.md +++ b/docs/reference/traits/from_fields.md @@ -6,7 +6,7 @@ sidebar_label: 'FromFields' Rebuilding a concrete value from its shape. -## What it's for +## Overview [`ToFields`](./to_fields.md) takes a value apart into an anonymous list of named entries. `FromFields` is the return journey: diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md index da5ceb20..c14203e3 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/from_variant.md @@ -6,7 +6,7 @@ sidebar_label: 'FromVariant' Generic construction of an enum from a named variant. -## What it's for +## Overview `Shape::Circle(circle)` names two things: the enum and the variant. That is fine where both are known and useless to code that knows neither — a routine handed a payload and told which variant to wrap it in cannot diff --git a/docs/reference/traits/has_builder.md b/docs/reference/traits/has_builder.md index 4f27d439..82e0ca38 100644 --- a/docs/reference/traits/has_builder.md +++ b/docs/reference/traits/has_builder.md @@ -6,7 +6,7 @@ sidebar_label: 'HasBuilder' Starting an empty builder for a record. -## What it's for +## Overview A struct literal supplies every field at once, in one place that names the type. `HasBuilder` is the entry point for the case where that is impossible: the fields come from several independent places, none diff --git a/docs/reference/traits/has_extractor.md b/docs/reference/traits/has_extractor.md index 15d0dc7d..60f29d36 100644 --- a/docs/reference/traits/has_extractor.md +++ b/docs/reference/traits/has_extractor.md @@ -6,7 +6,7 @@ sidebar_label: 'HasExtractor' Turning an enum into an extractor, and back. -## What it's for +## Overview [`ExtractField`](./extract_field.md) narrows an *extractor*, not an enum. `HasExtractor` is where one comes from: diff --git a/docs/reference/traits/has_extractor_mut.md b/docs/reference/traits/has_extractor_mut.md index 24dd6d46..96716bda 100644 --- a/docs/reference/traits/has_extractor_mut.md +++ b/docs/reference/traits/has_extractor_mut.md @@ -6,7 +6,7 @@ sidebar_label: 'HasExtractorMut' Obtaining an extractor that can change a payload in place. -## What it's for +## Overview [`HasExtractorRef`](./has_extractor_ref.md) borrows an enum so its variants can be read without consuming it. `HasExtractorMut` borrows it mutably, so a payload can be **changed in place**: diff --git a/docs/reference/traits/has_extractor_ref.md b/docs/reference/traits/has_extractor_ref.md index 36039f2e..ea4ae16e 100644 --- a/docs/reference/traits/has_extractor_ref.md +++ b/docs/reference/traits/has_extractor_ref.md @@ -6,7 +6,7 @@ sidebar_label: 'HasExtractorRef' Obtaining an extractor that borrows the value rather than consuming it. -## What it's for +## Overview [`HasExtractor`](./has_extractor.md) consumes an enum to produce an extractor with owned payloads. Code that only *reads* a variant — checking it, measuring it, rendering it — should not have to give up the diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/has_field.md index 2cb14a69..5193707e 100644 --- a/docs/reference/traits/has_field.md +++ b/docs/reference/traits/has_field.md @@ -6,7 +6,7 @@ sidebar_label: 'HasField' Reading a field by a type-level name, from a context you cannot name. -## What it's for +## Overview An implementation written against a **context** — the type the capability runs against, which supplies the values it needs as its fields — is generic over that context and cannot name its concrete type. So it diff --git a/docs/reference/traits/has_field_mut.md b/docs/reference/traits/has_field_mut.md index 2f3f35f0..e652ed80 100644 --- a/docs/reference/traits/has_field_mut.md +++ b/docs/reference/traits/has_field_mut.md @@ -6,7 +6,7 @@ sidebar_label: 'HasFieldMut' Mutable tag-keyed field access. -## What it's for +## Overview [`HasField`](./has_field.md) lets an implementation read a field of a context it cannot name, by keying on the field's name as a type. `HasFieldMut` is the same access with mutation: it hands back a `&mut` diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/has_fields.md index 2fc0f77b..f5638d78 100644 --- a/docs/reference/traits/has_fields.md +++ b/docs/reference/traits/has_fields.md @@ -6,7 +6,7 @@ sidebar_label: 'HasFields' A type's whole shape, as a single type. -## What it's for +## Overview Some code needs one field of a type. Other code needs the *shape* — every field, its name, and its type — so it can walk them: a serializer, a validator, a builder that merges two structs, a dispatcher that diff --git a/docs/reference/traits/has_fields_ref.md b/docs/reference/traits/has_fields_ref.md index 5df16c65..501f7cd0 100644 --- a/docs/reference/traits/has_fields_ref.md +++ b/docs/reference/traits/has_fields_ref.md @@ -17,7 +17,7 @@ lifetime name that shows up in an error message. ::: -## What it's for +## Overview [`HasFields`](./has_fields.md) describes a type as a list of named entries holding owned values. Code that only *reads* a value should not have to consume it to walk its shape — a validator, a serializer, a diff --git a/docs/reference/traits/has_optional_builder.md b/docs/reference/traits/has_optional_builder.md index 68707922..d6709ff2 100644 --- a/docs/reference/traits/has_optional_builder.md +++ b/docs/reference/traits/has_optional_builder.md @@ -6,7 +6,7 @@ sidebar_label: 'HasOptionalBuilder' Starting a builder in which every field is already optional. -## What it's for +## Overview The core [builder family](./has_builder.md) is deliberately strict: a field is set exactly once, and a partial record becomes its concrete struct only when **every** field is present. That strictness is what diff --git a/docs/reference/traits/into_builder.md b/docs/reference/traits/into_builder.md index 25ee5b53..1a8576d8 100644 --- a/docs/reference/traits/into_builder.md +++ b/docs/reference/traits/into_builder.md @@ -6,7 +6,7 @@ sidebar_label: 'IntoBuilder' Turning a complete record into a partial one, with every field present. -## What it's for +## Overview [`HasBuilder`](./has_builder.md) starts from nothing: a partial value with every field absent, to be filled. `IntoBuilder` starts from the other end: diff --git a/docs/reference/traits/is_provider_for.md b/docs/reference/traits/is_provider_for.md index 015d4af1..15a60c5c 100644 --- a/docs/reference/traits/is_provider_for.md +++ b/docs/reference/traits/is_provider_for.md @@ -17,7 +17,7 @@ names, and reading that error is the reason to know it exists. ::: -## What it's for +## Overview An implementation in CGP states what it needs from its **context** — the type the capability runs against — in its own `where` clause: a field, an abstract type, another capability. When one of those requirements is diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/lift_value.md index f688f703..2c4c1aab 100644 --- a/docs/reference/traits/lift_value.md +++ b/docs/reference/traits/lift_value.md @@ -18,7 +18,7 @@ one. ::: -## What it's for +## Overview A bind step in a [monadic pipeline](/docs/concepts/monadic-handlers) unwraps a value, runs a continuation or short-circuits, and then has to produce the step's own output. Producing it means diff --git a/docs/reference/traits/map_field.md b/docs/reference/traits/map_field.md index a2d8e9c2..5d030d81 100644 --- a/docs/reference/traits/map_field.md +++ b/docs/reference/traits/map_field.md @@ -17,7 +17,7 @@ which is why reaching a nested field is a provider rather than two chained reads ::: -## What it's for +## Overview Chaining field reads looks like it should just work — read a field, then read a field of *that* — and it does not, for a reason that is about lifetimes rather than about CGP. Writing diff --git a/docs/reference/traits/map_fields.md b/docs/reference/traits/map_fields.md index 9e6caae6..359ee370 100644 --- a/docs/reference/traits/map_fields.md +++ b/docs/reference/traits/map_fields.md @@ -18,7 +18,7 @@ beside it. The one case for naming it is generic code that must describe a unifo ::: -## What it's for +## Overview A partial record is the same record with every field's storage changed the same way — each value wrapped in an `Option`, or replaced by `()`, or left alone. Describing that as a type means rewriting every entry diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index c7b19ce3..801a866a 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -18,7 +18,7 @@ what each one means. The one case for bounding on the trait is generic code of y ::: -## What it's for +## Overview 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 diff --git a/docs/reference/traits/map_type_ref.md b/docs/reference/traits/map_type_ref.md index 50b0d668..f576ddb3 100644 --- a/docs/reference/traits/map_type_ref.md +++ b/docs/reference/traits/map_type_ref.md @@ -17,7 +17,7 @@ explains what each one means and how it composes with the per-field markers. The ::: -## What it's for +## Overview [`MapType`](./map_type.md) decides whether a field of a partial type holds its value, nothing, or an uninhabited type. A **borrowed** partial type needs a second decision on top: whether each payload is diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monadic_bind.md index 91ea4705..8f09fec8 100644 --- a/docs/reference/traits/monadic_bind.md +++ b/docs/reference/traits/monadic_bind.md @@ -17,7 +17,7 @@ otherwise this page is here to explain how a pipeline is assembled. ::: -## What it's for +## Overview A [monadic pipeline](/docs/concepts/monadic-handlers) chains steps where each may either continue or short-circuit — the familiar `?`-style behaviour, expressed as composable providers rather than as diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monadic_trans.md index 7ebb04cc..d870cade 100644 --- a/docs/reference/traits/monadic_trans.md +++ b/docs/reference/traits/monadic_trans.md @@ -17,7 +17,7 @@ a monad of your own a transformer form; otherwise this page is here to explain h ::: -## What it's for +## Overview A [monadic pipeline](/docs/concepts/monadic-handlers) over a nested output — a `Result` inside a `Result` — needs to peel more than one layer, and hard-coding a depth would give up the composability diff --git a/docs/reference/traits/mut_field_getter.md b/docs/reference/traits/mut_field_getter.md index 81f3dfb4..2381ffb6 100644 --- a/docs/reference/traits/mut_field_getter.md +++ b/docs/reference/traits/mut_field_getter.md @@ -17,7 +17,7 @@ explains what the mutable half of that entry provides. The one case for implemen ::: -## What it's for +## Overview [`FieldGetter`](./field_getter.md) is field access in provider-trait shape, so that a context can choose by wiring which field answers a getter. `MutFieldGetter` is the same thing with mutation: it hands back a diff --git a/docs/reference/traits/partial_data.md b/docs/reference/traits/partial_data.md index d55f0739..6f6dcbe6 100644 --- a/docs/reference/traits/partial_data.md +++ b/docs/reference/traits/partial_data.md @@ -18,7 +18,7 @@ where that projection comes from. The one case for bounding on it is generic cod ::: -## What it's for +## Overview A partial record is a companion type — `__PartialPerson` — and generic code holding one often needs to know what it will *become* before it is complete: to name the return type of a diff --git a/docs/reference/traits/set_optional.md b/docs/reference/traits/set_optional.md index df48b7ec..2ee513ba 100644 --- a/docs/reference/traits/set_optional.md +++ b/docs/reference/traits/set_optional.md @@ -6,7 +6,7 @@ sidebar_label: 'SetOptional' Setting one field of an optional builder, as many times as you like. -## What it's for +## Overview [`BuildField`](./build_field.md) sets an absent field and consumes the slot: the builder's type changes, and setting the same field twice is a compile error. `SetOptional` is the optional layer's answer, and its diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md index 99b28421..0a312b43 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/static_format.md @@ -17,7 +17,7 @@ and the narrow case where bounding on it is the answer. ::: -## What it's for +## Overview CGP encodes field and variant names as *types*, so a name can drive trait resolution. Printing one means turning that type back into characters, and `StaticFormat` is the trait that does it **lazily**, by diff --git a/docs/reference/traits/static_string.md b/docs/reference/traits/static_string.md index 5cfafd08..0d7bba76 100644 --- a/docs/reference/traits/static_string.md +++ b/docs/reference/traits/static_string.md @@ -6,7 +6,7 @@ sidebar_label: 'StaticString' Recovering a type-level string as a compile-time `&'static str`. -## What it's for +## Overview CGP encodes field and variant names as *types* — a [`Symbol!`](../macros/symbol.md) is a length plus a character list, one node per character — so that names can drive trait resolution. But a program diff --git a/docs/reference/traits/take_field.md b/docs/reference/traits/take_field.md index 48646c43..a5323bf4 100644 --- a/docs/reference/traits/take_field.md +++ b/docs/reference/traits/take_field.md @@ -6,7 +6,7 @@ sidebar_label: 'TakeField' Removing one currently-present field from a builder. -## What it's for +## Overview `TakeField` is the reverse of [`BuildField`](./build_field.md): it removes a field that is currently set, handing back the value and the partial record without it. diff --git a/docs/reference/traits/to_fields.md b/docs/reference/traits/to_fields.md index 20b7ea98..106ca716 100644 --- a/docs/reference/traits/to_fields.md +++ b/docs/reference/traits/to_fields.md @@ -6,7 +6,7 @@ sidebar_label: 'ToFields' Taking a value apart into its shape. -## What it's for +## Overview [`HasFields`](./has_fields.md) *names* a type's shape. `ToFields` produces a value in it: diff --git a/docs/reference/traits/to_fields_ref.md b/docs/reference/traits/to_fields_ref.md index a7fba8fa..f705bf0c 100644 --- a/docs/reference/traits/to_fields_ref.md +++ b/docs/reference/traits/to_fields_ref.md @@ -6,7 +6,7 @@ sidebar_label: 'ToFieldsRef' Walking a value's shape without consuming it. -## What it's for +## Overview [`ToFields`](./to_fields.md) takes a value apart into its shape and consumes it in the process. Code that only reads — a validator, a serializer, a routine that inspects a struct and hands it back — should not diff --git a/docs/reference/traits/to_optional.md b/docs/reference/traits/to_optional.md index a7cad73e..b32b5fd3 100644 --- a/docs/reference/traits/to_optional.md +++ b/docs/reference/traits/to_optional.md @@ -6,7 +6,7 @@ sidebar_label: 'ToOptional' Re-marking every field of an existing builder as optional. -## What it's for +## Overview [`HasOptionalBuilder`](./has_optional_builder.md) starts an all-optional builder from nothing. `ToOptional` is the conversion for the case where you already hold a partial value and want to relax it: diff --git a/docs/reference/traits/transform_map.md b/docs/reference/traits/transform_map.md index 3c152ac3..eeb7ee83 100644 --- a/docs/reference/traits/transform_map.md +++ b/docs/reference/traits/transform_map.md @@ -6,7 +6,7 @@ sidebar_label: 'TransformMap' The per-field function that converts a value from one marker's storage to another's. -## What it's for +## Overview [`MapType`](./map_type.md) only names storage *types*: it says that an `IsNothing` field holds `()` and an `IsPresent` field holds its value, and nothing about how you get from one to the other. diff --git a/docs/reference/traits/transform_map_default.md b/docs/reference/traits/transform_map_default.md index 2427985e..1c0f7931 100644 --- a/docs/reference/traits/transform_map_default.md +++ b/docs/reference/traits/transform_map_default.md @@ -18,7 +18,7 @@ transform of your own. ::: -## What it's for +## Overview [`CanFinalizeWithDefault`](./can_finalize_with_default.md) works by re-marking every field of a partial record to `IsPresent` and then calling the ordinary [`finalize_build`](./finalize_build.md). diff --git a/docs/reference/traits/transform_map_fields.md b/docs/reference/traits/transform_map_fields.md index ce32df17..12d74de0 100644 --- a/docs/reference/traits/transform_map_fields.md +++ b/docs/reference/traits/transform_map_fields.md @@ -17,7 +17,7 @@ you call. This page explains the walk, which is what makes those two behave so s ::: -## What it's for +## Overview [`TransformMap`](./transform_map.md) converts *one* field from one marker's storage to another's. `TransformMapFields` lifts that conversion across an entire partial record, so every field is re-marked diff --git a/docs/reference/traits/transform_optional.md b/docs/reference/traits/transform_optional.md index 4c4c6e0e..f019c4c7 100644 --- a/docs/reference/traits/transform_optional.md +++ b/docs/reference/traits/transform_optional.md @@ -17,7 +17,7 @@ less of a field's type than its defaulting counterpart does. The one case for na ::: -## What it's for +## Overview [`ToOptional`](./to_optional.md) re-marks every field of a partial record to `IsOptional`, so it can then be set freely and finalized either way. `TransformOptional` is the marker carrying the per-field diff --git a/docs/reference/traits/update_field.md b/docs/reference/traits/update_field.md index 68bcea1c..66bbf896 100644 --- a/docs/reference/traits/update_field.md +++ b/docs/reference/traits/update_field.md @@ -18,7 +18,7 @@ optional-field layer reaches for when neither direction fits. ::: -## What it's for +## Overview Everything in the [builder family](./has_builder.md) reduces to one operation: change one field's storage from one [`MapType`](./map_type.md) marker to another, and hand back what was there before. diff --git a/example-code/src/reference/derives/derive_build_field.rs b/example-code/src/reference/derives/derive_build_field.rs index 1fff72ec..cc894291 100644 --- a/example-code/src/reference/derives/derive_build_field.rs +++ b/example-code/src/reference/derives/derive_build_field.rs @@ -5,7 +5,7 @@ //! `cargo cgp expand` is the check on that section. What this file pins is that each of the page's //! snippets runs, and that the incomplete build it says will not compile does not. -/// ## What it's for +/// ## Overview /// /// The opening builder chain. The page shows it against `Person`, which it declares under *Using it*. pub mod what_its_for { diff --git a/example-code/src/reference/derives/derive_extract_field.rs b/example-code/src/reference/derives/derive_extract_field.rs index 4fd4ccfd..dafe6410 100644 --- a/example-code/src/reference/derives/derive_extract_field.rs +++ b/example-code/src/reference/derives/derive_extract_field.rs @@ -5,7 +5,7 @@ //! `cargo cgp expand` is the check on that section. What this file pins is the accepted and rejected //! shapes, the three extractors, and the exhaustiveness claim in both directions. -/// ## What it's for +/// ## Overview /// /// The opening extraction, and the payload types the page names without declaring. pub mod what_its_for { diff --git a/example-code/src/reference/derives/derive_from_variant.rs b/example-code/src/reference/derives/derive_from_variant.rs index 62100666..34e56011 100644 --- a/example-code/src/reference/derives/derive_from_variant.rs +++ b/example-code/src/reference/derives/derive_from_variant.rs @@ -5,7 +5,7 @@ //! check on that section. What this file pins is that the tag-generic constructor works, and the two //! shapes the page says are rejected. -/// ## What it's for +/// ## Overview /// /// The opening claim: `from_variant` with a tag is the same construction as naming the variant. pub mod what_its_for { diff --git a/example-code/src/reference/derives/derive_has_field.rs b/example-code/src/reference/derives/derive_has_field.rs index 23809e6f..6f142b06 100644 --- a/example-code/src/reference/derives/derive_has_field.rs +++ b/example-code/src/reference/derives/derive_has_field.rs @@ -5,7 +5,7 @@ //! only honest check on that section is `cargo cgp expand`. What this file pins is every input shape //! the page says is accepted, and that the generated access actually resolves. -/// ## What it's for +/// ## Overview /// /// The page opens on the bound an implementation writes. The component and the context are shown /// further down under *Examples*; they are declared here so the opening bound has something to hold. diff --git a/example-code/src/reference/derives/derive_has_fields.rs b/example-code/src/reference/derives/derive_has_fields.rs index 462286c9..46be6287 100644 --- a/example-code/src/reference/derives/derive_has_fields.rs +++ b/example-code/src/reference/derives/derive_has_fields.rs @@ -5,7 +5,7 @@ //! `cargo cgp expand` is the check on that section. What this file pins is the `Fields` type the page //! claims for each input shape, asserted by round-tripping a value through it. -/// ## What it's for +/// ## Overview /// /// The `Fields` type the page opens on, checked by naming it explicitly. pub mod what_its_for { diff --git a/example-code/src/reference/macros/delegate_components.rs b/example-code/src/reference/macros/delegate_components.rs index d3504d8f..f89a1031 100644 --- a/example-code/src/reference/macros/delegate_components.rs +++ b/example-code/src/reference/macros/delegate_components.rs @@ -1,6 +1,6 @@ //! Code from `docs/reference/macros/delegate_components.md` — *`delegate_components!`*. -/// ## What it's for +/// ## Overview /// /// The page opens on the single-entry table. The component, the provider, and the context it wires /// are shown further down the page under *Examples*; they are declared here so the opening snippet From 1defff259008633c2a444ef0fff62b51a4b254e5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 22 Aug 2026 15:20:47 +0200 Subject: [PATCH 034/516] Rename Using it to Usage, and revise macro reference pages Rename the "Using it" heading to "Usage" across all reference pages and their example-code doc comments, matching the knowledge base's updated writing guide, and fix the few cross-page anchor links this touches. Review and revise the macro reference pages beyond #[cgp_component]: cgp_impl, cgp_provider, cgp_fn, cgp_getter, cgp_auto_getter, delegate_components, check_components, delegate_and_check_components, cgp_computer, cgp_producer, cgp_auto_dispatch, symbol, product, sum, path, async_trait, and blanket_trait. Each gets the same treatment as cgp_component: remove pseudo-cleft sentences and crutch em dashes, and tighten prose per the base's writing-styles guide. Also correct a real inaccuracy in cgp_impl and cgp_provider: a provider struct that new can't declare, or one shared by several #[cgp_impl] blocks, is not by itself a reason to drop to the raw #[cgp_provider] form. Add a dedicated "Declaring the provider struct separately" section to cgp_impl covering both cases (write new once and omit it after, or declare the struct by hand up front). cgp_type and cgp_namespace are mid-revision and left as-is for a follow-up pass. Co-Authored-By: Claude Sonnet 5 --- docs/reference/attributes/default_impl.md | 2 +- docs/reference/attributes/derive_delegate.md | 2 +- docs/reference/attributes/extend.md | 2 +- docs/reference/attributes/extend_where.md | 2 +- docs/reference/attributes/implicit.md | 2 +- docs/reference/attributes/use_provider.md | 2 +- docs/reference/attributes/use_type.md | 2 +- docs/reference/attributes/uses.md | 2 +- docs/reference/derives/derive_build_field.md | 2 +- docs/reference/derives/derive_cgp_data.md | 2 +- docs/reference/derives/derive_cgp_record.md | 2 +- docs/reference/derives/derive_cgp_variant.md | 2 +- .../reference/derives/derive_extract_field.md | 2 +- docs/reference/derives/derive_from_variant.md | 2 +- docs/reference/derives/derive_has_field.md | 2 +- docs/reference/derives/derive_has_fields.md | 2 +- docs/reference/macros/async_trait.md | 32 ++-- docs/reference/macros/blanket_trait.md | 40 ++--- docs/reference/macros/cgp_auto_dispatch.md | 34 ++-- docs/reference/macros/cgp_auto_getter.md | 46 ++--- docs/reference/macros/cgp_component.md | 2 +- docs/reference/macros/cgp_computer.md | 40 ++--- docs/reference/macros/cgp_fn.md | 102 ++++++------ docs/reference/macros/cgp_getter.md | 50 +++--- docs/reference/macros/cgp_impl.md | 157 ++++++++++++------ docs/reference/macros/cgp_namespace.md | 2 +- docs/reference/macros/cgp_producer.md | 32 ++-- docs/reference/macros/cgp_provider.md | 148 ++++++++--------- docs/reference/macros/cgp_type.md | 18 +- docs/reference/macros/check_components.md | 68 ++++---- .../macros/delegate_and_check_components.md | 46 ++--- docs/reference/macros/delegate_components.md | 94 +++++------ docs/reference/macros/path.md | 50 +++--- docs/reference/macros/product.md | 38 ++--- docs/reference/macros/sum.md | 26 +-- docs/reference/macros/symbol.md | 38 ++--- docs/reference/traits/append_product.md | 2 +- docs/reference/traits/build_field.md | 2 +- docs/reference/traits/can_build_from.md | 2 +- .../traits/can_build_with_default.md | 2 +- docs/reference/traits/can_downcast.md | 2 +- docs/reference/traits/can_downcast_fields.md | 2 +- .../traits/can_finalize_with_default.md | 2 +- docs/reference/traits/can_upcast.md | 2 +- docs/reference/traits/can_use_component.md | 2 +- docs/reference/traits/concat_path.md | 2 +- docs/reference/traits/concat_product.md | 2 +- docs/reference/traits/contains_value.md | 2 +- docs/reference/traits/default_impls1.md | 2 +- docs/reference/traits/default_impls2.md | 4 +- docs/reference/traits/default_namespace.md | 2 +- docs/reference/traits/delegate_component.md | 2 +- docs/reference/traits/extract_field.md | 2 +- docs/reference/traits/field_getter.md | 2 +- docs/reference/traits/field_mapper.md | 2 +- docs/reference/traits/finalize_build.md | 2 +- docs/reference/traits/finalize_extract.md | 2 +- .../traits/finalize_extract_result.md | 2 +- docs/reference/traits/finalize_optional.md | 2 +- docs/reference/traits/from_fields.md | 2 +- docs/reference/traits/from_variant.md | 2 +- docs/reference/traits/has_builder.md | 2 +- docs/reference/traits/has_extractor.md | 2 +- docs/reference/traits/has_extractor_mut.md | 2 +- docs/reference/traits/has_extractor_ref.md | 2 +- docs/reference/traits/has_field.md | 2 +- docs/reference/traits/has_field_mut.md | 2 +- docs/reference/traits/has_fields.md | 2 +- docs/reference/traits/has_fields_ref.md | 2 +- docs/reference/traits/has_optional_builder.md | 2 +- docs/reference/traits/into_builder.md | 2 +- docs/reference/traits/is_provider_for.md | 2 +- docs/reference/traits/lift_value.md | 2 +- docs/reference/traits/map_field.md | 2 +- docs/reference/traits/map_fields.md | 2 +- docs/reference/traits/map_type.md | 2 +- docs/reference/traits/map_type_ref.md | 2 +- docs/reference/traits/monadic_bind.md | 2 +- docs/reference/traits/monadic_trans.md | 2 +- docs/reference/traits/mut_field_getter.md | 2 +- docs/reference/traits/partial_data.md | 2 +- docs/reference/traits/set_optional.md | 2 +- docs/reference/traits/static_format.md | 2 +- docs/reference/traits/static_string.md | 2 +- docs/reference/traits/take_field.md | 2 +- docs/reference/traits/to_fields.md | 2 +- docs/reference/traits/to_fields_ref.md | 2 +- docs/reference/traits/to_optional.md | 2 +- docs/reference/traits/transform_map.md | 2 +- .../reference/traits/transform_map_default.md | 2 +- docs/reference/traits/transform_map_fields.md | 2 +- docs/reference/traits/transform_optional.md | 2 +- docs/reference/traits/update_field.md | 2 +- .../reference/derives/derive_build_field.rs | 2 +- .../src/reference/derives/derive_cgp_data.rs | 2 +- .../reference/derives/derive_cgp_variant.rs | 2 +- .../reference/derives/derive_extract_field.rs | 2 +- .../reference/derives/derive_from_variant.rs | 2 +- .../src/reference/derives/derive_has_field.rs | 2 +- .../reference/derives/derive_has_fields.rs | 2 +- 100 files changed, 645 insertions(+), 580 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 44eb3bc6..8de00425 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -25,7 +25,7 @@ table.* A context that pulls that table in gets this provider without naming it. The value of registering at the definition is that the provider and its default sit together, so adding a new per-type implementation is one place to edit rather than two. -## Using it +## Usage The attribute goes on a [`#[cgp_impl]`](../macros/cgp_impl.md) provider and takes one argument in two parts, joined by the keyword `in`: diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 7077f048..e1cf64a5 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -51,7 +51,7 @@ The reason the `open` statement replaced this is that the indirection turned out per-type entries live on the context itself, there is no second table type to name, and the component needs no attribute at all. -## Using it +## Usage `#[derive_delegate]` takes a wrapper type parameterized by the trait generic to dispatch on: diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 5bd52dcc..8bf46ea7 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -31,7 +31,7 @@ On [`#[cgp_fn]`](../macros/cgp_fn.md) the attribute is not merely preferred but written on a `#[cgp_fn]` is treated as an implementation detail and never reaches the generated trait, so there is no way to spell a supertrait by hand — `#[extend]` is the only mechanism for one. -## Using it +## Usage `#[extend(...)]` takes a comma-separated list of trait bounds, each becoming a supertrait of the generated trait: diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index e6f6e97d..4e07bebb 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -35,7 +35,7 @@ a bound on `Self`, which callers do receive by elaboration. `#[extend_where]` ad can bound anything, most usefully one of the trait's own generic parameters, which a supertrait cannot reach. -## Using it +## Usage `#[extend_where(...)]` takes a comma-separated list of full `where`-clause predicates: diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index da3b4eee..24790813 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -31,7 +31,7 @@ That is why it is the recommended way to read a context's own field, and why it piece of CGP anyone writes. Nothing about it is unfamiliar: a reader who understands functions and arguments can write a working capability and meet the machinery later, when they have a reason to care. -## Using it +## Usage `#[implicit]` is a bare marker on a typed parameter. It takes no arguments in any form, and a list or name-value spelling is rejected rather than ignored: diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 754cca82..266a8a38 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -35,7 +35,7 @@ and it does not touch the body.** The inner implementation is still invoked as a the context passed explicitly — `InnerCalculator::area(self)` — because that is what the provider trait's method actually takes. The attribute removes the surprise from the bound; the call site keeps it. -## Using it +## Usage `#[use_provider(...)]` takes a provider, a colon, and the trait bounds it must satisfy: diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 5c09ac9f..3ca1e4be 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -35,7 +35,7 @@ terms of another, a type can be pulled from a parameter rather than from `Self`, be constrained to be the same — none of which you can express by writing a bare identifier and hoping. Those are the [advanced forms](#importing-from-another-type) below. -## Using it +## Usage Apply `#[use_type]` beside the macro it modifies, naming a trait and the associated type to import: diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 1f80f30f..1e0e575a 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -37,7 +37,7 @@ One property of that bound is worth naming, because it is the whole point of put the implementation. It lands on the implementation *only*, never on the trait, so a caller who bounds on the capability never sees it and never has to repeat it. What an implementation needs is its own business. -## Using it +## Usage `#[uses(...)]` takes a comma-separated list of bounds, each becoming a `Self:` predicate on the generated implementation: diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 371888a7..b6150740 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -33,7 +33,7 @@ The other half of the payoff is that steps are decoupled. Because each `build_fi type-level tag rather than by calling a method on the concrete type, generic code can fill in a field of a struct it does not know, and two independent implementations can each contribute part of one value. -## Using it +## Usage The macro is a plain derive on a struct. It takes no arguments and has no helper attributes: diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index a0175b31..3a2c4e85 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -24,7 +24,7 @@ type that tracks, in its own type parameters, which fields are present or which possible — so a half-built value and a finished one are *different types*, and using one where the other belongs is a compile error rather than a runtime panic. -## Using it +## Usage The derive takes no arguments and has no helper attributes, and it accepts either shape: diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index cf359783..6c798f12 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -22,7 +22,7 @@ and emit the same output on a struct; the difference is that this one **rejects time**, so a type that is meant to stay a struct says so and the error arrives at the derive rather than further along. -## Using it +## Usage The derive takes no arguments and has no helper attributes: diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 3b557ac6..650a0ec0 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -20,7 +20,7 @@ incremental extractor that peels variants off one at a time while tracking which It is the enum-only face of [`#[derive(CgpData)]`](./derive_cgp_data.md). The two run the same code and emit the same output on an enum; the difference is that this one **rejects a struct at parse time**. -## Using it +## Usage The derive takes no arguments and has no helper attributes: diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index c950ddb4..7730773c 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -34,7 +34,7 @@ fields are present rather than which variants are possible. Both are what "exten [extensible data](/docs/concepts/extensible-variants): the type carries the progress, so the compiler checks it. -## Using it +## Usage The macro is a plain derive on an enum. It takes no arguments and has no helper attributes: diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 14948ca9..c30a5729 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -26,7 +26,7 @@ parameter, so one function can build whichever variant it was asked for, of whic tracking, and no traits of its own — just a constructor per variant. It is the counterpart to [`#[derive(ExtractField)]`](./derive_extract_field.md), which takes a variant out; this one puts a variant in. -## Using it +## Usage The macro is a plain derive on an enum. It takes no arguments and has no helper attributes: diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 6cedfb80..be0a6cd7 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -31,7 +31,7 @@ ergonomic surface stands on: an [`#[implicit]`](../attributes/implicit.md) argum wiring entry all generate the bound above from a name you already wrote. What you write is the derive on the struct. -## Using it +## Usage The macro is a plain derive on a struct. It takes no arguments and has no helper attributes: diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 2fd83c5d..cb929dc4 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -33,7 +33,7 @@ The derive also generates the conversions that move values in and out of the rep makes it a two-way door rather than a description. Generic code can take a concrete value apart into its anonymous shape, work on it, and put a concrete value back together. -## Using it +## Usage The macro is a plain derive that takes no arguments and has no helper attributes. Unlike its singular sibling it accepts **both structs and enums**: diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 0827402e..ddcc8a1d 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -10,7 +10,7 @@ Rewrite a trait's `async fn` declarations into the lint-clean `-> impl Future` f Writing a bare `async fn` inside a trait compiles on stable Rust, and the compiler warns about it. The `async_fn_in_trait` lint fires because the future such a method returns is *opaque*: a caller working through -the trait cannot name it, so they cannot require anything of it — most importantly that it is `Send`. The +the trait cannot name it, so they cannot require anything of it, most importantly that it is `Send`. The hand-written way to silence the lint is to declare the method as a future-returning function instead, which is correct and obscures the intent: @@ -32,15 +32,15 @@ The trait reads as async code, and the declaration the compiler sees is the lint **The rewrite is a plain desugaring, not a framework.** Unlike the widely-used `async-trait` crate, nothing here boxes the future or allocates: it is return-position `impl Trait` in traits, so the future is exactly the one the body produces and the call costs what a hand-written future-returning method costs. That is why the -macro is used throughout CGP wherever a capability is asynchronous — it is simply how an async method is +macro is used throughout CGP wherever a capability is asynchronous: it is simply how an async method is spelled. One thing it does *not* do is add a `Send` bound, and that omission has consequences the moment a future is spawned. It is covered under [Gotchas](#gotchas). -## Using it +## Usage -Apply the attribute to a trait definition. It takes no arguments — tokens in the argument position are +Apply the attribute to a trait definition. It takes no arguments. Tokens in the argument position are ignored, so it is always written bare: ```rust @@ -125,9 +125,9 @@ delegate_components! { } ``` -Notice the provider needs no `#[async_trait]` of its own. An `async fn` is already legal in an impl block — -only a trait *declaration* trips the lint — so the provider keeps the natural body while the trait carries the -rewritten signature, and the two agree because an `async fn` desugars to exactly such a future-returning +Notice the provider needs no `#[async_trait]` of its own. An `async fn` is already legal in an impl block, +since only a trait *declaration* trips the lint, so the provider keeps the natural body while the trait carries +the rewritten signature, and the two agree because an `async fn` desugars to exactly such a future-returning method. ## When to reach for it, and when not @@ -144,9 +144,9 @@ The decisions worth making are around it rather than about it. can add the bound, for the reason in the [Gotchas](#gotchas). - **Consider whether the capability needs to be async at all.** The [handler family](./cgp_computer.md) has synchronous members, and the [promotion combinators](../providers/handler_combinators.md) lift a synchronous - provider into an async one where a caller needs it — so a computation that does no I/O is better declared + provider into an async one where a caller needs it. So a computation that does no I/O is better declared synchronous and promoted than declared async out of habit. -- **Reach for the `async-trait` crate instead only if you need `dyn` compatibility.** Boxing is what makes an +- **Reach for the `async-trait` crate instead only if you need `dyn` compatibility.** Boxing makes an async trait object-safe, and this macro deliberately does not box. CGP resolves providers statically, so it does not need `dyn`; a codebase that does for other reasons is outside what this macro is for. @@ -188,13 +188,13 @@ pub trait CanFetch { ``` Three things to read off it. The `Output` is the original return type verbatim. The bodiless `run` picked up -`Output = ()`. And `sync_method` was left completely alone, which is what lets a trait mix async and +`Output = ()`. And `sync_method` was left completely alone, which lets a trait mix async and synchronous methods. -**The macro rewrites only trait definitions.** Applied to anything else — most importantly an `impl` block — -it returns the tokens unchanged. That passthrough is what makes the composition work: an `async fn` is legal in +**The macro rewrites only trait definitions.** Applied to anything else, most importantly an `impl` block, +it returns the tokens unchanged. This passthrough makes the composition work: an `async fn` is legal in an impl already, so the provider's body stays as written while the trait's declaration carries the future -type, and the `async fn` satisfies it because that is precisely what an `async fn` desugars to. +type, and the `async fn` satisfies it because an `async fn` desugars to precisely that. The composition with [`#[cgp_fn]`](./cgp_fn.md) shows both halves at once. `#[cgp_fn]` first produces a trait and a blanket impl, attaching `#[async_trait]` to each: @@ -225,10 +225,10 @@ the `async fn` body survives intact. **The generated future carries no `Send` bound**, and this is the limitation that matters in practice. Because the rewrite produces a bare `impl Future`, the future is `Send` only when the concrete future -happens to be, and the trait does not require it — so code that spawns the future onto a multi-threaded, +happens to be, and the trait does not require it. So code that spawns the future onto a multi-threaded, work-stealing executor cannot express what it needs through this trait. -The bound you would want to write is Return Type Notation — `App: CanFetch` — which is not +The bound you would want to write is Return Type Notation (`App: CanFetch`), which is not stabilized, so it cannot be written today. The workaround is to declare a second, ordinary trait whose method spells `+ Send` on its return type directly, and to implement it for each concrete context. That pattern is mechanical but unavoidable; the opacity that makes the rewrite zero-cost is the same opacity that hides the @@ -243,7 +243,7 @@ error[E0277]: `{integer}` is not a future ``` That error names the body's type rather than the rewrite that caused it. In practice this is rarely hit, -because async trait methods are almost always declarations with the behaviour supplied by a provider — but a +because async trait methods are almost always declarations with the behaviour supplied by a provider. But a default-bodied `async fn` inside an `#[async_trait]` trait is not supported. Wrap the body in an `async { … }` block by hand, or move it to a provider. diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 2bd6a6ee..41df6435 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -11,15 +11,15 @@ Generate a blanket impl from a trait with default methods and supertrait depende The pattern CGP is built on is an **extension trait**: a trait with a clean interface whose [blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) carries the real requirements in its `where` clause. A trait declared `FooBar: Foo + Bar` with a default `foo_bar` method -exposes only `foo_bar` to callers, while the `Foo + Bar` requirements live on the impl — so any type +exposes only `foo_bar` to callers, while the `Foo + Bar` requirements live on the impl. So any type satisfying them gains the capability, and nobody calling `foo_bar` has to know or repeat what it needed. That is worth doing rather than writing a generic function, because a function's `where` clause propagates: every generic caller repeats it, and so does every caller of *those*. Hiding the requirement on an impl stops the cascade at one level. -Written by hand the pattern is repetitive. You state the supertraits twice — once on the trait, once on the -impl — and copy each default body across. `#[blanket_trait]` lets you write the trait once and generates the +Written by hand the pattern is repetitive. You state the supertraits twice, once on the trait and once on the +impl, and copy each default body across. `#[blanket_trait]` lets you write the trait once and generates the impl: ```rust @@ -32,13 +32,13 @@ pub trait FooBar: Foo + Bar { } ``` -**This is not a CGP component.** There is no consumer/provider split, no component marker, and no wiring — +**This is not a CGP component.** There is no consumer/provider split, no component marker, and no wiring: just an ordinary Rust trait and an ordinary blanket impl. It is the tool for a capability with exactly one definition, where you want extension-trait ergonomics without committing to the component machinery. When a second implementation becomes necessary, the trait can be promoted to a [`#[cgp_component]`](./cgp_component.md). -## Using it +## Usage `#[blanket_trait]` is **not exported by the prelude**, so it needs an explicit import: @@ -60,8 +60,8 @@ pub trait FooBar: Foo + Bar { } ``` -The attribute takes an optional identifier naming the generic **context** type — the type the capability runs -against — in the generated impl. Omitted, it is the reserved `__Context__`, chosen so it cannot collide with +The attribute takes an optional identifier naming the generic **context** type (the type the capability runs +against) in the generated impl. Omitted, it is the reserved `__Context__`, chosen so it cannot collide with one of your own type parameters: ```rust @@ -75,7 +75,7 @@ special treatment described next. ### Lifting an associated type out of a supertrait An associated type on the trait becomes a fresh generic parameter on the impl, bound through the supertrait's -associated-type equality. This is one of the pattern's main uses — re-exporting a supertrait's type under a +associated-type equality. This is one of the pattern's main uses: re-exporting a supertrait's type under a local name: ```rust @@ -87,7 +87,7 @@ pub trait HasFooTypeAtBar: HasFooTypeAt { A context implementing `HasFooTypeAt` gets `HasFooTypeAtBar` automatically, with `FooBar` resolved to whatever its `Foo` was. Bounds on the associated type move onto the lifted parameter, so `Clone` above becomes -a requirement on that underlying type. Associated types need no default — the macro supplies the assignment +a requirement on that underlying type. Associated types need no default: the macro supplies the assignment itself. ## Examples @@ -130,7 +130,7 @@ pub fn run(ctx: &Ctx) { ``` `Ctx` never mentions `FooBar`. It implements `Foo` and `Bar`, and the generated blanket impl supplies -`foo_bar` — while a caller of `foo_bar` sees a one-method interface and is shielded from the requirement +`foo_bar`. A caller of `foo_bar` sees a one-method interface and is shielded from the requirement entirely. The degenerate case is useful too. A trait with no methods becomes a trait alias in all but name, which is a @@ -146,7 +146,7 @@ Any type that is `Foo + Bar` is now `FooBar`, and a signature can say so in one ## When to reach for it, and when not **Reach for `#[blanket_trait]` when a capability has one definition and its dependencies are other traits.** -That last clause is the real discriminator, and it is what separates this macro from its closest neighbour. +That last clause is the real discriminator, separating this macro from its closest neighbour. - **[`#[cgp_fn]`](./cgp_fn.md) when the dependencies are context *fields*.** Both macros produce a single-implementation capability with a blanket impl and no wiring, so the choice is about the input. @@ -155,7 +155,7 @@ That last clause is the real discriminator, and it is what separates this macro default bodies. Values point to `#[cgp_fn]`, capabilities point here. - **[`#[cgp_component]`](./cgp_component.md) when a second implementation is needed.** A blanket impl covers every type satisfying its bounds, which leaves nowhere for an alternative to live. Promoting later is - cheap — the trait keeps its name and method — so starting here costs nothing if that changes. + cheap (the trait keeps its name and method), so starting here costs nothing if that changes. - **A trait alias, when one exists.** The empty-body form above is a workaround for a language feature Rust does not have on stable; it is the right workaround, but do not reach for the macro if a plain supertrait bound reads fine at the use site. @@ -214,8 +214,8 @@ where } ``` -The body appears twice — once as the trait's default and once in the impl — and that is what the macro -actually emits rather than a simplification. The impl is what supplies the method for every qualifying type; +The body appears twice, once as the trait's default and once in the impl, and the macro actually emits both +rather than simplifying. The impl supplies the method for every qualifying type; the retained default is harmless, and a type implementing the trait by hand can still rely on it. A trait with no methods generates an empty impl, which is the trait-alias form: @@ -246,10 +246,10 @@ where Reading it back: the impl applies to any context whose `HasFooTypeAt::Foo` is some `FooBar` that is `Clone`, and re-exposes that type under the local name. The declared bound moved from the associated type onto -the lifted parameter, which is what makes it a requirement on the *underlying* type rather than an assertion +the lifted parameter, which makes it a requirement on the *underlying* type rather than an assertion about the alias. -Associated constants are forwarded like methods — their default expressions become the impl's definitions. A +Associated constants are forwarded like methods: their default expressions become the impl's definitions. A method or constant with no usable default is an error, since the macro has nothing to forward.
@@ -278,16 +278,16 @@ reported as an unknown attribute rather than as a missing import: error: cannot find attribute `blanket_trait` in this scope ``` -Add `use cgp::core::macros::blanket_trait;`. This is the one macro on this page's family that needs it — +Add `use cgp::core::macros::blanket_trait;`. This is the one macro on this page's family that needs it: `#[cgp_fn]`, `#[cgp_component]`, and the rest are all re-exported by the prelude. **A method without a default body is an error.** The macro forwards defaults into the impl, so a bare declaration leaves it nothing to emit. This is the opposite of an ordinary trait, where a bodiless method is -the normal case. The same holds for a constant, and the two say so distinctly — *function item require +the normal case. The same holds for a constant, and the two say so distinctly: *function item require implementation block* and *const item require implementation expression*. -**Only methods, associated types, and associated constants are accepted.** A trait item of any other kind — -a macro invocation in the body, say — is refused with *unsupported trait item*, because the macro has to +**Only methods, associated types, and associated constants are accepted.** A trait item of any other kind, +such as a macro invocation in the body, is refused with *unsupported trait item*, because the macro has to mirror each item into the impl and knows only those three shapes. **The trait keeps its default bodies.** The expansion does not strip them, so each body appears both on the diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index b7ce68ca..ca068a2d 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -19,7 +19,7 @@ pub trait HasArea { ``` Implement `HasArea` for `Circle` and for `Rectangle`, and an `enum Shape` holding those two gets `HasArea` -as well — dispatching to whichever variant it currently holds. No `match` is written anywhere. +as well, dispatching to whichever variant it currently holds. No `match` is written anywhere. Without the macro you would either hand-write that `match` per method, or wire up the [dispatch combinators](../providers/dispatch_combinators.md) yourself: a matcher, a per-variant handler, and @@ -28,11 +28,11 @@ trait, its per-type impls, and a derive on the enum. **Its value is narrower than it looks, and worth naming precisely.** It fits when the per-variant behaviour is *exactly* "call the same trait method on the payload". The moment a variant needs different handling, or -the dispatch should be chosen by a **context** — the type the capability runs against — rather than fixed on -the enum, the combinators are what you want directly. This is the convenient front end to +the dispatch should be chosen by a **context** (the type the capability runs against) rather than fixed on +the enum, reach for the combinators directly. This is the convenient front end to [dispatching](../providers/dispatch_combinators.md), not a replacement for it. -## Using it +## Usage Write the attribute above a trait definition. It takes no arguments: @@ -100,7 +100,7 @@ assert_eq!(shape.area(), 4.0); **Every variant's payload must implement the trait**, and that requirement is checked: forgetting an impl for one variant is a compile error where the enum's method is used. That is the same exhaustiveness a hand-written -`match` gives, recovered for a generic matcher — and adding a variant to the enum without an impl for it +`match` gives, recovered for a generic matcher. Adding a variant to the enum without an impl for it breaks the build rather than silently falling through. Mutating and argument-taking methods dispatch the same way, so one trait can mix them: @@ -138,8 +138,8 @@ Reach for something else in four situations. [dispatch combinators](../providers/dispatch_combinators.md) directly and name a handler per variant. - **The dispatch should be a wired component.** The generated impl is fixed on the enum, with a unit context and a unit code, so a context cannot override how one variant is handled. Wiring - `MatchWithValueHandlers` into a context's own component is what gives that control. -- **A method needs to be generic.** Not supported, and not fixable by rearranging — see the + `MatchWithValueHandlers` into a context's own component gives that control. +- **A method needs to be generic.** Not supported, and not fixable by rearranging: see the [Gotchas](#gotchas). - **The trait needs an associated type or const.** Also rejected. A trait carrying either is not a dispatch trait in this sense; give the enum a component of its own instead. @@ -154,8 +154,8 @@ the operation from scratch and expect contexts to configure it, start with a ### Advanced -This section shows what the macro generates. You do not need it to use `#[cgp_auto_dispatch]`, but the -generated bound is what an unmet variant impl is reported against, so reading it once makes that error +This section shows what the macro generates. You do not need it to use `#[cgp_auto_dispatch]`, but an +unmet variant impl is reported against the generated bound, so reading it once makes that error legible. `cargo cgp expand` prints the same thing for your own code. ::: @@ -173,7 +173,7 @@ fn area<'__a__, __Variants__: HasArea>(__Variants__: &'__a__ __Variants__) -> f6 } ``` -The body just calls the trait method on the payload, which is what makes the per-variant handler "invoke +The body just calls the trait method on the payload, which makes the per-variant handler "invoke `HasArea::area` on whatever this variant holds". It is bound by `__Variants__: HasArea` so it applies to every payload type implementing the trait, and borrows through a fresh `'__a__` lifetime to mirror the `&self` receiver. @@ -197,9 +197,9 @@ where } ``` -Three things are worth reading off that. The matcher is invoked with a **unit context and unit code** — -`&()` and `PhantomData::<()>` — because the per-variant logic depends only on the payload, which is exactly -why a context cannot influence it. The `__Variants__: HasExtractor` bound is what requires the enum to be +Three things are worth reading off that. The matcher is invoked with a **unit context and unit code** +(`&()` and `PhantomData::<()>`), because the per-variant logic depends only on the payload, which is exactly +why a context cannot influence it. The `__Variants__: HasExtractor` bound requires the enum to be extensible. And **the first `where` bound is where a missing variant impl is reported**: it says the matcher must be a `Computer` over this enum, which holds only if every variant's payload can be handled. @@ -238,8 +238,8 @@ error: Dispatch trait methods cannot contain non-lifetime generic parameters due quantified constraints in Rust ``` -The blanket impl would need a quantified bound — "for every instantiation of the method's type parameter, -every variant's payload satisfies it" — and Rust has no way to write that. A method that must be generic has +The blanket impl would need a quantified bound ("for every instantiation of the method's type parameter, +every variant's payload satisfies it"), and Rust has no way to write that. A method that must be generic has to be handled with the [dispatch combinators](../providers/dispatch_combinators.md) directly. Lifetime parameters are fine. @@ -258,8 +258,8 @@ does not fail where the impl should have been; it fails where `shape.area()` is bound on `MatchWithValueHandlersRef`. The variant that is missing is somewhere in the chain rather than in the headline. -**The generated impl is a blanket impl over every type**, not just your enum. That is what lets it cover any -extensible enum whose payloads implement the trait — and it means the trait cannot also be implemented by +**The generated impl is a blanket impl over every type**, not just your enum. This lets it cover any +extensible enum whose payloads implement the trait, and it means the trait cannot also be implemented by hand for some other type without colliding with it. ## Related constructs diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 80b25243..81e5d05b 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -9,8 +9,9 @@ Define a getter as a blanket impl over `HasField`, keyed by the method name. ## Overview `#[cgp_auto_getter]` publishes a context field as a named, reusable accessor. You write a trait of getter -methods, and the macro implements it for every **context** — the type the capability runs against, which -supplies the values it needs as its fields — that happens to carry fields of the matching names: +methods, and the macro implements it for every **context** that happens to carry fields of the matching +names. The context is the type the capability runs against, and it supplies the values it needs as its +own fields. For example: ```rust #[cgp_auto_getter] @@ -24,18 +25,18 @@ wired and no impl is written: the macro emits one [blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) covering every qualifying context, keyed on each method's own name. -What it hides is the field-access trait CGP reads fields through, which is precise and unpleasant to write -by hand — a bound naming the field as a type-level string, and a `PhantomData` tag at every read. Being +It hides the field-access trait CGP reads fields through, which is precise and unpleasant to write by +hand: a bound naming the field as a type-level string, and a `PhantomData` tag at every read. Being able to state the same thing as `fn name(&self) -> &str;` is the point. -**Reach for it sparingly.** For the ordinary case — a provider reading a field of its own context — an +**Reach for it sparingly.** For the ordinary case, a provider reading a field of its own context, an [`#[implicit]`](../attributes/implicit.md) argument does the same job with no trait to declare, using the same field access and the same conversion rules, so a getter trait declared only to read a field adds a name and buys nothing. What a getter trait *does* buy is a capability other code can depend on by name, and the three cases where that matters are in [When to reach for it](#when-to-reach-for-it-and-when-not). -## Using it +## Usage Apply the attribute to a trait definition. It takes no arguments. The body is getter methods, each taking `&self` or `&mut self` and returning a reference: @@ -58,7 +59,7 @@ pub trait HasDimensions { ``` **The method name is the field name.** That is the whole convention, and also the construct's one real -limitation — a context must expose a field of exactly that name. +limitation: a context must expose a field of exactly that name. ### How the return type decides the read @@ -73,7 +74,7 @@ natural. The field's type is inferred from what you return: | `Option<&T>` | `Option` | `.as_ref()` | | `Option<&str>` | `Option` | `.as_deref()` | | [`MRef<'_, T>`](../types/mref.md) | `T` | by reference, wrapped as `MRef::Ref(…)` | -| An owned type — `f64`, `String`, a tuple, an array | the same type | by reference, then `.clone()` | +| An owned type (`f64`, `String`, a tuple, an array) | the same type | by reference, then `.clone()` | A `&mut self` receiver reads mutably, and each reference form has a mutable mirror: `&mut T`, `&mut [T]` through `AsMut<[T]>`, `Option<&mut T>` via `.as_mut()`, and `Option<&mut str>` via `.as_deref_mut()`. @@ -81,7 +82,7 @@ through `AsMut<[T]>`, `Option<&mut T>` via `.as_mut()`, and `Option<&mut str>` v The `&str` row is the one most often wanted and least obvious: the context stores a `String` and the getter hands out a borrow of it, so no context ever has to hold a `&str`. **These are the same rules an [`#[implicit]`](../attributes/implicit.md) argument follows**, so learning them once covers everywhere CGP -reads a field — with one difference worth holding onto. A getter takes its mutability from the +reads a field. There is one difference worth holding onto. A getter takes its mutability from the **receiver**, while an implicit argument takes it from the *argument's type*. So `fn name(&mut self) -> &mut String` reads mutably because of the `&mut self`, whereas `#[implicit] name: &String` on a `&mut self` method still reads through a shared borrow. @@ -99,11 +100,11 @@ pub trait HasFooBar: HasFooType + HasBarType { ``` The generated bound now falls on `Self::Foo` rather than on the context, and the method is called as an -associated function — `App::foo_bar(&foo)`. `Self` inside the argument and return types is rewritten to -the context, and `&` versus `&mut` decides the access mode exactly as a receiver would. +associated function: `App::foo_bar(&foo)`. The macro rewrites `Self` inside the argument and return +types to the context, and `&` versus `&mut` decides the access mode exactly as a receiver would. **This is the one getter shape an [`#[implicit]`](../attributes/implicit.md) argument cannot reach**, -because there is no `self` field to read — which makes it the clearest case for declaring a getter at +because there is no `self` field to read. This makes it the clearest case for declaring a getter at all. ### An optional `PhantomData` argument @@ -136,7 +137,7 @@ pub trait HasName { ``` The bound is enforced on whatever the field holds. When an associated type is present the trait must -contain **exactly one** getter method, whose return type is `&Self::AssocType` — there is only one field +contain **exactly one** getter method, whose return type is `&Self::AssocType`. There is only one field for the type to be inferred from. ## Examples @@ -161,7 +162,7 @@ pub fn greet(person: &Person) { } ``` -`Person` derives [`HasField`](../derives/derive_has_field.md), which is its entire qualification — the +`Person` derives [`HasField`](../derives/derive_has_field.md), which is its entire qualification. The blanket impl applies automatically, with no wiring anywhere in the program. The reason to declare the trait at all is that other code can now *require* it. A provider states the @@ -205,14 +206,15 @@ only job was to save you writing the body. **Prefer an [`#[implicit]`](../attributes/implicit.md) argument, and reach for a getter trait only when one cannot do the job.** An implicit argument reads a field of the provider's own context as an ordinary -parameter — no trait, no declaration, the same access rules — so it covers the common read directly, -including a field several providers each consume, declared as the same implicit argument in each. +parameter, with no trait, no declaration, and the same access rules, so it covers the common read +directly, including a field several providers each consume, declared as the same implicit argument in +each. A getter trait earns its keep in three cases an implicit argument cannot reach. - **The field lives on another type.** An implicit argument reads only from `self`, so a value held by a - request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type — - `Request: HasBasicAuthHeader`. There is no `self` field to read. + request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type, + as in `Request: HasBasicAuthHeader`. There is no `self` field to read. - **The accessor must be a named capability.** When other code depends on "this context can tell you its name" rather than on a field, that dependency needs a trait to point at, importable with [`#[uses]`](../attributes/uses.md) or usable as a supertrait via [`#[extend]`](../attributes/extend.md). @@ -224,7 +226,7 @@ Between the two getter macros the line is narrow and worth stating plainly. - **`#[cgp_auto_getter]` is the default getter.** One blanket impl, no wiring, field name fixed to the method name. - **[`#[cgp_getter]`](./cgp_getter.md) is the advanced one**, and not a general upgrade. Reach for it only - when a context needs to choose *which field* the getter reads — a different name per context, or an + when a context needs to choose *which field* the getter reads, as a different name per context, or an implementation selected by wiring. That control costs a line of wiring per context, and most getters do not want it. @@ -267,7 +269,7 @@ where Three things to recognize. The context parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours. [`Symbol!("name")`](./symbol.md) is a type-level string standing for the -field name — the compiler prints its expanded `Symbol<4, Chars<'n', …>>` form in errors, and +field name. The compiler prints its expanded `Symbol<4, Chars<'n', …>>` form in errors, and `cargo cgp expand` resugars it back to this. And because the return type is `&str`, the bound asks for a `String` field and the body appends `.as_str()`, which is the conversion table in action. @@ -290,7 +292,7 @@ where ``` The associated-type form lifts the type into an extra generic parameter on the impl and binds it through -the field's value, which is what lets the field decide it: +the field's value, which lets the field decide it: ```rust impl<__Context__, Name> HasName for __Context__ @@ -338,7 +340,7 @@ error: #[cgp_auto_getter] does not accept any attribute argument ``` **The trait still has to be in scope to call its method.** That is ordinary Rust, but it surprises readers -here, because nothing else about the getter had to be declared — a missing `use` reports the method as not +here, because nothing else about the getter had to be declared. A missing `use` reports the method as not found rather than the trait as not imported. ## Related constructs diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 3c5a303b..54d261e4 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -52,7 +52,7 @@ that names the capability and is the key `delegate_components!` wires against. Y every wiring entry and in most compiler errors that involve this capability, so you should be able to recognize it immediately, even though you never write its definition yourself. -## Using it +## Usage Apply the attribute to a trait definition and give it the provider trait's name. The simplest form is a bare identifier: diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 83aa6117..dcd9b9b9 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -8,7 +8,7 @@ Define a `Computer` provider from a plain function. ## Overview -CGP models computation as a family of components varying along three axes — synchronous or async, fallible +CGP models computation as a family of components varying along three axes: synchronous or async, fallible or not, taking an input or not. A provider in that family is a struct with one or more impls threading a **context** (the type the capability runs against, which supplies the values it needs as its fields), a phantom `Code` tag, and an `Input`. Written by hand for a computation as small as "add two numbers", that is @@ -23,19 +23,21 @@ fn add(a: u64, b: u64) -> u64 { } ``` -From that the macro produces the provider struct `Add`, an impl of the right base trait, and — the part -worth understanding — the wiring that makes the *same function* answer the whole family. `Add` satisfies +From that the macro produces the provider struct `Add`, an impl of the right base trait, and the wiring +that makes the *same function* answer the whole family. That wiring is the part worth understanding. +`Add` satisfies `compute`, `try_compute`, `compute_async`, and `handle`, along with their by-reference forms, without you implementing any of them. -That last property is what the macro is really for. The family exists so a provider can declare exactly the -capabilities it has, and the [promotion combinators](../providers/handler_combinators.md) exist so a simpler -provider can stand in where a more capable one is expected — an infallible computation is a fallible one -that never fails, a synchronous one is an async one that never awaits. `#[cgp_computer]` picks the narrowest +That last property is the whole reason for the macro. The family exists so a provider can declare exactly +the capabilities it has, and the [promotion combinators](../providers/handler_combinators.md) exist so a +simpler provider can stand in where a more capable one is expected: an infallible computation is a +fallible one that never fails, a synchronous one is an async one that never awaits. `#[cgp_computer]` picks +the narrowest base that fits your function and wires the promotions for the rest, so you write one body and get every shape. -## Using it +## Usage Apply the attribute to a free function. It takes an optional provider name: @@ -51,7 +53,7 @@ fn add(a: u64, b: u64) -> u64 { } ``` -Omitted, the provider struct takes the function name in PascalCase — `add` becomes `Add`. Given, the +Omitted, the provider struct takes the function name in PascalCase: `add` becomes `Add`. Given, the argument is used verbatim. The function's shape decides everything else: @@ -61,7 +63,7 @@ The function's shape decides everything else: - **Its return type becomes the output.** - **It must not take `self`.** A handler provider has no receiver; the context is supplied separately by the handler machinery. -- **It may be `async`**, and it may return a `Result`. Those two choices are what select the base trait. +- **It may be `async`**, and it may return a `Result`. Those two choices select the base trait. - **Its generics and `where` clause carry over** to the generated impl, so the provider can itself be generic. @@ -77,8 +79,8 @@ promotion bundle: | `async fn f(..) -> T` | `AsyncComputer` | `PromoteAsyncComputer` | | `async fn f(..) -> Result` | `AsyncComputer` | `PromoteHandler` | -The `Result` row is worth reading twice. The base trait stays `Computer` — its `Output` is simply the -`Result` type as written — and what changes is the *bundle*, which is what makes `try_compute` and `handle` +The `Result` row is worth reading twice. The base trait stays `Computer`, and its `Output` is simply the +`Result` type as written. Only the *bundle* changes, and it makes `try_compute` and `handle` surface the `Ok`/`Err` outcome as success or failure rather than handing back a `Result` as a plain value. ## Examples @@ -149,12 +151,12 @@ exists for, and it is the shortest route into the handler family. - **Use [`#[cgp_fn]`](./cgp_fn.md) when what you want is a capability on the context, not a pipeline step.** The two look similar and differ in what they produce: `#[cgp_fn]` gives a trait a context implements, called as `self.thing()`; `#[cgp_computer]` gives a *provider* that gets wired into a handler component and - composed with combinators. If you are not building a pipeline, `#[cgp_fn]` is what you want. + composed with combinators. If you are not building a pipeline, reach for `#[cgp_fn]` instead. - **Wire the [handler combinators](../providers/handler_combinators.md) directly for composition.** The macro produces one step; `PipeHandlers` and friends chain them. One thing not to do is reach for the handler family because a capability happens to transform a value. The -family earns its keep when computations are *composed* — piped, dispatched on a `Code` tag, promoted between +family earns its keep when computations are *composed*: piped, dispatched on a `Code` tag, promoted between variants. A single transform with one caller is a method. ## Under the hood @@ -198,8 +200,8 @@ impl<__Context__, __Code__> Computer<__Context__, __Code__, (u64, u64)> for Add } ``` -[`#[cgp_new_provider]`](./cgp_provider.md) is what declares `pub struct Add;` and derives the -[`IsProviderFor`](../traits/is_provider_for.md) impl — whose parameter tuple here is +[`#[cgp_new_provider]`](./cgp_provider.md) declares `pub struct Add;` and derives the +[`IsProviderFor`](../traits/is_provider_for.md) impl, whose parameter tuple here is `(__Code__, (u64, u64))`, the code tag and the input. The context and code parameters are introduced under the reserved names `__Context__` and `__Code__`, and the body ignores both. @@ -224,12 +226,12 @@ delegate_components! { Note the **`->` operator** rather than `:`. It delegates each key to *the value's own entry for that key* rather than to the value itself, so `Add` inherits whatever `PromoteComputer` resolves each component -to — and [`PromoteComputer`](../providers/handler_combinators.md) is itself a table of single-step promoters. +to. [`PromoteComputer`](../providers/handler_combinators.md) is itself a table of single-step promoters. `ComputerComponent` is absent from the list because `Add` implements it directly. The other three combinations differ only in which base trait is implemented and which bundle is named. An `async` function implements `AsyncComputer` instead, its method is `compute_async` and awaits the call, and -it delegates a smaller set — `AsyncComputerRefComponent`, `HandlerComponent`, `HandlerRefComponent` — since +it delegates a smaller set (`AsyncComputerRefComponent`, `HandlerComponent`, `HandlerRefComponent`), since the synchronous members are not derivable from an async base. A `Result`-returning function keeps its base trait and swaps the bundle to `PromoteTryComputer` or, when also async, `PromoteHandler`. @@ -271,7 +273,7 @@ input is `(T)`, which Rust treats as plain `T`. **The fallible forms need an error type on the context.** `try_compute` and `handle` name the context's abstract error, so a context wiring the provider without an [`ErrorTypeProviderComponent`](../components/has_error_type.md) fails on those members while `compute` works -fine — an error about the error type, arriving only for part of the family. Note also that the wiring key is +fine. This is an error about the error type, arriving only for part of the family. Note also that the wiring key is **not in the prelude**: it has to be imported from `cgp::core::error`, and forgetting that reports the component as an unresolved type rather than as a missing import. diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 7fce1bea..7ef4aed6 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -8,10 +8,10 @@ Define a single-implementation capability as a blanket-impl trait, straight from ## Overview -`#[cgp_fn]` is the smallest amount of CGP that does anything useful. You write a plain function, mark -the values it needs from the **context** — the type the capability runs against, which supplies those -values as its fields — and the macro turns it into a capability that every type with those fields gets -automatically: +`#[cgp_fn]` is the smallest amount of CGP that does anything useful. You write a plain function and +mark the values it needs from the **context**. The context is the type the capability runs against, +and it supplies those values as its own fields. The macro turns the function into a capability that +every type with those fields gets automatically: ```rust #[cgp_fn] @@ -21,26 +21,26 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> ``` Any struct with a `width` and a `height` can now call `.rectangle_area()`. There is no component to -define, no provider to name, and no wiring table anywhere — the macro emits a trait and one +define, no provider to name, and no wiring table anywhere. The macro emits a trait and one [blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) covering every context that satisfies the field requirements. That is the trade it makes, and it is worth being explicit about. A [`#[cgp_component]`](./cgp_component.md) supports many interchangeable implementations, one chosen per -context, and charges for it in ceremony. `#[cgp_fn]` supports exactly one implementation — the -function body — and charges nothing. For the large share of capabilities that have one natural -definition, that is the better deal, which is why `#[cgp_fn]` is the recommended place to start rather -than a lesser form of the real thing. +context, and this costs extra ceremony. `#[cgp_fn]` supports exactly one implementation, the function +body, and costs nothing. For the large share of capabilities that have one natural definition, that is +the better deal, which is why `#[cgp_fn]` is the recommended place to start rather than a lesser form +of the real thing. -It is also the gentlest introduction to CGP, because nothing in it is unfamiliar. A reader who +It is also the easiest introduction to CGP, because nothing in it is unfamiliar. A reader who understands functions and arguments can write a working capability without first meeting trait bounds, -blanket implementations, or type-level field names. All of that stays behind an -[`#[implicit]`](../attributes/implicit.md) parameter that looks like an ordinary one. +blanket implementations, or type-level field names. An [`#[implicit]`](../attributes/implicit.md) +parameter hides all of that and looks like an ordinary parameter. -## Using it +## Usage Apply the attribute to a free function. The function name becomes the method name, and its PascalCase -form becomes the trait name — `rectangle_area` generates a `RectangleArea` trait with a +form becomes the trait name: `rectangle_area` generates a `RectangleArea` trait with a `rectangle_area` method. Almost every `#[cgp_fn]` takes `self` as its first parameter, because reading a field from the context @@ -67,8 +67,8 @@ argument and write through it. An [`#[implicit]`](../attributes/implicit.md) parameter is removed from the method's signature and filled from a same-named field on the context instead. The parameter's *name* is the field name, and its *type* decides how the field is read: an owned type is cloned out, a `&str` is borrowed from a -`String` field, and a plain `&T` is borrowed with no conversion. The full set of forms — including -options, slices, and the mutable variants — is on the [`#[implicit]`](../attributes/implicit.md) page. +`String` field, and a plain `&T` is borrowed with no conversion. The full set of forms, including +options, slices, and the mutable variants, is on the [`#[implicit]`](../attributes/implicit.md) page. Because these parameters disappear from the signature, `rectangle_area` above is called with no arguments at all: `rect.rectangle_area()`. @@ -85,9 +85,9 @@ most of what there is to learn about the macro. | [`#[impl_generics(T: Bound)]`](#a-type-the-caller-should-not-name) | The impl only | | [`#[extend_where(...)]`](../attributes/extend_where.md) | Both the trait and the impl | -The default — generics on both, `where` clause on the impl alone — is what keeps a capability's -requirements out of sight of its callers. A caller bounds on the clean trait, and the constraints the -body actually needs stay one level down on the implementation: +By default, generics land on both the trait and the impl, and the `where` clause lands on the impl +alone. This keeps a capability's requirements out of sight of its callers: a caller bounds on the +clean trait, and the constraints the body actually needs stay one level down on the implementation: ```rust #[cgp_fn] @@ -103,8 +103,8 @@ where #### A type the caller should not name -When the function needs a type that should be inferred rather than chosen — a database handle, a -displayable value — declare it with `#[impl_generics(...)]`. The parameter goes on the impl alone, so +When the function needs a type that should be inferred rather than chosen, such as a database handle +or a displayable value, declare it with `#[impl_generics(...)]`. The parameter goes on the impl alone, so the trait stays unparameterized and no caller mentions it: ```rust @@ -119,7 +119,7 @@ pub fn describe(&self, #[implicit] name: &Name) -> String { `Display` type, and the type is resolved from that field. The cost is that the type is concealed rather than named. It exists only where a value of it flows -through an implicit argument, so nothing else can refer to it — including this function's own +through an implicit argument, so nothing else can refer to it, including this function's own signature. Naming it in a return type or an explicit parameter does not compile, as the [Gotchas](#gotchas) explain. When the type must be nameable, or when two capabilities have to agree that they mean the same type, promote it to an abstract type with [`#[cgp_type]`](./cgp_type.md) and @@ -179,8 +179,8 @@ pub fn report(rect: &Rectangle) { `scaled_rectangle_area` calls `self.rectangle_area()` because `#[uses(RectangleArea)]` declared the dependency; it does not know or care how that capability is implemented. `Rectangle` derives [`HasField`](../derives/derive_has_field.md) and happens to carry the three fields the two functions -read, which is its entire qualification — there is no `delegate_components!` anywhere in this program, -and adding one would change nothing. +read, and that is its entire qualification. There is no `delegate_components!` anywhere in this +program, and adding one would change nothing. ## When to reach for it, and when not @@ -191,13 +191,13 @@ you add at that point is the component, a named provider, and a line of wiring p Reach for something else in three cases. -- **The capability needs a second implementation, chosen per context.** That is what - [`#[cgp_component]`](./cgp_component.md) is for, and no amount of `#[cgp_fn]` will get you there — - its blanket impl already covers every context, so there is nowhere for an alternative to live. +- **The capability needs a second implementation, chosen per context.** + [`#[cgp_component]`](./cgp_component.md) is for that, and no amount of `#[cgp_fn]` will get you + there: its blanket impl already covers every context, so there is nowhere for an alternative to live. - **The dependencies are traits rather than fields.** [`#[blanket_trait]`](./blanket_trait.md) builds the same kind of single-implementation, no-wiring capability from a trait with supertraits and - default method bodies. Reach for it when what the body needs is other capabilities; reach for - `#[cgp_fn]` when what it needs is values. + default method bodies. Reach for it when the body needs other capabilities; reach for `#[cgp_fn]` + when it needs values. - **A generic must vary per call.** A generic parameter here goes on the trait rather than the method, so it is fixed by whatever satisfies the bounds for a given context rather than chosen at each call site. A capability that genuinely needs a per-call type parameter wants a hand-written blanket impl @@ -205,12 +205,12 @@ Reach for something else in three cases. One decision inside the macro is worth making deliberately rather than by default: **where a type the body needs should live.** Start with `#[impl_generics]` while the type only ever flows through implicit -arguments — it is shorter, needs no wiring, and reads as "this works with any `database` field of a +arguments. It is shorter, needs no wiring, and reads as "this works with any `database` field of a compatible type". Climb to an [abstract type](./cgp_type.md) when the type must appear in the -capability's own signature, or when two capabilities must agree that they mean the same one. What to -avoid in both cases is a plain generic parameter on the function, which lands on the trait and makes -every caller — and every intermediate capability built on it — declare the parameter and repeat its -bounds whether they touch it or not. +capability's own signature, or when two capabilities must agree that they mean the same one. Avoid a +plain generic parameter on the function in both cases: it lands on the trait and makes every caller, +and every intermediate capability built on it, declare the parameter and repeat its bounds whether +they touch it or not. ## Under the hood @@ -264,13 +264,13 @@ where Three details of the real output are worth recognizing. The context type parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours, and it is referred to as `Self` inside the impl. [`Symbol!("width")`](./symbol.md) is a type-level string standing for the field -name — the compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and -`cargo cgp expand` resugars it back to this. And the `.clone()` is what an *owned* implicit argument -compiles to; a `&str` argument ends in `.as_str()` instead, and a plain `&T` in nothing at all. +name. The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and +`cargo cgp expand` resugars it back to this. An *owned* implicit argument compiles to a trailing +`.clone()`; a `&str` argument ends in `.as_str()` instead, and a plain `&T` in nothing at all. The generics split shows up in the same impl. Given the `scale` function above, the generic goes on both items while the function's `where` bound stays on the impl, ordered *before* the implicit field -bounds — attribute-contributed predicates always come first, and the implicit ones are appended last: +bounds. Attribute-contributed predicates always come first, and the implicit ones are appended last: ```rust pub trait Scale { @@ -289,18 +289,18 @@ where The companion attributes layer into these same two items. `#[uses(Trait)]` adds a `Self: Trait` predicate to the impl; `#[extend(Trait)]` adds it to the impl *and* to the trait's supertraits; `#[extend_where(P)]` adds `P` to both `where` clauses; `#[impl_generics(T: Bound)]` inserts `T: Bound` -into the impl's generic list alone — its argument is a comma-separated list of ordinary generic -parameters, so a lifetime or a const parameter is accepted there too; and +into the impl's generic list alone (its argument is a comma-separated list of ordinary generic +parameters, so a lifetime or a const parameter is accepted there too); and `#[use_type(Trait.Type)]` adds the supertrait and rewrites every bare mention of the type into its -fully qualified form. The implicit-argument bounds are appended -last, after whatever the attributes contributed. +fully qualified form. The macro appends the implicit-argument bounds last, after whatever the +attributes contributed. Two smaller placements are worth knowing because neither is visible in the source you wrote. **The -function's visibility becomes the trait's**, and the method inside the impl is left inherited — so +function's visibility becomes the trait's**, and the impl's method keeps inherited visibility. So `pub fn rectangle_area` yields `pub trait RectangleArea`, and a private `fn` yields a private trait -usable only in its own module. And **an attribute the macro does not recognize is copied onto both -items**, which is what lets `#[allow(...)]`, `#[doc]`, or a doc comment ride through and apply to the -trait and the impl alike. +usable only in its own module. And **the macro copies an attribute it does not recognize onto both +items**, which lets `#[allow(...)]`, `#[doc]`, or a doc comment ride through and apply to the trait and +the impl alike.
Formal grammar @@ -346,11 +346,11 @@ trait. Both spellings report the same headline: error[E0425]: cannot find type `Db` in this scope ``` -What differs is the code, and that is the part worth noticing, since it is what you are likely to search -for. A bare `Db` reports `E0425` as above; a qualified path such as `Db::Row` reports `E0433`, whose span -is labelled *use of undeclared type `Db`* instead. Both mean the same thing — either the type belongs out -of the signature, or it needs to be an [abstract type](./cgp_type.md) rather than an inferred impl -parameter. +The error code differs, and that is the part worth noticing, since you are likely to search for it. A +bare `Db` reports `E0425` as above; a qualified path such as `Db::Row` reports `E0433`, and the +compiler labels its span *use of undeclared type `Db`* instead. Both mean the same thing: either the +type belongs out of the signature, or it needs to be an [abstract type](./cgp_type.md) rather than an +inferred impl parameter. ## Related constructs diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index dde7d791..b1e29093 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -10,12 +10,12 @@ Define a getter as a full component, so the field it reads is chosen by wiring r [`#[cgp_auto_getter]`](./cgp_auto_getter.md) ties a getter to a field of the same name: declare `fn name(&self) -> &str` and every context with a `name` field satisfies it. That is the right trade almost -always, and it has one hard edge — a context that stores the value under a different name cannot use the +always, and it has one hard edge: a context that stores the value under a different name cannot use the getter at all. -`#[cgp_getter]` removes that coupling by making the getter a real component. The **context** — the type -the capability runs against, which supplies the values it needs as its fields — then says in its wiring -which field the getter should read: +`#[cgp_getter]` removes that coupling by making the getter a real component. The **context** is the +type the capability runs against, and it supplies the values it needs as its own fields. It then says +in its wiring which field the getter should read: ```rust delegate_components! { @@ -34,10 +34,10 @@ decoupling is a line of wiring per context, and what you get is only useful when to control which field is read, or to supply the value some way other than reading a field. Most getters want neither. The [When to reach for it](#when-to-reach-for-it-and-when-not) section draws the line. -## Using it +## Usage -Apply the attribute to a getter trait, exactly as with [`#[cgp_auto_getter]`](./cgp_auto_getter.md). The -same method forms are accepted — every receiver shape, including a +Apply the attribute to a getter trait, exactly as with [`#[cgp_auto_getter]`](./cgp_auto_getter.md). It +accepts the same method forms: every receiver shape, including a [typed reference to another type](./cgp_auto_getter.md#reading-a-field-of-another-type) in place of `self` and an [optional `PhantomData` argument](./cgp_auto_getter.md#an-optional-phantomdata-argument); and the `&str`, `&[T]`, `Option<&T>`, `Option<&str>`, `MRef<'_, T>`, owned, and associated-type return @@ -76,12 +76,12 @@ Three providers come out of the macro, and which you name decides where the valu | Wire it to | The getter reads | |---|---| | [`UseField`](../providers/use_field.md) | the field named `f`, whatever the method is called | -| `UseFields` | the field named after each method — the `#[cgp_auto_getter]` behaviour, as a provider | +| `UseFields` | the field named after each method, the `#[cgp_auto_getter]` behaviour as a provider | | [`WithProvider

`](../providers/with_provider.md) | whatever the field-getter provider `P` supplies | `UseField` is the one to reach for, and the reason the construct exists. `UseFields` is useful when a trait has several methods and the names all happen to match, and it is the only one of the three that -works for a multi-method trait — the other two presuppose a single field. +works for a multi-method trait: the other two presuppose a single field. A `#[cgp_getter]` trait can also be implemented directly on a concrete context, like any Rust trait, when a particular context wants neither wiring nor a field. @@ -116,7 +116,7 @@ pub fn greet(person: &Person) { ``` `person.name()` returns `first_name`, because the wiring said so. A second context can store it under yet -another name and wire accordingly, with `HasName` and every caller unchanged — which is the whole +another name and wire accordingly, with `HasName` and every caller unchanged. This is the whole difference from the blanket-impl getter. Where the names *do* line up, `UseFields` gives the auto-getter behaviour without giving up the component: @@ -151,14 +151,14 @@ consumer trait can be implemented like any Rust trait. the last resort, and the ordering is worth holding whole: 1. **An [`#[implicit]`](../attributes/implicit.md) argument** for a provider reading a field of its own - context. No trait, no wiring — this covers most reads. + context. No trait, no wiring. This covers most reads. 2. **[`#[cgp_auto_getter]`](./cgp_auto_getter.md)** when the accessor has to exist as a *named capability* other code depends on, when the field lives on another type, or when the getter carries a type inferred from the field. One blanket impl, still no wiring. 3. **`#[cgp_getter]`** only when a context must control *how the getter is satisfied*. That third condition is narrow, and it has two real forms. One is a **field name that differs per -context** — the same capability reading `first_name` on one type and `display_name` on another. The other +context**: the same capability reading `first_name` on one type and `display_name` on another. The other is a context that supplies the value **some way other than a plain field read**, through `WithProvider` or a hand-written impl, while other contexts still read a field. @@ -182,19 +182,19 @@ Reach for something else in these cases. ### Advanced This section shows the getter-specific providers the macro adds. You do not need them to use -`#[cgp_getter]`, but the `UseField` impl is what makes the field name a wiring decision, and seeing it -explains why the tag is a parameter here and a fixed value in the auto-getter. `cargo cgp expand` prints -the same thing for your own code. +`#[cgp_getter]`, but the `UseField` impl makes the field name a wiring decision, and seeing it explains +why the tag is a parameter here and a fixed value in the auto-getter. `cargo cgp expand` prints the +same thing for your own code. ::: -`#[cgp_getter]` emits everything [`#[cgp_component]`](./cgp_component.md) would — the consumer trait, the +`#[cgp_getter]` emits everything [`#[cgp_component]`](./cgp_component.md) would: the consumer trait, the provider trait, the two blanket impls, the marker, and the standard [`UseContext`](../providers/use_context.md) and [`RedirectLookup`](../providers/redirect_lookup.md) -impls — then adds the getter providers below. `UseFields` is always emitted; `UseField` and `WithProvider` -only when the trait has exactly one method, since both presuppose a single field. +impls. It then adds the getter providers below. The macro always emits `UseFields`; it emits `UseField` +and `WithProvider` only when the trait has exactly one method, since both presuppose a single field. -The important addition is the **`UseField` impl**, which is what decouples the field from the method name. +The important addition is the **`UseField` impl**, which decouples the field from the method name. From this trait: ```rust @@ -223,8 +223,8 @@ where reads `first_name`. The `&str` shorthand behaves identically in both: the bound asks for a `String` and the body appends `.as_str()`. -Next is the `UseFields` impl, which is the auto-getter's behaviour expressed as a provider — the tag fixed -to each method's own name: +Next is the `UseFields` impl, which is the auto-getter's behaviour expressed as a provider, with the +tag fixed to each method's own name: ```rust impl<__Context__> NameGetter<__Context__> for UseFields @@ -286,8 +286,8 @@ error[E0277]: the trait bound `UseField>>: IsProviderF Nothing in that says the trait had too many methods, which is the actual cause. Use `UseFields`, or split the trait into one component per field. -**The provider name is derived by stripping `Has`.** `HasName` yields `NameGetterComponent`, so a trait -*not* named `Has…` produces a component whose name may surprise you — `Dimensions` yields +**The macro derives the provider name by stripping `Has`.** `HasName` yields `NameGetterComponent`, so +a trait *not* named `Has…` produces a component whose name may surprise you: `Dimensions` yields `DimensionsGetterComponent`. Pass the name explicitly when the convention does not fit. **Wiring `UseFields` everywhere means the component was unnecessary.** If no context ever names a @@ -302,8 +302,8 @@ tag chose the field and not the conversion: error[E0271]: type mismatch resolving `

>>>::Value == String` ``` -The `Symbol<10, …>` in that message is `first_name` with its length in bytes — worth being able to read, since -the tag is what tells you which field the mismatch is about. +The `Symbol<10, …>` in that message is `first_name` with its length in bytes, worth being able to read +since the tag tells you which field the mismatch is about. ## Related constructs diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 938d6d58..f7fc3de3 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -26,8 +26,8 @@ where ``` Every part of that is correct, and almost every part of it is unfamiliar. The trait carries a -parameter you did not write, `Self` is a type with no values, and there is no `self` anywhere — which -obscures the simple thing that is actually going on: this is an implementation of `CanCalculateArea`. +parameter you did not write, `Self` is a type with no values, and there is no `self` anywhere. This +hides a simple fact: it is an implementation of `CanCalculateArea`. `#[cgp_impl]` gives you back the familiar shape. Write the implementation as though you were implementing the consumer trait directly, with `self` and `Self` and the signatures from the original @@ -45,20 +45,20 @@ where } ``` -The macro performs the rewrite for you. **This is the form to write**; the inside-out one is what it -desugars to and what you will meet in generated code. +The macro performs the rewrite for you. Write providers this way. The macro produces the inside-out +form shown earlier, and you will meet that form in generated code. One fact the convenience must not hide: **inside a `#[cgp_impl]` block, `self` and `Self` mean the -context — the type the capability runs against, which supplies the values it needs as its fields — -and not the provider.** The provider is a -type-level name with no fields and no value: it is never constructed, and there is nothing in it to -read. The macro rewrites `self` to the context value and `Self` to the context type precisely because -the context is the only thing that exists when the method runs. +context, not the provider.** The context is the type the capability runs against, and it supplies the +values it needs as its own fields. The provider is a type-level name with no fields and no value: it +is never constructed, and there is nothing in it to read. The macro rewrites `self` to the context +value and `Self` to the context type because the context is the only thing that exists when the +method runs. -## Using it +## Usage -Apply the attribute to an `impl` block. Its argument names the provider, and has three parts of which -only the name is required. +Apply the attribute to an `impl` block. Its argument names the provider. The argument has three parts, +and only the name is required. ```rust #[cgp_impl(new RectangleArea)] @@ -78,7 +78,7 @@ where | provider name | Required. The type that takes the `Self` position in the generated provider impl. | | `: ComponentType` | Optional. Overrides which component this provider is registered as implementing. Defaults to the provider trait's name plus `Component`. | -Without `new`, the provider struct must already exist — a wiring entry naming a struct nothing +Without `new`, the provider struct must already exist. A wiring entry naming a struct nothing declares is a common and confusing first error. A provider may be generic. Parameters go in the attribute and in the impl generics together, which is @@ -95,10 +95,67 @@ impl AreaCalculator { } ``` +### Declaring the provider struct separately + +`new` is convenient for a provider used once, but a struct implementing several provider traits, or +one whose shape `new` cannot express, is usually declared on its own instead. + +**A provider often implements more than one component.** Each provider trait still needs its own +`#[cgp_impl]` block, but only one of those blocks should declare the struct. Write `new` on exactly +one of them and omit it from the rest: + +```rust +#[cgp_impl(new RectangleGeometry)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[cgp_impl(RectangleGeometry)] +impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } +} +``` + +The first block's `new` declares `pub struct RectangleGeometry;`; the second block names the same +struct without `new` and adds a second impl to it. Writing `new` on more than one block for the same +struct is a duplicate-definition error. + +**A struct whose shape `new` cannot express** is declared explicitly instead, once, above every +`#[cgp_impl]` block that targets it. A default generic parameter, such as +`pub struct IterSum(PhantomData);`, is the case you meet most often: + +```rust +pub struct RectangleGeometry; + +#[cgp_impl(RectangleGeometry)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[cgp_impl(RectangleGeometry)] +impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } +} +``` + +Either style works for a struct implementing several components. Declaring it explicitly reads more +consistently once there are more than two or three blocks, since a reader does not have to find the +one block carrying `new` to know where the struct comes from. Neither style requires +[`#[cgp_provider]`](./cgp_provider.md): the struct is only being declared once and reused, and the +body of every block still reads as an ordinary trait impl. + ### Companion attributes -Several attributes are processed on a `#[cgp_impl]` block before the rewrite happens, and together -they are how an idiomatic provider states what it needs. +Several attributes are processed on a `#[cgp_impl]` block before the rewrite happens. Together they +let an idiomatic provider state what it needs. - [`#[implicit]`](../attributes/implicit.md) on a parameter removes it from the signature and fills it from a same-named field on the context. @@ -112,13 +169,13 @@ they are how an idiomatic provider states what it needs. per-type default, for use with [`cgp_namespace!`](./cgp_namespace.md). Each may be repeated. All except `#[use_provider]` also take a comma-separated list inside one -attribute, which is the form to prefer — `#[uses(HasName, CanRaiseError)]` reads as one +attribute, which is the form to prefer: `#[uses(HasName, CanRaiseError)]` reads as one dependency list. `#[use_provider]` is the exception because its own argument already ends in a bound list, so a second pair after a comma has nowhere to go; write one attribute per inner provider. Three attributes that appear on other CGP macros are not read here. `#[extend]`, `#[extend_where]`, and `#[impl_generics]` all act on a *generated trait definition*, which a provider impl does not have, -so they belong to [`#[cgp_fn]`](./cgp_fn.md) and — for `#[extend]` — +so they belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to [`#[cgp_component]`](./cgp_component.md). Writing one here leaves a name nothing resolves; see [Gotchas](#gotchas). An impl-side bound that really is impl-side goes in the block's own `where` clause, which passes through untouched. @@ -127,8 +184,8 @@ clause, which passes through untouched. Naming `Self` as the provider bypasses the rewrite entirely and emits the block unchanged as an ordinary consumer-trait impl on a concrete type. This form requires the `for Context` clause, and it is -useful when you want a hand-written impl while still applying the companion attributes. Because no -provider struct is generated, `new` and the component override have no effect. +useful when you want a hand-written impl while still applying the companion attributes. Because the +macro does not generate a provider struct here, `new` and the component override have no effect. ```rust #[cgp_impl(Self)] @@ -189,36 +246,40 @@ fn print_area(rect: &Rectangle) { that call for something else are narrower than they look. Prefer the unqualified header `impl AreaCalculator`, with no `for Context`, and let the macro insert -the context parameter. That is what makes a provider read like an ordinary trait impl. Name the context -explicitly — `impl AreaCalculator for Context` — only when you actually need to say something -about it that the sugar cannot express, such as a lifetime or a higher-ranked bound. +the context parameter. This keeps a provider reading like an ordinary trait impl. Name the context +explicitly, as in `impl AreaCalculator for Context`, only when you actually need to say +something about it that the sugar cannot express, such as a lifetime or a higher-ranked bound. -That named context may be a *concrete* type rather than a parameter — `impl AreaCalculator for Rectangle` -— which writes a provider serving only that one context. Keep it distinct from the +That named context may be a *concrete* type rather than a parameter, as in +`impl AreaCalculator for Rectangle`, which writes a provider serving only that one context. Keep it +distinct from the [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which looks similar and does something else: this one still produces a named provider that a context wires like any other, and that one produces no provider at all. -Reach for something else in three cases. +Reach for something else in two cases. -- **The provider struct has to be declared separately.** [`#[cgp_provider]`](./cgp_provider.md) is the - raw form for that case, and `new` is what you drop: a struct carrying a default generic parameter, - such as `pub struct IterSum(PhantomData);`, cannot be declared by the - attribute, and neither can one shared by several impls. Write the struct, then annotate each impl. - **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain function with no component, no provider, and no wiring. - **You want to implement the consumer trait directly on one concrete type.** Use the [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which keeps the companion attributes while emitting an ordinary impl. +A struct that `new` cannot declare, or one [shared by several +`#[cgp_impl]` blocks](#declaring-the-provider-struct-separately), is not by itself a reason to drop to +[`#[cgp_provider]`](./cgp_provider.md): declare the struct yourself and keep writing every block with +`#[cgp_impl(ProviderName)]`, just without `new`. Reach for the raw form only when you need the +inside-out provider-trait shape itself: a bound the sugar cannot express, or a rare construct +`#[cgp_impl]`'s rewrite does not support, whether from a limitation or a bug. + ## Under the hood :::note ### Advanced -This section shows what the macro generates. You do not need it to write a provider, but the rewrite is -worth seeing once — most confusing errors in a provider body are explained by it. `cargo cgp expand` +This section shows what the macro generates. You do not need it to write a provider, but the rewrite +explains most confusing errors in a provider body, so it is worth seeing once. `cargo cgp expand` prints the same thing for your own code. ::: @@ -236,7 +297,7 @@ impl FooProvider for Context { } ``` -the macro produces the provider impl, an `IsProviderFor` impl, and — because `new` was given — the +the macro produces the provider impl, an `IsProviderFor` impl, and, because `new` was given, the provider struct: ```rust @@ -251,8 +312,8 @@ impl IsProviderFor for ValueToString pub struct ValueToString; ``` -Three things changed. The trait gained `Context` as its leading argument; the `Self` type became the -provider; and `&self` became the explicit parameter `__context__: &Context`. The receiver identifier is +Three things changed. The trait gained `Context` as its leading argument. The `Self` type became the +provider. `&self` became the explicit parameter `__context__: &Context`. The receiver identifier is the snake-cased context type wrapped in double underscores, so both `Context` and the default `__Context__` become `__context__`. Every `self` in a body is rewritten to that identifier, and every `Self` to the context type. @@ -273,21 +334,21 @@ where ``` The generated `IsProviderFor` impl copies the provider impl's signature, drops the body, and keeps the -`where` clause — which is how the provider's dependencies are captured for error reporting. Its +`where` clause. This is how the provider's dependencies are captured for error reporting. Its arguments are the component name, the context, and a tuple of any remaining provider-trait parameters, so a provider for `ComputerRef` gets `IsProviderFor`. **An associated type the block declares is exempt.** `Self::Output` in a provider that supplies `type Output` is left alone, because the macro gathers the block's own associated-type names first and -skips any `Self::` path starting with one. That is what it has to do: in the emitted impl `Self` is the -provider struct, which is the type that declares `Output`, so the path resolves as written. Every -other `Self` in the block is still rewritten — including one naming an abstract type the *context* -supplies. Associated consts are not covered by the exemption; see [Gotchas](#gotchas). - -**The rewrite is scoped to the block's own method bodies.** An item nested *inside* a body — a local -`struct` with its own impl, a helper `fn`, an inline `trait` — introduces a fresh `self`/`Self` that -belongs to that item, exactly as in ordinary Rust, and the macro leaves it alone. Closures, which +skips any `Self::` path starting with one. In the emitted impl, `Self` is the provider struct, which is +the type that declares `Output`, so the path resolves as written. Every other `Self` in the block is +still rewritten, including one naming an abstract type the *context* supplies. Associated consts are +not covered by the exemption; see [Gotchas](#gotchas). + +**The rewrite is scoped to the block's own method bodies.** An item nested *inside* a body, such as a +local `struct` with its own impl, a helper `fn`, or an inline `trait`, introduces a fresh `self`/`Self` +that belongs to that item, exactly as in ordinary Rust, and the macro leaves it alone. Closures, which capture the enclosing `self`, are rewritten like any other expression.

@@ -328,16 +389,16 @@ Name it through the provider trait instead, which the rewrite turns into the cor >::LIMIT ``` -The consumer side is unaffected — a wired context reads the same const as `::LIMIT`. +The consumer side is unaffected: a wired context reads the same const as `::LIMIT`. **One nesting case escapes the scoping rule.** An item written inside a `macro!( … )` invocation has its `self`/`Self` rewritten too, because a token-level rewrite cannot see the scope the macro will -eventually create. A `self::` *module* path inside a macro invocation is safe: the trailing `::` is -what tells the two meanings of `self` apart, and only the value form is rewritten. +eventually create. A `self::` *module* path inside a macro invocation is safe: the trailing `::` +distinguishes the two meanings of `self`, and only the value form is rewritten. **A misplaced companion attribute is reported by the compiler, not by the macro.** An attribute -`#[cgp_impl]` does not recognize is re-attached to the generated provider impl — which is what lets -`#[allow(...)]` ride through — so a stray `#[extend(HasName)]` produces a *cannot find attribute* +`#[cgp_impl]` does not recognize is re-attached to the generated provider impl, which lets +`#[allow(...)]` ride through. A stray `#[extend(HasName)]` therefore produces a *cannot find attribute* resolution error pointing at the impl, with no mention of `#[cgp_impl]`. ## Related constructs diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 0fd9829b..689aaf65 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -37,7 +37,7 @@ One structural point saves confusion later: **a namespace is not a context.** It the namespace — carrying a `Delegate` associated type and implemented once per key. Nothing instantiates it, and it holds no wiring of its own at the context level; it only says where a lookup should go next. -## Using it +## Usage The body resembles a [`delegate_components!`](./delegate_components.md) table with an optional header. The `new` keyword tells the macro to emit the namespace's trait and its backing struct: diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index a251d136..10da9c2e 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -21,16 +21,16 @@ fn magic_number() -> u64 { ``` That produces the provider struct `MagicNumber` and an impl of [`Producer`](../components/producer.md), the -family member whose method takes only a **context** — the type the capability runs against — and a phantom +family member whose method takes only a **context** (the type the capability runs against) and a phantom `Code` tag, with no input value at all. -The reason it is worth a macro of its own is what happens next. **A producer can stand in for any handler**, +Here is what makes a dedicated macro worth having. **A producer can stand in for any handler**, because a handler that ignores its input is just a producer with an unused parameter. So the macro wires the generated provider into every member of the family, and one function definition answers `produce`, -`compute`, `try_compute`, `compute_async`, `handle`, and their by-reference forms — every one of them +`compute`, `try_compute`, `compute_async`, `handle`, and their by-reference forms, every one of them yielding the same value regardless of what it is handed. -## Using it +## Usage Apply the attribute to a free function. It takes an optional provider name: @@ -46,7 +46,7 @@ fn magic_number() -> u64 { } ``` -Omitted, the provider struct takes the function name in PascalCase — `magic_number` becomes `MagicNumber`. +Omitted, the provider struct takes the function name in PascalCase: `magic_number` becomes `MagicNumber`. Given, the argument is used verbatim. The function's return type becomes the producer's output. **The function is constrained tightly, to exactly what a producer can be.** All three restrictions are @@ -92,7 +92,7 @@ delegate_components! { ``` The computer and handler forms accept an input argument and discard it, since the underlying producer takes -none. The error type wired into `App` is what lets the fallible forms build their `Result`; the produced +none. The error type wired into `App` lets the fallible forms build their `Result`; the produced value is always `Ok`. The typical use is as the first step of a pipeline, where a producer seeds the value the later steps @@ -119,7 +119,7 @@ within it there is nothing simpler. same macro with the restrictions lifted, and it handles generics, `async`, and `Result` returns. - **Write the provider by hand with [`#[cgp_impl]`](./cgp_impl.md) when the value comes from the context.** This is the boundary that matters. A `#[cgp_producer]` function has no receiver, so it cannot read a field, - name an abstract type, or call a capability — it can only return something it computes from nothing. A + name an abstract type, or call a capability. It can only return something it computes from nothing. A producer that draws on its context is an impl of `Producer` written with `#[cgp_impl]`, where `self` is the context and [`#[implicit]`](../attributes/implicit.md) works normally. **In practice that covers most producers**, which makes this macro narrower than it first looks: it is for constants and pure seeds. @@ -135,7 +135,7 @@ within it there is nothing simpler. ### Advanced This section shows the three items the macro emits. You do not need them to use `#[cgp_producer]`, but the -delegation block is what makes one function answer eight components, and it differs from +delegation block makes one function answer eight components, and it differs from [`#[cgp_computer]`](./cgp_computer.md)'s in a way worth noticing. `cargo cgp expand` prints the same thing for your own code. @@ -189,15 +189,15 @@ delegate_components! { ``` Two things differ from `#[cgp_computer]`'s block. `ComputerComponent` **is** in the list, because a producer -does not implement it directly — a computer takes an input and the producer has none, so the promotion is -what discards it. And the operator is **`:`** rather than `->`, delegating each component straight to +does not implement it directly. A computer takes an input and the producer has none, so the promotion +discards it. And the operator is **`:`** rather than `->`, delegating each component straight to [`PromoteProducer`](../providers/handler_combinators.md) rather than to that bundle's own entry for the key. `PromoteProducer` then wires `ComputerComponent` to a promoter that drops the input and calls `produce`, and derives the remaining members from there. **Unlike `#[cgp_computer]`, the expansion has no variation.** Because the function cannot be async, cannot be generic, and is not inspected for a `Result` return, there is exactly one base trait and one bundle for every -`#[cgp_producer]` — the output type is taken as written, whether or not it happens to be a `Result`. +`#[cgp_producer]`: the output type is taken as written, whether or not it happens to be a `Result`.
Formal grammar @@ -212,8 +212,8 @@ ProviderName -> IDENTIFIER ``` Omitted, the provider struct takes the function name converted to PascalCase; a given `IDENTIFIER` is used -verbatim. The annotated function is plain Rust, constrained to a producer's shape — no parameters, no -`async`, no generics — as described in [Using it](#using-it). +verbatim. The annotated function is plain Rust, constrained to a producer's shape (no parameters, no +`async`, no generics), as described in [Usage](#usage).
@@ -228,7 +228,7 @@ error: Producer functions must have empty generic parameters ``` For the first two, [`#[cgp_computer]`](./cgp_computer.md) is the macro that accepts them. For the third there -is no macro alternative — write the provider by hand. +is no macro alternative: write the provider by hand. **The function cannot reach the context**, so a producer that needs a field or an abstract type is not expressible this way at all. That rules out most real producers, which is worth knowing before reaching for @@ -236,7 +236,7 @@ the macro: write an impl of `Producer` with [`#[cgp_impl]`](./cgp_impl.md) inste **A `Result` return is not interpreted**, and this is the sharpest trap on the page. Unlike `#[cgp_computer]`, the macro does not inspect the output for fallibility, so a `#[cgp_producer]` returning -`Result` produces a `Producer` whose `Output` *is* that `Result` — and the fallible members wrap it +`Result` produces a `Producer` whose `Output` *is* that `Result`, and the fallible members wrap it again rather than treating it as failure: ```text @@ -251,7 +251,7 @@ instead. **The fallible forms still need an error type on the context.** `try_compute` and `handle` name the context's abstract error, so a context lacking an [`ErrorTypeProviderComponent`](../components/has_error_type.md) fails on those members while `produce` and -`compute` work. Note also that the wiring key is **not in the prelude** — it has to be imported from +`compute` work. Note also that the wiring key is **not in the prelude**: it has to be imported from `cgp::core::error`, and forgetting that reports the component as an unresolved type rather than as a missing import. diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 61f72f5f..28830522 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -4,15 +4,15 @@ sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' # `#[cgp_provider]` & `#[cgp_new_provider]` -Implement a provider trait directly, in the inside-out shape the sugar desugars to — with or without +Implement a provider trait directly, in the inside-out shape the sugar desugars to, with or without declaring the provider struct. ## Overview A provider trait is not shaped like the trait it came from. [`#[cgp_component]`](./cgp_component.md) -moves the original `Self` into an explicit leading type parameter for the **context** — the type the -capability runs against, which supplies the values it needs as its fields — and an implementation -targets a small named struct instead. Written out, a provider looks like this: +moves the original `Self` into an explicit leading type parameter for the **context**. The context is +the type the capability runs against, and it supplies the values it needs as its own fields. An +implementation targets a small named struct instead. Written out, a provider looks like this: ```rust impl AreaCalculator for RectangleArea @@ -28,21 +28,21 @@ where That impl is correct on its own but incomplete. CGP requires a provider to *also* implement a marker trait under exactly the same conditions, so that a context missing something the provider needs gets an error naming the missing thing rather than a bare "trait not implemented". Written by hand, that means -duplicating the generics and the whole `where` clause, and keeping the two copies in step forever. +duplicating the generics and the whole `where` clause, and keeping the two copies synchronized forever. `#[cgp_provider]` writes the second impl for you. You write only the real one, and the macro derives -its companion from it — same generics, same bounds, body stripped. The dependencies cannot drift out +its companion from it: same generics, same bounds, body stripped. The dependencies cannot drift out of sync, because they are read off the impl rather than restated. `#[cgp_new_provider]` is the same macro with one addition: it also declares `pub struct RectangleArea;`, so a provider that does not exist yet can be introduced in one block. **Neither is the form to write for a new provider.** [`#[cgp_impl]`](./cgp_impl.md) expresses the same -implementation in the consumer trait's shape — keeping `self`, `Self`, and the original signatures — -and desugars to exactly these two macros. Read this page to understand generated code and the narrow -cases the sugar cannot reach; write `#[cgp_impl]` the rest of the time. +implementation in the consumer trait's shape, keeping `self`, `Self`, and the original signatures, and +desugars to exactly these two macros. Read this page to understand generated code and the narrow cases +the sugar cannot reach; write `#[cgp_impl]` the rest of the time. -## Using it +## Usage Apply the attribute to an `impl` block that implements a provider trait for a provider struct. The impl is ordinary Rust: the trait carries the context as its leading type argument, the `Self` type is the @@ -100,14 +100,14 @@ pub struct SpawnAndRun(pub ::core::marker::PhantomData); ``` This is also the limit of what the attribute form can express, and the reason `#[cgp_provider]` still -has a job: a struct that needs a **default** generic parameter — the common -`pub struct IterSum(PhantomData);` shape a higher-order provider uses so it -can fall back to the context's own wiring — has to be written by hand, and so does one shared by -several impls. +has a job. A struct that needs a **default** generic parameter has to be written by hand, and so does +one shared by several impls. The common shape is +`pub struct IterSum(PhantomData);`, which a higher-order provider uses so it +can fall back to the context's own wiring. ## Examples -A complete provider with its struct declared separately, which is what `#[cgp_provider]` is for: +A complete provider with its struct declared separately, the case `#[cgp_provider]` handles: ```rust use cgp::prelude::*; @@ -136,8 +136,8 @@ where } ``` -A context wires it exactly as it would any provider, and the derived marker impl is what makes a -missing `width` field report itself as a missing field: +A context wires it exactly as it would any provider. The derived marker impl makes a missing `width` +field report itself as a missing field: ```rust #[derive(HasField)] @@ -167,7 +167,7 @@ where } ``` -And the same provider once more, in the form to actually write — where the context parameter is +And the same provider once more, in the form to actually write, where the context parameter is inserted for you and the body keeps `self`: ```rust @@ -186,27 +186,28 @@ the source. ## When to reach for it, and when not **Write [`#[cgp_impl]`](./cgp_impl.md) instead, by default.** It produces the identical output from -source that reads like an ordinary trait impl, which is why it is the recommended form and these two -are mostly what you *read* — in generated code, in a desugaring, and in CGP's own crates. - -Three cases genuinely call for the raw form. - -- **The struct cannot be declared by an attribute.** A default generic parameter, as in - `pub struct IterSum(PhantomData);`, or a struct several impls share. Write - the struct, then annotate each impl with `#[cgp_provider]`. +source that reads like an ordinary trait impl, so it is the recommended form. You mostly *read* these +two instead: in generated code, in a desugaring, and in CGP's own crates. + +Two cases genuinely call for writing the raw form yourself. + +- **You need the inside-out provider-trait shape itself**, not merely a separately-declared struct: a + bound `#[cgp_impl]`'s sugar cannot express, or a rare construct its rewrite does not support, whether + from a limitation or a bug. This is uncommon. Most bounds that look like they need the raw form are + expressible in `#[cgp_impl]`'s explicit-context form instead (`impl AreaCalculator for + Context`), which reaches a higher-ranked bound such as `for<'a> &'a Context: IntoIterator` and pins + the provider to a single concrete context with `impl AreaCalculator for Rectangle` alike. A struct + that `new` cannot declare, such as one carrying a default generic parameter + (`pub struct IterSum(PhantomData);`) or one shared by several impls, is + *not* by itself a reason to write the raw form: declare the struct yourself and keep writing the body + with `#[cgp_impl(ProviderName)]`, just without `new`. - **Reading, rather than writing.** A confusing provider error names types from this shape, and - `cargo cgp expand` prints it. Recognizing the form is most of what this page is for. - -**That first reason is narrower than it may seem, and it is worth saying what is *not* on the list.** -`#[cgp_impl]`'s explicit form — `impl AreaCalculator for Context` — reaches further than the -unqualified one, and covers cases that look like they would need the raw impl: a higher-ranked bound such -as `for<'a> &'a Context: IntoIterator` is expressible there, and so is pinning the provider to a single -concrete context with `impl AreaCalculator for Rectangle`. So the bound you want is very likely writable -in `#[cgp_impl]`; reach for `#[cgp_provider]` when the *struct* is the problem, not the bound. + `cargo cgp expand` prints it. Recognizing the form is the main reason to read this page. -Between the two macros the choice is mechanical: `#[cgp_new_provider]` when the provider is new, -`#[cgp_provider]` when the struct already exists. There is no other difference, and using the wrong one -is a duplicate-definition error rather than anything subtle. +Once you are genuinely writing the raw form, the choice between the two macros here is mechanical: +`#[cgp_new_provider]` when the provider struct is new, `#[cgp_provider]` when it already exists. There +is no other difference, and using the wrong one is a duplicate-definition error rather than anything +subtle. ## Under the hood @@ -249,26 +250,26 @@ where The derived impl is your impl with the body and associated types removed and the trait swapped. It keeps the same generic parameters and the same bounds, so it holds under precisely the conditions the -real impl holds — which is the whole point, since -[`IsProviderFor`](../traits/is_provider_for.md) is what a check evaluates to find out *why* a provider -does not apply. +real impl holds. This is the whole point: a check evaluates +[`IsProviderFor`](../traits/is_provider_for.md) to find out *why* a provider does not apply. -Its three trait arguments are assembled from the provider trait's own. The first is the **component** -(`ComputerRefComponent`, the default derived from the trait name, or whatever the attribute argument -said). The second is the **context**. The third is a **tuple of everything left over** — `(Code, Input)` -here, and the empty `()` for a provider trait that takes nothing but a context. +The macro assembles its three trait arguments from the provider trait's own. The first is the +**component** (`ComputerRefComponent`, the default derived from the trait name, or whatever the +attribute argument said). The second is the **context**. The third is a **tuple of everything left +over**: `(Code, Input)` here, and the empty `()` for a provider trait that takes nothing but a +context. Two rules decide that split, and they only become visible on a provider trait that carries a [lifetime](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html). The context is the first *type* argument rather than the first argument, because Rust puts lifetime arguments first and a -lifetime cannot be a context. And a lifetime is lifted into [`Life<'a>`](../types/life.md) to occupy -its slot in the tuple, which holds types. A provider for `ReferenceGetter<'a, Context, T>` therefore +lifetime cannot be a context. And the macro lifts a lifetime into [`Life<'a>`](../types/life.md) to +occupy its slot in the tuple, which holds types. A provider for `ReferenceGetter<'a, Context, T>` therefore derives `IsProviderFor, T)>`, keeping the order the arguments were written in. -**One bound is rewritten rather than copied**, and it is the mechanism that makes a nested provider -stack diagnosable. A bound naming *this component's provider trait* — the inner-provider bound of a -[higher-order provider](../attributes/use_provider.md) — gains its marker counterpart alongside it: +**The macro rewrites one bound instead of copying it**, and this is the mechanism that makes a nested +provider stack diagnosable. A bound naming *this component's provider trait*, the inner-provider bound +of a [higher-order provider](../attributes/use_provider.md), gains its marker counterpart alongside it: ```rust #[cgp_new_provider] @@ -289,23 +290,22 @@ where {} ``` -That added bound is what carries a requirement from the *inner* provider outward through the wrapper, -so a field missing three layers down still reaches the context where the component is checked. Bounds -of any other kind — an ordinary `Context: Clone`, a consumer-trait bound such as -`Context: CanPerimeter` — are copied verbatim, without a counterpart. +That added bound carries a requirement from the *inner* provider outward through the wrapper, so a +field missing three layers down still reaches the context where the component is checked. The macro +copies bounds of any other kind, such as an ordinary `Context: Clone` or a consumer-trait bound like +`Context: CanPerimeter`, verbatim, without a counterpart. `#[cgp_new_provider]` emits the same two items plus the struct, whose shape follows the `Self` type as described [above](#the-struct-cgp_new_provider-declares). ### Input the macros refuse -Four shapes are rejected at expansion rather than lowered into code that fails later, and both macros -reject the same four. An **inherent impl**, with no trait, has no provider trait to read the component -and context from. A **provider trait with no type argument** leaves nothing to be the context. A -**const argument** in the provider trait's argument list has nowhere to live in the type-only params -tuple — this is about the *trait's* arguments, not about a const generic on the provider struct, which -passes through untouched. And an item that is not an `impl` is refused outright. Each message names -what was missing. +Both macros reject four shapes at expansion, rather than lowering them into code that fails later. An +**inherent impl**, with no trait, has no provider trait to read the component and context from. A +**provider trait with no type argument** leaves nothing to be the context. A **const argument** in the +provider trait's argument list has nowhere to live in the type-only params tuple. This is about the +*trait's* arguments, not about a const generic on the provider struct, which passes through untouched. +And an item that is not an `impl` is refused outright. Each message names what was missing.
Formal grammar @@ -336,27 +336,27 @@ error[E0428]: the name `RectangleArea` is defined multiple times ``` **`new` is not part of this attribute's grammar.** `#[cgp_provider(new RectangleArea)]` does not -declare the struct — it fails to parse, because the argument holds a component type and nothing else. -Which macro you invoke is what decides whether the struct is declared, so use +declare the struct. It fails to parse, because the argument holds a component type and nothing else. +Which macro you invoke decides whether the struct is declared, so use `#[cgp_new_provider]`. The `new` keyword you may have seen belongs to -[`#[cgp_impl]`](./cgp_impl.md#using-it). +[`#[cgp_impl]`](./cgp_impl.md#usage). **A higher-order provider over a lifetime-carrying component loses the inner marker bound.** The -rewrite above finds the context by reading the inner bound's first argument, and on a component with a -lifetime that argument is the lifetime — so no counterpart is built and the bound is copied as-is. The -stack compiles and runs correctly; what is lost is the propagation, so a dependency unmet inside the +rewrite above finds the context by reading the inner bound's first argument. On a component with a +lifetime, that argument is the lifetime, so the macro builds no counterpart and copies the bound as-is. +The stack compiles and runs correctly, but it loses the propagation: a dependency unmet inside the inner provider no longer surfaces at the outer one, and `#[check_providers(...)]` cannot say which layer of such a stack is at fault. Components without lifetime parameters are unaffected. -**The component argument is not checked against the trait.** Passing a component that does not belong -to the provider trait you are implementing produces a marker impl for the wrong key, so the provider -silently fails to satisfy the wiring that names it — the error appears at the wiring site, saying the -provider is not a provider for that component. Omit the argument unless the trait's name genuinely -departs from the `{Trait}Component` convention. +**The macro does not check the component argument against the trait.** Passing a component that does +not belong to the provider trait you are implementing produces a marker impl for the wrong key, so the +provider silently fails to satisfy the wiring that names it. The error appears at the wiring site, +saying the provider is not a provider for that component. Omit the argument unless the trait's name +genuinely departs from the `{Trait}Component` convention. **A provider's own associated const or type still needs qualifying**, though for a different reason than -in [`#[cgp_impl]`](./cgp_impl.md#gotchas). Here `Self` really is the provider and nothing rewrites it — -but the provider struct is also a perfectly good context, so the consumer blanket impl gives it the +in [`#[cgp_impl]`](./cgp_impl.md#gotchas). Here `Self` really is the provider, and nothing rewrites it. +But the provider struct is also a perfectly good context, so the consumer blanket impl gives it the *consumer* trait as well, and both traits declare the item. `Self::LIMIT` is therefore ambiguous rather than missing: @@ -370,7 +370,7 @@ note: candidate #1 is defined in an impl of the trait `RateLimiter` for the type note: candidate #2 is defined in an impl of the trait `CanRateLimit` for the type `__Context__` ``` -Name the provider trait to disambiguate — `>::LIMIT` — which works here +Name the provider trait to disambiguate: `>::LIMIT` works here because `Self` is the provider. The `#[cgp_impl]` form needs `>::LIMIT` instead, since there `Self` is the context. Either way the consumer side is unaffected: a wired context reads `::LIMIT`. diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 08c14b52..b198f952 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -9,18 +9,18 @@ Define an abstract-type component, whose concrete type each context chooses for ## Overview Generic code often has to name a type it should not choose. A fallible operation returns *some* error, a -geometry routine computes in *some* scalar, a storage layer holds *some* connection handle — and code +geometry routine computes in *some* scalar, a storage layer holds *some* connection handle. Code written once for many applications cannot decide which. Rust's answer is an [associated type](https://doc.rust-lang.org/reference/items/associated-items.html): declare `trait HasScalarType { type Scalar; }`, and code written against it says `Self::Scalar` while leaving the actual type open. -An abstract type in CGP is exactly that trait and nothing more exotic. What `#[cgp_type]` adds is the -ability to fill the slot by **wiring** rather than by writing an impl. Without it, giving a context a -concrete scalar means writing a provider by hand — a whole impl whose only content is +An abstract type in CGP is exactly that trait and nothing more exotic. `#[cgp_type]` adds the ability to +fill the slot by **wiring** rather than by writing an impl. Without it, giving a context a +concrete scalar means writing a provider by hand: a whole impl whose only content is `type Scalar = f64;`. Since every abstract-type provider has that same trivial shape, `#[cgp_type]` -generates it once and for all, so a **context** — the type the capability runs against, which supplies -the values and types it needs — names the concrete type directly in its wiring table: +generates it once and for all. A **context** is the type the capability runs against, and it supplies +the values and types it needs. It names the concrete type directly in its wiring table: ```rust delegate_components! { @@ -31,15 +31,15 @@ delegate_components! { ``` That is the payoff: `App` now implements `HasScalarType` with `Scalar = f64`, and no provider was written -anywhere. The arrangement mirrors what [`#[cgp_getter]`](./cgp_getter.md) does for values — one +anywhere. The arrangement mirrors what [`#[cgp_getter]`](./cgp_getter.md) does for values: one general-purpose provider, parameterized by the thing the context wants to supply. Two consequences are worth having early. Because the type is chosen per context, two applications can pick differently from the same generic code. And because the trait is an ordinary Rust trait, a context -can skip the wiring entirely and write `impl HasScalarType for App { type Scalar = f64; }` — barely +can skip the wiring entirely and write `impl HasScalarType for App { type Scalar = f64; }`, barely longer, and the clearest way to see that nothing unusual is happening. -## Using it +## Usage Apply the attribute to a trait containing **exactly one associated type and no methods**: diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 45af85d8..088ac310 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -8,15 +8,15 @@ Assert at compile time that a context can actually use each component it wires. ## Overview -**CGP's wiring is lazy, and this macro is the answer to that.** When -[`delegate_components!`](./delegate_components.md) records that a **context** — the type the capability -runs against, which supplies the values it needs as its fields — delegates a component to some provider, -nothing checks that the provider can do the job. The entry is stored as a type-level fact and believed. -Whether the chosen provider's own requirements hold *for this context* is a separate question, and it is -not asked until something tries to use the component. +**CGP's wiring is lazy, and this macro is the answer to that.** The **context** is the type the +capability runs against, and it supplies the values it needs as its own fields. When +[`delegate_components!`](./delegate_components.md) records that a context delegates a component to some +provider, nothing checks that the provider can do the job. The entry is stored as a type-level fact and +believed. Whether the chosen provider's own requirements hold *for this context* is a separate question, +and it is not asked until something tries to use the component. So a context can look completely wired, compile, and still be broken. Every entry is accepted, the struct -compiles, the module compiles — and then the first call to the capability fails, often in a file far from +compiles, the module compiles. Then the first call to the capability fails, often in a file far from the mistake. `check_components!` forces the question at a line you choose: @@ -33,15 +33,15 @@ That block has no runtime existence. It compiles if `Person` really can use the cannot, at the wiring site rather than wherever the capability first gets called. The second thing it buys is a *readable* failure, and that is the part worth understanding. Asking the -obvious question — "does `Person` implement `CanGreet`?" — makes the compiler report only the last link in +obvious question, "does `Person` implement `CanGreet`?", makes the compiler report only the last link in the chain, typically that some provider does not implement its provider trait, with no word about why. The macro instead routes the assertion through [`CanUseComponent`](../traits/can_use_component.md), which holds only when the context both delegates the component *and* the chosen provider's real bounds are satisfied. Because those bounds ride explicitly on a marker trait, the compiler evaluates them and names the one that -failed — a missing `name` field surfaces as a missing `name` field, not as an opaque "trait not +failed. A missing `name` field surfaces as a missing `name` field, not as an opaque "trait not implemented". -## Using it +## Usage The macro takes one or more check tables. Each is a context type followed by a brace-delimited list of the components to verify on it: @@ -59,7 +59,7 @@ Several tables may appear in one invocation, each with its own context type and ### Components with generic parameters A component taking type parameters needs them supplied, because a check must name something concrete to -verify. Parameters go after a colon — one bare, several as a tuple, mirroring how the provider trait groups +verify. Parameters go after a colon: one bare, several as a tuple, mirroring how the provider trait groups them: ```rust @@ -87,9 +87,9 @@ That is four checks from one entry. A table may also carry a leading `<...>` gen ### Naming the check trait -The macro derives a trait name of the form `__Check{Context}` — `__CheckPerson` — from the **final segment** +The macro derives a trait name of the form `__Check{Context}` (`__CheckPerson`) from the **final segment** of the context's path, so `some_mod::Person` also yields `__CheckPerson`. Override it with -`#[check_trait(Name)]` on the table, which is what you need when two tables in one module would otherwise +`#[check_trait(Name)]` on the table. You need this when two tables in one module would otherwise collide: ```rust @@ -102,7 +102,7 @@ check_components! { ``` Note that [`delegate_and_check_components!`](./delegate_and_check_components.md) derives -`__CanUse{Context}` instead — deliberately different, so both macros can be used once each in one module +`__CanUse{Context}` instead: deliberately different, so both macros can be used once each in one module without a clash. ### Checking each provider instead of the context @@ -124,9 +124,9 @@ check_components! { } ``` -**This is how a broken layer of a nested provider stack is localized**, and it is the main reason to keep +**This localizes a broken layer of a nested provider stack**, and it is the main reason to keep `check_components!` separate from the wiring. A dependency missing only from the outer wrapper fails the -wrapper's line alone, while one missing from the inner provider fails both — so the pattern of failures +wrapper's line alone, while one missing from the inner provider fails both. The pattern of failures tells you which layer to look at. It must list at least one provider, and may appear at most once per table. ## Examples @@ -174,7 +174,7 @@ check_components! { ``` The `delegate_components!` block compiles on its own, because wiring is lazy. The `check_components!` block -does not — and it fails *here*, naming the missing field, rather than at some later `person.greet()` in +does not. It fails *here*, naming the missing field, rather than at some later `person.greet()` in another file. A generic component supplies its parameters, and the bracketed form checks several at once: @@ -196,16 +196,16 @@ This verifies `MyApp: CanCalculateArea` and `MyApp: CanCalculateArea< ## When to reach for it, and when not -**Every context's wiring should be checked somehow.** That is the rule without exceptions; which macro does -it is what scales. +**Every context's wiring should be checked somehow.** That is the rule without exceptions; only the +choice of macro scales with the wiring's complexity. - **Use a standalone `check_components!` for anything past simple wiring.** It is the form advanced codebases keep, because it is the only one with full control: concrete parameters for generic keys, `#[check_providers(...)]` for per-layer checks, and coverage of wiring the fused macro's derivation cannot - read — the `open` statement, `@`-path keys, and [namespaces](./cgp_namespace.md). + read: the `open` statement, `@`-path keys, and [namespaces](./cgp_namespace.md). - **Use [`delegate_and_check_components!`](./delegate_and_check_components.md) while getting started, or for - plain `Component: Provider` tables.** It fuses wiring and checking so the check cannot be forgotten, - which is what a newcomer needs. Its derivation understands only the plain entry form. + plain `Component: Provider` tables.** It fuses wiring and checking so the check cannot be forgotten. A + newcomer needs exactly that. Its derivation understands only the plain entry form. - **Do not check an [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time) as though it were a context.** A `new`-keyword bundle is delegated *to*; it has no fields and never stands in the context position, so a context-side check on it asks the wrong question. Verify it through a real @@ -213,7 +213,7 @@ it is what scales. [Gotchas](#gotchas) show what happens if you try. One limit is worth stating plainly: **not every unsatisfied bound is a component.** A provider may depend on -an ordinary Rust trait, and there is no component to name in a table for that — the check will still surface +an ordinary Rust trait, and there is no component to name in a table for that. The check will still surface the unsatisfied bound, but you cannot ask for it directly. ## Under the hood @@ -256,12 +256,12 @@ delegates the component and that its delegate satisfies [`IsProviderFor`](../tra unmet one is reported specifically rather than as a bare missing implementation. The generic parameters are literally `__Component__` and `__Params__` in the emitted code. -`__Params__` carries a `?Sized` bound, and that is load-bearing rather than defensive: a component's -parameter may be an unsized type, so a table checking a component declared over `str` — -`ReferenceGetterComponent: (Life<'a>, str)` — would be rejected before the assertion was even evaluated +`__Params__` carries a `?Sized` bound, and that is essential rather than defensive: a component's +parameter may be an unsized type, so a table checking a component declared over `str` +(`ReferenceGetterComponent: (Life<'a>, str)`) would be rejected before the assertion was even evaluated without it. -Generic parameters land in the `__Params__` slot — one directly, several as a tuple: +Generic parameters land in the `__Params__` slot: one directly, several as a tuple: ```rust impl __CheckMyApp for MyApp {} @@ -318,7 +318,7 @@ CheckValue -> CheckParam CheckParam -> Generics? Type ``` -One invocation may carry several `CheckTable`s, written one after another with no separator — which is how +One invocation may carry several `CheckTable`s, written one after another with no separator. This is how a module checks two contexts from one block. Both `TableAttr`s are optional, each may appear at most once, and any other attribute is rejected by name rather than ignored. `#[check_trait(...)]` overrides the derived `__Check{Context}` name, and `#[check_providers(...)]` switches the assertion to the listed providers. A @@ -328,8 +328,8 @@ which is merged with the table's before the impl is emitted. `Generics`, `WhereC grammar productions. Both bracketed lists accept **zero** elements, and the two empty forms behave differently. An empty value -list — `FooComponent: []` — falls back to the no-parameter check, exactly as omitting the colon would. An -empty *key* list — `[]: Rectangle` — produces no entries at all, so the line silently checks nothing; there +list, `FooComponent: []`, falls back to the no-parameter check, exactly as omitting the colon would. An +empty *key* list, `[]: Rectangle`, produces no entries at all, so the line silently checks nothing; there is no diagnostic, and it is worth a second look if a table appears to pass without doing anything.
@@ -339,7 +339,7 @@ is no diagnostic, and it is worth a second look if a table appears to pass witho **A check on an aggregate provider asks the wrong question, and how it fails depends on the provider.** A `new`-keyword bundle is not a context, so a context-side check demands that the *bundle* satisfy the leaf provider's dependencies. If that provider has none, the check passes vacuously and proves nothing. If it -needs anything from its context — a field, a type — the check fails, blaming the bundle: +needs anything from its context, such as a field or a type, the check fails, blaming the bundle: ```text error[E0277]: the trait bound `GeometryComponents: CanUseComponent` @@ -353,7 +353,7 @@ Nothing there says the target was never meant to be a context. Wire the bundle w **A component with generic parameters cannot be checked without them, and the error does not say so.** Omitting the value emits a check with an empty parameter tuple, which a component expecting a `Shape` can -never satisfy — so what you get is an ordinary unsatisfied-wiring complaint that never mentions the +never satisfy. You get an ordinary unsatisfied-wiring complaint that never mentions the parameters: ```text @@ -371,7 +371,7 @@ error: `#[check_providers(...)]` requires at least one provider type. ``` **Two tables in one module can collide on the derived name.** The name comes from the context's *last* path -segment, so `a::Person` and `b::Person` both derive `__CheckPerson` — and so do two tables for the same +segment, so `a::Person` and `b::Person` both derive `__CheckPerson`, and so do two tables for the same context: ```text @@ -381,7 +381,7 @@ error[E0428]: the name `__CheckPerson` is defined multiple times Use `#[check_trait(...)]` on one of them. **A passing check is not a claim that the capability is correct**, only that it resolves. It proves the -provider was found and its dependencies are satisfiable — not that the provider does what you meant. +provider was found and its dependencies are satisfiable, not that the provider does what you meant. ## Related constructs diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 4c846719..104c3ffa 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -10,8 +10,8 @@ Wire a context and check that wiring in one macro. CGP's wiring is [lazy](./delegate_components.md#gotchas): a [`delegate_components!`](./delegate_components.md) entry is accepted without verifying that the provider it -names can actually satisfy the component, so a **context** — the type the capability runs against, which -supplies the values it needs as its fields — can compile while being broken. The fix is a +names can actually satisfy the component, so a **context** (the type the capability runs against, which +supplies the values it needs as its own fields) can compile while being broken. The fix is a [`check_components!`](./check_components.md) block, and the problem with the fix is that keeping it in step with the wiring is manual. Add a delegation, remember to add its check. @@ -26,19 +26,19 @@ delegate_and_check_components! { } ``` -Every entry is wired *and* proven, in one place, with nothing to keep in sync. What it emits is exactly what +Every entry is wired *and* proven, in one place, with nothing to keep in sync. It emits exactly what writing both macros by hand would emit. **It is aimed at simple wiring and at getting started, not at being the default everywhere.** Its value is that a newcomer cannot forget the check and then meet the confusing errors lazy wiring produces. The derivation understands only a mapping keyed on a component *name*, though, so a codebase whose wiring grows -past that keeps the two macros separate — the reasons are in +past that keeps the two macros separate. The reasons are in [When to reach for it](#when-to-reach-for-it-and-when-not). -## Using it +## Usage -The macro takes the same table shape as [`delegate_components!`](./delegate_components.md) — an optional -generic list and `new` keyword, a target type, and brace-delimited `Key: Value` entries — plus a few +The macro takes the same table shape as [`delegate_components!`](./delegate_components.md): an optional +generic list and `new` keyword, a target type, and brace-delimited `Key: Value` entries, plus a few attributes governing the checking half: ```rust @@ -54,7 +54,7 @@ works". ### Naming the check trait -The derived trait is named `__CanUse{Context}` — `__CanUseScaledRectangle`. That deliberately differs from +The derived trait is named `__CanUse{Context}` (`__CanUseScaledRectangle`). That deliberately differs from the `__Check{Context}` name [`check_components!`](./check_components.md) derives, so both macros can be used once each in the same module without colliding. Override it with a table-level `#[check_trait(Name)]`: @@ -70,8 +70,8 @@ delegate_and_check_components! { ### Components with generic parameters A component with type parameters needs `#[check_params(...)]` on its entry. The delegation half does not -need them — its impl is generic over them — but the check half must name something concrete, and the macro -cannot infer what from the delegation alone: +need them, because its impl is generic over them, but the check half must name something concrete, and the +macro cannot infer what from the delegation alone: ```rust delegate_and_check_components! { @@ -139,15 +139,15 @@ error: cannot combine #[skip_check] with #[check_params] ### Two forms that quietly check nothing An **empty** `#[check_params()]` has no parameters to iterate over, so it skips the entry exactly as -`#[skip_check]` would, without saying so. Write `#[skip_check]` when that is what you mean. +`#[skip_check]` would, without saying so. Write `#[skip_check]` to say so directly. A key carrying **only generics** is the opposite case and is easy to assume away: it *is* still checked, with its generics bound on the check impl and unit parameters. ` FooKey: FooProvider` derives -`impl __CanUseContext, ()> for Context {}`, which is what keeps `I` from appearing unbound. +`impl __CanUseContext, ()> for Context {}`, which keeps `I` from appearing unbound. ### What is wired, and what is checked -**The wiring half accepts every form [`delegate_components!`](./delegate_components.md) accepts** — all +**The wiring half accepts every form [`delegate_components!`](./delegate_components.md) accepts**: all three operators, all three key forms including grouped `@`-paths, per-key generics, nested table values, and the `open`, `namespace`, and `for` statements. Read that page for the grammar; the delegation is literally the same evaluation. @@ -166,7 +166,7 @@ literally the same evaluation. Nothing warns about the rows that are not checked: the block compiles, the wiring is correct, and those components simply go unverified. That silence is the practical reason to split the macros once a table uses -more than plain entries — a standalone [`check_components!`](./check_components.md) block can name the +more than plain entries. A standalone [`check_components!`](./check_components.md) block can name the concrete parameters an opened component needs and cover what a namespace brought in. Attributes are accepted only where they mean something. `#[check_params(...)]` and `#[skip_check]` attach @@ -175,7 +175,7 @@ rather than read and ignored. ## Examples -The intended use — a straightforward context, wired and proven together: +The intended use is a straightforward context, wired and proven together: ```rust use cgp::prelude::*; @@ -236,7 +236,7 @@ wiring is simple. there are three things it cannot do, and each is a reason a larger codebase writes [`delegate_components!`](./delegate_components.md) and [`check_components!`](./check_components.md) apart: -- **Per-layer checks.** Only a standalone block can use `#[check_providers(...)]`, which is what localizes a +- **Per-layer checks.** Only a standalone block can use `#[check_providers(...)]`, which localizes a broken layer of a nested provider stack. - **Generic-parameter dispatch.** The `open` statement and `@`-path keys wire a provider per type; the derivation cannot tell which concrete types to check, so those entries need a standalone block naming them. @@ -245,8 +245,8 @@ there are three things it cannot do, and each is a reason a larger codebase writ **One case makes this macro wrong rather than merely unnecessary: an [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time).** A `new`-keyword bundle -is a provider other contexts delegate *to*, never a context itself — it has no fields and never stands in the -context position — so the derived context-side check asks a question that does not apply to it. Wire a bundle +is a provider other contexts delegate *to*, never a context itself. It has no fields and never stands in the +context position, so the derived context-side check asks a question that does not apply to it. Wire a bundle with plain `delegate_components!`. The [Gotchas](#gotchas) show what the failure looks like, and why it is easy to misread. @@ -260,7 +260,7 @@ beginner-proof way to guarantee that for simple contexts; the two separate macro ### Advanced This section shows both halves of what the macro emits. You do not need it to use the macro, but seeing that -the output is literally the two macros concatenated is what makes a later move to separate blocks +the output is literally the two macros concatenated makes a later move to separate blocks uneventful. `cargo cgp expand` prints the same thing for your own code. ::: @@ -293,7 +293,7 @@ where {} ``` -and the same pair again for `NameGetterComponent`. Then the checking half — a marker trait aliasing +and the same pair again for `NameGetterComponent`. Then comes the checking half: a marker trait aliasing [`CanUseComponent`](../traits/can_use_component.md), with one empty impl per delegated component: ```rust @@ -307,7 +307,7 @@ impl CheckMyContext for MyContext {} Without the `#[check_trait(...)]` override the trait would be `__CanUseMyContext`. The whole output is identical to a `delegate_components!` block followed by a `check_components!` block whose trait carries the -`__CanUse{Context}` name — which is why moving to separate blocks later changes nothing about what is +`__CanUse{Context}` name. This is why moving to separate blocks later changes nothing about what is checked. A `#[check_params(...)]` entry expands its parameters into the `__Params__` slot, one check impl per listed @@ -318,7 +318,7 @@ impl __CanUseMyApp for MyApp {} impl __CanUseMyApp for MyApp {} ``` -A `#[skip_check]` entry contributes its delegation impls and no check impl — present in the first half, +A `#[skip_check]` entry contributes its delegation impls and no check impl: present in the first half, absent from the second. A generic table threads its generics through both halves, so ` MyContext { … }` yields @@ -393,7 +393,7 @@ check. Add `#[check_params(...)]`, or move the entry to a standalone **An inherited, opened, or redirected component is not covered.** A `namespace` header, an `open` statement, an `@`-path key, and a `=>` redirect are all accepted in the table and all wired, but the -derivation only produces checks for entries keyed on a component name — so a table using any of them is +derivation only produces checks for entries keyed on a component name, so a table using any of them is *partly* checked, with no warning about the rest. The [coverage table above](#what-is-wired-and-what-is-checked) says which is which; add a standalone [`check_components!`](./check_components.md) for the rest. diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index d04fab35..f51ab602 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -10,8 +10,8 @@ Build a context's wiring table, naming the provider that implements each of its [`#[cgp_component]`](./cgp_component.md) separates the trait callers use from the trait implementations target, which leaves one question open: for a given type, *which* implementation -supplies the behavior? `delegate_components!` answers it. You give it a type and a list of entries — -the component name as the key, the chosen provider as the value — and it records that choice on the +supplies the behavior? `delegate_components!` answers it. You give it a type and a list of entries, +the component name as the key and the chosen provider as the value, and it records that choice on the type. ```rust @@ -24,24 +24,24 @@ delegate_components! { The mental model is a **table**: a compact list saying which implementation supplies each capability. It is worth being precise about one thing, because the analogy invites the wrong conclusion. This looks -like an object's method table, but it is resolved entirely at compile time — the keys and values are +like an object's method table, but it is resolved entirely at compile time: the keys and values are types, the lookup happens during trait resolution, and the result monomorphizes to a direct call. There is no table in the compiled program, no dynamic dispatch, and nothing in the binary for a provider you did not choose. The type this table is attached to is a **context**: the type that owns the wiring. Often it is a type -standing for your whole application, whose job is to carry choices rather than data — `struct App;` +standing for your whole application, whose job is to carry choices rather than data. `struct App;` with no fields is a perfectly good context. Sometimes, as above, it is the data type itself. A macro is worth having here because each entry expands to two impls rather than one. Besides the impl that stores the choice, the macro emits a second one that forwards the chosen provider's own -dependencies back through the table — which is what makes a missing transitive requirement produce a -usable error instead of a dead end. [Under the hood](#under-the-hood) shows both. +dependencies back through the table. This makes a missing transitive requirement produce a usable +error instead of a dead end. [Under the hood](#under-the-hood) shows both. -## Using it +## Usage The macro takes a target type and a brace-delimited body. The body holds any number of **statements** -followed by any number of **mappings**, and a mapping is a **key**, an **operator**, and a **value** — +followed by any number of **mappings**, and a mapping is a **key**, an **operator**, and a **value**: three choices you make independently. There are three operators, three key forms, two value forms, and three statements, and this section takes them in that order. @@ -74,7 +74,7 @@ delegate_components! { This is how you build an **aggregate provider**: a zero-sized provider whose only job is to hold a table dispatching each component to a sub-provider, so that other contexts can delegate a whole group -of components to it as one unit. An aggregate provider is a *provider*, not a context — it forwards +of components to it as one unit. An aggregate provider is a *provider*, not a context. It forwards each component's provider trait onward, and no call ever resolves with the bundle in the context position. That is why it must be wired with plain `delegate_components!` and never with [`delegate_and_check_components!`](./delegate_and_check_components.md), whose check asks whether the @@ -103,7 +103,7 @@ operator against any key form; which pairings are actually worth writing is note | `Key -> Table` | **Delegate directly** | whatever `Table`'s own entry for `Key` holds | | `Key => @path` | **Redirect** | wherever the path lands, resolved later | -`:` is what nearly all wiring uses, and the rest of this page's examples assume it unless they say +Nearly all wiring uses `:`, and the rest of this page's examples assume it unless they say otherwise. **`->` is direct delegation.** Instead of naming a provider it forwards the lookup one hop into another @@ -148,7 +148,7 @@ concern more than a per-context one. ### The three key forms -**A single key** is one component name, and may carry generics of its own — ` BazKey: BazProvider` +**A single key** is one component name, and may carry generics of its own: ` BazKey: BazProvider` adds a parameter to just that entry. **A list key** is a bracketed list, expanding to one entry per name so several components share one @@ -166,7 +166,7 @@ delegate_components! { } ``` -Each bracketed element is a full key, so an element may carry its own generics — in +Each bracketed element is a full key, so an element may carry its own generics: in `[BarKey, BazKey]: BarValue` only the second key introduces `T2`. The list is a key form rather than an operator, so `[A, B] -> SomeTable` and `[A, B] => @somewhere` are as legal as `[A, B]: Provider`; the first adopts several of another table's entries at once, the second points @@ -176,17 +176,17 @@ several components at one shared slot. redirect: the per-value slots an `open` statement opens, or the prefixed routes a [namespace](./cgp_namespace.md) registers. `@AreaCalculatorComponent.Rectangle: RectangleArea` stores `RectangleArea` where the `AreaCalculatorComponent` redirect lands when the dispatch type is -`Rectangle`. Segments follow [`Path!`](./path.md)'s convention — a lowercase, non-primitive identifier -becomes a type-level string, anything else names a type — and a segment may carry generics, as in +`Rectangle`. Segments follow [`Path!`](./path.md)'s convention: a lowercase, non-primitive identifier +becomes a type-level string, and anything else names a type. A segment may also carry generics, as in `@SomeComponent.<'a, T> &'a T: SomeProvider`. Two grouping forms fan one path key out into several, and **they are not interchangeable**: - **`[…]` groups alternatives for one segment**, and the path may continue after it. - `@app.[FooComponent, BarComponent].[u64, String]: DummyImpl` writes four entries — the cartesian + `@app.[FooComponent, BarComponent].[u64, String]: DummyImpl` writes four entries: the cartesian product of the two groups. - **`{…}` groups whole remainders**, and ends the path. Its elements may be different lengths and may - nest further groups, which is what lets one entry cover routes of different shapes. + nest further groups, which lets one entry cover routes of different shapes. ```rust delegate_components! { @@ -211,7 +211,7 @@ exists, and it is legacy. :::info -### Legacy — read, don't write +### Legacy: read, don't write Older code dispatches per type by nesting a table inside a [`UseDelegate`](../providers/use_delegate.md) value: @@ -230,7 +230,7 @@ delegate_components! { Three details of the form are easy to miss. The inner braces hold a **full table body**, so an inner table accepts everything an outer one does, nesting included. The **wrapper is not fixed to -`UseDelegate`** — any single-parameter wrapper type is accepted, which is how a component dispatched on +`UseDelegate`**: any single-parameter wrapper type is accepted, which is how a component dispatched on a tuple of parameters gets wired to a matching `UseDelegate2`. And the **inner table's name may carry generics**, which a per-entry generic on the outer key threads into: @@ -249,7 +249,7 @@ One prerequisite is not visible in either snippet: **the component must carry dispatch impl the wrapper resolves through. Leave it off and the table still expands, then fails at the check with an unsatisfied `IsProviderFor` that never mentions the missing attribute. -This still works, and you will meet it — including in CGP's own error and handler +This still works, and you will meet it, including in CGP's own error and handler components, which are defined with `#[derive_delegate]`. The `open` statement below achieves the same dispatch with no separate table type, no wrapper, and nothing added to the component, and is preferred for new code. @@ -323,8 +323,8 @@ only in how many entries a line produces and in what each entry resolves to. ### Attributes -The macro accepts **no attributes** anywhere — not on the table, not on a key, not on a key inside a -`for` loop or a nested table — and rejects any it finds rather than ignoring them. Attribute-driven +The macro accepts **no attributes** anywhere: not on the table, not on a key, and not on a key inside a +`for` loop or a nested table. It rejects any it finds rather than ignoring them. Attribute-driven variants such as `#[check_params(...)]` and `#[skip_check]` belong to [`delegate_and_check_components!`](./delegate_and_check_components.md). @@ -364,7 +364,7 @@ fn print_area(rect: &Rectangle) { } ``` -The payoff is what happens when a second context wants the same capability answered differently. It +The payoff shows up when a second context wants the same capability answered differently. It writes its own provider and its own table entry, and no code that calls `area()` changes: ```rust @@ -388,9 +388,9 @@ delegate_components! { ``` `Rectangle` and `Square` now both implement `CanCalculateArea`, through different providers reading -different fields — and a function generic over `CanCalculateArea` serves both without knowing that any -of it happened. Each context's choice stays one greppable line, which is the whole of what a reader has -to find to know which implementation runs. +different fields. A function generic over `CanCalculateArea` serves both without knowing that any of it +happened. Each context's choice stays one greppable line, which is all a reader needs to find to know +which implementation runs. When one context needs a different provider *per type* rather than one provider outright, it opens the component and fills the slots: @@ -416,16 +416,16 @@ check the wiring**, because CGP's wiring is *lazy*: a table with a missing or wr compiles, and the failure only surfaces later, where the capability is used. - **Pair it with [`check_components!`](./check_components.md)** for anything beyond simple wiring. A - separate check gives you full control over what is asserted — concrete parameters for generic keys, - per-provider layers, and opened or namespaced wiring — which is why larger codebases keep the two + separate check gives you full control over what is asserted: concrete parameters for generic keys, + per-provider layers, and opened or namespaced wiring. This is why larger codebases keep the two macros apart. - **Use [`delegate_and_check_components!`](./delegate_and_check_components.md)** when you are getting started or the wiring is plain `Component: Provider` entries. It fuses the two so the check cannot be forgotten. It accepts this whole grammar, but it derives checks only from mappings keyed on a component *name*, so opened, redirected, and namespaced entries are wired and left unchecked with no warning. -- **Use plain `delegate_components!` with no check** for an **aggregate provider** — the - [`new`-keyword form](#defining-the-target-at-the-same-time). That target is a provider other contexts +- **Use plain `delegate_components!` with no check** for an **aggregate provider** (the + [`new`-keyword form](#defining-the-target-at-the-same-time)). That target is a provider other contexts delegate to rather than a context in its own right, so a context-side check on it asks the wrong question: it either passes vacuously or blames the bundle for requirements a real context would have met. Verify it through a context that delegates to it instead. @@ -433,7 +433,7 @@ compiles, and the failure only surfaces later, where the capability is used. Two choices inside the table are worth naming as well. Prefer the **`open` statement** over the legacy nested `UseDelegate` table for per-type dispatch: it needs no separate table type and no wrapper. And reach for a **[namespace](./cgp_namespace.md)** rather than a longer table once the same wiring is -repeated across contexts, or once one table has grown too long to read — below that threshold, the +repeated across contexts, or once one table has grown too long to read. Below that threshold, the extra hop costs more than it saves. The one thing not to do is leave a context's wiring unchecked. Which macro you use to check it scales @@ -516,7 +516,7 @@ impl DelegateComponent for MyApp { } ``` -which is byte-for-byte what `AreaCalculatorComponent => @AreaCalculatorComponent,` produces. Each +`AreaCalculatorComponent => @AreaCalculatorComponent,` produces this same impl, byte-for-byte. Each `@AreaCalculatorComponent.Rectangle: RectangleArea` entry then stores its provider in that same table under a path key: @@ -532,15 +532,15 @@ impl<__Wildcard__> The [`RedirectLookup`](../providers/redirect_lookup.md) impl appends the dispatch parameter onto the path and reads the result back, so `MyApp: CanCalculateArea` resolves to `RectangleArea`. -The tail of that key is a **generic `__Wildcard__` parameter rather than `Nil`**, and that is what makes -it work: the entry matches any path *beginning* with this component and this dispatch type, whatever the +The tail of that key is a **generic `__Wildcard__` parameter rather than `Nil`**, and this makes it +work: the entry matches any path *beginning* with this component and this dispatch type, whatever the lookup appends after it, so one entry answers the redirect without having to predict the exact length of the path reaching it. One presentational quirk is worth knowing before you compare these listings against your own expansion. Both paths above are [`PathCons`](../types/type_level_spines.md) lists, but `cargo cgp expand` prints -them differently — it resugars the header's redirect target to [`Path!`](./path.md) form while leaving -the per-entry key as the raw spine — so the same kind of type appears in two spellings in one expansion. +them differently: it resugars the header's redirect target to [`Path!`](./path.md) form while leaving +the per-entry key as the raw spine. So the same kind of type appears in two spellings in one expansion. **A grouped path key expands to the cartesian product**, one impl pair per combination, each keyed on a full prefix ending in `__Wildcard__`. So @@ -549,13 +549,13 @@ braced group does the same with whole tails rather than single segments, produci lengths. **A nested-table value lifts its inner table out** into its own definition, wiring the outer entry to -`UseDelegate` over the generated type — so the legacy form is equivalent to writing two separate +`UseDelegate` over the generated type. So the legacy form is equivalent to writing two separate `delegate_components!` blocks, the inner one carrying `new`. Its per-value entries key on the same parameter `open` keys on; the difference is only that they live in a separate table type. **The two namespace statements** share one lowering: an impl generic over a `__Key__` and a `__Value__`, -bounded on the namespace trait with a `Delegate = __Value__` binding, which is what makes the namespace's -answer the context's answer. A bare `namespace DefaultNamespace;` produces the blanket form: +bounded on the namespace trait with a `Delegate = __Value__` binding. This makes the namespace's answer +the context's answer. A bare `namespace DefaultNamespace;` produces the blanket form: ```rust impl<__Key__, __Value__> DelegateComponent<__Key__> for App @@ -628,16 +628,16 @@ more path; a braced group holds alternative whole remainders and terminates the the braced form can nest. Both fan out to the cartesian product with the rest of the path. The three segment productions differ in what they permit, which is why they are named apart. A -`KeySegment` — inside a `PathKey` — may carry its own generic list, and the parameters of every segment -along one path are merged onto that entry's impls. A `PathSegment` — inside a `PathValue`, the -right-hand side of a `=>` — carries none, and admits no groups; it is [`Path!`](./path.md)'s own -production, which is what keeps the two in step. And every `Generics` list on a key is an impl-position -list, so a bound is accepted (` BazKey: BazProvider`) and a parameter *default* is not — +`KeySegment` (inside a `PathKey`) may carry its own generic list, and the parameters of every segment +along one path are merged onto that entry's impls. A `PathSegment` (inside a `PathValue`, the +right-hand side of a `=>`) carries none, and admits no groups. It is [`Path!`](./path.md)'s own +production, which keeps the two in step. And every `Generics` list on a key is an impl-position +list, so a bound is accepted (` BazKey: BazProvider`) and a parameter *default* is not: `` fails with `invalid impl generics syntax`. A `ProviderValue`'s nested-table form carries a full `TableBody`, so an inner table accepts every form an outer one does. An `InnerTable` is an identifier with an optional generic list rather than a full -`TargetType` — a nested table always names a fresh struct the macro declares — and its +`TargetType` (a nested table always names a fresh struct the macro declares), and its `BoundFreeGenerics` is a definition-position list: no bounds, no defaults, and a `const` parameter written as the bare name. Put a bound on the entry's own generics instead. A bound written on the inner table is rejected as `expected ','`, because the value parser tries the nested-table form speculatively @@ -653,7 +653,7 @@ anywhere and rejects any it finds. **Wiring is lazy.** A table with a missing entry, or one naming a provider whose own dependencies are unmet, still compiles. The failure appears later, at the place the capability is used, often as a long error naming types you did not write. This is the single most common source of confusion with CGP, and -the answer is to check the table — see [`check_components!`](./check_components.md) — and to run +the answer is to check the table (see [`check_components!`](./check_components.md)) and to run [`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`, which leads with the root cause for the classes it recognizes. @@ -671,7 +671,7 @@ The caret sits on the component being opened, so the message blames it rather th **`[…]` and `{…}` in a path are not the same group.** A bracketed group holds alternatives for one segment and may be followed by more path; a braced group holds whole tails and ends the path. So `@FooProviderComponent.{String, u32}.bool: DummyFoo` does not parse, and the message says nothing about -groups — it reports the trailing `.bool` sitting where the operator should be: +groups: it reports the trailing `.bool` sitting where the operator should be: ```text error: expected `:` @@ -687,7 +687,7 @@ names an unresolved type rather than anything about wiring. **Two entries claiming one key conflict**, and the compiler reports it as a coherence error rather than as a wiring one. This covers the obvious duplicate, an `open` header colliding with an explicit mapping for the same component, and a generic ` Wrapper` entry overlapping a specific `Wrapper` one. -The same applies to a direct entry for a path a joined namespace itself binds — see +The same applies to a direct entry for a path a joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#gotchas). ## Related constructs diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 7b8379da..e44d7466 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -8,14 +8,14 @@ A type-level path, used by namespaces and redirected lookups. ## Overview -`Path!(@a.B.c)` builds a type-level **route** — a list of segments naming a way through nested wiring tables. +`Path!(@a.B.c)` builds a type-level **route**: a list of segments naming a way through nested wiring tables. Read left to right, each segment narrows a lookup one step: through a namespace, through a prefix, down to a component key. CGP needs such routes because [namespaces](./cgp_namespace.md) resolve lookups by path rather than by bare -component name, which is what lets a whole subtree be rerouted at once and a single inherited entry be shadowed -without disturbing the rest. Written as the underlying spine those routes are unreadable — -`PathCons<…, PathCons<…, Nil>>` nested several deep — so `Path!` lets one be written the way it reads: +component name, which lets a whole subtree be rerouted at once and a single inherited entry be shadowed +without disturbing the rest. Written as the underlying spine, those routes are unreadable +(`PathCons<…, PathCons<…, Nil>>` nested several deep), so `Path!` lets one be written the way it reads: ```rust Path!(@app.error.ErrorRaiserComponent) @@ -28,13 +28,13 @@ It is the path-shaped sibling of CGP's other type-level construction macros. Whe **You will more often write the syntax than the macro.** The same `@`-path form is embedded directly in [`cgp_namespace!`](./cgp_namespace.md) entries, in `#[prefix(...)]` attributes, and in the `@`-path keys of -[`delegate_components!`](./delegate_components.md) — and that is where paths are normally written. The bare +[`delegate_components!`](./delegate_components.md). That is where paths are normally written. The bare macro is for the occasional case where a route needs naming as a type on its own. -## Using it +## Usage -`Path!` takes a single `@`-prefixed path of one or more dot-separated segments. The leading `@` is required — it -is the sigil marking the body as a path rather than a plain type — and at least one segment must follow: +`Path!` takes a single `@`-prefixed path of one or more dot-separated segments. The leading `@` is required, +since it is the sigil marking the body as a path rather than a plain type, and at least one segment must follow: ```rust Path!(@app) @@ -45,13 +45,13 @@ Path!(@app.error.ErrorRaiserComponent) ### How a segment is encoded Each segment is parsed as a type, and **its first character decides how it is treated**. This is the one rule -worth learning, because it is what lets a path mix names and types without any extra syntax: +worth learning, because it lets a path mix names and types without any extra syntax: | The segment | Becomes | |---|---| -| A single lowercase identifier — `app`, `error` | a [`Symbol`](./symbol.md) type-level string | -| A capitalized name — `ErrorRaiserComponent` | that named type | -| A primitive type name — `u32`, `bool`, `str` | that type, *not* a symbol | +| A single lowercase identifier (`app`, `error`) | a [`Symbol`](./symbol.md) type-level string | +| A capitalized name (`ErrorRaiserComponent`) | that named type | +| A primitive type name (`u32`, `bool`, `str`) | that type, *not* a symbol | So lowercase segments read as namespace and prefix names, capitalized ones as component keys or marker types, and the primitive exception keeps `@u32` meaning the type `u32` rather than the string `"u32"`. Mixing is @@ -114,16 +114,16 @@ different things. ## When to reach for it, and when not **Write the `@`-path syntax wherever a namespace or a wiring key asks for a route**, and reach for the bare -`Path!` macro only when a route needs to be a named type on its own — which is rare. +`Path!` macro only when a route needs to be a named type on its own, which is rare. - **Prefer the embedded form.** A namespace entry, a `#[prefix]`, or an `@`-path wiring key is where a route belongs, and each accepts the syntax directly. Naming a `type SomeRoute = Path!(…)` and using it indirectly usually makes the wiring harder to follow rather than easier. -- **Never hand-write the spine.** `PathCons>` is what the macro expands to, +- **Never hand-write the spine.** The macro expands to `PathCons>`, and writing it out is longer and identical in meaning. - **Reach for the [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement) rather than constructing paths yourself** when the goal is per-type dispatch on one component. `open` builds - the route for you, and its `@Component.Key` entries are the paths — you write the keys, not the routing. + the route for you, and its `@Component.Key` entries are the paths: you write the keys, not the routing. - **Do not use `Path!` as a general type-level list.** [`Product!`](./product.md) is the list for a sequence of types; `Path!` differs in its segment-classification rule, which exists to serve routing and would be surprising anywhere else. @@ -135,7 +135,7 @@ different things. ### Advanced This section shows the spine the macro builds. You do not need it to use `Path!`, but a namespace failure prints -the expanded path, so recognizing the shape is what lets you read which route came up empty. +the expanded path, so recognizing the shape lets you read which route came up empty. `cargo cgp expand` resugars it back for your own code. ::: @@ -167,18 +167,18 @@ it looks: the `Symbol` is itself a `Chars`/`Nil` chain, so `@app` desugars all t PathCons>>>, Nil> ``` -That is what a raw compiler error prints, and it is the main reason this section is worth reading once. The +A raw compiler error prints exactly that, which is the main reason this section is worth reading once. The segment-classification rule is visible in the result: `@MyComp` gives `PathCons` with no `Symbol` in it, and `@u32` gives `PathCons` rather than treating the primitive as a name. The same fold drives the embedded forms. A [`cgp_namespace!`](./cgp_namespace.md) redirect `FooProviderComponent => @MyFooComponent` produces a `RedirectLookup<__Table__, PathCons>`, and `#[prefix(@show in AppNamespace)]` on a -`CanShow` component produces a `PathCons>` — the prefix +`CanShow` component produces a `PathCons>`: the prefix followed by the component's own key. One presentational note: `cargo cgp expand` resugars a path back to `Path!(@…)` form in most positions, but not -uniformly — an `open` statement's per-entry key comes back as a raw `PathCons` spine while its header's redirect +uniformly. An `open` statement's per-entry key comes back as a raw `PathCons` spine while its header's redirect target is resugared. Seeing the same kind of type in two spellings in one expansion is expected rather than a sign that they differ. @@ -196,9 +196,9 @@ PathSegment -> Type The leading `` `@` `` is required and at least one segment must follow. Each `PathSegment` is parsed as a Rust `Type`, but its encoding is decided semantically: a single lowercase identifier that is not a primitive type name -becomes a `Symbol` type-level string, while every other segment — a capitalized name or a primitive — is kept as -the named type. This same grammar is what [`cgp_namespace!`](./cgp_namespace.md) entries and `#[prefix(...)]` -attributes embed, where it appears as the `Path` production. +becomes a `Symbol` type-level string, while every other segment (a capitalized name or a primitive) is kept as +the named type. [`cgp_namespace!`](./cgp_namespace.md) entries and `#[prefix(...)]` +attributes embed this same grammar, where it appears as the `Path` production.
@@ -210,8 +210,8 @@ attributes embed, where it appears as the `Path` production. error: expected `@` ``` -**Case decides meaning, silently.** `@app` and `@App` are entirely different segments — a type-level string -versus a named type — and both are valid, so a capitalization slip produces a path that compiles and routes +**Case decides meaning, silently.** `@app` and `@App` are entirely different segments (a type-level string +versus a named type), and both are valid, so a capitalization slip produces a path that compiles and routes somewhere else. The failure surfaces later as a lookup that resolves to nothing, with no hint that the cause was a capital letter. @@ -220,7 +220,7 @@ almost always what you want, and it means a path segment cannot be the *string* **A path that routes nowhere still compiles.** A route is just a type; nothing checks that anything is bound at its end. An unbound route is reported only when a [`check_components!`](./check_components.md) evaluates the -lookup, as an unsatisfied bound naming the expanded path — which is why namespace mistakes tend to surface at +lookup, as an unsatisfied bound naming the expanded path. This is why namespace mistakes tend to surface at the check rather than at the definition. ## Related constructs diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index c6082081..01fbf40d 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -9,7 +9,7 @@ A type-level list and its value-level counterpart. ## Overview `Product![A, B, C]` represents an ordered sequence of types as a single type. CGP uses it to describe the -*shape* of a struct — the list of its fields, in order, as one type that generic code can reason about. +*shape* of a struct: the list of its fields, in order, as one type that generic code can reason about. It is sometimes called an anonymous product type, because like a tuple it holds several things at once. The difference from a tuple is the one that matters: a `Product!` is built from a recursive spine that generic code @@ -19,20 +19,20 @@ can take apart **one element at a time**: Product![u32, String, bool] ``` -That recursion is what makes structural, field-by-field operations possible at all. Because a struct's fields +That recursion makes structural, field-by-field operations possible at all. Because a struct's fields are exposed as a single list type through [`HasFields`](../traits/has_fields.md), a provider can be written -once to walk, transform, or rebuild *any* struct's fields without naming the concrete struct — by recursing +once to walk, transform, or rebuild *any* struct's fields without naming the concrete struct, by recursing over the list. A plain tuple cannot be decomposed that way in generic code; the recursive list can. The lowercase `product![a, b, c]` is the value-level half. `Product!` produces a *type* and is used in type -position — associated types, bounds, aliases — while `product!` produces a *value* of the matching type and is +position (associated types, bounds, aliases), while `product!` produces a *value* of the matching type and is used in expression position, mirroring Rust's own split between a struct type and a struct literal. **You mostly read these rather than write them.** A struct's field list is generated by -[`#[derive(HasFields)]`](../derives/derive_has_fields.md); where you write `Product!` by hand is in a handler +[`#[derive(HasFields)]`](../derives/derive_has_fields.md); you write `Product!` by hand in a handler pipeline, listing the steps to run in order. -## Using it +## Usage Both macros take a comma-separated list, which may be empty, and a trailing comma is allowed: @@ -46,7 +46,7 @@ The element lists line up positionally, so the value `product!` builds has exact over the corresponding element types. `Product!` is used wherever a type is expected and `product!` wherever a value is expected. Nothing else about -them varies — there are no options and no attributes. +them varies: there are no options and no attributes. ## Examples @@ -75,7 +75,7 @@ The names are [`Symbol!`](./symbol.md) type-level strings and each entry is a [` the whole `Product!` is a complete type-level description of `Person`'s layout. Generic code walks that list to build or read a `Person` without being written against `Person`. -Where you write `Product!` yourself is a handler pipeline, where the list *is* the program — the steps run +You write `Product!` yourself in a handler pipeline, where the list *is* the program: the steps run left to right: ```rust @@ -103,8 +103,8 @@ let row: Row = product![1, "hi".to_string(), true]; **Write `Product!` when a construct asks for a type-level list**, which in practice means a handler pipeline or a provider list. Everywhere else it is generated for you. -- **Never hand-write the spine.** `Cons>` is what `Product!` expands to, and writing it out is - strictly worse — longer, harder to change, and identical in meaning. The same holds for +- **Never hand-write the spine.** `Product!` expands to `Cons>`, and writing it out is + strictly worse: longer, harder to change, and identical in meaning. The same holds for [`Sum!`](./sum.md)'s spine. - **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for a struct's shape** rather than declaring the list yourself. Writing it by hand means restating the struct, and the two will disagree eventually. @@ -121,8 +121,8 @@ a provider list. Everywhere else it is generated for you. ### Advanced -This section shows the spine both macros build. You do not need it to use them, but the expanded form is what a -compiler error prints, so recognizing it is what makes those errors readable. `cargo cgp expand` resugars it +This section shows the spine both macros build. You do not need it to use them, but a compiler error prints +the expanded form, so recognizing it makes those errors readable. `cargo cgp expand` resugars it back for your own code. ::: @@ -138,7 +138,7 @@ Cons>> ``` Both building blocks are ordinary types. `Cons` is a tuple struct holding the first element and the -rest of the list — `Cons(pub Head, pub Tail)` — and `Nil` is a unit struct terminating it. Chaining +rest of the list (`Cons(pub Head, pub Tail)`), and `Nil` is a unit struct terminating it. Chaining through the tail gives a list of any length, and the empty `Product![]` is simply `Nil`. The macro builds the chain by folding the elements right to left onto `Nil`. @@ -153,8 +153,8 @@ Cons(a, Cons(b, Cons(c, Nil))) ``` Because `Cons` is a real struct and `Nil` a real unit struct, the result is an ordinary owned value whose type -is exactly what `Product!` builds over the same elements' types. There is no magic layer between the two -macros — they are the same fold at two levels. +exactly matches what `Product!` builds over the same elements' types. There is no magic layer between the two +macros: they are the same fold at two levels. **What this means for reading errors**: a mismatched field list is reported as a mismatch between two `Cons` chains, and the position where they diverge is the field that differs. An error mentioning @@ -174,7 +174,7 @@ ProductExpr -> ( Expression ( `,` Expression )* `,`? )? `ProductInput` is the grammar of the type macro `Product!`, used in type position; `ProductExpr` is the grammar of the value macro `product!`, used in expression position. `Type` and `Expression` are the Rust -grammar's productions. Both lists may be empty — `Product![]`, `product![]` — or carry a trailing comma, and +grammar's productions. Both lists may be empty (`Product![]`, `product![]`) or carry a trailing comma, and they line up positionally so a `product!` value has the type the corresponding `Product!` builds.
@@ -182,7 +182,7 @@ they line up positionally so a `product!` value has the type the corresponding ` ## Gotchas **`Product!` and `product!` differ only in case, and the compiler's complaint will not say so.** Using the -type macro in expression position fails inside the macro's own parser, which is expecting a type — so the +type macro in expression position fails inside the macro's own parser, which is expecting a type, so the message is a list of type-position tokens with no hint that the lowercase macro was wanted: ```text @@ -190,7 +190,7 @@ error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime ``` -**A one-element list is not a wrapper.** `Product![T]` is `Cons`, which is a distinct type from `T` — +**A one-element list is not a wrapper.** `Product![T]` is `Cons`, which is a distinct type from `T`, so a pipeline of one step still needs the list, and unwrapping it is a type error rather than a no-op. **The empty list is `Nil`, a real value.** That is the difference from [`Sum!`](./sum.md), whose empty form is @@ -198,7 +198,7 @@ the uninhabited `Void`. An empty record exists; an empty choice cannot. **Element order is part of the type.** `Product![A, B]` and `Product![B, A]` are unrelated types. For a field list this matters less than it sounds, because the entries are name-tagged -[`Field`](../types/field.md)s and the operations that consume them match on names — but for a handler pipeline +[`Field`](../types/field.md)s and the operations that consume them match on names. But for a handler pipeline the order *is* the execution order. ## Related constructs diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index d60d3305..6ae65770 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -9,7 +9,7 @@ A type-level sum, the dual of `Product!`. ## Overview `Sum![A, B, C]` represents a *choice* among several types as a single type. CGP uses it to describe the shape -of an **enum** — the list of its variants — the way [`Product!`](./product.md) describes the fields of a +of an **enum**, the list of its variants, the way [`Product!`](./product.md) describes the fields of a struct. The pairing is exact and worth holding onto. A `Product!` holds a value for **every** element at once, which is @@ -19,10 +19,10 @@ a record. A `Sum!` holds a value for exactly **one** element, which is a tagged Sum![u32, String, bool] ``` -Like its dual it is built from a recursive spine, and that recursion is what makes variant-by-variant +Like its dual it is built from a recursive spine, and that recursion makes variant-by-variant operations possible. Because an enum's variants are exposed as a single sum type through [`HasFields`](../traits/has_fields.md), a provider can be written once to match on, dispatch over, or construct -*any* enum's variants without naming the concrete enum — by walking the nested branches. This is the basis for +*any* enum's variants without naming the concrete enum, by walking the nested branches. This is the basis for CGP's extensible-variant machinery, where each variant is handled by descending the chain rather than by writing a `match` against a fixed enum. @@ -30,7 +30,7 @@ writing a `match` against a fixed enum. [`#[derive(HasFields)]`](../derives/derive_has_fields.md) or the extensible-data derives; the value of knowing the construct is being able to read it in an expansion or an error. -## Using it +## Usage The macro takes a comma-separated list of types, which may be empty, and a trailing comma is allowed. It is used wherever a type is expected: @@ -41,7 +41,7 @@ Sum![] // the empty sum ``` Each listed type is one possible variant, and a value of the sum type carries exactly one of them. There are no -options and no value-level counterpart — unlike [`Product!`](./product.md), which has `product!`, a sum value is +options and no value-level counterpart. Unlike [`Product!`](./product.md), which has `product!`, a sum value is constructed through the variant machinery rather than by a literal. ## Examples @@ -71,7 +71,7 @@ pub enum Shape { ``` Two things to notice. The variant names are [`Symbol!`](./symbol.md) type-level strings, exactly as field names -are. And a struct-like variant nests a [`Product!`](./product.md) of its own fields — so an enum's full shape is +are. And a struct-like variant nests a [`Product!`](./product.md) of its own fields, so an enum's full shape is a sum of variants whose payloads may themselves be records. Generic code walks the `Sum!` to find which variant a value holds, then walks the nested `Product!` to reach that variant's fields. @@ -90,7 +90,7 @@ use. - **Use [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or [`#[derive(HasFields)]`](../derives/derive_has_fields.md) on the enum**, which generates the list from the variants you already declared. Writing it out means restating the enum, and the two will drift. -- **Never hand-write the spine.** `Either>` is what `Sum!` expands to, and writing it out is +- **Never hand-write the spine.** `Sum!` expands to `Either>`, and writing it out is longer and identical in meaning. - **Use [`Product!`](./product.md) for a collection rather than a choice.** They are duals: every element versus exactly one. A type error is the usual consequence of confusing them, which is at least loud. @@ -126,17 +126,17 @@ the rest of the chain. So a value of `Either>>` is `Right(Left(..))` for a `B`, and `Right(Right(Left(..)))` for a `C`. The terminator is `Void`, an **empty enum that can never be constructed**, and choosing it rather than `Nil` is -the load-bearing decision here. Reaching the `Void` position would mean the value matched none of the listed -types, which is impossible — so the type system knows the chain is exhausted. An empty `Sum![]` is therefore +the essential decision here. Reaching the `Void` position would mean the value matched none of the listed +types, which is impossible. So the type system knows the chain is exhausted. An empty `Sum![]` is therefore just `Void`: a type with no values. That is precisely the asymmetry with [`Product!`](./product.md). A product terminates in `Nil` because an empty record is a perfectly good value; a sum terminates in `Void` because an empty choice is *uninhabited*, there being nothing to pick. `Void` functions as the never type, used here to close a sum off. -**Why it matters beyond tidiness**: this is what gives generic variant handling compile-time exhaustiveness +**Why it matters beyond tidiness**: this gives generic variant handling compile-time exhaustiveness without a wildcard arm. As each variant is ruled out, the remaining type shrinks toward `Void`, and code that -has handled every variant is left holding a value that cannot exist — which the compiler accepts discharging +has handled every variant is left holding a value that cannot exist. The compiler accepts discharging it with no fallback case. Add a variant to the enum without handling it, and the remainder becomes inhabited again, so the code stops compiling. The same guarantee a concrete `match` gives, recovered for generic code. @@ -167,8 +167,8 @@ collection. constructing and destructuring like any other. **Variant order is part of the type.** `Sum![A, B]` and `Sum![B, A]` are unrelated. In practice the entries are -name-tagged [`Field`](../types/field.md)s and the operations match on names, so this bites less than it might — -but the *types* are still different, and a cast between two enums works through the name matching rather than +name-tagged [`Field`](../types/field.md)s and the operations match on names, so this bites less than it might. +But the *types* are still different, and a cast between two enums works through the name matching rather than by position. **A derivable enum's variants must each hold exactly one unnamed field.** That is a restriction of the diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index d1c31258..7121856c 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -9,7 +9,7 @@ A type-level string, used as a field-name tag. ## Overview CGP needs field *names* to be types. Reading a field goes through -[`HasField`](../traits/has_field.md), where `Tag` identifies which field is meant — so to look up a field +[`HasField`](../traits/has_field.md), where `Tag` identifies which field is meant. So to look up a field called `name`, something has to stand in for the string `"name"` at the type level. `Symbol!("name")` is that something. It produces a distinct type whose whole identity is the characters it @@ -20,21 +20,21 @@ types. HasField ``` -Encoding a string as a type is what lets field access take part in trait resolution. A **context** — the type -the capability runs against, which supplies the values it needs as its fields — can carry a +Encoding a string as a type lets field access take part in trait resolution. A **context** is the type +the capability runs against, and it supplies the values it needs as its own fields. It can carry a `HasField` impl and a `HasField` impl side by side, and the compiler picks the right one from the tag alone. Nothing is compared at runtime, because there is nothing at runtime: the tag exists only during compilation. **You rarely write it by hand.** [`#[implicit]`](../attributes/implicit.md) arguments, [`#[cgp_auto_getter]`](./cgp_auto_getter.md), and [`#[derive(HasField)]`](../derives/derive_has_field.md) all -generate the tag from a name you already wrote. Where `Symbol!` shows up explicitly is in a wiring entry that -names a field — `UseField` — and where it shows up unavoidably is in compiler errors, -which is the main reason to be able to read it. +generate the tag from a name you already wrote. It shows up explicitly in a wiring entry that names a field, +such as `UseField`, and it shows up unavoidably in compiler errors, which is the main +reason to be able to read it. -## Using it +## Usage -The macro takes a single string literal and is used wherever a type is expected — in trait bounds, in +The macro takes a single string literal and is used wherever a type is expected: in trait bounds, in associated-type positions, and inside a `PhantomData` tag: ```rust @@ -53,14 +53,14 @@ Self: HasField ### The tag for a tuple field A tuple-struct field has no name, so it cannot be keyed by a string. -[`#[derive(HasField)]`](../derives/derive_has_field.md) tags those with [`Index`](../types/index.md) instead — -`Index<0>`, `Index<1>` — which encodes a number at the type level the way `Symbol!` encodes a string. A field +[`#[derive(HasField)]`](../derives/derive_has_field.md) tags those with [`Index`](../types/index.md) instead +(`Index<0>`, `Index<1>`), which encodes a number at the type level the way `Symbol!` encodes a string. A field is keyed by `Symbol!` when it has a name and by `Index` when it has only a position. ### Raw identifiers A field written as a raw identifier is tagged by its *logical* name, with the `r#` stripped: a field `r#type` -is tagged `Symbol!("type")`. The macro itself performs no stripping — it takes the literal verbatim — so +is tagged `Symbol!("type")`. The macro itself performs no stripping. It takes the literal verbatim, so `Symbol!("type")` is the tag that matches, and `Symbol!("r#type")` would be a different tag matching nothing. ## Examples @@ -87,10 +87,10 @@ delegate_components! { } ``` -`Symbol!("first_name")` is what tells [`UseField`](../providers/use_field.md) which field to read. This is the +`Symbol!("first_name")` tells [`UseField`](../providers/use_field.md) which field to read. This is the one place a reader routinely writes the macro themselves. -It also appears in a hand-written field bound, which is what the ergonomic constructs generate for you: +It also appears in a hand-written field bound, the shape the ergonomic constructs generate for you: ```rust #[cgp_impl(new GreetHello)] @@ -105,7 +105,7 @@ where ``` Written idiomatically that provider would use an [`#[implicit]`](../attributes/implicit.md) argument and no -`Symbol!` would be visible at all — which is the point of the ergonomic surface, and why this form is worth +`Symbol!` would be visible at all. That is the point of the ergonomic surface, and why this form is worth recognizing rather than writing. A type-level string can also be turned back into a runtime string, which is occasionally useful for @@ -129,10 +129,10 @@ That is the honest summary: the construct is load-bearing and mostly generated. - **Use [`Index`](../types/index.md) for a tuple field**, not a `Symbol!` of `"0"`. They are different types and the derive generates the former. -Two things it is not. It is **not a runtime string** — there is no `&str` inside it, and the `Display` impl +Two things it is not. It is **not a runtime string**: there is no `&str` inside it, and the `Display` impl above reconstructs the text from the type rather than reading a stored value. And it is **not a general type-level string facility** to build programs out of; it exists to key field and variant lookups, and the -[`StaticFormat`](../traits/static_format.md) traits are what recover text from one when that is genuinely +[`StaticFormat`](../traits/static_format.md) traits recover text from one when that is genuinely needed. ## Under the hood @@ -160,7 +160,7 @@ Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>> Two type constructors do the work. `Chars` is one character paired with the rest of the string; chained through its tail and terminated by `Nil`, it forms a -[type-level list](../types/type_level_spines.md) of characters — the same shape as +[type-level list](../types/type_level_spines.md) of characters, the same shape as [`Product!`](./product.md)'s `Cons`/`Nil` spine, specialized so the head is a `const char` rather than a type. `Symbol` then wraps that list together with a length. @@ -195,7 +195,7 @@ The input is a single string literal, in the Rust Reference's SymbolInput -> STRING_LITERAL ``` -`STRING_LITERAL` is the Rust string-literal token, so any valid string literal is accepted — including the +`STRING_LITERAL` is the Rust string-literal token, so any valid string literal is accepted, including the empty string and multi-byte Unicode. The macro is used in type position, and this single literal is the whole of its input. @@ -204,7 +204,7 @@ of its input. ## Gotchas **The `LEN` in an expanded `Symbol` is bytes, not characters.** For ASCII the two coincide, which is why the -distinction only shows up on non-ASCII field names — where the number will not match the visible character +distinction only shows up on non-ASCII field names, where the number will not match the visible character count and the `Chars` chain will be shorter than `LEN`. **A raw-identifier field is tagged without the `r#`.** `Symbol!("r#type")` and `Symbol!("type")` are different diff --git a/docs/reference/traits/append_product.md b/docs/reference/traits/append_product.md index 0eb79792..c895ecfb 100644 --- a/docs/reference/traits/append_product.md +++ b/docs/reference/traits/append_product.md @@ -39,7 +39,7 @@ the trait solver while the compiler type-checks, so it carries no runtime cost a **This is one of the least user-facing traits in the reference.** You meet it if you write generic code over shapes, and otherwise only in an error message from code that does. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::traits`: diff --git a/docs/reference/traits/build_field.md b/docs/reference/traits/build_field.md index b5769a05..167b2239 100644 --- a/docs/reference/traits/build_field.md +++ b/docs/reference/traits/build_field.md @@ -29,7 +29,7 @@ It pins one transition of the [`UpdateField`](./update_field.md) primitive: `IsN Because it *requires* the starting marker to be `IsNothing`, **building a field that is already set is a compile error**, not a silent overwrite. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/can_build_from.md b/docs/reference/traits/can_build_from.md index 626969c3..97e3e79d 100644 --- a/docs/reference/traits/can_build_from.md +++ b/docs/reference/traits/can_build_from.md @@ -20,7 +20,7 @@ back, so several sources can be absorbed in sequence before the result is finali That is the merge step of the extensible builder pattern: independent parts of a program each produce a record, and the target absorbs all of them without any of them naming it. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::impls`: diff --git a/docs/reference/traits/can_build_with_default.md b/docs/reference/traits/can_build_with_default.md index 7eea1570..baa9022a 100644 --- a/docs/reference/traits/can_build_with_default.md +++ b/docs/reference/traits/can_build_with_default.md @@ -26,7 +26,7 @@ It chains [`builder()`](./has_builder.md), [`build_from`](./can_build_from.md), [`finalize_with_default`](./can_finalize_with_default.md), and it is worth reaching for precisely because those three lines together read as plumbing. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: diff --git a/docs/reference/traits/can_downcast.md b/docs/reference/traits/can_downcast.md index 568fe4db..00316e72 100644 --- a/docs/reference/traits/can_downcast.md +++ b/docs/reference/traits/can_downcast.md @@ -20,7 +20,7 @@ with the compiler tracking, at every step, which variants are still possible. The narrowing counterpart of [`CanUpcast`](./can_upcast.md), which always succeeds because a wider target has a home for everything. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::impls`, with `core::marker::PhantomData` for naming the target: diff --git a/docs/reference/traits/can_downcast_fields.md b/docs/reference/traits/can_downcast_fields.md index 8f27f11c..84ec55f4 100644 --- a/docs/reference/traits/can_downcast_fields.md +++ b/docs/reference/traits/can_downcast_fields.md @@ -19,7 +19,7 @@ it is already given. Since a remainder *is* an extractor, that is exactly the sh **So the pair is the construct, and this half is never used alone.** A chain reads as one `downcast` followed by one `downcast_fields` per additional candidate. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::impls`, alongside `CanDowncast`, which you will always be using with it: diff --git a/docs/reference/traits/can_finalize_with_default.md b/docs/reference/traits/can_finalize_with_default.md index 53888e99..cb4abe6b 100644 --- a/docs/reference/traits/can_finalize_with_default.md +++ b/docs/reference/traits/can_finalize_with_default.md @@ -33,7 +33,7 @@ It is one of two endings for a partial builder, and the choice is made at the ca | `CanFinalizeWithDefault` | filled from `Default` | | [`FinalizeOptional`](./finalize_optional.md) | `Err("field_name")` | -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: diff --git a/docs/reference/traits/can_upcast.md b/docs/reference/traits/can_upcast.md index c44fc040..6dfee7da 100644 --- a/docs/reference/traits/can_upcast.md +++ b/docs/reference/traits/can_upcast.md @@ -21,7 +21,7 @@ type-check at all, so `upcast` returns the target directly rather than a `Result difference between this trait and its narrowing counterpart, [`CanDowncast`](./can_downcast.md). -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::impls`, and bring `core::marker::PhantomData` into scope too, since the target is named with a `PhantomData` argument diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/can_use_component.md index 7f266541..c43d9d9f 100644 --- a/docs/reference/traits/can_use_component.md +++ b/docs/reference/traits/can_use_component.md @@ -42,7 +42,7 @@ evaluate and report them. The error that was hidden becomes visible, at the wiri **You never name this trait.** It is what [`check_components!`](../macros/check_components.md) asserts, and the reason that macro produces a legible error instead of a cascade. -## Using it +## Usage The trait is in the prelude. It is empty, and its entire meaning lives in a single blanket impl: diff --git a/docs/reference/traits/concat_path.md b/docs/reference/traits/concat_path.md index e25c2136..3fc3eae1 100644 --- a/docs/reference/traits/concat_path.md +++ b/docs/reference/traits/concat_path.md @@ -36,7 +36,7 @@ so it names the combined path type and nothing runs. It is the path-level analogue of [`ConcatProduct`](./concat_product.md), with the same two-impl recursion over a different spine. -## Using it +## Usage **`ConcatPath` is in the prelude** — `use cgp::prelude::*;` names it, which makes it the one member of the type-level recovery group that needs no import. Its two neighbours each need a different one: diff --git a/docs/reference/traits/concat_product.md b/docs/reference/traits/concat_product.md index 47df9d51..2bee9772 100644 --- a/docs/reference/traits/concat_product.md +++ b/docs/reference/traits/concat_product.md @@ -35,7 +35,7 @@ the trait solver during type checking, so it costs nothing at run time. It is the general form of [`AppendProduct`](./append_product.md): **append is the single-entry special case of concat**, and that is the shortest way to hold both in mind. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::traits`: diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/contains_value.md index 887ae8c8..53e7bc3c 100644 --- a/docs/reference/traits/contains_value.md +++ b/docs/reference/traits/contains_value.md @@ -43,7 +43,7 @@ back *in*. The other two, [`MonadicBind`](./monadic_bind.md) and **This is a plain capability trait, not a CGP component.** It has no generated provider trait and is never wired. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::monad::traits`: diff --git a/docs/reference/traits/default_impls1.md b/docs/reference/traits/default_impls1.md index 90a4c102..88356b46 100644 --- a/docs/reference/traits/default_impls1.md +++ b/docs/reference/traits/default_impls1.md @@ -46,7 +46,7 @@ out. ::: -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::component`, and you will need to, because the generated impl references the trait by name: diff --git a/docs/reference/traits/default_impls2.md b/docs/reference/traits/default_impls2.md index 724944d8..1b32c704 100644 --- a/docs/reference/traits/default_impls2.md +++ b/docs/reference/traits/default_impls2.md @@ -37,11 +37,11 @@ which is what lets the projection resolve cleanly. This is the widest of the thr **Nothing inside CGP emits or consumes it.** It is reachable and tested, and it is a provided extension point rather than a construct the generated code relies on — so there is no library-generated example to -pattern-match against. The [next section](#using-it) shows what a use looks like. +pattern-match against. The [next section](#usage) shows what a use looks like. ::: -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::component`: diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md index 3284f15f..4ada2a64 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/default_namespace.md @@ -45,7 +45,7 @@ It is the simplest of three lookup traits, keyed on the component alone. **You name it in one place**: the `namespace` header of a wiring block. The macros generate the impls and the forwarding, so this page is mostly about reading what they generate. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough — unlike its two siblings, which are not. diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/delegate_component.md index dadccb5b..683f48bb 100644 --- a/docs/reference/traits/delegate_component.md +++ b/docs/reference/traits/delegate_component.md @@ -44,7 +44,7 @@ component name.** When it is, the entry makes the context inherit the component' is any other type — a shape, a tag, a path segment — the same trait is just a lookup table that a provider walks. One trait covers both, which is why it underlies both ordinary wiring and the inner dispatch tables. -## Using it +## Usage The trait is in the prelude, so `use cgp::prelude::*;` is enough to name it. It carries one associated type and no methods: diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md index 0aab3c3c..1fbbf43e 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/extract_field.md @@ -36,7 +36,7 @@ so the code stops compiling until it is handled. The family is the mirror of the [builder](./has_builder.md): a builder tracks which fields are *present*, an extractor tracks which variants are still *possible*. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/field_getter.md b/docs/reference/traits/field_getter.md index a712c005..a002d80f 100644 --- a/docs/reference/traits/field_getter.md +++ b/docs/reference/traits/field_getter.md @@ -41,7 +41,7 @@ is read from. This is the ordinary consumer/provider duality applied to field ac [`UseField`](../providers/use_field.md) is the provider that implements it by reading a named field, and it is what [`#[cgp_getter]`](../macros/cgp_getter.md) targets. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/field_mapper.md b/docs/reference/traits/field_mapper.md index 3d05a094..faa4d293 100644 --- a/docs/reference/traits/field_mapper.md +++ b/docs/reference/traits/field_mapper.md @@ -44,7 +44,7 @@ pub trait FieldMapper: FieldGetter { **This is the one [`ChainGetters`](../providers/chain_getters.md) actually uses**, because a chained getter is a provider composing other providers rather than a method on a concrete type. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::traits`: diff --git a/docs/reference/traits/finalize_build.md b/docs/reference/traits/finalize_build.md index 4a7f76b4..568ba3db 100644 --- a/docs/reference/traits/finalize_build.md +++ b/docs/reference/traits/finalize_build.md @@ -34,7 +34,7 @@ The destination type comes from its supertrait [`PartialData`](./partial_data.md configuration implements. That division is deliberate: **one names where you are going, the other says you have arrived.** -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/finalize_extract.md b/docs/reference/traits/finalize_extract.md index 90a52091..39f4f194 100644 --- a/docs/reference/traits/finalize_extract.md +++ b/docs/reference/traits/finalize_extract.md @@ -26,7 +26,7 @@ That is what closes a generic match with **no wildcard arm and no `unreachable!( [`FinalizeBuild`](./finalize_build.md), and the two are sound for opposite reasons: a build finalizes because the value is *complete*, an extraction because the value is *impossible*. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/finalize_extract_result.md b/docs/reference/traits/finalize_extract_result.md index 6399ee43..c60a0a43 100644 --- a/docs/reference/traits/finalize_extract_result.md +++ b/docs/reference/traits/finalize_extract_result.md @@ -37,7 +37,7 @@ where 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. -## Using it +## 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 is what closes a chain: diff --git a/docs/reference/traits/finalize_optional.md b/docs/reference/traits/finalize_optional.md index 29fdc66c..bb193120 100644 --- a/docs/reference/traits/finalize_optional.md +++ b/docs/reference/traits/finalize_optional.md @@ -30,7 +30,7 @@ rather than when the builder is created: | `FinalizeOptional` | `Err("field_name")` | | [`CanFinalizeWithDefault`](./can_finalize_with_default.md) | filled from `Default` | -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: diff --git a/docs/reference/traits/from_fields.md b/docs/reference/traits/from_fields.md index abc4f7bc..154f1046 100644 --- a/docs/reference/traits/from_fields.md +++ b/docs/reference/traits/from_fields.md @@ -25,7 +25,7 @@ validate and nothing that can fail. It is an associated function rather than a method, since there is no value to call it on. The call reads `Person::from_fields(fields)`, or `T::from_fields(fields)` in generic code. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md index c14203e3..21e17160 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/from_variant.md @@ -27,7 +27,7 @@ to track — building a single variant has no intermediate states. It is the con [`ExtractField`](./extract_field.md)'s deconstruction, and the impls come from [`#[derive(FromVariant)]`](../derives/derive_from_variant.md), one per variant. -## Using it +## Usage The trait is in the prelude. It carries the payload type as an associated `Value` and one associated function: diff --git a/docs/reference/traits/has_builder.md b/docs/reference/traits/has_builder.md index 82e0ca38..b8f1ee48 100644 --- a/docs/reference/traits/has_builder.md +++ b/docs/reference/traits/has_builder.md @@ -35,7 +35,7 @@ let person = Person::builder() // every fie Delete a middle line and this does not compile. **Field presence lives in the type**, which is the defining idea of the whole family. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/has_extractor.md b/docs/reference/traits/has_extractor.md index 60f29d36..d84883b8 100644 --- a/docs/reference/traits/has_extractor.md +++ b/docs/reference/traits/has_extractor.md @@ -33,7 +33,7 @@ family: | [`HasExtractorRef`](./has_extractor_ref.md) | `&T` | survives | | [`HasExtractorMut`](./has_extractor_mut.md) | `&mut T` | survives, mutably borrowed | -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/has_extractor_mut.md b/docs/reference/traits/has_extractor_mut.md index 96716bda..ce370a98 100644 --- a/docs/reference/traits/has_extractor_mut.md +++ b/docs/reference/traits/has_extractor_mut.md @@ -33,7 +33,7 @@ It is the third of the group, and the one to reach for least often: | [`HasExtractorRef`](./has_extractor_ref.md) | `&T` | survives | | `HasExtractorMut` | `&mut T` | survives, mutably borrowed | -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/has_extractor_ref.md b/docs/reference/traits/has_extractor_ref.md index ea4ae16e..3e5997df 100644 --- a/docs/reference/traits/has_extractor_ref.md +++ b/docs/reference/traits/has_extractor_ref.md @@ -28,7 +28,7 @@ owned one, and the chain ends the same way. It is the weakest of the three accessors, so prefer it wherever it suffices. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/has_field.md index 5193707e..563b0f32 100644 --- a/docs/reference/traits/has_field.md +++ b/docs/reference/traits/has_field.md @@ -30,7 +30,7 @@ method, and a [`UseField`](../providers/use_field.md) wiring entry all generate already wrote. **You will read `HasField` far more often than you write it**, and the impls come from [`#[derive(HasField)]`](../derives/derive_has_field.md). -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/has_field_mut.md b/docs/reference/traits/has_field_mut.md index e652ed80..be204505 100644 --- a/docs/reference/traits/has_field_mut.md +++ b/docs/reference/traits/has_field_mut.md @@ -26,7 +26,7 @@ form gives you the read as well. `HasFieldMut` beside `HasField`, so every derived field is mutably accessible and there is no derive-level way to make one read-only. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/has_fields.md index f5638d78..fea4ee07 100644 --- a/docs/reference/traits/has_fields.md +++ b/docs/reference/traits/has_fields.md @@ -39,7 +39,7 @@ enum it is a [`Sum!`](../macros/sum.md) instead — the same idea for a choice r **The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md).** What you write is the derive; what you bound against is the trait. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method, because describing a type is not an operation — `Fields` is the whole trait. diff --git a/docs/reference/traits/has_fields_ref.md b/docs/reference/traits/has_fields_ref.md index 501f7cd0..00e86e1d 100644 --- a/docs/reference/traits/has_fields_ref.md +++ b/docs/reference/traits/has_fields_ref.md @@ -39,7 +39,7 @@ The two shape traits are independent rather than one extending the other, and th may be described owned, borrowed, or both. What connects the borrowed description to a value is [`ToFieldsRef`](./to_fields_ref.md). -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method — like its owned counterpart, this trait only names a type. diff --git a/docs/reference/traits/has_optional_builder.md b/docs/reference/traits/has_optional_builder.md index d6709ff2..d9c56db4 100644 --- a/docs/reference/traits/has_optional_builder.md +++ b/docs/reference/traits/has_optional_builder.md @@ -31,7 +31,7 @@ like, and the choice of how to end is deferred to the finalize call. It stands to [`HasBuilder`](./has_builder.md) as the optional layer stands to the core one: same machinery, different starting marker. -## Using it +## Usage **It is not in the prelude.** Nothing in the optional-field layer is — import it from `cgp::extra::field::impls`: diff --git a/docs/reference/traits/into_builder.md b/docs/reference/traits/into_builder.md index 1a8576d8..4c144220 100644 --- a/docs/reference/traits/into_builder.md +++ b/docs/reference/traits/into_builder.md @@ -30,7 +30,7 @@ The two entry points differ only in where they begin, and they produce the same | [`HasBuilder`](./has_builder.md) | every field `IsNothing` | assembling a record from pieces | | `IntoBuilder` | every field `IsPresent` | taking one apart and putting it back | -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/is_provider_for.md b/docs/reference/traits/is_provider_for.md index 15a60c5c..8386e6b5 100644 --- a/docs/reference/traits/is_provider_for.md +++ b/docs/reference/traits/is_provider_for.md @@ -40,7 +40,7 @@ constraint failed. the difference between "the trait is not implemented" and "the field `name` is missing on `App`", and it is the mechanism [`check_components!`](../macros/check_components.md) leans on to produce the second. -## Using it +## Usage The trait is in the prelude, so `use cgp::prelude::*;` names it. It is empty, with three parameters: diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/lift_value.md index 2c4c1aab..940b8fbb 100644 --- a/docs/reference/traits/lift_value.md +++ b/docs/reference/traits/lift_value.md @@ -44,7 +44,7 @@ output type, this one how to get back *in*. Together they run one step; the othe **This is a plain capability trait, not a CGP component.** It has no generated provider trait and is never wired. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::monad::traits`: diff --git a/docs/reference/traits/map_field.md b/docs/reference/traits/map_field.md index 5d030d81..69b1e8b2 100644 --- a/docs/reference/traits/map_field.md +++ b/docs/reference/traits/map_field.md @@ -42,7 +42,7 @@ compiler can pick the caller's rather than demanding `'static`. **You will not normally call it.** [`ChainGetters`](../providers/chain_getters.md) is what uses `map_field`, which is how a getter reaches a field on a nested context. -## Using it +## Usage **It is not in the prelude** — one of only two members of the `HasField` group that are not. Import it from `cgp::core::field::traits`: diff --git a/docs/reference/traits/map_fields.md b/docs/reference/traits/map_fields.md index 359ee370..d15c8cf0 100644 --- a/docs/reference/traits/map_fields.md +++ b/docs/reference/traits/map_fields.md @@ -39,7 +39,7 @@ It is the transforming member of the three product operations, and the only one spines: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum. That is what lets one operation produce both a partial record and a partial enum. -## Using it +## Usage **It is not in the prelude**, and neither is `IsOptional`. Import the trait from `cgp::core::field::traits` and any non-prelude marker from `cgp::core::field::impls`: diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index 801a866a..2d69f6f8 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -44,7 +44,7 @@ field `IsNothing` and flips each to `IsPresent` as it is filled; an extractor st parameter*, the compiler tracks exactly which fields are filled — and refuses to finalize an incomplete one. -## Using it +## Usage Four markers implement it, and they are the trait's whole public surface. **Three are in the prelude; `IsOptional` is not** — import it from `cgp::core::field::impls`. diff --git a/docs/reference/traits/map_type_ref.md b/docs/reference/traits/map_type_ref.md index f576ddb3..69849f58 100644 --- a/docs/reference/traits/map_type_ref.md +++ b/docs/reference/traits/map_type_ref.md @@ -44,7 +44,7 @@ is `MapType::Map>`. [`HasExtractorRef`](./has_extractor_r marker to `IsRef` and [`HasExtractorMut`](./has_extractor_mut.md) to `IsMut` — which is what lets a value be matched without being moved, with the narrowing working identically. -## Using it +## Usage **`IsRef` and `IsMut` are in the prelude; `IsOwned` is not** — import it from `cgp::core::field::impls`. The trait itself comes with the prelude. diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monadic_bind.md index 8f09fec8..ca72f789 100644 --- a/docs/reference/traits/monadic_bind.md +++ b/docs/reference/traits/monadic_bind.md @@ -47,7 +47,7 @@ It is one of four traits that give a monad marker its meaning, alongside [monad providers](../providers/monad_providers.md) consume it as an ordinary trait bound while folding a pipeline at compile time. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::monad::traits`: diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monadic_trans.md index d870cade..d0095779 100644 --- a/docs/reference/traits/monadic_trans.md +++ b/docs/reference/traits/monadic_trans.md @@ -41,7 +41,7 @@ each step. **This is a plain capability trait, not a CGP component.** It has no generated provider trait and is never wired. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::monad::traits`: diff --git a/docs/reference/traits/mut_field_getter.md b/docs/reference/traits/mut_field_getter.md index 2381ffb6..059ad5d9 100644 --- a/docs/reference/traits/mut_field_getter.md +++ b/docs/reference/traits/mut_field_getter.md @@ -42,7 +42,7 @@ write: | read | [`HasField`](./has_field.md) | [`FieldGetter`](./field_getter.md) | | write | [`HasFieldMut`](./has_field_mut.md) | `MutFieldGetter` | -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/partial_data.md b/docs/reference/traits/partial_data.md index 6f6dcbe6..b8640fd9 100644 --- a/docs/reference/traits/partial_data.md +++ b/docs/reference/traits/partial_data.md @@ -37,7 +37,7 @@ the first `builder()` call, long before any field is set. That is the division of labour with [`FinalizeBuild`](./finalize_build.md), which is implemented **only** at the all-present configuration. One says where you are going; the other says you have arrived. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method — naming a type is not an operation. diff --git a/docs/reference/traits/set_optional.md b/docs/reference/traits/set_optional.md index 2ee513ba..59ac842b 100644 --- a/docs/reference/traits/set_optional.md +++ b/docs/reference/traits/set_optional.md @@ -32,7 +32,7 @@ type does not change — which is exactly what makes an optional field settable The two methods differ only in what they do with whatever was there: `set` discards it, and `set_optional` hands it back. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md index 0a312b43..cb75dda4 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/static_format.md @@ -36,7 +36,7 @@ nothing. **It is what backs the `Display` impls on `Symbol` and `Chars`**, which is how you usually meet it: a type-level string can be printed with `{}` or `to_string()` because of this trait. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::base::traits`: diff --git a/docs/reference/traits/static_string.md b/docs/reference/traits/static_string.md index 0d7bba76..3c861d0d 100644 --- a/docs/reference/traits/static_string.md +++ b/docs/reference/traits/static_string.md @@ -28,7 +28,7 @@ string is available wherever a `const` is, costs nothing per use, and can be com [`StaticFormat`](./static_format.md) recovers a name lazily by writing into a formatter, which is what backs `Display`; reach for it only where there is no value to format and no constant will do. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::traits`: diff --git a/docs/reference/traits/take_field.md b/docs/reference/traits/take_field.md index a5323bf4..cf3828ed 100644 --- a/docs/reference/traits/take_field.md +++ b/docs/reference/traits/take_field.md @@ -31,7 +31,7 @@ Two things reach for it. Redistributing a record — [`into_builder`](./into_bui put them somewhere else — and, far more often, [`CanBuildFrom`](./can_build_from.md), whose merge recursion takes each field out of the source and builds it into the target. -## Using it +## Usage **It is not in the prelude** — the one member of the core builder family that is not. Import it from `cgp::core::field::traits` when you call `take_field` directly: diff --git a/docs/reference/traits/to_fields.md b/docs/reference/traits/to_fields.md index 106ca716..c2ac4627 100644 --- a/docs/reference/traits/to_fields.md +++ b/docs/reference/traits/to_fields.md @@ -28,7 +28,7 @@ The reverse direction is [`FromFields`](./from_fields.md), and the two round-tri `Fields` type, so generic code can decompose, transform, and rebuild with the shapes lining up by construction rather than by check. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/to_fields_ref.md b/docs/reference/traits/to_fields_ref.md index f705bf0c..3d237d0a 100644 --- a/docs/reference/traits/to_fields_ref.md +++ b/docs/reference/traits/to_fields_ref.md @@ -26,7 +26,7 @@ The original survives, and every entry in the result holds a reference rather th [`ToFields`](./to_fields.md) when a borrow would do forces every caller to give up ownership or clone, which is the most common over-requirement in this family. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/docs/reference/traits/to_optional.md b/docs/reference/traits/to_optional.md index b32b5fd3..8d131c73 100644 --- a/docs/reference/traits/to_optional.md +++ b/docs/reference/traits/to_optional.md @@ -28,7 +28,7 @@ ends it. **It is the conversion `optional_builder()` is built from**, which is the shortest way to describe both: one starts fresh and converts, the other converts something you already have. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: diff --git a/docs/reference/traits/transform_map.md b/docs/reference/traits/transform_map.md index eeb7ee83..6baa7e0c 100644 --- a/docs/reference/traits/transform_map.md +++ b/docs/reference/traits/transform_map.md @@ -26,7 +26,7 @@ currently in state `M1`, produce the same field in state `M2`.* new way to re-mark a record means writing one impl per source state and then applying it with [`TransformMapFields`](./transform_map_fields.md). -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::traits`, along with any non-prelude marker you name — `IsOptional` comes from `cgp::core::field::impls`: diff --git a/docs/reference/traits/transform_map_default.md b/docs/reference/traits/transform_map_default.md index 1c0f7931..629d2694 100644 --- a/docs/reference/traits/transform_map_default.md +++ b/docs/reference/traits/transform_map_default.md @@ -41,7 +41,7 @@ All three target `IsPresent`, which is exactly the configuration [`finalize_with_default`](./can_finalize_with_default.md) or [`build_with_default`](./can_build_with_default.md), with no marker in sight. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: diff --git a/docs/reference/traits/transform_map_fields.md b/docs/reference/traits/transform_map_fields.md index 12d74de0..7055f12f 100644 --- a/docs/reference/traits/transform_map_fields.md +++ b/docs/reference/traits/transform_map_fields.md @@ -40,7 +40,7 @@ then calling the ordinary [`finalize_build`](./finalize_build.md) is exactly wha [`CanFinalizeWithDefault`](./can_finalize_with_default.md) does, and re-marking to `IsOptional` is what [`ToOptional`](./to_optional.md) does. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::core::field::traits`: diff --git a/docs/reference/traits/transform_optional.md b/docs/reference/traits/transform_optional.md index f019c4c7..6c8b835d 100644 --- a/docs/reference/traits/transform_optional.md +++ b/docs/reference/traits/transform_optional.md @@ -42,7 +42,7 @@ workflows behave so alike. [`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md), with no marker in sight. -## Using it +## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: diff --git a/docs/reference/traits/update_field.md b/docs/reference/traits/update_field.md index 66bbf896..29b8e85f 100644 --- a/docs/reference/traits/update_field.md +++ b/docs/reference/traits/update_field.md @@ -47,7 +47,7 @@ directions. [`TakeField`](./take_field.md) are library blanket impls over it, each pinning one transition, which is why the general form is the one generated per field. -## Using it +## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. diff --git a/example-code/src/reference/derives/derive_build_field.rs b/example-code/src/reference/derives/derive_build_field.rs index cc894291..74b56968 100644 --- a/example-code/src/reference/derives/derive_build_field.rs +++ b/example-code/src/reference/derives/derive_build_field.rs @@ -106,7 +106,7 @@ pub mod rejected_read_of_an_unset_field {} /// ``` pub mod rejected_build_from_without_has_fields {} -/// ## Using it +/// ## Usage /// /// The shapes the page lists: a named-field struct, a tuple struct keyed by position, and the /// fieldless struct whose `builder()` is immediately finalizable. diff --git a/example-code/src/reference/derives/derive_cgp_data.rs b/example-code/src/reference/derives/derive_cgp_data.rs index 86da8e9b..5d685b90 100644 --- a/example-code/src/reference/derives/derive_cgp_data.rs +++ b/example-code/src/reference/derives/derive_cgp_data.rs @@ -4,7 +4,7 @@ //! shape pages, so what this file pins is the accepted and rejected shapes, that the umbrella and the //! two shape-specific faces agree on their output, and that the degenerate shapes compile. -/// ## Using it +/// ## Usage /// /// The two inputs the page opens on, the shape-specific faces, and the shapes the page says are /// accepted. The one it says is rejected is a doctest in the module below this one. diff --git a/example-code/src/reference/derives/derive_cgp_variant.rs b/example-code/src/reference/derives/derive_cgp_variant.rs index 84246866..0c82a6ed 100644 --- a/example-code/src/reference/derives/derive_cgp_variant.rs +++ b/example-code/src/reference/derives/derive_cgp_variant.rs @@ -3,7 +3,7 @@ //! The page's worked example, run, plus the shape it rejects. Written with `CgpVariant` rather than //! the umbrella, which is the page's own claim that the two emit the same output on an enum. -/// ## Using it +/// ## Usage /// /// The page's rejected snippet: a struct-style variant has no single payload type, so the derive /// fails. Every variant must carry exactly one unnamed payload, with no per-variant opt-out. diff --git a/example-code/src/reference/derives/derive_extract_field.rs b/example-code/src/reference/derives/derive_extract_field.rs index dafe6410..f83cbcd3 100644 --- a/example-code/src/reference/derives/derive_extract_field.rs +++ b/example-code/src/reference/derives/derive_extract_field.rs @@ -48,7 +48,7 @@ pub mod what_its_for { } } -/// ## Using it +/// ## Usage /// /// The accepted enum, the payload-struct rewrite the page recommends — including for a case that /// carries nothing — and the variantless enum the page says degenerates. diff --git a/example-code/src/reference/derives/derive_from_variant.rs b/example-code/src/reference/derives/derive_from_variant.rs index 34e56011..25d5edec 100644 --- a/example-code/src/reference/derives/derive_from_variant.rs +++ b/example-code/src/reference/derives/derive_from_variant.rs @@ -37,7 +37,7 @@ pub mod what_its_for { } } -/// ## Using it +/// ## Usage /// /// The accepted enum, a generic one, and the variantless enum the page says produces no impls. pub mod using_it { diff --git a/example-code/src/reference/derives/derive_has_field.rs b/example-code/src/reference/derives/derive_has_field.rs index 6f142b06..12219b59 100644 --- a/example-code/src/reference/derives/derive_has_field.rs +++ b/example-code/src/reference/derives/derive_has_field.rs @@ -35,7 +35,7 @@ pub mod what_its_for { } } -/// ## Using it +/// ## Usage /// /// The four struct shapes the page lists, in the order it lists them: named fields, a raw-identifier /// field, tuple fields, a unit struct, and a generic struct. The unit struct is the one whose whole diff --git a/example-code/src/reference/derives/derive_has_fields.rs b/example-code/src/reference/derives/derive_has_fields.rs index 46be6287..879521de 100644 --- a/example-code/src/reference/derives/derive_has_fields.rs +++ b/example-code/src/reference/derives/derive_has_fields.rs @@ -40,7 +40,7 @@ pub mod what_its_for { } } -/// ## Using it +/// ## Usage /// /// Every struct and enum shape the page lists. The four struct shapes come first, then the four /// variant shapes in the single enum the page uses for them. From 10694c3ca6e8ec1fb06d2b086d225aef2f4afd39 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 22 Aug 2026 15:45:27 +0200 Subject: [PATCH 035/516] Revise the #[cgp_impl] reference page Fix the shape-new-cannot-express example, which asserted a default-generic- parameter case but then just repeated the multi-component code block verbatim without ever showing one; move it to the end of its section and demonstrate it properly with the page's own ScaledAreaCalculator provider. Trim other restated content (the for-Context mechanics, the raw-provider rationale), fix writing-style issues (personification, an idiom, unnamed passives, a run-on sentence across a code block), and add missing coverage (the for-Context clause being optional, the #[cgp_impl(Self)] missing-context error, the new/component-override no-op on that form) verified against the internal reference and implementation documents. Cross-link the higher-order- providers and coherence concepts and the Static Dispatch tutorial where they bear directly on the text. Co-Authored-By: Claude Sonnet 5 --- docs/reference/macros/cgp_impl.md | 173 +++++++++++++++++------------- 1 file changed, 101 insertions(+), 72 deletions(-) diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index f7fc3de3..90b0c07a 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -26,8 +26,10 @@ where ``` Every part of that is correct, and almost every part of it is unfamiliar. The trait carries a -parameter you did not write, `Self` is a type with no values, and there is no `self` anywhere. This -hides a simple fact: it is an implementation of `CanCalculateArea`. +parameter you did not write, `Self` is a type with no values, and there is no `self` anywhere. Written +this way, the code does not read as an implementation of `CanCalculateArea`, even though that is +exactly what it is. [Bypassing coherence](/docs/concepts/coherence) is why the trait needs a `Self` it +owns instead of the type the capability is really about. `#[cgp_impl]` gives you back the familiar shape. Write the implementation as though you were implementing the consumer trait directly, with `self` and `Self` and the signatures from the original @@ -48,12 +50,12 @@ where The macro performs the rewrite for you. Write providers this way. The macro produces the inside-out form shown earlier, and you will meet that form in generated code. -One fact the convenience must not hide: **inside a `#[cgp_impl]` block, `self` and `Self` mean the -context, not the provider.** The context is the type the capability runs against, and it supplies the -values it needs as its own fields. The provider is a type-level name with no fields and no value: it -is never constructed, and there is nothing in it to read. The macro rewrites `self` to the context -value and `Self` to the context type because the context is the only thing that exists when the -method runs. +This convenience has one exception worth stating plainly: **inside a `#[cgp_impl]` block, `self` and +`Self` mean the context, not the provider.** The context is the type the capability runs against, and +it supplies the values it needs as its own fields. The provider is a type-level name with no fields +and no value: it is never constructed, and there is nothing in it to read. The macro rewrites `self` +to the context value and `Self` to the context type because the context is the only thing that exists +when the method runs. ## Usage @@ -78,11 +80,19 @@ where | provider name | Required. The type that takes the `Self` position in the generated provider impl. | | `: ComponentType` | Optional. Overrides which component this provider is registered as implementing. Defaults to the provider trait's name plus `Component`. | +The `for Context` clause is optional. Omitting it, as every example on this page does, lets the macro +insert a generic context parameter for you: write `impl AreaCalculator`, not +`impl AreaCalculator for Context`. Name the context explicitly only to bound it in a way the +omitted form cannot express, such as a lifetime or a higher-ranked bound, or to serve one *concrete* +context alone, as in `impl AreaCalculator for Rectangle`. +[When to reach for it](#when-to-reach-for-it-and-when-not) says more about choosing between these +forms. + Without `new`, the provider struct must already exist. A wiring entry naming a struct nothing declares is a common and confusing first error. A provider may be generic. Parameters go in the attribute and in the impl generics together, which is -how a higher-order provider takes an inner provider: +how a [higher-order provider](/docs/concepts/higher-order-providers) takes an inner provider: ```rust #[cgp_impl(new ScaledAreaCalculator)] @@ -124,33 +134,37 @@ The first block's `new` declares `pub struct RectangleGeometry;`; the second blo struct without `new` and adds a second impl to it. Writing `new` on more than one block for the same struct is a duplicate-definition error. -**A struct whose shape `new` cannot express** is declared explicitly instead, once, above every -`#[cgp_impl]` block that targets it. A default generic parameter, such as -`pub struct IterSum(PhantomData);`, is the case you meet most often: +Declaring the struct explicitly is an equally valid style for this same case: write +`pub struct RectangleGeometry;` once, above both blocks, and omit `new` from all of them rather than +from just the second. Either style works; declaring the struct explicitly reads more consistently once +there are more than two or three blocks, since a reader does not have to find the one block carrying +`new` to know where the struct comes from. Neither style requires +[`#[cgp_provider]`](./cgp_provider.md): the struct is only being declared once and reused, and the body +of every block still reads as an ordinary trait impl. + +**A struct whose shape `new` cannot express must be declared explicitly, because `new`'s own grammar is +narrow.** `#[cgp_impl(new ...)]` desugars to [`#[cgp_new_provider]`](./cgp_new_provider.md), and that +macro can only emit one of two shapes: a plain provider name becomes a unit struct with no fields, and +a generic provider becomes a tuple struct with one public +[`PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html) field wrapping all of its +generic parameters together, always `pub` and never with a default. Anything the struct needs outside +that shape has to be written by hand. + +The case you meet most often is a default on a higher-order provider's inner parameter, so an +application can omit the inner provider and fall back to +[`UseContext`](../providers/use_context.md), which routes back through the context's own +implementation of the component. If `ScaledAreaCalculator` from [Usage](#usage) should default this +way, `new` has no syntax for it, and the struct has to be declared by hand instead: ```rust -pub struct RectangleGeometry; - -#[cgp_impl(RectangleGeometry)] -impl AreaCalculator { - fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height - } -} - -#[cgp_impl(RectangleGeometry)] -impl PerimeterCalculator { - fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - 2.0 * (width + height) - } -} +pub struct ScaledAreaCalculator(PhantomData); ``` -Either style works for a struct implementing several components. Declaring it explicitly reads more -consistently once there are more than two or three blocks, since a reader does not have to find the -one block carrying `new` to know where the struct comes from. Neither style requires -[`#[cgp_provider]`](./cgp_provider.md): the struct is only being declared once and reused, and the -body of every block still reads as an ordinary trait impl. +Every `#[cgp_impl(ScaledAreaCalculator)]` block implementing a component for it then +looks exactly like the block shown in [Usage](#usage), minus `new`. The same reasoning covers any other +shape `new` cannot spell: an extra derive, a visibility narrower than `pub`, or fields beyond that one +blanket `PhantomData`. Declare the struct with whatever shape it needs, and keep every implementing +block written with `#[cgp_impl(ProviderName)]`. ### Companion attributes @@ -166,16 +180,17 @@ let an idiomatic provider state what it needs. - [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound in a higher-order provider. - [`#[default_impl(...)]`](../traits/default_namespace.md) registers the provider as a namespace's - per-type default, for use with [`cgp_namespace!`](./cgp_namespace.md). + per-type default, emitting a delegation impl alongside it, for use with + [`cgp_namespace!`](./cgp_namespace.md). Each may be repeated. All except `#[use_provider]` also take a comma-separated list inside one attribute, which is the form to prefer: `#[uses(HasName, CanRaiseError)]` reads as one dependency list. `#[use_provider]` is the exception because its own argument already ends in a bound list, so a second pair after a comma has nowhere to go; write one attribute per inner provider. -Three attributes that appear on other CGP macros are not read here. `#[extend]`, `#[extend_where]`, -and `#[impl_generics]` all act on a *generated trait definition*, which a provider impl does not have, -so they belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to +`#[cgp_impl]` does not read three attributes you may see on other CGP macros: `#[extend]`, +`#[extend_where]`, and `#[impl_generics]`. All three act on a *generated trait definition*, which a +provider impl does not have, so they belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to [`#[cgp_component]`](./cgp_component.md). Writing one here leaves a name nothing resolves; see [Gotchas](#gotchas). An impl-side bound that really is impl-side goes in the block's own `where` clause, which passes through untouched. @@ -183,9 +198,11 @@ clause, which passes through untouched. ### Implementing the consumer trait directly Naming `Self` as the provider bypasses the rewrite entirely and emits the block unchanged as an -ordinary consumer-trait impl on a concrete type. This form requires the `for Context` clause, and it is -useful when you want a hand-written impl while still applying the companion attributes. Because the -macro does not generate a provider struct here, `new` and the component override have no effect. +ordinary consumer-trait impl on a concrete type. This form requires the `for Context` clause. Omitting +it is rejected with an `Expected context type to be specified` error, since there is no context left to +find. The form is useful when you want a hand-written impl while still applying the companion +attributes. Because the macro does not generate a provider struct here, `new` and the component +override have no effect; see [Gotchas](#gotchas) for what happens if you write them anyway. ```rust #[cgp_impl(Self)] @@ -218,9 +235,9 @@ impl AreaCalculator { } ``` -The two `#[implicit]` parameters are removed from the signature and replaced by reads of the `width` -and `height` fields, so the provider requires a context that has them. The `new` keyword defines -`RectangleArea`. A concrete type then wires the component and calls through it: +The macro removes the two `#[implicit]` parameters from the signature and replaces them with reads of +the `width` and `height` fields, so the provider requires a context that has them. The `new` keyword +defines `RectangleArea`. A concrete type then wires the component and calls through it: ```rust #[derive(HasField)] @@ -245,32 +262,30 @@ fn print_area(rect: &Rectangle) { **Write providers with `#[cgp_impl]`.** It is the recommended form for every provider, and the cases that call for something else are narrower than they look. -Prefer the unqualified header `impl AreaCalculator`, with no `for Context`, and let the macro insert -the context parameter. This keeps a provider reading like an ordinary trait impl. Name the context -explicitly, as in `impl AreaCalculator for Context`, only when you actually need to say -something about it that the sugar cannot express, such as a lifetime or a higher-ranked bound. +Prefer the unqualified header from [Usage](#usage), `impl AreaCalculator` with no `for Context`, +letting the macro insert the context parameter, which keeps a provider reading like an ordinary trait +impl. Name the context explicitly only when the sugar genuinely falls short, such as a lifetime or a +higher-ranked bound. -That named context may be a *concrete* type rather than a parameter, as in -`impl AreaCalculator for Rectangle`, which writes a provider serving only that one context. Keep it -distinct from the -[`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which looks similar and does -something else: this one still produces a named provider that a context wires like any other, and that -one produces no provider at all. +Naming a *concrete* type as that context, as in `impl AreaCalculator for Rectangle`, is a different +choice worth keeping distinct from the +[`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which looks similar but does +something else. The concrete-context form still produces a named provider that a context wires like +any other. The `Self` form produces no provider at all. Reach for something else in two cases. - **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain - function with no component, no provider, and no wiring. + function with no component, no provider, and no wiring, which is the bottom rung of + [How much CGP to use](/docs/concepts/modularity-hierarchy). - **You want to implement the consumer trait directly on one concrete type.** Use the [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which keeps the companion attributes while emitting an ordinary impl. -A struct that `new` cannot declare, or one [shared by several -`#[cgp_impl]` blocks](#declaring-the-provider-struct-separately), is not by itself a reason to drop to -[`#[cgp_provider]`](./cgp_provider.md): declare the struct yourself and keep writing every block with -`#[cgp_impl(ProviderName)]`, just without `new`. Reach for the raw form only when you need the -inside-out provider-trait shape itself: a bound the sugar cannot express, or a rare construct -`#[cgp_impl]`'s rewrite does not support, whether from a limitation or a bug. +Needing to [declare the provider struct separately](#declaring-the-provider-struct-separately) is not +by itself a reason to drop to [`#[cgp_provider]`](./cgp_provider.md). Reach for the raw form only when +you need the inside-out provider-trait shape itself: a bound the sugar cannot express, or a rare +construct `#[cgp_impl]`'s rewrite does not support, whether from a limitation or a bug. ## Under the hood @@ -297,8 +312,8 @@ impl FooProvider for Context { } ``` -the macro produces the provider impl, an `IsProviderFor` impl, and, because `new` was given, the -provider struct: +Because `new` was given, the macro also produces the provider struct alongside the provider impl and +its `IsProviderFor` impl: ```rust impl FooProvider for ValueToString { @@ -315,8 +330,8 @@ pub struct ValueToString; Three things changed. The trait gained `Context` as its leading argument. The `Self` type became the provider. `&self` became the explicit parameter `__context__: &Context`. The receiver identifier is the snake-cased context type wrapped in double underscores, so both `Context` and the default -`__Context__` become `__context__`. Every `self` in a body is rewritten to that identifier, and every -`Self` to the context type. +`__Context__` become `__context__`. The macro rewrites every `self` in a body to that identifier, and +every `Self` to the context type. When `for Context` is omitted the only difference is that the inserted parameter is `__Context__`. The earlier `RectangleArea` example is exactly equivalent to writing it out: @@ -334,15 +349,15 @@ where ``` The generated `IsProviderFor` impl copies the provider impl's signature, drops the body, and keeps the -`where` clause. This is how the provider's dependencies are captured for error reporting. Its -arguments are the component name, the context, and a tuple of any remaining provider-trait parameters, +`where` clause, capturing the provider's dependencies for error reporting. Its arguments are the +component name, the context, and a tuple of any remaining provider-trait parameters, so a provider for `ComputerRef` gets `IsProviderFor`. -**An associated type the block declares is exempt.** `Self::Output` in a provider that supplies -`type Output` is left alone, because the macro gathers the block's own associated-type names first and -skips any `Self::` path starting with one. In the emitted impl, `Self` is the provider struct, which is -the type that declares `Output`, so the path resolves as written. Every other `Self` in the block is +**An associated type the block declares is exempt.** The macro leaves `Self::Output` alone in a +provider that supplies `type Output`, because it gathers the block's own associated-type names first +and skips any `Self::` path starting with one. In the emitted impl, `Self` is the provider struct, +which is the type that declares `Output`, so the path still resolves. Every other `Self` in the block is still rewritten, including one naming an abstract type the *context* supplies. Associated consts are not covered by the exemption; see [Gotchas](#gotchas). @@ -397,14 +412,23 @@ eventually create. A `self::` *module* path inside a macro invocation is safe: t distinguishes the two meanings of `self`, and only the value form is rewritten. **A misplaced companion attribute is reported by the compiler, not by the macro.** An attribute -`#[cgp_impl]` does not recognize is re-attached to the generated provider impl, which lets -`#[allow(...)]` ride through. A stray `#[extend(HasName)]` therefore produces a *cannot find attribute* -resolution error pointing at the impl, with no mention of `#[cgp_impl]`. +`#[cgp_impl]` does not recognize is re-attached to the generated provider impl rather than dropped, so +`#[allow(...)]` and similar attributes carry over unaffected. A stray `#[extend(HasName)]` therefore +produces a *cannot find attribute* resolution error pointing at the impl, with no mention of +`#[cgp_impl]`. + +**`new` and a component override are accepted, and ignored, on the `Self` form.** Writing +`#[cgp_impl(new Self)]` or `#[cgp_impl(Self: SomeComponent)]` parses and compiles, but has exactly the +same effect as a plain `#[cgp_impl(Self)]`: no struct is declared, and the component override is never +consulted, because this form builds neither a provider nor an `IsProviderFor` impl for either one to +apply to. Leave both out. ## Related constructs - [`#[cgp_component]`](./cgp_component.md) — defines the component this implements. - [`#[cgp_provider]`](./cgp_provider.md) — the lower-level form `#[cgp_impl]` desugars to. +- [`#[cgp_new_provider]`](./cgp_new_provider.md) — `#[cgp_provider]` with the struct declared too, + equivalent to `#[cgp_impl(new ...)]`. - [`#[cgp_fn]`](./cgp_fn.md) — the lighter alternative when one implementation is enough. - [`delegate_components!`](./delegate_components.md) — wires the provider onto a type. - [`check_components!`](./check_components.md) — verifies the wiring resolves. @@ -419,6 +443,11 @@ The ideas behind it: - [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — what the block's `where` clause is really doing. +To see it taught as a sequence of small steps rather than as a reference, the +[Static Dispatch tutorial](/docs/tutorials/area-calculation/static-dispatch) builds `#[cgp_component]` +and `#[cgp_impl]` up from the same coherence failure that +[Bypassing coherence](/docs/concepts/coherence) explains from the other side. + ## Source - Entry point: [`cgp_impl.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_impl.rs) From ca84ab25e9945820b45b89ac67ef3dafcf1c4080 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 22 Aug 2026 16:07:40 +0200 Subject: [PATCH 036/516] Add a macros overview page, order the sidebar, and align prose with style Add docs/reference/macros/index.md, grouping every macro by job (defining a component and its providers, wiring and checking, building type-level values), and point _category_.json at it instead of the autogenerated list. Give every page in the directory a sidebar_position so the sidebar leads with the constructs almost every CGP program needs and ends with the type-level sugar and the read-mostly #[cgp_provider] page. Fix a broken pair of links in cgp_impl.md left over from an earlier edit (#[cgp_new_provider] is consolidated onto cgp_provider.md on this site, not its own page). Bring the heavier prose in cgp_component.md, cgp_type.md, and cgp_namespace.md in line with the project's writing-style rules: replace em dashes used as a default connector with the punctuation the actual relationship calls for, and rewrite several pseudo-cleft sentences ("X is what does Y") so the real subject leads. Remove two words the communication-strategy vocabulary specifically flags (an idiom and "magic"), the idiom "ride through", "load-bearing" as a stand-in for "essential", and fifteen instances of "genuinely" as a decorative intensifier that added nothing once tested against the sentence's meaning. Co-Authored-By: Claude Sonnet 5 --- docs/reference/macros/_category_.json | 4 +- docs/reference/macros/async_trait.md | 1 + docs/reference/macros/blanket_trait.md | 5 +- docs/reference/macros/cgp_auto_dispatch.md | 1 + docs/reference/macros/cgp_auto_getter.md | 1 + docs/reference/macros/cgp_component.md | 85 ++++++++++--------- docs/reference/macros/cgp_computer.md | 1 + docs/reference/macros/cgp_fn.md | 6 +- docs/reference/macros/cgp_getter.md | 3 +- docs/reference/macros/cgp_impl.md | 13 +-- docs/reference/macros/cgp_namespace.md | 75 ++++++++-------- docs/reference/macros/cgp_producer.md | 9 +- docs/reference/macros/cgp_provider.md | 7 +- docs/reference/macros/cgp_type.md | 33 +++---- docs/reference/macros/check_components.md | 3 +- .../macros/delegate_and_check_components.md | 1 + docs/reference/macros/delegate_components.md | 1 + docs/reference/macros/index.md | 64 ++++++++++++++ docs/reference/macros/path.md | 1 + docs/reference/macros/product.md | 3 +- docs/reference/macros/sum.md | 1 + docs/reference/macros/symbol.md | 5 +- 22 files changed, 203 insertions(+), 120 deletions(-) create mode 100644 docs/reference/macros/index.md diff --git a/docs/reference/macros/_category_.json b/docs/reference/macros/_category_.json index fab498e8..192379c3 100644 --- a/docs/reference/macros/_category_.json +++ b/docs/reference/macros/_category_.json @@ -2,7 +2,7 @@ "label": "Macros", "position": 1, "link": { - "type": "generated-index", - "description": "The procedural macros you invoke directly: the ones that define components and providers, the ones that wire and check them, and the ones that build type-level values." + "type": "doc", + "id": "reference/macros/index" } } diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index ddcc8a1d..96223544 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[async_trait]' +sidebar_position: 12 --- # `#[async_trait]` diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 41df6435..7ab588b8 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[blanket_trait]' +sidebar_position: 11 --- # `#[blanket_trait]` @@ -159,7 +160,7 @@ That last clause is the real discriminator, separating this macro from its close - **A trait alias, when one exists.** The empty-body form above is a workaround for a language feature Rust does not have on stable; it is the right workaround, but do not reach for the macro if a plain supertrait bound reads fine at the use site. -- **Nothing at all, for a plain generic function.** If the requirement genuinely belongs in the signature +- **Nothing at all, for a plain generic function.** If the requirement belongs in the signature and no caller is generic over the type, a function with a `where` clause is simpler and the propagation problem never arises. @@ -175,7 +176,7 @@ trait. Needing that is the signal to move to a component. ### Advanced This section shows the two items the macro emits. You do not need them to use `#[blanket_trait]`, but the -associated-type lifting is genuinely surprising the first time, and knowing what the impl requires makes an +associated-type lifting is surprising the first time, and knowing what the impl requires makes an "unsatisfied bound" error much easier to read. `cargo cgp expand` prints the same thing for your own code. ::: diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index ca068a2d..cb5794b8 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_auto_dispatch]' +sidebar_position: 15 --- # `#[cgp_auto_dispatch]` diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 81e5d05b..6ec87ac9 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_auto_getter]' +sidebar_position: 8 --- # `#[cgp_auto_getter]` diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 54d261e4..2448c623 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_component]' +sidebar_position: 1 --- # `#[cgp_component]` @@ -81,7 +82,7 @@ pub trait CanCalculateArea { } ``` -Each key has a default and only `provider` is required — passing a bare identifier is shorthand for +Each key has a default and only `provider` is required. Passing a bare identifier is shorthand for setting it alone. | Key | What it sets | Default | @@ -106,8 +107,8 @@ inside one attribute. | [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) | Generates dispatch impls for a component generic over a parameter | | [`#[prefix(@path in Namespace)]`](./cgp_namespace.md) | Registers the component into a namespace under a type-level path | -When a component depends on a type another component supplies — most often the error type from -[`HasErrorType`](../components/has_error_type.md) — import it with `#[use_type]` rather than writing +When a component depends on a type another component supplies, most often the error type from +[`HasErrorType`](../components/has_error_type.md), import it with `#[use_type]` rather than writing the supertrait and the qualified path by hand: ```rust @@ -125,7 +126,7 @@ the macro rejects it with *Type equality constraints cannot be used in component Every other form of the attribute works on a component exactly as it does elsewhere. For a supertrait with no associated type to import, use `#[extend(...)]` in preference to native -`: Supertrait` syntax — `#[extend(HasName)]` reads as importing a capability, where +`: Supertrait` syntax. `#[extend(HasName)]` reads as importing a capability, while `pub trait CanGreet: HasName` reads as inheritance, which is not what a CGP supertrait is. An associated type the trait declares *itself* is not imported and stays written as `Self::Output`. @@ -136,7 +137,7 @@ rather than write. Three attributes that look like they belong here do not, and the error is confusing enough to be worth naming: `#[uses(...)]`, `#[extend_where(...)]`, and `#[use_provider(...)]` are read by [`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_fn]`](./cgp_fn.md) but not by `#[cgp_component]`. None of -them is an attribute in its own right, so writing one here leaves a name nothing can resolve — see +them is an attribute in its own right, so writing one here leaves a name nothing can resolve; see [Gotchas](#gotchas). The equivalent of `#[uses]` on a component is a supertrait, written with `#[extend]`. @@ -183,7 +184,7 @@ does, and nothing else in the program changes. ## When to reach for it, and when not -Reach for `#[cgp_component]` when a capability genuinely needs **more than one implementation, and the +Reach for `#[cgp_component]` when a capability needs **more than one implementation, and the choice belongs to the type using it.** That is the case it exists for, and its machinery is not free: a component is a trait, a second trait, a marker type, and a line of wiring per type. @@ -191,14 +192,14 @@ Prefer something simpler when you can. - **One implementation, ever.** Use [`#[cgp_fn]`](./cgp_fn.md) instead. It builds the capability straight from a function, needs no wiring at all, and keeps working unchanged if a second - implementation ever arrives — so it is the right starting point rather than a lesser one. -- **One implementation per type, chosen globally.** That is what a plain Rust trait already does well. + implementation ever arrives, which makes it the right starting point rather than a lesser one. +- **One implementation per type, chosen globally.** A plain Rust trait already does this well. Reach for a component when two *different* applications must make different choices for the same type, or when the implementations must overlap in a way the compiler rejects. - **A closed set of variants with fixed operations.** An `enum` and a `match` are clearer than any machinery. -There is also a finer line worth knowing: a capability may genuinely need several implementations +There is also a finer line worth knowing: a capability may need several implementations while each individual implementation serves exactly one type. In that case you can implement the consumer trait directly on each concrete type, as you would any Rust trait, and skip providers entirely. Named providers earn their place once a second type wants the *same* implementation, or once @@ -207,20 +208,20 @@ an implementation should compose with a wrapper. ### How many items should a component have? A component trait is an ordinary trait. It takes as many methods, associated types, and associated -consts as any other, and every one of them is reproduced on the provider trait — CGP's own -[`CanCompute`](../components/computer.md) declares an associated `Output` beside its method. There is -no cap. +consts as any other, and every one of them is reproduced on the provider trait. CGP's own +[`CanCompute`](../components/computer.md) declares an associated `Output` beside its method, and there +is no cap. What to group is a judgement rather than a rule, and the useful question is: **everything in one -component is answered by one provider choice.** Items a single choice settles belong together — a +component is answered by one provider choice.** Items a single choice settles belong together: a method and the associated type it returns, or several field reads one getter provider answers by name. Items that separate choices settle are better apart, because grouping them costs reuse: every provider then carries the union of the dependencies of all the methods, a wrapper must forward the methods it has no opinion about, and a type that needs only part of the surface must still supply the rest. The usual sign of a component that has grown past one decision is a consumer trait named after a noun -rather than a verb — `Shape` carrying `area`, `perimeter`, `scale`, and `rotate`. It compiles, but very -little of it is reusable. A good check before committing: could a second type plausibly reuse one of +rather than a verb, such as `Shape` carrying `area`, `perimeter`, `scale`, and `rotate`. It compiles, +but very little of it is reusable. A good check before committing: could a second type plausibly reuse one of this trait's providers *whole*? If not, implement the trait directly on the concrete type and skip the machinery. @@ -256,7 +257,7 @@ pub trait CanCalculateArea { Second, the **provider trait**: the same interface with `Self` replaced by a leading `Context` type parameter and every `self`/`Self` rewritten to `context`/`Context`. Its -[`IsProviderFor`](../traits/is_provider_for.md) supertrait is what makes an unmet dependency report +[`IsProviderFor`](../traits/is_provider_for.md) supertrait makes an unmet dependency report itself by name rather than as a bare "trait not implemented"; its third argument is a tuple of the component's extra type parameters, empty here: @@ -269,7 +270,7 @@ pub trait AreaCalculator: ``` `IsProviderFor` *replaces* the supertrait list rather than joining it. Any supertrait the consumer -trait had — written natively, or added by `#[extend]` or `#[use_type]` — becomes a `where` predicate +trait had, whether written natively or added by `#[extend]` or `#[use_type]`, becomes a `where` predicate on the context instead, which follows from the `Self`-to-`Context` move: a supertrait constrains the type the capability is about, and on the provider side that type is the context parameter. So `#[extend(HasName)]` on a `CanGreet` component produces: @@ -283,18 +284,18 @@ where } ``` -That predicate is added to every emitted item that mentions the context — the two blanket impls below and -the `UseContext` and `RedirectLookup` impls further down each gain their own `Context: HasName` — since +That predicate is added to every emitted item that mentions the context: the two blanket impls below and +the `UseContext` and `RedirectLookup` impls further down each gain their own `Context: HasName`, since none of them can apply where the supertrait does not hold. **A method may carry a default body, and the body moves to the provider trait.** This is the other thing -the `Self`-to-`Context` move reaches, and it is worth knowing because it is what lets a provider inherit a +the `Self`-to-`Context` move reaches, and it is worth knowing because it lets a provider inherit a default at all. Given `fn greet(&self) -> String { format!("Hello, {}!", self.name()) }` on the consumer -trait, the provider trait gets `fn greet(context: &Context) -> String { format!("Hello, {}!", context.name()) }` -— rewritten, and still a default. The consumer trait keeps its copy too, so the body appears twice in an +trait, the provider trait gets `fn greet(context: &Context) -> String { format!("Hello, {}!", context.name()) }`, +rewritten but still a default. The consumer trait keeps its copy too, so the body appears twice in an expansion. -That is what makes an **empty provider impl** meaningful, and it is how +This is why an **empty provider impl** is meaningful, and it is how [`UseDefault`](../providers/use_default.md) works: ```rust @@ -316,7 +317,7 @@ where } ``` -Fourth, the **provider blanket impl**, which is what makes wiring work: anything that delegates this +Fourth, the **provider blanket impl**, which makes wiring work: anything that delegates this component through [`DelegateComponent`](../traits/delegate_component.md) inherits the provider trait from whatever it delegates to. @@ -333,8 +334,8 @@ where } ``` -The `IsProviderFor` bound sits on `Provider` itself rather than on `Provider::Delegate`. That is what -threads a provider's dependencies down the delegation chain so they still appear in an error message. +The `IsProviderFor` bound sits on `Provider` itself rather than on `Provider::Delegate`, which threads +a provider's dependencies down the delegation chain so they still appear in an error message. Fifth, the **component marker**, the key wiring uses: @@ -343,8 +344,8 @@ pub struct AreaCalculatorComponent; ``` Those five are emitted in the order consumer trait, consumer impl, provider trait, provider impl, -marker — the listings above pair each trait with the impl that routes to it, which reads better than -the order they actually appear in. +marker. The listings above instead pair each trait with the impl that routes to it, which reads better +than the order they actually appear in. Beyond the five, the macro emits the provider impls that let the component participate in CGP's usual patterns. Two are always emitted, and two are one per attribute: @@ -352,7 +353,7 @@ patterns. Two are always emitted, and two are one per attribute: - A [`UseContext`](../providers/use_context.md) impl, so the provider trait can be satisfied by routing back through the context's own implementation. Its only bound is `Context: CanCalculateArea`, and each method forwards to the consumer method. -- A [`RedirectLookup`](../providers/redirect_lookup.md) impl, which is what the `open` statement and +- A [`RedirectLookup`](../providers/redirect_lookup.md) impl, which the `open` statement and [namespaces](./cgp_namespace.md) resolve through. - One [`UseDelegate`](../providers/use_delegate.md) impl per [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) attribute. @@ -363,13 +364,13 @@ The `RedirectLookup` impl is where a component's own type parameters earn a plac what makes `@AreaCalculatorComponent.Rectangle` resolve. For a component with type parameters the impl does not look the incoming path up directly: it appends the parameters to it first, so a lookup that arrives at `AreaCalculatorComponent` carrying no path ends up looking for `Rectangle`. Only -*type* parameters take part — a lifetime or a const parameter cannot key a path and is left out. +*type* parameters take part; a lifetime or a const parameter cannot key a path and is left out. Two details of the real output differ from the listings above, and both trip people up when reading an -error. The generated parameters carry **reserved names** — the context is literally `__Context__` -unless you override it, and the provider parameter is `__Provider__`; the readable `Context` and +error. The generated parameters carry **reserved names**: the context is literally `__Context__` +unless you override it, and the provider parameter is `__Provider__`. The readable `Context` and `Provider` here are for legibility only. And a component with parameters of its own appends them -*after* the context in the provider trait — except lifetimes, which Rust requires to lead — and groups +*after* the context in the provider trait, except lifetimes, which Rust requires to lead, and groups them into the `IsProviderFor` parameter tuple. That tuple holds types, so a lifetime is lifted into [`Life<'a>`](../types/life.md): @@ -381,7 +382,7 @@ them into the `IsProviderFor` parameter tuple. That tuple holds types, so a life | `HasReference<'a, T>` | `ReferenceGetter<'a, __Context__, T>` | `(Life<'a>, T)` | Bounds and defaults are dropped from the tuple, which names the parameters positionally and nothing -more. A const parameter has no place in it at all, which is why the macro rejects one — see +more. A const parameter has no place in it at all, which is why the macro rejects one; see [Gotchas](#gotchas).
@@ -405,9 +406,9 @@ ComponentName -> IDENTIFIER GenericArgs? `ProviderName` is shorthand for setting `provider` alone. In the key/value form each key may appear at most once, in any order, and `provider` is required. `IDENTIFIER` is a Rust identifier token, and -`GenericArgs` is the Rust grammar's `< … >` argument list — so the component name may carry generic -parameters while the provider name may not. The attribute delimiter — `(...)` for the bare form, -`{...}` for the key/value form — is ordinary Rust attribute syntax and does not change how the +`GenericArgs` is the Rust grammar's `< … >` argument list, so the component name may carry generic +parameters while the provider name may not. The attribute delimiter, `(...)` for the bare form and +`{...}` for the key/value form, is ordinary Rust attribute syntax and does not change how the arguments inside are parsed.
@@ -424,7 +425,7 @@ A component's extra parameters are recorded as a tuple of *types* in the `IsProv CGP's wiring dispatches on types rather than values, so a const value has nowhere to live in that machinery. -An associated `const` *item* is unaffected — `const LIMIT: u64;` as a trait member is an +An associated `const` *item* is unaffected. `const LIMIT: u64;` as a trait member is an [associated const](https://doc.rust-lang.org/reference/items/associated-items.html), not a generic parameter, and a provider supplies it in the ordinary way. Naming your own associated const from *inside* a [`#[cgp_impl]`](./cgp_impl.md) body has a wrinkle of its own, covered in that page's @@ -434,11 +435,11 @@ Gotchas. parse time with an error naming the trait the macro expected, rather than being lowered into code that fails to compile later. -**A misplaced companion attribute is reported by the compiler, not by the macro — and reported several -times.** An attribute `#[cgp_component]` does not recognize rides through onto *every* item the macro +**A misplaced companion attribute is reported by the compiler, not by the macro, and reported several +times.** An attribute `#[cgp_component]` does not recognize is carried onto *every* item the macro generates: the consumer trait, the provider trait, and the impls built from each. For `#[allow(...)]` or -a doc comment that is exactly what you want. For `#[uses(HasName)]` written above a component trait it -means one *cannot find attribute* resolution error per generated item, none of which mentions +a doc comment, that repetition is welcome. For `#[uses(HasName)]` written above a component +trait, it means one *cannot find attribute* resolution error per generated item, none of which mentions `#[cgp_component]`. Read the repetition as the signal: it is the same error a typo in an attribute name gives, so the fix is to move the attribute rather than to add an import. diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index dcd9b9b9..a43b426c 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_computer]' +sidebar_position: 13 --- # `#[cgp_computer]` diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 7ef4aed6..2e9c05ab 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_fn]' +sidebar_position: 3 --- # `#[cgp_fn]` @@ -200,7 +201,7 @@ Reach for something else in three cases. when it needs values. - **A generic must vary per call.** A generic parameter here goes on the trait rather than the method, so it is fixed by whatever satisfies the bounds for a given context rather than chosen at each call - site. A capability that genuinely needs a per-call type parameter wants a hand-written blanket impl + site. A capability that needs a per-call type parameter wants a hand-written blanket impl or a component. One decision inside the macro is worth making deliberately rather than by default: **where a type the @@ -299,8 +300,7 @@ Two smaller placements are worth knowing because neither is visible in the sourc function's visibility becomes the trait's**, and the impl's method keeps inherited visibility. So `pub fn rectangle_area` yields `pub trait RectangleArea`, and a private `fn` yields a private trait usable only in its own module. And **the macro copies an attribute it does not recognize onto both -items**, which lets `#[allow(...)]`, `#[doc]`, or a doc comment ride through and apply to the trait and -the impl alike. +items**, so `#[allow(...)]`, `#[doc]`, or a doc comment carries onto the trait and the impl alike.
Formal grammar diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index b1e29093..ef05a5ae 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_getter]' +sidebar_position: 9 --- # `#[cgp_getter]` @@ -30,7 +31,7 @@ has moved into the wiring, where a context can change it without touching the tr it. **This is an advanced tool, not the next step up from `#[cgp_auto_getter]`.** What you pay for the -decoupling is a line of wiring per context, and what you get is only useful when a context genuinely needs +decoupling is a line of wiring per context, and what you get is only useful when a context needs to control which field is read, or to supply the value some way other than reading a field. Most getters want neither. The [When to reach for it](#when-to-reach-for-it-and-when-not) section draws the line. diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 90b0c07a..fb896868 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_impl]' +sidebar_position: 2 --- # `#[cgp_impl]` @@ -143,8 +144,9 @@ there are more than two or three blocks, since a reader does not have to find th of every block still reads as an ordinary trait impl. **A struct whose shape `new` cannot express must be declared explicitly, because `new`'s own grammar is -narrow.** `#[cgp_impl(new ...)]` desugars to [`#[cgp_new_provider]`](./cgp_new_provider.md), and that -macro can only emit one of two shapes: a plain provider name becomes a unit struct with no fields, and +narrow.** `#[cgp_impl(new ...)]` desugars to +[`#[cgp_new_provider]`](./cgp_provider.md#the-struct-cgp_new_provider-declares), and that macro can +only emit one of two shapes: a plain provider name becomes a unit struct with no fields, and a generic provider becomes a tuple struct with one public [`PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html) field wrapping all of its generic parameters together, always `pub` and never with a default. Anything the struct needs outside @@ -264,7 +266,7 @@ that call for something else are narrower than they look. Prefer the unqualified header from [Usage](#usage), `impl AreaCalculator` with no `for Context`, letting the macro insert the context parameter, which keeps a provider reading like an ordinary trait -impl. Name the context explicitly only when the sugar genuinely falls short, such as a lifetime or a +impl. Name the context explicitly only when the sugar falls short, such as a lifetime or a higher-ranked bound. Naming a *concrete* type as that context, as in `impl AreaCalculator for Rectangle`, is a different @@ -426,9 +428,8 @@ apply to. Leave both out. ## Related constructs - [`#[cgp_component]`](./cgp_component.md) — defines the component this implements. -- [`#[cgp_provider]`](./cgp_provider.md) — the lower-level form `#[cgp_impl]` desugars to. -- [`#[cgp_new_provider]`](./cgp_new_provider.md) — `#[cgp_provider]` with the struct declared too, - equivalent to `#[cgp_impl(new ...)]`. +- [`#[cgp_provider]` and `#[cgp_new_provider]`](./cgp_provider.md) — the lower-level forms `#[cgp_impl]` + desugars to, the latter equivalent to `#[cgp_impl(new ...)]`. - [`#[cgp_fn]`](./cgp_fn.md) — the lighter alternative when one implementation is enough. - [`delegate_components!`](./delegate_components.md) — wires the provider onto a type. - [`check_components!`](./check_components.md) — verifies the wiring resolves. diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 689aaf65..8abc8d2e 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -1,5 +1,6 @@ --- sidebar_label: 'cgp_namespace!' +sidebar_position: 10 --- # `cgp_namespace!` @@ -8,8 +9,8 @@ Define a reusable, inheritable wiring table that many contexts can join. ## Overview -With [`delegate_components!`](./delegate_components.md) alone, every **context** — the type the capability -runs against, which supplies the values it needs as its fields — spells out its own wiring entry by entry. +With [`delegate_components!`](./delegate_components.md) alone, every **context** (the type the capability +runs against, which supplies the values it needs as its fields) spells out its own wiring entry by entry. Two contexts that should share the same providers repeat the same lines, and a table grows with the number of components until the wiring is the largest thing in the file. @@ -25,7 +26,7 @@ cgp_namespace! { A context then **joins** it with one line inside its own table, after which every lookup it does not wire directly falls through to the namespace. Its own entries win, so a namespace behaves like a base -configuration each context specializes — most of the wiring for free, and a handful of overrides where they +configuration each context specializes: most of the wiring for free, and a handful of overrides where they matter. That inherit-and-override behaviour is why **a namespace is how CGP expresses presets.** There is no @@ -33,8 +34,8 @@ separate preset construct: a library publishes a namespace of sensible defaults, changes the few entries it cares about. Namespaces can also inherit from one another, so a base can be extended into a richer one that every downstream context picks up. -One structural point saves confusion later: **a namespace is not a context.** It is a trait — named after -the namespace — carrying a `Delegate` associated type and implemented once per key. Nothing instantiates it, +One structural point saves confusion later: **a namespace is not a context.** It is a trait, named after +the namespace, carrying a `Delegate` associated type and implemented once per key. Nothing instantiates it, and it holds no wiring of its own at the context level; it only says where a lookup should go next. ## Usage @@ -62,31 +63,31 @@ A namespace body accepts two kinds of entry, and they do different things. | `Key => @path` | **Redirect.** Asked for `Key`, look up `@path` instead. The provider is decided wherever the path lands. | | `Key: Provider` | **Bind.** Asked for `Key`, resolve straight to `Provider`, as in `delegate_components!`. | -Redirection is what makes namespaces composable: because a lookup is keyed by a *path* rather than a bare +Redirection makes namespaces composable: because a lookup is keyed by a *path* rather than a bare component name, a whole subtree can be rerouted at once, and a more specific path takes precedence over an -inherited one. Paths are written with the `@` sigil as dotted sequences — `@MyFooComponent`, -`@app.ErrorRaiserComponent`, `@cgp.core.error` — where lowercase segments become type-level strings and +inherited one. Paths are written with the `@` sigil as dotted sequences, such as `@MyFooComponent`, +`@app.ErrorRaiserComponent`, and `@cgp.core.error`, where lowercase segments become type-level strings and capitalized segments name types. [`Path!`](./path.md) covers the syntax in full. ### The rest of the body grammar **A namespace body is parsed by the same code as a [`delegate_components!`](./delegate_components.md) table**, so everything that macro accepts parses here: -all three operators, all three key forms — including bracketed list keys and `@`-path keys with their -`[…]` and `{…}` groups — per-key generics, and the leading `open`, `namespace`, and `for` statements. That +all three operators, all three key forms (including bracketed list keys and `@`-path keys with their +`[…]` and `{…}` groups), per-key generics, and the leading `open`, `namespace`, and `for` statements. That page documents each of them; what follows is only what differs here. -What differs is what an entry becomes. A `delegate_components!` entry records a choice *for a context*; a +The entry itself means something different. A `delegate_components!` entry records a choice *for a context*; a namespace entry records where a lookup for a key should *go next*, for any context that later joins. That is why the two forms in the table above are the ones worth writing, and why the others are mostly not: - **`->` direct delegation** still projects through the *value's* own table, so it names a concrete table inside a definition that is meant to be table-generic. -- **`open Component;`** is accepted and generates exactly what `Component => @Component,` generates — +- **`open Component;`** is accepted and generates exactly what `Component => @Component,` generates; it is occasionally a convenient spelling for rooting a component's route at its own name. - **`namespace Other;`** is accepted, but inheritance is written with the `: ParentNamespace` header above. That is the form overriding and the cycle diagnostics are defined in terms of. -- **A nested table value** — `UseDelegate` — works, and is the one legacy form with a +- **A nested table value**, `UseDelegate`, works, and is the one legacy form with a reason to live in a namespace: the macro lifts the inner table out into its own struct and impls, so every context joining the namespace inherits the per-type dispatch without restating it. It still needs [`#[derive_delegate]`](../attributes/derive_delegate.md) on the component, as it does anywhere. @@ -135,7 +136,7 @@ delegate_components! { ``` A third statement form, `for in SomeTable { … }`, reads each entry of another lookup table and -emits one mapping per entry — which is how per-type defaults are pulled in wholesale. +emits one mapping per entry, which is how per-type defaults are pulled in wholesale. ## Examples @@ -182,7 +183,7 @@ check_components! { ``` Reading the resolution: `MyApp.show()` looks up `ShowImplComponent`, finds no direct entry, falls through to -`AppNamespace`, which redirects to the path `@show.ShowImplComponent` — and `MyApp`'s own table binds that +`AppNamespace`, which redirects to the path `@show.ShowImplComponent`, and `MyApp`'s own table binds that path to `ShowWithDebug`. **The division of labour is the point.** The namespace owns the *route*; the context owns the *provider*. A second context joins the same namespace and supplies a different provider at the same path, with nothing duplicated between them. @@ -208,7 +209,7 @@ delegate_components! { **Reach for a namespace when the same wiring is repeated across contexts, or when a top-level table has grown too long to read.** Those are the two problems it solves, and below that threshold it costs more than -it saves — a namespace adds a layer of indirection between a component and its provider, which is one more +it saves: a namespace adds a layer of indirection between a component and its provider, which is one more hop for a reader tracing what runs. Three lighter tools cover most cases, and it is worth knowing where each stops. @@ -217,16 +218,16 @@ Three lighter tools cover most cases, and it is worth knowing where each stops. is short and not shared. Most applications never outgrow this. - **The [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement)** is the lightweight special case of the same path machinery, for dispatching *one* component on its type parameter - directly on a context. It needs no namespace, no prefix, and no shared table — reach for it when the goal + directly on a context. It needs no namespace, no prefix, and no shared table; reach for it when the goal is per-type dispatch rather than shared wiring. -- **An [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time)** — the - `new`-keyword bundle — packages a group of wirings that contexts adopt by *delegating* named components to +- **An [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time)**, the + `new`-keyword bundle, packages a group of wirings that contexts adopt by *delegating* named components to it, rather than by joining and inheriting. It is the more direct mechanism and the better choice for a small, explicitly-delegated bundle. A namespace earns its extra machinery when there are many components, when inheritance is wanted, or when a library is publishing defaults for applications it does not know about. -Two things a namespace is *not* for. It will not make a single context's wiring shorter on its own — the +Two things a namespace is *not* for. It will not make a single context's wiring shorter on its own; the entries still have to exist somewhere. And it is not how one component gets per-type dispatch, which is `open`'s job; the two do not combine on the same component, as the [Gotchas](#gotchas) explain. @@ -244,7 +245,7 @@ code. ::: `cgp_namespace!` emits, in order, an optional backing struct, an optional lookup trait, and one impl of that -trait per entry — plus one inheritance impl when a parent is named. From this input: +trait per entry, plus one inheritance impl when a parent is named. From this input: ```rust cgp_namespace! { @@ -276,7 +277,7 @@ impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { ``` Read it back as: `MyNamespace`'s delegate for `FooProviderComponent` is "look up the path `MyFooComponent` -inside whatever `__Table__` is". The namespace names no provider — it only reroutes, so the provider is +inside whatever `__Table__` is". The namespace names no provider; it only reroutes, so the provider is decided wherever the path finally lands. A `:` entry skips the indirection and maps the key straight to a provider, one impl per key when the array form is used. @@ -310,7 +311,7 @@ after this impl and win where their keys are more specific. Two naming details appear verbatim in errors and are worth recognizing: the table parameter is literally `__Table__`, and the inheritance impl uses `__Key__` and `__Value__`. And every `@` path is a -[type-level list](../types/type_level_spines.md) built by [`Path!`](./path.md) — `expand` resugars it to +[type-level list](../types/type_level_spines.md) built by [`Path!`](./path.md); `expand` resugars it to `Path!(@…)` form, while a raw compiler error prints the underlying spine.
@@ -329,15 +330,15 @@ NamespaceBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? ``` `NamespaceBody` is [`delegate_components!`](./delegate_components.md)'s `TableBody` production unchanged, -so its `Statement` and `Mapping` rules — every operator, every key form, every value form — are defined on -that page rather than restated here. The two a namespace normally uses are `=>` to an `@`-path and `:` to a -provider. The `:` between `NamespaceName` and `ParentNamespace` is the inheritance colon, distinct from a +so its `Statement` and `Mapping` rules, covering every operator, every key form, and every value form, are +defined on that page rather than restated here. The two a namespace normally uses are `=>` to an `@`-path +and `:` to a provider. The `:` between `NamespaceName` and `ParentNamespace` is the inheritance colon, distinct from a mapping's. `NamespaceName` becomes both a trait and, with `new`, a struct. Two of the three statement forms in that shared production exist for this macro, because their job is -joining a context's table to a namespace. A `NamespaceStmt` — `namespace SomeNamespace;` — forwards every -unwired lookup through the named namespace. A `ForStmt` — -`for in SomeTable where … { … }` — binds a key variable and a provider variable, reads each +joining a context's table to a namespace. A `NamespaceStmt`, `namespace SomeNamespace;`, forwards every +unwired lookup through the named namespace. A `ForStmt`, +`for in SomeTable where … { … }`, binds a key variable and a provider variable, reads each entry of the table named after `in`, and emits one mapping per entry; its body admits only the `:` form, and its optional `where` clause is merged into every impl the loop generates. Like `delegate_components!`, the body accepts **no attributes** on any entry and rejects any it finds. @@ -352,7 +353,7 @@ NamespacePath -> TypePath GenericArgs? ``` `Path` is [`Path!`](./path.md)'s own `@`-prefixed dotted production, so its segments take no generics and -neither grouping form is accepted — one attribute registers under exactly one prefix, and the attribute +neither grouping form is accepted: one attribute registers under exactly one prefix, and the attribute is repeated to register into several namespaces. `NamespacePath` may itself be parameterized.
@@ -362,23 +363,23 @@ is repeated to register into several namespaces. `NamespacePath` may itself be p **A context cannot override a path its namespace itself terminates.** Joining with `namespace N;` emits a blanket `DelegateComponent` impl covering every path `N` resolves, so a direct entry for one of those paths is a second impl for the same key and the compiler rejects the overlap with `E0119`. Overriding works only on -a path the namespace *routes to* without binding — which is why the example above has the namespace own the +a path the namespace *routes to* without binding, which is why the example above has the namespace own the route and the context own the provider. A path the namespace binds with a `:` entry or a `#[default_impl]` has to be changed in the namespace instead. The same restriction stops a child namespace from redefining a key its parent binds. -**Joining two namespaces on one context conflicts**, for the same reason — two blanket forwarding impls each -covering every key: +**Joining two namespaces on one context conflicts, for the same reason.** Each namespace produces a blanket +forwarding impl covering every key, so joining two collides them: ```text error[E0119]: conflicting implementations of trait `DelegateComponent<_>` for type `App` ``` A bare-key `for` loop (`for in Table { Key: Value }`) alongside a `namespace` join collides the -same way, which is why a loop's key is normally embedded in a path — `@app.SomeComponent.Key: Value`. +same way, which is why a loop's key is normally embedded in a path, as in `@app.SomeComponent.Key: Value`. **`open` does not combine with a prefixed component in a joined namespace.** Once a component's lookups are -routed under a prefix, `open` — which roots the route at the bare component name — no longer reaches those +routed under a prefix, `open`, which roots the route at the bare component name, no longer reaches those entries. Write the per-value entries with the full prefixed path instead. **A cyclic parent chain and a self-inheriting namespace fail differently.** Two namespaces inheriting each @@ -390,7 +391,7 @@ error[E0275]: overflow evaluating the requirement `__Key__: A<__BComponents>` note: required for `__Key__` to implement `B<__AComponents>` ``` -A namespace inheriting *itself* — `new A: A {}` — does not overflow. It produces a forwarding impl whose +A namespace inheriting *itself*, as in `new A: A {}`, does not overflow. It produces a forwarding impl whose value parameter nothing can determine: ```text @@ -409,7 +410,7 @@ error[E0277]: the trait bound `PathCons>, ...>: AppNam is not satisfied ``` -The `Symbol<4, …>` is the prefix — `show` — so the message is saying "this route is not something the +The `Symbol<4, …>` is the prefix, `show`, so the message is saying "this route is not something the namespace resolves". This is the lazy-wiring problem in namespace clothing, and the answer is the same: check the context. diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 10da9c2e..f9b52ba7 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_producer]' +sidebar_position: 14 --- # `#[cgp_producer]` @@ -24,8 +25,8 @@ That produces the provider struct `MagicNumber` and an impl of [`Producer`](../c family member whose method takes only a **context** (the type the capability runs against) and a phantom `Code` tag, with no input value at all. -Here is what makes a dedicated macro worth having. **A producer can stand in for any handler**, -because a handler that ignores its input is just a producer with an unused parameter. So the macro wires the +A dedicated macro is worth having because **a producer can stand in for any handler**: a handler that +ignores its input is just a producer with an unused parameter. So the macro wires the generated provider into every member of the family, and one function definition answers `produce`, `compute`, `try_compute`, `compute_async`, `handle`, and their by-reference forms, every one of them yielding the same value regardless of what it is handed. @@ -126,7 +127,7 @@ within it there is nothing simpler. - **Use [`ReturnInput`](../providers/handler_combinators.md) rather than a producer that ignores its input.** If the goal is to pass a value through a pipeline unchanged, that combinator says so directly. - **Do not reach for the handler family at all for a plain constant.** A `const` or a function is clearer - unless the value is genuinely being composed into a pipeline or dispatched on a `Code` tag. + unless the value is being composed into a pipeline or dispatched on a `Code` tag. ## Under the hood @@ -245,7 +246,7 @@ producer try_compute = Ok(Err("nope")) ``` That `Ok(Err(..))` is a success carrying an error, so it short-circuits nothing and a pipeline downstream -keeps going. If the production can genuinely fail, write a `TryComputer` or `Handler` provider by hand +keeps going. If the production can fail, write a `TryComputer` or `Handler` provider by hand instead. **The fallible forms still need an error type on the context.** `try_compute` and `handle` name the context's diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 28830522..9885d372 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' +sidebar_position: 20 --- # `#[cgp_provider]` & `#[cgp_new_provider]` @@ -189,7 +190,7 @@ the source. source that reads like an ordinary trait impl, so it is the recommended form. You mostly *read* these two instead: in generated code, in a desugaring, and in CGP's own crates. -Two cases genuinely call for writing the raw form yourself. +Two cases call for writing the raw form yourself. - **You need the inside-out provider-trait shape itself**, not merely a separately-declared struct: a bound `#[cgp_impl]`'s sugar cannot express, or a rare construct its rewrite does not support, whether @@ -204,7 +205,7 @@ Two cases genuinely call for writing the raw form yourself. - **Reading, rather than writing.** A confusing provider error names types from this shape, and `cargo cgp expand` prints it. Recognizing the form is the main reason to read this page. -Once you are genuinely writing the raw form, the choice between the two macros here is mechanical: +Once you are writing the raw form, the choice between the two macros here is mechanical: `#[cgp_new_provider]` when the provider struct is new, `#[cgp_provider]` when it already exists. There is no other difference, and using the wrong one is a duplicate-definition error rather than anything subtle. @@ -352,7 +353,7 @@ layer of such a stack is at fault. Components without lifetime parameters are un not belong to the provider trait you are implementing produces a marker impl for the wrong key, so the provider silently fails to satisfy the wiring that names it. The error appears at the wiring site, saying the provider is not a provider for that component. Omit the argument unless the trait's name -genuinely departs from the `{Trait}Component` convention. +departs from the `{Trait}Component` convention. **A provider's own associated const or type still needs qualifying**, though for a different reason than in [`#[cgp_impl]`](./cgp_impl.md#gotchas). Here `Self` really is the provider, and nothing rewrites it. diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index b198f952..a48639ce 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[cgp_type]' +sidebar_position: 7 --- # `#[cgp_type]` @@ -51,7 +52,7 @@ pub trait HasScalarType { ``` Like [`#[cgp_component]`](./cgp_component.md), the component needs a provider trait name, and -`#[cgp_type]` derives one. **The default is keyed off the associated type's name, not the trait's** — +`#[cgp_type]` derives one. **The default is keyed off the associated type's name, not the trait's**: `type Scalar` yields the provider trait `ScalarTypeProvider` and the marker `ScalarTypeProviderComponent`. This is worth fixing in mind, because every other macro derives its default from the trait name. @@ -80,8 +81,8 @@ pub trait HasScalarType { } ``` -A context whose wiring names a type that does not satisfy the bound is rejected — `UseType` here, -since `String` is not `Copy` — so the bound is written once on the declaration and enforced against every +A context whose wiring names a type that does not satisfy the bound is rejected (`UseType` here, +since `String` is not `Copy`), so the bound is written once on the declaration and enforced against every context's choice. **It is enforced lazily, though, like all CGP wiring.** The `delegate_components!` entry naming @@ -119,7 +120,7 @@ where ``` `App` implements `HasScalarType` with `Scalar = f64` through the generated -[`UseType`](../providers/use_type.md) impl, and the `check_components!` block is what confirms `f64` satisfies +[`UseType`](../providers/use_type.md) impl, and the `check_components!` block confirms that `f64` satisfies the `Copy` bound. The point compounds when several pieces of code share one type. Because the type lives on a trait the @@ -134,7 +135,7 @@ pub trait CanCalculateArea { } ``` -Here `Rectangle` and `Circle` carry no scalar type of their own — the context computing their areas does, +Here `Rectangle` and `Circle` carry no scalar type of their own; the context computing their areas does, and changing its `UseType` to `UseType` changes the scalar for every shape at once. The bare `Scalar` in that signature is [`#[use_type]`](../attributes/use_type.md) at work, which is how an abstract type is *imported* wherever it is used. @@ -150,7 +151,7 @@ impl HasScalarType for App { ## When to reach for it, and when not **Reach for `#[cgp_type]` whenever generic code has to name a type the context should choose.** The error -type is the canonical instance — CGP's own [`HasErrorType`](../components/has_error_type.md) is defined +type is the canonical instance. CGP's own [`HasErrorType`](../components/has_error_type.md) is defined exactly this way, which is why every fallible capability can say `Error` and mean whatever the application picked. @@ -167,12 +168,12 @@ there is a cheaper option covering more ground than it looks. inferred parameter can do neither, since it exists only where a value of it passes through. - **Never thread it as a generic parameter on the capability.** A parameter is an input the caller supplies, so it lands in every intermediate signature whether that layer touches the type or not. An - abstract type is determined by the context and propagates nowhere. That difference is what the - construct is really buying, and it is why a context can decide a dozen types without any signature + abstract type is determined by the context and propagates nowhere. That difference is the whole + payoff of the construct, and it is why a context can decide a dozen types without any signature growing. - **Use plain [`#[cgp_component]`](./cgp_component.md) when the trait carries methods.** `#[cgp_type]` is only for a trait whose entire content is one associated type. A trait with a method *and* a type it - produces is an ordinary component — CGP's own `CanCompute` is that shape. + produces is an ordinary component; CGP's own `CanCompute` is that shape. One alternative looks like this construct and is not. A getter written with [`#[cgp_auto_getter]`](./cgp_auto_getter.md) may declare an associated type and return it, inferring it @@ -192,9 +193,9 @@ written. `cargo cgp expand` prints the same thing for your own code. ::: `#[cgp_type]` emits everything [`#[cgp_component]`](./cgp_component.md) would, then adds two provider -impls of its own. The component half is the familiar shape — consumer trait, provider trait, two blanket +impls of its own. The component half is the familiar shape: consumer trait, provider trait, two blanket impls, marker, and the standard [`UseContext`](../providers/use_context.md) and -[`RedirectLookup`](../providers/redirect_lookup.md) impls — differing only in that every blanket impl +[`RedirectLookup`](../providers/redirect_lookup.md) impls, differing only in that every blanket impl forwards an *associated type* rather than a method: ```rust @@ -219,7 +220,7 @@ where Read it as: `UseType` is a provider that supplies `T`. Wiring a context's component to `UseType` therefore gives it `Scalar = f64` with nothing written. Note the declaration's `Copy` bound copied into -the impl's `where` clause — that is what turns an unsuitable concrete type into an error where the wiring +the impl's `where` clause: it turns an unsuitable concrete type into an error where the wiring names it. The second addition is a [`WithProvider`](../providers/with_provider.md) impl, which adapts CGP's @@ -237,7 +238,7 @@ where ``` [`HasType` / `TypeProvider`](../components/has_type.md) is CGP's single built-in abstract-type component, -and `UseType` is itself a `TypeProvider`. This impl is what lets one `UseType` satisfy both the +and `UseType` is itself a `TypeProvider`. This impl lets one `UseType` satisfy both the built-in component and any `#[cgp_type]` component you declare, instead of needing a separate provider per component. @@ -246,7 +247,7 @@ Each generated provider impl is paired with a matching A bound that names the type it constrains is rewritten rather than refused. Declaring `type Scalar: Mul + Clone;` leaves the bound as written on the two traits, where -`Self::Scalar` still means what it says — but the copy landing on the `UseType` and `WithProvider` impls +`Self::Scalar` still means what it says. But the copy landing on the `UseType` and `WithProvider` impls becomes `Scalar: Mul + Clone`, with every `Self::Scalar` replaced by the free parameter. Copied unchanged it would have named an associated type of the wrong `Self`. @@ -276,7 +277,7 @@ second type, or no type at all all report the same thing: error: type trait should contain exactly one associated type item ``` -A trait that genuinely needs a method alongside a type it produces is an ordinary +A trait that needs a method alongside a type it produces is an ordinary [`#[cgp_component]`](./cgp_component.md). **The associated type may not be generic or carry a `where` clause**, since the `UseType` impl supplies @@ -287,7 +288,7 @@ error: generic associated type and where clause are not supported ``` **The default provider name comes from the type, not the trait.** `HasScalarType` declaring -`type Scalar` yields `ScalarTypeProviderComponent`, not `HasScalarTypeComponent` — so a wiring entry +`type Scalar` yields `ScalarTypeProviderComponent`, not `HasScalarTypeComponent`, so a wiring entry guessed from the trait name names a component that does not exist, and the error is an unresolved type rather than anything about wiring. diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 088ac310..a7f32e8f 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -1,5 +1,6 @@ --- sidebar_label: 'check_components!' +sidebar_position: 5 --- # `check_components!` @@ -360,7 +361,7 @@ parameters: error[E0277]: the trait bound `App: CanUseComponent` is not satisfied ``` -That looks identical to a genuinely broken wiring. If a check fails on a generic component and the wiring +That looks identical to a broken wiring. If a check fails on a generic component and the wiring looks right, the missing value is the first thing to suspect. **`#[check_providers(...)]` must list at least one provider**, and is rejected rather than treated as a diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 104c3ffa..d9fe3514 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -1,5 +1,6 @@ --- sidebar_label: 'delegate_and_check_components!' +sidebar_position: 6 --- # `delegate_and_check_components!` diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index f51ab602..4e71dbb6 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -1,5 +1,6 @@ --- sidebar_label: 'delegate_components!' +sidebar_position: 4 --- # `delegate_components!` diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md new file mode 100644 index 00000000..6d43b439 --- /dev/null +++ b/docs/reference/macros/index.md @@ -0,0 +1,64 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Macros + +CGP's procedural macros fall into three jobs: defining a component and writing the providers that +implement it, wiring a concrete type to the providers it uses and checking that wiring holds, and +building the type-level values (strings, lists, paths) that the rest of the system runs on. This +page groups every macro in this section by which of the three it does, in roughly the order most CGP +code reaches for them. + +If you are new to CGP, start with the [reference overview](/docs/reference/)'s six essentials rather +than here; this page is the fuller map for once those six are familiar. + +## Defining a component, and writing its providers + +[`#[cgp_component]`](./cgp_component.md) is the macro every wired capability starts from: it turns one +trait into the consumer trait callers use, the provider trait implementations target, and the marker +that wiring keys against. A provider is then written with [`#[cgp_impl]`](./cgp_impl.md), which keeps +`self`, `Self`, and the consumer trait's own method signatures; [`#[cgp_provider]` and +`#[cgp_new_provider]`](./cgp_provider.md) are the lower-level forms underneath it, mostly met in +generated code rather than written by hand. + +When a capability has exactly one implementation and needs no wiring at all, +[`#[cgp_fn]`](./cgp_fn.md) builds it straight from a function, and +[`#[blanket_trait]`](./blanket_trait.md) does the same starting from a trait with default methods and +supertrait dependencies. [`#[async_trait]`](./async_trait.md) is how any of these traits declares an +`async fn` without tripping the lint a bare one produces. + +Three macros specialize `#[cgp_component]` for a narrower job. [`#[cgp_type]`](./cgp_type.md) is for a +component that supplies a type a context chooses rather than a value it computes. +[`#[cgp_auto_getter]`](./cgp_auto_getter.md) publishes a context field as a named accessor with a +blanket impl and no wiring, and [`#[cgp_getter]`](./cgp_getter.md) is its wireable counterpart, for the +rarer case where a context needs to choose which field a getter reads. + +Three more build a provider from a plain function for CGP's computation family. +[`#[cgp_computer]`](./cgp_computer.md) and [`#[cgp_producer]`](./cgp_producer.md) wire one function to +answer every member of that family at once, synchronous, async, fallible, and infallible alike, and +[`#[cgp_auto_dispatch]`](./cgp_auto_dispatch.md) generates a handler that routes an extensible-data +input to a per-type trait's own implementations. + +## Wiring a type, and checking that wiring + +[`delegate_components!`](./delegate_components.md) is where a concrete type says which provider +answers each component, in a table that is a compile-time fact rather than a runtime lookup. Because +that wiring is lazy, [`check_components!`](./check_components.md) forces a missing or broken +choice to fail at the table rather than wherever the capability is finally called, and +[`delegate_and_check_components!`](./delegate_and_check_components.md) fuses the two for a newcomer or +a simple table, so the check cannot be forgotten. [`cgp_namespace!`](./cgp_namespace.md) lifts a table +out of any one type and gives it a name other types can join, which is how CGP expresses reusable +presets without a separate construct for them. + +## Building type-level values + +[`Symbol!`](./symbol.md) turns a string literal into a type-level field-name tag, +[`Product!`](./product.md) and its value-level twin `product!` build a type-level list for a struct's +fields or a handler pipeline's steps, [`Sum!`](./sum.md) builds the dual list for an enum's variants, +and [`Path!`](./path.md) builds the routing list that namespaces and redirected lookups resolve +against. All four are mostly generated for you, by a derive, by the ergonomic macros above, or by the +`open` statement inside `delegate_components!`, and the skill worth having is reading one back out of +a compiler error rather than writing it, since a diagnostic actually prints the raw spine each expands +to (`Cons`/`Nil`, `Either`/`Void`, `PathCons`). diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index e44d7466..c65993f0 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -1,5 +1,6 @@ --- sidebar_label: 'Path!' +sidebar_position: 19 --- # `Path!` diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 01fbf40d..7f060827 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -1,5 +1,6 @@ --- sidebar_label: 'Product! & product!' +sidebar_position: 17 --- # `Product!` & `product!` @@ -153,7 +154,7 @@ Cons(a, Cons(b, Cons(c, Nil))) ``` Because `Cons` is a real struct and `Nil` a real unit struct, the result is an ordinary owned value whose type -exactly matches what `Product!` builds over the same elements' types. There is no magic layer between the two +exactly matches what `Product!` builds over the same elements' types. There is no hidden layer between the two macros: they are the same fold at two levels. **What this means for reading errors**: a mismatched field list is reported as a mismatch between two `Cons` diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 6ae65770..7f4ca00c 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -1,5 +1,6 @@ --- sidebar_label: 'Sum!' +sidebar_position: 18 --- # `Sum!` diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 7121856c..3da47727 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -1,5 +1,6 @@ --- sidebar_label: 'Symbol!' +sidebar_position: 16 --- # `Symbol!` @@ -119,7 +120,7 @@ assert_eq!(s.to_string(), "hello"); ## When to reach for it, and when not **Write `Symbol!` when a wiring entry has to name a field**, and let the macros produce it everywhere else. -That is the honest summary: the construct is load-bearing and mostly generated. +That is the honest summary: the construct is essential and mostly generated. - **Use an [`#[implicit]`](../attributes/implicit.md) argument to read a field.** The parameter's name becomes the tag, so you never type one. @@ -132,7 +133,7 @@ That is the honest summary: the construct is load-bearing and mostly generated. Two things it is not. It is **not a runtime string**: there is no `&str` inside it, and the `Display` impl above reconstructs the text from the type rather than reading a stored value. And it is **not a general type-level string facility** to build programs out of; it exists to key field and variant lookups, and the -[`StaticFormat`](../traits/static_format.md) traits recover text from one when that is genuinely +[`StaticFormat`](../traits/static_format.md) traits recover text from one when that is needed. ## Under the hood From 0edbce9e80b8062cc5400e78011f4b2b5b84d9a5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 22 Aug 2026 16:24:09 +0200 Subject: [PATCH 037/516] Use realistic examples in delegate_components!, trim Under-the-hood notices Replace every Foo/Bar/Baz/Quux/Dummy placeholder in delegate_components.md with names drawn from the geometry vocabulary this page and its siblings already use (AreaCalculatorComponent, RectangleGeometry, GeometryComponents, and so on), each verified against the internal reference for accuracy. The direct-delegation example no longer keys on Index or repeats one table as both branches: ScaledGeometryComponents now names a scaled calculator outright for area while forwarding perimeter to the plain GeometryComponents bundle, a motivated pairing instead of an arbitrary one. Shrink the legacy UseDelegate notice from a box wrapping the whole subsection to a short two-sentence one, matching the pattern already used on derive_delegate.md, with the explanation and examples flowing as ordinary content below it instead of inside the box. Remove the boxed "Advanced" preamble from the Under-the-hood section on every macro reference page. The heading itself already says as much, and the box repeated the same three sentences with the macro name swapped in on all 20 pages. Co-Authored-By: Claude Sonnet 5 --- docs/reference/macros/async_trait.md | 9 -- docs/reference/macros/blanket_trait.md | 10 -- docs/reference/macros/cgp_auto_dispatch.md | 10 -- docs/reference/macros/cgp_auto_getter.md | 10 -- docs/reference/macros/cgp_component.md | 11 -- docs/reference/macros/cgp_computer.md | 11 -- docs/reference/macros/cgp_fn.md | 10 -- docs/reference/macros/cgp_getter.md | 11 -- docs/reference/macros/cgp_impl.md | 10 -- docs/reference/macros/cgp_namespace.md | 11 -- docs/reference/macros/cgp_producer.md | 11 -- docs/reference/macros/cgp_provider.md | 10 -- docs/reference/macros/cgp_type.md | 10 -- docs/reference/macros/check_components.md | 10 -- .../macros/delegate_and_check_components.md | 10 -- docs/reference/macros/delegate_components.md | 112 ++++++++---------- docs/reference/macros/path.md | 10 -- docs/reference/macros/product.md | 10 -- docs/reference/macros/sum.md | 10 -- docs/reference/macros/symbol.md | 10 -- 20 files changed, 52 insertions(+), 254 deletions(-) diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 96223544..7922f532 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -153,15 +153,6 @@ The decisions worth making are around it rather than about it. ## Under the hood -:::note - -### Advanced - -This section shows the rewrite. It is the simplest expansion in CGP, and worth seeing once because it explains -why a provider needs no attribute of its own. `cargo cgp expand` prints the same thing for your own code. - -::: - For each `async` method the macro removes the `async` keyword and wraps the return type in `impl ::core::future::Future`. A method with no return arrow is treated as returning `()`. From this input: diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 7ab588b8..8f519f4f 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -171,16 +171,6 @@ trait. Needing that is the signal to move to a component. ## Under the hood -:::note - -### Advanced - -This section shows the two items the macro emits. You do not need them to use `#[blanket_trait]`, but the -associated-type lifting is surprising the first time, and knowing what the impl requires makes an -"unsatisfied bound" error much easier to read. `cargo cgp expand` prints the same thing for your own code. - -::: - The macro emits the trait and a blanket impl over a generic context. From the method example: ```rust diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index cb5794b8..277ea62c 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -151,16 +151,6 @@ the operation from scratch and expect contexts to configure it, start with a ## Under the hood -:::note - -### Advanced - -This section shows what the macro generates. You do not need it to use `#[cgp_auto_dispatch]`, but an -unmet variant impl is reported against the generated bound, so reading it once makes that error -legible. `cargo cgp expand` prints the same thing for your own code. - -::: - The macro keeps the trait unchanged and appends two kinds of item: one per-method computer, and one blanket impl of the trait for a fresh enum parameter. diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 6ec87ac9..e45bd5d5 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -236,16 +236,6 @@ So the ordering is: implicit argument by default, `#[cgp_auto_getter]` for the t ## Under the hood -:::note - -### Advanced - -This section shows the blanket impl the macro generates. You do not need it to use `#[cgp_auto_getter]`, -but an unsatisfied getter names the generated bound rather than your method, so reading one makes that -error much easier to follow. `cargo cgp expand` prints the same thing for your own code. - -::: - The macro re-emits the trait unchanged and adds one blanket impl over a generic context. From this input: ```rust diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 2448c623..d99a7842 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -227,17 +227,6 @@ machinery. ## Under the hood -:::note - -### Advanced - -This section shows the code the macro generates. You do not need it to use `#[cgp_component]`, but -CGP's constructs are macros, and reading what one produces is the fastest way to understand a compiler -error that names a type you did not write. Running `cargo cgp expand` prints the same thing for your -own code. - -::: - From this input: ```rust diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index a43b426c..69d46a70 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -162,17 +162,6 @@ variants. A single transform with one caller is a method. ## Under the hood -:::note - -### Advanced - -This section shows the three items the macro emits, and how the promotion wiring makes one function answer -the whole family. You do not need it to use `#[cgp_computer]`, but the delegation block is unusual enough -that seeing it once explains a lot of handler errors. `cargo cgp expand` prints the same thing for your own -code. - -::: - The macro emits the function unchanged, a provider impl of the base trait, and a [`delegate_components!`](./delegate_components.md) block wiring the rest of the family. From this input: diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 2e9c05ab..1d0dce43 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -215,16 +215,6 @@ they touch it or not. ## Under the hood -:::note - -### Advanced - -This section shows the two items the macro generates. You do not need them to use `#[cgp_fn]`, but they -are what an unsatisfied field requirement names, so reading one makes those errors much easier to -follow. `cargo cgp expand` prints the same thing for your own code. - -::: - `#[cgp_fn]` emits exactly two items: the trait carrying the method, and a blanket impl of it for a generic context. From this input: diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index ef05a5ae..4bdd9fb8 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -178,17 +178,6 @@ Reach for something else in these cases. ## Under the hood -:::note - -### Advanced - -This section shows the getter-specific providers the macro adds. You do not need them to use -`#[cgp_getter]`, but the `UseField` impl makes the field name a wiring decision, and seeing it explains -why the tag is a parameter here and a fixed value in the auto-getter. `cargo cgp expand` prints the -same thing for your own code. - -::: - `#[cgp_getter]` emits everything [`#[cgp_component]`](./cgp_component.md) would: the consumer trait, the provider trait, the two blanket impls, the marker, and the standard [`UseContext`](../providers/use_context.md) and [`RedirectLookup`](../providers/redirect_lookup.md) diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index fb896868..fd014ba5 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -291,16 +291,6 @@ construct `#[cgp_impl]`'s rewrite does not support, whether from a limitation or ## Under the hood -:::note - -### Advanced - -This section shows what the macro generates. You do not need it to write a provider, but the rewrite -explains most confusing errors in a provider body, so it is worth seeing once. `cargo cgp expand` -prints the same thing for your own code. - -::: - `#[cgp_impl]` desugars to [`#[cgp_provider]`](./cgp_provider.md). It moves the context type to the leading position of the provider trait, swaps the provider name into the `Self` position, and rewrites every `self`/`Self`. From this input, with the context named explicitly for clarity: diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 8abc8d2e..1a51824b 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -233,17 +233,6 @@ entries still have to exist somewhere. And it is not how one component gets per- ## Under the hood -:::note - -### Advanced - -This section shows the trait and impls a namespace becomes. You do not need them to use one, but namespace -failures are reported in terms of these types, and the resolution is far easier to follow once you have seen -that a namespace is a trait with one associated type. `cargo cgp expand` prints the same thing for your own -code. - -::: - `cgp_namespace!` emits, in order, an optional backing struct, an optional lookup trait, and one impl of that trait per entry, plus one inheritance impl when a parent is named. From this input: diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index f9b52ba7..a9b7d282 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -131,17 +131,6 @@ within it there is nothing simpler. ## Under the hood -:::note - -### Advanced - -This section shows the three items the macro emits. You do not need them to use `#[cgp_producer]`, but the -delegation block makes one function answer eight components, and it differs from -[`#[cgp_computer]`](./cgp_computer.md)'s in a way worth noticing. `cargo cgp expand` prints the same thing for -your own code. - -::: - The macro emits the function unchanged, a provider impl of [`Producer`](../components/producer.md), and a [`delegate_components!`](./delegate_components.md) block wiring the whole family. From this input: diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 9885d372..3ea2cbde 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -212,16 +212,6 @@ subtle. ## Under the hood -:::note - -### Advanced - -This section shows the impls the macros emit. You do not need them to write a provider, but this is the -shape `#[cgp_impl]` desugars *to*, so reading it once explains most confusing provider errors. -`cargo cgp expand` prints the same thing for your own code. - -::: - `#[cgp_provider]` emits two items: your impl, passed through unchanged, and a marker impl derived from it. From this input: diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index a48639ce..77304ab4 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -182,16 +182,6 @@ wiring; `#[cgp_type]` is for a type that stands on its own. ## Under the hood -:::note - -### Advanced - -This section shows what the macro generates. You do not need it to use `#[cgp_type]`, but the `UseType` -impl is the piece that makes wiring a type possible, and seeing it explains why no provider has to be -written. `cargo cgp expand` prints the same thing for your own code. - -::: - `#[cgp_type]` emits everything [`#[cgp_component]`](./cgp_component.md) would, then adds two provider impls of its own. The component half is the familiar shape: consumer trait, provider trait, two blanket impls, marker, and the standard [`UseContext`](../providers/use_context.md) and diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index a7f32e8f..38e49b49 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -219,16 +219,6 @@ the unsatisfied bound, but you cannot ask for it directly. ## Under the hood -:::note - -### Advanced - -This section shows what a check table expands to. You do not need it to write one, but knowing that a check -is an empty impl explains both why it costs nothing at runtime and why its errors read the way they do. -`cargo cgp expand` prints the same thing for your own code. - -::: - A check table expands to one marker trait plus one empty impl per entry. The trait's supertrait *is* the assertion; the impl has nothing of its own to prove, so it compiles exactly when the supertrait holds. From this input: diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index d9fe3514..904bae1b 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -256,16 +256,6 @@ beginner-proof way to guarantee that for simple contexts; the two separate macro ## Under the hood -:::note - -### Advanced - -This section shows both halves of what the macro emits. You do not need it to use the macro, but seeing that -the output is literally the two macros concatenated makes a later move to separate blocks -uneventful. `cargo cgp expand` prints the same thing for your own code. - -::: - The macro emits the delegation impls exactly as [`delegate_components!`](./delegate_components.md) would, then appends a check trait and one impl per non-skipped entry exactly as [`check_components!`](./check_components.md) would. From this input: diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 4e71dbb6..f73c89f2 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -113,18 +113,20 @@ is how one table adopts a single choice from another rather than repeating it: ```rust delegate_components! { - new BarComponents { - Index<0>: - FooComponents, // the provider *is* FooComponents - Index<1> -> - FooComponents, // the provider is whatever FooComponents wires for Index<1> + new ScaledGeometryComponents { + AreaCalculatorComponent: + ScaledAreaCalculator, // the provider *is* this scaled calculator + PerimeterCalculatorComponent -> + GeometryComponents, // the provider is whatever GeometryComponents wires for perimeter } } ``` Those two lines are worth reading against each other, because the difference is easy to miss. The `:` -entry hands the whole lookup to `FooComponents`; the `->` entry reaches into `FooComponents`'s table -and copies out the one value it holds for that key. +entry names `ScaledAreaCalculator` outright, so `ScaledGeometryComponents` scales the +area calculation; the `->` entry reaches into `GeometryComponents`'s table and copies out whatever it +holds for `PerimeterCalculatorComponent`, so the perimeter is left exactly as `GeometryComponents` +already computes it, unscaled. **`=>` is redirection.** It sends the lookup along a type-level [path](./path.md) rather than to a provider, so the provider is decided wherever the path finally lands. On a context, that path names a @@ -134,10 +136,10 @@ from a single entry: ```rust delegate_components! { App { - [BarProviderComponent, BazProviderComponent] => + [AreaCalculatorComponent, PerimeterCalculatorComponent] => @shared, - @shared: DummyImpl, + @shared: RectangleGeometry, } } ``` @@ -149,8 +151,8 @@ concern more than a per-context one. ### The three key forms -**A single key** is one component name, and may carry generics of its own: ` BazKey: BazProvider` -adds a parameter to just that entry. +**A single key** is one component name, and may carry generics of its own: +` ShapeAreaCalculatorComponent: SumAreas` adds a parameter to just that entry. **A list key** is a bracketed list, expanding to one entry per name so several components share one value: @@ -159,17 +161,17 @@ value: delegate_components! { MyComponents { [ - FooComponent, - BarComponent, - ]: FooBarProvider, - BazComponent: BazProvider, + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: RectangleGeometry, + ColorComponent: SolidColor, } } ``` Each bracketed element is a full key, so an element may carry its own generics: in -`[BarKey, BazKey]: BarValue` only the second key introduces `T2`. The list is a -key form rather than an operator, so `[A, B] -> SomeTable` and `[A, B] => @somewhere` are as legal as +`[WidthKey, HeightKey]: RectangleValue` only the second key introduces `T2`. The +list is a key form rather than an operator, so `[A, B] -> SomeTable` and `[A, B] => @somewhere` are as legal as `[A, B]: Provider`; the first adopts several of another table's entries at once, the second points several components at one shared slot. @@ -184,8 +186,8 @@ becomes a type-level string, and anything else names a type. A segment may also Two grouping forms fan one path key out into several, and **they are not interchangeable**: - **`[…]` groups alternatives for one segment**, and the path may continue after it. - `@app.[FooComponent, BarComponent].[u64, String]: DummyImpl` writes four entries: the cartesian - product of the two groups. + `@app.[AreaCalculatorComponent, PerimeterCalculatorComponent].[u64, String]: RectangleGeometry` + writes four entries: the cartesian product of the two groups. - **`{…}` groups whole remainders**, and ends the path. Its elements may be different lengths and may nest further groups, which lets one entry cover routes of different shapes. @@ -212,10 +214,16 @@ exists, and it is legacy. :::info -### Legacy: read, don't write +### Legacy — read, don't write + +Older code dispatches per type by nesting a table inside a [`UseDelegate`](../providers/use_delegate.md) +value instead of using the `open` statement below. **Prefer `open` for anything new**: it needs no +separate table type and no wrapper. This form is here because you will meet it in existing code, +including in CGP's own error and handler components, which are still defined this way. + +::: -Older code dispatches per type by nesting a table inside a -[`UseDelegate`](../providers/use_delegate.md) value: +Nesting a table inside a `UseDelegate` value looks like this: ```rust delegate_components! { @@ -238,8 +246,8 @@ generics**, which a per-entry generic on the outer key threads into: ```rust delegate_components! { new MyComponents { - BarKey: UseDelegate { - BazKey: BazValue, + WidthKey: UseDelegate { + HeightKey: HeightValue, }>, } } @@ -250,13 +258,6 @@ One prerequisite is not visible in either snippet: **the component must carry dispatch impl the wrapper resolves through. Leave it off and the table still expands, then fails at the check with an unsatisfied `IsProviderFor` that never mentions the missing attribute. -This still works, and you will meet it, including in CGP's own error and handler -components, which are defined with `#[derive_delegate]`. The `open` statement below achieves the same -dispatch with no separate table type, no wrapper, and nothing added to the component, and is preferred -for new code. - -::: - ### Choosing a provider per type: the `open` statement When a component is generic over a type parameter, you usually want a different provider for each @@ -306,9 +307,9 @@ delegate_components! { App { open AreaCalculatorComponent; - BarProviderComponent -> BarBundle, + PerimeterCalculatorComponent -> GeometryComponents, - [BazProviderComponent, QuuxProviderComponent]: DummyBaz, + [ColorComponent, LabelComponent]: DefaultStyle, @AreaCalculatorComponent.{Rectangle, Circle}: ShapeArea, @@ -442,16 +443,6 @@ with how complicated the wiring is; that it is checked somehow does not. ## Under the hood -:::note - -### Advanced - -This section shows the impls each entry expands to. You do not need them to wire a context, but they -are what a wiring error names, so reading one makes those errors much easier to follow. -`cargo cgp expand` prints the same thing for your own code. - -::: - Each entry becomes a pair of impls. From the single-entry table above, first the [`DelegateComponent`](../traits/delegate_component.md) impl that records the choice: @@ -485,25 +476,26 @@ emitted code. **Every other form on this page lowers to that same pair.** What a form changes is how many pairs one line produces and what the `Delegate` type is. -**A list key repeats the pair per name.** A table pairing `[FooComponent, BarComponent]` with -`FooBarProvider`, alongside a `BazComponent: BazProvider` entry, yields three `DelegateComponent` impls -and three matching `IsProviderFor` impls. +**A list key repeats the pair per name.** A table pairing +`[AreaCalculatorComponent, PerimeterCalculatorComponent]` with `RectangleGeometry`, alongside a +`ColorComponent: SolidColor` entry, yields three `DelegateComponent` impls and three matching +`IsProviderFor` impls. **A `->` mapping projects through the value's table**, and adds the bound that makes the projection well-formed: ```rust -impl DelegateComponent> for BarComponents +impl DelegateComponent for ScaledGeometryComponents where - FooComponents: DelegateComponent>, + GeometryComponents: DelegateComponent, { - type Delegate = >>::Delegate; + type Delegate = >::Delegate; } ``` **A `=>` mapping wires a [`RedirectLookup`](../providers/redirect_lookup.md)** over the table and the -path. Against a plain key the path is complete, so `FooProviderComponent => @MyFooComponent` gives -`RedirectLookup`. Against a path key, both sides instead end in a shared +path. Against a plain key the path is complete, so `AreaCalculatorComponent => @shared` gives +`RedirectLookup`. Against a path key, both sides instead end in a shared wildcard parameter, so an entry like `@cgp.core.error => @app` rewrites one path prefix to another and passes everything beyond it through unchanged. @@ -545,9 +537,9 @@ the per-entry key as the raw spine. So the same kind of type appears in two spel **A grouped path key expands to the cartesian product**, one impl pair per combination, each keyed on a full prefix ending in `__Wildcard__`. So -`@app.[FooProviderComponent, BarProviderComponent].[u64, String]: DummyImpl` emits four pairs, and a -braced group does the same with whole tails rather than single segments, producing keys of different -lengths. +`@app.[AreaCalculatorComponent, PerimeterCalculatorComponent].[u64, String]: RectangleGeometry` emits +four pairs, and a braced group does the same with whole tails rather than single segments, producing +keys of different lengths. **A nested-table value lifts its inner table out** into its own definition, wiring the outer entry to `UseDelegate` over the generated type. So the legacy form is equivalent to writing two separate @@ -633,7 +625,7 @@ The three segment productions differ in what they permit, which is why they are along one path are merged onto that entry's impls. A `PathSegment` (inside a `PathValue`, the right-hand side of a `=>`) carries none, and admits no groups. It is [`Path!`](./path.md)'s own production, which keeps the two in step. And every `Generics` list on a key is an impl-position -list, so a bound is accepted (` BazKey: BazProvider`) and a parameter *default* is not: +list, so a bound is accepted (` WidthKey: WidthProvider`) and a parameter *default* is not: `` fails with `invalid impl generics syntax`. A `ProviderValue`'s nested-table form carries a full `TableBody`, so an inner table accepts every form @@ -671,8 +663,8 @@ The caret sits on the component being opened, so the message blames it rather th **`[…]` and `{…}` in a path are not the same group.** A bracketed group holds alternatives for one segment and may be followed by more path; a braced group holds whole tails and ends the path. So -`@FooProviderComponent.{String, u32}.bool: DummyFoo` does not parse, and the message says nothing about -groups: it reports the trailing `.bool` sitting where the operator should be: +`@AreaCalculatorComponent.{String, u32}.bool: RectangleGeometry` does not parse, and the message says +nothing about groups: it reports the trailing `.bool` sitting where the operator should be: ```text error: expected `:` @@ -687,9 +679,9 @@ names an unresolved type rather than anything about wiring. **Two entries claiming one key conflict**, and the compiler reports it as a coherence error rather than as a wiring one. This covers the obvious duplicate, an `open` header colliding with an explicit mapping -for the same component, and a generic ` Wrapper` entry overlapping a specific `Wrapper` one. -The same applies to a direct entry for a path a joined namespace itself binds: see -[`cgp_namespace!`](./cgp_namespace.md#gotchas). +for the same component, and a generic ` AreaCalculatorComponent` entry overlapping a +specific `AreaCalculatorComponent` one. The same applies to a direct entry for a path a +joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#gotchas). ## Related constructs diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index c65993f0..24fb4bd4 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -131,16 +131,6 @@ different things. ## Under the hood -:::note - -### Advanced - -This section shows the spine the macro builds. You do not need it to use `Path!`, but a namespace failure prints -the expanded path, so recognizing the shape lets you read which route came up empty. -`cargo cgp expand` resugars it back for your own code. - -::: - `Path!` expands to a right-nested chain of `PathCons` terminated by `Nil`, with each segment encoded by the lowercase-versus-capitalized rule: diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 7f060827..38243542 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -118,16 +118,6 @@ a provider list. Everywhere else it is generated for you. ## Under the hood -:::note - -### Advanced - -This section shows the spine both macros build. You do not need it to use them, but a compiler error prints -the expanded form, so recognizing it makes those errors readable. `cargo cgp expand` resugars it -back for your own code. - -::: - `Product!` expands to a right-nested chain of `Cons`, terminated by `Nil`: ```rust diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 7f4ca00c..ea9a7be6 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -101,16 +101,6 @@ use. ## Under the hood -:::note - -### Advanced - -This section shows the spine the macro builds, and why its terminator differs from `Product!`'s. You do not need -it to use `Sum!`, but the difference explains the exhaustiveness guarantee that the extensible-variant -machinery rests on. `cargo cgp expand` resugars it back for your own code. - -::: - `Sum!` expands to a right-nested chain of `Either`, terminated by `Void`: ```rust diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 3da47727..86a232c2 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -138,16 +138,6 @@ needed. ## Under the hood -:::note - -### Advanced - -This section shows what the macro expands to. You do not need it to use `Symbol!`, but the expanded form is -exactly what a compiler error prints, so reading it once turns an intimidating error into a legible one. -`cargo cgp expand` resugars it back for your own code. - -::: - `Symbol!("...")` expands to a `Symbol` type wrapping a `Chars` chain that spells the string one character at a time: From bd4702c553c4de8400490a6cea173bab534f2722 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 22 Aug 2026 21:45:46 +0200 Subject: [PATCH 038/516] docs(reference): revise attribute pages and apply reference-wide section conventions Revise docs/reference/attributes for the directness writing style and beginner-friendly overviews, add an Attributes overview page ordered by importance, and cross-link the abstract-types and modular-error-handling concepts. Apply three conventions across the whole reference: remove the Advanced admonition note, rename Gotchas to Common Mistakes (repointing every anchor), and turn Formal grammar into its own section. Co-Authored-By: Claude Opus 4.8 --- docs/reference/attributes/_category_.json | 4 +- docs/reference/attributes/default_impl.md | 74 ++++----- docs/reference/attributes/derive_delegate.md | 104 ++++++------ docs/reference/attributes/extend.md | 84 +++++----- docs/reference/attributes/extend_where.md | 85 +++++----- docs/reference/attributes/implicit.md | 153 +++++++++--------- docs/reference/attributes/index.md | 51 ++++++ docs/reference/attributes/use_provider.md | 120 +++++++------- docs/reference/attributes/use_type.md | 151 +++++++++-------- docs/reference/attributes/uses.md | 117 ++++++-------- docs/reference/derives/derive_build_field.md | 13 +- docs/reference/derives/derive_cgp_data.md | 15 +- docs/reference/derives/derive_cgp_record.md | 12 +- docs/reference/derives/derive_cgp_variant.md | 12 +- .../reference/derives/derive_extract_field.md | 12 +- docs/reference/derives/derive_from_variant.md | 13 +- docs/reference/derives/derive_has_field.md | 12 +- docs/reference/derives/derive_has_fields.md | 12 +- docs/reference/macros/async_trait.md | 6 +- docs/reference/macros/blanket_trait.md | 7 +- docs/reference/macros/cgp_auto_dispatch.md | 6 +- docs/reference/macros/cgp_auto_getter.md | 2 +- docs/reference/macros/cgp_component.md | 13 +- docs/reference/macros/cgp_computer.md | 7 +- docs/reference/macros/cgp_fn.md | 9 +- docs/reference/macros/cgp_getter.md | 7 +- docs/reference/macros/cgp_impl.md | 13 +- docs/reference/macros/cgp_namespace.md | 9 +- docs/reference/macros/cgp_producer.md | 7 +- docs/reference/macros/cgp_provider.md | 9 +- docs/reference/macros/cgp_type.md | 9 +- docs/reference/macros/check_components.md | 9 +- .../macros/delegate_and_check_components.md | 11 +- docs/reference/macros/delegate_components.md | 9 +- docs/reference/macros/path.md | 7 +- docs/reference/macros/product.md | 7 +- docs/reference/macros/sum.md | 7 +- docs/reference/macros/symbol.md | 7 +- docs/reference/traits/append_product.md | 11 +- docs/reference/traits/build_field.md | 10 +- docs/reference/traits/can_build_from.md | 10 +- .../traits/can_build_with_default.md | 10 +- docs/reference/traits/can_downcast.md | 10 +- docs/reference/traits/can_downcast_fields.md | 11 +- .../traits/can_finalize_with_default.md | 10 +- docs/reference/traits/can_upcast.md | 11 +- docs/reference/traits/can_use_component.md | 11 +- docs/reference/traits/concat_path.md | 11 +- docs/reference/traits/concat_product.md | 11 +- docs/reference/traits/contains_value.md | 10 +- docs/reference/traits/default_impls1.md | 10 +- docs/reference/traits/default_impls2.md | 11 +- docs/reference/traits/default_namespace.md | 10 +- docs/reference/traits/delegate_component.md | 12 +- docs/reference/traits/extract_field.md | 11 +- docs/reference/traits/field_getter.md | 10 +- docs/reference/traits/field_mapper.md | 10 +- docs/reference/traits/finalize_build.md | 10 +- docs/reference/traits/finalize_extract.md | 11 +- .../traits/finalize_extract_result.md | 10 +- docs/reference/traits/finalize_optional.md | 10 +- docs/reference/traits/from_fields.md | 10 +- docs/reference/traits/from_variant.md | 11 +- docs/reference/traits/has_builder.md | 12 +- docs/reference/traits/has_extractor.md | 10 +- docs/reference/traits/has_extractor_mut.md | 10 +- docs/reference/traits/has_extractor_ref.md | 10 +- docs/reference/traits/has_field.md | 12 +- docs/reference/traits/has_field_mut.md | 10 +- docs/reference/traits/has_fields.md | 12 +- docs/reference/traits/has_fields_ref.md | 10 +- docs/reference/traits/has_optional_builder.md | 10 +- docs/reference/traits/into_builder.md | 11 +- docs/reference/traits/is_provider_for.md | 12 +- docs/reference/traits/lift_value.md | 10 +- docs/reference/traits/map_field.md | 10 +- docs/reference/traits/map_fields.md | 10 +- docs/reference/traits/map_type.md | 10 +- docs/reference/traits/map_type_ref.md | 10 +- docs/reference/traits/monadic_bind.md | 10 +- docs/reference/traits/monadic_trans.md | 10 +- docs/reference/traits/mut_field_getter.md | 12 +- docs/reference/traits/partial_data.md | 10 +- docs/reference/traits/set_optional.md | 10 +- docs/reference/traits/static_format.md | 10 +- docs/reference/traits/static_string.md | 10 +- docs/reference/traits/take_field.md | 10 +- docs/reference/traits/to_fields.md | 10 +- docs/reference/traits/to_fields_ref.md | 10 +- docs/reference/traits/to_optional.md | 10 +- docs/reference/traits/transform_map.md | 10 +- .../reference/traits/transform_map_default.md | 10 +- docs/reference/traits/transform_map_fields.md | 10 +- docs/reference/traits/transform_optional.md | 10 +- docs/reference/traits/update_field.md | 10 +- 95 files changed, 585 insertions(+), 1213 deletions(-) create mode 100644 docs/reference/attributes/index.md diff --git a/docs/reference/attributes/_category_.json b/docs/reference/attributes/_category_.json index fc17a26e..5dda2e1e 100644 --- a/docs/reference/attributes/_category_.json +++ b/docs/reference/attributes/_category_.json @@ -2,7 +2,7 @@ "label": "Attributes", "position": 2, "link": { - "type": "generated-index", - "description": "The modifier attributes that refine what a definition macro generates. They are options consumed by a host macro rather than macros in their own right." + "type": "doc", + "id": "reference/attributes/index" } } diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 8de00425..380527d1 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[default_impl]' +sidebar_position: 7 --- # `#[default_impl(...)]` @@ -8,9 +9,9 @@ Register a provider as a namespace's default for a key. ## Overview -A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the -type the capability runs against — can opt into and then selectively override. Ordinarily a namespace's -entries are written in its own body. `#[default_impl(...)]` lets a *provider* register itself instead, +A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context**, the +type the capability runs against, can opt into and then selectively override. Ordinarily you write a +namespace's entries in its own body. `#[default_impl(...)]` lets a *provider* register itself instead, at the point where it is defined: ```rust @@ -22,8 +23,8 @@ impl ShowImpl { /* … */ } Read that as: *`ShowString` is the default for `String`, in the `DefaultImpls1` table.* A context that pulls that table in gets this provider without naming it. -The value of registering at the definition is that the provider and its default sit together, so adding a -new per-type implementation is one place to edit rather than two. +Registering at the definition keeps the provider and its default together, so adding a new per-type +implementation is one place to edit rather than two. ## Usage @@ -35,7 +36,7 @@ parts, joined by the keyword `in`: ``` **`Key` becomes the emitted impl's `Self`**, and `NamespacePath` names the lookup trait plus whatever -leading arguments you write inside it. The table parameter is appended for you. So the example above +leading arguments you write inside it. The macro appends the table parameter for you. So the example above emits: ```rust @@ -45,33 +46,16 @@ impl DefaultImpls1 for String { ``` That rule is worth internalizing, because the trait's own parameter names suggest the opposite -arrangement — see [`DefaultImpls1`](../traits/default_impls1.md#the-one-thing-to-get-right). +arrangement (see [`DefaultImpls1`](../traits/default_impls1.md#the-one-thing-to-get-right)). **The path may name any trait**, not only the three CGP ships. A trait of your own with the right shape works identically, which is why [`DefaultImpls2`](../traits/default_impls2.md) needed no new construct to be usable. The three built-in targets are [`DefaultNamespace`](../traits/default_namespace.md) for a component-only -key, [`DefaultImpls1`](../traits/default_impls1.md) for a per-type default — the usual choice — and +key, [`DefaultImpls1`](../traits/default_impls1.md) for a per-type default (the usual choice), and [`DefaultImpls2`](../traits/default_impls2.md) for a two-type key. -
-Formal grammar - -The attribute argument is a key type, the keyword `in`, and a namespace path, in the Rust Reference's -[notation](https://doc.rust-lang.org/reference/notation.html): - -```ebnf -DefaultImplArgs -> Type `in` TypePath -``` - -`Type` is the key that becomes the emitted impl's `Self`, and `TypePath` is the lookup trait with its -leading generic arguments written out — the table parameter is appended by the macro and must not be -given. The attribute takes exactly one such argument; it is neither comma-separated nor repeatable for -several tables on one provider. - -
- ## Examples The whole chain, from a provider declaring itself a default to a context pulling it in: @@ -114,7 +98,7 @@ delegate_components! { } ``` -**Environmental context, parameter-targeted** — `App` carries the wiring and the shown value is a +**Environmental context, parameter-targeted**: `App` carries the wiring and the shown value is a parameter. The loop wires every type with a registered default, and the direct `u64` line shadows whatever the namespace would otherwise supply for that one type. @@ -126,8 +110,8 @@ provider is written.** - **Write the entry in the namespace body instead** when the defaults belong together as a set, or when the provider is one of several candidates and none is obviously *the* default. A [`cgp_namespace!`](../macros/cgp_namespace.md) body reads as a table; scattered attributes do not. -- **Use it** when per-type defaults accumulate — a conversion, a formatter, a codec with one provider per - type — because then the alternative is a namespace body that has to be edited every time a type is +- **Use it** when per-type defaults accumulate (a conversion, a formatter, a codec with one provider per + type), because then the alternative is a namespace body that has to be edited every time a type is added. - **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. @@ -141,14 +125,6 @@ that must live downstream goes in the namespace body of the crate that owns it i ## Under the hood -:::note - -### Advanced - -This section shows what the attribute emits, and the one thing it deliberately leaves out. - -::: - The attribute emits a single impl of the named lookup trait, for the key type: ```rust @@ -160,8 +136,8 @@ impl DefaultImpls1 for String { The `Components` parameter is the table the lookup runs against, appended by the macro and left generic so one registration serves every context. -**The registration impl carries only the parameters naming the key and the provider, plus the table — -never the provider's own `where` clause.** That is deliberate and is what makes the attribute usable with +**The registration impl carries only the parameters naming the key and the provider, plus the table, +never the provider's own `where` clause.** That is deliberate, and it lets the attribute work with ordinary providers: a provider whose bounds come from [`#[use_type]`](./use_type.md), [`#[uses]`](./uses.md), [`#[implicit]`](./implicit.md), or [`#[use_provider]`](./use_provider.md) registers cleanly, because those bounds stay on the provider's impl and its @@ -175,10 +151,24 @@ Consumption is the mirror. A `for in DefaultImpls1 { where T: DefaultImpls1 ``` -Because the loop variables appear only in that bound and in the key, **the key must mention them** — or -the parameter is unconstrained and the impl is rejected with `E0207`. +Because the loop variables appear only in that bound and in the key, **the key must mention them**, or +the parameter is unconstrained and the compiler rejects the impl with `E0207`. + +## Formal grammar + +The attribute argument is a key type, the keyword `in`, and a namespace path, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +DefaultImplArgs -> Type `in` TypePath +``` + +`Type` is the key that becomes the emitted impl's `Self`, and `TypePath` is the lookup trait with its +leading generic arguments written out. The table parameter is appended by the macro and must not be +given. The attribute takes exactly one such argument; it is neither comma-separated nor repeatable for +several tables on one provider. -## Gotchas +## Common Mistakes **`Key` becomes `Self`, not a parameter.** Read `#[default_impl(Key in Path)]` as "`Key` becomes `Self`" and the trait's positions follow. The parameter names on @@ -188,7 +178,7 @@ and the trait's positions follow. The parameter names on wrong. **On a prefixed component it is confined to the namespace's crate**, by the orphan rule. This is not -something to work around — put the wiring in the namespace body instead. +something to work around: put the wiring in the namespace body instead. **The lookup trait must be imported.** The emitted impl names it, so [`DefaultImpls1`](../traits/default_impls1.md) and [`DefaultImpls2`](../traits/default_impls2.md) need diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index e1cf64a5..cc909992 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive_delegate]' +sidebar_position: 8 --- # `#[derive_delegate]` @@ -16,8 +17,8 @@ dispatched on a type parameter: the `open` statement of [`delegate_components!`](../macros/delegate_components.md) does the same job through machinery every component already has, with no separate table and no wrapper. -**Prefer `open` for anything new.** This page is here because you will meet the older form — including in -CGP's own error and handler components, which are still defined with this attribute — and because a +**Prefer `open` for anything new.** This page is here because you will meet the older form, including in +CGP's own error and handler components, which are still defined with this attribute, and because a component that keeps it stays compatible with existing wiring. It is expected to be deprecated once `open` is shown to cover every dispatch case. @@ -28,8 +29,8 @@ component that keeps it stays compatible with existing wiring. It is expected to A component generic over a type parameter usually wants a different implementation per value of it: `Rectangle` handled one way, `Circle` another. Something has to look at the type and pick, and written by hand that dispatcher is an implementation of the provider trait that reads a lookup table, finds the entry -for the type, and forwards every method to it — mechanical code, identical in shape for every component, -differing only in which parameter is the key. +for the type, and forwards every method to it. That code is mechanical, identical in shape for every +component, differing only in which parameter is the key. `#[derive_delegate]` generates it: @@ -41,13 +42,13 @@ pub trait CanCalculateArea { } ``` -A **context** — the type the capability runs against, which owns the wiring — then points the component at +A **context**, the type the capability runs against and owns the wiring, then points the component at [`UseDelegate`](../providers/use_delegate.md) over a table naming one implementation per shape, and the generated dispatcher does the lookup. -The reason the `open` statement replaced this is that the indirection turned out to be unnecessary. Every +`open` replaced this because the indirection turned out to be unnecessary. Every [`#[cgp_component]`](../macros/cgp_component.md) already generates a -[`RedirectLookup`](../providers/redirect_lookup.md) impl, and `open` routes through that instead — so the +[`RedirectLookup`](../providers/redirect_lookup.md) impl, and `open` routes through that instead, so the per-type entries live on the context itself, there is no second table type to name, and the component needs no attribute at all. @@ -68,7 +69,7 @@ once: ``` **To dispatch on several parameters independently, repeat the attribute**, one per dispatcher. Each names -its own wrapper type, and only the parameter in that wrapper's brackets is used as its key — the rest flow +its own wrapper type, and only the parameter in that wrapper's brackets is used as its key. The rest flow through unchanged: ```rust @@ -83,37 +84,13 @@ pub trait CanCompute { ``` `UseDelegate` is the wrapper CGP provides, but the machinery is not tied to it. Any struct of the same -shape works, which is how a second, independent dispatcher is added — a user-defined +shape works, which is how you add a second, independent dispatcher: a user-defined `pub struct UseInputDelegate(pub PhantomData);` is all the second line above needs. The attribute belongs on a [`#[cgp_component]`](../macros/cgp_component.md) trait and only makes sense for one that has generic parameters. -
-Formal grammar - -The attribute argument is a wrapper name and the parameters to key on, in the Rust Reference's -[notation](https://doc.rust-lang.org/reference/notation.html): - -```ebnf -DeriveDelegateArgs -> Wrapper `<` KeyParams `>` - -Wrapper -> IDENTIFIER - -KeyParams -> IDENTIFIER - | `(` IDENTIFIER ( `,` IDENTIFIER )* `,`? `)` -``` - -Both parts are required. `Wrapper` is a bare identifier rather than a path, so a wrapper reached through a -module path has to be imported first. `KeyParams` are **identifiers**, not types: each must name a generic -parameter the trait declares, and a type expression such as `Vec` in that position does not parse. The -parenthesized form must list at least one parameter — an empty `()` is rejected with *expect non-empty -tuple list of identifiers in use_delegate_spec* — and a single parameter written bare is keyed the same way -a one-element tuple would be. The attribute may be repeated, once per dispatcher. - -
- ## Examples A dispatching component, two implementations, and a context that routes each shape to its own: @@ -164,8 +141,8 @@ delegate_components! { `MyApp` now implements `CanCalculateArea` through `RectangleArea` and `CanCalculateArea` through `CircleArea`. -**The same result without the attribute** is what to write instead. Drop `#[derive_delegate]` from the -component and let the context open it: +**Write the same result without the attribute instead.** Drop `#[derive_delegate]` from the component and +let the context open it: ```rust delegate_components! { @@ -189,13 +166,13 @@ That is the recommendation without qualification for new code. Three situations still involve it, and only the first is a reason to write it. -- **Keeping compatibility with existing wiring.** The attribute is what makes +- **Keeping compatibility with existing wiring.** The attribute makes `UseDelegate` wiring possible, so removing it from a published component is a breaking change for any downstream user who wires that way. Removing it is still the right direction, but it is a - breaking change to schedule rather than a cleanup to slip in. + breaking change to schedule rather than a cleanup to make in passing. - **A dispatcher `open` cannot express.** `open` resolves through the `RedirectLookup` impl a component generates, which keys on the parameter that impl dispatches on. A *second*, independently keyed - dispatcher — the `UseInputDelegate` case above — has no `open` equivalent, so a component wanting + dispatcher, the `UseInputDelegate` case above, has no `open` equivalent, so a component wanting one still declares it here. - **Reading existing code.** CGP's own error and handler components are defined with this attribute, so `UseDelegate` tables appear in wiring you did not write. Understanding the form matters more than being @@ -203,16 +180,6 @@ Three situations still involve it, and only the first is a reason to write it. ## Under the hood -:::note - -### Advanced - -This section shows the dispatcher the attribute generates. You do not need it to use `#[derive_delegate]`, -but it is what a failed per-type lookup names in an error, and seeing it explains why `open` was able to -replace it. `cargo cgp expand` prints the same thing for your own code. - -::: - Each `#[derive_delegate]` adds one provider impl to everything [`#[cgp_component]`](../macros/cgp_component.md) already emits. It is the ordinary forwarding shape, except that the lookup key is the dispatch parameter rather than the component name. From the `AreaCalculator` @@ -234,26 +201,47 @@ where Reading it back: `UseDelegate` is a provider for any `Shape` whose entry in `Components` names something that is itself a provider for that `Shape`, and the method simply forwards. The `Components` type is the inner table, and [`DelegateComponent`](../traits/delegate_component.md) is the -same trait ordinary wiring is made of — which is why the table is written with +same trait ordinary wiring is made of, which is why you write the table with [`delegate_components!`](../macros/delegate_components.md) like any other. Two details of the real output are worth recognizing. **The key is wrapped in a tuple**, as `DelegateComponent<(Shape), …>`, so that a single-parameter key and a multi-parameter one compose -uniformly — a `UseDelegate<(Code, Input)>` declaration produces `DelegateComponent<(Code, Input), …>` with +uniformly: a `UseDelegate<(Code, Input)>` declaration produces `DelegateComponent<(Code, Input), …>` with no other change. And the generics carry reserved names: the table is `__Components__` and the looked-up entry `__Delegate__`, alongside the provider trait's own `__Context__`. -**A component's supertraits ride along into the dispatcher.** The provider trait records each supertrait as -a `Context:` predicate, and because the dispatcher reuses the provider trait's generics that predicate -appears here too — so a component declaring an error type through +**A component's supertraits carry into the dispatcher.** The provider trait records each supertrait as a +`Context:` predicate, and because the dispatcher reuses the provider trait's generics that predicate +appears here too, so a component declaring an error type through [`#[use_type]`](use_type.md) yields a dispatcher whose `where` clause also requires `__Context__: HasErrorType`. -When several `#[derive_delegate]` attributes are present, one impl is generated per attribute, each keyed -on its own parameter and otherwise identical. The two are independent, so a context may dispatch on either +When several `#[derive_delegate]` attributes are present, the macro generates one impl per attribute, +each keyed on its own parameter and otherwise identical. The two are independent, so a context may dispatch on either or nest one table inside the other. -## Gotchas +## Formal grammar + +The attribute argument is a wrapper name and the parameters to key on, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +DeriveDelegateArgs -> Wrapper `<` KeyParams `>` + +Wrapper -> IDENTIFIER + +KeyParams -> IDENTIFIER + | `(` IDENTIFIER ( `,` IDENTIFIER )* `,`? `)` +``` + +Both parts are required. `Wrapper` is a bare identifier rather than a path, so a wrapper reached through a +module path has to be imported first. `KeyParams` are **identifiers**, not types: each must name a generic +parameter the trait declares, and a type expression such as `Vec` in that position does not parse. The +parenthesized form must list at least one parameter (an empty `()` is rejected with *expect non-empty +tuple list of identifiers in use_delegate_spec*), and a single parameter written bare is keyed the same way +a one-element tuple would be. The attribute may be repeated, once per dispatcher. + +## Common Mistakes **The key must be a generic parameter the trait actually declares.** The attribute names it by identifier, so a parameter that is not in scope on the trait is reported as an unresolved type rather than as anything @@ -271,7 +259,7 @@ there is nothing for it to do. **One component gets one dispatch mechanism.** Wiring the same component both with `open` and with a `UseDelegate` table is a coherence conflict, because each produces its own table entry for that key. A -wiring entry expands to two impls, and both of them collide, so the conflict is reported twice — once +wiring entry expands to two impls, and both of them collide, so the compiler reports the conflict twice, once for `IsProviderFor` and once for `DelegateComponent`. The second is the readable one, since its trait argument names the component at issue: @@ -293,7 +281,7 @@ per-type entries have to be written with the full prefixed path instead. ## Related constructs - [`delegate_components!`](../macros/delegate_components.md) — its `open` statement is the replacement, and - its nested-table form is what this attribute enables. + this attribute enables its nested-table form. - [`UseDelegate`](../providers/use_delegate.md) — the provider the generated impl is written for. - [`RedirectLookup`](../providers/redirect_lookup.md) — what `open` resolves through instead. - [`#[cgp_component]`](../macros/cgp_component.md) — the host, and the source of the provider trait. diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 8bf46ea7..3eb8d7f6 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[extend]' +sidebar_position: 5 --- # `#[extend]` @@ -10,8 +11,8 @@ Add a capability as a supertrait of a generated trait, so callers can rely on it `#[extend]` declares that a capability is part of what a trait *guarantees*, rather than something its implementation happens to need. Where [`#[uses]`](uses.md) adds a private requirement, `#[extend]` adds a -supertrait: every **context** implementing the trait — every type the capability runs against — must also -satisfy it, and every caller may rely on it. +supertrait. Every **context** implementing the trait, meaning every type the capability runs against, +must also satisfy it, and every caller may rely on it. ```rust #[extend(HasName)] @@ -23,13 +24,13 @@ own use and keeps it out of sight, while the other re-exports it as part of the That framing is also why `#[extend]` is preferred over Rust's native supertrait syntax on a [`#[cgp_component]`](../macros/cgp_component.md). Writing `pub trait CanGreet: HasName` reads as -inheritance from a parent — an is-a relationship, which is not what a CGP supertrait is. `#[extend(HasName)]` -reads as importing a capability the trait passes on, which is what is actually happening. The two generate -the same trait, so this is a choice about how the definition reads. +inheritance from a parent, an is-a relationship that a CGP supertrait is not. `#[extend(HasName)]` reads +as importing a capability the trait passes on, which is the accurate description. The two generate the +same trait, so this is a choice about how the definition reads. -On [`#[cgp_fn]`](../macros/cgp_fn.md) the attribute is not merely preferred but necessary. A `where` clause -written on a `#[cgp_fn]` is treated as an implementation detail and never reaches the generated trait, so -there is no way to spell a supertrait by hand — `#[extend]` is the only mechanism for one. +On [`#[cgp_fn]`](../macros/cgp_fn.md) the attribute is not merely preferred but necessary. The `#[cgp_fn]` +macro treats a `where` clause you write as an implementation detail and never puts it on the generated +trait, so there is no way to spell a supertrait by hand. `#[extend]` is the only mechanism for one. ## Usage @@ -40,22 +41,22 @@ trait: #[extend(HasName, HasTitle)] ``` -Each entry names a trait, optionally with type arguments. Several may be listed in one attribute or spread -across attributes, and they accumulate — prefer one attribute carrying the whole list, as with +Each entry names a trait, optionally with type arguments. You may list several in one attribute or spread +them across attributes, and they accumulate. Prefer one attribute carrying the whole list, as with [`#[uses]`](uses.md). The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on [`#[cgp_component]`](../macros/cgp_component.md). It is **not** available on -[`#[cgp_impl]`](../macros/cgp_impl.md), which has no trait definition of its own to attach a supertrait to -— the supertraits belong to the component's trait, and a provider states its private needs with +[`#[cgp_impl]`](../macros/cgp_impl.md), which has no trait definition of its own to attach a supertrait to. +The supertraits belong to the component's trait, and a provider states its private needs with [`#[uses]`](uses.md) instead. ### When the supertrait supplies a type -If the reason for the supertrait is that the trait's signatures name a type the other component provides — -an error type, a scalar, a runtime — reach for [`#[use_type]`](use_type.md) instead. It adds the supertrait -*and* rewrites bare mentions of the type into their fully qualified form, so the signature reads -`Result` rather than `Result::Error>`: +If the reason for the supertrait is that the trait's signatures name a type the other component provides +(an error type, a scalar, a runtime), reach for [`#[use_type]`](use_type.md) instead. It adds the +supertrait *and* rewrites bare mentions of the type into their fully qualified form, so the signature +reads `Result` rather than `Result::Error>`: ```rust #[cgp_component(Loader)] @@ -65,7 +66,7 @@ pub trait CanLoad { } ``` -`#[extend]` is therefore for a **capability** supertrait — one whose methods matter and whose associated +`#[extend]` is therefore for a **capability** supertrait, one whose methods matter and whose associated types the signatures do not name. ## Examples @@ -92,7 +93,7 @@ pub fn full_label(&self) -> String { } ``` -The body can call both getters, and so can anyone holding a `T: FullLabel` — which is the difference from +The body can call both getters, and so can anyone holding a `T: FullLabel`, which is the difference from `#[uses]`. A function that takes a labelled value can format its name without asking for `HasName` separately. @@ -116,31 +117,21 @@ a capability supertrait on a `#[cgp_component]` in preference to native `:` synt else in three cases, and the choice turns on where the requirement should be visible. - **The implementation needs it privately.** Use [`#[uses]`](uses.md). This is the common case by a wide - margin: most dependencies are the implementation's business, and putting one on the trait forces it on + margin: most dependencies are private to the implementation, and putting one on the trait forces it on every context and every caller whether they touch it or not. - **The signatures name a type it supplies.** Use [`#[use_type]`](use_type.md), which adds the supertrait and removes the qualified paths. -- **The requirement is a predicate rather than a supertrait** — a bound on a generic parameter rather than +- **The requirement is a predicate rather than a supertrait**, a bound on a generic parameter rather than on `Self`. Use [`#[extend_where]`](extend_where.md), which puts it on the generated trait's own `where` clause. -There is a cost worth weighing before promoting anything. A supertrait widens the contract permanently: it -cannot later be narrowed without breaking every implementor, and it demands the capability from contexts -that only ever call the one method the trait actually declares. Prefer `#[uses]` unless callers genuinely -need the guarantee. +Weigh one cost before promoting anything. A supertrait widens the contract permanently: you cannot later +narrow it without breaking every implementor, and it demands the capability from contexts that only ever +call the one method the trait actually declares. Prefer `#[uses]` unless callers genuinely need the +guarantee. ## Under the hood -:::note - -### Advanced - -This section shows where the bound is placed. You do not need it to use `#[extend]`, but the placement is -the entire difference from `#[uses]`, so seeing both is what makes the pair make sense. -`cargo cgp expand` prints the same thing for your own code. - -::: - On a `#[cgp_fn]`, each entry lands in **two** places: as a supertrait of the generated trait, and as a `Self:` predicate on the generated implementation. From this input: @@ -167,9 +158,9 @@ where } ``` -The supertrait is what callers see; the predicate on the implementation is what lets the body call the -methods. Compare [`#[uses]`](uses.md), which emits only the second of those two, leaving the trait -declaration bare — that single difference is the whole of the distinction. +Callers see the supertrait, and the predicate on the implementation lets the body call the methods. +Compare [`#[uses]`](uses.md), which emits only the second of those two and leaves the trait declaration +bare. That single difference is the whole of the distinction. On a `#[cgp_component]` the supertrait goes on the consumer trait, and it also joins the `where` clause of the generated consumer blanket implementation, since that implementation can only apply where the @@ -191,13 +182,12 @@ where } ``` -Here the result is exactly what `pub trait CanGreet: HasName` would have produced, so on a component +Here the result is identical to `pub trait CanGreet: HasName`, so on a component `#[extend]` generates nothing the language cannot already spell. It remains the preferred form for the reason given above: it presents the bound as an import rather than as inheritance, and it keeps the `use`/`pub use` pairing with `#[uses]` reading consistently across both macros. -
-Formal grammar +## Formal grammar The attribute argument is a comma-separated list of bounds, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -206,14 +196,12 @@ The attribute argument is a comma-separated list of bounds, in the Rust Referenc ExtendArgs -> TypeParamBound ( `,` TypeParamBound )* `,`? ``` -This is the same production [`#[uses]`](uses.md) accepts — the Rust grammar's own bound, so a lifetime, a +This is the same production [`#[uses]`](uses.md) accepts, the Rust grammar's own bound, so a lifetime, a `?Sized`, or an associated-type equality parses as readily as a plain trait name. The list may be empty, -and the attribute may be repeated, with every occurrence's entries collected together. What differs -between the two attributes is not the grammar but where the bounds land. - -
+and the attribute may be repeated, with every occurrence's entries collected together. The two attributes +differ in where the bounds land, not in the grammar. -## Gotchas +## Common Mistakes **On a `#[cgp_impl]` the attribute is not recognized at all**, rather than being accepted and ignored. Nothing consumes it, so it falls through to the compiler as an unknown attribute: @@ -222,9 +210,9 @@ Nothing consumes it, so it falls through to the compiler as an unknown attribute error: cannot find attribute `extend` in this scope ``` -Expect a second error alongside it, because the bound was never added: the body's calls to the capability +Expect a second error alongside it, because the bound was never added. The body's calls to the capability then fail with `E0599`, reporting that the method exists but its trait bounds were not satisfied. Both -errors have the same cause — move the requirement to [`#[uses]`](uses.md), or onto the component's trait +errors have the same cause: move the requirement to [`#[uses]`](uses.md), or onto the component's trait where supertraits belong. **A supertrait cannot be narrowed later.** Because every implementor and every caller may now rely on it, diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 4e07bebb..07412a3a 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[extend_where]' +sidebar_position: 6 --- # `#[extend_where]` @@ -10,12 +11,12 @@ Add `where` predicates to a generated trait's own definition, not just to its im A [`#[cgp_fn]`](../macros/cgp_fn.md) treats the `where` clause you write on the function as an implementation detail: the bounds land on the generated implementation and never appear on the generated -trait. That default is what keeps a capability's requirements out of sight of its callers, and it is right -almost always. +trait. That default keeps a capability's requirements out of sight of its callers, and it is right almost +always. -What it costs is that an unsatisfiable requirement becomes invisible. A bound on the implementation only -decides which **contexts** the implementation covers — a context being the type the capability runs -against, which supplies the values it needs as its fields — so naming the capability for a type that can +The cost is that an unsatisfiable requirement becomes invisible. A bound on the implementation only +decides which **contexts** the implementation covers, a context being the type the capability runs +against, which supplies the values it needs as its fields. So naming the capability for a type that can never satisfy it is not an error. It is a bound nobody can prove, accepted quietly, and the complaint arrives later and somewhere else. `#[extend_where]` moves the predicate onto the trait, where it becomes a condition of naming the trait at all: @@ -24,13 +25,14 @@ condition of naming the trait at all: #[extend_where(Scalar: Clone)] ``` -The distinction is worth being exact about, because it is easy to get backwards. Promoting a predicate does -**not** hand it to callers — a trait's `where` clause is a precondition they must prove, not a guarantee -they receive, so a caller naming the trait still writes the bound themselves. What promotion buys is that -they are *made* to, and that getting it wrong is reported against the trait rather than deferred. +The distinction is worth being exact about, because it is easy to get backwards. Promoting a predicate +does **not** hand it to callers. A trait's `where` clause is a precondition they must prove, not a +guarantee they receive, so a caller naming the trait still writes the bound themselves. Promotion changes +two things: callers are now *made* to write the bound, and getting it wrong is reported against the trait +rather than deferred. It is the `where`-clause sibling of [`#[extend]`](extend.md). Both put a requirement into the trait's -public interface; they differ in position, and in what the reader gets. `#[extend]` adds a **supertrait** — +public interface; they differ in position, and in what the reader gets. `#[extend]` adds a **supertrait**, a bound on `Self`, which callers do receive by elaboration. `#[extend_where]` adds a **predicate**, which can bound anything, most usefully one of the trait's own generic parameters, which a supertrait cannot reach. @@ -44,13 +46,13 @@ reach. ``` Unlike [`#[uses]`](uses.md) and [`#[extend]`](extend.md), whose entries are trait bounds attached to `Self`, -these are arbitrary predicates — a bound on any type in scope, including an associated-type equality, a -higher-ranked bound, or a lifetime bound. Each is added to the generated trait's `where` clause verbatim, -and kept on the implementation as well. +these are arbitrary predicates: a bound on any type in scope, including an associated-type equality, a +higher-ranked bound, or a lifetime bound. The macro adds each to the generated trait's `where` clause +verbatim, and keeps it on the implementation as well. **`#[extend_where]` is supported only on [`#[cgp_fn]`](../macros/cgp_fn.md).** It has no meaning on [`#[cgp_impl]`](../macros/cgp_impl.md) or [`#[cgp_component]`](../macros/cgp_component.md), because in -those the `where` clause you write is already part of the definition — there is nothing to promote, so +those the `where` clause you write is already part of the definition. There is nothing to promote, so write the bound as an ordinary `where` clause directly. ## Examples @@ -71,12 +73,13 @@ where } ``` -Two bounds, two destinations. `Scalar: Clone` is promoted onto the trait, so it is checked wherever -`Scale` is named. `Scalar: Mul` stays on the implementation, because multiplying -is how *this* body happens to compute a scale and no use site needs to know it. +Two bounds, two destinations. The macro promotes `Scalar: Clone` onto the trait, so the compiler checks +it wherever `Scale` is named. `Scalar: Mul` stays on the implementation, because +multiplication is a detail of how *this* body computes a scale and no use site needs to know it. -What the promotion changes is visible at the boundary. A caller naming the capability for a type that -cannot satisfy it is rejected where the bound is written, and told which trait demanded it: +The promotion's effect is visible at the boundary. The compiler rejects a caller that names the +capability for a type it cannot satisfy, at the place the bound is written, and names the trait that +demanded it: ```rust pub struct NoClone; @@ -90,8 +93,8 @@ where ``` **Leave `Clone` on the implementation instead and that same function compiles**, with no diagnostic at -all — `Ctx: Scale` is simply a bound no type can ever prove, and nothing says so until somebody -tries to call `scale_it` with a concrete context. That silence is what the attribute exists to remove. +all: `Ctx: Scale` is simply a bound no type can ever prove, and nothing says so until somebody +tries to call `scale_it` with a concrete context. The attribute exists to remove that silence. A caller who *can* satisfy the predicate states it as usual, and there is no way around stating it: @@ -113,36 +116,25 @@ That is a real but uncommon need, and the default of leaving bounds on the imple almost everything. The useful test is who the bound is *about*. A bound describing how the body computes its answer belongs on -the implementation. A bound describing what the capability requires of its own type parameters — something -that would be part of the signature if you were writing the trait by hand — belongs on the trait. +the implementation. A bound describing what the capability requires of its own type parameters, something +that would be part of the signature if you were writing the trait by hand, belongs on the trait. Three neighbours cover what this attribute should not be used for. - **A bound on `Self`** is a supertrait, so use [`#[extend]`](extend.md). `#[extend_where]` can express it, but a supertrait reads as what it is, and unlike a predicate it *is* handed to callers by elaboration. -- **A private requirement** — the overwhelmingly common case — belongs in the function's own `where` clause, +- **A private requirement**, the overwhelmingly common case, belongs in the function's own `where` clause, or in [`#[uses]`](uses.md) when it is a capability. - **An abstract type pinned to a concrete one** is [`#[use_type]`](use_type.md)'s equality form, which adds the bound and lets the signature name the type as a bare word. Do not reach for it to spare callers a bound: it has the opposite effect. If the goal is that holding the -capability should imply something, that is what a supertrait does, and the bound has to be on `Self` for it -to work. +capability should imply something, a supertrait does that, and the bound has to be on `Self` for it to work. ## Under the hood -:::note - -### Advanced - -This section shows where each predicate lands, and in what order. You do not need it to use -`#[extend_where]`, but the ordering explains a long `where` clause that otherwise looks arbitrary. -`cargo cgp expand` prints the same thing for your own code. - -::: - -Each predicate is added to the generated trait's `where` clause, and also kept on the implementation so the -body can rely on it. From the `scale` example above: +The macro adds each predicate to the generated trait's `where` clause, and also keeps it on the +implementation so the body can rely on it. From the `scale` example above: ```rust pub trait Scale @@ -173,8 +165,7 @@ reading a long `where` clause in an expansion, since it tells you where each bou The context parameter is literally `__Context__` in the emitted code and appears as `Self` inside the implementation. -
-Formal grammar +## Formal grammar The attribute argument is a comma-separated list of `where` predicates, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -183,16 +174,14 @@ The attribute argument is a comma-separated list of `where` predicates, in the R ExtendWhereArgs -> WherePredicate ( `,` WherePredicate )* `,`? ``` -`WherePredicate` is the Rust grammar's own production — the thing that appears between the commas of a -`where` clause — which is what separates this attribute from [`#[uses]`](uses.md) and -[`#[extend]`](extend.md). Those take a *bound* and always attach it to `Self`; a predicate names its own -subject, so `#[extend_where(Self::Output: Clone)]` and `#[extend_where(for<'a> &'a T: IntoIterator)]` are -both expressible here and neither is expressible there. The list may be empty and the attribute may be +`WherePredicate` is the Rust grammar's own production, the thing that appears between the commas of a +`where` clause, and it separates this attribute from [`#[uses]`](uses.md) and [`#[extend]`](extend.md). +Those take a *bound* and always attach it to `Self`, whereas a predicate names its own subject, so +`#[extend_where(Self::Output: Clone)]` and `#[extend_where(for<'a> &'a T: IntoIterator)]` are both +expressible here and neither is expressible there. The list may be empty and the attribute may be repeated. -
- -## Gotchas +## Common Mistakes **A promoted predicate does not reach callers as a guarantee.** This is the mistake the attribute most invites: because `#[extend]` gives callers its supertrait, it is natural to assume `#[extend_where]` gives diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 24790813..1a3f0fff 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[implicit]' +sidebar_position: 1 --- # `#[implicit]` @@ -8,10 +9,9 @@ Source a function argument from a same-named field on the context. ## Overview -Reading a value out of the surrounding type is most of what CGP code does, and `#[implicit]` is what -makes it look like an ordinary function parameter. You mark a parameter, and it disappears from the -signature callers see — the value is read from a field of the same name on the **context**, the type the -capability runs against: +`#[implicit]` lets a CGP construct read a field value from a generic **context** by naming the field +like an ordinary function argument. The context is the type the construct runs against, and the +implicit argument is hidden from the public signature. ```rust #[cgp_fn] @@ -20,20 +20,24 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> } ``` -`rect.rectangle_area()` takes no arguments. Any type carrying a `width` and a `height` can call it. +A call like `rect.rectangle_area()` does not require the arguments to be passed explicitly. Instead, the +`width` and `height` fields are automatically extracted from the `rect` value. Any type carrying a +`width` and a `height` field can call it. -The alternative, without the attribute, is to declare that the context has those fields and then fetch -each one by hand — which means meeting a field-access trait, a type-level name for each field, and a -`PhantomData` tag before writing a single line of the calculation. `#[implicit]` keeps all of that behind -a parameter that reads as `width: f64`, and the parameter's *name* is what names the field. +`#[implicit]` gives better ergonomics than the alternatives, such as +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) or the direct use of +[`HasField`](../traits/has_field.md). With those, you declare that the context has each field and then +fetch it by hand, so you have to understand the mechanism behind field access, such as how a type-level +[`Symbol!`](../macros/symbol.md) and a `PhantomData` tag work. `#[implicit]` keeps all of that behind an +argument that reads as `width: f64`, and the argument's *name* names the field. That is why it is the recommended way to read a context's own field, and why it is usually the first -piece of CGP anyone writes. Nothing about it is unfamiliar: a reader who understands functions and -arguments can write a working capability and meet the machinery later, when they have a reason to care. +piece of CGP anyone writes. A reader who understands functions and arguments can write a working +capability and meet the machinery later, when they have a reason to care. ## Usage -`#[implicit]` is a bare marker on a typed parameter. It takes no arguments in any form, and a list or +`#[implicit]` is a bare marker on a typed argument. It takes no arguments in any form, and a list or name-value spelling is rejected rather than ignored: ```rust @@ -42,25 +46,23 @@ fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { } ``` -It is meaningful inside the two macros that rewrite a function body into an implementation — +`#[implicit]` works only inside the two macros that rewrite a function body into an implementation: [`#[cgp_fn]`](../macros/cgp_fn.md) and the methods of a [`#[cgp_impl]`](../macros/cgp_impl.md) block. It is not a macro of its own, so it does nothing on an ordinary function. Three rules constrain where it may appear. The function must take `self` first, since the field is read -from `self`. The parameter must be a bare identifier rather than a destructuring or `mut` pattern — to -get a mutable local, clone the value inside the body. And a **mutable** implicit argument must be the -only implicit argument on its function and requires a `&mut self` receiver, because reading a field -mutably borrows the whole context exclusively and cannot coexist with any other field read. Immutable -arguments carry no such restriction and combine freely, in any number, on either receiver. +from `self`. The argument must be a bare identifier, not a destructuring or `mut` pattern. And a +**mutable** implicit argument carries two further requirements of its own, covered in +[Mutable arguments](#mutable-arguments) below. -### How the parameter's type decides the read +### How the argument's type decides the read -The parameter's type is what the body works with, and the macro inserts whatever conversion bridges it to -the stored field. This is the whole of the mapping: +The body works with the argument's type, and the macro inserts whatever conversion bridges it to the +stored field. The table below is the whole mapping: -| The parameter's type | The field's type | How it is read | +| The argument's type | The field's type | How it is read | |---|---|---| -| An owned type — `f64`, `String`, a tuple, an array | the same type | by reference, then `.clone()` | +| An owned type (`f64`, `String`, a tuple, an array) | the same type | by reference, then `.clone()` | | `&T` | `T` | by reference, no conversion | | `&str` | `String` | `.as_str()` | | `&[T]` | anything `AsRef<[T]>` | `.as_ref()` | @@ -72,23 +74,40 @@ the stored field. This is the whole of the mapping: | `Option<&mut str>` | `Option` | `.as_deref_mut()` | | [`MRef<'a, T>`](../types/mref.md) | `T` | by reference, wrapped as `MRef::Ref(…)` | -Three of those rows are worth reading twice. `&str` is the case most often wanted and least obvious: the +Three of those rows are easy to misread. `&str` is the case most often wanted and least obvious: the field is a `String`, and the argument borrows from it, so a context never has to store a `&str`. An -owned parameter *clones* — cheap for an `f64`, less so for a large `String`, which is a reason to take -`&str` or `&T` wherever the body only needs to read. And `MRef` is the owned-or-borrowed form: it reads a -plain `T` field, hands the body a value that may be either, and is the one reference-shaped row with no -mutable counterpart. +owned argument *clones* the value. That is cheap for an `f64` and less so for a large `String`, which +is a reason to take `&str` or `&T` wherever the body only needs to read. And `MRef` is the +owned-or-borrowed form: it reads a plain `T` field, hands the body a value that may be either, and is +the one reference-shaped row with no mutable counterpart. -Mutability follows the *argument's* type rather than the receiver's. An argument carrying a `&mut` reads -mutably; every other argument — an `MRef` included — reads through a shared borrow, even on a `&mut self` -method. - -The `MRef` row is matched by *shape* rather than by resolving the name: a single-segment `MRef` with one -lifetime argument and one type argument. Anything else spelled `MRef` falls into the owned row and is -cloned, which is the one place a small change to the type silently changes the read. +The macro matches the `MRef` row by *shape* rather than by resolving the name: a single-segment `MRef` +with one lifetime argument and one type argument. Anything else spelled `MRef` falls into the owned row +and is cloned, which is the one place a small change to the type silently changes the read. The same rules govern the getter traits, so learning them once covers everywhere CGP reads a field. +### Mutable arguments + +An implicit argument is mutable when its type carries a `&mut`: the outer reference of a `&mut T` or a +`&mut [T]`, or the inner reference of an `Option<&mut T>` or an `Option<&mut str>`. A mutable argument +reads through [`HasFieldMut`](../traits/has_field_mut.md) and `get_field_mut` rather than through +[`HasField`](../traits/has_field.md) and `get_field`, so it borrows the field for writing. + +Two rules follow. A mutable argument requires a `&mut self` receiver, since a function cannot borrow a +field mutably through a shared `&self`. And it must be the only implicit argument on its function, +because reading one field mutably borrows the whole context exclusively and cannot coexist with any +other field read. + +Mutability follows the *argument's* type rather than the receiver's. An argument carrying a `&mut` reads +mutably, and every other argument, an `MRef` included, reads through a shared borrow. A `&mut self` +function may therefore still take any number of immutable implicit arguments, as long as none of them is +mutable. + +To get a mutable local from a field the body only reads, take the argument immutably and clone it inside +the body. `#[implicit]` rejects a `mut` binding on the argument itself, because a mutable argument means +a mutable field borrow rather than a mutable local copy. + ## Examples A complete capability, and a context that qualifies for it by having the right fields: @@ -115,8 +134,8 @@ pub fn print_area(rect: &Rectangle) { `Rectangle` derives [`HasField`](../derives/derive_has_field.md), which is its entire qualification. There is no wiring anywhere in this program. -Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) provider the attribute behaves identically, and mixes -freely with the method's real arguments — the implicit ones vanish from the signature while `to` and +Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) provider the attribute behaves identically and mixes +freely with the method's real arguments. The implicit ones vanish from the signature while `to` and `body` remain: ```rust @@ -128,31 +147,31 @@ impl EmailSender { } ``` -Callers still write `app.send_email(to, body)`. What the provider needs from its context — an -`smtp_server` field, here borrowed as a `&str` from a `String` — never appears in the trait everyone else +Callers still write `app.send_email(to, body)`. The provider's requirement from its context, an +`smtp_server` field borrowed here as a `&str` from a `String`, never appears in the trait everyone else calls. ## When to reach for it, and when not **Reach for `#[implicit]` by default whenever a provider needs a value from its own context.** It is the shortest form, it introduces no new declaration, and it uses the same field access a getter would, so a -getter trait declared only to read a field adds a name without buying anything. +getter trait declared only to read a field adds a name for no benefit. -That covers more ground than it first appears. An implicit argument reads a plain `&T` by reference with -no clone, so it suits a large value as well as a small one; and a field that several providers each need -is simply declared as the same implicit argument in each of them, which costs nothing and keeps every -provider's requirements visible where the provider is written. +That reach is wider than it first appears. An implicit argument reads a plain `&T` by reference with no +clone, so it suits a large value as well as a small one. A field that several providers each need is +declared as the same implicit argument in each of them, which costs nothing and keeps every provider's +requirements visible where the provider is written. -A **getter trait** earns its keep in the three cases an implicit argument cannot reach. +A **getter trait** is worth using in the three cases an implicit argument cannot reach. - **The field is on a different type.** An implicit argument reads only from `self`, so a value living on - a request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type — - there is no `self` field to read. + a request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type. + There is no `self` field to read. - **The accessor must be a named capability.** When other code depends on "this context can tell you its name" rather than on a field, that dependency needs a trait to point at, importable with [`#[uses]`](uses.md) or usable as a supertrait. - **The getter carries a type inferred from the field.** A getter may declare an associated type and - return it, which keeps the type abstract for callers in a way a concrete parameter cannot. + return it, which keeps the type abstract for callers in a way a concrete argument cannot. For those, use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md), which generates the getter from the method name. [`#[cgp_getter]`](../macros/cgp_getter.md) goes further still and is genuinely advanced: @@ -160,17 +179,7 @@ reach for it only when the *field a getter reads* should be chosen per context a ## Under the hood -:::note - -### Advanced - -This section shows what the attribute injects. You do not need it to use `#[implicit]`, but an -unsatisfied field requirement names the generated bound rather than your parameter, so reading one makes -those errors much easier to follow. `cargo cgp expand` prints the same thing for your own code. - -::: - -Each marked parameter becomes two things: a field bound on the generated implementation, and a `let` +Each marked argument becomes two things: a field bound on the generated implementation, and a `let` binding at the top of the body. From this input: ```rust @@ -180,7 +189,7 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> } ``` -the parameters are stripped from the trait's method and reappear as +the macro strips the arguments from the trait's method and turns them into [`HasField`](../traits/has_field.md) bounds and reads: ```rust @@ -206,26 +215,26 @@ where } ``` -The bindings are inserted in argument order, ahead of every original statement, so the names are in scope -for the whole body. [`Symbol!("width")`](../macros/symbol.md) is a type-level string standing for the -field name; the compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and +The macro inserts the bindings in argument order, ahead of every original statement, so the names are in +scope for the whole body. [`Symbol!("width")`](../macros/symbol.md) is a type-level string standing for the +field name. The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and `cargo cgp expand` resugars it back. The context parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours. Two shapes in the table above generate something other than a `Value = T` equality, which is worth recognizing because it reads oddly at first. A slice argument bounds the *associated type* instead, so -`&[u8]` emits `HasField + 'static>` — any field whose value can be -viewed as a `[u8]` qualifies, rather than one exact type. And every mutable form swaps the trait as well +`&[u8]` emits `HasField + 'static>`, so any field whose value can be +viewed as a `[u8]` qualifies rather than one exact type. And every mutable form swaps the trait as well as the accessor: `&mut u64` emits `HasFieldMut` and reads through `get_field_mut`. -Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the rewrite is the same, with the bounds joining -that provider's `where` clause instead — and with one addition that only a multi-method block can show: -the bounds are collected across *every* method and de-duplicated, so two methods each taking -`#[implicit] name: &str` add one `HasField` bound rather than two. The -`let` bindings are still emitted per method, since each body needs its own. +Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the rewrite is the same, except the bounds join +that provider's `where` clause. One addition shows only in a multi-method block: the macro collects the +bounds across *every* method and de-duplicates them, so two methods each taking `#[implicit] name: &str` +add one `HasField` bound rather than two. The macro still emits the +`let` bindings per method, since each body needs its own. -## Gotchas +## Common Mistakes **The attribute takes no arguments**, and says so rather than ignoring what it was given: @@ -233,7 +242,7 @@ the bounds are collected across *every* method and de-duplicated, so two methods error: `#[implicit]` does not take any arguments; write it as a bare `#[implicit]` ``` -**The parameter must be a plain identifier.** A destructuring pattern reports `Expected an identifier`, +**The argument must be a plain identifier.** A destructuring pattern reports `Expected an identifier`, and a `mut` binding is rejected with the fix in the message: ```text diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md new file mode 100644 index 00000000..bf95cce4 --- /dev/null +++ b/docs/reference/attributes/index.md @@ -0,0 +1,51 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Attributes + +An attribute here is a modifier, not a macro of its own. Each one is an option a host macro reads, +[`#[cgp_impl]`](../macros/cgp_impl.md), [`#[cgp_fn]`](../macros/cgp_fn.md), or +[`#[cgp_component]`](../macros/cgp_component.md), to refine the trait or implementation that macro +generates. This page groups every attribute in this section by the job it does, in roughly the order +most CGP code reaches for them. + +If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here; this page +is the fuller map for once the essentials are familiar. + +## Reading a value from the context + +[`#[implicit]`](./implicit.md) is the one almost every provider uses, and usually the first piece of CGP +anyone writes. It marks a function argument that the macro reads from a same-named field on the context +rather than from the caller, so a provider that needs a value reads like an ordinary function that takes +it. + +## Importing a dependency + +These attributes declare what an implementation depends on, each reading like an import. Most +dependencies belong on the implementation, out of sight of callers, and two of the attributes put one on +the generated trait instead, for when every caller must rely on it. + +[`#[uses]`](./uses.md) imports a consumer trait, or an ordinary Rust trait, that the context must +satisfy, which is the common case. [`#[use_type]`](./use_type.md) imports an abstract type another +component supplies, such as an error type, and lets the signature name it as a bare word instead of a +qualified path. [`#[use_provider]`](./use_provider.md) imports a provider trait a named inner provider +must satisfy, the dependency a higher-order provider declares. + +[`#[extend]`](./extend.md) and [`#[extend_where]`](./extend_where.md) put the requirement on the generated +trait rather than on the implementation, so every caller inherits it: `#[extend]` adds a supertrait, and +`#[extend_where]` adds a `where` predicate a supertrait cannot express. + +## Registering a namespace default + +[`#[default_impl]`](./default_impl.md) lets a provider register itself as a namespace's default for a +key, at the point where the provider is defined rather than in the namespace's own body. Reach for it +once per-type defaults accumulate. + +## Legacy + +[`#[derive_delegate]`](./derive_delegate.md) generates the older `UseDelegate` dispatcher for a component +generic over a type parameter. The `open` statement of +[`delegate_components!`](../macros/delegate_components.md) replaced it for new code; the page is here +because you will meet the form in existing wiring and in CGP's own error and handler components. diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 266a8a38..9b6138a0 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -1,39 +1,40 @@ --- sidebar_label: '#[use_provider]' +sidebar_position: 4 --- # `#[use_provider]` -Depend on another implementation by name, without writing the context argument its bound requires. +Depend on another provider by name, importing the provider trait it must satisfy. ## Overview -An implementation can be parameterized by *another* implementation — a wrapper that scales whatever an -inner calculator produces, a retry layer over whatever performs the request. Declaring that dependency -means bounding the inner one, and the bound has a surprise in it. - -A [provider trait](../macros/cgp_component.md) is not shaped like the trait it came from: the original -`Self` has moved into an explicit leading type parameter for the **context**, the type the implementation -runs against. So while callers write `CanCalculateArea`, an implementation depending on another one has to -write `AreaCalculator` — with a context argument that has no counterpart in the consumer trait, and -that a reader will not expect: +An implementation can depend on *another* implementation: a wrapper that scales whatever an inner +calculator produces, a retry layer over whatever performs a request. This shape is a +[higher-order provider](/docs/concepts/higher-order-providers), and `#[use_provider]` declares its +dependency by importing the [provider trait](../macros/cgp_component.md) the inner provider must satisfy: ```rust -where - InnerCalculator: AreaCalculator, +#[use_provider(InnerCalculator: AreaCalculator)] ``` -`#[use_provider]` lets you leave that argument off. You write the bound as though the provider trait had -the same shape as the trait it came from, and the macro fills the context in: +That reads as *`InnerCalculator` is an `AreaCalculator` for this context*, and it is the provider-side +counterpart to [`#[uses]`](uses.md). Where `#[uses]` imports a **consumer trait** (or an ordinary Rust +trait) that the **context** must satisfy, `#[use_provider]` imports a **provider trait** that a named +provider must satisfy for the context. The context is the type the implementation runs against. Both read +as importing a dependency; they differ only in whether the thing depended on is a capability of the +context or a provider. + +The inner provider is a named type rather than a method on the context, so the body calls it as an +associated function and passes the context: ```rust -#[use_provider(InnerCalculator: AreaCalculator)] +let base_area = InnerCalculator::area(self); ``` -That is the whole of what it does, and knowing the boundary matters: **it completes and inserts a bound, -and it does not touch the body.** The inner implementation is still invoked as an associated function with -the context passed explicitly — `InnerCalculator::area(self)` — because that is what the provider trait's -method actually takes. The attribute removes the surprise from the bound; the call site keeps it. +`#[use_provider]` writes the bound behind that call; it does not rewrite the call. Writing `self.area()` +instead would route through whatever provider the context has itself wired for `AreaCalculator`, which is +a different choice and usually not what a higher-order provider wants. ## Usage @@ -43,19 +44,19 @@ method actually takes. The attribute removes the surprise from the bound; the ca #[use_provider(InnerCalculator: AreaCalculator)] ``` -`InnerCalculator` is the provider — usually a generic parameter of the implementation — and -`AreaCalculator` is the provider trait whose context argument is filled in. The trait may carry further -arguments of its own after the context slot, and those are preserved in order behind the inserted context. +`InnerCalculator` is the provider, usually a generic parameter of the implementation, and +`AreaCalculator` is the provider trait it must satisfy. The trait may carry further arguments of its own, +and the macro preserves those in order. Two forms cover more than one bound, and which you need depends on what is being multiplied. -**One provider, several traits — join them with `+`:** +**One provider, several traits: join them with `+`.** ```rust #[use_provider(Inner: AreaCalculator + PerimeterCalculator)] ``` -**Several providers — one attribute each, stacked:** +**Several providers: one attribute each, stacked.** ```rust #[use_provider(A: AreaCalculator)] @@ -63,7 +64,7 @@ Two forms cover more than one bound, and which you need depends on what is being ``` Stacking is the intended form here rather than a fallback, because a comma-separated list of -provider-and-trait pairs is *not* accepted — see [Gotchas](#gotchas). This differs from +provider-and-trait pairs is *not* accepted (see [Common Mistakes](#common-mistakes)). This differs from [`#[uses]`](uses.md) and [`#[use_type]`](use_type.md), where commas are the preferred way to carry several entries, so it is worth remembering as the exception. @@ -72,7 +73,7 @@ entries, so it is worth remembering as the exception. ## Examples -The archetypal use is a wrapper parameterized by whatever it wraps. Given a component and a plain +The typical use is a wrapper parameterized by whatever it wraps. Given a component and a plain implementation of it: ```rust @@ -124,12 +125,12 @@ delegate_components! { ``` Because the wrapper never names a particular inner implementation, the same `ScaledArea` composes over any -of them — and composition is a type, so `type ScaledRectangle = ScaledArea;` is a complete -way to name the combination. +of them. Composition is itself a type, so `type ScaledRectangle = ScaledArea;` is a +complete way to name the combination. -The attribute is also useful for depending on one *specific* implementation rather than a parameter, which -is what a [`#[cgp_fn]`](../macros/cgp_fn.md) does when it wants a named implementation instead of whatever -the context has wired: +The attribute is also useful for depending on one *specific* implementation rather than a parameter. A +[`#[cgp_fn]`](../macros/cgp_fn.md) does exactly that when it wants a named implementation instead of +whatever the context has wired: ```rust #[cgp_fn] @@ -142,42 +143,36 @@ pub fn rect_area(&self) -> f64 { ## When to reach for it, and when not **Use `#[use_provider]` whenever an implementation depends on another implementation by name**, in -preference to writing the context argument by hand. That is the recommendation, and the explicit -`Inner: AreaCalculator` form is what to read rather than write. +preference to writing the bound by hand. You read the explicit `Inner: AreaCalculator` form in +generated code and older wiring rather than write it. The choice against its neighbours is about *what* is being depended on, and one of the distinctions is easy to miss because both spellings compile. -- **A capability of the context** is [`#[uses]`](uses.md). That bound is on `Self`; this one is on a - separate provider type, which is why `#[uses]` has no context argument to fill in. +- **A capability of the context** is [`#[uses]`](uses.md), which imports a consumer trait or an ordinary + trait the context satisfies. `#[use_provider]` imports a provider trait instead, one that a separate + provider satisfies for the context. - **Whatever the context already chose** needs no attribute at all. Calling `self.area()` in the body routes through the context's own wiring, which is a *different dispatch* from - `InnerCalculator::area(self)` — the first asks the context, the second names an implementation + `InnerCalculator::area(self)`: the first asks the context, the second names an implementation statically. Reach for `#[use_provider]` only when you want the second. - **A choice made per type rather than fixed** is dispatch rather than parameterization, so it belongs in the wiring: the `open` statement of [`delegate_components!`](../macros/delegate_components.md) maps each type to its own implementation. -One ergonomic option is worth knowing when writing the provider struct by hand: giving the parameter a -default of [`UseContext`](../providers/use_context.md) — `pub struct IterSum(...)` — +One ergonomic option is worth knowing when writing the provider struct by hand. Giving the parameter a +default of [`UseContext`](../providers/use_context.md), as in `pub struct IterSum(...)`, makes an unparameterized `IterSum` fall back to the context's own wiring, so the wrapper can be dropped in without naming a base case. ## Under the hood -:::note - -### Advanced - -This section shows the bound the attribute produces. You do not need it to use `#[use_provider]`, but the -inserted argument is exactly what an unsatisfied inner dependency names in an error, so it is worth seeing -once. `cargo cgp expand` prints the same thing for your own code. - -::: - -The attribute inserts the context type as the provider trait's leading argument and appends the completed -bound to the `where` clause. Nothing else changes — the body is emitted as written. From the `ScaledArea` -example: +A [provider trait](../macros/cgp_component.md) is not shaped like the consumer trait it came from: the +original `Self` moves into an explicit leading type parameter for the context, so the real bound on an +inner provider is `InnerCalculator: AreaCalculator`, with a context argument the consumer trait has +no counterpart for. `#[use_provider]` writes that `` for you. It inserts the context type as the +provider trait's leading argument and appends the completed bound to the `where` clause, and nothing else +changes: the macro emits the body as written. From the `ScaledArea` example: ```rust #[cgp_impl(new ScaledArea)] @@ -208,7 +203,7 @@ where } ``` -The `Self` you wrote in the attribute is the context, so it appears as `__Context__` here — the reserved +The `Self` you wrote in the attribute is the context, so it appears as `__Context__` here, the reserved name the surrounding macro inserted. Writing `#[use_provider(InnerCalculator: AreaCalculator)]` is therefore exactly equivalent to writing `where InnerCalculator: AreaCalculator` by hand. @@ -226,11 +221,10 @@ where } ``` -Note that the body is untouched in both. The call stays `InnerCalculator::area(__context__)`, passing the -context as the first argument, because that is the shape the provider trait's method has. +The macro leaves the body untouched in both. The call stays `InnerCalculator::area(__context__)`, passing +the context as the first argument, because that is the shape the provider trait's method has. -
-Formal grammar +## Formal grammar The attribute argument is one provider and the provider traits it must satisfy, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -243,20 +237,18 @@ ProviderBound -> TypePath GenericArgs? ``` Both parts are required. `ProviderType` names the generic parameter the inner provider occupies, and each -`ProviderBound` is the provider trait to require of it — written *without* its leading context argument, +`ProviderBound` is the provider trait to require of it, written *without* its leading context argument, which the attribute inserts. Two restrictions follow from those productions and account for every parse failure this attribute produces. **`ProviderBound` is a path with plain generic arguments**, not a full `TypeParamBound`, so a turbofish or an associated-type binding in that position does not parse; a bound of that shape belongs in -the block's own `where` clause. And **the argument holds exactly one provider**, because the `+`-separated -bound list runs to the end of the attribute — a comma after the first pair lands where a `+` was expected. -That makes this attribute the one exception to the comma-separated convention its siblings follow: bind -several inner providers by stacking one attribute each. See [Gotchas](#gotchas). - -
+the block's own `where` clause. And **the argument holds exactly one provider**, because the +`+`-separated bound list runs to the end of the attribute, so a comma after the first pair lands where a +`+` was expected. That makes this attribute the one exception to the comma-separated convention its +siblings follow: bind several inner providers by stacking one attribute each. See [Common Mistakes](#common-mistakes). -## Gotchas +## Common Mistakes **A comma-separated list of pairs is not accepted.** Writing two providers in one attribute is a parse error, because after the first trait the parser is looking for a `+` to continue that provider's bounds: diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 3ca1e4be..7be1c4fb 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[use_type]' +sidebar_position: 3 --- # `#[use_type]` @@ -8,32 +9,28 @@ Import an abstract associated type and write it as a bare name. ## Overview -Generic CGP code constantly needs a type it does not choose — an error type, a scalar, a database handle — -supplied by the **context**, the type the code runs against. Such a type lives as an -[associated type](https://doc.rust-lang.org/reference/items/associated-items.html) on another trait, and -Rust requires every mention of it to be written out in full: +`#[use_type]` imports a type from the **context**, the type the code runs against. In CGP a type +supplied this way is called an [*abstract type*](/docs/concepts/abstract-types): the code names it, +and the context chooses what it actually is, at compile time, through its +[`delegate_components!`](../macros/delegate_components.md) wiring. -```rust -fn load(&self, path: &str) -> Result::Error>; -``` - -That is correct and almost unreadable, and it has to be repeated at every occurrence — the return type, -each argument, each local binding. `#[use_type]` imports the type once so the signature can name it -plainly: +The type most often imported this way is a context's +[error type](/docs/concepts/modular-error-handling). One attribute lets a fallible signature name it as a +bare `Error`: ```rust #[use_type(HasErrorType.Error)] ``` -With that in place the same method reads `-> Result`, and the macro expands each bare -`Error` back into the qualified path while adding the bound that makes it available. The bare name behaves -like an ordinary type in your source and resolves to the associated type in the output. +A method can then return `Result`, and the code that writes it is reused as is: it +compiles whether the context chose `anyhow::Error`, `Box`, or a plain `String` as +its error type. The code never names any of those; the context does, in its wiring. -Reading better is the obvious benefit; the less obvious one is that the qualified form composes where a -bare one cannot. Because the macro always emits `::Type`, one import can be defined in -terms of another, a type can be pulled from a parameter rather than from `Self`, and two abstract types can -be constrained to be the same — none of which you can express by writing a bare identifier and hoping. -Those are the [advanced forms](#importing-from-another-type) below. +`#[use_type]` reads like a `use` statement for a type, which is what it is, and +[Under the hood](#under-the-hood) shows how the bare name resolves. It also has advanced forms a bare +identifier could not express, covered [below](#importing-from-another-type): pinning the type to a +concrete one, importing it from a parameter rather than the context, and tying two abstract types +together. ## Usage @@ -48,7 +45,7 @@ not `::`**, and that is deliberate: it leaves `::` free for the trait's own path `#[use_type(errors::HasErrorType.Error)]` imports from a trait named by path and `#[use_type(HasFooType.Foo)]` imports from a particular generic instantiation. -By default the type is projected from `Self`, so `Scalar` expands to `::Scalar`. +By default the macro projects the type from `Self`, so `Scalar` expands to `::Scalar`. The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md), [`#[cgp_impl]`](../macros/cgp_impl.md), and [`#[cgp_component]`](../macros/cgp_component.md). @@ -69,21 +66,21 @@ a local alias: #[use_type(HasFooType.{Foo, Bar as Baz})] ``` -Stacking several `#[use_type]` attributes behaves identically, because every attribute's entries are -collected into one list before any of them is resolved — so an alias declared in one is available to -another regardless of which comes first. Reach for a second attribute only when there is a reason. +Stacking several `#[use_type]` attributes behaves identically, because the macro collects every +attribute's entries into one list before it resolves any of them, so an alias declared in one is +available to another regardless of which comes first. Reach for a second attribute only when there is a reason. ### Pinning a type to a concrete one An `= Type` clause imports the type *and* constrains it, which is how a provider says "this only works when -the error type is `AppError`": +the error type is `anyhow::Error`": ```rust -#[use_type(HasErrorType.{Error = AppError})] +#[use_type(HasErrorType.{Error = anyhow::Error})] ``` -That emits `Self: HasErrorType` in place of the plain bound. The right-hand side is -itself substituted, so it may name another import — which is how two abstract types are tied together: +That emits `Self: HasErrorType` in place of the plain bound. The macro substitutes the +right-hand side too, so it may name another import, which is how two abstract types are tied together: ```rust #[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})] @@ -105,7 +102,7 @@ parameter rather than on `Self`: braced group projects every type in it against the same target, and because `in` is a reserved word it can never be mistaken for a type name. -This is also the form that lets an import parameterize the trait it comes from. An alias may appear in +This form also lets an import parameterize the trait it comes from. An alias may appear in another entry's `in` clause *or* in its trait arguments, and the macro resolves the chain for you: ```rust @@ -113,7 +110,7 @@ another entry's `in` clause *or* in its trait arguments, and the macro resolves ``` Here `Pool` is projected from `HasPoolType<::Db>`. Such chains may be written in any -order — see [Under the hood](#under-the-hood) — provided they do not form a cycle. +order (see [Under the hood](#under-the-hood)), provided they do not form a cycle. ## Examples @@ -144,7 +141,7 @@ impl AreaCalculator { ``` The component gains `HasScalarType` as a supertrait and the provider gains it as a bound, and every -`Scalar` in both becomes the same qualified projection — so the fields the provider reads and the value it +`Scalar` in both becomes the same qualified projection, so the fields the provider reads and the value it returns are guaranteed to agree on whatever scalar the context chose. A context supplies the concrete type by wiring, and nothing above changes: @@ -164,8 +161,9 @@ delegate_components! { } ``` -The most common use of all is an error type, where the import saves a projection in every fallible -signature: +The most common use of all is an +[error type](/docs/concepts/abstract-types#the-canonical-one-a-contexts-error-type), where the import +saves a projection in every fallible signature: ```rust #[cgp_component(Loader)] @@ -175,48 +173,43 @@ pub trait CanLoad { } ``` +The error type is one of three decisions a context makes about failure, and +[modular error handling](/docs/concepts/modular-error-handling#why-the-error-type-is-the-hard-one) +separates them. + ## When to reach for it, and when not **Use `#[use_type]` whenever a definition names an abstract type another component supplies.** It is the -recommended form, and a hand-written supertrait plus `Self::`-qualified paths is what to read rather than -write. +recommended form; you read a hand-written supertrait plus `Self::`-qualified paths in existing code rather +than write them. -Two neighbours cover requirements that are not types, and one construct is what `#[use_type]` imports -*from*. +Two neighbours cover requirements that are not types, and one further construct is the one `#[use_type]` +imports *from*. - **A capability** is [`#[uses]`](uses.md) for a private bound or [`#[extend]`](extend.md) for a - supertrait. Reach for `#[extend]` specifically when the supertrait's methods are what matter and its - associated types are not named in your signatures — that is the case `#[use_type]` has nothing to - rewrite. + supertrait. Reach for `#[extend]` specifically when the supertrait's methods matter and its associated + types are not named in your signatures, the case where `#[use_type]` has nothing to rewrite. - **A value from a field** is an [`#[implicit]`](implicit.md) argument. - **The type itself** is declared with [`#[cgp_type]`](../macros/cgp_type.md) and bound to a concrete type - by wiring the component to [`UseType`](../providers/use_type.md). Note that the `UseType` *provider* - and this *attribute* are different things despite the shared name: the provider supplies a type to a - context, and the attribute imports one into a definition. + by wiring the component to [`UseType`](../providers/use_type.md). The `UseType` *provider* and this + *attribute* are [two different things](/docs/concepts/abstract-types#two-things-called-usetype) despite + the shared name: the provider supplies a type to a context, and the attribute imports one into a + definition. -There is one boundary worth stating plainly, because getting it wrong produces a confusing error. A -construct's **own** associated type is not imported and stays qualified as `Self::Output`. `#[use_type]` +One boundary is worth stating plainly, because getting it wrong produces a confusing error. `#[use_type]` +does not import a construct's **own** associated type, so it stays qualified as `Self::Output`. It rewrites only the names it was given, so a local type written bare resolves to nothing. A mixed signature -such as `Result` is therefore correct and idiomatic — the local type qualified, the +such as `Result` is therefore correct and idiomatic: the local type qualified, the imported one bare. Finally, prefer an inferred parameter over an abstract type when the type only ever flows through values the body reads: [`#[impl_generics]`](../macros/cgp_fn.md) on a `#[cgp_fn]` is shorter and needs no wiring. Climb to an abstract type when the type must be named in the capability's own signature, or when two -capabilities have to agree that they mean the same one. +capabilities have to +[agree that they mean the same one](/docs/concepts/abstract-types#one-type-agreed-on-by-everything-that-needs-it). ## Under the hood -:::note - -### Advanced - -This section shows the three steps the attribute performs and what each one touches. You do not need it to -use `#[use_type]`, but the substitution has edges worth knowing, and an unmet import names the generated -bound rather than your import. `cargo cgp expand` prints the same thing for your own code. - -::: - `#[use_type]` runs before the surrounding macro, in three steps: it **grounds** each import's own type positions, **substitutes** every matching bare identifier, then **adds the bound**. @@ -250,9 +243,10 @@ where **Where the bound lands depends on the target.** When the type is projected from `Self` it becomes a *supertrait* of the generated trait, and also a `where` bound on the implementation. When an `in Context` clause names some other type, a supertrait of `Self` would be wrong, so the macro adds a plain -`Context: Trait` predicate — to the implementation, and on `#[cgp_fn]` and `#[cgp_component]` to the -generated trait's own `where` clause as well, since the trait's signatures now mention the projection and -would not otherwise be well-formed. A plain unbounded `` on your function is therefore enough: +`Context: Trait` predicate. That predicate goes on the implementation, and on `#[cgp_fn]` and +`#[cgp_component]` it goes on the generated trait's own `where` clause as well, since the trait's +signatures now mention the projection and would not otherwise be well-formed. A plain unbounded `` +on your function is therefore enough: ```rust pub trait AreaOf @@ -263,31 +257,31 @@ where } ``` -An equality pin is the exception: it stays on the implementation and is never added to the trait. +An equality pin is the exception: it stays on the implementation, and the macro never adds it to the trait. **What substitution touches.** The rewrite matches a single-segment type path with no arguments whose -identifier is an imported name or alias, anywhere it appears — a return type, an argument, a `where` +identifier is an imported name or alias, anywhere it appears: a return type, an argument, a `where` predicate, a local binding. It also reaches an alias used to *qualify* a path, so `Transaction::begin()` becomes `<::Transaction>::begin()`, since `::Assoc::method` is not valid syntax. -The one position left alone is a **bare alias in expression position**, which names a value — something an -abstract type can never be. So an alias sharing its name with a unit struct still constructs the struct: +The rewrite leaves one position alone: a **bare alias in expression position**, which names a value, +something an abstract type can never be. So an alias sharing its name with a unit struct still constructs +the struct: ```rust let value = Marker; // stays the unit struct `Marker` let typed: Marker = todo!(); // becomes ::Marker ``` -**Grounding, and why order does not matter.** Each import is resolved against the imports it *depends on* -rather than the ones written before it, so every arrangement of the same entries produces the same -substitutions and the same bounds. Only the order the bounds are listed in follows the source. A chain like +**Grounding, and why order does not matter.** The macro resolves each import against the imports it +*depends on* rather than the ones written before it, so every arrangement of the same entries produces +the same substitutions and the same bounds. Only the order the bounds are listed in follows the source. A chain like `#[use_type(HasC.C in B, HasB.B in A, HasA.A)]` grounds exactly as its front-to-back spelling does, -and two imports may share one target as readily as chain through it. What has no valid order is a -**cycle** — see the Gotchas. +and two imports may share one target as readily as chain through it. Only a **cycle** has no valid order; +see [Common Mistakes](#common-mistakes). -
-Formal grammar +## Formal grammar The tokens inside `#[use_type(...)]`, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -310,15 +304,13 @@ UseTypeIdent -> IDENTIFIER ( `as` IDENTIFIER )? ( `=` Type )? arguments; their `::` segments belong to the path, while the `.` after the trait begins the associated-type list. An omitted `in ContextPath` defaults the target to `Self`. In each `UseTypeIdent` the leading `IDENTIFIER` is the associated type's own name, `as` gives it a local alias to write in -signatures, and `= Type` pins it with an equality bound — accepted on `#[cgp_fn]` and `#[cgp_impl]`, +signatures, and `= Type` pins it with an equality bound, accepted on `#[cgp_fn]` and `#[cgp_impl]` and rejected on `#[cgp_component]`. -
- -## Gotchas +## Common Mistakes -**Two imports may not share a name or alias.** The substitution could only pick one, so a collision is -rejected rather than resolved: +**Two imports may not share a name or alias.** The substitution could only pick one, so the macro +rejects a collision rather than resolving it: ```text error: Multiple abstract types cannot share the same identifier or alias @@ -364,8 +356,11 @@ Pin the type on the provider with [`#[cgp_impl]`](../macros/cgp_impl.md) instead The ideas behind it: -- [Abstract types](/docs/concepts/abstract-types) — the idea behind the types this attribute - imports. +- [Abstract types](/docs/concepts/abstract-types) — the idea behind the types this attribute imports, + from [choosing the type by wiring](/docs/concepts/abstract-types#choosing-the-type-by-wiring) to + [what an abstract type costs](/docs/concepts/abstract-types#what-it-costs). +- [Modular error handling](/docs/concepts/modular-error-handling) — the error type is the abstract type + this attribute imports most, treated there as one of three independent wiring choices. ## Source diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 1e0e575a..746d8ce2 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[uses]' +sidebar_position: 2 --- # `#[uses]` @@ -8,34 +9,25 @@ Import the capabilities an implementation depends on, reading like a `use` state ## Overview -An implementation usually calls capabilities defined elsewhere, and to do so it has to require that the -**context** — the type it runs against — provides them. Written out, that requirement is a bound on -`Self`: - -```rust -where - Self: RectangleArea, -``` - -Bounding `Self` is unusual in everyday Rust and reads as machinery rather than as intent. `#[uses]` says -the same thing in the register the code is actually in: +`#[uses]` imports the capabilities an implementation depends on. It names a +[consumer trait](../macros/cgp_component.md) (or an ordinary Rust trait) that `Self` must satisfy, so the +body can call it. `Self` here is the **context**, the type the implementation runs against: ```rust #[uses(RectangleArea)] ``` -That reads as *this implementation uses the `RectangleArea` capability*, which is what a `use` statement -means for a name, and the body can then call `self.rectangle_area()` as though the capability had been -imported. - -The two forms generate exactly the same bound, so nothing is gained or lost mechanically. What changes is -that the dependency list stops looking like a constraint the author had to satisfy and starts looking like -a list of what the code needs — which is the reason `#[uses]` is the recommended form and a hand-written -`where Self: Trait` is what you meet in older code. +That reads as *this implementation uses the `RectangleArea` capability*, the same thing a `use` +statement means for a name, and the body can then call `self.rectangle_area()` as though the capability +had been imported. It is the consumer-side counterpart to [`#[use_provider]`](use_provider.md): where +`#[use_provider]` imports a provider trait a named provider must satisfy for the context, `#[uses]` +imports a trait the context itself must satisfy. -One property of that bound is worth naming, because it is the whole point of putting the dependency on -the implementation. It lands on the implementation *only*, never on the trait, so a caller who bounds on -the capability never sees it and never has to repeat it. What an implementation needs is its own business. +The requirement stays private to the implementation. A caller who depends on the capability never sees +it and never has to repeat it, which is the point of declaring the dependency where the implementation +lives rather than on its public interface. Preferring `#[uses]` over a hand-written bound is the +recommendation; the equivalent `where` clause is the older form you meet in existing code, and +[Under the hood](#under-the-hood) shows the two desugar identically. ## Usage @@ -46,17 +38,17 @@ implementation: #[uses(RectangleArea, CanCalculateArea)] ``` -Each entry is a capability, optionally with type arguments — a bare `RectangleArea` becomes +Each entry is a capability, optionally with type arguments: a bare `RectangleArea` becomes `Self: RectangleArea`, and `CanCompute` becomes `Self: CanCompute`. **The trait need not be a CGP construct.** `#[uses(Display)]` and `#[uses(AsRef<[u8]>)]` are accepted and preferred over the equivalent hand-written clause: the attribute only cares that the bound is one a context can satisfy, so an ordinary Rust trait imports exactly as a capability does. -**Prefer one attribute carrying every dependency** — `#[uses(RectangleArea, Display)]` — since a single -list reads as a single set of requirements. Entries may also be split across several `#[uses(...)]` -attributes on the same item and they accumulate into one bound, but reach for a second attribute only -when there is a reason rather than by default. +**Prefer one attribute carrying every dependency**, as in `#[uses(RectangleArea, Display)]`, since a +single list reads as a single set of requirements. Entries may also be split across several +`#[uses(...)]` attributes on the same item, and they accumulate into one bound, but reach for a second +attribute only when there is a reason rather than by default. `#[uses(...)]` is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on [`#[cgp_impl]`](../macros/cgp_impl.md). In both it imports into the thing being defined, and it does not @@ -65,8 +57,8 @@ care how the imported capability was itself produced. ### Bounds beyond the simple form The idiomatic entry is a plain `Trait`, because the attribute is meant to read as an import. An -entry may nonetheless be any bound a `where` clause accepts — an associated-type equality such as -`HasErrorType`, a higher-ranked bound, a lifetime bound — and it lands on the +entry may nonetheless be any bound a `where` clause accepts: an associated-type equality such as +`HasErrorType`, a higher-ranked bound, or a lifetime bound. Each lands on the `where` clause verbatim. Use that generality sparingly, and prefer a more specific tool where one exists. To pin an abstract type @@ -94,9 +86,9 @@ pub fn scaled_area(&self, #[implicit] scale_factor: f64) -> f64 { } ``` -`#[uses(CanCalculateArea)]` is what makes `self.area()` legal. The dependency is on the *consumer* trait -rather than on any particular provider, so every context that can calculate an area gets `scaled_area` -regardless of how it does so — and a context that swaps its area provider keeps `scaled_area` working +`#[uses(CanCalculateArea)]` makes `self.area()` legal. The dependency is on the *consumer* trait rather +than on any particular provider, so every context that can calculate an area gets `scaled_area` +regardless of how it does so. A context that swaps its area provider keeps `scaled_area` working unchanged. The same attribute inside a provider, this time importing a plain function-style capability: @@ -122,10 +114,10 @@ This provider is a two-line adapter: it satisfies the `AreaCalculator` component ## When to reach for it, and when not **Use `#[uses]` for every capability dependency**, in preference to writing the `Self:` bound by hand. -That is the recommendation, and the hand-written form is what to read rather than write. +That is the recommendation; you read the hand-written form in existing code rather than write it. -The distinction that decides between `#[uses]` and its neighbours is *what* is being depended on and -*where the requirement should be visible*. +Two questions decide between `#[uses]` and its neighbours: *what* is being depended on, and *where the +requirement should be visible*. - **A value from the context** is not a capability. Use an [`#[implicit]`](implicit.md) argument, which reads a field directly rather than routing through a trait. @@ -135,20 +127,10 @@ The distinction that decides between `#[uses]` and its neighbours is *what* is b provider trait carries a context argument that `#[uses]` would not fill in. - **A requirement callers should see** belongs on the trait rather than on the implementation: [`#[extend]`](extend.md) makes it a supertrait, and [`#[extend_where]`](extend_where.md) a predicate. - `#[uses]` is for what the implementation needs privately, which is the `use` to their `pub use`. + `#[uses]` keeps a requirement private to the implementation, where those two make it public. ## Under the hood -:::note - -### Advanced - -This section shows what the attribute injects. You do not need it to use `#[uses]`, but it is a short -rewrite and seeing it once explains why the bound never appears on the trait. `cargo cgp expand` prints -the same thing for your own code. - -::: - Every entry becomes one `Self`-anchored predicate on the generated implementation, joined with `+`, and nothing else changes. From this input: @@ -160,8 +142,8 @@ pub fn describe_area(&self) -> String { } ``` -the trait is emitted exactly as it would have been without the attribute, and the implementation carries -the imports: +the macro emits the trait exactly as it would have been without the attribute, and the implementation +carries the imports: ```rust pub trait DescribeArea { @@ -176,22 +158,21 @@ where } ``` -That asymmetry is the mechanism, not a detail: `DescribeArea` is what callers name, and it says nothing +That asymmetry is the mechanism rather than a detail: callers name `DescribeArea`, and it says nothing about `BaseArea` or `Display`, so a caller bounding on it inherits no requirement to pass on. Writing `#[uses(BaseArea, Display)]` is therefore exactly equivalent to writing `where Self: BaseArea + Display` on the function, and the two desugar identically. -Entries split across stacked `#[uses(...)]` attributes are collected before the bound is built, so +The macro collects entries split across stacked `#[uses(...)]` attributes before it builds the bound, so `#[uses(BaseArea)]` above `#[uses(Display)]` produces the same single predicate shown above. The context parameter is literally `__Context__` in the emitted code, and appears as `Self` inside the implementation. Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the behaviour is the same, with the predicates -appended to that provider's `where` clause — which is also where they are picked up by the generated -[`IsProviderFor`](../traits/is_provider_for.md) impl, so an unmet import is reported by name rather than -as a bare missing implementation. +appended to that provider's `where` clause. That is also where the generated +[`IsProviderFor`](../traits/is_provider_for.md) impl picks them up, so the compiler reports an unmet +import by name rather than as a bare missing implementation. -
-Formal grammar +## Formal grammar The attribute argument is a comma-separated list of bounds, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -202,18 +183,16 @@ UsesArgs -> TypeParamBound ( `,` TypeParamBound )* `,`? `TypeParamBound` is the Rust grammar's own bound production, which is wider than the plain `Trait` this attribute is normally written with: a lifetime, a `?Sized`, and an associated-type equality such as -`HasErrorType` all parse. The list may be empty, and the attribute may be repeated — -entries from every occurrence are collected into one `Self:` predicate. The commas separate *bounds*, so -`#[uses(A, B)]` and `#[uses(A)] #[uses(B)]` are the same thing; the single-attribute form is the one to -write. - -
+`HasErrorType` all parse. The list may be empty, and the attribute may be repeated, +with entries from every occurrence collected into one `Self:` predicate. The commas separate *bounds*, so +`#[uses(A, B)]` and `#[uses(A)] #[uses(B)]` are the same thing, and the single-attribute form is the one +to write. -## Gotchas +## Common Mistakes -**Naming a provider trait instead of a consumer trait does not work**, and this is the most likely way to -reach for `#[uses]` when [`#[use_provider]`](use_provider.md) is what you wanted. A provider trait carries -an explicit context parameter, and `#[uses]` does not fill it in, so the bound is incomplete: +**Naming a provider trait instead of a consumer trait does not work**, and it is the most likely way to +reach for `#[uses]` when you actually wanted [`#[use_provider]`](use_provider.md). A provider trait +carries an explicit context parameter, and `#[uses]` does not fill it in, so the bound is incomplete: ```text error[E0107]: missing generics for trait `AreaCalculator` @@ -224,10 +203,10 @@ error[E0107]: missing generics for trait `AreaCalculator` note: trait defined here, with 1 generic parameter: `__Context__` ``` -The `__Context__` in that note is the giveaway. Depend on the **consumer** trait — -`#[uses(CanCalculateArea)]` — when what you want is "whatever this context has wired", which is almost -always the case. Use [`#[use_provider]`](use_provider.md) when you genuinely mean a named implementation, -and it will supply the missing argument. +The `__Context__` in that note points to the mistake. Depend on the **consumer** trait, as in +`#[uses(CanCalculateArea)]`, when you want "whatever this context has wired", which is almost always the +case. Use [`#[use_provider]`](use_provider.md) when you genuinely mean a named implementation, and it +will supply the missing argument. ## Related constructs diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index b6150740..d20ed844 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -196,17 +196,6 @@ Between this derive and its neighbours the choice is about how much of the machi ## Under the hood -:::note - -### Advanced - -This section shows what the derive generates. You do not need it to use `#[derive(BuildField)]`, but the -companion type appears by name in every builder error, so recognizing it turns "no method named -`finalize_build`" into a legible message. `cargo cgp expand` prints the same thing for your own code, with -the tags resugared. - -::: - The derive centres on a companion struct named `__Partial{Name}`. It is your struct with one [`MapType`](../traits/map_type.md) parameter added per field, and each field's type wrapped in that parameter's projection. The marker decides how the field is stored: `IsPresent` maps `T` to `T`, `IsNothing` @@ -299,7 +288,7 @@ way to state — but it does mean a half-built value cannot be printed. Each generated impl is aimed at the token it came from: a per-field impl at its field, a whole-struct impl at the struct name. -## Gotchas +## Common Mistakes **`finalize_build` missing is the expected error, not a bug.** A field left unset means the all-present impl does not apply, and the compiler reports a missing method rather than a missing field. Read it as "some field diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 3a2c4e85..52f2a221 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -149,15 +149,6 @@ give, and it is not free. ## Under the hood -:::note - -### Advanced - -This section covers only what the umbrella itself does. The expansions are on the two shape pages, -because that is where they belong once the derives are documented separately. - -::: - Nothing about the umbrella is special. `#[derive(CgpData)]` inspects the item, dispatches on whether it is a struct or an enum, and then runs exactly the same code path the matching shape-specific derive runs — [`#[derive(CgpRecord)]`](./derive_cgp_record.md#under-the-hood) enters the first directly and @@ -167,11 +158,11 @@ one of the other two. Applied to a union, all three fail: the family models products and sums, and a union is neither. -## Gotchas +## Common Mistakes **Which gotchas apply depends on the shape**, and the shape pages carry them: the -[record ones](./derive_cgp_record.md#gotchas) — the companion's cleared attributes, position-keyed tuple -builders, the newtype special case — and the [variant ones](./derive_cgp_variant.md#gotchas) — the +[record ones](./derive_cgp_record.md#common-mistakes) — the companion's cleared attributes, position-keyed tuple +builders, the newtype special case — and the [variant ones](./derive_cgp_variant.md#common-mistakes) — the one-payload rule and the seven reserved variant names. Two are worth repeating here because they catch people who reached for the umbrella without reading either. diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index 6c798f12..3e347bf2 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -113,16 +113,6 @@ The full argument for when a type earns the extensible-data machinery at all is ## Under the hood -:::note - -### Advanced - -This section shows what the derive generates. You do not need it to use the derive, but the companion -type appears by name in every builder error, so recognizing one turns an intimidating error into a -legible one. `cargo cgp expand` prints the same thing for your own code, with the tags resugared. - -::: - The derive emits three groups in order. From: ```rust @@ -182,7 +172,7 @@ yields a `pub` companion. Each generated impl is aimed at the token it came from its field, a whole-type impl at the type name — so a conflict with a hand-written impl underlines that token rather than the whole derive. -## Gotchas +## Common Mistakes **The companion type carries none of your attributes.** The derive clears them, so a `#[derive(Debug, Clone)]` on the record does not reach `__Partial{Name}` and a partially-built value can diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 650a0ec0..83c88f51 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -138,16 +138,6 @@ The full argument for when a type earns the extensible-data machinery at all is ## Under the hood -:::note - -### Advanced - -This section shows what the derive generates and why the extraction chain can end without a wildcard. -You do not need it to use the derive, but the companion enums appear by name in every extraction error. -`cargo cgp expand` prints the same thing for your own code, with the tags resugared. - -::: - The derive emits three groups in order. From: ```rust @@ -215,7 +205,7 @@ The companion names are reserved: `__Partial{Name}` and `__PartialRef{Name}`. Th type's visibility. Each generated impl is aimed at the token it came from, so a conflict with a hand-written impl underlines that variant rather than the whole derive. -## Gotchas +## Common Mistakes **Every variant needs exactly one unnamed payload**, with no per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in the family that accepts all four diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 7730773c..570cde46 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -206,16 +206,6 @@ derive you did not need. ## Under the hood -:::note - -### Advanced - -This section shows what the derive generates. You do not need it to use `#[derive(ExtractField)]`, but the -companion enums appear by name in every extraction error, so recognizing one turns an intimidating error into -a legible message. `cargo cgp expand` prints the same thing for your own code, with the tags resugared. - -::: - The derive centres on **two** companion enums. `__Partial{Name}` is your enum with one [`MapType`](../traits/map_type.md) parameter added per variant and each payload wrapped in that parameter's projection, where `IsPresent` keeps the payload and `IsVoid` maps it to the uninhabited `Void`. @@ -309,7 +299,7 @@ borrow marker — leaving them in would make both unused parameters. And every b Each generated impl is aimed at the token it came from: a per-variant impl at its variant, a whole-enum impl at the enum name. The companion enums are cloned from yours, so their tokens already carry meaningful spans. -## Gotchas +## Common Mistakes **Every variant must carry exactly one unnamed payload.** A unit, multi-field, or struct-style variant fails, with no per-variant opt-out. Wrap the payload in its own struct — including for a case that carries nothing, diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index c30a5729..145b7abc 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -148,17 +148,6 @@ derived together because a generic pipeline usually does both. ## Under the hood -:::note - -### Advanced - -This section shows what the derive generates. You do not need it to use `#[derive(FromVariant)]`, and this is -the shortest expansion in the family — it is worth reading once because the impls appear by name in errors -about generic construction. `cargo cgp expand` prints the same thing for your own code, with the tags -resugared. - -::: - The derive emits **one impl per variant and nothing else** — no companion type, no markers, no state. From: ```rust @@ -201,7 +190,7 @@ The [`FromVariant`](../traits/from_variant.md) trait itself is defined in the li these per-variant impls. Each is aimed at the variant it came from, so a conflict with a hand-written impl underlines that variant rather than the whole `#[derive(FromVariant)]`. -## Gotchas +## Common Mistakes **Every variant must carry exactly one unnamed payload**, the same requirement the extractor has, with no per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the derive that accepts all four diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index be0a6cd7..f71dcf6a 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -193,16 +193,6 @@ access to fields that already exist. Building a struct up field by field is ## Under the hood -:::note - -### Advanced - -This section shows what the derive generates. You do not need it to use `#[derive(HasField)]`, but a missing -field is reported against the generated bound with the tag fully expanded, so reading one expansion makes -that error legible. `cargo cgp expand` prints the same thing for your own code, with the tags resugared. - -::: - The derive leaves the struct definition untouched and adds **two impls per field** — a read accessor and a mutable one. From this input: @@ -266,7 +256,7 @@ Each generated impl is also aimed at the field it came from, so a compiler error a conflict with a hand-written impl, or the "but the trait is implemented for" hint inside a missing-field error — underlines that field rather than the whole `#[derive(HasField)]`. -## Gotchas +## Common Mistakes **A unit struct produces nothing, silently.** There is no field to key, so the derive succeeds and emits no impls. That is correct, but it means the mistake surfaces later, as an unsatisfied `HasField` bound at a diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index cb929dc4..d07d0233 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -194,16 +194,6 @@ a type you do not own and cannot patch has no shape at all. ## Under the hood -:::note - -### Advanced - -This section shows what the derive generates. You do not need it to use `#[derive(HasFields)]`, but the -`Fields` type appears verbatim in compiler errors about structural code, so reading one expansion makes -those errors legible. `cargo cgp expand` prints the same thing for your own code, with the tags resugared. - -::: - The derive leaves the type definition untouched and emits **five impls**: the shape, the borrowed shape, and three conversions. From a named-field struct: @@ -295,7 +285,7 @@ empty `match`. Each generated impl is aimed at the type name the user wrote, so a conflict with a hand-written `HasFields` impl underlines the struct or enum rather than the whole `#[derive(HasFields)]`. -## Gotchas +## Common Mistakes **A newtype's `Fields` is the inner type, not a one-element product.** `struct Wrapper(String)` has `Fields = String`. Generic code written against `Cons, _>, Nil>` will not match it, and diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 7922f532..40343e2c 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -37,7 +37,7 @@ macro is used throughout CGP wherever a capability is asynchronous: it is simply spelled. One thing it does *not* do is add a `Send` bound, and that omission has consequences the moment a future is -spawned. It is covered under [Gotchas](#gotchas). +spawned. It is covered under [Common Mistakes](#common-mistakes). ## Usage @@ -142,7 +142,7 @@ The decisions worth making are around it rather than about it. - **Do not put it on an impl block.** It is accepted there and does nothing, since the rewrite only applies to trait definitions. Harmless, but it suggests a misunderstanding of where the lint comes from. - **Reach for the `Send`-recovery pattern when a future is spawned**, not for a different macro. No attribute - can add the bound, for the reason in the [Gotchas](#gotchas). + can add the bound, for the reason in the [Common Mistakes](#common-mistakes). - **Consider whether the capability needs to be async at all.** The [handler family](./cgp_computer.md) has synchronous members, and the [promotion combinators](../providers/handler_combinators.md) lift a synchronous provider into an async one where a caller needs it. So a computation that does no I/O is better declared @@ -213,7 +213,7 @@ where `#[async_trait]` then runs on both. On the trait it rewrites the declaration; on the impl it is a no-op, so the `async fn` body survives intact. -## Gotchas +## Common Mistakes **The generated future carries no `Send` bound**, and this is the limitation that matters in practice. Because the rewrite produces a bare `impl Future`, the future is `Send` only when the concrete future diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 8f519f4f..68de46b8 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -243,8 +243,7 @@ about the alias. Associated constants are forwarded like methods: their default expressions become the impl's definitions. A method or constant with no usable default is an error, since the macro has nothing to forward. -
-Formal grammar +## Formal grammar The attribute argument is a single optional context name, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -258,9 +257,7 @@ ContextName -> IDENTIFIER Omitted, the generic context type in the generated impl is the reserved identifier `__Context__`; a given `IDENTIFIER` overrides that name. -
- -## Gotchas +## Common Mistakes **The macro is not in the prelude.** `use cgp::prelude::*;` does not bring it into scope, and the failure is reported as an unknown attribute rather than as a missing import: diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 277ea62c..11a64292 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -51,7 +51,7 @@ Two restrictions are enforced when the macro expands: - **Every trait item must be a method.** Associated types and constants are rejected. - **A method may not have non-lifetime generic parameters.** Lifetimes are fine. The reason is in the - [Gotchas](#gotchas), and it is a real limitation rather than an oversight. + [Common Mistakes](#common-mistakes), and it is a real limitation rather than an oversight. Each method must have a `self` receiver, since the receiver is the enum value being matched. @@ -141,7 +141,7 @@ Reach for something else in four situations. and a unit code, so a context cannot override how one variant is handled. Wiring `MatchWithValueHandlers` into a context's own component gives that control. - **A method needs to be generic.** Not supported, and not fixable by rearranging: see the - [Gotchas](#gotchas). + [Common Mistakes](#common-mistakes). - **The trait needs an associated type or const.** Also rejected. A trait carrying either is not a dispatch trait in this sense; give the enum a component of its own instead. @@ -220,7 +220,7 @@ fn contains(&self, arg_0: f64, arg_1: f64) -> bool { An `async` method selects the `AsyncComputer` form of the bound and the call instead of `Computer`, and awaits the result. -## Gotchas +## Common Mistakes **A trait method cannot be generic**, and the macro explains why in the message itself: diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index e45bd5d5..8681195f 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -302,7 +302,7 @@ where The declared bound moves onto that parameter, so `Display` is required of whatever the field holds. Note that the field tag still comes from the **method** name rather than from the associated type's. -## Gotchas +## Common Mistakes **The field name is fixed to the method name.** A context storing the value under any other name does not satisfy the trait, and because the failure is an unmet bound on a blanket impl the method reads as missing diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index d99a7842..393134e2 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -138,7 +138,7 @@ Three attributes that look like they belong here do not, and the error is confus naming: `#[uses(...)]`, `#[extend_where(...)]`, and `#[use_provider(...)]` are read by [`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_fn]`](./cgp_fn.md) but not by `#[cgp_component]`. None of them is an attribute in its own right, so writing one here leaves a name nothing can resolve; see -[Gotchas](#gotchas). The equivalent of `#[uses]` on a component is a supertrait, written with +[Common Mistakes](#common-mistakes). The equivalent of `#[uses]` on a component is a supertrait, written with `#[extend]`. ## Examples @@ -372,10 +372,9 @@ them into the `IsProviderFor` parameter tuple. That tuple holds types, so a life Bounds and defaults are dropped from the tuple, which names the parameters positionally and nothing more. A const parameter has no place in it at all, which is why the macro rejects one; see -[Gotchas](#gotchas). +[Common Mistakes](#common-mistakes). -
-Formal grammar +## Formal grammar The attribute argument is either a bare provider name or a comma-separated set of keyed values, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -400,9 +399,7 @@ parameters while the provider name may not. The attribute delimiter, `(...)` for `{...}` for the key/value form, is ordinary Rust attribute syntax and does not change how the arguments inside are parsed. -
- -## Gotchas +## Common Mistakes **A const generic parameter on the trait is rejected**, by the macro rather than by the compiler: @@ -418,7 +415,7 @@ An associated `const` *item* is unaffected. `const LIMIT: u64;` as a trait membe [associated const](https://doc.rust-lang.org/reference/items/associated-items.html), not a generic parameter, and a provider supplies it in the ordinary way. Naming your own associated const from *inside* a [`#[cgp_impl]`](./cgp_impl.md) body has a wrinkle of its own, covered in that page's -Gotchas. +[Common Mistakes](./cgp_impl.md#common-mistakes). **The attribute must be applied to a trait.** A struct, an enum, or a free function is refused at parse time with an error naming the trait the macro expected, rather than being lowered into code that diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 69d46a70..e02f7b43 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -231,8 +231,7 @@ reference parameter is preserved too: `fn to_string_ref(value: &V) - `Computer` whose input tuple is `(&V)`, and the bundle's by-reference entries make it serve the `…Ref` components. -
-Formal grammar +## Formal grammar The attribute argument is a single optional provider name, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -247,9 +246,7 @@ Omitted, the provider struct takes the function name converted to PascalCase; a verbatim. The annotated function is plain Rust, and the macro reads its parameters, return type, `async`-ness, generics, and `where` clause to choose the base trait and promotion bundle as described above. -
- -## Gotchas +## Common Mistakes **The function cannot reach the context.** There is no receiver and no context parameter in scope, so `#[implicit]` arguments and `#[uses]` have nothing to attach to. A computation that needs anything from its diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 1d0dce43..98bcd460 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -122,7 +122,7 @@ pub fn describe(&self, #[implicit] name: &Name) -> String { The cost is that the type is concealed rather than named. It exists only where a value of it flows through an implicit argument, so nothing else can refer to it, including this function's own signature. Naming it in a return type or an explicit parameter does not compile, as the -[Gotchas](#gotchas) explain. When the type must be nameable, or when two capabilities have to agree +[Common Mistakes](#common-mistakes) explain. When the type must be nameable, or when two capabilities have to agree that they mean the same type, promote it to an abstract type with [`#[cgp_type]`](./cgp_type.md) and import it with [`#[use_type]`](../attributes/use_type.md). @@ -292,8 +292,7 @@ function's visibility becomes the trait's**, and the impl's method keeps inherit usable only in its own module. And **the macro copies an attribute it does not recognize onto both items**, so `#[allow(...)]`, `#[doc]`, or a doc comment carries onto the trait and the impl alike. -
-Formal grammar +## Formal grammar The attribute argument is a single optional trait name, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -308,9 +307,7 @@ When the argument is omitted, the trait name defaults to the function name conve `#[implicit]` markers on parameters and the companion attributes are separate attributes with grammars of their own, documented on their own pages. -
- -## Gotchas +## Common Mistakes **A function with implicit arguments must take `self` first.** Without a receiver there is no context to read a field from, and the macro says so rather than emitting a bound that fails later: diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 4bdd9fb8..658947b5 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -244,8 +244,7 @@ where Each of these is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl carrying the same bounds, so a missing field is reported by name when the component is checked. -
-Formal grammar +## Formal grammar The attribute argument is the same grammar as [`#[cgp_component]`](./cgp_component.md)'s, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -259,9 +258,7 @@ A bare provider name, or the keyed `name` / `provider` / `context` form. The onl derived from the trait name by stripping a leading `Has` and appending `Getter`, so `HasName` yields `NameGetter`. Every other key and default behaves as documented there. -
- -## Gotchas +## Common Mistakes **A multi-method trait gets no `UseField` provider.** Both `UseField` and `WithProvider` are emitted only for a single-method trait, because each supplies one field. Wiring a two-method getter to diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index fd014ba5..1b53078d 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -194,7 +194,7 @@ list, so a second pair after a comma has nowhere to go; write one attribute per `#[extend_where]`, and `#[impl_generics]`. All three act on a *generated trait definition*, which a provider impl does not have, so they belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to [`#[cgp_component]`](./cgp_component.md). Writing one here leaves a name nothing resolves; see -[Gotchas](#gotchas). An impl-side bound that really is impl-side goes in the block's own `where` +[Common Mistakes](#common-mistakes). An impl-side bound that really is impl-side goes in the block's own `where` clause, which passes through untouched. ### Implementing the consumer trait directly @@ -204,7 +204,7 @@ ordinary consumer-trait impl on a concrete type. This form requires the `for Con it is rejected with an `Expected context type to be specified` error, since there is no context left to find. The form is useful when you want a hand-written impl while still applying the companion attributes. Because the macro does not generate a provider struct here, `new` and the component -override have no effect; see [Gotchas](#gotchas) for what happens if you write them anyway. +override have no effect; see [Common Mistakes](#common-mistakes) for what happens if you write them anyway. ```rust #[cgp_impl(Self)] @@ -351,15 +351,14 @@ provider that supplies `type Output`, because it gathers the block's own associa and skips any `Self::` path starting with one. In the emitted impl, `Self` is the provider struct, which is the type that declares `Output`, so the path still resolves. Every other `Self` in the block is still rewritten, including one naming an abstract type the *context* supplies. Associated consts are -not covered by the exemption; see [Gotchas](#gotchas). +not covered by the exemption; see [Common Mistakes](#common-mistakes). **The rewrite is scoped to the block's own method bodies.** An item nested *inside* a body, such as a local `struct` with its own impl, a helper `fn`, or an inline `trait`, introduces a fresh `self`/`Self` that belongs to that item, exactly as in ordinary Rust, and the macro leaves it alone. Closures, which capture the enclosing `self`, are rewritten like any other expression. -
-Formal grammar +## Formal grammar The attribute argument names the provider, optionally preceded by `new` and followed by a component-type override, in the Rust Reference's @@ -377,9 +376,7 @@ generic provider such as `ScaledAreaCalculator`, or the literal passthrough form. `ComponentType` overrides the component in the generated `IsProviderFor` impl, defaulting to the provider trait's name plus `Component`. Both are Rust `Type` productions. -
- -## Gotchas +## Common Mistakes **A provider's own associated const is awkward to name inside its body**, and this follows directly from the rewrite. The exemption described above covers associated *types* only, so a provider that diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 1a51824b..e6c5a7ea 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -229,7 +229,7 @@ Three lighter tools cover most cases, and it is worth knowing where each stops. Two things a namespace is *not* for. It will not make a single context's wiring shorter on its own; the entries still have to exist somewhere. And it is not how one component gets per-type dispatch, which is -`open`'s job; the two do not combine on the same component, as the [Gotchas](#gotchas) explain. +`open`'s job; the two do not combine on the same component, as the [Common Mistakes](#common-mistakes) explain. ## Under the hood @@ -303,8 +303,7 @@ Two naming details appear verbatim in errors and are worth recognizing: the tabl [type-level list](../types/type_level_spines.md) built by [`Path!`](./path.md); `expand` resugars it to `Path!(@…)` form, while a raw compiler error prints the underlying spine. -
-Formal grammar +## Formal grammar The body is a header and a table, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -345,9 +344,7 @@ NamespacePath -> TypePath GenericArgs? neither grouping form is accepted: one attribute registers under exactly one prefix, and the attribute is repeated to register into several namespaces. `NamespacePath` may itself be parameterized. -
- -## Gotchas +## Common Mistakes **A context cannot override a path its namespace itself terminates.** Joining with `namespace N;` emits a blanket `DelegateComponent` impl covering every path `N` resolves, so a direct entry for one of those paths diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index a9b7d282..b0de9077 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -189,8 +189,7 @@ and derives the remaining members from there. generic, and is not inspected for a `Result` return, there is exactly one base trait and one bundle for every `#[cgp_producer]`: the output type is taken as written, whether or not it happens to be a `Result`. -
-Formal grammar +## Formal grammar The attribute argument is a single optional provider name, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -205,9 +204,7 @@ Omitted, the provider struct takes the function name converted to PascalCase; a verbatim. The annotated function is plain Rust, constrained to a producer's shape (no parameters, no `async`, no generics), as described in [Usage](#usage). -
- -## Gotchas +## Common Mistakes **All three shape restrictions have their own message**, so the macro tells you which one you broke: diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 3ea2cbde..87e5199c 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -298,8 +298,7 @@ provider trait's argument list has nowhere to live in the type-only params tuple *trait's* arguments, not about a const generic on the provider struct, which passes through untouched. And an item that is not an `impl` is refused outright. Each message names what was missing. -
-Formal grammar +## Formal grammar The attribute argument of either macro is a single optional component type, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -315,9 +314,7 @@ substituted into the first position of the generated marker impl. `Type` is the The struct declaration that distinguishes `#[cgp_new_provider]` is implied by the macro name and is not written in the argument. -
- -## Gotchas +## Common Mistakes **`#[cgp_new_provider]` fails if the struct already exists**, which is the usual result of converting one macro to the other and forgetting to delete the declaration: @@ -346,7 +343,7 @@ saying the provider is not a provider for that component. Omit the argument unle departs from the `{Trait}Component` convention. **A provider's own associated const or type still needs qualifying**, though for a different reason than -in [`#[cgp_impl]`](./cgp_impl.md#gotchas). Here `Self` really is the provider, and nothing rewrites it. +in [`#[cgp_impl]`](./cgp_impl.md#common-mistakes). Here `Self` really is the provider, and nothing rewrites it. But the provider struct is also a perfectly good context, so the consumer blanket impl gives it the *consumer* trait as well, and both traits declare the item. `Self::LIMIT` is therefore ambiguous rather than missing: diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 77304ab4..976bf339 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -241,8 +241,7 @@ A bound that names the type it constrains is rewritten rather than refused. Decl becomes `Scalar: Mul + Clone`, with every `Self::Scalar` replaced by the free parameter. Copied unchanged it would have named an associated type of the wrong `Self`. -
-Formal grammar +## Formal grammar The attribute argument is the same grammar as [`#[cgp_component]`](./cgp_component.md)'s, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -256,9 +255,7 @@ A bare provider name, or the keyed `name` / `provider` / `context` form. The onl derived from the **associated type's** name plus `TypeProvider`, so `type Scalar;` yields `ScalarTypeProvider`. Every other key and default behaves as documented there. -
- -## Gotchas +## Common Mistakes **The trait must contain exactly one associated type and nothing else.** A method beside the type, a second type, or no type at all all report the same thing: @@ -301,7 +298,7 @@ note: required for `UseType` to implement `IsProviderFor for ScaledArea -Formal grammar +## Formal grammar The input is one or more check tables, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -323,9 +322,7 @@ list, `FooComponent: []`, falls back to the no-parameter check, exactly as omitt empty *key* list, `[]: Rectangle`, produces no entries at all, so the line silently checks nothing; there is no diagnostic, and it is worth a second look if a table appears to pass without doing anything. -
- -## Gotchas +## Common Mistakes **A check on an aggregate provider asks the wrong question, and how it fails depends on the provider.** A `new`-keyword bundle is not a context, so a context-side check demands that the *bundle* satisfy the leaf diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 904bae1b..acba3c82 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -9,7 +9,7 @@ Wire a context and check that wiring in one macro. ## Overview -CGP's wiring is [lazy](./delegate_components.md#gotchas): a +CGP's wiring is [lazy](./delegate_components.md#common-mistakes): a [`delegate_components!`](./delegate_components.md) entry is accepted without verifying that the provider it names can actually satisfy the component, so a **context** (the type the capability runs against, which supplies the values it needs as its own fields) can compile while being broken. The fix is a @@ -248,7 +248,7 @@ there are three things it cannot do, and each is a reason a larger codebase writ [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time).** A `new`-keyword bundle is a provider other contexts delegate *to*, never a context itself. It has no fields and never stands in the context position, so the derived context-side check asks a question that does not apply to it. Wire a bundle -with plain `delegate_components!`. The [Gotchas](#gotchas) show what the failure looks like, and why it is +with plain `delegate_components!`. The [Common Mistakes](#common-mistakes) show what the failure looks like, and why it is easy to misread. The invariant across all of this is that a context's wiring is checked *somehow*. This macro is the @@ -318,8 +318,7 @@ A generic table threads its generics through both halves, so ` MyContext { derived check the same way, so ` BarGetterAtComponent: UseField` checks as `impl __CanUse…, ()> for MyContext {}`. -
-Formal grammar +## Formal grammar The body is [`delegate_components!`](./delegate_components.md)'s table shape plus the check attributes, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -344,9 +343,7 @@ The `Mapping`, `Key`, `ProviderValue`, and `Statement` productions are exactly `EntryAttr`, and the two are mutually exclusive: `#[check_params(...)]` supplies the parameters a generic component's check needs, and `#[skip_check]` wires the entry with no check at all. -
- -## Gotchas +## Common Mistakes **Used on an aggregate provider, this macro reports a failure that describes nothing real.** A `new`-keyword bundle is not a context, so the derived check asks whether the *bundle* satisfies the leaf provider's diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index f73c89f2..e9572402 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -562,8 +562,7 @@ where A `for` loop produces the same shape once per mapping in its body, plus any predicates its `where` clause adds. -
-Formal grammar +## Formal grammar In the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -639,9 +638,7 @@ opening exactly one component. Every `Statement` precedes every `Mapping`. `Name `ForStmt` are described under [`cgp_namespace!`](./cgp_namespace.md). The macro accepts no attributes anywhere and rejects any it finds. -
- -## Gotchas +## Common Mistakes **Wiring is lazy.** A table with a missing entry, or one naming a provider whose own dependencies are unmet, still compiles. The failure appears later, at the place the capability is used, often as a long @@ -681,7 +678,7 @@ names an unresolved type rather than anything about wiring. as a wiring one. This covers the obvious duplicate, an `open` header colliding with an explicit mapping for the same component, and a generic ` AreaCalculatorComponent` entry overlapping a specific `AreaCalculatorComponent` one. The same applies to a direct entry for a path a -joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#gotchas). +joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#common-mistakes). ## Related constructs diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 24fb4bd4..500ab256 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -173,8 +173,7 @@ uniformly. An `open` statement's per-entry key comes back as a raw `PathCons` sp target is resugared. Seeing the same kind of type in two spellings in one expansion is expected rather than a sign that they differ. -
-Formal grammar +## Formal grammar The input is a leading `@` followed by one or more dot-separated segments, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -191,9 +190,7 @@ becomes a `Symbol` type-level string, while every other segment (a capitalized n the named type. [`cgp_namespace!`](./cgp_namespace.md) entries and `#[prefix(...)]` attributes embed this same grammar, where it appears as the `Path` production. -
- -## Gotchas +## Common Mistakes **The leading `@` is not optional**, and the macro says exactly what it wanted: diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 38243542..75300f21 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -151,8 +151,7 @@ macros: they are the same fold at two levels. chains, and the position where they diverge is the field that differs. An error mentioning `Cons>` where you expected three fields is telling you the third entry is missing. -
-Formal grammar +## Formal grammar Both macros take a possibly-empty comma-separated list, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -168,9 +167,7 @@ grammar of the value macro `product!`, used in expression position. `Type` and ` grammar's productions. Both lists may be empty (`Product![]`, `product![]`) or carry a trailing comma, and they line up positionally so a `product!` value has the type the corresponding `Product!` builds. -
- -## Gotchas +## Common Mistakes **`Product!` and `product!` differ only in case, and the compiler's complaint will not say so.** Using the type macro in expression position fails inside the macro's own parser, which is expecting a type, so the diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index ea9a7be6..daf671b1 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -133,8 +133,7 @@ again, so the code stops compiling. The same guarantee a concrete `match` gives, The macro builds the chain by folding the element types right to left onto `Void`. -
-Formal grammar +## Formal grammar The input is a possibly-empty comma-separated list of types, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -146,9 +145,7 @@ SumInput -> ( Type ( `,` Type )* `,`? )? `Type` is the Rust grammar's type production, and the list may be empty (`Sum![]`) or carry a trailing comma. The macro is used in type position, and each listed type is one possible variant of the sum. -
- -## Gotchas +## Common Mistakes **The empty sum is uninhabited, not empty-but-usable.** `Sum![]` is `Void`, so a function claiming to return one can never return at all. That is deliberate and occasionally useful, but it is not the analogue of an empty diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 86a232c2..e7718ea8 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -176,8 +176,7 @@ against the expanded tag, so an error mentioning `HasField>>>` is telling you the field `width` is missing. Counting the characters is enough to decode it, and `cargo cgp check` resugars the common cases. -
-Formal grammar +## Formal grammar The input is a single string literal, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): @@ -190,9 +189,7 @@ SymbolInput -> STRING_LITERAL empty string and multi-byte Unicode. The macro is used in type position, and this single literal is the whole of its input. -
- -## Gotchas +## Common Mistakes **The `LEN` in an expanded `Symbol` is bytes, not characters.** For ASCII the two coincide, which is why the distinction only shows up on non-ASCII field names, where the number will not match the visible character diff --git a/docs/reference/traits/append_product.md b/docs/reference/traits/append_product.md index c895ecfb..dbe2d4ad 100644 --- a/docs/reference/traits/append_product.md +++ b/docs/reference/traits/append_product.md @@ -97,15 +97,6 @@ There is no `AppendSum`. Growing a sum is not an operation this layer provides. ## Under the hood -:::note - -### Advanced - -This section shows the recursion. It is four lines, and reading it makes -[`ConcatProduct`](./concat_product.md) obvious for free. - -::: - The trait is a pair of impls, one for the spine's `Cons` node and one for its `Nil` terminator. Each head is kept and the tail rebuilt, with a single-element list grafted on at the end: @@ -128,7 +119,7 @@ different orders are unrelated types. All of this is resolved during type checking. There is no `fn` anywhere on this page. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. This is the first thing that goes wrong when reaching for it. diff --git a/docs/reference/traits/build_field.md b/docs/reference/traits/build_field.md index 167b2239..e11d2a2f 100644 --- a/docs/reference/traits/build_field.md +++ b/docs/reference/traits/build_field.md @@ -90,14 +90,6 @@ the record.** ## Under the hood -:::note - -### Advanced - -This section shows why the trait is not generated. - -::: - `BuildField` is a **library blanket impl** over [`UpdateField`](./update_field.md), pinning the target marker to `IsPresent` and constraining the reported source marker to `IsNothing`: @@ -118,7 +110,7 @@ because the old value under `IsNothing` is `()`. [`TakeField`](./take_field.md) is the mirror image — the same primitive with `IsNothing` as the target and `Mapper = IsPresent` — which is why the two read as opposites and share every mechanism. -## Gotchas +## Common Mistakes **Building a field twice does not compile.** The second call finds `Mapper = IsPresent` and no impl. That is the guarantee, and the error is a missing-method one rather than anything mentioning "already set". diff --git a/docs/reference/traits/can_build_from.md b/docs/reference/traits/can_build_from.md index 97e3e79d..bc74b1fb 100644 --- a/docs/reference/traits/can_build_from.md +++ b/docs/reference/traits/can_build_from.md @@ -92,14 +92,6 @@ machinery, the names must match exactly, and nothing is inspected at run time. ## Under the hood -:::note - -### Advanced - -This section shows the recursion, which is the record mirror of the variant casts'. - -::: - `CanBuildFrom` **recurses over the source's field product.** For each field the source exposes, it uses [`TakeField`](./take_field.md) to remove that value from the source and [`BuildField`](./build_field.md) to write it into the target builder, threading both the shrinking source and the growing builder through @@ -112,7 +104,7 @@ One asymmetry in the source is worth knowing if you read it: this recursion, `Fi **private**, while the variant casts' `FieldsExtractor` is public. So the extractor recursion can appear by name in a diagnostic and be named in a bound; this one cannot. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::impls`. diff --git a/docs/reference/traits/can_build_with_default.md b/docs/reference/traits/can_build_with_default.md index baa9022a..90b1d258 100644 --- a/docs/reference/traits/can_build_with_default.md +++ b/docs/reference/traits/can_build_with_default.md @@ -86,14 +86,6 @@ in between needs to happen. ## Under the hood -:::note - -### Advanced - -This section shows the composition, which is all there is to it. - -::: - The impl chains the three steps and constrains each with a bound: ```rust @@ -116,7 +108,7 @@ remaining fields — through a [`TransformMapFields`](./transform_map_fields.md) So an unsatisfied bound here is always really an unsatisfied bound one layer down, which is worth knowing because the error names that layer rather than this trait. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. diff --git a/docs/reference/traits/can_downcast.md b/docs/reference/traits/can_downcast.md index 00316e72..5a9f7e95 100644 --- a/docs/reference/traits/can_downcast.md +++ b/docs/reference/traits/can_downcast.md @@ -92,14 +92,6 @@ first starts the chain and the second continues it on each remainder. ## Under the hood -:::note - -### Advanced - -This section shows the recursion, and why the remainder is the shape it is. - -::: - **The downcasts recurse over the *target's* variants**, which is the mirror image of [`CanUpcast`](./can_upcast.md#under-the-hood) walking the source's. For each `Field` in `Target::Fields`, the implementation tries pulling that variant out of the source extractor: on success @@ -112,7 +104,7 @@ this one calls [`to_extractor`](./has_extractor.md) on the enum first, while tha extractor it is handed. That is the entire reason two traits exist rather than one, and it is what makes chaining possible — the `Remainder` a `downcast` returns is precisely a `downcast_fields` input. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::impls`. diff --git a/docs/reference/traits/can_downcast_fields.md b/docs/reference/traits/can_downcast_fields.md index 84ec55f4..5aca25a0 100644 --- a/docs/reference/traits/can_downcast_fields.md +++ b/docs/reference/traits/can_downcast_fields.md @@ -97,15 +97,6 @@ use: its `Self` is a remainder, and a remainder only ever comes from a prior dow ## Under the hood -:::note - -### Advanced - -This section is one paragraph, because the recursion is -[`CanDowncast`](./can_downcast.md#under-the-hood)'s. - -::: - Both traits walk the *target's* variant list, trying to pull each one out of the extractor they hold and threading the shrunken remainder into the next attempt, with the terminal `Void` impl returning the whole remainder as `Err`. The only difference is the entry point: `CanDowncast` calls @@ -116,7 +107,7 @@ Because the remainder type narrows at every step, a chain's types are all distin knows at each point exactly which variants remain — the same narrowing a hand-written [extraction chain](./extract_field.md) performs. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::impls`. diff --git a/docs/reference/traits/can_finalize_with_default.md b/docs/reference/traits/can_finalize_with_default.md index cb4abe6b..c6d5c0d9 100644 --- a/docs/reference/traits/can_finalize_with_default.md +++ b/docs/reference/traits/can_finalize_with_default.md @@ -92,14 +92,6 @@ The one-call form that also copies from a source is ## Under the hood -:::note - -### Advanced - -This section shows the two-line body, which is the clearest statement of how the layer works. - -::: - The whole impl is a transform followed by the ordinary finalize: ```rust @@ -128,7 +120,7 @@ symmetrically. Because the transform targets `IsPresent`, the value handed to `finalize_build` is at exactly the configuration its single impl requires — so the strict check runs, and cannot fail. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. diff --git a/docs/reference/traits/can_upcast.md b/docs/reference/traits/can_upcast.md index 6dfee7da..7e4ad388 100644 --- a/docs/reference/traits/can_upcast.md +++ b/docs/reference/traits/can_upcast.md @@ -94,15 +94,6 @@ has not derived the machinery cannot participate at all. ## Under the hood -:::note - -### Advanced - -This section shows the recursion. You do not need it to call `upcast`, but it explains why the widening -is total where a narrowing is not. - -::: - `CanUpcast` **recurses over the source's variants**. It converts the source to its extractor with [`HasExtractor`](./has_extractor.md), then walks the source's own field list, pulling each variant out with [`ExtractField`](./extract_field.md) and rebuilding it into the target with @@ -116,7 +107,7 @@ One detail from the source is worth knowing if you read it: the recursion drivin `FieldsExtractor`, is **public**, so it can appear by name in a diagnostic and be named in a bound. Its record-side analogue `FieldsBuilder`, behind [`CanBuildFrom`](./can_build_from.md), is private. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::impls`. This is the first thing that goes wrong. diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/can_use_component.md index c43d9d9f..4ac72a78 100644 --- a/docs/reference/traits/can_use_component.md +++ b/docs/reference/traits/can_use_component.md @@ -167,15 +167,6 @@ verify those — they surface as themselves. ## Under the hood -:::note - -### Advanced - -This section shows how the two bounds distinguish the two ways wiring goes wrong. You do not need it to write -a check, but it is what tells you whether to add a wiring line or supply a dependency. - -::: - The blanket impl *is* the behaviour, and its two bounds fail differently — which is the practical payoff. **The first bound failing means the wiring is absent.** `Context: DelegateComponent` is unmet when @@ -196,7 +187,7 @@ supertrait is this bound, then one empty impl of that trait per checked entry. E supertrait holds, so the table is an assertion. Because it produces no values, a successful build *is* the passing test. -## Gotchas +## Common Mistakes **It is not the consumer trait.** `Person: CanUseComponent` holding is not the same statement as `Person: CanGreet`, even though in practice one follows the other. The check exists precisely diff --git a/docs/reference/traits/concat_path.md b/docs/reference/traits/concat_path.md index 3fc3eae1..b3b36e47 100644 --- a/docs/reference/traits/concat_path.md +++ b/docs/reference/traits/concat_path.md @@ -90,15 +90,6 @@ nothing to concatenate. ## Under the hood -:::note - -### Advanced - -This section shows the recursion, which is [`ConcatProduct`](./concat_product.md#under-the-hood)'s over -the path spine. - -::: - Two impls, one per spine node. Each node keeps its head segment and rebuilds the tail; the terminator becomes the other path outright: @@ -125,7 +116,7 @@ resolution proportional to the first path's length. It never touches a value; it only names the combined path type, which a getter or a [`RedirectLookup`](../providers/redirect_lookup.md) then uses to descend. -## Gotchas +## Common Mistakes **[`Path!`](../macros/path.md) requires a leading `@`.** `Path!(a.b)` does not parse; `Path!(@a.b)` does. This is the most common way an otherwise-correct `ConcatPath` example fails to build. diff --git a/docs/reference/traits/concat_product.md b/docs/reference/traits/concat_product.md index 2bee9772..ab7df5a6 100644 --- a/docs/reference/traits/concat_product.md +++ b/docs/reference/traits/concat_product.md @@ -88,15 +88,6 @@ There is no `ConcatSum`. Combining two sums is not an operation this layer provi ## Under the hood -:::note - -### Advanced - -This section shows the recursion, which is [`AppendProduct`](./append_product.md#under-the-hood)'s with -one line changed. - -::: - Two impls, one per spine node. Each head is kept and the tail rebuilt; at the terminator, the whole second list is substituted: @@ -119,7 +110,7 @@ append is a special case. The recursion walks the *first* list only, so its cost is proportional to the left operand's length rather than to the result's. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/contains_value.md index 53e7bc3c..2ecc2d61 100644 --- a/docs/reference/traits/contains_value.md +++ b/docs/reference/traits/contains_value.md @@ -94,14 +94,6 @@ of this. ## Under the hood -:::note - -### Advanced - -This section shows where a bind step uses it. - -::: - The [`BindOk` and `BindErr`](../providers/monad_providers.md) providers use `ContainsValue` in their [`Computer`](../components/computer.md) and `AsyncComputer` impls. Running one bind step means: take the step's output, ask the monad what value sits beneath its wrapper, and hand that to the continuation. This @@ -114,7 +106,7 @@ traits bracket one step: unwrap, run, re-wrap. Because the transformer forms implement it by delegating to the base monad, the unwrapping composes without any depth-specific code. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::monad::traits`. diff --git a/docs/reference/traits/default_impls1.md b/docs/reference/traits/default_impls1.md index 88356b46..7791a30a 100644 --- a/docs/reference/traits/default_impls1.md +++ b/docs/reference/traits/default_impls1.md @@ -162,14 +162,6 @@ Wiring that must live downstream goes in the namespace body of the crate that ow ## Under the hood -:::note - -### Advanced - -This section shows what the `for … in` loop generates. - -::: - A `for in DefaultImpls1 { … }` loop emits a [`DelegateComponent`](./delegate_component.md) impl whose `where` clause projects the default: @@ -190,7 +182,7 @@ this trait for the key type, carrying **only** the parameters naming the key and provider's impl and its [`IsProviderFor`](./is_provider_for.md), and are checked when a real context resolves it. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::component`. [`DefaultNamespace`](./default_namespace.md) is. diff --git a/docs/reference/traits/default_impls2.md b/docs/reference/traits/default_impls2.md index 1b32c704..f7f59636 100644 --- a/docs/reference/traits/default_impls2.md +++ b/docs/reference/traits/default_impls2.md @@ -119,15 +119,6 @@ and is worked out on [its page](./default_impls1.md#when-to-reach-for-it-and-whe ## Under the hood -:::note - -### Advanced - -This section is short, because the mechanism is -[`DefaultImpls1`](./default_impls1.md#under-the-hood)'s with one more parameter. - -::: - A `for … in` loop emits a [`DelegateComponent`](./delegate_component.md) impl whose `where` clause projects the default: @@ -145,7 +136,7 @@ are checked when a real context resolves it. Because nothing in the library emits this trait, there is no generated code to compare against — the impls you see are the ones you or the attribute wrote. -## Gotchas +## Common Mistakes **Nothing inside CGP uses it.** There is no generated code to pattern-match against, and no worked library example. diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md index 4ada2a64..78cb2a03 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/default_namespace.md @@ -110,14 +110,6 @@ where the syntax requires it.** It appears in a `namespace` header and nowhere e ## Under the hood -:::note - -### Advanced - -This section shows what a `namespace` header generates, and why an override does not conflict with it. - -::: - A `namespace N;` header does not emit one entry — it emits a **blanket** [`DelegateComponent`](./delegate_component.md) impl on the context that forwards every key through the namespace: @@ -144,7 +136,7 @@ forwarding any key the parent resolves, so the child resolves everything the par entries — and a context's direct entry still shadows either. All of it is projections, resolved at compile time, with nothing at run time. -## Gotchas +## Common Mistakes **A namespace default is a fallback, not an assignment.** It resolves only for keys the context does not wire directly, which is the intent, and it means a stray direct entry can silently shadow a default you diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/delegate_component.md index 683f48bb..39d1e13e 100644 --- a/docs/reference/traits/delegate_component.md +++ b/docs/reference/traits/delegate_component.md @@ -188,16 +188,6 @@ implementation is one of several, or is shared, or should compose with a wrapper ## Under the hood -:::note - -### Advanced - -This section shows how the generated code reads the table. You do not need it to wire a context, but the -trait's name appears in wiring errors and the routing explains why a call resolves the way it does. -`cargo cgp expand` prints the impls for your own code. - -::: - The trait is the plainest thing in CGP — one associated type, no method — so the interesting part is what reads it. The provider blanket impl generated by [`#[cgp_component]`](../macros/cgp_component.md) is the reader, and its body is itself a table lookup: it bounds the provider on `DelegateComponent` @@ -227,7 +217,7 @@ is both resolvable and checkable; the pair is what through the namespace, which is how a context inherits a whole table while still letting a direct entry shadow one key. -## Gotchas +## Common Mistakes **A missing entry and an unsatisfied provider are different errors.** `DelegateComponent` not implemented means the component was never wired. A wired component whose provider's dependencies are unmet fails diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md index 1fbbf43e..fccb3abe 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/extract_field.md @@ -114,15 +114,6 @@ the whole family is [`HasBuilder`](./has_builder.md). ## Under the hood -:::note - -### Advanced - -This section shows how narrowing is encoded. The partial enums appear by name in every extraction error, -so recognizing one makes those errors legible. - -::: - The derive generates a companion enum with one [`MapType`](./map_type.md) parameter per variant, each payload wrapped in that parameter's projection: @@ -149,7 +140,7 @@ The borrowed accessors use the same partial enum with an extra [`MapTypeRef`](./ parameter fixed to `IsRef` or `IsMut`, so a value can be matched without being moved and the narrowing works identically. -## Gotchas +## Common Mistakes **`Self` is an extractor, not the enum.** A chain starts with [`to_extractor`](./has_extractor.md) or one of its borrowing siblings. diff --git a/docs/reference/traits/field_getter.md b/docs/reference/traits/field_getter.md index a002d80f..2ce020ec 100644 --- a/docs/reference/traits/field_getter.md +++ b/docs/reference/traits/field_getter.md @@ -111,14 +111,6 @@ requires; the other is what a context supplies. ## Under the hood -:::note - -### Advanced - -This section shows the impl that connects wiring to a context's own fields. - -::: - The provider side connects to ordinary derived field access through one blanket impl: [`UseContext`](../providers/use_context.md) implements `FieldGetter` for any context that already has the field, delegating straight through. @@ -146,7 +138,7 @@ The lifetime-safe variant [`FieldMapper`](./field_mapper.md) is a blanket impl o with the getter and tag `'static`, which is what [`ChainGetters`](../providers/chain_getters.md) relies on. -## Gotchas +## Common Mistakes **`Self` is the provider, not the context.** The context is the first type parameter. Reading the signature the other way round is the usual confusion when meeting a provider trait, and it applies to diff --git a/docs/reference/traits/field_mapper.md b/docs/reference/traits/field_mapper.md index faa4d293..6920d0ca 100644 --- a/docs/reference/traits/field_mapper.md +++ b/docs/reference/traits/field_mapper.md @@ -121,14 +121,6 @@ whether composing the existing ones does the job. ## Under the hood -:::note - -### Advanced - -This section explains the two `'static` bounds and why they cost nothing. - -::: - `FieldMapper` is a blanket impl over every [`FieldGetter`](./field_getter.md), with two `'static` bounds that its consumer-side twin needs only one of: @@ -144,7 +136,7 @@ lifetime the naive chained read could not express. path segment, so an arbitrarily deep chain stays lifetime-correct. Because the impl is blanket, adding a new getter provider makes it chainable with no extra work. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. [`MapField`](./map_field.md) is the other non-prelude member of the group. diff --git a/docs/reference/traits/finalize_build.md b/docs/reference/traits/finalize_build.md index 568ba3db..e942fdc4 100644 --- a/docs/reference/traits/finalize_build.md +++ b/docs/reference/traits/finalize_build.md @@ -103,14 +103,6 @@ forgot, and it is the only place the compiler names it. ## Under the hood -:::note - -### Advanced - -This section shows the impl, and why the error reads the way it does. - -::: - The derive emits one impl, with every marker fixed: ```rust @@ -141,7 +133,7 @@ The optional layer reaches this same impl rather than replacing it: [`TransformMapFields`](./transform_map_fields.md) to `IsPresent` first, so **the strict, all-present impl remains the only way a partial value becomes a concrete struct.** -## Gotchas +## Common Mistakes **"No method named `finalize_build`" is the expected error for an incomplete build.** Read the partial type in the message: the field whose marker is still `IsNothing` is the one missing. diff --git a/docs/reference/traits/finalize_extract.md b/docs/reference/traits/finalize_extract.md index 39f4f194..6a9b9268 100644 --- a/docs/reference/traits/finalize_extract.md +++ b/docs/reference/traits/finalize_extract.md @@ -85,15 +85,6 @@ remainder.** The two do the same job at different points in the chain. ## Under the hood -:::note - -### Advanced - -This section is the exhaustiveness argument in full, and it is the one part of the extractor family worth -reading closely. - -::: - **Everything turns on what `IsVoid` maps to.** The [`MapType`](./map_type.md) marker `IsVoid` maps a payload to the uninhabited [`Void`](../types/type_level_spines.md), so once every variant's marker is `IsVoid`, every arm of the partial enum holds a `Void` and **the whole type is uninhabited**. @@ -119,7 +110,7 @@ no value can be in. That is exactly why a builder needs an explicit all-present [`FinalizeBuild`](./finalize_build.md) impl while an extractor can discharge its remainder with an empty `match`. -## Gotchas +## 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`, so the compiler reports a missing method. Read the type in diff --git a/docs/reference/traits/finalize_extract_result.md b/docs/reference/traits/finalize_extract_result.md index c60a0a43..34f3aabe 100644 --- a/docs/reference/traits/finalize_extract_result.md +++ b/docs/reference/traits/finalize_extract_result.md @@ -107,14 +107,6 @@ let rect = shape ## Under the hood -:::note - -### Advanced - -This section is short: the trait is one blanket impl. - -::: - The impl delegates to [`FinalizeExtract`](./finalize_extract.md) on the error half, which is where the soundness argument lives — 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. @@ -126,7 +118,7 @@ outside the extractor family, for collapsing a `Result` that a signature require `Output` being an associated type rather than a generic is what lets the call sit at the end of a method chain with nothing to annotate. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import it from `cgp::core::field::traits`. Without it there is no `finalize_extract_result` in scope and the chain has no clean ending — and the error is a diff --git a/docs/reference/traits/finalize_optional.md b/docs/reference/traits/finalize_optional.md index bb193120..8f9a542e 100644 --- a/docs/reference/traits/finalize_optional.md +++ b/docs/reference/traits/finalize_optional.md @@ -96,14 +96,6 @@ which field is missing and not enough to match on programmatically. ## Under the hood -:::note - -### Advanced - -This section shows why this one walks the shape itself rather than using a transform. - -::: - Unlike its defaulting sibling, `FinalizeOptional` does **not** go through [`TransformMapFields`](./transform_map_fields.md). It walks the target's [`HasFields`](./has_fields.md) spine directly, and the reason is that it has to be able to *stop*. @@ -125,7 +117,7 @@ before it is invoked — or reports why it could not be. That short-circuiting is also why only the *first* missing field is named: the walk stops at it rather than collecting. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. diff --git a/docs/reference/traits/from_fields.md b/docs/reference/traits/from_fields.md index 154f1046..6ff6dd81 100644 --- a/docs/reference/traits/from_fields.md +++ b/docs/reference/traits/from_fields.md @@ -91,14 +91,6 @@ direction happens. ## Under the hood -:::note - -### Advanced - -This section shows the generated impl, which is `to_fields` read backwards. - -::: - The conversion destructures the `Cons` chain positionally and unwraps each entry's value: ```rust @@ -117,7 +109,7 @@ exist only to make the types distinct. An enum's impl is the dual: a `match` over the `Either` chain, each arm reconstructing the corresponding variant, with the `Void` terminator unreachable by construction. -## Gotchas +## Common Mistakes **It is an associated function, not a method.** Write `T::from_fields(fields)`; there is no receiver. diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md index 21e17160..06ddf76c 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/from_variant.md @@ -131,15 +131,6 @@ The split with its counterpart is exactly what the names say: this trait puts a ## Under the hood -:::note - -### Advanced - -This section shows what the derive emits. It is the shortest expansion in the family, and worth reading once -because the impls appear by name in errors about generic construction. - -::: - The derive emits **one impl per variant and nothing else**: ```rust @@ -170,7 +161,7 @@ The trait itself is defined in the library; the derive supplies only these per-v the variant it came from, so a conflict with a hand-written impl underlines that variant rather than the whole derive. -## Gotchas +## Common Mistakes **The tag must be written out, not inferred.** `Shape::from_variant(PhantomData::, value)` needs the turbofish, because nothing in the value determines the variant when two variants could share a payload diff --git a/docs/reference/traits/has_builder.md b/docs/reference/traits/has_builder.md index b8f1ee48..46f4273b 100644 --- a/docs/reference/traits/has_builder.md +++ b/docs/reference/traits/has_builder.md @@ -120,16 +120,6 @@ are a different family: [`ExtractField`](./extract_field.md) for taking a value ## Under the hood -:::note - -### Advanced - -This section shows what `Builder` actually is, and why finalizing early fails. The partial type appears -by name in every builder error, so recognizing it turns "no method named `finalize_build`" into a legible -message. - -::: - The derive generates a companion struct — `__Partial{Name}` — that is your struct with one [`MapType`](./map_type.md) parameter added per field and each field's type wrapped in that parameter's projection: @@ -166,7 +156,7 @@ Everything between the two ends reduces to one primitive, [`UpdateField`](./upda what the derive actually writes; [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are library blanket impls over it in opposite directions. -## Gotchas +## Common Mistakes **"No method named `finalize_build`" is the expected error for an incomplete build.** A missing field means the all-present impl does not apply, so the compiler reports a missing method rather than a missing diff --git a/docs/reference/traits/has_extractor.md b/docs/reference/traits/has_extractor.md index d84883b8..dd748cac 100644 --- a/docs/reference/traits/has_extractor.md +++ b/docs/reference/traits/has_extractor.md @@ -99,14 +99,6 @@ accessor otherwise — the weakest that works is the right one. ## Under the hood -:::note - -### Advanced - -This section shows what `Extractor` is. - -::: - The derive generates a companion enum with one [`MapType`](./map_type.md) parameter per variant, and this trait fixes the starting configuration to all-possible: @@ -133,7 +125,7 @@ families share directly. Narrowing from here is [`ExtractField`](./extract_field.md), and the chain ends at [`FinalizeExtract`](./finalize_extract.md). -## Gotchas +## Common Mistakes **It consumes the value.** Reach for [`HasExtractorRef`](./has_extractor_ref.md) when the original must survive. This is the commonest over-requirement in the family. diff --git a/docs/reference/traits/has_extractor_mut.md b/docs/reference/traits/has_extractor_mut.md index ce370a98..f1911225 100644 --- a/docs/reference/traits/has_extractor_mut.md +++ b/docs/reference/traits/has_extractor_mut.md @@ -85,14 +85,6 @@ The payload arrives as `&mut Circle`, so the write lands in the original value. ## Under the hood -:::note - -### Advanced - -This section shows the marker that distinguishes it from the shared-borrow form. - -::: - It uses the **same borrowed companion** as [`HasExtractorRef`](./has_extractor_ref.md#under-the-hood), with the outer [`MapTypeRef`](./map_type_ref.md) marker fixed to `IsMut` rather than `IsRef`: @@ -108,7 +100,7 @@ difference between the two borrowing accessors: one marker. There is no rebuild counterpart, and none is needed — the value was never taken apart, only borrowed. -## Gotchas +## Common Mistakes **It takes `&mut self`, so nothing else may borrow the value** for as long as the extractor lives. That is ordinary borrow checking, but it surfaces as an error about the companion type, which reads as though the diff --git a/docs/reference/traits/has_extractor_ref.md b/docs/reference/traits/has_extractor_ref.md index 3e5997df..e8df3f04 100644 --- a/docs/reference/traits/has_extractor_ref.md +++ b/docs/reference/traits/has_extractor_ref.md @@ -78,14 +78,6 @@ full chain narrows the same way, with each remainder also borrowing. ## Under the hood -:::note - -### Advanced - -This section shows how the borrowed companion is built from the two marker families. - -::: - The borrowed accessor uses the **same partial enum** as the owning one, with an extra [`MapTypeRef`](./map_type_ref.md) parameter fixed to `IsRef`: @@ -110,7 +102,7 @@ through a borrow as through an owned value. There is no `from_extractor` counterpart here: a borrowed extractor cannot rebuild an owned enum, and the original is still there anyway. -## Gotchas +## Common Mistakes **There is no rebuild.** [`HasExtractor`](./has_extractor.md)'s `from_extractor` has no borrowing equivalent, which is rarely a problem since the value was never consumed. diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/has_field.md index 563b0f32..d720997c 100644 --- a/docs/reference/traits/has_field.md +++ b/docs/reference/traits/has_field.md @@ -147,16 +147,6 @@ provider-side mirror: you bound against `HasField` and wire `FieldGetter`. ## Under the hood -:::note - -### Advanced - -This section shows the blanket impls that make the access compose. You do not need it to read a field, -but a missing field is reported against the generated bound with the tag fully expanded, so recognizing -the shape makes that error legible. - -::: - The per-field impls come almost entirely from [`#[derive(HasField)]`](../derives/derive_has_field.md). What the trait module itself supplies is the blanket impls that let the access compose, and two of them belong to this trait. @@ -188,7 +178,7 @@ The remaining blanket impls belong to the neighbours: [`HasFieldMut`](./has_fiel `DerefMut` forwarding, and [`MapField`](./map_field.md) is free for every `HasField` whose tag is `'static`. -## Gotchas +## Common Mistakes **Two spellings of a name are unrelated types.** `Symbol!("first_name")` and `Symbol!("firstName")` have nothing to do with each other, and a mismatch reports as a missing `HasField` bound rather than as a diff --git a/docs/reference/traits/has_field_mut.md b/docs/reference/traits/has_field_mut.md index be204505..ce231965 100644 --- a/docs/reference/traits/has_field_mut.md +++ b/docs/reference/traits/has_field_mut.md @@ -106,14 +106,6 @@ shared reference satisfies [`HasField`](./has_field.md) and not this. ## Under the hood -:::note - -### Advanced - -One blanket impl belongs to this trait, and it mirrors its supertrait's. - -::: - `HasFieldMut` is implemented for any type whose [`DerefMut`](https://doc.rust-lang.org/std/ops/trait.DerefMut.html) target implements it, with the target additionally bounded `'static`. That extra bound is the one asymmetry with @@ -126,7 +118,7 @@ which keeps a missing-field error pointed at the struct that lacks the field rat The per-field impls themselves come from [`#[derive(HasField)]`](../derives/derive_has_field.md), one `HasFieldMut` beside each `HasField`. -## Gotchas +## Common Mistakes **It is not separately opt-in.** The derive always emits it, so there is no way to expose a field as read-only through the derive. Restricting mutation is a matter of what the implementations declare. diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/has_fields.md index fea4ee07..27a4d78f 100644 --- a/docs/reference/traits/has_fields.md +++ b/docs/reference/traits/has_fields.md @@ -130,16 +130,6 @@ building one up field by field or taking one apart variant by variant is the ## Under the hood -:::note - -### Advanced - -This section shows what the shape expands to. You do not need it to bound on the trait, but the `Fields` -type appears verbatim in compiler errors about structural code, so reading one makes those errors -legible. `cargo cgp expand` prints it resugared for your own code. - -::: - The trait module defines only the bare trait; every impl comes from [`#[derive(HasFields)]`](../derives/derive_has_fields.md). The load-bearing part is what the derive puts in `Fields`, and the sugar hides one level of structure: @@ -163,7 +153,7 @@ product. Because a shape is a type rather than a value, nothing about this costs anything at run time. It exists to give the trait solver something to recurse over. -## Gotchas +## Common Mistakes **`HasFields` and [`HasField`](./has_field.md) differ by one letter and do not overlap.** The plural is the whole shape and takes structs and enums; the singular is per-field access and takes only structs. diff --git a/docs/reference/traits/has_fields_ref.md b/docs/reference/traits/has_fields_ref.md index 00e86e1d..6a5efa90 100644 --- a/docs/reference/traits/has_fields_ref.md +++ b/docs/reference/traits/has_fields_ref.md @@ -99,14 +99,6 @@ a caller must supply. ## Under the hood -:::note - -### Advanced - -This section shows the generated impl, and the reserved lifetime name in it. - -::: - The derive emits the borrowed shape with a **reserved lifetime name**, `'__a`, so it cannot collide with a lifetime of yours: @@ -129,7 +121,7 @@ Because the rewrite is per-entry rather than structural, **a field that is alrea another one**: a field of type `&'a Name` appears as `&'__a &'a Name`. That is correct, and it is the one thing about this trait that surprises people in an error message. -## Gotchas +## Common Mistakes **A field that is already borrowed gets a second borrow.** `&'a Name` becomes `&'__a &'a Name` in `FieldsRef`, which reads oddly in a diagnostic and is not a bug. diff --git a/docs/reference/traits/has_optional_builder.md b/docs/reference/traits/has_optional_builder.md index d9c56db4..ed0ee30a 100644 --- a/docs/reference/traits/has_optional_builder.md +++ b/docs/reference/traits/has_optional_builder.md @@ -105,14 +105,6 @@ Had that used `finalize_optional`, it would have returned `Err("bar")` instead. ## Under the hood -:::note - -### Advanced - -This section shows that the entry point is a composition rather than new machinery. - -::: - `optional_builder()` is [`HasBuilder`](./has_builder.md)'s `builder()` followed by [`ToOptional`](./to_optional.md) — start at all-`IsNothing`, then re-mark every field to `IsOptional` with a [`TransformMapFields`](./transform_map_fields.md) walk carrying the @@ -131,7 +123,7 @@ operations apply: [`SetOptional`](./set_optional.md) resolves where [`FinalizeBuild`](./finalize_build.md) does not resolve at all until a finalize has re-marked the fields back to `IsPresent`. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`, along with whatever else in the layer you use. diff --git a/docs/reference/traits/into_builder.md b/docs/reference/traits/into_builder.md index 4c144220..d8b6f06b 100644 --- a/docs/reference/traits/into_builder.md +++ b/docs/reference/traits/into_builder.md @@ -80,15 +80,6 @@ entry points and the one that shows up in generic code more than in application ## Under the hood -:::note - -### Advanced - -This section is short, because the companion type is -[`HasBuilder`](./has_builder.md#under-the-hood)'s. - -::: - The derive generates one partial companion per record — `__Partial{Name}`, with a [`MapType`](./map_type.md) parameter per field — and the two entry points differ only in the configuration they name: @@ -111,7 +102,7 @@ Because the result is at the all-present configuration, it satisfies [`FinalizeBuild`](./finalize_build.md) immediately and [`TakeField`](./take_field.md) for every field, which is exactly the pair a redistribution needs. -## Gotchas +## Common Mistakes **It consumes the value.** There is no borrowing form; use [`ToFieldsRef`](./to_fields_ref.md) if the original must survive, bearing in mind that gives you a shape rather than a builder. diff --git a/docs/reference/traits/is_provider_for.md b/docs/reference/traits/is_provider_for.md index 8386e6b5..b08cef83 100644 --- a/docs/reference/traits/is_provider_for.md +++ b/docs/reference/traits/is_provider_for.md @@ -149,16 +149,6 @@ problem rather than the hidden one. ## Under the hood -:::note - -### Advanced - -This section shows where the three generated pieces come from. You do not need it to write CGP, but every -non-trivial wiring error names this trait, and the three-part chain is what those errors are walking. -`cargo cgp expand` prints all three for your own code. - -::: - `IsProviderFor` appears in three places, and together they form the chain an error travels along. **First, the supertrait link.** [`#[cgp_component]`](../macros/cgp_component.md) emits every provider trait @@ -212,7 +202,7 @@ clause the provider macros derive is **augmented rather than copied**. A bound n provider trait gains its marker counterpart, which is the mechanism that carries an inner provider's requirements outward through a higher-order stack. -## Gotchas +## Common Mistakes **`Params` grouping is the usual mistake in a hand-written assertion.** One parameter goes in directly, two or more as a tuple, none as `()`. Getting it wrong reports as an unsatisfied bound on a trait you did not diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/lift_value.md index 940b8fbb..69ff5e3e 100644 --- a/docs/reference/traits/lift_value.md +++ b/docs/reference/traits/lift_value.md @@ -94,14 +94,6 @@ chain steps without a branch and involve none of this. ## Under the hood -:::note - -### Advanced - -This section shows where a bind step uses it. - -::: - The [`BindOk` and `BindErr`](../providers/monad_providers.md) providers use `LiftValue` in their [`Computer`](../components/computer.md) and `AsyncComputer` impls, as the closing half of a step whose opening half is [`ContainsValue`](./contains_value.md). The step unwraps the incoming output, decides @@ -118,7 +110,7 @@ one where the distinction happens to be vacuous, not one where it does not exist The transformer forms implement both by delegating to the base monad after handling their own layer, which is what lets a stack lift through *n* layers with no depth-specific code. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::monad::traits`. diff --git a/docs/reference/traits/map_field.md b/docs/reference/traits/map_field.md index 69b1e8b2..81d7f2b4 100644 --- a/docs/reference/traits/map_field.md +++ b/docs/reference/traits/map_field.md @@ -120,14 +120,6 @@ say — and even then the existing ones usually compose. ## Under the hood -:::note - -### Advanced - -This section explains why the blanket impl needs a `'static` tag and the value does not. - -::: - `MapField` is a blanket impl for every [`HasField`](./has_field.md) whose **tag** is `'static`: ```rust @@ -146,7 +138,7 @@ lifetime, and the result can be returned to the caller. [`ChainGetters`](../providers/chain_getters.md) composes descents by nesting these calls, one per segment, so an arbitrarily deep path stays lifetime-correct with no `'static` anywhere in the chain. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. [`FieldMapper`](./field_mapper.md) is the other non-prelude member of the group; everything else in it diff --git a/docs/reference/traits/map_fields.md b/docs/reference/traits/map_fields.md index d15c8cf0..9c785a11 100644 --- a/docs/reference/traits/map_fields.md +++ b/docs/reference/traits/map_fields.md @@ -98,14 +98,6 @@ Three similar names, three unrelated jobs. ## Under the hood -:::note - -### Advanced - -This section shows the recursion, which exists twice — once per spine. - -::: - Like its two siblings, `MapFields` is a pair of impls per spine, one for the node and one for the terminator. Unlike them, it *transforms* the head rather than preserving it: @@ -131,7 +123,7 @@ sum still a sum. All of it resolves during type checking, so a mapped shape is a name for a type rather than a computation that runs. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`, and remember that `IsOptional` needs its own import from `cgp::core::field::impls`. diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index 2d69f6f8..1b4c7f72 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -122,14 +122,6 @@ one marker across every entry of a type-level list, where this one names a singl ## Under the hood -:::note - -### Advanced - -This section is short, because the trait is one associated type. - -::: - 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. @@ -148,7 +140,7 @@ So the partial type's *shape* is fixed while its *storage* is decided per instan transition is a change of type argument. [`UpdateField`](./update_field.md) is what performs one such transition on a value. -## Gotchas +## 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 diff --git a/docs/reference/traits/map_type_ref.md b/docs/reference/traits/map_type_ref.md index 69849f58..fd44c4b8 100644 --- a/docs/reference/traits/map_type_ref.md +++ b/docs/reference/traits/map_type_ref.md @@ -117,14 +117,6 @@ what this page is for: an error mentioning `IsRef` is telling you the value is b ## Under the hood -:::note - -### Advanced - -This section shows how the two marker families combine in one generated type. - -::: - A borrowed companion enum carries the outer marker as an extra parameter alongside the per-variant ones, and each payload slot projects through both: @@ -146,7 +138,7 @@ The `T: 'a` bound and the `: 'a` bound on the associated type are what keep the a payload cannot be borrowed for longer than it lives, and the resulting storage type cannot outlive the borrow either. -## Gotchas +## Common Mistakes **`IsOwned` is unused by CGP.** It is a legal marker with no consumer, so selecting it means writing the machinery that uses it yourself. diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monadic_bind.md index ca72f789..e1adef8c 100644 --- a/docs/reference/traits/monadic_bind.md +++ b/docs/reference/traits/monadic_bind.md @@ -105,14 +105,6 @@ And the alternatives to prefer when you do *not* need short-circuiting: ## Under the hood -:::note - -### Advanced - -This section shows where the fold uses it. - -::: - [`PipeMonadic`](../providers/monad_providers.md) walks the handler list and, for each step, asks the monad to turn the continuation built so far into a bind step — which is this trait. Because the walk proceeds from the end of the list backwards, `Provider` at each stage is everything that follows the current step, @@ -127,7 +119,7 @@ The whole fold happens during trait resolution. A monadic pipeline is not a runt provider it resolves to implements the [`Computer`](../components/computer.md) family like any other handler. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::monad::traits`. diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monadic_trans.md index d0095779..4a073892 100644 --- a/docs/reference/traits/monadic_trans.md +++ b/docs/reference/traits/monadic_trans.md @@ -95,14 +95,6 @@ marker directly. ## Under the hood -:::note - -### Advanced - -This section shows where the fold uses it. - -::: - `MonadicTrans` is applied to the **monads** rather than to the handlers, and it runs *before* any binding does. [`PipeMonadic`](../providers/monad_providers.md) resolves the stacked monad first, then walks the handler list asking [`MonadicBind`](./monadic_bind.md) to turn each continuation into a bind step. @@ -115,7 +107,7 @@ resolved stack is just another marker, and everything downstream treats it as on The whole fold happens during trait resolution, so a stacked monadic pipeline is not a runtime structure. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::monad::traits`. diff --git a/docs/reference/traits/mut_field_getter.md b/docs/reference/traits/mut_field_getter.md index 059ad5d9..720eb001 100644 --- a/docs/reference/traits/mut_field_getter.md +++ b/docs/reference/traits/mut_field_getter.md @@ -98,14 +98,6 @@ and rarer still than mutation generally. ## Under the hood -:::note - -### Advanced - -This section is short, because the machinery is [`FieldGetter`](./field_getter.md#under-the-hood)'s. - -::: - `MutFieldGetter` adds one method to its supertrait and no new resolution path: a provider that implements [`FieldGetter`](./field_getter.md) and can also produce a `&mut` implements this too, and [`UseField`](../providers/use_field.md) does for any context whose field is derived. @@ -115,7 +107,7 @@ The route from a wired getter back to a context's own fields runs through target that its immutable counterpart does not — so a context behind a smart pointer holding borrowed data can satisfy the wired read and not the wired write. -## Gotchas +## Common Mistakes **`Self` is the provider, not the context.** The context is the first type parameter, and it arrives as `&mut Context` in the method rather than as `&mut self`. @@ -127,7 +119,7 @@ read half is not optional. **The `'static` bound behind `DerefMut` can bite.** A wired read that resolves and a wired write that does not usually means the context is behind a smart pointer over borrowed data — see -[`HasFieldMut`](./has_field_mut.md#gotchas). +[`HasFieldMut`](./has_field_mut.md#common-mistakes). **Requiring it where a read would do narrows the contexts that fit**, since a provider holding `&Context` cannot satisfy it. diff --git a/docs/reference/traits/partial_data.md b/docs/reference/traits/partial_data.md index b8640fd9..0089fd7a 100644 --- a/docs/reference/traits/partial_data.md +++ b/docs/reference/traits/partial_data.md @@ -92,14 +92,6 @@ traits otherwise. ## Under the hood -:::note - -### Advanced - -This section explains why the trait is separate from the finalize. - -::: - The derive emits one impl covering every configuration at once, by leaving the markers generic: ```rust @@ -119,7 +111,7 @@ single trait carrying both would have to choose one or the other. The enum side implements it identically on its extraction companions, with `Target` naming the original enum, which is how [`HasExtractor`](./has_extractor.md)'s round trip knows what to rebuild. -## Gotchas +## Common Mistakes **It says nothing about completeness.** A `PartialData` bound is satisfied by an empty builder as readily as by a full one. Requiring completeness is [`FinalizeBuild`](./finalize_build.md). diff --git a/docs/reference/traits/set_optional.md b/docs/reference/traits/set_optional.md index 59ac842b..d2e9a416 100644 --- a/docs/reference/traits/set_optional.md +++ b/docs/reference/traits/set_optional.md @@ -93,14 +93,6 @@ thing the core builder cannot express. ## Under the hood -:::note - -### Advanced - -This section shows why the type does not change, which is the trait's whole trick. - -::: - `SetOptional` is a single [`UpdateField`](./update_field.md) call writing `Some(value)` into an `IsOptional` slot, with both the source and target markers pinned to `IsOptional`: @@ -120,7 +112,7 @@ Since the primitive returns the old storage alongside the new value, `set_option `set` discards it. Under `IsOptional` that old storage is an `Option`, which is why the returned value is optional even though the argument is not. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md index cb75dda4..6b45556a 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/static_format.md @@ -116,14 +116,6 @@ more than once, and this trait only when you need to write characters without a ## Under the hood -:::note - -### Advanced - -This section shows the recursion, which is the shorter of the two string recoveries. - -::: - Each character node writes itself and defers to the tail: ```rust @@ -147,7 +139,7 @@ than read out of storage, since there is no `&str` inside a `Symbol` to read. That per-call reconstruction is the difference from [`StaticString`](./static_string.md), which does the same decoding once, at compile time, into a `&'static str` constant. -## Gotchas +## Common Mistakes **It is not in the prelude, and its import differs from both its neighbours'.** This trait comes from `cgp::core::base::traits`, [`StaticString`](./static_string.md) from `cgp::core::field::traits`, and diff --git a/docs/reference/traits/static_string.md b/docs/reference/traits/static_string.md index 3c861d0d..cb373fcf 100644 --- a/docs/reference/traits/static_string.md +++ b/docs/reference/traits/static_string.md @@ -88,14 +88,6 @@ called, while [`HasField`](./has_field.md) is what reads its value. ## Under the hood -:::note - -### Advanced - -This section explains the `LEN` parameter that otherwise looks redundant on every `Symbol`. - -::: - `StaticString` is const evaluation rather than a recursion at run time. It is a blanket impl over an internal `StaticBytes` trait: `Symbol` computes a `[u8; LEN]` in a `const` block by walking the character list and UTF-8-encoding each character into the array, and `VALUE` then validates those @@ -106,7 +98,7 @@ size, and the size cannot be computed from inside the const context by walking t precomputes it. It is a *byte* length, which is what makes multi-byte Unicode round-trip correctly and why `LEN` disagrees with the visible character count for any non-ASCII name. -## Gotchas +## Common Mistakes **It is not in the prelude** while [`ConcatPath`](./concat_path.md) is — an asymmetry between two traits that do neighbouring jobs. Import `StaticString` from `cgp::core::field::traits`. diff --git a/docs/reference/traits/take_field.md b/docs/reference/traits/take_field.md index cf3828ed..8758f221 100644 --- a/docs/reference/traits/take_field.md +++ b/docs/reference/traits/take_field.md @@ -85,14 +85,6 @@ merging one record into another — already uses it for you. ## Under the hood -:::note - -### Advanced - -This section shows why the trait is not generated, and where it is really used. - -::: - `TakeField` is a **library blanket impl** over [`UpdateField`](./update_field.md), the mirror image of [`BuildField`](./build_field.md#under-the-hood): @@ -115,7 +107,7 @@ list, taking each field out with `take_field` and writing it into the target wit [`build_field`](./build_field.md), threading the shrinking source and the growing target through — which is why a merge needs [`HasFields`](./has_fields.md) on the source as well as a builder. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. Every other trait in the core builder family is. diff --git a/docs/reference/traits/to_fields.md b/docs/reference/traits/to_fields.md index c2ac4627..60c735a3 100644 --- a/docs/reference/traits/to_fields.md +++ b/docs/reference/traits/to_fields.md @@ -91,14 +91,6 @@ borrowing form otherwise. ## Under the hood -:::note - -### Advanced - -This section shows the generated impl, which is where the `Cons` spine becomes visible. - -::: - `Product![A, B]` is `Cons>`, so the conversion builds a `Cons` chain, one node per field, wrapping each value into its [`Field`](../types/field.md) entry: @@ -120,7 +112,7 @@ Because the shape is built positionally from declaration order, `to_fields` and [`from_fields`](./from_fields.md) are exact inverses by construction — there is no lookup, no matching by name at run time, and nothing that can fail. -## Gotchas +## Common Mistakes **It consumes the value.** Reach for [`ToFieldsRef`](./to_fields_ref.md) when you need to keep it. This is the commonest surprise in the family, because the two read alike. diff --git a/docs/reference/traits/to_fields_ref.md b/docs/reference/traits/to_fields_ref.md index 3d237d0a..ea90de2b 100644 --- a/docs/reference/traits/to_fields_ref.md +++ b/docs/reference/traits/to_fields_ref.md @@ -88,14 +88,6 @@ by ownership. A routine that must move a field out of a struct needs the owning ## Under the hood -:::note - -### Advanced - -This section covers the lifetime plumbing, which is the only interesting part. - -::: - The generated impl borrows each field and wraps it into the corresponding entry of the borrowed shape, under the reserved lifetime name `'__a` that [`HasFieldsRef`](./has_fields_ref.md#under-the-hood) declares: @@ -116,7 +108,7 @@ An enum's borrowed conversion matches the concrete variant and produces the corr borrowed sum, with the payload borrowed rather than moved — which is also how [`HasExtractorRef`](./has_extractor_ref.md) reads a variant without consuming the value. -## Gotchas +## Common Mistakes **It supertraits [`HasFieldsRef`](./has_fields_ref.md), not [`HasFields`](./has_fields.md).** Bounding on `ToFieldsRef` does not give you `Fields`; require both traits if the code needs both shapes. diff --git a/docs/reference/traits/to_optional.md b/docs/reference/traits/to_optional.md index 8d131c73..8300cbf6 100644 --- a/docs/reference/traits/to_optional.md +++ b/docs/reference/traits/to_optional.md @@ -92,14 +92,6 @@ let builder = context.into_builder().to_optional(); // every field Some ## Under the hood -:::note - -### Advanced - -This section shows the transform it drives. - -::: - `ToOptional` is a [`TransformMapFields`](./transform_map_fields.md) walk carrying the [`TransformOptional`](./transform_optional.md) marker, targeting `IsOptional`: @@ -118,7 +110,7 @@ with [`TransformMapDefault`](./transform_map_default.md) toward `IsPresent`. **B same recursion with a different marker**, which is why the defaulted and optional workflows behave so symmetrically. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. diff --git a/docs/reference/traits/transform_map.md b/docs/reference/traits/transform_map.md index 6baa7e0c..dd1415e9 100644 --- a/docs/reference/traits/transform_map.md +++ b/docs/reference/traits/transform_map.md @@ -103,14 +103,6 @@ and reading it here is the shortest route to understanding that layer. ## Under the hood -:::note - -### Advanced - -This section explains why the impls are shaped the way they are. - -::: - The signature's argument and return types are **projections through the two markers**, so the concrete types differ per impl even though the trait is the same. `TransformMap` has an argument type of `::Map`, which normalizes to `()`, and a return type of `T`. @@ -129,7 +121,7 @@ re-marks exactly the fields the concrete struct declares. Nothing here has a runtime representation beyond the field values themselves: the markers are zero-sized, and `transform_mapped` is an associated function with no receiver. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. diff --git a/docs/reference/traits/transform_map_default.md b/docs/reference/traits/transform_map_default.md index 629d2694..d4afd410 100644 --- a/docs/reference/traits/transform_map_default.md +++ b/docs/reference/traits/transform_map_default.md @@ -105,14 +105,6 @@ served by the two capabilities already built on it. ## Under the hood -:::note - -### Advanced - -This section shows the three impls, which are the layer's actual content. - -::: - The marker is zero-sized and carries no data. What it carries is three [`TransformMap`](./transform_map.md) impls, distinguished by their source marker: @@ -145,7 +137,7 @@ Three impls are needed rather than one because [`TransformMapFields`](./transform_map_fields.md#under-the-hood) resolves a conversion per field from whatever state that field is in, and a record may hold fields in all three states at once. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. diff --git a/docs/reference/traits/transform_map_fields.md b/docs/reference/traits/transform_map_fields.md index 7055f12f..152871ee 100644 --- a/docs/reference/traits/transform_map_fields.md +++ b/docs/reference/traits/transform_map_fields.md @@ -100,14 +100,6 @@ optional-field layer means. ## Under the hood -:::note - -### Advanced - -This section shows the recursion and the two limits it explains. - -::: - `TransformMapFields` walks the target's [`HasFields`](./has_fields.md) product one entry at a time. For each `Field` it uses [`UpdateField`](./update_field.md) **twice**: it takes the field out — replacing its marker with `IsNothing` and reading what the marker *was* — applies @@ -127,7 +119,7 @@ declares, in declaration order, and a field the shape does not mention is not vi The intermediate `IsNothing` state is invisible from outside: it exists only between the two `UpdateField` calls for one field, and no observable value is ever in a half-transformed configuration. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. diff --git a/docs/reference/traits/transform_optional.md b/docs/reference/traits/transform_optional.md index 6c8b835d..a9670375 100644 --- a/docs/reference/traits/transform_optional.md +++ b/docs/reference/traits/transform_optional.md @@ -102,14 +102,6 @@ Writing a marker of your own follows the same shape; the ## Under the hood -:::note - -### Advanced - -This section shows why it needs fewer impls than its counterpart. - -::: - The marker is zero-sized and carries [`TransformMap`](./transform_map.md) impls distinguished by their source marker, each targeting `IsOptional`: @@ -135,7 +127,7 @@ The result is a partial value at a configuration the core builder never reaches makes [`SetOptional`](./set_optional.md) resolve and the strict [`FinalizeBuild`](./finalize_build.md) not. -## Gotchas +## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. diff --git a/docs/reference/traits/update_field.md b/docs/reference/traits/update_field.md index 29b8e85f..8d8e18f8 100644 --- a/docs/reference/traits/update_field.md +++ b/docs/reference/traits/update_field.md @@ -103,14 +103,6 @@ call site. ## Under the hood -:::note - -### Advanced - -This section shows the generated impl, and the detail that makes build order free. - -::: - The derive emits one impl per field, and the key property is visible in the generics: **only the named field's marker moves, while every other stays generic.** @@ -137,7 +129,7 @@ by constraining it. [`BuildField`](./build_field.md) is a blanket impl over Nothing here changes a value's runtime layout beyond moving it in or out of the slot; the markers are zero-sized and the wrapping is a type-level fiction. -## Gotchas +## Common Mistakes **`Mapper` is the state *before* the call, not after.** The name reads either way, and getting it backwards makes a bound resolve to the wrong impl or none at all. From db80fae4ef2cde85440ddc7e04d0f7b5ef36d002 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 22 Aug 2026 22:28:38 +0200 Subject: [PATCH 039/516] Revise Concepts pages for writing style Apply the writing-styles conventions across all Concepts explanation pages: replace em-dash-as-connector with the mark the relationship needs, remove cleft and pseudo-cleft constructions, and hold the agent-drafted plain-English register (no metaphors or idioms, active voice with a named actor, no stacked dash/colon clauses). Prose only. Code blocks are unchanged, the site-standard AI-disclosure footer is left consistent, and the running examples and per-page cost statements are preserved. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_017iMYCYgoVv6h1YL58q4XVp --- docs/concepts/abstract-types.md | 42 +++---- docs/concepts/aggregate-providers.md | 26 ++-- docs/concepts/check-traits.md | 34 +++--- docs/concepts/coherence.md | 113 +++++++++--------- docs/concepts/consumer-and-provider-traits.md | 65 +++++----- docs/concepts/dispatching.md | 20 ++-- docs/concepts/extensible-records.md | 32 ++--- docs/concepts/extensible-variants.md | 33 ++--- docs/concepts/handlers.md | 38 +++--- docs/concepts/higher-order-providers.md | 44 +++---- docs/concepts/impl-side-dependencies.md | 51 ++++---- docs/concepts/implicit-arguments.md | 36 +++--- docs/concepts/index.md | 6 +- docs/concepts/modular-error-handling.md | 50 ++++---- docs/concepts/modularity-hierarchy.md | 55 ++++----- docs/concepts/monadic-handlers.md | 22 ++-- docs/concepts/namespaces.md | 40 +++---- docs/concepts/send-bounds.md | 26 ++-- docs/concepts/type-level-dsls.md | 29 ++--- 19 files changed, 383 insertions(+), 379 deletions(-) diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index 1ba72b3e..d9b44e84 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -5,8 +5,8 @@ sidebar_position: 5 # Abstract types -Naming a type in generic code — an error type, a scalar, a runtime — and letting each context decide -what it actually is. +Naming a type in generic code, such as an error type, a scalar, or a runtime, and letting each context +decide what it actually is. This page answers *how does code name a type it does not choose?* It starts from the ordinary Rust feature that already does this, shows what CGP adds to it, and works through the two things abstract @@ -34,10 +34,10 @@ impl HasScalarType for Embedded { Generic code names `Context::Scalar` and never commits to `f32` or `f64`. Each type answers for itself, the compiler resolves the answer where a concrete type is known, and nothing costs anything at runtime. -That is the whole idea, and CGP does not replace it — a context can implement an abstract-type trait +That is the whole idea, and CGP does not replace it. A context can implement an abstract-type trait directly, exactly as above, and everything else on this page still works. -What is worth noticing is the *direction*. A generic parameter is an input the caller supplies; an +The *direction* is worth noticing. A generic parameter is an input the caller supplies; an associated type is an output the implementing type determines. That difference is small in one function and decides how a codebase ages, which the last section of this page is about. @@ -69,18 +69,18 @@ delegate_components! { } ``` -`UseType` says "the type is `f64`", and that is all it says — every abstract type is answered the +`UseType` says "the type is `f64`", and that is all it says. Every abstract type is answered the same trivial way, so `#[cgp_type]` generates that answer once and a context supplies the type as an -argument to it. The bound on the associated type is carried through and enforced on whatever the context -chooses: wiring `UseType` against a `Copy` scalar is an error reading +argument to it. The bound on the associated type carries through, and the compiler enforces it on +whatever the context chooses: wiring `UseType` against a `Copy` scalar is an error reading `the trait bound String: Copy is not satisfied`. Like every other wiring choice it is [checked lazily](./check-traits.md), so that error appears where the component is checked or used rather than on the wiring line itself. -This is a small win on its own. What it buys is that a context's type choices sit beside its behaviour -choices, in one table, rather than being scattered across `impl` blocks — and that a type can be chosen -by something more interesting than a fixed answer, since `UseType` is just one provider among the -ones a component can be wired to. +This is a small win on its own. It buys two things. A context's type choices sit beside its behaviour +choices, in one table, rather than scattered across `impl` blocks. And a type can be chosen by +something more interesting than a fixed answer, since `UseType` is just one provider among the ones a +component can be wired to. ## One type, agreed on by everything that needs it @@ -101,10 +101,10 @@ pub trait CanCalculateShapeArea { `Rectangle` declares nothing. The application declares the scalar, every shape interoperates through it, and switching the application from `UseType` to `UseType` changes the arithmetic for every -shape at once. The application here is a type standing for the program rather than a piece of data — -`struct App;` with no fields is a complete one — which is the shape most CGP code is in. +shape at once. The application here is a type standing for the program rather than a piece of data, and +`struct App;` with no fields is a complete one, which is the shape most CGP code is in. -The `#[use_type(HasScalarType.Scalar)]` line is what lets the signature say `Scalar` instead of +The `#[use_type(HasScalarType.Scalar)]` line lets the signature say `Scalar` instead of `::Scalar`. It imports the type and adds the requirement in one line, and it reads like a `use` for a type because that is what it is. @@ -133,9 +133,9 @@ impl Loader { } ``` -`LoadOrFail` fails, and never learns what failing means in this application. The context decides — -`anyhow::Error`, a domain enum, a plain `String` — and every fallible provider in that context refers to -the same one, so errors compose instead of needing conversion at each boundary. +`LoadOrFail` fails, and never learns what failing means in this application. The context decides, +whether `anyhow::Error`, a domain enum, or a plain `String`, and every fallible provider in that context +refers to the same one, so errors compose instead of needing conversion at each boundary. [Modular error handling](./modular-error-handling.md) is the page for what else follows from that. ## Two things called `UseType` @@ -153,11 +153,11 @@ program constantly and never in the same position. **It is deferral, not encapsulation.** An abstract type leaves the choice open; it does not hide the answer. Once a context wires `UseType`, code with that context in hand sees `f64` and can do anything `f64` allows. If the goal is that callers must *not* know the representation, that is Rust's -module privacy, and an abstract type is the wrong tool for it — a distinction worth being precise about -with anyone arriving from ML modules. +module privacy, and an abstract type is the wrong tool for it. That distinction is worth being precise +about with anyone arriving from ML modules. **A bound on the associated type is the only thing generic code can rely on.** `type Scalar: Copy` means -generic code can copy a scalar and nothing else — no arithmetic, no comparison, unless those bounds are +generic code can copy a scalar and nothing else: no arithmetic and no comparison, unless those bounds are declared too. Adding one later is a change every context has to satisfy, so the bounds are worth thinking about when the trait is written. @@ -176,7 +176,7 @@ wiring line, like everything else. the type-shaped version of a requirement stated on the implementation, beside the capability leg and the value leg. [Implicit arguments](./implicit-arguments.md) is that value leg. -[Modular error handling](./modular-error-handling.md) develops the canonical case at length — the error +[Modular error handling](./modular-error-handling.md) develops the canonical case at length: the error type, how a foreign error becomes it, and what detail it carries, as three separate choices. For the constructs, [`#[cgp_type]`](/docs/reference/macros/cgp_type) defines an abstract-type component, diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index 4cddd955..9e5d696c 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -57,11 +57,11 @@ it. When `rectangle.area()` resolves: - and `GeometryComponents` implements it because *its* table sends the component to `RectangleArea`. At every step the context is `Rectangle`. `GeometryComponents` only ever appears as the thing being -delegated to. So when `RectangleArea` reads a `width`, it reads it from `Rectangle` — the bundle has no +delegated to. So when `RectangleArea` reads a `width`, it reads it from `Rectangle`. The bundle has no `width`, is never asked for one, and would not be consulted if it had one. -That is what makes a bundle a *provider* rather than a context: it is something delegated **to**, never -something used **as**. Bundles nest for the same reason — a table entry may name another table, and +This is why a bundle is a *provider* rather than a context: it is something delegated **to**, never +something used **as**. Bundles nest for the same reason: a table entry may name another table, and resolution walks each in turn while the context argument stays fixed on the real context at the end of the chain. @@ -72,13 +72,13 @@ There is one place a bundle behaves unlike anything else, and it is worth knowin **Never wire a bundle with the fused [`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components).** That macro derives a check asking whether the target can *use* each component as a context. For a bundle that is a -question about a role it never plays, so the answer carries no information — and which answer comes back +question about a role it never plays, so the answer carries no information, and which answer comes back depends on what is inside: - If the bundled providers need nothing from their context, they implement the capability for *every* context, the bundle included. The check passes. It has proved nothing, and it looks like it has. - If a bundled provider needs a field or a type, the check fails, reporting that `GeometryComponents` - does not have a `width` — blaming the bundle for something the real context would have supplied. + does not have a `width`, blaming the bundle for something the real context would have supplied. The silent case is the dangerous one. Wire a bundle with plain [`delegate_components!`](/docs/reference/macros/delegate_components) and let it be verified where the @@ -86,8 +86,8 @@ question means something. ## Verifying one properly -A bundle is checked through a context that uses it. Checking `Rectangle` walks the whole chain — through -the bundle's table, down to `RectangleArea`'s requirements, against `Rectangle`'s fields — so a gap +A bundle is checked through a context that uses it. Checking `Rectangle` walks the whole chain, through +the bundle's table, down to `RectangleArea`'s requirements, against `Rectangle`'s fields, so a gap several bundles deep still surfaces: ```rust @@ -99,7 +99,7 @@ check_components! { } ``` -When the bundle itself needs pinning down — usually to find which layer of a nested stack is broken — +When the bundle itself needs pinning down, usually to find which layer of a nested stack is broken, the [`#[check_providers]`](/docs/reference/macros/check_components) form asserts the provider-side question instead, naming the bundle *for a concrete context*: @@ -122,7 +122,7 @@ Both routes go through a real context. Neither treats the bundle as one. A bundle and a [namespace](./namespaces.md) both package reusable wiring, and they differ in how a context takes it on. -A context adopts a bundle by **delegating named components to it** — `[A, B]: TheBundle` — so the +A context adopts a bundle by **delegating named components to it**, `[A, B]: TheBundle`, so the context spells out which components come from where. That is direct, obvious to read, and it scales linearly: twenty components from a bundle means twenty names in the brackets. @@ -144,12 +144,12 @@ between the call and the code. nothing. The threshold is a second context wanting the same group, not the anticipation of one. **It is the construct whose checking rule is a genuine trap**, per the section above, and the failure -mode is a check that passes. Nothing in the code marks a bundle as different from a context — both are -`delegate_components!` on a type — so the distinction has to be held by the person writing it. +mode is a check that passes. Nothing in the code marks a bundle as different from a context, since both +are `delegate_components!` on a type, so the distinction has to be held by the person writing it. **And the type name carries no clue.** `GeometryComponents` is a struct like any other; only its usage -says it is a bundle. Naming the group rather than a thing — `…Components` — is the convention that keeps -it legible. +says it is a bundle. Naming the group rather than a thing, with a `…Components` suffix, is the convention +that keeps it legible. ## Where to go next diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index f363698b..8795ecb9 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -9,7 +9,7 @@ Why a wiring mistake still compiles, and how a compile-time assertion turns the one that names the real cause. This page answers *why did my mistake not fail where I made it?* It follows one broken context through -three stages — unchecked, checked, and checked through the error toolchain — quoting what the compiler +three stages, unchecked, checked, and checked through the error toolchain, quoting what the compiler actually reports at each. It closes on what checking does not fix, which is the honest version of CGP's most-cited cost. @@ -40,7 +40,7 @@ delegate_components! { BrokenApp { EmailSenderComponent: RecordEmails } } is meant to: the table stores "this key points to this provider" as a type-level fact, and nothing has asked yet whether the provider's own requirements hold for this particular context. -That laziness is not an oversight. It is what lets a provider be written once against every possible +That laziness is not an oversight. It lets a provider be written once against every possible context, lets a bundle of wiring be reused by applications the bundle has never heard of, and lets a table be assembled from pieces that never meet. Checking each entry as it was written would mean every entry knowing its final context, which is the coupling the whole design exists to avoid. @@ -49,9 +49,9 @@ The price is that a context can look finished and be broken. ## Where the failure surfaces instead -The question gets asked the first time something uses the capability, which may be in another module, -another crate, or a test somebody runs next week. And the answer arrives in a form that does not name -the problem: +The compiler asks the question the first time something uses the capability, which may be in another +module, another crate, or a test somebody runs next week. And the answer arrives in a form that does +not name the problem: ```text error[E0599]: the method `send_email` exists for reference `&BrokenApp`, @@ -67,16 +67,16 @@ note: the following trait bounds were not satisfied: Read it closely and it says only that the capability is unavailable, restated twice. The word `sent_emails` does not appear. Neither does anything about a field. The compiler answered the question -it was asked — *does this type have this method?* — and the reasoning that produced "no" was discarded -on the way out. +it was asked, *does this type have this method?*, and discarded the reasoning that produced "no" on the +way out. -This is the single worst experience CGP offers a newcomer, and it is worth being blunt that it is what -a mis-wire looks like by default. +This is the single worst experience CGP offers a newcomer, and it is worth being blunt that a mis-wire +looks like this by default. ## Asking the question at a line you chose A **check** forces the same question early, at the wiring, where you can see it. It is not a new -mechanism — the plain-Rust form is a trait that demands something and an impl with nothing in it: +mechanism. The plain-Rust form is a trait that demands something and an impl with nothing in it: ```rust trait CanUseApp: CanSendEmail {} @@ -98,9 +98,9 @@ check_components! { ``` But the important part is not the convenience. A check asserts something *stronger* than the consumer -trait, and that is what changes the error. Asking "does `BrokenApp` implement `CanSendEmail`?" gets the -answer above. Asking "can `BrokenApp` use this component?" makes the compiler evaluate the provider's -actual requirements and report the one that failed: +trait, and that stronger assertion changes the error. Asking "does `BrokenApp` implement +`CanSendEmail`?" gets the answer above. Asking "can `BrokenApp` use this component?" makes the compiler +evaluate the provider's actual requirements and report the one that failed: ```text error[E0277]: the trait bound `BrokenApp: CanUseComponent` @@ -117,7 +117,7 @@ note: required for `RecordEmails` to implement The cause is in there now. A field is missing, one *is* present, and the provider that wanted it is named. Two things still stand between that and a usable message: the field names are spelled as -type-level character lists — `sent_emails` and `smtp_server`, one character per layer — and the headline +type-level character lists, `sent_emails` and `smtp_server` at one character per layer, and the headline is about a trait nobody wrote. ## Reading it through the toolchain @@ -143,7 +143,7 @@ words you would use to describe it. The tool does more than reformat: for the worst class it turns on the compiler's next-generation trait solver to recover a cause the default solver discards entirely, which is why the first error on this page had nothing to reshape. It is a `v0.1.0-alpha`, it covers the core wiring errors rather than every -class, and some — orphan-rule failures among them — still pass through as the compiler wrote them. +class, and some still pass through as the compiler wrote them, orphan-rule failures among them. Dramatically better and actively improving, not solved. ## Checking a stack one layer at a time @@ -185,7 +185,7 @@ verified. One case is not a matter of taste: **never fuse the check onto a [bundle of wiring](./aggregate-providers.md)**. A bundle is a provider other contexts delegate to, not a -context, so a context-side check on it asks a question it was never meant to answer — and gets an answer +context, so a context-side check on it asks a question it was never meant to answer, and gets an answer that means nothing either way. It passes vacuously when the bundled providers need nothing from their context, and fails blaming the bundle when any of them does. Verify a bundle through a context that delegates to it. @@ -211,7 +211,7 @@ and three exist is the reader CGP loses. ## Where to go next [Impl-side dependencies](./impl-side-dependencies.md) is why the requirement was hidden in the first -place — the design decision this page pays for. [Higher-order providers](./higher-order-providers.md) is +place, the design decision this page pays for. [Higher-order providers](./higher-order-providers.md) is where per-layer checking earns its keep, and [Aggregate providers](./aggregate-providers.md) is the case where the context-side check is the wrong one. diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index bc468ea4..ab1b742a 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -9,14 +9,14 @@ Rust allows one implementation of a trait per type. Why that rule exists, what i writes many implementations and lets each context pick the one it wants. This page answers *why can't Rust do this already?* It builds up what the trait system gives you, shows -what that costs when you want two implementations of one thing, works through the move CGP makes — which -is smaller than it first appears, and does not throw the rule away — and closes on what that move costs in +what that costs when you want two implementations of one thing, and works through the move CGP makes, +which is smaller than it first appears and does not discard the rule. It closes on what that move costs in turn. It is a long page, and it is the one everything else in this section is downstream of. ## The trait system is already a dependency-injection mechanism -Start with what Rust does well, because the rule that gets in the way later is the same rule that makes -this work. +Start with what Rust does well, because the rule that blocks this later is the same rule that makes +it work. When you write a generic function with a bound, you are asking the compiler to find an implementation for you: @@ -34,14 +34,14 @@ at compile time, and it is so ordinary in Rust that it rarely gets called that. The part worth noticing is that it works **transitively**. If `describe` calls something that itself needs a bound, and that needs another, the compiler resolves the whole chain without a single caller naming any of it. You can add a requirement four layers deep and callers four layers up are unaffected. -That property is what makes Rust's generics composable rather than a bookkeeping exercise. +That property makes Rust's generics composable rather than a bookkeeping exercise. ## That only works because every lookup finds the same answer Transitive resolution depends on something easy to overlook: when the compiler looks up `Display for i32`, it must get the same answer no matter where it asks from. If one crate could see one implementation and another crate a different one, the same generic function would mean different things depending on who -called it, and a program combining both would be incoherent — two halves compiled against +called it, and a program combining both would be incoherent: two halves compiled against irreconcilable answers. **Coherence is the property that guarantees this**, and Rust enforces it with two rules. @@ -65,7 +65,7 @@ impl> CanEncode for T { } ``` -`String` satisfies both bounds, so the compiler would have no principled way to choose — and "pick +`String` satisfies both bounds, so the compiler would have no principled way to choose. And "pick whichever is in scope" is exactly the incoherence the rule exists to prevent. The **orphan rule** forbids implementing a trait for a type unless your crate owns one of the two. @@ -80,7 +80,7 @@ impl Display for Vec { ``` Without it, two unrelated crates could each add their own `Display for Vec`, and any program -depending on both would be unbuildable — with neither crate at fault. +depending on both would be unbuildable, with neither crate at fault. **Both rules are correct.** They are not conservatism or an unfinished corner of the language; they are what you pay for transitive resolution, and the trade is a good one. Any account of CGP that opens by @@ -88,11 +88,12 @@ calling coherence a limitation has the argument backwards. ## What the guarantee costs -The price is that some perfectly reasonable code is unwritable, and the two rules bite in different ways. +The price is that some perfectly reasonable code is unwritable, and the two rules cost you in different +ways. The overlap rule costs you **alternative implementations**. In the encoding example above, the author knows -exactly which implementation they want for which type — the ambiguity is the compiler's, not theirs — and -there is no way to say so. The trait admits one blanket implementation, full stop. +exactly which implementation they want for which type. The ambiguity is the compiler's, not theirs, and +there is no way to say so. The trait admits exactly one blanket implementation. The orphan rule costs you **reach**. A crate that wants to add a capability to another crate's type has to wrap it in a newtype and re-expose everything it still needs, which is boilerplate with no upside and a @@ -100,14 +101,14 @@ type your callers now have to know about. These are felt sharply enough that Rust developers build their own escape. The pattern is to stop implementing the trait for the interesting type and implement it for a marker type you own instead, with a -helper trait tying the two together — three or four extra lines of plumbing, arrived at and written up +helper trait tying the two together: three or four extra lines of plumbing, arrived at and written up independently by a Rust developer working around the overlap rule. **If you have written that, you have written CGP's central mechanism by hand**, and the rest of this page is about what it looks like made first-class. ## The move: make `Self` a type you own -CGP's first move is to take the type coherence ranges over — the `Self` of the implementation — and make +CGP's first move is to take the type coherence ranges over, the `Self` of the implementation, and make it something the implementing crate always owns. One trait definition becomes two. The **consumer trait** is the caller's view, keeping the ordinary `self` @@ -138,8 +139,8 @@ where } ``` -**Both compile.** They carry the same two overlapping bounds the compiler rejected a moment ago — -`Display` and `AsRef<[u8]>`, still overlapping on `String` — and there is no conflict, because each one's +**Both compile.** They carry the same two overlapping bounds the compiler rejected a moment ago: +`Display` and `AsRef<[u8]>`, still overlapping on `String`. There is no conflict, because each one's `Self` is now a different type (`EncodeAsText`, `EncodeAsHex`) that this crate declared for the purpose. Any number more would also compile. The orphan rule does not enter either, since that `Self` is always local, which is how a crate adds a capability to a type it did not define. @@ -150,9 +151,9 @@ the split and how a call finds its way across it. One other thing changed in that listing, and it is worth naming rather than leaving you to spot it: the value being encoded moved out of `Self` and into a `Value` parameter, so the trait is now -`CanEncodeValue` rather than `CanEncode`. That is a second move, not part of the first, and it is -what leaves `Self` free to be something other than the data. What it is free to be, and why that turns -out to matter more than the parameter does, is the next two sections. +`CanEncodeValue` rather than `CanEncode`. That is a second move, not part of the first, and it +leaves `Self` free to be something other than the data. The next two sections cover what it is free to +be, and why that matters more than the parameter. ## Coherence comes back, one context at a time @@ -160,7 +161,7 @@ Making implementations incoherent would be useless if it also made *use* incoher `app.encode(&value)` to mean one definite thing. So the second move reintroduces coherence at a smaller scale. Instead of one global choice per trait, each -**context** — a type you define to stand for one set of choices — names exactly one implementation, in a +**context**, a type you define to stand for one set of choices, names exactly one implementation in a small table: ```rust @@ -187,11 +188,10 @@ Firmware: 6869 ``` Within either context the choice is unambiguous, so resolution is coherent; between them it differs, with -no conflict, because the lookup is keyed on the context. The insight is that incoherence is only wanted -when *writing* implementations. When using them, what you want is many independent local scopes, each -internally consistent. +no conflict, because the lookup is keyed on the context. Incoherence is only wanted when you are *writing* +implementations. When you use them, you want many independent local scopes, each internally consistent. -**Coherence is not repealed — it is scoped.** That sentence is the whole page in eight words. +**Coherence is not repealed; it is scoped.** That line is the whole page in a sentence. ## Where the freedom actually comes from @@ -199,10 +199,10 @@ Here is the part most easily misread, and it is worth slowing down for: **the es becomes a type you own, not when a parameter appears.** A scope is one context type, so the number of independent choices a program can make is the number of -context types it can define. Wire a capability onto `String` — data, and not yours — and you get exactly -one answer for the whole program, because there is one `String`. Coherence was narrowed, not removed. -Wire it onto `ApiServer` and `Firmware`, types you declared, and you get as many answers as you care to -declare types. +context types it can define. Wire a capability onto `String`, which is data and not yours, and you get +exactly one answer for the whole program, because there is one `String`. Coherence was narrowed, not +removed. Wire it onto `ApiServer` and `Firmware`, types you declared, and you get as many answers as +you care to declare types. Which is why the two contexts above are `ApiServer` and `Firmware` rather than `String` wired twice. The second is impossible; the first is the point. @@ -234,12 +234,12 @@ impl CanEncodeValue for Firmware { This compiles, and it already does something useful: per-application encoding of the same type. Note that both structs have **no fields at all**. `struct ApiServer;` is a complete and legitimate type here, -because its entire purpose is to be a name the implementations hang off. An empty struct with traits on it +because its entire purpose is to be a name the implementations attach to. An empty struct with traits on it is otherwise close to unreadable, which is why it is worth saying outright. Now try to make it scale. Add a third value type, then a fourth, and you are hand-writing a body per -`(application, type)` pair. So you do the obvious thing and factor the shared logic into a blanket -implementation — and the overlap rule is waiting: +`(application, type)` pair. So you factor the shared logic into a blanket implementation, and the overlap +rule rejects it: ```rust impl CanEncodeValue for ApiServer { /* ... */ } @@ -249,58 +249,59 @@ impl CanEncodeValue for ApiServer { /* ... */ } impl> CanEncodeValue for ApiServer { /* ... */ } ``` -**So the shape is available and unrewarding.** It works, and nothing can be shared, so it dies at three -types and nobody carries it in their repertoire. That is why "application context" tends to land as an -unfamiliar noun rather than a familiar arrangement: readers have not built it, because until now there was -no reason to. +**So the shape is available and unrewarding.** It works, and nothing can be shared, so it stops paying off +at three types and nobody keeps it as a familiar technique. That is why "application context" usually +reads as an unfamiliar noun rather than a familiar arrangement: readers have not built it, because until +now there was no reason to. This is the strongest form of the payoff, and it is worth stating precisely. **Coherence does not forbid -this shape — it makes it not worth building.** CGP's contribution is therefore constructive rather than +this shape; it makes it not worth building.** CGP's contribution is therefore constructive rather than permissive: it does not merely escape a rule, it makes an available shape worth using. Named providers replace the hand-written bodies, and a per-pair decision becomes a line in a table. ### Naming the two shapes -Two distinctions have been doing quiet work above, and naming them is what keeps "context" from becoming a -word you cannot pin down — it is where readers most often lose track. +Two distinctions have been at work above. Naming them keeps "context" from becoming a word you cannot pin +down, and this is where readers most often lose track. The first crossing had no signal at all. In the `CanEncode` listing further up, the wired type was **the data**: `impl CanEncode for T` puts the thing being encoded in `Self`, exactly as `impl Display for String` does, and that is the shape essentially every Rust trait is in. From *The move* onward the wired type has -been `ApiServer` or `Firmware` — types you define, holding no data, existing to carry choices. No signature -announced the change and no parameter marked it, yet `Self` stopped being data. The vocabulary is a -**value context** for the first and an **environmental context** for the second, and this is the crossing -that escapes coherence: you can define as many application types as you like, and there is only one -`String`. - -The second crossing is visible in the code. A capability about `Self` is **self-targeted** — `CanEncode`, -as first written here. Moving the value into a parameter makes it **parameter-targeted**: +been `ApiServer` or `Firmware`, types you define, holding no data and existing to carry choices. No +signature announced the change and no parameter marked it, yet `Self` stopped being data. The vocabulary +is a **value context** for the first and an **environmental context** for the second, and this is the +crossing that escapes coherence: you can define as many application types as you like, and there is only +one `String`. + +The second crossing is visible in the code. A capability about `Self` is **self-targeted**, like +`CanEncode` as first written here. Moving the value into a parameter makes it **parameter-targeted**: `CanEncodeValue` is about the `Value`, and `Self` only decides for it. An environmental context can -already choose for itself without that parameter; what the parameter adds is the ability to choose for a -type you *do not own*. +already choose for itself without that parameter; the parameter adds the ability to choose for a type you +*do not own*. ## What it costs **It is more machinery than one trait.** A component is two traits, a marker type, and a wiring line per context. For a capability with one implementation that is pure overhead, and a plain trait is the right -tool — [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the CGP construct for that case, and it needs no +tool. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the CGP construct for that case, and it needs no wiring at all. **Uniqueness is per context, not global.** This is a real limit rather than a technicality. When a program -genuinely needs one answer program-wide — a single consistent `Ord` for a map key, where two orderings in -one program would corrupt the map — per-context choice is the wrong shape, and a coherent trait is safer. -CGP does not make coherence optional; it moves where the single answer is decided. +genuinely needs one answer program-wide, per-context choice is the wrong shape and a coherent trait is +safer. Consider a single consistent `Ord` for a map key, where two orderings in one program would corrupt +the map. CGP does not make coherence optional; it moves where the single answer is decided. -**The choice is explicit, and that cuts both ways.** Nothing is inferred. A context that has not named a -provider does not get a default, and adding a capability means adding a line. That is the property the -whole design rests on, and it is also more to write and read than a trait with one implementation. +**The choice is explicit, which is both the point and a cost.** Nothing is inferred. A context that has +not named a provider does not get a default, and adding a capability means adding a line. That is the +property the whole design rests on, and it is also more to write and read than a trait with one +implementation. **Wiring is checked lazily.** A table naming a provider whose requirements the context cannot meet still compiles; the failure appears later, where the capability is used, and can be long. [`check_components!`](/docs/reference/macros/check_components) forces it to the wiring line and names the actual missing requirement, and [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) leads with the root cause for the classes -it recognizes — a `v0.1.0-alpha` that reshapes the core wiring errors rather than all of them. +it recognizes. It is a `v0.1.0-alpha` that reshapes the core wiring errors rather than all of them. [Checking your wiring](./check-traits.md) is the fuller account. ## Where to go next @@ -311,7 +312,7 @@ not bother. It lays out the range from a plain trait to fully wired components a higher than a problem needs. [Consumer and provider traits](./consumer-and-provider-traits.md) develops the trait split this page -introduced — what each half is for, and how a method call crosses between them. +introduced: what each half is for, and how a method call crosses between them. To see it working rather than argued, the [Hello World tutorial](/docs/tutorials/hello) is five minutes and one durable idea, and the [Area calculation series](/docs/tutorials/area-calculation/) builds the split up diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index ce1fb7f8..9ddc637a 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -13,9 +13,9 @@ arrangement costs, which is the part worth reading before adopting it. ## What an ordinary Rust trait does, and where it stops A Rust trait joins two jobs that are usually the same job. The type that implements `Display` is the -type callers format, and that identity is what lets the compiler resolve a `where T: Display` bound -without anyone naming an implementation — it looks the type up, finds the one implementation, and is -done. Almost all Rust code wants exactly this, which is why the language is built around it. +type callers format, and that identity lets the compiler resolve a `where T: Display` bound without +anyone naming an implementation: it looks the type up, finds the one implementation, and is done. +Almost all Rust code wants exactly this, which is why the language is built around it. The consequence is that a trait offers one implementation per type, and that limit shows up sooner than it sounds. Consider an application that sends email, with a test harness that must not: @@ -50,12 +50,11 @@ impl CanSendEmail for TestApp { This compiles, and it is worth noticing that it already does what you want: two application types, two behaviours, no CGP anywhere. `App` and `TestApp` here are types that stand for a whole -application — their job is to carry the choices and the data the program needs, not to be operated +application. Their job is to carry the choices and the data the program needs, not to be operated on. That shape is legal Rust and nothing about it is unusual. -What fails is *sharing*. As soon as you try to lift a body out into something reusable — so that a -second application could adopt the SMTP behaviour without copying it — the two implementations -collide: +Sharing is where it fails. Try to lift a body out into something reusable, so that a second +application could adopt the SMTP behaviour without copying it, and the two implementations collide: ```rust impl CanSendEmail for T { /* over SMTP */ } @@ -65,7 +64,7 @@ impl CanSendEmail for T { /* record it */ } // error[E01 The compiler rejects the second impl because a type could satisfy both bounds, and it has no principled way to choose. So the arrangement above survives, but every application must hand-write every body, and nothing can be factored out. It is available and unrewarding, which is why almost -nobody builds on it — and it is exactly the gap CGP fills. +nobody builds on it. That is the gap CGP fills. ## Splitting one trait in two @@ -91,7 +90,7 @@ pub trait EmailSender { } ``` -Moving `Self` is the whole trick. An implementation no longer says "this type sends email"; it says +Moving `Self` is the whole change. An implementation no longer says "this type sends email"; it says "this *named implementation* sends email, for any context". The name is a small type the implementing crate declares for the purpose: @@ -102,18 +101,18 @@ impl EmailSender for RecordEmails { /* ... */ } Both compile, and any number more would. There is no overlap, because each `impl` has a different `Self`. There is no orphan-rule problem either, because that `Self` is a type the crate writing the -impl owns — which means a crate can add behaviour for a type it did not define. Neither rule was +impl owns, which means a crate can add behaviour for a type it did not define. Neither rule was repealed; the implementations simply stopped being the kind of thing the rules are about. The wider argument for why that is a fair trade is [Bypassing coherence](./coherence.md). ## A provider is a name, not a value -A **provider** is one of those named implementations — `SendViaSmtp`, `RecordEmails`. It is a +A **provider** is one of those named implementations: `SendViaSmtp`, `RecordEmails`. It is a zero-sized type that exists only to be named. Nothing constructs it, nothing stores it, and there is no field in it to read; at runtime it does not exist at all. That has one consequence worth fixing in mind before reading any provider code. Inside a provider, -`self` and `Self` refer to the **context** — the application type the method is running against — +`self` and `Self` refer to the **context**, the application type the method is running against, never to the provider. When you write a provider with [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), the macro keeps `self` in the source and rewrites it to the context underneath, precisely because the context is the only value that exists when the @@ -124,8 +123,8 @@ method runs. Two pieces connect the halves: a table on the context that names its choice, and a pair of generated implementations that follow it. -The table is what a context writes. It maps each **component** — one capability, defined once, that -implementations can be wired for — to the provider that should supply it, and it is the one place a +The table is what a context writes. It maps each **component**, one capability defined once that +implementations can be wired for, to the provider that should supply it, and it is the one place a choice is recorded: ```rust @@ -134,12 +133,12 @@ delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } ``` `EmailSenderComponent` is a marker type generated alongside the two traits, used purely as the key. -The table itself is a set of trait implementations rather than a runtime structure — the lookup is -performed by the compiler, and nothing survives into the program. +The table itself is a set of trait implementations rather than a runtime structure: the compiler +performs the lookup, and nothing survives into the program. The two generated implementations then chain through it. The first says that any context which -implements the *provider* trait for itself gets the *consumer* trait, which is what makes -`app.send_email(..)` a legal call: +implements the *provider* trait for itself gets the *consumer* trait, so `app.send_email(..)` becomes +a legal call: ```rust impl CanSendEmail for Context @@ -172,19 +171,19 @@ Put together, `app.send_email("a@b.c", "hi")` resolves in three steps. `App` imp `CanSendEmail` because it implements `EmailSender` for itself; it implements `EmailSender` because its table maps `EmailSenderComponent` to `SendViaSmtp`; and `SendViaSmtp` implements `EmailSender` directly. Every step is trait resolution, so the finished call is a direct call to -`SendViaSmtp::send_email` — no lookup happens while the program runs, and a provider no context uses +`SendViaSmtp::send_email`: no lookup happens while the program runs, and a provider no context uses never reaches the binary. The one piece of that listing not yet explained is -[`IsProviderFor`](/docs/reference/traits/is_provider_for), which also rides on the provider trait as a -supertrait. Every provider implements it under exactly the bounds it needs, and requiring it here is -what carries those bounds back down the chain — so when a context is missing something a provider -requires, the compiler can name the missing requirement instead of reporting only that the provider -trait is not implemented. It is generated, never written by hand. +[`IsProviderFor`](/docs/reference/traits/is_provider_for), which is also a supertrait on the provider +trait. Every provider implements it under exactly the bounds it needs, and requiring it here carries +those bounds back down the chain, so when a context is missing something a provider requires, the +compiler can name the missing requirement instead of reporting only that the provider trait is not +implemented. It is generated, never written by hand. Three liberties in the listings above are worth knowing before you read a real error message. The -generated type parameters carry reserved names — the context is `__Context__` and the provider -`__Provider__` — and the delegate is spelled out in full as +generated type parameters carry reserved names: the context is `__Context__` and the provider +`__Provider__`, and the delegate is spelled out in full as `<__Provider__ as DelegateComponent>::Delegate`. `Context`, `Provider`, and `Provider::Delegate` here are for legibility. And the provider trait printed earlier on this page omitted its `IsProviderFor` supertrait, which the real `EmailSender<__Context__>` carries. `cargo cgp expand` will @@ -195,7 +194,7 @@ show you all of it as the macros actually emit it. In practice you write neither trait by hand. [`#[cgp_component]`](/docs/reference/macros/cgp_component) generates the pair, the marker, and the two blanket implementations from one trait definition, and [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) lets a provider be written in the consumer trait's -shape — keeping `self` and the original signatures — and rewrites it into the provider form: +shape, keeping `self` and the original signatures, and rewrites it into the provider form: ```rust use cgp::prelude::*; @@ -238,9 +237,9 @@ Two details of that listing are worth pointing out. The [`#[implicit]`](/docs/reference/attributes/implicit) arguments are how each provider reaches into its context: they read a same-named field and disappear from the method's public signature, so `app.send_email(to, body)` still takes two arguments. And the two providers depend on *different* -fields — `SendViaSmtp` needs an `smtp_server`, `RecordEmails` needs somewhere to record — with +fields: `SendViaSmtp` needs an `smtp_server` and `RecordEmails` needs somewhere to record, with neither requirement appearing in `CanSendEmail`. That is -[impl-side dependency injection](./impl-side-dependencies.md), and it is what stops a context paying +[impl-side dependency injection](./impl-side-dependencies.md), and it stops a context paying for the needs of implementations it did not choose. A consumer trait remains an ordinary Rust trait throughout. Nothing stops a context from implementing @@ -251,7 +250,7 @@ implementation, not a replacement for how traits already work. ## What it costs **It is more machinery than a plain trait.** One capability becomes two traits, a marker type, and a -line of wiring per context. For a capability with a single implementation, that is pure overhead — +line of wiring per context. For a capability with a single implementation, that is pure overhead: write a plain trait, or reach for [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), which builds a capability from a function with no component and no wiring at all. @@ -262,20 +261,20 @@ capability is finally used, and the error can be long. This is real, and it has the error names the actual gap, and [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reshapes the recognized failures to lead with the root cause, though it is a `v0.1.0-alpha` and covers the core wiring errors rather than -every class. Neither makes the raw diagnostics pleasant — see +every class. Neither makes the raw diagnostics pleasant. See [Checking your wiring](./check-traits.md) for what to expect. **There is a hop between the call and the code that runs.** `app.send_email(..)` no longer points at one body you can jump to. Unlike runtime dispatch the indirection is fully resolved at compile time and never ambiguous, and the wiring table is a single greppable place naming exactly one provider per -component — but it is a hop, and a reader unfamiliar with the codebase has to follow it. +component. But it is a hop, and a reader unfamiliar with the codebase has to follow it. ## Where to go next [Bypassing coherence](./coherence.md) is the argument underneath this page: why Rust's rule exists, why it is correct, and why scoping it per context is a fair trade rather than a loophole. [Impl-side dependencies](./impl-side-dependencies.md) develops the other half of what makes providers -reusable — how an implementation states what it needs without the interface carrying it. +reusable: how an implementation states what it needs without the interface carrying it. To write this rather than read about it, the [Area calculation tutorial](/docs/tutorials/area-calculation/) builds the same split up from plain functions, and calls providers by name before any wiring exists. diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index 6fbee863..e6b84984 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -24,8 +24,8 @@ type-level list of handlers, one per element, run as an ordinary It runs in two directions, and they are mirror images. **Matching** consumes a sum. The value is converted into its extractor, and the handlers are tried in -turn until one matches — so the list stops at the first success. **Building** produces a product. The -builder starts empty, and every handler runs, each setting one field — so the list runs to the end. +turn until one matches, so the list stops at the first success. **Building** produces a product. The +builder starts empty, and every handler runs, each setting one field, so the list runs to the end. Both come out as `Computer` or `Handler` providers, which is the point: a dispatcher goes anywhere a computation goes. It can be wired to a context, nested inside another dispatcher to handle a group of @@ -72,8 +72,8 @@ The guarantee is the mirror image too: finalizing is available only when every f builder missing a handler cannot finalize and does not compile. A matcher proves it covered every variant; a builder proves it filled every field. -This is the machinery under the [extensible builder](./extensible-records.md) — the dispatcher is what -runs each subsystem's provider and merges the outputs. +This is the machinery under the [extensible builder](./extensible-records.md): the dispatcher runs +each subsystem's provider and merges the outputs. ## The shortcut for the common case @@ -89,24 +89,24 @@ pub trait CanDescribe { ``` Implement `CanDescribe` for `Circle` and for `Rectangle`, and any enum whose variants all implement it -gets it too — `shape.describe()` works with no wiring, no combinator named, and no `match`. It is the +gets it too: `shape.describe()` works with no wiring, no combinator named, and no `match`. It is the form to reach for first, and the rest of this page is what it is doing underneath. ## What it costs **A recursive shape needs an extra hop written by hand.** The table above names the matcher directly, which works because a `Shape` never contains another `Shape`. When a variant's payload *is* the enum -again — an expression language, a tree — the matcher dispatches back through the same component, and a -thin wrapper provider has to sit between the enum's entry and the matcher to break the resolution cycle. -It is ceremony with no conceptual content, and it is the piece of a hand-wired dispatcher most likely to -puzzle a reader. +again, as in an expression language or a tree, the matcher dispatches back through the same component, +and a thin wrapper provider has to sit between the enum's entry and the matcher to break the resolution +cycle. It is ceremony with no conceptual content, and it is the piece of a hand-wired dispatcher most +likely to puzzle a reader. **A missing handler reports as a shape, not as a name.** The failure is an unsatisfiable bound over a partial-variant or partial-record type, which is accurate about what is missing and does not say "`Rectangle` has no handler". **There is one hop per element.** Each variant tried is a resolution step, and the whole chain is -resolved at compile time — so this costs compile time rather than run time, and a wide enum +resolved at compile time, so this costs compile time rather than run time, and a wide enum dispatched at many types is somewhere that cost shows. **And a `match` is still usually right.** Dispatching pays when the shape is not known where the logic is diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index f8218e6d..2ee267e1 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -9,14 +9,14 @@ Building and reading a struct through the names of its fields, without naming th This page answers *how does code assemble a struct it does not know the type of?* It shows what a struct becomes when its shape is a type, how a value is built one field at a time with the compiler -tracking what is still missing, and the pattern that follows — independent pieces of a program each +tracking what is still missing, and the pattern that follows: independent pieces of a program each contributing part of a whole. It closes on the opt-in requirement, which is the honest limit of all of this. ## What a closed struct cannot do A Rust struct is closed against incremental construction. A struct literal names the concrete type and -supplies every field at once, so building one is something a single place has to do — and that place +supplies every field at once, so building one is something a single place has to do, and that place grows a line for every subsystem the program acquires: ```rust @@ -47,22 +47,22 @@ pub struct DatabaseClient { } ``` -Its shape is now available as a type-level list — one entry per field, each pairing the field's name +Its shape is now available as a type-level list, one entry per field, each pairing the field's name with the field's type: ```rust Product![Field, Field] ``` -`Symbol!("url")` is the field name lifted into a type, which is what makes matching *by name* something -the trait system can do. Nothing here is inspected at run time; the list exists during compilation and -is gone afterwards. This is the same field-name-as-type idea behind an -[implicit argument](./implicit-arguments.md), scaled from one field to a whole struct. +`Symbol!("url")` is the field name lifted into a type, so the trait system can match *by name*. Nothing +here is inspected at run time; the list exists during compilation and is gone afterwards. This is the +same field-name-as-type idea behind an [implicit argument](./implicit-arguments.md), scaled from one +field to a whole struct. ## Built one field at a time, checked all the way With the shape available, a value can be assembled by parts that never meet. Building goes through a -**partial record** — a companion type carrying, per field, whether that field is present yet: +**partial record**, a companion type carrying, per field, whether that field is present yet: ```rust let app: App = App::builder() @@ -76,7 +76,7 @@ struct's fields into it, matching them by name and flipping each from absent to change at every step, tracking what has been filled in. That tracking is the whole safety argument. `finalize_build` exists **only** for the configuration with -every field present, so finalizing early is not a runtime panic or a `None` — it does not compile: +every field present, so finalizing early is not a runtime panic or a `None`. It does not compile: ```rust // `http_timeout` has never been set, so there is no `finalize_build` to call. @@ -90,13 +90,13 @@ not matter. ## The pattern this is for -What the machinery buys is the **extensible builder**: each subsystem is a provider producing its own +The machinery buys the **extensible builder**: each subsystem is a provider producing its own small struct, knowing nothing about the target or about its siblings, and a dispatcher runs them all and merges the outputs into the whole. The list of contributors is then wiring, so swapping a subsystem is a line, and a second application -built from a different mix of the same providers is another table. What guarantees the mix is complete -is the same thing as above — if the providers between them do not supply every field, the build does not +built from a different mix of the same providers is another table. The same thing as above guarantees +the mix is complete: if the providers between them do not supply every field, the build does not finalize and the code does not compile. The dispatcher is one of the [dispatch combinators](./dispatching.md), which is where the general form @@ -105,12 +105,12 @@ of "run a handler per field" lives. ## What it costs **Only types that opted in.** All of this works on a struct that derives the shape. A struct from -another crate that has not is invisible to it — which is the honest difference between this and runtime +another crate that has not is invisible to it. That is the honest difference between this and runtime reflection, and the thing to say first when someone reads "generic over any type's structure". **Fields match by name and type, with nothing checking intent.** Two subsystems that both produce a -`timeout: u32` are producing the same field as far as merging is concerned. That is what makes the -decoupling work, and it means a rename in one place silently stops matching in another. +`timeout: u32` are producing the same field as far as merging is concerned. The decoupling depends on +exactly that, and it means a rename in one place silently stops matching in another. **The error messages are the worst in CGP.** A missing field surfaces as an unsatisfiable bound over a partial record whose type spells out every field and its presence marker. It is accurate, it is long, @@ -118,7 +118,7 @@ and there is no version of it that reads like "you forgot `http_timeout`" withou **And it is a lot of machinery for a constructor.** An application assembled in one place, by code that is allowed to know the type, should be assembled with a struct literal. This earns its keep when the -contributors must not know the whole — a plugin set, a framework building a user's type, several +contributors must not know the whole: a plugin set, a framework building a user's type, or several applications sharing subsystems. ## Where to go next diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 9c01aa6d..4e32b2f0 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -10,17 +10,17 @@ checked by the compiler. This page answers *how does code handle an enum whose variants it does not know?* It is the dual of [extensible records](./extensible-records.md) and assumes it. It shows the shape of an enum as a type, -the trick that keeps exhaustiveness checked without a wildcard, and the conversions between enums that -share variants. It closes on the one restriction the derive imposes. +the technique that keeps exhaustiveness checked without a wildcard, and the conversions between enums +that share variants. It closes on the one restriction the derive imposes. -## The problem a `match` bakes in +## The problem a `match` builds in A concrete `enum` plus a `match` puts the full set of variants into every function that consumes it. Add a variant and every `match` has to change; that is Rust's exhaustiveness check doing its job, and it is usually what you want. It stops being what you want at exactly two moments. When new variants should be addable **without -editing the code that handles the others** — a plugin adding a message kind, a downstream crate +editing the code that handles the others**: a plugin adding a message kind, or a downstream crate extending an expression language. And when a variant is defined **upstream**, where handling it means forking rather than extending. @@ -54,8 +54,8 @@ written against "an enum containing a `Circle` variant" rather than against `Sha Taking a value apart runs through a **partial variant**, and this is where the design earns its keep. The value is first converted into a form in which every variant is still possible. Then each variant is -tried in turn: if the value is that variant, its payload comes out; if not, what comes back is a -*remainder* — the same value, with that one variant ruled out **in the type**. +tried in turn. If the value is that variant, its payload comes out. If not, the result is a *remainder*: +the same value, with that one variant ruled out **in the type**. Each miss therefore narrows the type. After every variant has been tried, the remainder is a type that rules out everything, and a type that rules out everything is uninhabited: a value that cannot exist. @@ -64,7 +64,7 @@ nothing to handle. No wildcard arm, no `unreachable!()`. And the guarantee is the one a concrete `match` gives. Add a variant to the enum without handling it and the final remainder becomes inhabited again, so the code stops compiling until the new variant is -covered — recovered for generic code that never named the enum. +covered. The guarantee is recovered for generic code that never named the enum. ## One handler, many enums @@ -88,8 +88,8 @@ delegate_components! { ``` `App` can now stringify a two-variant `Reading` and a three-variant `ExtendedReading` through the same -wiring, with no arm added anywhere — because the handler is written against a variant, not against an -enum. That is the **extensible visitor**: the logic for each variant lives on its own, and a dispatcher +wiring, with no arm added anywhere, because the handler is written against a variant rather than against +an enum. That is the **extensible visitor**: the logic for each variant lives on its own, and a dispatcher routes a value to whichever one matches. [Dispatching](./dispatching.md) is the page for the dispatcher itself. @@ -98,7 +98,7 @@ itself. Because variants are matched by name, two enums with overlapping variants interconvert with no hand-written conversion. -**Widening always succeeds** — every variant of the narrow enum has a home in the wide one: +**Widening always succeeds**, because every variant of the narrow enum has a place in the wide one: ```rust let wide: ExtendedReading = narrow.upcast(PhantomData::); @@ -113,17 +113,17 @@ let narrow: Result = wide.downcast(PhantomData::); Widening is also how a provider constructs a value using only the variants it knows about: build a small local enum, lift it into the full one. That is the variant-side counterpart of reading a field through a -getter — code touching part of a shape without naming the whole. +getter: code touching part of a shape without naming the whole. ## What it costs **One unnamed field per variant.** A derivable enum must be a sum of products: each variant holds -exactly one unnamed payload. A richer variant wraps its data in a dedicated struct — which is why the +exactly one unnamed payload. A richer variant wraps its data in a dedicated struct, which is why the example above is `Circle(Circle)` rather than `Circle { radius: u64 }`. It is a real constraint on how the enum is written, and it is the first thing anyone hits. The constraint comes from constructing and deconstructing rather than from the shape itself: [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) accepts every variant shape, so an -enum that cannot take the full family can still have a structural representation — just no generic +enum that cannot take the full family can still have a structural representation, with no generic constructor and no extractor. **Only types that opted in**, as with records. An enum from a crate that has not derived the shape is @@ -135,13 +135,13 @@ a partial-variant type spelling out every variant and its presence marker. It is **And a closed enum with fixed operations should stay one.** A `match` is clearer, faster to read, and free. This pays when the variant set is genuinely open, or when independent modules must each contribute -one — not when an enum merely has several variants. +one, not when an enum merely has several variants. ## Where to go next [Extensible records](./extensible-records.md) is the other half, and worth reading first if the shape type above was unfamiliar. [Dispatching](./dispatching.md) is the machinery that runs a handler per -variant, and [Type-level DSLs](./type-level-dsls.md) is the largest thing this pattern builds — a +variant, and [Type-level DSLs](./type-level-dsls.md) is the largest thing this pattern builds: a language whose terms are types and whose interpreter is the trait system. For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) is the umbrella @@ -150,7 +150,8 @@ whole shape, [`#[derive(ExtractField)]`](/docs/reference/derives/derive_extract_ narrowing, and [`#[derive(FromVariant)]`](/docs/reference/derives/derive_from_variant) for construction by name. [`ExtractField`](/docs/reference/traits/extract_field) is the extractor family those produce, [`FromVariant`](/docs/reference/traits/from_variant) constructs a variant generically, and -[the casts](/docs/reference/traits/can_upcast) are `CanUpcast` and [`CanDowncast`](/docs/reference/traits/can_downcast). +[the casts](/docs/reference/traits/can_upcast) are `CanUpcast` and +[`CanDowncast`](/docs/reference/traits/can_downcast). --- diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 53e74080..b3afef44 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -5,8 +5,8 @@ sidebar_position: 11 # Handlers -The family of computation components, and the three axes — synchronous or async, fallible or not, -taking an input or not — that tell them apart. +The family of computation components, and the three axes that tell them apart: synchronous or async, +fallible or not, and taking an input or not. This page answers *why does CGP ship a dozen computation components instead of one?* It gives the shape they share, the three axes that separate them, the promotion that means you only ever write the @@ -16,7 +16,7 @@ better answer. ## Computation as something a context decides Most CGP components are capabilities an application has: send email, query a user, load a file. The -handler family is for a different thing — a *computation* the application performs on a value, where +handler family is for a different thing: a *computation* the application performs on a value, where the interesting question is not "can it" but "which one, and composed how". Everything in the family shares one shape: @@ -35,10 +35,10 @@ have. ## Three axes, and the names that encode them **Synchronous or asynchronous.** A synchronous member returns immediately; an asynchronous one returns -a future and carries `Async` in its name — `AsyncComputer` beside `Computer`. +a future and carries `Async` in its name, as `AsyncComputer` beside `Computer`. **Infallible or fallible.** A fallible member returns a `Result` against the context's -[abstract error type](./modular-error-handling.md), and carries `Try` — `TryComputer` beside `Computer`. +[abstract error type](./modular-error-handling.md), and carries `Try`, as `TryComputer` beside `Computer`. **Owned or borrowed input.** A `*Ref` variant takes `&Input` where the base takes `Input`, for a computation that only reads its argument. @@ -46,7 +46,7 @@ computation that only reads its argument. Cross those and you get the members that are documented separately: [`Computer`](/docs/reference/components/computer) is the pure synchronous corner, [`TryComputer`](/docs/reference/components/try_computer) the fallible synchronous one, and -[`Handler`](/docs/reference/components/handler) — async *and* fallible — the general workhorse, which is +[`Handler`](/docs/reference/components/handler), async *and* fallible, the general workhorse, which is why it needs no qualifier. [`Producer`](/docs/reference/components/producer) sits slightly apart: a computation with no input at all, producing a value from the context and a tag. @@ -56,8 +56,8 @@ two numbers is a `Computer`, and nothing about it should mention futures or erro ## Write the weakest one; the rest come free Which raises the obvious objection: if wiring wants a `Handler` and you wrote a `Computer`, have you -picked wrong? No — the inclusions between the axes are real (an infallible computation is a fallible one -that never fails, a synchronous one is an async one that never awaits) and CGP encodes each as a +picked wrong? No. The inclusions between the axes are real (an infallible computation is a fallible one +that never fails, a synchronous one is an async one that never awaits), and CGP encodes each as a combinator that lifts a provider from one member into another. The practical result is that one definition answers the whole family: @@ -85,7 +85,7 @@ whatever it needs.** You do not have to predict which one a caller will want. ## A pipeline is a wiring entry -Because every member is an ordinary component, composing computations is composing providers — and the +Because every member is an ordinary component, composing computations is composing providers, and the combinators that do it are [higher-order providers](./higher-order-providers.md), so a whole chain has a name and lives in a table: @@ -105,7 +105,7 @@ delegate_components! { `PipeHandlers` runs the stages left to right, threading each output into the next input. Each stage here reads one field from the context and folds it into the running value, so `app.compute(…, 5)` evaluates -`((5 * foo) + bar) * baz` — and the shape of the computation is a line of wiring rather than a function +`((5 * foo) + bar) * baz`, and the shape of the computation is a line of wiring rather than a function body. Changing the order, dropping a stage, or swapping one for another is an edit to a type. `ComposeHandlers` nests rather than chains, `ReturnInput` passes a value through, and the `Promote*` @@ -114,7 +114,7 @@ adapters are the lifts from the previous section made explicit. They are catalog ## Many computations on one context -The `Code` tag is what stops a context being limited to one computation per member of the family. Two +The `Code` tag stops a context being limited to one computation per member of the family. Two tags, two providers, one table: ```rust @@ -129,19 +129,19 @@ delegate_components! { ``` `App.compute(PhantomData::, 21)` and `App.compute(PhantomData::, 21)` reach different -providers. Dispatch can key on the `Input` type as readily as on the `Code`, which is what -[dispatching](./dispatching.md) over extensible data uses, and what makes a program written as types -interpretable — see [type-level DSLs](./type-level-dsls.md). +providers. Dispatch can key on the `Input` type as readily as on the `Code`. That is how +[dispatching](./dispatching.md) over extensible data works, and how a program written as types becomes +interpretable, as [type-level DSLs](./type-level-dsls.md) shows. ## What it costs **The `PhantomData` at every call site.** `app.compute(PhantomData::<()>, input)` is the price of the -tag being a type. For a context with one computation it is pure ceremony, and it is what most makes -handler code look unlike ordinary Rust. +tag being a type. For a context with one computation it is pure ceremony, and it does more than anything +else to make handler code look unlike ordinary Rust. **The family is a lot of names to hold.** Twelve or so components across three axes, plus the promotion -combinators, is more surface than any other part of CGP. The mitigation is the rule above — write the -weakest member and ignore the rest — but reading someone else's handler wiring means knowing which +combinators, is more surface than any other part of CGP. The mitigation is the rule above, to write the +weakest member and ignore the rest, but reading someone else's handler wiring means knowing which member each name belongs to. **A pipeline in a type is harder to debug than a function body.** There is no line to step through and @@ -150,7 +150,7 @@ terms of an `Output` associated type, and localizing it means the per-layer chec [checking your wiring](./check-traits.md). **And most computations should stay functions.** This family earns its keep when the *steps* need to be -chosen by wiring — when different contexts run different pipelines, or a program is data. A computation +chosen by wiring: when different contexts run different pipelines, or a program is data. A computation with one implementation is a function, and [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is how to write one that still reads its inputs from a context. diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index 17f2316e..8a4e2ab5 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -9,18 +9,18 @@ Providers parameterized by other providers, so one implementation can be express another. This page answers *how does one implementation build on another without choosing which one?* It shows -the shape, the one piece of syntax that makes it look strange, and the two things it buys — composition +the shape, the one piece of syntax that makes it look strange, and the two things it buys: composition without a context, and a wrapper that falls back to whatever the context already decided. It closes on why this is the step most often taken too early. ## Choosing is not the only thing you can do with a provider Wiring picks one implementation from several. That covers a lot, and it does not cover the case where -what you want is *the same transformation over any of them*. +you want *the same transformation over any of them*. A scaled area is that case. Scaling knows how to multiply by a factor squared; it does not know how to compute an area, and there is no reason for it to. The base calculation is not something the wrapper -should choose — it is something the wrapper should take: +should choose. It is something the wrapper should take: ```rust #[cgp_impl(new ScaledArea)] @@ -43,17 +43,17 @@ delegate_components! { ScaledCircle { AreaCalculatorComponent: ScaledArea`, and the attribute that fills it in One detail makes these look stranger than they are, and it is worth meeting deliberately rather than in an error message. -A provider trait carries the context as an explicit parameter — that is what the -[trait split](./consumer-and-provider-traits.md) does. So when a wrapper requires its inner provider to -implement the same capability, the requirement has to name that context slot: +The [trait split](./consumer-and-provider-traits.md) gives a provider trait the context as an explicit +parameter. So when a wrapper requires its inner provider to implement the same capability, the +requirement has to name that context slot: ```rust #[cgp_impl(new ScaledArea)] @@ -72,11 +72,11 @@ arrives as an unexplained argument. [`#[use_provider]`](/docs/reference/attribut to remove it: write `Inner: AreaCalculator` and the attribute supplies the ``, which is the whole of what it does. That is the version in the first snippet, and it is the one to write. -What the attribute does *not* do is change the call. `Inner::area(self)` stays as it is — the inner -provider is invoked as an associated function with the context passed explicitly, because that is the -shape the provider trait actually has. It is the one place in a well-written provider where the trait -split is still visible, and trying to make it read as `self.area()` would be calling the context's own -wiring, which is a different thing entirely. +The attribute does *not* change the call. `Inner::area(self)` stays as it is: you invoke the inner +provider as an associated function with the context passed explicitly, because that is the shape the +provider trait actually has. It is the one place in a well-written provider where the trait split is +still visible, and trying to make it read as `self.area()` would be calling the context's own wiring, +which is a different thing entirely. ## Composition without a context to name @@ -87,7 +87,7 @@ pub type ScaledScaledRectangleArea = ScaledArea>; ``` A type alias, with no bounds on it at all. Compare what composing two constrained generic functions -normally takes — the composed signature restating both sets of constraints, in Rust as much as in +normally takes: the composed signature restating both sets of constraints, in Rust as much as in Haskell. Here the requirements are discharged where a context wires the stack, not where the stack is written, so a composition is just a name for a shape and can be published, reused, and further wrapped without accumulating a `where` clause. @@ -124,7 +124,7 @@ delegate_components! { } ``` -Naming an inner provider instead — `SumAreas` — pins that step regardless of what the +Naming an inner provider instead, `SumAreas`, pins that step regardless of what the context would have said, which is how one entry overrides a nested decision without disturbing the rest of the table. The default only exists when the provider is declared with an explicit struct; one declared inline by the attribute has no parameter to default. @@ -147,28 +147,28 @@ where ``` `Tag` here is a field name, used as a key. Nothing is delegated to it, nothing implements a capability -on its behalf, and none of the machinery on this page applies. What makes a provider higher-order is -that a parameter is *bound to a provider trait* and invoked to do part of the work. +on its behalf, and none of the machinery on this page applies. A provider is higher-order when a +parameter is *bound to a provider trait* and invoked to do part of the work. ## What it costs **It is the step most often taken too early.** A provider that is not wrapping anything has nothing to gain from a parameter, and adding one buys a type argument at every wiring site, a bound to get right, and a call form that reads unlike the rest of the code. Reach for this when one implementation should -genuinely be expressed in terms of another — not when it merely could be. +genuinely be expressed in terms of another, not when it merely could be. **A failure names the stack, not the layer.** Checking a context tells you `ScaledArea` does not work; it does not say which half is at fault. The [`#[check_providers]`](/docs/reference/macros/check_components) form fixes that by asserting against -each layer separately, and a nested stack is the main reason it exists — but it is another thing to +each layer separately, and a nested stack is the main reason it exists. But it is another thing to remember, and without it a deep stack is genuinely hard to debug. **Compile-time work grows with depth.** Each layer is another round of trait resolution, and a stack that is several deep and instantiated at many types is one of the places CGP's compile-time cost is most visible. -**And the call form leaks.** `Inner::area(self)` is the one construct here that still reads -inside-out, and no attribute hides it. It is a small tax on every higher-order provider written. +**And the call form stays visible.** `Inner::area(self)` is the one construct here that still reads +inside-out, and no attribute hides it. It is a small cost on every higher-order provider written. ## Where to go next @@ -176,7 +176,7 @@ inside-out, and no attribute hides it. It is a small tax on every higher-order p with: bundling several wiring choices under one name, which composes tables rather than behaviour. [Checking your wiring](./check-traits.md) covers the per-layer check this page needs. -[Handlers](./handlers.md) is where composition of this kind is the whole point — a family of +[Handlers](./handlers.md) is where composition of this kind is the whole point: a family of computation components whose combinators are higher-order providers, chained into pipelines. For the constructs, [`#[use_provider]`](/docs/reference/attributes/use_provider) completes the inner diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index b44214f7..cf147b3d 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -44,14 +44,14 @@ where `greet_twice` never touches a name. It declares the requirement because the function it calls does, and the function above `greet_twice` will declare it for the same reason. Add a requirement four layers -down and every layer above grows a bound it has no interest in — which is why a mature generic API +down and every layer above grows a bound it has no interest in. This is why a mature generic API tends to accumulate signatures nobody can read, and why adding a dependency deep in a library is a change that reaches its users. ## Moving the requirement onto the implementation Rust already has the answer, and most Rust programmers have used it without naming it. Put the logic in -a **blanket implementation** — one `impl` covering every type that meets a bound — and the requirement +a **blanket implementation**, one `impl` covering every type that meets a bound, and the requirement moves out of the interface and onto the implementation: ```rust @@ -81,16 +81,16 @@ where } ``` -The requirement did not disappear — the compiler still checks it, at the point where a concrete type -meets the impl. What changed is that it stopped being part of the contract. That is an **impl-side +The requirement did not disappear: the compiler still checks it, at the point where a concrete type +meets the impl. It has only stopped being part of the contract. That is an **impl-side dependency**: something an implementation needs, stated where the implementation lives rather than where the interface is declared. This is the construct CGP is built out of, which is worth saying plainly, because it makes the foundation something you already have. If you have used `Itertools` or `StreamExt`, you have used a -blanket impl over every `Iterator` or every `Stream` — that is why a method appears on a type whose -author never wrote it. What CGP adds is not the mechanism but the ability to have more than one of them -and choose between them. +blanket impl over every `Iterator` or every `Stream`. That is why a method appears on a type whose +author never wrote it. CGP adds not the mechanism but the ability to have more than one of them and +choose between them. ## Two providers, two sets of requirements, one interface @@ -127,7 +127,7 @@ impl EmailSender { the right way to take it: the provider is saying *this code relies on the context being able to do this*. Underneath it becomes a bound on the implementation, exactly as in the blanket impl above. -The consequence is worth stating precisely. `CanSendEmail` has no idea that SMTP servers exist. A +The consequence is worth stating precisely. `CanSendEmail` says nothing about SMTP servers. A function bounded on it accepts both applications, even though they satisfy it for reasons that have nothing in common: @@ -140,20 +140,20 @@ where } ``` -Both examples here wire a type standing for an application — `App` for production, `TestApp` for a test -harness — rather than a piece of data. That is where most CGP code lives, and it is what makes the -point land: the two applications differ in what they can supply, and the interface between them and +Both examples here wire a type standing for an application, `App` for production and `TestApp` for a +test harness, rather than a piece of data. That is where most CGP code lives, and it makes the point +clearly: the two applications differ in what they can supply, and the interface between them and `notify` does not record the difference. ## The three things an implementation can ask for -Everything above is one kind of requirement — a capability. There are three, they all work the same +Everything above is one kind of requirement, a capability. There are three, they all work the same way, and each has a syntax that keeps the bound out of sight. -**A capability** is what `#[uses]` declares, as above. It covers other CGP capabilities and ordinary +**A capability** is the kind `#[uses]` declares, as above. It covers other CGP capabilities and ordinary Rust traits alike: `#[uses(AsRef<[u8]>)]` is as valid as `#[uses(HasSmtpServer)]`. -**A value** is a field the implementation reads, and it is declared by writing it as an argument: +**A value** is a field the implementation reads; you declare it by writing it as an argument: ```rust #[cgp_impl(new GreetByName)] @@ -164,13 +164,12 @@ impl Greeter { } ``` -The `name` argument is not passed by the caller. It is read from a `name` field on the context, the -requirement is generated from the argument's name and type and lands on the implementation, and -`greet()` still takes nothing from the outside. [Implicit arguments](./implicit-arguments.md) develops -this one. +The caller does not pass the `name` argument. The provider reads it from a `name` field on the context, +and the macro turns the argument's name and type into a requirement on the implementation, so `greet()` +still takes nothing from the outside. [Implicit arguments](./implicit-arguments.md) develops this one. -**A type** is the third, and it is the one that buys the most, because what it displaces is not a -leaked bound but a leaked *parameter*. +**A type** is the third, and it buys the most, because it displaces not a leaked bound but a leaked +*parameter*. ## Type dependencies, and why they need no parameter @@ -195,7 +194,7 @@ along declares all three and repeats their bounds, and adding a fourth open type for every caller. An **abstract type** inverts the direction. Rather than the caller supplying the type, the context -determines it — it is an associated type on a trait the context implements, so an implementation can +determines it. It is an associated type on a trait the context implements, so an implementation can name it without anyone choosing it at a call site: ```rust @@ -225,7 +224,7 @@ signatures growing: **the number of types a context decides can rise freely, bec passing.** [Abstract types](./abstract-types.md) is the page for that half. One thing to be accurate about: when a capability's own signature names the type, the owning trait does -become part of the contract — `CanRunJob` really does imply `HasErrorType`. But a caller bounding on +become part of the contract: `CanRunJob` really does imply `HasErrorType`. But a caller bounding on `CanRunJob` gets that implication for free, never restates it, and names the type only if it handles one. Compare `trait CanRunJob`, which forces `` onto every caller and every caller's caller whether they touch an error or not. The bound is on the implementation; the parameter would be on @@ -234,7 +233,7 @@ everyone. ## What it costs **A hidden requirement is hidden from you too.** The point of all this is that `CanSendEmail` does not -say what its implementations need — which also means reading the interface tells you nothing about what +say what its implementations need, which also means reading the interface tells you nothing about what a context must supply. The answer is in the provider, and finding it means knowing which provider the context wired. @@ -247,8 +246,8 @@ an unsatisfied field bound naming a type-level spelling of the field name, sever that caused it. [`check_components!`](/docs/reference/macros/check_components) forces the failure to the wiring line and names the actual gap, and [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) leads with the root cause for the -classes it recognizes — a `v0.1.0-alpha` covering the core wiring errors rather than all of them. Both -help substantially; neither makes the raw output pleasant. +classes it recognizes. It is a `v0.1.0-alpha` covering the core wiring errors rather than all of them. +Both help substantially; neither makes the raw output pleasant. **And it is more machinery than a plain function needs.** For a capability with one implementation, the blanket impl in the second section is the whole of what is useful here, and it is ordinary Rust. @@ -263,7 +262,7 @@ and the one that changes how a codebase's signatures age. [Consumer and provider traits](./consumer-and-provider-traits.md) is the other half of what a component is: this page covers how an implementation states what it needs, and that one covers how a call reaches -the implementation at all. [Checking your wiring](./check-traits.md) takes up the cost above — why the +the implementation at all. [Checking your wiring](./check-traits.md) takes up the cost above: why the check is late, and what to do about it. For the constructs themselves, [`#[uses]`](/docs/reference/attributes/uses) declares a capability, diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index 6670124e..f1aa64d7 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -53,15 +53,15 @@ impl Greeter { } ``` -The argument is not passed by anyone. `#[implicit]` removes it from the method's public signature, adds -the field requirement to the implementation, and binds the value at the top of the body — so a caller +Nobody passes the argument. `#[implicit]` removes it from the method's public signature, adds +the field requirement to the implementation, and binds the value at the top of the body, so a caller still writes `app.greet()` with no arguments, and the body reads a plain local. Nothing was hidden that was not already hidden. The bound, the tag, and the read are the same three -things; what changed is that the author writes the name of the value they want and the macro derives +things; the change is that the author writes the name of the value they want and the macro derives the rest from it. Someone who understands functions and arguments can write a complete provider without meeting a type-level anything, which is why this is the recommended way to read a context field and the -on-ramp most introductions to CGP should use. +starting point most introductions to CGP should use. ## A capability from a function alone @@ -75,8 +75,8 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> } ``` -Any context with a `width` and a `height` can now call `rectangle_area()`. That is the whole program — -there is no component to define and nothing to choose, because this capability has one implementation +Any context with a `width` and a `height` can now call `rectangle_area()`. That is the whole program. +There is no component to define and nothing to choose, because this capability has one implementation and needs none. It is the smallest useful thing CGP does, and the right place to start a codebase that may never need more. @@ -100,8 +100,8 @@ pub fn describe( } ``` -The rule of thumb is that the declared type is what the body works with and the conversion is the -macro's problem. Prefer a borrow where the body only reads — `&str` over `String` — since that is free +The rule of thumb is that the body works with the declared type and the conversion is the +macro's problem. Prefer a borrow where the body only reads, `&str` over `String`, since that is free while an owned argument clones. Further forms exist for options and slices, and they are enumerated on the [`#[implicit]`](/docs/reference/attributes/implicit) reference page rather than here. @@ -110,8 +110,8 @@ These are the same rules a getter follows, so learning them once covers both. ## When a getter trait is still the right thing An implicit argument reads from the provider's own `self`. That covers every value a provider wants -from its own context — including one that several providers each read, declared as the same argument in -each — so it is the default, and a getter trait is the exception. +from its own context, including one that several providers each read, declared as the same argument in +each, so it is the default, and a getter trait is the exception. Three cases fall outside it. The value may live on a **type other than the context**, where there is no `self` field to read and the requirement is a bound on that other type: @@ -130,9 +130,9 @@ where `HasAuthHeader` there is a getter on `Request`, not on the application, and no implicit argument can express that. The accessor may also need to exist as a **named capability** that other code depends on -through `#[uses(...)]` or a supertrait — a name is something you can require, and an argument is not. Or -the getter may carry an **associated type inferred from the field**, so callers stay generic over what -the value actually is. +through `#[uses(...)]` or a supertrait, because a name is something you can require and an argument is +not. Or the getter may carry an **associated type inferred from the field**, so callers stay generic +over what the value actually is. Outside those three, prefer the argument. A getter trait declared only so a provider can read a field of its own context is a trait, an impl, and an import bought for nothing. @@ -144,17 +144,17 @@ whose argument was named after it, and the failure surfaces as a missing-field e forces the check rather than at the rename. Nothing in the struct definition marks the coupling. **The requirement is invisible at the call site.** `app.greet()` gives no hint that the context must -carry a `name`. That is the point — it is what keeps the requirement off the interface — and it is also +carry a `name`. That is the point, since it keeps the requirement off the interface, and it is also why the answer to "what does this context need?" lives in the providers it wired rather than in the traits it implements. **Matching by name is looser than matching by type.** Two unrelated values with the same name and type are the same implicit argument as far as the machinery is concerned, so a context that happens to have a -field called `name` satisfies a provider written for something else. In practice that is what makes the -mechanism so cheap; it is still worth knowing that nobody is checking your intent. +field called `name` satisfies a provider written for something else. In practice that looseness makes +the mechanism cheap; it is still worth knowing that nobody is checking your intent. -**The clone is real.** An owned argument copies the field on every call. Usually that is nothing, and on -a large value in a hot path it is not — declare a borrow. +**The clone is real.** An owned argument copies the field on every call. Usually that is nothing; on +a large value in a hot path it is not, so declare a borrow. ## Where to go next diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 7d2855ea..28ff0baf 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -7,7 +7,7 @@ sidebar_position: 0 This section explains the ideas behind CGP: why it is built the way it is, what each of its ideas actually does, and where the boundaries of each one lie. It is written to be read away from a -keyboard — there is nothing here to follow along with, and nothing to install first. +keyboard. There is nothing here to follow along with, and nothing to install first. It sits alongside the other two parts of the documentation. The [tutorials](/docs/tutorials/hello) teach by building something, so they show a construct at the moment it is needed and move on. The @@ -24,8 +24,8 @@ correct, what it costs in practice, and the move CGP makes to work around it wit the rule buys. Almost everything else here is downstream of it. **Read [Consumer and provider traits](./consumer-and-provider-traits.md) first if you want to know -how CGP works.** It covers the trait split at the centre of the design — one trait you call, another -you implement — and how a call finds its way from one to the other. +how CGP works.** It covers the trait split at the centre of the design, one trait you call and another +you implement, and how a call finds its way from one to the other. **Read [How much CGP to use](./modularity-hierarchy.md) first if you are deciding whether to adopt it.** It lays out the range from an ordinary Rust trait to fully wired components as a ladder, and diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index ede9d24b..7608297b 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -15,9 +15,9 @@ paying. ## Why the error type is the hard one -Every fallible function has to return *something*, and generic code has no business deciding what. A +Every fallible function has to return *something*, and generic code should not decide what. A provider parsing a port number does not know whether the application wants `anyhow::Error`, a domain -enum, or a plain string — and hard-coding any of them commits every caller in every application to that +enum, or a plain string, and hard-coding any of them commits every caller in every application to that choice. The usual answers each cost something. A concrete error type in a library is a decision imposed on @@ -26,11 +26,11 @@ signature along with its bounds, which is the leak [impl-side dependencies](./im describes. Converting by hand at each boundary is the boilerplate error-handling crates exist to remove, and it comes back the moment the boundary is generic. -What makes this tractable is noticing that "error handling" is not one decision but three, and that they -are independent: +This becomes tractable once you notice that "error handling" is not one decision but three, and that +they are independent: -- **what the error type is** — a type the context names; -- **how a foreign error becomes it** — `ParseIntError`, `io::Error`, a `String` from a domain rule; +- **what the error type is**: a type the context names; +- **how a foreign error becomes it**: `ParseIntError`, `io::Error`, or a `String` from a domain rule; - **what detail is attached** as it propagates. CGP makes each of the three a wiring choice, and the code that fails makes none of them. @@ -64,15 +64,15 @@ impl PortParser { `Error` is the context's [abstract type](./abstract-types.md), imported by `#[use_type]`. `Self::raise_error` turns a concrete failure into it, and the `#[uses]` line declares which failures -this provider raises — two of them, a parse error and a string — as requirements on the implementation, -not on the interface. A caller bounding on `CanParsePort` learns none of it. +this provider raises, two of them, a parse error and a string, as requirements on the implementation +rather than on the interface. A caller bounding on `CanParsePort` learns none of it. -`raise_error` is called on the *type* rather than on a value, because constructing an error is something -the context knows how to do rather than something a particular value does. +The provider calls `raise_error` on the *type* rather than on a value, because constructing an error is +something the context knows how to do rather than something a particular value does. ## Three sources, three strategies, one table -The context supplies the answers, and the second and third decisions are made per source error type: +The context supplies the answers, making the second and third decisions per source error type: ```rust delegate_components! { @@ -89,15 +89,15 @@ delegate_components! { ``` Three lines, three decisions. The error type is `String`. A raised `String` is converted straight -through with `From`. A `ParseIntError` is formatted with `Debug` into a `String` — and then handed back -to the context's own `String` route, which is what makes the two compose rather than each needing to -know the final type. +through with `From`. A `ParseIntError` is formatted with `Debug` into a `String`, then handed back +to the context's own `String` route, so the two compose rather than each needing to know the final +type. -That last point is what the per-source dispatch buys. A real application raises a dozen unrelated +The per-source dispatch buys exactly that last point. A real application raises a dozen unrelated failures, and most of them want the same treatment; naming a strategy per source type lets the -interesting ones differ without a match arm anywhere. CGP ships the strategies as ordinary providers — +interesting ones differ without a match arm anywhere. CGP ships the strategies as ordinary providers: `RaiseFrom` for a `From` conversion, `DebugError` and `DisplayError` for formatting, `ReturnError` when -the source already is the error type, `RaiseInfallible` for a step that cannot fail — and they stay +the source already is the error type, and `RaiseInfallible` for a step that cannot fail. They stay generic over whatever error type the context chose. ## Changing the answer changes nothing else @@ -122,7 +122,7 @@ delegate_components! { named `String`, so nothing in it referred to the thing that changed. Swapping `anyhow` for `eyre`, or a prototype's `String` for a real domain type, is this edit. -Concrete backends come as separate crates for the same reason — `cgp-error-anyhow` and its siblings each +Concrete backends come as separate crates for the same reason: `cgp-error-anyhow` and its siblings each supply a type-setting provider and the raisers that go with it, so the dependency on `anyhow` lives in the wiring rather than in any code that fails. @@ -147,28 +147,28 @@ Self::raise_http_error(ErrUnauthorized, "you must first login") ``` and knows neither the status number nor the error type. The two are decided in the table, in the same -place as everything else the application decides — which is the whole pattern, applied to a vocabulary +place as everything else the application decides. This is the whole pattern, applied to a vocabulary the built-in components know nothing about. ## What it costs **The imports are not in the prelude, deliberately.** `HasErrorType` and `CanRaiseError` are, but the wiring keys live under `cgp::core::error` and the strategy providers under `cgp::extra::error`. That is -a real papercut the first time, and it is the price of the error components not being forced on code +a real annoyance the first time, and it is the price of the error components not being forced on code that does not use them. **Three decisions means three ways to be under-wired.** A context can name an error type and forget a raiser for a source some provider raises, and it compiles until something raises one. -[`check_components!`](/docs/reference/macros/check_components) is what catches it, as with any other +[`check_components!`](/docs/reference/macros/check_components) catches it, as with any other wiring. -**The error type is one per context.** Everything in a context agreeing on one `Error` is what lets -errors compose without conversion; it also means a context genuinely needing two unrelated error types -needs two components or two contexts. +**The error type is one per context.** All the code in a context sharing one `Error` lets errors +compose without conversion; it also means a context genuinely needing two unrelated error types needs +two components or two contexts. **And it does not decide what a good error is.** CGP makes the type swappable and the construction routable. Whether your errors carry useful context, whether they are matchable, whether the messages -help — all of that is the same design problem it always was, and none of it is answered by wiring. +help: all of that is the same design problem it always was, and wiring answers none of it. ## Where to go next diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index 6585ee72..529cd9ca 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -15,7 +15,7 @@ it. If you are still deciding whether CGP is for you at all, this is the page to ## The rule of thumb -**Use CGP when a capability needs more than one implementation and the choice belongs to the context — not +**Use CGP when a capability needs more than one implementation and the choice belongs to the context, not before.** Almost everything follows from that. Most code has one implementation of most things, and for that code a @@ -32,9 +32,9 @@ Each row concedes where the alternative wins, because in most rows it does. | **A direct impl on the context** | A provider would have exactly one user. Two contexts that each have their own single implementation need no providers and no wiring at all. | A second context wants the *same* implementation, or the implementation should compose with a wrapper. | | **An enum** | The variant set is small, closed, and known, with fixed operations. A `match` is clearer than any machinery. | The variant set is open, or independent modules must each contribute one. | | **`dyn Trait`** | The set of implementations is not known until runtime. That openness is exactly what CGP gives up. | The set *is* known at build time, and you want the decoupling without the dispatch cost. | -| **A dependency-injection crate** | You specifically want a container's lifecycle and object-graph semantics. | You want compile-time-checked, reflection-free injection — which is the traits-and-generics approach, not a framework. | +| **A dependency-injection crate** | You specifically want a container's lifecycle and object-graph semantics. | You want compile-time-checked, reflection-free injection, which is the traits-and-generics approach, not a framework. | | **A generic-programming library such as `frunk`** | A one-off manipulation of a heterogeneous list. The lighter, focused library is less to learn and enough. | The structural machinery is part of a larger component-and-wiring design. | -| **A hand-rolled macro** | The generation is narrow and local. | You notice you are reinventing marker types plus a helper trait — which is CGP's own mechanism. | +| **A hand-rolled macro** | The generation is narrow and local. | You notice you are reinventing marker types plus a helper trait, which is CGP's own mechanism. | | **Waiting for a language feature** | A first-class facility would serve better and you can afford to wait. Rust's effects and reflection work is pursuing ground CGP covers. | You need the capability now, on stable Rust. CGP is complementary to what the language is building rather than a bet against it. | That last row is worth taking seriously rather than reading as a formality. Some of what CGP does is @@ -50,13 +50,13 @@ where `dyn Trait` and the dynamic languages remain right. **Exactly one implementation.** A capability with one definition belongs in a plain trait. If you want it to read like CGP anyway, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds it from a function with no -component, no provider, and no wiring — and it keeps working unchanged if a second implementation ever +component, no provider, and no wiring, and it keeps working unchanged if a second implementation ever arrives. **A small closed set of variants.** An enum and a `match` are clearer, faster to read, and free. -**One instance program-wide.** When a program genuinely wants a single globally consistent answer — one -`Ord` for a map key, where two orderings in one program would corrupt the map — per-context choice is the +**One instance program-wide.** When a program genuinely wants a single globally consistent answer, one +`Ord` for a map key where two orderings in one program would corrupt the map, per-context choice is the wrong shape. Coherent traits are safer, and this is the limit of CGP's central bargain. ## "I only have one application — what does this buy me?" @@ -72,7 +72,7 @@ cannot check. Three things do pay with one context. - **Overlapping implementations Rust rejects outright.** These multiply along the *target types* one - application touches, not along its contexts — so a single application with several types to encode, + application touches, not along its contexts, so a single application with several types to encode, serialize, or validate already has more than one implementation to place. That is [bypassing coherence](./coherence.md), and it needs no second context at all. - **The orphan-rule escape.** Adding a capability to a type from another crate needs one context and a @@ -92,16 +92,17 @@ bargain does not pay. Reach for `#[cgp_fn]` alone, or nothing. ## "Won't I end up with a context per configuration?" Partly justified, and the answer is composition rather than reassurance. Separating every axis really would -multiply — four independent binary choices would mean sixteen types. +multiply: four independent binary choices would mean sixteen types. CGP does not ask you to separate an axis you do not need separated, and it composes with the patterns that collapse one. A generic parameter on the context struct keeps a single type across several database engines. An enum keeps a single type for a choice made from configuration at runtime. A context holds either of those and wires its components normally. -What a real application lands on is separation for the axis where a wrong combination must be -**impossible** — a mock client must never reach production — and collapse for everything else. CGP decides -which variations are worth their own type; the tools you already use handle the ones that are not. +A real application lands on separation for the axis where a wrong combination must be +**impossible**, such as a mock client never reaching production, and collapse for everything else. CGP +decides which variations are worth their own type; the tools you already use handle the ones that are +not. There is a payoff here worth naming if you are writing a library. An enum you expose for supported backends is normally a ceiling on what downstream users can have: a new variant means a pull request or a fork. When @@ -111,12 +112,12 @@ defines its own wider enum and its own context and reuses everything, with nothi ## Which shape to reach for CGP's code comes in three shapes, and readers sometimes resist being taught three where they expected one. -They are not three levels of sophistication — each answers a different question, and two questions settle +They are not three levels of sophistication. Each answers a different question, and two questions settle which you are in. **Is the capability about the data, or about the application?** About the data means the wired type *is* the -thing being operated on — `Rectangle: CanCalculateArea`. About the application means the wired type is one -you define to carry choices, often with no fields at all. +thing being operated on, as in `Rectangle: CanCalculateArea`. About the application means the wired type is +one you define to carry choices, often with no fields at all. **Does it concern a type you do not own, which different applications must treat differently?** If so, that type moves out of `Self` and becomes a parameter. If not, targeting `Self` is enough. @@ -124,13 +125,13 @@ type moves out of `Self` and becomes a parameter. If not, targeting `Self` is en | Answers | The shape | What it gives you | |---|---|---| | About the data | **Retrofit** | Alternative implementations for an existing type, without changing its trait. One choice per type, program-wide. | -| About the application | **Application** | One choice per context you define — and you can define as many as you like. | +| About the application | **Application** | One choice per context you define, and you can define as many as you like. | | About a foreign type, differing per application | **Fully modular** | One choice per context *per target type*. | **The application shape is where most CGP code lives**, which is worth stating plainly so that the most -elaborate shape does not read as the intended destination. A capability about the application — send an -email, query a user, run the server — wired per application, with no type parameter anywhere, is the -ordinary case. +elaborate shape does not read as the intended destination. A capability about the application, such as +sending an email, querying a user, or running the server, wired per application with no type parameter +anywhere, is the ordinary case. ## How far to go inside CGP @@ -138,18 +139,18 @@ Deciding to use CGP is not the last decision. Its constructs form a progression, inside as outside: **stop at the lowest step that solves the problem in front of you.** Each step below is a response to something you have already hit, not a level to reach. -1. **A capability from a function.** [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) — one implementation, no +1. **A capability from a function.** [`#[cgp_fn]`](/docs/reference/macros/cgp_fn): one implementation, no component, no wiring. Most capabilities never need more, and starting here costs nothing later: the trait keeps its name and method, so promoting it leaves every call site untouched. 2. **A component.** [`#[cgp_component]`](/docs/reference/macros/cgp_component) with a provider and a - [wiring table](/docs/reference/macros/delegate_components) — when a second implementation is real, not + [wiring table](/docs/reference/macros/delegate_components), when a second implementation is real, not anticipated. Add [`check_components!`](/docs/reference/macros/check_components) at the same time; the wiring is checked lazily and an unchecked table is the main source of confusing errors. 3. **Per-type dispatch.** The [`open` statement](/docs/reference/macros/delegate_components), when one component needs a different provider per value of a type parameter. A type has moved out of `Self` into a parameter by this point, so it usually arrives with the fully-modular shape rather than before it. 4. **Providers composed from providers.** A provider that takes another provider as a parameter and builds - on it, declared with [`#[use_provider]`](/docs/reference/attributes/use_provider) — when one + on it, declared with [`#[use_provider]`](/docs/reference/attributes/use_provider), when one implementation should be expressed in terms of another rather than chosen alongside it. Genuinely useful, and the step most often taken too early: if nothing is being wrapped, there is nothing for it to do. @@ -160,7 +161,7 @@ response to something you have already hit, not a level to reach. **Steps 2 and 3 are where most CGP code sits.** Steps 4 and 5 answer scale and composition specifically, and reaching for either before the problem exists is how a CGP codebase ends up harder to read than the one it -replaced — the machinery is real either way, and only pays when something is actually being shared or +replaced. The machinery is real either way, and only pays when something is actually being shared or wrapped. ## What it costs @@ -181,11 +182,11 @@ better and actively improving, not solved.** not be cited. The honest reframing is that resolution costing at compile time is resolution that would otherwise cost at runtime or not be checked at all. -**There is a learning curve.** The first useful thing — a capability written as a function, used with no -wiring — needs only ordinary Rust knowledge, so the first step is small. The curve past it is real. +**There is a learning curve.** The first useful thing, a capability written as a function used with no +wiring, needs only ordinary Rust knowledge, so the first step is small. The curve past it is real. -Three of those costs — the learning curve, decoding the diagnostics, and the volume of wiring to write and -read — are mechanical work over a vocabulary that is written down, which is the kind of thing a coding +Three of those costs, the learning curve, decoding the diagnostics, and the volume of wiring to write and +read, are mechanical work over a vocabulary that is written down, which is the kind of thing a coding assistant handles well. CGP publishes an [agent skill](https://github.com/contextgeneric/cgp-skills) that teaches one that vocabulary, and a reader who already works with an assistant can attach it and judge for themselves within the hour. It makes those three costs **smaller, not absent**: the diagnostics are still @@ -202,7 +203,7 @@ implementation per type, and what CGP does about it. Read it if the question is built on, and closes with the same costs stated for that construct specifically. If the answer here was "not yet", [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the whole of what you -need — a capability from a function, no wiring, nothing to reverse later. If it was "yes", +need: a capability from a function, no wiring, nothing to reverse later. If it was "yes", the [Area calculation series](/docs/tutorials/area-calculation/) climbs the rungs in order, and [`#[cgp_component]`](/docs/reference/macros/cgp_component) is where the component machinery starts. diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index 3f441adf..ac651a74 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -28,11 +28,11 @@ pub fn increment(value: u8) -> Result { ``` Chaining two of these plainly does not even compile: the first produces a `Result` and the second -wants a `u8`. And forcing the types to line up would be worse than the type error, because the later +wants a `u8`. And forcing the types to match would be worse than the type error, because the later steps would run on a value they were never meant to see. `Result` is the familiar case, and the shape is more general than `Result`. Any output type carrying two -possibilities — one to carry on with, one to return immediately — has the same problem. +possibilities, one to carry on with and one to return immediately, has the same problem. ## What a monad supplies @@ -53,16 +53,16 @@ type. ## The three CGP ships -**The err monad** continues on `Ok` and short-circuits on `Err` — the `?`-style early return above, +**The err monad** continues on `Ok` and short-circuits on `Err`, the `?`-style early return above, where the first failure wins. It is the one most pipelines want. **The ok monad** is its mirror: it continues on `Err` and stops on `Ok`. That sounds backwards until you -want a chain of attempts where the first *success* ends it — a lookup tried against several sources, a +want a chain of attempts where the first *success* ends it: a lookup tried against several sources, a parser trying alternatives. **The identity monad** never short-circuits and threads every value forward, which recovers plain composition. It exists so that "no short-circuiting" is a choice you make rather than a different -combinator you reach for, and it is what a `Result`-producing chain almost never wants. +combinator you reach for, and a `Result`-producing chain almost never wants it. They also stack, so a pipeline over a nested `Result, F>` can short-circuit on the outer error while threading the inner result. @@ -80,8 +80,8 @@ delegate_components! { } ``` -The whole construction lives in types — the monad is a zero-sized marker, the handler list is a -type-level list, and the pipeline carries no runtime value — so the only branching at run time is the +The whole construction lives in types: the monad is a zero-sized marker, the handler list is a +type-level list, and the pipeline carries no runtime value, so the only branching at run time is the branching the logic actually asked for. ## What it costs @@ -92,7 +92,7 @@ word that will cost you a reader, and a piece of CGP writing is usually better o behaviour than naming it. **A `?` in a function body is simpler, and usually right.** This pays when the *steps are chosen by -wiring* — when different contexts run different chains, or the chain is assembled from parts that do not +wiring*: when different contexts run different chains, or the chain is assembled from parts that do not know each other. When the steps are fixed, write a function and use `?`. **The type errors are among CGP's worst.** A stage whose output does not match the next stage's input @@ -110,11 +110,11 @@ looked like it came from nowhere. [Dispatching](./dispatching.md) is the other b matching an enum variant is a chain of attempts where the first success ends it. For the constructs, [monad providers](/docs/reference/providers/monad_providers) carries `PipeMonadic`, -the three markers, and the per-step `BindOk` / `BindErr` forms, and -the four monad traits — [`MonadicBind`](/docs/reference/traits/monadic_bind), +the three markers, and the per-step `BindOk` / `BindErr` forms. The four monad traits are the layer +defining what a monad is here: [`MonadicBind`](/docs/reference/traits/monadic_bind), [`ContainsValue`](/docs/reference/traits/contains_value), [`LiftValue`](/docs/reference/traits/lift_value), and -[`MonadicTrans`](/docs/reference/traits/monadic_trans) — are the layer defining what a monad is here. +[`MonadicTrans`](/docs/reference/traits/monadic_trans). --- diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index 7d5f87f8..c0878302 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -10,7 +10,7 @@ components grows. This page answers *how does wiring stay readable once there is a lot of it?* It shows what a table looks like when it has outgrown its usefulness, the routing that fixes it, and the one rule that -decides how a namespace has to be designed — a rule most people discover from a compiler error. It +decides how a namespace has to be designed, a rule most people discover from a compiler error. It closes on when the lighter alternative is the better buy. ## When a table stops being readable @@ -37,8 +37,8 @@ delegate_components! { ``` Two entries out of three are duplicated, and nothing records that they are meant to stay the same. -Scale that to the thirty components a real application accumulates and the interesting difference — -one line — is buried in twenty-nine identical ones, which is the opposite of what the table was for. +Scale that to the thirty components a real application accumulates and the interesting difference, one +line, is buried in twenty-nine identical ones, which is the opposite of what the table was for. A **namespace** is a table lifted out of any one context and given a name, so that contexts can share it. @@ -74,15 +74,15 @@ delegate_components! { ``` The `namespace` line makes everything `App` does not wire itself fall through to `AppNamespace`. -Routing through paths rather than flat keys is also what lets a whole group be redirected at once and -what makes inheritance possible, since a path has structure a name does not. +Routing through paths rather than flat keys also lets a whole group be redirected at once and makes +inheritance possible, since a path has structure a name does not. -On its own this is more machinery for the same result. What it buys arrives next. +On its own this is more machinery for the same result. The payoff arrives next. ## Binding what is shared, leaving open what varies -A namespace can also **bind** a path — supply the provider itself, rather than routing to it. That is -what turns it into a set of defaults: +A namespace can also **bind** a path, supplying the provider itself rather than routing to it. This +turns it into a set of defaults: ```rust cgp_namespace! { @@ -110,7 +110,7 @@ Here is the rule, and it is worth learning from this page rather than from the e **once a namespace binds a key, no one downstream can rebind it. Only a path the namespace leaves open is available to a context.** -The natural thing to reach for — "the namespace sets this, I want something different" — does not +The natural thing to reach for, "the namespace sets this, I want something different", does not compile: ```rust @@ -138,7 +138,7 @@ the specific one to win. So a namespace is designed around the question *what varies?*, and this is the practical shape: **bind what every context agrees on, and leave open what any context might need to differ on.** Where a -key varies, do not bind it in the shared namespace at all — inherit and bind it per configuration +key varies, do not bind it in the shared namespace at all. Inherit and bind it per configuration instead: ```rust @@ -151,8 +151,8 @@ naming which configuration it is. ## Namespaces are how CGP does presets -There is no separate preset construct, and no `cgp_preset!` to look for. A preset — a curated bundle of -defaults you adopt and then adjust — is exactly the inherit-and-adjust behaviour above, so a namespace +There is no separate preset construct, and no `cgp_preset!` to look for. A preset, a curated bundle of +defaults you adopt and then adjust, is exactly the inherit-and-adjust behaviour above, so a namespace *is* one. The same machinery serves a much smaller case. Dispatching a single component per type, with the @@ -169,29 +169,29 @@ delegate_components! { ``` `open` roots a route at the bare component name and puts the per-type entries in the context's own -table, with no shared namespace involved. It is the lightweight end of the same mechanism, and it is -what most code uses — which is why [bypassing coherence](./coherence.md) and +table, with no shared namespace involved. It is the lightweight end of the same mechanism, and most +code uses it, which is why [bypassing coherence](./coherence.md) and [dispatching](./dispatching.md) can use it without mentioning namespaces at all. The two do not combine for the same component: once a component is registered behind a namespace -prefix, `open` would root the route at the wrong place, and the full prefixed path is what reaches its +prefix, `open` would root the route at the wrong place, and only the full prefixed path reaches its entries. ## What it costs **The design decision comes first, and it is hard to revise.** Which keys a namespace binds and which -it leaves open is fixed by the rule above, and changing your mind means changing the namespace — which +it leaves open is fixed by the rule above, and changing your mind means changing the namespace, which reaches every context that joined it. A bundle of wiring is easier to get wrong here than anywhere else in CGP, because the mistake is not visible until a context wants to differ. **It is another hop, and a less obvious one.** With an [aggregate provider](./aggregate-providers.md) the context says which components come from the bundle. -With a namespace it says nothing — everything not wired locally falls through — so answering "where -does this capability come from?" means knowing the namespace and its parents. +With a namespace it says nothing, since everything not wired locally falls through, so answering +"where does this capability come from?" means knowing the namespace and its parents. **Paths are a second vocabulary.** `@app.GreeterComponent` is a type-level path, and it appears in -error messages spelled out at length. The toolchain resugars it for the classes it recognizes; the raw -form is still what a plain `cargo check` shows. +error messages spelled out at length. The toolchain resugars it for the classes it recognizes; a plain +`cargo check` still shows the raw form. **And it pays only at scale.** For three components shared by two contexts, the duplication at the top of this page is fine and a namespace is not worth its cost. The threshold is a table that has outgrown diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index d4be05ea..9995ae23 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -9,7 +9,7 @@ Restoring the guarantee an async trait method drops, so the future it returns ca multi-threaded runtime. This page answers *why will my async CGP handler not spawn?* It is short, and it is about a gap in -stable Rust rather than about CGP — CGP just meets it sooner than most code does. It explains where the +stable Rust rather than about CGP. CGP just meets it sooner than most code does. It explains where the guarantee goes, the bound that would fix it and does not exist yet, and the workaround. It closes on what that workaround costs, which is repetition. @@ -28,7 +28,7 @@ pub trait CanHandleApi { } ``` -That rewrite is faithful and costs nothing — no boxing, no allocation. It also drops every auto-trait +That rewrite is faithful and costs nothing: no boxing and no allocation. It also drops every auto-trait bound. The returned future is `Send` when the concrete future the body produces happens to be, and a caller working through the trait has no way to *require* it. @@ -37,8 +37,8 @@ not see the concrete type, and the future's `Send`-ness is part of what is hidde ## Why that matters, and what you cannot write -It matters the moment the future is spawned. A work-stealing runtime — the default Tokio runtime an Axum -server runs on — may move a task between threads while it is suspended, so every future it drives must +It matters the moment the future is spawned. A work-stealing runtime, the default Tokio runtime an Axum +server runs on, may move a task between threads while it is suspended, so every future it drives must be `Send`. A generic handler awaiting `handle_api` produces a task that is `Send` only if that future is. @@ -56,7 +56,7 @@ where } ``` -Return Type Notation — `handle_api(..): Send` — says exactly the right thing: whatever arguments the +Return Type Notation, `handle_api(..): Send`, says exactly the right thing: whatever arguments the method is called with, its future is `Send`. It is not stabilized, so this cannot be written in production code today. @@ -90,11 +90,11 @@ where ## Why the implementation cannot be generic The obvious next step is one blanket implementation covering every context that already handles the API. -It does not compile, and the reason is worth following, because it is the same gap wearing a disguise. +It does not compile, and the reason is worth following, because it is the same gap in another form. Such an impl would wrap `self.handle_api(..)` in an `async` block, and that block is `Send` only if the future it awaits is. For a generic `App` and `Api` the awaited future is an opaque `impl Future` whose -auto-traits are unknown — so the impl cannot prove its own `+ Send` return type. A generic blanket impl +auto-traits are unknown, so the impl cannot prove its own `+ Send` return type. A generic blanket impl *is* Return Type Notation, and it is blocked for the same reason. Dropping to a concrete context and a concrete API closes it: @@ -108,8 +108,9 @@ impl CanHandleApiSend for MockApp { ``` Now `Self` is a fixed type and `Api` is a fixed marker, so the call resolves through the wiring to a -concrete provider producing a concrete future — and the compiler computes that future's auto-traits and -finds it `Send`. No annotation is needed, because `Send` is inferred structurally for a known type. +concrete provider producing a concrete future, and the compiler computes that future's auto-traits and +finds it `Send`. No annotation is needed, because the compiler infers `Send` structurally for a known +type. Each of these impls is mechanical: forward, and await. Each is also a *proof*, accepted only because at this instantiation the future really is `Send`. @@ -120,8 +121,9 @@ this instantiation the future really is `Send`. where RTN would have allowed a single generic impl, this needs one for every pair. A service with eight endpoints and two contexts writes sixteen forwarding bodies. -**It is boilerplate that cannot be abstracted away**, since abstracting it is what does not compile. A -macro could generate it, and the impls would still be there. +**It is boilerplate that cannot be abstracted away.** The abstraction that would remove it is the +generic blanket impl, and that does not compile. A macro could generate the impls, but they would still +be there. **And it is a second trait to keep in step.** Adding a method to the capability means adding it here too, and nothing enforces that the two stay aligned beyond the supertrait. @@ -133,7 +135,7 @@ workaround with a known expiry, not a design. [Handlers](./handlers.md) is the family whose futures most often need this, since it is where CGP's async I/O lives. [Consumer and provider traits](./consumer-and-provider-traits.md) explains the wiring -the concrete impl forwards through, which is what makes the resolved future a concrete, checkable type. +the concrete impl forwards through, which turns the resolved future into a concrete, checkable type. For the constructs, [`#[async_trait]`](/docs/reference/macros/async_trait) is the rewrite that drops the bound, and its own page records the same gap from the macro's side. diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index ff401a95..1f07bf93 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -11,7 +11,7 @@ left at runtime. This page answers *what happens when the `Code` tag carries a whole program?* It is the furthest thing CGP's pieces are put to, and it assumes [handlers](./handlers.md). It shows a small language built from types, why separating its syntax from its meaning is the point, and how a third party extends it. It -closes on the boundary — the programs this cannot express. +closes on the boundary: the programs this cannot express. ## A program that is a type @@ -33,7 +33,7 @@ program: type Program = Multiply, Literal<3>>, Literal<4>>; ``` -That is `(2 + 3) * 4` as a type. It is the language's **abstract syntax**, and — this is the whole idea — +That is `(2 + 3) * 4` as a type. It is the language's **abstract syntax**, and this is the whole idea: it says nothing at all about what any of it means. For a real language the fragments carry more: a @@ -59,9 +59,10 @@ where } ``` -`EvalAdd` interprets *any* addition, whatever its operands, and it evaluates them by asking the context -— which is what makes the recursion work and what keeps the provider from knowing the rest of the -language. Its requirements say only "the context can evaluate my operands". +`EvalAdd` interprets *any* addition, whatever its operands, and it evaluates them by asking the context. +Asking the context, rather than evaluating the operands itself, both drives the recursion and keeps the +provider from knowing the rest of the language. Its requirements say only "the context can evaluate my +operands". The context then assembles the language, one row per fragment: @@ -83,24 +84,24 @@ And running a program is one call: Interpreter.compute(PhantomData::, ()) // 20 ``` -Because the keys are types with structure, a single row captures a whole family of programs — every +Because the keys are types with structure, a single row captures a whole family of programs, every `Add<_, _>` there will ever be. A value-level lookup table cannot do that. ## What the separation buys There is no parser, no syntax tree walked at run time, and no dispatch loop. **Type checking the call is the interpretation**: the compiler resolves the wiring recursively through the program's structure, -and what is left in the binary is the arithmetic. +and only the arithmetic is left in the binary. The more interesting consequence is that syntax and meaning vary independently. **One program, several meanings.** A second context wiring the same fragments to different providers -interprets the same program differently — evaluate it, pretty-print it, cost it, run it against a test +interprets the same program differently: evaluate it, pretty-print it, cost it, or run it against a test double. Nothing in the program changes, because the program never said what it meant. **One meaning, extended syntax.** A crate that does not own the language defines a new fragment and a provider for it, and a context that wants both wires both. The base language is not patched, forked, or -even recompiled — the extension is a row. That is the [expression problem](./extensible-variants.md) +even recompiled. The extension is a row. That is the [expression problem](./extensible-variants.md) answered on the syntax side, and it is why a DSL built this way can have third-party dialects. At scale the rows themselves become a [namespace](./namespaces.md), so a context joins a language rather @@ -119,20 +120,20 @@ the interpreters. ## What it costs **The program must be known at compile time.** This is the boundary, and it is absolute. A script read -from a file, a pipeline configured at startup, a user-supplied expression — none of them can be a type. +from a file, a pipeline configured at startup, or a user-supplied expression cannot be a type. If programs arrive at run time you need a runtime interpreter, and this technique is not one. **The diagnostics are the worst CGP produces.** A malformed program is a trait-resolution failure over a deeply nested type, reported in terms of the whole program rather than the fragment at fault. Checks localize it and the toolchain reshapes what it recognizes; a badly nested program is still hard reading. -**Compile times feel it.** Every fragment of every program is resolution work, and a large program +**Compile times go up.** Every fragment of every program is resolution work, and a large program instantiated several ways is where CGP's compile-time cost is most visible. **And it is the most advanced thing here.** Everything else in this section is worth reaching for -routinely. This is worth reaching for when a language is genuinely the right shape for a problem — -build pipelines, protocol descriptions, shell-like scripting — and when the programs are fixed when the -binary is. +routinely. This is worth reaching for when a language is genuinely the right shape for a problem, such +as build pipelines, protocol descriptions, or shell-like scripting, and when the programs are fixed when +the binary is. ## Where to go next From 253c2f4962ac197254ecabc2fbaaffae6c0c4318 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 22 Aug 2026 23:18:17 +0200 Subject: [PATCH 040/516] Make Concepts pages easier for a first-time reader Restructure the coherence page down to the basic tier, guided by the RustLab 2025 talk: it now explains the provider-trait move and simple per-type wiring, and defers parameter-targeted components, per-value dispatch, and application contexts to the modularity-hierarchy page. Ground the transitive-resolution point in a concrete Pair example. Across the section, add first-use glosses for prerequisite terms (associated type, blanket implementation), add a beginner on-ramp to the index pointing at the tutorials, and revise remaining pseudo-clefts and indirect phrasings into direct statements. Prose only; code blocks unchanged. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_017iMYCYgoVv6h1YL58q4XVp --- docs/concepts/abstract-types.md | 6 +- docs/concepts/aggregate-providers.md | 2 +- docs/concepts/coherence.md | 268 ++++++------------ docs/concepts/consumer-and-provider-traits.md | 2 +- docs/concepts/dispatching.md | 2 +- docs/concepts/handlers.md | 2 +- docs/concepts/higher-order-providers.md | 2 +- docs/concepts/index.md | 5 + docs/concepts/modularity-hierarchy.md | 2 +- 9 files changed, 103 insertions(+), 188 deletions(-) diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index d9b44e84..f3748dce 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -15,8 +15,8 @@ the costs, which are mostly about what an abstract type is *not*. ## Rust already has this -An abstract type in CGP is an ordinary associated type, and it is worth starting there because it means -half of what follows is a feature you already use: +An abstract type in CGP is an ordinary associated type: a type a trait names but leaves each implementer +to fill in. It is worth starting there, because half of what follows is a feature you already use: ```rust pub trait HasScalarType { @@ -106,7 +106,7 @@ shape at once. The application here is a type standing for the program rather th The `#[use_type(HasScalarType.Scalar)]` line lets the signature say `Scalar` instead of `::Scalar`. It imports the type and adds the requirement in one line, and it -reads like a `use` for a type because that is what it is. +reads like a `use` for a type because it is one. ## The canonical one: a context's error type diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index 9e5d696c..dd1cc22a 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -127,7 +127,7 @@ context spells out which components come from where. That is direct, obvious to linearly: twenty components from a bundle means twenty names in the brackets. A context adopts a namespace by **joining it**, after which everything it does not wire itself falls -through, and a direct entry overrides just that key. That is what you want once the count is large or +through, and a direct entry overrides just that key. You want that once the count is large or the defaults should be inherited and selectively replaced. Reach for a bundle when the group is small and you want the delegation visible. Reach for a namespace diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index ab1b742a..c6c94232 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -6,12 +6,12 @@ sidebar_position: 1 # Bypassing coherence Rust allows one implementation of a trait per type. Why that rule exists, what it costs, and how CGP -writes many implementations and lets each context pick the one it wants. +writes many implementations and lets each type pick the one it wants. This page answers *why can't Rust do this already?* It builds up what the trait system gives you, shows what that costs when you want two implementations of one thing, and works through the move CGP makes, which is smaller than it first appears and does not discard the rule. It closes on what that move costs in -turn. It is a long page, and it is the one everything else in this section is downstream of. +turn. It is the page everything else in this section is downstream of. ## The trait system is already a dependency-injection mechanism @@ -27,14 +27,28 @@ pub fn describe(value: &T) -> String { } ``` -Nobody passes `Display` in. The caller writes `describe(&42)` and the compiler goes looking for -`impl Display for i32`, finds it, and wires it up. That is dependency injection, done by the type system -at compile time, and it is so ordinary in Rust that it rarely gets called that. +There is no need to pass `Display` when `describe` is called. The caller writes `describe(&42)`, and the +compiler goes looking for `impl Display for i32`, finds it, and wires it up. That is dependency injection, +done by the type system at compile time, and it is so ordinary in Rust that Rust programmers rarely call +it that. -The part worth noticing is that it works **transitively**. If `describe` calls something that itself -needs a bound, and that needs another, the compiler resolves the whole chain without a single caller -naming any of it. You can add a requirement four layers deep and callers four layers up are unaffected. -That property makes Rust's generics composable rather than a bookkeeping exercise. +It is worth noticing that the compiler resolves the `T: Display` bound **transitively**. Suppose a pair +implements `Display` whenever both of its components do: + +```rust +struct Pair(A, B); + +impl Display for Pair { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "({}, {})", self.0, self.1) + } +} +``` + +Now `describe(&Pair("foo", 42u32))` asks the compiler for `Pair<&str, u32>: Display`, and to satisfy that +it resolves `&str: Display` and `u32: Display` in turn, without the caller naming either. The chain runs +as deep as the types do: add a requirement four layers down, and callers four layers up are unaffected. +That reach makes Rust's generics composable rather than a bookkeeping exercise. ## That only works because every lookup finds the same answer @@ -47,7 +61,8 @@ irreconcilable answers. **Coherence is the property that guarantees this**, and Rust enforces it with two rules. The **overlap rule** forbids two implementations that could both apply to the same type. Given a trait you -own and two blanket implementations, the compiler rejects the second: +own and two blanket implementations (each a single `impl` written once for every type that meets a bound), +the compiler rejects the second: ```rust pub trait CanEncode { @@ -65,8 +80,8 @@ impl> CanEncode for T { } ``` -`String` satisfies both bounds, so the compiler would have no principled way to choose. And "pick -whichever is in scope" is exactly the incoherence the rule exists to prevent. +`String` satisfies both bounds, so the compiler would have no principled way to choose. The rule exists +precisely to prevent the alternative: silently picking whichever implementation happens to be in scope. The **orphan rule** forbids implementing a trait for a type unless your crate owns one of the two. Neither `Display` nor `Vec` is yours, so this is rejected: @@ -83,7 +98,7 @@ Without it, two unrelated crates could each add their own `Display for Vec`, depending on both would be unbuildable, with neither crate at fault. **Both rules are correct.** They are not conservatism or an unfinished corner of the language; they are -what you pay for transitive resolution, and the trade is a good one. Any account of CGP that opens by +the price of transitive resolution, and the trade is a good one. Any account of CGP that opens by calling coherence a limitation has the argument backwards. ## What the guarantee costs @@ -99,205 +114,100 @@ The orphan rule costs you **reach**. A crate that wants to add a capability to a wrap it in a newtype and re-expose everything it still needs, which is boilerplate with no upside and a type your callers now have to know about. -These are felt sharply enough that Rust developers build their own escape. The pattern is to stop -implementing the trait for the interesting type and implement it for a marker type you own instead, with a -helper trait tying the two together: three or four extra lines of plumbing, arrived at and written up -independently by a Rust developer working around the overlap rule. **If you have written that, you have -written CGP's central mechanism by hand**, and the rest of this page is about what it looks like made +These pains are sharp enough that Rust developers work around them by hand, and at least one has +arrived independently at the pattern CGP is built on. The next section shows how CGP makes that pattern first-class. ## The move: make `Self` a type you own -CGP's first move is to take the type coherence ranges over, the `Self` of the implementation, and make -it something the implementing crate always owns. - -One trait definition becomes two. The **consumer trait** is the caller's view, keeping the ordinary `self` -receiver so that calling the capability is still a method call. The **provider trait** is the same -interface with `Self` moved out into an explicit parameter, and an implementation targets a small named -type of its own: +CGP's move is to split the trait in two and change what `Self` means on the side that implements it. One +definition becomes two traits. The **consumer trait** is the caller's view, `CanEncode` unchanged, so +`value.encode()` stays a method call. The **provider trait** carries the same method with the former +`Self` moved into a parameter, and each implementation targets a small type it declares for itself: ```rust #[cgp_component(Encoder)] -pub trait CanEncodeValue { - fn encode(&self, value: &Value) -> Vec; -} - -#[cgp_impl(new EncodeAsText)] -impl Encoder -where - Value: Display, -{ - fn encode(&self, value: &Value) -> Vec { value.to_string().into_bytes() } -} - -#[cgp_impl(new EncodeAsHex)] -impl Encoder -where - Value: AsRef<[u8]>, -{ - fn encode(&self, value: &Value) -> Vec { /* hex-encode the bytes */ } +pub trait CanEncode { + fn encode(&self) -> Vec; } ``` -**Both compile.** They carry the same two overlapping bounds the compiler rejected a moment ago: -`Display` and `AsRef<[u8]>`, still overlapping on `String`. There is no conflict, because each one's -`Self` is now a different type (`EncodeAsText`, `EncodeAsHex`) that this crate declared for the purpose. -Any number more would also compile. The orphan rule does not enter either, since that `Self` is always -local, which is how a crate adds a capability to a type it did not define. - -Neither rule was repealed. The implementations simply stopped being the kind of thing the rules are -about. [Consumer and provider traits](./consumer-and-provider-traits.md) works through the mechanics of -the split and how a call finds its way across it. - -One other thing changed in that listing, and it is worth naming rather than leaving you to spot it: the -value being encoded moved out of `Self` and into a `Value` parameter, so the trait is now -`CanEncodeValue` rather than `CanEncode`. That is a second move, not part of the first, and it -leaves `Self` free to be something other than the data. The next two sections cover what it is free to -be, and why that matters more than the parameter. - -## Coherence comes back, one context at a time - -Making implementations incoherent would be useless if it also made *use* incoherent. A caller still needs -`app.encode(&value)` to mean one definite thing. - -So the second move reintroduces coherence at a smaller scale. Instead of one global choice per trait, each -**context**, a type you define to stand for one set of choices, names exactly one implementation in a -small table: +`#[cgp_component]` generates the provider trait `Encoder` from that one definition, where the +type being encoded is now the `Context` parameter. Each implementation targets a dummy struct of its own, +so the two implementations that clashed a moment ago can both be written: ```rust -delegate_components! { - ApiServer { - open EncoderComponent; - @EncoderComponent.String: EncodeAsText, - } +#[cgp_impl(new EncodeAsText)] +#[uses(Display)] +impl Encoder { + fn encode(&self) -> Vec { self.to_string().into_bytes() } } -delegate_components! { - Firmware { - open EncoderComponent; - @EncoderComponent.String: EncodeAsHex, - } +#[cgp_impl(new EncodeAsHex)] +#[uses(AsRef<[u8]>)] +impl Encoder { + fn encode(&self) -> Vec { /* hex-encode self.as_ref() */ } } ``` -`ApiServer` encodes a `String` as its text and `Firmware` as hexadecimal: - -```text -ApiServer: hi -Firmware: 6869 -``` - -Within either context the choice is unambiguous, so resolution is coherent; between them it differs, with -no conflict, because the lookup is keyed on the context. Incoherence is only wanted when you are *writing* -implementations. When you use them, you want many independent local scopes, each internally consistent. - -**Coherence is not repealed; it is scoped.** That line is the whole page in a sentence. - -## Where the freedom actually comes from +**Both compile.** `EncodeAsText` and `EncodeAsHex` are different `Self` types, so the two impls no longer +overlap, however many bounds they share, and any number more would compile too. The orphan rule does not +enter either, because that `Self` is always a struct this crate declared, which is how a crate adds a +capability to a type it did not define. Coherence only ever looked at `Self`, and `Self` is now a local +dummy struct, so there is nothing left for the rules to reject. -Here is the part most easily misread, and it is worth slowing down for: **the escape happens when `Self` -becomes a type you own, not when a parameter appears.** +`#[cgp_impl]` lets a provider keep the consumer trait's `self` receiver, so inside `EncodeAsText` the +`self` is the value being encoded, and `#[uses(Display)]` records that this provider needs that value to +be `Display`. Neither rule was repealed; the implementations simply stopped being the kind of thing the +rules are about. [Consumer and provider traits](./consumer-and-provider-traits.md) works through the two +halves and how a call crosses between them. -A scope is one context type, so the number of independent choices a program can make is the number of -context types it can define. Wire a capability onto `String`, which is data and not yours, and you get -exactly one answer for the whole program, because there is one `String`. Coherence was narrowed, not -removed. Wire it onto `ApiServer` and `Firmware`, types you declared, and you get as many answers as -you care to declare types. +## Coherence comes back, one type at a time -Which is why the two contexts above are `ApiServer` and `Firmware` rather than `String` wired twice. The -second is impossible; the first is the point. +Making the implementations incoherent would be no use if it also made *using* them incoherent. A caller +still needs `value.encode()` to mean one definite thing. -### The shape this depends on - -That leaves one thing to build, because it is a shape vanilla Rust gives you no reason to have imagined: -**a type whose whole job is to stand for an application.** - -Start from the fact that it is perfectly ordinary Rust. It is the arrangement from two sections ago with -the CGP taken back out: two application types, one value type, two encodings, and nothing exotic. +So the second half brings coherence back at a smaller scale. A type chooses one provider for the +component, in a small wiring table: ```rust -pub trait CanEncodeValue { - fn encode(&self, value: &Value) -> Vec; -} - -pub struct ApiServer; -pub struct Firmware; - -impl CanEncodeValue for ApiServer { - fn encode(&self, value: &String) -> Vec { /* as text */ } -} - -impl CanEncodeValue for Firmware { - fn encode(&self, value: &String) -> Vec { /* as hexadecimal */ } -} +delegate_components! { String { EncoderComponent: EncodeAsText } } +delegate_components! { Vec { EncoderComponent: EncodeAsHex } } ``` -This compiles, and it already does something useful: per-application encoding of the same type. Note that -both structs have **no fields at all**. `struct ApiServer;` is a complete and legitimate type here, -because its entire purpose is to be a name the implementations attach to. An empty struct with traits on it -is otherwise close to unreadable, which is why it is worth saying outright. - -Now try to make it scale. Add a third value type, then a fourth, and you are hand-writing a body per -`(application, type)` pair. So you factor the shared logic into a blanket implementation, and the overlap -rule rejects it: - -```rust -impl CanEncodeValue for ApiServer { /* ... */ } - -// error[E0119]: conflicting implementations of trait `CanEncodeValue<_>` -// for type `ApiServer` -impl> CanEncodeValue for ApiServer { /* ... */ } -``` +Now `String` implements `CanEncode` through `EncodeAsText` and `Vec` through `EncodeAsHex`, so a +`value.encode()` call resolves to the provider its type named. The two providers still overlap freely, yet +no call is ambiguous, because each type records its own choice. -**So the shape is available and unrewarding.** It works, and nothing can be shared, so it stops paying off -at three types and nobody keeps it as a familiar technique. That is why "application context" usually -reads as an unfamiliar noun rather than a familiar arrangement: readers have not built it, because until -now there was no reason to. +That is the whole trade. **You want incoherence while writing implementations, and coherence while using +them.** While writing them, overlapping providers coexist with no global conflict. While using them, each +type names exactly one, and resolution is unambiguous. -This is the strongest form of the payoff, and it is worth stating precisely. **Coherence does not forbid -this shape; it makes it not worth building.** CGP's contribution is therefore constructive rather than -permissive: it does not merely escape a rule, it makes an available shape worth using. Named providers -replace the hand-written bodies, and a per-pair decision becomes a line in a table. +**Coherence is not repealed; it is scoped.** That line is the whole page in a sentence. -### Naming the two shapes +How far the idea scales is a separate question. Here each type picks one provider, which is the simplest +shape. A type you define to stand for your own application can pick its own providers, and the same +capability can even resolve differently for the same data in two applications. Those are higher rungs of +the same ladder, worked out in [How much CGP to use](./modularity-hierarchy.md). -Two distinctions have been at work above. Naming them keeps "context" from becoming a word you cannot pin -down, and this is where readers most often lose track. +## What it costs -The first crossing had no signal at all. In the `CanEncode` listing further up, the wired type was **the -data**: `impl CanEncode for T` puts the thing being encoded in `Self`, exactly as `impl Display for String` -does, and that is the shape essentially every Rust trait is in. From *The move* onward the wired type has -been `ApiServer` or `Firmware`, types you define, holding no data and existing to carry choices. No -signature announced the change and no parameter marked it, yet `Self` stopped being data. The vocabulary -is a **value context** for the first and an **environmental context** for the second, and this is the -crossing that escapes coherence: you can define as many application types as you like, and there is only -one `String`. +**It is more machinery than one trait.** A component is two traits, a marker type, and a wiring line per +type that uses it. For a capability with a single implementation that is pure overhead, and a plain trait +is the right tool. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the CGP construct for that case, and it +needs no wiring at all. -The second crossing is visible in the code. A capability about `Self` is **self-targeted**, like -`CanEncode` as first written here. Moving the value into a parameter makes it **parameter-targeted**: -`CanEncodeValue` is about the `Value`, and `Self` only decides for it. An environmental context can -already choose for itself without that parameter; the parameter adds the ability to choose for a type you -*do not own*. +**A wired choice is local, not global.** This is a real limit rather than a technicality. When a program +genuinely needs one answer program-wide, per-type choice is the wrong shape and a coherent trait is safer. +Consider a single consistent `Ord` for a map key, where two orderings in one program would corrupt the +map. CGP does not make coherence optional; it moves where the single answer is decided. -## What it costs +**The choice is explicit, which is both the point and a cost.** Nothing is inferred. A type that has not +named a provider does not get a default, and adding a capability means adding a line. That is the property +the whole design rests on, and it is also more to write and read than a trait with one implementation. -**It is more machinery than one trait.** A component is two traits, a marker type, and a wiring line per -context. For a capability with one implementation that is pure overhead, and a plain trait is the right -tool. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the CGP construct for that case, and it needs no -wiring at all. - -**Uniqueness is per context, not global.** This is a real limit rather than a technicality. When a program -genuinely needs one answer program-wide, per-context choice is the wrong shape and a coherent trait is -safer. Consider a single consistent `Ord` for a map key, where two orderings in one program would corrupt -the map. CGP does not make coherence optional; it moves where the single answer is decided. - -**The choice is explicit, which is both the point and a cost.** Nothing is inferred. A context that has -not named a provider does not get a default, and adding a capability means adding a line. That is the -property the whole design rests on, and it is also more to write and read than a trait with one -implementation. - -**Wiring is checked lazily.** A table naming a provider whose requirements the context cannot meet still -compiles; the failure appears later, where the capability is used, and can be long. +**Wiring is checked lazily.** A table naming a provider whose requirements the wired type cannot meet +still compiles; the failure appears later, where the capability is used, and can be long. [`check_components!`](/docs/reference/macros/check_components) forces it to the wiring line and names the actual missing requirement, and [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) leads with the root cause for the classes diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index 9ddc637a..679b9e61 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -123,7 +123,7 @@ method runs. Two pieces connect the halves: a table on the context that names its choice, and a pair of generated implementations that follow it. -The table is what a context writes. It maps each **component**, one capability defined once that +A context writes the table. It maps each **component**, one capability defined once that implementations can be wired for, to the provider that should supply it, and it is the one place a choice is recorded: diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index e6b84984..db59eb37 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -90,7 +90,7 @@ pub trait CanDescribe { Implement `CanDescribe` for `Circle` and for `Rectangle`, and any enum whose variants all implement it gets it too: `shape.describe()` works with no wiring, no combinator named, and no `match`. It is the -form to reach for first, and the rest of this page is what it is doing underneath. +form to reach for first, and the rest of this page shows what it does underneath. ## What it costs diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index b3afef44..d3f82594 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -158,7 +158,7 @@ one that still reads its inputs from a context. [Monadic handlers](./monadic-handlers.md) is the next thing a pipeline needs: what happens when a stage produces a result the chain should stop on. [Dispatching](./dispatching.md) is the family applied to the -shape of a record or an enum, and [Type-level DSLs](./type-level-dsls.md) is what it becomes when the +shape of a record or an enum, and the family becomes a [type-level DSL](./type-level-dsls.md) when the `Code` tag carries a whole program. [Higher-order providers](./higher-order-providers.md) is the mechanism the combinators are built from, diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index 8a4e2ab5..25d9d31c 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -43,7 +43,7 @@ delegate_components! { ScaledCircle { AreaCalculatorComponent: ScaledArea`, and the attribute that fills it in diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 28ff0baf..a3efe4c9 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -31,6 +31,11 @@ you implement, and how a call finds its way from one to the other. it.** It lays out the range from an ordinary Rust trait to fully wired components as a ladder, and argues for climbing no higher than a problem requires. +**New to Rust's traits and generics?** These pages explain the reasoning behind CGP and assume you are +comfortable with traits and generic bounds. If you are not yet, the [tutorials](/docs/tutorials/hello) +build the ideas up from working code and are the gentler way in; come back here for the *why* behind +them. + ## The ideas, grouped The pages below are ordered in the sidebar roughly as a reader meets them, and grouped here by what diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index 529cd9ca..8b89d4d3 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -31,7 +31,7 @@ Each row concedes where the alternative wins, because in most rows it does. | **A plain trait or generic** | A capability has one implementation, or one per type with a single global choice. **This is most code.** | The implementations multiply, the choice must differ per context, or threading a generic through every layer has started to hurt. | | **A direct impl on the context** | A provider would have exactly one user. Two contexts that each have their own single implementation need no providers and no wiring at all. | A second context wants the *same* implementation, or the implementation should compose with a wrapper. | | **An enum** | The variant set is small, closed, and known, with fixed operations. A `match` is clearer than any machinery. | The variant set is open, or independent modules must each contribute one. | -| **`dyn Trait`** | The set of implementations is not known until runtime. That openness is exactly what CGP gives up. | The set *is* known at build time, and you want the decoupling without the dispatch cost. | +| **`dyn Trait`** | The set of implementations is not known until runtime. CGP gives up exactly that openness. | The set *is* known at build time, and you want the decoupling without the dispatch cost. | | **A dependency-injection crate** | You specifically want a container's lifecycle and object-graph semantics. | You want compile-time-checked, reflection-free injection, which is the traits-and-generics approach, not a framework. | | **A generic-programming library such as `frunk`** | A one-off manipulation of a heterogeneous list. The lighter, focused library is less to learn and enough. | The structural machinery is part of a larger component-and-wiring design. | | **A hand-rolled macro** | The generation is narrow and local. | You notice you are reinventing marker types plus a helper trait, which is CGP's own mechanism. | From 43dc20a1cd2af90961f7f81c202e15a6d4a327b5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 00:19:42 +0200 Subject: [PATCH 041/516] docs(concepts): rebuild modularity page as Modularity Hierarchy Rename "How much CGP to use" back to "Modularity Hierarchy" and rebuild it as an explanation with a decision-guide tail: a summary table plus a dedicated section for each of the five tiers on one running encoding example, then the existing rule-of-thumb, alternatives, wrong-tool, and cost material. Change "rung" to "tier" throughout. Add the compiled counterpart example-code/src/concepts/modularity_hierarchy.rs, one module per tier, with a tier-5 test that resolves the higher-order wiring, and register it in the concepts module. Tier-3 providers are named EncodeSelfAsText / EncodeSelfAsBytes so they do not collide with the parameter-targeted EncodeAsText / EncodeAsHex used at tiers 4-5. Update the cross-links that named the old page: the blanket_trait, cgp_component, cgp_fn, and cgp_impl reference pages, the concepts index, and the coherence page. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_017sALDUMhxKZQg82mbeYxX4 --- docs/concepts/coherence.md | 6 +- docs/concepts/index.md | 10 +- docs/concepts/modularity-hierarchy.md | 481 ++++++++++++------ docs/reference/macros/blanket_trait.md | 2 +- docs/reference/macros/cgp_component.md | 2 +- docs/reference/macros/cgp_fn.md | 2 +- docs/reference/macros/cgp_impl.md | 4 +- example-code/src/concepts/mod.rs | 6 +- .../src/concepts/modularity_hierarchy.rs | 230 +++++++++ 9 files changed, 582 insertions(+), 161 deletions(-) create mode 100644 example-code/src/concepts/modularity_hierarchy.rs diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index c6c94232..453a4309 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -187,8 +187,8 @@ type names exactly one, and resolution is unambiguous. How far the idea scales is a separate question. Here each type picks one provider, which is the simplest shape. A type you define to stand for your own application can pick its own providers, and the same -capability can even resolve differently for the same data in two applications. Those are higher rungs of -the same ladder, worked out in [How much CGP to use](./modularity-hierarchy.md). +capability can even resolve differently for the same data in two applications. Those are higher tiers of +the same hierarchy, worked out in [Modularity Hierarchy](./modularity-hierarchy.md). ## What it costs @@ -216,7 +216,7 @@ it recognizes. It is a `v0.1.0-alpha` that reshapes the core wiring errors rathe ## Where to go next -[How much CGP to use](./modularity-hierarchy.md) is the page to read next if this argument landed, because +[Modularity Hierarchy](./modularity-hierarchy.md) is the page to read next if this argument landed, because a reader who has just been told coherence can be escaped needs to hear immediately that most code should not bother. It lays out the range from a plain trait to fully wired components and argues for climbing no higher than a problem needs. diff --git a/docs/concepts/index.md b/docs/concepts/index.md index a3efe4c9..fee1f521 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -27,9 +27,9 @@ the rule buys. Almost everything else here is downstream of it. how CGP works.** It covers the trait split at the centre of the design, one trait you call and another you implement, and how a call finds its way from one to the other. -**Read [How much CGP to use](./modularity-hierarchy.md) first if you are deciding whether to adopt -it.** It lays out the range from an ordinary Rust trait to fully wired components as a ladder, and -argues for climbing no higher than a problem requires. +**Read [Modularity Hierarchy](./modularity-hierarchy.md) first if you are deciding whether to adopt +it.** It lays out the range from an ordinary Rust trait to fully wired components as a hierarchy of +five tiers, and argues for going no higher than a problem requires. **New to Rust's traits and generics?** These pages explain the reasoning behind CGP and assume you are comfortable with traits and generic bounds. If you are not yet, the [tutorials](/docs/tutorials/hello) @@ -66,8 +66,8 @@ as it goes, turning a small language into types the compiler interprets. **Two pages stand slightly apart.** [Recovering `Send` bounds](./send-bounds.md) is a workaround for a gap in stable Rust rather than a CGP idea, and it matters as soon as an async CGP task is spawned. -[How much CGP to use](./modularity-hierarchy.md) is a decision guide rather than an explanation, and -it is the page to reach for when the question is how far to go. +[Modularity Hierarchy](./modularity-hierarchy.md) explains the five tiers of the hierarchy and then +turns into a decision guide, and it is the page to reach for when the question is how far to go. --- diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index 8b89d4d3..a11d67f0 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -1,30 +1,272 @@ --- -sidebar_label: 'How much CGP to use' +sidebar_label: 'Modularity Hierarchy' sidebar_position: 18 --- -# How much CGP to use +# Modularity Hierarchy + +How much CGP does a capability need? The answer is a tier in a five-tier hierarchy, where each tier +allows more independent implementations of one interface than the tier below, at a matching cost in +syntax or coupling. The right tier is the lowest one that still expresses the problem. + +This page explains each tier in turn on one running capability, encoding a value, so the only thing +that changes from tier to tier is the modularity, not the problem. It then turns to the decision: how +to pick a tier, when a plainer tool is the better choice, and what the machinery costs. If you are +still deciding whether CGP is for you at all, read to the end of the decision guide. + +## The five tiers at a glance + +The table is the summary; the sections below explain each tier in full. + +| Tier | What it allows | The construct | The coherence limit it escapes | +|---|---|---|---| +| **1** | One implementation for every type | a blanket impl, or [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) | none: one implementation only | +| **2** | One implementation per type | a plain Rust trait | none: one implementation per type | +| **3** | Many implementations, one wired per type | [`#[cgp_component]`](/docs/reference/macros/cgp_component) and [`delegate_components!`](/docs/reference/macros/delegate_components) | the overlap rule | +| **4** | Many implementations, one per type per context | a type parameter and the [`open` statement](/docs/reference/macros/delegate_components) | the orphan rule as well | +| **5** | Many implementations, per type per provider | a [higher-order provider](./higher-order-providers.md) | none new: a local override within tier 4 | + +Tiers 1 and 2 are ordinary Rust. Tiers 3 through 5 are CGP, and each one loosens a coherence +constraint that the tier below still obeys. + +## Tier 1: one implementation for every type + +The lowest tier is a single implementation that applies to every type meeting a bound. A blanket +trait implementation captures one piece of logic and offers no alternative to it. + +```rust +pub trait CanEncode { + fn encode(&self) -> Vec; +} + +impl> CanEncode for Value { + fn encode(&self) -> Vec { + self.as_ref().to_vec() + } +} +``` + +Every type that is `AsRef<[u8]>` now encodes the same way, and no second strategy is possible. +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds this same tier from a plain function, and hides +the bound behind a clean interface. Reach for tier 1 when a capability genuinely has one +implementation for all types. + +## Tier 2: one implementation per type + +A plain Rust trait raises the ceiling to one implementation per type. Each type supplies its own +body, and coherence still allows only one. + +```rust +pub trait CanEncode { + fn encode(&self) -> Vec; +} + +impl CanEncode for u32 { + fn encode(&self) -> Vec { + self.to_string().into_bytes() + } +} + +impl CanEncode for Vec { + fn encode(&self) -> Vec { + self.clone() + } +} +``` + +Each type varies, but the choice is global: once `u32` encodes one way, that is the only way for the +whole program. A blanket implementation that would share logic across several types is rejected, +because it could overlap. This is where Rust's coherence guarantee delivers its value, and also where +it starts to bind. Tier 2 is the right tier for a capability that varies by type but never by +application. + +## Tier 3: many implementations, one wired per type + +The first CGP tier splits the trait into a consumer trait you call and a provider trait you +implement. Many overlapping implementations become legal, each one a named provider, and every type +wires the one it uses. + +```rust +#[cgp_component(SelfEncoder)] +pub trait CanEncodeSelf { + fn encode(&self) -> Vec; +} + +#[cgp_impl(new EncodeSelfAsText)] +#[uses(core::fmt::Display)] +impl SelfEncoder { + fn encode(&self) -> Vec { + self.to_string().into_bytes() + } +} +``` + +`EncodeSelfAsText` and a bytes-based `EncodeSelfAsBytes` can both exist, even on a type that matches +both, because each provider is its own name rather than an implementation of the trait itself. A type +then wires one provider: + +```rust +delegate_components! { + u32 { + SelfEncoderComponent: EncodeSelfAsText, + } +} +``` + +Add [`check_components!`](/docs/reference/macros/check_components) when you wire. The wiring is checked +lazily, so an unchecked table is the main source of confusing errors. + +### Tier 3 holds two shapes + +This tier behaves differently depending on what the wired type *is*, and the difference is the one +readers most often miss, because nothing in a signature marks it. + +In the **retrofit** shape the wired type is the data itself, as `u32` is above. That type is usually +one you do not own, so it gets one wiring for the whole program. This is the right shape when the +capability belongs to the data, or when an existing trait cannot change its signature. + +In the **application** shape the wired type stands for the application rather than for data, and it +often has no fields at all. Here the "one wiring per type" limit stops mattering, because you decide +how many application types exist. The capability is about the application, such as sending an email or +querying a user, rather than about a value: + +```rust +#[cgp_component(EmailSender)] +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + +#[cgp_impl(new SendViaSmtp)] +impl EmailSender { /* connect and send over SMTP */ } + +#[cgp_impl(new RecordEmails)] +impl EmailSender { /* record to a Vec a test can read */ } + +delegate_components! { App { EmailSenderComponent: SendViaSmtp } } +delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } +``` + +`App` and `TestApp` are both yours, so each wires its own provider with no type parameter anywhere. +Notice the crossing: `u32` in the first example is data in the `Self` position, while `App` here is a +type that stands for the application. **The application shape is where most CGP code lives**, so a +reader who takes tier 3 to be only the retrofit shape has undersold it. + +## Tier 4: many implementations, one per type per context + +Tier 4 moves the target type out of `Self` and into a parameter, so `Self` is always an application +context. This lifts the orphan rule and lets each context choose a provider per target type, +including for types it does not own. + +```rust +#[cgp_component(Encoder)] +pub trait CanEncodeValue { + fn encode(&self, value: &Value) -> Vec; +} +``` + +Two applications can now encode the same foreign type differently. With an `EncodeAsText` provider +for `Display` types and an `EncodeAsHex` provider for `AsRef<[u8]>` types, `ApiServer` writes a +`String` as text where `Firmware` writes it as hexadecimal: + +```rust +delegate_components! { + ApiServer { + open EncoderComponent; + @EncoderComponent.String: EncodeAsText, + } +} + +delegate_components! { + Firmware { + open EncoderComponent; + @EncoderComponent.String: EncodeAsHex, + } +} +``` + +Because the wiring keys on the context rather than on `String`, a crate that owns neither the trait +nor `String` can still wire it, as long as it owns the context. The cost is that the trait must carry +the extra parameter from the start, so it cannot be added to an existing trait such as +`serde::Serialize` without a breaking change, and every value type a context uses must be wired. +Reach for tier 4 when different applications must treat the same foreign type differently. Most code +does not need it. + +## Tier 5: many implementations, per type per provider + +The top tier lets one provider fix the wiring of a nested type on its own, without routing that +choice back through the context. It takes the inner provider as a parameter, which makes it a +[higher-order provider](./higher-order-providers.md). An encoder for a `Vec` encodes each +element through an inner provider, and defaults that inner provider to the context when none is named: + +```rust +pub struct EncodeVecWith(pub PhantomData); + +#[cgp_impl(EncodeVecWith)] +#[use_provider(Inner: Encoder)] +impl Encoder> { + fn encode(&self, value: &Vec) -> Vec { + value.iter().flat_map(|item| Inner::encode(self, item)).collect() + } +} +``` + +A context can then pin the inner encoding for one collection while leaving others to its general +wiring: + +```rust +delegate_components! { + App { + open EncoderComponent; + @EncoderComponent.u32: EncodeAsText, + @EncoderComponent.Vec: EncodeVecWith, + @EncoderComponent.Vec>: EncodeVecWith, + } +} +``` + +The `Vec` entry omits the parameter, so each `u32` routes back through the context to +`EncodeAsText`. The `Vec>` entry pins its inner encoding to `EncodeAsHex`, whatever the +context does with `Vec` elsewhere. The `UseContext` default is what makes both entries read the +same. This tier adds coupling and higher-order machinery, so reach for it only when a local override +genuinely matters. + +## Choosing a tier + +The guiding rule is to settle at the lowest tier that expresses the use case, because each higher +tier trades simplicity for modularity that may not be needed. Most code has one implementation of +most things, and for that code a plain trait is the right answer rather than a compromise. + +Two questions place a capability faster than working through the tiers one by one. + +**Is the capability about the data, or about the application?** About the data means the wired type +*is* the thing being operated on, as `Rectangle: CanCalculateArea` is. About the application means the +wired type is one you define to carry choices, often with no fields at all. + +**Does it concern a type you do not own, which different applications must treat differently?** If so, +that type moves out of `Self` and becomes a parameter. If not, targeting `Self` is enough. + +The answers name one of three shapes, and none of them is more advanced than the others. Each is the +right answer to a different question. -The ladder from a plain trait to fully wired components, and how to settle at the lowest rung that solves -the problem in front of you. - -This page is a decision guide rather than an explanation, so it is written to be acted on rather than read -straight through: a rule of thumb first, then the alternatives you are actually choosing between, the cases -where CGP is simply the wrong tool, which of its shapes to reach for, and how far to go once you are inside -it. If you are still deciding whether CGP is for you at all, this is the page to read. - -## The rule of thumb +| Answers | The shape | What it gives you | +|---|---|---| +| About the data | **Retrofit** (tier 3) | Alternative implementations for an existing type, without changing its trait. One choice per type, program-wide. | +| About the application | **Application** (tier 3) | One choice per context you define, and you can define as many as you like. | +| About a foreign type, differing per application | **Fully modular** (tiers 4–5) | One choice per context, per target type. | -**Use CGP when a capability needs more than one implementation and the choice belongs to the context, not -before.** +**The application shape is where most CGP code lives.** A capability about the application, such as +sending an email or running the server, wired per application with no type parameter anywhere, is the +ordinary case rather than the elaborate one. -Almost everything follows from that. Most code has one implementation of most things, and for that code a -plain trait is not a compromise, it is the right answer. CGP is a rung you climb to deliberately, and the -useful question is never "is CGP good" but "CGP, or the thing already in place?". +As wiring grows, [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) and aggregate providers keep +it readable by grouping shared wiring into reusable tables. Both add a hop between a component and its +provider, so neither pays until the repetition is real. -## What you are choosing between +## CGP, or the tool already in place? -Each row concedes where the alternative wins, because in most rows it does. +Deciding a tier assumes CGP is the right tool at all, and often it is not. The useful question is +never "is CGP good" but "CGP, or the thing already in place?". Each row below concedes where the +alternative wins, because in most rows it does. | The alternative | Prefer it when | Reach for CGP when | |---|---|---| @@ -45,29 +287,29 @@ plausibly better as a language feature eventually, and a project that can wait s Four cases are not trade-offs. Naming them is more useful than any argument in CGP's favour. **Runtime dynamism.** CGP cannot give you plugins loaded at startup, heterogeneous collections, or -redefinition while the program runs. Its wiring is fixed at build time. That lives on the runtime side, -where `dyn Trait` and the dynamic languages remain right. +redefinition while the program runs. Its wiring is fixed at build time. That lives on the runtime +side, where `dyn Trait` and the dynamic languages remain right. -**Exactly one implementation.** A capability with one definition belongs in a plain trait. If you want it -to read like CGP anyway, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds it from a function with no -component, no provider, and no wiring, and it keeps working unchanged if a second implementation ever -arrives. +**Exactly one implementation.** A capability with one definition belongs in a plain trait, which is +tier 1 or tier 2. If you want it to read like CGP anyway, +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds it from a function with no component, no provider, +and no wiring, and it keeps working unchanged if a second implementation ever arrives. **A small closed set of variants.** An enum and a `match` are clearer, faster to read, and free. -**One instance program-wide.** When a program genuinely wants a single globally consistent answer, one -`Ord` for a map key where two orderings in one program would corrupt the map, per-context choice is the -wrong shape. Coherent traits are safer, and this is the limit of CGP's central bargain. +**One instance program-wide.** When a program genuinely wants a single globally consistent answer, +such as one `Ord` for a map key where two orderings in one program would corrupt the map, per-context +choice is the wrong shape. Coherent traits are safer, and this is the limit of CGP's central bargain. ## "I only have one application — what does this buy me?" -This is the question most people reach in their first week, looking at the single context their codebase -contains, and it deserves a straight answer rather than a prediction about the future. +This is the question most people reach in their first week, looking at the single context their +codebase contains, and it deserves a straight answer rather than a prediction about the future. **Concede the obvious part first: with one context, the swappability payoff is not available.** Every wiring line has one plausible value and every provider one user. Nothing about that is going to feel -worthwhile, and being told you will want a second context later asks you to spend now for a benefit you -cannot check. +worthwhile, and being told you will want a second context later asks you to spend now for a benefit +you cannot check. Three things do pay with one context. @@ -75,136 +317,85 @@ Three things do pay with one context. application touches, not along its contexts, so a single application with several types to encode, serialize, or validate already has more than one implementation to place. That is [bypassing coherence](./coherence.md), and it needs no second context at all. -- **The orphan-rule escape.** Adding a capability to a type from another crate needs one context and a - foreign type. No newtype wrapper, and no second application. -- **Dependencies declared where the implementation is.** A `&self` method on a concrete struct may read any - field and call any other method, so nothing short of reading the body tells you what it depends on. A - provider's declared requirements *are* that answer, and the compiler enforces them. This is worth - something in one context and more in each one added. +- **The orphan-rule escape.** Adding a capability to a type from another crate needs one context and + a foreign type. No newtype wrapper, and no second application. +- **Dependencies declared where the implementation is.** A `&self` method on a concrete struct may + read any field and call any other method, so nothing short of reading the body tells you what it + depends on. A provider's declared requirements *are* that answer, and the compiler enforces them. + This is worth something in one context and more in each one added. -And then the second context you probably already have: **the test harness.** It is the cheapest one to -justify and the one nobody argues about. +And then the second context you probably already have: **the test harness.** It is the cheapest one +to justify and the one nobody argues about. -**If none of that applies, the honest recommendation is to stay put.** A codebase with one application, no -capability needing more than one implementation, and no foreign type to extend is one where CGP's central -bargain does not pay. Reach for `#[cgp_fn]` alone, or nothing. +**If none of that applies, the honest recommendation is to stay put.** A codebase with one +application, no capability needing more than one implementation, and no foreign type to extend is one +where CGP's central bargain does not pay. Reach for `#[cgp_fn]` alone, or nothing. ## "Won't I end up with a context per configuration?" -Partly justified, and the answer is composition rather than reassurance. Separating every axis really would -multiply: four independent binary choices would mean sixteen types. - -CGP does not ask you to separate an axis you do not need separated, and it composes with the patterns that -collapse one. A generic parameter on the context struct keeps a single type across several database -engines. An enum keeps a single type for a choice made from configuration at runtime. A context holds -either of those and wires its components normally. - -A real application lands on separation for the axis where a wrong combination must be -**impossible**, such as a mock client never reaching production, and collapse for everything else. CGP -decides which variations are worth their own type; the tools you already use handle the ones that are -not. +Partly justified, and the answer is composition rather than reassurance. Separating every axis really +would multiply: four independent binary choices would mean sixteen types. -There is a payoff here worth naming if you are writing a library. An enum you expose for supported backends -is normally a ceiling on what downstream users can have: a new variant means a pull request or a fork. When -the context-generic code is written against capabilities rather than against the enum, a downstream crate -defines its own wider enum and its own context and reuses everything, with nothing to petition for. +CGP does not ask you to separate an axis you do not need separated, and it composes with the patterns +that collapse one. A generic parameter on the context struct keeps a single type across several +database engines. An enum keeps a single type for a choice made from configuration at runtime. A +context holds either of those and wires its components normally. -## Which shape to reach for +A real application lands on separation for the axis where a wrong combination must be **impossible**, +such as a mock client never reaching production, and collapse for everything else. CGP decides which +variations are worth their own type; the tools you already use handle the ones that are not. -CGP's code comes in three shapes, and readers sometimes resist being taught three where they expected one. -They are not three levels of sophistication. Each answers a different question, and two questions settle -which you are in. - -**Is the capability about the data, or about the application?** About the data means the wired type *is* the -thing being operated on, as in `Rectangle: CanCalculateArea`. About the application means the wired type is -one you define to carry choices, often with no fields at all. - -**Does it concern a type you do not own, which different applications must treat differently?** If so, that -type moves out of `Self` and becomes a parameter. If not, targeting `Self` is enough. - -| Answers | The shape | What it gives you | -|---|---|---| -| About the data | **Retrofit** | Alternative implementations for an existing type, without changing its trait. One choice per type, program-wide. | -| About the application | **Application** | One choice per context you define, and you can define as many as you like. | -| About a foreign type, differing per application | **Fully modular** | One choice per context *per target type*. | - -**The application shape is where most CGP code lives**, which is worth stating plainly so that the most -elaborate shape does not read as the intended destination. A capability about the application, such as -sending an email, querying a user, or running the server, wired per application with no type parameter -anywhere, is the ordinary case. - -## How far to go inside CGP - -Deciding to use CGP is not the last decision. Its constructs form a progression, and the same rule applies -inside as outside: **stop at the lowest step that solves the problem in front of you.** Each step below is a -response to something you have already hit, not a level to reach. - -1. **A capability from a function.** [`#[cgp_fn]`](/docs/reference/macros/cgp_fn): one implementation, no - component, no wiring. Most capabilities never need more, and starting here costs nothing later: the trait - keeps its name and method, so promoting it leaves every call site untouched. -2. **A component.** [`#[cgp_component]`](/docs/reference/macros/cgp_component) with a provider and a - [wiring table](/docs/reference/macros/delegate_components), when a second implementation is real, not - anticipated. Add [`check_components!`](/docs/reference/macros/check_components) at the same time; the - wiring is checked lazily and an unchecked table is the main source of confusing errors. -3. **Per-type dispatch.** The [`open` statement](/docs/reference/macros/delegate_components), when one - component needs a different provider per value of a type parameter. A type has moved out of `Self` into - a parameter by this point, so it usually arrives with the fully-modular shape rather than before it. -4. **Providers composed from providers.** A provider that takes another provider as a parameter and builds - on it, declared with [`#[use_provider]`](/docs/reference/attributes/use_provider), when one - implementation should be expressed in terms of another rather than chosen alongside it. Genuinely - useful, and the step most often taken too early: if nothing is being wrapped, there is nothing for it to - do. -5. **Reusable wiring.** An [aggregate provider](/docs/reference/macros/delegate_components) for a small - bundle several contexts delegate to, or [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) when - wiring repeats across many contexts or a table has outgrown reading. Both add a hop between a component - and its provider, so neither pays until the repetition is real. - -**Steps 2 and 3 are where most CGP code sits.** Steps 4 and 5 answer scale and composition specifically, and -reaching for either before the problem exists is how a CGP codebase ends up harder to read than the one it -replaced. The machinery is real either way, and only pays when something is actually being shared or -wrapped. +There is a payoff here worth naming if you are writing a library. An enum you expose for supported +backends is normally a ceiling on what downstream users can have: a new variant means a pull request +or a fork. When the context-generic code is written against capabilities rather than against the +enum, a downstream crate defines its own wider enum and its own context and reuses everything, with +nothing to petition for. ## What it costs -**Every rung above a plain trait costs syntax and indirection.** Two traits, a marker type, and a wiring -line per context, plus a hop between a call and the code that runs. The wiring table is a single greppable -place naming exactly one provider per component, and it is still a hop a reader has to follow. - -**Diagnostics are the sharpest cost, and honesty here matters more than elsewhere.** A mis-wired context can -produce a wall of generated types. [`check_components!`](/docs/reference/macros/check_components) forces the -failure to the wiring line and names the actual missing requirement, and -[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) un-hides the root cause the default trait -solver suppresses and leads with it. Both help substantially. Neither makes the raw output pleasant, and the -tool is a `v0.1.0-alpha` that reshapes the classes it recognizes rather than all of them. **Dramatically -better and actively improving, not solved.** - -**Compile-time cost goes up.** CGP does more work at compile time, and no number is quoted here that could -not be cited. The honest reframing is that resolution costing at compile time is resolution that would -otherwise cost at runtime or not be checked at all. - -**There is a learning curve.** The first useful thing, a capability written as a function used with no -wiring, needs only ordinary Rust knowledge, so the first step is small. The curve past it is real. - -Three of those costs, the learning curve, decoding the diagnostics, and the volume of wiring to write and -read, are mechanical work over a vocabulary that is written down, which is the kind of thing a coding -assistant handles well. CGP publishes an [agent skill](https://github.com/contextgeneric/cgp-skills) that -teaches one that vocabulary, and a reader who already works with an assistant can attach it and judge for -themselves within the hour. It makes those three costs **smaller, not absent**: the diagnostics are still -verbose, the vocabulary still has to be learned by whoever reviews the code, and none of it moves any -boundary on this page. A codebase that will only ever have one application still belongs on `#[cgp_fn]` -alone, regardless of who writes the wiring. +**Every tier above a plain trait costs syntax and indirection.** Two traits, a marker type, and a +wiring line per context, plus a hop between a call and the code that runs. The wiring table is a +single greppable place naming exactly one provider per component, and it is still a hop a reader has +to follow. + +**Diagnostics are the sharpest cost, and honesty here matters more than elsewhere.** A mis-wired +context can produce a wall of generated types. +[`check_components!`](/docs/reference/macros/check_components) forces the failure to the wiring line +and names the actual missing requirement, and +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) un-hides the root cause the default +trait solver suppresses and leads with it. Both help substantially. Neither makes the raw output +pleasant, and the tool is a `v0.1.0-alpha` that reshapes the classes it recognizes rather than all of +them. **Dramatically better and actively improving, not solved.** + +**Compile-time cost goes up.** CGP does more work at compile time, and no number is quoted here that +could not be cited. The honest reframing is that resolution costing at compile time is resolution +that would otherwise cost at runtime or not be checked at all. + +**There is a learning curve.** The first useful thing, a capability written as a function used with +no wiring, needs only ordinary Rust knowledge, so the first step is small. The curve past it is real. + +Three of those costs, the learning curve, decoding the diagnostics, and the volume of wiring to write +and read, are mechanical work over a vocabulary that is written down, which is the kind of thing a +coding assistant handles well. CGP publishes an +[agent skill](https://github.com/contextgeneric/cgp-skills) that teaches one that vocabulary, and a +reader who already works with an assistant can attach it and judge for themselves within the hour. It +makes those three costs **smaller, not absent**: the diagnostics are still verbose, the vocabulary +still has to be learned by whoever reviews the code, and none of it moves any boundary on this page. A +codebase that will only ever have one application still belongs on `#[cgp_fn]` alone, regardless of +who writes the wiring. ## Where to go next -[Bypassing coherence](./coherence.md) is the argument behind the rule of thumb: why Rust allows one -implementation per type, and what CGP does about it. Read it if the question is *why* rather than *whether*. +[Bypassing coherence](./coherence.md) is the argument behind the hierarchy: why Rust allows one +implementation per type, and what CGP does about it. Read it if the question is *why* rather than *how +far*. -[Consumer and provider traits](./consumer-and-provider-traits.md) covers the mechanism the upper rungs are -built on, and closes with the same costs stated for that construct specifically. +[Consumer and provider traits](./consumer-and-provider-traits.md) covers the mechanism tiers 3 +through 5 are built on, and closes with the same costs stated for that construct specifically. -If the answer here was "not yet", [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the whole of what you -need: a capability from a function, no wiring, nothing to reverse later. If it was "yes", -the [Area calculation series](/docs/tutorials/area-calculation/) climbs the rungs in order, and +If the answer here was "not yet", [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the whole of what +you need: a capability from a function, no wiring, nothing to reverse later. If it was "yes", the +[Area calculation series](/docs/tutorials/area-calculation/) works up the tiers in order, and [`#[cgp_component]`](/docs/reference/macros/cgp_component) is where the component machinery starts. --- diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 68de46b8..68f6ad19 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -300,7 +300,7 @@ The ideas behind it: - [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the idea this macro automates — requirements that live on the impl rather than the interface. -- [How much CGP to use](/docs/concepts/modularity-hierarchy) — where a blanket trait sits between a +- [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) — where a blanket trait sits between a plain trait and a full component. ## Source diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 393134e2..946a9489 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -446,7 +446,7 @@ The ideas behind it: - [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the trait split this macro creates, developed at length. - [Bypassing coherence](/docs/concepts/coherence) — why the split exists at all. -- [How much CGP to use](/docs/concepts/modularity-hierarchy) — when a component is the right rung, +- [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) — when a component is the right tier, and when it is more than the problem needs. ## Source diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 98bcd460..d431ce43 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -355,7 +355,7 @@ The ideas behind it: - [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the `where`-clause injection this macro is built on. -- [How much CGP to use](/docs/concepts/modularity-hierarchy) — the ladder this sits at the bottom +- [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) — the hierarchy this sits at the bottom of. ## Source diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 1b53078d..2f4a884d 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -278,8 +278,8 @@ any other. The `Self` form produces no provider at all. Reach for something else in two cases. - **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain - function with no component, no provider, and no wiring, which is the bottom rung of - [How much CGP to use](/docs/concepts/modularity-hierarchy). + function with no component, no provider, and no wiring, which is the bottom tier of + [Modularity Hierarchy](/docs/concepts/modularity-hierarchy). - **You want to implement the consumer trait directly on one concrete type.** Use the [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which keeps the companion attributes while emitting an ordinary impl. diff --git a/example-code/src/concepts/mod.rs b/example-code/src/concepts/mod.rs index a4faa64e..c8d92e9b 100644 --- a/example-code/src/concepts/mod.rs +++ b/example-code/src/concepts/mod.rs @@ -1,8 +1,7 @@ //! Code from the pages under `docs/concepts/`, one module per page. //! -//! All eighteen pages of that section are written, and the seventeen that show code have a module here. -//! The two that show none — the section index, and *How much CGP to use*, which is a decision guide -//! built from prose and tables — do not. +//! All eighteen pages of that section are written, and the ones that show code have a module here. +//! The section index shows none, so it has no module. pub mod abstract_types; pub mod aggregate_providers; @@ -17,6 +16,7 @@ pub mod higher_order_providers; pub mod impl_side_dependencies; pub mod implicit_arguments; pub mod modular_error_handling; +pub mod modularity_hierarchy; pub mod monadic_handlers; pub mod namespaces; pub mod send_bounds; diff --git a/example-code/src/concepts/modularity_hierarchy.rs b/example-code/src/concepts/modularity_hierarchy.rs new file mode 100644 index 00000000..ee27c45a --- /dev/null +++ b/example-code/src/concepts/modularity_hierarchy.rs @@ -0,0 +1,230 @@ +//! Code from `docs/concepts/modularity-hierarchy.md` — *Modularity Hierarchy*. +//! +//! One module per tier. The page walks the five tiers on one running capability — encoding a value — +//! so each module encodes the same kind of thing with more modularity than the one before it. The +//! `CanEncode` / `Encoder` / `EncodeAsText` names are the site's shared encoding example, carried over +//! from the front page and *Bypassing coherence*. + +/// ## Tier 1: one implementation for every type +/// +/// A blanket implementation: one body that applies everywhere the bound holds, with no alternative. +pub mod tier_1 { + pub trait CanEncode { + fn encode(&self) -> Vec; + } + + impl> CanEncode for Value { + fn encode(&self) -> Vec { + self.as_ref().to_vec() + } + } +} + +/// ## Tier 2: one implementation per type +/// +/// A plain trait: a different body per type, and coherence allows only one of them. +pub mod tier_2 { + pub trait CanEncode { + fn encode(&self) -> Vec; + } + + impl CanEncode for u32 { + fn encode(&self) -> Vec { + self.to_string().into_bytes() + } + } + + impl CanEncode for Vec { + fn encode(&self) -> Vec { + self.clone() + } + } +} + +/// ## Tier 3: many implementations, one wired per type +/// +/// The self-targeted component, wired on a value context (`u32`) and on an environmental context +/// (`App` / `TestApp`). The page shows the two shapes this tier holds. +pub mod tier_3 { + use cgp::prelude::*; + + #[cgp_component(SelfEncoder)] + pub trait CanEncodeSelf { + fn encode(&self) -> Vec; + } + + #[cgp_impl(new EncodeSelfAsText)] + #[uses(core::fmt::Display)] + impl SelfEncoder { + fn encode(&self) -> Vec { + self.to_string().into_bytes() + } + } + + #[cgp_impl(new EncodeSelfAsBytes)] + #[uses(AsRef<[u8]>)] + impl SelfEncoder { + // The page elides this body. + fn encode(&self) -> Vec { + self.as_ref().to_vec() + } + } + + delegate_components! { + u32 { + SelfEncoderComponent: EncodeSelfAsText, + } + } + + mod check_u32 { + use super::*; + check_components! { u32 { SelfEncoderComponent } } + } + + // The application shape: the wired type stands for the application, not for data. + #[cgp_component(EmailSender)] + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + #[cgp_impl(new SendViaSmtp)] + impl EmailSender { + // The page elides this body as `/* connect and send over SMTP */`. + fn send_email(&self, to: &str, body: &str) {} + } + + #[cgp_impl(new RecordEmails)] + impl EmailSender { + // The page elides this body as `/* record to a Vec a test can read */`. + fn send_email(&self, to: &str, body: &str) {} + } + + pub struct App; + pub struct TestApp; + + delegate_components! { App { EmailSenderComponent: SendViaSmtp } } + delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } + + mod check_app { + use super::*; + check_components! { App { EmailSenderComponent } } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { EmailSenderComponent } } + } +} + +/// ## Tier 4: many implementations, one per type per context +/// +/// The parameter-targeted component: two application contexts encode the same foreign type +/// (`String`) differently. +pub mod tier_4 { + use cgp::prelude::*; + + #[cgp_component(Encoder)] + pub trait CanEncodeValue { + fn encode(&self, value: &Value) -> Vec; + } + + #[cgp_impl(new EncodeAsText)] + impl Encoder + where + Value: core::fmt::Display, + { + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() + } + } + + #[cgp_impl(new EncodeAsHex)] + impl Encoder + where + Value: AsRef<[u8]>, + { + // The page elides this body as `/* hex-encode the bytes */`. + fn encode(&self, value: &Value) -> Vec { + value + .as_ref() + .iter() + .flat_map(|byte| format!("{byte:02x}").into_bytes()) + .collect() + } + } + + pub struct ApiServer; + pub struct Firmware; + + delegate_components! { + ApiServer { + open EncoderComponent; + @EncoderComponent.String: EncodeAsText, + } + } + + delegate_components! { + Firmware { + open EncoderComponent; + @EncoderComponent.String: EncodeAsHex, + } + } + + mod check_api_server { + use super::*; + check_components! { ApiServer { EncoderComponent: String } } + } + + mod check_firmware { + use super::*; + check_components! { Firmware { EncoderComponent: String } } + } +} + +/// ## Tier 5: many implementations, per type per provider +/// +/// A higher-order provider, built on tier 4's `Encoder` component. It encodes a `Vec` by encoding +/// each element through an inner provider, which defaults to the context. +pub mod tier_5 { + use core::marker::PhantomData; + + use cgp::prelude::*; + + use super::tier_4::{CanEncodeValue, EncodeAsHex, EncodeAsText, Encoder, EncoderComponent}; + + pub struct EncodeVecWith(pub PhantomData); + + #[cgp_impl(EncodeVecWith)] + #[use_provider(Inner: Encoder)] + impl Encoder> { + fn encode(&self, value: &Vec) -> Vec { + value + .iter() + .flat_map(|item| Inner::encode(self, item)) + .collect() + } + } + + pub struct App; + + delegate_components! { + App { + open EncoderComponent; + @EncoderComponent.u32: EncodeAsText, + @EncoderComponent.Vec: EncodeVecWith, + @EncoderComponent.Vec>: EncodeVecWith, + } + } + + // Calling the consumer trait forces the whole wiring chain to resolve at compile time, which a + // `delegate_components!` entry does not do on its own. The `Vec` call exercises the + // `UseContext` default, and the `Vec>` call exercises the pinned inner provider. + #[test] + fn app_encodes_nested_collections() { + let flat = >>::encode(&App, &vec![1, 2, 3]); + assert_eq!(flat, b"123"); + + let nested = >>>::encode(&App, &vec![vec![0xab]]); + assert_eq!(nested, b"ab"); + } +} From 858ae3d86e05bd07e3ed5663f2b23dfc98fffc69 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 11:52:47 +0200 Subject: [PATCH 042/516] Revise the derives reference, add an overview page, and order the sidebar Revise all eight derive pages for writing style, matching the conventions applied across the rest of the reference: remove prose em dashes, pseudo-clefts, and metaphors/idioms in favour of plain, direct English. Keep the term-gloss separators in Related constructs and Source lists, which are shared across the reference. Fix five broken cross-links found while revising: #[derive(CgpRecord)] and #[derive(CgpVariant)] pointed at derive_cgp_data.md in three pages, and HasFieldMut pointed at has_field.md instead of has_field_mut.md. Add a Derives overview page and give each construct a sidebar_position, so the sidebar leads with the most-used derives (HasField, HasFields) before the umbrella and its faces (CgpData, CgpRecord, CgpVariant) and the individual slices (BuildField, ExtractField, FromVariant), matching the internal reference's ordering. Co-Authored-By: Claude Opus 4.8 --- docs/reference/derives/_category_.json | 4 +- docs/reference/derives/derive_build_field.md | 68 ++++---- docs/reference/derives/derive_cgp_data.md | 38 ++--- docs/reference/derives/derive_cgp_record.md | 28 ++-- docs/reference/derives/derive_cgp_variant.md | 36 ++--- .../reference/derives/derive_extract_field.md | 64 ++++---- docs/reference/derives/derive_from_variant.md | 45 +++--- docs/reference/derives/derive_has_field.md | 145 ++++++++--------- docs/reference/derives/derive_has_fields.md | 150 +++++++++--------- docs/reference/derives/index.md | 65 ++++++++ 10 files changed, 360 insertions(+), 283 deletions(-) create mode 100644 docs/reference/derives/index.md diff --git a/docs/reference/derives/_category_.json b/docs/reference/derives/_category_.json index 8d8545d2..c0dc9c7d 100644 --- a/docs/reference/derives/_category_.json +++ b/docs/reference/derives/_category_.json @@ -2,7 +2,7 @@ "label": "Derives", "position": 3, "link": { - "type": "generated-index", - "description": "The `#[derive(...)]` macros that generate field access and the extensible-data machinery for your structs and enums." + "type": "doc", + "id": "reference/derives/index" } } diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index d20ed844..118bb172 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive(BuildField)]' +sidebar_position: 6 --- # `#[derive(BuildField)]` @@ -9,14 +10,14 @@ Builder support for a record. ## Overview A struct literal has to be written in one place that names the concrete type and supplies every field at -once. That is usually what you want — and it is exactly wrong when the fields come from several independent +once. That is usually what you want. It is exactly wrong when the fields come from several independent places, none of which should know the whole type. A hand-written constructor that grows a parameter per subsystem becomes the one file every change has to edit. -`#[derive(BuildField)]` replaces it with a builder whose completeness is tracked **in the type**. The derive -generates a companion struct that starts out with every field absent, and each step fills one field in and -returns a value of a *different* type — one where that field is now present. Only the all-present type can be -turned back into the real struct: +`#[derive(BuildField)]` replaces it with a builder whose completeness is tracked **in the type**. The +derive generates a companion struct that starts out with every field absent, and each step fills one +field in and returns a value of a *different* type: one where that field is now present. Only the +all-present type can be turned back into the real struct: ```rust let person = Person::builder() // nothing set yet @@ -25,9 +26,9 @@ let person = Person::builder() // nothing se .finalize_build(); // every field set: closes ``` -Delete either middle line and this does not compile. There is no runtime check, no `Option` per field, and no -panic path — `finalize_build` simply does not exist for a value with a field still missing. What a -conventional builder catches at run time, this catches while you are typing. +Delete either middle line and this does not compile. There is no runtime check, no `Option` per field, +and no panic path: `finalize_build` simply does not exist for a value with a field still missing. A +conventional builder catches a missing field at run time; this catches it while you are typing. The other half of the payoff is that steps are decoupled. Because each `build_field` names its field by a type-level tag rather than by calling a method on the concrete type, generic code can fill in a field of a @@ -53,9 +54,9 @@ tag holds. A tuple struct works the same way with positional tags: a field at po `build_field(PhantomData::>, value)`. Generic parameters, lifetimes, and a `where` clause are carried onto the companion type and every generated impl. -A fieldless struct is the degenerate case rather than an error. Its companion type takes no parameters at all, -so there is exactly one configuration of it and `builder()` is immediately finalizable — the presence tracking -has nothing to track. +A fieldless struct is the degenerate case rather than an error. Its companion type takes no parameters at +all, so there is exactly one configuration of it and `builder()` is immediately finalizable. The presence +tracking has nothing to track. The derive parses a struct, so applying it to an enum fails at parse time. The enum counterparts are [`#[derive(ExtractField)]`](./derive_extract_field.md) for taking one apart and @@ -64,14 +65,14 @@ The derive parses a struct, so applying it to an enum fails at parse time. The e ### What it does *not* generate This is the point of deriving it alone, so it is worth being explicit. `#[derive(BuildField)]` emits the -builder and nothing else — **no** `HasField` accessors on your struct and **no** whole-shape representation. +builder and nothing else: **no** `HasField` accessors on your struct and **no** whole-shape representation. Those come from [`#[derive(HasField)]`](./derive_has_field.md) and [`#[derive(HasFields)]`](./derive_has_fields.md), and the umbrella [`#[derive(CgpData)]`](./derive_cgp_data.md) includes all three. So a struct that derives only `BuildField` can be *built* generically and not *read* generically. That is -occasionally exactly right — an output type a pipeline assembles and hands back — and it is why the slice -exists. +occasionally exactly right, for an output type a pipeline assembles and hands back, and it is why the +slice exists. ### The three ways to fill a field @@ -93,17 +94,18 @@ Employee::builder() **The source of a `build_from` needs [`#[derive(HasFields)]`](./derive_has_fields.md) as well**, and this is the easiest thing on this page to get wrong. `build_from` walks the *source's* field list to know what -to copy, and that list is what `HasFields` provides — so a source deriving only `BuildField` has a builder -of its own and still cannot be merged into anything. The target needs only this derive. +to copy, and that list comes from `HasFields`. A source deriving only `BuildField` has a builder of its +own and still cannot be merged into anything. The target needs only this derive. **`take_field`** goes the other way: it removes a field that is already present, handing back the value alongside a builder with that field absent again. It is the reverse of `build_field` and comes from -`TakeField`, which unlike the rest of the family is **not in the prelude** — import it from -`cgp::core::field::traits` when calling it directly. Most code meets it indirectly, since it is what -`build_from` uses to pull each field out of the source. +`TakeField`, which unlike the rest of the family is **not in the prelude**. Import it from +`cgp::core::field::traits` when calling it directly. Most code meets it indirectly, since `build_from` +uses it to pull each field out of the source. -Two more methods bracket the process. `builder()` produces the empty builder, and `into_builder()` goes the -other way, turning a finished struct into an all-present builder so its fields can be redistributed. +Two more methods sit at the ends of the process. `builder()` produces the empty builder, and +`into_builder()` goes the other way, turning a finished struct into an all-present builder so its fields +can be redistributed. ## Examples @@ -151,8 +153,8 @@ assert_eq!(partial.get_field(PhantomData::), "Alice"); Asking for `last_name` there would not compile, since that field's accessor is not in scope until it is set. -And a finished value can be taken apart and put back together, which is what generic code redistributing -fields does: +And a finished value can be taken apart and put back together, the operation generic code performs when it +redistributes fields: ```rust use cgp::core::field::traits::TakeField; @@ -188,7 +190,7 @@ case it exists for, and it is a narrower case than "this struct has several fiel Between this derive and its neighbours the choice is about how much of the machinery you want. -- **[`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpRecord)]`](./derive_cgp_data.md)** if the +- **[`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpRecord)]`](./derive_cgp_record.md)** if the struct also needs per-field reads or a whole-shape representation, which is the common case. Those include this output. - **`#[derive(BuildField)]` alone** when the struct is only ever built generically and never read @@ -244,7 +246,7 @@ impl FinalizeBuild for __PartialPerson { // only at all-p } ``` -Then, per field, an `UpdateField` impl — the primitive everything else is built from. It moves one field's +Then, per field, an `UpdateField` impl: the primitive everything else is built from. It moves one field's marker to a new state, returning the old value alongside the rebuilt companion: ```rust @@ -259,7 +261,7 @@ impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> ``` And, per field, a `HasField` impl on the companion that is in scope only when that field's marker is -`IsPresent`, which is what lets a set field be read back mid-build: +`IsPresent`, which lets a set field be read back mid-build: ```rust impl<__F1__: MapType> HasField for __PartialPerson { @@ -269,8 +271,8 @@ impl<__F1__: MapType> HasField for __PartialPerson` covers `UpdateField`, the absent-to-present move. So `build_field` is `update_field` in that one direction. @@ -278,12 +280,12 @@ the marker to move *to* — is what the derive actually writes: `FinalizeBuild` is likewise a library trait; the derive supplies only the all-present impl of it. -Two properties of the companion follow from how it is built — the derive clones your struct and renames it. +Two properties of the companion follow from how it is built: the derive clones your struct and renames it. It **keeps your visibility**, yours and each field's, so a `pub struct` yields a `pub struct __PartialPerson` with `pub` fields. But it **carries none of your attributes**: those are cleared, so a -`#[derive(Debug, Clone)]` on the record does not reach the companion. That is not an oversight — a field's -type is the projection `<__F0__ as MapType>::Map`, so a derived `Debug` would need bounds the macro has no -way to state — but it does mean a half-built value cannot be printed. +`#[derive(Debug, Clone)]` on the record does not reach the companion. That is not an oversight. A field's +type is the projection `<__F0__ as MapType>::Map`, so a derived `Debug` would need bounds the macro +has no way to state. But it does mean a half-built value cannot be printed. Each generated impl is aimed at the token it came from: a per-field impl at its field, a whole-struct impl at the struct name. @@ -314,7 +316,7 @@ still has to be set explicitly, unless you reach for number. **Field order does not matter, but field *names* are the whole interface.** `build_from` matches by name, so -renaming a field in one struct silently stops it being copied from the other — the result is a +renaming a field in one struct silently stops it being copied from the other. The result is a `finalize_build` that no longer resolves, reported at the finalize rather than at the rename. **It does not accept an enum.** The enum counterparts are diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 52f2a221..3c7fa7bc 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive(CgpData)]' +sidebar_position: 3 --- # `#[derive(CgpData)]` @@ -15,14 +16,14 @@ data types ends up written once per type. `#[derive(CgpData)]` is the one-line answer: it turns a struct or an enum into **extensible data**, a type whose fields or variants generic code can name, read, construct, and take apart without ever mentioning the concrete type. It is the umbrella derive, and what it generates depends entirely on what -it is applied to — on a struct it emits the record machinery, on an enum the variant machinery. +it is applied to: on a struct it emits the record machinery, on an enum the variant machinery. -The two things this buys are worth naming separately, because together they are what "extensible" means -here. The **representation** view describes the type as a list of named entries, which is what lets one +The two things this buys are worth naming separately, because together they define what "extensible" +means here. The **representation** view describes the type as a list of named entries, which lets one implementation serialize any record or dispatch over any enum. The **incremental** view adds a companion type that tracks, in its own type parameters, which fields are present or which variants are still -possible — so a half-built value and a finished one are *different types*, and using one where the other -belongs is a compile error rather than a runtime panic. +possible. A half-built value and a finished one are therefore *different types*, and using one where the +other belongs is a compile error rather than a runtime panic. ## Usage @@ -51,8 +52,8 @@ everything generated, including the companion types. ### What each shape emits, and where it is documented -The derive dispatches on the shape of its input and then runs one of two fixed sequences. Those two -sequences are what the shape-specific derives run, so each is documented on its own page rather than +The derive dispatches on the shape of its input and then runs one of two fixed sequences. The +shape-specific derives run those same two sequences, so each is documented on its own page rather than twice here: | Applied to | It emits | Documented on | @@ -67,7 +68,7 @@ one unnamed payload**, and there is no per-variant opt-out. ### Choosing among the three The three derives are interchangeable wherever the shape allows, so the choice is about what you want -the code to say. There is no output difference to weigh — `CgpData` on a struct emits exactly what +the code to say. There is no output difference to weigh: `CgpData` on a struct emits exactly what `CgpRecord` emits, and on an enum exactly what `CgpVariant` emits. - **`#[derive(CgpData)]`** is the default. Use it unless you have a reason not to. @@ -112,14 +113,14 @@ constructors, and an extractor. Worked examples of each half are on the **Reach for one of these derives when generic code has to work over the type's own structure.** That is the test, and it is narrower than it sounds. Most types in a CGP program want [`#[derive(HasField)]`](./derive_has_field.md) and nothing more, because most of what implementations -need from a context — the type a capability runs against, which supplies values as its fields — is to +need from a context (the type a capability runs against, which supplies values as its own fields) is to read one value out of it. The cases that do earn it are specific. - **A record assembled from independent pieces.** When several parts of a program each contribute part - of a struct and no one place should know the whole type, that is the extensible builder pattern and - this is what it runs on. + of a struct and no one place should know the whole type, that is the extensible builder pattern, and + this derive runs it. - **An enum handled one variant at a time by independent code.** When variants and the operations over them both need to grow without editing each other, this is the extensible visitor pattern. - **A framework over any user type.** A serializer, a validator, or a mapper written once against the @@ -151,7 +152,7 @@ give, and it is not free. Nothing about the umbrella is special. `#[derive(CgpData)]` inspects the item, dispatches on whether it is a struct or an enum, and then runs exactly the same code path the matching shape-specific derive -runs — [`#[derive(CgpRecord)]`](./derive_cgp_record.md#under-the-hood) enters the first directly and +runs. [`#[derive(CgpRecord)]`](./derive_cgp_record.md#under-the-hood) enters the first directly, and [`#[derive(CgpVariant)]`](./derive_cgp_variant.md#under-the-hood) the second. That shared dispatch is why all three agree on their output, and why a claim about what `CgpData` emits is always a claim about one of the other two. @@ -160,15 +161,16 @@ Applied to a union, all three fail: the family models products and sums, and a u ## Common Mistakes -**Which gotchas apply depends on the shape**, and the shape pages carry them: the -[record ones](./derive_cgp_record.md#common-mistakes) — the companion's cleared attributes, position-keyed tuple -builders, the newtype special case — and the [variant ones](./derive_cgp_variant.md#common-mistakes) — the -one-payload rule and the seven reserved variant names. Two are worth repeating here because they catch -people who reached for the umbrella without reading either. +**Which mistakes apply depends on the shape**, and the shape pages carry them. The +[record ones](./derive_cgp_record.md#common-mistakes) cover the companion's cleared attributes, +position-keyed tuple builders, and the newtype special case; the +[variant ones](./derive_cgp_variant.md#common-mistakes) cover the one-payload rule and the seven reserved +variant names. Two are worth repeating here because they catch people who reached for the umbrella +without reading either. **Every enum variant needs exactly one unnamed payload.** A unit, multi-field, or struct-style variant fails, with no per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in -the family that accepts all four shapes, so it is what an enum with mixed variants gets. +the family that accepts all four shapes, so an enum with mixed variants gets that derive instead. **Absence is spelled differently on the two sides.** `IsNothing` for a missing record field, `IsVoid` for a ruled-out variant, and they are not interchangeable. An error mentioning the wrong one usually means diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index 3e347bf2..19df9809 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive(CgpRecord)]' +sidebar_position: 4 --- # `#[derive(CgpRecord)]` @@ -14,11 +15,11 @@ struct. `#[derive(CgpRecord)]` turns a struct into **extensible data**: a type whose fields generic code can name, read, and assemble without ever mentioning the concrete type. It produces the whole record half -of the family in one line — per-field access, the whole-shape field list, and an incremental builder +of the family in one line: per-field access, the whole-shape field list, and an incremental builder that fills a value one field at a time. It is the struct-only face of [`#[derive(CgpData)]`](./derive_cgp_data.md). The two run the same code -and emit the same output on a struct; the difference is that this one **rejects an enum at parse +and emit the same output on a struct. The difference is that this one **rejects an enum at parse time**, so a type that is meant to stay a struct says so and the error arrives at the derive rather than further along. @@ -38,8 +39,8 @@ pub struct Person { **Every struct shape is accepted.** A named-field struct is keyed by [`Symbol!`](../macros/symbol.md), a tuple struct by [`Index`](../types/index.md), and a fieldless -struct is the degenerate case rather than an error — its companion type takes no parameters at all, so -`builder()` is immediately finalizable because there is nothing to track. +struct is the degenerate case rather than an error. Its companion type takes no parameters at all, so +`builder()` is immediately finalizable, because there is nothing to track. Generic parameters, lifetimes, and a `where` clause are carried onto everything generated, including the companion type. @@ -104,9 +105,10 @@ about what it emits. - **Use [`#[derive(HasField)]`](./derive_has_field.md) alone** when the fields are only ever read. That is most types in a CGP program, and it is one impl pair per field rather than a companion type and a dozen impls. -- **Derive the slice you want** — [`HasFields`](./derive_has_fields.md) for the representation, - [`BuildField`](./derive_build_field.md) for the builder — when only part of the output is wanted. The - umbrella is the right call once you want most of them. +- **Derive the slice you want** when only part of the output is wanted: + [`HasFields`](./derive_has_fields.md) for the representation, + [`BuildField`](./derive_build_field.md) for the builder. The umbrella is the right call once you want + most of them. The full argument for when a type earns the extensible-data machinery at all is on the [umbrella page](./derive_cgp_data.md#when-to-reach-for-it-and-when-not). @@ -123,7 +125,7 @@ pub struct Person { } ``` -it first emits the **per-field access** — a [`HasField`](../traits/has_field.md) and a +it first emits the **per-field access**: a [`HasField`](../traits/has_field.md) and a [`HasFieldMut`](../traits/has_field_mut.md) impl per field, exactly what [`#[derive(HasField)]`](./derive_has_field.md) produces on its own. @@ -168,8 +170,8 @@ missing impl rather than a runtime check. The per-field [`UpdateField`](../trait that move a marker, and the `HasField` impls on the companion that let a set field be read back, follow. The companion is named `__Partial{Name}` and keeps the original type's visibility, so a `pub` struct -yields a `pub` companion. Each generated impl is aimed at the token it came from — a per-field impl at -its field, a whole-type impl at the type name — so a conflict with a hand-written impl underlines that +yields a `pub` companion. Each generated impl is aimed at the token it came from (a per-field impl at +its field, a whole-type impl at the type name), so a conflict with a hand-written impl underlines that token rather than the whole derive. ## Common Mistakes @@ -182,9 +184,9 @@ be neither printed nor cloned. Read a set field back through the companion's **A tuple struct's builder is keyed by position.** Its companion exposes `UpdateField, _>` rather than symbol-keyed impls, so `build_field` takes `PhantomData::>`. -**A single-field tuple struct's representation is the inner type directly**, not a one-element product — -the newtype special case described on the [`#[derive(HasFields)]`](./derive_has_fields.md) page, which -this derive inherits. +**A single-field tuple struct's representation is the inner type directly**, not a one-element product. +This is the newtype special case described on the [`#[derive(HasFields)]`](./derive_has_fields.md) page, +which this derive inherits. **A fieldless struct compiles and does nothing useful.** It yields a parameterless companion whose `builder()` is immediately finalizable. diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 83c88f51..1c44cc51 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive(CgpVariant)]' +sidebar_position: 5 --- # `#[derive(CgpVariant)]` @@ -9,16 +10,16 @@ The extensible-data derive for an enum. ## Overview A plain Rust enum is opaque to generic code. There is no way to refer to "the `Circle` variant" through -a type parameter, so anything that must work across several enums ends up written once per enum — and +a type parameter, so anything that must work across several enums ends up written once per enum, and the `match` that would make it exhaustive can only be written where the concrete enum is named. `#[derive(CgpVariant)]` turns an enum into **extensible data**: a type whose variants generic code can name, construct, and take apart without ever mentioning the concrete type. It produces the whole -variant half of the family in one line — the whole-shape variant list, a constructor per variant, and an -incremental extractor that peels variants off one at a time while tracking which are still possible. +variant half of the family in one line: the whole-shape variant list, a constructor per variant, and an +incremental extractor that removes variants one at a time while tracking which are still possible. It is the enum-only face of [`#[derive(CgpData)]`](./derive_cgp_data.md). The two run the same code and -emit the same output on an enum; the difference is that this one **rejects a struct at parse time**. +emit the same output on an enum. The difference is that this one **rejects a struct at parse time**. ## Usage @@ -42,7 +43,7 @@ and a `where` clause are carried onto everything generated, including the compan **This is the family's one real restriction.** It comes from the two slices that take an enum apart: each has to name a single type per variant, and a unit, multi-field, or struct-style variant gives it none or several. Such a variant fails with `Expected variant to contain exactly one unnamed field`, and -there is **no way to opt one variant out** — an enum that mixes shapes cannot take this derive at all. +there is **no way to opt one variant out**. An enum that mixes shapes cannot take this derive at all. The fix is to wrap the richer payload in its own struct, so the variant's value stays a single nameable type: @@ -64,14 +65,13 @@ pub enum Shape { } ``` -That is idiomatic rather than a workaround — the payload struct usually wants to be a type in its own +That is idiomatic rather than a workaround. The payload struct usually wants to be a type in its own right, and it can derive [`#[derive(CgpRecord)]`](./derive_cgp_record.md) too, which is how a nested shape becomes reachable. -One escape hatch is worth knowing: [`#[derive(HasFields)]`](./derive_has_fields.md) accepts **all four** +One exception is worth knowing: [`#[derive(HasFields)]`](./derive_has_fields.md) accepts **all four** variant shapes, because it only describes a variant rather than deconstructing it. So an enum with mixed -variants can still have a structural representation; what it cannot have is the generic constructor or -the extractor. +variants can still have a structural representation, but not the generic constructor or the extractor. ### What it generates @@ -113,8 +113,8 @@ fn area(shape: Shape) -> f64 { There is no wildcard arm and no `unreachable!()`. After the second extraction the remainder's type has both variants ruled out, which makes it uninhabited, and -[`finalize_extract_result`](../traits/finalize_extract_result.md) is what discharges a value that cannot -exist. Add a third variant to `Shape` and this function stops compiling until it is handled — the same +[`finalize_extract_result`](../traits/finalize_extract_result.md) discharges a value that cannot exist. +Add a third variant to `Shape` and this function stops compiling until it is handled, which is the same guarantee a concrete `match` gives, recovered for code that never names the enum. ## When to reach for it, and when not @@ -128,9 +128,9 @@ guarantee a concrete `match` gives, recovered for code that never names the enum - **Prefer a `match`** for a closed enum with fixed operations. It is clearer than any machinery and it already gives exhaustiveness. Reach for the variant derives when the variant set is open, or when independent modules must each contribute a variant or an operation over one. -- **Derive the slice you want** — [`FromVariant`](./derive_from_variant.md) alone if code only needs to - *construct*, [`ExtractField`](./derive_extract_field.md) alone if it only needs to deconstruct, - [`HasFields`](./derive_has_fields.md) alone for the shape, and it is the only one of the three that +- **Derive the slice you want**: [`FromVariant`](./derive_from_variant.md) alone if code only needs to + *construct*, [`ExtractField`](./derive_extract_field.md) alone if it only needs to deconstruct, and + [`HasFields`](./derive_has_fields.md) alone for the shape, which is the only one of the three that accepts every variant shape. The full argument for when a type earns the extensible-data machinery at all is on the @@ -175,7 +175,7 @@ impl FromVariant for Shape { ``` Then the **extractor**, which is [`#[derive(ExtractField)]`](./derive_extract_field.md)'s output and -where two companion enums appear — `__PartialShape` for owned extraction and `__PartialRefShape` for +where two companion enums appear: `__PartialShape` for owned extraction and `__PartialRefShape` for borrowed. A variant's payload is wrapped in a [`MapType`](../traits/map_type.md) marker that is either `IsPresent` or `IsVoid`, the latter mapping it to the uninhabited `Void`: @@ -198,7 +198,7 @@ impl FinalizeExtract for __PartialShape { // nothing left: un **Note the asymmetry with the record side, which is the detail most worth carrying away: a record uses `IsNothing` for a field that is not there, and a variant uses `IsVoid` for one that has been ruled out.** `IsNothing` maps a type to `()`, which is inhabited; `IsVoid` maps it to `Void`, which is not. That is -exactly why extraction ends the way it does — once every variant is `IsVoid` the whole companion enum is +exactly why extraction ends the way it does: once every variant is `IsVoid` the whole companion enum is uninhabited, so a value of it cannot exist and can be discharged to produce anything. The companion names are reserved: `__Partial{Name}` and `__PartialRef{Name}`. They keep the original @@ -209,7 +209,7 @@ hand-written impl underlines that variant rather than the whole derive. **Every variant needs exactly one unnamed payload**, with no per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in the family that accepts all four -shapes, so it is what an enum with mixed variants gets. +shapes, so an enum with mixed variants gets that derive instead. **Seven variant names are reserved.** Because the generated impls name their associated types through `Self::…`, a variant called `Fields`, `FieldsRef`, `Value`, `Remainder`, `Extractor`, `ExtractorRef`, or @@ -221,7 +221,7 @@ variant is the fix. Record field names are unaffected, since a field is not in t associated type. **The companion enums carry none of your attributes.** The derive clears them, so an extraction -remainder is neither `Debug` nor `PartialEq` however the enum is derived — `assert_eq!` over a +remainder is neither `Debug` nor `PartialEq` however the enum is derived. `assert_eq!` over a `Result` does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. **Absence is spelled differently on the two sides.** `IsVoid` for a ruled-out variant, `IsNothing` for a diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 570cde46..81271d7e 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive(ExtractField)]' +sidebar_position: 7 --- # `#[derive(ExtractField)]` @@ -8,9 +9,10 @@ Extractor support for a variant. ## Overview -A `match` on an enum is checked for exhaustiveness, which is one of Rust's best properties — and it only +A `match` on an enum is checked for exhaustiveness, which is one of Rust's best properties. But it only works where the concrete enum is named. Code that is generic over the enum cannot write a `match`, so it -falls back on a wildcard arm and an `unreachable!()`, which is precisely the guarantee you wanted to keep. +falls back on a wildcard arm and an `unreachable!()`, discarding exactly the guarantee you wanted to +keep. `#[derive(ExtractField)]` recovers it. It lets an enum be taken apart one variant at a time, and it tracks which variants are still possible **in the type**. Each attempt either yields the payload or hands back a @@ -24,13 +26,12 @@ match shape.to_extractor().extract_field(PhantomData::) { ``` Keep going and the remainder narrows each time. Once every variant has been ruled out, the remainder's type -is **uninhabited** — a value of it cannot exist — and that is what closes the chain with no wildcard arm and -no panic path. Add a variant to the enum and the final remainder becomes inhabited again, so the code stops -compiling until the new variant is handled. The exhaustiveness check survives, for code that never names the -enum. +is **uninhabited** (a value of it cannot exist), and that closes the chain with no wildcard arm and no panic +path. Add a variant to the enum and the final remainder becomes inhabited again, so the code stops compiling +until the new variant is handled. The exhaustiveness check survives, for code that never names the enum. -The mirror image on the struct side is [`#[derive(BuildField)]`](./derive_build_field.md), which tracks which -fields are present rather than which variants are possible. Both are what "extensible" means in +The struct-side counterpart is [`#[derive(BuildField)]`](./derive_build_field.md), which tracks which +fields are present rather than which variants are possible. Both show what "extensible" means in [extensible data](/docs/concepts/extensible-variants): the type carries the progress, so the compiler checks it. @@ -82,7 +83,7 @@ pub enum Shape { } ``` -That is idiomatic rather than a concession — the payload usually deserves to be a type, and it can derive the +That is idiomatic rather than a concession. The payload usually deserves to be a type, and it can derive the extensible-data machinery itself. Note that even a fieldless case has to be given a payload struct, since a bare `Empty` is a unit variant. @@ -95,7 +96,7 @@ The derive parses an enum, so applying it to a struct fails at parse time. The s ### What it does *not* generate -Deriving this slice alone gives you deconstruction and nothing else — **no** whole-shape representation and +Deriving this slice alone gives you deconstruction and nothing else: **no** whole-shape representation and **no** generic constructors. Those come from [`#[derive(HasFields)]`](./derive_has_fields.md) and [`#[derive(FromVariant)]`](./derive_from_variant.md), and the umbrella [`#[derive(CgpData)]`](./derive_cgp_data.md) includes all three. So an enum deriving only `ExtractField` is @@ -144,7 +145,7 @@ fn area(shape: Shape) -> f64 { ``` The second `extract_field` returns a `Result` whose error type is uninhabited, so -`finalize_extract_result` collapses it to the value with nothing to handle. That is not a convention — it is +`finalize_extract_result` collapses it to the value with nothing to handle. That is not a convention. It is the type. Try to finalize after only the first extraction and it does not compile, because `Rectangle` is still possible. @@ -171,7 +172,7 @@ if let Ok(circle) = shape In practice you rarely write these chains by hand. The [dispatch combinators](../providers/dispatch_combinators.md) build them for you from a set of per-variant -implementations, which is the extensible visitor pattern — a chain like the one above, generated, with one +implementations, which is the extensible visitor pattern: a chain like the one above, generated, with one implementation per variant chosen by wiring. ## When to reach for it, and when not @@ -180,20 +181,19 @@ implementation per variant chosen by wiring. matching cannot name the enum.** Those are the two cases, and outside them a `match` wins on every count. - **Reach for it for the extensible visitor pattern.** When variants and the operations over them both need - to grow without editing each other, per-variant implementations plus a dispatcher is what this derive is - for. + to grow without editing each other, this derive supports per-variant implementations plus a dispatcher. - **Reach for it when the enum is a type parameter.** Generic code cannot `match`, so the extractor is the only route to an exhaustiveness guarantee. - **Do not reach for it for a closed enum with fixed operations.** A `match` is shorter, reads better, - already gives exhaustiveness, and generates nothing. This derive is not an improvement on `match`; it is - what you use when `match` is unavailable. + already gives exhaustiveness, and generates nothing. This derive is not an improvement on `match`; you use + it when `match` is unavailable. - **Do not reach for it to test which variant a value holds.** `matches!` or an `if let` answers that in one line. The extractor's value is in the *chain* and what the chain proves. Between this derive and its neighbours: -- **[`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpVariant)]`](./derive_cgp_data.md)** if the - enum also needs a structural representation or generic construction, which is the common case — those +- **[`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpVariant)]`](./derive_cgp_variant.md)** if the + enum also needs a structural representation or generic construction, which is the common case. Those include this output. - **`#[derive(ExtractField)]` alone** when the enum is only ever deconstructed generically. - **[`#[derive(FromVariant)]`](./derive_from_variant.md)** is the opposite direction, and the two are often @@ -209,8 +209,8 @@ derive you did not need. The derive centres on **two** companion enums. `__Partial{Name}` is your enum with one [`MapType`](../traits/map_type.md) parameter added per variant and each payload wrapped in that parameter's projection, where `IsPresent` keeps the payload and `IsVoid` maps it to the uninhabited `Void`. -`__PartialRef{Name}` adds a reserved `'__a__` lifetime and a second marker that selects a shared or a mutable borrow of each -payload. From: +`__PartialRef{Name}` adds a reserved `'__a__` lifetime and a second marker that selects a shared or a mutable +borrow of each payload. From: ```rust #[derive(ExtractField)] @@ -254,7 +254,7 @@ impl HasExtractorRef for Shape { ``` The exit is the impl the whole design turns on. It exists only for the all-`IsVoid` configuration, and -because that configuration is uninhabited its body is an empty `match` — which is why it can claim to return +because that configuration is uninhabited its body is an empty `match`, which is why it can claim to return *any* type: ```rust @@ -282,17 +282,16 @@ impl<__F1__: MapType> ExtractField for __PartialShape` into `T`. **The variantless enum is genuinely special-cased**, and the reason is a Rust subtlety worth knowing. Such an enum borrows nothing, so the ref companion is emitted as a bare empty enum with neither the lifetime nor the -borrow marker — leaving them in would make both unused parameters. And every borrowed accessor matches +borrow marker. Leaving them in would make both unused parameters. And every borrowed accessor matches `*self` rather than `self`, because a reference is always considered inhabited even when its target is not, so `match self {}` on a `&Self` would be rejected as non-exhaustive. @@ -302,13 +301,13 @@ at the enum name. The companion enums are cloned from yours, so their tokens alr ## Common Mistakes **Every variant must carry exactly one unnamed payload.** A unit, multi-field, or struct-style variant fails, -with no per-variant opt-out. Wrap the payload in its own struct — including for a case that carries nothing, +with no per-variant opt-out. Wrap the payload in its own struct, including for a case that carries nothing, which still needs a payload type. [`#[derive(HasFields)]`](./derive_has_fields.md) is the derive that accepts all four shapes. **Absence here is `IsVoid`, not `IsNothing`.** The record side uses `IsNothing`, which maps a type to `()` -and is inhabited; a ruled-out variant uses `IsVoid`, which maps to the uninhabited `Void`. That difference is -load-bearing rather than cosmetic — it is why a fully-narrowed remainder cannot exist and can be discharged. +and is inhabited; a ruled-out variant uses `IsVoid`, which maps to the uninhabited `Void`. That difference +matters rather than being cosmetic: it is why a fully-narrowed remainder cannot exist and can be discharged. An error naming the wrong marker usually means record and variant machinery have been crossed. **Five variant names are reserved, and using one does not compile.** The generated impls write @@ -317,8 +316,9 @@ their associated types, so a variant with any of those names makes the path ambi `ambiguous associated item`, and this is the opaque one in the family: both the headline *and* the "could refer to the variant defined here" note land on the derive, so nothing in the output names the variant to rename. That is because these impls are generated for the companion enums rather than for -yours. Check your variant names against the five above. Renaming the variant is the fix. [`#[derive(HasFields)]`](./derive_has_fields.md) reserves `Fields` -and `FieldsRef` for the same reason, so an enum deriving the whole family should avoid all seven. +yours. Check your variant names against the five above. Renaming the variant is the fix. +[`#[derive(HasFields)]`](./derive_has_fields.md) reserves `Fields` and `FieldsRef` for the same reason, so an +enum deriving the whole family should avoid all seven. **A remainder carries none of the enum's attributes.** Like the record side's companion, the partial enums are generated without your derives, so a `Result` cannot be compared or printed as a @@ -332,7 +332,7 @@ while any marker is still `IsPresent`, so the compiler reports a missing method. the message to see which variants are still possible. **The order of extraction is free but the set is not.** Each step only changes its own variant's marker, so -you may extract in any order — but you must extract *every* variant before the remainder can be finalized. +you may extract in any order. But you must extract *every* variant before the remainder can be finalized. **Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the reason to prefer the [dispatch combinators](../providers/dispatch_combinators.md), which derive the chain from the diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 145b7abc..f615e9d0 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive(FromVariant)]' +sidebar_position: 8 --- # `#[derive(FromVariant)]` @@ -9,7 +10,7 @@ Generic construction of an enum from one of its named variants. ## Overview `Shape::Circle(circle)` names two things: the enum, and the variant. That is fine at a concrete call site and -useless to code that knows neither — a routine that has been handed a value and told which variant to wrap it +useless to code that knows neither: a routine that has been handed a value and told which variant to wrap it in cannot write that expression. `#[derive(FromVariant)]` gives it a way to. The derive adds one constructor per variant, addressed by the @@ -23,7 +24,7 @@ That call is equivalent to `Shape::Circle(circle)`. The difference is that the t parameter, so one function can build whichever variant it was asked for, of whichever enum. **This is the simplest derive in the extensible-data family.** It generates no companion type, no state -tracking, and no traits of its own — just a constructor per variant. It is the counterpart to +tracking, and no traits of its own: just a constructor per variant. It is the counterpart to [`#[derive(ExtractField)]`](./derive_extract_field.md), which takes a variant out; this one puts a variant in. ## Usage @@ -51,7 +52,7 @@ variant, a multi-field tuple variant, and a struct-style variant all fail with `Expected variant to contain exactly one unnamed field`. There is no per-variant opt-out, so an enum that mixes shapes cannot take this derive. -Wrapping the payload in its own struct is the fix, and it is what idiomatic CGP enums do anyway: +Wrapping the payload in its own struct is the fix, and idiomatic CGP enums do it anyway: ```rust pub struct Circle { @@ -68,8 +69,8 @@ If the enum only needs to be *described* rather than constructed, [`#[derive(HasFields)]`](./derive_has_fields.md) accepts all four variant shapes instead. A variantless enum is accepted here and simply produces no impls. -The derive parses an enum, so applying it to a struct fails at parse time. The struct analogue — setting one -field of a value being assembled — is [`#[derive(BuildField)]`](./derive_build_field.md). +The derive parses an enum, so applying it to a struct fails at parse time. The struct analogue, setting one +field of a value being assembled, is [`#[derive(BuildField)]`](./derive_build_field.md). ### What it does *not* generate @@ -109,9 +110,9 @@ let rect = wrap(PhantomData::, Rectangle { width: 3.0, hei No hand-written function can do that, because `Shape::Circle` and `Shape::Rectangle` are different expressions taking different types. -Where this earns its keep in practice is building a value using only the variants an implementation knows -about, then widening it. A routine that only produces two of a large enum's variants declares a small local -enum, constructs into that, and lifts the result into the full type with an upcast: +In practice this earns its keep when building a value using only the variants an implementation knows about, +then widening it. A routine that only produces two of a large enum's variants declares a small local enum, +constructs into that, and lifts the result into the full type with an upcast: ```rust use cgp::core::field::impls::CanUpcast; // not in the prelude @@ -119,7 +120,7 @@ use cgp::core::field::impls::CanUpcast; // not in the prelude let expr = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); ``` -The upcast always succeeds, because every variant of the smaller enum has a home in the larger one. That is +The upcast always succeeds, because every variant of the smaller enum maps to one in the larger one. That is the construction-side counterpart of reading a field through a getter: the implementation names only what it needs, and the widening is checked. Upcasting is documented with the other [structural casts](../traits/can_upcast.md), and it is built on the same per-variant machinery as this derive. @@ -127,28 +128,28 @@ needs, and the widening is checked. Upcasting is documented with the other ## When to reach for it, and when not **Derive it when code that does not name a variant has to construct one.** That is the whole test, and it is -a narrower need than deconstruction — most code decides which variant to build at a site that can just name +a narrower need than deconstruction. Most code decides which variant to build at a site that can just name it. - **Reach for it when the variant is chosen by a type parameter.** A routine parameterized over the variant it produces has no other option. - **Reach for it to make a smaller enum upcastable into a larger one.** Casting between enums is built on - these constructors, so this derive is what lets an implementation work in a narrow local enum and widen the + these constructors, so this derive lets an implementation work in a narrow local enum and widen the result. - **Do not reach for it for an ordinary constructor call.** `Shape::Circle(circle)` is shorter, clearer, and generates nothing. This derive adds a *second* way to do the same thing, for callers that cannot use the first. -- **Do not derive it alone if you also want to take the enum apart**, which is the usual case — reach for - [`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpVariant)]`](./derive_cgp_data.md), which +- **Do not derive it alone if you also want to take the enum apart**, which is the usual case. Reach for + [`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpVariant)]`](./derive_cgp_variant.md), which bundle construction, deconstruction, and the representation. -Between the constructor and the extractor the split is exactly what the names say: this derive puts a value +The constructor and the extractor divide exactly as their names suggest: this derive puts a value into an enum, [`#[derive(ExtractField)]`](./derive_extract_field.md) gets one out, and they are commonly derived together because a generic pipeline usually does both. ## Under the hood -The derive emits **one impl per variant and nothing else** — no companion type, no markers, no state. From: +The derive emits **one impl per variant and nothing else**: no companion type, no markers, no state. From: ```rust #[derive(FromVariant)] @@ -178,9 +179,9 @@ impl FromVariant for Shape { } ``` -Each body is the plain constructor call. What the impl adds is that the *choice* between them is now a type -argument, and that the payload type is reachable as `>::Value` — which is what lets -a generic signature name it without knowing which variant is in play. +Each body is the plain constructor call. The impl adds two things: the *choice* between them is now a type +argument, and the payload type is reachable as `>::Value`, which lets a generic +signature name it without knowing which variant is in play. The `PhantomData` parameter carries no value. It exists so a call site can say which impl it means when several are in scope, which is why the tag is passed as `PhantomData::` rather than @@ -207,10 +208,10 @@ for the previous point, and it means a mistyped tag is a missing-impl error rath `Symbol!("circle")` are unrelated types, so a case slip reports as an unsatisfied `FromVariant` bound. **A variant named `Value` does not compile.** The generated body writes `Self::Value` to name the payload -type, and a variant of that name makes the path ambiguous — the compiler reports -`ambiguous associated item` with its headline on the derive and a note pointing at the offending variant. `Value` is the only name -this derive reserves; the [extractor](./derive_extract_field.md) reserves several more, so an enum taking -both should avoid all of them. Renaming the variant is the fix. +type, and a variant of that name makes the path ambiguous. The compiler reports +`ambiguous associated item` with its headline on the derive and a note pointing at the offending variant. +`Value` is the only name this derive reserves; the [extractor](./derive_extract_field.md) reserves several +more, so an enum taking both should avoid all of them. Renaming the variant is the fix. **A variantless enum produces nothing**, silently. The derive succeeds and emits no impls, which is correct and, as with the other empty shapes, means a mistake shows up later rather than here. diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index f71dcf6a..333513f0 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive(HasField)]' +sidebar_position: 1 --- # `#[derive(HasField)]` @@ -8,27 +9,27 @@ Per-field accessors keyed by a type-level tag. ## Overview -An implementation written against a **context** — the type the capability runs against, which supplies the -values it needs as its fields — cannot name that context's concrete type. It is generic over it, so -`self.name` is not something it can write. Yet reading a field out of the context is the most common thing -such an implementation does. +An implementation written against a **context** cannot name that context's concrete type. The context +is the type the capability runs against, and it supplies the values the implementation needs as its own +fields. Because the implementation is generic over the context, it cannot write `self.name`. Yet reading +a field out of the context is the most common thing such an implementation does. -`#[derive(HasField)]` is what closes that gap. It gives each of a struct's fields a *type-level name*, so an -implementation can ask for "a `String` field called `name`" as an ordinary trait bound and receive the field -without knowing what type it came from: +`#[derive(HasField)]` closes that gap. It gives each of a struct's fields a *type-level name*, so an +implementation can ask for "a `String` field called `name`" as an ordinary trait bound and receive the +field without knowing what type it came from: ```rust Self: HasField ``` -Any struct that derives `HasField` and happens to have such a field satisfies that bound. Nothing is matched -by string at runtime — [`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler resolves the -lookup during compilation and the read compiles down to a direct field access. +Any struct that derives `HasField` and happens to have such a field satisfies that bound. Nothing is +matched by string at runtime. [`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler +resolves the lookup during compilation and the read compiles down to a direct field access. -**You will derive this constantly and almost never name `HasField` by hand.** It is the foundation the -ergonomic surface stands on: an [`#[implicit]`](../attributes/implicit.md) argument, a +**You will derive this constantly and almost never name `HasField` by hand.** It is the foundation of +the ergonomic surface: an [`#[implicit]`](../attributes/implicit.md) argument, a [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method, and a [`UseField`](../providers/use_field.md) -wiring entry all generate the bound above from a name you already wrote. What you write is the derive on the +wiring entry all generate the bound above from a name you already wrote. You write only the derive on the struct. ## Usage @@ -43,29 +44,29 @@ pub struct Person { } ``` -It accepts any struct shape. What differs between them is only how each field's tag is computed. +It accepts any struct shape. The shapes differ only in how each field's tag is computed. ### Named fields A named field is keyed by [`Symbol!`](../macros/symbol.md), the type-level string of its identifier. The struct above gains access keyed by `Symbol!("name")` and `Symbol!("age")`. -A field written as a [raw identifier](https://doc.rust-lang.org/reference/identifiers.html) is keyed by its -*logical* name, with the `r#` stripped — a field `r#type` is keyed by `Symbol!("type")`, not +A field written as a [raw identifier](https://doc.rust-lang.org/reference/identifiers.html) is keyed by +its *logical* name, with the `r#` stripped: a field `r#type` is keyed by `Symbol!("type")`, not `Symbol!("r#type")`. The generated accessor still borrows the real field. ### Tuple fields -A tuple field has no name, so it is keyed by [`Index`](../types/index.md), the type-level number of its -position: +A tuple field has no name, so it is keyed by [`Index`](../types/index.md), the type-level number of +its position: ```rust #[derive(HasField)] pub struct Rectangle(pub f64, pub f64); ``` -`Rectangle` gains access keyed by `Index<0>` and `Index<1>`. A tuple field is never keyed by a `Symbol!` of -its position — `Index<0>` and `Symbol!("0")` are different types. +`Rectangle` gains access keyed by `Index<0>` and `Index<1>`. A tuple field is never keyed by a `Symbol!` +of its position, because `Index<0>` and `Symbol!("0")` are different types. ### Unit structs @@ -77,14 +78,15 @@ rather than reporting an error: pub struct App; ``` -This is worth knowing because it is silent. Deriving `HasField` on a fieldless context is harmless and does -nothing, which is the right outcome — such a context carries choices rather than data — but it also means a -mistake that leaves a struct fieldless produces no complaint here, only an unsatisfied bound later. +This is worth knowing because it is silent. Deriving `HasField` on a fieldless context is harmless and +does nothing. That is the right outcome, since such a context carries choices rather than data. But it +also means a mistake that leaves a struct fieldless produces no complaint here, only an unsatisfied bound +later. ### Generic structs -Generic parameters, lifetimes, and a `where` clause are all carried onto the generated access, so a generic -struct works with no extra ceremony: +Generic parameters, lifetimes, and a `where` clause are all carried onto the generated access, so a +generic struct works with no extra work: ```rust #[derive(HasField)] @@ -99,13 +101,13 @@ pub struct Wrapper { The derive parses its input as a struct, so applying it to an enum or a union fails at parse time. The whole-shape view of a struct *or* an enum is a different derive, -[`#[derive(HasFields)]`](./derive_has_fields.md) — note the plural — and the two are frequently derived +[`#[derive(HasFields)]`](./derive_has_fields.md) (note the plural), and the two are frequently derived together. ## Examples -An implementation states the field it needs as a bound, and the derive is what lets a concrete context -satisfy it. First the implementation, asking for a `String` field called `name`: +An implementation states the field it needs as a bound, and the derive lets a concrete context satisfy +it. First the implementation, asking for a `String` field called `name`: ```rust use cgp::prelude::*; @@ -143,7 +145,7 @@ delegate_components! { Because `Person` derives `HasField`, it satisfies exactly the bound `GreetHello` requires, so `person.greet()` compiles and prints the person's name. Remove the `name` field and the wiring stops -compiling — the requirement is checked, not assumed. +compiling: the requirement is checked, not assumed. **Written idiomatically, none of that bound is visible.** The same read is an [`#[implicit]`](../attributes/implicit.md) argument, which looks like an ordinary function parameter: @@ -157,43 +159,41 @@ impl Greeter { } ``` -That version generates the same `HasField` bound and the same field read. The explicit form above is what -you *read* — in generated code, in a compiler error — rather than what you write. +That version generates the same `HasField` bound and the same field read. You *read* the explicit form +above in generated code or in a compiler error; you do not write it. Field access also passes through smart pointers with no extra derive. `Box` and any newtype that -dereferences to `Person` resolve a field read to the inner struct, so wrapping a context does not break the -implementations that read from it. +dereferences to `Person` resolve a field read to the inner struct, so wrapping a context does not break +the implementations that read from it. ## When to reach for it, and when not **Derive it on every context whose fields an implementation reads.** There is little judgement here: the -derive is how a struct's fields become visible to the trait system, it costs one line, and every construct -that reads a field needs it. A context that derives nothing can still be wired and can still implement -consumer traits — it just cannot supply values. +derive is how a struct's fields become visible to the trait system, it costs one line, and every +construct that reads a field needs it. A context that derives nothing can still be wired and can still +implement consumer traits. It just cannot supply values. -What *is* a judgement call is how you read the field once the derive is in place, and the ordering is -settled. +The judgement call is how you read the field once the derive is in place, and the ordering is settled. - **Use an [`#[implicit]`](../attributes/implicit.md) argument by default.** It reads a field of the - implementation's own context as a plain parameter, with no trait to declare. This covers the common case, - including a field that several implementations each read. + implementation's own context as a plain parameter, with no trait to declare. This covers the common + case, including a field that several implementations each read. - **Use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) when the read needs to be a named capability**, when the field lives on a type other than the context, or when the getter should carry a - type inferred from the field — the three cases an implicit argument cannot reach. -- **Write the `HasField` bound by hand only when neither fits**, which is rare. When you do, remember it is - an ordinary trait bound and can carry `Value = T` to pin the field's type. + type inferred from the field. Those are the three cases an implicit argument cannot reach. +- **Write the `HasField` bound by hand only when neither fits**, which is rare. When you do, remember it + is an ordinary trait bound and can carry `Value = T` to pin the field's type. - **Reach for [`#[derive(HasFields)]`](./derive_has_fields.md) instead when code must process the whole - shape** rather than one named field — serializing a struct, folding over its fields, building it + shape** rather than one named field: serializing a struct, folding over its fields, building it generically. The two answer different questions and are often derived together. -One thing this derive is not: it is **not** what makes a struct an extensible record. It gives indexed -access to fields that already exist. Building a struct up field by field is -[`#[derive(BuildField)]`](./derive_build_field.md), and the umbrella that includes both is -[`#[derive(CgpData)]`](./derive_cgp_data.md). +This derive does **not** make a struct an extensible record. It gives indexed access to fields that +already exist. Building a struct up field by field is [`#[derive(BuildField)]`](./derive_build_field.md), +and [`#[derive(CgpData)]`](./derive_cgp_data.md) is the umbrella that includes both. ## Under the hood -The derive leaves the struct definition untouched and adds **two impls per field** — a read accessor and a +The derive leaves the struct definition untouched and adds **two impls per field**: a read accessor and a mutable one. From this input: ```rust @@ -204,7 +204,8 @@ pub struct Person { } ``` -it produces, for each field, the field's type as the associated `Value` and a body that simply borrows it: +it produces, for each field, the field's type as the associated `Value` and a body that simply borrows +it: ```rust impl HasField for Person { @@ -224,10 +225,10 @@ impl HasFieldMut for Person { // and the same pair for `age`, with `Value = u8` ``` -The `PhantomData` parameter carries no value. It exists so a call site can say *which* field it means -when several `HasField` impls are in scope, which is what `PhantomData::` at a call site is -doing. [`HasFieldMut`](../traits/has_field.md) extends `HasField` with `get_field_mut`; it is always -generated alongside the read accessor, whether or not anything uses it. +The `PhantomData` parameter carries no value. It exists so a call site can say *which* field it +means when several `HasField` impls are in scope, which is why a call site writes +`PhantomData::`. [`HasFieldMut`](../traits/has_field_mut.md) extends `HasField` with +`get_field_mut`, and it is always generated alongside the read accessor, whether or not anything uses it. A tuple struct produces the same shape with a positional tag: @@ -241,36 +242,36 @@ impl HasField> for Rectangle { } ``` -A generic struct has its parameters split into impl-position generics, type arguments, and a `where` clause -and threaded onto every impl, so `struct Wrapper { value: T }` yields -`impl HasField for Wrapper` with `Value = T`. A struct lifetime carries through the -same way, and a borrowed field type is kept verbatim as `Value`. +A generic struct has its parameters split into impl-position generics, type arguments, and a `where` +clause and threaded onto every impl, so `struct Wrapper { value: T }` yields +`impl HasField for Wrapper` with `Value = T`. A struct lifetime carries through +the same way, and a borrowed field type is kept verbatim as `Value`. -**The smart-pointer behaviour comes from the library, not the derive.** `HasField` and `HasFieldMut` carry -blanket impls for any type whose [`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) target -implements them, which is what lets `Box` resolve a field read to the inner struct. Those blanket -impls are marked so the compiler does not suggest them in a diagnostic, which keeps a missing-field error +**The smart-pointer behaviour comes from the library, not the derive.** `HasField` and `HasFieldMut` +carry blanket impls for any type whose [`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) +target implements them, so `Box` resolves a field read to the inner struct. Those blanket impls +are marked so the compiler does not suggest them in a diagnostic, which keeps a missing-field error pointed at the struct that lacks the field rather than at the pointer. -Each generated impl is also aimed at the field it came from, so a compiler error about one field's access — -a conflict with a hand-written impl, or the "but the trait is implemented for" hint inside a missing-field -error — underlines that field rather than the whole `#[derive(HasField)]`. +Each generated impl is also aimed at the field it came from, so a compiler error about one field's access +underlines that field rather than the whole `#[derive(HasField)]`. That covers a conflict with a +hand-written impl, and the "but the trait is implemented for" hint inside a missing-field error. ## Common Mistakes -**A unit struct produces nothing, silently.** There is no field to key, so the derive succeeds and emits no -impls. That is correct, but it means the mistake surfaces later, as an unsatisfied `HasField` bound at a -wiring site rather than as a complaint on the struct. +**A unit struct produces nothing, silently.** There is no field to key, so the derive succeeds and emits +no impls. That is correct, but it means the mistake surfaces later, as an unsatisfied `HasField` bound at +a wiring site rather than as a complaint on the struct. **Two spellings of a field name are unrelated types.** `Symbol!("first_name")` and `Symbol!("firstName")` -have nothing to do with each other, and a mismatch is reported as a missing `HasField` bound rather than as -a typo. This is the usual cause of a read that "should" work. +have nothing to do with each other, and a mismatch is reported as a missing `HasField` bound rather than +as a typo. This is the usual cause of a read that "should" work. **A raw-identifier field is tagged without the `r#`.** The tag for `r#type` is `Symbol!("type")`, so `Symbol!("r#type")` matches nothing. -**A tuple field is keyed by `Index`, never by a `Symbol!` of the number.** `Index<0>` and `Symbol!("0")` -are different types, and only the first is generated. +**A tuple field is keyed by `Index`, never by a `Symbol!` of the number.** `Index<0>` and +`Symbol!("0")` are different types, and only the first is generated. **The mutable accessor is always generated.** There is no way to derive read-only access. If a field must not be mutated by an implementation, that is a matter of what the implementations declare rather than diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index d07d0233..b3325752 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -1,5 +1,6 @@ --- sidebar_label: '#[derive(HasFields)]' +sidebar_position: 2 --- # `#[derive(HasFields)]` @@ -8,14 +9,14 @@ The whole-struct or whole-enum field-list view. ## Overview -Some code needs one field of a type. Other code needs the *shape* of the type: every field, its name, and -its type, so it can walk them. A serializer, a validator, a builder that merges two structs, a dispatcher -that routes an enum to a handler per variant — none of these can be written against one field at a time, and -none of them can name the concrete type either. +Some code needs one field of a type. Other code needs the *shape* of the type: every field, its name, +and its type, so it can walk them. A serializer, a validator, a builder that merges two structs, a +dispatcher that routes an enum to a handler per variant: none of these can be written against one field +at a time, and none of them can name the concrete type either. `#[derive(HasFields)]` gives a type that shape as a single associated type. Where -[`#[derive(HasField)]`](./derive_has_field.md) — singular — answers "give me *this* field", -`HasFields` answers "describe *all* of them at once": +[`#[derive(HasField)]`](./derive_has_field.md) (singular) answers "give me *this* field", `HasFields` +answers "describe *all* of them at once": ```rust type Fields = Product![ @@ -26,17 +27,18 @@ type Fields = Product![ That is the whole struct written as a type: a [`Product!`](../macros/product.md) list with one [`Field`](../types/field.md) entry per field, each pairing a value type with its type-level name. For an -enum it is a [`Sum!`](../macros/sum.md) instead — the same idea for a choice rather than a combination. Code -that is generic over the shape recurses over that list, and everything is resolved during compilation. +enum it is a [`Sum!`](../macros/sum.md) instead: the same idea for a choice rather than a combination. +Code that is generic over the shape recurses over that list, and everything is resolved during +compilation. -The derive also generates the conversions that move values in and out of the representation, which is what -makes it a two-way door rather than a description. Generic code can take a concrete value apart into its -anonymous shape, work on it, and put a concrete value back together. +The derive also generates the conversions that move values in and out of the representation, so it works +in both directions rather than only describing the type. Generic code can take a concrete value apart +into its anonymous shape, work on it, and put a concrete value back together. ## Usage -The macro is a plain derive that takes no arguments and has no helper attributes. Unlike its singular -sibling it accepts **both structs and enums**: +The macro is a plain derive that takes no arguments and has no helper attributes. Unlike the singular +derive it accepts **both structs and enums**: ```rust #[derive(HasFields)] @@ -59,27 +61,29 @@ compile error. ### Struct shapes -Every struct shape is accepted, and three of the four are what you would predict from the field tags alone. +Every struct shape is accepted, and three of the four behave as you would predict from the field tags +alone. - A **named-field struct** becomes a product of `Field` entries, in declaration order. - A **multi-field tuple struct** becomes a product keyed by `Index`. - A **unit struct** becomes the empty product `Nil`. A fieldless struct is a valid, if trivial, record and round-trips through the representation like any other. -- A **single-field tuple struct** — a newtype — is the special case: its `Fields` is the inner type +- A **single-field tuple struct** (a newtype) is the special case: its `Fields` is the inner type *directly*, not wrapped in a one-element product. -The newtype case is worth pausing on, because it is the one that will surprise you. `struct Wrapper(String)` -has `Fields = String`, not `Product![Field, String>]`. The rationale is that a newtype is a -transparent wrapper and generic code almost always wants to see through it, but the practical effect is that -adding a second field to a newtype changes its `Fields` type in shape rather than in length. +The newtype case is worth noting, because it is the one that will surprise you. `struct Wrapper(String)` +has `Fields = String`, not `Product![Field, String>]`. The reason is that a newtype is a +transparent wrapper and generic code almost always wants the inner type rather than the wrapper. The +practical effect is that adding a second field to a newtype changes its `Fields` type in shape rather +than in length. ### Variant shapes **This is the one derive in the extensible-data family that places no restriction on an enum's variant -shapes.** The derives that take an enum *apart* — +shapes.** The derives that take an enum *apart* (that is, [`#[derive(ExtractField)]`](./derive_extract_field.md) and [`#[derive(FromVariant)]`](./derive_from_variant.md), and therefore -[`#[derive(CgpData)]`](./derive_cgp_data.md) — require every variant to carry exactly one unnamed payload, +[`#[derive(CgpData)]`](./derive_cgp_data.md)) require every variant to carry exactly one unnamed payload, because each has to name a single type per variant. `HasFields` only *describes* a variant, so it accepts all four shapes and nests that variant's own fields as a product inside its `Field` entry: @@ -102,25 +106,26 @@ Each variant maps by the same rules a struct's fields do: | `Rectangle(u32, u32)` | `Field, u32>, Field, u32>]>` | | `Triangle { base, height }` | `Field, Field]>` | -So a unit variant becomes the empty product, a newtype variant passes its payload straight through — the -same special case as a newtype struct, applied inside a variant — a multi-field tuple variant becomes an -`Index`-keyed product, and a named-field variant becomes a `Symbol!`-keyed one. All four round-trip through -the conversions. +So a unit variant becomes the empty product, a newtype variant passes its payload straight through (the +same special case as a newtype struct, applied inside a variant), a multi-field tuple variant becomes an +`Index`-keyed product, and a named-field variant becomes a `Symbol!`-keyed one. All four round-trip +through the conversions. -The consequence is worth stating plainly, because it decides which derive to reach for: **an enum with mixed -variant shapes can have a structural representation but no generic constructor or extractor.** +The consequence is worth stating plainly, because it decides which derive to reach for: **an enum with +mixed variant shapes can have a structural representation but no generic constructor or extractor.** `#[derive(HasFields)]` succeeds on the enum above; `#[derive(CgpData)]` on the same enum would not. ### Generic types -Generic parameters, lifetimes, and a `where` clause are carried onto every generated impl. A borrowed field -type appears verbatim in the shape, and the borrowed view of the shape layers its own borrow on top of it — -a field of type `&'a Name` appears as `&'__a &'a Name` in the borrowed form, where `'__a` is the reserved lifetime the derive introduces. +Generic parameters, lifetimes, and a `where` clause are carried onto every generated impl. A borrowed +field type appears verbatim in the shape, and the borrowed view of the shape layers its own borrow on top +of it: a field of type `&'a Name` appears as `&'__a &'a Name` in the borrowed form, where `'__a` is the +reserved lifetime the derive introduces. ## Examples -Deriving `HasFields` alongside [`HasField`](./derive_has_field.md) is the common pairing, giving one struct -both indexed and structural access: +Deriving `HasFields` alongside [`HasField`](./derive_has_field.md) is the common pairing, giving one +struct both indexed and structural access: ```rust use cgp::prelude::*; @@ -132,8 +137,8 @@ pub struct Config { } ``` -`Config::Fields` is now `Product![Field, Field]`, and a value -round-trips through it: +`Config::Fields` is now `Product![Field, Field]`, and a +value round-trips through it: ```rust let config = Config { host: "localhost".to_owned(), port: 8080 }; @@ -142,8 +147,7 @@ let fields = config.to_fields(); // Config -> the product let config_again = Config::from_fields(fields); // the product -> Config ``` -There is a borrowing form too, which is what read-only generic code uses so it does not have to consume the -value: +There is a borrowing form too, used by read-only generic code so it does not have to consume the value: ```rust let config = Config { host: "localhost".to_owned(), port: 8080 }; @@ -163,39 +167,39 @@ pub enum Shape { `Shape::Fields` is `Sum![Field, Field]`. -What generic code does with this is bound on the shape rather than on the type. An implementation that works -for any record writes `where Self: HasFields` and recurses over `Self::Fields`, so it applies to `Config`, -to `Person`, and to a struct declared in another crate that happens to derive the same thing. +Generic code binds on the shape rather than on the type. An implementation that works for any record +writes `where Self: HasFields` and recurses over `Self::Fields`, so it applies to `Config`, to `Person`, +and to a struct declared in another crate that happens to derive the same thing. ## When to reach for it, and when not **Reach for `#[derive(HasFields)]` when code must process a type's whole shape, and for [`#[derive(HasField)]`](./derive_has_field.md) when it needs one named field.** That is the whole -distinction, and the two are complementary rather than ranked — most types that need both derive both, in one -`#[derive(...)]`. +distinction, and the two are complementary rather than ranked. Most types that need both derive both, in +one `#[derive(...)]`. The finer question is whether to derive it on its own or take the umbrella. -- **Derive `HasFields` alone** when the type only needs to be *described* and converted — a payload being - serialized, a struct being read structurally, an enum whose shape a dispatcher inspects. This is also the - only choice available for an enum with mixed variant shapes. +- **Derive `HasFields` alone** when the type only needs to be *described* and converted: a payload being + serialized, a struct being read structurally, an enum whose shape a dispatcher inspects. This is also + the only choice available for an enum with mixed variant shapes. - **Reach for [`#[derive(CgpData)]`](./derive_cgp_data.md)** when the type also needs to be built up field by field or taken apart variant by variant, since that derive includes this one plus the incremental machinery. If you find yourself deriving `HasFields`, `HasField`, and [`BuildField`](./derive_build_field.md) together, the umbrella is the shorter way to say it. -- **Do not derive it speculatively.** It generates five impls and a representation type per use, and a type - nothing processes structurally gains nothing from having a shape. Deriving `HasField` for value reads is - the far more common need. +- **Do not derive it speculatively.** It generates five impls and a representation type per use, and a + type nothing processes structurally gains nothing from having a shape. Deriving `HasField` for value + reads is the far more common need. -One misreading to head off: **this is not runtime reflection.** A type has a shape only because it opted in -with a derive, there is nothing to query at runtime, and the shape is a type rather than data. What that -buys is that generic code over it is checked when written and costs nothing when run; what it costs is that -a type you do not own and cannot patch has no shape at all. +One misreading to head off: **this is not runtime reflection.** A type has a shape only because it opted +in with a derive, there is nothing to query at runtime, and the shape is a type rather than data. The +gain is that generic code over it is checked when written and costs nothing when run. The cost is that a +type you do not own and cannot patch has no shape at all. ## Under the hood -The derive leaves the type definition untouched and emits **five impls**: the shape, the borrowed shape, and -three conversions. From a named-field struct: +The derive leaves the type definition untouched and emits **five impls**: the shape, the borrowed shape, +and three conversions. From a named-field struct: ```rust #[derive(HasFields)] @@ -250,12 +254,12 @@ impl ToFieldsRef for Person { } ``` -`Product![A, B]` is sugar for `Cons>`, which is why the bodies build a `Cons` chain — the -[type-level spines](../types/type_level_spines.md) page covers that shape, and it is what you will see -printed in an error. +`Product![A, B]` is sugar for `Cons>`, which is why the bodies build a `Cons` chain. The +[type-level spines](../types/type_level_spines.md) page covers that shape, and it is the form printed in +an error. -An enum's shape is the dual: an [`Either`](../types/type_level_spines.md) chain terminated by `Void` rather -than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name: +An enum's shape is the dual: an [`Either`](../types/type_level_spines.md) chain terminated by `Void` +rather than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name: ```rust impl HasFields for Shape { @@ -266,10 +270,10 @@ impl HasFields for Shape { } ``` -The conversions match each concrete variant onto its arm and back. The four variant shapes described above -all fall out of one rule rather than being special-cased: each variant's own fields go through the same -product construction a struct's fields do, which is why a unit variant lands on `Nil`, a newtype variant on -its payload type, and the two multi-field shapes on `Index`- and `Symbol!`-keyed products. +The conversions match each concrete variant onto its arm and back. The four variant shapes described +above all fall out of one rule rather than being special-cased: each variant's own fields go through the +same product construction a struct's fields do, which is why a unit variant lands on `Nil`, a newtype +variant on its payload type, and the two multi-field shapes on `Index`- and `Symbol!`-keyed products. The empty shapes come from the same construction. A unit struct's `Fields` is `Nil`: @@ -279,11 +283,11 @@ impl HasFields for Unit { } ``` -and a variantless enum's is `Void`, with its borrowed conversions matching the uninhabited value through an -empty `match`. +and a variantless enum's is `Void`, with its borrowed conversions matching the uninhabited value through +an empty `match`. -Each generated impl is aimed at the type name the user wrote, so a conflict with a hand-written `HasFields` -impl underlines the struct or enum rather than the whole `#[derive(HasFields)]`. +Each generated impl is aimed at the type name the user wrote, so a conflict with a hand-written +`HasFields` impl underlines the struct or enum rather than the whole `#[derive(HasFields)]`. ## Common Mistakes @@ -309,15 +313,15 @@ different orders have different `Fields` types. Structural conversions that matc code written against a literal `Cons` chain does not. **Two variant names are reserved, and using one does not compile.** The generated impls write -`Self::Fields` and `Self::FieldsRef`, so an enum with a variant called `Fields` or `FieldsRef` makes the path -ambiguous. The compiler reports `ambiguous associated item` with its headline on the derive, and a note -pointing at the offending variant — so following the note tells you which one to rename. The [extractor](./derive_extract_field.md) and -[constructor](./derive_from_variant.md) derives reserve five more names, so an enum taking the whole family -should avoid all seven. +`Self::Fields` and `Self::FieldsRef`, so an enum with a variant called `Fields` or `FieldsRef` makes the +path ambiguous. The compiler reports `ambiguous associated item` with its headline on the derive, and a +note pointing at the offending variant, so following the note tells you which one to rename. The +[extractor](./derive_extract_field.md) and [constructor](./derive_from_variant.md) derives reserve five +more names, so an enum taking the whole family should avoid all seven. **It is a different derive from the singular one.** `#[derive(HasField)]` gives per-field access and takes -only structs; `#[derive(HasFields)]` gives the whole shape and takes structs and enums. The names differ by -one letter and the outputs do not overlap. +only structs; `#[derive(HasFields)]` gives the whole shape and takes structs and enums. The names differ +by one letter and the outputs do not overlap. ## Related constructs diff --git a/docs/reference/derives/index.md b/docs/reference/derives/index.md new file mode 100644 index 00000000..fc5b6c6c --- /dev/null +++ b/docs/reference/derives/index.md @@ -0,0 +1,65 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Derives + +A derive here turns an ordinary struct or enum into data that generic CGP code can work with, without +that code ever naming the concrete type. Each one generates trait impls beside the type rather than +changing the type itself, so a struct stays an ordinary struct and gains the machinery alongside it. +This page groups every derive in this section by the job it does, in roughly the order most CGP code +reaches for them. + +If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here; this page +is the fuller map for once the essentials are familiar. + +## Reading a value from a context + +The two field-access derives are the ones nearly every CGP program uses. + +[`#[derive(HasField)]`](./derive_has_field.md) is the foundational one, and usually the first derive +anyone writes. It gives each field a type-level name, so an implementation can ask for a field by name as +a trait bound and read it without knowing the concrete type. Every ergonomic value read stands on it: an +[`#[implicit]`](../attributes/implicit.md) argument and a +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method both generate a `HasField` bound from a name +you already wrote. + +[`#[derive(HasFields)]`](./derive_has_fields.md) gives the whole shape instead of one field: the struct +or enum described as a single type-level list, plus the conversions that move values in and out of it. +Reach for it when code must process every field at once, such as a serializer or a builder that merges +two records. It is often derived alongside `HasField`. + +## Turning a type into extensible data + +These three derives add the machinery for building a value up field by field, or taking one apart variant +by variant, with the progress tracked in the type so the compiler checks it. Each includes the field +access and representation above and adds the incremental half on top. + +[`#[derive(CgpData)]`](./derive_cgp_data.md) is the umbrella and the default. On a struct it emits the +record machinery; on an enum, the variant machinery. Use it unless you have a reason to name the shape. + +[`#[derive(CgpRecord)]`](./derive_cgp_record.md) is the struct-only face, and +[`#[derive(CgpVariant)]`](./derive_cgp_variant.md) the enum-only face. Each emits exactly what `CgpData` +emits for that shape and rejects the other shape at parse time, so a type that is meant to stay one kind +says so and a wrong shape fails at the derive. + +## Deriving one slice on its own + +Each half of the extensible-data output is also available as its own derive, for a type that needs only +part of the machinery. + +[`#[derive(BuildField)]`](./derive_build_field.md) is the record builder alone: assemble a struct one +field at a time, from code that does not know the whole struct. [`#[derive(ExtractField)]`](./derive_extract_field.md) +is the enum extractor alone: take an enum apart one variant at a time, with a provably exhaustive end. +[`#[derive(FromVariant)]`](./derive_from_variant.md) is the variant constructors alone: build an enum +from a variant chosen by name. The first belongs to structs; the last two belong to enums and are +commonly derived together. + +## One restriction to know before you reach for them + +The derives that take an enum apart, `#[derive(ExtractField)]` and `#[derive(FromVariant)]` and therefore +`#[derive(CgpData)]` and `#[derive(CgpVariant)]`, require every enum variant to carry exactly one unnamed +payload, with no per-variant opt-out. `#[derive(HasFields)]` is the exception: it only describes a +variant, so it accepts every variant shape, which makes it the derive an enum with mixed variants can +still use. From 665bf5a7a308ccd55e176811365d580f0445d5cf Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 13:02:44 +0200 Subject: [PATCH 043/516] Write the non-catalogue provider reference pages Port the eight singleton provider pages (UseContext, UseDefault, UseType, UseDelegatedType, UseDelegate, RedirectLookup, ChainGetters, WithProvider) and split use_field into UseField, UseFieldRef, and UseFields, per the one-page-per-construct granularity rule. Each page follows the six-section template with the context gloss, the generated-machinery and legacy notices where they apply, and the shared provenance note. Every snippet is backed by a compiled counterpart under example-code/src/reference/providers/ (cargo test green), which caught and fixed several wiring errors: ChainGetters, UseFieldRef, and UseDelegatedType are foundational providers wired through WithProvider aliases rather than directly, and the #[cgp_component] brace form has no derive_delegate key. Remove the now-redundant UseFieldRef/UseFields row from the reference index. Co-Authored-By: Claude Opus 4.8 --- docs/reference/index.md | 1 - docs/reference/providers/chain_getters.md | 181 ++++++++++++++++- docs/reference/providers/redirect_lookup.md | 169 +++++++++++++++- docs/reference/providers/use_context.md | 190 +++++++++++++++++- docs/reference/providers/use_default.md | 157 ++++++++++++++- docs/reference/providers/use_delegate.md | 177 +++++++++++++++- .../reference/providers/use_delegated_type.md | 160 ++++++++++++++- docs/reference/providers/use_field.md | 185 ++++++++++++++++- docs/reference/providers/use_field_ref.md | 169 ++++++++++++++++ docs/reference/providers/use_fields.md | 161 +++++++++++++++ docs/reference/providers/use_type.md | 173 +++++++++++++++- docs/reference/providers/with_provider.md | 180 ++++++++++++++++- example-code/src/reference/mod.rs | 1 + .../src/reference/providers/chain_getters.rs | 52 +++++ example-code/src/reference/providers/mod.rs | 16 ++ .../reference/providers/redirect_lookup.rs | 21 ++ .../src/reference/providers/use_context.rs | 58 ++++++ .../src/reference/providers/use_default.rs | 56 ++++++ .../src/reference/providers/use_delegate.rs | 87 ++++++++ .../reference/providers/use_delegated_type.rs | 46 +++++ .../src/reference/providers/use_field.rs | 65 ++++++ .../src/reference/providers/use_field_ref.rs | 55 +++++ .../src/reference/providers/use_fields.rs | 43 ++++ .../src/reference/providers/use_type.rs | 53 +++++ .../src/reference/providers/with_provider.rs | 40 ++++ 25 files changed, 2434 insertions(+), 62 deletions(-) create mode 100644 docs/reference/providers/use_field_ref.md create mode 100644 docs/reference/providers/use_fields.md create mode 100644 example-code/src/reference/providers/chain_getters.rs create mode 100644 example-code/src/reference/providers/mod.rs create mode 100644 example-code/src/reference/providers/redirect_lookup.rs create mode 100644 example-code/src/reference/providers/use_context.rs create mode 100644 example-code/src/reference/providers/use_default.rs create mode 100644 example-code/src/reference/providers/use_delegate.rs create mode 100644 example-code/src/reference/providers/use_delegated_type.rs create mode 100644 example-code/src/reference/providers/use_field.rs create mode 100644 example-code/src/reference/providers/use_field_ref.rs create mode 100644 example-code/src/reference/providers/use_fields.rs create mode 100644 example-code/src/reference/providers/use_type.rs create mode 100644 example-code/src/reference/providers/with_provider.rs diff --git a/docs/reference/index.md b/docs/reference/index.md index 3467b246..d893d5a8 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -227,7 +227,6 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w | Looking for | It's on | |---|---| | `#[cgp_new_provider]` | [`#[cgp_provider]`](./macros/cgp_provider.md) | -| `UseFieldRef`, `UseFields` | [`UseField`](./providers/use_field.md) | | `CanSendRun` | [`CanRun`](./components/runner.md) | | `CanWrapError` | [`CanRaiseError`](./components/can_raise_error.md) | | `HasRuntimeType` | [`HasRuntime`](./components/has_runtime.md) | diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 77172dd4..1520ea63 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -4,14 +4,181 @@ sidebar_label: 'ChainGetters' # `ChainGetters` -Compose getters to reach a field on a nested context. +Compose a list of field getters into one, reaching a field several hops inside a nested context. -:::info +## Overview -### Not written yet +`ChainGetters` reaches a field that does not live directly on the context but several levels +inside it. The **context** is the type a capability runs against, and a single +[`UseField`](use_field.md) reads one field of one context. But CGP contexts often nest: a context holds +a config, the config holds a connection, the connection holds a timeout, and a getter may need the +innermost value. Writing one provider that walks the whole path by hand is tedious and couples the +getter to the nesting. `ChainGetters` takes a list of getters, applies them in order, and +threads the reference from each step into the next, so the chain reads like the path it traverses: +outer getter, then the next, ending at the target field. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`ChainGetters` is a foundational [`FieldGetter`](../traits/field_getter.md), so it is wired to a getter +component through the [`WithProvider`](with_provider.md) adapter rather than named on its own. The list +is a type-level [`Cons`](../types/type_level_spines.md) spine whose elements are each a field getter for +the value the previous step produced, written with the [`Product!`](../macros/product.md) macro. +`ChainGetters` recurses down the list. Like every CGP provider, it carries no runtime value: it is a +marker named in wiring. -::: +## Usage + +`ChainGetters` is not in the prelude. Import it from `cgp::core::field::impls`: + +```rust +use cgp::core::field::impls::ChainGetters; +``` + +It takes one type parameter, a [`Product!`](../macros/product.md) list of getters, and appears wrapped +in [`WithProvider`](with_provider.md) as the value of a getter component's wiring entry: + +```rust +delegate_components! { + App { + NameGetterComponent: WithProvider< + ChainGetters, + UseField, + ]>, + >, + } +} +``` + +Each element of the list is a field getter, usually [`UseField`](use_field.md), for the value the +previous step produced. The value the last step reads must match what the getter returns, the same way +any getter provider must. Every step is asked under the same tag, so the chain navigates *contexts* +rather than different field names per step, and each getter in the list decides for itself which field +of its input it reads. `ChainGetters` has no dedicated alias; wrap it in `WithProvider` directly. + +## Examples + +A typical use reaches a field on a nested inner context by chaining the getter that produces the inner +context with the getter that reads the field. Here an `App` holds a `Config`, and the target is the +`Config`'s `name`: + +```rust +use cgp::prelude::*; +use cgp::core::field::impls::ChainGetters; // not in the prelude + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Config { + pub name: String, +} + +#[derive(HasField)] +pub struct App { + pub config: Config, +} + +delegate_components! { + App { + NameGetterComponent: WithProvider< + ChainGetters, + UseField, + ]>, + >, + } +} +``` + +`App` wires `NameGetterComponent` to `WithProvider>` over a two-element list. The +first getter, `UseField`, reads `App`'s `config` field to produce a `&Config`; the +second, `UseField`, reads that `Config`'s `name` field to produce the `&String` the +`&str` getter borrows from. `ChainGetters` threads the reference from the first step into the second, so +`app.name()` returns the name nested two levels in, with no hand-written walking code. + +## When to reach for it, and when not + +**Reach for `ChainGetters` when a getter's value lives on a nested inner context** rather than on the +context directly, so the getter has to walk through one or more intermediate values to reach it. + +For a field on the context itself, prefer an [`#[implicit]`](../attributes/implicit.md) argument, or +[`UseField`](use_field.md) when the field name must be a wiring decision. `ChainGetters` earns its place +only once the value is more than one hop away. + +## Under the hood + +`ChainGetters` implements the provider-side getter [`FieldGetter`](../traits/field_getter.md) with two +impls that together recurse over the list, one for a non-empty `Cons` and one for the empty `Nil`. The +`Cons` impl applies the head getter, then delegates the rest of the path to `ChainGetters` over the +tail: + +```rust +impl FieldGetter + for ChainGetters> +where + Getter: FieldMapper, + ChainGetters: FieldGetter, +{ + type Value = ValueB; + + fn get_field(context: &Context, tag: PhantomData) -> &ValueB { + Getter::map_field(context, tag, |value| { + >::get_field(value, tag) + }) + } +} +``` + +The head `Getter` reads `ValueA` from the `Context`, and the rest of the chain reads `ValueB` from that +`ValueA`, so the whole chain's `Value` is `ValueB`, the value at the end of the path. The head is +applied through [`FieldMapper`](../traits/field_mapper.md) rather than `FieldGetter` directly: +`map_field` hands the intermediate reference to a closure that runs the rest of the chain on it, which +is what keeps the borrowed lifetimes inferring across each hop. + +The recursion bottoms out at the empty list, where `ChainGetters` is the identity getter and +returns the context it was given: + +```rust +impl FieldGetter for ChainGetters { + type Value = Context; + + fn get_field(context: &Context, _tag: PhantomData) -> &Context { + context + } +} +``` + +So a chain of one getter resolves to that getter applied to the context, a chain of two applies the +first then the second, and so on down the `Cons` spine. Because `ChainGetters` produces a `FieldGetter` +rather than the getter component's own provider trait, the [`WithProvider`](with_provider.md) adapter is +what turns it into a provider a getter component can be wired to. + +## Related constructs + +- [`WithProvider`](with_provider.md) — the adapter that turns `ChainGetters` into a getter-component + provider. +- [`UseField`](use_field.md) and [`UseFieldRef`](use_field_ref.md) — the getters that form each step of + the chain, implementing the same [`FieldGetter`](../traits/field_getter.md) it composes. +- [`FieldMapper`](../traits/field_mapper.md) — what each step is applied through, to keep borrowed + lifetimes inferring across hops. +- [`Product!`](../macros/product.md) — builds the list of getters. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — defines the getter this is wired to. +- [`#[derive(HasField)]`](../derives/derive_has_field.md) — supplies the field access each step reads. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — value injection through a + provider's own requirements, here reaching across nested contexts. + +## Source + +- Struct and its two `FieldGetter` impls: + [`chain.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/chain.rs) +- The traits it builds on: + [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) + and [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index c68e4e91..89bee1b5 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -4,14 +4,173 @@ sidebar_label: 'RedirectLookup' # `RedirectLookup` -Re-route a component lookup along a type-level path. The mechanism behind namespaces and `open`. +Route a component's lookup along a type-level path in a separate table. The mechanism behind namespaces +and `open`. :::info -### Not written yet +### Generated machinery -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +**You are not expected to write `RedirectLookup` entries.** +[`#[cgp_component]`](../macros/cgp_component.md) generates a `RedirectLookup` impl for every component, +and the [`#[prefix]`](../macros/cgp_namespace.md) attribute and the `open` and `namespace` statements of +[`delegate_components!`](../macros/delegate_components.md) generate the delegation entries that target +it. This page explains what those generated entries *are*, so that an expansion or a wiring error naming +this provider is legible. ::: + +## Overview + +`RedirectLookup` separates *which key* a component is looked up under from *which +table* answers it. The ordinary provider blanket impl looks a component up in the **context**'s own +delegation table, keyed by the component marker, where the context is the type the capability runs +against. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed by a +type-level `Path`, then delegates to whatever provider that entry holds. This indirection is what lets +one component's resolution be redirected to a different key in a different table, which is the basis for +organizing wiring into namespaces. + +The redirection is what makes namespaces work. A namespace groups a context's components under a path +prefix so several related components can be wired in one place and addressed by a shared path. +`RedirectLookup` turns a prefixed path back into a concrete provider: the namespace machinery sets a +component's delegate to a `RedirectLookup` carrying the path under which the real provider was +registered, so a lookup of the component follows that path into the table and lands on the intended +provider. The `open` statement of [`delegate_components!`](../macros/delegate_components.md) is a +lightweight special case of the same redirection. + +`RedirectLookup` is not written by hand. Every `#[cgp_component]` generates its impl, and the namespace +attributes generate the delegation entries whose delegate is a `RedirectLookup`. Reading those +generated entries is where this provider appears. Like every CGP provider, it carries no runtime value. + +## Usage + +`RedirectLookup` is in the prelude, but you do not name it directly. It appears where the namespace and +`open` machinery generate it. A component is registered under a path with the +[`#[prefix(@path in Namespace)]`](../macros/cgp_namespace.md) attribute, and a context joins a namespace +or opens a component for per-type dispatch: + +```rust +delegate_components! { + App { + namespace DefaultNamespace; + + @bar.baz: TestProvider, + } +} +``` + +The path-keyed entry above (`@bar.baz`) is what a `RedirectLookup` later walks. The path itself is a +[`PathCons`](../types/type_level_spines.md) chain of [`Symbol!`](../macros/symbol.md) segments, most +easily written with [`Path!`](../macros/path.md). + +## Examples + +`RedirectLookup` appears in the delegate the namespace machinery generates, where a component is +registered under a path and reached through it: + +```rust +use cgp::prelude::*; + +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + @bar.baz: TestProvider, + } +} +``` + +This registers `TestProvider` under the path `bar` then `baz` in `App`'s default namespace. When a +component is later resolved against `App` through that namespace, its delegate is a +`RedirectLookup` whose `Path` is the `PathCons` chain `bar`, then `baz`, then the component +marker. The lookup follows that path into `App`'s table, matches the entry above, and dispatches to +`TestProvider`. The component marker never keys the context directly; it is the tail of a path that +`RedirectLookup` walks. This is the indirection that lets namespaces organize wiring by path while still +resolving to ordinary providers. + +## When to reach for it, and when not + +**You do not reach for `RedirectLookup` directly.** Use the [`open` statement](../macros/delegate_components.md) +for per-type dispatch on one context, and a [namespace](../macros/cgp_namespace.md) for reusable, +inheritable wiring. Both generate the `RedirectLookup` entries for you. The +[namespaces](/docs/concepts/namespaces) concept explains when to reach for each. + +Recognizing `RedirectLookup` in an expansion or a wiring error is the reason this page exists: a message +naming it means a lookup is being routed through a path, and the fix is usually a missing or misspelled +path entry rather than anything about the provider itself. + +## Under the hood + +[`#[cgp_component]`](../macros/cgp_component.md) generates a `RedirectLookup` impl of the provider trait +alongside the consumer blanket impl, the provider blanket impl, the component marker, and the +[`UseContext`](use_context.md) impl. The generated impl looks the path up in the table and forwards to +the resulting delegate. For a component such as + +```rust +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} +``` + +the macro generates this impl (shown with the macro's real placeholder identifiers): + +```rust +impl<__Context__, __Components__, __Path__> Greeter<__Context__> + for RedirectLookup<__Components__, __Path__> +where + __Components__: DelegateComponent<__Path__>, + <__Components__ as DelegateComponent<__Path__>>::Delegate: Greeter<__Context__>, +{ + fn greet(__context__: &__Context__) -> String { + <__Components__ as DelegateComponent<__Path__>>::Delegate::greet(__context__) + } +} +``` + +The mechanism is one [`DelegateComponent`](../traits/delegate_component.md) lookup keyed on `__Path__` +rather than on the component marker. `RedirectLookup` implements `Greeter` whenever +`Components` maps `Path` to a delegate that itself implements `Greeter`, and the method forwards to that +delegate. When the consumer trait carries generic type parameters, the impl additionally constrains +`Path` with `ConcatPath` so the parameters are appended to the path before the lookup, letting the +redirected key encode the generic arguments. As always, the impl is paired with a matching +[`IsProviderFor`](../traits/is_provider_for.md) impl. + +The `#[prefix(@path in Namespace)]` attribute is what populates the path side: it generates a namespace +impl whose delegate is `RedirectLookup`, with the prefix path joined onto the +component marker, so resolving the component under that namespace follows the prefixed path into the +table. + +## Related constructs + +- [`#[cgp_component]`](../macros/cgp_component.md) — generates a `RedirectLookup` impl for every + component. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines namespaces and the `#[prefix]` attribute that + target `RedirectLookup`. +- [`delegate_components!`](../macros/delegate_components.md) — the `open` and `namespace` statements that + generate the redirect entries. +- [`DelegateComponent`](../traits/delegate_component.md) — the table the lookup reads. +- [`Path!`](../macros/path.md) and [`PathCons`](../types/type_level_spines.md) — the type-level path it + walks. +- [`UseContext`](use_context.md) — the other `#[cgp_component]`-generated provider, routing back to the + context. + +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables, which this provider + implements. + +## Source + +- Struct: + [`redirect_lookup.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/redirect_lookup.rs) +- The generated impl: + [`cgp_component/evaluated/to_redirect_lookup_impl.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_component/evaluated/to_redirect_lookup_impl.rs) +- The `#[prefix]` attribute that targets it: + [`types/attributes/prefix.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/prefix.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index 12d0ec1d..cc9e600f 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -4,14 +4,190 @@ sidebar_label: 'UseContext' # `UseContext` -Satisfy a provider trait by routing back through the context's own consumer impl. +Satisfy a provider trait by routing back through the context's own consumer-trait implementation. -:::info +## Overview -### Not written yet +`UseContext` turns a context's existing consumer-trait implementation into a provider that other +providers can call. The **context** is the type a capability runs against, and it normally *uses* a +provider through its consumer trait. Sometimes the implementation another provider wants for a +capability is exactly the one the context already supplies that way. `UseContext` is that bridge: it is +a provider whose method bodies call the consumer method on the context, so handing a component +`UseContext` means "use whatever this context already does for this trait." -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +This makes `UseContext` the exact dual of the consumer-trait blanket implementation that +[`#[cgp_component]`](../macros/cgp_component.md) generates. That blanket impl runs in the +consumer-to-provider direction: a context implements `CanGreet` by delegating to whichever provider +implements `Greeter` for it. `UseContext` runs the other way: it implements the provider trait +`Greeter` by delegating to whatever `CanGreet` implementation the context has. One forwards the +consumer trait to a provider; the other forwards a provider trait back to the consumer trait. -::: +`UseContext` matters most with [higher-order providers](/docs/concepts/higher-order-providers), which +take another provider as a type parameter. A higher-order provider that wraps *one* capability while +delegating to *another* can default its inner-provider parameter to `UseContext`, so the inner step +falls back to whatever the context already wires for that other capability, and the author need not name +an explicit inner provider. Like every CGP provider, `UseContext` carries no runtime value: it is a +unit marker whose `self` position is never read. + +## Usage + +`UseContext` is in the prelude, so `use cgp::prelude::*;` is enough. It takes no type parameter and +appears in two places. Most often it is a higher-order provider's default inner provider, written in +the provider's struct definition: + +```rust +pub struct GreetLoudly(pub PhantomData); +``` + +It also appears directly in a wiring entry to route a component through the context's own +implementation, which is how the [dispatch combinators](dispatch_combinators.md) default their +per-variant provider. + +**Do not wire a component to `UseContext` when that component's only implementation on the context is +the delegation itself.** Doing so asks the context to implement the consumer trait by delegating to a +provider that implements the provider trait by calling the same consumer trait, a cycle the trait +solver cannot resolve. See [Common Mistakes](#common-mistakes). `UseContext` works when the provider +trait it stands in for resolves to a *different* implementation than the one being wired, which is why +it fits a wrapper that delegates to another capability. + +## Examples + +The idiomatic use is as the default inner provider of a higher-order provider that builds one capability +on top of another. Here a loud greeter wraps an ordinary greeter, and its inner provider defaults to +`UseContext` so it reuses whatever `CanGreet` the context already wires: + +```rust +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_component(LoudGreeter)] +pub trait CanGreetLoudly { + fn greet_loudly(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "Hello".to_owned() + } +} + +pub struct GreetLoudly(pub PhantomData); + +#[cgp_impl(GreetLoudly)] +#[use_provider(Inner: Greeter)] +impl LoudGreeter { + fn greet_loudly(&self) -> String { + format!("{}!", Inner::greet(self).to_uppercase()) + } +} + +pub struct App; + +delegate_components! { + App { + GreeterComponent: GreetHello, + LoudGreeterComponent: GreetLoudly, + } +} +``` + +`App` wires `LoudGreeterComponent` to a bare `GreetLoudly`, whose `Inner` defaults to `UseContext`. When +`app.greet_loudly()` runs, `GreetLoudly` calls `Inner::greet(self)`, which resolves through `UseContext` +to `App`'s own `CanGreet`, wired to `GreetHello`. The result is `"HELLO!"`. Because `GreetLoudly` +implements a *different* component from the one it delegates through, the delegation lands on +`GreetHello` rather than back on `GreetLoudly`, so there is no cycle. Overriding the parameter, as in +`GreetLoudly`, binds the inner greeter directly and bypasses the context's `CanGreet` +wiring. + +`UseContext` acts as a default only when the provider's struct definition gives it as the default +generic parameter, as `GreetLoudly` does. A provider without such a default has no inner provider to +fall back to, and the inner provider must always be named. + +## When to reach for it, and when not + +**Reach for `UseContext` as the default inner provider of a higher-order provider that delegates to a +different capability than the one it implements**, so the wrapper reuses the context's own wiring for +that other capability when no inner provider is named. + +**Do not wire a component to `UseContext` on the context that implements it only through that +delegation.** That is the one shape it cannot serve, because the component's implementation would depend +on itself. When you want a wrapper over the *same* capability, name the inner provider explicitly rather +than defaulting to `UseContext`. + +## Under the hood + +[`#[cgp_component]`](../macros/cgp_component.md) emits a `UseContext` implementation of the provider +trait for every component it defines, alongside the consumer blanket impl, the provider blanket impl, +the component marker, and the [`RedirectLookup`](redirect_lookup.md) impl. The generated impl bounds the +context on the consumer trait and forwards each method to it. For a component such as + +```rust +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} +``` + +the macro generates this `UseContext` impl (shown with the macro's real placeholder identifiers): + +```rust +impl<__Context__> Greeter<__Context__> for UseContext +where + __Context__: CanGreet, +{ + fn greet(__context__: &__Context__) { + __Context__::greet(__context__) + } +} +``` + +The provider method takes the context explicitly and calls the context's own `CanGreet::greet`. Each +`UseContext` impl is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl +carrying the same `where` clause, so delegation propagates the dependency and a check reports a missing +consumer-trait implementation precisely. Any supertrait bound on the consumer trait is reproduced in the +`where` clause, so a context must satisfy it before `UseContext` can stand in as a provider. + +## Common Mistakes + +**Wiring a component to `UseContext` on the context that owns it creates a cycle.** If `App` wires +`GreeterComponent` to `UseContext`, then `App`'s `CanGreet` is implemented by delegating to +`UseContext`, whose `Greeter` impl in turn calls `App`'s `CanGreet`. The trait solver chases this in a +loop and reports it as an overflow or an unsatisfied bound. The same happens with a same-component +wrapper that defaults its inner to `UseContext` and is then wired to that component. `UseContext` +belongs where the provider trait resolves to a different implementation, such as a wrapper over another +capability or a per-type dispatch entry. + +## Related constructs + +- [`#[cgp_component]`](../macros/cgp_component.md) — generates the `UseContext` impl for every + component, and the consumer blanket impl `UseContext` is the dual of. +- [Higher-order providers](/docs/concepts/higher-order-providers) — where `UseContext` is the default + inner provider. +- [`WithProvider`](with_provider.md) — its `WithContext` alias is `WithProvider`, adapting a + context's own implementation into a component. +- [`RedirectLookup`](redirect_lookup.md) — the other `#[cgp_component]`-generated provider, routing + through a separate table rather than back to the context. +- [Dispatch combinators](dispatch_combinators.md) — default their per-variant provider to `UseContext`. +- [`IsProviderFor`](../traits/is_provider_for.md) — carries the dependency `UseContext` propagates. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the two-way split + `UseContext` bridges. +- [Higher-order providers](/docs/concepts/higher-order-providers) — the pattern that makes it useful. + +## Source + +- Struct and the `WithContext` alias: + [`use_context.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_context.rs) +- The generated `UseContext` impl: + [`cgp_component/evaluated/to_use_context_impl.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_component/evaluated/to_use_context_impl.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index 9d53bf3f..9dbda233 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -4,14 +4,157 @@ sidebar_label: 'UseDefault' # `UseDefault` -Select a component's default method bodies. +Select a component's implementation from the consumer trait's own default method bodies. -:::info +## Overview -### Not written yet +`UseDefault` names the "use the trait's own defaults" choice in wiring. A consumer trait may define +default bodies for its methods, the same way any Rust trait can. When every method of a component has a +usable default, no behavior is left for a provider to supply, and the provider only needs to exist so +the component can be wired. `UseDefault` is that empty provider: wiring a component to `UseDefault` +selects an implementation whose method bodies come from the trait's defaults rather than from a +dedicated provider. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +This keeps a default-only component consistent with the rest of wiring. Without it, a component whose +methods are all defaulted would still need some provider type and some +[`delegate_components!`](../macros/delegate_components.md) entry to take part in the table. `UseDefault` +is the shared name for that role, so a **context** (the type the capability runs against) that wants +the defaults wires the component to `UseDefault` and writes no method bodies of its own. -::: +`UseDefault` is a bare marker that CGP defines but does not implement for any trait. Unlike +[`UseContext`](use_context.md) or the getter providers, no macro generates a provider implementation +for it. The author writes the implementation, usually with [`#[cgp_impl]`](../macros/cgp_impl.md) and +an empty body so the trait's defaults take effect. That is what distinguishes `UseDefault` from the +providers that carry generated behavior: it is purely a conventional name for an author-supplied, +default-bodied implementation. Like every CGP provider, it carries no runtime value. + +## Usage + +`UseDefault` is not in the prelude. Import it from `cgp::core::component`: + +```rust +use cgp::core::component::UseDefault; +``` + +Giving `UseDefault` a behavior takes two steps. First, write a provider implementation against it with +an empty body, so the trait's defaults fill in: + +```rust +#[cgp_impl(UseDefault)] +impl Greeter {} +``` + +Then wire the component to it, exactly like any other provider: + +```rust +delegate_components! { + App { + GreeterComponent: UseDefault, + } +} +``` + +Because `UseDefault` has no generated impls, the author controls precisely which components it serves. +A type with no provider impl written for a component is simply not a provider for it; there is no +automatic fallback, and the empty-body `#[cgp_impl]` is the explicit opt-in. + +## Examples + +The use of `UseDefault` is to wire several default-bodied components to one shared marker, then delegate +them all to it in the context's table. A getter and a greeter both carry default bodies: + +```rust +use cgp::prelude::*; +use cgp::core::component::UseDefault; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str { + "John" + } +} + +#[cgp_component(Greeter)] +pub trait CanGreet: HasName { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } +} + +#[cgp_impl(UseDefault)] +impl NameGetter {} + +#[cgp_impl(UseDefault)] +#[uses(HasName)] +impl Greeter {} + +pub struct App; + +delegate_components! { + App { + [ + NameGetterComponent, + GreeterComponent, + ]: + UseDefault, + } +} +``` + +The first `#[cgp_impl]` makes `UseDefault` a `NameGetter` provider whose `name` is the trait default +`"John"`; the second makes it a `Greeter` provider whose `greet` is the trait default that formats +around `self.name()`. The `Greeter` impl restates its consumer-side dependency with +[`#[uses(HasName)]`](../attributes/uses.md), because the default body of `greet` calls `name`. `App` +then delegates both components to `UseDefault` in one array entry, so `App.greet()` produces +`"Hello, John!"` entirely from the two default bodies, with no method implemented on `App` or on a +dedicated provider. + +## When to reach for it, and when not + +**Reach for `UseDefault` when a component's methods all have usable defaults and a context wants them +unchanged.** It gives a default-only component a name to wire, so it fits the delegation table like any +other component. + +Reach for a named provider written with [`#[cgp_impl]`](../macros/cgp_impl.md) whenever a component has +real behavior to supply, which is the usual case. `UseDefault` is only for the narrow case where the +trait's own defaults are the whole implementation. + +## Under the hood + +`UseDefault` has no generated implementations. It is a bare unit struct: + +```rust +pub struct UseDefault; +``` + +Meaning is given to it by the provider impl an author writes. An empty +[`#[cgp_impl(UseDefault)]`](../macros/cgp_impl.md) block emits a provider-trait implementation with no +method bodies, so each method falls back to the default defined on the consumer trait, plus the +matching [`IsProviderFor`](../traits/is_provider_for.md) implementation carrying the block's `where` +clause. That is the same pair any `#[cgp_impl]` produces; the only thing special about `UseDefault` is +the empty body and the shared, conventional name. + +## Related constructs + +- [`#[cgp_impl]`](../macros/cgp_impl.md) — writes the empty-body provider impl that gives `UseDefault` + its behavior. +- [`delegate_components!`](../macros/delegate_components.md) — wires it, and + [`check_components!`](../macros/check_components.md) verifies its dependencies. +- [`UseContext`](use_context.md) and [`UseFields`](use_fields.md) — the providers that carry + macro-generated behavior rather than relying on author-written empty bodies. +- [`IsProviderFor`](../traits/is_provider_for.md) — tracks the dependencies of a `UseDefault` impl. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the split that lets a + default-bodied consumer trait stand in for a provider's behavior. + +## Source + +- Struct: + [`use_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_default.rs) + — the file contains only the bare struct, with no generated impls. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 8a0ef815..96176fb3 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -4,14 +4,181 @@ sidebar_label: 'UseDelegate' # `UseDelegate` -Dispatch on a generic parameter through an inner table. Superseded by the `open` statement. +Dispatch a generic-parameter component to a different inner provider per type, through a lookup table. +Superseded by the `open` statement. :::info -### Not written yet +### Legacy — read, don't write -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`UseDelegate`, the [`#[derive_delegate]`](../attributes/derive_delegate.md) attribute that generates its +provider impl, and its nested-table wiring are the older way to choose a provider per type. The `open` +statement of [`delegate_components!`](../macros/delegate_components.md) does the same job through the +[`RedirectLookup`](redirect_lookup.md) impl every [`#[cgp_component]`](../macros/cgp_component.md) +already has, with no separate table type and no wrapper. + +**Prefer `open` for anything new.** This page is here because you will meet `UseDelegate` in existing +code and in CGP's own error and handler components, which are still defined with `#[derive_delegate]`. +It is expected to be deprecated once `open` is shown to cover every dispatch case. ::: + +## Overview + +`UseDelegate` chooses a provider based on a type argument rather than on the component alone. An +ordinary component picks its provider by looking the component name up in the **context**'s delegation +table, where the context is the type the capability runs against. But when a provider trait carries an +extra generic parameter, such as a `SourceError` to convert or a `Shape` to measure, the right provider +often depends on which concrete type that parameter is. `UseDelegate` performs a second lookup: it +treats one generic parameter as a key and reads the matching inner provider out of a table, so a single +wiring entry can fan out to many type-specific providers. + +This lets context-generic providers stay generic even when their implementations would otherwise overlap +on a parameter. Rather than one provider matching every possible `Shape`, you write a small provider per +shape and let `UseDelegate` route each concrete shape to its own. The dispatch is type-directed: the key +is a real type appearing in the trait, and the table maps that type to the provider responsible for it. +Like every CGP provider, `UseDelegate` holds no runtime value; the `Components` table is carried in +`PhantomData`. + +## Usage + +`UseDelegate` is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the +lookup table, and is most often written with an inline nested table using the `new` keyword: + +```rust +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +The `new` keyword declares the inner table `AreaCalculatorComponents` in place and maps each concrete +type to its provider. The component must be defined with a +[`#[derive_delegate(UseDelegate)]`](../attributes/derive_delegate.md) attribute naming the +parameter to dispatch on, which is what generates the `UseDelegate` provider impl that reads the table. + +## Examples + +`UseDelegate` is wired through a nested table that builds both the outer entry and the inner lookup in +one place. Given an area component that dispatches on a `Shape` parameter: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +#[derive_delegate(UseDelegate)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle; +pub struct Circle; + +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +The wiring reads in two layers. `MyApp` delegates `AreaCalculatorComponent` to +`UseDelegate`, so its area calculation routes through `UseDelegate` using that +table. The inner table maps the `Rectangle` type to `RectangleArea` and the `Circle` type to +`CircleArea`. The result is that `MyApp` implements `CanCalculateArea` through +`RectangleArea` and `CanCalculateArea` through `CircleArea`, with `UseDelegate` selecting between +them by the `Shape` argument. Adding a shape is one more entry in the inner table. + +The same dispatch, written with `open` for new code, folds the entries into the context's own table: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +## When to reach for it, and when not + +**Prefer the [`open` statement](../macros/delegate_components.md) for new per-type dispatch.** It needs +no separate table type, no `UseDelegate` wrapper, and no `#[derive_delegate]` on the component, because +it rides the [`RedirectLookup`](redirect_lookup.md) impl every component already generates. + +Read `UseDelegate` when you meet it in existing code, and keep using it where a component is still +defined with [`#[derive_delegate]`](../attributes/derive_delegate.md), including CGP's own error and +handler families. The dispatching-per-type choice is worked through in +[`#[derive_delegate]`](../attributes/derive_delegate.md). + +For dispatching on the *input* type of a handler rather than a `Code` parameter, the sibling provider is +[`UseInputDelegate`](handler_combinators.md). + +## Under the hood + +The [`#[derive_delegate(UseDelegate)]`](../attributes/derive_delegate.md) attribute on a +component generates the `UseDelegate` provider impl, which uses `Components` as the table and the named +parameter as the key. For a component such as `CanRaiseError` (provider `ErrorRaiser`) with +a `#[derive_delegate(UseDelegate)]` attribute, the generated impl is: + +```rust +impl ErrorRaiser + for UseDelegate +where + Context: HasErrorType, + Components: DelegateComponent, + Delegate: ErrorRaiser, +{ + fn raise_error(error: SourceError) -> Context::Error { + Delegate::raise_error(error) + } +} +``` + +The mechanism is a single [`DelegateComponent`](../traits/delegate_component.md) lookup keyed on +`SourceError`. `UseDelegate` implements `ErrorRaiser` for a given `SourceError` exactly when +`Components` maps that `SourceError` to a delegate that itself implements `ErrorRaiser`, and the method +forwards to it. Only the parameter named inside `UseDelegate<...>` is the key; the rest pass through +unchanged. Each impl is paired with an [`IsProviderFor`](../traits/is_provider_for.md) impl so +dependencies propagate to a check. A component may derive more than one dispatcher when different +parameters should be routed differently. + +## Related constructs + +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates this provider's impl; the page + that works through the legacy-versus-`open` choice. +- [`delegate_components!`](../macros/delegate_components.md) — wires it, usually through a nested table, + and carries the `open` statement that replaces it. +- [`RedirectLookup`](redirect_lookup.md) — the mechanism `open` rides instead. +- [`UseInputDelegate`](handler_combinators.md) — the sibling that keys on a handler's `Input` type. +- [`DelegateComponent`](../traits/delegate_component.md) — the table the lookup reads. +- [`IsProviderFor`](../traits/is_provider_for.md) — propagates the dispatched provider's dependencies. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the delegation table + this reuses, keyed on a type parameter rather than a component name. + +## Source + +- Struct: + [`use_delegate.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_delegate.rs) +- The generated impl comes from the `#[derive_delegate]` directive parsed in + [`types/attributes/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/) + and emitted by the + [`cgp_component`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component/) + pipeline. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index 7e3d7264..01286c7e 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -4,14 +4,160 @@ sidebar_label: 'UseDelegatedType' # `UseDelegatedType` -Resolve an abstract type through a lookup table instead of fixing it. +Resolve an abstract type by looking its tag up in a table, instead of fixing it to one concrete type. -:::info +## Overview -### Not written yet +`UseDelegatedType` is for the case where the concrete type an abstract type resolves to +should itself be decided by a table. The plain [`UseType`](use_type.md) provider binds an abstract +type to one fixed `T`. But sometimes a single provider must answer several abstract-type components at +once, or route each type tag to a different concrete type chosen elsewhere, such as when a namespace or +a higher-order provider supplies a coherent bundle of types. Hand-writing one `UseType` entry per tag +would scatter that decision; `UseDelegatedType` concentrates it into one `Components` table the provider +consults. As always, the **context** (the type a capability runs against) is what points its type +components at the provider. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +The mechanism is the same indirection [`UseDelegate`](use_delegate.md) provides for behavioral +components, lifted to the type level. Where `UseDelegate` dispatches a *method call* to +whichever provider `Components` maps the active tag to, `UseDelegatedType` dispatches a +*type resolution* to whichever concrete type `Components` maps the tag to. Both read an entry out of a +[`DelegateComponent`](../traits/delegate_component.md) table keyed by the tag, but one yields behavior +and the other yields a type. Like every CGP provider, it carries no runtime value. -::: +## Usage + +`UseDelegatedType` implements the built-in [`TypeProvider`](../components/has_type.md), so a +user-defined [`#[cgp_type]`](../macros/cgp_type.md) component is wired to it through its +[`WithProvider`](with_provider.md) alias, `WithDelegatedType`. Neither is in the prelude; import them +from `cgp::core::types`: + +```rust +use cgp::core::types::WithDelegatedType; +``` + +`WithDelegatedType` takes one type parameter, the lookup table, and appears as the value of +one or more abstract-type components' wiring entries: + +```rust +delegate_components! { + App { + [ + ScalarTypeProviderComponent, + IndexTypeProviderComponent, + ]: WithDelegatedType, + } +} +``` + +The `Components` parameter is a type that maps each type tag to a concrete type, built as an ordinary +[`delegate_components!`](../macros/delegate_components.md) table. Any tag the table has no entry for is +simply unresolved, and the context does not implement `HasType` for it. `WithDelegatedType` +is [`WithProvider>`](with_provider.md), and it is the form you wire, since +the bare `UseDelegatedType` provides the foundational `TypeProvider` rather than a named component's +provider trait. + +## Examples + +A typical use defines a lookup table mapping type tags to concrete types and wires a context's type +components through it. The table is an ordinary type carrying `DelegateComponent` entries: + +```rust +use cgp::prelude::*; +use cgp::core::types::WithDelegatedType; // not in the prelude + +#[cgp_type] +pub trait HasScalarType { + type Scalar; +} + +#[cgp_type] +pub trait HasIndexType { + type Index; +} + +pub struct App; +pub struct AppTypes; + +delegate_components! { + AppTypes { + ScalarTypeProviderComponent: f64, + IndexTypeProviderComponent: usize, + } +} + +delegate_components! { + App { + [ + ScalarTypeProviderComponent, + IndexTypeProviderComponent, + ]: WithDelegatedType, + } +} +``` + +`App` routes both its scalar and index type components through `WithDelegatedType`. When the +wiring asks for `App`'s `Scalar`, the provider looks `ScalarTypeProviderComponent` up in `AppTypes` and +finds `f64`; for `Index` it finds `usize`. One provider entry on `App` answers two abstract types, with +the concrete choices held in one place in `AppTypes` where they can be reused, swapped, or supplied by +a namespace. + +## When to reach for it, and when not + +**Reach for `UseDelegatedType` when several abstract types should be answered from one shared table**, +so a context points its type components at the table rather than fixing each one at the wiring site. +This is what makes a coherent bundle of types reusable across contexts or supplied by a namespace. + +Prefer [`UseType`](use_type.md) for the common case of fixing one abstract type to one concrete +type, which needs no table. + +## Under the hood + +`UseDelegatedType` implements [`TypeProvider`](../components/has_type.md) by looking the +type tag up in `Components` and reporting the delegate it finds as the abstract type: + +```rust +#[cgp_provider(TypeProviderComponent)] +impl TypeProvider for UseDelegatedType +where + Components: DelegateComponent, +{ + type Type = Type; +} +``` + +The `where` clause is the whole of the behavior. `Components: DelegateComponent` +reads the entry stored at key `Tag` in the table, and the impl sets the abstract `Type` to that +delegate. Because the lookup is keyed by `Tag`, one `UseDelegatedType` answers as many +distinct type tags as `Components` has entries, each resolving to its own concrete type. If the table +has no entry for a tag, the `DelegateComponent` bound is unsatisfied and the context does not implement +`HasType` for that tag. Contrast [`UseType`](use_type.md), whose impl is unconditional and always +reports the single type `T`: `UseDelegatedType` adds exactly one level of indirection, the +`DelegateComponent` lookup. + +## Related constructs + +- [`UseType`](use_type.md) — the simpler sibling that fixes an abstract type to one concrete type. +- [`UseDelegate`](use_delegate.md) — the behavioral counterpart that dispatches a method call through + the same kind of table. +- [`DelegateComponent`](../traits/delegate_component.md) — the table it reads. +- [`HasType` / `TypeProvider`](../components/has_type.md) — the abstract-type component it answers for. +- [`WithProvider`](with_provider.md) — the adapter behind the `WithDelegatedType` alias. +- [`#[cgp_type]`](../macros/cgp_type.md) — defines the abstract-type components it resolves. + +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — the associated types a context chooses for itself, + here from a shared table. + +## Source + +- Struct, `WithDelegatedType` alias, and the `TypeProvider` impl: + [`use_delegated_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/impls/use_delegated_type.rs) +- The `HasType`/`TypeProvider` traits: + [`has_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/traits/has_type.rs); + `DelegateComponent`: + [`delegate_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/delegate_component.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index e0ad48d7..ab7d81d3 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -1,17 +1,184 @@ --- -sidebar_label: 'UseField, UseFieldRef & UseFields' +sidebar_label: 'UseField' --- -# `UseField`, `UseFieldRef` & `UseFields` +# `UseField` -The field-backed getter providers, and how to choose between them. +Implement a getter component by reading a context field named by a tag, so the field name is a wiring +decision rather than the method name. -:::info +## Overview -### Not written yet +`UseField` decouples a getter's method name from the field it reads. A getter component defined +with [`#[cgp_getter]`](../macros/cgp_getter.md) describes a value the context can supply, such as +`fn name(&self) -> &str`. The **context** is the type the capability runs against, and it supplies +that value as one of its own fields. But the context may store the value under a different field name, +say `first_name`, and different contexts may store it under different names. `UseField` carries +the field name as its type parameter, so wiring a getter to `UseField` makes it +read `first_name` even though the method is `name`. The field name lives in the wiring, not in the +trait. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +This is the provider that [`#[cgp_getter]`](../macros/cgp_getter.md) targets. That macro generates a +`UseField` implementation for the getter's provider trait with the field tag left as a free parameter, +so a context picks the field by writing `UseField` in its wiring table. `UseField` +itself is the general provider underneath: it works for any tag the context's +[`HasField`](../traits/has_field.md) implementation supports. -::: +The `Tag` is usually a type-level string built with [`Symbol!`](../macros/symbol.md), such as +`Symbol!("name")`, or a type-level integer wrapped in `Index` for a tuple field. These are the tags +that [`#[derive(HasField)]`](../derives/derive_has_field.md) produces `HasField` implementations for. +Like every CGP provider, `UseField` carries no runtime value: it is a `PhantomData` marker named +in wiring, never constructed. + +## Usage + +`UseField` is in the prelude, so `use cgp::prelude::*;` is enough to name it. It takes one type +parameter, the field tag, and appears as the value of a getter component's wiring entry: + +```rust +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} +``` + +The tag is a [`Symbol!`](../macros/symbol.md) for a named field or an `Index` for a tuple field. +The context must have a `HasField` implementation for that tag, which +[`#[derive(HasField)]`](../derives/derive_has_field.md) supplies for every field of a struct. + +`UseField` has an alias, `WithField`, which is +[`WithProvider>`](with_provider.md). Both bind the same field; the alias routes through +the `WithProvider` adapter instead of the getter's own generated `UseField` implementation. Prefer the +plain `UseField` form. + +## Examples + +The defining use wires a getter to a field whose name differs from the method, which is the case the +simpler [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) cannot express. The method is `name`, but +the context stores the value in `first_name`: + +```rust +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} + +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} + +fn greet(person: &Person) { + println!("Hello, {}!", person.name()); // reads the first_name field +} +``` + +`Person` wires `NameGetterComponent` to `UseField`, so `person.name()` reads +the `first_name` field. The method name and the field name diverge, and the field name comes entirely +from the wiring. + +The same binding can be written with the `WithField` alias, which routes through +[`WithProvider`](with_provider.md): + +```rust +delegate_components! { + Person { + NameGetterComponent: WithField, + } +} +``` + +Both read `first_name`. + +## When to reach for it, and when not + +**Reach for `UseField` only when the field name must differ from the method name**, or when a context +needs full control over which field a getter reads from. That is the advanced case +[`#[cgp_getter]`](../macros/cgp_getter.md) exists for, and `UseField` is the provider it is wired to. + +For the common case of reading a field, prefer an [`#[implicit]`](../attributes/implicit.md) argument +instead, which reads a same-named field and looks like an ordinary function parameter with no getter +trait at all. Where a getter trait is genuinely needed but the field name matches the method name, use +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md), or wire [`UseFields`](use_fields.md), which keys +each method on its own name. The [`#[cgp_getter]`](../macros/cgp_getter.md) page works the choice +through in full. + +`UseField` already handles the common borrowed-view getters: a `-> &str` getter over a `String` field +and a `-> &[u8]` getter over a `Vec` field work through `UseField`, because the generated +implementation borrows through `as_str()` or `as_ref()` based on the return type. Two neighbours cover +the cases it does not. When a getter returns `&T` and the field is stored as a different type that +borrows to `T` through `AsRef`, use [`UseFieldRef`](use_field_ref.md). When the field lives several hops +inside a nested context, use [`ChainGetters`](chain_getters.md). + +## Under the hood + +`UseField` implements three provider traits, each forwarding to the context's +[`HasField`](../traits/has_field.md) implementation for `Tag`. The central one is the provider-side +getter [`FieldGetter`](../traits/field_getter.md), which reads the field by reference: + +```rust +impl FieldGetter for UseField +where + Context: HasField, +{ + type Value = Value; + + fn get_field(context: &Context, _tag: PhantomData) -> &Value { + context.get_field(PhantomData) + } +} +``` + +Two tags appear for a reason. `OutTag` is the tag the *component* asks under, the getter's own name, +while `Tag` is the *field* tag the provider was parameterized with. The implementation ignores `OutTag` +and reads `Tag` from the context, which is the decoupling: the component's identity and the field name +are independent. The associated `Value` comes from the context's `HasField` implementation, so +the returned reference is to the real field. + +`UseField` also implements the mutable getter [`MutFieldGetter`](../traits/mut_field_getter.md) +the same way, requiring `Context: HasFieldMut` and returning `&mut Value`. And it implements +[`TypeProvider`](../components/has_type.md), reporting the field's `Value` type as an abstract type, so +the *type* of a field can itself be wired as a context's abstract type. Each implementation is paired +with an [`IsProviderFor`](../traits/is_provider_for.md) implementation carrying the same `HasField` +bound, so delegation propagates the dependency and a check reports a missing field precisely. + +## Related constructs + +- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that generates a `UseField` implementation for + a getter and makes the field a wiring decision. +- [`UseFields`](use_fields.md) — the sibling that keys every method on its own name, with no tag. +- [`UseFieldRef`](use_field_ref.md) — the foundational getter for a stored type that borrows to a + different return type through `AsRef`. +- [`ChainGetters`](chain_getters.md) — reaches a field on a nested context by composing getters. +- [`WithProvider`](with_provider.md) — the adapter behind the `WithField` alias. +- [`UseType`](use_type.md) — the abstract-type analogue for a `#[cgp_type]` component. +- [`HasField`](../traits/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the + consumer-side field access this reads, keyed by [`Symbol!`](../macros/symbol.md) or `Index`. +- [`delegate_components!`](../macros/delegate_components.md) — wires it, and + [`check_components!`](../macros/check_components.md) verifies the field is present. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — value injection through a + provider's own requirements, of which reading a field is the most common form. + +## Source + +- Struct, `WithField` alias, and the `FieldGetter`/`MutFieldGetter`/`TypeProvider` impls: + [`use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs) +- The traits it implements: [`cgp-field/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-field/src/traits/) +- The `#[cgp_getter]`-generated `UseField` impl: + [`cgp_getter/use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_getter/use_field.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md new file mode 100644 index 00000000..aa0cb49c --- /dev/null +++ b/docs/reference/providers/use_field_ref.md @@ -0,0 +1,169 @@ +--- +sidebar_label: 'UseFieldRef' +--- + +# `UseFieldRef` + +The foundational field getter that borrows a field through `AsRef`/`AsMut`, for the case where the +stored type differs from the getter's return type. + +## Overview + +`UseFieldRef` reads the field named by `Tag` from the **context** (the type the capability +runs against, which supplies the field) and borrows it through `AsRef` to produce a `&Value`, where the +stored field type implements `AsRef`. It exists for a getter whose return type is reached +*through* a field rather than being the field's own type: a `&Config` from a stored `Arc`, for +example, where the field is not a `Config` but can be borrowed as one. + +`UseFieldRef` is a foundational [`FieldGetter`](../traits/field_getter.md) rather than a getter +component's own provider, so it is wired through the [`WithProvider`](with_provider.md) adapter using its +`WithFieldRef` alias. That distinguishes it from [`UseField`](use_field.md), which +[`#[cgp_getter]`](../macros/cgp_getter.md) generates a getter-component implementation for directly. + +Most borrowed-view getters do not need `UseFieldRef` at all, and this is the key thing to know before +reaching for it. When a getter's return type is one of the shorthands the getter macros recognize, +`&str` or `&[u8]`, the generated [`UseField`](use_field.md) implementation already borrows for you: it +reads the field and calls `as_str()` or `as_ref()`, so a `&str` getter over a `String` field, or a +`&[u8]` getter over a `Vec` field, is wired with a plain `UseField`. `UseFieldRef` is for the +remaining case, a getter that returns `&T` for some type `T` the field is not stored as but can be +borrowed as. Like every CGP provider, it carries no runtime value. + +## Usage + +`UseFieldRef` is not in the prelude, and neither is its `WithFieldRef` alias. Import them from +`cgp::core::field::impls`: + +```rust +use cgp::core::field::impls::WithFieldRef; +``` + +`WithFieldRef` is [`WithProvider>`](with_provider.md), and it is the +form you wire, since the bare `UseFieldRef` provides the foundational `FieldGetter` rather than a named +getter's provider trait. It takes the field tag and the borrowed value type, and appears as the value of +a getter component's wiring entry: + +```rust +delegate_components! { + App { + ConfigGetterComponent: WithFieldRef, + } +} +``` + +`Tag` names the field, as in [`UseField`](use_field.md), and `Value` is the type the getter exposes. The +stored field type must implement `AsRef` (and, for the mutable getter, `AsMut`), and the +getter's return type must be `&Value`. + +## Examples + +A getter returns `&Config` while the context stores the config in a wrapper that borrows as `Config`. +The wrapper implements `AsRef`, so `WithFieldRef` reads it and borrows through it: + +```rust +use cgp::prelude::*; +use cgp::core::field::impls::WithFieldRef; // not in the prelude + +pub struct Config { + pub port: u16, +} + +pub struct StoredConfig(pub Config); + +impl AsRef for StoredConfig { + fn as_ref(&self) -> &Config { + &self.0 + } +} + +#[cgp_getter] +pub trait HasConfig { + fn config(&self) -> &Config; +} + +#[derive(HasField)] +pub struct App { + pub config: StoredConfig, +} + +delegate_components! { + App { + ConfigGetterComponent: WithFieldRef, + } +} +``` + +`App` wires `ConfigGetterComponent` to `WithFieldRef`. The provider reads the +`config` field, a `StoredConfig`, and because `StoredConfig: AsRef`, returns `&Config` from +`as_ref()`. The getter exposes the borrowed `Config` view while the context owns the `StoredConfig`. + +## When to reach for it, and when not + +**Reach for `UseFieldRef` when a getter returns `&T` and the context stores a different type that +borrows as `T` through `AsRef`.** The stored type and the exposed type differ, and neither the plain +[`UseField`](use_field.md) nor an [`#[implicit]`](../attributes/implicit.md) argument can bridge them. + +Prefer [`UseField`](use_field.md) for the common borrowed-view getters. A `-> &str` getter over a +`String` field and a `-> &[u8]` getter over a `Vec` field are handled by the generated `UseField` +implementation, which borrows through `as_str()` or `as_ref()` based on the return type, so they need no +`UseFieldRef`. And for a field returned as its own type, an `#[implicit]` argument is simpler still. + +## Under the hood + +`UseFieldRef` implements the provider-side getter +[`FieldGetter`](../traits/field_getter.md) by reading the field at `Tag` and dereferencing it to +`&Value`: + +```rust +impl FieldGetter for UseFieldRef +where + Context: HasField + 'static>, +{ + type Value = Value; + + fn get_field(context: &Context, _tag: PhantomData) -> &Value { + context.get_field(PhantomData).as_ref() + } +} +``` + +The `where` clause carries the defining constraint: the context's field at `Tag` must implement +`AsRef`, so the stored type can be borrowed as the exposed type. As in +[`UseField`](use_field.md), `OutTag` is the tag the component asks under and is ignored, while the field +is read at `Tag`. The body reads the field and calls `as_ref()`. The `'static` bound on the field type +lets Rust infer the borrow's lifetime through the `AsRef` call. + +`UseFieldRef` also implements the mutable getter [`MutFieldGetter`](../traits/mut_field_getter.md), +requiring the field type to implement both `AsRef` and `AsMut` and returning `&mut Value` +through `as_mut()`. Because these are `FieldGetter` implementations rather than a getter component's own +provider trait, the [`WithProvider`](with_provider.md) adapter behind `WithFieldRef` is what turns +`UseFieldRef` into a provider a getter component can be wired to. Unlike [`UseField`](use_field.md), it +does not implement [`TypeProvider`](../components/has_type.md), because its purpose is borrowed field +access rather than abstract-type resolution. + +## Related constructs + +- [`UseField`](use_field.md) — the getter provider that reads a field directly, and that already handles + the `&str`/`&[u8]` borrowed shorthands. +- [`WithProvider`](with_provider.md) — the adapter behind the `WithFieldRef` alias, which turns + `UseFieldRef` into a getter-component provider. +- [`ChainGetters`](chain_getters.md) — another foundational `FieldGetter`, composed for nested contexts. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that defines the getter this is wired to. +- [`FieldGetter`](../traits/field_getter.md) and [`MutFieldGetter`](../traits/mut_field_getter.md) — the + provider-side getters it implements, over [`HasField`](../traits/has_field.md). + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — value injection through a + provider's own requirements, of which a getter is one form. + +## Source + +- Struct, `WithFieldRef` alias, and the `FieldGetter`/`MutFieldGetter` impls: + [`use_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_ref.rs) +- The traits it implements: + [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) + and [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md new file mode 100644 index 00000000..9d8d4f0a --- /dev/null +++ b/docs/reference/providers/use_fields.md @@ -0,0 +1,161 @@ +--- +sidebar_label: 'UseFields' +--- + +# `UseFields` + +Implement a getter component by reading each method's value from the context field named after the +method. + +## Overview + +`UseFields` is the provider form of the convention "the method `name` reads the field `name`." A getter +component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes one or more values the +**context** can supply, and the most common arrangement is that each value lives in a same-named field. +The context is the type the capability runs against, and it supplies those values as its own fields. +`UseFields` is the provider that realizes the arrangement: wiring a getter to `UseFields` makes every +method read the context field whose name equals the method name, looked up through +[`HasField`](../traits/has_field.md) keyed by a [`Symbol!`](../macros/symbol.md). + +This is the provider analogue of the blanket implementation that +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) emits. `#[cgp_auto_getter]` produces a single +blanket implementation that fires automatically for any context whose field names match the method +names, with nothing to wire. `UseFields` packages the same field-by-method-name behavior as a provider +that a [`#[cgp_getter]`](../macros/cgp_getter.md) component can be wired to, so a getter that +participates in CGP wiring can still opt into the auto-getter convention when its fields line up with +its methods. + +`UseFields` is distinct from its sibling [`UseField`](use_field.md), and the singular-versus-plural +naming marks the difference. `UseField` keys on a tag the wiring chooses, letting one method read +a field of any name; `UseFields` takes no parameter and keys every method on its own name. Reach for +`UseField` when the field name must differ from the method name, and for `UseFields` when the +convention holds. Like every CGP provider, `UseFields` carries no runtime value: it is a marker named +in wiring. + +## Usage + +`UseFields` is in the prelude, so `use cgp::prelude::*;` is enough. It takes no type parameter and +appears as the value of a getter component's wiring entry: + +```rust +delegate_components! { + App { + FooGetterComponent: UseFields, + } +} +``` + +Every method of the getter reads the context field whose name equals the method name. The context must +have a `HasField` implementation for each of those names, which +[`#[derive(HasField)]`](../derives/derive_has_field.md) supplies. The return-type shorthands the getter +macros support apply here too, so a `&str` return reads a `String` field and appends `.as_str()`. + +## Examples + +A context whose field name matches the getter method can be wired to `UseFields` to get the auto-getter +convention inside a `#[cgp_getter]` component. The method `foo` and the field `foo` share a name: + +```rust +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasFoo { + fn foo(&self) -> &str; +} + +#[derive(HasField)] +pub struct App { + pub foo: String, +} + +delegate_components! { + App { + FooGetterComponent: UseFields, + } +} + +fn describe(app: &App) -> &str { + app.foo() // reads the `foo` field +} +``` + +Because `App` wires `FooGetterComponent` to `UseFields`, the getter reads `App`'s `foo` field, the +field whose name equals the method `foo`. If the value were stored under a differently named field, +this wiring would not apply, and the context would wire [`UseField`](use_field.md) with +the actual field name instead. + +## When to reach for it, and when not + +**Reach for `UseFields` when a `#[cgp_getter]` component's methods each read a same-named field.** It is +the wired counterpart of the [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) convention, for the +case where the getter is a full component rather than a blanket impl. + +Prefer [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) when the getter does not need to be a +wireable component, and prefer an [`#[implicit]`](../attributes/implicit.md) argument when a provider +simply needs a value from its own context, which is the common case and needs no getter trait at all. +Reach for [`UseField`](use_field.md) instead when the field name must differ from the method name. + +## Under the hood + +[`#[cgp_getter]`](../macros/cgp_getter.md) generates a `UseFields` implementation of the getter's +provider trait, reading each method's value from the field whose name matches the method, keyed by a +`Symbol!`. For a single-method getter such as + +```rust +#[cgp_getter] +pub trait HasFoo { + fn foo(&self) -> &str; +} +``` + +the macro emits this `UseFields` implementation for the generated `FooGetter` provider trait (shown +with the macro's real placeholder identifiers, and with `Symbol!("foo")` in sugared form): + +```rust +impl<__Context__> FooGetter<__Context__> for UseFields +where + __Context__: HasField, +{ + fn foo(__context__: &__Context__) -> &str { + __context__.get_field(PhantomData::).as_str() + } +} +``` + +Each method becomes a `HasField` bound keyed on the method name as a `Symbol!`, and the body reads that +field. The `&str` return makes the field `Value` a `String` and appends `.as_str()`, the same shorthand +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) uses. When a getter has several methods, the +implementation carries one `HasField` bound and one body per method, each keyed by its own name. The +implementation is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md), so a check +reports a missing field precisely. + +This is one of three provider implementations `#[cgp_getter]` generates for a getter component. The +other two are [`UseField`](use_field.md), for a wiring-chosen field name, and +[`WithProvider`](with_provider.md), for adapting a foundational field getter. A context picks among +them at wiring time. + +## Related constructs + +- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that generates this implementation. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — the blanket-impl form of the same convention, + for a getter that need not be wired. +- [`UseField`](use_field.md) — the sibling that keys on a wiring-chosen tag instead of the method name. +- [`WithProvider`](with_provider.md) — the third getter provider `#[cgp_getter]` emits. +- [`HasField`](../traits/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the + field access it reads, keyed by [`Symbol!`](../macros/symbol.md) on the method name. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — value injection through a + provider's own requirements, of which a getter is one form. + +## Source + +- Struct: + [`use_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_fields.rs) +- The `#[cgp_getter]`-generated `UseFields` impl: + [`cgp_getter/to_use_fields_impl.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_getter/to_use_fields_impl.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index a8a27098..bf4e1d86 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -1,17 +1,176 @@ --- -sidebar_label: 'UseType' +sidebar_label: 'UseType (provider)' --- -# `UseType` +# `UseType` (provider) -Supply a concrete type for an abstract-type component. +Supply a concrete type as the value of an abstract-type component, binding it purely through wiring. :::info -### Not written yet +### Not the same as `#[use_type]` -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +This page documents the `UseType` **provider**, the struct `UseType`. It is a different construct +from the [`#[use_type]` attribute](../attributes/use_type.md), which rewrites bare type names inside a +definition and adds the owning trait as a bound. The attribute is about *referring to* an abstract type +ergonomically; the provider here is about *choosing the concrete type* an abstract type resolves to. +They share a name because both concern abstract types, but they live in different places and do +different jobs. ::: + +## Overview + +`UseType` removes the need to hand-write a provider every time a **context** wants to fix an +abstract type to a concrete one. The context is the type a capability runs against, and it decides what +each abstract type resolves to. An abstract type in CGP is a trait with a single associated type, +defined with [`#[cgp_type]`](../macros/cgp_type.md), such as `trait HasScalarType { type Scalar; }`. +Generic code refers to the type without committing to any particular one, and a concrete context +decides what it actually is. Without `UseType`, making that decision would mean writing a small +provider whose only content is `type Scalar = f64;`, repeated for every abstract type and every +concrete choice. + +`UseType` captures that trivial shape once. It is a [`TypeProvider`](../components/has_type.md) that +reports its type parameter `T` as the abstract type, so wiring a context's type component to +`UseType` sets the abstract type to `f64` with no custom impl. It is the type-level counterpart of +[`UseField`](use_field.md), which lets a getter read a field named by a parameter: a general provider +parameterized by exactly the thing the context wants to supply. Like every CGP provider, it carries no +runtime value. + +## Usage + +`UseType` is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the +concrete type to supply, and appears as the value of an abstract-type component's wiring entry: + +```rust +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } +} +``` + +A `#[cgp_type]` trait such as `HasScalarType` generates the provider trait `ScalarTypeProvider` and the +component marker `ScalarTypeProviderComponent`; wiring that marker to `UseType` sets the context's +`Scalar` to `f64`. Any bound on the associated type, such as `type Scalar: Copy`, is enforced against +the concrete type at the wiring site. + +`UseType` has an alias, `WithType`, which is +[`WithProvider>`](with_provider.md); it is imported from `cgp::core::types`. Both bind +the same type. Prefer the plain `UseType` form. + +## Examples + +A complete use defines an abstract type, wires a concrete type with `UseType`, and reads it back: + +```rust +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar: Copy; +} + +pub struct App; + +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } +} +``` + +`App` wires `ScalarTypeProviderComponent` to `UseType`, so `App` implements `HasScalarType` with +`Scalar = f64`. The `Copy` bound on the associated type is checked against `f64` where the wiring is +written. + +The same binding can be written with the `WithType` alias, which routes through +[`WithProvider`](with_provider.md): + +```rust +use cgp::core::types::WithType; // not in the prelude + +delegate_components! { + App { + ScalarTypeProviderComponent: WithType, + } +} +``` + +Both make `App::Scalar` resolve to `f64`. + +## When to reach for it, and when not + +**Reach for `UseType` to bind an abstract type to a concrete one, which is the common case.** It is +the idiomatic value for a [`#[cgp_type]`](../macros/cgp_type.md) component's wiring entry, and it saves +writing a one-line provider by hand. + +Reach for [`UseDelegatedType`](use_delegated_type.md) when the concrete type should itself come from a +lookup table rather than being fixed at the wiring site, which lets one entry answer several type +components at once. And do not confuse this provider with the +[`#[use_type]` attribute](../attributes/use_type.md), which imports an abstract type into a definition +and is unrelated to choosing the concrete type. + +## Under the hood + +`UseType` implements the built-in provider trait [`TypeProvider`](../components/has_type.md) for +every context and tag, setting its associated `Type` to the struct's own type parameter: + +```rust +#[cgp_provider(TypeProviderComponent)] +impl TypeProvider for UseType { + type Type = Type; +} +``` + +The implementation is unconditional in `Context` and `Tag`: `UseType` is a `TypeProvider` whose +`Type` is `f64` regardless of which context or type tag asks. `HasType` is the consumer trait that +reads this, so once a context's type component is wired to `UseType`, the context implements +`HasType` with `Type = f64`. + +The same provider is what [`#[cgp_type]`](../macros/cgp_type.md) targets. For +`#[cgp_type] trait HasScalarType { type Scalar; }`, the macro generates a `UseType` implementation for +the component's own provider trait: + +```rust +impl ScalarTypeProvider<__Context__> for UseType { + type Scalar = Scalar; +} +``` + +so wiring `ScalarTypeProviderComponent` to `UseType` sets `Scalar = f64`. The built-in +`TypeProvider` impl and the per-component impl are the two faces of the same `UseType` struct: the +first makes it a provider for the built-in `HasType` component, the second for a user-defined +abstract-type component. A bound on the associated type is copied into the generated impl's `where` +clause, so the concrete type must satisfy it at the wiring site. + +## Related constructs + +- [`#[cgp_type]`](../macros/cgp_type.md) — defines the abstract type and generates the `UseType` impl + that `UseType` supplies the concrete type for. +- [`#[use_type]` attribute](../attributes/use_type.md) — the differently-named construct that imports an + abstract type into a definition; do not confuse the two. +- [`HasType` / `TypeProvider`](../components/has_type.md) — the built-in abstract-type component this + implements. +- [`UseDelegatedType`](use_delegated_type.md) — resolves an abstract type through a table instead of + fixing it. +- [`WithProvider`](with_provider.md) — the adapter behind the `WithType` alias. +- [`UseField`](use_field.md) — the field-level analogue for getter components. + +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — the associated types a context chooses for itself, + which this provider supplies. + +## Source + +- Struct, `WithType` alias, and the built-in `TypeProvider` impl: + [`use_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/impls/use_type.rs) +- The `HasType`/`TypeProvider` traits: + [`has_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/traits/has_type.rs) +- The `#[cgp_type]`-generated `UseType` impl: + [`cgp_type/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_type/item.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 87318084..e5889203 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -4,14 +4,180 @@ sidebar_label: 'WithProvider' # `WithProvider` -Adapt a foundational provider into a named component, with its `WithType`/`WithField`/`WithContext` aliases. +Adapt a foundational provider, one implementing `TypeProvider` or `FieldGetter`, into a provider of a +specific named component. -:::info +## Overview -### Not written yet +`WithProvider` bridges CGP's two layers of provider trait. Foundational traits like +[`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field_getter.md) are generic, +component-agnostic mechanisms: a `TypeProvider` supplies *some* abstract type for *some* tag, and a +`FieldGetter` reads *some* field for *some* output tag, without either knowing which named component it +serves. A named component, by contrast, has a specific provider trait, such as `NameTypeProvider` or +`NameGetter`, that a **context** wires to, where the context is the type the capability runs against. +`WithProvider` is the adapter that lets a foundational provider stand in as the provider for +one of those named components: it implements the component's provider trait by forwarding to the +foundational provider's method. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +This adapter is what lets the foundational layer be wired without each foundational provider +implementing every component trait by hand. A field getter written once as a `FieldGetter` can serve any +number of getter components through `WithProvider`, and an abstract-type implementation written once as +a `TypeProvider` can serve any type component the same way. -::: +`WithProvider` is rarely written in full, because its common uses are packaged as aliases. The family +`WithContext`, `WithType`, `WithField`, `WithFieldRef`, and `WithDelegatedType` are each +`WithProvider<...>` specialized to a particular inner provider, and those aliases are what appear in +everyday wiring. Understanding `WithProvider` is what explains why the aliases work. Like every CGP +provider, it carries no runtime value. + +## Usage + +`WithProvider` is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the +foundational provider to adapt, and appears as the value of a named component's wiring entry. In +practice you write one of its aliases instead: + +| Alias | Expands to | Import from | +|---|---|---| +| `WithContext` | `WithProvider` | prelude | +| `WithType` | `WithProvider>` | `cgp::core::types` | +| `WithField` | `WithProvider>` | `cgp::core::field::impls` | +| `WithFieldRef` | `WithProvider>` | `cgp::core::field::impls` | +| `WithDelegatedType` | `WithProvider>` | `cgp::core::types` | + +Each alias wires the inner provider it names as a specific component's provider. A component becomes +adaptable this way only when its macro generates the `WithProvider` impl: +[`#[cgp_type]`](../macros/cgp_type.md) does so for every abstract-type component, and +[`#[cgp_getter]`](../macros/cgp_getter.md) does so for a getter with exactly one method. + +## Examples + +The everyday way to use `WithProvider` is through one of its aliases, which reads as a single wiring +choice. Adapting the context's own field getter into a getter component uses `WithField`: + +```rust +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} + +delegate_components! { + Person { + NameGetterComponent: WithField, + } +} +``` + +`WithField` expands to `WithProvider>`, so +`Person`'s `NameGetter` provider is the adapter wrapping the foundational +[`UseField`](use_field.md) getter for the `first_name` field. The generated `WithProvider` impl forwards +`name()` to `UseField`'s `FieldGetter::get_field`, which reads `first_name`. The same shape recurs for +abstract types: wiring a type component to `WithType` adapts [`UseType`](use_type.md), +and to `WithDelegatedType` adapts a [`UseDelegatedType`](use_delegated_type.md) that resolves +the type through a table. + +## When to reach for it, and when not + +**Reach for one of the aliases, not `WithProvider` directly.** `WithField`, `WithType`, `WithContext`, +`WithFieldRef`, and `WithDelegatedType` are the readable forms, and they are interchangeable with the +plain providers they wrap: wiring a getter to `WithField` and to +[`UseField`](use_field.md) both read the same field. Prefer the plain provider +([`UseField`](use_field.md), [`UseType`](use_type.md)) where it applies, and the `With...` alias where a +component is reached only through the `WithProvider` adapter. + +Write `WithProvider` in full only when adapting a foundational provider that has no ready +alias. + +## Under the hood + +[`#[cgp_type]`](../macros/cgp_type.md) and [`#[cgp_getter]`](../macros/cgp_getter.md) generate a +`WithProvider` impl that forwards a component's provider-trait method to the inner provider's +foundational method. For a type component such as + +```rust +#[cgp_type] +pub trait HasNameType { + type Name; +} +``` + +`#[cgp_type]` emits a `WithProvider` impl that defines the component's associated type from the inner +`TypeProvider` (shown with the macro's real placeholder identifiers): + +```rust +impl<__Provider__, Name, __Context__> NameTypeProvider<__Context__> for WithProvider<__Provider__> +where + __Provider__: TypeProvider<__Context__, NameTypeProviderComponent, Type = Name>, +{ + type Name = Name; +} +``` + +For a single-method getter, `#[cgp_getter]` emits an analogous impl that reads the value through the +inner `FieldGetter`: + +```rust +impl<__Context__, __Provider__> NameGetter<__Context__> for WithProvider<__Provider__> +where + __Provider__: FieldGetter<__Context__, NameGetterComponent, Value = String>, +{ + fn name(__context__: &__Context__) -> &str { + __Provider__::get_field(__context__, PhantomData::).as_str() + } +} +``` + +In both cases the bound names the foundational trait, keyed by the component marker, and the method or +associated type forwards to it. `#[cgp_getter]` generates the `WithProvider` impl only when the getter +has exactly one method, since a single foundational getter cannot serve several methods at once. Each +impl is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl. + +The aliases specialize `WithProvider` to a fixed inner provider so the common cases need no +`WithProvider<...>` spelled out. `WithContext = WithProvider` adapts the context's own +consumer-trait implementation; `WithType` and `WithField` adapt the foundational type and +field providers; `WithFieldRef` adapts a getter that borrows through `AsRef`; and +`WithDelegatedType` adapts a type provider that looks its type up in a table. Each alias +lives beside the inner provider it wraps. + +## Related constructs + +- [`#[cgp_type]`](../macros/cgp_type.md) and [`#[cgp_getter]`](../macros/cgp_getter.md) — generate the + `WithProvider` impls that make a component adaptable. +- [`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field_getter.md) — the + foundational traits it adapts. +- [`UseContext`](use_context.md), [`UseType`](use_type.md), [`UseField`](use_field.md), + [`UseFieldRef`](use_field_ref.md), and [`UseDelegatedType`](use_delegated_type.md) — the inner + providers its aliases wrap. +- [`delegate_components!`](../macros/delegate_components.md) — wires the aliases, and + [`check_components!`](../macros/check_components.md) verifies them. + +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — where the `TypeProvider` layer this adapts is used. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the provider-trait layer + the adapter bridges. + +## Source + +- Struct: + [`with_provider.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/with_provider.rs); + the `WithContext` alias in + [`use_context.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_context.rs) +- The `WithType`/`WithDelegatedType` aliases in + [`cgp-type/src/impls/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-type/src/impls/), + and `WithField`/`WithFieldRef` in + [`cgp-field/src/impls/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-field/src/impls/) +- The generated `WithProvider` impls: + [`cgp_type/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_type/item.rs) + and + [`cgp_getter/with_provider.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_getter/with_provider.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/example-code/src/reference/mod.rs b/example-code/src/reference/mod.rs index 3c799293..e9c71eda 100644 --- a/example-code/src/reference/mod.rs +++ b/example-code/src/reference/mod.rs @@ -6,4 +6,5 @@ pub mod derives; pub mod errors; pub mod macros; +pub mod providers; pub mod traits; diff --git a/example-code/src/reference/providers/chain_getters.rs b/example-code/src/reference/providers/chain_getters.rs new file mode 100644 index 00000000..e74e9459 --- /dev/null +++ b/example-code/src/reference/providers/chain_getters.rs @@ -0,0 +1,52 @@ +//! Code from `docs/reference/providers/chain_getters.md` — *`ChainGetters`*. +//! +//! Pins that a chain, wired as a getter provider through `WithProvider`, reaches a field on a nested +//! inner context: `App` holds a `Config`, and the getter reads the `Config`'s `name`. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::ChainGetters; + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Config { + pub name: String, + } + + #[derive(HasField)] + pub struct App { + pub config: Config, + } + + delegate_components! { + App { + NameGetterComponent: WithProvider< + ChainGetters, + UseField, + ]>, + >, + } + } + + check_components! { + App { + NameGetterComponent, + } + } + + #[test] + fn test_chain_getters_reaches_nested_field() { + let app = App { + config: Config { + name: "test".to_owned(), + }, + }; + assert_eq!(app.name(), "test"); + } +} diff --git a/example-code/src/reference/providers/mod.rs b/example-code/src/reference/providers/mod.rs new file mode 100644 index 00000000..0a133ed5 --- /dev/null +++ b/example-code/src/reference/providers/mod.rs @@ -0,0 +1,16 @@ +//! Code from the pages under `docs/reference/providers/`, one module per page. +//! +//! The section is filled in lazily, so the modules here are the pages someone has written, revised, +//! or reviewed rather than the section's full inventory. + +pub mod chain_getters; +pub mod redirect_lookup; +pub mod use_context; +pub mod use_default; +pub mod use_delegate; +pub mod use_delegated_type; +pub mod use_field; +pub mod use_field_ref; +pub mod use_fields; +pub mod use_type; +pub mod with_provider; diff --git a/example-code/src/reference/providers/redirect_lookup.rs b/example-code/src/reference/providers/redirect_lookup.rs new file mode 100644 index 00000000..a83f89db --- /dev/null +++ b/example-code/src/reference/providers/redirect_lookup.rs @@ -0,0 +1,21 @@ +//! Code from `docs/reference/providers/redirect_lookup.md` — *`RedirectLookup`*. +//! +//! `RedirectLookup` is generated machinery, so the only user-writable code the page shows is the +//! namespace registration that produces the redirect entries. This pins that that registration +//! compiles. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + pub struct App; + pub struct TestProvider; + + delegate_components! { + App { + namespace DefaultNamespace; + + @bar.baz: TestProvider, + } + } +} diff --git a/example-code/src/reference/providers/use_context.rs b/example-code/src/reference/providers/use_context.rs new file mode 100644 index 00000000..5451f174 --- /dev/null +++ b/example-code/src/reference/providers/use_context.rs @@ -0,0 +1,58 @@ +//! Code from `docs/reference/providers/use_context.md` — *`UseContext`*. +//! +//! Pins the non-cyclic default-inner-provider use: a loud greeter wraps the context's own greeter +//! through `UseContext`, delegating to a *different* component so there is no cycle. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_component(LoudGreeter)] + pub trait CanGreetLoudly { + fn greet_loudly(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello".to_owned() + } + } + + pub struct GreetLoudly(pub PhantomData); + + #[cgp_impl(GreetLoudly)] + #[use_provider(Inner: Greeter)] + impl LoudGreeter { + fn greet_loudly(&self) -> String { + format!("{}!", Inner::greet(self).to_uppercase()) + } + } + + pub struct App; + + delegate_components! { + App { + GreeterComponent: GreetHello, + LoudGreeterComponent: GreetLoudly, + } + } + + check_components! { + App { + GreeterComponent, + LoudGreeterComponent, + } + } + + #[test] + fn test_use_context_default_inner() { + let app = App; + assert_eq!(app.greet_loudly(), "HELLO!"); + } +} diff --git a/example-code/src/reference/providers/use_default.rs b/example-code/src/reference/providers/use_default.rs new file mode 100644 index 00000000..41f4771a --- /dev/null +++ b/example-code/src/reference/providers/use_default.rs @@ -0,0 +1,56 @@ +//! Code from `docs/reference/providers/use_default.md` — *`UseDefault`*. +//! +//! Pins that empty-body `#[cgp_impl(UseDefault)]` blocks make the trait's default method bodies the +//! implementation, and that both components can be delegated to `UseDefault` in one array entry. + +/// ## Examples +pub mod examples { + use cgp::core::component::UseDefault; + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str { + "John" + } + } + + #[cgp_component(Greeter)] + pub trait CanGreet: HasName { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } + } + + #[cgp_impl(UseDefault)] + impl NameGetter {} + + #[cgp_impl(UseDefault)] + #[uses(HasName)] + impl Greeter {} + + pub struct App; + + delegate_components! { + App { + [ + NameGetterComponent, + GreeterComponent, + ]: + UseDefault, + } + } + + check_components! { + App { + NameGetterComponent, + GreeterComponent, + } + } + + #[test] + fn test_use_default() { + let app = App; + assert_eq!(app.greet(), "Hello, John!"); + } +} diff --git a/example-code/src/reference/providers/use_delegate.rs b/example-code/src/reference/providers/use_delegate.rs new file mode 100644 index 00000000..a54f86cf --- /dev/null +++ b/example-code/src/reference/providers/use_delegate.rs @@ -0,0 +1,87 @@ +//! Code from `docs/reference/providers/use_delegate.md` — *`UseDelegate`*. +//! +//! Pins the legacy nested-table dispatch and its `open` equivalent, both routing a `Shape` parameter +//! to a per-shape provider. The two forms are wired on separate contexts, since each is a full +//! wiring of the same component. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + #[derive_delegate(UseDelegate)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + pub struct Circle { + pub radius: f64, + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height + } + } + + #[cgp_impl(new CircleArea)] + impl AreaCalculator { + fn area(&self, shape: &Circle) -> f64 { + core::f64::consts::PI * shape.radius * shape.radius + } + } + + // Legacy nested-table form. + pub struct MyApp; + + delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } + } + + // The `open` equivalent, on a separate context. + pub struct MyApp2; + + delegate_components! { + MyApp2 { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } + } + + check_components! { + MyApp2 { + AreaCalculatorComponent: [Rectangle, Circle], + } + } + + #[test] + fn test_use_delegate_dispatch() { + let app = MyApp; + assert_eq!( + app.area(&Rectangle { + width: 2.0, + height: 3.0 + }), + 6.0 + ); + } +} diff --git a/example-code/src/reference/providers/use_delegated_type.rs b/example-code/src/reference/providers/use_delegated_type.rs new file mode 100644 index 00000000..4a505024 --- /dev/null +++ b/example-code/src/reference/providers/use_delegated_type.rs @@ -0,0 +1,46 @@ +//! Code from `docs/reference/providers/use_delegated_type.md` — *`UseDelegatedType`*. +//! +//! Pins that one `UseDelegatedType` entry answers two abstract-type components, each +//! resolving to the concrete type held in the `AppTypes` table. + +/// ## Examples +pub mod examples { + use cgp::core::types::WithDelegatedType; + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar; + } + + #[cgp_type] + pub trait HasIndexType { + type Index; + } + + pub struct App; + pub struct AppTypes; + + delegate_components! { + AppTypes { + ScalarTypeProviderComponent: f64, + IndexTypeProviderComponent: usize, + } + } + + delegate_components! { + App { + [ + ScalarTypeProviderComponent, + IndexTypeProviderComponent, + ]: WithDelegatedType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + IndexTypeProviderComponent, + } + } +} diff --git a/example-code/src/reference/providers/use_field.rs b/example-code/src/reference/providers/use_field.rs new file mode 100644 index 00000000..b6dcd230 --- /dev/null +++ b/example-code/src/reference/providers/use_field.rs @@ -0,0 +1,65 @@ +//! Code from `docs/reference/providers/use_field.md` — *`UseField`*. +//! +//! Pins the decoupling the page is about: a getter method `name` reads a `first_name` field, once +//! through `UseField` and once through the `WithField` alias. The alias is wired on a second context, +//! since two entries for one component on one context would conflict. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::WithField; + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub first_name: String, + } + + delegate_components! { + Person { + NameGetterComponent: UseField, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + + // The page's `greet` fn. + fn greet(person: &Person) { + println!("Hello, {}!", person.name()); // reads the first_name field + } + + #[test] + fn test_use_field_reads_first_name() { + let person = Person { + first_name: "Alice".to_owned(), + }; + assert_eq!(person.name(), "Alice"); + greet(&person); + } + + // The `WithField` alias, on a separate context to avoid a duplicate wiring for one component. + #[derive(HasField)] + pub struct PersonWith { + pub first_name: String, + } + + delegate_components! { + PersonWith { + NameGetterComponent: WithField, + } + } + + check_components! { + PersonWith { + NameGetterComponent, + } + } +} diff --git a/example-code/src/reference/providers/use_field_ref.rs b/example-code/src/reference/providers/use_field_ref.rs new file mode 100644 index 00000000..324ace37 --- /dev/null +++ b/example-code/src/reference/providers/use_field_ref.rs @@ -0,0 +1,55 @@ +//! Code from `docs/reference/providers/use_field_ref.md` — *`UseFieldRef`*. +//! +//! `UseFieldRef` is a foundational `FieldGetter`, so it is wired to a getter component through the +//! `WithFieldRef` alias (`WithProvider>`). This pins that a `-> &Config` getter reads +//! a stored `AsRef` field. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::WithFieldRef; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq)] + pub struct Config { + pub port: u16, + } + + // A stored wrapper that borrows as `Config`. + pub struct StoredConfig(pub Config); + + impl AsRef for StoredConfig { + fn as_ref(&self) -> &Config { + &self.0 + } + } + + #[cgp_getter] + pub trait HasConfig { + fn config(&self) -> &Config; + } + + #[derive(HasField)] + pub struct App { + pub config: StoredConfig, + } + + delegate_components! { + App { + ConfigGetterComponent: WithFieldRef, + } + } + + check_components! { + App { + ConfigGetterComponent, + } + } + + #[test] + fn test_use_field_ref_borrows_through_as_ref() { + let app = App { + config: StoredConfig(Config { port: 8080 }), + }; + assert_eq!(app.config(), &Config { port: 8080 }); + } +} diff --git a/example-code/src/reference/providers/use_fields.rs b/example-code/src/reference/providers/use_fields.rs new file mode 100644 index 00000000..24206164 --- /dev/null +++ b/example-code/src/reference/providers/use_fields.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/providers/use_fields.md` — *`UseFields`*. +//! +//! Pins the method-name-equals-field-name convention: wiring a getter to `UseFields` reads the +//! same-named context field. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasFoo { + fn foo(&self) -> &str; + } + + #[derive(HasField)] + pub struct App { + pub foo: String, + } + + delegate_components! { + App { + FooGetterComponent: UseFields, + } + } + + check_components! { + App { + FooGetterComponent, + } + } + + fn describe(app: &App) -> &str { + app.foo() // reads the `foo` field + } + + #[test] + fn test_use_fields_reads_same_named_field() { + let app = App { + foo: "hi".to_owned(), + }; + assert_eq!(describe(&app), "hi"); + } +} diff --git a/example-code/src/reference/providers/use_type.rs b/example-code/src/reference/providers/use_type.rs new file mode 100644 index 00000000..6141ce75 --- /dev/null +++ b/example-code/src/reference/providers/use_type.rs @@ -0,0 +1,53 @@ +//! Code from `docs/reference/providers/use_type.md` — *`UseType` (provider)*. +//! +//! Pins that wiring an abstract-type component to `UseType` (or the `WithType` alias) sets the +//! context's abstract type to `f64` and enforces the `Copy` bound at the wiring site. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Copy; + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + } + } +} + +/// ## Examples — the `WithType` alias +pub mod examples_with_type { + use cgp::core::types::WithType; + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Copy; + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: WithType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + } + } +} diff --git a/example-code/src/reference/providers/with_provider.rs b/example-code/src/reference/providers/with_provider.rs new file mode 100644 index 00000000..73d68739 --- /dev/null +++ b/example-code/src/reference/providers/with_provider.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/providers/with_provider.md` — *`WithProvider`*. +//! +//! Pins that the `WithField` alias — `WithProvider>` — wires a getter to a named field +//! by adapting the foundational field getter. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::WithField; + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub first_name: String, + } + + delegate_components! { + Person { + NameGetterComponent: WithField, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + + #[test] + fn test_with_field_adapts_use_field() { + let person = Person { + first_name: "Ada".to_owned(), + }; + assert_eq!(person.name(), "Ada"); + } +} From d6f1b47768506481b0bb47433814bc79c215b64a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 13:16:13 +0200 Subject: [PATCH 044/516] Add providers overview page and order the sidebar by relevance Add a hand-written docs/reference/providers/index.md overview that groups the providers by job, and point the category link at it instead of a generated index, matching the macros, attributes, and derives groups. Give every provider page a sidebar_position so the sidebar leads with the most-used providers (UseContext, UseType, the field getters, UseDefault, WithProvider) before dispatch and namespaces, the specialized getters, and the computation-family catalogues. Co-Authored-By: Claude Opus 4.8 --- docs/reference/providers/_category_.json | 4 +- docs/reference/providers/chain_getters.md | 1 + .../providers/dispatch_combinators.md | 1 + docs/reference/providers/error_providers.md | 1 + .../providers/handler_combinators.md | 1 + docs/reference/providers/index.md | 57 +++++++++++++++++++ docs/reference/providers/monad_providers.md | 1 + docs/reference/providers/redirect_lookup.md | 1 + docs/reference/providers/use_context.md | 1 + docs/reference/providers/use_default.md | 1 + docs/reference/providers/use_delegate.md | 1 + .../reference/providers/use_delegated_type.md | 1 + docs/reference/providers/use_field.md | 1 + docs/reference/providers/use_field_ref.md | 1 + docs/reference/providers/use_fields.md | 1 + docs/reference/providers/use_type.md | 1 + docs/reference/providers/with_provider.md | 1 + 17 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 docs/reference/providers/index.md diff --git a/docs/reference/providers/_category_.json b/docs/reference/providers/_category_.json index 881aec3b..66c02186 100644 --- a/docs/reference/providers/_category_.json +++ b/docs/reference/providers/_category_.json @@ -2,7 +2,7 @@ "label": "Providers", "position": 5, "link": { - "type": "generated-index", - "description": "The zero-sized provider types that appear in wiring tables. They carry no runtime value and exist only at the type level." + "type": "doc", + "id": "reference/providers/index" } } diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 1520ea63..50299b36 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -1,5 +1,6 @@ --- sidebar_label: 'ChainGetters' +sidebar_position: 10 --- # `ChainGetters` diff --git a/docs/reference/providers/dispatch_combinators.md b/docs/reference/providers/dispatch_combinators.md index efd1e902..9a0bb50c 100644 --- a/docs/reference/providers/dispatch_combinators.md +++ b/docs/reference/providers/dispatch_combinators.md @@ -1,5 +1,6 @@ --- sidebar_label: 'Dispatch combinators' +sidebar_position: 14 --- # Dispatch combinators diff --git a/docs/reference/providers/error_providers.md b/docs/reference/providers/error_providers.md index 9fff4727..3429e0b1 100644 --- a/docs/reference/providers/error_providers.md +++ b/docs/reference/providers/error_providers.md @@ -1,5 +1,6 @@ --- sidebar_label: 'Error providers' +sidebar_position: 12 --- # Error providers diff --git a/docs/reference/providers/handler_combinators.md b/docs/reference/providers/handler_combinators.md index 61000dec..189e6f20 100644 --- a/docs/reference/providers/handler_combinators.md +++ b/docs/reference/providers/handler_combinators.md @@ -1,5 +1,6 @@ --- sidebar_label: 'Handler combinators' +sidebar_position: 13 --- # Handler combinators diff --git a/docs/reference/providers/index.md b/docs/reference/providers/index.md new file mode 100644 index 00000000..4877c0ba --- /dev/null +++ b/docs/reference/providers/index.md @@ -0,0 +1,57 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Providers + +A provider is a zero-sized type wired to a component to say how that component is implemented for a +context. Providers carry no runtime value; they are type-level markers named in a +[`delegate_components!`](../macros/delegate_components.md) table and resolved at compile time. This page +groups the providers CGP ships by the job they do, in roughly the order most CGP code reaches for them. + +If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here; this page +is the fuller map for once the essentials are familiar. + +## Wiring an everyday component + +[`UseContext`](./use_context.md) implements a provider trait by routing back through the context's own +consumer-trait implementation, which is what a higher-order provider falls back to and the default +per-variant provider a dispatch combinator routes each matched case through. +[`UseType`](./use_type.md) supplies a concrete type for an abstract-type component, so a context binds +its error type or runtime with one wiring line. +[`UseField`](./use_field.md) implements a getter by reading a context field named by a tag, and +[`UseFields`](./use_fields.md) does the same when every getter method reads a same-named field. +[`UseDefault`](./use_default.md) selects a component's own default method bodies when there is no +behaviour left for a provider to supply. + +[`WithProvider`](./with_provider.md) is the adapter behind the `With…` aliases: it turns a foundational +provider such as a field getter or a type provider into a provider for a named component, and the +aliases `WithField`, `WithType`, and `WithContext` are how it usually appears in wiring. + +## Dispatching per type, and organizing wiring + +[`UseDelegate`](./use_delegate.md) chooses a provider by the type of a generic parameter through a +lookup table, the legacy form of the per-type dispatch the `open` statement now expresses. +[`RedirectLookup`](./redirect_lookup.md) routes a component's lookup along a type-level path in a +separate table, the mechanism every namespace and `open` statement rides. Both are read in wiring far +more often than written. + +## The specialized getters and type providers + +[`UseFieldRef`](./use_field_ref.md) is the foundational getter that borrows a field through `AsRef`, for +a getter that returns a view of a field the context stores as a different type. +[`ChainGetters`](./chain_getters.md) composes a list of getters to reach a field several hops inside a +nested context. +[`UseDelegatedType`](./use_delegated_type.md) resolves an abstract type through a table rather than +fixing it to one concrete type. Each is reached through [`WithProvider`](./with_provider.md) when wired +to a component. + +## The computation-family combinators + +The handler family has its own providers, which build, route, and lift computations rather than wire a +single capability. The [error providers](./error_providers.md) raise and wrap a context's abstract +error, the [handler combinators](./handler_combinators.md) compose and promote handlers across the +family's synchronous, async, and fallible shapes, the [dispatch combinators](./dispatch_combinators.md) +route an extensible-data value to per-field or per-variant handlers, and the +[monad providers](./monad_providers.md) chain handlers that short-circuit through a monad. diff --git a/docs/reference/providers/monad_providers.md b/docs/reference/providers/monad_providers.md index ac118a16..846f8873 100644 --- a/docs/reference/providers/monad_providers.md +++ b/docs/reference/providers/monad_providers.md @@ -1,5 +1,6 @@ --- sidebar_label: 'Monad providers' +sidebar_position: 15 --- # Monad providers diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 89bee1b5..0075819f 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -1,5 +1,6 @@ --- sidebar_label: 'RedirectLookup' +sidebar_position: 8 --- # `RedirectLookup` diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index cc9e600f..21ba5336 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UseContext' +sidebar_position: 1 --- # `UseContext` diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index 9dbda233..321d064a 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UseDefault' +sidebar_position: 5 --- # `UseDefault` diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 96176fb3..17d8c83a 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UseDelegate' +sidebar_position: 7 --- # `UseDelegate` diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index 01286c7e..19fa024a 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UseDelegatedType' +sidebar_position: 11 --- # `UseDelegatedType` diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index ab7d81d3..90a63a90 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UseField' +sidebar_position: 3 --- # `UseField` diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index aa0cb49c..92d014c3 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UseFieldRef' +sidebar_position: 9 --- # `UseFieldRef` diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 9d8d4f0a..e44a82e8 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UseFields' +sidebar_position: 4 --- # `UseFields` diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index bf4e1d86..db9611d0 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UseType (provider)' +sidebar_position: 2 --- # `UseType` (provider) diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index e5889203..4f9e58ab 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -1,5 +1,6 @@ --- sidebar_label: 'WithProvider' +sidebar_position: 6 --- # `WithProvider` From 08577b6be1f39a3aa8cd7305602337c223884f23 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 19:16:24 +0200 Subject: [PATCH 045/516] Write provider reference pages and their example-code mirrors Replace the four provider catalogue stubs under docs/reference/providers/ with nested error/, handler/, dispatch/, and monad/ subdirectories: one page per provider construct plus an overview each, ported from the internal reference and verified against the cgp source. Repoint every inbound cross-link and update the reference and providers indexes. Add compiled, tested example-code mirrors for the new pages (error, handler, monad, and the dispatch matcher side). Writing the mirrors caught and fixed real page bugs: the PromoteComputer/PromoteProducer/PromoteAsyncComputer base wiring, PromoteRef's over-reference inner, and two error pages whose 'ParseError: RaiseFrom' required a From impl the scenario lacked. Co-Authored-By: Claude Opus 4.8 --- docs/concepts/dispatching.md | 2 +- docs/concepts/handlers.md | 4 +- docs/concepts/modular-error-handling.md | 2 +- docs/concepts/monadic-handlers.md | 2 +- docs/reference/derives/derive_build_field.md | 2 +- docs/reference/derives/derive_cgp_variant.md | 2 +- .../reference/derives/derive_extract_field.md | 6 +- docs/reference/index.md | 24 ++- docs/reference/macros/async_trait.md | 4 +- docs/reference/macros/cgp_auto_dispatch.md | 10 +- docs/reference/macros/cgp_computer.md | 8 +- docs/reference/macros/cgp_producer.md | 6 +- docs/reference/macros/product.md | 2 +- .../providers/dispatch/_category_.json | 8 + .../providers/dispatch/build_and_merge.md | 83 ++++++++++ .../dispatch/build_and_merge_outputs.md | 76 +++++++++ .../providers/dispatch/build_and_set_field.md | 81 ++++++++++ .../providers/dispatch/build_with_handlers.md | 96 +++++++++++ .../providers/dispatch/downcast_and_handle.md | 75 +++++++++ .../dispatch/extract_field_and_handle.md | 92 +++++++++++ .../providers/dispatch/handle_field_value.md | 80 ++++++++++ docs/reference/providers/dispatch/index.md | 91 +++++++++++ .../dispatch/match_first_with_handlers.md | 109 +++++++++++++ .../dispatch/match_with_field_handlers.md | 108 +++++++++++++ .../providers/dispatch/match_with_handlers.md | 149 ++++++++++++++++++ .../dispatch/match_with_value_handlers.md | 103 ++++++++++++ .../providers/dispatch_combinators.md | 18 --- .../reference/providers/error/_category_.json | 8 + docs/reference/providers/error/debug_error.md | 111 +++++++++++++ .../providers/error/discard_detail.md | 85 ++++++++++ .../providers/error/display_error.md | 104 ++++++++++++ docs/reference/providers/error/index.md | 92 +++++++++++ .../providers/error/panic_on_error.md | 85 ++++++++++ docs/reference/providers/error/raise_from.md | 114 ++++++++++++++ .../providers/error/raise_infallible.md | 89 +++++++++++ .../reference/providers/error/return_error.md | 103 ++++++++++++ docs/reference/providers/error_providers.md | 18 --- .../providers/handler/_category_.json | 8 + .../providers/handler/compose_handlers.md | 115 ++++++++++++++ docs/reference/providers/handler/index.md | 95 +++++++++++ .../providers/handler/pipe_handlers.md | 129 +++++++++++++++ docs/reference/providers/handler/promote.md | 94 +++++++++++ .../providers/handler/promote_async.md | 83 ++++++++++ .../handler/promote_async_computer.md | 74 +++++++++ .../providers/handler/promote_computer.md | 105 ++++++++++++ .../providers/handler/promote_handler.md | 72 +++++++++ .../providers/handler/promote_producer.md | 78 +++++++++ .../providers/handler/promote_ref.md | 88 +++++++++++ .../providers/handler/promote_try_computer.md | 75 +++++++++ .../providers/handler/return_input.md | 92 +++++++++++ .../providers/handler/try_promote.md | 88 +++++++++++ .../providers/handler/use_input_delegate.md | 124 +++++++++++++++ .../providers/handler_combinators.md | 18 --- docs/reference/providers/index.md | 9 +- .../reference/providers/monad/_category_.json | 8 + docs/reference/providers/monad/bind_err.md | 78 +++++++++ docs/reference/providers/monad/bind_ok.md | 78 +++++++++ docs/reference/providers/monad/index.md | 80 ++++++++++ .../reference/providers/monad/pipe_monadic.md | 116 ++++++++++++++ docs/reference/providers/monad_providers.md | 18 --- docs/reference/providers/use_context.md | 4 +- docs/reference/providers/use_delegate.md | 4 +- docs/reference/traits/can_upcast.md | 2 +- docs/reference/traits/contains_value.md | 12 +- docs/reference/traits/extract_field.md | 8 +- docs/reference/traits/finalize_extract.md | 6 +- .../traits/finalize_extract_result.md | 4 +- docs/reference/traits/from_variant.md | 2 +- docs/reference/traits/has_extractor.md | 2 +- docs/reference/traits/lift_value.md | 14 +- docs/reference/traits/monadic_bind.md | 20 +-- docs/reference/traits/monadic_trans.md | 10 +- example-code/README.md | 2 +- .../dispatch/extract_field_and_handle.rs | 83 ++++++++++ .../providers/dispatch/handle_field_value.rs | 82 ++++++++++ .../dispatch/match_with_field_handlers.rs | 69 ++++++++ .../providers/dispatch/match_with_handlers.rs | 86 ++++++++++ .../dispatch/match_with_value_handlers.rs | 88 +++++++++++ .../src/reference/providers/dispatch/mod.rs | 7 + .../reference/providers/error/debug_error.rs | 55 +++++++ .../providers/error/discard_detail.rs | 53 +++++++ .../providers/error/display_error.rs | 55 +++++++ .../src/reference/providers/error/mod.rs | 9 ++ .../providers/error/panic_on_error.rs | 48 ++++++ .../reference/providers/error/raise_from.rs | 65 ++++++++ .../providers/error/raise_infallible.rs | 58 +++++++ .../reference/providers/error/return_error.rs | 79 ++++++++++ .../providers/handler/compose_handlers.rs | 44 ++++++ .../src/reference/providers/handler/mod.rs | 15 ++ .../providers/handler/pipe_handlers.rs | 74 +++++++++ .../reference/providers/handler/promote.rs | 43 +++++ .../providers/handler/promote_async.rs | 40 +++++ .../handler/promote_async_computer.rs | 52 ++++++ .../providers/handler/promote_computer.rs | 64 ++++++++ .../providers/handler/promote_handler.rs | 50 ++++++ .../providers/handler/promote_producer.rs | 49 ++++++ .../providers/handler/promote_ref.rs | 48 ++++++ .../providers/handler/promote_try_computer.rs | 52 ++++++ .../providers/handler/return_input.rs | 40 +++++ .../providers/handler/try_promote.rs | 49 ++++++ .../providers/handler/use_input_delegate.rs | 66 ++++++++ example-code/src/reference/providers/mod.rs | 4 + .../src/reference/providers/monad/bind_err.rs | 43 +++++ .../src/reference/providers/monad/bind_ok.rs | 53 +++++++ .../src/reference/providers/monad/mod.rs | 5 + .../reference/providers/monad/pipe_monadic.rs | 59 +++++++ 106 files changed, 5395 insertions(+), 159 deletions(-) create mode 100644 docs/reference/providers/dispatch/_category_.json create mode 100644 docs/reference/providers/dispatch/build_and_merge.md create mode 100644 docs/reference/providers/dispatch/build_and_merge_outputs.md create mode 100644 docs/reference/providers/dispatch/build_and_set_field.md create mode 100644 docs/reference/providers/dispatch/build_with_handlers.md create mode 100644 docs/reference/providers/dispatch/downcast_and_handle.md create mode 100644 docs/reference/providers/dispatch/extract_field_and_handle.md create mode 100644 docs/reference/providers/dispatch/handle_field_value.md create mode 100644 docs/reference/providers/dispatch/index.md create mode 100644 docs/reference/providers/dispatch/match_first_with_handlers.md create mode 100644 docs/reference/providers/dispatch/match_with_field_handlers.md create mode 100644 docs/reference/providers/dispatch/match_with_handlers.md create mode 100644 docs/reference/providers/dispatch/match_with_value_handlers.md delete mode 100644 docs/reference/providers/dispatch_combinators.md create mode 100644 docs/reference/providers/error/_category_.json create mode 100644 docs/reference/providers/error/debug_error.md create mode 100644 docs/reference/providers/error/discard_detail.md create mode 100644 docs/reference/providers/error/display_error.md create mode 100644 docs/reference/providers/error/index.md create mode 100644 docs/reference/providers/error/panic_on_error.md create mode 100644 docs/reference/providers/error/raise_from.md create mode 100644 docs/reference/providers/error/raise_infallible.md create mode 100644 docs/reference/providers/error/return_error.md delete mode 100644 docs/reference/providers/error_providers.md create mode 100644 docs/reference/providers/handler/_category_.json create mode 100644 docs/reference/providers/handler/compose_handlers.md create mode 100644 docs/reference/providers/handler/index.md create mode 100644 docs/reference/providers/handler/pipe_handlers.md create mode 100644 docs/reference/providers/handler/promote.md create mode 100644 docs/reference/providers/handler/promote_async.md create mode 100644 docs/reference/providers/handler/promote_async_computer.md create mode 100644 docs/reference/providers/handler/promote_computer.md create mode 100644 docs/reference/providers/handler/promote_handler.md create mode 100644 docs/reference/providers/handler/promote_producer.md create mode 100644 docs/reference/providers/handler/promote_ref.md create mode 100644 docs/reference/providers/handler/promote_try_computer.md create mode 100644 docs/reference/providers/handler/return_input.md create mode 100644 docs/reference/providers/handler/try_promote.md create mode 100644 docs/reference/providers/handler/use_input_delegate.md delete mode 100644 docs/reference/providers/handler_combinators.md create mode 100644 docs/reference/providers/monad/_category_.json create mode 100644 docs/reference/providers/monad/bind_err.md create mode 100644 docs/reference/providers/monad/bind_ok.md create mode 100644 docs/reference/providers/monad/index.md create mode 100644 docs/reference/providers/monad/pipe_monadic.md delete mode 100644 docs/reference/providers/monad_providers.md create mode 100644 example-code/src/reference/providers/dispatch/extract_field_and_handle.rs create mode 100644 example-code/src/reference/providers/dispatch/handle_field_value.rs create mode 100644 example-code/src/reference/providers/dispatch/match_with_field_handlers.rs create mode 100644 example-code/src/reference/providers/dispatch/match_with_handlers.rs create mode 100644 example-code/src/reference/providers/dispatch/match_with_value_handlers.rs create mode 100644 example-code/src/reference/providers/dispatch/mod.rs create mode 100644 example-code/src/reference/providers/error/debug_error.rs create mode 100644 example-code/src/reference/providers/error/discard_detail.rs create mode 100644 example-code/src/reference/providers/error/display_error.rs create mode 100644 example-code/src/reference/providers/error/mod.rs create mode 100644 example-code/src/reference/providers/error/panic_on_error.rs create mode 100644 example-code/src/reference/providers/error/raise_from.rs create mode 100644 example-code/src/reference/providers/error/raise_infallible.rs create mode 100644 example-code/src/reference/providers/error/return_error.rs create mode 100644 example-code/src/reference/providers/handler/compose_handlers.rs create mode 100644 example-code/src/reference/providers/handler/mod.rs create mode 100644 example-code/src/reference/providers/handler/pipe_handlers.rs create mode 100644 example-code/src/reference/providers/handler/promote.rs create mode 100644 example-code/src/reference/providers/handler/promote_async.rs create mode 100644 example-code/src/reference/providers/handler/promote_async_computer.rs create mode 100644 example-code/src/reference/providers/handler/promote_computer.rs create mode 100644 example-code/src/reference/providers/handler/promote_handler.rs create mode 100644 example-code/src/reference/providers/handler/promote_producer.rs create mode 100644 example-code/src/reference/providers/handler/promote_ref.rs create mode 100644 example-code/src/reference/providers/handler/promote_try_computer.rs create mode 100644 example-code/src/reference/providers/handler/return_input.rs create mode 100644 example-code/src/reference/providers/handler/try_promote.rs create mode 100644 example-code/src/reference/providers/handler/use_input_delegate.rs create mode 100644 example-code/src/reference/providers/monad/bind_err.rs create mode 100644 example-code/src/reference/providers/monad/bind_ok.rs create mode 100644 example-code/src/reference/providers/monad/mod.rs create mode 100644 example-code/src/reference/providers/monad/pipe_monadic.rs diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index db59eb37..d41cfea0 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -120,7 +120,7 @@ the two halves this operates on, and both are worth reading first. [Handlers](./handlers.md) is the interface every dispatcher and every per-element handler speaks, and [monadic handlers](./monadic-handlers.md) is the chaining the matcher is built from. -For the constructs, [the dispatch combinators](/docs/reference/providers/dispatch_combinators) is the +For the constructs, [the dispatch combinators](/docs/reference/providers/dispatch) is the catalogue of matchers, builders, and per-element adapters, and [`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch) is the shortcut above. diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index d3f82594..2f802a68 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -110,7 +110,7 @@ body. Changing the order, dropping a stage, or swapping one for another is an ed `ComposeHandlers` nests rather than chains, `ReturnInput` passes a value through, and the `Promote*` adapters are the lifts from the previous section made explicit. They are catalogued together in -[handler combinators](/docs/reference/providers/handler_combinators). +[handler combinators](/docs/reference/providers/handler). ## Many computations on one context @@ -170,7 +170,7 @@ For the constructs, [`Computer`](/docs/reference/components/computer), [`Producer`](/docs/reference/components/producer) are the corners; [`#[cgp_computer]`](/docs/reference/macros/cgp_computer) and [`#[cgp_producer]`](/docs/reference/macros/cgp_producer) build a provider from a function; and -[handler combinators](/docs/reference/providers/handler_combinators) is the full catalogue. +[handler combinators](/docs/reference/providers/handler) is the full catalogue. --- diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index 7608297b..6b850320 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -179,7 +179,7 @@ if `#[use_type]` above was unfamiliar. [Impl-side dependencies](./impl-side-depe For the constructs, [`HasErrorType`](/docs/reference/components/has_error_type) is the abstract error type, [`CanRaiseError`](/docs/reference/components/can_raise_error) covers raising and wrapping, and -[the error providers](/docs/reference/providers/error_providers) is the catalogue of strategies with the +[the error providers](/docs/reference/providers/error) is the catalogue of strategies with the bound each one places on the context. --- diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index ac651a74..92acf3c4 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -109,7 +109,7 @@ pipeline does. looked like it came from nowhere. [Dispatching](./dispatching.md) is the other big user of the ok monad: matching an enum variant is a chain of attempts where the first success ends it. -For the constructs, [monad providers](/docs/reference/providers/monad_providers) carries `PipeMonadic`, +For the constructs, [monad providers](/docs/reference/providers/monad) carries `PipeMonadic`, the three markers, and the per-step `BindOk` / `BindErr` forms. The four monad traits are the layer defining what a monad is here: [`MonadicBind`](/docs/reference/traits/monadic_bind), [`ContainsValue`](/docs/reference/traits/contains_value), diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 118bb172..edcc3a88 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -340,7 +340,7 @@ renaming a field in one struct silently stops it being copied from the other. Th - [`HasOptionalBuilder`](../traits/has_optional_builder.md) and [`CanFinalizeWithDefault`](../traits/can_finalize_with_default.md) — optional and defaulted fields, which the plain builder does not model. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that run several builder +- [Dispatch combinators](../providers/dispatch/index.md) — the providers that run several builder implementations and merge their outputs. The ideas behind it: diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 1c44cc51..ddb5368c 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -244,7 +244,7 @@ record and variant machinery have been crossed. by. - [`CanUpcast`](../traits/can_upcast.md) and [`CanDowncast`](../traits/can_downcast.md) — converting between two enums whose variants overlap, built on this machinery. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that route a variant to +- [Dispatch combinators](../providers/dispatch/index.md) — the providers that route a variant to the implementation handling it. The ideas behind it: diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 81271d7e..c5dea150 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -171,7 +171,7 @@ if let Ok(circle) = shape ``` In practice you rarely write these chains by hand. The -[dispatch combinators](../providers/dispatch_combinators.md) build them for you from a set of per-variant +[dispatch combinators](../providers/dispatch/index.md) build them for you from a set of per-variant implementations, which is the extensible visitor pattern: a chain like the one above, generated, with one implementation per variant chosen by wiring. @@ -335,7 +335,7 @@ the message to see which variants are still possible. you may extract in any order. But you must extract *every* variant before the remainder can be finalized. **Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the reason -to prefer the [dispatch combinators](../providers/dispatch_combinators.md), which derive the chain from the +to prefer the [dispatch combinators](../providers/dispatch/index.md), which derive the chain from the enum's own variant list rather than repeating it at each site. **It does not accept a struct.** The struct analogue is @@ -357,7 +357,7 @@ enum's own variant list rather than repeating it at each site. - [`CanUpcast`](../traits/can_upcast.md) — upcasting and downcasting between enums, which reuse this recursion. - [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain an enum's shape is built from. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build an extraction chain +- [Dispatch combinators](../providers/dispatch/index.md) — the providers that build an extraction chain for you, one implementation per variant. The ideas behind it: diff --git a/docs/reference/index.md b/docs/reference/index.md index d893d5a8..da4b18c4 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -20,9 +20,9 @@ its own. ### Still being written The construct list below is complete — every construct the `cgp` crate exports has a page, or a named -place on a page it shares — so nothing is missing from this index. The macros, attributes, derives, and -traits are written; the components, providers, and type-level pages are still placeholders, and each one -says so when you open it. +place on a page it shares — so nothing is missing from this index. The macros, attributes, derives, +traits, and providers are written; the components and type-level pages are still placeholders, and each +one says so when you open it. ::: @@ -120,7 +120,7 @@ in as a named component's. [`HasErrorType`](./components/has_error_type.md) gives a context one shared error type, and [`CanRaiseError` and `CanWrapError`](./components/can_raise_error.md) construct it from a source error and attach detail. The interchangeable strategies that satisfy them — `RaiseFrom`, `ReturnError`, -`DebugError`, and the rest — are the [error providers](./providers/error_providers.md). +`DebugError`, and the rest — are the [error providers](./providers/error/index.md). ### Compute things @@ -136,9 +136,9 @@ they vary. Providers in this family are written from plain functions with [`#[cgp_computer]`](./macros/cgp_computer.md) and [`#[cgp_producer]`](./macros/cgp_producer.md), and -composed with the [handler combinators](./providers/handler_combinators.md), the -[dispatch combinators](./providers/dispatch_combinators.md), and the -[monad providers](./providers/monad_providers.md) built on the monad traits — +composed with the [handler combinators](./providers/handler/index.md), the +[dispatch combinators](./providers/dispatch/index.md), and the +[monad providers](./providers/monad/index.md) built on the monad traits — [`MonadicBind`](./traits/monadic_bind.md), [`ContainsValue`](./traits/contains_value.md), [`LiftValue`](./traits/lift_value.md), and [`MonadicTrans`](./traits/monadic_trans.md). [`#[cgp_auto_dispatch]`](./macros/cgp_auto_dispatch.md) generates a dispatching handler from a per-type @@ -232,13 +232,11 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w | `HasRuntimeType` | [`HasRuntime`](./components/has_runtime.md) | | `WithType`, `WithField`, `WithContext` | [`WithProvider`](./providers/with_provider.md) | | `Cons`, `Nil`, `Either`, `Void`, `Chars`, `PathCons` | [Type-level spines](./types/type_level_spines.md) | -| `ComposeHandlers`, `PipeHandlers`, `ReturnInput`, `Promote*` | [Handler combinators](./providers/handler_combinators.md) | -| `MatchWithHandlers`, `ExtractFieldAndHandle` | [Dispatch combinators](./providers/dispatch_combinators.md) | -| `PipeMonadic`, `BindOk`, `BindErr` | [Monad providers](./providers/monad_providers.md) | -| `RaiseFrom`, `ReturnError`, `DebugError`, `DisplayError` | [Error providers](./providers/error_providers.md) | +| `IdentMonadic`, `OkMonadic`, `ErrMonadic`, `OkMonadicTrans`, `ErrMonadicTrans` | [Monad providers](./providers/monad/index.md) | | `UseDelegatedType`, `WithDelegatedType` | [`UseDelegatedType`](./providers/use_delegated_type.md) and [`WithProvider`](./providers/with_provider.md) | -| `UseInputDelegate` | [Handler combinators](./providers/handler_combinators.md) | -| `RaiseInfallible`, `DiscardDetail`, `PanicOnError` | [Error providers](./providers/error_providers.md) | +| `MatchWithHandlersRef`, `MatchFirstWithHandlers`, and the other borrowed and first-argument matcher forms | the matcher page they vary, under [Dispatch combinators](./providers/dispatch/index.md) | +| `ExtractFirstFieldAndHandle`, `HandleFirstFieldValue` | [`ExtractFieldAndHandle`](./providers/dispatch/extract_field_and_handle.md), [`HandleFieldValue`](./providers/dispatch/handle_field_value.md) | +| `DispatchMatchers`, `ToFieldHandlers`, `HasFieldHandlers`, `MapFieldHandler` | [Dispatch combinators](./providers/dispatch/index.md) | | `ComputerRef`, `AsyncComputer`, `TryComputerRef`, `HandlerRef` | the page for the component they vary — [`Computer`](./components/computer.md), [`TryComputer`](./components/try_computer.md), [`Handler`](./components/handler.md) | | `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` | [`MapType`](./traits/map_type.md) | | `IsRef`, `IsMut`, `IsOwned` | [`MapTypeRef`](./traits/map_type_ref.md) | diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 40343e2c..52e8423c 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -144,7 +144,7 @@ The decisions worth making are around it rather than about it. - **Reach for the `Send`-recovery pattern when a future is spawned**, not for a different macro. No attribute can add the bound, for the reason in the [Common Mistakes](#common-mistakes). - **Consider whether the capability needs to be async at all.** The [handler family](./cgp_computer.md) has - synchronous members, and the [promotion combinators](../providers/handler_combinators.md) lift a synchronous + synchronous members, and the [promotion combinators](../providers/handler/index.md) lift a synchronous provider into an async one where a caller needs it. So a computation that does no I/O is better declared synchronous and promoted than declared async out of habit. - **Reach for the `async-trait` crate instead only if you need `dyn` compatibility.** Boxing makes an @@ -252,7 +252,7 @@ provider needed it; it did not, and removing it changes nothing. - [`#[cgp_impl]`](./cgp_impl.md) — where a provider writes an ordinary `async fn` body and needs no attribute. - [`Handler`](../components/handler.md) — CGP's built-in async, fallible component, declared this way. - [`#[cgp_computer]`](./cgp_computer.md) — where an `async` function selects the async base trait. -- [Handler combinators](../providers/handler_combinators.md) — the promotions that lift a synchronous provider +- [Handler combinators](../providers/handler/index.md) — the promotions that lift a synchronous provider into an async one. The ideas behind it: diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 11a64292..c509323f 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -23,7 +23,7 @@ Implement `HasArea` for `Circle` and for `Rectangle`, and an `enum Shape` holdin as well, dispatching to whichever variant it currently holds. No `match` is written anywhere. Without the macro you would either hand-write that `match` per method, or wire up the -[dispatch combinators](../providers/dispatch_combinators.md) yourself: a matcher, a per-variant handler, and +[dispatch combinators](../providers/dispatch/index.md) yourself: a matcher, a per-variant handler, and the field-extraction machinery between them. The macro does exactly that wiring, so what you write is the trait, its per-type impls, and a derive on the enum. @@ -31,7 +31,7 @@ trait, its per-type impls, and a derive on the enum. is *exactly* "call the same trait method on the payload". The moment a variant needs different handling, or the dispatch should be chosen by a **context** (the type the capability runs against) rather than fixed on the enum, reach for the combinators directly. This is the convenient front end to -[dispatching](../providers/dispatch_combinators.md), not a replacement for it. +[dispatching](../providers/dispatch/index.md), not a replacement for it. ## Usage @@ -136,7 +136,7 @@ Reach for something else in four situations. - **The behaviour differs per variant.** The macro generates one handler that calls the same method on every payload. When a variant needs something else, use the - [dispatch combinators](../providers/dispatch_combinators.md) directly and name a handler per variant. + [dispatch combinators](../providers/dispatch/index.md) directly and name a handler per variant. - **The dispatch should be a wired component.** The generated impl is fixed on the enum, with a unit context and a unit code, so a context cannot override how one variant is handled. Wiring `MatchWithValueHandlers` into a context's own component gives that control. @@ -231,7 +231,7 @@ error: Dispatch trait methods cannot contain non-lifetime generic parameters due The blanket impl would need a quantified bound ("for every instantiation of the method's type parameter, every variant's payload satisfies it"), and Rust has no way to write that. A method that must be generic has -to be handled with the [dispatch combinators](../providers/dispatch_combinators.md) directly. Lifetime +to be handled with the [dispatch combinators](../providers/dispatch/index.md) directly. Lifetime parameters are fine. **Associated types and consts are rejected.** Every trait item must be a method: @@ -255,7 +255,7 @@ hand for some other type without colliding with it. ## Related constructs -- [Dispatch combinators](../providers/dispatch_combinators.md) — the matchers this wires, and what to use +- [Dispatch combinators](../providers/dispatch/index.md) — the matchers this wires, and what to use directly for anything it cannot express. - [`#[cgp_computer]`](./cgp_computer.md) — how each per-variant handler is emitted. - [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — what the enum needs to be dispatchable. diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index e02f7b43..299726b0 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -31,7 +31,7 @@ that makes the *same function* answer the whole family. That wiring is the part implementing any of them. That last property is the whole reason for the macro. The family exists so a provider can declare exactly -the capabilities it has, and the [promotion combinators](../providers/handler_combinators.md) exist so a +the capabilities it has, and the [promotion combinators](../providers/handler/index.md) exist so a simpler provider can stand in where a more capable one is expected: an infallible computation is a fallible one that never fails, a synchronous one is an async one that never awaits. `#[cgp_computer]` picks the narrowest @@ -153,7 +153,7 @@ exists for, and it is the shortest route into the handler family. The two look similar and differ in what they produce: `#[cgp_fn]` gives a trait a context implements, called as `self.thing()`; `#[cgp_computer]` gives a *provider* that gets wired into a handler component and composed with combinators. If you are not building a pipeline, reach for `#[cgp_fn]` instead. -- **Wire the [handler combinators](../providers/handler_combinators.md) directly for composition.** The macro +- **Wire the [handler combinators](../providers/handler/index.md) directly for composition.** The macro produces one step; `PipeHandlers` and friends chain them. One thing not to do is reach for the handler family because a capability happens to transform a value. The @@ -216,7 +216,7 @@ delegate_components! { Note the **`->` operator** rather than `:`. It delegates each key to *the value's own entry for that key* rather than to the value itself, so `Add` inherits whatever `PromoteComputer` resolves each component -to. [`PromoteComputer`](../providers/handler_combinators.md) is itself a table of single-step promoters. +to. [`PromoteComputer`](../providers/handler/promote_computer.md) is itself a table of single-step promoters. `ComputerComponent` is absent from the list because `Add` implements it directly. The other three combinations differ only in which base trait is implemented and which bundle is named. An @@ -275,7 +275,7 @@ short-circuits. - [`Computer`](../components/computer.md) — the base component, with its by-reference and async variants. - [`Handler`](../components/handler.md) and [`TryComputer`](../components/try_computer.md) — the more capable members the promotions reach. -- [Handler combinators](../providers/handler_combinators.md) — the `Promote*` bundles this wires, plus +- [Handler combinators](../providers/handler/index.md) — the `Promote*` bundles this wires, plus `PipeHandlers` and `ComposeHandlers` for composing steps. - [`#[cgp_impl]`](./cgp_impl.md) — for a handler provider that needs its context. - [`#[cgp_fn]`](./cgp_fn.md) — for a capability on the context rather than a pipeline step. diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index b0de9077..79760a86 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -124,7 +124,7 @@ within it there is nothing simpler. producer that draws on its context is an impl of `Producer` written with `#[cgp_impl]`, where `self` is the context and [`#[implicit]`](../attributes/implicit.md) works normally. **In practice that covers most producers**, which makes this macro narrower than it first looks: it is for constants and pure seeds. -- **Use [`ReturnInput`](../providers/handler_combinators.md) rather than a producer that ignores its input.** +- **Use [`ReturnInput`](../providers/handler/return_input.md) rather than a producer that ignores its input.** If the goal is to pass a value through a pipeline unchanged, that combinator says so directly. - **Do not reach for the handler family at all for a plain constant.** A `const` or a function is clearer unless the value is being composed into a pipeline or dispatched on a `Code` tag. @@ -181,7 +181,7 @@ delegate_components! { Two things differ from `#[cgp_computer]`'s block. `ComputerComponent` **is** in the list, because a producer does not implement it directly. A computer takes an input and the producer has none, so the promotion discards it. And the operator is **`:`** rather than `->`, delegating each component straight to -[`PromoteProducer`](../providers/handler_combinators.md) rather than to that bundle's own entry for the +[`PromoteProducer`](../providers/handler/promote_producer.md) rather than to that bundle's own entry for the key. `PromoteProducer` then wires `ComputerComponent` to a promoter that drops the input and calls `produce`, and derives the remaining members from there. @@ -246,7 +246,7 @@ import. - [`#[cgp_computer]`](./cgp_computer.md) — the sibling for a computation that takes an input. - [`Producer`](../components/producer.md) — the base component this implements. -- [Handler combinators](../providers/handler_combinators.md) — `PromoteProducer`, which this wires, plus +- [Handler combinators](../providers/handler/index.md) — `PromoteProducer`, which this wires, plus `ReturnInput` and `PipeHandlers`. - [`Computer`](../components/computer.md) and [`Handler`](../components/handler.md) — the members the promotion reaches. diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 75300f21..2e4c558a 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -198,7 +198,7 @@ the order *is* the execution order. - [`HasFields`](../traits/has_fields.md) — the trait that exposes a struct's shape as one of these lists. - [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates that list for you. - [`AppendProduct`](../traits/append_product.md) — the operations that combine and transform these lists. -- [Handler combinators](../providers/handler_combinators.md) — where `Product!` is written by hand, as a +- [Handler combinators](../providers/handler/index.md) — where `Product!` is written by hand, as a pipeline. The ideas behind it: diff --git a/docs/reference/providers/dispatch/_category_.json b/docs/reference/providers/dispatch/_category_.json new file mode 100644 index 00000000..d8e05314 --- /dev/null +++ b/docs/reference/providers/dispatch/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Dispatch combinators", + "position": 14, + "link": { + "type": "doc", + "id": "reference/providers/dispatch/index" + } +} diff --git a/docs/reference/providers/dispatch/build_and_merge.md b/docs/reference/providers/dispatch/build_and_merge.md new file mode 100644 index 00000000..6fe7aaff --- /dev/null +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -0,0 +1,83 @@ +--- +sidebar_label: 'BuildAndMerge' +sidebar_position: 9 +--- + +# `BuildAndMerge` + +The builder adapter that computes a whole record's worth of fields and copies every shared field into +the builder at once. + +## Overview + +`BuildAndMerge` is the bulk counterpart of [`BuildAndSetField`](build_and_set_field.md). +Instead of setting one field, it runs `Provider` over a reference to the builder to produce another +record, then copies every shared field from that result into the builder in one step. It runs on a +**context**, the type a capability runs against, and is the field-list analogue of setting a single +field. Like every CGP provider, it carries no runtime value. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes the provider that produces the record to merge, and +appears in a builder list alongside single-field adapters: + +```rust +use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; + +type Handlers = Product![ + BuildAndMerge, + BuildAndSetField, +]; +``` + +## When to reach for it, and when not + +**Reach for `BuildAndMerge` when a builder step produces several fields at once**, a sub-record merged +into the result, inside a list passed to [`BuildWithHandlers`](build_with_handlers.md). For a single +field use [`BuildAndSetField`](build_and_set_field.md). When the list is plain field-producing providers +rather than builder adapters, [`BuildAndMergeOutputs`](build_and_merge_outputs.md) wraps each one in +`BuildAndMerge` for you. + +## Under the hood + +`BuildAndMerge` carries the provider in `PhantomData`: + +```rust +pub struct BuildAndMerge(pub PhantomData); + +impl Computer + for BuildAndMerge +where + Provider: for<'a> Computer, + Builder: CanBuildFrom, +{ + type Output = Output; + // compute: let output = Provider::compute(context, code, &builder); + // builder.build_from(output) +} +``` + +It runs `Provider` on a reference to the builder to produce a result record, then uses +[`CanBuildFrom`](../../traits/can_build_from.md) to copy every shared field into the builder. It +implements `Computer`, `TryComputer`, and `Handler`; the fallible and async forms require the context to +have an error type. + +## Related constructs + +- [`BuildAndSetField`](build_and_set_field.md) — the single-field counterpart. +- [`BuildWithHandlers`](build_with_handlers.md) — the entry point that runs a list of these adapters. +- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — wraps a list of plain field-producing providers + in `BuildAndMerge` automatically. +- [`CanBuildFrom`](../../traits/can_build_from.md) — the cast it uses to copy shared fields. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — assembling a record from independent parts. + +## Source + +- [`providers/field_builders/build_and_merge.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/field_builders/build_and_merge.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/build_and_merge_outputs.md b/docs/reference/providers/dispatch/build_and_merge_outputs.md new file mode 100644 index 00000000..0fda4889 --- /dev/null +++ b/docs/reference/providers/dispatch/build_and_merge_outputs.md @@ -0,0 +1,76 @@ +--- +sidebar_label: 'BuildAndMergeOutputs' +sidebar_position: 11 +--- + +# `BuildAndMergeOutputs` + +Build a record from a list of plain field-producing providers, wrapping each in a merge step +automatically. + +## Overview + +`BuildAndMergeOutputs` is a higher-level wrapper over +[`BuildWithHandlers`](build_with_handlers.md), used when the handler list is a list of plain +field-producing providers rather than builder adapters. It wraps each provider in +[`BuildAndMerge`](build_and_merge.md) for you, so a caller supplies result-producing providers and each +one is merged into the builder without the caller writing the merge step. It runs on a **context**, the +type a capability runs against. Like every CGP provider, it carries no runtime value. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes the output record type and a +[`Product!`](../../macros/product.md) list of field-producing providers: + +```rust +use cgp::extra::dispatch::BuildAndMergeOutputs; + +// Each provider produces some fields; BuildAndMergeOutputs merges them all into an App. +delegate_components! { + AppBuilder { + ComputerComponent: + BuildAndMergeOutputs, + } +} +``` + +Each of the three providers produces a record's worth of fields, and `BuildAndMergeOutputs` merges them +in turn into an `App`. + +## When to reach for it, and when not + +**Reach for `BuildAndMergeOutputs` when your handlers are plain field-producing providers** rather than +builder adapters, so each is merged into the builder without you writing the merge step. When you want +to control each step, setting one field or merging explicitly, use +[`BuildWithHandlers`](build_with_handlers.md) directly with +[`BuildAndSetField`](build_and_set_field.md) and [`BuildAndMerge`](build_and_merge.md). + +## Under the hood + +`BuildAndMergeOutputs` is a [`delegate_components!`](../../macros/delegate_components.md) +table that maps the whole handler family (`ComputerComponent`, `TryComputerComponent`, +`HandlerComponent`, and their `Ref` forms) to +`BuildWithHandlers`, where each provider in `Handlers` has first been wrapped +in [`BuildAndMerge`](build_and_merge.md). The wrapping is done by mapping the list through the +`ToBuildAndMergeHandler` [`MapType`](../../traits/map_type.md) marker, so a caller supplies plain +result-producing providers and each is merged into the builder automatically. + +## Related constructs + +- [`BuildWithHandlers`](build_with_handlers.md) — the entry point this wraps, for a list of builder + adapters directly. +- [`BuildAndMerge`](build_and_merge.md) — the merge step each provider in the list is wrapped in. +- [`MapType`](../../traits/map_type.md) — the trait the list-mapping marker implements. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — assembling a record from independent + per-subsystem outputs. + +## Source + +- [`providers/builders/build_and_merge_outputs.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/builders/build_and_merge_outputs.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/build_and_set_field.md b/docs/reference/providers/dispatch/build_and_set_field.md new file mode 100644 index 00000000..daca9418 --- /dev/null +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -0,0 +1,81 @@ +--- +sidebar_label: 'BuildAndSetField' +sidebar_position: 8 +--- + +# `BuildAndSetField` + +The builder adapter that computes one field's value and sets it on a partial record. + +## Overview + +`BuildAndSetField` is the single-field builder adapter. It takes a builder, a partial +record, runs `Provider` over a *reference* to that builder to compute the value for `Tag`, then sets +that field and returns the advanced builder. Because the provider sees `&Builder`, it can read fields +already set on the partial record while computing the next one. It runs on a **context**, the type a +capability runs against. Like every CGP provider, it carries no runtime value. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes a field tag and the provider that computes the field's +value, and appears as an element of a builder list passed to +[`BuildWithHandlers`](build_with_handlers.md): + +```rust +use cgp::extra::dispatch::{BuildAndSetField, BuildWithHandlers}; + +type Handlers = Product![ + BuildAndSetField, + BuildAndSetField, +]; +``` + +## When to reach for it, and when not + +**Reach for `BuildAndSetField` when a builder step computes one named field**, inside a list passed to +[`BuildWithHandlers`](build_with_handlers.md). To copy a whole record's worth of fields in one step, use +[`BuildAndMerge`](build_and_merge.md) instead. + +## Under the hood + +`BuildAndSetField` carries the tag and provider in `PhantomData`: + +```rust +pub struct BuildAndSetField(pub PhantomData<(Tag, Provider)>); + +impl Computer + for BuildAndSetField +where + Provider: for<'a> Computer, + Builder: BuildField, +{ + type Output = Output; + // compute: let value = Provider::compute(context, code, &builder); + // builder.build_field(PhantomData::, value) +} +``` + +It runs `Provider` on a reference to the builder to compute the value, then calls +[`BuildField`](../../traits/build_field.md) to set it. It implements `Computer`, `TryComputer`, and +`Handler`; the fallible and async forms require the context to have an error type and propagate the +provider's error. + +## Related constructs + +- [`BuildAndMerge`](build_and_merge.md) — the bulk counterpart, copying a whole record's fields at once. +- [`BuildWithHandlers`](build_with_handlers.md) — the entry point that runs a list of these adapters and + finalizes. +- [`BuildField`](../../traits/build_field.md) — the trait it drives to set a field. +- [`UseContext`](../use_context.md) — the default provider. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — building a record field by field. + +## Source + +- [`providers/field_builders/build_and_set_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/field_builders/build_and_set_field.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/build_with_handlers.md b/docs/reference/providers/dispatch/build_with_handlers.md new file mode 100644 index 00000000..10164fa8 --- /dev/null +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -0,0 +1,96 @@ +--- +sidebar_label: 'BuildWithHandlers' +sidebar_position: 10 +--- + +# `BuildWithHandlers` + +Turn a list of builder adapters into a complete record, starting from an empty builder and finalizing +the fully-populated result. + +## Overview + +`BuildWithHandlers` is the entry point on the builder side. It starts from an empty +partial record, pipes that builder through a list of builder adapters so each one sets its field, and +finalizes the fully-populated result into the concrete `Output`. It runs on a **context**, the type a +capability runs against. Because the finalize step is available only when every field is present, +omitting a handler for some field is a compile error rather than a runtime failure. Like every CGP +provider, it carries no runtime value. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes the output record type and a +[`Product!`](../../macros/product.md) list of builder adapters: + +```rust +use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; + +type Handlers = Product![ + BuildAndMerge, + BuildAndSetField, +]; + +let foo_bar_baz = BuildWithHandlers::::compute(&context, code, ()); +``` + +`BuildWithHandlers` starts from `FooBarBaz::builder()`, runs [`BuildAndMerge`](build_and_merge.md) to +copy the `foo` and `bar` fields from a built `FooBar`, runs +[`BuildAndSetField`](build_and_set_field.md) to compute and set `baz`, and finalizes. Dropping either +handler leaves a field unset and fails to compile at the finalize step. + +## When to reach for it, and when not + +**Reach for `BuildWithHandlers` to assemble a record from a list of builder adapters**, +[`BuildAndSetField`](build_and_set_field.md) and [`BuildAndMerge`](build_and_merge.md). When the list is +plain field-producing providers instead, [`BuildAndMergeOutputs`](build_and_merge_outputs.md) wraps each +one and defers here. To take a value apart rather than assemble one, use a matcher such as +[`MatchWithHandlers`](match_with_handlers.md). + +## Under the hood + +`BuildWithHandlers` carries the output type and the list in `PhantomData`: + +```rust +pub struct BuildWithHandlers(pub PhantomData<(Output, Handlers)>); + +impl Computer + for BuildWithHandlers +where + Output: HasBuilder, + PipeHandlers: Computer, + Res: FinalizeBuild, +{ + type Output = Output; + // compute: PipeHandlers::compute(context, code, Output::builder()).finalize_build() +} +``` + +It obtains an empty builder from [`HasBuilder`](../../traits/has_builder.md), threads it through the list +with [`PipeHandlers`](../handler/pipe_handlers.md) so each adapter sets its field, and calls +[`FinalizeBuild`](../../traits/finalize_build.md) to recover the concrete `Output`. The original `Input` +is discarded; the output is produced from the builder. It implements `Computer`, `TryComputer`, and +`Handler`, the latter two requiring the context to have an error type. Because `finalize_build` is in +scope only for the all-present builder configuration, a missing field is caught at compile time. + +## Related constructs + +- [`BuildAndSetField`](build_and_set_field.md), [`BuildAndMerge`](build_and_merge.md) — the adapters + its list is built from. +- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — the higher-level wrapper for a list of plain + field-producing providers. +- [`PipeHandlers`](../handler/pipe_handlers.md) — the pipeline it threads the builder through. +- [`HasBuilder`](../../traits/has_builder.md), [`FinalizeBuild`](../../traits/finalize_build.md) — the + traits that start and finish the build. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — building a record field by field, checked at + compile time. + +## Source + +- [`providers/with_handlers/build_with_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/with_handlers/build_with_handlers.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/downcast_and_handle.md b/docs/reference/providers/dispatch/downcast_and_handle.md new file mode 100644 index 00000000..a7859fdd --- /dev/null +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -0,0 +1,75 @@ +--- +sidebar_label: 'DowncastAndHandle' +sidebar_position: 7 +--- + +# `DowncastAndHandle` + +The adapter that matches a whole group of variants at once by narrowing to a smaller enum. + +## Overview + +`DowncastAndHandle` is the matcher adapter that handles a *group* of variants in one +step rather than a single variant. Instead of extracting one field, it tries to narrow the input to a +smaller enum type `Inner`. On success it hands the whole `Inner` value to `Provider` and returns `Ok`; +on failure it returns `Err` of the remainder. It runs on a **context**, the type a capability runs +against, and lets a matcher delegate several variants to one sub-matcher in a single step. Like every +CGP provider, it carries no runtime value. + +`Provider` defaults to [`UseContext`](../use_context.md). + +## Usage + +Import it from `cgp::extra::dispatch`. It takes the inner enum type to narrow to and an optional inner +provider, and appears as an element of a matcher's list alongside single-variant adapters: + +```rust +use cgp::extra::dispatch::{DowncastAndHandle, ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + +// Handle the two "primitive" variants together via a sub-matcher, and the rest one at a time. +type Match = MatchWithHandlers, + ExtractFieldAndHandle>, +]>; +``` + +## When to reach for it, and when not + +**Reach for `DowncastAndHandle` when several variants share one sub-handler** and you want to route them +as a group rather than name each one. For a single variant use +[`ExtractFieldAndHandle`](extract_field_and_handle.md). Both go in a list consumed by +[`MatchWithHandlers`](match_with_handlers.md). + +## Under the hood + +`DowncastAndHandle` carries the inner enum type and the provider in `PhantomData`: + +```rust +pub struct DowncastAndHandle(pub PhantomData<(Input, Provider)>); +``` + +Its `Output` is `Result`. It uses +[`CanDowncastFields`](../../traits/can_downcast_fields.md) to try to narrow the input to `Inner`; +on success it hands the whole `Inner` value to `Provider` and returns `Ok`, and on failure it returns +`Err` of the remainder. It implements both `Computer` and `AsyncComputer`. + +## Related constructs + +- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the single-variant adapter this generalizes to + a group. +- [`MatchWithHandlers`](match_with_handlers.md) — the matcher that consumes a list mixing both. +- [`CanDowncastFields`](../../traits/can_downcast_fields.md) — the cast it uses to narrow the input. +- [`UseContext`](../use_context.md) — the default inner provider. + +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — routing a group of variants to one sub-handler. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern and its casts. + +## Source + +- [`providers/field_matchers/extract_handle.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/field_matchers/extract_handle.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/extract_field_and_handle.md b/docs/reference/providers/dispatch/extract_field_and_handle.md new file mode 100644 index 00000000..d95806e9 --- /dev/null +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -0,0 +1,92 @@ +--- +sidebar_label: 'ExtractFieldAndHandle' +sidebar_position: 5 +--- + +# `ExtractFieldAndHandle` + +The per-variant adapter that tries one variant and forwards its matched payload to an inner handler. + +## Overview + +`ExtractFieldAndHandle` is the variant adapter a matcher's handler list is built from. It +tries to extract the variant named `Tag` from the input. On success it wraps the payload in a +`Field` and hands it to `Provider`, returning `Ok` of the provider's output. On failure it +returns `Err` of the remainder, the extractor with that variant ruled out. It runs on a **context**, the +type a capability runs against. The `Result` shape it returns is exactly what the +matcher loop expects, so a [`Product!`](../../macros/product.md) of these adapters is the list a matcher +consumes. Like every CGP provider, it carries no runtime value. + +`Provider` defaults to [`UseContext`](../use_context.md), so a matched payload routes back through the +context's own handler wiring unless another provider is named. The first-argument variant +`ExtractFirstFieldAndHandle` is the same adapter for the `(Input, Args)` calling +convention: it threads the arguments into the provider call as `(Field, Args)` and returns +`Result`. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes a variant tag and an optional inner provider, and +appears as an element of a matcher's list: + +```rust +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + +type Match = MatchWithHandlers>, + ExtractFieldAndHandle>, +]>; +``` + +The payload arrives at `Provider` still wrapped as a `Field`, so wrapping the inner handler +in [`HandleFieldValue`](handle_field_value.md) is what strips the tag to a bare value. The convenience +matchers [`MatchWithValueHandlers`](match_with_value_handlers.md) and +[`MatchWithFieldHandlers`](match_with_field_handlers.md) generate lists of these adapters from an enum's +fields, so you rarely write them out by hand. + +## When to reach for it, and when not + +**Reach for `ExtractFieldAndHandle` when you spell out a matcher's per-variant list by hand** with +[`MatchWithHandlers`](match_with_handlers.md), naming one adapter per variant. When every variant is +handled the same way, [`MatchWithValueHandlers`](match_with_value_handlers.md) generates the list of +these adapters for you and is far shorter. Use the first-argument form `ExtractFirstFieldAndHandle` +documented here when the handlers also take extra arguments, and +[`DowncastAndHandle`](downcast_and_handle.md) to match a group of variants in one step. + +## Under the hood + +`ExtractFieldAndHandle` carries the tag and provider in `PhantomData`: + +```rust +pub struct ExtractFieldAndHandle(pub PhantomData<(Tag, Provider)>); +pub struct ExtractFirstFieldAndHandle(pub PhantomData<(Tag, Provider)>); +``` + +Its `Output` is `Result`. It calls [`ExtractField`](../../traits/extract_field.md) +on the input; on success it forwards a `Field` to `Provider` and returns `Ok`, and on +failure it returns `Err` of the remainder, the extractor with that variant ruled out. It implements both +`Computer` and `AsyncComputer`. + +## Related constructs + +- [`HandleFieldValue`](handle_field_value.md) — strips the `Field` wrapper this adapter delivers, so the + inner handler receives the bare payload. +- [`DowncastAndHandle`](downcast_and_handle.md) — the adapter that matches a group of variants at once + instead of one. +- [`MatchWithHandlers`](match_with_handlers.md) — the matcher that consumes a list of these adapters. +- [`ExtractField`](../../traits/extract_field.md) — the trait it drives, and + [`Field`](../../types/field.md) — the tagged payload it forwards. +- [`UseContext`](../use_context.md) — the default inner provider. + +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — routing one variant to a handler. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern it serves. + +## Source + +- [`providers/field_matchers/extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/field_matchers/extract_field.rs), + and `extract_first_field.rs` for the first-argument form. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/handle_field_value.md b/docs/reference/providers/dispatch/handle_field_value.md new file mode 100644 index 00000000..cb8b6a44 --- /dev/null +++ b/docs/reference/providers/dispatch/handle_field_value.md @@ -0,0 +1,80 @@ +--- +sidebar_label: 'HandleFieldValue' +sidebar_position: 6 +--- + +# `HandleFieldValue` + +Strip the variant tag from a matched payload and pass the bare value to an inner handler. + +## Overview + +`HandleFieldValue` is the unwrapping adapter that sits between an extract adapter and the +handler that does the work. An extract adapter such as +[`ExtractFieldAndHandle`](extract_field_and_handle.md) delivers a `Field`, so the variant +name stays attached to the payload. `HandleFieldValue` strips the `Field` wrapper and passes the bare +`Value` to `Provider`, on a **context**, the type a capability runs against. This is what lets an +ordinary computer over the payload type serve as a per-variant handler. Like every CGP provider, it +carries no runtime value. + +`Provider` defaults to [`UseContext`](../use_context.md). The first-argument variant +`HandleFirstFieldValue` does the same for the `(Field, Args)` tuple, forwarding +`(Input, Args)`. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes one optional type parameter, the inner provider, and +wraps the handler inside an extract adapter: + +```rust +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue}; + +// ComputeArea is an ordinary computer over the payload type; HandleFieldValue +// removes the Field wrapper so it receives the bare payload. +type CircleArm = ExtractFieldAndHandle>; +``` + +The convenience matcher [`MatchWithValueHandlers`](match_with_value_handlers.md) adds this wrapper +automatically, which is the one difference between it and +[`MatchWithFieldHandlers`](match_with_field_handlers.md). + +## When to reach for it, and when not + +**Reach for `HandleFieldValue` inside an extract adapter when the inner handler is an ordinary computer +over the payload type**, so it receives the bare value rather than a tagged `Field`. You rarely write it +directly, because [`MatchWithValueHandlers`](match_with_value_handlers.md) adds it for you. Omit it, or +use [`MatchWithFieldHandlers`](match_with_field_handlers.md), when the handler needs the variant tag. + +## Under the hood + +`HandleFieldValue` carries the inner provider in `PhantomData`: + +```rust +pub struct HandleFieldValue(pub PhantomData); +pub struct HandleFirstFieldValue(pub PhantomData); +``` + +It takes a `Field` input, unwraps it to the bare `Value`, and forwards to `Provider`. +`HandleFirstFieldValue` unwraps the `(Field, Args)` tuple and forwards `(Input, Args)`. + +## Related constructs + +- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the extract adapter that delivers the + `Field` this strips. +- [`MatchWithValueHandlers`](match_with_value_handlers.md) — adds this wrapper automatically; + [`MatchWithFieldHandlers`](match_with_field_handlers.md) does not. +- [`Field`](../../types/field.md) — the tagged payload it unwraps. +- [`UseContext`](../use_context.md) — the default inner provider. + +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — preparing a matched payload for a handler. + +## Source + +- [`providers/field_matchers/field_value.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/field_matchers/field_value.rs), + and `first_field_value.rs` for the first-argument form. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/index.md b/docs/reference/providers/dispatch/index.md new file mode 100644 index 00000000..0f92f80e --- /dev/null +++ b/docs/reference/providers/dispatch/index.md @@ -0,0 +1,91 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Dispatch combinators + +The providers that route an extensible-data value (a record or a variant) to per-field or per-variant +handlers, and assemble or finalize the result. + +## Overview + +The dispatch combinators handle an arbitrary record or enum generically, where the set of fields or +variants is not known at the call site and the handling logic for each one lives in a separate +provider. A hand-written `match` names every variant in one place; these combinators instead drive the +extractor and builder trait families to do the same work over a value whose shape is only known at the +type level, dispatching each field or variant to a handler chosen by type. They run on a **context**, +the type a capability runs against, and are all [`Computer`](../../components/computer.md)-family +providers, several also [`Handler`](../../components/handler.md) and +[`TryComputer`](../../components/try_computer.md) providers. Like every CGP provider, each is zero-sized. + +The combinators divide into two halves. + +The **matcher** half consumes a sum type. It tries each variant in turn, hands the matched payload to a +handler, and proves the match exhaustive without a wildcard arm: + +- [`MatchWithHandlers`](match_with_handlers.md) runs a spelled-out list of per-variant handlers over an + owned input. +- [`MatchFirstWithHandlers`](match_first_with_handlers.md) does the same for the multi-argument calling + convention, where the input carries extra arguments alongside the value. +- [`MatchWithValueHandlers`](match_with_value_handlers.md) and + [`MatchWithFieldHandlers`](match_with_field_handlers.md) build that list automatically from the input + type's own field list. + +The per-variant list a matcher runs is normally a list of **adapters**, each trying one variant and +forwarding the payload: + +- [`ExtractFieldAndHandle`](extract_field_and_handle.md) extracts one variant and hands the payload, + still tagged, to an inner provider. +- [`HandleFieldValue`](handle_field_value.md) strips the tag so the inner provider receives the bare + value. +- [`DowncastAndHandle`](downcast_and_handle.md) matches a whole group of variants at once. + +The **builder** half produces a product type. It starts from an empty builder, runs a handler per field, +and finalizes the fully-populated record: + +- [`BuildAndSetField`](build_and_set_field.md) computes and sets one field. +- [`BuildAndMerge`](build_and_merge.md) copies a whole record's worth of fields in at once. +- [`BuildWithHandlers`](build_with_handlers.md) is the entry point that runs a list of builder adapters + and finalizes. +- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) is the wrapper for a list of plain field-producing + providers. + +Both halves are handler providers, so they compose with the [handler combinators](../handler/index.md), +nest inside [`UseInputDelegate`](../handler/use_input_delegate.md), and can be wired into a context with +[`delegate_components!`](../../macros/delegate_components.md). The matcher loop they share is +`DispatchMatchers`, a type alias for [`PipeMonadic`](../monad/pipe_monadic.md) under the `OkMonadic` +monad; it is an implementation detail rather than a construct a user names, and it is explained under +the hood on [`MatchWithHandlers`](match_with_handlers.md). + +## Related constructs + +- [`#[cgp_auto_dispatch]`](../../macros/cgp_auto_dispatch.md) — generates a matcher-backed handler impl + automatically. +- [`extract_field`](../../traits/extract_field.md), [`has_extractor`](../../traits/has_extractor.md), + [`finalize_extract`](../../traits/finalize_extract.md) — the enum-deconstruction traits the matchers + stand on. +- [`has_builder`](../../traits/has_builder.md), [`build_field`](../../traits/build_field.md), + [`finalize_build`](../../traits/finalize_build.md) — the record-assembly traits the builders stand on. +- [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher the convenience matchers + use. +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — the derive that gives a type the shape these + operate over. + +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to per-field and + per-variant handlers. +- [Extensible records](/docs/concepts/extensible-records) and + [Extensible variants](/docs/concepts/extensible-variants) — the data patterns the builders and matchers + serve. + +## Source + +- The provider structs are in `cgp-dispatch` under + [`providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-dispatch/src/providers). + The prelude re-exports the value-handler matchers; the rest are reached through `cgp::extra::dispatch`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/match_first_with_handlers.md b/docs/reference/providers/dispatch/match_first_with_handlers.md new file mode 100644 index 00000000..8d5d7763 --- /dev/null +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -0,0 +1,109 @@ +--- +sidebar_label: 'MatchFirstWithHandlers' +sidebar_position: 2 +--- + +# `MatchFirstWithHandlers` + +Match an enum for the multi-argument calling convention, where the input carries extra arguments +alongside the value. + +## Overview + +`MatchFirstWithHandlers` is the matcher for the calling convention where the input is a tuple +`(Input, Args)`: the value being matched, together with extra arguments to pass to each handler. It +threads `Args` through the loop unchanged, so on a miss both the shrinking remainder and the still-owned +arguments carry to the next handler. It runs on a **context**, the type a capability runs against. The +"first" in the name reflects that the value being matched is the *first* element of the input tuple. +Like every CGP provider, it carries no runtime value; the handler list rides in `PhantomData`. + +Two borrowed forms exist: `MatchFirstWithHandlersRef` over `(&Input, Args)` and +`MatchFirstWithHandlersMut` over `(&mut Input, Args)`. Each of the three implements both +`Computer` and `AsyncComputer`. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes one type parameter, a +[`Product!`](../../macros/product.md) list of per-variant adapters, built from +[`ExtractFirstFieldAndHandle`](extract_field_and_handle.md) and +[`HandleFirstFieldValue`](handle_field_value.md) rather than their plain forms: + +```rust +use cgp::extra::dispatch::{ + ExtractFirstFieldAndHandle, HandleFirstFieldValue, MatchFirstWithHandlers, +}; + +// Each handler receives the matched payload together with the shared Args. +type Match = MatchFirstWithHandlers>, + ExtractFirstFieldAndHandle>, +]>; +``` + +For a list built automatically, use [`MatchFirstWithValueHandlers`](match_with_value_handlers.md). + +## When to reach for it, and when not + +**Reach for `MatchFirstWithHandlers` when the per-variant handlers need extra arguments passed alongside +the matched value**, such as a renderer that takes a target buffer or a visitor that takes an +accumulator. When the handlers need only the value, use the plain +[`MatchWithHandlers`](match_with_handlers.md), which is simpler. + +## Under the hood + +`MatchFirstWithHandlers` carries the list in `PhantomData`: + +```rust +pub struct MatchFirstWithHandlers(pub PhantomData); +``` + +Its `Computer` impl runs the shared matcher loop over `(Input::Extractor, Args)` and returns +`Result`, so a miss carries both the shrunken remainder and the still-owned +arguments to the next handler. When the loop finishes with an `Err`, the remainder is uninhabited and is +discharged through `finalize_extract`: + +```rust +impl + Computer for MatchFirstWithHandlers +where + Input: HasExtractor, + DispatchMatchers: Computer< + Context, Code, (Input::Extractor, Args), + Output = Result>, + Remainder: FinalizeExtract, +{ + type Output = Output; + // compute: match DispatchMatchers::compute(context, code, (input.to_extractor(), args)) { + // Ok(output) => output, + // Err((remainder, _)) => remainder.finalize_extract(), + // } +} +``` + +The loop is the same `DispatchMatchers` alias described on +[`MatchWithHandlers`](match_with_handlers.md#under-the-hood). + +## Related constructs + +- [`MatchWithHandlers`](match_with_handlers.md) — the plain matcher, for handlers that need only the + value. +- [`ExtractFirstFieldAndHandle`](extract_field_and_handle.md), + [`HandleFirstFieldValue`](handle_field_value.md) — the first-argument adapters its list is built from. +- [`MatchWithValueHandlers`](match_with_value_handlers.md) — the automatic form, whose + `MatchFirstWithValueHandlers` sibling matches this convention. +- [`HasExtractor`](../../traits/has_extractor.md), [`FinalizeExtract`](../../traits/finalize_extract.md) + — the traits it stands on. + +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — routing a value, with extra arguments, to per-variant + handlers. + +## Source + +- [`providers/with_handlers/match_first_with_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/with_handlers/match_first_with_handlers.rs), + with the borrowed forms in `match_first_with_handlers_ref.rs` and `match_first_with_handlers_mut.rs`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/match_with_field_handlers.md b/docs/reference/providers/dispatch/match_with_field_handlers.md new file mode 100644 index 00000000..3ef5d80c --- /dev/null +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -0,0 +1,108 @@ +--- +sidebar_label: 'MatchWithFieldHandlers' +sidebar_position: 4 +--- + +# `MatchWithFieldHandlers` + +Match an enum by building the per-variant handler list automatically, passing each payload with its +variant tag still attached. + +## Overview + +`MatchWithFieldHandlers` synthesizes the per-variant handler list from the input type's own +field list, like [`MatchWithValueHandlers`](match_with_value_handlers.md), but hands each matched +payload to `Provider` as a `Field` with the variant name still attached rather than as a +bare value. It runs on a **context**, the type a capability runs against. Reach for it when the handler +needs to know which variant it received. Like every CGP provider, it carries no runtime value. + +The two matchers differ by exactly one [`HandleFieldValue`](handle_field_value.md) wrapper: +`MatchWithValueHandlers` wraps `Provider` in it to strip the tag, and `MatchWithFieldHandlers` does not. +`Provider` defaults to [`UseContext`](../use_context.md). The borrowed and multi-argument variants are +`MatchWithFieldHandlersRef` and the first-argument aliases `MatchFirstWithFieldHandlers`, +`MatchFirstWithFieldHandlersRef`, and `MatchFirstWithFieldHandlersMut`. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes one optional type parameter, the per-variant provider. +Because it is itself a [`UseInputDelegate`](../handler/use_input_delegate.md) alias, it is wired +directly to a handler component and dispatches on the input type: + +```rust +use cgp::extra::dispatch::MatchWithFieldHandlers; + +delegate_components! { + App { + ComputerComponent: MatchWithFieldHandlers, + } +} +``` + +`FieldToString` receives each matched payload as a `Field`, so the variant tag stays +attached to it. For a handler that wants only the payload, use +[`MatchWithValueHandlers`](match_with_value_handlers.md). + +## When to reach for it, and when not + +**Reach for `MatchWithFieldHandlers` when the per-variant handler needs the variant tag**, for example +to log which case ran or to route further by name. When the handler wants only the payload, which is the common +case, [`MatchWithValueHandlers`](match_with_value_handlers.md) is simpler. + +## Under the hood + +`MatchWithFieldHandlers` is a type alias over +[`UseInputDelegate`](../handler/use_input_delegate.md): + +```rust +pub type MatchWithFieldHandlers = + UseInputDelegate>; +``` + +The per-variant list is built from a context's field list by three cooperating traits. `MapFieldHandler` +is a type-level function from a field's `Tag` to the adapter that should handle it; `ToFieldHandlers` +walks the [sum spine](../../types/type_level_spines.md) of a field list and applies that function to each +field, producing a [`Product!`](../../macros/product.md) list of adapters; and `HasFieldHandlers` reads a +context's [`HasFields`](../../traits/has_fields.md) list and runs `ToFieldHandlers` over it: + +```rust +impl HasFieldHandlers for Context +where + Context: HasFields, + Fields: ToFieldHandlers, +{ + type Handlers = Fields::Handlers; +} +``` + +`ToFieldHandlers` is implemented inductively over the sum spine: for `Either, Rest>` +it produces `Cons, Rest::Handlers>`, and for the terminating `Void` it produces +`Nil`. The `MapFieldHandler` marker the crate supplies here is `MapExtractFieldAndHandle`, +whose `FieldHandler` is [`ExtractFieldAndHandle`](extract_field_and_handle.md)``, so +the matcher runs one extract adapter per variant without the user spelling out the list. +`MatchWithValueHandlers` differs only by wrapping `Provider` in +[`HandleFieldValue`](handle_field_value.md) first. + +## Related constructs + +- [`MatchWithValueHandlers`](match_with_value_handlers.md) — the sibling that strips the tag; the two + differ by one `HandleFieldValue` wrapper. +- [`MatchWithHandlers`](match_with_handlers.md) — the explicit form the list expands to. +- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the per-variant adapter the list is built + from. +- [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher this alias is built on. +- [`HasFields`](../../traits/has_fields.md) — the field list the handler list is synthesized from. + +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — routing each variant of an enum to a handler. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern it serves. + +## Source + +- [`providers/matchers/match_with_field_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs), + with the field-to-handler machinery in `to_field_handlers.rs` and the first-argument forms in + `match_first_with_field_handlers.rs`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/match_with_handlers.md b/docs/reference/providers/dispatch/match_with_handlers.md new file mode 100644 index 00000000..e170c2b5 --- /dev/null +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -0,0 +1,149 @@ +--- +sidebar_label: 'MatchWithHandlers' +sidebar_position: 1 +--- + +# `MatchWithHandlers` + +Match an enum against a spelled-out list of per-variant handlers, proving the match exhaustive without a +wildcard arm. + +## Overview + +`MatchWithHandlers` is the owned-input matcher. Given a value, it converts the value to its +extractor and runs a list of handlers over it, stopping at the first one that matches. It runs on a +**context**, the type a capability runs against. When the list is exhausted the remaining type has every +variant ruled out and is therefore uninhabited, which is what lets the matcher return the bare output +with no fallback arm. Like every CGP provider, it carries no runtime value; the handler list rides in +`PhantomData`. + +Two borrowed forms match a value without moving it: `MatchWithHandlersRef` over `&Input` and +`MatchWithHandlersMut` over `&mut Input`. Each of the three implements both the synchronous +`Computer` and the `AsyncComputer` form. + +## Usage + +Import it from `cgp::extra::dispatch`. It takes one type parameter, a [`Product!`](../../macros/product.md) +list of per-variant adapters. The list is normally one [`ExtractFieldAndHandle`](extract_field_and_handle.md) +per variant, each wrapping its payload handler in [`HandleFieldValue`](handle_field_value.md): + +```rust +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + +delegate_components! { + App { + ComputerComponent: + MatchWithHandlers>, + ExtractFieldAndHandle>, + ]>, + } +} +``` + +For a list built automatically from the enum's own variants, reach for +[`MatchWithValueHandlers`](match_with_value_handlers.md) instead, which spells this list out for you. + +## Examples + +Dispatching a `Shape` enum to a per-variant area computer: + +```rust +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +// ComputeArea implements Computer for both the Circle and Rectangle payloads. +let circle = Shape::Circle(Circle { radius: 5.0 }); + +let _area = MatchWithHandlers::< + Product![ + ExtractFieldAndHandle>, + ExtractFieldAndHandle>, + ], +>::compute(&(), PhantomData::<()>, circle); +``` + +The list tries `Circle` first. If the value is a circle, `ComputeArea` runs on the `Circle` payload and +the loop stops. Otherwise the remainder carries `Circle` ruled out into the `Rectangle` adapter, the +last arm, so its failure would leave an uninhabited remainder that the matcher discharges. + +## When to reach for it, and when not + +**Reach for `MatchWithHandlers` when you want to name a handler per variant explicitly**, or when the +variants map to handlers in a way the automatic form cannot express. For the common case where every +variant is routed the same way, [`MatchWithValueHandlers`](match_with_value_handlers.md) builds the list +from the enum's fields and is far shorter. When the handlers also need extra arguments passed alongside +the value, use [`MatchFirstWithHandlers`](match_first_with_handlers.md). + +## Under the hood + +`MatchWithHandlers` carries the list in `PhantomData`: + +```rust +pub struct MatchWithHandlers(pub PhantomData); +``` + +Its `Computer` impl requires the input to implement [`HasExtractor`](../../traits/has_extractor.md), runs +the shared matcher loop over `Input::Extractor` to obtain `Result`, and calls +`finalize_extract_result` on that result so the uninhabited remainder is discharged: + +```rust +impl Computer + for MatchWithHandlers +where + Input: HasExtractor, + DispatchMatchers: + Computer>, + Remainder: FinalizeExtract, +{ + type Output = Output; + // compute: DispatchMatchers::compute(context, code, input.to_extractor()) + // .finalize_extract_result() +} +``` + +`DispatchMatchers` is the matcher loop every matcher shares. It is a type alias for +[`PipeMonadic`](../monad/pipe_monadic.md) under the `OkMonadic` monad: + +```rust +pub type DispatchMatchers = PipeMonadic; +``` + +Each handler in the list returns `Ok(output)` when it matches and `Err(remainder)` when it does not, +handing back the extractor with one more variant ruled out. Under `OkMonadic` the loop threads along the +`Err` branch and short-circuits on `Ok`, so it runs handler by handler, carrying the shrinking remainder +forward, until one returns `Ok`. `DispatchMatchers` is an implementation detail rather than a construct +a user names. + +## Related constructs + +- [`MatchWithValueHandlers`](match_with_value_handlers.md) — builds the handler list from the enum's own + variants instead of spelling it out. +- [`MatchFirstWithHandlers`](match_first_with_handlers.md) — the same matcher for the multi-argument + convention. +- [`ExtractFieldAndHandle`](extract_field_and_handle.md), [`HandleFieldValue`](handle_field_value.md) — + the adapters the list is built from. +- [`PipeMonadic`](../monad/pipe_monadic.md) — the `OkMonadic` pipeline the matcher loop is built on. +- [`HasExtractor`](../../traits/has_extractor.md), [`FinalizeExtract`](../../traits/finalize_extract.md), + [`FinalizeExtractResult`](../../traits/finalize_extract_result.md) — the traits it stands on. + +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to per-variant handlers. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern the matchers serve. + +## Source + +- [`providers/with_handlers/match_with_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs), + with the borrowed forms in `match_with_handlers_ref.rs` and `match_with_handlers_mut.rs`, and the loop + alias in + [`providers/dispatchers/dispatch_matchers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/dispatchers/dispatch_matchers.rs). + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md new file mode 100644 index 00000000..55887b2d --- /dev/null +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -0,0 +1,103 @@ +--- +sidebar_label: 'MatchWithValueHandlers' +sidebar_position: 3 +--- + +# `MatchWithValueHandlers` + +Match an enum by building the per-variant handler list automatically, passing each payload as a bare +value. + +## Overview + +`MatchWithValueHandlers` is the convenience matcher for the common case. Rather than spelling +out one adapter per variant, it synthesizes the handler list from the input type's own field list, so +adding a variant needs no change to the wiring. Each matched payload reaches `Provider` as a bare value, +which is the form to use when the per-variant handler is an ordinary computer over the payload type, +such as one generated by [`#[cgp_computer]`](../../macros/cgp_computer.md). It runs on a **context**, +the type a capability runs against. Like every CGP provider, it carries no runtime value. + +It is the value-passing sibling of [`MatchWithFieldHandlers`](match_with_field_handlers.md): the two +differ by exactly one [`HandleFieldValue`](handle_field_value.md) wrapper, which +`MatchWithValueHandlers` adds so `Provider` receives the payload rather than a tagged field. `Provider` +defaults to [`UseContext`](../use_context.md), so each payload routes back through the context's own +handler wiring unless another provider is named. + +The borrowed and multi-argument variants are `MatchWithValueHandlersRef` (over `&Input`), +`MatchWithValueHandlersMut` (over `&mut Input`), and the first-argument forms +`MatchFirstWithValueHandlers`, `MatchFirstWithValueHandlersRef`, and `MatchFirstWithValueHandlersMut`. + +## Usage + +It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one optional type parameter, the +per-variant provider, and is most often wired through +[`UseInputDelegate`](../handler/use_input_delegate.md) so it is selected when the input is a given enum: + +```rust +delegate_components! { + App { + ComputerComponent: UseInputDelegate, + } +} +``` + +A `Circle` input is handled directly by `ComputeArea`, while a `Shape` input is handled by +`MatchWithValueHandlers`, which synthesizes an adapter for each variant and routes each payload back +through the context's own `ComputerComponent`, so the `Circle` and `Rectangle` payloads reach +`ComputeArea` after all. `UseInputDelegate` is the correct wiring here because it keys on the input +type; it has no `open`-statement equivalent. + +## When to reach for it, and when not + +**Reach for `MatchWithValueHandlers` when every variant of an enum is handled the same way and each +handler wants the bare payload.** This is the usual case, and far shorter than spelling out the list +with [`MatchWithHandlers`](match_with_handlers.md). Reach for +[`MatchWithFieldHandlers`](match_with_field_handlers.md) when a handler needs the variant's tag attached +to its payload, and for [`MatchWithHandlers`](match_with_handlers.md) when the handlers cannot be +generated uniformly from the field list. + +## Under the hood + +`MatchWithValueHandlers` is a type alias over +[`UseInputDelegate`](../handler/use_input_delegate.md) that dispatches on the input type and, for each +input, synthesizes the per-variant handler list from that input's [`HasFields`](../../traits/has_fields.md): + +```rust +pub type MatchWithValueHandlers = + UseInputDelegate>>; +``` + +Wrapping `Provider` in [`HandleFieldValue`](handle_field_value.md) is the one difference from +[`MatchWithFieldHandlers`](match_with_field_handlers.md), and it is what makes each payload arrive as a +bare value. The list itself is assembled by the `HasFieldHandlers` machinery described on +[`MatchWithFieldHandlers`](match_with_field_handlers.md#under-the-hood). The borrowed variants +additionally wire the `…RefComponent` handler traits through [`PromoteRef`](../handler/promote_ref.md), +so one struct serves both the by-value-of-reference and the by-reference interfaces. + +## Related constructs + +- [`MatchWithFieldHandlers`](match_with_field_handlers.md) — the sibling that keeps the variant tag on + the payload; the two differ by one `HandleFieldValue` wrapper. +- [`MatchWithHandlers`](match_with_handlers.md) — the explicit form, when the list cannot be generated. +- [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher this alias is built on. +- [`HandleFieldValue`](handle_field_value.md), [`UseContext`](../use_context.md) — the wrapper it adds + and the default per-variant provider. +- [`HasFields`](../../traits/has_fields.md) — the field list the handler list is synthesized from. + +The ideas behind it: + +- [Dispatching](/docs/concepts/dispatching) — routing each variant of an enum to a handler. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern it serves. + +## Source + +- [`providers/matchers/match_with_field_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs), + with the first-argument forms in `match_first_with_field_handlers.rs`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch_combinators.md b/docs/reference/providers/dispatch_combinators.md deleted file mode 100644 index 9a0bb50c..00000000 --- a/docs/reference/providers/dispatch_combinators.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -sidebar_label: 'Dispatch combinators' -sidebar_position: 14 ---- - -# Dispatch combinators - -The variant-matching and record-assembling providers that route extensible data to handlers. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/docs/reference/providers/error/_category_.json b/docs/reference/providers/error/_category_.json new file mode 100644 index 00000000..ce19e957 --- /dev/null +++ b/docs/reference/providers/error/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Error providers", + "position": 12, + "link": { + "type": "doc", + "id": "reference/providers/error/index" + } +} diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md new file mode 100644 index 00000000..d038203d --- /dev/null +++ b/docs/reference/providers/error/debug_error.md @@ -0,0 +1,111 @@ +--- +sidebar_label: 'DebugError' +sidebar_position: 4 +--- + +# `DebugError` + +Raise or wrap any `Debug` source by formatting it into a `String` and forwarding to the context's own +string handling. + +## Overview + +`DebugError` implements both error components by redirecting through a string. Rather than producing the +abstract error directly, it formats the source error or the detail with the `Debug` trait into a +`String`, then forwards to the **context**'s own `CanRaiseError` or `CanWrapError`, +where the context is the type a capability runs against. It does not know the context's error type: it +only knows how to turn a `Debug` value into a `String` and hand it off, leaving the final step to +whatever string-handling provider the context already wires. Like every CGP provider, `DebugError` +carries no runtime value. + +This design is what lets a context handle an open-ended set of error types with one concrete +string-raising rule. `DebugError` routes every `Debug` source through the single `String` path, and the +context wires one provider (often [`RaiseFrom`](raise_from.md)) for that path. + +## Usage + +Import the provider from `cgp::extra::error` and the wiring keys from `cgp::core::error`. `DebugError` +lives behind the crate's `alloc` feature, because it allocates a `String`. It takes no type parameter +and is wired to `ErrorRaiserComponent`, `ErrorWrapperComponent`, or both: + +```rust +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::{DebugError, RaiseFrom}; + +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } +} +``` + +The `String` entry must be present for `DebugError` to forward to. Here a raised `ParseIntError` is +formatted with `Debug` and handed to the `String` entry, which `RaiseFrom` converts into the abstract +error. + +## When to reach for it, and when not + +**Reach for `DebugError` when a source error implements `Debug` but the abstract error has no `From` impl +for it, and you want its debug output carried as a string.** Pair it with a provider on the `String` +source, since it forwards rather than finishes. + +Reach for [`DisplayError`](display_error.md) when the source implements `Display` and you want its +user-facing message rather than its debug form. Reach for [`RaiseFrom`](raise_from.md) when a real `From` +impl exists, which preserves the source rather than flattening it to a string. + +## Under the hood + +`DebugError` implements `ErrorRaiser` for any `Debug` source over a context that raises `String`, and +`ErrorWrapper` for any `Debug` detail over a context that wraps `String`: + +```rust +#[cgp_provider] +impl ErrorRaiser for DebugError +where + Context: CanRaiseError, + E: Debug, +{ + fn raise_error(e: E) -> Context::Error { + Context::raise_error(format!("{e:?}")) + } +} + +#[cgp_provider] +impl ErrorWrapper for DebugError +where + Context: CanWrapError, + Detail: Debug, +{ + fn wrap_error(error: Context::Error, detail: Detail) -> Context::Error { + Context::wrap_error(error, format!("{detail:?}")) + } +} +``` + +Both bounds require the context to already handle the `String` case, which is the indirection that +reduces any `Debug` source to the one case the context knows. Each impl is paired with a matching +[`IsProviderFor`](../../traits/is_provider_for.md) impl. + +## Related constructs + +- [`DisplayError`](display_error.md) — the same provider formatting with `Display` and `to_string()`. +- [`CanRaiseError` and `CanWrapError`](../../components/can_raise_error.md) — the components it supplies, + and the `String` forms it forwards to. +- [`RaiseFrom`](raise_from.md) — the usual provider on the `String` source that finishes the raise. +- [`UseDelegate`](../use_delegate.md) — dispatches `DebugError` for the source types it should format. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — formatting providers as a redirect + onto one concrete string rule. + +## Source + +- [`impls/alloc/debug_error.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-error-extra/src/impls/alloc/debug_error.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/discard_detail.md b/docs/reference/providers/error/discard_detail.md new file mode 100644 index 00000000..403d873b --- /dev/null +++ b/docs/reference/providers/error/discard_detail.md @@ -0,0 +1,85 @@ +--- +sidebar_label: 'DiscardDetail' +sidebar_position: 6 +--- + +# `DiscardDetail` + +Wrap an error by throwing the detail away and returning the error unchanged. + +## Overview + +`DiscardDetail` is the `ErrorWrapper` provider that ignores whatever detail is attached and returns the +error as it was. It satisfies the `CanWrapError` capability of a **context**, the type a capability runs +against, without enriching the error. This is useful when a context's error type cannot carry extra +context, or when the wrapping detail is deliberately not kept. It is the wrapping counterpart of a no-op: +the error propagates unchanged. Like every CGP provider, `DiscardDetail` carries no runtime value. + +## Usage + +Import the provider from `cgp::extra::error` and the wiring key `ErrorWrapperComponent` from +`cgp::core::error`. It takes no type parameter and accepts any detail type: + +```rust +use cgp::core::error::ErrorWrapperComponent; +use cgp::extra::error::DiscardDetail; + +delegate_components! { + App { + ErrorWrapperComponent: DiscardDetail, + } +} +``` + +Wired this way, any call to `Context::wrap_error(error, detail)` on `App` returns `error` and drops +`detail`, for every detail type. + +## When to reach for it, and when not + +**Reach for `DiscardDetail` when a context's error type cannot hold extra detail, or when a call site +attaches detail that this context has no use for.** It keeps the `CanWrapError` capability satisfiable +without storing anything. + +Reach for [`DebugError`](debug_error.md) or [`DisplayError`](display_error.md) when the detail should be +kept as a formatted string, or for a backend provider when the concrete error type can carry structured +context. + +## Under the hood + +`DiscardDetail` implements `ErrorWrapper` for any context and any detail type: + +```rust +#[cgp_new_provider] +impl ErrorWrapper for DiscardDetail +where + Context: HasErrorType, +{ + fn wrap_error(error: Context::Error, _detail: Detail) -> Context::Error { + error + } +} +``` + +The detail is bound only so the method can accept it; the body returns the error untouched. The +generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same `HasErrorType` bound. + +## Related constructs + +- [`CanWrapError`](../../components/can_raise_error.md) — the component `DiscardDetail` supplies, through + the `ErrorWrapper` provider trait. +- [`DebugError`](debug_error.md), [`DisplayError`](display_error.md) — wrap by keeping the detail as a + formatted string instead of discarding it. +- [`UseDelegate`](../use_delegate.md) — dispatches wrappers per detail type. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — attaching detail as a wiring + decision independent of the error type and its construction. + +## Source + +- [`discard_detail.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-error-extra/src/impls/discard_detail.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md new file mode 100644 index 00000000..128b4725 --- /dev/null +++ b/docs/reference/providers/error/display_error.md @@ -0,0 +1,104 @@ +--- +sidebar_label: 'DisplayError' +sidebar_position: 5 +--- + +# `DisplayError` + +Raise or wrap any `Display` source by formatting it into a `String` and forwarding to the context's own +string handling. + +## Overview + +`DisplayError` is the `Display` counterpart of [`DebugError`](debug_error.md). It implements both error +components by formatting the source error or the detail with the `Display` trait into a `String`, then +forwarding to the **context**'s own `CanRaiseError` or `CanWrapError`, where the context +is the type a capability runs against. It carries the source's user-facing message rather than its debug +representation. Like every CGP provider, `DisplayError` carries no runtime value. + +As with `DebugError`, it does not know the context's error type. It reduces any `Display` source to the +`String` case and leaves the final step to whatever provider the context wires for `String`. + +## Usage + +Import the provider from `cgp::extra::error` and the wiring keys from `cgp::core::error`. `DisplayError` +lives behind the crate's `alloc` feature, because it allocates a `String`. It takes no type parameter: + +```rust +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::{DisplayError, RaiseFrom}; + +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DisplayError, + } +} +``` + +A `String` entry must be present for `DisplayError` to forward to. + +## When to reach for it, and when not + +**Reach for `DisplayError` when a source implements `Display` and you want its user-facing message +carried as a string.** Pair it with a provider on the `String` source, since it forwards rather than +finishes. + +Reach for [`DebugError`](debug_error.md) when you want the source's debug form instead, or when the +source implements `Debug` but not `Display`. Reach for [`RaiseFrom`](raise_from.md) when a real `From` +impl exists, which keeps the source rather than reducing it to a string. + +## Under the hood + +`DisplayError` matches [`DebugError`](debug_error.md) in shape, but formats with `Display` through +`to_string()`: + +```rust +#[cgp_provider] +impl ErrorRaiser for DisplayError +where + Context: CanRaiseError, + E: Display, +{ + fn raise_error(e: E) -> Context::Error { + Context::raise_error(e.to_string()) + } +} + +#[cgp_provider] +impl ErrorWrapper for DisplayError +where + Context: CanWrapError, + Detail: Display, +{ + fn wrap_error(error: Context::Error, detail: Detail) -> Context::Error { + Context::wrap_error(error, detail.to_string()) + } +} +``` + +Both bounds require the context to already handle `String`. Each impl is paired with a matching +[`IsProviderFor`](../../traits/is_provider_for.md) impl. + +## Related constructs + +- [`DebugError`](debug_error.md) — the same provider formatting with `Debug` instead. +- [`CanRaiseError` and `CanWrapError`](../../components/can_raise_error.md) — the components it supplies, + and the `String` forms it forwards to. +- [`RaiseFrom`](raise_from.md) — the usual provider on the `String` source that finishes the raise. +- [`UseDelegate`](../use_delegate.md) — dispatches `DisplayError` for the source types it should format. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — formatting providers as a redirect + onto one concrete string rule. + +## Source + +- [`impls/alloc/display_error.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-error-extra/src/impls/alloc/display_error.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/index.md b/docs/reference/providers/error/index.md new file mode 100644 index 00000000..7f8a0f45 --- /dev/null +++ b/docs/reference/providers/error/index.md @@ -0,0 +1,92 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Error providers + +The zero-sized providers that raise and wrap a context's abstract error, without depending on which +concrete error type the context chose. + +## Overview + +The error providers supply common error-handling strategies to any **context**, the type a capability +runs against. [`CanRaiseError` and `CanWrapError`](../../components/can_raise_error.md) define *what* a +context can do with an error: turn a source error into its abstract `Self::Error`, or attach detail to +one it already holds. They say nothing about *how*. These providers supply the how for the cases that +need no particular error library. Each one is generic over the context, so it works with whatever error +type the context's [`HasErrorType`](../../components/has_error_type.md) names. + +Each provider implements one or both of two provider traits. `CanRaiseError`'s provider trait is +`ErrorRaiser`, wired with `ErrorRaiserComponent`. `CanWrapError`'s provider trait is `ErrorWrapper`, +wired with `ErrorWrapperComponent`. A provider that implements `ErrorRaiser` supplies raising; one that +implements `ErrorWrapper` supplies wrapping; two of them supply both. + +These are the in-tree counterparts to the standalone backends in `cgp-error-anyhow`, `cgp-error-eyre`, +and `cgp-error-std`. Those crates supply providers tied to one concrete error type, such as raising into +an `anyhow::Error`. The providers here stay abstract over the context's error type and capture +strategies that hold for any of them. A context usually wires a mix: a backend for the concrete error +type, plus these generic providers for the cross-cutting strategies. + +## The seven providers, by role + +The seven divide into three groups. + +The **pure raisers** convert a source error into the abstract error: + +- [`RaiseFrom`](raise_from.md) converts a source error through the standard `From` trait. +- [`ReturnError`](return_error.md) handles the case where the source error already *is* the context's + error, so raising is the identity. +- [`RaiseInfallible`](raise_infallible.md) absorbs `core::convert::Infallible`, an error that can never + be constructed. + +The **string-formatting providers** implement both components by formatting through a string: + +- [`DebugError`](debug_error.md) formats the source or detail with the `Debug` trait, then forwards to + the context's own `String` handling. +- [`DisplayError`](display_error.md) does the same with the `Display` trait. + +The remaining two act on the wrapping and raising components directly: + +- [`DiscardDetail`](discard_detail.md) wraps by throwing the detail away and returning the error + unchanged. +- [`PanicOnError`](panic_on_error.md) aborts with the source error's debug output rather than producing + an error value. + +## Wiring them + +A context gains an error strategy by wiring one of these providers to `ErrorRaiserComponent` or +`ErrorWrapperComponent`, exactly like any other component, and the provider's `where` clause decides +when that wiring type-checks. Because both components dispatch on the source-error or detail type, a +context commonly wires several providers at once, one per source error type. The modern form is the +`open` statement of [`delegate_components!`](../../macros/delegate_components.md); the error family is +still defined with [`#[derive_delegate]`](../../attributes/derive_delegate.md), so a nested +[`UseDelegate`](../use_delegate.md) table is the form you will read in existing code. + +## Related constructs + +- [`CanRaiseError` and `CanWrapError`](../../components/can_raise_error.md) — the components these + implement, through the `ErrorRaiser` and `ErrorWrapper` provider traits. +- [`HasErrorType`](../../components/has_error_type.md) — names the abstract `Self::Error` every provider + here produces. +- [`UseDelegate`](../use_delegate.md) — the table that dispatches these providers per source-error type. +- [`delegate_components!`](../../macros/delegate_components.md) and + [`check_components!`](../../macros/check_components.md) — wire and verify them. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — how the abstract error type, the + raise and wrap capabilities, and these strategies fit together as interchangeable wiring decisions. + +## Source + +- The providers are in `cgp-error-extra`: + [`impls/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-error-extra/src/impls). +- The `ErrorRaiser` and `ErrorWrapper` provider traits and the consumer traits they build on are in + [`cgp-error`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-error/src). +- The concrete backends are in + [`crates/standalone/error/`](https://github.com/contextgeneric/cgp/tree/main/crates/standalone/error). + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/panic_on_error.md b/docs/reference/providers/error/panic_on_error.md new file mode 100644 index 00000000..e3b84488 --- /dev/null +++ b/docs/reference/providers/error/panic_on_error.md @@ -0,0 +1,85 @@ +--- +sidebar_label: 'PanicOnError' +sidebar_position: 7 +--- + +# `PanicOnError` + +Abort with the source error's debug output instead of producing an abstract error value. + +## Overview + +`PanicOnError` is the `ErrorRaiser` provider that panics rather than returning an error. When a +**context**, the type a capability runs against, treats an error as a programming fault that should stop +the program, `PanicOnError` raises by calling `panic!` with the source error's debug representation. Its +signature promises to return the abstract error, but the body never does, because `panic!` diverges. +This suits tests and fail-fast tooling. Like every CGP provider, `PanicOnError` carries no runtime value. + +## Usage + +Import the provider from `cgp::extra::error` and the wiring key `ErrorRaiserComponent` from +`cgp::core::error`. It takes no type parameter and accepts any `Debug` source: + +```rust +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::PanicOnError; + +delegate_components! { + TestApp { + ErrorRaiserComponent: PanicOnError, + } +} +``` + +Any call to `Context::raise_error(source)` on `TestApp` panics with `format!("{source:?}")` rather than +returning. + +## When to reach for it, and when not + +**Reach for `PanicOnError` where an error means a bug that should abort rather than be handled**, such as +a test harness or a fail-fast tool. It removes the need to give the context a real error type or a +handling strategy. + +Do not wire it in production code that should recover from errors. Use [`RaiseFrom`](raise_from.md) or a +backend provider there, so a raised error becomes a value the caller can handle. + +## Under the hood + +`PanicOnError` implements `ErrorRaiser` for any `Debug` source over any context with an +error type: + +```rust +#[cgp_new_provider] +impl ErrorRaiser for PanicOnError +where + Context: HasErrorType, + E: Debug, +{ + fn raise_error(e: E) -> Context::Error { + panic!("{e:?}") + } +} +``` + +The return type is `Context::Error`, but `panic!` diverges, so the body never produces one. The +generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same bounds. + +## Related constructs + +- [`CanRaiseError`](../../components/can_raise_error.md) — the component `PanicOnError` supplies. +- [`RaiseFrom`](raise_from.md), [`ReturnError`](return_error.md) — the raisers to use when an error + should become a value rather than abort. +- [`UseDelegate`](../use_delegate.md) — dispatches raisers per source-error type. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — the raising strategy as a wiring + decision, here choosing to abort. + +## Source + +- [`panic_error.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-error-extra/src/impls/panic_error.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/raise_from.md b/docs/reference/providers/error/raise_from.md new file mode 100644 index 00000000..5fb9ad59 --- /dev/null +++ b/docs/reference/providers/error/raise_from.md @@ -0,0 +1,114 @@ +--- +sidebar_label: 'RaiseFrom' +sidebar_position: 1 +--- + +# `RaiseFrom` + +Raise a source error by converting it into the context's error type through the standard `From` trait. + +## Overview + +`RaiseFrom` is the `ErrorRaiser` provider for the common case: the **context**, the type a capability +runs against, already knows how to build its abstract `Error` from the source error through `From`. +Wiring it means "convert every source error the abstract error has a `From` impl for". It is the default +choice whenever that `From` impl exists, which covers most error raising in practice. + +Because the bound is on the abstract error rather than on one source type, a single wiring of `RaiseFrom` +covers every source error the context's error can absorb. Like every CGP provider, `RaiseFrom` carries +no runtime value. + +## Usage + +Import the provider from `cgp::extra::error` and the wiring key `ErrorRaiserComponent` from +`cgp::core::error`. It takes no type parameter: + +```rust +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::RaiseFrom; + +delegate_components! { + App { + ErrorRaiserComponent: RaiseFrom, + } +} +``` + +Wired this way, any provider that calls `Context::raise_error(source)` on `App` succeeds for every +`source` whose type the `App` error implements `From` for. + +## Examples + +`RaiseFrom` is most often one entry in a per-source dispatch table, alongside the formatting providers +for the source types the error cannot absorb directly. Here a raised `String` is converted straight +into the abstract error, while a `ParseIntError` is formatted first: + +```rust +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::{DebugError, RaiseFrom}; + +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } +} +``` + +[`DebugError`](debug_error.md) formats the `ParseIntError` into a `String` and forwards it back through the +`String` entry, which `RaiseFrom` handles. + +## When to reach for it, and when not + +**Reach for `RaiseFrom` whenever the abstract error already has a `From` impl for the source.** It is the +plainest raiser and the one to try first. + +Reach for [`ReturnError`](return_error.md) instead when the source *is* the abstract error, for +[`RaiseInfallible`](raise_infallible.md) when the source is `Infallible`, and for +[`DebugError`](debug_error.md) or [`DisplayError`](display_error.md) when no `From` impl exists but the +source is printable and the context handles `String` errors. + +## Under the hood + +`RaiseFrom` implements `ErrorRaiser` for any context whose abstract `Error` is `From`: + +```rust +#[cgp_new_provider] +impl ErrorRaiser for RaiseFrom +where + Context: HasErrorType, + Context::Error: From, +{ + fn raise_error(e: E) -> Context::Error { + e.into() + } +} +``` + +The bound `Context::Error: From` is what makes one wiring cover many source types. The generated +[`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same clause, so a +[check](../../macros/check_components.md) reports a missing `From` impl at the wiring site. + +## Related constructs + +- [`CanRaiseError`](../../components/can_raise_error.md) — the component `RaiseFrom` supplies, through + the `ErrorRaiser` provider trait. +- [`ReturnError`](return_error.md), [`RaiseInfallible`](raise_infallible.md) — the other pure raisers. +- [`DebugError`](debug_error.md), [`DisplayError`](display_error.md) — format a non-convertible source + into a `String` that `RaiseFrom` can then convert. +- [`UseDelegate`](../use_delegate.md) — dispatches `RaiseFrom` per source-error type. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — the error type and its construction + as separate wiring decisions. + +## Source + +- [`raise_from.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-error-extra/src/impls/raise_from.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/raise_infallible.md b/docs/reference/providers/error/raise_infallible.md new file mode 100644 index 00000000..66841720 --- /dev/null +++ b/docs/reference/providers/error/raise_infallible.md @@ -0,0 +1,89 @@ +--- +sidebar_label: 'RaiseInfallible' +sidebar_position: 3 +--- + +# `RaiseInfallible` + +Absorb `core::convert::Infallible`, the error type that can never be constructed. + +## Overview + +`RaiseInfallible` is the `ErrorRaiser` provider for `core::convert::Infallible`, an error type with no +values. It lets generic code that is parameterized over a fallible operation be wired uniformly on a +**context**, the type a capability runs against, even when the operation chosen for that context cannot +fail. Because an `Infallible` value cannot exist, the raising method is never actually called at +runtime. Like every CGP provider, `RaiseInfallible` carries no runtime value. + +## Usage + +Import the provider from `cgp::extra::error` and the wiring key `ErrorRaiserComponent` from +`cgp::core::error`. It takes no type parameter and accepts only `Infallible` as the source: + +```rust +use core::convert::Infallible; +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::{RaiseFrom, RaiseInfallible}; + +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.Infallible: RaiseInfallible, + @ErrorRaiserComponent.String: RaiseFrom, + } +} +``` + +The `Infallible` entry satisfies the raiser bound for a step that cannot fail, while other entries handle +the source types that can. + +## When to reach for it, and when not + +**Reach for `RaiseInfallible` when generic code must raise an `Infallible` on a context, even though the +value can never occur.** This happens when a component is generic over an operation and one wiring of it +picks an operation that never errors, so the raiser slot for `Infallible` still has to be filled. + +For any other source type, use one of the other raisers: [`RaiseFrom`](raise_from.md), +[`ReturnError`](return_error.md), [`DebugError`](debug_error.md), or [`DisplayError`](display_error.md). + +## Under the hood + +`RaiseInfallible` implements `ErrorRaiser` for any context with an error type, +producing the abstract error by matching on the uninhabited value: + +```rust +#[cgp_new_provider] +impl ErrorRaiser for RaiseInfallible +where + Context: HasErrorType, +{ + fn raise_error(e: Infallible) -> Context::Error { + match e {} + } +} +``` + +Because an `Infallible` value cannot be constructed, the empty `match` is total and the function has no +reachable body. The generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same +`HasErrorType` bound. + +## Related constructs + +- [`CanRaiseError`](../../components/can_raise_error.md) — the component `RaiseInfallible` supplies. +- [`RaiseFrom`](raise_from.md), [`ReturnError`](return_error.md) — the other pure raisers. +- [`UseDelegate`](../use_delegate.md) — dispatches raisers per source-error type, which is where the + `Infallible` entry sits. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — raising a source into the abstract + error type as a wiring decision. + +## Source + +- [`infallible.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-error-extra/src/impls/infallible.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md new file mode 100644 index 00000000..a05422bb --- /dev/null +++ b/docs/reference/providers/error/return_error.md @@ -0,0 +1,103 @@ +--- +sidebar_label: 'ReturnError' +sidebar_position: 2 +--- + +# `ReturnError` + +Raise a source error that already is the context's abstract error, so raising is the identity. + +## Overview + +`ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly the abstract +error the **context** chose, where the context is the type a capability runs against. Raising then has +nothing to convert: it returns its argument untouched. This is what a context uses when generic code +raises a value that is already of the context's own error type. Like every CGP provider, `ReturnError` +carries no runtime value. + +## Usage + +Import the provider from `cgp::extra::error` and the wiring key `ErrorRaiserComponent` from +`cgp::core::error`. It takes no type parameter, and it type-checks only for the one source type that +equals the context's `Error`: + +```rust +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::ReturnError; + +delegate_components! { + App { + ErrorRaiserComponent: ReturnError, + } +} +``` + +## Examples + +`ReturnError` most often sits in a per-source table as the entry for the context's own error type, +beside other raisers for the foreign types. If `App` chose `AppError` as its error, this entry raises an +`AppError` source by returning it and converts other sources elsewhere: + +```rust +use cgp::core::error::ErrorRaiserComponent; +use cgp::extra::error::{DebugError, RaiseFrom, ReturnError}; + +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.AppError: ReturnError, + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } +} +``` + +## When to reach for it, and when not + +**Reach for `ReturnError` when generic code raises a value that is already the context's error type.** A +`From for AppError` impl exists in the standard library, so [`RaiseFrom`](raise_from.md) would +also work here; `ReturnError` states the intent directly and needs no `From` bound. + +For a source the error can absorb through `From`, use [`RaiseFrom`](raise_from.md). For a printable +source with no `From` impl, use [`DebugError`](debug_error.md) or [`DisplayError`](display_error.md). + +## Under the hood + +`ReturnError` implements `ErrorRaiser` only when the context's `Error` is exactly `E`: + +```rust +#[cgp_new_provider] +impl ErrorRaiser for ReturnError +where + Context: HasErrorType, +{ + fn raise_error(e: E) -> E { + e + } +} +``` + +The `HasErrorType` bound ties the source type to the abstract error, so `raise_error` returns +its argument. The generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same +bound. + +## Related constructs + +- [`CanRaiseError`](../../components/can_raise_error.md) — the component `ReturnError` supplies. +- [`RaiseFrom`](raise_from.md) — converts through `From` rather than requiring an exact match. +- [`RaiseInfallible`](raise_infallible.md) — the raiser for `Infallible`. +- [`UseDelegate`](../use_delegate.md) — dispatches `ReturnError` per source-error type. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — the error type and its construction + as separate wiring decisions. + +## Source + +- [`return_error.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-error-extra/src/impls/return_error.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error_providers.md b/docs/reference/providers/error_providers.md deleted file mode 100644 index 3429e0b1..00000000 --- a/docs/reference/providers/error_providers.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -sidebar_label: 'Error providers' -sidebar_position: 12 ---- - -# Error providers - -`RaiseFrom`, `ReturnError`, `DebugError`, and the other backends behind the error components. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/docs/reference/providers/handler/_category_.json b/docs/reference/providers/handler/_category_.json new file mode 100644 index 00000000..e7c9b3a4 --- /dev/null +++ b/docs/reference/providers/handler/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Handler combinators", + "position": 13, + "link": { + "type": "doc", + "id": "reference/providers/handler/index" + } +} diff --git a/docs/reference/providers/handler/compose_handlers.md b/docs/reference/providers/handler/compose_handlers.md new file mode 100644 index 00000000..162e6028 --- /dev/null +++ b/docs/reference/providers/handler/compose_handlers.md @@ -0,0 +1,115 @@ +--- +sidebar_label: 'ComposeHandlers' +sidebar_position: 1 +--- + +# `ComposeHandlers` + +Run two handlers back to back, feeding the output of the first as the input of the second. + +## Overview + +`ComposeHandlers` is the fundamental sequencing combinator. It runs `ProviderA`, +then runs `ProviderB` on `ProviderA`'s output, under one **context**, the type a capability runs +against, and one `Code` tag. It implements every member of the handler family by threading the +intermediary value through both providers. Only the value flowing between them changes type. Like every +CGP provider, it carries no runtime value; the two inner providers ride in `PhantomData`. + +## Usage + +Import it from `cgp::extra::handler`. It takes two provider type parameters, the first handler and the +second: + +```rust +use cgp::extra::handler::ComposeHandlers; + +delegate_components! { + App { + ComputerComponent: ComposeHandlers, + } +} +``` + +The second provider's input type is pinned to the first's output type, so the two must line up: +`ProviderB` computes over `ProviderA::Output`, and the composite output is `ProviderB::Output`. + +For composing more than two handlers, reach for [`PipeHandlers`](pipe_handlers.md), which takes a list +and folds it into nested `ComposeHandlers`. + +## Examples + +`ComposeHandlers` chains two field-reading computers over a context. Given a `Double` computer and an +`AddOne` computer, both over `u64`: + +```rust +use cgp::extra::handler::{CanCompute, ComposeHandlers}; + +delegate_components! { + App { + ComputerComponent: ComposeHandlers, + } +} +``` + +Computing over an input of `5` runs `Double` first, then `AddOne` on its output, giving `(5 * 2) + 1`. +The same composite serves as a `TryComputer`, `AsyncComputer`, or `Handler` if both stages support that +shape. + +## When to reach for it, and when not + +**Reach for `ComposeHandlers` to sequence exactly two handlers.** For three or more, use +[`PipeHandlers`](pipe_handlers.md), which reads better as a list and folds to the same nested +composition. For a step that should short-circuit on a `Result` branch rather than always run the next +stage, use the [monad providers](../monad/pipe_monadic.md) instead. + +## Under the hood + +`ComposeHandlers` carries the two inner providers in `PhantomData`: + +```rust +pub struct ComposeHandlers(pub PhantomData<(ProviderA, ProviderB)>); +``` + +Its `Computer` impl requires `ProviderA: Computer` and +`ProviderB: Computer`, and sets the composite `Output` to +`ProviderB::Output`: + +```rust +impl Computer + for ComposeHandlers +where + ProviderA: Computer, + ProviderB: Computer, +{ + type Output = ProviderB::Output; + + fn compute(context: &Context, code: PhantomData, input: Input) -> Self::Output { + let intermediary = ProviderA::compute(context, code, input); + ProviderB::compute(context, code, intermediary) + } +} +``` + +The same shape is implemented for `TryComputer`, `AsyncComputer`, and `Handler`. The fallible variants +use `?` to short-circuit on the first provider's error, so they require the context to have an error +type; the async variants `.await` each step. + +## Related constructs + +- [`PipeHandlers`](pipe_handlers.md) — generalizes this to a list, folding to nested `ComposeHandlers`. +- [`ReturnInput`](return_input.md) — the identity that composes with any handler without changing it. +- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family it + implements. +- [`PipeMonadic`](../monad/pipe_monadic.md) — composition that short-circuits through a monad. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family these combinators build. + +## Source + +- [`providers/compose.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/compose.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md new file mode 100644 index 00000000..c3a571b3 --- /dev/null +++ b/docs/reference/providers/handler/index.md @@ -0,0 +1,95 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Handler combinators + +The providers that build, sequence, and adapt handlers: composing them end to end, threading a list +through a pipeline, returning the input unchanged, and lifting one handler shape into another. + +## Overview + +The handler combinators exist because the handler family is not one trait but several related ones, and +code is rarely written against all of them at once. A provider author writes a plain synchronous +[`Computer`](../../components/computer.md), a fallible [`TryComputer`](../../components/try_computer.md), +or an async [`Handler`](../../components/handler.md), depending on the computation. The combinators let +those single-shape providers be wired where a different shape is expected, and let several providers be +glued into a larger one, on a **context**, the type a capability runs against. Like every CGP provider, +each combinator is zero-sized: its type parameters are inner providers carried in `PhantomData`. + +## The handler family + +Every combinator is defined in terms of the handler component traits, so a short orientation helps. The +family shares one method signature: a context reference, a `PhantomData` tag selecting the +operation, and an input, producing an associated `Output`. The members differ on two axes. + +- [`Computer`](../../components/computer.md) is synchronous and infallible. +- [`TryComputer`](../../components/try_computer.md) is synchronous and fallible, and requires the context + to have an error type. +- `AsyncComputer` is asynchronous and infallible. +- [`Handler`](../../components/handler.md) is asynchronous and fallible, the most general member. +- [`Producer`](../../components/producer.md) takes no input. + +Each of the first four has a `…Ref` companion whose method takes the input by reference. The promotion +combinators trade on the natural orderings among these: a `Computer` is also a valid `TryComputer` and a +valid `AsyncComputer`, a `TryComputer` is a valid `Handler`, and a value handler can serve a reference +handler by dereferencing. + +## The combinators, by role + +**Composition** feeds one handler's output into the next: + +- [`ComposeHandlers`](compose_handlers.md) runs two handlers back to back. +- [`PipeHandlers`](pipe_handlers.md) generalizes that to a type-level list of handlers. + +**Identity** is the neutral element of composition: + +- [`ReturnInput`](return_input.md) passes its input straight through. + +**Promotion** lifts one handler shape into another, so one written implementation satisfies several +traits: + +- [`Promote`](promote.md) lifts along the infallible-to-fallible and sync-to-async axes. +- [`PromoteAsync`](promote_async.md) lifts a synchronous provider into an asynchronous one. +- [`PromoteRef`](promote_ref.md) bridges value handlers and reference handlers by dereferencing. +- [`TryPromote`](try_promote.md) bridges a `Result`-valued output and a fallible trait. + +**Promotion bundles** wire a whole cluster of handler components to the right single-step promotion at +once, so a provider author implements one trait and gets the rest of the family. These are what +[`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md) +wire automatically: + +- [`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), + [`PromoteProducer`](promote_producer.md), [`PromoteAsyncComputer`](promote_async_computer.md), and + [`PromoteHandler`](promote_handler.md), one per base trait. + +**Input dispatch** chooses a handler by the type of the value: + +- [`UseInputDelegate`](use_input_delegate.md) keys a lookup table on the handler's `Input` type. + +## Related constructs + +- [`Computer`](../../components/computer.md), [`TryComputer`](../../components/try_computer.md), + [`Handler`](../../components/handler.md), [`Producer`](../../components/producer.md) — the components + these providers implement. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md) + — generate a single-trait provider and wire the rest of the family through the promotion bundles. +- [`Product!`](../../macros/product.md) — the type-level list `PipeHandlers` composes. +- [`UseDelegate`](../use_delegate.md) — the `Code`-keyed sibling of `UseInputDelegate`. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. + +## Source + +- The combinators are in `cgp-handler` under + [`providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/providers), + and `UseInputDelegate` in + [`types.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/types.rs). + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/pipe_handlers.md b/docs/reference/providers/handler/pipe_handlers.md new file mode 100644 index 00000000..d2c9c274 --- /dev/null +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -0,0 +1,129 @@ +--- +sidebar_label: 'PipeHandlers' +sidebar_position: 2 +--- + +# `PipeHandlers` + +Compose a type-level list of handlers into a single pipeline, threading each stage's output into the +next. + +## Overview + +`PipeHandlers` generalizes [`ComposeHandlers`](compose_handlers.md) from two handlers to a +list of them. It takes a [`Product!`](../../macros/product.md) list of providers and folds the whole +pipeline into one nested `ComposeHandlers`, so the input flows through each stage in turn, on one +**context**, the type a capability runs against. It is the combinator to reach for when wiring a +multi-stage transformation: list the stages in order and let `PipeHandlers` build the composition. Like +every CGP provider, it carries no runtime value; the list rides in `PhantomData`. + +## Usage + +Import it from `cgp::extra::handler`. It takes one type parameter, a `Product!` list of handler +providers: + +```rust +use cgp::extra::handler::{CanCompute, PipeHandlers}; + +delegate_components! { + App { + ComputerComponent: + PipeHandlers, + } +} +``` + +The list runs left to right: `ParseInput`, then `Validate` on its output, then `Normalize`. Each +stage's output type must match the next stage's input type. Because the fold is generic over the +component, one list serves as a `Computer`, `TryComputer`, `AsyncComputer`, or `Handler`, whichever the +wiring asks for, as long as every stage supports that shape. + +## Examples + +A pipeline of field-reading computers over a context. Suppose `Multiply` and `Add` are +`Computer` providers over `u64` that read a factor or an addend from a context field: + +```rust +use cgp::prelude::*; +use cgp::extra::handler::{CanCompute, PipeHandlers}; + +#[derive(HasField)] +pub struct MyContext { + pub foo: u64, + pub bar: u64, + pub baz: u64, +} + +delegate_components! { + MyContext { + ComputerComponent: + PipeHandlers, + Add, + Multiply, + ]>, + } +} +``` + +Wiring `ComputerComponent` to this list composes the three into +`ComposeHandlers, ComposeHandlers, Multiply<…>>>`. Computing over an input of `5` on +a context with `foo = 2`, `bar = 3`, `baz = 4` gives `((5 * 2) + 3) * 4`. Stages of mismatched shapes +can be reconciled inline, as in `PromoteAsync>>`, which lifts a plain +`Computer` stage up to the async `Handler` shape a pipeline expects. + +## When to reach for it, and when not + +**Reach for `PipeHandlers` to compose three or more handlers**, or any time a list reads better than +nesting [`ComposeHandlers`](compose_handlers.md) by hand. For exactly two, `ComposeHandlers` is the +plainer choice. + +For a pipeline where a step should short-circuit on a `Result` branch rather than always feed the next +stage, use [`PipeMonadic`](../monad/pipe_monadic.md), the monadic generalization that +`PipeHandlers` reduces to. + +## Under the hood + +`PipeHandlers` carries the list in `PhantomData` and holds no handler impls of its own: + +```rust +pub struct PipeHandlers(pub PhantomData); +``` + +Instead it delegates every handler component to whatever single provider the list folds down to, +computed by an internal `ComposeProviders` trait that walks the `Cons`/`Nil` list. A one-element list +folds to that provider unchanged; a list `Cons` folds to +`ComposeHandlers`: + +```rust +delegate_components! { + > + PipeHandlers { + Component: Provider, + } +} +``` + +Because the delegation is generic over the `Component` key, the same pipeline answers whichever handler +shape the wiring asks for. + +## Related constructs + +- [`ComposeHandlers`](compose_handlers.md) — the two-handler combinator this folds a list into. +- [`ReturnInput`](return_input.md) — the identity stage, the neutral element of the fold. +- [`Product!`](../../macros/product.md) — the type-level list of stages. +- [`PipeMonadic`](../monad/pipe_monadic.md) — the monadic pipeline that adds short-circuiting. +- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family a + pipeline implements. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its composition. + +## Source + +- [`providers/pipe.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/pipe.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote.md b/docs/reference/providers/handler/promote.md new file mode 100644 index 00000000..b57c4875 --- /dev/null +++ b/docs/reference/providers/handler/promote.md @@ -0,0 +1,94 @@ +--- +sidebar_label: 'Promote' +sidebar_position: 4 +--- + +# `Promote` + +Lift a handler upward along the infallible-to-fallible and sync-to-async axes, without adding behavior +of its own. + +:::info + +### Generated machinery + +**You are not expected to name `Promote` directly.** The promotion bundle +[`PromoteComputer`](promote_computer.md) and the others wire it into the right handler slots, and those +bundles are what [`#[cgp_computer]`](../../macros/cgp_computer.md) and +[`#[cgp_producer]`](../../macros/cgp_producer.md) generate. You reach for it by hand only when wiring the +handler family one slot at a time. This page explains what that wiring emits. + +::: + +## Overview + +`Promote` re-exposes one inner provider under a more capable member of the handler family, +treating a less capable provider as a more capable one without introducing error or async behavior +itself. The **context**, the type a capability runs against, sees the promoted shape while the inner +provider does the same work. Like every CGP provider, it carries no runtime value; the inner provider +rides in `PhantomData`. + +## Usage + +Import it from `cgp::extra::handler`. It takes one type parameter, the inner provider: + +```rust +use cgp::extra::handler::Promote; + +// Fill a TryComputer slot from a plain Computer, wrapping its result in Ok. +delegate_components! { + App { + TryComputerComponent: Promote, + } +} +``` + +## When to reach for it, and when not + +**You rarely reach for `Promote` by hand.** A provider written with +[`#[cgp_computer]`](../../macros/cgp_computer.md) or [`#[cgp_producer]`](../../macros/cgp_producer.md) +gets the right lifts wired through a bundle such as [`PromoteComputer`](promote_computer.md), so the +whole family is filled in for you. Name `Promote` yourself only when you wire the family one slot at a +time and a slot needs exactly this lift: a producer filling a computer slot, or an infallible result +wrapped in `Ok`. For the sync-to-async lift use [`PromoteAsync`](promote_async.md), for the borrow lift +[`PromoteRef`](promote_ref.md), and for the `Result` bridge [`TryPromote`](try_promote.md). + +## Under the hood + +`Promote` carries the inner provider in `PhantomData` and gives three impls: + +```rust +pub struct Promote(pub PhantomData); +``` + +- As a `Computer`, it requires the inner `Provider: Producer` and ignores its own input, + calling `Provider::produce`. This adapts a producer, which takes no input, to fill a computer slot + that is handed an input it does not need. +- As a `TryComputer`, it requires `Provider: Computer` and wraps the infallible result in `Ok`. +- As a `Handler`, it requires `Provider: AsyncComputer` and wraps the awaited result in `Ok`. + +Each promotion adds the missing capability, either discarding an input or introducing an always-`Ok` +result, without changing what the inner provider computes. + +## Related constructs + +- [`PromoteAsync`](promote_async.md), [`PromoteRef`](promote_ref.md), [`TryPromote`](try_promote.md) — + the other single-step lifts, along different axes. +- [`PromoteComputer`](promote_computer.md) and the other bundles — wire `Promote` into the family + automatically. +- [`#[cgp_computer]`](../../macros/cgp_computer.md), [`#[cgp_producer]`](../../macros/cgp_producer.md) — + generate providers that the bundles promote. +- [`Producer`](../../components/producer.md), [`Computer`](../../components/computer.md), + [`Handler`](../../components/handler.md) — the family members it lifts between. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family and the orderings the promotions trade on. + +## Source + +- [`providers/promote.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_async.md b/docs/reference/providers/handler/promote_async.md new file mode 100644 index 00000000..bf4b5f83 --- /dev/null +++ b/docs/reference/providers/handler/promote_async.md @@ -0,0 +1,83 @@ +--- +sidebar_label: 'PromoteAsync' +sidebar_position: 5 +--- + +# `PromoteAsync` + +Lift a synchronous handler into an asynchronous one. + +:::info + +### Generated machinery + +**You are not expected to name `PromoteAsync` directly.** The promotion bundle +[`PromoteComputer`](promote_computer.md) wires it into the async slots, and the bundles are what +[`#[cgp_computer]`](../../macros/cgp_computer.md) generates. You reach for it by hand only when wiring +the handler family one slot at a time. This page explains what that wiring emits. + +::: + +## Overview + +`PromoteAsync` runs a synchronous inner provider inside an async method, so a synchronous +handler serves an asynchronous slot on a **context**, the type a capability runs against. The returned +future is ready immediately, so no actual asynchrony is added. Like every CGP provider, it carries no +runtime value; the inner provider rides in `PhantomData`. + +## Usage + +Import it from `cgp::extra::handler`. It takes one type parameter, the inner provider: + +```rust +use cgp::extra::handler::PromoteAsync; + +// Serve an AsyncComputer slot from a synchronous Computer. +delegate_components! { + App { + AsyncComputerComponent: PromoteAsync, + } +} +``` + +## When to reach for it, and when not + +**You rarely reach for `PromoteAsync` by hand.** The [`PromoteComputer`](promote_computer.md) bundle +wires it into the async slots, so a synchronous provider serves the async family without you naming it. +Reach for it directly only when wiring a slot by hand and that slot needs a synchronous provider run in +an async method. For the infallible-to-fallible or producer lift use [`Promote`](promote.md), and for +the borrow lift [`PromoteRef`](promote_ref.md). + +## Under the hood + +`PromoteAsync` carries the inner provider in `PhantomData`: + +```rust +pub struct PromoteAsync(pub PhantomData); +``` + +- As an `AsyncComputer`, it requires `Provider: Computer` and runs it synchronously inside the async + method, returning a future that is already ready. +- As a `Handler`, it requires `Provider: TryComputer` and returns that fallible synchronous result, so + a synchronous fallible computer becomes an async fallible handler. + +## Related constructs + +- [`Promote`](promote.md), [`PromoteRef`](promote_ref.md), [`TryPromote`](try_promote.md) — the other + single-step lifts. +- [`PromoteComputer`](promote_computer.md) and the other bundles — wire `PromoteAsync` into the family + automatically. +- [`Computer`](../../components/computer.md), [`TryComputer`](../../components/try_computer.md), + [`Handler`](../../components/handler.md) — the family members it lifts between. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family and the sync-to-async ordering this lift trades on. + +## Source + +- [`providers/promote_async.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_async.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md new file mode 100644 index 00000000..24894d90 --- /dev/null +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -0,0 +1,74 @@ +--- +sidebar_label: 'PromoteAsyncComputer' +sidebar_position: 11 +--- + +# `PromoteAsyncComputer` + +Fill in the handler family from a provider that implements `AsyncComputer`. + +:::info + +### Generated machinery + +**You are not expected to name `PromoteAsyncComputer` directly.** It is wired for a generated provider +whose base is the asynchronous infallible computer. You name it by hand only when wiring a hand-written +`AsyncComputer`'s family explicitly. This page explains what that wiring emits. + +::: + +## Overview + +`PromoteAsyncComputer` starts from a provider that implements `AsyncComputer`, the +asynchronous infallible base, and fills in the rest of the handler family on a **context**, the type a +capability runs against. It is the async-base counterpart of [`PromoteComputer`](promote_computer.md). +Like every CGP provider, it carries no runtime value. + +## Usage + +It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base +`AsyncComputer` provider. `PromoteAsyncComputer` answers `HandlerComponent` and the async-ref members +but not `AsyncComputerComponent`, so the base is wired to `AsyncComputerComponent` directly and the +bundle fills in the rest: + +```rust +delegate_components! { + App { + AsyncComputerComponent: Double, + HandlerComponent: PromoteAsyncComputer, + } +} +``` + +## When to reach for it, and when not + +**Reach for `PromoteAsyncComputer` when the base is an infallible async `AsyncComputer`** and you wire +its family by hand. For a synchronous base use [`PromoteComputer`](promote_computer.md), and for a +fallible async `Handler` base use [`PromoteHandler`](promote_handler.md). + +## Under the hood + +`PromoteAsyncComputer` is a [`delegate_components!`](../../macros/delegate_components.md) table over a +generic inner `Provider`. It routes `HandlerComponent` to [`Promote`](promote.md), which wraps the +awaited value in `Ok`, and routes `AsyncComputerRefComponent` and `HandlerRefComponent` to +[`PromoteRef`](promote_ref.md). + +## Related constructs + +- [`PromoteComputer`](promote_computer.md) — the synchronous-base counterpart. +- [`PromoteHandler`](promote_handler.md) — defers its async-ref components here. +- [`Promote`](promote.md), [`PromoteRef`](promote_ref.md) — the lifts this table wires. +- [`Handler`](../../components/handler.md), [`Computer`](../../components/computer.md) — the family it + fills in. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family and its sync-to-async ordering. + +## Source + +- [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md new file mode 100644 index 00000000..83bc99b6 --- /dev/null +++ b/docs/reference/providers/handler/promote_computer.md @@ -0,0 +1,105 @@ +--- +sidebar_label: 'PromoteComputer' +sidebar_position: 8 +--- + +# `PromoteComputer` + +Fill in every member of the handler family from a provider that implements `Computer`. + +:::info + +### Generated machinery + +**You are not expected to name `PromoteComputer` directly.** +[`#[cgp_computer]`](../../macros/cgp_computer.md) wires it across the family for the provider it +generates, so one written `Computer` impl answers the whole handler surface. You name +`PromoteComputer` by hand only when wiring a hand-written computer's family explicitly. This +page explains what that wiring emits. + +::: + +## Overview + +`PromoteComputer` starts from a provider that implements `Computer`, the by-value synchronous +infallible base, and fills in every other member of the handler family by promotion, on a **context**, +the type a capability runs against. It is a delegation table that routes each remaining handler +component to the right single-step promotion. Like every CGP provider, it carries no runtime value. + +## Usage + +It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base +`Computer` provider. `PromoteComputer` answers every family member *except* `ComputerComponent`, so the +base is wired to `ComputerComponent` directly and the bundle fills in the rest: + +```rust +delegate_components! { + App { + ComputerComponent: Double, + [ + TryComputerComponent, + AsyncComputerComponent, + HandlerComponent, + ]: PromoteComputer, + } +} +``` + +Most code gets this wiring from [`#[cgp_computer]`](../../macros/cgp_computer.md) rather than writing it. + +## When to reach for it, and when not + +**Reach for `PromoteComputer` when you wire a hand-written `Computer` provider's family explicitly** +rather than through [`#[cgp_computer]`](../../macros/cgp_computer.md), which wires it for you. Use a +different bundle when the base is a different trait: [`PromoteTryComputer`](promote_try_computer.md) +from a `TryComputer`, [`PromoteProducer`](promote_producer.md) from a `Producer`, +[`PromoteAsyncComputer`](promote_async_computer.md) from an `AsyncComputer`, and +[`PromoteHandler`](promote_handler.md) from a `Handler`. + +## Under the hood + +`PromoteComputer` is defined with [`delegate_components!`](../../macros/delegate_components.md) over a +generic inner `Provider`. It routes the fallible slot to [`Promote`](promote.md) (wrap in `Ok`), the +async slots to [`PromoteAsync`](promote_async.md) (run synchronously in an async method), and every +`…Ref` slot to [`PromoteRef`](promote_ref.md) (dereference, then defer to the base): + +```rust +delegate_components! { + + new PromoteComputer { + ComputerRefComponent: PromoteRef, + TryComputerComponent: Promote, + TryComputerRefComponent: PromoteRef, + AsyncComputerComponent: PromoteAsync, + AsyncComputerRefComponent: PromoteRef, + HandlerComponent: PromoteAsync, + HandlerRefComponent: PromoteRef, + } +} +``` + +The base `ComputerComponent` is the inner provider itself; the table fills in the other seven. + +## Related constructs + +- [`#[cgp_computer]`](../../macros/cgp_computer.md) — generates a `Computer` provider and wires + `PromoteComputer` across the family. +- [`PromoteTryComputer`](promote_try_computer.md), [`PromoteProducer`](promote_producer.md), + [`PromoteAsyncComputer`](promote_async_computer.md), [`PromoteHandler`](promote_handler.md) — the + bundles for the other base traits. +- [`Promote`](promote.md), [`PromoteAsync`](promote_async.md), [`PromoteRef`](promote_ref.md) — the + single-step lifts this table wires. +- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family it + fills in. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family and why one written trait can answer all of it. + +## Source + +- [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_handler.md b/docs/reference/providers/handler/promote_handler.md new file mode 100644 index 00000000..3c76a991 --- /dev/null +++ b/docs/reference/providers/handler/promote_handler.md @@ -0,0 +1,72 @@ +--- +sidebar_label: 'PromoteHandler' +sidebar_position: 12 +--- + +# `PromoteHandler` + +Fill in the handler family from a provider that implements `Handler`, the most general base. + +:::info + +### Generated machinery + +**You are not expected to name `PromoteHandler` directly.** It is wired for a generated provider whose +base is the async fallible handler. You name it by hand only when wiring a hand-written `Handler`'s +family explicitly. This page explains what that wiring emits. + +::: + +## Overview + +`PromoteHandler` starts from the most general base, a provider that implements +[`Handler`](../../components/handler.md), and fills in the rest of the family on a **context**, the +type a capability runs against. Like every CGP provider, it carries no runtime value. + +## Usage + +It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base +`Handler` provider: + +```rust +delegate_components! { + App { + [HandlerComponent, HandlerRefComponent]: PromoteHandler, + } +} +``` + +## When to reach for it, and when not + +**Reach for `PromoteHandler` when the base is the fully general async fallible `Handler`** and you wire +its family by hand. For a less capable base, use the bundle that matches it: +[`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), +[`PromoteProducer`](promote_producer.md), or [`PromoteAsyncComputer`](promote_async_computer.md). + +## Under the hood + +`PromoteHandler` is a [`delegate_components!`](../../macros/delegate_components.md) table over a generic +inner `Provider`. It routes `HandlerComponent` to [`TryPromote`](try_promote.md), which exposes the +handler as an async computer returning an explicit `Result`, and defers the async-ref components to +[`PromoteAsyncComputer`](promote_async_computer.md). + +## Related constructs + +- [`PromoteAsyncComputer`](promote_async_computer.md) — the bundle this defers its async-ref components + to. +- [`TryPromote`](try_promote.md) — the lift it routes the handler slot through. +- [`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), + [`PromoteProducer`](promote_producer.md) — the bundles for the other base traits. +- [`Handler`](../../components/handler.md) — the base and the most general family member. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family and its most general member. + +## Source + +- [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_producer.md b/docs/reference/providers/handler/promote_producer.md new file mode 100644 index 00000000..f5a57304 --- /dev/null +++ b/docs/reference/providers/handler/promote_producer.md @@ -0,0 +1,78 @@ +--- +sidebar_label: 'PromoteProducer' +sidebar_position: 10 +--- + +# `PromoteProducer` + +Fill in the handler family from a provider that implements `Producer`. + +:::info + +### Generated machinery + +**You are not expected to name `PromoteProducer` directly.** +[`#[cgp_producer]`](../../macros/cgp_producer.md) wires it across the family for the provider it +generates. You name `PromoteProducer` by hand only when wiring a hand-written producer's +family explicitly. This page explains what that wiring emits. + +::: + +## Overview + +`PromoteProducer` starts from a [`Producer`](../../components/producer.md), a provider that +takes no input, and fills in every input-taking member of the handler family on a **context**, the +type a capability runs against. The single produced value flows out of every handler shape regardless +of the input, which the promotion discards. Like every CGP provider, it carries no runtime value. + +## Usage + +It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base +`Producer` provider. The base answers `ProducerComponent`, and `PromoteProducer` answers +`ComputerComponent` (and the rest of the family) by discarding the input and calling the producer: + +```rust +delegate_components! { + App { + ProducerComponent: MakeDefault, + ComputerComponent: PromoteProducer, + } +} +``` + +Most code gets this wiring from [`#[cgp_producer]`](../../macros/cgp_producer.md) rather than writing it. + +## When to reach for it, and when not + +**Reach for `PromoteProducer` when the base is an input-free `Producer`** and you wire its family by +hand rather than through [`#[cgp_producer]`](../../macros/cgp_producer.md). For an input-taking base use +[`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), +[`PromoteAsyncComputer`](promote_async_computer.md), or [`PromoteHandler`](promote_handler.md). + +## Under the hood + +`PromoteProducer` is a [`delegate_components!`](../../macros/delegate_components.md) table over a generic +inner `Provider`. It routes `ComputerComponent` to [`Promote`](promote.md), which discards the +computer's input and calls the producer, and defers every remaining component to +[`PromoteComputer`](promote_computer.md), so the produced value reaches every handler shape. + +## Related constructs + +- [`#[cgp_producer]`](../../macros/cgp_producer.md) — generates a `Producer` provider and wires + `PromoteProducer`. +- [`Promote`](promote.md) — the lift that discards a computer's input and calls the producer. +- [`PromoteComputer`](promote_computer.md) — the bundle this defers to. +- [`Producer`](../../components/producer.md), [`Computer`](../../components/computer.md) — the base and + the family it fills in. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family, including the input-free producer. + +## Source + +- [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_ref.md b/docs/reference/providers/handler/promote_ref.md new file mode 100644 index 00000000..090de23c --- /dev/null +++ b/docs/reference/providers/handler/promote_ref.md @@ -0,0 +1,88 @@ +--- +sidebar_label: 'PromoteRef' +sidebar_position: 6 +--- + +# `PromoteRef` + +Bridge between value handlers and reference handlers by dereferencing. + +:::info + +### Generated machinery + +**You are not expected to name `PromoteRef` directly.** The promotion bundles such as +[`PromoteComputer`](promote_computer.md) wire it into every `…Ref` slot, and the bundles are what +[`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md) +generate. You reach for it by hand only when wiring the handler family one slot at a time. This page +explains what that wiring emits. + +::: + +## Overview + +`PromoteRef` lets a provider written to take a value serve a slot that takes a reference, and +the reverse, without manual dereference code. It is the most thoroughly implemented promotion: it +covers all four handler families in both directions, on a **context**, the type a capability runs +against. Like every CGP provider, it carries no runtime value; the inner provider rides in +`PhantomData`. + +## Usage + +Import it from `cgp::extra::handler`. It takes one type parameter, the inner provider. To fill a +by-reference slot such as `ComputerRefComponent`, the inner provider is a by-value provider whose input +is a reference (`Computer`), and `PromoteRef` calls it on the borrowed input: + +```rust +use cgp::extra::handler::PromoteRef; + +// `DoubleRef` is a `Computer<_, _, &u64>`; PromoteRef serves the by-reference slot from it. +delegate_components! { + App { + ComputerRefComponent: PromoteRef, + } +} +``` + +## When to reach for it, and when not + +**You rarely reach for `PromoteRef` by hand.** Every promotion bundle wires it into the `…Ref` slots, so +the by-reference family follows from a by-value provider automatically. Reach for it directly only when +wiring a `…Ref` slot by hand. For the other axes use [`Promote`](promote.md), +[`PromoteAsync`](promote_async.md), or [`TryPromote`](try_promote.md). + +## Under the hood + +`PromoteRef` carries the inner provider in `PhantomData`: + +```rust +pub struct PromoteRef(pub PhantomData); +``` + +For each of `Computer`/`ComputerRef`, `TryComputer`/`TryComputerRef`, `AsyncComputer`/`AsyncComputerRef`, +and `Handler`/`HandlerRef`, it provides two impls. One direction implements the by-value trait given an +inner by-reference provider plus `Input: Deref`, calling the inner provider on +`input.deref()`. The other direction implements the by-reference trait given an inner by-value provider +that works `for<'a>` over `&'a Input`, calling the inner provider on the borrowed input. A provider +written to take `&T` can then serve a slot that hands it a smart pointer to `T`, and the reverse. + +## Related constructs + +- [`Promote`](promote.md), [`PromoteAsync`](promote_async.md), [`TryPromote`](try_promote.md) — the + other single-step lifts, along the fallibility and asynchrony axes rather than the borrow axis. +- [`PromoteComputer`](promote_computer.md) and the other bundles — wire `PromoteRef` into every `…Ref` + slot automatically. +- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family + members and their by-reference companions it bridges. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family, including the by-reference companion of each member. + +## Source + +- [`providers/promote_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_ref.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md new file mode 100644 index 00000000..96f168a3 --- /dev/null +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -0,0 +1,75 @@ +--- +sidebar_label: 'PromoteTryComputer' +sidebar_position: 9 +--- + +# `PromoteTryComputer` + +Fill in the handler family from a provider that implements `TryComputer`. + +:::info + +### Generated machinery + +**You are not expected to name `PromoteTryComputer` directly.** It is wired for a generated provider +that implements the fallible synchronous base. You name it by hand only when wiring a hand-written +`TryComputer`'s family explicitly. This page explains what that wiring emits. + +::: + +## Overview + +`PromoteTryComputer` starts from a provider that implements `TryComputer`, the synchronous +fallible base, and fills in the rest of the handler family on a **context**, the type a capability runs +against. It first turns the fallible base into a plain computer, then derives the rest of the family +from there. Like every CGP provider, it carries no runtime value. + +## Usage + +It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base +`TryComputer` provider: + +```rust +delegate_components! { + App { + [TryComputerComponent, HandlerComponent]: PromoteTryComputer, + } +} +``` + +## When to reach for it, and when not + +**Reach for `PromoteTryComputer` when the base provider is a synchronous fallible `TryComputer`** and +you wire its family by hand. For a plain `Computer` base use [`PromoteComputer`](promote_computer.md); +for the other bases use [`PromoteProducer`](promote_producer.md), +[`PromoteAsyncComputer`](promote_async_computer.md), or [`PromoteHandler`](promote_handler.md). + +## Under the hood + +`PromoteTryComputer` is a [`delegate_components!`](../../macros/delegate_components.md) table over a +generic inner `Provider`. It routes `TryComputerComponent` to [`TryPromote`](try_promote.md), which +exposes the fallible base as a computer returning an explicit `Result`, and defers every remaining +component to [`PromoteComputer`](promote_computer.md), so the rest of the family is derived from that +computer form. + +## Related constructs + +- [`PromoteComputer`](promote_computer.md) — the bundle this defers to once the base is a plain + computer. +- [`TryPromote`](try_promote.md) — the lift it routes the fallible slot through. +- [`PromoteProducer`](promote_producer.md), [`PromoteAsyncComputer`](promote_async_computer.md), + [`PromoteHandler`](promote_handler.md) — the bundles for the other base traits. +- [`TryComputer`](../../components/try_computer.md), [`Handler`](../../components/handler.md) — the + family it fills in. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family and its fallibility axis. + +## Source + +- [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/return_input.md b/docs/reference/providers/handler/return_input.md new file mode 100644 index 00000000..ee3656f0 --- /dev/null +++ b/docs/reference/providers/handler/return_input.md @@ -0,0 +1,92 @@ +--- +sidebar_label: 'ReturnInput' +sidebar_position: 3 +--- + +# `ReturnInput` + +The identity handler: return the input unchanged as the output. + +## Overview + +`ReturnInput` ignores the **context**, the type a capability runs against, and the `Code` tag, and +returns its input as its output. It is the neutral element of handler composition: putting it before or +after any other handler leaves that handler's behavior unchanged. It fills a handler slot where no +transformation is wanted, serves as the base case of a conditionally-built pipeline, and stands in as a +placeholder stage. Like every CGP provider, it carries no runtime value; it is a plain unit struct. + +## Usage + +Import it from `cgp::extra::handler`. It takes no type parameter: + +```rust +use cgp::extra::handler::ReturnInput; + +delegate_components! { + App { + ComputerComponent: ReturnInput, + } +} +``` + +Wired this way, computing over any input returns that input unchanged. + +## Examples + +`ReturnInput` is most useful as a pass-through stage. A pipeline that conditionally transforms its input +can fall back to `ReturnInput` when there is nothing to do, so the slot is always filled: + +```rust +use cgp::extra::handler::{PipeHandlers, ReturnInput}; + +// A pipeline whose middle stage is a no-op for this context. +delegate_components! { + App { + ComputerComponent: + PipeHandlers, + } +} +``` + +The `ReturnInput` stage passes its input straight to `Format`, so the pipeline behaves as +`PipeHandlers`. + +## When to reach for it, and when not + +**Reach for `ReturnInput` when a handler slot must be filled but no transformation is wanted**, such as +the base case of a pipeline built up conditionally, or a stage that is a no-op for one context. Reach +for a producer written with [`#[cgp_producer]`](../../macros/cgp_producer.md) instead when the slot +should compute a fixed value rather than echo its input. + +## Under the hood + +`ReturnInput` is a plain unit struct: + +```rust +pub struct ReturnInput; +``` + +It implements `Computer`, `TryComputer`, `AsyncComputer`, and `Handler`, in each case setting +`Output = Input` and returning the input directly. The fallible variants wrap the input in `Ok`, so they +require the context to have an error type. + +## Related constructs + +- [`ComposeHandlers`](compose_handlers.md), [`PipeHandlers`](pipe_handlers.md) — the composition + combinators `ReturnInput` is the neutral element of. +- [`Producer`](../../components/producer.md) — for a stage that computes a value rather than echoing + the input. +- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family it + implements. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its composition. + +## Source + +- [`providers/return_input.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/return_input.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/try_promote.md b/docs/reference/providers/handler/try_promote.md new file mode 100644 index 00000000..4be03dea --- /dev/null +++ b/docs/reference/providers/handler/try_promote.md @@ -0,0 +1,88 @@ +--- +sidebar_label: 'TryPromote' +sidebar_position: 7 +--- + +# `TryPromote` + +Bridge in both directions between a `Result`-valued output and a fallible handler trait. + +:::info + +### Generated machinery + +**You are not expected to name `TryPromote` directly.** The promotion bundle +[`PromoteTryComputer`](promote_try_computer.md) wires it, and [`PipeMonadic`](../monad/pipe_monadic.md) +uses it internally to bridge fallible and infallible handlers. You reach for it by hand only when +wiring the handler family one slot at a time. This page explains what that wiring does. + +::: + +## Overview + +`TryPromote` unifies the two ways of expressing fallibility: a handler that *returns* a +`Result`, and a genuinely fallible handler trait. It converts between them in both directions on a +**context**, the type a capability runs against. Every impl requires the context to have an error type. +Like every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. + +## Usage + +Import it from `cgp::extra::handler`. It takes one type parameter, the inner provider: + +```rust +use cgp::extra::handler::TryPromote; + +// Turn a Computer that returns Result into a genuine TryComputer. +delegate_components! { + App { + TryComputerComponent: TryPromote, + } +} +``` + +## When to reach for it, and when not + +**You rarely reach for `TryPromote` by hand.** The [`PromoteTryComputer`](promote_try_computer.md) and +[`PromoteHandler`](promote_handler.md) bundles wire it, and [`PipeMonadic`](../monad/pipe_monadic.md) +uses it internally. Reach for it directly only to convert between a `Result`-valued output and a +fallible trait when wiring a slot by hand. For the other lifts use [`Promote`](promote.md), +[`PromoteAsync`](promote_async.md), or [`PromoteRef`](promote_ref.md). + +## Under the hood + +`TryPromote` carries the inner provider in `PhantomData`: + +```rust +pub struct TryPromote(pub PhantomData); +``` + +- As a `TryComputer`, it requires the inner `Provider: Computer` whose `Output` is itself a + `Result`, and unwraps that into the `TryComputer` result. This turns a + computer that *returns* a `Result` into a genuine fallible computer. +- As a `Computer`, it goes the other way: given `Provider: TryComputer`, its output type is + `Result`, surfacing the fallible result as an ordinary value. + +The analogous pair lifts between `Handler` (from an `AsyncComputer` returning a `Result`) and +`AsyncComputer` (from a `Handler`). All four impls require the context to have an error type. + +## Related constructs + +- [`Promote`](promote.md), [`PromoteAsync`](promote_async.md), [`PromoteRef`](promote_ref.md) — the + other single-step lifts. +- [`PromoteTryComputer`](promote_try_computer.md) — the bundle that wires `TryPromote`. +- [`PipeMonadic`](../monad/pipe_monadic.md) — uses `TryPromote` to demote fallible handlers when + composing a fallible monadic pipeline. +- [`TryComputer`](../../components/try_computer.md), [`Handler`](../../components/handler.md) — the + fallible family members it bridges. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family and its fallibility axis. + +## Source + +- [`providers/try_promote.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/try_promote.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/use_input_delegate.md b/docs/reference/providers/handler/use_input_delegate.md new file mode 100644 index 00000000..8956b94c --- /dev/null +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -0,0 +1,124 @@ +--- +sidebar_label: 'UseInputDelegate' +sidebar_position: 13 +--- + +# `UseInputDelegate` + +Dispatch a handler to a different inner provider per input type, through a lookup table. + +## Overview + +`UseInputDelegate` chooses a handler provider by the type of the value being handled. An +ordinary handler component is answered by one provider. `UseInputDelegate` performs a second lookup: it +treats the handler's `Input` type as a key and reads the matching inner provider out of a table, so a +single wiring entry on a **context**, the type a capability runs against, fans out to many +input-specific providers. Like every CGP provider, it holds no runtime value; the table rides in +`PhantomData`. + +It is the sibling of [`UseDelegate`](../use_delegate.md). Where `UseDelegate` keys on the first generic +parameter of a provider trait, the `Code` for a handler, `UseInputDelegate` keys on the `Input` +parameter, so the provider that handles a value is chosen by the type of that value. The handler +components enable both dispatchers at once. + +## Usage + +Import it from `cgp::extra::handler`. It takes one type parameter, the lookup table, and is wired +through a nested table that maps each concrete input type to its provider: + +```rust +use cgp::extra::handler::UseInputDelegate; + +delegate_components! { + App { + ComputerComponent: UseInputDelegate, + } +} +``` + +The outer entry routes the handler component to `UseInputDelegate`, and the inner table +maps each input type to the provider responsible for it. Unlike the per-`Code` dispatch of +[`UseDelegate`](../use_delegate.md), input dispatch has no `open`-statement equivalent, so the nested +table is the current form rather than a legacy one. + +## When to reach for it, and when not + +**Reach for `UseInputDelegate` when a handler should run a different provider depending on the type of +its input**, which is common in the [dispatch combinators](../dispatch/index.md), where a matcher routes +each variant of an enum to a handler chosen by the payload type. For dispatch on the `Code` selector +rather than the input, use the `open` statement of +[`delegate_components!`](../../macros/delegate_components.md), or the legacy +[`UseDelegate`](../use_delegate.md) it supersedes. + +## Under the hood + +`UseInputDelegate` carries the table in `PhantomData`: + +```rust +pub struct UseInputDelegate(pub PhantomData); +``` + +Each handler component trait is declared with two +[`#[derive_delegate]`](../../attributes/derive_delegate.md) directives, `UseDelegate` and +`UseInputDelegate`, as on the `Computer` component: + +```rust +#[cgp_component(Computer)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +pub trait CanCompute { + type Output; + + fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; +} +``` + +The second directive makes [`#[cgp_component]`](../../macros/cgp_component.md) generate a provider impl +that looks `Components` up by the `Input` type and forwards to the matching delegate: + +```rust +impl Computer + for UseInputDelegate +where + Components: DelegateComponent, + Delegate: Computer, +{ + type Output = Delegate::Output; + + fn compute(context: &Context, code: PhantomData, input: Input) -> Self::Output { + Delegate::compute(context, code, input) + } +} +``` + +The lookup key is the `Input` type, while `Code` and `Context` pass through unchanged. The same impl +shape is generated for every handler family member. + +## Related constructs + +- [`UseDelegate`](../use_delegate.md) — the sibling that keys on the `Code` selector. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates both dispatch impls on a + handler component. +- [`delegate_components!`](../../macros/delegate_components.md) — wires it through a nested table. +- [Dispatch combinators](../dispatch/index.md) — the main users of input dispatch, selecting a per-variant + handler by payload type. +- [`DelegateComponent`](../../traits/delegate_component.md) — the table the lookup reads. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the family whose input this dispatches on. +- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to per-type handlers. + +## Source + +- [`types.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/types.rs), + with the impls generated from the `#[derive_delegate(UseInputDelegate)]` directive on the + handler components in + [`components/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/components). + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler_combinators.md b/docs/reference/providers/handler_combinators.md deleted file mode 100644 index 189e6f20..00000000 --- a/docs/reference/providers/handler_combinators.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -sidebar_label: 'Handler combinators' -sidebar_position: 13 ---- - -# Handler combinators - -`ComposeHandlers`, `PipeHandlers`, `ReturnInput`, and the `Promote*` lifts. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/docs/reference/providers/index.md b/docs/reference/providers/index.md index 4877c0ba..967a0a30 100644 --- a/docs/reference/providers/index.md +++ b/docs/reference/providers/index.md @@ -50,8 +50,9 @@ to a component. ## The computation-family combinators The handler family has its own providers, which build, route, and lift computations rather than wire a -single capability. The [error providers](./error_providers.md) raise and wrap a context's abstract -error, the [handler combinators](./handler_combinators.md) compose and promote handlers across the -family's synchronous, async, and fallible shapes, the [dispatch combinators](./dispatch_combinators.md) +single capability. The [error providers](./error/index.md) raise and wrap a context's abstract +error, the [handler combinators](./handler/index.md) compose and promote handlers across the +family's synchronous, async, and fallible shapes, the [dispatch combinators](./dispatch/index.md) route an extensible-data value to per-field or per-variant handlers, and the -[monad providers](./monad_providers.md) chain handlers that short-circuit through a monad. +[monad providers](./monad/index.md) chain handlers that short-circuit through a monad. Each group is a +subsection here with one page per provider and its own overview. diff --git a/docs/reference/providers/monad/_category_.json b/docs/reference/providers/monad/_category_.json new file mode 100644 index 00000000..96ce213f --- /dev/null +++ b/docs/reference/providers/monad/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Monad providers", + "position": 15, + "link": { + "type": "doc", + "id": "reference/providers/monad/index" + } +} diff --git a/docs/reference/providers/monad/bind_err.md b/docs/reference/providers/monad/bind_err.md new file mode 100644 index 00000000..664ed849 --- /dev/null +++ b/docs/reference/providers/monad/bind_err.md @@ -0,0 +1,78 @@ +--- +sidebar_label: 'BindErr' +sidebar_position: 3 +--- + +# `BindErr` + +The per-step provider for one bind of the err monad: run the continuation on the `Ok` value, and +short-circuit on `Err`. + +## Overview + +`BindErr` implements a single bind step of the err monad, the ordinary `?`-style behavior. +[`PipeMonadic`](pipe_monadic.md) composes it for you when it folds a pipeline under +[`ErrMonadic`](index.md#the-monad-markers), so most code never names it. It is usable directly as a +handler provider on a **context**, the type a capability runs against, when a pipeline is built step by +step through [`PipeHandlers`](../handler/pipe_handlers.md). Like every CGP provider, it carries no +runtime value; the two parameters ride in `PhantomData`. + +## Usage + +Import it from `cgp::extra::monad::monadic::err`. It is not in the prelude. `M` is the monad layer +beneath this bind, and `Cont` is the continuation provider run on the continue branch: + +```rust +use cgp::extra::monad::monadic::err::BindErr; +use cgp::extra::monad::monadic::ident::IdentMonadic; +use cgp::extra::handler::PipeHandlers; + +// This is what PipeMonadic builds internally for a two-element list under ErrMonadic. +type Pipeline = PipeHandlers]>; +// 1 -> Ok(2) -> BindErr runs the second Increment on 2 -> Ok(3) +``` + +## When to reach for it, and when not + +**Reach for the [monad providers](index.md) rather than `BindErr` directly.** Wiring +[`PipeMonadic`](pipe_monadic.md) with the [`ErrMonadic`](index.md#the-monad-markers) marker composes +`BindErr` for you. Name it yourself only when building a pipeline step by step inside a +[`PipeHandlers`](../handler/pipe_handlers.md) list. For the mirror that continues on `Err` and +short-circuits on `Ok`, use [`BindOk`](bind_ok.md). + +## Under the hood + +`BindErr` carries the monad layer and the continuation in `PhantomData`: + +```rust +pub struct BindErr(pub PhantomData<(M, Cont)>); +``` + +It implements `Computer` and `AsyncComputer` for an input of `Result`. On `Ok(value)` it runs +`Cont` on the value and lifts the continuation's output back through `M`. On `Err(err)` it +short-circuits, lifting the error directly to the output and skipping `Cont`. It is the mirror of +[`BindOk`](bind_ok.md), which branches the other way. The `M` parameter is what lets these binds nest: at +the bottom of a single-layer pipeline it is `IdentMonadic`, and a stacked monad threads a deeper monad +through it. + +## Related constructs + +- [`BindOk`](bind_ok.md) — the mirror, binding the err branch and short-circuiting on `Ok`. +- [`PipeMonadic`](pipe_monadic.md) — composes `BindErr` internally under `ErrMonadic`. +- The [monad markers](index.md#the-monad-markers) — `ErrMonadic` is the marker `BindErr` implements the + bind for. +- [`PipeHandlers`](../handler/pipe_handlers.md) — where a hand-built bind step is placed. +- [`ContainsValue`](../../traits/contains_value.md), [`LiftValue`](../../traits/lift_value.md) — the + traits it uses to inspect and lift a step's value. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — the bind step and how the monads compose. + +## Source + +- [`monadic/err.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/monadic/err.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad/bind_ok.md b/docs/reference/providers/monad/bind_ok.md new file mode 100644 index 00000000..f33cd247 --- /dev/null +++ b/docs/reference/providers/monad/bind_ok.md @@ -0,0 +1,78 @@ +--- +sidebar_label: 'BindOk' +sidebar_position: 2 +--- + +# `BindOk` + +The per-step provider for one bind of the ok monad: run the continuation on the `Err` payload, and +short-circuit on `Ok`. + +## Overview + +`BindOk` implements a single bind step of the ok monad. [`PipeMonadic`](pipe_monadic.md) +composes it for you when it folds a pipeline under [`OkMonadic`](index.md#the-monad-markers), so most +code never names it. It is usable directly as a handler provider on a **context**, the type a capability +runs against, when a pipeline is built step by step through +[`PipeHandlers`](../handler/pipe_handlers.md) rather than through `PipeMonadic`. Like every CGP +provider, it carries no runtime value; the two parameters ride in `PhantomData`. + +## Usage + +Import it from `cgp::extra::monad::monadic::ok`. It is not in the prelude. `M` is the monad layer beneath +this bind, and `Cont` is the continuation provider run on the continue branch: + +```rust +use cgp::extra::monad::monadic::ok::BindOk; +use cgp::extra::monad::monadic::ident::IdentMonadic; +use cgp::extra::handler::PipeHandlers; + +// Build one ok-bind step by hand inside a PipeHandlers list. +type Pipeline = PipeHandlers]>; +``` + +At the bottom of a single-layer pipeline `M` is `IdentMonadic`; a stacked monad threads a deeper monad +through it. + +## When to reach for it, and when not + +**Reach for the [monad providers](index.md) rather than `BindOk` directly.** Wiring +[`PipeMonadic`](pipe_monadic.md) with the [`OkMonadic`](index.md#the-monad-markers) marker composes +`BindOk` for you. Name it yourself only when building a pipeline step by step inside a +[`PipeHandlers`](../handler/pipe_handlers.md) list. For the `?`-style mirror that continues on `Ok` and +short-circuits on `Err`, use [`BindErr`](bind_err.md). + +## Under the hood + +`BindOk` carries the monad layer and the continuation in `PhantomData`: + +```rust +pub struct BindOk(pub PhantomData<(M, Cont)>); +``` + +It implements `Computer` and `AsyncComputer` for an input of `Result`. On `Err(payload)` it runs +`Cont` on the payload and lifts the continuation's output back through `M`. On `Ok(value)` it +short-circuits, lifting the value directly to the output and skipping `Cont`. It is the mirror of +[`BindErr`](bind_err.md), which branches the other way. + +## Related constructs + +- [`BindErr`](bind_err.md) — the mirror, binding the ok branch and short-circuiting on `Err`. +- [`PipeMonadic`](pipe_monadic.md) — composes `BindOk` internally under `OkMonadic`. +- The [monad markers](index.md#the-monad-markers) — `OkMonadic` is the marker `BindOk` implements the + bind for. +- [`PipeHandlers`](../handler/pipe_handlers.md) — where a hand-built bind step is placed. +- [`ContainsValue`](../../traits/contains_value.md), [`LiftValue`](../../traits/lift_value.md) — the + traits it uses to inspect and lift a step's value. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — the bind step and how the monads compose. + +## Source + +- [`monadic/ok.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/monadic/ok.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad/index.md b/docs/reference/providers/monad/index.md new file mode 100644 index 00000000..d9dab3cb --- /dev/null +++ b/docs/reference/providers/monad/index.md @@ -0,0 +1,80 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Monad providers + +Turn a list of handlers and a choice of monad into a single handler that short-circuits on the +appropriate branch. + +## Overview + +The monad providers build [monadic handler composition](/docs/concepts/monadic-handlers) on top of the +[`Computer`](../../components/computer.md) family. They let a sequence of handlers whose outputs carry a +"continue" case and a "stop" case be chained without pattern-matching each step by hand: the monad +decides which case threads forward and which short-circuits. A built pipeline is itself a provider for +`Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires into a **context**, the type a +capability runs against, exactly like any other handler. + +The providers divide into three groups: + +- [`PipeMonadic`](pipe_monadic.md) is the pipeline builder, the provider a user wires or invokes. +- The **monad markers** below are the zero-sized types that select the short-circuiting behavior. +- [`BindOk`](bind_ok.md) and [`BindErr`](bind_err.md) are the per-step bind providers that `PipeMonadic` + composes internally, and that can also be used directly. + +## The monad markers + +A monad marker selects which branch of a step's output continues the pipeline and which stops it. CGP +defines three base markers and a transformer form for the two that branch on `Result`. They are not +providers, so they have no page of their own; they are the `M` argument the providers above take. + +**`IdentMonadic`** is the identity monad. It threads every value forward and never short-circuits, so a +`PipeMonadic` is equivalent to plain composition with +[`PipeHandlers`](../handler/pipe_handlers.md). + +**`OkMonadic`** short-circuits on `Ok` and continues on `Err`. It is the mirror behavior, running until +something succeeds, which suits a fallback chain. + +**`ErrMonadic`** short-circuits on `Err` and continues on `Ok`. This is the ordinary early-return-on-error +behavior, the same as Rust's `?` operator. + +The naming reads the opposite of the behavior, and getting it wrong produces a pipeline that runs +exactly when you expected it to stop: **`OkMonadic` continues on `Err`, and `ErrMonadic` continues on +`Ok`**. `ErrMonadic` is the one that behaves like `?`. + +**`OkMonadicTrans`** and **`ErrMonadicTrans`** are transformer forms that apply the same behavior +on top of a base monad `M`, so monads can stack over nested result types. Writing +`OkMonadicTrans` builds a monad that short-circuits on an outer `Ok` while threading an +inner `Result` through the err monad beneath it. A single layer of branching needs no explicit +transformer, because the bare markers produce their own transformer form over `IdentMonadic` when used +as transformers. The trait layer that gives a marker its meaning is documented under +[`MonadicBind`](../../traits/monadic_bind.md) and [`MonadicTrans`](../../traits/monadic_trans.md). + +## Related constructs + +- [`PipeMonadic`](pipe_monadic.md) — the pipeline builder that consumes a marker and a handler list. +- [`BindOk`](bind_ok.md), [`BindErr`](bind_err.md) — the per-step bind providers. +- [`PipeHandlers`](../handler/pipe_handlers.md) — non-monadic composition, which `PipeMonadic` + reduces to. +- [`MonadicBind`](../../traits/monadic_bind.md), [`MonadicTrans`](../../traits/monadic_trans.md), + [`ContainsValue`](../../traits/contains_value.md), [`LiftValue`](../../traits/lift_value.md) — the + four traits a marker implements. +- [`Product!`](../../macros/product.md) — the type-level list a pipeline's steps are given in. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads + compose. + +## Source + +- The pipeline provider is in + [`providers/pipe_monadic.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/providers/pipe_monadic.rs), + and the markers and bind providers in + [`monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic). + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md new file mode 100644 index 00000000..d758f444 --- /dev/null +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -0,0 +1,116 @@ +--- +sidebar_label: 'PipeMonadic' +sidebar_position: 1 +--- + +# `PipeMonadic` + +Compose a list of handlers under a monad into a single handler that short-circuits on the monad's stop +branch. + +## Overview + +`PipeMonadic` composes a handler list `Providers` under a monad `M` into one +short-circuiting handler, on a **context**, the type a capability runs against. Each step runs only on +the previous step's continue branch, and the monad decides which branch that is. The result is a +provider for `Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires like any other +handler. Like every CGP provider, it carries no runtime value; `M` and the list ride in `PhantomData`. + +## Usage + +Import it from `cgp::extra::monad::providers`, and the monad markers from `cgp::extra::monad::monadic`. +None of these is in the prelude. `PipeMonadic` takes a monad marker and a +[`Product!`](../../macros/product.md) list of handler providers: + +```rust +use cgp::extra::monad::providers::PipeMonadic; +use cgp::extra::monad::monadic::err::ErrMonadic; + +delegate_components! { + App { + ComputerComponent: + PipeMonadic, + } +} +``` + +Under `ErrMonadic`, each step runs on the previous step's `Ok` value and the first `Err` becomes the +pipeline's output. The [monad markers](index.md#the-monad-markers) choose the branching; the naming trap +there is worth re-reading, since `ErrMonadic` is the `?`-style monad. + +## Examples + +Composing a homogeneous list under a base monad. With an `Increment` computer that returns +`Result`, `Ok` on success and `Err("overflow")` on overflow, three under `ErrMonadic` chain on +the `Ok` value and stop at the first error: + +```rust +PipeMonadic::::compute(&context, code, 253) +// 253 -> Ok(254) -> Ok(255) -> Err("overflow") +``` + +Stacking monads handles nested results. Composing handlers that return `Result, &str>` +under `OkMonadicTrans` short-circuits on the outer `Ok` while threading the inner `Result` +through the err monad, and the same list composed under `OkMonadic` can be driven through the fallible +`try_compute` and async `handle` entry points, because `PipeMonadic` implements `TryComputer` and +`Handler` as well: + +```rust +PipeMonadic::::try_compute(&context, code, 1) +``` + +## When to reach for it, and when not + +**Reach for `PipeMonadic` when a pipeline's steps should short-circuit on a branch**, such as an error +or the first success, rather than always feeding the next step. For a pipeline where every step runs +unconditionally, use [`PipeHandlers`](../handler/pipe_handlers.md), which `PipeMonadic` +reduces to. When the whole chain lives in one provider body, Rust's own `?` operator is clearer than any +composition. + +## Under the hood + +`PipeMonadic` carries the monad and the list in `PhantomData`: + +```rust +pub struct PipeMonadic(pub PhantomData<(M, Providers)>); +``` + +It implements `ComputerComponent` and `AsyncComputerComponent` by folding the list: an internal +`BindProviders` computation walks the list so the first provider runs on the input and its result is +bound, through the monad, to the monadically-composed rest of the list. + +For the fallible components `TryComputerComponent` and `HandlerComponent`, it bridges through the err +monad. It first maps every provider to [`TryPromote`](../handler/try_promote.md), demoting fallible +handlers to plain computers whose output is an explicit `Result`; the mapper that rewrites the whole list +is `TryPromoteProviders`, which implements [`MapType`](../../traits/map_type.md). It then applies +`ErrMonadic` as a transformer on top of `M`, composes the demoted list under the transformed monad, and +wraps the composed provider back in `TryPromote` to restore the fallible interface. A `PipeMonadic` over +fallible handlers therefore short-circuits on the context's error type in addition to whatever branching +`M` contributes. The whole fold happens during trait resolution, so the pipeline is not a runtime +structure. + +## Related constructs + +- The [monad markers](index.md#the-monad-markers) — the `M` argument that selects the branching. +- [`BindOk`](bind_ok.md), [`BindErr`](bind_err.md) — the per-step providers `PipeMonadic` composes + internally. +- [`PipeHandlers`](../handler/pipe_handlers.md) — the non-monadic pipeline this generalizes. +- [`TryPromote`](../handler/try_promote.md) — the lift it uses to bridge fallible and infallible + handlers. +- [`MonadicBind`](../../traits/monadic_bind.md), [`MonadicTrans`](../../traits/monadic_trans.md) — the + traits it bounds on while folding. +- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family a + pipeline implements. + +The ideas behind it: + +- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads + compose. + +## Source + +- [`providers/pipe_monadic.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/providers/pipe_monadic.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad_providers.md b/docs/reference/providers/monad_providers.md deleted file mode 100644 index 846f8873..00000000 --- a/docs/reference/providers/monad_providers.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -sidebar_label: 'Monad providers' -sidebar_position: 15 ---- - -# Monad providers - -`PipeMonadic`, `BindOk`, `BindErr`, and the identity/ok/err monad markers. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index 21ba5336..cee90c01 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -41,7 +41,7 @@ pub struct GreetLoudly(pub PhantomData); ``` It also appears directly in a wiring entry to route a component through the context's own -implementation, which is how the [dispatch combinators](dispatch_combinators.md) default their +implementation, which is how the [dispatch combinators](dispatch/index.md) default their per-variant provider. **Do not wire a component to `UseContext` when that component's only implementation on the context is @@ -173,7 +173,7 @@ capability or a per-type dispatch entry. context's own implementation into a component. - [`RedirectLookup`](redirect_lookup.md) — the other `#[cgp_component]`-generated provider, routing through a separate table rather than back to the context. -- [Dispatch combinators](dispatch_combinators.md) — default their per-variant provider to `UseContext`. +- [Dispatch combinators](dispatch/index.md) — default their per-variant provider to `UseContext`. - [`IsProviderFor`](../traits/is_provider_for.md) — carries the dependency `UseContext` propagates. The ideas behind it: diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 17d8c83a..a5e5d067 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -123,7 +123,7 @@ handler families. The dispatching-per-type choice is worked through in [`#[derive_delegate]`](../attributes/derive_delegate.md). For dispatching on the *input* type of a handler rather than a `Code` parameter, the sibling provider is -[`UseInputDelegate`](handler_combinators.md). +[`UseInputDelegate`](handler/use_input_delegate.md). ## Under the hood @@ -161,7 +161,7 @@ parameters should be routed differently. - [`delegate_components!`](../macros/delegate_components.md) — wires it, usually through a nested table, and carries the `open` statement that replaces it. - [`RedirectLookup`](redirect_lookup.md) — the mechanism `open` rides instead. -- [`UseInputDelegate`](handler_combinators.md) — the sibling that keys on a handler's `Input` type. +- [`UseInputDelegate`](handler/use_input_delegate.md) — the sibling that keys on a handler's `Input` type. - [`DelegateComponent`](../traits/delegate_component.md) — the table the lookup reads. - [`IsProviderFor`](../traits/is_provider_for.md) — propagates the dispatched provider's dependencies. diff --git a/docs/reference/traits/can_upcast.md b/docs/reference/traits/can_upcast.md index 7e4ad388..494ccf32 100644 --- a/docs/reference/traits/can_upcast.md +++ b/docs/reference/traits/can_upcast.md @@ -135,7 +135,7 @@ value type are both part of the entry. recursion routes through. - [`HasFields`](./has_fields.md) — the variant shape being walked. - [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain underneath. -- [Dispatch combinators](../providers/dispatch_combinators.md) — where casting meets per-variant routing. +- [Dispatch combinators](../providers/dispatch/index.md) — where casting meets per-variant routing. The ideas behind it: diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/contains_value.md index 2ecc2d61..5089e219 100644 --- a/docs/reference/traits/contains_value.md +++ b/docs/reference/traits/contains_value.md @@ -11,7 +11,7 @@ Naming the value a monad threads forward out of a step's output. ### Generated machinery **You are not expected to name `ContainsValue`.** The -[bind providers](../providers/monad_providers.md) use it while running a step, and the monad markers CGP +[bind providers](../providers/monad/index.md) use it while running a step, and the monad markers CGP ships already implement it. The one case for naming it is defining a monad of your own; otherwise this page is here to explain how a step unwraps its input. @@ -79,8 +79,8 @@ specific to any depth. ## When to reach for it, and when not -**Reach for the [monad providers](../providers/monad_providers.md), not this trait.** A pipeline is built -by wiring [`PipeMonadic`](../providers/monad_providers.md) with a marker and a handler list; this is what +**Reach for the [monad providers](../providers/monad/index.md), not this trait.** A pipeline is built +by wiring [`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker and a handler list; this is what the bind providers bound on internally. The one real reason to name it is **defining a new monad** — short-circuiting over an `Option`, or over a @@ -89,12 +89,12 @@ that runs a step and neither is useful without the other, and copy the mirror-im `OkMonadic`/`ErrMonadic` pair as the model. If you do not need short-circuiting at all, the -[handler combinators](../providers/handler_combinators.md) chain steps without a branch and involve none +[handler combinators](../providers/handler/index.md) chain steps without a branch and involve none of this. ## Under the hood -The [`BindOk` and `BindErr`](../providers/monad_providers.md) providers use `ContainsValue` in their +The [`BindOk` and `BindErr`](../providers/monad/index.md) providers use `ContainsValue` in their [`Computer`](../components/computer.md) and `AsyncComputer` impls. Running one bind step means: take the step's output, ask the monad what value sits beneath its wrapper, and hand that to the continuation. This trait is the second half of that sentence. @@ -128,7 +128,7 @@ the first step rather than at the definition. - [`LiftValue`](./lift_value.md) — the other half of running a step: getting back into the output type. - [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md) — the two traits that fold the pipeline rather than run a step. -- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers; what you actually wire. - [`Computer`](../components/computer.md) — the component family the bind providers implement. - [`TryComputer`](../components/try_computer.md) and [`Handler`](../components/handler.md) — the fallible diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md index fccb3abe..7c1344ee 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/extract_field.md @@ -85,7 +85,7 @@ finalize is accepted with no wildcard arm. That is not a convention — it is th after only the first extraction and it does not compile. **In practice you rarely write these chains.** The -[dispatch combinators](../providers/dispatch_combinators.md) build them from a set of per-variant +[dispatch combinators](../providers/dispatch/index.md) build them from a set of per-variant implementations, which is the extensible visitor pattern: a chain exactly like the one above, generated, with one implementation per variant chosen by wiring. @@ -104,7 +104,7 @@ exhaustive, and it generates nothing. This is not an improvement on `match`; it [`to_extractor`](./has_extractor.md) only when you genuinely want to consume. - **Do not use it to test which variant a value holds.** `matches!` or an `if let` answers that in a line. The family's value is in the *chain* and what the chain proves. -- **Reach for the [dispatch combinators](../providers/dispatch_combinators.md) rather than writing the +- **Reach for the [dispatch combinators](../providers/dispatch/index.md) rather than writing the chain**, since they derive it from the enum's own variant list instead of repeating it at each site — which is what keeps "add a variant" from breaking every call site by hand. @@ -159,7 +159,7 @@ derives, so a `Result` is neither `Debug` nor `PartialEq` ho be written in any order — but every variant must be tried before the remainder can be finalized. **Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the -reason to prefer the [dispatch combinators](../providers/dispatch_combinators.md). +reason to prefer the [dispatch combinators](../providers/dispatch/index.md). **Five enum variant names are reserved**, because the generated impls name their associated types through `Self::…`. The [derive's page](../derives/derive_extract_field.md) lists them. @@ -177,7 +177,7 @@ reason to prefer the [dispatch combinators](../providers/dispatch_combinators.md - [`CanDowncast`](./can_downcast.md) — narrowing to another enum rather than to a payload, built on this. - [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the partial enums and every impl here. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build the chain for +- [Dispatch combinators](../providers/dispatch/index.md) — the providers that build the chain for you. - [Type-level spines](../types/type_level_spines.md) — `Either`/`Void`, where the uninhabited terminator comes from. diff --git a/docs/reference/traits/finalize_extract.md b/docs/reference/traits/finalize_extract.md index 6a9b9268..37ce3b7b 100644 --- a/docs/reference/traits/finalize_extract.md +++ b/docs/reference/traits/finalize_extract.md @@ -78,7 +78,7 @@ remainder.** The two do the same job at different points in the chain. `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](../providers/dispatch_combinators.md)** rather than writing the chain at +- **The [dispatch combinators](../providers/dispatch/index.md)** rather than writing the chain at all — they generate it from the enum's variant list, which is what 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. @@ -124,7 +124,7 @@ 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](../providers/dispatch_combinators.md). +[dispatch combinators](../providers/dispatch/index.md). **It also covers `Infallible`**, which is occasionally useful when threading a chain through an error type that cannot occur. @@ -140,7 +140,7 @@ that cannot occur. - [`MapType`](./map_type.md) — the `IsVoid` marker the argument rests on. - [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. - [`CanUpcast`](./can_upcast.md) — a cast whose total walk ends with this same discharge. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build the chain. +- [Dispatch combinators](../providers/dispatch/index.md) — the providers that build the chain. - [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates this impl. The ideas behind it: diff --git a/docs/reference/traits/finalize_extract_result.md b/docs/reference/traits/finalize_extract_result.md index 34f3aabe..d31c6507 100644 --- a/docs/reference/traits/finalize_extract_result.md +++ b/docs/reference/traits/finalize_extract_result.md @@ -98,7 +98,7 @@ let rect = shape holding a `Result`. - **[`FinalizeExtract`](./finalize_extract.md)** when a nested `match` has already unwrapped the remainder out of its `Result`. -- **The [dispatch combinators](../providers/dispatch_combinators.md)** rather than a hand-written chain, +- **The [dispatch combinators](../providers/dispatch/index.md)** rather than a hand-written chain, since they generate it from the enum's own variant list — which is what keeps "add a variant" from breaking every call site. - **`.ok()` or a `match`** when you are making a single attempt and do not intend to exhaust the enum. @@ -144,7 +144,7 @@ bound stops being satisfied. - [`HasExtractor`](./has_extractor.md) — where a chain begins. - [`FinalizeBuild`](./finalize_build.md) — the record family's ending. - [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. -- [Dispatch combinators](../providers/dispatch_combinators.md) — the providers that build the chain for +- [Dispatch combinators](../providers/dispatch/index.md) — the providers that build the chain for you. - [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — what makes an enum extractable. diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md index 06ddf76c..981a3569 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/from_variant.md @@ -191,7 +191,7 @@ struct. - [`Symbol!`](../macros/symbol.md) — the tag that names a variant. - [`CanUpcast`](./can_upcast.md) — widening a narrow enum into a wider one, built on these constructors. - [`HasFields`](./has_fields.md) — the variant shape a cast walks while rebuilding. -- [Dispatch combinators](../providers/dispatch_combinators.md) — where variant construction meets routing. +- [Dispatch combinators](../providers/dispatch/index.md) — where variant construction meets routing. The ideas behind it: diff --git a/docs/reference/traits/has_extractor.md b/docs/reference/traits/has_extractor.md index dd748cac..2423bdca 100644 --- a/docs/reference/traits/has_extractor.md +++ b/docs/reference/traits/has_extractor.md @@ -94,7 +94,7 @@ accessor otherwise — the weakest that works is the right one. - **[`HasExtractorMut`](./has_extractor_mut.md)** to change a payload in place. - **`HasExtractor`** when the payload must be moved out — returned, stored, or handed on by value. - **A `match`** when the enum is concrete. The family is for code that cannot name it. -- **The [dispatch combinators](../providers/dispatch_combinators.md)** rather than a hand-written chain, +- **The [dispatch combinators](../providers/dispatch/index.md)** rather than a hand-written chain, since they derive it from the enum's variant list. ## Under the hood diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/lift_value.md index 69ff5e3e..eba6f0d6 100644 --- a/docs/reference/traits/lift_value.md +++ b/docs/reference/traits/lift_value.md @@ -11,7 +11,7 @@ Putting a value back into a monad's output type, on either branch. ### Generated machinery **You are not expected to name `LiftValue`.** The -[bind providers](../providers/monad_providers.md) use it while running a step, and the monad markers CGP +[bind providers](../providers/monad/index.md) use it while running a step, and the monad markers CGP ships already implement it. The one case for naming it is defining a monad of your own; otherwise this page is here to explain how a step produces its output — and why that takes two methods rather than one. @@ -81,20 +81,20 @@ collapses the two branches. ## When to reach for it, and when not -**Reach for the [monad providers](../providers/monad_providers.md), not this trait.** A pipeline is built -by wiring [`PipeMonadic`](../providers/monad_providers.md) with a marker and a handler list. +**Reach for the [monad providers](../providers/monad/index.md), not this trait.** A pipeline is built +by wiring [`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker and a handler list. The one real reason to name it is **defining a new monad**. Implement it alongside [`ContainsValue`](./contains_value.md), since the two are the pair that runs a step, and take the `OkMonadic`/`ErrMonadic` pair as the model — including their separate treatment of the two methods, which is the part a first implementation usually gets wrong. -If short-circuiting is not what you need, the [handler combinators](../providers/handler_combinators.md) +If short-circuiting is not what you need, the [handler combinators](../providers/handler/index.md) chain steps without a branch and involve none of this. ## Under the hood -The [`BindOk` and `BindErr`](../providers/monad_providers.md) providers use `LiftValue` in their +The [`BindOk` and `BindErr`](../providers/monad/index.md) providers use `LiftValue` in their [`Computer`](../components/computer.md) and `AsyncComputer` impls, as the closing half of a step whose opening half is [`ContainsValue`](./contains_value.md). The step unwraps the incoming output, decides whether to short-circuit, and then lifts: @@ -134,10 +134,10 @@ forwarded; the associated type is the step's own. They coincide for some monads type. - [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md) — the two traits that fold the pipeline rather than run a step. -- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers; what you actually wire. - [`Computer`](../components/computer.md) — the component family the bind providers implement. -- [Handler combinators](../providers/handler_combinators.md) — composition without a short-circuit +- [Handler combinators](../providers/handler/index.md) — composition without a short-circuit branch. The ideas behind it: diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monadic_bind.md index e1adef8c..20d6a496 100644 --- a/docs/reference/traits/monadic_bind.md +++ b/docs/reference/traits/monadic_bind.md @@ -11,7 +11,7 @@ Turning a continuation into one bind step of a monadic pipeline. ### Generated machinery **You are not expected to name `MonadicBind`.** -[`PipeMonadic`](../providers/monad_providers.md) bounds on it while folding a pipeline, and the monad +[`PipeMonadic`](../providers/monad/pipe_monadic.md) bounds on it while folding a pipeline, and the monad markers CGP ships already implement it. The one case for naming it is defining a monad of your own; otherwise this page is here to explain how a pipeline is assembled. @@ -34,7 +34,7 @@ pub trait MonadicBind { `Self` is the monad marker. The parameter is the **continuation** — the handler that should run on the continue branch — and the associated type is the **bind provider** that wraps it. For the base monads -this resolves to a [`BindOk` or `BindErr`](../providers/monad_providers.md) provider; for `IdentMonadic` +this resolves to a [`BindOk` or `BindErr`](../providers/monad/index.md) provider; for `IdentMonadic` it is the continuation unchanged, which is what makes the identity monad free. It is one of four traits that give a monad marker its meaning, alongside @@ -44,7 +44,7 @@ It is one of four traits that give a monad marker its meaning, alongside **This is a plain capability trait, not a CGP component.** It has no generated provider trait, no `…Component` marker, and is never wired through [`delegate_components!`](../macros/delegate_components.md) — the -[monad providers](../providers/monad_providers.md) consume it as an ordinary trait bound while folding a +[monad providers](../providers/monad/index.md) consume it as an ordinary trait bound while folding a pipeline at compile time. ## Usage @@ -56,7 +56,7 @@ use cgp::extra::monad::traits::MonadicBind; ``` In practice you import it only when **defining a monad of your own**. Using the existing ones means -naming [`PipeMonadic`](../providers/monad_providers.md) and a marker in a wiring entry, with no trait in +naming [`PipeMonadic`](../providers/monad/pipe_monadic.md) and a marker in a wiring entry, with no trait in sight. There is no method. The whole trait is a type-level function from a continuation to the provider that @@ -87,7 +87,7 @@ own `Result` layer and hand the rest to `M`, which is how a stack reaches arbitr ## When to reach for it, and when not -**Reach for the [monad providers](../providers/monad_providers.md), not this trait.** Building a pipeline +**Reach for the [monad providers](../providers/monad/index.md), not this trait.** Building a pipeline means wiring `PipeMonadic` with a monad marker and a handler list; this is what that provider bounds on internally. @@ -98,14 +98,14 @@ step tries to run, because the running half is [`ContainsValue`](./contains_valu And the alternatives to prefer when you do *not* need short-circuiting: -- **[Handler combinators](../providers/handler_combinators.md)** — `ComposeHandlers` and `PipeHandlers` +- **[Handler combinators](../providers/handler/index.md)** — `ComposeHandlers` and `PipeHandlers` chain handlers without a branch. If every step runs unconditionally, do not involve a monad at all. - **Ordinary `?` in one provider body** — if the whole chain lives in a single implementation, Rust's own operator is clearer than any composition. ## Under the hood -[`PipeMonadic`](../providers/monad_providers.md) walks the handler list and, for each step, asks the monad +[`PipeMonadic`](../providers/monad/pipe_monadic.md) walks the handler list and, for each step, asks the monad to turn the continuation built so far into a bind step — which is this trait. Because the walk proceeds from the end of the list backwards, `Provider` at each stage is everything that follows the current step, and the result is a single nested provider by the time the list is exhausted. @@ -128,7 +128,7 @@ handler. consumes it. **`OkMonadic` short-circuits on `Ok`, not on `Err`.** The naming reads as "the monad *for* `Ok`" and means -"the monad whose continue branch is `Err`". [`ErrMonadic`](../providers/monad_providers.md) is the one +"the monad whose continue branch is `Err`". [`ErrMonadic`](../providers/monad/index.md) is the one that behaves like `?`. Getting these the wrong way round produces a pipeline that runs exactly when you expected it to stop. @@ -141,9 +141,9 @@ missing trait rather than the gap. - [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) — the two traits that run one bind step, where this one only builds it. - [`MonadicTrans`](./monadic_trans.md) — stacking one monad on another during the same fold. -- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the monad +- [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the monad markers; what you actually wire. -- [Handler combinators](../providers/handler_combinators.md) — composition without a short-circuit +- [Handler combinators](../providers/handler/index.md) — composition without a short-circuit branch. - [`Computer`](../components/computer.md) — the component family a monadic pipeline implements. - [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monadic_trans.md index 4a073892..00eac5b9 100644 --- a/docs/reference/traits/monadic_trans.md +++ b/docs/reference/traits/monadic_trans.md @@ -11,7 +11,7 @@ Stacking one monad on top of another. ### Generated machinery **You are not expected to name `MonadicTrans`.** -[`PipeMonadic`](../providers/monad_providers.md) resolves a stacked monad through it before any binding +[`PipeMonadic`](../providers/monad/pipe_monadic.md) resolves a stacked monad through it before any binding happens, and the transformer markers CGP ships already implement it. The one case for naming it is giving a monad of your own a transformer form; otherwise this page is here to explain how monads stack. @@ -77,8 +77,8 @@ An *n*-layer stack unwraps *n* layers with no code specific to any depth, which ## When to reach for it, and when not -**Reach for the [monad providers](../providers/monad_providers.md), not this trait.** Wiring -[`PipeMonadic`](../providers/monad_providers.md) with a marker — including a stacked one — is how a +**Reach for the [monad providers](../providers/monad/index.md), not this trait.** Wiring +[`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker — including a stacked one — is how a pipeline is built. The reasons to name it are two, and both are narrow. @@ -96,7 +96,7 @@ marker directly. ## Under the hood `MonadicTrans` is applied to the **monads** rather than to the handlers, and it runs *before* any binding -does. [`PipeMonadic`](../providers/monad_providers.md) resolves the stacked monad first, then walks the +does. [`PipeMonadic`](../providers/monad/pipe_monadic.md) resolves the stacked monad first, then walks the handler list asking [`MonadicBind`](./monadic_bind.md) to turn each continuation into a bind step. Because the transformer forms implement [`ContainsValue`](./contains_value.md) and @@ -132,7 +132,7 @@ bound rather than saying the marker is not stackable. step. - [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) — the two traits that run one step, where these two build the pipeline. -- [Monad providers](../providers/monad_providers.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers, including the transformer forms. - [`Computer`](../components/computer.md) — the component family a monadic pipeline implements. - [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. diff --git a/example-code/README.md b/example-code/README.md index b42a2220..fdb11570 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -19,7 +19,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — sixteen files under `src/concepts/`, one per page that shows code | -| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, and the `traits/` pages that show checkable code; the section is being filled in lazily | +| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, the `traits/` pages that show checkable code, and most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`); the section is being filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `src/cargo_cgp/` | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/src/reference/providers/dispatch/extract_field_and_handle.rs b/example-code/src/reference/providers/dispatch/extract_field_and_handle.rs new file mode 100644 index 00000000..3cfab232 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/extract_field_and_handle.rs @@ -0,0 +1,83 @@ +//! Code from `docs/reference/providers/dispatch/extract_field_and_handle.md` — `ExtractFieldAndHandle`. + +/// ## Usage and Examples +/// +/// `ExtractFieldAndHandle` is the per-variant adapter a matcher's list is built from. It +/// tries to extract the variant named `Tag`; on success it hands the payload, still tagged, to +/// `Provider`. Here each variant of `Shape` gets its own adapter, wrapped in `HandleFieldValue` so the +/// handler receives the bare payload. +pub mod one_adapter_per_variant { + use core::marker::PhantomData; + + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_new_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: MatchWithHandlers< + Product![ + ExtractFieldAndHandle>, + ExtractFieldAndHandle>, + ] + >, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), Shape), + } + } + } + + #[test] + fn the_adapter_extracts_its_variant_and_forwards_the_payload() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!( + app.compute(code, Shape::Rectangle(Rectangle { width: 2.0, height: 5.0 })), + 10.0, + ); + } +} diff --git a/example-code/src/reference/providers/dispatch/handle_field_value.rs b/example-code/src/reference/providers/dispatch/handle_field_value.rs new file mode 100644 index 00000000..25843a2f --- /dev/null +++ b/example-code/src/reference/providers/dispatch/handle_field_value.rs @@ -0,0 +1,82 @@ +//! Code from `docs/reference/providers/dispatch/handle_field_value.md` — `HandleFieldValue`. + +/// ## Usage and Examples +/// +/// `HandleFieldValue` strips the `Field` wrapper an extract adapter delivers and +/// passes the bare `Value` to `Provider`. That is what lets an ordinary computer over the payload type +/// serve as a per-variant handler. Here `ComputeArea` is a plain computer over each payload type, +/// reached through `HandleFieldValue`. +pub mod unwrapping_the_field { + use core::marker::PhantomData; + + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + // A plain computer over the bare payload type; it never sees the `Field` wrapper. + #[cgp_new_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: MatchWithHandlers< + Product![ + ExtractFieldAndHandle>, + ExtractFieldAndHandle>, + ] + >, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), Shape), + } + } + } + + #[test] + fn the_handler_receives_the_bare_payload() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + let circle = app.compute(code, Shape::Circle(Circle { radius: 2.0 })); + assert!((circle - 4.0 * core::f64::consts::PI).abs() < 1e-9); + } +} diff --git a/example-code/src/reference/providers/dispatch/match_with_field_handlers.rs b/example-code/src/reference/providers/dispatch/match_with_field_handlers.rs new file mode 100644 index 00000000..6a22fbe0 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/match_with_field_handlers.rs @@ -0,0 +1,69 @@ +//! Code from `docs/reference/providers/dispatch/match_with_field_handlers.md` — `MatchWithFieldHandlers`. + +/// ## Usage and Examples +/// +/// `MatchWithFieldHandlers` builds the per-variant list from the enum's fields like +/// `MatchWithValueHandlers`, but hands each payload to the provider as a `Field` with the +/// variant tag still attached. Here one handler over `Field` serves every variant, and the +/// same wiring serves a wider enum with no new arm. +pub mod matching_with_the_tag_attached { + use core::convert::Infallible; + use core::fmt::Display; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::dispatch::MatchWithFieldHandlers; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum Reading { + Temperature(u64), + Label(String), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum ExtendedReading { + Temperature(u64), + Label(String), + Flag(bool), + } + + // The payload arrives as a `Field`, so the handler still has the variant tag. + #[cgp_computer] + pub fn field_to_string(Field { value, .. }: Field) -> String + where + Value: Display, + { + value.to_string() + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ComputerComponent: MatchWithFieldHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: [((), Reading), ((), ExtendedReading)], + } + } + } + + #[test] + fn one_handler_serves_every_variant_of_two_enums() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(app.compute(code, Reading::Temperature(21)), "21"); + assert_eq!(app.compute(code, Reading::Label("north".to_owned())), "north"); + assert_eq!(app.compute(code, ExtendedReading::Flag(true)), "true"); + } +} diff --git a/example-code/src/reference/providers/dispatch/match_with_handlers.rs b/example-code/src/reference/providers/dispatch/match_with_handlers.rs new file mode 100644 index 00000000..3b07cf6a --- /dev/null +++ b/example-code/src/reference/providers/dispatch/match_with_handlers.rs @@ -0,0 +1,86 @@ +//! Code from `docs/reference/providers/dispatch/match_with_handlers.md` — `MatchWithHandlers`. + +/// ## Usage and Examples +/// +/// `MatchWithHandlers` runs a spelled-out list of per-variant adapters over an enum, stopping at the +/// first match. Each adapter extracts one variant and hands its payload to a handler; the list is +/// exhaustive, so no wildcard arm is needed. +pub mod matching_an_explicit_list { + use core::marker::PhantomData; + + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + // One provider handles every payload type, with an impl per shape. + #[cgp_new_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: MatchWithHandlers< + Product![ + ExtractFieldAndHandle>, + ExtractFieldAndHandle>, + ] + >, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), Shape), + } + } + } + + #[test] + fn the_first_matching_arm_handles_the_value() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!( + app.compute(code, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), + 12.0, + ); + + let circle = app.compute(code, Shape::Circle(Circle { radius: 1.0 })); + assert!((circle - core::f64::consts::PI).abs() < 1e-9); + } +} diff --git a/example-code/src/reference/providers/dispatch/match_with_value_handlers.rs b/example-code/src/reference/providers/dispatch/match_with_value_handlers.rs new file mode 100644 index 00000000..0caa2274 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/match_with_value_handlers.rs @@ -0,0 +1,88 @@ +//! Code from `docs/reference/providers/dispatch/match_with_value_handlers.md` — `MatchWithValueHandlers`. + +/// ## Usage and Examples +/// +/// `MatchWithValueHandlers` builds the per-variant handler list from the enum's own fields and passes +/// each payload as a bare value. Wired through `UseInputDelegate`, it is selected when the input is a +/// `Shape`, and each payload routes back through the context's own `ComputerComponent` to its handler. +pub mod matching_by_value { + use core::convert::Infallible; + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::dispatch::MatchWithValueHandlers; + use cgp::extra::handler::{Computer, ComputerComponent, UseInputDelegate}; + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_new_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + + ComputerComponent: UseInputDelegate, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: [((), Shape), ((), Circle), ((), Rectangle)], + } + } + } + + #[test] + fn each_variant_reaches_its_handler() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!( + app.compute(code, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), + 12.0, + ); + + let circle = app.compute(code, Shape::Circle(Circle { radius: 1.0 })); + assert!((circle - core::f64::consts::PI).abs() < 1e-9); + } +} diff --git a/example-code/src/reference/providers/dispatch/mod.rs b/example-code/src/reference/providers/dispatch/mod.rs new file mode 100644 index 00000000..ae054449 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/mod.rs @@ -0,0 +1,7 @@ +//! Code from the pages under `docs/reference/providers/dispatch/`, one module per page. + +pub mod extract_field_and_handle; +pub mod handle_field_value; +pub mod match_with_field_handlers; +pub mod match_with_handlers; +pub mod match_with_value_handlers; diff --git a/example-code/src/reference/providers/error/debug_error.rs b/example-code/src/reference/providers/error/debug_error.rs new file mode 100644 index 00000000..6584eb50 --- /dev/null +++ b/example-code/src/reference/providers/error/debug_error.rs @@ -0,0 +1,55 @@ +//! Code from `docs/reference/providers/error/debug_error.md` — `DebugError`. + +/// ## Usage and Examples +/// +/// `DebugError` formats a `Debug` source into a `String` and forwards it to the context's own +/// `String` route, which `RaiseFrom` converts. A `String` entry must be present for it to forward +/// to. +pub mod formatting_through_debug { + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::prelude::*; + + #[cgp_component(Parser)] + #[use_type(HasErrorType.Error)] + pub trait CanParse { + fn parse(&self, raw: &str) -> Result; + } + + #[cgp_impl(new ParseNumber)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl Parser { + fn parse(&self, raw: &str) -> Result { + let parsed = raw.parse().map_err(Self::raise_error)?; + Ok(parsed) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + ParserComponent: ParseNumber, + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } + } + + mod check_app { + use super::*; + check_components! { App { ParserComponent } } + } + + #[test] + fn a_parse_error_is_carried_as_its_debug_output() { + assert_eq!(App.parse("42").unwrap(), 42); + assert!(App.parse("nope").unwrap_err().contains("ParseIntError")); + } +} diff --git a/example-code/src/reference/providers/error/discard_detail.rs b/example-code/src/reference/providers/error/discard_detail.rs new file mode 100644 index 00000000..7d95900e --- /dev/null +++ b/example-code/src/reference/providers/error/discard_detail.rs @@ -0,0 +1,53 @@ +//! Code from `docs/reference/providers/error/discard_detail.md` — `DiscardDetail`. + +/// ## Usage and Examples +/// +/// `DiscardDetail` satisfies the wrapping capability by returning the error and dropping the detail. +/// Here a base error is raised and then wrapped with a detail string; because the wrapper is +/// `DiscardDetail`, the detail is discarded and the base error propagates unchanged. +pub mod wrapping_by_discarding { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapperComponent}; + use cgp::extra::error::{DiscardDetail, RaiseFrom}; + use cgp::prelude::*; + + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self) -> Result<(), Error>; + } + + #[cgp_impl(new LoadWithContext)] + #[uses(CanRaiseError, CanWrapError)] + #[use_type(HasErrorType.Error)] + impl Loader { + fn load(&self) -> Result<(), Error> { + let base = Self::raise_error("disk offline".to_owned()); + // The detail is attached here, but the wrapper is free to drop it. + Err(Self::wrap_error(base, "while loading config".to_owned())) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + ErrorWrapperComponent: DiscardDetail, + LoaderComponent: LoadWithContext, + + @ErrorRaiserComponent.String: RaiseFrom, + } + } + + mod check_app { + use super::*; + check_components! { App { LoaderComponent } } + } + + #[test] + fn the_detail_is_dropped_and_the_error_is_unchanged() { + assert_eq!(App.load().unwrap_err(), "disk offline"); + } +} diff --git a/example-code/src/reference/providers/error/display_error.rs b/example-code/src/reference/providers/error/display_error.rs new file mode 100644 index 00000000..79c0e3ec --- /dev/null +++ b/example-code/src/reference/providers/error/display_error.rs @@ -0,0 +1,55 @@ +//! Code from `docs/reference/providers/error/display_error.md` — `DisplayError`. + +/// ## Usage and Examples +/// +/// `DisplayError` formats a `Display` source into a `String` through `to_string()` and forwards it +/// to the context's `String` route. A `String` entry must be present for it to forward to. +pub mod formatting_through_display { + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DisplayError, RaiseFrom}; + use cgp::prelude::*; + + #[cgp_component(Parser)] + #[use_type(HasErrorType.Error)] + pub trait CanParse { + fn parse(&self, raw: &str) -> Result; + } + + #[cgp_impl(new ParseNumber)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl Parser { + fn parse(&self, raw: &str) -> Result { + let parsed = raw.parse().map_err(Self::raise_error)?; + Ok(parsed) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + ParserComponent: ParseNumber, + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DisplayError, + } + } + + mod check_app { + use super::*; + check_components! { App { ParserComponent } } + } + + #[test] + fn a_parse_error_is_carried_as_its_display_message() { + assert_eq!(App.parse("42").unwrap(), 42); + // The `Display` of `ParseIntError` reads "invalid digit found in string". + assert_eq!(App.parse("nope").unwrap_err(), "invalid digit found in string"); + } +} diff --git a/example-code/src/reference/providers/error/mod.rs b/example-code/src/reference/providers/error/mod.rs new file mode 100644 index 00000000..80bf48ba --- /dev/null +++ b/example-code/src/reference/providers/error/mod.rs @@ -0,0 +1,9 @@ +//! Code from the pages under `docs/reference/providers/error/`, one module per page. + +pub mod debug_error; +pub mod discard_detail; +pub mod display_error; +pub mod panic_on_error; +pub mod raise_from; +pub mod raise_infallible; +pub mod return_error; diff --git a/example-code/src/reference/providers/error/panic_on_error.rs b/example-code/src/reference/providers/error/panic_on_error.rs new file mode 100644 index 00000000..267e8af9 --- /dev/null +++ b/example-code/src/reference/providers/error/panic_on_error.rs @@ -0,0 +1,48 @@ +//! Code from `docs/reference/providers/error/panic_on_error.md` — `PanicOnError`. + +/// ## Usage and Examples +/// +/// `PanicOnError` raises by panicking with the source error's `Debug` output rather than returning +/// an error value. It suits a context that treats an error as a fault to abort on, such as a test +/// harness. The `#[should_panic]` test is what pins that behavior. +pub mod aborting_on_error { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::PanicOnError; + use cgp::prelude::*; + + #[cgp_component(Runner)] + #[use_type(HasErrorType.Error)] + pub trait CanRun { + fn run(&self) -> Result<(), Error>; + } + + #[cgp_impl(new RunOrAbort)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl Runner { + fn run(&self) -> Result<(), Error> { + Err(Self::raise_error("unrecoverable".to_owned())) + } + } + + pub struct TestApp; + + delegate_components! { + TestApp { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: PanicOnError, + RunnerComponent: RunOrAbort, + } + } + + mod check_test_app { + use super::*; + check_components! { TestApp { RunnerComponent } } + } + + #[test] + #[should_panic] + fn raising_aborts_the_program() { + let _ = TestApp.run(); + } +} diff --git a/example-code/src/reference/providers/error/raise_from.rs b/example-code/src/reference/providers/error/raise_from.rs new file mode 100644 index 00000000..c66bd55a --- /dev/null +++ b/example-code/src/reference/providers/error/raise_from.rs @@ -0,0 +1,65 @@ +//! Code from `docs/reference/providers/error/raise_from.md` — `RaiseFrom`. + +/// ## Usage and Examples +/// +/// The page shows `RaiseFrom` wired on its own, then dispatched per source type beside a formatter. +/// One program covers both: a `String` is converted straight through `RaiseFrom` (the abstract error +/// *is* `String`, and `String: From`), while a `ParseIntError` is formatted by `DebugError` +/// and forwarded back through the same `String` route. +/// +/// The page's illustrative `ParseError` key is a real `ParseIntError` here, so the parse can run. +pub mod raising_through_from { + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::prelude::*; + + #[cgp_component(PortParser)] + #[use_type(HasErrorType.Error)] + pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; + } + + #[cgp_impl(new ParsePort)] + #[uses(CanRaiseError, CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + let parsed: u32 = raw.parse().map_err(Self::raise_error)?; + + if parsed > u16::MAX as u32 { + // Raised as a `String`, converted straight through by `RaiseFrom`. + return Err(Self::raise_error(format!("port {parsed} out of range"))); + } + + Ok(parsed as u16) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + PortParserComponent: ParsePort, + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } + } + + mod check_app { + use super::*; + check_components! { App { PortParserComponent } } + } + + #[test] + fn a_string_is_converted_and_a_parse_error_is_formatted() { + assert_eq!(App.parse_port("8080").unwrap(), 8080); + assert_eq!(App.parse_port("70000").unwrap_err(), "port 70000 out of range"); + assert!(App.parse_port("nope").unwrap_err().contains("ParseIntError")); + } +} diff --git a/example-code/src/reference/providers/error/raise_infallible.rs b/example-code/src/reference/providers/error/raise_infallible.rs new file mode 100644 index 00000000..71fe9890 --- /dev/null +++ b/example-code/src/reference/providers/error/raise_infallible.rs @@ -0,0 +1,58 @@ +//! Code from `docs/reference/providers/error/raise_infallible.md` — `RaiseInfallible`. + +/// ## Usage and Examples +/// +/// `RaiseInfallible` fills the raiser slot for `core::convert::Infallible` on a context whose +/// operation cannot fail. The `Infallible` value is never constructed, so the raise path is wired +/// but never taken at run time; `check_components!` is what proves the wiring resolves. A second +/// source, a `String`, uses `RaiseFrom` beside it. +pub mod absorbing_an_impossible_error { + use core::convert::Infallible; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{RaiseFrom, RaiseInfallible}; + use cgp::prelude::*; + + #[cgp_component(Runner)] + #[use_type(HasErrorType.Error)] + pub trait CanRun { + fn run(&self) -> Result<(), Error>; + } + + #[cgp_impl(new RunInfallibly)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl Runner { + fn run(&self) -> Result<(), Error> { + // A step that cannot fail. Its `Infallible` error is raised uniformly, which lets this + // provider be wired the same way as one whose step can fail. + let outcome: Result<(), Infallible> = Ok(()); + outcome.map_err(Self::raise_error)?; + Ok(()) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + RunnerComponent: RunInfallibly, + + @ErrorRaiserComponent.Infallible: RaiseInfallible, + @ErrorRaiserComponent.String: RaiseFrom, + } + } + + mod check_app { + use super::*; + check_components! { App { RunnerComponent } } + } + + #[test] + fn the_infallible_step_runs() { + assert_eq!(App.run(), Ok(())); + } +} diff --git a/example-code/src/reference/providers/error/return_error.rs b/example-code/src/reference/providers/error/return_error.rs new file mode 100644 index 00000000..7eff7232 --- /dev/null +++ b/example-code/src/reference/providers/error/return_error.rs @@ -0,0 +1,79 @@ +//! Code from `docs/reference/providers/error/return_error.md` — `ReturnError`. + +/// ## Usage and Examples +/// +/// `ReturnError` raises a source that already *is* the context's error type, so it returns its +/// argument. Here the context's error is `AppError`: an `AppError` source is raised through +/// `ReturnError`, and a `ParseIntError` is formatted and forwarded to the `String` route that +/// `RaiseFrom` converts (`AppError: From`). +pub mod returning_the_error_itself { + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DebugError, RaiseFrom, ReturnError}; + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct AppError { + pub message: String, + } + + impl From for AppError { + fn from(message: String) -> Self { + AppError { message } + } + } + + #[cgp_component(Checker)] + #[use_type(HasErrorType.Error)] + pub trait CanCheck { + fn check(&self, raw: &str) -> Result; + } + + #[cgp_impl(new CheckPort)] + #[uses(CanRaiseError, CanRaiseError)] + #[use_type(HasErrorType.{Error = AppError})] + impl Checker { + fn check(&self, raw: &str) -> Result { + let parsed: u32 = raw.parse().map_err(Self::raise_error)?; + + if parsed == 0 { + // Already an `AppError`, raised by returning it. + return Err(Self::raise_error(AppError { + message: "port 0 is reserved".to_owned(), + })); + } + + Ok(parsed as u16) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + CheckerComponent: CheckPort, + + @ErrorRaiserComponent.AppError: ReturnError, + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } + } + + mod check_app { + use super::*; + check_components! { App { CheckerComponent } } + } + + #[test] + fn an_app_error_source_is_returned_unchanged() { + assert_eq!(App.check("8080").unwrap(), 8080); + assert_eq!( + App.check("0").unwrap_err(), + AppError { message: "port 0 is reserved".to_owned() }, + ); + } +} diff --git a/example-code/src/reference/providers/handler/compose_handlers.rs b/example-code/src/reference/providers/handler/compose_handlers.rs new file mode 100644 index 00000000..4c9239a1 --- /dev/null +++ b/example-code/src/reference/providers/handler/compose_handlers.rs @@ -0,0 +1,44 @@ +//! Code from `docs/reference/providers/handler/compose_handlers.md` — `ComposeHandlers`. + +/// ## Usage and Examples +/// +/// `ComposeHandlers` runs `A`, then `B` on `A`'s output. Here `Double` then `AddOne` turns an +/// input of 5 into `(5 * 2) + 1`. +pub mod composing_two_handlers { + use cgp::extra::handler::{ComposeHandlers, ComputerComponent}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn double(value: u64) -> u64 { + value * 2 + } + + #[cgp_computer] + pub fn add_one(value: u64) -> u64 { + value + 1 + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: ComposeHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), u64), + } + } + } + + #[test] + fn the_output_of_the_first_feeds_the_second() { + use cgp::extra::handler::CanCompute; + + assert_eq!(App.compute(PhantomData::<()>, 5u64), 11); + } +} diff --git a/example-code/src/reference/providers/handler/mod.rs b/example-code/src/reference/providers/handler/mod.rs new file mode 100644 index 00000000..d9e06704 --- /dev/null +++ b/example-code/src/reference/providers/handler/mod.rs @@ -0,0 +1,15 @@ +//! Code from the pages under `docs/reference/providers/handler/`, one module per page. + +pub mod compose_handlers; +pub mod pipe_handlers; +pub mod promote; +pub mod promote_async; +pub mod promote_async_computer; +pub mod promote_computer; +pub mod promote_handler; +pub mod promote_producer; +pub mod promote_ref; +pub mod promote_try_computer; +pub mod return_input; +pub mod try_promote; +pub mod use_input_delegate; diff --git a/example-code/src/reference/providers/handler/pipe_handlers.rs b/example-code/src/reference/providers/handler/pipe_handlers.rs new file mode 100644 index 00000000..166e3482 --- /dev/null +++ b/example-code/src/reference/providers/handler/pipe_handlers.rs @@ -0,0 +1,74 @@ +//! Code from `docs/reference/providers/handler/pipe_handlers.md` — `PipeHandlers`. + +/// ## Usage and Examples +/// +/// `PipeHandlers` folds a list of handlers into one pipeline. `Multiply` and `Add` each +/// read a factor or addend from a context field, so the three-stage list computes +/// `((5 * foo) + bar) * baz`. +pub mod a_pipeline_of_field_readers { + use core::marker::PhantomData; + + use cgp::extra::handler::{Computer, ComputerComponent, PipeHandlers}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Multiply + where + Context: HasField, + { + type Output = u64; + + fn compute(context: &Context, _code: PhantomData, input: u64) -> u64 { + input * context.get_field(PhantomData) + } + } + + #[cgp_new_provider] + impl Computer for Add + where + Context: HasField, + { + type Output = u64; + + fn compute(context: &Context, _code: PhantomData, input: u64) -> u64 { + input + context.get_field(PhantomData) + } + } + + #[derive(HasField)] + pub struct App { + pub foo: u64, + pub bar: u64, + pub baz: u64, + } + + delegate_components! { + App { + ComputerComponent: PipeHandlers< + Product![ + Multiply, + Add, + Multiply, + ] + >, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), u64), + } + } + } + + #[test] + fn the_stages_run_left_to_right() { + use cgp::extra::handler::CanCompute; + + let app = App { foo: 2, bar: 3, baz: 4 }; + // ((5 * 2) + 3) * 4 + assert_eq!(app.compute(PhantomData::<()>, 5u64), 52); + } +} diff --git a/example-code/src/reference/providers/handler/promote.rs b/example-code/src/reference/providers/handler/promote.rs new file mode 100644 index 00000000..07cf68f4 --- /dev/null +++ b/example-code/src/reference/providers/handler/promote.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/providers/handler/promote.md` — `Promote`. + +/// ## Usage and Examples +/// +/// `Promote` lifts a provider up the family. Here a plain `Computer` (`Double`) fills a `TryComputer` +/// slot: `Promote` wraps its infallible result in `Ok`. +pub mod lifting_a_computer_into_a_try_computer { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{Promote, TryComputerComponent}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn double(value: u64) -> u64 { + value * 2 + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + TryComputerComponent: Promote, + } + } + + mod check_app { + use super::*; + check_components! { + App { + TryComputerComponent: ((), u64), + } + } + } + + #[test] + fn the_infallible_result_is_wrapped_in_ok() { + use cgp::extra::handler::CanTryCompute; + + assert_eq!(App.try_compute(PhantomData::<()>, 5u64), Ok(10)); + } +} diff --git a/example-code/src/reference/providers/handler/promote_async.rs b/example-code/src/reference/providers/handler/promote_async.rs new file mode 100644 index 00000000..101621b2 --- /dev/null +++ b/example-code/src/reference/providers/handler/promote_async.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/providers/handler/promote_async.md` — `PromoteAsync`. + +/// ## Usage and Examples +/// +/// `PromoteAsync` lifts a synchronous provider into an asynchronous one. Here a plain `Computer` +/// (`Double`) fills an `AsyncComputer` slot; the returned future is ready immediately. +pub mod lifting_a_computer_into_an_async_computer { + use cgp::extra::handler::{AsyncComputerComponent, PromoteAsync}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn double(value: u64) -> u64 { + value * 2 + } + + pub struct App; + + delegate_components! { + App { + AsyncComputerComponent: PromoteAsync, + } + } + + mod check_app { + use super::*; + check_components! { + App { + AsyncComputerComponent: ((), u64), + } + } + } + + #[test] + fn the_synchronous_provider_runs_in_an_async_method() { + use cgp::extra::handler::CanComputeAsync; + use futures::executor::block_on; + + assert_eq!(block_on(App.compute_async(PhantomData::<()>, 5u64)), 10); + } +} diff --git a/example-code/src/reference/providers/handler/promote_async_computer.rs b/example-code/src/reference/providers/handler/promote_async_computer.rs new file mode 100644 index 00000000..69802ecc --- /dev/null +++ b/example-code/src/reference/providers/handler/promote_async_computer.rs @@ -0,0 +1,52 @@ +//! Code from `docs/reference/providers/handler/promote_async_computer.md` — `PromoteAsyncComputer`. + +/// ## Usage and Examples +/// +/// `PromoteAsyncComputer` fills the family from an infallible async base. It answers +/// `HandlerComponent` (and the async-ref members) but not `AsyncComputerComponent`, so the base is +/// wired to `AsyncComputerComponent` directly and the bundle fills in the rest. +pub mod filling_the_family_from_an_async_computer { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{AsyncComputerComponent, HandlerComponent, PromoteAsyncComputer}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn double(value: u64) -> u64 { + value * 2 + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + + AsyncComputerComponent: Double, + HandlerComponent: PromoteAsyncComputer, + } + } + + mod check_app { + use super::*; + check_components! { + App { + AsyncComputerComponent: ((), u64), + HandlerComponent: ((), u64), + } + } + } + + #[test] + fn the_async_base_answers_the_family() { + use cgp::extra::handler::{CanComputeAsync, CanHandle}; + use futures::executor::block_on; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(block_on(app.compute_async(code, 5u64)), 10); + assert_eq!(block_on(app.handle(code, 5u64)), Ok(10)); + } +} diff --git a/example-code/src/reference/providers/handler/promote_computer.rs b/example-code/src/reference/providers/handler/promote_computer.rs new file mode 100644 index 00000000..61f560a4 --- /dev/null +++ b/example-code/src/reference/providers/handler/promote_computer.rs @@ -0,0 +1,64 @@ +//! Code from `docs/reference/providers/handler/promote_computer.md` — `PromoteComputer`. + +/// ## Usage and Examples +/// +/// `PromoteComputer` fills in every family member *other than* `ComputerComponent`. The base provider +/// answers `ComputerComponent`, and the bundle answers the rest, so one `Computer` implementation +/// serves the whole family. +pub mod filling_the_family_from_a_computer { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{ + AsyncComputerComponent, ComputerComponent, HandlerComponent, PromoteComputer, + TryComputerComponent, + }; + use cgp::prelude::*; + + #[cgp_computer] + pub fn double(value: u64) -> u64 { + value * 2 + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + + // The base answers `ComputerComponent`; the bundle fills in the rest of the family. + ComputerComponent: Double, + [ + TryComputerComponent, + AsyncComputerComponent, + HandlerComponent, + ]: PromoteComputer, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), u64), + TryComputerComponent: ((), u64), + AsyncComputerComponent: ((), u64), + HandlerComponent: ((), u64), + } + } + } + + #[test] + fn one_computer_answers_the_family() { + use cgp::extra::handler::{CanCompute, CanComputeAsync, CanHandle, CanTryCompute}; + use futures::executor::block_on; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(app.compute(code, 5u64), 10); + assert_eq!(app.try_compute(code, 5u64), Ok(10)); + assert_eq!(block_on(app.compute_async(code, 5u64)), 10); + assert_eq!(block_on(app.handle(code, 5u64)), Ok(10)); + } +} diff --git a/example-code/src/reference/providers/handler/promote_handler.rs b/example-code/src/reference/providers/handler/promote_handler.rs new file mode 100644 index 00000000..5f91fe69 --- /dev/null +++ b/example-code/src/reference/providers/handler/promote_handler.rs @@ -0,0 +1,50 @@ +//! Code from `docs/reference/providers/handler/promote_handler.md` — `PromoteHandler`. + +/// ## Usage and Examples +/// +/// `PromoteHandler` fills the family from the most general base, a `Handler`. It answers +/// `HandlerComponent` and `HandlerRefComponent`, so those are routed to it; a base computer returning +/// a `Result` supplies the fallible async behavior. +pub mod filling_the_family_from_a_handler { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{HandlerComponent, PromoteHandler}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn checked_add(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "overflow".to_owned()) + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + + HandlerComponent: PromoteHandler, + } + } + + mod check_app { + use super::*; + check_components! { + App { + HandlerComponent: ((), (u64, u64)), + } + } + } + + #[test] + fn the_handler_base_answers_the_family() { + use cgp::extra::handler::CanHandle; + use futures::executor::block_on; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(block_on(app.handle(code, (1u64, 2u64))), Ok(3)); + assert_eq!(block_on(app.handle(code, (u64::MAX, 1u64))), Err("overflow".to_owned())); + } +} diff --git a/example-code/src/reference/providers/handler/promote_producer.rs b/example-code/src/reference/providers/handler/promote_producer.rs new file mode 100644 index 00000000..c9278449 --- /dev/null +++ b/example-code/src/reference/providers/handler/promote_producer.rs @@ -0,0 +1,49 @@ +//! Code from `docs/reference/providers/handler/promote_producer.md` — `PromoteProducer`. + +/// ## Usage and Examples +/// +/// `PromoteProducer` fills in the input-taking family members from an input-free `Producer`. The base +/// answers `ProducerComponent`, and the bundle answers `ComputerComponent` (and the rest) by +/// discarding the input and calling the producer. +pub mod filling_the_family_from_a_producer { + use cgp::extra::handler::{ComputerComponent, ProducerComponent, PromoteProducer}; + use cgp::prelude::*; + + #[cgp_producer] + pub fn make_default() -> u64 { + 42 + } + + pub struct App; + + delegate_components! { + App { + // The base answers `ProducerComponent`; the bundle answers `ComputerComponent` by + // discarding the input and calling the producer. + ProducerComponent: MakeDefault, + ComputerComponent: PromoteProducer, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ProducerComponent: (), + ComputerComponent: ((), u64), + } + } + } + + #[test] + fn the_produced_value_flows_out_of_every_shape() { + use cgp::extra::handler::{CanCompute, CanProduce}; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(app.produce(code), 42); + // The computer shape discards its input and produces the same value. + assert_eq!(app.compute(code, 999u64), 42); + } +} diff --git a/example-code/src/reference/providers/handler/promote_ref.rs b/example-code/src/reference/providers/handler/promote_ref.rs new file mode 100644 index 00000000..12fa6c38 --- /dev/null +++ b/example-code/src/reference/providers/handler/promote_ref.rs @@ -0,0 +1,48 @@ +//! Code from `docs/reference/providers/handler/promote_ref.md` — `PromoteRef`. + +/// ## Usage and Examples +/// +/// `PromoteRef` bridges by-value and by-reference handlers. To fill a by-reference slot such as +/// `ComputerRefComponent`, the inner provider is a by-value provider whose input is a reference; the +/// bridge calls it on the borrowed input. +pub mod bridging_value_and_reference { + use core::marker::PhantomData; + + use cgp::extra::handler::{Computer, ComputerRefComponent, PromoteRef}; + use cgp::prelude::*; + + /// A by-value computer whose input is a reference: doubles the value behind it. + #[cgp_new_provider] + impl Computer for DoubleRef { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: &u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + ComputerRefComponent: PromoteRef, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerRefComponent: ((), u64), + } + } + } + + #[test] + fn the_by_reference_slot_is_served_from_the_inner_provider() { + use cgp::extra::handler::CanComputeRef; + + let app = App; + assert_eq!(app.compute_ref(PhantomData::<()>, &5u64), 10); + } +} diff --git a/example-code/src/reference/providers/handler/promote_try_computer.rs b/example-code/src/reference/providers/handler/promote_try_computer.rs new file mode 100644 index 00000000..f5b85670 --- /dev/null +++ b/example-code/src/reference/providers/handler/promote_try_computer.rs @@ -0,0 +1,52 @@ +//! Code from `docs/reference/providers/handler/promote_try_computer.md` — `PromoteTryComputer`. + +/// ## Usage and Examples +/// +/// `PromoteTryComputer` fills the family from a synchronous fallible base. It answers +/// `TryComputerComponent` and the async members, so those are routed to it; a base computer returning +/// a `Result` supplies the fallible behavior. +pub mod filling_the_family_from_a_try_computer { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{HandlerComponent, PromoteTryComputer, TryComputerComponent}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn checked_add(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "overflow".to_owned()) + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + + [TryComputerComponent, HandlerComponent]: PromoteTryComputer, + } + } + + mod check_app { + use super::*; + check_components! { + App { + TryComputerComponent: ((), (u64, u64)), + HandlerComponent: ((), (u64, u64)), + } + } + } + + #[test] + fn the_fallible_base_answers_the_family() { + use cgp::extra::handler::{CanHandle, CanTryCompute}; + use futures::executor::block_on; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(app.try_compute(code, (1u64, 2u64)), Ok(3)); + assert_eq!(app.try_compute(code, (u64::MAX, 1u64)), Err("overflow".to_owned())); + assert_eq!(block_on(app.handle(code, (1u64, 2u64))), Ok(3)); + } +} diff --git a/example-code/src/reference/providers/handler/return_input.rs b/example-code/src/reference/providers/handler/return_input.rs new file mode 100644 index 00000000..9067a7ea --- /dev/null +++ b/example-code/src/reference/providers/handler/return_input.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/providers/handler/return_input.md` — `ReturnInput`. + +/// ## Usage and Examples +/// +/// `ReturnInput` is the identity handler: it returns its input unchanged. Here it is the middle stage +/// of a pipeline, so the pipeline behaves as though the stage were not there. +pub mod the_identity_stage { + use cgp::extra::handler::{ComputerComponent, PipeHandlers, ReturnInput}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn add_one(value: u64) -> u64 { + value + 1 + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: PipeHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), u64), + } + } + } + + #[test] + fn the_input_passes_straight_through() { + use cgp::extra::handler::CanCompute; + + // AddOne, then ReturnInput (a no-op), then AddOne: 5 -> 6 -> 6 -> 7. + assert_eq!(App.compute(PhantomData::<()>, 5u64), 7); + } +} diff --git a/example-code/src/reference/providers/handler/try_promote.rs b/example-code/src/reference/providers/handler/try_promote.rs new file mode 100644 index 00000000..a189b999 --- /dev/null +++ b/example-code/src/reference/providers/handler/try_promote.rs @@ -0,0 +1,49 @@ +//! Code from `docs/reference/providers/handler/try_promote.md` — `TryPromote`. + +/// ## Usage and Examples +/// +/// `TryPromote` turns a `Computer` that *returns* a `Result` into a genuine `TryComputer`, unwrapping +/// the `Result` into the fallible interface. The context's error type is what the `Result`'s error +/// arm becomes. +pub mod unwrapping_a_result_output { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{TryComputerComponent, TryPromote}; + use cgp::prelude::*; + + /// A computer whose output is itself a `Result`. + #[cgp_computer] + pub fn checked_add(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "overflow".to_owned()) + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + TryComputerComponent: TryPromote, + } + } + + mod check_app { + use super::*; + check_components! { + App { + TryComputerComponent: ((), (u64, u64)), + } + } + } + + #[test] + fn the_result_becomes_the_fallible_interface() { + use cgp::extra::handler::CanTryCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(app.try_compute(code, (1u64, 2u64)), Ok(3)); + assert_eq!(app.try_compute(code, (u64::MAX, 1u64)), Err("overflow".to_owned())); + } +} diff --git a/example-code/src/reference/providers/handler/use_input_delegate.rs b/example-code/src/reference/providers/handler/use_input_delegate.rs new file mode 100644 index 00000000..379e71ed --- /dev/null +++ b/example-code/src/reference/providers/handler/use_input_delegate.rs @@ -0,0 +1,66 @@ +//! Code from `docs/reference/providers/handler/use_input_delegate.md` — `UseInputDelegate`. + +/// ## Usage and Examples +/// +/// `UseInputDelegate` chooses the handler by the type of the input. Here a `Circle` input routes to +/// `CircleArea` and a `Rectangle` input to `RectangleArea`, through one wiring entry keyed on the +/// input type. +pub mod dispatching_on_the_input_type { + use cgp::extra::handler::{ComputerComponent, UseInputDelegate}; + use cgp::prelude::*; + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_computer] + pub fn circle_area(circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + + #[cgp_computer] + pub fn rectangle_area(rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: UseInputDelegate, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: [((), Circle), ((), Rectangle)], + } + } + } + + #[test] + fn each_input_reaches_its_own_handler() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!( + app.compute(code, Rectangle { width: 3.0, height: 4.0 }), + 12.0, + ); + + let area = app.compute(code, Circle { radius: 1.0 }); + assert!((area - core::f64::consts::PI).abs() < 1e-9); + } +} diff --git a/example-code/src/reference/providers/mod.rs b/example-code/src/reference/providers/mod.rs index 0a133ed5..ec25449d 100644 --- a/example-code/src/reference/providers/mod.rs +++ b/example-code/src/reference/providers/mod.rs @@ -4,6 +4,10 @@ //! or reviewed rather than the section's full inventory. pub mod chain_getters; +pub mod error; +pub mod dispatch; +pub mod handler; +pub mod monad; pub mod redirect_lookup; pub mod use_context; pub mod use_default; diff --git a/example-code/src/reference/providers/monad/bind_err.rs b/example-code/src/reference/providers/monad/bind_err.rs new file mode 100644 index 00000000..fbf90573 --- /dev/null +++ b/example-code/src/reference/providers/monad/bind_err.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/providers/monad/bind_err.md` — `BindErr`. + +/// ## Usage and Examples +/// +/// `BindErr` is one bind step of the err monad: it runs its continuation on the `Ok` value and +/// short-circuits on `Err`. This is what `PipeMonadic` composes internally under `ErrMonadic`; the +/// page shows it built by hand inside a `PipeHandlers` list, which is the one time it is named +/// directly. +pub mod one_hand_built_bind_step { + use cgp::prelude::*; + + #[cgp_computer] + pub fn increment(value: u8) -> Result { + value.checked_add(1).ok_or("overflow") + } + + #[test] + fn the_bind_runs_the_continuation_on_the_ok_value() { + use cgp::extra::handler::PipeHandlers; + use cgp::extra::monad::monadic::err::BindErr; + use cgp::extra::monad::monadic::ident::IdentMonadic; + + // 1 -> Ok(2); BindErr runs the second Increment on 2 -> Ok(3). + assert_eq!( + PipeHandlers::]>::compute( + &(), + PhantomData::<()>, + 1u8, + ), + Ok(3), + ); + + // The first step overflows, so the bind short-circuits and the continuation never runs. + assert_eq!( + PipeHandlers::]>::compute( + &(), + PhantomData::<()>, + 255u8, + ), + Err("overflow"), + ); + } +} diff --git a/example-code/src/reference/providers/monad/bind_ok.rs b/example-code/src/reference/providers/monad/bind_ok.rs new file mode 100644 index 00000000..7a371cc8 --- /dev/null +++ b/example-code/src/reference/providers/monad/bind_ok.rs @@ -0,0 +1,53 @@ +//! Code from `docs/reference/providers/monad/bind_ok.md` — `BindOk`. + +/// ## Usage and Examples +/// +/// `BindOk` is the mirror of `BindErr`: it runs its continuation on the `Err` value and +/// short-circuits on `Ok`, which is the fallback behavior `PipeMonadic` composes under `OkMonadic`. +/// The page shows it built by hand inside a `PipeHandlers` list. +pub mod one_hand_built_bind_step { + use cgp::prelude::*; + + /// Accept a small value, or hand a too-large one to the fallback as an `Err`. + #[cgp_computer] + pub fn classify(value: u8) -> Result { + if value < 10 { + Ok(value) + } else { + Err(value) + } + } + + /// The fallback: run only on the `Err` branch, halving the rejected value. + #[cgp_computer] + pub fn halve(value: u8) -> Result { + Ok(value / 2) + } + + #[test] + fn the_bind_runs_the_continuation_on_the_err_value() { + use cgp::extra::handler::PipeHandlers; + use cgp::extra::monad::monadic::ident::IdentMonadic; + use cgp::extra::monad::monadic::ok::BindOk; + + // 5 is accepted, so BindOk short-circuits and the fallback never runs. + assert_eq!( + PipeHandlers::]>::compute( + &(), + PhantomData::<()>, + 5u8, + ), + Ok(5), + ); + + // 20 is rejected, so BindOk runs the fallback on the Err value: 20 -> 10. + assert_eq!( + PipeHandlers::]>::compute( + &(), + PhantomData::<()>, + 20u8, + ), + Ok(10), + ); + } +} diff --git a/example-code/src/reference/providers/monad/mod.rs b/example-code/src/reference/providers/monad/mod.rs new file mode 100644 index 00000000..6748082e --- /dev/null +++ b/example-code/src/reference/providers/monad/mod.rs @@ -0,0 +1,5 @@ +//! Code from the pages under `docs/reference/providers/monad/`, one module per page. + +pub mod bind_err; +pub mod bind_ok; +pub mod pipe_monadic; diff --git a/example-code/src/reference/providers/monad/pipe_monadic.rs b/example-code/src/reference/providers/monad/pipe_monadic.rs new file mode 100644 index 00000000..84c8cc52 --- /dev/null +++ b/example-code/src/reference/providers/monad/pipe_monadic.rs @@ -0,0 +1,59 @@ +//! Code from `docs/reference/providers/monad/pipe_monadic.md` — `PipeMonadic`. + +/// ## Usage and Examples +/// +/// `PipeMonadic` composes a handler list under a monad into one short-circuiting handler. Under +/// `ErrMonadic` each step runs on the previous step's `Ok` value and the first `Err` becomes the +/// output. The composed pipeline is wired like any other computation. +pub mod chaining_under_a_monad { + use cgp::extra::handler::ComputerComponent; + use cgp::extra::monad::monadic::err::ErrMonadic; + use cgp::extra::monad::providers::PipeMonadic; + use cgp::prelude::*; + + /// A fallible step: succeeds with the next value, or reports an overflow. + #[cgp_computer] + pub fn increment(value: u8) -> Result { + value.checked_add(1).ok_or("overflow") + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: PipeMonadic, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), u8), + } + } + } + + #[test] + fn the_first_error_becomes_the_output() { + use cgp::extra::handler::CanCompute; + + // Three successful steps. + assert_eq!(App.compute(PhantomData::<()>, 1u8), Ok(4)); + + // The third step overflows, and the remaining steps do not run. + assert_eq!(App.compute(PhantomData::<()>, 253u8), Err("overflow")); + } + + #[test] + fn invoked_directly_without_wiring() { + assert_eq!( + PipeMonadic::::compute( + &App, + PhantomData::<()>, + 1u8, + ), + Ok(4), + ); + } +} From 2b32f8f7595ee6e386a529321052969824c2b271 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 20:39:58 +0200 Subject: [PATCH 046/516] reference/providers: writing-style pass, With* alias pages, example-code coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review and revise the whole `docs/reference/providers` tree: - Fix writing style: remove the "is what" cleft hinges from the prose. (The em dashes are the site-wide `name — gloss` list convention, left as-is.) - Add dedicated pages for the five `With*` provider aliases (WithContext, WithType, WithField, WithFieldRef, WithDelegatedType), moving the per-alias explanations off with_provider.md and the use_* pages. The foundational-only aliases (WithFieldRef, WithDelegatedType) own the wiring form and worked example while their inner-provider pages keep the mechanism. WithContext is documented as rarely-used, without an unverifiable wiring claim. - Add the missing provenance footer to the providers index, cross-link the aliases, and add a ConcatPath link on redirect_lookup. - Rework the UseContext example to the realistic `EncodeVec` over `CanEncode>`, and deduplicate the cyclic bare-UseContext warning into a single Common Mistakes section. Example-code coverage (cargo test green, 0 warnings): - Mirror the four wireable alias pages (with_type, with_field, with_field_ref, with_delegated_type); use_field_ref.rs and use_delegated_type.rs move to their alias mirrors. - Add the six previously-unmirrored dispatch pages: build_and_set_field, build_and_merge, build_with_handlers, build_and_merge_outputs, downcast_and_handle, match_first_with_handlers. - Fix a pre-existing unused-import warning in modularity_hierarchy.rs by scoping the test-only import to its test. Note: use_type.md also carries an unrelated title change ("(provider)" dropped from the heading and sidebar label) that was already in the working tree. Co-Authored-By: Claude Opus 4.8 --- docs/reference/components/_category_.json | 2 +- docs/reference/providers/chain_getters.md | 2 +- .../dispatch/extract_field_and_handle.md | 4 +- .../providers/dispatch/handle_field_value.md | 2 +- .../providers/dispatch/match_with_handlers.md | 2 +- .../dispatch/match_with_value_handlers.md | 2 +- docs/reference/providers/error/debug_error.md | 2 +- docs/reference/providers/error/raise_from.md | 2 +- .../reference/providers/error/return_error.md | 2 +- docs/reference/providers/index.md | 19 ++- docs/reference/providers/monad/bind_err.md | 4 +- docs/reference/providers/redirect_lookup.md | 12 +- docs/reference/providers/use_context.md | 128 +++++++++-------- docs/reference/providers/use_default.md | 2 +- docs/reference/providers/use_delegate.md | 2 +- .../reference/providers/use_delegated_type.md | 92 ++---------- docs/reference/providers/use_field.md | 22 +-- docs/reference/providers/use_field_ref.md | 89 ++---------- docs/reference/providers/use_type.md | 28 ++-- docs/reference/providers/with_context.md | 81 +++++++++++ .../providers/with_delegated_type.md | 133 ++++++++++++++++++ docs/reference/providers/with_field.md | 111 +++++++++++++++ docs/reference/providers/with_field_ref.md | 131 +++++++++++++++++ docs/reference/providers/with_provider.md | 38 ++--- docs/reference/providers/with_type.md | 106 ++++++++++++++ .../src/concepts/modularity_hierarchy.rs | 4 +- .../providers/dispatch/build_and_merge.rs | 77 ++++++++++ .../dispatch/build_and_merge_outputs.rs | 80 +++++++++++ .../providers/dispatch/build_and_set_field.rs | 67 +++++++++ .../providers/dispatch/build_with_handlers.rs | 77 ++++++++++ .../providers/dispatch/downcast_and_handle.rs | 72 ++++++++++ .../dispatch/match_first_with_handlers.rs | 87 ++++++++++++ .../src/reference/providers/dispatch/mod.rs | 6 + example-code/src/reference/providers/mod.rs | 6 +- .../src/reference/providers/use_context.rs | 64 +++++---- .../src/reference/providers/use_field.rs | 24 +--- .../src/reference/providers/use_type.rs | 30 +--- ...legated_type.rs => with_delegated_type.rs} | 5 +- .../src/reference/providers/with_field.rs | 40 ++++++ .../{use_field_ref.rs => with_field_ref.rs} | 9 +- .../src/reference/providers/with_type.rs | 29 ++++ 41 files changed, 1311 insertions(+), 384 deletions(-) create mode 100644 docs/reference/providers/with_context.md create mode 100644 docs/reference/providers/with_delegated_type.md create mode 100644 docs/reference/providers/with_field.md create mode 100644 docs/reference/providers/with_field_ref.md create mode 100644 docs/reference/providers/with_type.md create mode 100644 example-code/src/reference/providers/dispatch/build_and_merge.rs create mode 100644 example-code/src/reference/providers/dispatch/build_and_merge_outputs.rs create mode 100644 example-code/src/reference/providers/dispatch/build_and_set_field.rs create mode 100644 example-code/src/reference/providers/dispatch/build_with_handlers.rs create mode 100644 example-code/src/reference/providers/dispatch/downcast_and_handle.rs create mode 100644 example-code/src/reference/providers/dispatch/match_first_with_handlers.rs rename example-code/src/reference/providers/{use_delegated_type.rs => with_delegated_type.rs} (74%) create mode 100644 example-code/src/reference/providers/with_field.rs rename example-code/src/reference/providers/{use_field_ref.rs => with_field_ref.rs} (72%) create mode 100644 example-code/src/reference/providers/with_type.rs diff --git a/docs/reference/components/_category_.json b/docs/reference/components/_category_.json index 58b1ac25..587a54ed 100644 --- a/docs/reference/components/_category_.json +++ b/docs/reference/components/_category_.json @@ -1,5 +1,5 @@ { - "label": "Built-in components", + "label": "Components", "position": 4, "link": { "type": "generated-index", diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 50299b36..a4125e9d 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -135,7 +135,7 @@ The head `Getter` reads `ValueA` from the `Context`, and the rest of the chain r `ValueA`, so the whole chain's `Value` is `ValueB`, the value at the end of the path. The head is applied through [`FieldMapper`](../traits/field_mapper.md) rather than `FieldGetter` directly: `map_field` hands the intermediate reference to a closure that runs the rest of the chain on it, which -is what keeps the borrowed lifetimes inferring across each hop. +keeps the borrowed lifetimes inferring across each hop. The recursion bottoms out at the empty list, where `ChainGetters` is the identity getter and returns the context it was given: diff --git a/docs/reference/providers/dispatch/extract_field_and_handle.md b/docs/reference/providers/dispatch/extract_field_and_handle.md index d95806e9..25d6e031 100644 --- a/docs/reference/providers/dispatch/extract_field_and_handle.md +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -13,7 +13,7 @@ The per-variant adapter that tries one variant and forwards its matched payload tries to extract the variant named `Tag` from the input. On success it wraps the payload in a `Field` and hands it to `Provider`, returning `Ok` of the provider's output. On failure it returns `Err` of the remainder, the extractor with that variant ruled out. It runs on a **context**, the -type a capability runs against. The `Result` shape it returns is exactly what the +type a capability runs against. It returns the `Result` shape the matcher loop expects, so a [`Product!`](../../macros/product.md) of these adapters is the list a matcher consumes. Like every CGP provider, it carries no runtime value. @@ -38,7 +38,7 @@ type Match = MatchWithHandlers`, so wrapping the inner handler -in [`HandleFieldValue`](handle_field_value.md) is what strips the tag to a bare value. The convenience +in [`HandleFieldValue`](handle_field_value.md) strips the tag to a bare value. The convenience matchers [`MatchWithValueHandlers`](match_with_value_handlers.md) and [`MatchWithFieldHandlers`](match_with_field_handlers.md) generate lists of these adapters from an enum's fields, so you rarely write them out by hand. diff --git a/docs/reference/providers/dispatch/handle_field_value.md b/docs/reference/providers/dispatch/handle_field_value.md index cb8b6a44..ad536bb1 100644 --- a/docs/reference/providers/dispatch/handle_field_value.md +++ b/docs/reference/providers/dispatch/handle_field_value.md @@ -13,7 +13,7 @@ Strip the variant tag from a matched payload and pass the bare value to an inner handler that does the work. An extract adapter such as [`ExtractFieldAndHandle`](extract_field_and_handle.md) delivers a `Field`, so the variant name stays attached to the payload. `HandleFieldValue` strips the `Field` wrapper and passes the bare -`Value` to `Provider`, on a **context**, the type a capability runs against. This is what lets an +`Value` to `Provider`, on a **context**, the type a capability runs against. This lets an ordinary computer over the payload type serve as a per-variant handler. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/dispatch/match_with_handlers.md b/docs/reference/providers/dispatch/match_with_handlers.md index e170c2b5..16014a57 100644 --- a/docs/reference/providers/dispatch/match_with_handlers.md +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -13,7 +13,7 @@ wildcard arm. `MatchWithHandlers` is the owned-input matcher. Given a value, it converts the value to its extractor and runs a list of handlers over it, stopping at the first one that matches. It runs on a **context**, the type a capability runs against. When the list is exhausted the remaining type has every -variant ruled out and is therefore uninhabited, which is what lets the matcher return the bare output +variant ruled out and is therefore uninhabited, which lets the matcher return the bare output with no fallback arm. Like every CGP provider, it carries no runtime value; the handler list rides in `PhantomData`. diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index 55887b2d..38651241 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -72,7 +72,7 @@ pub type MatchWithValueHandlers = ``` Wrapping `Provider` in [`HandleFieldValue`](handle_field_value.md) is the one difference from -[`MatchWithFieldHandlers`](match_with_field_handlers.md), and it is what makes each payload arrive as a +[`MatchWithFieldHandlers`](match_with_field_handlers.md), and it makes each payload arrive as a bare value. The list itself is assembled by the `HasFieldHandlers` machinery described on [`MatchWithFieldHandlers`](match_with_field_handlers.md#under-the-hood). The borrowed variants additionally wire the `…RefComponent` handler traits through [`PromoteRef`](../handler/promote_ref.md), diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index d038203d..70ffb11a 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -18,7 +18,7 @@ only knows how to turn a `Debug` value into a `String` and hand it off, leaving whatever string-handling provider the context already wires. Like every CGP provider, `DebugError` carries no runtime value. -This design is what lets a context handle an open-ended set of error types with one concrete +This design lets a context handle an open-ended set of error types with one concrete string-raising rule. `DebugError` routes every `Debug` source through the single `String` path, and the context wires one provider (often [`RaiseFrom`](raise_from.md)) for that path. diff --git a/docs/reference/providers/error/raise_from.md b/docs/reference/providers/error/raise_from.md index 5fb9ad59..4bda9996 100644 --- a/docs/reference/providers/error/raise_from.md +++ b/docs/reference/providers/error/raise_from.md @@ -87,7 +87,7 @@ where } ``` -The bound `Context::Error: From` is what makes one wiring cover many source types. The generated +The bound `Context::Error: From` makes one wiring cover many source types. The generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same clause, so a [check](../../macros/check_components.md) reports a missing `From` impl at the wiring site. diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md index a05422bb..633c0cf0 100644 --- a/docs/reference/providers/error/return_error.md +++ b/docs/reference/providers/error/return_error.md @@ -11,7 +11,7 @@ Raise a source error that already is the context's abstract error, so raising is `ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly the abstract error the **context** chose, where the context is the type a capability runs against. Raising then has -nothing to convert: it returns its argument untouched. This is what a context uses when generic code +nothing to convert: it returns its argument untouched. A context uses it when generic code raises a value that is already of the context's own error type. Like every CGP provider, `ReturnError` carries no runtime value. diff --git a/docs/reference/providers/index.md b/docs/reference/providers/index.md index 967a0a30..664c9532 100644 --- a/docs/reference/providers/index.md +++ b/docs/reference/providers/index.md @@ -16,8 +16,8 @@ is the fuller map for once the essentials are familiar. ## Wiring an everyday component [`UseContext`](./use_context.md) implements a provider trait by routing back through the context's own -consumer-trait implementation, which is what a higher-order provider falls back to and the default -per-variant provider a dispatch combinator routes each matched case through. +consumer-trait implementation. A higher-order provider falls back to it, and a dispatch combinator +routes each matched case through it as its default per-variant provider. [`UseType`](./use_type.md) supplies a concrete type for an abstract-type component, so a context binds its error type or runtime with one wiring line. [`UseField`](./use_field.md) implements a getter by reading a context field named by a tag, and @@ -27,15 +27,18 @@ behaviour left for a provider to supply. [`WithProvider`](./with_provider.md) is the adapter behind the `With…` aliases: it turns a foundational provider such as a field getter or a type provider into a provider for a named component, and the -aliases `WithField`, `WithType`, and `WithContext` are how it usually appears in wiring. +aliases [`WithField`](./with_field.md), [`WithType`](./with_type.md), [`WithContext`](./with_context.md), +[`WithFieldRef`](./with_field_ref.md), and [`WithDelegatedType`](./with_delegated_type.md) are how it +usually appears in wiring. ## Dispatching per type, and organizing wiring [`UseDelegate`](./use_delegate.md) chooses a provider by the type of a generic parameter through a -lookup table, the legacy form of the per-type dispatch the `open` statement now expresses. +lookup table, the legacy form of the per-type dispatch the +[`open` statement](../macros/delegate_components.md) now expresses. [`RedirectLookup`](./redirect_lookup.md) routes a component's lookup along a type-level path in a -separate table, the mechanism every namespace and `open` statement rides. Both are read in wiring far -more often than written. +separate table, the mechanism every [namespace](../macros/cgp_namespace.md) and `open` statement rides. +Both are read in wiring far more often than written. ## The specialized getters and type providers @@ -56,3 +59,7 @@ family's synchronous, async, and fallible shapes, the [dispatch combinators](./d route an extensible-data value to per-field or per-variant handlers, and the [monad providers](./monad/index.md) chain handlers that short-circuit through a monad. Each group is a subsection here with one page per provider and its own overview. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad/bind_err.md b/docs/reference/providers/monad/bind_err.md index 664ed849..9d2ca4da 100644 --- a/docs/reference/providers/monad/bind_err.md +++ b/docs/reference/providers/monad/bind_err.md @@ -27,7 +27,7 @@ use cgp::extra::monad::monadic::err::BindErr; use cgp::extra::monad::monadic::ident::IdentMonadic; use cgp::extra::handler::PipeHandlers; -// This is what PipeMonadic builds internally for a two-element list under ErrMonadic. +// PipeMonadic builds this internally for a two-element list under ErrMonadic. type Pipeline = PipeHandlers]>; // 1 -> Ok(2) -> BindErr runs the second Increment on 2 -> Ok(3) ``` @@ -51,7 +51,7 @@ pub struct BindErr(pub PhantomData<(M, Cont)>); It implements `Computer` and `AsyncComputer` for an input of `Result`. On `Ok(value)` it runs `Cont` on the value and lifts the continuation's output back through `M`. On `Err(err)` it short-circuits, lifting the error directly to the output and skipping `Cont`. It is the mirror of -[`BindOk`](bind_ok.md), which branches the other way. The `M` parameter is what lets these binds nest: at +[`BindOk`](bind_ok.md), which branches the other way. The `M` parameter lets these binds nest: at the bottom of a single-layer pipeline it is `IdentMonadic`, and a stacked monad threads a deeper monad through it. diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 0075819f..7ec74537 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -27,11 +27,11 @@ this provider is legible. table* answers it. The ordinary provider blanket impl looks a component up in the **context**'s own delegation table, keyed by the component marker, where the context is the type the capability runs against. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed by a -type-level `Path`, then delegates to whatever provider that entry holds. This indirection is what lets +type-level `Path`, then delegates to whatever provider that entry holds. This indirection lets one component's resolution be redirected to a different key in a different table, which is the basis for organizing wiring into namespaces. -The redirection is what makes namespaces work. A namespace groups a context's components under a path +The redirection makes namespaces work. A namespace groups a context's components under a path prefix so several related components can be wired in one place and addressed by a shared path. `RedirectLookup` turns a prefixed path back into a concrete provider: the namespace machinery sets a component's delegate to a `RedirectLookup` carrying the path under which the real provider was @@ -60,7 +60,7 @@ delegate_components! { } ``` -The path-keyed entry above (`@bar.baz`) is what a `RedirectLookup` later walks. The path itself is a +A `RedirectLookup` later walks the path-keyed entry above (`@bar.baz`). The path itself is a [`PathCons`](../types/type_level_spines.md) chain of [`Symbol!`](../macros/symbol.md) segments, most easily written with [`Path!`](../macros/path.md). @@ -135,11 +135,11 @@ The mechanism is one [`DelegateComponent`](../traits/delegate_component.md) look rather than on the component marker. `RedirectLookup` implements `Greeter` whenever `Components` maps `Path` to a delegate that itself implements `Greeter`, and the method forwards to that delegate. When the consumer trait carries generic type parameters, the impl additionally constrains -`Path` with `ConcatPath` so the parameters are appended to the path before the lookup, letting the -redirected key encode the generic arguments. As always, the impl is paired with a matching +`Path` with [`ConcatPath`](../traits/concat_path.md) so the parameters are appended to the path before +the lookup, letting the redirected key encode the generic arguments. As always, the impl is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl. -The `#[prefix(@path in Namespace)]` attribute is what populates the path side: it generates a namespace +The `#[prefix(@path in Namespace)]` attribute populates the path side: it generates a namespace impl whose delegate is `RedirectLookup`, with the prefix path joined onto the component marker, so resolving the component under that namespace follows the prefixed path into the table. diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index cee90c01..9f1b6dd1 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -18,17 +18,18 @@ a provider whose method bodies call the consumer method on the context, so handi This makes `UseContext` the exact dual of the consumer-trait blanket implementation that [`#[cgp_component]`](../macros/cgp_component.md) generates. That blanket impl runs in the -consumer-to-provider direction: a context implements `CanGreet` by delegating to whichever provider -implements `Greeter` for it. `UseContext` runs the other way: it implements the provider trait -`Greeter` by delegating to whatever `CanGreet` implementation the context has. One forwards the +consumer-to-provider direction: a context implements `CanEncode` by delegating to whichever provider +implements `Encoder` for it. `UseContext` runs the other way: it implements the provider trait +`Encoder` by delegating to whatever `CanEncode` implementation the context has. One forwards the consumer trait to a provider; the other forwards a provider trait back to the consumer trait. `UseContext` matters most with [higher-order providers](/docs/concepts/higher-order-providers), which -take another provider as a type parameter. A higher-order provider that wraps *one* capability while -delegating to *another* can default its inner-provider parameter to `UseContext`, so the inner step -falls back to whatever the context already wires for that other capability, and the author need not name -an explicit inner provider. Like every CGP provider, `UseContext` carries no runtime value: it is a -unit marker whose `self` position is never read. +take another provider as a type parameter. Such a provider can default its inner-provider parameter to +`UseContext`, so when no inner provider is named, the inner step falls back to whatever the context +already wires for it. That inner step may be a different capability, or the same capability at a +different type, as the example below shows by encoding a `Vec` through the context's own encoder for +`T`. Like every CGP provider, `UseContext` carries no runtime value: it is a unit marker whose `self` +position is never read. ## Usage @@ -37,53 +38,51 @@ appears in two places. Most often it is a higher-order provider's default inner the provider's struct definition: ```rust -pub struct GreetLoudly(pub PhantomData); +pub struct EncodeVec(pub PhantomData); ``` It also appears directly in a wiring entry to route a component through the context's own implementation, which is how the [dispatch combinators](dispatch/index.md) default their per-variant provider. -**Do not wire a component to `UseContext` when that component's only implementation on the context is -the delegation itself.** Doing so asks the context to implement the consumer trait by delegating to a -provider that implements the provider trait by calling the same consumer trait, a cycle the trait -solver cannot resolve. See [Common Mistakes](#common-mistakes). `UseContext` works when the provider -trait it stands in for resolves to a *different* implementation than the one being wired, which is why -it fits a wrapper that delegates to another capability. +`UseContext` stands in for a provider trait only where that trait resolves to a *different* +implementation than the one being wired: a wrapper over another capability, or a per-type dispatch entry +for a different type. ## Examples -The idiomatic use is as the default inner provider of a higher-order provider that builds one capability -on top of another. Here a loud greeter wraps an ordinary greeter, and its inner provider defaults to -`UseContext` so it reuses whatever `CanGreet` the context already wires: +The idiomatic use is as the default inner provider of a higher-order provider. `EncodeVec` encodes a +`Vec` by encoding each element through an inner provider, and defaults that inner provider to +`UseContext`, so the elements are encoded by whatever the context already wires for their type: ```rust use cgp::prelude::*; -#[cgp_component(Greeter)] -pub trait CanGreet { - fn greet(&self) -> String; -} - -#[cgp_component(LoudGreeter)] -pub trait CanGreetLoudly { - fn greet_loudly(&self) -> String; +#[cgp_component(Encoder)] +pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; } -#[cgp_impl(new GreetHello)] -impl Greeter { - fn greet(&self) -> String { - "Hello".to_owned() +#[cgp_impl(new EncodeAsText)] +impl Encoder +where + Value: core::fmt::Display, +{ + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() } } -pub struct GreetLoudly(pub PhantomData); +pub struct EncodeVec(pub PhantomData); -#[cgp_impl(GreetLoudly)] -#[use_provider(Inner: Greeter)] -impl LoudGreeter { - fn greet_loudly(&self) -> String { - format!("{}!", Inner::greet(self).to_uppercase()) +#[cgp_impl(EncodeVec)] +#[use_provider(Inner: Encoder)] +impl Encoder> { + fn encode(&self, values: &Vec) -> Vec { + values + .iter() + .flat_map(|item| Inner::encode(self, item)) + .collect() } } @@ -91,34 +90,38 @@ pub struct App; delegate_components! { App { - GreeterComponent: GreetHello, - LoudGreeterComponent: GreetLoudly, + open EncoderComponent; + + @EncoderComponent.u32: EncodeAsText, + @EncoderComponent.Vec: EncodeVec, } } ``` -`App` wires `LoudGreeterComponent` to a bare `GreetLoudly`, whose `Inner` defaults to `UseContext`. When -`app.greet_loudly()` runs, `GreetLoudly` calls `Inner::greet(self)`, which resolves through `UseContext` -to `App`'s own `CanGreet`, wired to `GreetHello`. The result is `"HELLO!"`. Because `GreetLoudly` -implements a *different* component from the one it delegates through, the delegation lands on -`GreetHello` rather than back on `GreetLoudly`, so there is no cycle. Overriding the parameter, as in -`GreetLoudly`, binds the inner greeter directly and bypasses the context's `CanGreet` +`App` uses the [`open` statement](../macros/delegate_components.md) to wire the `Encoder` component per +value type, giving `Vec` a bare `EncodeVec` whose `Inner` defaults to `UseContext`. Encoding a +`Vec` runs `EncodeVec`, which calls `Inner::encode(self, item)` on each element; `Inner` resolves +through `UseContext` to `App`'s own `CanEncode`, wired to `EncodeAsText`. So encoding +`vec![1u32, 2, 3]` produces the bytes of `"123"`. There is no cycle, because the element lookup is for a +*different* type (`u32`) than the wired one (`Vec`). Naming an explicit inner provider in place of +the `UseContext` default binds the element encoder directly and bypasses the context's `CanEncode` wiring. `UseContext` acts as a default only when the provider's struct definition gives it as the default -generic parameter, as `GreetLoudly` does. A provider without such a default has no inner provider to -fall back to, and the inner provider must always be named. +generic parameter, as `EncodeVec` does. A provider without such a default has no inner provider to fall +back to, and the inner provider must always be named. ## When to reach for it, and when not -**Reach for `UseContext` as the default inner provider of a higher-order provider that delegates to a -different capability than the one it implements**, so the wrapper reuses the context's own wiring for -that other capability when no inner provider is named. +**Reach for `UseContext` as the default inner provider of a higher-order provider**, so the wrapper +reuses the context's own wiring for the inner step when no inner provider is named. The inner step may +be a different capability, or the same capability at a different type, as `EncodeVec` delegates +`Encoder>` to the context's `Encoder`. -**Do not wire a component to `UseContext` on the context that implements it only through that -delegation.** That is the one shape it cannot serve, because the component's implementation would depend -on itself. When you want a wrapper over the *same* capability, name the inner provider explicitly rather -than defaulting to `UseContext`. +The one shape `UseContext` cannot serve is a component whose only implementation on the context is that +same delegation, which loops; [Common Mistakes](#common-mistakes) explains it. When you want a wrapper +over the *same* capability and the *same* type, name the inner provider explicitly rather than +defaulting to `UseContext`. ## Under the hood @@ -155,13 +158,14 @@ consumer-trait implementation precisely. Any supertrait bound on the consumer tr ## Common Mistakes -**Wiring a component to `UseContext` on the context that owns it creates a cycle.** If `App` wires -`GreeterComponent` to `UseContext`, then `App`'s `CanGreet` is implemented by delegating to -`UseContext`, whose `Greeter` impl in turn calls `App`'s `CanGreet`. The trait solver chases this in a -loop and reports it as an overflow or an unsatisfied bound. The same happens with a same-component -wrapper that defaults its inner to `UseContext` and is then wired to that component. `UseContext` -belongs where the provider trait resolves to a different implementation, such as a wrapper over another -capability or a per-type dispatch entry. +**Wiring a component to `UseContext` on the context whose only implementation is that same delegation +creates a cycle.** If `App` wired `@EncoderComponent.u32: UseContext`, then `App`'s `CanEncode` +would be implemented by delegating to `UseContext`, whose `Encoder` impl in turn calls `App`'s +`CanEncode`. The trait solver chases this in a loop and reports it as an overflow or an unsatisfied +bound. `UseContext` belongs where the provider trait resolves to a *different* implementation, such as a +wrapper over another capability or a per-type dispatch entry for a different type. The `EncodeVec` +example above is safe for exactly that reason: it is wired for `Vec`, but its inner `UseContext` +resolves `Encoder`, a different entry. ## Related constructs @@ -169,11 +173,15 @@ capability or a per-type dispatch entry. component, and the consumer blanket impl `UseContext` is the dual of. - [Higher-order providers](/docs/concepts/higher-order-providers) — where `UseContext` is the default inner provider. +- [`WithContext`](with_context.md) — the `WithProvider`-adapted alias of `UseContext`, for serving a + component from the context's own foundational implementation. - [`WithProvider`](with_provider.md) — its `WithContext` alias is `WithProvider`, adapting a context's own implementation into a component. - [`RedirectLookup`](redirect_lookup.md) — the other `#[cgp_component]`-generated provider, routing through a separate table rather than back to the context. - [Dispatch combinators](dispatch/index.md) — default their per-variant provider to `UseContext`. +- [`delegate_components!`](../macros/delegate_components.md) — wires it, and its `open` statement + dispatches a component per type as the example does. - [`IsProviderFor`](../traits/is_provider_for.md) — carries the dependency `UseContext` propagates. The ideas behind it: diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index 321d064a..e6c37e50 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -25,7 +25,7 @@ the defaults wires the component to `UseDefault` and writes no method bodies of `UseDefault` is a bare marker that CGP defines but does not implement for any trait. Unlike [`UseContext`](use_context.md) or the getter providers, no macro generates a provider implementation for it. The author writes the implementation, usually with [`#[cgp_impl]`](../macros/cgp_impl.md) and -an empty body so the trait's defaults take effect. That is what distinguishes `UseDefault` from the +an empty body so the trait's defaults take effect. That distinguishes `UseDefault` from the providers that carry generated behavior: it is purely a conventional name for an author-supplied, default-bodied implementation. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index a5e5d067..c9dd754f 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -61,7 +61,7 @@ delegate_components! { The `new` keyword declares the inner table `AreaCalculatorComponents` in place and maps each concrete type to its provider. The component must be defined with a [`#[derive_delegate(UseDelegate)]`](../attributes/derive_delegate.md) attribute naming the -parameter to dispatch on, which is what generates the `UseDelegate` provider impl that reads the table. +parameter to dispatch on, which generates the `UseDelegate` provider impl that reads the table. ## Examples diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index 19fa024a..696555a8 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -15,7 +15,7 @@ type to one fixed `T`. But sometimes a single provider must answer several abstr once, or route each type tag to a different concrete type chosen elsewhere, such as when a namespace or a higher-order provider supplies a coherent bundle of types. Hand-writing one `UseType` entry per tag would scatter that decision; `UseDelegatedType` concentrates it into one `Components` table the provider -consults. As always, the **context** (the type a capability runs against) is what points its type +consults. As always, the **context** (the type a capability runs against) points its type components at the provider. The mechanism is the same indirection [`UseDelegate`](use_delegate.md) provides for behavioral @@ -27,89 +27,17 @@ and the other yields a type. Like every CGP provider, it carries no runtime valu ## Usage -`UseDelegatedType` implements the built-in [`TypeProvider`](../components/has_type.md), so a -user-defined [`#[cgp_type]`](../macros/cgp_type.md) component is wired to it through its -[`WithProvider`](with_provider.md) alias, `WithDelegatedType`. Neither is in the prelude; import them -from `cgp::core::types`: - -```rust -use cgp::core::types::WithDelegatedType; -``` - -`WithDelegatedType` takes one type parameter, the lookup table, and appears as the value of -one or more abstract-type components' wiring entries: - -```rust -delegate_components! { - App { - [ - ScalarTypeProviderComponent, - IndexTypeProviderComponent, - ]: WithDelegatedType, - } -} -``` - -The `Components` parameter is a type that maps each type tag to a concrete type, built as an ordinary -[`delegate_components!`](../macros/delegate_components.md) table. Any tag the table has no entry for is -simply unresolved, and the context does not implement `HasType` for it. `WithDelegatedType` -is [`WithProvider>`](with_provider.md), and it is the form you wire, since -the bare `UseDelegatedType` provides the foundational `TypeProvider` rather than a named component's -provider trait. - -## Examples - -A typical use defines a lookup table mapping type tags to concrete types and wires a context's type -components through it. The table is an ordinary type carrying `DelegateComponent` entries: - -```rust -use cgp::prelude::*; -use cgp::core::types::WithDelegatedType; // not in the prelude - -#[cgp_type] -pub trait HasScalarType { - type Scalar; -} - -#[cgp_type] -pub trait HasIndexType { - type Index; -} - -pub struct App; -pub struct AppTypes; - -delegate_components! { - AppTypes { - ScalarTypeProviderComponent: f64, - IndexTypeProviderComponent: usize, - } -} - -delegate_components! { - App { - [ - ScalarTypeProviderComponent, - IndexTypeProviderComponent, - ]: WithDelegatedType, - } -} -``` - -`App` routes both its scalar and index type components through `WithDelegatedType`. When the -wiring asks for `App`'s `Scalar`, the provider looks `ScalarTypeProviderComponent` up in `AppTypes` and -finds `f64`; for `Index` it finds `usize`. One provider entry on `App` answers two abstract types, with -the concrete choices held in one place in `AppTypes` where they can be reused, swapped, or supplied by -a namespace. +`UseDelegatedType` supplies only the foundational [`TypeProvider`](../components/has_type.md), so it is +wired through its [`WithDelegatedType`](with_delegated_type.md) alias rather than named directly. See +[`WithDelegatedType`](with_delegated_type.md) for the import, the wiring form, and a worked example; the +mechanism those rest on is described under [Under the hood](#under-the-hood) below. ## When to reach for it, and when not -**Reach for `UseDelegatedType` when several abstract types should be answered from one shared table**, -so a context points its type components at the table rather than fixing each one at the wiring site. -This is what makes a coherent bundle of types reusable across contexts or supplied by a namespace. - -Prefer [`UseType`](use_type.md) for the common case of fixing one abstract type to one concrete -type, which needs no table. +You choose `UseDelegatedType` by wiring its [`WithDelegatedType`](with_delegated_type.md) alias, so the +guidance on when to answer several abstract types from one shared table — rather than fixing each one +with [`UseType`](use_type.md) — lives with that alias, on +[`WithDelegatedType`](with_delegated_type.md). ## Under the hood @@ -142,6 +70,8 @@ reports the single type `T`: `UseDelegatedType` adds exactly one level of indire the same kind of table. - [`DelegateComponent`](../traits/delegate_component.md) — the table it reads. - [`HasType` / `TypeProvider`](../components/has_type.md) — the abstract-type component it answers for. +- [`WithDelegatedType`](with_delegated_type.md) — the alias you wire, and the home of the import and + worked example. - [`WithProvider`](with_provider.md) — the adapter behind the `WithDelegatedType` alias. - [`#[cgp_type]`](../macros/cgp_type.md) — defines the abstract-type components it resolves. diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index 90a63a90..2271431b 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -48,10 +48,9 @@ The tag is a [`Symbol!`](../macros/symbol.md) for a named field or an `Index` The context must have a `HasField` implementation for that tag, which [`#[derive(HasField)]`](../derives/derive_has_field.md) supplies for every field of a struct. -`UseField` has an alias, `WithField`, which is -[`WithProvider>`](with_provider.md). Both bind the same field; the alias routes through -the `WithProvider` adapter instead of the getter's own generated `UseField` implementation. Prefer the -plain `UseField` form. +`UseField` also has an alias, [`WithField`](with_field.md), which is +[`WithProvider>`](with_provider.md). Both bind the same field; prefer the plain +`UseField` form. ## Examples @@ -87,18 +86,8 @@ fn greet(person: &Person) { the `first_name` field. The method name and the field name diverge, and the field name comes entirely from the wiring. -The same binding can be written with the `WithField` alias, which routes through -[`WithProvider`](with_provider.md): - -```rust -delegate_components! { - Person { - NameGetterComponent: WithField, - } -} -``` - -Both read `first_name`. +The same binding can be written with the [`WithField`](with_field.md) alias, which routes through +[`WithProvider`](with_provider.md). ## When to reach for it, and when not @@ -160,6 +149,7 @@ bound, so delegation propagates the dependency and a check reports a missing fie - [`UseFieldRef`](use_field_ref.md) — the foundational getter for a stored type that borrows to a different return type through `AsRef`. - [`ChainGetters`](chain_getters.md) — reaches a field on a nested context by composing getters. +- [`WithField`](with_field.md) — the `WithProvider`-adapted alias that binds the same field. - [`WithProvider`](with_provider.md) — the adapter behind the `WithField` alias. - [`UseType`](use_type.md) — the abstract-type analogue for a `#[cgp_type]` component. - [`HasField`](../traits/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index 92d014c3..f7772ff0 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -17,8 +17,8 @@ stored field type implements `AsRef`. It exists for a getter whose return example, where the field is not a `Config` but can be borrowed as one. `UseFieldRef` is a foundational [`FieldGetter`](../traits/field_getter.md) rather than a getter -component's own provider, so it is wired through the [`WithProvider`](with_provider.md) adapter using its -`WithFieldRef` alias. That distinguishes it from [`UseField`](use_field.md), which +component's own provider, so it is wired through its [`WithFieldRef`](with_field_ref.md) alias, +`WithProvider>`. That distinguishes it from [`UseField`](use_field.md), which [`#[cgp_getter]`](../macros/cgp_getter.md) generates a getter-component implementation for directly. Most borrowed-view getters do not need `UseFieldRef` at all, and this is the key thing to know before @@ -31,82 +31,17 @@ borrowed as. Like every CGP provider, it carries no runtime value. ## Usage -`UseFieldRef` is not in the prelude, and neither is its `WithFieldRef` alias. Import them from -`cgp::core::field::impls`: - -```rust -use cgp::core::field::impls::WithFieldRef; -``` - -`WithFieldRef` is [`WithProvider>`](with_provider.md), and it is the -form you wire, since the bare `UseFieldRef` provides the foundational `FieldGetter` rather than a named -getter's provider trait. It takes the field tag and the borrowed value type, and appears as the value of -a getter component's wiring entry: - -```rust -delegate_components! { - App { - ConfigGetterComponent: WithFieldRef, - } -} -``` - -`Tag` names the field, as in [`UseField`](use_field.md), and `Value` is the type the getter exposes. The -stored field type must implement `AsRef` (and, for the mutable getter, `AsMut`), and the -getter's return type must be `&Value`. - -## Examples - -A getter returns `&Config` while the context stores the config in a wrapper that borrows as `Config`. -The wrapper implements `AsRef`, so `WithFieldRef` reads it and borrows through it: - -```rust -use cgp::prelude::*; -use cgp::core::field::impls::WithFieldRef; // not in the prelude - -pub struct Config { - pub port: u16, -} - -pub struct StoredConfig(pub Config); - -impl AsRef for StoredConfig { - fn as_ref(&self) -> &Config { - &self.0 - } -} - -#[cgp_getter] -pub trait HasConfig { - fn config(&self) -> &Config; -} - -#[derive(HasField)] -pub struct App { - pub config: StoredConfig, -} - -delegate_components! { - App { - ConfigGetterComponent: WithFieldRef, - } -} -``` - -`App` wires `ConfigGetterComponent` to `WithFieldRef`. The provider reads the -`config` field, a `StoredConfig`, and because `StoredConfig: AsRef`, returns `&Config` from -`as_ref()`. The getter exposes the borrowed `Config` view while the context owns the `StoredConfig`. +`UseFieldRef` supplies only the foundational [`FieldGetter`](../traits/field_getter.md), so it is wired +through its [`WithFieldRef`](with_field_ref.md) alias rather than named directly. See +[`WithFieldRef`](with_field_ref.md) for the import, the wiring form, and a worked example; the mechanism +those rest on is described under [Under the hood](#under-the-hood) below. ## When to reach for it, and when not -**Reach for `UseFieldRef` when a getter returns `&T` and the context stores a different type that -borrows as `T` through `AsRef`.** The stored type and the exposed type differ, and neither the plain -[`UseField`](use_field.md) nor an [`#[implicit]`](../attributes/implicit.md) argument can bridge them. - -Prefer [`UseField`](use_field.md) for the common borrowed-view getters. A `-> &str` getter over a -`String` field and a `-> &[u8]` getter over a `Vec` field are handled by the generated `UseField` -implementation, which borrows through `as_str()` or `as_ref()` based on the return type, so they need no -`UseFieldRef`. And for a field returned as its own type, an `#[implicit]` argument is simpler still. +You choose `UseFieldRef` by wiring its [`WithFieldRef`](with_field_ref.md) alias, so the guidance on when +a borrowed-view getter needs it — rather than the plain [`UseField`](use_field.md) or an +[`#[implicit]`](../attributes/implicit.md) argument — lives with that alias, on +[`WithFieldRef`](with_field_ref.md). ## Under the hood @@ -136,7 +71,7 @@ lets Rust infer the borrow's lifetime through the `AsRef` call. `UseFieldRef` also implements the mutable getter [`MutFieldGetter`](../traits/mut_field_getter.md), requiring the field type to implement both `AsRef` and `AsMut` and returning `&mut Value` through `as_mut()`. Because these are `FieldGetter` implementations rather than a getter component's own -provider trait, the [`WithProvider`](with_provider.md) adapter behind `WithFieldRef` is what turns +provider trait, the [`WithProvider`](with_provider.md) adapter behind `WithFieldRef` turns `UseFieldRef` into a provider a getter component can be wired to. Unlike [`UseField`](use_field.md), it does not implement [`TypeProvider`](../components/has_type.md), because its purpose is borrowed field access rather than abstract-type resolution. @@ -145,6 +80,8 @@ access rather than abstract-type resolution. - [`UseField`](use_field.md) — the getter provider that reads a field directly, and that already handles the `&str`/`&[u8]` borrowed shorthands. +- [`WithFieldRef`](with_field_ref.md) — the alias you wire, and the home of the import and worked + example. - [`WithProvider`](with_provider.md) — the adapter behind the `WithFieldRef` alias, which turns `UseFieldRef` into a getter-component provider. - [`ChainGetters`](chain_getters.md) — another foundational `FieldGetter`, composed for nested contexts. diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index db9611d0..5fc092a5 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -1,9 +1,9 @@ --- -sidebar_label: 'UseType (provider)' +sidebar_label: 'UseType' sidebar_position: 2 --- -# `UseType` (provider) +# `UseType` Supply a concrete type as the value of an abstract-type component, binding it purely through wiring. @@ -56,9 +56,8 @@ component marker `ScalarTypeProviderComponent`; wiring that marker to `UseType` has an alias, `WithType`, which is -[`WithProvider>`](with_provider.md); it is imported from `cgp::core::types`. Both bind -the same type. Prefer the plain `UseType` form. +`UseType` also has an alias, [`WithType`](with_type.md), the `WithProvider`-adapted form +imported from `cgp::core::types`. Both bind the same type; prefer the plain `UseType` form. ## Examples @@ -85,20 +84,8 @@ delegate_components! { `Scalar = f64`. The `Copy` bound on the associated type is checked against `f64` where the wiring is written. -The same binding can be written with the `WithType` alias, which routes through -[`WithProvider`](with_provider.md): - -```rust -use cgp::core::types::WithType; // not in the prelude - -delegate_components! { - App { - ScalarTypeProviderComponent: WithType, - } -} -``` - -Both make `App::Scalar` resolve to `f64`. +The same binding can be written with the [`WithType`](with_type.md) alias, which routes through +[`WithProvider`](with_provider.md). ## When to reach for it, and when not @@ -129,7 +116,7 @@ The implementation is unconditional in `Context` and `Tag`: `UseType` is a reads this, so once a context's type component is wired to `UseType`, the context implements `HasType` with `Type = f64`. -The same provider is what [`#[cgp_type]`](../macros/cgp_type.md) targets. For +[`#[cgp_type]`](../macros/cgp_type.md) targets the same provider. For `#[cgp_type] trait HasScalarType { type Scalar; }`, the macro generates a `UseType` implementation for the component's own provider trait: @@ -155,6 +142,7 @@ clause, so the concrete type must satisfy it at the wiring site. implements. - [`UseDelegatedType`](use_delegated_type.md) — resolves an abstract type through a table instead of fixing it. +- [`WithType`](with_type.md) — the `WithProvider`-adapted alias that binds the same type. - [`WithProvider`](with_provider.md) — the adapter behind the `WithType` alias. - [`UseField`](use_field.md) — the field-level analogue for getter components. diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md new file mode 100644 index 00000000..aaf4364e --- /dev/null +++ b/docs/reference/providers/with_context.md @@ -0,0 +1,81 @@ +--- +sidebar_label: 'WithContext' +sidebar_position: 6.1 +--- + +# `WithContext` + +The `WithProvider`-adapted spelling of `UseContext`, defined for completeness of the `With…` family. + +## Overview + +`WithContext` is the alias `WithProvider`. It pairs the [`WithProvider`](with_provider.md) +adapter with [`UseContext`](use_context.md) on a **context**, the type a capability runs against. +[`UseContext`](use_context.md) carries a foundational [`FieldGetter`](../traits/field_getter.md), and +[`WithProvider`](with_provider.md) adapts a foundational provider into a named component's provider, so +`WithContext` is the two composed. Like every CGP provider, it carries no runtime value. + +`WithContext` is distinct from the bare [`UseContext`](use_context.md), and the two play different +roles. `UseContext` implements a component's provider trait *directly* by routing back to the context's +consumer trait, which is how it serves as a higher-order provider's default inner provider. `WithContext` +instead wraps `UseContext` in the [`WithProvider`](with_provider.md) adapter. It is the least-used member +of the `With…` family: the library defines it for completeness, and the common ways to serve a component +from the context's own state are the constructs named below rather than this alias. + +## Usage + +`WithContext` is in the prelude, so `use cgp::prelude::*;` is enough. It takes no type parameter. It is +the alias `WithProvider`, so it appears wherever `WithProvider` would, adapting +`UseContext`'s foundational implementation into a named component's provider. + +For the everyday needs it is adjacent to, reach for one of these instead, all of which the codebase +exercises directly: + +- an [`#[implicit]`](../attributes/implicit.md) argument, where a provider simply needs a value from its + own context; +- [`UseFields`](use_fields.md) on a getter component, to read same-named fields; +- the bare [`UseContext`](use_context.md), as a higher-order provider's default inner provider. + +## When to reach for it, and when not + +**Reach for the constructs above rather than `WithContext` in practice.** The value it wraps is reached +more directly through [`UseContext`](use_context.md), [`UseFields`](use_fields.md), or an +[`#[implicit]`](../attributes/implicit.md) argument. + +## Under the hood + +`WithContext` is a type alias: + +```rust +pub type WithContext = WithProvider; +``` + +The [`WithProvider`](with_provider.md) adapter forwards a component's provider-trait method to the inner +provider's foundational method, and [`UseContext`](use_context.md) supplies that foundational method, +its [`FieldGetter`](../traits/field_getter.md) reading the context's `HasField`. The generated +`WithProvider` impl that makes this work is shown on the [`WithProvider`](with_provider.md) page. + +## Related constructs + +- [`WithProvider`](with_provider.md) — the adapter this alias specializes. +- [`UseContext`](use_context.md) — the inner provider it wraps, whose direct form serves as a + higher-order provider's inner default. +- [`WithField`](with_field.md), [`WithType`](with_type.md) — the sibling aliases for a specific field or + concrete type. +- [`UseFields`](use_fields.md) — reads same-named fields on a getter component, one of the direct forms + to prefer. +- [`FieldGetter`](../traits/field_getter.md) — the foundational getter `UseContext` supplies here. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the two-way split + `UseContext` bridges. + +## Source + +- The alias: + [`use_context.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_context.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md new file mode 100644 index 00000000..97667d91 --- /dev/null +++ b/docs/reference/providers/with_delegated_type.md @@ -0,0 +1,133 @@ +--- +sidebar_label: 'WithDelegatedType' +sidebar_position: 6.5 +--- + +# `WithDelegatedType` + +Resolve one or more abstract-type components from a shared table, through the `WithProvider` adapter. + +## Overview + +`WithDelegatedType` is the alias `WithProvider>`. It answers a +context's abstract-type components by looking each type tag up in the `Components` table, on a +**context**, the type a capability runs against, by adapting the foundational +[`UseDelegatedType`](use_delegated_type.md) provider through the [`WithProvider`](with_provider.md) +layer. Like every CGP provider, it carries no runtime value. + +Unlike [`WithType`](with_type.md), this alias is not an alternative to a directly-wireable provider: the +bare [`UseDelegatedType`](use_delegated_type.md) supplies only the foundational +[`TypeProvider`](../components/has_type.md), so `WithDelegatedType` is the form you wire. + +## Usage + +`WithDelegatedType` is not in the prelude. Import it from `cgp::core::types`. It takes one type +parameter, the lookup table, and appears as the value of one or more abstract-type components' wiring +entries: + +```rust +use cgp::core::types::WithDelegatedType; + +delegate_components! { + App { + [ + ScalarTypeProviderComponent, + IndexTypeProviderComponent, + ]: WithDelegatedType, + } +} +``` + +The `Components` parameter is a type that maps each type tag to a concrete type, built as an ordinary +[`delegate_components!`](../macros/delegate_components.md) table. Any tag the table has no entry for is +unresolved, and the context does not implement `HasType` for it. + +## Examples + +A lookup table maps type tags to concrete types, and a context wires several type components through it: + +```rust +use cgp::core::types::WithDelegatedType; +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar; +} + +#[cgp_type] +pub trait HasIndexType { + type Index; +} + +pub struct App; +pub struct AppTypes; + +delegate_components! { + AppTypes { + ScalarTypeProviderComponent: f64, + IndexTypeProviderComponent: usize, + } +} + +delegate_components! { + App { + [ + ScalarTypeProviderComponent, + IndexTypeProviderComponent, + ]: WithDelegatedType, + } +} +``` + +`App` routes both its scalar and index type components through `WithDelegatedType`. For `App`'s +`Scalar` the provider finds `f64` in `AppTypes`, and for `Index` it finds `usize`. One provider entry on +`App` answers two abstract types, with the concrete choices held in one place where they can be reused, +swapped, or supplied by a namespace. + +## When to reach for it, and when not + +**Reach for `WithDelegatedType` when several abstract types should be answered from one shared table**, +so a context points its type components at the table rather than fixing each one at the wiring site. + +Prefer [`WithType`](with_type.md) or the plain [`UseType`](use_type.md) for the common case of +fixing one abstract type to one concrete type, which needs no table. + +## Under the hood + +`WithDelegatedType` is a type alias: + +```rust +pub type WithDelegatedType = WithProvider>; +``` + +The [`WithProvider`](with_provider.md) adapter forwards a type component's provider-trait method to the +inner provider's foundational method, and [`UseDelegatedType`](use_delegated_type.md) is the +foundational [`TypeProvider`](../components/has_type.md) that resolves each tag through a +[`DelegateComponent`](../traits/delegate_component.md) lookup. The `UseDelegatedType` mechanism is +documented on the [`UseDelegatedType`](use_delegated_type.md) page, and the generated `WithProvider` impl +on the [`WithProvider`](with_provider.md) page. + +## Related constructs + +- [`WithProvider`](with_provider.md) — the adapter this alias specializes. +- [`UseDelegatedType`](use_delegated_type.md) — the foundational provider it wraps, where the table + lookup is documented. +- [`WithType`](with_type.md) — the sibling alias for a single fixed concrete type. +- [`DelegateComponent`](../traits/delegate_component.md) — the table the lookup reads. +- [`HasType` / `TypeProvider`](../components/has_type.md) — the abstract-type component it answers for. +- [`#[cgp_type]`](../macros/cgp_type.md) — defines the abstract-type components it resolves. + +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — the associated types a context chooses for itself, + here from a shared table. + +## Source + +- The alias: + [`use_delegated_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/impls/use_delegated_type.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_field.md b/docs/reference/providers/with_field.md new file mode 100644 index 00000000..264206b8 --- /dev/null +++ b/docs/reference/providers/with_field.md @@ -0,0 +1,111 @@ +--- +sidebar_label: 'WithField' +sidebar_position: 6.3 +--- + +# `WithField` + +Wire a getter component to a named context field, through the `WithProvider` adapter. + +## Overview + +`WithField` is the alias `WithProvider>`. It implements a getter component by reading +the context field named by `Tag`, on a **context**, the type a capability runs against, by adapting the +foundational [`UseField`](use_field.md) getter through the [`WithProvider`](with_provider.md) layer. +It reads the same field the plain [`UseField`](use_field.md) provider does, and both are interchangeable +in wiring. Like every CGP provider, it carries no runtime value. + +## Usage + +`WithField` is not in the prelude. Import it from `cgp::core::field::impls`. It takes one type parameter, +the field tag, and appears as the value of a getter component's wiring entry: + +```rust +use cgp::core::field::impls::WithField; + +delegate_components! { + Person { + NameGetterComponent: WithField, + } +} +``` + +The tag is a [`Symbol!`](../macros/symbol.md) for a named field or an `Index` for a tuple field, and +the context must have a [`HasField`](../traits/has_field.md) implementation for it. This reads the +`first_name` field exactly as wiring [`UseField`](use_field.md) would. + +## Examples + +A getter whose method name differs from the field it reads, wired through the alias: + +```rust +use cgp::core::field::impls::WithField; +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} + +delegate_components! { + Person { + NameGetterComponent: WithField, + } +} +``` + +`WithField` expands to `WithProvider>`, so +`person.name()` reads the `first_name` field. The field name lives in the wiring, not in the trait. + +## When to reach for it, and when not + +**Prefer the plain [`UseField`](use_field.md) form.** It reads the same field and is the value a +[`#[cgp_getter]`](../macros/cgp_getter.md) component is normally wired to. `WithField` exists for the +case where a component is reached only through the [`WithProvider`](with_provider.md) adapter, and it +reads as a single wiring choice where spelling out `WithProvider>` would not. + +For the common case of reading a field, an [`#[implicit]`](../attributes/implicit.md) argument is +simpler than any getter provider. For a stored type that borrows to the getter's return type through +`AsRef`, use [`WithFieldRef`](with_field_ref.md). + +## Under the hood + +`WithField` is a type alias: + +```rust +pub type WithField = WithProvider>; +``` + +The [`WithProvider`](with_provider.md) adapter forwards a getter's provider-trait method to the inner +provider's foundational method, and [`UseField`](use_field.md) is the foundational +[`FieldGetter`](../traits/field_getter.md) that reads the field at `Tag`. The generated `WithProvider` +impl that makes this work is shown on the [`WithProvider`](with_provider.md) page. + +## Related constructs + +- [`WithProvider`](with_provider.md) — the adapter this alias specializes. +- [`UseField`](use_field.md) — the inner provider it wraps, and the plain form to prefer. +- [`WithFieldRef`](with_field_ref.md) — the sibling alias for a field borrowed through `AsRef`. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — defines the getter component and generates the + `WithProvider` impl. +- [`HasField`](../traits/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the + field access it reads, keyed by [`Symbol!`](../macros/symbol.md) or `Index`. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — value injection through a + provider's own requirements, of which reading a field is the most common form. + +## Source + +- The alias: + [`use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md new file mode 100644 index 00000000..3b91db44 --- /dev/null +++ b/docs/reference/providers/with_field_ref.md @@ -0,0 +1,131 @@ +--- +sidebar_label: 'WithFieldRef' +sidebar_position: 6.4 +--- + +# `WithFieldRef` + +Wire a getter component to a field borrowed through `AsRef`, through the `WithProvider` adapter. + +## Overview + +`WithFieldRef` is the alias `WithProvider>`. It implements a getter +component by reading the field named by `Tag` from the **context**, the type a capability runs against, +and borrowing it through `AsRef` to produce a `&Value`, where the stored field type implements +`AsRef`. It adapts the foundational [`UseFieldRef`](use_field_ref.md) getter through the +[`WithProvider`](with_provider.md) layer. Like every CGP provider, it carries no runtime value. + +Unlike [`WithField`](with_field.md), this alias is not an alternative to a directly-wireable provider: +the bare [`UseFieldRef`](use_field_ref.md) supplies only the foundational +[`FieldGetter`](../traits/field_getter.md), so `WithFieldRef` is the form you wire. + +## Usage + +`WithFieldRef` is not in the prelude. Import it from `cgp::core::field::impls`. It takes the field tag +and the borrowed value type, and appears as the value of a getter component's wiring entry: + +```rust +use cgp::core::field::impls::WithFieldRef; + +delegate_components! { + App { + ConfigGetterComponent: WithFieldRef, + } +} +``` + +`Tag` names the field, as in [`UseField`](use_field.md), and `Value` is the type the getter exposes. The +stored field type must implement `AsRef` (and, for the mutable getter, `AsMut`), and the +getter's return type must be `&Value`. + +## Examples + +A getter returns `&Config` while the context stores the config in a wrapper that borrows as `Config`. +The wrapper implements `AsRef`, so `WithFieldRef` reads it and borrows through it: + +```rust +use cgp::core::field::impls::WithFieldRef; +use cgp::prelude::*; + +pub struct Config { + pub port: u16, +} + +pub struct StoredConfig(pub Config); + +impl AsRef for StoredConfig { + fn as_ref(&self) -> &Config { + &self.0 + } +} + +#[cgp_getter] +pub trait HasConfig { + fn config(&self) -> &Config; +} + +#[derive(HasField)] +pub struct App { + pub config: StoredConfig, +} + +delegate_components! { + App { + ConfigGetterComponent: WithFieldRef, + } +} +``` + +`App` wires `ConfigGetterComponent` to `WithFieldRef`. The provider reads the +`config` field, a `StoredConfig`, and because `StoredConfig: AsRef`, returns `&Config` from +`as_ref()`. The getter exposes the borrowed `Config` view while the context owns the `StoredConfig`. + +## When to reach for it, and when not + +**Reach for `WithFieldRef` when a getter returns `&T` and the context stores a different type that +borrows as `T` through `AsRef`.** The stored type and the exposed type differ, and neither the plain +[`WithField`](with_field.md) nor an [`#[implicit]`](../attributes/implicit.md) argument can bridge them. + +For the common borrowed-view getters — a `-> &str` getter over a `String` field, a `-> &[u8]` getter +over a `Vec` field — the plain [`UseField`](use_field.md) or [`WithField`](with_field.md) already +borrows for you through the return-type shorthands, so no `WithFieldRef` is needed. For a field returned +as its own type, an `#[implicit]` argument is simpler still. + +## Under the hood + +`WithFieldRef` is a type alias: + +```rust +pub type WithFieldRef = WithProvider>; +``` + +The [`WithProvider`](with_provider.md) adapter forwards a getter's provider-trait method to the inner +provider's foundational method, and [`UseFieldRef`](use_field_ref.md) is the foundational +[`FieldGetter`](../traits/field_getter.md) that reads the field at `Tag` and borrows it through `AsRef`. +The `UseFieldRef` mechanism, including its mutable form, is documented on the +[`UseFieldRef`](use_field_ref.md) page, and the generated `WithProvider` impl on the +[`WithProvider`](with_provider.md) page. + +## Related constructs + +- [`WithProvider`](with_provider.md) — the adapter this alias specializes. +- [`UseFieldRef`](use_field_ref.md) — the foundational getter it wraps, where the `AsRef` mechanism is + documented. +- [`WithField`](with_field.md) — the sibling alias for a field read directly, without the `AsRef` step. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — defines the getter component this is wired to. +- [`FieldGetter`](../traits/field_getter.md) and [`MutFieldGetter`](../traits/mut_field_getter.md) — the + provider-side getters the inner provider implements, over [`HasField`](../traits/has_field.md). + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — value injection through a + provider's own requirements, of which a getter is one form. + +## Source + +- The alias: + [`use_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_ref.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 4f9e58ab..fc6a905a 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -20,7 +20,7 @@ serves. A named component, by contrast, has a specific provider trait, such as ` one of those named components: it implements the component's provider trait by forwarding to the foundational provider's method. -This adapter is what lets the foundational layer be wired without each foundational provider +This adapter lets the foundational layer be wired without each foundational provider implementing every component trait by hand. A field getter written once as a `FieldGetter` can serve any number of getter components through `WithProvider`, and an abstract-type implementation written once as a `TypeProvider` can serve any type component the same way. @@ -28,7 +28,7 @@ a `TypeProvider` can serve any type component the same way. `WithProvider` is rarely written in full, because its common uses are packaged as aliases. The family `WithContext`, `WithType`, `WithField`, `WithFieldRef`, and `WithDelegatedType` are each `WithProvider<...>` specialized to a particular inner provider, and those aliases are what appear in -everyday wiring. Understanding `WithProvider` is what explains why the aliases work. Like every CGP +everyday wiring. Understanding `WithProvider` explains why the aliases work. Like every CGP provider, it carries no runtime value. ## Usage @@ -39,11 +39,11 @@ practice you write one of its aliases instead: | Alias | Expands to | Import from | |---|---|---| -| `WithContext` | `WithProvider` | prelude | -| `WithType` | `WithProvider>` | `cgp::core::types` | -| `WithField` | `WithProvider>` | `cgp::core::field::impls` | -| `WithFieldRef` | `WithProvider>` | `cgp::core::field::impls` | -| `WithDelegatedType` | `WithProvider>` | `cgp::core::types` | +| [`WithContext`](with_context.md) | `WithProvider` | prelude | +| [`WithType`](with_type.md) | `WithProvider>` | `cgp::core::types` | +| [`WithField`](with_field.md) | `WithProvider>` | `cgp::core::field::impls` | +| [`WithFieldRef`](with_field_ref.md) | `WithProvider>` | `cgp::core::field::impls` | +| [`WithDelegatedType`](with_delegated_type.md) | `WithProvider>` | `cgp::core::types` | Each alias wires the inner provider it names as a specific component's provider. A component becomes adaptable this way only when its macro generates the `WithProvider` impl: @@ -85,12 +85,13 @@ the type through a table. ## When to reach for it, and when not -**Reach for one of the aliases, not `WithProvider` directly.** `WithField`, `WithType`, `WithContext`, -`WithFieldRef`, and `WithDelegatedType` are the readable forms, and they are interchangeable with the -plain providers they wrap: wiring a getter to `WithField` and to -[`UseField`](use_field.md) both read the same field. Prefer the plain provider -([`UseField`](use_field.md), [`UseType`](use_type.md)) where it applies, and the `With...` alias where a -component is reached only through the `WithProvider` adapter. +**Reach for one of the aliases, not `WithProvider` directly.** [`WithField`](with_field.md), +[`WithType`](with_type.md), and [`WithContext`](with_context.md) are interchangeable with the plain +providers they wrap: wiring a getter to `WithField` and to [`UseField`](use_field.md) both +read the same field, so prefer the plain provider ([`UseField`](use_field.md), [`UseType`](use_type.md)) +where it applies. [`WithFieldRef`](with_field_ref.md) and [`WithDelegatedType`](with_delegated_type.md) +have no plain wireable form, because their inner providers are foundational, so you wire the alias. +Each alias is documented on its own page, linked from the table above. Write `WithProvider` in full only when adapting a foundational provider that has no ready alias. @@ -140,11 +141,9 @@ has exactly one method, since a single foundational getter cannot serve several impl is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl. The aliases specialize `WithProvider` to a fixed inner provider so the common cases need no -`WithProvider<...>` spelled out. `WithContext = WithProvider` adapts the context's own -consumer-trait implementation; `WithType` and `WithField` adapt the foundational type and -field providers; `WithFieldRef` adapts a getter that borrows through `AsRef`; and -`WithDelegatedType` adapts a type provider that looks its type up in a table. Each alias -lives beside the inner provider it wraps. +`WithProvider<...>` spelled out. Each has its own page: [`WithContext`](with_context.md), +[`WithType`](with_type.md), [`WithField`](with_field.md), [`WithFieldRef`](with_field_ref.md), and +[`WithDelegatedType`](with_delegated_type.md), and each lives beside the inner provider it wraps. ## Related constructs @@ -155,6 +154,9 @@ lives beside the inner provider it wraps. - [`UseContext`](use_context.md), [`UseType`](use_type.md), [`UseField`](use_field.md), [`UseFieldRef`](use_field_ref.md), and [`UseDelegatedType`](use_delegated_type.md) — the inner providers its aliases wrap. +- [`WithContext`](with_context.md), [`WithType`](with_type.md), [`WithField`](with_field.md), + [`WithFieldRef`](with_field_ref.md), and [`WithDelegatedType`](with_delegated_type.md) — the aliases + this adapter is spelled through, one page each. - [`delegate_components!`](../macros/delegate_components.md) — wires the aliases, and [`check_components!`](../macros/check_components.md) verifies them. diff --git a/docs/reference/providers/with_type.md b/docs/reference/providers/with_type.md new file mode 100644 index 00000000..5b10049d --- /dev/null +++ b/docs/reference/providers/with_type.md @@ -0,0 +1,106 @@ +--- +sidebar_label: 'WithType' +sidebar_position: 6.2 +--- + +# `WithType` + +Bind an abstract-type component to a concrete type, through the `WithProvider` adapter. + +## Overview + +`WithType` is the alias `WithProvider>`. It binds an abstract-type component to the +concrete `Type` on a **context**, the type a capability runs against, by adapting the foundational +[`UseType`](use_type.md) provider through the [`WithProvider`](with_provider.md) layer. It sets +the same abstract type the plain [`UseType`](use_type.md) provider does, and both are interchangeable in +wiring. Like every CGP provider, it carries no runtime value. + +## Usage + +`WithType` is not in the prelude. Import it from `cgp::core::types`. It takes one type parameter, the +concrete type to supply, and appears as the value of an abstract-type component's wiring entry: + +```rust +use cgp::core::types::WithType; + +delegate_components! { + App { + ScalarTypeProviderComponent: WithType, + } +} +``` + +This sets the context's `Scalar` to `f64`, exactly as wiring [`UseType`](use_type.md) would. + +## Examples + +A complete use defines an abstract type and wires a concrete type through the alias: + +```rust +use cgp::core::types::WithType; +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar: Copy; +} + +pub struct App; + +delegate_components! { + App { + ScalarTypeProviderComponent: WithType, + } +} +``` + +`App` wires `ScalarTypeProviderComponent` to `WithType`, so `App` implements `HasScalarType` with +`Scalar = f64`. The `Copy` bound on the associated type is checked against `f64` where the wiring is +written. + +## When to reach for it, and when not + +**Prefer the plain [`UseType`](use_type.md) form.** It binds the same type and is the idiomatic +value for a [`#[cgp_type]`](../macros/cgp_type.md) component's wiring entry. `WithType` exists for the +case where a component is reached only through the [`WithProvider`](with_provider.md) adapter, and it +reads as a single wiring choice where spelling out `WithProvider>` would not. + +For an abstract type resolved through a table rather than fixed to one concrete type, use +[`WithDelegatedType`](with_delegated_type.md). + +## Under the hood + +`WithType` is a type alias: + +```rust +pub type WithType = WithProvider>; +``` + +The [`WithProvider`](with_provider.md) adapter forwards a component's provider-trait method to the +inner provider's foundational method, and [`UseType`](use_type.md) is the foundational +[`TypeProvider`](../components/has_type.md) that reports `Type` as the abstract type. The generated +`WithProvider` impl that makes this work is shown on the [`WithProvider`](with_provider.md) page. + +## Related constructs + +- [`WithProvider`](with_provider.md) — the adapter this alias specializes. +- [`UseType`](use_type.md) — the inner provider it wraps, and the plain form to prefer. +- [`WithDelegatedType`](with_delegated_type.md) — the sibling alias for a table-resolved type. +- [`#[cgp_type]`](../macros/cgp_type.md) — defines the abstract-type component and generates the + `WithProvider` impl. +- [`HasType` / `TypeProvider`](../components/has_type.md) — the built-in abstract-type component this + binds. + +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — the associated types a context chooses for itself, + which this alias supplies. + +## Source + +- The alias: + [`use_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/impls/use_type.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/example-code/src/concepts/modularity_hierarchy.rs b/example-code/src/concepts/modularity_hierarchy.rs index ee27c45a..713d69f1 100644 --- a/example-code/src/concepts/modularity_hierarchy.rs +++ b/example-code/src/concepts/modularity_hierarchy.rs @@ -190,7 +190,7 @@ pub mod tier_5 { use cgp::prelude::*; - use super::tier_4::{CanEncodeValue, EncodeAsHex, EncodeAsText, Encoder, EncoderComponent}; + use super::tier_4::{EncodeAsHex, EncodeAsText, Encoder, EncoderComponent}; pub struct EncodeVecWith(pub PhantomData); @@ -221,6 +221,8 @@ pub mod tier_5 { // `UseContext` default, and the `Vec>` call exercises the pinned inner provider. #[test] fn app_encodes_nested_collections() { + use super::tier_4::CanEncodeValue; + let flat = >>::encode(&App, &vec![1, 2, 3]); assert_eq!(flat, b"123"); diff --git a/example-code/src/reference/providers/dispatch/build_and_merge.rs b/example-code/src/reference/providers/dispatch/build_and_merge.rs new file mode 100644 index 00000000..e7301cd1 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/build_and_merge.rs @@ -0,0 +1,77 @@ +//! Code from `docs/reference/providers/dispatch/build_and_merge.md` — `BuildAndMerge`. +//! +//! Pins that `BuildAndMerge` copies a whole sub-record's shared fields into the builder at +//! once, beside a single-field `BuildAndSetField`, under `BuildWithHandlers`. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + #[derive(CgpData)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[cgp_producer] + fn build_foo_bar() -> FooBar { + FooBar { + foo: 1, + bar: "bar".to_owned(), + } + } + + #[cgp_producer(BuildBaz)] + fn build_baz() -> bool { + true + } + + // `BuildAndMerge` copies `foo` and `bar`; `BuildAndSetField` sets `baz`. + pub type Handlers = + Product![BuildAndMerge, BuildAndSetField]; + + pub struct App; + + delegate_components! { + App { + ComputerComponent: BuildWithHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), ()), + } + } + } + + #[test] + fn test_build_and_merge() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!( + app.compute(code, ()), + FooBarBaz { + foo: 1, + bar: "bar".to_owned(), + baz: true, + }, + ); + } +} diff --git a/example-code/src/reference/providers/dispatch/build_and_merge_outputs.rs b/example-code/src/reference/providers/dispatch/build_and_merge_outputs.rs new file mode 100644 index 00000000..055afdb5 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/build_and_merge_outputs.rs @@ -0,0 +1,80 @@ +//! Code from `docs/reference/providers/dispatch/build_and_merge_outputs.md` — `BuildAndMergeOutputs`. +//! +//! Pins that `BuildAndMergeOutputs` wraps each plain field-producing provider in a +//! merge step, so a list of sub-record producers assembles the whole record without the caller writing +//! the merges. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::dispatch::BuildAndMergeOutputs; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct App { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + #[derive(CgpData)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[derive(CgpData)] + pub struct BazPart { + pub baz: bool, + } + + #[cgp_producer] + fn build_foo_bar() -> FooBar { + FooBar { + foo: 1, + bar: "bar".to_owned(), + } + } + + #[cgp_producer] + fn build_baz_part() -> BazPart { + BazPart { baz: true } + } + + pub struct AppBuilder; + + delegate_components! { + AppBuilder { + ComputerComponent: + BuildAndMergeOutputs, + } + } + + mod check_builder { + use super::*; + check_components! { + AppBuilder { + ComputerComponent: ((), ()), + } + } + } + + #[test] + fn test_build_and_merge_outputs() { + use cgp::extra::handler::CanCompute; + + let builder = AppBuilder; + let code = PhantomData::<()>; + + assert_eq!( + builder.compute(code, ()), + App { + foo: 1, + bar: "bar".to_owned(), + baz: true, + }, + ); + } +} diff --git a/example-code/src/reference/providers/dispatch/build_and_set_field.rs b/example-code/src/reference/providers/dispatch/build_and_set_field.rs new file mode 100644 index 00000000..bb208315 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/build_and_set_field.rs @@ -0,0 +1,67 @@ +//! Code from `docs/reference/providers/dispatch/build_and_set_field.md` — `BuildAndSetField`. +//! +//! Pins that `BuildAndSetField` computes one named field and sets it on the builder, and +//! that a `Product!` of them assembles a whole record through `BuildWithHandlers`. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::dispatch::{BuildAndSetField, BuildWithHandlers}; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct Rectangle { + pub width: u64, + pub height: u64, + } + + #[cgp_producer(ComputeWidth)] + fn compute_width() -> u64 { + 3 + } + + #[cgp_producer(ComputeHeight)] + fn compute_height() -> u64 { + 4 + } + + pub type Handlers = Product![ + BuildAndSetField, + BuildAndSetField, + ]; + + pub struct App; + + delegate_components! { + App { + ComputerComponent: BuildWithHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), ()), + } + } + } + + #[test] + fn test_build_and_set_field() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!( + app.compute(code, ()), + Rectangle { + width: 3, + height: 4, + }, + ); + } +} diff --git a/example-code/src/reference/providers/dispatch/build_with_handlers.rs b/example-code/src/reference/providers/dispatch/build_with_handlers.rs new file mode 100644 index 00000000..8626084b --- /dev/null +++ b/example-code/src/reference/providers/dispatch/build_with_handlers.rs @@ -0,0 +1,77 @@ +//! Code from `docs/reference/providers/dispatch/build_with_handlers.md` — `BuildWithHandlers`. +//! +//! Pins that `BuildWithHandlers` assembles a record from a `Product!` of builder adapters, starting +//! from an empty builder and finalizing the all-present result. Dropping a handler for some field would +//! fail to compile at the finalize step. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + #[derive(CgpData)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[cgp_producer] + fn build_foo_bar() -> FooBar { + FooBar { + foo: 1, + bar: "bar".to_owned(), + } + } + + #[cgp_producer(BuildBaz)] + fn build_baz() -> bool { + true + } + + pub type Handlers = + Product![BuildAndMerge, BuildAndSetField]; + + pub struct App; + + delegate_components! { + App { + ComputerComponent: BuildWithHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), ()), + } + } + } + + #[test] + fn test_build_with_handlers() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!( + app.compute(code, ()), + FooBarBaz { + foo: 1, + bar: "bar".to_owned(), + baz: true, + }, + ); + } +} diff --git a/example-code/src/reference/providers/dispatch/downcast_and_handle.rs b/example-code/src/reference/providers/dispatch/downcast_and_handle.rs new file mode 100644 index 00000000..2bf26e71 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/downcast_and_handle.rs @@ -0,0 +1,72 @@ +//! Code from `docs/reference/providers/dispatch/downcast_and_handle.md` — `DowncastAndHandle`. +//! +//! Pins that `DowncastAndHandle` matches a group of variants at once by narrowing to a +//! smaller enum, beside a single-variant `ExtractFieldAndHandle`, inside one `MatchWithHandlers` list. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::dispatch::{ + DowncastAndHandle, ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers, + }; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum FooBar { + Foo(u64), + Bar(String), + } + + #[cgp_computer] + fn show_foo_bar(input: FooBar) -> String { + format!("FooBar::{input:?}") + } + + #[cgp_computer] + fn show_baz(input: bool) -> String { + format!("Baz({input:?})") + } + + // `Foo` and `Bar` are handled together by narrowing to `FooBar`; `Baz` is matched on its own. + pub type Computers = Product![ + ExtractFieldAndHandle>, + DowncastAndHandle, + ]; + + pub struct App; + + delegate_components! { + App { + ComputerComponent: MatchWithHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), FooBarBaz), + } + } + } + + #[test] + fn test_downcast_and_handle() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + + assert_eq!(app.compute(code, FooBarBaz::Foo(1)), "FooBar::Foo(1)"); + assert_eq!(app.compute(code, FooBarBaz::Baz(true)), "Baz(true)"); + } +} diff --git a/example-code/src/reference/providers/dispatch/match_first_with_handlers.rs b/example-code/src/reference/providers/dispatch/match_first_with_handlers.rs new file mode 100644 index 00000000..10d8a048 --- /dev/null +++ b/example-code/src/reference/providers/dispatch/match_first_with_handlers.rs @@ -0,0 +1,87 @@ +//! Code from `docs/reference/providers/dispatch/match_first_with_handlers.md` — `MatchFirstWithHandlers`. +//! +//! Pins the multi-argument calling convention: the input is `(Input, Args)`, and each per-variant +//! handler receives the matched payload together with the shared `Args`. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::dispatch::{ + ExtractFirstFieldAndHandle, HandleFirstFieldValue, MatchFirstWithHandlers, + }; + use cgp::extra::handler::ComputerComponent; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + #[derive(Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + #[derive(Debug, PartialEq)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub trait Container { + fn contains(self, x: f64, y: f64) -> bool; + } + + impl Container for Circle { + fn contains(self, _x: f64, _y: f64) -> bool { + true + } + } + + impl Container for Rectangle { + fn contains(self, _x: f64, _y: f64) -> bool { + true + } + } + + // A computer that takes the payload plus the shared `(x, y)` argument. + #[cgp_computer] + fn contains(shape: T, (x, y): (f64, f64)) -> bool { + shape.contains(x, y) + } + + pub type Handlers = Product![ + ExtractFirstFieldAndHandle>, + ExtractFirstFieldAndHandle>, + ]; + + pub struct App; + + delegate_components! { + App { + ComputerComponent: MatchFirstWithHandlers, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ComputerComponent: ((), (Shape, (f64, f64))), + } + } + } + + #[test] + fn test_match_first_with_handlers() { + use cgp::extra::handler::CanCompute; + + let app = App; + let code = PhantomData::<()>; + let circle = Shape::Circle(Circle { radius: 5.0 }); + + assert!(app.compute(code, (circle, (1.0, 2.0)))); + } +} diff --git a/example-code/src/reference/providers/dispatch/mod.rs b/example-code/src/reference/providers/dispatch/mod.rs index ae054449..c7266730 100644 --- a/example-code/src/reference/providers/dispatch/mod.rs +++ b/example-code/src/reference/providers/dispatch/mod.rs @@ -1,7 +1,13 @@ //! Code from the pages under `docs/reference/providers/dispatch/`, one module per page. +pub mod build_and_merge; +pub mod build_and_merge_outputs; +pub mod build_and_set_field; +pub mod build_with_handlers; +pub mod downcast_and_handle; pub mod extract_field_and_handle; pub mod handle_field_value; +pub mod match_first_with_handlers; pub mod match_with_field_handlers; pub mod match_with_handlers; pub mod match_with_value_handlers; diff --git a/example-code/src/reference/providers/mod.rs b/example-code/src/reference/providers/mod.rs index ec25449d..097bef3b 100644 --- a/example-code/src/reference/providers/mod.rs +++ b/example-code/src/reference/providers/mod.rs @@ -12,9 +12,11 @@ pub mod redirect_lookup; pub mod use_context; pub mod use_default; pub mod use_delegate; -pub mod use_delegated_type; pub mod use_field; -pub mod use_field_ref; pub mod use_fields; pub mod use_type; +pub mod with_delegated_type; +pub mod with_field; +pub mod with_field_ref; pub mod with_provider; +pub mod with_type; diff --git a/example-code/src/reference/providers/use_context.rs b/example-code/src/reference/providers/use_context.rs index 5451f174..bcc93a4e 100644 --- a/example-code/src/reference/providers/use_context.rs +++ b/example-code/src/reference/providers/use_context.rs @@ -1,36 +1,39 @@ //! Code from `docs/reference/providers/use_context.md` — *`UseContext`*. //! -//! Pins the non-cyclic default-inner-provider use: a loud greeter wraps the context's own greeter -//! through `UseContext`, delegating to a *different* component so there is no cycle. +//! Pins the default-inner-provider use: `EncodeVec` encodes a `Vec` by encoding each element through its +//! inner provider, which defaults to `UseContext` so the elements route back to the context's own +//! `CanEncode` wiring for their type. No cycle, because the element lookup is for a different type +//! (`u32`) than the wired one (`Vec`). /// ## Examples pub mod examples { use cgp::prelude::*; - #[cgp_component(Greeter)] - pub trait CanGreet { - fn greet(&self) -> String; + #[cgp_component(Encoder)] + pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; } - #[cgp_component(LoudGreeter)] - pub trait CanGreetLoudly { - fn greet_loudly(&self) -> String; - } - - #[cgp_impl(new GreetHello)] - impl Greeter { - fn greet(&self) -> String { - "Hello".to_owned() + #[cgp_impl(new EncodeAsText)] + impl Encoder + where + Value: core::fmt::Display, + { + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() } } - pub struct GreetLoudly(pub PhantomData); + pub struct EncodeVec(pub PhantomData); - #[cgp_impl(GreetLoudly)] - #[use_provider(Inner: Greeter)] - impl LoudGreeter { - fn greet_loudly(&self) -> String { - format!("{}!", Inner::greet(self).to_uppercase()) + #[cgp_impl(EncodeVec)] + #[use_provider(Inner: Encoder)] + impl Encoder> { + fn encode(&self, values: &Vec) -> Vec { + values + .iter() + .flat_map(|item| Inner::encode(self, item)) + .collect() } } @@ -38,21 +41,26 @@ pub mod examples { delegate_components! { App { - GreeterComponent: GreetHello, - LoudGreeterComponent: GreetLoudly, + open EncoderComponent; + + @EncoderComponent.u32: EncodeAsText, + @EncoderComponent.Vec: EncodeVec, } } - check_components! { - App { - GreeterComponent, - LoudGreeterComponent, + mod check_app { + use super::*; + check_components! { + App { + EncoderComponent: [u32, Vec], + } } } #[test] fn test_use_context_default_inner() { - let app = App; - assert_eq!(app.greet_loudly(), "HELLO!"); + // The `Vec` element encoding routes through `UseContext` to the `u32` encoder. + let flat = >>::encode(&App, &vec![1u32, 2, 3]); + assert_eq!(flat, b"123"); } } diff --git a/example-code/src/reference/providers/use_field.rs b/example-code/src/reference/providers/use_field.rs index b6dcd230..e9135b83 100644 --- a/example-code/src/reference/providers/use_field.rs +++ b/example-code/src/reference/providers/use_field.rs @@ -1,12 +1,10 @@ //! Code from `docs/reference/providers/use_field.md` — *`UseField`*. //! -//! Pins the decoupling the page is about: a getter method `name` reads a `first_name` field, once -//! through `UseField` and once through the `WithField` alias. The alias is wired on a second context, -//! since two entries for one component on one context would conflict. +//! Pins the decoupling the page is about: a getter method `name` reads a `first_name` field through +//! `UseField`. The `WithField` alias is covered by `with_field.rs`. /// ## Examples pub mod examples { - use cgp::core::field::impls::WithField; use cgp::prelude::*; #[cgp_getter] @@ -44,22 +42,4 @@ pub mod examples { assert_eq!(person.name(), "Alice"); greet(&person); } - - // The `WithField` alias, on a separate context to avoid a duplicate wiring for one component. - #[derive(HasField)] - pub struct PersonWith { - pub first_name: String, - } - - delegate_components! { - PersonWith { - NameGetterComponent: WithField, - } - } - - check_components! { - PersonWith { - NameGetterComponent, - } - } } diff --git a/example-code/src/reference/providers/use_type.rs b/example-code/src/reference/providers/use_type.rs index 6141ce75..eaa87755 100644 --- a/example-code/src/reference/providers/use_type.rs +++ b/example-code/src/reference/providers/use_type.rs @@ -1,7 +1,8 @@ //! Code from `docs/reference/providers/use_type.md` — *`UseType` (provider)*. //! -//! Pins that wiring an abstract-type component to `UseType` (or the `WithType` alias) sets the -//! context's abstract type to `f64` and enforces the `Copy` bound at the wiring site. +//! Pins that wiring an abstract-type component to `UseType` sets the context's abstract type to +//! `f64` and enforces the `Copy` bound at the wiring site. The `WithType` alias is covered by +//! `with_type.rs`. /// ## Examples pub mod examples { @@ -26,28 +27,3 @@ pub mod examples { } } } - -/// ## Examples — the `WithType` alias -pub mod examples_with_type { - use cgp::core::types::WithType; - use cgp::prelude::*; - - #[cgp_type] - pub trait HasScalarType { - type Scalar: Copy; - } - - pub struct App; - - delegate_components! { - App { - ScalarTypeProviderComponent: WithType, - } - } - - check_components! { - App { - ScalarTypeProviderComponent, - } - } -} diff --git a/example-code/src/reference/providers/use_delegated_type.rs b/example-code/src/reference/providers/with_delegated_type.rs similarity index 74% rename from example-code/src/reference/providers/use_delegated_type.rs rename to example-code/src/reference/providers/with_delegated_type.rs index 4a505024..241fb57a 100644 --- a/example-code/src/reference/providers/use_delegated_type.rs +++ b/example-code/src/reference/providers/with_delegated_type.rs @@ -1,6 +1,7 @@ -//! Code from `docs/reference/providers/use_delegated_type.md` — *`UseDelegatedType`*. +//! Code from `docs/reference/providers/with_delegated_type.md` — *`WithDelegatedType`*. //! -//! Pins that one `UseDelegatedType` entry answers two abstract-type components, each +//! `WithDelegatedType` (`WithProvider>`) is the form that wires the foundational +//! `UseDelegatedType` provider. This pins that one entry answers two abstract-type components, each //! resolving to the concrete type held in the `AppTypes` table. /// ## Examples diff --git a/example-code/src/reference/providers/with_field.rs b/example-code/src/reference/providers/with_field.rs new file mode 100644 index 00000000..b49a5403 --- /dev/null +++ b/example-code/src/reference/providers/with_field.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/providers/with_field.md` — *`WithField`*. +//! +//! Pins that the `WithField` alias wires a `name` getter to read the +//! `first_name` field, the same as the plain `UseField`. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::WithField; + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub first_name: String, + } + + delegate_components! { + Person { + NameGetterComponent: WithField, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + + #[test] + fn test_with_field_reads_first_name() { + let person = Person { + first_name: "Alice".to_owned(), + }; + assert_eq!(person.name(), "Alice"); + } +} diff --git a/example-code/src/reference/providers/use_field_ref.rs b/example-code/src/reference/providers/with_field_ref.rs similarity index 72% rename from example-code/src/reference/providers/use_field_ref.rs rename to example-code/src/reference/providers/with_field_ref.rs index 324ace37..ecdd7693 100644 --- a/example-code/src/reference/providers/use_field_ref.rs +++ b/example-code/src/reference/providers/with_field_ref.rs @@ -1,8 +1,7 @@ -//! Code from `docs/reference/providers/use_field_ref.md` — *`UseFieldRef`*. +//! Code from `docs/reference/providers/with_field_ref.md` — *`WithFieldRef`*. //! -//! `UseFieldRef` is a foundational `FieldGetter`, so it is wired to a getter component through the -//! `WithFieldRef` alias (`WithProvider>`). This pins that a `-> &Config` getter reads -//! a stored `AsRef` field. +//! `WithFieldRef` (`WithProvider>`) is the form that wires the foundational +//! `UseFieldRef` getter. This pins that a `-> &Config` getter reads a stored `AsRef` field. /// ## Examples pub mod examples { @@ -46,7 +45,7 @@ pub mod examples { } #[test] - fn test_use_field_ref_borrows_through_as_ref() { + fn test_with_field_ref_borrows_through_as_ref() { let app = App { config: StoredConfig(Config { port: 8080 }), }; diff --git a/example-code/src/reference/providers/with_type.rs b/example-code/src/reference/providers/with_type.rs new file mode 100644 index 00000000..581f040f --- /dev/null +++ b/example-code/src/reference/providers/with_type.rs @@ -0,0 +1,29 @@ +//! Code from `docs/reference/providers/with_type.md` — *`WithType`*. +//! +//! Pins that wiring an abstract-type component to the `WithType` alias binds the context's abstract +//! type to `f64`, the same as the plain `UseType`. + +/// ## Examples +pub mod examples { + use cgp::core::types::WithType; + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Copy; + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: WithType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + } + } +} From 7bc77e6bd3e27c6d1851bcd54c670ce4d321ee09 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 22:07:29 +0200 Subject: [PATCH 047/516] Add and restructure the reference component pages Write every component reference page, one page per component construct: split the bundled stubs, give each handler-family member its own page under a new handler/ subsection with an overview, and add a components overview page. Each page now carries a Definition section that shows the trait definition and explains every attribute in a linked bullet, and no Under the hood section. Add example-code mirrors for every component page, with dispatch wired through `open`, and re-point inbound links to the moved handler pages. Co-Authored-By: Claude Opus 4.8 --- docs/concepts/handlers.md | 16 +- docs/concepts/type-level-dsls.md | 4 +- docs/reference/components/_category_.json | 4 +- docs/reference/components/can_raise_error.md | 154 +++++++++++++++++- docs/reference/components/can_wrap_error.md | 144 ++++++++++++++++ docs/reference/components/computer.md | 17 -- docs/reference/components/handler.md | 17 -- .../components/handler/_category_.json | 8 + .../components/handler/async_computer.md | 119 ++++++++++++++ .../components/handler/async_computer_ref.md | 112 +++++++++++++ docs/reference/components/handler/computer.md | 149 +++++++++++++++++ .../components/handler/computer_ref.md | 113 +++++++++++++ docs/reference/components/handler/handler.md | 149 +++++++++++++++++ .../components/handler/handler_ref.md | 128 +++++++++++++++ docs/reference/components/handler/index.md | 52 ++++++ docs/reference/components/handler/producer.md | 135 +++++++++++++++ .../components/handler/try_computer.md | 153 +++++++++++++++++ .../components/handler/try_computer_ref.md | 123 ++++++++++++++ docs/reference/components/has_error_type.md | 154 +++++++++++++++++- docs/reference/components/has_runtime.md | 153 ++++++++++++++++- docs/reference/components/has_runtime_type.md | 129 +++++++++++++++ docs/reference/components/has_type.md | 145 ++++++++++++++++- docs/reference/components/index.md | 72 ++++++++ docs/reference/components/producer.md | 17 -- docs/reference/components/runner.md | 149 ++++++++++++++++- docs/reference/components/send_runner.md | 145 +++++++++++++++++ docs/reference/components/try_computer.md | 17 -- docs/reference/index.md | 41 ++--- docs/reference/macros/async_trait.md | 2 +- docs/reference/macros/cgp_auto_dispatch.md | 2 +- docs/reference/macros/cgp_component.md | 2 +- docs/reference/macros/cgp_computer.md | 4 +- docs/reference/macros/cgp_producer.md | 8 +- docs/reference/providers/dispatch/index.md | 6 +- docs/reference/providers/error/debug_error.md | 2 +- .../providers/error/discard_detail.md | 2 +- .../providers/error/display_error.md | 2 +- docs/reference/providers/error/index.md | 4 +- .../providers/handler/compose_handlers.md | 2 +- docs/reference/providers/handler/index.md | 16 +- .../providers/handler/pipe_handlers.md | 2 +- docs/reference/providers/handler/promote.md | 4 +- .../providers/handler/promote_async.md | 4 +- .../handler/promote_async_computer.md | 2 +- .../providers/handler/promote_computer.md | 2 +- .../providers/handler/promote_handler.md | 4 +- .../providers/handler/promote_producer.md | 4 +- .../providers/handler/promote_ref.md | 2 +- .../providers/handler/promote_try_computer.md | 2 +- .../providers/handler/return_input.md | 4 +- .../providers/handler/try_promote.md | 2 +- docs/reference/providers/monad/index.md | 2 +- .../reference/providers/monad/pipe_monadic.md | 2 +- docs/reference/traits/contains_value.md | 6 +- docs/reference/traits/has_extractor_mut.md | 2 +- docs/reference/traits/has_field_mut.md | 2 +- docs/reference/traits/lift_value.md | 4 +- docs/reference/traits/monadic_bind.md | 4 +- docs/reference/traits/monadic_trans.md | 2 +- example-code/README.md | 2 +- .../reference/components/can_raise_error.rs | 29 ++++ .../reference/components/can_wrap_error.rs | 31 ++++ .../components/handler/async_computer.rs | 18 ++ .../components/handler/async_computer_ref.rs | 18 ++ .../reference/components/handler/computer.rs | 47 ++++++ .../components/handler/computer_ref.rs | 18 ++ .../reference/components/handler/handler.rs | 21 +++ .../components/handler/handler_ref.rs | 21 +++ .../src/reference/components/handler/mod.rs | 11 ++ .../reference/components/handler/producer.rs | 46 ++++++ .../components/handler/try_computer.rs | 66 ++++++++ .../components/handler/try_computer_ref.rs | 21 +++ .../reference/components/has_error_type.rs | 36 ++++ .../src/reference/components/has_runtime.rs | 44 +++++ .../reference/components/has_runtime_type.rs | 38 +++++ .../src/reference/components/has_type.rs | 45 +++++ example-code/src/reference/components/mod.rs | 14 ++ .../src/reference/components/runner.rs | 86 ++++++++++ .../src/reference/components/send_runner.rs | 85 ++++++++++ example-code/src/reference/mod.rs | 1 + 80 files changed, 3228 insertions(+), 197 deletions(-) create mode 100644 docs/reference/components/can_wrap_error.md delete mode 100644 docs/reference/components/computer.md delete mode 100644 docs/reference/components/handler.md create mode 100644 docs/reference/components/handler/_category_.json create mode 100644 docs/reference/components/handler/async_computer.md create mode 100644 docs/reference/components/handler/async_computer_ref.md create mode 100644 docs/reference/components/handler/computer.md create mode 100644 docs/reference/components/handler/computer_ref.md create mode 100644 docs/reference/components/handler/handler.md create mode 100644 docs/reference/components/handler/handler_ref.md create mode 100644 docs/reference/components/handler/index.md create mode 100644 docs/reference/components/handler/producer.md create mode 100644 docs/reference/components/handler/try_computer.md create mode 100644 docs/reference/components/handler/try_computer_ref.md create mode 100644 docs/reference/components/has_runtime_type.md create mode 100644 docs/reference/components/index.md delete mode 100644 docs/reference/components/producer.md create mode 100644 docs/reference/components/send_runner.md delete mode 100644 docs/reference/components/try_computer.md create mode 100644 example-code/src/reference/components/can_raise_error.rs create mode 100644 example-code/src/reference/components/can_wrap_error.rs create mode 100644 example-code/src/reference/components/handler/async_computer.rs create mode 100644 example-code/src/reference/components/handler/async_computer_ref.rs create mode 100644 example-code/src/reference/components/handler/computer.rs create mode 100644 example-code/src/reference/components/handler/computer_ref.rs create mode 100644 example-code/src/reference/components/handler/handler.rs create mode 100644 example-code/src/reference/components/handler/handler_ref.rs create mode 100644 example-code/src/reference/components/handler/mod.rs create mode 100644 example-code/src/reference/components/handler/producer.rs create mode 100644 example-code/src/reference/components/handler/try_computer.rs create mode 100644 example-code/src/reference/components/handler/try_computer_ref.rs create mode 100644 example-code/src/reference/components/has_error_type.rs create mode 100644 example-code/src/reference/components/has_runtime.rs create mode 100644 example-code/src/reference/components/has_runtime_type.rs create mode 100644 example-code/src/reference/components/has_type.rs create mode 100644 example-code/src/reference/components/mod.rs create mode 100644 example-code/src/reference/components/runner.rs create mode 100644 example-code/src/reference/components/send_runner.rs diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 2f802a68..4010f518 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -44,10 +44,10 @@ a future and carries `Async` in its name, as `AsyncComputer` beside `Computer`. computation that only reads its argument. Cross those and you get the members that are documented separately: -[`Computer`](/docs/reference/components/computer) is the pure synchronous corner, -[`TryComputer`](/docs/reference/components/try_computer) the fallible synchronous one, and -[`Handler`](/docs/reference/components/handler), async *and* fallible, the general workhorse, which is -why it needs no qualifier. [`Producer`](/docs/reference/components/producer) sits slightly apart: a +[`Computer`](/docs/reference/components/handler/computer) is the pure synchronous corner, +[`TryComputer`](/docs/reference/components/handler/try_computer) the fallible synchronous one, and +[`Handler`](/docs/reference/components/handler/handler), async *and* fallible, the general workhorse, which is +why it needs no qualifier. [`Producer`](/docs/reference/components/handler/producer) sits slightly apart: a computation with no input at all, producing a value from the context and a tag. The point of the spread is that a provider declares exactly the capabilities it has. A function adding @@ -164,10 +164,10 @@ shape of a record or an enum, and the family becomes a [type-level DSL](./type-l [Higher-order providers](./higher-order-providers.md) is the mechanism the combinators are built from, and worth reading first if `PipeHandlers` looked like new machinery. -For the constructs, [`Computer`](/docs/reference/components/computer), -[`TryComputer`](/docs/reference/components/try_computer), -[`Handler`](/docs/reference/components/handler), and -[`Producer`](/docs/reference/components/producer) are the corners; +For the constructs, [`Computer`](/docs/reference/components/handler/computer), +[`TryComputer`](/docs/reference/components/handler/try_computer), +[`Handler`](/docs/reference/components/handler/handler), and +[`Producer`](/docs/reference/components/handler/producer) are the corners; [`#[cgp_computer]`](/docs/reference/macros/cgp_computer) and [`#[cgp_producer]`](/docs/reference/macros/cgp_producer) build a provider from a function; and [handler combinators](/docs/reference/providers/handler) is the full catalogue. diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index 1f07bf93..c3e21f40 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -141,8 +141,8 @@ the binary is. [Dispatching](./dispatching.md) is the same routing applied to data rather than to programs, and [namespaces](./namespaces.md) is how a language is packaged once it outgrows a table. -For the constructs, [`Computer`](/docs/reference/components/computer) and -[`Handler`](/docs/reference/components/handler) are the interpreter interfaces, +For the constructs, [`Computer`](/docs/reference/components/handler/computer) and +[`Handler`](/docs/reference/components/handler/handler) are the interpreter interfaces, [`delegate_components!`](/docs/reference/macros/delegate_components) carries the `open` statement and generic path keys, and [`Product!`](/docs/reference/macros/product) and [`Symbol!`](/docs/reference/macros/symbol) are how a real language carries lists and strings. diff --git a/docs/reference/components/_category_.json b/docs/reference/components/_category_.json index 587a54ed..ad05d6c1 100644 --- a/docs/reference/components/_category_.json +++ b/docs/reference/components/_category_.json @@ -2,7 +2,7 @@ "label": "Components", "position": 4, "link": { - "type": "generated-index", - "description": "The components CGP ships with \u2014 each a consumer trait, a provider trait, and a wiring key \u2014 that your application wires like any component it defines itself." + "type": "doc", + "id": "reference/components/index" } } diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md index d08431cc..917de154 100644 --- a/docs/reference/components/can_raise_error.md +++ b/docs/reference/components/can_raise_error.md @@ -1,17 +1,153 @@ --- -sidebar_label: 'CanRaiseError & CanWrapError' +sidebar_label: 'CanRaiseError' +sidebar_position: 2 --- -# `CanRaiseError` & `CanWrapError` +# `CanRaiseError` -Raise a source error into the context's error type, and attach detail to it. +Turn a concrete source error into the context's abstract `Self::Error`. -:::info +## Overview -### Not written yet +`CanRaiseError` lets generic CGP code produce its context's abstract error from any +concrete error it meets. A provider that calls a fallible operation gets back a specific error type, a +parse error, an I/O error, a string message, but it must return the **context's** abstract `Self::Error`, +whose concrete identity it does not know. The context here is the type a capability runs against, which +supplies the values an implementation needs as its own fields, and it decides how each source error maps +into its chosen error type. `CanRaiseError` bridges the gap: generic code writes +`Context::raise_error(source)` and the context converts the concrete `SourceError` into `Self::Error`. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +Because the trait is parameterized by `SourceError`, one context can know how to raise many different +source errors into its single abstract error. This is the "raise" half of CGP's error handling; the +"wrap" half, attaching detail to an error the context already holds, is [`CanWrapError`](./can_wrap_error.md). +Both build on [`HasErrorType`](./has_error_type.md), which supplies the `Self::Error` they produce. -::: +## Definition + +`CanRaiseError` is defined as: + +```rust +#[cgp_component(ErrorRaiser)] +#[prefix(@cgp.core.error in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanRaiseError { + fn raise_error(error: SourceError) -> Error; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `ErrorRaiser` that implementations target and the wiring key `ErrorRaiserComponent`, while `CanRaiseError` stays the consumer trait callers use. +- [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `SourceError` type, so a context can route each `SourceError` to its own provider; the `open` statement is the modern sugar for the same dispatch. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. + +## Usage + +`CanRaiseError` is in the prelude. It carries the concrete error type as a parameter, and its method is +an associated function rather than a `&self` method, because raising an error is a property of the +context type rather than of any particular value: + +```rust +fn raise_error(error: SourceError) -> Error; +``` + +A context gains the capability by wiring `ErrorRaiserComponent`, whose key lives under +`cgp::core::error`, to a provider. Because the trait dispatches per source-error type, the natural +wiring is a table keyed on `SourceError`, most idiomatically an +[`open` statement](../macros/delegate_components.md) that routes each concrete error to a provider that +knows how to handle it: + +```rust +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseError: DebugError, + } +} +``` + +The interchangeable strategies that satisfy `CanRaiseError` are the +[error providers](../providers/error/index.md): `RaiseFrom` converts through `From`, `DebugError` and +`DisplayError` format the source into a string, `ReturnError` returns it unchanged, and so on. The +standalone backend crates (`cgp-error-anyhow`, `cgp-error-eyre`, `cgp-error-std`) supply providers for +common cases, so an application usually wires a backend rather than writing raise logic itself. + +Because `raise_error` is an associated function, generic code calls it on the context *type*, +`Context::raise_error(source)` or `Self::raise_error(source)`, without borrowing a context value. This +matches how errors are constructed deep inside generic code where only the type parameter is in scope. + +## Examples + +A provider raises a concrete error into the context's abstract one: + +```rust +use cgp::prelude::*; + +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} + +#[cgp_impl(new LoadOrFail)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + return Err(Self::raise_error("empty path".to_owned())); + } + Ok(format!("contents of {path}")) + } +} +``` + +The provider `LoadOrFail` names neither the context nor its concrete error type. It requires +`CanRaiseError` through [`#[uses]`](../attributes/uses.md) to turn a `String` message into the +abstract error, and any wired context that satisfies that bound, typically by plugging in an error +backend, makes `load` produce errors in that context's chosen type. The context is an **environmental +context**, and the capability targets it rather than a value. + +## When to reach for it, and when not + +**Reach for `CanRaiseError` whenever a provider holds a concrete error `E` and must return the +context's abstract error.** It is the standard way a fallible provider bridges from a library's error +type to the context's own, and declaring it with [`#[uses(CanRaiseError)]`](../attributes/uses.md) +keeps the dependency off the consumer trait's public signature. Where a provider also needs to attach a +message or other detail as the error propagates, pair it with [`CanWrapError`](./can_wrap_error.md). + +Do not reach for it when the source error already *is* the context's error type, where returning it +directly is simpler, or when a component fixes one concrete error type for the whole program with no +per-context choice. + +## Related constructs + +- [`CanWrapError`](./can_wrap_error.md) — the companion that attaches detail to an existing error. +- [`HasErrorType`](./has_error_type.md) — the supertrait supplying the `Self::Error` this produces. +- [Error providers](../providers/error/index.md) — `RaiseFrom`, `DebugError`, and the other strategies + that satisfy this component. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates the `UseDelegate` dispatch this + uses. +- [`#[uses]`](../attributes/uses.md) — the idiomatic way a provider declares this dependency. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — the error type, its construction, + and its detail as three independent wiring decisions. + +## Source + +- The trait: + [`can_raise_error.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/traits/can_raise_error.rs) +- The abstract error it builds on: + [`has_error_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/traits/has_error_type.rs) +- The pluggable providers that implement it: + [`standalone/error/`](https://github.com/contextgeneric/cgp/tree/main/crates/standalone/error/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/can_wrap_error.md b/docs/reference/components/can_wrap_error.md new file mode 100644 index 00000000..7be1d879 --- /dev/null +++ b/docs/reference/components/can_wrap_error.md @@ -0,0 +1,144 @@ +--- +sidebar_label: 'CanWrapError' +sidebar_position: 3 +--- + +# `CanWrapError` + +Attach a piece of detail to an error the context already holds, enriching it as it propagates. + +## Overview + +`CanWrapError` enriches an error as it travels up a call stack. Where +[`CanRaiseError`](./can_raise_error.md) converts a *foreign* error into the context's abstract error, +`CanWrapError` takes an error the **context** already holds and folds a piece of `Detail` into it, a +message, a span, a path, producing an enriched `Self::Error`. The context is the type a capability runs +against, which supplies the values an implementation needs as its own fields, and it decides how detail +is combined with an existing error. Together the two components cover the common error-handling motions +in CGP: raise a foreign error in, then wrap context onto it as it bubbles up. + +Because the trait is parameterized by `Detail`, one context can attach many kinds of detail, each +through its own provider, all onto the same abstract error. Like its companion, `CanWrapError` builds on +[`HasErrorType`](./has_error_type.md), which supplies the `Self::Error` it takes and returns. + +## Definition + +`CanWrapError` is defined as: + +```rust +#[cgp_component(ErrorWrapper)] +#[prefix(@cgp.core.error in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanWrapError { + fn wrap_error(error: Error, detail: Detail) -> Error; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `ErrorWrapper` that implementations target and the wiring key `ErrorWrapperComponent`, while `CanWrapError` stays the consumer trait callers use. +- [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Detail` type, so a context can route each `Detail` to its own provider; the `open` statement is the modern sugar for the same dispatch. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. + +## Usage + +`CanWrapError` is in the prelude. Its method is an associated function that takes the context's current +error plus a detail and returns a new error with the detail folded in: + +```rust +fn wrap_error(error: Error, detail: Detail) -> Error; +``` + +A context gains the capability by wiring `ErrorWrapperComponent`, whose key lives under +`cgp::core::error`, to a provider. The trait dispatches per detail type, so the natural wiring is a +table keyed on `Detail`, most idiomatically an [`open` statement](../macros/delegate_components.md): + +```rust +delegate_components! { + App { + open ErrorWrapperComponent; + + @ErrorWrapperComponent.String: DisplayError, + } +} +``` + +The [error providers](../providers/error/index.md) supply the strategies that satisfy it, and the +standalone backend crates (`cgp-error-anyhow`, `cgp-error-eyre`, `cgp-error-std`) wire wrapping for +common detail types, so an application usually plugs in a backend rather than writing wrap logic itself. +Because `wrap_error` is an associated function, generic code calls it on the context type, +`Context::wrap_error(err, detail)`, without borrowing a context value. + +## Examples + +A provider wraps a message onto an error as it propagates: + +```rust +use cgp::prelude::*; + +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} + +#[cgp_impl(new LoadOrFail)] +#[uses(CanRaiseError, CanWrapError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + let err = Self::raise_error("empty path".to_owned()); + return Err(Self::wrap_error(err, format!("while loading {path}"))); + } + Ok(format!("contents of {path}")) + } +} +``` + +The provider `LoadOrFail` first raises a `String` into the context's abstract error with +[`CanRaiseError`](./can_raise_error.md), then wraps a further message onto it with `CanWrapError`. Both +dependencies are declared with [`#[uses]`](../attributes/uses.md), so neither appears on the public +`CanLoad` signature, and any context that satisfies them makes `load` produce enriched errors in its own +error type. The context is an **environmental context**, and the capability targets it. + +## When to reach for it, and when not + +**Reach for `CanWrapError` when a provider should add context to an error before returning it.** It +is how a CGP program builds the equivalent of an error chain or a `.context(...)` message without +committing to a concrete error library, and it pairs naturally with +[`CanRaiseError`](./can_raise_error.md) in a provider that both converts and enriches. Declare it with +[`#[uses(CanWrapError)]`](../attributes/uses.md) so the dependency stays off the consumer trait. + +Do not reach for it when there is no detail worth attaching, where raising the error is enough, or when +the context's error type already captures the surrounding context by other means. + +## Related constructs + +- [`CanRaiseError`](./can_raise_error.md) — the companion that converts a foreign error into the abstract + one. +- [`HasErrorType`](./has_error_type.md) — the supertrait supplying the `Self::Error` this enriches. +- [Error providers](../providers/error/index.md) — the strategies that satisfy this component. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates the `UseDelegate` dispatch this + uses. +- [`#[uses]`](../attributes/uses.md) — the idiomatic way a provider declares this dependency. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — the error type, its construction, + and its detail as three independent wiring decisions. + +## Source + +- The trait: + [`can_wrap_error.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/traits/can_wrap_error.rs) +- The abstract error it builds on: + [`has_error_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/traits/has_error_type.rs) +- The pluggable providers that implement it: + [`standalone/error/`](https://github.com/contextgeneric/cgp/tree/main/crates/standalone/error/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/computer.md b/docs/reference/components/computer.md deleted file mode 100644 index b8852ad4..00000000 --- a/docs/reference/components/computer.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: 'Computer & CanCompute' ---- - -# `Computer` & `CanCompute` - -The synchronous, infallible transform, with its by-reference and async variants. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/docs/reference/components/handler.md b/docs/reference/components/handler.md deleted file mode 100644 index 2cda0010..00000000 --- a/docs/reference/components/handler.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: 'Handler & CanHandle' ---- - -# `Handler` & `CanHandle` - -The general async, fallible, error-aware computation component. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/docs/reference/components/handler/_category_.json b/docs/reference/components/handler/_category_.json new file mode 100644 index 00000000..15c5e5f8 --- /dev/null +++ b/docs/reference/components/handler/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Handler family", + "position": 5, + "link": { + "type": "doc", + "id": "reference/components/handler/index" + } +} diff --git a/docs/reference/components/handler/async_computer.md b/docs/reference/components/handler/async_computer.md new file mode 100644 index 00000000..dcaae15b --- /dev/null +++ b/docs/reference/components/handler/async_computer.md @@ -0,0 +1,119 @@ +--- +sidebar_label: 'AsyncComputer' +sidebar_position: 5 +--- + +# `AsyncComputer` + +The asynchronous, infallible member of the handler family: a [`Computer`](./computer.md) that awaits. + +## Overview + +`AsyncComputer` is for computations that must await but still cannot fail. Reading a value that is +already in memory is a [`Computer`](./computer.md); awaiting a timer or a channel that always yields is +an `AsyncComputer`. It is the async point on the family's synchronicity axis with the failure path still +absent, so it transforms an `Input` into an `Output` under a phantom `Code` tag, against a **context** +(the type a capability runs against, which supplies the values an implementation needs as its own +fields), and returns the `Output` directly rather than a `Result`. + +It sits between [`Computer`](./computer.md), which drops the asynchrony, and [`Handler`](./handler.md), +which adds a failure path on top of the asynchrony. Like the pure computer, it never names an error type, +so it does not supertrait [`HasErrorType`](../has_error_type.md). See the +[handler family overview](./index.md) for how the members relate and promote. + +## Definition + +`CanComputeAsync` is defined as: + +```rust +#[async_trait] +#[cgp_component(AsyncComputer)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +pub trait CanComputeAsync { + type Output; + + async fn compute_async(&self, _code: PhantomData, input: Input) -> Self::Output; +} +``` + +Its attributes: + +- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `AsyncComputer` that implementations target and the wiring key `AsyncComputerComponent`, while `CanComputeAsync` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. + +## Usage + +`AsyncComputer` and its consumer trait `CanComputeAsync` are imported from `cgp::extra::handler`. The +method is `async` and takes the input by value: + +```rust +async fn compute_async(&self, _code: PhantomData, input: Input) -> Self::Output; +``` + +A context gains the capability by wiring `AsyncComputerComponent` to a provider, and it dispatches on +both the `Code` tag and the `Input` type. In everyday code the provider comes from +[`#[cgp_computer]`](../../macros/cgp_computer.md), which wires the promotion table so a synchronous +function also answers `CanComputeAsync`, and the crate ships a [`UseField`](../../providers/use_field.md) +provider that forwards the async computation to a field of the context. Its by-reference sibling is +[`AsyncComputerRef`](./async_computer_ref.md). + +## Examples + +A generic consumer awaits an async computation wired on its context: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::CanComputeAsync; + +async fn run(context: &Context, input: u64) -> Context::Output +where + Context: CanComputeAsync, +{ + context.compute_async(PhantomData::, input).await +} +``` + +`run` works for any context that wires an async computer for the given `Code` and `u64` input. The +example is **parameter-targeted**: the computation acts on the `Input`, while the context decides the +provider. A provider is usually generated from a function with +[`#[cgp_computer]`](../../macros/cgp_computer.md) rather than written by hand. + +## When to reach for it, and when not + +**Reach for `AsyncComputer` for a computation that awaits but cannot fail.** It is the async infallible +corner of the family, so a provider that only reads its input should prefer the by-reference +[`AsyncComputerRef`](./async_computer_ref.md). + +Reach for [`Computer`](./computer.md) instead when nothing needs awaiting, since a synchronous computer +promotes into an `AsyncComputer` for free and stays usable in more positions. Reach for +[`Handler`](./handler.md) when the computation can also fail. Implement whichever single variant fits and +let the wiring promote it. + +## Related constructs + +- [`Computer`](./computer.md) — the synchronous counterpart; promotes into this. +- [`AsyncComputerRef`](./async_computer_ref.md) — the by-reference variant of this component. +- [`Handler`](./handler.md) — adds a failure path on top of the asynchrony. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) — builds a provider that answers this through + promotion. +- [Handler combinators](../../providers/handler/index.md) — promote a `Computer` into this. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. + +## Source + +- `AsyncComputer` and `AsyncComputerRef`: + [`async_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/async_computer.rs) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/async_computer_ref.md b/docs/reference/components/handler/async_computer_ref.md new file mode 100644 index 00000000..44b31a61 --- /dev/null +++ b/docs/reference/components/handler/async_computer_ref.md @@ -0,0 +1,112 @@ +--- +sidebar_label: 'AsyncComputerRef' +sidebar_position: 9 +--- + +# `AsyncComputerRef` + +The async, by-reference member of the handler family: an [`AsyncComputer`](./async_computer.md) that +borrows its input. + +## Overview + +`AsyncComputerRef` combines two of the family's axes at once: it is asynchronous like +[`AsyncComputer`](./async_computer.md) and takes its input by reference like +[`ComputerRef`](./computer_ref.md). A computation that must await and only *reads* its argument, while +still never failing, fits it: its method is `async`, receives `&Input`, and returns the `Output` directly +with no failure path. It runs against a **context**, the type a capability runs against that supplies the +values an implementation needs as its own fields. + +It is the async by-reference corner of the infallible computers. Like the other computers it never names +an error type, so it does not supertrait [`HasErrorType`](../has_error_type.md). See the +[handler family overview](./index.md) for how the members relate and promote. + +## Definition + +`CanComputeAsyncRef` is defined as: + +```rust +#[async_trait] +#[cgp_component(AsyncComputerRef)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +pub trait CanComputeAsyncRef { + type Output; + + async fn compute_async_ref(&self, _code: PhantomData, input: &Input) -> Self::Output; +} +``` + +Its attributes: + +- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `AsyncComputerRef` that implementations target and the wiring key `AsyncComputerRefComponent`, while `CanComputeAsyncRef` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. + +## Usage + +`AsyncComputerRef` and its consumer trait `CanComputeAsyncRef` are imported from `cgp::extra::handler`. +The method is `async` and borrows the input: + +```rust +async fn compute_async_ref(&self, _code: PhantomData, input: &Input) -> Self::Output; +``` + +A context gains the capability by wiring `AsyncComputerRefComponent` to a provider, and it dispatches on +both the `Code` tag and the `Input` type. It is the least commonly wired member of the family, reached +when a computation is at once async, infallible, and read-only over its input. A simpler variant is +usually promoted into it through the [handler combinators](../../providers/handler/index.md). + +## Examples + +A generic consumer awaits an infallible computation over a borrowed input: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::CanComputeAsyncRef; + +async fn scan(context: &Context, input: &String) -> Context::Output +where + Context: CanComputeAsyncRef, +{ + context.compute_async_ref(PhantomData::, input).await +} +``` + +`scan` awaits the computation while keeping ownership of the `String` with the caller. The example is +**parameter-targeted**: the computation acts on the `Input`, while the context decides the provider. + +## When to reach for it, and when not + +**Reach for `AsyncComputerRef` when a computation is async and infallible and only reads its input.** +That is a narrow combination, so most code reaches a simpler member first and lets promotion bridge to +this one. + +Reach for [`AsyncComputer`](./async_computer.md) when the computation takes the input by value, for +[`ComputerRef`](./computer_ref.md) when a borrowed-input computation needs no awaiting, and for +[`HandlerRef`](./handler_ref.md) when a borrowed-input async computation can also fail. + +## Related constructs + +- [`AsyncComputer`](./async_computer.md) — the owned-input counterpart. +- [`ComputerRef`](./computer_ref.md) — the synchronous by-reference computer. +- [`HandlerRef`](./handler_ref.md) — the fallible async by-reference member. +- [Handler combinators](../../providers/handler/index.md) — promote a simpler variant into this. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. + +## Source + +- `AsyncComputer` and `AsyncComputerRef`: + [`async_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/async_computer.rs) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md new file mode 100644 index 00000000..dab0438a --- /dev/null +++ b/docs/reference/components/handler/computer.md @@ -0,0 +1,149 @@ +--- +sidebar_label: 'Computer' +sidebar_position: 1 +--- + +# `Computer` + +The pure synchronous transform of the handler family: infallible, and the simplest provider to write. + +## Overview + +`Computer` is for computations that always succeed and need no error type. A computation that adds two +numbers, formats a value, or projects a field never fails and never needs the **context's** abstract +error, so forcing it to return a `Result` would be noise. The context is the type a capability runs +against, which supplies the values an implementation needs as its own fields. `Computer` captures the +succeeds-always case: a provider names an `Output` type and produces it from the context, a phantom +`Code` tag, and an `Input`, with no failure path. + +It is the simplest member of the [handler family](/docs/concepts/handlers) and the one a provider author +reaches for first, because a pure computation can always be *promoted* into the fallible, async, and +general variants when the wiring needs them, while a fallible provider cannot be demoted back. Writing +the narrowest variant that fits keeps a provider usable in every position. + +## Definition + +`CanCompute` is defined as: + +```rust +#[cgp_component(Computer)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +pub trait CanCompute { + type Output; + + fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Computer` that implementations target and the wiring key `ComputerComponent`, while `CanCompute` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. + +## Usage + +`Computer` and its consumer trait `CanCompute` are imported from `cgp::extra::handler`. The consumer +method takes the context, a `PhantomData` naming which computation is wanted, and the `Input` by +value, returning the associated `Output`: + +```rust +fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; +``` + +A context gains the capability by wiring `ComputerComponent` to a provider. In everyday code the +provider comes from [`#[cgp_computer]`](../../macros/cgp_computer.md), which turns a plain function such as +`fn double(input: u64) -> u64` into a `Computer` provider and wires the promotion table so the same +function also answers `CanTryCompute`, `CanComputeAsync`, `CanHandle`, and the by-reference forms. + +The component dispatches on both the `Code` tag and the `Input` type. It has three siblings, each +differing from `Computer` by one axis and documented on its own page: +[`ComputerRef`](./computer_ref.md) borrows the input, [`AsyncComputer`](./async_computer.md) is the async +counterpart, and [`AsyncComputerRef`](./async_computer_ref.md) combines the two. None of the four +supertrait [`HasErrorType`](../has_error_type.md), because none of them can fail. + +## Examples + +A computer provider that doubles its input, wired into a context and invoked through the consumer trait: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::{CanCompute, Computer, ComputerComponent}; + +#[cgp_new_provider] +impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } +} + +#[derive(HasField)] +pub struct App; + +delegate_components! { + App { + ComputerComponent: Double, + } +} + +// `App` now implements `CanCompute<(), u64, Output = u64>`: +fn run(app: &App) -> u64 { + app.compute(PhantomData::<()>, 21) // returns 42 +} +``` + +`Double` implements the `Computer` provider trait for any context and any `Code`, fixing `Input` and +`Output` to `u64`. `App` delegates `ComputerComponent` to it, and the call passes `PhantomData::<()>` as +the `Code` tag. The example is **parameter-targeted**: the computation acts on the `Input` value, while +the context decides the provider. In practice a provider like this is written with +[`#[cgp_computer]`](../../macros/cgp_computer.md) rather than by hand. + +## When to reach for it, and when not + +**Reach for `Computer` for a synchronous transform that cannot fail.** It is the default member of the +family to implement, because promotion lifts it into every other variant, so one `Computer` provider can +answer a fallible or async bound elsewhere in the wiring. Prefer [`ComputerRef`](./computer_ref.md) when +the computation only reads its input, and [`AsyncComputer`](./async_computer.md) when it must await but +still cannot fail. + +Reach for [`TryComputer`](./try_computer.md) instead when the computation can fail, for +[`Handler`](./handler.md) when it is both async and fallible, and for [`Producer`](./producer.md) when it +takes no input. Do not force a fallible computation into a `Computer` by making its `Output` a `Result` +unless you specifically want the result passed through unexamined. + +## Related constructs + +- [`ComputerRef`](./computer_ref.md) — the by-reference variant that borrows its input. +- [`AsyncComputer`](./async_computer.md) — the async variant that awaits. +- [`AsyncComputerRef`](./async_computer_ref.md) — the async, by-reference variant. +- [`TryComputer`](./try_computer.md) — the fallible synchronous counterpart. +- [`Handler`](./handler.md) — the general async-and-fallible generalization. +- [`Producer`](./producer.md) — the input-free member of the family. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) — builds a `Computer` provider from a plain function. +- [Handler combinators](../../providers/handler/index.md) — compose computers and promote them into the + other variants. +- [`UseField`](../../providers/use_field.md) — the built-in computer provider that forwards to a context + field. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. +- [Dispatching](/docs/concepts/dispatching) — routing a computation on its `Code` or `Input`. + +## Source + +- The synchronous computers `Computer`/`ComputerRef`: + [`computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/computer.rs) +- The async computers `AsyncComputer`/`AsyncComputerRef`: + [`async_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/async_computer.rs) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/computer_ref.md b/docs/reference/components/handler/computer_ref.md new file mode 100644 index 00000000..9d364e11 --- /dev/null +++ b/docs/reference/components/handler/computer_ref.md @@ -0,0 +1,113 @@ +--- +sidebar_label: 'ComputerRef' +sidebar_position: 6 +--- + +# `ComputerRef` + +The by-reference member of the handler family: a [`Computer`](./computer.md) that borrows its input. + +## Overview + +`ComputerRef` is a [`Computer`](./computer.md) that takes its input by reference instead of by value. A +synchronous, infallible computation that only *reads* its argument and should not take ownership of it +fits `ComputerRef`, whose method receives `&Input` where `CanCompute` receives `Input`. Everything else +is the same: it transforms toward an `Output` under a phantom `Code` tag, against a **context** (the type +a capability runs against, which supplies the values an implementation needs as its own fields), and +returns the `Output` directly with no failure path. + +It is the owned-versus-borrowed variant of the pure computer, differing on the input axis alone. Like +`Computer` it never names an error type, so it does not supertrait +[`HasErrorType`](../has_error_type.md). See the [handler family overview](./index.md) for how the members +relate. + +## Definition + +`CanComputeRef` is defined as: + +```rust +#[cgp_component(ComputerRef)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +pub trait CanComputeRef { + type Output; + + fn compute_ref(&self, _code: PhantomData, input: &Input) -> Self::Output; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `ComputerRef` that implementations target and the wiring key `ComputerRefComponent`, while `CanComputeRef` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. + +## Usage + +`ComputerRef` and its consumer trait `CanComputeRef` are imported from `cgp::extra::handler`. The method +borrows the input: + +```rust +fn compute_ref(&self, _code: PhantomData, input: &Input) -> Self::Output; +``` + +A context gains the capability by wiring `ComputerRefComponent` to a provider, and it dispatches on both +the `Code` tag and the `Input` type. A provider that reads rather than consumes its input reaches for +this variant; a [`Computer`](./computer.md) can also be bridged to it by the +[`PromoteRef`](../../providers/handler/index.md) combinator, which supplies an owned input by +dereferencing the borrow. Its async counterpart is [`AsyncComputerRef`](./async_computer_ref.md). + +## Examples + +A generic consumer computes from a borrowed input: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::CanComputeRef; + +fn measure(context: &Context, input: &String) -> Context::Output +where + Context: CanComputeRef, +{ + context.compute_ref(PhantomData::, input) +} +``` + +`measure` passes the input by reference, so the caller keeps ownership of the `String`. The example is +**parameter-targeted**: the computation acts on the `Input`, while the context decides the provider. + +## When to reach for it, and when not + +**Reach for `ComputerRef` when a synchronous, infallible computation only needs to read its input.** It +avoids handing ownership to a computation that does not consume the value, which matters when the caller +reuses the input afterwards. + +Reach for [`Computer`](./computer.md) instead when the computation takes the input by value, which is the +more common case, and for [`AsyncComputerRef`](./async_computer_ref.md) when a borrowed-input computation +must also await. If the computation can fail, use [`TryComputer`](./try_computer.md) or its by-reference +sibling [`TryComputerRef`](./try_computer_ref.md). + +## Related constructs + +- [`Computer`](./computer.md) — the owned-input counterpart. +- [`AsyncComputerRef`](./async_computer_ref.md) — the async version of this by-reference variant. +- [`TryComputerRef`](./try_computer_ref.md) — the fallible by-reference computer. +- [Handler combinators](../../providers/handler/index.md) — the `PromoteRef` combinator bridging owned + and borrowed inputs. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. + +## Source + +- `Computer` and `ComputerRef`: + [`computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/computer.rs) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md new file mode 100644 index 00000000..84635564 --- /dev/null +++ b/docs/reference/components/handler/handler.md @@ -0,0 +1,149 @@ +--- +sidebar_label: 'Handler' +sidebar_position: 3 +--- + +# `Handler` + +The general computation component: asynchronous, fallible, and error-aware. + +## Overview + +`Handler` is the corner of the [handler family](/docs/concepts/handlers) that offers everything the +family can: a computation that runs asynchronously *and* can fail. A handler that calls a remote service +must await the response and must report failures, so it lives where the family is both async and +fallible. It transforms an `Input` into an `Output` under a phantom `Code` tag, returning a `Result` +against the **context's** abstract error type, where the context is the type a capability runs against +that supplies the values an implementation needs as its own fields. + +Every other handler component is a special case of `Handler` obtained by dropping one capability: drop +the failure path and it becomes an [`AsyncComputer`](./computer.md); drop the asynchrony and it becomes +a [`TryComputer`](./try_computer.md); drop both and it becomes a [`Computer`](./computer.md). This is why +generic pipeline code bounds against `Handler`: it is the one bound *every* member of the family can +meet, because each simpler provider promotes safely up to it. The reverse does not hold, since a general +computation cannot be assumed pure or synchronous. + +## Definition + +`CanHandle` is defined as: + +```rust +#[async_trait] +#[cgp_component(Handler)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanHandle { + type Output; + + async fn handle( + &self, + _tag: PhantomData, + input: Input, + ) -> Result; +} +``` + +Its attributes: + +- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Handler` that implementations target and the wiring key `HandlerComponent`, while `CanHandle` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. + +## Usage + +`Handler` and its consumer trait `CanHandle` are imported from `cgp::extra::handler`. The consumer +method is `async` and returns a `Result` against the context's error type: + +```rust +async fn handle(&self, _tag: PhantomData, input: Input) -> Result; +``` + +A context gains the capability by wiring `HandlerComponent` to a provider. In practice most `Handler` +implementations are not written directly but produced by *promoting* a simpler provider: a function +written as a [`#[cgp_computer]`](../../macros/cgp_computer.md) or [`#[cgp_producer]`](../../macros/cgp_producer.md) +wires the promotion table so the same function answers `CanHandle` too, and the +[handler combinators](../../providers/handler/index.md) lift the narrowest fitting variant to a handler +wherever one is required. + +The component dispatches on both the `Code` tag and the `Input` type, so wiring can route different +codes or inputs to different handlers, as covered under [dispatching](/docs/concepts/dispatching). Its +by-reference sibling [`HandlerRef`](./handler_ref.md), documented on its own page, is identical except +that its `handle_ref` method borrows the input as `&Input`. + +## Examples + +A generic consumer that bounds its context by `CanHandle` accepts any wired computation, whatever its +underlying capabilities: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::CanHandle; + +async fn run_with( + context: &Context, + input: String, +) -> Result +where + Context: CanHandle, +{ + context.handle(PhantomData::, input).await +} +``` + +`run_with` works for any context that wires a handler for the given `Code` and `String` input, whether +the wired provider is a pure `Computer`, a fallible `TryComputer`, an `AsyncComputer`, or a genuine +`Handler`, because the promotion combinators make each of them satisfy `CanHandle`. This is why generic +pipeline code targets `Handler`. The example is **parameter-targeted**: the computation acts on the +`Input` type, while the context decides which provider answers. + +## When to reach for it, and when not + +**Bound generic pipeline code against `CanHandle` when it should accept any computation regardless of +which capabilities the provider actually uses.** Because every simpler member promotes up to a handler, +a consumer written against `Handler` is the most reusable, and it is the right target for I/O steps, +request handlers, and composed pipelines. + +Do not *write* a `Handler` provider by hand when a simpler variant fits: implement a +[`Computer`](./computer.md) for a pure transform, a [`TryComputer`](./try_computer.md) for a fallible +synchronous one, or a [`Producer`](./producer.md) for an input-free one, and let the wiring promote it. +Writing the narrowest variant keeps the provider reusable in every position, where a `Handler` can only +be used where a full handler is wanted. + +## Related constructs + +- [`HandlerRef`](./handler_ref.md) — the by-reference variant that borrows its input. +- [`Computer`](./computer.md) — the pure synchronous member; promotes up to `Handler`. +- [`TryComputer`](./try_computer.md) — the fallible synchronous member; promotes up to `Handler`. +- [`AsyncComputer`](./async_computer.md) — the async infallible member; promotes up to `Handler`. +- [`Producer`](./producer.md) — the input-free member of the family. +- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Self::Error` a handler returns. +- [Handler combinators](../../providers/handler/index.md) — compose handlers and promote simpler variants + into them. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) / [`#[cgp_producer]`](../../macros/cgp_producer.md) — wire + a function so it answers `CanHandle` through promotion. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. +- [Monadic handlers](/docs/concepts/monadic-handlers) — chaining handlers that short-circuit through a + monad. +- [Recovering `Send` bounds](/docs/concepts/send-bounds) — restoring the `Send` guarantee an async trait + method drops. + +## Source + +- `Handler` and `HandlerRef`: + [`handler.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/handler.rs) +- The `ReturnInput` provider and the promotion combinators: + [`cgp-handler/src/providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/handler_ref.md b/docs/reference/components/handler/handler_ref.md new file mode 100644 index 00000000..7645a5c3 --- /dev/null +++ b/docs/reference/components/handler/handler_ref.md @@ -0,0 +1,128 @@ +--- +sidebar_label: 'HandlerRef' +sidebar_position: 8 +--- + +# `HandlerRef` + +The by-reference member of the handler family's general corner: a [`Handler`](./handler.md) that borrows +its input. + +## Overview + +`HandlerRef` is a [`Handler`](./handler.md) that takes its input by reference. It is asynchronous and +fallible like the general handler, so it awaits and may return the **context's** abstract error, but its +method receives `&Input` where `CanHandle` receives `Input`. The context is the type a capability runs +against, which supplies the values an implementation needs as its own fields. `HandlerRef` is the +owned-versus-borrowed variant of the family's most general member, differing on the input axis alone, for +an async-and-fallible computation that reads rather than consumes its argument. + +Because it can fail, it supertraits [`HasErrorType`](../has_error_type.md), which supplies the +`Self::Error` it names in its `Result`. See the [handler family overview](./index.md) for how the members +relate and promote. + +## Definition + +`CanHandleRef` is defined as: + +```rust +#[async_trait] +#[cgp_component(HandlerRef)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanHandleRef { + type Output; + + async fn handle_ref( + &self, + _tag: PhantomData, + input: &Input, + ) -> Result; +} +``` + +Its attributes: + +- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `HandlerRef` that implementations target and the wiring key `HandlerRefComponent`, while `CanHandleRef` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. + +## Usage + +`HandlerRef` and its consumer trait `CanHandleRef` are imported from `cgp::extra::handler`. The method is +`async`, borrows the input, and returns a `Result`: + +```rust +async fn handle_ref(&self, _tag: PhantomData, input: &Input) -> Result; +``` + +A context gains the capability by wiring `HandlerRefComponent` to a provider, and it dispatches on both +the `Code` tag and the `Input` type. Because the consumer trait supertraits `HasErrorType`, the context +must also wire an error type. A [`Handler`](./handler.md) is bridged to `HandlerRef` by the +[`PromoteRef`](../../providers/handler/index.md) combinator, which supplies an owned input by dereferencing +the borrow, so most `HandlerRef` implementations come from promotion rather than being written by hand. + +## Examples + +A generic consumer awaits a fallible computation over a borrowed input: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::CanHandleRef; + +async fn serve( + context: &Context, + request: &String, +) -> Result +where + Context: CanHandleRef, +{ + context.handle_ref(PhantomData::, request).await +} +``` + +`serve` passes the request by reference, so the caller keeps ownership, and returns the context's +abstract error on failure. The example is **parameter-targeted**: the computation acts on the `Input`, +while the context decides the provider and the error type. + +## When to reach for it, and when not + +**Reach for `HandlerRef` when an async, fallible computation only needs to read its input**, for instance +a request handler that inspects a borrowed request without consuming it. Bounding generic pipeline code +against it accepts any provider that fits, since the simpler by-reference variants promote up to it. + +Reach for [`Handler`](./handler.md) instead when the computation takes the input by value, which is the +more common case, and for [`TryComputerRef`](./try_computer_ref.md) when a borrowed-input fallible +computation is synchronous. Do not write a `HandlerRef` by hand when a simpler by-reference variant fits: +implement that and let the wiring promote it. + +## Related constructs + +- [`Handler`](./handler.md) — the owned-input counterpart, and the family's general corner. +- [`TryComputerRef`](./try_computer_ref.md) — the synchronous fallible by-reference computer. +- [`AsyncComputerRef`](./async_computer_ref.md) — the infallible async by-reference computer. +- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Self::Error` this returns. +- [Handler combinators](../../providers/handler/index.md) — the `PromoteRef` combinator that bridges + `Handler` and `HandlerRef`. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. +- [Recovering `Send` bounds](/docs/concepts/send-bounds) — restoring the `Send` guarantee an async trait + method drops. + +## Source + +- `Handler` and `HandlerRef`: + [`handler.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/handler.rs) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/index.md b/docs/reference/components/handler/index.md new file mode 100644 index 00000000..85ec1d8f --- /dev/null +++ b/docs/reference/components/handler/index.md @@ -0,0 +1,52 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# The handler family + +The handler family models a computation as a swappable component, so a pipeline step, an I/O call, or a +type-level interpreter is wired and composed the same way as any other component. Every member +transforms an `Input` into an `Output` under a phantom `Code` tag, against a **context**, the type a +capability runs against that supplies the values an implementation needs as its own fields. The members +differ along three axes: synchronous or async, infallible or fallible, and taking an input or not. This +page maps the family; each member has its own page for the full detail. + +The one distinction that organizes the rest is which corner of those axes a member sits in. +[`Computer`](./computer.md) is the simplest, a pure synchronous transform that cannot fail. +[`TryComputer`](./try_computer.md) adds a failure path, returning a `Result` against the context's +abstract error type. [`Handler`](./handler.md) adds asynchrony on top of that, so it is both async and +fallible, and it is the general corner every other member is a special case of. +[`Producer`](./producer.md) is the odd one out on the input axis: it takes no input and simply yields a +value from the context and a `Code` tag. + +The family is built to be written from its weakest member and promoted upward. A pure `Computer` +promotes into a `TryComputer` by wrapping its output in `Ok`, into an `AsyncComputer` by wrapping it in a +future that never awaits, and all the way up to a `Handler`; a `Producer` promotes into any of them by +ignoring the input the target supplies. Because promotion only ever widens, a provider author implements +the narrowest variant that fits and lets the wiring lift it wherever a more capable one is required. +This is why generic pipeline code bounds against [`Handler`](./handler.md): it is the one bound every +member can meet. + +The family has nine members in all, because three of the base members carry by-reference and, for the +computers, async siblings, each a component of its own that differs from its base by a single axis. The +computers cover both axes: [`Computer`](./computer.md) with [`ComputerRef`](./computer_ref.md), +[`AsyncComputer`](./async_computer.md), and [`AsyncComputerRef`](./async_computer_ref.md); +[`TryComputer`](./try_computer.md) with [`TryComputerRef`](./try_computer_ref.md); and +[`Handler`](./handler.md) with [`HandlerRef`](./handler_ref.md). [`Producer`](./producer.md) has no such +sibling, because it has no input to borrow. Each has its own page; the variant pages lean on their base +member for the shared model. + +You rarely implement a member of this family by hand. Providers come from +[`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md), +which turn a plain function into a provider and wire the promotion table so one function answers the +whole family, and they are composed and routed with the +[handler combinators](../../providers/handler/index.md), the +[dispatch combinators](../../providers/dispatch/index.md), and the +[monad providers](../../providers/monad/index.md). A fallible member supertraits +[`HasErrorType`](../has_error_type.md), and an effectful one reaches the runtime through +[`HasRuntime`](../has_runtime.md). + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/producer.md b/docs/reference/components/handler/producer.md new file mode 100644 index 00000000..12c0b24b --- /dev/null +++ b/docs/reference/components/handler/producer.md @@ -0,0 +1,135 @@ +--- +sidebar_label: 'Producer' +sidebar_position: 4 +--- + +# `Producer` + +The input-free member of the handler family: a synchronous, infallible source of a value. + +## Overview + +`Producer` is for computations that take nothing to compute and simply yield a value. A handler that +supplies a default configuration, a constant, or a value read entirely from the **context** has no +`Input` to transform: it needs only the context and a phantom `Code` tag to know which value to produce. +The context is the type a capability runs against, which supplies the values an implementation needs as +its own fields. The rest of the [handler family](/docs/concepts/handlers) threads an `Input` through +every method; `Producer` is the case where that input is absent. It is the simplest component in the +family, synchronous and infallible, producing an `Output` directly. + +Being input-free does not isolate a producer from the family. It makes it the natural *source* of values +that flow into the other handlers: a producer promotes into any computer or handler by ignoring whatever +input that variant supplies and returning the produced value regardless. This is how a constant or a +context-derived value enters a computation pipeline. + +## Definition + +`CanProduce` is defined as: + +```rust +#[cgp_component(Producer)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +pub trait CanProduce { + type Output; + + fn produce(&self, _code: PhantomData) -> Self::Output; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Producer` that implementations target and the wiring key `ProducerComponent`, while `CanProduce` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Code` type, so a context can route each `Code` to its own provider; the `open` statement is the modern sugar for the same dispatch. + +## Usage + +`Producer` and its consumer trait `CanProduce` are imported from `cgp::extra::handler`. The consumer +method takes only the context and a `Code` tag, with no `Input`: + +```rust +fn produce(&self, _code: PhantomData) -> Self::Output; +``` + +A context gains the capability by wiring `ProducerComponent` to a provider. In everyday use the provider +comes from [`#[cgp_producer]`](../../macros/cgp_producer.md), which turns a zero-argument function such as +`fn magic_number() -> u64 { 42 }` into a `Producer` provider and wires `PromoteProducer` so the +same function also answers the input-taking components. Because there is no input to dispatch on, the +component dispatches on the `Code` tag alone, with no `Input`-keyed table. `Producer` has no +by-reference or async sibling, since there is no input to borrow. + +## Examples + +A producer wired into a context and invoked directly: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::{CanProduce, Producer, ProducerComponent}; + +#[cgp_new_provider] +impl Producer for MagicNumber { + type Output = u64; + + fn produce(_context: &Context, _code: PhantomData) -> u64 { + 42 + } +} + +pub struct App; + +delegate_components! { + App { + ProducerComponent: MagicNumber, + } +} + +fn run(app: &App) -> u64 { + app.produce(PhantomData::<()>) // returns 42 +} +``` + +`MagicNumber` produces `42` from the `Code` tag alone, and `App` delegates `ProducerComponent` to it, +giving `App` the `CanProduce<(), Output = u64>` capability. The example is **parameter-targeted**: the +context decides which provider answers, and no value is operated on. In practice the provider is written +with [`#[cgp_producer]`](../../macros/cgp_producer.md), which also wires the promotion so the same function +answers the input-taking components while ignoring their input. + +## When to reach for it, and when not + +**Reach for `Producer` for a value that a computation needs but does not compute from an input**, such +as a constant, a default, or a value read from the context. It is the family's source, and promotion +lets one producer feed the input-taking members: delegating a context's handler surface to +`PromoteProducer` makes one producer answer `CanCompute`, `CanTryCompute`, `CanComputeAsync`, +`CanHandle`, and their by-reference forms. + +Reach for [`Computer`](./computer.md) instead when the value is computed *from* an input, and for +[`TryComputer`](./try_computer.md) or [`Handler`](./handler.md) when producing it can fail or must await. + +## Related constructs + +- [`Computer`](./computer.md) — the synchronous input-taking member; a producer promotes into it. +- [`TryComputer`](./try_computer.md) — the fallible member of the family. +- [`Handler`](./handler.md) — the general async-and-fallible member. +- [`#[cgp_producer]`](../../macros/cgp_producer.md) — builds a `Producer` provider from a zero-argument + function. +- [Handler combinators](../../providers/handler/index.md) — the `Promote` provider and the `PromoteProducer` + table that lift a producer into the rest of the family. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. + +## Source + +- `Producer`: + [`produce.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/produce.rs) +- The `Promote` combinator and the `PromoteProducer` table: + [`cgp-handler/src/providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/try_computer.md b/docs/reference/components/handler/try_computer.md new file mode 100644 index 00000000..9e030a16 --- /dev/null +++ b/docs/reference/components/handler/try_computer.md @@ -0,0 +1,153 @@ +--- +sidebar_label: 'TryComputer' +sidebar_position: 2 +--- + +# `TryComputer` + +The fallible synchronous member of the handler family: a computer that can return an error. + +## Overview + +`TryComputer` is for synchronous computations that can fail. 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`](./computer.md) returns its `Output` directly, `TryComputer` returns +`Result`, where the error is the **context's** shared abstract error type. The context is +the type a capability runs against, which supplies the values an implementation needs as its own fields. +This places `TryComputer` one step up from `Computer` on the fallibility axis of the +[handler family](/docs/concepts/handlers), still synchronous but now able to fail, and one step below +[`Handler`](./handler.md), which adds asynchrony on top. + +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 +`Self::Error`, and the concrete type is decided at wiring time. This is why the component supertraits +[`HasErrorType`](../has_error_type.md): the supertrait supplies the `Self::Error` it names in its +`Result`, and it ties every fallible component in a context to the same error so their results compose. + +## Definition + +`CanTryCompute` is defined as: + +```rust +#[cgp_component(TryComputer)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanTryCompute { + type Output; + + fn try_compute( + &self, + _code: PhantomData, + input: Input, + ) -> Result; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `TryComputer` that implementations target and the wiring key `TryComputerComponent`, while `CanTryCompute` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. + +## Usage + +`TryComputer` and its consumer trait `CanTryCompute` are imported from `cgp::extra::handler`. The +consumer method mirrors `compute` but returns a `Result`: + +```rust +fn try_compute(&self, _code: PhantomData, input: Input) -> Result; +``` + +A context gains the capability by wiring `TryComputerComponent` to a provider. In everyday use the +provider comes from [`#[cgp_computer]`](../../macros/cgp_computer.md), which turns a function returning +`Result` into a `TryComputer` provider and wires the promotion table so the same function +also answers `CanCompute`, `CanHandle`, and the by-reference forms. + +The component dispatches on both the `Code` tag and the `Input` type. Its by-reference sibling +[`TryComputerRef`](./try_computer_ref.md), documented on its own page, differs by one axis: its +`try_compute_ref` method borrows the input as `&Input`. Both are synchronous; the async-and-fallible +counterpart is [`Handler`](./handler.md). + +## Examples + +A `TryComputer` provider that parses a string into a number, raising the context's error on failure: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::{CanTryCompute, TryComputer, TryComputerComponent}; + +#[cgp_impl(new ParseU64)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl TryComputer { + type Output = u64; + + fn try_compute( + &self, + _code: PhantomData, + input: String, + ) -> Result { + input.parse().map_err(|e| Self::raise_error(e)) + } +} + +delegate_components! { + App { + TryComputerComponent: ParseU64, + } +} +``` + +`ParseU64` returns its `u64` output or the context's abstract error, converting the concrete +`ParseIntError` into that error with [`CanRaiseError`](../can_raise_error.md). Because the consumer trait +supertraits `HasErrorType`, `App` must also wire an error type and an error raiser before it can call +`try_compute`. The example is **parameter-targeted**: the computation acts on the `Input`, while the +context decides the provider and the error type. + +## When to reach for it, and when not + +**Reach for `TryComputer` for a synchronous computation that can fail.** It is the fallible middle of +the family, and it sits in the promotion lattice, so it both receives providers promoted from a +[`Computer`](./computer.md) and is itself promoted up to a [`Handler`](./handler.md). Prefer +`TryComputerRef` when the computation only reads its input. + +Reach for [`Computer`](./computer.md) instead when the computation cannot fail, since a pure computer +promotes into a `TryComputer` for free and stays usable in more positions, and for +[`Handler`](./handler.md) when the computation must also await. A provider author implements whichever +single variant fits and lets the wiring bridge the rest. + +## Related constructs + +- [`TryComputerRef`](./try_computer_ref.md) — the by-reference variant that borrows its input. +- [`Computer`](./computer.md) — the infallible counterpart; promotes into a `TryComputer`. +- [`Handler`](./handler.md) — the async-and-fallible generalization. +- [`Producer`](./producer.md) — the input-free member of the family. +- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Self::Error` this returns. +- [`CanRaiseError`](../can_raise_error.md) — converts a concrete source error into that abstract error. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) — builds a `TryComputer` provider from a fallible + function. +- [Handler combinators](../../providers/handler/index.md) — promote a `Computer` into this and this into a + `Handler`. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. +- [Modular error handling](/docs/concepts/modular-error-handling) — the abstract error a fallible + computer returns. + +## Source + +- `TryComputer` and `TryComputerRef`: + [`try_compute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/try_compute.rs) +- The `ReturnInput` provider and the promotion combinators: + [`cgp-handler/src/providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/try_computer_ref.md b/docs/reference/components/handler/try_computer_ref.md new file mode 100644 index 00000000..941961a3 --- /dev/null +++ b/docs/reference/components/handler/try_computer_ref.md @@ -0,0 +1,123 @@ +--- +sidebar_label: 'TryComputerRef' +sidebar_position: 7 +--- + +# `TryComputerRef` + +The by-reference member of the handler family's fallible corner: a [`TryComputer`](./try_computer.md) +that borrows its input. + +## Overview + +`TryComputerRef` is a [`TryComputer`](./try_computer.md) that takes its input by reference. A synchronous +computation that can fail and only *reads* its argument fits it: its method receives `&Input` and returns +`Result`, where the error is the **context's** abstract error type. The context is the +type a capability runs against, which supplies the values an implementation needs as its own fields. +`TryComputerRef` is the owned-versus-borrowed variant of the fallible synchronous computer, differing on +the input axis alone. + +Because it can fail, it supertraits [`HasErrorType`](../has_error_type.md), which supplies the +`Self::Error` it names in its `Result` and ties it to the same error every other fallible component in +the context uses. See the [handler family overview](./index.md) for how the members relate and promote. + +## Definition + +`CanTryComputeRef` is defined as: + +```rust +#[cgp_component(TryComputerRef)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanTryComputeRef { + type Output; + + fn try_compute_ref( + &self, + _code: PhantomData, + input: &Input, + ) -> Result; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `TryComputerRef` that implementations target and the wiring key `TryComputerRefComponent`, while `CanTryComputeRef` stays the consumer trait callers use. +- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. + +## Usage + +`TryComputerRef` and its consumer trait `CanTryComputeRef` are imported from `cgp::extra::handler`. The +method borrows the input and returns a `Result`: + +```rust +fn try_compute_ref(&self, _code: PhantomData, input: &Input) -> Result; +``` + +A context gains the capability by wiring `TryComputerRefComponent` to a provider, and it dispatches on +both the `Code` tag and the `Input` type. Because the consumer trait supertraits `HasErrorType`, the +context must also wire an error type before it can call `try_compute_ref`. A provider that reads rather +than consumes its input reaches for this variant; the owned-input [`TryComputer`](./try_computer.md) is +the more common one. + +## Examples + +A generic consumer runs a fallible computation over a borrowed input: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::extra::handler::CanTryComputeRef; + +fn check( + context: &Context, + input: &String, +) -> Result +where + Context: CanTryComputeRef, +{ + context.try_compute_ref(PhantomData::, input) +} +``` + +`check` passes the input by reference, so the caller keeps the `String`, and returns the context's +abstract error on failure. The example is **parameter-targeted**: the computation acts on the `Input`, +while the context decides the provider and the error type. + +## When to reach for it, and when not + +**Reach for `TryComputerRef` when a fallible synchronous computation only needs to read its input.** It +keeps ownership with the caller while still reporting failure through the context's error type. + +Reach for [`TryComputer`](./try_computer.md) instead when the computation takes the input by value, for +[`ComputerRef`](./computer_ref.md) when a borrowed-input computation cannot fail, and for +[`Handler`](./handler.md) or [`HandlerRef`](./handler_ref.md) when it must also await. + +## Related constructs + +- [`TryComputer`](./try_computer.md) — the owned-input counterpart. +- [`ComputerRef`](./computer_ref.md) — the infallible by-reference computer. +- [`HandlerRef`](./handler_ref.md) — the async-and-fallible by-reference member. +- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Self::Error` this returns. +- [`CanRaiseError`](../can_raise_error.md) — converts a concrete source error into that abstract error. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and + input-passing axes. +- [Modular error handling](/docs/concepts/modular-error-handling) — the abstract error a fallible + computer returns. + +## Source + +- `TryComputer` and `TryComputerRef`: + [`try_compute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/try_compute.rs) +- Re-exported through `cgp::extra::handler`. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index 687a317a..7115fa01 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -1,17 +1,157 @@ --- sidebar_label: 'HasErrorType' +sidebar_position: 1 --- # `HasErrorType` -The abstract error type every fallible CGP capability names. +Give a context one shared, abstract `Error` type, so fallible generic code never names a concrete error. -:::info +## Overview -### Not written yet +`HasErrorType` lets generic CGP code fail without committing to a concrete error type. A provider that +may error has to produce *some* error, but it runs against a **context**, the type a capability runs +against that supplies the values an implementation needs, and it cannot know whether that context wants +`anyhow::Error`, `std::io::Error`, or an enum of its own. `HasErrorType` resolves this by giving the +context one abstract `Self::Error` type that every fallible operation refers to. Generic code returns +`Result`, and the concrete error is decided once, at wiring time, by whichever error +backend the context plugs in. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +Putting the error type on one component also keeps errors composable. If each fallible trait declared +its own associated `Error`, a context bounded by several of them would face several unrelated `Self::Error` +types with no way to unify them. Because the fallible components all supertrait `HasErrorType`, every one +of them names the *same* `Self::Error`, so their results combine. This single shared abstract error is +the anchor that [`CanRaiseError`](./can_raise_error.md) and [`CanWrapError`](./can_wrap_error.md) build +on. -::: +## Definition + +`HasErrorType` is defined as: + +```rust +#[cgp_type] +#[prefix(@cgp.core.error in DefaultNamespace)] +pub trait HasErrorType { + type Error: Debug; +} + +pub type ErrorOf = ::Error; +``` + +Its attributes: + +- [`#[cgp_type]`](../macros/cgp_type.md) — makes this an abstract-type component rather than a plain trait: it generates the provider trait, the component marker, and a [`UseType`](../providers/use_type.md) impl, so a context binds the concrete type by wiring. +- [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. + +## Usage + +`HasErrorType` is in the prelude, so `use cgp::prelude::*;` is enough to name it. It is an +abstract-type component: a +[trait](https://doc.rust-lang.org/book/ch10-02-traits.html) with one +[associated type](https://doc.rust-lang.org/reference/items/associated-items.html), `Error`, carrying a +`Debug` bound. A context supplies its error type in one of two ways. + +The direct way is an ordinary trait impl, which shows that `HasErrorType` is a plain associated-type +trait: + +```rust +impl HasErrorType for App { + type Error = anyhow::Error; +} +``` + +The wired way, and the common one, delegates the component's key to a provider that supplies the type. +Because `HasErrorType` is defined with [`#[cgp_type]`](../macros/cgp_type.md), a context can name the +concrete error directly with [`UseType`](../providers/use_type.md): + +```rust +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} +``` + +The wiring key is `ErrorTypeProviderComponent`, not the trait name, and it lives under +`cgp::core::error` rather than in the prelude, so a context that wires it imports the key. Whatever +concrete error is chosen must implement `Debug`, because that bound is carried through every generated +construct. The standalone backend crates `cgp-error-anyhow`, `cgp-error-eyre`, and `cgp-error-std` +supply ready-made providers that set `Error` to their respective types. + +Generic code names the abstract error with the [`#[use_type]`](../attributes/use_type.md) attribute, +which imports it as the bare name `Error`, or through the `ErrorOf` alias, which spells +`::Error`. + +## Examples + +A context declares its abstract error, and generic code returns it without naming a concrete type: + +```rust +use cgp::prelude::*; + +#[cgp_component(Validator)] +#[use_type(HasErrorType.Error)] +pub trait CanValidate { + fn validate(&self) -> Result<(), Error>; +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} +``` + +Here [`#[use_type(HasErrorType.Error)]`](../attributes/use_type.md) adds `HasErrorType` as a supertrait +of `CanValidate` and rewrites the bare `Error` to `::Error`, so `validate` returns +the context's shared error without spelling `Self::Error`. `App` wires its error type to `String`, which +satisfies the `Debug` bound. `App` is an **environmental context**, a type that stands for the +application and carries its choices, and the capability targets that context rather than a value. + +## When to reach for it, and when not + +**Reach for `HasErrorType` in any fallible component whose error type the context should choose.** It is +the foundation of CGP's error handling and is a supertrait of every other fallible capability, so a +component that returns a `Result` almost always wants the context's abstract error rather than a +concrete one. Import it with [`#[use_type(HasErrorType.Error)]`](../attributes/use_type.md) rather than +writing a `: HasErrorType` supertrait and a `Self::Error` path by hand. + +Do not reach for it when a component genuinely wants one fixed error type for the whole program with no +per-context choice, where a concrete error in the signature is simpler. And where a provider must pin +the abstract error to a concrete type, use the equality form +[`#[use_type(HasErrorType.{Error = AppError})]`](../attributes/use_type.md) rather than a hand-written +`where Self: HasErrorType` clause. + +## Related constructs + +- [`#[cgp_type]`](../macros/cgp_type.md) — the macro `HasErrorType` is defined with, which generates its + `UseType` provider. +- [`HasType` / `TypeProvider`](./has_type.md) — the built-in abstract-type substrate `#[cgp_type]` + builds this on. +- [`CanRaiseError`](./can_raise_error.md) — raises a source error into this abstract error. +- [`CanWrapError`](./can_wrap_error.md) — wraps detail onto this abstract error. +- [`#[use_type]`](../attributes/use_type.md) — imports the abstract error into a definition as the bare + name `Error`. +- [Error providers](../providers/error/index.md) — the interchangeable strategies that construct the + error. + +The ideas behind it: + +- [Modular error handling](/docs/concepts/modular-error-handling) — the abstract error type, its + construction, and its detail as three independent wiring decisions. +- [Abstract types](/docs/concepts/abstract-types) — the associated types a context chooses for itself. + +## Source + +- The trait and the `ErrorOf` alias: + [`has_error_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/traits/has_error_type.rs) +- The `#[cgp_type]` machinery it relies on: + [`cgp_type/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_type/) +- The pluggable concrete error backends: + [`standalone/error/`](https://github.com/contextgeneric/cgp/tree/main/crates/standalone/error/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index 3f40f140..a1d361e0 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -1,17 +1,152 @@ --- -sidebar_label: 'HasRuntime & HasRuntimeType' +sidebar_label: 'HasRuntime' +sidebar_position: 6 --- -# `HasRuntime` & `HasRuntimeType` +# `HasRuntime` -The abstract runtime type and the accessor that reaches it. +Hand out a borrow of the context's runtime value, so effectful code reaches it generically. -:::info +## Overview -### Not written yet +`HasRuntime` lets context-generic code obtain the runtime it runs against without naming a concrete one. +A runtime here is whatever object provides the capabilities an application needs at execution time, +spawning tasks, sleeping, opening sockets, reading the clock, and different deployments want different +runtimes: Tokio in production, a mock in tests, a single-threaded executor in a benchmark. Rather than +thread a concrete runtime type through every signature, the **context**, the type a capability runs +against that supplies the values an implementation needs as its own fields, stores one runtime value, +and `HasRuntime` is the getter that borrows it. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`HasRuntime` answers *how to obtain the runtime value*; its companion +[`HasRuntimeType`](./has_runtime_type.md) answers *what the runtime type is*. The two are split because +the questions are independent: some code names only the runtime type and never touches a value, and +needs `HasRuntimeType` alone, while code that performs effects needs `HasRuntime`, which supertraits +`HasRuntimeType` so the value's type is always in scope. `HasRuntime` is the seam where context-generic +logic meets the concrete async machinery, which is why it underpins the [`CanRun`](./runner.md) family +of task runners. -::: +## Definition + +`HasRuntime` is defined as: + +```rust +#[cgp_getter] +#[use_type(HasRuntimeType.Runtime)] +pub trait HasRuntime { + fn runtime(&self) -> &Runtime; +} +``` + +Its attributes: + +- [`#[cgp_getter]`](../macros/cgp_getter.md) — makes this a getter component: it derives the provider name from the trait name and generates a [`UseField`](../providers/use_field.md) impl, so the field it reads is chosen by wiring. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasRuntimeType` as a supertrait and rewrites the bare `Runtime` to `::Runtime`. + +## Usage + +`HasRuntime` is imported from `cgp::extra::runtime`. It is a getter component: its method borrows the +runtime value out of a borrow of the context, returning `&Runtime`, where `Runtime` is the abstract type +supplied by [`HasRuntimeType`](./has_runtime_type.md): + +```rust +fn runtime(&self) -> &Runtime; +``` + +A context supplies the value either by implementing `HasRuntime` directly or, more commonly, by wiring +`RuntimeGetterComponent` to a [`UseField`](../providers/use_field.md) provider that names the field +holding the runtime. Because `HasRuntime` supertraits `HasRuntimeType`, a context cannot satisfy it +without also having declared its runtime *type*, which keeps the returned `&Runtime` well-defined. A +context that stores its runtime in a `runtime` field wires: + +```rust +delegate_components! { + App { + RuntimeTypeProviderComponent: UseType, + RuntimeGetterComponent: UseField, + } +} +``` + +One entry fixes the abstract runtime type, and the other says where the value lives. Context-generic +providers then write `where Self: HasRuntime` and call `self.runtime()` to obtain a `&RuntimeOf`, +never naming the concrete runtime. + +## Examples + +A context declares its runtime type and the field holding the value, and a provider reaches the runtime +generically: + +```rust +use cgp::prelude::*; +use cgp::extra::runtime::{HasRuntime, HasRuntimeType, RuntimeOf}; + +pub struct TokioRuntime { /* handle, clock, etc. */ } + +#[derive(HasField)] +pub struct App { + pub runtime: TokioRuntime, +} + +delegate_components! { + App { + RuntimeTypeProviderComponent: UseType, + RuntimeGetterComponent: UseField, + } +} + +fn runtime_of(context: &Context) -> &RuntimeOf +where + Context: HasRuntime, +{ + context.runtime() +} +``` + +`App` resolves `HasRuntimeType` with `Runtime = TokioRuntime` through `UseType`, and resolves +`HasRuntime` by reading its `runtime` field through `UseField`. `runtime_of` names neither +`TokioRuntime` nor any field, so swapping `UseType` for `UseType` in a test +context retargets it at the mock with no change to its body. `App` is an **environmental context**, and +the capability targets it. + +## When to reach for it, and when not + +**Reach for `HasRuntime` in any provider that performs an effect against the runtime**, such as spawning +a task, awaiting a timer, or opening a connection, and reach it as a `#[uses(HasRuntime)]` dependency so +the bound stays off the consumer trait. It is the standard way effectful CGP code stays generic over the +runtime, and it makes the same task-running code reusable across a Tokio context, a mock, and a +test executor with only a wiring change. + +Reach for [`HasRuntimeType`](./has_runtime_type.md) alone when code names the runtime type but never +touches a value, which asks for exactly the capability it uses. Do not reach for `HasRuntime` when a +value the provider needs is not really the runtime but an ordinary context field, where an +[`#[implicit]`](../attributes/implicit.md) argument is simpler. + +## Related constructs + +- [`HasRuntimeType`](./has_runtime_type.md) — the companion that declares the runtime *type* this + borrows. +- [`CanRun` / `Runner`](./runner.md) — the primary consumer, reaching the runtime through `HasRuntime` to + execute work. +- [`CanSendRun` / `SendRunner`](./send_runner.md) — the `Send`-future variant of the runner. +- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro `HasRuntime` is defined with. +- [`UseField`](../providers/use_field.md) — the provider that reads the runtime value from a named field. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the effectful computation family that reaches the runtime through + this getter. +- [Abstract types](/docs/concepts/abstract-types) — the abstract runtime type a context chooses for + itself. + +## Source + +- `HasRuntime` and its `RuntimeGetter` provider trait: + [`has_runtime.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-runtime/src/traits/has_runtime.rs) +- Re-exported through `cgp::extra::runtime`: + [`cgp-runtime/src/lib.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-runtime/src/lib.rs) +- The `#[cgp_getter]` expansion it relies on: + [`cgp-macro-core/src/types/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md new file mode 100644 index 00000000..fae6f853 --- /dev/null +++ b/docs/reference/components/has_runtime_type.md @@ -0,0 +1,129 @@ +--- +sidebar_label: 'HasRuntimeType' +sidebar_position: 7 +--- + +# `HasRuntimeType` + +Declare the abstract runtime *type* a context runs against, chosen per context through wiring. + +## Overview + +`HasRuntimeType` lets context-generic code name the runtime type a context uses without committing to a +concrete one. A runtime is whatever object supplies the capabilities an application needs at execution +time, and different deployments want different runtimes: Tokio in production, a mock in tests, an +executor in a benchmark. `HasRuntimeType` gives the **context**, the type a capability runs against that +supplies the values an implementation needs as its own fields, an abstract associated `Runtime` type, +resolved to a concrete one at wiring time. + +The runtime abstraction is split into a type component and a getter component because the two questions +are independent. `HasRuntimeType` answers *what the runtime type is*, while its companion +[`HasRuntime`](./has_runtime.md) answers *how to obtain the runtime value* from a borrow of the context. +Some code is generic only over the runtime type: it names types the runtime exposes but never touches a +runtime value, and it needs `HasRuntimeType` alone. Keeping the type separate means such a bound asks +for exactly the capability it uses. + +## Definition + +`HasRuntimeType` is defined as: + +```rust +#[cgp_type] +pub trait HasRuntimeType { + type Runtime; +} + +pub type RuntimeOf = ::Runtime; +``` + +Its attributes: + +- [`#[cgp_type]`](../macros/cgp_type.md) — makes this an abstract-type component rather than a plain trait: it generates the provider trait, the component marker, and a [`UseType`](../providers/use_type.md) impl, so a context binds the concrete type by wiring. + +## Usage + +`HasRuntimeType` is imported from `cgp::extra::runtime`. It is an abstract-type component with a single +associated type, `Runtime`, carrying no bound, so any concrete type may be plugged in. A context supplies +the type either by implementing `HasRuntimeType` directly or, more commonly, by wiring +`RuntimeTypeProviderComponent` to [`UseType`](../providers/use_type.md): + +```rust +delegate_components! { + App { + RuntimeTypeProviderComponent: UseType, + } +} +``` + +This makes the context resolve `HasRuntimeType` with `Runtime = TokioRuntime`, and from then on the +alias `RuntimeOf` is `TokioRuntime`. Generic code names the runtime type with the +[`#[use_type]`](../attributes/use_type.md) attribute, which imports it as the bare name `Runtime`, or +through the `RuntimeOf` alias. + +## Examples + +A context fixes its runtime type, and generic code names it without committing to a concrete one: + +```rust +use cgp::prelude::*; +use cgp::extra::runtime::{HasRuntimeType, RuntimeOf}; + +pub struct TokioRuntime { /* handle, clock, etc. */ } + +pub struct App; + +delegate_components! { + App { + RuntimeTypeProviderComponent: UseType, + } +} + +fn describe() -> &'static str +where + Context: HasRuntimeType, + RuntimeOf: Default, +{ + "the context has a default-constructible runtime type" +} +``` + +`App` resolves `HasRuntimeType` with `Runtime = TokioRuntime` through `UseType`, so `RuntimeOf` is +`TokioRuntime`. `describe` names only the runtime type and never a runtime value, which is exactly the +case `HasRuntimeType` serves alone. `App` is an **environmental context**, and the capability targets it. + +## When to reach for it, and when not + +**Reach for `HasRuntimeType` when code names the runtime type but never touches a runtime value.** That +is the narrower of the two runtime capabilities, and asking for it alone keeps a bound honest about what +it uses. It is also the type half a context must wire before it can satisfy +[`HasRuntime`](./has_runtime.md), because the getter borrows a value of this type. + +Reach for [`HasRuntime`](./has_runtime.md) instead when a provider actually performs an effect and needs +the runtime *value*, since `HasRuntime` supertraits this one and gives access to both. For an abstract +type that is not the runtime, define your own component with [`#[cgp_type]`](../macros/cgp_type.md) +rather than reusing this one. + +## Related constructs + +- [`HasRuntime`](./has_runtime.md) — the getter companion that borrows a value of this type. +- [`#[cgp_type]`](../macros/cgp_type.md) — the macro `HasRuntimeType` is defined with. +- [`HasType` / `TypeProvider`](./has_type.md) — the built-in abstract-type substrate this rests on. +- [`UseType`](../providers/use_type.md) — the provider that fixes the runtime type in wiring. +- [`CanRun` / `Runner`](./runner.md) — the task runner whose providers reach the runtime. + +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — the associated types a context chooses for itself. + +## Source + +- `HasRuntimeType`, the `RuntimeTypeProvider` provider trait, and the `RuntimeOf` alias: + [`has_runtime_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-runtime/src/traits/has_runtime_type.rs) +- Re-exported through `cgp::extra::runtime`: + [`cgp-runtime/src/lib.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-runtime/src/lib.rs) +- The `#[cgp_type]` expansion it relies on: + [`cgp-macro-core/src/types/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index 6781aea2..18d79246 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -1,17 +1,144 @@ --- -sidebar_label: 'HasType & TypeProvider' +sidebar_label: 'HasType' +sidebar_position: 4 --- -# `HasType` & `TypeProvider` +# `HasType` -CGP's built-in abstract-type component. +CGP's single built-in abstract-type component: a tag-indexed type a context resolves through wiring. -:::info +## Overview -### Not written yet +`HasType` lets generic code refer to a type that is chosen per context without committing to a +concrete one. An abstract type in CGP is a +[trait](https://doc.rust-lang.org/book/ch10-02-traits.html) with a single +[associated type](https://doc.rust-lang.org/reference/items/associated-items.html), and `HasType` +is the foundational, tag-indexed instance of that pattern. A **context**, the type a capability runs +against, can carry many distinct abstract types, one per `Tag`, and resolve each to a concrete type +through wiring. Generic code names `Self::Type` (or the alias `TypeOf`), the concrete type +stays hidden behind the tag, and any context that wires the tag to a type satisfies the bound. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +What makes `HasType` central is that it is the *only* abstract-type component built into CGP, and it is +the machinery [`#[cgp_type]`](../macros/cgp_type.md) defers to. Every named abstract-type component a +program defines with `#[cgp_type]`, including [`HasErrorType`](./has_error_type.md) and +[`HasRuntimeType`](./has_runtime_type.md), is wired on top of this one, so the same +[`UseType`](../providers/use_type.md) marker that resolves `HasType` also resolves any `#[cgp_type]` +component. `HasType` is the common substrate; `#[cgp_type]` is the ergonomic layer that gives each +abstract type its own named trait. -::: +## Definition + +`HasType` is defined as: + +```rust +#[cgp_component(TypeProvider)] +#[derive_delegate(UseDelegate)] +pub trait HasType { + type Type; +} + +pub type TypeOf = >::Type; +``` + +Its attributes: + +- [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `TypeProvider` that implementations target and the wiring key `TypeProviderComponent`, while `HasType` stays the consumer trait callers use. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Tag` type, so a context can route each `Tag` to its own provider; the `open` statement is the modern sugar for the same dispatch. + +## Usage + +`HasType` is in the prelude. It carries a `Tag` parameter, the type-level name that distinguishes one +abstract type from another within a context, and an associated `Type` that the tag resolves to. A +context supplies the type in one of two ways. + +The direct way is an ordinary trait impl. The wired way, and the common one, delegates the component's +key `TypeProviderComponent` to [`UseType`](../providers/use_type.md), the zero-sized marker that +reports its own parameter as the abstract type: + +```rust +delegate_components! { + App { + TypeProviderComponent: UseType, + } +} +``` + +In most code you would not wire `HasType` directly. You would define a named abstract type with +[`#[cgp_type]`](../macros/cgp_type.md), such as `#[cgp_type] trait HasScalarType { type Scalar; }`, +which gives a readable `Self::Scalar` and its own provider trait and marker, all resolving down to this +`HasType` substrate. The related [`#[use_type]`](../attributes/use_type.md) attribute, distinct from the +`UseType` provider despite the shared name, rewrites a bare type name and adds the bound inside a +definition. + +## Examples + +A direct use defines no new component and resolves an abstract type by tag through `UseType`: + +```rust +use cgp::prelude::*; + +pub struct ScalarTag; + +pub struct App; + +delegate_components! { + App { + TypeProviderComponent: UseType, + } +} + +fn zero() -> TypeOf +where + Context: HasType, + TypeOf: Default, +{ + Default::default() +} +``` + +`App` wires `TypeProviderComponent` to `UseType`, so the `UseType` impl makes `App` implement +`HasType` with `Type = f64`. `App` is an **environmental context** here, a type standing for +the application that carries its type choices. In real code you would write the named `#[cgp_type]` +layer; this page documents the substrate it rests on. + +## When to reach for it, and when not + +**You rarely name `HasType` directly. Reach for [`#[cgp_type]`](../macros/cgp_type.md) instead**, which +defines a named abstract type with its own readable trait, and let it build on this substrate. The one +time `HasType` is useful on its own is when a program wants a family of abstract types keyed by a +tag it computes rather than a fixed set of named traits. + +Recognizing `HasType` matters more than writing it: an expansion or an error message names it +when a `#[cgp_type]` component fails to resolve, and knowing that every abstract type reduces to it +explains why the one [`UseType`](../providers/use_type.md) provider wires all of them. + +## Related constructs + +- [`#[cgp_type]`](../macros/cgp_type.md) — builds every named abstract-type component on this substrate. +- [`UseType`](../providers/use_type.md) — the zero-sized marker that supplies a concrete type to the + abstract one. +- [`#[use_type]`](../attributes/use_type.md) — the differently-named attribute that imports an abstract + type into a definition; do not confuse the two. +- [`UseDelegatedType`](../providers/use_delegated_type.md) — resolves an abstract type through a table + rather than fixing it. +- [`WithProvider`](../providers/with_provider.md) — the adapter that lets a `TypeProvider` stand in as a + named component's provider. +- [`HasErrorType`](./has_error_type.md) — a concrete abstract-type component built on this one. + +The ideas behind it: + +- [Abstract types](/docs/concepts/abstract-types) — the associated types a context chooses for itself, + and why a determined type propagates nowhere while a parameter propagates everywhere. + +## Source + +- The trait, the `TypeProvider` provider trait, and the `TypeOf` alias: + [`has_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/traits/has_type.rs) +- The `UseType` provider and its `TypeProvider` impl: + [`use_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/impls/use_type.rs) +- The `#[cgp_type]` macro that builds named components on this substrate: + [`cgp_type/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_type/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/index.md b/docs/reference/components/index.md new file mode 100644 index 00000000..a275ecee --- /dev/null +++ b/docs/reference/components/index.md @@ -0,0 +1,72 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Components + +A component is one capability, defined once, that a context can wire to any of several +implementations. The constructs on the other pages of this reference are the tools you use to *build* +your own components; the pages in this section document the components CGP already ships. Each is a +consumer trait you call, a provider trait an implementation targets, and a wiring key a context +delegates, exactly like a component you define yourself, so you wire a built-in error type or runtime +with the same [`delegate_components!`](../macros/delegate_components.md) table as everything else. + +A context is the type a capability runs against, which supplies whatever values an implementation needs +as its own fields. You wire these components onto a context and call them the way you call any CGP +capability. This page groups them by the job they do, in roughly the order most CGP code reaches for +them. If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here. + +## Handle errors + +CGP keeps the error type abstract so that fallible generic code never names a concrete error, and three +components carry that. [`HasErrorType`](./has_error_type.md) gives a context one shared abstract `Error` +type, chosen once at wiring time, so that every fallible operation refers to the same error and their +results compose. It is the component nearly every non-trivial program meets, and the two below build on +it. + +[`CanRaiseError`](./can_raise_error.md) turns a concrete source error into that abstract error, so a +provider can call `Context::raise_error(source)` without knowing what the context's error type is. +[`CanWrapError`](./can_wrap_error.md) attaches detail to an error the context already holds, such as a +message or a path, as it propagates. Both dispatch per source or detail type, and both are usually +satisfied by wiring one of the [error providers](../providers/error/index.md) or a standalone backend +crate rather than by hand. + +## Let each context choose a type + +[`HasType`](./has_type.md) is CGP's single built-in abstract-type component: a tag-indexed trait whose +associated type a context resolves to a concrete one through wiring. Every named abstract type a program +defines with [`#[cgp_type]`](../macros/cgp_type.md), including `HasErrorType` and +[`HasRuntimeType`](./has_runtime_type.md) below, is built on this substrate, and the same +[`UseType`](../providers/use_type.md) marker resolves all of them. You reach for `HasType` directly +only rarely, but recognizing it explains how every other abstract type in a codebase works. + +## Compute things + +The [handler family](./handler/index.md) models a computation as a swappable component along three axes: +synchronous or async, fallible or not, and taking an input or not. It is a subsection of its own, with +one page per member. [`Computer`](./handler/computer.md) is the pure synchronous transform that never +fails, [`TryComputer`](./handler/try_computer.md) adds a failure path, and +[`Handler`](./handler/handler.md) is the general corner, async and fallible, that generic pipeline code +targets because every simpler member promotes up to it. [`Producer`](./handler/producer.md) is the +input-free case that yields a value from the context alone. + +Each of `Computer`, `TryComputer`, and `Handler` also has by-reference and, for the computers, async +siblings, such as `ComputerRef`, `AsyncComputer`, and `HandlerRef`. These differ from the base member by +one axis and are documented on the base member's page. Providers for the family are written from plain +functions with [`#[cgp_computer]`](../macros/cgp_computer.md) and +[`#[cgp_producer]`](../macros/cgp_producer.md), then composed with the +[handler combinators](../providers/handler/index.md). + +## Run tasks against a runtime + +The last group executes work and supplies the runtime that work runs on. [`HasRuntime`](./has_runtime.md) +hands out a borrow of the context's runtime value, and [`HasRuntimeType`](./has_runtime_type.md) declares +the abstract runtime *type* it borrows, so a provider reaches a Tokio runtime, a mock, or a test executor +generically. [`CanRun`](./runner.md) runs a task named at the type level to a `Result<(), Error>`, and +[`CanSendRun`](./send_runner.md) is the variant whose returned future is `Send`, for work that must cross +a thread boundary. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/producer.md b/docs/reference/components/producer.md deleted file mode 100644 index aa18f026..00000000 --- a/docs/reference/components/producer.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: 'Producer & CanProduce' ---- - -# `Producer` & `CanProduce` - -The input-free production component. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index 9464d03d..9d0c69ce 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -1,17 +1,148 @@ --- -sidebar_label: 'CanRun & CanSendRun' +sidebar_label: 'CanRun' +sidebar_position: 8 --- -# `CanRun` & `CanSendRun` +# `CanRun` -The task-running components. +Run a task named at the type level to a `Result<(), Error>`, with the behavior chosen through wiring. -:::info +## Overview -### Not written yet +`CanRun` gives a context a uniform way to *execute a unit of work* selected at the type level. The +unit of work is identified by a `Code` type parameter, a phantom tag rather than a value, so a single +**context**, the type a capability runs against that supplies the values an implementation needs as its +own fields, can host many distinct tasks, one per `Code`, and dispatch each to its own provider. Running +a task here means invoking the provider wired for that `Code` and awaiting an asynchronous +`Result<(), Error>`: the task either completes or produces the context's abstract error. The component +carries no input or output beyond success-or-error, so it models a fire-and-complete action rather than +a transformation, which separates it from the [handler family](./handler/index.md) that maps an +`Input` to an `Output`. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +`CanRun` is the execution layer that ties a CGP application together: a runner provider typically reaches +the context's runtime through [`HasRuntime`](./has_runtime.md) to spawn or await work, and dispatches to +other components to do the actual job. Application code calls `CanRun` to set everything in +motion. Its companion [`CanSendRun`](./send_runner.md) is the variant whose returned future is `Send`, +for when the work must cross a thread boundary. -::: +## Definition + +`CanRun` is defined as: + +```rust +#[cgp_component(Runner)] +#[async_trait] +#[derive_delegate(UseDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanRun { + async fn run(&self, _code: PhantomData) -> Result<(), Error>; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Runner` that implementations target and the wiring key `RunnerComponent`, while `CanRun` stays the consumer trait callers use. +- [`#[async_trait]`](../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Code` type, so a context can route each `Code` to its own provider; the `open` statement is the modern sugar for the same dispatch. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. + +## Usage + +`CanRun` is imported from `cgp::extra::run`. Its method is `async` and takes only a `Code` tag: + +```rust +async fn run(&self, _code: PhantomData) -> Result<(), Error>; +``` + +A context gains the capability by wiring `RunnerComponent` to a provider. Because the component dispatches +on `Code`, the idiomatic way a context hosts several tasks is the `open` statement, routing each task tag +to its own provider: + +```rust +delegate_components! { + App { + open RunnerComponent; + + @RunnerComponent.ActionA: RunWithFooBar, + @RunnerComponent.ActionB: SpawnAndRun, + } +} +``` + +With this wiring, `app.run(PhantomData::)` runs the `RunWithFooBar` provider while +`app.run(PhantomData::)` runs `SpawnAndRun`. A runner provider is a normal CGP +provider written for the `Runner` provider trait; it receives `&Context` and the `PhantomData` tag +and may call other components on the context, fetching values or performing effects, before it completes. +Existing code often wires the same dispatch with the older `UseDelegate` table, which the `open` +statement supersedes. + +## Examples + +A spawning runner provider requires the context to be [`CanSendRun`](./send_runner.md) so it can hand a +`Send` future to a spawner, and runs an inner task on a background thread: + +```rust +#[cgp_impl(new SpawnAndRun: RunnerComponent)] +#[use_type(HasErrorType.Error)] +impl Runner +where + Self: 'static + Send + Clone + CanSendRun, +{ + async fn run(&self, _code: PhantomData) -> Result<(), Error> { + let context = self.clone(); + + spawn(async move { + let _ = context.send_run(PhantomData).await; + }); + + Ok(()) + } +} +``` + +`SpawnAndRun` runs the task `Code` by cloning the context and spawning the *inner* task `InCode`. +The spawner requires a `Send + 'static` future, which `context.send_run(PhantomData::)` +returns, so the bound `Self: CanSendRun` makes the spawn type-check. None of the abstract +task or error types carry `Send` bounds; that requirement is discharged only at the concrete +[`CanSendRun`](./send_runner.md) proxy. `App` is an **environmental context**, and the task is a +type-level `Code` selector the wiring dispatches on. + +## When to reach for it, and when not + +**Reach for `CanRun` to model a unit of work a context executes to completion**, such as a background +job, a startup action, or a scheduled task, especially when one context hosts several such tasks that +should each dispatch to their own provider. It is the entry point application code calls, and it composes +with [`HasRuntime`](./has_runtime.md) for the runtime the work runs on. + +Reach for the [handler family](./handler/index.md) instead when the work transforms an `Input` into an +`Output` rather than only succeeding or failing, and reach for [`CanSendRun`](./send_runner.md) when the +future must be `Send` to be spawned across threads. For a synchronous action that cannot fail, a plain +method or a [`Computer`](./handler/computer.md) is simpler than a runner. + +## Related constructs + +- [`CanSendRun` / `SendRunner`](./send_runner.md) — the variant whose future is `Send`, for spawning + across threads. +- [`HasRuntime`](./has_runtime.md) — the runtime a runner provider reaches to spawn or await work. +- [`HasErrorType`](./has_error_type.md) — the supertrait supplying the `Self::Error` a task fails with. +- [Handler family](./handler/index.md) — the computation components a runner dispatches to, which + transform an input rather than only completing. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates the per-`Code` dispatch this uses. + +The ideas behind it: + +- [Handlers](/docs/concepts/handlers) — the effectful computation family a runner drives. +- [Recovering `Send` bounds](/docs/concepts/send-bounds) — the workaround the `Send` runner variant + embodies. + +## Source + +- `CanRun` / `Runner` and `CanSendRun` / `SendRunner`: + [`cgp-run/src/lib.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-run/src/lib.rs), + reached from the facade as `cgp::extra::run`. +- The `#[cgp_component]` and `#[derive_delegate]` expansions they rely on: + [`cgp-macro-core/src/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/send_runner.md b/docs/reference/components/send_runner.md new file mode 100644 index 00000000..96bb221a --- /dev/null +++ b/docs/reference/components/send_runner.md @@ -0,0 +1,145 @@ +--- +sidebar_label: 'CanSendRun' +sidebar_position: 9 +--- + +# `CanSendRun` + +The runner variant whose returned future is `Send`, for work that must cross a thread boundary. + +## Overview + +`CanSendRun` is [`CanRun`](./runner.md) with one added guarantee: the future its method returns is +[`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html), so it can be handed to a spawner such as +`tokio::spawn`. It exists to solve a specific Rust limitation. A generic `async fn` over abstract +**context** types (the context being the type a capability runs against that supplies the values an +implementation needs as its own fields) cannot promise its future is `Send` without annotating `Send` +bounds on every abstract type in scope, and those bounds pollute every interface. +`CanSendRun` sidesteps that by returning an explicit +`impl Future> + Send`, so the `Send` requirement lives on this one trait +rather than spreading across the abstract types. + +A context implements `CanSendRun` as a thin proxy over its [`CanRun`](./runner.md) +implementation. Because the proxy is written against the *concrete* context, the compiler can confirm +the concrete future is `Send` without abstract-type annotations. This is a workaround that stays +necessary until Rust stabilizes Return Type Notation; once that lands, the `Send`-bound future could be +expressed without the separate trait. The pattern is developed as a concept in +[recovering `Send` bounds](/docs/concepts/send-bounds). + +## Definition + +`CanSendRun` is defined as: + +```rust +#[cgp_component(SendRunner)] +#[async_trait] +#[derive_delegate(UseDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanSendRun { + fn send_run( + &self, + _code: PhantomData, + ) -> impl Future> + Send; +} +``` + +Its attributes: + +- [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `SendRunner` that implementations target and the wiring key `SendRunnerComponent`, while `CanSendRun` stays the consumer trait callers use. +- [`#[async_trait]`](../macros/async_trait.md) — the attribute CGP's async trait methods carry; it rewrites an `async fn` into a lint-clean `-> impl Future` method. Here `send_run` is already written in that form so it can add the `+ Send` bound that [`CanRun`](./runner.md)'s `run` omits. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Code` type, so a context can route each `Code` to its own provider; the `open` statement is the modern sugar for the same dispatch. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. + +## Usage + +`CanSendRun` is imported from `cgp::extra::run`. Its method differs from `run` only in the shape of its +return, an explicit `Send` future rather than a plain `async fn`: + +```rust +fn send_run(&self, _code: PhantomData) -> impl Future> + Send; +``` + +A context gains the capability by wiring `SendRunnerComponent`, or, in the common case, by supplying a +proxy impl on the concrete context that forwards to its own `run`. The proxy discharges the +`Send` bound: + +```rust +#[cgp_provider] +impl SendRunner for App { + async fn send_run(context: &App, code: PhantomData) -> Result<(), Infallible> { + context.run(code).await + } +} +``` + +Because this impl names the concrete `App` and `ActionA`, the future produced by `context.run(code)` has +a fully known type, so the compiler can verify it is `Send` and satisfy the `+ Send` bound on +`send_run`, which the generic [`CanRun`](./runner.md) definition deliberately does not assert. A spawning +runner provider can then require `Context: CanSendRun`, clone the context into a `Send` future, +and hand it to a spawner, all without `Send` bounds leaking into the abstract interfaces. + +## Examples + +A spawning provider requires the context to be `CanSendRun` and hands a `Send` future to a spawner: + +```rust +#[cgp_impl(new SpawnAndRun: RunnerComponent)] +#[use_type(HasErrorType.Error)] +impl Runner +where + Self: 'static + Send + Clone + CanSendRun, +{ + async fn run(&self, _code: PhantomData) -> Result<(), Error> { + let context = self.clone(); + + spawn(async move { + let _ = context.send_run(PhantomData).await; + }); + + Ok(()) + } +} +``` + +The spawner requires a `Send + 'static` future, which +`context.send_run(PhantomData::)` returns, so the bound `Context: CanSendRun` +makes the spawn type-check. The context wires its [`CanRun`](./runner.md) tasks and supplies a +`SendRunner` proxy for the inner task, and the `Send` bound is discharged only at that concrete proxy, +never on the abstract task or error types. `App` is an **environmental context**, and the task is a +type-level `Code` selector. + +## When to reach for it, and when not + +**Reach for `CanSendRun` when a runner's future must be `Send`**, which in practice means whenever the +work is handed to a work-stealing spawner like `tokio::spawn`. A provider that spawns bounds its context +by `CanSendRun` and supplies a concrete proxy for each task it spawns, which keeps the `Send` +requirement out of every abstract interface. + +Do not reach for it when the future is never spawned across a thread boundary, where plain +[`CanRun`](./runner.md) is enough and needs no proxy. `CanSendRun` is a targeted workaround for the +`Send`-future limitation rather than a default: use it only where the `Send` bound is actually required. + +## Related constructs + +- [`CanRun` / `Runner`](./runner.md) — the base runner this proxies, without the `Send` requirement. +- [`HasRuntime`](./has_runtime.md) — the runtime a spawning runner reaches to hand off the `Send` future. +- [`HasErrorType`](./has_error_type.md) — the supertrait supplying the `Self::Error` a task fails with. +- [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates the per-`Code` dispatch this uses. + +The ideas behind it: + +- [Recovering `Send` bounds](/docs/concepts/send-bounds) — restoring the `Send` guarantee an async trait + method drops, which this component embodies. +- [Handlers](/docs/concepts/handlers) — the effectful computation family a runner drives. + +## Source + +- `CanSendRun` / `SendRunner`, defined beside `CanRun`: + [`cgp-run/src/lib.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-run/src/lib.rs), + reached from the facade as `cgp::extra::run`. +- The `#[cgp_component]` and `#[derive_delegate]` expansions it relies on: + [`cgp-macro-core/src/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/try_computer.md b/docs/reference/components/try_computer.md deleted file mode 100644 index f2560218..00000000 --- a/docs/reference/components/try_computer.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: 'TryComputer & CanTryCompute' ---- - -# `TryComputer` & `CanTryCompute` - -The fallible computer. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/docs/reference/index.md b/docs/reference/index.md index da4b18c4..885e1b09 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -21,7 +21,7 @@ its own. The construct list below is complete — every construct the `cgp` crate exports has a page, or a named place on a page it shares — so nothing is missing from this index. The macros, attributes, derives, -traits, and providers are written; the components and type-level pages are still placeholders, and each +traits, providers, and components are written; the type-level pages are still placeholders, and each one says so when you open it. ::: @@ -117,22 +117,29 @@ in as a named component's. ### Handle errors -[`HasErrorType`](./components/has_error_type.md) gives a context one shared error type, and -[`CanRaiseError` and `CanWrapError`](./components/can_raise_error.md) construct it from a source error -and attach detail. The interchangeable strategies that satisfy them — `RaiseFrom`, `ReturnError`, -`DebugError`, and the rest — are the [error providers](./providers/error/index.md). +[`HasErrorType`](./components/has_error_type.md) gives a context one shared error type, +[`CanRaiseError`](./components/can_raise_error.md) constructs it from a source error, and +[`CanWrapError`](./components/can_wrap_error.md) attaches detail to it. The interchangeable strategies +that satisfy them — `RaiseFrom`, `ReturnError`, `DebugError`, and the rest — are the +[error providers](./providers/error/index.md). ### Compute things -The handler family models computation along three axes: synchronous or async, fallible or not, taking -an input or not. [`Computer`](./components/computer.md) is the plain synchronous transform, -[`TryComputer`](./components/try_computer.md) adds fallibility, -[`Handler`](./components/handler.md) is the general async and fallible case, and -[`Producer`](./components/producer.md) is the input-free one. -[`CanRun`](./components/runner.md) runs tasks and [`HasRuntime`](./components/has_runtime.md) supplies -the runtime they run on. Each of those four has by-reference and, where it applies, async siblings — -`ComputerRef`, `AsyncComputer`, `HandlerRef`, and the rest — documented on the page for the component -they vary. +The [handler family](./components/handler/index.md) models computation along three axes: synchronous or +async, fallible or not, taking an input or not. [`Computer`](./components/handler/computer.md) is the +plain synchronous transform, [`TryComputer`](./components/handler/try_computer.md) adds fallibility, +[`Handler`](./components/handler/handler.md) is the general async and fallible case, and +[`Producer`](./components/handler/producer.md) is the input-free one. +[`CanRun`](./components/runner.md) runs tasks, [`CanSendRun`](./components/send_runner.md) is its +`Send`-future variant, and [`HasRuntime`](./components/has_runtime.md) with +[`HasRuntimeType`](./components/has_runtime_type.md) supplies the runtime they run on. Each of the three +computers and the handler also has by-reference and, where it applies, async siblings — +[`ComputerRef`](./components/handler/computer_ref.md), +[`AsyncComputer`](./components/handler/async_computer.md), +[`AsyncComputerRef`](./components/handler/async_computer_ref.md), +[`TryComputerRef`](./components/handler/try_computer_ref.md), and +[`HandlerRef`](./components/handler/handler_ref.md) — each a component with its own page under the +[handler family](./components/handler/index.md). Providers in this family are written from plain functions with [`#[cgp_computer]`](./macros/cgp_computer.md) and [`#[cgp_producer]`](./macros/cgp_producer.md), and @@ -221,15 +228,12 @@ name, and [`CanUseComponent`](./traits/can_use_component.md), which is what a ch Almost every construct has a page of its own. The exceptions are names that are not separately *constructs*: a **marker** is a type implementing a trait, an **alias** is another spelling of a -construct, and a **variant** of a component differs from it by one axis. Each is documented on the page +construct, and a **variant** differs from a base construct by one axis. Each is documented on the page of the thing it belongs to. If you arrived knowing one of these names, this is where it lives. | Looking for | It's on | |---|---| | `#[cgp_new_provider]` | [`#[cgp_provider]`](./macros/cgp_provider.md) | -| `CanSendRun` | [`CanRun`](./components/runner.md) | -| `CanWrapError` | [`CanRaiseError`](./components/can_raise_error.md) | -| `HasRuntimeType` | [`HasRuntime`](./components/has_runtime.md) | | `WithType`, `WithField`, `WithContext` | [`WithProvider`](./providers/with_provider.md) | | `Cons`, `Nil`, `Either`, `Void`, `Chars`, `PathCons` | [Type-level spines](./types/type_level_spines.md) | | `IdentMonadic`, `OkMonadic`, `ErrMonadic`, `OkMonadicTrans`, `ErrMonadicTrans` | [Monad providers](./providers/monad/index.md) | @@ -237,7 +241,6 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w | `MatchWithHandlersRef`, `MatchFirstWithHandlers`, and the other borrowed and first-argument matcher forms | the matcher page they vary, under [Dispatch combinators](./providers/dispatch/index.md) | | `ExtractFirstFieldAndHandle`, `HandleFirstFieldValue` | [`ExtractFieldAndHandle`](./providers/dispatch/extract_field_and_handle.md), [`HandleFieldValue`](./providers/dispatch/handle_field_value.md) | | `DispatchMatchers`, `ToFieldHandlers`, `HasFieldHandlers`, `MapFieldHandler` | [Dispatch combinators](./providers/dispatch/index.md) | -| `ComputerRef`, `AsyncComputer`, `TryComputerRef`, `HandlerRef` | the page for the component they vary — [`Computer`](./components/computer.md), [`TryComputer`](./components/try_computer.md), [`Handler`](./components/handler.md) | | `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` | [`MapType`](./traits/map_type.md) | | `IsRef`, `IsMut`, `IsOwned` | [`MapTypeRef`](./traits/map_type_ref.md) | | `product!` (the value-level form) | [`Product!`](./macros/product.md) | diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 52e8423c..2c24c920 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -250,7 +250,7 @@ provider needed it; it did not, and removing it changes nothing. - [`#[cgp_component]`](./cgp_component.md) — the usual host, with `#[async_trait]` placed outermost. - [`#[cgp_fn]`](./cgp_fn.md) — the other host, with `#[async_trait]` placed beneath it. - [`#[cgp_impl]`](./cgp_impl.md) — where a provider writes an ordinary `async fn` body and needs no attribute. -- [`Handler`](../components/handler.md) — CGP's built-in async, fallible component, declared this way. +- [`Handler`](../components/handler/handler.md) — CGP's built-in async, fallible component, declared this way. - [`#[cgp_computer]`](./cgp_computer.md) — where an `async` function selects the async base trait. - [Handler combinators](../providers/handler/index.md) — the promotions that lift a synchronous provider into an async one. diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index c509323f..119a6c0b 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -259,7 +259,7 @@ hand for some other type without colliding with it. directly for anything it cannot express. - [`#[cgp_computer]`](./cgp_computer.md) — how each per-variant handler is emitted. - [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — what the enum needs to be dispatchable. -- [`Computer`](../components/computer.md) — the component the generated bound is written against. +- [`Computer`](../components/handler/computer.md) — the component the generated bound is written against. - [`ExtractField`](../traits/extract_field.md) — the extractor family the matching walks. - [`#[cgp_component]`](./cgp_component.md) — the better starting point when contexts should configure the operation. diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 946a9489..ba8147ec 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -209,7 +209,7 @@ an implementation should compose with a wrapper. A component trait is an ordinary trait. It takes as many methods, associated types, and associated consts as any other, and every one of them is reproduced on the provider trait. CGP's own -[`CanCompute`](../components/computer.md) declares an associated `Output` beside its method, and there +[`CanCompute`](../components/handler/computer.md) declares an associated `Output` beside its method, and there is no cap. What to group is a judgement rather than a rule, and the useful question is: **everything in one diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 299726b0..cee8c0db 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -272,8 +272,8 @@ short-circuits. ## Related constructs - [`#[cgp_producer]`](./cgp_producer.md) — the input-free sibling, producing a `Producer`. -- [`Computer`](../components/computer.md) — the base component, with its by-reference and async variants. -- [`Handler`](../components/handler.md) and [`TryComputer`](../components/try_computer.md) — the more capable +- [`Computer`](../components/handler/computer.md) — the base component, with its by-reference and async variants. +- [`Handler`](../components/handler/handler.md) and [`TryComputer`](../components/handler/try_computer.md) — the more capable members the promotions reach. - [Handler combinators](../providers/handler/index.md) — the `Promote*` bundles this wires, plus `PipeHandlers` and `ComposeHandlers` for composing steps. diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 79760a86..4c859871 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -21,7 +21,7 @@ fn magic_number() -> u64 { } ``` -That produces the provider struct `MagicNumber` and an impl of [`Producer`](../components/producer.md), the +That produces the provider struct `MagicNumber` and an impl of [`Producer`](../components/handler/producer.md), the family member whose method takes only a **context** (the type the capability runs against) and a phantom `Code` tag, with no input value at all. @@ -131,7 +131,7 @@ within it there is nothing simpler. ## Under the hood -The macro emits the function unchanged, a provider impl of [`Producer`](../components/producer.md), and a +The macro emits the function unchanged, a provider impl of [`Producer`](../components/handler/producer.md), and a [`delegate_components!`](./delegate_components.md) block wiring the whole family. From this input: ```rust @@ -245,10 +245,10 @@ import. ## Related constructs - [`#[cgp_computer]`](./cgp_computer.md) — the sibling for a computation that takes an input. -- [`Producer`](../components/producer.md) — the base component this implements. +- [`Producer`](../components/handler/producer.md) — the base component this implements. - [Handler combinators](../providers/handler/index.md) — `PromoteProducer`, which this wires, plus `ReturnInput` and `PipeHandlers`. -- [`Computer`](../components/computer.md) and [`Handler`](../components/handler.md) — the members the +- [`Computer`](../components/handler/computer.md) and [`Handler`](../components/handler/handler.md) — the members the promotion reaches. - [`#[cgp_impl]`](./cgp_impl.md) — for a producer that needs its context, which is most of them. - [`#[cgp_new_provider]`](./cgp_provider.md) — what the generated impl is emitted through. diff --git a/docs/reference/providers/dispatch/index.md b/docs/reference/providers/dispatch/index.md index 0f92f80e..86420c6a 100644 --- a/docs/reference/providers/dispatch/index.md +++ b/docs/reference/providers/dispatch/index.md @@ -15,9 +15,9 @@ variants is not known at the call site and the handling logic for each one lives provider. A hand-written `match` names every variant in one place; these combinators instead drive the extractor and builder trait families to do the same work over a value whose shape is only known at the type level, dispatching each field or variant to a handler chosen by type. They run on a **context**, -the type a capability runs against, and are all [`Computer`](../../components/computer.md)-family -providers, several also [`Handler`](../../components/handler.md) and -[`TryComputer`](../../components/try_computer.md) providers. Like every CGP provider, each is zero-sized. +the type a capability runs against, and are all [`Computer`](../../components/handler/computer.md)-family +providers, several also [`Handler`](../../components/handler/handler.md) and +[`TryComputer`](../../components/handler/try_computer.md) providers. Like every CGP provider, each is zero-sized. The combinators divide into two halves. diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index 70ffb11a..5491620e 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -92,7 +92,7 @@ reduces any `Debug` source to the one case the context knows. Each impl is paire ## Related constructs - [`DisplayError`](display_error.md) — the same provider formatting with `Display` and `to_string()`. -- [`CanRaiseError` and `CanWrapError`](../../components/can_raise_error.md) — the components it supplies, +- [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) — the components it supplies, and the `String` forms it forwards to. - [`RaiseFrom`](raise_from.md) — the usual provider on the `String` source that finishes the raise. - [`UseDelegate`](../use_delegate.md) — dispatches `DebugError` for the source types it should format. diff --git a/docs/reference/providers/error/discard_detail.md b/docs/reference/providers/error/discard_detail.md index 403d873b..409e248b 100644 --- a/docs/reference/providers/error/discard_detail.md +++ b/docs/reference/providers/error/discard_detail.md @@ -65,7 +65,7 @@ generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the sa ## Related constructs -- [`CanWrapError`](../../components/can_raise_error.md) — the component `DiscardDetail` supplies, through +- [`CanWrapError`](../../components/can_wrap_error.md) — the component `DiscardDetail` supplies, through the `ErrorWrapper` provider trait. - [`DebugError`](debug_error.md), [`DisplayError`](display_error.md) — wrap by keeping the detail as a formatted string instead of discarding it. diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md index 128b4725..a7d642ab 100644 --- a/docs/reference/providers/error/display_error.md +++ b/docs/reference/providers/error/display_error.md @@ -85,7 +85,7 @@ Both bounds require the context to already handle `String`. Each impl is paired ## Related constructs - [`DebugError`](debug_error.md) — the same provider formatting with `Debug` instead. -- [`CanRaiseError` and `CanWrapError`](../../components/can_raise_error.md) — the components it supplies, +- [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) — the components it supplies, and the `String` forms it forwards to. - [`RaiseFrom`](raise_from.md) — the usual provider on the `String` source that finishes the raise. - [`UseDelegate`](../use_delegate.md) — dispatches `DisplayError` for the source types it should format. diff --git a/docs/reference/providers/error/index.md b/docs/reference/providers/error/index.md index 7f8a0f45..fa372935 100644 --- a/docs/reference/providers/error/index.md +++ b/docs/reference/providers/error/index.md @@ -11,7 +11,7 @@ concrete error type the context chose. ## Overview The error providers supply common error-handling strategies to any **context**, the type a capability -runs against. [`CanRaiseError` and `CanWrapError`](../../components/can_raise_error.md) define *what* a +runs against. [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) define *what* a context can do with an error: turn a source error into its abstract `Self::Error`, or attach detail to one it already holds. They say nothing about *how*. These providers supply the how for the cases that need no particular error library. Each one is generic over the context, so it works with whatever error @@ -65,7 +65,7 @@ still defined with [`#[derive_delegate]`](../../attributes/derive_delegate.md), ## Related constructs -- [`CanRaiseError` and `CanWrapError`](../../components/can_raise_error.md) — the components these +- [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) — the components these implement, through the `ErrorRaiser` and `ErrorWrapper` provider traits. - [`HasErrorType`](../../components/has_error_type.md) — names the abstract `Self::Error` every provider here produces. diff --git a/docs/reference/providers/handler/compose_handlers.md b/docs/reference/providers/handler/compose_handlers.md index 162e6028..7ce5313b 100644 --- a/docs/reference/providers/handler/compose_handlers.md +++ b/docs/reference/providers/handler/compose_handlers.md @@ -98,7 +98,7 @@ type; the async variants `.await` each step. - [`PipeHandlers`](pipe_handlers.md) — generalizes this to a list, folding to nested `ComposeHandlers`. - [`ReturnInput`](return_input.md) — the identity that composes with any handler without changing it. -- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family it +- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family it implements. - [`PipeMonadic`](../monad/pipe_monadic.md) — composition that short-circuits through a monad. diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md index c3a571b3..04263402 100644 --- a/docs/reference/providers/handler/index.md +++ b/docs/reference/providers/handler/index.md @@ -12,8 +12,8 @@ through a pipeline, returning the input unchanged, and lifting one handler shape The handler combinators exist because the handler family is not one trait but several related ones, and code is rarely written against all of them at once. A provider author writes a plain synchronous -[`Computer`](../../components/computer.md), a fallible [`TryComputer`](../../components/try_computer.md), -or an async [`Handler`](../../components/handler.md), depending on the computation. The combinators let +[`Computer`](../../components/handler/computer.md), a fallible [`TryComputer`](../../components/handler/try_computer.md), +or an async [`Handler`](../../components/handler/handler.md), depending on the computation. The combinators let those single-shape providers be wired where a different shape is expected, and let several providers be glued into a larger one, on a **context**, the type a capability runs against. Like every CGP provider, each combinator is zero-sized: its type parameters are inner providers carried in `PhantomData`. @@ -24,12 +24,12 @@ Every combinator is defined in terms of the handler component traits, so a short family shares one method signature: a context reference, a `PhantomData` tag selecting the operation, and an input, producing an associated `Output`. The members differ on two axes. -- [`Computer`](../../components/computer.md) is synchronous and infallible. -- [`TryComputer`](../../components/try_computer.md) is synchronous and fallible, and requires the context +- [`Computer`](../../components/handler/computer.md) is synchronous and infallible. +- [`TryComputer`](../../components/handler/try_computer.md) is synchronous and fallible, and requires the context to have an error type. - `AsyncComputer` is asynchronous and infallible. -- [`Handler`](../../components/handler.md) is asynchronous and fallible, the most general member. -- [`Producer`](../../components/producer.md) takes no input. +- [`Handler`](../../components/handler/handler.md) is asynchronous and fallible, the most general member. +- [`Producer`](../../components/handler/producer.md) takes no input. Each of the first four has a `…Ref` companion whose method takes the input by reference. The promotion combinators trade on the natural orderings among these: a `Computer` is also a valid `TryComputer` and a @@ -70,8 +70,8 @@ wire automatically: ## Related constructs -- [`Computer`](../../components/computer.md), [`TryComputer`](../../components/try_computer.md), - [`Handler`](../../components/handler.md), [`Producer`](../../components/producer.md) — the components +- [`Computer`](../../components/handler/computer.md), [`TryComputer`](../../components/handler/try_computer.md), + [`Handler`](../../components/handler/handler.md), [`Producer`](../../components/handler/producer.md) — the components these providers implement. - [`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md) — generate a single-trait provider and wire the rest of the family through the promotion bundles. diff --git a/docs/reference/providers/handler/pipe_handlers.md b/docs/reference/providers/handler/pipe_handlers.md index d2c9c274..562ca662 100644 --- a/docs/reference/providers/handler/pipe_handlers.md +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -113,7 +113,7 @@ shape the wiring asks for. - [`ReturnInput`](return_input.md) — the identity stage, the neutral element of the fold. - [`Product!`](../../macros/product.md) — the type-level list of stages. - [`PipeMonadic`](../monad/pipe_monadic.md) — the monadic pipeline that adds short-circuiting. -- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family a +- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family a pipeline implements. The ideas behind it: diff --git a/docs/reference/providers/handler/promote.md b/docs/reference/providers/handler/promote.md index b57c4875..62dbb9a0 100644 --- a/docs/reference/providers/handler/promote.md +++ b/docs/reference/providers/handler/promote.md @@ -78,8 +78,8 @@ result, without changing what the inner provider computes. automatically. - [`#[cgp_computer]`](../../macros/cgp_computer.md), [`#[cgp_producer]`](../../macros/cgp_producer.md) — generate providers that the bundles promote. -- [`Producer`](../../components/producer.md), [`Computer`](../../components/computer.md), - [`Handler`](../../components/handler.md) — the family members it lifts between. +- [`Producer`](../../components/handler/producer.md), [`Computer`](../../components/handler/computer.md), + [`Handler`](../../components/handler/handler.md) — the family members it lifts between. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_async.md b/docs/reference/providers/handler/promote_async.md index bf4b5f83..e69e6b5d 100644 --- a/docs/reference/providers/handler/promote_async.md +++ b/docs/reference/providers/handler/promote_async.md @@ -67,8 +67,8 @@ pub struct PromoteAsync(pub PhantomData); single-step lifts. - [`PromoteComputer`](promote_computer.md) and the other bundles — wire `PromoteAsync` into the family automatically. -- [`Computer`](../../components/computer.md), [`TryComputer`](../../components/try_computer.md), - [`Handler`](../../components/handler.md) — the family members it lifts between. +- [`Computer`](../../components/handler/computer.md), [`TryComputer`](../../components/handler/try_computer.md), + [`Handler`](../../components/handler/handler.md) — the family members it lifts between. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md index 24894d90..72196605 100644 --- a/docs/reference/providers/handler/promote_async_computer.md +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -58,7 +58,7 @@ awaited value in `Ok`, and routes `AsyncComputerRefComponent` and `HandlerRefCom - [`PromoteComputer`](promote_computer.md) — the synchronous-base counterpart. - [`PromoteHandler`](promote_handler.md) — defers its async-ref components here. - [`Promote`](promote.md), [`PromoteRef`](promote_ref.md) — the lifts this table wires. -- [`Handler`](../../components/handler.md), [`Computer`](../../components/computer.md) — the family it +- [`Handler`](../../components/handler/handler.md), [`Computer`](../../components/handler/computer.md) — the family it fills in. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md index 83bc99b6..deeb0e67 100644 --- a/docs/reference/providers/handler/promote_computer.md +++ b/docs/reference/providers/handler/promote_computer.md @@ -89,7 +89,7 @@ The base `ComputerComponent` is the inner provider itself; the table fills in th bundles for the other base traits. - [`Promote`](promote.md), [`PromoteAsync`](promote_async.md), [`PromoteRef`](promote_ref.md) — the single-step lifts this table wires. -- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family it +- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family it fills in. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_handler.md b/docs/reference/providers/handler/promote_handler.md index 3c76a991..50476983 100644 --- a/docs/reference/providers/handler/promote_handler.md +++ b/docs/reference/providers/handler/promote_handler.md @@ -20,7 +20,7 @@ family explicitly. This page explains what that wiring emits. ## Overview `PromoteHandler` starts from the most general base, a provider that implements -[`Handler`](../../components/handler.md), and fills in the rest of the family on a **context**, the +[`Handler`](../../components/handler/handler.md), and fills in the rest of the family on a **context**, the type a capability runs against. Like every CGP provider, it carries no runtime value. ## Usage @@ -57,7 +57,7 @@ handler as an async computer returning an explicit `Result`, and defers the asyn - [`TryPromote`](try_promote.md) — the lift it routes the handler slot through. - [`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), [`PromoteProducer`](promote_producer.md) — the bundles for the other base traits. -- [`Handler`](../../components/handler.md) — the base and the most general family member. +- [`Handler`](../../components/handler/handler.md) — the base and the most general family member. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_producer.md b/docs/reference/providers/handler/promote_producer.md index f5a57304..edf6a247 100644 --- a/docs/reference/providers/handler/promote_producer.md +++ b/docs/reference/providers/handler/promote_producer.md @@ -20,7 +20,7 @@ family explicitly. This page explains what that wiring emits. ## Overview -`PromoteProducer` starts from a [`Producer`](../../components/producer.md), a provider that +`PromoteProducer` starts from a [`Producer`](../../components/handler/producer.md), a provider that takes no input, and fills in every input-taking member of the handler family on a **context**, the type a capability runs against. The single produced value flows out of every handler shape regardless of the input, which the promotion discards. Like every CGP provider, it carries no runtime value. @@ -62,7 +62,7 @@ computer's input and calls the producer, and defers every remaining component to `PromoteProducer`. - [`Promote`](promote.md) — the lift that discards a computer's input and calls the producer. - [`PromoteComputer`](promote_computer.md) — the bundle this defers to. -- [`Producer`](../../components/producer.md), [`Computer`](../../components/computer.md) — the base and +- [`Producer`](../../components/handler/producer.md), [`Computer`](../../components/handler/computer.md) — the base and the family it fills in. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_ref.md b/docs/reference/providers/handler/promote_ref.md index 090de23c..db5811b2 100644 --- a/docs/reference/providers/handler/promote_ref.md +++ b/docs/reference/providers/handler/promote_ref.md @@ -72,7 +72,7 @@ written to take `&T` can then serve a slot that hands it a smart pointer to `T`, other single-step lifts, along the fallibility and asynchrony axes rather than the borrow axis. - [`PromoteComputer`](promote_computer.md) and the other bundles — wire `PromoteRef` into every `…Ref` slot automatically. -- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family +- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family members and their by-reference companions it bridges. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md index 96f168a3..e501a7a5 100644 --- a/docs/reference/providers/handler/promote_try_computer.md +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -59,7 +59,7 @@ computer form. - [`TryPromote`](try_promote.md) — the lift it routes the fallible slot through. - [`PromoteProducer`](promote_producer.md), [`PromoteAsyncComputer`](promote_async_computer.md), [`PromoteHandler`](promote_handler.md) — the bundles for the other base traits. -- [`TryComputer`](../../components/try_computer.md), [`Handler`](../../components/handler.md) — the +- [`TryComputer`](../../components/handler/try_computer.md), [`Handler`](../../components/handler/handler.md) — the family it fills in. The ideas behind it: diff --git a/docs/reference/providers/handler/return_input.md b/docs/reference/providers/handler/return_input.md index ee3656f0..9b0428d6 100644 --- a/docs/reference/providers/handler/return_input.md +++ b/docs/reference/providers/handler/return_input.md @@ -74,9 +74,9 @@ require the context to have an error type. - [`ComposeHandlers`](compose_handlers.md), [`PipeHandlers`](pipe_handlers.md) — the composition combinators `ReturnInput` is the neutral element of. -- [`Producer`](../../components/producer.md) — for a stage that computes a value rather than echoing +- [`Producer`](../../components/handler/producer.md) — for a stage that computes a value rather than echoing the input. -- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family it +- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family it implements. The ideas behind it: diff --git a/docs/reference/providers/handler/try_promote.md b/docs/reference/providers/handler/try_promote.md index 4be03dea..b927eae3 100644 --- a/docs/reference/providers/handler/try_promote.md +++ b/docs/reference/providers/handler/try_promote.md @@ -72,7 +72,7 @@ The analogous pair lifts between `Handler` (from an `AsyncComputer` returning a - [`PromoteTryComputer`](promote_try_computer.md) — the bundle that wires `TryPromote`. - [`PipeMonadic`](../monad/pipe_monadic.md) — uses `TryPromote` to demote fallible handlers when composing a fallible monadic pipeline. -- [`TryComputer`](../../components/try_computer.md), [`Handler`](../../components/handler.md) — the +- [`TryComputer`](../../components/handler/try_computer.md), [`Handler`](../../components/handler/handler.md) — the fallible family members it bridges. The ideas behind it: diff --git a/docs/reference/providers/monad/index.md b/docs/reference/providers/monad/index.md index d9dab3cb..25a6c20a 100644 --- a/docs/reference/providers/monad/index.md +++ b/docs/reference/providers/monad/index.md @@ -11,7 +11,7 @@ appropriate branch. ## Overview The monad providers build [monadic handler composition](/docs/concepts/monadic-handlers) on top of the -[`Computer`](../../components/computer.md) family. They let a sequence of handlers whose outputs carry a +[`Computer`](../../components/handler/computer.md) family. They let a sequence of handlers whose outputs carry a "continue" case and a "stop" case be chained without pattern-matching each step by hand: the monad decides which case threads forward and which short-circuits. A built pipeline is itself a provider for `Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires into a **context**, the type a diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index d758f444..02ba238a 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -99,7 +99,7 @@ structure. handlers. - [`MonadicBind`](../../traits/monadic_bind.md), [`MonadicTrans`](../../traits/monadic_trans.md) — the traits it bounds on while folding. -- [`Computer`](../../components/computer.md), [`Handler`](../../components/handler.md) — the family a +- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family a pipeline implements. The ideas behind it: diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/contains_value.md index 5089e219..44871227 100644 --- a/docs/reference/traits/contains_value.md +++ b/docs/reference/traits/contains_value.md @@ -95,7 +95,7 @@ of this. ## Under the hood The [`BindOk` and `BindErr`](../providers/monad/index.md) providers use `ContainsValue` in their -[`Computer`](../components/computer.md) and `AsyncComputer` impls. Running one bind step means: take the +[`Computer`](../components/handler/computer.md) and `AsyncComputer` impls. Running one bind step means: take the step's output, ask the monad what value sits beneath its wrapper, and hand that to the continuation. This trait is the second half of that sentence. @@ -130,8 +130,8 @@ the first step rather than at the definition. the pipeline rather than run a step. - [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers; what you actually wire. -- [`Computer`](../components/computer.md) — the component family the bind providers implement. -- [`TryComputer`](../components/try_computer.md) and [`Handler`](../components/handler.md) — the fallible +- [`Computer`](../components/handler/computer.md) — the component family the bind providers implement. +- [`TryComputer`](../components/handler/try_computer.md) and [`Handler`](../components/handler/handler.md) — the fallible members a single step usually is. The ideas behind it: diff --git a/docs/reference/traits/has_extractor_mut.md b/docs/reference/traits/has_extractor_mut.md index f1911225..56351543 100644 --- a/docs/reference/traits/has_extractor_mut.md +++ b/docs/reference/traits/has_extractor_mut.md @@ -81,7 +81,7 @@ The payload arrives as `&mut Circle`, so the write lands in the original value. - **A `match` on `&mut`** when the enum is concrete. `if let Shape::Circle(c) = &mut shape` does this in a line, and the family is for code that cannot name the enum. - **Consider returning a new value instead.** Much CGP code threads state through handler outputs rather - than mutating in place, which composes better with the [handler family](../components/handler.md). + than mutating in place, which composes better with the [handler family](../components/handler/handler.md). ## Under the hood diff --git a/docs/reference/traits/has_field_mut.md b/docs/reference/traits/has_field_mut.md index ce231965..bfc09278 100644 --- a/docs/reference/traits/has_field_mut.md +++ b/docs/reference/traits/has_field_mut.md @@ -102,7 +102,7 @@ shared reference satisfies [`HasField`](./has_field.md) and not this. bounded — the provider-side mirror of this trait. - **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable and threads state through handler outputs instead, which composes better with the - [handler family](../components/handler.md). + [handler family](../components/handler/handler.md). ## Under the hood diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/lift_value.md index eba6f0d6..ddc90470 100644 --- a/docs/reference/traits/lift_value.md +++ b/docs/reference/traits/lift_value.md @@ -95,7 +95,7 @@ chain steps without a branch and involve none of this. ## Under the hood The [`BindOk` and `BindErr`](../providers/monad/index.md) providers use `LiftValue` in their -[`Computer`](../components/computer.md) and `AsyncComputer` impls, as the closing half of a step whose +[`Computer`](../components/handler/computer.md) and `AsyncComputer` impls, as the closing half of a step whose opening half is [`ContainsValue`](./contains_value.md). The step unwraps the incoming output, decides whether to short-circuit, and then lifts: @@ -136,7 +136,7 @@ forwarded; the associated type is the step's own. They coincide for some monads the pipeline rather than run a step. - [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers; what you actually wire. -- [`Computer`](../components/computer.md) — the component family the bind providers implement. +- [`Computer`](../components/handler/computer.md) — the component family the bind providers implement. - [Handler combinators](../providers/handler/index.md) — composition without a short-circuit branch. diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monadic_bind.md index 20d6a496..e076e2c1 100644 --- a/docs/reference/traits/monadic_bind.md +++ b/docs/reference/traits/monadic_bind.md @@ -116,7 +116,7 @@ list-folding half of the four traits, while [`ContainsValue`](./contains_value.m [`LiftValue`](./lift_value.md) are the step-running half. The whole fold happens during trait resolution. A monadic pipeline is not a runtime structure, and the -provider it resolves to implements the [`Computer`](../components/computer.md) family like any other +provider it resolves to implements the [`Computer`](../components/handler/computer.md) family like any other handler. ## Common Mistakes @@ -145,7 +145,7 @@ missing trait rather than the gap. markers; what you actually wire. - [Handler combinators](../providers/handler/index.md) — composition without a short-circuit branch. -- [`Computer`](../components/computer.md) — the component family a monadic pipeline implements. +- [`Computer`](../components/handler/computer.md) — the component family a monadic pipeline implements. - [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. The ideas behind it: diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monadic_trans.md index 00eac5b9..d839c47f 100644 --- a/docs/reference/traits/monadic_trans.md +++ b/docs/reference/traits/monadic_trans.md @@ -134,7 +134,7 @@ bound rather than saying the marker is not stackable. step, where these two build the pipeline. - [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers, including the transformer forms. -- [`Computer`](../components/computer.md) — the component family a monadic pipeline implements. +- [`Computer`](../components/handler/computer.md) — the component family a monadic pipeline implements. - [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. The ideas behind it: diff --git a/example-code/README.md b/example-code/README.md index fdb11570..d597816b 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -19,7 +19,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — sixteen files under `src/concepts/`, one per page that shows code | -| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, the `traits/` pages that show checkable code, and most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`); the section is being filled in lazily | +| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), and all of `components/` (each component page that shows code, including the `handler/` subsection); `types/` is the remaining gap, and the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `src/cargo_cgp/` | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/src/reference/components/can_raise_error.rs b/example-code/src/reference/components/can_raise_error.rs new file mode 100644 index 00000000..5e7b6024 --- /dev/null +++ b/example-code/src/reference/components/can_raise_error.rs @@ -0,0 +1,29 @@ +//! Code from `docs/reference/components/can_raise_error.md` — `CanRaiseError`. +//! +//! Pins the `LoadOrFail` provider from the page's Examples, which raises a `String` into the context's +//! abstract error through `#[uses(CanRaiseError)]`. The provider is generic over its context, +//! so it compiles on its own; the `CanRaiseError` dependency is discharged wherever a concrete +//! context wires `LoadOrFail`. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self, path: &str) -> Result; + } + + #[cgp_impl(new LoadOrFail)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + return Err(Self::raise_error("empty path".to_owned())); + } + Ok(format!("contents of {path}")) + } + } +} diff --git a/example-code/src/reference/components/can_wrap_error.rs b/example-code/src/reference/components/can_wrap_error.rs new file mode 100644 index 00000000..e8d0ea33 --- /dev/null +++ b/example-code/src/reference/components/can_wrap_error.rs @@ -0,0 +1,31 @@ +//! Code from `docs/reference/components/can_wrap_error.md` — `CanWrapError`. +//! +//! Pins the `LoadOrFail` provider from the page's Examples, which raises a `String` into the context's +//! abstract error and then wraps a further message onto it, declaring both dependencies through +//! `#[uses]`. The provider is generic over its context, so it compiles on its own; the +//! `CanRaiseError` and `CanWrapError` dependencies are discharged wherever a concrete +//! context wires `LoadOrFail`. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self, path: &str) -> Result; + } + + #[cgp_impl(new LoadOrFail)] + #[uses(CanRaiseError, CanWrapError)] + #[use_type(HasErrorType.Error)] + impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + let err = Self::raise_error("empty path".to_owned()); + return Err(Self::wrap_error(err, format!("while loading {path}"))); + } + Ok(format!("contents of {path}")) + } + } +} diff --git a/example-code/src/reference/components/handler/async_computer.rs b/example-code/src/reference/components/handler/async_computer.rs new file mode 100644 index 00000000..d5b925d5 --- /dev/null +++ b/example-code/src/reference/components/handler/async_computer.rs @@ -0,0 +1,18 @@ +//! Code from `docs/reference/components/handler/async_computer.md` — `AsyncComputer`. +//! +//! Pins the generic consumer from the page's Examples, which awaits an async computation wired on its +//! context. It is generic over the context, so it compiles on its own. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::CanComputeAsync; + + pub async fn run(context: &Context, input: u64) -> Context::Output + where + Context: CanComputeAsync, + { + context.compute_async(PhantomData::, input).await + } +} diff --git a/example-code/src/reference/components/handler/async_computer_ref.rs b/example-code/src/reference/components/handler/async_computer_ref.rs new file mode 100644 index 00000000..a679c2a3 --- /dev/null +++ b/example-code/src/reference/components/handler/async_computer_ref.rs @@ -0,0 +1,18 @@ +//! Code from `docs/reference/components/handler/async_computer_ref.md` — `AsyncComputerRef`. +//! +//! Pins the generic consumer from the page's Examples, which awaits an infallible computation over a +//! borrowed input. It is generic over the context, so it compiles on its own. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::CanComputeAsyncRef; + + pub async fn scan(context: &Context, input: &String) -> Context::Output + where + Context: CanComputeAsyncRef, + { + context.compute_async_ref(PhantomData::, input).await + } +} diff --git a/example-code/src/reference/components/handler/computer.rs b/example-code/src/reference/components/handler/computer.rs new file mode 100644 index 00000000..83642dff --- /dev/null +++ b/example-code/src/reference/components/handler/computer.rs @@ -0,0 +1,47 @@ +//! Code from `docs/reference/components/handler/computer.md` — `Computer`. +//! +//! Pins the `Double` provider from the page's Examples, wired onto a context and invoked through +//! `CanCompute`. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + #[derive(HasField)] + pub struct App; + + delegate_components! { + App { + ComputerComponent: Double, + } + } + + mod check_app { + use super::*; + + check_components! { + App { + ComputerComponent: ((), u64), + } + } + } + + #[test] + fn app_doubles_its_input() { + use cgp::extra::handler::CanCompute; + + assert_eq!(App.compute(PhantomData::<()>, 21u64), 42); + } +} diff --git a/example-code/src/reference/components/handler/computer_ref.rs b/example-code/src/reference/components/handler/computer_ref.rs new file mode 100644 index 00000000..5250208a --- /dev/null +++ b/example-code/src/reference/components/handler/computer_ref.rs @@ -0,0 +1,18 @@ +//! Code from `docs/reference/components/handler/computer_ref.md` — `ComputerRef`. +//! +//! Pins the generic consumer from the page's Examples, which computes from a borrowed input. It is +//! generic over the context, so it compiles on its own. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::CanComputeRef; + + pub fn measure(context: &Context, input: &String) -> Context::Output + where + Context: CanComputeRef, + { + context.compute_ref(PhantomData::, input) + } +} diff --git a/example-code/src/reference/components/handler/handler.rs b/example-code/src/reference/components/handler/handler.rs new file mode 100644 index 00000000..58d4f93a --- /dev/null +++ b/example-code/src/reference/components/handler/handler.rs @@ -0,0 +1,21 @@ +//! Code from `docs/reference/components/handler/handler.md` — `Handler`. +//! +//! Pins the generic consumer from the page's Examples, which bounds its context by `CanHandle` and so +//! accepts any wired computation. It is generic over the context, so it compiles on its own. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::CanHandle; + + pub async fn run_with( + context: &Context, + input: String, + ) -> Result + where + Context: CanHandle, + { + context.handle(PhantomData::, input).await + } +} diff --git a/example-code/src/reference/components/handler/handler_ref.rs b/example-code/src/reference/components/handler/handler_ref.rs new file mode 100644 index 00000000..e5c2ecb7 --- /dev/null +++ b/example-code/src/reference/components/handler/handler_ref.rs @@ -0,0 +1,21 @@ +//! Code from `docs/reference/components/handler/handler_ref.md` — `HandlerRef`. +//! +//! Pins the generic consumer from the page's Examples, which awaits a fallible computation over a +//! borrowed input. It is generic over the context, so it compiles on its own. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::CanHandleRef; + + pub async fn serve( + context: &Context, + request: &String, + ) -> Result + where + Context: CanHandleRef, + { + context.handle_ref(PhantomData::, request).await + } +} diff --git a/example-code/src/reference/components/handler/mod.rs b/example-code/src/reference/components/handler/mod.rs new file mode 100644 index 00000000..6dc3c2ea --- /dev/null +++ b/example-code/src/reference/components/handler/mod.rs @@ -0,0 +1,11 @@ +//! Code from the pages under `docs/reference/components/handler/`, one module per page. + +pub mod async_computer; +pub mod async_computer_ref; +pub mod computer; +pub mod computer_ref; +pub mod handler; +pub mod handler_ref; +pub mod producer; +pub mod try_computer; +pub mod try_computer_ref; diff --git a/example-code/src/reference/components/handler/producer.rs b/example-code/src/reference/components/handler/producer.rs new file mode 100644 index 00000000..c3037ef9 --- /dev/null +++ b/example-code/src/reference/components/handler/producer.rs @@ -0,0 +1,46 @@ +//! Code from `docs/reference/components/handler/producer.md` — `Producer`. +//! +//! Pins the `MagicNumber` provider from the page's Examples, wired onto a context and invoked through +//! `CanProduce`. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::{Producer, ProducerComponent}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Producer for MagicNumber { + type Output = u64; + + fn produce(_context: &Context, _code: PhantomData) -> u64 { + 42 + } + } + + pub struct App; + + delegate_components! { + App { + ProducerComponent: MagicNumber, + } + } + + mod check_app { + use super::*; + + check_components! { + App { + ProducerComponent: (), + } + } + } + + #[test] + fn app_produces_the_magic_number() { + use cgp::extra::handler::CanProduce; + + assert_eq!(App.produce(PhantomData::<()>), 42); + } +} diff --git a/example-code/src/reference/components/handler/try_computer.rs b/example-code/src/reference/components/handler/try_computer.rs new file mode 100644 index 00000000..fad71e9e --- /dev/null +++ b/example-code/src/reference/components/handler/try_computer.rs @@ -0,0 +1,66 @@ +//! Code from `docs/reference/components/handler/try_computer.md` — `TryComputer`. +//! +//! Pins the `ParseU64` provider from the page's Examples, wired onto a context that also supplies an +//! error type and an error raiser for `ParseIntError`, and invoked through `CanTryCompute`. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::extra::handler::{TryComputer, TryComputerComponent}; + use cgp::prelude::*; + + #[cgp_impl(new ParseU64)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl TryComputer { + type Output = u64; + + fn try_compute( + &self, + _code: PhantomData, + input: String, + ) -> Result { + input.parse().map_err(|e| Self::raise_error(e)) + } + } + + pub struct App; + + // The page shows only `TryComputerComponent: ParseU64` and says the context also wires an error + // type and an error raiser. That backend is filled in here so the wiring resolves: `DebugError` + // formats the `ParseIntError` into a `String`, which `RaiseFrom` then raises into the `String` + // error type. + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + TryComputerComponent: ParseU64, + @ErrorRaiserComponent.core::num::ParseIntError: DebugError, + @ErrorRaiserComponent.String: RaiseFrom, + } + } + + mod check_app { + use super::*; + + check_components! { + App { + TryComputerComponent: ((), String), + } + } + } + + #[test] + fn app_parses_a_number() { + use cgp::extra::handler::CanTryCompute; + + assert_eq!( + App.try_compute(PhantomData::<()>, "42".to_owned()).unwrap(), + 42, + ); + } +} diff --git a/example-code/src/reference/components/handler/try_computer_ref.rs b/example-code/src/reference/components/handler/try_computer_ref.rs new file mode 100644 index 00000000..704a887a --- /dev/null +++ b/example-code/src/reference/components/handler/try_computer_ref.rs @@ -0,0 +1,21 @@ +//! Code from `docs/reference/components/handler/try_computer_ref.md` — `TryComputerRef`. +//! +//! Pins the generic consumer from the page's Examples, which runs a fallible computation over a +//! borrowed input. It is generic over the context, so it compiles on its own. + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::extra::handler::CanTryComputeRef; + + pub fn check( + context: &Context, + input: &String, + ) -> Result + where + Context: CanTryComputeRef, + { + context.try_compute_ref(PhantomData::, input) + } +} diff --git a/example-code/src/reference/components/has_error_type.rs b/example-code/src/reference/components/has_error_type.rs new file mode 100644 index 00000000..d35eab5a --- /dev/null +++ b/example-code/src/reference/components/has_error_type.rs @@ -0,0 +1,36 @@ +//! Code from `docs/reference/components/has_error_type.md` — `HasErrorType`. +//! +//! Pins that a context wires its abstract error to a concrete type through `UseType`, and that an +//! error-aware component names the error as the bare `Error` via `#[use_type]`. The page's direct-impl +//! form uses `anyhow::Error`, which this crate does not depend on, so the wired `String` form stands +//! in for it. + +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + #[cgp_component(Validator)] + #[use_type(HasErrorType.Error)] + pub trait CanValidate { + fn validate(&self) -> Result<(), Error>; + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } + } + + mod check_app { + use super::*; + + check_components! { + App { + ErrorTypeProviderComponent, + } + } + } +} diff --git a/example-code/src/reference/components/has_runtime.rs b/example-code/src/reference/components/has_runtime.rs new file mode 100644 index 00000000..bc3ca067 --- /dev/null +++ b/example-code/src/reference/components/has_runtime.rs @@ -0,0 +1,44 @@ +//! Code from `docs/reference/components/has_runtime.md` — `HasRuntime`. +//! +//! Pins a context that declares its runtime type with `UseType` and its runtime field with `UseField`, +//! and the generic accessor that reaches the runtime through `HasRuntime`. + +/// ## Examples +pub mod examples { + use cgp::extra::runtime::{ + HasRuntime, RuntimeGetterComponent, RuntimeOf, RuntimeTypeProviderComponent, + }; + use cgp::prelude::*; + + pub struct TokioRuntime; + + #[derive(HasField)] + pub struct App { + pub runtime: TokioRuntime, + } + + delegate_components! { + App { + RuntimeTypeProviderComponent: UseType, + RuntimeGetterComponent: UseField, + } + } + + mod check_app { + use super::*; + + check_components! { + App { + RuntimeTypeProviderComponent, + RuntimeGetterComponent, + } + } + } + + pub fn runtime_of(context: &Context) -> &RuntimeOf + where + Context: HasRuntime, + { + context.runtime() + } +} diff --git a/example-code/src/reference/components/has_runtime_type.rs b/example-code/src/reference/components/has_runtime_type.rs new file mode 100644 index 00000000..0f828d93 --- /dev/null +++ b/example-code/src/reference/components/has_runtime_type.rs @@ -0,0 +1,38 @@ +//! Code from `docs/reference/components/has_runtime_type.md` — `HasRuntimeType`. +//! +//! Pins a context that fixes its runtime type with `UseType`, and the generic function that names the +//! runtime type without touching a runtime value. + +/// ## Examples +pub mod examples { + use cgp::extra::runtime::{HasRuntimeType, RuntimeOf, RuntimeTypeProviderComponent}; + use cgp::prelude::*; + + pub struct TokioRuntime; + + pub struct App; + + delegate_components! { + App { + RuntimeTypeProviderComponent: UseType, + } + } + + mod check_app { + use super::*; + + check_components! { + App { + RuntimeTypeProviderComponent, + } + } + } + + pub fn describe() -> &'static str + where + Context: HasRuntimeType, + RuntimeOf: Default, + { + "the context has a default-constructible runtime type" + } +} diff --git a/example-code/src/reference/components/has_type.rs b/example-code/src/reference/components/has_type.rs new file mode 100644 index 00000000..4b25f6cb --- /dev/null +++ b/example-code/src/reference/components/has_type.rs @@ -0,0 +1,45 @@ +//! Code from `docs/reference/components/has_type.md` — `HasType`. +//! +//! Pins that wiring the built-in `TypeProviderComponent` to `UseType` makes a context implement +//! `HasType` with `Type = f64` for any tag, and that generic code reads it back through `TypeOf`. + +/// ## Examples +pub mod examples { + use cgp::core::types::{TypeOf, TypeProviderComponent}; + use cgp::prelude::*; + + pub struct ScalarTag; + + pub struct App; + + delegate_components! { + App { + TypeProviderComponent: UseType, + } + } + + mod check_app { + use super::*; + + check_components! { + App { + TypeProviderComponent: ScalarTag, + } + } + } + + pub fn zero() -> TypeOf + where + Context: HasType, + TypeOf: Default, + { + Default::default() + } + + #[test] + fn app_resolves_any_tag_to_f64() { + // `App` wires `TypeProviderComponent` to `UseType`, so `HasType` resolves to + // `f64` for every tag, `ScalarTag` included. + assert_eq!(zero::(), 0.0); + } +} diff --git a/example-code/src/reference/components/mod.rs b/example-code/src/reference/components/mod.rs new file mode 100644 index 00000000..e2cca1cf --- /dev/null +++ b/example-code/src/reference/components/mod.rs @@ -0,0 +1,14 @@ +//! Code from the pages under `docs/reference/components/`, one module per page. +//! +//! The section is filled in lazily, so the modules here are the pages someone has written, revised, +//! or reviewed rather than the section's full inventory. + +pub mod can_raise_error; +pub mod can_wrap_error; +pub mod handler; +pub mod has_error_type; +pub mod has_runtime; +pub mod has_runtime_type; +pub mod has_type; +pub mod runner; +pub mod send_runner; diff --git a/example-code/src/reference/components/runner.rs b/example-code/src/reference/components/runner.rs new file mode 100644 index 00000000..b0da2504 --- /dev/null +++ b/example-code/src/reference/components/runner.rs @@ -0,0 +1,86 @@ +//! Code from `docs/reference/components/runner.md` — `CanRun`. +//! +//! Pins the `SpawnAndRun` provider from the page's Examples, together with the cast the page names but +//! does not show in full: a base `RunWithFooBar` runner, a `UseDelegate` table routing two tasks, a +//! `SendRunner` proxy on the concrete context, and a `dummy_spawn` standing in for `tokio::spawn`. It +//! follows the library's own async-and-send spawn test. The elided `RunWithFooBar` body is a trivial +//! success here. + +/// ## Examples +pub mod examples { + use core::convert::Infallible; + use core::future::Future; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::run::{ + CanRun, CanSendRun, Runner, RunnerComponent, SendRunner, SendRunnerComponent, + }; + use cgp::prelude::*; + + // Stands in for `tokio::spawn`: it demands the future be `Send + 'static`. + fn dummy_spawn(_future: F) + where + F: Future + Send + 'static, + F::Output: Send + 'static, + { + } + + #[cgp_impl(new RunWithFooBar)] + #[use_type(HasErrorType.Error)] + impl Runner { + async fn run(&self, _code: PhantomData) -> Result<(), Error> { + // The page's `RunWithFooBar` fetches and acts; its body is elided there, so a trivial + // success stands in. + Ok(()) + } + } + + #[cgp_impl(new SpawnAndRun: RunnerComponent)] + #[use_type(HasErrorType.Error)] + impl Runner + where + Self: 'static + Send + Clone + CanSendRun, + { + async fn run(&self, _code: PhantomData) -> Result<(), Error> { + let context = self.clone(); + + dummy_spawn(async move { + let _ = context.send_run(PhantomData).await; + }); + + Ok(()) + } + } + + #[derive(Clone)] + pub struct App; + + pub struct ActionA; + pub struct ActionB; + + delegate_components! { + App { + open RunnerComponent; + + ErrorTypeProviderComponent: UseType, + @RunnerComponent.ActionA: RunWithFooBar, + @RunnerComponent.ActionB: SpawnAndRun, + } + } + + // The `Send` variant is a proxy on the concrete context, forwarding to its own `run`. + #[cgp_provider] + impl SendRunner for App { + async fn send_run(context: &App, code: PhantomData) -> Result<(), Infallible> { + context.run(code).await + } + } + + #[test] + fn spawns_and_runs_a_task() { + use futures::executor::block_on; + + let app = App; + block_on(app.run(PhantomData::)).unwrap(); + } +} diff --git a/example-code/src/reference/components/send_runner.rs b/example-code/src/reference/components/send_runner.rs new file mode 100644 index 00000000..0eea6e87 --- /dev/null +++ b/example-code/src/reference/components/send_runner.rs @@ -0,0 +1,85 @@ +//! Code from `docs/reference/components/send_runner.md` — `CanSendRun`. +//! +//! Pins the concrete `SendRunner` proxy from the page's Examples, together with the `SpawnAndRun` +//! spawner that consumes it and the cast needed to compile and run them: a base `RunWithFooBar` +//! runner, a `UseDelegate` table, and a `dummy_spawn` standing in for `tokio::spawn`. It follows the +//! library's own async-and-send spawn test. The proxy is what discharges the `Send` bound at the +//! concrete context. + +/// ## Examples +pub mod examples { + use core::convert::Infallible; + use core::future::Future; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::run::{ + CanRun, CanSendRun, Runner, RunnerComponent, SendRunner, SendRunnerComponent, + }; + use cgp::prelude::*; + + // Stands in for `tokio::spawn`: it demands the future be `Send + 'static`. + fn dummy_spawn(_future: F) + where + F: Future + Send + 'static, + F::Output: Send + 'static, + { + } + + #[cgp_impl(new RunWithFooBar)] + #[use_type(HasErrorType.Error)] + impl Runner { + async fn run(&self, _code: PhantomData) -> Result<(), Error> { + Ok(()) + } + } + + #[cgp_impl(new SpawnAndRun: RunnerComponent)] + #[use_type(HasErrorType.Error)] + impl Runner + where + Self: 'static + Send + Clone + CanSendRun, + { + async fn run(&self, _code: PhantomData) -> Result<(), Error> { + let context = self.clone(); + + dummy_spawn(async move { + let _ = context.send_run(PhantomData).await; + }); + + Ok(()) + } + } + + #[derive(Clone)] + pub struct App; + + pub struct ActionA; + pub struct ActionB; + + delegate_components! { + App { + open RunnerComponent; + + ErrorTypeProviderComponent: UseType, + @RunnerComponent.ActionA: RunWithFooBar, + @RunnerComponent.ActionB: SpawnAndRun, + } + } + + // Because this impl names the concrete `App` and `ActionA`, the future `context.run(code)` produces + // has a fully known type, so the compiler can prove it is `Send` and satisfy the `+ Send` bound. + #[cgp_provider] + impl SendRunner for App { + async fn send_run(context: &App, code: PhantomData) -> Result<(), Infallible> { + context.run(code).await + } + } + + #[test] + fn the_proxy_lets_a_task_be_spawned() { + use futures::executor::block_on; + + let app = App; + block_on(app.run(PhantomData::)).unwrap(); + } +} diff --git a/example-code/src/reference/mod.rs b/example-code/src/reference/mod.rs index e9c71eda..3bc4cd23 100644 --- a/example-code/src/reference/mod.rs +++ b/example-code/src/reference/mod.rs @@ -3,6 +3,7 @@ //! The section is filled in lazily, so the modules here are the pages someone has written, revised, //! or reviewed rather than the section's full inventory. +pub mod components; pub mod derives; pub mod errors; pub mod macros; From ae708dd6ee795404358a001f9c3a480a05eb7d3a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 22:14:10 +0200 Subject: [PATCH 048/516] Rename reference section to "When to use it" Shorten the "When to reach for it, and when not" section heading to "When to use it" across every reference page and the cargo-cgp expand page, and re-point the inbound anchor links and visible labels to the new anchor. Co-Authored-By: Claude Opus 4.8 --- docs/ai/skills/SKILL.md | 1122 ++++++++++++++++- docs/ai/skills/references/abstract-types.md | 168 ++- docs/ai/skills/references/checking.md | 210 ++- docs/ai/skills/references/components.md | 258 +++- docs/ai/skills/references/error-extraction.md | 89 +- docs/ai/skills/references/error-handling.md | 139 +- docs/ai/skills/references/extensible-data.md | 164 ++- .../references/functions-and-getters.md | 315 ++++- docs/ai/skills/references/handlers.md | 267 +++- .../references/higher-order-providers.md | 162 ++- docs/ai/skills/references/macro-grammar.md | 342 ++++- docs/ai/skills/references/modern-idioms.md | 285 ++++- .../skills/references/modularity-hierarchy.md | 205 ++- docs/ai/skills/references/namespaces.md | 174 ++- .../references/type-level-primitives.md | 207 ++- docs/ai/skills/references/wiring.md | 195 ++- docs/cargo-cgp/expand.md | 2 +- docs/reference/attributes/default_impl.md | 2 +- docs/reference/attributes/derive_delegate.md | 2 +- docs/reference/attributes/extend.md | 2 +- docs/reference/attributes/extend_where.md | 2 +- docs/reference/attributes/implicit.md | 2 +- docs/reference/attributes/use_provider.md | 2 +- docs/reference/attributes/use_type.md | 2 +- docs/reference/attributes/uses.md | 2 +- docs/reference/components/can_raise_error.md | 2 +- docs/reference/components/can_wrap_error.md | 2 +- .../components/handler/async_computer.md | 2 +- .../components/handler/async_computer_ref.md | 2 +- docs/reference/components/handler/computer.md | 2 +- .../components/handler/computer_ref.md | 2 +- docs/reference/components/handler/handler.md | 2 +- .../components/handler/handler_ref.md | 2 +- docs/reference/components/handler/producer.md | 2 +- .../components/handler/try_computer.md | 2 +- .../components/handler/try_computer_ref.md | 2 +- docs/reference/components/has_error_type.md | 2 +- docs/reference/components/has_runtime.md | 2 +- docs/reference/components/has_runtime_type.md | 2 +- docs/reference/components/has_type.md | 2 +- docs/reference/components/runner.md | 2 +- docs/reference/components/send_runner.md | 2 +- docs/reference/derives/derive_build_field.md | 2 +- docs/reference/derives/derive_cgp_data.md | 2 +- docs/reference/derives/derive_cgp_record.md | 4 +- docs/reference/derives/derive_cgp_variant.md | 4 +- .../reference/derives/derive_extract_field.md | 2 +- docs/reference/derives/derive_from_variant.md | 2 +- docs/reference/derives/derive_has_field.md | 2 +- docs/reference/derives/derive_has_fields.md | 2 +- docs/reference/macros/async_trait.md | 2 +- docs/reference/macros/blanket_trait.md | 2 +- docs/reference/macros/cgp_auto_dispatch.md | 2 +- docs/reference/macros/cgp_auto_getter.md | 4 +- docs/reference/macros/cgp_component.md | 2 +- docs/reference/macros/cgp_computer.md | 2 +- docs/reference/macros/cgp_fn.md | 2 +- docs/reference/macros/cgp_getter.md | 4 +- docs/reference/macros/cgp_impl.md | 4 +- docs/reference/macros/cgp_namespace.md | 2 +- docs/reference/macros/cgp_producer.md | 2 +- docs/reference/macros/cgp_provider.md | 2 +- docs/reference/macros/cgp_type.md | 2 +- docs/reference/macros/check_components.md | 2 +- .../macros/delegate_and_check_components.md | 4 +- docs/reference/macros/delegate_components.md | 2 +- docs/reference/macros/path.md | 2 +- docs/reference/macros/product.md | 2 +- docs/reference/macros/sum.md | 2 +- docs/reference/macros/symbol.md | 2 +- docs/reference/providers/chain_getters.md | 2 +- .../providers/dispatch/build_and_merge.md | 2 +- .../dispatch/build_and_merge_outputs.md | 2 +- .../providers/dispatch/build_and_set_field.md | 2 +- .../providers/dispatch/build_with_handlers.md | 2 +- .../providers/dispatch/downcast_and_handle.md | 2 +- .../dispatch/extract_field_and_handle.md | 2 +- .../providers/dispatch/handle_field_value.md | 2 +- .../dispatch/match_first_with_handlers.md | 2 +- .../dispatch/match_with_field_handlers.md | 2 +- .../providers/dispatch/match_with_handlers.md | 2 +- .../dispatch/match_with_value_handlers.md | 2 +- docs/reference/providers/error/debug_error.md | 2 +- .../providers/error/discard_detail.md | 2 +- .../providers/error/display_error.md | 2 +- .../providers/error/panic_on_error.md | 2 +- docs/reference/providers/error/raise_from.md | 2 +- .../providers/error/raise_infallible.md | 2 +- .../reference/providers/error/return_error.md | 2 +- .../providers/handler/compose_handlers.md | 2 +- .../providers/handler/pipe_handlers.md | 2 +- docs/reference/providers/handler/promote.md | 2 +- .../providers/handler/promote_async.md | 2 +- .../handler/promote_async_computer.md | 2 +- .../providers/handler/promote_computer.md | 2 +- .../providers/handler/promote_handler.md | 2 +- .../providers/handler/promote_producer.md | 2 +- .../providers/handler/promote_ref.md | 2 +- .../providers/handler/promote_try_computer.md | 2 +- .../providers/handler/return_input.md | 2 +- .../providers/handler/try_promote.md | 2 +- .../providers/handler/use_input_delegate.md | 2 +- docs/reference/providers/monad/bind_err.md | 2 +- docs/reference/providers/monad/bind_ok.md | 2 +- .../reference/providers/monad/pipe_monadic.md | 2 +- docs/reference/providers/redirect_lookup.md | 2 +- docs/reference/providers/use_context.md | 2 +- docs/reference/providers/use_default.md | 2 +- docs/reference/providers/use_delegate.md | 2 +- .../reference/providers/use_delegated_type.md | 2 +- docs/reference/providers/use_field.md | 2 +- docs/reference/providers/use_field_ref.md | 2 +- docs/reference/providers/use_fields.md | 2 +- docs/reference/providers/use_type.md | 2 +- docs/reference/providers/with_context.md | 2 +- .../providers/with_delegated_type.md | 2 +- docs/reference/providers/with_field.md | 2 +- docs/reference/providers/with_field_ref.md | 2 +- docs/reference/providers/with_provider.md | 2 +- docs/reference/providers/with_type.md | 2 +- docs/reference/traits/append_product.md | 2 +- docs/reference/traits/build_field.md | 2 +- docs/reference/traits/can_build_from.md | 2 +- .../traits/can_build_with_default.md | 2 +- docs/reference/traits/can_downcast.md | 2 +- docs/reference/traits/can_downcast_fields.md | 2 +- .../traits/can_finalize_with_default.md | 2 +- docs/reference/traits/can_upcast.md | 2 +- docs/reference/traits/can_use_component.md | 2 +- docs/reference/traits/concat_path.md | 2 +- docs/reference/traits/concat_product.md | 2 +- docs/reference/traits/contains_value.md | 2 +- docs/reference/traits/default_impls1.md | 2 +- docs/reference/traits/default_impls2.md | 4 +- docs/reference/traits/default_namespace.md | 4 +- docs/reference/traits/delegate_component.md | 2 +- docs/reference/traits/extract_field.md | 2 +- docs/reference/traits/field_getter.md | 2 +- docs/reference/traits/field_mapper.md | 2 +- docs/reference/traits/finalize_build.md | 2 +- docs/reference/traits/finalize_extract.md | 2 +- .../traits/finalize_extract_result.md | 2 +- docs/reference/traits/finalize_optional.md | 2 +- docs/reference/traits/from_fields.md | 2 +- docs/reference/traits/from_variant.md | 2 +- docs/reference/traits/has_builder.md | 2 +- docs/reference/traits/has_extractor.md | 2 +- docs/reference/traits/has_extractor_mut.md | 2 +- docs/reference/traits/has_extractor_ref.md | 2 +- docs/reference/traits/has_field.md | 2 +- docs/reference/traits/has_field_mut.md | 2 +- docs/reference/traits/has_fields.md | 2 +- docs/reference/traits/has_fields_ref.md | 2 +- docs/reference/traits/has_optional_builder.md | 2 +- docs/reference/traits/into_builder.md | 2 +- docs/reference/traits/is_provider_for.md | 2 +- docs/reference/traits/lift_value.md | 2 +- docs/reference/traits/map_field.md | 2 +- docs/reference/traits/map_fields.md | 2 +- docs/reference/traits/map_type.md | 2 +- docs/reference/traits/map_type_ref.md | 2 +- docs/reference/traits/monadic_bind.md | 2 +- docs/reference/traits/monadic_trans.md | 2 +- docs/reference/traits/mut_field_getter.md | 2 +- docs/reference/traits/partial_data.md | 2 +- docs/reference/traits/set_optional.md | 2 +- docs/reference/traits/static_format.md | 2 +- docs/reference/traits/static_string.md | 2 +- docs/reference/traits/take_field.md | 2 +- docs/reference/traits/to_fields.md | 2 +- docs/reference/traits/to_fields_ref.md | 2 +- docs/reference/traits/to_optional.md | 2 +- docs/reference/traits/transform_map.md | 2 +- .../reference/traits/transform_map_default.md | 2 +- docs/reference/traits/transform_map_fields.md | 2 +- docs/reference/traits/transform_optional.md | 2 +- docs/reference/traits/update_field.md | 2 +- 177 files changed, 4455 insertions(+), 185 deletions(-) mode change 120000 => 100644 docs/ai/skills/SKILL.md mode change 120000 => 100644 docs/ai/skills/references/abstract-types.md mode change 120000 => 100644 docs/ai/skills/references/checking.md mode change 120000 => 100644 docs/ai/skills/references/components.md mode change 120000 => 100644 docs/ai/skills/references/error-extraction.md mode change 120000 => 100644 docs/ai/skills/references/error-handling.md mode change 120000 => 100644 docs/ai/skills/references/extensible-data.md mode change 120000 => 100644 docs/ai/skills/references/functions-and-getters.md mode change 120000 => 100644 docs/ai/skills/references/handlers.md mode change 120000 => 100644 docs/ai/skills/references/higher-order-providers.md mode change 120000 => 100644 docs/ai/skills/references/macro-grammar.md mode change 120000 => 100644 docs/ai/skills/references/modern-idioms.md mode change 120000 => 100644 docs/ai/skills/references/modularity-hierarchy.md mode change 120000 => 100644 docs/ai/skills/references/namespaces.md mode change 120000 => 100644 docs/ai/skills/references/type-level-primitives.md mode change 120000 => 100644 docs/ai/skills/references/wiring.md diff --git a/docs/ai/skills/SKILL.md b/docs/ai/skills/SKILL.md deleted file mode 120000 index a71bbb56..00000000 --- a/docs/ai/skills/SKILL.md +++ /dev/null @@ -1 +0,0 @@ -cgp-skills/cgp/SKILL.md \ No newline at end of file diff --git a/docs/ai/skills/SKILL.md b/docs/ai/skills/SKILL.md new file mode 100644 index 00000000..d4002383 --- /dev/null +++ b/docs/ai/skills/SKILL.md @@ -0,0 +1,1121 @@ +--- +name: cgp +description: >- + Read, write, debug, and explain Context-Generic Programming (CGP) code in Rust. + Use this skill whenever you encounter or are asked to work with CGP — any code that + uses `cgp::prelude::*`, the `#[cgp_component]`, `#[cgp_impl]`, `#[cgp_provider]`, + `#[cgp_fn]`, `#[cgp_type]`, `#[cgp_getter]`, `#[cgp_auto_getter]`, `#[cgp_computer]`, + `#[cgp_producer]`, or `cgp_namespace!` macros, the `delegate_components!`, + `check_components!`, or `delegate_and_check_components!` macros, the `Symbol!`, + `Product!`, `Sum!`, or `Path!` type-level macros, the `HasField`/`HasFields` traits or + their derives, providers such as `UseContext`/`UseDelegate`/`UseField`/`UseType`, the + handler family (`Computer`/`Producer`/`Handler`), or terms like consumer trait, + provider trait, provider, wiring, impl-side dependency, or context-generic. Trigger it + even when the user does not say "CGP" by name but is clearly working with these + constructs, when a Rust trait error mentions `IsProviderFor`/`DelegateComponent`, or + when someone wants modular, dependency-injected, multiple-implementation Rust traits. +--- + +# Context-Generic Programming (CGP) in Rust + +CGP is a modular programming paradigm for Rust that works around the language's coherence +restrictions, letting you write many overlapping or "orphan" trait implementations and then +choose which one applies by **wiring** them onto a concrete context type. This file is a +self-contained primer: read it top to bottom and you hold the whole mental model — every core term, +the shape of every construct, and enough of each expansion to read, write, and debug the majority of +CGP code. It is longer than a typical skill on purpose, because CGP's surface is broad and an agent +who stops here should still be competent, not lost. + +**This primer is the map, not the territory — load the sub-skill before you act on any construct it +covers.** The primer gives you the shape of each construct; the `references/` sub-skills give you the +exact grammar, the full expansion, the corner cases, and the worked examples that keep you from +writing subtly wrong code. The gap between the two is where mistakes live: the primer tells you +`#[cgp_impl]` writes a provider, but [components](references/components.md) tells you what `self` +rewrites to, [macro-grammar](references/macro-grammar.md) tells you which attribute forms parse, and +only reading them stops you from emitting an impl that fails to compile in a way the error message +will not explain. So before you write, modify, review, or debug code using a construct — even one +that looks simple — **open the sub-skill that owns it.** Each entry in [the sub-skill +index](#sub-skills-load-the-one-that-owns-your-task) below says exactly what it adds beyond this +primer, so you can tell what you would be guessing at without it. Treat "I already read the primer" +as insufficient: the primer is calibrated to make you *know what you do not know*, and the sub-skill +is where that gap is closed. + +CGP is implemented almost entirely as procedural macros. Every macro desugars to ordinary Rust +traits and impls, so the reliable way to understand any construct is to know the code it expands +to. This primer shows those expansions where they matter and keeps them out of the way where they +do not. + +## Tooling: use cargo-cgp for readable errors and expansions + +**Before debugging any CGP compile error, use `cargo-cgp` if it is available.** It has two commands +you will want: `check`, which reshapes the errors, and +[`expand`](#reading-what-a-macro-generated-cargo-cgp-expand), which shows the code the macros generated. `cargo-cgp` is CGP's +first-class toolchain — a cargo subcommand that stands in for `cargo check` and rewrites CGP's +compiler errors into a compact, root-cause-first form, tagging each rewritten message with a +`[CGP-Exxx]` code. A raw CGP error is often a wall of generated types with the real cause buried or +hidden entirely; `cargo-cgp` names the cause and renders the dependency chain that leads to it. +Recommend it to the user for building and checking CGP code, and prefer it over plain `cargo check` +whenever a wiring failure needs diagnosing. + +**Check whether it is installed** with `cargo cgp --version` (or just run `cargo cgp check` in a CGP +project). If the subcommand is missing, it is not installed. + +**If it is not installed, recommend installing it** — tell the user it makes CGP errors far more +readable — and **install it on their behalf only with their approval**, since it provisions a nightly +toolchain and builds a compiler-linked driver (heavy). + +**Prefer the cargo path**, which is the default for almost every machine: `cargo install cargo-cgp` +then `cargo cgp setup` (the first installs the small front-end on whatever toolchain is present; +`setup` provisions the pinned nightly and builds the matching driver in lockstep). It needs rustup. + +**Reach for Nix only if the host actually has it** — a `nix` command on `PATH` or a `flake.nix` in the +project — or if the user explicitly asks for it; otherwise do not bring Nix up at all. When Nix *is* +present but cargo-cgp is not installed, the lightest move is to **not install** and instead run the +tool through the flake from the project directory: +`nix run github:contextgeneric/cargo-cgp/v0.1.0-alpha -- check` (arguments after `--` go to +`cargo check`). To install into a Nix profile instead, use +`nix profile install github:contextgeneric/cargo-cgp/v0.1.0-alpha`. + +cargo-cgp requires a specific pinned Rust nightly, installed by `cargo cgp setup` (or built by the +Nix flake), and forces it only for its own check, so the user's project keeps its own toolchain +untouched. Full instructions: +. + +**Using it:** run it wherever you would run `cargo check` (arguments after `check` are forwarded): +`cargo cgp check`, `cargo cgp check --workspace`. It keeps rustc's own error code and adds a +`[CGP-Exxx]` tag, leading with the root cause over a `cargo tree`-style dependency chain; the codes +are catalogued at +. + +### Reading what a macro generated: `cargo cgp expand` + +**When a CGP error stops making sense, read the code the macros produced rather than reasoning about +what you think they produce.** A wiring failure is always "the emitted impls do not resolve," and the +impls are generated, so the fastest way past a confusing diagnostic is often to look at them. +`cargo cgp expand` prints the crate after macro expansion, with CGP's type-level constructs +**resugared** — a field tag reads `Symbol!("width")`, not the raw `Symbol<5, Chars<'w', …>>` +spine the compiler prints; a pipeline reads `Product![StepOne, StepTwo]`; a namespace key reads +`Path!(@app.GreeterComponent)` — so the generated code is legible in the same vocabulary as the +source. + +Reach for it in four situations, each one where the answer is in the generated code rather than in the +message: + +- **A diagnostic names a type you did not write** (`IsProviderFor<…>`, a `PathCons<…>` key, a + `__Context__` parameter) and you need to see the impl it came from. +- **A wiring table does not resolve** and you want the real `DelegateComponent` keys and `Delegate` + values it produced, rather than inferring them from the table's syntax. +- **You are unsure what a construct emits** — the exact `where` clauses of a provider impl, whether a + getter's blanket impl requires the field you think it does. Reading the expansion beats guessing, and + beats trusting a remembered expansion. +- **Two forms differ and only one compiles.** Expand both and diff; the delta is the bug. + +Run it on one target, narrowed to what you care about: + +```sh +cargo cgp expand --lib # the whole library target +cargo cgp expand --lib --item contexts::MockApp # one module, type, or trait +``` + +**Target selection is required when a package has several targets** — pass `--lib` or `--bin NAME`, or +cargo declines with "extra arguments to `rustc` can only be passed to one target". Other arguments +(`-p`, `--features`) forward to `cargo rustc`, and the expansion goes to stdout, so redirect it to a +file when it is long and read that instead of flooding your context. + +**`--item ` is what makes the output manageable**, and which of three rules applies depends on +what the path names. The path is `::`-separated, may carry a leading `crate::`, and names something +inside the crate being expanded: + +- a **module** → its contents (`--item contexts`); +- a **type** → its declaration and every impl written *for* it. For a context that is its struct, the + `HasField`/`HasFieldMut` impls the derive generated, and its `DelegateComponent` wiring entries with + the real key and provider types (`--item Rectangle`); +- a **trait** → its definition and every impl *of* it, which is usually the rule you want. Naming a + component's *provider* trait (`--item AreaCalculator`) gives the provider trait, the delegation + blanket impl, the `UseContext` and `RedirectLookup` impls, and each wired provider's impl; naming the + *consumer* trait (`--item CanCalculateArea`) gives just the consumer trait and its routing blanket. + +Two limits matter when you read the output. **`expand` is not a check**: it stops once the macros are +expanded, so it reports nothing about wiring — use `cargo cgp check` for that, and expect `expand` to +succeed even on a crate that does not type-check (which is exactly what makes it useful mid-debugging). +And the output is for reading, not compiling: the `cgp::macro_prelude::` qualifier is stripped, and an +`open` statement's per-key entry keeps its raw `PathCons<…>` key. + +One availability note: `expand` is newer than cargo-cgp v0.1.0-alpha, so a crates.io install does +not carry it yet. Until the next release it comes from the Nix flake without a tag +(`nix run github:contextgeneric/cargo-cgp -- expand --lib`) or from a source checkout; see +. + +**Scope:** cargo-cgp is optional and adds only `check` and `expand` — there is no +`cargo cgp build`/`run`/`test`, so build, run, and test the project with plain cargo. CGP itself +compiles on any **stable Rust ≥ 1.89**, so plain `cargo check` works on a CGP project too; reach for +`cargo cgp check` specifically when you hit or expect a wiring error and want it made readable. + +`cargo-cgp` can also be Rust Analyzer's on-save check backend, via +`rust-analyzer.check.overrideCommand` set to +`["cargo","cgp","check","--workspace","--all-targets","--message-format=json"]`. But **never modify +the user's Rust Analyzer settings implicitly** — mention this option and let them opt in, and only +edit their editor configuration when they explicitly ask you to. + +**When cargo-cgp is not available, or leaves an error largely unrewritten**, fall back to reading the +raw compiler output by hand — and only then load the [error-extraction sub-skill](references/error-extraction.md), +the technique for reducing a raw CGP cascade to its root cause. When cargo-cgp *has* reshaped the +error, its `[CGP-Exxx]` headline and root-cause tree are already the compact summary that sub-skill +would produce, so you do not need it. + +### Versions and keeping this skill current + +This skill is written for **CGP v0.8.0** and **cargo-cgp v0.1.0-alpha**. Check both on the host and +act on a mismatch: + +- Read the user's `cgp` version (its `Cargo.toml`/`Cargo.lock` entry) and run `cargo cgp --version` + for the tool. +- **If either is older than recorded here**, recommend updating it — `cargo update -p cgp` for the + library, `cargo cgp update` (or a Nix flake refresh) for the tool — so its behavior matches this + skill. +- **If the host's `cgp` is *newer* than v0.8.0**, this skill is behind the library: tell the user the + **skill should be upgraded** to match their `cgp`, rather than changing their code to fit an older + skill. Treat the newer `cgp` as authoritative and flag the gap instead of guessing. + +## The problem CGP solves + +Rust's coherence rules permit at most one implementation of a trait for a given type, and forbid +implementing a foreign trait for a foreign type (the orphan rule). This makes it hard to offer +several interchangeable implementations of one interface, or to let a downstream crate choose an +implementation for a type it does not own. CGP sidesteps both limits with a two-trait split: an +implementation is written against a **provider trait** whose `Self` is a dummy marker type the +crate owns, so coherence never blocks it, and a concrete **context** type later picks which +provider it uses through a small type-level table. The choice is local to the context, so two +different contexts can wire the same interface to different implementations. + +## Blanket traits and impl-side dependencies + +CGP grows out of blanket trait implementations (extension traits), and the single most important +idea to internalize is the **impl-side dependency**: a blanket impl can require constraints in its +`where` clause that are *not* part of the trait interface. Those hidden requirements are the +paradigm's form of dependency injection. For example: + +```rust +pub trait CanGreet { + fn greet(&self); +} + +pub trait HasName { + fn name(&self) -> &str; +} + +impl CanGreet for Context +where + Context: HasName, +{ + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} +``` + +`CanGreet` hides its `HasName` dependency inside the blanket impl, so a caller that is itself +generic does not have to forward `HasName` the way it would with a free generic function. In CGP +you typically start by writing generic logic as a blanket trait like this, and promote it to a +full CGP component later only when you need more than one implementation. Blanket traits are not +themselves CGP components, but the technique recurs throughout CGP. + +## The core vocabulary + +CGP code is readable once you hold five terms in mind. A **consumer trait** is the ordinary, +`self`-style trait you call (`CanGreet`, `CanCalculateArea`); it reads as a verb (`CanDoX`). A +**provider trait**, generated by `#[cgp_component]`, is the same interface with `Self` moved to an +explicit `Context` generic parameter (`Greeter`, `AreaCalculator`); it reads as +a noun (`SomethingDoer`, or `…Provider` when no noun fits). A **provider** is a zero-sized marker +struct (e.g. `GreetHello`, `RectangleArea`) that implements a provider trait — it carries no +runtime value and exists only as a name at the type level. **Wiring** is the act of telling a +context which provider implements each component, recorded in a type-level table. An +**impl-side dependency** is a `where`-clause constraint a provider needs but the consumer trait +does not expose. A **component** is the whole bundle a macro generates: consumer trait, provider +trait, and a `…Component` marker type that keys the wiring table. + +The duality is the crux: a consumer trait is what you *use*, a provider trait is what you +*implement*, and the macro-generated blanket impls connect them so that wiring a context to a +provider makes the context implement the consumer trait. When you see a provider trait method take +`context: &Context` where the consumer took `&self`, that is the same method — `self` became +`context`. + +**"Context" covers two situations that look alike and behave very differently, and this is the most +common place a reader's model of CGP breaks.** A **value context** is a context that *is* the data the +capability operates on — the `String` in `String: CanEncode`, the `Rectangle` in +`Rectangle: CanCalculateArea`. An **environmental context** is a type that exists to supply choices and +capabilities rather than to be operated on: an application, a test harness, a service. It is the far more +common kind in real CGP code, and it frequently has no fields at all — `struct App;` is a complete +context, because its whole job is to be a name the wiring table hangs off. Both sit in the `Self` position +and both carry a wiring table, so nothing in a signature distinguishes them. + +A second, independent distinction describes the **component** rather than its context. A component is +**self-targeted** when the capability is about the `Self` type (`CanGreet`, `HasErrorType`, every getter), +and **parameter-targeted** when it is about a type parameter while `Self` only decides +(`CanEncodeValue`, `CanCalculateArea`). A parameter alone does not settle it: in +`CanCompute` the target is `Input` while `Code` is a *selector* the wiring dispatches on, and +a component may carry both. Which pair a capability uses decides how many independent choices are +available — a self-targeted component wired on a foreign value type gets one provider program-wide, while +an environmental context can be defined as many times as needed — and +[modularity-hierarchy](references/modularity-hierarchy.md) works out which to reach for. **When you +explain CGP to a user, say which arrangement the example is in**, because moving from a value context to +an environmental one changes no signature and readers otherwise lose track of what a context is. + +A persistent source of confusion to avoid: inside a provider, `self`/`Self` (in `#[cgp_impl]`) or +the `context`/`Context` parameter (in the raw provider-trait form) always refer to the **context**, +never to the provider struct. The provider struct is a pure type-level name with no fields and no +runtime value — you cannot store state in it, and any attempt to read a "field" of a provider at +runtime is a mistake. + +## Reading CGP code on sight + +To follow most CGP code you only need to recognize a handful of shapes: + +- `#[cgp_component(Greeter)] trait CanGreet { fn greet(&self); }` defines a component. `CanGreet` + is the consumer trait you call; `Greeter` is the provider trait implementations target; + `GreeterComponent` is the wiring key. +- `#[cgp_impl(new GreetHello)] #[uses(HasName)] impl Greeter { fn greet(&self) { … } }` writes a + provider named `GreetHello` for the `Greeter` component. Inside, `self`/`Self` mean the + *context*, and `#[uses]` lists the impl-side dependencies — it desugars to `where Self: HasName`, + which is the form you read in older code. +- `#[cgp_fn] fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { … }` + defines a single-implementation capability as a blanket-impl trait, pulling `width`/`height` from + the context's fields automatically. +- `delegate_components! { Person { GreeterComponent: GreetHello } }` wires the `Person` context: it + says "for the `Greeter` component, `Person` uses the `GreetHello` provider." After this, `Person` + implements `CanGreet`. +- `check_components! { Person { GreeterComponent } }` is a compile-time assertion that the wiring is + complete and all transitive dependencies are satisfied. + +A consumer trait can also be implemented directly on a context like any normal Rust trait +(`impl CanGreet for Person { … }`) — CGP traits are a superset of vanilla traits, and the macros +only save boilerplate. + +## Which construct to use: prefer this, not that + +When two constructs can express the same thing, CGP has a preferred one, and choosing wrong produces +code that compiles but reads as dated or misuses an advanced tool. This table is the quick answer, so +you pick the right pattern even without reading further. Each preference is a default with narrow +exceptions, spelled out under [Writing providers](#writing-providers) below and, with full before/after +examples, in the [modern-idioms](references/modern-idioms.md) sub-skill; the "avoid" column is not +wrong, it is what you *read* in generated code and legacy wiring, not what you *write* anew. + +| To… | Prefer | Not (legacy / advanced / read-only) | +|---|---|---| +| write a provider | `#[cgp_impl]`, header `impl Trait` (omit `for Context`) | raw `#[cgp_provider]` / `#[cgp_new_provider]` | +| read a field from your own context | an `#[implicit]` argument | `#[cgp_auto_getter]` / any getter trait declared just to read it | +| declare a getter (field on *another* type, or a named shared capability) | `#[cgp_auto_getter]`, used sparingly | `#[cgp_getter]` (only for per-context field choice) | +| require a capability | `#[uses(Trait)]` | `where Self: Trait` | +| require an inner provider | `#[use_provider(P: Trait)]` | `where P: Trait` | +| name an abstract type (e.g. `Error`) | `#[use_type(Trait.Type)]` + the bare alias | `: Trait` supertrait + `Self::Type` | +| pass several args to `#[uses]` / `#[use_type]` | one attribute, comma-separated | repeating the same attribute | +| bind several inner providers with `#[use_provider]` | one attribute per provider | a comma-separated list of pairs — it does not parse | +| add a capability supertrait | `#[extend(Trait)]` | native `pub trait …: Supertrait` | +| dispatch a component per type | the `open` statement (or a namespace) | `#[derive_delegate]` + `UseDelegate` tables | +| verify a context is fully wired | separate `check_components!` (or `delegate_and_check_components!` for a basic starter context) | leaving a context's wiring unchecked | +| build a field/list/string/path type | `Symbol!` / `Product!` / `Sum!` / `Path!` sugar | hand-written `Cons`/`Nil`/`Chars`/`Either`/`PathCons` | + +Two names are gone entirely, not merely dated: never write `#[cgp_context]` (removed — assemble a +context with `delegate_components!` and the derives instead) or `ProvideType` (renamed to +`TypeProvider`). One caveat carries across the whole table: a construct's *own* local associated type +stays qualified as `Self::Output` — only an *imported* abstract type is written bare via `#[use_type]`. + +## The prelude and version + +Almost everything CGP exports comes through one import, which belongs at the top of every module +that uses CGP: + +```rust +use cgp::prelude::*; +``` + +This skill describes CGP **v0.8.0** (and cargo-cgp **v0.1.0-alpha** — see +[Tooling](#tooling-use-cargo-cgp-for-readable-errors-and-expansions) for checking both versions on the host and +reconciling a mismatch). A few names are intentionally *not* in the prelude and must be +imported from their module — most notably the error-handling wiring keys and backends (see Error +handling below). Inside documentation code blocks you may omit the prelude import for brevity. + +--- + +## Components: the heart of CGP + +A component is what `#[cgp_component]` builds from one trait so that *using* a capability and +*implementing* it become separate, swappable things. Applying it to a consumer trait: + +```rust +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} +``` + +generates five items, of which you write or call only the first. The **consumer trait** `CanGreet` +is emitted unchanged — callers write `person.greet()`. The **provider trait** is the same interface +with `Self` moved to a leading `Context` parameter and `self` rewritten to `context`: + +```rust +pub trait Greeter: IsProviderFor { + fn greet(context: &Context); +} +``` + +The **component marker** `pub struct GreeterComponent;` is the zero-sized key into the wiring table. +Two **blanket impls** connect the sides: one makes any context that implements the provider trait +*for itself* automatically implement the consumer trait; the other lets a context that delegates +this component (via `DelegateComponent`) inherit the provider trait from whatever provider it +delegates to. You never write these blanket impls; they are the routing machinery, and it is enough +to think of wiring as a table lookup. Crucially, that lookup is resolved **entirely at compile +time**: the table is a set of trait impls, so the compiler picks the provider during type +resolution and monomorphizes the call to a direct, statically-dispatched one. CGP wiring is +therefore zero-cost — there is no runtime table, no dynamic dispatch, and no `vtable` in the +generated code, even though "table lookup" is a useful mental model. In real generated code the +context parameter is named `__Context__` and the provider parameter `__Provider__` (reserved +identifiers chosen so they never clash with your types); the names `Context`/`Provider` here are +for readability. + +The attribute's argument sets those three generated names. The bare `#[cgp_component(Greeter)]` form +names only the provider trait; the component marker defaults to that name plus `Component` +(`GreeterComponent`) and the context to `__Context__`. A key/value form with brace delimiters +overrides any of the three — `#[cgp_component { name: GreeterComponent, provider: Greeter, context: Context }]` +— where only `provider` is required. One limitation to know: a **const generic parameter** on the +trait is rejected, because a component's extra parameters are recorded as a tuple of *types* in +`IsProviderFor` and a const value has nowhere to live there (an associated `const` *item* on the +trait is fine — it is supplied by a const-generic provider struct as usual). See +[macro-grammar](references/macro-grammar.md) for the full argument grammar and +[components](references/components.md) for the complete expansion. + +**A component trait may declare as many items as any Rust trait; what to group is the items one provider +choice decides together.** Everything in one component is answered by one provider, so items settled by one +decision belong together and items settled by different decisions do not. Most application capabilities are +one decision and so one method — which is why single-method components dominate — but a method plus the +associated type it produces is one decision too, which is why CGP's own `CanCompute` and `CanHandle` +declare `type Output` beside their method, and a getter component groups several field reads because one +`UseFields` provider answers them all by name. What costs reuse is grouping *different* decisions, as an +entity trait does (`Shape` with `area`, `perimeter`, `scale`, `rotate`): each provider then carries the +union of every method's dependencies, a higher-order provider must forward the methods it has no opinion +about, and a context needing part of the surface must still answer all of it with placeholder types and +`unimplemented!()` bodies. A consumer trait named after a noun rather than a verb is the usual sign. When +you write or review one, check that a second context could plausibly reuse one of its providers *whole*; if +not, implement the trait directly on the concrete context and skip the machinery. +[components](references/components.md) carries the two multi-item cases, the costs, and the procedure for +splitting a trait that has grown past one decision. + +### `IsProviderFor` and error messages + +`IsProviderFor` is an empty marker trait that rides as a supertrait on +every provider trait. Its only purpose is good error messages: a provider lists its dependencies in +a `where` clause, and the macros implement `IsProviderFor` for the provider under the *same* bounds, +so when a dependency is unmet the compiler can name the missing bound instead of vaguely saying "the +trait is not implemented." When you see an error that some provider does not implement +`IsProviderFor<…>`, read it as "the provider trait is not implemented, because the named dependency +is missing." You never write `IsProviderFor` yourself — the provider macros generate it. + +### Writing providers + +A provider can be written at three levels of sugar over the same machinery. **`#[cgp_impl]` is the +form to prefer**, because it lets you write the provider in consumer-style syntax — keeping `self`, +`Self`, and the consumer method signatures — and the macro rewrites it into the provider-trait +shape: + +```rust +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} +``` + +The provider name goes in the attribute argument; a leading `new` keyword also declares the +`struct GreetHello;`. The dependency is declared with [`#[uses]`](#uses-extend-extend_where) rather than a +hand-written `where Self: HasName` clause, which is the preferred form and desugars to exactly that bound. +**Prefer the unqualified `impl Greeter` form and let the macro insert the +context parameter** — omitting `for Context` is what makes a provider read like an ordinary trait +impl. Write the explicit `impl Greeter for Context` only when you must bound or name the +context readably (for example a lifetime or HRTB the sugar cannot express); it must then be declared +in the impl generics. Remember that `self`/`Self` here mean the context. `#[cgp_impl]` desugars to: + +```rust +#[cgp_new_provider] +impl Greeter for GreetHello +where + Context: HasName, +{ + fn greet(context: &Context) { + println!("Hello, {}!", context.name()); + } +} +``` + +The lower forms are what you mostly *read* rather than write. `#[cgp_provider]` is applied to a +provider-trait impl written directly on an existing provider struct; it passes the impl through and +auto-generates the matching `IsProviderFor` impl from the same `where` clause. +`#[cgp_new_provider]` is the same but also declares the provider struct (a generic provider gets a +`PhantomData` field over its parameters, e.g. `pub struct Multiply(PhantomData);`). +The attribute argument can override the component name, which otherwise defaults to the provider +trait's name plus `Component`. One special `#[cgp_impl]` form, `#[cgp_impl(Self)]`, bypasses the +provider rewrite entirely and emits the block as a *direct* consumer-trait impl on the concrete +context (the `for Context` clause is then required) — useful when you want to implement a consumer +trait by hand while still applying companion attributes such as `#[use_provider]`. + +**Strongly prefer the modern, vanilla-looking idioms when you write CGP, and reach for the explicit +forms only when a construct genuinely cannot express the case.** Each idiom below trades a piece of +visible machinery for syntax that reads like ordinary Rust: + +- **Write providers with `#[cgp_impl]`** (not `#[cgp_provider]`/`#[cgp_new_provider]`), omitting + `for Context` so the header reads `impl Greeter`. +- **Declare dependencies with attributes, not hand-written bounds:** capability dependencies with + [`#[uses(...)]`](references/functions-and-getters.md), inner-provider dependencies with + [`#[use_provider(...)]`](references/higher-order-providers.md), instead of raw `Self:` / + `Provider: …` `where` clauses. When one of these attributes — or + [`#[use_type]`](references/abstract-types.md) — carries several arguments, put them all in one + attribute separated by commas (`#[uses(A, B)]`, `#[use_type(T.X, U.Y)]`) rather than stacking the + same attribute repeatedly; one attribute reads as a single dependency list. +- **Read context fields with [`#[implicit]`](references/functions-and-getters.md) arguments** rather + than a getter trait — this is the default for *any* field a provider reads from its own context, + including one several providers each read. An implicit argument reads only from `self` and takes a + plain `&T` by reference without cloning. Use `#[cgp_auto_getter]` sparingly, only where an implicit + argument cannot reach: a getter for a field on *another* type required as a `where` bound on it + (`Request: HasBasicAuthHeader`), an accessor other code depends on as a named capability, or a + getter carrying an associated type inferred from the field. Reserve `#[cgp_getter]` for the advanced + case of choosing the source field per context. +- **Add non-type capability supertraits with [`#[extend(...)]`](references/functions-and-getters.md)** + rather than native `: Supertrait` syntax, which reads as OOP-style inheritance rather than a + capability import. +- **Import abstract types with [`#[use_type]`](references/abstract-types.md)**, writing the bare + alias (`Scalar`, `Error`) instead of a hand-written `: HasScalarType` supertrait and a qualified + `Self::Scalar` at every use. This holds even in `#[cgp_component]` definitions: prefer + `#[use_type(HasErrorType.Error)]` over `: HasErrorType` + `Self::Error`. When a provider *pins* an + abstract type to a concrete one — a `where Self: HasErrorType` clause — express + that with the equality form `#[use_type(HasErrorType.{Error = AppError})]`, which emits the same + `Self: HasErrorType` bound; the right-hand side is substituted too, so an + imported alias is grounded wherever it appears in it — naming one outright unifies two abstract + types (`#[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})]`), + and one nested inside a type is grounded in place + (`#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits + `Self: HasTransactionType::Db>>`). The equality form is a + `#[cgp_impl]`/`#[cgp_fn]` tool — it is rejected on `#[cgp_component]`. +- **Dispatch a generic-parameter component with the `open` statement or a namespace**, skipping + `#[derive_delegate]`/`UseDelegate` when defining a new component. + +The explicit forms remain correct and are what you *read* in generated code and desugaring; the +exceptions that still need them are narrow — an associated-type-equality bound on a **non-abstract-type** +trait (`Iterator`, `From`), which `#[use_type]` cannot spell and which reads more clearly +as an explicit `where` clause than crammed into an import-shaped `#[uses]` (which now accepts it), a +lifetime or HRTB that forces a named context, or a **local** associated type such as `Self::Output`, +which stays qualified because it is the trait's own type, not an imported abstract one. Do *not* leave an +equality bound on an **abstract-type** trait (`Self: HasErrorType`) as a hand-written +`where` clause — that is exactly what the `#[use_type]` equality form `#[use_type(HasErrorType.{Error = AppError})]` +replaces; only equality on a trait you would never `#[use_type]` from stays an explicit `where`. For the full legacy-to-modern before/after mapping of each idiom — the +reference to load whenever you read or modernize existing CGP — see +[modern-idioms](references/modern-idioms.md). + +The provider's `where` clause is where **impl-side dependencies** live, whether you write it by hand or let +`#[uses]` generate it: `GreetHello` requires `Self: HasName`, but `CanGreet` exposes no such bound, so a +caller bounding on `CanGreet` never sees `HasName`. The wiring satisfies each dependency by resolving it +through the same context. + +A consumer trait is still an ordinary trait: when you don't need multiple implementations, write +`impl CanGreet for Person { … }` directly and skip the provider machinery entirely. + +--- + +## Wiring: connecting a context to providers + +Wiring records, on a context type, which provider supplies each component. The underlying mechanism +is the `DelegateComponent` trait — a type-level table whose key is the `…Component` marker and whose +`Delegate` associated type is the chosen provider — but you almost always write it through +`delegate_components!`: + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} +``` + +After this, `Person` implements `CanGreet` and `person.greet()` resolves through the table to +`GreetHello`. Swapping the table entry is the only change needed to swap behavior. + +The macro has a few shorthands. An **array key** maps several components to one provider: +`[FooComponent, BarComponent]: FooBarProvider`. A leading **`new`** keyword +(`delegate_components! { new MyComponents { … } }`) also defines `struct MyComponents;`, which is how +you build an **aggregate provider** — a zero-sized provider that holds a table dispatching each +component to a sub-provider, so other contexts can delegate a whole group of components to it as one +reusable unit. A leading **generic list** (`delegate_components! { MyContext { … } }`) wires a +whole family of contexts at once. + +Two further **operators** stand where the `:` does, and you will meet both when reading real wiring. +`Key -> OtherTable` forwards the key to *that table's* own entry for the same key instead of naming a +provider, and `Key => @path` redirects the lookup along a type-level path, of which the `open` +statement below is the sugared special case. Those, the `@`-path key forms, and the `namespace` and +`for` statements are the rest of one shared body grammar that `cgp_namespace!` and +`delegate_and_check_components!` reuse wholesale; [wiring](references/wiring.md) and +[macro-grammar](references/macro-grammar.md) carry it in full, and all of the forms combine inside a +single block. + +The target of `delegate_components!` is therefore not always a context: it is either a concrete +context (as `Person` is above) or an aggregate provider (as `MyComponents` is). This distinction +governs checking — an aggregate provider is dispatched *to* by contexts and is never its own context, +so it must be wired with plain `delegate_components!` and never `delegate_and_check_components!`; the +next section explains why. + +To understand what wiring *does*, picture the explicit version: `delegate_components!` is equivalent +to implementing the consumer trait by hand and forwarding to the provider — +`impl CanGreet for Person { fn greet(&self) { >::greet(self) } }`. +The macro just generates that plumbing (plus the `IsProviderFor` propagation) for you. + +### `UseContext` + +`UseContext` is a provider that implements a provider trait by routing back through the context's +*own* consumer-trait impl — the dual of the consumer blanket impl. Wiring a component to +`UseContext` means "use whatever this context already does for this trait," which is mainly useful +as the default inner provider of a higher-order provider (below). Delegating a component directly to +`UseContext` when the context's only implementation of that component *is* that delegation creates a +circular dependency and fails to compile. + +### Dispatching a generic-parameter component per type with `open` + +When a component is generic over a type parameter, you often want a different provider per value of +that parameter. The modern, preferred way is the **`open` statement** inside `delegate_components!`. +Given a component `CanCalculateArea` (provider `AreaCalculator`), a context dispatches per +shape like this: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +The `open … ;` header opens one or more components for per-value wiring and **must lead** the +block (it comes before any plain `Component: Provider` mappings, or the macro fails to parse). The +braces are optional when opening a single component (`open AreaCalculatorComponent;`); use the +braced list `open { A, B };` to open several at once. Each +`@Component.Key: Provider` entry then assigns a provider for one value of the dispatch parameter. Two +grouping forms share one provider across several values and are **not** interchangeable: a braced group +holds whole path *tails* and ends the path (`@AreaCalculatorComponent.{u32, u64, bool}: SomeProvider`), +while a bracketed group holds alternatives for *one segment* and may be followed by more path +(`@app.[FooComponent, BarComponent].[u64, String]: P` writes all four combinations). A key may also +carry generics (`@SomeComponent.<'a, T> &'a T: SomeProvider`). `open` works through the `RedirectLookup` impl that +every `#[cgp_component]` already generates, so it needs no extra attribute on the component. It does +not combine with a joined namespace (`#[prefix(...)]`); that is the full namespace feature. + +**Legacy form (read but don't write):** older code dispatches the same way by wrapping a nested +table in the `UseDelegate` provider — +`AreaCalculatorComponent: UseDelegate` +— generated by a `#[derive_delegate(UseDelegate)]` attribute on the component. This still +works and is common in existing code, but it is slated for deprecation; prefer `open` for new code. +Note that some CGP-shipped components (the error and handler families) are still *defined* with +`#[derive_delegate]` in the library, so you will see `UseDelegate` tables wiring them. + +--- + +## Checking: verifying wiring at compile time + +CGP wiring is **lazy**: defining a `delegate_components!` entry does not itself check that the +provider's transitive dependencies are satisfied. A missing dependency therefore surfaces only when +the consumer trait is finally used, often as a confusing error. To catch it early and clearly, assert +the wiring with a check: + +```rust +check_components! { + Person { + GreeterComponent, + } +} +``` + +This generates a check trait whose supertrait is `CanUseComponent` for +`Person`; if `Person` cannot actually use the component, the compiler reports the missing dependency +at this site, walking through `IsProviderFor` so the real cause (e.g. a missing +`HasField`) is named rather than hidden. For a component with generic parameters, +list the parameter after the component (`GreeterComponent: Rectangle`), group multiple parameters as +a tuple (`(Rectangle, f64)`), and use array syntax to check several at once. + +`delegate_and_check_components!` fuses wiring and checking in one step, so every delegation is +verified the moment it is written: + +```rust +delegate_and_check_components! { + Person { + GreeterComponent: GreetHello, + } +} +``` + +Its check trait is named `__CanUse{Context}` (vs. `__Check{Context}` for `check_components!`), so +both macros can appear once per module without clashing; override with `#[check_trait(Name)]`. When +the delegated component has generic parameters, add `#[check_params(...)]` on the entry; skip a +single entry's check with `#[skip_check]`. + +**This fused macro is a convenience for basic wiring and for getting started — not the default for +advanced code.** It exists so a newcomer cannot forget to write a separate `check_components!` and +then hit confusing lazy-wiring errors, and it derives a check only for the plain `Component: Provider` +delegation form. It cannot easily derive checks for advanced mappings — generic-parameter dispatch +(the `open` statement and `@`-path keys), namespaces, or per-layer higher-order checks. **In larger, +more advanced codebases, keep `delegate_components!` and `check_components!` separate**, which gives +full control over what is checked: `#[check_providers(...)]` per provider layer, concrete parameters +for generic keys, and checks over opened or namespaced wiring. The one non-negotiable is that a +context's wiring *is* checked somehow; which macro you use to do it scales with the wiring's +complexity. + +One case makes `delegate_and_check_components!` not just unnecessary but wrong: an **aggregate +provider** (the `new MyComponents { … }` table above). That target is a provider other contexts +delegate to, not a context itself, so the check's `CanUseComponent` assertion asks whether the bundle +can use each component *as a context* — a role it never plays, making the answer uninformative either +way. It passes vacuously when the bundled providers need nothing from their context, and fails +blaming the bundle when any of them needs a field or a type the real context would have supplied. +Wire an aggregate provider with plain `delegate_components!`; it is verified indirectly when a real +context that delegates to it is checked, or directly with a `#[check_providers(...)]` block that +asserts `IsProviderFor` on it. Finally, not every unsatisfied +bound is a CGP component — some are ordinary or blanket traits that `check_components!` cannot verify. + +For a nested [higher-order provider](references/higher-order-providers.md), checking the context +tells you a layer is broken but not which one. The `#[check_providers(...)]` attribute on a +`check_components!` table changes the assertion from `CanUseComponent` on the context to +`IsProviderFor` on each named provider, so a dependency missing only from the outer wrapper errors on +its line alone while one missing from the inner provider errors on both — pinpointing the layer. See +[checking](references/checking.md) for the debugging playbook. + +--- + +## Functions and getters: the ergonomic surface + +Most basic CGP reads and writes values from the context, and the constructs here make that look like +plain Rust. + +### `HasField` and `#[derive(HasField)]` + +`HasField` is tag-keyed field access. The `Tag` is a type-level name: `Symbol!("width")` for a +named field or `Index<0>` for a tuple field. `#[derive(HasField)]` generates one impl per field: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} +// generates HasField and HasField +``` + +Field values are read with `self.get_field(PhantomData::)`; the `PhantomData` +carries the tag so type inference knows which field is meant. + +### `#[cgp_fn]` and `#[implicit]` arguments + +`#[cgp_fn]` turns one function into a single-implementation blanket-impl trait — the simplest entry +point to CGP. Arguments marked `#[implicit]` are removed from the signature and pulled from context +fields via `HasField`: + +```rust +#[cgp_fn] +fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +This generates a `RectangleArea` trait (named from the function in PascalCase; override with +`#[cgp_fn(MyName)]`) with a blanket impl for any context that has `width: f64` and `height: f64` +fields. Implicit arguments get `.clone()` added automatically for owned values and `.as_str()` for +`&str`. Generic parameters on the function move to the trait and impl; the `where` clause becomes +impl-side dependencies on the impl only; generic *method* parameters are intentionally unsupported. +Prefer implicit arguments for basic code — they make CGP look like ordinary functions. + +### `#[uses]`, `#[extend]`, `#[extend_where]` + +`#[uses(TraitA, TraitB)]` (on `#[cgp_fn]` or `#[cgp_impl]`) imports `Self` trait bounds, read +like a `use` statement. The simple `Trait` form is idiomatic, but any `where`-clause bound is +accepted, including associated-type equality (`HasErrorType`) — prefer `#[use_type]`'s +equality form for abstract-type pins: + +```rust +#[cgp_fn] +#[uses(RectangleArea)] +fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 { + self.rectangle_area() * scale_factor * scale_factor +} +``` + +`#[extend(Trait)]` adds *supertrait* bounds to the generated trait — the only way to add supertraits +in `#[cgp_fn]` (whose `where` clauses are impl-side dependencies), and the **preferred** way to add a +*non-type capability* supertrait on `#[cgp_component]` too: `#[extend(HasName)]` reads as importing a +capability, whereas the native `pub trait CanGreet: HasName` syntax reads as OOP-style inheritance +from a parent class, which a CGP supertrait is not. (When the supertrait is an abstract-type component +whose associated type the signatures name, prefer `#[use_type]` instead — it adds the supertrait *and* +rewrites the type, and is the recommended form for abstract-type components.) `#[extend_where(Bound)]` +adds `where` clauses to the generated trait definition (`#[cgp_fn]` only), and accepts arbitrary +predicates including associated-type equality, unlike `#[uses]`/`#[extend]`. A fourth `#[cgp_fn]`-only +attribute, `#[impl_generics(Param: Bound)]`, adds a bounded generic parameter to the generated *impl* +alone — not the trait — which is how a `#[cgp_fn]` body borrows a generic value it does not want to +expose as a trait parameter (e.g. `#[impl_generics(Name: Display)]` over an `#[implicit] name: &Name`). + +### Getters: `#[cgp_auto_getter]`, `#[cgp_getter]`, `UseField` + +An `#[implicit]` argument (above) is the default way to read a context field, so a getter trait is +used *sparingly* — only where an implicit argument cannot reach. Because an implicit argument reads +only from the provider's own `self` (and takes a plain `&T` by reference, no clone), it covers every +same-context read, even a field several providers each consume. A getter trait earns its keep in +three cases it cannot handle: a field that lives on a type *other* than the provider's context, where +the getter is required as a `where` bound on that type (`Request: HasBasicAuthHeader`, so there +is no `self` field to read); an accessor other code depends on as a *named* capability through +`#[uses(HasName)]` or a supertrait; and a getter carrying an *associated type inferred from the +field* so the type stays abstract for callers. + +`#[cgp_auto_getter]` generates a blanket getter impl over `HasField`, with the field name taken from +the method name, and is the getter form to prefer for those cases: + +```rust +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} +// blanket impl for any context with a `name` field; &str/&String shorthands handled +``` + +A single-getter trait may instead declare a local associated type used as the return type, inferred +from the field — `trait HasName { type Name; fn name(&self) -> &Self::Name; }`. + +`#[cgp_getter]` is an **advanced** tool, reserved for when a context needs full control over which +field a getter reads from — most getters should use `#[cgp_auto_getter]` or an implicit argument +instead. It is like `#[cgp_component]` but also provides a `UseField` blanket impl, so the +getter's source field can be chosen by *wiring* rather than fixed to the method name. The +`UseField` provider implements a getter by reading the field named `Tag`, which may differ from +the method name: + +```rust +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} +// Person::name() now returns the `first_name` field +``` + +`UseFieldRef` is the `AsRef`/`AsMut`-based variant. Any getter can also be implemented by hand — the +macros only save boilerplate. + +--- + +## Abstract types + +CGP abstracts over types with associated types in components. `#[cgp_type]` is the dedicated macro +(use it instead of `#[cgp_component]` for an abstract-type trait): + +```rust +#[cgp_type] +pub trait HasNameType { + type Name; +} +``` + +This defaults the provider name to the type name plus `TypeProvider` (here `NameTypeProvider`, marker +`NameTypeProviderComponent`) and additionally generates a `UseType` blanket impl. A context fixes the +type by wiring the component to `UseType`: + +```rust +delegate_components! { + Person { + NameTypeProviderComponent: UseType, + } +} +// or directly: impl HasNameType for Person { type Name = String; } +``` + +The direct impl is just as valid and shows that abstract types are ordinary associated-type traits. + +The `#[use_type(HasScalarType.Scalar)]` attribute is the recommended way to *use* an abstract type +inside `#[cgp_fn]`/`#[cgp_impl]`/`#[cgp_component]`: it rewrites bare `Scalar` to the fully-qualified +`::Scalar` everywhere and adds the supertrait/where bound, removing `Self::` +boilerplate and ambiguity. CGP's built-in abstract-type component is `HasType` (provider +`TypeProvider`). + +--- + +## Higher-order providers + +A **higher-order provider** takes another provider as a generic parameter and constrains it with a +provider-trait bound, so its inner behavior is chosen by wiring rather than fixed: + +```rust +#[cgp_impl(new ScaledAreaCalculator)] +#[use_provider(InnerCalculator: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + let base_area = InnerCalculator::area(self); + base_area * scale_factor * scale_factor + } +} +``` + +`#[use_provider(InnerCalculator: AreaCalculator)]` completes the inner provider's bound by adding the +`Self` parameter for you (you write `: AreaCalculator`, it means `AreaCalculator`) and moves it +into the `where` clause — that is the *only* thing the attribute does. Inside the body you still call +the provider explicitly with the associated-function form `InnerCalculator::area(self)`; there is no +call-site rewriting. A context then chooses the inner provider when wiring, e.g. +`AreaCalculatorComponent: ScaledAreaCalculator`. + +A higher-order provider often defaults its inner parameter to `UseContext` +(`pub struct IterSumArea(PhantomData);`), so that when no inner provider is +named, the inner step falls back to the context's own wiring. Not every provider with a generic +parameter is higher-order: a provider like `GetName` that uses `Tag` only as a `HasField` key +(no provider-trait bound) is not. + +When a component itself is generic (`#[cgp_component(AreaCalculator)] trait CanCalculateArea`), +the provider trait appends the parameters after the context (`AreaCalculator`), +`IsProviderFor` groups them into its `Params` tuple, and lifetimes are lifted into the `Life<'a>` +type. Such a component is most useful for **cross-context dependencies**: when the main target is a +generic parameter (e.g. `CanCalculateArea: HasScalarType`), individual shape types need not +implement shared capabilities — the common context supplies the shared abstract type, value-level +injection (a global scale factor via a getter), and lazy per-context provider binding, so two apps +can wire the same shape to different providers. + +--- + +## Error handling + +CGP makes the error type abstract so generic code can fail without naming a concrete error. +`HasErrorType` (an abstract-type component, `type Error: Debug`) gives a context one shared +error type; `CanRaiseError` constructs it from a concrete source error +(`Context::raise_error(source)`); `CanWrapError` attaches detail. Both build on +`HasErrorType` and are associated-function (no `self`) components that dispatch per source/detail +type. An error-aware trait imports that error type with `#[use_type(HasErrorType.Error)]`, so it +names the error as the bare `Error` instead of writing `: HasErrorType` and `Self::Error` by hand: + +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} + +#[cgp_impl(new LoadOrFail)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + return Err(Self::raise_error("empty path".to_owned())); + } + Ok(format!("contents of {path}")) + } +} +``` + +A context wires its error type and the raise/wrap behavior. The backend providers — `RaiseFrom` +(convert via `From`), `ReturnError`, `RaiseInfallible`, `PanicOnError`, `DebugError`/`DisplayError` +(format into a `String` and forward), `DiscardDetail` — plug in per source type, modern-style with +`open`: + +```rust +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseError: DebugError, + } +} +``` + +**Imports:** `HasErrorType`, `CanRaiseError`, and `CanWrapError` come from the prelude, but the +wiring keys (`ErrorTypeProviderComponent`, `ErrorRaiserComponent`, `ErrorWrapperComponent`) live +under `cgp::core::error`, and the backend providers (`RaiseFrom`, `DebugError`, …) under +`cgp::extra::error` — import the specific names you wire. Standalone backends (`cgp-error-anyhow`, +`cgp-error-eyre`, `cgp-error-std`) provide ready error types. + +--- + +## Handlers: the computation family + +CGP models computation as a family of components along three axes — synchronous vs. async, +infallible vs. fallible, and input-taking vs. input-free: + +- **`Computer` / `CanCompute`** — a synchronous, infallible transform `compute(&self, PhantomData, input) -> Output`. By-reference (`ComputerRef`) and async (`AsyncComputer`) variants exist. +- **`TryComputer` / `CanTryCompute`** — the fallible computer. +- **`Producer` / `CanProduce`** — input-free production (only a context and a `Code` tag). +- **`Handler` / `CanHandle`** — the general **async, fallible, error-aware** computation; the workhorse for I/O and pipelines. It supertraits `HasErrorType`. +- **`CanRun` / `CanSendRun`** — task runners. + +Any CGP trait with async methods — a handler, a runner, or one you define — declares them under the +`#[async_trait]` attribute, which rewrites each `async fn` to `-> impl Future` (the lint-clean, +allocation-free form). The generated future carries no `Send` bound, so spawning it on a +work-stealing executor needs the `Send`-recovery pattern in [handlers](references/handlers.md). + +`#[cgp_computer]` and `#[cgp_producer]` define a `Computer`/`Producer` provider from a function. +Providers compose through combinators: `PipeHandlers` chains handlers +left-to-right, `ComposeHandlers` nests them, `ReturnInput` passes input through, and the `Promote*` +adapters lift a simpler handler (e.g. a sync `Computer`) into a more capable one (an async +`Handler`). For example, a context wires a pipeline of field-reading computers: + +```rust +delegate_components! { + MyContext { + ComputerComponent: + PipeHandlers, + Add, + Multiply, + ]>, + } +} +// context.compute(PhantomData::<()>, 5) runs ((5*foo)+bar)*baz +``` + +Dispatch routes an extensible-data input to per-variant handlers: `#[cgp_auto_dispatch]` generates a +handler from a trait, and the combinators `MatchWithHandlers` / `MatchWithValueHandlers` / +`ExtractFieldAndHandle` match an enum's variants to sub-handlers, proving exhaustiveness without a +wildcard. Monadic handlers (`PipeMonadic`, `BindOk`, `BindErr`, the identity/ok/err monads) compose +handlers through a monad. The handler family is broad — read [handlers](references/handlers.md) for +the full set, including `Send`-bound recovery for async trait methods. + +--- + +## Extensible data + +CGP can build and read structs and enums generically, by their named fields and variants. The +`#[derive(HasFields)]` derive exposes a type's whole field list; `#[derive(CgpData)]` (and the +record/variant-specific `CgpRecord`/`CgpVariant`) derive the full extensible-data machinery: + +```rust +#[derive(CgpData)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} +``` + +Records are built field-by-field through the builder family (`HasBuilder`, `BuildField`) — the +**extensible builder pattern** assembles a context from independent per-field outputs. Variants are +constructed with `FromVariant`, deconstructed with the `ExtractField` extractor family, and the +**extensible visitor pattern** handles each variant. The type-level spines underneath are the +product list (`Product![A, B, C]` over `Cons`/`Nil`) for records and the sum list (`Sum![A, B]` over +`Either`/`Void`) for variants. Structural **casts** convert between shapes — `CanUpcast` widens a +smaller enum into a larger one, `CanDowncast` narrows, `CanBuildFrom` rebuilds a record from a +superset. Dispatching extensible-data inputs to handlers uses the dispatch combinators above. + +--- + +## Namespaces + +Namespaces are reusable, inheritable wiring tables (a preset mechanism) that keep top-level wiring +short as component counts grow. `cgp_namespace! { new MyNs: ParentNs { … } }` defines a namespace +(optionally inheriting a parent after the colon); a context then **joins** it inside +`delegate_components!` with a `namespace MyNs;` statement, after which every lookup it does not wire +directly forwards through the namespace, so any direct entry overrides just that key. A component +**registers into** a namespace with the `#[prefix(@path in MyNs)]` attribute on its `#[cgp_component]` +trait, and a `#[cgp_impl]` provider registers as a per-type default with `#[default_impl(T in DefaultImpls1)]`, +which a context pulls in with a `for in Table { … }` loop. + +The underlying mechanism is the `RedirectLookup` provider, which re-routes a component lookup along a +type-level `Path!`; the `open` statement above is a lightweight special case of it. `DefaultNamespace` +resolves a default provider when a context does not override one. Read +[namespaces](references/namespaces.md) for the preset and inheritance syntax. + +--- + +## Type-level primitives: a decoder ring + +CGP encodes lists, strings, and numbers as types. You mostly use the sugared macros and only need to +*recognize* the expanded forms in errors: + +- **`Symbol!("name")`** — a type-level string (field-name tag). Expands to `Symbol<4, Chars<'n', Chars<'a', Chars<'m', Chars<'e', Nil>>>>`. The leading length works around missing const-generics. +- **`Product![A, B, C]`** — a type-level list. Expands to `Cons>>`. `product![…]` is the value-level form. Used for field lists and handler pipelines. +- **`Sum![A, B]`** — a type-level sum (the dual of `Product!`), over the `Either`/`Void` spine. Used for enum variant lists. +- **`Index`** — a type-level natural number, tags tuple-struct fields. +- **`Field`** — a value paired with its type-level name tag. +- **`Path!`** / `PathCons` — a type-level path, used by namespaces and `RedirectLookup`. +- **`Life<'a>`** — a lifetime lifted into a type, used when a component has lifetime parameters. +- **`MRef`** — an owned-or-borrowed value. + +Prefer the sugar (`Symbol!`, `Product!`) and the readable names (`Cons`/`Nil`) in anything you write. + +--- + +## Sub-skills: load the one that owns your task + +The primer gave you the shape of every construct; each sub-skill below is the ground truth for one +area — the exact grammar, the full expansion, the corner cases, and worked examples. **Loading the +relevant sub-skill is not optional polish; it is the step that turns a plausible guess into correct +code.** Every entry names what it adds beyond this primer *and* what you would be guessing at without +it, so you can see the risk of skipping it. Load a sub-skill whenever your task touches its area — +reading it, writing it, reviewing it, or debugging an error that mentions it — and re-load it when +you move into an unfamiliar corner. When a task spans several areas, load each one; they cross-link, +and following those links is expected, not a detour. + +Two of the sub-skills are cross-cutting rather than construct-specific, and one of them applies to almost every task. Start with **[references/macro-grammar.md](references/macro-grammar.md)** for any task that writes, edits, or debugs CGP syntax: it is the single reference for the formal grammar of every macro, the invariant each expansion preserves, and a decoder for the compiler errors CGP produces. *Without it* you are guessing which attribute forms parse, what a macro emits, and what an `IsProviderFor` or `DelegateComponent` error is actually telling you. Reach for **[references/modern-idioms.md](references/modern-idioms.md)** whenever you read or modernize existing CGP: it maps every legacy, explicit form to the modern idiom you should prefer, both to write vanilla-looking code and to decode the inside-out provider impls, hand-written `where` bounds, `Self::Type` paths, and `UseDelegate` tables you meet in older code. *Without it* you will either propagate outdated syntax or fail to recognize that legacy code and modern code mean the same thing. + +The remaining sub-skills each own one construct family: + +- **[references/components.md](references/components.md)** — `#[cgp_component]` and the full expansion (consumer/provider traits, the two blanket impls, the `…Component` marker), why `IsProviderFor` exists, the three provider-writing macros (`#[cgp_impl]`, `#[cgp_provider]`, `#[cgp_new_provider]`), and how many methods a component should carry — with the three costs a monolithic entity trait pays and how to split one. *Without it* you will misjudge what `self`/`Self` mean inside a provider, how the blanket impls route a call, and how coarse a component can get before its providers stop being reusable. Load it before writing any component or provider. +- **[references/wiring.md](references/wiring.md)** — `DelegateComponent`, every `delegate_components!` form (arrays, `new`, generic tables), `open` per-type dispatch, direct consumer-trait impls, `UseContext` and its circular-dependency trap, the legacy `UseDelegate` tables, and the other providers you see in tables (`WithProvider` and its `WithField`/`WithType`/`WithContext` aliases, `UseDefault`). *Without it* you will not know when a hand-written impl collides with the table, why `UseContext` overflows, or what a `WithField<…>` entry means. Load it before wiring any context. +- **[references/checking.md](references/checking.md)** — why wiring is lazy, how check traits and `CanUseComponent` force readable errors, every `check_components!` / `delegate_and_check_components!` option (`#[check_trait]`, `#[check_providers]`, `#[check_params]`, `#[skip_check]`), and a debugging playbook. *Without it* you cannot localize a broken wiring or read the error it throws. Load it whenever a wiring fails to compile. +- **[references/error-extraction.md](references/error-extraction.md)** — the **fallback for when `cargo-cgp` is not available, or leaves an error largely unrewritten** (see [Tooling](#tooling-use-cargo-cgp-for-readable-errors-and-expansions) first — `cargo-cgp`'s `[CGP-Exxx]` headline and root-cause tree already are the compact summary this sub-skill produces, so reach for the sub-skill only when the tool is absent or passes the error through). It covers how to reduce a long raw CGP compile error to a compact, root-cause-first summary, the hidden-versus-surfaced distinction that decides whether the root cause is even present in the output, how to confirm a suspected cause by grepping for one signature line, and how to delegate the reading to a sub-agent so a wall of generated-type errors does not consume your context. *Without it* you will read a cascade inline, chase a cause a hidden error does not contain, or hand back raw output instead of the few facts that matter. +- **[references/functions-and-getters.md](references/functions-and-getters.md)** — `HasField`/`#[derive(HasField)]`, `#[cgp_fn]`, `#[implicit]` and its access rules, `#[uses]`/`#[extend]`/`#[extend_where]`/`#[impl_generics]`, the getters `#[cgp_auto_getter]`/`#[cgp_getter]`/`UseField`/`WithField`, and `ChainGetters` for nested-context fields. *Without it* you will reach for a getter trait where an implicit argument is idiomatic, or misapply the `.clone()`/`.as_str()`/`&mut` field-access rules. Load it for the ergonomic day-to-day surface. +- **[references/abstract-types.md](references/abstract-types.md)** — `#[cgp_type]`, the built-in `HasType`/`TypeProvider`, wiring with `UseType` (and `UseDelegatedType` for table-chosen types), importing types with the `#[use_type]` attribute (distinct from the `UseType` provider), and the `WithType`/`WithDelegatedType` adapters. *Without it* you will confuse the provider and the attribute and write `Self::` paths by hand. Load it for any associated-type abstraction. +- **[references/higher-order-providers.md](references/higher-order-providers.md)** — providers parameterized by other providers, the stray `` on the inner bound, `#[use_provider]`, `UseContext` defaults, generic-parameter components, and cross-context dependencies. *Without it* you will call the inner provider as a method instead of `Provider::method(self)` and misplace the context slot. Load it before composing providers. +- **[references/error-handling.md](references/error-handling.md)** — `HasErrorType`, `CanRaiseError`/`CanWrapError`, the backend providers (`RaiseFrom`, `DebugError`, …), and — critically — which names come from the prelude versus `cgp::core::error` / `cgp::extra::error`. *Without it* you will fail to import the wiring keys and backends. Load it for any fallible CGP code. +- **[references/handlers.md](references/handlers.md)** — the `Computer`/`TryComputer`/`Producer`/`Handler`/runner family across its three axes, `#[cgp_computer]`/`#[cgp_producer]`/`#[cgp_auto_dispatch]`, the combinators (`PipeHandlers`, `Promote*`, dispatch matchers), monadic handlers, the `HasRuntime`/`HasRuntimeType` runtime components, and the `Send`-recovery pattern. *Without it* you will pick the wrong family member or miswire a pipeline. Load it for computation and I/O pipelines. +- **[references/extensible-data.md](references/extensible-data.md)** — the `CgpData`/`CgpRecord`/`CgpVariant` derives, the builder and extractor families (with the optional/defaulted-field extension), `Product!`/`Sum!` spines and their `AppendProduct`/`ConcatProduct`/`MapFields` algebra, structural casts (`CanUpcast`/`CanDowncast`/`CanBuildFrom`), and the builder/visitor patterns. *Without it* you will miss the compile-time exhaustiveness guarantees and the single-payload variant rule. Load it for generic struct/enum manipulation. +- **[references/namespaces.md](references/namespaces.md)** — `cgp_namespace!`, the `namespace`/`for … in` statements that join a namespace, the `#[prefix]`/`#[default_impl]` attributes that register into one, `RedirectLookup`, `Path!`, and the `DefaultNamespace` family. *Without it* you cannot read or write preset/inheritance wiring. Load it whenever wiring is grouped or inherited. +- **[references/type-level-primitives.md](references/type-level-primitives.md)** — `Symbol!`/`Chars`, `Product!`/`Cons`/`Nil`, `Sum!`/`Either`/`Void`, `Index`, `Field`, `Path!`/`PathCons`, `Life`, `MRef`, and the `StaticFormat` recovery traits. *Without it* you cannot decode the long nested types in error messages and expansions. Load it as the decoder ring. +- **[references/modularity-hierarchy.md](references/modularity-hierarchy.md)** — the five-level spectrum from a plain blanket trait to per-provider wiring, and which coherence rule each level escapes. *Without it* you will reach for more CGP machinery than a problem needs. Load it when deciding *how much* CGP to apply. + +### Exhaustive online reference + +For the exact macro expansion of any construct, every accepted syntax form, corner cases, or the +implementing source, consult the online knowledge base at +**https://github.com/contextgeneric/cgp-knowledge-base** — CGP's own section is +[`cgp/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp), whose `reference/`, +`concepts/`, `guides/`, and `errors/` directories are the authoritative, exhaustive record, and the +worked [`examples/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/examples) sit at +the base's top level beside it. The base also documents `cargo-cgp`, under +[`cargo-cgp/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cargo-cgp). Fetch the +relevant page when a detail is not covered here; do not assume a local copy exists, since this skill +is deployed on its own. + +--- + +## Instructions for explaining CGP to users + +Assume by default that the user has only basic Rust experience and is new to CGP, but do not +over-explain: when code merely uses CGP concepts, write or modify it without lecturing, and add +explanation only when asked. When you do explain, assume unfamiliarity with advanced Rust (generics, +traits, blanket impls, coherence) and with functional/type-level programming — describe type-level +tables, lists, and strings through familiar analogies such as a map or a lookup table, and expand on +advanced Rust as needed. Keep the simplified picture front and center: present wiring as choosing a +table entry, and keep `IsProviderFor`, `DelegateComponent`, and generated blanket impls out of the +explanation unless the user is asking specifically about the internals. One caveat when you reach +for an analogy: the "table lookup" is resolved at compile time and compiles down to direct static +calls, so if you use a runtime-flavored analogy like a vtable, say explicitly that — unlike a real +vtable — CGP's resolution is static and zero-cost, with no runtime table or dynamic dispatch. Never +leave a reader thinking CGP wiring has runtime lookup overhead. + +**Never leave a reader thinking a CGP trait is limited to one item, either.** Because single-decision +components dominate idiomatic CGP, an explanation built only from one-method traits reads as a restriction +the macros impose, and a reader who believes their traits are being capped pushes back on the whole +paradigm rather than on the guidance. So say plainly, whenever the subject comes up, that a component trait +is an ordinary trait taking as many methods, associated types, and consts as any other — CGP's own +`CanCompute` and `CanHandle` carry an associated `Output` beside their method — and present the grouping +guidance the way [components](references/components.md) frames it: a trade-off about how much reuse a +provider can collect, decided by the author, never a rule about item counts. + +When asked to explain a specific piece of code, look up the definitions it depends on before +answering. To explain a `delegate_components!` entry, find the consumer and provider traits behind +the component key and the body of the provider it maps to. To explain a provider, read its own +definition and the definitions of every capability in its `where` clause. To explain how a context +implements something, follow its wiring to see which providers are chosen and trace a method call +through them — for instance, if `NameGetterComponent` is wired to `UseField`, +then a `self.name()` call inside another provider returns the context's `first_name` field. diff --git a/docs/ai/skills/references/abstract-types.md b/docs/ai/skills/references/abstract-types.md deleted file mode 120000 index 1dcc0850..00000000 --- a/docs/ai/skills/references/abstract-types.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/abstract-types.md \ No newline at end of file diff --git a/docs/ai/skills/references/abstract-types.md b/docs/ai/skills/references/abstract-types.md new file mode 100644 index 00000000..906492b8 --- /dev/null +++ b/docs/ai/skills/references/abstract-types.md @@ -0,0 +1,167 @@ +# Abstract types + +An abstract type is a CGP trait carrying a single associated type that generic code names as `Self::Foo` without committing to a concrete type, leaving the concrete choice to wiring so it can differ from one context to another. + +## The idea + +An abstract type lets generic code name a type it does not fix. Instead of hard-coding `f64` or `String`, a trait declares one associated type — `trait HasNameType { type Name; }` — and code written against it refers to `Self::Name`, leaving the actual type open. The trait is the abstraction; the associated type is the slot a context fills in. This is the type-level analogue of an impl-side dependency: just as a getter lets a context supply a *value* a provider needs, an abstract-type trait lets a context supply a *type* a provider builds on. + +The payoff is the same one CGP gives for behavior. A provider written in terms of `Self::Name` works unchanged whether a context chooses `String`, `&'static str`, or a custom name type, and two contexts can make different choices from the same generic code. Under the hood an abstract type is nothing more than an ordinary Rust trait with one associated type — generic functions constrain `Context: HasNameType` and use `Context::Name` exactly as they would any associated type. The CGP machinery only makes declaring and wiring these traits cheap. + +## Direct implementation: it's just a trait + +Because an abstract type is a vanilla associated-type trait, the most transparent way to bind it is to implement it directly on a concrete context. Given the trait, a context names the concrete type in a plain `impl`: + +```rust +#[cgp_type] +pub trait HasNameType { + type Name; +} + +pub struct Person; + +impl HasNameType for Person { + type Name = String; +} +``` + +This makes `Person::Name` resolve to `String`, and any generic code constrained on `HasNameType` sees that choice. The direct form is the right mental model for newcomers — there is no hidden machinery, just an associated type pinned to a concrete one — and it is barely longer than the wired form shown below. The rest of this reference explains the `#[cgp_type]` macro and the wiring conveniences that make the choice swappable through a delegation table instead. + +## Making a type swappable with `#[cgp_type]` + +The `#[cgp_type]` macro turns an abstract-type trait into a full component, so the concrete type can be chosen through wiring rather than a hand-written impl. It is the abstract-type specialization of `#[cgp_component]`: applied to a trait with exactly one associated type and no methods, it produces everything `#[cgp_component]` would — the consumer trait, the provider trait, the blanket impls, the `…Component` marker — but each impl forwards the *associated type* rather than a method. + +```rust +#[cgp_type] +pub trait HasNameType { + type Name; +} +``` + +The default provider name is keyed off the *associated type* name, not the trait name, with a `TypeProvider` suffix. So `type Name;` yields the provider `NameTypeProvider` and the component marker `NameTypeProviderComponent`. A bound on the associated type — `type Name: Clone;` — is carried everywhere the type appears in the expansion and enforced on whatever concrete type a context chooses. You can override the derived provider name by passing one, exactly as with `#[cgp_component]`: `#[cgp_type(ProvideName)]`. + +The construct that distinguishes `#[cgp_type]` from a plain component is an extra blanket impl it generates for the `UseType` provider, described next, which is what lets a context pick a concrete type without writing a provider of its own. + +## Wiring a concrete type with `UseType` + +A context binds an abstract type to a concrete one by wiring its provider component to `UseType`. Because every abstract-type provider has the same trivial shape — "the associated type *is* this concrete type" — `#[cgp_type]` generates that shape once as a blanket impl of the provider trait for `UseType`, setting the associated type to the generic parameter. The context then names the concrete type directly in its delegation table: + +```rust +delegate_components! { + Person { + NameTypeProviderComponent: UseType, + } +} +``` + +Wiring `NameTypeProviderComponent` to `UseType` makes `Person` implement `HasNameType` with `Name = String`, with no bespoke provider, and any bound on the associated type is checked against `String` at the wiring site. `UseType` is a zero-sized marker struct carrying no runtime value — it exists only to be named in a delegation table, never constructed. This is the type-level mirror of how `UseField` supplies a value-level getter (see [functions and getters](functions-and-getters.md)). + +The blanket impl that `#[cgp_type]` generates for the example above is: + +```rust +impl NameTypeProvider<__Context__> for UseType { + type Name = Name; +} +``` + +This says `UseType` is a provider that supplies `T` as the abstract type, for any context. If the associated type carried a bound, that bound would be copied into the impl's `where` clause so the concrete type must satisfy it. + +A word of caution on the name: the `UseType` *provider struct* shown here is a different construct from the `#[use_type]` *attribute* covered below. The provider wires a concrete type *into* a context; the attribute imports an abstract type *into* a definition and rewrites bare mentions of it. They share a name because both center on abstract types, but they live in different places and do different jobs. + +## The built-in `HasType` / `TypeProvider` component + +Underneath every named abstract type sits CGP's single built-in abstract-type component, `HasType`. It is tag-indexed: `HasType` is the consumer trait, `TypeProvider` is its provider trait, and a context can carry many distinct abstract types — one per `Tag` — resolving each through wiring. + +```rust +#[cgp_component(TypeProvider)] +pub trait HasType { + type Type; +} +``` + +Every `#[cgp_type]` component you define is wired on top of this substrate: the macro generates an internal `WithProvider` impl that adapts a `TypeProvider` into the named component, so the same `UseType` marker satisfies both the built-in `HasType` and any user-defined abstract type at once. In practice you rarely name `HasType` directly — you define a readable `HasNameType` with `#[cgp_type]` and get `Self::Name` and its own provider, all resolving down to this `HasType` machinery. The takeaway is that `UseType` is itself a `TypeProvider`, which is why one marker serves every abstract type. When you do want to name that adapter explicitly, its alias is `WithType` (the `WithProvider` family from [wiring](wiring.md)). + +## Choosing the concrete type from a table with `UseDelegatedType` + +`UseDelegatedType` is the type-level analogue of the `UseDelegate` dispatcher: where `UseType` binds an abstract type to one fixed `T`, `UseDelegatedType` looks the concrete type up in an inner `DelegateComponent` table keyed by the type tag, so one provider can answer several abstract-type components at once or route each tag to a type chosen elsewhere. It reads an entry out of the same kind of table `UseDelegate` reads, but yields a *type* rather than a method — the abstract-type mirror of the per-value behavioral dispatch in [wiring](wiring.md). Its `WithProvider` alias is `WithDelegatedType`. Reach for it only when a bundle of related types must be decided together; for a single concrete type per component, `UseType` is simpler. + +## Abstract type as a getter return type + +When an abstract type's only role is to be the return type of a getter, you can declare it inline with `#[cgp_auto_getter]` rather than defining a separate `#[cgp_type]` trait. The getter trait carries the associated type locally, and the field's type is inferred from it: + +```rust +#[cgp_auto_getter] +pub trait HasName { + type Name; + + fn name(&self) -> &Self::Name; +} +``` + +A context implementing this through its field wiring supplies both the concrete `Name` and the value. This keeps a one-off abstract type local to the getter that uses it instead of promoting it to a shared, wired component. See [functions and getters](functions-and-getters.md) for how `#[cgp_auto_getter]` derives the getter from a field. + +## Importing an abstract type with `#[use_type]` + +The strongly recommended way to *refer to* an abstract type from another definition is the `#[use_type]` attribute. A provider or component often needs a type that lives on a different trait — a `Scalar` from `HasScalarType`, an `Error` from `HasErrorType` — and Rust requires every mention to be written in fully-qualified form, `::Scalar`, because a bare `Scalar` is not a type the compiler knows. Writing that prefix on every occurrence is verbose and easy to get wrong. + +`#[use_type]` lets you write the bare identifier everywhere and have the macro expand it. You declare the import once alongside `#[cgp_fn]`, `#[cgp_impl]`, or `#[cgp_component]` as `#[use_type(Trait.AssocType)]` — a `.` (not `::`) separates the trait from the associated type — and the macro rewrites each standalone `Scalar` into `::Scalar` while also adding `HasScalarType` as a supertrait (for `#[cgp_component]`) or a `where`-clause bound (for `#[cgp_impl]` and `#[cgp_fn]`). The `.` separator keeps the trait unambiguous even when it is a full path or carries generic arguments (`errors::HasErrorType.Error`, `HasFooType.Foo`). Consider a `rectangle_area` function that multiplies two implicit fields: + +```rust +pub trait HasScalarType { + type Scalar: Clone + Mul; +} + +#[cgp_fn] +#[use_type(HasScalarType.Scalar)] +fn rectangle_area( + &self, + #[implicit] width: Scalar, + #[implicit] height: Scalar, +) -> Scalar { + width * height +} +``` + +The macro rewrites every bare `Scalar` to the qualified path and adds the supertrait/bound, so the effective trait and impl read: + +```rust +pub trait RectangleArea: HasScalarType { + fn rectangle_area(&self) -> ::Scalar; +} + +impl RectangleArea for Context +where + Self: HasField::Scalar> + + HasField::Scalar>, + Self: HasScalarType, +{ + fn rectangle_area(&self) -> ::Scalar { + let width: ::Scalar = + self.get_field(PhantomData::).clone(); + let height: ::Scalar = + self.get_field(PhantomData::).clone(); + width * height + } +} +``` + +The substitution is purely textual at the type level — it matches single-segment, argument-free type paths whose identifier equals the imported name — so a bare `Scalar` in the return type, an implicit-argument annotation, or a `let` binding inside the body is all rewritten the same way. Beyond saving keystrokes, the always-qualified rewrite removes the ambiguity the bare form cannot express, which is why this is the default way to import abstract types in all three macros. + +The attribute has a few richer forms worth knowing. A trailing `in Context` clause changes the rewrite target from `Self` to a named type, which imports a *foreign* abstract type from a generic parameter: `#[use_type(HasScalarType.Scalar in Types)]` rewrites `Scalar` to `::Scalar` and adds `Types: HasScalarType` as a `where` bound rather than a supertrait. That bound lands on the generated impl *and*, on `#[cgp_fn]`/`#[cgp_component]`, on the generated trait itself, so a plain unbounded `` parameter is enough — you do not restate `Types: HasScalarType` by hand. The `in Context` clause may also point at another abstract type imported in the same attribute, chaining through several hops (`HasTypes.Types, HasScalarType.Scalar in Types` yields the two-hop `<::Types as HasScalarType>::Scalar`), and so may a *generic argument of the imported trait*, so an alias can parameterize the trait it is imported from (`HasDbType.Db, HasPoolType.Pool` projects against `HasPoolType<::Db>`). Either way the order you write the imports in does not matter, and two imports may share one context; the one arrangement rejected is a **cycle**, where the contexts or trait arguments resolve through each other (`HasA.A in B, HasB.B in A`, or the degenerate `HasAType.A in A`), which is a compile error naming the cycle rather than a confusing unresolved-name error later. A braced list imports several types from one trait, each optionally renamed with `as` or constrained with `=`: `#[use_type(HasScalarType.{Scalar = f64})]` both imports `Scalar` and emits `Self: HasScalarType`, pinning it (and when the trait is generic the pin joins its existing arguments, so `HasFooType.{Foo = u32}` emits `Self: HasFooType`). This equality form is the modern replacement for a hand-written `where Self: HasScalarType` clause on a `#[cgp_impl]` or `#[cgp_fn]` — prefer moving such a pin into the attribute rather than leaving it as an explicit `where`. The right-hand side of `=` is substituted too, so an imported alias is grounded wherever it appears in it: naming another alias outright *unifies* two abstract types (`#[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})]` emits `Self: HasHashedPasswordType::Password>`), while an alias nested inside the type is grounded in place (`#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits `Self: HasTransactionType::Db>>`). To import types from *several* traits, separate the trait paths with commas inside one attribute — `#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasErrorType.Error)]` — and prefer that combined form over stacking one `#[use_type]` attribute per trait, since it reads as a single import list; stacked attributes behave identically but are for when a real reason calls for it. The `= ...` equality form is rejected on `#[cgp_component]`, since a trait definition cannot carry the impl-side equality constraint it produces; it belongs on `#[cgp_fn]` and `#[cgp_impl]`. Two imports may not resolve to the same identifier or alias — across specs or within one braced list — since the substitution could then match only one; a collision is a compile error on every host macro, as is the import cycle described above. + +## Sharing one type across contexts + +The value of an abstract type compounds when several pieces of generic code share it. Because the type lives on a trait the context implements, every provider and trait that needs a `Scalar` refers to the *same* `Self::Scalar`, so a context fixes the choice once and all of them agree. This is sharpest when a trait's main subject is a generic parameter rather than the context itself — a `CanCalculateAreaOfShape` implemented by one context for many shapes. The shapes carry no scalar type of their own; the shared context supplies a single `Scalar` through its `HasScalarType` wiring, and switching `UseType` to `UseType` changes the scalar for every shape at once. The same arrangement is how CGP shares one error type across an application: `HasErrorType` is itself defined with `#[cgp_type]`, and every fallible provider refers to the same `Self::Error` (see [error handling](error-handling.md)). + +## Related references + +Abstract types are wired into a context with [components](components.md) and consumed by [functions and getters](functions-and-getters.md). `UseType` is one of the higher-order providers described in [higher-order providers](higher-order-providers.md), and the shared error type pattern is covered in [error handling](error-handling.md). + +## Further reference + +Online docs: +[`#[cgp_type]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_type.md), +[`HasType`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/has_type.md), +[`UseType` provider](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_type.md), +[`#[use_type]` +attribute](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/use_type.md). diff --git a/docs/ai/skills/references/checking.md b/docs/ai/skills/references/checking.md deleted file mode 120000 index ba2fb78e..00000000 --- a/docs/ai/skills/references/checking.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/checking.md \ No newline at end of file diff --git a/docs/ai/skills/references/checking.md b/docs/ai/skills/references/checking.md new file mode 100644 index 00000000..0387657e --- /dev/null +++ b/docs/ai/skills/references/checking.md @@ -0,0 +1,209 @@ +# Checking wiring + +How to verify at compile time that a context's [wiring](wiring.md) is complete, using check traits and the `check_components!` / `delegate_and_check_components!` macros to turn confusing use-site errors into precise ones at the wiring site. + +## Why wiring is lazy + +CGP wiring is lazy: recording that a context delegates a [component](components.md) to a provider does not verify that the provider can actually satisfy that component for that context. When you write a `DelegateComponent` entry mapping `GreeterComponent` to `GreetHello`, the type system stores "this key points to this provider" as an associated type and asks no further questions. Whether the provider's own `where` bounds — its impl-side dependencies — hold for this particular context is simply not checked at the point of delegation. The check is deferred until something downstream actually *uses* the component, which is the first moment the compiler is forced to evaluate the provider's bounds against the concrete context. + +This laziness is what makes CGP composable, but it has a cost: a context can look fully wired and still be broken. Every entry compiles, the struct compiles, the whole module compiles — and then the first call to a consumer trait method fails, often far from the wiring that caused it. A missing field, a missing abstract type, an unsatisfied transitive bound three providers deep: none of these surface where the mistake was made. + +Consider a greeter provider that depends on a `name` field, wired onto a context whose field is misnamed: + +```rust +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, // mismatch: GreetHello needs `name` +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} +``` + +This whole block compiles. `GreetHello` needs `HasName`, `Person` has no `name` field, and nothing complains — until some distant `person.greet()` call fails to typecheck. + +## Why the resulting errors are poor + +When a lazily-wired context is finally used and a dependency is missing, the compiler reports the outermost unmet conclusion and hides the reasoning behind it. Asking the plain question "does `Person` implement `CanGreet`?" makes Rust answer with the last link in the chain — typically that `GreetHello` does not implement the provider trait for `Person` — without explaining *why* the provider's bounds were not met. The provider blanket impl is a competing candidate that suppresses the detailed diagnostic. The root cause, a single missing `name` getter, is buried beneath a conclusion that points at the provider rather than at the gap, and the surface error spells field names in their verbose type-level form (`Symbol<…, Chars<…>>`), making even that hard to read. + +The fix is to force the compiler to evaluate the provider's bounds *and report them in detail*, at a location you control — the wiring site — rather than wherever the component happens to be used first. + +## How check traits force readable errors + +A check trait is a dummy trait whose supertrait is the requirement being asserted; implementing it for a context with an empty body compiles only if that requirement holds. The hand-written form is plain Rust: + +```rust +trait CanUsePerson: CanGreet {} +impl CanUsePerson for Person {} +``` + +The `impl` block has nothing to prove on its own, so it succeeds exactly when `Person: CanGreet` holds and fails otherwise. Placed next to the wiring, it converts a latent gap into an immediate compile error at a known line. But asserting the *consumer* trait directly is not enough: it reproduces the same vague error as before, naming the provider rather than the missing dependency. The remedy is to route the assertion through `CanUseComponent` instead. + +`CanUseComponent` is satisfied only when the context both delegates the component and the delegated provider satisfies `IsProviderFor` for that context. The crucial property is that `IsProviderFor` carries the provider's *real* `where` bounds — the same impl-side dependencies the provider needs to implement its provider trait. Routing a check through `CanUseComponent` therefore forces the compiler to evaluate those bounds and, because they are stated explicitly through the marker, to report the specific one that failed. A missing `name` field surfaces as an unsatisfied `HasName`/`HasField` bound pointing at the context, not as a bare "provider not implemented." The two bounds also distinguish the two ways wiring goes wrong: failing the `DelegateComponent` bound means the component was never wired (add the delegation), while failing the `IsProviderFor` bound means it was wired to a provider whose dependencies are unmet (supply the missing dependency). You rarely name `CanUseComponent` directly — its job is to be the bound the check macros emit. + +## Generating checks with `check_components!` + +Rather than spell out check traits by hand, `check_components!` generates them from a short table of components to verify. Given a context and a list of components, it emits a marker trait aliasing `CanUseComponent` and one empty impl per component: + +```rust +check_components! { + Person { + GreeterComponent, + } +} +``` + +The generated impl compiles only if `Person: CanUseComponent`, which drags in `GreetHello`'s `IsProviderFor` bounds and reports the first that fails — here, the missing `name` field, pinpointed at the wiring site instead of at a future `person.greet()`. A successful build *is* the passing assertion; these checks have no runtime existence. + +The check trait is named `__Check{Context}` by default — `__CheckPerson` here. When two `check_components!` tables in the same module would collide on that name, override it with `#[check_trait(Name)]` on the table: + +```rust +check_components! { + #[check_trait(CheckPersonGreeting)] + Person { + GreeterComponent, + } +} +``` + +A component with generic parameters cannot be checked bare, because the check must name concrete parameters to have anything to verify. List them after a colon: a single parameter bare, multiple parameters grouped into a tuple, mirroring how the provider trait groups them in its `IsProviderFor` `Params` slot. Given an area calculator generic over a shape: + +```rust +#[cgp_component(AreaOfShapeCalculator)] +pub trait CanCalculateAreaOfShape { + fn area(&self, shape: &Shape) -> f64; +} + +check_components! { + MyApp { + AreaOfShapeCalculatorComponent: Rectangle, // one parameter + TransformCalculatorComponent: (Rectangle, f64), // two, as a tuple + } +} +``` + +Array syntax on either side of the colon expands to the cartesian product, so a set of components can be checked against a set of parameters in one line. A bracketed value checks one component against several parameter sets; a bracketed key checks several components against one set; bracketing both checks every combination: + +```rust +check_components! { + MyApp { + AreaOfShapeCalculatorComponent: [Rectangle, Circle], // one component, two shapes + } +} +``` + +This verifies `MyApp: CanCalculateAreaOfShape` and `MyApp: CanCalculateAreaOfShape` in one entry. + +## Checking providers directly with `#[check_providers(...)]` + +For [higher-order providers](higher-order-providers.md), checking the context as a whole tells you a layer is broken but not which one. The `#[check_providers(...)]` attribute changes what is checked: instead of asserting `CanUseComponent` on the context, it asserts `IsProviderFor` directly on each named provider, so each layer is verified on its own impl: + +```rust +check_components! { + #[check_trait(CheckScaledRectangleProviders)] + #[check_providers( + RectangleAreaCalculator, + ScaledAreaCalculator, + )] + ScaledRectangle { + AreaCalculatorComponent, + } +} +``` + +Because each provider is checked independently, a dependency missing only from the outer `ScaledAreaCalculator` wrapper errors on the wrapper's line alone, while one missing from the inner `RectangleAreaCalculator` errors on both lines — which narrows down where in a nested stack the gap lives. + +## Wiring and checking together with `delegate_and_check_components!` + +For basic wiring, and especially while getting started with CGP, `delegate_and_check_components!` removes the bookkeeping of keeping a standalone `check_components!` block in sync with the delegations. It fuses the two — wiring each entry exactly as `delegate_components!` would and deriving a check for each delegated key — so a simple context is proven the moment it is written and a newcomer cannot forget the check. (Its reach stops at that basic form, which is why advanced codebases keep the two macros separate; see the recommendation at the end of this section.) + +```rust +#[derive(HasField)] +pub struct MyContext { + pub name: String, +} + +delegate_and_check_components! { + MyContext { + NameTypeProviderComponent: UseType, + NameGetterComponent: UseField, + } +} +``` + +If `MyContext` were missing the `name` field, the derived check on `NameGetterComponent` would fail to compile and report the missing bound, rather than letting the gap slip through to a later use. + +Its check trait is named `__CanUse{Context}` by default — deliberately distinct from `check_components!`'s `__Check{Context}` — so one of each macro can appear in the same module without a clash. As with `check_components!`, `#[check_trait(Name)]` overrides the derived name. + +Because the delegation half is generic over a component's parameters but the check half needs concrete ones, an entry for a component with generic parameters *requires* a `#[check_params(...)]` attribute supplying them, using the same single-versus-tuple convention: + +```rust +delegate_and_check_components! { + MyApp { + #[check_params(Rectangle, Circle)] + AreaOfShapeCalculatorComponent: + UseDelegate, + } +} +``` + +The nested `UseDelegate` table shown here is the legacy form of per-type dispatch; the modern equivalent opens the component with the `open` statement of `delegate_components!` (see [wiring](wiring.md)). The `#[check_params(...)]` requirement is the same either way — whichever wiring form supplies the dispatch entries, the check half still needs the concrete parameters spelled out. + +To wire an entry without checking it — for instance a higher-order delegation you verify separately with a `#[check_providers(...)]` block — mark it `#[skip_check]`. The two attributes are mutually exclusive on a given entry: + +```rust +delegate_and_check_components! { + ScaledRectangle { + AreaCalculatorComponent: + ScaledAreaCalculator, + + #[skip_check] + TransformCalculatorComponent: + ComplexTransform, // checked in a dedicated check_components! block + } +} +``` + +Where `delegate_and_check_components!` fits is narrower than its convenience suggests: it is the beginner-friendly, basic-wiring form, not the default for advanced code. Its value is that a newcomer cannot forget to write a separate `check_components!` and then be tripped by the confusing lazy-wiring errors that follow; it derives a check for each entry keyed on a component *name* — the plain `Component: Provider` form and its `->` sibling — so getting-started code is checked by construction. But the derivation only understands a key that names a component. The advanced forms still *wire*, and are left **silently unchecked**: generic-parameter dispatch through the `open` statement and `@`-path keys, `=>` redirects, and namespace joins all produce delegation impls and no check entry, with nothing warning that a table is only partly verified. Per-layer higher-order checks are not expressible here at all. Each of these needs concrete parameters or providers the fused derivation cannot infer from a delegation alone. So in larger, more advanced codebases, keep `delegate_components!` and `check_components!` separate: the standalone `check_components!` block is where `#[check_providers(...)]`, concrete parameters for generic keys, and checks over opened or namespaced wiring all live. The rule that does not bend is that a context's wiring is checked *somehow*; `delegate_and_check_components!` is simply the training-wheels way to guarantee that for simple contexts, and the two separate macros are the way that scales. + +There is also a case where `delegate_and_check_components!` is not merely unnecessary but outright *wrong*: an **aggregate provider**. A `delegate_components!` table need not describe a context at all — a `new SomeComponents { … }` table (see [wiring](wiring.md)) defines a zero-sized provider that dispatches each component to a sub-provider, which other contexts then delegate to as a reusable bundle. Such an aggregate provider is always wired with plain `delegate_components!`, never the checked variant, because the check asserts that the target can *use* each component as a context — `Target: CanUseComponent` — which is a role the bundle never plays, so the answer is uninformative whichever way it goes. **Which way it goes depends on the bundled provider, and this is worth knowing, because one of the two failures is silent.** A leaf provider with no impl-side dependencies implements its provider trait for *every* context, the bundle included, so the assertion holds vacuously and the check passes while proving nothing about the bundle. A leaf provider that needs a field or an abstract type makes the assertion fail and blames the bundle: a bundled `RectangleArea` reading a `width` field reports that `GeometryComponents: CanUseComponent` is unsatisfied because `GeometryComponents` does not implement `HasField`, which names neither the real mistake nor the real context. An aggregate provider is verified indirectly instead, when a real context that delegates to it is checked, or directly with a `#[check_providers(...)]` block that names the aggregate and asserts `IsProviderFor` on it for a real context — the provider-side check, not the context-side one. + +## Debugging an unsatisfied check + +When a check fails, the error names the unmet bound — read it as a thread to pull rather than a final verdict. The reported bound is the first impl-side dependency the compiler could not satisfy; walk the transitive dependencies from there. If `GreetHello` requires `HasName`, the error names `HasName` on the context, and the fix is to supply that field or wire the getter component. A bound several providers deep names the innermost requirement, so trace from the failing component through each provider it delegates into. + +When a large `delegate_and_check_components!` table reports a tangle of errors, narrow it down by adding the suspect component to a separate `check_components!` block on its own. Checking one component in isolation, with its parameters spelled out, strips away the noise from the other entries and forces the compiler to report just that component's unmet dependency. For a higher-order stack, switch to `#[check_providers(...)]` to see which layer fails on its own line. + +Finally, remember that not every unsatisfied bound is a CGP component. A check trait only verifies wiring routed through `CanUseComponent` — it cannot prove a plain trait or a blanket-impl bound that a provider also depends on. If the error names a trait that has no `…Component` marker and no entry in any delegation table, no amount of checking will surface it through the wiring; that bound must be satisfied by ordinary Rust means (an `impl`, a derive, a `where` clause on the context), and the check will pass only once it is. + +## Further reference + +Online docs: +[`check_components.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/check_components.md), +[`delegate_and_check_components.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/delegate_and_check_components.md), +and the conceptual overview +[`concepts/check-traits.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/check-traits.md). diff --git a/docs/ai/skills/references/components.md b/docs/ai/skills/references/components.md deleted file mode 120000 index 1be8ff5e..00000000 --- a/docs/ai/skills/references/components.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/components.md \ No newline at end of file diff --git a/docs/ai/skills/references/components.md b/docs/ai/skills/references/components.md new file mode 100644 index 00000000..12f016be --- /dev/null +++ b/docs/ai/skills/references/components.md @@ -0,0 +1,257 @@ +# Components + +A CGP **component** is the bundle that `#[cgp_component]` generates from one trait so that *using* a capability and *implementing* it become separate, swappable things — this is the central reference; read it first. + +## What a component is + +A component is a single trait definition compiled into a small machine: a **consumer trait** that callers invoke, a **provider trait** that implementations target, a `…Component` marker key, and the blanket impls that connect them. An ordinary Rust trait conflates using a capability with implementing it — the type you call `.area()` on is the same type that supplies the `area` body — and Rust's coherence rules then allow only one implementation per type. A component breaks that conflation, which is what lets many independent implementations of the same capability coexist and lets you implement a capability for a type you do not own. + +The split is produced by `#[cgp_component]`, applied to an ordinary trait. Throughout this file the running examples are the greeting component (`CanGreet` / `Greeter` / `GreetHello`, on a `Person`) and the area component (`CanCalculateArea` / `AreaCalculator` / `RectangleArea`, on a `Rectangle`). Assume `use cgp::prelude::*;` in every snippet; the CGP version is v0.8.0. + +## What `#[cgp_component(Greeter)]` generates + +Applying the macro to a consumer trait produces five items: the consumer trait, the provider trait, two blanket impls, and the marker struct. Start from the trait, naming the provider trait in the attribute argument: + +```rust +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} +``` + +The first item is the **consumer trait**, emitted unchanged. This is the self-style trait callers use (`CanDoX`), so a caller writes `person.greet()` exactly as with any trait: + +```rust +pub trait CanGreet { + fn greet(&self); +} +``` + +The second item is the **provider trait**, the same interface with `Self` moved out into an explicit leading `Context` type parameter and every `self`/`Self` rewritten to `context`/`Context`. It is named in noun form (`SomethingDoer`, or `…Provider` when no noun fits), and it carries an `IsProviderFor` supertrait that captures the component, the context, and a `Params` tuple of any extra type parameters — `()` when there are none: + +```rust +pub trait Greeter: + IsProviderFor +{ + fn greet(context: &Context); +} +``` + +A provider trait is implemented not for the context but for a dedicated zero-sized **provider** +struct — a type-level marker that is never instantiated and carries no runtime value. Because a +provider implements `Greeter` for *its own* struct over a generic `Context`, the orphan and +overlap rules never bite, so `GreetHello`, `GreetGoodbye`, and any number of further providers for +the same component can all exist at once. See +[bypassing coherence](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/coherence.md) +(online) for why moving `Self` to a parameter is what sidesteps the rules, and +[modularity hierarchy](modularity-hierarchy.md) for the spectrum of how far to take the split. + +## How the two traits connect + +Two generated blanket impls bridge the consumer and provider sides, and together they make `person.greet()` resolve to a chosen provider without the caller naming it. Read them as the wiring machinery; you never write them. + +The first is the **consumer blanket impl**, which says that any context implementing the provider trait *for itself* automatically gets the consumer trait. It forwards `context.greet()` to `Context::greet(self)`: + +```rust +impl CanGreet for Context +where + Context: Greeter, +{ + fn greet(&self) { + Context::greet(self) + } +} +``` + +The second is the **provider blanket impl**, which lets any provider that delegates this component inherit the provider trait from whatever it delegates to. The delegation is a type-level table lookup through `DelegateComponent`, keyed on the `GreeterComponent` marker: + +```rust +impl Greeter for Provider +where + Provider: DelegateComponent + + IsProviderFor, + Provider::Delegate: Greeter, +{ + fn greet(context: &Context) { + Provider::Delegate::greet(context) + } +} +``` + +The fifth item is the **component marker**, a zero-sized key into those delegation tables: + +```rust +pub struct GreeterComponent; +``` + +These two examples use readable names for clarity; the emitted code uses reserved identifiers — `__Context__` for the context parameter (overridable) and `__Provider__` for the provider parameter — chosen so they never clash with a user's own type names. + +## Wiring is the table lookup that ties it all together + +**Wiring** is the step that supplies the delegation the provider blanket impl reads, by making a context into a type-level table whose entry for each component names the chosen provider. With the greeting component wired, the chain resolves end to end: `person.greet()` goes through the consumer impl to `Person` implementing the provider trait for itself, which goes through the provider impl to the table entry, landing on the selected provider's `greet`. Swapping the table entry is the only change needed to swap behavior; no caller is touched. + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} +``` + +The full table grammar — including per-value dispatch and presets — lives in [wiring](wiring.md). This file shows only the single-entry form needed to make the resolution concrete. + +## Why `IsProviderFor` exists + +`IsProviderFor` is an empty marker trait that rides along on every provider trait as a supertrait, and its only job is to make a missing dependency produce a readable error. A provider lists what it needs from the context in a `where` clause; when that clause is unmet, the bare question "does this provider implement the provider trait?" yields only "trait not implemented", because the provider blanket impl is also a candidate and Rust suppresses its detailed reasoning whenever more than one impl could apply. + +`IsProviderFor` is the second, independent path that un-hides the real reason. The macros implement it for a provider under *exactly the same* `where` bounds as the provider trait, and because that impl is the only candidate (no competing blanket), Rust commits to it and prints the precise unsatisfied constraint. The practical translation a reader needs: an `IsProviderFor` not implemented error means the provider trait is not implemented, and the named bound is the missing dependency. The trait is generated and consumed entirely by the macros — you observe it in errors, you never write it. + +```rust +#[diagnostic::on_unimplemented( + note = "You need to add `#[cgp_provider({Component})]` on the impl block for CGP provider traits" +)] +pub trait IsProviderFor {} +``` + +## Writing providers + +A provider can be written at three levels of sugar over the same machinery, and `#[cgp_impl]` is the one to reach for. The lower forms exist for when the native provider-trait shape is wanted explicitly, and they are what `#[cgp_impl]` desugars to. + +The lowest form is `#[cgp_provider]`, applied to a provider-trait impl written directly on a provider struct. It passes the impl through unchanged and auto-generates the matching `IsProviderFor` impl from the same `where` clause, so the dependency set can never drift. The provider struct must already exist: + +```rust +pub struct RectangleArea; + +#[cgp_provider] +impl AreaCalculator for RectangleArea +where + Context: HasDimensions, +{ + fn area(context: &Context) -> f64 { + context.width() * context.height() + } +} +``` + +That expands to the impl above plus the empty marker impl carrying the same bound, which is what surfaces a missing `HasDimensions` as a named error: + +```rust +impl IsProviderFor for RectangleArea +where + Context: HasDimensions, +{} +``` + +The optional attribute argument overrides the component type, defaulting otherwise to the provider trait's name plus a `Component` suffix; pass it explicitly only when the trait name does not follow that convention. + +The middle form is `#[cgp_new_provider]`, identical to `#[cgp_provider]` but it also declares the provider struct, folding `pub struct RectangleArea;` into the same block. Use it when introducing a fresh provider so you need not write the struct separately; a generic provider yields a struct with a `PhantomData` field over its parameters. + +The preferred form is `#[cgp_impl]`, which lets you write the provider in **consumer-style syntax** — keeping `self`, `Self`, and the consumer trait's method signatures — and mechanically rewrites it into the provider-trait shape. The provider name moves into the attribute argument instead of the `Self` position; a leading `new` keyword declares the struct; and you may omit `for Context` entirely, letting the macro insert the context parameter for you: + +```rust +#[cgp_impl(new RectangleArea)] +impl AreaCalculator +where + Self: HasDimensions, +{ + fn area(&self) -> f64 { + self.width() * self.height() + } +} +``` + +The one rule this convenience must not let you forget: inside a `#[cgp_impl]` block, `self` and `Self` mean the **context**, never the provider struct. The provider has no runtime value, so the macro rewrites every `self` to the context value and every `Self` to the context type — those are the only things that exist when the method runs. + +`#[cgp_impl]` desugars to `#[cgp_provider]` (or `#[cgp_new_provider]` when `new` is given). The block above is equivalent to writing the context out by hand and lowering it: + +```rust +#[cgp_new_provider] +impl<__Context__> AreaCalculator<__Context__> for RectangleArea +where + __Context__: HasDimensions, +{ + fn area(__context__: &__Context__) -> f64 { + __context__.width() * __context__.height() + } +} +``` + +The receiver `&self` became `__context__: &__Context__` — the receiver identifier is the snake-cased context name wrapped in double underscores — and `Self` in the `where` clause became the context type. When you write `for Context` explicitly, that name is used instead of `__Context__`, which is worth doing when you need to bound or refer to the context readably. + +## Impl-side dependencies + +A provider states what it needs from the context as bounds in its `where` clause, and those bounds — +**impl-side dependencies** — are constraints the consumer trait never exposes. `CanCalculateArea` +declares only `area`, while `RectangleArea` requires `Context: HasDimensions`; a caller bounding on +`CanCalculateArea` never sees `HasDimensions`, so the requirement stays one level down and does not +cascade through transitive callers. This is dependency injection through the `where` clause: any +context satisfying the bound gains the capability automatically, and the wiring satisfies each bound +by resolving it through the same context. See +[impl-side dependencies](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/impl-side-dependencies.md) +(online) for the full treatment, and [functions and getters](functions-and-getters.md) for the +value-injection forms (`#[implicit]` arguments and getters) that read fields off the context through +the same mechanism. + +## Which items belong in one component + +**A component trait may declare as many items as any Rust trait — the question is not how many, but how +many independent *choices* they represent.** Everything in one component is answered by one provider, so +group the items a single provider choice decides together and separate the ones different choices decide. +Most application capabilities are one decision and therefore one method, which is why single-method +components dominate; the count follows from the principle rather than being a limit. + +Two groupings of several items are right rather than merely allowed. **A method plus the associated type it +produces**: a provider that answers *how* also answers *what comes back*, which is why CGP's own +`CanCompute`, `CanHandle`, and `CanProduce` each declare `type Output` beside their method, and why a +`CanQueryDatabase` with `type Row` and `query` is good design — splitting `Row` out would let a context +pair the Postgres querier with the SQLite row type. **A getter component grouping several field reads**: a +getter is answered by its own method name rather than by a strategy, so one `UseFields` provider satisfies +every method at once, and there is nothing to split. The trade-off there is that `UseField` and +`WithProvider` are emitted only for a single-method getter trait, so a getter wired to a differently named +field needs its own component. + +Grouping items that answer to *different* choices costs three things, and the cost rises with how unrelated +they are rather than with the count. Every provider carries the **union of its methods' dependencies**, so +a capability one method needs is imposed on all of them and on every context wiring that provider. A +[higher-order provider](higher-order-providers.md) must **implement every item**, forwarding the ones it +has no opinion about — a single-decision component wraps in four lines, while a wrapper over an entity +trait is mostly passthrough that grows with every method added. And a context or provider needing part of +the surface must **still answer all of it**, which in practice means placeholder associated types and +`unimplemented!()` bodies, most often in mock contexts written for tests. + +Two checks catch a component that has grown past one decision. A consumer trait named after a noun rather +than a verb usually holds several. And if no provider for the trait could ever be reused *whole* by a +second context, the machinery is not paying for itself — implement the trait directly on the concrete +context instead, per the section below. To break one up, split along the axis on which the contexts you +actually want differ: the methods whose dependencies are shared across those contexts become components +with reusable providers, and the ones that must differ get a direct impl on each context. The full +procedure and its costs are in +[sizing a component](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/guides/sizing-a-component.md) +(online). + +## A consumer trait is still an ordinary trait + +A consumer trait can also be implemented directly on a context, exactly like a vanilla Rust trait, when code reuse across providers is not the goal. The consumer/provider split is a superset of ordinary traits, not a replacement: the provider machinery is what you opt into when a capability needs more than one implementation, and skipping it costs nothing for the simple case. You write `impl CanGreet for Person { ... }` as usual, and `person.greet()` resolves to that direct impl with no wiring involved. + +## Further reference + +For the full expansion and accepted syntax of each macro, see the online docs: +[`#[cgp_component]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_component.md), +[`#[cgp_impl]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_impl.md), +[`#[cgp_provider]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_provider.md), +[`#[cgp_new_provider]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_new_provider.md), +and +[`IsProviderFor`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/is_provider_for.md). +For the concepts behind the split, see +[consumer and provider traits](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/consumer-and-provider-traits.md), +[bypassing coherence](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/coherence.md), +and +[impl-side dependencies](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/impl-side-dependencies.md). +For sibling sub-skills, see [wiring](wiring.md), [checking](checking.md), +[functions and getters](functions-and-getters.md), and +[higher-order providers](higher-order-providers.md). diff --git a/docs/ai/skills/references/error-extraction.md b/docs/ai/skills/references/error-extraction.md deleted file mode 120000 index a9f87756..00000000 --- a/docs/ai/skills/references/error-extraction.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/error-extraction.md \ No newline at end of file diff --git a/docs/ai/skills/references/error-extraction.md b/docs/ai/skills/references/error-extraction.md new file mode 100644 index 00000000..ef58267b --- /dev/null +++ b/docs/ai/skills/references/error-extraction.md @@ -0,0 +1,88 @@ +# Extracting CGP compile errors + +How to turn a CGP compile error — often a wall of repeated failures naming generated types — into a compact, root-cause-first summary. This skill serves two roles, and which one applies depends on your task: an agent **extracting** an error reads raw compiler output and reduces it to a few facts, while an agent **delegating** hands a long error to a sub-agent so it never touches the main context. Both roles rely on the same shape knowledge, so read [The two shapes](#the-two-shapes-to-recognize) first, then jump to [Role 1 — extracting](#role-1--extracting-an-error-yourself) or [Role 2 — delegating](#role-2--delegating-the-extraction-to-a-sub-agent). + +**Prefer `cargo-cgp` first — this sub-skill is the fallback.** When +[`cargo-cgp`](https://github.com/contextgeneric/cargo-cgp) is available, it has already done this +extraction: it rewrites a recognized CGP error into a `[CGP-Exxx]` headline over a root-cause +dependency tree, which *is* the compact summary below. Reach for the manual technique here only when +the tool is not installed, or when it leaves an error largely as `rustc` wrote it (a class it does +not yet rewrite). The main [SKILL.md tooling section](../SKILL.md) covers installing and running the +tool; everything below is for reading raw compiler output by hand. + +## Why extraction is a skill of its own + +CGP error output is disproportionately large and disproportionately misleading, so reading it well is a distinct task from fixing the code. Wiring is resolved [lazily](checking.md), so one broken link surfaces at every place that transitively needs it, and each failure quotes *generated* code — `IsProviderFor`, `DelegateComponent`, `CanUseComponent`, and the type-level `Symbol`/`Chars`/`PathCons` spines you never wrote. A single missing field can print screens of near-identical errors. Worse, some of that output is actively deceptive: a whole class of CGP errors reports that a trait's bounds are unsatisfied while *hiding* the dependency that actually failed. Reading such output inline, in the agent trying to fix the code, wastes context on noise and risks chasing a cause the output does not contain. + +## The two shapes to recognize + +Before decoding any nested type, read the *trait* in the error and decide which of two shapes you are looking at, because the shapes differ in whether the root cause is even present. The [macro-grammar](macro-grammar.md) decoder and the [checking](checking.md) playbook cover the full set; extraction needs the one binary distinction. + +A **surfaced** error carries the root cause. It is an `E0277` note chain, typically topped by `CanUseComponent` or `IsProviderFor`, that names a concrete missing bound such as `HasField`. This is what a [`check_components!`](checking.md) assertion produces, because the check requires `IsProviderFor` as a *direct* bound and forces the compiler to evaluate the provider's `where` clause. The concrete bound is the fact to extract — the compiler names it in a `help:`/"is not implemented" note, and the `required for …` notes trace the dependency path from it back to the check. + +A **hidden** error does not. It is an `E0599` "the method `greet` exists for struct `Person`, but its trait bounds were not satisfied", or an `E0277` that a consumer trait like `Person: CanGreet` is unsatisfied, and it names the consumer or provider trait and then stops — with no note descending to the missing field or dependency. This happens when broken wiring is exercised by *calling the consumer-trait method directly* rather than through a check: the compiler sees the consumer trait's blanket impl among the candidate impls, finds it inapplicable, and suppresses the nested bound that made it so. The cause is **absent**, not buried. Do not scan a hidden error for a root cause; there is none to find. The fix is to *promote* it into a surfaced error — add a `check_components!` for the failing component at the wiring site — and read that instead. + +## The cheap first move: grep for the suspected line + +Before committing to either role, try to answer your question with a grep, because the main agent can often confirm or dismiss a hypothesis without reading the log itself or spawning a sub-agent to read it. This is the move to reach for whenever you have a specific suspicion — a field you think you forgot, a key you think you wired twice, a `UseContext` you think is a cycle — and the failing build is captured to a file. Grep is not a third role so much as the way to avoid needing Role 2: a targeted search costs a few lines of output where delegating costs a whole sub-agent turn, so a hypothesis you can phrase as a pattern is one you should grep for rather than delegate. + +Grep the error headlines first, because that one search does the classifying. +`grep -nE '^error' /tmp/cgp-error.txt` prints one line per error block — the code and the trait each +names — which decides the [shape](#the-two-shapes-to-recognize) and, with the +[macro-grammar decoder](macro-grammar.md), the class. A second grep for the class's signature then +confirms the cause: `grep -n 'help:'` for a surfaced dependency leaf (a `HasField>` spells +the field name letter-by-letter on one line), `conflicting implementation` for a duplicate key, +`overflow evaluating` for a cycle, `does not contain any DelegateComponent entry` for an unwired +component, `is not constrained` for an unconstrained generic, and so on. The +[debugging guide's grep table](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/guides/debugging.md#grep-for-the-suspected-line-instead-of-reading-the-whole-log) +lists the signature line for every class. + +Two limits decide when grep gives way to a full read or a delegation. A **hidden** error cannot be grepped: if the only headline is an `E0599` "method … exists … but its trait bounds were not satisfied", the cause is absent from the output, so promote it with a `check_components!` and re-run rather than searching for a leaf that is not there. And when the headline grep shows several unrelated classes at once, or the cause hides behind an elided `...` whose full form sits in a `long-type-….txt` file, the search will not converge — that is the point to escalate to [Role 2](#role-2--delegating-the-extraction-to-a-sub-agent) and let a sub-agent absorb the whole log. The rule is the same throughout: a targeted question is a grep, an open-ended read is a delegation. + +## Role 1 — extracting an error yourself + +You are in this role whenever you are the one reading the raw output — as a sub-agent handed the job, or as the main agent facing an error short enough to read inline. Your product is the [compact summary](#reduce-to-the-compact-summary) below, never the raw dump. + +### Capture the output without flooding context + +Capture the compiler output to a file rather than letting it stream into your transcript, and target the smallest unit that reproduces the failure. A whole-workspace build multiplies the cascade across crates; a single crate, test, example, or ten-line scratch module shrinks it to the one thing you care about. The commands are just your project's ordinary build and test invocations — nothing CGP-specific: + +```bash +# Target the smallest failing unit and redirect everything to a scratch file. +cargo check -p 2>&1 | tee /tmp/cgp-error.txt + +# or a single test / example that exercises the failing wiring: +cargo test -p --test 2>&1 | tee /tmp/cgp-error.txt +``` + +Two details recur, both plain `rustc` behavior rather than anything CGP-specific. When a type in the error is elided as `...`, the compiler writes its full form to a file named in a final note (`the full name for the type has been written to '….long-type-….txt'`); that elided middle is frequently the one segment that reveals *which* context or path the error is about, so read that file when the cause hinges on a long type. And watch for the **near-contradiction** shape — "the trait `X` is not implemented for `T`" immediately followed by a `help:` note that `X` *is* implemented for `T` — which means an impl exists but a nested bound it carries does not hold, or two candidates are ambiguous; trust the error, not the `help:`. + +When the cause hinges on *what the macro emitted* rather than on the message itself, stop reading the error and read the expansion. Reach for `cargo cgp expand` first: it prints the crate after macro expansion with CGP's type-level constructs resugared, so a field tag that the error rendered as a `Chars` spine reads `Symbol!("height")` in the expansion — the generated code is often easier to read than the diagnostic about it. Narrow it to the part you care about, since a whole crate's expansion is long and a filtered one keeps your context clear: + +```sh +cargo cgp expand --lib --item AreaCalculator # a trait: every impl of it — what a component generated +cargo cgp expand --lib --item contexts::MockApp # a type: its HasField impls and its wiring entries +cargo cgp expand --lib > /tmp/expanded.rs # or redirect the whole thing and grep it +``` + +Pass `--lib` or `--bin NAME` when the package has several targets, or cargo refuses to run. Plain `cargo expand` is the fallback where `cargo cgp expand` is unavailable — it shows the same expansion without the resugaring — and in a project set up with the CGP test utilities the `snapshot_*!` helpers from `cgp-macro-test-util` additionally pin an expansion as a reviewable snapshot. The [macro-grammar](macro-grammar.md) skill covers how to read the expanded impls once you have them. + +### Reduce to the compact summary + +Reduce the output to the same few facts — the anatomy a CGP error catalog records — and nothing more: + +- **Class and code** — the error code(s) and the trait(s) named (`E0599` on a provider trait, `E0277` through `CanUseComponent`, `E0119` conflicting `DelegateComponent`, `E0207` unconstrained generic, and so on). +- **Hidden or surfaced** — whether the root cause is present in the output at all. +- **Root cause and position** — if surfaced, the concrete failing bound and where it sits (in the compiler's `help:` note, near the last or second-to-last block of a cascade, or inside the `long-type-….txt` file); if hidden, say so plainly. +- **Recommended next action** — fix the named field or wiring, promote a hidden error with a `check_components!`, break a cycle, remove a duplicate key — whatever the class implies. + +A good summary is a few lines, not a transcript. Never hand back the raw output; that defeats the purpose of extracting it. + +## Role 2 — delegating the extraction to a sub-agent + +You are in this role when you are the main agent and the error is long — a deep cascade, many crates, or output that runs to screens. Spawn a sub-agent to read it and return only the [compact summary](#reduce-to-the-compact-summary); the sub-agent absorbs the wall of text while you keep your own context clean. Give the sub-agent three things: the exact command to run (or the path to an already-captured output file), this skill so it knows the two shapes and the summary format, and the instruction to return *only* the summary. This is the intended workflow both when documenting an error class — where a sub-agent gathers the facts from a failing reproduction — and in an ordinary debugging session, where a sub-agent reads an error too long to justify reading inline. When the returned summary says the error is hidden, the follow-up is almost always to add a check and re-run, which itself may be worth delegating. + +## Further reference + +- Sibling skills: [checking](checking.md) for why wiring is lazy and how checks force a surfaced error; [macro-grammar](macro-grammar.md) for the full error decoder and how to read an expansion; [wiring](wiring.md) for the delegation mechanics behind a conflict or cycle. +- Online: the [error catalog](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp/errors) documents each error class and where its root cause sits, and the [debugging guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/guides/debugging.md) is the full tracing playbook. diff --git a/docs/ai/skills/references/error-handling.md b/docs/ai/skills/references/error-handling.md deleted file mode 120000 index 49935b1e..00000000 --- a/docs/ai/skills/references/error-handling.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/error-handling.md \ No newline at end of file diff --git a/docs/ai/skills/references/error-handling.md b/docs/ai/skills/references/error-handling.md new file mode 100644 index 00000000..1e80d523 --- /dev/null +++ b/docs/ai/skills/references/error-handling.md @@ -0,0 +1,138 @@ +# Error handling + +CGP's modular error handling: one shared abstract `Error` type per context, plus pluggable behavior for constructing that error from a source error and for attaching detail to it. + +Generic CGP code must be able to fail without naming a concrete error type. A provider that hits a fallible operation gets back a `parse error`, an `io::Error`, or a string, yet it is generic over the context and cannot commit to `anyhow::Error` or any other choice — that choice belongs to the application assembling the context. CGP resolves this with three cooperating [components](components.md): `HasErrorType` gives the context one abstract `Self::Error`, `CanRaiseError` constructs that abstract error from a concrete source error, and `CanWrapError` enriches an existing abstract error with extra detail. The concrete error type and the raising/wrapping behavior are decided once, at [wiring](wiring.md) time, by whichever error backend the context plugs in. + +A note on imports: the consumer traits `HasErrorType`, `CanRaiseError`, and `CanWrapError` come through `use cgp::prelude::*;`, but the wiring keys and backend providers below do not. The component markers (`ErrorTypeProviderComponent`, `ErrorRaiserComponent`, `ErrorWrapperComponent`) live under `cgp::core::error`, and the backend providers (`RaiseFrom`, `ReturnError`, `DebugError`, `DisplayError`, and the rest) live under `cgp::extra::error`, so a module that wires error handling imports the specific names it uses, for example `use cgp::core::error::ErrorRaiserComponent;` and `use cgp::extra::error::RaiseFrom;`. + +## `HasErrorType`: the shared abstract error + +`HasErrorType` is the abstract-type component that gives a context a single shared `Error` type, and every fallible CGP operation refers to it. It is declared with `#[cgp_type]`, so it behaves like any other [abstract type](abstract-types.md) — a trait with one associated type, wired through a provider rather than hand-implemented: + +```rust +#[cgp_type] +pub trait HasErrorType { + type Error: Debug; +} + +pub type ErrorOf = ::Error; +``` + +The `Debug` bound lets `Self::Error` flow into `.unwrap()` and straightforward logging without an extra constraint, and it is enforced on whatever concrete type a context chooses. `ErrorOf` is the convenient spelling of the associated-type path. Generic code that may fail returns `Result` (or `Result>`) and never names a concrete error. + +Centralizing the error type on one trait is what lets errors compose. A context trait that may fail depends on `HasErrorType`, so every such trait refers to the *same* error; if each declared its own associated `Error`, a context bounded by several of them would face several incompatible error types with no way to unify them. `HasErrorType` carries no methods — it only declares the type. The behavior of producing errors lives in the traits that build on it. The preferred way to author such a trait is [`#[use_type(HasErrorType.Error)]`](abstract-types.md), which adds `HasErrorType` as a supertrait *and* rewrites a bare `Error` in the signatures to `::Error` — so you write neither `: HasErrorType` nor `Self::Error` by hand. + +Because `#[cgp_type]` generates a `UseType` blanket impl, a context fixes its error type by wiring the error-type component to `UseType`, exactly as for any abstract type: + +```rust +#[cgp_component(Validator)] +#[use_type(HasErrorType.Error)] +pub trait CanValidate { + fn validate(&self) -> Result<(), Error>; +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} +``` + +Here `#[use_type(HasErrorType.Error)]` makes `CanValidate` depend on the shared abstract error and lets `validate` name it as the bare `Error`, and `App` fixes that error to `String`. The standalone backends (`cgp-error-anyhow`, `cgp-error-eyre`, `cgp-error-std`) supply ready-made providers that set `Error` to their respective library types instead. A context can equally implement the trait directly — `impl HasErrorType for App { type Error = String; }` — which makes plain that it is an ordinary trait with a `Debug`-bounded associated type. + +## `CanRaiseError` and `CanWrapError`: producing and enriching the error + +`CanRaiseError` is the consumer trait for turning a concrete source error into the context's abstract error, and `CanWrapError` is the companion that attaches detail to an existing one. Both import the error type with `#[use_type(HasErrorType.Error)]` — so they name it as the bare `Error` and gain `HasErrorType` as a supertrait — and both are `#[cgp_component]`s that delegate per type so a context can handle each source error or detail with a different provider: + +```rust +#[cgp_component(ErrorRaiser)] +#[derive_delegate(UseDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanRaiseError { + fn raise_error(error: SourceError) -> Error; +} + +#[cgp_component(ErrorWrapper)] +#[derive_delegate(UseDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanWrapError { + fn wrap_error(error: Error, detail: Detail) -> Error; +} +``` + +`raise_error` takes the source error by value and returns the abstract error; `wrap_error` takes the current abstract error plus a `Detail` and returns an enriched one. Both are associated functions with no `self` receiver — raising and wrapping are properties of the context *type*, so generic code calls `Context::raise_error(source)` and `Context::wrap_error(err, detail)` where only the type parameter is in scope. The `#[cgp_component(...)]` attribute names the provider traits `ErrorRaiser` and `ErrorWrapper`, and `#[derive_delegate(UseDelegate<...>)]` makes each dispatch per `SourceError` or `Detail` type through a delegation table. + +A provider written against these bounds names neither the context nor its concrete error type: + +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} + +#[cgp_impl(new LoadOrFail)] +#[uses(CanRaiseError, CanWrapError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + let err = Self::raise_error("empty path".to_owned()); + return Err(Self::wrap_error(err, format!("while loading {path}"))); + } + Ok(format!("contents of {path}")) + } +} +``` + +The provider requires `CanRaiseError` to turn a message into the abstract error and `CanWrapError` to attach context as it propagates — both [impl-side dependencies](components.md) that any wired context satisfies by plugging in providers. The context decides, through wiring, what concrete error type `load` actually produces. + +## Wiring the behavior: error-backend providers + +A context gains raising and wrapping by wiring `ErrorRaiserComponent` and `ErrorWrapperComponent` to providers, exactly like any other component. The `cgp-error-extra` crate supplies a family of zero-sized providers (the [providers](components.md) are markers with no runtime value) that are generic over the context's error type and capture cross-cutting strategies independent of any one error library; they sit alongside the standalone backends, which specialize to a concrete library error such as `anyhow::Error`. A typical context wires a mix: a backend for the concrete error type plus these generic providers for the strategies. The raisers, wrappers, and their bounds are: + +- `RaiseFrom` implements `ErrorRaiser` by converting through `From` — it raises any source error whose `Context::Error: From`, the default choice when the abstract error already absorbs the source. +- `ReturnError` implements `ErrorRaiser` for the case where the source *is* the abstract error (`HasErrorType`), returning it untouched. +- `RaiseInfallible` implements `ErrorRaiser` for `core::convert::Infallible`, producing the error by an empty `match` that can never run — letting code parameterized over a fallible operation be wired uniformly even when the chosen operation cannot fail. +- `PanicOnError` implements `ErrorRaiser` by `panic!`-ing with the source error's `Debug` output instead of returning a value — for contexts that treat an error as a fail-fast fault, such as tests. +- `DiscardDetail` implements `ErrorWrapper` by dropping the detail and returning the error unchanged — the wrapping no-op, for error types that cannot carry extra context. +- `DebugError` and `DisplayError` implement *both* components by formatting the source error or detail into a `String` and forwarding to the context's own `CanRaiseError` / `CanWrapError` — `DebugError` via `Debug`, `DisplayError` via `Display`/`to_string()`. Both live behind the crate's `alloc` feature. + +The simplest wiring delegates to a single provider. Wiring `RaiseFrom` lets `App` raise any source error its abstract error implements `From` for: + +```rust +delegate_components! { + App { + ErrorRaiserComponent: RaiseFrom, + } +} +``` + +The string-formatting providers are designed to *compose* with the others rather than replace them: `DebugError` and `DisplayError` do not know the context's error type, they only reduce a `Debug` or `Display` value to a `String` and hand it off, so the context must separately wire a provider that handles the `String` source. Because both components dispatch per source-error type, the idiomatic wiring lists one entry per source error — a concrete string-raising rule plus formatting redirects for everything else — opened on the component with the `open` statement of `delegate_components!`: + +```rust +delegate_components! { + App { + open ErrorRaiserComponent; + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseError: DebugError, + } +} +``` + +The `open ErrorRaiserComponent;` header opens the component for per-type wiring, and each `@ErrorRaiserComponent.: Provider` entry assigns the provider for one source-error type, folded directly into `App`'s own table — `open` needs no `#[derive_delegate]` of its own because every `#[cgp_component]` already generates the `RedirectLookup` impl it dispatches through. The legacy equivalent writes the same per-type entries into a separate `UseDelegate` nested table; that form is still common in existing code but is slated for deprecation, so prefer `open` for new wiring. See [wiring](wiring.md) for both forms. + +A raised `String` is converted straight into the abstract error by `RaiseFrom`, while a raised `ParseError` is formatted with `Debug` by `DebugError` and then routed back through the `String` entry — which `RaiseFrom` handles — yielding one coherent error type from two unrelated sources. The choice of provider is therefore also a statement about which source errors the context accepts and how, and each wiring is verified with `check_components!` like any other. + +## Related constructs + +`HasErrorType` is an [abstract type](abstract-types.md) declared with `#[cgp_type]`, so it is wired with `UseType` or a backend provider the same way every abstract type is. `CanRaiseError` and `CanWrapError` are ordinary [components](components.md) that supertrait it, wired with `delegate_components!` as covered in [wiring](wiring.md), and their `#[derive_delegate(UseDelegate<...>)]` is what lets a context dispatch raising and wrapping per source-error or detail type through a delegation table. + +Further reference (online): +[components/has_error_type.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/has_error_type.md), +[components/can_raise_error.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/can_raise_error.md), +[providers/error_providers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/error_providers.md). diff --git a/docs/ai/skills/references/extensible-data.md b/docs/ai/skills/references/extensible-data.md deleted file mode 120000 index a60d2eb9..00000000 --- a/docs/ai/skills/references/extensible-data.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/extensible-data.md \ No newline at end of file diff --git a/docs/ai/skills/references/extensible-data.md b/docs/ai/skills/references/extensible-data.md new file mode 100644 index 00000000..2c1272b1 --- /dev/null +++ b/docs/ai/skills/references/extensible-data.md @@ -0,0 +1,163 @@ +# Extensible data + +Treat a struct as a product of named fields and an enum as a sum of named variants, so that generic code can read, build, deconstruct, and convert any data type by its type-level field and variant names rather than by naming the concrete type. + +A plain Rust `struct` or `enum` is opaque to generic code: nothing about "the `first_name` field" or "the `Circle` variant" can be named through a type parameter, so a struct literal must list every field at one site and a `match` must spell out every variant. Extensible data breaks that by deriving a type-level description of a type's shape — its fields or variants, each tagged by name — and the machinery to build, take apart, and convert values through that description. This brings row polymorphism and structural sum types to Rust, resolved entirely at compile time, and it is what lets independent components each contribute one field or handle one variant without knowing the whole type. The result feeds directly into CGP wiring: builders, variant dispatchers, and structural casts all consume the field-level machinery these derives generate. A context is just such a data type when it flows through providers this way. + +The whole family is dual. A record is a product (every field present at once); an enum is a sum (exactly one variant present). The two share their presence markers, their casting traits, and their dispatch machinery, so reading one half tells you the shape of the other. + +## The umbrella derive and its shape-specific faces + +`#[derive(CgpData)]` is the high-level entry point: applied to a struct it emits the full record machinery, applied to an enum the full variant machinery, dispatching on the item kind. `#[derive(CgpRecord)]` and `#[derive(CgpVariant)]` are the same code paths restricted to one shape — use them when the type is always a struct or always an enum and you want the name to say so; applying the wrong one is a type error. The narrower building-block derives (`HasFields`, `HasField`, `BuildField`, `ExtractField`, `FromVariant`) each emit one slice of that output when you want only part of it. + +```rust +#[derive(CgpData)] +pub struct Person { pub first_name: String, pub last_name: String } + +#[derive(CgpData)] +pub enum Shape { Circle(Circle), Rectangle(Rectangle) } +``` + +Field tags drive everything generated. A named struct field or an enum variant is keyed by the type-level string `Symbol!("name")`, and an unnamed field of a tuple struct by its positional `Index`; that tag is what addresses the field across every generated impl. One restriction shapes the variant side: a derivable enum must follow the sum-of-products form, where each variant holds exactly one unnamed payload — wrap a richer payload in a dedicated struct so the variant's value stays a single nameable type. A fieldless, multi-field, or struct-style variant is a compile error. + +## Records: the whole-struct field view + +`#[derive(HasFields)]` gives a type its whole-shape view, the foundation everything else builds on. For a struct it implements `HasFields` with a `Fields` associated type that is a [`Product!`](type-level-primitives.md) of `Field` entries — the type-level spelling of the struct's layout, one entry per field tagged by name: + +```rust +impl HasFields for Person { + type Fields = Product![ + Field, + Field, + ]; +} +``` + +The derive also emits the conversions that move values in and out of that representation: `ToFields` turns an owned value into its `Fields` product, `FromFields` rebuilds the value from one, and `ToFieldsRef` borrows it as a product of references. Generic algorithms bound `Context: HasFields` (or `ToFields`/`FromFields`) and fold over `Context::Fields` structurally, never naming the concrete struct. This whole-shape view is distinct from per-field indexed access: reading a single field by name is `HasField`, the dependency-injection capability that getter traits resolve against (see [functions and getters](functions-and-getters.md)). A struct that wants both derives both. + +## Records: building a struct field by field + +The capability `#[derive(CgpRecord)]` and `#[derive(BuildField)]` add on top of reading is incremental, type-checked construction, exposed through the builder trait family. Construction runs through a *partial record* — a generated companion struct `__Partial{Name}` carrying one `MapType` marker per field that records whether that field is present yet. The marker `IsPresent` stores the field's real value, `IsNothing` stores `()`, so a partial record with every marker `IsNothing` is an empty builder and one with every marker `IsPresent` is a fully populated value. The family walks between these states. + +```rust +let employee: Employee = Employee::builder() // every field IsNothing + .build_from(person) // first_name + last_name now IsPresent + .build_field(PhantomData::, 1) // employee_id now IsPresent + .finalize_build(); // exists only at the all-present configuration +``` + +`HasBuilder::builder()` produces the empty partial record; `BuildField::build_field` flips one marker from `IsNothing` to `IsPresent`; and `FinalizeBuild::finalize_build` turns the partial record back into the concrete struct. Underneath, both `BuildField` and its reverse `TakeField` (the `IsPresent → IsNothing` direction) are blanket impls over a single per-field primitive `UpdateField`, which changes one field's marker and returns the old value alongside the rebuilt partial. The tracking is what makes the pattern safe: `finalize_build` is implemented *only* for the all-`IsPresent` configuration, so finalizing with any field still absent is a compile error rather than a runtime panic, and the order in which fields are built does not matter. The reverse direction is equally useful — `IntoBuilder` turns a complete struct into an all-present partial, and `TakeField` removes fields one at a time. + +That all-present strictness is sometimes too rigid — a record may have fields with sensible defaults or ones genuinely allowed to be absent. The `cgp-field-extra` **optional-field** extension relaxes it in two controlled ways while reusing the same `UpdateField` machinery: it can fill an unset field with `Default::default()` at finalize time, and it can track a field as an `Option` (the `IsOptional` marker) so absence becomes a runtime value rather than a compile error. Reach for it when a struct has optional or defaulted fields; the strict all-present builder above remains the default. + +## Records: the extensible builder pattern + +`CanBuildFrom` (one of the structural casts below) is what lets a builder absorb the shared fields of an entire source struct in one `build_from` step: it recurses over the source's field product, using `TakeField` to pull each field out and `BuildField` to write it into the target builder. So a small struct like a database client can be merged into a larger application struct without either type naming the other — they share only field names, matched at the type level. This is the basis of the *extensible builder pattern*, where the construction of one context is split across several independent providers, one per subsystem, none of which knows the final type or each other. Each provider builds a small output struct, and a dispatcher merges every output into the target's builder before finalizing. + +```rust +delegate_components! { + FullAppBuilder { + HandlerComponent: + BuildAndMergeOutputs, + } +} +``` + +Because the dispatcher is generic over the target struct and the provider list, swapping a subsystem means changing one entry, and selecting among several target structs is a matter of code-based dispatch. The `BuildAndMergeOutputs` combinator and the rest of this routing live in [handlers](handlers.md). + +## Variants: constructing and deconstructing an enum + +For an enum, `#[derive(HasFields)]` produces a `Fields` that is a [`Sum!`](type-level-primitives.md) of `Field` entries built on the `Either`/`Void` spine, mirroring the product side. Construction is `FromVariant`, generated per variant by `#[derive(FromVariant)]`: it builds the enum from one variant chosen by a type-level tag, so generic code parameterized over a `Tag` can construct whichever variant it was asked for. + +```rust +fn wrap_circle(circle: Circle) -> Shape { + Shape::from_variant(PhantomData::, circle) // == Shape::Circle(circle) +} +``` + +Deconstruction is the dual of the builder and runs through a *partial variant* — the companion enum `__Partial{Name}` generated by `#[derive(ExtractField)]`, carrying one `MapType` marker per variant just as a partial record carries one per field. The crucial difference is the absence marker: a record uses `IsNothing` (storing `()`), while a variant uses `IsVoid`, mapping a ruled-out variant to the uninhabited `Void` type. `HasExtractor::to_extractor` converts the enum into a partial variant with every variant still `IsPresent`, and `ExtractField::extract_field` tries to pull out one variant, returning `Ok(value)` if the value is that variant or `Err(remainder)` — the partial variant with that variant flipped to `IsVoid` — otherwise. + +```rust +fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + // remainder's type now has Circle ruled out (IsVoid); try the next variant + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); // remainder is now empty; this cannot fail + rect.width * rect.height + } + } +} +``` + +Marking extracted variants as `IsVoid` is what gives compile-time exhaustiveness without a wildcard arm. Each failed `extract_field` rules out one more variant in the type, so after every variant has been tried the remainder has every marker `IsVoid` and is therefore uninhabited. `FinalizeExtract::finalize_extract` discharges such a remainder with an empty `match`, sound precisely because no value can reach it — and `FinalizeExtractResult::finalize_extract_result` is the convenience wrapper that collapses the final `Result` into its `Ok` value. Add a variant to the enum without handling it and the final remainder becomes inhabited again, so the code fails to compile until the new variant is covered, recovering the guarantee a concrete `match` gives. `HasExtractorRef` and `HasExtractorMut` provide the same machinery over borrows. + +## Variants: the extensible visitor pattern + +Routing a value to the handler for its current variant is the *extensible visitor pattern*, which solves the expression problem: new variants can be added without touching the handlers for the others, and the same handler set can serve several enums that share variants. The logic for each variant lives in its own provider, and a dispatcher derives one extract-and-handle step per variant from the enum's `Fields`, running them as a pipeline that short-circuits on the first matching variant and threads the remainder forward otherwise. + +```rust +delegate_components! { + Interpreter { + ComputerComponent: + UseInputDelegate: EvalAdd, // one provider per variant + Times: EvalMultiply, + Literal: EvalLiteral, + }>, + } +} +``` + +The `MathExpr` entry routes the whole enum through a thin context-specific provider that defers to the matcher combinator; that wrapper exists to break the trait-resolution cycle between the matcher and the per-variant providers it dispatches to. The matcher combinators (`MatchWithValueHandlers` and its by-reference form) and the per-variant handler families live in [handlers](handlers.md). + +## The type-level spines underneath + +Both halves rest on the same right-nested type-level lists, kept brief here and covered fully in [type-level primitives](type-level-primitives.md). A struct's `Fields` is a `Product![A, B, C]`, which desugars to `Cons>>` over the `Cons`/`Nil` record spine — a list terminated by the constructible empty `Nil`, because an empty record is a valid value. An enum's `Fields` is a `Sum![A, B]`, which desugars to `Either>` over the `Either`/`Void` variant spine — a chain that branches at each step and terminates in the uninhabited `Void`, because an empty choice has no value to pick. The lowercase `product![..]` builds a value of the matching `Product!` type. Generic providers walk these spines one element at a time, which is exactly what no plain tuple or enum permits in generic code. + +The machinery above computes new spines from old ones through a small type-level list algebra you will meet in the traits it expands to: `AppendProduct` adds one field to the end of a product, `ConcatProduct` splices two products together, and `MapFields` rewrites every entry uniformly (the operation behind producing a partial record from a full one). All three are pure functions from type lists to type lists, evaluated by the compiler during type checking at no runtime cost — building a record appends, merging records concatenates, and forming a partial record maps a marker over every field. + +## Structural casts between records and variants + +Two types that share a subset of named fields or variants convert into one another generically, with no hand-written `From`/`TryFrom`, through the casting traits — every conversion is just routing each named entry to the matching slot in the target. `CanUpcast` lifts a value of a narrow enum into a wider one whose variants are a superset; it always succeeds, since every source variant has a home in the target, and it walks the source's variants, extracting each and reconstructing it via `FromVariant`. `CanDowncast` goes the other way, narrowing a wide enum into a smaller one and succeeding only if the value's current variant exists in the target, otherwise handing back a remainder; `CanDowncastFields` is the same operation on a remainder, so downcasting against several candidates chains a `downcast` followed by `downcast_fields`. `CanBuildFrom` is the record counterpart already met above, assembling a target builder out of the fields of one or more sources. + +```rust +let wide = FooBar::Foo(1).upcast(PhantomData::); // always succeeds +assert_eq!(wide, FooBarBaz::Foo(1)); + +FooBarBaz::Bar("hi".into()).downcast(PhantomData::).ok(); // Some(FooBar::Bar(..)) +FooBarBaz::Baz(true).downcast(PhantomData::).ok(); // None — Baz has no home in FooBar +``` + +Upcasting is also how a provider constructs a value using only the subset of variants it cares about: it builds a small local enum and upcasts it into the full type — the variant-side analog of reading a field through a getter. + +## Dispatching over extensible data + +The payoff of exposing data shape at the type level is that *dispatch* becomes generic: a record builder routes each field to the provider that produces it, and a variant visitor routes each value to the provider for its current variant. Both are realized with the dispatch combinators — `BuildAndMergeOutputs` on the record side, `MatchWithValueHandlers` on the variant side — which derive one per-field or per-variant step from the type's `Fields` and sequence them. Those combinators and the handler families they build on are documented in [handlers](handlers.md); the wiring tables that name a provider per [component](components.md) are the ordinary `delegate_components!` entries shown above. + +## Further reference + +Online docs (current as of CGP v0.8.0): +[concepts/extensible-records.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/extensible-records.md), +[concepts/extensible-variants.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/extensible-variants.md), +the derive references under +[reference/derives/](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp/reference/derives) +(`derive_cgp_data.md`, `derive_cgp_record.md`, `derive_cgp_variant.md`, `derive_has_fields.md`, +`derive_build_field.md`, `derive_extract_field.md`, `derive_from_variant.md`), the trait references +[traits/has_builder.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/has_builder.md), +[traits/extract_field.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/extract_field.md), +[traits/from_variant.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/from_variant.md), +[traits/has_fields.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/has_fields.md), +and +[traits/cast.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/cast.md), +and the type macros +[macros/product.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/product.md) +and +[macros/sum.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/sum.md). diff --git a/docs/ai/skills/references/functions-and-getters.md b/docs/ai/skills/references/functions-and-getters.md deleted file mode 120000 index 40e7e3b9..00000000 --- a/docs/ai/skills/references/functions-and-getters.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/functions-and-getters.md \ No newline at end of file diff --git a/docs/ai/skills/references/functions-and-getters.md b/docs/ai/skills/references/functions-and-getters.md new file mode 100644 index 00000000..187cc04e --- /dev/null +++ b/docs/ai/skills/references/functions-and-getters.md @@ -0,0 +1,314 @@ +# Functions and Getters + +The ergonomic surface of basic CGP — `HasField` field access, `#[cgp_fn]` single-implementation capabilities, `#[implicit]` arguments, and getter traits — the constructs that let CGP code read like ordinary Rust functions and accessors. + +## How field access works underneath: `HasField` + +Every value a provider reads out of its context flows through one tiny consumer trait, `HasField`, which keys a single field by a *type-level* name rather than by the concrete struct it lives in. A provider is generic over its context and cannot reach into a struct it does not know, so instead of naming the field directly it demands one by tag: a `where`-clause bound `Context: HasField` says "any context wired to me must carry a `String` field called `name`," and the trait system supplies it. This makes field access an [impl-side dependency](components.md) — a requirement hidden from the trait interface and satisfied automatically by any matching context. Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. + +The trait carries the field's type as an associated `Value` and returns a reference, taking a `PhantomData` argument whose only job is to tell the compiler which field is meant when several `HasField` impls are in scope: + +```rust +pub trait HasField { + type Value; + fn get_field(&self, _tag: PhantomData) -> &Self::Value; +} +``` + +The `Tag` is a type-level name, and CGP has two kinds. A named struct field is keyed by `Symbol!("field_name")`, the type-level string of its identifier; a tuple field is keyed by `Index`, the type-level natural number of its position. Both are [type-level primitives](type-level-primitives.md) — types with no values — which is exactly why `get_field` needs the `PhantomData` argument to carry one at the call site. A `HasFieldMut: HasField` companion adds `get_field_mut` returning `&mut Self::Value` for the rarer mutable case. + +Reading a field is the PhantomData tag-inference trick in practice. Inside a provider body you write `self.get_field(PhantomData)` and let Rust infer the tag from the surrounding bound, or pin it explicitly with `self.get_field(PhantomData::)` when more than one field could match: + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData)); + } +} +``` + +You almost never write `HasField` impls by hand. The companion derive does it for you. + +## Generating field access: `#[derive(HasField)]` + +`#[derive(HasField)]` turns a struct's concrete fields into the type-level entries the trait system looks up, emitting one `HasField` and one `HasFieldMut` impl per field and leaving the struct definition untouched. It is the bridge between an ordinary Rust struct and constraint-based field access: without it, a struct's fields are invisible to CGP, and every getter would be hand-written. For a named struct, + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, + pub age: u8, +} +``` + +the derive emits a `Symbol!`-keyed pair per field — `impl HasField for Person { type Value = String; … }` reading `&self.name`, and the same for `age` — so `Person` satisfies `HasField` exactly as the `GreetHello` bound above requires. A tuple struct expands identically except each field is keyed by its positional `Index` instead of a `Symbol!`: + +```rust +#[derive(HasField)] +pub struct Rectangle(pub f64, pub f64); +// → impl HasField> for Rectangle { type Value = f64; … &self.0 } +// → impl HasField> for Rectangle { type Value = f64; … &self.1 } +``` + +Generic parameters thread through faithfully, and field access also flows through smart pointers — `HasField` has a blanket impl over any `Deref` target that has the field, so a `Box` resolves `get_field` to the inner struct. Deriving `HasField` is the one thing a context must do for every higher-level construct on this page — `#[cgp_fn]`, `#[implicit]`, and both getter macros all desugar into `HasField` bounds. + +## Single-implementation capabilities: `#[cgp_fn]` + +`#[cgp_fn]` turns a plain function into a CGP capability that every context gains automatically, with no wiring step at all. A full [component](components.md) defines a consumer trait, a provider trait, and a delegation table so that many providers can be swapped per context; `#[cgp_fn]` is the lightweight counterpart for the common case where a capability has a single natural definition. You write the body as if `self` were concrete, and the macro emits a trait plus a *blanket* impl over a generic context — so the method becomes available on every type that satisfies the body's impl-side dependencies, with no `delegate_components!` block and no provider struct anywhere. + +The function name in snake case becomes the method name, and the trait name defaults to that name in PascalCase. Given: + +```rust +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} +``` + +the macro emits a `RectangleArea` trait whose method takes no arguments, and a blanket impl over the reserved context type `__Context__` in which each `#[implicit]` parameter became a `HasField` bound and a `get_field` binding at the top of the body: + +```rust +pub trait RectangleArea { + fn rectangle_area(&self) -> f64; +} + +impl<__Context__> RectangleArea for __Context__ +where + Self: HasField + + HasField, +{ + fn rectangle_area(&self) -> f64 { + let width: f64 = self.get_field(PhantomData::).clone(); + let height: f64 = self.get_field(PhantomData::).clone(); + width * height + } +} +``` + +That generated blanket impl is the whole point of the macro, so it is worth seeing: the context type parameter is literally `__Context__` and references to it inside the impl read as `Self`. Pass an identifier to override the default trait name, which is useful when a verb-style name reads better — `#[cgp_fn(CanCalculateRectangleArea)]` generates `CanCalculateRectangleArea` instead of `RectangleArea`. + +Generics and `where` clauses are handled with a deliberate split: every generic parameter in the function's `<...>` list goes onto *both* the trait and the impl, while the function's `where` bounds land only on the impl, hidden from the trait as impl-side dependencies. A generic area function makes this concrete: + +```rust +#[cgp_fn] +pub fn rectangle_area( + &self, + #[implicit] width: Scalar, + #[implicit] height: Scalar, +) -> Scalar +where + Scalar: Mul + Copy, +{ + width * height +} +``` + +Here `Scalar` appears on `RectangleArea` and its impl, while `Scalar: Mul + Copy` stays on the impl only, ordered before the implicit `HasField` bounds (which are always appended last). One restriction is intentional: `#[cgp_fn]` does not support generics on the *method* itself — method-level generics belong to the trait and impl, and the rare genuine need for them is an advanced case better written as an explicit blanket impl or a full component. + +## Field access dressed as a function argument: `#[implicit]` + +The `#[implicit]` attribute marks a function argument as sourced from a context field instead of from the caller, so a provider reads like a function taking parameters while behaving like one injecting dependencies. This is the recommended on-ramp to CGP: a programmer who understands functions and arguments can write a complete provider without first meeting `HasField`, `Symbol!`, or `PhantomData`. Strongly prefer implicit arguments in basic code — they keep CGP looking like ordinary Rust. The argument name doubles as the field name, so `#[implicit] width: f64` reads as "this function needs a `width` of type `f64`," and the macro removes the argument from the signature, adds the matching `HasField` bound, and binds the value at the top of the body (as the `#[cgp_fn]` expansion above shows). + +The argument type controls how the field is read, following a small set of rules so the body always receives exactly the declared type. An owned type such as `f64` or `String` reads the field by reference and appends `.clone()`, leaving the context's field intact; the one special case to memorize is `&str`, which is backed by a `String` field and read with `.as_str()` rather than `.clone()`, letting the body borrow without forcing the context to store a `&str`: + +```rust +#[cgp_fn] +pub fn greet(&self, #[implicit] name: &str) { + println!("Hello, {}!", name); +} +// bound: HasField +// binding: let name: &str = self.get_field(PhantomData::).as_str(); +``` + +Three rules constrain where `#[implicit]` may appear. The function must take `self` as its first argument, since the field is read from it; the argument pattern must be a bare identifier, not a destructuring or `mut` pattern (clone inside the body for a mutable local); and a mutable implicit argument — one whose type carries a `&mut` (a `&mut T`, `&mut [T]`, `Option<&mut T>`, or `Option<&mut str>`) — must be the *only* implicit argument (and needs a `&mut self` receiver), since it reads through `get_field_mut` and borrows the whole context exclusively — immutable implicits are shared borrows and combine freely in any number. The access mode follows the argument's own type, not the receiver's: only an argument carrying a `&mut` reads through `get_field_mut` (a `&mut [T]` via an `AsMut<[T]>` field, an `Option<&mut T>` via `.as_mut()`, an `Option<&mut str>` via `.as_deref_mut()` on an `Option` field). `#[implicit]` is usable in both `#[cgp_fn]` and the methods of a `#[cgp_impl]` provider, with the same desugaring in each — inside `#[cgp_impl]` the `HasField` bounds simply join the provider impl's `where` clause. + +## Importing capabilities: `#[uses]` + +`#[uses(...)]` adds `Self: Trait<...>` bounds to a provider's `where` clause, written to read like a `use` import of the capabilities the body depends on. A provider that calls another `#[cgp_fn]` capability, or a [component](components.md) consumer trait, must require the context to implement it — a `where Self: SomeTrait` bound that reads as machinery. `#[uses(RectangleArea)]` instead reads as "this function uses the `RectangleArea` capability," and the macro turns each listed name into the corresponding `Self` bound on the impl so the body can call those methods directly on `self`. **The listed trait need not be a CGP construct**: `#[uses(Display)]` and `#[uses(AsRef<[u8]>)]` are accepted and preferred over the equivalent hand-written clause, since the attribute only cares that the bound is one a context can satisfy — so an ordinary Rust trait imports exactly as a capability does. Building a scaled area on top of the base one: + +```rust +#[cgp_fn] +#[uses(RectangleArea)] +pub fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 { + self.rectangle_area() * scale_factor * scale_factor +} +``` + +This adds `Self: RectangleArea` to the generated impl's `where` clause, alongside the `HasField` bound from the implicit `scale_factor` — the imported bound lands on the impl only, never on the trait, exactly like writing `where Self: RectangleArea` by hand. The simple `TraitIdent` form is the idiomatic one, since the attribute is meant to read like an import, but an entry may be any bound a `where` clause accepts, including an associated-type-equality binding such as `HasErrorType`. Reach for that sparingly: to pin an *abstract type*, prefer the [`#[use_type]` equality form](abstract-types.md) `#[use_type(HasErrorType.{Error = AppError})]`, which adds the bound *and* rewrites the type, over spelling the equality in `#[uses]`. When a provider imports several capabilities, list them all in one attribute separated by commas — `#[uses(CanQueryUserBalance, CanRaiseHttpError)]` — rather than stacking `#[uses(...)]` repeatedly; the combined form reads as a single dependency list. `#[uses(...)]` works in both `#[cgp_fn]` and `#[cgp_impl]`, and the imported capability may itself be defined either way. + +## Adding supertraits and trait bounds: `#[extend]` and `#[extend_where]` + +In `#[cgp_fn]`, the function's own `where` clauses are impl-side dependencies kept off the trait, so there is no place to write a supertrait by hand — `#[extend(...)]` is the only way to add one. Where `#[uses]` adds a hidden impl-side bound (the `use` equivalent), `#[extend]` promotes its bound to a *supertrait* of the generated trait — a public requirement every implementor satisfies and every caller may rely on (the `pub use` equivalent). The bound appears in two places: as a supertrait on the trait, so an associated type like `Self::Scalar` resolves and callers know the bound holds, and in the impl's `where` clause so the body can use it. The example below uses the abstract-type trait `HasScalarType` to make that two-placement behavior visible in one signature, but for an abstract-type supertrait like this, `#[use_type]` is the production form (see the note after it) and `#[extend]` is reserved for a non-type capability supertrait. A `#[cgp_fn]` over an abstract scalar type: + +```rust +pub trait HasScalarType { + type Scalar: Clone + Mul; +} + +#[cgp_fn] +#[extend(HasScalarType)] +pub fn rectangle_area( + &self, + #[implicit] width: Self::Scalar, + #[implicit] height: Self::Scalar, +) -> Self::Scalar { + width * height +} +// → pub trait RectangleArea: HasScalarType { fn rectangle_area(&self) -> Self::Scalar; } +``` + +`#[extend]` accepts the same simplified `TraitIdent` syntax as `#[uses]`, and is also usable on `#[cgp_component]`, where it is the preferred way to add a *non-type capability* supertrait: writing `#[extend(HasName)]` reads as importing a capability, whereas the native `pub trait CanGreet: HasName` syntax reads as OOP-style inheritance from a parent class, which a CGP supertrait is not. (For an abstract-type component whose associated type the signatures name, prefer `#[use_type]` instead, which adds the supertrait *and* rewrites the type — the recommended form for abstract-type components.) Its sibling `#[extend_where(...)]` adds *`where`-clause* predicates to the generated trait definition rather than supertraits, and is `#[cgp_fn]`-only. Unlike `#[uses]` and `#[extend]`, it accepts arbitrary predicates — including associated-type equality — so a generic parameter can carry a publicly visible bound: + +```rust +#[cgp_fn] +#[extend_where(Scalar: Clone)] +pub fn rectangle_area(/* … */) -> Scalar +where + Scalar: Mul, +{ /* … */ } +// → pub trait RectangleArea where Scalar: Clone { fn rectangle_area(&self) -> Scalar; } +``` + +The `Scalar: Mul` bound from the body stays an impl-side dependency, while `Scalar: Clone` from `#[extend_where]` is promoted onto the trait. **What that promotion buys is enforcement at the use site, not a bound callers inherit** — the distinction is easy to state backwards. A trait's `where` clause is a *precondition* on naming the trait rather than something elaborated to whoever holds it, so code generic over `Scalar` must still write `Scalar: Clone` in its own `where` clause; only a supertrait added with `#[extend]` is handed to callers. What promotion changes is that an unsatisfiable requirement is caught where the trait is named — `Ctx: RectangleArea` becomes an `E0277` with a `required by a bound in RectangleArea` note — whereas the same bound left on the impl alone is accepted in silence, since an impl-side bound only decides where the impl applies and nothing complains until a concrete context is supplied. + +## Getter traits: `#[cgp_auto_getter]` + +A getter trait exposes a context field as a reusable `self.name()` accessor, and `#[cgp_auto_getter]` generates its single blanket impl by reading the field whose name matches the method name. Use it *sparingly* — an [implicit argument](#field-access-dressed-as-a-function-argument-implicit) is the default for reading a field, since it injects the value as an ordinary-looking parameter with no separate trait to declare, reads only from the provider's own `self`, and takes a plain `&T` by reference without cloning. Because that covers every same-context read — even a field several providers each consume, written as the same implicit argument in each — a getter trait earns its keep only in the cases an implicit argument cannot reach: the field lives on a type *other* than the provider's context, so the getter is required as a `where` bound on that type (`Request: HasBasicAuthHeader`, with no `self` field to read); the accessor must exist as a *named* capability other code depends on through `#[uses(HasName)]` or a supertrait; or the getter carries an associated type inferred from the field so the type stays abstract for callers. The macro takes no arguments and re-emits the trait verbatim, adding a blanket impl over `__Context__` keyed by the method name as a `Symbol!`: + +```rust +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +// generated: +impl<__Context__> HasName for __Context__ +where + __Context__: HasField, +{ + fn name(&self) -> &str { + self.get_field(PhantomData::).as_str() + } +} +``` + +That generated blanket impl is the point of the macro, and it follows the same access rules as `#[implicit]`: a plain `&T` return reads a `T` field directly, while the `&str` shorthand reads a `String` field and appends `.as_str()`. Other shorthands include `Option<&T>` (an `Option` field via `.as_ref()`), `Option<&str>` (an `Option` field via `.as_deref()`), `&[T]` (a field implementing `AsRef<[T]>`), an owned type — path, tuple, or array — via `.clone()`, and, with a `&mut self` receiver, the mutable mirrors `&mut T`, `&mut [T]` (a field implementing `AsMut<[T]>`, via `.as_mut()`), `Option<&mut T>` (via `.as_mut()`), and `Option<&mut str>` (an `Option` field via `.as_deref_mut()`) — all through `get_field_mut`. A trait may declare several methods, each mapping independently to its own field — `fn width(&self) -> &f64; fn height(&self) -> &f64;` produces one `where` predicate and one body per field in the same impl. + +A single getter may also declare a local associated type and use it as its return type, which lets the abstract type be inferred from the field. The trait must then contain exactly one method returning `&Self::AssocType`; the macro lifts the type into a generic parameter on the impl and binds it through the `HasField` `Value`: + +```rust +#[cgp_auto_getter] +pub trait HasName { + type Name: Display; + fn name(&self) -> &Self::Name; +} +// → impl<__Context__, Name> HasName for __Context__ +// where Name: Display, __Context__: HasField +// { type Name = Name; … } +``` + +A context gains the getter just by deriving `HasField` with a matching field — `person.name()` resolves through the blanket impl with no wiring. The cost of that simplicity is rigidity: the field name *must* equal the method name, and there is no way to swap the implementation. When you need either, `#[cgp_getter]` provides it — but that is an advanced tool, not a routine next step. + +When the getter's return type names an abstract type that lives on a *foreign* type — a generic parameter of the trait rather than `Self` — prefer importing it with [`#[use_type]`](abstract-types.md)'s `in Context` clause over a hand-written `where` bound and a qualified path. Write + +```rust +#[cgp_auto_getter] +#[use_type(HasUserIdType.UserId in App)] +pub trait HasLoggedInUser { + fn logged_in_user(&self) -> &Option; +} +``` + +rather than declaring `where App: HasUserIdType` and returning `&Option`. The `in App` clause supplies `App: HasUserIdType` on the generated trait and rewrites the bare `UserId` to `::UserId`, so the plain `` parameter and the bare alias are enough — the same benefit `#[use_type]` gives on `Self`, extended to a parameter. + +## Wireable getters: `#[cgp_getter]` and `UseField` + +`#[cgp_getter]` defines a getter as a full CGP [component](components.md) instead of a blanket impl, so the field name can differ from the method name and the getter can be swapped per context through [wiring](wiring.md). It is a specialized, advanced tool: reserve it for when a context genuinely needs full control over which field a getter reads from, and prefer an implicit argument or `#[cgp_auto_getter]` for the ordinary case of a same-named field. It accepts the same getter-method forms as `#[cgp_auto_getter]`, but because it is an extension of `#[cgp_component]` it needs a provider trait name. The default derives one from the trait name by stripping a leading `Has` and appending `Getter`, so `HasName` yields the provider `NameGetter` and the component marker `NameGetterComponent`; pass an argument like `#[cgp_getter(GetName)]` to override it. + +The decoupling is delivered by an automatically generated `UseField` provider impl. `UseField` is a zero-sized provider (a `PhantomData`-only marker named in wiring, carrying no runtime value) that implements the getter by reading the field named `Tag` from the context — and crucially, `Tag` need not be the method name: + +```rust +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} + +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} +// person.name() now reads the first_name field +``` + +The trait method is `name` but the context stores the value in `first_name`, and the wiring `NameGetterComponent: UseField` bridges the two — the field name lives in the wiring, not in the trait. Internally `#[cgp_getter]` generates a `UseField` impl whose tag is left as a free parameter, in contrast to the `#[cgp_auto_getter]` blanket impl that hard-codes the tag to the method name. The macro also emits a `UseFields` provider (the provider-side analogue of the auto-getter blanket impl, keyed by method name) and, for single-method getters, a `WithProvider` adapter. + +For getters whose return type is reached *through* a field by `AsRef`/`AsMut` rather than being the field itself, the related `UseFieldRef` provider reads the field at `Tag` and calls `as_ref()` to expose `&Value` — for example `UseFieldRef` exposes `&str` from a `String` field. It decouples the exposed type from the stored type as well as the field name from the method name. Unlike `UseField`, it is not re-exported through the prelude; reach it through `cgp::core::field::impls`. + +`UseField` and `UseFieldRef` are the foundational field-getter providers; their `WithProvider` aliases `WithField` and `WithFieldRef` (see [wiring](wiring.md)) are what you often see wired directly onto a getter component, reading `NameGetterComponent: WithField` as "serve this getter from the named field." + +## Reaching a nested field with `ChainGetters` + +When the value a getter needs is not on the context but several hops inside it — the context holds a config, the config holds a connection, the connection holds the timeout — `ChainGetters` walks the path. It takes a `Product!` list of getters and applies them in order, threading the reference each step produces into the next, so the chain reads like the path it traverses: + +```rust +delegate_components! { + App { + TimeoutGetterComponent: ChainGetters Config + GetConnection, // Config -> Connection + GetTimeout, // Connection -> Duration + ]>, + } +} +``` + +Each element is itself a field getter for the value the previous step produced, and like every provider `ChainGetters` is a zero-sized marker named in wiring. It saves writing a bespoke provider that hand-walks the nesting whenever a getter must reach into a sub-context. + +## Getters are just traits: explicit implementation + +Every getter the macros produce is an ordinary trait, and explicit implementation is always available — the macros only save boilerplate. This matters when a context does not derive `HasField`, or stores the value under a name no tag matches. Because `#[cgp_auto_getter]` adds only a blanket impl and `#[cgp_getter]` a component whose consumer trait is plain Rust, you can write the impl by hand on a concrete type: + +```rust +pub struct Person { + pub full_name: String, +} + +impl HasName for Person { + fn name(&self) -> &str { + &self.full_name + } +} +``` + +The explicit form is more verbose but requires no understanding of `HasField` or blanket impls — a reminder that the whole apparatus on this page is convenience layered over vanilla Rust traits. + +## Choosing between the constructs + +For reading a field into a provider — the common case — an `#[implicit]` argument is the default: it keeps the access local and the code reading like a plain function, whether the value is used once or throughout the body, and it applies to any field on the provider's own context, even one several providers each read. Promote a field to a getter trait only when an implicit argument cannot reach it — the field lives on another type and the getter is a `where` bound on it, the accessor must be a named capability other code depends on, or it carries an associated type inferred from the field — and then use `#[cgp_auto_getter]` when the field name matches the method name (the usual getter), and `#[cgp_getter]` (with `UseField`) as the advanced tool reserved for when the source field name must be chosen per context at wiring time. For a whole capability rather than a single field, `#[cgp_fn]` defines one with no wiring when a single implementation suffices, and a full [component](components.md) when many providers must coexist. All of them rest on the same `HasField` machinery and the same access rules, so mixing them carries no conceptual overhead. + +## Further reference + +Online docs (current v0.8.0): +[`#[cgp_fn]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_fn.md), +[`HasField`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/has_field.md), +[`#[derive(HasField)]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/derives/derive_has_field.md), +[`#[implicit]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/implicit.md), +[`#[uses]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/uses.md), +[`#[extend]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/extend.md), +[`#[extend_where]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/extend_where.md), +[`#[cgp_auto_getter]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_auto_getter.md), +[`#[cgp_getter]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_getter.md), +[`UseField`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_field.md), +[`UseFieldRef`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_field_ref.md), +and the +[implicit-arguments concept](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/implicit-arguments.md). diff --git a/docs/ai/skills/references/handlers.md b/docs/ai/skills/references/handlers.md deleted file mode 120000 index 5ceb91b5..00000000 --- a/docs/ai/skills/references/handlers.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/handlers.md \ No newline at end of file diff --git a/docs/ai/skills/references/handlers.md b/docs/ai/skills/references/handlers.md new file mode 100644 index 00000000..823087e4 --- /dev/null +++ b/docs/ai/skills/references/handlers.md @@ -0,0 +1,266 @@ +# Handlers + +The handler family is a spectrum of CGP components that all transform an `Input` into an `Output` under a phantom `Code` tag, varying along three axes — synchronous vs. async, infallible vs. fallible, and input vs. no-input — together with the macros that build handlers from functions, the combinators that compose and lift them, the dispatchers that route over extensible data, and the monads that chain them. + +Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. Every handler is an ordinary [component](components.md) — a consumer trait the context calls, a provider trait a zero-sized provider implements, and a `…Component` marker that [wiring](wiring.md) maps to a provider — so nothing here needs machinery beyond what you already know. + +## The shared shape and the three axes + +Every handler maps `(context, Code, Input) -> Output`, where `Code` is a phantom tag carried as `PhantomData` and `Output` is an *associated type* the provider chooses, not a parameter the caller fixes. The `Code` tag holds no data; it exists so one context can host many handlers keyed by distinct tags, and so wiring can dispatch on it. The family is large because real computations differ along three independent axes, and each combination gets its own component so a provider declares exactly the capabilities it has. + +The first axis is **synchronous vs. async**: an async component returns a future and its method is `async`, marked by `Async` in the name (`AsyncComputer` is the async `Computer`). The second is **infallible vs. fallible**: a fallible component returns `Result` against the context's abstract error and so supertraits [`HasErrorType`](abstract-types.md), marked by the `Try` prefix. The third is **owned vs. by-reference input**: every base component has a `*Ref` sibling that borrows `&Input` instead of consuming `Input`. The general principle is that you write the *weakest* variant that fits and let combinators promote it upward, because an infallible computation is trivially fallible, a sync one trivially async, and an owned-input one can serve a borrow — but never the reverse. + +The components, by corner, are these. `Computer`/`CanCompute` is the pure-computation base — synchronous and infallible, with `AsyncComputer` and the `*Ref` variants alongside it. `TryComputer`/`CanTryCompute` is fallible but synchronous. `Handler`/`CanHandle` is the fully general async-and-fallible computation, the bound a generic consumer targets because every simpler provider promotes up to it. `Producer`/`CanProduce` sits apart as the no-input case, producing a value from the context and `Code` alone. A related pair, `CanRun`/`CanSendRun`, runs a named task rather than transforming a value. + +## The computation components + +`CanCompute` is the simplest member and the one to reach for first. Its method takes the `Code` tag and the input by value and returns the chosen `Output` with no failure path: + +```rust +#[cgp_component(Computer)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +pub trait CanCompute { + type Output; + fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; +} +``` + +The provider trait `Computer` moves the context into an explicit first parameter, as for any component; the marker is `ComputerComponent`. The two `#[derive_delegate]` directives let a context route to different providers by `Code` (via `UseDelegate`) or by `Input` type (via the family's `UseInputDelegate`), the basis of [dispatching](#dispatching-over-extensible-data). `AsyncComputer`/`CanComputeAsync` is identical but declares `async fn compute_async` under `#[async_trait]`, and `ComputerRef`/`AsyncComputerRef` borrow the input as `&Input`. None of the four supertrait `HasErrorType`, because none can fail. + +`CanTryCompute` adds the failure path. It supertraits `HasErrorType` so its `Result` can name the context's abstract error, which is what keeps a provider generic over the error backend: + +```rust +#[cgp_component(TryComputer)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanTryCompute { + type Output; + fn try_compute(&self, _code: PhantomData, input: Input) + -> Result; +} +``` + +A `TryComputer` provider carries a `Context: HasErrorType` bound and typically converts a concrete source error into the abstract one with [`CanRaiseError`](error-handling.md). `TryComputerRef` is the by-reference sibling. + +`CanHandle` is the general corner — async *and* fallible — and is the bound generic pipeline code targets, since `Computer`, `AsyncComputer`, and `TryComputer` all promote up to it: + +```rust +#[async_trait] +#[cgp_component(Handler)] +#[derive_delegate(UseDelegate)] +#[derive_delegate(UseInputDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanHandle { + type Output; + async fn handle(&self, _tag: PhantomData, input: Input) + -> Result; +} +``` + +A function bounded by `Context: CanHandle` accepts any wired computation regardless of which capabilities the underlying provider actually uses. `HandlerRef` borrows the input. + +`CanProduce` is the no-input case: it threads no `Input`, only the context and a `Code` tag, and so carries a single `#[derive_delegate(UseDelegate)]` with no `UseInputDelegate` counterpart and does not supertrait `HasErrorType`: + +```rust +#[cgp_component(Producer)] +#[derive_delegate(UseDelegate)] +pub trait CanProduce { + type Output; + fn produce(&self, _code: PhantomData) -> Self::Output; +} +``` + +A producer is the natural source of values that flow into a pipeline — a constant or a context-derived default — and promotes into any input-taking handler by ignoring the supplied input. + +A handler provider is an ordinary zero-sized provider implementing the provider trait for a generic context. The built-in `UseField` is a `Computer` that forwards the computation to the value held in the context's `Tag` field; beyond it, the combinators below supply the rest. + +## Task runners: `CanRun` and `CanSendRun` + +The runner pair executes a unit of work selected by a `Code` tag rather than transforming a value, completing to `Result<(), Error>`. `CanRun` is the base async form; `CanSendRun` exists to recover a `Send` future for spawning: + +```rust +#[cgp_component(Runner)] +#[async_trait] +#[derive_delegate(UseDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanRun { + async fn run(&self, _code: PhantomData) -> Result<(), Error>; +} + +#[cgp_component(SendRunner)] +#[async_trait] +#[derive_delegate(UseDelegate)] +#[use_type(HasErrorType.Error)] +pub trait CanSendRun { + fn send_run(&self, _code: PhantomData) + -> impl Future> + Send; +} +``` + +A context hosts many tasks by wiring `RunnerComponent` to a `UseDelegate` table keyed on `Code`, so `app.run(PhantomData::)` and `app.run(PhantomData::)` reach distinct providers. A runner provider reaches the runtime through `HasRuntime` to spawn or await work; the `CanSendRun` variant is the mechanism for the `Send`-recovery pattern described under [recovering `Send` bounds](#recovering-send-bounds). + +## The runtime: `HasRuntimeType` and `HasRuntime` + +A runner needs something to run *against* — an executor that can spawn, sleep, open sockets, or read the clock — and CGP keeps that runtime abstract so the same code runs on Tokio in production, a mock in tests, or a single-threaded executor in a benchmark. Two built-in components express it, split because the two questions are independent. `HasRuntimeType` is an [abstract type](abstract-types.md) (`type Runtime`) answering *what* the runtime type is, chosen per context through wiring like any `#[cgp_type]` component. `HasRuntime` is a getter that supertraits `HasRuntimeType` and answers *how to obtain* the runtime value from a borrow of the context (`fn runtime(&self) -> &Self::Runtime`). Code that only names types the runtime exposes bounds on `HasRuntimeType` alone; code that performs effects bounds on `HasRuntime`. This pair is the seam where context-generic logic meets concrete async machinery, which is why the runner providers reach through it to do their work. + +## Defining handlers from functions + +`#[cgp_computer]` turns a plain function into a `Computer` provider and wires the rest of the family by promotion, so a computation as small as "add two numbers" needs no hand-written plumbing: + +```rust +#[cgp_computer] +fn add(a: u64, b: u64) -> u64 { + a + b +} +``` + +The function name becomes the provider name in PascalCase (`Add`), unless an explicit name is given as `#[cgp_computer(MyAdder)]`. The parameters are collected into a tuple that becomes the single `Input` type and destructured back inside the generated method; the return type becomes `Output`. The macro emits the function unchanged, a `#[cgp_new_provider]` impl of the base trait, and a `delegate_components!` block routing every other handler component to a promotion bundle: + +```rust +#[cgp_new_provider] +impl<__Context__, __Code__> Computer<__Context__, __Code__, (u64, u64)> for Add { + type Output = u64; + fn compute(_context: &__Context__, _code: PhantomData<__Code__>, + (arg_0, arg_1): (u64, u64)) -> Self::Output { + add(arg_0, arg_1) + } +} +// delegate_components! routes the rest of the family to PromoteComputer +``` + +The base trait and bundle are chosen from two axes the macro reads off the signature. A synchronous plain-value function uses `Computer` + `PromoteComputer`; a synchronous `Result`-returning one keeps `Computer` as the base (its `Output` is the `Result`) but uses `PromoteTryComputer`, which surfaces the `Ok`/`Err` as genuine success/failure; an `async` plain-value function uses `AsyncComputer` + `PromoteAsyncComputer`; an `async` `Result` function uses `AsyncComputer` + `PromoteHandler`. Generic parameters and `where` clauses carry onto the impl; a `&Value` parameter makes the input tuple borrow and the bundle's `PromoteRef` entries serve the `*Ref` components. The result is that one `add` answers `compute`, `try_compute`, `compute_async`, and `handle`. + +`#[cgp_producer]` is the input-less sibling, turning a zero-argument function into a `Producer` and wiring `PromoteProducer` across the whole family: + +```rust +#[cgp_producer] +fn magic_number() -> u64 { + 42 +} +``` + +The function must take no parameters, must not be `async`, and must have no generics — a producer's shape is fixed, so there is no variation in the expansion. The generated `MagicNumber` answers `produce` and, because `PromoteProducer` discards the input that each computer slot supplies, also `compute`, `try_compute`, `handle`, and the `*Ref` forms, every one yielding `42`. + +## Composing and promoting with handler combinators + +The handler combinators are zero-sized providers of `cgp-handler` that build, sequence, and lift handlers, carrying their inner providers in `PhantomData`. They divide into composition, the identity element, and promotion. + +`ComposeHandlers` runs two handlers back to back, pinning the second's input to the first's output and exposing the pair as a member of every handler family; the fallible variants `?`-short-circuit and the async variants `.await` each step. `PipeHandlers` generalizes it to a `Product![...]` list, folding right to left so `PipeHandlers` behaves as `ComposeHandlers>` and serves whichever handler shape the wiring asks for, provided every stage supports it: + +```rust +delegate_components! { + MyContext { + ComputerComponent: + PipeHandlers, + Add, + Multiply, + ]>, + } +} +// input 5 over foo=2, bar=3, baz=4 -> ((5 * 2) + 3) * 4 +``` + +`ReturnInput` is the identity handler — it ignores the context and `Code` and returns its input unchanged (wrapped in `Ok` for the fallible variants) — and is the neutral element of composition, useful as a placeholder stage. + +The promotion combinators each take one inner provider and re-expose it under a different, more capable family member, encoding the one-directional lifts the axes permit. `Promote` lifts upward without adding behavior: a `Producer` into a `Computer` (ignoring the input), a `Computer` into a `TryComputer` (wrapping in `Ok`), an `AsyncComputer` into a `Handler`. `PromoteAsync` lifts a sync provider into an async one whose future is immediately ready. `PromoteRef` bridges value and reference handlers by dereferencing or re-borrowing. `TryPromote` bridges a `Result`-valued `Computer` and a genuine `TryComputer` in both directions. You rarely name these one at a time; instead the *promotion bundles* — `PromoteComputer`, `PromoteTryComputer`, `PromoteProducer`, `PromoteAsyncComputer`, `PromoteHandler` — are `delegate_components!` tables that wire a whole cluster of components to the right single-step promoter from a given base. These are exactly what `#[cgp_computer]` and `#[cgp_producer]` wire for you, and reaching for `PromoteComputer` by hand achieves the same when wiring explicitly. + +## Dispatching over extensible data + +Dispatching routes an [extensible-data](extensible-data.md) value to per-variant or per-field handlers: for an enum, match the current variant and run its handler; for a record, run a handler per field to build it. It keeps the per-variant/per-field structure of a concrete `match` or struct literal but lets the shape and handlers be chosen by type, so the same matcher serves many enums. + +`#[cgp_auto_dispatch]` is the highest-level entry point. Written above a trait that already has one impl per payload type, it generates a blanket impl of that trait for any extensible enum of those types, dispatching each variant to that payload's impl: + +```rust +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} +// with impls for Circle and Rectangle, and a #[derive(CgpData)] enum Shape, +// HasArea is now implemented for Shape too: +let shape = Shape::Rectangle(Rectangle { width: 2.0, height: 2.0 }); +assert_eq!(shape.area(), 4.0); +``` + +For each method it emits a per-variant computer via `#[cgp_computer]` (named `Compute` plus the method name) and an enum-level impl that runs the appropriate value-handler matcher — `MatchWithValueHandlers` for `&self`, its `Mut` form for `&mut self`, and the `MatchFirstWith…` family when the method takes extra arguments, with the `Async` form for `async` methods. A method may not have non-lifetime generic parameters, since the generated impl would need a quantified bound Rust lacks; such a method must use the combinators directly. + +Underneath, the dispatch combinators of `cgp-dispatch` express both directions as handler providers. On the matching side, `MatchWithHandlers` (with `Ref`/`Mut` and `MatchFirstWith…` forms) converts the input to its extractor and runs a list of per-variant adapters — `ExtractFieldAndHandle` tries one variant and forwards its payload, `HandleFieldValue` strips the `Field` wrapper to hand the bare value to a computer, and `DowncastAndHandle` matches a group of variants to a sub-matcher. The list runs as a monadic pipeline that short-circuits on the first match and proves exhaustiveness without a wildcard, because each miss rules out one variant until the final remainder is uninhabited. `MatchWithValueHandlers` builds that list automatically from the enum's own field list. Dispatch on the *input* type uses the `Computer` component's `UseInputDelegate` directive, wired as a nested table with one entry per input type: + +```rust +delegate_components! { + App { + ComputerComponent: + UseInputDelegate, + } +} +``` + +Each entry routes one input type (the array form sharing a provider across several), so a `Circle` or `Rectangle` input reaches `ComputeArea` while a whole `Shape` enum reaches the matcher. This input-type dispatch keys on the `Input` parameter through the component's `UseInputDelegate` directive, which is why it is written as a nested table rather than through the `open` statement — `open` rides the default `RedirectLookup` that keys on the primary `Code` parameter (see [wiring](wiring.md) for the `open` form, which is the modern way to do `Code`-keyed dispatch). The nested-table form is the established way to dispatch on the input type, and this concerns only the *wiring* — the dispatch combinators above are unaffected. + +On the building side, `BuildWithHandlers` starts from an empty builder, pipes it through per-field adapters — `BuildAndSetField` computes and sets one field, `BuildAndMerge` merges a whole record's shared fields — and finalizes. Because finalization is available only when every field is present, omitting a handler for a field is a compile error rather than a runtime half-built value. + +## Composing through a monad + +Plain composition feeds each output straight into the next step, which is wrong the moment a step can produce a value meaning "stop here." Monadic handlers solve this: the monad decides which branch of a step's output threads forward and which short-circuits out as the final result. `PipeMonadic` is the entry point — a monad marker plus a `Product![...]` list — and the pipeline it builds is itself a `Computer`-family provider: + +```rust +PipeMonadic::::compute(&context, code, 253) +// 253 -> Ok(254) -> Ok(255) -> Err("overflow"); the third overflow becomes the output +``` + +CGP ships three monad markers. `IdentMonadic` threads every value forward and never short-circuits, recovering plain `PipeHandlers` composition. `ErrMonadic` short-circuits on `Err` and continues on `Ok` — the `?`-style early return where the first error wins. `OkMonadic` is the mirror, stopping at the first `Ok`, which suits retry-until-success and is what the dispatch matcher loop runs under. The two `Result`-branching markers have transformer forms, `OkMonadicTrans` and `ErrMonadicTrans`, that stack their behavior on a base monad so a pipeline over a nested `Result, F>` can short-circuit on the outer error while threading the inner result. + +The per-step providers `BindOk` and `BindErr` implement a single bind and are what `PipeMonadic` composes internally; they can also be dropped into a `PipeHandlers` list directly for step-by-step control. `BindErr` runs `Cont` on an `Ok` payload and short-circuits an `Err`; `BindOk` is its mirror. `PipeMonadic` also implements the fallible and async-fallible components by demoting each provider through `TryPromote`, applying `ErrMonadic` as a transformer over `M`, and re-wrapping — so a monadic pipeline reached through `try_compute` or `handle` short-circuits on the context's error type as well. + +## Recovering `Send` bounds + +An async trait method advertises a future whose auto-traits the caller cannot name. The `#[async_trait]` rewrite turns `async fn handle(..)` into `fn handle(..) -> impl Future<..>` with no boxing and no `Send`, which is faithful and zero-cost but drops the `Send` guarantee. The bound becomes load-bearing when the future is spawned onto a work-stealing executor (the default Tokio runtime an Axum server uses), which may migrate a suspended task between threads. The clause you want — "the future of `handle` is `Send` for any arguments" — is Return Type Notation (`handle(..): Send`), which stable Rust does not yet offer. + +The workaround is a second, ordinary trait whose method states `+ Send` directly in its return type, sidestepping RTN: + +```rust +pub trait CanHandleApiSend: + CanHandleApi + Send + Sync +{ + fn handle_api_send(&self, _api: PhantomData, request: Self::Request) + -> impl Future> + Send; +} +``` + +This is a plain trait, not a component — it adds nothing to the wiring and exists only to carry the stronger bound. It cannot be implemented with a single generic blanket impl, because the body wraps `self.handle_api(..)` in an `async` block whose `Send`-ness depends on the opaque future it awaits — the same gap restated, just RTN in disguise. The impl must therefore be written per *concrete* `(context, API)` pair, where `self.handle_api(api, request)` resolves through the wiring to a concrete future whose auto-traits the compiler computes structurally and finds `Send`: + +```rust +impl CanHandleApiSend for MockApp { + async fn handle_api_send(&self, api: PhantomData, request: Self::Request) + -> Result { + self.handle_api(api, request).await + } +} +``` + +Each impl is mechanical forwarding, yet each is also a proof accepted only because the future really is `Send` at that instantiation. One concrete impl per API per context replaces the single generic impl RTN would have allowed — the cost of the missing notation. The built-in `CanSendRun` runner applies the same pattern as a `SendRunner` proxy on the concrete context, letting a spawning runner provider clone the context into a `Send` future without `Send` bounds leaking into any abstract interface. + +## Further reference + +Online docs: +[concepts/handlers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/handlers.md), +[concepts/dispatching.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/dispatching.md), +[concepts/monadic-handlers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/monadic-handlers.md), +[concepts/send-bounds.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/send-bounds.md); +reference docs +[components/computer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/computer.md), +[components/try_computer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/try_computer.md), +[components/handler.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/handler.md), +[components/producer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/producer.md), +[components/runner.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/runner.md), +[macros/cgp_computer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_computer.md), +[macros/cgp_producer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_producer.md), +[macros/cgp_auto_dispatch.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_auto_dispatch.md), +[providers/handler_combinators.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/handler_combinators.md), +[providers/dispatch_combinators.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/dispatch_combinators.md), +[providers/monad_providers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/monad_providers.md). diff --git a/docs/ai/skills/references/higher-order-providers.md b/docs/ai/skills/references/higher-order-providers.md deleted file mode 120000 index a7fac975..00000000 --- a/docs/ai/skills/references/higher-order-providers.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/higher-order-providers.md \ No newline at end of file diff --git a/docs/ai/skills/references/higher-order-providers.md b/docs/ai/skills/references/higher-order-providers.md new file mode 100644 index 00000000..973513dc --- /dev/null +++ b/docs/ai/skills/references/higher-order-providers.md @@ -0,0 +1,161 @@ +# Higher-order providers + +How one provider takes another provider as a generic parameter and builds on whatever that inner provider computes — the type-level counterpart to passing a function to a function. + +A higher-order provider is a [provider](components.md) parameterized by another provider, so part of its behavior is supplied by an inner provider it delegates to rather than fixed in its own code. The motivating shape is a wrapper that transforms the output of an existing implementation: a `ScaledArea` that multiplies whatever area an inner calculator produces, an `IterSumArea` that sums the areas an inner calculator returns over a collection, a `GloballyScaledArea` that applies a context-wide factor on top of a base calculation. In each case the outer provider knows the *transformation* but not the *base case* — the base case is a parameter. Because a provider carries no runtime value (it is a zero-sized marker naming an implementation), nesting providers costs nothing: the composition happens entirely in types. Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. + +## The shape, and the stray `` + +A higher-order provider is written like any other provider with `#[cgp_impl]`, with the inner provider declared as a generic parameter in the provider's `Self` position and bound to a *provider trait* in the `where` clause. The detail that makes it look stranger than it is the extra `` on that inner bound. Recall that a [provider trait](components.md) moves the consumer trait's `Self` into an explicit leading `Context` parameter — `AreaCalculator`, not the consumer trait's `CanCalculateArea`. So when the outer provider depends on its inner provider, the bound must name that context argument explicitly: + +```rust +#[cgp_impl(new ScaledArea)] +impl AreaCalculator +where + InnerCalculator: AreaCalculator, +{ + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } +} +``` + +The `` in `InnerCalculator: AreaCalculator` is exactly that leading context slot, filled with the context the outer provider is implementing for. Inside `#[cgp_impl]`, `self`/`Self` mean the *context*, so `` is the context type. The same asymmetry shows at the call site: the inner provider is invoked as the associated function `InnerCalculator::area(self)`, not as a method `self.area()`, because the provider trait's method takes the context as an explicit first argument. A reader who thinks of a provider as "just the consumer trait implemented elsewhere" is caught off guard by both the bound and the call. + +## Hiding the friction with `#[use_provider]` + +The `#[use_provider]` attribute exists to erase the bound surprise, and is the idiomatic way to write higher-order providers — always reach for it, since it preserves the illusion that a provider trait has the same shape as the consumer trait it came from. Written alongside `#[cgp_impl]`, it takes the inner bound *without* the context argument and fills the `` back in for you: + +```rust +#[cgp_impl(new ScaledArea)] +#[use_provider(InnerCalculator: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + let base_area = InnerCalculator::area(self); + base_area * scale_factor * scale_factor + } +} +``` + +The author writes `InnerCalculator: AreaCalculator` and the macro inserts the context type at index 0 of the trait's generic arguments, emitting `InnerCalculator: AreaCalculator` into the `where` clause — the two snippets above are equivalent. The shape it parses is `Provider: Trait`: a provider type, a colon, and one or more provider-trait bounds joined by `+`; the trait may carry further generic arguments after the context slot, preserved in order behind the inserted `Self`. To bind several inner providers, write **one attribute per provider**: + +```rust +#[use_provider(A: AreaCalculator)] +#[use_provider(P: PerimeterCalculator)] +``` + +Stacking is the intended form here rather than a fallback, because a comma-separated list of pairs does *not* parse — after the first trait the parser is continuing that provider's bound list, so `#[use_provider(A: TraitA, B: TraitB)]` fails with `expected +`. What the `+` does join is several trait bounds on *one* provider: `#[use_provider(Inner: AreaCalculator + PerimeterCalculator)]`. This makes `#[use_provider]` the exception to the one-attribute-comma-separated convention that `#[uses]` and `#[use_type]` follow, so the habit transfers wrongly. The same attribute works on `#[cgp_fn]`. + +What `#[use_provider]` does *not* do is rewrite the body. It completes the bound only; the inner provider is still invoked as the associated function `InnerCalculator::area(self)`, with `self` passed as the explicit context. There is no call-site form — a bare `#[use_provider(InnerCalculator)]` on an expression is not accepted, and no pass turns `receiver.method(args)` into `Provider::method(receiver, args)`. The body must spell the associated-function call out itself. Calling the inner provider as a method (`self.area()`) would instead route through whatever provider the context has wired for the component, a different dispatch and usually not what a higher-order provider wants. + +## `UseContext` as a default inner provider + +A higher-order provider can default its inner provider to [`UseContext`](wiring.md) so that, absent an explicit choice, it falls back to whatever the context itself is already wired to. This requires giving the provider an explicit struct definition with a default generic parameter: + +```rust +pub struct IterSumArea(pub PhantomData); +``` + +`UseContext` is the provider that implements any provider trait by deferring to the context's own consumer-trait implementation — the dual of the consumer blanket impl. With `IterSumArea` as the default, an unparameterized `IterSumArea` computes each inner element through the context's existing area wiring, so the wrapper drops in without restating the base case. Overriding the parameter — `IterSumArea` — instead binds the inner behavior statically, bypassing the context's wiring, which is useful for overriding or short-circuiting what the context would otherwise resolve. This default exists *only* when the provider has an explicit struct carrying the default parameter; a provider defined purely through `#[cgp_impl(new ...)]` has no default and must always have its inner provider named. + +## Not every generic provider is higher-order + +A provider that merely has generic parameters is not a higher-order provider; it becomes one only when a parameter is constrained to implement a provider trait. Many providers are generic for unrelated reasons. The `UseField`-style getter provider is generic over a field tag: + +```rust +#[cgp_impl(new GetName)] +impl NameGetter +where + Self: HasField, +{ + fn name(&self) -> &str { + self.get_field(PhantomData) + } +} +``` + +Here `Tag` is a type-level field name used only as a `HasField` key, with no provider-trait bound — so `GetName` is an ordinary parameterized provider, not a higher-order one. The defining trait of a higher-order provider is that a generic parameter appears in a *provider-trait* bound and is invoked to do part of the work, as `InnerCalculator: AreaCalculator` does. When that bound is absent, `#[use_provider]` has nothing to fill in and none of the machinery applies. + +## Generic-parameter CGP traits + +A component's trait may itself carry generic parameters, and `#[cgp_component]` appends them after the context slot. Declaring the area component to dispatch on a `Shape`: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} +``` + +generates the provider trait `AreaCalculator` — the original trait's parameters land *after* the leading `Context`, in declaration order. The `IsProviderFor` supertrait that every provider trait carries groups all those extra parameters into a single tuple in its `Params` slot (`()` when there are none), and any lifetime parameters are lifted into the `Life<'a>` type rather than appearing as bare lifetimes. A provider then writes `impl AreaCalculator for RectangleArea`, naming the concrete `Shape` it handles. + +## Dispatching on a generic parameter with `open` + +When the right provider depends on *which* concrete type a generic parameter is — `Rectangle` handled by one provider, `Circle` by another — the choice is made by a second lookup keyed on that parameter rather than on the component marker. The modern way a context writes this per-type dispatch is the `open` statement of `delegate_components!`, which folds the per-value entries directly into the context's own table. Given a `CanCalculateArea` consumer trait whose `Shape` parameter selects the area formula, a context opens the component and then assigns a provider per shape: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +The leading `open AreaCalculatorComponent;` header opens the component for per-value wiring, and each `@AreaCalculatorComponent.Key: Provider` entry assigns a provider for one value of the dispatch parameter: when `Shape` is `Rectangle`, `MyApp` calculates area through `RectangleArea`, and `Circle` resolves to `CircleArea`. After this wiring, `MyApp` implements `CanCalculateArea` through `RectangleArea` and `CanCalculateArea` through `CircleArea`, with the dispatch parameter selecting between them. Adding a shape is one more entry; the providers stay untouched. The `open` form needs no extra macro on the component — it rides the `RedirectLookup` impl that every `#[cgp_component]` already generates, so dispatching a component per type requires no `#[derive_delegate]` on the trait. Two shorthands keep the entries compact: an array on the final path segment shares one provider across several values (`@AreaCalculatorComponent.[Rectangle, Circle]: SomeProvider`), and generic parameters precede the dispatch value when it needs them (`@AreaCalculatorComponent.<'a, T> &'a T: SomeProvider`). The [wiring](wiring.md) reference is the canonical home of the `open` statement and its grammar. + +### Legacy: `derive_delegate` and `UseDelegate` nested tables + +An older form generates a `UseDelegate` provider and wires the per-type entries into a separate table it points at. The `#[derive_delegate(...)]` attribute asks `#[cgp_component]` to generate that provider: + +```rust +#[cgp_component(AreaCalculator)] +#[derive_delegate(UseDelegate)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} +``` + +`UseDelegate` is a zero-sized provider that treats its `Components` type as a type-level table — a `DelegateComponent` table keyed on the named parameter (`Shape`) — and forwards each method to the delegate that table maps the concrete type to. A context wires it through a nested table inside `delegate_components!`, building the outer entry and the inner lookup in one place: + +```rust +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +This reads in two layers: `MyApp` delegates `AreaCalculatorComponent` to `UseDelegate`, and the inner table — defined inline by `new` — maps `Rectangle` to `RectangleArea` and `Circle` to `CircleArea`. The end effect matches the `open` example above, but the dispatch values live in a named side table reached through `UseDelegate` instead of in `MyApp`'s table directly. This is a legacy dispatch mechanism, retained for compatibility and expected to be deprecated; prefer `open` for new code, but expect to still encounter the `derive_delegate`/`UseDelegate` form when reading existing wiring (see [wiring](wiring.md) for both forms side by side). + +A component may dispatch on more than one parameter by stacking several `#[derive_delegate(...)]` attributes, one per dispatcher. Writing `#[derive_delegate(UseDelegate)]` and `#[derive_delegate(UseInputDelegate)]` generates one impl per dispatcher — the default `UseDelegate` keying on `Code`, plus a user-defined `UseInputDelegate` (an ordinary struct of the same single-parameter shape) keying on `Input` — so each parameter is looked up through its own table. Only the parameter named in a dispatcher's angle brackets is used as the key; the others flow through. Per-type dispatch and higher-order providers compose either way: an `open` entry or a nested delegation table can map each shape to a different `ScaledArea<...>`. + +## Cross-context dependencies through a shared context + +The real leverage of generic-parameter dispatch appears when the main target of a capability is itself a generic parameter, and a supertrait constrains the *context* rather than each parameter type. Consider an area component whose result type is an abstract scalar the context supplies: + +```rust +#[cgp_component(AreaCalculator)] +#[use_type(HasScalarType.Scalar)] +pub trait CanCalculateAreaOfShape { + fn area_of_shape(&self, shape: &Shape) -> Scalar; +} +``` + +Because the shared capability — `HasScalarType` and any value-level injection — lives on the common context, the individual shape types (`Rectangle`, `Circle`) need not implement it themselves; they only know their own geometry. The context provides the shared abstract type ([abstract types](abstract-types.md)): one app might wire `Scalar` to `f64`, another to a fixed-point type, and every shape provider produces that scalar. The context also provides value-level injection — a `GloballyScaledArea` provider can read a global scale factor from a field on the context through an implicit argument and multiply every shape's area by it, so the scale is configured once per context rather than per shape. Most importantly, provider binding is *lazy and per-context*: a `BaseApp` and a `ScaledApp` can wire the very same `Shape` to different providers — `BaseApp` opening `AreaOfShapeCalculatorComponent` and mapping `@AreaOfShapeCalculatorComponent.Rectangle: RectangleArea` to a plain `RectangleArea`, `ScaledApp` mapping `@AreaOfShapeCalculatorComponent.Rectangle: GloballyScaledArea` instead — so the same generic capability resolves to different behavior in each context without either app's shapes knowing about the other. Each context writes its per-shape choices with the `open` statement detailed in [wiring](wiring.md); the legacy `derive_delegate`/`UseDelegate` nested-table form wires the same dispatch and still appears in existing code. Each layer of such nesting can be verified independently with the `#[check_providers]` form of `check_components!`, which is what makes higher-order wiring debuggable; see [checking](checking.md). + +## Related constructs + +Higher-order providers build on the consumer/provider split and the `IsProviderFor` propagation described in [components](components.md), and they are connected to contexts through [wiring](wiring.md), where `UseContext`, the `open` statement, and the legacy nested-table `UseDelegate` forms all live. `UseContext` lets the inner provider fall back to the context's own consumer-trait impl; the `open` statement dispatches a component on a generic parameter by folding per-value entries into the context's own table, with the legacy `UseDelegate` provider (generated by the `derive_delegate` option) doing the same through a separate side table; the abstract result types that make cross-context dependencies work are covered in [abstract types](abstract-types.md) and the type-level keys in [type-level primitives](type-level-primitives.md). Each layer of a nested provider is checked independently through [checking](checking.md). + +Further reference (online docs): +[concepts/higher-order-providers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/higher-order-providers.md), +[reference/attributes/use_provider.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/use_provider.md), +[reference/providers/use_delegate.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_delegate.md), +[reference/attributes/derive_delegate.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/derive_delegate.md). diff --git a/docs/ai/skills/references/macro-grammar.md b/docs/ai/skills/references/macro-grammar.md deleted file mode 120000 index 6116f1cf..00000000 --- a/docs/ai/skills/references/macro-grammar.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/macro-grammar.md \ No newline at end of file diff --git a/docs/ai/skills/references/macro-grammar.md b/docs/ai/skills/references/macro-grammar.md new file mode 100644 index 00000000..ecd90694 --- /dev/null +++ b/docs/ai/skills/references/macro-grammar.md @@ -0,0 +1,341 @@ +# Macro grammar and expansion rules + +The grammar every CGP macro parses, the code each one expands to, and how to read the compiler errors that result — the reference for writing CGP that parses, and for decoding what goes wrong when it does not. + +CGP is almost entirely procedural macros, so "valid CGP code" means two separate things: input the macro's own parser accepts, and output that expands to Rust the compiler accepts. This file covers both. It gives the formal grammar of each macro's custom syntax, states the invariant each expansion preserves, and closes with a decoder for the error messages the two layers produce. Read it to check a form you are unsure about, to predict what a macro emits, or to trace an error back to its cause. Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. + +## How to read the grammars + +The grammars use the notation of the [Rust Reference](https://doc.rust-lang.org/nightly/reference/notation.html), in production-rule form. A production is `Name -> Expression`, one per line inside an `ebnf` block. `x?` is optional, `x*` is zero-or-more, `x+` is one-or-more, `A | B` is a choice, `( … )` groups, and juxtaposition is sequence. A terminal is written in backticks (`` `new` ``, `` `:` ``, `` `@` ``); a nonterminal is a CamelCase name. + +A CamelCase name this file does not define is a production of the **Rust grammar**, reused rather than re-specified — `Type`, `Generics` (the `< … >` parameter list), `GenericArgs` (the `< … >` argument list), `WhereClause`, `TypePath`, and `Expression`. An `ALL_CAPS` name is a Rust lexer token: `IDENTIFIER` is a Rust identifier and `STRING_LITERAL` a string literal. Each grammar describes only the tokens the macro itself parses — the argument tokens inside an attribute's `#[name(…)]` or `#[name{…}]` delimiters, or the body tokens inside a function-like macro's `name!{ … }` — never the delimiters themselves, and never the plain Rust item an attribute is applied to. + +## Reserved identifiers the expansions introduce + +Every macro that turns a trait or impl "inside out" invents identifiers, and it wraps them in double underscores so they cannot collide with a user's names. Recognizing them is what lets you read raw expansions and the errors that quote them. The context type parameter is `__Context__` (overridable), the provider parameter is `__Provider__`, a rewritten `self` receiver is `__context__`, the component key generic is `__Component__`, an inner delegation table is `__Components__`, a looked-up delegate is `__Delegate__`, the `IsProviderFor` params tuple is `__Params__`, a getter's free field tag is `__Tag__`, and a namespace's table generic is `__Table__`. Throughout this file the readable names `Context`/`Provider`/`Params` stand in for these where clarity is served, but the emitted code uses the reserved forms. + +Two more names appear in expansions and resolve through the prelude: any CGP construct the output references is emitted as `::cgp::macro_prelude::`, so an expansion compiles in a crate that has only `cgp` in scope. You never write that path yourself. + +--- + +## Component-definition macros + +### `#[cgp_component]` + +The argument is either a bare provider name or a comma-separated set of keyed values: + +```ebnf +CgpComponentArgs -> ProviderName + | KeyValueArg ( `,` KeyValueArg )* `,`? + +ProviderName -> IDENTIFIER + +KeyValueArg -> `name` `:` ComponentName + | `provider` `:` IDENTIFIER + | `context` `:` IDENTIFIER + +ComponentName -> IDENTIFIER GenericArgs? +``` + +`ProviderName` is shorthand for setting `provider` alone. In the keyed form — written with brace delimiters, `#[cgp_component { … }]` — each of the three keys appears at most once, in any order, and `provider` is required. The `name` key defaults to the provider name with a `Component` suffix (`AreaCalculator` → `AreaCalculatorComponent`), and `context` defaults to `__Context__`. The provider name may not carry generics; the component name may. + +**Expansion invariant.** From one trait, `#[cgp_component]` emits five items plus standard provider impls, and this shape never varies: the **consumer trait** unchanged; the **provider trait** with `Self` moved to a leading `Context` parameter, every `self`/`Self` rewritten to `context`/`Context`, and an `IsProviderFor<{Name}Component, Context, Params>` supertrait; the **consumer blanket impl** (`Context: {Provider}` ⟹ consumer trait); the **provider blanket impl** (delegates through `DelegateComponent<{Name}Component>`); and the zero-sized **`{Name}Component` marker**. Alongside these it emits a `UseContext` impl, a `RedirectLookup` impl (what the `open` statement and namespaces dispatch through), one `UseDelegate` impl per `#[derive_delegate]`, and prefix impls per `#[prefix]`. Any trait generics land *after* the context in the provider trait and are grouped into the `IsProviderFor` `Params` tuple. See [components](components.md) for the full worked expansion. + +### `#[cgp_type]` and `#[cgp_getter]` + +Both reuse `CgpComponentArgs` verbatim and differ only in the default when `provider` is omitted: + +```ebnf +CgpTypeArgs -> CgpComponentArgs // default provider: {AssocType}TypeProvider +CgpGetterArgs -> CgpComponentArgs // default provider: strip leading `Has`, append `Getter` +``` + +`#[cgp_type]` keys its default off the *associated type's* name (`type Scalar;` → `ScalarTypeProvider`, marker `ScalarTypeProviderComponent`); `#[cgp_getter]` strips a leading `Has` from the trait name and appends `Getter` (`HasName` → `NameGetter`). Beyond the shared component output, `#[cgp_type]` adds a `UseType` blanket impl (the associated type *is* `T`) and a `WithProvider` impl adapting the built-in `TypeProvider`; `#[cgp_getter]` adds a `UseFields` impl (always) plus a `UseField` impl and a `WithProvider` impl (only when the trait has exactly one method). See [abstract-types](abstract-types.md) and [functions-and-getters](functions-and-getters.md). + +--- + +## Provider-writing macros + +### `#[cgp_impl]` + +The argument names the provider, optionally preceded by `new` and followed by a component override: + +```ebnf +CgpImplArgs -> `new`? ProviderType ( `:` ComponentType )? + +ProviderType -> Type +ComponentType -> Type +``` + +`new` makes the macro also emit `pub struct ;`. `ProviderType` takes the `Self` position of the generated provider impl — a plain name, a generic provider (`ScaledArea`), or the literal `Self`. The optional `: ComponentType` overrides the component in the generated `IsProviderFor` impl, defaulting to the provider trait name plus `Component`. + +Two forms of the impl header matter. **Omit `for Context`** and the macro inserts `__Context__` for you — this is the preferred form, and it reads like an ordinary trait impl. Write `impl Trait for Context` explicitly only to bound or name the context readably (a lifetime or HRTB the sugar cannot spell). Naming the provider **`Self`** — `#[cgp_impl(Self)]` — is a passthrough: it emits the block unchanged as a direct consumer-trait impl on the concrete context (the `for Context` clause is then *required*), which is how you apply companion attributes like `#[use_provider]` to a hand-written impl; `new` and the component override are ignored in this form. + +**Expansion invariant.** `#[cgp_impl]` desugars to `#[cgp_provider]` (or `#[cgp_new_provider]` with `new`): it moves the context back to the provider trait's leading position, swaps the provider name into `Self`, rewrites `&self` to `__context__: &__Context__`, every `self` to `__context__`, and every `Self` to the context type. The rewrite is scoped to the method bodies — a nested item's own `self`/`Self` is left alone (except inside a `macro!(…)` invocation, which the token rewrite cannot scope and so rewrites anyway). See [components](components.md). + +### `#[cgp_provider]` and `#[cgp_new_provider]` + +Both take a single optional component type; `#[cgp_new_provider]` additionally declares the provider struct (implied by the name, not the argument): + +```ebnf +CgpProviderArgs -> ComponentType? +CgpNewProviderArgs -> ComponentType? + +ComponentType -> Type +``` + +Applied to a provider-trait impl written directly on a provider struct, the macro passes the impl through unchanged and derives the matching `IsProviderFor` impl from it — a copy with the body and associated types stripped, the trait swapped to `IsProviderFor`, and the same `where` clause kept. The trait arguments become `IsProviderFor<{Component}, {Context}, ({trailing params})>`: component first (the argument overrides the default), context second (the provider trait's leading argument), and a tuple of every remaining provider-trait parameter third (`()` when none). A **const argument in the provider trait's own argument list is rejected** with a spanned error, because a const cannot key the type-based `Params` tuple; a const generic on the provider *struct* flows through untouched. + +--- + +## Function, getter, and handler macros + +These macros are applied to a plain Rust function or trait, so most take only an optional name and read the rest of their behavior off the item's shape. Their grammars are small: + +```ebnf +CgpFnArgs -> TraitName? // #[cgp_fn]: default = fn name in PascalCase +CgpComputerArgs -> ProviderName? // #[cgp_computer]: default = fn name in PascalCase +CgpProducerArgs -> ProviderName? // #[cgp_producer]: default = fn name in PascalCase +BlanketTraitArgs -> ContextName? // #[blanket_trait]: default = __Context__ + +TraitName -> IDENTIFIER +ProviderName -> IDENTIFIER +ContextName -> IDENTIFIER +``` + +`#[cgp_auto_getter]`, `#[cgp_auto_dispatch]`, and `#[async_trait]` take **no argument** — they are plain attributes on a trait, with no custom grammar. Their behavior comes entirely from the annotated trait and from separate companion attributes. + +The rest of each function macro's contract is read from the item, not the argument. `#[cgp_fn]` lifts function generics onto both the generated trait and impl while keeping the `where` clause impl-only, turns `#[implicit]` parameters into `HasField` reads, and forbids generics on the desugared *method* (a method-level generic is silently treated as a trait/impl generic). `#[cgp_computer]` collects the function's parameters into one tuple `Input`, chooses the base component and promotion bundle from whether the function is `async` and whether it returns `Result`, and wires the rest of the handler family by promotion; `#[cgp_producer]` requires a zero-parameter, non-`async`, non-generic function. `#[async_trait]` rewrites each `async fn` to `-> impl Future`. See [functions-and-getters](functions-and-getters.md) and [handlers](handlers.md) for the expansions. + +--- + +## Attribute modifiers + +These attributes refine what a host macro generates; none is a standalone macro. The table names each one's form, what it contributes, and which host macros accept it. + +- **`#[implicit]`** — a bare marker on a typed, plain-identifier function argument (`#[implicit] width: f64`); no argument of its own, and `#[implicit(x)]` or `#[implicit = "x"]` is rejected. Removes the argument, adds a `HasField` bound, and binds the value at the top of the body. A *mutable* implicit (its type carries a `&mut`) must be the sole implicit and needs `&mut self`. Host: `#[cgp_fn]`, `#[cgp_impl]`. +- **`#[uses(Trait, Trait

, …)]`** — a comma-separated list of trait bounds, accumulating across repeats. Adds each as a `Self:` impl-side bound. The simple `Trait` form reads like an import and is idiomatic, but any `where`-clause bound is accepted, including associated-type equality (`HasErrorType`); prefer `#[use_type]`'s equality form to pin an abstract type. Host: `#[cgp_fn]`, `#[cgp_impl]`. +- **`#[extend(Trait, Trait

, …)]`** — same simple-path list. Adds each as a *supertrait* of the generated trait (and, in `#[cgp_fn]`, also as an impl bound). Host: `#[cgp_fn]`, `#[cgp_component]`. Not `#[cgp_impl]` (a provider impl has no trait to attach supertraits to). +- **`#[extend_where(Pred, …)]`** — a list of full `where`-clause predicates, including associated-type equality, added verbatim to the generated trait's `where` clause. Host: `#[cgp_fn]` only. +- **`#[impl_generics(Param: Bound, …)]`** — bounded generic parameters added to the generated impl **only**, never the trait. Host: `#[cgp_fn]` only. +- **`#[use_provider(Provider: Trait<…> + …)]`** — completes an inner provider bound by inserting the context as the trait's leading argument (you write `: AreaCalculator`, it means `AreaCalculator`) and moving it into the `where` clause. Several trait bounds on **one** provider are joined with `+`; several **providers** take one stacked attribute each, because a comma-separated list of provider-and-trait pairs does *not* parse — after the first trait the parser is continuing that provider's bounds, so a comma reports `expected +`. This makes the attribute the exception to the one-attribute-comma-separated convention `#[uses]` and `#[use_type]` follow. It only *completes the bound* — it never rewrites the body, which must still call `Provider::method(self)` explicitly. Host: `#[cgp_impl]`, `#[cgp_fn]`. +- **`#[derive_delegate(Wrapper)]`** — generates a `UseDelegate`-style dispatcher impl keyed on `Param`; repeat for several dispatchers; the key may be a tuple `Wrapper<(A, B)>`. **Legacy** — prefer the `open` statement; see [wiring](wiring.md). Host: `#[cgp_component]`. +- **`#[prefix(@Path in Namespace)]`** — registers the component into `Namespace` under `@Path`, emitting one `RedirectLookup` impl; repeat for several namespaces. Host: `#[cgp_component]`. +- **`#[default_impl(T in DefaultImpls1)]`** — registers a `#[cgp_impl]` provider as a namespace's per-type default for `T`. Host: `#[cgp_impl]`. + +The check macros carry their own modifiers, covered with them below: `#[check_trait(Name)]` and `#[check_providers(…)]` on a table, `#[check_params(…)]` and `#[skip_check]` on an entry. + +### `#[use_type]` + +This attribute has enough structure to warrant a grammar of its own: + +```ebnf +UseTypeArgs -> UseTypeSpec ( `,` UseTypeSpec )* `,`? + +UseTypeSpec -> TraitPath `.` TypeItems ( `in` ContextPath )? + +ContextPath -> TypePath +TraitPath -> TypePath + +TypeItems -> UseTypeIdent + | `{` UseTypeIdent ( `,` UseTypeIdent )* `,`? `}` + +UseTypeIdent -> IDENTIFIER ( `as` IDENTIFIER )? ( `=` Type )? +``` + +The `.` (not `::`) after the trait path starts the associated-type list — a trait path keeps its own `::` segments and may carry generics. Omitting the `in ContextPath` suffix defaults the rewrite target to `Self`; an `in Types` suffix rewrites against a named generic parameter and adds `Types: Trait` as a `where` bound rather than a supertrait (`in` is a reserved keyword, so it can never be mistaken for part of a type, and reads like the `in` in `#[prefix(@Path in Namespace)]`). In each `UseTypeIdent`, `as` gives a local alias to write in signatures, and `= Type` pins the type with an equality bound (accepted on `#[cgp_fn]`/`#[cgp_impl]`, **rejected on `#[cgp_component]`**, whose trait definition cannot carry the impl-side equality). The macro rewrites every bare mention of the imported identifier (or alias) to the fully-qualified `::Type`. Host: `#[cgp_fn]`, `#[cgp_impl]`, `#[cgp_component]`. See [abstract-types](abstract-types.md). + +--- + +## Wiring and checking macros + +### `delegate_components!` + +The body is an optional generic list and `new` keyword, a target type, and a brace-delimited table: + +```ebnf +DelegateComponents -> Generics? `new`? TargetType `{` TableBody `}` + +TargetType -> Type + +TableBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? + +Statement -> OpenStmt | NamespaceStmt | ForStmt + +OpenStmt -> `open` ( `{` Type ( `,` Type )* `,`? `}` | Type ) `;` + +Mapping -> Key `:` ProviderValue + | Key `->` ProviderValue + | Key `=>` PathValue + +Key -> SingleKey | MultiKey | PathKey +SingleKey -> Generics? Type +MultiKey -> `[` SingleKey ( `,` SingleKey )* `,`? `]` +PathKey -> Generics? `@` PathHead + +PathHead -> PathSegment ( `.` PathHead )? + | `[` PathSegment ( `,` PathSegment )* `,`? `]` ( `.` PathHead )? + | `{` PathHead ( `,` PathHead )* `,`? `}` + +PathSegment -> Generics? Type + +PathValue -> `@` PathSegment ( `.` PathSegment )* + +ProviderValue -> Type + | IDENTIFIER `<` `new` InnerTable `>` + +InnerTable -> IDENTIFIER GenericArgs? `{` TableBody `}` +``` + +Every **statement must lead the block, before any mapping** — the parser reads statements first, so an `open`, `namespace`, or `for` written after a `Key: Value` line fails to parse (see error decoding below). A leading `Generics` list makes the whole table generic over the target; `new` also emits the target struct. Of the three mapping operators, `` `:` `` (map to a provider) is the common one. `` `->` `` forwards the key to *another table's* entry for that same key, adding a `Value: DelegateComponent` bound — a plain-wiring form with no namespace involved. `` `=>` `` redirects the lookup along an `@`-path and is the namespace mechanism, of which `open` is the sugared special case. The parser accepts any operator against any key form, but far fewer combinations are useful than the grammar allows. + +A `Key` may be one type, a bracketed list expanding to one entry each, or an `@`-path. **The two grouping forms inside a path key are different and are easy to confuse**: a bracketed group holds alternative segments for *one position* and may be followed by `` `.` `` and more path (`@app.[FooComponent, BarComponent].[u64, String]`), while a braced group holds alternative *whole tails* and ends the path, so only it can nest and its alternatives may differ in length (`@app.{ErrorRaiserComponent.{&'static str, String}, ErrorWrapperComponent}`). Both fan out to the cartesian product with the rest of the path. A `PathValue` — the right side of a `` `=>` `` — takes no groups. The nested-table `ProviderValue` form (`UseDelegate`) defines an inner table in place — the legacy dispatch form, whose inner name may itself carry generics (`UseDelegate { … }>`) and whose wrapper need not be `UseDelegate`. An `OpenStmt` opens one component (braces optional) or several (braces required) for per-value `@Component.Key: Provider` wiring folded into the context's own table. **No attributes are accepted** on the table or any entry; an unknown attribute is a spanned error, not silently dropped. See [wiring](wiring.md). + +**Expansion invariant.** Each plain `Key: Provider` entry emits a `DelegateComponent` impl with `Delegate = Provider` plus a forwarding `IsProviderFor` impl that threads the provider's dependencies back through the target. An `open Component;` header emits `DelegateComponent` = `RedirectLookup>`, and each `@Component.Value: Provider` entry stores that provider under the path key `PathCons>` on the target — **the tail is a generic `__Wildcard__` parameter, not `Nil`**, so one entry answers a redirect of any length; the `RedirectLookup` impl appends the dispatch parameter onto the path at resolution time. An `open C;` header and a `C => @C,` mapping produce the identical impl. + +### `delegate_and_check_components!` + +The same table shape, with a table-level check-trait attribute and per-entry check attributes: + +```ebnf +DelegateAndCheck -> TableAttr* Generics? `new`? TargetType `{` TableBody `}` + +TableAttr -> `#` `[` `check_trait` `(` IDENTIFIER `)` `]` + +TableBody -> Statement* ( CheckedMapping ( `,` CheckedMapping )* `,`? )? + +CheckedMapping -> EntryAttr? Mapping + +EntryAttr -> `#` `[` `check_params` `(` Type ( `,` Type )* `,`? `)` `]` + | `#` `[` `skip_check` `]` +``` + +`Mapping`, `Key`, `ProviderValue`, and `Statement` are exactly `delegate_components!`'s, so the **wiring** half accepts everything that macro does. The **check** half does not: a check entry is derived only from a mapping keyed on a component *name* (a `SingleKey` or `MultiKey`, under either `` `:` `` or `` `->` ``), so an `@`-path key, a `` `=>` `` redirect, and every `open`/`namespace`/`for` statement is wired and left **silently unchecked** — no warning marks the gap, which is the practical reason larger codebases keep the two macros apart. Its check trait defaults to `__CanUse{Context}` (distinct from `check_components!`'s `__Check{Context}`, so both fit one module). Each mapping carries at most one `EntryAttr`; `#[check_params(…)]` supplies the concrete generic parameters a parameterized component's check needs, and `#[skip_check]` wires without checking — the two are mutually exclusive. See [checking](checking.md). + +### `check_components!` + +One or more check tables, each with optional attributes, generics, a context, an optional `where` clause, and a brace list of entries: + +```ebnf +CheckComponents -> CheckTable+ + +CheckTable -> TableAttr* Generics? ContextType WhereClause? `{` CheckEntries `}` + +TableAttr -> `#` `[` `check_trait` `(` IDENTIFIER `)` `]` + | `#` `[` `check_providers` `(` Type ( `,` Type )* `,`? `)` `]` + +ContextType -> Type + +CheckEntries -> ( CheckEntry ( `,` CheckEntry )* `,`? )? + +CheckEntry -> CheckKey ( `:` CheckValue )? + +CheckKey -> Type + | `[` Type ( `,` Type )* `,`? `]` + +CheckValue -> CheckParam + | `[` CheckParam ( `,` CheckParam )* `,`? `]` + +CheckParam -> Generics? Type +``` + +A `CheckEntry`'s value is omitted for a parameterless component and required otherwise; a bracketed key or value expands to the cartesian product, so a set of components is checked against a set of parameters. `#[check_trait(Name)]` overrides the derived `__Check{Context}` name. `#[check_providers(…)]` changes the check: instead of asserting `CanUseComponent` on the context, it asserts `IsProviderFor` on each listed provider, so each layer of a higher-order stack is verified on its own line. See [checking](checking.md). + +**Expansion invariant.** A check table emits one marker trait aliasing the asserted bound plus one empty impl per entry — the impl compiles only if the bound holds. The default form aliases `CanUseComponent` and implements it for the context; `#[check_providers(…)]` aliases `IsProviderFor` and implements it for each provider. A successful build *is* the passing assertion; the checks have no runtime existence. + +### `cgp_namespace!` + +The body is an optional generic list and `new`, a namespace name, an optional parent, and a table: + +```ebnf +CgpNamespace -> Generics? `new`? NamespaceName ( `:` ParentNamespace )? `{` NamespaceBody `}` + +NamespaceName -> IDENTIFIER GenericArgs? +ParentNamespace -> TypePath GenericArgs? + +NamespaceBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? +``` + +The mappings are `delegate_components!`'s `Mapping` — most often a `` `=>` `` redirect to an `@`-path or a `` `:` `` direct provider. The colon between `NamespaceName` and `ParentNamespace` is the *inheritance* colon, distinct from a mapping's `:`; naming a parent makes the namespace resolve everything the parent does plus its own entries. This macro also owns the two statement forms a context's `delegate_components!` table uses to consume a namespace: + +```ebnf +Statement -> NamespaceStmt | ForStmt + +NamespaceStmt -> `namespace` IDENTIFIER `;` + +ForStmt -> `for` `<` IDENTIFIER `,` IDENTIFIER `>` `in` TypePath WhereClause? + `{` ( NormalMapping ( `,` NormalMapping )* `,`? )? `}` + +NormalMapping -> Key `:` ProviderValue +``` + +A `NamespaceStmt` forwards every unresolved lookup through the named namespace. A `ForStmt` binds a key variable and a provider variable, reads each entry of the table named after `in`, and emits one `:` mapping per entry; its optional `where` clause is merged into every impl it generates. Like `delegate_components!`, the body accepts no attributes on any entry. See [namespaces](namespaces.md). + +--- + +## Type-level construction macros + +The four type-level macros build the vocabulary the rest of CGP keys on, and their grammars are minimal: + +```ebnf +SymbolInput -> STRING_LITERAL + +ProductInput -> ( Type ( `,` Type )* `,`? )? // Product! (type position) +ProductExpr -> ( Expression ( `,` Expression )* `,`? )? // product! (value position) + +SumInput -> ( Type ( `,` Type )* `,`? )? + +PathInput -> `@` PathSegment ( `.` PathSegment )* +PathSegment -> Type +``` + +Each expands to a fixed spine, and knowing the spine is what lets you read a printed type. `Symbol!("abc")` becomes `Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>` — the leading const is the *byte* length (so `Symbol!("世界")` records `6`), present only because stable Rust cannot compute a `Chars` length in const position. `Product![A, B]` becomes `Cons>` and `product![…]` builds the matching value; the empty forms are `Product![]`/`product![]` over `Nil`. `Sum![A, B]` becomes `Either>`, terminating in the uninhabited `Void` rather than `Nil`. `Path!(@app.error.FooComponent)` becomes a `PathCons` chain in which a lowercase, non-primitive segment is a `Symbol!` and a capitalized or primitive segment stays the named type. See [type-level-primitives](type-level-primitives.md). + +--- + +## Derives + +The data derives (`#[derive(HasField)]`, `HasFields`, `CgpData`, `CgpRecord`, `CgpVariant`, `BuildField`, `ExtractField`, `FromVariant`) take no custom arguments — they are ordinary derives whose behavior is fixed by the item they annotate. Their one grammar-shaped constraint is on **variant shape**: the enum derives (`CgpVariant`, `CgpData` on an enum, `ExtractField`, `FromVariant`) require every variant to be a single unnamed-field tuple variant (`Circle(Circle)`), because each variant's payload must be one nameable type. A fieldless (`Empty`), multi-field (`Pair(A, B)`), or struct-style (`Named { x: A }`) variant fails with **"Expected variant to contain exactly one unnamed field"** — wrap a richer payload in a dedicated struct. A named struct field is keyed by `Symbol!`, a tuple-struct field by `Index`. See [extensible-data](extensible-data.md). + +--- + +## Reading error messages + +CGP errors come from two layers — the macro's own parser, and the compiler resolving the expanded code — and each has a recognizable vocabulary. The parser errors are usually clear because most macros validate with spanned messages; the type errors are the ones that need decoding, because they name generated traits rather than the mistake you made. + +### Wiring and dependency errors + +**`the trait bound X: IsProviderFor is not satisfied`** is the most common, and it never means "write an `IsProviderFor` impl." Read it as *the provider `X` is not a valid provider for this component on `Ctx`, because one of its impl-side dependencies is unmet*. The truly missing bound is named nearby (a `HasField`, an abstract type, another capability); that is the thing to supply. `IsProviderFor` exists precisely to surface that named bound instead of a bare "trait not implemented" — see [components](components.md). + +**`the trait bound Ctx: DelegateComponent is not satisfied`** means the component was never wired on `Ctx` at all — add the `delegate_components!` entry. Contrast this with the `IsProviderFor` failure above, which means the component *was* wired but to a provider whose dependencies fail. A [check](checking.md) distinguishes the two for you: a failed `DelegateComponent` bound is "not wired," a failed `IsProviderFor` bound is "wired but unsatisfied." + +**A `CanUseComponent` error** comes from a `check_components!` or `delegate_and_check_components!` assertion firing at the wiring site — which is the point of checking. The named unmet bound is the first impl-side dependency the compiler could not satisfy; trace it through the provider chain to its root. Not every unmet bound is a CGP component: a plain trait or blanket-impl bound a provider also needs has no `…Component` marker and cannot be surfaced through wiring, so it must be satisfied by ordinary Rust means. + +**`overflow evaluating the requirement …`** on a component usually means a `UseContext` cycle — a component wired directly to `UseContext` whose only impl of that component *is* that delegation, so the context implements the consumer trait by calling a provider that implements the provider trait by calling the consumer trait. `UseContext` belongs as another provider's inner provider, not as a context's own delegate for the same component; see [wiring](wiring.md). + +### Decoding printed type-level values + +A long `Symbol>>` in an error is just a **field-name string** — read the `Chars` characters in order (here `name`) and ignore the leading length. A `Cons<…, Cons<…, Nil>>` is a record field list, an `Either<…, Either<…, Void>>` an enum variant list, and a `PathCons<…, …>` a namespace/redirect route. The [type-level-primitives](type-level-primitives.md) sub-skill is the full decoder ring; the shortcut is that any nested type ending in `Nil` is a product list and any ending in `Void` is a sum. + +### Errors that underline the whole macro block + +A coherence conflict (**`E0119`, conflicting implementations**) or an unconstrained-parameter error (**`E0207`**) whose caret covers an *entire* macro invocation rather than one entry is a span artifact, not a sign the whole block is wrong. The macros stamp generated items with a re-span onto the originating token, but a synthesized token that has lost its span falls back to the invocation site. When you see `E0119` between two generated impls, look for a **duplicated wiring entry** or two `open`/dispatch keys that overlap on the same type; when you see `E0207`, look for a generic parameter that appears in a provider or `#[cgp_fn]` header but is not bound by any argument or `where` clause. + +### Macro-parser errors + +These fire before expansion and are worth recognizing by shape. An **`expected :` parse error near an `open`/`namespace`/`for`** almost always means a statement was written *after* a mapping — statements must lead the block. An **"unsupported attribute"** (or a spanned rejection) on a `delegate_components!` / `cgp_namespace!` entry means those macros accept no attributes there at all. A **const generic** on a `#[cgp_component]` trait or in a provider trait's argument list is rejected, because CGP dispatches on types, not values (an associated `const` item on the trait is fine). **"Expected variant to contain exactly one unnamed field"** is the variant-derive shape rule above. A **default-bodied `async fn`** inside `#[async_trait]` is unsupported (the body is not wrapped in `async {}`), and a **generic method on a `#[cgp_auto_dispatch]` trait** is rejected because Rust lacks the quantified bound the blanket impl would need. + +--- + +## Further reference + +This file is a companion to the per-topic sub-skills, which show the same expansions in worked +context: [components](components.md), [wiring](wiring.md), [checking](checking.md), +[functions-and-getters](functions-and-getters.md), [abstract-types](abstract-types.md), +[higher-order-providers](higher-order-providers.md), [namespaces](namespaces.md), +[handlers](handlers.md), [extensible-data](extensible-data.md), and +[type-level-primitives](type-level-primitives.md). For the authoritative, exhaustive grammar and +expansion of any single construct — every accepted form, every corner case, and the implementing +source — fetch the online knowledge base at +`https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp`, whose `reference/macros/` +documents carry the formal Syntax Grammar and Expansion sections these grammars are drawn from. diff --git a/docs/ai/skills/references/modern-idioms.md b/docs/ai/skills/references/modern-idioms.md deleted file mode 120000 index fb39eb5f..00000000 --- a/docs/ai/skills/references/modern-idioms.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/modern-idioms.md \ No newline at end of file diff --git a/docs/ai/skills/references/modern-idioms.md b/docs/ai/skills/references/modern-idioms.md new file mode 100644 index 00000000..60ef40cb --- /dev/null +++ b/docs/ai/skills/references/modern-idioms.md @@ -0,0 +1,284 @@ +# Modern idioms: reading and modernizing CGP + +The map from each older, explicit CGP form to the modern idiom you should prefer — so you can recognize legacy syntax in existing code, understand what it desugars to, and rewrite it in the vanilla-looking form. + +CGP's explicit forms came first, and they are still exactly what the macros desugar to, so you will keep meeting them in generated code, in reference Expansion sections, and in any codebase written before the newer idioms landed. The modern idioms exist to lower the barrier to entry: they let a provider look like an ordinary trait `impl`, a dependency look like a `use` import, and an abstract type look like a plain generic. **Prefer the modern idiom in all new code, and reach for an explicit form only when a construct genuinely cannot express the case** (the closing section lists those exceptions). This file is the bidirectional reference: read it forward to write modern CGP, and backward to decode legacy CGP you are asked to read or update. Assume `use cgp::prelude::*;`; the CGP version is v0.8.0. + +Each shift below shows the legacy form, the modern equivalent, and the mechanical rule that connects them. All of them desugar to the same generated code, so a rewrite is a readability change, never a behavioral one. + +## Provider shape: `#[cgp_impl]` over the raw provider forms + +Write a provider with [`#[cgp_impl]`](components.md), which keeps `self`, `Self`, and the consumer method signatures, rather than the lower-level [`#[cgp_provider]`/`#[cgp_new_provider]`](components.md), which require the inside-out provider-trait shape (the context moved to a leading type parameter, the receiver written as `context: &Context`). The legacy form: + +```rust +#[cgp_new_provider] +impl AreaCalculator for RectangleArea +where + Context: HasField, + Context: HasField, +{ + fn area(context: &Context) -> f64 { + *context.get_field(PhantomData::) + * *context.get_field(PhantomData::) + } +} +``` + +becomes, with `#[cgp_impl]` and [`#[implicit]`](functions-and-getters.md) arguments: + +```rust +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} +``` + +`#[cgp_impl]` desugars back to `#[cgp_provider]`/`#[cgp_new_provider]`, so the raw forms remain what you read in expansions. Write the raw form yourself only when you need the inside-out shape directly — for instance a provider whose `Self` is a concrete context, or a bound the sugar cannot spell. + +## Context parameter: omit `for Context` + +Inside a `#[cgp_impl]` block, prefer the unqualified `impl AreaCalculator` and let the macro insert the reserved context parameter, rather than naming it as `impl AreaCalculator for Context`. Omitting `for Context` is what makes the provider read like an ordinary trait `impl`. Name the context explicitly only when you must bound it with a lifetime or higher-ranked bound the sugar cannot carry, or refer to it by a readable name. So the legacy + +```rust +#[cgp_impl(new RectangleArea)] +impl AreaCalculator for Context +where + Context: HasDimensions, +{ + fn area(&self) -> f64 { self.width() * self.height() } +} +``` + +shortens to the bare header, with the bound moved to `#[uses]`: + +```rust +#[cgp_impl(new RectangleArea)] +#[uses(HasDimensions)] +impl AreaCalculator { + fn area(&self) -> f64 { self.width() * self.height() } +} +``` + +## Dependencies: `#[uses]` and `#[use_provider]` over hand-written `where` + +State a provider's [impl-side dependencies](components.md) with [`#[uses(...)]`](functions-and-getters.md) and [`#[use_provider(...)]`](higher-order-providers.md) rather than hand-written `where` clauses, so a dependency reads like a `use` import. `#[uses(CanCalculateArea)]` adds `Self: CanCalculateArea`; `#[use_provider(Inner: AreaCalculator)]` adds `Inner: AreaCalculator`, filling in the `` context argument a provider-trait bound needs. The legacy `where` forms: + +```rust +#[cgp_impl(new ScaledArea)] +impl AreaCalculator for Context +where + Self: HasField, + InnerCalculator: AreaCalculator, +{ + fn area(&self) -> f64 { /* ... */ } +} +``` + +become the attribute forms plus an implicit argument: + +```rust +#[cgp_impl(new ScaledArea)] +#[use_provider(InnerCalculator: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { /* ... */ } +} +``` + +`#[uses]` accepts any bound a `where` clause allows, including one carrying associated-type equality, though the simple `Trait` form is idiomatic. Where that bound pins an **abstract type** — `Self: HasErrorType` — express it with the [`#[use_type]` equality form](#abstract-types-use_type-over-supertrait--selftype) below, rather than spelling the equality in `#[uses]` or writing a hand-written `where` clause; only equality on a trait you would never import from with `#[use_type]` (`Iterator`) stays an explicit `where` clause. When a provider imports several capabilities, combine them into one `#[uses]` attribute separated by commas — `#[uses(CanQueryUserBalance, CanRaiseHttpError)]` — rather than stacking the attribute repeatedly; one combined attribute reads as a single dependency list, and splitting across repeats behaves identically but is for when a real reason calls for it. **`#[use_provider]` is the exception and does not follow this convention:** a comma-separated list of provider-and-trait pairs does not parse, so several inner providers take one stacked attribute each, and `+` is what joins several trait bounds on a single provider. + +## Field reads: `#[implicit]` over a getter trait + +Read a value from a context field with an [`#[implicit]`](functions-and-getters.md) argument — in a `#[cgp_impl]` method exactly as in `#[cgp_fn]` — rather than declaring a getter trait and importing it. This is the default for *any* field a provider reads from its own context, since an implicit argument reads from `self` and takes a plain `&T` by reference without cloning — even a field several providers each read is written as the same implicit argument in each, not promoted to a getter. An implicit argument names both a local and the field it comes from, keeping the `HasField` machinery out of sight. The getter-trait version: + +```rust +#[cgp_auto_getter] +pub trait HasDimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; +} + +#[cgp_impl(new RectangleArea)] +#[uses(HasDimensions)] +impl AreaCalculator { + fn area(&self) -> f64 { self.width() * self.height() } +} +``` + +collapses to reading the fields directly: + +```rust +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} +``` + +Use `#[cgp_auto_getter]` sparingly — only where an implicit argument cannot reach. There are three such cases. The field lives on a type *other* than the provider's own context, so the getter is required as a `where` bound on that type (`Request: HasBasicAuthHeader`) and there is no `self` field for an implicit argument to read; the accessor must exist as a *named* capability other code depends on through `#[uses(HasName)]` or a supertrait; or the getter carries an *associated type inferred from the field* so the type stays abstract for callers. Everywhere else — including a same-context field read shared by several providers — prefer the implicit argument. Avoid `#[cgp_getter]` in ordinary code, since its full wireable component is for the advanced case of choosing the source field per context at wiring time. + +## Abstract types: `#[use_type]` over supertrait + `Self::Type` + +Bring an abstract type into a definition with [`#[use_type]`](abstract-types.md) and write it as a bare alias, rather than declaring the owning trait as a supertrait and qualifying every use as `Self::Type`. The attribute does both jobs: it adds the supertrait (on `#[cgp_component]`) or `where` bound (on `#[cgp_impl]`/`#[cgp_fn]`) *and* rewrites each bare `Error`/`Scalar` to its fully-qualified path. This is preferred even for the built-in error type — the legacy + +```rust +#[cgp_component(Loader)] +pub trait CanLoad: HasErrorType { + fn load(&self, path: &str) -> Result; +} +``` + +becomes + +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} +``` + +One rule bounds the rewrite: it fires only on the bare identifier of an *imported* type. A construct's own **local associated type stays qualified as `Self::Assoc`** — a handler that declares `type Output` writes `Self::Output`, never a bare `Output`. So a mixed signature like `Result` is exactly right: the local `Self::Output` stays qualified, the imported `Error` is bare. + +When a definition imports types from several traits, combine them into one `#[use_type]` attribute with the trait paths comma-separated — `#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasErrorType.Error)]` — rather than stacking one attribute per trait; the combined form reads as a single import list. Several types from one trait use the braced list (`#[use_type(HasFooType.{Foo, Bar})]`). Stacking repeated `#[use_type]` attributes behaves identically, but reach for it only when a real reason calls for it. + +Prefer `#[use_type]` even when the type lives on a **foreign** type rather than `Self` — a type named by a generic parameter — using the trailing `in Context` clause. It rewrites the bare alias to `::Assoc` *and* supplies `Context: Trait`, so the hand-written + +```rust +#[cgp_auto_getter] +pub trait HasLoggedInUser +where + App: HasUserIdType, +{ + fn logged_in_user(&self) -> &Option; +} +``` + +becomes + +```rust +#[cgp_auto_getter] +#[use_type(HasUserIdType.UserId in App)] +pub trait HasLoggedInUser { + fn logged_in_user(&self) -> &Option; +} +``` + +with `App: HasUserIdType` supplied for you, so the plain `` parameter and the bare `UserId` are enough. + +Import a type with `#[use_type]` even when it *already* arrives transitively — as the supertrait of a trait pulled in by `#[uses]`. When `CanCreateFoo` has `HasFooType` as a supertrait, prefer re-importing over leaning on the transitive `Self::Foo`: + +```rust +#[cgp_fn] +#[uses(CanCreateFoo)] +#[use_type(HasFooType.Foo)] // re-import: bare `Foo`, explicit `HasFooType` dep +fn bar(&self) -> Foo { self.create_foo(42) } +``` + +instead of + +```rust +#[cgp_fn] +#[uses(CanCreateFoo)] +fn bar(&self) -> Self::Foo { self.create_foo(42) } // relies on the reachable supertrait +``` + +The re-import re-adds a harmless (already-implied) `Self: HasFooType` and rewrites the bare `Foo`, so `#[uses]` states the *capability* dependency and `#[use_type]` states the *type* dependency, both visible rather than one riding in silently. + +`#[use_type]` also *pins* an abstract type with the equality form `{Assoc = Type}`, which is the modern replacement for a hand-written `where Self: HasXType` clause — reach for it whenever a provider constrains an abstract type to a concrete one, rather than leaving the equality as an explicit `where`. On a `#[cgp_impl]`, the legacy + +```rust +#[cgp_impl(new DisplayHttpError)] +impl HttpErrorRaiser +where + Self: HasErrorType, + Code: IsStatusCode, + Detail: Display, +{ + fn raise_http_error(_code: Code, detail: Detail) -> AppError { /* ... */ } +} +``` + +becomes, with the equality moved into the attribute: + +```rust +#[cgp_impl(new DisplayHttpError)] +#[use_type(HasErrorType.{Error = AppError})] +impl HttpErrorRaiser +where + Code: IsStatusCode, + Detail: Display, +{ + fn raise_http_error(_code: Code, detail: Detail) -> AppError { /* ... */ } +} +``` + +The attribute emits the same `Self: HasErrorType` bound (and would rewrite any bare `Error`, though here the body names the concrete `AppError` directly). The right-hand side is substituted too, so an imported alias is grounded wherever it appears in it. Naming *another* alias outright unifies two abstract types: `#[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})]` emits `Self: HasHashedPasswordType::Password>`. An alias *nested inside* the type is grounded in place: `#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits `Self: HasTransactionType::Db>>`, which is how a pin says "a transaction of *this* database" without naming a concrete engine. Because the equality form produces an impl-side bound, it belongs on `#[cgp_impl]` and `#[cgp_fn]` only — it is rejected on `#[cgp_component]`. The one equality bound that *stays* a hand-written `where` clause is one on a trait you would never `#[use_type]` from, such as `Iterator`. + +## Supertraits: `#[extend]` over native `:` syntax + +Add a non-type capability supertrait to a `#[cgp_component]` trait with [`#[extend(...)]`](functions-and-getters.md) rather than native `pub trait CanDoX: Supertrait` syntax. Both produce the same trait, but `#[extend]` reads as importing a capability the trait re-exports, which is what a CGP supertrait actually is — a declared dependency, not a base class. It pairs symmetrically with `#[uses]`: `#[uses]` imports a capability for private use, `#[extend]` re-exports one as part of the trait's contract. The native + +```rust +#[cgp_component(Greeter)] +pub trait CanGreet: HasName { + fn greet(&self) -> String; +} +``` + +becomes + +```rust +#[cgp_component(Greeter)] +#[extend(HasName)] +pub trait CanGreet { + fn greet(&self) -> String; +} +``` + +Use `#[extend]` for a supertrait that contributes only a *capability* (like `HasName`, read through the getter); use `#[use_type]` instead when the supertrait is an abstract-type component whose associated type the signature names, since `#[use_type]` also rewrites the type. In `#[cgp_fn]`, whose `where` clauses are impl-side dependencies, `#[extend]` is the only way to declare a supertrait at all. + +## Per-type dispatch: `open` and namespaces over `UseDelegate` + +Route a generic-parameter component to a different provider per type with the [`open` statement](wiring.md) or a [namespace](namespaces.md), rather than the legacy [`UseDelegate`](higher-order-providers.md) nested-table pattern. Both ride the `RedirectLookup` impl every `#[cgp_component]` already generates, so they store the per-type entries directly on the context with no wrapper type. The legacy nested table: + +```rust +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} +``` + +becomes the inline `open` form: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +Because `open` and namespaces ride `RedirectLookup`, a **new** component you dispatch this way needs no [`#[derive_delegate(UseDelegate)]`](macro-grammar.md) attribute — that attribute exists only to generate the `UseDelegate` provider the nested-table form relies on. You will still see `#[derive_delegate]` on some CGP-shipped components (the error and handler families) so their existing `UseDelegate` wiring keeps working, but code dispatching only through `open` or a namespace can omit it. Prefer `open` for a context wiring its own components, and a namespace when a reusable, inheritable dispatch table is worth sharing. + +## When the explicit forms are still right + +A handful of cases genuinely need an explicit form, and choosing one there is not a regression. Keep an explicit `where` clause for an associated-type-equality bound on a non-`#[use_type]` trait — `Iterator`, `From`, and the like — which reads more clearly as a `where` clause than in an import-shaped `#[uses]` (which does accept it); but note the exception's own exception: an equality bound on an **abstract-type** trait (`Self: HasErrorType`) is *not* one of these, because the [`#[use_type]` equality form](#abstract-types-use_type-over-supertrait--selftype) `#[use_type(HasErrorType.{Error = AppError})]` does express it and is preferred; leave only equality on a non-`#[use_type]` trait as a hand-written `where`. Name the context explicitly, `impl Trait for Context`, to attach a lifetime or higher-ranked bound the sugar cannot carry, or when `Self` must be a concrete context (the `#[cgp_impl(Self)]` passthrough is the direct-impl case). Reach for `#[cgp_getter]` when you specifically want to choose which field a getter reads per context at wiring time. Write a raw provider-trait `impl` when you need the inside-out shape directly. And keep a local associated type qualified as `Self::Output` always — it is never a `#[use_type]` import. + +## Reading pre-0.7 code: renamed and removed names + +Very old code and pre-0.7 write-ups can use names that no longer exist, as opposed to the still-valid legacy *forms* above. These do not compile against current CGP, so treat them as signals to translate, not to copy: the attribute `#[cgp_context]` was removed (a context is now assembled with `delegate_components!` and the derive/getter machinery rather than a dedicated context macro), and the abstract-type provider trait once called `ProvideType` is now `TypeProvider`. When you meet a name the current prelude does not export, assume it was renamed or removed rather than that you are misremembering, and fetch the online knowledge base's changelog and reference to find its modern spelling; do not reintroduce a removed name into new code. + +## Related sub-skills + +Every shift here is a shortcut over a construct documented in full elsewhere: provider forms in [components](components.md), field injection and `#[uses]`/`#[extend]` in [functions-and-getters](functions-and-getters.md), abstract types and `#[use_type]` in [abstract-types](abstract-types.md), the inner-provider pattern in [higher-order-providers](higher-order-providers.md), per-type dispatch in [wiring](wiring.md) and [namespaces](namespaces.md), and the grammar and expansion of every form in [macro-grammar](macro-grammar.md). For how much CGP a problem needs in the first place, see [modularity-hierarchy](modularity-hierarchy.md). diff --git a/docs/ai/skills/references/modularity-hierarchy.md b/docs/ai/skills/references/modularity-hierarchy.md deleted file mode 120000 index f534e9ce..00000000 --- a/docs/ai/skills/references/modularity-hierarchy.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/modularity-hierarchy.md \ No newline at end of file diff --git a/docs/ai/skills/references/modularity-hierarchy.md b/docs/ai/skills/references/modularity-hierarchy.md new file mode 100644 index 00000000..884a9447 --- /dev/null +++ b/docs/ai/skills/references/modularity-hierarchy.md @@ -0,0 +1,204 @@ +# Modularity hierarchy + +A spectrum of how decoupled an implementation can be from the type it serves, from plain generic functions up to per-provider wiring, so you can pick how much CGP machinery a problem actually needs. + +CGP is not all-or-nothing. The same capability — here, serializing a value with Serde — can be expressed at several levels of modularity, each more decoupled than the last and each carrying more machinery in exchange. This page walks the spectrum on one running example so a reader can stop at the first level that solves the problem rather than reaching for the heaviest tool by reflex. Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. + +## Two questions decide the level + +Before the levels, the two things that actually vary, because the level numbers name consequences while these name causes. + +**What is the `Self` type?** Either a **value context** — the data the capability operates on, like the `Vec` being serialized — or an **environmental context**, a type that exists to supply choices and capabilities rather than to be operated on, like an application. Both are contexts: both sit in `Self` and both carry a wiring table. An environmental context often has no fields at all, since its whole job is to be a name the table hangs off. + +**What does the capability target?** Either `Self` (**self-targeted**: `CanGreet`, `HasErrorType`, every getter) or a type parameter that `Self` only decides for (**parameter-targeted**: `CanSerializeValue`, `CanCalculateArea`). A parameter alone does not settle this — in `CanCompute` the target is `Input` while `Code` is a selector the wiring dispatches on. + +Three combinations occur: a **value context** targeting `Self` (Level 3's retrofit case), an **environmental context** targeting `Self` (also Level 3, and where most CGP code lives), and an **environmental context** targeting a parameter (Levels 4–5). + +**The escape from coherence happens when `Self` becomes a type you own, not when a parameter appears.** This is the part most easily misread. Wired on a foreign value type, a self-targeted component still gets one provider program-wide. Wired on an environmental context, the constraint "one wiring per type" stops binding, because you can define a second context: `App` and `TestApp` each choose their own `CanSendEmail` provider with no parameter anywhere. What Level 4's parameter adds is the ability to make that choice about types you do *not* own. + +Vanilla Rust idiomatically supports only the first combination — `impl Display for String` — which is why a Rust programmer arrives with no vocabulary for the others. The other two are legal but unrewarding: an environmental context works until you factor two implementations into blanket impls and they overlap, and a parameter-targeted trait on an application type compiles fine but needs a hand-written body for every context-and-type pair. CGP's contribution is making the implementations reusable, which is what turns each arrangement into a technique. + +## The coherence problem the hierarchy escapes + +What forces this hierarchy to exist is Rust's coherence rules, which guarantee that every trait +lookup resolves to one globally unique implementation. Two rules enforce that uniqueness. The +**overlap rule** forbids two implementations that could both apply to the same type — you cannot +blanket-implement `Serialize` for every `T: Display` *and* for every `T: AsRef<[u8]>`, because a +`String` satisfies both and the compiler has no principled way to choose. The **orphan rule** +forbids implementing a trait for a type unless your crate owns either the trait or the type — you +cannot implement someone else's `Serialize` for someone else's `Vec`. Each level below loosens +one more of these constraints. CGP's escape route is to move the type that coherence ranges over — +the `Self` of the implementation — into a position the implementing crate always owns, then restore +a single unambiguous answer locally, one [context](components.md) at a time, through +[wiring](wiring.md). See +[coherence](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/coherence.md) +for the full framing. + +## Level 1 — one implementation per interface + +The least machinery is a generic function or a blanket trait impl, which both define exactly one implementation behind an interface. A generic function captures the logic and its bounds in one place: + +```rust +pub fn serialize_bytes, S: Serializer>( + value: &Value, + serializer: S, +) -> Result { ... } +``` + +A blanket trait carries the same one-implementation limitation but reads more ergonomically at the call site, since the bound hides behind the trait impl and the caller writes a method: + +```rust +pub trait CanSerializeBytes { + fn serialize_bytes(&self, serializer: S) -> Result; +} + +impl> CanSerializeBytes for Value { + fn serialize_bytes(&self, serializer: S) -> Result { ... } +} +``` + +The gain is reuse with zero ceremony. The limitation is absolute: there can be exactly one blanket impl, so you cannot offer two ways to serialize bytes and let a caller pick between them. + +## Level 2 — one unique implementation per type per interface + +A vanilla Rust trait lifts the one-implementation limit slightly: many types may share the interface, but coherence still permits at most one implementation per type. Each type that wants the behavior writes its own impl: + +```rust +pub trait Serialize { + fn serialize(&self, serializer: S) -> Result; +} + +impl Serialize for Vec { + fn serialize(&self, serializer: S) -> Result { + self.serialize_bytes(serializer) + } +} + +impl<'a> Serialize for &'a [u8] { + fn serialize(&self, serializer: S) -> Result { + self.serialize_bytes(serializer) + } +} +``` + +The gain is that different types can be serialized differently. The cost is duplication: `Vec` and `&[u8]` each need an explicit impl even though the logic is identical. The body can still call out to a Level-1 building block such as `CanSerializeBytes` to share the actual work, so the duplication is confined to the boilerplate of forwarding. The remaining limitation is the one-impl-per-type ceiling — there is still no way to give `Vec` two serialization strategies and choose between them. + +## Level 3 — multiple implementations per type, globally unique wiring + +Applying basic CGP to a vanilla trait removes the duplication of Level 2 by turning the shared logic into a reusable [provider](components.md) and letting each type [wire](wiring.md) to it. The trait keeps its original shape, which makes the component **self-targeted** and each wired type a **value context**; `#[cgp_component]` generates the [consumer trait](components.md) and [provider trait](components.md) pair, `#[cgp_impl(new ...)]` defines a named provider once, and `delegate_components!` points each type at it. Note that Level 4 below defines a *different* component, `CanSerializeValue`, rather than revising this one: + +```rust +#[cgp_component(SelfSerializer)] +pub trait Serialize { + fn serialize(&self, serializer: S) -> Result; +} + +#[cgp_impl(new SerializeSelfAsBytes)] +#[uses(AsRef<[u8]>)] +impl SelfSerializer { + fn serialize(&self, serializer: S) -> Result { ... } +} + +delegate_components! { + Vec { + SelfSerializerComponent: SerializeSelfAsBytes, + } +} + +delegate_components! { + <'a> &'a [u8] { + SelfSerializerComponent: SerializeSelfAsBytes, + } +} +``` + +The gain is real reuse without modifying the interface: `Serialize` is unchanged, so a type can still implement it directly without opting into CGP at all, and existing users of the trait are unaffected. The `SelfSerializer` provider trait removes the need for ad-hoc interfaces like `CanSerializeBytes`, and `delegate_components!` removes the manual forwarding of Level 2. The limitation is that coherence still binds the wiring itself: each type carries one global wiring, so a `Vec` entry conflicts with any overlapping `Vec` entry, the choice cannot be overridden per context, and the orphan rule still means you can only wire `Vec` from a crate that owns either `Serialize` or `Vec`. + +**That limitation only bites because the wired type is a value context you do not own, and this level holds a second case where it does not bite at all.** Wire a self-targeted component on an *environmental* context and the same level gives per-application choice, because you control how many contexts exist: + +```rust +delegate_components! { App { EmailSenderComponent: SendViaSmtp } } +delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } +``` + +No parameter is involved and nothing has been worked around. That is where most CGP code lives — a capability about the application itself, wired per application — so reading Level 3 as only the retrofit case undersells it, and reading Level 4 as the first level with per-context choice is wrong. + +## Level 4 — unique wiring per type, per context + +Making the component **parameter-targeted** fully decouples the implementation from the type, so each context wires its own choices and the orphan rule lifts entirely. The trait changes shape: the original `Self` becomes an explicit `Value` parameter and `Self` is now always an **environmental context**, so the component dispatches on which concrete value type it serializes. What this adds over Level 3's environmental case is narrow and worth stating precisely — Level 3 already lets each context you define make its own choice, so what Level 4 buys is making that choice about types you do *not* own. Each context then folds its per-type choices straight into its own table with the `open` statement of `delegate_components!`: + +```rust +#[cgp_component(ValueSerializer)] +pub trait CanSerializeValue { + fn serialize(&self, value: &Value, serializer: S) -> Result + where + S: serde::Serializer; +} + +delegate_components! { + new MyAppA { + open ValueSerializerComponent; + + @ValueSerializerComponent.Vec: SerializeBytes, + @ValueSerializerComponent.Vec: SerializeIterator, + } +} + +delegate_components! { + new MyAppB { + open ValueSerializerComponent; + + @ValueSerializerComponent.Vec: SerializeHex, + @ValueSerializerComponent.Vec: SerializeIterator, + } +} +``` + +The `open ValueSerializerComponent;` header opens the component for per-value wiring, and each `@ValueSerializerComponent.Value: Provider` entry assigns a provider for one concrete value type. The gain is that `MyAppA` and `MyAppB` resolve `Vec` to different providers — bytes versus hex — with no conflict, because each choice is coherent only within its own context. The orphan rule no longer applies: a context can wire `Vec` even when its crate owns neither `CanSerializeValue` nor `Vec`, as long as it owns the context type, so you never commit to a global serialization for `Vec` up front. The costs are that the trait must be modified to add the context parameter, and that every value type a context touches must be wired explicitly, which grows tedious for a large type set. + +The `open` form rides the dispatch machinery that every `#[cgp_component]` already generates, so the trait needs no extra option. A legacy alternative writes the same dispatch with a `#[derive_delegate(UseDelegate)]` attribute on the trait and a `UseDelegate: SerializeBytes, ... }>` nested table in each context's wiring; it is retained for compatibility but `open` is preferred for new code, and the two forms appear side by side in [wiring](wiring.md). + +## Level 5 — explicit wiring per type, per provider + +The finest grain overrides wiring *inside* a provider rather than at the context, using a [higher-order provider](higher-order-providers.md) whose inner provider defaults to `UseContext`. The default routes nested lookups back through the context as usual, while an explicit inner provider overrides one branch locally without touching the context's table: + +```rust +pub struct SerializeIteratorWith(pub PhantomData); + +#[cgp_impl(SerializeIteratorWith)] +impl ValueSerializer +where + for<'a> &'a Value: IntoIterator, + Provider: for<'a> ValueSerializer::Item>, +{ + fn serialize(&self, value: &Value, serializer: S) -> Result + where + S: serde::Serializer, + { ... } +} + +delegate_components! { + new MyAppA { + open ValueSerializerComponent; + + @ValueSerializerComponent.Vec: SerializeBytes, + @ValueSerializerComponent.Vec>: SerializeIteratorWith, + @ValueSerializerComponent.Vec: SerializeIteratorWith, + @ValueSerializerComponent.[u8, u64]: UseSerde, + } +} +``` + +Here `Vec>` serializes its inner `Vec` as hex strings, while a bare `Vec` elsewhere in the same context still serializes as bytes — the inner provider is overridden for that one branch only. Where `SerializeIteratorWith` is left without an argument, as for `Vec`, the `UseContext` default takes over and the item lookup goes back through the context, so the `u64` items resolve to `UseSerde` from the table. The gain is per-provider control: a wiring decision can be pinned at the point of use instead of globally at the context level. The cost is the higher-order plumbing itself — the extra provider parameter, the explicit context argument in the inner bound, and the discipline of choosing when to override versus when to defer to the context. + +## Choosing a level + +Read the spectrum as a ladder and stop at the first rung that fits. Levels 1 and 2 are plain Rust and need no CGP at all — reach for them when one implementation, or one per type, is genuinely all you need. Level 3 buys reuse and swappable providers while leaving the trait and its existing users untouched: on a value context that is the right entry point for retrofitting CGP onto an established trait, and on an environmental context it is where most CGP code lives. Level 4 pays a modified interface for the ability to choose per context about types you do not own. Level 5 is a local refinement layered on top of Level 4, used only where a single nested branch must diverge from the context's global choice. Each step up trades ceremony for decoupling, so the discipline is to climb only as far as the problem demands. + +Two questions settle it faster than walking the levels. **Is the capability about the data, or about the application?** About the data means a value context and Level 3's retrofit case; about the application means an environmental context. **Does it concern a type you do not own, which different applications must treat differently?** If yes, the target moves into a parameter and you are at Level 4; if no, self-targeting is enough. Each arrangement answers a different question rather than representing a different amount of sophistication. + +Further reference: +[coherence](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/coherence.md) +for the rules this hierarchy escapes, and +[modular serialization](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/examples/modular-serialization.md) +for the full worked example. diff --git a/docs/ai/skills/references/namespaces.md b/docs/ai/skills/references/namespaces.md deleted file mode 120000 index 395ca3f9..00000000 --- a/docs/ai/skills/references/namespaces.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/namespaces.md \ No newline at end of file diff --git a/docs/ai/skills/references/namespaces.md b/docs/ai/skills/references/namespaces.md new file mode 100644 index 00000000..0fc61e94 --- /dev/null +++ b/docs/ai/skills/references/namespaces.md @@ -0,0 +1,173 @@ +# Namespaces + +A namespace is a reusable, named lookup table of component wirings that a context inherits wholesale and then selectively overrides — CGP's preset mechanism, expressed entirely at the type level with no runtime cost. + +As the component count of an application grows, the [wiring](wiring.md) on each context grows with it: every context spells out its own `delegate_components!` table entry by entry, and two contexts that should share the same set of providers must repeat the whole block. A namespace lifts that block out of any single context, gives it a name, and lets other contexts say "use everything in this namespace" to pull in the entire group at once. This is exactly the preset pattern — a curated bundle of defaults you adopt and then customize — and CGP has no separate `cgp_preset!` construct because a preset *is* a namespace. This file covers `cgp_namespace!` (defining and inheriting a namespace), the `RedirectLookup` provider that makes the indirection work, the `Path!` macro that addresses entries, and the `DefaultNamespace` family of default-resolution traits. + +## What a namespace is + +A namespace is not a context — it is a trait, named after the namespace, that carries a single `Delegate` associated type and is implemented once per key. A context that joins a namespace forwards its lookups through that trait, so the namespace supplies defaults without ever being instantiated or holding any wiring at the context level. The defining behavior is inheritance with override: a context inherits the namespace's entries as defaults, and any entry it wires directly on itself wins, because a context's own [`DelegateComponent`](wiring.md) entry resolves before the namespace fallback is consulted. + +The forwarding is keyed by a *path* rather than a bare component name, and that is what makes inheritance and selective override possible. A path is a type-level list of symbols and component names; keying on it lets one namespace inherit from another, lets a parent's whole subtree be rerouted at once, and lets a child context shadow a single inherited entry without disturbing the rest. + +## Defining a namespace with `cgp_namespace!` + +`cgp_namespace!` defines a namespace from a body that resembles a `delegate_components!` table. The `new` keyword tells the macro to emit the namespace's marker struct and its lookup trait; the entries inside map keys to redirect paths or to providers: + +```rust +cgp_namespace! { + new DefaultShowComponents { + [String, u64]: ShowWithDisplay, + } +} +``` + +Two entry forms appear in the body and generate different table contents. A `:` entry maps a key straight to a provider, exactly as in `delegate_components!` — the `[String, u64]: ShowWithDisplay` line above resolves both keys to the `ShowWithDisplay` provider. A `=>` entry instead redirects a key along a path: `FooProviderComponent => @MyFooComponent` says "when this namespace is asked for `FooProviderComponent`, look up the path `@MyFooComponent` instead of naming a provider outright," leaving the actual provider to be decided wherever the path lands. + +Those two are the forms worth writing, but they are not the whole grammar: a namespace body is parsed by the same code as a `delegate_components!` table, so every operator, key form, statement, and value form that macro accepts parses here too — each lowering to an `impl Namespace<__Table__> for Key` rather than a `DelegateComponent` impl. Two consequences are worth holding. `open C;` in a namespace body is simply another spelling of `C => @C,`, while inheritance is written with the `: ParentNamespace` header rather than with a `namespace` statement. And the legacy nested-table value works, with the inner table lifted out into its own struct and impls just as in a delegation table — which is the one reason to write that form in a namespace rather than on a context, since every joining context then inherits the dispatch table. + +A namespace inherits from a parent by naming it after a colon in the header. The child then resolves everything the parent does, plus its own entries: + +```rust +cgp_namespace! { + new ExtendedNamespace: DefaultNamespace { + @cgp.core.error => + @app, + } +} +``` + +`ExtendedNamespace` inherits every entry `DefaultNamespace` resolves and additionally reroutes the entire `@cgp.core.error` subtree to `@app` — a single path-rewriting entry redirects a whole prefix of the parent namespace at once, not just one component. + +### What the macro generates + +With `new` present, the macro emits a backing struct (named with an `__…Components` wrapper) and the lookup trait carrying the table's `__Table__` generic parameter and a `Delegate` associated type: + +```rust +pub struct __MyNamespaceComponents; + +pub trait MyNamespace<__Table__> { + type Delegate; +} +``` + +Each `=>` entry becomes an `impl` of that trait for the entry's key, whose `Delegate` is a `RedirectLookup` pointing the table at the entry's path; each `:` entry becomes an `impl` whose `Delegate` is the named provider directly. For `FooProviderComponent => @MyFooComponent` the macro emits: + +```rust +impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { + type Delegate = RedirectLookup<__Table__, PathCons>; +} +``` + +When a parent is named, the macro prepends a blanket impl that forwards every key the parent resolves down to the child, so the child inherits the parent's full table; the child's own entries are emitted after it and take precedence where their keys are more specific. + +## Attaching components and joining namespaces + +A namespace is consumed from two sides: components register into it, and contexts join it. A [component](components.md) attaches to a namespace through the `#[prefix(@path in Namespace)]` attribute on its [`#[cgp_component]`](components.md) trait, which emits one extra impl registering the component into the named namespace under a path prefix. CGP's own [`HasErrorType`](components.md), for example, carries `#[prefix(@cgp.core.error in DefaultNamespace)]`, placing the standard error wiring into the built-in `DefaultNamespace` so any context joining that namespace inherits it. The generated impl routes the component's lookup under the prefix path: + +```rust +impl<__Components__> MyNamespace<__Components__> for BarProviderComponent { + type Delegate = RedirectLookup< + __Components__, + PathCons>, + >; +} +``` + +A context joins a namespace inside `delegate_components!` with a `namespace` header line, after which every lookup it cannot resolve directly forwards through the namespace. A direct entry on the same context shadows just that key, leaving the rest of the inherited wiring intact: + +```rust +delegate_components! { + AppA { + namespace DefaultNamespace; + + @test.ShowImplComponent.u64: + ShowWithDisplay, // overrides only the u64 entry + } +} +``` + +The `namespace DefaultNamespace;` line emits a blanket `DelegateComponent` impl on `AppA` that forwards every key through `DefaultNamespace`, paired with the matching `IsProviderFor` forwarding so dependency errors stay diagnosable through [checking](checking.md). The direct `@test.ShowImplComponent.u64` line resolves first, so it wins for `u64` only — the inherit-and-override pattern in action. The override works because `DefaultNamespace` only routes the *marker* `ShowImplComponent` to a path that the context itself fills; a context cannot instead override a path the joined namespace *itself* registers (through a `:` body entry or a `#[default_impl]`), because the direct entry and the namespace's blanket `DelegateComponent` impl would both cover that path and conflict (`E0119`). To leave a path overridable, route the marker through the namespace but terminate the redirect on the context. Joining through `delegate_and_check_components!` does the same and additionally checks the entries the block writes directly, but its derivation does not cover the components the namespace itself brings in — so verifying the full inherited wiring is a job for a standalone `check_components!` (see [checking](checking.md)). + +## Paths with `Path!` + +A path is the type-level address that namespace entries redirect along, and `Path!` is the macro that builds one from a readable dotted, `@`-prefixed form. Each segment narrows the lookup one step — through a namespace, through a prefix, down to a component key — and the leading `@` is the sigil marking the body as a path rather than a plain type: + +```rust +type ErrorRoute = Path!(@app.error.ErrorRaiserComponent); +// PathCons>> +``` + +The encoding of each segment is decided by its first character: a single lowercase identifier that is not a primitive type name (like `app` or `error`) becomes a [`Symbol`](abstract-types.md) type-level string, while every capitalized segment (like `ErrorRaiserComponent`) is kept as the named type — typically a component key or namespace marker. The macro folds the segments right-to-left onto `Nil`, wrapping each in a `PathCons`. You rarely call `Path!` directly; the same `@`-path syntax is embedded inside `cgp_namespace!` entries and `#[prefix(...)]` attributes, which is where paths are most often written. These [type-level primitives](type-level-primitives.md) carry no runtime value. + +## The `RedirectLookup` provider + +`RedirectLookup` is the [provider](components.md) — a zero-sized marker struct, no runtime value — that turns a path-addressed entry back into a concrete provider, and it is the mechanism every namespace runs on under the hood. The ordinary provider blanket impl looks a component up in the context's own table keyed by the component-name marker; `RedirectLookup` instead consults a table keyed by an arbitrary type-level path, then delegates to whatever provider that entry holds. This decouples *which key* a component is looked up under from *which table* answers it — the basis for organizing wiring into namespaces. + +`RedirectLookup` is never written by hand; it is emitted by the macros. Every `#[cgp_component]` generates a `RedirectLookup` impl of its provider trait, and the namespace `=>` entries and `#[prefix]` attributes generate entries whose `Delegate` is a `RedirectLookup`. The generated impl performs one `DelegateComponent` lookup keyed on the path rather than on the component name: + +```rust +impl<__Context__, __Components__, __Path__> Greeter<__Context__> + for RedirectLookup<__Components__, __Path__> +where + __Components__: DelegateComponent<__Path__>, + <__Components__ as DelegateComponent<__Path__>>::Delegate: Greeter<__Context__>, +{ + fn greet(__context__: &__Context__) -> String { + <__Components__ as DelegateComponent<__Path__>>::Delegate::greet(__context__) + } +} +``` + +So `RedirectLookup` implements the provider trait whenever the table maps the path to a delegate that itself implements that trait, and forwards the call to it. When the provider trait carries a generic type parameter, the impl additionally appends that parameter onto the path before the lookup, so the redirected key can encode the generic argument — this is how per-type dispatch through a namespace works. + +## Default resolution: the `DefaultNamespace` family + +The traits that back namespaces come in three arities, differing only in how many type parameters take part in the key. `DefaultNamespace` keys a default purely on the component name; `DefaultImpls1` keys it on the component name *and* one further type — the shape for a per-type default where the same component resolves differently for `String` than for `u64` — and `DefaultImpls2` does the same for a pair. Each carries a single `Delegate` associated type and no method or data; resolution is the projection of `Delegate` from the matching impl: + +```rust +pub trait DefaultNamespace { + type Delegate; +} + +pub trait DefaultImpls1 { + type Delegate; +} +``` + +`DefaultNamespace` is the built-in namespace that `#[prefix(... in DefaultNamespace)]` registers components into and that a context joins with `namespace DefaultNamespace;`. A per-type default is registered with the `#[default_impl(T in DefaultImpls1)]` attribute on a provider impl, which emits `impl DefaultImpls1 for T { type Delegate = Provider; }`. The registration impl drops the provider's own impl-side `where` clause (its `#[use_type]`/`#[uses]` bounds), so a provider that depends on abstract types registers cleanly. Where the attribute may be *written* follows the orphan rule: the crate must own the namespace trait or the key — so an unprefixed component's marker key can be registered into a foreign namespace downstream, but a `#[prefix]`-ed component's key is a foreign `PathCons` path, confining its default to the namespace's own crate. A context then pulls those defaults in with a `for … in` loop that projects the `Delegate` for each type: + +```rust +delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + @test.ShowImplComponent.u64: + ShowWithDisplay, // overrides the inherited default for u64 + } +} +``` + +The `for in DefaultImpls1` loop wires each type `T` by reading `T: DefaultImpls1`, and the direct `u64` line shadows whatever the namespace would otherwise supply for that type. The loop target can equally be a whole namespace defined with `cgp_namespace!`, such as the `DefaultShowComponents` namespace shown earlier — `for in DefaultShowComponents { … }` wires its listed types through the same projection. An optional `where` clause after the loop target (`for in Table where T: Clone { … }`) adds its bounds to every impl the loop emits, narrowing which types it wires. + +## Defining a preset once, reusing it across contexts + +The payoff is that a bundle of wiring is defined once and reused everywhere. A library publishes a namespace of sensible defaults — possibly extended from a base namespace as `ExtendedNamespace: DefaultNamespace` does — and any number of applications join it, inherit the whole bundle, and override only the entries specific to their needs. Each context's table shrinks to a `namespace` header plus a short list of overrides, no matter how many components the namespace bundles. Because the inheritance, the overrides, and the redirections are all resolved through trait projection and type-level paths, the entire arrangement is resolved at compile time with no runtime cost — a preset is simply one more namespace in the chain. + +## Related constructs + +Namespaces build directly on [wiring](wiring.md): a namespace is a `DelegateComponent` table addressed by paths, and a context joins one inside `delegate_components!`. The keys a namespace maps are the `…Component` markers of [components](components.md), attached via the `#[prefix(...)]` attribute on a `#[cgp_component]` trait, and the `IsProviderFor` forwarding a `namespace` header emits feeds the completeness guarantees in [checking](checking.md). The `@`-paths and `Symbol` segments are [type-level primitives](type-level-primitives.md). The per-type dispatch `RedirectLookup` enables — appending a generic parameter onto the lookup path — is the same mechanism the type-parameter dispatch forms in [higher-order providers](higher-order-providers.md) use. + +## Further reference + +Online docs: +[concepts/namespaces.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/namespaces.md), +[reference/macros/cgp_namespace.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_namespace.md), +[reference/providers/redirect_lookup.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/redirect_lookup.md), +[reference/macros/path.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/path.md). diff --git a/docs/ai/skills/references/type-level-primitives.md b/docs/ai/skills/references/type-level-primitives.md deleted file mode 120000 index a9f05118..00000000 --- a/docs/ai/skills/references/type-level-primitives.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/type-level-primitives.md \ No newline at end of file diff --git a/docs/ai/skills/references/type-level-primitives.md b/docs/ai/skills/references/type-level-primitives.md new file mode 100644 index 00000000..f26a72d1 --- /dev/null +++ b/docs/ai/skills/references/type-level-primitives.md @@ -0,0 +1,206 @@ +# Type-level primitives + +The handful of zero-sized types and type macros that CGP folds strings, numbers, lists, choices, and routes into the type system, so the compiler can match a field name or a wiring route through trait resolution alone. + +## The idea + +CGP keys nearly everything by *type*, not by value. A getter looks up a field by a tag type; a [wiring](wiring.md) table selects a [provider](components.md) by a [component](components.md) key type; a [namespace](namespaces.md) re-routes a lookup along a path type. For that to work, things that are normally values — a field name string, a tuple position, a list of fields, a lifetime — have to be encoded as types the compiler can compare and dispatch on. The primitives in this reference are those encodings. Each is a familiar value-level idea lifted into a type: a string becomes a type-level character list, a number becomes a const-generic marker, a list becomes a recursive cons cell, a sum becomes a recursive branch. + +These types are almost never written by hand. They are produced by macros (`Symbol!`, `Product!`, `Sum!`, `Path!`) or emitted by derives, and a reader mostly meets them when *decoding a type the compiler prints* — in an error message, a macro-expansion dump, or a hover. (`cargo cgp expand` resugars them back to `Symbol!`/`Product!`/`Path!`, so a raw spine there means the resugaring declined; an error message or a plain `cargo expand` shows them as they are.) This reference is a decoder ring: skim it to read off what a long nested type means. The prose below always uses the readable `Cons`/`Nil`/`Symbol!` forms, which are exactly what the compiler prints — no abbreviations or aliases are substituted for these types. + +Assume `use cgp::prelude::*;` throughout. + +## Type-level lists: `Product!`, `Cons`, `Nil` + +A type-level list is a compile-time linked list — the analogue of a tuple that generic code can take apart one element at a time. It is built from two cells: `Cons`, a pair holding the first element and the rest of the list, and `Nil`, a unit struct marking the end. Chained to the right and terminated by `Nil`, they form an *anonymous product type* — a record-shaped type whose width and contents a provider can walk without knowing the concrete struct it came from. + +```rust +pub struct Cons(pub Head, pub Tail); +pub struct Nil; +``` + +The `Product!` macro is the sugar a programmer writes instead of nesting `Cons` by hand, and the lowercase `product!` builds a matching value with the tuple-struct constructor: + +```rust +type Row = Product![u32, String, bool]; +// Row == Cons>> + +let row: Row = product![1, "hi".to_string(), true]; +// row == Cons(1, Cons("hi".to_string(), Cons(true, Nil))) +``` + +The list is what makes structural, field-by-field code possible. A struct's fields are exposed as one `Product!` type through `HasFields`, so a provider written once to recurse over `Cons`/`Nil` — a `Nil` impl for the base case, a `Cons` impl for the step — iterates, reads, or rebuilds *any* struct's fields. The elements are usually [`Field`](#field-a-named-value) entries pairing a name with a value, so a derived struct's layout reads as a `Product!` of `Field` cells. See [extensible data](extensible-data.md) for how that machinery is used. + +## Type-level sums: `Sum!`, `Either`, `Void` + +A type-level sum is the dual of the list: where a `Product!` holds a value for *every* element at once, a `Sum!` holds a value for exactly *one* branch — a tagged union the compiler can walk variant by variant. It shares the same right-nested shape but branches at each step instead of pairing, and terminates in an uninhabited marker instead of a constructible one. + +```rust +pub enum Either { Left(Head), Right(Tail) } +pub enum Void {} +``` + +`Either` is the sum cell — `Left(head)` selects this branch, `Right(tail)` defers to the rest — and `Void`, an empty enum with no values, closes the chain. The `Sum!` macro folds a list of types onto that spine, and a value picks one branch by how deep it sits: + +```rust +type Token = Sum![u32, String, bool]; +// Token == Either>> + +let t: Token = Either::Right(Either::Left("hi".to_string())); // the String branch +``` + +The terminator is the one real difference from the product spine, and it is load-bearing. A product ends in the constructible `Nil` because an empty record is a valid value; a sum ends in the *uninhabited* `Void` because an empty choice has no value to pick. After an extractor has tried every variant and matched none, the leftover has type `Void` — a value that cannot exist — which the machinery discharges with an empty `match self {}`, making a fully-handled variant match total at compile time with no unreachable runtime branch. An enum's variants are exposed as a `Sum!` of `Field` entries through `HasFields`, mirroring how a struct's fields are a `Product!`. + +## Type-level strings: `Symbol!`, `Symbol`, `Chars` + +A type-level string is a field name encoded as a type, so the name can drive trait resolution. CGP's getter, `HasField`, keys each field by a `Tag` type; to read a field called `name`, the string `"name"` must become a unique type, so that two symbols from the same string are the *same* type and two from different strings are *different* types. `Symbol!("name")` produces exactly that. + +The reason it is a *list of characters* rather than one const value is a stable-Rust limitation: a `&str` cannot be a const-generic parameter, but a single `char` can. So `Chars` spells the string out one character at a time — the specialized analogue of `Cons` where the head is a `const char` — and `Symbol` wraps that list together with the byte length: + +```rust +pub struct Chars(pub PhantomData); +pub struct Symbol(pub PhantomData); +``` + +The `Symbol!` macro hides all of this. The leading `LEN` const is the part most likely to puzzle a reader: stable Rust cannot compute a `Chars` chain's length inside a const-generic context, so the macro precomputes `str::len()` — the *byte* length — and bakes it into the type: + +```rust +// before +Symbol!("abc") +// after +Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>> +``` + +Because `LEN` is the byte length, a multi-byte string records its UTF-8 width: `Symbol!("世界你好")` records `12`, while its character list still has one `Chars` node per scalar. The empty string is `Symbol<0, Nil>`. A type-level string is most often seen as the tag in a getter bound, where it names the field a provider reads without that context naming the provider: + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData::)); + } +} +``` + +The same string can be recovered at runtime — see [`StaticFormat`](#staticformat-recovering-strings-and-paths) below. + +## `Index`: type-level numbers + +`Index` is the numeric counterpart to `Symbol!` — a `usize` lifted into a type, used to tag a tuple-struct field that has a position but no name. Where a named field is keyed by `Symbol!("name")`, the field at position `N` is keyed by `Index`, so `Index<0>`, `Index<1>`, and `Index<2>` are three distinct tag types standing in for `.0`, `.1`, and `.2`. + +```rust +pub struct Index; +``` + +It is a zero-sized marker: the number lives entirely in the type, so a tuple struct can carry a `HasField>` impl and a `HasField>` impl side by side and the compiler selects the right one purely from the tag. Selecting a wrong position — `Index<5>` on a three-field struct — is a type error, not a runtime panic, because no matching impl exists. `Index` prints its number directly through `Display`, so `Index::<2>.to_string()` is `"2"` and the tag is legible in diagnostics. + +## `Field`: a named value + +`Field` is the element type that fills both spines — a value paired with the type-level tag naming it. A bare `Product![String, u8]` records only types and order; wrapping each element as `Field` attaches the name as a phantom type, making the structural representation self-describing so a provider can match on the tag to find the field it wants. + +```rust +pub struct Field { + pub value: Value, + pub phantom: PhantomData, +} +``` + +The tag is a phantom — needed only at compile time for resolution — so a `Field` is exactly as large as its `Value` and costs nothing at runtime. It is built from a value with no tag argument, since the tag is fixed by the target type: `let f: Field = "Alice".to_string().into();`. The same shape names a record field (tag from `Symbol!` or `Index`) and an enum variant (tag from `Symbol!`, value being the payload), which is why a derived `HasFields` is a `Product!` or `Sum!` of `Field` entries: + +```rust +#[derive(HasFields)] +pub struct Person { pub name: String, pub age: u8 } + +// generated: +// type Fields = Product![ +// Field, +// Field, +// ]; +``` + +## `Path!` and `PathCons`: type-level routes + +A type-level path is a route through nested [wiring](wiring.md) tables, expressed as a single type. Where a bare component key picks one entry out of a context's table, a path points at an entry behind one or more layers of indirection — inside a [namespace](namespaces.md), under a prefix — by listing the segments to walk left to right. `PathCons` is the cons cell of that route, terminated by `Nil`, and it differs from the `Cons` product spine in one way: both `Head` and `Tail` are `?Sized`, because a path segment is a pure type-level marker that never needs a known size. + +```rust +pub struct PathCons(pub PhantomData, pub PhantomData); +``` + +The `Path!` macro builds the route from a dotted, `@`-prefixed name, encoding each segment by case: a lowercase, non-primitive identifier becomes a `Symbol!` type-level string, and a capitalized name stays the named type it spells (typically a component key or namespace marker): + +```rust +type ErrorRoute = Path!(@app.error.ErrorRaiserComponent); +// PathCons>> +``` + +A path names only *where to look*, never a provider directly, so the same path resolves to different providers depending on the table it is walked against — the job of the `RedirectLookup` provider that consumes it. This same `@`-path syntax appears verbatim inside namespace entries, which is where paths are most often written rather than through the bare macro. See [namespaces](namespaces.md) for the redirected-lookup mechanism. + +## `Life<'a>`: a lifetime as a type + +`Life<'a>` lifts a lifetime into a type, so a CGP trait that borrows can still ride through wiring machinery that only accepts types. CGP's dependency marker, `IsProviderFor`, takes a tuple of a component's generic parameters as one type argument — and a tuple member must be a type, never a bare lifetime. A consumer trait declaring `fn get_reference(&self) -> &'a T` therefore cannot record its `'a` directly; `Life<'a>` is the conversion that packages the lifetime as a type so it can sit in the tuple as `(Life<'a>, T)`. + +```rust +pub struct Life<'a>(pub PhantomData<*mut &'a ()>); +``` + +The `*mut &'a ()` phantom is deliberate: a raw pointer is *invariant* in its lifetime, so `Life<'a>` is invariant in `'a`. That is correct here — the lifetime is an exact identity in the dependency marker, and a variant `Life` would let the compiler silently coerce one instantiation into another and pick the wrong provider. The macros insert `Life` automatically when a component carries a lifetime; a reader meets it in the generated provider trait, where `IsProviderFor<…, (Life<'a>, T)>` names the lifetime as a type rather than a bare `'a`. Conceptually it joins `Index` (which lifts a `usize`) and `Symbol` (which lifts a string) as another marker making a non-type thing addressable in trait resolution. + +## `MRef<'a, T>`: owned-or-borrowed + +`MRef<'a, T>` is a "maybe-reference" — an enum holding either a borrow of a `T` or an owned `T` — so a single getter signature serves both the context that already stores a value and the one that must produce it. Unlike the rest of this reference, there is nothing type-level about it: it is an ordinary runtime value, the payload a getter hands back. + +```rust +pub enum MRef<'a, T> { Ref(&'a T), Owned(T) } +``` + +A getter declared to return `MRef<'a, T>` lets a context with the value in a field return `MRef::Ref` and lend it, while a context that computes the value returns `MRef::Owned` and gives it away — with no extra cost in the common stored-field case. The caller treats both uniformly because `MRef` derefs to `T`: it implements `Deref` and `AsRef`, builds either variant through `From` and `From<&'a T>`, and promotes a borrow to ownership with `get_or_clone` when `T: Clone`. + +```rust +let stored = String::from("hello"); +let borrowed: MRef<'_, String> = MRef::from(&stored); // lends a stored value +let made: MRef<'_, String> = MRef::from(String::from("world")); // hands over a built one +assert_eq!(&*borrowed, "hello"); +let owned: String = borrowed.get_or_clone(); // clones the borrowed case +``` + +It is one of the getter return modes recognized by the field macros, parallel to `&T`, `Option<&T>`, or `&str`; see [functions and getters](functions-and-getters.md). Its lifetime is an ordinary borrow and is unrelated to the `Life<'a>` lift above. + +## `StaticFormat`: recovering strings and paths + +The type-level encodings need a way back to runtime data, and three traits provide it. `StaticFormat` recovers a type-level string *lazily* by writing into a formatter — it backs the `Display` impls on `Symbol` and `Chars`, recursing down the `Chars` spine to emit each character, so any symbol prints with `to_string()` or `{}`: + +```rust +let s = ::default(); +assert_eq!(s.to_string(), "hello"); +``` + +`StaticString` recovers it *eagerly*, as a compile-time `&'static str` constant: a blanket impl walks the `Chars` list and UTF-8-encodes it into a `[u8; LEN]` at const-evaluation time — which is the consumer that `Symbol`'s `LEN` byte length exists to size — then validates the bytes as a `&'static str`. Use `Display` when a runtime value will do; use `StaticString::VALUE` when a `const` is needed or in a hot path. Both round-trip multi-byte Unicode faithfully: + +```rust +use cgp::core::field::traits::StaticString; +assert_eq!(::VALUE, "世界你好"); +``` + +`ConcatPath` works one level up, joining two `PathCons` paths into one as a pure type-level computation — it keeps each `Head` and splices the second path on where the first reaches `Nil`, the operation behind composing nested accessors: + +```rust +type Joined = >::Output; // the path a.b.c.d +``` + +## Further reference + +Online source-of-truth documents: the +[types directory](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp/reference/types) +(`cons.md`, `either.md`, `chars.md`, `index.md`, `field.md`, `life.md`, `mref.md`, `path_cons.md`), +the construction macros +[`macros/symbol.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/symbol.md), +[`macros/product.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/product.md), +[`macros/sum.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/sum.md), +[`macros/path.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/path.md), +and the recovery traits +[`traits/static_format.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/static_format.md). diff --git a/docs/ai/skills/references/wiring.md b/docs/ai/skills/references/wiring.md deleted file mode 120000 index d5645fa3..00000000 --- a/docs/ai/skills/references/wiring.md +++ /dev/null @@ -1 +0,0 @@ -../cgp-skills/cgp/references/wiring.md \ No newline at end of file diff --git a/docs/ai/skills/references/wiring.md b/docs/ai/skills/references/wiring.md new file mode 100644 index 00000000..9aef7341 --- /dev/null +++ b/docs/ai/skills/references/wiring.md @@ -0,0 +1,194 @@ +# Wiring + +How a context selects which provider implements each of its components, by recording a type-level table that maps every `…Component` marker key to a chosen provider. + +A CGP [component](components.md) splits the consumer trait callers use (`CanDoX`) from the provider trait implementers write (`SomethingDoer`), but that split leaves one question open: for a given context, *which* provider supplies the behavior? Wiring is the answer. It is the act of telling a context, component by component, which provider stands behind each consumer-trait call — and the mechanism is a small type-level lookup table carried on the context type. This file explains that table, the `delegate_components!` macro that populates it, and the `UseContext` provider that lets a provider trait route back through the context's own consumer-trait impl. + +## The table: `DelegateComponent` + +The table is the trait `DelegateComponent`, which maps one key type to one value type: + +```rust +pub trait DelegateComponent { + type Delegate; +} +``` + +There is no method and no data — the trait exists purely to associate a value type (`Delegate`) with a key type (`Key`) on a carrier type (`Self`). The mental model is a type-level key-value map living on the `Self` type, analogous to an object's method table (vtable) in object-oriented languages: where a vtable maps method names to function pointers resolved at runtime, this table maps `…Component` marker types to provider types resolved entirely at compile time. Implementing `DelegateComponent` is "setting" the entry at `Key`; naming `Self: DelegateComponent` in a bound and reading `Self::Delegate` is "getting" the value back out. Because Rust forbids two impls of the same trait for the same `Self` and `Key`, each key maps to exactly one value, which is what makes the structure a genuine map. + +When the key is a component marker such as `GreeterComponent`, a populated entry causes the context to inherit the matching provider trait through the blanket impl, and from there the consumer trait — so `app.greet()` type-checks. The blanket impl's body is itself a `DelegateComponent` lookup: it reads the entry, finds the provider, and forwards the call to it. The lookup *is* the whole routing mechanism. (When the key is some arbitrary type instead of a component marker — a shape, a tag — the same trait serves as a plain dispatch table walked by a higher-order provider, with no provider trait attached; see [higher-order providers](higher-order-providers.md).) + +## `delegate_components!`: populating the table + +You almost never write `DelegateComponent` impls by hand. The `delegate_components!` macro populates the table from a compact `Key: Value` syntax, one entry per component, the marker as the key and the chosen provider as the value: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +This wires `Rectangle` to use the `RectangleArea` provider for its `AreaCalculatorComponent`. After this, calling `rect.area()` resolves through `Rectangle`'s table to `RectangleArea`. The target before the brace is the [context](checking.md) (or an intermediary provider table) whose table is being defined; each key is a `…Component` marker type and each value is the provider type to delegate it to. + +When several components share one provider, the array form on the key side lets a bracketed list of markers expand to one entry each, all pointing at the same value: + +```rust +delegate_components! { + Rectangle { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: RectangleGeometry, + GreeterComponent: GreetHello, + } +} +``` + +This is exactly equivalent to writing `AreaCalculatorComponent: RectangleGeometry` and `PerimeterCalculatorComponent: RectangleGeometry` on separate lines, plus the `GreeterComponent` entry — three entries in all. + +A `new` keyword in front of the target makes the macro define the target struct as well, saving a separate declaration. `new GeometryComponents { … }` emits `struct GeometryComponents;` alongside the table impls. This is the idiomatic way to declare an **aggregate provider** — a zero-sized provider whose only purpose is to hold a table that dispatches each component to a sub-provider, so that other contexts can delegate a whole group of components to it as a single unit: + +```rust +delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } +} +``` + +An aggregate provider is a *provider*, not a context. `GeometryComponents` implements each component's provider trait by forwarding through its `DelegateComponent` table, and another context then delegates to it — `delegate_components! { App { [AreaCalculatorComponent, PerimeterCalculatorComponent]: GeometryComponents } }` — reusing the whole bundle in one line. Because it is never its own context, an aggregate provider is always wired with plain `delegate_components!`, never `delegate_and_check_components!`: the checked macro would assert that the aggregate can *use* each component as a context, which the bundle was never meant to answer, so the result is uninformative whichever way it goes — it passes vacuously when the bundled providers need nothing from their context, and fails blaming the bundle when any of them needs a field or a type the real context would have supplied. An aggregate provider is verified instead when a real context that delegates to it is checked; see [checking](checking.md). + +A leading generic list on the target makes the whole table generic, so one wiring applies across a family of contexts: `delegate_components! { MyContext { … } }` wires every `MyContext` at once. + +### What the macro generates + +Each entry expands to a pair of impls. The first is the `DelegateComponent` impl that stores the entry — for the `Rectangle` example above, the macro emits: + +```rust +impl DelegateComponent for Rectangle { + type Delegate = RectangleArea; +} +``` + +This impl alone is what the provider blanket impl reads when it looks the component up. The second impl is an `IsProviderFor` impl that forwards the chosen provider's requirements back through the table, so a missing transitive [impl-side dependency](components.md) still surfaces as a usable compiler error rather than a dead end. The details of that propagation belong to [components](components.md) and [checking](checking.md) — here it is enough to know that wiring an entry makes it both *resolvable* (the `DelegateComponent` half) and *checkable* (the `IsProviderFor` half). + +## Explicit delegation: what wiring effectively does + +To see what `delegate_components!` buys you, it helps to write the routing out by hand. Without any table, a context can implement a consumer trait directly by calling a provider's provider-trait method itself. Given the `AreaCalculator` provider trait (whose method takes the context as an explicit `Context` parameter rather than `&self`), a context can hand-route its `CanCalculateArea` consumer impl through the `RectangleArea` provider: + +```rust +impl CanCalculateArea for Rectangle { + fn area(&self) -> f64 { + >::area(self) + } +} +``` + +This is the manual equivalent of one `delegate_components!` entry: it names the provider explicitly, invokes its provider-trait method, and passes `self` as the context. The single line `AreaCalculatorComponent: RectangleArea` in the table achieves the same routing generically, through the generated `DelegateComponent` impl and the blanket impl that reads it — for every method on the trait, without you writing out each call. Use this explicit form only as a teaching device or in the rare case where you want a context to bypass the table for one trait; the table form is the idiom. + +## Direct implementation of a consumer trait + +A context need not delegate at all. When the behavior is specific to one context and there is no provider worth naming, you can implement the consumer trait directly — plain vanilla Rust, no table involved: + +```rust +impl CanGreet for Person { + fn greet(&self) { + println!("Hello, I am {}", self.name); + } +} +``` + +This bypasses the provider-trait machinery entirely: `person.greet()` calls this impl directly. Direct implementation and table-driven wiring are mutually exclusive for a given component on a given context — the table's blanket impl already supplies the consumer trait, so a hand-written consumer impl would collide with it. Reach for direct implementation when a component has exactly one context-specific behavior and the indirection of a separate provider adds nothing. + +## `UseContext`: routing a provider trait back to the consumer trait + +`UseContext` is a [provider](components.md) — a zero-sized marker struct with no runtime value — that implements *any* provider trait by forwarding its methods back to the context's own consumer-trait implementation: + +```rust +pub struct UseContext; +``` + +It is the exact dual of the consumer-trait blanket impl. That blanket impl runs consumer-to-provider — a context implements `CanGreet` by delegating to whichever provider implements `Greeter` for it. `UseContext` runs the opposite direction: it implements the provider trait `Greeter` by calling whatever `CanGreet` implementation the context already has. `#[cgp_component]` generates a `UseContext` impl of the provider trait for every component, of roughly the shape: + +```rust +impl Greeter for UseContext +where + Context: CanGreet, +{ + fn greet(context: &Context) { + Context::greet(context) + } +} +``` + +So wiring a component to `UseContext` means "use whatever this context already does for this trait." Its purpose is to turn a context's existing consumer-trait impl into a provider that *another* provider can call. The pattern matters most for [higher-order providers](higher-order-providers.md), which take an inner provider as a type parameter and often default it to `UseContext`, so the inner step falls back to the context's own wiring unless an explicit provider is named. + +The one rule to respect is the circular-dependency caveat: never delegate a component to `UseContext` when the context's only impl of that component *is* the delegation itself. Doing so asks the context to implement the consumer trait by delegating to a provider (`UseContext`) that in turn implements the provider trait by calling the consumer trait — a cycle the trait solver cannot resolve, surfacing as an overflow or unsatisfied-bound compile error. `UseContext` is meant to be supplied to another provider as its inner provider, not wired as a context's own delegate for the same component. + +## Other providers you will see in tables: `WithProvider` and `UseDefault` + +Two more provider markers appear in real wiring often enough to recognize on sight. Both are ordinary zero-sized providers wired like any other, but neither carries behavior of its own — one adapts a lower-level provider into a component, and the other selects a component's own default method bodies. + +`WithProvider` adapts a *foundational* provider into the provider a named component expects. CGP has two layers of provider: the component-specific provider traits a context wires (`NameGetter`, `NameTypeProvider`), and a handful of generic, component-agnostic mechanisms beneath them — [`FieldGetter`](functions-and-getters.md) reads *some* field for *some* tag, and [`TypeProvider`](abstract-types.md) supplies *some* abstract type — that do not know which component they serve. `WithProvider` is the adapter that lets one of those foundational providers stand in for a named component by forwarding the component's method to it. You rarely write `WithProvider<…>` in full, because its common cases ship as aliases you *will* see wired: `WithField` and `WithFieldRef` (a `FieldGetter` as a getter component), `WithType` and `WithDelegatedType` (a `TypeProvider` as an abstract-type component), and `WithContext` (the context's own capability). Reading `NameGetterComponent: WithField<…>`, treat it as "this getter is served by the foundational field-getter named inside." + +`UseDefault` is the empty provider that selects a component's *own* default method bodies. A consumer trait may give its methods default bodies exactly as any Rust trait can; when every method is defaulted there is no behavior left for a provider to supply, yet the component still needs *some* provider in the table to be wired. `UseDefault` is the conventional name for that role — but unlike `UseContext` or `UseField`, no macro generates its impl, so the author writes an empty `#[cgp_impl(UseDefault)]` (or an empty impl on the concrete context) whose body falls through to the trait defaults. Wiring a component to `UseDefault` therefore reads as "use the trait's own defaults for this component." + +## Dispatching a component per type with `open` + +When a provider trait carries an extra generic parameter and the right provider depends on which concrete type that parameter is, the choice is made by a second lookup keyed on that parameter rather than on the component marker. The `open` statement inside `delegate_components!` is the way to write that per-value wiring: it folds the per-type entries directly into the context's own table, one provider per concrete value of the dispatch parameter. Given a `CanCalculateArea` consumer trait whose `Shape` parameter selects the area formula, a context wires each shape to its own provider like this: + +```rust +delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } +} +``` + +The leading `open AreaCalculatorComponent;` header opens one or more components for per-value wiring. The braces are optional when opening a single component, so `open AreaCalculatorComponent;` and `open { AreaCalculatorComponent };` are equivalent; to open several components together, list them inside the braces (`open { A, B };`). The header is a *leading* statement: when a single block mixes plain `Component: Provider` mappings with an `open` block, the `open` header must come first, before any plain mappings, or the macro fails to parse. Each subsequent `@Component.Key: Provider` entry then assigns a provider for one value of that component's dispatch parameter: `@AreaCalculatorComponent.Rectangle: RectangleArea` says that when `Shape` is `Rectangle`, `MyApp` calculates area through `RectangleArea`, and the `Circle` line does the same for `Circle`. After this wiring, `MyApp` implements `CanCalculateArea` via `RectangleArea` and `CanCalculateArea` via `CircleArea`. + +Three shorthands keep the entries compact. When several values of the dispatch parameter share one provider, a **bracketed group** on a path segment expands to one entry each — `@AreaCalculatorComponent.[Rectangle, Circle]: SomeProvider` wires both shapes to `SomeProvider`. A bracketed group is not restricted to the last segment and may be followed by more path, so `@app.[FooComponent, BarComponent].[u64, String]: P` writes all four combinations in one entry. A **braced group** looks similar and behaves differently: its elements are whole *tails* rather than single segments, so they may differ in length and may nest, but nothing may follow the closing brace — `@app.{ErrorRaiserComponent.{&'static str, String}, ErrorWrapperComponent}: RaiseFrom` is one entry covering three routes, while writing `.bool` after such a group is a parse error reported only as `expected ':'`. And when a dispatch value needs generic parameters of its own, they precede the value: `@SomeComponent.<'a, T> &'a T: SomeProvider` dispatches on the type `&'a T` for all `'a` and `T`. + +The `open` form needs no extra macro on the component. It works through the `RedirectLookup` impl that every `#[cgp_component]` already generates, so dispatching a component per type requires no `#[derive_delegate]` on the trait — the same component you wire by marker is the one you open by value. `open` is a lightweight form of the full namespace feature, suited to a context wiring its own components directly; it does not combine with a joined namespace where the component carries `#[prefix(...)]`. The full namespace machinery, including `@`-path keys and the `namespace` statement, is described in [namespaces](namespaces.md). + +### Legacy: `UseDelegate` nested tables + +An older form writes the per-type entries into a separate table wrapped in the `UseDelegate` provider, rather than folding them into the context's own table with `open`. It nests a `new` table inside a single `UseDelegate<…>` value: + +```rust +delegate_components! { + MyApp { + AreaCalculatorComponent: UseDelegate, + } +} +``` + +This desugars `UseDelegate` into a standalone `delegate_components! { new AreaCalculatorComponents { … } }` plus an outer entry `AreaCalculatorComponent: UseDelegate` pointing the component at that inner table. The end effect matches the `open` example above — `MyApp` dispatches `Rectangle` to `RectangleArea` and `Circle` to `CircleArea` — but the dispatch values live in a named side table reached through `UseDelegate` instead of in `MyApp`'s table directly. + +This is a legacy dispatch mechanism, retained for compatibility and expected to be deprecated and removed. It is documented here so that the nested-table form can be *read* where it still appears in existing code; for *writing* new wiring, prefer `open`, which dispatches the same component without the extra `UseDelegate` indirection or the separate inner table. The detailed mechanics of the `UseDelegate` provider — how it reads its inner table at the provider level — belong to [higher-order providers](higher-order-providers.md). + +## Related constructs + +Wiring is the step that connects [components](components.md) — the consumer/provider trait pairs and `…Component` markers — to the providers that implement them, and the `IsProviderFor` impls it generates feed the completeness guarantees described in [checking](checking.md). The `open` statement shown above dispatches a generic-parameter component per value through the `RedirectLookup` impl every component generates; the full namespace feature it derives from, including `@`-path keys and the `namespace` statement, is described in [namespaces](namespaces.md). `UseContext` and the legacy `UseDelegate` provider — including how it reads an inner dispatch table — are covered in [higher-order providers](higher-order-providers.md). + +## Further reference + +Online docs: +[delegate_components.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/delegate_components.md), +[traits/delegate_component.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/delegate_component.md), +[providers/use_context.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_context.md). diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index b29be5de..ec29e9f1 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -163,7 +163,7 @@ during expansion — but a wiring mistake does not surface here at all. That is useful mid-debugging: it works on a crate that does not type-check. For the wiring mistake itself, use [`cargo cgp check`](./check.md). -## When to reach for it +## When to use it Four situations, all of them cases where the answer is in the generated code rather than in a message: diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 380527d1..766e2e7c 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -102,7 +102,7 @@ delegate_components! { parameter. The loop wires every type with a registered default, and the direct `u64` line shadows whatever the namespace would otherwise supply for that one type. -## When to reach for it, and when not +## When to use it **Reach for it when a provider is the natural default for its key and you want that recorded where the provider is written.** diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index cc909992..50b77558 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -158,7 +158,7 @@ delegate_components! { No wrapper, no second table type, and nothing on the component. The two forms dispatch on the same parameter and resolve to the same implementations. -## When to reach for it, and when not +## When to use it **Do not add `#[derive_delegate]` to a new component.** Use the `open` statement of [`delegate_components!`](../macros/delegate_components.md), which needs no attribute and no table type. diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 3eb8d7f6..fb737e51 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -110,7 +110,7 @@ pub trait CanGreet { `CanGreet` now means "can greet, and can tell you its name". Every provider may rely on the name being available, and so may every caller. -## When to reach for it, and when not +## When to use it **Reach for `#[extend]` when callers of the trait should be able to rely on the capability too**, and for a capability supertrait on a `#[cgp_component]` in preference to native `:` syntax. Reach for something diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 07412a3a..a8f11211 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -108,7 +108,7 @@ where } ``` -## When to reach for it, and when not +## When to use it **Reach for `#[extend_where]` when a predicate is part of what the capability means**, and you want it enforced where the trait is named rather than silently narrowing which contexts the implementation covers. diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 1a3f0fff..954352af 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -151,7 +151,7 @@ Callers still write `app.send_email(to, body)`. The provider's requirement from `smtp_server` field borrowed here as a `&str` from a `String`, never appears in the trait everyone else calls. -## When to reach for it, and when not +## When to use it **Reach for `#[implicit]` by default whenever a provider needs a value from its own context.** It is the shortest form, it introduces no new declaration, and it uses the same field access a getter would, so a diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 9b6138a0..84ed387d 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -140,7 +140,7 @@ pub fn rect_area(&self) -> f64 { } ``` -## When to reach for it, and when not +## When to use it **Use `#[use_provider]` whenever an implementation depends on another implementation by name**, in preference to writing the bound by hand. You read the explicit `Inner: AreaCalculator` form in diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 7be1c4fb..236a5f58 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -177,7 +177,7 @@ The error type is one of three decisions a context makes about failure, and [modular error handling](/docs/concepts/modular-error-handling#why-the-error-type-is-the-hard-one) separates them. -## When to reach for it, and when not +## When to use it **Use `#[use_type]` whenever a definition names an abstract type another component supplies.** It is the recommended form; you read a hand-written supertrait plus `Self::`-qualified paths in existing code rather diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 746d8ce2..68ef5bac 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -111,7 +111,7 @@ impl AreaCalculator { This provider is a two-line adapter: it satisfies the `AreaCalculator` component by deferring to whatever `rectangle_area` computes. Any context with the fields that capability needs can wire it. -## When to reach for it, and when not +## When to use it **Use `#[uses]` for every capability dependency**, in preference to writing the `Self:` bound by hand. That is the recommendation; you read the hand-written form in existing code rather than write it. diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md index 917de154..32c031de 100644 --- a/docs/reference/components/can_raise_error.md +++ b/docs/reference/components/can_raise_error.md @@ -112,7 +112,7 @@ abstract error, and any wired context that satisfies that bound, typically by pl backend, makes `load` produce errors in that context's chosen type. The context is an **environmental context**, and the capability targets it rather than a value. -## When to reach for it, and when not +## When to use it **Reach for `CanRaiseError` whenever a provider holds a concrete error `E` and must return the context's abstract error.** It is the standard way a fallible provider bridges from a library's error diff --git a/docs/reference/components/can_wrap_error.md b/docs/reference/components/can_wrap_error.md index 7be1d879..e5fd027b 100644 --- a/docs/reference/components/can_wrap_error.md +++ b/docs/reference/components/can_wrap_error.md @@ -104,7 +104,7 @@ dependencies are declared with [`#[uses]`](../attributes/uses.md), so neither ap `CanLoad` signature, and any context that satisfies them makes `load` produce enriched errors in its own error type. The context is an **environmental context**, and the capability targets it. -## When to reach for it, and when not +## When to use it **Reach for `CanWrapError` when a provider should add context to an error before returning it.** It is how a CGP program builds the equivalent of an error chain or a `.context(...)` message without diff --git a/docs/reference/components/handler/async_computer.md b/docs/reference/components/handler/async_computer.md index dcaae15b..3947379c 100644 --- a/docs/reference/components/handler/async_computer.md +++ b/docs/reference/components/handler/async_computer.md @@ -83,7 +83,7 @@ example is **parameter-targeted**: the computation acts on the `Input`, while th provider. A provider is usually generated from a function with [`#[cgp_computer]`](../../macros/cgp_computer.md) rather than written by hand. -## When to reach for it, and when not +## When to use it **Reach for `AsyncComputer` for a computation that awaits but cannot fail.** It is the async infallible corner of the family, so a provider that only reads its input should prefer the by-reference diff --git a/docs/reference/components/handler/async_computer_ref.md b/docs/reference/components/handler/async_computer_ref.md index 44b31a61..92d785d5 100644 --- a/docs/reference/components/handler/async_computer_ref.md +++ b/docs/reference/components/handler/async_computer_ref.md @@ -79,7 +79,7 @@ where `scan` awaits the computation while keeping ownership of the `String` with the caller. The example is **parameter-targeted**: the computation acts on the `Input`, while the context decides the provider. -## When to reach for it, and when not +## When to use it **Reach for `AsyncComputerRef` when a computation is async and infallible and only reads its input.** That is a narrow combination, so most code reaches a simpler member first and lets promotion bridge to diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md index dab0438a..ef1c8a3e 100644 --- a/docs/reference/components/handler/computer.md +++ b/docs/reference/components/handler/computer.md @@ -103,7 +103,7 @@ the `Code` tag. The example is **parameter-targeted**: the computation acts on t the context decides the provider. In practice a provider like this is written with [`#[cgp_computer]`](../../macros/cgp_computer.md) rather than by hand. -## When to reach for it, and when not +## When to use it **Reach for `Computer` for a synchronous transform that cannot fail.** It is the default member of the family to implement, because promotion lifts it into every other variant, so one `Computer` provider can diff --git a/docs/reference/components/handler/computer_ref.md b/docs/reference/components/handler/computer_ref.md index 9d364e11..42a8b224 100644 --- a/docs/reference/components/handler/computer_ref.md +++ b/docs/reference/components/handler/computer_ref.md @@ -78,7 +78,7 @@ where `measure` passes the input by reference, so the caller keeps ownership of the `String`. The example is **parameter-targeted**: the computation acts on the `Input`, while the context decides the provider. -## When to reach for it, and when not +## When to use it **Reach for `ComputerRef` when a synchronous, infallible computation only needs to read its input.** It avoids handing ownership to a computation that does not consume the value, which matters when the caller diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md index 84635564..29eea8af 100644 --- a/docs/reference/components/handler/handler.md +++ b/docs/reference/components/handler/handler.md @@ -101,7 +101,7 @@ the wired provider is a pure `Computer`, a fallible `TryComputer`, an `AsyncComp pipeline code targets `Handler`. The example is **parameter-targeted**: the computation acts on the `Input` type, while the context decides which provider answers. -## When to reach for it, and when not +## When to use it **Bound generic pipeline code against `CanHandle` when it should accept any computation regardless of which capabilities the provider actually uses.** Because every simpler member promotes up to a handler, diff --git a/docs/reference/components/handler/handler_ref.md b/docs/reference/components/handler/handler_ref.md index 7645a5c3..28e041df 100644 --- a/docs/reference/components/handler/handler_ref.md +++ b/docs/reference/components/handler/handler_ref.md @@ -90,7 +90,7 @@ where abstract error on failure. The example is **parameter-targeted**: the computation acts on the `Input`, while the context decides the provider and the error type. -## When to reach for it, and when not +## When to use it **Reach for `HandlerRef` when an async, fallible computation only needs to read its input**, for instance a request handler that inspects a borrowed request without consuming it. Bounding generic pipeline code diff --git a/docs/reference/components/handler/producer.md b/docs/reference/components/handler/producer.md index 12c0b24b..6083b764 100644 --- a/docs/reference/components/handler/producer.md +++ b/docs/reference/components/handler/producer.md @@ -96,7 +96,7 @@ context decides which provider answers, and no value is operated on. In practice with [`#[cgp_producer]`](../../macros/cgp_producer.md), which also wires the promotion so the same function answers the input-taking components while ignoring their input. -## When to reach for it, and when not +## When to use it **Reach for `Producer` for a value that a computation needs but does not compute from an input**, such as a constant, a default, or a value read from the context. It is the family's source, and promotion diff --git a/docs/reference/components/handler/try_computer.md b/docs/reference/components/handler/try_computer.md index 9e030a16..7fa12b8b 100644 --- a/docs/reference/components/handler/try_computer.md +++ b/docs/reference/components/handler/try_computer.md @@ -108,7 +108,7 @@ supertraits `HasErrorType`, `App` must also wire an error type and an error rais `try_compute`. The example is **parameter-targeted**: the computation acts on the `Input`, while the context decides the provider and the error type. -## When to reach for it, and when not +## When to use it **Reach for `TryComputer` for a synchronous computation that can fail.** It is the fallible middle of the family, and it sits in the promotion lattice, so it both receives providers promoted from a diff --git a/docs/reference/components/handler/try_computer_ref.md b/docs/reference/components/handler/try_computer_ref.md index 941961a3..bbad598a 100644 --- a/docs/reference/components/handler/try_computer_ref.md +++ b/docs/reference/components/handler/try_computer_ref.md @@ -88,7 +88,7 @@ where abstract error on failure. The example is **parameter-targeted**: the computation acts on the `Input`, while the context decides the provider and the error type. -## When to reach for it, and when not +## When to use it **Reach for `TryComputerRef` when a fallible synchronous computation only needs to read its input.** It keeps ownership with the caller while still reporting failure through the context's error type. diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index 7115fa01..b6cb44b0 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -110,7 +110,7 @@ the context's shared error without spelling `Self::Error`. `App` wires its error satisfies the `Debug` bound. `App` is an **environmental context**, a type that stands for the application and carries its choices, and the capability targets that context rather than a value. -## When to reach for it, and when not +## When to use it **Reach for `HasErrorType` in any fallible component whose error type the context should choose.** It is the foundation of CGP's error handling and is a supertrait of every other fallible capability, so a diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index a1d361e0..8eb0a319 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -108,7 +108,7 @@ where context retargets it at the mock with no change to its body. `App` is an **environmental context**, and the capability targets it. -## When to reach for it, and when not +## When to use it **Reach for `HasRuntime` in any provider that performs an effect against the runtime**, such as spawning a task, awaiting a timer, or opening a connection, and reach it as a `#[uses(HasRuntime)]` dependency so diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md index fae6f853..1f4aa49f 100644 --- a/docs/reference/components/has_runtime_type.md +++ b/docs/reference/components/has_runtime_type.md @@ -91,7 +91,7 @@ where `TokioRuntime`. `describe` names only the runtime type and never a runtime value, which is exactly the case `HasRuntimeType` serves alone. `App` is an **environmental context**, and the capability targets it. -## When to reach for it, and when not +## When to use it **Reach for `HasRuntimeType` when code names the runtime type but never touches a runtime value.** That is the narrower of the two runtime capabilities, and asking for it alone keeps a bound honest about what diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index 18d79246..acfb7beb 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -101,7 +101,7 @@ where the application that carries its type choices. In real code you would write the named `#[cgp_type]` layer; this page documents the substrate it rests on. -## When to reach for it, and when not +## When to use it **You rarely name `HasType` directly. Reach for [`#[cgp_type]`](../macros/cgp_type.md) instead**, which defines a named abstract type with its own readable trait, and let it build on this substrate. The one diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index 9d0c69ce..a8c581f5 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -107,7 +107,7 @@ task or error types carry `Send` bounds; that requirement is discharged only at [`CanSendRun`](./send_runner.md) proxy. `App` is an **environmental context**, and the task is a type-level `Code` selector the wiring dispatches on. -## When to reach for it, and when not +## When to use it **Reach for `CanRun` to model a unit of work a context executes to completion**, such as a background job, a startup action, or a scheduled task, especially when one context hosts several such tasks that diff --git a/docs/reference/components/send_runner.md b/docs/reference/components/send_runner.md index 96bb221a..4f2670fa 100644 --- a/docs/reference/components/send_runner.md +++ b/docs/reference/components/send_runner.md @@ -108,7 +108,7 @@ makes the spawn type-check. The context wires its [`CanRun`](./runner.md) tasks never on the abstract task or error types. `App` is an **environmental context**, and the task is a type-level `Code` selector. -## When to reach for it, and when not +## When to use it **Reach for `CanSendRun` when a runner's future must be `Send`**, which in practice means whenever the work is handed to a work-stealing spawner like `tokio::spawn`. A provider that spawns bounds its context diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index edcc3a88..cc4e479e 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -169,7 +169,7 @@ let person = remainder .finalize_build(); // all present again ``` -## When to reach for it, and when not +## When to use it **Derive `BuildField` when a struct is assembled by code that does not know the whole struct.** That is the case it exists for, and it is a narrower case than "this struct has several fields". diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 3c7fa7bc..d1968e51 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -108,7 +108,7 @@ pub enum Shape { constructors, and an extractor. Worked examples of each half are on the [record](./derive_cgp_record.md#examples) and [variant](./derive_cgp_variant.md#examples) pages. -## When to reach for it, and when not +## When to use it **Reach for one of these derives when generic code has to work over the type's own structure.** That is the test, and it is narrower than it sounds. Most types in a CGP program want diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index 19df9809..c78dbd1e 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -91,7 +91,7 @@ Neither struct knows about the other. They share two field *names*, matched at t caller. Remove the `build_field` line and this stops compiling, because [`finalize_build`](../traits/finalize_build.md) only exists once every field is present. -## When to reach for it, and when not +## When to use it **Reach for it when generic code has to work over the struct's own structure**, and prefer [`#[derive(CgpData)]`](./derive_cgp_data.md) unless naming the shape earns its keep as documentation. @@ -111,7 +111,7 @@ about what it emits. most of them. The full argument for when a type earns the extensible-data machinery at all is on the -[umbrella page](./derive_cgp_data.md#when-to-reach-for-it-and-when-not). +[umbrella page](./derive_cgp_data.md#when-to-use-it). ## Under the hood diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index ddb5368c..9a50bfdf 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -117,7 +117,7 @@ both variants ruled out, which makes it uninhabited, and Add a third variant to `Shape` and this function stops compiling until it is handled, which is the same guarantee a concrete `match` gives, recovered for code that never names the enum. -## When to reach for it, and when not +## When to use it **Reach for it when generic code has to work over the enum's own structure**, and prefer [`#[derive(CgpData)]`](./derive_cgp_data.md) unless naming the shape earns its keep as documentation. @@ -134,7 +134,7 @@ guarantee a concrete `match` gives, recovered for code that never names the enum accepts every variant shape. The full argument for when a type earns the extensible-data machinery at all is on the -[umbrella page](./derive_cgp_data.md#when-to-reach-for-it-and-when-not). +[umbrella page](./derive_cgp_data.md#when-to-use-it). ## Under the hood diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index c5dea150..c78effcf 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -175,7 +175,7 @@ In practice you rarely write these chains by hand. The implementations, which is the extensible visitor pattern: a chain like the one above, generated, with one implementation per variant chosen by wiring. -## When to reach for it, and when not +## When to use it **Derive an extractor when independent code has to handle one variant each, or when the code doing the matching cannot name the enum.** Those are the two cases, and outside them a `match` wins on every count. diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index f615e9d0..63b0ffc9 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -125,7 +125,7 @@ the construction-side counterpart of reading a field through a getter: the imple needs, and the widening is checked. Upcasting is documented with the other [structural casts](../traits/can_upcast.md), and it is built on the same per-variant machinery as this derive. -## When to reach for it, and when not +## When to use it **Derive it when code that does not name a variant has to construct one.** That is the whole test, and it is a narrower need than deconstruction. Most code decides which variant to build at a site that can just name diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 333513f0..e4ce3a95 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -166,7 +166,7 @@ Field access also passes through smart pointers with no extra derive. `Box &str;` is the point. same field access and the same conversion rules, so a getter trait declared only to read a field adds a name and buys nothing. What a getter trait *does* buy is a capability other code can depend on by name, and the three cases where that matters are in -[When to reach for it](#when-to-reach-for-it-and-when-not). +[When to use it](#when-to-use-it). ## Usage @@ -203,7 +203,7 @@ impl HasName for Employee { That hand-written impl is worth seeing, because it shows the trait is an ordinary Rust trait. The macro's only job was to save you writing the body. -## When to reach for it, and when not +## When to use it **Prefer an [`#[implicit]`](../attributes/implicit.md) argument, and reach for a getter trait only when one cannot do the job.** An implicit argument reads a field of the provider's own context as an ordinary diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index ba8147ec..cdb30017 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -182,7 +182,7 @@ table, which maps `AreaCalculatorComponent` to `RectangleArea`, and `RectangleAr fields to compute the result. Swapping the provider in that one wiring line changes what `rect.area()` does, and nothing else in the program changes. -## When to reach for it, and when not +## When to use it Reach for `#[cgp_component]` when a capability needs **more than one implementation, and the choice belongs to the type using it.** That is the case it exists for, and its machinery is not free: diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index cee8c0db..be2d0b6d 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -136,7 +136,7 @@ pub fn add_generic>(a: T, b: T) -> T { } ``` -## When to reach for it, and when not +## When to use it **Reach for `#[cgp_computer]` when a step in a pipeline is naturally a function.** That is the case it exists for, and it is the shortest route into the handler family. diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index d431ce43..94cc66cd 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -183,7 +183,7 @@ dependency; it does not know or care how that capability is implemented. `Rectan read, and that is its entire qualification. There is no `delegate_components!` anywhere in this program, and adding one would change nothing. -## When to reach for it, and when not +## When to use it **Reach for `#[cgp_fn]` first.** When a capability has one natural definition, this is the form to write, and starting here costs nothing if that changes later: the trait keeps its name and its method, diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 658947b5..bbb6d51c 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -33,7 +33,7 @@ it. **This is an advanced tool, not the next step up from `#[cgp_auto_getter]`.** What you pay for the decoupling is a line of wiring per context, and what you get is only useful when a context needs to control which field is read, or to supply the value some way other than reading a field. Most getters -want neither. The [When to reach for it](#when-to-reach-for-it-and-when-not) section draws the line. +want neither. The [When to use it](#when-to-use-it) section draws the line. ## Usage @@ -146,7 +146,7 @@ impl HasName for Anonymous { That last form is worth seeing, because it shows a `#[cgp_getter]` trait is an ordinary component whose consumer trait can be implemented like any Rust trait. -## When to reach for it, and when not +## When to use it **Do not reach for `#[cgp_getter]` by default.** Among the three ways to read a value from a context it is the last resort, and the ordering is worth holding whole: diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 2f4a884d..145c32e7 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -86,7 +86,7 @@ insert a generic context parameter for you: write `impl AreaCalculator`, not `impl AreaCalculator for Context`. Name the context explicitly only to bound it in a way the omitted form cannot express, such as a lifetime or a higher-ranked bound, or to serve one *concrete* context alone, as in `impl AreaCalculator for Rectangle`. -[When to reach for it](#when-to-reach-for-it-and-when-not) says more about choosing between these +[When to use it](#when-to-use-it) says more about choosing between these forms. Without `new`, the provider struct must already exist. A wiring entry naming a struct nothing @@ -259,7 +259,7 @@ fn print_area(rect: &Rectangle) { } ``` -## When to reach for it, and when not +## When to use it **Write providers with `#[cgp_impl]`.** It is the recommended form for every provider, and the cases that call for something else are narrower than they look. diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index e6c5a7ea..e038d867 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -205,7 +205,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **Reach for a namespace when the same wiring is repeated across contexts, or when a top-level table has grown too long to read.** Those are the two problems it solves, and below that threshold it costs more than diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 4c859871..a18fc921 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -111,7 +111,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **Reach for `#[cgp_producer]` when a pipeline step needs no input.** That is the whole of its remit, and within it there is nothing simpler. diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 87e5199c..f6a6905c 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -184,7 +184,7 @@ impl AreaCalculator { All three produce the same three items. The difference is only how much of the machinery is visible in the source. -## When to reach for it, and when not +## When to use it **Write [`#[cgp_impl]`](./cgp_impl.md) instead, by default.** It produces the identical output from source that reads like an ordinary trait impl, so it is the recommended form. You mostly *read* these diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 976bf339..cea009ba 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -148,7 +148,7 @@ impl HasScalarType for App { } ``` -## When to reach for it, and when not +## When to use it **Reach for `#[cgp_type]` whenever generic code has to name a type the context should choose.** The error type is the canonical instance. CGP's own [`HasErrorType`](../components/has_error_type.md) is defined diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 674ca7ad..ab3428f6 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -195,7 +195,7 @@ check_components! { This verifies `MyApp: CanCalculateArea` and `MyApp: CanCalculateArea` in one table. -## When to reach for it, and when not +## When to use it **Every context's wiring should be checked somehow.** That is the rule without exceptions; only the choice of macro scales with the wiring's complexity. diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index acba3c82..db9021d6 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -34,7 +34,7 @@ writing both macros by hand would emit. that a newcomer cannot forget the check and then meet the confusing errors lazy wiring produces. The derivation understands only a mapping keyed on a component *name*, though, so a codebase whose wiring grows past that keeps the two macros separate. The reasons are in -[When to reach for it](#when-to-reach-for-it-and-when-not). +[When to use it](#when-to-use-it). ## Usage @@ -227,7 +227,7 @@ check_components! { That pairing is the usual reason to reach for `#[skip_check]`: the fused derivation can only check the context, and a nested stack is better checked per layer. -## When to reach for it, and when not +## When to use it **Reach for it while getting started, and for tables that are plain `Component: Provider` entries.** It is the form that makes forgetting a check impossible, which is worth more than the control it gives up when the diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index e9572402..49651fc6 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -410,7 +410,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it Use `delegate_components!` whenever a context needs to choose providers, which is any time you use [`#[cgp_component]`](./cgp_component.md) at all. The real decision is not whether to wire but **how to diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 500ab256..d7492048 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -112,7 +112,7 @@ delegate_components! { All four build the same kind of list. The macro and the embedded syntax are two places to write it, not two different things. -## When to reach for it, and when not +## When to use it **Write the `@`-path syntax wherever a namespace or a wiring key asks for a route**, and reach for the bare `Path!` macro only when a route needs to be a named type on its own, which is rare. diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 2e4c558a..823ddbc9 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -99,7 +99,7 @@ type Row = Product![u32, String, bool]; let row: Row = product![1, "hi".to_string(), true]; ``` -## When to reach for it, and when not +## When to use it **Write `Product!` when a construct asks for a type-level list**, which in practice means a handler pipeline or a provider list. Everywhere else it is generated for you. diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index daf671b1..092c5a66 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -82,7 +82,7 @@ A standalone sum can be written directly, which is mostly useful for illustratio type Token = Sum![u32, String, bool]; ``` -## When to reach for it, and when not +## When to use it **Let the derives write it.** That is the honest recommendation for this construct: unlike [`Product!`](./product.md), which you write by hand for handler pipelines, `Sum!` has no everyday hand-written diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index e7718ea8..8b4e3677 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -117,7 +117,7 @@ let s = ::default(); assert_eq!(s.to_string(), "hello"); ``` -## When to reach for it, and when not +## When to use it **Write `Symbol!` when a wiring entry has to name a field**, and let the macros produce it everywhere else. That is the honest summary: the construct is essential and mostly generated. diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index a4125e9d..341feca7 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -98,7 +98,7 @@ second, `UseField`, reads that `Config`'s `name` field to produ `&str` getter borrows from. `ChainGetters` threads the reference from the first step into the second, so `app.name()` returns the name nested two levels in, with no hand-written walking code. -## When to reach for it, and when not +## When to use it **Reach for `ChainGetters` when a getter's value lives on a nested inner context** rather than on the context directly, so the getter has to walk through one or more intermediate values to reach it. diff --git a/docs/reference/providers/dispatch/build_and_merge.md b/docs/reference/providers/dispatch/build_and_merge.md index 6fe7aaff..7441fa46 100644 --- a/docs/reference/providers/dispatch/build_and_merge.md +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -30,7 +30,7 @@ type Handlers = Product![ ]; ``` -## When to reach for it, and when not +## When to use it **Reach for `BuildAndMerge` when a builder step produces several fields at once**, a sub-record merged into the result, inside a list passed to [`BuildWithHandlers`](build_with_handlers.md). For a single diff --git a/docs/reference/providers/dispatch/build_and_merge_outputs.md b/docs/reference/providers/dispatch/build_and_merge_outputs.md index 0fda4889..f2decb4a 100644 --- a/docs/reference/providers/dispatch/build_and_merge_outputs.md +++ b/docs/reference/providers/dispatch/build_and_merge_outputs.md @@ -37,7 +37,7 @@ delegate_components! { Each of the three providers produces a record's worth of fields, and `BuildAndMergeOutputs` merges them in turn into an `App`. -## When to reach for it, and when not +## When to use it **Reach for `BuildAndMergeOutputs` when your handlers are plain field-producing providers** rather than builder adapters, so each is merged into the builder without you writing the merge step. When you want diff --git a/docs/reference/providers/dispatch/build_and_set_field.md b/docs/reference/providers/dispatch/build_and_set_field.md index daca9418..688e9228 100644 --- a/docs/reference/providers/dispatch/build_and_set_field.md +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -30,7 +30,7 @@ type Handlers = Product![ ]; ``` -## When to reach for it, and when not +## When to use it **Reach for `BuildAndSetField` when a builder step computes one named field**, inside a list passed to [`BuildWithHandlers`](build_with_handlers.md). To copy a whole record's worth of fields in one step, use diff --git a/docs/reference/providers/dispatch/build_with_handlers.md b/docs/reference/providers/dispatch/build_with_handlers.md index 10164fa8..d1d1993c 100644 --- a/docs/reference/providers/dispatch/build_with_handlers.md +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -38,7 +38,7 @@ copy the `foo` and `bar` fields from a built `FooBar`, runs [`BuildAndSetField`](build_and_set_field.md) to compute and set `baz`, and finalizes. Dropping either handler leaves a field unset and fails to compile at the finalize step. -## When to reach for it, and when not +## When to use it **Reach for `BuildWithHandlers` to assemble a record from a list of builder adapters**, [`BuildAndSetField`](build_and_set_field.md) and [`BuildAndMerge`](build_and_merge.md). When the list is diff --git a/docs/reference/providers/dispatch/downcast_and_handle.md b/docs/reference/providers/dispatch/downcast_and_handle.md index a7859fdd..8b7a1a5e 100644 --- a/docs/reference/providers/dispatch/downcast_and_handle.md +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -33,7 +33,7 @@ type Match = MatchWithHandlers; ``` -## When to reach for it, and when not +## When to use it **Reach for `DowncastAndHandle` when several variants share one sub-handler** and you want to route them as a group rather than name each one. For a single variant use diff --git a/docs/reference/providers/dispatch/extract_field_and_handle.md b/docs/reference/providers/dispatch/extract_field_and_handle.md index 25d6e031..8e661086 100644 --- a/docs/reference/providers/dispatch/extract_field_and_handle.md +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -43,7 +43,7 @@ matchers [`MatchWithValueHandlers`](match_with_value_handlers.md) and [`MatchWithFieldHandlers`](match_with_field_handlers.md) generate lists of these adapters from an enum's fields, so you rarely write them out by hand. -## When to reach for it, and when not +## When to use it **Reach for `ExtractFieldAndHandle` when you spell out a matcher's per-variant list by hand** with [`MatchWithHandlers`](match_with_handlers.md), naming one adapter per variant. When every variant is diff --git a/docs/reference/providers/dispatch/handle_field_value.md b/docs/reference/providers/dispatch/handle_field_value.md index ad536bb1..0634fe45 100644 --- a/docs/reference/providers/dispatch/handle_field_value.md +++ b/docs/reference/providers/dispatch/handle_field_value.md @@ -38,7 +38,7 @@ The convenience matcher [`MatchWithValueHandlers`](match_with_value_handlers.md) automatically, which is the one difference between it and [`MatchWithFieldHandlers`](match_with_field_handlers.md). -## When to reach for it, and when not +## When to use it **Reach for `HandleFieldValue` inside an extract adapter when the inner handler is an ordinary computer over the payload type**, so it receives the bare value rather than a tagged `Field`. You rarely write it diff --git a/docs/reference/providers/dispatch/match_first_with_handlers.md b/docs/reference/providers/dispatch/match_first_with_handlers.md index 8d5d7763..26a88df6 100644 --- a/docs/reference/providers/dispatch/match_first_with_handlers.md +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -42,7 +42,7 @@ type Match = MatchFirstWithHandlers for AppError` impl exists in the standard library, so [`RaiseFrom`](raise_from.md) would diff --git a/docs/reference/providers/handler/compose_handlers.md b/docs/reference/providers/handler/compose_handlers.md index 7ce5313b..dd8e7c90 100644 --- a/docs/reference/providers/handler/compose_handlers.md +++ b/docs/reference/providers/handler/compose_handlers.md @@ -55,7 +55,7 @@ Computing over an input of `5` runs `Double` first, then `AddOne` on its output, The same composite serves as a `TryComputer`, `AsyncComputer`, or `Handler` if both stages support that shape. -## When to reach for it, and when not +## When to use it **Reach for `ComposeHandlers` to sequence exactly two handlers.** For three or more, use [`PipeHandlers`](pipe_handlers.md), which reads better as a list and folds to the same nested diff --git a/docs/reference/providers/handler/pipe_handlers.md b/docs/reference/providers/handler/pipe_handlers.md index 562ca662..d147cb31 100644 --- a/docs/reference/providers/handler/pipe_handlers.md +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -72,7 +72,7 @@ a context with `foo = 2`, `bar = 3`, `baz = 4` gives `((5 * 2) + 3) * 4`. Stages can be reconciled inline, as in `PromoteAsync>>`, which lifts a plain `Computer` stage up to the async `Handler` shape a pipeline expects. -## When to reach for it, and when not +## When to use it **Reach for `PipeHandlers` to compose three or more handlers**, or any time a list reads better than nesting [`ComposeHandlers`](compose_handlers.md) by hand. For exactly two, `ComposeHandlers` is the diff --git a/docs/reference/providers/handler/promote.md b/docs/reference/providers/handler/promote.md index 62dbb9a0..882f901e 100644 --- a/docs/reference/providers/handler/promote.md +++ b/docs/reference/providers/handler/promote.md @@ -43,7 +43,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **You rarely reach for `Promote` by hand.** A provider written with [`#[cgp_computer]`](../../macros/cgp_computer.md) or [`#[cgp_producer]`](../../macros/cgp_producer.md) diff --git a/docs/reference/providers/handler/promote_async.md b/docs/reference/providers/handler/promote_async.md index e69e6b5d..65f51084 100644 --- a/docs/reference/providers/handler/promote_async.md +++ b/docs/reference/providers/handler/promote_async.md @@ -40,7 +40,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **You rarely reach for `PromoteAsync` by hand.** The [`PromoteComputer`](promote_computer.md) bundle wires it into the async slots, so a synchronous provider serves the async family without you naming it. diff --git a/docs/reference/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md index 72196605..50fdf53d 100644 --- a/docs/reference/providers/handler/promote_async_computer.md +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -40,7 +40,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **Reach for `PromoteAsyncComputer` when the base is an infallible async `AsyncComputer`** and you wire its family by hand. For a synchronous base use [`PromoteComputer`](promote_computer.md), and for a diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md index deeb0e67..8d0f707b 100644 --- a/docs/reference/providers/handler/promote_computer.md +++ b/docs/reference/providers/handler/promote_computer.md @@ -47,7 +47,7 @@ delegate_components! { Most code gets this wiring from [`#[cgp_computer]`](../../macros/cgp_computer.md) rather than writing it. -## When to reach for it, and when not +## When to use it **Reach for `PromoteComputer` when you wire a hand-written `Computer` provider's family explicitly** rather than through [`#[cgp_computer]`](../../macros/cgp_computer.md), which wires it for you. Use a diff --git a/docs/reference/providers/handler/promote_handler.md b/docs/reference/providers/handler/promote_handler.md index 50476983..ceaa0ad2 100644 --- a/docs/reference/providers/handler/promote_handler.md +++ b/docs/reference/providers/handler/promote_handler.md @@ -36,7 +36,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **Reach for `PromoteHandler` when the base is the fully general async fallible `Handler`** and you wire its family by hand. For a less capable base, use the bundle that matches it: diff --git a/docs/reference/providers/handler/promote_producer.md b/docs/reference/providers/handler/promote_producer.md index edf6a247..91b865a1 100644 --- a/docs/reference/providers/handler/promote_producer.md +++ b/docs/reference/providers/handler/promote_producer.md @@ -42,7 +42,7 @@ delegate_components! { Most code gets this wiring from [`#[cgp_producer]`](../../macros/cgp_producer.md) rather than writing it. -## When to reach for it, and when not +## When to use it **Reach for `PromoteProducer` when the base is an input-free `Producer`** and you wire its family by hand rather than through [`#[cgp_producer]`](../../macros/cgp_producer.md). For an input-taking base use diff --git a/docs/reference/providers/handler/promote_ref.md b/docs/reference/providers/handler/promote_ref.md index db5811b2..c5ed85fb 100644 --- a/docs/reference/providers/handler/promote_ref.md +++ b/docs/reference/providers/handler/promote_ref.md @@ -44,7 +44,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **You rarely reach for `PromoteRef` by hand.** Every promotion bundle wires it into the `…Ref` slots, so the by-reference family follows from a by-value provider automatically. Reach for it directly only when diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md index e501a7a5..d3c03caf 100644 --- a/docs/reference/providers/handler/promote_try_computer.md +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -37,7 +37,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **Reach for `PromoteTryComputer` when the base provider is a synchronous fallible `TryComputer`** and you wire its family by hand. For a plain `Computer` base use [`PromoteComputer`](promote_computer.md); diff --git a/docs/reference/providers/handler/return_input.md b/docs/reference/providers/handler/return_input.md index 9b0428d6..6f94a7b1 100644 --- a/docs/reference/providers/handler/return_input.md +++ b/docs/reference/providers/handler/return_input.md @@ -51,7 +51,7 @@ delegate_components! { The `ReturnInput` stage passes its input straight to `Format`, so the pipeline behaves as `PipeHandlers`. -## When to reach for it, and when not +## When to use it **Reach for `ReturnInput` when a handler slot must be filled but no transformation is wanted**, such as the base case of a pipeline built up conditionally, or a stage that is a no-op for one context. Reach diff --git a/docs/reference/providers/handler/try_promote.md b/docs/reference/providers/handler/try_promote.md index b927eae3..896785c3 100644 --- a/docs/reference/providers/handler/try_promote.md +++ b/docs/reference/providers/handler/try_promote.md @@ -40,7 +40,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **You rarely reach for `TryPromote` by hand.** The [`PromoteTryComputer`](promote_try_computer.md) and [`PromoteHandler`](promote_handler.md) bundles wire it, and [`PipeMonadic`](../monad/pipe_monadic.md) diff --git a/docs/reference/providers/handler/use_input_delegate.md b/docs/reference/providers/handler/use_input_delegate.md index 8956b94c..dbe7625c 100644 --- a/docs/reference/providers/handler/use_input_delegate.md +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -44,7 +44,7 @@ maps each input type to the provider responsible for it. Unlike the per-`Code` d [`UseDelegate`](../use_delegate.md), input dispatch has no `open`-statement equivalent, so the nested table is the current form rather than a legacy one. -## When to reach for it, and when not +## When to use it **Reach for `UseInputDelegate` when a handler should run a different provider depending on the type of its input**, which is common in the [dispatch combinators](../dispatch/index.md), where a matcher routes diff --git a/docs/reference/providers/monad/bind_err.md b/docs/reference/providers/monad/bind_err.md index 9d2ca4da..486c13e3 100644 --- a/docs/reference/providers/monad/bind_err.md +++ b/docs/reference/providers/monad/bind_err.md @@ -32,7 +32,7 @@ type Pipeline = PipeHandlers Ok(2) -> BindErr runs the second Increment on 2 -> Ok(3) ``` -## When to reach for it, and when not +## When to use it **Reach for the [monad providers](index.md) rather than `BindErr` directly.** Wiring [`PipeMonadic`](pipe_monadic.md) with the [`ErrMonadic`](index.md#the-monad-markers) marker composes diff --git a/docs/reference/providers/monad/bind_ok.md b/docs/reference/providers/monad/bind_ok.md index f33cd247..d7340404 100644 --- a/docs/reference/providers/monad/bind_ok.md +++ b/docs/reference/providers/monad/bind_ok.md @@ -34,7 +34,7 @@ type Pipeline = PipeHandlers]>; At the bottom of a single-layer pipeline `M` is `IdentMonadic`; a stacked monad threads a deeper monad through it. -## When to reach for it, and when not +## When to use it **Reach for the [monad providers](index.md) rather than `BindOk` directly.** Wiring [`PipeMonadic`](pipe_monadic.md) with the [`OkMonadic`](index.md#the-monad-markers) marker composes diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index 02ba238a..9542ae3d 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -59,7 +59,7 @@ through the err monad, and the same list composed under `OkMonadic` can be drive PipeMonadic::::try_compute(&context, code, 1) ``` -## When to reach for it, and when not +## When to use it **Reach for `PipeMonadic` when a pipeline's steps should short-circuit on a branch**, such as an error or the first success, rather than always feeding the next step. For a pipeline where every step runs diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 7ec74537..a938749c 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -91,7 +91,7 @@ marker. The lookup follows that path into `App`'s table, matches the entry above `RedirectLookup` walks. This is the indirection that lets namespaces organize wiring by path while still resolving to ordinary providers. -## When to reach for it, and when not +## When to use it **You do not reach for `RedirectLookup` directly.** Use the [`open` statement](../macros/delegate_components.md) for per-type dispatch on one context, and a [namespace](../macros/cgp_namespace.md) for reusable, diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index 9f1b6dd1..84604d5d 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -111,7 +111,7 @@ wiring. generic parameter, as `EncodeVec` does. A provider without such a default has no inner provider to fall back to, and the inner provider must always be named. -## When to reach for it, and when not +## When to use it **Reach for `UseContext` as the default inner provider of a higher-order provider**, so the wrapper reuses the context's own wiring for the inner step when no inner provider is named. The inner step may diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index e6c37e50..55aaf6c3 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -110,7 +110,7 @@ then delegates both components to `UseDefault` in one array entry, so `App.greet `"Hello, John!"` entirely from the two default bodies, with no method implemented on `App` or on a dedicated provider. -## When to reach for it, and when not +## When to use it **Reach for `UseDefault` when a component's methods all have usable defaults and a context wants them unchanged.** It gives a default-only component a name to wire, so it fits the delegation table like any diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index c9dd754f..0588d1d0 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -111,7 +111,7 @@ delegate_components! { } ``` -## When to reach for it, and when not +## When to use it **Prefer the [`open` statement](../macros/delegate_components.md) for new per-type dispatch.** It needs no separate table type, no `UseDelegate` wrapper, and no `#[derive_delegate]` on the component, because diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index 696555a8..b109abf4 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -32,7 +32,7 @@ wired through its [`WithDelegatedType`](with_delegated_type.md) alias rather tha [`WithDelegatedType`](with_delegated_type.md) for the import, the wiring form, and a worked example; the mechanism those rest on is described under [Under the hood](#under-the-hood) below. -## When to reach for it, and when not +## When to use it You choose `UseDelegatedType` by wiring its [`WithDelegatedType`](with_delegated_type.md) alias, so the guidance on when to answer several abstract types from one shared table — rather than fixing each one diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index 2271431b..0018404e 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -89,7 +89,7 @@ from the wiring. The same binding can be written with the [`WithField`](with_field.md) alias, which routes through [`WithProvider`](with_provider.md). -## When to reach for it, and when not +## When to use it **Reach for `UseField` only when the field name must differ from the method name**, or when a context needs full control over which field a getter reads from. That is the advanced case diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index f7772ff0..7bd984c8 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -36,7 +36,7 @@ through its [`WithFieldRef`](with_field_ref.md) alias rather than named directly [`WithFieldRef`](with_field_ref.md) for the import, the wiring form, and a worked example; the mechanism those rest on is described under [Under the hood](#under-the-hood) below. -## When to reach for it, and when not +## When to use it You choose `UseFieldRef` by wiring its [`WithFieldRef`](with_field_ref.md) alias, so the guidance on when a borrowed-view getter needs it — rather than the plain [`UseField`](use_field.md) or an diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index e44a82e8..8b47f241 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -85,7 +85,7 @@ field whose name equals the method `foo`. If the value were stored under a diffe this wiring would not apply, and the context would wire [`UseField`](use_field.md) with the actual field name instead. -## When to reach for it, and when not +## When to use it **Reach for `UseFields` when a `#[cgp_getter]` component's methods each read a same-named field.** It is the wired counterpart of the [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) convention, for the diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index 5fc092a5..ea750c20 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -87,7 +87,7 @@ written. The same binding can be written with the [`WithType`](with_type.md) alias, which routes through [`WithProvider`](with_provider.md). -## When to reach for it, and when not +## When to use it **Reach for `UseType` to bind an abstract type to a concrete one, which is the common case.** It is the idiomatic value for a [`#[cgp_type]`](../macros/cgp_type.md) component's wiring entry, and it saves diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md index aaf4364e..b9da17f7 100644 --- a/docs/reference/providers/with_context.md +++ b/docs/reference/providers/with_context.md @@ -36,7 +36,7 @@ exercises directly: - [`UseFields`](use_fields.md) on a getter component, to read same-named fields; - the bare [`UseContext`](use_context.md), as a higher-order provider's default inner provider. -## When to reach for it, and when not +## When to use it **Reach for the constructs above rather than `WithContext` in practice.** The value it wraps is reached more directly through [`UseContext`](use_context.md), [`UseFields`](use_fields.md), or an diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md index 97667d91..31dd56fe 100644 --- a/docs/reference/providers/with_delegated_type.md +++ b/docs/reference/providers/with_delegated_type.md @@ -85,7 +85,7 @@ delegate_components! { `App` answers two abstract types, with the concrete choices held in one place where they can be reused, swapped, or supplied by a namespace. -## When to reach for it, and when not +## When to use it **Reach for `WithDelegatedType` when several abstract types should be answered from one shared table**, so a context points its type components at the table rather than fixing each one at the wiring site. diff --git a/docs/reference/providers/with_field.md b/docs/reference/providers/with_field.md index 264206b8..555bb1bd 100644 --- a/docs/reference/providers/with_field.md +++ b/docs/reference/providers/with_field.md @@ -62,7 +62,7 @@ delegate_components! { `WithField` expands to `WithProvider>`, so `person.name()` reads the `first_name` field. The field name lives in the wiring, not in the trait. -## When to reach for it, and when not +## When to use it **Prefer the plain [`UseField`](use_field.md) form.** It reads the same field and is the value a [`#[cgp_getter]`](../macros/cgp_getter.md) component is normally wired to. `WithField` exists for the diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md index 3b91db44..1a074202 100644 --- a/docs/reference/providers/with_field_ref.md +++ b/docs/reference/providers/with_field_ref.md @@ -80,7 +80,7 @@ delegate_components! { `config` field, a `StoredConfig`, and because `StoredConfig: AsRef`, returns `&Config` from `as_ref()`. The getter exposes the borrowed `Config` view while the context owns the `StoredConfig`. -## When to reach for it, and when not +## When to use it **Reach for `WithFieldRef` when a getter returns `&T` and the context stores a different type that borrows as `T` through `AsRef`.** The stored type and the exposed type differ, and neither the plain diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index fc6a905a..4f548f61 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -83,7 +83,7 @@ abstract types: wiring a type component to `WithType` adapts [`UseType` adapts a [`UseDelegatedType`](use_delegated_type.md) that resolves the type through a table. -## When to reach for it, and when not +## When to use it **Reach for one of the aliases, not `WithProvider` directly.** [`WithField`](with_field.md), [`WithType`](with_type.md), and [`WithContext`](with_context.md) are interchangeable with the plain diff --git a/docs/reference/providers/with_type.md b/docs/reference/providers/with_type.md index 5b10049d..e43b312d 100644 --- a/docs/reference/providers/with_type.md +++ b/docs/reference/providers/with_type.md @@ -58,7 +58,7 @@ delegate_components! { `Scalar = f64`. The `Copy` bound on the associated type is checked against `f64` where the wiring is written. -## When to reach for it, and when not +## When to use it **Prefer the plain [`UseType`](use_type.md) form.** It binds the same type and is the idiomatic value for a [`#[cgp_type]`](../macros/cgp_type.md) component's wiring entry. `WithType` exists for the diff --git a/docs/reference/traits/append_product.md b/docs/reference/traits/append_product.md index dbe2d4ad..f86826dd 100644 --- a/docs/reference/traits/append_product.md +++ b/docs/reference/traits/append_product.md @@ -78,7 +78,7 @@ where } ``` -## When to reach for it, and when not +## When to use it **Reach for it when a routine must describe the shape it *will* produce** — in a signature, an associated type, or a `where` clause — and essentially never otherwise. It is a building block the extensible-data diff --git a/docs/reference/traits/build_field.md b/docs/reference/traits/build_field.md index e11d2a2f..fc4b212c 100644 --- a/docs/reference/traits/build_field.md +++ b/docs/reference/traits/build_field.md @@ -74,7 +74,7 @@ let employee = Employee::builder() .finalize_build(); ``` -## When to reach for it, and when not +## When to use it **Call `build_field` in any code that fills a builder; bound on the trait when the code is generic over the record.** diff --git a/docs/reference/traits/can_build_from.md b/docs/reference/traits/can_build_from.md index bc74b1fb..1bf3b9dc 100644 --- a/docs/reference/traits/can_build_from.md +++ b/docs/reference/traits/can_build_from.md @@ -73,7 +73,7 @@ let employee = Employee::builder() .finalize_build(); ``` -## When to reach for it, and when not +## When to use it **Reach for it when a record is assembled from independent pieces.** That is the extensible builder pattern's merge step, and it is what the trait exists for. diff --git a/docs/reference/traits/can_build_with_default.md b/docs/reference/traits/can_build_with_default.md index 90b1d258..560602ba 100644 --- a/docs/reference/traits/can_build_with_default.md +++ b/docs/reference/traits/can_build_with_default.md @@ -70,7 +70,7 @@ let point_3d: Point3d = Point3d::builder() .finalize_with_default(); ``` -## When to reach for it, and when not +## When to use it **Reach for it for a one-call widening from a narrower record**, and reach for the pieces when anything in between needs to happen. diff --git a/docs/reference/traits/can_downcast.md b/docs/reference/traits/can_downcast.md index 5a9f7e95..22b1974c 100644 --- a/docs/reference/traits/can_downcast.md +++ b/docs/reference/traits/can_downcast.md @@ -75,7 +75,7 @@ assert_eq!(FooBarBaz::Baz(true).downcast(PhantomData::).ok(), None); `.ok()` is right for a single attempt and wrong when another target should be tried, because it throws away the remainder that the next attempt needs. -## When to reach for it, and when not +## When to use it **Reach for it when a value must be tried against a target the source may or may not fit**, and reach for it *with* [`CanDowncastFields`](./can_downcast_fields.md) when there is more than one candidate: the diff --git a/docs/reference/traits/can_downcast_fields.md b/docs/reference/traits/can_downcast_fields.md index 5aca25a0..f662bb03 100644 --- a/docs/reference/traits/can_downcast_fields.md +++ b/docs/reference/traits/can_downcast_fields.md @@ -82,7 +82,7 @@ match value.downcast(PhantomData::) { The first call starts the chain and the second continues it. Written the other way round — a second `downcast` on the remainder — it does not compile, because a remainder is not an enum. -## When to reach for it, and when not +## When to use it **Reach for it only as the continuation of a [`CanDowncast`](./can_downcast.md) chain.** It has no other use: its `Self` is a remainder, and a remainder only ever comes from a prior downcast. diff --git a/docs/reference/traits/can_finalize_with_default.md b/docs/reference/traits/can_finalize_with_default.md index c6d5c0d9..cb7c2f3a 100644 --- a/docs/reference/traits/can_finalize_with_default.md +++ b/docs/reference/traits/can_finalize_with_default.md @@ -77,7 +77,7 @@ Had that used [`finalize_optional`](./finalize_optional.md), it would have retur The one-call form that also copies from a source is [`CanBuildWithDefault`](./can_build_with_default.md). -## When to reach for it, and when not +## When to use it **Reach for it when unset fields have meaningful defaults and silence is the right outcome.** diff --git a/docs/reference/traits/can_upcast.md b/docs/reference/traits/can_upcast.md index 494ccf32..59610984 100644 --- a/docs/reference/traits/can_upcast.md +++ b/docs/reference/traits/can_upcast.md @@ -74,7 +74,7 @@ assert_eq!(wide, FooBarBaz::Foo(1)); Neither enum names the other. They share variant *names*, matched at the type level, and that is the whole coupling. -## When to reach for it, and when not +## When to use it **Reach for it when an implementation works in a small local enum and its result must be widened.** That is the common use, and it is the construction-side counterpart of reading one field through a getter: diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/can_use_component.md index 4ac72a78..4742e008 100644 --- a/docs/reference/traits/can_use_component.md +++ b/docs/reference/traits/can_use_component.md @@ -137,7 +137,7 @@ some later `person.greet()`. Rename the field to `name` and the block compiles and produces nothing — a passing check is a successful build, with nothing added to the binary. -## When to reach for it, and when not +## When to use it **Reach for [`check_components!`](../macros/check_components.md); it is what reaches for this trait.** The one non-negotiable is that a context's wiring gets checked *somehow* — lazy wiring means an unchecked context can diff --git a/docs/reference/traits/concat_path.md b/docs/reference/traits/concat_path.md index b3b36e47..c62e9d8f 100644 --- a/docs/reference/traits/concat_path.md +++ b/docs/reference/traits/concat_path.md @@ -75,7 +75,7 @@ where } ``` -## When to reach for it, and when not +## When to use it **Reach for it when composing paths in generic code**, which is nested-accessor territory. If you are writing a path literally, [`Path!`](../macros/path.md) already gives you the whole thing and there is diff --git a/docs/reference/traits/concat_product.md b/docs/reference/traits/concat_product.md index ab7df5a6..aff50c20 100644 --- a/docs/reference/traits/concat_product.md +++ b/docs/reference/traits/concat_product.md @@ -71,7 +71,7 @@ type Full = >::Output; Which is the type-level counterpart of what [`CanBuildFrom`](./can_build_from.md) does with values: this names the combined shape, that moves the fields into it. -## When to reach for it, and when not +## When to use it **Reach for it when generic code must name the shape produced by combining two others** — a merge, a routine that extends a record with a caller-supplied set of fields — and essentially never otherwise. diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/contains_value.md index 44871227..c0c86533 100644 --- a/docs/reference/traits/contains_value.md +++ b/docs/reference/traits/contains_value.md @@ -77,7 +77,7 @@ behaviour. stack therefore unwraps two `Result` layers in order, and an *n*-layer stack unwraps *n*, with no code specific to any depth. -## When to reach for it, and when not +## When to use it **Reach for the [monad providers](../providers/monad/index.md), not this trait.** A pipeline is built by wiring [`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker and a handler list; this is what diff --git a/docs/reference/traits/default_impls1.md b/docs/reference/traits/default_impls1.md index 7791a30a..f62b761a 100644 --- a/docs/reference/traits/default_impls1.md +++ b/docs/reference/traits/default_impls1.md @@ -139,7 +139,7 @@ cgp_namespace! { Pointing `for in DefaultShowComponents { … }` at this wires the listed types through the same projection. -## When to reach for it, and when not +## When to use it **Use it for a per-type default, and reach for the simpler trait when the key is a component alone.** diff --git a/docs/reference/traits/default_impls2.md b/docs/reference/traits/default_impls2.md index f7f59636..6860facf 100644 --- a/docs/reference/traits/default_impls2.md +++ b/docs/reference/traits/default_impls2.md @@ -100,7 +100,7 @@ delegate_components! { **Environmental context, parameter-targeted.** The loop variable must still appear in the key, exactly as for the one-type form. -## When to reach for it, and when not +## When to use it **Reach for it when a default genuinely depends on two types**, and prefer the narrower forms otherwise — each extra key position is one more thing a reader has to hold. @@ -115,7 +115,7 @@ each extra key position is one more thing a reader has to hold. purpose-named trait is often the clearer choice. The orphan-rule constraint on where a registration may be *written* is the same as for the one-type form, -and is worked out on [its page](./default_impls1.md#when-to-reach-for-it-and-when-not). +and is worked out on [its page](./default_impls1.md#when-to-use-it). ## Under the hood diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/default_namespace.md index 78cb2a03..b1dc7a05 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/default_namespace.md @@ -92,7 +92,7 @@ delegate_components! { namespace, and the direct entry shadows whatever the namespace would otherwise supply for that one key — the inheritance-with-override shape presets rely on. -## When to reach for it, and when not +## When to use it **Write [`cgp_namespace!`](../macros/cgp_namespace.md) and the wiring statements; name this trait only where the syntax requires it.** It appears in a `namespace` header and nowhere else in ordinary code. @@ -151,7 +151,7 @@ type takes the `Self` position instead. The inconsistency is the family's sharpe **There is no method.** Resolving a default is a type projection. **Registering into a foreign namespace is bound by the orphan rule** — see -[`DefaultImpls1`](./default_impls1.md#when-to-reach-for-it-and-when-not), where the +[`DefaultImpls1`](./default_impls1.md#when-to-use-it), where the [`#[default_impl]`](../attributes/default_impl.md) attribute's placement constraint is worked out. ## Related constructs diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/delegate_component.md index 39d1e13e..3a5a319c 100644 --- a/docs/reference/traits/delegate_component.md +++ b/docs/reference/traits/delegate_component.md @@ -164,7 +164,7 @@ delegate_components! { trait attaches to either; they are data that a [`UseDelegate`](../providers/use_delegate.md) provider reads at dispatch time to pick `RectangleArea` or `CircleArea` for the shape it was asked about. -## When to reach for it, and when not +## When to use it **Write [`delegate_components!`](../macros/delegate_components.md), not `DelegateComponent`.** That is the honest summary of this page: the trait is what you read, and the macro is what you write. The macro also diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/extract_field.md index 7c1344ee..30e6d58e 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/extract_field.md @@ -89,7 +89,7 @@ after only the first extraction and it does not compile. implementations, which is the extensible visitor pattern: a chain exactly like the one above, generated, with one implementation per variant chosen by wiring. -## When to reach for it, and when not +## When to use it **Reach for the family when independent code handles one variant each, or when the matching code cannot name the enum.** Outside those two cases a `match` wins on every count: shorter, clearer, already diff --git a/docs/reference/traits/field_getter.md b/docs/reference/traits/field_getter.md index 2ce020ec..57c830f5 100644 --- a/docs/reference/traits/field_getter.md +++ b/docs/reference/traits/field_getter.md @@ -92,7 +92,7 @@ delegate_components! { A second context can answer the same getter from a different field by changing one wiring line, which is what the provider-side shape buys and what a plain [`HasField`](./has_field.md) bound cannot express. -## When to reach for it, and when not +## When to use it **Wire a `FieldGetter` only when a context must choose which field a getter reads**, which is the advanced case. Everything else is better served higher up. diff --git a/docs/reference/traits/field_mapper.md b/docs/reference/traits/field_mapper.md index 6920d0ca..20d3e989 100644 --- a/docs/reference/traits/field_mapper.md +++ b/docs/reference/traits/field_mapper.md @@ -104,7 +104,7 @@ let name = >::map_field( ); ``` -## When to reach for it, and when not +## When to use it **Reach for [`ChainGetters`](../providers/chain_getters.md) rather than this trait.** It is the construct; `FieldMapper` is the mechanism underneath it. diff --git a/docs/reference/traits/finalize_build.md b/docs/reference/traits/finalize_build.md index e942fdc4..5bab1611 100644 --- a/docs/reference/traits/finalize_build.md +++ b/docs/reference/traits/finalize_build.md @@ -87,7 +87,7 @@ let person = Person::builder() **Read the partial type in the message to see which marker is still `IsNothing`.** That is the field you forgot, and it is the only place the compiler names it. -## When to reach for it, and when not +## When to use it **Call it at the end of every build; bound on it when the code is generic over the record.** diff --git a/docs/reference/traits/finalize_extract.md b/docs/reference/traits/finalize_extract.md index 37ce3b7b..43f6dc2d 100644 --- a/docs/reference/traits/finalize_extract.md +++ b/docs/reference/traits/finalize_extract.md @@ -69,7 +69,7 @@ let rect = remainder .finalize_extract_result(); ``` -## When to reach for it, and when not +## When to use it **Reach for [`FinalizeExtractResult`](./finalize_extract_result.md) unless you already hold a remainder.** The two do the same job at different points in the chain. diff --git a/docs/reference/traits/finalize_extract_result.md b/docs/reference/traits/finalize_extract_result.md index d31c6507..901dd24d 100644 --- a/docs/reference/traits/finalize_extract_result.md +++ b/docs/reference/traits/finalize_extract_result.md @@ -90,7 +90,7 @@ let rect = shape .finalize_extract_result(); ``` -## When to reach for it, and when not +## When to use it **Use it to close every hand-written extraction chain**, and prefer not writing the chain at all. diff --git a/docs/reference/traits/finalize_optional.md b/docs/reference/traits/finalize_optional.md index 8f9a542e..b1374ef8 100644 --- a/docs/reference/traits/finalize_optional.md +++ b/docs/reference/traits/finalize_optional.md @@ -77,7 +77,7 @@ let result = Context::optional_builder() assert_eq!(result.err(), Some("bar")); ``` -## When to reach for it, and when not +## When to use it **Reach for it when absence is an error you want to *report* rather than paper over.** diff --git a/docs/reference/traits/from_fields.md b/docs/reference/traits/from_fields.md index 6ff6dd81..9d6c8ab5 100644 --- a/docs/reference/traits/from_fields.md +++ b/docs/reference/traits/from_fields.md @@ -72,7 +72,7 @@ where An enum rebuilds the same way, from a [`Sum!`](../macros/sum.md) rather than a product — the arm that is present becomes the variant that is constructed. -## When to reach for it, and when not +## When to use it **Bound on it when generic code produces a concrete value from entries it has assembled or transformed.** Pair it with [`ToFields`](./to_fields.md) for a round trip, and require only one of the two when only one diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/from_variant.md index 981a3569..dfdc7a6a 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/from_variant.md @@ -110,7 +110,7 @@ The upcast always succeeds, because every variant of the smaller enum has a home a field through a getter: the implementation names only what it needs, and the widening is checked. Upcasting is documented with the other [structural casts](./can_upcast.md). -## When to reach for it, and when not +## When to use it **Bound on `FromVariant` when the variant to build is decided by a type parameter.** That is the whole test, and it is narrower than the extractor's, because most code decides which variant to build at a site that can diff --git a/docs/reference/traits/has_builder.md b/docs/reference/traits/has_builder.md index 46f4273b..4f081085 100644 --- a/docs/reference/traits/has_builder.md +++ b/docs/reference/traits/has_builder.md @@ -97,7 +97,7 @@ assert_eq!(partial.get_field(PhantomData::), "Alice"); Asking for `last_name` there would not compile. -## When to reach for it, and when not +## When to use it **Call `builder()` freely in concrete code; bound on the trait only in generic code.** In concrete code you call it and never name a trait. The bound matters when you write code that is generic over the diff --git a/docs/reference/traits/has_extractor.md b/docs/reference/traits/has_extractor.md index 2423bdca..7a78b0ff 100644 --- a/docs/reference/traits/has_extractor.md +++ b/docs/reference/traits/has_extractor.md @@ -83,7 +83,7 @@ let shape = Shape::from_extractor(extractor); Note that this only works on an extractor still at the all-possible configuration. Once a variant has been ruled out the type has changed, and there is no way back. -## When to reach for it, and when not +## When to use it **Reach for `to_extractor` only when the chain will take payloads by value**, and prefer a borrowing accessor otherwise — the weakest that works is the right one. diff --git a/docs/reference/traits/has_extractor_mut.md b/docs/reference/traits/has_extractor_mut.md index 56351543..a2416782 100644 --- a/docs/reference/traits/has_extractor_mut.md +++ b/docs/reference/traits/has_extractor_mut.md @@ -70,7 +70,7 @@ if let Ok(circle) = shape The payload arrives as `&mut Circle`, so the write lands in the original value. Written with [`HasExtractor`](./has_extractor.md) instead, the same code would consume `shape` and have to rebuild it. -## When to reach for it, and when not +## When to use it **Reach for it only when a payload must be mutated in place**, which is the narrowest of the three cases. diff --git a/docs/reference/traits/has_extractor_ref.md b/docs/reference/traits/has_extractor_ref.md index e8df3f04..1bb47661 100644 --- a/docs/reference/traits/has_extractor_ref.md +++ b/docs/reference/traits/has_extractor_ref.md @@ -64,7 +64,7 @@ let radius = shape The payload arrives as `&Circle`, so `circle.radius` reads through the borrow and nothing is moved. A full chain narrows the same way, with each remainder also borrowing. -## When to reach for it, and when not +## When to use it **Reach for it whenever the value must survive**, which is most read-only code over an enum. diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/has_field.md index d720997c..ded89f7d 100644 --- a/docs/reference/traits/has_field.md +++ b/docs/reference/traits/has_field.md @@ -122,7 +122,7 @@ let boxed: Box = Box::new(Person { name: "Alice".to_owned() }); assert_eq!(boxed.get_field(PhantomData::), "Alice"); ``` -## When to reach for it, and when not +## When to use it **Bound against `HasField` only when the ergonomic constructs cannot do the job**, which is rarely. The ordering is settled and worth following. diff --git a/docs/reference/traits/has_field_mut.md b/docs/reference/traits/has_field_mut.md index bfc09278..3ee367cf 100644 --- a/docs/reference/traits/has_field_mut.md +++ b/docs/reference/traits/has_field_mut.md @@ -86,7 +86,7 @@ delegate_components! { Mutable access passes through a smart pointer too, via a `DerefMut` forwarding impl, so a `Box` resolves the write to the inner struct. -## When to reach for it, and when not +## When to use it **Bound on it only when the implementation genuinely writes**, and prefer the read-only bound otherwise. Requiring mutation where none happens narrows what a caller can pass for no benefit — a context behind a diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/has_fields.md index 27a4d78f..9c76e846 100644 --- a/docs/reference/traits/has_fields.md +++ b/docs/reference/traits/has_fields.md @@ -107,7 +107,7 @@ giving `Sum![Field, Field`, which routes thro requirement — so the error names the absent field, at the wiring site. Remove the `check_components!` block and the same mistake surfaces far away, at whatever calls `app.greet()`, as a much worse message. -## When to reach for it, and when not +## When to use it **Do not reach for it. Recognize it.** There is no case in ordinary CGP code where you write `IsProviderFor`: the provider macros emit the impl, `#[cgp_component]` emits the supertrait link, and diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/lift_value.md index ddc90470..86d807aa 100644 --- a/docs/reference/traits/lift_value.md +++ b/docs/reference/traits/lift_value.md @@ -79,7 +79,7 @@ bare value is being wrapped for the first time; `lift_output` where a continuati something in the inner shape and the step is passing it outward. Implementing the second as the first collapses the two branches. -## When to reach for it, and when not +## When to use it **Reach for the [monad providers](../providers/monad/index.md), not this trait.** A pipeline is built by wiring [`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker and a handler list. diff --git a/docs/reference/traits/map_field.md b/docs/reference/traits/map_field.md index 81d7f2b4..b16e12df 100644 --- a/docs/reference/traits/map_field.md +++ b/docs/reference/traits/map_field.md @@ -101,7 +101,7 @@ delegate_components! { which is the same descent, chosen at the wiring site rather than written at the call site. -## When to reach for it, and when not +## When to use it **Reach for [`ChainGetters`](../providers/chain_getters.md) rather than this trait.** The provider is the construct; `map_field` is the mechanism it is built from, and calling it by hand means writing at a call diff --git a/docs/reference/traits/map_fields.md b/docs/reference/traits/map_fields.md index 9c785a11..fe4151e4 100644 --- a/docs/reference/traits/map_fields.md +++ b/docs/reference/traits/map_fields.md @@ -80,7 +80,7 @@ type OptionalVariants = >::Mapped; // = Sum![Option, Option] ``` -## When to reach for it, and when not +## When to use it **Reach for it when generic code must name a uniformly re-wrapped shape**, which is what a partial representation is — and essentially never otherwise. diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/map_type.md index 1b4c7f72..181fe643 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/map_type.md @@ -98,7 +98,7 @@ and a projection names one marker's storage directly: // IsVoid::Map is Void ``` -## When to reach for it, and when not +## 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 diff --git a/docs/reference/traits/map_type_ref.md b/docs/reference/traits/map_type_ref.md index fd44c4b8..a29ca63a 100644 --- a/docs/reference/traits/map_type_ref.md +++ b/docs/reference/traits/map_type_ref.md @@ -97,7 +97,7 @@ Neither call names a marker. What the markers do is decide the type the payload in the first case, `&mut Circle` in the second — while the per-field [`MapType`](./map_type.md) markers track which variants are still possible. -## When to reach for it, and when not +## When to use it **You will recognize these markers far more often than you name them**, and recognizing them is most of what this page is for: an error mentioning `IsRef` is telling you the value is being read through diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monadic_bind.md index e076e2c1..713b61a0 100644 --- a/docs/reference/traits/monadic_bind.md +++ b/docs/reference/traits/monadic_bind.md @@ -85,7 +85,7 @@ something succeeds — useful for a fallback chain. **The transformer forms delegate one layer down.** `OkMonadicTrans` and `ErrMonadicTrans` bind their own `Result` layer and hand the rest to `M`, which is how a stack reaches arbitrary depth. -## When to reach for it, and when not +## When to use it **Reach for the [monad providers](../providers/monad/index.md), not this trait.** Building a pipeline means wiring `PipeMonadic` with a monad marker and a handler list; this is what that provider bounds on diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monadic_trans.md index d839c47f..f58fc1eb 100644 --- a/docs/reference/traits/monadic_trans.md +++ b/docs/reference/traits/monadic_trans.md @@ -75,7 +75,7 @@ An *n*-layer stack unwraps *n* layers with no code specific to any depth, which **Layer order is meaningful.** `OkMonadicTrans` and `ErrMonadicTrans` unwrap their `Result` layers in opposite orders and are not interchangeable. -## When to reach for it, and when not +## When to use it **Reach for the [monad providers](../providers/monad/index.md), not this trait.** Wiring [`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker — including a stacked one — is how a diff --git a/docs/reference/traits/mut_field_getter.md b/docs/reference/traits/mut_field_getter.md index 720eb001..365cd7cc 100644 --- a/docs/reference/traits/mut_field_getter.md +++ b/docs/reference/traits/mut_field_getter.md @@ -82,7 +82,7 @@ delegate_components! { and because [`UseField`](../providers/use_field.md) implements `MutFieldGetter` as well, a provider that holds `&mut App` can write through the same wiring. -## When to reach for it, and when not +## When to use it **Wire it only when the mutable access must be chosen per context**, which is rarer than the read case and rarer still than mutation generally. diff --git a/docs/reference/traits/partial_data.md b/docs/reference/traits/partial_data.md index 0089fd7a..af4129f9 100644 --- a/docs/reference/traits/partial_data.md +++ b/docs/reference/traits/partial_data.md @@ -76,7 +76,7 @@ The same appears in [`FinalizeOptional`](./finalize_optional.md), which returns `Result` — again projecting the destination through this trait rather than declaring one of its own. -## When to reach for it, and when not +## When to use it **Bound on it when generic code needs the destination type mid-build**, and reach for the more specific traits otherwise. diff --git a/docs/reference/traits/set_optional.md b/docs/reference/traits/set_optional.md index d2e9a416..e1409e96 100644 --- a/docs/reference/traits/set_optional.md +++ b/docs/reference/traits/set_optional.md @@ -79,7 +79,7 @@ assert_eq!(context.foo, "bar"); Because `set` returns `Self`, the calls chain exactly as core `build_field` calls do — the difference is invisible at the call site and lives entirely in the type. -## When to reach for it, and when not +## When to use it **Reach for it when a field may be set more than once, or when the order is not known.** That is the one thing the core builder cannot express. diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/static_format.md index 6b45556a..d205c44c 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/static_format.md @@ -100,7 +100,7 @@ use cgp::core::field::traits::StaticString; assert_eq!(::VALUE, "height"); ``` -## When to reach for it, and when not +## When to use it **Reach for `Display` for one-off formatting, [`StaticString`](./static_string.md) for a name you use more than once, and this trait only when you need to write characters without a value to hand.** diff --git a/docs/reference/traits/static_string.md b/docs/reference/traits/static_string.md index cb373fcf..56e89fb6 100644 --- a/docs/reference/traits/static_string.md +++ b/docs/reference/traits/static_string.md @@ -69,7 +69,7 @@ Where it shows up in real code is recovering a name for an error. The [optional-field layer](./finalize_optional.md)'s `finalize_optional` reports its missing field by returning `Tag::VALUE` — the field's own name, as a static string, with no allocation. -## When to reach for it, and when not +## When to use it **Reach for `StaticString` when you need a name as data, and for `Display` when you need it in a message.** That is the whole decision. diff --git a/docs/reference/traits/take_field.md b/docs/reference/traits/take_field.md index 8758f221..248920b7 100644 --- a/docs/reference/traits/take_field.md +++ b/docs/reference/traits/take_field.md @@ -68,7 +68,7 @@ let person = remainder Dropping the `build_field` line makes `finalize_build` fail to resolve, which is the guarantee: a field taken out and not replaced cannot be forgotten silently. -## When to reach for it, and when not +## When to use it **Reach for it when a complete value must be decomposed**, and remember that the common case — merging one record into another — already uses it for you. diff --git a/docs/reference/traits/to_fields.md b/docs/reference/traits/to_fields.md index 60c735a3..7630d010 100644 --- a/docs/reference/traits/to_fields.md +++ b/docs/reference/traits/to_fields.md @@ -73,7 +73,7 @@ where } ``` -## When to reach for it, and when not +## When to use it **Bound on it when generic code must consume a value and work on its entries**, and reach for the borrowing form otherwise. diff --git a/docs/reference/traits/to_fields_ref.md b/docs/reference/traits/to_fields_ref.md index ea90de2b..167d009a 100644 --- a/docs/reference/traits/to_fields_ref.md +++ b/docs/reference/traits/to_fields_ref.md @@ -72,7 +72,7 @@ where } ``` -## When to reach for it, and when not +## When to use it **Bound on it whenever generic code reads a shape and the caller keeps the value** — which is most read-only structural code. diff --git a/docs/reference/traits/to_optional.md b/docs/reference/traits/to_optional.md index 8300cbf6..c9991962 100644 --- a/docs/reference/traits/to_optional.md +++ b/docs/reference/traits/to_optional.md @@ -77,7 +77,7 @@ Converting a *complete* value works too, by way of let builder = context.into_builder().to_optional(); // every field Some ``` -## When to reach for it, and when not +## When to use it **Reach for it when a builder already exists and its strictness has become the wrong shape.** diff --git a/docs/reference/traits/transform_map.md b/docs/reference/traits/transform_map.md index dd1415e9..6a40cdf2 100644 --- a/docs/reference/traits/transform_map.md +++ b/docs/reference/traits/transform_map.md @@ -85,7 +85,7 @@ configuration [`FinalizeBuild`](./finalize_build.md) accepts. **That is not hypothetical: it is how [`CanFinalizeWithDefault`](./can_finalize_with_default.md) works**, and reading it here is the shortest route to understanding that layer. -## When to reach for it, and when not +## When to use it **Implement it to define a new per-field conversion**, and reach for the existing layer otherwise. diff --git a/docs/reference/traits/transform_map_default.md b/docs/reference/traits/transform_map_default.md index d4afd410..7af46864 100644 --- a/docs/reference/traits/transform_map_default.md +++ b/docs/reference/traits/transform_map_default.md @@ -90,7 +90,7 @@ The marker is the first type argument, and swapping it for Writing a marker of your own follows the same three-impl shape; the [`TransformMap`](./transform_map.md#examples) page shows one. -## When to reach for it, and when not +## When to use it **Name it only when writing a capability that drives the defaulting conversion.** Everything else is served by the two capabilities already built on it. diff --git a/docs/reference/traits/transform_map_fields.md b/docs/reference/traits/transform_map_fields.md index 152871ee..ec4518a0 100644 --- a/docs/reference/traits/transform_map_fields.md +++ b/docs/reference/traits/transform_map_fields.md @@ -84,7 +84,7 @@ still runs — it just always passes, because the transform guaranteed presence Applying a transform of your own follows the same shape, with your marker in place of `TransformMapDefault`. -## When to reach for it, and when not +## When to use it **Bound on it when writing a capability that re-marks a whole record**, which is what extending the optional-field layer means. diff --git a/docs/reference/traits/transform_optional.md b/docs/reference/traits/transform_optional.md index a9670375..659187f9 100644 --- a/docs/reference/traits/transform_optional.md +++ b/docs/reference/traits/transform_optional.md @@ -89,7 +89,7 @@ much. Writing a marker of your own follows the same shape; the [`TransformMap`](./transform_map.md#examples) page shows one with three impls. -## When to reach for it, and when not +## When to use it **Name it only when writing a capability that drives the optional conversion.** diff --git a/docs/reference/traits/update_field.md b/docs/reference/traits/update_field.md index 8d8e18f8..ea6f1f61 100644 --- a/docs/reference/traits/update_field.md +++ b/docs/reference/traits/update_field.md @@ -87,7 +87,7 @@ let (previous, builder) = builder.update_field( Because both markers are `IsOptional` here, `Output` is the same type as `Self` — which is exactly what lets an optional field be set repeatedly, unlike the core `build_field` that consumes an absent slot once. -## When to reach for it, and when not +## When to use it **Bound on it directly only for an operation neither [`BuildField`](./build_field.md) nor [`TakeField`](./take_field.md) covers.** Those two are the common transitions and read far better at a From 812451609eeafcabe1ec6c4046c501f239d5f2d6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 22:46:19 +0200 Subject: [PATCH 049/516] Move example-code checks from src to tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the example-code crate's page mirrors from src/ to tests/, as one integration-test binary per docs section (concepts, reference, cargo_cgp) pulling in a mirror module tree, and drop the library target. Convert the compile_fail checks — which only ran as doctests against a library — to trybuild compile-fail fixtures under tests/compile_fail/, with a harness and blessed .stderr, and add trybuild as a dev-dependency. Hoist the test-only imports in the component mirrors to module top now that the checks compile as integration tests. Co-Authored-By: Claude Opus 4.8 --- example-code/Cargo.toml | 1 + example-code/README.md | 60 +++++++++----- example-code/src/lib.rs | 24 ------ .../{src => tests}/cargo_cgp/check.rs | 34 +------- .../{src => tests}/cargo_cgp/expand.rs | 0 example-code/{src => tests}/cargo_cgp/mod.rs | 0 example-code/tests/cargo_cgp_tests.rs | 10 +++ .../compile_fail/cargo_cgp/check_check.rs | 33 ++++++++ .../compile_fail/cargo_cgp/check_check.stderr | 28 +++++++ ...ecking_a_bundle_asks_the_wrong_question.rs | 22 ++++++ ...ng_a_bundle_asks_the_wrong_question.stderr | 27 +++++++ ...eck_traits_where_the_failure_surfaces_1.rs | 31 ++++++++ ...traits_where_the_failure_surfaces_1.stderr | 41 ++++++++++ ...eck_traits_where_the_failure_surfaces_2.rs | 32 ++++++++ ...traits_where_the_failure_surfaces_2.stderr | 28 +++++++ ...ce_every_lookup_finds_the_same_answer_1.rs | 17 ++++ ...very_lookup_finds_the_same_answer_1.stderr | 8 ++ ...ce_every_lookup_finds_the_same_answer_2.rs | 9 +++ ...very_lookup_finds_the_same_answer_2.stderr | 19 +++++ .../coherence_the_shape_stops_scaling.rs | 19 +++++ .../coherence_the_shape_stops_scaling.stderr | 8 ++ ...traits_what_an_ordinary_rust_trait_does.rs | 11 +++ ...ts_what_an_ordinary_rust_trait_does.stderr | 33 ++++++++ ...cords_finalizing_early_does_not_compile.rs | 20 +++++ ...s_finalizing_early_does_not_compile.stderr | 17 ++++ ...dic_handlers_plain_composition_is_wrong.rs | 13 +++ ...handlers_plain_composition_is_wrong.stderr | 22 ++++++ ...aces_a_bound_entry_is_not_overridable_1.rs | 30 +++++++ ..._a_bound_entry_is_not_overridable_1.stderr | 17 ++++ ...aces_a_bound_entry_is_not_overridable_2.rs | 26 ++++++ ..._a_bound_entry_is_not_overridable_2.stderr | 7 ++ ..._bounds_the_bound_a_caller_cannot_write.rs | 20 +++++ ...nds_the_bound_a_caller_cannot_write.stderr | 15 ++++ ..._rejected_build_from_without_has_fields.rs | 28 +++++++ ...ected_build_from_without_has_fields.stderr | 14 ++++ ...e_build_field_rejected_incomplete_build.rs | 14 ++++ ...ild_field_rejected_incomplete_build.stderr | 17 ++++ ...d_field_rejected_read_of_an_unset_field.rs | 15 ++++ ...eld_rejected_read_of_an_unset_field.stderr | 15 ++++ ..._cgp_data_rejected_struct_style_variant.rs | 8 ++ ..._data_rejected_struct_style_variant.stderr | 5 ++ ...p_variant_rejected_struct_style_variant.rs | 8 ++ ...riant_rejected_struct_style_variant.stderr | 5 ++ ...tract_field_rejected_premature_finalize.rs | 26 ++++++ ...t_field_rejected_premature_finalize.stderr | 28 +++++++ ...e_extract_field_rejected_variant_shapes.rs | 9 +++ ...tract_field_rejected_variant_shapes.stderr | 5 ++ ...m_variant_rejected_struct_style_variant.rs | 8 ++ ...riant_rejected_struct_style_variant.stderr | 5 ++ .../reference/errors_the_fix_1.rs | 41 ++++++++++ .../reference/errors_the_fix_1.stderr | 37 +++++++++ .../reference/errors_the_fix_2.rs | 36 +++++++++ .../reference/errors_the_fix_2.stderr | 10 +++ .../macros/delegate_components_gotchas.rs | 24 ++++++ .../macros/delegate_components_gotchas.stderr | 5 ++ ..._rejected_build_from_without_has_fields.rs | 21 +++++ ...ected_build_from_without_has_fields.stderr | 14 ++++ .../has_builder_rejected_incomplete_build.rs | 14 ++++ ...s_builder_rejected_incomplete_build.stderr | 17 ++++ example-code/tests/compile_fail_tests.rs | 14 ++++ .../{src => tests}/concepts/abstract_types.rs | 0 .../concepts/aggregate_providers.rs | 70 ++++++---------- .../{src => tests}/concepts/check_traits.rs | 20 +---- .../{src => tests}/concepts/coherence.rs | 48 +---------- .../concepts/consumer_and_provider_traits.rs | 12 +-- .../{src => tests}/concepts/dispatching.rs | 0 .../concepts/extensible_records.rs | 23 +----- .../concepts/extensible_variants.rs | 0 .../{src => tests}/concepts/handlers.rs | 0 .../concepts/higher_order_providers.rs | 0 .../concepts/impl_side_dependencies.rs | 0 .../concepts/implicit_arguments.rs | 0 example-code/{src => tests}/concepts/mod.rs | 0 .../concepts/modular_error_handling.rs | 0 .../concepts/modularity_hierarchy.rs | 0 .../concepts/monadic_handlers.rs | 11 +-- .../{src => tests}/concepts/namespaces.rs | 58 +------------- .../{src => tests}/concepts/send_bounds.rs | 12 +-- .../concepts/type_level_dsls.rs | 0 example-code/tests/concepts_tests.rs | 10 +++ .../reference/components/can_raise_error.rs | 0 .../reference/components/can_wrap_error.rs | 0 .../components/handler/async_computer.rs | 0 .../components/handler/async_computer_ref.rs | 0 .../reference/components/handler/computer.rs | 4 +- .../components/handler/computer_ref.rs | 0 .../reference/components/handler/handler.rs | 0 .../components/handler/handler_ref.rs | 0 .../reference/components/handler/mod.rs | 0 .../reference/components/handler/producer.rs | 4 +- .../components/handler/try_computer.rs | 4 +- .../components/handler/try_computer_ref.rs | 0 .../reference/components/has_error_type.rs | 0 .../reference/components/has_runtime.rs | 0 .../reference/components/has_runtime_type.rs | 0 .../reference/components/has_type.rs | 0 .../reference/components/mod.rs | 0 .../reference/components/runner.rs | 3 +- .../reference/components/send_runner.rs | 3 +- .../reference/derives/derive_build_field.rs | 54 +------------ .../reference/derives/derive_cgp_data.rs | 9 +-- .../reference/derives/derive_cgp_record.rs | 0 .../reference/derives/derive_cgp_variant.rs | 9 +-- .../reference/derives/derive_extract_field.rs | 31 +------- .../reference/derives/derive_from_variant.rs | 9 +-- .../reference/derives/derive_has_field.rs | 0 .../reference/derives/derive_has_fields.rs | 0 .../{src => tests}/reference/derives/mod.rs | 0 .../{src => tests}/reference/errors.rs | 79 +------------------ .../reference/macros/delegate_components.rs | 25 +----- .../{src => tests}/reference/macros/mod.rs | 0 example-code/{src => tests}/reference/mod.rs | 0 .../reference/providers/chain_getters.rs | 0 .../providers/dispatch/build_and_merge.rs | 0 .../dispatch/build_and_merge_outputs.rs | 0 .../providers/dispatch/build_and_set_field.rs | 0 .../providers/dispatch/build_with_handlers.rs | 0 .../providers/dispatch/downcast_and_handle.rs | 0 .../dispatch/extract_field_and_handle.rs | 0 .../providers/dispatch/handle_field_value.rs | 0 .../dispatch/match_first_with_handlers.rs | 0 .../dispatch/match_with_field_handlers.rs | 0 .../providers/dispatch/match_with_handlers.rs | 0 .../dispatch/match_with_value_handlers.rs | 0 .../reference/providers/dispatch/mod.rs | 0 .../reference/providers/error/debug_error.rs | 0 .../providers/error/discard_detail.rs | 0 .../providers/error/display_error.rs | 0 .../reference/providers/error/mod.rs | 0 .../providers/error/panic_on_error.rs | 0 .../reference/providers/error/raise_from.rs | 0 .../providers/error/raise_infallible.rs | 0 .../reference/providers/error/return_error.rs | 0 .../providers/handler/compose_handlers.rs | 0 .../reference/providers/handler/mod.rs | 0 .../providers/handler/pipe_handlers.rs | 0 .../reference/providers/handler/promote.rs | 0 .../providers/handler/promote_async.rs | 0 .../handler/promote_async_computer.rs | 0 .../providers/handler/promote_computer.rs | 0 .../providers/handler/promote_handler.rs | 0 .../providers/handler/promote_producer.rs | 0 .../providers/handler/promote_ref.rs | 0 .../providers/handler/promote_try_computer.rs | 0 .../providers/handler/return_input.rs | 0 .../providers/handler/try_promote.rs | 0 .../providers/handler/use_input_delegate.rs | 0 .../{src => tests}/reference/providers/mod.rs | 0 .../reference/providers/monad/bind_err.rs | 0 .../reference/providers/monad/bind_ok.rs | 0 .../reference/providers/monad/mod.rs | 0 .../reference/providers/monad/pipe_monadic.rs | 0 .../reference/providers/redirect_lookup.rs | 0 .../reference/providers/use_context.rs | 0 .../reference/providers/use_default.rs | 0 .../reference/providers/use_delegate.rs | 0 .../reference/providers/use_field.rs | 0 .../reference/providers/use_fields.rs | 0 .../reference/providers/use_type.rs | 0 .../providers/with_delegated_type.rs | 0 .../reference/providers/with_field.rs | 0 .../reference/providers/with_field_ref.rs | 0 .../reference/providers/with_provider.rs | 0 .../reference/providers/with_type.rs | 0 .../reference/traits/append_product.rs | 0 .../reference/traits/can_build_from.rs | 0 .../reference/traits/can_downcast.rs | 0 .../reference/traits/can_downcast_fields.rs | 0 .../reference/traits/can_upcast.rs | 0 .../reference/traits/concat_path.rs | 0 .../reference/traits/concat_product.rs | 0 .../reference/traits/has_builder.rs | 30 +------ .../reference/traits/map_fields.rs | 0 .../{src => tests}/reference/traits/mod.rs | 0 .../reference/traits/static_format.rs | 0 .../reference/traits/static_string.rs | 0 example-code/tests/reference_tests.rs | 10 +++ 177 files changed, 1123 insertions(+), 540 deletions(-) delete mode 100644 example-code/src/lib.rs rename example-code/{src => tests}/cargo_cgp/check.rs (50%) rename example-code/{src => tests}/cargo_cgp/expand.rs (100%) rename example-code/{src => tests}/cargo_cgp/mod.rs (100%) create mode 100644 example-code/tests/cargo_cgp_tests.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/check_check.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/check_check.stderr create mode 100644 example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs create mode 100644 example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.stderr create mode 100644 example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs create mode 100644 example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.stderr create mode 100644 example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs create mode 100644 example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr create mode 100644 example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.rs create mode 100644 example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.stderr create mode 100644 example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.rs create mode 100644 example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.stderr create mode 100644 example-code/tests/compile_fail/concepts/coherence_the_shape_stops_scaling.rs create mode 100644 example-code/tests/compile_fail/concepts/coherence_the_shape_stops_scaling.stderr create mode 100644 example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs create mode 100644 example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.stderr create mode 100644 example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.rs create mode 100644 example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.stderr create mode 100644 example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.rs create mode 100644 example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr create mode 100644 example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.rs create mode 100644 example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.stderr create mode 100644 example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.rs create mode 100644 example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.stderr create mode 100644 example-code/tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.rs create mode 100644 example-code/tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/errors_the_fix_1.rs create mode 100644 example-code/tests/compile_fail/reference/errors_the_fix_1.stderr create mode 100644 example-code/tests/compile_fail/reference/errors_the_fix_2.rs create mode 100644 example-code/tests/compile_fail/reference/errors_the_fix_2.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs create mode 100644 example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.rs create mode 100644 example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.stderr create mode 100644 example-code/tests/compile_fail_tests.rs rename example-code/{src => tests}/concepts/abstract_types.rs (100%) rename example-code/{src => tests}/concepts/aggregate_providers.rs (81%) rename example-code/{src => tests}/concepts/check_traits.rs (88%) rename example-code/{src => tests}/concepts/coherence.rs (78%) rename example-code/{src => tests}/concepts/consumer_and_provider_traits.rs (95%) rename example-code/{src => tests}/concepts/dispatching.rs (100%) rename example-code/{src => tests}/concepts/extensible_records.rs (78%) rename example-code/{src => tests}/concepts/extensible_variants.rs (100%) rename example-code/{src => tests}/concepts/handlers.rs (100%) rename example-code/{src => tests}/concepts/higher_order_providers.rs (100%) rename example-code/{src => tests}/concepts/impl_side_dependencies.rs (100%) rename example-code/{src => tests}/concepts/implicit_arguments.rs (100%) rename example-code/{src => tests}/concepts/mod.rs (100%) rename example-code/{src => tests}/concepts/modular_error_handling.rs (100%) rename example-code/{src => tests}/concepts/modularity_hierarchy.rs (100%) rename example-code/{src => tests}/concepts/monadic_handlers.rs (88%) rename example-code/{src => tests}/concepts/namespaces.rs (83%) rename example-code/{src => tests}/concepts/send_bounds.rs (89%) rename example-code/{src => tests}/concepts/type_level_dsls.rs (100%) create mode 100644 example-code/tests/concepts_tests.rs rename example-code/{src => tests}/reference/components/can_raise_error.rs (100%) rename example-code/{src => tests}/reference/components/can_wrap_error.rs (100%) rename example-code/{src => tests}/reference/components/handler/async_computer.rs (100%) rename example-code/{src => tests}/reference/components/handler/async_computer_ref.rs (100%) rename example-code/{src => tests}/reference/components/handler/computer.rs (90%) rename example-code/{src => tests}/reference/components/handler/computer_ref.rs (100%) rename example-code/{src => tests}/reference/components/handler/handler.rs (100%) rename example-code/{src => tests}/reference/components/handler/handler_ref.rs (100%) rename example-code/{src => tests}/reference/components/handler/mod.rs (100%) rename example-code/{src => tests}/reference/components/handler/producer.rs (89%) rename example-code/{src => tests}/reference/components/handler/try_computer.rs (94%) rename example-code/{src => tests}/reference/components/handler/try_computer_ref.rs (100%) rename example-code/{src => tests}/reference/components/has_error_type.rs (100%) rename example-code/{src => tests}/reference/components/has_runtime.rs (100%) rename example-code/{src => tests}/reference/components/has_runtime_type.rs (100%) rename example-code/{src => tests}/reference/components/has_type.rs (100%) rename example-code/{src => tests}/reference/components/mod.rs (100%) rename example-code/{src => tests}/reference/components/runner.rs (98%) rename example-code/{src => tests}/reference/components/send_runner.rs (98%) rename example-code/{src => tests}/reference/derives/derive_build_field.rs (83%) rename example-code/{src => tests}/reference/derives/derive_cgp_data.rs (96%) rename example-code/{src => tests}/reference/derives/derive_cgp_record.rs (100%) rename example-code/{src => tests}/reference/derives/derive_cgp_variant.rs (93%) rename example-code/{src => tests}/reference/derives/derive_extract_field.rs (89%) rename example-code/{src => tests}/reference/derives/derive_from_variant.rs (96%) rename example-code/{src => tests}/reference/derives/derive_has_field.rs (100%) rename example-code/{src => tests}/reference/derives/derive_has_fields.rs (100%) rename example-code/{src => tests}/reference/derives/mod.rs (100%) rename example-code/{src => tests}/reference/errors.rs (62%) rename example-code/{src => tests}/reference/macros/delegate_components.rs (97%) rename example-code/{src => tests}/reference/macros/mod.rs (100%) rename example-code/{src => tests}/reference/mod.rs (100%) rename example-code/{src => tests}/reference/providers/chain_getters.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/build_and_merge.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/build_and_merge_outputs.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/build_and_set_field.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/build_with_handlers.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/downcast_and_handle.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/extract_field_and_handle.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/handle_field_value.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/match_first_with_handlers.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/match_with_field_handlers.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/match_with_handlers.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/match_with_value_handlers.rs (100%) rename example-code/{src => tests}/reference/providers/dispatch/mod.rs (100%) rename example-code/{src => tests}/reference/providers/error/debug_error.rs (100%) rename example-code/{src => tests}/reference/providers/error/discard_detail.rs (100%) rename example-code/{src => tests}/reference/providers/error/display_error.rs (100%) rename example-code/{src => tests}/reference/providers/error/mod.rs (100%) rename example-code/{src => tests}/reference/providers/error/panic_on_error.rs (100%) rename example-code/{src => tests}/reference/providers/error/raise_from.rs (100%) rename example-code/{src => tests}/reference/providers/error/raise_infallible.rs (100%) rename example-code/{src => tests}/reference/providers/error/return_error.rs (100%) rename example-code/{src => tests}/reference/providers/handler/compose_handlers.rs (100%) rename example-code/{src => tests}/reference/providers/handler/mod.rs (100%) rename example-code/{src => tests}/reference/providers/handler/pipe_handlers.rs (100%) rename example-code/{src => tests}/reference/providers/handler/promote.rs (100%) rename example-code/{src => tests}/reference/providers/handler/promote_async.rs (100%) rename example-code/{src => tests}/reference/providers/handler/promote_async_computer.rs (100%) rename example-code/{src => tests}/reference/providers/handler/promote_computer.rs (100%) rename example-code/{src => tests}/reference/providers/handler/promote_handler.rs (100%) rename example-code/{src => tests}/reference/providers/handler/promote_producer.rs (100%) rename example-code/{src => tests}/reference/providers/handler/promote_ref.rs (100%) rename example-code/{src => tests}/reference/providers/handler/promote_try_computer.rs (100%) rename example-code/{src => tests}/reference/providers/handler/return_input.rs (100%) rename example-code/{src => tests}/reference/providers/handler/try_promote.rs (100%) rename example-code/{src => tests}/reference/providers/handler/use_input_delegate.rs (100%) rename example-code/{src => tests}/reference/providers/mod.rs (100%) rename example-code/{src => tests}/reference/providers/monad/bind_err.rs (100%) rename example-code/{src => tests}/reference/providers/monad/bind_ok.rs (100%) rename example-code/{src => tests}/reference/providers/monad/mod.rs (100%) rename example-code/{src => tests}/reference/providers/monad/pipe_monadic.rs (100%) rename example-code/{src => tests}/reference/providers/redirect_lookup.rs (100%) rename example-code/{src => tests}/reference/providers/use_context.rs (100%) rename example-code/{src => tests}/reference/providers/use_default.rs (100%) rename example-code/{src => tests}/reference/providers/use_delegate.rs (100%) rename example-code/{src => tests}/reference/providers/use_field.rs (100%) rename example-code/{src => tests}/reference/providers/use_fields.rs (100%) rename example-code/{src => tests}/reference/providers/use_type.rs (100%) rename example-code/{src => tests}/reference/providers/with_delegated_type.rs (100%) rename example-code/{src => tests}/reference/providers/with_field.rs (100%) rename example-code/{src => tests}/reference/providers/with_field_ref.rs (100%) rename example-code/{src => tests}/reference/providers/with_provider.rs (100%) rename example-code/{src => tests}/reference/providers/with_type.rs (100%) rename example-code/{src => tests}/reference/traits/append_product.rs (100%) rename example-code/{src => tests}/reference/traits/can_build_from.rs (100%) rename example-code/{src => tests}/reference/traits/can_downcast.rs (100%) rename example-code/{src => tests}/reference/traits/can_downcast_fields.rs (100%) rename example-code/{src => tests}/reference/traits/can_upcast.rs (100%) rename example-code/{src => tests}/reference/traits/concat_path.rs (100%) rename example-code/{src => tests}/reference/traits/concat_product.rs (100%) rename example-code/{src => tests}/reference/traits/has_builder.rs (80%) rename example-code/{src => tests}/reference/traits/map_fields.rs (100%) rename example-code/{src => tests}/reference/traits/mod.rs (100%) rename example-code/{src => tests}/reference/traits/static_format.rs (100%) rename example-code/{src => tests}/reference/traits/static_string.rs (100%) create mode 100644 example-code/tests/reference_tests.rs diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index b0cc285b..5f9d2e0b 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -10,5 +10,6 @@ cgp = "0.8.0-alpha" [dev-dependencies] futures = "0.3" +trybuild = "1" [workspace] diff --git a/example-code/README.md b/example-code/README.md index d597816b..cafa721e 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -8,25 +8,36 @@ that page can be checked against something the compiler has agreed to rather tha Run it from this directory: ```sh -cargo test # the full check: the code compiles, and the rejected snippets still fail -cargo check # the fast check: the code compiles +cargo test # the full check: the code compiles, and the rejected snippets still fail +cargo test --no-run # the fast check: everything compiles, nothing runs ``` +The code lives in **integration tests**, which a plain `cargo check` skips; use `cargo test --no-run` +(or `cargo check --tests`) for a compile-only pass. The crate has no library or binary target. + ## The layout mirrors `docs/` +The code lives under `tests/`, as one integration-test binary per `docs/` section. Each entrypoint +pulls in a module tree that mirrors that section's pages: + +- `tests/concepts_tests.rs` → `tests/concepts/`, mirroring `docs/concepts/` +- `tests/reference_tests.rs` → `tests/reference/`, mirroring `docs/reference/` +- `tests/cargo_cgp_tests.rs` → `tests/cargo_cgp/`, mirroring `docs/cargo-cgp/` +- `tests/compile_fail_tests.rs` → `tests/compile_fail/`, the snippets the pages **reject** (see below) + One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| -| `docs/concepts/` | complete — sixteen files under `src/concepts/`, one per page that shows code | +| `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | | `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), and all of `components/` (each component page that shows code, including the `handler/` subsection); `types/` is the remaining gap, and the section is filled in lazily | -| `docs/cargo-cgp/` | complete — the two pages that show Rust, under `src/cargo_cgp/` | +| `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | Within a covered section the mapping is mechanical: `docs/concepts/coherence.md` is answered by -`src/concepts/coherence.rs`, and `docs/concepts/consumer-and-provider-traits.md` by -`src/concepts/consumer_and_provider_traits.rs`. +`tests/concepts/coherence.rs`, and `docs/concepts/consumer-and-provider-traits.md` by +`tests/concepts/consumer_and_provider_traits.rs`. A page that shows no code gets no file — `docs/concepts/modularity-hierarchy.md` is prose and tables, so it has no module here, and neither does a section index. @@ -59,25 +70,32 @@ page is not, so the page is the likelier culprit, but a stale file here is worse ## Code a page deliberately rejects -Several pages show code the compiler refuses, quoting the error as the point of the snippet. That -code cannot live in the crate, so it is carried as a `compile_fail` doctest in the module for its -section, with the quoted error code in a comment. +Several pages show code the compiler refuses, quoting the error as the point of the snippet. That code +cannot live in a module, so each rejected snippet is a standalone fixture under `tests/compile_fail/`, +at the page's mirrored path, and [`trybuild`](https://docs.rs/trybuild) compiles each one and checks +that it fails. The harness is `tests/compile_fail_tests.rs`. + +Each fixture is a **complete program** whose only fault is the intended one: the elided bodies are +filled in, an item-only snippet carries a trailing `fn main() {}`, and a snippet with statements is +wrapped in `fn main() { ... }` — the way rustdoc wraps the doctest these were carried as before. -Two limits are worth knowing. **`compile_fail` does not check *which* error is produced** — rustdoc -accepts an error code after the annotation but does not enforce it, so a snippet that starts failing -for an unrelated reason still passes. What the doctest genuinely catches is the regression that -matters: a snippet the page calls rejected that the compiler has started accepting. And **a body the -page elides has to be filled in for these too**, so that the quoted error is the only thing wrong -with the snippet — an empty `/* ... */` body would fail on its own and the doctest would pass while -proving nothing. +trybuild compares each fixture's output against a sibling `.stderr` file. **What that genuinely guards +is the regression that matters: a snippet the page calls rejected that the compiler has started +accepting.** The exact wording of a `.stderr` is toolchain- and `cgp`-version-specific, so re-bless +them after a bump rather than editing them by hand: + +```sh +TRYBUILD=overwrite cargo test --test compile_fail_tests +``` ## Generated code Two of these pages show what a macro *generates*, in simplified form. A hand-rolled rendering of such a listing — as `concepts::consumer_and_provider_traits::how_a_call_finds_its_provider` carries — is a weaker check than the rest of this crate: it shows the listing is structurally sound, not that its -text is current. **The authority on what a macro emits is `cargo cgp expand --lib --item …`**, run -against the crate the page's example lives in. Check the text with `expand`; check the shape here. +text is current. **The authority on what a macro emits is `cargo cgp expand`**, run against the test +target the example lives in (for example `cargo cgp expand --test concepts_tests --item …`). Check the +text with `expand`; check the shape here. ## Adding a file @@ -85,8 +103,10 @@ Files are added **lazily**: when a page that shows code is written, or revised, is created or brought back into agreement in the same change. There is no obligation to backfill pages nobody is working on, and a missing file means only that nobody has been through that page yet. -Adding one means creating it at the mirrored path, registering it in the parent `mod.rs`, adding a -row to the table above, and leaving `cargo test` green. +Adding a runnable one means creating it at the mirrored path under `tests/

/`, registering it +in the parent `mod.rs`, adding a row to the table above, and leaving `cargo test` green. Adding a +rejected snippet means writing a fixture under `tests/compile_fail/`, blessing its `.stderr` with +`TRYBUILD=overwrite cargo test --test compile_fail_tests`, and leaving `cargo test` green. ## The `cgp` version diff --git a/example-code/src/lib.rs b/example-code/src/lib.rs deleted file mode 100644 index ad406dbd..00000000 --- a/example-code/src/lib.rs +++ /dev/null @@ -1,24 +0,0 @@ -//! Compiled counterparts of the code shown on . -//! -//! This crate is **not part of the website**. Nothing here is rendered, linked, or served, and no -//! page refers to it. It exists so that an agent revising a documentation page can check the code on -//! that page against something the compiler has agreed to, instead of reading the snippet and hoping. -//! -//! The layout mirrors the `docs/` tree one file per page: the code on -//! `docs/concepts/consumer-and-provider-traits.md` lives in -//! `src/concepts/consumer_and_provider_traits.rs`, and so on for every page that shows code. Pages -//! that show none get no file. Duplication between files is expected and wanted — each file answers -//! for one page, so a shared example is written out again rather than factored into a helper that -//! neither page shows. -//! -//! See `README.md` for how to use it, what "matches" means when a page elides a body, and the rules -//! for adding a file. - -// A page shows the shape of a program rather than a whole one, so its code is full of items nothing -// calls and parameters nothing reads once an elided body is filled in. Those warnings would be noise -// here; a warning that means something — an unused import, an unreachable pattern — still fires. -#![allow(dead_code, unused_variables)] - -pub mod cargo_cgp; -pub mod concepts; -pub mod reference; diff --git a/example-code/src/cargo_cgp/check.rs b/example-code/tests/cargo_cgp/check.rs similarity index 50% rename from example-code/src/cargo_cgp/check.rs rename to example-code/tests/cargo_cgp/check.rs index ebead929..0e79c495 100644 --- a/example-code/src/cargo_cgp/check.rs +++ b/example-code/tests/cargo_cgp/check.rs @@ -9,36 +9,4 @@ //! nothing at all about the `cargo cgp check` output the page quotes beside it. That output was //! produced by running the tool, and re-running it is the only way to re-verify it. //! -//! ```compile_fail -//! use cgp::prelude::*; -//! -//! #[cgp_component(AreaCalculator)] -//! pub trait CanCalculateArea { -//! fn area(&self) -> f64; -//! } -//! -//! #[cgp_impl(new RectangleArea)] -//! impl AreaCalculator { -//! fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { -//! width * height -//! } -//! } -//! -//! // The mistake: no `height` field, though the provider reads one. -//! #[derive(HasField)] -//! pub struct Rectangle { -//! pub width: f64, -//! } -//! -//! delegate_components! { -//! Rectangle { -//! AreaCalculatorComponent: RectangleArea, -//! } -//! } -//! -//! check_components! { -//! Rectangle { -//! AreaCalculatorComponent, -//! } -//! } -//! ``` +//! Rejected snippet — trybuild fixture `tests/compile_fail/cargo_cgp/check_check.rs`. diff --git a/example-code/src/cargo_cgp/expand.rs b/example-code/tests/cargo_cgp/expand.rs similarity index 100% rename from example-code/src/cargo_cgp/expand.rs rename to example-code/tests/cargo_cgp/expand.rs diff --git a/example-code/src/cargo_cgp/mod.rs b/example-code/tests/cargo_cgp/mod.rs similarity index 100% rename from example-code/src/cargo_cgp/mod.rs rename to example-code/tests/cargo_cgp/mod.rs diff --git a/example-code/tests/cargo_cgp_tests.rs b/example-code/tests/cargo_cgp_tests.rs new file mode 100644 index 00000000..3c4d6f11 --- /dev/null +++ b/example-code/tests/cargo_cgp_tests.rs @@ -0,0 +1,10 @@ +//! Runnable checks for the code shown on the `docs/cargo-cgp/` pages. +//! +//! One module per page, under `tests/cargo_cgp/`. See the crate `README.md` for the layout and for +//! how the rejected snippets are handled (they live under `tests/compile_fail/`). + +// A page shows the shape of a program rather than a whole one, so its code carries items nothing calls +// and parameters nothing reads once an elided body is filled in. A genuinely unused import still warns. +#![allow(dead_code, unused_variables)] + +mod cargo_cgp; diff --git a/example-code/tests/compile_fail/cargo_cgp/check_check.rs b/example-code/tests/compile_fail/cargo_cgp/check_check.rs new file mode 100644 index 00000000..861ab2b1 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/check_check.rs @@ -0,0 +1,33 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +// The mistake: no `height` field, though the provider reads one. +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/check_check.stderr b/example-code/tests/compile_fail/cargo_cgp/check_check.stderr new file mode 100644 index 00000000..9e680bac --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/check_check.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `Rectangle: CanUseComponent` is not satisfied + --> tests/compile_fail/cargo_cgp/check_check.rs:29:9 + | +29 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>` is implemented for it + --> tests/compile_fail/cargo_cgp/check_check.rs:16:10 + | +16 | #[derive(HasField)] + | ^^^^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/cargo_cgp/check_check.rs:8:1 + | + 8 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Rectangle` to implement `CanUseComponent` +note: required by a bound in `__CheckRectangle` + --> tests/compile_fail/cargo_cgp/check_check.rs:27:1 + | +27 | / check_components! { +28 | | Rectangle { +29 | | AreaCalculatorComponent, +30 | | } +31 | | } + | |_^ required by this bound in `__CheckRectangle` + = note: this error originates in the derive macro `HasField` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs b/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs new file mode 100644 index 00000000..cfab3380 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs @@ -0,0 +1,22 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { width * height } +} + +// error[E0277]: the trait bound +// `GeometryComponents: CanUseComponent` +// is not satisfied +delegate_and_check_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.stderr b/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.stderr new file mode 100644 index 00000000..8a45d920 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.stderr @@ -0,0 +1,27 @@ +error[E0277]: the trait bound `GeometryComponents: CanUseComponent` is not satisfied + --> tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs:18:9 + | +18 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::prelude::HasField>>>>>>` is not implemented for `GeometryComponents` + --> tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs:17:9 + | +17 | new GeometryComponents { + | ^^^^^^^^^^^^^^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs:8:1 + | + 8 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `GeometryComponents` to implement `CanUseComponent` +note: required by a bound in `__CanUseGeometryComponents` + --> tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs:16:1 + | +16 | / delegate_and_check_components! { +17 | | new GeometryComponents { +18 | | AreaCalculatorComponent: RectangleArea, +19 | | } +20 | | } + | |_^ required by this bound in `__CanUseGeometryComponents` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `delegate_and_check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs new file mode 100644 index 00000000..ae9173ba --- /dev/null +++ b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs @@ -0,0 +1,31 @@ +use core::cell::RefCell; + +use cgp::prelude::*; + +#[cgp_component(EmailSender)] +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + +#[cgp_impl(new RecordEmails)] +impl EmailSender { + fn send_email(&self, #[implicit] sent_emails: &RefCell>, to: &str, body: &str) { + sent_emails.borrow_mut().push(format!("{to}: {body}")); + } +} + +// The mistake: `BrokenApp` has no `sent_emails` field, though `RecordEmails` reads one. +#[derive(HasField)] +pub struct BrokenApp { + pub smtp_server: String, +} + +delegate_components! { BrokenApp { EmailSenderComponent: RecordEmails } } + +fn main() { + let app = BrokenApp { + smtp_server: "localhost".to_owned(), + }; + // The hidden failure: `E0599` at the call site, naming nothing about the missing field. + app.send_email("a@b.c", "hi"); +} diff --git a/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.stderr b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.stderr new file mode 100644 index 00000000..5e6dd2fc --- /dev/null +++ b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.stderr @@ -0,0 +1,41 @@ +error[E0599]: the method `send_email` exists for struct `BrokenApp`, but its trait bounds were not satisfied + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:30:9 + | +19 | pub struct BrokenApp { + | -------------------- method `send_email` not found for this struct because it doesn't satisfy `BrokenApp: CanSendEmail` or `BrokenApp: EmailSender` +... +30 | app.send_email("a@b.c", "hi"); + | ^^^^^^^^^^ this is an associated function, not a method + | + = note: found the following associated functions; to be used as methods, functions must have a `self` parameter +note: the candidate is defined in the trait `EmailSender` + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:7:5 + | + 7 | fn send_email(&self, to: &str, body: &str); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: trait bound `BrokenApp: EmailSender` was not satisfied + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:5:1 + | + 5 | #[cgp_component(EmailSender)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 6 | pub trait CanSendEmail { + | ^^^^^^^^^^^^ +note: the trait `EmailSender` must be implemented + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:6:1 + | + 6 | / pub trait CanSendEmail { + 7 | | fn send_email(&self, to: &str, body: &str); + 8 | | } + | |_^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `CanSendEmail` defines an item `send_email`, perhaps you need to implement it + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs:6:1 + | + 6 | pub trait CanSendEmail { + | ^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use associated function syntax instead + | +30 - app.send_email("a@b.c", "hi"); +30 + BrokenApp::send_email("a@b.c", "hi"); + | diff --git a/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs new file mode 100644 index 00000000..68ccc9c7 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs @@ -0,0 +1,32 @@ +use core::cell::RefCell; + +use cgp::prelude::*; + +#[cgp_component(EmailSender)] +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + +#[cgp_impl(new RecordEmails)] +impl EmailSender { + fn send_email(&self, #[implicit] sent_emails: &RefCell>, to: &str, body: &str) { + sent_emails.borrow_mut().push(format!("{to}: {body}")); + } +} + +// The mistake: `BrokenApp` has no `sent_emails` field, though `RecordEmails` reads one. +#[derive(HasField)] +pub struct BrokenApp { + pub smtp_server: String, +} + +delegate_components! { BrokenApp { EmailSenderComponent: RecordEmails } } + +// The check forces the failure to the wiring site and names the missing field. +check_components! { + BrokenApp { + EmailSenderComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr new file mode 100644 index 00000000..1e7c73c8 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `BrokenApp: CanUseComponent` is not satisfied + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:28:9 + | +28 | EmailSenderComponent, + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>>>>>>>` is not implemented for `BrokenApp` + but trait `HasField>>>>>>>>>>>>` is implemented for it + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:18:10 + | +18 | #[derive(HasField)] + | ^^^^^^^^ +note: required for `RecordEmails` to implement `IsProviderFor` + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:10:1 + | +10 | #[cgp_impl(new RecordEmails)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `BrokenApp` to implement `CanUseComponent` +note: required by a bound in `__CheckBrokenApp` + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:26:1 + | +26 | / check_components! { +27 | | BrokenApp { +28 | | EmailSenderComponent, +29 | | } +30 | | } + | |_^ required by this bound in `__CheckBrokenApp` + = note: this error originates in the derive macro `HasField` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.rs b/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.rs new file mode 100644 index 00000000..cc842070 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.rs @@ -0,0 +1,17 @@ +use core::fmt::Display; + +pub trait CanEncode { + fn encode(&self) -> Vec; +} + +// Legal on its own. +impl CanEncode for T { + fn encode(&self) -> Vec { self.to_string().into_bytes() } +} + +// error[E0119]: conflicting implementations of trait `CanEncode` +impl> CanEncode for T { + fn encode(&self) -> Vec { self.as_ref().to_vec() } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.stderr b/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.stderr new file mode 100644 index 00000000..2066bcb0 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.stderr @@ -0,0 +1,8 @@ +error[E0119]: conflicting implementations of trait `CanEncode` + --> tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.rs:13:1 + | + 8 | impl CanEncode for T { + | -------------------------------- first implementation here +... +13 | impl> CanEncode for T { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation diff --git a/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.rs b/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.rs new file mode 100644 index 00000000..a1c1fb56 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.rs @@ -0,0 +1,9 @@ +use core::fmt::{self, Display, Formatter}; + +// error[E0117]: only traits defined in the current crate can be implemented +// for types defined outside of the crate +impl Display for Vec { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { Ok(()) } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.stderr b/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.stderr new file mode 100644 index 00000000..d1113157 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.stderr @@ -0,0 +1,19 @@ +error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate + --> tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.rs:5:1 + | +5 | impl Display for Vec { + | ^^^^^^^^^^^^^^^^^------- + | | + | `Vec` is not defined in the current crate + | + = note: impl doesn't have any local type before any uncovered type parameters + = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules + = note: define and implement a trait or new type instead + +warning: unused variable: `f` + --> tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.rs:6:19 + | +6 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { Ok(()) } + | ^ help: if this is intentional, prefix it with an underscore: `_f` + | + = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default diff --git a/example-code/tests/compile_fail/concepts/coherence_the_shape_stops_scaling.rs b/example-code/tests/compile_fail/concepts/coherence_the_shape_stops_scaling.rs new file mode 100644 index 00000000..f74a07eb --- /dev/null +++ b/example-code/tests/compile_fail/concepts/coherence_the_shape_stops_scaling.rs @@ -0,0 +1,19 @@ +use core::fmt::Display; + +pub trait CanEncodeValue { + fn encode(&self, value: &Value) -> Vec; +} + +pub struct ApiServer; + +impl CanEncodeValue for ApiServer { + fn encode(&self, value: &V) -> Vec { value.to_string().into_bytes() } +} + +// error[E0119]: conflicting implementations of trait `CanEncodeValue<_>` +// for type `ApiServer` +impl> CanEncodeValue for ApiServer { + fn encode(&self, value: &V) -> Vec { value.as_ref().to_vec() } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/coherence_the_shape_stops_scaling.stderr b/example-code/tests/compile_fail/concepts/coherence_the_shape_stops_scaling.stderr new file mode 100644 index 00000000..b12b2290 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/coherence_the_shape_stops_scaling.stderr @@ -0,0 +1,8 @@ +error[E0119]: conflicting implementations of trait `CanEncodeValue<_>` for type `ApiServer` + --> tests/compile_fail/concepts/coherence_the_shape_stops_scaling.rs:15:1 + | + 9 | impl CanEncodeValue for ApiServer { + | ------------------------------------------------ first implementation here +... +15 | impl> CanEncodeValue for ApiServer { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ApiServer` diff --git a/example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs b/example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs new file mode 100644 index 00000000..accf69e7 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs @@ -0,0 +1,11 @@ +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + +pub trait HasSmtpConfig {} +pub trait HasRecordedEmails {} + +impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } +impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } // error[E0119] + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.stderr b/example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.stderr new file mode 100644 index 00000000..a23664da --- /dev/null +++ b/example-code/tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.stderr @@ -0,0 +1,33 @@ +error[E0119]: conflicting implementations of trait `CanSendEmail` + --> tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs:9:1 + | +8 | impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } + | --------------------------------------------- first implementation here +9 | impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } // error[E0119] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation + +warning: unused variable: `to` + --> tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs:8:70 + | +8 | impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } + | ^^ help: if this is intentional, prefix it with an underscore: `_to` + | + = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default + +warning: unused variable: `body` + --> tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs:8:80 + | +8 | impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } + | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` + +warning: unused variable: `to` + --> tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs:9:70 + | +9 | impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } // error[E0119] + | ^^ help: if this is intentional, prefix it with an underscore: `_to` + +warning: unused variable: `body` + --> tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs:9:80 + | +9 | impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } // error[E0119] + | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` diff --git a/example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.rs b/example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.rs new file mode 100644 index 00000000..72c7f188 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.rs @@ -0,0 +1,20 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct App { + pub database: String, + pub http_timeout: u32, +} + +#[derive(CgpData)] +pub struct DatabaseConfig { + pub database: String, +} + +fn main() { + // `http_timeout` has never been set, so there is no `finalize_build` to call. + let _app: App = App::builder() + .build_from(DatabaseConfig { database: "postgres://…".to_owned() }) + .finalize_build(); +} diff --git a/example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.stderr b/example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.stderr new file mode 100644 index 00000000..16dcc7a8 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.stderr @@ -0,0 +1,17 @@ +error[E0599]: no method named `finalize_build` found for struct `__PartialApp<__F0__, __F1__>` in the current scope + --> tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.rs:19:10 + | + 5 | pub struct App { + | -------------- method `finalize_build` not found for this struct +... +17 | let _app: App = App::builder() + | _____________________- +18 | | .build_from(DatabaseConfig { database: "postgres://…".to_owned() }) +19 | | .finalize_build(); + | | -^^^^^^^^^^^^^^ method not found in `__PartialApp` + | |_________| + | + | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `finalize_build`, perhaps you need to implement it: + candidate #1: `cgp::prelude::FinalizeBuild` diff --git a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.rs b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.rs new file mode 100644 index 00000000..3818bf83 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.rs @@ -0,0 +1,13 @@ +use cgp::extra::handler::{Computer, PipeHandlers}; +use cgp::prelude::*; + +#[cgp_computer] +pub fn increment(value: u8) -> Result { + value.checked_add(1).ok_or("overflow") +} + +fn main() { + // `Increment` produces `Result` and the next `Increment` wants a `u8`, so plain + // composition does not type-check. + let _ = PipeHandlers::::compute(&(), PhantomData::<()>, 1u8); +} diff --git a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr new file mode 100644 index 00000000..97ad2ad9 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr @@ -0,0 +1,22 @@ +error[E0599]: the associated function or constant `compute` exists for struct `PipeHandlers>>`, but its trait bounds were not satisfied + --> tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.rs:12:61 + | +12 | let _ = PipeHandlers::::compute(&(), PhantomData::<()>, 1u8); + | ^^^^^^^ associated function or constant cannot be called due to unsatisfied trait bounds + | + ::: $CARGO/cgp-handler-$VERSION/src/providers/pipe.rs + | + | pub struct PipeHandlers(pub PhantomData); + | ---------------------------------- doesn't satisfy `_: Computer<_, _, _>` or `_: IsProviderFor` + | + = note: the following trait bounds were not satisfied: + `PipeHandlers>>: IsProviderFor` + which is required by `PipeHandlers>>: Computer<_, _, _>` + `&PipeHandlers>>: DelegateComponent` + which is required by `&PipeHandlers>>: Computer<_, _, _>` + `&PipeHandlers>>: IsProviderFor` + which is required by `&PipeHandlers>>: Computer<_, _, _>` + `&mut PipeHandlers>>: DelegateComponent` + which is required by `&mut PipeHandlers>>: Computer<_, _, _>` + `&mut PipeHandlers>>: IsProviderFor` + which is required by `&mut PipeHandlers>>: Computer<_, _, _>` diff --git a/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.rs b/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.rs new file mode 100644 index 00000000..6b5beb59 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.rs @@ -0,0 +1,30 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { fn greet(&self) -> String; } + +#[cgp_impl(new GreetHello)] +impl Greeter { fn greet(&self) -> String { "Hello!".to_owned() } } + +#[cgp_impl(new GreetQuietly)] +impl Greeter { fn greet(&self) -> String { "hello".to_owned() } } + +cgp_namespace! { + new AppDefaults { + GreeterComponent: GreetHello, + } +} + +pub struct TestApp; + +// error[E0119]: conflicting implementations of trait +// `DelegateComponent` for type `TestApp` +delegate_components! { + TestApp { + namespace AppDefaults; + + GreeterComponent: GreetQuietly, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.stderr b/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.stderr new file mode 100644 index 00000000..1afa52d2 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.stderr @@ -0,0 +1,17 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `TestApp` + --> tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.rs:26:9 + | +24 | namespace AppDefaults; + | ----------- first implementation here +25 | +26 | GreeterComponent: GreetQuietly, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `TestApp` + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `TestApp` + --> tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.rs:26:9 + | +24 | namespace AppDefaults; + | ----------- first implementation here +25 | +26 | GreeterComponent: GreetQuietly, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `TestApp` diff --git a/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.rs b/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.rs new file mode 100644 index 00000000..e74293f0 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.rs @@ -0,0 +1,26 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { fn greet(&self) -> String; } + +#[cgp_impl(new GreetHello)] +impl Greeter { fn greet(&self) -> String { "Hello!".to_owned() } } + +#[cgp_impl(new GreetQuietly)] +impl Greeter { fn greet(&self) -> String { "hello".to_owned() } } + +cgp_namespace! { + new BaseDefaults { + GreeterComponent: GreetHello, + } +} + +// error[E0119]: conflicting implementations of trait `QuietDefaults<_>` +// for type `GreeterComponent` +cgp_namespace! { + new QuietDefaults: BaseDefaults { + GreeterComponent: GreetQuietly, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.stderr b/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.stderr new file mode 100644 index 00000000..5da09b69 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.stderr @@ -0,0 +1,7 @@ +error[E0119]: conflicting implementations of trait `QuietDefaults<_>` for type `GreeterComponent` + --> tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.rs:22:9 + | +21 | new QuietDefaults: BaseDefaults { + | ------------ first implementation here +22 | GreeterComponent: GreetQuietly, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `GreeterComponent` diff --git a/example-code/tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.rs b/example-code/tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.rs new file mode 100644 index 00000000..4f7b0ad7 --- /dev/null +++ b/example-code/tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.rs @@ -0,0 +1,20 @@ +use core::marker::PhantomData; + +use cgp::prelude::*; + +#[cgp_component(ApiHandler)] +#[async_trait] +pub trait CanHandleApi { + type Response; + + async fn handle_api(&self, _api: PhantomData) -> Self::Response; +} + +// Not available on stable Rust: the return-type-notation bound `handle_api(..): Send`. +fn spawn_handler(app: App) +where + App: CanHandleApi + Send + 'static, +{ +} + +fn main() {} diff --git a/example-code/tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.stderr b/example-code/tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.stderr new file mode 100644 index 00000000..3fac3f4a --- /dev/null +++ b/example-code/tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.stderr @@ -0,0 +1,15 @@ +error[E0658]: return type notation is experimental + --> tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.rs:16:38 + | +16 | App: CanHandleApi + Send + 'static, + | ^^^^ + | + = note: see issue #109417 for more information + +warning: unused variable: `app` + --> tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.rs:14:28 + | +14 | fn spawn_handler(app: App) + | ^^^ help: if this is intentional, prefix it with an underscore: `_app` + | + = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs new file mode 100644 index 00000000..ef214485 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs @@ -0,0 +1,28 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct FooBar { + pub foo: u64, + pub bar: String, +} + +#[derive(BuildField)] +pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, +} + +fn main() { + // `build_from` needs `#[derive(HasFields)]` on the source, which `FooBar` lacks. + let source = FooBar { + foo: 1, + bar: "bar".to_owned(), + }; + + let _ = FooBarBaz::builder() + .build_from(source) + .build_field(PhantomData::, true) + .finalize_build(); +} diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr new file mode 100644 index 00000000..49d94b6e --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr @@ -0,0 +1,14 @@ +error[E0277]: the trait bound `FooBar: HasFields` is not satisfied + --> tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs:25:21 + | +25 | .build_from(source) + | ---------- ^^^^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call + | +help: the trait `HasFields` is not implemented for `FooBar` + --> tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs:5:1 + | + 5 | pub struct FooBar { + | ^^^^^^^^^^^^^^^^^ + = note: required for `__PartialFooBarBaz` to implement `CanBuildFrom` diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.rs b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.rs new file mode 100644 index 00000000..948ab5d0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.rs @@ -0,0 +1,14 @@ +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +fn main() { + // `finalize_build` is called without setting `last_name`. + let person: Person = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .finalize_build(); +} diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.stderr new file mode 100644 index 00000000..4039029a --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.stderr @@ -0,0 +1,17 @@ +error[E0599]: no method named `finalize_build` found for struct `__PartialPerson<__F0__, __F1__>` in the current scope + --> tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.rs:13:10 + | + 4 | pub struct Person { + | ----------------- method `finalize_build` not found for this struct +... +11 | let person: Person = Person::builder() + | __________________________- +12 | | .build_field(PhantomData::, "Alice".to_owned()) +13 | | .finalize_build(); + | | -^^^^^^^^^^^^^^ method not found in `__PartialPerson` + | |_________| + | + | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `finalize_build`, perhaps you need to implement it: + candidate #1: `cgp::prelude::FinalizeBuild` diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.rs b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.rs new file mode 100644 index 00000000..3f686144 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.rs @@ -0,0 +1,15 @@ +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +fn main() { + let partial = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()); + + // Reading a field that was never set. + let _ = partial.get_field(PhantomData::); +} diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr new file mode 100644 index 00000000..3235b125 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr @@ -0,0 +1,15 @@ +error[E0308]: mismatched types + --> tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.rs:14:31 + | +14 | let _ = partial.get_field(PhantomData::); + | --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `10`, found `9` + | | + | arguments to this method are incorrect + | + = note: expected struct `std::marker::PhantomData>>>>>>>>>>>` + found struct `std::marker::PhantomData>>>>>>>>>>` +note: method defined here + --> $CARGO/cgp-field-$VERSION/src/traits/has_field.rs + | + | fn get_field(&self, _tag: PhantomData) -> &Self::Value; + | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.rs new file mode 100644 index 00000000..41e74255 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.rs @@ -0,0 +1,8 @@ +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle { radius: f64 }, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.stderr new file mode 100644 index 00000000..ff165eca --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.stderr @@ -0,0 +1,5 @@ +error: Expected variant to contain exactly one unnamed field + --> tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.rs:5:5 + | +5 | Circle { radius: f64 }, + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.rs new file mode 100644 index 00000000..d11eae19 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.rs @@ -0,0 +1,8 @@ +use cgp::prelude::*; + +#[derive(CgpVariant)] +pub enum Shape { + Circle { radius: f64 }, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.stderr new file mode 100644 index 00000000..18bce633 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.stderr @@ -0,0 +1,5 @@ +error: Expected variant to contain exactly one unnamed field + --> tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.rs:5:5 + | +5 | Circle { radius: f64 }, + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.rs b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.rs new file mode 100644 index 00000000..4270beb3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.rs @@ -0,0 +1,26 @@ +use cgp::core::field::traits::FinalizeExtractResult; +use cgp::prelude::*; + +pub struct Circle { + pub radius: f64, +} +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn main() { + let shape = Shape::Circle(Circle { radius: 1.0 }); + + // Finalizing after extracting only one of the two variants. + let _ = shape + .to_extractor() + .extract_field(PhantomData::) + .finalize_extract_result(); +} diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr new file mode 100644 index 00000000..bf431dcf --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr @@ -0,0 +1,28 @@ +error[E0599]: the method `finalize_extract_result` exists for enum `Result>`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.rs:25:10 + | +13 | pub enum Shape { + | -------------- doesn't satisfy `__PartialShape: FinalizeExtract` +... +22 | let _ = shape + | _____________- +23 | | .to_extractor() +24 | | .extract_field(PhantomData::) +25 | | .finalize_extract_result(); + | | -^^^^^^^^^^^^^^^^^^^^^^^ method cannot be called on `Result>` due to unsatisfied trait bounds + | |_________| + | + | + ::: $RUST/core/src/result.rs + | + | pub enum Result { + | --------------------- doesn't satisfy `_: FinalizeExtractResult` + | + = note: the following trait bounds were not satisfied: + `__PartialShape: FinalizeExtract` + which is required by `Result>: FinalizeExtractResult` +note: the trait `FinalizeExtract` must be implemented + --> $CARGO/cgp-field-$VERSION/src/traits/extract_field.rs + | + | pub trait FinalizeExtract { + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.rs b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.rs new file mode 100644 index 00000000..419bd31c --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +#[derive(ExtractField)] +pub enum Shape { + Circle { radius: f64 }, + Empty, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.stderr new file mode 100644 index 00000000..3594ca8c --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.stderr @@ -0,0 +1,5 @@ +error: Expected variant to contain exactly one unnamed field + --> tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.rs:5:5 + | +5 | Circle { radius: f64 }, + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.rs new file mode 100644 index 00000000..62cce3bd --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.rs @@ -0,0 +1,8 @@ +use cgp::prelude::*; + +#[derive(FromVariant)] +pub enum Shape { + Circle { radius: f64 }, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.stderr new file mode 100644 index 00000000..de202c15 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.stderr @@ -0,0 +1,5 @@ +error: Expected variant to contain exactly one unnamed field + --> tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.rs:5:5 + | +5 | Circle { radius: f64 }, + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_1.rs b/example-code/tests/compile_fail/reference/errors_the_fix_1.rs new file mode 100644 index 00000000..f4312820 --- /dev/null +++ b/example-code/tests/compile_fail/reference/errors_the_fix_1.rs @@ -0,0 +1,41 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + let _ = self.name(); + } +} + +#[derive(HasField)] +pub struct Person { + pub age: u8, +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} + +// error[E0277]: [CGP-E001] the consumer trait `CanGreet` is not implemented for +// context `Person` +// root cause: [CGP-E106] missing field `name` on `Person` +check_components! { + Person { + GreeterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr b/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr new file mode 100644 index 00000000..ceba3f39 --- /dev/null +++ b/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr @@ -0,0 +1,37 @@ +error[E0277]: the trait bound `Person: CanUseComponent` is not satisfied + --> tests/compile_fail/reference/errors_the_fix_1.rs:37:9 + | +37 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>` is not implemented for `Person` + but trait `HasField>>>>` is implemented for it + --> tests/compile_fail/reference/errors_the_fix_1.rs:21:10 + | +21 | #[derive(HasField)] + | ^^^^^^^^ +note: required for `Person` to implement `HasName` + --> tests/compile_fail/reference/errors_the_fix_1.rs:8:1 + | + 8 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ + 9 | pub trait HasName { + | ^^^^^^^ +note: required for `GreetHello` to implement `IsProviderFor` + --> tests/compile_fail/reference/errors_the_fix_1.rs:13:1 + | +13 | #[cgp_impl(new GreetHello)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +14 | #[uses(HasName)] + | ------- unsatisfied trait bound introduced here + = note: required for `Person` to implement `CanUseComponent` +note: required by a bound in `__CheckPerson` + --> tests/compile_fail/reference/errors_the_fix_1.rs:35:1 + | +35 | / check_components! { +36 | | Person { +37 | | GreeterComponent, +38 | | } +39 | | } + | |_^ required by this bound in `__CheckPerson` + = note: this error originates in the derive macro `HasField` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_2.rs b/example-code/tests/compile_fail/reference/errors_the_fix_2.rs new file mode 100644 index 00000000..493540dc --- /dev/null +++ b/example-code/tests/compile_fail/reference/errors_the_fix_2.rs @@ -0,0 +1,36 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + let _ = self.name(); + } +} + +#[derive(HasField)] +pub struct Person { + pub age: u8, +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} + +// error[E0599]: the method `greet` exists for struct `Person`, but its trait bounds +// were not satisfied +Person { age: 0 }.greet(); + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_2.stderr b/example-code/tests/compile_fail/reference/errors_the_fix_2.stderr new file mode 100644 index 00000000..50f750bd --- /dev/null +++ b/example-code/tests/compile_fail/reference/errors_the_fix_2.stderr @@ -0,0 +1,10 @@ +error: missing `struct` for struct definition + --> tests/compile_fail/reference/errors_the_fix_2.rs:34:1 + | +34 | Person { age: 0 }.greet(); + | ^^^^^^ + | +help: add `struct` here to parse `Person` as a struct + | +34 | struct Person { age: 0 }.greet(); + | ++++++ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.rs new file mode 100644 index 00000000..45ddbb20 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.rs @@ -0,0 +1,24 @@ +use cgp::prelude::*; + +#[cgp_component(FooProvider)] +pub trait Foo { + fn foo(&self, value: &T); +} + +#[cgp_impl(new DummyFoo)] +impl FooProvider { + fn foo(&self, _value: &T) {} +} + +pub struct App; + +// error: expected `:` +delegate_components! { + App { + open FooProviderComponent; + + @FooProviderComponent.{String, u32}.bool: DummyFoo, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.stderr new file mode 100644 index 00000000..22230728 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.stderr @@ -0,0 +1,5 @@ +error: expected `:` + --> tests/compile_fail/reference/macros/delegate_components_gotchas.rs:20:44 + | +20 | @FooProviderComponent.{String, u32}.bool: DummyFoo, + | ^ diff --git a/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs new file mode 100644 index 00000000..dc21ad9f --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs @@ -0,0 +1,21 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct FooBar { + pub foo: u64, +} + +#[derive(BuildField)] +pub struct FooBaz { + pub foo: u64, + pub baz: bool, +} + +fn main() { + // `build_from` needs `#[derive(HasFields)]` on the source, which `FooBar` lacks. + let _ = FooBaz::builder() + .build_from(FooBar { foo: 1 }) + .build_field(PhantomData::, true) + .finalize_build(); +} diff --git a/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr new file mode 100644 index 00000000..acfe2a78 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr @@ -0,0 +1,14 @@ +error[E0277]: the trait bound `FooBar: HasFields` is not satisfied + --> tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs:18:21 + | +18 | .build_from(FooBar { foo: 1 }) + | ---------- ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call + | +help: the trait `HasFields` is not implemented for `FooBar` + --> tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs:5:1 + | + 5 | pub struct FooBar { + | ^^^^^^^^^^^^^^^^^ + = note: required for `__PartialFooBaz` to implement `CanBuildFrom` diff --git a/example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.rs b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.rs new file mode 100644 index 00000000..948ab5d0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.rs @@ -0,0 +1,14 @@ +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +fn main() { + // `finalize_build` is called without setting `last_name`. + let person: Person = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .finalize_build(); +} diff --git a/example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.stderr b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.stderr new file mode 100644 index 00000000..ad83ecd7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.stderr @@ -0,0 +1,17 @@ +error[E0599]: no method named `finalize_build` found for struct `__PartialPerson<__F0__, __F1__>` in the current scope + --> tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.rs:13:10 + | + 4 | pub struct Person { + | ----------------- method `finalize_build` not found for this struct +... +11 | let person: Person = Person::builder() + | __________________________- +12 | | .build_field(PhantomData::, "Alice".to_owned()) +13 | | .finalize_build(); + | | -^^^^^^^^^^^^^^ method not found in `__PartialPerson` + | |_________| + | + | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `finalize_build`, perhaps you need to implement it: + candidate #1: `cgp::prelude::FinalizeBuild` diff --git a/example-code/tests/compile_fail_tests.rs b/example-code/tests/compile_fail_tests.rs new file mode 100644 index 00000000..55fe6169 --- /dev/null +++ b/example-code/tests/compile_fail_tests.rs @@ -0,0 +1,14 @@ +//! Compile-fail checks for the snippets the docs pages deliberately reject. +//! +//! Each fixture under `tests/compile_fail/` is a complete program the compiler must refuse, carrying +//! the rejected snippet with its elided bodies filled in so the intended error is the only thing +//! wrong with it. `trybuild` compiles each one and compares its output against the sibling `.stderr` +//! file; a fixture that has started compiling is the regression this guards against. +//! +//! Re-bless the `.stderr` files after a toolchain or `cgp` bump with +//! `TRYBUILD=overwrite cargo test --test compile_fail_tests`. + +#[test] +fn rejected_snippets_do_not_compile() { + trybuild::TestCases::new().compile_fail("tests/compile_fail/**/*.rs"); +} diff --git a/example-code/src/concepts/abstract_types.rs b/example-code/tests/concepts/abstract_types.rs similarity index 100% rename from example-code/src/concepts/abstract_types.rs rename to example-code/tests/concepts/abstract_types.rs diff --git a/example-code/src/concepts/aggregate_providers.rs b/example-code/tests/concepts/aggregate_providers.rs similarity index 81% rename from example-code/src/concepts/aggregate_providers.rs rename to example-code/tests/concepts/aggregate_providers.rs index 0f4535e4..e2c2910b 100644 --- a/example-code/src/concepts/aggregate_providers.rs +++ b/example-code/tests/concepts/aggregate_providers.rs @@ -147,53 +147,35 @@ pub mod bundles_nest { /// the two ways is silent. /// /// The silent one. `AlwaysOne` needs nothing from its context, so it implements the provider trait -/// for every context including the bundle — the check passes and proves nothing: -/// -/// ```rust -/// use cgp::prelude::*; -/// -/// #[cgp_component(AreaCalculator)] -/// pub trait CanCalculateArea { -/// fn area(&self) -> f64; -/// } -/// -/// #[cgp_impl(new AlwaysOne)] -/// impl AreaCalculator { -/// fn area(&self) -> f64 { 1.0 } -/// } -/// -/// delegate_and_check_components! { -/// new GeometryComponents { -/// AreaCalculatorComponent: AlwaysOne, -/// } -/// } -/// ``` +/// for every context including the bundle — the check passes and proves nothing. It is in the module +/// body below, since it compiles. /// /// The loud one. `RectangleArea` needs fields, and the check demands them of the bundle: /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[cgp_component(AreaCalculator)] -/// pub trait CanCalculateArea { -/// fn area(&self) -> f64; -/// } -/// -/// #[cgp_impl(new RectangleArea)] -/// impl AreaCalculator { -/// fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { width * height } -/// } -/// -/// // error[E0277]: the trait bound -/// // `GeometryComponents: CanUseComponent` -/// // is not satisfied -/// delegate_and_check_components! { -/// new GeometryComponents { -/// AreaCalculatorComponent: RectangleArea, -/// } -/// } -/// ``` -pub mod checking_a_bundle_asks_the_wrong_question {} +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs`. +pub mod checking_a_bundle_asks_the_wrong_question { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new AlwaysOne)] + impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } + } + + // The silent pass: `delegate_and_check_components!` on the bundle compiles, because `AlwaysOne` + // needs nothing from a context, so the check proves nothing. + delegate_and_check_components! { + new GeometryComponents { + AreaCalculatorComponent: AlwaysOne, + } + } +} /// ## Checking the bundle on its own, correctly /// diff --git a/example-code/src/concepts/check_traits.rs b/example-code/tests/concepts/check_traits.rs similarity index 88% rename from example-code/src/concepts/check_traits.rs rename to example-code/tests/concepts/check_traits.rs index 1328a9e8..52ad6228 100644 --- a/example-code/src/concepts/check_traits.rs +++ b/example-code/tests/concepts/check_traits.rs @@ -35,28 +35,12 @@ pub mod a_context_can_be_wrong_and_still_compile { /// Calling the capability is the first thing that forces the question, so the error arrives at the /// call rather than at the wiring — and names a field requirement the caller never wrote. /// -/// ```compile_fail -/// use cgp_website_example_code::concepts::check_traits::a_context_can_be_wrong_and_still_compile::*; -/// -/// fn main() { -/// let app = BrokenApp { smtp_server: "localhost".to_owned() }; -/// app.send_email("a@b.c", "hi"); -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs`. /// /// A check placed beside the wiring forces the same question at a line you chose. This one fails, /// which is the point of it: /// -/// ```compile_fail -/// use cgp::prelude::*; -/// use cgp_website_example_code::concepts::check_traits::a_context_can_be_wrong_and_still_compile::*; -/// -/// check_components! { -/// BrokenApp { -/// EmailSenderComponent, -/// } -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs`. pub mod where_the_failure_surfaces {} /// ## A check is an empty impl of a trait that demands something diff --git a/example-code/src/concepts/coherence.rs b/example-code/tests/concepts/coherence.rs similarity index 78% rename from example-code/src/concepts/coherence.rs rename to example-code/tests/concepts/coherence.rs index ec49bbcc..aa953de7 100644 --- a/example-code/src/concepts/coherence.rs +++ b/example-code/tests/concepts/coherence.rs @@ -27,35 +27,11 @@ pub mod trait_system_as_dependency_injection { /// /// The overlap rule. `String` is both `Display` and `AsRef<[u8]>`: /// -/// ```compile_fail -/// use core::fmt::Display; -/// -/// pub trait CanEncode { -/// fn encode(&self) -> Vec; -/// } -/// -/// // Legal on its own. -/// impl CanEncode for T { -/// fn encode(&self) -> Vec { self.to_string().into_bytes() } -/// } -/// -/// // error[E0119]: conflicting implementations of trait `CanEncode` -/// impl> CanEncode for T { -/// fn encode(&self) -> Vec { self.as_ref().to_vec() } -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.rs`. /// /// The orphan rule. Neither `Display` nor `Vec` belongs to this crate: /// -/// ```compile_fail -/// use core::fmt::{self, Display, Formatter}; -/// -/// // error[E0117]: only traits defined in the current crate can be implemented -/// // for types defined outside of the crate -/// impl Display for Vec { -/// fn fmt(&self, f: &mut Formatter) -> fmt::Result { Ok(()) } -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.rs`. pub mod every_lookup_finds_the_same_answer {} /// ## The move: make `Self` a type you own @@ -179,23 +155,5 @@ pub mod the_shape_this_depends_on { /// The second block of that section: factoring the shared logic into a blanket implementation runs /// into the overlap rule, this time on an application type. Rejected, so it is a doctest. /// -/// ```compile_fail -/// use core::fmt::Display; -/// -/// pub trait CanEncodeValue { -/// fn encode(&self, value: &Value) -> Vec; -/// } -/// -/// pub struct ApiServer; -/// -/// impl CanEncodeValue for ApiServer { -/// fn encode(&self, value: &V) -> Vec { value.to_string().into_bytes() } -/// } -/// -/// // error[E0119]: conflicting implementations of trait `CanEncodeValue<_>` -/// // for type `ApiServer` -/// impl> CanEncodeValue for ApiServer { -/// fn encode(&self, value: &V) -> Vec { value.as_ref().to_vec() } -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/coherence_the_shape_stops_scaling.rs`. pub mod the_shape_stops_scaling {} diff --git a/example-code/src/concepts/consumer_and_provider_traits.rs b/example-code/tests/concepts/consumer_and_provider_traits.rs similarity index 95% rename from example-code/src/concepts/consumer_and_provider_traits.rs rename to example-code/tests/concepts/consumer_and_provider_traits.rs index 9d05e931..0310e2d3 100644 --- a/example-code/src/concepts/consumer_and_provider_traits.rs +++ b/example-code/tests/concepts/consumer_and_provider_traits.rs @@ -14,17 +14,7 @@ /// marker traits it bounds on are undeclared on the page, so they are declared here; without them /// the failure would be an unresolved name rather than the overlap it is meant to show: /// -/// ```compile_fail -/// pub trait CanSendEmail { -/// fn send_email(&self, to: &str, body: &str); -/// } -/// -/// pub trait HasSmtpConfig {} -/// pub trait HasRecordedEmails {} -/// -/// impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } -/// impl CanSendEmail for T { fn send_email(&self, to: &str, body: &str) {} } // error[E0119] -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/consumer_and_provider_traits_what_an_ordinary_rust_trait_does.rs`. pub mod what_an_ordinary_rust_trait_does { use core::cell::RefCell; diff --git a/example-code/src/concepts/dispatching.rs b/example-code/tests/concepts/dispatching.rs similarity index 100% rename from example-code/src/concepts/dispatching.rs rename to example-code/tests/concepts/dispatching.rs diff --git a/example-code/src/concepts/extensible_records.rs b/example-code/tests/concepts/extensible_records.rs similarity index 78% rename from example-code/src/concepts/extensible_records.rs rename to example-code/tests/concepts/extensible_records.rs index cf018580..c261aa79 100644 --- a/example-code/src/concepts/extensible_records.rs +++ b/example-code/tests/concepts/extensible_records.rs @@ -74,26 +74,5 @@ pub mod building_one_field_at_a_time { /// The partial record tracks which fields are present, and the operation that turns it back into /// the struct exists only at the all-present configuration. /// -/// ```compile_fail -/// use cgp::core::field::impls::CanBuildFrom; -/// use cgp::prelude::*; -/// -/// #[derive(CgpData)] -/// pub struct App { -/// pub database: String, -/// pub http_timeout: u32, -/// } -/// -/// #[derive(CgpData)] -/// pub struct DatabaseConfig { -/// pub database: String, -/// } -/// -/// fn main() { -/// // `http_timeout` has never been set, so there is no `finalize_build` to call. -/// let _app: App = App::builder() -/// .build_from(DatabaseConfig { database: "postgres://…".to_owned() }) -/// .finalize_build(); -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/extensible_records_finalizing_early_does_not_compile.rs`. pub mod finalizing_early_does_not_compile {} diff --git a/example-code/src/concepts/extensible_variants.rs b/example-code/tests/concepts/extensible_variants.rs similarity index 100% rename from example-code/src/concepts/extensible_variants.rs rename to example-code/tests/concepts/extensible_variants.rs diff --git a/example-code/src/concepts/handlers.rs b/example-code/tests/concepts/handlers.rs similarity index 100% rename from example-code/src/concepts/handlers.rs rename to example-code/tests/concepts/handlers.rs diff --git a/example-code/src/concepts/higher_order_providers.rs b/example-code/tests/concepts/higher_order_providers.rs similarity index 100% rename from example-code/src/concepts/higher_order_providers.rs rename to example-code/tests/concepts/higher_order_providers.rs diff --git a/example-code/src/concepts/impl_side_dependencies.rs b/example-code/tests/concepts/impl_side_dependencies.rs similarity index 100% rename from example-code/src/concepts/impl_side_dependencies.rs rename to example-code/tests/concepts/impl_side_dependencies.rs diff --git a/example-code/src/concepts/implicit_arguments.rs b/example-code/tests/concepts/implicit_arguments.rs similarity index 100% rename from example-code/src/concepts/implicit_arguments.rs rename to example-code/tests/concepts/implicit_arguments.rs diff --git a/example-code/src/concepts/mod.rs b/example-code/tests/concepts/mod.rs similarity index 100% rename from example-code/src/concepts/mod.rs rename to example-code/tests/concepts/mod.rs diff --git a/example-code/src/concepts/modular_error_handling.rs b/example-code/tests/concepts/modular_error_handling.rs similarity index 100% rename from example-code/src/concepts/modular_error_handling.rs rename to example-code/tests/concepts/modular_error_handling.rs diff --git a/example-code/src/concepts/modularity_hierarchy.rs b/example-code/tests/concepts/modularity_hierarchy.rs similarity index 100% rename from example-code/src/concepts/modularity_hierarchy.rs rename to example-code/tests/concepts/modularity_hierarchy.rs diff --git a/example-code/src/concepts/monadic_handlers.rs b/example-code/tests/concepts/monadic_handlers.rs similarity index 88% rename from example-code/src/concepts/monadic_handlers.rs rename to example-code/tests/concepts/monadic_handlers.rs index 9dd65265..1d7bd441 100644 --- a/example-code/src/concepts/monadic_handlers.rs +++ b/example-code/tests/concepts/monadic_handlers.rs @@ -17,16 +17,7 @@ pub fn increment(value: u8) -> Result { /// Written out, the type mismatch is what stops this compiling — which is the honest form of "plain /// composition does not fit". /// -/// ```compile_fail -/// use cgp::extra::handler::PipeHandlers; -/// use cgp::prelude::*; -/// use cgp_website_example_code::concepts::monadic_handlers::Increment; -/// -/// fn main() { -/// // `Increment` produces `Result` and the next `Increment` wants a `u8`. -/// let _ = PipeHandlers::::compute(&(), PhantomData::<()>, 1u8); -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.rs`. pub mod plain_composition_is_wrong {} /// ## Chaining through the err monad diff --git a/example-code/src/concepts/namespaces.rs b/example-code/tests/concepts/namespaces.rs similarity index 83% rename from example-code/src/concepts/namespaces.rs rename to example-code/tests/concepts/namespaces.rs index 6ba9b6a0..87e356ed 100644 --- a/example-code/src/concepts/namespaces.rs +++ b/example-code/tests/concepts/namespaces.rs @@ -223,65 +223,11 @@ pub mod binding_what_is_shared { /// /// A context re-wiring a key its namespace binds: /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[cgp_component(Greeter)] -/// pub trait CanGreet { fn greet(&self) -> String; } -/// -/// #[cgp_impl(new GreetHello)] -/// impl Greeter { fn greet(&self) -> String { "Hello!".to_owned() } } -/// -/// #[cgp_impl(new GreetQuietly)] -/// impl Greeter { fn greet(&self) -> String { "hello".to_owned() } } -/// -/// cgp_namespace! { -/// new AppDefaults { -/// GreeterComponent: GreetHello, -/// } -/// } -/// -/// pub struct TestApp; -/// -/// // error[E0119]: conflicting implementations of trait -/// // `DelegateComponent` for type `TestApp` -/// delegate_components! { -/// TestApp { -/// namespace AppDefaults; -/// -/// GreeterComponent: GreetQuietly, -/// } -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_1.rs`. /// /// And a child namespace redefining a key it inherits: /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[cgp_component(Greeter)] -/// pub trait CanGreet { fn greet(&self) -> String; } -/// -/// #[cgp_impl(new GreetHello)] -/// impl Greeter { fn greet(&self) -> String { "Hello!".to_owned() } } -/// -/// #[cgp_impl(new GreetQuietly)] -/// impl Greeter { fn greet(&self) -> String { "hello".to_owned() } } -/// -/// cgp_namespace! { -/// new BaseDefaults { -/// GreeterComponent: GreetHello, -/// } -/// } -/// -/// // error[E0119]: conflicting implementations of trait `QuietDefaults<_>` -/// // for type `GreeterComponent` -/// cgp_namespace! { -/// new QuietDefaults: BaseDefaults { -/// GreeterComponent: GreetQuietly, -/// } -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/namespaces_a_bound_entry_is_not_overridable_2.rs`. pub mod a_bound_entry_is_not_overridable {} /// ## One namespace per configuration diff --git a/example-code/src/concepts/send_bounds.rs b/example-code/tests/concepts/send_bounds.rs similarity index 89% rename from example-code/src/concepts/send_bounds.rs rename to example-code/tests/concepts/send_bounds.rs index 1bf885e2..a92e1738 100644 --- a/example-code/src/concepts/send_bounds.rs +++ b/example-code/tests/concepts/send_bounds.rs @@ -48,17 +48,7 @@ mod check_mock_app { /// context cannot say so, because the future's auto-traits are hidden behind the trait boundary — /// the notation for it, Return Type Notation, is not stable. /// -/// ```compile_fail -/// use core::marker::PhantomData; -/// use cgp_website_example_code::concepts::send_bounds::*; -/// -/// // Not available on stable Rust. -/// fn spawn_handler(app: App) -/// where -/// App: CanHandleApi + Send + 'static, -/// { -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/send_bounds_the_bound_a_caller_cannot_write.rs`. pub mod the_bound_a_caller_cannot_write {} /// ## The trait that states the bound directly diff --git a/example-code/src/concepts/type_level_dsls.rs b/example-code/tests/concepts/type_level_dsls.rs similarity index 100% rename from example-code/src/concepts/type_level_dsls.rs rename to example-code/tests/concepts/type_level_dsls.rs diff --git a/example-code/tests/concepts_tests.rs b/example-code/tests/concepts_tests.rs new file mode 100644 index 00000000..fa2856d7 --- /dev/null +++ b/example-code/tests/concepts_tests.rs @@ -0,0 +1,10 @@ +//! Runnable checks for the code shown on the `docs/concepts/` pages. +//! +//! One module per page, under `tests/concepts/`. See the crate `README.md` for the layout and for +//! how the rejected snippets are handled (they live under `tests/compile_fail/`). + +// A page shows the shape of a program rather than a whole one, so its code carries items nothing calls +// and parameters nothing reads once an elided body is filled in. A genuinely unused import still warns. +#![allow(dead_code, unused_variables)] + +mod concepts; diff --git a/example-code/src/reference/components/can_raise_error.rs b/example-code/tests/reference/components/can_raise_error.rs similarity index 100% rename from example-code/src/reference/components/can_raise_error.rs rename to example-code/tests/reference/components/can_raise_error.rs diff --git a/example-code/src/reference/components/can_wrap_error.rs b/example-code/tests/reference/components/can_wrap_error.rs similarity index 100% rename from example-code/src/reference/components/can_wrap_error.rs rename to example-code/tests/reference/components/can_wrap_error.rs diff --git a/example-code/src/reference/components/handler/async_computer.rs b/example-code/tests/reference/components/handler/async_computer.rs similarity index 100% rename from example-code/src/reference/components/handler/async_computer.rs rename to example-code/tests/reference/components/handler/async_computer.rs diff --git a/example-code/src/reference/components/handler/async_computer_ref.rs b/example-code/tests/reference/components/handler/async_computer_ref.rs similarity index 100% rename from example-code/src/reference/components/handler/async_computer_ref.rs rename to example-code/tests/reference/components/handler/async_computer_ref.rs diff --git a/example-code/src/reference/components/handler/computer.rs b/example-code/tests/reference/components/handler/computer.rs similarity index 90% rename from example-code/src/reference/components/handler/computer.rs rename to example-code/tests/reference/components/handler/computer.rs index 83642dff..a54ee055 100644 --- a/example-code/src/reference/components/handler/computer.rs +++ b/example-code/tests/reference/components/handler/computer.rs @@ -7,7 +7,7 @@ pub mod examples { use core::marker::PhantomData; - use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::extra::handler::{CanCompute, Computer, ComputerComponent}; use cgp::prelude::*; #[cgp_new_provider] @@ -40,8 +40,6 @@ pub mod examples { #[test] fn app_doubles_its_input() { - use cgp::extra::handler::CanCompute; - assert_eq!(App.compute(PhantomData::<()>, 21u64), 42); } } diff --git a/example-code/src/reference/components/handler/computer_ref.rs b/example-code/tests/reference/components/handler/computer_ref.rs similarity index 100% rename from example-code/src/reference/components/handler/computer_ref.rs rename to example-code/tests/reference/components/handler/computer_ref.rs diff --git a/example-code/src/reference/components/handler/handler.rs b/example-code/tests/reference/components/handler/handler.rs similarity index 100% rename from example-code/src/reference/components/handler/handler.rs rename to example-code/tests/reference/components/handler/handler.rs diff --git a/example-code/src/reference/components/handler/handler_ref.rs b/example-code/tests/reference/components/handler/handler_ref.rs similarity index 100% rename from example-code/src/reference/components/handler/handler_ref.rs rename to example-code/tests/reference/components/handler/handler_ref.rs diff --git a/example-code/src/reference/components/handler/mod.rs b/example-code/tests/reference/components/handler/mod.rs similarity index 100% rename from example-code/src/reference/components/handler/mod.rs rename to example-code/tests/reference/components/handler/mod.rs diff --git a/example-code/src/reference/components/handler/producer.rs b/example-code/tests/reference/components/handler/producer.rs similarity index 89% rename from example-code/src/reference/components/handler/producer.rs rename to example-code/tests/reference/components/handler/producer.rs index c3037ef9..df67680a 100644 --- a/example-code/src/reference/components/handler/producer.rs +++ b/example-code/tests/reference/components/handler/producer.rs @@ -7,7 +7,7 @@ pub mod examples { use core::marker::PhantomData; - use cgp::extra::handler::{Producer, ProducerComponent}; + use cgp::extra::handler::{CanProduce, Producer, ProducerComponent}; use cgp::prelude::*; #[cgp_new_provider] @@ -39,8 +39,6 @@ pub mod examples { #[test] fn app_produces_the_magic_number() { - use cgp::extra::handler::CanProduce; - assert_eq!(App.produce(PhantomData::<()>), 42); } } diff --git a/example-code/src/reference/components/handler/try_computer.rs b/example-code/tests/reference/components/handler/try_computer.rs similarity index 94% rename from example-code/src/reference/components/handler/try_computer.rs rename to example-code/tests/reference/components/handler/try_computer.rs index fad71e9e..2d80959a 100644 --- a/example-code/src/reference/components/handler/try_computer.rs +++ b/example-code/tests/reference/components/handler/try_computer.rs @@ -9,7 +9,7 @@ pub mod examples { use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::error::{DebugError, RaiseFrom}; - use cgp::extra::handler::{TryComputer, TryComputerComponent}; + use cgp::extra::handler::{CanTryCompute, TryComputer, TryComputerComponent}; use cgp::prelude::*; #[cgp_impl(new ParseU64)] @@ -56,8 +56,6 @@ pub mod examples { #[test] fn app_parses_a_number() { - use cgp::extra::handler::CanTryCompute; - assert_eq!( App.try_compute(PhantomData::<()>, "42".to_owned()).unwrap(), 42, diff --git a/example-code/src/reference/components/handler/try_computer_ref.rs b/example-code/tests/reference/components/handler/try_computer_ref.rs similarity index 100% rename from example-code/src/reference/components/handler/try_computer_ref.rs rename to example-code/tests/reference/components/handler/try_computer_ref.rs diff --git a/example-code/src/reference/components/has_error_type.rs b/example-code/tests/reference/components/has_error_type.rs similarity index 100% rename from example-code/src/reference/components/has_error_type.rs rename to example-code/tests/reference/components/has_error_type.rs diff --git a/example-code/src/reference/components/has_runtime.rs b/example-code/tests/reference/components/has_runtime.rs similarity index 100% rename from example-code/src/reference/components/has_runtime.rs rename to example-code/tests/reference/components/has_runtime.rs diff --git a/example-code/src/reference/components/has_runtime_type.rs b/example-code/tests/reference/components/has_runtime_type.rs similarity index 100% rename from example-code/src/reference/components/has_runtime_type.rs rename to example-code/tests/reference/components/has_runtime_type.rs diff --git a/example-code/src/reference/components/has_type.rs b/example-code/tests/reference/components/has_type.rs similarity index 100% rename from example-code/src/reference/components/has_type.rs rename to example-code/tests/reference/components/has_type.rs diff --git a/example-code/src/reference/components/mod.rs b/example-code/tests/reference/components/mod.rs similarity index 100% rename from example-code/src/reference/components/mod.rs rename to example-code/tests/reference/components/mod.rs diff --git a/example-code/src/reference/components/runner.rs b/example-code/tests/reference/components/runner.rs similarity index 98% rename from example-code/src/reference/components/runner.rs rename to example-code/tests/reference/components/runner.rs index b0da2504..c94b276a 100644 --- a/example-code/src/reference/components/runner.rs +++ b/example-code/tests/reference/components/runner.rs @@ -16,6 +16,7 @@ pub mod examples { CanRun, CanSendRun, Runner, RunnerComponent, SendRunner, SendRunnerComponent, }; use cgp::prelude::*; + use futures::executor::block_on; // Stands in for `tokio::spawn`: it demands the future be `Send + 'static`. fn dummy_spawn(_future: F) @@ -78,8 +79,6 @@ pub mod examples { #[test] fn spawns_and_runs_a_task() { - use futures::executor::block_on; - let app = App; block_on(app.run(PhantomData::)).unwrap(); } diff --git a/example-code/src/reference/components/send_runner.rs b/example-code/tests/reference/components/send_runner.rs similarity index 98% rename from example-code/src/reference/components/send_runner.rs rename to example-code/tests/reference/components/send_runner.rs index 0eea6e87..e930de8e 100644 --- a/example-code/src/reference/components/send_runner.rs +++ b/example-code/tests/reference/components/send_runner.rs @@ -16,6 +16,7 @@ pub mod examples { CanRun, CanSendRun, Runner, RunnerComponent, SendRunner, SendRunnerComponent, }; use cgp::prelude::*; + use futures::executor::block_on; // Stands in for `tokio::spawn`: it demands the future be `Send + 'static`. fn dummy_spawn(_future: F) @@ -77,8 +78,6 @@ pub mod examples { #[test] fn the_proxy_lets_a_task_be_spawned() { - use futures::executor::block_on; - let app = App; block_on(app.run(PhantomData::)).unwrap(); } diff --git a/example-code/src/reference/derives/derive_build_field.rs b/example-code/tests/reference/derives/derive_build_field.rs similarity index 83% rename from example-code/src/reference/derives/derive_build_field.rs rename to example-code/tests/reference/derives/derive_build_field.rs index 74b56968..e53e130e 100644 --- a/example-code/src/reference/derives/derive_build_field.rs +++ b/example-code/tests/reference/derives/derive_build_field.rs @@ -40,19 +40,7 @@ pub mod what_its_for { /// The page's central claim, as a rejected snippet: dropping a `build_field` line means /// `finalize_build` does not resolve, because its impl exists only at the all-present configuration. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[derive(BuildField)] -/// pub struct Person { -/// pub first_name: String, -/// pub last_name: String, -/// } -/// -/// let person: Person = Person::builder() -/// .build_field(PhantomData::, "Alice".to_owned()) -/// .finalize_build(); -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_build_field_rejected_incomplete_build.rs`. pub mod rejected_incomplete_build {} /// The page's other rejected case: a field's accessor on the companion is in scope only once that @@ -60,50 +48,14 @@ pub mod rejected_incomplete_build {} /// on the tag rather than as a missing method, because the only applicable `HasField` impl is the one /// for the field that *is* present. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[derive(BuildField)] -/// pub struct Person { -/// pub first_name: String, -/// pub last_name: String, -/// } -/// -/// let partial = Person::builder() -/// .build_field(PhantomData::, "Alice".to_owned()); -/// -/// let _ = partial.get_field(PhantomData::); -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.rs`. pub mod rejected_read_of_an_unset_field {} /// The page's third rejected case: `build_from` walks the *source's* field list, so a source deriving /// only `BuildField` cannot be merged into anything. The error is an unsatisfied `HasFields` bound on /// the source type. /// -/// ```compile_fail -/// use cgp::core::field::impls::CanBuildFrom; -/// use cgp::prelude::*; -/// -/// #[derive(BuildField)] -/// pub struct FooBar { -/// pub foo: u64, -/// pub bar: String, -/// } -/// -/// #[derive(BuildField)] -/// pub struct FooBarBaz { -/// pub foo: u64, -/// pub bar: String, -/// pub baz: bool, -/// } -/// -/// let source = FooBar { foo: 1, bar: "bar".to_owned() }; -/// -/// let _ = FooBarBaz::builder() -/// .build_from(source) -/// .build_field(PhantomData::, true) -/// .finalize_build(); -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs`. pub mod rejected_build_from_without_has_fields {} /// ## Usage diff --git a/example-code/src/reference/derives/derive_cgp_data.rs b/example-code/tests/reference/derives/derive_cgp_data.rs similarity index 96% rename from example-code/src/reference/derives/derive_cgp_data.rs rename to example-code/tests/reference/derives/derive_cgp_data.rs index 5d685b90..c92282d3 100644 --- a/example-code/src/reference/derives/derive_cgp_data.rs +++ b/example-code/tests/reference/derives/derive_cgp_data.rs @@ -104,14 +104,7 @@ pub mod using_it { /// The page's rejected snippet: a struct-style variant has no single payload type, so the derive /// refuses it. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[derive(CgpData)] -/// pub enum Shape { -/// Circle { radius: f64 }, -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.rs`. pub mod rejected_struct_style_variant {} /// ## Examples diff --git a/example-code/src/reference/derives/derive_cgp_record.rs b/example-code/tests/reference/derives/derive_cgp_record.rs similarity index 100% rename from example-code/src/reference/derives/derive_cgp_record.rs rename to example-code/tests/reference/derives/derive_cgp_record.rs diff --git a/example-code/src/reference/derives/derive_cgp_variant.rs b/example-code/tests/reference/derives/derive_cgp_variant.rs similarity index 93% rename from example-code/src/reference/derives/derive_cgp_variant.rs rename to example-code/tests/reference/derives/derive_cgp_variant.rs index 0c82a6ed..1f63a914 100644 --- a/example-code/src/reference/derives/derive_cgp_variant.rs +++ b/example-code/tests/reference/derives/derive_cgp_variant.rs @@ -8,14 +8,7 @@ /// The page's rejected snippet: a struct-style variant has no single payload type, so the derive /// fails. Every variant must carry exactly one unnamed payload, with no per-variant opt-out. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[derive(CgpVariant)] -/// pub enum Shape { -/// Circle { radius: f64 }, -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.rs`. pub mod rejected_struct_style_variant {} /// ## Examples diff --git a/example-code/src/reference/derives/derive_extract_field.rs b/example-code/tests/reference/derives/derive_extract_field.rs similarity index 89% rename from example-code/src/reference/derives/derive_extract_field.rs rename to example-code/tests/reference/derives/derive_extract_field.rs index f83cbcd3..94a09189 100644 --- a/example-code/src/reference/derives/derive_extract_field.rs +++ b/example-code/tests/reference/derives/derive_extract_field.rs @@ -105,15 +105,7 @@ pub mod using_it { /// The page's rejected snippet: a struct-style variant and a unit variant both fail, because /// extraction has to name one payload type per variant. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[derive(ExtractField)] -/// pub enum Shape { -/// Circle { radius: f64 }, -/// Empty, -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.rs`. pub mod rejected_variant_shapes {} /// ## Examples @@ -205,24 +197,5 @@ pub mod examples { /// The page's claim that finalizing before every variant has been tried does not compile, because the /// remainder is still inhabited. /// -/// ```compile_fail -/// use cgp::core::field::traits::FinalizeExtractResult; -/// use cgp::prelude::*; -/// -/// pub struct Circle { pub radius: f64 } -/// pub struct Rectangle { pub width: f64, pub height: f64 } -/// -/// #[derive(ExtractField)] -/// pub enum Shape { -/// Circle(Circle), -/// Rectangle(Rectangle), -/// } -/// -/// let shape = Shape::Circle(Circle { radius: 1.0 }); -/// -/// let _ = shape -/// .to_extractor() -/// .extract_field(PhantomData::) -/// .finalize_extract_result(); -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.rs`. pub mod rejected_premature_finalize {} diff --git a/example-code/src/reference/derives/derive_from_variant.rs b/example-code/tests/reference/derives/derive_from_variant.rs similarity index 96% rename from example-code/src/reference/derives/derive_from_variant.rs rename to example-code/tests/reference/derives/derive_from_variant.rs index 25d5edec..ed03d39f 100644 --- a/example-code/src/reference/derives/derive_from_variant.rs +++ b/example-code/tests/reference/derives/derive_from_variant.rs @@ -74,14 +74,7 @@ pub mod using_it { /// The page's rejected snippet: a struct-style variant has no single payload type for the constructor /// to take. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[derive(FromVariant)] -/// pub enum Shape { -/// Circle { radius: f64 }, -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.rs`. pub mod rejected_struct_style_variant {} /// ## Examples diff --git a/example-code/src/reference/derives/derive_has_field.rs b/example-code/tests/reference/derives/derive_has_field.rs similarity index 100% rename from example-code/src/reference/derives/derive_has_field.rs rename to example-code/tests/reference/derives/derive_has_field.rs diff --git a/example-code/src/reference/derives/derive_has_fields.rs b/example-code/tests/reference/derives/derive_has_fields.rs similarity index 100% rename from example-code/src/reference/derives/derive_has_fields.rs rename to example-code/tests/reference/derives/derive_has_fields.rs diff --git a/example-code/src/reference/derives/mod.rs b/example-code/tests/reference/derives/mod.rs similarity index 100% rename from example-code/src/reference/derives/mod.rs rename to example-code/tests/reference/derives/mod.rs diff --git a/example-code/src/reference/errors.rs b/example-code/tests/reference/errors.rs similarity index 62% rename from example-code/src/reference/errors.rs rename to example-code/tests/reference/errors.rs index 9fd491b5..80743887 100644 --- a/example-code/src/reference/errors.rs +++ b/example-code/tests/reference/errors.rs @@ -62,86 +62,11 @@ pub mod a_dependency_is_not_met { /// The program is repeated in full rather than importing the module above, because a doctest is /// compiled as its own crate and because the page shows it whole. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[cgp_component(Greeter)] -/// pub trait CanGreet { -/// fn greet(&self); -/// } -/// -/// #[cgp_auto_getter] -/// pub trait HasName { -/// fn name(&self) -> &str; -/// } -/// -/// #[cgp_impl(new GreetHello)] -/// #[uses(HasName)] -/// impl Greeter { -/// fn greet(&self) { -/// let _ = self.name(); -/// } -/// } -/// -/// #[derive(HasField)] -/// pub struct Person { -/// pub age: u8, -/// } -/// -/// delegate_components! { -/// Person { -/// GreeterComponent: GreetHello, -/// } -/// } -/// -/// // error[E0277]: [CGP-E001] the consumer trait `CanGreet` is not implemented for -/// // context `Person` -/// // root cause: [CGP-E106] missing field `name` on `Person` -/// check_components! { -/// Person { -/// GreeterComponent, -/// } -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/errors_the_fix_1.rs`. /// /// And the hidden half of the same mistake, which the page contrasts against the checked one: no /// check anywhere, the failure reached by calling the method instead. The compiler reports `E0599` /// and names nothing about the missing field. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[cgp_component(Greeter)] -/// pub trait CanGreet { -/// fn greet(&self); -/// } -/// -/// #[cgp_auto_getter] -/// pub trait HasName { -/// fn name(&self) -> &str; -/// } -/// -/// #[cgp_impl(new GreetHello)] -/// #[uses(HasName)] -/// impl Greeter { -/// fn greet(&self) { -/// let _ = self.name(); -/// } -/// } -/// -/// #[derive(HasField)] -/// pub struct Person { -/// pub age: u8, -/// } -/// -/// delegate_components! { -/// Person { -/// GreeterComponent: GreetHello, -/// } -/// } -/// -/// // error[E0599]: the method `greet` exists for struct `Person`, but its trait bounds -/// // were not satisfied -/// Person { age: 0 }.greet(); -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/errors_the_fix_2.rs`. pub mod the_fix {} diff --git a/example-code/src/reference/macros/delegate_components.rs b/example-code/tests/reference/macros/delegate_components.rs similarity index 97% rename from example-code/src/reference/macros/delegate_components.rs rename to example-code/tests/reference/macros/delegate_components.rs index f89a1031..4546ba76 100644 --- a/example-code/src/reference/macros/delegate_components.rs +++ b/example-code/tests/reference/macros/delegate_components.rs @@ -604,28 +604,5 @@ pub mod examples { /// The bracketed form, which the page offers as the fix, is exercised above under /// [`choosing_a_provider_per_type_the_open_statement`]. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[cgp_component(FooProvider)] -/// pub trait Foo { -/// fn foo(&self, value: &T); -/// } -/// -/// #[cgp_impl(new DummyFoo)] -/// impl FooProvider { -/// fn foo(&self, _value: &T) {} -/// } -/// -/// pub struct App; -/// -/// // error: expected `:` -/// delegate_components! { -/// App { -/// open FooProviderComponent; -/// -/// @FooProviderComponent.{String, u32}.bool: DummyFoo, -/// } -/// } -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/macros/delegate_components_gotchas.rs`. pub mod gotchas {} diff --git a/example-code/src/reference/macros/mod.rs b/example-code/tests/reference/macros/mod.rs similarity index 100% rename from example-code/src/reference/macros/mod.rs rename to example-code/tests/reference/macros/mod.rs diff --git a/example-code/src/reference/mod.rs b/example-code/tests/reference/mod.rs similarity index 100% rename from example-code/src/reference/mod.rs rename to example-code/tests/reference/mod.rs diff --git a/example-code/src/reference/providers/chain_getters.rs b/example-code/tests/reference/providers/chain_getters.rs similarity index 100% rename from example-code/src/reference/providers/chain_getters.rs rename to example-code/tests/reference/providers/chain_getters.rs diff --git a/example-code/src/reference/providers/dispatch/build_and_merge.rs b/example-code/tests/reference/providers/dispatch/build_and_merge.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/build_and_merge.rs rename to example-code/tests/reference/providers/dispatch/build_and_merge.rs diff --git a/example-code/src/reference/providers/dispatch/build_and_merge_outputs.rs b/example-code/tests/reference/providers/dispatch/build_and_merge_outputs.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/build_and_merge_outputs.rs rename to example-code/tests/reference/providers/dispatch/build_and_merge_outputs.rs diff --git a/example-code/src/reference/providers/dispatch/build_and_set_field.rs b/example-code/tests/reference/providers/dispatch/build_and_set_field.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/build_and_set_field.rs rename to example-code/tests/reference/providers/dispatch/build_and_set_field.rs diff --git a/example-code/src/reference/providers/dispatch/build_with_handlers.rs b/example-code/tests/reference/providers/dispatch/build_with_handlers.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/build_with_handlers.rs rename to example-code/tests/reference/providers/dispatch/build_with_handlers.rs diff --git a/example-code/src/reference/providers/dispatch/downcast_and_handle.rs b/example-code/tests/reference/providers/dispatch/downcast_and_handle.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/downcast_and_handle.rs rename to example-code/tests/reference/providers/dispatch/downcast_and_handle.rs diff --git a/example-code/src/reference/providers/dispatch/extract_field_and_handle.rs b/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/extract_field_and_handle.rs rename to example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs diff --git a/example-code/src/reference/providers/dispatch/handle_field_value.rs b/example-code/tests/reference/providers/dispatch/handle_field_value.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/handle_field_value.rs rename to example-code/tests/reference/providers/dispatch/handle_field_value.rs diff --git a/example-code/src/reference/providers/dispatch/match_first_with_handlers.rs b/example-code/tests/reference/providers/dispatch/match_first_with_handlers.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/match_first_with_handlers.rs rename to example-code/tests/reference/providers/dispatch/match_first_with_handlers.rs diff --git a/example-code/src/reference/providers/dispatch/match_with_field_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/match_with_field_handlers.rs rename to example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs diff --git a/example-code/src/reference/providers/dispatch/match_with_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_handlers.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/match_with_handlers.rs rename to example-code/tests/reference/providers/dispatch/match_with_handlers.rs diff --git a/example-code/src/reference/providers/dispatch/match_with_value_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/match_with_value_handlers.rs rename to example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs diff --git a/example-code/src/reference/providers/dispatch/mod.rs b/example-code/tests/reference/providers/dispatch/mod.rs similarity index 100% rename from example-code/src/reference/providers/dispatch/mod.rs rename to example-code/tests/reference/providers/dispatch/mod.rs diff --git a/example-code/src/reference/providers/error/debug_error.rs b/example-code/tests/reference/providers/error/debug_error.rs similarity index 100% rename from example-code/src/reference/providers/error/debug_error.rs rename to example-code/tests/reference/providers/error/debug_error.rs diff --git a/example-code/src/reference/providers/error/discard_detail.rs b/example-code/tests/reference/providers/error/discard_detail.rs similarity index 100% rename from example-code/src/reference/providers/error/discard_detail.rs rename to example-code/tests/reference/providers/error/discard_detail.rs diff --git a/example-code/src/reference/providers/error/display_error.rs b/example-code/tests/reference/providers/error/display_error.rs similarity index 100% rename from example-code/src/reference/providers/error/display_error.rs rename to example-code/tests/reference/providers/error/display_error.rs diff --git a/example-code/src/reference/providers/error/mod.rs b/example-code/tests/reference/providers/error/mod.rs similarity index 100% rename from example-code/src/reference/providers/error/mod.rs rename to example-code/tests/reference/providers/error/mod.rs diff --git a/example-code/src/reference/providers/error/panic_on_error.rs b/example-code/tests/reference/providers/error/panic_on_error.rs similarity index 100% rename from example-code/src/reference/providers/error/panic_on_error.rs rename to example-code/tests/reference/providers/error/panic_on_error.rs diff --git a/example-code/src/reference/providers/error/raise_from.rs b/example-code/tests/reference/providers/error/raise_from.rs similarity index 100% rename from example-code/src/reference/providers/error/raise_from.rs rename to example-code/tests/reference/providers/error/raise_from.rs diff --git a/example-code/src/reference/providers/error/raise_infallible.rs b/example-code/tests/reference/providers/error/raise_infallible.rs similarity index 100% rename from example-code/src/reference/providers/error/raise_infallible.rs rename to example-code/tests/reference/providers/error/raise_infallible.rs diff --git a/example-code/src/reference/providers/error/return_error.rs b/example-code/tests/reference/providers/error/return_error.rs similarity index 100% rename from example-code/src/reference/providers/error/return_error.rs rename to example-code/tests/reference/providers/error/return_error.rs diff --git a/example-code/src/reference/providers/handler/compose_handlers.rs b/example-code/tests/reference/providers/handler/compose_handlers.rs similarity index 100% rename from example-code/src/reference/providers/handler/compose_handlers.rs rename to example-code/tests/reference/providers/handler/compose_handlers.rs diff --git a/example-code/src/reference/providers/handler/mod.rs b/example-code/tests/reference/providers/handler/mod.rs similarity index 100% rename from example-code/src/reference/providers/handler/mod.rs rename to example-code/tests/reference/providers/handler/mod.rs diff --git a/example-code/src/reference/providers/handler/pipe_handlers.rs b/example-code/tests/reference/providers/handler/pipe_handlers.rs similarity index 100% rename from example-code/src/reference/providers/handler/pipe_handlers.rs rename to example-code/tests/reference/providers/handler/pipe_handlers.rs diff --git a/example-code/src/reference/providers/handler/promote.rs b/example-code/tests/reference/providers/handler/promote.rs similarity index 100% rename from example-code/src/reference/providers/handler/promote.rs rename to example-code/tests/reference/providers/handler/promote.rs diff --git a/example-code/src/reference/providers/handler/promote_async.rs b/example-code/tests/reference/providers/handler/promote_async.rs similarity index 100% rename from example-code/src/reference/providers/handler/promote_async.rs rename to example-code/tests/reference/providers/handler/promote_async.rs diff --git a/example-code/src/reference/providers/handler/promote_async_computer.rs b/example-code/tests/reference/providers/handler/promote_async_computer.rs similarity index 100% rename from example-code/src/reference/providers/handler/promote_async_computer.rs rename to example-code/tests/reference/providers/handler/promote_async_computer.rs diff --git a/example-code/src/reference/providers/handler/promote_computer.rs b/example-code/tests/reference/providers/handler/promote_computer.rs similarity index 100% rename from example-code/src/reference/providers/handler/promote_computer.rs rename to example-code/tests/reference/providers/handler/promote_computer.rs diff --git a/example-code/src/reference/providers/handler/promote_handler.rs b/example-code/tests/reference/providers/handler/promote_handler.rs similarity index 100% rename from example-code/src/reference/providers/handler/promote_handler.rs rename to example-code/tests/reference/providers/handler/promote_handler.rs diff --git a/example-code/src/reference/providers/handler/promote_producer.rs b/example-code/tests/reference/providers/handler/promote_producer.rs similarity index 100% rename from example-code/src/reference/providers/handler/promote_producer.rs rename to example-code/tests/reference/providers/handler/promote_producer.rs diff --git a/example-code/src/reference/providers/handler/promote_ref.rs b/example-code/tests/reference/providers/handler/promote_ref.rs similarity index 100% rename from example-code/src/reference/providers/handler/promote_ref.rs rename to example-code/tests/reference/providers/handler/promote_ref.rs diff --git a/example-code/src/reference/providers/handler/promote_try_computer.rs b/example-code/tests/reference/providers/handler/promote_try_computer.rs similarity index 100% rename from example-code/src/reference/providers/handler/promote_try_computer.rs rename to example-code/tests/reference/providers/handler/promote_try_computer.rs diff --git a/example-code/src/reference/providers/handler/return_input.rs b/example-code/tests/reference/providers/handler/return_input.rs similarity index 100% rename from example-code/src/reference/providers/handler/return_input.rs rename to example-code/tests/reference/providers/handler/return_input.rs diff --git a/example-code/src/reference/providers/handler/try_promote.rs b/example-code/tests/reference/providers/handler/try_promote.rs similarity index 100% rename from example-code/src/reference/providers/handler/try_promote.rs rename to example-code/tests/reference/providers/handler/try_promote.rs diff --git a/example-code/src/reference/providers/handler/use_input_delegate.rs b/example-code/tests/reference/providers/handler/use_input_delegate.rs similarity index 100% rename from example-code/src/reference/providers/handler/use_input_delegate.rs rename to example-code/tests/reference/providers/handler/use_input_delegate.rs diff --git a/example-code/src/reference/providers/mod.rs b/example-code/tests/reference/providers/mod.rs similarity index 100% rename from example-code/src/reference/providers/mod.rs rename to example-code/tests/reference/providers/mod.rs diff --git a/example-code/src/reference/providers/monad/bind_err.rs b/example-code/tests/reference/providers/monad/bind_err.rs similarity index 100% rename from example-code/src/reference/providers/monad/bind_err.rs rename to example-code/tests/reference/providers/monad/bind_err.rs diff --git a/example-code/src/reference/providers/monad/bind_ok.rs b/example-code/tests/reference/providers/monad/bind_ok.rs similarity index 100% rename from example-code/src/reference/providers/monad/bind_ok.rs rename to example-code/tests/reference/providers/monad/bind_ok.rs diff --git a/example-code/src/reference/providers/monad/mod.rs b/example-code/tests/reference/providers/monad/mod.rs similarity index 100% rename from example-code/src/reference/providers/monad/mod.rs rename to example-code/tests/reference/providers/monad/mod.rs diff --git a/example-code/src/reference/providers/monad/pipe_monadic.rs b/example-code/tests/reference/providers/monad/pipe_monadic.rs similarity index 100% rename from example-code/src/reference/providers/monad/pipe_monadic.rs rename to example-code/tests/reference/providers/monad/pipe_monadic.rs diff --git a/example-code/src/reference/providers/redirect_lookup.rs b/example-code/tests/reference/providers/redirect_lookup.rs similarity index 100% rename from example-code/src/reference/providers/redirect_lookup.rs rename to example-code/tests/reference/providers/redirect_lookup.rs diff --git a/example-code/src/reference/providers/use_context.rs b/example-code/tests/reference/providers/use_context.rs similarity index 100% rename from example-code/src/reference/providers/use_context.rs rename to example-code/tests/reference/providers/use_context.rs diff --git a/example-code/src/reference/providers/use_default.rs b/example-code/tests/reference/providers/use_default.rs similarity index 100% rename from example-code/src/reference/providers/use_default.rs rename to example-code/tests/reference/providers/use_default.rs diff --git a/example-code/src/reference/providers/use_delegate.rs b/example-code/tests/reference/providers/use_delegate.rs similarity index 100% rename from example-code/src/reference/providers/use_delegate.rs rename to example-code/tests/reference/providers/use_delegate.rs diff --git a/example-code/src/reference/providers/use_field.rs b/example-code/tests/reference/providers/use_field.rs similarity index 100% rename from example-code/src/reference/providers/use_field.rs rename to example-code/tests/reference/providers/use_field.rs diff --git a/example-code/src/reference/providers/use_fields.rs b/example-code/tests/reference/providers/use_fields.rs similarity index 100% rename from example-code/src/reference/providers/use_fields.rs rename to example-code/tests/reference/providers/use_fields.rs diff --git a/example-code/src/reference/providers/use_type.rs b/example-code/tests/reference/providers/use_type.rs similarity index 100% rename from example-code/src/reference/providers/use_type.rs rename to example-code/tests/reference/providers/use_type.rs diff --git a/example-code/src/reference/providers/with_delegated_type.rs b/example-code/tests/reference/providers/with_delegated_type.rs similarity index 100% rename from example-code/src/reference/providers/with_delegated_type.rs rename to example-code/tests/reference/providers/with_delegated_type.rs diff --git a/example-code/src/reference/providers/with_field.rs b/example-code/tests/reference/providers/with_field.rs similarity index 100% rename from example-code/src/reference/providers/with_field.rs rename to example-code/tests/reference/providers/with_field.rs diff --git a/example-code/src/reference/providers/with_field_ref.rs b/example-code/tests/reference/providers/with_field_ref.rs similarity index 100% rename from example-code/src/reference/providers/with_field_ref.rs rename to example-code/tests/reference/providers/with_field_ref.rs diff --git a/example-code/src/reference/providers/with_provider.rs b/example-code/tests/reference/providers/with_provider.rs similarity index 100% rename from example-code/src/reference/providers/with_provider.rs rename to example-code/tests/reference/providers/with_provider.rs diff --git a/example-code/src/reference/providers/with_type.rs b/example-code/tests/reference/providers/with_type.rs similarity index 100% rename from example-code/src/reference/providers/with_type.rs rename to example-code/tests/reference/providers/with_type.rs diff --git a/example-code/src/reference/traits/append_product.rs b/example-code/tests/reference/traits/append_product.rs similarity index 100% rename from example-code/src/reference/traits/append_product.rs rename to example-code/tests/reference/traits/append_product.rs diff --git a/example-code/src/reference/traits/can_build_from.rs b/example-code/tests/reference/traits/can_build_from.rs similarity index 100% rename from example-code/src/reference/traits/can_build_from.rs rename to example-code/tests/reference/traits/can_build_from.rs diff --git a/example-code/src/reference/traits/can_downcast.rs b/example-code/tests/reference/traits/can_downcast.rs similarity index 100% rename from example-code/src/reference/traits/can_downcast.rs rename to example-code/tests/reference/traits/can_downcast.rs diff --git a/example-code/src/reference/traits/can_downcast_fields.rs b/example-code/tests/reference/traits/can_downcast_fields.rs similarity index 100% rename from example-code/src/reference/traits/can_downcast_fields.rs rename to example-code/tests/reference/traits/can_downcast_fields.rs diff --git a/example-code/src/reference/traits/can_upcast.rs b/example-code/tests/reference/traits/can_upcast.rs similarity index 100% rename from example-code/src/reference/traits/can_upcast.rs rename to example-code/tests/reference/traits/can_upcast.rs diff --git a/example-code/src/reference/traits/concat_path.rs b/example-code/tests/reference/traits/concat_path.rs similarity index 100% rename from example-code/src/reference/traits/concat_path.rs rename to example-code/tests/reference/traits/concat_path.rs diff --git a/example-code/src/reference/traits/concat_product.rs b/example-code/tests/reference/traits/concat_product.rs similarity index 100% rename from example-code/src/reference/traits/concat_product.rs rename to example-code/tests/reference/traits/concat_product.rs diff --git a/example-code/src/reference/traits/has_builder.rs b/example-code/tests/reference/traits/has_builder.rs similarity index 80% rename from example-code/src/reference/traits/has_builder.rs rename to example-code/tests/reference/traits/has_builder.rs index ebd2c8dc..ef192b8f 100644 --- a/example-code/src/reference/traits/has_builder.rs +++ b/example-code/tests/reference/traits/has_builder.rs @@ -98,37 +98,11 @@ pub mod examples { /// The page's central claim: `finalize_build` exists only at the all-present configuration, so an /// incomplete build does not resolve. /// -/// ```compile_fail -/// use cgp::prelude::*; -/// -/// #[derive(BuildField)] -/// pub struct Person { -/// pub first_name: String, -/// pub last_name: String, -/// } -/// -/// let person: Person = Person::builder() -/// .build_field(PhantomData::, "Alice".to_owned()) -/// .finalize_build(); -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.rs`. pub mod rejected_incomplete_build {} /// The page's other claim: a `build_from` source deriving only `BuildField` cannot be merged, because /// the recursion needs the source's `HasFields` shape. /// -/// ```compile_fail -/// use cgp::core::field::impls::CanBuildFrom; -/// use cgp::prelude::*; -/// -/// #[derive(BuildField)] -/// pub struct FooBar { pub foo: u64 } -/// -/// #[derive(BuildField)] -/// pub struct FooBaz { pub foo: u64, pub baz: bool } -/// -/// let _ = FooBaz::builder() -/// .build_from(FooBar { foo: 1 }) -/// .build_field(PhantomData::, true) -/// .finalize_build(); -/// ``` +/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs`. pub mod rejected_build_from_without_has_fields {} diff --git a/example-code/src/reference/traits/map_fields.rs b/example-code/tests/reference/traits/map_fields.rs similarity index 100% rename from example-code/src/reference/traits/map_fields.rs rename to example-code/tests/reference/traits/map_fields.rs diff --git a/example-code/src/reference/traits/mod.rs b/example-code/tests/reference/traits/mod.rs similarity index 100% rename from example-code/src/reference/traits/mod.rs rename to example-code/tests/reference/traits/mod.rs diff --git a/example-code/src/reference/traits/static_format.rs b/example-code/tests/reference/traits/static_format.rs similarity index 100% rename from example-code/src/reference/traits/static_format.rs rename to example-code/tests/reference/traits/static_format.rs diff --git a/example-code/src/reference/traits/static_string.rs b/example-code/tests/reference/traits/static_string.rs similarity index 100% rename from example-code/src/reference/traits/static_string.rs rename to example-code/tests/reference/traits/static_string.rs diff --git a/example-code/tests/reference_tests.rs b/example-code/tests/reference_tests.rs new file mode 100644 index 00000000..46c0cfe5 --- /dev/null +++ b/example-code/tests/reference_tests.rs @@ -0,0 +1,10 @@ +//! Runnable checks for the code shown on the `docs/reference/` pages. +//! +//! One module per page, under `tests/reference/`. See the crate `README.md` for the layout and for +//! how the rejected snippets are handled (they live under `tests/compile_fail/`). + +// A page shows the shape of a program rather than a whole one, so its code carries items nothing calls +// and parameters nothing reads once an elided body is filled in. A genuinely unused import still warns. +#![allow(dead_code, unused_variables)] + +mod reference; From de95d3cc6be8511b3c68843ebb54dc4db481cb6a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 23 Aug 2026 23:40:35 +0200 Subject: [PATCH 050/516] reference/traits: reorganize into families, add overviews and Definition sections Group the 57 trait reference pages into 11 importance-ordered subdirectories (wiring, field-access, shape, builder, optional, variant, casting, type-level, namespace, formatting, monad), mirroring the internal reference's trait families. Add a top-level Traits overview and one Overview per subdirectory (12 pages), with sidebar_position ordering and a doc-linked _category_.json per group. Add a Definition section after Overview on every construct page, showing the trait's own definition and explaining each element (moved out of Overview/Usage rather than duplicated). Revise the prose for the writing-style rules: rewrite pseudo-clefts, convert connector em dashes, prefer active voice, drop idioms. Rewrite every inbound and internal link for the new paths; the production build is clean. Also fix a pre-existing broken link: components/handler/handler.md collided with its folder index via the category-index convention, so pin it with an explicit slug. Co-Authored-By: Claude Opus 4.8 --- docs/cargo-cgp/expand.md | 4 +- docs/concepts/consumer-and-provider-traits.md | 2 +- docs/concepts/extensible-records.md | 4 +- docs/concepts/extensible-variants.md | 8 +- docs/concepts/implicit-arguments.md | 2 +- docs/concepts/monadic-handlers.md | 8 +- docs/reference/attributes/default_impl.md | 28 +++--- docs/reference/attributes/derive_delegate.md | 4 +- docs/reference/attributes/extend_where.md | 2 +- docs/reference/attributes/implicit.md | 10 +- docs/reference/attributes/uses.md | 2 +- docs/reference/components/handler/handler.md | 1 + docs/reference/derives/derive_build_field.md | 18 ++-- docs/reference/derives/derive_cgp_data.md | 4 +- docs/reference/derives/derive_cgp_record.md | 24 ++--- docs/reference/derives/derive_cgp_variant.md | 10 +- .../reference/derives/derive_extract_field.md | 8 +- docs/reference/derives/derive_from_variant.md | 8 +- docs/reference/derives/derive_has_field.md | 4 +- docs/reference/derives/derive_has_fields.md | 6 +- docs/reference/errors.md | 4 +- docs/reference/index.md | 74 +++++++------- docs/reference/macros/blanket_trait.md | 2 +- docs/reference/macros/cgp_auto_dispatch.md | 2 +- docs/reference/macros/cgp_auto_getter.md | 2 +- docs/reference/macros/cgp_component.md | 4 +- docs/reference/macros/cgp_computer.md | 2 +- docs/reference/macros/cgp_fn.md | 2 +- docs/reference/macros/cgp_getter.md | 4 +- docs/reference/macros/cgp_impl.md | 4 +- docs/reference/macros/cgp_namespace.md | 4 +- docs/reference/macros/cgp_producer.md | 2 +- docs/reference/macros/cgp_provider.md | 4 +- docs/reference/macros/cgp_type.md | 2 +- docs/reference/macros/check_components.md | 10 +- .../macros/delegate_and_check_components.md | 12 +-- docs/reference/macros/delegate_components.md | 8 +- docs/reference/macros/path.md | 2 +- docs/reference/macros/product.md | 6 +- docs/reference/macros/sum.md | 8 +- docs/reference/macros/symbol.md | 8 +- docs/reference/providers/chain_getters.md | 10 +- .../providers/dispatch/build_and_merge.md | 4 +- .../dispatch/build_and_merge_outputs.md | 4 +- .../providers/dispatch/build_and_set_field.md | 4 +- .../providers/dispatch/build_with_handlers.md | 6 +- .../providers/dispatch/downcast_and_handle.md | 4 +- .../dispatch/extract_field_and_handle.md | 4 +- docs/reference/providers/dispatch/index.md | 8 +- .../dispatch/match_first_with_handlers.md | 2 +- .../dispatch/match_with_field_handlers.md | 4 +- .../providers/dispatch/match_with_handlers.md | 6 +- .../dispatch/match_with_value_handlers.md | 4 +- docs/reference/providers/error/debug_error.md | 2 +- .../providers/error/discard_detail.md | 2 +- .../providers/error/display_error.md | 2 +- .../providers/error/panic_on_error.md | 2 +- docs/reference/providers/error/raise_from.md | 2 +- .../providers/error/raise_infallible.md | 2 +- .../reference/providers/error/return_error.md | 2 +- .../providers/handler/use_input_delegate.md | 2 +- docs/reference/providers/monad/bind_err.md | 2 +- docs/reference/providers/monad/bind_ok.md | 2 +- docs/reference/providers/monad/index.md | 6 +- .../reference/providers/monad/pipe_monadic.md | 4 +- docs/reference/providers/redirect_lookup.md | 8 +- docs/reference/providers/use_context.md | 4 +- docs/reference/providers/use_default.md | 4 +- docs/reference/providers/use_delegate.md | 8 +- .../reference/providers/use_delegated_type.md | 4 +- docs/reference/providers/use_field.md | 12 +-- docs/reference/providers/use_field_ref.md | 12 +-- docs/reference/providers/use_fields.md | 6 +- docs/reference/providers/with_context.md | 6 +- .../providers/with_delegated_type.md | 4 +- docs/reference/providers/with_field.md | 6 +- docs/reference/providers/with_field_ref.md | 8 +- docs/reference/providers/with_provider.md | 6 +- docs/reference/traits/_category_.json | 4 +- docs/reference/traits/builder/_category_.json | 8 ++ .../traits/{ => builder}/build_field.md | 50 ++++++---- .../traits/{ => builder}/finalize_build.md | 53 ++++++---- .../traits/{ => builder}/has_builder.md | 65 +++++++------ docs/reference/traits/builder/index.md | 42 ++++++++ .../traits/{ => builder}/into_builder.md | 57 ++++++----- .../traits/{ => builder}/partial_data.md | 57 ++++++----- .../traits/{ => builder}/take_field.md | 50 ++++++---- .../traits/{ => builder}/update_field.md | 59 +++++++----- docs/reference/traits/casting/_category_.json | 8 ++ .../traits/{ => casting}/can_build_from.md | 55 ++++++----- .../traits/{ => casting}/can_downcast.md | 59 +++++++----- .../{ => casting}/can_downcast_fields.md | 51 +++++----- .../traits/{ => casting}/can_upcast.md | 55 ++++++----- docs/reference/traits/casting/index.md | 36 +++++++ .../traits/field-access/_category_.json | 8 ++ .../traits/{ => field-access}/field_getter.md | 64 +++++++------ .../traits/{ => field-access}/field_mapper.md | 63 ++++++------ .../traits/{ => field-access}/has_field.md | 74 +++++++------- .../{ => field-access}/has_field_mut.md | 39 ++++---- docs/reference/traits/field-access/index.md | 41 ++++++++ .../traits/{ => field-access}/map_field.md | 55 ++++++----- .../{ => field-access}/mut_field_getter.md | 51 +++++----- .../traits/formatting/_category_.json | 8 ++ .../traits/{ => formatting}/concat_path.md | 56 +++++------ docs/reference/traits/formatting/index.md | 34 +++++++ .../traits/{ => formatting}/static_format.md | 29 +++--- .../traits/{ => formatting}/static_string.md | 39 ++++---- docs/reference/traits/index.md | 58 +++++++++++ docs/reference/traits/monad/_category_.json | 8 ++ .../traits/{ => monad}/contains_value.md | 43 +++++---- docs/reference/traits/monad/index.md | 37 +++++++ .../traits/{ => monad}/lift_value.md | 52 +++++----- .../traits/{ => monad}/monadic_bind.md | 65 +++++++------ .../traits/{ => monad}/monadic_trans.md | 46 +++++---- .../traits/namespace/_category_.json | 8 ++ .../traits/{ => namespace}/default_impls1.md | 54 ++++++----- .../traits/{ => namespace}/default_impls2.md | 35 ++++--- .../{ => namespace}/default_namespace.md | 68 ++++++------- docs/reference/traits/namespace/index.md | 39 ++++++++ .../reference/traits/optional/_category_.json | 8 ++ .../{ => optional}/can_build_with_default.md | 61 +++++++----- .../can_finalize_with_default.md | 59 +++++++----- .../{ => optional}/finalize_optional.md | 65 +++++++------ .../{ => optional}/has_optional_builder.md | 56 ++++++----- docs/reference/traits/optional/index.md | 44 +++++++++ .../traits/{ => optional}/set_optional.md | 54 ++++++----- .../traits/{ => optional}/to_optional.md | 57 ++++++----- .../{ => optional}/transform_map_default.md | 51 ++++++---- .../{ => optional}/transform_optional.md | 59 +++++++----- docs/reference/traits/shape/_category_.json | 8 ++ .../traits/{ => shape}/from_fields.md | 52 +++++----- .../traits/{ => shape}/has_fields.md | 75 ++++++++------- .../traits/{ => shape}/has_fields_ref.md | 41 ++++---- docs/reference/traits/shape/index.md | 35 +++++++ .../reference/traits/{ => shape}/to_fields.md | 61 ++++++------ .../traits/{ => shape}/to_fields_ref.md | 45 +++++---- .../traits/type-level/_category_.json | 8 ++ .../traits/{ => type-level}/append_product.md | 45 +++++---- .../traits/{ => type-level}/concat_product.md | 46 +++++---- docs/reference/traits/type-level/index.md | 37 +++++++ .../traits/{ => type-level}/map_fields.md | 49 ++++++---- .../traits/{ => type-level}/map_type.md | 52 +++++----- .../traits/{ => type-level}/map_type_ref.md | 58 +++++------ .../traits/{ => type-level}/transform_map.md | 52 +++++----- .../{ => type-level}/transform_map_fields.md | 66 +++++++------ docs/reference/traits/variant/_category_.json | 8 ++ .../traits/{ => variant}/extract_field.md | 89 +++++++++-------- .../traits/{ => variant}/finalize_extract.md | 61 ++++++------ .../{ => variant}/finalize_extract_result.md | 46 +++++---- .../traits/{ => variant}/from_variant.md | 66 +++++++------ .../traits/{ => variant}/has_extractor.md | 68 ++++++------- .../traits/{ => variant}/has_extractor_mut.md | 60 +++++++----- .../traits/{ => variant}/has_extractor_ref.md | 47 +++++---- docs/reference/traits/variant/index.md | 41 ++++++++ docs/reference/traits/wiring/_category_.json | 8 ++ .../traits/{ => wiring}/can_use_component.md | 53 +++++----- .../traits/{ => wiring}/delegate_component.md | 96 +++++++++---------- docs/reference/traits/wiring/index.md | 42 ++++++++ .../traits/{ => wiring}/is_provider_for.md | 73 ++++++++------ 159 files changed, 2628 insertions(+), 1658 deletions(-) create mode 100644 docs/reference/traits/builder/_category_.json rename docs/reference/traits/{ => builder}/build_field.md (79%) rename docs/reference/traits/{ => builder}/finalize_build.md (75%) rename docs/reference/traits/{ => builder}/has_builder.md (76%) create mode 100644 docs/reference/traits/builder/index.md rename docs/reference/traits/{ => builder}/into_builder.md (75%) rename docs/reference/traits/{ => builder}/partial_data.md (68%) rename docs/reference/traits/{ => builder}/take_field.md (75%) rename docs/reference/traits/{ => builder}/update_field.md (68%) create mode 100644 docs/reference/traits/casting/_category_.json rename docs/reference/traits/{ => casting}/can_build_from.md (70%) rename docs/reference/traits/{ => casting}/can_downcast.md (72%) rename docs/reference/traits/{ => casting}/can_downcast_fields.md (74%) rename docs/reference/traits/{ => casting}/can_upcast.md (76%) create mode 100644 docs/reference/traits/casting/index.md create mode 100644 docs/reference/traits/field-access/_category_.json rename docs/reference/traits/{ => field-access}/field_getter.md (64%) rename docs/reference/traits/{ => field-access}/field_mapper.md (73%) rename docs/reference/traits/{ => field-access}/has_field.md (68%) rename docs/reference/traits/{ => field-access}/has_field_mut.md (79%) create mode 100644 docs/reference/traits/field-access/index.md rename docs/reference/traits/{ => field-access}/map_field.md (70%) rename docs/reference/traits/{ => field-access}/mut_field_getter.md (75%) create mode 100644 docs/reference/traits/formatting/_category_.json rename docs/reference/traits/{ => formatting}/concat_path.md (68%) create mode 100644 docs/reference/traits/formatting/index.md rename docs/reference/traits/{ => formatting}/static_format.md (87%) rename docs/reference/traits/{ => formatting}/static_string.md (80%) create mode 100644 docs/reference/traits/index.md create mode 100644 docs/reference/traits/monad/_category_.json rename docs/reference/traits/{ => monad}/contains_value.md (82%) create mode 100644 docs/reference/traits/monad/index.md rename docs/reference/traits/{ => monad}/lift_value.md (77%) rename docs/reference/traits/{ => monad}/monadic_bind.md (72%) rename docs/reference/traits/{ => monad}/monadic_trans.md (81%) create mode 100644 docs/reference/traits/namespace/_category_.json rename docs/reference/traits/{ => namespace}/default_impls1.md (75%) rename docs/reference/traits/{ => namespace}/default_impls2.md (78%) rename docs/reference/traits/{ => namespace}/default_namespace.md (67%) create mode 100644 docs/reference/traits/namespace/index.md create mode 100644 docs/reference/traits/optional/_category_.json rename docs/reference/traits/{ => optional}/can_build_with_default.md (66%) rename docs/reference/traits/{ => optional}/can_finalize_with_default.md (75%) rename docs/reference/traits/{ => optional}/finalize_optional.md (69%) rename docs/reference/traits/{ => optional}/has_optional_builder.md (67%) create mode 100644 docs/reference/traits/optional/index.md rename docs/reference/traits/{ => optional}/set_optional.md (65%) rename docs/reference/traits/{ => optional}/to_optional.md (75%) rename docs/reference/traits/{ => optional}/transform_map_default.md (77%) rename docs/reference/traits/{ => optional}/transform_optional.md (74%) create mode 100644 docs/reference/traits/shape/_category_.json rename docs/reference/traits/{ => shape}/from_fields.md (66%) rename docs/reference/traits/{ => shape}/has_fields.md (66%) rename docs/reference/traits/{ => shape}/has_fields_ref.md (74%) create mode 100644 docs/reference/traits/shape/index.md rename docs/reference/traits/{ => shape}/to_fields.md (69%) rename docs/reference/traits/{ => shape}/to_fields_ref.md (76%) create mode 100644 docs/reference/traits/type-level/_category_.json rename docs/reference/traits/{ => type-level}/append_product.md (77%) rename docs/reference/traits/{ => type-level}/concat_product.md (74%) create mode 100644 docs/reference/traits/type-level/index.md rename docs/reference/traits/{ => type-level}/map_fields.md (80%) rename docs/reference/traits/{ => type-level}/map_type.md (77%) rename docs/reference/traits/{ => type-level}/map_type_ref.md (78%) rename docs/reference/traits/{ => type-level}/transform_map.md (76%) rename docs/reference/traits/{ => type-level}/transform_map_fields.md (64%) create mode 100644 docs/reference/traits/variant/_category_.json rename docs/reference/traits/{ => variant}/extract_field.md (69%) rename docs/reference/traits/{ => variant}/finalize_extract.md (72%) rename docs/reference/traits/{ => variant}/finalize_extract_result.md (76%) rename docs/reference/traits/{ => variant}/from_variant.md (70%) rename docs/reference/traits/{ => variant}/has_extractor.md (68%) rename docs/reference/traits/{ => variant}/has_extractor_mut.md (74%) rename docs/reference/traits/{ => variant}/has_extractor_ref.md (75%) create mode 100644 docs/reference/traits/variant/index.md create mode 100644 docs/reference/traits/wiring/_category_.json rename docs/reference/traits/{ => wiring}/can_use_component.md (77%) rename docs/reference/traits/{ => wiring}/delegate_component.md (75%) create mode 100644 docs/reference/traits/wiring/index.md rename docs/reference/traits/{ => wiring}/is_provider_for.md (73%) diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index ec29e9f1..54d28eb2 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -168,10 +168,10 @@ useful mid-debugging: it works on a crate that does not type-check. For the wiri Four situations, all of them cases where the answer is in the generated code rather than in a message: - **A diagnostic names a type you did not write** — - [`IsProviderFor`](/docs/reference/traits/is_provider_for), a `PathCons` key, a `__Context__` + [`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for), a `PathCons` key, a `__Context__` parameter — and you want to see the impl it came from. - **A wiring table does not resolve** and you want its real - [`DelegateComponent`](/docs/reference/traits/delegate_component) keys and values rather + [`DelegateComponent`](/docs/reference/traits/wiring/delegate_component) keys and values rather than inferring them from the table's syntax. - **You are unsure what a construct emits** — the exact `where` clauses of a provider impl, whether a getter's blanket impl needs the field you think it does. diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index 679b9e61..fbb9fc60 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -175,7 +175,7 @@ because its table maps `EmailSenderComponent` to `SendViaSmtp`; and `SendViaSmtp never reaches the binary. The one piece of that listing not yet explained is -[`IsProviderFor`](/docs/reference/traits/is_provider_for), which is also a supertrait on the provider +[`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for), which is also a supertrait on the provider trait. Every provider implements it under exactly the bounds it needs, and requiring it here carries those bounds back down the chain, so when a context is missing something a provider requires, the compiler can name the missing requirement instead of reporting only that the provider trait is not diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index 2ee267e1..07e14ad3 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -132,8 +132,8 @@ For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_da derive and its slices are [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) for reading one field, [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) for the whole shape, and [`#[derive(BuildField)]`](/docs/reference/derives/derive_build_field) for the builder. -[`HasFields`](/docs/reference/traits/has_fields) is the whole-shape view those produce, -[`HasBuilder`](/docs/reference/traits/has_builder) is the builder family, and +[`HasFields`](/docs/reference/traits/shape/has_fields) is the whole-shape view those produce, +[`HasBuilder`](/docs/reference/traits/builder/has_builder) is the builder family, and [`Field`](/docs/reference/types/field) and [`Symbol!`](/docs/reference/macros/symbol) are the pieces a shape is made of. diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 4e32b2f0..05581324 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -148,10 +148,10 @@ For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_da derive and its slices are [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) for the whole shape, [`#[derive(ExtractField)]`](/docs/reference/derives/derive_extract_field) for the narrowing, and [`#[derive(FromVariant)]`](/docs/reference/derives/derive_from_variant) for construction -by name. [`ExtractField`](/docs/reference/traits/extract_field) is the extractor family those produce, -[`FromVariant`](/docs/reference/traits/from_variant) constructs a variant generically, and -[the casts](/docs/reference/traits/can_upcast) are `CanUpcast` and -[`CanDowncast`](/docs/reference/traits/can_downcast). +by name. [`ExtractField`](/docs/reference/traits/variant/extract_field) is the extractor family those produce, +[`FromVariant`](/docs/reference/traits/variant/from_variant) constructs a variant generically, and +[the casts](/docs/reference/traits/casting/can_upcast) are `CanUpcast` and +[`CanDowncast`](/docs/reference/traits/casting/can_downcast). --- diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index f1aa64d7..fdfdafe4 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -171,7 +171,7 @@ this shape. For the constructs, [`#[implicit]`](/docs/reference/attributes/implicit) carries the full list of accepted forms and access rules, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the no-wiring capability, [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter) is the getter to reach for in -the three cases above, and [`HasField`](/docs/reference/traits/has_field) is the trait underneath all of +the three cases above, and [`HasField`](/docs/reference/traits/field-access/has_field) is the trait underneath all of them. --- diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index 92acf3c4..477c103c 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -111,10 +111,10 @@ matching an enum variant is a chain of attempts where the first success ends it. For the constructs, [monad providers](/docs/reference/providers/monad) carries `PipeMonadic`, the three markers, and the per-step `BindOk` / `BindErr` forms. The four monad traits are the layer -defining what a monad is here: [`MonadicBind`](/docs/reference/traits/monadic_bind), -[`ContainsValue`](/docs/reference/traits/contains_value), -[`LiftValue`](/docs/reference/traits/lift_value), and -[`MonadicTrans`](/docs/reference/traits/monadic_trans). +defining what a monad is here: [`MonadicBind`](/docs/reference/traits/monad/monadic_bind), +[`ContainsValue`](/docs/reference/traits/monad/contains_value), +[`LiftValue`](/docs/reference/traits/monad/lift_value), and +[`MonadicTrans`](/docs/reference/traits/monad/monadic_trans). --- diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 766e2e7c..d731197c 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -46,15 +46,15 @@ impl DefaultImpls1 for String { ``` That rule is worth internalizing, because the trait's own parameter names suggest the opposite -arrangement (see [`DefaultImpls1`](../traits/default_impls1.md#the-one-thing-to-get-right)). +arrangement (see [`DefaultImpls1`](../traits/namespace/default_impls1.md#the-one-thing-to-get-right)). **The path may name any trait**, not only the three CGP ships. A trait of your own with the right shape -works identically, which is why [`DefaultImpls2`](../traits/default_impls2.md) needed no new construct to +works identically, which is why [`DefaultImpls2`](../traits/namespace/default_impls2.md) needed no new construct to be usable. -The three built-in targets are [`DefaultNamespace`](../traits/default_namespace.md) for a component-only -key, [`DefaultImpls1`](../traits/default_impls1.md) for a per-type default (the usual choice), and -[`DefaultImpls2`](../traits/default_impls2.md) for a two-type key. +The three built-in targets are [`DefaultNamespace`](../traits/namespace/default_namespace.md) for a component-only +key, [`DefaultImpls1`](../traits/namespace/default_impls1.md) for a per-type default (the usual choice), and +[`DefaultImpls2`](../traits/namespace/default_impls2.md) for a two-type key. ## Examples @@ -141,11 +141,11 @@ never the provider's own `where` clause.** That is deliberate, and it lets the a ordinary providers: a provider whose bounds come from [`#[use_type]`](./use_type.md), [`#[uses]`](./uses.md), [`#[implicit]`](./implicit.md), or [`#[use_provider]`](./use_provider.md) registers cleanly, because those bounds stay on the provider's impl and its -[`IsProviderFor`](../traits/is_provider_for.md) and are checked when a real context resolves it. +[`IsProviderFor`](../traits/wiring/is_provider_for.md) and are checked when a real context resolves it. Consumption is the mirror. A `for in DefaultImpls1 { … }` loop inside [`delegate_components!`](../macros/delegate_components.md) emits a -[`DelegateComponent`](../traits/delegate_component.md) impl whose `where` clause projects the default: +[`DelegateComponent`](../traits/wiring/delegate_component.md) impl whose `where` clause projects the default: ```rust where T: DefaultImpls1 @@ -172,7 +172,7 @@ several tables on one provider. **`Key` becomes `Self`, not a parameter.** Read `#[default_impl(Key in Path)]` as "`Key` becomes `Self`" and the trait's positions follow. The parameter names on -[`DefaultImpls1`](../traits/default_impls1.md) suggest otherwise. +[`DefaultImpls1`](../traits/namespace/default_impls1.md) suggest otherwise. **Do not write the table parameter.** The macro appends it; supplying it yourself makes the path's arity wrong. @@ -181,8 +181,8 @@ wrong. something to work around: put the wiring in the namespace body instead. **The lookup trait must be imported.** The emitted impl names it, so -[`DefaultImpls1`](../traits/default_impls1.md) and [`DefaultImpls2`](../traits/default_impls2.md) need -`use cgp::core::component::…`; [`DefaultNamespace`](../traits/default_namespace.md) is in the prelude. +[`DefaultImpls1`](../traits/namespace/default_impls1.md) and [`DefaultImpls2`](../traits/namespace/default_impls2.md) need +`use cgp::core::component::…`; [`DefaultNamespace`](../traits/namespace/default_namespace.md) is in the prelude. **It takes one argument and is not repeatable** for several tables on one provider. @@ -190,16 +190,16 @@ something to work around: put the wiring in the namespace body instead. ## Related constructs -- [`DefaultImpls1`](../traits/default_impls1.md) — the usual target, and where the positional rule is +- [`DefaultImpls1`](../traits/namespace/default_impls1.md) — the usual target, and where the positional rule is worked out. -- [`DefaultNamespace`](../traits/default_namespace.md) and - [`DefaultImpls2`](../traits/default_impls2.md) — the component-only and two-type targets. +- [`DefaultNamespace`](../traits/namespace/default_namespace.md) and + [`DefaultImpls2`](../traits/namespace/default_impls2.md) — the component-only and two-type targets. - [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. - [`delegate_components!`](../macros/delegate_components.md) — carries the `namespace` header and the `for … in` loop that consume a registration. - [`#[cgp_impl]`](../macros/cgp_impl.md) — the host this attribute goes on. -- [`IsProviderFor`](../traits/is_provider_for.md) — where a registered provider's real bounds are +- [`IsProviderFor`](../traits/wiring/is_provider_for.md) — where a registered provider's real bounds are checked. - [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value. diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 50b77558..94c8fb81 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -200,7 +200,7 @@ where Reading it back: `UseDelegate` is a provider for any `Shape` whose entry in `Components` names something that is itself a provider for that `Shape`, and the method simply forwards. The -`Components` type is the inner table, and [`DelegateComponent`](../traits/delegate_component.md) is the +`Components` type is the inner table, and [`DelegateComponent`](../traits/wiring/delegate_component.md) is the same trait ordinary wiring is made of, which is why you write the table with [`delegate_components!`](../macros/delegate_components.md) like any other. @@ -285,7 +285,7 @@ per-type entries have to be written with the full prefixed path instead. - [`UseDelegate`](../providers/use_delegate.md) — the provider the generated impl is written for. - [`RedirectLookup`](../providers/redirect_lookup.md) — what `open` resolves through instead. - [`#[cgp_component]`](../macros/cgp_component.md) — the host, and the source of the provider trait. -- [`DelegateComponent`](../traits/delegate_component.md) — the table trait the lookup reads. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table trait the lookup reads. - [`cgp_namespace!`](../macros/cgp_namespace.md) — the full form of the mechanism `open` is a special case of. The ideas behind it: diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index a8f11211..3b1e6bb0 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -158,7 +158,7 @@ The trait carries only the promoted predicate; the function's own bound is absen default this attribute overrides. The implementation carries three, and their **order is fixed**: the function's own `where` clause first, -then whatever the attributes contribute, then the [`HasField`](../traits/has_field.md) bounds from +then whatever the attributes contribute, then the [`HasField`](../traits/field-access/has_field.md) bounds from [`#[implicit]`](implicit.md) arguments, which are always appended last. That order is worth knowing when reading a long `where` clause in an expansion, since it tells you where each bound came from. diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 954352af..9d325a83 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -26,7 +26,7 @@ A call like `rect.rectangle_area()` does not require the arguments to be passed `#[implicit]` gives better ergonomics than the alternatives, such as [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) or the direct use of -[`HasField`](../traits/has_field.md). With those, you declare that the context has each field and then +[`HasField`](../traits/field-access/has_field.md). With those, you declare that the context has each field and then fetch it by hand, so you have to understand the mechanism behind field access, such as how a type-level [`Symbol!`](../macros/symbol.md) and a `PhantomData` tag work. `#[implicit]` keeps all of that behind an argument that reads as `width: f64`, and the argument's *name* names the field. @@ -91,8 +91,8 @@ The same rules govern the getter traits, so learning them once covers everywhere An implicit argument is mutable when its type carries a `&mut`: the outer reference of a `&mut T` or a `&mut [T]`, or the inner reference of an `Option<&mut T>` or an `Option<&mut str>`. A mutable argument -reads through [`HasFieldMut`](../traits/has_field_mut.md) and `get_field_mut` rather than through -[`HasField`](../traits/has_field.md) and `get_field`, so it borrows the field for writing. +reads through [`HasFieldMut`](../traits/field-access/has_field_mut.md) and `get_field_mut` rather than through +[`HasField`](../traits/field-access/has_field.md) and `get_field`, so it borrows the field for writing. Two rules follow. A mutable argument requires a `&mut self` receiver, since a function cannot borrow a field mutably through a shared `&self`. And it must be the only implicit argument on its function, @@ -190,7 +190,7 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> ``` the macro strips the arguments from the trait's method and turns them into -[`HasField`](../traits/has_field.md) bounds and reads: +[`HasField`](../traits/field-access/has_field.md) bounds and reads: ```rust pub trait RectangleArea { @@ -272,7 +272,7 @@ error: a `&mut` implicit argument must be the only implicit argument, since its - [`#[cgp_fn]`](../macros/cgp_fn.md) — the usual host, turning a function into a capability. - [`#[cgp_impl]`](../macros/cgp_impl.md) — the other host, for a component's provider. - [`#[derive(HasField)]`](../derives/derive_has_field.md) — what a context derives to qualify. -- [`HasField`](../traits/has_field.md) — the trait the generated bounds are written against. +- [`HasField`](../traits/field-access/has_field.md) — the trait the generated bounds are written against. - [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — the getter form, for the cases above. - [`#[cgp_getter]`](../macros/cgp_getter.md) — a getter whose source field is chosen by wiring. - [`#[uses]`](uses.md) — imports a capability rather than a value. diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 68ef5bac..368170db 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -169,7 +169,7 @@ parameter is literally `__Context__` in the emitted code, and appears as `Self` Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the behaviour is the same, with the predicates appended to that provider's `where` clause. That is also where the generated -[`IsProviderFor`](../traits/is_provider_for.md) impl picks them up, so the compiler reports an unmet +[`IsProviderFor`](../traits/wiring/is_provider_for.md) impl picks them up, so the compiler reports an unmet import by name rather than as a bare missing implementation. ## Formal grammar diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md index 29eea8af..288369db 100644 --- a/docs/reference/components/handler/handler.md +++ b/docs/reference/components/handler/handler.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Handler' sidebar_position: 3 +slug: /reference/components/handler/handler --- # `Handler` diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index cc4e479e..fa2c2fb0 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -82,7 +82,7 @@ three of them. **`build_field`** sets one absent field to a value, which is the step shown above. **`build_from`** copies every field the target and a source record share, in one step. It comes from -[`CanBuildFrom`](../traits/can_build_from.md), and is imported from +[`CanBuildFrom`](../traits/casting/can_build_from.md), and is imported from `cgp::core::field::impls`: ```rust @@ -185,7 +185,7 @@ case it exists for, and it is a narrower case than "this struct has several fiel - **Do not reach for it in place of a conventional builder** with defaults and validation. It tracks presence and nothing else: it has no notion of a default value, no way to run a check at finalize time, and no optional field unless you make the field's own type optional. The - [optional-field extensions](../traits/has_optional_builder.md) cover the defaulted and optional cases, + [optional-field extensions](../traits/optional/has_optional_builder.md) cover the defaulted and optional cases, and a hand-written builder remains the better fit when the logic is the point. Between this derive and its neighbours the choice is about how much of the machinery you want. @@ -199,7 +199,7 @@ Between this derive and its neighbours the choice is about how much of the machi ## Under the hood The derive centres on a companion struct named `__Partial{Name}`. It is your struct with one -[`MapType`](../traits/map_type.md) parameter added per field, and each field's type wrapped in that +[`MapType`](../traits/type-level/map_type.md) parameter added per field, and each field's type wrapped in that parameter's projection. The marker decides how the field is stored: `IsPresent` maps `T` to `T`, `IsNothing` maps it to `()`, and `IsVoid` maps it to the uninhabited `Void`. From: @@ -310,7 +310,7 @@ directly. `CanBuildFrom`, which provides `build_from`, comes from `cgp::core::fi **There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible default still has to be set explicitly, unless you reach for -[`CanFinalizeWithDefault`](../traits/can_finalize_with_default.md). +[`CanFinalizeWithDefault`](../traits/optional/can_finalize_with_default.md). **A tuple struct's steps are keyed by position.** Use `PhantomData::>`, not a `Symbol!` of the number. @@ -332,13 +332,13 @@ renaming a field in one struct silently stops it being copied from the other. Th not generate either. - [`#[derive(ExtractField)]`](./derive_extract_field.md) — the enum analogue: incremental deconstruction rather than construction. -- [`HasBuilder`](../traits/has_builder.md) — the builder trait family, including `UpdateField`, `BuildField`, +- [`HasBuilder`](../traits/builder/has_builder.md) — the builder trait family, including `UpdateField`, `BuildField`, `TakeField`, and `FinalizeBuild`. -- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers the companion is +- [`MapType`](../traits/type-level/map_type.md) — the `IsPresent`/`IsNothing`/`IsVoid` markers the companion is parameterized by. -- [`CanBuildFrom`](../traits/can_build_from.md) — where `build_from` is documented. -- [`HasOptionalBuilder`](../traits/has_optional_builder.md) and - [`CanFinalizeWithDefault`](../traits/can_finalize_with_default.md) — optional and defaulted fields, +- [`CanBuildFrom`](../traits/casting/can_build_from.md) — where `build_from` is documented. +- [`HasOptionalBuilder`](../traits/optional/has_optional_builder.md) and + [`CanFinalizeWithDefault`](../traits/optional/can_finalize_with_default.md) — optional and defaulted fields, which the plain builder does not model. - [Dispatch combinators](../providers/dispatch/index.md) — the providers that run several builder implementations and merge their outputs. diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index d1968e51..dcd4746c 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -189,9 +189,9 @@ companion type and roughly twenty impls. If only part of the output is wanted, d - [`#[derive(BuildField)]`](./derive_build_field.md) — the record builder slice, on its own. - [`#[derive(ExtractField)]`](./derive_extract_field.md) — the extractor slice, on its own. - [`#[derive(FromVariant)]`](./derive_from_variant.md) — the variant constructors, on their own. -- [`HasBuilder`](../traits/has_builder.md) and [`ExtractField`](../traits/extract_field.md) — the two +- [`HasBuilder`](../traits/builder/has_builder.md) and [`ExtractField`](../traits/variant/extract_field.md) — the two trait families the shapes generate impls for. -- [`MapType`](../traits/map_type.md) — the markers the companion types are parameterized by. +- [`MapType`](../traits/type-level/map_type.md) — the markers the companion types are parameterized by. The ideas behind it: diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index c78dbd1e..8d86a900 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -87,9 +87,9 @@ fn promote(person: Person, id: u64) -> Employee { ``` Neither struct knows about the other. They share two field *names*, matched at the type level, so -[`build_from`](../traits/can_build_from.md) moves those fields across and leaves `employee_id` for the +[`build_from`](../traits/casting/can_build_from.md) moves those fields across and leaves `employee_id` for the caller. Remove the `build_field` line and this stops compiling, because -[`finalize_build`](../traits/finalize_build.md) only exists once every field is present. +[`finalize_build`](../traits/builder/finalize_build.md) only exists once every field is present. ## When to use it @@ -125,8 +125,8 @@ pub struct Person { } ``` -it first emits the **per-field access**: a [`HasField`](../traits/has_field.md) and a -[`HasFieldMut`](../traits/has_field_mut.md) impl per field, exactly what +it first emits the **per-field access**: a [`HasField`](../traits/field-access/has_field.md) and a +[`HasFieldMut`](../traits/field-access/has_field_mut.md) impl per field, exactly what [`#[derive(HasField)]`](./derive_has_field.md) produces on its own. Then the **representation**, exposing the struct as a product of named entries with conversions in both @@ -144,7 +144,7 @@ impl HasFields for Person { ``` Then the **builder**, which is [`#[derive(BuildField)]`](./derive_build_field.md)'s output and where the -companion type appears. Each field's type is wrapped in a [`MapType`](../traits/map_type.md) marker, so +companion type appears. Each field's type is wrapped in a [`MapType`](../traits/type-level/map_type.md) marker, so a field can be present (`IsPresent`, holding the value) or absent (`IsNothing`, holding `()`): ```rust @@ -164,9 +164,9 @@ impl FinalizeBuild for __PartialPerson { ``` That pair of impls is the whole safety argument: `builder()` starts at all-absent, each -[`build_field`](../traits/build_field.md) flips one marker, and -[`finalize_build`](../traits/finalize_build.md) exists only at all-present, so finalizing early is a -missing impl rather than a runtime check. The per-field [`UpdateField`](../traits/update_field.md) impls +[`build_field`](../traits/builder/build_field.md) flips one marker, and +[`finalize_build`](../traits/builder/finalize_build.md) exists only at all-present, so finalizing early is a +missing impl rather than a runtime check. The per-field [`UpdateField`](../traits/builder/update_field.md) impls that move a marker, and the `HasField` impls on the companion that let a set field be read back, follow. The companion is named `__Partial{Name}` and keeps the original type's visibility, so a `pub` struct @@ -179,7 +179,7 @@ token rather than the whole derive. **The companion type carries none of your attributes.** The derive clears them, so a `#[derive(Debug, Clone)]` on the record does not reach `__Partial{Name}` and a partially-built value can be neither printed nor cloned. Read a set field back through the companion's -[`HasField`](../traits/has_field.md) impl instead. +[`HasField`](../traits/field-access/has_field.md) impl instead. **A tuple struct's builder is keyed by position.** Its companion exposes `UpdateField, _>` rather than symbol-keyed impls, so `build_field` takes `PhantomData::>`. @@ -203,10 +203,10 @@ companion type and roughly twenty impls. If only part of the output is wanted, d - [`#[derive(CgpVariant)]`](./derive_cgp_variant.md) — the enum face. - [`#[derive(HasField)]`](./derive_has_field.md), [`#[derive(HasFields)]`](./derive_has_fields.md), and [`#[derive(BuildField)]`](./derive_build_field.md) — the three slices this emits. -- [`HasBuilder`](../traits/has_builder.md) — the builder family it generates impls for. -- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsNothing` markers the companion is +- [`HasBuilder`](../traits/builder/has_builder.md) — the builder family it generates impls for. +- [`MapType`](../traits/type-level/map_type.md) — the `IsPresent`/`IsNothing` markers the companion is parameterized by. -- [`CanBuildFrom`](../traits/can_build_from.md) — merging one record into another's builder. +- [`CanBuildFrom`](../traits/casting/can_build_from.md) — merging one record into another's builder. The ideas behind it: diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 9a50bfdf..7cecbc84 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -113,7 +113,7 @@ fn area(shape: Shape) -> f64 { There is no wildcard arm and no `unreachable!()`. After the second extraction the remainder's type has both variants ruled out, which makes it uninhabited, and -[`finalize_extract_result`](../traits/finalize_extract_result.md) discharges a value that cannot exist. +[`finalize_extract_result`](../traits/variant/finalize_extract_result.md) discharges a value that cannot exist. Add a third variant to `Shape` and this function stops compiling until it is handled, which is the same guarantee a concrete `match` gives, recovered for code that never names the enum. @@ -176,7 +176,7 @@ impl FromVariant for Shape { Then the **extractor**, which is [`#[derive(ExtractField)]`](./derive_extract_field.md)'s output and where two companion enums appear: `__PartialShape` for owned extraction and `__PartialRefShape` for -borrowed. A variant's payload is wrapped in a [`MapType`](../traits/map_type.md) marker that is either +borrowed. A variant's payload is wrapped in a [`MapType`](../traits/type-level/map_type.md) marker that is either `IsPresent` or `IsVoid`, the latter mapping it to the uninhabited `Void`: ```rust @@ -239,10 +239,10 @@ record and variant machinery have been crossed. - [`#[derive(CgpRecord)]`](./derive_cgp_record.md) — the struct face. - [`#[derive(HasFields)]`](./derive_has_fields.md), [`#[derive(FromVariant)]`](./derive_from_variant.md), and [`#[derive(ExtractField)]`](./derive_extract_field.md) — the three slices this emits. -- [`ExtractField`](../traits/extract_field.md) — the extractor family it generates impls for. -- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsVoid` markers the companions are parameterized +- [`ExtractField`](../traits/variant/extract_field.md) — the extractor family it generates impls for. +- [`MapType`](../traits/type-level/map_type.md) — the `IsPresent`/`IsVoid` markers the companions are parameterized by. -- [`CanUpcast`](../traits/can_upcast.md) and [`CanDowncast`](../traits/can_downcast.md) — converting +- [`CanUpcast`](../traits/casting/can_upcast.md) and [`CanDowncast`](../traits/casting/can_downcast.md) — converting between two enums whose variants overlap, built on this machinery. - [Dispatch combinators](../providers/dispatch/index.md) — the providers that route a variant to the implementation handling it. diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index c78effcf..a264eb44 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -207,7 +207,7 @@ derive you did not need. ## Under the hood The derive centres on **two** companion enums. `__Partial{Name}` is your enum with one -[`MapType`](../traits/map_type.md) parameter added per variant and each payload wrapped in that parameter's +[`MapType`](../traits/type-level/map_type.md) parameter added per variant and each payload wrapped in that parameter's projection, where `IsPresent` keeps the payload and `IsVoid` maps it to the uninhabited `Void`. `__PartialRef{Name}` adds a reserved `'__a__` lifetime and a second marker that selects a shared or a mutable borrow of each payload. From: @@ -350,11 +350,11 @@ enum's own variant list rather than repeating it at each site. not generate either, and the one derive that accepts every variant shape. - [`#[derive(BuildField)]`](./derive_build_field.md) — the struct analogue: incremental construction rather than deconstruction. -- [`ExtractField`](../traits/extract_field.md) — the extractor trait family, including `HasExtractor`, +- [`ExtractField`](../traits/variant/extract_field.md) — the extractor trait family, including `HasExtractor`, `FinalizeExtract`, and `FinalizeExtractResult`. -- [`MapType`](../traits/map_type.md) — the `IsPresent`/`IsVoid` markers the companion enums are parameterized +- [`MapType`](../traits/type-level/map_type.md) — the `IsPresent`/`IsVoid` markers the companion enums are parameterized by. -- [`CanUpcast`](../traits/can_upcast.md) — upcasting and downcasting between enums, which reuse this recursion. +- [`CanUpcast`](../traits/casting/can_upcast.md) — upcasting and downcasting between enums, which reuse this recursion. - [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain an enum's shape is built from. - [Dispatch combinators](../providers/dispatch/index.md) — the providers that build an extraction chain diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 63b0ffc9..d09ba8c4 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -123,7 +123,7 @@ let expr = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::` parameter carries no value. It exists so a call site can several are in scope, which is why the tag is passed as `PhantomData::` rather than inferred. -The [`FromVariant`](../traits/from_variant.md) trait itself is defined in the library; the derive supplies only +The [`FromVariant`](../traits/variant/from_variant.md) trait itself is defined in the library; the derive supplies only these per-variant impls. Each is aimed at the variant it came from, so a conflict with a hand-written impl underlines that variant rather than the whole `#[derive(FromVariant)]`. @@ -228,9 +228,9 @@ and, as with the other empty shapes, means a mistake shows up later rather than not generate, and the only derive that accepts every variant shape. - [`#[derive(BuildField)]`](./derive_build_field.md) — the struct analogue: setting one field rather than choosing one variant. -- [`FromVariant`](../traits/from_variant.md) — the trait this generates impls of. +- [`FromVariant`](../traits/variant/from_variant.md) — the trait this generates impls of. - [`Symbol!`](../macros/symbol.md) — the tag that names a variant. -- [`CanUpcast`](../traits/can_upcast.md) — widening a smaller enum into a larger one, built on these constructors. +- [`CanUpcast`](../traits/casting/can_upcast.md) — widening a smaller enum into a larger one, built on these constructors. - [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain the constructed variants correspond to. diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index e4ce3a95..780e1af3 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -227,7 +227,7 @@ impl HasFieldMut for Person { The `PhantomData` parameter carries no value. It exists so a call site can say *which* field it means when several `HasField` impls are in scope, which is why a call site writes -`PhantomData::`. [`HasFieldMut`](../traits/has_field_mut.md) extends `HasField` with +`PhantomData::`. [`HasFieldMut`](../traits/field-access/has_field_mut.md) extends `HasField` with `get_field_mut`, and it is always generated alongside the read accessor, whether or not anything uses it. A tuple struct produces the same shape with a positional tag: @@ -285,7 +285,7 @@ are easy to confuse. - [`#[derive(HasFields)]`](./derive_has_fields.md) — the whole-shape counterpart, commonly derived alongside this one. -- [`HasField`](../traits/has_field.md) — the trait this generates, with `HasFieldMut` and the provider-side +- [`HasField`](../traits/field-access/has_field.md) — the trait this generates, with `HasFieldMut` and the provider-side `FieldGetter`. - [`Symbol!`](../macros/symbol.md) — the tag for a named field. - [`Index`](../types/index.md) — the tag for a tuple field. diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 59601b92..2c3fdfab 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -327,7 +327,7 @@ by one letter and the outputs do not overlap. - [`#[derive(HasField)]`](./derive_has_field.md) — the singular counterpart, per-field access, commonly derived alongside this one. -- [`HasFields`](../traits/has_fields.md) — the traits this generates and the conversions between a value +- [`HasFields`](../traits/shape/has_fields.md) — the traits this generates and the conversions between a value and its shape. - [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this one plus the incremental machinery. @@ -337,8 +337,8 @@ by one letter and the outputs do not overlap. - [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that name an entry. - [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains the sugar expands to. -- [`AppendProduct`](../traits/append_product.md) — operations over a shape once you have one. -- [`CanUpcast`](../traits/can_upcast.md) — converting between two types whose shapes overlap. +- [`AppendProduct`](../traits/type-level/append_product.md) — operations over a shape once you have one. +- [`CanUpcast`](../traits/casting/can_upcast.md) — converting between two types whose shapes overlap. The ideas behind it: diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 6e51377e..e3b4c8e8 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -651,9 +651,9 @@ A tree entry that merely passes a non-CGP message through in rustc's own words i - [`check_components!`](./macros/check_components.md) — turns a hidden failure into a surfaced one, and the first thing to reach for. - [`delegate_components!`](./macros/delegate_components.md) — the wiring nearly every error here is about. -- [`IsProviderFor`](./traits/is_provider_for.md) — the marker that carries a provider's requirements into +- [`IsProviderFor`](./traits/wiring/is_provider_for.md) — the marker that carries a provider's requirements into a diagnostic; the reason a checked error names the cause at all. -- [`CanUseComponent`](./traits/can_use_component.md) — what a check asserts. +- [`CanUseComponent`](./traits/wiring/can_use_component.md) — what a check asserts. - [`cargo cgp check`](/docs/cargo-cgp/check) — the tool every rewritten output on this page came from. - [`Symbol!`](./macros/symbol.md) — the type-level field name whose raw `Chars<…>` spine the tool resugars. diff --git a/docs/reference/index.md b/docs/reference/index.md index 885e1b09..6cfbe2e6 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -70,7 +70,7 @@ complete and every dependency behind it is satisfied. suits simple wiring and getting started. Two providers appear in tables constantly: [`UseContext`](./providers/use_context.md), which routes back through the context's own implementation, and [`UseDefault`](./providers/use_default.md), which selects a component's default -method bodies. Underneath it all is [`DelegateComponent`](./traits/delegate_component.md), the trait +method bodies. Underneath it all is [`DelegateComponent`](./traits/wiring/delegate_component.md), the trait the table is made of. ### Read values out of the context @@ -78,12 +78,12 @@ the table is made of. An [`#[implicit]`](./attributes/implicit.md) argument is the default way to read a field: it looks like an ordinary function parameter and is filled from a same-named field on the context. The field access itself comes from [`#[derive(HasField)]`](./derives/derive_has_field.md) and the -[`HasField`](./traits/has_field.md) trait, whose mutable form is -[`HasFieldMut`](./traits/has_field_mut.md). Four further traits are the machinery underneath, generated -rather than written: [`FieldGetter`](./traits/field_getter.md) and -[`MutFieldGetter`](./traits/mut_field_getter.md) are the provider-side mirrors a getter component is -wired through, and [`MapField`](./traits/map_field.md) with -[`FieldMapper`](./traits/field_mapper.md) are what let a getter reach into a nested value without +[`HasField`](./traits/field-access/has_field.md) trait, whose mutable form is +[`HasFieldMut`](./traits/field-access/has_field_mut.md). Four further traits are the machinery underneath, generated +rather than written: [`FieldGetter`](./traits/field-access/field_getter.md) and +[`MutFieldGetter`](./traits/field-access/mut_field_getter.md) are the provider-side mirrors a getter component is +wired through, and [`MapField`](./traits/field-access/map_field.md) with +[`FieldMapper`](./traits/field-access/field_mapper.md) are what let a getter reach into a nested value without forcing its type to be `'static`. Getter traits are the sparing alternative, for the cases an implicit argument cannot reach. @@ -146,8 +146,8 @@ Providers in this family are written from plain functions with composed with the [handler combinators](./providers/handler/index.md), the [dispatch combinators](./providers/dispatch/index.md), and the [monad providers](./providers/monad/index.md) built on the monad traits — -[`MonadicBind`](./traits/monadic_bind.md), [`ContainsValue`](./traits/contains_value.md), -[`LiftValue`](./traits/lift_value.md), and [`MonadicTrans`](./traits/monadic_trans.md). +[`MonadicBind`](./traits/monad/monadic_bind.md), [`ContainsValue`](./traits/monad/contains_value.md), +[`LiftValue`](./traits/monad/lift_value.md), and [`MonadicTrans`](./traits/monad/monadic_trans.md). [`#[cgp_auto_dispatch]`](./macros/cgp_auto_dispatch.md) generates a dispatching handler from a per-type trait. @@ -164,18 +164,18 @@ individual slices are [`#[derive(HasFields)]`](./derives/derive_has_fields.md), [`#[derive(FromVariant)]`](./derives/derive_from_variant.md). Each of those generates traits, and the traits are where the operations live. The whole-shape view is -[`HasFields`](./traits/has_fields.md) with its conversions [`ToFields`](./traits/to_fields.md) and -[`FromFields`](./traits/from_fields.md); the builder family runs from -[`HasBuilder`](./traits/has_builder.md) through [`BuildField`](./traits/build_field.md) to -[`FinalizeBuild`](./traits/finalize_build.md); the extractor family runs from -[`HasExtractor`](./traits/has_extractor.md) through [`ExtractField`](./traits/extract_field.md) to -[`FinalizeExtract`](./traits/finalize_extract.md), with -[`FromVariant`](./traits/from_variant.md) constructing rather than deconstructing. Underneath sit the -presence markers of [`MapType`](./traits/map_type.md), the list algebra of -[`AppendProduct`](./traits/append_product.md), the structural casts -[`CanUpcast`](./traits/can_upcast.md) and [`CanBuildFrom`](./traits/can_build_from.md), and the +[`HasFields`](./traits/shape/has_fields.md) with its conversions [`ToFields`](./traits/shape/to_fields.md) and +[`FromFields`](./traits/shape/from_fields.md); the builder family runs from +[`HasBuilder`](./traits/builder/has_builder.md) through [`BuildField`](./traits/builder/build_field.md) to +[`FinalizeBuild`](./traits/builder/finalize_build.md); the extractor family runs from +[`HasExtractor`](./traits/variant/has_extractor.md) through [`ExtractField`](./traits/variant/extract_field.md) to +[`FinalizeExtract`](./traits/variant/finalize_extract.md), with +[`FromVariant`](./traits/variant/from_variant.md) constructing rather than deconstructing. Underneath sit the +presence markers of [`MapType`](./traits/type-level/map_type.md), the list algebra of +[`AppendProduct`](./traits/type-level/append_product.md), the structural casts +[`CanUpcast`](./traits/casting/can_upcast.md) and [`CanBuildFrom`](./traits/casting/can_build_from.md), and the optional-field extensions starting at -[`HasOptionalBuilder`](./traits/has_optional_builder.md). Each entry in a shape is a +[`HasOptionalBuilder`](./traits/optional/has_optional_builder.md). Each entry in a shape is a [`Field`](./types/field.md). Those families run to a good many traits, most of which you read rather than write. The table below is @@ -183,13 +183,13 @@ the whole set, so that a name met in an expansion or an error message can be loo | Family | The traits in it | |---|---| -| The shape | [`HasFields`](./traits/has_fields.md), [`HasFieldsRef`](./traits/has_fields_ref.md), [`ToFields`](./traits/to_fields.md), [`FromFields`](./traits/from_fields.md), [`ToFieldsRef`](./traits/to_fields_ref.md) | -| Building a record | [`HasBuilder`](./traits/has_builder.md), [`IntoBuilder`](./traits/into_builder.md), [`BuildField`](./traits/build_field.md), [`TakeField`](./traits/take_field.md), [`UpdateField`](./traits/update_field.md), [`PartialData`](./traits/partial_data.md), [`FinalizeBuild`](./traits/finalize_build.md) | -| Taking an enum apart | [`HasExtractor`](./traits/has_extractor.md), [`HasExtractorRef`](./traits/has_extractor_ref.md), [`HasExtractorMut`](./traits/has_extractor_mut.md), [`ExtractField`](./traits/extract_field.md), [`FinalizeExtract`](./traits/finalize_extract.md), [`FinalizeExtractResult`](./traits/finalize_extract_result.md), [`FromVariant`](./traits/from_variant.md) | -| Converting between shapes | [`CanUpcast`](./traits/can_upcast.md), [`CanDowncast`](./traits/can_downcast.md), [`CanDowncastFields`](./traits/can_downcast_fields.md), [`CanBuildFrom`](./traits/can_build_from.md) | -| Optional and defaulted fields | [`HasOptionalBuilder`](./traits/has_optional_builder.md), [`ToOptional`](./traits/to_optional.md), [`SetOptional`](./traits/set_optional.md), [`FinalizeOptional`](./traits/finalize_optional.md), [`CanFinalizeWithDefault`](./traits/can_finalize_with_default.md), [`CanBuildWithDefault`](./traits/can_build_with_default.md) | -| Field state, and changing it | [`MapType`](./traits/map_type.md), [`MapTypeRef`](./traits/map_type_ref.md), [`TransformMap`](./traits/transform_map.md), [`TransformMapFields`](./traits/transform_map_fields.md), [`TransformMapDefault`](./traits/transform_map_default.md), [`TransformOptional`](./traits/transform_optional.md) | -| Computing a shape | [`AppendProduct`](./traits/append_product.md), [`ConcatProduct`](./traits/concat_product.md), [`MapFields`](./traits/map_fields.md) | +| The shape | [`HasFields`](./traits/shape/has_fields.md), [`HasFieldsRef`](./traits/shape/has_fields_ref.md), [`ToFields`](./traits/shape/to_fields.md), [`FromFields`](./traits/shape/from_fields.md), [`ToFieldsRef`](./traits/shape/to_fields_ref.md) | +| Building a record | [`HasBuilder`](./traits/builder/has_builder.md), [`IntoBuilder`](./traits/builder/into_builder.md), [`BuildField`](./traits/builder/build_field.md), [`TakeField`](./traits/builder/take_field.md), [`UpdateField`](./traits/builder/update_field.md), [`PartialData`](./traits/builder/partial_data.md), [`FinalizeBuild`](./traits/builder/finalize_build.md) | +| Taking an enum apart | [`HasExtractor`](./traits/variant/has_extractor.md), [`HasExtractorRef`](./traits/variant/has_extractor_ref.md), [`HasExtractorMut`](./traits/variant/has_extractor_mut.md), [`ExtractField`](./traits/variant/extract_field.md), [`FinalizeExtract`](./traits/variant/finalize_extract.md), [`FinalizeExtractResult`](./traits/variant/finalize_extract_result.md), [`FromVariant`](./traits/variant/from_variant.md) | +| Converting between shapes | [`CanUpcast`](./traits/casting/can_upcast.md), [`CanDowncast`](./traits/casting/can_downcast.md), [`CanDowncastFields`](./traits/casting/can_downcast_fields.md), [`CanBuildFrom`](./traits/casting/can_build_from.md) | +| Optional and defaulted fields | [`HasOptionalBuilder`](./traits/optional/has_optional_builder.md), [`ToOptional`](./traits/optional/to_optional.md), [`SetOptional`](./traits/optional/set_optional.md), [`FinalizeOptional`](./traits/optional/finalize_optional.md), [`CanFinalizeWithDefault`](./traits/optional/can_finalize_with_default.md), [`CanBuildWithDefault`](./traits/optional/can_build_with_default.md) | +| Field state, and changing it | [`MapType`](./traits/type-level/map_type.md), [`MapTypeRef`](./traits/type-level/map_type_ref.md), [`TransformMap`](./traits/type-level/transform_map.md), [`TransformMapFields`](./traits/type-level/transform_map_fields.md), [`TransformMapDefault`](./traits/optional/transform_map_default.md), [`TransformOptional`](./traits/optional/transform_optional.md) | +| Computing a shape | [`AppendProduct`](./traits/type-level/append_product.md), [`ConcatProduct`](./traits/type-level/concat_product.md), [`MapFields`](./traits/type-level/map_fields.md) | ### Keep large wiring manageable @@ -197,8 +197,8 @@ the whole set, so that a name met in an expansion or an error message can be loo contexts can join, which is how top-level wiring stays short as component counts grow. It works through [`RedirectLookup`](./providers/redirect_lookup.md), which re-routes a lookup along a [`Path!`](./macros/path.md), together with the three lookup traits that resolve inherited and per-type -defaults — [`DefaultNamespace`](./traits/default_namespace.md) for a key that is a component alone, and -[`DefaultImpls1`](./traits/default_impls1.md) and [`DefaultImpls2`](./traits/default_impls2.md) when the +defaults — [`DefaultNamespace`](./traits/namespace/default_namespace.md) for a key that is a component alone, and +[`DefaultImpls1`](./traits/namespace/default_impls1.md) and [`DefaultImpls2`](./traits/namespace/default_impls2.md) when the key carries one further type or two. A provider registers itself as one of those defaults with [`#[default_impl(...)]`](./attributes/default_impl.md). The `open` statement of [`delegate_components!`](./macros/delegate_components.md) is a @@ -214,14 +214,14 @@ sugar — [`Symbol!`](./macros/symbol.md) for a field name, [`Product!`](./macro recognize [what they expand into](./types/type_level_spines.md) when it appears in an error message. [`Index`](./types/index.md) tags a tuple field and [`Life`](./types/life.md) lifts a lifetime into a type. Three traits turn those encodings back into runtime data: -[`StaticString`](./traits/static_string.md) decodes a type-level string into a constant, -[`StaticFormat`](./traits/static_format.md) writes one into a formatter and is what makes it printable -at all, and [`ConcatPath`](./traits/concat_path.md) joins two paths. +[`StaticString`](./traits/formatting/static_string.md) decodes a type-level string into a constant, +[`StaticFormat`](./traits/formatting/static_format.md) writes one into a formatter and is what makes it printable +at all, and [`ConcatPath`](./traits/formatting/concat_path.md) joins two paths. When wiring fails, three traits are what you will see named: -[`DelegateComponent`](./traits/delegate_component.md), -[`IsProviderFor`](./traits/is_provider_for.md), which is what makes a missing dependency show up by -name, and [`CanUseComponent`](./traits/can_use_component.md), which is what a check asserts. The +[`DelegateComponent`](./traits/wiring/delegate_component.md), +[`IsProviderFor`](./traits/wiring/is_provider_for.md), which is what makes a missing dependency show up by +name, and [`CanUseComponent`](./traits/wiring/can_use_component.md), which is what a check asserts. The [compile errors](./errors.md) page covers the recurring failures and how to read them. ## Looking for a name you don't see? @@ -241,8 +241,8 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w | `MatchWithHandlersRef`, `MatchFirstWithHandlers`, and the other borrowed and first-argument matcher forms | the matcher page they vary, under [Dispatch combinators](./providers/dispatch/index.md) | | `ExtractFirstFieldAndHandle`, `HandleFirstFieldValue` | [`ExtractFieldAndHandle`](./providers/dispatch/extract_field_and_handle.md), [`HandleFieldValue`](./providers/dispatch/handle_field_value.md) | | `DispatchMatchers`, `ToFieldHandlers`, `HasFieldHandlers`, `MapFieldHandler` | [Dispatch combinators](./providers/dispatch/index.md) | -| `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` | [`MapType`](./traits/map_type.md) | -| `IsRef`, `IsMut`, `IsOwned` | [`MapTypeRef`](./traits/map_type_ref.md) | +| `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` | [`MapType`](./traits/type-level/map_type.md) | +| `IsRef`, `IsMut`, `IsOwned` | [`MapTypeRef`](./traits/type-level/map_type_ref.md) | | `product!` (the value-level form) | [`Product!`](./macros/product.md) | | `#[impl_generics(...)]` | [`#[cgp_fn]`](./macros/cgp_fn.md) | | `#[prefix(...)]` | [`cgp_namespace!`](./macros/cgp_namespace.md) | diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index b30f62af..8635f1af 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -292,7 +292,7 @@ Where a type needs different behaviour, the trait wants to be a [component](./cg dependencies are fields rather than traits. - [`#[cgp_component]`](./cgp_component.md) — the step up, when one implementation is not enough. - [`#[cgp_auto_getter]`](./cgp_auto_getter.md) — the same constraint-hiding applied to reading a field. -- [`HasField`](../traits/has_field.md) — what value-level dependency injection is built on. +- [`HasField`](../traits/field-access/has_field.md) — what value-level dependency injection is built on. - [`#[uses]`](../attributes/uses.md) — how a CGP provider declares the trait dependencies a supertrait declares here. diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index c2fa03a1..d2d97944 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -260,7 +260,7 @@ hand for some other type without colliding with it. - [`#[cgp_computer]`](./cgp_computer.md) — how each per-variant handler is emitted. - [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — what the enum needs to be dispatchable. - [`Computer`](../components/handler/computer.md) — the component the generated bound is written against. -- [`ExtractField`](../traits/extract_field.md) — the extractor family the matching walks. +- [`ExtractField`](../traits/variant/extract_field.md) — the extractor family the matching walks. - [`#[cgp_component]`](./cgp_component.md) — the better starting point when contexts should configure the operation. diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 46224399..03d67db0 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -339,7 +339,7 @@ found rather than the trait as not imported. - [`#[implicit]`](../attributes/implicit.md) — the default way to read a field, and the form to prefer. - [`#[cgp_getter]`](./cgp_getter.md) — the wireable counterpart, for per-context field choice. - [`#[derive(HasField)]`](../derives/derive_has_field.md) — what a context derives to qualify. -- [`HasField`](../traits/has_field.md) — the trait the generated bound is written against. +- [`HasField`](../traits/field-access/has_field.md) — the trait the generated bound is written against. - [`Symbol!`](./symbol.md) — the type-level field name the bound is keyed on. - [`#[uses]`](../attributes/uses.md) — how a provider depends on a getter by name. - [`#[cgp_type]`](./cgp_type.md) — for an abstract type standing on its own rather than inferred from a diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index cdb30017..69e843a3 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -246,7 +246,7 @@ pub trait CanCalculateArea { Second, the **provider trait**: the same interface with `Self` replaced by a leading `Context` type parameter and every `self`/`Self` rewritten to `context`/`Context`. Its -[`IsProviderFor`](../traits/is_provider_for.md) supertrait makes an unmet dependency report +[`IsProviderFor`](../traits/wiring/is_provider_for.md) supertrait makes an unmet dependency report itself by name rather than as a bare "trait not implemented"; its third argument is a tuple of the component's extra type parameters, empty here: @@ -307,7 +307,7 @@ where ``` Fourth, the **provider blanket impl**, which makes wiring work: anything that delegates this -component through [`DelegateComponent`](../traits/delegate_component.md) inherits the provider trait +component through [`DelegateComponent`](../traits/wiring/delegate_component.md) inherits the provider trait from whatever it delegates to. ```rust diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index be2d0b6d..38a1e402 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -191,7 +191,7 @@ impl<__Context__, __Code__> Computer<__Context__, __Code__, (u64, u64)> for Add ``` [`#[cgp_new_provider]`](./cgp_provider.md) declares `pub struct Add;` and derives the -[`IsProviderFor`](../traits/is_provider_for.md) impl, whose parameter tuple here is +[`IsProviderFor`](../traits/wiring/is_provider_for.md) impl, whose parameter tuple here is `(__Code__, (u64, u64))`, the code tag and the input. The context and code parameters are introduced under the reserved names `__Context__` and `__Code__`, and the body ignores both. diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 94cc66cd..35e20c6e 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -226,7 +226,7 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> ``` the macro produces the trait with the implicit parameters stripped from the signature, and the impl -with those parameters turned into [`HasField`](../traits/has_field.md) bounds and `let` bindings at the +with those parameters turned into [`HasField`](../traits/field-access/has_field.md) bounds and `let` bindings at the top of the body: ```rust diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index bbb6d51c..dc387310 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -241,7 +241,7 @@ where } ``` -Each of these is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl carrying the +Each of these is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl carrying the same bounds, so a missing field is reported by name when the component is checked. ## Formal grammar @@ -299,7 +299,7 @@ since the tag tells you which field the mismatch is about. - [`UseField`](../providers/use_field.md) — the provider that makes the field name a wiring decision, with `UseFieldRef` and `UseFields` alongside it. - [`#[cgp_component]`](./cgp_component.md) — the macro this extends, and the source of the naming rules. -- [`#[derive(HasField)]`](../derives/derive_has_field.md) and [`HasField`](../traits/has_field.md) — the +- [`#[derive(HasField)]`](../derives/derive_has_field.md) and [`HasField`](../traits/field-access/has_field.md) — the field access underneath. - [`Symbol!`](./symbol.md) — the type-level field name a wiring entry supplies. - [`WithProvider`](../providers/with_provider.md) — the adapter for a value that does not come from a field. diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 145c32e7..71f37efd 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -181,7 +181,7 @@ let an idiomatic provider state what it needs. occurrences to fully qualified form. - [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound in a higher-order provider. -- [`#[default_impl(...)]`](../traits/default_namespace.md) registers the provider as a namespace's +- [`#[default_impl(...)]`](../traits/namespace/default_namespace.md) registers the provider as a namespace's per-type default, emitting a delegation impl alongside it, for use with [`cgp_namespace!`](./cgp_namespace.md). @@ -422,7 +422,7 @@ apply to. Leave both out. - [`check_components!`](./check_components.md) — verifies the wiring resolves. - [`#[implicit]`](../attributes/implicit.md), [`#[uses]`](../attributes/uses.md), [`#[use_type]`](../attributes/use_type.md), [`#[use_provider]`](../attributes/use_provider.md), - [`#[default_impl]`](../traits/default_namespace.md) — the companion attributes. + [`#[default_impl]`](../traits/namespace/default_namespace.md) — the companion attributes. The ideas behind it: diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index e038d867..516f8061 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -406,10 +406,10 @@ the context. the shared table grammar. - [`Path!`](./path.md) — the `@`-path syntax namespace entries and `#[prefix]` use. - [`RedirectLookup`](../providers/redirect_lookup.md) — the provider every redirect resolves through. -- [`DefaultNamespace`](../traits/default_namespace.md) — inherited and per-type default resolution, +- [`DefaultNamespace`](../traits/namespace/default_namespace.md) — inherited and per-type default resolution, including `#[default_impl(...)]`. - [`#[cgp_component]`](./cgp_component.md) — the host of the `#[prefix(...)]` attribute. -- [`DelegateComponent`](../traits/delegate_component.md) — the per-key table a redirect finally walks. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) — the per-key table a redirect finally walks. - [`check_components!`](./check_components.md) — the only thing that catches a route bound to nothing. The ideas behind it: diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index a18fc921..a3136b12 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -155,7 +155,7 @@ impl<__Context__, __Code__> Producer<__Context__, __Code__> for MagicNumber { ``` [`#[cgp_new_provider]`](./cgp_provider.md) declares `pub struct MagicNumber;` and derives the -[`IsProviderFor`](../traits/is_provider_for.md) impl, whose parameter tuple here holds just the code tag. The +[`IsProviderFor`](../traits/wiring/is_provider_for.md) impl, whose parameter tuple here holds just the code tag. The context and code parameters carry the reserved names `__Context__` and `__Code__`. Then the wiring, which reaches **all eight** other components: diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index f6a6905c..1a8daabf 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -242,7 +242,7 @@ where The derived impl is your impl with the body and associated types removed and the trait swapped. It keeps the same generic parameters and the same bounds, so it holds under precisely the conditions the real impl holds. This is the whole point: a check evaluates -[`IsProviderFor`](../traits/is_provider_for.md) to find out *why* a provider does not apply. +[`IsProviderFor`](../traits/wiring/is_provider_for.md) to find out *why* a provider does not apply. The macro assembles its three trait arguments from the provider trait's own. The first is the **component** (`ComputerRefComponent`, the default derived from the trait name, or whatever the @@ -367,7 +367,7 @@ the consumer side is unaffected: a wired context reads `::L - [`#[cgp_impl]`](./cgp_impl.md) — the form to write, which desugars to these two. - [`#[cgp_component]`](./cgp_component.md) — defines the provider trait being implemented. -- [`IsProviderFor`](../traits/is_provider_for.md) — the marker trait the macro derives, and why. +- [`IsProviderFor`](../traits/wiring/is_provider_for.md) — the marker trait the macro derives, and why. - [`delegate_components!`](./delegate_components.md) — wires a provider onto a context. - [`check_components!`](./check_components.md) — evaluates the derived marker to report a missing dependency by name. diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index cea009ba..d36ab750 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -233,7 +233,7 @@ built-in component and any `#[cgp_type]` component you declare, instead of needi per component. Each generated provider impl is paired with a matching -[`IsProviderFor`](../traits/is_provider_for.md) impl carrying the same bounds, as everywhere else. +[`IsProviderFor`](../traits/wiring/is_provider_for.md) impl carrying the same bounds, as everywhere else. A bound that names the type it constrains is rewritten rather than refused. Declaring `type Scalar: Mul + Clone;` leaves the bound as written on the two traits, where diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index ab3428f6..05ab7f8b 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -36,7 +36,7 @@ cannot, at the wiring site rather than wherever the capability first gets called The second thing it buys is a *readable* failure, and that is the part worth understanding. Asking the obvious question, "does `Person` implement `CanGreet`?", makes the compiler report only the last link in the chain, typically that some provider does not implement its provider trait, with no word about why. The -macro instead routes the assertion through [`CanUseComponent`](../traits/can_use_component.md), which holds +macro instead routes the assertion through [`CanUseComponent`](../traits/wiring/can_use_component.md), which holds only when the context both delegates the component *and* the chosen provider's real bounds are satisfied. Because those bounds ride explicitly on a marker trait, the compiler evaluates them and names the one that failed. A missing `name` field surfaces as a missing `name` field, not as an opaque "trait not @@ -242,7 +242,7 @@ impl __CheckPerson for Person {} ``` The impl holds only if `Person: CanUseComponent`, which in turn requires that `Person` -delegates the component and that its delegate satisfies [`IsProviderFor`](../traits/is_provider_for.md) for +delegates the component and that its delegate satisfies [`IsProviderFor`](../traits/wiring/is_provider_for.md) for `Person`. That indirection is the entire point: because the marker carries the provider's real bounds, an unmet one is reported specifically rather than as a bare missing implementation. The generic parameters are literally `__Component__` and `__Params__` in the emitted code. @@ -376,10 +376,10 @@ provider was found and its dependencies are satisfiable, not that the provider d - [`delegate_components!`](./delegate_components.md) — the wiring this verifies. - [`delegate_and_check_components!`](./delegate_and_check_components.md) — wires and checks in one step, for simple tables. -- [`CanUseComponent`](../traits/can_use_component.md) — the assertion the default form makes. -- [`IsProviderFor`](../traits/is_provider_for.md) — what `#[check_providers]` asserts, and what carries a +- [`CanUseComponent`](../traits/wiring/can_use_component.md) — the assertion the default form makes. +- [`IsProviderFor`](../traits/wiring/is_provider_for.md) — what `#[check_providers]` asserts, and what carries a provider's real bounds. -- [`DelegateComponent`](../traits/delegate_component.md) — the lazily-accepted table entry that makes a check +- [`DelegateComponent`](../traits/wiring/delegate_component.md) — the lazily-accepted table entry that makes a check necessary. - [`#[cgp_component]`](./cgp_component.md) — defines the components a table names. - [`#[use_provider]`](../attributes/use_provider.md) — builds the nested stacks `#[check_providers]` exists diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index db9021d6..fdf6ea89 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -270,8 +270,8 @@ delegate_and_check_components! { } ``` -the wiring half is a [`DelegateComponent`](../traits/delegate_component.md) impl plus an -[`IsProviderFor`](../traits/is_provider_for.md) forwarding impl per entry: +the wiring half is a [`DelegateComponent`](../traits/wiring/delegate_component.md) impl plus an +[`IsProviderFor`](../traits/wiring/is_provider_for.md) forwarding impl per entry: ```rust impl DelegateComponent for MyContext { @@ -285,7 +285,7 @@ where ``` and the same pair again for `NameGetterComponent`. Then comes the checking half: a marker trait aliasing -[`CanUseComponent`](../traits/can_use_component.md), with one empty impl per delegated component: +[`CanUseComponent`](../traits/wiring/can_use_component.md), with one empty impl per delegated component: ```rust trait CheckMyContext<__Component__, __Params__: ?Sized>: @@ -390,9 +390,9 @@ derivation only produces checks for entries keyed on a component name, so a tabl - [`delegate_components!`](./delegate_components.md) — the wiring half, and what to use alone for a bundle. - [`check_components!`](./check_components.md) — the checking half, and the form to use once wiring grows. -- [`CanUseComponent`](../traits/can_use_component.md) — the assertion the derived check makes. -- [`DelegateComponent`](../traits/delegate_component.md) and - [`IsProviderFor`](../traits/is_provider_for.md) — the impls each entry expands into. +- [`CanUseComponent`](../traits/wiring/can_use_component.md) — the assertion the derived check makes. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) and + [`IsProviderFor`](../traits/wiring/is_provider_for.md) — the impls each entry expands into. - [`#[cgp_component]`](./cgp_component.md) — defines the components a table wires. - [`cgp_namespace!`](./cgp_namespace.md) — inherited wiring, which the derivation does not cover. - [`UseField`](../providers/use_field.md) and [`UseType`](../providers/use_type.md) — the providers the diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 49651fc6..4b307baf 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -444,7 +444,7 @@ with how complicated the wiring is; that it is checked somehow does not. ## Under the hood Each entry becomes a pair of impls. From the single-entry table above, first the -[`DelegateComponent`](../traits/delegate_component.md) impl that records the choice: +[`DelegateComponent`](../traits/wiring/delegate_component.md) impl that records the choice: ```rust impl DelegateComponent for Rectangle { @@ -457,7 +457,7 @@ That impl alone is the whole lookup. The provider blanket impl generated by from `RectangleArea`, and the consumer blanket impl then gives `Rectangle` the `CanCalculateArea` trait. The hand-written equivalent of one wiring entry is exactly that block. -Second, the [`IsProviderFor`](../traits/is_provider_for.md) impl that forwards the provider's +Second, the [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl that forwards the provider's requirements: ```rust @@ -688,8 +688,8 @@ joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#common- - [`check_components!`](./check_components.md) — asserts the table is complete and resolvable. - [`delegate_and_check_components!`](./delegate_and_check_components.md) — wires and checks together, for the plain entries. -- [`DelegateComponent`](../traits/delegate_component.md) and - [`IsProviderFor`](../traits/is_provider_for.md) — the traits each entry expands into. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) and + [`IsProviderFor`](../traits/wiring/is_provider_for.md) — the traits each entry expands into. - [`RedirectLookup`](../providers/redirect_lookup.md) — what `open` and `=>` resolve through. - [`Path!`](./path.md) — the path syntax behind `@`-keys and `=>` values. - [`UseDelegate`](../providers/use_delegate.md) — the legacy dispatch form `open` supersedes. diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index d7492048..e02c2f47 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -221,7 +221,7 @@ the check rather than at the definition. - [`Symbol!`](./symbol.md) — what a lowercase segment becomes. - [Type-level spines](../types/type_level_spines.md) — the `PathCons` chain the expansion builds. - [`Product!`](./product.md) and [`Sum!`](./sum.md) — the sibling construction macros, sharing the fold shape. -- [`DelegateComponent`](../traits/delegate_component.md) — the per-key table a resolved path finally reads. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) — the per-key table a resolved path finally reads. The ideas behind it: diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 823ddbc9..7cd06d16 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -21,7 +21,7 @@ Product![u32, String, bool] ``` That recursion makes structural, field-by-field operations possible at all. Because a struct's fields -are exposed as a single list type through [`HasFields`](../traits/has_fields.md), a provider can be written +are exposed as a single list type through [`HasFields`](../traits/shape/has_fields.md), a provider can be written once to walk, transform, or rebuild *any* struct's fields without naming the concrete struct, by recursing over the list. A plain tuple cannot be decomposed that way in generic code; the recursive list can. @@ -195,9 +195,9 @@ the order *is* the execution order. - [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` types the expansion builds. - [`Field`](../types/field.md) — what the entries usually are, pairing a name with a type. - [`Symbol!`](./symbol.md) — the name half of a `Field` entry. -- [`HasFields`](../traits/has_fields.md) — the trait that exposes a struct's shape as one of these lists. +- [`HasFields`](../traits/shape/has_fields.md) — the trait that exposes a struct's shape as one of these lists. - [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates that list for you. -- [`AppendProduct`](../traits/append_product.md) — the operations that combine and transform these lists. +- [`AppendProduct`](../traits/type-level/append_product.md) — the operations that combine and transform these lists. - [Handler combinators](../providers/handler/index.md) — where `Product!` is written by hand, as a pipeline. diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 092c5a66..b8b945c9 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -22,7 +22,7 @@ Sum![u32, String, bool] Like its dual it is built from a recursive spine, and that recursion makes variant-by-variant operations possible. Because an enum's variants are exposed as a single sum type through -[`HasFields`](../traits/has_fields.md), a provider can be written once to match on, dispatch over, or construct +[`HasFields`](../traits/shape/has_fields.md), a provider can be written once to match on, dispatch over, or construct *any* enum's variants without naming the concrete enum, by walking the nested branches. This is the basis for CGP's extensible-variant machinery, where each variant is handled by descending the chain rather than by writing a `match` against a fixed enum. @@ -169,12 +169,12 @@ struct: the variant's payload type has to be a single nameable type for the sum - [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` types the expansion builds. - [`Field`](../types/field.md) — what the branches usually are, pairing a variant name with its payload. - [`Symbol!`](./symbol.md) — the name half of a branch. -- [`HasFields`](../traits/has_fields.md) — the trait exposing an enum's shape as one of these sums. +- [`HasFields`](../traits/shape/has_fields.md) — the trait exposing an enum's shape as one of these sums. - [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — the derive that generates it, with the variant machinery. -- [`FromVariant`](../traits/from_variant.md) and [`ExtractField`](../traits/extract_field.md) — constructing and +- [`FromVariant`](../traits/variant/from_variant.md) and [`ExtractField`](../traits/variant/extract_field.md) — constructing and taking apart a variant generically. -- [`CanUpcast`](../traits/can_upcast.md) — converting between two enums that share variants. +- [`CanUpcast`](../traits/casting/can_upcast.md) — converting between two enums that share variants. The ideas behind it: diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 8b4e3677..39b5872d 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -10,7 +10,7 @@ A type-level string, used as a field-name tag. ## Overview CGP needs field *names* to be types. Reading a field goes through -[`HasField`](../traits/has_field.md), where `Tag` identifies which field is meant. So to look up a field +[`HasField`](../traits/field-access/has_field.md), where `Tag` identifies which field is meant. So to look up a field called `name`, something has to stand in for the string `"name"` at the type level. `Symbol!("name")` is that something. It produces a distinct type whose whole identity is the characters it @@ -133,7 +133,7 @@ That is the honest summary: the construct is essential and mostly generated. Two things it is not. It is **not a runtime string**: there is no `&str` inside it, and the `Display` impl above reconstructs the text from the type rather than reading a stored value. And it is **not a general type-level string facility** to build programs out of; it exists to key field and variant lookups, and the -[`StaticFormat`](../traits/static_format.md) traits recover text from one when that is +[`StaticFormat`](../traits/formatting/static_format.md) traits recover text from one when that is needed. ## Under the hood @@ -209,7 +209,7 @@ type argument rather than the value. ## Related constructs - [`Index`](../types/index.md) — the position-keyed tag for tuple-struct fields. -- [`HasField`](../traits/has_field.md) — what a tag is looked up through. +- [`HasField`](../traits/field-access/has_field.md) — what a tag is looked up through. - [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates one tag per named field. - [`#[implicit]`](../attributes/implicit.md) — generates the tag from an argument name. - [`#[cgp_auto_getter]`](./cgp_auto_getter.md) — generates it from a method name. @@ -217,7 +217,7 @@ type argument rather than the value. - [Type-level spines](../types/type_level_spines.md) — the `Chars`/`Nil` chain the expansion builds. - [`Product!`](./product.md) and [`Sum!`](./sum.md) — the record and variant lists whose entries carry these tags. -- [`StaticFormat`](../traits/static_format.md) — recovering runtime text from a type-level string. +- [`StaticFormat`](../traits/formatting/static_format.md) — recovering runtime text from a type-level string. The ideas behind it: diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 341feca7..4a0ef5fd 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -18,7 +18,7 @@ getter to the nesting. `ChainGetters` takes a list of getters, applies threads the reference from each step into the next, so the chain reads like the path it traverses: outer getter, then the next, ending at the target field. -`ChainGetters` is a foundational [`FieldGetter`](../traits/field_getter.md), so it is wired to a getter +`ChainGetters` is a foundational [`FieldGetter`](../traits/field-access/field_getter.md), so it is wired to a getter component through the [`WithProvider`](with_provider.md) adapter rather than named on its own. The list is a type-level [`Cons`](../types/type_level_spines.md) spine whose elements are each a field getter for the value the previous step produced, written with the [`Product!`](../macros/product.md) macro. @@ -109,7 +109,7 @@ only once the value is more than one hop away. ## Under the hood -`ChainGetters` implements the provider-side getter [`FieldGetter`](../traits/field_getter.md) with two +`ChainGetters` implements the provider-side getter [`FieldGetter`](../traits/field-access/field_getter.md) with two impls that together recurse over the list, one for a non-empty `Cons` and one for the empty `Nil`. The `Cons` impl applies the head getter, then delegates the rest of the path to `ChainGetters` over the tail: @@ -133,7 +133,7 @@ where The head `Getter` reads `ValueA` from the `Context`, and the rest of the chain reads `ValueB` from that `ValueA`, so the whole chain's `Value` is `ValueB`, the value at the end of the path. The head is -applied through [`FieldMapper`](../traits/field_mapper.md) rather than `FieldGetter` directly: +applied through [`FieldMapper`](../traits/field-access/field_mapper.md) rather than `FieldGetter` directly: `map_field` hands the intermediate reference to a closure that runs the rest of the chain on it, which keeps the borrowed lifetimes inferring across each hop. @@ -160,8 +160,8 @@ what turns it into a provider a getter component can be wired to. - [`WithProvider`](with_provider.md) — the adapter that turns `ChainGetters` into a getter-component provider. - [`UseField`](use_field.md) and [`UseFieldRef`](use_field_ref.md) — the getters that form each step of - the chain, implementing the same [`FieldGetter`](../traits/field_getter.md) it composes. -- [`FieldMapper`](../traits/field_mapper.md) — what each step is applied through, to keep borrowed + the chain, implementing the same [`FieldGetter`](../traits/field-access/field_getter.md) it composes. +- [`FieldMapper`](../traits/field-access/field_mapper.md) — what each step is applied through, to keep borrowed lifetimes inferring across hops. - [`Product!`](../macros/product.md) — builds the list of getters. - [`#[cgp_getter]`](../macros/cgp_getter.md) — defines the getter this is wired to. diff --git a/docs/reference/providers/dispatch/build_and_merge.md b/docs/reference/providers/dispatch/build_and_merge.md index 7441fa46..05317379 100644 --- a/docs/reference/providers/dispatch/build_and_merge.md +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -58,7 +58,7 @@ where ``` It runs `Provider` on a reference to the builder to produce a result record, then uses -[`CanBuildFrom`](../../traits/can_build_from.md) to copy every shared field into the builder. It +[`CanBuildFrom`](../../traits/casting/can_build_from.md) to copy every shared field into the builder. It implements `Computer`, `TryComputer`, and `Handler`; the fallible and async forms require the context to have an error type. @@ -68,7 +68,7 @@ have an error type. - [`BuildWithHandlers`](build_with_handlers.md) — the entry point that runs a list of these adapters. - [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — wraps a list of plain field-producing providers in `BuildAndMerge` automatically. -- [`CanBuildFrom`](../../traits/can_build_from.md) — the cast it uses to copy shared fields. +- [`CanBuildFrom`](../../traits/casting/can_build_from.md) — the cast it uses to copy shared fields. The ideas behind it: diff --git a/docs/reference/providers/dispatch/build_and_merge_outputs.md b/docs/reference/providers/dispatch/build_and_merge_outputs.md index f2decb4a..99ab50b9 100644 --- a/docs/reference/providers/dispatch/build_and_merge_outputs.md +++ b/docs/reference/providers/dispatch/build_and_merge_outputs.md @@ -52,7 +52,7 @@ table that maps the whole handler family (`ComputerComponent`, `TryComputerCompo `HandlerComponent`, and their `Ref` forms) to `BuildWithHandlers`, where each provider in `Handlers` has first been wrapped in [`BuildAndMerge`](build_and_merge.md). The wrapping is done by mapping the list through the -`ToBuildAndMergeHandler` [`MapType`](../../traits/map_type.md) marker, so a caller supplies plain +`ToBuildAndMergeHandler` [`MapType`](../../traits/type-level/map_type.md) marker, so a caller supplies plain result-producing providers and each is merged into the builder automatically. ## Related constructs @@ -60,7 +60,7 @@ result-producing providers and each is merged into the builder automatically. - [`BuildWithHandlers`](build_with_handlers.md) — the entry point this wraps, for a list of builder adapters directly. - [`BuildAndMerge`](build_and_merge.md) — the merge step each provider in the list is wrapped in. -- [`MapType`](../../traits/map_type.md) — the trait the list-mapping marker implements. +- [`MapType`](../../traits/type-level/map_type.md) — the trait the list-mapping marker implements. The ideas behind it: diff --git a/docs/reference/providers/dispatch/build_and_set_field.md b/docs/reference/providers/dispatch/build_and_set_field.md index 688e9228..ccb59dd3 100644 --- a/docs/reference/providers/dispatch/build_and_set_field.md +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -56,7 +56,7 @@ where ``` It runs `Provider` on a reference to the builder to compute the value, then calls -[`BuildField`](../../traits/build_field.md) to set it. It implements `Computer`, `TryComputer`, and +[`BuildField`](../../traits/builder/build_field.md) to set it. It implements `Computer`, `TryComputer`, and `Handler`; the fallible and async forms require the context to have an error type and propagate the provider's error. @@ -65,7 +65,7 @@ provider's error. - [`BuildAndMerge`](build_and_merge.md) — the bulk counterpart, copying a whole record's fields at once. - [`BuildWithHandlers`](build_with_handlers.md) — the entry point that runs a list of these adapters and finalizes. -- [`BuildField`](../../traits/build_field.md) — the trait it drives to set a field. +- [`BuildField`](../../traits/builder/build_field.md) — the trait it drives to set a field. - [`UseContext`](../use_context.md) — the default provider. The ideas behind it: diff --git a/docs/reference/providers/dispatch/build_with_handlers.md b/docs/reference/providers/dispatch/build_with_handlers.md index d1d1993c..f6669265 100644 --- a/docs/reference/providers/dispatch/build_with_handlers.md +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -65,9 +65,9 @@ where } ``` -It obtains an empty builder from [`HasBuilder`](../../traits/has_builder.md), threads it through the list +It obtains an empty builder from [`HasBuilder`](../../traits/builder/has_builder.md), threads it through the list with [`PipeHandlers`](../handler/pipe_handlers.md) so each adapter sets its field, and calls -[`FinalizeBuild`](../../traits/finalize_build.md) to recover the concrete `Output`. The original `Input` +[`FinalizeBuild`](../../traits/builder/finalize_build.md) to recover the concrete `Output`. The original `Input` is discarded; the output is produced from the builder. It implements `Computer`, `TryComputer`, and `Handler`, the latter two requiring the context to have an error type. Because `finalize_build` is in scope only for the all-present builder configuration, a missing field is caught at compile time. @@ -79,7 +79,7 @@ scope only for the all-present builder configuration, a missing field is caught - [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — the higher-level wrapper for a list of plain field-producing providers. - [`PipeHandlers`](../handler/pipe_handlers.md) — the pipeline it threads the builder through. -- [`HasBuilder`](../../traits/has_builder.md), [`FinalizeBuild`](../../traits/finalize_build.md) — the +- [`HasBuilder`](../../traits/builder/has_builder.md), [`FinalizeBuild`](../../traits/builder/finalize_build.md) — the traits that start and finish the build. The ideas behind it: diff --git a/docs/reference/providers/dispatch/downcast_and_handle.md b/docs/reference/providers/dispatch/downcast_and_handle.md index 8b7a1a5e..b2e2748a 100644 --- a/docs/reference/providers/dispatch/downcast_and_handle.md +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -49,7 +49,7 @@ pub struct DowncastAndHandle(pub PhantomData<(Inpu ``` Its `Output` is `Result`. It uses -[`CanDowncastFields`](../../traits/can_downcast_fields.md) to try to narrow the input to `Inner`; +[`CanDowncastFields`](../../traits/casting/can_downcast_fields.md) to try to narrow the input to `Inner`; on success it hands the whole `Inner` value to `Provider` and returns `Ok`, and on failure it returns `Err` of the remainder. It implements both `Computer` and `AsyncComputer`. @@ -58,7 +58,7 @@ on success it hands the whole `Inner` value to `Provider` and returns `Ok`, and - [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the single-variant adapter this generalizes to a group. - [`MatchWithHandlers`](match_with_handlers.md) — the matcher that consumes a list mixing both. -- [`CanDowncastFields`](../../traits/can_downcast_fields.md) — the cast it uses to narrow the input. +- [`CanDowncastFields`](../../traits/casting/can_downcast_fields.md) — the cast it uses to narrow the input. - [`UseContext`](../use_context.md) — the default inner provider. The ideas behind it: diff --git a/docs/reference/providers/dispatch/extract_field_and_handle.md b/docs/reference/providers/dispatch/extract_field_and_handle.md index 8e661086..dba6022f 100644 --- a/docs/reference/providers/dispatch/extract_field_and_handle.md +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -61,7 +61,7 @@ pub struct ExtractFieldAndHandle(pub PhantomData<(Ta pub struct ExtractFirstFieldAndHandle(pub PhantomData<(Tag, Provider)>); ``` -Its `Output` is `Result`. It calls [`ExtractField`](../../traits/extract_field.md) +Its `Output` is `Result`. It calls [`ExtractField`](../../traits/variant/extract_field.md) on the input; on success it forwards a `Field` to `Provider` and returns `Ok`, and on failure it returns `Err` of the remainder, the extractor with that variant ruled out. It implements both `Computer` and `AsyncComputer`. @@ -73,7 +73,7 @@ failure it returns `Err` of the remainder, the extractor with that variant ruled - [`DowncastAndHandle`](downcast_and_handle.md) — the adapter that matches a group of variants at once instead of one. - [`MatchWithHandlers`](match_with_handlers.md) — the matcher that consumes a list of these adapters. -- [`ExtractField`](../../traits/extract_field.md) — the trait it drives, and +- [`ExtractField`](../../traits/variant/extract_field.md) — the trait it drives, and [`Field`](../../types/field.md) — the tagged payload it forwards. - [`UseContext`](../use_context.md) — the default inner provider. diff --git a/docs/reference/providers/dispatch/index.md b/docs/reference/providers/dispatch/index.md index 86420c6a..294e6a68 100644 --- a/docs/reference/providers/dispatch/index.md +++ b/docs/reference/providers/dispatch/index.md @@ -62,11 +62,11 @@ the hood on [`MatchWithHandlers`](match_with_handlers.md). - [`#[cgp_auto_dispatch]`](../../macros/cgp_auto_dispatch.md) — generates a matcher-backed handler impl automatically. -- [`extract_field`](../../traits/extract_field.md), [`has_extractor`](../../traits/has_extractor.md), - [`finalize_extract`](../../traits/finalize_extract.md) — the enum-deconstruction traits the matchers +- [`extract_field`](../../traits/variant/extract_field.md), [`has_extractor`](../../traits/variant/has_extractor.md), + [`finalize_extract`](../../traits/variant/finalize_extract.md) — the enum-deconstruction traits the matchers stand on. -- [`has_builder`](../../traits/has_builder.md), [`build_field`](../../traits/build_field.md), - [`finalize_build`](../../traits/finalize_build.md) — the record-assembly traits the builders stand on. +- [`has_builder`](../../traits/builder/has_builder.md), [`build_field`](../../traits/builder/build_field.md), + [`finalize_build`](../../traits/builder/finalize_build.md) — the record-assembly traits the builders stand on. - [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher the convenience matchers use. - [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — the derive that gives a type the shape these diff --git a/docs/reference/providers/dispatch/match_first_with_handlers.md b/docs/reference/providers/dispatch/match_first_with_handlers.md index 26a88df6..e395ff8b 100644 --- a/docs/reference/providers/dispatch/match_first_with_handlers.md +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -91,7 +91,7 @@ The loop is the same `DispatchMatchers` alias described on [`HandleFirstFieldValue`](handle_field_value.md) — the first-argument adapters its list is built from. - [`MatchWithValueHandlers`](match_with_value_handlers.md) — the automatic form, whose `MatchFirstWithValueHandlers` sibling matches this convention. -- [`HasExtractor`](../../traits/has_extractor.md), [`FinalizeExtract`](../../traits/finalize_extract.md) +- [`HasExtractor`](../../traits/variant/has_extractor.md), [`FinalizeExtract`](../../traits/variant/finalize_extract.md) — the traits it stands on. The ideas behind it: diff --git a/docs/reference/providers/dispatch/match_with_field_handlers.md b/docs/reference/providers/dispatch/match_with_field_handlers.md index 220995e3..a0deeecc 100644 --- a/docs/reference/providers/dispatch/match_with_field_handlers.md +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -62,7 +62,7 @@ The per-variant list is built from a context's field list by three cooperating t is a type-level function from a field's `Tag` to the adapter that should handle it; `ToFieldHandlers` walks the [sum spine](../../types/type_level_spines.md) of a field list and applies that function to each field, producing a [`Product!`](../../macros/product.md) list of adapters; and `HasFieldHandlers` reads a -context's [`HasFields`](../../traits/has_fields.md) list and runs `ToFieldHandlers` over it: +context's [`HasFields`](../../traits/shape/has_fields.md) list and runs `ToFieldHandlers` over it: ```rust impl HasFieldHandlers for Context @@ -90,7 +90,7 @@ the matcher runs one extract adapter per variant without the user spelling out t - [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the per-variant adapter the list is built from. - [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher this alias is built on. -- [`HasFields`](../../traits/has_fields.md) — the field list the handler list is synthesized from. +- [`HasFields`](../../traits/shape/has_fields.md) — the field list the handler list is synthesized from. The ideas behind it: diff --git a/docs/reference/providers/dispatch/match_with_handlers.md b/docs/reference/providers/dispatch/match_with_handlers.md index 292cf388..f37706c8 100644 --- a/docs/reference/providers/dispatch/match_with_handlers.md +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -88,7 +88,7 @@ the value, use [`MatchFirstWithHandlers`](match_first_with_handlers.md). pub struct MatchWithHandlers(pub PhantomData); ``` -Its `Computer` impl requires the input to implement [`HasExtractor`](../../traits/has_extractor.md), runs +Its `Computer` impl requires the input to implement [`HasExtractor`](../../traits/variant/has_extractor.md), runs the shared matcher loop over `Input::Extractor` to obtain `Result`, and calls `finalize_extract_result` on that result so the uninhabited remainder is discharged: @@ -129,8 +129,8 @@ a user names. - [`ExtractFieldAndHandle`](extract_field_and_handle.md), [`HandleFieldValue`](handle_field_value.md) — the adapters the list is built from. - [`PipeMonadic`](../monad/pipe_monadic.md) — the `OkMonadic` pipeline the matcher loop is built on. -- [`HasExtractor`](../../traits/has_extractor.md), [`FinalizeExtract`](../../traits/finalize_extract.md), - [`FinalizeExtractResult`](../../traits/finalize_extract_result.md) — the traits it stands on. +- [`HasExtractor`](../../traits/variant/has_extractor.md), [`FinalizeExtract`](../../traits/variant/finalize_extract.md), + [`FinalizeExtractResult`](../../traits/variant/finalize_extract_result.md) — the traits it stands on. The ideas behind it: diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index 6ef6a1be..835e9e29 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -64,7 +64,7 @@ generated uniformly from the field list. `MatchWithValueHandlers` is a type alias over [`UseInputDelegate`](../handler/use_input_delegate.md) that dispatches on the input type and, for each -input, synthesizes the per-variant handler list from that input's [`HasFields`](../../traits/has_fields.md): +input, synthesizes the per-variant handler list from that input's [`HasFields`](../../traits/shape/has_fields.md): ```rust pub type MatchWithValueHandlers = @@ -86,7 +86,7 @@ so one struct serves both the by-value-of-reference and the by-reference interfa - [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher this alias is built on. - [`HandleFieldValue`](handle_field_value.md), [`UseContext`](../use_context.md) — the wrapper it adds and the default per-variant provider. -- [`HasFields`](../../traits/has_fields.md) — the field list the handler list is synthesized from. +- [`HasFields`](../../traits/shape/has_fields.md) — the field list the handler list is synthesized from. The ideas behind it: diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index 3844e3ee..178c8981 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -87,7 +87,7 @@ where Both bounds require the context to already handle the `String` case, which is the indirection that reduces any `Debug` source to the one case the context knows. Each impl is paired with a matching -[`IsProviderFor`](../../traits/is_provider_for.md) impl. +[`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl. ## Related constructs diff --git a/docs/reference/providers/error/discard_detail.md b/docs/reference/providers/error/discard_detail.md index 48a1dd47..e660500c 100644 --- a/docs/reference/providers/error/discard_detail.md +++ b/docs/reference/providers/error/discard_detail.md @@ -61,7 +61,7 @@ where ``` The detail is bound only so the method can accept it; the body returns the error untouched. The -generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same `HasErrorType` bound. +generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same `HasErrorType` bound. ## Related constructs diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md index 8e0b144b..005e690b 100644 --- a/docs/reference/providers/error/display_error.md +++ b/docs/reference/providers/error/display_error.md @@ -80,7 +80,7 @@ where ``` Both bounds require the context to already handle `String`. Each impl is paired with a matching -[`IsProviderFor`](../../traits/is_provider_for.md) impl. +[`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl. ## Related constructs diff --git a/docs/reference/providers/error/panic_on_error.md b/docs/reference/providers/error/panic_on_error.md index 8efbbb3f..a3b2968d 100644 --- a/docs/reference/providers/error/panic_on_error.md +++ b/docs/reference/providers/error/panic_on_error.md @@ -62,7 +62,7 @@ where ``` The return type is `Context::Error`, but `panic!` diverges, so the body never produces one. The -generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same bounds. +generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same bounds. ## Related constructs diff --git a/docs/reference/providers/error/raise_from.md b/docs/reference/providers/error/raise_from.md index 5f7fd279..2d783a44 100644 --- a/docs/reference/providers/error/raise_from.md +++ b/docs/reference/providers/error/raise_from.md @@ -88,7 +88,7 @@ where ``` The bound `Context::Error: From` makes one wiring cover many source types. The generated -[`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same clause, so a +[`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same clause, so a [check](../../macros/check_components.md) reports a missing `From` impl at the wiring site. ## Related constructs diff --git a/docs/reference/providers/error/raise_infallible.md b/docs/reference/providers/error/raise_infallible.md index 1af050b1..45143734 100644 --- a/docs/reference/providers/error/raise_infallible.md +++ b/docs/reference/providers/error/raise_infallible.md @@ -65,7 +65,7 @@ where ``` Because an `Infallible` value cannot be constructed, the empty `match` is total and the function has no -reachable body. The generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same +reachable body. The generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same `HasErrorType` bound. ## Related constructs diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md index 6fc020d3..dc5c8d38 100644 --- a/docs/reference/providers/error/return_error.md +++ b/docs/reference/providers/error/return_error.md @@ -79,7 +79,7 @@ where ``` The `HasErrorType` bound ties the source type to the abstract error, so `raise_error` returns -its argument. The generated [`IsProviderFor`](../../traits/is_provider_for.md) impl carries the same +its argument. The generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same bound. ## Related constructs diff --git a/docs/reference/providers/handler/use_input_delegate.md b/docs/reference/providers/handler/use_input_delegate.md index dbe7625c..d1898c4d 100644 --- a/docs/reference/providers/handler/use_input_delegate.md +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -105,7 +105,7 @@ shape is generated for every handler family member. - [`delegate_components!`](../../macros/delegate_components.md) — wires it through a nested table. - [Dispatch combinators](../dispatch/index.md) — the main users of input dispatch, selecting a per-variant handler by payload type. -- [`DelegateComponent`](../../traits/delegate_component.md) — the table the lookup reads. +- [`DelegateComponent`](../../traits/wiring/delegate_component.md) — the table the lookup reads. The ideas behind it: diff --git a/docs/reference/providers/monad/bind_err.md b/docs/reference/providers/monad/bind_err.md index 486c13e3..5c30e89a 100644 --- a/docs/reference/providers/monad/bind_err.md +++ b/docs/reference/providers/monad/bind_err.md @@ -62,7 +62,7 @@ through it. - The [monad markers](index.md#the-monad-markers) — `ErrMonadic` is the marker `BindErr` implements the bind for. - [`PipeHandlers`](../handler/pipe_handlers.md) — where a hand-built bind step is placed. -- [`ContainsValue`](../../traits/contains_value.md), [`LiftValue`](../../traits/lift_value.md) — the +- [`ContainsValue`](../../traits/monad/contains_value.md), [`LiftValue`](../../traits/monad/lift_value.md) — the traits it uses to inspect and lift a step's value. The ideas behind it: diff --git a/docs/reference/providers/monad/bind_ok.md b/docs/reference/providers/monad/bind_ok.md index d7340404..453ed29a 100644 --- a/docs/reference/providers/monad/bind_ok.md +++ b/docs/reference/providers/monad/bind_ok.md @@ -62,7 +62,7 @@ short-circuits, lifting the value directly to the output and skipping `Cont`. It - The [monad markers](index.md#the-monad-markers) — `OkMonadic` is the marker `BindOk` implements the bind for. - [`PipeHandlers`](../handler/pipe_handlers.md) — where a hand-built bind step is placed. -- [`ContainsValue`](../../traits/contains_value.md), [`LiftValue`](../../traits/lift_value.md) — the +- [`ContainsValue`](../../traits/monad/contains_value.md), [`LiftValue`](../../traits/monad/lift_value.md) — the traits it uses to inspect and lift a step's value. The ideas behind it: diff --git a/docs/reference/providers/monad/index.md b/docs/reference/providers/monad/index.md index 25a6c20a..f6360455 100644 --- a/docs/reference/providers/monad/index.md +++ b/docs/reference/providers/monad/index.md @@ -50,7 +50,7 @@ on top of a base monad `M`, so monads can stack over nested result types. Writin inner `Result` through the err monad beneath it. A single layer of branching needs no explicit transformer, because the bare markers produce their own transformer form over `IdentMonadic` when used as transformers. The trait layer that gives a marker its meaning is documented under -[`MonadicBind`](../../traits/monadic_bind.md) and [`MonadicTrans`](../../traits/monadic_trans.md). +[`MonadicBind`](../../traits/monad/monadic_bind.md) and [`MonadicTrans`](../../traits/monad/monadic_trans.md). ## Related constructs @@ -58,8 +58,8 @@ as transformers. The trait layer that gives a marker its meaning is documented u - [`BindOk`](bind_ok.md), [`BindErr`](bind_err.md) — the per-step bind providers. - [`PipeHandlers`](../handler/pipe_handlers.md) — non-monadic composition, which `PipeMonadic` reduces to. -- [`MonadicBind`](../../traits/monadic_bind.md), [`MonadicTrans`](../../traits/monadic_trans.md), - [`ContainsValue`](../../traits/contains_value.md), [`LiftValue`](../../traits/lift_value.md) — the +- [`MonadicBind`](../../traits/monad/monadic_bind.md), [`MonadicTrans`](../../traits/monad/monadic_trans.md), + [`ContainsValue`](../../traits/monad/contains_value.md), [`LiftValue`](../../traits/monad/lift_value.md) — the four traits a marker implements. - [`Product!`](../../macros/product.md) — the type-level list a pipeline's steps are given in. diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index 9542ae3d..f52d7a03 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -82,7 +82,7 @@ bound, through the monad, to the monadically-composed rest of the list. For the fallible components `TryComputerComponent` and `HandlerComponent`, it bridges through the err monad. It first maps every provider to [`TryPromote`](../handler/try_promote.md), demoting fallible handlers to plain computers whose output is an explicit `Result`; the mapper that rewrites the whole list -is `TryPromoteProviders`, which implements [`MapType`](../../traits/map_type.md). It then applies +is `TryPromoteProviders`, which implements [`MapType`](../../traits/type-level/map_type.md). It then applies `ErrMonadic` as a transformer on top of `M`, composes the demoted list under the transformed monad, and wraps the composed provider back in `TryPromote` to restore the fallible interface. A `PipeMonadic` over fallible handlers therefore short-circuits on the context's error type in addition to whatever branching @@ -97,7 +97,7 @@ structure. - [`PipeHandlers`](../handler/pipe_handlers.md) — the non-monadic pipeline this generalizes. - [`TryPromote`](../handler/try_promote.md) — the lift it uses to bridge fallible and infallible handlers. -- [`MonadicBind`](../../traits/monadic_bind.md), [`MonadicTrans`](../../traits/monadic_trans.md) — the +- [`MonadicBind`](../../traits/monad/monadic_bind.md), [`MonadicTrans`](../../traits/monad/monadic_trans.md) — the traits it bounds on while folding. - [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family a pipeline implements. diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index a938749c..414a0b49 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -131,13 +131,13 @@ where } ``` -The mechanism is one [`DelegateComponent`](../traits/delegate_component.md) lookup keyed on `__Path__` +The mechanism is one [`DelegateComponent`](../traits/wiring/delegate_component.md) lookup keyed on `__Path__` rather than on the component marker. `RedirectLookup` implements `Greeter` whenever `Components` maps `Path` to a delegate that itself implements `Greeter`, and the method forwards to that delegate. When the consumer trait carries generic type parameters, the impl additionally constrains -`Path` with [`ConcatPath`](../traits/concat_path.md) so the parameters are appended to the path before +`Path` with [`ConcatPath`](../traits/formatting/concat_path.md) so the parameters are appended to the path before the lookup, letting the redirected key encode the generic arguments. As always, the impl is paired with a matching -[`IsProviderFor`](../traits/is_provider_for.md) impl. +[`IsProviderFor`](../traits/wiring/is_provider_for.md) impl. The `#[prefix(@path in Namespace)]` attribute populates the path side: it generates a namespace impl whose delegate is `RedirectLookup`, with the prefix path joined onto the @@ -152,7 +152,7 @@ table. target `RedirectLookup`. - [`delegate_components!`](../macros/delegate_components.md) — the `open` and `namespace` statements that generate the redirect entries. -- [`DelegateComponent`](../traits/delegate_component.md) — the table the lookup reads. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table the lookup reads. - [`Path!`](../macros/path.md) and [`PathCons`](../types/type_level_spines.md) — the type-level path it walks. - [`UseContext`](use_context.md) — the other `#[cgp_component]`-generated provider, routing back to the diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index 84604d5d..a0172f87 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -151,7 +151,7 @@ where ``` The provider method takes the context explicitly and calls the context's own `CanGreet::greet`. Each -`UseContext` impl is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl +`UseContext` impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl carrying the same `where` clause, so delegation propagates the dependency and a check reports a missing consumer-trait implementation precisely. Any supertrait bound on the consumer trait is reproduced in the `where` clause, so a context must satisfy it before `UseContext` can stand in as a provider. @@ -182,7 +182,7 @@ resolves `Encoder`, a different entry. - [Dispatch combinators](dispatch/index.md) — default their per-variant provider to `UseContext`. - [`delegate_components!`](../macros/delegate_components.md) — wires it, and its `open` statement dispatches a component per type as the example does. -- [`IsProviderFor`](../traits/is_provider_for.md) — carries the dependency `UseContext` propagates. +- [`IsProviderFor`](../traits/wiring/is_provider_for.md) — carries the dependency `UseContext` propagates. The ideas behind it: diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index 55aaf6c3..de748525 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -131,7 +131,7 @@ pub struct UseDefault; Meaning is given to it by the provider impl an author writes. An empty [`#[cgp_impl(UseDefault)]`](../macros/cgp_impl.md) block emits a provider-trait implementation with no method bodies, so each method falls back to the default defined on the consumer trait, plus the -matching [`IsProviderFor`](../traits/is_provider_for.md) implementation carrying the block's `where` +matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) implementation carrying the block's `where` clause. That is the same pair any `#[cgp_impl]` produces; the only thing special about `UseDefault` is the empty body and the shared, conventional name. @@ -143,7 +143,7 @@ the empty body and the shared, conventional name. [`check_components!`](../macros/check_components.md) verifies its dependencies. - [`UseContext`](use_context.md) and [`UseFields`](use_fields.md) — the providers that carry macro-generated behavior rather than relying on author-written empty bodies. -- [`IsProviderFor`](../traits/is_provider_for.md) — tracks the dependencies of a `UseDefault` impl. +- [`IsProviderFor`](../traits/wiring/is_provider_for.md) — tracks the dependencies of a `UseDefault` impl. The ideas behind it: diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 0588d1d0..ef9e47c3 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -146,11 +146,11 @@ where } ``` -The mechanism is a single [`DelegateComponent`](../traits/delegate_component.md) lookup keyed on +The mechanism is a single [`DelegateComponent`](../traits/wiring/delegate_component.md) lookup keyed on `SourceError`. `UseDelegate` implements `ErrorRaiser` for a given `SourceError` exactly when `Components` maps that `SourceError` to a delegate that itself implements `ErrorRaiser`, and the method forwards to it. Only the parameter named inside `UseDelegate<...>` is the key; the rest pass through -unchanged. Each impl is paired with an [`IsProviderFor`](../traits/is_provider_for.md) impl so +unchanged. Each impl is paired with an [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl so dependencies propagate to a check. A component may derive more than one dispatcher when different parameters should be routed differently. @@ -162,8 +162,8 @@ parameters should be routed differently. and carries the `open` statement that replaces it. - [`RedirectLookup`](redirect_lookup.md) — the mechanism `open` rides instead. - [`UseInputDelegate`](handler/use_input_delegate.md) — the sibling that keys on a handler's `Input` type. -- [`DelegateComponent`](../traits/delegate_component.md) — the table the lookup reads. -- [`IsProviderFor`](../traits/is_provider_for.md) — propagates the dispatched provider's dependencies. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table the lookup reads. +- [`IsProviderFor`](../traits/wiring/is_provider_for.md) — propagates the dispatched provider's dependencies. The ideas behind it: diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index b109abf4..3ba2d32f 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -22,7 +22,7 @@ The mechanism is the same indirection [`UseDelegate`](use_delegate.md) provides components, lifted to the type level. Where `UseDelegate` dispatches a *method call* to whichever provider `Components` maps the active tag to, `UseDelegatedType` dispatches a *type resolution* to whichever concrete type `Components` maps the tag to. Both read an entry out of a -[`DelegateComponent`](../traits/delegate_component.md) table keyed by the tag, but one yields behavior +[`DelegateComponent`](../traits/wiring/delegate_component.md) table keyed by the tag, but one yields behavior and the other yields a type. Like every CGP provider, it carries no runtime value. ## Usage @@ -68,7 +68,7 @@ reports the single type `T`: `UseDelegatedType` adds exactly one level of indire - [`UseType`](use_type.md) — the simpler sibling that fixes an abstract type to one concrete type. - [`UseDelegate`](use_delegate.md) — the behavioral counterpart that dispatches a method call through the same kind of table. -- [`DelegateComponent`](../traits/delegate_component.md) — the table it reads. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table it reads. - [`HasType` / `TypeProvider`](../components/has_type.md) — the abstract-type component it answers for. - [`WithDelegatedType`](with_delegated_type.md) — the alias you wire, and the home of the import and worked example. diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index 0018404e..e00d8abd 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -23,7 +23,7 @@ This is the provider that [`#[cgp_getter]`](../macros/cgp_getter.md) targets. Th `UseField` implementation for the getter's provider trait with the field tag left as a free parameter, so a context picks the field by writing `UseField` in its wiring table. `UseField` itself is the general provider underneath: it works for any tag the context's -[`HasField`](../traits/has_field.md) implementation supports. +[`HasField`](../traits/field-access/has_field.md) implementation supports. The `Tag` is usually a type-level string built with [`Symbol!`](../macros/symbol.md), such as `Symbol!("name")`, or a type-level integer wrapped in `Index` for a tuple field. These are the tags @@ -112,8 +112,8 @@ inside a nested context, use [`ChainGetters`](chain_getters.md). ## Under the hood `UseField` implements three provider traits, each forwarding to the context's -[`HasField`](../traits/has_field.md) implementation for `Tag`. The central one is the provider-side -getter [`FieldGetter`](../traits/field_getter.md), which reads the field by reference: +[`HasField`](../traits/field-access/has_field.md) implementation for `Tag`. The central one is the provider-side +getter [`FieldGetter`](../traits/field-access/field_getter.md), which reads the field by reference: ```rust impl FieldGetter for UseField @@ -134,11 +134,11 @@ and reads `Tag` from the context, which is the decoupling: the component's ident are independent. The associated `Value` comes from the context's `HasField` implementation, so the returned reference is to the real field. -`UseField` also implements the mutable getter [`MutFieldGetter`](../traits/mut_field_getter.md) +`UseField` also implements the mutable getter [`MutFieldGetter`](../traits/field-access/mut_field_getter.md) the same way, requiring `Context: HasFieldMut` and returning `&mut Value`. And it implements [`TypeProvider`](../components/has_type.md), reporting the field's `Value` type as an abstract type, so the *type* of a field can itself be wired as a context's abstract type. Each implementation is paired -with an [`IsProviderFor`](../traits/is_provider_for.md) implementation carrying the same `HasField` +with an [`IsProviderFor`](../traits/wiring/is_provider_for.md) implementation carrying the same `HasField` bound, so delegation propagates the dependency and a check reports a missing field precisely. ## Related constructs @@ -152,7 +152,7 @@ bound, so delegation propagates the dependency and a check reports a missing fie - [`WithField`](with_field.md) — the `WithProvider`-adapted alias that binds the same field. - [`WithProvider`](with_provider.md) — the adapter behind the `WithField` alias. - [`UseType`](use_type.md) — the abstract-type analogue for a `#[cgp_type]` component. -- [`HasField`](../traits/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the +- [`HasField`](../traits/field-access/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the consumer-side field access this reads, keyed by [`Symbol!`](../macros/symbol.md) or `Index`. - [`delegate_components!`](../macros/delegate_components.md) — wires it, and [`check_components!`](../macros/check_components.md) verifies the field is present. diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index 7bd984c8..fbb06da9 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -16,7 +16,7 @@ stored field type implements `AsRef`. It exists for a getter whose return *through* a field rather than being the field's own type: a `&Config` from a stored `Arc`, for example, where the field is not a `Config` but can be borrowed as one. -`UseFieldRef` is a foundational [`FieldGetter`](../traits/field_getter.md) rather than a getter +`UseFieldRef` is a foundational [`FieldGetter`](../traits/field-access/field_getter.md) rather than a getter component's own provider, so it is wired through its [`WithFieldRef`](with_field_ref.md) alias, `WithProvider>`. That distinguishes it from [`UseField`](use_field.md), which [`#[cgp_getter]`](../macros/cgp_getter.md) generates a getter-component implementation for directly. @@ -31,7 +31,7 @@ borrowed as. Like every CGP provider, it carries no runtime value. ## Usage -`UseFieldRef` supplies only the foundational [`FieldGetter`](../traits/field_getter.md), so it is wired +`UseFieldRef` supplies only the foundational [`FieldGetter`](../traits/field-access/field_getter.md), so it is wired through its [`WithFieldRef`](with_field_ref.md) alias rather than named directly. See [`WithFieldRef`](with_field_ref.md) for the import, the wiring form, and a worked example; the mechanism those rest on is described under [Under the hood](#under-the-hood) below. @@ -46,7 +46,7 @@ a borrowed-view getter needs it — rather than the plain [`UseField`](use_field ## Under the hood `UseFieldRef` implements the provider-side getter -[`FieldGetter`](../traits/field_getter.md) by reading the field at `Tag` and dereferencing it to +[`FieldGetter`](../traits/field-access/field_getter.md) by reading the field at `Tag` and dereferencing it to `&Value`: ```rust @@ -68,7 +68,7 @@ The `where` clause carries the defining constraint: the context's field at `Tag` is read at `Tag`. The body reads the field and calls `as_ref()`. The `'static` bound on the field type lets Rust infer the borrow's lifetime through the `AsRef` call. -`UseFieldRef` also implements the mutable getter [`MutFieldGetter`](../traits/mut_field_getter.md), +`UseFieldRef` also implements the mutable getter [`MutFieldGetter`](../traits/field-access/mut_field_getter.md), requiring the field type to implement both `AsRef` and `AsMut` and returning `&mut Value` through `as_mut()`. Because these are `FieldGetter` implementations rather than a getter component's own provider trait, the [`WithProvider`](with_provider.md) adapter behind `WithFieldRef` turns @@ -86,8 +86,8 @@ access rather than abstract-type resolution. `UseFieldRef` into a getter-component provider. - [`ChainGetters`](chain_getters.md) — another foundational `FieldGetter`, composed for nested contexts. - [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that defines the getter this is wired to. -- [`FieldGetter`](../traits/field_getter.md) and [`MutFieldGetter`](../traits/mut_field_getter.md) — the - provider-side getters it implements, over [`HasField`](../traits/has_field.md). +- [`FieldGetter`](../traits/field-access/field_getter.md) and [`MutFieldGetter`](../traits/field-access/mut_field_getter.md) — the + provider-side getters it implements, over [`HasField`](../traits/field-access/has_field.md). The ideas behind it: diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 8b47f241..3151f7b1 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -16,7 +16,7 @@ component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes one The context is the type the capability runs against, and it supplies those values as its own fields. `UseFields` is the provider that realizes the arrangement: wiring a getter to `UseFields` makes every method read the context field whose name equals the method name, looked up through -[`HasField`](../traits/has_field.md) keyed by a [`Symbol!`](../macros/symbol.md). +[`HasField`](../traits/field-access/has_field.md) keyed by a [`Symbol!`](../macros/symbol.md). This is the provider analogue of the blanket implementation that [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) emits. `#[cgp_auto_getter]` produces a single @@ -127,7 +127,7 @@ Each method becomes a `HasField` bound keyed on the method name as a `Symbol!`, field. The `&str` return makes the field `Value` a `String` and appends `.as_str()`, the same shorthand [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) uses. When a getter has several methods, the implementation carries one `HasField` bound and one body per method, each keyed by its own name. The -implementation is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md), so a check +implementation is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md), so a check reports a missing field precisely. This is one of three provider implementations `#[cgp_getter]` generates for a getter component. The @@ -142,7 +142,7 @@ them at wiring time. for a getter that need not be wired. - [`UseField`](use_field.md) — the sibling that keys on a wiring-chosen tag instead of the method name. - [`WithProvider`](with_provider.md) — the third getter provider `#[cgp_getter]` emits. -- [`HasField`](../traits/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the +- [`HasField`](../traits/field-access/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the field access it reads, keyed by [`Symbol!`](../macros/symbol.md) on the method name. The ideas behind it: diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md index b9da17f7..56e59108 100644 --- a/docs/reference/providers/with_context.md +++ b/docs/reference/providers/with_context.md @@ -11,7 +11,7 @@ The `WithProvider`-adapted spelling of `UseContext`, defined for completeness of `WithContext` is the alias `WithProvider`. It pairs the [`WithProvider`](with_provider.md) adapter with [`UseContext`](use_context.md) on a **context**, the type a capability runs against. -[`UseContext`](use_context.md) carries a foundational [`FieldGetter`](../traits/field_getter.md), and +[`UseContext`](use_context.md) carries a foundational [`FieldGetter`](../traits/field-access/field_getter.md), and [`WithProvider`](with_provider.md) adapts a foundational provider into a named component's provider, so `WithContext` is the two composed. Like every CGP provider, it carries no runtime value. @@ -52,7 +52,7 @@ pub type WithContext = WithProvider; The [`WithProvider`](with_provider.md) adapter forwards a component's provider-trait method to the inner provider's foundational method, and [`UseContext`](use_context.md) supplies that foundational method, -its [`FieldGetter`](../traits/field_getter.md) reading the context's `HasField`. The generated +its [`FieldGetter`](../traits/field-access/field_getter.md) reading the context's `HasField`. The generated `WithProvider` impl that makes this work is shown on the [`WithProvider`](with_provider.md) page. ## Related constructs @@ -64,7 +64,7 @@ its [`FieldGetter`](../traits/field_getter.md) reading the context's `HasField`. concrete type. - [`UseFields`](use_fields.md) — reads same-named fields on a getter component, one of the direct forms to prefer. -- [`FieldGetter`](../traits/field_getter.md) — the foundational getter `UseContext` supplies here. +- [`FieldGetter`](../traits/field-access/field_getter.md) — the foundational getter `UseContext` supplies here. The ideas behind it: diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md index 31dd56fe..3b93d315 100644 --- a/docs/reference/providers/with_delegated_type.md +++ b/docs/reference/providers/with_delegated_type.md @@ -104,7 +104,7 @@ pub type WithDelegatedType = WithProvider`](use_delegated_type.md) is the foundational [`TypeProvider`](../components/has_type.md) that resolves each tag through a -[`DelegateComponent`](../traits/delegate_component.md) lookup. The `UseDelegatedType` mechanism is +[`DelegateComponent`](../traits/wiring/delegate_component.md) lookup. The `UseDelegatedType` mechanism is documented on the [`UseDelegatedType`](use_delegated_type.md) page, and the generated `WithProvider` impl on the [`WithProvider`](with_provider.md) page. @@ -114,7 +114,7 @@ on the [`WithProvider`](with_provider.md) page. - [`UseDelegatedType`](use_delegated_type.md) — the foundational provider it wraps, where the table lookup is documented. - [`WithType`](with_type.md) — the sibling alias for a single fixed concrete type. -- [`DelegateComponent`](../traits/delegate_component.md) — the table the lookup reads. +- [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table the lookup reads. - [`HasType` / `TypeProvider`](../components/has_type.md) — the abstract-type component it answers for. - [`#[cgp_type]`](../macros/cgp_type.md) — defines the abstract-type components it resolves. diff --git a/docs/reference/providers/with_field.md b/docs/reference/providers/with_field.md index 555bb1bd..01fa2191 100644 --- a/docs/reference/providers/with_field.md +++ b/docs/reference/providers/with_field.md @@ -31,7 +31,7 @@ delegate_components! { ``` The tag is a [`Symbol!`](../macros/symbol.md) for a named field or an `Index` for a tuple field, and -the context must have a [`HasField`](../traits/has_field.md) implementation for it. This reads the +the context must have a [`HasField`](../traits/field-access/has_field.md) implementation for it. This reads the `first_name` field exactly as wiring [`UseField`](use_field.md) would. ## Examples @@ -83,7 +83,7 @@ pub type WithField = WithProvider>; The [`WithProvider`](with_provider.md) adapter forwards a getter's provider-trait method to the inner provider's foundational method, and [`UseField`](use_field.md) is the foundational -[`FieldGetter`](../traits/field_getter.md) that reads the field at `Tag`. The generated `WithProvider` +[`FieldGetter`](../traits/field-access/field_getter.md) that reads the field at `Tag`. The generated `WithProvider` impl that makes this work is shown on the [`WithProvider`](with_provider.md) page. ## Related constructs @@ -93,7 +93,7 @@ impl that makes this work is shown on the [`WithProvider`](with_provider.md) pag - [`WithFieldRef`](with_field_ref.md) — the sibling alias for a field borrowed through `AsRef`. - [`#[cgp_getter]`](../macros/cgp_getter.md) — defines the getter component and generates the `WithProvider` impl. -- [`HasField`](../traits/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the +- [`HasField`](../traits/field-access/has_field.md) and [`#[derive(HasField)]`](../derives/derive_has_field.md) — the field access it reads, keyed by [`Symbol!`](../macros/symbol.md) or `Index`. The ideas behind it: diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md index 1a074202..993d643a 100644 --- a/docs/reference/providers/with_field_ref.md +++ b/docs/reference/providers/with_field_ref.md @@ -17,7 +17,7 @@ and borrowing it through `AsRef` to produce a `&Value`, where the stored field t Unlike [`WithField`](with_field.md), this alias is not an alternative to a directly-wireable provider: the bare [`UseFieldRef`](use_field_ref.md) supplies only the foundational -[`FieldGetter`](../traits/field_getter.md), so `WithFieldRef` is the form you wire. +[`FieldGetter`](../traits/field-access/field_getter.md), so `WithFieldRef` is the form you wire. ## Usage @@ -101,7 +101,7 @@ pub type WithFieldRef = WithProvider>; The [`WithProvider`](with_provider.md) adapter forwards a getter's provider-trait method to the inner provider's foundational method, and [`UseFieldRef`](use_field_ref.md) is the foundational -[`FieldGetter`](../traits/field_getter.md) that reads the field at `Tag` and borrows it through `AsRef`. +[`FieldGetter`](../traits/field-access/field_getter.md) that reads the field at `Tag` and borrows it through `AsRef`. The `UseFieldRef` mechanism, including its mutable form, is documented on the [`UseFieldRef`](use_field_ref.md) page, and the generated `WithProvider` impl on the [`WithProvider`](with_provider.md) page. @@ -113,8 +113,8 @@ The `UseFieldRef` mechanism, including its mutable form, is documented on the documented. - [`WithField`](with_field.md) — the sibling alias for a field read directly, without the `AsRef` step. - [`#[cgp_getter]`](../macros/cgp_getter.md) — defines the getter component this is wired to. -- [`FieldGetter`](../traits/field_getter.md) and [`MutFieldGetter`](../traits/mut_field_getter.md) — the - provider-side getters the inner provider implements, over [`HasField`](../traits/has_field.md). +- [`FieldGetter`](../traits/field-access/field_getter.md) and [`MutFieldGetter`](../traits/field-access/mut_field_getter.md) — the + provider-side getters the inner provider implements, over [`HasField`](../traits/field-access/has_field.md). The ideas behind it: diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 4f548f61..93ba129a 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -11,7 +11,7 @@ specific named component. ## Overview `WithProvider` bridges CGP's two layers of provider trait. Foundational traits like -[`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field_getter.md) are generic, +[`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field-access/field_getter.md) are generic, component-agnostic mechanisms: a `TypeProvider` supplies *some* abstract type for *some* tag, and a `FieldGetter` reads *some* field for *some* output tag, without either knowing which named component it serves. A named component, by contrast, has a specific provider trait, such as `NameTypeProvider` or @@ -138,7 +138,7 @@ where In both cases the bound names the foundational trait, keyed by the component marker, and the method or associated type forwards to it. `#[cgp_getter]` generates the `WithProvider` impl only when the getter has exactly one method, since a single foundational getter cannot serve several methods at once. Each -impl is paired with a matching [`IsProviderFor`](../traits/is_provider_for.md) impl. +impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl. The aliases specialize `WithProvider` to a fixed inner provider so the common cases need no `WithProvider<...>` spelled out. Each has its own page: [`WithContext`](with_context.md), @@ -149,7 +149,7 @@ The aliases specialize `WithProvider` to a fixed inner provider so the common ca - [`#[cgp_type]`](../macros/cgp_type.md) and [`#[cgp_getter]`](../macros/cgp_getter.md) — generate the `WithProvider` impls that make a component adaptable. -- [`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field_getter.md) — the +- [`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field-access/field_getter.md) — the foundational traits it adapts. - [`UseContext`](use_context.md), [`UseType`](use_type.md), [`UseField`](use_field.md), [`UseFieldRef`](use_field_ref.md), and [`UseDelegatedType`](use_delegated_type.md) — the inner diff --git a/docs/reference/traits/_category_.json b/docs/reference/traits/_category_.json index d0a1fe9f..352fb396 100644 --- a/docs/reference/traits/_category_.json +++ b/docs/reference/traits/_category_.json @@ -2,7 +2,7 @@ "label": "Traits", "position": 6, "link": { - "type": "generated-index", - "description": "The capability and mechanism traits the macros expand into \u2014 rarely written by hand, but worth understanding when reading generated code or a compiler error." + "type": "doc", + "id": "reference/traits/index" } } diff --git a/docs/reference/traits/builder/_category_.json b/docs/reference/traits/builder/_category_.json new file mode 100644 index 00000000..39ade422 --- /dev/null +++ b/docs/reference/traits/builder/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Record builders", + "position": 4, + "link": { + "type": "doc", + "id": "reference/traits/builder/index" + } +} diff --git a/docs/reference/traits/build_field.md b/docs/reference/traits/builder/build_field.md similarity index 79% rename from docs/reference/traits/build_field.md rename to docs/reference/traits/builder/build_field.md index fc4b212c..61423ca5 100644 --- a/docs/reference/traits/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -1,5 +1,6 @@ --- sidebar_label: 'BuildField' +sidebar_position: 3 --- # `BuildField` @@ -11,6 +12,19 @@ Setting one currently-absent field of a builder. `BuildField` is the direction of the [builder family](./has_builder.md) you write most: take a partial record with a field absent, supply the value, and get back a partial record with that field present. +`Output` is a **different type** from `Self` — the same partial record with one marker flipped — which is +what makes the compiler track completeness. A chain of `build_field` calls walks through as many distinct +types as there are fields, and only the last one satisfies +[`FinalizeBuild`](./finalize_build.md). + +It pins one transition of the [`UpdateField`](./update_field.md) primitive: `IsNothing → IsPresent`. +Because it *requires* the starting marker to be `IsNothing`, **building a field that is already set is a +compile error**, not a silent overwrite. + +## Definition + +`BuildField` is keyed by the field's `Tag`, with two associated types and one method: + ```rust pub trait BuildField { type Value; @@ -20,20 +34,16 @@ pub trait BuildField { } ``` -`Output` is a **different type** from `Self` — the same partial record with one marker flipped — which is -what makes the compiler track completeness. A chain of `build_field` calls walks through as many distinct -types as there are fields, and only the last one satisfies -[`FinalizeBuild`](./finalize_build.md). - -It pins one transition of the [`UpdateField`](./update_field.md) primitive: `IsNothing → IsPresent`. -Because it *requires* the starting marker to be `IsNothing`, **building a field that is already set is a -compile error**, not a silent overwrite. +`Tag` names the field. `Value` is the field's declared type, so `build_field` takes an ordinary value with +no marker wrapper. `Output` is the partial record with that one field's marker flipped from `IsNothing` to +`IsPresent`, a different type from `Self`. The blanket impl over [`UpdateField`](./update_field.md) that +supplies all of this is shown in [Under the hood](#under-the-hood). ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -The `PhantomData` argument names the field, the same way a [`HasField`](./has_field.md) read does: +The `PhantomData` argument names the field, the same way a [`HasField`](../field-access/has_field.md) read does: `PhantomData::` for a named field, `PhantomData::>` for a tuple-struct position. `Value` is the field's declared type, so what you pass is an ordinary value with no wrapper. @@ -81,10 +91,10 @@ the record.** - **Bound on [`HasBuilder`](./has_builder.md) + `BuildField` + [`FinalizeBuild`](./finalize_build.md)** to write a routine that assembles a record it does not name. -- **Use [`CanBuildFrom`](./can_build_from.md)** to copy every shared field from another record at once, +- **Use [`CanBuildFrom`](../casting/can_build_from.md)** to copy every shared field from another record at once, rather than one `build_field` per field. -- **Use [`SetOptional`](./set_optional.md)** when a field must be settable more than once. `build_field` - consumes an absent slot exactly once by design; the optional layer is what relaxes that. +- **Use [`SetOptional`](../optional/set_optional.md)** when a field must be settable more than once. `build_field` + consumes an absent slot exactly once by design; the optional layer relaxes that. - **Use [`UpdateField`](./update_field.md)** for a transition this does not cover. - **Prefer a struct literal** in concrete code that knows every field. @@ -99,7 +109,7 @@ marker to `IsPresent` and constraining the reported source marker to `IsNothing` // where Partial: UpdateField ``` -The `Mapper = IsNothing` constraint is what does the checking. `Mapper` is an *output* of the primitive — +The `Mapper = IsNothing` constraint does the checking. `Mapper` is an *output* of the primitive — the marker the field was in — so constraining it selects only those partial types whose field is currently absent. A field already set has `Mapper = IsPresent`, no impl matches, and the call fails to resolve. @@ -122,13 +132,13 @@ across a chain, and it cannot be filled in a loop — the chain is unrolled by c detectable at the end, since any prefix of a chain is a legal partial value. **It sets, it does not overwrite.** For a settable-and-resettable field, reach for -[`SetOptional`](./set_optional.md). +[`SetOptional`](../optional/set_optional.md). **The `PhantomData` argument carries the tag.** At a site where inference cannot determine it, write `PhantomData::` in full. **Nothing implements it directly**, so an unsatisfied `BuildField` bound is really an unsatisfied -[`UpdateField`](./update_field.md) one — which is what the error names. +[`UpdateField`](./update_field.md) one, which the error names. ## Related constructs @@ -137,12 +147,12 @@ detectable at the end, since any prefix of a chain is a legal partial value. - [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — where a partial value comes from. - [`FinalizeBuild`](./finalize_build.md) — where a completed one goes. -- [`CanBuildFrom`](./can_build_from.md) — filling many fields from another record in one call. -- [`SetOptional`](./set_optional.md) — the settable-repeatedly counterpart. -- [`MapType`](./map_type.md) — the `IsNothing`/`IsPresent` markers this moves between. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the `UpdateField` impls behind +- [`CanBuildFrom`](../casting/can_build_from.md) — filling many fields from another record in one call. +- [`SetOptional`](../optional/set_optional.md) — the settable-repeatedly counterpart. +- [`MapType`](../type-level/map_type.md) — the `IsNothing`/`IsPresent` markers this moves between. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the `UpdateField` impls behind it. -- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that name a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that name a field. The ideas behind it: diff --git a/docs/reference/traits/finalize_build.md b/docs/reference/traits/builder/finalize_build.md similarity index 75% rename from docs/reference/traits/finalize_build.md rename to docs/reference/traits/builder/finalize_build.md index 5bab1611..1e13430f 100644 --- a/docs/reference/traits/finalize_build.md +++ b/docs/reference/traits/builder/finalize_build.md @@ -1,5 +1,6 @@ --- sidebar_label: 'FinalizeBuild' +sidebar_position: 6 --- # `FinalizeBuild` @@ -8,15 +9,8 @@ Turning a fully-built partial record back into the concrete struct. ## Overview -`FinalizeBuild` is where a build ends: - -```rust -pub trait FinalizeBuild: PartialData { - fn finalize_build(self) -> Self::Target; -} -``` - -What makes it the family's safety argument is not the method but **where the impl exists**. It is +`FinalizeBuild` is where a build ends. What makes it the family's safety argument is not the method but +**where the impl exists**. It is implemented for exactly one configuration of a partial record — the one in which every field is `IsPresent` — so calling it on an incomplete value is a *missing impl*, not a runtime check that fails: @@ -34,6 +28,23 @@ The destination type comes from its supertrait [`PartialData`](./partial_data.md configuration implements. That division is deliberate: **one names where you are going, the other says you have arrived.** +## Definition + +`FinalizeBuild` has one method and a supertrait: + +```rust +pub trait FinalizeBuild: PartialData { + fn finalize_build(self) -> Self::Target; +} +``` + +`finalize_build` takes `self` by value, so it consumes the partial record, and returns `Self::Target`, the +concrete struct being built. `Target` is not declared here: it comes from the supertrait +[`PartialData`](./partial_data.md), which every configuration of a partial record implements, so the +destination is nameable at any point in a build. What `FinalizeBuild` adds is the method, and its impl +exists for only one configuration — every field `IsPresent` — which is the safety argument the rest of +this page works out. + ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. @@ -52,7 +63,7 @@ where } ``` -The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md), which emits exactly one +The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), which emits exactly one per record. ## Examples @@ -93,10 +104,10 @@ forgot, and it is the only place the compiler names it. - **Bound on [`HasBuilder`](./has_builder.md) + [`BuildField`](./build_field.md) + `FinalizeBuild`** to write a routine that assembles a record it does not name. -- **Use [`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when unset fields should be filled +- **Use [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md)** when unset fields should be filled from `Default` rather than rejected. It re-marks every field to `IsPresent` and then calls this, so the strict check still runs and always passes. -- **Use [`FinalizeOptional`](./finalize_optional.md)** when absence should be *reported* at run time +- **Use [`FinalizeOptional`](../optional/finalize_optional.md)** when absence should be *reported* at run time rather than caught at compile time. It returns a `Result` naming the first missing field. - **Stay with `FinalizeBuild`** when every field is genuinely required. Moving to either of the other two gives up the compile-time completeness check, which is the reason the family exists. @@ -129,8 +140,8 @@ compiler has no way to say "you forgot `last_name`", because nothing in the fail names. The marker list in the type is the diagnostic. The optional layer reaches this same impl rather than replacing it: -[`CanFinalizeWithDefault`](./can_finalize_with_default.md) runs a -[`TransformMapFields`](./transform_map_fields.md) to `IsPresent` first, so **the strict, all-present impl +[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) runs a +[`TransformMapFields`](../type-level/transform_map_fields.md) to `IsPresent` first, so **the strict, all-present impl remains the only way a partial value becomes a concrete struct.** ## Common Mistakes @@ -144,12 +155,12 @@ type in the message: the field whose marker is still `IsNothing` is the one miss `Target` is projected from the supertrait. **There is no fallible variant here.** Reporting absence at run time is -[`FinalizeOptional`](./finalize_optional.md), a different trait in a different crate. +[`FinalizeOptional`](../optional/finalize_optional.md), a different trait in a different crate. **A fieldless struct finalizes immediately.** Its companion has no markers, so `builder().finalize_build()` compiles — legal and useless. -**The enum side has its own ending.** [`FinalizeExtract`](./finalize_extract.md) discharges an exhausted +**The enum side has its own ending.** [`FinalizeExtract`](../variant/finalize_extract.md) discharges an exhausted extractor, and it is sound for the opposite reason: the value cannot exist, rather than being complete. ## Related constructs @@ -160,11 +171,11 @@ extractor, and it is sound for the opposite reason: the value cannot exist, rath - [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) — what moves it between configurations. - [`UpdateField`](./update_field.md) — the primitive underneath both. -- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) and - [`FinalizeOptional`](./finalize_optional.md) — the two relaxed endings. -- [`MapType`](./map_type.md) — the `IsPresent` marker every field must reach. -- [`FinalizeExtract`](./finalize_extract.md) — the enum family's ending, sound for the opposite reason. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates this impl. +- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and + [`FinalizeOptional`](../optional/finalize_optional.md) — the two relaxed endings. +- [`MapType`](../type-level/map_type.md) — the `IsPresent` marker every field must reach. +- [`FinalizeExtract`](../variant/finalize_extract.md) — the enum family's ending, sound for the opposite reason. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates this impl. The ideas behind it: diff --git a/docs/reference/traits/has_builder.md b/docs/reference/traits/builder/has_builder.md similarity index 76% rename from docs/reference/traits/has_builder.md rename to docs/reference/traits/builder/has_builder.md index 4f081085..41fee744 100644 --- a/docs/reference/traits/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasBuilder' +sidebar_position: 1 --- # `HasBuilder` @@ -12,14 +13,6 @@ A struct literal supplies every field at once, in one place that names the type. entry point for the case where that is impossible: the fields come from several independent places, none of which should know the whole struct, and the result must still be checked at compile time. -```rust -pub trait HasBuilder { - type Builder; - - fn builder() -> Self::Builder; -} -``` - `builder()` hands back a partial value with **every field absent**. Filling it is [`BuildField`](./build_field.md), and turning it back into the concrete struct is [`FinalizeBuild`](./finalize_build.md) — which is implemented **only** for the fully-present @@ -35,17 +28,33 @@ let person = Person::builder() // every fie Delete a middle line and this does not compile. **Field presence lives in the type**, which is the defining idea of the whole family. +## Definition + +`HasBuilder` is a small trait: one associated type and one associated function. + +```rust +pub trait HasBuilder { + type Builder; + + fn builder() -> Self::Builder; +} +``` + +`Self` is the concrete record being built. `Builder` is the *partial companion type* the derive generates +for it, the record carrying one [`MapType`](../type-level/map_type.md) presence marker per field. +`builder()` is an associated function, so it takes no receiver, and it returns that companion at its +all-absent configuration, ready to fill. + ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -`builder()` is an associated function with no receiver, called as `Person::builder()` or `T::builder()` -in generic code. `Builder` names the partial companion type the derive generated — you rarely write that -type, but it is what appears in an error when a build is incomplete. +`builder()` is called with no receiver, as `Person::builder()` or `T::builder()` in generic code. You +rarely name the `Builder` type yourself, but it appears in an error when a build is incomplete. -The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md), also available through -[`#[derive(CgpRecord)]`](../derives/derive_cgp_record.md) and -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). +The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), also available through +[`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md) and +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md). **Its counterpart is [`IntoBuilder`](./into_builder.md)**, which starts from an existing value with every field *present* rather than from nothing. The two differ only in where they begin, and the choice is @@ -54,7 +63,7 @@ about whether you are assembling a record or redistributing one. ## Examples The everyday shape is `builder()`, some `build_field` calls, and `finalize_build`, with -[`build_from`](./can_build_from.md) copying every shared field from another record in one step: +[`build_from`](../casting/can_build_from.md) copying every shared field from another record in one step: ```rust use cgp::core::field::impls::CanBuildFrom; @@ -86,7 +95,7 @@ Every line changes the partial *type*, and the last one type-checks only because present. Reorder them so `finalize_build` runs before `baz` is set and it is a compile error. A field that has been set can be read back mid-build, because the derive emits a -[`HasField`](./has_field.md) impl on the partial type gated on presence: +[`HasField`](../field-access/has_field.md) impl on the partial type gated on presence: ```rust let partial = Person::builder() @@ -113,15 +122,15 @@ record being built — which is the extensible builder pattern, and the reason t Two boundaries are worth stating plainly. This is **not a conventional builder**: it tracks presence and nothing else — no defaults, no validation at finalize, no optional field unless the field's own type is -optional. The [optional-field extensions](./has_optional_builder.md) cover the defaulted and optional +optional. The [optional-field extensions](../optional/has_optional_builder.md) cover the defaulted and optional cases, and a hand-written builder remains better when the *logic* is the point. And the enum counterparts -are a different family: [`ExtractField`](./extract_field.md) for taking a value apart and -[`FromVariant`](./from_variant.md) for constructing one. +are a different family: [`ExtractField`](../variant/extract_field.md) for taking a value apart and +[`FromVariant`](../variant/from_variant.md) for constructing one. ## Under the hood The derive generates a companion struct — `__Partial{Name}` — that is your struct with one -[`MapType`](./map_type.md) parameter added per field and each field's type wrapped in that parameter's +[`MapType`](../type-level/map_type.md) parameter added per field and each field's type wrapped in that parameter's projection: ```rust @@ -164,11 +173,11 @@ field. Read the partial type in the message to see which marker is still `IsNoth **The partial type cannot be printed or cloned.** The derive clears the original's attributes, so no `Debug`, no `Clone`, whatever the record derives. Read a set field through the partial type's -[`HasField`](./has_field.md) impl instead. +[`HasField`](../field-access/has_field.md) impl instead. **There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible default still has to be set, unless you reach for the -[optional-field extensions](./can_finalize_with_default.md). +[optional-field extensions](../optional/can_finalize_with_default.md). **`builder()` is an associated function.** There is no receiver, so it is `Person::builder()` rather than anything called on a value. Starting from a value is [`IntoBuilder`](./into_builder.md). @@ -184,13 +193,13 @@ legal and useless. - [`UpdateField`](./update_field.md) — the primitive both are built from. - [`PartialData`](./partial_data.md) and [`FinalizeBuild`](./finalize_build.md) — naming the destination, and reaching it. -- [`CanBuildFrom`](./can_build_from.md) — merging every shared field from another record. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the partial type and every impl +- [`CanBuildFrom`](../casting/can_build_from.md) — merging every shared field from another record. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the partial type and every impl in the family. -- [`MapType`](./map_type.md) — the `IsPresent`/`IsNothing` markers presence is encoded in. -- [`HasField`](./has_field.md) — how a set field is read back off a partial value. -- [Optional fields](./has_optional_builder.md) — defaulted and optional finalization. -- [`ExtractField`](./extract_field.md) and [`FromVariant`](./from_variant.md) — the enum counterparts. +- [`MapType`](../type-level/map_type.md) — the `IsPresent`/`IsNothing` markers presence is encoded in. +- [`HasField`](../field-access/has_field.md) — how a set field is read back off a partial value. +- [Optional fields](../optional/has_optional_builder.md) — defaulted and optional finalization. +- [`ExtractField`](../variant/extract_field.md) and [`FromVariant`](../variant/from_variant.md) — the enum counterparts. The ideas behind it: diff --git a/docs/reference/traits/builder/index.md b/docs/reference/traits/builder/index.md new file mode 100644 index 00000000..441f2a7e --- /dev/null +++ b/docs/reference/traits/builder/index.md @@ -0,0 +1,42 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Record builders + +Assembling a struct one field at a time, with field presence tracked in the type. + +## Overview + +These traits build a record incrementally, where the fields come from several independent places and +the result must still be checked at compile time. The build starts from an empty *partial* value and +adds fields one by one, and each field's presence lives in the type — so finalizing an incomplete +record is a missing impl rather than a runtime panic. The impls come from +[`#[derive(BuildField)]`](../../derives/derive_build_field.md), which also generates the partial +companion type. + +The family divides into entry points, the update primitive and its two directions, and the finalize +step. + +The **entry points** obtain a partial value to build into. [`HasBuilder`](has_builder.md) produces an +empty one, and [`IntoBuilder`](into_builder.md) turns a complete value into a full one to redistribute. + +The **field operations** move one field between states. [`UpdateField`](update_field.md) is the +primitive the derive writes; [`BuildField`](build_field.md) sets an absent field and +[`TakeField`](take_field.md) removes a present one, each a blanket impl over the primitive in one +direction. + +The **finalize step** ends a build. [`FinalizeBuild`](finalize_build.md) turns a fully-present partial +value back into the concrete struct, and exists only at that configuration. +[`PartialData`](partial_data.md) names the destination type at every configuration, which is how +generic builder code knows what it is building before the build is complete. + +## The ideas behind them + +- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder + pattern. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/into_builder.md b/docs/reference/traits/builder/into_builder.md similarity index 75% rename from docs/reference/traits/into_builder.md rename to docs/reference/traits/builder/into_builder.md index 0123ebb5..e857dd4d 100644 --- a/docs/reference/traits/into_builder.md +++ b/docs/reference/traits/builder/into_builder.md @@ -1,5 +1,6 @@ --- sidebar_label: 'IntoBuilder' +sidebar_position: 2 --- # `IntoBuilder` @@ -9,7 +10,20 @@ Turning a complete record into a partial one, with every field present. ## Overview [`HasBuilder`](./has_builder.md) starts from nothing: a partial value with every field absent, to be -filled. `IntoBuilder` starts from the other end: +filled. `IntoBuilder` starts from the other end: `into_builder(self)` consumes an existing value and +hands back a partial one with **every field present**. You reach for it when *redistributing* a struct's +fields rather than assembling one: taking a value apart, moving some fields elsewhere, and rebuilding. + +The two entry points differ only in where they begin, and they produce the same kind of value: + +| | starting configuration | what it is for | +|---|---|---| +| [`HasBuilder`](./has_builder.md) | every field `IsNothing` | assembling a record from pieces | +| `IntoBuilder` | every field `IsPresent` | taking one apart and putting it back | + +## Definition + +`IntoBuilder` mirrors [`HasBuilder`](./has_builder.md), with one associated type and one method: ```rust pub trait IntoBuilder { @@ -19,28 +33,20 @@ pub trait IntoBuilder { } ``` -`into_builder(self)` consumes an existing value and hands back a partial one with **every field -present**. That is what you want when *redistributing* a struct's fields rather than assembling one — -taking a value apart, moving some fields elsewhere, and rebuilding. - -The two entry points differ only in where they begin, and they produce the same kind of value: - -| | starting configuration | what it is for | -|---|---|---| -| [`HasBuilder`](./has_builder.md) | every field `IsNothing` | assembling a record from pieces | -| `IntoBuilder` | every field `IsPresent` | taking one apart and putting it back | +`Self` is the complete record. `Builder` is the same partial companion type +[`HasBuilder`](./has_builder.md) names, but at the all-present configuration rather than the all-absent +one. `into_builder` takes `self` by value, so it consumes the record and returns the companion with every +field already set. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -Unlike `builder()`, this one is a method taking `self`, so it is called on a value: -`person.into_builder()`. `Builder` names the same partial companion type -[`HasBuilder`](./has_builder.md) names, at the all-present configuration rather than the all-absent one. +Unlike `builder()`, this is a method taking `self`, so it is called on a value: `person.into_builder()`. -The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md), also available through -[`#[derive(CgpRecord)]`](../derives/derive_cgp_record.md) and -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). +The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), also available through +[`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md) and +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md). ## Examples @@ -61,8 +67,7 @@ let person = remainder ``` Note that a value straight out of `into_builder` is already finalizable — every marker is `IsPresent`, so -[`finalize_build`](./finalize_build.md) resolves immediately and the round trip is the identity. What -makes the trait useful is what happens in between. +[`finalize_build`](./finalize_build.md) resolves immediately and the round trip is the identity. The trait earns its keep only from what happens in between. ## When to use it @@ -73,7 +78,7 @@ entry points and the one that shows up in generic code more than in application common case and the one the extensible builder pattern is about. - **Use `IntoBuilder`** when a complete value must be decomposed — to swap one field, to hand fields to several destinations, to rebuild a record with one type changed. -- **Use [`ToFields`](./to_fields.md)** instead when what you want is the value's *shape* as a flat list +- **Use [`ToFields`](../shape/to_fields.md)** instead when what you want is the value's *shape* as a flat list rather than a partial type you can fill. A partial value tracks presence; a `Fields` product does not. - **Prefer a struct update expression** in concrete code. `Person { first_name, ..person }` does the common case with no machinery, and this family is for code that cannot name the type. @@ -81,7 +86,7 @@ entry points and the one that shows up in generic code more than in application ## Under the hood The derive generates one partial companion per record — `__Partial{Name}`, with a -[`MapType`](./map_type.md) parameter per field — and the two entry points differ only in the +[`MapType`](../type-level/map_type.md) parameter per field — and the two entry points differ only in the configuration they name: ```rust @@ -104,7 +109,7 @@ which is exactly the pair a redistribution needs. ## Common Mistakes -**It consumes the value.** There is no borrowing form; use [`ToFieldsRef`](./to_fields_ref.md) if the +**It consumes the value.** There is no borrowing form; use [`ToFieldsRef`](../shape/to_fields_ref.md) if the original must survive, bearing in mind that gives you a shape rather than a builder. **The result is already finalizable.** Calling `into_builder().finalize_build()` is the identity, which @@ -124,14 +129,14 @@ dropped. ## Related constructs - [`HasBuilder`](./has_builder.md) — the other entry point, and where the family is explained in full. -- [`TakeField`](./take_field.md) — removing a present field, which is what this enables. +- [`TakeField`](./take_field.md) — removing a present field, which this enables. - [`BuildField`](./build_field.md) — putting one back. - [`FinalizeBuild`](./finalize_build.md) — returning to the concrete struct. - [`UpdateField`](./update_field.md) — the primitive underneath both directions. - [`PartialData`](./partial_data.md) — what names the destination type mid-build. -- [`ToFields`](./to_fields.md) — the flat-shape alternative to a partial value. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates this impl. -- [`MapType`](./map_type.md) — the markers the configuration is written in. +- [`ToFields`](../shape/to_fields.md) — the flat-shape alternative to a partial value. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates this impl. +- [`MapType`](../type-level/map_type.md) — the markers the configuration is written in. The ideas behind it: diff --git a/docs/reference/traits/partial_data.md b/docs/reference/traits/builder/partial_data.md similarity index 68% rename from docs/reference/traits/partial_data.md rename to docs/reference/traits/builder/partial_data.md index af4129f9..0af960f0 100644 --- a/docs/reference/traits/partial_data.md +++ b/docs/reference/traits/builder/partial_data.md @@ -1,5 +1,6 @@ --- sidebar_label: 'PartialData' +sidebar_position: 7 --- # `PartialData` @@ -11,8 +12,8 @@ Naming the concrete type a partial value is on its way to becoming. ### Generated machinery **You are not expected to implement `PartialData`.** -[`#[derive(BuildField)]`](../derives/derive_build_field.md) and -[`#[derive(ExtractField)]`](../derives/derive_extract_field.md) emit it for every companion type they +[`#[derive(BuildField)]`](../../derives/derive_build_field.md) and +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) emit it for every companion type they generate. What you meet is the projection `Self::Target` in another trait's signature; this page explains where that projection comes from. The one case for bounding on it is generic code that needs the destination type before the value is complete. @@ -22,7 +23,17 @@ where that projection comes from. The one case for bounding on it is generic cod A partial record is a companion type — `__PartialPerson` — and generic code holding one often needs to know what it will *become* before it is complete: to name the return type of a -routine, to state a bound, to decide what to do next. `PartialData` answers that: +routine, to state a bound, to decide what to do next. `PartialData` answers that: its single `Target` +associated type is the concrete struct or enum the partial value corresponds to. **It is implemented for +every configuration**, complete or not, and that coverage is the point: the destination is knowable from +the first `builder()` call, long before any field is set. + +That is the division of labour with [`FinalizeBuild`](./finalize_build.md), which is implemented **only** +at the all-present configuration. One says where you are going; the other says you have arrived. + +## Definition + +`PartialData` is a single associated type and nothing else: ```rust pub trait PartialData { @@ -30,17 +41,15 @@ pub trait PartialData { } ``` -`Target` is the concrete struct or enum the partial value corresponds to. **It is implemented for every -configuration**, complete or not, which is exactly what makes it useful: the destination is knowable from -the first `builder()` call, long before any field is set. - -That is the division of labour with [`FinalizeBuild`](./finalize_build.md), which is implemented **only** -at the all-present configuration. One says where you are going; the other says you have arrived. +`Self` is a partial companion type, a record builder or an extraction remainder. `Target` is the concrete +struct or enum it belongs to. There is no method, because naming a type is not an operation; the trait +exists so that generic code can project `Self::Target` while holding a value of unknown completeness. +[`FinalizeBuild`](./finalize_build.md) and [`FinalizeOptional`](../optional/finalize_optional.md) both +read the destination through this projection rather than declaring one of their own. ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method — naming a type is not -an operation. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. You bound on it when a signature must mention the destination while holding a partial value: @@ -53,8 +62,8 @@ where } ``` -The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md) for a record and -[`#[derive(ExtractField)]`](../derives/derive_extract_field.md) for an enum — **both** partial families +The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md) for a record and +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) for an enum — **both** partial families implement it, which is worth knowing because it is the one trait the builder and extractor sides share directly. @@ -72,7 +81,7 @@ pub trait FinalizeBuild: PartialData { `Self::Target` in that signature comes from here. Without it the finalize would need its own associated type, and the destination would be unnameable until the value was complete. -The same appears in [`FinalizeOptional`](./finalize_optional.md), which returns +The same appears in [`FinalizeOptional`](../optional/finalize_optional.md), which returns `Result` — again projecting the destination through this trait rather than declaring one of its own. @@ -87,7 +96,7 @@ traits otherwise. opposite direction: `Person::Builder` from `Person`, rather than `Target` from a partial. - **`PartialData`** when the code holds a partial value of unknown completeness and must name what it belongs to — a signature, a `where` clause, an error message. -- **[`TransformMapFields`](./transform_map_fields.md)** requires it, which is the other place it shows up +- **[`TransformMapFields`](../type-level/transform_map_fields.md)** requires it, which is the other place it shows up in a bound rather than as a projection. ## Under the hood @@ -101,15 +110,15 @@ The derive emits one impl covering every configuration at once, by leaving the m // } ``` -Nothing about the markers is constrained, which is what makes the destination available at every step of +Nothing about the markers is constrained, so the destination stays available at every step of a build. Contrast [`FinalizeBuild`](./finalize_build.md), whose impl fixes every marker to `IsPresent`. -Splitting the two is what lets generic builder code be written against a destination it can name while +Splitting the two lets generic builder code work against a destination it can name while still being *unable* to finalize prematurely — the type is known, the conversion is not available. A single trait carrying both would have to choose one or the other. The enum side implements it identically on its extraction companions, with `Target` naming the original -enum, which is how [`HasExtractor`](./has_extractor.md)'s round trip knows what to rebuild. +enum, which is how [`HasExtractor`](../variant/has_extractor.md)'s round trip knows what to rebuild. ## Common Mistakes @@ -132,13 +141,13 @@ usual confusion when meeting it in an error. - [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — the opposite direction, from a concrete type to a partial one. - [`UpdateField`](./update_field.md) — what moves a partial value between configurations. -- [`FinalizeOptional`](./finalize_optional.md) — the optional layer's finalize, which projects `Target` +- [`FinalizeOptional`](../optional/finalize_optional.md) — the optional layer's finalize, which projects `Target` the same way. -- [`TransformMapFields`](./transform_map_fields.md) — requires this bound. -- [`ExtractField`](./extract_field.md) — the enum family whose companions also implement it. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) and - [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generate the impls. -- [`MapType`](./map_type.md) — the markers a configuration is written in. +- [`TransformMapFields`](../type-level/transform_map_fields.md) — requires this bound. +- [`ExtractField`](../variant/extract_field.md) — the enum family whose companions also implement it. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) and + [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generate the impls. +- [`MapType`](../type-level/map_type.md) — the markers a configuration is written in. The ideas behind it: diff --git a/docs/reference/traits/take_field.md b/docs/reference/traits/builder/take_field.md similarity index 75% rename from docs/reference/traits/take_field.md rename to docs/reference/traits/builder/take_field.md index 248920b7..dae74232 100644 --- a/docs/reference/traits/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -1,5 +1,6 @@ --- sidebar_label: 'TakeField' +sidebar_position: 4 --- # `TakeField` @@ -9,7 +10,21 @@ Removing one currently-present field from a builder. ## Overview `TakeField` is the reverse of [`BuildField`](./build_field.md): it removes a field that is currently set, -handing back the value and the partial record without it. +handing back the value and the partial record without it. The value comes out owned, and the remainder is +the partial record with that one field flipped back to absent, so it can no longer be finalized until the +field is put back. + +It pins the `IsPresent → IsNothing` transition of the [`UpdateField`](./update_field.md) primitive, and +because it *requires* the starting marker to be `IsPresent`, **taking a field that is absent is a compile +error** rather than an `Option` you have to handle. + +Two things reach for it. Redistributing a record — [`into_builder`](./into_builder.md), take fields out, +put them somewhere else — and, far more often, [`CanBuildFrom`](../casting/can_build_from.md), whose merge +recursion takes each field out of the source and builds it into the target. + +## Definition + +`TakeField` is keyed by the field's `Tag`, with two associated types and one method: ```rust pub trait TakeField { @@ -20,16 +35,11 @@ pub trait TakeField { } ``` -The value comes out owned; `Remainder` is the partial record with that one field's marker flipped back to -`IsNothing`, so it can no longer be finalized until the field is put back. - -It pins the `IsPresent → IsNothing` transition of the [`UpdateField`](./update_field.md) primitive, and -because it *requires* the starting marker to be `IsPresent`, **taking a field that is absent is a compile -error** rather than an `Option` you have to handle. - -Two things reach for it. Redistributing a record — [`into_builder`](./into_builder.md), take fields out, -put them somewhere else — and, far more often, [`CanBuildFrom`](./can_build_from.md), whose merge -recursion takes each field out of the source and builds it into the target. +`Tag` names the field. `Value` is the field's declared type, returned owned. `Remainder` is the partial +record with that one field's marker flipped from `IsPresent` back to `IsNothing`, a different type from +`Self` that can no longer be finalized until the field is restored. `take_field` returns the two as a +tuple, the value first and the remainder second. The blanket impl over [`UpdateField`](./update_field.md) +that supplies this is shown in [Under the hood](#under-the-hood). ## Usage @@ -73,12 +83,12 @@ taken out and not replaced cannot be forgotten silently. **Reach for it when a complete value must be decomposed**, and remember that the common case — merging one record into another — already uses it for you. -- **Use [`CanBuildFrom`](./can_build_from.md)** to move every shared field from one record into another's +- **Use [`CanBuildFrom`](../casting/can_build_from.md)** to move every shared field from one record into another's builder. It is this trait applied in a loop, written once. - **Use `take_field`** when a *specific* field must be extracted from a partial value, typically after [`into_builder`](./into_builder.md). - **Use [`BuildField`](./build_field.md)** for the opposite direction. -- **Use [`ToFields`](./to_fields.md)** when the whole value should become a flat shape rather than a +- **Use [`ToFields`](../shape/to_fields.md)** when the whole value should become a flat shape rather than a partial record with one field missing. - **Prefer ordinary destructuring** in concrete code. `let Person { first_name, .. } = person;` needs no machinery, and this family is for code that cannot name the type. @@ -98,14 +108,14 @@ The target marker is `IsNothing` and the constraint on the reported source marke swapped relative to `BuildField`. Since `Mapper` is an *output* of the primitive, constraining it selects only those partial types whose field is currently set. -The primitive's signature is what makes one trait serve both directions: `update_field` takes the new +The primitive's signature makes one trait serve both directions: `update_field` takes the new storage in and hands the old storage back, so under this transition it takes `()` in and hands the real value back. -**Its heaviest user is [`CanBuildFrom`](./can_build_from.md).** That recursion walks the source's field +**Its heaviest user is [`CanBuildFrom`](../casting/can_build_from.md).** That recursion walks the source's field list, taking each field out with `take_field` and writing it into the target with [`build_field`](./build_field.md), threading the shrinking source and the growing target through — which -is why a merge needs [`HasFields`](./has_fields.md) on the source as well as a builder. +is why a merge needs [`HasFields`](../shape/has_fields.md) on the source as well as a builder. ## Common Mistakes @@ -132,12 +142,12 @@ variable. - [`BuildField`](./build_field.md) — the opposite direction. - [`UpdateField`](./update_field.md) — the primitive both are built from. - [`IntoBuilder`](./into_builder.md) — how a complete value becomes a partial one to take from. -- [`CanBuildFrom`](./can_build_from.md) — the merge that uses this internally. +- [`CanBuildFrom`](../casting/can_build_from.md) — the merge that uses this internally. - [`FinalizeBuild`](./finalize_build.md) — what a remainder cannot satisfy until the field is restored. - [`HasBuilder`](./has_builder.md) — the family's entry point. -- [`MapType`](./map_type.md) — the `IsPresent`/`IsNothing` markers this moves between. -- [`ToFields`](./to_fields.md) — the flat-shape alternative to decomposing a partial value. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the `UpdateField` impls behind +- [`MapType`](../type-level/map_type.md) — the `IsPresent`/`IsNothing` markers this moves between. +- [`ToFields`](../shape/to_fields.md) — the flat-shape alternative to decomposing a partial value. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the `UpdateField` impls behind it. The ideas behind it: diff --git a/docs/reference/traits/update_field.md b/docs/reference/traits/builder/update_field.md similarity index 68% rename from docs/reference/traits/update_field.md rename to docs/reference/traits/builder/update_field.md index ea6f1f61..b2fc828c 100644 --- a/docs/reference/traits/update_field.md +++ b/docs/reference/traits/builder/update_field.md @@ -1,5 +1,6 @@ --- sidebar_label: 'UpdateField' +sidebar_position: 5 --- # `UpdateField` @@ -11,7 +12,7 @@ The primitive that moves one field of a partial record between states. ### Generated machinery **You are not expected to call `update_field` directly.** It is the per-field -primitive [`#[derive(BuildField)]`](../derives/derive_build_field.md) emits, and +primitive [`#[derive(BuildField)]`](../../derives/derive_build_field.md) emits, and [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are the two directions you actually call. This page explains the primitive, because it is what makes build order free and what the optional-field layer reaches for when neither direction fits. @@ -21,8 +22,15 @@ optional-field layer reaches for when neither direction fits. ## Overview Everything in the [builder family](./has_builder.md) reduces to one operation: change one field's storage -from one [`MapType`](./map_type.md) marker to another, and hand back what was there before. -`UpdateField` is that operation: +from one [`MapType`](../type-level/map_type.md) marker to another, and hand back what was there before. +`UpdateField` is that operation. [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are +library blanket impls over it, each pinning one transition, which is why the derive writes this general +form once per field. + +## Definition + +`UpdateField` is parameterized by the field's `Tag` and a target marker `M`, and carries three associated +types and one method: ```rust pub trait UpdateField { @@ -38,28 +46,27 @@ pub trait UpdateField { } ``` -The `Map<…>` wrappers are the field's value *as stored* under each marker: `IsPresent` stores the value -itself, `IsNothing` stores `()`. So setting an absent field takes the real value in and hands `()` back, -and removing a present one takes `()` in and hands the real value back — one signature covering both -directions. +`Tag` names the field, and `M` is the [`MapType`](../type-level/map_type.md) marker the field should end +in. `Value` is the field's declared type, stripped of any marker. `Mapper` is the marker the field was in +*before* the call, which the impl reports rather than requires. `Output` is the partial type with that one +field now in state `M`. -**This is what the derive actually writes.** [`BuildField`](./build_field.md) and -[`TakeField`](./take_field.md) are library blanket impls over it, each pinning one transition, which is -why the general form is the one generated per field. +Both the `value` argument and the first component the method returns are *marker projections* rather than +bare values. `M::Map` is the field's value as stored under the target marker, and +`::Map` is how it was stored before. `IsPresent` stores the value +itself and `IsNothing` stores `()`, so setting an absent field takes the real value in and hands `()` +back, and removing a present one takes `()` in and hands the real value back. One signature covers both +directions. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -Reading the associated types is most of using it. `Value` is the field's declared type, stripped of any -marker; `Mapper` is the marker the field was in *before* the call, which the impl reports rather than -requires; and `Output` is the partial type with that one field now in `M`. - -The `M` parameter is the target marker and is usually inferred from the value you pass — supplying a +The `M` parameter is the target marker, and it is usually inferred from the value you pass: supplying a `String` where the field's type is `String` means `M = IsPresent`, and supplying `()` means `M = IsNothing`. -The impls come from [`#[derive(BuildField)]`](../derives/derive_build_field.md), one per field. +The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), one per field. ## Examples @@ -95,9 +102,9 @@ call site. - **[`BuildField`](./build_field.md)** for `IsNothing → IsPresent`, which is setting a field. - **[`TakeField`](./take_field.md)** for `IsPresent → IsNothing`, which is removing one. -- **`UpdateField`** for anything else — a transition to or from `IsOptional`, which is what the - [optional-field extensions](./set_optional.md) do, or a transform's intermediate steps. -- **[`TransformMapFields`](./transform_map_fields.md)** when *every* field changes state rather than one. +- **`UpdateField`** for anything else — a transition to or from `IsOptional`, which the + [optional-field extensions](../optional/set_optional.md) do, or a transform's intermediate steps. +- **[`TransformMapFields`](../type-level/transform_map_fields.md)** when *every* field changes state rather than one. It calls this twice per field internally, and reaching for `UpdateField` in a loop is re-implementing it. @@ -121,7 +128,7 @@ impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> passes through untouched. That is precisely why fields can be built in any order: no impl cares about the other fields' states. -`Mapper` being an *output* rather than an input is what lets the two directional traits pin a transition +Because `Mapper` is an *output* rather than an input, the two directional traits can pin a transition by constraining it. [`BuildField`](./build_field.md) is a blanket impl over `UpdateField` and [`TakeField`](./take_field.md) over `UpdateField` — same primitive, opposite constraints. @@ -141,7 +148,7 @@ backwards makes a bound resolve to the wrong impl or none at all. fine, but the shape catches people expecting the builder alone. **It changes one field.** For a whole-record transition, use -[`TransformMapFields`](./transform_map_fields.md). +[`TransformMapFields`](../type-level/transform_map_fields.md). **Reaching for it where [`BuildField`](./build_field.md) would do makes the code harder to read** for no gain. The directional traits exist because they say what is happening. @@ -156,12 +163,12 @@ with the tag fully expanded rather than saying the field does not exist. - [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — where a partial value comes from. - [`FinalizeBuild`](./finalize_build.md) — where one ends up. -- [`MapType`](./map_type.md) — the markers a field moves between. -- [`TransformMapFields`](./transform_map_fields.md) — the whole-record form, which calls this twice per +- [`MapType`](../type-level/map_type.md) — the markers a field moves between. +- [`TransformMapFields`](../type-level/transform_map_fields.md) — the whole-record form, which calls this twice per field. -- [`SetOptional`](./set_optional.md) — a transition this covers and the directional traits do not. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the per-field impls. -- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that name a field. +- [`SetOptional`](../optional/set_optional.md) — a transition this covers and the directional traits do not. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the per-field impls. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that name a field. The ideas behind it: diff --git a/docs/reference/traits/casting/_category_.json b/docs/reference/traits/casting/_category_.json new file mode 100644 index 00000000..da0759cc --- /dev/null +++ b/docs/reference/traits/casting/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Structural casts", + "position": 7, + "link": { + "type": "doc", + "id": "reference/traits/casting/index" + } +} diff --git a/docs/reference/traits/can_build_from.md b/docs/reference/traits/casting/can_build_from.md similarity index 70% rename from docs/reference/traits/can_build_from.md rename to docs/reference/traits/casting/can_build_from.md index 1bf3b9dc..588e28cc 100644 --- a/docs/reference/traits/can_build_from.md +++ b/docs/reference/traits/casting/can_build_from.md @@ -1,5 +1,6 @@ --- sidebar_label: 'CanBuildFrom' +sidebar_position: 4 --- # `CanBuildFrom` @@ -20,13 +21,9 @@ back, so several sources can be absorbed in sequence before the result is finali That is the merge step of the extensible builder pattern: independent parts of a program each produce a record, and the target absorbs all of them without any of them naming it. -## Usage +## Definition -**It is not in the prelude.** Import it from `cgp::core::field::impls`: - -```rust -use cgp::core::field::impls::CanBuildFrom; -``` +`CanBuildFrom` is parameterized by the source record, with an `Output` type and one method: ```rust pub trait CanBuildFrom { @@ -36,10 +33,20 @@ pub trait CanBuildFrom { } ``` -`Self` is the builder, which is why the call reads `Target::builder().build_from(source)`. `Output` is -the updated builder — **not** the finished struct, which is what lets a second `build_from` follow. +`Self` is the builder, not the target type, which is why the call reads +`Target::builder().build_from(source)`. `Source` is the record being copied from, taken by value. +`Output` is the updated builder rather than the finished struct, which lets a second `build_from` follow +before a finalize. + +## Usage + +**It is not in the prelude.** Import it from `cgp::core::field::impls`: + +```rust +use cgp::core::field::impls::CanBuildFrom; +``` -**The source needs [`HasFields`](./has_fields.md) as well as a builder**, because the recursion walks the +**The source needs [`HasFields`](../shape/has_fields.md) as well as a builder**, because the recursion walks the source's field list to know what to copy. The target needs only its builder. Deriving the same thing on both looks symmetric and does not compile, which is the mistake this trait causes most often. @@ -76,14 +83,14 @@ let employee = Employee::builder() ## When to use it **Reach for it when a record is assembled from independent pieces.** That is the extensible builder -pattern's merge step, and it is what the trait exists for. +pattern's merge step, and the reason the trait exists. - **Prefer a struct literal** when one place knows every field. A literal is already checked for completeness, reads better, and generates nothing. - **Prefer a plain `From` impl** when the two types are yours and the conversion is one you would write once. This trait earns its keep when the conversion must be *derived* from names rather than written. -- **Reach for [`CanBuildWithDefault`](./can_build_with_default.md)** when the target has fields the source - does not cover and their defaults are acceptable — it chains `builder()`, `build_from`, and a defaulted +- **Reach for [`CanBuildWithDefault`](../optional/can_build_with_default.md)** when the target has fields the source + does not cover and their defaults are acceptable: it chains `builder()`, `build_from`, and a defaulted finalize into one call. - **Reach for [`CanUpcast`](./can_upcast.md)** for the enum analogue. @@ -93,12 +100,12 @@ machinery, the names must match exactly, and nothing is inspected at run time. ## Under the hood `CanBuildFrom` **recurses over the source's field product.** For each field the source exposes, it uses -[`TakeField`](./take_field.md) to remove that value from the source and [`BuildField`](./build_field.md) +[`TakeField`](../builder/take_field.md) to remove that value from the source and [`BuildField`](../builder/build_field.md) to write it into the target builder, threading both the shrinking source and the growing builder through the walk. -When the source's fields run out, the builder is returned — **not finalized**, which is exactly what -lets a second `build_from` follow, and why `Output` is a builder type rather than the target struct. +When the source's fields run out, the builder is returned, **not finalized**, which lets a second +`build_from` follow and is why `Output` is a builder type rather than the target struct. One asymmetry in the source is worth knowing if you read it: this recursion, `FieldsBuilder`, is **private**, while the variant casts' `FieldsExtractor` is public. So the extractor recursion can appear @@ -108,12 +115,12 @@ by name in a diagnostic and be named in a bound; this one cannot. **It is not in the prelude.** Import from `cgp::core::field::impls`. -**The source needs [`HasFields`](./has_fields.md), not just a builder.** Deriving only -[`BuildField`](../derives/derive_build_field.md) on both structs looks symmetric and fails; the error is +**The source needs [`HasFields`](../shape/has_fields.md), not just a builder.** Deriving only +[`BuildField`](../../derives/derive_build_field.md) on both structs looks symmetric and fails; the error is an unsatisfied `HasFields` bound on the source type. **It is called on the builder, not the target.** `Target::builder().build_from(source)`, and the result -is a builder you still have to [finalize](./finalize_build.md). +is a builder you still have to [finalize](../builder/finalize_build.md). **Field names are the whole interface.** Renaming a field in one struct silently stops it being copied, and the failure surfaces at `finalize_build` — a missing-method error — rather than at the rename. @@ -125,14 +132,14 @@ an extra field on the source is simply dropped. ## Related constructs -- [`HasBuilder`](./has_builder.md) — where a builder comes from, and the family this belongs to. -- [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) — the two primitives the recursion +- [`HasBuilder`](../builder/has_builder.md) — where a builder comes from, and the family this belongs to. +- [`BuildField`](../builder/build_field.md) and [`TakeField`](../builder/take_field.md) — the two primitives the recursion routes through. -- [`FinalizeBuild`](./finalize_build.md) — how the resulting builder becomes a struct. -- [`HasFields`](./has_fields.md) — the shape the walk reads, and what the source must derive. -- [`CanBuildWithDefault`](./can_build_with_default.md) — merge plus a defaulted finalize, in one call. +- [`FinalizeBuild`](../builder/finalize_build.md) — how the resulting builder becomes a struct. +- [`HasFields`](../shape/has_fields.md) — the shape the walk reads, and what the source must derive. +- [`CanBuildWithDefault`](../optional/can_build_with_default.md) — merge plus a defaulted finalize, in one call. - [`CanUpcast`](./can_upcast.md) — the enum counterpart. -- [`#[derive(CgpRecord)]`](../derives/derive_cgp_record.md) — what makes a struct eligible. +- [`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md) — what makes a struct eligible. The ideas behind it: diff --git a/docs/reference/traits/can_downcast.md b/docs/reference/traits/casting/can_downcast.md similarity index 72% rename from docs/reference/traits/can_downcast.md rename to docs/reference/traits/casting/can_downcast.md index 22b1974c..531f974a 100644 --- a/docs/reference/traits/can_downcast.md +++ b/docs/reference/traits/casting/can_downcast.md @@ -1,5 +1,6 @@ --- sidebar_label: 'CanDowncast' +sidebar_position: 2 --- # `CanDowncast` @@ -9,26 +10,20 @@ Narrowing a wide enum into a smaller one, or handing back what is left. ## Overview Converting a wide enum into a narrower one is the direction that can fail: the value's current variant -may be one the target does not have. `CanDowncast` attempts that conversion, and what makes it more than -a fallible `From` is what it returns on failure. +may be one the target does not have. `CanDowncast` attempts that conversion, and it does more than +a fallible `From` because of what it returns on failure. **A failed downcast hands back a *remainder* rather than an error.** The remainder is the same value with -the attempted variants ruled out *in its type*, so it can be tried against another target — and each -attempt narrows what remains. That is what lets a value be routed through a chain of candidate targets -with the compiler tracking, at every step, which variants are still possible. +the attempted variants ruled out *in its type*, so it can be tried against another target, and each +attempt narrows what remains. That lets a value travel through a chain of candidate targets +while the compiler tracks, at every step, which variants are still possible. The narrowing counterpart of [`CanUpcast`](./can_upcast.md), which always succeeds because a wider target has a home for everything. -## Usage +## Definition -**It is not in the prelude.** Import it from `cgp::core::field::impls`, with -`core::marker::PhantomData` for naming the target: - -```rust -use cgp::core::field::impls::CanDowncast; -use core::marker::PhantomData; -``` +`CanDowncast` is parameterized by the target enum, with a fallible method and a `Remainder` type: ```rust pub trait CanDowncast { @@ -38,9 +33,21 @@ pub trait CanDowncast { } ``` -`Ok` carries the narrowed value. `Err` carries the source's extractor with the target's variants removed -— which is exactly what [`CanDowncastFields`](./can_downcast_fields.md) is called on to continue the -chain. `Self` is the wide enum, consumed. +`Self` is the wide enum and `Target` the narrower one. The method takes `self` by value and returns +`Result`: `Ok` carries the narrowed value, and `Err` carries the source's extractor +with the target's variants removed. `Remainder` is that leftover extractor type, and it is the value you +pass to [`CanDowncastFields`](./can_downcast_fields.md) to continue a chain against another candidate. The +`PhantomData` argument names the target for inference. + +## Usage + +**It is not in the prelude.** Import it from `cgp::core::field::impls`, with +`core::marker::PhantomData` for naming the target: + +```rust +use cgp::core::field::impls::CanDowncast; +use core::marker::PhantomData; +``` ## Examples @@ -86,7 +93,7 @@ first starts the chain and the second continues it on each remainder. - **Prefer a plain `TryFrom` impl** when both types are yours and the conversion is one you would write once. Nothing about a hand-written impl needs either type to derive anything. - **Reach for [`CanUpcast`](./can_upcast.md)** for the widening direction, which cannot fail. -- **Reach for the [extractor family](./extract_field.md)** when you want to handle *every* variant rather +- **Reach for the [extractor family](../variant/extract_field.md)** when you want to handle *every* variant rather than convert to another enum. A downcast chain and an extraction chain narrow the same way; the difference is whether each step produces another enum or a payload. @@ -95,14 +102,14 @@ first starts the chain and the second continues it on each remainder. **The downcasts recurse over the *target's* variants**, which is the mirror image of [`CanUpcast`](./can_upcast.md#under-the-hood) walking the source's. For each `Field` in `Target::Fields`, the implementation tries pulling that variant out of the source extractor: on success -it rebuilds the target with [`FromVariant`](./from_variant.md) and returns `Ok`; on failure it threads the +it rebuilds the target with [`FromVariant`](../variant/from_variant.md) and returns `Ok`; on failure it threads the shrunken remainder into the next attempt. If no target variant matches, the terminal `Void` impl returns the whole remainder as `Err`. `CanDowncast` differs from [`CanDowncastFields`](./can_downcast_fields.md) only in where the walk starts: -this one calls [`to_extractor`](./has_extractor.md) on the enum first, while that one operates on an -extractor it is handed. That is the entire reason two traits exist rather than one, and it is what makes -chaining possible — the `Remainder` a `downcast` returns is precisely a `downcast_fields` input. +this one calls [`to_extractor`](../variant/has_extractor.md) on the enum first, while that one operates on an +extractor it is handed. That is the entire reason two traits exist rather than one, and it makes +chaining possible: the `Remainder` a `downcast` returns is precisely a `downcast_fields` input. ## Common Mistakes @@ -126,12 +133,12 @@ stored where the original was. - [`CanDowncastFields`](./can_downcast_fields.md) — the continuation, called on each remainder. - [`CanUpcast`](./can_upcast.md) — the widening direction, which cannot fail. - [`CanBuildFrom`](./can_build_from.md) — the record counterpart of casting. -- [`ExtractField`](./extract_field.md) — the primitive each attempt uses, and the family that narrows the +- [`ExtractField`](../variant/extract_field.md) — the primitive each attempt uses, and the family that narrows the same way to a payload. -- [`HasExtractor`](./has_extractor.md) — where the walk starts. -- [`FromVariant`](./from_variant.md) — how a matched variant is rebuilt into the target. -- [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) — what makes an enum eligible. -- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain underneath. +- [`HasExtractor`](../variant/has_extractor.md) — where the walk starts. +- [`FromVariant`](../variant/from_variant.md) — how a matched variant is rebuilt into the target. +- [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) — what makes an enum eligible. +- [Type-level spines](../../types/type_level_spines.md) — the `Either`/`Void` chain underneath. The ideas behind it: diff --git a/docs/reference/traits/can_downcast_fields.md b/docs/reference/traits/casting/can_downcast_fields.md similarity index 74% rename from docs/reference/traits/can_downcast_fields.md rename to docs/reference/traits/casting/can_downcast_fields.md index f662bb03..4c08d07b 100644 --- a/docs/reference/traits/can_downcast_fields.md +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -1,5 +1,6 @@ --- sidebar_label: 'CanDowncastFields' +sidebar_position: 3 --- # `CanDowncastFields` @@ -8,9 +9,9 @@ Continuing a narrowing chain on a remainder. ## Overview -[`CanDowncast`](./can_downcast.md) narrows an enum and, when it fails, hands back a *remainder* — the -same value with the attempted variants ruled out in its type. `CanDowncastFields` is what that remainder -is then passed to, so a value can be tried against a second target, a third, and so on. +[`CanDowncast`](./can_downcast.md) narrows an enum and, when it fails, hands back a *remainder*: the +same value with the attempted variants ruled out in its type. You then pass that remainder to +`CanDowncastFields`, so a value can be tried against a second target, a third, and so on. The two traits do the same narrowing and differ in one thing: **where the walk starts**. `CanDowncast` is called on an enum and converts it to an extractor first; `CanDowncastFields` is called on an extractor @@ -19,15 +20,9 @@ it is already given. Since a remainder *is* an extractor, that is exactly the sh **So the pair is the construct, and this half is never used alone.** A chain reads as one `downcast` followed by one `downcast_fields` per additional candidate. -## Usage +## Definition -**It is not in the prelude.** Import it from `cgp::core::field::impls`, alongside `CanDowncast`, which -you will always be using with it: - -```rust -use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; -use core::marker::PhantomData; -``` +`CanDowncastFields` has the same signature as [`CanDowncast`](./can_downcast.md): ```rust pub trait CanDowncastFields { @@ -37,9 +32,19 @@ pub trait CanDowncastFields { } ``` -The signature is `CanDowncast`'s exactly. `Self` here is a remainder rather than an enum, and the -`Remainder` it returns is narrower again — so each call in a chain has a different, progressively -smaller `Self` type. +`Target` is the enum being narrowed to. `Self` here is a *remainder* rather than an enum, and the method +takes it by value, returning `Result` just as `downcast` does. The returned +`Remainder` is narrower again, so each call in a chain has a different, progressively smaller `Self` type. + +## Usage + +**It is not in the prelude.** Import it from `cgp::core::field::impls`, alongside `CanDowncast`, which +you will always be using with it: + +```rust +use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; +use core::marker::PhantomData; +``` ## Examples @@ -89,9 +94,9 @@ use: its `Self` is a remainder, and a remainder only ever comes from a prior dow - **Use one `downcast` and then one `downcast_fields` per further candidate.** That is the whole pattern. -- **Prefer the [extractor family](./extract_field.md)** when what you want is the *payload* of whichever +- **Prefer the [extractor family](../variant/extract_field.md)** when what you want is the *payload* of whichever variant is present rather than another enum. It narrows identically and ends with a checked, - wildcard-free discharge through [`FinalizeExtract`](./finalize_extract.md). + wildcard-free discharge through [`FinalizeExtract`](../variant/finalize_extract.md). - **Prefer a `match`** when the enum is concrete and the candidates are few. A cast chain earns its keep when the targets are type parameters or the chain is long. @@ -100,12 +105,12 @@ use: its `Self` is a remainder, and a remainder only ever comes from a prior dow Both traits walk the *target's* variant list, trying to pull each one out of the extractor they hold and threading the shrunken remainder into the next attempt, with the terminal `Void` impl returning the whole remainder as `Err`. The only difference is the entry point: `CanDowncast` calls -[`to_extractor`](./has_extractor.md) on an enum to obtain the extractor, and this trait takes one it is +[`to_extractor`](../variant/has_extractor.md) on an enum to obtain the extractor, and this trait takes one it is handed. Because the remainder type narrows at every step, a chain's types are all distinct, and the compiler knows at each point exactly which variants remain — the same narrowing a hand-written -[extraction chain](./extract_field.md) performs. +[extraction chain](../variant/extract_field.md) performs. ## Common Mistakes @@ -121,16 +126,16 @@ attempt needs. `PartialEq`. **Each step has a different `Self` type**, so a chain cannot be written as a loop or collected into a -`Vec` of attempts — it is unrolled by construction. +`Vec` of attempts: it is unrolled by construction. ## Related constructs - [`CanDowncast`](./can_downcast.md) — the first step, and where the pair is explained in full. - [`CanUpcast`](./can_upcast.md) — the widening direction. -- [`ExtractField`](./extract_field.md) — narrowing to a payload rather than to another enum. -- [`FinalizeExtract`](./finalize_extract.md) — how an exhausted remainder is discharged. -- [`HasExtractor`](./has_extractor.md) — what turns an enum into the extractor this operates on. -- [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) — what makes an enum eligible. +- [`ExtractField`](../variant/extract_field.md) — narrowing to a payload rather than to another enum. +- [`FinalizeExtract`](../variant/finalize_extract.md) — how an exhausted remainder is discharged. +- [`HasExtractor`](../variant/has_extractor.md) — what turns an enum into the extractor this operates on. +- [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) — what makes an enum eligible. The ideas behind it: diff --git a/docs/reference/traits/can_upcast.md b/docs/reference/traits/casting/can_upcast.md similarity index 76% rename from docs/reference/traits/can_upcast.md rename to docs/reference/traits/casting/can_upcast.md index 59610984..1c089008 100644 --- a/docs/reference/traits/can_upcast.md +++ b/docs/reference/traits/casting/can_upcast.md @@ -1,5 +1,6 @@ --- sidebar_label: 'CanUpcast' +sidebar_position: 1 --- # `CanUpcast` @@ -13,7 +14,7 @@ say. Converting the narrow one into the wide one is a conversion you could write pure boilerplate: one `match` arm per variant, rewrapping each payload under the same name. `CanUpcast` derives that conversion from the names instead. Once both enums expose their shape as a -type-level list — which [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) makes them — widening is a +type-level list — which [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) makes them — widening is a matter of routing each source variant to the target's slot of the same name. **It always succeeds.** Every variant of the source has a home in the target, or the conversion does not @@ -21,6 +22,22 @@ type-check at all, so `upcast` returns the target directly rather than a `Result difference between this trait and its narrowing counterpart, [`CanDowncast`](./can_downcast.md). +## Definition + +`CanUpcast` is a one-method trait parameterized by the target enum: + +```rust +pub trait CanUpcast { + fn upcast(self, _tag: PhantomData) -> Target; +} +``` + +`Self` is the narrow enum and `Target` the wider one. The method takes `self` by value and consumes it, +returning the `Target` directly rather than a `Result`, because a widening cannot fail. The +`PhantomData` argument names the target for inference and carries no data. Both enums must derive +the extensible-data machinery, and the target's variant set must include every one of the source's, +matched by name and by payload type. + ## Usage **It is not in the prelude.** Import it from `cgp::core::field::impls`, and bring @@ -32,18 +49,6 @@ use cgp::core::field::impls::CanUpcast; use core::marker::PhantomData; ``` -The trait itself is one method: - -```rust -pub trait CanUpcast { - fn upcast(self, _tag: PhantomData) -> Target; -} -``` - -`Self` is the narrow enum, consumed; `Target` is the wider one. Both must derive the extensible-data -machinery, and the target's variant set must include every one of the source's — matched by name and by -payload type. - ## Examples Two independently-defined enums that share variant names interconvert with no manual impl: @@ -95,12 +100,12 @@ has not derived the machinery cannot participate at all. ## Under the hood `CanUpcast` **recurses over the source's variants**. It converts the source to its extractor with -[`HasExtractor`](./has_extractor.md), then walks the source's own field list, pulling each variant out -with [`ExtractField`](./extract_field.md) and rebuilding it into the target with -[`FromVariant`](./from_variant.md). +[`HasExtractor`](../variant/has_extractor.md), then walks the source's own field list, pulling each variant out +with [`ExtractField`](../variant/extract_field.md) and rebuilding it into the target with +[`FromVariant`](../variant/from_variant.md). -Because every source variant is guaranteed to exist in a wider target, the walk is total — and the -extractor left at the end is uninhabited, discharged with [`FinalizeExtract`](./finalize_extract.md). +Because every source variant is guaranteed to exist in a wider target, the walk is total, and the +extractor left at the end is uninhabited, discharged with [`FinalizeExtract`](../variant/finalize_extract.md). That is precisely why `upcast` returns the target directly instead of a `Result`. One detail from the source is worth knowing if you read it: the recursion driving this, @@ -113,7 +118,7 @@ record-side analogue `FieldsBuilder`, behind [`CanBuildFrom`](./can_build_from.m wrong. **An upcast is total only if the target really is wider.** If the target lacks one of the source's -variants there is no impl, and the failure is an unsatisfied bound rather than a runtime error — which is +variants there is no impl, and the failure is an unsatisfied bound rather than a runtime error. That is the guarantee, but it reads as a puzzling missing-impl message until you check the variant lists. **Names must match exactly.** Renaming a variant in one enum silently removes it from the overlap, and @@ -129,13 +134,13 @@ value type are both part of the entry. - [`CanDowncast`](./can_downcast.md) — the narrowing direction, which can fail. - [`CanDowncastFields`](./can_downcast_fields.md) — narrowing continued on a remainder. - [`CanBuildFrom`](./can_build_from.md) — the record counterpart. -- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) and - [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) — what makes an enum eligible. -- [`ExtractField`](./extract_field.md) and [`FromVariant`](./from_variant.md) — the two primitives the +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) and + [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) — what makes an enum eligible. +- [`ExtractField`](../variant/extract_field.md) and [`FromVariant`](../variant/from_variant.md) — the two primitives the recursion routes through. -- [`HasFields`](./has_fields.md) — the variant shape being walked. -- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain underneath. -- [Dispatch combinators](../providers/dispatch/index.md) — where casting meets per-variant routing. +- [`HasFields`](../shape/has_fields.md) — the variant shape being walked. +- [Type-level spines](../../types/type_level_spines.md) — the `Either`/`Void` chain underneath. +- [Dispatch combinators](../../providers/dispatch/index.md) — where casting meets per-variant routing. The ideas behind it: diff --git a/docs/reference/traits/casting/index.md b/docs/reference/traits/casting/index.md new file mode 100644 index 00000000..8813082e --- /dev/null +++ b/docs/reference/traits/casting/index.md @@ -0,0 +1,36 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Structural casts + +Converting between two data types by their shared fields or variants, with no hand-written conversion. + +## Overview + +Two types that share a subset of named fields or variants can convert into one another generically, +without a hand-written `From` or `TryFrom`. Because CGP represents each record as a product of named +fields and each enum as a sum of named variants, a conversion becomes a matter of routing each named +entry to the target's slot of the same name. Both types must derive the extensible-data machinery, and +the names are matched at the type level. None of these traits is in the prelude — import each from +`cgp::core::field::impls`. + +The four cover the directions that routing can take. + +For **enums**, [`CanUpcast`](can_upcast.md) widens a value into an enum whose variants are a superset, +which always succeeds, and [`CanDowncast`](can_downcast.md) narrows into a smaller enum, which can fail +and hands back a remainder. [`CanDowncastFields`](can_downcast_fields.md) continues a narrowing chain on +that remainder against a further candidate. + +For **records**, [`CanBuildFrom`](can_build_from.md) fills a builder with every field it shares with +another record, so several sources can be merged into one target before it is finalized. + +## The ideas behind them + +- [Extensible variants](/docs/concepts/extensible-variants) — upcasting and downcasting between enums. +- [Extensible records](/docs/concepts/extensible-records) — merging records through a builder. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field-access/_category_.json b/docs/reference/traits/field-access/_category_.json new file mode 100644 index 00000000..095e851d --- /dev/null +++ b/docs/reference/traits/field-access/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Field access", + "position": 2, + "link": { + "type": "doc", + "id": "reference/traits/field-access/index" + } +} diff --git a/docs/reference/traits/field_getter.md b/docs/reference/traits/field-access/field_getter.md similarity index 64% rename from docs/reference/traits/field_getter.md rename to docs/reference/traits/field-access/field_getter.md index 57c830f5..2bc467bd 100644 --- a/docs/reference/traits/field_getter.md +++ b/docs/reference/traits/field-access/field_getter.md @@ -1,5 +1,6 @@ --- sidebar_label: 'FieldGetter' +sidebar_position: 3 --- # `FieldGetter` @@ -11,8 +12,8 @@ The provider-side mirror of `HasField` — field access that gets wired. ### Generated machinery **You are not expected to implement `FieldGetter`.** -[`#[cgp_getter]`](../macros/cgp_getter.md) generates it as the getter's provider trait, and -[`UseField`](../providers/use_field.md) is the provider you wire to satisfy it. What you write is the +[`#[cgp_getter]`](../../macros/cgp_getter.md) generates it as the getter's provider trait, and +[`UseField`](../../providers/use_field.md) is the provider you wire to satisfy it. What you write is the wiring entry; this page explains the shape that entry resolves through. The one case for implementing it by hand is a getter whose value is computed rather than stored. ::: @@ -24,7 +25,16 @@ access should instead be **chosen by wiring**, so that a context decides which o given getter. That needs the provider-trait shape: the context as an explicit type argument rather than as `&self`. -`FieldGetter` is that shape: +`FieldGetter` is that shape. This is the ordinary consumer/provider duality applied to field access: +**you bound against [`HasField`](./has_field.md), and you wire `FieldGetter`**. They are not alternatives. + +[`UseField`](../../providers/use_field.md) is the provider that implements it by reading a named field, +and [`#[cgp_getter]`](../../macros/cgp_getter.md) targets it. + +## Definition + +`FieldGetter` is the provider-trait mirror of [`HasField`](./has_field.md), with the context +as an explicit type argument instead of `&self`: ```rust pub trait FieldGetter { @@ -34,12 +44,10 @@ pub trait FieldGetter { } ``` -`Self` is the **provider** — a zero-sized marker carrying no data — while `Context` is the type the field -is read from. This is the ordinary consumer/provider duality applied to field access: **you bound against -[`HasField`](./has_field.md), and you wire `FieldGetter`**. They are not alternatives. - -[`UseField`](../providers/use_field.md) is the provider that implements it by reading a named field, and -it is what [`#[cgp_getter]`](../macros/cgp_getter.md) targets. +`Self` is the **provider**, a zero-sized marker carrying no data, and `Context` is the type the field is +read from. `Tag` names the field, exactly as it does on `HasField`, and `Value` is the field's type. +`get_field` takes the context by shared reference and returns `&Self::Value`, with the `PhantomData` +argument disambiguating which field is meant. ## Usage @@ -56,7 +64,7 @@ delegate_components! { } ``` -Reading it back: the getter component is answered by [`UseField`](../providers/use_field.md), which +Reading it back: the getter component is answered by [`UseField`](../../providers/use_field.md), which implements `FieldGetter` by reading the `first_name` field — a field whose name need not match the getter's method name, which is the whole point of wiring the access rather than deriving it. @@ -89,19 +97,19 @@ delegate_components! { `person.name()` now returns the `first_name` field. **Value context, self-targeted.** -A second context can answer the same getter from a different field by changing one wiring line, which is -what the provider-side shape buys and what a plain [`HasField`](./has_field.md) bound cannot express. +A second context can answer the same getter from a different field by changing one wiring line, which +the provider-side shape buys and a plain [`HasField`](./has_field.md) bound cannot express. ## When to use it **Wire a `FieldGetter` only when a context must choose which field a getter reads**, which is the advanced case. Everything else is better served higher up. -- **Use an [`#[implicit]`](../attributes/implicit.md) argument** for a field an implementation reads from +- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** for a field an implementation reads from its own context. It generates a [`HasField`](./has_field.md) bound and involves no provider at all. -- **Use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md)** when the read must be a named capability, +- **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a named capability, keyed by the method name. It generates a blanket impl over `HasField` and needs no wiring. -- **Use [`#[cgp_getter]`](../macros/cgp_getter.md)** when the source field must be chosen per context. +- **Use [`#[cgp_getter]`](../../macros/cgp_getter.md)** when the source field must be chosen per context. That is what makes the getter a full component with a `FieldGetter` provider trait, and it costs a wiring line per context. - **Reach for [`MutFieldGetter`](./mut_field_getter.md)** when the wired access must also mutate. @@ -112,7 +120,7 @@ requires; the other is what a context supplies. ## Under the hood The provider side connects to ordinary derived field access through one blanket impl: -[`UseContext`](../providers/use_context.md) implements `FieldGetter` for any context that already has the +[`UseContext`](../../providers/use_context.md) implements `FieldGetter` for any context that already has the field, delegating straight through. ```rust @@ -129,13 +137,13 @@ where ``` So wiring a getter to `UseContext` means "read the field of the same name off the context", which is the -behaviour [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) gives without any wiring. +behaviour [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) gives without any wiring. -[`UseField`](../providers/use_field.md) is the more interesting provider: it fixes the tag at the +[`UseField`](../../providers/use_field.md) is the more interesting provider: it fixes the tag at the wiring site, so the field it reads is decided there rather than by the method's name. The lifetime-safe variant [`FieldMapper`](./field_mapper.md) is a blanket impl over every `FieldGetter` -with the getter and tag `'static`, which is what [`ChainGetters`](../providers/chain_getters.md) relies +with the getter and tag `'static`, which [`ChainGetters`](../../providers/chain_getters.md) relies on. ## Common Mistakes @@ -149,27 +157,27 @@ instead of `HasField` is almost always a mistake: the implementation wants a req not a provider parameter. **The getter's method name and the field's name are independent once wired.** That is the feature, and it -means a reader cannot infer the field from the getter — the wiring line is the only place the answer +means a reader cannot infer the field from the getter: the wiring line is the only place the answer lives. -**A getter wired to [`UseContext`](../providers/use_context.md) needs the field to exist under the +**A getter wired to [`UseContext`](../../providers/use_context.md) needs the field to exist under the getter's own name**, since that impl keys on the tag it is given. **It returns a reference.** A getter that must produce an owned or computed value uses -[`MRef`](../types/mref.md) as its return type instead. +[`MRef`](../../types/mref.md) as its return type instead. ## Related constructs - [`HasField`](./has_field.md) — the consumer side you bound against. - [`MutFieldGetter`](./mut_field_getter.md) — the mutable extension of this trait. - [`FieldMapper`](./field_mapper.md) — the lifetime-safe form, for nested access. -- [`UseField`](../providers/use_field.md) — the provider that implements it by reading a named field. -- [`UseContext`](../providers/use_context.md) — the provider that routes back through the context's own +- [`UseField`](../../providers/use_field.md) — the provider that implements it by reading a named field. +- [`UseContext`](../../providers/use_context.md) — the provider that routes back through the context's own fields. -- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that makes a getter a full component. -- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — the simpler getter, keyed by method name. -- [`ChainGetters`](../providers/chain_getters.md) — composing getters to reach a nested field. -- [`MRef`](../types/mref.md) — the owned-or-borrowed return type for a getter that may produce its value. +- [`#[cgp_getter]`](../../macros/cgp_getter.md) — the macro that makes a getter a full component. +- [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) — the simpler getter, keyed by method name. +- [`ChainGetters`](../../providers/chain_getters.md) — composing getters to reach a nested field. +- [`MRef`](../../types/mref.md) — the owned-or-borrowed return type for a getter that may produce its value. The ideas behind it: diff --git a/docs/reference/traits/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md similarity index 73% rename from docs/reference/traits/field_mapper.md rename to docs/reference/traits/field-access/field_mapper.md index 20d3e989..f48afaa7 100644 --- a/docs/reference/traits/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -1,5 +1,6 @@ --- sidebar_label: 'FieldMapper' +sidebar_position: 6 --- # `FieldMapper` @@ -11,7 +12,7 @@ The provider-side mirror of `MapField`. ### Generated machinery **You will not call `map_field` yourself.** It is a blanket impl over every -[`FieldGetter`](./field_getter.md), and [`ChainGetters`](../providers/chain_getters.md) is its only +[`FieldGetter`](./field_getter.md), and [`ChainGetters`](../../providers/chain_getters.md) is its only caller in practice. This page explains the mechanism a chained getter is built from. The one case for calling it directly is writing a getter provider of your own that has to descend. ::: @@ -20,7 +21,21 @@ caller in practice. This page explains the mechanism a chained getter is built f [`MapField`](./map_field.md) reads through a field without forcing its type to be `'static`, by taking a higher-ranked closure instead of returning the intermediate borrow. `FieldMapper` is the same operation -in provider-trait shape, with the context as an explicit type argument rather than as `&self`: +in provider-trait shape, with the context as an explicit type argument rather than as `&self`. The +group's two-by-two shape holds here too: + +| | you bound against | you wire | +|---|---|---| +| plain read | [`HasField`](./has_field.md) | [`FieldGetter`](./field_getter.md) | +| read through | [`MapField`](./map_field.md) | `FieldMapper` | + +**This is the one [`ChainGetters`](../../providers/chain_getters.md) actually uses**, because a chained +getter is a provider composing other providers rather than a method on a concrete type. + +## Definition + +`FieldMapper` is the provider-trait mirror of [`MapField`](./map_field.md), with the context +as an explicit type argument instead of `&self`: ```rust pub trait FieldMapper: FieldGetter { @@ -32,17 +47,11 @@ pub trait FieldMapper: FieldGetter { } ``` -`Self` is the provider; `Context` is the type being read from. It is a supertrait extension of +`Self` is the provider and `Context` is the type being read from. It is a supertrait extension of [`FieldGetter`](./field_getter.md), exactly as [`MapField`](./map_field.md) extends -[`HasField`](./has_field.md) — so the group's two-by-two shape holds here too: - -| | you bound against | you wire | -|---|---|---| -| plain read | [`HasField`](./has_field.md) | [`FieldGetter`](./field_getter.md) | -| read through | [`MapField`](./map_field.md) | `FieldMapper` | - -**This is the one [`ChainGetters`](../providers/chain_getters.md) actually uses**, because a chained -getter is a provider composing other providers rather than a method on a concrete type. +[`HasField`](./has_field.md), so `Value` comes from the supertrait. `map_field` takes the context by +shared reference, the `PhantomData` that names the field, and a `mapper` closure whose higher-ranked +`for<'a>` bound ties the returned `&T` to the field's own lifetime. ## Usage @@ -53,8 +62,8 @@ use cgp::core::field::traits::FieldMapper; ``` **Nobody implements it.** It is a blanket impl for every [`FieldGetter`](./field_getter.md) with the -getter and the tag `'static`, so every field-getter provider gains `map_field` for free — which is -precisely what makes chaining composable without each provider opting in. +getter and the tag `'static`, so every field-getter provider gains `map_field` for free, which makes +chaining composable without each provider opting in. The `mapper` argument carries the same `for<'a>` binder as its consumer-side twin, and for the same reason: it lets the returned borrow be tied to the field borrow rather than to a fixed lifetime. @@ -88,8 +97,8 @@ delegate_components! { } ``` -**Environmental context, self-targeted.** [`ChainGetters`](../providers/chain_getters.md) descends into -`inner` with `FieldMapper::map_field` and then applies the inner provider to what it finds — so +**Environmental context, self-targeted.** [`ChainGetters`](../../providers/chain_getters.md) descends into +`inner` with `FieldMapper::map_field` and then applies the inner provider to what it finds, so `outer.name()` resolves to `outer.inner.name` with no lifetime obligations leaking into either type. Calling it directly is possible and rarely what you want: @@ -106,14 +115,14 @@ let name = >::map_field( ## When to use it -**Reach for [`ChainGetters`](../providers/chain_getters.md) rather than this trait.** It is the construct; +**Reach for [`ChainGetters`](../../providers/chain_getters.md) rather than this trait.** It is the construct; `FieldMapper` is the mechanism underneath it. -- **Use [`ChainGetters`](../providers/chain_getters.md)** to reach a field on a nested context by wiring. +- **Use [`ChainGetters`](../../providers/chain_getters.md)** to reach a field on a nested context by wiring. - **Use [`FieldGetter`](./field_getter.md)** when the wired access is a plain one-level read. - **Use [`MapField`](./map_field.md)** when the descent happens on `self` rather than on a wired context — the consumer-side twin. -- **Use an [`#[implicit]`](../attributes/implicit.md) argument** before any of them for a field of the +- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** before any of them for a field of the implementation's own context. Name it directly only when writing a getter provider of your own that must descend, and check first @@ -124,15 +133,15 @@ whether composing the existing ones does the job. `FieldMapper` is a blanket impl over every [`FieldGetter`](./field_getter.md), with two `'static` bounds that its consumer-side twin needs only one of: -- the **tag** must be `'static`, which is free — a [`Symbol!`](../macros/symbol.md) or an - [`Index`](../types/index.md) is `'static` by construction; +- the **tag** must be `'static`, which is free — a [`Symbol!`](../../macros/symbol.md) or an + [`Index`](../../types/index.md) is `'static` by construction; - the **getter** — that is, `Self`, the provider — must be `'static`, which is also free, since a provider is a zero-sized marker type with no lifetime parameters in the ordinary case. The field's *value* stays free of any bound, which is the whole point: it is the intermediate whose lifetime the naive chained read could not express. -[`ChainGetters`](../providers/chain_getters.md) composes descents by nesting `map_field` calls, one per +[`ChainGetters`](../../providers/chain_getters.md) composes descents by nesting `map_field` calls, one per path segment, so an arbitrarily deep chain stays lifetime-correct. Because the impl is blanket, adding a new getter provider makes it chainable with no extra work. @@ -152,19 +161,19 @@ ordinary zero-sized marker and not for one carrying a lifetime, which is a rare failure when it happens. **It cannot map to an owned value.** The signature returns `&T`; a getter that must produce a value uses -[`MRef`](../types/mref.md). +[`MRef`](../../types/mref.md). ## Related constructs - [`MapField`](./map_field.md) — the consumer-side twin, and where the lifetime problem is explained in full. - [`FieldGetter`](./field_getter.md) — the supertrait, and the plain wired read. -- [`ChainGetters`](../providers/chain_getters.md) — the provider that uses this to descend. +- [`ChainGetters`](../../providers/chain_getters.md) — the provider that uses this to descend. - [`HasField`](./has_field.md) — the consumer side of field access. -- [`UseField`](../providers/use_field.md) and [`UseContext`](../providers/use_context.md) — the two +- [`UseField`](../../providers/use_field.md) and [`UseContext`](../../providers/use_context.md) — the two providers a chain is usually built from. -- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags, `'static` by construction. -- [`MRef`](../types/mref.md) — the return type for a getter that may produce rather than lend. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags, `'static` by construction. +- [`MRef`](../../types/mref.md) — the return type for a getter that may produce rather than lend. The ideas behind it: diff --git a/docs/reference/traits/has_field.md b/docs/reference/traits/field-access/has_field.md similarity index 68% rename from docs/reference/traits/has_field.md rename to docs/reference/traits/field-access/has_field.md index ded89f7d..04e0dee3 100644 --- a/docs/reference/traits/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasField' +sidebar_position: 1 --- # `HasField` @@ -21,18 +22,18 @@ Self: HasField ``` Any context with a matching field satisfies that bound. Nothing is compared by string at run time — -[`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler resolves which field is meant and the +[`Symbol!("name")`](../../macros/symbol.md) is a type, so the compiler resolves which field is meant and the read compiles to a direct field access. This is the foundation the whole ergonomic surface stands on. An -[`#[implicit]`](../attributes/implicit.md) argument, a [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) -method, and a [`UseField`](../providers/use_field.md) wiring entry all generate this bound from a name you +[`#[implicit]`](../../attributes/implicit.md) argument, a [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) +method, and a [`UseField`](../../providers/use_field.md) wiring entry all generate this bound from a name you already wrote. **You will read `HasField` far more often than you write it**, and the impls come from -[`#[derive(HasField)]`](../derives/derive_has_field.md). +[`#[derive(HasField)]`](../../derives/derive_has_field.md). -## Usage +## Definition -**It is in the prelude**, so `use cgp::prelude::*;` is enough. +`HasField` carries the field's type as an associated `Value` and returns a reference to it: ```rust pub trait HasField { @@ -42,19 +43,20 @@ pub trait HasField { } ``` -The `PhantomData` argument carries nothing. It exists so a call site can say *which* field it means -when several impls are in scope, which is why reads are written -`self.get_field(PhantomData::)`. - -A named field is keyed by [`Symbol!("field_name")`](../macros/symbol.md); a tuple field by -[`Index`](../types/index.md). +`Tag` is a type-level name: [`Symbol!("field_name")`](../../macros/symbol.md) for a named field, +[`Index`](../../types/index.md) for a tuple field. `Value` is the field's type, exposed as an associated +type so a bound can pin it or leave it open — `HasField` accepts a field of any type, +while `HasField` requires a `String`. `get_field` takes `&self` and +returns `&Self::Value`, a borrow of the field; its `PhantomData` argument carries no data and only +lets a call site say *which* field it means when several `HasField` impls are in scope, which is why a +read is written `self.get_field(PhantomData::)`. The trait also carries a +`#[diagnostic::on_unimplemented]` note pointing at +[`#[derive(HasField)]`](../../derives/derive_has_field.md), so a missing field reads as a missing derive +rather than an opaque trait failure. -`Value` is an associated type, so it can be pinned or left open: `HasField` alone accepts -a field of any type, while adding `Value = String` requires that type. +## Usage -The trait carries a diagnostic note pointing a reader at -[`#[derive(HasField)]`](../derives/derive_has_field.md) when the bound is unsatisfied, so a missing field -reads as a missing derive rather than an opaque trait failure. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. **Four neighbours complete the picture**, each on its own page: [`HasFieldMut`](./has_field_mut.md) for mutable access, [`FieldGetter`](./field_getter.md) for the provider-side mirror that gets wired, and @@ -99,7 +101,7 @@ delegate_components! { compiles. **Value context, self-targeted** — the wired type is the data the capability runs against. **Written idiomatically, none of that bound is visible.** The same read is an -[`#[implicit]`](../attributes/implicit.md) argument: +[`#[implicit]`](../../attributes/implicit.md) argument: ```rust #[cgp_impl(new GreetHello)] @@ -110,8 +112,8 @@ impl Greeter { } ``` -which generates the identical bound and the identical read. The explicit form above is what you meet in -an error message or an expansion, not what you type. +which generates the identical bound and the identical read. The explicit form above appears in an error +message or an expansion, not in code you type. Field access also passes through smart pointers with no extra work, because the trait carries a `Deref` forwarding impl: @@ -127,19 +129,19 @@ assert_eq!(boxed.get_field(PhantomData::), "Alice"); **Bound against `HasField` only when the ergonomic constructs cannot do the job**, which is rarely. The ordering is settled and worth following. -- **Use an [`#[implicit]`](../attributes/implicit.md) argument by default.** It reads a field of the +- **Use an [`#[implicit]`](../../attributes/implicit.md) argument by default.** It reads a field of the implementation's own context as a plain parameter, generating this bound for you. It covers the common case, including a field several implementations each read. -- **Use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md)** when the read must be a *named* capability, +- **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a *named* capability, when the field lives on a type other than the context, or when the getter should carry a type inferred from the field — the three cases an implicit argument cannot reach. -- **Use [`#[cgp_getter]`](../macros/cgp_getter.md) with [`UseField`](../providers/use_field.md)** only +- **Use [`#[cgp_getter]`](../../macros/cgp_getter.md) with [`UseField`](../../providers/use_field.md)** only when a context needs to choose *which* field the getter reads. That is the advanced case and costs a wiring line per context. - **Write the bound by hand** when none of those fit — a bound on a type that is not `Self`, say. It is an ordinary trait bound. -Three neighbours are easy to confuse with it. [`HasFields`](./has_fields.md) — plural — is the +Three neighbours are easy to confuse with it. [`HasFields`](../shape/has_fields.md) — plural — is the whole-shape view, for code that must process *every* field rather than one named one; the two are complementary and often derived together. [`HasFieldMut`](./has_field_mut.md) is the same access with mutation, not an alternative. And [`FieldGetter`](./field_getter.md) is not an alternative either but the @@ -148,17 +150,17 @@ provider-side mirror: you bound against `HasField` and wire `FieldGetter`. ## Under the hood The per-field impls come almost entirely from -[`#[derive(HasField)]`](../derives/derive_has_field.md). What the trait module itself supplies is the +[`#[derive(HasField)]`](../../derives/derive_has_field.md). What the trait module itself supplies is the blanket impls that let the access compose, and two of them belong to this trait. **Smart-pointer forwarding.** `HasField` is implemented for any type whose [`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) target implements it, so a `Box` or a newtype resolves a read to the inner struct. It is marked so the compiler does **not** suggest it in a -diagnostic — which is what keeps a missing-field error pointed at the struct that lacks the field rather +diagnostic, which keeps a missing-field error pointed at the struct that lacks the field rather than at the pointer. **`UseContext` as a field getter.** The provider side connects to wiring through one impl: -[`UseContext`](../providers/use_context.md) implements [`FieldGetter`](./field_getter.md) for any context +[`UseContext`](../../providers/use_context.md) implements [`FieldGetter`](./field_getter.md) for any context that already has the field, delegating straight through. ```rust @@ -184,7 +186,7 @@ The remaining blanket impls belong to the neighbours: [`HasFieldMut`](./has_fiel nothing to do with each other, and a mismatch reports as a missing `HasField` bound rather than as a typo. This is the usual cause of a read that "should" work. -**A tuple field is keyed by [`Index`](../types/index.md), never by a `Symbol!` of the number.** +**A tuple field is keyed by [`Index`](../../types/index.md), never by a `Symbol!` of the number.** `Index<0>` and `Symbol!("0")` are different types. **`Value` can be pinned or left open.** Omitting `Value = T` when you meant to pin it produces an @@ -195,23 +197,23 @@ where inference can determine the tag from context; at an ambiguous site write `PhantomData::`. **It returns a reference, always.** There is no owning read; cloning is the caller's business, and an -[`#[implicit]`](../attributes/implicit.md) argument is what inserts a `.clone()` for you when the +[`#[implicit]`](../../attributes/implicit.md) argument inserts a `.clone()` for you when the parameter is owned. ## Related constructs -- [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates the per-field impls; what a context +- [`#[derive(HasField)]`](../../derives/derive_has_field.md) — generates the per-field impls; what a context writes. - [`HasFieldMut`](./has_field_mut.md) — the mutable extension. - [`FieldGetter`](./field_getter.md) — the provider-side mirror that gets wired. - [`MapField`](./map_field.md) — the lifetime-safe form for reaching into a nested value. -- [`HasFields`](./has_fields.md) — the plural, whole-shape counterpart. -- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that key a field. -- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to read a field. -- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../macros/cgp_getter.md) — +- [`HasFields`](../shape/has_fields.md) — the plural, whole-shape counterpart. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that key a field. +- [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to read a field. +- [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../../macros/cgp_getter.md) — getter traits over the same access. -- [`UseField`](../providers/use_field.md) — the provider-side implementation of `FieldGetter`. -- [`HasBuilder`](./has_builder.md) — where `HasField` reappears on a partial record, gated on presence. +- [`UseField`](../../providers/use_field.md) — the provider-side implementation of `FieldGetter`. +- [`HasBuilder`](../builder/has_builder.md) — where `HasField` reappears on a partial record, gated on presence. The ideas behind it: diff --git a/docs/reference/traits/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md similarity index 79% rename from docs/reference/traits/has_field_mut.md rename to docs/reference/traits/field-access/has_field_mut.md index 3ee367cf..144c5e66 100644 --- a/docs/reference/traits/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasFieldMut' +sidebar_position: 2 --- # `HasFieldMut` @@ -12,19 +13,25 @@ Mutable tag-keyed field access. on the field's name as a type. `HasFieldMut` is the same access with mutation: it hands back a `&mut` rather than a `&`, so an implementation can change a value in place. +**You do not opt into it.** [`#[derive(HasField)]`](../../derives/derive_has_field.md) always emits +`HasFieldMut` beside `HasField`, so every derived field is mutably accessible and there is no +derive-level way to make one read-only. + +## Definition + +`HasFieldMut` extends [`HasField`](./has_field.md) with one method that returns a mutable +borrow: + ```rust pub trait HasFieldMut: HasField { fn get_field_mut(&mut self, tag: PhantomData) -> &mut Self::Value; } ``` -It is a **supertrait extension** rather than an alternative: `HasFieldMut` requires -`HasField`, and the field's type comes from that supertrait's `Value`. So bounding on the mutable -form gives you the read as well. - -**You do not opt into it.** [`#[derive(HasField)]`](../derives/derive_has_field.md) always emits -`HasFieldMut` beside `HasField`, so every derived field is mutably accessible and there is no -derive-level way to make one read-only. +It is a **supertrait extension** rather than an alternative: `HasFieldMut` requires `HasField`, +so the field's type comes from that supertrait's `Value`, and bounding on the mutable form gives you the +read as well. `get_field_mut` takes `&mut self` and returns `&mut Self::Value`, with the +`PhantomData` argument naming the field exactly as [`HasField`](./has_field.md)'s `get_field` does. ## Usage @@ -44,7 +51,7 @@ Self: HasFieldMut ``` Like its supertrait it carries a diagnostic note pointing at -[`#[derive(HasField)]`](../derives/derive_has_field.md), so an unsatisfied bound reads as a missing +[`#[derive(HasField)]`](../../derives/derive_has_field.md), so an unsatisfied bound reads as a missing derive. ## Examples @@ -94,7 +101,7 @@ shared reference satisfies [`HasField`](./has_field.md) and not this. - **Use [`HasField`](./has_field.md)** whenever the value is only read. This is the overwhelmingly common case. -- **Use an [`#[implicit]`](../attributes/implicit.md) argument** for a read, since it generates the +- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** for a read, since it generates the immutable bound for you and reads like an ordinary parameter. Implicit arguments cover mutable access too, under the access rules on that page, which is the idiomatic route before reaching for this trait by hand. @@ -102,7 +109,7 @@ shared reference satisfies [`HasField`](./has_field.md) and not this. bounded — the provider-side mirror of this trait. - **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable and threads state through handler outputs instead, which composes better with the - [handler family](../components/handler/handler.md). + [handler family](../../components/handler/handler.md). ## Under the hood @@ -115,7 +122,7 @@ a smart pointer sometimes resolves the read and not the write. Like the immutable forwarding, it is marked so the compiler does **not** suggest it in a diagnostic, which keeps a missing-field error pointed at the struct that lacks the field rather than at the pointer. -The per-field impls themselves come from [`#[derive(HasField)]`](../derives/derive_has_field.md), one +The per-field impls themselves come from [`#[derive(HasField)]`](../../derives/derive_has_field.md), one `HasFieldMut` beside each `HasField`. ## Common Mistakes @@ -133,16 +140,16 @@ the lifetime rather than the field. **`Value` lives on the supertrait.** Pin it as `HasFieldMut` — the associated type is inherited, not redeclared. -**A tuple field is keyed by [`Index`](../types/index.md)**, exactly as for the immutable form. +**A tuple field is keyed by [`Index`](../../types/index.md)**, exactly as for the immutable form. ## Related constructs - [`HasField`](./has_field.md) — the supertrait, and where the tag-keyed access is explained in full. - [`MutFieldGetter`](./mut_field_getter.md) — the provider-side mirror of this trait. -- [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates both impls per field. -- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to reach a field, including mutably. -- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that key a field. -- [`UseField`](../providers/use_field.md) — the provider that implements the wired form. +- [`#[derive(HasField)]`](../../derives/derive_has_field.md) — generates both impls per field. +- [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to reach a field, including mutably. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that key a field. +- [`UseField`](../../providers/use_field.md) — the provider that implements the wired form. The ideas behind it: diff --git a/docs/reference/traits/field-access/index.md b/docs/reference/traits/field-access/index.md new file mode 100644 index 00000000..b784ec72 --- /dev/null +++ b/docs/reference/traits/field-access/index.md @@ -0,0 +1,41 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Field access + +Reading one field of a context by its type-level name, from code that cannot name the context. + +## Overview + +The most common thing a CGP implementation does is read a value out of its **context** — the type a +capability runs against — without naming that type. It reads the field by keying on the field's *name +as a type*, so any context with a matching field satisfies the bound. These traits are the foundation +the ergonomic surface stands on: an [`#[implicit]`](../../attributes/implicit.md) argument, a +[`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) method, and a +[`UseField`](../../providers/use_field.md) wiring entry all generate a bound on the traits here. + +The six traits divide on two axes: read versus write, and consumer-side versus provider-side. + +The **consumer traits** are what an implementation bounds against on its own context. +[`HasField`](has_field.md) reads a field, and [`HasFieldMut`](has_field_mut.md) adds mutable access. + +The **provider-side mirrors** are what a getter component is wired through, so that a context chooses by +wiring which field answers a getter. [`FieldGetter`](field_getter.md) is the read side and +[`MutFieldGetter`](mut_field_getter.md) the write side. + +The **lifetime-safe forms** let a getter reach into a nested value without forcing its type to be +`'static`. [`MapField`](map_field.md) is the consumer side and [`FieldMapper`](field_mapper.md) the +provider side, and [`ChainGetters`](../../providers/chain_getters.md) composes them to descend into a +nested context. + +## The ideas behind them + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on + the implementation rather than the interface. +- [Implicit arguments](/docs/concepts/implicit-arguments) — the ergonomic surface built on these traits. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/map_field.md b/docs/reference/traits/field-access/map_field.md similarity index 70% rename from docs/reference/traits/map_field.md rename to docs/reference/traits/field-access/map_field.md index b16e12df..65d8f26d 100644 --- a/docs/reference/traits/map_field.md +++ b/docs/reference/traits/field-access/map_field.md @@ -1,5 +1,6 @@ --- sidebar_label: 'MapField' +sidebar_position: 5 --- # `MapField` @@ -11,7 +12,7 @@ Reading through a field without forcing its type to be `'static`. ### Generated machinery **You will not call `map_field` yourself.** It is a blanket impl that every -[`HasField`](./has_field.md) already has, and [`ChainGetters`](../providers/chain_getters.md) is what +[`HasField`](./has_field.md) already has, and [`ChainGetters`](../../providers/chain_getters.md) is what uses it to descend into a nested context. This page explains the lifetime problem it exists to solve, which is why reaching a nested field is a provider rather than two chained reads. The one case for calling it directly is writing a getter provider of your own that has to descend. @@ -24,7 +25,15 @@ and it does not, for a reason that is about lifetimes rather than about CGP. Wri `context.get_field(..).get_field(..)` makes the intermediate `Value` outlive the borrow it came from, which the compiler can only accept by requiring it to be `'static`. -`MapField` sidesteps that by taking a closure instead of returning the intermediate: +`MapField` sidesteps that by taking a closure instead of returning the intermediate borrow. + +**You will not normally call it.** [`ChainGetters`](../../providers/chain_getters.md) uses +`map_field`, which is how a getter reaches a field on a nested context. + +## Definition + +`MapField` extends [`HasField`](./has_field.md) with a `map_field` method that reads the field +and hands it to a closure: ```rust pub trait MapField: HasField { @@ -36,11 +45,11 @@ pub trait MapField: HasField { } ``` -The higher-ranked bound is the whole trick: the closure is required to work for *any* lifetime, so the -compiler can pick the caller's rather than demanding `'static`. - -**You will not normally call it.** [`ChainGetters`](../providers/chain_getters.md) is what uses -`map_field`, which is how a getter reaches a field on a nested context. +It is a supertrait extension of [`HasField`](./has_field.md), so `Value` comes from the supertrait. +`map_field` takes `&self`, the `PhantomData` that names the field, and a `mapper` closure, and it +returns `&T`. The higher-ranked `for<'a>` bound on the closure is the whole trick: the closure must work +for *any* lifetime, so the compiler ties the returned borrow to the field's own lifetime rather than +demanding `'static`. ## Usage @@ -52,8 +61,8 @@ use cgp::core::field::traits::MapField; ``` It is a supertrait extension of [`HasField`](./has_field.md), so bounding on it gives you the plain read -as well. The `mapper` argument is an ordinary closure; what makes it unusual is the `for<'a>` binder, -which means a closure that captures a reference of some *specific* lifetime will not satisfy it. +as well. The `mapper` argument is an ordinary closure; the `for<'a>` binder makes it unusual, because a +closure that captures a reference of some *specific* lifetime will not satisfy it. **Nobody implements it.** It is a blanket impl for every `HasField` whose tag is `'static`, so every field access gains `map_field` for free. @@ -103,14 +112,14 @@ which is the same descent, chosen at the wiring site rather than written at the ## When to use it -**Reach for [`ChainGetters`](../providers/chain_getters.md) rather than this trait.** The provider is the +**Reach for [`ChainGetters`](../../providers/chain_getters.md) rather than this trait.** The provider is the construct; `map_field` is the mechanism it is built from, and calling it by hand means writing at a call site what the wiring could have decided. -- **Use [`ChainGetters`](../providers/chain_getters.md)** to reach a field on a nested context. +- **Use [`ChainGetters`](../../providers/chain_getters.md)** to reach a field on a nested context. - **Use [`HasField`](./has_field.md)** for a field of the context itself, which is the common case and needs none of this. -- **Use an [`#[implicit]`](../attributes/implicit.md) argument** before either, since it covers every +- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** before either, since it covers every same-context read. - **Reach for [`FieldMapper`](./field_mapper.md)** when the same descent must happen on the provider side, where the context is a type argument rather than `self`. @@ -126,8 +135,8 @@ say — and even then the existing ones usually compose. // for every Context: HasField, where Tag: 'static ``` -The bound is on the *tag*, not on the value — and that is the point. A tag is a -[`Symbol!`](../macros/symbol.md) or an [`Index`](../types/index.md), both of which are `'static` by +The bound is on the *tag*, not on the value, and that is the point. A tag is a +[`Symbol!`](../../macros/symbol.md) or an [`Index`](../../types/index.md), both of which are `'static` by construction, so the bound costs nothing. The value stays free, which is exactly what the naive chained read could not achieve. @@ -135,7 +144,7 @@ Inside, the implementation reads the field once and hands the borrow to the mapp is higher-ranked over `'a`, its return borrow is tied to the field borrow rather than to any fixed lifetime, and the result can be returned to the caller. -[`ChainGetters`](../providers/chain_getters.md) composes descents by nesting these calls, one per +[`ChainGetters`](../../providers/chain_getters.md) composes descents by nesting these calls, one per segment, so an arbitrarily deep path stays lifetime-correct with no `'static` anywhere in the chain. ## Common Mistakes @@ -146,15 +155,15 @@ is in the prelude. **The closure must be higher-ranked.** A closure that captures a reference with a particular lifetime will not satisfy `for<'a>`, and the error talks about lifetime bounds rather than about the closure's -body — which is confusing the first time. +body, which is confusing the first time. **The mapper must return a borrow *derived from* its argument.** Returning a reference to something else in scope does not satisfy the binder, which is the safety the design buys. **It cannot map to an owned value.** The signature returns `&T`. A getter that must produce a value uses -[`MRef`](../types/mref.md) instead. +[`MRef`](../../types/mref.md) instead. -**`MapField` is not [`MapFields`](./map_fields.md) and not [`MapType`](./map_type.md).** Three similar +**`MapField` is not [`MapFields`](../type-level/map_fields.md) and not [`MapType`](../type-level/map_type.md).** Three similar names: this one is a lifetime helper for reading a nested field, `MapFields` applies a marker across a type-level list, and `MapType` names one field's storage on a partial type. @@ -162,12 +171,12 @@ type-level list, and `MapType` names one field's storage on a partial type. - [`FieldMapper`](./field_mapper.md) — the provider-side mirror of this trait. - [`HasField`](./has_field.md) — the supertrait, and the plain read. -- [`ChainGetters`](../providers/chain_getters.md) — the provider that uses `map_field` to descend. -- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to read a field of the context itself. -- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags, which are `'static` by +- [`ChainGetters`](../../providers/chain_getters.md) — the provider that uses `map_field` to descend. +- [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to read a field of the context itself. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags, which are `'static` by construction. -- [`MRef`](../types/mref.md) — the return type for a getter that may produce rather than lend. -- [`MapFields`](./map_fields.md) and [`MapType`](./map_type.md) — the two similarly-named traits that do +- [`MRef`](../../types/mref.md) — the return type for a getter that may produce rather than lend. +- [`MapFields`](../type-level/map_fields.md) and [`MapType`](../type-level/map_type.md) — the two similarly-named traits that do something else. The ideas behind it: diff --git a/docs/reference/traits/mut_field_getter.md b/docs/reference/traits/field-access/mut_field_getter.md similarity index 75% rename from docs/reference/traits/mut_field_getter.md rename to docs/reference/traits/field-access/mut_field_getter.md index 365cd7cc..03e113f4 100644 --- a/docs/reference/traits/mut_field_getter.md +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -1,5 +1,6 @@ --- sidebar_label: 'MutFieldGetter' +sidebar_position: 4 --- # `MutFieldGetter` @@ -11,8 +12,8 @@ The provider-side mirror of `HasFieldMut` — wired field access that can mutate ### Generated machinery **You are not expected to implement `MutFieldGetter`.** -[`#[cgp_getter]`](../macros/cgp_getter.md) generates it alongside its supertrait, and -[`UseField`](../providers/use_field.md) satisfies both. What you write is the wiring entry; this page +[`#[cgp_getter]`](../../macros/cgp_getter.md) generates it alongside its supertrait, and +[`UseField`](../../providers/use_field.md) satisfies both. What you write is the wiring entry; this page explains what the mutable half of that entry provides. The one case for implementing it by hand is a provider whose mutable access is not a plain field read. ::: @@ -23,6 +24,19 @@ explains what the mutable half of that entry provides. The one case for implemen by wiring which field answers a getter. `MutFieldGetter` is the same thing with mutation: it hands back a `&mut` rather than a `&`. +Completing the square, the four traits divide on two axes, consumer versus provider and read versus +write: + +| | you bound against | you wire | +|---|---|---| +| read | [`HasField`](./has_field.md) | [`FieldGetter`](./field_getter.md) | +| write | [`HasFieldMut`](./has_field_mut.md) | `MutFieldGetter` | + +## Definition + +`MutFieldGetter` extends [`FieldGetter`](./field_getter.md) with one method that returns a +mutable borrow: + ```rust pub trait MutFieldGetter: FieldGetter { fn get_field_mut(context: &mut Context, tag: PhantomData) -> &mut Self::Value; @@ -30,24 +44,17 @@ pub trait MutFieldGetter: FieldGetter { ``` It stands to [`FieldGetter`](./field_getter.md) exactly as [`HasFieldMut`](./has_field_mut.md) stands to -[`HasField`](./has_field.md): a **supertrait extension** rather than an alternative, with the field's -type inherited from the supertrait's `Value`. `Self` is the provider; `Context` is the type being -mutated. - -Completing the square, the four traits divide on two axes — consumer versus provider, and read versus -write: - -| | you bound against | you wire | -|---|---|---| -| read | [`HasField`](./has_field.md) | [`FieldGetter`](./field_getter.md) | -| write | [`HasFieldMut`](./has_field_mut.md) | `MutFieldGetter` | +[`HasField`](./has_field.md): a **supertrait extension** rather than an alternative, with the field's type +inherited from the supertrait's `Value`. `Self` is the provider and `Context` is the type being mutated; +`get_field_mut` takes the context by mutable reference and returns `&mut Self::Value`, with the +`PhantomData` argument naming the field. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. As with its immutable sibling you rarely name the trait. What you write is a wiring entry naming a -provider that implements it — [`UseField`](../providers/use_field.md) does, so a getter component wired +provider that implements it — [`UseField`](../../providers/use_field.md) does, so a getter component wired to `UseField` supports both the read and the write. Writing an impl by hand is the escape hatch for a provider whose mutable access is not a plain field @@ -79,7 +86,7 @@ delegate_components! { ``` **Environmental context, self-targeted.** The getter reads `request_count` though it is named `counter`, -and because [`UseField`](../providers/use_field.md) implements `MutFieldGetter` as well, a provider that +and because [`UseField`](../../providers/use_field.md) implements `MutFieldGetter` as well, a provider that holds `&mut App` can write through the same wiring. ## When to use it @@ -87,7 +94,7 @@ holds `&mut App` can write through the same wiring. **Wire it only when the mutable access must be chosen per context**, which is rarer than the read case and rarer still than mutation generally. -- **Use an [`#[implicit]`](../attributes/implicit.md) argument** for a field the implementation reaches +- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** for a field the implementation reaches on its own context. The access rules on that page cover mutable access, and no provider is involved. - **Use [`HasFieldMut`](./has_field_mut.md)** when the implementation should simply *require* mutable access rather than have it wired. @@ -100,11 +107,11 @@ and rarer still than mutation generally. `MutFieldGetter` adds one method to its supertrait and no new resolution path: a provider that implements [`FieldGetter`](./field_getter.md) and can also produce a `&mut` implements this too, and -[`UseField`](../providers/use_field.md) does for any context whose field is derived. +[`UseField`](../../providers/use_field.md) does for any context whose field is derived. The route from a wired getter back to a context's own fields runs through [`HasFieldMut`](./has_field_mut.md), whose `DerefMut` forwarding carries the `'static` bound on the -target that its immutable counterpart does not — so a context behind a smart pointer holding borrowed +target that its immutable counterpart does not, so a context behind a smart pointer holding borrowed data can satisfy the wired read and not the wired write. ## Common Mistakes @@ -129,10 +136,10 @@ cannot satisfy it. - [`FieldGetter`](./field_getter.md) — the supertrait, and where the wired form is explained in full. - [`HasFieldMut`](./has_field_mut.md) — the consumer side you bound against. - [`HasField`](./has_field.md) — the read half of the consumer side. -- [`UseField`](../providers/use_field.md) — the provider that implements both halves. -- [`#[cgp_getter]`](../macros/cgp_getter.md) — the macro that makes a getter a full component. -- [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to reach a field. -- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that key a field. +- [`UseField`](../../providers/use_field.md) — the provider that implements both halves. +- [`#[cgp_getter]`](../../macros/cgp_getter.md) — the macro that makes a getter a full component. +- [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to reach a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that key a field. The ideas behind it: diff --git a/docs/reference/traits/formatting/_category_.json b/docs/reference/traits/formatting/_category_.json new file mode 100644 index 00000000..d123e0d2 --- /dev/null +++ b/docs/reference/traits/formatting/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Type-level strings and paths", + "position": 10, + "link": { + "type": "doc", + "id": "reference/traits/formatting/index" + } +} diff --git a/docs/reference/traits/concat_path.md b/docs/reference/traits/formatting/concat_path.md similarity index 68% rename from docs/reference/traits/concat_path.md rename to docs/reference/traits/formatting/concat_path.md index c62e9d8f..43e37d8c 100644 --- a/docs/reference/traits/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -1,5 +1,6 @@ --- sidebar_label: 'ConcatPath' +sidebar_position: 3 --- # `ConcatPath` @@ -11,8 +12,8 @@ Joining two type-level paths. ### Generated machinery **You are not expected to call `ConcatPath` directly.** -[`cgp_namespace!`](../macros/cgp_namespace.md) and [`RedirectLookup`](../providers/redirect_lookup.md) -use it to extend a route one segment at a time, and [`ChainGetters`](../providers/chain_getters.md) to +[`cgp_namespace!`](../../macros/cgp_namespace.md) and [`RedirectLookup`](../../providers/redirect_lookup.md) +use it to extend a route one segment at a time, and [`ChainGetters`](../../providers/chain_getters.md) to descend into a nested context. This page explains the operation, so that a composed path in an expansion or an error message is legible. The one case for naming it is generic code that composes paths rather than writing one out. @@ -20,9 +21,15 @@ expansion or an error message is legible. The one case for naming it is generic ## Overview -A [`Path!`](../macros/path.md) is a type-level list of segments — the route a namespaced component +A [`Path!`](../../macros/path.md) is a type-level list of segments — the route a namespaced component lookup is redirected along, or the chain of field names a nested getter descends. Composing two such -routes means splicing one list onto the end of another, and `ConcatPath` is that operation: +routes means splicing one list onto the end of another, and `ConcatPath` is that operation. It is the +path-level analogue of [`ConcatProduct`](../type-level/concat_product.md), with the same two-impl +recursion over a different spine. + +## Definition + +`ConcatPath` carries a single associated type and no method: ```rust pub trait ConcatPath { @@ -30,11 +37,10 @@ pub trait ConcatPath { } ``` -There is no method and no value. It is a pure type-level computation resolved during trait resolution, -so it names the combined path type and nothing runs. - -It is the path-level analogue of [`ConcatProduct`](./concat_product.md), with the same two-impl -recursion over a different spine. +`Self` is the first path and `Other` the second, and `Output` is the first path's segments followed by +the second's. **Both sides may be unsized**, since path types are markers rather than types anything is +instantiated at. There is no method and no value: `ConcatPath` is a pure type-level computation resolved +during trait resolution, so it names the combined path type and nothing runs. ## Usage @@ -44,10 +50,6 @@ the type-level recovery group that needs no import. Its two neighbours each need [`StaticFormat`](./static_format.md) — defined in the same crate as this trait — from `cgp::core::base::traits`. -`Self` is the first path and `Other` the second, and the result is the first's segments followed by the -second's. **Both sides may be unsized**, since path types are markers rather than types anything is -instantiated at. - ## Examples Two paths composed at the type level, which is the operation behind chaining nested accessors: @@ -61,7 +63,7 @@ type Inner = Path!(@c.d); type Joined = >::Output; // the path @a.b.c.d ``` -Note the leading `@` — [`Path!`](../macros/path.md) requires it, and `Path!(a.b)` does not parse. +Note the leading `@` — [`Path!`](../../macros/path.md) requires it, and `Path!(a.b)` does not parse. In generic code the projection usually appears in a bound rather than a type alias, naming the route a composed getter will take: @@ -78,12 +80,12 @@ where ## When to use it **Reach for it when composing paths in generic code**, which is nested-accessor territory. If you are -writing a path literally, [`Path!`](../macros/path.md) already gives you the whole thing and there is +writing a path literally, [`Path!`](../../macros/path.md) already gives you the whole thing and there is nothing to concatenate. -- **Use [`ChainGetters`](../providers/chain_getters.md)** rather than composing paths by hand when the +- **Use [`ChainGetters`](../../providers/chain_getters.md)** rather than composing paths by hand when the goal is reaching a field on a nested context. That provider is the construct this operation serves. -- **Use [`ConcatProduct`](./concat_product.md)** for field lists rather than paths. The two recursions +- **Use [`ConcatProduct`](../type-level/concat_product.md)** for field lists rather than paths. The two recursions are the same shape over different spines and are not interchangeable. - **Use [`StaticString`](./static_string.md)** if what you want is the segments as *text*. This produces a type; decoding it means decoding each segment's symbol. @@ -106,19 +108,19 @@ impl ConcatPath for Nil { } ``` -Note the `?Sized` on every parameter, including the associated type — that is what lets both operands +Note the `?Sized` on every parameter, including the associated type — that lets both operands be the unsized markers a path is built from, and it is the one way this recursion differs from -[`ConcatProduct`](./concat_product.md)'s otherwise identical shape. +[`ConcatProduct`](../type-level/concat_product.md)'s otherwise identical shape. So the result is the first path's segments followed by the second's, in order, with the cost of resolution proportional to the first path's length. It never touches a value; it only names the combined path type, which a getter or a -[`RedirectLookup`](../providers/redirect_lookup.md) then uses to descend. +[`RedirectLookup`](../../providers/redirect_lookup.md) then uses to descend. ## Common Mistakes -**[`Path!`](../macros/path.md) requires a leading `@`.** `Path!(a.b)` does not parse; `Path!(@a.b)` does. +**[`Path!`](../../macros/path.md) requires a leading `@`.** `Path!(a.b)` does not parse; `Path!(@a.b)` does. This is the most common way an otherwise-correct `ConcatPath` example fails to build. **It produces a type, not a joined string.** This is path composition for trait resolution. If you want @@ -135,15 +137,15 @@ normalizes them. ## Related constructs -- [`Path!`](../macros/path.md) — the sugar for the paths this joins. -- [`PathCons`](../types/type_level_spines.md) — the spine underneath. -- [`ConcatProduct`](./concat_product.md) — the product-level analogue. +- [`Path!`](../../macros/path.md) — the sugar for the paths this joins. +- [`PathCons`](../../types/type_level_spines.md) — the spine underneath. +- [`ConcatProduct`](../type-level/concat_product.md) — the product-level analogue. - [`StaticString`](./static_string.md) — recovering a segment's name as text. - [`StaticFormat`](./static_format.md) — the lazy formatting counterpart. -- [`RedirectLookup`](../providers/redirect_lookup.md) — the provider that follows a path. -- [`ChainGetters`](../providers/chain_getters.md) — nested accessors, the setting path composition +- [`RedirectLookup`](../../providers/redirect_lookup.md) — the provider that follows a path. +- [`ChainGetters`](../../providers/chain_getters.md) — nested accessors, the setting path composition serves. -- [`cgp_namespace!`](../macros/cgp_namespace.md) — where paths key a namespace's entries. +- [`cgp_namespace!`](../../macros/cgp_namespace.md) — where paths key a namespace's entries. The ideas behind it: diff --git a/docs/reference/traits/formatting/index.md b/docs/reference/traits/formatting/index.md new file mode 100644 index 00000000..4afe1e05 --- /dev/null +++ b/docs/reference/traits/formatting/index.md @@ -0,0 +1,34 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Type-level strings and paths + +Recovering a field name or a routing path as runtime data. + +## Overview + +CGP encodes field and variant names as *types*, so that a name can drive trait resolution. A program +eventually needs those names as ordinary strings — to report a missing field, to build a key, to render +a path — and these traits are how a name comes back out. The three sit in three different homes, which +is the group's sharpest edge: one is in the prelude and the other two each need a different import. + +- [`StaticString`](static_string.md) decodes a [`Symbol!`](../../macros/symbol.md) into a compile-time + `&'static str` constant. This is the one to reach for when you need a name as data. Import it from + `cgp::core::field::traits`. +- [`StaticFormat`](static_format.md) writes a type-level string into a formatter, and backs the + `Display` impl on `Symbol`, so a `Display` bound is usually all you need. Reach for the trait itself + only where there is no value to format. Import it from `cgp::core::base::traits`. +- [`ConcatPath`](concat_path.md) joins two type-level [`Path!`](../../macros/path.md) routes, the + path-level analogue of `ConcatProduct`. It is in the prelude. + +## The ideas behind them + +- [Namespaces](/docs/concepts/namespaces) — reusable wiring tables and the paths that route into them. +- [Extensible records](/docs/concepts/extensible-records) — where field-name types are put to work at + scale. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/static_format.md b/docs/reference/traits/formatting/static_format.md similarity index 87% rename from docs/reference/traits/static_format.md rename to docs/reference/traits/formatting/static_format.md index d205c44c..666688dd 100644 --- a/docs/reference/traits/static_format.md +++ b/docs/reference/traits/formatting/static_format.md @@ -1,5 +1,6 @@ --- sidebar_label: 'StaticFormat' +sidebar_position: 2 --- # `StaticFormat` @@ -21,7 +22,14 @@ and the narrow case where bounding on it is the answer. CGP encodes field and variant names as *types*, so a name can drive trait resolution. Printing one means turning that type back into characters, and `StaticFormat` is the trait that does it **lazily**, by -writing into a formatter rather than producing a value: +writing into a formatter rather than producing a value. + +**It backs the `Display` impls on `Symbol` and `Chars`**, which is how you usually meet it: a +type-level string can be printed with `{}` or `to_string()` because of this trait. + +## Definition + +`StaticFormat` carries a single associated function and no data: ```rust pub trait StaticFormat { @@ -29,12 +37,9 @@ pub trait StaticFormat { } ``` -Note the absent `self`: there is no runtime value, only the type. It is implemented by recursion over the -character spine — each node writes its own character and defers to the tail, and the terminator writes -nothing. - -**It is what backs the `Display` impls on `Symbol` and `Chars`**, which is how you usually meet it: a -type-level string can be printed with `{}` or `to_string()` because of this trait. +Note the absent `self`: there is no runtime value, only the type, so `fmt` takes the formatter alone and +writes the type's characters into it. The trait is implemented for the type-level string itself, by +recursion over the character spine, and the terminator writes nothing. ## Usage @@ -66,7 +71,7 @@ delegating to its inner list. Every type-level string therefore formats, includi ## Examples -Formatting is what a diagnostic or a log line wants, where the name appears once. A `Display` bound is +A diagnostic or a log line wants formatting, where the name appears once. A `Display` bound is usually enough, and needs no import: ```rust @@ -81,7 +86,7 @@ let message = describe(core::marker::PhantomData::); assert_eq!(message, "missing field `height`"); ``` -Bounding on the trait itself is what you reach for when there is no *value* to call `Display` on — the +You reach for the trait itself when there is no *value* to call `Display` on. The method is an associated function, so it writes a type's characters without one: ```rust @@ -160,9 +165,9 @@ this trait is what you need when there is no value to construct. - [`StaticString`](./static_string.md) — the eager counterpart, and the one to reach for. - [`ConcatPath`](./concat_path.md) — path composition, its reachable sibling in the same group. -- [`Symbol!`](../macros/symbol.md) — the type-level string being formatted. -- [Type-level spines](../types/type_level_spines.md) — the `Chars` chain being walked. -- [`HasField`](./has_field.md) — where the names being decoded are used as keys. +- [`Symbol!`](../../macros/symbol.md) — the type-level string being formatted. +- [Type-level spines](../../types/type_level_spines.md) — the `Chars` chain being walked. +- [`HasField`](../field-access/has_field.md) — where the names being decoded are used as keys. The ideas behind it: diff --git a/docs/reference/traits/static_string.md b/docs/reference/traits/formatting/static_string.md similarity index 80% rename from docs/reference/traits/static_string.md rename to docs/reference/traits/formatting/static_string.md index 56e89fb6..8fe3ee89 100644 --- a/docs/reference/traits/static_string.md +++ b/docs/reference/traits/formatting/static_string.md @@ -1,5 +1,6 @@ --- sidebar_label: 'StaticString' +sidebar_position: 1 --- # `StaticString` @@ -8,12 +9,20 @@ Recovering a type-level string as a compile-time `&'static str`. ## Overview -CGP encodes field and variant names as *types* — a [`Symbol!`](../macros/symbol.md) is a length plus a +CGP encodes field and variant names as *types* — a [`Symbol!`](../../macros/symbol.md) is a length plus a character list, one node per character — so that names can drive trait resolution. But a program eventually needs those names as ordinary strings: to report a missing field, to build a key, to compare against input. -`StaticString` is how a name comes back out, and it does it **eagerly**: +`StaticString` is how a name comes back out, and it does it **eagerly**. + +**This is the one of the three recovery traits to reach for.** Its sibling +[`StaticFormat`](./static_format.md) recovers a name lazily by writing into a formatter, which backs +`Display`; reach for it only where there is no value to format and no constant will do. + +## Definition + +`StaticString` carries a single associated constant and no method: ```rust pub trait StaticString { @@ -21,12 +30,10 @@ pub trait StaticString { } ``` -`VALUE` is the decoded string as a constant, computed by const evaluation rather than at run time. So the +`VALUE` is the decoded string as a constant, computed by const evaluation rather than at run time, so the string is available wherever a `const` is, costs nothing per use, and can be compared or stored freely. - -**This is the one of the three recovery traits to reach for.** Its sibling -[`StaticFormat`](./static_format.md) recovers a name lazily by writing into a formatter, which is what -backs `Display`; reach for it only where there is no value to format and no constant will do. +The trait is implemented for the type-level string itself and carries no method, because there is no +value to call one on. ## Usage @@ -66,7 +73,7 @@ assert_eq!(::VALUE, ""); ``` Where it shows up in real code is recovering a name for an error. The -[optional-field layer](./finalize_optional.md)'s `finalize_optional` reports its missing field by +[optional-field layer](../optional/finalize_optional.md)'s `finalize_optional` reports its missing field by returning `Tag::VALUE` — the field's own name, as a static string, with no allocation. ## When to use it @@ -81,10 +88,10 @@ message.** That is the whole decision. where there is no value to format. - **[`ConcatPath`](./concat_path.md)** when the thing being composed is a path rather than a string. -Two things this is not for. It is **not a general string facility**: [`Symbol!`](../macros/symbol.md) +Two things this is not for. It is **not a general string facility**: [`Symbol!`](../../macros/symbol.md) exists to key field and variant lookups, and building programs out of type-level strings is not what the encoding is for. And it is **not how you read a field** — recovering a name tells you what a field is -called, while [`HasField`](./has_field.md) is what reads its value. +called, while [`HasField`](../field-access/has_field.md) reads its value. ## Under the hood @@ -95,7 +102,7 @@ bytes as UTF-8 and exposes the `&'static str`. **That array is why `Symbol` carries a `LEN` at all.** A const-evaluated byte array must have a known size, and the size cannot be computed from inside the const context by walking the list — so the macro -precomputes it. It is a *byte* length, which is what makes multi-byte Unicode round-trip correctly and +precomputes it. It is a *byte* length, which makes multi-byte Unicode round-trip correctly and why `LEN` disagrees with the visible character count for any non-ASCII name. ## Common Mistakes @@ -112,17 +119,17 @@ surfaces on a non-ASCII name, where the number will not match the visible charac **`Display` reconstructs the string rather than reading a stored one.** There is no `&str` inside a `Symbol`, so `to_string()` walks the type. For a name used repeatedly, `VALUE` is the cheaper choice. -**It decodes a symbol, not a path.** A [`Path!`](../macros/path.md) is a list of segments; decoding one +**It decodes a symbol, not a path.** A [`Path!`](../../macros/path.md) is a list of segments; decoding one means decoding each segment's symbol. ## Related constructs - [`StaticFormat`](./static_format.md) — the lazy counterpart, behind the `Display` impls. - [`ConcatPath`](./concat_path.md) — the same recovery idea one level up, for paths. -- [`Symbol!`](../macros/symbol.md) — the type-level string this decodes, and where the `LEN` comes from. -- [Type-level spines](../types/type_level_spines.md) — the `Chars` chain being walked. -- [`HasField`](./has_field.md) — where the names being decoded are used as keys. -- [`FinalizeOptional`](./finalize_optional.md) — a real consumer, reporting a missing field by name. +- [`Symbol!`](../../macros/symbol.md) — the type-level string this decodes, and where the `LEN` comes from. +- [Type-level spines](../../types/type_level_spines.md) — the `Chars` chain being walked. +- [`HasField`](../field-access/has_field.md) — where the names being decoded are used as keys. +- [`FinalizeOptional`](../optional/finalize_optional.md) — a real consumer, reporting a missing field by name. The ideas behind it: diff --git a/docs/reference/traits/index.md b/docs/reference/traits/index.md new file mode 100644 index 00000000..19d59ef6 --- /dev/null +++ b/docs/reference/traits/index.md @@ -0,0 +1,58 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Traits + +The traits on these pages are the machinery CGP's macros generate and consume. A component definition, +a wiring table, a derive, or a field read all expand into impls of these traits, so you meet the names +here in an expansion or a compiler error far more often than you write them. This section groups the +traits by the job they do, so that a name from a diagnostic has a page to land on. + +If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here. This page +is the fuller map for once the essentials are familiar. + +## The traits you meet first + +Three traits carry every wiring, and a wiring error names one of them. [`DelegateComponent`](wiring/delegate_component.md) +records which provider a context uses for each component. [`IsProviderFor`](wiring/is_provider_for.md) +makes a missing dependency show up by name instead of hiding behind a bare "trait not implemented." +[`CanUseComponent`](wiring/can_use_component.md) is the bound a check asserts. Read +[Wiring and checking](wiring/index.md) first. + +Reading a value out of a context is the next most common need. +[Field access](field-access/index.md) covers reading one field by its type-level name, through +[`HasField`](field-access/has_field.md) and the provider-side and lifetime-safe traits around it. + +## The extensible-data families + +Most of the remaining traits build and read structs and enums generically, by their fields and +variants. They divide into families that mirror the extensible-data derives: + +- [Field structure](shape/index.md) exposes a type's whole shape as a single type, and moves a value + through it in both directions. +- [Record builders](builder/index.md) assemble a struct one field at a time, with field presence + tracked at compile time so an incomplete record cannot be finalized. +- [Optional and defaulted fields](optional/index.md) relax that strict builder, filling a missing field + from `Default` or reporting it at run time. +- [Extensible variants](variant/index.md) construct an enum from one named variant and take one apart + variant by variant, with exhaustiveness proven in the type. +- [Structural casts](casting/index.md) convert between two data types by their shared fields or + variants, with no hand-written conversion. +- [Type-level list algebra](type-level/index.md) holds the per-field state markers and the list + operations the families above are built from. + +## The specialized machinery + +Three smaller groups each serve one area: + +- [Namespaces and defaults](namespace/index.md) are the lookup traits behind a namespace and a per-type + default. +- [Type-level strings and paths](formatting/index.md) recover a field name or a path as runtime data. +- [Monad interface](monad/index.md) holds the four traits that give a monad marker its meaning for + monadic handler composition. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monad/_category_.json b/docs/reference/traits/monad/_category_.json new file mode 100644 index 00000000..08ea7699 --- /dev/null +++ b/docs/reference/traits/monad/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Monad interface", + "position": 11, + "link": { + "type": "doc", + "id": "reference/traits/monad/index" + } +} diff --git a/docs/reference/traits/contains_value.md b/docs/reference/traits/monad/contains_value.md similarity index 82% rename from docs/reference/traits/contains_value.md rename to docs/reference/traits/monad/contains_value.md index c0c86533..50f3e9ff 100644 --- a/docs/reference/traits/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -1,5 +1,6 @@ --- sidebar_label: 'ContainsValue' +sidebar_position: 2 --- # `ContainsValue` @@ -11,7 +12,7 @@ Naming the value a monad threads forward out of a step's output. ### Generated machinery **You are not expected to name `ContainsValue`.** The -[bind providers](../providers/monad/index.md) use it while running a step, and the monad markers CGP +[bind providers](../../providers/monad/index.md) use it while running a step, and the monad markers CGP ships already implement it. The one case for naming it is defining a monad of your own; otherwise this page is here to explain how a step unwraps its input. @@ -23,7 +24,19 @@ A step in a [monadic pipeline](/docs/concepts/monadic-handlers) produces a wrapp say — and the next step needs the value *inside* the wrapper for the branch that continues. Which half of the wrapper that is depends on the monad, so it cannot be hard-coded. -`ContainsValue` is where each monad answers it: +`ContainsValue` is where each monad answers it. + +It is one of four traits that give a monad marker its meaning, and it pairs with +[`LiftValue`](./lift_value.md): this one says how to get *out* of the output type, that one how to get +back *in*. The other two, [`MonadicBind`](./monadic_bind.md) and +[`MonadicTrans`](./monadic_trans.md), fold the pipeline rather than run a step of it. + +**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is +never wired. + +## Definition + +`ContainsValue` carries a single associated type and no method: ```rust pub trait ContainsValue { @@ -35,14 +48,6 @@ pub trait ContainsValue { carried in the branch this monad threads forward. A continuation consumes that value, or a deeper monad layer unwraps it further. -It is one of four traits that give a monad marker its meaning, and it pairs with -[`LiftValue`](./lift_value.md): this one says how to get *out* of the output type, that one how to get -back *in*. The other two, [`MonadicBind`](./monadic_bind.md) and -[`MonadicTrans`](./monadic_trans.md), fold the pipeline rather than run a step of it. - -**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is -never wired. - ## Usage **It is not in the prelude.** Import it from `cgp::extra::monad::traits`: @@ -56,7 +61,7 @@ projection from an output type to the value beneath the wrapper. ## Examples -What each marker's impl says is what decides how a pipeline behaves. +What each marker's impl says decides how a pipeline behaves. **`IdentMonadic` is the identity**: `ContainsValue::Value` is `T`. Nothing is wrapped, so nothing is unwrapped, and every value threads forward. @@ -79,8 +84,8 @@ specific to any depth. ## When to use it -**Reach for the [monad providers](../providers/monad/index.md), not this trait.** A pipeline is built -by wiring [`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker and a handler list; this is what +**Reach for the [monad providers](../../providers/monad/index.md), not this trait.** A pipeline is built +by wiring [`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker and a handler list; this is what the bind providers bound on internally. The one real reason to name it is **defining a new monad** — short-circuiting over an `Option`, or over a @@ -89,13 +94,13 @@ that runs a step and neither is useful without the other, and copy the mirror-im `OkMonadic`/`ErrMonadic` pair as the model. If you do not need short-circuiting at all, the -[handler combinators](../providers/handler/index.md) chain steps without a branch and involve none +[handler combinators](../../providers/handler/index.md) chain steps without a branch and involve none of this. ## Under the hood -The [`BindOk` and `BindErr`](../providers/monad/index.md) providers use `ContainsValue` in their -[`Computer`](../components/handler/computer.md) and `AsyncComputer` impls. Running one bind step means: take the +The [`BindOk` and `BindErr`](../../providers/monad/index.md) providers use `ContainsValue` in their +[`Computer`](../../components/handler/computer.md) and `AsyncComputer` impls. Running one bind step means: take the step's output, ask the monad what value sits beneath its wrapper, and hand that to the continuation. This trait is the second half of that sentence. @@ -128,10 +133,10 @@ the first step rather than at the definition. - [`LiftValue`](./lift_value.md) — the other half of running a step: getting back into the output type. - [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md) — the two traits that fold the pipeline rather than run a step. -- [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers; what you actually wire. -- [`Computer`](../components/handler/computer.md) — the component family the bind providers implement. -- [`TryComputer`](../components/handler/try_computer.md) and [`Handler`](../components/handler/handler.md) — the fallible +- [`Computer`](../../components/handler/computer.md) — the component family the bind providers implement. +- [`TryComputer`](../../components/handler/try_computer.md) and [`Handler`](../../components/handler/handler.md) — the fallible members a single step usually is. The ideas behind it: diff --git a/docs/reference/traits/monad/index.md b/docs/reference/traits/monad/index.md new file mode 100644 index 00000000..335c19c1 --- /dev/null +++ b/docs/reference/traits/monad/index.md @@ -0,0 +1,37 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Monad interface + +The four traits that give a monad marker its meaning for monadic handler composition. + +## Overview + +A [monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue or +short-circuit — the `?`-style behaviour, expressed as composable providers. A monad in CGP is a +zero-sized marker, and these four traits are what give that marker meaning. They are plain capability +traits rather than CGP components: they have no generated provider trait and are never wired. The +[monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a +pipeline at compile time, so you name a trait here only when defining a monad of your own. Import each +from `cgp::extra::monad::traits`. + +The four split into the pair that folds the pipeline and the pair that runs one step. + +The **folding pair** decides the shape of the composed provider. [`MonadicBind`](monadic_bind.md) turns +a continuation into one bind step, and [`MonadicTrans`](monadic_trans.md) stacks one monad over another +so a pipeline can peel a nested `Result`. + +The **step-running pair** brackets one bind step. [`ContainsValue`](contains_value.md) names the value a +monad threads forward out of a step's output, and [`LiftValue`](lift_value.md) puts a value back into +the output type on either branch. + +## The ideas behind them + +- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads + compose. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/lift_value.md b/docs/reference/traits/monad/lift_value.md similarity index 77% rename from docs/reference/traits/lift_value.md rename to docs/reference/traits/monad/lift_value.md index 86d807aa..dd1a5a31 100644 --- a/docs/reference/traits/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -1,5 +1,6 @@ --- sidebar_label: 'LiftValue' +sidebar_position: 3 --- # `LiftValue` @@ -11,7 +12,7 @@ Putting a value back into a monad's output type, on either branch. ### Generated machinery **You are not expected to name `LiftValue`.** The -[bind providers](../providers/monad/index.md) use it while running a step, and the monad markers CGP +[bind providers](../../providers/monad/index.md) use it while running a step, and the monad markers CGP ships already implement it. The one case for naming it is defining a monad of your own; otherwise this page is here to explain how a step produces its output — and why that takes two methods rather than one. @@ -22,8 +23,19 @@ one. A bind step in a [monadic pipeline](/docs/concepts/monadic-handlers) unwraps a value, runs a continuation or short-circuits, and then has to produce the step's own output. Producing it means -wrapping something back up — and there are **two** things that might need wrapping, which is why this -trait has two methods rather than one: +wrapping something back up, and there are **two** things that might need wrapping, so this trait has two +methods rather than one. + +It is the counterpart of [`ContainsValue`](./contains_value.md): that one says how to get *out* of an +output type, this one how to get back *in*. Together they run one step; the other two monad traits, +[`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline instead. + +**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is +never wired. + +## Definition + +`LiftValue` carries an associated type and two methods: ```rust pub trait LiftValue { @@ -34,15 +46,11 @@ pub trait LiftValue { } ``` -`lift_value` wraps a bare value from the continue or short-circuit branch into the final output. -`lift_output` re-wraps a value already in the inner shape, forwarding a continuation's computed result. - -It is the counterpart of [`ContainsValue`](./contains_value.md): that one says how to get *out* of an -output type, this one how to get back *in*. Together they run one step; the other two monad traits, -[`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline instead. - -**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is -never wired. +`Self` is the monad marker, `Value` is the bare value, and the `Output` parameter is the inner output +being forwarded. The associated `Output`, which shares the parameter's name and is not the same thing, +is the step's final output type. `lift_value` wraps a bare value from the continue or short-circuit +branch into that final output; `lift_output` re-wraps a value already in the inner shape, forwarding a +continuation's computed result. ## Usage @@ -58,7 +66,7 @@ output type. ## Examples -What each marker's impl says is what decides how a pipeline behaves. +What each marker's impl says decides how a pipeline behaves. **`IdentMonadic` is the identity in both directions**: `LiftValue` returns `T` from both methods. Nothing is wrapped, so a pipeline under it is plain function composition. @@ -81,21 +89,21 @@ collapses the two branches. ## When to use it -**Reach for the [monad providers](../providers/monad/index.md), not this trait.** A pipeline is built -by wiring [`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker and a handler list. +**Reach for the [monad providers](../../providers/monad/index.md), not this trait.** A pipeline is built +by wiring [`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker and a handler list. The one real reason to name it is **defining a new monad**. Implement it alongside [`ContainsValue`](./contains_value.md), since the two are the pair that runs a step, and take the `OkMonadic`/`ErrMonadic` pair as the model — including their separate treatment of the two methods, which is the part a first implementation usually gets wrong. -If short-circuiting is not what you need, the [handler combinators](../providers/handler/index.md) +If short-circuiting is not what you need, the [handler combinators](../../providers/handler/index.md) chain steps without a branch and involve none of this. ## Under the hood -The [`BindOk` and `BindErr`](../providers/monad/index.md) providers use `LiftValue` in their -[`Computer`](../components/handler/computer.md) and `AsyncComputer` impls, as the closing half of a step whose +The [`BindOk` and `BindErr`](../../providers/monad/index.md) providers use `LiftValue` in their +[`Computer`](../../components/handler/computer.md) and `AsyncComputer` impls, as the closing half of a step whose opening half is [`ContainsValue`](./contains_value.md). The step unwraps the incoming output, decides whether to short-circuit, and then lifts: @@ -108,7 +116,7 @@ That is the whole reason for two methods. A monad whose two methods agree — as one where the distinction happens to be vacuous, not one where it does not exist. The transformer forms implement both by delegating to the base monad after handling their own layer, -which is what lets a stack lift through *n* layers with no depth-specific code. +which lets a stack lift through *n* layers with no depth-specific code. ## Common Mistakes @@ -134,10 +142,10 @@ forwarded; the associated type is the step's own. They coincide for some monads type. - [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md) — the two traits that fold the pipeline rather than run a step. -- [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers; what you actually wire. -- [`Computer`](../components/handler/computer.md) — the component family the bind providers implement. -- [Handler combinators](../providers/handler/index.md) — composition without a short-circuit +- [`Computer`](../../components/handler/computer.md) — the component family the bind providers implement. +- [Handler combinators](../../providers/handler/index.md) — composition without a short-circuit branch. The ideas behind it: diff --git a/docs/reference/traits/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md similarity index 72% rename from docs/reference/traits/monadic_bind.md rename to docs/reference/traits/monad/monadic_bind.md index 713b61a0..f344adc8 100644 --- a/docs/reference/traits/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -1,5 +1,6 @@ --- sidebar_label: 'MonadicBind' +sidebar_position: 1 --- # `MonadicBind` @@ -11,7 +12,7 @@ Turning a continuation into one bind step of a monadic pipeline. ### Generated machinery **You are not expected to name `MonadicBind`.** -[`PipeMonadic`](../providers/monad/pipe_monadic.md) bounds on it while folding a pipeline, and the monad +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) bounds on it while folding a pipeline, and the monad markers CGP ships already implement it. The one case for naming it is defining a monad of your own; otherwise this page is here to explain how a pipeline is assembled. @@ -24,29 +25,33 @@ short-circuit — the familiar `?`-style behaviour, expressed as composable prov syntax. Folding such a pipeline means asking the monad, once per step: *given everything built so far, what provider runs one bind?* -`MonadicBind` is that question: - -```rust -pub trait MonadicBind { - type Provider; -} -``` - -`Self` is the monad marker. The parameter is the **continuation** — the handler that should run on the -continue branch — and the associated type is the **bind provider** that wraps it. For the base monads -this resolves to a [`BindOk` or `BindErr`](../providers/monad/index.md) provider; for `IdentMonadic` -it is the continuation unchanged, which is what makes the identity monad free. +`MonadicBind` is that question. It is one of four traits that give a monad marker its meaning, alongside [`ContainsValue`](./contains_value.md), [`LiftValue`](./lift_value.md), and -[`MonadicTrans`](./monadic_trans.md). Keeping them apart is what lets one marker serve all four roles. +[`MonadicTrans`](./monadic_trans.md). Keeping them apart lets one marker serve all four roles. **This is a plain capability trait, not a CGP component.** It has no generated provider trait, no `…Component` marker, and is never wired through -[`delegate_components!`](../macros/delegate_components.md) — the -[monad providers](../providers/monad/index.md) consume it as an ordinary trait bound while folding a +[`delegate_components!`](../../macros/delegate_components.md): the +[monad providers](../../providers/monad/index.md) consume it as an ordinary trait bound while folding a pipeline at compile time. +## Definition + +`MonadicBind` carries a single associated type and no method: + +```rust +pub trait MonadicBind { + type Provider; +} +``` + +`Self` is the monad marker. The `Provider` parameter is the **continuation**, the handler that should +run on the continue branch, and the `Provider` associated type is the **bind provider** that wraps it. +For the base monads this resolves to a [`BindOk` or `BindErr`](../../providers/monad/index.md) provider; +for `IdentMonadic` it is the continuation unchanged, which makes the identity monad free. + ## Usage **It is not in the prelude.** Import it from `cgp::extra::monad::traits`: @@ -56,7 +61,7 @@ use cgp::extra::monad::traits::MonadicBind; ``` In practice you import it only when **defining a monad of your own**. Using the existing ones means -naming [`PipeMonadic`](../providers/monad/pipe_monadic.md) and a marker in a wiring entry, with no trait in +naming [`PipeMonadic`](../../providers/monad/pipe_monadic.md) and a marker in a wiring entry, with no trait in sight. There is no method. The whole trait is a type-level function from a continuation to the provider that @@ -65,7 +70,7 @@ binds it. ## Examples The trait is consumed rather than called, so the thing to read is what each marker's impl *says* — -because that is what decides how a pipeline behaves. +because that decides how a pipeline behaves. **`IdentMonadic` implements it as the identity**: `MonadicBind::Provider` is `Provider` unchanged. Nothing wraps the continuation, nothing branches, and a pipeline under `IdentMonadic` is @@ -87,9 +92,9 @@ own `Result` layer and hand the rest to `M`, which is how a stack reaches arbitr ## When to use it -**Reach for the [monad providers](../providers/monad/index.md), not this trait.** Building a pipeline -means wiring `PipeMonadic` with a monad marker and a handler list; this is what that provider bounds on -internally. +**Reach for the [monad providers](../../providers/monad/index.md), not this trait.** Building a pipeline +means wiring `PipeMonadic` with a monad marker and a handler list, and that provider bounds on this +trait internally. The one real reason to name it is **defining a new monad**, where you implement all four traits for a new marker. Implementing this one alone yields a marker that folds a pipeline and then fails to resolve when a @@ -98,14 +103,14 @@ step tries to run, because the running half is [`ContainsValue`](./contains_valu And the alternatives to prefer when you do *not* need short-circuiting: -- **[Handler combinators](../providers/handler/index.md)** — `ComposeHandlers` and `PipeHandlers` +- **[Handler combinators](../../providers/handler/index.md)** — `ComposeHandlers` and `PipeHandlers` chain handlers without a branch. If every step runs unconditionally, do not involve a monad at all. - **Ordinary `?` in one provider body** — if the whole chain lives in a single implementation, Rust's own operator is clearer than any composition. ## Under the hood -[`PipeMonadic`](../providers/monad/pipe_monadic.md) walks the handler list and, for each step, asks the monad +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) walks the handler list and, for each step, asks the monad to turn the continuation built so far into a bind step — which is this trait. Because the walk proceeds from the end of the list backwards, `Provider` at each stage is everything that follows the current step, and the result is a single nested provider by the time the list is exhausted. @@ -116,7 +121,7 @@ list-folding half of the four traits, while [`ContainsValue`](./contains_value.m [`LiftValue`](./lift_value.md) are the step-running half. The whole fold happens during trait resolution. A monadic pipeline is not a runtime structure, and the -provider it resolves to implements the [`Computer`](../components/handler/computer.md) family like any other +provider it resolves to implements the [`Computer`](../../components/handler/computer.md) family like any other handler. ## Common Mistakes @@ -124,11 +129,11 @@ handler. **It is not in the prelude.** Import from `cgp::extra::monad::traits`. **It is not a component and cannot be wired.** There is no `…Component` marker, so it never appears in a -[`delegate_components!`](../macros/delegate_components.md) block. What gets wired is the provider that +[`delegate_components!`](../../macros/delegate_components.md) block. What gets wired is the provider that consumes it. **`OkMonadic` short-circuits on `Ok`, not on `Err`.** The naming reads as "the monad *for* `Ok`" and means -"the monad whose continue branch is `Err`". [`ErrMonadic`](../providers/monad/index.md) is the one +"the monad whose continue branch is `Err`". [`ErrMonadic`](../../providers/monad/index.md) is the one that behaves like `?`. Getting these the wrong way round produces a pipeline that runs exactly when you expected it to stop. @@ -141,12 +146,12 @@ missing trait rather than the gap. - [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) — the two traits that run one bind step, where this one only builds it. - [`MonadicTrans`](./monadic_trans.md) — stacking one monad on another during the same fold. -- [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the monad +- [Monad providers](../../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the monad markers; what you actually wire. -- [Handler combinators](../providers/handler/index.md) — composition without a short-circuit +- [Handler combinators](../../providers/handler/index.md) — composition without a short-circuit branch. -- [`Computer`](../components/handler/computer.md) — the component family a monadic pipeline implements. -- [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. +- [`Computer`](../../components/handler/computer.md) — the component family a monadic pipeline implements. +- [`Product!`](../../macros/product.md) — the type-level list a pipeline's steps are given in. The ideas behind it: diff --git a/docs/reference/traits/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md similarity index 81% rename from docs/reference/traits/monadic_trans.md rename to docs/reference/traits/monad/monadic_trans.md index f58fc1eb..0127b652 100644 --- a/docs/reference/traits/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -1,5 +1,6 @@ --- sidebar_label: 'MonadicTrans' +sidebar_position: 4 --- # `MonadicTrans` @@ -11,7 +12,7 @@ Stacking one monad on top of another. ### Generated machinery **You are not expected to name `MonadicTrans`.** -[`PipeMonadic`](../providers/monad/pipe_monadic.md) resolves a stacked monad through it before any binding +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) resolves a stacked monad through it before any binding happens, and the transformer markers CGP ships already implement it. The one case for naming it is giving a monad of your own a transformer form; otherwise this page is here to explain how monads stack. @@ -21,17 +22,7 @@ a monad of your own a transformer form; otherwise this page is here to explain h A [monadic pipeline](/docs/concepts/monadic-handlers) over a nested output — a `Result` inside a `Result` — needs to peel more than one layer, and hard-coding a depth would give up the composability -the design exists for. `MonadicTrans` is how a monad is expressed as a *transformer* over another: - -```rust -pub trait MonadicTrans { - type M; -} -``` - -`Self` is the monad being applied, `M` is the base monad being transformed, and the associated `M` is the -resulting stack. That is what lets `OkMonadic` be written as `OkMonadicTrans` when a pipeline -operates over a nested result, layering one behaviour on top of another. +the design exists for. `MonadicTrans` is how a monad is expressed as a *transformer* over another. It is one of four traits that give a monad marker its meaning, and it belongs with [`MonadicBind`](./monadic_bind.md) as the pipeline-folding half: those two decide the *shape* of the @@ -41,6 +32,21 @@ each step. **This is a plain capability trait, not a CGP component.** It has no generated provider trait and is never wired. +## Definition + +`MonadicTrans` carries a single associated type and no method: + +```rust +pub trait MonadicTrans { + type M; +} +``` + +`Self` is the monad being applied, the `M` parameter is the base monad being transformed, and the +associated `M`, which shares the parameter's name, is the resulting stack. That lets `OkMonadic` be +written as `OkMonadicTrans` when a pipeline operates over a nested result, layering one +behaviour on top of another. + ## Usage **It is not in the prelude.** Import it from `cgp::extra::monad::traits`: @@ -77,17 +83,17 @@ An *n*-layer stack unwraps *n* layers with no code specific to any depth, which ## When to use it -**Reach for the [monad providers](../providers/monad/index.md), not this trait.** Wiring -[`PipeMonadic`](../providers/monad/pipe_monadic.md) with a marker — including a stacked one — is how a +**Reach for the [monad providers](../../providers/monad/index.md), not this trait.** Wiring +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker — including a stacked one — is how a pipeline is built. The reasons to name it are two, and both are narrow. - **Defining a new monad that should stack.** The three other traits give a marker meaning on its own; - this one is what lets it sit over another. A marker without it works as a base monad and cannot be a + this one lets it sit over another. A marker without it works as a base monad and cannot be a transformer. - **Reading a stacked marker in an error.** A resolution failure over a nested result usually names this - trait, and knowing it is the composition step rather than the running step is what tells you the + trait, and knowing it is the composition step rather than the running step tells you the problem is the stack's shape rather than a step's types. If your pipeline runs over a single-layer output, you do not need a transformer at all — use the base @@ -96,7 +102,7 @@ marker directly. ## Under the hood `MonadicTrans` is applied to the **monads** rather than to the handlers, and it runs *before* any binding -does. [`PipeMonadic`](../providers/monad/pipe_monadic.md) resolves the stacked monad first, then walks the +does. [`PipeMonadic`](../../providers/monad/pipe_monadic.md) resolves the stacked monad first, then walks the handler list asking [`MonadicBind`](./monadic_bind.md) to turn each continuation into a bind step. Because the transformer forms implement [`ContainsValue`](./contains_value.md) and @@ -132,10 +138,10 @@ bound rather than saying the marker is not stackable. step. - [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) — the two traits that run one step, where these two build the pipeline. -- [Monad providers](../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the markers, including the transformer forms. -- [`Computer`](../components/handler/computer.md) — the component family a monadic pipeline implements. -- [`Product!`](../macros/product.md) — the type-level list a pipeline's steps are given in. +- [`Computer`](../../components/handler/computer.md) — the component family a monadic pipeline implements. +- [`Product!`](../../macros/product.md) — the type-level list a pipeline's steps are given in. The ideas behind it: diff --git a/docs/reference/traits/namespace/_category_.json b/docs/reference/traits/namespace/_category_.json new file mode 100644 index 00000000..04e81835 --- /dev/null +++ b/docs/reference/traits/namespace/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Namespaces and defaults", + "position": 9, + "link": { + "type": "doc", + "id": "reference/traits/namespace/index" + } +} diff --git a/docs/reference/traits/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md similarity index 75% rename from docs/reference/traits/default_impls1.md rename to docs/reference/traits/namespace/default_impls1.md index f62b761a..9c09feff 100644 --- a/docs/reference/traits/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -1,5 +1,6 @@ --- sidebar_label: 'DefaultImpls1' +sidebar_position: 2 --- # `DefaultImpls1` @@ -11,8 +12,8 @@ Resolving a namespace default keyed on a component *and* a type. ### Generated machinery **You do not implement `DefaultImpls1`.** -[`#[default_impl(...)]`](../attributes/default_impl.md) emits the impls and a `for … in` statement inside -[`delegate_components!`](../macros/delegate_components.md) consumes them. You name the trait in those two +[`#[default_impl(...)]`](../../attributes/default_impl.md) emits the impls and a `for … in` statement inside +[`delegate_components!`](../../macros/delegate_components.md) consumes them. You name the trait in those two places only; this page explains what each of them emits, and the positional rule that is easy to get backwards. @@ -21,8 +22,12 @@ backwards. ## Overview [`DefaultNamespace`](./default_namespace.md) keys a default on the component alone: one component, one -default provider. `DefaultImpls1` adds a second type to the key, which is what a **per-type default** -needs — the same component resolving differently for `String` than for `u64`: +default provider. `DefaultImpls1` adds a second type to the key, which a **per-type default** +needs: the same component resolving differently for `String` than for `u64`. + +## Definition + +`DefaultImpls1` carries a single associated type and no method: ```rust pub trait DefaultImpls1 { @@ -30,11 +35,14 @@ pub trait DefaultImpls1 { } ``` -There is no method and no data. Resolving a default *is* projecting `Delegate` from the matching impl, -exactly as with [`DelegateComponent`](./delegate_component.md). +`Self` is the key being looked up — the *instance* type, such as `String`. `T` is the further lookup +type, which the attribute fills with the component name. `Components` is the table the lookup runs +against, and `Delegate` is the resolved provider. There is no method and no data, so resolving a default +projects `Delegate` from the matching impl, exactly as with +[`DelegateComponent`](../wiring/delegate_component.md). Three traits exist rather than one variadic trait because each fixes the key's arity at the type level, -which is what lets the projection `>` resolve cleanly. +which lets the projection `>` resolve cleanly. [`DefaultImpls2`](./default_impls2.md) is the two-type form. :::warning @@ -56,8 +64,8 @@ use cgp::core::component::DefaultImpls1; ``` **You name it in two places**: the target of a `for … in` loop inside -[`delegate_components!`](../macros/delegate_components.md), and the -[`#[default_impl(...)]`](../attributes/default_impl.md) attribute that registers a provider as a default. +[`delegate_components!`](../../macros/delegate_components.md), and the +[`#[default_impl(...)]`](../../attributes/default_impl.md) attribute that registers a provider as a default. The macros generate the impls and the forwarding. ### The one thing to get right @@ -144,26 +152,26 @@ same projection. **Use it for a per-type default, and reach for the simpler trait when the key is a component alone.** - **[`DefaultNamespace`](./default_namespace.md)** when one component has one default. That is the common - case, and it is what [`#[prefix(...)]`](../macros/cgp_namespace.md) registers into. -- **`DefaultImpls1`** when the same component resolves differently per type. This is what - [`#[default_impl]`](../attributes/default_impl.md) is usually pointed at. + case, and it is what [`#[prefix(...)]`](../../macros/cgp_namespace.md) registers a component into. +- **`DefaultImpls1`** when the same component resolves differently per type. + [`#[default_impl]`](../../attributes/default_impl.md) is usually pointed at it. - **[`DefaultImpls2`](./default_impls2.md)** for a two-type key. - **Define your own namespace trait** when you want a named table of your own; - [`#[default_impl]`](../attributes/default_impl.md) accepts any path, so these three are conveniences + [`#[default_impl]`](../../attributes/default_impl.md) accepts any path, so these three are conveniences rather than the only options. **One constraint decides where a `#[default_impl]` may be written, and it is Rust's orphan rule rather than anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, so a crate may register a default when it owns either the namespace trait or the key type. For an unprefixed component the key is the component's own marker, so a downstream crate owning the component can register into a foreign -namespace. For a [`#[prefix]`](../macros/cgp_namespace.md)-ed component the key is a path built from +namespace. For a [`#[prefix]`](../../macros/cgp_namespace.md)-ed component the key is a path built from `cgp`-owned types plus the marker, so the impl is orphan-legal **only in the namespace's own crate**. Wiring that must live downstream goes in the namespace body of the crate that owns it instead. ## Under the hood A `for in DefaultImpls1 { … }` loop emits a -[`DelegateComponent`](./delegate_component.md) impl whose `where` clause projects the default: +[`DelegateComponent`](../wiring/delegate_component.md) impl whose `where` clause projects the default: ```rust where T: DefaultImpls1 @@ -175,11 +183,11 @@ Read it as: for each type `T` that has a default, wire that key to the projected otherwise the parameter is unconstrained and the compiler rejects the impl with `E0207`, which reads as a puzzling error about a generic parameter rather than about the loop. -The registration side is the mirror. [`#[default_impl]`](../attributes/default_impl.md) emits an impl of +The registration side is the mirror. [`#[default_impl]`](../../attributes/default_impl.md) emits an impl of this trait for the key type, carrying **only** the parameters naming the key and provider plus the table — never the provider's own `where` clause. A provider whose bounds come from `#[use_type]`, `#[uses]`, `#[implicit]`, or `#[use_provider]` therefore registers cleanly, because those bounds stay on the -provider's impl and its [`IsProviderFor`](./is_provider_for.md), and are checked when a real context +provider's impl and its [`IsProviderFor`](../wiring/is_provider_for.md), and are checked when a real context resolves it. ## Common Mistakes @@ -204,12 +212,12 @@ where the provider is used rather than where it is registered. - [`DefaultNamespace`](./default_namespace.md) — the one-key form, and the common case. - [`DefaultImpls2`](./default_impls2.md) — the two-type form. -- [`#[default_impl(...)]`](../attributes/default_impl.md) — the attribute that emits impls of this trait. -- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. -- [`delegate_components!`](../macros/delegate_components.md) — carries the `for … in` loop. -- [`DelegateComponent`](./delegate_component.md) — what the loop ultimately writes. -- [`IsProviderFor`](./is_provider_for.md) — where a registered provider's real bounds are checked. -- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value. +- [`#[default_impl(...)]`](../../attributes/default_impl.md) — the attribute that emits impls of this trait. +- [`cgp_namespace!`](../../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. +- [`delegate_components!`](../../macros/delegate_components.md) — carries the `for … in` loop. +- [`DelegateComponent`](../wiring/delegate_component.md) — what the loop ultimately writes. +- [`IsProviderFor`](../wiring/is_provider_for.md) — where a registered provider's real bounds are checked. +- [`RedirectLookup`](../../providers/redirect_lookup.md) — the usual `Delegate` value. The ideas behind it: diff --git a/docs/reference/traits/default_impls2.md b/docs/reference/traits/namespace/default_impls2.md similarity index 78% rename from docs/reference/traits/default_impls2.md rename to docs/reference/traits/namespace/default_impls2.md index 6860facf..591476d8 100644 --- a/docs/reference/traits/default_impls2.md +++ b/docs/reference/traits/namespace/default_impls2.md @@ -1,5 +1,6 @@ --- sidebar_label: 'DefaultImpls2' +sidebar_position: 3 --- # `DefaultImpls2` @@ -11,7 +12,7 @@ Resolving a namespace default keyed on a component and *two* types. ### Generated machinery **You do not implement `DefaultImpls2`.** -[`#[default_impl(...)]`](../attributes/default_impl.md) emits the impls and a `for … in` statement +[`#[default_impl(...)]`](../../attributes/default_impl.md) emits the impls and a `for … in` statement consumes them, exactly as for its one-type sibling. You name the trait in those two places only; this page explains what they emit. @@ -19,8 +20,12 @@ page explains what they emit. ## Overview -[`DefaultImpls1`](./default_impls1.md) keys a namespace default on a component plus one type, which is -what a per-type default needs. `DefaultImpls2` is the same idea under a **pair** of types: +[`DefaultImpls1`](./default_impls1.md) keys a namespace default on a component plus one type, which a +per-type default needs. `DefaultImpls2` is the same idea under a **pair** of types. + +## Definition + +`DefaultImpls2` carries a single associated type and no method: ```rust pub trait DefaultImpls2 { @@ -28,10 +33,12 @@ pub trait DefaultImpls2 { } ``` -There is no method and no data — resolving a default is projecting `Delegate` from the matching impl. +`Self` is the key being looked up, `T1` and `T2` are the two further lookup types the attribute fills +from the namespace path, `Components` is the table, and `Delegate` is the resolved provider. There is no +method and no data, so resolving a default projects `Delegate` from the matching impl. Three traits exist rather than one variadic trait because each fixes the key's arity at the type level, -which is what lets the projection resolve cleanly. This is the widest of the three. +which lets the projection resolve cleanly. This is the widest of the three. :::warning @@ -59,9 +66,9 @@ impl DefaultImpls2 for Key { } ``` -Registration is [`#[default_impl(...)]`](../attributes/default_impl.md), which accepts an arbitrary +Registration is [`#[default_impl(...)]`](../../attributes/default_impl.md), which accepts an arbitrary namespace path and therefore needed no new construct to support this trait. Consumption is a `for … in` -loop inside [`delegate_components!`](../macros/delegate_components.md), whose bound projects `Delegate` +loop inside [`delegate_components!`](../../macros/delegate_components.md), whose bound projects `Delegate` the same way the one-type form does. ## Examples @@ -110,7 +117,7 @@ each extra key position is one more thing a reader has to hold. `#[default_impl]` is usually pointed at. - **`DefaultImpls2`** when two do — a conversion keyed on source *and* target, say. - **Define your own namespace trait** when the shape does not fit. - [`#[default_impl]`](../attributes/default_impl.md) accepts any path, so a trait of your own with + [`#[default_impl]`](../../attributes/default_impl.md) accepts any path, so a trait of your own with whatever arity you need works identically. Given that nothing in the library uses this one, a purpose-named trait is often the clearer choice. @@ -119,7 +126,7 @@ and is worked out on [its page](./default_impls1.md#when-to-use-it). ## Under the hood -A `for … in` loop emits a [`DelegateComponent`](./delegate_component.md) impl whose `where` clause +A `for … in` loop emits a [`DelegateComponent`](../wiring/delegate_component.md) impl whose `where` clause projects the default: ```rust @@ -158,11 +165,11 @@ library example. - [`DefaultImpls1`](./default_impls1.md) — the one-type form, and where the family's mechanics are worked out. - [`DefaultNamespace`](./default_namespace.md) — the component-only form. -- [`#[default_impl(...)]`](../attributes/default_impl.md) — the attribute that emits impls of this trait. -- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace. -- [`delegate_components!`](../macros/delegate_components.md) — carries the `for … in` loop. -- [`DelegateComponent`](./delegate_component.md) — what the loop ultimately writes. -- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value. +- [`#[default_impl(...)]`](../../attributes/default_impl.md) — the attribute that emits impls of this trait. +- [`cgp_namespace!`](../../macros/cgp_namespace.md) — defines a namespace. +- [`delegate_components!`](../../macros/delegate_components.md) — carries the `for … in` loop. +- [`DelegateComponent`](../wiring/delegate_component.md) — what the loop ultimately writes. +- [`RedirectLookup`](../../providers/redirect_lookup.md) — the usual `Delegate` value. The ideas behind it: diff --git a/docs/reference/traits/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md similarity index 67% rename from docs/reference/traits/default_namespace.md rename to docs/reference/traits/namespace/default_namespace.md index b1dc7a05..03de2ea6 100644 --- a/docs/reference/traits/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -1,5 +1,6 @@ --- sidebar_label: 'DefaultNamespace' +sidebar_position: 1 --- # `DefaultNamespace` @@ -11,10 +12,10 @@ Resolving a namespace's default provider for a component. ### Generated machinery **You do not implement `DefaultNamespace`.** -[`cgp_namespace!`](../macros/cgp_namespace.md) and its -[`#[prefix(...)]`](../macros/cgp_namespace.md) attribute emit the impls. You name the trait in exactly +[`cgp_namespace!`](../../macros/cgp_namespace.md) and its +[`#[prefix(...)]`](../../macros/cgp_namespace.md) attribute emit the impls. You name the trait in exactly one place — a `namespace` header inside -[`delegate_components!`](../macros/delegate_components.md) — and this page explains what that header +[`delegate_components!`](../../macros/delegate_components.md) — and this page explains what that header generates, including why a direct entry can shadow an inherited default without conflicting with it. ::: @@ -25,7 +26,16 @@ A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings type the capability runs against — can opt into and then selectively override. Resolving one of those defaults means asking: *for this component, what does the namespace delegate to?* -`DefaultNamespace` is what answers that: +`DefaultNamespace` answers that. It is the simplest of three lookup traits, keyed on the component alone. +[`DefaultImpls1`](./default_impls1.md) adds one further type for a *per-type* default, and +[`DefaultImpls2`](./default_impls2.md) does the same under a pair. + +**You name it in one place**: the `namespace` header of a wiring block. The macros generate the impls and +the forwarding, so this page is mostly about reading what they generate. + +## Definition + +`DefaultNamespace` carries a single associated type and no method: ```rust pub trait DefaultNamespace { @@ -33,24 +43,18 @@ pub trait DefaultNamespace { } ``` -`Self` is the component being looked up, `Components` is the table the lookup runs against — threaded -through so one key can resolve differently per context — and `Delegate` is the resolved provider. There -is no method and no data; resolving a default *is* projecting `Delegate` from the matching impl, exactly -as with [`DelegateComponent`](./delegate_component.md). - -It is the simplest of three lookup traits, keyed on the component alone. -[`DefaultImpls1`](./default_impls1.md) adds one further type for a *per-type* default, and -[`DefaultImpls2`](./default_impls2.md) does the same under a pair. - -**You name it in one place**: the `namespace` header of a wiring block. The macros generate the impls and -the forwarding, so this page is mostly about reading what they generate. +`Self` is the component being looked up. `Components` is the table the lookup runs against, threaded +through as a parameter so one key can resolve differently for each context. `Delegate` is the resolved +value: the provider the key maps to. There is no method and no data, so resolving a default projects +`Delegate` from the matching impl, exactly as with +[`DelegateComponent`](../wiring/delegate_component.md). ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough — unlike its two siblings, which are not. A context joins a namespace with a header inside -[`delegate_components!`](../macros/delegate_components.md): +[`delegate_components!`](../../macros/delegate_components.md): ```rust delegate_components! { @@ -61,7 +65,7 @@ delegate_components! { ``` after which every lookup `App` does not wire directly forwards through the namespace. A component -registers into one with the [`#[prefix(...)]`](../macros/cgp_namespace.md) attribute on its +registers into one with the [`#[prefix(...)]`](../../macros/cgp_namespace.md) attribute on its `#[cgp_component]` trait. ## Examples @@ -94,24 +98,24 @@ the inheritance-with-override shape presets rely on. ## When to use it -**Write [`cgp_namespace!`](../macros/cgp_namespace.md) and the wiring statements; name this trait only +**Write [`cgp_namespace!`](../../macros/cgp_namespace.md) and the wiring statements; name this trait only where the syntax requires it.** It appears in a `namespace` header and nowhere else in ordinary code. - **Use `DefaultNamespace`** for a namespace whose defaults are per component, which is the common case - and what [`#[prefix(...)]`](../macros/cgp_namespace.md) registers into. + and what [`#[prefix(...)]`](../../macros/cgp_namespace.md) registers into. - **Use [`DefaultImpls1`](./default_impls1.md)** for a per-type default, where one component resolves differently per type. - **Define your own namespace trait instead** when you want a named table of your own; - [`cgp_namespace!`](../macros/cgp_namespace.md) generates one, so this is a convenience rather than the + [`cgp_namespace!`](../../macros/cgp_namespace.md) generates one, so this is a convenience rather than the only option. - **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. A namespace buys reuse and inheritance at the cost of one more indirection to follow when reading, and a - short [`delegate_components!`](../macros/delegate_components.md) block needs neither. + short [`delegate_components!`](../../macros/delegate_components.md) block needs neither. ## Under the hood A `namespace N;` header does not emit one entry — it emits a **blanket** -[`DelegateComponent`](./delegate_component.md) impl on the context that forwards every key through the +[`DelegateComponent`](../wiring/delegate_component.md) impl on the context that forwards every key through the namespace: ```rust @@ -123,10 +127,10 @@ where } ``` -paired with the matching [`IsProviderFor`](./is_provider_for.md) forwarding so dependencies stay +paired with the matching [`IsProviderFor`](../wiring/is_provider_for.md) forwarding so dependencies stay diagnosable. -**That blanket is what makes override work.** A directly-wired entry is a *concrete* impl for one key, +**That blanket makes override work.** A directly-wired entry is a *concrete* impl for one key, and a concrete impl is more specific than the blanket, so it resolves first — shadowing the inherited default for that key and leaving the rest untouched. Two *concrete* entries for one key would conflict; a concrete entry against a blanket does not. @@ -152,21 +156,21 @@ type takes the `Self` position instead. The inconsistency is the family's sharpe **Registering into a foreign namespace is bound by the orphan rule** — see [`DefaultImpls1`](./default_impls1.md#when-to-use-it), where the -[`#[default_impl]`](../attributes/default_impl.md) attribute's placement constraint is worked out. +[`#[default_impl]`](../../attributes/default_impl.md) attribute's placement constraint is worked out. ## Related constructs - [`DefaultImpls1`](./default_impls1.md) and [`DefaultImpls2`](./default_impls2.md) — the per-type and per-pair variants. -- [`#[default_impl(...)]`](../attributes/default_impl.md) — the attribute that registers a provider as a +- [`#[default_impl(...)]`](../../attributes/default_impl.md) — the attribute that registers a provider as a default. -- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. -- [`delegate_components!`](../macros/delegate_components.md) — carries the `namespace` header. -- [`DelegateComponent`](./delegate_component.md) — what a namespace header forwards *into*. -- [`IsProviderFor`](./is_provider_for.md) — forwarded alongside, so dependency errors stay readable. -- [`RedirectLookup`](../providers/redirect_lookup.md) — the usual `Delegate` value, re-routing along a +- [`cgp_namespace!`](../../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. +- [`delegate_components!`](../../macros/delegate_components.md) — carries the `namespace` header. +- [`DelegateComponent`](../wiring/delegate_component.md) — what a namespace header forwards *into*. +- [`IsProviderFor`](../wiring/is_provider_for.md) — forwarded alongside, so dependency errors stay readable. +- [`RedirectLookup`](../../providers/redirect_lookup.md) — the usual `Delegate` value, re-routing along a path. -- [`Path!`](../macros/path.md) — the paths a prefixed key is built from. +- [`Path!`](../../macros/path.md) — the paths a prefixed key is built from. The ideas behind it: diff --git a/docs/reference/traits/namespace/index.md b/docs/reference/traits/namespace/index.md new file mode 100644 index 00000000..24085ffd --- /dev/null +++ b/docs/reference/traits/namespace/index.md @@ -0,0 +1,39 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Namespaces and defaults + +The lookup traits behind a namespace and a per-type default. + +## Overview + +A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a context opts into +and then selectively overrides. Resolving one of those defaults means asking, for a given key, what the +namespace delegates to — and these three traits answer it, differing only in how many types take part +in the key. You name them where the syntax requires it: a `namespace` header or a `for … in` loop +inside [`delegate_components!`](../../macros/delegate_components.md), and the +[`#[default_impl]`](../../attributes/default_impl.md) attribute. The macros generate the impls. + +- [`DefaultNamespace`](default_namespace.md) keys a default on the component alone, the common case that + [`#[prefix(...)]`](../../macros/cgp_namespace.md) registers into. It is the one member of the group + that is in the prelude. +- [`DefaultImpls1`](default_impls1.md) adds one further type, for a per-type default where the same + component resolves differently for `String` than for `u64`. +- [`DefaultImpls2`](default_impls2.md) does the same under a pair of types. Nothing in the library emits + it; it is a provided extension point. + +One edge is worth carrying across the group: for the two `DefaultImpls` traits the instance type takes +the `Self` position and the component name is a leading parameter, which is the opposite of the +parameter names' suggestion. The [`DefaultImpls1`](default_impls1.md#the-one-thing-to-get-right) page +works it out. + +## The ideas behind them + +- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style + configuration. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/_category_.json b/docs/reference/traits/optional/_category_.json new file mode 100644 index 00000000..e9dcb2b0 --- /dev/null +++ b/docs/reference/traits/optional/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Optional and defaulted fields", + "position": 5, + "link": { + "type": "doc", + "id": "reference/traits/optional/index" + } +} diff --git a/docs/reference/traits/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md similarity index 66% rename from docs/reference/traits/can_build_with_default.md rename to docs/reference/traits/optional/can_build_with_default.md index 560602ba..429573b3 100644 --- a/docs/reference/traits/can_build_with_default.md +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -1,5 +1,6 @@ --- sidebar_label: 'CanBuildWithDefault' +sidebar_position: 6 --- # `CanBuildWithDefault` @@ -10,7 +11,19 @@ Widening one record into another in a single call. Turning a narrow record into a wider one whose extra fields have sensible defaults is a three-step motion: start a builder, copy the shared fields, default the rest. `CanBuildWithDefault` is that motion as one -call: +call. + +`Self` is the target record and `Source` the narrower one. **It is the field-level counterpart of an +[upcast](../casting/can_upcast.md)** — turning a `Point2d` into a `Point3d` whose extra `z` is `0`, naming no field +explicitly. + +It chains [`builder()`](../builder/has_builder.md), [`build_from`](../casting/can_build_from.md), and +[`finalize_with_default`](./can_finalize_with_default.md), and it is worth reaching for precisely because +those three lines together read as plumbing. + +## Definition + +`CanBuildWithDefault` is keyed by the source record and builds the target directly: ```rust pub trait CanBuildWithDefault { @@ -18,13 +31,13 @@ pub trait CanBuildWithDefault { } ``` -`Self` is the target record and `Source` the narrower one. **It is the field-level counterpart of an -[upcast](./can_upcast.md)** — turning a `Point2d` into a `Point3d` whose extra `z` is `0`, naming no field -explicitly. - -It chains [`builder()`](./has_builder.md), [`build_from`](./can_build_from.md), and -[`finalize_with_default`](./can_finalize_with_default.md), and it is worth reaching for precisely because -those three lines together read as plumbing. +`Source` is the narrower record and `Self` is the target. `build_with_default` is an associated function +with no receiver, and it returns a fully built `Self`. The trait declares no associated type and no +supertrait; it is a blanket impl chaining a builder, a merge, and a defaulted finalize, shown in +[*Under the hood*](#under-the-hood). Two requirements follow from that chain: the source needs +[`HasFields`](../shape/has_fields.md), because the merge walks its field list, and every field the source +does not supply needs `Default`, because the finalize fills it. It is not in the prelude; import it from +`cgp-field-extra`. ## Usage @@ -36,10 +49,6 @@ use cgp::extra::field::impls::CanBuildWithDefault; It is an **associated function**, called on the target: `Point3d::build_with_default(point_2d)`. -Two requirements come from the steps it chains. **The source needs [`HasFields`](./has_fields.md)**, -because [`build_from`](./can_build_from.md) walks the source's field list — the same requirement any merge -carries. And **every field the source does not supply needs `Default`**, because the finalize fills them. - ## Examples Widening a record with no field named anywhere: @@ -75,10 +84,10 @@ let point_3d: Point3d = Point3d::builder() **Reach for it for a one-call widening from a narrower record**, and reach for the pieces when anything in between needs to happen. -- **[`CanBuildFrom`](./can_build_from.md) plus an explicit finalize** when some fields must be set by +- **[`CanBuildFrom`](../casting/can_build_from.md) plus an explicit finalize** when some fields must be set by hand as well as copied. This trait offers no place to insert a `build_field`. - **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when there is no source to merge from. -- **[`CanUpcast`](./can_upcast.md)** for the enum analogue — widening a variant set rather than a field +- **[`CanUpcast`](../casting/can_upcast.md)** for the enum analogue — widening a variant set rather than a field set. - **A plain `From` impl** when both types are yours and the conversion is one you would write once. A hand-written `From` is clearer, requires nothing of either type, and lets you choose values other than @@ -99,10 +108,10 @@ The impl chains the three steps and constrains each with a bound: // } ``` -Each bound is where one of the requirements comes from: [`CanBuildFrom`](./can_build_from.md) brings the -[`HasFields`](./has_fields.md) obligation on the source, and +Each bound is where one of the requirements comes from: [`CanBuildFrom`](../casting/can_build_from.md) brings the +[`HasFields`](../shape/has_fields.md) obligation on the source, and [`CanFinalizeWithDefault`](./can_finalize_with_default.md) brings the `Default` obligation on the -remaining fields — through a [`TransformMapFields`](./transform_map_fields.md) walk carrying +remaining fields — through a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying [`TransformMapDefault`](./transform_map_default.md). So an unsatisfied bound here is always really an unsatisfied bound one layer down, which is worth knowing @@ -112,12 +121,12 @@ because the error names that layer rather than this trait. **It is not in the prelude.** Import from `cgp::extra::field::impls`. -**The source needs [`HasFields`](./has_fields.md), not just a builder.** Deriving only -[`BuildField`](../derives/derive_build_field.md) on both looks symmetric and fails — the same trap -[`CanBuildFrom`](./can_build_from.md) carries. +**The source needs [`HasFields`](../shape/has_fields.md), not just a builder.** Deriving only +[`BuildField`](../../derives/derive_build_field.md) on both looks symmetric and fails — the same trap +[`CanBuildFrom`](../casting/can_build_from.md) carries. **Every field the source does not supply needs `Default`.** The error names the missing -[`TransformMap`](./transform_map.md) impl rather than the field. +[`TransformMap`](../type-level/transform_map.md) impl rather than the field. **It is an associated function on the target.** `Point3d::build_with_default(source)`, not a method on the source. @@ -128,13 +137,13 @@ the source. ## Related constructs -- [`CanBuildFrom`](./can_build_from.md) — the merge step, and where the source's requirements come from. +- [`CanBuildFrom`](../casting/can_build_from.md) — the merge step, and where the source's requirements come from. - [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the defaulting finalize step. -- [`HasBuilder`](./has_builder.md) — the builder it starts from. +- [`HasBuilder`](../builder/has_builder.md) — the builder it starts from. - [`TransformMapDefault`](./transform_map_default.md) — the marker behind the defaulting. -- [`CanUpcast`](./can_upcast.md) — the enum analogue of widening. -- [`HasFields`](./has_fields.md) — what the source must derive. -- [`#[derive(CgpRecord)]`](../derives/derive_cgp_record.md) — what makes both records eligible. +- [`CanUpcast`](../casting/can_upcast.md) — the enum analogue of widening. +- [`HasFields`](../shape/has_fields.md) — what the source must derive. +- [`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md) — what makes both records eligible. The ideas behind it: diff --git a/docs/reference/traits/can_finalize_with_default.md b/docs/reference/traits/optional/can_finalize_with_default.md similarity index 75% rename from docs/reference/traits/can_finalize_with_default.md rename to docs/reference/traits/optional/can_finalize_with_default.md index cb7c2f3a..e0655c70 100644 --- a/docs/reference/traits/can_finalize_with_default.md +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -1,5 +1,6 @@ --- sidebar_label: 'CanFinalizeWithDefault' +sidebar_position: 5 --- # `CanFinalizeWithDefault` @@ -8,23 +9,14 @@ Finalizing a partial record, filling whatever is unset from `Default`. ## Overview -The core [builder family](./has_builder.md) refuses to finalize an incomplete record, which is what +The core [builder family](../builder/has_builder.md) refuses to finalize an incomplete record, which is what catches a missing field at compile time. For a record where some fields have sensible defaults, that -strictness is the wrong shape. `CanFinalizeWithDefault` relaxes it: - -```rust -pub trait CanFinalizeWithDefault { - type Output; - - fn finalize_with_default(self) -> Self::Output; -} -``` - -Every field that is not set becomes `Default::default()`, and the result is the concrete struct. +strictness is the wrong shape. `CanFinalizeWithDefault` relaxes it: every field that is not set becomes +`Default::default()`, and the result is the concrete struct. **The strict presence check still runs — it just always passes**, because the fields are re-marked to `IsPresent` first. That is the layer's whole design in one sentence, and it is why the core -[`FinalizeBuild`](./finalize_build.md) remains the only route from a partial value to a struct. +[`FinalizeBuild`](../builder/finalize_build.md) remains the only route from a partial value to a struct. It is one of two endings for a partial builder, and the choice is made at the call site: @@ -33,6 +25,27 @@ It is one of two endings for a partial builder, and the choice is made at the ca | `CanFinalizeWithDefault` | filled from `Default` | | [`FinalizeOptional`](./finalize_optional.md) | `Err("field_name")` | +## Definition + +`CanFinalizeWithDefault` carries the finished struct as an associated `Output` and finalizes a partial +record into it: + +```rust +pub trait CanFinalizeWithDefault { + type Output; + + fn finalize_with_default(self) -> Self::Output; +} +``` + +`Self` is any partial builder whose fields can be re-marked to all-present, which covers a core builder +from [`builder()`](../builder/has_builder.md) as well as an optional one from +[`optional_builder()`](./has_optional_builder.md). `Output` is the concrete struct being built. +`finalize_with_default` takes `self`, consuming the builder, and returns that struct with every unset +field filled from `Default`. The trait has no supertrait; it is a blanket impl over the +transform-then-finalize shown in [*Under the hood*](#under-the-hood). It is not in the prelude; import it +from `cgp-field-extra`. + ## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: @@ -41,13 +54,9 @@ It is one of two endings for a partial builder, and the choice is made at the ca use cgp::extra::field::impls::CanFinalizeWithDefault; ``` -`Output` is the concrete struct. It applies to any partial value whose fields can be transformed to -all-present, which covers a core builder from [`builder()`](./has_builder.md) as well as an optional one -from [`optional_builder()`](./has_optional_builder.md). - **Every unset field's type needs `Default`.** A field whose type has none makes the transform unresolvable, and the error names the missing -[`TransformMap`](./transform_map.md) impl rather than the field. +[`TransformMap`](../type-level/transform_map.md) impl rather than the field. ## Examples @@ -83,7 +92,7 @@ The one-call form that also copies from a source is - **[`FinalizeOptional`](./finalize_optional.md)** when absence is an error worth reporting. The two are the same builder finalized differently. -- **[`FinalizeBuild`](./finalize_build.md)** — the core builder — when every field is genuinely +- **[`FinalizeBuild`](../builder/finalize_build.md)** — the core builder — when every field is genuinely required. A missing field is then a compile error, which is strictly stronger. - **[`CanBuildWithDefault`](./can_build_with_default.md)** when the set fields come from another record rather than from individual calls. It chains the merge and this finalize into one call. @@ -112,7 +121,7 @@ Read the bounds together: the first says every field can be re-marked to `IsPres [`TransformMapDefault`](./transform_map_default.md), and the second says the result is then finalizable. Its mirror image is [`ToOptional`](./to_optional.md), which runs the same -[`TransformMapFields`](./transform_map_fields.md) walk with +[`TransformMapFields`](../type-level/transform_map_fields.md) walk with [`TransformOptional`](./transform_optional.md) toward `IsOptional`. **Both capabilities are the same recursion with a different marker**, which is why the defaulted and optional workflows behave so symmetrically. @@ -125,7 +134,7 @@ configuration its single impl requires — so the strict check runs, and cannot **It is not in the prelude.** Import from `cgp::extra::field::impls`. **Every field's type needs `Default`.** A field whose type has none makes the transform unresolvable, and -the error names the missing [`TransformMap`](./transform_map.md) impl rather than the field — which is +the error names the missing [`TransformMap`](../type-level/transform_map.md) impl rather than the field — which is the most confusing failure in this layer. **A defaulted field is silent.** Nothing distinguishes "set to zero" from "left unset" in the result, which @@ -143,12 +152,12 @@ transformed as readily as a `None`. - [`FinalizeOptional`](./finalize_optional.md) — the other ending, reporting rather than filling. - [`CanBuildWithDefault`](./can_build_with_default.md) — merge and default in one call. - [`TransformMapDefault`](./transform_map_default.md) — the marker this drives. -- [`TransformMapFields`](./transform_map_fields.md) — the walk it runs. -- [`FinalizeBuild`](./finalize_build.md) — the strict impl it ultimately calls. +- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk it runs. +- [`FinalizeBuild`](../builder/finalize_build.md) — the strict impl it ultimately calls. - [`HasOptionalBuilder`](./has_optional_builder.md) and [`ToOptional`](./to_optional.md) — the optional entry points. -- [`HasBuilder`](./has_builder.md) — the core family this relaxes. -- [`MapType`](./map_type.md) — the markers the transform moves between. +- [`HasBuilder`](../builder/has_builder.md) — the core family this relaxes. +- [`MapType`](../type-level/map_type.md) — the markers the transform moves between. The ideas behind it: diff --git a/docs/reference/traits/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md similarity index 69% rename from docs/reference/traits/finalize_optional.md rename to docs/reference/traits/optional/finalize_optional.md index b1374ef8..d7a636ae 100644 --- a/docs/reference/traits/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -1,5 +1,6 @@ --- sidebar_label: 'FinalizeOptional' +sidebar_position: 4 --- # `FinalizeOptional` @@ -10,17 +11,8 @@ Finalizing an optional builder, reporting the first missing field. An [optional builder](./has_optional_builder.md) has given up the compile-time completeness check: every field is `IsOptional`, so the type no longer records what has been set. Something has to check at run -time instead, and `FinalizeOptional` is the strict way to do it: - -```rust -pub trait FinalizeOptional: PartialData { - fn finalize_optional(self) -> Result; -} -``` - -It succeeds only if every field holds a value. The error is **the first missing field's own name**, as a -`&'static str` recovered from the field's type-level tag — so a caller learns which field was left unset -without any allocation. +time instead, and `FinalizeOptional` is the strict way to do it: it succeeds only if every field holds a +value, and otherwise reports the first missing field by name. It is one of two endings for an optional builder, and the choice between them is made at the call site rather than when the builder is created: @@ -30,6 +22,24 @@ rather than when the builder is created: | `FinalizeOptional` | `Err("field_name")` | | [`CanFinalizeWithDefault`](./can_finalize_with_default.md) | filled from `Default` | +## Definition + +`FinalizeOptional` supertraits [`PartialData`](../builder/partial_data.md) and finalizes an optional +builder into its concrete struct: + +```rust +pub trait FinalizeOptional: PartialData { + fn finalize_optional(self) -> Result; +} +``` + +The `PartialData` supertrait supplies `Target`, the concrete struct being built, so the method projects +its return type through it and declares no associated type of its own. `finalize_optional` takes `self`, +consuming the builder, and returns `Result`: the built struct on success, +or, on failure, the first missing field's own name, recovered from its type-level tag as a `&'static +str` with no allocation. The trait carries no other parameter. It is not in the prelude; import it from +`cgp-field-extra`. + ## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: @@ -38,9 +48,6 @@ rather than when the builder is created: use cgp::extra::field::impls::FinalizeOptional; ``` -It supertraits [`PartialData`](./partial_data.md), which is where `Target` — the concrete struct being -built — comes from. - `Self` must be an optional builder, from [`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md). @@ -84,9 +91,9 @@ assert_eq!(result.err(), Some("bar")); - **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when unset fields have meaningful defaults and silence is the right outcome. The two are the same builder finalized differently, so the same value can go either way. -- **[`FinalizeBuild`](./finalize_build.md)** — that is, the core builder — when every field is genuinely +- **[`FinalizeBuild`](../builder/finalize_build.md)** — that is, the core builder — when every field is genuinely required and set once. A missing field is then a *compile* error, which is strictly better than a - `Result` and is what you give up by moving to this layer. + `Result`, and moving to this layer gives that check up. - **A hand-written check** when the validation is more than presence: interdependent fields, ranges, anything needing a structured error. @@ -97,20 +104,20 @@ which field is missing and not enough to match on programmatically. ## Under the hood Unlike its defaulting sibling, `FinalizeOptional` does **not** go through -[`TransformMapFields`](./transform_map_fields.md). It walks the target's -[`HasFields`](./has_fields.md) spine directly, and the reason is that it has to be able to *stop*. +[`TransformMapFields`](../type-level/transform_map_fields.md). It walks the target's +[`HasFields`](../shape/has_fields.md) spine directly, and the reason is that it has to be able to *stop*. -For each field it pulls the `Option` out with [`UpdateField`](./update_field.md), and: +For each field it pulls the `Option` out with [`UpdateField`](../builder/update_field.md), and: -- if it is `Some`, writes the value back as `IsPresent` with [`BuildField`](./build_field.md) and +- if it is `Some`, writes the value back as `IsPresent` with [`BuildField`](../builder/build_field.md) and continues; - if it is `None`, returns `Err(Tag::VALUE)` immediately — the field's name recovered as a static string - through [`StaticString`](./static_string.md). + through [`StaticString`](../formatting/static_string.md). Only if every field yields a value does the walk reach the all-present configuration and call -[`finalize_build`](./finalize_build.md). +[`finalize_build`](../builder/finalize_build.md). -**The strict, all-present [`FinalizeBuild`](./finalize_build.md) remains the only way a partial value +**The strict, all-present [`FinalizeBuild`](../builder/finalize_build.md) remains the only way a partial value becomes a concrete struct.** Everything in this layer simply guarantees that configuration is reached before it is invoked — or reports why it could not be. @@ -129,7 +136,7 @@ cannot be matched on beyond string comparison. **It does not apply to a core builder.** The fields must be `IsOptional`; a core builder either finalizes at compile time or does not. -**It supertraits [`PartialData`](./partial_data.md)**, so `Target` is projected from there and naming +**It supertraits [`PartialData`](../builder/partial_data.md)**, so `Target` is projected from there and naming both in a bound is redundant. **Field order decides which name you get**, since the walk follows declaration order and stops at the @@ -142,11 +149,11 @@ first `None`. - [`HasOptionalBuilder`](./has_optional_builder.md) and [`ToOptional`](./to_optional.md) — where an optional builder comes from. - [`SetOptional`](./set_optional.md) — filling one. -- [`FinalizeBuild`](./finalize_build.md) — the strict impl this ultimately calls. -- [`PartialData`](./partial_data.md) — the supertrait naming the destination. -- [`StaticString`](./static_string.md) — how the missing field's name is recovered. -- [`UpdateField`](./update_field.md) and [`BuildField`](./build_field.md) — the primitives the walk uses. -- [`HasFields`](./has_fields.md) — the shape it walks. +- [`FinalizeBuild`](../builder/finalize_build.md) — the strict impl this ultimately calls. +- [`PartialData`](../builder/partial_data.md) — the supertrait naming the destination. +- [`StaticString`](../formatting/static_string.md) — how the missing field's name is recovered. +- [`UpdateField`](../builder/update_field.md) and [`BuildField`](../builder/build_field.md) — the primitives the walk uses. +- [`HasFields`](../shape/has_fields.md) — the shape it walks. The ideas behind it: diff --git a/docs/reference/traits/has_optional_builder.md b/docs/reference/traits/optional/has_optional_builder.md similarity index 67% rename from docs/reference/traits/has_optional_builder.md rename to docs/reference/traits/optional/has_optional_builder.md index e0094f08..cc017360 100644 --- a/docs/reference/traits/has_optional_builder.md +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasOptionalBuilder' +sidebar_position: 1 --- # `HasOptionalBuilder` @@ -8,12 +9,24 @@ Starting a builder in which every field is already optional. ## Overview -The core [builder family](./has_builder.md) is deliberately strict: a field is set exactly once, and a +The core [builder family](../builder/has_builder.md) is deliberately strict: a field is set exactly once, and a partial record becomes its concrete struct only when **every** field is present. That strictness is what catches a missing field at compile time, and it is too rigid for a record whose fields arrive in an unpredictable order, or more than once. -`HasOptionalBuilder` is the entry point that relaxes it: +`HasOptionalBuilder` is the entry point that relaxes it. It hands back a partial value with every field +marked `IsOptional` rather than `IsNothing`, so each slot holds an `Option` and **absence becomes a +runtime condition instead of a type-level one.** Fields can then be set freely with +[`SetOptional`](./set_optional.md), in any order and as many times as you like, and the choice of how to +end is deferred to the finalize call. + +It stands to [`HasBuilder`](../builder/has_builder.md) as the optional layer stands to the core one: same +machinery, different starting marker. + +## Definition + +`HasOptionalBuilder` carries the partial builder type as an associated `Builder` and hands back an empty +one: ```rust pub trait HasOptionalBuilder { @@ -23,13 +36,12 @@ pub trait HasOptionalBuilder { } ``` -It hands back a partial value with every field marked `IsOptional` rather than `IsNothing` — so each -slot holds an `Option` and **absence becomes a runtime condition instead of a type-level one.** Fields -can then be set freely with [`SetOptional`](./set_optional.md), in any order and as many times as you -like, and the choice of how to end is deferred to the finalize call. - -It stands to [`HasBuilder`](./has_builder.md) as the optional layer stands to the core one: same -machinery, different starting marker. +`Builder` names the partial companion type the derive generated, with every field marked `IsOptional`. +It is the same companion the core builder produces, at a configuration the core builder never starts +from. `optional_builder` is an associated function with no receiver, so a caller writes +`Context::optional_builder()`. The trait carries no supertrait, and it is implemented as a blanket impl +over the core builder machinery, so any record that derives the builder gains it. It is not in the +prelude; the whole optional-field layer lives in `cgp-field-extra`. ## Usage @@ -40,11 +52,9 @@ machinery, different starting marker. use cgp::extra::field::impls::HasOptionalBuilder; ``` -`optional_builder()` is an associated function with no receiver: `Context::optional_builder()`. - The impls are blanket ones over the core builder machinery, so any record deriving -[`#[derive(BuildField)]`](../derives/derive_build_field.md) — or -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — gets this for free. There is no separate derive. +[`#[derive(BuildField)]`](../../derives/derive_build_field.md) — or +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — gets this for free. There is no separate derive. **Two endings are available**, and picking between them at the call site is the layer's real payoff: [`FinalizeOptional`](./finalize_optional.md) requires every field and reports the first missing one, while @@ -92,7 +102,7 @@ Had that used `finalize_optional`, it would have returned `Err("bar")` instead. **Reach for it when fields must be settable in any order and more than once**, which the core `build_field` cannot do — and stay on the core builder otherwise. -- **[`HasBuilder`](./has_builder.md)** when every field is genuinely required and set once. You lose the +- **[`HasBuilder`](../builder/has_builder.md)** when every field is genuinely required and set once. You lose the compile-time completeness check by moving here, and that check is the reason the builder family exists. - **`HasOptionalBuilder`** when the fields arrive unpredictably — parsed configuration, accumulated @@ -105,9 +115,9 @@ Had that used `finalize_optional`, it would have returned `Err("bar")` instead. ## Under the hood -`optional_builder()` is [`HasBuilder`](./has_builder.md)'s `builder()` followed by +`optional_builder()` is [`HasBuilder`](../builder/has_builder.md)'s `builder()` followed by [`ToOptional`](./to_optional.md) — start at all-`IsNothing`, then re-mark every field to `IsOptional` -with a [`TransformMapFields`](./transform_map_fields.md) walk carrying the +with a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying the [`TransformOptional`](./transform_optional.md) marker. So the resulting type is the same partial companion the core builder uses, at a configuration the core @@ -119,8 +129,8 @@ builder never reaches on its own: Nothing about the companion type is special to this layer. What changes is the marker, and with it which operations apply: [`SetOptional`](./set_optional.md) resolves where -[`BuildField`](./build_field.md) does not, and the strict -[`FinalizeBuild`](./finalize_build.md) does not resolve at all until a finalize has re-marked the fields +[`BuildField`](../builder/build_field.md) does not, and the strict +[`FinalizeBuild`](../builder/finalize_build.md) does not resolve at all until a finalize has re-marked the fields back to `IsPresent`. ## Common Mistakes @@ -133,7 +143,7 @@ compile error; here it is an `Err` or a silently substituted default. That is th making consciously. **The builder's type does not record what you have set.** Every field stays `IsOptional` throughout, -which is what allows re-setting and is why finalizing has to check at run time. +which allows re-setting and is why finalizing has to check at run time. **`optional_builder()` is an associated function**, so it is `Context::optional_builder()` with no receiver. @@ -148,10 +158,10 @@ Conflating them produces an `Option>`. - [`FinalizeOptional`](./finalize_optional.md) — the strict ending, reporting the first missing field. - [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the defaulting ending. - [`ToOptional`](./to_optional.md) — converting an existing core builder instead of starting fresh. -- [`HasBuilder`](./has_builder.md) — the core entry point this relaxes. -- [`MapType`](./map_type.md) — the `IsOptional` marker the layer runs on. -- [`TransformMapFields`](./transform_map_fields.md) — the walk that re-marks every field. -- [`#[derive(BuildField)]`](../derives/derive_build_field.md) — generates the machinery underneath. +- [`HasBuilder`](../builder/has_builder.md) — the core entry point this relaxes. +- [`MapType`](../type-level/map_type.md) — the `IsOptional` marker the layer runs on. +- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk that re-marks every field. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the machinery underneath. The ideas behind it: diff --git a/docs/reference/traits/optional/index.md b/docs/reference/traits/optional/index.md new file mode 100644 index 00000000..c83c39a9 --- /dev/null +++ b/docs/reference/traits/optional/index.md @@ -0,0 +1,44 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Optional and defaulted fields + +Relaxing the strict record builder, so a field can be set in any order or left unset. + +## Overview + +The core [record builder](../builder/index.md) is deliberately strict: a field is set once, and a +partial record becomes its struct only when every field is present. That strictness catches a missing +field at compile time, and it is too rigid for a record whose fields arrive unpredictably or have +sensible defaults. These traits, from `cgp-field-extra`, relax it while reusing the same machinery +underneath. Nothing here is in the prelude — import each from `cgp::extra::field::impls`. + +The layer divides into entry points, the setter, the two endings, and the transform markers behind +them. + +The **entry points** produce an all-optional builder, whose every field is an `Option`. +[`HasOptionalBuilder`](has_optional_builder.md) starts one from nothing, and [`ToOptional`](to_optional.md) +converts an existing builder into one. + +[`SetOptional`](set_optional.md) is the **setter**, which sets a field as many times as you like, +because an optional field's marker does not change when it is written. + +The **two endings** are chosen at the finalize call rather than when the builder is made. +[`FinalizeOptional`](finalize_optional.md) requires every field and reports the first missing one, while +[`CanFinalizeWithDefault`](can_finalize_with_default.md) fills a missing field from `Default`. +[`CanBuildWithDefault`](can_build_with_default.md) chains a merge and a defaulted finalize into one call. + +The **transform markers** carry the per-field conversions the endings run. +[`TransformMapDefault`](transform_map_default.md) makes every field present, and +[`TransformOptional`](transform_optional.md) makes every field optional. + +## The ideas behind them + +- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence + fits. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/set_optional.md b/docs/reference/traits/optional/set_optional.md similarity index 65% rename from docs/reference/traits/set_optional.md rename to docs/reference/traits/optional/set_optional.md index e1409e96..6d3c5525 100644 --- a/docs/reference/traits/set_optional.md +++ b/docs/reference/traits/optional/set_optional.md @@ -1,5 +1,6 @@ --- sidebar_label: 'SetOptional' +sidebar_position: 3 --- # `SetOptional` @@ -8,9 +9,14 @@ Setting one field of an optional builder, as many times as you like. ## Overview -[`BuildField`](./build_field.md) sets an absent field and consumes the slot: the builder's type changes, +[`BuildField`](../builder/build_field.md) sets an absent field and consumes the slot: the builder's type changes, and setting the same field twice is a compile error. `SetOptional` is the optional layer's answer, and its -defining property is the opposite: +defining property is the opposite: an optional field is settable in any order and as many times as you +like. + +## Definition + +`SetOptional` is keyed by the field's tag and exposes the field's type as an associated `Value`: ```rust pub trait SetOptional { @@ -26,11 +32,14 @@ pub trait SetOptional { } ``` -**Both methods return `Self`.** The field's marker is `IsOptional` before *and* after, so the builder's -type does not change — which is exactly what makes an optional field settable repeatedly. - -The two methods differ only in what they do with whatever was there: `set` discards it, and -`set_optional` hands it back. +`Tag` is the field's type-level name, a [`Symbol!`](../../macros/symbol.md) for a named field or an +[`Index`](../../types/index.md) for a tuple field, passed at the call site as a `PhantomData` +argument. `Value` is the field's declared type, so a caller passes an ordinary value rather than an +`Option`. Both methods take `self` and return `Self`: the field's marker stays `IsOptional` before and +after, so the builder's type does not change and an optional field can be set repeatedly. The two +methods differ only in what they do with whatever was already there. `set` discards it; `set_optional` +returns it as an `Option` alongside the rebuilt builder. The trait has no supertrait. It is +not in the prelude; import it from `cgp-field-extra`. ## Usage @@ -42,11 +51,8 @@ use cgp::extra::field::impls::SetOptional; `Self` must be an optional builder — one from [`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md). Calling it on a -core builder does not resolve, because the field's marker is `IsNothing` rather than `IsOptional`. - -`Value` is the field's declared type, so what you pass is an ordinary value rather than an `Option`. -Setting a field to "absent" is not something this trait does; a field starts absent and stays so unless -set. +core builder does not resolve, because the field's marker is `IsNothing` rather than `IsOptional`. There +is no "unset" operation: a field starts absent and stays so unless it is set. ## Examples @@ -84,16 +90,16 @@ invisible at the call site and lives entirely in the type. **Reach for it when a field may be set more than once, or when the order is not known.** That is the one thing the core builder cannot express. -- **[`BuildField`](./build_field.md)** when each field is set exactly once. The compile-time +- **[`BuildField`](../builder/build_field.md)** when each field is set exactly once. The compile-time completeness check it buys is the reason the core family exists. - **`set`** when whatever was there should simply be replaced. - **`set_optional`** when the previous value matters — merging, accumulating, warning on a duplicate. -- **[`CanBuildFrom`](./can_build_from.md)** when the values come from another record wholesale rather +- **[`CanBuildFrom`](../casting/can_build_from.md)** when the values come from another record wholesale rather than one at a time. ## Under the hood -`SetOptional` is a single [`UpdateField`](./update_field.md) call writing `Some(value)` into an +`SetOptional` is a single [`UpdateField`](../builder/update_field.md) call writing `Some(value)` into an `IsOptional` slot, with both the source and target markers pinned to `IsOptional`: ```rust @@ -102,11 +108,11 @@ thing the core builder cannot express. ``` `Mapper = IsOptional` requires the field to already be in the optional state, and `Output = Partial` -pins the result to the same type on both sides. **That pinning is exactly what allows repeated sets** — +pins the result to the same type on both sides. **That pinning allows repeated sets:** there is no marker to consume, so no impl becomes unavailable after the first call. -Contrast [`BuildField`](./build_field.md#under-the-hood), which pins `Mapper = IsNothing` and a target of -`IsPresent`: its `Output` is a *different* type, which is what makes a second call fail to resolve. +Contrast [`BuildField`](../builder/build_field.md#under-the-hood), which pins `Mapper = IsNothing` and a target of +`IsPresent`: its `Output` is a *different* type, which makes a second call fail to resolve. Since the primitive returns the old storage alongside the new value, `set_optional` simply exposes it and `set` discards it. Under `IsOptional` that old storage is an `Option`, which is why the returned @@ -119,8 +125,8 @@ value is optional even though the argument is not. **It does not apply to a core builder.** The field must already be `IsOptional`, so start with [`optional_builder()`](./has_optional_builder.md) or convert with [`to_optional()`](./to_optional.md). -**The builder's type never changes, so it carries no record of what you have set.** That is deliberate — -it is what allows re-setting — and it is why finalizing has to check at run time. +**The builder's type never changes, so it carries no record of what you have set.** That is deliberate: +it allows re-setting, and it is why finalizing has to check at run time. **`set_optional` returns `(previous, builder)`, in that order.** Reversing the binding is a type error, and a confusing one in generic code. @@ -138,10 +144,10 @@ conflate. - [`ToOptional`](./to_optional.md) — converting an existing builder into one. - [`FinalizeOptional`](./finalize_optional.md) and [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the two endings. -- [`BuildField`](./build_field.md) — the strict, set-once counterpart. -- [`UpdateField`](./update_field.md) — the primitive this is one call of. -- [`MapType`](./map_type.md) — the `IsOptional` marker it pins on both sides. -- [`CanBuildFrom`](./can_build_from.md) — filling many fields from another record. +- [`BuildField`](../builder/build_field.md) — the strict, set-once counterpart. +- [`UpdateField`](../builder/update_field.md) — the primitive this is one call of. +- [`MapType`](../type-level/map_type.md) — the `IsOptional` marker it pins on both sides. +- [`CanBuildFrom`](../casting/can_build_from.md) — filling many fields from another record. The ideas behind it: diff --git a/docs/reference/traits/to_optional.md b/docs/reference/traits/optional/to_optional.md similarity index 75% rename from docs/reference/traits/to_optional.md rename to docs/reference/traits/optional/to_optional.md index c9991962..386db95c 100644 --- a/docs/reference/traits/to_optional.md +++ b/docs/reference/traits/optional/to_optional.md @@ -1,5 +1,6 @@ --- sidebar_label: 'ToOptional' +sidebar_position: 2 --- # `ToOptional` @@ -9,7 +10,20 @@ Re-marking every field of an existing builder as optional. ## Overview [`HasOptionalBuilder`](./has_optional_builder.md) starts an all-optional builder from nothing. -`ToOptional` is the conversion for the case where you already hold a partial value and want to relax it: +`ToOptional` is the conversion for the case where you already hold a partial value and want to relax it. +Every field is re-marked to `IsOptional`, whatever state it was in — a set field becomes `Some(value)`, +an absent one becomes `None` — and from there the value behaves like any other optional builder: +[`SetOptional`](./set_optional.md) applies, and either +[`FinalizeOptional`](./finalize_optional.md) or [`CanFinalizeWithDefault`](./can_finalize_with_default.md) +ends it. + +**It is the conversion `optional_builder()` is built from**, which is the shortest way to describe both: +one starts fresh and converts, the other converts something you already have. + +## Definition + +`ToOptional` carries the re-marked builder type as an associated `Output` and converts a partial value +into it: ```rust pub trait ToOptional { @@ -19,14 +33,12 @@ pub trait ToOptional { } ``` -Every field is re-marked to `IsOptional`, whatever state it was in — a set field becomes `Some(value)`, -an absent one becomes `None` — and from there the value behaves like any other optional builder: -[`SetOptional`](./set_optional.md) applies, and either -[`FinalizeOptional`](./finalize_optional.md) or [`CanFinalizeWithDefault`](./can_finalize_with_default.md) -ends it. - -**It is the conversion `optional_builder()` is built from**, which is the shortest way to describe both: -one starts fresh and converts, the other converts something you already have. +`Self` is any partial builder, and `Output` is the same partial companion type with every marker set to +`IsOptional`. `to_optional` takes `self`, consuming the builder and returning the re-marked one. The +trait has no supertrait; it is a blanket impl over +[`TransformMapFields`](../type-level/transform_map_fields.md), so any partial value whose fields can be +re-marked gains it, with nothing to implement by hand. It is not in the prelude; the optional-field +layer lives in `cgp-field-extra`. ## Usage @@ -36,10 +48,7 @@ one starts fresh and converts, the other converts something you already have. use cgp::extra::field::impls::ToOptional; ``` -`Output` is the same partial companion type with every marker set to `IsOptional`. There is nothing to -implement — the impl is a blanket one over -[`TransformMapFields`](./transform_map_fields.md), so any partial value whose fields can be re-marked -gets it. +You call it on a partial value, as `builder.to_optional()`. ## Examples @@ -67,11 +76,11 @@ let context = builder assert_eq!(context.bar, 42); ``` -The already-set `foo` survives the conversion as `Some("foo")`, which is what distinguishes this from +The already-set `foo` survives the conversion as `Some("foo")`, which distinguishes this from starting over with [`optional_builder()`](./has_optional_builder.md). Converting a *complete* value works too, by way of -[`into_builder`](./into_builder.md): +[`into_builder`](../builder/into_builder.md): ```rust let builder = context.into_builder().to_optional(); // every field Some @@ -85,14 +94,14 @@ let builder = context.into_builder().to_optional(); // every field Some `optional_builder()` is `builder().to_optional()` and reads better. - **`ToOptional`** when a core builder is partly filled — because a routine handed it to you, or because the first few fields were known and the rest are not. -- **[`IntoBuilder`](./into_builder.md) then `to_optional`** to relax a complete value, typically before +- **[`IntoBuilder`](../builder/into_builder.md) then `to_optional`** to relax a complete value, typically before overwriting some of its fields. -- **Stay on the [core builder](./has_builder.md)** if the remaining fields are known and set once. The +- **Stay on the [core builder](../builder/has_builder.md)** if the remaining fields are known and set once. The conversion costs the compile-time completeness check. ## Under the hood -`ToOptional` is a [`TransformMapFields`](./transform_map_fields.md) walk carrying the +`ToOptional` is a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying the [`TransformOptional`](./transform_optional.md) marker, targeting `IsOptional`: ```rust @@ -100,8 +109,8 @@ let builder = context.into_builder().to_optional(); // every field Some // self.transform_map_fields::() ``` -That walk visits each field of the target's [`HasFields`](./has_fields.md) shape, uses -[`UpdateField`](./update_field.md) to take the field out and learn its current marker, applies the +That walk visits each field of the target's [`HasFields`](../shape/has_fields.md) shape, uses +[`UpdateField`](../builder/update_field.md) to take the field out and learn its current marker, applies the transform, and writes it back under `IsOptional`. The transform's own impls are what decide the value: `IsPresent` becomes `Some(value)`, `IsNothing` becomes `None`, and `IsOptional` passes through. @@ -136,10 +145,10 @@ the outer layer is the builder's presence tracking — and reads confusingly in - [`FinalizeOptional`](./finalize_optional.md) and [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the two endings. - [`TransformOptional`](./transform_optional.md) — the marker this walk carries. -- [`TransformMapFields`](./transform_map_fields.md) — the walk itself. -- [`IntoBuilder`](./into_builder.md) — how a complete value becomes a builder to convert. -- [`HasBuilder`](./has_builder.md) — the core family this relaxes. -- [`MapType`](./map_type.md) — the `IsOptional` marker. +- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk itself. +- [`IntoBuilder`](../builder/into_builder.md) — how a complete value becomes a builder to convert. +- [`HasBuilder`](../builder/has_builder.md) — the core family this relaxes. +- [`MapType`](../type-level/map_type.md) — the `IsOptional` marker. The ideas behind it: diff --git a/docs/reference/traits/transform_map_default.md b/docs/reference/traits/optional/transform_map_default.md similarity index 77% rename from docs/reference/traits/transform_map_default.md rename to docs/reference/traits/optional/transform_map_default.md index 7af46864..cb914ee6 100644 --- a/docs/reference/traits/transform_map_default.md +++ b/docs/reference/traits/optional/transform_map_default.md @@ -1,5 +1,6 @@ --- sidebar_label: 'TransformMapDefault' +sidebar_position: 7 --- # `TransformMapDefault` @@ -21,12 +22,24 @@ transform of your own. ## Overview [`CanFinalizeWithDefault`](./can_finalize_with_default.md) works by re-marking every field of a partial -record to `IsPresent` and then calling the ordinary [`finalize_build`](./finalize_build.md). +record to `IsPresent` and then calling the ordinary [`finalize_build`](../builder/finalize_build.md). `TransformMapDefault` is the marker that carries the per-field conversions making that possible. -It is a zero-sized type implementing [`TransformMap`](./transform_map.md) three times, once per state a -field might currently be in — and reading those three impls is the shortest description of what the -defaulting layer does: +**You name it only when extending the layer.** Using the defaulting workflow means calling +[`finalize_with_default`](./can_finalize_with_default.md) or +[`build_with_default`](./can_build_with_default.md), with no marker in sight. + +## Definition + +`TransformMapDefault` is a zero-sized marker type: + +```rust +pub struct TransformMapDefault; +``` + +It carries no data. It becomes a transform by implementing +[`TransformMap`](../type-level/transform_map.md) once for each state a field might currently be in, every +impl targeting `IsPresent`: | a field currently | becomes | |---|---| @@ -34,12 +47,10 @@ defaulting layer does: | `IsNothing` | `Default::default()` | | `IsOptional` | its contents, or the default if `None` | -All three target `IsPresent`, which is exactly the configuration -[`FinalizeBuild`](./finalize_build.md) accepts. - -**You name it only when extending the layer.** Using the defaulting workflow means calling -[`finalize_with_default`](./can_finalize_with_default.md) or -[`build_with_default`](./can_build_with_default.md), with no marker in sight. +Because all three impls target `IsPresent`, applying the marker across a record leaves every field +present, the configuration [`FinalizeBuild`](../builder/finalize_build.md) accepts. The impl bodies are +in [*Under the hood*](#under-the-hood). The marker is not in the prelude; import it from +`cgp-field-extra`. ## Usage @@ -50,7 +61,7 @@ use cgp::extra::field::impls::TransformMapDefault; ``` There is nothing to call. The marker exists to be named in a -[`TransformMapFields`](./transform_map_fields.md) bound, which is where a capability says *which* +[`TransformMapFields`](../type-level/transform_map_fields.md) bound, which is where a capability says *which* conversion it drives: ```rust @@ -88,7 +99,7 @@ The marker is the first type argument, and swapping it for [`ToOptional`](./to_optional.md) is written. **Same recursion, different marker.** Writing a marker of your own follows the same three-impl shape; the -[`TransformMap`](./transform_map.md#examples) page shows one. +[`TransformMap`](../type-level/transform_map.md#examples) page shows one. ## When to use it @@ -99,14 +110,14 @@ served by the two capabilities already built on it. gaps. - **[`CanBuildWithDefault`](./can_build_with_default.md)** to merge from a source and default the rest, in one call. -- **Write your own [`TransformMap`](./transform_map.md) marker** for a conversion these do not cover — one +- **Write your own [`TransformMap`](../type-level/transform_map.md) marker** for a conversion these do not cover — one that validates, logs, or fills from something other than `Default`. - **[`TransformOptional`](./transform_optional.md)** is its counterpart, targeting `IsOptional` instead. ## Under the hood The marker is zero-sized and carries no data. What it carries is three -[`TransformMap`](./transform_map.md) impls, distinguished by their source marker: +[`TransformMap`](../type-level/transform_map.md) impls, distinguished by their source marker: ```rust impl TransformMap for TransformMapDefault { @@ -129,12 +140,12 @@ impl TransformMap for TransformMapDefault ``` Note that each argument type is the *source* marker's projection — `T`, then `()`, then `Option` — -which is what keeps the three from overlapping. And note that only two carry the `T: Default` bound: a +which keeps the three from overlapping. And note that only two carry the `T: Default` bound: a field already present needs no default, which is why a fully-set builder can be finalized this way regardless of its field types. Three impls are needed rather than one because -[`TransformMapFields`](./transform_map_fields.md#under-the-hood) resolves a conversion per field from +[`TransformMapFields`](../type-level/transform_map_fields.md#under-the-hood) resolves a conversion per field from whatever state that field is in, and a record may hold fields in all three states at once. ## Common Mistakes @@ -158,10 +169,10 @@ trade against [`FinalizeOptional`](./finalize_optional.md). - [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the capability built directly on it. - [`CanBuildWithDefault`](./can_build_with_default.md) — merge plus that finalize. - [`TransformOptional`](./transform_optional.md) — the counterpart marker, targeting `IsOptional`. -- [`TransformMap`](./transform_map.md) — the trait it implements three times. -- [`TransformMapFields`](./transform_map_fields.md) — the walk that applies it. -- [`MapType`](./map_type.md) — the markers it converts between. -- [`FinalizeBuild`](./finalize_build.md) — what an all-`IsPresent` result is accepted by. +- [`TransformMap`](../type-level/transform_map.md) — the trait it implements three times. +- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk that applies it. +- [`MapType`](../type-level/map_type.md) — the markers it converts between. +- [`FinalizeBuild`](../builder/finalize_build.md) — what an all-`IsPresent` result is accepted by. The ideas behind it: diff --git a/docs/reference/traits/transform_optional.md b/docs/reference/traits/optional/transform_optional.md similarity index 74% rename from docs/reference/traits/transform_optional.md rename to docs/reference/traits/optional/transform_optional.md index 659187f9..3a4cb53e 100644 --- a/docs/reference/traits/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -1,5 +1,6 @@ --- sidebar_label: 'TransformOptional' +sidebar_position: 8 --- # `TransformOptional` @@ -23,17 +24,6 @@ less of a field's type than its defaulting counterpart does. The one case for na be set freely and finalized either way. `TransformOptional` is the marker carrying the per-field conversions that make that possible. -It is a zero-sized type implementing [`TransformMap`](./transform_map.md), and reading its impls is the -shortest description of what the optional conversion does: - -| a field currently | becomes | -|---|---| -| `IsPresent` | `Some(value)` | -| `IsNothing` | `None` | - -Both target `IsOptional`, which is the configuration [`SetOptional`](./set_optional.md) requires and the -one an optional builder lives at. - **It is the exact mirror of [`TransformMapDefault`](./transform_map_default.md)**, which targets `IsPresent` instead — same walk, different destination. That symmetry is why the defaulted and optional workflows behave so alike. @@ -42,6 +32,29 @@ workflows behave so alike. [`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md), with no marker in sight. +## Definition + +`TransformOptional` is a zero-sized marker type: + +```rust +pub struct TransformOptional; +``` + +It carries no data. It becomes a transform by implementing +[`TransformMap`](../type-level/transform_map.md) once for each state a field might currently be in, both +impls targeting `IsOptional`: + +| a field currently | becomes | +|---|---| +| `IsPresent` | `Some(value)` | +| `IsNothing` | `None` | + +Because both impls target `IsOptional`, applying the marker across a record leaves every field optional, +the configuration [`SetOptional`](./set_optional.md) requires. Unlike its defaulting counterpart it needs +nothing of the field types, since wrapping a value in `Some` and producing `None` require no `Default`. +The impl bodies are in [*Under the hood*](#under-the-hood). The marker is not in the prelude; import it +from `cgp-field-extra`. + ## Usage **It is not in the prelude.** Import it from `cgp::extra::field::impls`: @@ -51,7 +64,7 @@ use cgp::extra::field::impls::TransformOptional; ``` There is nothing to call. The marker is named in a -[`TransformMapFields`](./transform_map_fields.md) bound, which is where a capability says which +[`TransformMapFields`](../type-level/transform_map_fields.md) bound, which is where a capability says which conversion it drives: ```rust @@ -82,12 +95,12 @@ use cgp::prelude::*; ``` Swap the marker for [`TransformMapDefault`](./transform_map_default.md) and the target for `IsPresent`, -add a [`finalize_build`](./finalize_build.md), and you have +add a [`finalize_build`](../builder/finalize_build.md), and you have [`CanFinalizeWithDefault`](./can_finalize_with_default.md). The two capabilities differ by exactly that much. Writing a marker of your own follows the same shape; the -[`TransformMap`](./transform_map.md#examples) page shows one with three impls. +[`TransformMap`](../type-level/transform_map.md#examples) page shows one with three impls. ## When to use it @@ -98,11 +111,11 @@ Writing a marker of your own follows the same shape; the `builder().to_optional()`. - **[`TransformMapDefault`](./transform_map_default.md)** when the destination is `IsPresent` rather than `IsOptional`. -- **Write your own [`TransformMap`](./transform_map.md) marker** for a conversion neither covers. +- **Write your own [`TransformMap`](../type-level/transform_map.md) marker** for a conversion neither covers. ## Under the hood -The marker is zero-sized and carries [`TransformMap`](./transform_map.md) impls distinguished by their +The marker is zero-sized and carries [`TransformMap`](../type-level/transform_map.md) impls distinguished by their source marker, each targeting `IsOptional`: ```rust @@ -118,14 +131,14 @@ Note what is absent: **no `Default` bound anywhere.** Its counterpart an absent field means producing a value from nothing. Producing `None` does not, so this conversion applies to every field type. -[`TransformMapFields`](./transform_map_fields.md#under-the-hood) is what applies it, visiting each field -of the target's [`HasFields`](./has_fields.md) shape and using -[`UpdateField`](./update_field.md) twice per field — once to take the value out and learn its marker, +[`TransformMapFields`](../type-level/transform_map_fields.md#under-the-hood) applies it, visiting each field +of the target's [`HasFields`](../shape/has_fields.md) shape and using +[`UpdateField`](../builder/update_field.md) twice per field — once to take the value out and learn its marker, once to write it back under `IsOptional`. The result is a partial value at a configuration the core builder never reaches on its own, which is what makes [`SetOptional`](./set_optional.md) resolve and the strict -[`FinalizeBuild`](./finalize_build.md) not. +[`FinalizeBuild`](../builder/finalize_build.md) not. ## Common Mistakes @@ -150,10 +163,10 @@ builder's presence tracking, and the two are easy to conflate in an error. - [`ToOptional`](./to_optional.md) — the conversion built directly on it. - [`HasOptionalBuilder`](./has_optional_builder.md) — the entry point built on that. - [`TransformMapDefault`](./transform_map_default.md) — the counterpart marker, targeting `IsPresent`. -- [`TransformMap`](./transform_map.md) — the trait it implements. -- [`TransformMapFields`](./transform_map_fields.md) — the walk that applies it. +- [`TransformMap`](../type-level/transform_map.md) — the trait it implements. +- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk that applies it. - [`SetOptional`](./set_optional.md) — what the resulting configuration makes available. -- [`MapType`](./map_type.md) — the `IsOptional` marker it targets. +- [`MapType`](../type-level/map_type.md) — the `IsOptional` marker it targets. The ideas behind it: diff --git a/docs/reference/traits/shape/_category_.json b/docs/reference/traits/shape/_category_.json new file mode 100644 index 00000000..1a04209f --- /dev/null +++ b/docs/reference/traits/shape/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Field structure", + "position": 3, + "link": { + "type": "doc", + "id": "reference/traits/shape/index" + } +} diff --git a/docs/reference/traits/from_fields.md b/docs/reference/traits/shape/from_fields.md similarity index 66% rename from docs/reference/traits/from_fields.md rename to docs/reference/traits/shape/from_fields.md index 9d6c8ab5..150a05d2 100644 --- a/docs/reference/traits/from_fields.md +++ b/docs/reference/traits/shape/from_fields.md @@ -1,5 +1,6 @@ --- sidebar_label: 'FromFields' +sidebar_position: 4 --- # `FromFields` @@ -9,7 +10,14 @@ Rebuilding a concrete value from its shape. ## Overview [`ToFields`](./to_fields.md) takes a value apart into an anonymous list of named entries. `FromFields` is -the return journey: +the return journey. It closes the loop for generic code: decompose a value, work on the entries without +naming the type, and put a concrete value back together at the end. Both directions go through the +identical `Fields` type, so **the shapes line up by construction rather than by check** — there is +nothing to validate and nothing that can fail. + +## Definition + +`FromFields` adds one associated function to the shape trait it extends: ```rust pub trait FromFields: HasFields { @@ -17,25 +25,23 @@ pub trait FromFields: HasFields { } ``` -It is what closes the loop for generic code: decompose a value, work on the entries without naming the -type, and put a concrete value back together at the end. Both directions go through the identical -`Fields` type, so **the shapes line up by construction rather than by check** — there is nothing to -validate and nothing that can fail. - -It is an associated function rather than a method, since there is no value to call it on. The call reads -`Person::from_fields(fields)`, or `T::from_fields(fields)` in generic code. +It supertraits [`HasFields`](./has_fields.md), so `from_fields` takes that trait's `Fields` shape and a +bound on `FromFields` gives you `Fields` as well. It is an associated function rather than a method, +because there is no value to call it on, so the call reads `Person::from_fields(fields)`, or +`T::from_fields(fields)` in generic code. ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. The impls come from +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all five shape traits together. -It supertraits [`HasFields`](./has_fields.md), so bounding on `FromFields` gives you `Fields` as well. -The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md), which emits all five shape -traits together. +The argument must be **exactly** `Self::Fields` — the same entries, the same tags, in the same order. A +shape that merely has the same field names in a different order is a different type and will not be +accepted, which makes the conversion total. The argument must be **exactly** `Self::Fields` — the same entries, the same tags, in the same order. A shape that merely has the same field names in a different order is a different type and will not be -accepted, which is what makes the conversion total. +accepted, which makes the conversion total. ## Examples @@ -69,7 +75,7 @@ where } ``` -An enum rebuilds the same way, from a [`Sum!`](../macros/sum.md) rather than a product — the arm that is +An enum rebuilds the same way, from a [`Sum!`](../../macros/sum.md) rather than a product — the arm that is present becomes the variant that is constructed. ## When to use it @@ -80,11 +86,11 @@ direction happens. - **[`ToFields`](./to_fields.md)** for the decomposition half. - **[`HasFields`](./has_fields.md) alone** when the code names the shape and never builds a value. -- **The [builder family](./has_builder.md)** when the value is assembled *incrementally*, from pieces +- **The [builder family](../builder/has_builder.md)** when the value is assembled *incrementally*, from pieces arriving at different times. `from_fields` needs the whole shape at once, already complete; - [`HasBuilder`](./has_builder.md) tracks presence field by field and is what the extensible builder - pattern uses. -- **[`FromVariant`](./from_variant.md)** when an enum is built from *one* named variant rather than from + [`HasBuilder`](../builder/has_builder.md) tracks presence field by field, and the extensible builder + pattern uses it. +- **[`FromVariant`](../variant/from_variant.md)** when an enum is built from *one* named variant rather than from a whole shape. That is the far more common way to construct an enum generically. - **A plain constructor** when the type is concrete. Nothing about `from_fields` improves on a struct literal where one can be written. @@ -123,7 +129,7 @@ whole chain rather than against the field that moved. **It supertraits [`HasFields`](./has_fields.md)**, so naming both in a bound is redundant. **It cannot build a value incrementally.** The whole shape is required at once. Assembling from -independent pieces is [`HasBuilder`](./has_builder.md)'s job, and reaching for `from_fields` there means +independent pieces is [`HasBuilder`](../builder/has_builder.md)'s job, and reaching for `from_fields` there means constructing the complete product by hand first. **There is no borrowing counterpart.** [`ToFieldsRef`](./to_fields_ref.md) has no `FromFieldsRef`, because @@ -135,10 +141,10 @@ a borrowed shape cannot yield an owned value. - [`HasFields`](./has_fields.md) — the supertrait that names the shape. - [`ToFieldsRef`](./to_fields_ref.md) and [`HasFieldsRef`](./has_fields_ref.md) — the borrowed half of the family, which has no rebuild. -- [`FromVariant`](./from_variant.md) — constructing an enum from one named variant. -- [`HasBuilder`](./has_builder.md) — incremental assembly, as against this wholesale conversion. -- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl. -- [`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), and [`Field`](../types/field.md) — what +- [`FromVariant`](../variant/from_variant.md) — constructing an enum from one named variant. +- [`HasBuilder`](../builder/has_builder.md) — incremental assembly, as against this wholesale conversion. +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. +- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md) — what a shape is made of. The ideas behind it: diff --git a/docs/reference/traits/has_fields.md b/docs/reference/traits/shape/has_fields.md similarity index 66% rename from docs/reference/traits/has_fields.md rename to docs/reference/traits/shape/has_fields.md index 9c76e846..f7056de4 100644 --- a/docs/reference/traits/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasFields' +sidebar_position: 1 --- # `HasFields` @@ -14,8 +15,15 @@ routes an enum to a handler per variant. None of those can be written one field name the concrete type either. `HasFields` gives a type that shape as a single associated type. Where -[`HasField`](./has_field.md) — singular — answers *"give me this field"*, `HasFields` answers -*"describe all of them at once"*: +[`HasField`](../field-access/has_field.md) — singular — answers *"give me this field"*, `HasFields` answers +*"describe all of them at once"*. + +**The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md).** What you write is the +derive; what you bound against is the trait. + +## Definition + +`HasFields` carries one associated type and no method: ```rust pub trait HasFields { @@ -23,7 +31,14 @@ pub trait HasFields { } ``` -For `struct Person { name: String, age: u8 }` that is: +`Self` is the type being described, a struct or an enum, and `Fields` is its shape written as a single +type. For a struct that shape is a [`Product!`](../../macros/product.md) list with one +[`Field`](../../types/field.md) entry per field, each pairing a value type with its type-level name. For +an enum it is a [`Sum!`](../../macros/sum.md) instead, the same idea for a choice rather than a +combination. There is no method, because describing a type is not an operation, so the associated type is +the whole trait. + +For `struct Person { name: String, age: u8 }` the shape is: ```rust type Fields = Product![ @@ -32,23 +47,15 @@ type Fields = Product![ ]; ``` -The struct written as a type: a [`Product!`](../macros/product.md) list with one -[`Field`](../types/field.md) entry per field, each pairing a value type with its type-level name. For an -enum it is a [`Sum!`](../macros/sum.md) instead — the same idea for a choice rather than a combination. - -**The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md).** What you write is the -derive; what you bound against is the trait. - ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method, because describing a -type is not an operation — `Fields` is the whole trait. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. The shape's construction follows one rule everywhere: a named field or variant is keyed by -[`Symbol!`](../macros/symbol.md), a positional field by [`Index`](../types/index.md), a struct becomes +[`Symbol!`](../../macros/symbol.md), a positional field by [`Index`](../../types/index.md), a struct becomes a `Cons`/`Nil` product, and an enum becomes an `Either`/`Void` sum. A single-field tuple struct is the one -special case — its `Fields` is the inner type directly rather than a one-element product — and the -[derive's page](../derives/derive_has_fields.md) covers that and the other shapes in full. +special case, with its `Fields` the inner type directly rather than a one-element product. The +[derive's page](../../derives/derive_has_fields.md) covers that and the other shapes in full. **Four companions turn the description into a two-way door**, each on its own page: [`HasFieldsRef`](./has_fields_ref.md) names the borrowed shape, and [`ToFields`](./to_fields.md), @@ -75,7 +82,7 @@ have to move through it. ## Examples -Deriving it alongside [`HasField`](./has_field.md) is the common pairing, giving one struct both indexed +Deriving it alongside [`HasField`](../field-access/has_field.md) is the common pairing, giving one struct both indexed and structural access: ```rust @@ -110,11 +117,11 @@ it. The derives that take an enum apart need exactly one unnamed payload per var ## When to use it **Bound on `HasFields` when code must process a type's whole shape; bound on -[`HasField`](./has_field.md) when it needs one named field.** That is the entire distinction, and the two +[`HasField`](../field-access/has_field.md) when it needs one named field.** That is the entire distinction, and the two are complementary rather than ranked — most types that need both derive both in one `#[derive(...)]`. - **`HasFields` alone** when the code only names the shape — a `where` clause, an associated-type - projection, a type-level computation like [`AppendProduct`](./append_product.md). + projection, a type-level computation like [`AppendProduct`](../type-level/append_product.md). - **[`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md)** when values move through the shape in both directions. - **[`ToFieldsRef`](./to_fields_ref.md)** when the value must not be consumed. Requiring `ToFields` where @@ -125,14 +132,14 @@ with a derive, there is nothing to query at run time, and the shape is a type ra buys is static checking and no runtime cost; what it costs is that a foreign type you cannot patch has no shape at all. And it is **not the whole extensible-data story** — the shape describes a type, while building one up field by field or taking one apart variant by variant is the -[builder](./has_builder.md) and [extractor](./extract_field.md) families, bundled with this one by -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). +[builder](../builder/has_builder.md) and [extractor](../variant/extract_field.md) families, bundled with this one by +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md). ## Under the hood The trait module defines only the bare trait; every impl comes from -[`#[derive(HasFields)]`](../derives/derive_has_fields.md). The load-bearing part is what the derive puts -in `Fields`, and the sugar hides one level of structure: +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md). The part that matters is the type the derive +puts in `Fields`, and the sugar hides one level of structure: ```rust impl HasFields for Person { @@ -144,7 +151,7 @@ impl HasFields for Person { ``` `Product![A, B]` is `Cons>`, so a `Fields` type in an error message is a `Cons` chain -rather than the sugar — the [type-level spines](../types/type_level_spines.md) page covers reading it. +rather than the sugar — the [type-level spines](../../types/type_level_spines.md) page covers reading it. An enum's shape is the dual: an `Either` chain terminated by `Void` rather than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name and carrying that variant's own fields as a nested @@ -155,20 +162,20 @@ to give the trait solver something to recurse over. ## Common Mistakes -**`HasFields` and [`HasField`](./has_field.md) differ by one letter and do not overlap.** The plural is +**`HasFields` and [`HasField`](../field-access/has_field.md) differ by one letter and do not overlap.** The plural is the whole shape and takes structs and enums; the singular is per-field access and takes only structs. Their derives are likewise distinct. **A newtype's shape is the inner type, not a one-element product.** `struct Wrapper(String)` has `Fields = String`. Generic code written against a `Cons` chain will not match it — the -[derive's page](../derives/derive_has_fields.md) has the rule and the other shapes. +[derive's page](../../derives/derive_has_fields.md) has the rule and the other shapes. **Field order is declaration order and is part of the type.** Two structs with the same names in different orders have different `Fields` types. Name-driven conversions cope; code written against a literal `Cons` chain does not. **Two enum variant names are reserved.** A variant called `Fields` or `FieldsRef` collides with these -associated types and the derive fails; the [derive's page](../derives/derive_has_fields.md) lists it with +associated types and the derive fails; the [derive's page](../../derives/derive_has_fields.md) lists it with the other reserved names. **There is no method.** `Fields` is a type. Getting a *value* in that shape is @@ -176,20 +183,20 @@ the other reserved names. ## Related constructs -- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl and the four +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl and the four companions'; what you write. - [`HasFieldsRef`](./has_fields_ref.md) — the borrowed shape. - [`ToFields`](./to_fields.md), [`FromFields`](./from_fields.md), and [`ToFieldsRef`](./to_fields_ref.md) — the conversions between a value and its shape. -- [`HasField`](./has_field.md) — the singular counterpart, per-field access. -- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this with the builder and extractor. -- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a shape is built +- [`HasField`](../field-access/has_field.md) — the singular counterpart, per-field access. +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — bundles this with the builder and extractor. +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the list types a shape is built from. -- [`Field`](../types/field.md) — one entry: a value paired with its type-level name. -- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains +- [`Field`](../../types/field.md) — one entry: a value paired with its type-level name. +- [Type-level spines](../../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. -- [`AppendProduct`](./append_product.md) — the operations that compute new shapes from old ones. -- [`CanUpcast`](./can_upcast.md) and [`CanBuildFrom`](./can_build_from.md) — conversions between two +- [`AppendProduct`](../type-level/append_product.md) — the operations that compute new shapes from old ones. +- [`CanUpcast`](../casting/can_upcast.md) and [`CanBuildFrom`](../casting/can_build_from.md) — conversions between two types whose shapes overlap, driven by this one. The ideas behind it: diff --git a/docs/reference/traits/has_fields_ref.md b/docs/reference/traits/shape/has_fields_ref.md similarity index 74% rename from docs/reference/traits/has_fields_ref.md rename to docs/reference/traits/shape/has_fields_ref.md index 74d96acd..18bbb65d 100644 --- a/docs/reference/traits/has_fields_ref.md +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasFieldsRef' +sidebar_position: 2 --- # `HasFieldsRef` @@ -11,7 +12,7 @@ A type's whole shape, with every value borrowed. ### Generated machinery **You are not expected to implement `HasFieldsRef`.** -[`#[derive(HasFields)]`](../derives/derive_has_fields.md) emits it alongside the owned shape. What +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md) emits it alongside the owned shape. What generic code writes is a bound; this page explains the type the derive produces, including the reserved lifetime name that shows up in an error message. @@ -22,7 +23,11 @@ lifetime name that shows up in an error message. [`HasFields`](./has_fields.md) describes a type as a list of named entries holding owned values. Code that only *reads* a value should not have to consume it to walk its shape — a validator, a serializer, a routine that inspects a struct and hands it back — so there is a second description in which every entry -holds a borrow instead: +holds a borrow instead. + +## Definition + +`HasFieldsRef` carries one generic associated type and no method: ```rust pub trait HasFieldsRef { @@ -32,22 +37,20 @@ pub trait HasFieldsRef { } ``` -`FieldsRef<'a>` is the same shape as `Fields` with each value borrowed for `'a`. It is a **generic -associated type**, which is what lets one trait describe the shape at whatever lifetime a caller has. +`Self` is the type being described. `FieldsRef<'a>` is the same shape as [`HasFields`](./has_fields.md)'s +`Fields`, with each value borrowed for `'a`. It is a **generic associated type**, which lets one trait +describe the shape at whatever lifetime a caller has, and the `where Self: 'a` clause keeps the borrowed +shape from outliving the value it describes. There is no method, because the trait only names a type; the +conversion that produces a value in this shape is [`ToFieldsRef`](./to_fields_ref.md). The two shape traits are independent rather than one extending the other, and that is deliberate: a type -may be described owned, borrowed, or both. What connects the borrowed description to a value is -[`ToFieldsRef`](./to_fields_ref.md). +may be described owned, borrowed, or both. ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. There is no method — like its owned -counterpart, this trait only names a type. - -The `where Self: 'a` clause on the associated type is required and worth recognizing: it says the borrow -cannot outlive the value it describes, which every use site inherits. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. -The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md), which emits this alongside +The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits this alongside [`HasFields`](./has_fields.md) rather than as a separate opt-in. ## Examples @@ -91,7 +94,7 @@ clone it. destructuring. - **Use `HasFieldsRef` + [`ToFieldsRef`](./to_fields_ref.md)** when the original must survive. This is the weaker requirement, so prefer it when it suffices. -- **Use [`HasField`](./has_field.md)** when only one named field is needed. The whole-shape traits are +- **Use [`HasField`](../field-access/has_field.md)** when only one named field is needed. The whole-shape traits are for code that walks everything. Being precise about which of the five shape traits a routine requires pays, because each one narrows what @@ -129,7 +132,7 @@ thing about this trait that surprises people in an error message. **The `where Self: 'a` clause propagates.** Any bound naming `FieldsRef<'a>` inherits it, so a signature that borrows the shape usually needs the lifetime spelled out rather than elided. -**It is emitted by [`#[derive(HasFields)]`](../derives/derive_has_fields.md), not by a derive of its +**It is emitted by [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), not by a derive of its own.** There is no `#[derive(HasFieldsRef)]`. **Naming the shape is not obtaining it.** [`ToFieldsRef`](./to_fields_ref.md) is the method half; this @@ -137,18 +140,18 @@ trait has none. **Two enum variant names are reserved**, `Fields` and `FieldsRef`, because these associated types are named through `Self::…` in the generated impls. The -[derive's page](../derives/derive_has_fields.md) lists them with the others. +[derive's page](../../derives/derive_has_fields.md) lists them with the others. ## Related constructs - [`HasFields`](./has_fields.md) — the owned shape, and where the family is explained in full. - [`ToFieldsRef`](./to_fields_ref.md) — the conversion that produces a value in this shape. - [`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md) — the owned conversions. -- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl. -- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a shape is built +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the list types a shape is built from. -- [`Field`](../types/field.md) — one entry of a shape. -- [`MapTypeRef`](./map_type_ref.md) — the borrow markers the extractor family uses for the same job. +- [`Field`](../../types/field.md) — one entry of a shape. +- [`MapTypeRef`](../type-level/map_type_ref.md) — the borrow markers the extractor family uses for the same job. The ideas behind it: diff --git a/docs/reference/traits/shape/index.md b/docs/reference/traits/shape/index.md new file mode 100644 index 00000000..e38d4e0b --- /dev/null +++ b/docs/reference/traits/shape/index.md @@ -0,0 +1,35 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Field structure + +A type's whole shape as a single type, and the conversions that move a value through it. + +## Overview + +Where [field access](../field-access/index.md) reads one named field, these traits describe a type's +*whole shape* at once — every field, its name, and its type — as a single associated type. That is what +lets generic code walk a struct or an enum it cannot name: a serializer, a validator, a merge, a +dispatcher. The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md). + +Two traits name the shape, and three convert a value in and out of it. + +The **shape traits** describe the type. [`HasFields`](has_fields.md) names the owned shape — a +[`Product!`](../../macros/product.md) for a struct, a [`Sum!`](../../macros/sum.md) for an enum — and +[`HasFieldsRef`](has_fields_ref.md) names the borrowed shape, with every value a reference. + +The **conversions** move a concrete value through the shape. [`ToFields`](to_fields.md) takes a value +apart into its shape and [`FromFields`](from_fields.md) rebuilds it, and the two round-trip through the +identical type so nothing can fail. [`ToFieldsRef`](to_fields_ref.md) is the borrowing form, for code +that reads a shape without consuming the value. + +## The ideas behind them + +- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum half. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/to_fields.md b/docs/reference/traits/shape/to_fields.md similarity index 69% rename from docs/reference/traits/to_fields.md rename to docs/reference/traits/shape/to_fields.md index 7630d010..38c9e953 100644 --- a/docs/reference/traits/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -1,5 +1,6 @@ --- sidebar_label: 'ToFields' +sidebar_position: 3 --- # `ToFields` @@ -8,18 +9,12 @@ Taking a value apart into its shape. ## Overview -[`HasFields`](./has_fields.md) *names* a type's shape. `ToFields` produces a value in it: +[`HasFields`](./has_fields.md) *names* a type's shape. `ToFields` produces a value in it. -```rust -pub trait ToFields: HasFields { - fn to_fields(self) -> Self::Fields; -} -``` - -That is what lets generic code stop working on a concrete struct and start working on an anonymous list -of named entries — the form a serializer walks, a converter rewrites, or a merge consumes. The -concrete type goes in; a [`Product!`](../macros/product.md) of [`Field`](../types/field.md) entries comes -out, or a [`Sum!`](../macros/sum.md) for an enum. +That lets generic code stop working on a concrete struct and start working on an anonymous list +of named entries: the form a serializer walks, a converter rewrites, or a merge consumes. The +concrete type goes in; a [`Product!`](../../macros/product.md) of [`Field`](../../types/field.md) entries comes +out, or a [`Sum!`](../../macros/sum.md) for an enum. **It consumes the value.** That is the difference from [`ToFieldsRef`](./to_fields_ref.md), and it is the commonest surprise in the family, because the two read alike at a call site. @@ -28,14 +23,26 @@ The reverse direction is [`FromFields`](./from_fields.md), and the two round-tri `Fields` type, so generic code can decompose, transform, and rebuild with the shapes lining up by construction rather than by check. -## Usage +## Definition + +`ToFields` adds one method to the shape trait it extends: -**It is in the prelude**, so `use cgp::prelude::*;` is enough. +```rust +pub trait ToFields: HasFields { + fn to_fields(self) -> Self::Fields; +} +``` + +It supertraits [`HasFields`](./has_fields.md), so `to_fields` returns that trait's `Fields` shape and a +bound on `ToFields` gives you `Fields` as well. The method takes `self` by value, so it consumes the +value to produce the owned shape. + +## Usage -It supertraits [`HasFields`](./has_fields.md), so bounding on `ToFields` gives you `Fields` as well and -there is no need to name both — though writing `T: HasFields + ToFields` is common and harmless. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. Writing `T: HasFields + ToFields` is common +and harmless, though `T: ToFields` alone already gives you `Fields` through the supertrait. -The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md), which emits all five shape +The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all five shape traits together. ## Examples @@ -62,7 +69,7 @@ assert_eq!(config, config_again); The `clone()` is there only because the assertion compares against the original — `to_fields` would otherwise have consumed it, which is exactly the point. -In generic code the bound is what matters: +In generic code, the bound is the point: ```rust fn shape_of(value: T) -> T::Fields @@ -84,15 +91,15 @@ borrowing form otherwise. - **[`FromFields`](./from_fields.md)** for the other direction, and both together for a round trip. - **[`HasFields`](./has_fields.md) alone** when the code only *names* the shape and never holds a value in it. -- **[`HasField`](./has_field.md)** when one named field is all that is wanted. Decomposing a whole struct +- **[`HasField`](../field-access/has_field.md)** when one named field is all that is wanted. Decomposing a whole struct to read one entry is the wrong tool. -- **The [builder family](./has_builder.md)** when a value is assembled incrementally rather than +- **The [builder family](../builder/has_builder.md)** when a value is assembled incrementally rather than converted wholesale. `to_fields` is a single flat conversion; a builder tracks presence field by field. ## Under the hood `Product![A, B]` is `Cons>`, so the conversion builds a `Cons` chain, one node per field, -wrapping each value into its [`Field`](../types/field.md) entry: +wrapping each value into its [`Field`](../../types/field.md) entry: ```rust impl ToFields for Person { @@ -102,8 +109,8 @@ impl ToFields for Person { } ``` -That chain is what an error message prints when structural code fails to resolve, and the -[type-level spines](../types/type_level_spines.md) page covers reading it. +An error message prints that chain when structural code fails to resolve, and the +[type-level spines](../../types/type_level_spines.md) page covers reading it. An enum's conversion is the dual: each concrete variant is matched onto its arm of an `Either` chain terminated by `Void`, tagged with the variant name. @@ -128,7 +135,7 @@ it. wrong. **There is no fallible form.** The conversion cannot fail; anything that could is a different operation, -such as a [cast](./can_downcast.md). +such as a [cast](../casting/can_downcast.md). ## Related constructs @@ -136,11 +143,11 @@ such as a [cast](./can_downcast.md). - [`FromFields`](./from_fields.md) — the reverse conversion. - [`ToFieldsRef`](./to_fields_ref.md) — the borrowing form, which leaves the value intact. - [`HasFieldsRef`](./has_fields_ref.md) — the shape that form produces. -- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl. -- [`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), and [`Field`](../types/field.md) — what +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. +- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md) — what a shape is made of. -- [Type-level spines](../types/type_level_spines.md) — the `Cons` chain the conversion builds. -- [`HasBuilder`](./has_builder.md) — incremental assembly, as against this wholesale conversion. +- [Type-level spines](../../types/type_level_spines.md) — the `Cons` chain the conversion builds. +- [`HasBuilder`](../builder/has_builder.md) — incremental assembly, as against this wholesale conversion. The ideas behind it: diff --git a/docs/reference/traits/to_fields_ref.md b/docs/reference/traits/shape/to_fields_ref.md similarity index 76% rename from docs/reference/traits/to_fields_ref.md rename to docs/reference/traits/shape/to_fields_ref.md index 167d009a..da4e4a19 100644 --- a/docs/reference/traits/to_fields_ref.md +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -1,5 +1,6 @@ --- sidebar_label: 'ToFieldsRef' +sidebar_position: 5 --- # `ToFieldsRef` @@ -10,7 +11,16 @@ Walking a value's shape without consuming it. [`ToFields`](./to_fields.md) takes a value apart into its shape and consumes it in the process. Code that only reads — a validator, a serializer, a routine that inspects a struct and hands it back — should not -have to. `ToFieldsRef` produces the **borrowed** shape instead: +have to. `ToFieldsRef` produces the **borrowed** shape instead. The original survives, and every entry in +the result holds a reference rather than a value. + +**It is the weaker requirement, so prefer it wherever it suffices.** Bounding on +[`ToFields`](./to_fields.md) when a borrow would do forces every caller to give up ownership or clone, +which is the most common over-requirement in this family. + +## Definition + +`ToFieldsRef` adds one borrowing method to the borrowed-shape trait it extends: ```rust pub trait ToFieldsRef: HasFieldsRef { @@ -20,21 +30,18 @@ pub trait ToFieldsRef: HasFieldsRef { } ``` -The original survives, and every entry in the result holds a reference rather than a value. - -**It is the weaker requirement, so prefer it wherever it suffices.** Bounding on -[`ToFields`](./to_fields.md) when a borrow would do forces every caller to give up ownership or clone, -which is the most common over-requirement in this family. +It supertraits [`HasFieldsRef`](./has_fields_ref.md) rather than [`HasFields`](./has_fields.md), which is +the one structural difference from its owning counterpart [`ToFields`](./to_fields.md): the borrowed shape +and the owned shape are named by two independent traits, and each conversion supertraits the one it +produces. The method borrows `self` for `'a` and returns the borrowed +[`FieldsRef<'a>`](./has_fields_ref.md) shape at that lifetime, so the original stays intact, and the +`where Self: 'a` clause keeps the borrowed shape from outliving the value. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -It supertraits [`HasFieldsRef`](./has_fields_ref.md) rather than [`HasFields`](./has_fields.md), which -is the one structural difference from its owning counterpart: the borrowed shape and the owned shape are -named by two independent traits, and each conversion supertraits the one it produces. - -The impls come from [`#[derive(HasFields)]`](../derives/derive_has_fields.md), which emits all five shape +The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all five shape traits together. ## Examples @@ -74,14 +81,14 @@ where ## When to use it -**Bound on it whenever generic code reads a shape and the caller keeps the value** — which is most +**Bound on it whenever generic code reads a shape and the caller keeps the value.** This is most read-only structural code. - **[`ToFields`](./to_fields.md)** when the code genuinely consumes: a conversion, a merge, a rebuild. - **[`FromFields`](./from_fields.md)** for constructing a value, which has no borrowing counterpart — a borrowed shape cannot yield an owned value. - **[`HasFieldsRef`](./has_fields_ref.md) alone** when the code only *names* the borrowed shape. -- **[`HasField`](./has_field.md)** when one named field is all that is wanted. +- **[`HasField`](../field-access/has_field.md)** when one named field is all that is wanted. There is one thing this cannot do that [`ToFields`](./to_fields.md) can: hand the entries' values onward by ownership. A routine that must move a field out of a struct needs the owning form. @@ -97,7 +104,7 @@ under the reserved lifetime name `'__a` that // Cons((&self.name).into(), Cons((&self.age).into(), Nil)) ``` -The `where Self: 'a` clause on both the trait method and the associated type is what keeps the result +The `where Self: 'a` clause on both the trait method and the associated type keeps the result tied to the borrow it came from, so the shape cannot outlive the value. One consequence follows from the rewrite being per-entry rather than structural: **a field that is @@ -105,8 +112,8 @@ already a reference gains another one**, appearing as `&'__a &'a Name`. That is detail most likely to look wrong in an error message. An enum's borrowed conversion matches the concrete variant and produces the corresponding arm of the -borrowed sum, with the payload borrowed rather than moved — which is also how -[`HasExtractorRef`](./has_extractor_ref.md) reads a variant without consuming the value. +borrowed sum, with the payload borrowed rather than moved, which is also how +[`HasExtractorRef`](../variant/has_extractor_ref.md) reads a variant without consuming the value. ## Common Mistakes @@ -129,10 +136,10 @@ special case the owned shape has. - [`ToFields`](./to_fields.md) — the owning counterpart, which consumes the value. - [`FromFields`](./from_fields.md) — rebuilding a value, which has no borrowing form. - [`HasFields`](./has_fields.md) — the owned shape, and where the family is explained in full. -- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates this impl. -- [`HasExtractorRef`](./has_extractor_ref.md) — the same borrow-rather-than-consume idea on the enum +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. +- [`HasExtractorRef`](../variant/has_extractor_ref.md) — the same borrow-rather-than-consume idea on the enum side. -- [`Field`](../types/field.md) — one entry of a shape. +- [`Field`](../../types/field.md) — one entry of a shape. The ideas behind it: diff --git a/docs/reference/traits/type-level/_category_.json b/docs/reference/traits/type-level/_category_.json new file mode 100644 index 00000000..0db95506 --- /dev/null +++ b/docs/reference/traits/type-level/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Type-level list algebra", + "position": 8, + "link": { + "type": "doc", + "id": "reference/traits/type-level/index" + } +} diff --git a/docs/reference/traits/append_product.md b/docs/reference/traits/type-level/append_product.md similarity index 77% rename from docs/reference/traits/append_product.md rename to docs/reference/traits/type-level/append_product.md index f86826dd..537daeeb 100644 --- a/docs/reference/traits/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -1,5 +1,6 @@ --- sidebar_label: 'AppendProduct' +sidebar_position: 5 --- # `AppendProduct` @@ -19,13 +20,20 @@ explains what it produces so that message is legible. The one case for naming it ## Overview -A struct's shape in CGP is a type-level list — a [`Product!`](../macros/product.md) of named fields. +A struct's shape in CGP is a type-level list — a [`Product!`](../../macros/product.md) of named fields. Code that processes such a shape generically sometimes needs to describe a *new* shape computed from an old one: the shape a builder will have after one more field is set, say, or the shape a routine promises to return. `AppendProduct` is that computation for a single entry. It takes a product and an item and names -the product with that item added **at the end**: +the product with that item added **at the end**. + +**This is one of the least user-facing traits in the reference.** You meet it if you write generic code +over shapes, and otherwise only in an error message from code that does. + +## Definition + +`AppendProduct` is parameterized by the item to add and exposes the extended list as an associated type: ```rust pub trait AppendProduct { @@ -33,11 +41,10 @@ pub trait AppendProduct { } ``` -There is no method, because there is nothing to execute. The result is an associated type, evaluated by -the trait solver while the compiler type-checks, so it carries no runtime cost and imposes no ordering. - -**This is one of the least user-facing traits in the reference.** You meet it if you write generic code -over shapes, and otherwise only in an error message from code that does. +`Self` is the existing product, `Item` is the entry to add, and `Output` is the resulting product. `Item` +may be unsized. There is no method, because there is nothing to execute: `Output` is an associated type +the trait solver evaluates while the compiler type-checks, so it carries no runtime cost and imposes no +ordering. ## Usage @@ -47,11 +54,9 @@ over shapes, and otherwise only in an error message from code that does. use cgp::core::field::traits::AppendProduct; ``` -`Self` is the existing product, `Item` is the entry to add, and `Output` is the result. `Item` may be -unsized. Every existing entry is preserved in order, and the new one lands last. - -Appending onto `Nil` — the empty product — yields a one-element list, which is the recursion's base case -and occasionally useful to know when reading a bound. +Every existing entry is preserved in order, and the new one lands last. Appending onto `Nil` — the empty +product — yields a one-element list, which is the recursion's base case and occasionally useful to know +when reading a bound. ## Examples @@ -82,14 +87,14 @@ where **Reach for it when a routine must describe the shape it *will* produce** — in a signature, an associated type, or a `where` clause — and essentially never otherwise. It is a building block the extensible-data -machinery uses; the machinery itself is what application code touches. +machinery uses; application code touches the machinery itself. - **Reach for [`ConcatProduct`](./concat_product.md)** to splice a whole list rather than one entry. Append is its single-entry special case, so if you find yourself appending in a loop, you wanted concat. -- **Use [`HasFields`](./has_fields.md) instead** if you only need a type's *existing* shape. This trait +- **Use [`HasFields`](../shape/has_fields.md) instead** if you only need a type's *existing* shape. This trait computes new shapes; it is not how you obtain one. -- **Use the [builder](./has_builder.md) or [extractor](./extract_field.md) family instead** if you are +- **Use the [builder](../builder/has_builder.md) or [extractor](../variant/extract_field.md) family instead** if you are moving *values* through a shape. This never touches a value, so if you want something to happen at run time, it is the wrong layer. @@ -141,11 +146,11 @@ from. - [`ConcatProduct`](./concat_product.md) — the general form; append is its single-entry case. - [`MapFields`](./map_fields.md) — rewriting every entry rather than adding one. -- [`Product!`](../macros/product.md) — the sugar for the lists this operates on. -- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` chain underneath. -- [`HasFields`](./has_fields.md) — where a type's existing shape comes from. -- [`Field`](../types/field.md) — the entries a field list is usually made of. -- [`HasBuilder`](./has_builder.md) — the family that moves values through the shapes this computes. +- [`Product!`](../../macros/product.md) — the sugar for the lists this operates on. +- [Type-level spines](../../types/type_level_spines.md) — the `Cons`/`Nil` chain underneath. +- [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. +- [`Field`](../../types/field.md) — the entries a field list is usually made of. +- [`HasBuilder`](../builder/has_builder.md) — the family that moves values through the shapes this computes. The ideas behind it: diff --git a/docs/reference/traits/concat_product.md b/docs/reference/traits/type-level/concat_product.md similarity index 74% rename from docs/reference/traits/concat_product.md rename to docs/reference/traits/type-level/concat_product.md index aff50c20..c493a0a2 100644 --- a/docs/reference/traits/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -1,5 +1,6 @@ --- sidebar_label: 'ConcatProduct' +sidebar_position: 6 --- # `ConcatProduct` @@ -20,8 +21,16 @@ produces. The one case for naming it is generic code that must describe the shap ## Overview Merging two records means merging their shapes, and the shapes are type-level lists — a -[`Product!`](../macros/product.md) of named fields each. `ConcatProduct` names the list you get by -following one product with another: +[`Product!`](../../macros/product.md) of named fields each. `ConcatProduct` names the list you get by +following one product with another. + +It is the general form of [`AppendProduct`](./append_product.md): **append is the single-entry special +case of concat**, and that is the shortest way to hold both in mind. + +## Definition + +`ConcatProduct` is parameterized by the second product and exposes the joined list as an associated +type: ```rust pub trait ConcatProduct { @@ -29,11 +38,9 @@ pub trait ConcatProduct { } ``` -There is no method, because there is nothing to execute. The result is an associated type evaluated by -the trait solver during type checking, so it costs nothing at run time. - -It is the general form of [`AppendProduct`](./append_product.md): **append is the single-entry special -case of concat**, and that is the shortest way to hold both in mind. +`Self` is the first product, `Items` is the second, and `Output` is the first's entries followed by the +second's, in order. There is no method, because there is nothing to execute: `Output` is an associated +type the trait solver evaluates during type checking, so it costs nothing at run time. ## Usage @@ -43,9 +50,6 @@ case of concat**, and that is the shortest way to hold both in mind. use cgp::core::field::traits::ConcatProduct; ``` -`Self` is the first product, `Items` is the second, and `Output` is the first's entries followed by the -second's. Order is preserved on both sides. - Two identities are worth knowing, because they let a generic bound resolve in the degenerate cases: concatenating onto `Nil` yields the other list unchanged, and concatenating `Nil` onto a list leaves it unchanged. @@ -68,7 +72,7 @@ type Full = >::Output; // = Product![host, port, tls] ``` -Which is the type-level counterpart of what [`CanBuildFrom`](./can_build_from.md) does with values: this +Which is the type-level counterpart of what [`CanBuildFrom`](../casting/can_build_from.md) does with values: this names the combined shape, that moves the fields into it. ## When to use it @@ -78,11 +82,11 @@ routine that extends a record with a caller-supplied set of fields — and essen - **Reach for [`AppendProduct`](./append_product.md)** for a single entry. It is the same recursion with a one-element graft, and it reads better for the one-field case. -- **Use [`HasFields`](./has_fields.md) instead** if you only need a type's *existing* shape. -- **Use [`CanBuildFrom`](./can_build_from.md) instead** if you want the *values* merged rather than the +- **Use [`HasFields`](../shape/has_fields.md) instead** if you only need a type's *existing* shape. +- **Use [`CanBuildFrom`](../casting/can_build_from.md) instead** if you want the *values* merged rather than the shapes named. This trait never touches a value. -- **Note that [`ConcatPath`](./concat_path.md) is the path-level analogue**, doing the same job for the - segment lists behind [`Path!`](../macros/path.md), with the same two-impl recursion. +- **Note that [`ConcatPath`](../formatting/concat_path.md) is the path-level analogue**, doing the same job for the + segment lists behind [`Path!`](../../macros/path.md), with the same two-impl recursion. There is no `ConcatSum`. Combining two sums is not an operation this layer provides. @@ -117,7 +121,7 @@ rather than to the result's. **The result is `Output`, while [`MapFields`](./map_fields.md) exposes `Mapped`.** The asymmetry between the three product operations is easy to forget. -**It is product-only.** For paths, the analogue is [`ConcatPath`](./concat_path.md); for sums, there is +**It is product-only.** For paths, the analogue is [`ConcatPath`](../formatting/concat_path.md); for sums, there is nothing. **Duplicate entries are not detected.** Concatenating two products that share a field name yields a list @@ -134,11 +138,11 @@ to the first one's width. - [`AppendProduct`](./append_product.md) — the single-entry case. - [`MapFields`](./map_fields.md) — rewriting every entry rather than adding any. -- [`ConcatPath`](./concat_path.md) — the same operation over type-level paths. -- [`Product!`](../macros/product.md) — the sugar for the lists this operates on. -- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` chain underneath. -- [`CanBuildFrom`](./can_build_from.md) — merging the values whose shapes this combines. -- [`HasFields`](./has_fields.md) — where a type's existing shape comes from. +- [`ConcatPath`](../formatting/concat_path.md) — the same operation over type-level paths. +- [`Product!`](../../macros/product.md) — the sugar for the lists this operates on. +- [Type-level spines](../../types/type_level_spines.md) — the `Cons`/`Nil` chain underneath. +- [`CanBuildFrom`](../casting/can_build_from.md) — merging the values whose shapes this combines. +- [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. The ideas behind it: diff --git a/docs/reference/traits/type-level/index.md b/docs/reference/traits/type-level/index.md new file mode 100644 index 00000000..0d775db5 --- /dev/null +++ b/docs/reference/traits/type-level/index.md @@ -0,0 +1,37 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Type-level list algebra + +The per-field state markers and list operations the extensible-data families are built from. + +## Overview + +These are the least user-facing traits in the reference. They are the type-level plumbing beneath the +[builders](../builder/index.md), [extractors](../variant/index.md), and [casts](../casting/index.md): +the markers that record what state one field is in, and the operations that grow and reshape a type's +field list. You meet them in an error message from code that walks a shape far more often than in code +you wrote, and this group exists so that such a message is legible. Most are not in the prelude. + +The group divides into the state markers and the list operations. + +The **state markers** name how one field of a partial type is stored. [`MapType`](map_type.md) is the +marker trait, and its `IsPresent`, `IsNothing`, and `IsVoid` markers are what a builder or extractor +error prints. [`MapTypeRef`](map_type_ref.md) does the same for a borrowed view, adding a lifetime. +[`TransformMap`](transform_map.md) carries the function that converts one field between markers, and +[`TransformMapFields`](transform_map_fields.md) lifts that conversion across a whole record. + +The **list operations** compute new field lists from old ones. [`AppendProduct`](append_product.md) adds +one entry to a product and [`ConcatProduct`](concat_product.md) splices two together, while +[`MapFields`](map_fields.md) rewrites every entry of a product or a sum through one marker. + +## The ideas behind them + +- [Extensible records](/docs/concepts/extensible-records) — presence tracking on a partial record. +- [Extensible variants](/docs/concepts/extensible-variants) — possibility tracking on a partial variant. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/map_fields.md b/docs/reference/traits/type-level/map_fields.md similarity index 80% rename from docs/reference/traits/map_fields.md rename to docs/reference/traits/type-level/map_fields.md index fe4151e4..232cbbf9 100644 --- a/docs/reference/traits/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -1,5 +1,6 @@ --- sidebar_label: 'MapFields' +sidebar_position: 7 --- # `MapFields` @@ -12,7 +13,7 @@ Rewriting every entry of a type-level list through one marker. **You are not expected to use `MapFields` directly.** It is the type-level operation behind a partial record's shape, computed by the machinery -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) generates. You will most likely meet it in an error +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) generates. You will most likely meet it in an error message; this page explains what it produces, and how it differs from the two similarly-named traits beside it. The one case for naming it is generic code that must describe a uniformly re-wrapped shape. @@ -22,13 +23,7 @@ beside it. The one case for naming it is generic code that must describe a unifo A partial record is the same record with every field's storage changed the same way — each value wrapped in an `Option`, or replaced by `()`, or left alone. Describing that as a type means rewriting every entry -of the shape uniformly, and `MapFields` is that operation: - -```rust -pub trait MapFields { - type Mapped; -} -``` +of the shape uniformly, and `MapFields` is that operation. The list's length and order never change. Each entry type `T` becomes `Mapper::Map`, where the mapper is a [`MapType`](./map_type.md) marker — so **the marker decides the whole effect**. With `IsPresent` it @@ -36,9 +31,24 @@ is the identity; with `IsNothing` every entry collapses to `()`; with `IsOptiona `Option<_>`; with `IsVoid` every entry becomes uninhabited. It is the transforming member of the three product operations, and the only one defined over **both** -spines: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum. That is what lets one +spines: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum. That lets one operation produce both a partial record and a partial enum. +## Definition + +`MapFields` is parameterized by a marker and exposes the rewritten list as an associated type: + +```rust +pub trait MapFields { + type Mapped; +} +``` + +`Self` is the list, `Mapper` is the [`MapType`](./map_type.md) marker to apply, and the result is exposed +as `Mapped` — note the name, which differs from the `Output` its two siblings +[`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md) expose. There is no +method, because there is nothing to execute. + ## Usage **It is not in the prelude**, and neither is `IsOptional`. Import the trait from @@ -51,9 +61,6 @@ use cgp::core::field::traits::MapFields; `IsPresent`, `IsNothing`, and `IsVoid` are in the prelude; `IsOptional` is not. -`Self` is the list, `Mapper` is the marker, and the result is `Mapped` — note the name, which differs -from the `Output` its two siblings expose. There is no method, because there is nothing to execute. - ## Examples Applying `IsOptional` turns a product of values into a product of optionals — the shape a partial builder @@ -70,7 +77,7 @@ type Optional = >::Mapped; // = Product![Option, Option, Option] ``` -The same marker applies over a sum, which is what makes one operation serve both halves of the +The same marker applies over a sum, which makes one operation serve both halves of the extensible-data machinery: ```rust @@ -82,18 +89,18 @@ type OptionalVariants = >::Mapped; ## When to use it -**Reach for it when generic code must name a uniformly re-wrapped shape**, which is what a partial -representation is — and essentially never otherwise. +**Reach for it when generic code must name a uniformly re-wrapped shape**, the form a partial +representation takes — and essentially never otherwise. - **Reach for [`AppendProduct`](./append_product.md) or [`ConcatProduct`](./concat_product.md)** when the shape grows rather than changing its wrapping. - **Use [`TransformMapFields`](./transform_map_fields.md) instead** when you want the *values* re-wrapped rather than the type named. This trait computes a type; nothing wraps anything at run time by itself. -- **Use [`HasFields`](./has_fields.md) instead** if you only need a type's existing shape. +- **Use [`HasFields`](../shape/has_fields.md) instead** if you only need a type's existing shape. One name worth disambiguating, because three similar ones sit close together. `MapFields` applies one marker across a whole list; [`MapType`](./map_type.md) is a single marker naming *one* field's storage; -and [`MapField`](./map_field.md) — singular, no *s* — is a lifetime helper for reading a nested field. +and [`MapField`](../field-access/map_field.md) — singular, no *s* — is a lifetime helper for reading a nested field. Three similar names, three unrelated jobs. ## Under the hood @@ -150,11 +157,11 @@ width. that grow a list rather than rewrite it. - [`TransformMapFields`](./transform_map_fields.md) — the value-level counterpart, which actually converts the fields. -- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the sugar for both spines. -- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the sugar for both spines. +- [Type-level spines](../../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. -- [`HasFields`](./has_fields.md) — where a type's existing shape comes from. -- [`MapField`](./map_field.md) — the similarly-named lifetime helper, which does something else entirely. +- [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. +- [`MapField`](../field-access/map_field.md) — the similarly-named lifetime helper, which does something else entirely. The ideas behind it: diff --git a/docs/reference/traits/map_type.md b/docs/reference/traits/type-level/map_type.md similarity index 77% rename from docs/reference/traits/map_type.md rename to docs/reference/traits/type-level/map_type.md index 181fe643..29c96f01 100644 --- a/docs/reference/traits/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -1,5 +1,6 @@ --- sidebar_label: 'MapType' +sidebar_position: 1 --- # `MapType` @@ -12,7 +13,7 @@ The marker trait that decides how one field of a partial type is stored. **You are not expected to implement `MapType`.** Its four markers are supplied by CGP, and the partial types parameterized by them are generated by -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) and its slices. What you do with this trait is +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) 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. @@ -25,7 +26,16 @@ independently wrapped: a field that is set carries its value, a field that is no 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, and it has one member: +`MapType` is that marker's trait. It lets the [builder](../builder/has_builder.md) and +[extractor](../variant/extract_field.md) 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 no method: ```rust pub trait MapType { @@ -34,15 +44,9 @@ pub trait MapType { ``` `Map` names the storage type the marker assigns to a field whose value type is `T`. So -`IsPresent::Map` is `String`, and `IsNothing::Map` is `()`. **The marker is the field's -state, expressed as a type.** - -That is what lets the [builder](./has_builder.md) and [extractor](./extract_field.md) 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. +`IsPresent::Map` is `String`, and `IsNothing::Map` is `()`. The marker is the field's +state, expressed as a type. Because `Map` is a **generic associated type**, a bound that pins the +storage reads `M: MapType = String>`, and one that leaves it open is plain `M: MapType`. ## Usage @@ -59,13 +63,9 @@ impl MapType for IsOptional { type Map = Option; } // the field may or may **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** — which is exactly how an +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. -`Map` is a **generic associated type**, so a bound naming it is written -`M: MapType = String>` when the storage must be pinned, and plain `M: MapType` when it need -not be. - **Three companions complete the picture**, each on its own page: [`MapTypeRef`](./map_type_ref.md) does the same job for borrowed views, where the wrapping also introduces a lifetime, while [`TransformMap`](./transform_map.md) and [`TransformMapFields`](./transform_map_fields.md) are the @@ -74,10 +74,10 @@ value-level side, carrying the functions that actually convert a field from one ## Examples You mostly meet the markers inside the partial types that -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) generates, where a builder's type reads +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) generates, where a builder's type reads `__PartialPerson` and tells you at a glance which fields are set. -Bounding on the trait is what generic partial-type machinery does: +Generic partial-type machinery bounds on the trait: ```rust use cgp::prelude::*; @@ -114,7 +114,7 @@ The trait itself has narrower uses. - **Do not implement `MapType` for a new marker** expecting the derives to use it. The generated partial types are parameterized over markers, but only the four standard ones have transforms and finalize impls behind them; a fifth marker is a type with no machinery attached. -- **Reach for the [optional-field layer](./has_optional_builder.md)** if what you want is defaulted or +- **Reach for the [optional-field layer](../optional/has_optional_builder.md)** if what you want is defaulted or optional finalization. Both already exist, built on exactly this. [`MapFields`](./map_fields.md) — the other trait with a similar name — is a different thing: it applies @@ -137,7 +137,7 @@ pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { ``` 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`](./update_field.md) is what performs one such +transition is a change of type argument. [`UpdateField`](../builder/update_field.md) performs one such transition on a value. ## Common Mistakes @@ -151,7 +151,7 @@ two families have been crossed. **`MapType` and [`MapFields`](./map_fields.md) 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`](./map_field.md) — singular, no *s* — is a third, unrelated thing again. +[`MapField`](../field-access/map_field.md) — singular, no *s* — is a third, unrelated thing again. **A new marker gets you a type and nothing else.** Implementing `MapType` is easy; the derives' finalize and transform impls are written against the standard markers, so a custom one has no machinery behind it. @@ -164,13 +164,13 @@ and transform impls are written against the standard markers, so a custom one ha - [`MapTypeRef`](./map_type_ref.md) — the same idea for borrowed views, with a lifetime. - [`TransformMap`](./transform_map.md) — the per-field conversion function, and the extension point. - [`TransformMapFields`](./transform_map_fields.md) — that conversion lifted across a whole record. -- [`HasBuilder`](./has_builder.md) — uses `IsPresent`/`IsNothing` to track which fields are filled. -- [`ExtractField`](./extract_field.md) — uses `IsPresent`/`IsVoid` to track which variants remain. -- [`UpdateField`](./update_field.md) — the primitive that moves a field from one marker to another. +- [`HasBuilder`](../builder/has_builder.md) — uses `IsPresent`/`IsNothing` to track which fields are filled. +- [`ExtractField`](../variant/extract_field.md) — uses `IsPresent`/`IsVoid` to track which variants remain. +- [`UpdateField`](../builder/update_field.md) — the primitive that moves a field from one marker to another. - [`MapFields`](./map_fields.md) — applies one marker across a whole type-level list. -- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — generates the partial types these markers +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — generates the partial types these markers parameterize. -- [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. +- [Type-level spines](../../types/type_level_spines.md) — where the uninhabited `Void` comes from. The ideas behind it: diff --git a/docs/reference/traits/map_type_ref.md b/docs/reference/traits/type-level/map_type_ref.md similarity index 78% rename from docs/reference/traits/map_type_ref.md rename to docs/reference/traits/type-level/map_type_ref.md index a29ca63a..58d6f02e 100644 --- a/docs/reference/traits/map_type_ref.md +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -1,5 +1,6 @@ --- sidebar_label: 'MapTypeRef' +sidebar_position: 2 --- # `MapTypeRef` @@ -11,7 +12,7 @@ The marker trait deciding how a borrowed partial type holds its payloads. ### Generated machinery **You are not expected to implement `MapTypeRef`.** Its three markers are supplied -by CGP, and [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) generates the borrowed +by CGP, and [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) generates the borrowed companion that carries one. What you do with this trait is recognize its markers in an error; this page explains what each one means and how it composes with the per-field markers. The one case for bounding on the trait is generic code of your own over a borrowed partial type's outer marker. @@ -22,7 +23,17 @@ explains what each one means and how it composes with the per-field markers. The [`MapType`](./map_type.md) decides whether a field of a partial type holds its value, nothing, or an uninhabited type. A **borrowed** partial type needs a second decision on top: whether each payload is held by shared reference, by mutable reference, or by value. That decision brings a lifetime with it, -which is why it needs its own trait: +which is why it needs its own trait. + +**The two families compose rather than compete.** A borrowed extractor carries one outer `MapTypeRef` +marker shared across all fields and one [`MapType`](./map_type.md) marker per field, so a field's storage +is `MapType::Map>`. [`HasExtractorRef`](../variant/has_extractor_ref.md) fixes the outer +marker to `IsRef` and [`HasExtractorMut`](../variant/has_extractor_mut.md) to `IsMut`, which lets a value +be matched without being moved, with the narrowing working identically. + +## Definition + +`MapTypeRef` carries a single generic associated type and no method: ```rust pub trait MapTypeRef { @@ -30,7 +41,15 @@ pub trait MapTypeRef { } ``` -Three markers implement it: +`Map<'a, T>` is a **generic associated type** over both a lifetime and a type. The `T: 'a` bound +requires the payload to outlive the borrow, and the `: 'a` bound on the result keeps the storage type +from outliving it either. That is more machinery than [`MapType`](./map_type.md)'s single-parameter +`Map`, and it makes the borrowed shape expressible at whatever lifetime a caller has. + +## Usage + +**`IsRef` and `IsMut` are in the prelude; `IsOwned` is not** — import it from `cgp::core::field::impls`. +The trait itself comes with the prelude. Three markers implement it: ```rust impl MapTypeRef for IsRef { type Map<'a, T: 'a> = &'a T; } @@ -38,21 +57,6 @@ impl MapTypeRef for IsMut { type Map<'a, T: 'a> = &'a mut T; } impl MapTypeRef for IsOwned { type Map<'a, T: 'a> = T; } ``` -**The two families compose rather than compete.** A borrowed extractor carries one outer `MapTypeRef` -marker shared across all fields and one [`MapType`](./map_type.md) marker per field, so a field's storage -is `MapType::Map>`. [`HasExtractorRef`](./has_extractor_ref.md) fixes the outer -marker to `IsRef` and [`HasExtractorMut`](./has_extractor_mut.md) to `IsMut` — which is what lets a value -be matched without being moved, with the narrowing working identically. - -## Usage - -**`IsRef` and `IsMut` are in the prelude; `IsOwned` is not** — import it from `cgp::core::field::impls`. -The trait itself comes with the prelude. - -The associated type is generic over both a lifetime and a type, with `T: 'a` required and the result -bounded `'a`. That is more machinery than [`MapType`](./map_type.md)'s single-parameter `Map`, and it -is what makes the borrowed shape expressible at whatever lifetime a caller has. - :::warning **`IsOwned` has no consumer in CGP.** No derive emits it and no provider resolves against it. It is @@ -101,9 +105,9 @@ in the first case, `&mut Circle` in the second — while the per-field **You will recognize these markers far more often than you name them**, and recognizing them is most of what this page is for: an error mentioning `IsRef` is telling you the value is being read through -[`extractor_ref`](./has_extractor_ref.md) rather than consumed. +[`extractor_ref`](../variant/has_extractor_ref.md) rather than consumed. -- **Use [`HasExtractorRef`](./has_extractor_ref.md) or [`HasExtractorMut`](./has_extractor_mut.md)** +- **Use [`HasExtractorRef`](../variant/has_extractor_ref.md) or [`HasExtractorMut`](../variant/has_extractor_mut.md)** rather than naming a marker. They fix the outer marker for you, and they are the constructs this trait serves. - **Bound on `MapTypeRef`** only when writing generic machinery over a borrowed partial type's outer @@ -111,7 +115,7 @@ what this page is for: an error mentioning `IsRef` is telling you the value is b - **Do not select `IsOwned` expecting it to work.** Nothing in CGP consumes it. - **Use [`MapType`](./map_type.md)** for the per-field state, which is the decision this one sits beside rather than replaces. -- **Use [`ToFieldsRef`](./to_fields_ref.md)** when what you want is the borrowed *shape* of a struct +- **Use [`ToFieldsRef`](../shape/to_fields_ref.md)** when what you want is the borrowed *shape* of a struct rather than a borrowed extractor. That trait solves the same problem for the record side, without markers. @@ -159,13 +163,13 @@ reads as though the machinery is at fault. ## Related constructs - [`MapType`](./map_type.md) — the per-field presence marker this composes with. -- [`HasExtractorRef`](./has_extractor_ref.md) and [`HasExtractorMut`](./has_extractor_mut.md) — the two +- [`HasExtractorRef`](../variant/has_extractor_ref.md) and [`HasExtractorMut`](../variant/has_extractor_mut.md) — the two accessors that fix the outer marker. -- [`ExtractField`](./extract_field.md) — the narrowing that works identically through a borrow. -- [`ToFieldsRef`](./to_fields_ref.md) — the record side's answer to the same problem. -- [`HasFieldsRef`](./has_fields_ref.md) — the borrowed shape it produces. -- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the borrowed companion. -- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain underneath. +- [`ExtractField`](../variant/extract_field.md) — the narrowing that works identically through a borrow. +- [`ToFieldsRef`](../shape/to_fields_ref.md) — the record side's answer to the same problem. +- [`HasFieldsRef`](../shape/has_fields_ref.md) — the borrowed shape it produces. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the borrowed companion. +- [Type-level spines](../../types/type_level_spines.md) — the `Either`/`Void` chain underneath. The ideas behind it: diff --git a/docs/reference/traits/transform_map.md b/docs/reference/traits/type-level/transform_map.md similarity index 76% rename from docs/reference/traits/transform_map.md rename to docs/reference/traits/type-level/transform_map.md index 6a40cdf2..7a3d4339 100644 --- a/docs/reference/traits/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -1,5 +1,6 @@ --- sidebar_label: 'TransformMap' +sidebar_position: 3 --- # `TransformMap` @@ -10,7 +11,16 @@ The per-field function that converts a value from one marker's storage to anothe [`MapType`](./map_type.md) only names storage *types*: it says that an `IsNothing` field holds `()` and an `IsPresent` field holds its value, and nothing about how you get from one to the other. -`TransformMap` carries that missing half — the actual function: +`TransformMap` carries that missing half: the function that performs the conversion. + +**This is the extension point of the whole partial-type scheme**, and it is genuinely usable. Defining a +new way to re-mark a record means writing one impl per source state and then applying it with +[`TransformMapFields`](./transform_map_fields.md). + +## Definition + +`TransformMap` is parameterized by a source marker, a target marker, and a value type, and carries one +method: ```rust pub trait TransformMap { @@ -18,13 +28,11 @@ pub trait TransformMap { } ``` -`Self` is a transform marker of your own naming; `M1` is the field's current state, `M2` the state it -should end in, and `T` the field's value type. So one impl answers one question: *given a field -currently in state `M1`, produce the same field in state `M2`.* - -**This is the extension point of the whole partial-type scheme**, and it is genuinely usable. Defining a -new way to re-mark a record means writing one impl per source state and then applying it with -[`TransformMapFields`](./transform_map_fields.md). +`Self` is a transform marker of your own naming. `M1` is the field's current state and `M2` the state it +should end in, both [`MapType`](./map_type.md) markers, and `T` is the field's value type. +`transform_mapped` takes the field's value as stored under `M1` (`M1::Map`) and returns it as stored +under `M2` (`M2::Map`). So one impl answers one question: given a field currently in state `M1`, +produce the same field in state `M2`. ## Usage @@ -75,24 +83,24 @@ impl TransformMap for FillDefaults { Read that as three cases of one rule: a present field passes through, an absent one becomes its default, and an optional one becomes its contents or the default. Note how each signature's argument type is the -source marker's `Map` — `T`, then `()`, then `Option` — which is what makes the three impls +source marker's `Map` — `T`, then `()`, then `Option` — which makes the three impls non-overlapping. Because all three target `IsPresent`, applying `FillDefaults` through [`transform_map_fields`](./transform_map_fields.md) leaves every field present, which is precisely the -configuration [`FinalizeBuild`](./finalize_build.md) accepts. +configuration [`FinalizeBuild`](../builder/finalize_build.md) accepts. -**That is not hypothetical: it is how [`CanFinalizeWithDefault`](./can_finalize_with_default.md) works**, +**That is not hypothetical: it is how [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) works**, and reading it here is the shortest route to understanding that layer. ## When to use it **Implement it to define a new per-field conversion**, and reach for the existing layer otherwise. -- **Use the [optional-field layer](./can_finalize_with_default.md)** if what you want is defaulted or +- **Use the [optional-field layer](../optional/can_finalize_with_default.md)** if what you want is defaulted or optional finalization. Both already exist, built on exactly this, and - [`TransformMapDefault`](./transform_map_default.md) and - [`TransformOptional`](./transform_optional.md) are the two markers it ships. + [`TransformMapDefault`](../optional/transform_map_default.md) and + [`TransformOptional`](../optional/transform_optional.md) are the two markers it ships. - **Implement `TransformMap`** for a conversion those do not cover — a validating transform, one that logs, one that fills from something other than `Default`. - **Use [`TransformMapFields`](./transform_map_fields.md)** to apply what you have written. This trait @@ -106,10 +114,10 @@ and reading it here is the shortest route to understanding that layer. The signature's argument and return types are **projections through the two markers**, so the concrete types differ per impl even though the trait is the same. `TransformMap` has an argument type of `::Map`, which normalizes to `()`, and a return type of `T`. -That is what lets three impls for one marker coexist without overlapping: they differ in `M1`. +That lets three impls for one marker coexist without overlapping: they differ in `M1`. -[`TransformMapFields`](./transform_map_fields.md) is what calls this. For each field of the target's -[`HasFields`](./has_fields.md) shape, it uses [`UpdateField`](./update_field.md) to take the field out — +[`TransformMapFields`](./transform_map_fields.md) calls this. For each field of the target's +[`HasFields`](../shape/has_fields.md) shape, it uses [`UpdateField`](../builder/update_field.md) to take the field out — learning the marker it was in — applies `Transform::transform_mapped`, and writes the result back under the target marker. @@ -145,13 +153,13 @@ layer's payoff comes from every field landing in one state, usually `IsPresent`. - [`TransformMapFields`](./transform_map_fields.md) — lifts this across a whole partial record. - [`MapType`](./map_type.md) — the markers naming each state, and the trait this supplies the missing half of. -- [`TransformMapDefault`](./transform_map_default.md) and [`TransformOptional`](./transform_optional.md) +- [`TransformMapDefault`](../optional/transform_map_default.md) and [`TransformOptional`](../optional/transform_optional.md) — the two markers CGP ships, and the models to copy. -- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the capability built from the first of +- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) — the capability built from the first of them. -- [`UpdateField`](./update_field.md) — the primitive the walk uses to take a field out and write it back. -- [`FinalizeBuild`](./finalize_build.md) — what an all-`IsPresent` result is accepted by. -- [`HasFields`](./has_fields.md) — the shape the walk follows. +- [`UpdateField`](../builder/update_field.md) — the primitive the walk uses to take a field out and write it back. +- [`FinalizeBuild`](../builder/finalize_build.md) — what an all-`IsPresent` result is accepted by. +- [`HasFields`](../shape/has_fields.md) — the shape the walk follows. The ideas behind it: diff --git a/docs/reference/traits/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md similarity index 64% rename from docs/reference/traits/transform_map_fields.md rename to docs/reference/traits/type-level/transform_map_fields.md index ec4518a0..a4a55272 100644 --- a/docs/reference/traits/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -1,5 +1,6 @@ --- sidebar_label: 'TransformMapFields' +sidebar_position: 4 --- # `TransformMapFields` @@ -12,8 +13,8 @@ Applying one per-field transform across a whole partial record. **You are not expected to call `transform_map_fields` directly.** It is the recursion the optional-field layer is built from, and -[`CanFinalizeWithDefault`](./can_finalize_with_default.md) and [`ToOptional`](./to_optional.md) are what -you call. This page explains the walk, which is what makes those two behave so symmetrically. The one case for bounding on it is writing a capability of your own that re-marks a whole record. +[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and [`ToOptional`](../optional/to_optional.md) are what +you call. This page explains the walk, which makes those two behave so symmetrically. The one case for bounding on it is writing a capability of your own that re-marks a whole record. ::: @@ -21,7 +22,16 @@ you call. This page explains the walk, which is what makes those two behave so s [`TransformMap`](./transform_map.md) converts *one* field from one marker's storage to another's. `TransformMapFields` lifts that conversion across an entire partial record, so every field is re-marked -in one call: +in one call. + +**This is the motion the optional-field layer is made of.** Re-marking every field to `IsPresent` and +then calling the ordinary [`finalize_build`](../builder/finalize_build.md) is exactly what +[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) does, and re-marking to `IsOptional` is what +[`ToOptional`](../optional/to_optional.md) does. + +## Definition + +`TransformMapFields` is parameterized by a transform marker and a target marker, and carries one method: ```rust pub trait TransformMapFields { @@ -31,14 +41,10 @@ pub trait TransformMapFields { } ``` -`Self` is the partial value, `Transform` is the marker carrying the per-field functions, and `TargetMap` -is the [`MapType`](./map_type.md) marker every field should end in. `Output` is the partial type with -every field re-marked accordingly. - -**This is the motion the optional-field layer is made of.** Re-marking every field to `IsPresent` and -then calling the ordinary [`finalize_build`](./finalize_build.md) is exactly what -[`CanFinalizeWithDefault`](./can_finalize_with_default.md) does, and re-marking to `IsOptional` is what -[`ToOptional`](./to_optional.md) does. +`Self` is the partial value. `Transform` is the marker carrying the per-field functions, written as +[`TransformMap`](./transform_map.md) impls, and `TargetMap` is the [`MapType`](./map_type.md) marker +every field should end in. `Output` is the partial type with every field re-marked accordingly, and +`transform_map_fields` consumes the partial value and returns it. ## Usage @@ -48,7 +54,7 @@ then calling the ordinary [`finalize_build`](./finalize_build.md) is exactly wha use cgp::core::field::traits::TransformMapFields; ``` -It is implemented for any [`PartialData`](./partial_data.md) whose fields the transform can convert, so +It is implemented for any [`PartialData`](../builder/partial_data.md) whose fields the transform can convert, so there is nothing to implement — what you supply is the `Transform` marker, by writing [`TransformMap`](./transform_map.md) impls for it. @@ -58,7 +64,7 @@ site, which is why the method reads as a bare `self.transform_map_fields()`. ## Examples You reach it through the layer built on it far more often than directly. This is the whole body of -[`CanFinalizeWithDefault`](./can_finalize_with_default.md): +[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md): ```rust use cgp::core::field::traits::TransformMapFields; @@ -79,29 +85,29 @@ where Read the two bounds together: the first says every field can be re-marked to `IsPresent` by `TransformMapDefault`, and the second says the result is then finalizable. The strict presence check -still runs — it just always passes, because the transform guaranteed presence first. +still runs. It just always passes, because the transform guaranteed presence first. Applying a transform of your own follows the same shape, with your marker in place of `TransformMapDefault`. ## When to use it -**Bound on it when writing a capability that re-marks a whole record**, which is what extending the -optional-field layer means. +**Bound on it when writing a capability that re-marks a whole record.** Extending the optional-field +layer requires exactly that. -- **Use [`CanFinalizeWithDefault`](./can_finalize_with_default.md) or - [`ToOptional`](./to_optional.md)** if what you want is one of the two conversions CGP already ships. +- **Use [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) or + [`ToOptional`](../optional/to_optional.md)** if what you want is one of the two conversions CGP already ships. - **Write a [`TransformMap`](./transform_map.md) marker and apply it here** for a conversion they do not cover. -- **Use [`UpdateField`](./update_field.md)** when a *single* field changes state. This trait is the +- **Use [`UpdateField`](../builder/update_field.md)** when a *single* field changes state. This trait is the whole-record form, and reaching for it to change one field walks every other field for nothing. - **Use [`MapFields`](./map_fields.md)** when you only need to *name* the re-marked shape as a type. That trait computes the type; this one converts the values. ## Under the hood -`TransformMapFields` walks the target's [`HasFields`](./has_fields.md) product one entry at a time. For -each `Field` it uses [`UpdateField`](./update_field.md) **twice**: it takes the field out — +`TransformMapFields` walks the target's [`HasFields`](../shape/has_fields.md) product one entry at a time. For +each `Field` it uses [`UpdateField`](../builder/update_field.md) **twice**: it takes the field out — replacing its marker with `IsNothing` and reading what the marker *was* — applies `Transform::transform_mapped` to convert the value into the `TargetMap` wrapping, then writes it back under `TargetMap`. @@ -128,29 +134,29 @@ impl for one field's source marker, not the record, so it reads as being about a about the transform being incomplete. **`Output` is a partial type, not the finished struct.** Finalizing is still -[`FinalizeBuild`](./finalize_build.md)'s job — this trait only guarantees the configuration that impl +[`FinalizeBuild`](../builder/finalize_build.md)'s job — this trait only guarantees the configuration that impl requires. -**It walks every field.** For a single field's transition, [`UpdateField`](./update_field.md) is the +**It walks every field.** For a single field's transition, [`UpdateField`](../builder/update_field.md) is the right tool. **It is [`MapFields`](./map_fields.md)'s value-level counterpart, and they are easy to confuse.** That one computes a type; this one converts values and needs a transform to do it. -**It requires [`PartialData`](./partial_data.md).** A plain struct is not a partial value; obtain one -with [`HasBuilder`](./has_builder.md) or [`IntoBuilder`](./into_builder.md) first. +**It requires [`PartialData`](../builder/partial_data.md).** A plain struct is not a partial value; obtain one +with [`HasBuilder`](../builder/has_builder.md) or [`IntoBuilder`](../builder/into_builder.md) first. ## Related constructs - [`TransformMap`](./transform_map.md) — the per-field conversion this lifts. - [`MapType`](./map_type.md) — the markers naming each state. -- [`UpdateField`](./update_field.md) — the primitive the walk calls twice per field. -- [`PartialData`](./partial_data.md) — what a partial value is, and the bound this requires. -- [`FinalizeBuild`](./finalize_build.md) — what an all-`IsPresent` result is accepted by. -- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) and [`ToOptional`](./to_optional.md) — the +- [`UpdateField`](../builder/update_field.md) — the primitive the walk calls twice per field. +- [`PartialData`](../builder/partial_data.md) — what a partial value is, and the bound this requires. +- [`FinalizeBuild`](../builder/finalize_build.md) — what an all-`IsPresent` result is accepted by. +- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and [`ToOptional`](../optional/to_optional.md) — the two capabilities built directly on this. - [`MapFields`](./map_fields.md) — the type-level counterpart. -- [`HasFields`](./has_fields.md) — the shape the walk follows. +- [`HasFields`](../shape/has_fields.md) — the shape the walk follows. The ideas behind it: diff --git a/docs/reference/traits/variant/_category_.json b/docs/reference/traits/variant/_category_.json new file mode 100644 index 00000000..a0cb89c2 --- /dev/null +++ b/docs/reference/traits/variant/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Extensible variants", + "position": 6, + "link": { + "type": "doc", + "id": "reference/traits/variant/index" + } +} diff --git a/docs/reference/traits/extract_field.md b/docs/reference/traits/variant/extract_field.md similarity index 69% rename from docs/reference/traits/extract_field.md rename to docs/reference/traits/variant/extract_field.md index 30e6d58e..822cdc5f 100644 --- a/docs/reference/traits/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -1,5 +1,6 @@ --- sidebar_label: 'ExtractField' +sidebar_position: 1 --- # `ExtractField` @@ -9,11 +10,25 @@ Pulling one variant out of an extractor, or narrowing what remains. ## Overview A `match` on a concrete enum is checked for exhaustiveness. Code that is generic over the enum cannot -write one, so it falls back on a wildcard arm and an `unreachable!()` — losing exactly the guarantee you +write one, so it falls back on a wildcard arm and an `unreachable!()`, losing exactly the guarantee you wanted. `ExtractField` is the operation that recovers it. Each attempt either yields the payload or hands back a -*remainder* whose type has that variant ruled out: +*remainder* whose type has that variant ruled out, and **the impl exists only while the requested variant +is still possible**, so attempting the same variant twice is a compile error rather than a guaranteed +miss. + +Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** — +a value of it cannot exist — and [`FinalizeExtract`](./finalize_extract.md) closes the chain with +no wildcard and no panic path. Add a variant to the enum and the final remainder becomes inhabited again, +so the code stops compiling until it is handled. + +The family is the mirror of the [builder](../builder/has_builder.md): a builder tracks which fields are *present*, +an extractor tracks which variants are still *possible*. + +## Definition + +`ExtractField` takes one variant, named by a type-level tag, out of an extractor: ```rust pub trait ExtractField { @@ -24,17 +39,11 @@ pub trait ExtractField { } ``` -`Ok` carries the payload; `Err` carries the same extractor with this one variant ruled out. **The impl -exists only while the requested variant is still possible**, so attempting the same variant twice is a -compile error rather than a guaranteed miss. - -Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** — -a value of it cannot exist — and [`FinalizeExtract`](./finalize_extract.md) is what closes the chain with -no wildcard and no panic path. Add a variant to the enum and the final remainder becomes inhabited again, -so the code stops compiling until it is handled. - -The family is the mirror of the [builder](./has_builder.md): a builder tracks which fields are *present*, -an extractor tracks which variants are still *possible*. +`Self` is an extractor rather than the enum. `Tag` is the variant's name as a +[`Symbol!`](../../macros/symbol.md), `Value` is that variant's payload type, and `Remainder` is the same +extractor with this one variant ruled out. `extract_field` consumes the extractor and takes a +`PhantomData` to name the variant, returning `Ok(value)` when the runtime value is that variant and +`Err(remainder)` when it is not. ## Usage @@ -45,11 +54,11 @@ an extractor tracks which variants are still *possible*. borrow it, or [`extractor_mut`](./has_extractor_mut.md) to borrow it mutably. Which one you pick decides whether the payloads come out owned, shared, or mutable; the narrowing is identical in all three. -The `PhantomData` argument names the variant, keyed by [`Symbol!`](../macros/symbol.md) of its name. +The `PhantomData` argument names the variant, keyed by [`Symbol!`](../../macros/symbol.md) of its name. -The impls come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md), also available -through [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) and -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). +The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md), also available +through [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) and +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md). ## Examples @@ -81,11 +90,11 @@ fn area(shape: Shape) -> f64 { ``` After the second extraction both variants are ruled out, so the remainder's type is uninhabited and the -finalize is accepted with no wildcard arm. That is not a convention — it is the type. Try to finalize +finalize is accepted with no wildcard arm. That is not a convention but the type. Try to finalize after only the first extraction and it does not compile. **In practice you rarely write these chains.** The -[dispatch combinators](../providers/dispatch/index.md) build them from a set of per-variant +[dispatch combinators](../../providers/dispatch/index.md) build them from a set of per-variant implementations, which is the extensible visitor pattern: a chain exactly like the one above, generated, with one implementation per variant chosen by wiring. @@ -93,7 +102,7 @@ with one implementation per variant chosen by wiring. **Reach for the family when independent code handles one variant each, or when the matching code cannot name the enum.** Outside those two cases a `match` wins on every count: shorter, clearer, already -exhaustive, and it generates nothing. This is not an improvement on `match`; it is what you use where +exhaustive, and it generates nothing. This is not an improvement on `match`; you reach for it only where `match` is unavailable. - **Bound on [`HasExtractor`](./has_extractor.md) + `ExtractField`** to write a routine that @@ -104,17 +113,17 @@ exhaustive, and it generates nothing. This is not an improvement on `match`; it [`to_extractor`](./has_extractor.md) only when you genuinely want to consume. - **Do not use it to test which variant a value holds.** `matches!` or an `if let` answers that in a line. The family's value is in the *chain* and what the chain proves. -- **Reach for the [dispatch combinators](../providers/dispatch/index.md) rather than writing the - chain**, since they derive it from the enum's own variant list instead of repeating it at each site — - which is what keeps "add a variant" from breaking every call site by hand. +- **Reach for the [dispatch combinators](../../providers/dispatch/index.md) rather than writing the + chain**, since they derive it from the enum's own variant list instead of repeating it at each site, + which keeps "add a variant" from breaking every call site by hand. The construction counterpart is [`FromVariant`](./from_variant.md), and the two are commonly wanted together because a generic pipeline usually takes a value apart and puts one back. The struct analogue of -the whole family is [`HasBuilder`](./has_builder.md). +the whole family is [`HasBuilder`](../builder/has_builder.md). ## Under the hood -The derive generates a companion enum with one [`MapType`](./map_type.md) parameter per variant, each +The derive generates a companion enum with one [`MapType`](../type-level/map_type.md) parameter per variant, each payload wrapped in that parameter's projection: ```rust @@ -126,17 +135,17 @@ pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { [`to_extractor`](./has_extractor.md) starts at the all-`IsPresent` configuration, where every variant is still possible. **Each `extract_field` impl is in scope only while its variant's marker is `IsPresent`**; -on a miss it returns the remainder with that one marker flipped to `IsVoid`, leaving the rest generic — +on a miss it returns the remainder with that one marker flipped to `IsVoid`, leaving the rest generic, which is why extractions may happen in any order. -That per-variant scoping is the mirror of [`BuildField`](./build_field.md)'s requirement that a field be -`IsNothing` before it can be set, and it is what makes a repeated attempt a compile error rather than a +That per-variant scoping is the mirror of [`BuildField`](../builder/build_field.md)'s requirement that a field be +`IsNothing` before it can be set, and it makes a repeated attempt a compile error rather than a guaranteed `Err`. The exhaustiveness argument itself belongs to [`FinalizeExtract`](./finalize_extract.md), and turns on `IsVoid` mapping a payload to the uninhabited `Void`. -The borrowed accessors use the same partial enum with an extra [`MapTypeRef`](./map_type_ref.md) +The borrowed accessors use the same partial enum with an extra [`MapTypeRef`](../type-level/map_type_ref.md) parameter fixed to `IsRef` or `IsMut`, so a value can be matched without being moved and the narrowing works identically. @@ -152,17 +161,17 @@ applies, reported as a missing method. naming the wrong one usually means record and variant machinery have been crossed. **A remainder carries none of the enum's attributes.** The partial enums are generated without your -derives, so a `Result` is neither `Debug` nor `PartialEq` however the enum is derived -— `assert_eq!` on the whole result does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. +derives, so a `Result` is neither `Debug` nor `PartialEq` however the enum is derived, +and `assert_eq!` on the whole result does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. **Order is free but the set is not.** Each step changes only its own variant's marker, so extractions may -be written in any order — but every variant must be tried before the remainder can be finalized. +be written in any order, but every variant must be tried before the remainder can be finalized. **Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the -reason to prefer the [dispatch combinators](../providers/dispatch/index.md). +reason to prefer the [dispatch combinators](../../providers/dispatch/index.md). **Five enum variant names are reserved**, because the generated impls name their associated types through -`Self::…`. The [derive's page](../derives/derive_extract_field.md) lists them. +`Self::…`. The [derive's page](../../derives/derive_extract_field.md) lists them. ## Related constructs @@ -171,15 +180,15 @@ reason to prefer the [dispatch combinators](../providers/dispatch/index.md). - [`FinalizeExtract`](./finalize_extract.md) and [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. - [`FromVariant`](./from_variant.md) — the construction counterpart. -- [`HasBuilder`](./has_builder.md) — the struct analogue of the whole family. -- [`MapType`](./map_type.md) — the `IsPresent`/`IsVoid` markers, and where the contrast with `IsNothing` +- [`HasBuilder`](../builder/has_builder.md) — the struct analogue of the whole family. +- [`MapType`](../type-level/map_type.md) — the `IsPresent`/`IsVoid` markers, and where the contrast with `IsNothing` is explained. -- [`CanDowncast`](./can_downcast.md) — narrowing to another enum rather than to a payload, built on this. -- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the partial enums and every +- [`CanDowncast`](../casting/can_downcast.md) — narrowing to another enum rather than to a payload, built on this. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the partial enums and every impl here. -- [Dispatch combinators](../providers/dispatch/index.md) — the providers that build the chain for +- [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain for you. -- [Type-level spines](../types/type_level_spines.md) — `Either`/`Void`, where the uninhabited terminator +- [Type-level spines](../../types/type_level_spines.md) — `Either`/`Void`, where the uninhabited terminator comes from. The ideas behind it: diff --git a/docs/reference/traits/finalize_extract.md b/docs/reference/traits/variant/finalize_extract.md similarity index 72% rename from docs/reference/traits/finalize_extract.md rename to docs/reference/traits/variant/finalize_extract.md index 43f6dc2d..8b800fed 100644 --- a/docs/reference/traits/finalize_extract.md +++ b/docs/reference/traits/variant/finalize_extract.md @@ -1,5 +1,6 @@ --- sidebar_label: 'FinalizeExtract' +sidebar_position: 5 --- # `FinalizeExtract` @@ -9,8 +10,18 @@ Discharging an extractor that has nothing left in it. ## Overview An [extraction chain](./extract_field.md) 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` is what turns -that fact into a usable ending: +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, because there is no value to return it from: +the method can only be called on something that cannot exist, so its body is an empty `match` and no +execution path reaches it. + +That closes a generic match with **no wildcard arm and no `unreachable!()`**. It is the mirror of +[`FinalizeBuild`](../builder/finalize_build.md), and the two are sound for opposite reasons: a build finalizes +because the value is *complete*, an extraction because the value is *impossible*. + +## Definition ```rust pub trait FinalizeExtract { @@ -18,27 +29,21 @@ pub trait FinalizeExtract { } ``` -**It returns *any* type.** That looks unsound and is not, because there is no value to return it from: -the method can only be called on something that cannot exist, so its body is an empty `match` and no -execution path reaches it. - -That is what closes a generic match with **no wildcard arm and no `unreachable!()`**. It is the mirror of -[`FinalizeBuild`](./finalize_build.md), and the two are sound for opposite reasons: a build finalizes -because the value is *complete*, an extraction because the value is *impossible*. +`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 trait is implemented for the uninhabited +[`Void`](../../types/type_level_spines.md), the standard `Infallible`, and the all-ruled-out +configuration of a partial enum. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -It is implemented for three things: the uninhabited [`Void`](../types/type_level_spines.md), the standard -`Infallible`, and the all-ruled-out configuration of a partial enum. Anything holding one of those can be -discharged. - **You will usually call [`FinalizeExtractResult`](./finalize_extract_result.md) 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 come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md). +The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md). ## Examples @@ -59,7 +64,7 @@ match shape.to_extractor().extract_field(PhantomData::) { The last arm returns whatever the surrounding `match` needs, and the compiler accepts it because the value being matched cannot exist. -The same chain written with the `Result` helper is shorter and is what most code uses: +The same chain written with the `Result` helper is shorter and is the form most code uses: ```rust use cgp::core::field::traits::FinalizeExtractResult; @@ -78,15 +83,15 @@ remainder.** The two do the same job at different points in the chain. `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](../providers/dispatch/index.md)** rather than writing the chain at - all — they generate it from the enum's variant list, which is what stops "add a variant" from breaking +- **The [dispatch combinators](../../providers/dispatch/index.md)** 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`](./map_type.md) marker `IsVoid` maps a -payload to the uninhabited [`Void`](../types/type_level_spines.md), so once every variant's marker is +**Everything turns on what `IsVoid` maps to.** The [`MapType`](../type-level/map_type.md) marker `IsVoid` maps a +payload to the uninhabited [`Void`](../../types/type_level_spines.md), 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: @@ -103,11 +108,11 @@ An empty `match` is legal precisely because no value of the scrutinee's type can any return type for the same reason. So a caller reaches `finalize_extract` only after trying every variant, and the compiler accepts the discharge with no fallback. -**This is where the record and variant families diverge, and the difference is load-bearing.** A record +**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 exactly why a builder needs an explicit all-present -[`FinalizeBuild`](./finalize_build.md) impl while an extractor can discharge its remainder with an empty +[`FinalizeBuild`](../builder/finalize_build.md) impl while an extractor can discharge its remainder with an empty `match`. ## Common Mistakes @@ -124,7 +129,7 @@ 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](../providers/dispatch/index.md). +[dispatch combinators](../../providers/dispatch/index.md). **It also covers `Infallible`**, which is occasionally useful when threading a chain through an error type that cannot occur. @@ -136,12 +141,12 @@ that cannot occur. - [`FinalizeExtractResult`](./finalize_extract_result.md) — the form that closes a chain from a `Result`. - [`ExtractField`](./extract_field.md) — the narrowing that leads here. - [`HasExtractor`](./has_extractor.md) — where a chain begins. -- [`FinalizeBuild`](./finalize_build.md) — the record family's ending, sound for the opposite reason. -- [`MapType`](./map_type.md) — the `IsVoid` marker the argument rests on. -- [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. -- [`CanUpcast`](./can_upcast.md) — a cast whose total walk ends with this same discharge. -- [Dispatch combinators](../providers/dispatch/index.md) — the providers that build the chain. -- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates this impl. +- [`FinalizeBuild`](../builder/finalize_build.md) — the record family's ending, sound for the opposite reason. +- [`MapType`](../type-level/map_type.md) — the `IsVoid` marker the argument rests on. +- [Type-level spines](../../types/type_level_spines.md) — where the uninhabited `Void` comes from. +- [`CanUpcast`](../casting/can_upcast.md) — a cast whose total walk ends with this same discharge. +- [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates this impl. The ideas behind it: diff --git a/docs/reference/traits/finalize_extract_result.md b/docs/reference/traits/variant/finalize_extract_result.md similarity index 76% rename from docs/reference/traits/finalize_extract_result.md rename to docs/reference/traits/variant/finalize_extract_result.md index 901dd24d..12fa335f 100644 --- a/docs/reference/traits/finalize_extract_result.md +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -1,5 +1,6 @@ --- sidebar_label: 'FinalizeExtractResult' +sidebar_position: 6 --- # `FinalizeExtractResult` @@ -10,7 +11,15 @@ Collapsing the `Result` at the end of an extraction chain. Every step of an [extraction chain](./extract_field.md) 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` is what says so: +happen, and `FinalizeExtractResult` says so. + +**This is the one you actually call.** [`FinalizeExtract`](./finalize_extract.md) 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: ```rust pub trait FinalizeExtractResult { @@ -20,8 +29,8 @@ pub trait FinalizeExtractResult { } ``` -`Self` is the `Result`, and `Output` is the payload alone. It is implemented for any `Result` whose -error half can be discharged: +`Self` is the `Result` and `Output` is the payload alone. The trait has one blanket impl, for any +`Result` whose error half can be discharged: ```rust impl FinalizeExtractResult for Result @@ -33,14 +42,13 @@ where } ``` -**This is the one you actually call.** [`FinalizeExtract`](./finalize_extract.md) 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. +`finalize_extract_result` returns the `Ok` value directly and discharges the `Err` half through +[`FinalizeExtract`](./finalize_extract.md), 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 is what closes a chain: +`cgp::core::field::traits`, and you will want it, because it closes a chain: ```rust use cgp::core::field::traits::FinalizeExtractResult; @@ -77,7 +85,7 @@ fn area(shape: Shape) -> f64 { ``` No `.unwrap()`, no `expect`, and no wildcard arm. The call compiles only because both variants have been -tried, which is what makes it a proof rather than an assertion. +tried, which makes it a proof rather than an assertion. Calling it one step early does not compile: @@ -98,8 +106,8 @@ let rect = shape holding a `Result`. - **[`FinalizeExtract`](./finalize_extract.md)** when a nested `match` has already unwrapped the remainder out of its `Result`. -- **The [dispatch combinators](../providers/dispatch/index.md)** rather than a hand-written chain, - since they generate it from the enum's own variant list — which is what keeps "add a variant" from +- **The [dispatch combinators](../../providers/dispatch/index.md)** 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 a `match`** when you are making a single attempt and do not intend to exhaust the enum. Reaching for this trait then simply will not resolve. @@ -108,26 +116,26 @@ let rect = shape ## Under the hood The impl delegates to [`FinalizeExtract`](./finalize_extract.md) on the error half, which is where the -soundness argument lives — the remainder is uninhabited once every variant is `IsVoid`, so the `Err` arm +soundness argument lives: 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`](../types/type_level_spines.md). That is occasionally useful +whose error is `Infallible` or [`Void`](../../types/type_level_spines.md). That is occasionally useful outside the extractor family, for collapsing a `Result` that a signature required but that cannot fail. -`Output` being an associated type rather than a generic is what lets the call sit at the end of a method +`Output` being an associated type rather than a generic lets the call 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 it there is no -`finalize_extract_result` in scope and the chain has no clean ending — and the error is a +`finalize_extract_result` in scope and the chain has no clean ending, and the error is a missing-method one, which reads as though the chain is wrong rather than the import missing. **Calling it early does not compile.** Any variant still possible leaves the remainder inhabited and the bound unsatisfied. -**It discards nothing and cannot panic.** Unlike `.unwrap()`, there is no runtime branch — the `Err` case +**It discards nothing and cannot panic.** Unlike `.unwrap()`, there is no runtime branch: 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 @@ -142,11 +150,11 @@ bound stops being satisfied. argument. - [`ExtractField`](./extract_field.md) — the narrowing that produces the `Result` this collapses. - [`HasExtractor`](./has_extractor.md) — where a chain begins. -- [`FinalizeBuild`](./finalize_build.md) — the record family's ending. -- [Type-level spines](../types/type_level_spines.md) — where the uninhabited `Void` comes from. -- [Dispatch combinators](../providers/dispatch/index.md) — the providers that build the chain for +- [`FinalizeBuild`](../builder/finalize_build.md) — the record family's ending. +- [Type-level spines](../../types/type_level_spines.md) — where the uninhabited `Void` comes from. +- [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain for you. -- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — what makes an enum extractable. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — what makes an enum extractable. The ideas behind it: diff --git a/docs/reference/traits/from_variant.md b/docs/reference/traits/variant/from_variant.md similarity index 70% rename from docs/reference/traits/from_variant.md rename to docs/reference/traits/variant/from_variant.md index dfdc7a6a..1fd376fc 100644 --- a/docs/reference/traits/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -1,5 +1,6 @@ --- sidebar_label: 'FromVariant' +sidebar_position: 7 --- # `FromVariant` @@ -23,13 +24,14 @@ That call is exactly `Shape::Circle(circle)`. The difference is that the tag can one function can build whichever variant it was asked for, on whatever enum implements the trait for that tag. **This is the smallest trait in the extensible-data family.** There is no companion type, no state, and nothing -to track — building a single variant has no intermediate states. It is the construction counterpart to +to track, because building a single variant has no intermediate states. It is the construction counterpart to [`ExtractField`](./extract_field.md)'s deconstruction, and the impls come from -[`#[derive(FromVariant)]`](../derives/derive_from_variant.md), one per variant. +[`#[derive(FromVariant)]`](../../derives/derive_from_variant.md), one per variant. -## Usage +## Definition -The trait is in the prelude. It carries the payload type as an associated `Value` and one associated function: +`FromVariant` carries the variant's payload type as an associated `Value` and one associated +function: ```rust pub trait FromVariant { @@ -39,17 +41,23 @@ pub trait FromVariant { } ``` -`Tag` is the variant's name as a [`Symbol!`](../macros/symbol.md) type-level string, `Value` is that variant's -payload type, and `from_variant` wraps a payload into the enum. The `PhantomData` argument carries no -data; it exists so a caller can pick which variant to build when several impls — one per variant — are in scope -on the same enum. +`Self` is the enum. `Tag` is the variant's name as a [`Symbol!`](../../macros/symbol.md) type-level +string, and `Value` is that variant's payload type. `from_variant` wraps a payload into the enum as the +chosen variant. The `PhantomData` argument carries no data; it lets a caller pick which variant to +build when several impls, one per variant, are in scope on the same enum. Because the trait is +implemented once per variant, each impl fixing its own `Tag` and `Value`, choosing the impl **is** +choosing the variant. + +## Usage -The trait is implemented once per variant, each impl fixing its own `Tag` and `Value`, so **choosing the impl -*is* choosing the variant**. +The trait is in the prelude, so `use cgp::prelude::*;` names it. You rarely write a `FromVariant` impl +yourself: the derive supplies one per variant, and you either call +`T::from_variant(PhantomData::, value)` at a concrete site or bound on the trait in +code generic over the tag. ### Naming the payload type generically -The associated `Value` is what makes a generic signature possible: a function that does not know the variant +The associated `Value` makes a generic signature possible: a function that does not know the variant still needs to name the type it takes. Project it through the trait: ```rust @@ -105,10 +113,10 @@ use cgp::core::field::impls::CanUpcast; let ident = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); ``` -The upcast always succeeds, because every variant of the smaller enum has a home in the larger one — and it is -`FromVariant` that rebuilds each variant into the target. That is the construction-side counterpart of reading +The upcast always succeeds, because every variant of the smaller enum has a home in the larger one, and +`FromVariant` rebuilds each variant into the target. That is the construction-side counterpart of reading a field through a getter: the implementation names only what it needs, and the widening is checked. -Upcasting is documented with the other [structural casts](./can_upcast.md). +Upcasting is documented with the other [structural casts](../casting/can_upcast.md). ## When to use it @@ -118,16 +126,16 @@ simply name it. - **Bound on it in a routine parameterized over the variant it produces.** There is no alternative. - **Derive it to make a smaller enum upcastable into a larger one.** Casting between enums is built on these - constructors, so this is what lets an implementation work in a narrow local enum and widen the result. + constructors, so this lets an implementation work in a narrow local enum and widen the result. - **Do not reach for it for an ordinary constructor call.** `Shape::Circle(circle)` is shorter, clearer, and generates nothing. The trait adds a *second* way to do the same thing, for callers that cannot use the first. -- **Do not derive it alone if you also take the enum apart**, which is the usual case — reach for - [`#[derive(CgpData)]`](../derives/derive_cgp_data.md), which bundles construction, deconstruction, and the +- **Do not derive it alone if you also take the enum apart**, which is the usual case; reach for + [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md), which bundles construction, deconstruction, and the shape. -The split with its counterpart is exactly what the names say: this trait puts a value *into* an enum, +The names capture the split exactly: this trait puts a value *into* an enum, [`ExtractField`](./extract_field.md) gets one *out*. For structs, the analogous field-setting primitive is -[`BuildField`](./has_builder.md). +[`BuildField`](../builder/has_builder.md). ## Under the hood @@ -153,7 +161,7 @@ impl FromVariant for Shape { Each body is the plain constructor call, and there is no intermediate type, no marker, and no validation beyond the type system's own check that the payload matches. Because the impls are distinguished *only* by their `Tag` -parameter, resolving a `from_variant` call comes down to which `Symbol!` the caller names — the compiler picks +parameter, resolving a `from_variant` call comes down to which `Symbol!` the caller names: the compiler picks the matching impl and inlines it to the corresponding constructor. So the generic call costs exactly what the concrete one does. @@ -174,24 +182,24 @@ point, and it means a mistyped tag is a missing-impl error rather than a type mi case slip reports as an unsatisfied `FromVariant` bound. **A variant named `Value` does not compile**, because the generated signature names the payload as -`Self::Value`. The [derive's page](../derives/derive_from_variant.md) covers this with the family's other +`Self::Value`. The [derive's page](../../derives/derive_from_variant.md) covers this with the family's other reserved names. -**Every variant needs exactly one unnamed payload**, which is the derive's requirement rather than the trait's — +**Every variant needs exactly one unnamed payload**, which is the derive's requirement rather than the trait's: a unit, multi-field, or struct-style variant cannot be given a single `Value`. Wrap the payload in its own struct. ## Related constructs -- [`#[derive(FromVariant)]`](../derives/derive_from_variant.md) — generates the per-variant impls; what you +- [`#[derive(FromVariant)]`](../../derives/derive_from_variant.md) — generates the per-variant impls; what you write. - [`ExtractField`](./extract_field.md) — the reverse operation, and the trait most often derived alongside. -- [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — bundles this with the extractor and the shape. -- [`HasBuilder`](./has_builder.md) — the struct analogue: setting one field rather than choosing one variant. -- [`Symbol!`](../macros/symbol.md) — the tag that names a variant. -- [`CanUpcast`](./can_upcast.md) — widening a narrow enum into a wider one, built on these constructors. -- [`HasFields`](./has_fields.md) — the variant shape a cast walks while rebuilding. -- [Dispatch combinators](../providers/dispatch/index.md) — where variant construction meets routing. +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — bundles this with the extractor and the shape. +- [`HasBuilder`](../builder/has_builder.md) — the struct analogue: setting one field rather than choosing one variant. +- [`Symbol!`](../../macros/symbol.md) — the tag that names a variant. +- [`CanUpcast`](../casting/can_upcast.md) — widening a narrow enum into a wider one, built on these constructors. +- [`HasFields`](../shape/has_fields.md) — the variant shape a cast walks while rebuilding. +- [Dispatch combinators](../../providers/dispatch/index.md) — where variant construction meets routing. The ideas behind it: diff --git a/docs/reference/traits/has_extractor.md b/docs/reference/traits/variant/has_extractor.md similarity index 68% rename from docs/reference/traits/has_extractor.md rename to docs/reference/traits/variant/has_extractor.md index 7a78b0ff..7e02a1b8 100644 --- a/docs/reference/traits/has_extractor.md +++ b/docs/reference/traits/variant/has_extractor.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasExtractor' +sidebar_position: 2 --- # `HasExtractor` @@ -9,7 +10,18 @@ Turning an enum into an extractor, and back. ## Overview [`ExtractField`](./extract_field.md) narrows an *extractor*, not an enum. `HasExtractor` is where one -comes from: +comes from. It is the owning member of a group of three, and choosing between them is most of using the +extractor family: + +| | payloads come out as | the original | +|---|---|---| +| `HasExtractor` | owned | consumed | +| [`HasExtractorRef`](./has_extractor_ref.md) | `&T` | survives | +| [`HasExtractorMut`](./has_extractor_mut.md) | `&mut T` | survives, mutably borrowed | + +## Definition + +`HasExtractor` converts an enum into an extractor, and back: ```rust pub trait HasExtractor { @@ -20,34 +32,26 @@ pub trait HasExtractor { } ``` -`to_extractor` **consumes** the value and yields an extractor whose payloads are owned, which is what a -chain needs when it will take a payload away. `from_extractor` reverses it, rebuilding the enum from an -extractor that was not narrowed — useful when a routine inspects a value and hands it back unchanged. - -It is the owning member of a group of three, and choosing between them is most of using the extractor -family: - -| | payloads come out as | the original | -|---|---|---| -| `HasExtractor` | owned | consumed | -| [`HasExtractorRef`](./has_extractor_ref.md) | `&T` | survives | -| [`HasExtractorMut`](./has_extractor_mut.md) | `&mut T` | survives, mutably borrowed | +`Self` is the enum. `Extractor` is the partial companion enum at its all-possible configuration, with +every variant still available. `to_extractor` **consumes** the value and yields an extractor whose +payloads are owned, which a chain needs when it will take a payload away. `from_extractor` reverses it, +rebuilding the enum from an extractor that was not narrowed, which is useful when a routine inspects a +value and hands it back unchanged. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -`Extractor` names the partial companion enum at its all-possible configuration — every variant still -available. That is the type a chain starts from, and the type that appears in an error when a chain is +The `Extractor` type is where a chain starts, and the type that appears in an error when a chain is finalized too early. -The impls come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md), also available -through [`#[derive(CgpVariant)]`](../derives/derive_cgp_variant.md) and -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md). +The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md), also available +through [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) and +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md). ## Examples -Starting a chain, which is what `to_extractor` is for: +Starting a chain, which is `to_extractor`'s job: ```rust use cgp::core::field::traits::FinalizeExtractResult; @@ -86,20 +90,20 @@ been ruled out the type has changed, and there is no way back. ## When to use it **Reach for `to_extractor` only when the chain will take payloads by value**, and prefer a borrowing -accessor otherwise — the weakest that works is the right one. +accessor otherwise; the weakest that works is the right one. - **[`HasExtractorRef`](./has_extractor_ref.md)** for a read-only operation over a value you do not own. This is the common case, and requiring ownership where a borrow would do forces callers to clone or give up their value. - **[`HasExtractorMut`](./has_extractor_mut.md)** to change a payload in place. -- **`HasExtractor`** when the payload must be moved out — returned, stored, or handed on by value. +- **`HasExtractor`** when the payload must be moved out: returned, stored, or handed on by value. - **A `match`** when the enum is concrete. The family is for code that cannot name it. -- **The [dispatch combinators](../providers/dispatch/index.md)** rather than a hand-written chain, +- **The [dispatch combinators](../../providers/dispatch/index.md)** rather than a hand-written chain, since they derive it from the enum's variant list. ## Under the hood -The derive generates a companion enum with one [`MapType`](./map_type.md) parameter per variant, and this +The derive generates a companion enum with one [`MapType`](../type-level/map_type.md) parameter per variant, and this trait fixes the starting configuration to all-possible: ```rust @@ -118,8 +122,8 @@ Because `IsPresent::Map` is `T`, the all-possible companion holds exactly the `to_extractor` is a variant-for-variant move rather than a wrapping, and `from_extractor` is the same move back. -The companion also implements [`PartialData`](./partial_data.md), with `Target` naming the original enum -— which is how `from_extractor` knows what to rebuild, and the one trait the builder and extractor +The companion also implements [`PartialData`](../builder/partial_data.md), with `Target` naming the original enum, +which is how `from_extractor` knows what to rebuild, and the one trait the builder and extractor families share directly. Narrowing from here is [`ExtractField`](./extract_field.md), and the chain ends at @@ -131,7 +135,7 @@ Narrowing from here is [`ExtractField`](./extract_field.md), and the chain ends survive. This is the commonest over-requirement in the family. **`from_extractor` only accepts an un-narrowed extractor.** Once a variant is ruled out the type is -different and there is no rebuild — which is correct, since the value may no longer be representable. +different and there is no rebuild, which is correct, since the value may no longer be representable. **The extractor carries none of the enum's attributes.** The companion is generated without your derives, so it is neither `Debug` nor `PartialEq` however the enum is derived. @@ -141,7 +145,7 @@ type, and naming it in a public API exposes a generated name. **Every variant must carry exactly one unnamed payload** for the derive to apply at all — the family's one real restriction, covered on the -[derive's page](../derives/derive_extract_field.md). +[derive's page](../../derives/derive_extract_field.md). ## Related constructs @@ -151,12 +155,12 @@ one real restriction, covered on the - [`FinalizeExtract`](./finalize_extract.md) and [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. - [`FromVariant`](./from_variant.md) — constructing an enum from one named variant. -- [`PartialData`](./partial_data.md) — what names the enum a companion belongs to. -- [`MapType`](./map_type.md) — the `IsPresent`/`IsVoid` markers the companion is parameterized by. -- [`CanUpcast`](./can_upcast.md) and [`CanDowncast`](./can_downcast.md) — casts built on this recursion. -- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the companion and this +- [`PartialData`](../builder/partial_data.md) — what names the enum a companion belongs to. +- [`MapType`](../type-level/map_type.md) — the `IsPresent`/`IsVoid` markers the companion is parameterized by. +- [`CanUpcast`](../casting/can_upcast.md) and [`CanDowncast`](../casting/can_downcast.md) — casts built on this recursion. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the companion and this impl. -- [`HasBuilder`](./has_builder.md) — the struct analogue. +- [`HasBuilder`](../builder/has_builder.md) — the struct analogue. The ideas behind it: diff --git a/docs/reference/traits/has_extractor_mut.md b/docs/reference/traits/variant/has_extractor_mut.md similarity index 74% rename from docs/reference/traits/has_extractor_mut.md rename to docs/reference/traits/variant/has_extractor_mut.md index a2416782..81cdee6f 100644 --- a/docs/reference/traits/has_extractor_mut.md +++ b/docs/reference/traits/variant/has_extractor_mut.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasExtractorMut' +sidebar_position: 4 --- # `HasExtractorMut` @@ -9,20 +10,10 @@ Obtaining an extractor that can change a payload in place. ## Overview [`HasExtractorRef`](./has_extractor_ref.md) borrows an enum so its variants can be read without consuming -it. `HasExtractorMut` borrows it mutably, so a payload can be **changed in place**: - -```rust -pub trait HasExtractorMut { - type ExtractorMut<'a> - where - Self: 'a; - - fn extractor_mut(&mut self) -> Self::ExtractorMut<'_>; -} -``` +it. `HasExtractorMut` borrows it mutably, so a payload can be **changed in place**. Payloads come out as `&mut T`. The original survives, mutably borrowed for the duration, and the -narrowing works exactly as it does for the other two accessors — [`ExtractField`](./extract_field.md) +narrowing works exactly as it does for the other two accessors: [`ExtractField`](./extract_field.md) does not care how the payloads are held. It is the third of the group, and the one to reach for least often: @@ -33,15 +24,31 @@ It is the third of the group, and the one to reach for least often: | [`HasExtractorRef`](./has_extractor_ref.md) | `&T` | survives | | `HasExtractorMut` | `&mut T` | survives, mutably borrowed | +## Definition + +`HasExtractorMut` produces a mutably-borrowing extractor: + +```rust +pub trait HasExtractorMut { + type ExtractorMut<'a> + where + Self: 'a; + + fn extractor_mut(&mut self) -> Self::ExtractorMut<'_>; +} +``` + +`Self` is the enum. `ExtractorMut<'a>` is a **generic associated type**: the borrowed extractor over the +same partial companion enum, with every payload held as a mutable reference for `'a`. The `where Self: +'a` clause keeps it from outliving the value. `extractor_mut` takes a mutable borrow and returns the +extractor at the anonymous lifetime, so the call reads with no lifetime written and the borrow ends where +the extractor is dropped. + ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -`ExtractorMut<'a>` is a **generic associated type** with a `where Self: 'a` clause, and -`extractor_mut(&mut self)` returns one at the anonymous lifetime — so the call reads with no lifetime -written, and the borrow ends where the extractor is dropped. - -The impls come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md), alongside the owning +The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md), alongside the owning and shared-borrow accessors. ## Examples @@ -81,12 +88,12 @@ The payload arrives as `&mut Circle`, so the write lands in the original value. - **A `match` on `&mut`** when the enum is concrete. `if let Shape::Circle(c) = &mut shape` does this in a line, and the family is for code that cannot name the enum. - **Consider returning a new value instead.** Much CGP code threads state through handler outputs rather - than mutating in place, which composes better with the [handler family](../components/handler/handler.md). + than mutating in place, which composes better with the [handler family](../../components/handler/handler.md). ## Under the hood It uses the **same borrowed companion** as [`HasExtractorRef`](./has_extractor_ref.md#under-the-hood), -with the outer [`MapTypeRef`](./map_type_ref.md) marker fixed to `IsMut` rather than `IsRef`: +with the outer [`MapTypeRef`](../type-level/map_type_ref.md) marker fixed to `IsMut` rather than `IsRef`: ```rust // impl HasExtractorMut for Shape { @@ -95,10 +102,11 @@ with the outer [`MapTypeRef`](./map_type_ref.md) marker fixed to `IsMut` rather ``` Since `IsMut::Map<'a, T>` is `&'a mut T`, every payload slot becomes a mutable reference while the -per-variant [`MapType`](./map_type.md) markers continue to track possibility. That is the whole +per-variant [`MapType`](../type-level/map_type.md) markers continue to track possibility. That is the whole difference between the two borrowing accessors: one marker. -There is no rebuild counterpart, and none is needed — the value was never taken apart, only borrowed. +There is no rebuild counterpart, and none is needed, because the value was never taken apart, only +borrowed. ## Common Mistakes @@ -115,7 +123,7 @@ machinery is at fault. its lifetime cleanly. **The three extractors are three different types.** Code generic over "an extractor" must pick one or be -generic over the [`MapTypeRef`](./map_type_ref.md) marker too. +generic over the [`MapTypeRef`](../type-level/map_type_ref.md) marker too. **A remainder still carries none of the enum's attributes.** @@ -126,10 +134,10 @@ generic over the [`MapTypeRef`](./map_type_ref.md) marker too. - [`ExtractField`](./extract_field.md) — the narrowing, identical through a mutable borrow. - [`FinalizeExtract`](./finalize_extract.md) and [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. -- [`MapTypeRef`](./map_type_ref.md) — the `IsMut` marker this fixes. -- [`MapType`](./map_type.md) — the per-variant markers it composes with. -- [`HasFieldMut`](./has_field_mut.md) — the record side's mutable access. -- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the borrowed companion. +- [`MapTypeRef`](../type-level/map_type_ref.md) — the `IsMut` marker this fixes. +- [`MapType`](../type-level/map_type.md) — the per-variant markers it composes with. +- [`HasFieldMut`](../field-access/has_field_mut.md) — the record side's mutable access. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the borrowed companion. The ideas behind it: diff --git a/docs/reference/traits/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md similarity index 75% rename from docs/reference/traits/has_extractor_ref.md rename to docs/reference/traits/variant/has_extractor_ref.md index 1bb47661..2eec701f 100644 --- a/docs/reference/traits/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -1,5 +1,6 @@ --- sidebar_label: 'HasExtractorRef' +sidebar_position: 3 --- # `HasExtractorRef` @@ -10,7 +11,17 @@ Obtaining an extractor that borrows the value rather than consuming it. [`HasExtractor`](./has_extractor.md) consumes an enum to produce an extractor with owned payloads. Code that only *reads* a variant — checking it, measuring it, rendering it — should not have to give up the -value. `HasExtractorRef` is the borrowing accessor: +value. `HasExtractorRef` is the borrowing accessor. + +Payloads come out as shared references and the original survives. **The narrowing works identically**: +[`ExtractField`](./extract_field.md) rules variants out of a borrowed extractor exactly as it does an +owned one, and the chain ends the same way. + +It is the weakest of the three accessors, so prefer it wherever it suffices. + +## Definition + +`HasExtractorRef` produces a borrowing extractor: ```rust pub trait HasExtractorRef { @@ -22,21 +33,17 @@ pub trait HasExtractorRef { } ``` -Payloads come out as shared references and the original survives. **The narrowing works identically** — -[`ExtractField`](./extract_field.md) rules variants out of a borrowed extractor exactly as it does an -owned one, and the chain ends the same way. - -It is the weakest of the three accessors, so prefer it wherever it suffices. +`Self` is the enum. `ExtractorRef<'a>` is a **generic associated type**: the borrowed extractor over the +same partial companion enum, with every payload held for the lifetime `'a`. The `where Self: 'a` clause +keeps the borrowed extractor from outliving the value it came from. `extractor_ref` takes a shared borrow +of the value and returns the extractor at the anonymous lifetime, which is why the call reads with no +lifetime written. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -`ExtractorRef<'a>` is a **generic associated type** with a `where Self: 'a` clause, so the borrowed -extractor cannot outlive the value it came from. `extractor_ref(&self)` takes a shared borrow and returns -one at the anonymous lifetime, which is why the call reads with no lifetime written. - -The impls come from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md), alongside the owning +The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md), alongside the owning and mutable accessors. ## Examples @@ -73,13 +80,13 @@ full chain narrows the same way, with each remainder also borrowing. - **[`HasExtractorMut`](./has_extractor_mut.md)** to change a payload in place. - **[`HasExtractor`](./has_extractor.md)** only when the payload must be moved out. - **A `match`** when the enum is concrete. This family is for code that cannot name it. -- **[`ToFieldsRef`](./to_fields_ref.md)** when what you want is the value's borrowed *shape* rather than +- **[`ToFieldsRef`](../shape/to_fields_ref.md)** when what you want is the value's borrowed *shape* rather than a narrowing chain — the same borrow-rather-than-consume idea, applied to the whole-shape view. ## Under the hood The borrowed accessor uses the **same partial enum** as the owning one, with an extra -[`MapTypeRef`](./map_type_ref.md) parameter fixed to `IsRef`: +[`MapTypeRef`](../type-level/map_type_ref.md) parameter fixed to `IsRef`: ```rust // conceptually @@ -94,8 +101,8 @@ The borrowed accessor uses the **same partial enum** as the owning one, with an // } ``` -Read the nesting outward: the [`MapTypeRef`](./map_type_ref.md) marker decides *how* a payload is held — -`IsRef::Map<'a, T>` is `&'a T` — and the per-variant [`MapType`](./map_type.md) markers decide *whether* +Read the nesting outward: the [`MapTypeRef`](../type-level/map_type_ref.md) marker decides *how* a payload is held — +`IsRef::Map<'a, T>` is `&'a T` — and the per-variant [`MapType`](../type-level/map_type.md) markers decide *whether* it is still possible. The two axes are independent, which is precisely why narrowing behaves the same through a borrow as through an owned value. @@ -117,7 +124,7 @@ has to spell the lifetime out rather than elide it. nor `PartialEq`. **The borrowed and owned extractors are different types.** Code generic over "an extractor" has to pick -one, or be generic over the [`MapTypeRef`](./map_type_ref.md) marker as well. +one, or be generic over the [`MapTypeRef`](../type-level/map_type_ref.md) marker as well. ## Related constructs @@ -126,10 +133,10 @@ one, or be generic over the [`MapTypeRef`](./map_type_ref.md) marker as well. - [`ExtractField`](./extract_field.md) — the narrowing, identical through a borrow. - [`FinalizeExtract`](./finalize_extract.md) and [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. -- [`MapTypeRef`](./map_type_ref.md) — the `IsRef` marker this fixes. -- [`MapType`](./map_type.md) — the per-variant markers it composes with. -- [`ToFieldsRef`](./to_fields_ref.md) — the record side's borrow-rather-than-consume view. -- [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) — generates the borrowed companion. +- [`MapTypeRef`](../type-level/map_type_ref.md) — the `IsRef` marker this fixes. +- [`MapType`](../type-level/map_type.md) — the per-variant markers it composes with. +- [`ToFieldsRef`](../shape/to_fields_ref.md) — the record side's borrow-rather-than-consume view. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the borrowed companion. The ideas behind it: diff --git a/docs/reference/traits/variant/index.md b/docs/reference/traits/variant/index.md new file mode 100644 index 00000000..699921fa --- /dev/null +++ b/docs/reference/traits/variant/index.md @@ -0,0 +1,41 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Extensible variants + +Constructing an enum from one named variant, and taking one apart variant by variant. + +## Overview + +These traits are the enum counterpart of the [record builder](../builder/index.md): where a record is +a product of named fields, an enum is a sum of named variants, and the same name-driven, decoupled +treatment applies. They let generic code build and match an enum it cannot name, with exhaustiveness +proven in the type rather than by a wildcard arm. The impls come from +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) and +[`#[derive(FromVariant)]`](../../derives/derive_from_variant.md). + +The family splits into deconstruction and construction. + +**Deconstruction** takes an enum apart. [`ExtractField`](extract_field.md) pulls one variant out of an +*extractor* or hands back a narrowed remainder, and the three accessors obtain that extractor in one +ownership mode each: [`HasExtractor`](has_extractor.md) consumes the value, +[`HasExtractorRef`](has_extractor_ref.md) borrows it, and [`HasExtractorMut`](has_extractor_mut.md) +borrows it mutably. [`FinalizeExtract`](finalize_extract.md) discharges the exhausted remainder with no +wildcard, and [`FinalizeExtractResult`](finalize_extract_result.md) is the form that closes a chain from +the `Result` a step returns. + +**Construction** is the smaller half. [`FromVariant`](from_variant.md) builds an enum from a single +variant chosen by its type-level name, which lets code work in a narrow local enum and widen the +result. + +## The ideas behind them + +- [Extensible variants](/docs/concepts/extensible-variants) — partial variants, the exhaustiveness + argument, and the extensible visitor pattern. +- [Dispatching](/docs/concepts/dispatching) — routing a variant to the implementation that handles it. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/wiring/_category_.json b/docs/reference/traits/wiring/_category_.json new file mode 100644 index 00000000..6098539c --- /dev/null +++ b/docs/reference/traits/wiring/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Wiring and checking", + "position": 1, + "link": { + "type": "doc", + "id": "reference/traits/wiring/index" + } +} diff --git a/docs/reference/traits/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md similarity index 77% rename from docs/reference/traits/can_use_component.md rename to docs/reference/traits/wiring/can_use_component.md index 4742e008..2eb7bfd5 100644 --- a/docs/reference/traits/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -1,5 +1,6 @@ --- sidebar_label: 'CanUseComponent' +sidebar_position: 3 --- # `CanUseComponent` @@ -11,8 +12,8 @@ The context-side check that a context both wires a component and satisfies its p ### Generated machinery **You are not expected to name `CanUseComponent` directly.** -[`check_components!`](../macros/check_components.md) and -[`delegate_and_check_components!`](../macros/delegate_and_check_components.md) generate the assertion +[`check_components!`](../../macros/check_components.md) and +[`delegate_and_check_components!`](../../macros/delegate_and_check_components.md) generate the assertion that uses it. What you write is the check; this page explains what a check actually asserts, so that its failure is legible. @@ -39,12 +40,12 @@ hold together: Because `IsProviderFor` carries the provider's real `where` bounds, requiring it forces the compiler to evaluate and report them. The error that was hidden becomes visible, at the wiring site. -**You never name this trait.** It is what [`check_components!`](../macros/check_components.md) asserts, and the +**You never name this trait.** It is the bound [`check_components!`](../../macros/check_components.md) asserts, and the reason that macro produces a legible error instead of a cascade. -## Usage +## Definition -The trait is in the prelude. It is empty, and its entire meaning lives in a single blanket impl: +`CanUseComponent` is an empty marker trait, and its entire meaning lives in a single blanket impl: ```rust pub trait CanUseComponent {} @@ -57,14 +58,22 @@ where } ``` -`Self` is the context being checked, `Component` is the component-name marker, and `Params` collects the -component's extra generic parameters — filled by the same rule -[`IsProviderFor`](./is_provider_for.md) uses: one parameter directly, several as a tuple, `()` when there are -none. +`Self` is the context being checked. `Component` is the component-name marker, the same key the wiring +table uses. `Params` collects the component's extra generic parameters and defaults to `()` when there +are none, filled by the same rule [`IsProviderFor`](./is_provider_for.md) uses: one parameter directly, +several as a tuple. The trait has no method, so the blanket impl carries the meaning. Its two bounds are +the two halves of "can use": the context must hold a [`DelegateComponent`](./delegate_component.md) entry +for the component, and that entry's provider must satisfy [`IsProviderFor`](./is_provider_for.md) for this +context and these parameters. Because `IsProviderFor` re-exposes the provider's real `where` bounds, +requiring it forces the compiler to evaluate and report them. + +## Usage + +The trait is in the prelude. You do not name it directly; you assert it through a check macro. ### Asserting it -You assert it through a macro. A [`check_components!`](../macros/check_components.md) table reduces to one +You assert it through a macro. A [`check_components!`](../../macros/check_components.md) table reduces to one impl of a private check trait per entry, whose supertrait is this bound, so the impl compiles only if the bound holds: @@ -139,14 +148,14 @@ build, with nothing added to the binary. ## When to use it -**Reach for [`check_components!`](../macros/check_components.md); it is what reaches for this trait.** The one -non-negotiable is that a context's wiring gets checked *somehow* — lazy wiring means an unchecked context can +**Reach for [`check_components!`](../../macros/check_components.md), which reaches for this trait.** The one +non-negotiable is that a context's wiring gets checked *somehow*: lazy wiring means an unchecked context can compile and fail later. Which macro does it is a matter of scale. -- **[`delegate_and_check_components!`](../macros/delegate_and_check_components.md)** fuses wiring and checking, +- **[`delegate_and_check_components!`](../../macros/delegate_and_check_components.md)** fuses wiring and checking, which suits basic wiring and getting started. It derives a check only for plain `Component: Provider` entries. -- **Separate [`check_components!`](../macros/check_components.md)** is what larger wiring wants, because it +- **Separate [`check_components!`](../../macros/check_components.md)** is what larger wiring wants, because it gives control over *what* is checked: concrete parameters for a generic component, checks over opened or namespaced wiring, and `#[check_providers(...)]` per provider layer. - **`#[check_providers(...)]`** switches the assertion from this trait to @@ -155,7 +164,7 @@ compile and fail later. Which macro does it is a matter of scale. layer*, which a context-side check cannot tell you. One case makes a context-side check actively wrong rather than merely unnecessary: **a provider bundle.** A -[`delegate_components!`](../macros/delegate_components.md) block with a leading `new` declares a provider that +[`delegate_components!`](../../macros/delegate_components.md) block with a leading `new` declares a provider that other contexts delegate to, not a context. Asserting `CanUseComponent` on it asks whether the bundle can use each component *as a context* — a role it never plays — so the answer is uninformative either way. It passes vacuously when the bundled providers need nothing from their context, and fails blaming the bundle when any of @@ -167,7 +176,7 @@ verify those — they surface as themselves. ## Under the hood -The blanket impl *is* the behaviour, and its two bounds fail differently — which is the practical payoff. +The blanket impl *is* the behaviour, and its two bounds fail differently, which is the practical payoff. **The first bound failing means the wiring is absent.** `Context: DelegateComponent` is unmet when the context never wired the component, and the [`DelegateComponent`](./delegate_component.md) diagnostic @@ -182,7 +191,7 @@ Reading which bound failed is therefore the first thing to do with the error. Th (`Self = Context`) rather than on the provider (`Self = Provider`). One starts from "the context delegates and its delegate is valid"; the other from "this specific provider is valid". -[`check_components!`](../macros/check_components.md) consumes it by emitting a private check trait whose +[`check_components!`](../../macros/check_components.md) consumes it by emitting a private check trait whose supertrait is this bound, then one empty impl of that trait per checked entry. Each impl compiles only if its supertrait holds, so the table is an assertion. Because it produces no values, a successful build *is* the passing test. @@ -195,7 +204,7 @@ because the two questions produce different diagnostics. **Do not assert it on a provider bundle.** The question is meaningless there, and worse, it can pass vacuously — so a green check on a bundle proves nothing. This is why -[`delegate_and_check_components!`](../macros/delegate_and_check_components.md) is wrong for a bundle. +[`delegate_and_check_components!`](../../macros/delegate_and_check_components.md) is wrong for a bundle. **`Params` follows the tuple rule.** One parameter directly, several as a tuple, `()` for none. A hand-written assertion that gets this wrong reports as an unsatisfied bound rather than an arity error. @@ -208,14 +217,14 @@ the binary. The cost is trait resolution at build time, which is the trade the c ## Related constructs -- [`check_components!`](../macros/check_components.md) — the macro that asserts this trait; what you write. -- [`delegate_and_check_components!`](../macros/delegate_and_check_components.md) — wires and checks at once, +- [`check_components!`](../../macros/check_components.md) — the macro that asserts this trait; what you write. +- [`delegate_and_check_components!`](../../macros/delegate_and_check_components.md) — wires and checks at once, for basic wiring. - [`DelegateComponent`](./delegate_component.md) — the first of the two bounds: the context must delegate. - [`IsProviderFor`](./is_provider_for.md) — the second bound, and the provider-indexed counterpart of this trait. -- [`#[cgp_component]`](../macros/cgp_component.md) — defines the components being checked. -- [Compile errors](../errors.md) — the shapes these checks produce, and how to read them. +- [`#[cgp_component]`](../../macros/cgp_component.md) — defines the components being checked. +- [Compile errors](../../errors.md) — the shapes these checks produce, and how to read them. The ideas behind it: diff --git a/docs/reference/traits/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md similarity index 75% rename from docs/reference/traits/delegate_component.md rename to docs/reference/traits/wiring/delegate_component.md index 3a5a319c..83dac1e6 100644 --- a/docs/reference/traits/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -1,5 +1,6 @@ --- sidebar_label: 'DelegateComponent' +sidebar_position: 1 --- # `DelegateComponent` @@ -11,8 +12,8 @@ The per-context type-level table mapping a component key to its provider. ### Generated machinery **You are not expected to write `DelegateComponent` impls.** -[`delegate_components!`](../macros/delegate_components.md) emits one per entry of a wiring table, and -[`cgp_namespace!`](../macros/cgp_namespace.md) emits the blanket forwarding impls behind a namespace. +[`delegate_components!`](../../macros/delegate_components.md) emits one per entry of a wiring table, and +[`cgp_namespace!`](../../macros/cgp_namespace.md) emits the blanket forwarding impls behind a namespace. What you write is the table. This page explains what the table *becomes*, so that an expansion or a wiring error naming this trait is legible. @@ -31,10 +32,10 @@ impl DelegateComponent for App { ``` Read that as *"in `App`'s table, the entry at `GreeterComponent` is `GreetHello`."* The key is a type, the -value is a type, and the whole lookup happens while the compiler is type-checking — which is why the +value is a type, and the whole lookup happens while the compiler is type-checking, which is why the "table" costs nothing at runtime and compiles down to a direct call. -**You will almost never write this by hand.** [`delegate_components!`](../macros/delegate_components.md) +**You will almost never write this by hand.** [`delegate_components!`](../../macros/delegate_components.md) generates one impl per line of its body, and that macro is what you write. What makes the trait worth a page is that it appears by name in compiler errors, and that reading it is how you understand what wiring *is*: not a registry, not a lookup at startup, but a set of trait impls the compiler resolves. @@ -44,27 +45,39 @@ component name.** When it is, the entry makes the context inherit the component' is any other type — a shape, a tag, a path segment — the same trait is just a lookup table that a provider walks. One trait covers both, which is why it underlies both ordinary wiring and the inner dispatch tables. -## Usage +## Definition -The trait is in the prelude, so `use cgp::prelude::*;` is enough to name it. It carries one associated type -and no methods: +`DelegateComponent` carries a single associated type and no method, and it wears a diagnostic attribute +that shapes the error when a lookup misses: ```rust +#[diagnostic::on_unimplemented( + message = "{Self} does not contain any DelegateComponent entry for {Key}", + note = "You might want to implement the provider trait for {Key} on {Self}" +)] pub trait DelegateComponent { type Delegate; } ``` -`Self` is the table — the context or the provider bundle that owns the entry. `Key` is what is being looked -up, and it is `?Sized` so that an unsized marker can serve as one. `Delegate` is the value stored there. -There is nothing else: no method, no data, no runtime representation. +`Self` is the table: the context or the provider bundle that owns the entry. `Key` is the type being +looked up, and it is `?Sized` so that an unsized marker can serve as one. `Delegate` is the value stored +at that key, the provider or the further table the entry resolves to. There is no method and no data; the +trait only associates one value type with one key type on a carrier type, so the whole lookup happens +while the compiler type-checks. The `#[diagnostic::on_unimplemented]` attribute reports a missed lookup as +a missing *entry* rather than an opaque "trait not implemented", one of the few diagnostics CGP improves +without a tool. + +## Usage + +The trait is in the prelude, so `use cgp::prelude::*;` is enough to name it. ### Setting an entry, and reading one There are only two operations, and both are ordinary Rust rather than anything CGP-specific. **Setting** an entry is writing the impl, which in practice means writing a -[`delegate_components!`](../macros/delegate_components.md) line. **Reading** one is bounding on the trait +[`delegate_components!`](../../macros/delegate_components.md) line. **Reading** one is bounding on the trait and projecting the associated type: ```rust @@ -77,29 +90,29 @@ where ``` The bound is the "get"; `
>::Delegate` is the value it returns. Because Rust -forbids two impls of one trait for the same `Self` and `Key`, each key maps to exactly one value — which is -what makes this a map rather than a relation, and what makes a duplicate wiring entry a coherence error -rather than a silent overwrite. +forbids two impls of one trait for the same `Self` and `Key`, each key maps to exactly one value. This +makes the structure a map rather than a relation, and it turns a duplicate wiring entry into a coherence +error rather than a silent overwrite. ### What can be a key The key's type decides what the entry *means*, and there are three shapes in practice. A **component name** — `GreeterComponent`, `AreaCalculatorComponent` — is the ordinary case. An entry keyed -this way is read by the blanket impl that [`#[cgp_component]`](../macros/cgp_component.md) generates, which +this way is read by the blanket impl that [`#[cgp_component]`](../../macros/cgp_component.md) generates, which concludes that the context has the component's provider trait, and from there its consumer trait. An **arbitrary type** — a shape, a tag — makes the table a plain dispatch map with no provider trait -attached. This is what the nested tables inside [`UseDelegate`](../providers/use_delegate.md) are, and what +attached. This is what the nested tables inside [`UseDelegate`](../../providers/use_delegate.md) are, and what the `open` statement's per-key entries resolve through. -A **type-level path** — a [`PathCons`](../types/type_level_spines.md) list built by -[`Path!`](../macros/path.md) — is how namespaces key their entries, so a lookup walks one segment at a time. -[`RedirectLookup`](../providers/redirect_lookup.md) is the provider that performs that walk. +A **type-level path** — a [`PathCons`](../../types/type_level_spines.md) list built by +[`Path!`](../../macros/path.md) — is how namespaces key their entries, so a lookup walks one segment at a time. +[`RedirectLookup`](../../providers/redirect_lookup.md) is the provider that performs that walk. ### What owns a table -`Self` is not always a context. A [`delegate_components!`](../macros/delegate_components.md) block with a +`Self` is not always a context. A [`delegate_components!`](../../macros/delegate_components.md) block with a leading `new` declares a provider bundle that owns its own table, so several contexts can delegate a whole group of components to it as one unit. Resolution is shallow — one read yields the immediate `Delegate` — and chaining happens when that delegate is itself a table, which is exactly what a bundle is. @@ -161,12 +174,12 @@ delegate_components! { ``` `AreaComponents` now has `DelegateComponent` and `DelegateComponent` entries. No provider -trait attaches to either; they are data that a [`UseDelegate`](../providers/use_delegate.md) provider reads +trait attaches to either; they are data that a [`UseDelegate`](../../providers/use_delegate.md) provider reads at dispatch time to pick `RectangleArea` or `CircleArea` for the shape it was asked about. ## When to use it -**Write [`delegate_components!`](../macros/delegate_components.md), not `DelegateComponent`.** That is the +**Write [`delegate_components!`](../../macros/delegate_components.md), not `DelegateComponent`.** That is the honest summary of this page: the trait is what you read, and the macro is what you write. The macro also emits the [`IsProviderFor`](./is_provider_for.md) forwarding impl beside each entry, which is what keeps a missing dependency diagnosable — so a hand-written `DelegateComponent` impl gets you the wiring and loses @@ -189,30 +202,17 @@ implementation is one of several, or is shared, or should compose with a wrapper ## Under the hood The trait is the plainest thing in CGP — one associated type, no method — so the interesting part is what -reads it. The provider blanket impl generated by [`#[cgp_component]`](../macros/cgp_component.md) is the +reads it. The provider blanket impl generated by [`#[cgp_component]`](../../macros/cgp_component.md) is the reader, and its body is itself a table lookup: it bounds the provider on `DelegateComponent` and forwards each method to `>::Delegate`. So the "routing" is -literally the projection, and the call it forwards to is resolved statically and inlined. - -The trait carries a diagnostic attribute that shapes the error when a lookup misses: - -```rust -#[diagnostic::on_unimplemented( - message = "{Self} does not contain any DelegateComponent entry for {Key}", - note = "You might want to implement the provider trait for {Key} on {Self}" -)] -pub trait DelegateComponent { - type Delegate; -} -``` - -That message is why an unwired component reports as a missing *entry* rather than as an opaque unimplemented -trait — one of the few places CGP can improve a diagnostic without a tool. +literally the projection, and the call it forwards to is resolved statically and inlined. The +[`#[diagnostic::on_unimplemented]`](#definition) message shown above turns an unwired component into a +readable missing-*entry* error rather than an opaque unimplemented trait. Two further facts about the generated impls are worth carrying away. Each entry is emitted **alongside** an [`IsProviderFor`](./is_provider_for.md) impl that forwards the chosen provider's requirements, so the entry -is both resolvable and checkable; the pair is what -[`CanUseComponent`](./can_use_component.md) then combines into a single assertion. And a namespace's +is both resolvable and checkable, and [`CanUseComponent`](./can_use_component.md) then combines the pair +into a single assertion. And a namespace's `namespace N;` header emits not one entry but a *blanket* `DelegateComponent` impl that forwards every key through the namespace, which is how a context inherits a whole table while still letting a direct entry shadow one key. @@ -237,21 +237,21 @@ forwarding that makes a missing transitive dependency readable. Use the macro. **The table is resolved at compile time, in full.** There is no runtime map to inspect, no way to add an entry dynamically, and no cost per call. If you are looking for a place to register something at startup, -this is not it — and that is the point. +this is not it, and that is the point. ## Related constructs -- [`delegate_components!`](../macros/delegate_components.md) — the macro that generates these impls; what +- [`delegate_components!`](../../macros/delegate_components.md) — the macro that generates these impls; what you write instead of the trait. -- [`#[cgp_component]`](../macros/cgp_component.md) — generates the blanket impl that reads the table. +- [`#[cgp_component]`](../../macros/cgp_component.md) — generates the blanket impl that reads the table. - [`IsProviderFor`](./is_provider_for.md) — emitted beside each entry so a missing dependency stays readable. - [`CanUseComponent`](./can_use_component.md) — combines a delegation and a valid provider into one assertion. -- [`check_components!`](../macros/check_components.md) — asserts that combination. -- [`UseDelegate`](../providers/use_delegate.md) — reads an arbitrary-key table for per-type dispatch. -- [`RedirectLookup`](../providers/redirect_lookup.md) — walks path-keyed entries; the namespace mechanism. -- [`DefaultNamespace`](./default_namespace.md) — the lookup traits a `namespace` header forwards through. +- [`check_components!`](../../macros/check_components.md) — asserts that combination. +- [`UseDelegate`](../../providers/use_delegate.md) — reads an arbitrary-key table for per-type dispatch. +- [`RedirectLookup`](../../providers/redirect_lookup.md) — walks path-keyed entries; the namespace mechanism. +- [`DefaultNamespace`](../namespace/default_namespace.md) — the lookup traits a `namespace` header forwards through. The ideas behind it: diff --git a/docs/reference/traits/wiring/index.md b/docs/reference/traits/wiring/index.md new file mode 100644 index 00000000..b7a121e4 --- /dev/null +++ b/docs/reference/traits/wiring/index.md @@ -0,0 +1,42 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Wiring and checking + +The three traits every context's wiring rests on, and the ones a wiring error names. + +## Overview + +Wiring a **context** — the type a capability runs against — records which provider it uses for each +component and checks that the provider's own requirements are met. Three traits carry that, and you +read them far more often than you write them, because a +[`delegate_components!`](../../macros/delegate_components.md) table generates the first two and a +[`check_components!`](../../macros/check_components.md) block asserts the third. + +The three build on one another. A context becomes a type-level table through +[`DelegateComponent`](delegate_component.md), one entry per component. Each entry also carries an +[`IsProviderFor`](is_provider_for.md) impl that re-exposes the chosen provider's `where` bounds, so a +missing dependency is named rather than hidden. [`CanUseComponent`](can_use_component.md) combines the +two into a single question that a check asserts: does the context delegate this component, and do its +provider's requirements hold? + +- [`DelegateComponent`](delegate_component.md) — the per-context table mapping a component to its + provider; what a wiring line becomes. +- [`IsProviderFor`](is_provider_for.md) — the marker that surfaces a provider's missing dependency by + name, and the trait a `#[check_providers]` assertion names. +- [`CanUseComponent`](can_use_component.md) — the context-side check a `check_components!` block + reduces to, holding only when a component is both delegated and satisfiable. + +## The ideas behind them + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the split this wiring + connects. +- [Bypassing coherence](/docs/concepts/coherence) — why the choice is recorded per context. +- [Check traits](/docs/concepts/check-traits) — why wiring is lazy, and how an assertion makes its + failures readable. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md similarity index 73% rename from docs/reference/traits/is_provider_for.md rename to docs/reference/traits/wiring/is_provider_for.md index df196f58..dacc596e 100644 --- a/docs/reference/traits/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -1,5 +1,6 @@ --- sidebar_label: 'IsProviderFor' +sidebar_position: 2 --- # `IsProviderFor` @@ -11,7 +12,7 @@ The marker supertrait that makes a provider's missing dependency show up by name ### Generated machinery **You never write `IsProviderFor` yourself.** The provider macros — -[`#[cgp_impl]`](../macros/cgp_impl.md) and [`#[cgp_provider]`](../macros/cgp_provider.md), which also +[`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md), which also covers `#[cgp_new_provider]` — derive it from the same `where` clause you already wrote. This page explains what they emit, because this trait is what a missing-dependency error names, and reading that error is the reason to know it exists. @@ -36,22 +37,36 @@ itself. Every generated provider trait carries it as a supertrait, so asking whe candidate impl, no blanket competing with it, the compiler commits to it and reports precisely which constraint failed. -**This is invisible plumbing until you read an error.** You never write it and never call it. What it buys is -the difference between "the trait is not implemented" and "the field `name` is missing on `App`", and it is -the mechanism [`check_components!`](../macros/check_components.md) leans on to produce the second. +**This is invisible plumbing until you read an error.** You never write it and never call it. It buys the +difference between "the trait is not implemented" and "the field `name` is missing on `App`", and it is +the mechanism [`check_components!`](../../macros/check_components.md) leans on to produce the second. -## Usage +## Definition -The trait is in the prelude, so `use cgp::prelude::*;` names it. It is empty, with three parameters: +`IsProviderFor` is an empty marker trait with three type parameters and a diagnostic note: ```rust +#[diagnostic::on_unimplemented( + note = "You need to add `#[cgp_provider({Component})]` on the impl block for CGP provider traits" +)] pub trait IsProviderFor {} ``` -The four types together identify one provider-trait implementation. `Self` is the **provider** whose validity -is asserted. `Component` is the component-name marker, the same key the wiring table uses. `Context` is the -context the provider trait is implemented for. `Params` collects the component's own extra generic -parameters. +The four types together identify one provider-trait implementation. `Self` is the **provider** whose +validity is asserted. `Component` is the component-name marker, the same key the wiring table uses. +`Context` is the context the provider trait is implemented for. `Params` collects the component's own +extra generic parameters, and it defaults to the unit tuple `()` for a component that has none; how +several parameters are grouped is covered under [How `Params` is filled](#how-params-is-filled). The +trait has no method and no associated item. [`#[cgp_component]`](../../macros/cgp_component.md) attaches +it as a supertrait on every provider trait, so using a provider trait requires establishing +`IsProviderFor` first — which is why probing the marker probes the provider trait's whole dependency set. +The `#[diagnostic::on_unimplemented]` note points a reader at the missing `#[cgp_provider]` attribute when +the marker impl is absent. + +## Usage + +The trait is in the prelude, so `use cgp::prelude::*;` names it. You never implement it; the useful +operations are supplying `Params` correctly and, occasionally, asserting the marker. ### How `Params` is filled @@ -60,7 +75,7 @@ This is the only part with a rule worth memorizing, and it is what a hand-writte - A component with **no** parameters uses the default, `()`. - A component with **one** parameter passes it directly — `IsProviderFor`. - A component with **several** groups them into a tuple — `IsProviderFor`. -- A **lifetime** parameter is lifted into [`Life<'a>`](../types/life.md), because the tuple holds types and a +- A **lifetime** parameter is lifted into [`Life<'a>`](../../types/life.md), because the tuple holds types and a lifetime cannot sit there directly. ### Asserting it @@ -75,7 +90,7 @@ where ``` That holds exactly when `GreetHello`'s dependencies are satisfied for `App`. In practice you write this -through the `#[check_providers(...)]` form of [`check_components!`](../macros/check_components.md) rather +through the `#[check_providers(...)]` form of [`check_components!`](../../macros/check_components.md) rather than by hand — which is the tool for localizing a failure inside a stack of [higher-order providers](/docs/concepts/higher-order-providers), where checking the context tells you a layer is broken but not which one. @@ -129,8 +144,8 @@ and the same mistake surfaces far away, at whatever calls `app.greet()`, as a mu **Do not reach for it. Recognize it.** There is no case in ordinary CGP code where you write `IsProviderFor`: the provider macros emit the impl, `#[cgp_component]` emits the supertrait link, and -[`delegate_components!`](../macros/delegate_components.md) emits the forwarding. What you do with it is read -it in an error and, occasionally, assert it through a check. +[`delegate_components!`](../../macros/delegate_components.md) emits the forwarding. You instead read it in +an error and, occasionally, assert it through a check. Two situations do put its name in your hands, and both are about diagnosis rather than construction. @@ -143,7 +158,7 @@ Two situations do put its name in your hands, and both are about diagnosis rathe the chain readable. If you find yourself wanting to implement it by hand, the thing you actually want is -[`#[cgp_provider]`](../macros/cgp_provider.md) or [`#[cgp_impl]`](../macros/cgp_impl.md) on the impl block — +[`#[cgp_provider]`](../../macros/cgp_provider.md) or [`#[cgp_impl]`](../../macros/cgp_impl.md) on the impl block — the trait's own diagnostic says so, which is the one case where a missing marker impl is the reported problem rather than the hidden one. @@ -151,7 +166,7 @@ problem rather than the hidden one. `IsProviderFor` appears in three places, and together they form the chain an error travels along. -**First, the supertrait link.** [`#[cgp_component]`](../macros/cgp_component.md) emits every provider trait +**First, the supertrait link.** [`#[cgp_component]`](../../macros/cgp_component.md) emits every provider trait with the marker as a supertrait, so for a component `CanGetFooAt` the provider trait reads: ```rust @@ -160,11 +175,11 @@ pub trait FooGetterAt: { /* … */ } ``` -This is what binds a provider's dependency set to the marker: using the provider trait *requires* +This binds a provider's dependency set to the marker: using the provider trait *requires* establishing `IsProviderFor` first, so probing the marker is equivalent to probing the provider trait. -**Second, the per-provider impl.** [`#[cgp_provider]`](../macros/cgp_provider.md) and -[`#[cgp_impl]`](../macros/cgp_impl.md) emit an empty impl beside the provider trait impl, carrying identical +**Second, the per-provider impl.** [`#[cgp_provider]`](../../macros/cgp_provider.md) and +[`#[cgp_impl]`](../../macros/cgp_impl.md) emit an empty impl beside the provider trait impl, carrying identical bounds: ```rust @@ -179,10 +194,10 @@ where {} ``` -Identical `where` clauses mean the marker is satisfiable exactly when the provider trait is — which is the +Identical `where` clauses mean the marker is satisfiable exactly when the provider trait is. That is the whole trick. -**Third, the table forwarding.** [`delegate_components!`](../macros/delegate_components.md) emits, for each +**Third, the table forwarding.** [`delegate_components!`](../../macros/delegate_components.md) emits, for each entry, an impl on the table that forwards to the delegated provider's marker: ```rust @@ -193,7 +208,7 @@ where ``` Because this is an explicit impl rather than a blanket, the compiler follows it and surfaces everything -`GreetHello` requires. It is also what carries requirements *across layers*: when a provider bundle delegates +`GreetHello` requires. It also carries requirements *across layers*: when a provider bundle delegates to another bundle, each forwards to the next, so a dependency unmet several tables deep still propagates back to where the component is checked. @@ -208,12 +223,12 @@ requirements outward through a higher-order stack. or more as a tuple, none as `()`. Getting it wrong reports as an unsatisfied bound on a trait you did not expect, rather than as a helpful arity error. -**A lifetime parameter becomes [`Life<'a>`](../types/life.md) in the tuple.** It cannot appear as a bare +**A lifetime parameter becomes [`Life<'a>`](../../types/life.md) in the tuple.** It cannot appear as a bare lifetime in a type position, so it is lifted. **A missing marker impl usually means a missing attribute.** If the compiler says a provider does not implement `IsProviderFor`, the likeliest cause is a provider-trait impl written without -[`#[cgp_provider]`](../macros/cgp_provider.md) — the trait's own diagnostic note says exactly this. +[`#[cgp_provider]`](../../macros/cgp_provider.md) — the trait's own diagnostic note says exactly this. **Read it as "because", not as "instead".** `GreetHello: IsProviderFor<…> is not satisfied` does not mean the marker is the problem; it means the provider trait is not implemented *because* the named dependency is @@ -229,17 +244,17 @@ is the propagation that lets `#[check_providers]` localize a broken layer. ## Related constructs -- [`#[cgp_component]`](../macros/cgp_component.md) — attaches the marker as a supertrait on every provider +- [`#[cgp_component]`](../../macros/cgp_component.md) — attaches the marker as a supertrait on every provider trait. -- [`#[cgp_impl]`](../macros/cgp_impl.md) and [`#[cgp_provider]`](../macros/cgp_provider.md) — emit the +- [`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md) — emit the per-provider impl beside the provider trait impl. -- [`delegate_components!`](../macros/delegate_components.md) — emits the forwarding impl at each table entry. +- [`delegate_components!`](../../macros/delegate_components.md) — emits the forwarding impl at each table entry. - [`DelegateComponent`](./delegate_component.md) — the table those entries live in. - [`CanUseComponent`](./can_use_component.md) — the context-indexed counterpart, which requires this of the delegate. -- [`check_components!`](../macros/check_components.md) — forces both; its `#[check_providers(...)]` form +- [`check_components!`](../../macros/check_components.md) — forces both; its `#[check_providers(...)]` form asserts this trait directly. -- [Compile errors](../errors.md) — how the resulting diagnostics read, and what the tool makes of them. +- [Compile errors](../../errors.md) — how the resulting diagnostics read, and what the tool makes of them. The ideas behind it: From d4d1cbdabf28c734ab96e08776c4e9d94ff64c0f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 24 Aug 2026 10:31:59 +0200 Subject: [PATCH 051/516] reference: write the types/ construct pages Fill in the last stubbed reference group, one page per type. Split the consolidated type_level_spines page into a spines/ subdirectory (Cons, Nil, Either, Void, Chars, PathCons), keep Field/Index/Life/MRef as top-level singletons, and add a new PhantomData page and section+spines overviews. Order the section by importance (PhantomData, Field, spines, Index, Life, MRef). Rename the Index type page to index_type.md so index.md can be the section overview, re-point every inbound link to the split spine pages and the renamed Index page, and update the reference index prose and lookup table. Remove the "still being written" notice, since no reference stub remains. Back the type pages with example-code mirrors (one file per page that shows code, spines nested) and a compile-fail fixture for the E0392 "unused type parameter" snippet on the PhantomData page. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01MdT4e1ra7BqrnpTg2zd5b2 --- docs/reference/derives/derive_build_field.md | 2 +- docs/reference/derives/derive_cgp_data.md | 2 +- docs/reference/derives/derive_cgp_record.md | 2 +- .../reference/derives/derive_extract_field.md | 2 +- docs/reference/derives/derive_from_variant.md | 2 +- docs/reference/derives/derive_has_field.md | 4 +- docs/reference/derives/derive_has_fields.md | 10 +- docs/reference/index.md | 33 ++- docs/reference/macros/cgp_namespace.md | 2 +- docs/reference/macros/delegate_components.md | 2 +- docs/reference/macros/path.md | 2 +- docs/reference/macros/product.md | 2 +- docs/reference/macros/sum.md | 2 +- docs/reference/macros/symbol.md | 10 +- docs/reference/providers/chain_getters.md | 2 +- .../dispatch/match_with_field_handlers.md | 2 +- docs/reference/providers/redirect_lookup.md | 4 +- docs/reference/traits/builder/build_field.md | 2 +- docs/reference/traits/builder/update_field.md | 2 +- docs/reference/traits/casting/can_downcast.md | 2 +- docs/reference/traits/casting/can_upcast.md | 2 +- .../traits/field-access/field_mapper.md | 4 +- .../traits/field-access/has_field.md | 6 +- .../traits/field-access/has_field_mut.md | 4 +- .../traits/field-access/map_field.md | 4 +- .../traits/field-access/mut_field_getter.md | 2 +- .../traits/formatting/concat_path.md | 2 +- .../traits/formatting/static_format.md | 2 +- .../traits/formatting/static_string.md | 2 +- .../reference/traits/optional/set_optional.md | 2 +- docs/reference/traits/shape/has_fields.md | 6 +- docs/reference/traits/shape/to_fields.md | 4 +- .../traits/type-level/append_product.md | 2 +- .../traits/type-level/concat_product.md | 2 +- .../reference/traits/type-level/map_fields.md | 2 +- docs/reference/traits/type-level/map_type.md | 2 +- .../traits/type-level/map_type_ref.md | 2 +- .../reference/traits/variant/extract_field.md | 2 +- .../traits/variant/finalize_extract.md | 6 +- .../traits/variant/finalize_extract_result.md | 4 +- .../traits/wiring/delegate_component.md | 2 +- docs/reference/types/_category_.json | 6 +- docs/reference/types/field.md | 168 +++++++++++++- docs/reference/types/index.md | 56 ++++- docs/reference/types/index_type.md | 149 +++++++++++++ docs/reference/types/life.md | 138 +++++++++++- docs/reference/types/mref.md | 138 +++++++++++- docs/reference/types/phantom_data.md | 207 ++++++++++++++++++ docs/reference/types/spines/_category_.json | 8 + docs/reference/types/spines/chars.md | 160 ++++++++++++++ docs/reference/types/spines/cons.md | 163 ++++++++++++++ docs/reference/types/spines/either.md | 164 ++++++++++++++ docs/reference/types/spines/index.md | 65 ++++++ docs/reference/types/spines/nil.md | 127 +++++++++++ docs/reference/types/spines/path_cons.md | 164 ++++++++++++++ docs/reference/types/spines/void.md | 136 ++++++++++++ docs/reference/types/type_level_spines.md | 17 -- example-code/README.md | 2 +- .../phantom_data_a_marker_needs_the_field.rs | 7 + ...antom_data_a_marker_needs_the_field.stderr | 8 + example-code/tests/reference/mod.rs | 1 + example-code/tests/reference/types/field.rs | 34 +++ .../tests/reference/types/index_type.rs | 26 +++ example-code/tests/reference/types/life.rs | 19 ++ example-code/tests/reference/types/mod.rs | 12 + example-code/tests/reference/types/mref.rs | 29 +++ .../tests/reference/types/phantom_data.rs | 80 +++++++ .../tests/reference/types/spines/chars.rs | 58 +++++ .../tests/reference/types/spines/cons.rs | 40 ++++ .../tests/reference/types/spines/either.rs | 50 +++++ .../tests/reference/types/spines/mod.rs | 8 + .../tests/reference/types/spines/nil.rs | 25 +++ .../tests/reference/types/spines/path_cons.rs | 40 ++++ .../tests/reference/types/spines/void.rs | 21 ++ 74 files changed, 2355 insertions(+), 126 deletions(-) create mode 100644 docs/reference/types/index_type.md create mode 100644 docs/reference/types/phantom_data.md create mode 100644 docs/reference/types/spines/_category_.json create mode 100644 docs/reference/types/spines/chars.md create mode 100644 docs/reference/types/spines/cons.md create mode 100644 docs/reference/types/spines/either.md create mode 100644 docs/reference/types/spines/index.md create mode 100644 docs/reference/types/spines/nil.md create mode 100644 docs/reference/types/spines/path_cons.md create mode 100644 docs/reference/types/spines/void.md delete mode 100644 docs/reference/types/type_level_spines.md create mode 100644 example-code/tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.rs create mode 100644 example-code/tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.stderr create mode 100644 example-code/tests/reference/types/field.rs create mode 100644 example-code/tests/reference/types/index_type.rs create mode 100644 example-code/tests/reference/types/life.rs create mode 100644 example-code/tests/reference/types/mod.rs create mode 100644 example-code/tests/reference/types/mref.rs create mode 100644 example-code/tests/reference/types/phantom_data.rs create mode 100644 example-code/tests/reference/types/spines/chars.rs create mode 100644 example-code/tests/reference/types/spines/cons.rs create mode 100644 example-code/tests/reference/types/spines/either.rs create mode 100644 example-code/tests/reference/types/spines/mod.rs create mode 100644 example-code/tests/reference/types/spines/nil.rs create mode 100644 example-code/tests/reference/types/spines/path_cons.rs create mode 100644 example-code/tests/reference/types/spines/void.rs diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index fa2c2fb0..0d9f191d 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -50,7 +50,7 @@ pub struct Person { Each named field becomes a [`Symbol!`](../macros/symbol.md) tag and its declared type becomes the value that tag holds. A tuple struct works the same way with positional tags: a field at position `N` is keyed by -[`Index`](../types/index.md), so its builder step is +[`Index`](../types/index_type.md), so its builder step is `build_field(PhantomData::>, value)`. Generic parameters, lifetimes, and a `where` clause are carried onto the companion type and every generated impl. diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index dcd4746c..14469ae6 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -47,7 +47,7 @@ pub enum Shape { Naming follows the family's rules: a named struct field or a variant is keyed by [`Symbol!`](../macros/symbol.md), and a positional field of a tuple struct by -[`Index`](../types/index.md). Generic parameters, lifetimes, and a `where` clause are carried onto +[`Index`](../types/index_type.md). Generic parameters, lifetimes, and a `where` clause are carried onto everything generated, including the companion types. ### What each shape emits, and where it is documented diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index 8d86a900..c5c6d83a 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -38,7 +38,7 @@ pub struct Person { ``` **Every struct shape is accepted.** A named-field struct is keyed by -[`Symbol!`](../macros/symbol.md), a tuple struct by [`Index`](../types/index.md), and a fieldless +[`Symbol!`](../macros/symbol.md), a tuple struct by [`Index`](../types/index_type.md), and a fieldless struct is the degenerate case rather than an error. Its companion type takes no parameters at all, so `builder()` is immediately finalizable, because there is nothing to track. diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index a264eb44..ef68a79c 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -355,7 +355,7 @@ enum's own variant list rather than repeating it at each site. - [`MapType`](../traits/type-level/map_type.md) — the `IsPresent`/`IsVoid` markers the companion enums are parameterized by. - [`CanUpcast`](../traits/casting/can_upcast.md) — upcasting and downcasting between enums, which reuse this recursion. -- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain an enum's shape is built +- [Type-level spines](../types/spines/index.md) — the `Either`/`Void` chain an enum's shape is built from. - [Dispatch combinators](../providers/dispatch/index.md) — the providers that build an extraction chain for you, one implementation per variant. diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index d09ba8c4..fb052256 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -231,7 +231,7 @@ and, as with the other empty shapes, means a mistake shows up later rather than - [`FromVariant`](../traits/variant/from_variant.md) — the trait this generates impls of. - [`Symbol!`](../macros/symbol.md) — the tag that names a variant. - [`CanUpcast`](../traits/casting/can_upcast.md) — widening a smaller enum into a larger one, built on these constructors. -- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` chain the constructed variants +- [Type-level spines](../types/spines/index.md) — the `Either`/`Void` chain the constructed variants correspond to. The ideas behind it: diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 780e1af3..54aad656 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -57,7 +57,7 @@ its *logical* name, with the `r#` stripped: a field `r#type` is keyed by `Symbol ### Tuple fields -A tuple field has no name, so it is keyed by [`Index`](../types/index.md), the type-level number of +A tuple field has no name, so it is keyed by [`Index`](../types/index_type.md), the type-level number of its position: ```rust @@ -288,7 +288,7 @@ are easy to confuse. - [`HasField`](../traits/field-access/has_field.md) — the trait this generates, with `HasFieldMut` and the provider-side `FieldGetter`. - [`Symbol!`](../macros/symbol.md) — the tag for a named field. -- [`Index`](../types/index.md) — the tag for a tuple field. +- [`Index`](../types/index_type.md) — the tag for a tuple field. - [`#[implicit]`](../attributes/implicit.md) — the idiomatic way to read a field, generating the bound for you. - [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — a named accessor over the same access. diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 2c3fdfab..3a2408a6 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -56,7 +56,7 @@ pub enum Shape { For a struct the shape is a product; for an enum it is a sum. Naming follows the same rules everywhere: a named field or a variant is keyed by [`Symbol!`](../macros/symbol.md), a positional field by -[`Index`](../types/index.md). Applying the derive to anything other than a struct or an enum is a +[`Index`](../types/index_type.md). Applying the derive to anything other than a struct or an enum is a compile error. ### Struct shapes @@ -255,10 +255,10 @@ impl ToFieldsRef for Person { ``` `Product![A, B]` is sugar for `Cons>`, which is why the bodies build a `Cons` chain. The -[type-level spines](../types/type_level_spines.md) page covers that shape, and it is the form printed in +[type-level spines](../types/spines/index.md) page covers that shape, and it is the form printed in an error. -An enum's shape is the dual: an [`Either`](../types/type_level_spines.md) chain terminated by `Void` +An enum's shape is the dual: an [`Either`](../types/spines/either.md) chain terminated by `Void` rather than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name: ```rust @@ -334,8 +334,8 @@ by one letter and the outputs do not overlap. - [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a struct and an enum shape are built from. - [`Field`](../types/field.md) — one entry: a value paired with its type-level name. -- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index.md) — the tags that name an entry. -- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains the +- [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index_type.md) — the tags that name an entry. +- [Type-level spines](../types/spines/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains the sugar expands to. - [`AppendProduct`](../traits/type-level/append_product.md) — operations over a shape once you have one. - [`CanUpcast`](../traits/casting/can_upcast.md) — converting between two types whose shapes overlap. diff --git a/docs/reference/index.md b/docs/reference/index.md index 6cfbe2e6..b1018a3d 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -15,17 +15,6 @@ time rather than building an idea up. When a page here tells you *what* a constr to know *why* CGP works that way, the [concepts](/docs/concepts/) are where each idea is explained on its own. -:::info - -### Still being written - -The construct list below is complete — every construct the `cgp` crate exports has a page, or a named -place on a page it shares — so nothing is missing from this index. The macros, attributes, derives, -traits, providers, and components are written; the type-level pages are still placeholders, and each -one says so when you open it. - -::: - ## Start with these six Most CGP code uses a small number of constructs over and over. If you read nothing else here, read @@ -208,12 +197,20 @@ lightweight special case of the same mechanism, and it supersedes the older ### Understand a generated type or an error -These are the type-level building blocks the rest of CGP is made of. You mostly write them through -sugar — [`Symbol!`](./macros/symbol.md) for a field name, [`Product!`](./macros/product.md) for a list, -[`Sum!`](./macros/sum.md) for its dual, [`Path!`](./macros/path.md) for a route — and only need to -recognize [what they expand into](./types/type_level_spines.md) when it appears in an error message. -[`Index`](./types/index.md) tags a tuple field and [`Life`](./types/life.md) lifts a lifetime into a -type. Three traits turn those encodings back into runtime data: +These are the type-level building blocks the rest of CGP is made of, and the place to look when a +generated type or an error names one you did not write. [`PhantomData`](./types/phantom_data.md) is the +one to start with: it is what lets a provider or a tag carry a type it stores no value of, and it +underlies most of the rest. You write the lists through sugar — [`Symbol!`](./macros/symbol.md) for a +field name, [`Product!`](./macros/product.md) for a record list, [`Sum!`](./macros/sum.md) for its dual, +[`Path!`](./macros/path.md) for a route — and only need to recognize the +[list spines](./types/spines/index.md) they expand into, [`Cons`](./types/spines/cons.md) and +[`Nil`](./types/spines/nil.md), [`Either`](./types/spines/either.md) and +[`Void`](./types/spines/void.md), [`Chars`](./types/spines/chars.md), and +[`PathCons`](./types/spines/path_cons.md), when one shows up in an error. Each entry in a record or a +variant is a [`Field`](./types/field.md), tagged by a [`Symbol!`](./macros/symbol.md) or an +[`Index`](./types/index_type.md), and [`Life`](./types/life.md) lifts a lifetime into a type where the +wiring needs one. [`MRef`](./types/mref.md) is the odd one out, a runtime value a getter returns rather +than a type-level marker. Three traits turn those encodings back into runtime data: [`StaticString`](./traits/formatting/static_string.md) decodes a type-level string into a constant, [`StaticFormat`](./traits/formatting/static_format.md) writes one into a formatter and is what makes it printable at all, and [`ConcatPath`](./traits/formatting/concat_path.md) joins two paths. @@ -235,7 +232,7 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w |---|---| | `#[cgp_new_provider]` | [`#[cgp_provider]`](./macros/cgp_provider.md) | | `WithType`, `WithField`, `WithContext` | [`WithProvider`](./providers/with_provider.md) | -| `Cons`, `Nil`, `Either`, `Void`, `Chars`, `PathCons` | [Type-level spines](./types/type_level_spines.md) | +| `Symbol` (the type, not the `Symbol!` macro) | [`Chars`](./types/spines/chars.md) | | `IdentMonadic`, `OkMonadic`, `ErrMonadic`, `OkMonadicTrans`, `ErrMonadicTrans` | [Monad providers](./providers/monad/index.md) | | `UseDelegatedType`, `WithDelegatedType` | [`UseDelegatedType`](./providers/use_delegated_type.md) and [`WithProvider`](./providers/with_provider.md) | | `MatchWithHandlersRef`, `MatchFirstWithHandlers`, and the other borrowed and first-argument matcher forms | the matcher page they vary, under [Dispatch combinators](./providers/dispatch/index.md) | diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 516f8061..ddd22b18 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -300,7 +300,7 @@ after this impl and win where their keys are more specific. Two naming details appear verbatim in errors and are worth recognizing: the table parameter is literally `__Table__`, and the inheritance impl uses `__Key__` and `__Value__`. And every `@` path is a -[type-level list](../types/type_level_spines.md) built by [`Path!`](./path.md); `expand` resugars it to +[type-level list](../types/spines/path_cons.md) built by [`Path!`](./path.md); `expand` resugars it to `Path!(@…)` form, while a raw compiler error prints the underlying spine. ## Formal grammar diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 4b307baf..1a93a3ee 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -531,7 +531,7 @@ lookup appends after it, so one entry answers the redirect without having to pre the path reaching it. One presentational quirk is worth knowing before you compare these listings against your own expansion. -Both paths above are [`PathCons`](../types/type_level_spines.md) lists, but `cargo cgp expand` prints +Both paths above are [`PathCons`](../types/spines/path_cons.md) lists, but `cargo cgp expand` prints them differently: it resugars the header's redirect target to [`Path!`](./path.md) form while leaving the per-entry key as the raw spine. So the same kind of type appears in two spellings in one expansion. diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index e02c2f47..9f5e89a9 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -219,7 +219,7 @@ the check rather than at the definition. - [`delegate_components!`](./delegate_components.md) — `@`-path keys and the `open` statement that builds routes for you. - [`Symbol!`](./symbol.md) — what a lowercase segment becomes. -- [Type-level spines](../types/type_level_spines.md) — the `PathCons` chain the expansion builds. +- [Type-level spines](../types/spines/index.md) — the `PathCons` chain the expansion builds. - [`Product!`](./product.md) and [`Sum!`](./sum.md) — the sibling construction macros, sharing the fold shape. - [`DelegateComponent`](../traits/wiring/delegate_component.md) — the per-key table a resolved path finally reads. diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 7cd06d16..a3adebcb 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -192,7 +192,7 @@ the order *is* the execution order. ## Related constructs - [`Sum!`](./sum.md) — the dual, for a choice among types rather than a collection of them. -- [Type-level spines](../types/type_level_spines.md) — the `Cons`/`Nil` types the expansion builds. +- [Type-level spines](../types/spines/index.md) — the `Cons`/`Nil` types the expansion builds. - [`Field`](../types/field.md) — what the entries usually are, pairing a name with a type. - [`Symbol!`](./symbol.md) — the name half of a `Field` entry. - [`HasFields`](../traits/shape/has_fields.md) — the trait that exposes a struct's shape as one of these lists. diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index b8b945c9..015e60ac 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -166,7 +166,7 @@ struct: the variant's payload type has to be a single nameable type for the sum ## Related constructs - [`Product!`](./product.md) — the dual, for a collection rather than a choice. -- [Type-level spines](../types/type_level_spines.md) — the `Either`/`Void` types the expansion builds. +- [Type-level spines](../types/spines/index.md) — the `Either`/`Void` types the expansion builds. - [`Field`](../types/field.md) — what the branches usually are, pairing a variant name with its payload. - [`Symbol!`](./symbol.md) — the name half of a branch. - [`HasFields`](../traits/shape/has_fields.md) — the trait exposing an enum's shape as one of these sums. diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 39b5872d..c71aded8 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -54,7 +54,7 @@ Self: HasField ### The tag for a tuple field A tuple-struct field has no name, so it cannot be keyed by a string. -[`#[derive(HasField)]`](../derives/derive_has_field.md) tags those with [`Index`](../types/index.md) instead +[`#[derive(HasField)]`](../derives/derive_has_field.md) tags those with [`Index`](../types/index_type.md) instead (`Index<0>`, `Index<1>`), which encodes a number at the type level the way `Symbol!` encodes a string. A field is keyed by `Symbol!` when it has a name and by `Index` when it has only a position. @@ -127,7 +127,7 @@ That is the honest summary: the construct is essential and mostly generated. - **Use [`#[cgp_auto_getter]`](./cgp_auto_getter.md) for a named accessor.** The method name becomes the tag. - **Write `Symbol!` explicitly with [`UseField`](../providers/use_field.md)**, where the whole point is that the field name is a wiring decision rather than fixed to a method name. This is its main hand-written use. -- **Use [`Index`](../types/index.md) for a tuple field**, not a `Symbol!` of `"0"`. They are different types +- **Use [`Index`](../types/index_type.md) for a tuple field**, not a `Symbol!` of `"0"`. They are different types and the derive generates the former. Two things it is not. It is **not a runtime string**: there is no `&str` inside it, and the `Display` impl @@ -151,7 +151,7 @@ Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>> Two type constructors do the work. `Chars` is one character paired with the rest of the string; chained through its tail and terminated by `Nil`, it forms a -[type-level list](../types/type_level_spines.md) of characters, the same shape as +[type-level list](../types/spines/chars.md) of characters, the same shape as [`Product!`](./product.md)'s `Cons`/`Nil` spine, specialized so the head is a `const char` rather than a type. `Symbol` then wraps that list together with a length. @@ -208,13 +208,13 @@ type argument rather than the value. ## Related constructs -- [`Index`](../types/index.md) — the position-keyed tag for tuple-struct fields. +- [`Index`](../types/index_type.md) — the position-keyed tag for tuple-struct fields. - [`HasField`](../traits/field-access/has_field.md) — what a tag is looked up through. - [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates one tag per named field. - [`#[implicit]`](../attributes/implicit.md) — generates the tag from an argument name. - [`#[cgp_auto_getter]`](./cgp_auto_getter.md) — generates it from a method name. - [`UseField`](../providers/use_field.md) — where the tag is written by hand, as a wiring decision. -- [Type-level spines](../types/type_level_spines.md) — the `Chars`/`Nil` chain the expansion builds. +- [Type-level spines](../types/spines/index.md) — the `Chars`/`Nil` chain the expansion builds. - [`Product!`](./product.md) and [`Sum!`](./sum.md) — the record and variant lists whose entries carry these tags. - [`StaticFormat`](../traits/formatting/static_format.md) — recovering runtime text from a type-level string. diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 4a0ef5fd..3d7b4f17 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -20,7 +20,7 @@ outer getter, then the next, ending at the target field. `ChainGetters` is a foundational [`FieldGetter`](../traits/field-access/field_getter.md), so it is wired to a getter component through the [`WithProvider`](with_provider.md) adapter rather than named on its own. The list -is a type-level [`Cons`](../types/type_level_spines.md) spine whose elements are each a field getter for +is a type-level [`Cons`](../types/spines/cons.md) spine whose elements are each a field getter for the value the previous step produced, written with the [`Product!`](../macros/product.md) macro. `ChainGetters` recurses down the list. Like every CGP provider, it carries no runtime value: it is a marker named in wiring. diff --git a/docs/reference/providers/dispatch/match_with_field_handlers.md b/docs/reference/providers/dispatch/match_with_field_handlers.md index a0deeecc..2f671dcf 100644 --- a/docs/reference/providers/dispatch/match_with_field_handlers.md +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -60,7 +60,7 @@ pub type MatchWithFieldHandlers = The per-variant list is built from a context's field list by three cooperating traits. `MapFieldHandler` is a type-level function from a field's `Tag` to the adapter that should handle it; `ToFieldHandlers` -walks the [sum spine](../../types/type_level_spines.md) of a field list and applies that function to each +walks the [sum spine](../../types/spines/either.md) of a field list and applies that function to each field, producing a [`Product!`](../../macros/product.md) list of adapters; and `HasFieldHandlers` reads a context's [`HasFields`](../../traits/shape/has_fields.md) list and runs `ToFieldHandlers` over it: diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 414a0b49..b528136f 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -61,7 +61,7 @@ delegate_components! { ``` A `RedirectLookup` later walks the path-keyed entry above (`@bar.baz`). The path itself is a -[`PathCons`](../types/type_level_spines.md) chain of [`Symbol!`](../macros/symbol.md) segments, most +[`PathCons`](../types/spines/path_cons.md) chain of [`Symbol!`](../macros/symbol.md) segments, most easily written with [`Path!`](../macros/path.md). ## Examples @@ -153,7 +153,7 @@ table. - [`delegate_components!`](../macros/delegate_components.md) — the `open` and `namespace` statements that generate the redirect entries. - [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table the lookup reads. -- [`Path!`](../macros/path.md) and [`PathCons`](../types/type_level_spines.md) — the type-level path it +- [`Path!`](../macros/path.md) and [`PathCons`](../types/spines/path_cons.md) — the type-level path it walks. - [`UseContext`](use_context.md) — the other `#[cgp_component]`-generated provider, routing back to the context. diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index 61423ca5..e04951f3 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -152,7 +152,7 @@ detectable at the end, since any prefix of a chain is a legal partial value. - [`MapType`](../type-level/map_type.md) — the `IsNothing`/`IsPresent` markers this moves between. - [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the `UpdateField` impls behind it. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that name a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that name a field. The ideas behind it: diff --git a/docs/reference/traits/builder/update_field.md b/docs/reference/traits/builder/update_field.md index b2fc828c..b2696029 100644 --- a/docs/reference/traits/builder/update_field.md +++ b/docs/reference/traits/builder/update_field.md @@ -168,7 +168,7 @@ with the tag fully expanded rather than saying the field does not exist. field. - [`SetOptional`](../optional/set_optional.md) — a transition this covers and the directional traits do not. - [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the per-field impls. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that name a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that name a field. The ideas behind it: diff --git a/docs/reference/traits/casting/can_downcast.md b/docs/reference/traits/casting/can_downcast.md index 531f974a..590656c3 100644 --- a/docs/reference/traits/casting/can_downcast.md +++ b/docs/reference/traits/casting/can_downcast.md @@ -138,7 +138,7 @@ stored where the original was. - [`HasExtractor`](../variant/has_extractor.md) — where the walk starts. - [`FromVariant`](../variant/from_variant.md) — how a matched variant is rebuilt into the target. - [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) — what makes an enum eligible. -- [Type-level spines](../../types/type_level_spines.md) — the `Either`/`Void` chain underneath. +- [Type-level spines](../../types/spines/index.md) — the `Either`/`Void` chain underneath. The ideas behind it: diff --git a/docs/reference/traits/casting/can_upcast.md b/docs/reference/traits/casting/can_upcast.md index 1c089008..4096e95f 100644 --- a/docs/reference/traits/casting/can_upcast.md +++ b/docs/reference/traits/casting/can_upcast.md @@ -139,7 +139,7 @@ value type are both part of the entry. - [`ExtractField`](../variant/extract_field.md) and [`FromVariant`](../variant/from_variant.md) — the two primitives the recursion routes through. - [`HasFields`](../shape/has_fields.md) — the variant shape being walked. -- [Type-level spines](../../types/type_level_spines.md) — the `Either`/`Void` chain underneath. +- [Type-level spines](../../types/spines/index.md) — the `Either`/`Void` chain underneath. - [Dispatch combinators](../../providers/dispatch/index.md) — where casting meets per-variant routing. The ideas behind it: diff --git a/docs/reference/traits/field-access/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md index f48afaa7..f8dcda8e 100644 --- a/docs/reference/traits/field-access/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -134,7 +134,7 @@ whether composing the existing ones does the job. that its consumer-side twin needs only one of: - the **tag** must be `'static`, which is free — a [`Symbol!`](../../macros/symbol.md) or an - [`Index`](../../types/index.md) is `'static` by construction; + [`Index`](../../types/index_type.md) is `'static` by construction; - the **getter** — that is, `Self`, the provider — must be `'static`, which is also free, since a provider is a zero-sized marker type with no lifetime parameters in the ordinary case. @@ -172,7 +172,7 @@ failure when it happens. - [`HasField`](./has_field.md) — the consumer side of field access. - [`UseField`](../../providers/use_field.md) and [`UseContext`](../../providers/use_context.md) — the two providers a chain is usually built from. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags, `'static` by construction. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags, `'static` by construction. - [`MRef`](../../types/mref.md) — the return type for a getter that may produce rather than lend. The ideas behind it: diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index 04e0dee3..62f73b28 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -44,7 +44,7 @@ pub trait HasField { ``` `Tag` is a type-level name: [`Symbol!("field_name")`](../../macros/symbol.md) for a named field, -[`Index`](../../types/index.md) for a tuple field. `Value` is the field's type, exposed as an associated +[`Index`](../../types/index_type.md) for a tuple field. `Value` is the field's type, exposed as an associated type so a bound can pin it or leave it open — `HasField` accepts a field of any type, while `HasField` requires a `String`. `get_field` takes `&self` and returns `&Self::Value`, a borrow of the field; its `PhantomData` argument carries no data and only @@ -186,7 +186,7 @@ The remaining blanket impls belong to the neighbours: [`HasFieldMut`](./has_fiel nothing to do with each other, and a mismatch reports as a missing `HasField` bound rather than as a typo. This is the usual cause of a read that "should" work. -**A tuple field is keyed by [`Index`](../../types/index.md), never by a `Symbol!` of the number.** +**A tuple field is keyed by [`Index`](../../types/index_type.md), never by a `Symbol!` of the number.** `Index<0>` and `Symbol!("0")` are different types. **`Value` can be pinned or left open.** Omitting `Value = T` when you meant to pin it produces an @@ -208,7 +208,7 @@ parameter is owned. - [`FieldGetter`](./field_getter.md) — the provider-side mirror that gets wired. - [`MapField`](./map_field.md) — the lifetime-safe form for reaching into a nested value. - [`HasFields`](../shape/has_fields.md) — the plural, whole-shape counterpart. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that key a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that key a field. - [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to read a field. - [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../../macros/cgp_getter.md) — getter traits over the same access. diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index 144c5e66..d7bf00ae 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -140,7 +140,7 @@ the lifetime rather than the field. **`Value` lives on the supertrait.** Pin it as `HasFieldMut` — the associated type is inherited, not redeclared. -**A tuple field is keyed by [`Index`](../../types/index.md)**, exactly as for the immutable form. +**A tuple field is keyed by [`Index`](../../types/index_type.md)**, exactly as for the immutable form. ## Related constructs @@ -148,7 +148,7 @@ type is inherited, not redeclared. - [`MutFieldGetter`](./mut_field_getter.md) — the provider-side mirror of this trait. - [`#[derive(HasField)]`](../../derives/derive_has_field.md) — generates both impls per field. - [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to reach a field, including mutably. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that key a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that key a field. - [`UseField`](../../providers/use_field.md) — the provider that implements the wired form. The ideas behind it: diff --git a/docs/reference/traits/field-access/map_field.md b/docs/reference/traits/field-access/map_field.md index 65d8f26d..25d309f0 100644 --- a/docs/reference/traits/field-access/map_field.md +++ b/docs/reference/traits/field-access/map_field.md @@ -136,7 +136,7 @@ say — and even then the existing ones usually compose. ``` The bound is on the *tag*, not on the value, and that is the point. A tag is a -[`Symbol!`](../../macros/symbol.md) or an [`Index`](../../types/index.md), both of which are `'static` by +[`Symbol!`](../../macros/symbol.md) or an [`Index`](../../types/index_type.md), both of which are `'static` by construction, so the bound costs nothing. The value stays free, which is exactly what the naive chained read could not achieve. @@ -173,7 +173,7 @@ type-level list, and `MapType` names one field's storage on a partial type. - [`HasField`](./has_field.md) — the supertrait, and the plain read. - [`ChainGetters`](../../providers/chain_getters.md) — the provider that uses `map_field` to descend. - [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to read a field of the context itself. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags, which are `'static` by +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags, which are `'static` by construction. - [`MRef`](../../types/mref.md) — the return type for a getter that may produce rather than lend. - [`MapFields`](../type-level/map_fields.md) and [`MapType`](../type-level/map_type.md) — the two similarly-named traits that do diff --git a/docs/reference/traits/field-access/mut_field_getter.md b/docs/reference/traits/field-access/mut_field_getter.md index 03e113f4..2098f17b 100644 --- a/docs/reference/traits/field-access/mut_field_getter.md +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -139,7 +139,7 @@ cannot satisfy it. - [`UseField`](../../providers/use_field.md) — the provider that implements both halves. - [`#[cgp_getter]`](../../macros/cgp_getter.md) — the macro that makes a getter a full component. - [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to reach a field. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index.md) — the tags that key a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that key a field. The ideas behind it: diff --git a/docs/reference/traits/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md index 43e37d8c..b1f2e1bc 100644 --- a/docs/reference/traits/formatting/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -138,7 +138,7 @@ normalizes them. ## Related constructs - [`Path!`](../../macros/path.md) — the sugar for the paths this joins. -- [`PathCons`](../../types/type_level_spines.md) — the spine underneath. +- [`PathCons`](../../types/spines/path_cons.md) — the spine underneath. - [`ConcatProduct`](../type-level/concat_product.md) — the product-level analogue. - [`StaticString`](./static_string.md) — recovering a segment's name as text. - [`StaticFormat`](./static_format.md) — the lazy formatting counterpart. diff --git a/docs/reference/traits/formatting/static_format.md b/docs/reference/traits/formatting/static_format.md index 666688dd..e0ddf6b3 100644 --- a/docs/reference/traits/formatting/static_format.md +++ b/docs/reference/traits/formatting/static_format.md @@ -166,7 +166,7 @@ this trait is what you need when there is no value to construct. - [`StaticString`](./static_string.md) — the eager counterpart, and the one to reach for. - [`ConcatPath`](./concat_path.md) — path composition, its reachable sibling in the same group. - [`Symbol!`](../../macros/symbol.md) — the type-level string being formatted. -- [Type-level spines](../../types/type_level_spines.md) — the `Chars` chain being walked. +- [Type-level spines](../../types/spines/index.md) — the `Chars` chain being walked. - [`HasField`](../field-access/has_field.md) — where the names being decoded are used as keys. The ideas behind it: diff --git a/docs/reference/traits/formatting/static_string.md b/docs/reference/traits/formatting/static_string.md index 8fe3ee89..a9107223 100644 --- a/docs/reference/traits/formatting/static_string.md +++ b/docs/reference/traits/formatting/static_string.md @@ -127,7 +127,7 @@ means decoding each segment's symbol. - [`StaticFormat`](./static_format.md) — the lazy counterpart, behind the `Display` impls. - [`ConcatPath`](./concat_path.md) — the same recovery idea one level up, for paths. - [`Symbol!`](../../macros/symbol.md) — the type-level string this decodes, and where the `LEN` comes from. -- [Type-level spines](../../types/type_level_spines.md) — the `Chars` chain being walked. +- [Type-level spines](../../types/spines/index.md) — the `Chars` chain being walked. - [`HasField`](../field-access/has_field.md) — where the names being decoded are used as keys. - [`FinalizeOptional`](../optional/finalize_optional.md) — a real consumer, reporting a missing field by name. diff --git a/docs/reference/traits/optional/set_optional.md b/docs/reference/traits/optional/set_optional.md index 6d3c5525..6837c66d 100644 --- a/docs/reference/traits/optional/set_optional.md +++ b/docs/reference/traits/optional/set_optional.md @@ -33,7 +33,7 @@ pub trait SetOptional { ``` `Tag` is the field's type-level name, a [`Symbol!`](../../macros/symbol.md) for a named field or an -[`Index`](../../types/index.md) for a tuple field, passed at the call site as a `PhantomData` +[`Index`](../../types/index_type.md) for a tuple field, passed at the call site as a `PhantomData` argument. `Value` is the field's declared type, so a caller passes an ordinary value rather than an `Option`. Both methods take `self` and return `Self`: the field's marker stays `IsOptional` before and after, so the builder's type does not change and an optional field can be set repeatedly. The two diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index f7056de4..588f3092 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -52,7 +52,7 @@ type Fields = Product![ **It is in the prelude**, so `use cgp::prelude::*;` is enough. The shape's construction follows one rule everywhere: a named field or variant is keyed by -[`Symbol!`](../../macros/symbol.md), a positional field by [`Index`](../../types/index.md), a struct becomes +[`Symbol!`](../../macros/symbol.md), a positional field by [`Index`](../../types/index_type.md), a struct becomes a `Cons`/`Nil` product, and an enum becomes an `Either`/`Void` sum. A single-field tuple struct is the one special case, with its `Fields` the inner type directly rather than a one-element product. The [derive's page](../../derives/derive_has_fields.md) covers that and the other shapes in full. @@ -151,7 +151,7 @@ impl HasFields for Person { ``` `Product![A, B]` is `Cons>`, so a `Fields` type in an error message is a `Cons` chain -rather than the sugar — the [type-level spines](../../types/type_level_spines.md) page covers reading it. +rather than the sugar — the [type-level spines](../../types/spines/index.md) page covers reading it. An enum's shape is the dual: an `Either` chain terminated by `Void` rather than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name and carrying that variant's own fields as a nested @@ -193,7 +193,7 @@ the other reserved names. - [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the list types a shape is built from. - [`Field`](../../types/field.md) — one entry: a value paired with its type-level name. -- [Type-level spines](../../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains +- [Type-level spines](../../types/spines/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. - [`AppendProduct`](../type-level/append_product.md) — the operations that compute new shapes from old ones. - [`CanUpcast`](../casting/can_upcast.md) and [`CanBuildFrom`](../casting/can_build_from.md) — conversions between two diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index 38c9e953..7ee16b2b 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -110,7 +110,7 @@ impl ToFields for Person { ``` An error message prints that chain when structural code fails to resolve, and the -[type-level spines](../../types/type_level_spines.md) page covers reading it. +[type-level spines](../../types/spines/index.md) page covers reading it. An enum's conversion is the dual: each concrete variant is matched onto its arm of an `Either` chain terminated by `Void`, tagged with the variant name. @@ -146,7 +146,7 @@ such as a [cast](../casting/can_downcast.md). - [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. - [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md) — what a shape is made of. -- [Type-level spines](../../types/type_level_spines.md) — the `Cons` chain the conversion builds. +- [Type-level spines](../../types/spines/index.md) — the `Cons` chain the conversion builds. - [`HasBuilder`](../builder/has_builder.md) — incremental assembly, as against this wholesale conversion. The ideas behind it: diff --git a/docs/reference/traits/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md index 537daeeb..48d880dc 100644 --- a/docs/reference/traits/type-level/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -147,7 +147,7 @@ from. - [`ConcatProduct`](./concat_product.md) — the general form; append is its single-entry case. - [`MapFields`](./map_fields.md) — rewriting every entry rather than adding one. - [`Product!`](../../macros/product.md) — the sugar for the lists this operates on. -- [Type-level spines](../../types/type_level_spines.md) — the `Cons`/`Nil` chain underneath. +- [Type-level spines](../../types/spines/index.md) — the `Cons`/`Nil` chain underneath. - [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. - [`Field`](../../types/field.md) — the entries a field list is usually made of. - [`HasBuilder`](../builder/has_builder.md) — the family that moves values through the shapes this computes. diff --git a/docs/reference/traits/type-level/concat_product.md b/docs/reference/traits/type-level/concat_product.md index c493a0a2..2455f629 100644 --- a/docs/reference/traits/type-level/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -140,7 +140,7 @@ to the first one's width. - [`MapFields`](./map_fields.md) — rewriting every entry rather than adding any. - [`ConcatPath`](../formatting/concat_path.md) — the same operation over type-level paths. - [`Product!`](../../macros/product.md) — the sugar for the lists this operates on. -- [Type-level spines](../../types/type_level_spines.md) — the `Cons`/`Nil` chain underneath. +- [Type-level spines](../../types/spines/index.md) — the `Cons`/`Nil` chain underneath. - [`CanBuildFrom`](../casting/can_build_from.md) — merging the values whose shapes this combines. - [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index 232cbbf9..9b0bc803 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -158,7 +158,7 @@ width. - [`TransformMapFields`](./transform_map_fields.md) — the value-level counterpart, which actually converts the fields. - [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the sugar for both spines. -- [Type-level spines](../../types/type_level_spines.md) — the `Cons`/`Nil` and `Either`/`Void` chains +- [Type-level spines](../../types/spines/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. - [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. - [`MapField`](../field-access/map_field.md) — the similarly-named lifetime helper, which does something else entirely. diff --git a/docs/reference/traits/type-level/map_type.md b/docs/reference/traits/type-level/map_type.md index 29c96f01..0f648741 100644 --- a/docs/reference/traits/type-level/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -170,7 +170,7 @@ and transform impls are written against the standard markers, so a custom one ha - [`MapFields`](./map_fields.md) — applies one marker across a whole type-level list. - [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — generates the partial types these markers parameterize. -- [Type-level spines](../../types/type_level_spines.md) — where the uninhabited `Void` comes from. +- [Type-level spines](../../types/spines/index.md) — where the uninhabited `Void` comes from. The ideas behind it: diff --git a/docs/reference/traits/type-level/map_type_ref.md b/docs/reference/traits/type-level/map_type_ref.md index 58d6f02e..4bc77d50 100644 --- a/docs/reference/traits/type-level/map_type_ref.md +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -169,7 +169,7 @@ reads as though the machinery is at fault. - [`ToFieldsRef`](../shape/to_fields_ref.md) — the record side's answer to the same problem. - [`HasFieldsRef`](../shape/has_fields_ref.md) — the borrowed shape it produces. - [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the borrowed companion. -- [Type-level spines](../../types/type_level_spines.md) — the `Either`/`Void` chain underneath. +- [Type-level spines](../../types/spines/index.md) — the `Either`/`Void` chain underneath. The ideas behind it: diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index 822cdc5f..086d67cb 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -188,7 +188,7 @@ reason to prefer the [dispatch combinators](../../providers/dispatch/index.md). impl here. - [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain for you. -- [Type-level spines](../../types/type_level_spines.md) — `Either`/`Void`, where the uninhabited terminator +- [Type-level spines](../../types/spines/index.md) — `Either`/`Void`, where the uninhabited terminator comes from. The ideas behind it: diff --git a/docs/reference/traits/variant/finalize_extract.md b/docs/reference/traits/variant/finalize_extract.md index 8b800fed..58375f05 100644 --- a/docs/reference/traits/variant/finalize_extract.md +++ b/docs/reference/traits/variant/finalize_extract.md @@ -32,7 +32,7 @@ pub trait FinalizeExtract { `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 trait is implemented for the uninhabited -[`Void`](../../types/type_level_spines.md), the standard `Infallible`, and the all-ruled-out +[`Void`](../../types/spines/void.md), the standard `Infallible`, and the all-ruled-out configuration of a partial enum. ## Usage @@ -91,7 +91,7 @@ remainder.** The two do the same job at different points in the chain. ## Under the hood **Everything turns on what `IsVoid` maps to.** The [`MapType`](../type-level/map_type.md) marker `IsVoid` maps a -payload to the uninhabited [`Void`](../../types/type_level_spines.md), so once every variant's marker is +payload to the uninhabited [`Void`](../../types/spines/void.md), 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: @@ -143,7 +143,7 @@ that cannot occur. - [`HasExtractor`](./has_extractor.md) — where a chain begins. - [`FinalizeBuild`](../builder/finalize_build.md) — the record family's ending, sound for the opposite reason. - [`MapType`](../type-level/map_type.md) — the `IsVoid` marker the argument rests on. -- [Type-level spines](../../types/type_level_spines.md) — where the uninhabited `Void` comes from. +- [Type-level spines](../../types/spines/index.md) — where the uninhabited `Void` comes from. - [`CanUpcast`](../casting/can_upcast.md) — a cast whose total walk ends with this same discharge. - [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain. - [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates this impl. diff --git a/docs/reference/traits/variant/finalize_extract_result.md b/docs/reference/traits/variant/finalize_extract_result.md index 12fa335f..503a0b25 100644 --- a/docs/reference/traits/variant/finalize_extract_result.md +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -120,7 +120,7 @@ soundness argument lives: the remainder is uninhabited once every variant is `Is 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`](../../types/type_level_spines.md). That is occasionally useful +whose error is `Infallible` or [`Void`](../../types/spines/void.md). That is occasionally useful outside the extractor family, for collapsing a `Result` that a signature required but that cannot fail. `Output` being an associated type rather than a generic lets the call sit at the end of a method @@ -151,7 +151,7 @@ bound stops being satisfied. - [`ExtractField`](./extract_field.md) — the narrowing that produces the `Result` this collapses. - [`HasExtractor`](./has_extractor.md) — where a chain begins. - [`FinalizeBuild`](../builder/finalize_build.md) — the record family's ending. -- [Type-level spines](../../types/type_level_spines.md) — where the uninhabited `Void` comes from. +- [Type-level spines](../../types/spines/index.md) — where the uninhabited `Void` comes from. - [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain for you. - [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — what makes an enum extractable. diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index 83dac1e6..b6b21870 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -106,7 +106,7 @@ An **arbitrary type** — a shape, a tag — makes the table a plain dispatch ma attached. This is what the nested tables inside [`UseDelegate`](../../providers/use_delegate.md) are, and what the `open` statement's per-key entries resolve through. -A **type-level path** — a [`PathCons`](../../types/type_level_spines.md) list built by +A **type-level path** — a [`PathCons`](../../types/spines/path_cons.md) list built by [`Path!`](../../macros/path.md) — is how namespaces key their entries, so a lookup walks one segment at a time. [`RedirectLookup`](../../providers/redirect_lookup.md) is the provider that performs that walk. diff --git a/docs/reference/types/_category_.json b/docs/reference/types/_category_.json index ceb69b4c..78f2036d 100644 --- a/docs/reference/types/_category_.json +++ b/docs/reference/types/_category_.json @@ -1,8 +1,8 @@ { - "label": "Type-level types", + "label": "Types", "position": 7, "link": { - "type": "generated-index", - "description": "The type-level building blocks the rest of CGP is constructed from." + "type": "doc", + "id": "reference/types/index" } } diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index c9f3ef30..677edeeb 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -1,17 +1,175 @@ --- sidebar_label: 'Field' +sidebar_position: 2 --- # `Field` -A value paired with its type-level name tag. +A value paired with its type-level name tag, so a struct's fields and an enum's variants can be +described one entry at a time without naming the concrete type. :::info -### Not written yet +### Generated machinery -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +**You rarely write `Field` by hand.** The extensible-data derives — +[`#[derive(HasFields)]`](../derives/derive_has_fields.md) and the wider +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — build the `Field` entries that make up a type's +shape. You meet the type in a generated shape, in a builder or extractor error, and occasionally when +you construct one entry directly. This page explains what it is so those are legible. ::: + +## Overview + +`Field` carries a field's *name* and its *value* together in one type. A bare +[`Product!`](../macros/product.md) list such as `Product![String, u8]` records the value types and their +order, but it cannot tell `name: String` from any other `String`. Wrapping each element in a `Field`, +as `Field`, attaches the name as a type, so a struct's shape describes itself: +code walking the list matches on the tag to find the field it wants. + +The name rides as a type because it is needed only at compile time, for trait resolution and dispatch, +never at run time. A `Field` is exactly as large as its `Value`, since the tag lives in a +zero-sized [`PhantomData`](phantom_data.md), so naming a field this way costs nothing while making +field-by-field generic code possible. This is the same type-as-name trick that +[`Symbol!`](../macros/symbol.md) provides for a named field and [`Index`](index_type.md) for a tuple +position. `Field` is where that tag meets the value it labels. + +`Field` fills both structural spines. In a record it is the element of a [`Product!`](../macros/product.md) +of entries, one per field. In a variant it is the element of a [`Sum!`](../macros/sum.md) of entries, one +per variant, where the `Value` is the variant's payload. The same `Field` shape names a +field in a struct and a variant in an enum. + +## Definition + +`Field` holds the value alongside a phantom tag: + +```rust +pub struct Field { + pub value: Value, + pub phantom: PhantomData, +} +``` + +`Tag` is the type-level name of the field. It appears only inside `PhantomData` and never in a +stored field, and it is usually a type-level string such as `Symbol!("name")` for a named field or a +type-level number such as `Index<0>` for a tuple position. `Value` is the field's actual type, and +`value` is the only data the struct keeps. Apart from the tag, a `Field` is a thin wrapper around its +`Value`. + +## Behavior + +You build a `Field` from a value with no tag argument, because the tag comes from the target type rather +than from you. The `From` impl fills in `value` and sets `phantom` to `PhantomData`, so +`let f: Field = "Alice".to_string().into();` works and the tag is inferred from +the expected type. This is why generated code builds each entry with a plain `.into()`. + +The other trait impls defer to the value and ignore the tag, so a `Field` behaves like its `Value` for +comparison and printing. `Debug` forwards to the value's `Debug` and does not show the tag. +`PartialEq` and `Eq` compare only `value`, each gated on the matching bound on `Value`. Two `Field` +values are equal when their values are equal; the tag is a compile-time matter and plays no part at run +time. + +Because the tag lives only in `PhantomData`, code that needs the name reads it from the `Tag` parameter +through trait resolution, for example by matching a `Field` against a +[`HasField`](../traits/field-access/has_field.md) bound, rather than from any stored +data. + +## Examples + +`Field` appears most often inside the shape a derive generates, where each struct field becomes one +entry tagged by its [`Symbol!`](../macros/symbol.md) name: + +```rust +use cgp::prelude::*; + +#[derive(HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} + +// generated: +// impl HasFields for Person { +// type Fields = Product![ +// Field, +// Field, +// ]; +// } +``` + +A single `Field` can also be built directly from its value, with the tag supplied by the type +annotation: + +```rust +use cgp::prelude::*; + +let name: Field = "Alice".to_string().into(); +assert_eq!(name.value, "Alice"); +``` + +For a tuple-struct field the tag is an [`Index`](index_type.md) rather than a `Symbol!`, so the same +wrapper names a positional field, as `Field, u32>`. + +## When to use it + +**You read `Field` far more often than you write it.** Recognizing it in a generated shape or an error +is the common case, and it is most of what this page is for. + +- **Let the derives build it.** [`#[derive(HasFields)]`](../derives/derive_has_fields.md) and + [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) produce the `Field` entries of a type's shape, so + a type you own gets its entries from one derive rather than from a hand-written list. +- **Construct a `Field` directly** only in generic shape code of your own, where you assemble or rewrite + a record or a variant entry by entry. The `.into()` form is how you build one, and the tag comes from + the expected type. +- **Do not reach for a bare [`Product!`](../macros/product.md) of values** when you need the names. + A list of `Field` entries is what carries the names, and the operations that walk a shape match on + them. + +## Common Mistakes + +**The tag is compile-time only, so it never affects equality or printing.** Two `Field` values compare +equal when their values are equal, and `Debug` shows the value alone. If you expected the tag to +distinguish them at run time, it does not; the tag distinguishes them only in the type. + +**A `Field` is the size of its `Value`, not larger.** The tag adds no space, so wrapping a value in a +`Field` is free at run time. + +**The tag must match exactly for a lookup to resolve.** `Field` and +`Field` carry unrelated tags, so a name mismatch shows up as an unsatisfied +[`HasField`](../traits/field-access/has_field.md) bound rather than as a typo. + +## Related constructs + +- [`Symbol!`](../macros/symbol.md) — the tag for a named field or variant. +- [`Index`](index_type.md) — the tag for a tuple-struct position. +- [`PhantomData`](phantom_data.md) — where the tag is stored, at zero size. +- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the lists of `Field` entries that + describe a record and a variant. +- [Type-level spines](spines/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains those lists are + built from. +- [`HasFields`](../traits/shape/has_fields.md) — exposes a type's whole list of `Field` entries. +- [`HasField`](../traits/field-access/has_field.md) — single-field access against a matching tag. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — assigns the list of entries to a type. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where field-name entries are used at scale. +- [Extensible variants](/docs/concepts/extensible-variants) — the same entry naming a variant. + +## Source + +- The type and its `From`, `Debug`, `PartialEq`, and `Eq` impls: + [`field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/field.rs) +- Consumed by the field machinery: + [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs), + with rebuilding in + [`from_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_fields.rs) + and + [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs) +- The derive that emits `Product!`/`Sum!` lists of entries: + [`derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index bd8b1ff1..c2efbdc4 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -1,17 +1,55 @@ --- -sidebar_label: 'Index' +sidebar_label: 'Overview' +sidebar_position: 0 --- -# `Index` +# Type-level building blocks -A type-level natural number, used to tag tuple-struct fields. +The small types CGP is built out of: the markers that carry information in the type system, the +recursive lists that describe a struct or an enum, and the wrappers you meet in an expansion or an +error message. -:::info +## Overview -### Not written yet +Most CGP machinery works at the type level, where a field name, a variant, a position, or a whole +record shape is a *type* rather than a value. The types on these pages are how that is done. You write +almost none of them by hand. You meet them when you read the code a macro generated, or when a wiring +mistake prints a wall of nested types, and this section exists so that such a type is legible. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +One idea runs through nearly all of them, and it is worth holding before the rest: a type can carry +information the program never stores as a value. A struct can name a type parameter it keeps no field +of, so a name, a number, or a lifetime becomes part of a type's identity and the compiler matches on +it during trait resolution. [`PhantomData`](phantom_data.md) is the standard-library tool that makes +this legal, so it is the first page here and the mechanism the others build on. -::: +The rest divide into a few groups. + +The **markers** each attach one piece of information at the type level. [`Index`](index_type.md) turns a +tuple-field position into a type, the way [`Symbol!`](../macros/symbol.md) turns a field name into one, +and [`Life`](life.md) lifts a lifetime into a type so it can travel through machinery that only accepts +types. [`Field`](field.md) uses such a tag: it pairs a value with its type-level name, so a record or a +variant entry knows what it is called. + +The **[list spines](spines/index.md)** are the recursive lists everything structural is built from: +[`Cons`](spines/cons.md) and [`Nil`](spines/nil.md) for a record, [`Either`](spines/either.md) and +[`Void`](spines/void.md) for a variant, [`Chars`](spines/chars.md) for a string, and +[`PathCons`](spines/path_cons.md) for a routing path. You write these through the sugar — +[`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), [`Symbol!`](../macros/symbol.md), and +[`Path!`](../macros/path.md) — and read them in expansions and errors. + +One type stands apart: [`MRef`](mref.md) is an ordinary runtime value, not a type-level marker. It is +the owned-or-borrowed return type of a getter, and it is here because it is the one type in this group +you write on purpose. + +## The ideas behind them + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — where the zero-sized + provider structs that carry these markers come from. +- [Extensible records](/docs/concepts/extensible-records) — the record shape the product spine + describes. +- [Extensible variants](/docs/concepts/extensible-variants) — the variant shape the sum spine + describes. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md new file mode 100644 index 00000000..7217691f --- /dev/null +++ b/docs/reference/types/index_type.md @@ -0,0 +1,149 @@ +--- +sidebar_label: 'Index' +sidebar_position: 4 +--- + +# `Index` + +A number lifted into a type, so a tuple-struct field can be named by its position the way +[`Symbol!`](../macros/symbol.md) names a field by its string. + +## Overview + +`Index` encodes a `usize` at the type level. CGP's getter mechanism keys every field by a +*type* tag, and a tuple-struct field has no string name to turn into a [`Symbol!`](../macros/symbol.md); +it has only a position. To let positional fields use the same trait-resolution machinery as named fields, +the position itself becomes a type. `Index` is that type: it carries a `usize` as a const parameter +and nothing else, so `Index<0>`, `Index<1>`, and `Index<2>` are three distinct types standing in for the +first, second, and third fields of a tuple struct. + +Encoding the position as a type lets positional field access resolve through traits. A **context** is +the type the capability runs against, which supplies those values as its own fields. Because +`Index<0>` is a type, a context can carry a +[`HasField>`](../traits/field-access/has_field.md) impl for its first field and a +`HasField>` impl for its second side by side, and the compiler selects the right one from the +tag alone, exactly as it would for two differently-named `Symbol!` tags. `Index` is the numeric +counterpart to `Symbol!`: a field is keyed by a `Symbol!` when it has a name and by an `Index` when it +has only a position. + +`Index` carries no runtime data; it is a zero-sized marker. Its whole job is to make a number available +at the type level, so it can be a [`HasField`](../traits/field-access/has_field.md) tag, the tag of a +[`Field`](field.md) entry inside a tuple struct's shape, and the type passed inside a +[`PhantomData`](phantom_data.md) wherever a positional name is needed at compile time. + +## Definition + +`Index` is a zero-sized struct parameterized only by a const `usize`: + +```rust +#[derive(Eq, PartialEq, Clone, Copy, Default)] +pub struct Index; +``` + +`I` is the position the type represents: `Index<0>` for the field at offset zero, and so on. The struct +has no fields, so a value of `Index` carries no data and the number lives entirely in the type. The +derived `Default`, `Clone`, and `Copy` make a value trivially available when one is needed, and `Eq` and +`PartialEq` compare two values of the same `Index` as always equal, since there is nothing to differ. +`Index` also implements `Display` and `Debug`, and both print the underlying number, so `Index<0>` +displays as `0` and the position a tag stands for is visible in output and in diagnostics. + +## Behavior + +A tuple struct keys each of its fields by `Index`, counting from zero, so the field at position `N` is +read through the tag `Index`. When a tuple struct derives +[`#[derive(HasField)]`](../derives/derive_has_field.md), the generated impl uses `Index<0>` for the `.0` +field, `Index<1>` for `.1`, and so on, mapping each `get_field(PhantomData::>)` call to the +matching positional access. Those tags then appear as the tag of each [`Field`](field.md) entry in the +tuple struct's [`HasFields`](../traits/shape/has_fields.md) shape, so generic code walking the field list +reads positions where it would read `Symbol!` names for a named struct. + +Because `Index` is zero-sized and the position lives in the type, accessing a field by index resolves +entirely at compile time: there is no array bound check and no runtime indexing. Selecting the wrong +index is a type error rather than a panic, because `Index<5>` on a three-field struct simply has no +matching `HasField` impl. + +## Examples + +When a tuple struct derives `HasField`, each positional field is tagged by an `Index`: + +```rust +use cgp::prelude::*; + +pub struct Pair(pub u32, pub String); + +// generated for the first field: +// impl HasField> for Pair { +// type Value = u32; +// fn get_field(&self, _tag: PhantomData>) -> &u32 { +// &self.0 +// } +// } +``` + +A field is then read by supplying the `Index` tag, and the chosen position is fixed at compile time: + +```rust +use cgp::prelude::*; + +let pair = Pair(7, "hi".to_string()); +assert_eq!(*pair.get_field(PhantomData::>), 7); +``` + +The number an `Index` carries is also visible through its `Display` impl: + +```rust +assert_eq!(Index::<2>.to_string(), "2"); +``` + +## When to use it + +**Use `Index` for a tuple-field tag, and let the derive produce it where it can.** It is generated for +every field of a tuple struct that derives [`#[derive(HasField)]`](../derives/derive_has_field.md), and +you write it by hand only when you tag a positional field yourself. + +- **Use [`Symbol!`](../macros/symbol.md) for a named field,** not an `Index`. Named and positional fields + use different tags, and the derive generates the right one for each. +- **Write `Index` for a tuple position,** never a `Symbol!` of the number. `Symbol!("0")` is a string + tag and matches nothing on a tuple struct. +- **Read `Index` in an error as a position.** A missing `HasField>` bound names the third + field of a tuple struct. + +## Common Mistakes + +**`Index` and `Symbol!("N")` are different types.** A tuple field is keyed by the number lifted into a +type, not by a string of the digit, so `Symbol!("0")` never matches a tuple field and the derive never +generates it. + +**Indices count from zero.** `Index<0>` is the first field, matching Rust's own `.0` access. An +off-by-one here reports as a missing `HasField` impl rather than an out-of-range error. + +**Selecting a position that does not exist is a type error, not a panic.** `Index<5>` on a three-field +struct has no `HasField` impl, so the mistake is caught at compile time. + +## Related constructs + +- [`Symbol!`](../macros/symbol.md) — the string tag for a named field, the counterpart to this numeric + one. +- [`HasField`](../traits/field-access/has_field.md) — what a tag is looked up through. +- [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates an `Index` tag per tuple field. +- [`Field`](field.md) — carries an `Index` tag beside a positional value. +- [`PhantomData`](phantom_data.md) — how an `Index` tag is passed to `get_field`. +- [`HasFields`](../traits/shape/has_fields.md) — the tuple struct's shape whose entries this tag names. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where positional field access is used at + scale. + +## Source + +- The type and its `Display` and `Debug` impls: + [`index.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/index.rs) +- The `#[derive(HasField)]` codegen that tags tuple fields with `Index`: + [`cgp_data/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data), + and the `HasField` trait it targets: + [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index 34b4fd71..d3264809 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -1,17 +1,145 @@ --- sidebar_label: 'Life' +sidebar_position: 5 --- # `Life` -A lifetime lifted into a type. +A lifetime lifted into a type, so a lifetime parameter can travel through machinery that only accepts +types. :::info -### Not written yet +### Generated machinery -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +**You are not expected to write `Life` by hand.** The component-defining macros, principally +[`#[cgp_component]`](../macros/cgp_component.md), insert it when a trait carries a lifetime. You meet it +in a generated provider trait and in a provider-resolution error, and this page explains why it is there. ::: + +## Overview + +`Life<'a>` exists because CGP's wiring is parameterized by *types*, not lifetimes, yet a CGP trait may +carry a lifetime of its own. The marker that surfaces a provider's dependencies, +[`IsProviderFor`](../traits/wiring/is_provider_for.md), takes a tuple of the trait's generic parameters as +one type argument, so the compiler can match a provider against the exact instantiation it is asked for. +A lifetime cannot sit in that tuple, because a tuple is a type and its members must be types. So a +lifetime parameter on the trait must first become a type, and `Life<'a>` is that conversion: it packages +the lifetime `'a` as a concrete type that can stand alongside the trait's other type parameters. + +Without this lift, a trait that borrows could not record its lifetime in the dependency marker, and the +wiring could not tell one lifetime instantiation from another. Here a **context** is the type the +capability runs against. `Life` lets the lifetime ride through `IsProviderFor` as `(Life<'a>, T)`, +keeping it part of the provider's identity while the marker's argument stays a plain type. + +## Definition + +`Life` is a tuple struct wrapping a single phantom marker over a raw pointer to a borrowed unit: + +```rust +pub struct Life<'a>(pub PhantomData<*mut &'a ()>); +``` + +The struct holds no runtime data. Its only job is to carry the lifetime `'a` in the type system through +[`PhantomData`](phantom_data.md). The choice of `PhantomData<*mut &'a ()>` is deliberate and controls how +`Life<'a>` relates to other lifetimes under subtyping. A `*mut T` is *invariant* in `T`, so wrapping +`&'a ()` behind a `*mut` makes `Life<'a>` invariant in `'a`: a `Life<'long>` is neither a subtype nor a +supertype of a `Life<'short>`. Invariance is correct here because the lifetime is an exact identity in +the dependency marker. Two providers wired for different lifetimes must be treated as wired for genuinely +different things, and a variant `Life` would let the compiler coerce one instantiation into another and +pick the wrong provider. The raw pointer also keeps `Life<'a>` from carrying auto-trait obligations tied +to a real borrow, since it neither owns nor references a real value. + +## Behavior + +`Life` has no methods and implements no CGP traits of its own; its entire behavior is to occupy a type +position. In a generated provider trait for a component with a lifetime, the lifetime is collected into +the [`IsProviderFor`](../traits/wiring/is_provider_for.md) argument tuple as `Life<'a>`, so the provider's +dependency obligation reads the same way it would for any type parameter. The provider trait, its blanket +forwarding impl, and the impls that satisfy it all agree on the same `(Life<'a>, T)` shape, which is what +lets a borrowing component be wired and checked exactly like a non-borrowing one. + +## Examples + +`Life` appears in the wiring generated for a component whose consumer trait carries a lifetime. Given a +borrowing getter component: + +```rust +use cgp::prelude::*; + +#[cgp_component(ReferenceGetter)] +pub trait HasReference<'a, T: 'a + ?Sized> { + fn get_reference(&self) -> &'a T; +} +``` + +the generated provider trait records the lifetime in its dependency marker through `Life`, so its +`IsProviderFor` bound names the lifetime as the type `Life<'a>` rather than as a bare `'a`: + +```rust +// generated, in readable form: +// pub trait ReferenceGetter<'a, __Context__, T: 'a + ?Sized>: +// IsProviderFor, T)> +// { +// fn get_reference(__context__: &__Context__) -> &'a T; +// } +``` + +Every impl that wires this component, whether through `UseContext`, a `UseField` getter, or a +hand-written provider, carries the same `(Life<'a>, T)` tuple, so the lifetime is preserved end to end +through the resolution machinery. + +## When to use it + +**You read `Life` in generated code; you do not write it.** The macros insert it, and recognizing it is +all that is asked. + +- **Read `Life<'a>` in an `IsProviderFor` tuple as the component's lifetime.** A dependency marker such + as `IsProviderFor<..., (Life<'a>, T)>` is naming a lifetime and a type parameter, in that order. +- **Do not substitute a bare [`PhantomData`](phantom_data.md) for it** when you write a lifetime marker + by hand. A plain `PhantomData<&'a ()>` is covariant, which is the wrong relationship for a dependency + marker; `Life` forces the invariance that keeps two lifetime instantiations distinct. + +## Common Mistakes + +**A lifetime cannot appear directly in the `IsProviderFor` tuple.** The tuple holds types, so a bare +`'a` is invalid there and is lifted into `Life<'a>`. Meeting `Life` in an error is the sign a component +carries a lifetime. + +**`Life<'a>` is invariant in `'a`, on purpose.** It does not behave like `&'a ()`, which is covariant. +The invariance is what keeps providers wired for different lifetimes from being confused, so it is a +feature rather than an over-restriction. + +**A higher-order provider with a lifetime loses its dependency propagation.** The inner-provider bound of +such a stack gets no marker counterpart when the component carries a lifetime, because the rewrite reads +the bound's first generic argument as the context and finds a lifetime there. The stack still compiles +and runs; what is lost is the propagation that lets `#[check_providers]` localize a broken layer. This is +a recorded limitation, noted on [`IsProviderFor`](../traits/wiring/is_provider_for.md). + +## Related constructs + +- [`IsProviderFor`](../traits/wiring/is_provider_for.md) — whose parameter tuple a lifetime is lifted + into as `Life<'a>`. +- [`#[cgp_component]`](../macros/cgp_component.md) — inserts `Life` when a consumer trait carries a + lifetime. +- [`PhantomData`](phantom_data.md) — the marker `Life` is built from, wrapped for invariance. +- [`Index`](index_type.md) and [`Chars`](spines/chars.md) — the other lifts that make a non-type + addressable in trait resolution, a number and a string where `Life` lifts a lifetime. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the provider-trait + machinery whose dependency marker carries this lift. + +## Source + +- The type: + [`life.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/life.rs) +- The macro logic that wraps a trait's lifetime parameters in `Life` when building the `IsProviderFor` + argument tuple: + [`is_provider_params.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/is_provider_params.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 8779979f..3d5591cb 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -1,17 +1,141 @@ --- sidebar_label: 'MRef' +sidebar_position: 6 --- # `MRef` -An owned-or-borrowed getter value. +A "maybe-reference": a value that is either a borrow of a `T` or an owned `T`, so a getter can return +whichever it has without forcing every implementor to one or the other. -:::info +## Overview -### Not written yet +`MRef<'a, T>` lets one getter signature serve both the context that already stores a value and the +context that must produce one. Here a **context** is the type the capability runs against, which supplies +the values it needs as its own fields. A getter that returns `&'a T` forces every context to keep a `T` +it can lend; a getter that returns `T` forces every context to hand over ownership, cloning even when it +has a perfectly good reference to share. `MRef<'a, T>` removes that dilemma by being either case at run +time: a context with the value in a field returns `MRef::Ref` and lends it, while a context that computes +or assembles the value returns `MRef::Owned` and gives it away. The caller treats both the same, because +`MRef` derefs to `T`. -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. +The type earns its place in CGP's getter machinery, where a getter method's return type decides what body +the macro generates. When a getter returns `MRef<'a, T>` over `&self`, the generated accessor wraps the +borrowed field as `MRef::Ref(...)`, so the common case, reading a stored field, costs nothing extra, +while the same interface still lets a provider elsewhere return an owned value. This lets a +getter abstract over "do I have this value, or do I make it?" without splitting into two traits. -::: +Unlike the rest of this section, `MRef` is an ordinary runtime value rather than a type-level marker. +It is here because it is the one type in the group you write on purpose, as the return type of a getter. + +## Definition + +`MRef` is a two-variant enum parameterized by a lifetime and an element type: + +```rust +pub enum MRef<'a, T> { + Ref(&'a T), + Owned(T), +} +``` + +`Ref` borrows a `T` for the lifetime `'a`; `Owned` carries a `T` by value. The lifetime applies only to +the borrowed case, so an `MRef` built from an owned value is effectively unbounded in `'a`. It is an +ordinary owned value, with nothing type-level about it, and it is the payload a getter passes back to its +caller. + +## Behavior + +`MRef` behaves like a smart pointer to `T`, which makes the two variants interchangeable at the +call site. It implements `Deref` by matching on the variant and returning a `&T` either way, +so `&*my_ref` and any auto-deref method call work regardless of which case is inside. It also implements +`AsRef` over the same logic, giving an explicit `as_ref()` for code that prefers it. + +Building an `MRef` is frictionless, because it implements `From` in both directions: `From` builds +`Owned` and `From<&'a T>` builds `Ref`, so a value or a reference converts with `.into()`. When a caller +needs ownership unconditionally, `get_or_clone` resolves the enum to a plain `T`, returning the owned +value as is or cloning the borrowed one, and is available whenever `T: Clone`. These three pieces, the +transparent `Deref` and `AsRef`, the two `From` impls, and `get_or_clone`, are the whole surface: a +borrowed `MRef` is read cheaply and promoted to ownership only when asked. + +## Examples + +`MRef` is the return type of a getter that should work whether the context stores the value or produces +it. A borrowed field and a freshly built value have the same type and are read the same way: + +```rust +use cgp::prelude::*; + +let stored = String::from("hello"); + +// a context lending a stored value: +let borrowed: MRef<'_, String> = MRef::from(&stored); +assert_eq!(&*borrowed, "hello"); + +// a provider returning a freshly built value through the same type: +let made: MRef<'_, String> = MRef::from(String::from("world")); +assert_eq!(made.as_ref(), "world"); + +// promote either to an owned value when ownership is required: +let owned: String = borrowed.get_or_clone(); +assert_eq!(owned, "hello"); +``` + +Both `borrowed` and `made` have the same type and are consumed the same way; only the construction +differs, and `get_or_clone` clones the borrowed case while moving the owned one. + +## When to use it + +**Return `MRef<'a, T>` from a getter that some contexts store and others build.** It is the getter return +mode to reach for when the value is not always a field the context can lend. + +- **Use a plain `&T` return** when every context stores the value and can lend it. `MRef` earns its keep + only where some context must produce the value instead. +- **Use an [`#[implicit]`](../attributes/implicit.md) argument** to read a stored field in a provider, + which is the default for field access; an implicit argument can itself be typed `MRef<'_, T>` when the + field may be lent or produced. +- **Reach for `MRef` with [`#[cgp_getter]`](../macros/cgp_getter.md)** and the + [`UseField`](../providers/use_field.md) family, where a getter's return type selects the accessor the + macro generates. + +## Common Mistakes + +**`MRef` is not related to [`Life`](life.md).** Its `'a` is an ordinary borrow lifetime on a runtime +value; `Life<'a>` is a zero-sized type-level lift for provider wiring. The shared word "lifetime" is the +only thing they have in common. + +**`get_or_clone` clones only the borrowed case.** It moves an `Owned` value and clones a `Ref` one, so it +is free when the getter already owns the value and costs a clone when it borrowed. Reach for it only when +you genuinely need ownership. + +**`Deref` makes the variants transparent, so you rarely match on them.** Reading through `&*` or +`as_ref()` works whichever case is inside, and matching on `Ref` versus `Owned` by hand is usually a sign +the value should have been promoted with `get_or_clone` instead. + +## Related constructs + +- [`#[cgp_getter]`](../macros/cgp_getter.md) — the getter component whose return type may be `MRef`. +- [`UseField`](../providers/use_field.md) and [`UseFieldRef`](../providers/use_field_ref.md) — the + providers that wire a getter, and the by-reference variant. +- [`HasField`](../traits/field-access/has_field.md) — the field access an `MRef` getter builds on. +- [`#[implicit]`](../attributes/implicit.md) — the default way to read a field, which also accepts an + `MRef` type. +- [`Life`](life.md) — a different, type-level use of a lifetime, not to be confused with this one. + +The ideas behind it: + +- [Implicit arguments](/docs/concepts/implicit-arguments) — reading a value out of a context, which is + what an `MRef` getter returns. + +## Source + +- The type, with its `Deref`, `AsRef`, the two `From` impls, and `get_or_clone`: + [`mref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/mref.rs) +- The macro logic that recognizes an `MRef<'a, T>` getter return type: + [`field/parse.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/field/parse.rs), + with the `MRef::Ref(...)` body emitted by + [`getter/field_mode.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/getter/field_mode.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/phantom_data.md b/docs/reference/types/phantom_data.md new file mode 100644 index 00000000..aad93a66 --- /dev/null +++ b/docs/reference/types/phantom_data.md @@ -0,0 +1,207 @@ +--- +sidebar_label: 'PhantomData' +sidebar_position: 1 +--- + +# `PhantomData` + +The standard-library marker that lets a type carry a type parameter it stores no value of. It is what +makes CGP's zero-sized providers and type-level markers legal, and it is the token you pass to hand a +type to a function. + +## Overview + +`PhantomData` is not a CGP type. It comes from the Rust standard library, in +[`core::marker`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html). It appears so often in +CGP code, and does a job so specific, that it is worth one page explaining what it is really for, +because a reader who has only seen it as noise in a struct definition will misread half of what CGP +generates. + +CGP uses it in two ways, worked through below: **declaring** a type that is generic over something it +never stores, and **passing** a type to a function as a zero-sized token. + +## Why a marker needs it + +Rust requires every generic parameter on a type to be *used* by that type, in a field or a bound. A +type-level marker breaks that rule on purpose: it is generic over a parameter it stores no value of, +because the parameter is part of the type's identity rather than its data. + +A provider is the clearest case. `Multiply` holds no runtime data, yet it must be generic over +`Field` so the wiring can tell one instance from another. Written as a plain unit struct, it does not +compile: + +```rust +pub struct Multiply; +// error[E0392]: type parameter `Field` is never used +``` + +`PhantomData` is the fix. It is a zero-sized field that tells the compiler to treat the type as +though it holds a `Field`, so the parameter counts as used and nothing is added at run time: + +```rust +use core::marker::PhantomData; + +pub struct Multiply(pub PhantomData); +``` + +`Multiply` and `Multiply` are now distinct types the wiring can choose between, and the struct +is still zero-sized. + +## Definition + +`PhantomData` is a zero-sized unit-like struct with one type parameter: + +```rust +pub struct PhantomData; +``` + +That definition is itself the shape the previous section said the compiler rejects: a struct generic +over a `T` it stores nowhere. `PhantomData` compiles anyway because it is built into the compiler. It +carries a `#[lang = "phantom_data"]` attribute the compiler recognizes, so it alone is exempt from the +unused-parameter rule and can be the marker every other type reaches for. Those types satisfy the rule +by *holding* a `PhantomData` field rather than by being one. + +The parameter is `?Sized`, so `T` may be any type, sized or not. A value of `PhantomData` occupies +no space and holds nothing; its only content is the type `T` recorded in its own type. You construct +one by writing `PhantomData`, and you name the type it carries with a turbofish where inference cannot, +as in `PhantomData::`. + +Because the type parameter is recorded but no value of it is stored, `PhantomData` also tells the +compiler how the surrounding type relates to `T` for three purposes beyond the "used parameter" rule: +**variance** (whether a longer lifetime may stand in for a shorter one), **drop checking**, and the +**auto traits** such as `Send` and `Sync`. Most CGP markers do not care which relationship they get and +use the plain `PhantomData`. The exception is [`Life`](life.md), which wraps its lifetime as +`PhantomData<*mut &'a ()>` on purpose, to force invariance so two lifetime instantiations are treated +as genuinely different. That page explains why. + +## How CGP uses it + +The two uses are the declaring side and the passing side, and they look different in the code. + +**On the declaring side, `PhantomData` fills the field of a zero-sized type**, the way `Multiply` +above carries it. The same pattern runs through CGP's [list spines](spines/index.md): a +[`Chars`](spines/chars.md) node holds its next node in a `PhantomData`, a +[`PathCons`](spines/path_cons.md) holds both its head and tail that way, and a [`Field`](field.md) holds +its type-level name tag in a `PhantomData` beside the one real value it stores. In each case the +parameter is part of the type's identity and nothing the type keeps at run time. + +**On the passing side, `PhantomData::` is a zero-sized value that hands the type `T` to a +function.** A method that must know which field, which code, or which tag is meant takes a +`PhantomData` argument, and the caller supplies the type through it: + +```rust +// which field to read: +let name = self.get_field(PhantomData::); + +// which computation to run: +let output = context.compute(PhantomData::, input); +``` + +Here the **context** is the type the capability runs against, which supplies the values it needs as its +own fields. The `PhantomData` argument carries no data; it exists so that type inference selects the +right [`HasField`](../traits/field-access/has_field.md) impl or the right handler. You could think of it +as passing a type where a value is expected, with `PhantomData::` as the empty value that stands for +the type `T`. + +**You rarely write either role by hand; a higher-level construct produces each for you.** + +- On the declaring side, the `new` keyword of [`#[cgp_impl]`](../macros/cgp_impl.md) declares the + provider struct: a `PhantomData` field per generic parameter, or a bare `struct Foo;` when there are + none. +- On the passing side, [`#[implicit]`](../attributes/implicit.md) and + [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) read a context field without the tag, so no + `get_field(PhantomData::<...>)` appears in your code. + +You meet `PhantomData` directly only when you drop below these constructs. + +## Examples + +At a call site, `PhantomData::` selects which field a getter reads: + +```rust +use cgp::prelude::*; + +#[cgp_impl(new GreetHello)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) { + let name = self.get_field(PhantomData::); + println!("Hello, {name}!"); + } +} +``` + +This is the form you meet in an expansion rather than one you write: the idiomatic version uses an +[`#[implicit]`](../attributes/implicit.md) argument and shows no `PhantomData` at all. + +A type that carries two parameters uses one `PhantomData` over a tuple: + +```rust +pub struct Add(pub PhantomData<(Left, Right)>); +``` + +## When to use it + +**You write `PhantomData` yourself in only two places.** Everywhere else the macros insert it for you. + +- **Declare a `PhantomData` field** when you write a zero-sized struct that is generic over a type it + stores no value of, such as a provider struct you define by hand rather than through + [`#[cgp_new_provider]`](../macros/cgp_provider.md). One `PhantomData` over a tuple covers several + parameters. +- **Pass `PhantomData::`** at a call site that takes a type-level selector, such as `get_field` or a + handler's `compute`. This is the common hand-written use, and the turbofish is how you name the type + when inference cannot. +- **Reach for [`Life`](life.md), not a bare `PhantomData`, for a lifetime** you need to keep invariant. + A plain `PhantomData<&'a ()>` is covariant, which is the wrong relationship for a dependency marker. + +## Common Mistakes + +**It costs nothing at run time.** `PhantomData` is zero-sized whatever `T` is, so a struct full of +`PhantomData` fields is still zero-sized, and a `PhantomData` argument compiles to nothing. Seeing it in +a signature is not a sign of a hidden allocation. + +**`PhantomData` and `PhantomData::` differ only by whether the type is inferred.** In a struct field +the type comes from the field's declared type, so plain `PhantomData` is enough. At a call site where +nothing pins `T`, the turbofish `PhantomData::` states it, and omitting it gives a +"type annotations needed" error rather than a wrong result. + +**A bare `PhantomData<&'a ()>` is covariant.** If you write a lifetime marker by hand and let a longer +lifetime stand in for a shorter one, the compiler may pick a provider wired for a different lifetime. +Use [`Life<'a>`](life.md), whose `PhantomData<*mut &'a ()>` forces invariance, when the lifetime is an +exact identity. + +**A generic marker needs its `PhantomData` field.** A struct generic over a `T` it stores no value of +fails to compile with `error[E0392]` without one. + +## Related constructs + +- [`Field`](field.md) — holds its type-level name tag in a `PhantomData` beside its value. +- [`Life`](life.md) — a lifetime lifted into a type through a deliberately invariant `PhantomData`. +- [Type-level spines](spines/index.md) — the recursive lists whose tails are `PhantomData` markers. +- [`Symbol!`](../macros/symbol.md) and [`Index`](index_type.md) — the tags a `PhantomData::` + argument usually carries. +- [`HasField`](../traits/field-access/has_field.md) — whose `get_field` takes the tag as a + `PhantomData` argument. +- [`#[cgp_new_provider]`](../macros/cgp_provider.md) — declares a provider struct's `PhantomData` field + for you. + +The ideas behind it: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — where the zero-sized + provider structs that carry `PhantomData` come from. +- [Type-level DSLs](/docs/concepts/type-level-dsls) — encoding a program as types, which is why a type + gets passed as a value at all. + +## Source + +- The type is standard-library: + [`core::marker::PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html), whose + documentation covers the variance, drop-check, and auto-trait effects in full. +- CGP re-exports it through the prelude, so `use cgp::prelude::*;` brings `PhantomData` into scope + alongside the rest. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/spines/_category_.json b/docs/reference/types/spines/_category_.json new file mode 100644 index 00000000..832c1382 --- /dev/null +++ b/docs/reference/types/spines/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Type-level list spines", + "position": 3, + "link": { + "type": "doc", + "id": "reference/types/spines/index" + } +} diff --git a/docs/reference/types/spines/chars.md b/docs/reference/types/spines/chars.md new file mode 100644 index 00000000..3c89abd6 --- /dev/null +++ b/docs/reference/types/spines/chars.md @@ -0,0 +1,160 @@ +--- +sidebar_label: 'Chars' +sidebar_position: 5 +--- + +# `Chars` + +One character of a type-level string: the spine that spells a field name out one character at a time so +the name can be a type. + +:::info + +### Generated machinery + +**You are not expected to write `Chars` by hand.** The [`Symbol!`](../../macros/symbol.md) macro folds a +string literal into a `Chars` chain, and a `Symbol` wraps that chain. You meet `Chars` in a +missing-field error, where a field name prints as its expanded character list, and this page explains how +to read it. + +::: + +## Overview + +`Chars` encodes a string as a type, so that a field name can take part in trait +resolution. CGP keys field access by a tag type: to read a field called `name`, something must stand in +for the string `"name"` at the type level, so the compiler can match one +[`HasField`](../../traits/field-access/has_field.md) impl against another purely from the tag. A `Chars` +chain is how the string becomes a type, and a `Symbol` wrapping that chain is the tag itself. + +The reason the encoding is a *list of characters* is a limit in stable Rust: a `String` or `&str` cannot +be a const-generic parameter, but a single `char` can. So CGP spells the string out one character at a +time through a recursive `Chars` spine, terminated by [`Nil`](nil.md), the same way the product spine +spells out its elements through [`Cons`](cons.md). `Chars` is the specialized form of `Cons` in which the +head is a `const char` rather than a type. + +You write this through [`Symbol!`](../../macros/symbol.md) rather than by hand. `Symbol!("abc")` folds +into `Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>`, and that macro's page carries the fold, the +byte-length parameter, and the rest of the wrapper. This page is the runtime `Chars` type underneath. + +## Definition + +`Chars` is a zero-sized struct carrying one character as a const parameter and the rest of the string as +its tail: + +```rust +pub struct Chars(pub PhantomData); +``` + +`CHAR` is the character at this position, and `Tail` is the rest of the string, expected to be either the +next `Chars` node or [`Nil`](nil.md) at the end. The character lives in the const parameter and the tail +in a [`PhantomData`](../phantom_data.md), so a `Chars` chain carries no runtime data and is erased +to a zero-sized value. A `Symbol` then wraps such a chain together with the +string's byte length; the length is stored explicitly because stable Rust cannot compute it inside a +const-generic context, and [`Symbol!`](../../macros/symbol.md) covers why. + +## Behavior + +A `Chars` chain reconstructs its original string on demand through the +[`StaticFormat`](../../traits/formatting/static_format.md) trait, which formats a type-level string into a +`Formatter` without needing a value. `Chars` writes `CHAR` and then recurses into the tail, +and [`Nil`](nil.md) ends the recursion by writing nothing. A `Symbol` forwards to its inner `Chars`, and +its `Display` impl defers to `StaticFormat`, so `::default().to_string()` yields +`"hello"`. + +The length a `Symbol` records enables [`StaticString`](../../traits/formatting/static_string.md), which +exposes the string as a `const VALUE: &'static str` rather than a formatting routine, by decoding the +characters into a byte buffer sized by that length at compile time. Code that needs the string at run +time uses `Display`; code that needs it as a const uses `StaticString`. + +## Examples + +A type-level string most often appears as the tag in a +[`HasField`](../../traits/field-access/has_field.md) bound, where it names the field a provider reads: + +```rust +use cgp::prelude::*; + +#[cgp_impl(new GreetHello)] +impl Greeter +where + Self: HasField, +{ + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData::)); + } +} +``` + +The same type can be built and inspected at run time through its `Display` impl, which walks the `Chars` +chain to rebuild the string: + +```rust +use cgp::prelude::*; + +let s = ::default(); +assert_eq!(s.to_string(), "hello"); +``` + +Because the encoding is a list, an empty string is `Symbol<0, Nil>`: a `Symbol` whose character list is +just the terminator and whose recorded length is zero. + +## When to use it + +**You read `Chars` in an error; you write [`Symbol!`](../../macros/symbol.md).** The macro produces the +chain, and the reason to know the type is to decode a field name in a diagnostic. + +- **Decode a `Chars` chain by reading off the characters.** An error mentioning + `HasField>>>` is telling you the field `width` is missing, and + `cargo cgp check` resugars the common cases. +- **Use [`Symbol!`](../../macros/symbol.md) for a field-name tag,** and let the ergonomic constructs + produce it from an argument or a method name where they can. +- **Use [`Index`](../index_type.md) for a tuple-field position,** which encodes a number rather than a + string. + +## Common Mistakes + +**The `LEN` in a wrapping `Symbol` is bytes, not characters.** For ASCII the two coincide, so the +distinction only shows on a non-ASCII field name, where `LEN` will not match the visible character count +and the `Chars` chain will be shorter than `LEN`. + +**`Chars` is zero-sized, so it holds no string at run time.** The `Display` impl rebuilds the text from +the type; there is no stored `&str` inside it. + +**A `Chars` chain is the character specialization of [`Cons`](cons.md), not a general list.** Its head is +a `const char`, so it cannot carry arbitrary element types the way a product list does. + +## Related constructs + +- [`Nil`](nil.md) — the end marker that terminates a `Chars` chain. +- [`Cons`](cons.md) — the general product spine this one specializes, with a type head rather than a + `const char`. +- [`Symbol!`](../../macros/symbol.md) — the macro that folds a string into a `Chars` chain and wraps it. +- [`StaticFormat`](../../traits/formatting/static_format.md) and + [`StaticString`](../../traits/formatting/static_string.md) — recover the runtime string and the const + from the chain. +- [`HasField`](../../traits/field-access/has_field.md) — matches a field against its `Symbol!` tag. +- [`Field`](../field.md) — carries a `Symbol!` tag beside its value. +- [`Index`](../index_type.md) — the position tag for a tuple field, the numeric counterpart. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where field-name tags are used at scale. + +## Source + +- The type: + [`chars.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/chars.rs), + with the `Symbol` wrapper in + [`symbol.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/symbol.rs) + and [`Nil`](nil.md) in + [`nil.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/nil.rs) +- The `StaticFormat` impls behind `Display`: + [`static_format.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/static_format.rs), + and the const-decoding `StaticString`: + [`static_string.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/static_string.rs) +- The constructing macro is [`Symbol!`](../../macros/symbol.md). + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/spines/cons.md b/docs/reference/types/spines/cons.md new file mode 100644 index 00000000..afdd652c --- /dev/null +++ b/docs/reference/types/spines/cons.md @@ -0,0 +1,163 @@ +--- +sidebar_label: 'Cons' +sidebar_position: 1 +--- + +# `Cons` + +The head-and-tail cell of the product spine: the recursive list that describes a record, one field at a +time. + +:::info + +### Generated machinery + +**You are not expected to write `Cons` by hand.** You build a product list with the +[`Product!`](../../macros/product.md) and `product!` macros, and a struct's field list comes from +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md). You meet `Cons` in an expansion and in a +field-mismatch error, and this page explains its shape so those read clearly. + +::: + +## Overview + +`Cons` represents an ordered sequence of types as a single type, so a collection of fields +can be reasoned about generically. A Rust tuple holds several things at once but cannot be taken apart +by generic code element by element; a recursive list can. `Cons` pairs the first element with the rest of +the list, and [`Nil`](nil.md) marks the end, so the two together form an *anonymous product type*: a +record-shaped value that code can walk without knowing the concrete struct it came from. + +This spine makes structural, field-by-field operations work across every struct uniformly. A +struct's fields are exposed as one list type through [`HasFields`](../../traits/shape/has_fields.md), so a +provider written once to recurse over `Cons` and `Nil` can iterate, transform, read, or rebuild *any* +struct's fields. Each step handles the `Head`, then recurses into the `Tail`, until it reaches `Nil` and +stops. + +You write this spine through the [`Product!`](../../macros/product.md) macro rather than by hand. +`Product![A, B, C]` is the right-nested `Cons` chain, and the value macro `product![a, b, c]` builds a +matching value. The elements are most often [`Field`](../field.md) entries pairing a name with a value, +so a struct's layout becomes a `Product!` of `Field` cells over this spine. + +## Definition + +`Cons` is a tuple struct holding the first element and the rest of the list: + +```rust +#[derive(Eq, PartialEq, Clone, Default, Debug)] +pub struct Cons(pub Head, pub Tail); +``` + +`Head` is the first element's type and `Tail` is the rest of the list, itself another `Cons` or, at the +end, [`Nil`](nil.md). Both positional fields are public, so `Cons(head, tail)` builds a cell and `.0` and +`.1` reach its parts. Unlike the zero-sized [`Chars`](chars.md) and [`PathCons`](path_cons.md) spines, +`Cons` holds real values: it is as large as its elements laid out by nesting, with nothing boxed or +virtual. It derives `Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a list of values that +implement those traits inherits them structurally, comparing head to head down the chain. + +## Behavior + +A list of any length is a `Cons` chain ending in `Nil`, nested to the right. The type `Product![A, B, C]` +is `Cons>>`, and the empty `Product![]` is just `Nil`. The matching value is +built with the tuple-struct constructor, `Cons(a, Cons(b, Cons(c, Nil)))`, so a `product!` value is an +ordinary owned value whose type is exactly the one `Product!` produces over the same elements' types. + +Generic code consumes the spine by recursing on its two cases. A trait implemented for `Nil` supplies +the base case, the empty list, and a blanket impl for `Cons` supplies the recursive step, +usually constraining `Tail` to implement the same trait so the recursion bottoms out at `Nil`. This +pairing of a `Nil` impl with a `Cons` impl is the standard shape for any operation that +folds over a product, and it is how the field machinery processes a struct of any width with no per-field +code. + +## Examples + +The product spine appears most visibly as the `Fields` of a struct that derives +[`HasFields`](../../derives/derive_has_fields.md), where the [`Product!`](../../macros/product.md) sugar +hides the `Cons`/`Nil` chain: + +```rust +use cgp::prelude::*; + +#[derive(HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} + +// generated: +// impl HasFields for Person { +// type Fields = Product![ +// Field, +// Field, +// ]; +// // i.e. Cons, +// // Cons, Nil>> +// } +``` + +A standalone list type and a matching value can also be written through the sugar, which expands to the +nested `Cons` form: + +```rust +use cgp::prelude::*; + +type Row = Product![u32, String, bool]; +let row: Row = product![1, "hi".to_string(), true]; +// Row == Cons>> +// row == Cons(1, Cons("hi".to_string(), Cons(true, Nil))) +``` + +## When to use it + +**Read `Cons` in an expansion; write [`Product!`](../../macros/product.md) instead.** The spine is what +the sugar produces, and spelling it out by hand is longer, harder to change, and identical in meaning. + +- **Use [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) for a struct's shape** rather than + declaring the `Cons` chain yourself, since a hand-written list restates the struct and the two drift + apart. +- **Use [`Product!`](../../macros/product.md) for a list you write on purpose,** such as a handler + pipeline, and let it build the spine. +- **Decode a `Cons` chain in an error by counting cells.** A field-list mismatch is reported as a + mismatch between two `Cons` chains, and the position where they diverge is the field that differs. + +## Common Mistakes + +**A one-element list is not the element.** `Product![T]` is `Cons`, a distinct type from `T`, so a +list of one still carries its cell. + +**Element order is part of the type.** `Cons>` and `Cons>` are unrelated +types. For a field list this matters less than it sounds, because the entries are name-tagged +[`Field`](../field.md)s and the operations match on names; for a handler pipeline the order is the +execution order. + +**The empty product is [`Nil`](nil.md), a real value.** That is the difference from the sum spine, whose +empty form is the uninhabited [`Void`](void.md). An empty record exists; an empty choice cannot. + +## Related constructs + +- [`Nil`](nil.md) — the end marker that terminates this spine. +- [`Either`](either.md) and [`Void`](void.md) — the sum spine, the choice-shaped dual of this one. +- [`Chars`](chars.md) — the same spine specialized to a `const char` head. +- [`Product!`](../../macros/product.md) — the macro that folds elements onto this spine. +- [`Field`](../field.md) — what the elements usually are, pairing a name with a value. +- [`HasFields`](../../traits/shape/has_fields.md) — exposes a struct's shape as one of these lists. +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates that list for a struct. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — the record representation this spine is the + backbone of. + +## Source + +- The type: + [`cons.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/cons.rs), + with [`Nil`](nil.md) in + [`nil.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/nil.rs) +- The `Product!`/`product!` folds: + [`types/product/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/product) +- The `HasFields` machinery that recurses over it: + [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/spines/either.md b/docs/reference/types/spines/either.md new file mode 100644 index 00000000..19864f4c --- /dev/null +++ b/docs/reference/types/spines/either.md @@ -0,0 +1,164 @@ +--- +sidebar_label: 'Either' +sidebar_position: 3 +--- + +# `Either` + +The head-or-rest cell of the sum spine: the recursive list that describes an enum, one variant at a +time. + +:::info + +### Generated machinery + +**You are not expected to write `Either` by hand.** You build a sum list with the +[`Sum!`](../../macros/sum.md) macro, and an enum's variant list comes from +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md). You meet `Either` in an expansion and in a +variant-mismatch error, and this page explains its shape so those read clearly. + +::: + +## Overview + +`Either` represents a choice among several types as a single type, so an enum's variants can +be reasoned about generically. Where the [product spine](cons.md) holds a value for *every* element at +once, the sum spine holds a value for exactly *one* of its branches: a tagged union, or *anonymous sum +type*. `Either` branches at each step, and [`Void`](void.md) marks the end, so the two together form a +coproduct that code can walk without knowing the concrete enum it came from. + +This spine makes structural, variant-by-variant operations work across every enum uniformly. An +enum's variants are exposed as one sum type through [`HasFields`](../../traits/shape/has_fields.md), so a +provider written once to recurse over the `Either` and `Void` branches can match, dispatch on, or +construct *any* enum's variants. This is the basis for CGP's extensible-variant machinery: a variant is +reached by walking the nested branches rather than by a hand-written `match` against a fixed enum. + +You write this spine through the [`Sum!`](../../macros/sum.md) macro. `Sum![A, B, C]` is the right-nested +`Either` chain terminated by `Void`. The branches are most often [`Field`](../field.md) entries pairing a +variant name with its payload, so an enum's shape becomes a `Sum!` of `Field` branches over this spine. + +## Definition + +`Either` is a two-case enum that selects the head or defers to the rest: + +```rust +#[derive(Eq, PartialEq, Debug, Clone)] +pub enum Either { + Left(Head), + Right(Tail), +} +``` + +`Head` is the type of the current branch and `Tail` is the rest of the chain, itself another `Either` +or, at the end, [`Void`](void.md). `Left(Head)` carries a value of the head type; `Right(Tail)` carries a +value belonging somewhere further down the chain. It derives `Eq`, `PartialEq`, `Debug`, and `Clone`, so +a sum of values that implement those traits inherits them. + +## Behavior + +A sum of any width is an `Either` chain ending in `Void`, nested to the right. The type `Sum![A, B, C]` +is `Either>>`, and the empty `Sum![]` is just `Void`. A value selects one +branch by how deep it sits: `Left(a)` is an `A`, `Right(Left(b))` is a `B`, and `Right(Right(Left(c)))` +is a `C`. Reaching the `Void` position would mean the value matched none of the listed branches, which is +impossible, because `Void` has no values, so the chain is closed off at its end. + +Generic code consumes the sum by recursing on its two cases, mirroring how it folds the product spine but +branching instead of pairing. A `Left` is handled directly as the head; a `Right` defers to a trait impl +on the `Tail`, recursing until a `Left` is found. The base case is the [`Void`](void.md) terminator, and +here the difference from the product spine matters: a product ends in the constructible [`Nil`](nil.md), +but a sum ends in the uninhabited `Void`, because an empty choice has no value to pick. + +## Examples + +The sum spine appears most visibly as the `Fields` of an enum that derives +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md), where the [`Sum!`](../../macros/sum.md) sugar +hides the `Either`/`Void` chain: + +```rust +use cgp::prelude::*; + +#[derive(HasFields)] +pub enum Shape { + Circle(f64), + Rectangle { width: f64, height: f64 }, +} + +// generated (schematically): +// impl HasFields for Shape { +// type Fields = Sum![ +// Field, +// Field, +// Field, +// ]>, +// ]; +// // i.e. Either, +// // Either, Void>> +// } +``` + +A standalone sum type can also be written through the sugar, and a value picks one branch by its nesting +depth: + +```rust +use cgp::prelude::*; + +type Token = Sum![u32, String, bool]; +// Token == Either>> + +let t: Token = Either::Right(Either::Left("hi".to_string())); // the String branch +``` + +## When to use it + +**Read `Either` in an expansion; write [`Sum!`](../../macros/sum.md) instead.** The spine is what the +sugar produces, and spelling it out by hand is longer, harder to change, and identical in meaning. + +- **Use [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) for an enum's shape** rather than + declaring the `Either` chain yourself. +- **Decode an `Either` chain in an error by counting the `Right` wrappers.** The depth is which variant a + value selects, and a mismatch is reported as a mismatch between two `Either` chains. +- **Reach for [`Cons`](cons.md), not `Either`, when every element is present at once.** A product holds a + value for every element; a sum holds one for exactly one. They are duals, and mixing them produces a + type error rather than a subtle bug. + +## Common Mistakes + +**A sum holds one branch, not all of them.** `Either>` is a value that is *either* an +`A` or a `B`, not both. This is the opposite of the [product spine](cons.md), and confusing the two is the +usual cause of a "expected `Either`, found `Cons`" error. + +**The empty sum is the uninhabited [`Void`](void.md), not a value.** `Sum![]` is `Void`, which has no +values, so an empty choice cannot be constructed. An empty record can, because it ends in +[`Nil`](nil.md). + +**Branch order is part of the type.** `Sum![A, B]` and `Sum![B, A]` are unrelated types. Because the +branches are name-tagged [`Field`](../field.md)s and the operations match on names, this bites less than +it might, but the types still differ. + +## Related constructs + +- [`Void`](void.md) — the uninhabited end marker that terminates this spine. +- [`Cons`](cons.md) and [`Nil`](nil.md) — the product spine, the record-shaped dual of this one. +- [`Sum!`](../../macros/sum.md) — the macro that folds element types onto this spine. +- [`Field`](../field.md) — what the branches usually are, pairing a variant name with its payload. +- [`HasFields`](../../traits/shape/has_fields.md) — exposes an enum's shape as one of these lists. +- [`ExtractField`](../../traits/variant/extract_field.md) — the extractor family that walks this spine. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — the variant representation this spine is the + backbone of. + +## Source + +- `Either` and [`Void`](void.md) are both in + [`sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/sum.rs) +- The `Sum!` fold: + [`types/sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/sum.rs) +- The enum `HasFields` derive that emits a `Sum!` of entries: + [`derive_has_fields/sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields/sum.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/spines/index.md b/docs/reference/types/spines/index.md new file mode 100644 index 00000000..65867cb0 --- /dev/null +++ b/docs/reference/types/spines/index.md @@ -0,0 +1,65 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +--- + +# Type-level list spines + +The recursive lists CGP folds over: one for a record, one for a variant, one for a string, and one for +a routing path. You write them through sugar and read them in expansions and errors. + +## Overview + +A **spine** is a list encoded as a type. Instead of holding several things in one flat type the way a +tuple does, a spine pairs a head with the rest of the list and terminates in an end marker, so generic +code can take the list apart one element at a time. That is what a tuple cannot do and a spine can, and +it is the mechanism behind every field-by-field and variant-by-variant operation in CGP. + +All the spines share one shape: right-nested, terminated by an end marker, and consumed by recursing on +two cases. A trait implemented for the end marker gives the base case, and a blanket impl for the +head-and-tail cell gives the recursive step, usually constraining the tail to implement the same trait +so the recursion stops at the end. This one pattern processes a list of any length with no per-element +code. + +Four spines cover four jobs, and they differ in what sits in the head and what marks the end. + +The **product spine** describes a record. [`Cons`](cons.md) pairs a field with the rest, and +[`Nil`](nil.md) marks the end. A record is a `Cons` chain ending in `Nil`, and it is what +[`Product!`](../../macros/product.md) builds. + +The **sum spine** describes a variant. [`Either`](either.md) selects the head or defers to the rest, and +[`Void`](void.md) marks the end. A variant is an `Either` chain ending in the uninhabited `Void`, and it +is what [`Sum!`](../../macros/sum.md) builds. The end marker is where the two data spines differ: a +record ends in the constructible `Nil`, a variant in the impossible `Void`. + +The **string spine** describes a field name. [`Chars`](chars.md) holds one character and the rest of the +string, again ending in `Nil`, and it is what a [`Symbol!`](../../macros/symbol.md) wraps. It is the +product spine specialized so the head is a `const char` rather than a type. + +The **path spine** describes a route through delegation tables. [`PathCons`](path_cons.md) holds one +segment and the rest of the path, ending in `Nil`, and it is what [`Path!`](../../macros/path.md) builds. +It differs from the product spine in one way: its segments may be unsized, because they are pure markers +rather than values. + +You write none of these by hand. The sugar builds them, and the reason to know them is that a mismatched +shape or a routing failure prints the expanded spine, and counting the cells is how you read it. + +## The pages + +- [`Cons`](cons.md) — the head-and-tail cell of a record. +- [`Nil`](nil.md) — the end marker shared by the product, string, and path spines. +- [`Either`](either.md) — the head-or-rest cell of a variant. +- [`Void`](void.md) — the uninhabited end marker of a variant. +- [`Chars`](chars.md) — one character of a type-level string. +- [`PathCons`](path_cons.md) — one segment of a type-level path. + +## The ideas behind them + +- [Extensible records](/docs/concepts/extensible-records) — the record shape the product spine + describes. +- [Extensible variants](/docs/concepts/extensible-variants) — the variant shape the sum spine describes. +- [Namespaces](/docs/concepts/namespaces) — where a path spine routes a component lookup. + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/spines/nil.md b/docs/reference/types/spines/nil.md new file mode 100644 index 00000000..348a6743 --- /dev/null +++ b/docs/reference/types/spines/nil.md @@ -0,0 +1,127 @@ +--- +sidebar_label: 'Nil' +sidebar_position: 2 +--- + +# `Nil` + +The end marker of the product, string, and path spines: an empty, constructible list. + +:::info + +### Generated machinery + +**You are not expected to write `Nil` by hand.** It is produced by the sugar that builds the spines it +terminates: [`Product!`](../../macros/product.md), [`Symbol!`](../../macros/symbol.md), and +[`Path!`](../../macros/path.md). You meet it at the end of a chain in an expansion or an error, and this +page explains what it marks. + +::: + +## Overview + +`Nil` marks the end of a right-nested type-level list. Where a [`Cons`](cons.md) cell pairs a head with +the rest of the list, `Nil` is the rest when there is nothing left, so a list of any length is a `Cons` +chain that finishes in `Nil`. On its own, `Nil` is the empty list. + +The same marker terminates three of CGP's four spines. It ends the product spine built from +[`Cons`](cons.md), the string spine built from [`Chars`](chars.md), and the path spine built from +[`PathCons`](path_cons.md). Only the sum spine ends differently, in the uninhabited [`Void`](void.md), +and that difference is the point of both markers: a record, a string, and a path can each be empty and +still exist, so their terminator is a real value. + +## Definition + +`Nil` is a unit struct: + +```rust +#[derive(Eq, PartialEq, Clone, Default, Debug)] +pub struct Nil; +``` + +It carries no data. Used as a tail it terminates a chain, and used on its own it is the empty list. It +derives `Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a list ending in `Nil` inherits those +traits structurally and `Nil` itself compares equal to `Nil`. + +## Behavior + +`Nil` is the base case of every recursion over a spine it terminates. An operation that folds over a +product implements the step for [`Cons`](cons.md) and the base case for `Nil`, and the +recursion bottoms out when it reaches `Nil`. The string and path spines do the same: a walk over +[`Chars`](chars.md) stops at `Nil`, and a walk over [`PathCons`](path_cons.md) stops at `Nil`. + +Because `Nil` is a real, constructible value, the empty product `Product![]` is `Nil` and the empty value +`product![]` is `Nil` as a value. This is what a builder or a conversion returns when a shape has no +fields left, and it is why an empty record is a value the program can hold. The contrast with +[`Void`](void.md) is exact: a value with every field ruled out cannot exist, so a sum ends in an +uninhabited marker, while a record ends in this inhabited one. + +## Examples + +`Nil` closes off every product chain, visible when the [`Product!`](../../macros/product.md) sugar is +expanded: + +```rust +use cgp::prelude::*; + +// Product![u32, bool] expands to: +type Row = Cons>; + +// the empty list is Nil alone: +type Empty = Product![]; // == Nil +``` + +It also terminates a [`Symbol!`](../../macros/symbol.md) character chain and a +[`Path!`](../../macros/path.md) segment chain: + +```rust +// Symbol!("hi") ends its Chars chain in Nil +// Path!(@a.b) ends its PathCons chain in Nil +``` + +## When to use it + +**You read `Nil` at the end of a chain; you do not write it.** The sugar produces it, and recognizing it +is all that is asked. + +- **Read `Nil` as "the list ends here."** In an expanded `Cons`, `Chars`, or `PathCons` chain, the `Nil` + is the terminator and marks the count of cells before it. +- **Expect `Nil`, not [`Void`](void.md), at the end of a record, a string, or a path.** A sum ends in + `Void`; the other three spines end in `Nil`. Meeting the wrong terminator in an error usually means the + product and sum families have been crossed. + +## Common Mistakes + +**`Nil` is inhabited; [`Void`](void.md) is not.** `Nil` is a real value the empty product is, while `Void` +is an uninhabited type an empty choice would be. They are not interchangeable, and the whole extractor +machinery depends on the difference. + +**`Nil` terminates three spines, not just the product one.** A `Nil` at the end of a +[`Chars`](chars.md) chain or a [`PathCons`](path_cons.md) chain is the same marker doing the same job, so +seeing it outside a record is expected. + +## Related constructs + +- [`Cons`](cons.md) — the head-and-tail cell this marker terminates in a record. +- [`Void`](void.md) — the sum spine's uninhabited end marker, the counterpart to this one. +- [`Chars`](chars.md) and [`PathCons`](path_cons.md) — the string and path spines `Nil` also terminates. +- [`Product!`](../../macros/product.md) — the macro whose empty form is `Nil`. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — where the empty and terminating record shape + matters. + +## Source + +- The type: + [`nil.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/nil.rs) +- The spines it terminates: + [`cons.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/cons.rs), + [`chars.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/chars.rs), + and + [`path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/path.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/spines/path_cons.md b/docs/reference/types/spines/path_cons.md new file mode 100644 index 00000000..c6fbf170 --- /dev/null +++ b/docs/reference/types/spines/path_cons.md @@ -0,0 +1,164 @@ +--- +sidebar_label: 'PathCons' +sidebar_position: 6 +--- + +# `PathCons` + +One segment of a type-level path: the spine that names a route through nested delegation tables, so a +lookup can reach an entry several layers deep. + +:::info + +### Generated machinery + +**You are not expected to write `PathCons` by hand.** The [`Path!`](../../macros/path.md) macro builds it, +and [`cgp_namespace!`](../../macros/cgp_namespace.md) emits it when it reroutes a component. You meet it +in an expansion of namespace wiring and in a routing error, and this page explains its shape. + +::: + +## Overview + +`PathCons` expresses a *route* through nested delegation tables as a single type. A bare +component name picks one entry out of a context's table, where the **context** is the type the capability +runs against and the table records which provider it uses for each component. Sometimes the entry a +lookup wants lives behind one or more layers of indirection: inside a namespace, behind a namespace it +inherits from, under a prefix. A path names such a route, as a list of segments read left to right, each +one narrowing the lookup a step further. `PathCons` is the cell of that list, and [`Nil`](nil.md) +terminates it, so `PathCons>` is the two-step path "first `A`, then `B`". + +A path is a distinct spine from the [`Cons`](cons.md) product list, even though both are right-nested and +`Nil`-terminated, and the difference is the unsized bound. `PathCons` declares its head and tail +`?Sized`, so a segment may be a trait object or another unsized type and the whole path can be +manipulated without its parts having a known size. A product list keys a struct's fields and its +elements are always sized values; a path keys a lookup and its segments are pure type-level markers that +never need to be `Sized`. + +The segments are the markers CGP uses elsewhere: a lowercase dotted name becomes a +[`Symbol`](chars.md) type-level string, and a capitalized name becomes that named type, usually a +component key such as `FooProviderComponent` or a namespace marker. A path is therefore an interleaving +of symbols and component names, the form `@a.B.c`, assembled into a `PathCons` chain. You write paths +through the [`Path!`](../../macros/path.md) macro, so this page is the runtime spine and that macro's page +carries the `@`-segment syntax. + +## Definition + +`PathCons` is a zero-sized struct holding two phantom markers, one for the head segment and one for the +rest: + +```rust +pub struct PathCons(pub PhantomData, pub PhantomData); +``` + +`Head` is the first segment and `Tail` is the remainder, expected to be either another `PathCons` or +[`Nil`](nil.md) at the end. Both bounds are `?Sized`, so any type may occupy a segment. The struct carries +no runtime data: like the other type-level building blocks it exists through +[`PhantomData`](../phantom_data.md) so a route can be named and matched in trait resolution. + +## Behavior + +`PathCons` supports path concatenation through the +[`ConcatPath`](../../traits/formatting/concat_path.md) trait, which appends one path onto the end of +another at the type level. The trait recurses down the spine: `PathCons` concatenates with +`Other` by keeping `Head` and concatenating `Tail` with `Other`, while [`Nil`](nil.md) concatenates with +`Other` by becoming `Other`. The result is ordinary list append, computed as an associated-type +projection. + +Beyond concatenation, a path is consumed by [`RedirectLookup`](../../providers/redirect_lookup.md), the +provider that resolves a delegation by walking a context's table along a path. When a namespace or a +prefixed component reroutes a lookup, it produces a `RedirectLookup` whose `Path` is a +`PathCons` chain, and `RedirectLookup` follows the chain segment by segment until it lands on a concrete +provider. The path never names a provider itself; it only describes where to look, so the same path can +resolve to different providers depending on the table it is walked against. + +## Examples + +Paths are produced by the [`Path!`](../../macros/path.md) macro and most often appear inside the wirings +that [`cgp_namespace!`](../../macros/cgp_namespace.md) emits. A namespace entry that redirects one +component key to a path desugars into a `RedirectLookup` over a `PathCons` chain: + +```rust +use cgp::prelude::*; + +cgp_namespace! { + new MyNamespace { + FooProviderComponent => + @MyFooComponent, + } +} + +// the emitted entry, in readable form: +// impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { +// type Delegate = RedirectLookup<__Table__, PathCons>; +// } +``` + +A path with both a lowercase symbol segment and a capitalized component segment interleaves the two +marker kinds. Registering a component into a namespace under a prefix produces a two-segment path: + +```rust +// @MyBarComponent.BarProviderComponent expands to +// PathCons> +``` + +The lookup steps first through `MyBarComponent` and then through `BarProviderComponent` before +resolving. A single-segment path is `PathCons`, and the empty path is [`Nil`](nil.md) alone. + +## When to use it + +**You read `PathCons` in an expansion; you write [`Path!`](../../macros/path.md), or wire a namespace.** + +- **Decode a `PathCons` chain by reading the segments left to right.** Each is one step of the route, a + [`Symbol`](chars.md) for a lowercase name or a component or namespace type for a capitalized one. +- **Use [`Path!`](../../macros/path.md) to write a path** when you need one directly, in its `@a.B.c` + form. +- **Use a namespace rather than a raw path** for the common case: joining a + [`cgp_namespace!`](../../macros/cgp_namespace.md) or the `open` statement of + [`delegate_components!`](../../macros/delegate_components.md) produces the paths for you. + +## Common Mistakes + +**A path names a route, not a provider.** A `PathCons` chain describes where to look; which provider it +resolves to depends on the table [`RedirectLookup`](../../providers/redirect_lookup.md) walks it against. +The same path can land on different providers in different contexts. + +**A path spine is `?Sized`, unlike the [`Cons`](cons.md) product spine.** Its segments are markers rather +than values, so a segment need not have a known size. Expecting a path to behave like a product list of +values is the usual source of confusion. + +**Both a path and a product end in [`Nil`](nil.md).** Seeing `Nil` at the end of a `PathCons` chain is +the same terminator doing the same job it does for a record, not a sign the two spines have been mixed. + +## Related constructs + +- [`Nil`](nil.md) — the end marker that terminates a `PathCons` chain. +- [`Cons`](cons.md) — the product spine this one parallels, whose elements are sized values rather than + `?Sized` markers. +- [`Chars`](chars.md) — the [`Symbol`](chars.md) segments a path is built from. +- [`Path!`](../../macros/path.md) — the macro that folds `@`-segments onto this spine. +- [`ConcatPath`](../../traits/formatting/concat_path.md) — appends one path onto another. +- [`RedirectLookup`](../../providers/redirect_lookup.md) — walks a path against a table at resolution + time. +- [`cgp_namespace!`](../../macros/cgp_namespace.md) — emits these paths to reroute and register entries. + +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — where a path routes a component lookup through a reusable + table. + +## Source + +- The type: + [`path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/path.rs), + with [`Nil`](nil.md) in + [`nil.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/nil.rs) +- The `ConcatPath` trait and impls: + [`concat_path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/concat_path.rs) +- The constructing macro is [`Path!`](../../macros/path.md); `RedirectLookup`, which consumes a path, is + in + [`redirect_lookup.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/redirect_lookup.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/spines/void.md b/docs/reference/types/spines/void.md new file mode 100644 index 00000000..7bd9badb --- /dev/null +++ b/docs/reference/types/spines/void.md @@ -0,0 +1,136 @@ +--- +sidebar_label: 'Void' +sidebar_position: 4 +--- + +# `Void` + +The uninhabited end marker of the sum spine: an empty enum that can never be constructed, which is what +lets a total variant match close with no runtime branch. + +:::info + +### Generated machinery + +**You are not expected to write `Void` by hand.** It is produced by [`Sum!`](../../macros/sum.md) as the +terminator of a sum, and it appears in the extractor machinery. You meet it at the end of an +[`Either`](either.md) chain and in an extraction error, and this page explains why it is uninhabited. + +::: + +## Overview + +`Void` marks the end of a sum, and unlike the [`Nil`](nil.md) that ends the other spines, it is +uninhabited: it has no values. Where a record, a string, or a path can each be empty and still exist, +an empty *choice* cannot. There is no value that is "none of the branches", so the natural terminator +for the sum spine is a type with no values at all. + +That uninhabitedness is not a technicality; it makes the sum spine work. An [`Either`](either.md) +chain ends in `Void`, so a value that walked past every real branch would have type `Void`, which is +impossible to reach. The chain is therefore closed at its end by construction, and a match that has +handled every real variant has nothing left to handle. + +## Definition + +`Void` is an empty enum: + +```rust +#[derive(Eq, PartialEq, Debug, Clone)] +pub enum Void {} +``` + +It has no variants, so it has no values: it is uninhabited, the same idea as Rust's never type. It +derives the standard traits so a sum ending in `Void` can inherit them, but no value of `Void` is ever +built, so those impls are never run on one. + +## Behavior + +`Void` is the base case of a recursion over a sum, and it behaves differently from the product spine's +base case in exactly one way that matters. A walk over an [`Either`](either.md) chain handles each +`Left` as a branch and defers each `Right` to the tail, until the tail is `Void`, at which point there +is nothing left to handle. + +The uninhabitedness is essential to the extractor machinery. After an extractor has tried every +variant of a sum and matched none, the leftover value has type `Void`, a value that cannot exist. +[`FinalizeExtract`](../../traits/variant/finalize_extract.md) for `Void` turns that into any required +type with an empty `match self {}`, since there are no cases to handle, so a fully-handled variant +extraction is total at compile time with no unreachable runtime branch: + +```rust +// schematically: +impl FinalizeExtract for Void { + fn finalize_extract(self) -> T { + match self {} // no cases, because Void has no values + } +} +``` + +A constructible terminator like [`Nil`](nil.md) could not be discharged this way, because the compiler +would demand a value for the `Nil` case. Only an uninhabited type lets the empty match stand, which is +why the sum spine terminates in `Void` and the product spine in `Nil`. + +## Examples + +`Void` closes off every sum chain, visible when the [`Sum!`](../../macros/sum.md) sugar is expanded: + +```rust +use cgp::prelude::*; + +// Sum![u32, bool] expands to: +type Token = Either>; + +// the empty sum is Void alone: +type Empty = Sum![]; // == Void +``` + +You do not construct a `Void`; you discharge one. The only thing code does with a `Void` value is match +on it with no arms, which the extractor family does when a variant match is complete. + +## When to use it + +**You read `Void` at the end of a sum and in an extractor's type; you do not write it.** + +- **Read `Void` as "the choice ends here, and this point is unreachable."** In an expanded + [`Either`](either.md) chain, the `Void` marks the end, and a value can never sit at it. +- **Expect `Void`, not [`Nil`](nil.md), at the end of a variant.** A record, a string, and a path end in + `Nil`; a variant ends in `Void`. Meeting the wrong terminator in an error usually means the product and + sum families have been crossed. +- **Recognize `Void` in a [`FinalizeExtract`](../../traits/variant/finalize_extract.md) error** as the + all-ruled-out remainder of a variant extraction. + +## Common Mistakes + +**`Void` is uninhabited; [`Nil`](nil.md) is not.** `Nil` is a real value the empty product is, while +`Void` is a type with no values. Records use the first, variants the second, and an error naming the +wrong one usually means the two families have been crossed. + +**You cannot build a `Void`.** There is no constructor and no literal for it, by design. Any code that +appears to "return a `Void`" is really an empty match that never returns at all. + +## Related constructs + +- [`Either`](either.md) — the head-or-rest cell this marker terminates. +- [`Nil`](nil.md) — the product, string, and path spines' constructible end marker, the counterpart to + this one. +- [`Sum!`](../../macros/sum.md) — the macro whose empty form is `Void`. +- [`FinalizeExtract`](../../traits/variant/finalize_extract.md) — discharges the uninhabited remainder of + a variant extraction with an empty match. +- [`FinalizeExtractResult`](../../traits/variant/finalize_extract_result.md) — the result-carrying form + built on the same idea. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — where the uninhabited terminator closes a + total variant match. + +## Source + +- `Void` is in + [`sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/sum.rs), + alongside [`Either`](either.md) +- `FinalizeExtract for Void`, which discharges the uninhabited remainder: + [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/type_level_spines.md b/docs/reference/types/type_level_spines.md deleted file mode 100644 index e80154fb..00000000 --- a/docs/reference/types/type_level_spines.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -sidebar_label: 'Type-level spines' ---- - -# Type-level spines - -`Cons`/`Nil`, `Either`/`Void`, `Chars`, and `PathCons` — the lists the sugar expands into. - -:::info - -### Not written yet - -This reference page is still being written. Until it lands, the -[`cgp` source](https://github.com/contextgeneric/cgp) is the authority on this construct, -and `cargo cgp expand` will show you what it generates in your own code. - -::: diff --git a/example-code/README.md b/example-code/README.md index cafa721e..d5046070 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -30,7 +30,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), and all of `components/` (each component page that shows code, including the `handler/` subsection); `types/` is the remaining gap, and the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.rs b/example-code/tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.rs new file mode 100644 index 00000000..e98baf29 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.rs @@ -0,0 +1,7 @@ +// A zero-sized marker generic over a parameter it stores no value of does not compile without a +// `PhantomData` field: Rust requires every type parameter to be used. This is the "before" of the +// `PhantomData` page's *Why a marker needs it* section; the "after" adds `PhantomData`. + +pub struct Multiply; + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.stderr b/example-code/tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.stderr new file mode 100644 index 00000000..7e65758c --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.stderr @@ -0,0 +1,8 @@ +error[E0392]: type parameter `Field` is never used + --> tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.rs:5:21 + | +5 | pub struct Multiply; + | ^^^^^ unused type parameter + | + = help: consider removing `Field`, referring to it in a field, or using a marker such as `PhantomData` + = help: if you intended `Field` to be a const parameter, use `const Field: /* Type */` instead diff --git a/example-code/tests/reference/mod.rs b/example-code/tests/reference/mod.rs index 3bc4cd23..dabc50fe 100644 --- a/example-code/tests/reference/mod.rs +++ b/example-code/tests/reference/mod.rs @@ -9,3 +9,4 @@ pub mod errors; pub mod macros; pub mod providers; pub mod traits; +pub mod types; diff --git a/example-code/tests/reference/types/field.rs b/example-code/tests/reference/types/field.rs new file mode 100644 index 00000000..ac8419be --- /dev/null +++ b/example-code/tests/reference/types/field.rs @@ -0,0 +1,34 @@ +//! Code from `docs/reference/types/field.md` — *`Field`*. +//! +//! A `Field` pairs a value with a type-level tag. This pins the `Fields` shape a derive assigns, where +//! each entry is a `Field`, and the `.into()` construction the page shows. + +/// ## Examples +/// +/// Each entry of a struct's shape is a `Field` tagged by its name; naming the shape checks the mapping. +/// A single `Field` is built from its value with `.into()`, the tag supplied by the type annotation, +/// and a tuple-struct field is tagged by an `Index` rather than a `Symbol!`. +pub mod examples { + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + pub type ExpectedFields = Product![Field, Field]; + + pub fn assert_fields(fields: ::Fields) -> ExpectedFields { + fields + } + + // The positional form the page names: `Index<0>` in place of a `Symbol!`. + pub type PositionalField = Field, u32>; + + #[test] + fn test_a_field_is_built_from_its_value() { + let name: Field = "Alice".to_string().into(); + assert_eq!(name.value, "Alice"); + } +} diff --git a/example-code/tests/reference/types/index_type.rs b/example-code/tests/reference/types/index_type.rs new file mode 100644 index 00000000..3b696cb3 --- /dev/null +++ b/example-code/tests/reference/types/index_type.rs @@ -0,0 +1,26 @@ +//! Code from `docs/reference/types/index_type.md` — *`Index`*. +//! +//! `Index` tags a tuple-struct field by its position. The page reads a field by its index and prints +//! the number a tag stands for; both run here. + +/// ## Examples +/// +/// Deriving `HasField` on a tuple struct is what makes the positional `get_field` below resolve, and an +/// `Index` prints its number through `Display`. +pub mod examples { + use cgp::prelude::*; + + #[derive(HasField)] + pub struct Pair(pub u32, pub String); + + #[test] + fn test_a_tuple_field_is_read_by_its_index() { + let pair = Pair(7, "hi".to_string()); + assert_eq!(*pair.get_field(PhantomData::>), 7); + } + + #[test] + fn test_an_index_prints_its_number() { + assert_eq!(Index::<2>.to_string(), "2"); + } +} diff --git a/example-code/tests/reference/types/life.rs b/example-code/tests/reference/types/life.rs new file mode 100644 index 00000000..d93b6d90 --- /dev/null +++ b/example-code/tests/reference/types/life.rs @@ -0,0 +1,19 @@ +//! Code from `docs/reference/types/life.md` — *`Life`*. +//! +//! `Life` is inserted by the macros; the only user-written code the page shows is a component whose +//! consumer trait carries a lifetime. This pins that `#[cgp_component]` accepts that form. The +//! generated provider trait, which records the lifetime as `Life<'a>`, is shown as a comment on the +//! page and checked by `cargo cgp expand` rather than here. + +/// ## Examples +/// +/// A borrowing getter component. Defining it is the check: the macro accepts the lifetime and lifts it +/// into the dependency marker. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(ReferenceGetter)] + pub trait HasReference<'a, T: 'a + ?Sized> { + fn get_reference(&self) -> &'a T; + } +} diff --git a/example-code/tests/reference/types/mod.rs b/example-code/tests/reference/types/mod.rs new file mode 100644 index 00000000..2b712098 --- /dev/null +++ b/example-code/tests/reference/types/mod.rs @@ -0,0 +1,12 @@ +//! Code from the pages under `docs/reference/types/`. +//! +//! Most of these types are type-level markers a reader recognizes rather than writes, so a page gets a +//! module only where it shows code a compiler can check: a shape a derive assigns, a value built from a +//! marker, a call site that passes a tag. The two overview pages, which show no code, get none. + +pub mod field; +pub mod index_type; +pub mod life; +pub mod mref; +pub mod phantom_data; +pub mod spines; diff --git a/example-code/tests/reference/types/mref.rs b/example-code/tests/reference/types/mref.rs new file mode 100644 index 00000000..6d6db2df --- /dev/null +++ b/example-code/tests/reference/types/mref.rs @@ -0,0 +1,29 @@ +//! Code from `docs/reference/types/mref.md` — *`MRef`*. +//! +//! `MRef` is an ordinary runtime value, not a type-level marker. The page builds one both ways and +//! promotes it to an owned value; this runs that. + +/// ## Examples +/// +/// A borrowed value and a freshly built one have the same type and are read the same way, and +/// `get_or_clone` promotes either to ownership. +pub mod examples { + use cgp::prelude::*; + + #[test] + fn test_borrowed_and_owned_are_read_the_same_way() { + let stored = String::from("hello"); + + // a context lending a stored value: + let borrowed: MRef<'_, String> = MRef::from(&stored); + assert_eq!(&*borrowed, "hello"); + + // a provider returning a freshly built value through the same type: + let made: MRef<'_, String> = MRef::from(String::from("world")); + assert_eq!(made.as_ref(), "world"); + + // promote either to an owned value when ownership is required: + let owned: String = borrowed.get_or_clone(); + assert_eq!(owned, "hello"); + } +} diff --git a/example-code/tests/reference/types/phantom_data.rs b/example-code/tests/reference/types/phantom_data.rs new file mode 100644 index 00000000..ff345a45 --- /dev/null +++ b/example-code/tests/reference/types/phantom_data.rs @@ -0,0 +1,80 @@ +//! Code from `docs/reference/types/phantom_data.md` — *`PhantomData`*. +//! +//! `PhantomData` is a standard-library type, so there is nothing of CGP's to re-declare. What the +//! page's snippets check are its two roles: declaring a zero-sized struct generic over a type it +//! stores no value of, and passing a type to a call site as a token. The greet provider exercises the +//! second through `get_field(PhantomData::)`. + +/// ## Why a marker needs it +/// +/// The fixed form of the page's failing snippet: a marker generic over a parameter it stores no value +/// of carries a `PhantomData` over it and stays zero-sized. (The failing form is the compile-fail +/// fixture `tests/compile_fail/reference/types/phantom_data_a_marker_needs_the_field.rs`.) +pub mod why_a_marker_needs_it { + use cgp::prelude::*; + + pub struct Multiply(pub PhantomData); + + #[test] + fn test_a_marker_struct_is_zero_sized() { + assert_eq!(core::mem::size_of::>(), 0); + } +} + +/// ## Examples +/// +/// Passing a type to a call site: `PhantomData::` selects which field the getter +/// reads. The component and the context are filled in around the page's `#[cgp_impl]` snippet so the +/// call resolves. A type carrying two parameters uses one `PhantomData` over a tuple. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); + } + + #[cgp_impl(new GreetHello)] + impl Greeter + where + Self: HasField, + { + fn greet(&self) { + let name = self.get_field(PhantomData::); + println!("Hello, {name}!"); + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { + App { + GreeterComponent: GreetHello, + } + } + + check_components! { + App { + GreeterComponent + } + } + + // A type that must carry two parameters uses one `PhantomData` over a tuple. + pub struct Add(pub PhantomData<(Left, Right)>); + + #[test] + fn test_greet_reads_the_name_field() { + let app = App { + name: "World".to_owned(), + }; + app.greet(); + } + + #[test] + fn test_a_two_parameter_marker_is_zero_sized() { + assert_eq!(core::mem::size_of::>(), 0); + } +} diff --git a/example-code/tests/reference/types/spines/chars.rs b/example-code/tests/reference/types/spines/chars.rs new file mode 100644 index 00000000..9f1b79ba --- /dev/null +++ b/example-code/tests/reference/types/spines/chars.rs @@ -0,0 +1,58 @@ +//! Code from `docs/reference/types/spines/chars.md` — *`Chars`*. +//! +//! A `Symbol!` wraps a `Chars` chain. The page reads a field by its `Symbol!` tag and rebuilds the +//! string from the type; both run here. The greet provider duplicates the one on the `PhantomData` +//! page, which the crate prefers over a shared helper so each file answers for its own page. + +/// ## Examples +/// +/// A field-name tag drives a getter, and a `Symbol!` rebuilds its string through `Display`. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); + } + + #[cgp_impl(new GreetHello)] + impl Greeter + where + Self: HasField, + { + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData::)); + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { + App { + GreeterComponent: GreetHello, + } + } + + check_components! { + App { + GreeterComponent + } + } + + #[test] + fn test_a_symbol_rebuilds_its_string() { + let s = ::default(); + assert_eq!(s.to_string(), "hello"); + } + + #[test] + fn test_greet_reads_the_name_field() { + let app = App { + name: "World".to_owned(), + }; + app.greet(); + } +} diff --git a/example-code/tests/reference/types/spines/cons.rs b/example-code/tests/reference/types/spines/cons.rs new file mode 100644 index 00000000..ac8b1032 --- /dev/null +++ b/example-code/tests/reference/types/spines/cons.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/types/spines/cons.md` — *`Cons`*. +//! +//! `Cons`/`Nil` are what `Product!` expands to. This pins the `Cons` chain a derive assigns and the one +//! a `Product!` alias produces, by naming the chain explicitly and by building a `product!` value by +//! hand. + +/// ## Examples +/// +/// A struct's shape is a `Cons` chain of `Field` entries, and a `Product!` value is a `Cons` value. +pub mod examples { + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + // The page shows the generated `Fields` as a `Cons` chain; the coercion checks it. + pub fn assert_person_fields( + fields: ::Fields, + ) -> Cons, Cons, Nil>> { + fields + } + + pub type Row = Product![u32, String, bool]; + + // `Product!` is sugar for the right-nested `Cons` chain. + pub fn assert_row_is_cons(row: Row) -> Cons>> { + row + } + + #[test] + fn test_a_product_value_is_a_cons_value() { + let row: Row = product![1, "hi".to_string(), true]; + let by_hand: Cons>> = + Cons(1, Cons("hi".to_string(), Cons(true, Nil))); + assert_eq!(row, by_hand); + } +} diff --git a/example-code/tests/reference/types/spines/either.rs b/example-code/tests/reference/types/spines/either.rs new file mode 100644 index 00000000..93ab8514 --- /dev/null +++ b/example-code/tests/reference/types/spines/either.rs @@ -0,0 +1,50 @@ +//! Code from `docs/reference/types/spines/either.md` — *`Either`*. +//! +//! `Either`/`Void` are what `Sum!` expands to. This pins the `Either` chain a derive assigns to an enum +//! and the branch a nested `Either` value selects. + +/// ## Examples +/// +/// An enum's shape is an `Either` chain of `Field` entries terminated by `Void`, and a `Sum!` value +/// selects one branch by its nesting depth. +pub mod examples { + use cgp::prelude::*; + + #[derive(HasFields)] + pub enum Shape { + Circle(f64), + Rectangle { width: f64, height: f64 }, + } + + // The page shows the generated `Fields` as an `Either` chain; the coercion checks it. + pub fn assert_shape_fields( + fields: ::Fields, + ) -> Either< + Field, + Either< + Field< + Symbol!("Rectangle"), + Product![Field, Field], + >, + Void, + >, + > { + fields + } + + pub type Token = Sum![u32, String, bool]; + + pub fn assert_token_is_either(token: Token) -> Either>> { + token + } + + #[test] + fn test_a_value_selects_a_branch_by_depth() { + // the String branch + let t: Token = Either::Right(Either::Left("hi".to_string())); + match t { + Either::Right(Either::Left(s)) => assert_eq!(s, "hi"), + _ => panic!("wrong branch"), + } + } +} diff --git a/example-code/tests/reference/types/spines/mod.rs b/example-code/tests/reference/types/spines/mod.rs new file mode 100644 index 00000000..0a951ea1 --- /dev/null +++ b/example-code/tests/reference/types/spines/mod.rs @@ -0,0 +1,8 @@ +//! Code from the pages under `docs/reference/types/spines/`. + +pub mod chars; +pub mod cons; +pub mod either; +pub mod nil; +pub mod path_cons; +pub mod void; diff --git a/example-code/tests/reference/types/spines/nil.rs b/example-code/tests/reference/types/spines/nil.rs new file mode 100644 index 00000000..fcb4a5e9 --- /dev/null +++ b/example-code/tests/reference/types/spines/nil.rs @@ -0,0 +1,25 @@ +//! Code from `docs/reference/types/spines/nil.md` — *`Nil`*. +//! +//! `Nil` terminates the product, string, and path spines and is the empty product. This pins that the +//! empty `Product!` is `Nil`, at the type level and the value level. + +/// ## Examples +/// +/// A `Cons` chain ends in `Nil`, and the empty product is `Nil` alone. +pub mod examples { + use cgp::prelude::*; + + pub type Row = Cons>; + + pub type Empty = Product![]; + + pub fn assert_empty_is_nil(empty: Empty) -> Nil { + empty + } + + #[test] + fn test_the_empty_product_value_is_nil() { + let empty: Empty = product![]; + assert_eq!(empty, Nil); + } +} diff --git a/example-code/tests/reference/types/spines/path_cons.rs b/example-code/tests/reference/types/spines/path_cons.rs new file mode 100644 index 00000000..55f4ad6d --- /dev/null +++ b/example-code/tests/reference/types/spines/path_cons.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/types/spines/path_cons.md` — *`PathCons`*. +//! +//! `PathCons` is built by `Path!` and emitted by `cgp_namespace!`. Paths are unsized markers, so there +//! is no value to build: naming the `PathCons` chain a `Path!` produces and coercing it is the check, +//! and the namespace registration pins that the `=>` redirect the page shows compiles. + +/// ## Examples +/// +/// A lowercase path segment is a `Symbol`, so `Path!(@a.b)` is a two-segment `PathCons` chain, which is +/// the expansion the page shows. The page's `cgp_namespace!` then reroutes one component to a path; the +/// two components it names are defined here, which the page elides, so the redirect compiles. +pub mod examples { + use cgp::prelude::*; + + pub type TwoSegments = Path!(@a.b); + + #[allow(dead_code)] + pub fn assert_path_is_pathcons( + path: PhantomData<&TwoSegments>, + ) -> PhantomData<&PathCons>> { + path + } + + #[cgp_component(FooProvider)] + pub trait CanFoo { + fn foo(&self); + } + + #[cgp_component(MyFoo)] + pub trait CanMyFoo { + fn my_foo(&self); + } + + cgp_namespace! { + new MyNamespace { + FooProviderComponent => + @MyFooComponent, + } + } +} diff --git a/example-code/tests/reference/types/spines/void.rs b/example-code/tests/reference/types/spines/void.rs new file mode 100644 index 00000000..d0139ecd --- /dev/null +++ b/example-code/tests/reference/types/spines/void.rs @@ -0,0 +1,21 @@ +//! Code from `docs/reference/types/spines/void.md` — *`Void`*. +//! +//! `Void` is uninhabited, so there is no value to build. Naming the empty `Sum!` as `Void` and coercing +//! it is the check. + +/// ## Examples +/// +/// An `Either` chain ends in `Void`, and the empty sum is `Void` alone. +pub mod examples { + use cgp::prelude::*; + + pub type Token = Either>; + + pub type Empty = Sum![]; + + // No value of either type is constructed: the coercion checks the type equality. + #[allow(dead_code)] + pub fn assert_empty_is_void(empty: Empty) -> Void { + empty + } +} From 9bf01616ca6245f4f90dca29ee1c9c07d2dd7884 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 31 Aug 2026 22:56:22 +0200 Subject: [PATCH 052/516] reference/types: rename "spine" to "list" and flatten the section Rename the type-level "spine" vocabulary to "list" across the whole reference. "spine" is not the established name for these encodings: in Haskell it names a list's evaluation skeleton, while the encodings themselves are products and sums (GHC.Generics, frunk HList/Coproduct), which also matches CGP's own Product!/Sum! macros. The families are now the product list, sum list, string list, and path list. Flatten docs/reference/types: remove the spines/ subdirectory so all 11 construct pages sit directly under Types, ordered PhantomData, Field, Index, Life, then Cons, Nil, Either, Void, Chars, PathCons, then MRef. Each head cell now owns its family's explanation (Cons the product, Either the sum, Chars the string, PathCons the path), replacing the deleted group overview. Rewrite the Types overview to cover all of CGP's types accurately: most are type-level building blocks, and MRef is called out as the one ordinary runtime data type. Repoint the ~45 inbound links and the links to the removed group overview. Clean up register while revising these sentences: drop a cleft cluster ("The list is what the sugar produces" and friends) and two "backbone" metaphors, and replace an em-dash parenthetical in the overview. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XnyQ9YwnJDberZ9vNnUWcY --- docs/cargo-cgp/expand.md | 2 +- docs/cargo-cgp/index.md | 4 +- .../reference/derives/derive_extract_field.md | 2 +- docs/reference/derives/derive_from_variant.md | 2 +- docs/reference/derives/derive_has_fields.md | 6 +- docs/reference/errors.md | 4 +- docs/reference/index.md | 10 +-- docs/reference/macros/cgp_getter.md | 2 +- docs/reference/macros/cgp_namespace.md | 4 +- docs/reference/macros/delegate_components.md | 4 +- docs/reference/macros/index.md | 2 +- docs/reference/macros/path.md | 10 +-- docs/reference/macros/product.md | 12 ++-- docs/reference/macros/sum.md | 10 +-- docs/reference/macros/symbol.md | 6 +- docs/reference/providers/chain_getters.md | 4 +- .../dispatch/match_with_field_handlers.md | 4 +- docs/reference/providers/redirect_lookup.md | 4 +- docs/reference/traits/casting/can_downcast.md | 2 +- docs/reference/traits/casting/can_upcast.md | 2 +- .../traits/formatting/concat_path.md | 8 +-- .../traits/formatting/static_format.md | 6 +- .../traits/formatting/static_string.md | 2 +- .../traits/optional/finalize_optional.md | 2 +- docs/reference/traits/shape/has_fields.md | 4 +- docs/reference/traits/shape/has_fields_ref.md | 2 +- docs/reference/traits/shape/to_fields.md | 4 +- .../traits/type-level/append_product.md | 8 +-- .../traits/type-level/concat_product.md | 4 +- .../reference/traits/type-level/map_fields.md | 12 ++-- docs/reference/traits/type-level/map_type.md | 2 +- .../traits/type-level/map_type_ref.md | 2 +- .../reference/traits/variant/extract_field.md | 2 +- .../traits/variant/finalize_extract.md | 6 +- .../traits/variant/finalize_extract_result.md | 4 +- .../traits/wiring/delegate_component.md | 2 +- docs/reference/types/{spines => }/chars.md | 44 ++++++------- docs/reference/types/{spines => }/cons.md | 57 ++++++++-------- docs/reference/types/{spines => }/either.md | 55 ++++++++-------- docs/reference/types/field.md | 7 +- docs/reference/types/index.md | 52 +++++++-------- docs/reference/types/index_type.md | 2 +- docs/reference/types/life.md | 6 +- docs/reference/types/mref.md | 2 +- docs/reference/types/{spines => }/nil.md | 40 ++++++------ .../reference/types/{spines => }/path_cons.md | 50 +++++++------- docs/reference/types/phantom_data.md | 9 +-- docs/reference/types/spines/_category_.json | 8 --- docs/reference/types/spines/index.md | 65 ------------------- docs/reference/types/{spines => }/void.md | 30 ++++----- 50 files changed, 259 insertions(+), 334 deletions(-) rename docs/reference/types/{spines => }/chars.md (73%) rename docs/reference/types/{spines => }/cons.md (70%) rename docs/reference/types/{spines => }/either.md (70%) rename docs/reference/types/{spines => }/nil.md (72%) rename docs/reference/types/{spines => }/path_cons.md (73%) delete mode 100644 docs/reference/types/spines/_category_.json delete mode 100644 docs/reference/types/spines/index.md rename docs/reference/types/{spines => }/void.md (81%) diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 54d28eb2..0191dedd 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -140,7 +140,7 @@ Symbol<6, Chars<'h', Chars<'e', Chars<'i', Chars<'g', Chars<'h', Chars<'t', Nil> `cargo cgp expand` resugars it back to `Symbol!("height")`, which is what you wrote. It does the same for the rest of the vocabulary — a pipeline reads `Product![StepOne, StepTwo]` rather than a `Cons` -spine, and a namespace key reads `Path!(@app.GreeterComponent)`. On a page of wiring the difference is +list, and a namespace key reads `Path!(@app.GreeterComponent)`. On a page of wiring the difference is between a listing you can read and one you have to decode. Two smaller differences follow from the same purpose. **`--item` understands Rust items** — asking for diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index 2212eac5..694abdac 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -47,7 +47,7 @@ help: the trait `HasField>`, which is why the bodies build a `Cons` chain. The -[type-level spines](../types/spines/index.md) page covers that shape, and it is the form printed in +[type-level lists](../types/index.md) page covers that shape, and it is the form printed in an error. -An enum's shape is the dual: an [`Either`](../types/spines/either.md) chain terminated by `Void` +An enum's shape is the dual: an [`Either`](../types/either.md) chain terminated by `Void` rather than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name: ```rust @@ -335,7 +335,7 @@ by one letter and the outputs do not overlap. shape are built from. - [`Field`](../types/field.md) — one entry: a value paired with its type-level name. - [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index_type.md) — the tags that name an entry. -- [Type-level spines](../types/spines/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains the +- [Type-level lists](../types/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains the sugar expands to. - [`AppendProduct`](../traits/type-level/append_product.md) — operations over a shape once you have one. - [`CanUpcast`](../traits/casting/can_upcast.md) — converting between two types whose shapes overlap. diff --git a/docs/reference/errors.md b/docs/reference/errors.md index e3b4c8e8..b262605c 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -306,7 +306,7 @@ or direct wiring puts a provider there: The same `[CGP-E107]` leaf covers a component the context simply never wired. The path is resugared to its `@app.GreeterComponent` form, which is the largest readability win here — raw `rustc` prints it as a -`PathCons>, _>` spine. +`PathCons>, _>` list. In the raw output this class is unusual in that the cause **is** the primary error rather than a note below it: an `E0277` saying a `PathCons<…>` path does not implement the namespace trait. A `Self` that is @@ -655,7 +655,7 @@ A tree entry that merely passes a non-CGP message through in rustc's own words i a diagnostic; the reason a checked error names the cause at all. - [`CanUseComponent`](./traits/wiring/can_use_component.md) — what a check asserts. - [`cargo cgp check`](/docs/cargo-cgp/check) — the tool every rewritten output on this page came from. -- [`Symbol!`](./macros/symbol.md) — the type-level field name whose raw `Chars<…>` spine the tool +- [`Symbol!`](./macros/symbol.md) — the type-level field name whose raw `Chars<…>` list the tool resugars. The ideas behind it: diff --git a/docs/reference/index.md b/docs/reference/index.md index b1018a3d..9bb4a615 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -203,10 +203,10 @@ one to start with: it is what lets a provider or a tag carry a type it stores no underlies most of the rest. You write the lists through sugar — [`Symbol!`](./macros/symbol.md) for a field name, [`Product!`](./macros/product.md) for a record list, [`Sum!`](./macros/sum.md) for its dual, [`Path!`](./macros/path.md) for a route — and only need to recognize the -[list spines](./types/spines/index.md) they expand into, [`Cons`](./types/spines/cons.md) and -[`Nil`](./types/spines/nil.md), [`Either`](./types/spines/either.md) and -[`Void`](./types/spines/void.md), [`Chars`](./types/spines/chars.md), and -[`PathCons`](./types/spines/path_cons.md), when one shows up in an error. Each entry in a record or a +[lists](./types/index.md) they expand into, [`Cons`](./types/cons.md) and +[`Nil`](./types/nil.md), [`Either`](./types/either.md) and +[`Void`](./types/void.md), [`Chars`](./types/chars.md), and +[`PathCons`](./types/path_cons.md), when one shows up in an error. Each entry in a record or a variant is a [`Field`](./types/field.md), tagged by a [`Symbol!`](./macros/symbol.md) or an [`Index`](./types/index_type.md), and [`Life`](./types/life.md) lifts a lifetime into a type where the wiring needs one. [`MRef`](./types/mref.md) is the odd one out, a runtime value a getter returns rather @@ -232,7 +232,7 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w |---|---| | `#[cgp_new_provider]` | [`#[cgp_provider]`](./macros/cgp_provider.md) | | `WithType`, `WithField`, `WithContext` | [`WithProvider`](./providers/with_provider.md) | -| `Symbol` (the type, not the `Symbol!` macro) | [`Chars`](./types/spines/chars.md) | +| `Symbol` (the type, not the `Symbol!` macro) | [`Chars`](./types/chars.md) | | `IdentMonadic`, `OkMonadic`, `ErrMonadic`, `OkMonadicTrans`, `ErrMonadicTrans` | [Monad providers](./providers/monad/index.md) | | `UseDelegatedType`, `WithDelegatedType` | [`UseDelegatedType`](./providers/use_delegated_type.md) and [`WithProvider`](./providers/with_provider.md) | | `MatchWithHandlersRef`, `MatchFirstWithHandlers`, and the other borrowed and first-argument matcher forms | the matcher page they vary, under [Dispatch combinators](./providers/dispatch/index.md) | diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index dc387310..cdbcbf43 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -263,7 +263,7 @@ derived from the trait name by stripping a leading `Has` and appending `Getter`, **A multi-method trait gets no `UseField` provider.** Both `UseField` and `WithProvider` are emitted only for a single-method trait, because each supplies one field. Wiring a two-method getter to `UseField` therefore reports the provider as not being a provider for the component, -with the tag expanded into its raw spine: +with the tag expanded into its raw list: ```text error[E0277]: the trait bound `UseField>>: IsProviderFor<..., ...>` diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index ddd22b18..693771de 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -300,8 +300,8 @@ after this impl and win where their keys are more specific. Two naming details appear verbatim in errors and are worth recognizing: the table parameter is literally `__Table__`, and the inheritance impl uses `__Key__` and `__Value__`. And every `@` path is a -[type-level list](../types/spines/path_cons.md) built by [`Path!`](./path.md); `expand` resugars it to -`Path!(@…)` form, while a raw compiler error prints the underlying spine. +[type-level list](../types/path_cons.md) built by [`Path!`](./path.md); `expand` resugars it to +`Path!(@…)` form, while a raw compiler error prints the underlying list. ## Formal grammar diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 1a93a3ee..ea8ad4ca 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -531,9 +531,9 @@ lookup appends after it, so one entry answers the redirect without having to pre the path reaching it. One presentational quirk is worth knowing before you compare these listings against your own expansion. -Both paths above are [`PathCons`](../types/spines/path_cons.md) lists, but `cargo cgp expand` prints +Both paths above are [`PathCons`](../types/path_cons.md) lists, but `cargo cgp expand` prints them differently: it resugars the header's redirect target to [`Path!`](./path.md) form while leaving -the per-entry key as the raw spine. So the same kind of type appears in two spellings in one expansion. +the per-entry key as the raw list. So the same kind of type appears in two spellings in one expansion. **A grouped path key expands to the cartesian product**, one impl pair per combination, each keyed on a full prefix ending in `__Wildcard__`. So diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md index 6d43b439..36adc7e7 100644 --- a/docs/reference/macros/index.md +++ b/docs/reference/macros/index.md @@ -60,5 +60,5 @@ fields or a handler pipeline's steps, [`Sum!`](./sum.md) builds the dual list fo and [`Path!`](./path.md) builds the routing list that namespaces and redirected lookups resolve against. All four are mostly generated for you, by a derive, by the ergonomic macros above, or by the `open` statement inside `delegate_components!`, and the skill worth having is reading one back out of -a compiler error rather than writing it, since a diagnostic actually prints the raw spine each expands +a compiler error rather than writing it, since a diagnostic actually prints the raw list each expands to (`Cons`/`Nil`, `Either`/`Void`, `PathCons`). diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 9f5e89a9..63ec72bc 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -15,7 +15,7 @@ component key. CGP needs such routes because [namespaces](./cgp_namespace.md) resolve lookups by path rather than by bare component name, which lets a whole subtree be rerouted at once and a single inherited entry be shadowed -without disturbing the rest. Written as the underlying spine, those routes are unreadable +without disturbing the rest. Written as the underlying list, those routes are unreadable (`PathCons<…, PathCons<…, Nil>>` nested several deep), so `Path!` lets one be written the way it reads: ```rust @@ -120,7 +120,7 @@ different things. - **Prefer the embedded form.** A namespace entry, a `#[prefix]`, or an `@`-path wiring key is where a route belongs, and each accepts the syntax directly. Naming a `type SomeRoute = Path!(…)` and using it indirectly usually makes the wiring harder to follow rather than easier. -- **Never hand-write the spine.** The macro expands to `PathCons>`, +- **Never hand-write the list.** The macro expands to `PathCons>`, and writing it out is longer and identical in meaning. - **Reach for the [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement) rather than constructing paths yourself** when the goal is per-type dispatch on one component. `open` builds @@ -151,7 +151,7 @@ PathCons< The macro parses the segments after the `@` into a list and folds them right to left onto `Nil`, wrapping each in a `PathCons` whose tail is the accumulated rest. A single-segment path is therefore `PathCons`. -**A lowercase segment nests a second spine inside the first**, which is why a fully-expanded path is longer than +**A lowercase segment nests a second list inside the first**, which is why a fully-expanded path is longer than it looks: the `Symbol` is itself a `Chars`/`Nil` chain, so `@app` desugars all the way down to ```rust @@ -169,7 +169,7 @@ The same fold drives the embedded forms. A [`cgp_namespace!`](./cgp_namespace.md followed by the component's own key. One presentational note: `cargo cgp expand` resugars a path back to `Path!(@…)` form in most positions, but not -uniformly. An `open` statement's per-entry key comes back as a raw `PathCons` spine while its header's redirect +uniformly. An `open` statement's per-entry key comes back as a raw `PathCons` list while its header's redirect target is resugared. Seeing the same kind of type in two spellings in one expansion is expected rather than a sign that they differ. @@ -219,7 +219,7 @@ the check rather than at the definition. - [`delegate_components!`](./delegate_components.md) — `@`-path keys and the `open` statement that builds routes for you. - [`Symbol!`](./symbol.md) — what a lowercase segment becomes. -- [Type-level spines](../types/spines/index.md) — the `PathCons` chain the expansion builds. +- [Type-level lists](../types/index.md) — the `PathCons` chain the expansion builds. - [`Product!`](./product.md) and [`Sum!`](./sum.md) — the sibling construction macros, sharing the fold shape. - [`DelegateComponent`](../traits/wiring/delegate_component.md) — the per-key table a resolved path finally reads. diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index a3adebcb..ad9b0660 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -13,7 +13,7 @@ A type-level list and its value-level counterpart. *shape* of a struct: the list of its fields, in order, as one type that generic code can reason about. It is sometimes called an anonymous product type, because like a tuple it holds several things at once. The -difference from a tuple is the one that matters: a `Product!` is built from a recursive spine that generic code +difference from a tuple is the one that matters: a `Product!` is built from a recursive list that generic code can take apart **one element at a time**: ```rust @@ -104,9 +104,9 @@ let row: Row = product![1, "hi".to_string(), true]; **Write `Product!` when a construct asks for a type-level list**, which in practice means a handler pipeline or a provider list. Everywhere else it is generated for you. -- **Never hand-write the spine.** `Product!` expands to `Cons>`, and writing it out is +- **Never hand-write the list.** `Product!` expands to `Cons>`, and writing it out is strictly worse: longer, harder to change, and identical in meaning. The same holds for - [`Sum!`](./sum.md)'s spine. + [`Sum!`](./sum.md)'s list. - **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for a struct's shape** rather than declaring the list yourself. Writing it by hand means restating the struct, and the two will disagree eventually. - **Use a tuple when nothing generic consumes it.** A `Product!` earns its keep only where code recurses over @@ -192,7 +192,7 @@ the order *is* the execution order. ## Related constructs - [`Sum!`](./sum.md) — the dual, for a choice among types rather than a collection of them. -- [Type-level spines](../types/spines/index.md) — the `Cons`/`Nil` types the expansion builds. +- [Type-level lists](../types/index.md) — the `Cons`/`Nil` types the expansion builds. - [`Field`](../types/field.md) — what the entries usually are, pairing a name with a type. - [`Symbol!`](./symbol.md) — the name half of a `Field` entry. - [`HasFields`](../traits/shape/has_fields.md) — the trait that exposes a struct's shape as one of these lists. @@ -203,8 +203,8 @@ the order *is* the execution order. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — the record representation this list is - the spine of. +- [Extensible records](/docs/concepts/extensible-records) — the record representation this list + encodes. ## Source diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 015e60ac..4d0aa631 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -20,7 +20,7 @@ a record. A `Sum!` holds a value for exactly **one** element, which is a tagged Sum![u32, String, bool] ``` -Like its dual it is built from a recursive spine, and that recursion makes variant-by-variant +Like its dual it is built from a recursive list, and that recursion makes variant-by-variant operations possible. Because an enum's variants are exposed as a single sum type through [`HasFields`](../traits/shape/has_fields.md), a provider can be written once to match on, dispatch over, or construct *any* enum's variants without naming the concrete enum, by walking the nested branches. This is the basis for @@ -91,7 +91,7 @@ use. - **Use [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or [`#[derive(HasFields)]`](../derives/derive_has_fields.md) on the enum**, which generates the list from the variants you already declared. Writing it out means restating the enum, and the two will drift. -- **Never hand-write the spine.** `Sum!` expands to `Either>`, and writing it out is +- **Never hand-write the list.** `Sum!` expands to `Either>`, and writing it out is longer and identical in meaning. - **Use [`Product!`](./product.md) for a collection rather than a choice.** They are duals: every element versus exactly one. A type error is the usual consequence of confusing them, which is at least loud. @@ -111,7 +111,7 @@ Sum![A, B, C] Either>> ``` -The two building blocks differ from the product spine in being *branching* rather than pairing. +The two building blocks differ from the product list in being *branching* rather than pairing. `Either` is an enum with two cases: `Left(Head)` selects the head type, and `Right(Tail)` defers to the rest of the chain. So a value of `Either>>` is `Left` for an `A`, `Right(Left(..))` for a `B`, and `Right(Right(Left(..)))` for a `C`. @@ -166,7 +166,7 @@ struct: the variant's payload type has to be a single nameable type for the sum ## Related constructs - [`Product!`](./product.md) — the dual, for a collection rather than a choice. -- [Type-level spines](../types/spines/index.md) — the `Either`/`Void` types the expansion builds. +- [Type-level lists](../types/index.md) — the `Either`/`Void` types the expansion builds. - [`Field`](../types/field.md) — what the branches usually are, pairing a variant name with its payload. - [`Symbol!`](./symbol.md) — the name half of a branch. - [`HasFields`](../traits/shape/has_fields.md) — the trait exposing an enum's shape as one of these sums. @@ -179,7 +179,7 @@ struct: the variant's payload type has to be a single nameable type for the sum The ideas behind it: - [Extensible variants](/docs/concepts/extensible-variants) — the variant representation this list - is the spine of. + encodes. ## Source diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index c71aded8..fc442af7 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -151,8 +151,8 @@ Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>> Two type constructors do the work. `Chars` is one character paired with the rest of the string; chained through its tail and terminated by `Nil`, it forms a -[type-level list](../types/spines/chars.md) of characters, the same shape as -[`Product!`](./product.md)'s `Cons`/`Nil` spine, specialized so the head is a `const char` rather than a type. +[type-level list](../types/chars.md) of characters, the same shape as +[`Product!`](./product.md)'s `Cons`/`Nil` list, specialized so the head is a `const char` rather than a type. `Symbol` then wraps that list together with a length. **The `LEN` parameter is the part most likely to surprise**, and it exists to work around a limit in stable @@ -214,7 +214,7 @@ type argument rather than the value. - [`#[implicit]`](../attributes/implicit.md) — generates the tag from an argument name. - [`#[cgp_auto_getter]`](./cgp_auto_getter.md) — generates it from a method name. - [`UseField`](../providers/use_field.md) — where the tag is written by hand, as a wiring decision. -- [Type-level spines](../types/spines/index.md) — the `Chars`/`Nil` chain the expansion builds. +- [Type-level lists](../types/index.md) — the `Chars`/`Nil` chain the expansion builds. - [`Product!`](./product.md) and [`Sum!`](./sum.md) — the record and variant lists whose entries carry these tags. - [`StaticFormat`](../traits/formatting/static_format.md) — recovering runtime text from a type-level string. diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 3d7b4f17..a01906ba 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -20,7 +20,7 @@ outer getter, then the next, ending at the target field. `ChainGetters` is a foundational [`FieldGetter`](../traits/field-access/field_getter.md), so it is wired to a getter component through the [`WithProvider`](with_provider.md) adapter rather than named on its own. The list -is a type-level [`Cons`](../types/spines/cons.md) spine whose elements are each a field getter for +is a type-level [`Cons`](../types/cons.md) list whose elements are each a field getter for the value the previous step produced, written with the [`Product!`](../macros/product.md) macro. `ChainGetters` recurses down the list. Like every CGP provider, it carries no runtime value: it is a marker named in wiring. @@ -151,7 +151,7 @@ impl FieldGetter for ChainGetters { ``` So a chain of one getter resolves to that getter applied to the context, a chain of two applies the -first then the second, and so on down the `Cons` spine. Because `ChainGetters` produces a `FieldGetter` +first then the second, and so on down the `Cons` list. Because `ChainGetters` produces a `FieldGetter` rather than the getter component's own provider trait, the [`WithProvider`](with_provider.md) adapter is what turns it into a provider a getter component can be wired to. diff --git a/docs/reference/providers/dispatch/match_with_field_handlers.md b/docs/reference/providers/dispatch/match_with_field_handlers.md index 2f671dcf..1352f5a5 100644 --- a/docs/reference/providers/dispatch/match_with_field_handlers.md +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -60,7 +60,7 @@ pub type MatchWithFieldHandlers = The per-variant list is built from a context's field list by three cooperating traits. `MapFieldHandler` is a type-level function from a field's `Tag` to the adapter that should handle it; `ToFieldHandlers` -walks the [sum spine](../../types/spines/either.md) of a field list and applies that function to each +walks the [sum list](../../types/either.md) of a field list and applies that function to each field, producing a [`Product!`](../../macros/product.md) list of adapters; and `HasFieldHandlers` reads a context's [`HasFields`](../../traits/shape/has_fields.md) list and runs `ToFieldHandlers` over it: @@ -74,7 +74,7 @@ where } ``` -`ToFieldHandlers` is implemented inductively over the sum spine: for `Either, Rest>` +`ToFieldHandlers` is implemented inductively over the sum list: for `Either, Rest>` it produces `Cons, Rest::Handlers>`, and for the terminating `Void` it produces `Nil`. The `MapFieldHandler` marker the crate supplies here is `MapExtractFieldAndHandle`, whose `FieldHandler` is [`ExtractFieldAndHandle`](extract_field_and_handle.md)``, so diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index b528136f..0a59089b 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -61,7 +61,7 @@ delegate_components! { ``` A `RedirectLookup` later walks the path-keyed entry above (`@bar.baz`). The path itself is a -[`PathCons`](../types/spines/path_cons.md) chain of [`Symbol!`](../macros/symbol.md) segments, most +[`PathCons`](../types/path_cons.md) chain of [`Symbol!`](../macros/symbol.md) segments, most easily written with [`Path!`](../macros/path.md). ## Examples @@ -153,7 +153,7 @@ table. - [`delegate_components!`](../macros/delegate_components.md) — the `open` and `namespace` statements that generate the redirect entries. - [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table the lookup reads. -- [`Path!`](../macros/path.md) and [`PathCons`](../types/spines/path_cons.md) — the type-level path it +- [`Path!`](../macros/path.md) and [`PathCons`](../types/path_cons.md) — the type-level path it walks. - [`UseContext`](use_context.md) — the other `#[cgp_component]`-generated provider, routing back to the context. diff --git a/docs/reference/traits/casting/can_downcast.md b/docs/reference/traits/casting/can_downcast.md index 590656c3..449d3450 100644 --- a/docs/reference/traits/casting/can_downcast.md +++ b/docs/reference/traits/casting/can_downcast.md @@ -138,7 +138,7 @@ stored where the original was. - [`HasExtractor`](../variant/has_extractor.md) — where the walk starts. - [`FromVariant`](../variant/from_variant.md) — how a matched variant is rebuilt into the target. - [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) — what makes an enum eligible. -- [Type-level spines](../../types/spines/index.md) — the `Either`/`Void` chain underneath. +- [Type-level lists](../../types/index.md) — the `Either`/`Void` chain underneath. The ideas behind it: diff --git a/docs/reference/traits/casting/can_upcast.md b/docs/reference/traits/casting/can_upcast.md index 4096e95f..9758820b 100644 --- a/docs/reference/traits/casting/can_upcast.md +++ b/docs/reference/traits/casting/can_upcast.md @@ -139,7 +139,7 @@ value type are both part of the entry. - [`ExtractField`](../variant/extract_field.md) and [`FromVariant`](../variant/from_variant.md) — the two primitives the recursion routes through. - [`HasFields`](../shape/has_fields.md) — the variant shape being walked. -- [Type-level spines](../../types/spines/index.md) — the `Either`/`Void` chain underneath. +- [Type-level lists](../../types/index.md) — the `Either`/`Void` chain underneath. - [Dispatch combinators](../../providers/dispatch/index.md) — where casting meets per-variant routing. The ideas behind it: diff --git a/docs/reference/traits/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md index b1f2e1bc..66e83180 100644 --- a/docs/reference/traits/formatting/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -25,7 +25,7 @@ A [`Path!`](../../macros/path.md) is a type-level list of segments — the route lookup is redirected along, or the chain of field names a nested getter descends. Composing two such routes means splicing one list onto the end of another, and `ConcatPath` is that operation. It is the path-level analogue of [`ConcatProduct`](../type-level/concat_product.md), with the same two-impl -recursion over a different spine. +recursion over a different list. ## Definition @@ -86,13 +86,13 @@ nothing to concatenate. - **Use [`ChainGetters`](../../providers/chain_getters.md)** rather than composing paths by hand when the goal is reaching a field on a nested context. That provider is the construct this operation serves. - **Use [`ConcatProduct`](../type-level/concat_product.md)** for field lists rather than paths. The two recursions - are the same shape over different spines and are not interchangeable. + are the same shape over different lists and are not interchangeable. - **Use [`StaticString`](./static_string.md)** if what you want is the segments as *text*. This produces a type; decoding it means decoding each segment's symbol. ## Under the hood -Two impls, one per spine node. Each node keeps its head segment and rebuilds the tail; the terminator +Two impls, one per list node. Each node keeps its head segment and rebuilds the tail; the terminator becomes the other path outright: ```rust @@ -138,7 +138,7 @@ normalizes them. ## Related constructs - [`Path!`](../../macros/path.md) — the sugar for the paths this joins. -- [`PathCons`](../../types/spines/path_cons.md) — the spine underneath. +- [`PathCons`](../../types/path_cons.md) — the list underneath. - [`ConcatProduct`](../type-level/concat_product.md) — the product-level analogue. - [`StaticString`](./static_string.md) — recovering a segment's name as text. - [`StaticFormat`](./static_format.md) — the lazy formatting counterpart. diff --git a/docs/reference/traits/formatting/static_format.md b/docs/reference/traits/formatting/static_format.md index e0ddf6b3..f7473385 100644 --- a/docs/reference/traits/formatting/static_format.md +++ b/docs/reference/traits/formatting/static_format.md @@ -39,7 +39,7 @@ pub trait StaticFormat { Note the absent `self`: there is no runtime value, only the type, so `fmt` takes the formatter alone and writes the type's characters into it. The trait is implemented for the type-level string itself, by -recursion over the character spine, and the terminator writes nothing. +recursion over the character list, and the terminator writes nothing. ## Usage @@ -66,7 +66,7 @@ assert_eq!(s.to_string(), "hello"); assert_eq!(format!("field: {s}"), "field: hello"); ``` -The impls exist for `Chars` — the character spine — and for `Nil`, which terminates it, with `Symbol` +The impls exist for `Chars` — the character list — and for `Nil`, which terminates it, with `Symbol` delegating to its inner list. Every type-level string therefore formats, including the empty one. ## Examples @@ -166,7 +166,7 @@ this trait is what you need when there is no value to construct. - [`StaticString`](./static_string.md) — the eager counterpart, and the one to reach for. - [`ConcatPath`](./concat_path.md) — path composition, its reachable sibling in the same group. - [`Symbol!`](../../macros/symbol.md) — the type-level string being formatted. -- [Type-level spines](../../types/spines/index.md) — the `Chars` chain being walked. +- [Type-level lists](../../types/index.md) — the `Chars` chain being walked. - [`HasField`](../field-access/has_field.md) — where the names being decoded are used as keys. The ideas behind it: diff --git a/docs/reference/traits/formatting/static_string.md b/docs/reference/traits/formatting/static_string.md index a9107223..4ed1a143 100644 --- a/docs/reference/traits/formatting/static_string.md +++ b/docs/reference/traits/formatting/static_string.md @@ -127,7 +127,7 @@ means decoding each segment's symbol. - [`StaticFormat`](./static_format.md) — the lazy counterpart, behind the `Display` impls. - [`ConcatPath`](./concat_path.md) — the same recovery idea one level up, for paths. - [`Symbol!`](../../macros/symbol.md) — the type-level string this decodes, and where the `LEN` comes from. -- [Type-level spines](../../types/spines/index.md) — the `Chars` chain being walked. +- [Type-level lists](../../types/index.md) — the `Chars` chain being walked. - [`HasField`](../field-access/has_field.md) — where the names being decoded are used as keys. - [`FinalizeOptional`](../optional/finalize_optional.md) — a real consumer, reporting a missing field by name. diff --git a/docs/reference/traits/optional/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md index d7a636ae..6efb0c68 100644 --- a/docs/reference/traits/optional/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -105,7 +105,7 @@ which field is missing and not enough to match on programmatically. Unlike its defaulting sibling, `FinalizeOptional` does **not** go through [`TransformMapFields`](../type-level/transform_map_fields.md). It walks the target's -[`HasFields`](../shape/has_fields.md) spine directly, and the reason is that it has to be able to *stop*. +[`HasFields`](../shape/has_fields.md) list directly, and the reason is that it has to be able to *stop*. For each field it pulls the `Option` out with [`UpdateField`](../builder/update_field.md), and: diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index 588f3092..4960d8ce 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -151,7 +151,7 @@ impl HasFields for Person { ``` `Product![A, B]` is `Cons>`, so a `Fields` type in an error message is a `Cons` chain -rather than the sugar — the [type-level spines](../../types/spines/index.md) page covers reading it. +rather than the sugar — the [type-level lists](../../types/index.md) page covers reading it. An enum's shape is the dual: an `Either` chain terminated by `Void` rather than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name and carrying that variant's own fields as a nested @@ -193,7 +193,7 @@ the other reserved names. - [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the list types a shape is built from. - [`Field`](../../types/field.md) — one entry: a value paired with its type-level name. -- [Type-level spines](../../types/spines/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains +- [Type-level lists](../../types/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. - [`AppendProduct`](../type-level/append_product.md) — the operations that compute new shapes from old ones. - [`CanUpcast`](../casting/can_upcast.md) and [`CanBuildFrom`](../casting/can_build_from.md) — conversions between two diff --git a/docs/reference/traits/shape/has_fields_ref.md b/docs/reference/traits/shape/has_fields_ref.md index 18bbb65d..982c069b 100644 --- a/docs/reference/traits/shape/has_fields_ref.md +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -116,7 +116,7 @@ impl HasFieldsRef for Person { } ``` -The transformation is uniform: each entry's value type `T` becomes `&'__a T`, and the spine is otherwise +The transformation is uniform: each entry's value type `T` becomes `&'__a T`, and the list is otherwise untouched — same length, same order, same tags. An enum's borrowed shape is the dual, an `Either` chain whose arms carry borrowed payloads. diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index 7ee16b2b..37785133 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -110,7 +110,7 @@ impl ToFields for Person { ``` An error message prints that chain when structural code fails to resolve, and the -[type-level spines](../../types/spines/index.md) page covers reading it. +[type-level lists](../../types/index.md) page covers reading it. An enum's conversion is the dual: each concrete variant is matched onto its arm of an `Either` chain terminated by `Void`, tagged with the variant name. @@ -146,7 +146,7 @@ such as a [cast](../casting/can_downcast.md). - [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. - [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md) — what a shape is made of. -- [Type-level spines](../../types/spines/index.md) — the `Cons` chain the conversion builds. +- [Type-level lists](../../types/index.md) — the `Cons` chain the conversion builds. - [`HasBuilder`](../builder/has_builder.md) — incremental assembly, as against this wholesale conversion. The ideas behind it: diff --git a/docs/reference/traits/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md index 48d880dc..258f4ed8 100644 --- a/docs/reference/traits/type-level/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -102,7 +102,7 @@ There is no `AppendSum`. Growing a sum is not an operation this layer provides. ## Under the hood -The trait is a pair of impls, one for the spine's `Cons` node and one for its `Nil` terminator. Each head +The trait is a pair of impls, one for the list's `Cons` node and one for its `Nil` terminator. Each head is kept and the tail rebuilt, with a single-element list grafted on at the end: ```rust @@ -118,7 +118,7 @@ where } ``` -Because the recursion only ever rebuilds the spine, order is structurally preserved — which is why +Because the recursion only ever rebuilds the list, order is structurally preserved — which is why appending yields a *different* type from prepending, and why two products with the same entries in different orders are unrelated types. @@ -138,7 +138,7 @@ unresolved-associated-type error. **Order is part of the type.** Appending is not commutative with prepending, and nothing reorders a list to make two shapes match. -**A long list means a deep recursion.** This is trait resolution over the spine, so a very wide struct +**A long list means a deep recursion.** This is trait resolution over the list, so a very wide struct costs compile time proportional to its width — one of the places CGP's compile-time cost actually comes from. @@ -147,7 +147,7 @@ from. - [`ConcatProduct`](./concat_product.md) — the general form; append is its single-entry case. - [`MapFields`](./map_fields.md) — rewriting every entry rather than adding one. - [`Product!`](../../macros/product.md) — the sugar for the lists this operates on. -- [Type-level spines](../../types/spines/index.md) — the `Cons`/`Nil` chain underneath. +- [Type-level lists](../../types/index.md) — the `Cons`/`Nil` chain underneath. - [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. - [`Field`](../../types/field.md) — the entries a field list is usually made of. - [`HasBuilder`](../builder/has_builder.md) — the family that moves values through the shapes this computes. diff --git a/docs/reference/traits/type-level/concat_product.md b/docs/reference/traits/type-level/concat_product.md index 2455f629..a05caf34 100644 --- a/docs/reference/traits/type-level/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -92,7 +92,7 @@ There is no `ConcatSum`. Combining two sums is not an operation this layer provi ## Under the hood -Two impls, one per spine node. Each head is kept and the tail rebuilt; at the terminator, the whole +Two impls, one per list node. Each head is kept and the tail rebuilt; at the terminator, the whole second list is substituted: ```rust @@ -140,7 +140,7 @@ to the first one's width. - [`MapFields`](./map_fields.md) — rewriting every entry rather than adding any. - [`ConcatPath`](../formatting/concat_path.md) — the same operation over type-level paths. - [`Product!`](../../macros/product.md) — the sugar for the lists this operates on. -- [Type-level spines](../../types/spines/index.md) — the `Cons`/`Nil` chain underneath. +- [Type-level lists](../../types/index.md) — the `Cons`/`Nil` chain underneath. - [`CanBuildFrom`](../casting/can_build_from.md) — merging the values whose shapes this combines. - [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index 9b0bc803..cb305812 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -31,7 +31,7 @@ is the identity; with `IsNothing` every entry collapses to `()`; with `IsOptiona `Option<_>`; with `IsVoid` every entry becomes uninhabited. It is the transforming member of the three product operations, and the only one defined over **both** -spines: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum. That lets one +lists: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum. That lets one operation produce both a partial record and a partial enum. ## Definition @@ -105,7 +105,7 @@ Three similar names, three unrelated jobs. ## Under the hood -Like its two siblings, `MapFields` is a pair of impls per spine, one for the node and one for the +Like its two siblings, `MapFields` is a pair of impls per list, one for the node and one for the terminator. Unlike them, it *transforms* the head rather than preserving it: ```rust @@ -123,7 +123,7 @@ impl MapFields for Nil { ``` The `Either`/`Void` impls mirror these exactly, with `Either` standing where `Cons` does and `Void` where -`Nil` does. Because the recursion only ever replaces a head *type*, the spine's length and shape are +`Nil` does. Because the recursion only ever replaces a head *type*, the list's length and shape are structurally preserved — which is why a mapped product is still a product of the same arity, and a mapped sum still a sum. @@ -157,8 +157,8 @@ width. that grow a list rather than rewrite it. - [`TransformMapFields`](./transform_map_fields.md) — the value-level counterpart, which actually converts the fields. -- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the sugar for both spines. -- [Type-level spines](../../types/spines/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the sugar for both lists. +- [Type-level lists](../../types/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains underneath. - [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. - [`MapField`](../field-access/map_field.md) — the similarly-named lifetime helper, which does something else entirely. @@ -171,7 +171,7 @@ The ideas behind it: ## Source - [`map_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_fields.rs) - — `MapFields`, over both spines + — `MapFields`, over both lists --- diff --git a/docs/reference/traits/type-level/map_type.md b/docs/reference/traits/type-level/map_type.md index 0f648741..29392971 100644 --- a/docs/reference/traits/type-level/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -170,7 +170,7 @@ and transform impls are written against the standard markers, so a custom one ha - [`MapFields`](./map_fields.md) — applies one marker across a whole type-level list. - [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — generates the partial types these markers parameterize. -- [Type-level spines](../../types/spines/index.md) — where the uninhabited `Void` comes from. +- [Type-level lists](../../types/index.md) — where the uninhabited `Void` comes from. The ideas behind it: diff --git a/docs/reference/traits/type-level/map_type_ref.md b/docs/reference/traits/type-level/map_type_ref.md index 4bc77d50..4e7fa27c 100644 --- a/docs/reference/traits/type-level/map_type_ref.md +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -169,7 +169,7 @@ reads as though the machinery is at fault. - [`ToFieldsRef`](../shape/to_fields_ref.md) — the record side's answer to the same problem. - [`HasFieldsRef`](../shape/has_fields_ref.md) — the borrowed shape it produces. - [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the borrowed companion. -- [Type-level spines](../../types/spines/index.md) — the `Either`/`Void` chain underneath. +- [Type-level lists](../../types/index.md) — the `Either`/`Void` chain underneath. The ideas behind it: diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index 086d67cb..1ac96ead 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -188,7 +188,7 @@ reason to prefer the [dispatch combinators](../../providers/dispatch/index.md). impl here. - [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain for you. -- [Type-level spines](../../types/spines/index.md) — `Either`/`Void`, where the uninhabited terminator +- [Type-level lists](../../types/index.md) — `Either`/`Void`, where the uninhabited terminator comes from. The ideas behind it: diff --git a/docs/reference/traits/variant/finalize_extract.md b/docs/reference/traits/variant/finalize_extract.md index 58375f05..c338057c 100644 --- a/docs/reference/traits/variant/finalize_extract.md +++ b/docs/reference/traits/variant/finalize_extract.md @@ -32,7 +32,7 @@ pub trait FinalizeExtract { `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 trait is implemented for the uninhabited -[`Void`](../../types/spines/void.md), the standard `Infallible`, and the all-ruled-out +[`Void`](../../types/void.md), the standard `Infallible`, and the all-ruled-out configuration of a partial enum. ## Usage @@ -91,7 +91,7 @@ remainder.** The two do the same job at different points in the chain. ## Under the hood **Everything turns on what `IsVoid` maps to.** The [`MapType`](../type-level/map_type.md) marker `IsVoid` maps a -payload to the uninhabited [`Void`](../../types/spines/void.md), so once every variant's marker is +payload to the uninhabited [`Void`](../../types/void.md), 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: @@ -143,7 +143,7 @@ that cannot occur. - [`HasExtractor`](./has_extractor.md) — where a chain begins. - [`FinalizeBuild`](../builder/finalize_build.md) — the record family's ending, sound for the opposite reason. - [`MapType`](../type-level/map_type.md) — the `IsVoid` marker the argument rests on. -- [Type-level spines](../../types/spines/index.md) — where the uninhabited `Void` comes from. +- [Type-level lists](../../types/index.md) — where the uninhabited `Void` comes from. - [`CanUpcast`](../casting/can_upcast.md) — a cast whose total walk ends with this same discharge. - [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain. - [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates this impl. diff --git a/docs/reference/traits/variant/finalize_extract_result.md b/docs/reference/traits/variant/finalize_extract_result.md index 503a0b25..5a2c8a07 100644 --- a/docs/reference/traits/variant/finalize_extract_result.md +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -120,7 +120,7 @@ soundness argument lives: the remainder is uninhabited once every variant is `Is 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`](../../types/spines/void.md). That is occasionally useful +whose error is `Infallible` or [`Void`](../../types/void.md). That is occasionally useful outside the extractor family, for collapsing a `Result` that a signature required but that cannot fail. `Output` being an associated type rather than a generic lets the call sit at the end of a method @@ -151,7 +151,7 @@ bound stops being satisfied. - [`ExtractField`](./extract_field.md) — the narrowing that produces the `Result` this collapses. - [`HasExtractor`](./has_extractor.md) — where a chain begins. - [`FinalizeBuild`](../builder/finalize_build.md) — the record family's ending. -- [Type-level spines](../../types/spines/index.md) — where the uninhabited `Void` comes from. +- [Type-level lists](../../types/index.md) — where the uninhabited `Void` comes from. - [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain for you. - [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — what makes an enum extractable. diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index b6b21870..f76a62f0 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -106,7 +106,7 @@ An **arbitrary type** — a shape, a tag — makes the table a plain dispatch ma attached. This is what the nested tables inside [`UseDelegate`](../../providers/use_delegate.md) are, and what the `open` statement's per-key entries resolve through. -A **type-level path** — a [`PathCons`](../../types/spines/path_cons.md) list built by +A **type-level path** — a [`PathCons`](../../types/path_cons.md) list built by [`Path!`](../../macros/path.md) — is how namespaces key their entries, so a lookup walks one segment at a time. [`RedirectLookup`](../../providers/redirect_lookup.md) is the provider that performs that walk. diff --git a/docs/reference/types/spines/chars.md b/docs/reference/types/chars.md similarity index 73% rename from docs/reference/types/spines/chars.md rename to docs/reference/types/chars.md index 3c89abd6..8b8be863 100644 --- a/docs/reference/types/spines/chars.md +++ b/docs/reference/types/chars.md @@ -1,18 +1,18 @@ --- sidebar_label: 'Chars' -sidebar_position: 5 +sidebar_position: 9 --- # `Chars` -One character of a type-level string: the spine that spells a field name out one character at a time so +One character of a type-level string: the list that spells a field name out one character at a time so the name can be a type. :::info ### Generated machinery -**You are not expected to write `Chars` by hand.** The [`Symbol!`](../../macros/symbol.md) macro folds a +**You are not expected to write `Chars` by hand.** The [`Symbol!`](../macros/symbol.md) macro folds a string literal into a `Chars` chain, and a `Symbol` wraps that chain. You meet `Chars` in a missing-field error, where a field name prints as its expanded character list, and this page explains how to read it. @@ -24,16 +24,16 @@ to read it. `Chars` encodes a string as a type, so that a field name can take part in trait resolution. CGP keys field access by a tag type: to read a field called `name`, something must stand in for the string `"name"` at the type level, so the compiler can match one -[`HasField`](../../traits/field-access/has_field.md) impl against another purely from the tag. A `Chars` +[`HasField`](../traits/field-access/has_field.md) impl against another purely from the tag. A `Chars` chain is how the string becomes a type, and a `Symbol` wrapping that chain is the tag itself. The reason the encoding is a *list of characters* is a limit in stable Rust: a `String` or `&str` cannot be a const-generic parameter, but a single `char` can. So CGP spells the string out one character at a -time through a recursive `Chars` spine, terminated by [`Nil`](nil.md), the same way the product spine +time through a recursive `Chars` list, terminated by [`Nil`](nil.md), the same way the product list spells out its elements through [`Cons`](cons.md). `Chars` is the specialized form of `Cons` in which the head is a `const char` rather than a type. -You write this through [`Symbol!`](../../macros/symbol.md) rather than by hand. `Symbol!("abc")` folds +You write this through [`Symbol!`](../macros/symbol.md) rather than by hand. `Symbol!("abc")` folds into `Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>`, and that macro's page carries the fold, the byte-length parameter, and the rest of the wrapper. This page is the runtime `Chars` type underneath. @@ -48,21 +48,21 @@ pub struct Chars(pub PhantomData); `CHAR` is the character at this position, and `Tail` is the rest of the string, expected to be either the next `Chars` node or [`Nil`](nil.md) at the end. The character lives in the const parameter and the tail -in a [`PhantomData`](../phantom_data.md), so a `Chars` chain carries no runtime data and is erased +in a [`PhantomData`](phantom_data.md), so a `Chars` chain carries no runtime data and is erased to a zero-sized value. A `Symbol` then wraps such a chain together with the string's byte length; the length is stored explicitly because stable Rust cannot compute it inside a -const-generic context, and [`Symbol!`](../../macros/symbol.md) covers why. +const-generic context, and [`Symbol!`](../macros/symbol.md) covers why. ## Behavior A `Chars` chain reconstructs its original string on demand through the -[`StaticFormat`](../../traits/formatting/static_format.md) trait, which formats a type-level string into a +[`StaticFormat`](../traits/formatting/static_format.md) trait, which formats a type-level string into a `Formatter` without needing a value. `Chars` writes `CHAR` and then recurses into the tail, and [`Nil`](nil.md) ends the recursion by writing nothing. A `Symbol` forwards to its inner `Chars`, and its `Display` impl defers to `StaticFormat`, so `::default().to_string()` yields `"hello"`. -The length a `Symbol` records enables [`StaticString`](../../traits/formatting/static_string.md), which +The length a `Symbol` records enables [`StaticString`](../traits/formatting/static_string.md), which exposes the string as a `const VALUE: &'static str` rather than a formatting routine, by decoding the characters into a byte buffer sized by that length at compile time. Code that needs the string at run time uses `Display`; code that needs it as a const uses `StaticString`. @@ -70,7 +70,7 @@ time uses `Display`; code that needs it as a const uses `StaticString`. ## Examples A type-level string most often appears as the tag in a -[`HasField`](../../traits/field-access/has_field.md) bound, where it names the field a provider reads: +[`HasField`](../traits/field-access/has_field.md) bound, where it names the field a provider reads: ```rust use cgp::prelude::*; @@ -101,15 +101,15 @@ just the terminator and whose recorded length is zero. ## When to use it -**You read `Chars` in an error; you write [`Symbol!`](../../macros/symbol.md).** The macro produces the +**You read `Chars` in an error; you write [`Symbol!`](../macros/symbol.md).** The macro produces the chain, and the reason to know the type is to decode a field name in a diagnostic. - **Decode a `Chars` chain by reading off the characters.** An error mentioning `HasField>>>` is telling you the field `width` is missing, and `cargo cgp check` resugars the common cases. -- **Use [`Symbol!`](../../macros/symbol.md) for a field-name tag,** and let the ergonomic constructs +- **Use [`Symbol!`](../macros/symbol.md) for a field-name tag,** and let the ergonomic constructs produce it from an argument or a method name where they can. -- **Use [`Index`](../index_type.md) for a tuple-field position,** which encodes a number rather than a +- **Use [`Index`](index_type.md) for a tuple-field position,** which encodes a number rather than a string. ## Common Mistakes @@ -127,15 +127,15 @@ a `const char`, so it cannot carry arbitrary element types the way a product lis ## Related constructs - [`Nil`](nil.md) — the end marker that terminates a `Chars` chain. -- [`Cons`](cons.md) — the general product spine this one specializes, with a type head rather than a +- [`Cons`](cons.md) — the general product list this one specializes, with a type head rather than a `const char`. -- [`Symbol!`](../../macros/symbol.md) — the macro that folds a string into a `Chars` chain and wraps it. -- [`StaticFormat`](../../traits/formatting/static_format.md) and - [`StaticString`](../../traits/formatting/static_string.md) — recover the runtime string and the const +- [`Symbol!`](../macros/symbol.md) — the macro that folds a string into a `Chars` chain and wraps it. +- [`StaticFormat`](../traits/formatting/static_format.md) and + [`StaticString`](../traits/formatting/static_string.md) — recover the runtime string and the const from the chain. -- [`HasField`](../../traits/field-access/has_field.md) — matches a field against its `Symbol!` tag. -- [`Field`](../field.md) — carries a `Symbol!` tag beside its value. -- [`Index`](../index_type.md) — the position tag for a tuple field, the numeric counterpart. +- [`HasField`](../traits/field-access/has_field.md) — matches a field against its `Symbol!` tag. +- [`Field`](field.md) — carries a `Symbol!` tag beside its value. +- [`Index`](index_type.md) — the position tag for a tuple field, the numeric counterpart. The ideas behind it: @@ -153,7 +153,7 @@ The ideas behind it: [`static_format.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/static_format.rs), and the const-decoding `StaticString`: [`static_string.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/static_string.rs) -- The constructing macro is [`Symbol!`](../../macros/symbol.md). +- The constructing macro is [`Symbol!`](../macros/symbol.md). --- diff --git a/docs/reference/types/spines/cons.md b/docs/reference/types/cons.md similarity index 70% rename from docs/reference/types/spines/cons.md rename to docs/reference/types/cons.md index afdd652c..e55193b4 100644 --- a/docs/reference/types/spines/cons.md +++ b/docs/reference/types/cons.md @@ -1,11 +1,11 @@ --- sidebar_label: 'Cons' -sidebar_position: 1 +sidebar_position: 5 --- # `Cons` -The head-and-tail cell of the product spine: the recursive list that describes a record, one field at a +The head-and-tail cell of the product list: the recursive list that describes a record, one field at a time. :::info @@ -13,8 +13,8 @@ time. ### Generated machinery **You are not expected to write `Cons` by hand.** You build a product list with the -[`Product!`](../../macros/product.md) and `product!` macros, and a struct's field list comes from -[`#[derive(HasFields)]`](../../derives/derive_has_fields.md). You meet `Cons` in an expansion and in a +[`Product!`](../macros/product.md) and `product!` macros, and a struct's field list comes from +[`#[derive(HasFields)]`](../derives/derive_has_fields.md). You meet `Cons` in an expansion and in a field-mismatch error, and this page explains its shape so those read clearly. ::: @@ -27,16 +27,16 @@ by generic code element by element; a recursive list can. `Cons` pairs the first the list, and [`Nil`](nil.md) marks the end, so the two together form an *anonymous product type*: a record-shaped value that code can walk without knowing the concrete struct it came from. -This spine makes structural, field-by-field operations work across every struct uniformly. A -struct's fields are exposed as one list type through [`HasFields`](../../traits/shape/has_fields.md), so a +This list makes structural, field-by-field operations work across every struct uniformly. A +struct's fields are exposed as one list type through [`HasFields`](../traits/shape/has_fields.md), so a provider written once to recurse over `Cons` and `Nil` can iterate, transform, read, or rebuild *any* struct's fields. Each step handles the `Head`, then recurses into the `Tail`, until it reaches `Nil` and stops. -You write this spine through the [`Product!`](../../macros/product.md) macro rather than by hand. +You write this list through the [`Product!`](../macros/product.md) macro rather than by hand. `Product![A, B, C]` is the right-nested `Cons` chain, and the value macro `product![a, b, c]` builds a -matching value. The elements are most often [`Field`](../field.md) entries pairing a name with a value, -so a struct's layout becomes a `Product!` of `Field` cells over this spine. +matching value. The elements are most often [`Field`](field.md) entries pairing a name with a value, +so a struct's layout becomes a `Product!` of `Field` cells over this list. ## Definition @@ -49,7 +49,7 @@ pub struct Cons(pub Head, pub Tail); `Head` is the first element's type and `Tail` is the rest of the list, itself another `Cons` or, at the end, [`Nil`](nil.md). Both positional fields are public, so `Cons(head, tail)` builds a cell and `.0` and -`.1` reach its parts. Unlike the zero-sized [`Chars`](chars.md) and [`PathCons`](path_cons.md) spines, +`.1` reach its parts. Unlike the zero-sized [`Chars`](chars.md) and [`PathCons`](path_cons.md) lists, `Cons` holds real values: it is as large as its elements laid out by nesting, with nothing boxed or virtual. It derives `Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a list of values that implement those traits inherits them structurally, comparing head to head down the chain. @@ -61,7 +61,7 @@ is `Cons>>`, and the empty `Product![]` is just `Nil`. T built with the tuple-struct constructor, `Cons(a, Cons(b, Cons(c, Nil)))`, so a `product!` value is an ordinary owned value whose type is exactly the one `Product!` produces over the same elements' types. -Generic code consumes the spine by recursing on its two cases. A trait implemented for `Nil` supplies +Generic code consumes the list by recursing on its two cases. A trait implemented for `Nil` supplies the base case, the empty list, and a blanket impl for `Cons` supplies the recursive step, usually constraining `Tail` to implement the same trait so the recursion bottoms out at `Nil`. This pairing of a `Nil` impl with a `Cons` impl is the standard shape for any operation that @@ -70,8 +70,8 @@ code. ## Examples -The product spine appears most visibly as the `Fields` of a struct that derives -[`HasFields`](../../derives/derive_has_fields.md), where the [`Product!`](../../macros/product.md) sugar +The product list appears most visibly as the `Fields` of a struct that derives +[`HasFields`](../derives/derive_has_fields.md), where the [`Product!`](../macros/product.md) sugar hides the `Cons`/`Nil` chain: ```rust @@ -108,14 +108,14 @@ let row: Row = product![1, "hi".to_string(), true]; ## When to use it -**Read `Cons` in an expansion; write [`Product!`](../../macros/product.md) instead.** The spine is what -the sugar produces, and spelling it out by hand is longer, harder to change, and identical in meaning. +**Read `Cons` in an expansion; write [`Product!`](../macros/product.md) instead.** The sugar produces +the list, and spelling it out by hand is longer, harder to change, and identical in meaning. -- **Use [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) for a struct's shape** rather than +- **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for a struct's shape** rather than declaring the `Cons` chain yourself, since a hand-written list restates the struct and the two drift apart. -- **Use [`Product!`](../../macros/product.md) for a list you write on purpose,** such as a handler - pipeline, and let it build the spine. +- **Use [`Product!`](../macros/product.md) for a list you write on purpose,** such as a handler + pipeline, and let it build the list. - **Decode a `Cons` chain in an error by counting cells.** A field-list mismatch is reported as a mismatch between two `Cons` chains, and the position where they diverge is the field that differs. @@ -126,26 +126,25 @@ list of one still carries its cell. **Element order is part of the type.** `Cons>` and `Cons>` are unrelated types. For a field list this matters less than it sounds, because the entries are name-tagged -[`Field`](../field.md)s and the operations match on names; for a handler pipeline the order is the +[`Field`](field.md)s and the operations match on names; for a handler pipeline the order is the execution order. -**The empty product is [`Nil`](nil.md), a real value.** That is the difference from the sum spine, whose +**The empty product is [`Nil`](nil.md), a real value.** That is the difference from the sum list, whose empty form is the uninhabited [`Void`](void.md). An empty record exists; an empty choice cannot. ## Related constructs -- [`Nil`](nil.md) — the end marker that terminates this spine. -- [`Either`](either.md) and [`Void`](void.md) — the sum spine, the choice-shaped dual of this one. -- [`Chars`](chars.md) — the same spine specialized to a `const char` head. -- [`Product!`](../../macros/product.md) — the macro that folds elements onto this spine. -- [`Field`](../field.md) — what the elements usually are, pairing a name with a value. -- [`HasFields`](../../traits/shape/has_fields.md) — exposes a struct's shape as one of these lists. -- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates that list for a struct. +- [`Nil`](nil.md) — the end marker that terminates this list. +- [`Either`](either.md) and [`Void`](void.md) — the sum list, the choice-shaped dual of this one. +- [`Chars`](chars.md) — the same list specialized to a `const char` head. +- [`Product!`](../macros/product.md) — the macro that folds elements onto this list. +- [`Field`](field.md) — what the elements usually are, pairing a name with a value. +- [`HasFields`](../traits/shape/has_fields.md) — exposes a struct's shape as one of these lists. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates that list for a struct. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — the record representation this spine is the - backbone of. +- [Extensible records](/docs/concepts/extensible-records) — the record representation this list encodes. ## Source diff --git a/docs/reference/types/spines/either.md b/docs/reference/types/either.md similarity index 70% rename from docs/reference/types/spines/either.md rename to docs/reference/types/either.md index 19864f4c..9ed46014 100644 --- a/docs/reference/types/spines/either.md +++ b/docs/reference/types/either.md @@ -1,11 +1,11 @@ --- sidebar_label: 'Either' -sidebar_position: 3 +sidebar_position: 7 --- # `Either` -The head-or-rest cell of the sum spine: the recursive list that describes an enum, one variant at a +The head-or-rest cell of the sum list: the recursive list that describes an enum, one variant at a time. :::info @@ -13,8 +13,8 @@ time. ### Generated machinery **You are not expected to write `Either` by hand.** You build a sum list with the -[`Sum!`](../../macros/sum.md) macro, and an enum's variant list comes from -[`#[derive(HasFields)]`](../../derives/derive_has_fields.md). You meet `Either` in an expansion and in a +[`Sum!`](../macros/sum.md) macro, and an enum's variant list comes from +[`#[derive(HasFields)]`](../derives/derive_has_fields.md). You meet `Either` in an expansion and in a variant-mismatch error, and this page explains its shape so those read clearly. ::: @@ -22,20 +22,20 @@ variant-mismatch error, and this page explains its shape so those read clearly. ## Overview `Either` represents a choice among several types as a single type, so an enum's variants can -be reasoned about generically. Where the [product spine](cons.md) holds a value for *every* element at -once, the sum spine holds a value for exactly *one* of its branches: a tagged union, or *anonymous sum +be reasoned about generically. Where the [product list](cons.md) holds a value for *every* element at +once, the sum list holds a value for exactly *one* of its branches: a tagged union, or *anonymous sum type*. `Either` branches at each step, and [`Void`](void.md) marks the end, so the two together form a coproduct that code can walk without knowing the concrete enum it came from. -This spine makes structural, variant-by-variant operations work across every enum uniformly. An -enum's variants are exposed as one sum type through [`HasFields`](../../traits/shape/has_fields.md), so a +This list makes structural, variant-by-variant operations work across every enum uniformly. An +enum's variants are exposed as one sum type through [`HasFields`](../traits/shape/has_fields.md), so a provider written once to recurse over the `Either` and `Void` branches can match, dispatch on, or construct *any* enum's variants. This is the basis for CGP's extensible-variant machinery: a variant is reached by walking the nested branches rather than by a hand-written `match` against a fixed enum. -You write this spine through the [`Sum!`](../../macros/sum.md) macro. `Sum![A, B, C]` is the right-nested -`Either` chain terminated by `Void`. The branches are most often [`Field`](../field.md) entries pairing a -variant name with its payload, so an enum's shape becomes a `Sum!` of `Field` branches over this spine. +You write this list through the [`Sum!`](../macros/sum.md) macro. `Sum![A, B, C]` is the right-nested +`Either` chain terminated by `Void`. The branches are most often [`Field`](field.md) entries pairing a +variant name with its payload, so an enum's shape becomes a `Sum!` of `Field` branches over this list. ## Definition @@ -62,16 +62,16 @@ branch by how deep it sits: `Left(a)` is an `A`, `Right(Left(b))` is a `B`, and is a `C`. Reaching the `Void` position would mean the value matched none of the listed branches, which is impossible, because `Void` has no values, so the chain is closed off at its end. -Generic code consumes the sum by recursing on its two cases, mirroring how it folds the product spine but +Generic code consumes the sum by recursing on its two cases, mirroring how it folds the product list but branching instead of pairing. A `Left` is handled directly as the head; a `Right` defers to a trait impl on the `Tail`, recursing until a `Left` is found. The base case is the [`Void`](void.md) terminator, and -here the difference from the product spine matters: a product ends in the constructible [`Nil`](nil.md), +here the difference from the product list matters: a product ends in the constructible [`Nil`](nil.md), but a sum ends in the uninhabited `Void`, because an empty choice has no value to pick. ## Examples -The sum spine appears most visibly as the `Fields` of an enum that derives -[`#[derive(HasFields)]`](../../derives/derive_has_fields.md), where the [`Sum!`](../../macros/sum.md) sugar +The sum list appears most visibly as the `Fields` of an enum that derives +[`#[derive(HasFields)]`](../derives/derive_has_fields.md), where the [`Sum!`](../macros/sum.md) sugar hides the `Either`/`Void` chain: ```rust @@ -111,10 +111,10 @@ let t: Token = Either::Right(Either::Left("hi".to_string())); // the String bran ## When to use it -**Read `Either` in an expansion; write [`Sum!`](../../macros/sum.md) instead.** The spine is what the -sugar produces, and spelling it out by hand is longer, harder to change, and identical in meaning. +**Read `Either` in an expansion; write [`Sum!`](../macros/sum.md) instead.** The sugar produces the +list, and spelling it out by hand is longer, harder to change, and identical in meaning. -- **Use [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) for an enum's shape** rather than +- **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for an enum's shape** rather than declaring the `Either` chain yourself. - **Decode an `Either` chain in an error by counting the `Right` wrappers.** The depth is which variant a value selects, and a mismatch is reported as a mismatch between two `Either` chains. @@ -125,7 +125,7 @@ sugar produces, and spelling it out by hand is longer, harder to change, and ide ## Common Mistakes **A sum holds one branch, not all of them.** `Either>` is a value that is *either* an -`A` or a `B`, not both. This is the opposite of the [product spine](cons.md), and confusing the two is the +`A` or a `B`, not both. This is the opposite of the [product list](cons.md), and confusing the two is the usual cause of a "expected `Either`, found `Cons`" error. **The empty sum is the uninhabited [`Void`](void.md), not a value.** `Sum![]` is `Void`, which has no @@ -133,22 +133,21 @@ values, so an empty choice cannot be constructed. An empty record can, because i [`Nil`](nil.md). **Branch order is part of the type.** `Sum![A, B]` and `Sum![B, A]` are unrelated types. Because the -branches are name-tagged [`Field`](../field.md)s and the operations match on names, this bites less than +branches are name-tagged [`Field`](field.md)s and the operations match on names, this bites less than it might, but the types still differ. ## Related constructs -- [`Void`](void.md) — the uninhabited end marker that terminates this spine. -- [`Cons`](cons.md) and [`Nil`](nil.md) — the product spine, the record-shaped dual of this one. -- [`Sum!`](../../macros/sum.md) — the macro that folds element types onto this spine. -- [`Field`](../field.md) — what the branches usually are, pairing a variant name with its payload. -- [`HasFields`](../../traits/shape/has_fields.md) — exposes an enum's shape as one of these lists. -- [`ExtractField`](../../traits/variant/extract_field.md) — the extractor family that walks this spine. +- [`Void`](void.md) — the uninhabited end marker that terminates this list. +- [`Cons`](cons.md) and [`Nil`](nil.md) — the product list, the record-shaped dual of this one. +- [`Sum!`](../macros/sum.md) — the macro that folds element types onto this list. +- [`Field`](field.md) — what the branches usually are, pairing a variant name with its payload. +- [`HasFields`](../traits/shape/has_fields.md) — exposes an enum's shape as one of these lists. +- [`ExtractField`](../traits/variant/extract_field.md) — the extractor family that walks this list. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — the variant representation this spine is the - backbone of. +- [Extensible variants](/docs/concepts/extensible-variants) — the variant representation this list encodes. ## Source diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index 677edeeb..fb030b48 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -35,7 +35,7 @@ field-by-field generic code possible. This is the same type-as-name trick that [`Symbol!`](../macros/symbol.md) provides for a named field and [`Index`](index_type.md) for a tuple position. `Field` is where that tag meets the value it labels. -`Field` fills both structural spines. In a record it is the element of a [`Product!`](../macros/product.md) +`Field` fills both structural lists. In a record it is the element of a [`Product!`](../macros/product.md) of entries, one per field. In a variant it is the element of a [`Sum!`](../macros/sum.md) of entries, one per variant, where the `Value` is the variant's payload. The same `Field` shape names a field in a struct and a variant in an enum. @@ -123,7 +123,7 @@ is the common case, and it is most of what this page is for. a record or a variant entry by entry. The `.into()` form is how you build one, and the tag comes from the expected type. - **Do not reach for a bare [`Product!`](../macros/product.md) of values** when you need the names. - A list of `Field` entries is what carries the names, and the operations that walk a shape match on + A list of `Field` entries carries the names, and the operations that walk a shape match on them. ## Common Mistakes @@ -146,8 +146,7 @@ distinguish them at run time, it does not; the tag distinguishes them only in th - [`PhantomData`](phantom_data.md) — where the tag is stored, at zero size. - [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the lists of `Field` entries that describe a record and a variant. -- [Type-level spines](spines/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains those lists are - built from. +- [`Cons`](cons.md) and [`Either`](either.md) — the product and sum lists those entries are built into. - [`HasFields`](../traits/shape/has_fields.md) — exposes a type's whole list of `Field` entries. - [`HasField`](../traits/field-access/has_field.md) — single-field access against a matching tag. - [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — assigns the list of entries to a type. diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index c2efbdc4..078caaaf 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -3,26 +3,26 @@ sidebar_label: 'Overview' sidebar_position: 0 --- -# Type-level building blocks +# Types -The small types CGP is built out of: the markers that carry information in the type system, the -recursive lists that describe a struct or an enum, and the wrappers you meet in an expansion or an -error message. +The types CGP is built out of: the type-level building blocks that carry information in the type system, +and the one ordinary runtime data type you return from a getter. ## Overview -Most CGP machinery works at the type level, where a field name, a variant, a position, or a whole -record shape is a *type* rather than a value. The types on these pages are how that is done. You write -almost none of them by hand. You meet them when you read the code a macro generated, or when a wiring -mistake prints a wall of nested types, and this section exists so that such a type is legible. +Most of the types on these pages are **type-level building blocks**. Much of CGP's machinery works at the +type level, where a field name, a variant, a position, or a whole record shape is a *type* rather than a +value. These building blocks are how that is done, and you write almost none of them by hand. You meet +them when you read the code a macro generated, or when a wiring mistake prints a wall of nested types, +and this section exists so that such a type is legible. One idea runs through nearly all of them, and it is worth holding before the rest: a type can carry -information the program never stores as a value. A struct can name a type parameter it keeps no field -of, so a name, a number, or a lifetime becomes part of a type's identity and the compiler matches on -it during trait resolution. [`PhantomData`](phantom_data.md) is the standard-library tool that makes -this legal, so it is the first page here and the mechanism the others build on. +information the program never stores as a value. A struct can name a type parameter it keeps no field of, +so a name, a number, or a lifetime becomes part of a type's identity and the compiler matches on it during +trait resolution. [`PhantomData`](phantom_data.md) is the standard-library tool that makes this legal, so +it is the first page here and the mechanism the others build on. -The rest divide into a few groups. +The building blocks divide into two groups. The **markers** each attach one piece of information at the type level. [`Index`](index_type.md) turns a tuple-field position into a type, the way [`Symbol!`](../macros/symbol.md) turns a field name into one, @@ -30,25 +30,25 @@ and [`Life`](life.md) lifts a lifetime into a type so it can travel through mach types. [`Field`](field.md) uses such a tag: it pairs a value with its type-level name, so a record or a variant entry knows what it is called. -The **[list spines](spines/index.md)** are the recursive lists everything structural is built from: -[`Cons`](spines/cons.md) and [`Nil`](spines/nil.md) for a record, [`Either`](spines/either.md) and -[`Void`](spines/void.md) for a variant, [`Chars`](spines/chars.md) for a string, and -[`PathCons`](spines/path_cons.md) for a routing path. You write these through the sugar — -[`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), [`Symbol!`](../macros/symbol.md), and -[`Path!`](../macros/path.md) — and read them in expansions and errors. +The **recursive type-level lists** are the chains everything structural is built from: a head-and-tail +cell paired with a terminator, which generic code takes apart one element at a time. Four cover four jobs, +and each family's full account lives on its head cell. [`Cons`](cons.md) and [`Nil`](nil.md) build a +record, and `Cons` owns the type-level product. [`Either`](either.md) and [`Void`](void.md) build a +variant, and `Either` owns the type-level sum. [`Chars`](chars.md) builds a string, and +[`PathCons`](path_cons.md) builds a routing path. You write these through the sugar +([`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), [`Symbol!`](../macros/symbol.md), and +[`Path!`](../macros/path.md)) and read them in expansions and errors. -One type stands apart: [`MRef`](mref.md) is an ordinary runtime value, not a type-level marker. It is -the owned-or-borrowed return type of a getter, and it is here because it is the one type in this group -you write on purpose. +One type is not a building block at all. [`MRef`](mref.md) is an ordinary runtime value, the +owned-or-borrowed return type of a getter, and it is here because it is the one type in this section you +write on purpose. ## The ideas behind them - [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — where the zero-sized provider structs that carry these markers come from. -- [Extensible records](/docs/concepts/extensible-records) — the record shape the product spine - describes. -- [Extensible variants](/docs/concepts/extensible-variants) — the variant shape the sum spine - describes. +- [Extensible records](/docs/concepts/extensible-records) — the record shape the product list describes. +- [Extensible variants](/docs/concepts/extensible-variants) — the variant shape the sum list describes. --- diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index 7217691f..04928976 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -1,6 +1,6 @@ --- sidebar_label: 'Index' -sidebar_position: 4 +sidebar_position: 3 --- # `Index` diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index d3264809..5078cd4d 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -1,6 +1,6 @@ --- sidebar_label: 'Life' -sidebar_position: 5 +sidebar_position: 4 --- # `Life` @@ -108,7 +108,7 @@ all that is asked. carries a lifetime. **`Life<'a>` is invariant in `'a`, on purpose.** It does not behave like `&'a ()`, which is covariant. -The invariance is what keeps providers wired for different lifetimes from being confused, so it is a +The invariance keeps providers wired for different lifetimes from being confused, so it is a feature rather than an over-restriction. **A higher-order provider with a lifetime loses its dependency propagation.** The inner-provider bound of @@ -124,7 +124,7 @@ a recorded limitation, noted on [`IsProviderFor`](../traits/wiring/is_provider_f - [`#[cgp_component]`](../macros/cgp_component.md) — inserts `Life` when a consumer trait carries a lifetime. - [`PhantomData`](phantom_data.md) — the marker `Life` is built from, wrapped for invariance. -- [`Index`](index_type.md) and [`Chars`](spines/chars.md) — the other lifts that make a non-type +- [`Index`](index_type.md) and [`Chars`](chars.md) — the other lifts that make a non-type addressable in trait resolution, a number and a string where `Life` lifts a lifetime. The ideas behind it: diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 3d5591cb..1562e0f0 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -1,6 +1,6 @@ --- sidebar_label: 'MRef' -sidebar_position: 6 +sidebar_position: 11 --- # `MRef` diff --git a/docs/reference/types/spines/nil.md b/docs/reference/types/nil.md similarity index 72% rename from docs/reference/types/spines/nil.md rename to docs/reference/types/nil.md index 348a6743..02065a21 100644 --- a/docs/reference/types/spines/nil.md +++ b/docs/reference/types/nil.md @@ -1,19 +1,19 @@ --- sidebar_label: 'Nil' -sidebar_position: 2 +sidebar_position: 6 --- # `Nil` -The end marker of the product, string, and path spines: an empty, constructible list. +The end marker of the product, string, and path lists: an empty, constructible list. :::info ### Generated machinery -**You are not expected to write `Nil` by hand.** It is produced by the sugar that builds the spines it -terminates: [`Product!`](../../macros/product.md), [`Symbol!`](../../macros/symbol.md), and -[`Path!`](../../macros/path.md). You meet it at the end of a chain in an expansion or an error, and this +**You are not expected to write `Nil` by hand.** It is produced by the sugar that builds the lists it +terminates: [`Product!`](../macros/product.md), [`Symbol!`](../macros/symbol.md), and +[`Path!`](../macros/path.md). You meet it at the end of a chain in an expansion or an error, and this page explains what it marks. ::: @@ -24,9 +24,9 @@ page explains what it marks. the rest of the list, `Nil` is the rest when there is nothing left, so a list of any length is a `Cons` chain that finishes in `Nil`. On its own, `Nil` is the empty list. -The same marker terminates three of CGP's four spines. It ends the product spine built from -[`Cons`](cons.md), the string spine built from [`Chars`](chars.md), and the path spine built from -[`PathCons`](path_cons.md). Only the sum spine ends differently, in the uninhabited [`Void`](void.md), +The same marker terminates three of CGP's four lists. It ends the product list built from +[`Cons`](cons.md), the string list built from [`Chars`](chars.md), and the path list built from +[`PathCons`](path_cons.md). Only the sum list ends differently, in the uninhabited [`Void`](void.md), and that difference is the point of both markers: a record, a string, and a path can each be empty and still exist, so their terminator is a real value. @@ -45,20 +45,20 @@ traits structurally and `Nil` itself compares equal to `Nil`. ## Behavior -`Nil` is the base case of every recursion over a spine it terminates. An operation that folds over a +`Nil` is the base case of every recursion over a list it terminates. An operation that folds over a product implements the step for [`Cons`](cons.md) and the base case for `Nil`, and the -recursion bottoms out when it reaches `Nil`. The string and path spines do the same: a walk over +recursion bottoms out when it reaches `Nil`. The string and path lists do the same: a walk over [`Chars`](chars.md) stops at `Nil`, and a walk over [`PathCons`](path_cons.md) stops at `Nil`. Because `Nil` is a real, constructible value, the empty product `Product![]` is `Nil` and the empty value -`product![]` is `Nil` as a value. This is what a builder or a conversion returns when a shape has no +`product![]` is `Nil` as a value. A builder or a conversion returns this when a shape has no fields left, and it is why an empty record is a value the program can hold. The contrast with [`Void`](void.md) is exact: a value with every field ruled out cannot exist, so a sum ends in an uninhabited marker, while a record ends in this inhabited one. ## Examples -`Nil` closes off every product chain, visible when the [`Product!`](../../macros/product.md) sugar is +`Nil` closes off every product chain, visible when the [`Product!`](../macros/product.md) sugar is expanded: ```rust @@ -71,8 +71,8 @@ type Row = Cons>; type Empty = Product![]; // == Nil ``` -It also terminates a [`Symbol!`](../../macros/symbol.md) character chain and a -[`Path!`](../../macros/path.md) segment chain: +It also terminates a [`Symbol!`](../macros/symbol.md) character chain and a +[`Path!`](../macros/path.md) segment chain: ```rust // Symbol!("hi") ends its Chars chain in Nil @@ -87,7 +87,7 @@ is all that is asked. - **Read `Nil` as "the list ends here."** In an expanded `Cons`, `Chars`, or `PathCons` chain, the `Nil` is the terminator and marks the count of cells before it. - **Expect `Nil`, not [`Void`](void.md), at the end of a record, a string, or a path.** A sum ends in - `Void`; the other three spines end in `Nil`. Meeting the wrong terminator in an error usually means the + `Void`; the other three lists end in `Nil`. Meeting the wrong terminator in an error usually means the product and sum families have been crossed. ## Common Mistakes @@ -96,16 +96,16 @@ is all that is asked. is an uninhabited type an empty choice would be. They are not interchangeable, and the whole extractor machinery depends on the difference. -**`Nil` terminates three spines, not just the product one.** A `Nil` at the end of a +**`Nil` terminates three lists, not just the product one.** A `Nil` at the end of a [`Chars`](chars.md) chain or a [`PathCons`](path_cons.md) chain is the same marker doing the same job, so seeing it outside a record is expected. ## Related constructs - [`Cons`](cons.md) — the head-and-tail cell this marker terminates in a record. -- [`Void`](void.md) — the sum spine's uninhabited end marker, the counterpart to this one. -- [`Chars`](chars.md) and [`PathCons`](path_cons.md) — the string and path spines `Nil` also terminates. -- [`Product!`](../../macros/product.md) — the macro whose empty form is `Nil`. +- [`Void`](void.md) — the sum list's uninhabited end marker, the counterpart to this one. +- [`Chars`](chars.md) and [`PathCons`](path_cons.md) — the string and path lists `Nil` also terminates. +- [`Product!`](../macros/product.md) — the macro whose empty form is `Nil`. The ideas behind it: @@ -116,7 +116,7 @@ The ideas behind it: - The type: [`nil.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/nil.rs) -- The spines it terminates: +- The lists it terminates: [`cons.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/cons.rs), [`chars.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/chars.rs), and diff --git a/docs/reference/types/spines/path_cons.md b/docs/reference/types/path_cons.md similarity index 73% rename from docs/reference/types/spines/path_cons.md rename to docs/reference/types/path_cons.md index c6fbf170..02ecd1e3 100644 --- a/docs/reference/types/spines/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -1,19 +1,19 @@ --- sidebar_label: 'PathCons' -sidebar_position: 6 +sidebar_position: 10 --- # `PathCons` -One segment of a type-level path: the spine that names a route through nested delegation tables, so a +One segment of a type-level path: the list that names a route through nested delegation tables, so a lookup can reach an entry several layers deep. :::info ### Generated machinery -**You are not expected to write `PathCons` by hand.** The [`Path!`](../../macros/path.md) macro builds it, -and [`cgp_namespace!`](../../macros/cgp_namespace.md) emits it when it reroutes a component. You meet it +**You are not expected to write `PathCons` by hand.** The [`Path!`](../macros/path.md) macro builds it, +and [`cgp_namespace!`](../macros/cgp_namespace.md) emits it when it reroutes a component. You meet it in an expansion of namespace wiring and in a routing error, and this page explains its shape. ::: @@ -28,7 +28,7 @@ inherits from, under a prefix. A path names such a route, as a list of segments one narrowing the lookup a step further. `PathCons` is the cell of that list, and [`Nil`](nil.md) terminates it, so `PathCons>` is the two-step path "first `A`, then `B`". -A path is a distinct spine from the [`Cons`](cons.md) product list, even though both are right-nested and +A path differs from the [`Cons`](cons.md) product list, even though both are right-nested and `Nil`-terminated, and the difference is the unsized bound. `PathCons` declares its head and tail `?Sized`, so a segment may be a trait object or another unsized type and the whole path can be manipulated without its parts having a known size. A product list keys a struct's fields and its @@ -39,7 +39,7 @@ The segments are the markers CGP uses elsewhere: a lowercase dotted name becomes [`Symbol`](chars.md) type-level string, and a capitalized name becomes that named type, usually a component key such as `FooProviderComponent` or a namespace marker. A path is therefore an interleaving of symbols and component names, the form `@a.B.c`, assembled into a `PathCons` chain. You write paths -through the [`Path!`](../../macros/path.md) macro, so this page is the runtime spine and that macro's page +through the [`Path!`](../macros/path.md) macro, so this page is the runtime list and that macro's page carries the `@`-segment syntax. ## Definition @@ -54,18 +54,18 @@ pub struct PathCons(pub PhantomData, pub Phant `Head` is the first segment and `Tail` is the remainder, expected to be either another `PathCons` or [`Nil`](nil.md) at the end. Both bounds are `?Sized`, so any type may occupy a segment. The struct carries no runtime data: like the other type-level building blocks it exists through -[`PhantomData`](../phantom_data.md) so a route can be named and matched in trait resolution. +[`PhantomData`](phantom_data.md) so a route can be named and matched in trait resolution. ## Behavior `PathCons` supports path concatenation through the -[`ConcatPath`](../../traits/formatting/concat_path.md) trait, which appends one path onto the end of -another at the type level. The trait recurses down the spine: `PathCons` concatenates with +[`ConcatPath`](../traits/formatting/concat_path.md) trait, which appends one path onto the end of +another at the type level. The trait recurses down the list: `PathCons` concatenates with `Other` by keeping `Head` and concatenating `Tail` with `Other`, while [`Nil`](nil.md) concatenates with `Other` by becoming `Other`. The result is ordinary list append, computed as an associated-type projection. -Beyond concatenation, a path is consumed by [`RedirectLookup`](../../providers/redirect_lookup.md), the +Beyond concatenation, a path is consumed by [`RedirectLookup`](../providers/redirect_lookup.md), the provider that resolves a delegation by walking a context's table along a path. When a namespace or a prefixed component reroutes a lookup, it produces a `RedirectLookup` whose `Path` is a `PathCons` chain, and `RedirectLookup` follows the chain segment by segment until it lands on a concrete @@ -74,8 +74,8 @@ resolve to different providers depending on the table it is walked against. ## Examples -Paths are produced by the [`Path!`](../../macros/path.md) macro and most often appear inside the wirings -that [`cgp_namespace!`](../../macros/cgp_namespace.md) emits. A namespace entry that redirects one +Paths are produced by the [`Path!`](../macros/path.md) macro and most often appear inside the wirings +that [`cgp_namespace!`](../macros/cgp_namespace.md) emits. A namespace entry that redirects one component key to a path desugars into a `RedirectLookup` over a `PathCons` chain: ```rust @@ -107,40 +107,40 @@ resolving. A single-segment path is `PathCons`, and the empty path ## When to use it -**You read `PathCons` in an expansion; you write [`Path!`](../../macros/path.md), or wire a namespace.** +**You read `PathCons` in an expansion; you write [`Path!`](../macros/path.md), or wire a namespace.** - **Decode a `PathCons` chain by reading the segments left to right.** Each is one step of the route, a [`Symbol`](chars.md) for a lowercase name or a component or namespace type for a capitalized one. -- **Use [`Path!`](../../macros/path.md) to write a path** when you need one directly, in its `@a.B.c` +- **Use [`Path!`](../macros/path.md) to write a path** when you need one directly, in its `@a.B.c` form. - **Use a namespace rather than a raw path** for the common case: joining a - [`cgp_namespace!`](../../macros/cgp_namespace.md) or the `open` statement of - [`delegate_components!`](../../macros/delegate_components.md) produces the paths for you. + [`cgp_namespace!`](../macros/cgp_namespace.md) or the `open` statement of + [`delegate_components!`](../macros/delegate_components.md) produces the paths for you. ## Common Mistakes **A path names a route, not a provider.** A `PathCons` chain describes where to look; which provider it -resolves to depends on the table [`RedirectLookup`](../../providers/redirect_lookup.md) walks it against. +resolves to depends on the table [`RedirectLookup`](../providers/redirect_lookup.md) walks it against. The same path can land on different providers in different contexts. -**A path spine is `?Sized`, unlike the [`Cons`](cons.md) product spine.** Its segments are markers rather +**A path list is `?Sized`, unlike the [`Cons`](cons.md) product list.** Its segments are markers rather than values, so a segment need not have a known size. Expecting a path to behave like a product list of values is the usual source of confusion. **Both a path and a product end in [`Nil`](nil.md).** Seeing `Nil` at the end of a `PathCons` chain is -the same terminator doing the same job it does for a record, not a sign the two spines have been mixed. +the same terminator doing the same job it does for a record, not a sign the two lists have been mixed. ## Related constructs - [`Nil`](nil.md) — the end marker that terminates a `PathCons` chain. -- [`Cons`](cons.md) — the product spine this one parallels, whose elements are sized values rather than +- [`Cons`](cons.md) — the product list this one parallels, whose elements are sized values rather than `?Sized` markers. - [`Chars`](chars.md) — the [`Symbol`](chars.md) segments a path is built from. -- [`Path!`](../../macros/path.md) — the macro that folds `@`-segments onto this spine. -- [`ConcatPath`](../../traits/formatting/concat_path.md) — appends one path onto another. -- [`RedirectLookup`](../../providers/redirect_lookup.md) — walks a path against a table at resolution +- [`Path!`](../macros/path.md) — the macro that folds `@`-segments onto this list. +- [`ConcatPath`](../traits/formatting/concat_path.md) — appends one path onto another. +- [`RedirectLookup`](../providers/redirect_lookup.md) — walks a path against a table at resolution time. -- [`cgp_namespace!`](../../macros/cgp_namespace.md) — emits these paths to reroute and register entries. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — emits these paths to reroute and register entries. The ideas behind it: @@ -155,7 +155,7 @@ The ideas behind it: [`nil.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/nil.rs) - The `ConcatPath` trait and impls: [`concat_path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/concat_path.rs) -- The constructing macro is [`Path!`](../../macros/path.md); `RedirectLookup`, which consumes a path, is +- The constructing macro is [`Path!`](../macros/path.md); `RedirectLookup`, which consumes a path, is in [`redirect_lookup.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/redirect_lookup.rs) diff --git a/docs/reference/types/phantom_data.md b/docs/reference/types/phantom_data.md index aad93a66..56658940 100644 --- a/docs/reference/types/phantom_data.md +++ b/docs/reference/types/phantom_data.md @@ -79,9 +79,9 @@ as genuinely different. That page explains why. The two uses are the declaring side and the passing side, and they look different in the code. **On the declaring side, `PhantomData` fills the field of a zero-sized type**, the way `Multiply` -above carries it. The same pattern runs through CGP's [list spines](spines/index.md): a -[`Chars`](spines/chars.md) node holds its next node in a `PhantomData`, a -[`PathCons`](spines/path_cons.md) holds both its head and tail that way, and a [`Field`](field.md) holds +above carries it. The same pattern runs through CGP's recursive type-level lists: a +[`Chars`](chars.md) node holds its next node in a `PhantomData`, a +[`PathCons`](path_cons.md) holds both its head and tail that way, and a [`Field`](field.md) holds its type-level name tag in a `PhantomData` beside the one real value it stores. In each case the parameter is part of the type's identity and nothing the type keeps at run time. @@ -179,7 +179,8 @@ fails to compile with `error[E0392]` without one. - [`Field`](field.md) — holds its type-level name tag in a `PhantomData` beside its value. - [`Life`](life.md) — a lifetime lifted into a type through a deliberately invariant `PhantomData`. -- [Type-level spines](spines/index.md) — the recursive lists whose tails are `PhantomData` markers. +- [`Chars`](chars.md) and [`PathCons`](path_cons.md) — recursive type-level lists whose tails are + `PhantomData` markers. - [`Symbol!`](../macros/symbol.md) and [`Index`](index_type.md) — the tags a `PhantomData::` argument usually carries. - [`HasField`](../traits/field-access/has_field.md) — whose `get_field` takes the tag as a diff --git a/docs/reference/types/spines/_category_.json b/docs/reference/types/spines/_category_.json deleted file mode 100644 index 832c1382..00000000 --- a/docs/reference/types/spines/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Type-level list spines", - "position": 3, - "link": { - "type": "doc", - "id": "reference/types/spines/index" - } -} diff --git a/docs/reference/types/spines/index.md b/docs/reference/types/spines/index.md deleted file mode 100644 index 65867cb0..00000000 --- a/docs/reference/types/spines/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -sidebar_label: 'Overview' -sidebar_position: 0 ---- - -# Type-level list spines - -The recursive lists CGP folds over: one for a record, one for a variant, one for a string, and one for -a routing path. You write them through sugar and read them in expansions and errors. - -## Overview - -A **spine** is a list encoded as a type. Instead of holding several things in one flat type the way a -tuple does, a spine pairs a head with the rest of the list and terminates in an end marker, so generic -code can take the list apart one element at a time. That is what a tuple cannot do and a spine can, and -it is the mechanism behind every field-by-field and variant-by-variant operation in CGP. - -All the spines share one shape: right-nested, terminated by an end marker, and consumed by recursing on -two cases. A trait implemented for the end marker gives the base case, and a blanket impl for the -head-and-tail cell gives the recursive step, usually constraining the tail to implement the same trait -so the recursion stops at the end. This one pattern processes a list of any length with no per-element -code. - -Four spines cover four jobs, and they differ in what sits in the head and what marks the end. - -The **product spine** describes a record. [`Cons`](cons.md) pairs a field with the rest, and -[`Nil`](nil.md) marks the end. A record is a `Cons` chain ending in `Nil`, and it is what -[`Product!`](../../macros/product.md) builds. - -The **sum spine** describes a variant. [`Either`](either.md) selects the head or defers to the rest, and -[`Void`](void.md) marks the end. A variant is an `Either` chain ending in the uninhabited `Void`, and it -is what [`Sum!`](../../macros/sum.md) builds. The end marker is where the two data spines differ: a -record ends in the constructible `Nil`, a variant in the impossible `Void`. - -The **string spine** describes a field name. [`Chars`](chars.md) holds one character and the rest of the -string, again ending in `Nil`, and it is what a [`Symbol!`](../../macros/symbol.md) wraps. It is the -product spine specialized so the head is a `const char` rather than a type. - -The **path spine** describes a route through delegation tables. [`PathCons`](path_cons.md) holds one -segment and the rest of the path, ending in `Nil`, and it is what [`Path!`](../../macros/path.md) builds. -It differs from the product spine in one way: its segments may be unsized, because they are pure markers -rather than values. - -You write none of these by hand. The sugar builds them, and the reason to know them is that a mismatched -shape or a routing failure prints the expanded spine, and counting the cells is how you read it. - -## The pages - -- [`Cons`](cons.md) — the head-and-tail cell of a record. -- [`Nil`](nil.md) — the end marker shared by the product, string, and path spines. -- [`Either`](either.md) — the head-or-rest cell of a variant. -- [`Void`](void.md) — the uninhabited end marker of a variant. -- [`Chars`](chars.md) — one character of a type-level string. -- [`PathCons`](path_cons.md) — one segment of a type-level path. - -## The ideas behind them - -- [Extensible records](/docs/concepts/extensible-records) — the record shape the product spine - describes. -- [Extensible variants](/docs/concepts/extensible-variants) — the variant shape the sum spine describes. -- [Namespaces](/docs/concepts/namespaces) — where a path spine routes a component lookup. - ---- - -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/spines/void.md b/docs/reference/types/void.md similarity index 81% rename from docs/reference/types/spines/void.md rename to docs/reference/types/void.md index 7bd9badb..57a4554e 100644 --- a/docs/reference/types/spines/void.md +++ b/docs/reference/types/void.md @@ -1,18 +1,18 @@ --- sidebar_label: 'Void' -sidebar_position: 4 +sidebar_position: 8 --- # `Void` -The uninhabited end marker of the sum spine: an empty enum that can never be constructed, which is what +The uninhabited end marker of the sum list: an empty enum that can never be constructed, which is what lets a total variant match close with no runtime branch. :::info ### Generated machinery -**You are not expected to write `Void` by hand.** It is produced by [`Sum!`](../../macros/sum.md) as the +**You are not expected to write `Void` by hand.** It is produced by [`Sum!`](../macros/sum.md) as the terminator of a sum, and it appears in the extractor machinery. You meet it at the end of an [`Either`](either.md) chain and in an extraction error, and this page explains why it is uninhabited. @@ -20,12 +20,12 @@ terminator of a sum, and it appears in the extractor machinery. You meet it at t ## Overview -`Void` marks the end of a sum, and unlike the [`Nil`](nil.md) that ends the other spines, it is +`Void` marks the end of a sum, and unlike the [`Nil`](nil.md) that ends the other lists, it is uninhabited: it has no values. Where a record, a string, or a path can each be empty and still exist, an empty *choice* cannot. There is no value that is "none of the branches", so the natural terminator -for the sum spine is a type with no values at all. +for the sum list is a type with no values at all. -That uninhabitedness is not a technicality; it makes the sum spine work. An [`Either`](either.md) +That uninhabitedness is not a technicality; it makes the sum list work. An [`Either`](either.md) chain ends in `Void`, so a value that walked past every real branch would have type `Void`, which is impossible to reach. The chain is therefore closed at its end by construction, and a match that has handled every real variant has nothing left to handle. @@ -45,14 +45,14 @@ built, so those impls are never run on one. ## Behavior -`Void` is the base case of a recursion over a sum, and it behaves differently from the product spine's +`Void` is the base case of a recursion over a sum, and it behaves differently from the product list's base case in exactly one way that matters. A walk over an [`Either`](either.md) chain handles each `Left` as a branch and defers each `Right` to the tail, until the tail is `Void`, at which point there is nothing left to handle. The uninhabitedness is essential to the extractor machinery. After an extractor has tried every variant of a sum and matched none, the leftover value has type `Void`, a value that cannot exist. -[`FinalizeExtract`](../../traits/variant/finalize_extract.md) for `Void` turns that into any required +[`FinalizeExtract`](../traits/variant/finalize_extract.md) for `Void` turns that into any required type with an empty `match self {}`, since there are no cases to handle, so a fully-handled variant extraction is total at compile time with no unreachable runtime branch: @@ -67,11 +67,11 @@ impl FinalizeExtract for Void { A constructible terminator like [`Nil`](nil.md) could not be discharged this way, because the compiler would demand a value for the `Nil` case. Only an uninhabited type lets the empty match stand, which is -why the sum spine terminates in `Void` and the product spine in `Nil`. +why the sum list terminates in `Void` and the product list in `Nil`. ## Examples -`Void` closes off every sum chain, visible when the [`Sum!`](../../macros/sum.md) sugar is expanded: +`Void` closes off every sum chain, visible when the [`Sum!`](../macros/sum.md) sugar is expanded: ```rust use cgp::prelude::*; @@ -95,7 +95,7 @@ on it with no arms, which the extractor family does when a variant match is comp - **Expect `Void`, not [`Nil`](nil.md), at the end of a variant.** A record, a string, and a path end in `Nil`; a variant ends in `Void`. Meeting the wrong terminator in an error usually means the product and sum families have been crossed. -- **Recognize `Void` in a [`FinalizeExtract`](../../traits/variant/finalize_extract.md) error** as the +- **Recognize `Void` in a [`FinalizeExtract`](../traits/variant/finalize_extract.md) error** as the all-ruled-out remainder of a variant extraction. ## Common Mistakes @@ -110,12 +110,12 @@ appears to "return a `Void`" is really an empty match that never returns at all. ## Related constructs - [`Either`](either.md) — the head-or-rest cell this marker terminates. -- [`Nil`](nil.md) — the product, string, and path spines' constructible end marker, the counterpart to +- [`Nil`](nil.md) — the product, string, and path lists' constructible end marker, the counterpart to this one. -- [`Sum!`](../../macros/sum.md) — the macro whose empty form is `Void`. -- [`FinalizeExtract`](../../traits/variant/finalize_extract.md) — discharges the uninhabited remainder of +- [`Sum!`](../macros/sum.md) — the macro whose empty form is `Void`. +- [`FinalizeExtract`](../traits/variant/finalize_extract.md) — discharges the uninhabited remainder of a variant extraction with an empty match. -- [`FinalizeExtractResult`](../../traits/variant/finalize_extract_result.md) — the result-carrying form +- [`FinalizeExtractResult`](../traits/variant/finalize_extract_result.md) — the result-carrying form built on the same idea. The ideas behind it: From b72ce5e2dd3bb8f979049a22eede51f70540e500 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 31 Aug 2026 23:16:20 +0200 Subject: [PATCH 053/516] example-code: flatten types test mirror to match the docs Follow-up to flattening docs/reference/types: move the six list test files up out of spines/ into tests/reference/types/, drop spines/mod.rs, and rewrite types/mod.rs, so the mirror path matches each page again. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XnyQ9YwnJDberZ9vNnUWcY --- example-code/tests/reference/traits/map_fields.rs | 2 +- example-code/tests/reference/types/{spines => }/chars.rs | 2 +- example-code/tests/reference/types/{spines => }/cons.rs | 2 +- example-code/tests/reference/types/{spines => }/either.rs | 2 +- example-code/tests/reference/types/mod.rs | 7 ++++++- example-code/tests/reference/types/{spines => }/nil.rs | 4 ++-- .../tests/reference/types/{spines => }/path_cons.rs | 2 +- example-code/tests/reference/types/spines/mod.rs | 8 -------- example-code/tests/reference/types/{spines => }/void.rs | 2 +- 9 files changed, 14 insertions(+), 17 deletions(-) rename example-code/tests/reference/types/{spines => }/chars.rs (95%) rename example-code/tests/reference/types/{spines => }/cons.rs (95%) rename example-code/tests/reference/types/{spines => }/either.rs (95%) rename example-code/tests/reference/types/{spines => }/nil.rs (75%) rename example-code/tests/reference/types/{spines => }/path_cons.rs (94%) delete mode 100644 example-code/tests/reference/types/spines/mod.rs rename example-code/tests/reference/types/{spines => }/void.rs (89%) diff --git a/example-code/tests/reference/traits/map_fields.rs b/example-code/tests/reference/traits/map_fields.rs index 2cddd1c1..7cebe2ea 100644 --- a/example-code/tests/reference/traits/map_fields.rs +++ b/example-code/tests/reference/traits/map_fields.rs @@ -1,7 +1,7 @@ //! Code from `docs/reference/traits/map_fields.md` — *`MapFields`*. //! //! A pure type-level function, so the check is a type equality. What this pins beyond the page's two -//! snippets is that the same marker applies over *both* spines — a product and a sum — and the two +//! snippets is that the same marker applies over *both* lists — a product and a sum — and the two //! import paths, since neither the trait nor the `IsOptional` marker is in the prelude. /// ## Examples diff --git a/example-code/tests/reference/types/spines/chars.rs b/example-code/tests/reference/types/chars.rs similarity index 95% rename from example-code/tests/reference/types/spines/chars.rs rename to example-code/tests/reference/types/chars.rs index 9f1b79ba..e86f226a 100644 --- a/example-code/tests/reference/types/spines/chars.rs +++ b/example-code/tests/reference/types/chars.rs @@ -1,4 +1,4 @@ -//! Code from `docs/reference/types/spines/chars.md` — *`Chars`*. +//! Code from `docs/reference/types/chars.md` — *`Chars`*. //! //! A `Symbol!` wraps a `Chars` chain. The page reads a field by its `Symbol!` tag and rebuilds the //! string from the type; both run here. The greet provider duplicates the one on the `PhantomData` diff --git a/example-code/tests/reference/types/spines/cons.rs b/example-code/tests/reference/types/cons.rs similarity index 95% rename from example-code/tests/reference/types/spines/cons.rs rename to example-code/tests/reference/types/cons.rs index ac8b1032..8eb443b5 100644 --- a/example-code/tests/reference/types/spines/cons.rs +++ b/example-code/tests/reference/types/cons.rs @@ -1,4 +1,4 @@ -//! Code from `docs/reference/types/spines/cons.md` — *`Cons`*. +//! Code from `docs/reference/types/cons.md` — *`Cons`*. //! //! `Cons`/`Nil` are what `Product!` expands to. This pins the `Cons` chain a derive assigns and the one //! a `Product!` alias produces, by naming the chain explicitly and by building a `product!` value by diff --git a/example-code/tests/reference/types/spines/either.rs b/example-code/tests/reference/types/either.rs similarity index 95% rename from example-code/tests/reference/types/spines/either.rs rename to example-code/tests/reference/types/either.rs index 93ab8514..42f2428d 100644 --- a/example-code/tests/reference/types/spines/either.rs +++ b/example-code/tests/reference/types/either.rs @@ -1,4 +1,4 @@ -//! Code from `docs/reference/types/spines/either.md` — *`Either`*. +//! Code from `docs/reference/types/either.md` — *`Either`*. //! //! `Either`/`Void` are what `Sum!` expands to. This pins the `Either` chain a derive assigns to an enum //! and the branch a nested `Either` value selects. diff --git a/example-code/tests/reference/types/mod.rs b/example-code/tests/reference/types/mod.rs index 2b712098..61a7a183 100644 --- a/example-code/tests/reference/types/mod.rs +++ b/example-code/tests/reference/types/mod.rs @@ -4,9 +4,14 @@ //! module only where it shows code a compiler can check: a shape a derive assigns, a value built from a //! marker, a call site that passes a tag. The two overview pages, which show no code, get none. +pub mod chars; +pub mod cons; +pub mod either; pub mod field; pub mod index_type; pub mod life; pub mod mref; +pub mod nil; +pub mod path_cons; pub mod phantom_data; -pub mod spines; +pub mod void; diff --git a/example-code/tests/reference/types/spines/nil.rs b/example-code/tests/reference/types/nil.rs similarity index 75% rename from example-code/tests/reference/types/spines/nil.rs rename to example-code/tests/reference/types/nil.rs index fcb4a5e9..ee94dddb 100644 --- a/example-code/tests/reference/types/spines/nil.rs +++ b/example-code/tests/reference/types/nil.rs @@ -1,6 +1,6 @@ -//! Code from `docs/reference/types/spines/nil.md` — *`Nil`*. +//! Code from `docs/reference/types/nil.md` — *`Nil`*. //! -//! `Nil` terminates the product, string, and path spines and is the empty product. This pins that the +//! `Nil` terminates the product, string, and path lists and is the empty product. This pins that the //! empty `Product!` is `Nil`, at the type level and the value level. /// ## Examples diff --git a/example-code/tests/reference/types/spines/path_cons.rs b/example-code/tests/reference/types/path_cons.rs similarity index 94% rename from example-code/tests/reference/types/spines/path_cons.rs rename to example-code/tests/reference/types/path_cons.rs index 55f4ad6d..5b04fd8f 100644 --- a/example-code/tests/reference/types/spines/path_cons.rs +++ b/example-code/tests/reference/types/path_cons.rs @@ -1,4 +1,4 @@ -//! Code from `docs/reference/types/spines/path_cons.md` — *`PathCons`*. +//! Code from `docs/reference/types/path_cons.md` — *`PathCons`*. //! //! `PathCons` is built by `Path!` and emitted by `cgp_namespace!`. Paths are unsized markers, so there //! is no value to build: naming the `PathCons` chain a `Path!` produces and coercing it is the check, diff --git a/example-code/tests/reference/types/spines/mod.rs b/example-code/tests/reference/types/spines/mod.rs deleted file mode 100644 index 0a951ea1..00000000 --- a/example-code/tests/reference/types/spines/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! Code from the pages under `docs/reference/types/spines/`. - -pub mod chars; -pub mod cons; -pub mod either; -pub mod nil; -pub mod path_cons; -pub mod void; diff --git a/example-code/tests/reference/types/spines/void.rs b/example-code/tests/reference/types/void.rs similarity index 89% rename from example-code/tests/reference/types/spines/void.rs rename to example-code/tests/reference/types/void.rs index d0139ecd..7e2e0d9d 100644 --- a/example-code/tests/reference/types/spines/void.rs +++ b/example-code/tests/reference/types/void.rs @@ -1,4 +1,4 @@ -//! Code from `docs/reference/types/spines/void.md` — *`Void`*. +//! Code from `docs/reference/types/void.md` — *`Void`*. //! //! `Void` is uninhabited, so there is no value to build. Naming the empty `Sum!` as `Void` and coercing //! it is the check. From 6a66bec9c470abd595028ccfb9ce6fd6aca2139b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 31 Aug 2026 23:25:12 +0200 Subject: [PATCH 054/516] reference/types: remove the Generated machinery notices Every page in the types section is a type-level building block a reader recognizes rather than writes, and the section overview already frames them that way, so a per-page Generated machinery notice only repeated it. Remove the notice from all eight pages that carried one (chars, cons, either, field, life, nil, path_cons, void), and drop a cleft in void's summary while there. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01XnyQ9YwnJDberZ9vNnUWcY --- docs/reference/types/chars.md | 11 ----------- docs/reference/types/cons.md | 11 ----------- docs/reference/types/either.md | 11 ----------- docs/reference/types/field.md | 12 ------------ docs/reference/types/life.md | 10 ---------- docs/reference/types/nil.md | 11 ----------- docs/reference/types/path_cons.md | 10 ---------- docs/reference/types/void.md | 14 ++------------ 8 files changed, 2 insertions(+), 88 deletions(-) diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index 8b8be863..ba5f7166 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -8,17 +8,6 @@ sidebar_position: 9 One character of a type-level string: the list that spells a field name out one character at a time so the name can be a type. -:::info - -### Generated machinery - -**You are not expected to write `Chars` by hand.** The [`Symbol!`](../macros/symbol.md) macro folds a -string literal into a `Chars` chain, and a `Symbol` wraps that chain. You meet `Chars` in a -missing-field error, where a field name prints as its expanded character list, and this page explains how -to read it. - -::: - ## Overview `Chars` encodes a string as a type, so that a field name can take part in trait diff --git a/docs/reference/types/cons.md b/docs/reference/types/cons.md index e55193b4..930c667e 100644 --- a/docs/reference/types/cons.md +++ b/docs/reference/types/cons.md @@ -8,17 +8,6 @@ sidebar_position: 5 The head-and-tail cell of the product list: the recursive list that describes a record, one field at a time. -:::info - -### Generated machinery - -**You are not expected to write `Cons` by hand.** You build a product list with the -[`Product!`](../macros/product.md) and `product!` macros, and a struct's field list comes from -[`#[derive(HasFields)]`](../derives/derive_has_fields.md). You meet `Cons` in an expansion and in a -field-mismatch error, and this page explains its shape so those read clearly. - -::: - ## Overview `Cons` represents an ordered sequence of types as a single type, so a collection of fields diff --git a/docs/reference/types/either.md b/docs/reference/types/either.md index 9ed46014..cc027613 100644 --- a/docs/reference/types/either.md +++ b/docs/reference/types/either.md @@ -8,17 +8,6 @@ sidebar_position: 7 The head-or-rest cell of the sum list: the recursive list that describes an enum, one variant at a time. -:::info - -### Generated machinery - -**You are not expected to write `Either` by hand.** You build a sum list with the -[`Sum!`](../macros/sum.md) macro, and an enum's variant list comes from -[`#[derive(HasFields)]`](../derives/derive_has_fields.md). You meet `Either` in an expansion and in a -variant-mismatch error, and this page explains its shape so those read clearly. - -::: - ## Overview `Either` represents a choice among several types as a single type, so an enum's variants can diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index fb030b48..96d6114a 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -8,18 +8,6 @@ sidebar_position: 2 A value paired with its type-level name tag, so a struct's fields and an enum's variants can be described one entry at a time without naming the concrete type. -:::info - -### Generated machinery - -**You rarely write `Field` by hand.** The extensible-data derives — -[`#[derive(HasFields)]`](../derives/derive_has_fields.md) and the wider -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) — build the `Field` entries that make up a type's -shape. You meet the type in a generated shape, in a builder or extractor error, and occasionally when -you construct one entry directly. This page explains what it is so those are legible. - -::: - ## Overview `Field` carries a field's *name* and its *value* together in one type. A bare diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index 5078cd4d..9e3861a1 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -8,16 +8,6 @@ sidebar_position: 4 A lifetime lifted into a type, so a lifetime parameter can travel through machinery that only accepts types. -:::info - -### Generated machinery - -**You are not expected to write `Life` by hand.** The component-defining macros, principally -[`#[cgp_component]`](../macros/cgp_component.md), insert it when a trait carries a lifetime. You meet it -in a generated provider trait and in a provider-resolution error, and this page explains why it is there. - -::: - ## Overview `Life<'a>` exists because CGP's wiring is parameterized by *types*, not lifetimes, yet a CGP trait may diff --git a/docs/reference/types/nil.md b/docs/reference/types/nil.md index 02065a21..7c1b045e 100644 --- a/docs/reference/types/nil.md +++ b/docs/reference/types/nil.md @@ -7,17 +7,6 @@ sidebar_position: 6 The end marker of the product, string, and path lists: an empty, constructible list. -:::info - -### Generated machinery - -**You are not expected to write `Nil` by hand.** It is produced by the sugar that builds the lists it -terminates: [`Product!`](../macros/product.md), [`Symbol!`](../macros/symbol.md), and -[`Path!`](../macros/path.md). You meet it at the end of a chain in an expansion or an error, and this -page explains what it marks. - -::: - ## Overview `Nil` marks the end of a right-nested type-level list. Where a [`Cons`](cons.md) cell pairs a head with diff --git a/docs/reference/types/path_cons.md b/docs/reference/types/path_cons.md index 02ecd1e3..7b4e5e16 100644 --- a/docs/reference/types/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -8,16 +8,6 @@ sidebar_position: 10 One segment of a type-level path: the list that names a route through nested delegation tables, so a lookup can reach an entry several layers deep. -:::info - -### Generated machinery - -**You are not expected to write `PathCons` by hand.** The [`Path!`](../macros/path.md) macro builds it, -and [`cgp_namespace!`](../macros/cgp_namespace.md) emits it when it reroutes a component. You meet it -in an expansion of namespace wiring and in a routing error, and this page explains its shape. - -::: - ## Overview `PathCons` expresses a *route* through nested delegation tables as a single type. A bare diff --git a/docs/reference/types/void.md b/docs/reference/types/void.md index 57a4554e..2ea6d40f 100644 --- a/docs/reference/types/void.md +++ b/docs/reference/types/void.md @@ -5,18 +5,8 @@ sidebar_position: 8 # `Void` -The uninhabited end marker of the sum list: an empty enum that can never be constructed, which is what -lets a total variant match close with no runtime branch. - -:::info - -### Generated machinery - -**You are not expected to write `Void` by hand.** It is produced by [`Sum!`](../macros/sum.md) as the -terminator of a sum, and it appears in the extractor machinery. You meet it at the end of an -[`Either`](either.md) chain and in an extraction error, and this page explains why it is uninhabited. - -::: +The uninhabited end marker of the sum list: an empty enum that can never be constructed, which lets a +total variant match close with no runtime branch. ## Overview From d173b80735e1455d13c3590c4da0eca471090393 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 10:50:37 +0200 Subject: [PATCH 055/516] reference/types: revise prose for point-first style MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove em dashes (convert glossary "link — gloss" bullets to colons), drop pseudo-clefts and copular openers, replace stated counts and ordinal back-references, and trim verbose or dangling phrasing across all twelve type pages. Footer disclaimer lines left unchanged to stay consistent with the rest of the site. Co-Authored-By: Claude Opus 4.8 --- docs/reference/types/chars.md | 18 ++++++------ docs/reference/types/cons.md | 16 +++++----- docs/reference/types/either.md | 14 ++++----- docs/reference/types/field.md | 20 ++++++------- docs/reference/types/index.md | 44 ++++++++++++++-------------- docs/reference/types/index_type.md | 28 +++++++++--------- docs/reference/types/life.md | 22 +++++++------- docs/reference/types/mref.md | 16 +++++----- docs/reference/types/nil.md | 12 ++++---- docs/reference/types/path_cons.md | 16 +++++----- docs/reference/types/phantom_data.md | 24 +++++++-------- docs/reference/types/void.md | 14 ++++----- 12 files changed, 122 insertions(+), 122 deletions(-) diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index ba5f7166..a805d839 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -16,7 +16,7 @@ for the string `"name"` at the type level, so the compiler can match one [`HasField`](../traits/field-access/has_field.md) impl against another purely from the tag. A `Chars` chain is how the string becomes a type, and a `Symbol` wrapping that chain is the tag itself. -The reason the encoding is a *list of characters* is a limit in stable Rust: a `String` or `&str` cannot +The encoding is a *list of characters* because of a limit in stable Rust: a `String` or `&str` cannot be a const-generic parameter, but a single `char` can. So CGP spells the string out one character at a time through a recursive `Chars` list, terminated by [`Nil`](nil.md), the same way the product list spells out its elements through [`Cons`](cons.md). `Chars` is the specialized form of `Cons` in which the @@ -115,20 +115,20 @@ a `const char`, so it cannot carry arbitrary element types the way a product lis ## Related constructs -- [`Nil`](nil.md) — the end marker that terminates a `Chars` chain. -- [`Cons`](cons.md) — the general product list this one specializes, with a type head rather than a +- [`Nil`](nil.md): the end marker that terminates a `Chars` chain. +- [`Cons`](cons.md): the general product list this one specializes, with a type head rather than a `const char`. -- [`Symbol!`](../macros/symbol.md) — the macro that folds a string into a `Chars` chain and wraps it. +- [`Symbol!`](../macros/symbol.md): the macro that folds a string into a `Chars` chain and wraps it. - [`StaticFormat`](../traits/formatting/static_format.md) and - [`StaticString`](../traits/formatting/static_string.md) — recover the runtime string and the const + [`StaticString`](../traits/formatting/static_string.md): recover the runtime string and the const from the chain. -- [`HasField`](../traits/field-access/has_field.md) — matches a field against its `Symbol!` tag. -- [`Field`](field.md) — carries a `Symbol!` tag beside its value. -- [`Index`](index_type.md) — the position tag for a tuple field, the numeric counterpart. +- [`HasField`](../traits/field-access/has_field.md): matches a field against its `Symbol!` tag. +- [`Field`](field.md): carries a `Symbol!` tag beside its value. +- [`Index`](index_type.md): the position tag for a tuple field, the numeric counterpart. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where field-name tags are used at scale. +- [Extensible records](/docs/concepts/extensible-records): where field-name tags are used at scale. ## Source diff --git a/docs/reference/types/cons.md b/docs/reference/types/cons.md index 930c667e..a896580a 100644 --- a/docs/reference/types/cons.md +++ b/docs/reference/types/cons.md @@ -123,17 +123,17 @@ empty form is the uninhabited [`Void`](void.md). An empty record exists; an empt ## Related constructs -- [`Nil`](nil.md) — the end marker that terminates this list. -- [`Either`](either.md) and [`Void`](void.md) — the sum list, the choice-shaped dual of this one. -- [`Chars`](chars.md) — the same list specialized to a `const char` head. -- [`Product!`](../macros/product.md) — the macro that folds elements onto this list. -- [`Field`](field.md) — what the elements usually are, pairing a name with a value. -- [`HasFields`](../traits/shape/has_fields.md) — exposes a struct's shape as one of these lists. -- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — generates that list for a struct. +- [`Nil`](nil.md): the end marker that terminates this list. +- [`Either`](either.md) and [`Void`](void.md): the sum list, the choice-shaped dual of this one. +- [`Chars`](chars.md): the same list specialized to a `const char` head. +- [`Product!`](../macros/product.md): the macro that folds elements onto this list. +- [`Field`](field.md): what the elements usually are, pairing a name with a value. +- [`HasFields`](../traits/shape/has_fields.md): exposes a struct's shape as one of these lists. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md): generates that list for a struct. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — the record representation this list encodes. +- [Extensible records](/docs/concepts/extensible-records): the record representation this list encodes. ## Source diff --git a/docs/reference/types/either.md b/docs/reference/types/either.md index cc027613..bef30715 100644 --- a/docs/reference/types/either.md +++ b/docs/reference/types/either.md @@ -127,16 +127,16 @@ it might, but the types still differ. ## Related constructs -- [`Void`](void.md) — the uninhabited end marker that terminates this list. -- [`Cons`](cons.md) and [`Nil`](nil.md) — the product list, the record-shaped dual of this one. -- [`Sum!`](../macros/sum.md) — the macro that folds element types onto this list. -- [`Field`](field.md) — what the branches usually are, pairing a variant name with its payload. -- [`HasFields`](../traits/shape/has_fields.md) — exposes an enum's shape as one of these lists. -- [`ExtractField`](../traits/variant/extract_field.md) — the extractor family that walks this list. +- [`Void`](void.md): the uninhabited end marker that terminates this list. +- [`Cons`](cons.md) and [`Nil`](nil.md): the product list, the record-shaped dual of this one. +- [`Sum!`](../macros/sum.md): the macro that folds element types onto this list. +- [`Field`](field.md): what the branches usually are, pairing a variant name with its payload. +- [`HasFields`](../traits/shape/has_fields.md): exposes an enum's shape as one of these lists. +- [`ExtractField`](../traits/variant/extract_field.md): the extractor family that walks this list. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — the variant representation this list encodes. +- [Extensible variants](/docs/concepts/extensible-variants): the variant representation this list encodes. ## Source diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index 96d6114a..2656e004 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -129,20 +129,20 @@ distinguish them at run time, it does not; the tag distinguishes them only in th ## Related constructs -- [`Symbol!`](../macros/symbol.md) — the tag for a named field or variant. -- [`Index`](index_type.md) — the tag for a tuple-struct position. -- [`PhantomData`](phantom_data.md) — where the tag is stored, at zero size. -- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the lists of `Field` entries that +- [`Symbol!`](../macros/symbol.md): the tag for a named field or variant. +- [`Index`](index_type.md): the tag for a tuple-struct position. +- [`PhantomData`](phantom_data.md): where the tag is stored, at zero size. +- [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md): the lists of `Field` entries that describe a record and a variant. -- [`Cons`](cons.md) and [`Either`](either.md) — the product and sum lists those entries are built into. -- [`HasFields`](../traits/shape/has_fields.md) — exposes a type's whole list of `Field` entries. -- [`HasField`](../traits/field-access/has_field.md) — single-field access against a matching tag. -- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — assigns the list of entries to a type. +- [`Cons`](cons.md) and [`Either`](either.md): the product and sum lists those entries are built into. +- [`HasFields`](../traits/shape/has_fields.md): exposes a type's whole list of `Field` entries. +- [`HasField`](../traits/field-access/has_field.md): single-field access against a matching tag. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md): assigns the list of entries to a type. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where field-name entries are used at scale. -- [Extensible variants](/docs/concepts/extensible-variants) — the same entry naming a variant. +- [Extensible records](/docs/concepts/extensible-records): where field-name entries are used at scale. +- [Extensible variants](/docs/concepts/extensible-variants): the same entry naming a variant. ## Source diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index 078caaaf..b64f3340 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -5,34 +5,34 @@ sidebar_position: 0 # Types -The types CGP is built out of: the type-level building blocks that carry information in the type system, -and the one ordinary runtime data type you return from a getter. +The types CGP is built from: the type-level building blocks that carry information in the type system, and +the one ordinary runtime type you return from a getter. ## Overview -Most of the types on these pages are **type-level building blocks**. Much of CGP's machinery works at the -type level, where a field name, a variant, a position, or a whole record shape is a *type* rather than a -value. These building blocks are how that is done, and you write almost none of them by hand. You meet -them when you read the code a macro generated, or when a wiring mistake prints a wall of nested types, -and this section exists so that such a type is legible. +Most types on these pages are **type-level building blocks**. Much of CGP's machinery runs at the type +level, where a field name, a variant, a position, or a whole record shape is a *type* rather than a value. +These building blocks are how CGP does that, and you write almost none of them by hand. You meet them when +you read the code a macro generated, or when a wiring mistake prints a wall of nested types. This section +exists to make such a type legible. -One idea runs through nearly all of them, and it is worth holding before the rest: a type can carry -information the program never stores as a value. A struct can name a type parameter it keeps no field of, -so a name, a number, or a lifetime becomes part of a type's identity and the compiler matches on it during -trait resolution. [`PhantomData`](phantom_data.md) is the standard-library tool that makes this legal, so -it is the first page here and the mechanism the others build on. +One idea runs through nearly all of them, so hold it first: a type can carry information the program never +stores as a value. A struct can name a type parameter it keeps no field of, so a name, a number, or a +lifetime becomes part of the type's identity, and the compiler matches on it during trait resolution. +[`PhantomData`](phantom_data.md) is the standard-library tool that makes this legal, so it comes first +here, and the other types build on it. -The building blocks divide into two groups. +The building blocks divide into two groups: markers and recursive type-level lists. The **markers** each attach one piece of information at the type level. [`Index`](index_type.md) turns a tuple-field position into a type, the way [`Symbol!`](../macros/symbol.md) turns a field name into one, -and [`Life`](life.md) lifts a lifetime into a type so it can travel through machinery that only accepts +and [`Life`](life.md) lifts a lifetime into a type so it can travel through machinery that accepts only types. [`Field`](field.md) uses such a tag: it pairs a value with its type-level name, so a record or a variant entry knows what it is called. -The **recursive type-level lists** are the chains everything structural is built from: a head-and-tail -cell paired with a terminator, which generic code takes apart one element at a time. Four cover four jobs, -and each family's full account lives on its head cell. [`Cons`](cons.md) and [`Nil`](nil.md) build a +The **recursive type-level lists** are the chains everything structural is built from. Each pairs a +head-and-tail cell with a terminator, and generic code takes it apart one element at a time. Each family +covers one job, and its full account lives on its head cell. [`Cons`](cons.md) and [`Nil`](nil.md) build a record, and `Cons` owns the type-level product. [`Either`](either.md) and [`Void`](void.md) build a variant, and `Either` owns the type-level sum. [`Chars`](chars.md) builds a string, and [`PathCons`](path_cons.md) builds a routing path. You write these through the sugar @@ -40,15 +40,15 @@ variant, and `Either` owns the type-level sum. [`Chars`](chars.md) builds a stri [`Path!`](../macros/path.md)) and read them in expansions and errors. One type is not a building block at all. [`MRef`](mref.md) is an ordinary runtime value, the -owned-or-borrowed return type of a getter, and it is here because it is the one type in this section you -write on purpose. +owned-or-borrowed return type of a getter. It is here because it is the one type in this section you write +on purpose. ## The ideas behind them -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — where the zero-sized +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): where the zero-sized provider structs that carry these markers come from. -- [Extensible records](/docs/concepts/extensible-records) — the record shape the product list describes. -- [Extensible variants](/docs/concepts/extensible-variants) — the variant shape the sum list describes. +- [Extensible records](/docs/concepts/extensible-records): the record shape the product list describes. +- [Extensible variants](/docs/concepts/extensible-variants): the variant shape the sum list describes. --- diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index 04928976..cf3b0360 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -14,11 +14,11 @@ A number lifted into a type, so a tuple-struct field can be named by its positio *type* tag, and a tuple-struct field has no string name to turn into a [`Symbol!`](../macros/symbol.md); it has only a position. To let positional fields use the same trait-resolution machinery as named fields, the position itself becomes a type. `Index` is that type: it carries a `usize` as a const parameter -and nothing else, so `Index<0>`, `Index<1>`, and `Index<2>` are three distinct types standing in for the -first, second, and third fields of a tuple struct. +and nothing else, so `Index<0>`, `Index<1>`, and `Index<2>` are distinct types standing in for a tuple +struct's positional fields. -Encoding the position as a type lets positional field access resolve through traits. A **context** is -the type the capability runs against, which supplies those values as its own fields. Because +Encoding the position as a type lets positional field access resolve through traits. Here a **context** is +the type the capability runs against, which supplies the values it needs as its own fields. Because `Index<0>` is a type, a context can carry a [`HasField>`](../traits/field-access/has_field.md) impl for its first field and a `HasField>` impl for its second side by side, and the compiler selects the right one from the @@ -42,8 +42,8 @@ pub struct Index; `I` is the position the type represents: `Index<0>` for the field at offset zero, and so on. The struct has no fields, so a value of `Index` carries no data and the number lives entirely in the type. The -derived `Default`, `Clone`, and `Copy` make a value trivially available when one is needed, and `Eq` and -`PartialEq` compare two values of the same `Index` as always equal, since there is nothing to differ. +derived `Default`, `Clone`, and `Copy` make a value available whenever one is needed, and `Eq` and +`PartialEq` treat two values of the same `Index` as always equal, since they hold no data. `Index` also implements `Display` and `Debug`, and both print the underlying number, so `Index<0>` displays as `0` and the position a tag stands for is visible in output and in diagnostics. @@ -59,7 +59,7 @@ reads positions where it would read `Symbol!` names for a named struct. Because `Index` is zero-sized and the position lives in the type, accessing a field by index resolves entirely at compile time: there is no array bound check and no runtime indexing. Selecting the wrong -index is a type error rather than a panic, because `Index<5>` on a three-field struct simply has no +index is a type error rather than a panic, because `Index<5>` on a three-field struct has no matching `HasField` impl. ## Examples @@ -122,17 +122,17 @@ struct has no `HasField` impl, so the mistake is caught at compile time. ## Related constructs -- [`Symbol!`](../macros/symbol.md) — the string tag for a named field, the counterpart to this numeric +- [`Symbol!`](../macros/symbol.md): the string tag for a named field, the counterpart to this numeric one. -- [`HasField`](../traits/field-access/has_field.md) — what a tag is looked up through. -- [`#[derive(HasField)]`](../derives/derive_has_field.md) — generates an `Index` tag per tuple field. -- [`Field`](field.md) — carries an `Index` tag beside a positional value. -- [`PhantomData`](phantom_data.md) — how an `Index` tag is passed to `get_field`. -- [`HasFields`](../traits/shape/has_fields.md) — the tuple struct's shape whose entries this tag names. +- [`HasField`](../traits/field-access/has_field.md): what a tag is looked up through. +- [`#[derive(HasField)]`](../derives/derive_has_field.md): generates an `Index` tag per tuple field. +- [`Field`](field.md): carries an `Index` tag beside a positional value. +- [`PhantomData`](phantom_data.md): how an `Index` tag is passed to `get_field`. +- [`HasFields`](../traits/shape/has_fields.md): the tuple struct's shape whose entries this tag names. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where positional field access is used at +- [Extensible records](/docs/concepts/extensible-records): where positional field access is used at scale. ## Source diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index 9e3861a1..523fc232 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -5,7 +5,7 @@ sidebar_position: 4 # `Life` -A lifetime lifted into a type, so a lifetime parameter can travel through machinery that only accepts +A lifetime lifted into a type, so a lifetime parameter can travel through machinery that accepts only types. ## Overview @@ -19,9 +19,9 @@ lifetime parameter on the trait must first become a type, and `Life<'a>` is that the lifetime `'a` as a concrete type that can stand alongside the trait's other type parameters. Without this lift, a trait that borrows could not record its lifetime in the dependency marker, and the -wiring could not tell one lifetime instantiation from another. Here a **context** is the type the -capability runs against. `Life` lets the lifetime ride through `IsProviderFor` as `(Life<'a>, T)`, -keeping it part of the provider's identity while the marker's argument stays a plain type. +wiring could not tell one lifetime instantiation from another. `Life` lets the lifetime ride through +`IsProviderFor` as `(Life<'a>, T)`, keeping it part of the provider's identity while the marker's +argument stays a plain type. ## Definition @@ -47,8 +47,8 @@ to a real borrow, since it neither owns nor references a real value. position. In a generated provider trait for a component with a lifetime, the lifetime is collected into the [`IsProviderFor`](../traits/wiring/is_provider_for.md) argument tuple as `Life<'a>`, so the provider's dependency obligation reads the same way it would for any type parameter. The provider trait, its blanket -forwarding impl, and the impls that satisfy it all agree on the same `(Life<'a>, T)` shape, which is what -lets a borrowing component be wired and checked exactly like a non-borrowing one. +forwarding impl, and the impls that satisfy it all agree on the same `(Life<'a>, T)` shape, and that +shared shape lets a borrowing component be wired and checked exactly like a non-borrowing one. ## Examples @@ -109,17 +109,17 @@ a recorded limitation, noted on [`IsProviderFor`](../traits/wiring/is_provider_f ## Related constructs -- [`IsProviderFor`](../traits/wiring/is_provider_for.md) — whose parameter tuple a lifetime is lifted +- [`IsProviderFor`](../traits/wiring/is_provider_for.md): whose parameter tuple a lifetime is lifted into as `Life<'a>`. -- [`#[cgp_component]`](../macros/cgp_component.md) — inserts `Life` when a consumer trait carries a +- [`#[cgp_component]`](../macros/cgp_component.md): inserts `Life` when a consumer trait carries a lifetime. -- [`PhantomData`](phantom_data.md) — the marker `Life` is built from, wrapped for invariance. -- [`Index`](index_type.md) and [`Chars`](chars.md) — the other lifts that make a non-type +- [`PhantomData`](phantom_data.md): the marker `Life` is built from, wrapped for invariance. +- [`Index`](index_type.md) and [`Chars`](chars.md): the other lifts that make a non-type addressable in trait resolution, a number and a string where `Life` lifts a lifetime. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the provider-trait +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the provider-trait machinery whose dependency marker carries this lift. ## Source diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 1562e0f0..6440c2be 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -54,8 +54,8 @@ so `&*my_ref` and any auto-deref method call work regardless of which case is in Building an `MRef` is frictionless, because it implements `From` in both directions: `From` builds `Owned` and `From<&'a T>` builds `Ref`, so a value or a reference converts with `.into()`. When a caller needs ownership unconditionally, `get_or_clone` resolves the enum to a plain `T`, returning the owned -value as is or cloning the borrowed one, and is available whenever `T: Clone`. These three pieces, the -transparent `Deref` and `AsRef`, the two `From` impls, and `get_or_clone`, are the whole surface: a +value as is or cloning the borrowed one, and is available whenever `T: Clone`. Together these make up the +whole surface: the transparent `Deref` and `AsRef`, the two `From` impls, and `get_or_clone`. A borrowed `MRef` is read cheaply and promoted to ownership only when asked. ## Examples @@ -114,17 +114,17 @@ the value should have been promoted with `get_or_clone` instead. ## Related constructs -- [`#[cgp_getter]`](../macros/cgp_getter.md) — the getter component whose return type may be `MRef`. -- [`UseField`](../providers/use_field.md) and [`UseFieldRef`](../providers/use_field_ref.md) — the +- [`#[cgp_getter]`](../macros/cgp_getter.md): the getter component whose return type may be `MRef`. +- [`UseField`](../providers/use_field.md) and [`UseFieldRef`](../providers/use_field_ref.md): the providers that wire a getter, and the by-reference variant. -- [`HasField`](../traits/field-access/has_field.md) — the field access an `MRef` getter builds on. -- [`#[implicit]`](../attributes/implicit.md) — the default way to read a field, which also accepts an +- [`HasField`](../traits/field-access/has_field.md): the field access an `MRef` getter builds on. +- [`#[implicit]`](../attributes/implicit.md): the default way to read a field, which also accepts an `MRef` type. -- [`Life`](life.md) — a different, type-level use of a lifetime, not to be confused with this one. +- [`Life`](life.md): a different, type-level use of a lifetime, not to be confused with this one. The ideas behind it: -- [Implicit arguments](/docs/concepts/implicit-arguments) — reading a value out of a context, which is +- [Implicit arguments](/docs/concepts/implicit-arguments): reading a value out of a context, which is what an `MRef` getter returns. ## Source diff --git a/docs/reference/types/nil.md b/docs/reference/types/nil.md index 7c1b045e..09701d77 100644 --- a/docs/reference/types/nil.md +++ b/docs/reference/types/nil.md @@ -13,7 +13,7 @@ The end marker of the product, string, and path lists: an empty, constructible l the rest of the list, `Nil` is the rest when there is nothing left, so a list of any length is a `Cons` chain that finishes in `Nil`. On its own, `Nil` is the empty list. -The same marker terminates three of CGP's four lists. It ends the product list built from +The same marker terminates every CGP list but one. It ends the product list built from [`Cons`](cons.md), the string list built from [`Chars`](chars.md), and the path list built from [`PathCons`](path_cons.md). Only the sum list ends differently, in the uninhabited [`Void`](void.md), and that difference is the point of both markers: a record, a string, and a path can each be empty and @@ -91,14 +91,14 @@ seeing it outside a record is expected. ## Related constructs -- [`Cons`](cons.md) — the head-and-tail cell this marker terminates in a record. -- [`Void`](void.md) — the sum list's uninhabited end marker, the counterpart to this one. -- [`Chars`](chars.md) and [`PathCons`](path_cons.md) — the string and path lists `Nil` also terminates. -- [`Product!`](../macros/product.md) — the macro whose empty form is `Nil`. +- [`Cons`](cons.md): the head-and-tail cell this marker terminates in a record. +- [`Void`](void.md): the sum list's uninhabited end marker, the counterpart to this one. +- [`Chars`](chars.md) and [`PathCons`](path_cons.md): the string and path lists `Nil` also terminates. +- [`Product!`](../macros/product.md): the macro whose empty form is `Nil`. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where the empty and terminating record shape +- [Extensible records](/docs/concepts/extensible-records): where the empty and terminating record shape matters. ## Source diff --git a/docs/reference/types/path_cons.md b/docs/reference/types/path_cons.md index 7b4e5e16..abfaee38 100644 --- a/docs/reference/types/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -122,19 +122,19 @@ the same terminator doing the same job it does for a record, not a sign the two ## Related constructs -- [`Nil`](nil.md) — the end marker that terminates a `PathCons` chain. -- [`Cons`](cons.md) — the product list this one parallels, whose elements are sized values rather than +- [`Nil`](nil.md): the end marker that terminates a `PathCons` chain. +- [`Cons`](cons.md): the product list this one parallels, whose elements are sized values rather than `?Sized` markers. -- [`Chars`](chars.md) — the [`Symbol`](chars.md) segments a path is built from. -- [`Path!`](../macros/path.md) — the macro that folds `@`-segments onto this list. -- [`ConcatPath`](../traits/formatting/concat_path.md) — appends one path onto another. -- [`RedirectLookup`](../providers/redirect_lookup.md) — walks a path against a table at resolution +- [`Chars`](chars.md): the [`Symbol`](chars.md) segments a path is built from. +- [`Path!`](../macros/path.md): the macro that folds `@`-segments onto this list. +- [`ConcatPath`](../traits/formatting/concat_path.md): appends one path onto another. +- [`RedirectLookup`](../providers/redirect_lookup.md): walks a path against a table at resolution time. -- [`cgp_namespace!`](../macros/cgp_namespace.md) — emits these paths to reroute and register entries. +- [`cgp_namespace!`](../macros/cgp_namespace.md): emits these paths to reroute and register entries. The ideas behind it: -- [Namespaces](/docs/concepts/namespaces) — where a path routes a component lookup through a reusable +- [Namespaces](/docs/concepts/namespaces): where a path routes a component lookup through a reusable table. ## Source diff --git a/docs/reference/types/phantom_data.md b/docs/reference/types/phantom_data.md index 56658940..62109658 100644 --- a/docs/reference/types/phantom_data.md +++ b/docs/reference/types/phantom_data.md @@ -5,8 +5,8 @@ sidebar_position: 1 # `PhantomData` -The standard-library marker that lets a type carry a type parameter it stores no value of. It is what -makes CGP's zero-sized providers and type-level markers legal, and it is the token you pass to hand a +The standard-library marker that lets a type carry a type parameter it stores no value of. It makes +CGP's zero-sized providers and type-level markers legal, and it is the token you pass to hand a type to a function. ## Overview @@ -67,7 +67,7 @@ one by writing `PhantomData`, and you name the type it carries with a turbofish as in `PhantomData::`. Because the type parameter is recorded but no value of it is stored, `PhantomData` also tells the -compiler how the surrounding type relates to `T` for three purposes beyond the "used parameter" rule: +compiler how the surrounding type relates to `T`, beyond the "used parameter" rule: it sets **variance** (whether a longer lifetime may stand in for a shorter one), **drop checking**, and the **auto traits** such as `Send` and `Sync`. Most CGP markers do not care which relationship they get and use the plain `PhantomData`. The exception is [`Life`](life.md), which wraps its lifetime as @@ -86,7 +86,7 @@ its type-level name tag in a `PhantomData` beside the one real value it sto parameter is part of the type's identity and nothing the type keeps at run time. **On the passing side, `PhantomData::` is a zero-sized value that hands the type `T` to a -function.** A method that must know which field, which code, or which tag is meant takes a +function.** A method that must know which field, which computation, or which tag is meant takes a `PhantomData` argument, and the caller supplies the type through it: ```rust @@ -177,22 +177,22 @@ fails to compile with `error[E0392]` without one. ## Related constructs -- [`Field`](field.md) — holds its type-level name tag in a `PhantomData` beside its value. -- [`Life`](life.md) — a lifetime lifted into a type through a deliberately invariant `PhantomData`. -- [`Chars`](chars.md) and [`PathCons`](path_cons.md) — recursive type-level lists whose tails are +- [`Field`](field.md): holds its type-level name tag in a `PhantomData` beside its value. +- [`Life`](life.md): a lifetime lifted into a type through a deliberately invariant `PhantomData`. +- [`Chars`](chars.md) and [`PathCons`](path_cons.md): recursive type-level lists whose tails are `PhantomData` markers. -- [`Symbol!`](../macros/symbol.md) and [`Index`](index_type.md) — the tags a `PhantomData::` +- [`Symbol!`](../macros/symbol.md) and [`Index`](index_type.md): the tags a `PhantomData::` argument usually carries. -- [`HasField`](../traits/field-access/has_field.md) — whose `get_field` takes the tag as a +- [`HasField`](../traits/field-access/has_field.md): whose `get_field` takes the tag as a `PhantomData` argument. -- [`#[cgp_new_provider]`](../macros/cgp_provider.md) — declares a provider struct's `PhantomData` field +- [`#[cgp_new_provider]`](../macros/cgp_provider.md): declares a provider struct's `PhantomData` field for you. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — where the zero-sized +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): where the zero-sized provider structs that carry `PhantomData` come from. -- [Type-level DSLs](/docs/concepts/type-level-dsls) — encoding a program as types, which is why a type +- [Type-level DSLs](/docs/concepts/type-level-dsls): encoding a program as types, which is why a type gets passed as a value at all. ## Source diff --git a/docs/reference/types/void.md b/docs/reference/types/void.md index 2ea6d40f..d91007a7 100644 --- a/docs/reference/types/void.md +++ b/docs/reference/types/void.md @@ -91,7 +91,7 @@ on it with no arms, which the extractor family does when a variant match is comp ## Common Mistakes **`Void` is uninhabited; [`Nil`](nil.md) is not.** `Nil` is a real value the empty product is, while -`Void` is a type with no values. Records use the first, variants the second, and an error naming the +`Void` is a type with no values. Records use `Nil`, variants use `Void`, and an error naming the wrong one usually means the two families have been crossed. **You cannot build a `Void`.** There is no constructor and no literal for it, by design. Any code that @@ -99,18 +99,18 @@ appears to "return a `Void`" is really an empty match that never returns at all. ## Related constructs -- [`Either`](either.md) — the head-or-rest cell this marker terminates. -- [`Nil`](nil.md) — the product, string, and path lists' constructible end marker, the counterpart to +- [`Either`](either.md): the head-or-rest cell this marker terminates. +- [`Nil`](nil.md): the product, string, and path lists' constructible end marker, the counterpart to this one. -- [`Sum!`](../macros/sum.md) — the macro whose empty form is `Void`. -- [`FinalizeExtract`](../traits/variant/finalize_extract.md) — discharges the uninhabited remainder of +- [`Sum!`](../macros/sum.md): the macro whose empty form is `Void`. +- [`FinalizeExtract`](../traits/variant/finalize_extract.md): discharges the uninhabited remainder of a variant extraction with an empty match. -- [`FinalizeExtractResult`](../traits/variant/finalize_extract_result.md) — the result-carrying form +- [`FinalizeExtractResult`](../traits/variant/finalize_extract_result.md): the result-carrying form built on the same idea. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — where the uninhabited terminator closes a +- [Extensible variants](/docs/concepts/extensible-variants): where the uninhabited terminator closes a total variant match. ## Source From d26dd39c67135edc25702c5e812d125413039341 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 11:31:19 +0200 Subject: [PATCH 056/516] reference/traits: revise prose for point-first style MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove em dashes across all trait pages: name the relationship each one stood in for (colon, period, parentheses, comma, or a connective such as so/since/which), and convert glossary "link — gloss" bullets to colons. Also drop pseudo-clefts and copular openers, replace stated counts and ordinal list-leads, and remove a duplicated paragraph in shape/from_fields. Footer disclaimer lines left unchanged to stay consistent with the site. Co-Authored-By: Claude Opus 4.8 --- docs/reference/traits/builder/build_field.md | 36 ++++++------ .../traits/builder/finalize_build.md | 38 ++++++------ docs/reference/traits/builder/has_builder.md | 40 ++++++------- docs/reference/traits/builder/index.md | 4 +- docs/reference/traits/builder/into_builder.md | 40 ++++++------- docs/reference/traits/builder/partial_data.md | 32 +++++----- docs/reference/traits/builder/take_field.md | 40 ++++++------- docs/reference/traits/builder/update_field.md | 30 +++++----- .../traits/casting/can_build_from.md | 24 ++++---- docs/reference/traits/casting/can_downcast.md | 22 +++---- .../traits/casting/can_downcast_fields.md | 22 +++---- docs/reference/traits/casting/can_upcast.md | 28 ++++----- docs/reference/traits/casting/index.md | 8 +-- .../traits/field-access/field_getter.md | 34 +++++------ .../traits/field-access/field_mapper.md | 28 ++++----- .../traits/field-access/has_field.md | 46 +++++++-------- .../traits/field-access/has_field_mut.md | 28 ++++----- docs/reference/traits/field-access/index.md | 12 ++-- .../traits/field-access/map_field.md | 36 ++++++------ .../traits/field-access/mut_field_getter.md | 32 +++++----- .../traits/formatting/concat_path.md | 34 +++++------ docs/reference/traits/formatting/index.md | 8 +-- .../traits/formatting/static_format.md | 38 ++++++------ .../traits/formatting/static_string.md | 36 ++++++------ docs/reference/traits/monad/contains_value.md | 28 ++++----- docs/reference/traits/monad/index.md | 8 +-- docs/reference/traits/monad/lift_value.md | 28 ++++----- docs/reference/traits/monad/monadic_bind.md | 32 +++++----- docs/reference/traits/monad/monadic_trans.md | 32 +++++----- .../traits/namespace/default_impls1.md | 38 ++++++------ .../traits/namespace/default_impls2.md | 32 +++++----- .../traits/namespace/default_namespace.md | 44 +++++++------- docs/reference/traits/namespace/index.md | 4 +- .../traits/optional/can_build_with_default.md | 28 ++++----- .../optional/can_finalize_with_default.md | 36 ++++++------ .../traits/optional/finalize_optional.md | 28 ++++----- .../traits/optional/has_optional_builder.md | 40 ++++++------- docs/reference/traits/optional/index.md | 4 +- .../reference/traits/optional/set_optional.md | 26 ++++----- docs/reference/traits/optional/to_optional.md | 34 +++++------ .../traits/optional/transform_map_default.md | 32 +++++----- .../traits/optional/transform_optional.md | 28 ++++----- docs/reference/traits/shape/from_fields.md | 34 +++++------ docs/reference/traits/shape/has_fields.md | 56 +++++++++--------- docs/reference/traits/shape/has_fields_ref.md | 30 +++++----- docs/reference/traits/shape/index.md | 12 ++-- docs/reference/traits/shape/to_fields.md | 26 ++++----- docs/reference/traits/shape/to_fields_ref.md | 26 ++++----- .../traits/type-level/append_product.md | 36 ++++++------ .../traits/type-level/concat_product.md | 26 ++++----- docs/reference/traits/type-level/index.md | 4 +- .../reference/traits/type-level/map_fields.md | 40 ++++++------- docs/reference/traits/type-level/map_type.md | 40 ++++++------- .../traits/type-level/map_type_ref.md | 32 +++++----- .../traits/type-level/transform_map.md | 36 ++++++------ .../traits/type-level/transform_map_fields.md | 32 +++++----- .../reference/traits/variant/extract_field.md | 32 +++++----- .../traits/variant/finalize_extract.md | 30 +++++----- .../traits/variant/finalize_extract_result.md | 24 ++++---- docs/reference/traits/variant/from_variant.md | 20 +++---- .../reference/traits/variant/has_extractor.md | 30 +++++----- .../traits/variant/has_extractor_mut.md | 26 ++++----- .../traits/variant/has_extractor_ref.md | 34 +++++------ docs/reference/traits/variant/index.md | 4 +- .../traits/wiring/can_use_component.md | 30 +++++----- .../traits/wiring/delegate_component.md | 52 ++++++++--------- docs/reference/traits/wiring/index.md | 18 +++--- .../traits/wiring/is_provider_for.md | 58 +++++++++---------- 68 files changed, 991 insertions(+), 995 deletions(-) diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index e04951f3..a9320812 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -12,7 +12,7 @@ Setting one currently-absent field of a builder. `BuildField` is the direction of the [builder family](./has_builder.md) you write most: take a partial record with a field absent, supply the value, and get back a partial record with that field present. -`Output` is a **different type** from `Self` — the same partial record with one marker flipped — which is +`Output` is a **different type** from `Self` (the same partial record with one marker flipped), which is what makes the compiler track completeness. A chain of `build_field` calls walks through as many distinct types as there are fields, and only the last one satisfies [`FinalizeBuild`](./finalize_build.md). @@ -109,16 +109,16 @@ marker to `IsPresent` and constraining the reported source marker to `IsNothing` // where Partial: UpdateField ``` -The `Mapper = IsNothing` constraint does the checking. `Mapper` is an *output* of the primitive — -the marker the field was in — so constraining it selects only those partial types whose field is +The `Mapper = IsNothing` constraint does the checking. `Mapper` is an *output* of the primitive (the +marker the field was in), so constraining it selects only those partial types whose field is currently absent. A field already set has `Mapper = IsPresent`, no impl matches, and the call fails to resolve. `update_field` returns the old value alongside the new partial; `build_field` discards it, which is sound because the old value under `IsNothing` is `()`. -[`TakeField`](./take_field.md) is the mirror image — the same primitive with `IsNothing` as the target -and `Mapper = IsPresent` — which is why the two read as opposites and share every mechanism. +[`TakeField`](./take_field.md) is the mirror image (the same primitive with `IsNothing` as the target +and `Mapper = IsPresent`), which is why the two read as opposites and share every mechanism. ## Common Mistakes @@ -126,7 +126,7 @@ and `Mapper = IsPresent` — which is why the two read as opposites and share ev is the guarantee, and the error is a missing-method one rather than anything mentioning "already set". **`Output` is a different type from `Self`.** A builder cannot be stored in a variable of fixed type -across a chain, and it cannot be filled in a loop — the chain is unrolled by construction. +across a chain, and it cannot be filled in a loop. The chain is unrolled by construction. **The error for an incomplete build arrives at `finalize_build`**, not here. Forgetting a field is only detectable at the end, since any prefix of a chain is a legal partial value. @@ -142,27 +142,27 @@ detectable at the end, since any prefix of a chain is a legal partial value. ## Related constructs -- [`UpdateField`](./update_field.md) — the primitive this pins one direction of. -- [`TakeField`](./take_field.md) — the opposite direction. -- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — where a partial value comes +- [`UpdateField`](./update_field.md): the primitive this pins one direction of. +- [`TakeField`](./take_field.md): the opposite direction. +- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md): where a partial value comes from. -- [`FinalizeBuild`](./finalize_build.md) — where a completed one goes. -- [`CanBuildFrom`](../casting/can_build_from.md) — filling many fields from another record in one call. -- [`SetOptional`](../optional/set_optional.md) — the settable-repeatedly counterpart. -- [`MapType`](../type-level/map_type.md) — the `IsNothing`/`IsPresent` markers this moves between. -- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the `UpdateField` impls behind +- [`FinalizeBuild`](./finalize_build.md): where a completed one goes. +- [`CanBuildFrom`](../casting/can_build_from.md): filling many fields from another record in one call. +- [`SetOptional`](../optional/set_optional.md): the settable-repeatedly counterpart. +- [`MapType`](../type-level/map_type.md): the `IsNothing`/`IsPresent` markers this moves between. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md): generates the `UpdateField` impls behind it. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that name a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that name a field. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder pattern. ## Source -- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs) - — `BuildField` and `FinalizeBuild` +- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs): + `BuildField` and `FinalizeBuild` --- diff --git a/docs/reference/traits/builder/finalize_build.md b/docs/reference/traits/builder/finalize_build.md index 1e13430f..4e6c7903 100644 --- a/docs/reference/traits/builder/finalize_build.md +++ b/docs/reference/traits/builder/finalize_build.md @@ -11,8 +11,8 @@ Turning a fully-built partial record back into the concrete struct. `FinalizeBuild` is where a build ends. What makes it the family's safety argument is not the method but **where the impl exists**. It is -implemented for exactly one configuration of a partial record — the one in which every field is -`IsPresent` — so calling it on an incomplete value is a *missing impl*, not a runtime check that fails: +implemented for exactly one configuration of a partial record, the one in which every field is +`IsPresent`, so calling it on an incomplete value is a *missing impl*, not a runtime check that fails: ```rust let person = Person::builder() @@ -21,7 +21,7 @@ let person = Person::builder() .finalize_build(); // resolves only here ``` -Delete a middle line and this does not compile. There is nothing to run and nothing to panic — the method +Delete a middle line and this does not compile. There is nothing to run and nothing to panic: the method is simply not in scope for a value with a field still absent. The destination type comes from its supertrait [`PartialData`](./partial_data.md), which every @@ -42,14 +42,14 @@ pub trait FinalizeBuild: PartialData { concrete struct being built. `Target` is not declared here: it comes from the supertrait [`PartialData`](./partial_data.md), which every configuration of a partial record implements, so the destination is nameable at any point in a build. What `FinalizeBuild` adds is the method, and its impl -exists for only one configuration — every field `IsPresent` — which is the safety argument the rest of +exists for only one configuration (every field `IsPresent`), which is the safety argument the rest of this page works out. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -`finalize_build` consumes the partial value and returns `Self::Target`. It takes no arguments — there is +`finalize_build` consumes the partial value and returns `Self::Target`. It takes no arguments. There is nothing left to decide by the time it applies. Bounding on it is how generic builder code says it will produce a finished value: @@ -85,7 +85,7 @@ let person = Person::builder() .finalize_build(); ``` -And the failure it exists to produce — omitting a field: +And the failure it exists to produce, omitting a field: ```rust // error: no method named `finalize_build` found for struct @@ -135,7 +135,7 @@ So a partial value always knows its destination and only sometimes has a way to same order, and the body is a field-by-field move with nothing to unwrap. **This is why the error is a missing method rather than a missing field.** Method resolution looks for -`finalize_build` on `__PartialPerson`, finds no impl, and reports that — the +`finalize_build` on `__PartialPerson`, finds no impl, and reports that. The compiler has no way to say "you forgot `last_name`", because nothing in the failed lookup mentions field names. The marker list in the type is the diagnostic. @@ -158,34 +158,34 @@ type in the message: the field whose marker is still `IsNothing` is the one miss [`FinalizeOptional`](../optional/finalize_optional.md), a different trait in a different crate. **A fieldless struct finalizes immediately.** Its companion has no markers, so `builder().finalize_build()` -compiles — legal and useless. +compiles, which is legal and useless. **The enum side has its own ending.** [`FinalizeExtract`](../variant/finalize_extract.md) discharges an exhausted extractor, and it is sound for the opposite reason: the value cannot exist, rather than being complete. ## Related constructs -- [`PartialData`](./partial_data.md) — the supertrait naming the destination. -- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — where a partial value comes +- [`PartialData`](./partial_data.md): the supertrait naming the destination. +- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md): where a partial value comes from. -- [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) — what moves it between +- [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md): what moves it between configurations. -- [`UpdateField`](./update_field.md) — the primitive underneath both. +- [`UpdateField`](./update_field.md): the primitive underneath both. - [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and - [`FinalizeOptional`](../optional/finalize_optional.md) — the two relaxed endings. -- [`MapType`](../type-level/map_type.md) — the `IsPresent` marker every field must reach. -- [`FinalizeExtract`](../variant/finalize_extract.md) — the enum family's ending, sound for the opposite reason. -- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates this impl. + [`FinalizeOptional`](../optional/finalize_optional.md): the two relaxed endings. +- [`MapType`](../type-level/map_type.md): the `IsPresent` marker every field must reach. +- [`FinalizeExtract`](../variant/finalize_extract.md): the enum family's ending, sound for the opposite reason. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md): generates this impl. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder pattern. ## Source -- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs) - — `FinalizeBuild` and `BuildField` +- [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs): + `FinalizeBuild` and `BuildField` --- diff --git a/docs/reference/traits/builder/has_builder.md b/docs/reference/traits/builder/has_builder.md index 41fee744..b9ca46d5 100644 --- a/docs/reference/traits/builder/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -15,7 +15,7 @@ of which should know the whole struct, and the result must still be checked at c `builder()` hands back a partial value with **every field absent**. Filling it is [`BuildField`](./build_field.md), and turning it back into the concrete struct is -[`FinalizeBuild`](./finalize_build.md) — which is implemented **only** for the fully-present +[`FinalizeBuild`](./finalize_build.md), which is implemented **only** for the fully-present configuration, so finalizing early is a missing impl rather than a runtime panic: ```rust @@ -110,7 +110,7 @@ Asking for `last_name` there would not compile. **Call `builder()` freely in concrete code; bound on the trait only in generic code.** In concrete code you call it and never name a trait. The bound matters when you write code that is generic over the -record being built — which is the extensible builder pattern, and the reason the family exists. +record being built, which is the extensible builder pattern, and the reason the family exists. - **Bound on `HasBuilder` + [`BuildField`](./build_field.md) + [`FinalizeBuild`](./finalize_build.md)** to write a routine that assembles some record it does not name. @@ -121,15 +121,15 @@ record being built — which is the extensible builder pattern, and the reason t decouple it is pure cost. Two boundaries are worth stating plainly. This is **not a conventional builder**: it tracks presence and -nothing else — no defaults, no validation at finalize, no optional field unless the field's own type is -optional. The [optional-field extensions](../optional/has_optional_builder.md) cover the defaulted and optional +nothing else, with no defaults, no validation at finalize, and no optional field unless the field's own +type is optional. The [optional-field extensions](../optional/has_optional_builder.md) cover the defaulted and optional cases, and a hand-written builder remains better when the *logic* is the point. And the enum counterparts are a different family: [`ExtractField`](../variant/extract_field.md) for taking a value apart and [`FromVariant`](../variant/from_variant.md) for constructing one. ## Under the hood -The derive generates a companion struct — `__Partial{Name}` — that is your struct with one +The derive generates a companion struct, `__Partial{Name}`, that is your struct with one [`MapType`](../type-level/map_type.md) parameter added per field and each field's type wrapped in that parameter's projection: @@ -158,7 +158,7 @@ impl FinalizeBuild for __PartialPerson { ``` That pair is the whole safety argument. `builder()` starts at all-absent, each -[`build_field`](./build_field.md) flips one marker, and there is no check to run at the end — the impl +[`build_field`](./build_field.md) flips one marker, and there is no check to run at the end: the impl simply is not there for an incomplete value. Everything between the two ends reduces to one primitive, [`UpdateField`](./update_field.md), which is @@ -187,29 +187,29 @@ legal and useless. ## Related constructs -- [`IntoBuilder`](./into_builder.md) — the other entry point, starting from a complete value. -- [`BuildField`](./build_field.md) — setting one absent field. -- [`TakeField`](./take_field.md) — the reverse, removing one present field. -- [`UpdateField`](./update_field.md) — the primitive both are built from. -- [`PartialData`](./partial_data.md) and [`FinalizeBuild`](./finalize_build.md) — naming the destination, +- [`IntoBuilder`](./into_builder.md): the other entry point, starting from a complete value. +- [`BuildField`](./build_field.md): setting one absent field. +- [`TakeField`](./take_field.md): the reverse, removing one present field. +- [`UpdateField`](./update_field.md): the primitive both are built from. +- [`PartialData`](./partial_data.md) and [`FinalizeBuild`](./finalize_build.md): naming the destination, and reaching it. -- [`CanBuildFrom`](../casting/can_build_from.md) — merging every shared field from another record. -- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the partial type and every impl +- [`CanBuildFrom`](../casting/can_build_from.md): merging every shared field from another record. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md): generates the partial type and every impl in the family. -- [`MapType`](../type-level/map_type.md) — the `IsPresent`/`IsNothing` markers presence is encoded in. -- [`HasField`](../field-access/has_field.md) — how a set field is read back off a partial value. -- [Optional fields](../optional/has_optional_builder.md) — defaulted and optional finalization. -- [`ExtractField`](../variant/extract_field.md) and [`FromVariant`](../variant/from_variant.md) — the enum counterparts. +- [`MapType`](../type-level/map_type.md): the `IsPresent`/`IsNothing` markers presence is encoded in. +- [`HasField`](../field-access/has_field.md): how a set field is read back off a partial value. +- [Optional fields](../optional/has_optional_builder.md): defaulted and optional finalization. +- [`ExtractField`](../variant/extract_field.md) and [`FromVariant`](../variant/from_variant.md): the enum counterparts. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder pattern. ## Source -- [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs) - — `HasBuilder` and `IntoBuilder` +- [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs): + `HasBuilder` and `IntoBuilder` --- diff --git a/docs/reference/traits/builder/index.md b/docs/reference/traits/builder/index.md index 441f2a7e..e298deb4 100644 --- a/docs/reference/traits/builder/index.md +++ b/docs/reference/traits/builder/index.md @@ -11,7 +11,7 @@ Assembling a struct one field at a time, with field presence tracked in the type These traits build a record incrementally, where the fields come from several independent places and the result must still be checked at compile time. The build starts from an empty *partial* value and -adds fields one by one, and each field's presence lives in the type — so finalizing an incomplete +adds fields one by one, and each field's presence lives in the type, so finalizing an incomplete record is a missing impl rather than a runtime panic. The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), which also generates the partial companion type. @@ -34,7 +34,7 @@ generic builder code knows what it is building before the build is complete. ## The ideas behind them -- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder pattern. --- diff --git a/docs/reference/traits/builder/into_builder.md b/docs/reference/traits/builder/into_builder.md index e857dd4d..be4374a0 100644 --- a/docs/reference/traits/builder/into_builder.md +++ b/docs/reference/traits/builder/into_builder.md @@ -66,7 +66,7 @@ let person = remainder .finalize_build(); // all present again ``` -Note that a value straight out of `into_builder` is already finalizable — every marker is `IsPresent`, so +Note that a value straight out of `into_builder` is already finalizable: every marker is `IsPresent`, so [`finalize_build`](./finalize_build.md) resolves immediately and the round trip is the identity. The trait earns its keep only from what happens in between. ## When to use it @@ -76,8 +76,8 @@ entry points and the one that shows up in generic code more than in application - **Use [`HasBuilder`](./has_builder.md)** when assembling a record from independent pieces. That is the common case and the one the extensible builder pattern is about. -- **Use `IntoBuilder`** when a complete value must be decomposed — to swap one field, to hand fields to - several destinations, to rebuild a record with one type changed. +- **Use `IntoBuilder`** when a complete value must be decomposed: to swap one field, to hand fields to + several destinations, or to rebuild a record with one type changed. - **Use [`ToFields`](../shape/to_fields.md)** instead when what you want is the value's *shape* as a flat list rather than a partial type you can fill. A partial value tracks presence; a `Fields` product does not. - **Prefer a struct update expression** in concrete code. `Person { first_name, ..person }` does the @@ -85,8 +85,8 @@ entry points and the one that shows up in generic code more than in application ## Under the hood -The derive generates one partial companion per record — `__Partial{Name}`, with a -[`MapType`](../type-level/map_type.md) parameter per field — and the two entry points differ only in the +The derive generates one partial companion per record (`__Partial{Name}`, with a +[`MapType`](../type-level/map_type.md) parameter per field), and the two entry points differ only in the configuration they name: ```rust @@ -100,7 +100,7 @@ impl IntoBuilder for Person { ``` `into_builder` moves each field of the concrete struct into the corresponding slot of the companion, -which under `IsPresent` holds the value itself — so the conversion is a move rather than a wrap, and +which under `IsPresent` holds the value itself, so the conversion is a move rather than a wrap, and nothing about the runtime representation changes. Because the result is at the all-present configuration, it satisfies @@ -113,13 +113,13 @@ which is exactly the pair a redistribution needs. original must survive, bearing in mind that gives you a shape rather than a builder. **The result is already finalizable.** Calling `into_builder().finalize_build()` is the identity, which -is legal and pointless — the trait earns its keep only if something happens in between. +is legal and pointless. The trait earns its keep only if something happens in between. **The partial type cannot be printed or cloned.** The derive clears the original's attributes, so a value mid-redistribution has none of the record's own derives. **It is a method, where [`HasBuilder`](./has_builder.md)'s `builder()` is an associated function.** The -asymmetry is deliberate — one starts from a value and the other from nothing — and it catches people +asymmetry is deliberate (one starts from a value and the other from nothing), and it catches people writing `Person::into_builder()`. **Taking a field out makes the value unfinalizable until it is put back.** That is the guarantee, and it @@ -128,25 +128,25 @@ dropped. ## Related constructs -- [`HasBuilder`](./has_builder.md) — the other entry point, and where the family is explained in full. -- [`TakeField`](./take_field.md) — removing a present field, which this enables. -- [`BuildField`](./build_field.md) — putting one back. -- [`FinalizeBuild`](./finalize_build.md) — returning to the concrete struct. -- [`UpdateField`](./update_field.md) — the primitive underneath both directions. -- [`PartialData`](./partial_data.md) — what names the destination type mid-build. -- [`ToFields`](../shape/to_fields.md) — the flat-shape alternative to a partial value. -- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates this impl. -- [`MapType`](../type-level/map_type.md) — the markers the configuration is written in. +- [`HasBuilder`](./has_builder.md): the other entry point, and where the family is explained in full. +- [`TakeField`](./take_field.md): removing a present field, which this enables. +- [`BuildField`](./build_field.md): putting one back. +- [`FinalizeBuild`](./finalize_build.md): returning to the concrete struct. +- [`UpdateField`](./update_field.md): the primitive underneath both directions. +- [`PartialData`](./partial_data.md): what names the destination type mid-build. +- [`ToFields`](../shape/to_fields.md): the flat-shape alternative to a partial value. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md): generates this impl. +- [`MapType`](../type-level/map_type.md): the markers the configuration is written in. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder pattern. ## Source -- [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs) - — `IntoBuilder` and `HasBuilder` +- [`has_builder.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_builder.rs): + `IntoBuilder` and `HasBuilder` --- diff --git a/docs/reference/traits/builder/partial_data.md b/docs/reference/traits/builder/partial_data.md index 0af960f0..17fefe79 100644 --- a/docs/reference/traits/builder/partial_data.md +++ b/docs/reference/traits/builder/partial_data.md @@ -21,7 +21,7 @@ where that projection comes from. The one case for bounding on it is generic cod ## Overview -A partial record is a companion type — `__PartialPerson` — and generic code holding +A partial record is a companion type (`__PartialPerson`), and generic code holding one often needs to know what it will *become* before it is complete: to name the return type of a routine, to state a bound, to decide what to do next. `PartialData` answers that: its single `Target` associated type is the concrete struct or enum the partial value corresponds to. **It is implemented for @@ -63,7 +63,7 @@ where ``` The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md) for a record and -[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) for an enum — **both** partial families +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) for an enum. **Both** partial families implement it, which is worth knowing because it is the one trait the builder and extractor sides share directly. @@ -82,7 +82,7 @@ pub trait FinalizeBuild: PartialData { type, and the destination would be unnameable until the value was complete. The same appears in [`FinalizeOptional`](../optional/finalize_optional.md), which returns -`Result` — again projecting the destination through this trait rather than +`Result`, again projecting the destination through this trait rather than declaring one of its own. ## When to use it @@ -95,7 +95,7 @@ traits otherwise. - **[`HasBuilder`](./has_builder.md)** when you have the concrete type and want a builder. That is the opposite direction: `Person::Builder` from `Person`, rather than `Target` from a partial. - **`PartialData`** when the code holds a partial value of unknown completeness and must name what it - belongs to — a signature, a `where` clause, an error message. + belongs to: a signature, a `where` clause, an error message. - **[`TransformMapFields`](../type-level/transform_map_fields.md)** requires it, which is the other place it shows up in a bound rather than as a projection. @@ -114,7 +114,7 @@ Nothing about the markers is constrained, so the destination stays available at a build. Contrast [`FinalizeBuild`](./finalize_build.md), whose impl fixes every marker to `IsPresent`. Splitting the two lets generic builder code work against a destination it can name while -still being *unable* to finalize prematurely — the type is known, the conversion is not available. A +still being *unable* to finalize prematurely: the type is known, the conversion is not available. A single trait carrying both would have to choose one or the other. The enum side implements it identically on its extraction companions, with `Target` naming the original @@ -137,27 +137,27 @@ usual confusion when meeting it in an error. ## Related constructs -- [`FinalizeBuild`](./finalize_build.md) — the subtrait that actually produces the target. -- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — the opposite direction, from +- [`FinalizeBuild`](./finalize_build.md): the subtrait that actually produces the target. +- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md): the opposite direction, from a concrete type to a partial one. -- [`UpdateField`](./update_field.md) — what moves a partial value between configurations. -- [`FinalizeOptional`](../optional/finalize_optional.md) — the optional layer's finalize, which projects `Target` +- [`UpdateField`](./update_field.md): what moves a partial value between configurations. +- [`FinalizeOptional`](../optional/finalize_optional.md): the optional layer's finalize, which projects `Target` the same way. -- [`TransformMapFields`](../type-level/transform_map_fields.md) — requires this bound. -- [`ExtractField`](../variant/extract_field.md) — the enum family whose companions also implement it. +- [`TransformMapFields`](../type-level/transform_map_fields.md): requires this bound. +- [`ExtractField`](../variant/extract_field.md): the enum family whose companions also implement it. - [`#[derive(BuildField)]`](../../derives/derive_build_field.md) and - [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generate the impls. -- [`MapType`](../type-level/map_type.md) — the markers a configuration is written in. + [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md): generate the impls. +- [`MapType`](../type-level/map_type.md): the markers a configuration is written in. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder pattern. ## Source -- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs) - — `PartialData` +- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs): + `PartialData` --- diff --git a/docs/reference/traits/builder/take_field.md b/docs/reference/traits/builder/take_field.md index dae74232..1db8f03c 100644 --- a/docs/reference/traits/builder/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -18,9 +18,9 @@ It pins the `IsPresent → IsNothing` transition of the [`UpdateField`](./update because it *requires* the starting marker to be `IsPresent`, **taking a field that is absent is a compile error** rather than an `Option` you have to handle. -Two things reach for it. Redistributing a record — [`into_builder`](./into_builder.md), take fields out, -put them somewhere else — and, far more often, [`CanBuildFrom`](../casting/can_build_from.md), whose merge -recursion takes each field out of the source and builds it into the target. +Two uses reach for it. One is redistributing a record: [`into_builder`](./into_builder.md), take fields +out, put them somewhere else. The other, far more often, is [`CanBuildFrom`](../casting/can_build_from.md), +whose merge recursion takes each field out of the source and builds it into the target. ## Definition @@ -43,7 +43,7 @@ that supplies this is shown in [Under the hood](#under-the-hood). ## Usage -**It is not in the prelude** — the one member of the core builder family that is not. Import it from +**It is not in the prelude**, the one member of the core builder family that is not. Import it from `cgp::core::field::traits` when you call `take_field` directly: ```rust @@ -80,8 +80,8 @@ taken out and not replaced cannot be forgotten silently. ## When to use it -**Reach for it when a complete value must be decomposed**, and remember that the common case — -merging one record into another — already uses it for you. +**Reach for it when a complete value must be decomposed**, and remember that the common case, +merging one record into another, already uses it for you. - **Use [`CanBuildFrom`](../casting/can_build_from.md)** to move every shared field from one record into another's builder. It is this trait applied in a loop, written once. @@ -104,7 +104,7 @@ merging one record into another — already uses it for you. // where Partial: UpdateField ``` -The target marker is `IsNothing` and the constraint on the reported source marker is `IsPresent` — both +The target marker is `IsNothing` and the constraint on the reported source marker is `IsPresent`, both swapped relative to `BuildField`. Since `Mapper` is an *output* of the primitive, constraining it selects only those partial types whose field is currently set. @@ -114,7 +114,7 @@ value back. **Its heaviest user is [`CanBuildFrom`](../casting/can_build_from.md).** That recursion walks the source's field list, taking each field out with `take_field` and writing it into the target with -[`build_field`](./build_field.md), threading the shrinking source and the growing target through — which +[`build_field`](./build_field.md), threading the shrinking source and the growing target through, which is why a merge needs [`HasFields`](../shape/has_fields.md) on the source as well as a builder. ## Common Mistakes @@ -139,26 +139,26 @@ variable. ## Related constructs -- [`BuildField`](./build_field.md) — the opposite direction. -- [`UpdateField`](./update_field.md) — the primitive both are built from. -- [`IntoBuilder`](./into_builder.md) — how a complete value becomes a partial one to take from. -- [`CanBuildFrom`](../casting/can_build_from.md) — the merge that uses this internally. -- [`FinalizeBuild`](./finalize_build.md) — what a remainder cannot satisfy until the field is restored. -- [`HasBuilder`](./has_builder.md) — the family's entry point. -- [`MapType`](../type-level/map_type.md) — the `IsPresent`/`IsNothing` markers this moves between. -- [`ToFields`](../shape/to_fields.md) — the flat-shape alternative to decomposing a partial value. -- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the `UpdateField` impls behind +- [`BuildField`](./build_field.md): the opposite direction. +- [`UpdateField`](./update_field.md): the primitive both are built from. +- [`IntoBuilder`](./into_builder.md): how a complete value becomes a partial one to take from. +- [`CanBuildFrom`](../casting/can_build_from.md): the merge that uses this internally. +- [`FinalizeBuild`](./finalize_build.md): what a remainder cannot satisfy until the field is restored. +- [`HasBuilder`](./has_builder.md): the family's entry point. +- [`MapType`](../type-level/map_type.md): the `IsPresent`/`IsNothing` markers this moves between. +- [`ToFields`](../shape/to_fields.md): the flat-shape alternative to decomposing a partial value. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md): generates the `UpdateField` impls behind it. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder pattern. ## Source -- [`take_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/take_field.rs) - — `TakeField` +- [`take_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/take_field.rs): + `TakeField` --- diff --git a/docs/reference/traits/builder/update_field.md b/docs/reference/traits/builder/update_field.md index b2696029..dd33d03a 100644 --- a/docs/reference/traits/builder/update_field.md +++ b/docs/reference/traits/builder/update_field.md @@ -80,7 +80,7 @@ let partial = Person::builder() .build_field(PhantomData::, "Alice".to_owned()); ``` -Naming `UpdateField` yourself is for a transition neither direction covers — which in practice means one +Naming `UpdateField` yourself is for a transition neither direction covers, which in practice means one involving `IsOptional`: ```rust @@ -91,7 +91,7 @@ let (previous, builder) = builder.update_field( ); ``` -Because both markers are `IsOptional` here, `Output` is the same type as `Self` — which is exactly what +Because both markers are `IsOptional` here, `Output` is the same type as `Self`, which is exactly what lets an optional field be set repeatedly, unlike the core `build_field` that consumes an absent slot once. ## When to use it @@ -102,7 +102,7 @@ call site. - **[`BuildField`](./build_field.md)** for `IsNothing → IsPresent`, which is setting a field. - **[`TakeField`](./take_field.md)** for `IsPresent → IsNothing`, which is removing one. -- **`UpdateField`** for anything else — a transition to or from `IsOptional`, which the +- **`UpdateField`** for anything else: a transition to or from `IsOptional`, which the [optional-field extensions](../optional/set_optional.md) do, or a transform's intermediate steps. - **[`TransformMapFields`](../type-level/transform_map_fields.md)** when *every* field changes state rather than one. It calls this twice per field internally, and reaching for `UpdateField` in a loop is re-implementing @@ -131,7 +131,7 @@ other fields' states. Because `Mapper` is an *output* rather than an input, the two directional traits can pin a transition by constraining it. [`BuildField`](./build_field.md) is a blanket impl over `UpdateField` and [`TakeField`](./take_field.md) over -`UpdateField` — same primitive, opposite constraints. +`UpdateField`: same primitive, opposite constraints. Nothing here changes a value's runtime layout beyond moving it in or out of the slot; the markers are zero-sized and the wrapping is a type-level fiction. @@ -158,27 +158,27 @@ with the tag fully expanded rather than saying the field does not exist. ## Related constructs -- [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) — the two directions, as blanket +- [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md): the two directions, as blanket impls over this. -- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md) — where a partial value comes +- [`HasBuilder`](./has_builder.md) and [`IntoBuilder`](./into_builder.md): where a partial value comes from. -- [`FinalizeBuild`](./finalize_build.md) — where one ends up. -- [`MapType`](../type-level/map_type.md) — the markers a field moves between. -- [`TransformMapFields`](../type-level/transform_map_fields.md) — the whole-record form, which calls this twice per +- [`FinalizeBuild`](./finalize_build.md): where one ends up. +- [`MapType`](../type-level/map_type.md): the markers a field moves between. +- [`TransformMapFields`](../type-level/transform_map_fields.md): the whole-record form, which calls this twice per field. -- [`SetOptional`](../optional/set_optional.md) — a transition this covers and the directional traits do not. -- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the per-field impls. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that name a field. +- [`SetOptional`](../optional/set_optional.md): a transition this covers and the directional traits do not. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md): generates the per-field impls. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that name a field. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder pattern. ## Source -- [`update_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/update_field.rs) - — `UpdateField` +- [`update_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/update_field.rs): + `UpdateField` --- diff --git a/docs/reference/traits/casting/can_build_from.md b/docs/reference/traits/casting/can_build_from.md index 588e28cc..8ac1aacf 100644 --- a/docs/reference/traits/casting/can_build_from.md +++ b/docs/reference/traits/casting/can_build_from.md @@ -9,7 +9,7 @@ Filling a builder with every field it shares with another record. ## Overview -Assembling one struct out of several smaller ones means copying each shared field across by hand — a +Assembling one struct out of several smaller ones means copying each shared field across by hand: a line per field, repeated for every pair of types. `CanBuildFrom` derives that copying from the field names instead. @@ -123,7 +123,7 @@ an unsatisfied `HasFields` bound on the source type. is a builder you still have to [finalize](../builder/finalize_build.md). **Field names are the whole interface.** Renaming a field in one struct silently stops it being copied, -and the failure surfaces at `finalize_build` — a missing-method error — rather than at the rename. +and the failure surfaces at `finalize_build`, as a missing-method error, rather than at the rename. **A field the target lacks is not an error and not copied.** The walk matches on the target's slots, so an extra field on the source is simply dropped. @@ -132,23 +132,23 @@ an extra field on the source is simply dropped. ## Related constructs -- [`HasBuilder`](../builder/has_builder.md) — where a builder comes from, and the family this belongs to. -- [`BuildField`](../builder/build_field.md) and [`TakeField`](../builder/take_field.md) — the two primitives the recursion +- [`HasBuilder`](../builder/has_builder.md): where a builder comes from, and the family this belongs to. +- [`BuildField`](../builder/build_field.md) and [`TakeField`](../builder/take_field.md): the two primitives the recursion routes through. -- [`FinalizeBuild`](../builder/finalize_build.md) — how the resulting builder becomes a struct. -- [`HasFields`](../shape/has_fields.md) — the shape the walk reads, and what the source must derive. -- [`CanBuildWithDefault`](../optional/can_build_with_default.md) — merge plus a defaulted finalize, in one call. -- [`CanUpcast`](./can_upcast.md) — the enum counterpart. -- [`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md) — what makes a struct eligible. +- [`FinalizeBuild`](../builder/finalize_build.md): how the resulting builder becomes a struct. +- [`HasFields`](../shape/has_fields.md): the shape the walk reads, and what the source must derive. +- [`CanBuildWithDefault`](../optional/can_build_with_default.md): merge plus a defaulted finalize, in one call. +- [`CanUpcast`](./can_upcast.md): the enum counterpart. +- [`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md): what makes a struct eligible. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — merging records through a builder. +- [Extensible records](/docs/concepts/extensible-records): merging records through a builder. ## Source -- [`build_from.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/build_from.rs) - — `CanBuildFrom` and its `FieldsBuilder` recursion +- [`build_from.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/build_from.rs): + `CanBuildFrom` and its `FieldsBuilder` recursion --- diff --git a/docs/reference/traits/casting/can_downcast.md b/docs/reference/traits/casting/can_downcast.md index 449d3450..8aa481da 100644 --- a/docs/reference/traits/casting/can_downcast.md +++ b/docs/reference/traits/casting/can_downcast.md @@ -119,7 +119,7 @@ chaining possible: the `Remainder` a `downcast` returns is precisely a `downcast attempt and wrong if you meant to try another target. **A remainder carries none of the enum's attributes**, so a `Result` is neither -`Debug` nor `PartialEq` — comparing one whole does not compile. Reach for `.ok()`, `.is_ok()`, or a +`Debug` nor `PartialEq`, and comparing one whole does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. **Names and payload types must match exactly**, and a mismatch is a compile error rather than a runtime @@ -130,23 +130,23 @@ stored where the original was. ## Related constructs -- [`CanDowncastFields`](./can_downcast_fields.md) — the continuation, called on each remainder. -- [`CanUpcast`](./can_upcast.md) — the widening direction, which cannot fail. -- [`CanBuildFrom`](./can_build_from.md) — the record counterpart of casting. -- [`ExtractField`](../variant/extract_field.md) — the primitive each attempt uses, and the family that narrows the +- [`CanDowncastFields`](./can_downcast_fields.md): the continuation, called on each remainder. +- [`CanUpcast`](./can_upcast.md): the widening direction, which cannot fail. +- [`CanBuildFrom`](./can_build_from.md): the record counterpart of casting. +- [`ExtractField`](../variant/extract_field.md): the primitive each attempt uses, and the family that narrows the same way to a payload. -- [`HasExtractor`](../variant/has_extractor.md) — where the walk starts. -- [`FromVariant`](../variant/from_variant.md) — how a matched variant is rebuilt into the target. -- [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) — what makes an enum eligible. -- [Type-level lists](../../types/index.md) — the `Either`/`Void` chain underneath. +- [`HasExtractor`](../variant/has_extractor.md): where the walk starts. +- [`FromVariant`](../variant/from_variant.md): how a matched variant is rebuilt into the target. +- [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md): what makes an enum eligible. +- [Type-level lists](../../types/index.md): the `Either`/`Void` chain underneath. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — upcasting and downcasting between enums. +- [Extensible variants](/docs/concepts/extensible-variants): upcasting and downcasting between enums. ## Source -- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs) — +- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs): `CanDowncast` and the `FieldsExtractor` recursion --- diff --git a/docs/reference/traits/casting/can_downcast_fields.md b/docs/reference/traits/casting/can_downcast_fields.md index 4c08d07b..a5cbd62a 100644 --- a/docs/reference/traits/casting/can_downcast_fields.md +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -84,8 +84,8 @@ match value.downcast(PhantomData::) { } ``` -The first call starts the chain and the second continues it. Written the other way round — a second -`downcast` on the remainder — it does not compile, because a remainder is not an enum. +The first call starts the chain and the second continues it. Written the other way round, with a second +`downcast` on the remainder, it does not compile, because a remainder is not an enum. ## When to use it @@ -109,7 +109,7 @@ remainder as `Err`. The only difference is the entry point: `CanDowncast` calls handed. Because the remainder type narrows at every step, a chain's types are all distinct, and the compiler -knows at each point exactly which variants remain — the same narrowing a hand-written +knows at each point exactly which variants remain, the same narrowing a hand-written [extraction chain](../variant/extract_field.md) performs. ## Common Mistakes @@ -130,20 +130,20 @@ attempt needs. ## Related constructs -- [`CanDowncast`](./can_downcast.md) — the first step, and where the pair is explained in full. -- [`CanUpcast`](./can_upcast.md) — the widening direction. -- [`ExtractField`](../variant/extract_field.md) — narrowing to a payload rather than to another enum. -- [`FinalizeExtract`](../variant/finalize_extract.md) — how an exhausted remainder is discharged. -- [`HasExtractor`](../variant/has_extractor.md) — what turns an enum into the extractor this operates on. -- [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) — what makes an enum eligible. +- [`CanDowncast`](./can_downcast.md): the first step, and where the pair is explained in full. +- [`CanUpcast`](./can_upcast.md): the widening direction. +- [`ExtractField`](../variant/extract_field.md): narrowing to a payload rather than to another enum. +- [`FinalizeExtract`](../variant/finalize_extract.md): how an exhausted remainder is discharged. +- [`HasExtractor`](../variant/has_extractor.md): what turns an enum into the extractor this operates on. +- [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md): what makes an enum eligible. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — partial variants and the narrowing chain. +- [Extensible variants](/docs/concepts/extensible-variants): partial variants and the narrowing chain. ## Source -- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs) — +- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs): `CanDowncastFields` and the `FieldsExtractor` recursion --- diff --git a/docs/reference/traits/casting/can_upcast.md b/docs/reference/traits/casting/can_upcast.md index 9758820b..b3aab02d 100644 --- a/docs/reference/traits/casting/can_upcast.md +++ b/docs/reference/traits/casting/can_upcast.md @@ -9,12 +9,12 @@ Widening a narrow enum into a wider one that shares its variants. ## Overview -Two enums defined independently can share variant names — a small `FooBar` and a larger `FooBarBaz`, -say. Converting the narrow one into the wide one is a conversion you could write by hand, and it is +Two enums defined independently can share variant names, say a small `FooBar` and a larger `FooBarBaz`. +Converting the narrow one into the wide one is a conversion you could write by hand, and it is pure boilerplate: one `match` arm per variant, rewrapping each payload under the same name. `CanUpcast` derives that conversion from the names instead. Once both enums expose their shape as a -type-level list — which [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) makes them — widening is a +type-level list, which [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) makes them, widening is a matter of routing each source variant to the target's slot of the same name. **It always succeeds.** Every variant of the source has a home in the target, or the conversion does not @@ -90,7 +90,7 @@ name only the variants you need, and let the widening be checked. type, and generates nothing. - **Reach for [`CanDowncast`](./can_downcast.md)** for the other direction, which can fail and therefore reads quite differently. -- **Reach for [`CanBuildFrom`](./can_build_from.md)** for the record analogue — merging a struct's fields +- **Reach for [`CanBuildFrom`](./can_build_from.md)** for the record analogue: merging a struct's fields into another struct's builder. One boundary worth stating: this is **compile-time, name-driven, and opt-in**. Both enums must derive @@ -131,24 +131,24 @@ value type are both part of the entry. ## Related constructs -- [`CanDowncast`](./can_downcast.md) — the narrowing direction, which can fail. -- [`CanDowncastFields`](./can_downcast_fields.md) — narrowing continued on a remainder. -- [`CanBuildFrom`](./can_build_from.md) — the record counterpart. +- [`CanDowncast`](./can_downcast.md): the narrowing direction, which can fail. +- [`CanDowncastFields`](./can_downcast_fields.md): narrowing continued on a remainder. +- [`CanBuildFrom`](./can_build_from.md): the record counterpart. - [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) and - [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) — what makes an enum eligible. -- [`ExtractField`](../variant/extract_field.md) and [`FromVariant`](../variant/from_variant.md) — the two primitives the + [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md): what makes an enum eligible. +- [`ExtractField`](../variant/extract_field.md) and [`FromVariant`](../variant/from_variant.md): the two primitives the recursion routes through. -- [`HasFields`](../shape/has_fields.md) — the variant shape being walked. -- [Type-level lists](../../types/index.md) — the `Either`/`Void` chain underneath. -- [Dispatch combinators](../../providers/dispatch/index.md) — where casting meets per-variant routing. +- [`HasFields`](../shape/has_fields.md): the variant shape being walked. +- [Type-level lists](../../types/index.md): the `Either`/`Void` chain underneath. +- [Dispatch combinators](../../providers/dispatch/index.md): where casting meets per-variant routing. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — upcasting and downcasting between enums. +- [Extensible variants](/docs/concepts/extensible-variants): upcasting and downcasting between enums. ## Source -- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs) — +- [`cast.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/cast.rs): `CanUpcast` and the `FieldsExtractor` recursion --- diff --git a/docs/reference/traits/casting/index.md b/docs/reference/traits/casting/index.md index 8813082e..eafa6cba 100644 --- a/docs/reference/traits/casting/index.md +++ b/docs/reference/traits/casting/index.md @@ -13,10 +13,10 @@ Two types that share a subset of named fields or variants can convert into one a without a hand-written `From` or `TryFrom`. Because CGP represents each record as a product of named fields and each enum as a sum of named variants, a conversion becomes a matter of routing each named entry to the target's slot of the same name. Both types must derive the extensible-data machinery, and -the names are matched at the type level. None of these traits is in the prelude — import each from +the names are matched at the type level. None of these traits is in the prelude. Import each from `cgp::core::field::impls`. -The four cover the directions that routing can take. +These traits cover the directions that routing can take. For **enums**, [`CanUpcast`](can_upcast.md) widens a value into an enum whose variants are a superset, which always succeeds, and [`CanDowncast`](can_downcast.md) narrows into a smaller enum, which can fail @@ -28,8 +28,8 @@ another record, so several sources can be merged into one target before it is fi ## The ideas behind them -- [Extensible variants](/docs/concepts/extensible-variants) — upcasting and downcasting between enums. -- [Extensible records](/docs/concepts/extensible-records) — merging records through a builder. +- [Extensible variants](/docs/concepts/extensible-variants): upcasting and downcasting between enums. +- [Extensible records](/docs/concepts/extensible-records): merging records through a builder. --- diff --git a/docs/reference/traits/field-access/field_getter.md b/docs/reference/traits/field-access/field_getter.md index 2bc467bd..92c19ccd 100644 --- a/docs/reference/traits/field-access/field_getter.md +++ b/docs/reference/traits/field-access/field_getter.md @@ -5,7 +5,7 @@ sidebar_position: 3 # `FieldGetter` -The provider-side mirror of `HasField` — field access that gets wired. +The provider-side mirror of `HasField`: field access that gets wired. :::info @@ -65,8 +65,8 @@ delegate_components! { ``` Reading it back: the getter component is answered by [`UseField`](../../providers/use_field.md), which -implements `FieldGetter` by reading the `first_name` field — a field whose name need not match the -getter's method name, which is the whole point of wiring the access rather than deriving it. +implements `FieldGetter` by reading the `first_name` field, whose name need not match the getter's method +name. That is the whole point of wiring the access rather than deriving it. Writing a `FieldGetter` impl by hand is the escape hatch for a getter whose value is computed rather than stored, and it is an ordinary trait impl on a marker type of your own. @@ -168,28 +168,28 @@ getter's own name**, since that impl keys on the tag it is given. ## Related constructs -- [`HasField`](./has_field.md) — the consumer side you bound against. -- [`MutFieldGetter`](./mut_field_getter.md) — the mutable extension of this trait. -- [`FieldMapper`](./field_mapper.md) — the lifetime-safe form, for nested access. -- [`UseField`](../../providers/use_field.md) — the provider that implements it by reading a named field. -- [`UseContext`](../../providers/use_context.md) — the provider that routes back through the context's own +- [`HasField`](./has_field.md): the consumer side you bound against. +- [`MutFieldGetter`](./mut_field_getter.md): the mutable extension of this trait. +- [`FieldMapper`](./field_mapper.md): the lifetime-safe form, for nested access. +- [`UseField`](../../providers/use_field.md): the provider that implements it by reading a named field. +- [`UseContext`](../../providers/use_context.md): the provider that routes back through the context's own fields. -- [`#[cgp_getter]`](../../macros/cgp_getter.md) — the macro that makes a getter a full component. -- [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) — the simpler getter, keyed by method name. -- [`ChainGetters`](../../providers/chain_getters.md) — composing getters to reach a nested field. -- [`MRef`](../../types/mref.md) — the owned-or-borrowed return type for a getter that may produce its value. +- [`#[cgp_getter]`](../../macros/cgp_getter.md): the macro that makes a getter a full component. +- [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md): the simpler getter, keyed by method name. +- [`ChainGetters`](../../providers/chain_getters.md): composing getters to reach a nested field. +- [`MRef`](../../types/mref.md): the owned-or-borrowed return type for a getter that may produce its value. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the duality this trait is +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the duality this trait is the field-access instance of. ## Source -- [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) - — `FieldGetter` and the `UseContext` impl -- [`use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs) - — the `UseField` provider +- [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs): + `FieldGetter` and the `UseContext` impl +- [`use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs): + the `UseField` provider --- diff --git a/docs/reference/traits/field-access/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md index f8dcda8e..0fe66add 100644 --- a/docs/reference/traits/field-access/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -120,8 +120,8 @@ let name = >::map_field( - **Use [`ChainGetters`](../../providers/chain_getters.md)** to reach a field on a nested context by wiring. - **Use [`FieldGetter`](./field_getter.md)** when the wired access is a plain one-level read. -- **Use [`MapField`](./map_field.md)** when the descent happens on `self` rather than on a wired context - — the consumer-side twin. +- **Use [`MapField`](./map_field.md)** when the descent happens on `self` rather than on a wired context: + the consumer-side twin. - **Use an [`#[implicit]`](../../attributes/implicit.md) argument** before any of them for a field of the implementation's own context. @@ -133,9 +133,9 @@ whether composing the existing ones does the job. `FieldMapper` is a blanket impl over every [`FieldGetter`](./field_getter.md), with two `'static` bounds that its consumer-side twin needs only one of: -- the **tag** must be `'static`, which is free — a [`Symbol!`](../../macros/symbol.md) or an +- the **tag** must be `'static`, which is free, since a [`Symbol!`](../../macros/symbol.md) or an [`Index`](../../types/index_type.md) is `'static` by construction; -- the **getter** — that is, `Self`, the provider — must be `'static`, which is also free, since a +- the **getter**, that is, `Self`, the provider, must be `'static`, which is also free, since a provider is a zero-sized marker type with no lifetime parameters in the ordinary case. The field's *value* stays free of any bound, which is the whole point: it is the intermediate whose @@ -165,25 +165,25 @@ failure when it happens. ## Related constructs -- [`MapField`](./map_field.md) — the consumer-side twin, and where the lifetime problem is explained in +- [`MapField`](./map_field.md): the consumer-side twin, and where the lifetime problem is explained in full. -- [`FieldGetter`](./field_getter.md) — the supertrait, and the plain wired read. -- [`ChainGetters`](../../providers/chain_getters.md) — the provider that uses this to descend. -- [`HasField`](./has_field.md) — the consumer side of field access. -- [`UseField`](../../providers/use_field.md) and [`UseContext`](../../providers/use_context.md) — the two +- [`FieldGetter`](./field_getter.md): the supertrait, and the plain wired read. +- [`ChainGetters`](../../providers/chain_getters.md): the provider that uses this to descend. +- [`HasField`](./has_field.md): the consumer side of field access. +- [`UseField`](../../providers/use_field.md) and [`UseContext`](../../providers/use_context.md): the two providers a chain is usually built from. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags, `'static` by construction. -- [`MRef`](../../types/mref.md) — the return type for a getter that may produce rather than lend. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags, `'static` by construction. +- [`MRef`](../../types/mref.md): the return type for a getter that may produce rather than lend. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the duality this trait is +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the duality this trait is an instance of. ## Source -- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs) - — `FieldMapper` and `MapField` +- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs): + `FieldMapper` and `MapField` --- diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index 62f73b28..de4d27f8 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -9,8 +9,8 @@ Reading a field by a type-level name, from a context you cannot name. ## Overview -An implementation written against a **context** — the type the capability runs against, which supplies -the values it needs as its fields — is generic over that context and cannot name its concrete type. So it +An implementation written against a **context**, the type the capability runs against, which supplies +the values it needs as its fields, is generic over that context and cannot name its concrete type. So it cannot write `self.name`. Yet reading a value out of the context is the commonest thing such an implementation does. @@ -21,7 +21,7 @@ an ordinary trait bound: Self: HasField ``` -Any context with a matching field satisfies that bound. Nothing is compared by string at run time — +Any context with a matching field satisfies that bound. Nothing is compared by string at run time. [`Symbol!("name")`](../../macros/symbol.md) is a type, so the compiler resolves which field is meant and the read compiles to a direct field access. @@ -45,7 +45,7 @@ pub trait HasField { `Tag` is a type-level name: [`Symbol!("field_name")`](../../macros/symbol.md) for a named field, [`Index`](../../types/index_type.md) for a tuple field. `Value` is the field's type, exposed as an associated -type so a bound can pin it or leave it open — `HasField` accepts a field of any type, +type so a bound can pin it or leave it open: `HasField` accepts a field of any type, while `HasField` requires a `String`. `get_field` takes `&self` and returns `&Self::Value`, a borrow of the field; its `PhantomData` argument carries no data and only lets a call site say *which* field it means when several `HasField` impls are in scope, which is why a @@ -98,7 +98,7 @@ delegate_components! { ``` `Person` derives the access, so it satisfies exactly the bound `GreetHello` requires and the wiring -compiles. **Value context, self-targeted** — the wired type is the data the capability runs against. +compiles. **Value context, self-targeted**: the wired type is the data the capability runs against. **Written idiomatically, none of that bound is visible.** The same read is an [`#[implicit]`](../../attributes/implicit.md) argument: @@ -134,14 +134,14 @@ ordering is settled and worth following. case, including a field several implementations each read. - **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a *named* capability, when the field lives on a type other than the context, or when the getter should carry a type inferred - from the field — the three cases an implicit argument cannot reach. + from the field. An implicit argument cannot reach those cases. - **Use [`#[cgp_getter]`](../../macros/cgp_getter.md) with [`UseField`](../../providers/use_field.md)** only when a context needs to choose *which* field the getter reads. That is the advanced case and costs a wiring line per context. -- **Write the bound by hand** when none of those fit — a bound on a type that is not `Self`, say. It is an - ordinary trait bound. +- **Write the bound by hand** when none of those fit, such as a bound on a type that is not `Self`. It is + an ordinary trait bound. -Three neighbours are easy to confuse with it. [`HasFields`](../shape/has_fields.md) — plural — is the +Three neighbours are easy to confuse with it. [`HasFields`](../shape/has_fields.md), the plural, is the whole-shape view, for code that must process *every* field rather than one named one; the two are complementary and often derived together. [`HasFieldMut`](./has_field_mut.md) is the same access with mutation, not an alternative. And [`FieldGetter`](./field_getter.md) is not an alternative either but the @@ -202,29 +202,29 @@ parameter is owned. ## Related constructs -- [`#[derive(HasField)]`](../../derives/derive_has_field.md) — generates the per-field impls; what a context +- [`#[derive(HasField)]`](../../derives/derive_has_field.md): generates the per-field impls; what a context writes. -- [`HasFieldMut`](./has_field_mut.md) — the mutable extension. -- [`FieldGetter`](./field_getter.md) — the provider-side mirror that gets wired. -- [`MapField`](./map_field.md) — the lifetime-safe form for reaching into a nested value. -- [`HasFields`](../shape/has_fields.md) — the plural, whole-shape counterpart. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that key a field. -- [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to read a field. -- [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../../macros/cgp_getter.md) — +- [`HasFieldMut`](./has_field_mut.md): the mutable extension. +- [`FieldGetter`](./field_getter.md): the provider-side mirror that gets wired. +- [`MapField`](./map_field.md): the lifetime-safe form for reaching into a nested value. +- [`HasFields`](../shape/has_fields.md): the plural, whole-shape counterpart. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that key a field. +- [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to read a field. +- [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../../macros/cgp_getter.md): getter traits over the same access. -- [`UseField`](../../providers/use_field.md) — the provider-side implementation of `FieldGetter`. -- [`HasBuilder`](../builder/has_builder.md) — where `HasField` reappears on a partial record, gated on presence. +- [`UseField`](../../providers/use_field.md): the provider-side implementation of `FieldGetter`. +- [`HasBuilder`](../builder/has_builder.md): where `HasField` reappears on a partial record, gated on presence. The ideas behind it: -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): why a field requirement belongs on the implementation rather than the interface. -- [Implicit arguments](/docs/concepts/implicit-arguments) — the ergonomic surface built on this trait. +- [Implicit arguments](/docs/concepts/implicit-arguments): the ergonomic surface built on this trait. ## Source -- [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) - — `HasField`, `FieldGetter`, the `Deref` forwarding, and the `UseContext` impl +- [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs): + `HasField`, `FieldGetter`, the `Deref` forwarding, and the `UseContext` impl --- diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index d7bf00ae..3a94b964 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -88,7 +88,7 @@ delegate_components! { } ``` -**Environmental context, self-targeted** — `App` stands for the application and carries the wiring. +**Environmental context, self-targeted**: `App` stands for the application and carries the wiring. Mutable access passes through a smart pointer too, via a `DerefMut` forwarding impl, so a `Box` resolves the write to the inner struct. @@ -96,8 +96,8 @@ Mutable access passes through a smart pointer too, via a `DerefMut` forwarding i ## When to use it **Bound on it only when the implementation genuinely writes**, and prefer the read-only bound otherwise. -Requiring mutation where none happens narrows what a caller can pass for no benefit — a context behind a -shared reference satisfies [`HasField`](./has_field.md) and not this. +Requiring mutation where none happens narrows what a caller can pass for no benefit. A context behind a +shared reference satisfies [`HasField`](./has_field.md) but not this. - **Use [`HasField`](./has_field.md)** whenever the value is only read. This is the overwhelmingly common case. @@ -106,7 +106,7 @@ shared reference satisfies [`HasField`](./has_field.md) and not this. too, under the access rules on that page, which is the idiomatic route before reaching for this trait by hand. - **Reach for [`MutFieldGetter`](./mut_field_getter.md)** when the mutation must be *wired* rather than - bounded — the provider-side mirror of this trait. + bounded: the provider-side mirror of this trait. - **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable and threads state through handler outputs instead, which composes better with the [handler family](../../components/handler/handler.md). @@ -137,29 +137,29 @@ the lifetime rather than the field. **Bounding on it implies the read.** `Self: HasFieldMut` already gives `get_field`, so adding `HasField` alongside is redundant. -**`Value` lives on the supertrait.** Pin it as `HasFieldMut` — the associated +**`Value` lives on the supertrait.** Pin it as `HasFieldMut`. The associated type is inherited, not redeclared. **A tuple field is keyed by [`Index`](../../types/index_type.md)**, exactly as for the immutable form. ## Related constructs -- [`HasField`](./has_field.md) — the supertrait, and where the tag-keyed access is explained in full. -- [`MutFieldGetter`](./mut_field_getter.md) — the provider-side mirror of this trait. -- [`#[derive(HasField)]`](../../derives/derive_has_field.md) — generates both impls per field. -- [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to reach a field, including mutably. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that key a field. -- [`UseField`](../../providers/use_field.md) — the provider that implements the wired form. +- [`HasField`](./has_field.md): the supertrait, and where the tag-keyed access is explained in full. +- [`MutFieldGetter`](./mut_field_getter.md): the provider-side mirror of this trait. +- [`#[derive(HasField)]`](../../derives/derive_has_field.md): generates both impls per field. +- [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to reach a field, including mutably. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that key a field. +- [`UseField`](../../providers/use_field.md): the provider that implements the wired form. The ideas behind it: -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): why a field requirement belongs on the implementation rather than the interface. ## Source -- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs) - — `HasFieldMut`, `MutFieldGetter`, and the `DerefMut` forwarding +- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs): + `HasFieldMut`, `MutFieldGetter`, and the `DerefMut` forwarding --- diff --git a/docs/reference/traits/field-access/index.md b/docs/reference/traits/field-access/index.md index b784ec72..e48457b8 100644 --- a/docs/reference/traits/field-access/index.md +++ b/docs/reference/traits/field-access/index.md @@ -9,14 +9,14 @@ Reading one field of a context by its type-level name, from code that cannot nam ## Overview -The most common thing a CGP implementation does is read a value out of its **context** — the type a -capability runs against — without naming that type. It reads the field by keying on the field's *name -as a type*, so any context with a matching field satisfies the bound. These traits are the foundation +A CGP implementation most often reads a value out of its **context**, the type a capability runs against, +without naming that type. It reads the field by keying on the field's *name as a type*, so any context +with a matching field satisfies the bound. These traits are the foundation the ergonomic surface stands on: an [`#[implicit]`](../../attributes/implicit.md) argument, a [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) method, and a [`UseField`](../../providers/use_field.md) wiring entry all generate a bound on the traits here. -The six traits divide on two axes: read versus write, and consumer-side versus provider-side. +The traits divide on two axes: read versus write, and consumer-side versus provider-side. The **consumer traits** are what an implementation bounds against on its own context. [`HasField`](has_field.md) reads a field, and [`HasFieldMut`](has_field_mut.md) adds mutable access. @@ -32,9 +32,9 @@ nested context. ## The ideas behind them -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): why a field requirement belongs on the implementation rather than the interface. -- [Implicit arguments](/docs/concepts/implicit-arguments) — the ergonomic surface built on these traits. +- [Implicit arguments](/docs/concepts/implicit-arguments): the ergonomic surface built on these traits. --- diff --git a/docs/reference/traits/field-access/map_field.md b/docs/reference/traits/field-access/map_field.md index 25d309f0..0001f12e 100644 --- a/docs/reference/traits/field-access/map_field.md +++ b/docs/reference/traits/field-access/map_field.md @@ -20,8 +20,8 @@ which is why reaching a nested field is a provider rather than two chained reads ## Overview -Chaining field reads looks like it should just work — read a field, then read a field of *that* — -and it does not, for a reason that is about lifetimes rather than about CGP. Writing +Chaining field reads looks like it should just work: read a field, then read a field of *that*. It does +not, and the reason is about lifetimes rather than about CGP. Writing `context.get_field(..).get_field(..)` makes the intermediate `Value` outlive the borrow it came from, which the compiler can only accept by requiring it to be `'static`. @@ -53,7 +53,7 @@ demanding `'static`. ## Usage -**It is not in the prelude** — one of only two members of the `HasField` group that are not. Import it +**It is not in the prelude**, one of only two members of the `HasField` group that are not. Import it from `cgp::core::field::traits`: ```rust @@ -124,8 +124,8 @@ site what the wiring could have decided. - **Reach for [`FieldMapper`](./field_mapper.md)** when the same descent must happen on the provider side, where the context is a type argument rather than `self`. -Call `map_field` directly only when you are writing machinery of the same kind — a new getter provider, -say — and even then the existing ones usually compose. +Call `map_field` directly only when you are writing machinery of the same kind, such as a new getter +provider, and even then the existing ones usually compose. ## Under the hood @@ -163,30 +163,30 @@ in scope does not satisfy the binder, which is the safety the design buys. **It cannot map to an owned value.** The signature returns `&T`. A getter that must produce a value uses [`MRef`](../../types/mref.md) instead. -**`MapField` is not [`MapFields`](../type-level/map_fields.md) and not [`MapType`](../type-level/map_type.md).** Three similar -names: this one is a lifetime helper for reading a nested field, `MapFields` applies a marker across a -type-level list, and `MapType` names one field's storage on a partial type. +**`MapField` is not [`MapFields`](../type-level/map_fields.md) and not [`MapType`](../type-level/map_type.md).** The names +are similar: this one is a lifetime helper for reading a nested field, `MapFields` applies a marker across +a type-level list, and `MapType` names one field's storage on a partial type. ## Related constructs -- [`FieldMapper`](./field_mapper.md) — the provider-side mirror of this trait. -- [`HasField`](./has_field.md) — the supertrait, and the plain read. -- [`ChainGetters`](../../providers/chain_getters.md) — the provider that uses `map_field` to descend. -- [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to read a field of the context itself. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags, which are `'static` by +- [`FieldMapper`](./field_mapper.md): the provider-side mirror of this trait. +- [`HasField`](./has_field.md): the supertrait, and the plain read. +- [`ChainGetters`](../../providers/chain_getters.md): the provider that uses `map_field` to descend. +- [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to read a field of the context itself. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags, which are `'static` by construction. -- [`MRef`](../../types/mref.md) — the return type for a getter that may produce rather than lend. -- [`MapFields`](../type-level/map_fields.md) and [`MapType`](../type-level/map_type.md) — the two similarly-named traits that do +- [`MRef`](../../types/mref.md): the return type for a getter that may produce rather than lend. +- [`MapFields`](../type-level/map_fields.md) and [`MapType`](../type-level/map_type.md): the two similarly-named traits that do something else. The ideas behind it: -- [Implicit arguments](/docs/concepts/implicit-arguments) — the ergonomic surface over field access. +- [Implicit arguments](/docs/concepts/implicit-arguments): the ergonomic surface over field access. ## Source -- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs) - — `MapField` and `FieldMapper` +- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs): + `MapField` and `FieldMapper` --- diff --git a/docs/reference/traits/field-access/mut_field_getter.md b/docs/reference/traits/field-access/mut_field_getter.md index 2098f17b..14d9bc83 100644 --- a/docs/reference/traits/field-access/mut_field_getter.md +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -5,7 +5,7 @@ sidebar_position: 4 # `MutFieldGetter` -The provider-side mirror of `HasFieldMut` — wired field access that can mutate. +The provider-side mirror of `HasFieldMut`: wired field access that can mutate. :::info @@ -24,7 +24,7 @@ explains what the mutable half of that entry provides. The one case for implemen by wiring which field answers a getter. `MutFieldGetter` is the same thing with mutation: it hands back a `&mut` rather than a `&`. -Completing the square, the four traits divide on two axes, consumer versus provider and read versus +Completing the square, the traits divide on two axes, consumer versus provider and read versus write: | | you bound against | you wire | @@ -54,7 +54,7 @@ inherited from the supertrait's `Value`. `Self` is the provider and `Context` is **It is in the prelude**, so `use cgp::prelude::*;` is enough. As with its immutable sibling you rarely name the trait. What you write is a wiring entry naming a -provider that implements it — [`UseField`](../../providers/use_field.md) does, so a getter component wired +provider that implements it. [`UseField`](../../providers/use_field.md) does, so a getter component wired to `UseField` supports both the read and the write. Writing an impl by hand is the escape hatch for a provider whose mutable access is not a plain field @@ -98,8 +98,8 @@ and rarer still than mutation generally. on its own context. The access rules on that page cover mutable access, and no provider is involved. - **Use [`HasFieldMut`](./has_field_mut.md)** when the implementation should simply *require* mutable access rather than have it wired. -- **Use [`FieldGetter`](./field_getter.md)** when the wired access is read-only, which is the common case - — requiring mutation narrows what a context can supply for no benefit. +- **Use [`FieldGetter`](./field_getter.md)** when the wired access is read-only, which is the common case. + Requiring mutation narrows what a context can supply for no benefit. - **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable and threads state through handler outputs instead. @@ -125,7 +125,7 @@ read half is not optional. **`Value` lives on the supertrait**, so pin it there rather than redeclaring it. **The `'static` bound behind `DerefMut` can bite.** A wired read that resolves and a wired write that -does not usually means the context is behind a smart pointer over borrowed data — see +does not usually means the context is behind a smart pointer over borrowed data. See [`HasFieldMut`](./has_field_mut.md#common-mistakes). **Requiring it where a read would do narrows the contexts that fit**, since a provider holding `&Context` @@ -133,23 +133,23 @@ cannot satisfy it. ## Related constructs -- [`FieldGetter`](./field_getter.md) — the supertrait, and where the wired form is explained in full. -- [`HasFieldMut`](./has_field_mut.md) — the consumer side you bound against. -- [`HasField`](./has_field.md) — the read half of the consumer side. -- [`UseField`](../../providers/use_field.md) — the provider that implements both halves. -- [`#[cgp_getter]`](../../macros/cgp_getter.md) — the macro that makes a getter a full component. -- [`#[implicit]`](../../attributes/implicit.md) — the idiomatic way to reach a field. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) — the tags that key a field. +- [`FieldGetter`](./field_getter.md): the supertrait, and where the wired form is explained in full. +- [`HasFieldMut`](./has_field_mut.md): the consumer side you bound against. +- [`HasField`](./has_field.md): the read half of the consumer side. +- [`UseField`](../../providers/use_field.md): the provider that implements both halves. +- [`#[cgp_getter]`](../../macros/cgp_getter.md): the macro that makes a getter a full component. +- [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to reach a field. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that key a field. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the duality this trait is +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the duality this trait is an instance of. ## Source -- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs) - — `MutFieldGetter`, `HasFieldMut`, and the `DerefMut` forwarding +- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs): + `MutFieldGetter`, `HasFieldMut`, and the `DerefMut` forwarding --- diff --git a/docs/reference/traits/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md index 66e83180..9f0726a3 100644 --- a/docs/reference/traits/formatting/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -21,7 +21,7 @@ expansion or an error message is legible. The one case for naming it is generic ## Overview -A [`Path!`](../../macros/path.md) is a type-level list of segments — the route a namespaced component +A [`Path!`](../../macros/path.md) is a type-level list of segments: the route a namespaced component lookup is redirected along, or the chain of field names a nested getter descends. Composing two such routes means splicing one list onto the end of another, and `ConcatPath` is that operation. It is the path-level analogue of [`ConcatProduct`](../type-level/concat_product.md), with the same two-impl @@ -44,10 +44,10 @@ during trait resolution, so it names the combined path type and nothing runs. ## Usage -**`ConcatPath` is in the prelude** — `use cgp::prelude::*;` names it, which makes it the one member of +**`ConcatPath` is in the prelude**: `use cgp::prelude::*;` names it, which makes it the one member of the type-level recovery group that needs no import. Its two neighbours each need a different one: [`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and -[`StaticFormat`](./static_format.md) — defined in the same crate as this trait — from +[`StaticFormat`](./static_format.md), defined in the same crate as this trait, from `cgp::core::base::traits`. ## Examples @@ -63,7 +63,7 @@ type Inner = Path!(@c.d); type Joined = >::Output; // the path @a.b.c.d ``` -Note the leading `@` — [`Path!`](../../macros/path.md) requires it, and `Path!(a.b)` does not parse. +Note the leading `@`: [`Path!`](../../macros/path.md) requires it, and `Path!(a.b)` does not parse. In generic code the projection usually appears in a bound rather than a type alias, naming the route a composed getter will take: @@ -108,7 +108,7 @@ impl ConcatPath for Nil { } ``` -Note the `?Sized` on every parameter, including the associated type — that lets both operands +Note the `?Sized` on every parameter, including the associated type: that lets both operands be the unsized markers a path is built from, and it is the one way this recursion differs from [`ConcatProduct`](../type-level/concat_product.md)'s otherwise identical shape. @@ -126,7 +126,7 @@ This is the most common way an otherwise-correct `ConcatPath` example fails to b **It produces a type, not a joined string.** This is path composition for trait resolution. If you want the segments as text, decode the symbols with [`StaticString`](./static_string.md). -**Both sides may be unsized**, which is why the trait carries `?Sized` on the parameter and the output — +**Both sides may be unsized**, which is why the trait carries `?Sized` on the parameter and the output, a detail worth noticing if you write a bound over it and get an unexpected `Sized` error. **It is in the prelude while [`StaticString`](./static_string.md) is not.** The asymmetry between two @@ -137,24 +137,24 @@ normalizes them. ## Related constructs -- [`Path!`](../../macros/path.md) — the sugar for the paths this joins. -- [`PathCons`](../../types/path_cons.md) — the list underneath. -- [`ConcatProduct`](../type-level/concat_product.md) — the product-level analogue. -- [`StaticString`](./static_string.md) — recovering a segment's name as text. -- [`StaticFormat`](./static_format.md) — the lazy formatting counterpart. -- [`RedirectLookup`](../../providers/redirect_lookup.md) — the provider that follows a path. -- [`ChainGetters`](../../providers/chain_getters.md) — nested accessors, the setting path composition +- [`Path!`](../../macros/path.md): the sugar for the paths this joins. +- [`PathCons`](../../types/path_cons.md): the list underneath. +- [`ConcatProduct`](../type-level/concat_product.md): the product-level analogue. +- [`StaticString`](./static_string.md): recovering a segment's name as text. +- [`StaticFormat`](./static_format.md): the lazy formatting counterpart. +- [`RedirectLookup`](../../providers/redirect_lookup.md): the provider that follows a path. +- [`ChainGetters`](../../providers/chain_getters.md): nested accessors, the setting path composition serves. -- [`cgp_namespace!`](../../macros/cgp_namespace.md) — where paths key a namespace's entries. +- [`cgp_namespace!`](../../macros/cgp_namespace.md): where paths key a namespace's entries. The ideas behind it: -- [Namespaces](/docs/concepts/namespaces) — reusable wiring tables and the paths that route into them. +- [Namespaces](/docs/concepts/namespaces): reusable wiring tables and the paths that route into them. ## Source -- [`concat_path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/concat_path.rs) - — `ConcatPath` +- [`concat_path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/concat_path.rs): + `ConcatPath` --- diff --git a/docs/reference/traits/formatting/index.md b/docs/reference/traits/formatting/index.md index 4afe1e05..68180d1e 100644 --- a/docs/reference/traits/formatting/index.md +++ b/docs/reference/traits/formatting/index.md @@ -10,8 +10,8 @@ Recovering a field name or a routing path as runtime data. ## Overview CGP encodes field and variant names as *types*, so that a name can drive trait resolution. A program -eventually needs those names as ordinary strings — to report a missing field, to build a key, to render -a path — and these traits are how a name comes back out. The three sit in three different homes, which +eventually needs those names as ordinary strings, to report a missing field, to build a key, or to render +a path, and these traits are how a name comes back out. They sit in three different homes, which is the group's sharpest edge: one is in the prelude and the other two each need a different import. - [`StaticString`](static_string.md) decodes a [`Symbol!`](../../macros/symbol.md) into a compile-time @@ -25,8 +25,8 @@ is the group's sharpest edge: one is in the prelude and the other two each need ## The ideas behind them -- [Namespaces](/docs/concepts/namespaces) — reusable wiring tables and the paths that route into them. -- [Extensible records](/docs/concepts/extensible-records) — where field-name types are put to work at +- [Namespaces](/docs/concepts/namespaces): reusable wiring tables and the paths that route into them. +- [Extensible records](/docs/concepts/extensible-records): where field-name types are put to work at scale. --- diff --git a/docs/reference/traits/formatting/static_format.md b/docs/reference/traits/formatting/static_format.md index f7473385..8092bf22 100644 --- a/docs/reference/traits/formatting/static_format.md +++ b/docs/reference/traits/formatting/static_format.md @@ -5,14 +5,14 @@ sidebar_position: 2 # `StaticFormat` -Writing a type-level string into a formatter — the trait behind `Display` on `Symbol`. +Writing a type-level string into a formatter: the trait behind `Display` on `Symbol`. :::info ### Generated machinery **You are not expected to name `StaticFormat`.** It backs the `Display` impls on -`Symbol` and `Chars`, which is how a type-level string prints at all — so reach for `Display`, or for +`Symbol` and `Chars`, which is how a type-level string prints at all. So reach for `Display`, or for [`StaticString`](./static_string.md) when you want a constant. This page explains the trait behind them, and the narrow case where bounding on it is the answer. @@ -51,7 +51,7 @@ use cgp::core::base::traits::StaticFormat; That module is where the base type-level crate is re-exported, and it is a different home from its neighbours: [`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and -[`ConcatPath`](./concat_path.md) — which lives in the same crate as this trait — is in the prelude. +[`ConcatPath`](./concat_path.md), which lives in the same crate as this trait, is in the prelude. Three neighbouring traits, three different imports. Most of the time you reach the effect rather than the trait. Any type-level string can be interpolated @@ -66,7 +66,7 @@ assert_eq!(s.to_string(), "hello"); assert_eq!(format!("field: {s}"), "field: hello"); ``` -The impls exist for `Chars` — the character list — and for `Nil`, which terminates it, with `Symbol` +The impls exist for `Chars`, the character list, and for `Nil`, which terminates it, with `Symbol` delegating to its inner list. Every type-level string therefore formats, including the empty one. ## Examples @@ -114,9 +114,9 @@ more than once, and this trait only when you need to write characters without a exists to power, and it is the form to prefer. - **[`StaticString`](./static_string.md)** for a constant, a key, or a comparison. It is computed at compile time, so there is no per-call work. -- **`StaticFormat`** when a formatter has to be written into from a type with no value — implementing - `Display` for a wrapper over a type-level string, say. This is the narrow case, and it is why the - method takes no `self`. +- **`StaticFormat`** when a formatter has to be written into from a type with no value, such as + implementing `Display` for a wrapper over a type-level string. This is the narrow case, and it is why + the method takes no `self`. - **[`ConcatPath`](./concat_path.md)** when the thing being composed is a path rather than a string. ## Under the hood @@ -138,7 +138,7 @@ impl StaticFormat for Nil { /* writes nothing */ } ``` Because both `Symbol` and `Chars` implement `Display` by delegating to this, any type-level string can be -interpolated or turned into an owned `String` — and the string is *reconstructed* on each call rather +interpolated or turned into an owned `String`, and the string is *reconstructed* on each call rather than read out of storage, since there is no `&str` inside a `Symbol` to read. That per-call reconstruction is the difference from [`StaticString`](./static_string.md), which does the @@ -148,7 +148,7 @@ same decoding once, at compile time, into a `&'static str` constant. **It is not in the prelude, and its import differs from both its neighbours'.** This trait comes from `cgp::core::base::traits`, [`StaticString`](./static_string.md) from `cgp::core::field::traits`, and -[`ConcatPath`](./concat_path.md) — defined in the same crate as this one — is in the prelude. Reaching for +[`ConcatPath`](./concat_path.md), defined in the same crate as this one, is in the prelude. Reaching for the wrong module is the usual first failure. **Prefer a `Display` bound where one will do.** Any code that only needs to *format* a type-level string @@ -158,26 +158,26 @@ should require `Display`, which needs no import and is what the trait produces. [`StaticString`](./static_string.md)'s `VALUE` is the cheaper choice. **There is no `self`.** The trait's method is an associated function, because a type-level string has no -value — which is why the `Display` impl goes through a `Default`-constructed marker, and why a bound on -this trait is what you need when there is no value to construct. +value. That is why the `Display` impl goes through a `Default`-constructed marker, and why you need a +bound on this trait when there is no value to construct. ## Related constructs -- [`StaticString`](./static_string.md) — the eager counterpart, and the one to reach for. -- [`ConcatPath`](./concat_path.md) — path composition, its reachable sibling in the same group. -- [`Symbol!`](../../macros/symbol.md) — the type-level string being formatted. -- [Type-level lists](../../types/index.md) — the `Chars` chain being walked. -- [`HasField`](../field-access/has_field.md) — where the names being decoded are used as keys. +- [`StaticString`](./static_string.md): the eager counterpart, and the one to reach for. +- [`ConcatPath`](./concat_path.md): path composition, its reachable sibling in the same group. +- [`Symbol!`](../../macros/symbol.md): the type-level string being formatted. +- [Type-level lists](../../types/index.md): the `Chars` chain being walked. +- [`HasField`](../field-access/has_field.md): where the names being decoded are used as keys. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where field-name types are put to work at +- [Extensible records](/docs/concepts/extensible-records): where field-name types are put to work at scale. ## Source -- [`static_format.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/static_format.rs) - — `StaticFormat` and its character-list impls +- [`static_format.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/static_format.rs): + `StaticFormat` and its character-list impls --- diff --git a/docs/reference/traits/formatting/static_string.md b/docs/reference/traits/formatting/static_string.md index 4ed1a143..45dad562 100644 --- a/docs/reference/traits/formatting/static_string.md +++ b/docs/reference/traits/formatting/static_string.md @@ -9,8 +9,8 @@ Recovering a type-level string as a compile-time `&'static str`. ## Overview -CGP encodes field and variant names as *types* — a [`Symbol!`](../../macros/symbol.md) is a length plus a -character list, one node per character — so that names can drive trait resolution. But a program +CGP encodes field and variant names as *types* (a [`Symbol!`](../../macros/symbol.md) is a length plus a +character list, one node per character) so that names can drive trait resolution. But a program eventually needs those names as ordinary strings: to report a missing field, to build a key, to compare against input. @@ -60,7 +60,7 @@ use cgp::prelude::*; // eagerly, as a compile-time constant assert_eq!(::VALUE, "hello"); -// lazily, through Display — reconstructed at the point of formatting +// lazily, through Display: reconstructed at the point of formatting let s = ::default(); assert_eq!(s.to_string(), "hello"); ``` @@ -74,7 +74,7 @@ assert_eq!(::VALUE, ""); Where it shows up in real code is recovering a name for an error. The [optional-field layer](../optional/finalize_optional.md)'s `finalize_optional` reports its missing field by -returning `Tag::VALUE` — the field's own name, as a static string, with no allocation. +returning `Tag::VALUE`, the field's own name, as a static string, with no allocation. ## When to use it @@ -90,7 +90,7 @@ message.** That is the whole decision. Two things this is not for. It is **not a general string facility**: [`Symbol!`](../../macros/symbol.md) exists to key field and variant lookups, and building programs out of type-level strings is not what the -encoding is for. And it is **not how you read a field** — recovering a name tells you what a field is +encoding is for. And it is **not how you read a field**: recovering a name tells you what a field is called, while [`HasField`](../field-access/has_field.md) reads its value. ## Under the hood @@ -101,13 +101,13 @@ the character list and UTF-8-encoding each character into the array, and `VALUE` bytes as UTF-8 and exposes the `&'static str`. **That array is why `Symbol` carries a `LEN` at all.** A const-evaluated byte array must have a known -size, and the size cannot be computed from inside the const context by walking the list — so the macro -precomputes it. It is a *byte* length, which makes multi-byte Unicode round-trip correctly and -why `LEN` disagrees with the visible character count for any non-ASCII name. +size, and the size cannot be computed from inside the const context by walking the list, so the macro +precomputes it. It is a *byte* length, which makes multi-byte Unicode round-trip correctly and makes +`LEN` disagree with the visible character count for any non-ASCII name. ## Common Mistakes -**It is not in the prelude** while [`ConcatPath`](./concat_path.md) is — an asymmetry between two traits +**It is not in the prelude** while [`ConcatPath`](./concat_path.md) is, an asymmetry between two traits that do neighbouring jobs. Import `StaticString` from `cgp::core::field::traits`. **`VALUE` is a constant, so it is named through the trait.** Write @@ -124,22 +124,22 @@ means decoding each segment's symbol. ## Related constructs -- [`StaticFormat`](./static_format.md) — the lazy counterpart, behind the `Display` impls. -- [`ConcatPath`](./concat_path.md) — the same recovery idea one level up, for paths. -- [`Symbol!`](../../macros/symbol.md) — the type-level string this decodes, and where the `LEN` comes from. -- [Type-level lists](../../types/index.md) — the `Chars` chain being walked. -- [`HasField`](../field-access/has_field.md) — where the names being decoded are used as keys. -- [`FinalizeOptional`](../optional/finalize_optional.md) — a real consumer, reporting a missing field by name. +- [`StaticFormat`](./static_format.md): the lazy counterpart, behind the `Display` impls. +- [`ConcatPath`](./concat_path.md): the same recovery idea one level up, for paths. +- [`Symbol!`](../../macros/symbol.md): the type-level string this decodes, and where the `LEN` comes from. +- [Type-level lists](../../types/index.md): the `Chars` chain being walked. +- [`HasField`](../field-access/has_field.md): where the names being decoded are used as keys. +- [`FinalizeOptional`](../optional/finalize_optional.md): a real consumer, reporting a missing field by name. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where field-name types are put to work at +- [Extensible records](/docs/concepts/extensible-records): where field-name types are put to work at scale. ## Source -- [`static_string.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/static_string.rs) - — `StaticString` and its const-evaluated UTF-8 decoding +- [`static_string.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/static_string.rs): + `StaticString` and its const-evaluated UTF-8 decoding --- diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index 50f3e9ff..15c6c60a 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -20,8 +20,8 @@ page is here to explain how a step unwraps its input. ## Overview -A step in a [monadic pipeline](/docs/concepts/monadic-handlers) produces a wrapped output — a `Result`, -say — and the next step needs the value *inside* the wrapper for the branch that continues. Which half of +A step in a [monadic pipeline](/docs/concepts/monadic-handlers) produces a wrapped output, a `Result`, +say, and the next step needs the value *inside* the wrapper for the branch that continues. Which half of the wrapper that is depends on the monad, so it cannot be hard-coded. `ContainsValue` is where each monad answers it. @@ -56,7 +56,7 @@ layer unwraps it further. use cgp::extra::monad::traits::ContainsValue; ``` -You import it only when **defining a monad of your own**. There is no method — the trait is a type-level +You import it only when **defining a monad of your own**. There is no method. The trait is a type-level projection from an output type to the value beneath the wrapper. ## Examples @@ -73,7 +73,7 @@ unwrapped, and every value threads forward. | `ErrMonadic` | `T` | the `Ok` payload threads forward | | `OkMonadic` | `E` | the `Err` payload threads forward | -So under `ErrMonadic` a step's continuation receives the `Ok` payload — the ordinary `?` behaviour — and +So under `ErrMonadic` a step's continuation receives the `Ok` payload, the ordinary `?` behaviour, and under `OkMonadic` it receives the `Err` payload, which is the inverted, run-until-something-succeeds behaviour. @@ -88,7 +88,7 @@ specific to any depth. by wiring [`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker and a handler list; this is what the bind providers bound on internally. -The one real reason to name it is **defining a new monad** — short-circuiting over an `Option`, or over a +The one real reason to name it is **defining a new monad**: short-circuiting over an `Option`, or over a custom two-branch enum. Implement it alongside [`LiftValue`](./lift_value.md), since the two are the pair that runs a step and neither is useful without the other, and copy the mirror-image `OkMonadic`/`ErrMonadic` pair as the model. @@ -104,7 +104,7 @@ The [`BindOk` and `BindErr`](../../providers/monad/index.md) providers use `Cont step's output, ask the monad what value sits beneath its wrapper, and hand that to the continuation. This trait is the second half of that sentence. -[`LiftValue`](./lift_value.md) is then what puts a result back into the output type — `lift_value` for the +[`LiftValue`](./lift_value.md) then puts a result back into the output type: `lift_value` for the branch that short-circuits, `lift_output` for the branch that forwarded to the continuation. So the two traits bracket one step: unwrap, run, re-wrap. @@ -130,24 +130,24 @@ the first step rather than at the definition. ## Related constructs -- [`LiftValue`](./lift_value.md) — the other half of running a step: getting back into the output type. -- [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md) — the two traits that fold +- [`LiftValue`](./lift_value.md): the other half of running a step: getting back into the output type. +- [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md): the two traits that fold the pipeline rather than run a step. -- [Monad providers](../../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../../providers/monad/index.md): `PipeMonadic`, `BindOk`, `BindErr`, and the markers; what you actually wire. -- [`Computer`](../../components/handler/computer.md) — the component family the bind providers implement. -- [`TryComputer`](../../components/handler/try_computer.md) and [`Handler`](../../components/handler/handler.md) — the fallible +- [`Computer`](../../components/handler/computer.md): the component family the bind providers implement. +- [`TryComputer`](../../components/handler/try_computer.md) and [`Handler`](../../components/handler/handler.md): the fallible members a single step usually is. The ideas behind it: -- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads +- [Monadic handlers](/docs/concepts/monadic-handlers): why a pipeline short-circuits and how the monads compose. ## Source -- [`value.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/value.rs) - — `ContainsValue` +- [`value.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/value.rs): + `ContainsValue` - Per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) --- diff --git a/docs/reference/traits/monad/index.md b/docs/reference/traits/monad/index.md index 335c19c1..49bb0ecc 100644 --- a/docs/reference/traits/monad/index.md +++ b/docs/reference/traits/monad/index.md @@ -5,19 +5,19 @@ sidebar_position: 0 # Monad interface -The four traits that give a monad marker its meaning for monadic handler composition. +The traits that give a monad marker its meaning for monadic handler composition. ## Overview A [monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue or -short-circuit — the `?`-style behaviour, expressed as composable providers. A monad in CGP is a +short-circuit, the `?`-style behaviour, expressed as composable providers. A monad in CGP is a zero-sized marker, and these four traits are what give that marker meaning. They are plain capability traits rather than CGP components: they have no generated provider trait and are never wired. The [monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a pipeline at compile time, so you name a trait here only when defining a monad of your own. Import each from `cgp::extra::monad::traits`. -The four split into the pair that folds the pipeline and the pair that runs one step. +They split into the pair that folds the pipeline and the pair that runs one step. The **folding pair** decides the shape of the composed provider. [`MonadicBind`](monadic_bind.md) turns a continuation into one bind step, and [`MonadicTrans`](monadic_trans.md) stacks one monad over another @@ -29,7 +29,7 @@ the output type on either branch. ## The ideas behind them -- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads +- [Monadic handlers](/docs/concepts/monadic-handlers): why a pipeline short-circuits and how the monads compose. --- diff --git a/docs/reference/traits/monad/lift_value.md b/docs/reference/traits/monad/lift_value.md index dd1a5a31..3fa9606a 100644 --- a/docs/reference/traits/monad/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -14,7 +14,7 @@ Putting a value back into a monad's output type, on either branch. **You are not expected to name `LiftValue`.** The [bind providers](../../providers/monad/index.md) use it while running a step, and the monad markers CGP ships already implement it. The one case for naming it is defining a monad of your own; otherwise this -page is here to explain how a step produces its output — and why that takes two methods rather than +page is here to explain how a step produces its output, and why that takes two methods rather than one. ::: @@ -79,7 +79,7 @@ where the mirroring shows: | `ErrMonadic` | `Ok` | `Ok` | | `OkMonadic` | `Err` | `Err` | -So under `ErrMonadic` a bare value re-enters the pipeline as `Ok(value)` — the ordinary `?` behaviour — +So under `ErrMonadic` a bare value re-enters the pipeline as `Ok(value)`, the ordinary `?` behaviour, and under `OkMonadic` as `Err(value)`. **Both methods matter, and conflating them changes behaviour silently.** `lift_value` is used where a @@ -94,7 +94,7 @@ by wiring [`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker a The one real reason to name it is **defining a new monad**. Implement it alongside [`ContainsValue`](./contains_value.md), since the two are the pair that runs a step, and take the -`OkMonadic`/`ErrMonadic` pair as the model — including their separate treatment of the two methods, which +`OkMonadic`/`ErrMonadic` pair as the model, including their separate treatment of the two methods, which is the part a first implementation usually gets wrong. If short-circuiting is not what you need, the [handler combinators](../../providers/handler/index.md) @@ -112,7 +112,7 @@ whether to short-circuit, and then lifts: - on the **continue** branch, the continuation has already produced an inner output, so it is forwarded with `lift_output`. -That is the whole reason for two methods. A monad whose two methods agree — as `IdentMonadic`'s do — is +That is the whole reason for two methods. A monad whose two methods agree, as `IdentMonadic`'s do, is one where the distinction happens to be vacuous, not one where it does not exist. The transformer forms implement both by delegating to the base monad after handling their own layer, @@ -124,8 +124,8 @@ which lets a stack lift through *n* layers with no depth-specific code. **It is not a component and cannot be wired.** What gets wired is the provider that consumes it. -**`lift_value` and `lift_output` are not the same method.** Implementing the second as the first — or -forgetting the distinction — collapses the two branches and silently changes what a pipeline does on a +**`lift_value` and `lift_output` are not the same method.** Implementing the second as the first, or +forgetting the distinction, collapses the two branches and silently changes what a pipeline does on a short-circuit. This is the most likely defect in a hand-written monad. **`OkMonadic` lifts with `Err`.** Its continue branch is the error half, which follows from @@ -138,25 +138,25 @@ forwarded; the associated type is the step's own. They coincide for some monads ## Related constructs -- [`ContainsValue`](./contains_value.md) — the other half of running a step: getting out of the output +- [`ContainsValue`](./contains_value.md): the other half of running a step: getting out of the output type. -- [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md) — the two traits that fold +- [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md): the two traits that fold the pipeline rather than run a step. -- [Monad providers](../../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../../providers/monad/index.md): `PipeMonadic`, `BindOk`, `BindErr`, and the markers; what you actually wire. -- [`Computer`](../../components/handler/computer.md) — the component family the bind providers implement. -- [Handler combinators](../../providers/handler/index.md) — composition without a short-circuit +- [`Computer`](../../components/handler/computer.md): the component family the bind providers implement. +- [Handler combinators](../../providers/handler/index.md): composition without a short-circuit branch. The ideas behind it: -- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads +- [Monadic handlers](/docs/concepts/monadic-handlers): why a pipeline short-circuits and how the monads compose. ## Source -- [`lift.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/lift.rs) - — `LiftValue` +- [`lift.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/lift.rs): + `LiftValue` - Per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) --- diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index f344adc8..69b2584e 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -21,7 +21,7 @@ otherwise this page is here to explain how a pipeline is assembled. ## Overview A [monadic pipeline](/docs/concepts/monadic-handlers) chains steps where each may either continue or -short-circuit — the familiar `?`-style behaviour, expressed as composable providers rather than as +short-circuit, the familiar `?`-style behaviour, expressed as composable providers rather than as syntax. Folding such a pipeline means asking the monad, once per step: *given everything built so far, what provider runs one bind?* @@ -69,8 +69,8 @@ binds it. ## Examples -The trait is consumed rather than called, so the thing to read is what each marker's impl *says* — -because that decides how a pipeline behaves. +The trait is consumed rather than called, so read what each marker's impl *says*, because that decides +how a pipeline behaves. **`IdentMonadic` implements it as the identity**: `MonadicBind::Provider` is `Provider` unchanged. Nothing wraps the continuation, nothing branches, and a pipeline under `IdentMonadic` is @@ -85,7 +85,7 @@ over a `Result`: | `OkMonadic` | `Err` | `Ok` | `BindErr` | So `ErrMonadic` gives the ordinary `?` behaviour, and `OkMonadic` the inverted one that runs until -something succeeds — useful for a fallback chain. +something succeeds, useful for a fallback chain. **The transformer forms delegate one layer down.** `OkMonadicTrans` and `ErrMonadicTrans` bind their own `Result` layer and hand the rest to `M`, which is how a stack reaches arbitrary depth. @@ -103,15 +103,15 @@ step tries to run, because the running half is [`ContainsValue`](./contains_valu And the alternatives to prefer when you do *not* need short-circuiting: -- **[Handler combinators](../../providers/handler/index.md)** — `ComposeHandlers` and `PipeHandlers` +- **[Handler combinators](../../providers/handler/index.md)**: `ComposeHandlers` and `PipeHandlers` chain handlers without a branch. If every step runs unconditionally, do not involve a monad at all. -- **Ordinary `?` in one provider body** — if the whole chain lives in a single implementation, Rust's own +- **Ordinary `?` in one provider body**: if the whole chain lives in a single implementation, Rust's own operator is clearer than any composition. ## Under the hood [`PipeMonadic`](../../providers/monad/pipe_monadic.md) walks the handler list and, for each step, asks the monad -to turn the continuation built so far into a bind step — which is this trait. Because the walk proceeds +to turn the continuation built so far into a bind step, which is this trait. Because the walk proceeds from the end of the list backwards, `Provider` at each stage is everything that follows the current step, and the result is a single nested provider by the time the list is exhausted. @@ -143,25 +143,25 @@ missing trait rather than the gap. ## Related constructs -- [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) — the two traits that run one +- [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md): the two traits that run one bind step, where this one only builds it. -- [`MonadicTrans`](./monadic_trans.md) — stacking one monad on another during the same fold. -- [Monad providers](../../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the monad +- [`MonadicTrans`](./monadic_trans.md): stacking one monad on another during the same fold. +- [Monad providers](../../providers/monad/index.md): `PipeMonadic`, `BindOk`, `BindErr`, and the monad markers; what you actually wire. -- [Handler combinators](../../providers/handler/index.md) — composition without a short-circuit +- [Handler combinators](../../providers/handler/index.md): composition without a short-circuit branch. -- [`Computer`](../../components/handler/computer.md) — the component family a monadic pipeline implements. -- [`Product!`](../../macros/product.md) — the type-level list a pipeline's steps are given in. +- [`Computer`](../../components/handler/computer.md): the component family a monadic pipeline implements. +- [`Product!`](../../macros/product.md): the type-level list a pipeline's steps are given in. The ideas behind it: -- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads +- [Monadic handlers](/docs/concepts/monadic-handlers): why a pipeline short-circuits and how the monads compose. ## Source -- [`bind.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/bind.rs) - — `MonadicBind` +- [`bind.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/bind.rs): + `MonadicBind` - Per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) --- diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index 0127b652..4d4f7acf 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -20,8 +20,8 @@ a monad of your own a transformer form; otherwise this page is here to explain h ## Overview -A [monadic pipeline](/docs/concepts/monadic-handlers) over a nested output — a `Result` inside a -`Result` — needs to peel more than one layer, and hard-coding a depth would give up the composability +A [monadic pipeline](/docs/concepts/monadic-handlers) over a nested output, a `Result` inside a +`Result`, needs to peel more than one layer, and hard-coding a depth would give up the composability the design exists for. `MonadicTrans` is how a monad is expressed as a *transformer* over another. It is one of four traits that give a monad marker its meaning, and it belongs with @@ -63,8 +63,8 @@ composed one. What each marker's impl says decides how deeply a pipeline can reach. -**`IdentMonadic` returns `M` unchanged**, so applying it as a transformer changes nothing — which is what -makes it the neutral element of a stack as well as of a pipeline. +**`IdentMonadic` returns `M` unchanged**, so applying it as a transformer changes nothing, which makes +it the neutral element of a stack as well as of a pipeline. **The transformer forms compose.** `OkMonadicTrans` and `ErrMonadicTrans` implement the running traits by peeling their own `Result` layer and handing the rest to `M`, and their `MonadicTrans` impls @@ -84,10 +84,10 @@ An *n*-layer stack unwraps *n* layers with no code specific to any depth, which ## When to use it **Reach for the [monad providers](../../providers/monad/index.md), not this trait.** Wiring -[`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker — including a stacked one — is how a +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker, including a stacked one, is how a pipeline is built. -The reasons to name it are two, and both are narrow. +The reasons to name it are narrow. - **Defining a new monad that should stack.** The three other traits give a marker meaning on its own; this one lets it sit over another. A marker without it works as a base monad and cannot be a @@ -96,7 +96,7 @@ The reasons to name it are two, and both are narrow. trait, and knowing it is the composition step rather than the running step tells you the problem is the stack's shape rather than a step's types. -If your pipeline runs over a single-layer output, you do not need a transformer at all — use the base +If your pipeline runs over a single-layer output, you do not need a transformer at all. Use the base marker directly. ## Under the hood @@ -107,7 +107,7 @@ handler list asking [`MonadicBind`](./monadic_bind.md) to turn each continuation Because the transformer forms implement [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) by delegating to the base monad after handling their own layer, a -two-layer stack unwraps two `Result` layers in order and re-wraps them in reverse — and the same code +two-layer stack unwraps two `Result` layers in order and re-wraps them in reverse, and the same code serves any depth. That is the sense in which stacking is composition rather than a special case: the resolved stack is just another marker, and everything downstream treats it as one. @@ -134,24 +134,24 @@ bound rather than saying the marker is not stackable. ## Related constructs -- [`MonadicBind`](./monadic_bind.md) — the other folding trait, which turns a continuation into a bind +- [`MonadicBind`](./monadic_bind.md): the other folding trait, which turns a continuation into a bind step. -- [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) — the two traits that run one +- [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md): the two traits that run one step, where these two build the pipeline. -- [Monad providers](../../providers/monad/index.md) — `PipeMonadic`, `BindOk`, `BindErr`, and the +- [Monad providers](../../providers/monad/index.md): `PipeMonadic`, `BindOk`, `BindErr`, and the markers, including the transformer forms. -- [`Computer`](../../components/handler/computer.md) — the component family a monadic pipeline implements. -- [`Product!`](../../macros/product.md) — the type-level list a pipeline's steps are given in. +- [`Computer`](../../components/handler/computer.md): the component family a monadic pipeline implements. +- [`Product!`](../../macros/product.md): the type-level list a pipeline's steps are given in. The ideas behind it: -- [Monadic handlers](/docs/concepts/monadic-handlers) — why a pipeline short-circuits and how the monads +- [Monadic handlers](/docs/concepts/monadic-handlers): why a pipeline short-circuits and how the monads compose. ## Source -- [`monadic_trans.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/monadic_trans.rs) - — `MonadicTrans` +- [`monadic_trans.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-monad/src/traits/monadic_trans.rs): + `MonadicTrans` - Per-marker impls: [`cgp-monad/src/monadic/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-monad/src/monadic) --- diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index 9c09feff..523ca83d 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -35,7 +35,7 @@ pub trait DefaultImpls1 { } ``` -`Self` is the key being looked up — the *instance* type, such as `String`. `T` is the further lookup +`Self` is the key being looked up, the *instance* type, such as `String`. `T` is the further lookup type, which the attribute fills with the component name. `Components` is the table the lookup runs against, and `Delegate` is the resolved provider. There is no method and no data, so resolving a default projects `Delegate` from the matching impl, exactly as with @@ -48,7 +48,7 @@ which lets the projection `>` resolve cle :::warning **The parameter names are misleading about which position holds what.** For this trait and its sibling, -**`Self` is the instance type and the component name is a leading parameter** — the opposite of +**`Self` is the instance type and the component name is a leading parameter**, the opposite of [`DefaultNamespace`](./default_namespace.md). The [next section](#the-one-thing-to-get-right) works it out. @@ -82,7 +82,7 @@ impl DefaultImpls1 for String { The rule that governs this comes from the attribute rather than the trait, and once you have it the positions stop being surprising. **`#[default_impl(Key in NamespacePath)]` makes `Key` the impl's -`Self`** and appends the table parameter to whatever `NamespacePath` names — so the leading arguments are +`Self`** and appends the table parameter to whatever `NamespacePath` names, so the leading arguments are simply whatever you wrote inside the path. The same rule is why the `for … in` loop's bound reads `T: DefaultImpls1`, with the loop variable in the `Self` position. @@ -129,7 +129,7 @@ delegate_components! { } ``` -**Environmental context, parameter-targeted** — `App` carries the wiring and the shown value is a +**Environmental context, parameter-targeted.** `App` carries the wiring and the shown value is a parameter. The loop wires every type with a registered default by projecting `T: DefaultImpls1`, and the direct `u64` line shadows whatever the namespace would otherwise supply for that one type. @@ -179,13 +179,13 @@ where T: DefaultImpls1 Read it as: for each type `T` that has a default, wire that key to the projected `Provider`. -**Because the loop variables appear only in that bound and in the key, the key must mention `T`** — +**Because the loop variables appear only in that bound and in the key, the key must mention `T`**, otherwise the parameter is unconstrained and the compiler rejects the impl with `E0207`, which reads as a puzzling error about a generic parameter rather than about the loop. The registration side is the mirror. [`#[default_impl]`](../../attributes/default_impl.md) emits an impl of -this trait for the key type, carrying **only** the parameters naming the key and provider plus the table -— never the provider's own `where` clause. A provider whose bounds come from `#[use_type]`, `#[uses]`, +this trait for the key type, carrying **only** the parameters naming the key and provider plus the table, +never the provider's own `where` clause. A provider whose bounds come from `#[use_type]`, `#[uses]`, `#[implicit]`, or `#[use_provider]` therefore registers cleanly, because those bounds stay on the provider's impl and its [`IsProviderFor`](../wiring/is_provider_for.md), and are checked when a real context resolves it. @@ -205,29 +205,29 @@ Put downstream wiring in the namespace body instead. **A default is a fallback, not an assignment.** A direct entry silently shadows it. -**The registration impl carries none of the provider's bounds**, which is deliberate — they are checked +**The registration impl carries none of the provider's bounds**, which is deliberate: they are checked where the provider is used rather than where it is registered. ## Related constructs -- [`DefaultNamespace`](./default_namespace.md) — the one-key form, and the common case. -- [`DefaultImpls2`](./default_impls2.md) — the two-type form. -- [`#[default_impl(...)]`](../../attributes/default_impl.md) — the attribute that emits impls of this trait. -- [`cgp_namespace!`](../../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. -- [`delegate_components!`](../../macros/delegate_components.md) — carries the `for … in` loop. -- [`DelegateComponent`](../wiring/delegate_component.md) — what the loop ultimately writes. -- [`IsProviderFor`](../wiring/is_provider_for.md) — where a registered provider's real bounds are checked. -- [`RedirectLookup`](../../providers/redirect_lookup.md) — the usual `Delegate` value. +- [`DefaultNamespace`](./default_namespace.md): the one-key form, and the common case. +- [`DefaultImpls2`](./default_impls2.md): the two-type form. +- [`#[default_impl(...)]`](../../attributes/default_impl.md): the attribute that emits impls of this trait. +- [`cgp_namespace!`](../../macros/cgp_namespace.md): defines a namespace, and documents `#[prefix(...)]`. +- [`delegate_components!`](../../macros/delegate_components.md): carries the `for … in` loop. +- [`DelegateComponent`](../wiring/delegate_component.md): what the loop ultimately writes. +- [`IsProviderFor`](../wiring/is_provider_for.md): where a registered provider's real bounds are checked. +- [`RedirectLookup`](../../providers/redirect_lookup.md): the usual `Delegate` value. The ideas behind it: -- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style +- [Namespaces](/docs/concepts/namespaces): reusable, inheritable wiring tables and preset-style configuration. ## Source -- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) - — the three lookup traits +- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs): + the three lookup traits - The `#[default_impl]` attribute: [`attributes/default_impl/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/default_impl) - Header and loop codegen: [`delegate_component/statement/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/statement) diff --git a/docs/reference/traits/namespace/default_impls2.md b/docs/reference/traits/namespace/default_impls2.md index 591476d8..e494277f 100644 --- a/docs/reference/traits/namespace/default_impls2.md +++ b/docs/reference/traits/namespace/default_impls2.md @@ -43,7 +43,7 @@ which lets the projection resolve cleanly. This is the widest of the three. :::warning **Nothing inside CGP emits or consumes it.** It is reachable and tested, and it is a provided extension -point rather than a construct the generated code relies on — so there is no library-generated example to +point rather than a construct the generated code relies on, so there is no library-generated example to pattern-match against. The [next section](#usage) shows what a use looks like. ::: @@ -109,13 +109,13 @@ for the one-type form. ## When to use it -**Reach for it when a default genuinely depends on two types**, and prefer the narrower forms otherwise — -each extra key position is one more thing a reader has to hold. +**Reach for it when a default genuinely depends on two types**, and prefer the narrower forms otherwise, +since each extra key position is one more thing a reader has to hold. - **[`DefaultNamespace`](./default_namespace.md)** when the key is the component alone. The common case. - **[`DefaultImpls1`](./default_impls1.md)** when one further type decides the default. This is what `#[default_impl]` is usually pointed at. -- **`DefaultImpls2`** when two do — a conversion keyed on source *and* target, say. +- **`DefaultImpls2`** when two do, such as a conversion keyed on source *and* target. - **Define your own namespace trait** when the shape does not fit. [`#[default_impl]`](../../attributes/default_impl.md) accepts any path, so a trait of your own with whatever arity you need works identically. Given that nothing in the library uses this one, a @@ -133,14 +133,14 @@ projects the default: where T: DefaultImpls2 ``` -The loop variables appear only in that bound and in the key, so **the key must mention them** — otherwise +The loop variables appear only in that bound and in the key, so **the key must mention them**, otherwise the parameter is unconstrained and the compiler rejects the impl with `E0207`. The registration impl carries only the parameters naming the key and provider plus the table, never the provider's own `where` clause, so a provider with impl-side dependencies registers cleanly and its bounds are checked when a real context resolves it. -Because nothing in the library emits this trait, there is no generated code to compare against — the +Because nothing in the library emits this trait, there is no generated code to compare against. The impls you see are the ones you or the attribute wrote. ## Common Mistakes @@ -162,24 +162,24 @@ library example. ## Related constructs -- [`DefaultImpls1`](./default_impls1.md) — the one-type form, and where the family's mechanics are +- [`DefaultImpls1`](./default_impls1.md): the one-type form, and where the family's mechanics are worked out. -- [`DefaultNamespace`](./default_namespace.md) — the component-only form. -- [`#[default_impl(...)]`](../../attributes/default_impl.md) — the attribute that emits impls of this trait. -- [`cgp_namespace!`](../../macros/cgp_namespace.md) — defines a namespace. -- [`delegate_components!`](../../macros/delegate_components.md) — carries the `for … in` loop. -- [`DelegateComponent`](../wiring/delegate_component.md) — what the loop ultimately writes. -- [`RedirectLookup`](../../providers/redirect_lookup.md) — the usual `Delegate` value. +- [`DefaultNamespace`](./default_namespace.md): the component-only form. +- [`#[default_impl(...)]`](../../attributes/default_impl.md): the attribute that emits impls of this trait. +- [`cgp_namespace!`](../../macros/cgp_namespace.md): defines a namespace. +- [`delegate_components!`](../../macros/delegate_components.md): carries the `for … in` loop. +- [`DelegateComponent`](../wiring/delegate_component.md): what the loop ultimately writes. +- [`RedirectLookup`](../../providers/redirect_lookup.md): the usual `Delegate` value. The ideas behind it: -- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style +- [Namespaces](/docs/concepts/namespaces): reusable, inheritable wiring tables and preset-style configuration. ## Source -- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) - — the three lookup traits +- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs): + the three lookup traits - The `#[default_impl]` attribute: [`attributes/default_impl/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/attributes/default_impl) --- diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index 03de2ea6..33a50fcc 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -14,16 +14,16 @@ Resolving a namespace's default provider for a component. **You do not implement `DefaultNamespace`.** [`cgp_namespace!`](../../macros/cgp_namespace.md) and its [`#[prefix(...)]`](../../macros/cgp_namespace.md) attribute emit the impls. You name the trait in exactly -one place — a `namespace` header inside -[`delegate_components!`](../../macros/delegate_components.md) — and this page explains what that header +one place, a `namespace` header inside +[`delegate_components!`](../../macros/delegate_components.md), and this page explains what that header generates, including why a direct entry can shadow an inherited default without conflicting with it. ::: ## Overview -A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** — the -type the capability runs against — can opt into and then selectively override. Resolving one of those +A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** (the +type the capability runs against) can opt into and then selectively override. Resolving one of those defaults means asking: *for this component, what does the namespace delegate to?* `DefaultNamespace` answers that. It is the simplest of three lookup traits, keyed on the component alone. @@ -51,7 +51,7 @@ value: the provider the key maps to. There is no method and no data, so resolvin ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough — unlike its two siblings, which are not. +**It is in the prelude**, so `use cgp::prelude::*;` is enough, unlike its two siblings, which are not. A context joins a namespace with a header inside [`delegate_components!`](../../macros/delegate_components.md): @@ -93,7 +93,7 @@ delegate_components! { ``` **Environmental context, self-targeted.** The header forwards `App`'s unwired lookups through the -namespace, and the direct entry shadows whatever the namespace would otherwise supply for that one key — +namespace, and the direct entry shadows whatever the namespace would otherwise supply for that one key, the inheritance-with-override shape presets rely on. ## When to use it @@ -114,7 +114,7 @@ where the syntax requires it.** It appears in a `namespace` header and nowhere e ## Under the hood -A `namespace N;` header does not emit one entry — it emits a **blanket** +A `namespace N;` header does not emit one entry. It emits a **blanket** [`DelegateComponent`](../wiring/delegate_component.md) impl on the context that forwards every key through the namespace: @@ -131,13 +131,13 @@ paired with the matching [`IsProviderFor`](../wiring/is_provider_for.md) forward diagnosable. **That blanket makes override work.** A directly-wired entry is a *concrete* impl for one key, -and a concrete impl is more specific than the blanket, so it resolves first — shadowing the inherited +and a concrete impl is more specific than the blanket, so it resolves first, shadowing the inherited default for that key and leaving the rest untouched. Two *concrete* entries for one key would conflict; a concrete entry against a blanket does not. Inheritance composes on top. A namespace declared `new Child: Parent { … }` emits a blanket impl forwarding any key the parent resolves, so the child resolves everything the parent does plus its own -entries — and a context's direct entry still shadows either. All of it is projections, resolved at +entries, and a context's direct entry still shadows either. All of it is projections, resolved at compile time, with nothing at run time. ## Common Mistakes @@ -146,7 +146,7 @@ compile time, with nothing at run time. wire directly, which is the intent, and it means a stray direct entry can silently shadow a default you expected to apply. -**`Self` is the component here**, as you would expect — but **not** in +**`Self` is the component here**, as you would expect, but **not** in [`DefaultImpls1`](./default_impls1.md) and [`DefaultImpls2`](./default_impls2.md), where the instance type takes the `Self` position instead. The inconsistency is the family's sharpest edge. @@ -154,33 +154,33 @@ type takes the `Self` position instead. The inconsistency is the family's sharpe **There is no method.** Resolving a default is a type projection. -**Registering into a foreign namespace is bound by the orphan rule** — see +**Registering into a foreign namespace is bound by the orphan rule.** See [`DefaultImpls1`](./default_impls1.md#when-to-use-it), where the [`#[default_impl]`](../../attributes/default_impl.md) attribute's placement constraint is worked out. ## Related constructs -- [`DefaultImpls1`](./default_impls1.md) and [`DefaultImpls2`](./default_impls2.md) — the per-type and +- [`DefaultImpls1`](./default_impls1.md) and [`DefaultImpls2`](./default_impls2.md): the per-type and per-pair variants. -- [`#[default_impl(...)]`](../../attributes/default_impl.md) — the attribute that registers a provider as a +- [`#[default_impl(...)]`](../../attributes/default_impl.md): the attribute that registers a provider as a default. -- [`cgp_namespace!`](../../macros/cgp_namespace.md) — defines a namespace, and documents `#[prefix(...)]`. -- [`delegate_components!`](../../macros/delegate_components.md) — carries the `namespace` header. -- [`DelegateComponent`](../wiring/delegate_component.md) — what a namespace header forwards *into*. -- [`IsProviderFor`](../wiring/is_provider_for.md) — forwarded alongside, so dependency errors stay readable. -- [`RedirectLookup`](../../providers/redirect_lookup.md) — the usual `Delegate` value, re-routing along a +- [`cgp_namespace!`](../../macros/cgp_namespace.md): defines a namespace, and documents `#[prefix(...)]`. +- [`delegate_components!`](../../macros/delegate_components.md): carries the `namespace` header. +- [`DelegateComponent`](../wiring/delegate_component.md): what a namespace header forwards *into*. +- [`IsProviderFor`](../wiring/is_provider_for.md): forwarded alongside, so dependency errors stay readable. +- [`RedirectLookup`](../../providers/redirect_lookup.md): the usual `Delegate` value, re-routing along a path. -- [`Path!`](../../macros/path.md) — the paths a prefixed key is built from. +- [`Path!`](../../macros/path.md): the paths a prefixed key is built from. The ideas behind it: -- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style +- [Namespaces](/docs/concepts/namespaces): reusable, inheritable wiring tables and preset-style configuration. ## Source -- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs) - — the three lookup traits +- [`namespaces.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/namespaces.rs): + the three lookup traits - Header and loop codegen: [`delegate_component/statement/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component/statement) --- diff --git a/docs/reference/traits/namespace/index.md b/docs/reference/traits/namespace/index.md index 24085ffd..80277ea2 100644 --- a/docs/reference/traits/namespace/index.md +++ b/docs/reference/traits/namespace/index.md @@ -11,7 +11,7 @@ The lookup traits behind a namespace and a per-type default. A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a context opts into and then selectively overrides. Resolving one of those defaults means asking, for a given key, what the -namespace delegates to — and these three traits answer it, differing only in how many types take part +namespace delegates to, and these three traits answer it, differing only in how many types take part in the key. You name them where the syntax requires it: a `namespace` header or a `for … in` loop inside [`delegate_components!`](../../macros/delegate_components.md), and the [`#[default_impl]`](../../attributes/default_impl.md) attribute. The macros generate the impls. @@ -31,7 +31,7 @@ works it out. ## The ideas behind them -- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables and preset-style +- [Namespaces](/docs/concepts/namespaces): reusable, inheritable wiring tables and preset-style configuration. --- diff --git a/docs/reference/traits/optional/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md index 429573b3..94e595c2 100644 --- a/docs/reference/traits/optional/can_build_with_default.md +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -14,7 +14,7 @@ start a builder, copy the shared fields, default the rest. `CanBuildWithDefault` call. `Self` is the target record and `Source` the narrower one. **It is the field-level counterpart of an -[upcast](../casting/can_upcast.md)** — turning a `Point2d` into a `Point3d` whose extra `z` is `0`, naming no field +[upcast](../casting/can_upcast.md)**: turning a `Point2d` into a `Point3d` whose extra `z` is `0`, naming no field explicitly. It chains [`builder()`](../builder/has_builder.md), [`build_from`](../casting/can_build_from.md), and @@ -87,7 +87,7 @@ in between needs to happen. - **[`CanBuildFrom`](../casting/can_build_from.md) plus an explicit finalize** when some fields must be set by hand as well as copied. This trait offers no place to insert a `build_field`. - **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when there is no source to merge from. -- **[`CanUpcast`](../casting/can_upcast.md)** for the enum analogue — widening a variant set rather than a field +- **[`CanUpcast`](../casting/can_upcast.md)** for the enum analogue: widening a variant set rather than a field set. - **A plain `From` impl** when both types are yours and the conversion is one you would write once. A hand-written `From` is clearer, requires nothing of either type, and lets you choose values other than @@ -111,7 +111,7 @@ The impl chains the three steps and constrains each with a bound: Each bound is where one of the requirements comes from: [`CanBuildFrom`](../casting/can_build_from.md) brings the [`HasFields`](../shape/has_fields.md) obligation on the source, and [`CanFinalizeWithDefault`](./can_finalize_with_default.md) brings the `Default` obligation on the -remaining fields — through a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying +remaining fields, through a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying [`TransformMapDefault`](./transform_map_default.md). So an unsatisfied bound here is always really an unsatisfied bound one layer down, which is worth knowing @@ -122,7 +122,7 @@ because the error names that layer rather than this trait. **It is not in the prelude.** Import from `cgp::extra::field::impls`. **The source needs [`HasFields`](../shape/has_fields.md), not just a builder.** Deriving only -[`BuildField`](../../derives/derive_build_field.md) on both looks symmetric and fails — the same trap +[`BuildField`](../../derives/derive_build_field.md) on both looks symmetric and fails, the same trap [`CanBuildFrom`](../casting/can_build_from.md) carries. **Every field the source does not supply needs `Default`.** The error names the missing @@ -137,22 +137,22 @@ the source. ## Related constructs -- [`CanBuildFrom`](../casting/can_build_from.md) — the merge step, and where the source's requirements come from. -- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the defaulting finalize step. -- [`HasBuilder`](../builder/has_builder.md) — the builder it starts from. -- [`TransformMapDefault`](./transform_map_default.md) — the marker behind the defaulting. -- [`CanUpcast`](../casting/can_upcast.md) — the enum analogue of widening. -- [`HasFields`](../shape/has_fields.md) — what the source must derive. -- [`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md) — what makes both records eligible. +- [`CanBuildFrom`](../casting/can_build_from.md): the merge step, and where the source's requirements come from. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the defaulting finalize step. +- [`HasBuilder`](../builder/has_builder.md): the builder it starts from. +- [`TransformMapDefault`](./transform_map_default.md): the marker behind the defaulting. +- [`CanUpcast`](../casting/can_upcast.md): the enum analogue of widening. +- [`HasFields`](../shape/has_fields.md): what the source must derive. +- [`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md): what makes both records eligible. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — merging records through a builder. +- [Extensible records](/docs/concepts/extensible-records): merging records through a builder. ## Source -- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs) - — `CanBuildWithDefault`, `CanFinalizeWithDefault`, and `TransformMapDefault` +- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs): + `CanBuildWithDefault`, `CanFinalizeWithDefault`, and `TransformMapDefault` --- diff --git a/docs/reference/traits/optional/can_finalize_with_default.md b/docs/reference/traits/optional/can_finalize_with_default.md index e0655c70..fcb5e5c8 100644 --- a/docs/reference/traits/optional/can_finalize_with_default.md +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -14,7 +14,7 @@ catches a missing field at compile time. For a record where some fields have sen strictness is the wrong shape. `CanFinalizeWithDefault` relaxes it: every field that is not set becomes `Default::default()`, and the result is the concrete struct. -**The strict presence check still runs — it just always passes**, because the fields are re-marked to +**The strict presence check still runs; it just always passes**, because the fields are re-marked to `IsPresent` first. That is the layer's whole design in one sentence, and it is why the core [`FinalizeBuild`](../builder/finalize_build.md) remains the only route from a partial value to a struct. @@ -80,8 +80,8 @@ assert_eq!(context.foo, "foo"); assert_eq!(context.bar, 0); // defaulted ``` -Had that used [`finalize_optional`](./finalize_optional.md), it would have returned `Err("bar")` instead -— which is the point of deferring the choice to the finalize call rather than to the builder. +Had that used [`finalize_optional`](./finalize_optional.md), it would have returned `Err("bar")` instead, +which is the point of deferring the choice to the finalize call rather than to the builder. The one-call form that also copies from a source is [`CanBuildWithDefault`](./can_build_with_default.md). @@ -92,7 +92,7 @@ The one-call form that also copies from a source is - **[`FinalizeOptional`](./finalize_optional.md)** when absence is an error worth reporting. The two are the same builder finalized differently. -- **[`FinalizeBuild`](../builder/finalize_build.md)** — the core builder — when every field is genuinely +- **[`FinalizeBuild`](../builder/finalize_build.md)** (the core builder) when every field is genuinely required. A missing field is then a compile error, which is strictly stronger. - **[`CanBuildWithDefault`](./can_build_with_default.md)** when the set fields come from another record rather than from individual calls. It chains the merge and this finalize into one call. @@ -127,14 +127,14 @@ recursion with a different marker**, which is why the defaulted and optional wor symmetrically. Because the transform targets `IsPresent`, the value handed to `finalize_build` is at exactly the -configuration its single impl requires — so the strict check runs, and cannot fail. +configuration its single impl requires, so the strict check runs, and cannot fail. ## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. **Every field's type needs `Default`.** A field whose type has none makes the transform unresolvable, and -the error names the missing [`TransformMap`](../type-level/transform_map.md) impl rather than the field — which is +the error names the missing [`TransformMap`](../type-level/transform_map.md) impl rather than the field, which is the most confusing failure in this layer. **A defaulted field is silent.** Nothing distinguishes "set to zero" from "left unset" in the result, which @@ -142,32 +142,32 @@ is the trade against [`FinalizeOptional`](./finalize_optional.md). **It gives up the compile-time completeness check** that the core builder provides. -**It applies to a core builder too**, not only an optional one — an absent `IsNothing` field is +**It applies to a core builder too**, not only an optional one: an absent `IsNothing` field is transformed as readily as a `None`. **It consumes the builder.** ## Related constructs -- [`FinalizeOptional`](./finalize_optional.md) — the other ending, reporting rather than filling. -- [`CanBuildWithDefault`](./can_build_with_default.md) — merge and default in one call. -- [`TransformMapDefault`](./transform_map_default.md) — the marker this drives. -- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk it runs. -- [`FinalizeBuild`](../builder/finalize_build.md) — the strict impl it ultimately calls. -- [`HasOptionalBuilder`](./has_optional_builder.md) and [`ToOptional`](./to_optional.md) — the optional +- [`FinalizeOptional`](./finalize_optional.md): the other ending, reporting rather than filling. +- [`CanBuildWithDefault`](./can_build_with_default.md): merge and default in one call. +- [`TransformMapDefault`](./transform_map_default.md): the marker this drives. +- [`TransformMapFields`](../type-level/transform_map_fields.md): the walk it runs. +- [`FinalizeBuild`](../builder/finalize_build.md): the strict impl it ultimately calls. +- [`HasOptionalBuilder`](./has_optional_builder.md) and [`ToOptional`](./to_optional.md): the optional entry points. -- [`HasBuilder`](../builder/has_builder.md) — the core family this relaxes. -- [`MapType`](../type-level/map_type.md) — the markers the transform moves between. +- [`HasBuilder`](../builder/has_builder.md): the core family this relaxes. +- [`MapType`](../type-level/map_type.md): the markers the transform moves between. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence +- [Extensible records](/docs/concepts/extensible-records): partial records, and where relaxing presence fits. ## Source -- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs) - — `CanFinalizeWithDefault`, `CanBuildWithDefault`, and `TransformMapDefault` +- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs): + `CanFinalizeWithDefault`, `CanBuildWithDefault`, and `TransformMapDefault` --- diff --git a/docs/reference/traits/optional/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md index 6efb0c68..1dbc541f 100644 --- a/docs/reference/traits/optional/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -91,7 +91,7 @@ assert_eq!(result.err(), Some("bar")); - **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when unset fields have meaningful defaults and silence is the right outcome. The two are the same builder finalized differently, so the same value can go either way. -- **[`FinalizeBuild`](../builder/finalize_build.md)** — that is, the core builder — when every field is genuinely +- **[`FinalizeBuild`](../builder/finalize_build.md)** (that is, the core builder) when every field is genuinely required and set once. A missing field is then a *compile* error, which is strictly better than a `Result`, and moving to this layer gives that check up. - **A hand-written check** when the validation is more than presence: interdependent fields, ranges, @@ -111,7 +111,7 @@ For each field it pulls the `Option` out with [`UpdateField`](../builder/update_ - if it is `Some`, writes the value back as `IsPresent` with [`BuildField`](../builder/build_field.md) and continues; -- if it is `None`, returns `Err(Tag::VALUE)` immediately — the field's name recovered as a static string +- if it is `None`, returns `Err(Tag::VALUE)` immediately, the field's name recovered as a static string through [`StaticString`](../formatting/static_string.md). Only if every field yields a value does the walk reach the all-present configuration and call @@ -119,7 +119,7 @@ Only if every field yields a value does the walk reach the all-present configura **The strict, all-present [`FinalizeBuild`](../builder/finalize_build.md) remains the only way a partial value becomes a concrete struct.** Everything in this layer simply guarantees that configuration is reached -before it is invoked — or reports why it could not be. +before it is invoked, or reports why it could not be. That short-circuiting is also why only the *first* missing field is named: the walk stops at it rather than collecting. @@ -144,26 +144,26 @@ first `None`. ## Related constructs -- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the other ending, filling gaps from +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the other ending, filling gaps from `Default`. -- [`HasOptionalBuilder`](./has_optional_builder.md) and [`ToOptional`](./to_optional.md) — where an +- [`HasOptionalBuilder`](./has_optional_builder.md) and [`ToOptional`](./to_optional.md): where an optional builder comes from. -- [`SetOptional`](./set_optional.md) — filling one. -- [`FinalizeBuild`](../builder/finalize_build.md) — the strict impl this ultimately calls. -- [`PartialData`](../builder/partial_data.md) — the supertrait naming the destination. -- [`StaticString`](../formatting/static_string.md) — how the missing field's name is recovered. -- [`UpdateField`](../builder/update_field.md) and [`BuildField`](../builder/build_field.md) — the primitives the walk uses. -- [`HasFields`](../shape/has_fields.md) — the shape it walks. +- [`SetOptional`](./set_optional.md): filling one. +- [`FinalizeBuild`](../builder/finalize_build.md): the strict impl this ultimately calls. +- [`PartialData`](../builder/partial_data.md): the supertrait naming the destination. +- [`StaticString`](../formatting/static_string.md): how the missing field's name is recovered. +- [`UpdateField`](../builder/update_field.md) and [`BuildField`](../builder/build_field.md): the primitives the walk uses. +- [`HasFields`](../shape/has_fields.md): the shape it walks. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence +- [Extensible records](/docs/concepts/extensible-records): partial records, and where relaxing presence fits. ## Source -- [`finalize_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/finalize_optional.rs) - — `FinalizeOptional` +- [`finalize_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/finalize_optional.rs): + `FinalizeOptional` --- diff --git a/docs/reference/traits/optional/has_optional_builder.md b/docs/reference/traits/optional/has_optional_builder.md index cc017360..aea91b2b 100644 --- a/docs/reference/traits/optional/has_optional_builder.md +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -45,7 +45,7 @@ prelude; the whole optional-field layer lives in `cgp-field-extra`. ## Usage -**It is not in the prelude.** Nothing in the optional-field layer is — import it from +**It is not in the prelude.** Nothing in the optional-field layer is. Import it from `cgp::extra::field::impls`: ```rust @@ -53,8 +53,8 @@ use cgp::extra::field::impls::HasOptionalBuilder; ``` The impls are blanket ones over the core builder machinery, so any record deriving -[`#[derive(BuildField)]`](../../derives/derive_build_field.md) — or -[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — gets this for free. There is no separate derive. +[`#[derive(BuildField)]`](../../derives/derive_build_field.md) (or +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md)) gets this for free. There is no separate derive. **Two endings are available**, and picking between them at the call site is the layer's real payoff: [`FinalizeOptional`](./finalize_optional.md) requires every field and reports the first missing one, while @@ -100,23 +100,23 @@ Had that used `finalize_optional`, it would have returned `Err("bar")` instead. ## When to use it **Reach for it when fields must be settable in any order and more than once**, which the core -`build_field` cannot do — and stay on the core builder otherwise. +`build_field` cannot do, and stay on the core builder otherwise. - **[`HasBuilder`](../builder/has_builder.md)** when every field is genuinely required and set once. You lose the compile-time completeness check by moving here, and that check is the reason the builder family exists. -- **`HasOptionalBuilder`** when the fields arrive unpredictably — parsed configuration, accumulated - defaults, a value assembled across several passes. +- **`HasOptionalBuilder`** when the fields arrive unpredictably: parsed configuration, accumulated + defaults, or a value assembled across several passes. - **[`ToOptional`](./to_optional.md)** when you already hold a core builder and want to convert it rather than start fresh. -- **A hand-written builder** when the *logic* is the point — validation at finalize, interdependent - fields, computed defaults that are not `Default::default()`. This layer models presence and defaulting, +- **A hand-written builder** when the *logic* is the point: validation at finalize, interdependent + fields, or computed defaults that are not `Default::default()`. This layer models presence and defaulting, and nothing else. ## Under the hood `optional_builder()` is [`HasBuilder`](../builder/has_builder.md)'s `builder()` followed by -[`ToOptional`](./to_optional.md) — start at all-`IsNothing`, then re-mark every field to `IsOptional` +[`ToOptional`](./to_optional.md): start at all-`IsNothing`, then re-mark every field to `IsOptional` with a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying the [`TransformOptional`](./transform_optional.md) marker. @@ -154,24 +154,24 @@ Conflating them produces an `Option>`. ## Related constructs -- [`SetOptional`](./set_optional.md) — setting a field on the builder this produces. -- [`FinalizeOptional`](./finalize_optional.md) — the strict ending, reporting the first missing field. -- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the defaulting ending. -- [`ToOptional`](./to_optional.md) — converting an existing core builder instead of starting fresh. -- [`HasBuilder`](../builder/has_builder.md) — the core entry point this relaxes. -- [`MapType`](../type-level/map_type.md) — the `IsOptional` marker the layer runs on. -- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk that re-marks every field. -- [`#[derive(BuildField)]`](../../derives/derive_build_field.md) — generates the machinery underneath. +- [`SetOptional`](./set_optional.md): setting a field on the builder this produces. +- [`FinalizeOptional`](./finalize_optional.md): the strict ending, reporting the first missing field. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the defaulting ending. +- [`ToOptional`](./to_optional.md): converting an existing core builder instead of starting fresh. +- [`HasBuilder`](../builder/has_builder.md): the core entry point this relaxes. +- [`MapType`](../type-level/map_type.md): the `IsOptional` marker the layer runs on. +- [`TransformMapFields`](../type-level/transform_map_fields.md): the walk that re-marks every field. +- [`#[derive(BuildField)]`](../../derives/derive_build_field.md): generates the machinery underneath. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence +- [Extensible records](/docs/concepts/extensible-records): partial records, and where relaxing presence fits. ## Source -- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs) - — `HasOptionalBuilder`, `ToOptional`, and `TransformOptional` +- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs): + `HasOptionalBuilder`, `ToOptional`, and `TransformOptional` --- diff --git a/docs/reference/traits/optional/index.md b/docs/reference/traits/optional/index.md index c83c39a9..8921335c 100644 --- a/docs/reference/traits/optional/index.md +++ b/docs/reference/traits/optional/index.md @@ -13,7 +13,7 @@ The core [record builder](../builder/index.md) is deliberately strict: a field i partial record becomes its struct only when every field is present. That strictness catches a missing field at compile time, and it is too rigid for a record whose fields arrive unpredictably or have sensible defaults. These traits, from `cgp-field-extra`, relax it while reusing the same machinery -underneath. Nothing here is in the prelude — import each from `cgp::extra::field::impls`. +underneath. Nothing here is in the prelude. Import each from `cgp::extra::field::impls`. The layer divides into entry points, the setter, the two endings, and the transform markers behind them. @@ -36,7 +36,7 @@ The **transform markers** carry the per-field conversions the endings run. ## The ideas behind them -- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence +- [Extensible records](/docs/concepts/extensible-records): partial records, and where relaxing presence fits. --- diff --git a/docs/reference/traits/optional/set_optional.md b/docs/reference/traits/optional/set_optional.md index 6837c66d..02b2bf62 100644 --- a/docs/reference/traits/optional/set_optional.md +++ b/docs/reference/traits/optional/set_optional.md @@ -49,7 +49,7 @@ not in the prelude; import it from `cgp-field-extra`. use cgp::extra::field::impls::SetOptional; ``` -`Self` must be an optional builder — one from +`Self` must be an optional builder, one from [`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md). Calling it on a core builder does not resolve, because the field's marker is `IsNothing` rather than `IsOptional`. There is no "unset" operation: a field starts absent and stays so unless it is set. @@ -82,7 +82,7 @@ let context = builder.finalize_optional().unwrap(); assert_eq!(context.foo, "bar"); ``` -Because `set` returns `Self`, the calls chain exactly as core `build_field` calls do — the difference is +Because `set` returns `Self`, the calls chain exactly as core `build_field` calls do. The difference is invisible at the call site and lives entirely in the type. ## When to use it @@ -93,7 +93,7 @@ thing the core builder cannot express. - **[`BuildField`](../builder/build_field.md)** when each field is set exactly once. The compile-time completeness check it buys is the reason the core family exists. - **`set`** when whatever was there should simply be replaced. -- **`set_optional`** when the previous value matters — merging, accumulating, warning on a duplicate. +- **`set_optional`** when the previous value matters: merging, accumulating, or warning on a duplicate. - **[`CanBuildFrom`](../casting/can_build_from.md)** when the values come from another record wholesale rather than one at a time. @@ -140,24 +140,24 @@ conflate. ## Related constructs -- [`HasOptionalBuilder`](./has_optional_builder.md) — where an optional builder comes from. -- [`ToOptional`](./to_optional.md) — converting an existing builder into one. +- [`HasOptionalBuilder`](./has_optional_builder.md): where an optional builder comes from. +- [`ToOptional`](./to_optional.md): converting an existing builder into one. - [`FinalizeOptional`](./finalize_optional.md) and - [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the two endings. -- [`BuildField`](../builder/build_field.md) — the strict, set-once counterpart. -- [`UpdateField`](../builder/update_field.md) — the primitive this is one call of. -- [`MapType`](../type-level/map_type.md) — the `IsOptional` marker it pins on both sides. -- [`CanBuildFrom`](../casting/can_build_from.md) — filling many fields from another record. + [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the two endings. +- [`BuildField`](../builder/build_field.md): the strict, set-once counterpart. +- [`UpdateField`](../builder/update_field.md): the primitive this is one call of. +- [`MapType`](../type-level/map_type.md): the `IsOptional` marker it pins on both sides. +- [`CanBuildFrom`](../casting/can_build_from.md): filling many fields from another record. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence +- [Extensible records](/docs/concepts/extensible-records): partial records, and where relaxing presence fits. ## Source -- [`set_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/set_optional.rs) - — `SetOptional` +- [`set_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/set_optional.rs): + `SetOptional` --- diff --git a/docs/reference/traits/optional/to_optional.md b/docs/reference/traits/optional/to_optional.md index 386db95c..3effcd11 100644 --- a/docs/reference/traits/optional/to_optional.md +++ b/docs/reference/traits/optional/to_optional.md @@ -11,8 +11,8 @@ Re-marking every field of an existing builder as optional. [`HasOptionalBuilder`](./has_optional_builder.md) starts an all-optional builder from nothing. `ToOptional` is the conversion for the case where you already hold a partial value and want to relax it. -Every field is re-marked to `IsOptional`, whatever state it was in — a set field becomes `Some(value)`, -an absent one becomes `None` — and from there the value behaves like any other optional builder: +Every field is re-marked to `IsOptional`, whatever state it was in (a set field becomes `Some(value)`, +an absent one becomes `None`), and from there the value behaves like any other optional builder: [`SetOptional`](./set_optional.md) applies, and either [`FinalizeOptional`](./finalize_optional.md) or [`CanFinalizeWithDefault`](./can_finalize_with_default.md) ends it. @@ -92,7 +92,7 @@ let builder = context.into_builder().to_optional(); // every field Some - **[`HasOptionalBuilder`](./has_optional_builder.md)** when nothing has been built yet. `optional_builder()` is `builder().to_optional()` and reads better. -- **`ToOptional`** when a core builder is partly filled — because a routine handed it to you, or because +- **`ToOptional`** when a core builder is partly filled, because a routine handed it to you, or because the first few fields were known and the rest are not. - **[`IntoBuilder`](../builder/into_builder.md) then `to_optional`** to relax a complete value, typically before overwriting some of its fields. @@ -128,37 +128,37 @@ symmetrically. **A field already set survives as `Some`.** It is not reset, which is the difference from [`optional_builder()`](./has_optional_builder.md) and is easy to assume the other way round. -**Converting gives up the compile-time completeness check** for the fields that were still absent — from +**Converting gives up the compile-time completeness check** for the fields that were still absent. From here a missing field is an `Err` or a default rather than a compile error. **It is not reversible.** There is no `from_optional`; getting back to a strict configuration means finalizing, through [`FinalizeOptional`](./finalize_optional.md) or [`CanFinalizeWithDefault`](./can_finalize_with_default.md). -**A field whose type is already `Option` becomes `Option>`** in the slot. That is correct — -the outer layer is the builder's presence tracking — and reads confusingly in an error. +**A field whose type is already `Option` becomes `Option>`** in the slot. That is correct +(the outer layer is the builder's presence tracking) and reads confusingly in an error. ## Related constructs -- [`HasOptionalBuilder`](./has_optional_builder.md) — the entry point built from this conversion. -- [`SetOptional`](./set_optional.md) — setting a field once every marker is `IsOptional`. +- [`HasOptionalBuilder`](./has_optional_builder.md): the entry point built from this conversion. +- [`SetOptional`](./set_optional.md): setting a field once every marker is `IsOptional`. - [`FinalizeOptional`](./finalize_optional.md) and - [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the two endings. -- [`TransformOptional`](./transform_optional.md) — the marker this walk carries. -- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk itself. -- [`IntoBuilder`](../builder/into_builder.md) — how a complete value becomes a builder to convert. -- [`HasBuilder`](../builder/has_builder.md) — the core family this relaxes. -- [`MapType`](../type-level/map_type.md) — the `IsOptional` marker. + [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the two endings. +- [`TransformOptional`](./transform_optional.md): the marker this walk carries. +- [`TransformMapFields`](../type-level/transform_map_fields.md): the walk itself. +- [`IntoBuilder`](../builder/into_builder.md): how a complete value becomes a builder to convert. +- [`HasBuilder`](../builder/has_builder.md): the core family this relaxes. +- [`MapType`](../type-level/map_type.md): the `IsOptional` marker. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records, and where relaxing presence +- [Extensible records](/docs/concepts/extensible-records): partial records, and where relaxing presence fits. ## Source -- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs) - — `ToOptional`, `HasOptionalBuilder`, and `TransformOptional` +- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs): + `ToOptional`, `HasOptionalBuilder`, and `TransformOptional` --- diff --git a/docs/reference/traits/optional/transform_map_default.md b/docs/reference/traits/optional/transform_map_default.md index cb914ee6..6ac30046 100644 --- a/docs/reference/traits/optional/transform_map_default.md +++ b/docs/reference/traits/optional/transform_map_default.md @@ -14,7 +14,7 @@ The transform marker that makes every field present, defaulting whatever is not. **You are not expected to name `TransformMapDefault` directly.** It is the marker [`CanFinalizeWithDefault`](./can_finalize_with_default.md) and [`CanBuildWithDefault`](./can_build_with_default.md) drive, and calling one of those is what you write. -This page explains the three conversions behind them — which is also the model to copy if you write a +This page explains the three conversions behind them, which is also the model to copy if you write a transform of your own. ::: @@ -68,7 +68,7 @@ conversion it drives: Builder: TransformMapFields ``` -**Every field's type must implement `Default`** for the two filling impls to apply — which is where the +**Every field's type must implement `Default`** for the two filling impls to apply, which is where the defaulting layer's one real requirement comes from. ## Examples @@ -95,7 +95,7 @@ where ``` The marker is the first type argument, and swapping it for -[`TransformOptional`](./transform_optional.md) — with `IsOptional` as the target — is exactly how +[`TransformOptional`](./transform_optional.md) (with `IsOptional` as the target) is exactly how [`ToOptional`](./to_optional.md) is written. **Same recursion, different marker.** Writing a marker of your own follows the same three-impl shape; the @@ -110,7 +110,7 @@ served by the two capabilities already built on it. gaps. - **[`CanBuildWithDefault`](./can_build_with_default.md)** to merge from a source and default the rest, in one call. -- **Write your own [`TransformMap`](../type-level/transform_map.md) marker** for a conversion these do not cover — one +- **Write your own [`TransformMap`](../type-level/transform_map.md) marker** for a conversion these do not cover: one that validates, logs, or fills from something other than `Default`. - **[`TransformOptional`](./transform_optional.md)** is its counterpart, targeting `IsOptional` instead. @@ -139,7 +139,7 @@ impl TransformMap for TransformMapDefault } ``` -Note that each argument type is the *source* marker's projection — `T`, then `()`, then `Option` — +Note that each argument type is the *source* marker's projection (`T`, then `()`, then `Option`), which keeps the three from overlapping. And note that only two carry the `T: Default` bound: a field already present needs no default, which is why a fully-set builder can be finalized this way regardless of its field types. @@ -158,7 +158,7 @@ moment that field is unset, and the error names the missing `TransformMap` impl **It always targets `IsPresent`.** It cannot be used to reach any other configuration; that is [`TransformOptional`](./transform_optional.md)'s job. -**It is a marker, not a capability.** There is no method to call and nothing to wire — it is named in a +**It is a marker, not a capability.** There is no method to call and nothing to wire. It is named in a bound. **A defaulted field is indistinguishable from one set to the default value** in the result, which is the @@ -166,22 +166,22 @@ trade against [`FinalizeOptional`](./finalize_optional.md). ## Related constructs -- [`CanFinalizeWithDefault`](./can_finalize_with_default.md) — the capability built directly on it. -- [`CanBuildWithDefault`](./can_build_with_default.md) — merge plus that finalize. -- [`TransformOptional`](./transform_optional.md) — the counterpart marker, targeting `IsOptional`. -- [`TransformMap`](../type-level/transform_map.md) — the trait it implements three times. -- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk that applies it. -- [`MapType`](../type-level/map_type.md) — the markers it converts between. -- [`FinalizeBuild`](../builder/finalize_build.md) — what an all-`IsPresent` result is accepted by. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the capability built directly on it. +- [`CanBuildWithDefault`](./can_build_with_default.md): merge plus that finalize. +- [`TransformOptional`](./transform_optional.md): the counterpart marker, targeting `IsOptional`. +- [`TransformMap`](../type-level/transform_map.md): the trait it implements three times. +- [`TransformMapFields`](../type-level/transform_map_fields.md): the walk that applies it. +- [`MapType`](../type-level/map_type.md): the markers it converts between. +- [`FinalizeBuild`](../builder/finalize_build.md): what an all-`IsPresent` result is accepted by. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and how their states change. +- [Extensible records](/docs/concepts/extensible-records): partial records and how their states change. ## Source -- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs) - — `TransformMapDefault` and the capabilities built on it +- [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs): + `TransformMapDefault` and the capabilities built on it --- diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index 3a4cb53e..1f56c48b 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -25,7 +25,7 @@ be set freely and finalized either way. `TransformOptional` is the marker carryi conversions that make that possible. **It is the exact mirror of [`TransformMapDefault`](./transform_map_default.md)**, which targets -`IsPresent` instead — same walk, different destination. That symmetry is why the defaulted and optional +`IsPresent` instead: same walk, different destination. That symmetry is why the defaulted and optional workflows behave so alike. **You name it only when extending the layer.** Using the optional workflow means calling @@ -71,7 +71,7 @@ conversion it drives: Builder: TransformMapFields ``` -Unlike its defaulting counterpart, **it requires nothing of the field types** — wrapping a value in +Unlike its defaulting counterpart, **it requires nothing of the field types**: wrapping a value in `Some` and producing `None` need no `Default` and no other bound, which is why the optional path applies to records the defaulting path does not. @@ -133,7 +133,7 @@ applies to every field type. [`TransformMapFields`](../type-level/transform_map_fields.md#under-the-hood) applies it, visiting each field of the target's [`HasFields`](../shape/has_fields.md) shape and using -[`UpdateField`](../builder/update_field.md) twice per field — once to take the value out and learn its marker, +[`UpdateField`](../builder/update_field.md) twice per field: once to take the value out and learn its marker, once to write it back under `IsOptional`. The result is a partial value at a configuration the core builder never reaches on its own, which is what @@ -147,7 +147,7 @@ makes [`SetOptional`](./set_optional.md) resolve and the strict **It always targets `IsOptional`.** Reaching `IsPresent` is [`TransformMapDefault`](./transform_map_default.md)'s job. -**It is a marker, not a capability.** There is no method and nothing to wire — it is named in a bound. +**It is a marker, not a capability.** There is no method and nothing to wire. It is named in a bound. **It requires nothing of the field types**, which is the one place the two markers genuinely differ in what they can be applied to. @@ -160,22 +160,22 @@ builder's presence tracking, and the two are easy to conflate in an error. ## Related constructs -- [`ToOptional`](./to_optional.md) — the conversion built directly on it. -- [`HasOptionalBuilder`](./has_optional_builder.md) — the entry point built on that. -- [`TransformMapDefault`](./transform_map_default.md) — the counterpart marker, targeting `IsPresent`. -- [`TransformMap`](../type-level/transform_map.md) — the trait it implements. -- [`TransformMapFields`](../type-level/transform_map_fields.md) — the walk that applies it. -- [`SetOptional`](./set_optional.md) — what the resulting configuration makes available. -- [`MapType`](../type-level/map_type.md) — the `IsOptional` marker it targets. +- [`ToOptional`](./to_optional.md): the conversion built directly on it. +- [`HasOptionalBuilder`](./has_optional_builder.md): the entry point built on that. +- [`TransformMapDefault`](./transform_map_default.md): the counterpart marker, targeting `IsPresent`. +- [`TransformMap`](../type-level/transform_map.md): the trait it implements. +- [`TransformMapFields`](../type-level/transform_map_fields.md): the walk that applies it. +- [`SetOptional`](./set_optional.md): what the resulting configuration makes available. +- [`MapType`](../type-level/map_type.md): the `IsOptional` marker it targets. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and how their states change. +- [Extensible records](/docs/concepts/extensible-records): partial records and how their states change. ## Source -- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs) - — `TransformOptional`, `ToOptional`, and `HasOptionalBuilder` +- [`to_optional.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/to_optional.rs): + `TransformOptional`, `ToOptional`, and `HasOptionalBuilder` --- diff --git a/docs/reference/traits/shape/from_fields.md b/docs/reference/traits/shape/from_fields.md index 150a05d2..49b1ca80 100644 --- a/docs/reference/traits/shape/from_fields.md +++ b/docs/reference/traits/shape/from_fields.md @@ -12,7 +12,7 @@ Rebuilding a concrete value from its shape. [`ToFields`](./to_fields.md) takes a value apart into an anonymous list of named entries. `FromFields` is the return journey. It closes the loop for generic code: decompose a value, work on the entries without naming the type, and put a concrete value back together at the end. Both directions go through the -identical `Fields` type, so **the shapes line up by construction rather than by check** — there is +identical `Fields` type, so **the shapes line up by construction rather than by check**: there is nothing to validate and nothing that can fail. ## Definition @@ -35,11 +35,7 @@ because there is no value to call it on, so the call reads `Person::from_fields( **It is in the prelude**, so `use cgp::prelude::*;` is enough. The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all five shape traits together. -The argument must be **exactly** `Self::Fields` — the same entries, the same tags, in the same order. A -shape that merely has the same field names in a different order is a different type and will not be -accepted, which makes the conversion total. - -The argument must be **exactly** `Self::Fields` — the same entries, the same tags, in the same order. A +The argument must be **exactly** `Self::Fields`: the same entries, the same tags, in the same order. A shape that merely has the same field names in a different order is a different type and will not be accepted, which makes the conversion total. @@ -75,7 +71,7 @@ where } ``` -An enum rebuilds the same way, from a [`Sum!`](../../macros/sum.md) rather than a product — the arm that is +An enum rebuilds the same way, from a [`Sum!`](../../macros/sum.md) rather than a product: the arm that is present becomes the variant that is constructed. ## When to use it @@ -109,7 +105,7 @@ impl FromFields for Person { Note the pattern in the argument position: the shape is matched apart in the signature itself, one node per field, terminated by `Nil`. Because the chain is built and matched in declaration order, this is the -exact inverse of [`to_fields`](./to_fields.md) — no lookup by name happens at run time, and the tags +exact inverse of [`to_fields`](./to_fields.md): no lookup by name happens at run time, and the tags exist only to make the types distinct. An enum's impl is the dual: a `match` over the `Either` chain, each arm reconstructing the corresponding @@ -137,25 +133,25 @@ a borrowed shape cannot yield an owned value. ## Related constructs -- [`ToFields`](./to_fields.md) — the reverse conversion, and the one usually written first. -- [`HasFields`](./has_fields.md) — the supertrait that names the shape. -- [`ToFieldsRef`](./to_fields_ref.md) and [`HasFieldsRef`](./has_fields_ref.md) — the borrowed half of +- [`ToFields`](./to_fields.md): the reverse conversion, and the one usually written first. +- [`HasFields`](./has_fields.md): the supertrait that names the shape. +- [`ToFieldsRef`](./to_fields_ref.md) and [`HasFieldsRef`](./has_fields_ref.md): the borrowed half of the family, which has no rebuild. -- [`FromVariant`](../variant/from_variant.md) — constructing an enum from one named variant. -- [`HasBuilder`](../builder/has_builder.md) — incremental assembly, as against this wholesale conversion. -- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. -- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md) — what +- [`FromVariant`](../variant/from_variant.md): constructing an enum from one named variant. +- [`HasBuilder`](../builder/has_builder.md): incremental assembly, as against this wholesale conversion. +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl. +- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md): what a shape is made of. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. -- [Extensible variants](/docs/concepts/extensible-variants) — the enum half. +- [Extensible records](/docs/concepts/extensible-records): a struct as a product of named fields. +- [Extensible variants](/docs/concepts/extensible-variants): the enum half. ## Source -- [`from_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_fields.rs) - — `FromFields` +- [`from_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_fields.rs): + `FromFields` --- diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index 4960d8ce..f2575bd3 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -9,13 +9,13 @@ A type's whole shape, as a single type. ## Overview -Some code needs one field of a type. Other code needs the *shape* — every field, its name, and its type -— so it can walk them: a serializer, a validator, a builder that merges two structs, a dispatcher that +Some code needs one field of a type. Other code needs the *shape*, every field, its name, and its type, +so it can walk them: a serializer, a validator, a builder that merges two structs, a dispatcher that routes an enum to a handler per variant. None of those can be written one field at a time, and none can name the concrete type either. `HasFields` gives a type that shape as a single associated type. Where -[`HasField`](../field-access/has_field.md) — singular — answers *"give me this field"*, `HasFields` answers +[`HasField`](../field-access/has_field.md), the singular, answers *"give me this field"*, `HasFields` answers *"describe all of them at once"*. **The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md).** What you write is the @@ -65,7 +65,7 @@ value and it. This trait names the shape; those move values through it. ### Bounding on the shape The point of all this is a bound. Generic code writes `T: HasFields` and recurses over `T::Fields`, so it -applies to any type that derives the shape — including one declared in another crate: +applies to any type that derives the shape, including one declared in another crate: ```rust fn describe() -> &'static str @@ -110,27 +110,27 @@ pub enum Shape { giving `Sum![Field, Field]`. -**`HasFields` is the one member of the extensible-data family that accepts every variant shape** — unit, -tuple, multi-field, and struct-style — because it only *describes* a variant rather than deconstructing +**`HasFields` is the one member of the extensible-data family that accepts every variant shape** (unit, +tuple, multi-field, and struct-style) because it only *describes* a variant rather than deconstructing it. The derives that take an enum apart need exactly one unnamed payload per variant; this one does not. ## When to use it **Bound on `HasFields` when code must process a type's whole shape; bound on [`HasField`](../field-access/has_field.md) when it needs one named field.** That is the entire distinction, and the two -are complementary rather than ranked — most types that need both derive both in one `#[derive(...)]`. +are complementary rather than ranked. Most types that need both derive both in one `#[derive(...)]`. -- **`HasFields` alone** when the code only names the shape — a `where` clause, an associated-type - projection, a type-level computation like [`AppendProduct`](../type-level/append_product.md). +- **`HasFields` alone** when the code only names the shape: a `where` clause, an associated-type + projection, or a type-level computation like [`AppendProduct`](../type-level/append_product.md). - **[`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md)** when values move through the shape in both directions. - **[`ToFieldsRef`](./to_fields_ref.md)** when the value must not be consumed. Requiring `ToFields` where a borrow would do forces callers to clone. Two things this is not. It is **not runtime reflection**: a type has a shape only because it opted in -with a derive, there is nothing to query at run time, and the shape is a type rather than data. What that -buys is static checking and no runtime cost; what it costs is that a foreign type you cannot patch has no -shape at all. And it is **not the whole extensible-data story** — the shape describes a type, while +with a derive, there is nothing to query at run time, and the shape is a type rather than data. That buys +static checking and no runtime cost, and it costs one thing: a foreign type you cannot patch has no +shape at all. And it is **not the whole extensible-data story**. The shape describes a type, while building one up field by field or taking one apart variant by variant is the [builder](../builder/has_builder.md) and [extractor](../variant/extract_field.md) families, bundled with this one by [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md). @@ -151,7 +151,7 @@ impl HasFields for Person { ``` `Product![A, B]` is `Cons>`, so a `Fields` type in an error message is a `Cons` chain -rather than the sugar — the [type-level lists](../../types/index.md) page covers reading it. +rather than the sugar. The [type-level lists](../../types/index.md) page covers reading it. An enum's shape is the dual: an `Either` chain terminated by `Void` rather than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name and carrying that variant's own fields as a nested @@ -167,7 +167,7 @@ the whole shape and takes structs and enums; the singular is per-field access an Their derives are likewise distinct. **A newtype's shape is the inner type, not a one-element product.** `struct Wrapper(String)` has -`Fields = String`. Generic code written against a `Cons` chain will not match it — the +`Fields = String`. Generic code written against a `Cons` chain will not match it. The [derive's page](../../derives/derive_has_fields.md) has the rule and the other shapes. **Field order is declaration order and is part of the type.** Two structs with the same names in @@ -183,31 +183,31 @@ the other reserved names. ## Related constructs -- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl and the four +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl and the four companions'; what you write. -- [`HasFieldsRef`](./has_fields_ref.md) — the borrowed shape. +- [`HasFieldsRef`](./has_fields_ref.md): the borrowed shape. - [`ToFields`](./to_fields.md), [`FromFields`](./from_fields.md), and - [`ToFieldsRef`](./to_fields_ref.md) — the conversions between a value and its shape. -- [`HasField`](../field-access/has_field.md) — the singular counterpart, per-field access. -- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — bundles this with the builder and extractor. -- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the list types a shape is built + [`ToFieldsRef`](./to_fields_ref.md): the conversions between a value and its shape. +- [`HasField`](../field-access/has_field.md): the singular counterpart, per-field access. +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md): bundles this with the builder and extractor. +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md): the list types a shape is built from. -- [`Field`](../../types/field.md) — one entry: a value paired with its type-level name. -- [Type-level lists](../../types/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains +- [`Field`](../../types/field.md): one entry: a value paired with its type-level name. +- [Type-level lists](../../types/index.md): the `Cons`/`Nil` and `Either`/`Void` chains underneath. -- [`AppendProduct`](../type-level/append_product.md) — the operations that compute new shapes from old ones. -- [`CanUpcast`](../casting/can_upcast.md) and [`CanBuildFrom`](../casting/can_build_from.md) — conversions between two +- [`AppendProduct`](../type-level/append_product.md): the operations that compute new shapes from old ones. +- [`CanUpcast`](../casting/can_upcast.md) and [`CanBuildFrom`](../casting/can_build_from.md): conversions between two types whose shapes overlap, driven by this one. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. -- [Extensible variants](/docs/concepts/extensible-variants) — the enum half, and the expression problem. +- [Extensible records](/docs/concepts/extensible-records): a struct as a product of named fields. +- [Extensible variants](/docs/concepts/extensible-variants): the enum half, and the expression problem. ## Source -- [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs) - — `HasFields` and `HasFieldsRef` +- [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs): + `HasFields` and `HasFieldsRef` - Derive codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) --- diff --git a/docs/reference/traits/shape/has_fields_ref.md b/docs/reference/traits/shape/has_fields_ref.md index 982c069b..56153cf5 100644 --- a/docs/reference/traits/shape/has_fields_ref.md +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -21,8 +21,8 @@ lifetime name that shows up in an error message. ## Overview [`HasFields`](./has_fields.md) describes a type as a list of named entries holding owned values. Code -that only *reads* a value should not have to consume it to walk its shape — a validator, a serializer, a -routine that inspects a struct and hands it back — so there is a second description in which every entry +that only *reads* a value should not have to consume it to walk its shape (a validator, a serializer, a +routine that inspects a struct and hands it back), so there is a second description in which every entry holds a borrow instead. ## Definition @@ -90,14 +90,14 @@ clone it. **Bound on it when generic code reads a type's shape without consuming it**, and pair it with [`ToFieldsRef`](./to_fields_ref.md), which is the only way to obtain a value in this shape. -- **Use [`HasFields`](./has_fields.md)** when the code takes ownership — building, converting, +- **Use [`HasFields`](./has_fields.md)** when the code takes ownership: building, converting, destructuring. - **Use `HasFieldsRef` + [`ToFieldsRef`](./to_fields_ref.md)** when the original must survive. This is the weaker requirement, so prefer it when it suffices. - **Use [`HasField`](../field-access/has_field.md)** when only one named field is needed. The whole-shape traits are for code that walks everything. -Being precise about which of the five shape traits a routine requires pays, because each one narrows what +Being precise about which shape trait a routine requires pays, because each one narrows what a caller must supply. ## Under the hood @@ -117,7 +117,7 @@ impl HasFieldsRef for Person { ``` The transformation is uniform: each entry's value type `T` becomes `&'__a T`, and the list is otherwise -untouched — same length, same order, same tags. An enum's borrowed shape is the dual, an `Either` chain +untouched: same length, same order, same tags. An enum's borrowed shape is the dual, an `Either` chain whose arms carry borrowed payloads. Because the rewrite is per-entry rather than structural, **a field that is already a reference gains @@ -144,23 +144,23 @@ named through `Self::…` in the generated impls. The ## Related constructs -- [`HasFields`](./has_fields.md) — the owned shape, and where the family is explained in full. -- [`ToFieldsRef`](./to_fields_ref.md) — the conversion that produces a value in this shape. -- [`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md) — the owned conversions. -- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. -- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the list types a shape is built +- [`HasFields`](./has_fields.md): the owned shape, and where the family is explained in full. +- [`ToFieldsRef`](./to_fields_ref.md): the conversion that produces a value in this shape. +- [`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md): the owned conversions. +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl. +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md): the list types a shape is built from. -- [`Field`](../../types/field.md) — one entry of a shape. -- [`MapTypeRef`](../type-level/map_type_ref.md) — the borrow markers the extractor family uses for the same job. +- [`Field`](../../types/field.md): one entry of a shape. +- [`MapTypeRef`](../type-level/map_type_ref.md): the borrow markers the extractor family uses for the same job. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. +- [Extensible records](/docs/concepts/extensible-records): a struct as a product of named fields. ## Source -- [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs) - — `HasFieldsRef` and `HasFields` +- [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs): + `HasFieldsRef` and `HasFields` - Derive codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) --- diff --git a/docs/reference/traits/shape/index.md b/docs/reference/traits/shape/index.md index e38d4e0b..3d6a9b95 100644 --- a/docs/reference/traits/shape/index.md +++ b/docs/reference/traits/shape/index.md @@ -10,14 +10,14 @@ A type's whole shape as a single type, and the conversions that move a value thr ## Overview Where [field access](../field-access/index.md) reads one named field, these traits describe a type's -*whole shape* at once — every field, its name, and its type — as a single associated type. That is what +*whole shape* at once, every field, its name, and its type, as a single associated type. That is what lets generic code walk a struct or an enum it cannot name: a serializer, a validator, a merge, a dispatcher. The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md). -Two traits name the shape, and three convert a value in and out of it. +The family splits into traits that name the shape and conversions that move a value in and out of it. -The **shape traits** describe the type. [`HasFields`](has_fields.md) names the owned shape — a -[`Product!`](../../macros/product.md) for a struct, a [`Sum!`](../../macros/sum.md) for an enum — and +The **shape traits** describe the type. [`HasFields`](has_fields.md) names the owned shape (a +[`Product!`](../../macros/product.md) for a struct, a [`Sum!`](../../macros/sum.md) for an enum), and [`HasFieldsRef`](has_fields_ref.md) names the borrowed shape, with every value a reference. The **conversions** move a concrete value through the shape. [`ToFields`](to_fields.md) takes a value @@ -27,8 +27,8 @@ that reads a shape without consuming the value. ## The ideas behind them -- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. -- [Extensible variants](/docs/concepts/extensible-variants) — the enum half. +- [Extensible records](/docs/concepts/extensible-records): a struct as a product of named fields. +- [Extensible variants](/docs/concepts/extensible-variants): the enum half. --- diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index 37785133..d4a783fe 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -66,7 +66,7 @@ let config_again = Config::from_fields(fields); // the product -> Config assert_eq!(config, config_again); ``` -The `clone()` is there only because the assertion compares against the original — `to_fields` would +The `clone()` is there only because the assertion compares against the original. `to_fields` would otherwise have consumed it, which is exactly the point. In generic code, the bound is the point: @@ -116,7 +116,7 @@ An enum's conversion is the dual: each concrete variant is matched onto its arm terminated by `Void`, tagged with the variant name. Because the shape is built positionally from declaration order, `to_fields` and -[`from_fields`](./from_fields.md) are exact inverses by construction — there is no lookup, no matching by +[`from_fields`](./from_fields.md) are exact inverses by construction: there is no lookup, no matching by name at run time, and nothing that can fail. ## Common Mistakes @@ -139,24 +139,24 @@ such as a [cast](../casting/can_downcast.md). ## Related constructs -- [`HasFields`](./has_fields.md) — the supertrait that names the shape. -- [`FromFields`](./from_fields.md) — the reverse conversion. -- [`ToFieldsRef`](./to_fields_ref.md) — the borrowing form, which leaves the value intact. -- [`HasFieldsRef`](./has_fields_ref.md) — the shape that form produces. -- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. -- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md) — what +- [`HasFields`](./has_fields.md): the supertrait that names the shape. +- [`FromFields`](./from_fields.md): the reverse conversion. +- [`ToFieldsRef`](./to_fields_ref.md): the borrowing form, which leaves the value intact. +- [`HasFieldsRef`](./has_fields_ref.md): the shape that form produces. +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl. +- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md): what a shape is made of. -- [Type-level lists](../../types/index.md) — the `Cons` chain the conversion builds. -- [`HasBuilder`](../builder/has_builder.md) — incremental assembly, as against this wholesale conversion. +- [Type-level lists](../../types/index.md): the `Cons` chain the conversion builds. +- [`HasBuilder`](../builder/has_builder.md): incremental assembly, as against this wholesale conversion. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. +- [Extensible records](/docs/concepts/extensible-records): a struct as a product of named fields. ## Source -- [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs) - — `ToFields` and `ToFieldsRef` +- [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs): + `ToFields` and `ToFieldsRef` --- diff --git a/docs/reference/traits/shape/to_fields_ref.md b/docs/reference/traits/shape/to_fields_ref.md index da4e4a19..12b175a3 100644 --- a/docs/reference/traits/shape/to_fields_ref.md +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -10,7 +10,7 @@ Walking a value's shape without consuming it. ## Overview [`ToFields`](./to_fields.md) takes a value apart into its shape and consumes it in the process. Code that -only reads — a validator, a serializer, a routine that inspects a struct and hands it back — should not +only reads (a validator, a serializer, a routine that inspects a struct and hands it back) should not have to. `ToFieldsRef` produces the **borrowed** shape instead. The original survives, and every entry in the result holds a reference rather than a value. @@ -85,7 +85,7 @@ where read-only structural code. - **[`ToFields`](./to_fields.md)** when the code genuinely consumes: a conversion, a merge, a rebuild. -- **[`FromFields`](./from_fields.md)** for constructing a value, which has no borrowing counterpart — +- **[`FromFields`](./from_fields.md)** for constructing a value, which has no borrowing counterpart: a borrowed shape cannot yield an owned value. - **[`HasFieldsRef`](./has_fields_ref.md) alone** when the code only *names* the borrowed shape. - **[`HasField`](../field-access/has_field.md)** when one named field is all that is wanted. @@ -127,28 +127,28 @@ borrowed sum, with the payload borrowed rather than moved, which is also how **The lifetime usually has to be spelled out.** A signature that returns or stores `FieldsRef<'a>` inherits the `where Self: 'a` clause and rarely elides cleanly. -**A newtype's borrowed shape is a borrow of the inner type**, not a one-element product — the same +**A newtype's borrowed shape is a borrow of the inner type**, not a one-element product. It is the same special case the owned shape has. ## Related constructs -- [`HasFieldsRef`](./has_fields_ref.md) — the supertrait that names the borrowed shape. -- [`ToFields`](./to_fields.md) — the owning counterpart, which consumes the value. -- [`FromFields`](./from_fields.md) — rebuilding a value, which has no borrowing form. -- [`HasFields`](./has_fields.md) — the owned shape, and where the family is explained in full. -- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md) — generates this impl. -- [`HasExtractorRef`](../variant/has_extractor_ref.md) — the same borrow-rather-than-consume idea on the enum +- [`HasFieldsRef`](./has_fields_ref.md): the supertrait that names the borrowed shape. +- [`ToFields`](./to_fields.md): the owning counterpart, which consumes the value. +- [`FromFields`](./from_fields.md): rebuilding a value, which has no borrowing form. +- [`HasFields`](./has_fields.md): the owned shape, and where the family is explained in full. +- [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl. +- [`HasExtractorRef`](../variant/has_extractor_ref.md): the same borrow-rather-than-consume idea on the enum side. -- [`Field`](../../types/field.md) — one entry of a shape. +- [`Field`](../../types/field.md): one entry of a shape. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields. +- [Extensible records](/docs/concepts/extensible-records): a struct as a product of named fields. ## Source -- [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs) - — `ToFieldsRef` and `ToFields` +- [`to_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/to_fields.rs): + `ToFieldsRef` and `ToFields` --- diff --git a/docs/reference/traits/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md index 258f4ed8..0970e7c7 100644 --- a/docs/reference/traits/type-level/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -12,7 +12,7 @@ Adding one entry to the end of a type-level product list. ### Generated machinery **You are not expected to use `AppendProduct` directly.** It is a type-level -operation the extensible-data machinery computes with — the builder and merge recursions are its callers +operation the extensible-data machinery computes with. The builder and merge recursions are its callers in practice. You will most likely meet it in an error message from code that walks a shape; this page explains what it produces so that message is legible. The one case for naming it is generic code that must describe in a signature the shape it *will* produce. @@ -20,7 +20,7 @@ explains what it produces so that message is legible. The one case for naming it ## Overview -A struct's shape in CGP is a type-level list — a [`Product!`](../../macros/product.md) of named fields. +A struct's shape in CGP is a type-level list, a [`Product!`](../../macros/product.md) of named fields. Code that processes such a shape generically sometimes needs to describe a *new* shape computed from an old one: the shape a builder will have after one more field is set, say, or the shape a routine promises to return. @@ -54,8 +54,8 @@ ordering. use cgp::core::field::traits::AppendProduct; ``` -Every existing entry is preserved in order, and the new one lands last. Appending onto `Nil` — the empty -product — yields a one-element list, which is the recursion's base case and occasionally useful to know +Every existing entry is preserved in order, and the new one lands last. Appending onto `Nil` (the empty +product) yields a one-element list, which is the recursion's base case and occasionally useful to know when reading a bound. ## Examples @@ -85,8 +85,8 @@ where ## When to use it -**Reach for it when a routine must describe the shape it *will* produce** — in a signature, an associated -type, or a `where` clause — and essentially never otherwise. It is a building block the extensible-data +**Reach for it when a routine must describe the shape it *will* produce** (in a signature, an associated +type, or a `where` clause) and essentially never otherwise. It is a building block the extensible-data machinery uses; application code touches the machinery itself. - **Reach for [`ConcatProduct`](./concat_product.md)** to splice a whole list rather than one entry. @@ -118,7 +118,7 @@ where } ``` -Because the recursion only ever rebuilds the list, order is structurally preserved — which is why +Because the recursion only ever rebuilds the list, order is structurally preserved, which is why appending yields a *different* type from prepending, and why two products with the same entries in different orders are unrelated types. @@ -139,27 +139,27 @@ unresolved-associated-type error. to make two shapes match. **A long list means a deep recursion.** This is trait resolution over the list, so a very wide struct -costs compile time proportional to its width — one of the places CGP's compile-time cost actually comes +costs compile time proportional to its width, one of the places CGP's compile-time cost actually comes from. ## Related constructs -- [`ConcatProduct`](./concat_product.md) — the general form; append is its single-entry case. -- [`MapFields`](./map_fields.md) — rewriting every entry rather than adding one. -- [`Product!`](../../macros/product.md) — the sugar for the lists this operates on. -- [Type-level lists](../../types/index.md) — the `Cons`/`Nil` chain underneath. -- [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. -- [`Field`](../../types/field.md) — the entries a field list is usually made of. -- [`HasBuilder`](../builder/has_builder.md) — the family that moves values through the shapes this computes. +- [`ConcatProduct`](./concat_product.md): the general form; append is its single-entry case. +- [`MapFields`](./map_fields.md): rewriting every entry rather than adding one. +- [`Product!`](../../macros/product.md): the sugar for the lists this operates on. +- [Type-level lists](../../types/index.md): the `Cons`/`Nil` chain underneath. +- [`HasFields`](../shape/has_fields.md): where a type's existing shape comes from. +- [`Field`](../../types/field.md): the entries a field list is usually made of. +- [`HasBuilder`](../builder/has_builder.md): the family that moves values through the shapes this computes. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where computing a new shape is put to work. +- [Extensible records](/docs/concepts/extensible-records): where computing a new shape is put to work. ## Source -- [`append_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/append_product.rs) - — `AppendProduct` +- [`append_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/append_product.rs): + `AppendProduct` --- diff --git a/docs/reference/traits/type-level/concat_product.md b/docs/reference/traits/type-level/concat_product.md index a05caf34..2bed1b90 100644 --- a/docs/reference/traits/type-level/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -20,7 +20,7 @@ produces. The one case for naming it is generic code that must describe the shap ## Overview -Merging two records means merging their shapes, and the shapes are type-level lists — a +Merging two records means merging their shapes, and the shapes are type-level lists, a [`Product!`](../../macros/product.md) of named fields each. `ConcatProduct` names the list you get by following one product with another. @@ -77,8 +77,8 @@ names the combined shape, that moves the fields into it. ## When to use it -**Reach for it when generic code must name the shape produced by combining two others** — a merge, a -routine that extends a record with a caller-supplied set of fields — and essentially never otherwise. +**Reach for it when generic code must name the shape produced by combining two others** (a merge, a +routine that extends a record with a caller-supplied set of fields) and essentially never otherwise. - **Reach for [`AppendProduct`](./append_product.md)** for a single entry. It is the same recursion with a one-element graft, and it reads better for the one-field case. @@ -136,22 +136,22 @@ to the first one's width. ## Related constructs -- [`AppendProduct`](./append_product.md) — the single-entry case. -- [`MapFields`](./map_fields.md) — rewriting every entry rather than adding any. -- [`ConcatPath`](../formatting/concat_path.md) — the same operation over type-level paths. -- [`Product!`](../../macros/product.md) — the sugar for the lists this operates on. -- [Type-level lists](../../types/index.md) — the `Cons`/`Nil` chain underneath. -- [`CanBuildFrom`](../casting/can_build_from.md) — merging the values whose shapes this combines. -- [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. +- [`AppendProduct`](./append_product.md): the single-entry case. +- [`MapFields`](./map_fields.md): rewriting every entry rather than adding any. +- [`ConcatPath`](../formatting/concat_path.md): the same operation over type-level paths. +- [`Product!`](../../macros/product.md): the sugar for the lists this operates on. +- [Type-level lists](../../types/index.md): the `Cons`/`Nil` chain underneath. +- [`CanBuildFrom`](../casting/can_build_from.md): merging the values whose shapes this combines. +- [`HasFields`](../shape/has_fields.md): where a type's existing shape comes from. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — where computing a new shape is put to work. +- [Extensible records](/docs/concepts/extensible-records): where computing a new shape is put to work. ## Source -- [`concat_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/concat_product.rs) - — `ConcatProduct` +- [`concat_product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/concat_product.rs): + `ConcatProduct` --- diff --git a/docs/reference/traits/type-level/index.md b/docs/reference/traits/type-level/index.md index 0d775db5..41932d72 100644 --- a/docs/reference/traits/type-level/index.md +++ b/docs/reference/traits/type-level/index.md @@ -29,8 +29,8 @@ one entry to a product and [`ConcatProduct`](concat_product.md) splices two toge ## The ideas behind them -- [Extensible records](/docs/concepts/extensible-records) — presence tracking on a partial record. -- [Extensible variants](/docs/concepts/extensible-variants) — possibility tracking on a partial variant. +- [Extensible records](/docs/concepts/extensible-records): presence tracking on a partial record. +- [Extensible variants](/docs/concepts/extensible-variants): possibility tracking on a partial variant. --- diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index cb305812..b602e3e3 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -21,12 +21,12 @@ beside it. The one case for naming it is generic code that must describe a unifo ## Overview -A partial record is the same record with every field's storage changed the same way — each value wrapped +A partial record is the same record with every field's storage changed the same way: each value wrapped in an `Option`, or replaced by `()`, or left alone. Describing that as a type means rewriting every entry of the shape uniformly, and `MapFields` is that operation. The list's length and order never change. Each entry type `T` becomes `Mapper::Map`, where the mapper -is a [`MapType`](./map_type.md) marker — so **the marker decides the whole effect**. With `IsPresent` it +is a [`MapType`](./map_type.md) marker, so **the marker decides the whole effect**. With `IsPresent` it is the identity; with `IsNothing` every entry collapses to `()`; with `IsOptional` every entry becomes `Option<_>`; with `IsVoid` every entry becomes uninhabited. @@ -45,7 +45,7 @@ pub trait MapFields { ``` `Self` is the list, `Mapper` is the [`MapType`](./map_type.md) marker to apply, and the result is exposed -as `Mapped` — note the name, which differs from the `Output` its two siblings +as `Mapped`. Note the name, which differs from the `Output` its two siblings [`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md) expose. There is no method, because there is nothing to execute. @@ -63,7 +63,7 @@ use cgp::core::field::traits::MapFields; ## Examples -Applying `IsOptional` turns a product of values into a product of optionals — the shape a partial builder +Applying `IsOptional` turns a product of values into a product of optionals, the shape a partial builder uses to track what is not yet filled: ```rust @@ -90,7 +90,7 @@ type OptionalVariants = >::Mapped; ## When to use it **Reach for it when generic code must name a uniformly re-wrapped shape**, the form a partial -representation takes — and essentially never otherwise. +representation takes, and essentially never otherwise. - **Reach for [`AppendProduct`](./append_product.md) or [`ConcatProduct`](./concat_product.md)** when the shape grows rather than changing its wrapping. @@ -100,7 +100,7 @@ representation takes — and essentially never otherwise. One name worth disambiguating, because three similar ones sit close together. `MapFields` applies one marker across a whole list; [`MapType`](./map_type.md) is a single marker naming *one* field's storage; -and [`MapField`](../field-access/map_field.md) — singular, no *s* — is a lifetime helper for reading a nested field. +and [`MapField`](../field-access/map_field.md), singular, with no *s*, is a lifetime helper for reading a nested field. Three similar names, three unrelated jobs. ## Under the hood @@ -124,7 +124,7 @@ impl MapFields for Nil { The `Either`/`Void` impls mirror these exactly, with `Either` standing where `Cons` does and `Void` where `Nil` does. Because the recursion only ever replaces a head *type*, the list's length and shape are -structurally preserved — which is why a mapped product is still a product of the same arity, and a mapped +structurally preserved, which is why a mapped product is still a product of the same arity, and a mapped sum still a sum. All of it resolves during type checking, so a mapped shape is a name for a type rather than a @@ -138,8 +138,8 @@ needs its own import from `cgp::core::field::impls`. **The result is `Mapped`, not `Output`.** [`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md) both expose `Output`, and this one does not. -**It computes types, not values.** A `MapFields` result does not wrap anything at run time — -something still has to build the wrapped values, which on a partial record is +**It computes types, not values.** A `MapFields` result does not wrap anything at run time. +Something still has to build the wrapped values, which on a partial record is [`TransformMapFields`](./transform_map_fields.md). **A marker with no `MapType` impl does not resolve**, and the error names the missing `MapType` bound @@ -152,26 +152,26 @@ width. ## Related constructs -- [`MapType`](./map_type.md) — the markers this applies, and the trait most easily confused with it. -- [`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md) — the two operations +- [`MapType`](./map_type.md): the markers this applies, and the trait most easily confused with it. +- [`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md): the two operations that grow a list rather than rewrite it. -- [`TransformMapFields`](./transform_map_fields.md) — the value-level counterpart, which actually converts +- [`TransformMapFields`](./transform_map_fields.md): the value-level counterpart, which actually converts the fields. -- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md) — the sugar for both lists. -- [Type-level lists](../../types/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md): the sugar for both lists. +- [Type-level lists](../../types/index.md): the `Cons`/`Nil` and `Either`/`Void` chains underneath. -- [`HasFields`](../shape/has_fields.md) — where a type's existing shape comes from. -- [`MapField`](../field-access/map_field.md) — the similarly-named lifetime helper, which does something else entirely. +- [`HasFields`](../shape/has_fields.md): where a type's existing shape comes from. +- [`MapField`](../field-access/map_field.md): the similarly-named lifetime helper, which does something else entirely. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — presence tracking on a partial record. -- [Extensible variants](/docs/concepts/extensible-variants) — possibility tracking on a partial variant. +- [Extensible records](/docs/concepts/extensible-records): presence tracking on a partial record. +- [Extensible variants](/docs/concepts/extensible-variants): possibility tracking on a partial variant. ## Source -- [`map_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_fields.rs) - — `MapFields`, over both lists +- [`map_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_fields.rs): + `MapFields`, over both lists --- diff --git a/docs/reference/traits/type-level/map_type.md b/docs/reference/traits/type-level/map_type.md index 29392971..b6691670 100644 --- a/docs/reference/traits/type-level/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -51,7 +51,7 @@ storage reads `M: MapType = String>`, and one that leaves it open is ## Usage Four markers implement it, and they are the trait's whole public surface. **Three are in the prelude; -`IsOptional` is not** — import it from `cgp::core::field::impls`. +`IsOptional` is not.** Import it from `cgp::core::field::impls`. ```rust impl MapType for IsPresent { type Map = T; } // the field holds its value @@ -61,7 +61,7 @@ impl MapType for IsOptional { type Map = Option; } // the field may or may ``` **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 +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. @@ -106,7 +106,7 @@ 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 +- **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`](./transform_map.md)** rather than this trait to define a new per-field @@ -117,7 +117,7 @@ The trait itself has narrower uses. - **Reach for the [optional-field layer](../optional/has_optional_builder.md)** if what you want is defaulted or optional finalization. Both already exist, built on exactly this. -[`MapFields`](./map_fields.md) — the other trait with a similar name — is a different thing: it applies +[`MapFields`](./map_fields.md), 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 @@ -151,7 +151,7 @@ two families have been crossed. **`MapType` and [`MapFields`](./map_fields.md) 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`](../field-access/map_field.md) — singular, no *s* — is a third, unrelated thing again. +[`MapField`](../field-access/map_field.md), singular, with no *s*, is a third, unrelated thing again. **A new marker gets you a type and nothing else.** Implementing `MapType` is easy; the derives' finalize and transform impls are written against the standard markers, so a custom one has no machinery behind it. @@ -161,28 +161,28 @@ and transform impls are written against the standard markers, so a custom one ha ## Related constructs -- [`MapTypeRef`](./map_type_ref.md) — the same idea for borrowed views, with a lifetime. -- [`TransformMap`](./transform_map.md) — the per-field conversion function, and the extension point. -- [`TransformMapFields`](./transform_map_fields.md) — that conversion lifted across a whole record. -- [`HasBuilder`](../builder/has_builder.md) — uses `IsPresent`/`IsNothing` to track which fields are filled. -- [`ExtractField`](../variant/extract_field.md) — uses `IsPresent`/`IsVoid` to track which variants remain. -- [`UpdateField`](../builder/update_field.md) — the primitive that moves a field from one marker to another. -- [`MapFields`](./map_fields.md) — applies one marker across a whole type-level list. -- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — generates the partial types these markers +- [`MapTypeRef`](./map_type_ref.md): the same idea for borrowed views, with a lifetime. +- [`TransformMap`](./transform_map.md): the per-field conversion function, and the extension point. +- [`TransformMapFields`](./transform_map_fields.md): that conversion lifted across a whole record. +- [`HasBuilder`](../builder/has_builder.md): uses `IsPresent`/`IsNothing` to track which fields are filled. +- [`ExtractField`](../variant/extract_field.md): uses `IsPresent`/`IsVoid` to track which variants remain. +- [`UpdateField`](../builder/update_field.md): the primitive that moves a field from one marker to another. +- [`MapFields`](./map_fields.md): applies one marker across a whole type-level list. +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md): generates the partial types these markers parameterize. -- [Type-level lists](../../types/index.md) — where the uninhabited `Void` comes from. +- [Type-level lists](../../types/index.md): where the uninhabited `Void` comes from. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — presence tracking on a partial record. -- [Extensible variants](/docs/concepts/extensible-variants) — possibility tracking on a partial variant. +- [Extensible records](/docs/concepts/extensible-records): presence tracking on a partial record. +- [Extensible variants](/docs/concepts/extensible-variants): possibility tracking on a partial variant. ## Source -- [`map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type.rs) - — the trait -- [`impls/map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type.rs) - — `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` +- [`map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type.rs): + the trait +- [`impls/map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type.rs): + `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` --- diff --git a/docs/reference/traits/type-level/map_type_ref.md b/docs/reference/traits/type-level/map_type_ref.md index 4e7fa27c..aa1ea003 100644 --- a/docs/reference/traits/type-level/map_type_ref.md +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -48,7 +48,7 @@ from outliving it either. That is more machinery than [`MapType`](./map_type.md) ## Usage -**`IsRef` and `IsMut` are in the prelude; `IsOwned` is not** — import it from `cgp::core::field::impls`. +**`IsRef` and `IsMut` are in the prelude; `IsOwned` is not.** Import it from `cgp::core::field::impls`. The trait itself comes with the prelude. Three markers implement it: ```rust @@ -97,8 +97,8 @@ if let Ok(circle) = shape } ``` -Neither call names a marker. What the markers do is decide the type the payload comes out as — `&Circle` -in the first case, `&mut Circle` in the second — while the per-field +Neither call names a marker. What the markers do is decide the type the payload comes out as (`&Circle` +in the first case, `&mut Circle` in the second) while the per-field [`MapType`](./map_type.md) markers track which variants are still possible. ## When to use it @@ -157,31 +157,31 @@ usually means the owned and borrowed forms have been crossed. `MapType` bound, and eliding the lifetime rarely works. **A mutable extractor cannot coexist with another borrow of the same value**, which is ordinary borrow -checking rather than anything CGP adds — but it surfaces as an error about the companion type, which +checking rather than anything CGP adds, but it surfaces as an error about the companion type, which reads as though the machinery is at fault. ## Related constructs -- [`MapType`](./map_type.md) — the per-field presence marker this composes with. -- [`HasExtractorRef`](../variant/has_extractor_ref.md) and [`HasExtractorMut`](../variant/has_extractor_mut.md) — the two +- [`MapType`](./map_type.md): the per-field presence marker this composes with. +- [`HasExtractorRef`](../variant/has_extractor_ref.md) and [`HasExtractorMut`](../variant/has_extractor_mut.md): the two accessors that fix the outer marker. -- [`ExtractField`](../variant/extract_field.md) — the narrowing that works identically through a borrow. -- [`ToFieldsRef`](../shape/to_fields_ref.md) — the record side's answer to the same problem. -- [`HasFieldsRef`](../shape/has_fields_ref.md) — the borrowed shape it produces. -- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the borrowed companion. -- [Type-level lists](../../types/index.md) — the `Either`/`Void` chain underneath. +- [`ExtractField`](../variant/extract_field.md): the narrowing that works identically through a borrow. +- [`ToFieldsRef`](../shape/to_fields_ref.md): the record side's answer to the same problem. +- [`HasFieldsRef`](../shape/has_fields_ref.md): the borrowed shape it produces. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md): generates the borrowed companion. +- [Type-level lists](../../types/index.md): the `Either`/`Void` chain underneath. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — matching a variant without consuming the +- [Extensible variants](/docs/concepts/extensible-variants): matching a variant without consuming the value. ## Source -- [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type_ref.rs) - — the trait -- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) - — `IsRef`, `IsMut`, `IsOwned` +- [`map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_type_ref.rs): + the trait +- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs): + `IsRef`, `IsMut`, `IsOwned` --- diff --git a/docs/reference/traits/type-level/transform_map.md b/docs/reference/traits/type-level/transform_map.md index 7a3d4339..84146f24 100644 --- a/docs/reference/traits/type-level/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -37,7 +37,7 @@ produce the same field in state `M2`. ## Usage **It is not in the prelude.** Import it from `cgp::core::field::traits`, along with any non-prelude -marker you name — `IsOptional` comes from `cgp::core::field::impls`: +marker you name; `IsOptional` comes from `cgp::core::field::impls`: ```rust use cgp::core::field::impls::IsOptional; @@ -48,7 +48,7 @@ The trait is implemented on a **transform marker**, a zero-sized type you declar and exists only to name the set of conversions, exactly as a provider does elsewhere in CGP. **A transform needs an impl for every source marker a field might currently be in.** That is the rule -that decides how many impls you write, and getting it wrong is the usual failure — the walk simply does +that decides how many impls you write, and getting it wrong is the usual failure: the walk does not resolve, and the error names the missing `TransformMap` impl rather than the field. ## Examples @@ -83,7 +83,7 @@ impl TransformMap for FillDefaults { Read that as three cases of one rule: a present field passes through, an absent one becomes its default, and an optional one becomes its contents or the default. Note how each signature's argument type is the -source marker's `Map` — `T`, then `()`, then `Option` — which makes the three impls +source marker's `Map` (`T`, then `()`, then `Option`), which makes the three impls non-overlapping. Because all three target `IsPresent`, applying `FillDefaults` through @@ -101,8 +101,8 @@ and reading it here is the shortest route to understanding that layer. optional finalization. Both already exist, built on exactly this, and [`TransformMapDefault`](../optional/transform_map_default.md) and [`TransformOptional`](../optional/transform_optional.md) are the two markers it ships. -- **Implement `TransformMap`** for a conversion those do not cover — a validating transform, one that - logs, one that fills from something other than `Default`. +- **Implement `TransformMap`** for a conversion those do not cover: a validating transform, one that + logs, or one that fills from something other than `Default`. - **Use [`TransformMapFields`](./transform_map_fields.md)** to apply what you have written. This trait converts one field; that one walks a whole record. - **Do not implement [`MapType`](./map_type.md) for a new marker** and expect the derives to use it. A @@ -117,8 +117,8 @@ argument type of `::Map`, which normalizes to `()`, and That lets three impls for one marker coexist without overlapping: they differ in `M1`. [`TransformMapFields`](./transform_map_fields.md) calls this. For each field of the target's -[`HasFields`](../shape/has_fields.md) shape, it uses [`UpdateField`](../builder/update_field.md) to take the field out — -learning the marker it was in — applies `Transform::transform_mapped`, and writes the result back under +[`HasFields`](../shape/has_fields.md) shape, it uses [`UpdateField`](../builder/update_field.md) to take the field out +(learning the marker it was in), applies `Transform::transform_mapped`, and writes the result back under the target marker. Two consequences follow from that construction, and both explain limits you might otherwise trip over. @@ -150,25 +150,25 @@ layer's payoff comes from every field landing in one state, usually `IsPresent`. ## Related constructs -- [`TransformMapFields`](./transform_map_fields.md) — lifts this across a whole partial record. -- [`MapType`](./map_type.md) — the markers naming each state, and the trait this supplies the missing +- [`TransformMapFields`](./transform_map_fields.md): lifts this across a whole partial record. +- [`MapType`](./map_type.md): the markers naming each state, and the trait this supplies the missing half of. -- [`TransformMapDefault`](../optional/transform_map_default.md) and [`TransformOptional`](../optional/transform_optional.md) - — the two markers CGP ships, and the models to copy. -- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) — the capability built from the first of +- [`TransformMapDefault`](../optional/transform_map_default.md) and [`TransformOptional`](../optional/transform_optional.md): + the two markers CGP ships, and the models to copy. +- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md): the capability built from the first of them. -- [`UpdateField`](../builder/update_field.md) — the primitive the walk uses to take a field out and write it back. -- [`FinalizeBuild`](../builder/finalize_build.md) — what an all-`IsPresent` result is accepted by. -- [`HasFields`](../shape/has_fields.md) — the shape the walk follows. +- [`UpdateField`](../builder/update_field.md): the primitive the walk uses to take a field out and write it back. +- [`FinalizeBuild`](../builder/finalize_build.md): what an all-`IsPresent` result is accepted by. +- [`HasFields`](../shape/has_fields.md): the shape the walk follows. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and how their states change. +- [Extensible records](/docs/concepts/extensible-records): partial records and how their states change. ## Source -- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs) - — `TransformMap` and `TransformMapFields` +- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs): + `TransformMap` and `TransformMapFields` --- diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index a4a55272..22ac48b6 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -55,7 +55,7 @@ use cgp::core::field::traits::TransformMapFields; ``` It is implemented for any [`PartialData`](../builder/partial_data.md) whose fields the transform can convert, so -there is nothing to implement — what you supply is the `Transform` marker, by writing +there is nothing to implement. What you supply is the `Transform` marker, by writing [`TransformMap`](./transform_map.md) impls for it. The two type parameters are usually inferred from the surrounding bound rather than written at a call @@ -107,8 +107,8 @@ layer requires exactly that. ## Under the hood `TransformMapFields` walks the target's [`HasFields`](../shape/has_fields.md) product one entry at a time. For -each `Field` it uses [`UpdateField`](../builder/update_field.md) **twice**: it takes the field out — -replacing its marker with `IsNothing` and reading what the marker *was* — applies +each `Field` it uses [`UpdateField`](../builder/update_field.md) **twice**: it takes the field out +(replacing its marker with `IsNothing` and reading what the marker *was*), applies `Transform::transform_mapped` to convert the value into the `TargetMap` wrapping, then writes it back under `TargetMap`. @@ -116,7 +116,7 @@ So the result type has every field re-marked to `TargetMap`, with the values con things follow from that construction, and both explain limits you might otherwise trip over. **The transform must have an impl for every source marker a field might currently be in**, or the walk -does not resolve — which is why a transform like `FillDefaults` needs three +does not resolve, which is why a transform like `FillDefaults` needs three [`TransformMap`](./transform_map.md) impls rather than one. **The recursion is driven by the target's shape**, so it re-marks exactly the fields the concrete struct @@ -134,7 +134,7 @@ impl for one field's source marker, not the record, so it reads as being about a about the transform being incomplete. **`Output` is a partial type, not the finished struct.** Finalizing is still -[`FinalizeBuild`](../builder/finalize_build.md)'s job — this trait only guarantees the configuration that impl +[`FinalizeBuild`](../builder/finalize_build.md)'s job. This trait only guarantees the configuration that impl requires. **It walks every field.** For a single field's transition, [`UpdateField`](../builder/update_field.md) is the @@ -148,24 +148,24 @@ with [`HasBuilder`](../builder/has_builder.md) or [`IntoBuilder`](../builder/int ## Related constructs -- [`TransformMap`](./transform_map.md) — the per-field conversion this lifts. -- [`MapType`](./map_type.md) — the markers naming each state. -- [`UpdateField`](../builder/update_field.md) — the primitive the walk calls twice per field. -- [`PartialData`](../builder/partial_data.md) — what a partial value is, and the bound this requires. -- [`FinalizeBuild`](../builder/finalize_build.md) — what an all-`IsPresent` result is accepted by. -- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and [`ToOptional`](../optional/to_optional.md) — the +- [`TransformMap`](./transform_map.md): the per-field conversion this lifts. +- [`MapType`](./map_type.md): the markers naming each state. +- [`UpdateField`](../builder/update_field.md): the primitive the walk calls twice per field. +- [`PartialData`](../builder/partial_data.md): what a partial value is, and the bound this requires. +- [`FinalizeBuild`](../builder/finalize_build.md): what an all-`IsPresent` result is accepted by. +- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and [`ToOptional`](../optional/to_optional.md): the two capabilities built directly on this. -- [`MapFields`](./map_fields.md) — the type-level counterpart. -- [`HasFields`](../shape/has_fields.md) — the shape the walk follows. +- [`MapFields`](./map_fields.md): the type-level counterpart. +- [`HasFields`](../shape/has_fields.md): the shape the walk follows. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — partial records and how their states change. +- [Extensible records](/docs/concepts/extensible-records): partial records and how their states change. ## Source -- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs) - — `TransformMapFields` and `TransformMap` +- [`transform_map.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/transform_map.rs): + `TransformMapFields` and `TransformMap` --- diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index 1ac96ead..4cb4f8a1 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -18,8 +18,8 @@ wanted. is still possible**, so attempting the same variant twice is a compile error rather than a guaranteed miss. -Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** — -a value of it cannot exist — and [`FinalizeExtract`](./finalize_extract.md) closes the chain with +Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** +(a value of it cannot exist), and [`FinalizeExtract`](./finalize_extract.md) closes the chain with no wildcard and no panic path. Add a variant to the enum and the final remainder becomes inhabited again, so the code stops compiling until it is handled. @@ -49,7 +49,7 @@ extractor with this one variant ruled out. `extract_field` consumes the extracto **It is in the prelude**, so `use cgp::prelude::*;` is enough. -`Self` is an extractor rather than the enum, so a chain begins by obtaining one — +`Self` is an extractor rather than the enum, so a chain begins by obtaining one: [`to_extractor`](./has_extractor.md) to consume the value, [`extractor_ref`](./has_extractor_ref.md) to borrow it, or [`extractor_mut`](./has_extractor_mut.md) to borrow it mutably. Which one you pick decides whether the payloads come out owned, shared, or mutable; the narrowing is identical in all three. @@ -176,31 +176,31 @@ reason to prefer the [dispatch combinators](../../providers/dispatch/index.md). ## Related constructs - [`HasExtractor`](./has_extractor.md), [`HasExtractorRef`](./has_extractor_ref.md), and - [`HasExtractorMut`](./has_extractor_mut.md) — the three ways to obtain an extractor. + [`HasExtractorMut`](./has_extractor_mut.md): the three ways to obtain an extractor. - [`FinalizeExtract`](./finalize_extract.md) and - [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. -- [`FromVariant`](./from_variant.md) — the construction counterpart. -- [`HasBuilder`](../builder/has_builder.md) — the struct analogue of the whole family. -- [`MapType`](../type-level/map_type.md) — the `IsPresent`/`IsVoid` markers, and where the contrast with `IsNothing` + [`FinalizeExtractResult`](./finalize_extract_result.md): how a chain ends. +- [`FromVariant`](./from_variant.md): the construction counterpart. +- [`HasBuilder`](../builder/has_builder.md): the struct analogue of the whole family. +- [`MapType`](../type-level/map_type.md): the `IsPresent`/`IsVoid` markers, and where the contrast with `IsNothing` is explained. -- [`CanDowncast`](../casting/can_downcast.md) — narrowing to another enum rather than to a payload, built on this. -- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the partial enums and every +- [`CanDowncast`](../casting/can_downcast.md): narrowing to another enum rather than to a payload, built on this. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md): generates the partial enums and every impl here. -- [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain for +- [Dispatch combinators](../../providers/dispatch/index.md): the providers that build the chain for you. -- [Type-level lists](../../types/index.md) — `Either`/`Void`, where the uninhabited terminator +- [Type-level lists](../../types/index.md): `Either`/`Void`, where the uninhabited terminator comes from. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — partial variants, the exhaustiveness +- [Extensible variants](/docs/concepts/extensible-variants): partial variants, the exhaustiveness argument, and the extensible visitor pattern. -- [Dispatching](/docs/concepts/dispatching) — routing a variant to the implementation that handles it. +- [Dispatching](/docs/concepts/dispatching): routing a variant to the implementation that handles it. ## Source -- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) - — `ExtractField` and the rest of the family +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs): + `ExtractField` and the rest of the family --- diff --git a/docs/reference/traits/variant/finalize_extract.md b/docs/reference/traits/variant/finalize_extract.md index c338057c..49fd0d38 100644 --- a/docs/reference/traits/variant/finalize_extract.md +++ b/docs/reference/traits/variant/finalize_extract.md @@ -10,7 +10,7 @@ Discharging an extractor that has nothing left in it. ## Overview An [extraction chain](./extract_field.md) 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 +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, because there is no value to return it from: @@ -109,8 +109,8 @@ any return type for the same reason. So a caller reaches `finalize_extract` only variant, and the compiler accepts the discharge with no 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 +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 exactly why a builder needs an explicit all-present [`FinalizeBuild`](../builder/finalize_build.md) impl while an extractor can discharge its remainder with an empty `match`. @@ -138,24 +138,24 @@ that cannot occur. ## Related constructs -- [`FinalizeExtractResult`](./finalize_extract_result.md) — the form that closes a chain from a `Result`. -- [`ExtractField`](./extract_field.md) — the narrowing that leads here. -- [`HasExtractor`](./has_extractor.md) — where a chain begins. -- [`FinalizeBuild`](../builder/finalize_build.md) — the record family's ending, sound for the opposite reason. -- [`MapType`](../type-level/map_type.md) — the `IsVoid` marker the argument rests on. -- [Type-level lists](../../types/index.md) — where the uninhabited `Void` comes from. -- [`CanUpcast`](../casting/can_upcast.md) — a cast whose total walk ends with this same discharge. -- [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain. -- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates this impl. +- [`FinalizeExtractResult`](./finalize_extract_result.md): the form that closes a chain from a `Result`. +- [`ExtractField`](./extract_field.md): the narrowing that leads here. +- [`HasExtractor`](./has_extractor.md): where a chain begins. +- [`FinalizeBuild`](../builder/finalize_build.md): the record family's ending, sound for the opposite reason. +- [`MapType`](../type-level/map_type.md): the `IsVoid` marker the argument rests on. +- [Type-level lists](../../types/index.md): where the uninhabited `Void` comes from. +- [`CanUpcast`](../casting/can_upcast.md): a cast whose total walk ends with this same discharge. +- [Dispatch combinators](../../providers/dispatch/index.md): the providers that build the chain. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md): generates this impl. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — the exhaustiveness argument, in full. +- [Extensible variants](/docs/concepts/extensible-variants): the exhaustiveness argument, in full. ## Source -- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) - — `FinalizeExtract` and the rest of the family +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs): + `FinalizeExtract` and the rest of the family --- diff --git a/docs/reference/traits/variant/finalize_extract_result.md b/docs/reference/traits/variant/finalize_extract_result.md index 5a2c8a07..aced8593 100644 --- a/docs/reference/traits/variant/finalize_extract_result.md +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -47,7 +47,7 @@ where ## Usage -**It is not in the prelude** — the one member of the extractor family that is not. Import it from +**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: ```rust @@ -90,7 +90,7 @@ tried, which makes it a proof rather than an assertion. Calling it one step early does not compile: ```rust -// error: the trait bound is not satisfied — Circle is still possible, +// error: the trait bound is not satisfied: Circle is still possible, // so the remainder is inhabited and cannot be discharged let rect = shape .to_extractor() @@ -146,25 +146,25 @@ bound stops being satisfied. ## Related constructs -- [`FinalizeExtract`](./finalize_extract.md) — the underlying discharge, and the full exhaustiveness +- [`FinalizeExtract`](./finalize_extract.md): the underlying discharge, and the full exhaustiveness argument. -- [`ExtractField`](./extract_field.md) — the narrowing that produces the `Result` this collapses. -- [`HasExtractor`](./has_extractor.md) — where a chain begins. -- [`FinalizeBuild`](../builder/finalize_build.md) — the record family's ending. -- [Type-level lists](../../types/index.md) — where the uninhabited `Void` comes from. -- [Dispatch combinators](../../providers/dispatch/index.md) — the providers that build the chain for +- [`ExtractField`](./extract_field.md): the narrowing that produces the `Result` this collapses. +- [`HasExtractor`](./has_extractor.md): where a chain begins. +- [`FinalizeBuild`](../builder/finalize_build.md): the record family's ending. +- [Type-level lists](../../types/index.md): where the uninhabited `Void` comes from. +- [Dispatch combinators](../../providers/dispatch/index.md): the providers that build the chain for you. -- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — what makes an enum extractable. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md): what makes an enum extractable. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — the exhaustiveness argument and the +- [Extensible variants](/docs/concepts/extensible-variants): the exhaustiveness argument and the extensible visitor pattern. ## Source -- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) - — `FinalizeExtractResult` and the rest of the family +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs): + `FinalizeExtractResult` and the rest of the family --- diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index 1fd376fc..485778c0 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -10,7 +10,7 @@ Generic construction of an enum from a named variant. ## Overview `Shape::Circle(circle)` names two things: the enum and the variant. That is fine where both are known and -useless to code that knows neither — a routine handed a payload and told which variant to wrap it in cannot +useless to code that knows neither: a routine handed a payload and told which variant to wrap it in cannot write that expression. `FromVariant` gives it a way to. The variant is selected by its *name as a type*, so the choice becomes a @@ -191,19 +191,19 @@ struct. ## Related constructs -- [`#[derive(FromVariant)]`](../../derives/derive_from_variant.md) — generates the per-variant impls; what you +- [`#[derive(FromVariant)]`](../../derives/derive_from_variant.md): generates the per-variant impls; what you write. -- [`ExtractField`](./extract_field.md) — the reverse operation, and the trait most often derived alongside. -- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — bundles this with the extractor and the shape. -- [`HasBuilder`](../builder/has_builder.md) — the struct analogue: setting one field rather than choosing one variant. -- [`Symbol!`](../../macros/symbol.md) — the tag that names a variant. -- [`CanUpcast`](../casting/can_upcast.md) — widening a narrow enum into a wider one, built on these constructors. -- [`HasFields`](../shape/has_fields.md) — the variant shape a cast walks while rebuilding. -- [Dispatch combinators](../../providers/dispatch/index.md) — where variant construction meets routing. +- [`ExtractField`](./extract_field.md): the reverse operation, and the trait most often derived alongside. +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md): bundles this with the extractor and the shape. +- [`HasBuilder`](../builder/has_builder.md): the struct analogue: setting one field rather than choosing one variant. +- [`Symbol!`](../../macros/symbol.md): the tag that names a variant. +- [`CanUpcast`](../casting/can_upcast.md): widening a narrow enum into a wider one, built on these constructors. +- [`HasFields`](../shape/has_fields.md): the variant shape a cast walks while rebuilding. +- [Dispatch combinators](../../providers/dispatch/index.md): where variant construction meets routing. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — construction by name, and building through a +- [Extensible variants](/docs/concepts/extensible-variants): construction by name, and building through a small local enum before widening. ## Source diff --git a/docs/reference/traits/variant/has_extractor.md b/docs/reference/traits/variant/has_extractor.md index 7e02a1b8..ced27411 100644 --- a/docs/reference/traits/variant/has_extractor.md +++ b/docs/reference/traits/variant/has_extractor.md @@ -143,36 +143,36 @@ so it is neither `Debug` nor `PartialEq` however the enum is derived. **`Extractor` is not the enum.** A signature that returns `Self::Extractor` is returning a companion type, and naming it in a public API exposes a generated name. -**Every variant must carry exactly one unnamed payload** for the derive to apply at all — the family's +**Every variant must carry exactly one unnamed payload** for the derive to apply at all, the family's one real restriction, covered on the [derive's page](../../derives/derive_extract_field.md). ## Related constructs -- [`ExtractField`](./extract_field.md) — what narrows the extractor this produces. -- [`HasExtractorRef`](./has_extractor_ref.md) and [`HasExtractorMut`](./has_extractor_mut.md) — the two +- [`ExtractField`](./extract_field.md): what narrows the extractor this produces. +- [`HasExtractorRef`](./has_extractor_ref.md) and [`HasExtractorMut`](./has_extractor_mut.md): the two borrowing accessors. - [`FinalizeExtract`](./finalize_extract.md) and - [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. -- [`FromVariant`](./from_variant.md) — constructing an enum from one named variant. -- [`PartialData`](../builder/partial_data.md) — what names the enum a companion belongs to. -- [`MapType`](../type-level/map_type.md) — the `IsPresent`/`IsVoid` markers the companion is parameterized by. -- [`CanUpcast`](../casting/can_upcast.md) and [`CanDowncast`](../casting/can_downcast.md) — casts built on this recursion. -- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the companion and this + [`FinalizeExtractResult`](./finalize_extract_result.md): how a chain ends. +- [`FromVariant`](./from_variant.md): constructing an enum from one named variant. +- [`PartialData`](../builder/partial_data.md): what names the enum a companion belongs to. +- [`MapType`](../type-level/map_type.md): the `IsPresent`/`IsVoid` markers the companion is parameterized by. +- [`CanUpcast`](../casting/can_upcast.md) and [`CanDowncast`](../casting/can_downcast.md): casts built on this recursion. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md): generates the companion and this impl. -- [`HasBuilder`](../builder/has_builder.md) — the struct analogue. +- [`HasBuilder`](../builder/has_builder.md): the struct analogue. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — partial variants and the extensible visitor +- [Extensible variants](/docs/concepts/extensible-variants): partial variants and the extensible visitor pattern. ## Source -- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) - — `HasExtractor` and the rest of the family -- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs) - — `PartialData`, which the companions also implement +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs): + `HasExtractor` and the rest of the family +- [`partial_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/partial_data.rs): + `PartialData`, which the companions also implement --- diff --git a/docs/reference/traits/variant/has_extractor_mut.md b/docs/reference/traits/variant/has_extractor_mut.md index 81cdee6f..23cb4fb0 100644 --- a/docs/reference/traits/variant/has_extractor_mut.md +++ b/docs/reference/traits/variant/has_extractor_mut.md @@ -129,27 +129,27 @@ generic over the [`MapTypeRef`](../type-level/map_type_ref.md) marker too. ## Related constructs -- [`HasExtractorRef`](./has_extractor_ref.md) — the shared-borrow accessor, and the one to prefer. -- [`HasExtractor`](./has_extractor.md) — the owning accessor, and where the group is compared. -- [`ExtractField`](./extract_field.md) — the narrowing, identical through a mutable borrow. +- [`HasExtractorRef`](./has_extractor_ref.md): the shared-borrow accessor, and the one to prefer. +- [`HasExtractor`](./has_extractor.md): the owning accessor, and where the group is compared. +- [`ExtractField`](./extract_field.md): the narrowing, identical through a mutable borrow. - [`FinalizeExtract`](./finalize_extract.md) and - [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. -- [`MapTypeRef`](../type-level/map_type_ref.md) — the `IsMut` marker this fixes. -- [`MapType`](../type-level/map_type.md) — the per-variant markers it composes with. -- [`HasFieldMut`](../field-access/has_field_mut.md) — the record side's mutable access. -- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the borrowed companion. + [`FinalizeExtractResult`](./finalize_extract_result.md): how a chain ends. +- [`MapTypeRef`](../type-level/map_type_ref.md): the `IsMut` marker this fixes. +- [`MapType`](../type-level/map_type.md): the per-variant markers it composes with. +- [`HasFieldMut`](../field-access/has_field_mut.md): the record side's mutable access. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md): generates the borrowed companion. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — matching a variant without consuming the +- [Extensible variants](/docs/concepts/extensible-variants): matching a variant without consuming the value. ## Source -- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) - — `HasExtractorMut` and the rest of the family -- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) - — the `IsMut` marker +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs): + `HasExtractorMut` and the rest of the family +- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs): + the `IsMut` marker --- diff --git a/docs/reference/traits/variant/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md index 2eec701f..e3091550 100644 --- a/docs/reference/traits/variant/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -10,7 +10,7 @@ Obtaining an extractor that borrows the value rather than consuming it. ## Overview [`HasExtractor`](./has_extractor.md) consumes an enum to produce an extractor with owned payloads. Code -that only *reads* a variant — checking it, measuring it, rendering it — should not have to give up the +that only *reads* a variant (checking it, measuring it, rendering it) should not have to give up the value. `HasExtractorRef` is the borrowing accessor. Payloads come out as shared references and the original survives. **The narrowing works identically**: @@ -81,7 +81,7 @@ full chain narrows the same way, with each remainder also borrowing. - **[`HasExtractor`](./has_extractor.md)** only when the payload must be moved out. - **A `match`** when the enum is concrete. This family is for code that cannot name it. - **[`ToFieldsRef`](../shape/to_fields_ref.md)** when what you want is the value's borrowed *shape* rather than - a narrowing chain — the same borrow-rather-than-consume idea, applied to the whole-shape view. + a narrowing chain: the same borrow-rather-than-consume idea, applied to the whole-shape view. ## Under the hood @@ -101,8 +101,8 @@ The borrowed accessor uses the **same partial enum** as the owning one, with an // } ``` -Read the nesting outward: the [`MapTypeRef`](../type-level/map_type_ref.md) marker decides *how* a payload is held — -`IsRef::Map<'a, T>` is `&'a T` — and the per-variant [`MapType`](../type-level/map_type.md) markers decide *whether* +Read the nesting outward: the [`MapTypeRef`](../type-level/map_type_ref.md) marker decides *how* a payload is held +(`IsRef::Map<'a, T>` is `&'a T`), and the per-variant [`MapType`](../type-level/map_type.md) markers decide *whether* it is still possible. The two axes are independent, which is precisely why narrowing behaves the same through a borrow as through an owned value. @@ -128,27 +128,27 @@ one, or be generic over the [`MapTypeRef`](../type-level/map_type_ref.md) marker ## Related constructs -- [`HasExtractor`](./has_extractor.md) — the owning accessor, and where the group is compared. -- [`HasExtractorMut`](./has_extractor_mut.md) — the mutable accessor. -- [`ExtractField`](./extract_field.md) — the narrowing, identical through a borrow. +- [`HasExtractor`](./has_extractor.md): the owning accessor, and where the group is compared. +- [`HasExtractorMut`](./has_extractor_mut.md): the mutable accessor. +- [`ExtractField`](./extract_field.md): the narrowing, identical through a borrow. - [`FinalizeExtract`](./finalize_extract.md) and - [`FinalizeExtractResult`](./finalize_extract_result.md) — how a chain ends. -- [`MapTypeRef`](../type-level/map_type_ref.md) — the `IsRef` marker this fixes. -- [`MapType`](../type-level/map_type.md) — the per-variant markers it composes with. -- [`ToFieldsRef`](../shape/to_fields_ref.md) — the record side's borrow-rather-than-consume view. -- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) — generates the borrowed companion. + [`FinalizeExtractResult`](./finalize_extract_result.md): how a chain ends. +- [`MapTypeRef`](../type-level/map_type_ref.md): the `IsRef` marker this fixes. +- [`MapType`](../type-level/map_type.md): the per-variant markers it composes with. +- [`ToFieldsRef`](../shape/to_fields_ref.md): the record side's borrow-rather-than-consume view. +- [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md): generates the borrowed companion. The ideas behind it: -- [Extensible variants](/docs/concepts/extensible-variants) — matching a variant without consuming the +- [Extensible variants](/docs/concepts/extensible-variants): matching a variant without consuming the value. ## Source -- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) - — `HasExtractorRef` and the rest of the family -- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs) - — the `IsRef` marker +- [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs): + `HasExtractorRef` and the rest of the family +- [`impls/map_type_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type_ref.rs): + the `IsRef` marker --- diff --git a/docs/reference/traits/variant/index.md b/docs/reference/traits/variant/index.md index 699921fa..bf7b1f52 100644 --- a/docs/reference/traits/variant/index.md +++ b/docs/reference/traits/variant/index.md @@ -32,9 +32,9 @@ result. ## The ideas behind them -- [Extensible variants](/docs/concepts/extensible-variants) — partial variants, the exhaustiveness +- [Extensible variants](/docs/concepts/extensible-variants): partial variants, the exhaustiveness argument, and the extensible visitor pattern. -- [Dispatching](/docs/concepts/dispatching) — routing a variant to the implementation that handles it. +- [Dispatching](/docs/concepts/dispatching): routing a variant to the implementation that handles it. --- diff --git a/docs/reference/traits/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md index 2eb7bfd5..2a549ec3 100644 --- a/docs/reference/traits/wiring/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -26,15 +26,15 @@ are met. That check happens the first time the capability is actually called, wh from the wiring and produces a bad error when it fails. `CanUseComponent` is the bound that forces the check early, and it exists because the obvious way of asking -does not work. Asking "does this **context** — the type the capability runs against — implement the consumer +does not work. Asking "does this **context** (the type the capability runs against) implement the consumer trait?" makes the compiler report the outermost unmet bound, usually a bare "the provider does not implement the provider trait", and hide the reasoning behind it. The root cause, often one absent field, never appears. `CanUseComponent` reframes the same question along a path the compiler will explain. It holds when two things hold together: -- the context **delegates** the component — it has a [`DelegateComponent`](./delegate_component.md) entry; -- the delegated provider **is a valid provider** for that exact context and parameters — it satisfies +- the context **delegates** the component: it has a [`DelegateComponent`](./delegate_component.md) entry; +- the delegated provider **is a valid provider** for that exact context and parameters: it satisfies [`IsProviderFor`](./is_provider_for.md). Because `IsProviderFor` carries the provider's real `where` bounds, requiring it forces the compiler to @@ -143,7 +143,7 @@ The check forces `Person: CanUseComponent`. Resolving it n and `Person` has no `name` field. The compiler reports the absent field **here**, at the check, rather than at some later `person.greet()`. -Rename the field to `name` and the block compiles and produces nothing — a passing check is a successful +Rename the field to `name` and the block compiles and produces nothing: a passing check is a successful build, with nothing added to the binary. ## When to use it @@ -166,13 +166,13 @@ compile and fail later. Which macro does it is a matter of scale. One case makes a context-side check actively wrong rather than merely unnecessary: **a provider bundle.** A [`delegate_components!`](../../macros/delegate_components.md) block with a leading `new` declares a provider that other contexts delegate to, not a context. Asserting `CanUseComponent` on it asks whether the bundle can use -each component *as a context* — a role it never plays — so the answer is uninformative either way. It passes +each component *as a context* (a role it never plays), so the answer is uninformative either way. It passes vacuously when the bundled providers need nothing from their context, and fails blaming the bundle when any of them needs something the real context would have supplied. Wire a bundle with plain `delegate_components!` and let a real context's check verify it, or assert `IsProviderFor` on it directly. Finally, not every unmet bound is a component. Some are ordinary or blanket traits, and no check macro can -verify those — they surface as themselves. +verify those. They surface as themselves. ## Under the hood @@ -203,7 +203,7 @@ statement as `Person: CanGreet`, even though in practice one follows the other. because the two questions produce different diagnostics. **Do not assert it on a provider bundle.** The question is meaningless there, and worse, it can pass -vacuously — so a green check on a bundle proves nothing. This is why +vacuously, so a green check on a bundle proves nothing. This is why [`delegate_and_check_components!`](../../macros/delegate_and_check_components.md) is wrong for a bundle. **`Params` follows the tuple rule.** One parameter directly, several as a tuple, `()` for none. A hand-written @@ -217,19 +217,19 @@ the binary. The cost is trait resolution at build time, which is the trade the c ## Related constructs -- [`check_components!`](../../macros/check_components.md) — the macro that asserts this trait; what you write. -- [`delegate_and_check_components!`](../../macros/delegate_and_check_components.md) — wires and checks at once, +- [`check_components!`](../../macros/check_components.md): the macro that asserts this trait; what you write. +- [`delegate_and_check_components!`](../../macros/delegate_and_check_components.md): wires and checks at once, for basic wiring. -- [`DelegateComponent`](./delegate_component.md) — the first of the two bounds: the context must delegate. -- [`IsProviderFor`](./is_provider_for.md) — the second bound, and the provider-indexed counterpart of this +- [`DelegateComponent`](./delegate_component.md): the first of the two bounds: the context must delegate. +- [`IsProviderFor`](./is_provider_for.md): the second bound, and the provider-indexed counterpart of this trait. -- [`#[cgp_component]`](../../macros/cgp_component.md) — defines the components being checked. -- [Compile errors](../../errors.md) — the shapes these checks produce, and how to read them. +- [`#[cgp_component]`](../../macros/cgp_component.md): defines the components being checked. +- [Compile errors](../../errors.md): the shapes these checks produce, and how to read them. The ideas behind it: -- [Check traits](/docs/concepts/check-traits) — why wiring is lazy, and what a compile-time assertion buys. -- [Higher-order providers](/docs/concepts/higher-order-providers) — the case where a context-side check is not +- [Check traits](/docs/concepts/check-traits): why wiring is lazy, and what a compile-time assertion buys. +- [Higher-order providers](/docs/concepts/higher-order-providers): the case where a context-side check is not enough. ## Source diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index f76a62f0..a888c3ac 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -21,8 +21,8 @@ wiring error naming this trait is legible. ## Overview -Wiring a **context** — the type the capability runs against, which supplies the values it needs as its -fields — means recording which implementation it uses for each capability. `DelegateComponent` is the trait +Wiring a **context** (the type the capability runs against, which supplies the values it needs as its +fields) means recording which implementation it uses for each capability. `DelegateComponent` is the trait that record is made of. One impl is one entry: ```rust @@ -42,7 +42,7 @@ page is that it appears by name in compiler errors, and that reading it is how y One thing to notice early, because it explains why the trait is so general: **the key does not have to be a component name.** When it is, the entry makes the context inherit the component's provider trait. When it -is any other type — a shape, a tag, a path segment — the same trait is just a lookup table that a provider +is any other type (a shape, a tag, a path segment) the same trait is just a lookup table that a provider walks. One trait covers both, which is why it underlies both ordinary wiring and the inner dispatch tables. ## Definition @@ -98,23 +98,23 @@ error rather than a silent overwrite. The key's type decides what the entry *means*, and there are three shapes in practice. -A **component name** — `GreeterComponent`, `AreaCalculatorComponent` — is the ordinary case. An entry keyed +A **component name** (`GreeterComponent`, `AreaCalculatorComponent`) is the ordinary case. An entry keyed this way is read by the blanket impl that [`#[cgp_component]`](../../macros/cgp_component.md) generates, which concludes that the context has the component's provider trait, and from there its consumer trait. -An **arbitrary type** — a shape, a tag — makes the table a plain dispatch map with no provider trait +An **arbitrary type** (a shape, a tag) makes the table a plain dispatch map with no provider trait attached. This is what the nested tables inside [`UseDelegate`](../../providers/use_delegate.md) are, and what the `open` statement's per-key entries resolve through. -A **type-level path** — a [`PathCons`](../../types/path_cons.md) list built by -[`Path!`](../../macros/path.md) — is how namespaces key their entries, so a lookup walks one segment at a time. +A **type-level path** (a [`PathCons`](../../types/path_cons.md) list built by +[`Path!`](../../macros/path.md)) is how namespaces key their entries, so a lookup walks one segment at a time. [`RedirectLookup`](../../providers/redirect_lookup.md) is the provider that performs that walk. ### What owns a table `Self` is not always a context. A [`delegate_components!`](../../macros/delegate_components.md) block with a leading `new` declares a provider bundle that owns its own table, so several contexts can delegate a whole -group of components to it as one unit. Resolution is shallow — one read yields the immediate `Delegate` — +group of components to it as one unit. Resolution is shallow (one read yields the immediate `Delegate`), and chaining happens when that delegate is itself a table, which is exactly what a bundle is. ## Examples @@ -158,7 +158,7 @@ impl DelegateComponent for App { ``` From there the generated blanket impls take over: because `App` delegates `GreeterComponent`, it gets the -`Greeter` provider trait, and because it has that, it gets `CanGreet` — so `app.greet()` compiles. Swap +`Greeter` provider trait, and because it has that, it gets `CanGreet`, so `app.greet()` compiles. Swap `GreetHello` for another provider and only that one line changes. An arbitrary-key table looks identical and means something different. The nested-table syntax builds a @@ -182,13 +182,13 @@ at dispatch time to pick `RectangleArea` or `CircleArea` for the shape it was as **Write [`delegate_components!`](../../macros/delegate_components.md), not `DelegateComponent`.** That is the honest summary of this page: the trait is what you read, and the macro is what you write. The macro also emits the [`IsProviderFor`](./is_provider_for.md) forwarding impl beside each entry, which is what keeps a -missing dependency diagnosable — so a hand-written `DelegateComponent` impl gets you the wiring and loses +missing dependency diagnosable, so a hand-written `DelegateComponent` impl gets you the wiring and loses the error message. -There are two narrow reasons to name the trait yourself. +There are narrow reasons to name the trait yourself. -- **Reading an entry in generic code.** A provider that must resolve a key itself — a dispatcher, a - higher-order provider walking a table — bounds on `DelegateComponent` and projects `Delegate`. This +- **Reading an entry in generic code.** A provider that must resolve a key itself (a dispatcher, a + higher-order provider walking a table) bounds on `DelegateComponent` and projects `Delegate`. This is the one legitimate hand-written use, and it is a *read*. - **Recognizing it in an error.** `the trait bound App: DelegateComponent is not satisfied` means the context never wired that component. That is the most common wiring error there is, @@ -201,7 +201,7 @@ implementation is one of several, or is shared, or should compose with a wrapper ## Under the hood -The trait is the plainest thing in CGP — one associated type, no method — so the interesting part is what +The trait is the plainest thing in CGP (one associated type, no method), so the interesting part is what reads it. The provider blanket impl generated by [`#[cgp_component]`](../../macros/cgp_component.md) is the reader, and its body is itself a table lookup: it bounds the provider on `DelegateComponent` and forwards each method to `>::Delegate`. So the "routing" is @@ -226,7 +226,7 @@ add a wiring line or supply a dependency. **Two entries for the same key is a coherence error, not an override.** Wiring one component twice on one context reports `E0119` conflicting implementations. A namespace *can* be shadowed by a direct entry, -because the namespace side is a blanket impl rather than a second concrete one — but two concrete entries +because the namespace side is a blanket impl rather than a second concrete one, but two concrete entries always conflict. **`Self` is not always a context.** A provider bundle declared with `new` owns a table too, and reading an @@ -241,24 +241,24 @@ this is not it, and that is the point. ## Related constructs -- [`delegate_components!`](../../macros/delegate_components.md) — the macro that generates these impls; what +- [`delegate_components!`](../../macros/delegate_components.md): the macro that generates these impls; what you write instead of the trait. -- [`#[cgp_component]`](../../macros/cgp_component.md) — generates the blanket impl that reads the table. -- [`IsProviderFor`](./is_provider_for.md) — emitted beside each entry so a missing dependency stays +- [`#[cgp_component]`](../../macros/cgp_component.md): generates the blanket impl that reads the table. +- [`IsProviderFor`](./is_provider_for.md): emitted beside each entry so a missing dependency stays readable. -- [`CanUseComponent`](./can_use_component.md) — combines a delegation and a valid provider into one +- [`CanUseComponent`](./can_use_component.md): combines a delegation and a valid provider into one assertion. -- [`check_components!`](../../macros/check_components.md) — asserts that combination. -- [`UseDelegate`](../../providers/use_delegate.md) — reads an arbitrary-key table for per-type dispatch. -- [`RedirectLookup`](../../providers/redirect_lookup.md) — walks path-keyed entries; the namespace mechanism. -- [`DefaultNamespace`](../namespace/default_namespace.md) — the lookup traits a `namespace` header forwards through. +- [`check_components!`](../../macros/check_components.md): asserts that combination. +- [`UseDelegate`](../../providers/use_delegate.md): reads an arbitrary-key table for per-type dispatch. +- [`RedirectLookup`](../../providers/redirect_lookup.md): walks path-keyed entries; the namespace mechanism. +- [`DefaultNamespace`](../namespace/default_namespace.md): the lookup traits a `namespace` header forwards through. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the split this table +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the split this table connects. -- [Bypassing coherence](/docs/concepts/coherence) — why the choice is recorded per context at all. -- [Aggregate providers](/docs/concepts/aggregate-providers) — a table owned by a provider rather than a +- [Bypassing coherence](/docs/concepts/coherence): why the choice is recorded per context at all. +- [Aggregate providers](/docs/concepts/aggregate-providers): a table owned by a provider rather than a context. ## Source diff --git a/docs/reference/traits/wiring/index.md b/docs/reference/traits/wiring/index.md index b7a121e4..415603e8 100644 --- a/docs/reference/traits/wiring/index.md +++ b/docs/reference/traits/wiring/index.md @@ -9,32 +9,32 @@ The three traits every context's wiring rests on, and the ones a wiring error na ## Overview -Wiring a **context** — the type a capability runs against — records which provider it uses for each -component and checks that the provider's own requirements are met. Three traits carry that, and you +Wiring a **context**, the type a capability runs against, records which provider it uses for each +component and checks that the provider's own requirements are met. These traits carry that, and you read them far more often than you write them, because a [`delegate_components!`](../../macros/delegate_components.md) table generates the first two and a [`check_components!`](../../macros/check_components.md) block asserts the third. -The three build on one another. A context becomes a type-level table through +They build on one another. A context becomes a type-level table through [`DelegateComponent`](delegate_component.md), one entry per component. Each entry also carries an [`IsProviderFor`](is_provider_for.md) impl that re-exposes the chosen provider's `where` bounds, so a missing dependency is named rather than hidden. [`CanUseComponent`](can_use_component.md) combines the two into a single question that a check asserts: does the context delegate this component, and do its provider's requirements hold? -- [`DelegateComponent`](delegate_component.md) — the per-context table mapping a component to its +- [`DelegateComponent`](delegate_component.md): the per-context table mapping a component to its provider; what a wiring line becomes. -- [`IsProviderFor`](is_provider_for.md) — the marker that surfaces a provider's missing dependency by +- [`IsProviderFor`](is_provider_for.md): the marker that surfaces a provider's missing dependency by name, and the trait a `#[check_providers]` assertion names. -- [`CanUseComponent`](can_use_component.md) — the context-side check a `check_components!` block +- [`CanUseComponent`](can_use_component.md): the context-side check a `check_components!` block reduces to, holding only when a component is both delegated and satisfiable. ## The ideas behind them -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the split this wiring +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the split this wiring connects. -- [Bypassing coherence](/docs/concepts/coherence) — why the choice is recorded per context. -- [Check traits](/docs/concepts/check-traits) — why wiring is lazy, and how an assertion makes its +- [Bypassing coherence](/docs/concepts/coherence): why the choice is recorded per context. +- [Check traits](/docs/concepts/check-traits): why wiring is lazy, and how an assertion makes its failures readable. --- diff --git a/docs/reference/traits/wiring/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md index dacc596e..c0a35c1c 100644 --- a/docs/reference/traits/wiring/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -11,30 +11,30 @@ The marker supertrait that makes a provider's missing dependency show up by name ### Generated machinery -**You never write `IsProviderFor` yourself.** The provider macros — -[`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md), which also -covers `#[cgp_new_provider]` — derive it from the same `where` clause you already wrote. This page explains what they emit, because this trait is what a missing-dependency error +**You never write `IsProviderFor` yourself.** The provider macros, +[`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md) (which also +covers `#[cgp_new_provider]`), derive it from the same `where` clause you already wrote. This page explains what they emit, because this trait is what a missing-dependency error names, and reading that error is the reason to know it exists. ::: ## Overview -An implementation in CGP states what it needs from its **context** — the type the capability runs against — +An implementation in CGP states what it needs from its **context**, the type the capability runs against, in its own `where` clause: a field, an abstract type, another capability. When one of those requirements is not met, you want the compiler to say *which*. Left to itself, it will not. The reason is a specific behaviour of Rust's diagnostics. Asking "does this provider implement the provider -trait?" has two candidate answers in scope — the blanket impl that routes through the wiring table, and the -implementation you wrote — and when more than one impl could apply, Rust reports only that none matched and +trait?" has two candidate answers in scope (the blanket impl that routes through the wiring table, and the +implementation you wrote), and when more than one impl could apply, Rust reports only that none matched and withholds the per-candidate reasoning, because it cannot know which one you meant. The real cause, often a single absent field, never appears. `IsProviderFor` is a second path to the same question that Rust *will* explain. It is an empty marker trait, and the macros implement it for a provider under **exactly the same** `where` bounds as the provider trait itself. Every generated provider trait carries it as a supertrait, so asking whether a provider satisfies -`IsProviderFor` forces the compiler to evaluate those bounds — and because that question has only one -candidate impl, no blanket competing with it, the compiler commits to it and reports precisely which +`IsProviderFor` forces the compiler to evaluate those bounds, and because that question has only one +candidate impl, with no blanket competing with it, the compiler commits to it and reports precisely which constraint failed. **This is invisible plumbing until you read an error.** You never write it and never call it. It buys the @@ -59,7 +59,7 @@ extra generic parameters, and it defaults to the unit tuple `()` for a component several parameters are grouped is covered under [How `Params` is filled](#how-params-is-filled). The trait has no method and no associated item. [`#[cgp_component]`](../../macros/cgp_component.md) attaches it as a supertrait on every provider trait, so using a provider trait requires establishing -`IsProviderFor` first — which is why probing the marker probes the provider trait's whole dependency set. +`IsProviderFor` first, which is why probing the marker probes the provider trait's whole dependency set. The `#[diagnostic::on_unimplemented]` note points a reader at the missing `#[cgp_provider]` attribute when the marker impl is absent. @@ -73,8 +73,8 @@ operations are supplying `Params` correctly and, occasionally, asserting the mar This is the only part with a rule worth memorizing, and it is what a hand-written assertion gets wrong. - A component with **no** parameters uses the default, `()`. -- A component with **one** parameter passes it directly — `IsProviderFor`. -- A component with **several** groups them into a tuple — `IsProviderFor`. +- A component with **one** parameter passes it directly: `IsProviderFor`. +- A component with **several** groups them into a tuple: `IsProviderFor`. - A **lifetime** parameter is lifted into [`Life<'a>`](../../types/life.md), because the tuple holds types and a lifetime cannot sit there directly. @@ -91,7 +91,7 @@ where That holds exactly when `GreetHello`'s dependencies are satisfied for `App`. In practice you write this through the `#[check_providers(...)]` form of [`check_components!`](../../macros/check_components.md) rather -than by hand — which is the tool for localizing a failure inside a stack of +than by hand. That form is the tool for localizing a failure inside a stack of [higher-order providers](/docs/concepts/higher-order-providers), where checking the context tells you a layer is broken but not which one. @@ -137,7 +137,7 @@ check_components! { The check forces `App: CanUseComponent`, which routes through `GreetHello: IsProviderFor`, whose `where` clause names the `HasName` -requirement — so the error names the absent field, at the wiring site. Remove the `check_components!` block +requirement, so the error names the absent field, at the wiring site. Remove the `check_components!` block and the same mistake surfaces far away, at whatever calls `app.greet()`, as a much worse message. ## When to use it @@ -152,21 +152,21 @@ Two situations do put its name in your hands, and both are about diagnosis rathe - **Localizing a broken layer in a higher-order provider stack.** Checking the context proves *something* in the stack is unsatisfied. `#[check_providers(...)]` asserts `IsProviderFor` on each named provider instead, so a dependency missing only from the outer wrapper errors on its line alone while one missing - from the inner provider errors on both — which pins the layer. + from the inner provider errors on both, which pins the layer. - **Reading a `[CGP-Exxx]` diagnostic.** `cargo cgp check` names this trait in the dependency chain it renders, and knowing that a frame means "this provider's requirements, for this context" is what makes the chain readable. If you find yourself wanting to implement it by hand, the thing you actually want is -[`#[cgp_provider]`](../../macros/cgp_provider.md) or [`#[cgp_impl]`](../../macros/cgp_impl.md) on the impl block — -the trait's own diagnostic says so, which is the one case where a missing marker impl is the reported +[`#[cgp_provider]`](../../macros/cgp_provider.md) or [`#[cgp_impl]`](../../macros/cgp_impl.md) on the impl block. +The trait's own diagnostic says so, which is the one case where a missing marker impl is the reported problem rather than the hidden one. ## Under the hood `IsProviderFor` appears in three places, and together they form the chain an error travels along. -**First, the supertrait link.** [`#[cgp_component]`](../../macros/cgp_component.md) emits every provider trait +**The supertrait link.** [`#[cgp_component]`](../../macros/cgp_component.md) emits every provider trait with the marker as a supertrait, so for a component `CanGetFooAt` the provider trait reads: ```rust @@ -178,7 +178,7 @@ pub trait FooGetterAt: This binds a provider's dependency set to the marker: using the provider trait *requires* establishing `IsProviderFor` first, so probing the marker is equivalent to probing the provider trait. -**Second, the per-provider impl.** [`#[cgp_provider]`](../../macros/cgp_provider.md) and +**The per-provider impl.** [`#[cgp_provider]`](../../macros/cgp_provider.md) and [`#[cgp_impl]`](../../macros/cgp_impl.md) emit an empty impl beside the provider trait impl, carrying identical bounds: @@ -197,7 +197,7 @@ where Identical `where` clauses mean the marker is satisfiable exactly when the provider trait is. That is the whole trick. -**Third, the table forwarding.** [`delegate_components!`](../../macros/delegate_components.md) emits, for each +**The table forwarding.** [`delegate_components!`](../../macros/delegate_components.md) emits, for each entry, an impl on the table that forwards to the delegated provider's marker: ```rust @@ -228,7 +228,7 @@ lifetime in a type position, so it is lifted. **A missing marker impl usually means a missing attribute.** If the compiler says a provider does not implement `IsProviderFor`, the likeliest cause is a provider-trait impl written without -[`#[cgp_provider]`](../../macros/cgp_provider.md) — the trait's own diagnostic note says exactly this. +[`#[cgp_provider]`](../../macros/cgp_provider.md). The trait's own diagnostic note says exactly this. **Read it as "because", not as "instead".** `GreetHello: IsProviderFor<…> is not satisfied` does not mean the marker is the problem; it means the provider trait is not implemented *because* the named dependency is @@ -244,23 +244,23 @@ is the propagation that lets `#[check_providers]` localize a broken layer. ## Related constructs -- [`#[cgp_component]`](../../macros/cgp_component.md) — attaches the marker as a supertrait on every provider +- [`#[cgp_component]`](../../macros/cgp_component.md): attaches the marker as a supertrait on every provider trait. -- [`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md) — emit the +- [`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md): emit the per-provider impl beside the provider trait impl. -- [`delegate_components!`](../../macros/delegate_components.md) — emits the forwarding impl at each table entry. -- [`DelegateComponent`](./delegate_component.md) — the table those entries live in. -- [`CanUseComponent`](./can_use_component.md) — the context-indexed counterpart, which requires this of the +- [`delegate_components!`](../../macros/delegate_components.md): emits the forwarding impl at each table entry. +- [`DelegateComponent`](./delegate_component.md): the table those entries live in. +- [`CanUseComponent`](./can_use_component.md): the context-indexed counterpart, which requires this of the delegate. -- [`check_components!`](../../macros/check_components.md) — forces both; its `#[check_providers(...)]` form +- [`check_components!`](../../macros/check_components.md): forces both; its `#[check_providers(...)]` form asserts this trait directly. -- [Compile errors](../../errors.md) — how the resulting diagnostics read, and what the tool makes of them. +- [Compile errors](../../errors.md): how the resulting diagnostics read, and what the tool makes of them. The ideas behind it: -- [Check traits](/docs/concepts/check-traits) — why wiring is lazy and how an assertion makes its failures +- [Check traits](/docs/concepts/check-traits): why wiring is lazy and how an assertion makes its failures readable. -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the `where`-clause requirements this +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the `where`-clause requirements this trait re-exposes. ## Source From 974a8613bef796a9776e8026c24f505d882eee27 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 13:28:00 +0200 Subject: [PATCH 057/516] Revise prose of the types reference pages for point-first style Rewrite the writing of every page under docs/reference/types so each paragraph leads with its point, clauses are split and joined with a named connective instead of a semicolon, idioms and metaphors are replaced with the plain action, counting phrases are removed, negation moves onto the verb, and passive sentences name their actor. Also fix the PathCons example paragraph, which described a mixed lowercase-and-capitalized path while the example shows two capitalized segments. Code blocks, link targets, frontmatter, section order, and the shared footer are unchanged. Co-Authored-By: Claude Fable 5.1 --- docs/reference/types/chars.md | 64 +++++++------- docs/reference/types/cons.md | 83 +++++++++--------- docs/reference/types/either.md | 78 ++++++++--------- docs/reference/types/field.md | 70 ++++++++-------- docs/reference/types/index.md | 63 +++++++------- docs/reference/types/index_type.md | 76 ++++++++--------- docs/reference/types/life.md | 83 +++++++++--------- docs/reference/types/mref.md | 97 ++++++++++----------- docs/reference/types/nil.md | 47 +++++------ docs/reference/types/path_cons.md | 94 ++++++++++----------- docs/reference/types/phantom_data.md | 121 +++++++++++++-------------- docs/reference/types/void.md | 73 ++++++++-------- 12 files changed, 475 insertions(+), 474 deletions(-) diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index a805d839..ff86936f 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -11,20 +11,20 @@ the name can be a type. ## Overview `Chars` encodes a string as a type, so that a field name can take part in trait -resolution. CGP keys field access by a tag type: to read a field called `name`, something must stand in -for the string `"name"` at the type level, so the compiler can match one -[`HasField`](../traits/field-access/has_field.md) impl against another purely from the tag. A `Chars` -chain is how the string becomes a type, and a `Symbol` wrapping that chain is the tag itself. +resolution. CGP keys field access by a tag type. To read a field called `name`, something must stand for +the string `"name"` at the type level, so that the compiler can tell one +[`HasField`](../traits/field-access/has_field.md) impl from another by the tag alone. A `Chars` chain +turns the string into a type, and a `Symbol` that wraps the chain is the tag itself. -The encoding is a *list of characters* because of a limit in stable Rust: a `String` or `&str` cannot -be a const-generic parameter, but a single `char` can. So CGP spells the string out one character at a -time through a recursive `Chars` list, terminated by [`Nil`](nil.md), the same way the product list -spells out its elements through [`Cons`](cons.md). `Chars` is the specialized form of `Cons` in which the -head is a `const char` rather than a type. +The encoding is a *list of characters* because of a limit in stable Rust. A `String` or `&str` cannot be +a const-generic parameter, but a single `char` can. So CGP spells the string out one character at a time +through a recursive `Chars` list terminated by [`Nil`](nil.md), in the same way the product list spells +out its elements through [`Cons`](cons.md). `Chars` is the specialized form of `Cons` whose head is a +`const char` rather than a type. -You write this through [`Symbol!`](../macros/symbol.md) rather than by hand. `Symbol!("abc")` folds -into `Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>`, and that macro's page carries the fold, the -byte-length parameter, and the rest of the wrapper. This page is the runtime `Chars` type underneath. +You write this through [`Symbol!`](../macros/symbol.md) rather than directly. `Symbol!("abc")` folds +into `Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>`. That macro's page covers the fold, the +byte-length parameter, and the rest of the wrapper. This page covers the `Chars` type underneath. ## Definition @@ -35,12 +35,12 @@ its tail: pub struct Chars(pub PhantomData); ``` -`CHAR` is the character at this position, and `Tail` is the rest of the string, expected to be either the -next `Chars` node or [`Nil`](nil.md) at the end. The character lives in the const parameter and the tail -in a [`PhantomData`](phantom_data.md), so a `Chars` chain carries no runtime data and is erased -to a zero-sized value. A `Symbol` then wraps such a chain together with the -string's byte length; the length is stored explicitly because stable Rust cannot compute it inside a -const-generic context, and [`Symbol!`](../macros/symbol.md) covers why. +`CHAR` is the character at this position, and `Tail` is the rest of the string, which is the next `Chars` +node or [`Nil`](nil.md) at the end. The character lives in the const parameter, and the tail lives in a +[`PhantomData`](phantom_data.md), so a `Chars` chain does not carry runtime data and compiles to +a zero-sized value. A `Symbol` then wraps such a chain together with the string's +byte length. The wrapper stores the length explicitly because stable Rust cannot compute it inside a +const-generic context, and the [`Symbol!`](../macros/symbol.md) page explains why. ## Behavior @@ -52,9 +52,9 @@ its `Display` impl defers to `StaticFormat`, so `::default().t `"hello"`. The length a `Symbol` records enables [`StaticString`](../traits/formatting/static_string.md), which -exposes the string as a `const VALUE: &'static str` rather than a formatting routine, by decoding the +exposes the string as a `const VALUE: &'static str` rather than as a formatting routine. It decodes the characters into a byte buffer sized by that length at compile time. Code that needs the string at run -time uses `Display`; code that needs it as a const uses `StaticString`. +time uses `Display`, and code that needs it as a const uses `StaticString`. ## Examples @@ -75,8 +75,8 @@ where } ``` -The same type can be built and inspected at run time through its `Display` impl, which walks the `Chars` -chain to rebuild the string: +You can also build the same type at run time and inspect it through its `Display` impl, which walks the +`Chars` chain to rebuild the string: ```rust use cgp::prelude::*; @@ -90,12 +90,12 @@ just the terminator and whose recorded length is zero. ## When to use it -**You read `Chars` in an error; you write [`Symbol!`](../macros/symbol.md).** The macro produces the -chain, and the reason to know the type is to decode a field name in a diagnostic. +**You read `Chars` in an error, and you write [`Symbol!`](../macros/symbol.md).** The macro produces the +chain. You need to know the type so that you can decode a field name in a diagnostic. -- **Decode a `Chars` chain by reading off the characters.** An error mentioning - `HasField>>>` is telling you the field `width` is missing, and - `cargo cgp check` resugars the common cases. +- **Decode a `Chars` chain by reading off the characters.** An error that mentions + `HasField>>>` says that the field `width` is missing, and + `cargo cgp check` restores the `Symbol!` form in the common cases. - **Use [`Symbol!`](../macros/symbol.md) for a field-name tag,** and let the ergonomic constructs produce it from an argument or a method name where they can. - **Use [`Index`](index_type.md) for a tuple-field position,** which encodes a number rather than a @@ -103,12 +103,12 @@ chain, and the reason to know the type is to decode a field name in a diagnostic ## Common Mistakes -**The `LEN` in a wrapping `Symbol` is bytes, not characters.** For ASCII the two coincide, so the -distinction only shows on a non-ASCII field name, where `LEN` will not match the visible character count -and the `Chars` chain will be shorter than `LEN`. +**The `LEN` in a wrapping `Symbol` is bytes, not characters.** For ASCII the two counts agree, so the +difference shows only on a non-ASCII field name. There `LEN` does not match the visible character count, +and the `Chars` chain is shorter than `LEN`. -**`Chars` is zero-sized, so it holds no string at run time.** The `Display` impl rebuilds the text from -the type; there is no stored `&str` inside it. +**`Chars` is zero-sized, so it does not hold a string at run time.** The `Display` impl rebuilds the text +from the type, and the value does not store a `&str`. **A `Chars` chain is the character specialization of [`Cons`](cons.md), not a general list.** Its head is a `const char`, so it cannot carry arbitrary element types the way a product list does. diff --git a/docs/reference/types/cons.md b/docs/reference/types/cons.md index a896580a..32c33c19 100644 --- a/docs/reference/types/cons.md +++ b/docs/reference/types/cons.md @@ -10,22 +10,22 @@ time. ## Overview -`Cons` represents an ordered sequence of types as a single type, so a collection of fields -can be reasoned about generically. A Rust tuple holds several things at once but cannot be taken apart -by generic code element by element; a recursive list can. `Cons` pairs the first element with the rest of -the list, and [`Nil`](nil.md) marks the end, so the two together form an *anonymous product type*: a -record-shaped value that code can walk without knowing the concrete struct it came from. - -This list makes structural, field-by-field operations work across every struct uniformly. A -struct's fields are exposed as one list type through [`HasFields`](../traits/shape/has_fields.md), so a -provider written once to recurse over `Cons` and `Nil` can iterate, transform, read, or rebuild *any* -struct's fields. Each step handles the `Head`, then recurses into the `Tail`, until it reaches `Nil` and -stops. - -You write this list through the [`Product!`](../macros/product.md) macro rather than by hand. +`Cons` represents an ordered sequence of types as a single type, so that generic code can +reason about a collection of fields. A Rust tuple holds several things at once, but generic code cannot +take it apart element by element. A recursive list allows that. `Cons` pairs the +first element with the rest of the list, and [`Nil`](nil.md) marks the end. Together they form an +*anonymous product type*: a record-shaped value that code can walk without knowing the concrete struct it +came from. + +This list makes structural, field-by-field operations work across every struct in the same way. +[`HasFields`](../traits/shape/has_fields.md) exposes a struct's fields as one list type, so a provider +written once to recurse over `Cons` and `Nil` can iterate, transform, read, or rebuild *any* struct's +fields. Each step handles the `Head`, then recurses into the `Tail`, until it reaches `Nil` and stops. + +You write this list through the [`Product!`](../macros/product.md) macro rather than directly. `Product![A, B, C]` is the right-nested `Cons` chain, and the value macro `product![a, b, c]` builds a -matching value. The elements are most often [`Field`](field.md) entries pairing a name with a value, -so a struct's layout becomes a `Product!` of `Field` cells over this list. +matching value. The elements are most often [`Field`](field.md) entries that pair a name with a value, so +a struct's layout becomes a `Product!` of `Field` cells over this list. ## Definition @@ -36,31 +36,30 @@ so a struct's layout becomes a `Product!` of `Field` cells over this list. pub struct Cons(pub Head, pub Tail); ``` -`Head` is the first element's type and `Tail` is the rest of the list, itself another `Cons` or, at the -end, [`Nil`](nil.md). Both positional fields are public, so `Cons(head, tail)` builds a cell and `.0` and +`Head` is the first element's type, and `Tail` is the rest of the list, which is another `Cons` or, at the +end, [`Nil`](nil.md). Both positional fields are public, so `Cons(head, tail)` builds a cell, and `.0` and `.1` reach its parts. Unlike the zero-sized [`Chars`](chars.md) and [`PathCons`](path_cons.md) lists, -`Cons` holds real values: it is as large as its elements laid out by nesting, with nothing boxed or -virtual. It derives `Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a list of values that -implement those traits inherits them structurally, comparing head to head down the chain. +`Cons` holds real values. It is as large as its nested elements, without boxing or indirection. It derives +`Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a list of values that implement those traits +inherits them structurally, comparing head to head down the chain. ## Behavior A list of any length is a `Cons` chain ending in `Nil`, nested to the right. The type `Product![A, B, C]` -is `Cons>>`, and the empty `Product![]` is just `Nil`. The matching value is -built with the tuple-struct constructor, `Cons(a, Cons(b, Cons(c, Nil)))`, so a `product!` value is an -ordinary owned value whose type is exactly the one `Product!` produces over the same elements' types. +is `Cons>>`, and the empty `Product![]` is just `Nil`. The tuple-struct +constructor builds the matching value, `Cons(a, Cons(b, Cons(c, Nil)))`. So a `product!` value is an +ordinary owned value, and its type is exactly the one `Product!` produces over the same element types. -Generic code consumes the list by recursing on its two cases. A trait implemented for `Nil` supplies -the base case, the empty list, and a blanket impl for `Cons` supplies the recursive step, -usually constraining `Tail` to implement the same trait so the recursion bottoms out at `Nil`. This -pairing of a `Nil` impl with a `Cons` impl is the standard shape for any operation that -folds over a product, and it is how the field machinery processes a struct of any width with no per-field -code. +Generic code consumes the list by recursing on its cases. A trait impl for `Nil` supplies the base case, +the empty list. A blanket impl for `Cons` supplies the recursive step, and it usually +constrains `Tail` to implement the same trait, so that the recursion ends at `Nil`. This pairing of a +`Nil` impl with a `Cons` impl is the standard shape for any operation that folds over a +product. It is how the field machinery processes a struct of any width without per-field code. ## Examples The product list appears most visibly as the `Fields` of a struct that derives -[`HasFields`](../derives/derive_has_fields.md), where the [`Product!`](../macros/product.md) sugar +[`HasFields`](../derives/derive_has_fields.md), where the [`Product!`](../macros/product.md) macro hides the `Cons`/`Nil` chain: ```rust @@ -83,7 +82,7 @@ pub struct Person { // } ``` -A standalone list type and a matching value can also be written through the sugar, which expands to the +You can also write a standalone list type and a matching value through the macros, which expand to the nested `Cons` form: ```rust @@ -97,16 +96,16 @@ let row: Row = product![1, "hi".to_string(), true]; ## When to use it -**Read `Cons` in an expansion; write [`Product!`](../macros/product.md) instead.** The sugar produces -the list, and spelling it out by hand is longer, harder to change, and identical in meaning. +**Read `Cons` in an expansion, and write [`Product!`](../macros/product.md) instead.** The macro produces +the list. Writing the chain out yourself is longer, harder to change, and identical in meaning. - **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for a struct's shape** rather than - declaring the `Cons` chain yourself, since a hand-written list restates the struct and the two drift - apart. -- **Use [`Product!`](../macros/product.md) for a list you write on purpose,** such as a handler - pipeline, and let it build the list. -- **Decode a `Cons` chain in an error by counting cells.** A field-list mismatch is reported as a - mismatch between two `Cons` chains, and the position where they diverge is the field that differs. + declaring the `Cons` chain yourself, because a list you write yourself restates the struct, and the two + drift apart. +- **Use [`Product!`](../macros/product.md) for a list you write deliberately,** such as a handler + pipeline, and let the macro build the chain. +- **Decode a `Cons` chain in an error by counting cells.** The compiler reports a field-list mismatch as + a mismatch between two `Cons` chains, and the position where they diverge is the field that differs. ## Common Mistakes @@ -115,11 +114,11 @@ list of one still carries its cell. **Element order is part of the type.** `Cons>` and `Cons>` are unrelated types. For a field list this matters less than it sounds, because the entries are name-tagged -[`Field`](field.md)s and the operations match on names; for a handler pipeline the order is the +[`Field`](field.md)s and the operations match on names. For a handler pipeline, the order is the execution order. -**The empty product is [`Nil`](nil.md), a real value.** That is the difference from the sum list, whose -empty form is the uninhabited [`Void`](void.md). An empty record exists; an empty choice cannot. +**The empty product is [`Nil`](nil.md), a real value.** This differs from the sum list, whose empty form +is the uninhabited [`Void`](void.md). An empty record can exist, but an empty choice cannot. ## Related constructs diff --git a/docs/reference/types/either.md b/docs/reference/types/either.md index bef30715..3da6783e 100644 --- a/docs/reference/types/either.md +++ b/docs/reference/types/either.md @@ -10,20 +10,20 @@ time. ## Overview -`Either` represents a choice among several types as a single type, so an enum's variants can -be reasoned about generically. Where the [product list](cons.md) holds a value for *every* element at -once, the sum list holds a value for exactly *one* of its branches: a tagged union, or *anonymous sum -type*. `Either` branches at each step, and [`Void`](void.md) marks the end, so the two together form a -coproduct that code can walk without knowing the concrete enum it came from. - -This list makes structural, variant-by-variant operations work across every enum uniformly. An -enum's variants are exposed as one sum type through [`HasFields`](../traits/shape/has_fields.md), so a -provider written once to recurse over the `Either` and `Void` branches can match, dispatch on, or -construct *any* enum's variants. This is the basis for CGP's extensible-variant machinery: a variant is -reached by walking the nested branches rather than by a hand-written `match` against a fixed enum. +`Either` represents a choice among several types as a single type, so that generic code can +reason about an enum's variants. The [product list](cons.md) holds a value for *every* element at once. +The sum list holds a value for exactly *one* of its branches, which makes it a tagged union, or +*anonymous sum type*. `Either` branches at each step, and [`Void`](void.md) marks the end. Together they +form a coproduct that code can walk without knowing the concrete enum it came from. + +This list makes structural, variant-by-variant operations work across every enum in the same way. +[`HasFields`](../traits/shape/has_fields.md) exposes an enum's variants as one sum type, so a provider +written once to recurse over the `Either` and `Void` branches can match, dispatch on, or construct *any* +enum's variants. CGP's extensible-variant machinery rests on this. It reaches a variant by walking the +nested branches rather than by a `match` written against a fixed enum. You write this list through the [`Sum!`](../macros/sum.md) macro. `Sum![A, B, C]` is the right-nested -`Either` chain terminated by `Void`. The branches are most often [`Field`](field.md) entries pairing a +`Either` chain terminated by `Void`. The branches are most often [`Field`](field.md) entries that pair a variant name with its payload, so an enum's shape becomes a `Sum!` of `Field` branches over this list. ## Definition @@ -38,29 +38,29 @@ pub enum Either { } ``` -`Head` is the type of the current branch and `Tail` is the rest of the chain, itself another `Either` -or, at the end, [`Void`](void.md). `Left(Head)` carries a value of the head type; `Right(Tail)` carries a -value belonging somewhere further down the chain. It derives `Eq`, `PartialEq`, `Debug`, and `Clone`, so -a sum of values that implement those traits inherits them. +`Head` is the type of the current branch, and `Tail` is the rest of the chain, which is another `Either` +or, at the end, [`Void`](void.md). `Left(Head)` carries a value of the head type, and `Right(Tail)` +carries a value that belongs further down the chain. It derives `Eq`, `PartialEq`, `Debug`, and `Clone`, +so a sum of values that implement those traits inherits them. ## Behavior A sum of any width is an `Either` chain ending in `Void`, nested to the right. The type `Sum![A, B, C]` is `Either>>`, and the empty `Sum![]` is just `Void`. A value selects one -branch by how deep it sits: `Left(a)` is an `A`, `Right(Left(b))` is a `B`, and `Right(Right(Left(c)))` -is a `C`. Reaching the `Void` position would mean the value matched none of the listed branches, which is -impossible, because `Void` has no values, so the chain is closed off at its end. +branch by its nesting depth: `Left(a)` is an `A`, `Right(Left(b))` is a `B`, and `Right(Right(Left(c)))` +is a `C`. A value at the `Void` position would match none of the listed branches. That is impossible, +because a value of `Void` cannot exist, so the chain is closed at its end. -Generic code consumes the sum by recursing on its two cases, mirroring how it folds the product list but -branching instead of pairing. A `Left` is handled directly as the head; a `Right` defers to a trait impl -on the `Tail`, recursing until a `Left` is found. The base case is the [`Void`](void.md) terminator, and -here the difference from the product list matters: a product ends in the constructible [`Nil`](nil.md), -but a sum ends in the uninhabited `Void`, because an empty choice has no value to pick. +Generic code consumes the sum by recursing on its cases, in the same way it folds the product list, but it +branches instead of pairing. The code handles a `Left` directly as the head. A `Right` defers to a trait +impl on the `Tail`, which recurses until it finds a `Left`. The base case is the [`Void`](void.md) +terminator, and here the difference from the product list matters. A product ends in the constructible +[`Nil`](nil.md), but a sum ends in the uninhabited `Void`, because an empty choice cannot hold a value. ## Examples The sum list appears most visibly as the `Fields` of an enum that derives -[`#[derive(HasFields)]`](../derives/derive_has_fields.md), where the [`Sum!`](../macros/sum.md) sugar +[`#[derive(HasFields)]`](../derives/derive_has_fields.md), where the [`Sum!`](../macros/sum.md) macro hides the `Either`/`Void` chain: ```rust @@ -86,7 +86,7 @@ pub enum Shape { // } ``` -A standalone sum type can also be written through the sugar, and a value picks one branch by its nesting +You can also write a standalone sum type through the macro, and a value picks one branch by its nesting depth: ```rust @@ -100,30 +100,30 @@ let t: Token = Either::Right(Either::Left("hi".to_string())); // the String bran ## When to use it -**Read `Either` in an expansion; write [`Sum!`](../macros/sum.md) instead.** The sugar produces the -list, and spelling it out by hand is longer, harder to change, and identical in meaning. +**Read `Either` in an expansion, and write [`Sum!`](../macros/sum.md) instead.** The macro produces the +list. Writing the chain out yourself is longer, harder to change, and identical in meaning. - **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for an enum's shape** rather than declaring the `Either` chain yourself. -- **Decode an `Either` chain in an error by counting the `Right` wrappers.** The depth is which variant a - value selects, and a mismatch is reported as a mismatch between two `Either` chains. -- **Reach for [`Cons`](cons.md), not `Either`, when every element is present at once.** A product holds a - value for every element; a sum holds one for exactly one. They are duals, and mixing them produces a - type error rather than a subtle bug. +- **Decode an `Either` chain in an error by counting the `Right` wrappers.** The depth says which variant + a value selects, and the compiler reports a mismatch as a mismatch between two `Either` chains. +- **Use [`Cons`](cons.md), not `Either`, when every element is present at once.** A product holds a + value for every element, and a sum holds a value for exactly one. They are duals, and mixing them + produces a type error rather than a subtle bug. ## Common Mistakes **A sum holds one branch, not all of them.** `Either>` is a value that is *either* an `A` or a `B`, not both. This is the opposite of the [product list](cons.md), and confusing the two is the -usual cause of a "expected `Either`, found `Cons`" error. +usual cause of an "expected `Either`, found `Cons`" error. -**The empty sum is the uninhabited [`Void`](void.md), not a value.** `Sum![]` is `Void`, which has no -values, so an empty choice cannot be constructed. An empty record can, because it ends in -[`Nil`](nil.md). +**The empty sum is the uninhabited [`Void`](void.md), not a value.** `Sum![]` is `Void`, which is +uninhabited, so code cannot construct an empty choice. It can construct an empty record, because a record +ends in [`Nil`](nil.md). **Branch order is part of the type.** `Sum![A, B]` and `Sum![B, A]` are unrelated types. Because the -branches are name-tagged [`Field`](field.md)s and the operations match on names, this bites less than -it might, but the types still differ. +branches are name-tagged [`Field`](field.md)s and the operations match on names, this matters less than +it sounds, but the types still differ. ## Related constructs diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index 2656e004..f8e11dba 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -13,15 +13,16 @@ described one entry at a time without naming the concrete type. `Field` carries a field's *name* and its *value* together in one type. A bare [`Product!`](../macros/product.md) list such as `Product![String, u8]` records the value types and their order, but it cannot tell `name: String` from any other `String`. Wrapping each element in a `Field`, -as `Field`, attaches the name as a type, so a struct's shape describes itself: -code walking the list matches on the tag to find the field it wants. +as `Field`, attaches the name as a type, so a struct's shape describes itself. +Code that walks the list matches on the tag to find the field it wants. -The name rides as a type because it is needed only at compile time, for trait resolution and dispatch, -never at run time. A `Field` is exactly as large as its `Value`, since the tag lives in a -zero-sized [`PhantomData`](phantom_data.md), so naming a field this way costs nothing while making -field-by-field generic code possible. This is the same type-as-name trick that -[`Symbol!`](../macros/symbol.md) provides for a named field and [`Index`](index_type.md) for a tuple -position. `Field` is where that tag meets the value it labels. +The name is a type because the program needs it only at compile time, for trait resolution and +dispatch, and never at run time. A `Field` is exactly as large as its `Value`, because +the tag lives in a zero-sized [`PhantomData`](phantom_data.md). So naming a field this way +costs nothing at run time and makes field-by-field generic code possible. +[`Symbol!`](../macros/symbol.md) provides the same type-as-name encoding for a named field, and +[`Index`](index_type.md) provides it for a tuple position. `Field` joins that tag to the value it +labels. `Field` fills both structural lists. In a record it is the element of a [`Product!`](../macros/product.md) of entries, one per field. In a variant it is the element of a [`Sum!`](../macros/sum.md) of entries, one @@ -39,29 +40,28 @@ pub struct Field { } ``` -`Tag` is the type-level name of the field. It appears only inside `PhantomData` and never in a -stored field, and it is usually a type-level string such as `Symbol!("name")` for a named field or a -type-level number such as `Index<0>` for a tuple position. `Value` is the field's actual type, and -`value` is the only data the struct keeps. Apart from the tag, a `Field` is a thin wrapper around its -`Value`. +`Tag` is the type-level name of the field. It appears only inside `PhantomData`, never in a stored +field. It is usually a type-level string such as `Symbol!("name")` for a named field, or a type-level +number such as `Index<0>` for a tuple position. `Value` is the field's actual type, and `value` is the +only data the struct keeps. Apart from the tag, a `Field` is a thin wrapper around its `Value`. ## Behavior -You build a `Field` from a value with no tag argument, because the tag comes from the target type rather -than from you. The `From` impl fills in `value` and sets `phantom` to `PhantomData`, so -`let f: Field = "Alice".to_string().into();` works and the tag is inferred from -the expected type. This is why generated code builds each entry with a plain `.into()`. +You build a `Field` from a value without a tag argument, because the tag comes from the target type +rather than from you. The `From` impl fills in `value` and sets `phantom` to `PhantomData`. So +`let f: Field = "Alice".to_string().into();` compiles, and the compiler infers +the tag from the expected type. This is why generated code builds each entry with a plain `.into()`. The other trait impls defer to the value and ignore the tag, so a `Field` behaves like its `Value` for comparison and printing. `Debug` forwards to the value's `Debug` and does not show the tag. `PartialEq` and `Eq` compare only `value`, each gated on the matching bound on `Value`. Two `Field` -values are equal when their values are equal; the tag is a compile-time matter and plays no part at run +values are equal when their values are equal. The tag is a compile-time matter and plays no part at run time. Because the tag lives only in `PhantomData`, code that needs the name reads it from the `Tag` parameter -through trait resolution, for example by matching a `Field` against a -[`HasField`](../traits/field-access/has_field.md) bound, rather than from any stored -data. +through trait resolution rather than from stored data. For example, it matches a +`Field` against a [`HasField`](../traits/field-access/has_field.md) +bound. ## Examples @@ -86,8 +86,7 @@ pub struct Person { // } ``` -A single `Field` can also be built directly from its value, with the tag supplied by the type -annotation: +You can also build a single `Field` directly from its value, with the type annotation supplying the tag: ```rust use cgp::prelude::*; @@ -101,30 +100,29 @@ wrapper names a positional field, as `Field, u32>`. ## When to use it -**You read `Field` far more often than you write it.** Recognizing it in a generated shape or an error -is the common case, and it is most of what this page is for. +**You read `Field` far more often than you write it.** The common case is to recognize it in a generated +shape or in an error, and this page is mostly for that. - **Let the derives build it.** [`#[derive(HasFields)]`](../derives/derive_has_fields.md) and [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) produce the `Field` entries of a type's shape, so - a type you own gets its entries from one derive rather than from a hand-written list. + a type you own gets its entries from one derive rather than from a list you write yourself. - **Construct a `Field` directly** only in generic shape code of your own, where you assemble or rewrite - a record or a variant entry by entry. The `.into()` form is how you build one, and the tag comes from - the expected type. -- **Do not reach for a bare [`Product!`](../macros/product.md) of values** when you need the names. - A list of `Field` entries carries the names, and the operations that walk a shape match on - them. + a record or a variant entry by entry. Build one with `.into()`, and let the expected type supply the + tag. +- **Do not use a bare [`Product!`](../macros/product.md) of values** when you need the names. A list of + `Field` entries carries the names, and the operations that walk a shape match on them. ## Common Mistakes **The tag is compile-time only, so it never affects equality or printing.** Two `Field` values compare -equal when their values are equal, and `Debug` shows the value alone. If you expected the tag to -distinguish them at run time, it does not; the tag distinguishes them only in the type. +equal when their values are equal, and `Debug` shows the value alone. The tag does not distinguish them at +run time. It distinguishes them only in the type. -**A `Field` is the size of its `Value`, not larger.** The tag adds no space, so wrapping a value in a -`Field` is free at run time. +**A `Field` is the size of its `Value`, not larger.** The tag occupies zero bytes, so wrapping a value in +a `Field` is free at run time. **The tag must match exactly for a lookup to resolve.** `Field` and -`Field` carry unrelated tags, so a name mismatch shows up as an unsatisfied +`Field` carry unrelated tags, so a name mismatch appears as an unsatisfied [`HasField`](../traits/field-access/has_field.md) bound rather than as a typo. ## Related constructs diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index b64f3340..b442ef90 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -10,38 +10,39 @@ the one ordinary runtime type you return from a getter. ## Overview -Most types on these pages are **type-level building blocks**. Much of CGP's machinery runs at the type -level, where a field name, a variant, a position, or a whole record shape is a *type* rather than a value. -These building blocks are how CGP does that, and you write almost none of them by hand. You meet them when -you read the code a macro generated, or when a wiring mistake prints a wall of nested types. This section -exists to make such a type legible. - -One idea runs through nearly all of them, so hold it first: a type can carry information the program never -stores as a value. A struct can name a type parameter it keeps no field of, so a name, a number, or a +Most types on these pages are **type-level building blocks**, and you read them far more often than you +write them. Much of CGP's machinery runs at the type level, where a field name, a variant, a position, or +a whole record shape is a *type* rather than a value. These building blocks carry that information. A +macro writes almost all of them for you, so you meet them when you read generated code or when a wiring +mistake reports a deeply nested type. This section exists to make such a type readable. + +One idea runs through nearly all of them: a type can carry information the program never stores as a +value. A struct can name a type parameter without keeping a field of that type, so a name, a number, or a lifetime becomes part of the type's identity, and the compiler matches on it during trait resolution. -[`PhantomData`](phantom_data.md) is the standard-library tool that makes this legal, so it comes first -here, and the other types build on it. - -The building blocks divide into two groups: markers and recursive type-level lists. - -The **markers** each attach one piece of information at the type level. [`Index`](index_type.md) turns a -tuple-field position into a type, the way [`Symbol!`](../macros/symbol.md) turns a field name into one, -and [`Life`](life.md) lifts a lifetime into a type so it can travel through machinery that accepts only -types. [`Field`](field.md) uses such a tag: it pairs a value with its type-level name, so a record or a -variant entry knows what it is called. - -The **recursive type-level lists** are the chains everything structural is built from. Each pairs a -head-and-tail cell with a terminator, and generic code takes it apart one element at a time. Each family -covers one job, and its full account lives on its head cell. [`Cons`](cons.md) and [`Nil`](nil.md) build a -record, and `Cons` owns the type-level product. [`Either`](either.md) and [`Void`](void.md) build a -variant, and `Either` owns the type-level sum. [`Chars`](chars.md) builds a string, and -[`PathCons`](path_cons.md) builds a routing path. You write these through the sugar -([`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), [`Symbol!`](../macros/symbol.md), and -[`Path!`](../macros/path.md)) and read them in expansions and errors. - -One type is not a building block at all. [`MRef`](mref.md) is an ordinary runtime value, the -owned-or-borrowed return type of a getter. It is here because it is the one type in this section you write -on purpose. +[`PhantomData`](phantom_data.md) is the standard-library marker that makes this legal. It comes first +here, because the other types build on it. + +The building blocks are either markers or recursive type-level lists. + +Each **marker** attaches one piece of information at the type level. [`Index`](index_type.md) turns a +tuple-field position into a type, in the same way that [`Symbol!`](../macros/symbol.md) turns a field +name into one. [`Life`](life.md) lifts a lifetime into a type, so that it can pass through machinery that +accepts only types. [`Field`](field.md) uses such a tag: it pairs a value with its type-level name, so a +record entry or a variant entry carries its own name. + +The **recursive type-level lists** are the chains that every structural shape is built from. Each list +pairs a head-and-tail cell with a terminator, and generic code takes the list apart one element at a time. +Each family covers one job, and the head cell's page carries the full account of that family. +[`Cons`](cons.md) and [`Nil`](nil.md) build a record, and the `Cons` page explains the type-level product. +[`Either`](either.md) and [`Void`](void.md) build a variant, and the `Either` page explains the type-level +sum. [`Chars`](chars.md) builds a string, and [`PathCons`](path_cons.md) builds a routing path. You write +these lists through the macros ([`Product!`](../macros/product.md), [`Sum!`](../macros/sum.md), +[`Symbol!`](../macros/symbol.md), and [`Path!`](../macros/path.md)) and read them in expansions and +errors. + +[`MRef`](mref.md) is the one type here that is not a building block. It is an ordinary runtime value, the +owned-or-borrowed return type of a getter. It belongs in this section because it is the one type here that +you write yourself. ## The ideas behind them diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index cf3b0360..66a0cb55 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -11,25 +11,25 @@ A number lifted into a type, so a tuple-struct field can be named by its positio ## Overview `Index` encodes a `usize` at the type level. CGP's getter mechanism keys every field by a -*type* tag, and a tuple-struct field has no string name to turn into a [`Symbol!`](../macros/symbol.md); -it has only a position. To let positional fields use the same trait-resolution machinery as named fields, -the position itself becomes a type. `Index` is that type: it carries a `usize` as a const parameter -and nothing else, so `Index<0>`, `Index<1>`, and `Index<2>` are distinct types standing in for a tuple -struct's positional fields. +*type* tag, but a tuple-struct field has only a position and lacks a string name to turn into a +[`Symbol!`](../macros/symbol.md). So the position itself becomes a type, and positional fields can use the +same trait-resolution machinery as named fields. `Index` is that type. It carries a `usize` as a const +parameter and nothing else, so `Index<0>`, `Index<1>`, and `Index<2>` are distinct types that stand for a +tuple struct's positional fields. Encoding the position as a type lets positional field access resolve through traits. Here a **context** is -the type the capability runs against, which supplies the values it needs as its own fields. Because -`Index<0>` is a type, a context can carry a +the type the capability runs against. It supplies the values the capability needs as its own fields. +Because `Index<0>` is a type, a context can carry a [`HasField>`](../traits/field-access/has_field.md) impl for its first field and a -`HasField>` impl for its second side by side, and the compiler selects the right one from the -tag alone, exactly as it would for two differently-named `Symbol!` tags. `Index` is the numeric -counterpart to `Symbol!`: a field is keyed by a `Symbol!` when it has a name and by an `Index` when it -has only a position. +`HasField>` impl for its second, side by side. The compiler selects the right one from the tag +alone, exactly as it does for differently named `Symbol!` tags. `Index` is the numeric counterpart to +`Symbol!`. A field is keyed by a `Symbol!` when it has a name, and by an `Index` when it has only a +position. -`Index` carries no runtime data; it is a zero-sized marker. Its whole job is to make a number available -at the type level, so it can be a [`HasField`](../traits/field-access/has_field.md) tag, the tag of a -[`Field`](field.md) entry inside a tuple struct's shape, and the type passed inside a -[`PhantomData`](phantom_data.md) wherever a positional name is needed at compile time. +`Index` is a zero-sized marker without runtime data. Its only job is to make a number available at the +type level. So it can serve as a [`HasField`](../traits/field-access/has_field.md) tag, as the tag of +a [`Field`](field.md) entry inside a tuple struct's shape, and as the type inside a +[`PhantomData`](phantom_data.md) wherever compile-time code needs a positional name. ## Definition @@ -41,30 +41,30 @@ pub struct Index; ``` `I` is the position the type represents: `Index<0>` for the field at offset zero, and so on. The struct -has no fields, so a value of `Index` carries no data and the number lives entirely in the type. The -derived `Default`, `Clone`, and `Copy` make a value available whenever one is needed, and `Eq` and -`PartialEq` treat two values of the same `Index` as always equal, since they hold no data. -`Index` also implements `Display` and `Debug`, and both print the underlying number, so `Index<0>` -displays as `0` and the position a tag stands for is visible in output and in diagnostics. +is empty, so a value of `Index` holds nothing, and the number lives entirely in the type. The +derived `Default`, `Clone`, and `Copy` make a value available whenever code needs one. `Eq` and +`PartialEq` treat any two values of the same `Index` as equal, because they hold no data. `Index` +also implements `Display` and `Debug`, and both print the underlying number. So `Index<0>` displays as +`0`, and output and diagnostics show the position a tag stands for. ## Behavior -A tuple struct keys each of its fields by `Index`, counting from zero, so the field at position `N` is -read through the tag `Index`. When a tuple struct derives +A tuple struct keys each of its fields by `Index`, counting from zero, so code reads the field at +position `N` through the tag `Index`. When a tuple struct derives [`#[derive(HasField)]`](../derives/derive_has_field.md), the generated impl uses `Index<0>` for the `.0` -field, `Index<1>` for `.1`, and so on, mapping each `get_field(PhantomData::>)` call to the +field, `Index<1>` for `.1`, and so on. Each `get_field(PhantomData::>)` call maps to the matching positional access. Those tags then appear as the tag of each [`Field`](field.md) entry in the -tuple struct's [`HasFields`](../traits/shape/has_fields.md) shape, so generic code walking the field list -reads positions where it would read `Symbol!` names for a named struct. +tuple struct's [`HasFields`](../traits/shape/has_fields.md) shape. So generic code that walks the field +list reads positions where it would read `Symbol!` names for a named struct. -Because `Index` is zero-sized and the position lives in the type, accessing a field by index resolves -entirely at compile time: there is no array bound check and no runtime indexing. Selecting the wrong -index is a type error rather than a panic, because `Index<5>` on a three-field struct has no -matching `HasField` impl. +Because `Index` is zero-sized and the position lives in the type, a field access by index resolves +entirely at compile time. The access does not check an array bound and does not index at run time. +Selecting the wrong index is a type error rather than a panic, because a three-field struct lacks a +`HasField` impl for `Index<5>`. ## Examples -When a tuple struct derives `HasField`, each positional field is tagged by an `Index`: +When a tuple struct derives `HasField`, the derive tags each positional field with an `Index`: ```rust use cgp::prelude::*; @@ -80,7 +80,7 @@ pub struct Pair(pub u32, pub String); // } ``` -A field is then read by supplying the `Index` tag, and the chosen position is fixed at compile time: +You then read a field by supplying the `Index` tag, and the compiler fixes the chosen position: ```rust use cgp::prelude::*; @@ -97,14 +97,14 @@ assert_eq!(Index::<2>.to_string(), "2"); ## When to use it -**Use `Index` for a tuple-field tag, and let the derive produce it where it can.** It is generated for -every field of a tuple struct that derives [`#[derive(HasField)]`](../derives/derive_has_field.md), and -you write it by hand only when you tag a positional field yourself. +**Use `Index` for a tuple-field tag, and let the derive produce it where it can.** The derive generates it +for every field of a tuple struct that derives [`#[derive(HasField)]`](../derives/derive_has_field.md), +so you write it only when you tag a positional field yourself. - **Use [`Symbol!`](../macros/symbol.md) for a named field,** not an `Index`. Named and positional fields use different tags, and the derive generates the right one for each. - **Write `Index` for a tuple position,** never a `Symbol!` of the number. `Symbol!("0")` is a string - tag and matches nothing on a tuple struct. + tag and does not match any field of a tuple struct. - **Read `Index` in an error as a position.** A missing `HasField>` bound names the third field of a tuple struct. @@ -115,10 +115,10 @@ type, not by a string of the digit, so `Symbol!("0")` never matches a tuple fiel generates it. **Indices count from zero.** `Index<0>` is the first field, matching Rust's own `.0` access. An -off-by-one here reports as a missing `HasField` impl rather than an out-of-range error. +off-by-one error here appears as a missing `HasField` impl rather than as an out-of-range error. -**Selecting a position that does not exist is a type error, not a panic.** `Index<5>` on a three-field -struct has no `HasField` impl, so the mistake is caught at compile time. +**Selecting a position that does not exist is a type error, not a panic.** A three-field struct lacks a +`HasField` impl for `Index<5>`, so the compiler catches the mistake. ## Related constructs diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index 523fc232..ebaec580 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -10,17 +10,17 @@ types. ## Overview -`Life<'a>` exists because CGP's wiring is parameterized by *types*, not lifetimes, yet a CGP trait may -carry a lifetime of its own. The marker that surfaces a provider's dependencies, +`Life<'a>` turns the lifetime `'a` into a type, because CGP's wiring is parameterized by *types* and a CGP +trait may carry a lifetime of its own. The marker that records a provider's dependencies, [`IsProviderFor`](../traits/wiring/is_provider_for.md), takes a tuple of the trait's generic parameters as -one type argument, so the compiler can match a provider against the exact instantiation it is asked for. -A lifetime cannot sit in that tuple, because a tuple is a type and its members must be types. So a -lifetime parameter on the trait must first become a type, and `Life<'a>` is that conversion: it packages -the lifetime `'a` as a concrete type that can stand alongside the trait's other type parameters. +one type argument, so that the compiler can match a provider against the exact instantiation asked for. A +lifetime cannot sit in that tuple, because a tuple is a type and its members must be types. So a lifetime +parameter on the trait must first become a type. `Life<'a>` is that conversion. It packages the lifetime +`'a` as a concrete type that can stand beside the trait's other type parameters. Without this lift, a trait that borrows could not record its lifetime in the dependency marker, and the -wiring could not tell one lifetime instantiation from another. `Life` lets the lifetime ride through -`IsProviderFor` as `(Life<'a>, T)`, keeping it part of the provider's identity while the marker's +wiring could not tell one lifetime instantiation from another. `Life` lets the lifetime pass through +`IsProviderFor` as `(Life<'a>, T)`, so it stays part of the provider's identity while the marker's argument stays a plain type. ## Definition @@ -31,24 +31,27 @@ argument stays a plain type. pub struct Life<'a>(pub PhantomData<*mut &'a ()>); ``` -The struct holds no runtime data. Its only job is to carry the lifetime `'a` in the type system through -[`PhantomData`](phantom_data.md). The choice of `PhantomData<*mut &'a ()>` is deliberate and controls how -`Life<'a>` relates to other lifetimes under subtyping. A `*mut T` is *invariant* in `T`, so wrapping -`&'a ()` behind a `*mut` makes `Life<'a>` invariant in `'a`: a `Life<'long>` is neither a subtype nor a -supertype of a `Life<'short>`. Invariance is correct here because the lifetime is an exact identity in -the dependency marker. Two providers wired for different lifetimes must be treated as wired for genuinely -different things, and a variant `Life` would let the compiler coerce one instantiation into another and -pick the wrong provider. The raw pointer also keeps `Life<'a>` from carrying auto-trait obligations tied -to a real borrow, since it neither owns nor references a real value. +The struct holds nothing at run time. Its only job is to carry the lifetime `'a` in the type system +through [`PhantomData`](phantom_data.md). The choice of `PhantomData<*mut &'a ()>` is deliberate, +because it controls how `Life<'a>` relates to other lifetimes under subtyping. A `*mut T` is +*invariant* in `T`, so wrapping `&'a ()` behind a `*mut` makes `Life<'a>` invariant in `'a`. A +`Life<'long>` is neither a subtype nor a supertype of a `Life<'short>`. + +Invariance is correct here because the lifetime is an exact identity in the dependency marker. The +compiler must treat two providers wired for different lifetimes as wired for different things. A variant +`Life` would let the compiler coerce one instantiation into another and pick the wrong provider. The raw +pointer also means that `Life<'a>` does not carry auto-trait obligations tied to a real borrow, because +it neither owns nor references a real value. ## Behavior -`Life` has no methods and implements no CGP traits of its own; its entire behavior is to occupy a type -position. In a generated provider trait for a component with a lifetime, the lifetime is collected into -the [`IsProviderFor`](../traits/wiring/is_provider_for.md) argument tuple as `Life<'a>`, so the provider's -dependency obligation reads the same way it would for any type parameter. The provider trait, its blanket -forwarding impl, and the impls that satisfy it all agree on the same `(Life<'a>, T)` shape, and that -shared shape lets a borrowing component be wired and checked exactly like a non-borrowing one. +`Life` does not define methods and does not implement CGP traits of its own. Its entire behavior is to +occupy a type position. In the generated provider trait for a component with a lifetime, the macro +collects the lifetime into the [`IsProviderFor`](../traits/wiring/is_provider_for.md) argument tuple as +`Life<'a>`, so the provider's dependency obligation reads the same way as for any type parameter. The +provider trait, its blanket forwarding impl, and the impls that satisfy it all agree on the same +`(Life<'a>, T)` shape. That shared shape lets CGP wire and check a borrowing component exactly like a +non-borrowing one. ## Examples @@ -76,36 +79,36 @@ the generated provider trait records the lifetime in its dependency marker throu // } ``` -Every impl that wires this component, whether through `UseContext`, a `UseField` getter, or a -hand-written provider, carries the same `(Life<'a>, T)` tuple, so the lifetime is preserved end to end -through the resolution machinery. +Every impl that wires this component, whether through `UseContext`, a `UseField` getter, or a provider you +write yourself, carries the same `(Life<'a>, T)` tuple, so the resolution machinery preserves the lifetime +end to end. ## When to use it -**You read `Life` in generated code; you do not write it.** The macros insert it, and recognizing it is -all that is asked. +**You read `Life` in generated code, and you do not write it.** The macros insert it, and you only need to +recognize it. - **Read `Life<'a>` in an `IsProviderFor` tuple as the component's lifetime.** A dependency marker such - as `IsProviderFor<..., (Life<'a>, T)>` is naming a lifetime and a type parameter, in that order. + as `IsProviderFor<..., (Life<'a>, T)>` names a lifetime and a type parameter, in that order. - **Do not substitute a bare [`PhantomData`](phantom_data.md) for it** when you write a lifetime marker - by hand. A plain `PhantomData<&'a ()>` is covariant, which is the wrong relationship for a dependency - marker; `Life` forces the invariance that keeps two lifetime instantiations distinct. + yourself. A plain `PhantomData<&'a ()>` is covariant, which is the wrong relationship for a dependency + marker. `Life` forces the invariance that keeps two lifetime instantiations distinct. ## Common Mistakes **A lifetime cannot appear directly in the `IsProviderFor` tuple.** The tuple holds types, so a bare -`'a` is invalid there and is lifted into `Life<'a>`. Meeting `Life` in an error is the sign a component +`'a` is invalid there, and the macro lifts it into `Life<'a>`. `Life` in an error means that the component carries a lifetime. -**`Life<'a>` is invariant in `'a`, on purpose.** It does not behave like `&'a ()`, which is covariant. -The invariance keeps providers wired for different lifetimes from being confused, so it is a -feature rather than an over-restriction. +**`Life<'a>` is invariant in `'a` by design.** It does not behave like `&'a ()`, which is covariant. The +invariance keeps the compiler from confusing providers wired for different lifetimes, so it is intended +rather than an over-restriction. -**A higher-order provider with a lifetime loses its dependency propagation.** The inner-provider bound of -such a stack gets no marker counterpart when the component carries a lifetime, because the rewrite reads -the bound's first generic argument as the context and finds a lifetime there. The stack still compiles -and runs; what is lost is the propagation that lets `#[check_providers]` localize a broken layer. This is -a recorded limitation, noted on [`IsProviderFor`](../traits/wiring/is_provider_for.md). +**A higher-order provider with a lifetime loses its dependency propagation.** When the component carries a +lifetime, the inner-provider bound of such a stack does not get a marker counterpart, because the rewrite +reads the bound's first generic argument as the context and finds a lifetime there. The stack still +compiles and runs. But it loses the propagation that lets `#[check_providers]` localize a broken layer. +[`IsProviderFor`](../traits/wiring/is_provider_for.md) records this limitation. ## Related constructs diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 6440c2be..e4ba54be 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -11,26 +11,29 @@ whichever it has without forcing every implementor to one or the other. ## Overview `MRef<'a, T>` lets one getter signature serve both the context that already stores a value and the -context that must produce one. Here a **context** is the type the capability runs against, which supplies -the values it needs as its own fields. A getter that returns `&'a T` forces every context to keep a `T` -it can lend; a getter that returns `T` forces every context to hand over ownership, cloning even when it -has a perfectly good reference to share. `MRef<'a, T>` removes that dilemma by being either case at run -time: a context with the value in a field returns `MRef::Ref` and lends it, while a context that computes -or assembles the value returns `MRef::Owned` and gives it away. The caller treats both the same, because -`MRef` derefs to `T`. - -The type earns its place in CGP's getter machinery, where a getter method's return type decides what body -the macro generates. When a getter returns `MRef<'a, T>` over `&self`, the generated accessor wraps the -borrowed field as `MRef::Ref(...)`, so the common case, reading a stored field, costs nothing extra, -while the same interface still lets a provider elsewhere return an owned value. This lets a -getter abstract over "do I have this value, or do I make it?" without splitting into two traits. - -Unlike the rest of this section, `MRef` is an ordinary runtime value rather than a type-level marker. -It is here because it is the one type in the group you write on purpose, as the return type of a getter. +context that must produce one. Here a **context** is the type the capability runs against. It supplies the +values the capability needs as its own fields. A getter that returns `&'a T` forces every context to keep +a `T` it can lend. A getter that returns `T` forces every context to give up ownership, and to clone even +when it could share a reference. `MRef<'a, T>` avoids both constraints by being either case at run time. A +context with the value in a field returns `MRef::Ref` and lends it. A context that computes or assembles +the value returns `MRef::Owned` and transfers it. The caller treats both the same, because `MRef` derefs +to `T`. + +CGP's getter machinery uses the type directly, because a getter method's return type decides what +body the macro generates. When a getter returns `MRef<'a, T>` over `&self`, the generated accessor +wraps the borrowed field as `MRef::Ref(...)`. So the common case, reading a stored field, costs +nothing extra, and the same interface still lets a provider elsewhere return an owned value. A +getter can therefore leave open whether the context stores the value or makes it, without splitting +into a separate trait for each case. + +Unlike the rest of this section, `MRef` is an ordinary runtime value rather than a type-level marker. It +belongs here because it is the one type in the group that you write yourself, as the return type of a +getter. ## Definition -`MRef` is a two-variant enum parameterized by a lifetime and an element type: +`MRef` is an enum with a borrowed variant and an owned variant, parameterized by a lifetime and an element +type: ```rust pub enum MRef<'a, T> { @@ -39,29 +42,29 @@ pub enum MRef<'a, T> { } ``` -`Ref` borrows a `T` for the lifetime `'a`; `Owned` carries a `T` by value. The lifetime applies only to -the borrowed case, so an `MRef` built from an owned value is effectively unbounded in `'a`. It is an -ordinary owned value, with nothing type-level about it, and it is the payload a getter passes back to its -caller. +`Ref` borrows a `T` for the lifetime `'a`, and `Owned` carries a `T` by value. The lifetime applies only +to the borrowed case, so an `MRef` built from an owned value is effectively unbounded in `'a`. The enum is +an ordinary owned value, with nothing type-level about it, and it is the payload a getter passes back to +its caller. ## Behavior -`MRef` behaves like a smart pointer to `T`, which makes the two variants interchangeable at the -call site. It implements `Deref` by matching on the variant and returning a `&T` either way, -so `&*my_ref` and any auto-deref method call work regardless of which case is inside. It also implements -`AsRef` over the same logic, giving an explicit `as_ref()` for code that prefers it. +`MRef` behaves like a smart pointer to `T`, which makes the variants interchangeable at the call site. It +implements `Deref` by matching on the variant and returning a `&T` either way, so `&*my_ref` +and any auto-deref method call work regardless of which case is inside. It also implements `AsRef` over +the same logic, giving an explicit `as_ref()` for code that prefers it. -Building an `MRef` is frictionless, because it implements `From` in both directions: `From` builds -`Owned` and `From<&'a T>` builds `Ref`, so a value or a reference converts with `.into()`. When a caller -needs ownership unconditionally, `get_or_clone` resolves the enum to a plain `T`, returning the owned -value as is or cloning the borrowed one, and is available whenever `T: Clone`. Together these make up the -whole surface: the transparent `Deref` and `AsRef`, the two `From` impls, and `get_or_clone`. A -borrowed `MRef` is read cheaply and promoted to ownership only when asked. +Building an `MRef` takes a single `.into()`, because it implements `From` for both cases. `From` builds +`Owned`, and `From<&'a T>` builds `Ref`, so a value or a reference converts with `.into()`. When a caller +needs ownership unconditionally, `get_or_clone` resolves the enum to a plain `T`. It returns the owned +value as is or clones the borrowed one, and it is available whenever `T: Clone`. These make up the whole +API: the transparent `Deref` and `AsRef`, the `From` impls, and `get_or_clone`. Code reads a borrowed +`MRef` cheaply and promotes it to ownership only on request. ## Examples `MRef` is the return type of a getter that should work whether the context stores the value or produces -it. A borrowed field and a freshly built value have the same type and are read the same way: +it. A borrowed field and a freshly built value have the same type, and code reads them the same way: ```rust use cgp::prelude::*; @@ -81,36 +84,36 @@ let owned: String = borrowed.get_or_clone(); assert_eq!(owned, "hello"); ``` -Both `borrowed` and `made` have the same type and are consumed the same way; only the construction -differs, and `get_or_clone` clones the borrowed case while moving the owned one. +Both `borrowed` and `made` have the same type, and code consumes them the same way. Only the construction +differs. `get_or_clone` clones the borrowed case and moves the owned one. ## When to use it -**Return `MRef<'a, T>` from a getter that some contexts store and others build.** It is the getter return -mode to reach for when the value is not always a field the context can lend. +**Return `MRef<'a, T>` from a getter that some contexts store and others build.** It is the right getter +return type when the value is not always a field the context can lend. -- **Use a plain `&T` return** when every context stores the value and can lend it. `MRef` earns its keep - only where some context must produce the value instead. +- **Use a plain `&T` return** when every context stores the value and can lend it. `MRef` is useful only + where some context must produce the value instead. - **Use an [`#[implicit]`](../attributes/implicit.md) argument** to read a stored field in a provider, - which is the default for field access; an implicit argument can itself be typed `MRef<'_, T>` when the - field may be lent or produced. -- **Reach for `MRef` with [`#[cgp_getter]`](../macros/cgp_getter.md)** and the + which is the default for field access. An implicit argument can itself have the type `MRef<'_, T>` when + the field may be lent or produced. +- **Use `MRef` with [`#[cgp_getter]`](../macros/cgp_getter.md)** and the [`UseField`](../providers/use_field.md) family, where a getter's return type selects the accessor the macro generates. ## Common Mistakes **`MRef` is not related to [`Life`](life.md).** Its `'a` is an ordinary borrow lifetime on a runtime -value; `Life<'a>` is a zero-sized type-level lift for provider wiring. The shared word "lifetime" is the -only thing they have in common. +value, while `Life<'a>` is a zero-sized type-level lift for provider wiring. They share only the word +"lifetime". **`get_or_clone` clones only the borrowed case.** It moves an `Owned` value and clones a `Ref` one, so it -is free when the getter already owns the value and costs a clone when it borrowed. Reach for it only when -you genuinely need ownership. +is free when the getter already owns the value and costs a clone when it borrowed. Use it only when you +need ownership. **`Deref` makes the variants transparent, so you rarely match on them.** Reading through `&*` or -`as_ref()` works whichever case is inside, and matching on `Ref` versus `Owned` by hand is usually a sign -the value should have been promoted with `get_or_clone` instead. +`as_ref()` works whichever case is inside, and a manual match on `Ref` versus `Owned` usually means the +code should have called `get_or_clone` instead. ## Related constructs diff --git a/docs/reference/types/nil.md b/docs/reference/types/nil.md index 09701d77..4ce9e309 100644 --- a/docs/reference/types/nil.md +++ b/docs/reference/types/nil.md @@ -10,14 +10,14 @@ The end marker of the product, string, and path lists: an empty, constructible l ## Overview `Nil` marks the end of a right-nested type-level list. Where a [`Cons`](cons.md) cell pairs a head with -the rest of the list, `Nil` is the rest when there is nothing left, so a list of any length is a `Cons` -chain that finishes in `Nil`. On its own, `Nil` is the empty list. +the rest of the list, `Nil` is the rest when nothing is left, so a list of any length is a `Cons` chain +that finishes in `Nil`. On its own, `Nil` is the empty list. -The same marker terminates every CGP list but one. It ends the product list built from +The same marker terminates every CGP list except the sum list. It ends the product list built from [`Cons`](cons.md), the string list built from [`Chars`](chars.md), and the path list built from -[`PathCons`](path_cons.md). Only the sum list ends differently, in the uninhabited [`Void`](void.md), -and that difference is the point of both markers: a record, a string, and a path can each be empty and -still exist, so their terminator is a real value. +[`PathCons`](path_cons.md). Only the sum list ends differently, in the uninhabited [`Void`](void.md). That +difference is the point of both markers. A record, a string, and a path can each be empty and still exist, +so their terminator is a real value. ## Definition @@ -28,27 +28,26 @@ still exist, so their terminator is a real value. pub struct Nil; ``` -It carries no data. Used as a tail it terminates a chain, and used on its own it is the empty list. It +It holds nothing. Used as a tail it terminates a chain, and used on its own it is the empty list. It derives `Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a list ending in `Nil` inherits those -traits structurally and `Nil` itself compares equal to `Nil`. +traits structurally, and `Nil` itself compares equal to `Nil`. ## Behavior `Nil` is the base case of every recursion over a list it terminates. An operation that folds over a product implements the step for [`Cons`](cons.md) and the base case for `Nil`, and the -recursion bottoms out when it reaches `Nil`. The string and path lists do the same: a walk over +recursion stops when it reaches `Nil`. The string and path lists work the same way: a walk over [`Chars`](chars.md) stops at `Nil`, and a walk over [`PathCons`](path_cons.md) stops at `Nil`. -Because `Nil` is a real, constructible value, the empty product `Product![]` is `Nil` and the empty value -`product![]` is `Nil` as a value. A builder or a conversion returns this when a shape has no -fields left, and it is why an empty record is a value the program can hold. The contrast with -[`Void`](void.md) is exact: a value with every field ruled out cannot exist, so a sum ends in an -uninhabited marker, while a record ends in this inhabited one. +Because `Nil` is a real, constructible value, the empty product `Product![]` is `Nil`, and the empty +value `product![]` is the `Nil` value. A builder or a conversion returns it when every field of a +shape has been consumed. This is why an empty record is a value the program can hold. The contrast +with [`Void`](void.md) is exact. A value with every branch ruled out cannot exist, so a sum ends in +an uninhabited marker, while a record ends in this inhabited one. ## Examples -`Nil` closes off every product chain, visible when the [`Product!`](../macros/product.md) sugar is -expanded: +`Nil` ends every product chain, which the expansion of [`Product!`](../macros/product.md) shows: ```rust use cgp::prelude::*; @@ -70,24 +69,24 @@ It also terminates a [`Symbol!`](../macros/symbol.md) character chain and a ## When to use it -**You read `Nil` at the end of a chain; you do not write it.** The sugar produces it, and recognizing it -is all that is asked. +**You read `Nil` at the end of a chain, and you do not write it.** The macros produce it, and you +only need to recognize it. - **Read `Nil` as "the list ends here."** In an expanded `Cons`, `Chars`, or `PathCons` chain, the `Nil` is the terminator and marks the count of cells before it. - **Expect `Nil`, not [`Void`](void.md), at the end of a record, a string, or a path.** A sum ends in - `Void`; the other three lists end in `Nil`. Meeting the wrong terminator in an error usually means the - product and sum families have been crossed. + `Void`, and the other lists end in `Nil`. The wrong terminator in an error usually means the product and + sum families have been mixed up. ## Common Mistakes -**`Nil` is inhabited; [`Void`](void.md) is not.** `Nil` is a real value the empty product is, while `Void` -is an uninhabited type an empty choice would be. They are not interchangeable, and the whole extractor +**`Nil` is inhabited, and [`Void`](void.md) is not.** `Nil` is the real value of the empty product, while +`Void` is the uninhabited type of an empty choice. They are not interchangeable, and the extractor machinery depends on the difference. -**`Nil` terminates three lists, not just the product one.** A `Nil` at the end of a +**`Nil` terminates the string and path lists as well as the product list.** A `Nil` at the end of a [`Chars`](chars.md) chain or a [`PathCons`](path_cons.md) chain is the same marker doing the same job, so -seeing it outside a record is expected. +it is expected outside a record. ## Related constructs diff --git a/docs/reference/types/path_cons.md b/docs/reference/types/path_cons.md index abfaee38..dcc55882 100644 --- a/docs/reference/types/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -11,40 +11,38 @@ lookup can reach an entry several layers deep. ## Overview `PathCons` expresses a *route* through nested delegation tables as a single type. A bare -component name picks one entry out of a context's table, where the **context** is the type the capability -runs against and the table records which provider it uses for each component. Sometimes the entry a -lookup wants lives behind one or more layers of indirection: inside a namespace, behind a namespace it -inherits from, under a prefix. A path names such a route, as a list of segments read left to right, each -one narrowing the lookup a step further. `PathCons` is the cell of that list, and [`Nil`](nil.md) -terminates it, so `PathCons>` is the two-step path "first `A`, then `B`". - -A path differs from the [`Cons`](cons.md) product list, even though both are right-nested and -`Nil`-terminated, and the difference is the unsized bound. `PathCons` declares its head and tail -`?Sized`, so a segment may be a trait object or another unsized type and the whole path can be -manipulated without its parts having a known size. A product list keys a struct's fields and its -elements are always sized values; a path keys a lookup and its segments are pure type-level markers that -never need to be `Sized`. - -The segments are the markers CGP uses elsewhere: a lowercase dotted name becomes a +component name picks one entry out of a context's table. Here the **context** is the type the capability +runs against, and its table records which provider it uses for each component. Sometimes the entry a +lookup wants sits behind a layer of indirection: inside a namespace, behind a namespace it inherits from, +or under a prefix. A path names such a route as a list of segments read left to right, and each segment +narrows the lookup a step further. `PathCons` is the cell of that list, and [`Nil`](nil.md) terminates +it, so `PathCons>` is the path that steps through `A` and then `B`. + +A path differs from the [`Cons`](cons.md) product list in its unsized bound, even though both are +right-nested and end in `Nil`. `PathCons` declares its head and tail `?Sized`, so a segment may be a trait +object or another unsized type, and code can manipulate the whole path without its parts having a known +size. A product list keys a struct's fields, and its elements are always sized values. A path keys a +lookup, and its segments are pure type-level markers that never need to be `Sized`. + +The segments are the markers CGP uses elsewhere. A lowercase dotted name becomes a [`Symbol`](chars.md) type-level string, and a capitalized name becomes that named type, usually a -component key such as `FooProviderComponent` or a namespace marker. A path is therefore an interleaving -of symbols and component names, the form `@a.B.c`, assembled into a `PathCons` chain. You write paths -through the [`Path!`](../macros/path.md) macro, so this page is the runtime list and that macro's page -carries the `@`-segment syntax. +component key such as `FooProviderComponent` or a namespace marker. So a path interleaves symbols and +component names, in the form `@a.B.c`, assembled into a `PathCons` chain. You write paths through the +[`Path!`](../macros/path.md) macro. This page covers the list type, and that macro's page covers the +`@`-segment syntax. ## Definition -`PathCons` is a zero-sized struct holding two phantom markers, one for the head segment and one for the -rest: +`PathCons` is a zero-sized struct holding a phantom marker for the head segment and another for the rest: ```rust pub struct PathCons(pub PhantomData, pub PhantomData); ``` -`Head` is the first segment and `Tail` is the remainder, expected to be either another `PathCons` or -[`Nil`](nil.md) at the end. Both bounds are `?Sized`, so any type may occupy a segment. The struct carries -no runtime data: like the other type-level building blocks it exists through -[`PhantomData`](phantom_data.md) so a route can be named and matched in trait resolution. +`Head` is the first segment, and `Tail` is the remainder, which is another `PathCons` or [`Nil`](nil.md) +at the end. Both bounds are `?Sized`, so any type may occupy a segment. The struct holds nothing at run +time. Like the other type-level building blocks, it exists through [`PhantomData`](phantom_data.md) so +that trait resolution can name and match a route. ## Behavior @@ -55,18 +53,18 @@ another at the type level. The trait recurses down the list: `PathCons` whose `Path` is a -`PathCons` chain, and `RedirectLookup` follows the chain segment by segment until it lands on a concrete -provider. The path never names a provider itself; it only describes where to look, so the same path can -resolve to different providers depending on the table it is walked against. +Beyond concatenation, [`RedirectLookup`](../providers/redirect_lookup.md) consumes a path. That provider +resolves a delegation by walking a context's table along the path. When a namespace or a prefixed +component reroutes a lookup, it produces a `RedirectLookup` whose `Path` is a `PathCons` +chain, and `RedirectLookup` follows the chain segment by segment until it reaches a concrete provider. The +path never names a provider itself. It only describes where to look, so the same path can resolve to +different providers depending on the table `RedirectLookup` walks. ## Examples -Paths are produced by the [`Path!`](../macros/path.md) macro and most often appear inside the wirings -that [`cgp_namespace!`](../macros/cgp_namespace.md) emits. A namespace entry that redirects one -component key to a path desugars into a `RedirectLookup` over a `PathCons` chain: +The [`Path!`](../macros/path.md) macro produces paths, and they most often appear inside the wirings that +[`cgp_namespace!`](../macros/cgp_namespace.md) emits. A namespace entry that redirects one component key +to a path expands into a `RedirectLookup` over a `PathCons` chain: ```rust use cgp::prelude::*; @@ -84,23 +82,25 @@ cgp_namespace! { // } ``` -A path with both a lowercase symbol segment and a capitalized component segment interleaves the two -marker kinds. Registering a component into a namespace under a prefix produces a two-segment path: +A path can interleave lowercase symbol segments with capitalized component segments. Registering a +component into a namespace under a prefix produces a path that steps through the prefix and then the +component: ```rust // @MyBarComponent.BarProviderComponent expands to // PathCons> ``` -The lookup steps first through `MyBarComponent` and then through `BarProviderComponent` before -resolving. A single-segment path is `PathCons`, and the empty path is [`Nil`](nil.md) alone. +The lookup steps through `MyBarComponent` and then through `BarProviderComponent` before it resolves. A +single-segment path is `PathCons`, and the empty path is [`Nil`](nil.md) alone. ## When to use it -**You read `PathCons` in an expansion; you write [`Path!`](../macros/path.md), or wire a namespace.** +**You read `PathCons` in an expansion. You write [`Path!`](../macros/path.md), or you wire a namespace.** -- **Decode a `PathCons` chain by reading the segments left to right.** Each is one step of the route, a - [`Symbol`](chars.md) for a lowercase name or a component or namespace type for a capitalized one. +- **Decode a `PathCons` chain by reading the segments left to right.** Each segment is one step of the + route: a [`Symbol`](chars.md) for a lowercase name, or a component or namespace type for a capitalized + one. - **Use [`Path!`](../macros/path.md) to write a path** when you need one directly, in its `@a.B.c` form. - **Use a namespace rather than a raw path** for the common case: joining a @@ -109,16 +109,16 @@ resolving. A single-segment path is `PathCons`, and the empty path ## Common Mistakes -**A path names a route, not a provider.** A `PathCons` chain describes where to look; which provider it -resolves to depends on the table [`RedirectLookup`](../providers/redirect_lookup.md) walks it against. -The same path can land on different providers in different contexts. +**A path names a route, not a provider.** A `PathCons` chain describes where to look. The provider it +resolves to depends on the table that [`RedirectLookup`](../providers/redirect_lookup.md) walks. The same +path can resolve to different providers in different contexts. **A path list is `?Sized`, unlike the [`Cons`](cons.md) product list.** Its segments are markers rather than values, so a segment need not have a known size. Expecting a path to behave like a product list of values is the usual source of confusion. -**Both a path and a product end in [`Nil`](nil.md).** Seeing `Nil` at the end of a `PathCons` chain is -the same terminator doing the same job it does for a record, not a sign the two lists have been mixed. +**Both a path and a product end in [`Nil`](nil.md).** A `Nil` at the end of a `PathCons` chain is the +same terminator doing the same job it does for a record. It does not mean the two lists have been mixed. ## Related constructs @@ -145,7 +145,7 @@ The ideas behind it: [`nil.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/types/nil.rs) - The `ConcatPath` trait and impls: [`concat_path.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-base-types/src/traits/concat_path.rs) -- The constructing macro is [`Path!`](../macros/path.md); `RedirectLookup`, which consumes a path, is +- The constructing macro is [`Path!`](../macros/path.md). `RedirectLookup`, which consumes a path, is in [`redirect_lookup.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/redirect_lookup.rs) diff --git a/docs/reference/types/phantom_data.md b/docs/reference/types/phantom_data.md index 62109658..7668c617 100644 --- a/docs/reference/types/phantom_data.md +++ b/docs/reference/types/phantom_data.md @@ -5,29 +5,28 @@ sidebar_position: 1 # `PhantomData` -The standard-library marker that lets a type carry a type parameter it stores no value of. It makes -CGP's zero-sized providers and type-level markers legal, and it is the token you pass to hand a -type to a function. +The standard-library marker that lets a type carry a type parameter without storing a value of it. +It makes CGP's zero-sized providers and type-level markers legal, and it is the value you pass to +give a function a type instead of data. ## Overview -`PhantomData` is not a CGP type. It comes from the Rust standard library, in -[`core::marker`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html). It appears so often in -CGP code, and does a job so specific, that it is worth one page explaining what it is really for, -because a reader who has only seen it as noise in a struct definition will misread half of what CGP -generates. +`PhantomData` is a standard-library type, not a CGP type. It comes from +[`core::marker`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html). It has a page here because +it appears throughout CGP code and does one specific job. A reader who has only seen it as noise in a +struct definition will misread much of what CGP generates. -CGP uses it in two ways, worked through below: **declaring** a type that is generic over something it -never stores, and **passing** a type to a function as a zero-sized token. +CGP uses it for **declaring** a type that is generic over something it never stores, and for **passing** a +type to a function as a zero-sized value. The sections below work through both uses. ## Why a marker needs it -Rust requires every generic parameter on a type to be *used* by that type, in a field or a bound. A -type-level marker breaks that rule on purpose: it is generic over a parameter it stores no value of, +Rust requires a type to *use* every generic parameter it declares, in a field or in a bound. A type-level +marker conflicts with that rule by design. It is generic over a parameter without storing a value of it, because the parameter is part of the type's identity rather than its data. -A provider is the clearest case. `Multiply` holds no runtime data, yet it must be generic over -`Field` so the wiring can tell one instance from another. Written as a plain unit struct, it does not +A provider is the clearest case. `Multiply` stores nothing at run time, yet it must be generic over +`Field` so that the wiring can tell one instance from another. Written as a plain unit struct, it does not compile: ```rust @@ -36,7 +35,7 @@ pub struct Multiply; ``` `PhantomData` is the fix. It is a zero-sized field that tells the compiler to treat the type as -though it holds a `Field`, so the parameter counts as used and nothing is added at run time: +though it holds a `Field`, so the parameter counts as used and the struct stays empty at run time: ```rust use core::marker::PhantomData; @@ -55,37 +54,36 @@ is still zero-sized. pub struct PhantomData; ``` -That definition is itself the shape the previous section said the compiler rejects: a struct generic -over a `T` it stores nowhere. `PhantomData` compiles anyway because it is built into the compiler. It -carries a `#[lang = "phantom_data"]` attribute the compiler recognizes, so it alone is exempt from the -unused-parameter rule and can be the marker every other type reaches for. Those types satisfy the rule -by *holding* a `PhantomData` field rather than by being one. - -The parameter is `?Sized`, so `T` may be any type, sized or not. A value of `PhantomData` occupies -no space and holds nothing; its only content is the type `T` recorded in its own type. You construct -one by writing `PhantomData`, and you name the type it carries with a turbofish where inference cannot, -as in `PhantomData::`. - -Because the type parameter is recorded but no value of it is stored, `PhantomData` also tells the -compiler how the surrounding type relates to `T`, beyond the "used parameter" rule: it sets -**variance** (whether a longer lifetime may stand in for a shorter one), **drop checking**, and the -**auto traits** such as `Send` and `Sync`. Most CGP markers do not care which relationship they get and -use the plain `PhantomData`. The exception is [`Life`](life.md), which wraps its lifetime as -`PhantomData<*mut &'a ()>` on purpose, to force invariance so two lifetime instantiations are treated -as genuinely different. That page explains why. +That definition has the shape the previous section said the compiler rejects: a struct generic over a `T` +that it stores nowhere. `PhantomData` compiles anyway because the compiler knows it. It carries a +`#[lang = "phantom_data"]` attribute that the compiler recognizes, so it alone is exempt from the +unused-parameter rule, and every other marker type can use it. Those types satisfy the rule by *holding* a +`PhantomData` field rather than by being one. + +The parameter is `?Sized`, so `T` may be any type, sized or not. A value of `PhantomData` occupies no +space and holds nothing. Its only content is the type `T`, recorded in its own type. You construct one by +writing `PhantomData`. Where inference cannot supply the type, you name it with a turbofish, as in +`PhantomData::`. + +`PhantomData` also tells the compiler how the surrounding type relates to `T`, beyond satisfying the +used-parameter rule. It sets **variance** (whether a longer lifetime may stand in for a shorter one), drop +checking, and the auto traits such as `Send` and `Sync`. Most CGP markers do not depend on which +relationship they get, so they use the plain `PhantomData`. [`Life`](life.md) is the exception. It +wraps its lifetime as `PhantomData<*mut &'a ()>` to force invariance, so that the compiler treats two +lifetime instantiations as different types. That page explains why. ## How CGP uses it -The two uses are the declaring side and the passing side, and they look different in the code. +The declaring side and the passing side look different in the code. **On the declaring side, `PhantomData` fills the field of a zero-sized type**, the way `Multiply` above carries it. The same pattern runs through CGP's recursive type-level lists: a [`Chars`](chars.md) node holds its next node in a `PhantomData`, a [`PathCons`](path_cons.md) holds both its head and tail that way, and a [`Field`](field.md) holds its type-level name tag in a `PhantomData` beside the one real value it stores. In each case the -parameter is part of the type's identity and nothing the type keeps at run time. +parameter is part of the type's identity, and the type does not keep a value of it at run time. -**On the passing side, `PhantomData::` is a zero-sized value that hands the type `T` to a +**On the passing side, `PhantomData::` is a zero-sized value that passes the type `T` to a function.** A method that must know which field, which computation, or which tag is meant takes a `PhantomData` argument, and the caller supplies the type through it: @@ -97,22 +95,22 @@ let name = self.get_field(PhantomData::); let output = context.compute(PhantomData::, input); ``` -Here the **context** is the type the capability runs against, which supplies the values it needs as its -own fields. The `PhantomData` argument carries no data; it exists so that type inference selects the -right [`HasField`](../traits/field-access/has_field.md) impl or the right handler. You could think of it -as passing a type where a value is expected, with `PhantomData::` as the empty value that stands for -the type `T`. +Here the **context** is the type the capability runs against. It supplies the values the capability +needs as its own fields. The `PhantomData` argument carries nothing. It exists so that type +inference selects the right [`HasField`](../traits/field-access/has_field.md) impl or the right +handler. In effect, the call passes a type where a value is expected, and `PhantomData::` is the +empty value that stands for the type `T`. -**You rarely write either role by hand; a higher-level construct produces each for you.** +**You rarely write either role yourself, because a higher-level construct produces each for you.** - On the declaring side, the `new` keyword of [`#[cgp_impl]`](../macros/cgp_impl.md) declares the provider struct: a `PhantomData` field per generic parameter, or a bare `struct Foo;` when there are none. - On the passing side, [`#[implicit]`](../attributes/implicit.md) and - [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) read a context field without the tag, so no - `get_field(PhantomData::<...>)` appears in your code. + [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) read a context field without the tag, so your code + does not contain a `get_field(PhantomData::<...>)` call. -You meet `PhantomData` directly only when you drop below these constructs. +You meet `PhantomData` directly only when you work below these constructs. ## Examples @@ -133,10 +131,10 @@ where } ``` -This is the form you meet in an expansion rather than one you write: the idiomatic version uses an -[`#[implicit]`](../attributes/implicit.md) argument and shows no `PhantomData` at all. +You meet this form in an expansion rather than write it. The idiomatic version uses an +[`#[implicit]`](../attributes/implicit.md) argument and does not show `PhantomData` at all. -A type that carries two parameters uses one `PhantomData` over a tuple: +A type with several parameters uses one `PhantomData` over a tuple: ```rust pub struct Add(pub PhantomData<(Left, Right)>); @@ -144,36 +142,37 @@ pub struct Add(pub PhantomData<(Left, Right)>); ## When to use it -**You write `PhantomData` yourself in only two places.** Everywhere else the macros insert it for you. +**You write `PhantomData` yourself only to declare a marker field or to pass a type at a call site.** +Everywhere else the macros insert it for you. -- **Declare a `PhantomData` field** when you write a zero-sized struct that is generic over a type it - stores no value of, such as a provider struct you define by hand rather than through +- **Declare a `PhantomData` field** when you write a zero-sized struct that is generic over a type without + storing a value of it, such as a provider struct you define yourself rather than through [`#[cgp_new_provider]`](../macros/cgp_provider.md). One `PhantomData` over a tuple covers several parameters. - **Pass `PhantomData::`** at a call site that takes a type-level selector, such as `get_field` or a - handler's `compute`. This is the common hand-written use, and the turbofish is how you name the type - when inference cannot. -- **Reach for [`Life`](life.md), not a bare `PhantomData`, for a lifetime** you need to keep invariant. - A plain `PhantomData<&'a ()>` is covariant, which is the wrong relationship for a dependency marker. + handler's `compute`. This is the common case you write yourself, and the turbofish names the type when + inference cannot. +- **Use [`Life`](life.md), not a bare `PhantomData`, for a lifetime** that must stay invariant. A plain + `PhantomData<&'a ()>` is covariant, which is the wrong relationship for a dependency marker. ## Common Mistakes **It costs nothing at run time.** `PhantomData` is zero-sized whatever `T` is, so a struct full of -`PhantomData` fields is still zero-sized, and a `PhantomData` argument compiles to nothing. Seeing it in -a signature is not a sign of a hidden allocation. +`PhantomData` fields is still zero-sized, and a `PhantomData` argument compiles to nothing. A +`PhantomData` in a signature does not mean a hidden allocation. **`PhantomData` and `PhantomData::` differ only by whether the type is inferred.** In a struct field the type comes from the field's declared type, so plain `PhantomData` is enough. At a call site where -nothing pins `T`, the turbofish `PhantomData::` states it, and omitting it gives a +nothing fixes `T`, the turbofish `PhantomData::` states it, and omitting it gives a "type annotations needed" error rather than a wrong result. -**A bare `PhantomData<&'a ()>` is covariant.** If you write a lifetime marker by hand and let a longer +**A bare `PhantomData<&'a ()>` is covariant.** If you write a lifetime marker yourself and let a longer lifetime stand in for a shorter one, the compiler may pick a provider wired for a different lifetime. Use [`Life<'a>`](life.md), whose `PhantomData<*mut &'a ()>` forces invariance, when the lifetime is an exact identity. -**A generic marker needs its `PhantomData` field.** A struct generic over a `T` it stores no value of -fails to compile with `error[E0392]` without one. +**A generic marker needs its `PhantomData` field.** A struct that is generic over a `T` without storing a +value of it fails to compile with `error[E0392]`. ## Related constructs diff --git a/docs/reference/types/void.md b/docs/reference/types/void.md index d91007a7..d0185a08 100644 --- a/docs/reference/types/void.md +++ b/docs/reference/types/void.md @@ -6,19 +6,19 @@ sidebar_position: 8 # `Void` The uninhabited end marker of the sum list: an empty enum that can never be constructed, which lets a -total variant match close with no runtime branch. +complete variant match end without a runtime branch. ## Overview -`Void` marks the end of a sum, and unlike the [`Nil`](nil.md) that ends the other lists, it is -uninhabited: it has no values. Where a record, a string, or a path can each be empty and still exist, -an empty *choice* cannot. There is no value that is "none of the branches", so the natural terminator -for the sum list is a type with no values at all. +`Void` marks the end of a sum. Unlike the [`Nil`](nil.md) that ends the other lists, it is uninhabited: a +value of `Void` cannot exist. A record, a string, or a path can each be empty and still exist, but an +empty *choice* cannot. A value that is "none of the branches" cannot exist, so the natural terminator for +the sum list is a type without values. -That uninhabitedness is not a technicality; it makes the sum list work. An [`Either`](either.md) -chain ends in `Void`, so a value that walked past every real branch would have type `Void`, which is -impossible to reach. The chain is therefore closed at its end by construction, and a match that has -handled every real variant has nothing left to handle. +The sum list depends on this uninhabitedness. An [`Either`](either.md) chain ends in `Void`, so a +value that passed every real branch would have type `Void`, and such a value cannot exist. So the +chain is closed at its end by its definition, and a match that has handled every real variant has +nothing left to handle. ## Definition @@ -29,22 +29,21 @@ handled every real variant has nothing left to handle. pub enum Void {} ``` -It has no variants, so it has no values: it is uninhabited, the same idea as Rust's never type. It -derives the standard traits so a sum ending in `Void` can inherit them, but no value of `Void` is ever -built, so those impls are never run on one. +Its variant list is empty, so it is uninhabited, like Rust's never type. It derives the standard +traits so that a sum ending in `Void` can inherit them. But code never builds a value of `Void`, so +those impls never run on one. ## Behavior -`Void` is the base case of a recursion over a sum, and it behaves differently from the product list's -base case in exactly one way that matters. A walk over an [`Either`](either.md) chain handles each -`Left` as a branch and defers each `Right` to the tail, until the tail is `Void`, at which point there -is nothing left to handle. +`Void` is the base case of a recursion over a sum, and it differs from the product list's base case in a +way that matters. A walk over an [`Either`](either.md) chain handles each `Left` as a branch and defers +each `Right` to the tail, until the tail is `Void`. At that point nothing is left to handle. -The uninhabitedness is essential to the extractor machinery. After an extractor has tried every -variant of a sum and matched none, the leftover value has type `Void`, a value that cannot exist. -[`FinalizeExtract`](../traits/variant/finalize_extract.md) for `Void` turns that into any required -type with an empty `match self {}`, since there are no cases to handle, so a fully-handled variant -extraction is total at compile time with no unreachable runtime branch: +The extractor machinery depends on this uninhabitedness. After an extractor has tried every variant of a +sum and matched none, the leftover value has type `Void`, so it cannot exist. +[`FinalizeExtract`](../traits/variant/finalize_extract.md) for `Void` turns that value into any required +type with an empty `match self {}`, because nothing remains to handle. So a fully handled variant +extraction is complete at compile time and does not need an unreachable runtime branch: ```rust // schematically: @@ -55,13 +54,13 @@ impl FinalizeExtract for Void { } ``` -A constructible terminator like [`Nil`](nil.md) could not be discharged this way, because the compiler -would demand a value for the `Nil` case. Only an uninhabited type lets the empty match stand, which is -why the sum list terminates in `Void` and the product list in `Nil`. +A constructible terminator like [`Nil`](nil.md) could not be consumed this way, because the compiler would +demand an arm for the `Nil` case. Only an uninhabited type lets the empty match stand. This is why the sum +list terminates in `Void` and the product list in `Nil`. ## Examples -`Void` closes off every sum chain, visible when the [`Sum!`](../macros/sum.md) sugar is expanded: +`Void` ends every sum chain, which the expansion of [`Sum!`](../macros/sum.md) shows: ```rust use cgp::prelude::*; @@ -73,29 +72,29 @@ type Token = Either>; type Empty = Sum![]; // == Void ``` -You do not construct a `Void`; you discharge one. The only thing code does with a `Void` value is match -on it with no arms, which the extractor family does when a variant match is complete. +You do not construct a `Void`. You only eliminate one. The only thing code does with a `Void` value is +match on it with an empty `match`, and the extractor family does that when a variant match is complete. ## When to use it -**You read `Void` at the end of a sum and in an extractor's type; you do not write it.** +**You read `Void` at the end of a sum and in an extractor's type, and you do not write it.** - **Read `Void` as "the choice ends here, and this point is unreachable."** In an expanded [`Either`](either.md) chain, the `Void` marks the end, and a value can never sit at it. - **Expect `Void`, not [`Nil`](nil.md), at the end of a variant.** A record, a string, and a path end in - `Nil`; a variant ends in `Void`. Meeting the wrong terminator in an error usually means the product and - sum families have been crossed. + `Nil`, and a variant ends in `Void`. The wrong terminator in an error usually means the product and sum + families have been mixed up. - **Recognize `Void` in a [`FinalizeExtract`](../traits/variant/finalize_extract.md) error** as the all-ruled-out remainder of a variant extraction. ## Common Mistakes -**`Void` is uninhabited; [`Nil`](nil.md) is not.** `Nil` is a real value the empty product is, while -`Void` is a type with no values. Records use `Nil`, variants use `Void`, and an error naming the -wrong one usually means the two families have been crossed. +**`Void` is uninhabited, and [`Nil`](nil.md) is not.** `Nil` is the real value of the empty product, while +`Void` is a type without values. Records use `Nil`, and variants use `Void`. An error that names the wrong +one usually means the two families have been mixed up. -**You cannot build a `Void`.** There is no constructor and no literal for it, by design. Any code that -appears to "return a `Void`" is really an empty match that never returns at all. +**You cannot build a `Void`.** It has neither a constructor nor a literal, by design. Code that appears to +"return a `Void`" is really an empty match that never returns. ## Related constructs @@ -103,7 +102,7 @@ appears to "return a `Void`" is really an empty match that never returns at all. - [`Nil`](nil.md): the product, string, and path lists' constructible end marker, the counterpart to this one. - [`Sum!`](../macros/sum.md): the macro whose empty form is `Void`. -- [`FinalizeExtract`](../traits/variant/finalize_extract.md): discharges the uninhabited remainder of +- [`FinalizeExtract`](../traits/variant/finalize_extract.md): eliminates the uninhabited remainder of a variant extraction with an empty match. - [`FinalizeExtractResult`](../traits/variant/finalize_extract_result.md): the result-carrying form built on the same idea. @@ -118,7 +117,7 @@ The ideas behind it: - `Void` is in [`sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/sum.rs), alongside [`Either`](either.md) -- `FinalizeExtract for Void`, which discharges the uninhabited remainder: +- `FinalizeExtract for Void`, which eliminates the uninhabited remainder: [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) --- From c6c88628e7d149127c3adf72071ef6c0d79901e6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 14:30:30 +0200 Subject: [PATCH 058/516] docs(reference/macros): plain-English pass over the macros reference Flatten idioms and metaphors, remove stated-count openers, rewrite pseudo-clefts, and take em dashes out of prose across all 21 macro reference pages, following the point-first-writing guidance. Code blocks, links, error text, and technical claims are unchanged. Co-Authored-By: Claude Opus 4.8 --- docs/reference/macros/async_trait.md | 6 ++-- docs/reference/macros/blanket_trait.md | 8 ++--- docs/reference/macros/cgp_auto_dispatch.md | 10 +++--- docs/reference/macros/cgp_auto_getter.md | 18 +++++------ docs/reference/macros/cgp_component.md | 22 ++++++------- docs/reference/macros/cgp_computer.md | 18 +++++------ docs/reference/macros/cgp_fn.md | 20 ++++++------ docs/reference/macros/cgp_getter.md | 24 +++++++------- docs/reference/macros/cgp_impl.md | 10 +++--- docs/reference/macros/cgp_namespace.md | 24 +++++++------- docs/reference/macros/cgp_producer.md | 20 ++++++------ docs/reference/macros/cgp_provider.md | 12 +++---- docs/reference/macros/cgp_type.md | 14 ++++---- docs/reference/macros/check_components.md | 8 ++--- .../macros/delegate_and_check_components.md | 14 ++++---- docs/reference/macros/delegate_components.md | 32 +++++++++---------- docs/reference/macros/index.md | 16 +++++----- docs/reference/macros/path.md | 6 ++-- docs/reference/macros/product.md | 2 +- docs/reference/macros/sum.md | 6 ++-- docs/reference/macros/symbol.md | 6 ++-- 21 files changed, 148 insertions(+), 148 deletions(-) diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 444739a4..2cd298ea 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -141,13 +141,13 @@ The decisions worth making are around it rather than about it. - **Do not put it on an impl block.** It is accepted there and does nothing, since the rewrite only applies to trait definitions. Harmless, but it suggests a misunderstanding of where the lint comes from. -- **Reach for the `Send`-recovery pattern when a future is spawned**, not for a different macro. No attribute +- **Use the `Send`-recovery pattern when a future is spawned**, not a different macro. No attribute can add the bound, for the reason in the [Common Mistakes](#common-mistakes). - **Consider whether the capability needs to be async at all.** The [handler family](./cgp_computer.md) has synchronous members, and the [promotion combinators](../providers/handler/index.md) lift a synchronous provider into an async one where a caller needs it. So a computation that does no I/O is better declared synchronous and promoted than declared async out of habit. -- **Reach for the `async-trait` crate instead only if you need `dyn` compatibility.** Boxing makes an +- **Use the `async-trait` crate instead only if you need `dyn` compatibility.** Boxing makes an async trait object-safe, and this macro deliberately does not box. CGP resolves providers statically, so it does not need `dyn`; a codebase that does for other reasons is outside what this macro is for. @@ -179,7 +179,7 @@ pub trait CanFetch { } ``` -Three things to read off it. The `Output` is the original return type verbatim. The bodiless `run` picked up +A few things to read off it. The `Output` is the original return type verbatim. The bodiless `run` picked up `Output = ()`. And `sync_method` was left completely alone, which lets a trait mix async and synchronous methods. diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 8635f1af..b6b90f2f 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -146,7 +146,7 @@ Any type that is `Foo + Bar` is now `FooBar`, and a signature can say so in one ## When to use it -**Reach for `#[blanket_trait]` when a capability has one definition and its dependencies are other traits.** +**Use `#[blanket_trait]` when a capability has one definition and its dependencies are other traits.** That last clause is the real discriminator, separating this macro from its closest neighbour. - **[`#[cgp_fn]`](./cgp_fn.md) when the dependencies are context *fields*.** Both macros produce a @@ -158,7 +158,7 @@ That last clause is the real discriminator, separating this macro from its close every type satisfying its bounds, which leaves nowhere for an alternative to live. Promoting later is cheap (the trait keeps its name and method), so starting here costs nothing if that changes. - **A trait alias, when one exists.** The empty-body form above is a workaround for a language feature Rust - does not have on stable; it is the right workaround, but do not reach for the macro if a plain supertrait + does not have on stable; it is the right workaround, but do not use the macro if a plain supertrait bound reads fine at the use site. - **Nothing at all, for a plain generic function.** If the requirement belongs in the signature and no caller is generic over the type, a function with a `where` clause is simpler and the propagation @@ -218,7 +218,7 @@ where {} ``` -Associated types are where the expansion earns its keep. Each becomes a new generic parameter on the impl, +Associated types are where the expansion does its real work. Each becomes a new generic parameter on the impl, the supertrait's equality bound is rewritten to name that parameter, and the impl assigns it back: ```rust @@ -298,7 +298,7 @@ Where a type needs different behaviour, the trait wants to be a [component](./cg The ideas behind it: -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the idea this macro automates — +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — the idea this macro automates: requirements that live on the impl rather than the interface. - [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) — where a blanket trait sits between a plain trait and a full component. diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index d2d97944..07b7f098 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -30,7 +30,7 @@ trait, its per-type impls, and a derive on the enum. **Its value is narrower than it looks, and worth naming precisely.** It fits when the per-variant behaviour is *exactly* "call the same trait method on the payload". The moment a variant needs different handling, or the dispatch should be chosen by a **context** (the type the capability runs against) rather than fixed on -the enum, reach for the combinators directly. This is the convenient front end to +the enum, use the combinators directly. This is the convenient front end to [dispatching](../providers/dispatch/index.md), not a replacement for it. ## Usage @@ -47,7 +47,7 @@ pub trait HasArea { The trait may have generic parameters and supertraits. Each method may take `self` by value, by shared reference, or by mutable reference; may take further value or reference arguments; and may be `async`. -Two restrictions are enforced when the macro expands: +A couple of restrictions are enforced when the macro expands: - **Every trait item must be a method.** Associated types and constants are rejected. - **A method may not have non-lifetime generic parameters.** Lifetimes are fine. The reason is in the @@ -129,10 +129,10 @@ shape.scale(2.0); ## When to use it -**Reach for it when an existing per-type trait should also work on an enum of those types, unchanged.** That +**Use it when an existing per-type trait should also work on an enum of those types, unchanged.** That is the case it is built for, and within it there is nothing shorter. -Reach for something else in four situations. +Use something else in these situations: - **The behaviour differs per variant.** The macro generates one handler that calls the same method on every payload. When a variant needs something else, use the @@ -188,7 +188,7 @@ where } ``` -Three things are worth reading off that. The matcher is invoked with a **unit context and unit code** +A few things are worth reading off that. The matcher is invoked with a **unit context and unit code** (`&()` and `PhantomData::<()>`), because the per-variant logic depends only on the payload, which is exactly why a context cannot influence it. The `__Variants__: HasExtractor` bound requires the enum to be extensible. And **the first `where` bound is where a missing variant impl is reported**: it says the matcher diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 03d67db0..af916a46 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -30,11 +30,11 @@ It hides the field-access trait CGP reads fields through, which is precise and u hand: a bound naming the field as a type-level string, and a `PhantomData` tag at every read. Being able to state the same thing as `fn name(&self) -> &str;` is the point. -**Reach for it sparingly.** For the ordinary case, a provider reading a field of its own context, an +**Use it sparingly.** For the ordinary case, a provider reading a field of its own context, an [`#[implicit]`](../attributes/implicit.md) argument does the same job with no trait to declare, using the same field access and the same conversion rules, so a getter trait declared only to read a field adds a -name and buys nothing. What a getter trait *does* buy is a capability other code can depend on by name, -and the three cases where that matters are in +name and gives nothing back. A getter trait *does* give you one thing: a capability other code can depend on by name. +The cases where that matters are in [When to use it](#when-to-use-it). ## Usage @@ -83,7 +83,7 @@ through `AsMut<[T]>`, `Option<&mut T>` via `.as_mut()`, and `Option<&mut str>` v The `&str` row is the one most often wanted and least obvious: the context stores a `String` and the getter hands out a borrow of it, so no context ever has to hold a `&str`. **These are the same rules an [`#[implicit]`](../attributes/implicit.md) argument follows**, so learning them once covers everywhere CGP -reads a field. There is one difference worth holding onto. A getter takes its mutability from the +reads a field. There is one difference worth remembering. A getter takes its mutability from the **receiver**, while an implicit argument takes it from the *argument's type*. So `fn name(&mut self) -> &mut String` reads mutably because of the `&mut self`, whereas `#[implicit] name: &String` on a `&mut self` method still reads through a shared borrow. @@ -205,13 +205,13 @@ only job was to save you writing the body. ## When to use it -**Prefer an [`#[implicit]`](../attributes/implicit.md) argument, and reach for a getter trait only when one +**Prefer an [`#[implicit]`](../attributes/implicit.md) argument, and use a getter trait only when one cannot do the job.** An implicit argument reads a field of the provider's own context as an ordinary parameter, with no trait, no declaration, and the same access rules, so it covers the common read directly, including a field several providers each consume, declared as the same implicit argument in each. -A getter trait earns its keep in three cases an implicit argument cannot reach. +A getter trait is worth declaring in a few cases an implicit argument cannot reach. - **The field lives on another type.** An implicit argument reads only from `self`, so a value held by a request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type, @@ -226,12 +226,12 @@ Between the two getter macros the line is narrow and worth stating plainly. - **`#[cgp_auto_getter]` is the default getter.** One blanket impl, no wiring, field name fixed to the method name. -- **[`#[cgp_getter]`](./cgp_getter.md) is the advanced one**, and not a general upgrade. Reach for it only +- **[`#[cgp_getter]`](./cgp_getter.md) is the advanced one**, and not a general upgrade. Use it only when a context needs to choose *which field* the getter reads, as a different name per context, or an implementation selected by wiring. That control costs a line of wiring per context, and most getters do not want it. -So the ordering is: implicit argument by default, `#[cgp_auto_getter]` for the three cases above, and +So the ordering is: implicit argument by default, `#[cgp_auto_getter]` for the cases above, and `#[cgp_getter]` only for per-context field choice. ## Under the hood @@ -258,7 +258,7 @@ where } ``` -Three things to recognize. The context parameter is literally `__Context__`, a reserved name chosen so it +A few things to recognize. The context parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours. [`Symbol!("name")`](./symbol.md) is a type-level string standing for the field name. The compiler prints its expanded `Symbol<4, Chars<'n', …>>` form in errors, and `cargo cgp expand` resugars it back to this. And because the return type is `&str`, the bound asks for a diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 69e843a3..7129d237 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -49,9 +49,9 @@ turns the call into a direct, statically-dispatched call, exactly as if you had implementation yourself. The macro's last piece is the **component** itself, a marker type such as `AreaCalculatorComponent` -that names the capability and is the key `delegate_components!` wires against. You will meet it in +that names the capability and is the key `delegate_components!` wires against. You see it in every wiring entry and in most compiler errors that involve this capability, so you should be able to -recognize it immediately, even though you never write its definition yourself. +recognize it at once, even though you never write its definition yourself. ## Usage @@ -134,7 +134,7 @@ associated type the trait declares *itself* is not imported and stays written as [`delegate_components!`](./delegate_components.md) and is mostly something you read in existing code rather than write. -Three attributes that look like they belong here do not, and the error is confusing enough to be worth +A few attributes that look like they belong here do not, and the error is confusing enough to be worth naming: `#[uses(...)]`, `#[extend_where(...)]`, and `#[use_provider(...)]` are read by [`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_fn]`](./cgp_fn.md) but not by `#[cgp_component]`. None of them is an attribute in its own right, so writing one here leaves a name nothing can resolve; see @@ -184,7 +184,7 @@ does, and nothing else in the program changes. ## When to use it -Reach for `#[cgp_component]` when a capability needs **more than one implementation, and the +Use `#[cgp_component]` when a capability needs **more than one implementation, and the choice belongs to the type using it.** That is the case it exists for, and its machinery is not free: a component is a trait, a second trait, a marker type, and a line of wiring per type. @@ -194,7 +194,7 @@ Prefer something simpler when you can. straight from a function, needs no wiring at all, and keeps working unchanged if a second implementation ever arrives, which makes it the right starting point rather than a lesser one. - **One implementation per type, chosen globally.** A plain Rust trait already does this well. - Reach for a component when two *different* applications must make different choices for the same + Use a component when two *different* applications must make different choices for the same type, or when the implementations must overlap in a way the compiler rejects. - **A closed set of variants with fixed operations.** An `enum` and a `match` are clearer than any machinery. @@ -202,7 +202,7 @@ Prefer something simpler when you can. There is also a finer line worth knowing: a capability may need several implementations while each individual implementation serves exactly one type. In that case you can implement the consumer trait directly on each concrete type, as you would any Rust trait, and skip providers -entirely. Named providers earn their place once a second type wants the *same* implementation, or once +entirely. Named providers become worth their cost once a second type wants the *same* implementation, or once an implementation should compose with a wrapper. ### How many items should a component have? @@ -212,12 +212,12 @@ consts as any other, and every one of them is reproduced on the provider trait. [`CanCompute`](../components/handler/computer.md) declares an associated `Output` beside its method, and there is no cap. -What to group is a judgement rather than a rule, and the useful question is: **everything in one +How much to group is a judgement rather than a rule, and the useful question is: **everything in one component is answered by one provider choice.** Items a single choice settles belong together: a method and the associated type it returns, or several field reads one getter provider answers by name. Items that separate choices settle are better apart, because grouping them costs reuse: every provider then carries the union of the dependencies of all the methods, a wrapper must forward the methods it -has no opinion about, and a type that needs only part of the surface must still supply the rest. +does not touch, and a type that needs only part of the surface must still supply the rest. The usual sign of a component that has grown past one decision is a consumer trait named after a noun rather than a verb, such as `Shape` carrying `area`, `perimeter`, `scale`, and `rotate`. It compiles, @@ -336,8 +336,8 @@ Those five are emitted in the order consumer trait, consumer impl, provider trai marker. The listings above instead pair each trait with the impl that routes to it, which reads better than the order they actually appear in. -Beyond the five, the macro emits the provider impls that let the component participate in CGP's usual -patterns. Two are always emitted, and two are one per attribute: +Beyond the five, the macro emits the provider impls that let the component take part in CGP's usual +patterns. The first two below are always emitted; the last two are generated one per attribute: - A [`UseContext`](../providers/use_context.md) impl, so the provider trait can be satisfied by routing back through the context's own implementation. Its only bound is @@ -355,7 +355,7 @@ impl does not look the incoming path up directly: it appends the parameters to i that arrives at `AreaCalculatorComponent` carrying no path ends up looking for `Rectangle`. Only *type* parameters take part; a lifetime or a const parameter cannot key a path and is left out. -Two details of the real output differ from the listings above, and both trip people up when reading an +Some details of the real output differ from the listings above, and each is easy to misread when reading an error. The generated parameters carry **reserved names**: the context is literally `__Context__` unless you override it, and the provider parameter is `__Provider__`. The readable `Context` and `Provider` here are for legibility only. And a component with parameters of its own appends them diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 38a1e402..2ac6bd2e 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -13,7 +13,7 @@ CGP models computation as a family of components varying along three axes: synch or not, taking an input or not. A provider in that family is a struct with one or more impls threading a **context** (the type the capability runs against, which supplies the values it needs as its fields), a phantom `Code` tag, and an `Input`. Written by hand for a computation as small as "add two numbers", that is -disproportionate ceremony. +far more code than the task needs. `#[cgp_computer]` lets you write just the computation: @@ -80,7 +80,7 @@ promotion bundle: | `async fn f(..) -> T` | `AsyncComputer` | `PromoteAsyncComputer` | | `async fn f(..) -> Result` | `AsyncComputer` | `PromoteHandler` | -The `Result` row is worth reading twice. The base trait stays `Computer`, and its `Output` is simply the +The `Result` row is worth a careful read. The base trait stays `Computer`, and its `Output` is simply the `Result` type as written. Only the *bundle* changes, and it makes `try_compute` and `handle` surface the `Ok`/`Err` outcome as success or failure rather than handing back a `Result` as a plain value. @@ -138,8 +138,8 @@ pub fn add_generic>(a: T, b: T) -> T { ## When to use it -**Reach for `#[cgp_computer]` when a step in a pipeline is naturally a function.** That is the case it -exists for, and it is the shortest route into the handler family. +**Use `#[cgp_computer]` when a step in a pipeline is naturally a function.** That is the case it +exists for, and it is the simplest way into the handler family. - **Use [`#[cgp_producer]`](./cgp_producer.md) when the computation takes no input.** A constant, or a value drawn from the context alone. It is the input-free sibling and produces a `Producer`. @@ -149,15 +149,15 @@ exists for, and it is the shortest route into the handler family. capability, it wants a provider impl of `Computer` or `Handler` written with `#[cgp_impl]`, where `self` is the context and [`#[implicit]`](../attributes/implicit.md) and [`#[uses]`](../attributes/uses.md) work normally. -- **Use [`#[cgp_fn]`](./cgp_fn.md) when what you want is a capability on the context, not a pipeline step.** +- **Use [`#[cgp_fn]`](./cgp_fn.md) when you want a capability on the context, not a pipeline step.** The two look similar and differ in what they produce: `#[cgp_fn]` gives a trait a context implements, called as `self.thing()`; `#[cgp_computer]` gives a *provider* that gets wired into a handler component and - composed with combinators. If you are not building a pipeline, reach for `#[cgp_fn]` instead. + composed with combinators. If you are not building a pipeline, use `#[cgp_fn]` instead. - **Wire the [handler combinators](../providers/handler/index.md) directly for composition.** The macro produces one step; `PipeHandlers` and friends chain them. -One thing not to do is reach for the handler family because a capability happens to transform a value. The -family earns its keep when computations are *composed*: piped, dispatched on a `Code` tag, promoted between +One thing not to do is use the handler family just because a capability happens to transform a value. The +family is worth using when computations are *composed*: piped, dispatched on a `Code` tag, promoted between variants. A single transform with one caller is a method. ## Under the hood @@ -219,7 +219,7 @@ rather than to the value itself, so `Add` inherits whatever `PromoteComputer>` form in errors, and @@ -286,7 +286,7 @@ parameters, so a lifetime or a const parameter is accepted there too); and fully qualified form. The macro appends the implicit-argument bounds last, after whatever the attributes contributed. -Two smaller placements are worth knowing because neither is visible in the source you wrote. **The +A couple of smaller placements are worth knowing because neither is visible in the source you wrote. **The function's visibility becomes the trait's**, and the impl's method keeps inherited visibility. So `pub fn rectangle_area` yields `pub trait RectangleArea`, and a private `fn` yields a private trait usable only in its own module. And **the macro copies an attribute it does not recognize onto both diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index cdbcbf43..e72bef7b 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -10,8 +10,8 @@ Define a getter as a full component, so the field it reads is chosen by wiring r ## Overview [`#[cgp_auto_getter]`](./cgp_auto_getter.md) ties a getter to a field of the same name: declare -`fn name(&self) -> &str` and every context with a `name` field satisfies it. That is the right trade almost -always, and it has one hard edge: a context that stores the value under a different name cannot use the +`fn name(&self) -> &str` and every context with a `name` field satisfies it. That is the right tradeoff almost +always, and it has one hard limitation: a context that stores the value under a different name cannot use the getter at all. `#[cgp_getter]` removes that coupling by making the getter a real component. The **context** is the @@ -30,10 +30,10 @@ delegate_components! { has moved into the wiring, where a context can change it without touching the trait or any code that calls it. -**This is an advanced tool, not the next step up from `#[cgp_auto_getter]`.** What you pay for the -decoupling is a line of wiring per context, and what you get is only useful when a context needs +**This is an advanced tool, not the next step up from `#[cgp_auto_getter]`.** The decoupling costs a +line of wiring per context, and it helps only when a context needs to control which field is read, or to supply the value some way other than reading a field. Most getters -want neither. The [When to use it](#when-to-use-it) section draws the line. +need neither. The [When to use it](#when-to-use-it) section draws the line. ## Usage @@ -72,7 +72,7 @@ Here the provider trait is `GetName` and the component `GetNameComponent`. The k ### What a context can wire it to -Three providers come out of the macro, and which you name decides where the value comes from. +The macro produces these providers, and which you name decides where the value comes from: | Wire it to | The getter reads | |---|---| @@ -80,8 +80,8 @@ Three providers come out of the macro, and which you name decides where the valu | `UseFields` | the field named after each method, the `#[cgp_auto_getter]` behaviour as a provider | | [`WithProvider

, …)]`** — a comma-separated list of trait bounds, accumulating across repeats. Adds each as a `Self:` impl-side bound. The simple `Trait` form reads like an import and is idiomatic, but any `where`-clause bound is accepted, including associated-type equality (`HasErrorType`); prefer `#[use_type]`'s equality form to pin an abstract type. Host: `#[cgp_fn]`, `#[cgp_impl]`. -- **`#[extend(Trait, Trait

, …)]`** — same simple-path list. Adds each as a *supertrait* of the generated trait (and, in `#[cgp_fn]`, also as an impl bound). Host: `#[cgp_fn]`, `#[cgp_component]`. Not `#[cgp_impl]` (a provider impl has no trait to attach supertraits to). -- **`#[extend_where(Pred, …)]`** — a list of full `where`-clause predicates, including associated-type equality, added verbatim to the generated trait's `where` clause. Host: `#[cgp_fn]` only. -- **`#[impl_generics(Param: Bound, …)]`** — bounded generic parameters added to the generated impl **only**, never the trait. Host: `#[cgp_fn]` only. -- **`#[use_provider(Provider: Trait<…> + …)]`** — completes an inner provider bound by inserting the context as the trait's leading argument (you write `: AreaCalculator`, it means `AreaCalculator`) and moving it into the `where` clause. Several trait bounds on **one** provider are joined with `+`; several **providers** take one stacked attribute each, because a comma-separated list of provider-and-trait pairs does *not* parse — after the first trait the parser is continuing that provider's bounds, so a comma reports `expected +`. This makes the attribute the exception to the one-attribute-comma-separated convention `#[uses]` and `#[use_type]` follow. It only *completes the bound* — it never rewrites the body, which must still call `Provider::method(self)` explicitly. Host: `#[cgp_impl]`, `#[cgp_fn]`. -- **`#[derive_delegate(Wrapper)]`** — generates a `UseDelegate`-style dispatcher impl keyed on `Param`; repeat for several dispatchers; the key may be a tuple `Wrapper<(A, B)>`. **Legacy** — prefer the `open` statement; see [wiring](wiring.md). Host: `#[cgp_component]`. -- **`#[prefix(@Path in Namespace)]`** — registers the component into `Namespace` under `@Path`, emitting one `RedirectLookup` impl; repeat for several namespaces. Host: `#[cgp_component]`. -- **`#[default_impl(T in DefaultImpls1)]`** — registers a `#[cgp_impl]` provider as a namespace's per-type default for `T`. Host: `#[cgp_impl]`. - -The check macros carry their own modifiers, covered with them below: `#[check_trait(Name)]` and `#[check_providers(…)]` on a table, `#[check_params(…)]` and `#[skip_check]` on an entry. - -### `#[use_type]` - -This attribute has enough structure to warrant a grammar of its own: - -```ebnf -UseTypeArgs -> UseTypeSpec ( `,` UseTypeSpec )* `,`? - -UseTypeSpec -> TraitPath `.` TypeItems ( `in` ContextPath )? - -ContextPath -> TypePath -TraitPath -> TypePath - -TypeItems -> UseTypeIdent - | `{` UseTypeIdent ( `,` UseTypeIdent )* `,`? `}` - -UseTypeIdent -> IDENTIFIER ( `as` IDENTIFIER )? ( `=` Type )? -``` - -The `.` (not `::`) after the trait path starts the associated-type list — a trait path keeps its own `::` segments and may carry generics. Omitting the `in ContextPath` suffix defaults the rewrite target to `Self`; an `in Types` suffix rewrites against a named generic parameter and adds `Types: Trait` as a `where` bound rather than a supertrait (`in` is a reserved keyword, so it can never be mistaken for part of a type, and reads like the `in` in `#[prefix(@Path in Namespace)]`). In each `UseTypeIdent`, `as` gives a local alias to write in signatures, and `= Type` pins the type with an equality bound (accepted on `#[cgp_fn]`/`#[cgp_impl]`, **rejected on `#[cgp_component]`**, whose trait definition cannot carry the impl-side equality). The macro rewrites every bare mention of the imported identifier (or alias) to the fully-qualified `::Type`. Host: `#[cgp_fn]`, `#[cgp_impl]`, `#[cgp_component]`. See [abstract-types](abstract-types.md). - ---- - -## Wiring and checking macros - -### `delegate_components!` - -The body is an optional generic list and `new` keyword, a target type, and a brace-delimited table: - -```ebnf -DelegateComponents -> Generics? `new`? TargetType `{` TableBody `}` - -TargetType -> Type - -TableBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? - -Statement -> OpenStmt | NamespaceStmt | ForStmt - -OpenStmt -> `open` ( `{` Type ( `,` Type )* `,`? `}` | Type ) `;` - -Mapping -> Key `:` ProviderValue - | Key `->` ProviderValue - | Key `=>` PathValue - -Key -> SingleKey | MultiKey | PathKey -SingleKey -> Generics? Type -MultiKey -> `[` SingleKey ( `,` SingleKey )* `,`? `]` -PathKey -> Generics? `@` PathHead - -PathHead -> PathSegment ( `.` PathHead )? - | `[` PathSegment ( `,` PathSegment )* `,`? `]` ( `.` PathHead )? - | `{` PathHead ( `,` PathHead )* `,`? `}` - -PathSegment -> Generics? Type - -PathValue -> `@` PathSegment ( `.` PathSegment )* - -ProviderValue -> Type - | IDENTIFIER `<` `new` InnerTable `>` - -InnerTable -> IDENTIFIER GenericArgs? `{` TableBody `}` -``` - -Every **statement must lead the block, before any mapping** — the parser reads statements first, so an `open`, `namespace`, or `for` written after a `Key: Value` line fails to parse (see error decoding below). A leading `Generics` list makes the whole table generic over the target; `new` also emits the target struct. Of the three mapping operators, `` `:` `` (map to a provider) is the common one. `` `->` `` forwards the key to *another table's* entry for that same key, adding a `Value: DelegateComponent` bound — a plain-wiring form with no namespace involved. `` `=>` `` redirects the lookup along an `@`-path and is the namespace mechanism, of which `open` is the sugared special case. The parser accepts any operator against any key form, but far fewer combinations are useful than the grammar allows. - -A `Key` may be one type, a bracketed list expanding to one entry each, or an `@`-path. **The two grouping forms inside a path key are different and are easy to confuse**: a bracketed group holds alternative segments for *one position* and may be followed by `` `.` `` and more path (`@app.[FooComponent, BarComponent].[u64, String]`), while a braced group holds alternative *whole tails* and ends the path, so only it can nest and its alternatives may differ in length (`@app.{ErrorRaiserComponent.{&'static str, String}, ErrorWrapperComponent}`). Both fan out to the cartesian product with the rest of the path. A `PathValue` — the right side of a `` `=>` `` — takes no groups. The nested-table `ProviderValue` form (`UseDelegate`) defines an inner table in place — the legacy dispatch form, whose inner name may itself carry generics (`UseDelegate { … }>`) and whose wrapper need not be `UseDelegate`. An `OpenStmt` opens one component (braces optional) or several (braces required) for per-value `@Component.Key: Provider` wiring folded into the context's own table. **No attributes are accepted** on the table or any entry; an unknown attribute is a spanned error, not silently dropped. See [wiring](wiring.md). - -**Expansion invariant.** Each plain `Key: Provider` entry emits a `DelegateComponent` impl with `Delegate = Provider` plus a forwarding `IsProviderFor` impl that threads the provider's dependencies back through the target. An `open Component;` header emits `DelegateComponent` = `RedirectLookup>`, and each `@Component.Value: Provider` entry stores that provider under the path key `PathCons>` on the target — **the tail is a generic `__Wildcard__` parameter, not `Nil`**, so one entry answers a redirect of any length; the `RedirectLookup` impl appends the dispatch parameter onto the path at resolution time. An `open C;` header and a `C => @C,` mapping produce the identical impl. - -### `delegate_and_check_components!` - -The same table shape, with a table-level check-trait attribute and per-entry check attributes: - -```ebnf -DelegateAndCheck -> TableAttr* Generics? `new`? TargetType `{` TableBody `}` - -TableAttr -> `#` `[` `check_trait` `(` IDENTIFIER `)` `]` - -TableBody -> Statement* ( CheckedMapping ( `,` CheckedMapping )* `,`? )? - -CheckedMapping -> EntryAttr? Mapping - -EntryAttr -> `#` `[` `check_params` `(` Type ( `,` Type )* `,`? `)` `]` - | `#` `[` `skip_check` `]` -``` - -`Mapping`, `Key`, `ProviderValue`, and `Statement` are exactly `delegate_components!`'s, so the **wiring** half accepts everything that macro does. The **check** half does not: a check entry is derived only from a mapping keyed on a component *name* (a `SingleKey` or `MultiKey`, under either `` `:` `` or `` `->` ``), so an `@`-path key, a `` `=>` `` redirect, and every `open`/`namespace`/`for` statement is wired and left **silently unchecked** — no warning marks the gap, which is the practical reason larger codebases keep the two macros apart. Its check trait defaults to `__CanUse{Context}` (distinct from `check_components!`'s `__Check{Context}`, so both fit one module). Each mapping carries at most one `EntryAttr`; `#[check_params(…)]` supplies the concrete generic parameters a parameterized component's check needs, and `#[skip_check]` wires without checking — the two are mutually exclusive. See [checking](checking.md). - -### `check_components!` - -One or more check tables, each with optional attributes, generics, a context, an optional `where` clause, and a brace list of entries: - -```ebnf -CheckComponents -> CheckTable+ - -CheckTable -> TableAttr* Generics? ContextType WhereClause? `{` CheckEntries `}` - -TableAttr -> `#` `[` `check_trait` `(` IDENTIFIER `)` `]` - | `#` `[` `check_providers` `(` Type ( `,` Type )* `,`? `)` `]` - -ContextType -> Type - -CheckEntries -> ( CheckEntry ( `,` CheckEntry )* `,`? )? - -CheckEntry -> CheckKey ( `:` CheckValue )? - -CheckKey -> Type - | `[` Type ( `,` Type )* `,`? `]` - -CheckValue -> CheckParam - | `[` CheckParam ( `,` CheckParam )* `,`? `]` - -CheckParam -> Generics? Type -``` - -A `CheckEntry`'s value is omitted for a parameterless component and required otherwise; a bracketed key or value expands to the cartesian product, so a set of components is checked against a set of parameters. `#[check_trait(Name)]` overrides the derived `__Check{Context}` name. `#[check_providers(…)]` changes the check: instead of asserting `CanUseComponent` on the context, it asserts `IsProviderFor` on each listed provider, so each layer of a higher-order stack is verified on its own line. See [checking](checking.md). - -**Expansion invariant.** A check table emits one marker trait aliasing the asserted bound plus one empty impl per entry — the impl compiles only if the bound holds. The default form aliases `CanUseComponent` and implements it for the context; `#[check_providers(…)]` aliases `IsProviderFor` and implements it for each provider. A successful build *is* the passing assertion; the checks have no runtime existence. - -### `cgp_namespace!` - -The body is an optional generic list and `new`, a namespace name, an optional parent, and a table: - -```ebnf -CgpNamespace -> Generics? `new`? NamespaceName ( `:` ParentNamespace )? `{` NamespaceBody `}` - -NamespaceName -> IDENTIFIER GenericArgs? -ParentNamespace -> TypePath GenericArgs? - -NamespaceBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? -``` - -The mappings are `delegate_components!`'s `Mapping` — most often a `` `=>` `` redirect to an `@`-path or a `` `:` `` direct provider. The colon between `NamespaceName` and `ParentNamespace` is the *inheritance* colon, distinct from a mapping's `:`; naming a parent makes the namespace resolve everything the parent does plus its own entries. This macro also owns the two statement forms a context's `delegate_components!` table uses to consume a namespace: - -```ebnf -Statement -> NamespaceStmt | ForStmt - -NamespaceStmt -> `namespace` IDENTIFIER `;` - -ForStmt -> `for` `<` IDENTIFIER `,` IDENTIFIER `>` `in` TypePath WhereClause? - `{` ( NormalMapping ( `,` NormalMapping )* `,`? )? `}` - -NormalMapping -> Key `:` ProviderValue -``` - -A `NamespaceStmt` forwards every unresolved lookup through the named namespace. A `ForStmt` binds a key variable and a provider variable, reads each entry of the table named after `in`, and emits one `:` mapping per entry; its optional `where` clause is merged into every impl it generates. Like `delegate_components!`, the body accepts no attributes on any entry. See [namespaces](namespaces.md). - ---- - -## Type-level construction macros - -The four type-level macros build the vocabulary the rest of CGP keys on, and their grammars are minimal: - -```ebnf -SymbolInput -> STRING_LITERAL - -ProductInput -> ( Type ( `,` Type )* `,`? )? // Product! (type position) -ProductExpr -> ( Expression ( `,` Expression )* `,`? )? // product! (value position) - -SumInput -> ( Type ( `,` Type )* `,`? )? - -PathInput -> `@` PathSegment ( `.` PathSegment )* -PathSegment -> Type -``` - -Each expands to a fixed spine, and knowing the spine is what lets you read a printed type. `Symbol!("abc")` becomes `Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>>` — the leading const is the *byte* length (so `Symbol!("世界")` records `6`), present only because stable Rust cannot compute a `Chars` length in const position. `Product![A, B]` becomes `Cons>` and `product![…]` builds the matching value; the empty forms are `Product![]`/`product![]` over `Nil`. `Sum![A, B]` becomes `Either>`, terminating in the uninhabited `Void` rather than `Nil`. `Path!(@app.error.FooComponent)` becomes a `PathCons` chain in which a lowercase, non-primitive segment is a `Symbol!` and a capitalized or primitive segment stays the named type. See [type-level-primitives](type-level-primitives.md). - ---- - -## Derives - -The data derives (`#[derive(HasField)]`, `HasFields`, `CgpData`, `CgpRecord`, `CgpVariant`, `BuildField`, `ExtractField`, `FromVariant`) take no custom arguments — they are ordinary derives whose behavior is fixed by the item they annotate. Their one grammar-shaped constraint is on **variant shape**: the enum derives (`CgpVariant`, `CgpData` on an enum, `ExtractField`, `FromVariant`) require every variant to be a single unnamed-field tuple variant (`Circle(Circle)`), because each variant's payload must be one nameable type. A fieldless (`Empty`), multi-field (`Pair(A, B)`), or struct-style (`Named { x: A }`) variant fails with **"Expected variant to contain exactly one unnamed field"** — wrap a richer payload in a dedicated struct. A named struct field is keyed by `Symbol!`, a tuple-struct field by `Index`. See [extensible-data](extensible-data.md). - ---- - -## Reading error messages - -CGP errors come from two layers — the macro's own parser, and the compiler resolving the expanded code — and each has a recognizable vocabulary. The parser errors are usually clear because most macros validate with spanned messages; the type errors are the ones that need decoding, because they name generated traits rather than the mistake you made. - -### Wiring and dependency errors - -**`the trait bound X: IsProviderFor is not satisfied`** is the most common, and it never means "write an `IsProviderFor` impl." Read it as *the provider `X` is not a valid provider for this component on `Ctx`, because one of its impl-side dependencies is unmet*. The truly missing bound is named nearby (a `HasField`, an abstract type, another capability); that is the thing to supply. `IsProviderFor` exists precisely to surface that named bound instead of a bare "trait not implemented" — see [components](components.md). - -**`the trait bound Ctx: DelegateComponent is not satisfied`** means the component was never wired on `Ctx` at all — add the `delegate_components!` entry. Contrast this with the `IsProviderFor` failure above, which means the component *was* wired but to a provider whose dependencies fail. A [check](checking.md) distinguishes the two for you: a failed `DelegateComponent` bound is "not wired," a failed `IsProviderFor` bound is "wired but unsatisfied." - -**A `CanUseComponent` error** comes from a `check_components!` or `delegate_and_check_components!` assertion firing at the wiring site — which is the point of checking. The named unmet bound is the first impl-side dependency the compiler could not satisfy; trace it through the provider chain to its root. Not every unmet bound is a CGP component: a plain trait or blanket-impl bound a provider also needs has no `…Component` marker and cannot be surfaced through wiring, so it must be satisfied by ordinary Rust means. - -**`overflow evaluating the requirement …`** on a component usually means a `UseContext` cycle — a component wired directly to `UseContext` whose only impl of that component *is* that delegation, so the context implements the consumer trait by calling a provider that implements the provider trait by calling the consumer trait. `UseContext` belongs as another provider's inner provider, not as a context's own delegate for the same component; see [wiring](wiring.md). - -### Decoding printed type-level values - -A long `Symbol>>` in an error is just a **field-name string** — read the `Chars` characters in order (here `name`) and ignore the leading length. A `Cons<…, Cons<…, Nil>>` is a record field list, an `Either<…, Either<…, Void>>` an enum variant list, and a `PathCons<…, …>` a namespace/redirect route. The [type-level-primitives](type-level-primitives.md) sub-skill is the full decoder ring; the shortcut is that any nested type ending in `Nil` is a product list and any ending in `Void` is a sum. - -### Errors that underline the whole macro block - -A coherence conflict (**`E0119`, conflicting implementations**) or an unconstrained-parameter error (**`E0207`**) whose caret covers an *entire* macro invocation rather than one entry is a span artifact, not a sign the whole block is wrong. The macros stamp generated items with a re-span onto the originating token, but a synthesized token that has lost its span falls back to the invocation site. When you see `E0119` between two generated impls, look for a **duplicated wiring entry** or two `open`/dispatch keys that overlap on the same type; when you see `E0207`, look for a generic parameter that appears in a provider or `#[cgp_fn]` header but is not bound by any argument or `where` clause. - -### Macro-parser errors - -These fire before expansion and are worth recognizing by shape. An **`expected :` parse error near an `open`/`namespace`/`for`** almost always means a statement was written *after* a mapping — statements must lead the block. An **"unsupported attribute"** (or a spanned rejection) on a `delegate_components!` / `cgp_namespace!` entry means those macros accept no attributes there at all. A **const generic** on a `#[cgp_component]` trait or in a provider trait's argument list is rejected, because CGP dispatches on types, not values (an associated `const` item on the trait is fine). **"Expected variant to contain exactly one unnamed field"** is the variant-derive shape rule above. A **default-bodied `async fn`** inside `#[async_trait]` is unsupported (the body is not wrapped in `async {}`), and a **generic method on a `#[cgp_auto_dispatch]` trait** is rejected because Rust lacks the quantified bound the blanket impl would need. - ---- - -## Further reference - -This file is a companion to the per-topic sub-skills, which show the same expansions in worked -context: [components](components.md), [wiring](wiring.md), [checking](checking.md), -[functions-and-getters](functions-and-getters.md), [abstract-types](abstract-types.md), -[higher-order-providers](higher-order-providers.md), [namespaces](namespaces.md), -[handlers](handlers.md), [extensible-data](extensible-data.md), and -[type-level-primitives](type-level-primitives.md). For the authoritative, exhaustive grammar and -expansion of any single construct — every accepted form, every corner case, and the implementing -source — fetch the online knowledge base at -`https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp`, whose `reference/macros/` -documents carry the formal Syntax Grammar and Expansion sections these grammars are drawn from. diff --git a/docs/ai/skills/references/macro-grammar.md b/docs/ai/skills/references/macro-grammar.md new file mode 120000 index 00000000..a071a10f --- /dev/null +++ b/docs/ai/skills/references/macro-grammar.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/macro-grammar.md \ No newline at end of file diff --git a/docs/ai/skills/references/modern-idioms.md b/docs/ai/skills/references/modern-idioms.md deleted file mode 100644 index 60ef40cb..00000000 --- a/docs/ai/skills/references/modern-idioms.md +++ /dev/null @@ -1,284 +0,0 @@ -# Modern idioms: reading and modernizing CGP - -The map from each older, explicit CGP form to the modern idiom you should prefer — so you can recognize legacy syntax in existing code, understand what it desugars to, and rewrite it in the vanilla-looking form. - -CGP's explicit forms came first, and they are still exactly what the macros desugar to, so you will keep meeting them in generated code, in reference Expansion sections, and in any codebase written before the newer idioms landed. The modern idioms exist to lower the barrier to entry: they let a provider look like an ordinary trait `impl`, a dependency look like a `use` import, and an abstract type look like a plain generic. **Prefer the modern idiom in all new code, and reach for an explicit form only when a construct genuinely cannot express the case** (the closing section lists those exceptions). This file is the bidirectional reference: read it forward to write modern CGP, and backward to decode legacy CGP you are asked to read or update. Assume `use cgp::prelude::*;`; the CGP version is v0.8.0. - -Each shift below shows the legacy form, the modern equivalent, and the mechanical rule that connects them. All of them desugar to the same generated code, so a rewrite is a readability change, never a behavioral one. - -## Provider shape: `#[cgp_impl]` over the raw provider forms - -Write a provider with [`#[cgp_impl]`](components.md), which keeps `self`, `Self`, and the consumer method signatures, rather than the lower-level [`#[cgp_provider]`/`#[cgp_new_provider]`](components.md), which require the inside-out provider-trait shape (the context moved to a leading type parameter, the receiver written as `context: &Context`). The legacy form: - -```rust -#[cgp_new_provider] -impl AreaCalculator for RectangleArea -where - Context: HasField, - Context: HasField, -{ - fn area(context: &Context) -> f64 { - *context.get_field(PhantomData::) - * *context.get_field(PhantomData::) - } -} -``` - -becomes, with `#[cgp_impl]` and [`#[implicit]`](functions-and-getters.md) arguments: - -```rust -#[cgp_impl(new RectangleArea)] -impl AreaCalculator { - fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height - } -} -``` - -`#[cgp_impl]` desugars back to `#[cgp_provider]`/`#[cgp_new_provider]`, so the raw forms remain what you read in expansions. Write the raw form yourself only when you need the inside-out shape directly — for instance a provider whose `Self` is a concrete context, or a bound the sugar cannot spell. - -## Context parameter: omit `for Context` - -Inside a `#[cgp_impl]` block, prefer the unqualified `impl AreaCalculator` and let the macro insert the reserved context parameter, rather than naming it as `impl AreaCalculator for Context`. Omitting `for Context` is what makes the provider read like an ordinary trait `impl`. Name the context explicitly only when you must bound it with a lifetime or higher-ranked bound the sugar cannot carry, or refer to it by a readable name. So the legacy - -```rust -#[cgp_impl(new RectangleArea)] -impl AreaCalculator for Context -where - Context: HasDimensions, -{ - fn area(&self) -> f64 { self.width() * self.height() } -} -``` - -shortens to the bare header, with the bound moved to `#[uses]`: - -```rust -#[cgp_impl(new RectangleArea)] -#[uses(HasDimensions)] -impl AreaCalculator { - fn area(&self) -> f64 { self.width() * self.height() } -} -``` - -## Dependencies: `#[uses]` and `#[use_provider]` over hand-written `where` - -State a provider's [impl-side dependencies](components.md) with [`#[uses(...)]`](functions-and-getters.md) and [`#[use_provider(...)]`](higher-order-providers.md) rather than hand-written `where` clauses, so a dependency reads like a `use` import. `#[uses(CanCalculateArea)]` adds `Self: CanCalculateArea`; `#[use_provider(Inner: AreaCalculator)]` adds `Inner: AreaCalculator`, filling in the `` context argument a provider-trait bound needs. The legacy `where` forms: - -```rust -#[cgp_impl(new ScaledArea)] -impl AreaCalculator for Context -where - Self: HasField, - InnerCalculator: AreaCalculator, -{ - fn area(&self) -> f64 { /* ... */ } -} -``` - -become the attribute forms plus an implicit argument: - -```rust -#[cgp_impl(new ScaledArea)] -#[use_provider(InnerCalculator: AreaCalculator)] -impl AreaCalculator { - fn area(&self, #[implicit] scale_factor: f64) -> f64 { /* ... */ } -} -``` - -`#[uses]` accepts any bound a `where` clause allows, including one carrying associated-type equality, though the simple `Trait` form is idiomatic. Where that bound pins an **abstract type** — `Self: HasErrorType` — express it with the [`#[use_type]` equality form](#abstract-types-use_type-over-supertrait--selftype) below, rather than spelling the equality in `#[uses]` or writing a hand-written `where` clause; only equality on a trait you would never import from with `#[use_type]` (`Iterator`) stays an explicit `where` clause. When a provider imports several capabilities, combine them into one `#[uses]` attribute separated by commas — `#[uses(CanQueryUserBalance, CanRaiseHttpError)]` — rather than stacking the attribute repeatedly; one combined attribute reads as a single dependency list, and splitting across repeats behaves identically but is for when a real reason calls for it. **`#[use_provider]` is the exception and does not follow this convention:** a comma-separated list of provider-and-trait pairs does not parse, so several inner providers take one stacked attribute each, and `+` is what joins several trait bounds on a single provider. - -## Field reads: `#[implicit]` over a getter trait - -Read a value from a context field with an [`#[implicit]`](functions-and-getters.md) argument — in a `#[cgp_impl]` method exactly as in `#[cgp_fn]` — rather than declaring a getter trait and importing it. This is the default for *any* field a provider reads from its own context, since an implicit argument reads from `self` and takes a plain `&T` by reference without cloning — even a field several providers each read is written as the same implicit argument in each, not promoted to a getter. An implicit argument names both a local and the field it comes from, keeping the `HasField` machinery out of sight. The getter-trait version: - -```rust -#[cgp_auto_getter] -pub trait HasDimensions { - fn width(&self) -> &f64; - fn height(&self) -> &f64; -} - -#[cgp_impl(new RectangleArea)] -#[uses(HasDimensions)] -impl AreaCalculator { - fn area(&self) -> f64 { self.width() * self.height() } -} -``` - -collapses to reading the fields directly: - -```rust -#[cgp_impl(new RectangleArea)] -impl AreaCalculator { - fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height - } -} -``` - -Use `#[cgp_auto_getter]` sparingly — only where an implicit argument cannot reach. There are three such cases. The field lives on a type *other* than the provider's own context, so the getter is required as a `where` bound on that type (`Request: HasBasicAuthHeader`) and there is no `self` field for an implicit argument to read; the accessor must exist as a *named* capability other code depends on through `#[uses(HasName)]` or a supertrait; or the getter carries an *associated type inferred from the field* so the type stays abstract for callers. Everywhere else — including a same-context field read shared by several providers — prefer the implicit argument. Avoid `#[cgp_getter]` in ordinary code, since its full wireable component is for the advanced case of choosing the source field per context at wiring time. - -## Abstract types: `#[use_type]` over supertrait + `Self::Type` - -Bring an abstract type into a definition with [`#[use_type]`](abstract-types.md) and write it as a bare alias, rather than declaring the owning trait as a supertrait and qualifying every use as `Self::Type`. The attribute does both jobs: it adds the supertrait (on `#[cgp_component]`) or `where` bound (on `#[cgp_impl]`/`#[cgp_fn]`) *and* rewrites each bare `Error`/`Scalar` to its fully-qualified path. This is preferred even for the built-in error type — the legacy - -```rust -#[cgp_component(Loader)] -pub trait CanLoad: HasErrorType { - fn load(&self, path: &str) -> Result; -} -``` - -becomes - -```rust -#[cgp_component(Loader)] -#[use_type(HasErrorType.Error)] -pub trait CanLoad { - fn load(&self, path: &str) -> Result; -} -``` - -One rule bounds the rewrite: it fires only on the bare identifier of an *imported* type. A construct's own **local associated type stays qualified as `Self::Assoc`** — a handler that declares `type Output` writes `Self::Output`, never a bare `Output`. So a mixed signature like `Result` is exactly right: the local `Self::Output` stays qualified, the imported `Error` is bare. - -When a definition imports types from several traits, combine them into one `#[use_type]` attribute with the trait paths comma-separated — `#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasErrorType.Error)]` — rather than stacking one attribute per trait; the combined form reads as a single import list. Several types from one trait use the braced list (`#[use_type(HasFooType.{Foo, Bar})]`). Stacking repeated `#[use_type]` attributes behaves identically, but reach for it only when a real reason calls for it. - -Prefer `#[use_type]` even when the type lives on a **foreign** type rather than `Self` — a type named by a generic parameter — using the trailing `in Context` clause. It rewrites the bare alias to `::Assoc` *and* supplies `Context: Trait`, so the hand-written - -```rust -#[cgp_auto_getter] -pub trait HasLoggedInUser -where - App: HasUserIdType, -{ - fn logged_in_user(&self) -> &Option; -} -``` - -becomes - -```rust -#[cgp_auto_getter] -#[use_type(HasUserIdType.UserId in App)] -pub trait HasLoggedInUser { - fn logged_in_user(&self) -> &Option; -} -``` - -with `App: HasUserIdType` supplied for you, so the plain `` parameter and the bare `UserId` are enough. - -Import a type with `#[use_type]` even when it *already* arrives transitively — as the supertrait of a trait pulled in by `#[uses]`. When `CanCreateFoo` has `HasFooType` as a supertrait, prefer re-importing over leaning on the transitive `Self::Foo`: - -```rust -#[cgp_fn] -#[uses(CanCreateFoo)] -#[use_type(HasFooType.Foo)] // re-import: bare `Foo`, explicit `HasFooType` dep -fn bar(&self) -> Foo { self.create_foo(42) } -``` - -instead of - -```rust -#[cgp_fn] -#[uses(CanCreateFoo)] -fn bar(&self) -> Self::Foo { self.create_foo(42) } // relies on the reachable supertrait -``` - -The re-import re-adds a harmless (already-implied) `Self: HasFooType` and rewrites the bare `Foo`, so `#[uses]` states the *capability* dependency and `#[use_type]` states the *type* dependency, both visible rather than one riding in silently. - -`#[use_type]` also *pins* an abstract type with the equality form `{Assoc = Type}`, which is the modern replacement for a hand-written `where Self: HasXType` clause — reach for it whenever a provider constrains an abstract type to a concrete one, rather than leaving the equality as an explicit `where`. On a `#[cgp_impl]`, the legacy - -```rust -#[cgp_impl(new DisplayHttpError)] -impl HttpErrorRaiser -where - Self: HasErrorType, - Code: IsStatusCode, - Detail: Display, -{ - fn raise_http_error(_code: Code, detail: Detail) -> AppError { /* ... */ } -} -``` - -becomes, with the equality moved into the attribute: - -```rust -#[cgp_impl(new DisplayHttpError)] -#[use_type(HasErrorType.{Error = AppError})] -impl HttpErrorRaiser -where - Code: IsStatusCode, - Detail: Display, -{ - fn raise_http_error(_code: Code, detail: Detail) -> AppError { /* ... */ } -} -``` - -The attribute emits the same `Self: HasErrorType` bound (and would rewrite any bare `Error`, though here the body names the concrete `AppError` directly). The right-hand side is substituted too, so an imported alias is grounded wherever it appears in it. Naming *another* alias outright unifies two abstract types: `#[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})]` emits `Self: HasHashedPasswordType::Password>`. An alias *nested inside* the type is grounded in place: `#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits `Self: HasTransactionType::Db>>`, which is how a pin says "a transaction of *this* database" without naming a concrete engine. Because the equality form produces an impl-side bound, it belongs on `#[cgp_impl]` and `#[cgp_fn]` only — it is rejected on `#[cgp_component]`. The one equality bound that *stays* a hand-written `where` clause is one on a trait you would never `#[use_type]` from, such as `Iterator`. - -## Supertraits: `#[extend]` over native `:` syntax - -Add a non-type capability supertrait to a `#[cgp_component]` trait with [`#[extend(...)]`](functions-and-getters.md) rather than native `pub trait CanDoX: Supertrait` syntax. Both produce the same trait, but `#[extend]` reads as importing a capability the trait re-exports, which is what a CGP supertrait actually is — a declared dependency, not a base class. It pairs symmetrically with `#[uses]`: `#[uses]` imports a capability for private use, `#[extend]` re-exports one as part of the trait's contract. The native - -```rust -#[cgp_component(Greeter)] -pub trait CanGreet: HasName { - fn greet(&self) -> String; -} -``` - -becomes - -```rust -#[cgp_component(Greeter)] -#[extend(HasName)] -pub trait CanGreet { - fn greet(&self) -> String; -} -``` - -Use `#[extend]` for a supertrait that contributes only a *capability* (like `HasName`, read through the getter); use `#[use_type]` instead when the supertrait is an abstract-type component whose associated type the signature names, since `#[use_type]` also rewrites the type. In `#[cgp_fn]`, whose `where` clauses are impl-side dependencies, `#[extend]` is the only way to declare a supertrait at all. - -## Per-type dispatch: `open` and namespaces over `UseDelegate` - -Route a generic-parameter component to a different provider per type with the [`open` statement](wiring.md) or a [namespace](namespaces.md), rather than the legacy [`UseDelegate`](higher-order-providers.md) nested-table pattern. Both ride the `RedirectLookup` impl every `#[cgp_component]` already generates, so they store the per-type entries directly on the context with no wrapper type. The legacy nested table: - -```rust -delegate_components! { - MyApp { - AreaCalculatorComponent: - UseDelegate, - } -} -``` - -becomes the inline `open` form: - -```rust -delegate_components! { - MyApp { - open AreaCalculatorComponent; - - @AreaCalculatorComponent.Rectangle: RectangleArea, - @AreaCalculatorComponent.Circle: CircleArea, - } -} -``` - -Because `open` and namespaces ride `RedirectLookup`, a **new** component you dispatch this way needs no [`#[derive_delegate(UseDelegate)]`](macro-grammar.md) attribute — that attribute exists only to generate the `UseDelegate` provider the nested-table form relies on. You will still see `#[derive_delegate]` on some CGP-shipped components (the error and handler families) so their existing `UseDelegate` wiring keeps working, but code dispatching only through `open` or a namespace can omit it. Prefer `open` for a context wiring its own components, and a namespace when a reusable, inheritable dispatch table is worth sharing. - -## When the explicit forms are still right - -A handful of cases genuinely need an explicit form, and choosing one there is not a regression. Keep an explicit `where` clause for an associated-type-equality bound on a non-`#[use_type]` trait — `Iterator`, `From`, and the like — which reads more clearly as a `where` clause than in an import-shaped `#[uses]` (which does accept it); but note the exception's own exception: an equality bound on an **abstract-type** trait (`Self: HasErrorType`) is *not* one of these, because the [`#[use_type]` equality form](#abstract-types-use_type-over-supertrait--selftype) `#[use_type(HasErrorType.{Error = AppError})]` does express it and is preferred; leave only equality on a non-`#[use_type]` trait as a hand-written `where`. Name the context explicitly, `impl Trait for Context`, to attach a lifetime or higher-ranked bound the sugar cannot carry, or when `Self` must be a concrete context (the `#[cgp_impl(Self)]` passthrough is the direct-impl case). Reach for `#[cgp_getter]` when you specifically want to choose which field a getter reads per context at wiring time. Write a raw provider-trait `impl` when you need the inside-out shape directly. And keep a local associated type qualified as `Self::Output` always — it is never a `#[use_type]` import. - -## Reading pre-0.7 code: renamed and removed names - -Very old code and pre-0.7 write-ups can use names that no longer exist, as opposed to the still-valid legacy *forms* above. These do not compile against current CGP, so treat them as signals to translate, not to copy: the attribute `#[cgp_context]` was removed (a context is now assembled with `delegate_components!` and the derive/getter machinery rather than a dedicated context macro), and the abstract-type provider trait once called `ProvideType` is now `TypeProvider`. When you meet a name the current prelude does not export, assume it was renamed or removed rather than that you are misremembering, and fetch the online knowledge base's changelog and reference to find its modern spelling; do not reintroduce a removed name into new code. - -## Related sub-skills - -Every shift here is a shortcut over a construct documented in full elsewhere: provider forms in [components](components.md), field injection and `#[uses]`/`#[extend]` in [functions-and-getters](functions-and-getters.md), abstract types and `#[use_type]` in [abstract-types](abstract-types.md), the inner-provider pattern in [higher-order-providers](higher-order-providers.md), per-type dispatch in [wiring](wiring.md) and [namespaces](namespaces.md), and the grammar and expansion of every form in [macro-grammar](macro-grammar.md). For how much CGP a problem needs in the first place, see [modularity-hierarchy](modularity-hierarchy.md). diff --git a/docs/ai/skills/references/modern-idioms.md b/docs/ai/skills/references/modern-idioms.md new file mode 120000 index 00000000..a7f86144 --- /dev/null +++ b/docs/ai/skills/references/modern-idioms.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/modern-idioms.md \ No newline at end of file diff --git a/docs/ai/skills/references/modularity-hierarchy.md b/docs/ai/skills/references/modularity-hierarchy.md deleted file mode 100644 index 884a9447..00000000 --- a/docs/ai/skills/references/modularity-hierarchy.md +++ /dev/null @@ -1,204 +0,0 @@ -# Modularity hierarchy - -A spectrum of how decoupled an implementation can be from the type it serves, from plain generic functions up to per-provider wiring, so you can pick how much CGP machinery a problem actually needs. - -CGP is not all-or-nothing. The same capability — here, serializing a value with Serde — can be expressed at several levels of modularity, each more decoupled than the last and each carrying more machinery in exchange. This page walks the spectrum on one running example so a reader can stop at the first level that solves the problem rather than reaching for the heaviest tool by reflex. Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. - -## Two questions decide the level - -Before the levels, the two things that actually vary, because the level numbers name consequences while these name causes. - -**What is the `Self` type?** Either a **value context** — the data the capability operates on, like the `Vec` being serialized — or an **environmental context**, a type that exists to supply choices and capabilities rather than to be operated on, like an application. Both are contexts: both sit in `Self` and both carry a wiring table. An environmental context often has no fields at all, since its whole job is to be a name the table hangs off. - -**What does the capability target?** Either `Self` (**self-targeted**: `CanGreet`, `HasErrorType`, every getter) or a type parameter that `Self` only decides for (**parameter-targeted**: `CanSerializeValue`, `CanCalculateArea`). A parameter alone does not settle this — in `CanCompute` the target is `Input` while `Code` is a selector the wiring dispatches on. - -Three combinations occur: a **value context** targeting `Self` (Level 3's retrofit case), an **environmental context** targeting `Self` (also Level 3, and where most CGP code lives), and an **environmental context** targeting a parameter (Levels 4–5). - -**The escape from coherence happens when `Self` becomes a type you own, not when a parameter appears.** This is the part most easily misread. Wired on a foreign value type, a self-targeted component still gets one provider program-wide. Wired on an environmental context, the constraint "one wiring per type" stops binding, because you can define a second context: `App` and `TestApp` each choose their own `CanSendEmail` provider with no parameter anywhere. What Level 4's parameter adds is the ability to make that choice about types you do *not* own. - -Vanilla Rust idiomatically supports only the first combination — `impl Display for String` — which is why a Rust programmer arrives with no vocabulary for the others. The other two are legal but unrewarding: an environmental context works until you factor two implementations into blanket impls and they overlap, and a parameter-targeted trait on an application type compiles fine but needs a hand-written body for every context-and-type pair. CGP's contribution is making the implementations reusable, which is what turns each arrangement into a technique. - -## The coherence problem the hierarchy escapes - -What forces this hierarchy to exist is Rust's coherence rules, which guarantee that every trait -lookup resolves to one globally unique implementation. Two rules enforce that uniqueness. The -**overlap rule** forbids two implementations that could both apply to the same type — you cannot -blanket-implement `Serialize` for every `T: Display` *and* for every `T: AsRef<[u8]>`, because a -`String` satisfies both and the compiler has no principled way to choose. The **orphan rule** -forbids implementing a trait for a type unless your crate owns either the trait or the type — you -cannot implement someone else's `Serialize` for someone else's `Vec`. Each level below loosens -one more of these constraints. CGP's escape route is to move the type that coherence ranges over — -the `Self` of the implementation — into a position the implementing crate always owns, then restore -a single unambiguous answer locally, one [context](components.md) at a time, through -[wiring](wiring.md). See -[coherence](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/coherence.md) -for the full framing. - -## Level 1 — one implementation per interface - -The least machinery is a generic function or a blanket trait impl, which both define exactly one implementation behind an interface. A generic function captures the logic and its bounds in one place: - -```rust -pub fn serialize_bytes, S: Serializer>( - value: &Value, - serializer: S, -) -> Result { ... } -``` - -A blanket trait carries the same one-implementation limitation but reads more ergonomically at the call site, since the bound hides behind the trait impl and the caller writes a method: - -```rust -pub trait CanSerializeBytes { - fn serialize_bytes(&self, serializer: S) -> Result; -} - -impl> CanSerializeBytes for Value { - fn serialize_bytes(&self, serializer: S) -> Result { ... } -} -``` - -The gain is reuse with zero ceremony. The limitation is absolute: there can be exactly one blanket impl, so you cannot offer two ways to serialize bytes and let a caller pick between them. - -## Level 2 — one unique implementation per type per interface - -A vanilla Rust trait lifts the one-implementation limit slightly: many types may share the interface, but coherence still permits at most one implementation per type. Each type that wants the behavior writes its own impl: - -```rust -pub trait Serialize { - fn serialize(&self, serializer: S) -> Result; -} - -impl Serialize for Vec { - fn serialize(&self, serializer: S) -> Result { - self.serialize_bytes(serializer) - } -} - -impl<'a> Serialize for &'a [u8] { - fn serialize(&self, serializer: S) -> Result { - self.serialize_bytes(serializer) - } -} -``` - -The gain is that different types can be serialized differently. The cost is duplication: `Vec` and `&[u8]` each need an explicit impl even though the logic is identical. The body can still call out to a Level-1 building block such as `CanSerializeBytes` to share the actual work, so the duplication is confined to the boilerplate of forwarding. The remaining limitation is the one-impl-per-type ceiling — there is still no way to give `Vec` two serialization strategies and choose between them. - -## Level 3 — multiple implementations per type, globally unique wiring - -Applying basic CGP to a vanilla trait removes the duplication of Level 2 by turning the shared logic into a reusable [provider](components.md) and letting each type [wire](wiring.md) to it. The trait keeps its original shape, which makes the component **self-targeted** and each wired type a **value context**; `#[cgp_component]` generates the [consumer trait](components.md) and [provider trait](components.md) pair, `#[cgp_impl(new ...)]` defines a named provider once, and `delegate_components!` points each type at it. Note that Level 4 below defines a *different* component, `CanSerializeValue`, rather than revising this one: - -```rust -#[cgp_component(SelfSerializer)] -pub trait Serialize { - fn serialize(&self, serializer: S) -> Result; -} - -#[cgp_impl(new SerializeSelfAsBytes)] -#[uses(AsRef<[u8]>)] -impl SelfSerializer { - fn serialize(&self, serializer: S) -> Result { ... } -} - -delegate_components! { - Vec { - SelfSerializerComponent: SerializeSelfAsBytes, - } -} - -delegate_components! { - <'a> &'a [u8] { - SelfSerializerComponent: SerializeSelfAsBytes, - } -} -``` - -The gain is real reuse without modifying the interface: `Serialize` is unchanged, so a type can still implement it directly without opting into CGP at all, and existing users of the trait are unaffected. The `SelfSerializer` provider trait removes the need for ad-hoc interfaces like `CanSerializeBytes`, and `delegate_components!` removes the manual forwarding of Level 2. The limitation is that coherence still binds the wiring itself: each type carries one global wiring, so a `Vec` entry conflicts with any overlapping `Vec` entry, the choice cannot be overridden per context, and the orphan rule still means you can only wire `Vec` from a crate that owns either `Serialize` or `Vec`. - -**That limitation only bites because the wired type is a value context you do not own, and this level holds a second case where it does not bite at all.** Wire a self-targeted component on an *environmental* context and the same level gives per-application choice, because you control how many contexts exist: - -```rust -delegate_components! { App { EmailSenderComponent: SendViaSmtp } } -delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } -``` - -No parameter is involved and nothing has been worked around. That is where most CGP code lives — a capability about the application itself, wired per application — so reading Level 3 as only the retrofit case undersells it, and reading Level 4 as the first level with per-context choice is wrong. - -## Level 4 — unique wiring per type, per context - -Making the component **parameter-targeted** fully decouples the implementation from the type, so each context wires its own choices and the orphan rule lifts entirely. The trait changes shape: the original `Self` becomes an explicit `Value` parameter and `Self` is now always an **environmental context**, so the component dispatches on which concrete value type it serializes. What this adds over Level 3's environmental case is narrow and worth stating precisely — Level 3 already lets each context you define make its own choice, so what Level 4 buys is making that choice about types you do *not* own. Each context then folds its per-type choices straight into its own table with the `open` statement of `delegate_components!`: - -```rust -#[cgp_component(ValueSerializer)] -pub trait CanSerializeValue { - fn serialize(&self, value: &Value, serializer: S) -> Result - where - S: serde::Serializer; -} - -delegate_components! { - new MyAppA { - open ValueSerializerComponent; - - @ValueSerializerComponent.Vec: SerializeBytes, - @ValueSerializerComponent.Vec: SerializeIterator, - } -} - -delegate_components! { - new MyAppB { - open ValueSerializerComponent; - - @ValueSerializerComponent.Vec: SerializeHex, - @ValueSerializerComponent.Vec: SerializeIterator, - } -} -``` - -The `open ValueSerializerComponent;` header opens the component for per-value wiring, and each `@ValueSerializerComponent.Value: Provider` entry assigns a provider for one concrete value type. The gain is that `MyAppA` and `MyAppB` resolve `Vec` to different providers — bytes versus hex — with no conflict, because each choice is coherent only within its own context. The orphan rule no longer applies: a context can wire `Vec` even when its crate owns neither `CanSerializeValue` nor `Vec`, as long as it owns the context type, so you never commit to a global serialization for `Vec` up front. The costs are that the trait must be modified to add the context parameter, and that every value type a context touches must be wired explicitly, which grows tedious for a large type set. - -The `open` form rides the dispatch machinery that every `#[cgp_component]` already generates, so the trait needs no extra option. A legacy alternative writes the same dispatch with a `#[derive_delegate(UseDelegate)]` attribute on the trait and a `UseDelegate: SerializeBytes, ... }>` nested table in each context's wiring; it is retained for compatibility but `open` is preferred for new code, and the two forms appear side by side in [wiring](wiring.md). - -## Level 5 — explicit wiring per type, per provider - -The finest grain overrides wiring *inside* a provider rather than at the context, using a [higher-order provider](higher-order-providers.md) whose inner provider defaults to `UseContext`. The default routes nested lookups back through the context as usual, while an explicit inner provider overrides one branch locally without touching the context's table: - -```rust -pub struct SerializeIteratorWith(pub PhantomData); - -#[cgp_impl(SerializeIteratorWith)] -impl ValueSerializer -where - for<'a> &'a Value: IntoIterator, - Provider: for<'a> ValueSerializer::Item>, -{ - fn serialize(&self, value: &Value, serializer: S) -> Result - where - S: serde::Serializer, - { ... } -} - -delegate_components! { - new MyAppA { - open ValueSerializerComponent; - - @ValueSerializerComponent.Vec: SerializeBytes, - @ValueSerializerComponent.Vec>: SerializeIteratorWith, - @ValueSerializerComponent.Vec: SerializeIteratorWith, - @ValueSerializerComponent.[u8, u64]: UseSerde, - } -} -``` - -Here `Vec>` serializes its inner `Vec` as hex strings, while a bare `Vec` elsewhere in the same context still serializes as bytes — the inner provider is overridden for that one branch only. Where `SerializeIteratorWith` is left without an argument, as for `Vec`, the `UseContext` default takes over and the item lookup goes back through the context, so the `u64` items resolve to `UseSerde` from the table. The gain is per-provider control: a wiring decision can be pinned at the point of use instead of globally at the context level. The cost is the higher-order plumbing itself — the extra provider parameter, the explicit context argument in the inner bound, and the discipline of choosing when to override versus when to defer to the context. - -## Choosing a level - -Read the spectrum as a ladder and stop at the first rung that fits. Levels 1 and 2 are plain Rust and need no CGP at all — reach for them when one implementation, or one per type, is genuinely all you need. Level 3 buys reuse and swappable providers while leaving the trait and its existing users untouched: on a value context that is the right entry point for retrofitting CGP onto an established trait, and on an environmental context it is where most CGP code lives. Level 4 pays a modified interface for the ability to choose per context about types you do not own. Level 5 is a local refinement layered on top of Level 4, used only where a single nested branch must diverge from the context's global choice. Each step up trades ceremony for decoupling, so the discipline is to climb only as far as the problem demands. - -Two questions settle it faster than walking the levels. **Is the capability about the data, or about the application?** About the data means a value context and Level 3's retrofit case; about the application means an environmental context. **Does it concern a type you do not own, which different applications must treat differently?** If yes, the target moves into a parameter and you are at Level 4; if no, self-targeting is enough. Each arrangement answers a different question rather than representing a different amount of sophistication. - -Further reference: -[coherence](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/coherence.md) -for the rules this hierarchy escapes, and -[modular serialization](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/examples/modular-serialization.md) -for the full worked example. diff --git a/docs/ai/skills/references/modularity-hierarchy.md b/docs/ai/skills/references/modularity-hierarchy.md new file mode 120000 index 00000000..66935870 --- /dev/null +++ b/docs/ai/skills/references/modularity-hierarchy.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/modularity-hierarchy.md \ No newline at end of file diff --git a/docs/ai/skills/references/namespaces.md b/docs/ai/skills/references/namespaces.md deleted file mode 100644 index 0fc61e94..00000000 --- a/docs/ai/skills/references/namespaces.md +++ /dev/null @@ -1,173 +0,0 @@ -# Namespaces - -A namespace is a reusable, named lookup table of component wirings that a context inherits wholesale and then selectively overrides — CGP's preset mechanism, expressed entirely at the type level with no runtime cost. - -As the component count of an application grows, the [wiring](wiring.md) on each context grows with it: every context spells out its own `delegate_components!` table entry by entry, and two contexts that should share the same set of providers must repeat the whole block. A namespace lifts that block out of any single context, gives it a name, and lets other contexts say "use everything in this namespace" to pull in the entire group at once. This is exactly the preset pattern — a curated bundle of defaults you adopt and then customize — and CGP has no separate `cgp_preset!` construct because a preset *is* a namespace. This file covers `cgp_namespace!` (defining and inheriting a namespace), the `RedirectLookup` provider that makes the indirection work, the `Path!` macro that addresses entries, and the `DefaultNamespace` family of default-resolution traits. - -## What a namespace is - -A namespace is not a context — it is a trait, named after the namespace, that carries a single `Delegate` associated type and is implemented once per key. A context that joins a namespace forwards its lookups through that trait, so the namespace supplies defaults without ever being instantiated or holding any wiring at the context level. The defining behavior is inheritance with override: a context inherits the namespace's entries as defaults, and any entry it wires directly on itself wins, because a context's own [`DelegateComponent`](wiring.md) entry resolves before the namespace fallback is consulted. - -The forwarding is keyed by a *path* rather than a bare component name, and that is what makes inheritance and selective override possible. A path is a type-level list of symbols and component names; keying on it lets one namespace inherit from another, lets a parent's whole subtree be rerouted at once, and lets a child context shadow a single inherited entry without disturbing the rest. - -## Defining a namespace with `cgp_namespace!` - -`cgp_namespace!` defines a namespace from a body that resembles a `delegate_components!` table. The `new` keyword tells the macro to emit the namespace's marker struct and its lookup trait; the entries inside map keys to redirect paths or to providers: - -```rust -cgp_namespace! { - new DefaultShowComponents { - [String, u64]: ShowWithDisplay, - } -} -``` - -Two entry forms appear in the body and generate different table contents. A `:` entry maps a key straight to a provider, exactly as in `delegate_components!` — the `[String, u64]: ShowWithDisplay` line above resolves both keys to the `ShowWithDisplay` provider. A `=>` entry instead redirects a key along a path: `FooProviderComponent => @MyFooComponent` says "when this namespace is asked for `FooProviderComponent`, look up the path `@MyFooComponent` instead of naming a provider outright," leaving the actual provider to be decided wherever the path lands. - -Those two are the forms worth writing, but they are not the whole grammar: a namespace body is parsed by the same code as a `delegate_components!` table, so every operator, key form, statement, and value form that macro accepts parses here too — each lowering to an `impl Namespace<__Table__> for Key` rather than a `DelegateComponent` impl. Two consequences are worth holding. `open C;` in a namespace body is simply another spelling of `C => @C,`, while inheritance is written with the `: ParentNamespace` header rather than with a `namespace` statement. And the legacy nested-table value works, with the inner table lifted out into its own struct and impls just as in a delegation table — which is the one reason to write that form in a namespace rather than on a context, since every joining context then inherits the dispatch table. - -A namespace inherits from a parent by naming it after a colon in the header. The child then resolves everything the parent does, plus its own entries: - -```rust -cgp_namespace! { - new ExtendedNamespace: DefaultNamespace { - @cgp.core.error => - @app, - } -} -``` - -`ExtendedNamespace` inherits every entry `DefaultNamespace` resolves and additionally reroutes the entire `@cgp.core.error` subtree to `@app` — a single path-rewriting entry redirects a whole prefix of the parent namespace at once, not just one component. - -### What the macro generates - -With `new` present, the macro emits a backing struct (named with an `__…Components` wrapper) and the lookup trait carrying the table's `__Table__` generic parameter and a `Delegate` associated type: - -```rust -pub struct __MyNamespaceComponents; - -pub trait MyNamespace<__Table__> { - type Delegate; -} -``` - -Each `=>` entry becomes an `impl` of that trait for the entry's key, whose `Delegate` is a `RedirectLookup` pointing the table at the entry's path; each `:` entry becomes an `impl` whose `Delegate` is the named provider directly. For `FooProviderComponent => @MyFooComponent` the macro emits: - -```rust -impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { - type Delegate = RedirectLookup<__Table__, PathCons>; -} -``` - -When a parent is named, the macro prepends a blanket impl that forwards every key the parent resolves down to the child, so the child inherits the parent's full table; the child's own entries are emitted after it and take precedence where their keys are more specific. - -## Attaching components and joining namespaces - -A namespace is consumed from two sides: components register into it, and contexts join it. A [component](components.md) attaches to a namespace through the `#[prefix(@path in Namespace)]` attribute on its [`#[cgp_component]`](components.md) trait, which emits one extra impl registering the component into the named namespace under a path prefix. CGP's own [`HasErrorType`](components.md), for example, carries `#[prefix(@cgp.core.error in DefaultNamespace)]`, placing the standard error wiring into the built-in `DefaultNamespace` so any context joining that namespace inherits it. The generated impl routes the component's lookup under the prefix path: - -```rust -impl<__Components__> MyNamespace<__Components__> for BarProviderComponent { - type Delegate = RedirectLookup< - __Components__, - PathCons>, - >; -} -``` - -A context joins a namespace inside `delegate_components!` with a `namespace` header line, after which every lookup it cannot resolve directly forwards through the namespace. A direct entry on the same context shadows just that key, leaving the rest of the inherited wiring intact: - -```rust -delegate_components! { - AppA { - namespace DefaultNamespace; - - @test.ShowImplComponent.u64: - ShowWithDisplay, // overrides only the u64 entry - } -} -``` - -The `namespace DefaultNamespace;` line emits a blanket `DelegateComponent` impl on `AppA` that forwards every key through `DefaultNamespace`, paired with the matching `IsProviderFor` forwarding so dependency errors stay diagnosable through [checking](checking.md). The direct `@test.ShowImplComponent.u64` line resolves first, so it wins for `u64` only — the inherit-and-override pattern in action. The override works because `DefaultNamespace` only routes the *marker* `ShowImplComponent` to a path that the context itself fills; a context cannot instead override a path the joined namespace *itself* registers (through a `:` body entry or a `#[default_impl]`), because the direct entry and the namespace's blanket `DelegateComponent` impl would both cover that path and conflict (`E0119`). To leave a path overridable, route the marker through the namespace but terminate the redirect on the context. Joining through `delegate_and_check_components!` does the same and additionally checks the entries the block writes directly, but its derivation does not cover the components the namespace itself brings in — so verifying the full inherited wiring is a job for a standalone `check_components!` (see [checking](checking.md)). - -## Paths with `Path!` - -A path is the type-level address that namespace entries redirect along, and `Path!` is the macro that builds one from a readable dotted, `@`-prefixed form. Each segment narrows the lookup one step — through a namespace, through a prefix, down to a component key — and the leading `@` is the sigil marking the body as a path rather than a plain type: - -```rust -type ErrorRoute = Path!(@app.error.ErrorRaiserComponent); -// PathCons>> -``` - -The encoding of each segment is decided by its first character: a single lowercase identifier that is not a primitive type name (like `app` or `error`) becomes a [`Symbol`](abstract-types.md) type-level string, while every capitalized segment (like `ErrorRaiserComponent`) is kept as the named type — typically a component key or namespace marker. The macro folds the segments right-to-left onto `Nil`, wrapping each in a `PathCons`. You rarely call `Path!` directly; the same `@`-path syntax is embedded inside `cgp_namespace!` entries and `#[prefix(...)]` attributes, which is where paths are most often written. These [type-level primitives](type-level-primitives.md) carry no runtime value. - -## The `RedirectLookup` provider - -`RedirectLookup` is the [provider](components.md) — a zero-sized marker struct, no runtime value — that turns a path-addressed entry back into a concrete provider, and it is the mechanism every namespace runs on under the hood. The ordinary provider blanket impl looks a component up in the context's own table keyed by the component-name marker; `RedirectLookup` instead consults a table keyed by an arbitrary type-level path, then delegates to whatever provider that entry holds. This decouples *which key* a component is looked up under from *which table* answers it — the basis for organizing wiring into namespaces. - -`RedirectLookup` is never written by hand; it is emitted by the macros. Every `#[cgp_component]` generates a `RedirectLookup` impl of its provider trait, and the namespace `=>` entries and `#[prefix]` attributes generate entries whose `Delegate` is a `RedirectLookup`. The generated impl performs one `DelegateComponent` lookup keyed on the path rather than on the component name: - -```rust -impl<__Context__, __Components__, __Path__> Greeter<__Context__> - for RedirectLookup<__Components__, __Path__> -where - __Components__: DelegateComponent<__Path__>, - <__Components__ as DelegateComponent<__Path__>>::Delegate: Greeter<__Context__>, -{ - fn greet(__context__: &__Context__) -> String { - <__Components__ as DelegateComponent<__Path__>>::Delegate::greet(__context__) - } -} -``` - -So `RedirectLookup` implements the provider trait whenever the table maps the path to a delegate that itself implements that trait, and forwards the call to it. When the provider trait carries a generic type parameter, the impl additionally appends that parameter onto the path before the lookup, so the redirected key can encode the generic argument — this is how per-type dispatch through a namespace works. - -## Default resolution: the `DefaultNamespace` family - -The traits that back namespaces come in three arities, differing only in how many type parameters take part in the key. `DefaultNamespace` keys a default purely on the component name; `DefaultImpls1` keys it on the component name *and* one further type — the shape for a per-type default where the same component resolves differently for `String` than for `u64` — and `DefaultImpls2` does the same for a pair. Each carries a single `Delegate` associated type and no method or data; resolution is the projection of `Delegate` from the matching impl: - -```rust -pub trait DefaultNamespace { - type Delegate; -} - -pub trait DefaultImpls1 { - type Delegate; -} -``` - -`DefaultNamespace` is the built-in namespace that `#[prefix(... in DefaultNamespace)]` registers components into and that a context joins with `namespace DefaultNamespace;`. A per-type default is registered with the `#[default_impl(T in DefaultImpls1)]` attribute on a provider impl, which emits `impl DefaultImpls1 for T { type Delegate = Provider; }`. The registration impl drops the provider's own impl-side `where` clause (its `#[use_type]`/`#[uses]` bounds), so a provider that depends on abstract types registers cleanly. Where the attribute may be *written* follows the orphan rule: the crate must own the namespace trait or the key — so an unprefixed component's marker key can be registered into a foreign namespace downstream, but a `#[prefix]`-ed component's key is a foreign `PathCons` path, confining its default to the namespace's own crate. A context then pulls those defaults in with a `for … in` loop that projects the `Delegate` for each type: - -```rust -delegate_components! { - App { - namespace DefaultNamespace; - - for in DefaultImpls1 { - @test.ShowImplComponent.T: Provider, - } - - @test.ShowImplComponent.u64: - ShowWithDisplay, // overrides the inherited default for u64 - } -} -``` - -The `for in DefaultImpls1` loop wires each type `T` by reading `T: DefaultImpls1`, and the direct `u64` line shadows whatever the namespace would otherwise supply for that type. The loop target can equally be a whole namespace defined with `cgp_namespace!`, such as the `DefaultShowComponents` namespace shown earlier — `for in DefaultShowComponents { … }` wires its listed types through the same projection. An optional `where` clause after the loop target (`for in Table where T: Clone { … }`) adds its bounds to every impl the loop emits, narrowing which types it wires. - -## Defining a preset once, reusing it across contexts - -The payoff is that a bundle of wiring is defined once and reused everywhere. A library publishes a namespace of sensible defaults — possibly extended from a base namespace as `ExtendedNamespace: DefaultNamespace` does — and any number of applications join it, inherit the whole bundle, and override only the entries specific to their needs. Each context's table shrinks to a `namespace` header plus a short list of overrides, no matter how many components the namespace bundles. Because the inheritance, the overrides, and the redirections are all resolved through trait projection and type-level paths, the entire arrangement is resolved at compile time with no runtime cost — a preset is simply one more namespace in the chain. - -## Related constructs - -Namespaces build directly on [wiring](wiring.md): a namespace is a `DelegateComponent` table addressed by paths, and a context joins one inside `delegate_components!`. The keys a namespace maps are the `…Component` markers of [components](components.md), attached via the `#[prefix(...)]` attribute on a `#[cgp_component]` trait, and the `IsProviderFor` forwarding a `namespace` header emits feeds the completeness guarantees in [checking](checking.md). The `@`-paths and `Symbol` segments are [type-level primitives](type-level-primitives.md). The per-type dispatch `RedirectLookup` enables — appending a generic parameter onto the lookup path — is the same mechanism the type-parameter dispatch forms in [higher-order providers](higher-order-providers.md) use. - -## Further reference - -Online docs: -[concepts/namespaces.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/namespaces.md), -[reference/macros/cgp_namespace.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_namespace.md), -[reference/providers/redirect_lookup.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/redirect_lookup.md), -[reference/macros/path.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/path.md). diff --git a/docs/ai/skills/references/namespaces.md b/docs/ai/skills/references/namespaces.md new file mode 120000 index 00000000..a2b487a5 --- /dev/null +++ b/docs/ai/skills/references/namespaces.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/namespaces.md \ No newline at end of file diff --git a/docs/ai/skills/references/type-level-primitives.md b/docs/ai/skills/references/type-level-primitives.md deleted file mode 100644 index f26a72d1..00000000 --- a/docs/ai/skills/references/type-level-primitives.md +++ /dev/null @@ -1,206 +0,0 @@ -# Type-level primitives - -The handful of zero-sized types and type macros that CGP folds strings, numbers, lists, choices, and routes into the type system, so the compiler can match a field name or a wiring route through trait resolution alone. - -## The idea - -CGP keys nearly everything by *type*, not by value. A getter looks up a field by a tag type; a [wiring](wiring.md) table selects a [provider](components.md) by a [component](components.md) key type; a [namespace](namespaces.md) re-routes a lookup along a path type. For that to work, things that are normally values — a field name string, a tuple position, a list of fields, a lifetime — have to be encoded as types the compiler can compare and dispatch on. The primitives in this reference are those encodings. Each is a familiar value-level idea lifted into a type: a string becomes a type-level character list, a number becomes a const-generic marker, a list becomes a recursive cons cell, a sum becomes a recursive branch. - -These types are almost never written by hand. They are produced by macros (`Symbol!`, `Product!`, `Sum!`, `Path!`) or emitted by derives, and a reader mostly meets them when *decoding a type the compiler prints* — in an error message, a macro-expansion dump, or a hover. (`cargo cgp expand` resugars them back to `Symbol!`/`Product!`/`Path!`, so a raw spine there means the resugaring declined; an error message or a plain `cargo expand` shows them as they are.) This reference is a decoder ring: skim it to read off what a long nested type means. The prose below always uses the readable `Cons`/`Nil`/`Symbol!` forms, which are exactly what the compiler prints — no abbreviations or aliases are substituted for these types. - -Assume `use cgp::prelude::*;` throughout. - -## Type-level lists: `Product!`, `Cons`, `Nil` - -A type-level list is a compile-time linked list — the analogue of a tuple that generic code can take apart one element at a time. It is built from two cells: `Cons`, a pair holding the first element and the rest of the list, and `Nil`, a unit struct marking the end. Chained to the right and terminated by `Nil`, they form an *anonymous product type* — a record-shaped type whose width and contents a provider can walk without knowing the concrete struct it came from. - -```rust -pub struct Cons(pub Head, pub Tail); -pub struct Nil; -``` - -The `Product!` macro is the sugar a programmer writes instead of nesting `Cons` by hand, and the lowercase `product!` builds a matching value with the tuple-struct constructor: - -```rust -type Row = Product![u32, String, bool]; -// Row == Cons>> - -let row: Row = product![1, "hi".to_string(), true]; -// row == Cons(1, Cons("hi".to_string(), Cons(true, Nil))) -``` - -The list is what makes structural, field-by-field code possible. A struct's fields are exposed as one `Product!` type through `HasFields`, so a provider written once to recurse over `Cons`/`Nil` — a `Nil` impl for the base case, a `Cons` impl for the step — iterates, reads, or rebuilds *any* struct's fields. The elements are usually [`Field`](#field-a-named-value) entries pairing a name with a value, so a derived struct's layout reads as a `Product!` of `Field` cells. See [extensible data](extensible-data.md) for how that machinery is used. - -## Type-level sums: `Sum!`, `Either`, `Void` - -A type-level sum is the dual of the list: where a `Product!` holds a value for *every* element at once, a `Sum!` holds a value for exactly *one* branch — a tagged union the compiler can walk variant by variant. It shares the same right-nested shape but branches at each step instead of pairing, and terminates in an uninhabited marker instead of a constructible one. - -```rust -pub enum Either { Left(Head), Right(Tail) } -pub enum Void {} -``` - -`Either` is the sum cell — `Left(head)` selects this branch, `Right(tail)` defers to the rest — and `Void`, an empty enum with no values, closes the chain. The `Sum!` macro folds a list of types onto that spine, and a value picks one branch by how deep it sits: - -```rust -type Token = Sum![u32, String, bool]; -// Token == Either>> - -let t: Token = Either::Right(Either::Left("hi".to_string())); // the String branch -``` - -The terminator is the one real difference from the product spine, and it is load-bearing. A product ends in the constructible `Nil` because an empty record is a valid value; a sum ends in the *uninhabited* `Void` because an empty choice has no value to pick. After an extractor has tried every variant and matched none, the leftover has type `Void` — a value that cannot exist — which the machinery discharges with an empty `match self {}`, making a fully-handled variant match total at compile time with no unreachable runtime branch. An enum's variants are exposed as a `Sum!` of `Field` entries through `HasFields`, mirroring how a struct's fields are a `Product!`. - -## Type-level strings: `Symbol!`, `Symbol`, `Chars` - -A type-level string is a field name encoded as a type, so the name can drive trait resolution. CGP's getter, `HasField`, keys each field by a `Tag` type; to read a field called `name`, the string `"name"` must become a unique type, so that two symbols from the same string are the *same* type and two from different strings are *different* types. `Symbol!("name")` produces exactly that. - -The reason it is a *list of characters* rather than one const value is a stable-Rust limitation: a `&str` cannot be a const-generic parameter, but a single `char` can. So `Chars` spells the string out one character at a time — the specialized analogue of `Cons` where the head is a `const char` — and `Symbol` wraps that list together with the byte length: - -```rust -pub struct Chars(pub PhantomData); -pub struct Symbol(pub PhantomData); -``` - -The `Symbol!` macro hides all of this. The leading `LEN` const is the part most likely to puzzle a reader: stable Rust cannot compute a `Chars` chain's length inside a const-generic context, so the macro precomputes `str::len()` — the *byte* length — and bakes it into the type: - -```rust -// before -Symbol!("abc") -// after -Symbol<3, Chars<'a', Chars<'b', Chars<'c', Nil>>>> -``` - -Because `LEN` is the byte length, a multi-byte string records its UTF-8 width: `Symbol!("世界你好")` records `12`, while its character list still has one `Chars` node per scalar. The empty string is `Symbol<0, Nil>`. A type-level string is most often seen as the tag in a getter bound, where it names the field a provider reads without that context naming the provider: - -```rust -#[cgp_impl(new GreetHello)] -impl Greeter -where - Self: HasField, -{ - fn greet(&self) { - println!("Hello, {}!", self.get_field(PhantomData::)); - } -} -``` - -The same string can be recovered at runtime — see [`StaticFormat`](#staticformat-recovering-strings-and-paths) below. - -## `Index`: type-level numbers - -`Index` is the numeric counterpart to `Symbol!` — a `usize` lifted into a type, used to tag a tuple-struct field that has a position but no name. Where a named field is keyed by `Symbol!("name")`, the field at position `N` is keyed by `Index`, so `Index<0>`, `Index<1>`, and `Index<2>` are three distinct tag types standing in for `.0`, `.1`, and `.2`. - -```rust -pub struct Index; -``` - -It is a zero-sized marker: the number lives entirely in the type, so a tuple struct can carry a `HasField>` impl and a `HasField>` impl side by side and the compiler selects the right one purely from the tag. Selecting a wrong position — `Index<5>` on a three-field struct — is a type error, not a runtime panic, because no matching impl exists. `Index` prints its number directly through `Display`, so `Index::<2>.to_string()` is `"2"` and the tag is legible in diagnostics. - -## `Field`: a named value - -`Field` is the element type that fills both spines — a value paired with the type-level tag naming it. A bare `Product![String, u8]` records only types and order; wrapping each element as `Field` attaches the name as a phantom type, making the structural representation self-describing so a provider can match on the tag to find the field it wants. - -```rust -pub struct Field { - pub value: Value, - pub phantom: PhantomData, -} -``` - -The tag is a phantom — needed only at compile time for resolution — so a `Field` is exactly as large as its `Value` and costs nothing at runtime. It is built from a value with no tag argument, since the tag is fixed by the target type: `let f: Field = "Alice".to_string().into();`. The same shape names a record field (tag from `Symbol!` or `Index`) and an enum variant (tag from `Symbol!`, value being the payload), which is why a derived `HasFields` is a `Product!` or `Sum!` of `Field` entries: - -```rust -#[derive(HasFields)] -pub struct Person { pub name: String, pub age: u8 } - -// generated: -// type Fields = Product![ -// Field, -// Field, -// ]; -``` - -## `Path!` and `PathCons`: type-level routes - -A type-level path is a route through nested [wiring](wiring.md) tables, expressed as a single type. Where a bare component key picks one entry out of a context's table, a path points at an entry behind one or more layers of indirection — inside a [namespace](namespaces.md), under a prefix — by listing the segments to walk left to right. `PathCons` is the cons cell of that route, terminated by `Nil`, and it differs from the `Cons` product spine in one way: both `Head` and `Tail` are `?Sized`, because a path segment is a pure type-level marker that never needs a known size. - -```rust -pub struct PathCons(pub PhantomData, pub PhantomData); -``` - -The `Path!` macro builds the route from a dotted, `@`-prefixed name, encoding each segment by case: a lowercase, non-primitive identifier becomes a `Symbol!` type-level string, and a capitalized name stays the named type it spells (typically a component key or namespace marker): - -```rust -type ErrorRoute = Path!(@app.error.ErrorRaiserComponent); -// PathCons>> -``` - -A path names only *where to look*, never a provider directly, so the same path resolves to different providers depending on the table it is walked against — the job of the `RedirectLookup` provider that consumes it. This same `@`-path syntax appears verbatim inside namespace entries, which is where paths are most often written rather than through the bare macro. See [namespaces](namespaces.md) for the redirected-lookup mechanism. - -## `Life<'a>`: a lifetime as a type - -`Life<'a>` lifts a lifetime into a type, so a CGP trait that borrows can still ride through wiring machinery that only accepts types. CGP's dependency marker, `IsProviderFor`, takes a tuple of a component's generic parameters as one type argument — and a tuple member must be a type, never a bare lifetime. A consumer trait declaring `fn get_reference(&self) -> &'a T` therefore cannot record its `'a` directly; `Life<'a>` is the conversion that packages the lifetime as a type so it can sit in the tuple as `(Life<'a>, T)`. - -```rust -pub struct Life<'a>(pub PhantomData<*mut &'a ()>); -``` - -The `*mut &'a ()` phantom is deliberate: a raw pointer is *invariant* in its lifetime, so `Life<'a>` is invariant in `'a`. That is correct here — the lifetime is an exact identity in the dependency marker, and a variant `Life` would let the compiler silently coerce one instantiation into another and pick the wrong provider. The macros insert `Life` automatically when a component carries a lifetime; a reader meets it in the generated provider trait, where `IsProviderFor<…, (Life<'a>, T)>` names the lifetime as a type rather than a bare `'a`. Conceptually it joins `Index` (which lifts a `usize`) and `Symbol` (which lifts a string) as another marker making a non-type thing addressable in trait resolution. - -## `MRef<'a, T>`: owned-or-borrowed - -`MRef<'a, T>` is a "maybe-reference" — an enum holding either a borrow of a `T` or an owned `T` — so a single getter signature serves both the context that already stores a value and the one that must produce it. Unlike the rest of this reference, there is nothing type-level about it: it is an ordinary runtime value, the payload a getter hands back. - -```rust -pub enum MRef<'a, T> { Ref(&'a T), Owned(T) } -``` - -A getter declared to return `MRef<'a, T>` lets a context with the value in a field return `MRef::Ref` and lend it, while a context that computes the value returns `MRef::Owned` and gives it away — with no extra cost in the common stored-field case. The caller treats both uniformly because `MRef` derefs to `T`: it implements `Deref` and `AsRef`, builds either variant through `From` and `From<&'a T>`, and promotes a borrow to ownership with `get_or_clone` when `T: Clone`. - -```rust -let stored = String::from("hello"); -let borrowed: MRef<'_, String> = MRef::from(&stored); // lends a stored value -let made: MRef<'_, String> = MRef::from(String::from("world")); // hands over a built one -assert_eq!(&*borrowed, "hello"); -let owned: String = borrowed.get_or_clone(); // clones the borrowed case -``` - -It is one of the getter return modes recognized by the field macros, parallel to `&T`, `Option<&T>`, or `&str`; see [functions and getters](functions-and-getters.md). Its lifetime is an ordinary borrow and is unrelated to the `Life<'a>` lift above. - -## `StaticFormat`: recovering strings and paths - -The type-level encodings need a way back to runtime data, and three traits provide it. `StaticFormat` recovers a type-level string *lazily* by writing into a formatter — it backs the `Display` impls on `Symbol` and `Chars`, recursing down the `Chars` spine to emit each character, so any symbol prints with `to_string()` or `{}`: - -```rust -let s = ::default(); -assert_eq!(s.to_string(), "hello"); -``` - -`StaticString` recovers it *eagerly*, as a compile-time `&'static str` constant: a blanket impl walks the `Chars` list and UTF-8-encodes it into a `[u8; LEN]` at const-evaluation time — which is the consumer that `Symbol`'s `LEN` byte length exists to size — then validates the bytes as a `&'static str`. Use `Display` when a runtime value will do; use `StaticString::VALUE` when a `const` is needed or in a hot path. Both round-trip multi-byte Unicode faithfully: - -```rust -use cgp::core::field::traits::StaticString; -assert_eq!(::VALUE, "世界你好"); -``` - -`ConcatPath` works one level up, joining two `PathCons` paths into one as a pure type-level computation — it keeps each `Head` and splices the second path on where the first reaches `Nil`, the operation behind composing nested accessors: - -```rust -type Joined = >::Output; // the path a.b.c.d -``` - -## Further reference - -Online source-of-truth documents: the -[types directory](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp/reference/types) -(`cons.md`, `either.md`, `chars.md`, `index.md`, `field.md`, `life.md`, `mref.md`, `path_cons.md`), -the construction macros -[`macros/symbol.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/symbol.md), -[`macros/product.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/product.md), -[`macros/sum.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/sum.md), -[`macros/path.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/path.md), -and the recovery traits -[`traits/static_format.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/static_format.md). diff --git a/docs/ai/skills/references/type-level-primitives.md b/docs/ai/skills/references/type-level-primitives.md new file mode 120000 index 00000000..79574a2b --- /dev/null +++ b/docs/ai/skills/references/type-level-primitives.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/type-level-primitives.md \ No newline at end of file diff --git a/docs/ai/skills/references/wiring.md b/docs/ai/skills/references/wiring.md deleted file mode 100644 index 9aef7341..00000000 --- a/docs/ai/skills/references/wiring.md +++ /dev/null @@ -1,194 +0,0 @@ -# Wiring - -How a context selects which provider implements each of its components, by recording a type-level table that maps every `…Component` marker key to a chosen provider. - -A CGP [component](components.md) splits the consumer trait callers use (`CanDoX`) from the provider trait implementers write (`SomethingDoer`), but that split leaves one question open: for a given context, *which* provider supplies the behavior? Wiring is the answer. It is the act of telling a context, component by component, which provider stands behind each consumer-trait call — and the mechanism is a small type-level lookup table carried on the context type. This file explains that table, the `delegate_components!` macro that populates it, and the `UseContext` provider that lets a provider trait route back through the context's own consumer-trait impl. - -## The table: `DelegateComponent` - -The table is the trait `DelegateComponent`, which maps one key type to one value type: - -```rust -pub trait DelegateComponent { - type Delegate; -} -``` - -There is no method and no data — the trait exists purely to associate a value type (`Delegate`) with a key type (`Key`) on a carrier type (`Self`). The mental model is a type-level key-value map living on the `Self` type, analogous to an object's method table (vtable) in object-oriented languages: where a vtable maps method names to function pointers resolved at runtime, this table maps `…Component` marker types to provider types resolved entirely at compile time. Implementing `DelegateComponent` is "setting" the entry at `Key`; naming `Self: DelegateComponent` in a bound and reading `Self::Delegate` is "getting" the value back out. Because Rust forbids two impls of the same trait for the same `Self` and `Key`, each key maps to exactly one value, which is what makes the structure a genuine map. - -When the key is a component marker such as `GreeterComponent`, a populated entry causes the context to inherit the matching provider trait through the blanket impl, and from there the consumer trait — so `app.greet()` type-checks. The blanket impl's body is itself a `DelegateComponent` lookup: it reads the entry, finds the provider, and forwards the call to it. The lookup *is* the whole routing mechanism. (When the key is some arbitrary type instead of a component marker — a shape, a tag — the same trait serves as a plain dispatch table walked by a higher-order provider, with no provider trait attached; see [higher-order providers](higher-order-providers.md).) - -## `delegate_components!`: populating the table - -You almost never write `DelegateComponent` impls by hand. The `delegate_components!` macro populates the table from a compact `Key: Value` syntax, one entry per component, the marker as the key and the chosen provider as the value: - -```rust -#[derive(HasField)] -pub struct Rectangle { - pub width: f64, - pub height: f64, -} - -delegate_components! { - Rectangle { - AreaCalculatorComponent: RectangleArea, - } -} -``` - -This wires `Rectangle` to use the `RectangleArea` provider for its `AreaCalculatorComponent`. After this, calling `rect.area()` resolves through `Rectangle`'s table to `RectangleArea`. The target before the brace is the [context](checking.md) (or an intermediary provider table) whose table is being defined; each key is a `…Component` marker type and each value is the provider type to delegate it to. - -When several components share one provider, the array form on the key side lets a bracketed list of markers expand to one entry each, all pointing at the same value: - -```rust -delegate_components! { - Rectangle { - [ - AreaCalculatorComponent, - PerimeterCalculatorComponent, - ]: RectangleGeometry, - GreeterComponent: GreetHello, - } -} -``` - -This is exactly equivalent to writing `AreaCalculatorComponent: RectangleGeometry` and `PerimeterCalculatorComponent: RectangleGeometry` on separate lines, plus the `GreeterComponent` entry — three entries in all. - -A `new` keyword in front of the target makes the macro define the target struct as well, saving a separate declaration. `new GeometryComponents { … }` emits `struct GeometryComponents;` alongside the table impls. This is the idiomatic way to declare an **aggregate provider** — a zero-sized provider whose only purpose is to hold a table that dispatches each component to a sub-provider, so that other contexts can delegate a whole group of components to it as a single unit: - -```rust -delegate_components! { - new GeometryComponents { - AreaCalculatorComponent: RectangleArea, - PerimeterCalculatorComponent: RectanglePerimeter, - } -} -``` - -An aggregate provider is a *provider*, not a context. `GeometryComponents` implements each component's provider trait by forwarding through its `DelegateComponent` table, and another context then delegates to it — `delegate_components! { App { [AreaCalculatorComponent, PerimeterCalculatorComponent]: GeometryComponents } }` — reusing the whole bundle in one line. Because it is never its own context, an aggregate provider is always wired with plain `delegate_components!`, never `delegate_and_check_components!`: the checked macro would assert that the aggregate can *use* each component as a context, which the bundle was never meant to answer, so the result is uninformative whichever way it goes — it passes vacuously when the bundled providers need nothing from their context, and fails blaming the bundle when any of them needs a field or a type the real context would have supplied. An aggregate provider is verified instead when a real context that delegates to it is checked; see [checking](checking.md). - -A leading generic list on the target makes the whole table generic, so one wiring applies across a family of contexts: `delegate_components! { MyContext { … } }` wires every `MyContext` at once. - -### What the macro generates - -Each entry expands to a pair of impls. The first is the `DelegateComponent` impl that stores the entry — for the `Rectangle` example above, the macro emits: - -```rust -impl DelegateComponent for Rectangle { - type Delegate = RectangleArea; -} -``` - -This impl alone is what the provider blanket impl reads when it looks the component up. The second impl is an `IsProviderFor` impl that forwards the chosen provider's requirements back through the table, so a missing transitive [impl-side dependency](components.md) still surfaces as a usable compiler error rather than a dead end. The details of that propagation belong to [components](components.md) and [checking](checking.md) — here it is enough to know that wiring an entry makes it both *resolvable* (the `DelegateComponent` half) and *checkable* (the `IsProviderFor` half). - -## Explicit delegation: what wiring effectively does - -To see what `delegate_components!` buys you, it helps to write the routing out by hand. Without any table, a context can implement a consumer trait directly by calling a provider's provider-trait method itself. Given the `AreaCalculator` provider trait (whose method takes the context as an explicit `Context` parameter rather than `&self`), a context can hand-route its `CanCalculateArea` consumer impl through the `RectangleArea` provider: - -```rust -impl CanCalculateArea for Rectangle { - fn area(&self) -> f64 { - >::area(self) - } -} -``` - -This is the manual equivalent of one `delegate_components!` entry: it names the provider explicitly, invokes its provider-trait method, and passes `self` as the context. The single line `AreaCalculatorComponent: RectangleArea` in the table achieves the same routing generically, through the generated `DelegateComponent` impl and the blanket impl that reads it — for every method on the trait, without you writing out each call. Use this explicit form only as a teaching device or in the rare case where you want a context to bypass the table for one trait; the table form is the idiom. - -## Direct implementation of a consumer trait - -A context need not delegate at all. When the behavior is specific to one context and there is no provider worth naming, you can implement the consumer trait directly — plain vanilla Rust, no table involved: - -```rust -impl CanGreet for Person { - fn greet(&self) { - println!("Hello, I am {}", self.name); - } -} -``` - -This bypasses the provider-trait machinery entirely: `person.greet()` calls this impl directly. Direct implementation and table-driven wiring are mutually exclusive for a given component on a given context — the table's blanket impl already supplies the consumer trait, so a hand-written consumer impl would collide with it. Reach for direct implementation when a component has exactly one context-specific behavior and the indirection of a separate provider adds nothing. - -## `UseContext`: routing a provider trait back to the consumer trait - -`UseContext` is a [provider](components.md) — a zero-sized marker struct with no runtime value — that implements *any* provider trait by forwarding its methods back to the context's own consumer-trait implementation: - -```rust -pub struct UseContext; -``` - -It is the exact dual of the consumer-trait blanket impl. That blanket impl runs consumer-to-provider — a context implements `CanGreet` by delegating to whichever provider implements `Greeter` for it. `UseContext` runs the opposite direction: it implements the provider trait `Greeter` by calling whatever `CanGreet` implementation the context already has. `#[cgp_component]` generates a `UseContext` impl of the provider trait for every component, of roughly the shape: - -```rust -impl Greeter for UseContext -where - Context: CanGreet, -{ - fn greet(context: &Context) { - Context::greet(context) - } -} -``` - -So wiring a component to `UseContext` means "use whatever this context already does for this trait." Its purpose is to turn a context's existing consumer-trait impl into a provider that *another* provider can call. The pattern matters most for [higher-order providers](higher-order-providers.md), which take an inner provider as a type parameter and often default it to `UseContext`, so the inner step falls back to the context's own wiring unless an explicit provider is named. - -The one rule to respect is the circular-dependency caveat: never delegate a component to `UseContext` when the context's only impl of that component *is* the delegation itself. Doing so asks the context to implement the consumer trait by delegating to a provider (`UseContext`) that in turn implements the provider trait by calling the consumer trait — a cycle the trait solver cannot resolve, surfacing as an overflow or unsatisfied-bound compile error. `UseContext` is meant to be supplied to another provider as its inner provider, not wired as a context's own delegate for the same component. - -## Other providers you will see in tables: `WithProvider` and `UseDefault` - -Two more provider markers appear in real wiring often enough to recognize on sight. Both are ordinary zero-sized providers wired like any other, but neither carries behavior of its own — one adapts a lower-level provider into a component, and the other selects a component's own default method bodies. - -`WithProvider` adapts a *foundational* provider into the provider a named component expects. CGP has two layers of provider: the component-specific provider traits a context wires (`NameGetter`, `NameTypeProvider`), and a handful of generic, component-agnostic mechanisms beneath them — [`FieldGetter`](functions-and-getters.md) reads *some* field for *some* tag, and [`TypeProvider`](abstract-types.md) supplies *some* abstract type — that do not know which component they serve. `WithProvider` is the adapter that lets one of those foundational providers stand in for a named component by forwarding the component's method to it. You rarely write `WithProvider<…>` in full, because its common cases ship as aliases you *will* see wired: `WithField` and `WithFieldRef` (a `FieldGetter` as a getter component), `WithType` and `WithDelegatedType` (a `TypeProvider` as an abstract-type component), and `WithContext` (the context's own capability). Reading `NameGetterComponent: WithField<…>`, treat it as "this getter is served by the foundational field-getter named inside." - -`UseDefault` is the empty provider that selects a component's *own* default method bodies. A consumer trait may give its methods default bodies exactly as any Rust trait can; when every method is defaulted there is no behavior left for a provider to supply, yet the component still needs *some* provider in the table to be wired. `UseDefault` is the conventional name for that role — but unlike `UseContext` or `UseField`, no macro generates its impl, so the author writes an empty `#[cgp_impl(UseDefault)]` (or an empty impl on the concrete context) whose body falls through to the trait defaults. Wiring a component to `UseDefault` therefore reads as "use the trait's own defaults for this component." - -## Dispatching a component per type with `open` - -When a provider trait carries an extra generic parameter and the right provider depends on which concrete type that parameter is, the choice is made by a second lookup keyed on that parameter rather than on the component marker. The `open` statement inside `delegate_components!` is the way to write that per-value wiring: it folds the per-type entries directly into the context's own table, one provider per concrete value of the dispatch parameter. Given a `CanCalculateArea` consumer trait whose `Shape` parameter selects the area formula, a context wires each shape to its own provider like this: - -```rust -delegate_components! { - MyApp { - open AreaCalculatorComponent; - - @AreaCalculatorComponent.Rectangle: RectangleArea, - @AreaCalculatorComponent.Circle: CircleArea, - } -} -``` - -The leading `open AreaCalculatorComponent;` header opens one or more components for per-value wiring. The braces are optional when opening a single component, so `open AreaCalculatorComponent;` and `open { AreaCalculatorComponent };` are equivalent; to open several components together, list them inside the braces (`open { A, B };`). The header is a *leading* statement: when a single block mixes plain `Component: Provider` mappings with an `open` block, the `open` header must come first, before any plain mappings, or the macro fails to parse. Each subsequent `@Component.Key: Provider` entry then assigns a provider for one value of that component's dispatch parameter: `@AreaCalculatorComponent.Rectangle: RectangleArea` says that when `Shape` is `Rectangle`, `MyApp` calculates area through `RectangleArea`, and the `Circle` line does the same for `Circle`. After this wiring, `MyApp` implements `CanCalculateArea` via `RectangleArea` and `CanCalculateArea` via `CircleArea`. - -Three shorthands keep the entries compact. When several values of the dispatch parameter share one provider, a **bracketed group** on a path segment expands to one entry each — `@AreaCalculatorComponent.[Rectangle, Circle]: SomeProvider` wires both shapes to `SomeProvider`. A bracketed group is not restricted to the last segment and may be followed by more path, so `@app.[FooComponent, BarComponent].[u64, String]: P` writes all four combinations in one entry. A **braced group** looks similar and behaves differently: its elements are whole *tails* rather than single segments, so they may differ in length and may nest, but nothing may follow the closing brace — `@app.{ErrorRaiserComponent.{&'static str, String}, ErrorWrapperComponent}: RaiseFrom` is one entry covering three routes, while writing `.bool` after such a group is a parse error reported only as `expected ':'`. And when a dispatch value needs generic parameters of its own, they precede the value: `@SomeComponent.<'a, T> &'a T: SomeProvider` dispatches on the type `&'a T` for all `'a` and `T`. - -The `open` form needs no extra macro on the component. It works through the `RedirectLookup` impl that every `#[cgp_component]` already generates, so dispatching a component per type requires no `#[derive_delegate]` on the trait — the same component you wire by marker is the one you open by value. `open` is a lightweight form of the full namespace feature, suited to a context wiring its own components directly; it does not combine with a joined namespace where the component carries `#[prefix(...)]`. The full namespace machinery, including `@`-path keys and the `namespace` statement, is described in [namespaces](namespaces.md). - -### Legacy: `UseDelegate` nested tables - -An older form writes the per-type entries into a separate table wrapped in the `UseDelegate` provider, rather than folding them into the context's own table with `open`. It nests a `new` table inside a single `UseDelegate<…>` value: - -```rust -delegate_components! { - MyApp { - AreaCalculatorComponent: UseDelegate, - } -} -``` - -This desugars `UseDelegate` into a standalone `delegate_components! { new AreaCalculatorComponents { … } }` plus an outer entry `AreaCalculatorComponent: UseDelegate` pointing the component at that inner table. The end effect matches the `open` example above — `MyApp` dispatches `Rectangle` to `RectangleArea` and `Circle` to `CircleArea` — but the dispatch values live in a named side table reached through `UseDelegate` instead of in `MyApp`'s table directly. - -This is a legacy dispatch mechanism, retained for compatibility and expected to be deprecated and removed. It is documented here so that the nested-table form can be *read* where it still appears in existing code; for *writing* new wiring, prefer `open`, which dispatches the same component without the extra `UseDelegate` indirection or the separate inner table. The detailed mechanics of the `UseDelegate` provider — how it reads its inner table at the provider level — belong to [higher-order providers](higher-order-providers.md). - -## Related constructs - -Wiring is the step that connects [components](components.md) — the consumer/provider trait pairs and `…Component` markers — to the providers that implement them, and the `IsProviderFor` impls it generates feed the completeness guarantees described in [checking](checking.md). The `open` statement shown above dispatches a generic-parameter component per value through the `RedirectLookup` impl every component generates; the full namespace feature it derives from, including `@`-path keys and the `namespace` statement, is described in [namespaces](namespaces.md). `UseContext` and the legacy `UseDelegate` provider — including how it reads an inner dispatch table — are covered in [higher-order providers](higher-order-providers.md). - -## Further reference - -Online docs: -[delegate_components.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/delegate_components.md), -[traits/delegate_component.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/delegate_component.md), -[providers/use_context.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_context.md). diff --git a/docs/ai/skills/references/wiring.md b/docs/ai/skills/references/wiring.md new file mode 120000 index 00000000..4e8e406f --- /dev/null +++ b/docs/ai/skills/references/wiring.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/wiring.md \ No newline at end of file From d80a09df69b28f7dba24c07a0ab7ae88f42276ba Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 14 Sep 2026 09:35:08 +0000 Subject: [PATCH 071/516] Clarify CGP introductions and AI documentation Revise the introduction and overview with current learning paths, concrete capabilities, and qualified guarantees. Clarify AI authorship, review practices, and agent skill setup. Co-Authored-By: GPT-6 --- docs/ai/disclaimer.md | 172 +++++++++++++++------------------------ docs/ai/skills/index.md | 59 +++++++------- docs/index.md | 102 +++++++++++------------ docs/overview.md | 176 ++++++++++++++++++++++++++++++---------- 4 files changed, 274 insertions(+), 235 deletions(-) diff --git a/docs/ai/disclaimer.md b/docs/ai/disclaimer.md index 667806f4..5e4c3460 100644 --- a/docs/ai/disclaimer.md +++ b/docs/ai/disclaimer.md @@ -5,142 +5,100 @@ sidebar_label: AI Disclaimer # How AI Is Used in the CGP Project -CGP is built with substantial help from AI coding agents, and how much help varies a great deal from -one part of the project to another. This page says which parts, and why the line falls where it does, -so that you can decide for yourself how much weight to give each. - -The short version is that **the CGP library is designed and written by hand, while most of the -documentation around it is written by agents from a public knowledge base that is checked against the -library's source.** Everything else sits somewhere between those two, and the sections below take each -part in turn, starting where AI does the most. +CGP uses AI agents to write documentation, develop tools, maintain tests, and assist with library +implementation. The author designs every CGP construct and interface and writes the core library +almost entirely by hand. This page explains who does what, how the work is checked, and where those +checks have limits. ## Why the levels differ -Two questions decide how much of any given artifact an agent writes, and they point the same way. +CGP gives agents more writing responsibility when the result can be checked against existing code +and does not become part of your compiled program. Documentation, tools, and tests fit that +arrangement. The core library requires more direct authorship because applications depend on its +code and its design establishes the behavior that other work must follow. -**Does it become part of your program?** Code you add as a dependency and compile into your own project -is code you inherit, and you cannot easily audit it at the moment you need it to be right. Code that -merely runs *on* your project — a command-line tool, a test suite — is judged on its results, and you -can stop using it without touching anything you wrote. +Verification also differs by artifact. A claim about a macro can be checked against its source and +expansion snapshots. A tool's output can be compared with test fixtures. Design requires the author's +judgment about which behavior the library should provide; passing tests alone cannot settle it. -**Can it be checked against something that is already true?** A sentence about what a macro generates -can be checked against the macro. A test can be checked by running it. A *design* cannot be checked -against anything, because it is the thing everything else is checked against. +## Documentation and reference pages -So the closer something sits to the code you compile, the more of it is written by hand; and the more -cheaply it can be verified against a ground truth, the more of it an agent writes. +AI agents write most of CGP's reference pages, explanations, guides, and error documentation from the +public [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base). That repository +records the material behind the website and the rules agents must follow. Readers can inspect both +the documentation and the process used to produce it. -## Documentation and reference pages +**The source code is authoritative.** Agents must check claims about accepted syntax, generated names, +and macro expansions against the code, tests, or expansion snapshots. When documentation and code +disagree, the documentation needs correction. The rules also require documentation updates alongside +behavior changes and direct corrections to pages that describe current behavior. -Most of the written material about CGP — the construct reference, the explanations, the guides, and the -error catalog — is written by AI agents rather than by hand. - -What makes that workable is not the agents but the arrangement around them, and that arrangement is -public, so it can be inspected rather than taken on trust. All of this material is developed first in -the [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base), a separate repository -that holds the project's documentation along with the rules an agent must follow to write it. The -website pages are then derived from what is recorded there. - -**The knowledge base answers to the source code.** Its governing rule is that the source in each -repository is the single source of truth, ranking above any document and above the agent skill built -from it. So a claim about what a macro expands to, which identifier it generates, or which syntax it -accepts is not written from an agent's recollection — it is read out of the code, out of the test -suite, or out of the expansion snapshots that pin what each macro emits. When several descriptions of -one behavior disagree, the disagreement is treated as a defect and the code wins. - -Two further rules keep it from drifting. Documentation changes in the same change as the behavior it -describes, rather than in a follow-up, on the principle that a document describing behavior the library -no longer has is worse than no document at all, because the next reader will trust it. And each -document describes only how things work now, so a page is corrected in place rather than accumulating -notes about what used to be true. - -**The history is public too, and it is specific.** Every commit to the knowledge base records which -model contributed to it in a `Co-Authored-By` trailer. If you want to know how a particular sentence -about `#[cgp_component]` came to exist, you can read the rule that produced it and the commit that -landed it. That is a stronger claim than any assurance this page could make, which is why the knowledge -base is public in the first place. - -**What the human author does is set the rules and read what matters.** He decides what gets written and -in what order, sets the conventions the agents work under, reads in full the pages that carry the -project's argument — the front page, the explanation pages, the reference index, this page, and every -blog post — and is answerable for all of it. - -**The honest limit:** that review is not uniform, and it would be easy to imply otherwise. The roughly -seventy per-construct reference pages are not each read line by line. They are a mechanical port of -documents already written and verified against the source, into a fixed template, so the risk they -carry is a wrong expansion rather than a wrong argument — and a wrong expansion is caught by checking -the source, which is what the knowledge base's rules exist to enforce. Review where judgement matters, -verification against the source everywhere: that is the actual arrangement, and it is worth knowing -precisely rather than approximately. +The public history records AI contributions through `Co-Authored-By` commit trailers naming the +model. Together with the writing rules, that history lets readers inspect how the documentation was +produced. It provides a record of contributions, not a guarantee that every statement is correct. -## Blog posts and tutorials +**Human review varies by page.** The author sets the writing rules and priorities and reads the front +page, Concepts explanation pages, reference index, this disclosure, and every blog post in full +before publication. Individual construct reference pages follow a writing guide and receive spot +checks; the author does not read each one line by line. -These work the other way round. **The author writes the draft; an agent revises it against the -knowledge base.** The argument, the judgement about what is worth saying, the concessions, and the -voice all originate with him, and the agent's job is to improve the prose and to check the code and -claims against what the knowledge base records. +Source verification and human review serve different purposes. Checking a macro expansion against +the source can reveal a technical mistake, while reading an explanation can reveal a misleading +argument. Both can miss errors, and the project remains responsible for correcting them. -The ordering is the whole difference, and it is worth stating because "AI-assisted" otherwise covers -both this and the section above. A blog post is the author's argument, improved; a reference page is an -agent's writing, governed. Those are not the same thing. +## Blog posts and tutorials + +The author drafts blog posts and tutorials, then an agent revises the prose and checks the code and +claims against the knowledge base. The author supplies the argument, examples, and judgment about +what to teach. This differs from reference pages, where agents write the initial text. -**The honest limit:** a revised draft is still the author's claim, and revision does not make a wrong -argument right. Note also that this describes how posts and tutorials are written now — the site's -older text was refined with LLM assistance more broadly, as +Revision does not guarantee that an argument is correct. This describes the current writing process; +older site text received broader LLM refinement, as [the post about this website](/blog/2026/02/21/new-website) describes. ## Tooling and tests -[`cargo-cgp`](https://github.com/contextgeneric/cargo-cgp), the toolchain that makes CGP's compiler -errors readable, is mostly written by agents, and CGP's test suite is largely maintained by them. - -One rule gates both: **neither becomes part of your program.** A cargo subcommand runs *on* a project -and is never a dependency of it, so you are exposed to its behavior rather than to its source — and its -behavior is pinned by a snapshot test suite that either matches or does not. A test is the same case in -a sharper form, because a test is self-verifying against the real library: a wrong test fails loudly -rather than misleading quietly. +Agents write most of [cargo-cgp](https://github.com/contextgeneric/cargo-cgp) and maintain much of +CGP's test suite. These tools run on a project rather than becoming library dependencies compiled +into its application. Their output can be checked against fixtures and the library's behavior. -The test suite also has a positive reason rather than merely a permissive one. Exhaustively exercising -every syntax form a procedural macro accepts is large, mechanical, high-value work that one person -writing in their own time will never finish, and the library is better tested for having an agent do -it. +Agents also help expand test coverage across the syntax forms the procedural macros accept. That +work is extensive and repetitive, so assistance makes coverage practical beyond what the author +could maintain alone. Passing tests provide evidence for the cases they cover; an incorrect +expectation or a missing case can still leave a bug undetected. -**The honest limit:** `cargo-cgp` is an early pre-release, and a bug in a tool is still a bug. It -reshapes the error classes it recognizes and passes the rest through as the compiler wrote them. +`cargo-cgp` is an early pre-release and can contain bugs. It rewrites the error classes it recognizes +and passes other diagnostics through in the compiler's wording. ## The CGP library -**The design of every CGP construct and interface is the author's, and the library is written almost -entirely by hand.** This is the code you import and compile, and it is where the ground truth runs out: -there is nothing to check a design against, because the design is what everything else is checked -against. +The author designs every CGP construct and interface, and writes the core library almost entirely +by hand. This is the code applications import and compile, so he takes direct responsibility for +its design and implementation. -AI is used here too, and it would be misleading to imply otherwise. It is used to verify correctness, -to review code quality, and to work through the implementation of the procedural macros. The -[`cgp` repository's](https://github.com/contextgeneric/cgp) commit history records this in the same -`Co-Authored-By` trailers the knowledge base uses, and some of those commits touch the macros — so the -distinction that matters is not whether an agent has ever contributed a line, but which decisions are -whose. +AI assists with correctness checks, code-quality review, and procedural-macro implementation. The +author directs and reviews that implementation work. The +[cgp repository](https://github.com/contextgeneric/cgp) records shared work through +`Co-Authored-By` trailers, including contributions to the macros. -That distinction is this: **what CGP *is*** — every construct, every interface, and every decision -about how the pieces fit together — **is the author's work**, while **how a given macro is -implemented** is work he directs, reviews, and frequently shares. The first is what you are adopting -when you adopt CGP. The second is an implementation detail, held to the same standard as any other code -in the library. +The distinction is between design ownership and implementation assistance. The author decides what +CGP provides and how its interfaces fit together; agents help implement and check some of those +decisions. The library is not entirely free of AI contributions, and its checks cannot guarantee +that every implementation is correct. ## Responsibility -None of the above transfers responsibility. Everything published under CGP's name is the project's, and -an error in it is the project's error rather than an agent's — and as CGP's author, I would rather you -told me about one than worked around it. +The project is responsible for everything published under CGP's name, including errors in +agent-written work. As CGP's author, I would rather you told me about an error than worked around it. ## How pages are marked -Pages written with AI assistance carry a short note at the foot, linking back to the section here that -describes how they were made. That note goes on pages written from now on. Older pages do not carry one -and have not been retrofitted with one, because attaching a provenance note to a page without first -establishing what is actually true of it would be a guess rather than a disclosure. +New or substantially rewritten pages carry a short note linking to the section here that describes +how they were made. Older pages receive a note only after their provenance has been established. +The absence of a note does not mean a page was written without AI assistance. --- -*This page was written by an AI agent from the [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base) and reviewed by the author — see [Documentation and reference pages](#documentation-and-reference-pages).* +*This page was written and revised by an AI agent using the +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base). See +[Documentation and reference pages](#documentation-and-reference-pages).* diff --git a/docs/ai/skills/index.md b/docs/ai/skills/index.md index aac6d9cf..b44715fb 100644 --- a/docs/ai/skills/index.md +++ b/docs/ai/skills/index.md @@ -4,57 +4,54 @@ sidebar_position: 1 # CGP's Agent Skill -CGP publishes an [agent skill](https://agentskills.io/): a set of Markdown files that teach an LLM -coding assistant how to read, write, and debug CGP code. It lives in the -[**cgp-skills** repository](https://github.com/contextgeneric/cgp-skills), and the pages in this -section are that skill, published here unchanged. +CGP's agent skill teaches coding assistants how to read, write, and debug CGP code. It is a set of +Markdown instructions in the [cgp-skills repository](https://github.com/contextgeneric/cgp-skills). +The pages in this section publish a snapshot of those files without changing their content. ## What it is for -An assistant that has not met CGP treats it as ordinary Rust and gets the wiring wrong: it reaches for -a plain trait impl where a provider belongs, or writes a `delegate_components!` table it cannot then -explain. The skill supplies the missing vocabulary — consumer and provider traits, wiring, impl-side -dependencies — along with the code each macro expands to and how to read the errors CGP produces. +The skill gives an assistant the CGP vocabulary and patterns it needs to work with the library. +It explains consumer and provider traits, component wiring, implementation dependencies, macro +expansions, and compiler errors. Without that guidance, an assistant may write a plain trait +implementation where a provider is needed or produce incorrect wiring. -That is a narrow claim, and it is worth keeping narrow. The skill teaches the assistant, not you. It -does not make CGP simpler, and an assistant using it still writes code you have to review. +You still need to review the assistant's code. The skill supplies instructions and examples; it +does not guarantee correct output or replace your understanding of the application. ## Using it -The quickest way is to hand your assistant the main file. Download -[`SKILL.md`](https://raw.githubusercontent.com/contextgeneric/cgp-skills/refs/heads/main/cgp/SKILL.md) -and attach it to the context window of whichever model you use. +For a first look, download +[SKILL.md](https://raw.githubusercontent.com/contextgeneric/cgp-skills/refs/heads/main/cgp/SKILL.md) +and attach it to your assistant's conversation. The file introduces the core model and identifies +the reference files needed for particular tasks. Make those files available when the assistant needs +their detailed rules and examples. -For everyday work, install the whole skill rather than the one file. Clone the repository and point -your assistant's skills directory at it, so the sub-skills load on demand instead of all at once: +For ongoing work, download the complete skill so the assistant can open its references as needed. +Clone the repository: ```sh git clone https://github.com/contextgeneric/cgp-skills.git ``` -The layout follows the convention the tooling expects: `cgp/SKILL.md` is the entry point, and -`cgp/references/` holds one file per area — components, wiring, checking, handlers, and the rest. The -entry point is a complete primer on its own, and it tells the assistant which reference to open for -the construct in front of it. +Install the `cgp/` directory using your assistant's skill-loading instructions. Keep `cgp/SKILL.md` +and `cgp/references/` together so the relative links resolve. Cloning the repository downloads the +files; your assistant's setup determines how it discovers and loads them. ## Reading it yourself -Nothing stops you, and the skill is written plainly enough to follow. But it is written *for a machine -reader*: it is dense, it repeats itself where repetition helps an assistant, and it assumes a reader -who wants exhaustive rules rather than a gentle path through them. - -If you are learning CGP, the [Tutorials](/docs/tutorials/hello) start from a working program and the -[Concepts](/docs/concepts) pages take one idea at a time. Come back here when you want to see exactly -what your assistant has been told. +The [tutorials](/docs/tutorials/hello) and [Concepts](/docs/concepts) pages are the starting points +for learning CGP. The skill is written for an assistant that needs dense rules and worked examples +for a specific task. Read it when you want that detail or want to see the instructions your +assistant receives. ## What is published here -The pages below are the skill's own files, served from the `cgp-skills` repository as a submodule -pinned to one revision. Nothing here is retyped or summarised — a page is the skill's own bytes — but it -is a *snapshot*, and the repository moves first. Treat the repository as canonical, and raise any issue -or correction there. +The skill pages on this site are pinned to a particular repository revision. The repository may +contain newer changes, so use it as the authoritative source and report skill corrections there. +The site provides a place to browse the published snapshot; the repository supplies the files to +install. --- -*This page was written by an AI agent from the CGP knowledge base — see +*This page was written and revised by an AI agent using the CGP knowledge base. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/index.md b/docs/index.md index 99176583..7c55198a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -2,75 +2,67 @@ sidebar_position: 1 --- - # Introduction -Context-Generic Programming (CGP) is a modular programming paradigm that enables you to bypass the **coherence restrictions** in Rust traits, allowing for **overlapping** and **orphan** implementations of any CGP trait. - -You can adapt almost any existing Rust trait to use CGP today by applying the `#[cgp_component]` macro to the trait definition. After this annotation, you can write **named** implementations of the trait using `#[cgp_impl]`, which can be defined without being constrained by the coherence rules. You can then selectively enable and reuse the named implementation for your type using the `delegate_components!` macro. +Context-Generic Programming (CGP) is a language extension for Rust, with pluggable trait +implementations at compile-time. You can define several implementations of an interface and choose +which one each application uses. CGP is a library on stable Rust: its macros generate ordinary traits +and implementations, and the compiler resolves the choices into direct calls. -For instance, we can, in principle, annotate the standard library’s [`Hash`](https://doc.rust-lang.org/std/hash/trait.Hash.html) trait with `#[cgp_component]` like this: +For example, an application can send email through a mail server while a test records messages in +memory. Both use the same interface, and the code that calls it stays the same. Each application type +chooses its implementation separately. -```rust -#[cgp_component(HashProvider)] -pub trait Hash { ... } -``` +CGP calls the type that holds these choices a **context**, and a named implementation a **provider**. +In the email example, the context represents the application and holds any state its providers need. +Wiring selects a provider for each component, the interface whose implementation you want to choose. +The [consumer and provider traits](/docs/concepts/consumer-and-provider-traits) explanation shows +how this separation works. -This change does not affect existing code that uses or implements `Hash`, but it allows for new, potentially overlapping implementations, such as one that works for any type that also implements `Display`: +You can adopt CGP one component at a time. A consumer trait remains an ordinary Rust trait that you +can implement directly. Providers and wiring become useful when you need interchangeable +implementations or want to reuse an implementation across contexts. The +[Overview](/docs/overview) covers those capabilities, along with abstract types, extensible data, and +composable handlers. -```rust -#[cgp_impl(HashWithDisplay)] -impl HashProvider -where - Self: Display, -{ ... } -``` +## Current Status -You can then apply and reuse this implementation on any type by using the `delegate_components!` macro: +CGP is in active development, with a young ecosystem and limited community support. Learning its +patterns takes time, and compiler errors can be difficult to interpret. If you adopt it for a +mission-critical project, expect to investigate problems yourself when the available documentation +and support do not cover your case. -```rust -pub struct MyData { ... } -impl Display for MyData { ... } +[cargo-cgp](/docs/cargo-cgp) helps diagnose wiring errors by naming their root cause and showing the +dependency chain. The tool is an early pre-release and rewrites the error classes it recognizes; +other diagnostics retain the compiler's wording. CGP also publishes an +[agent skill](/docs/ai/skills) to help coding assistants read, write, and debug CGP code. You still +need to review the code an assistant produces. -delegate_components! { - MyData { - HashProviderComponent: HashWithDisplay, - } -} -``` +Start with a small part of your project whose implementation choices already vary. For a capability +with one implementation, a plain trait may be enough. CGP particularly welcomes +[early adopters and contributors](/docs/contribute) who want to experiment and help improve the +library, tools, and documentation. -In this example, `MyData` implements the `Hash` trait by using `delegate_components!` to delegate its implementation to the `HashWithDisplay` provider, identified by the key `HashProviderComponent`. Because `MyData` already implements `Display`, the `Hash` trait is now automatically implemented through CGP via this delegation. - ---- +## Getting Started -# Current Status +Start with the [Hello World tutorial](/docs/tutorials/hello) for a short working example. Continue +with the [area-calculation series](/docs/tutorials/area-calculation) to learn how ordinary Rust +functions develop into components and providers. -As of 2025, it is important to note that CGP remains in its **formative, early stages** of active development. While the potential is genuinely promising, it still has several inevitable rough edges, particularly in key areas such as comprehensive documentation, mature tooling, streamlined debugging techniques, robust community support, and overall ecosystem maturity. +Use the documentation according to the question you need to answer: -Consequently, embracing CGP for your mission-critical, serious projects comes with inherent challenges, and you should be advised to proceed **at your own discretion and risk**. The primary risk you face is not strictly technical, but rather stems from the current limited support available when you inevitably encounter difficulties while learning or attempting to apply CGP in production. +- [Overview](/docs/overview): what CGP offers and where it helps. +- [Concepts](/docs/concepts): how its ideas work and fit together. +- [Reference](/docs/reference): the syntax and behavior of individual constructs. +- [Resources](/docs/resources): libraries, projects, talks, and further reading. -At this pioneering stage, CGP is an ideal fit for [**early adopters and enthusiastic potential contributors**](/docs/contribute/) who are eager to experiment with the paradigm and actively help to shape its powerful future. +The [Context-Generic Programming Patterns book](https://patterns.contextgeneric.dev/) develops CGP +from first principles. It is useful for understanding the underlying patterns, but its examples do +not consistently match the current library. Use the maintained tutorials and reference when writing +new code. The [blog](/blog) records releases, design discussions, and talks; older posts describe +the library as it was when they were published. --- -# Getting Started - -Even though the CGP project is officially still less than one year old, some of the initial documentation and resources you might find have already become slightly outdated, or they have been gracefully superseded by more intuitive and modern patterns. Nevertheless, this section is an attempt to provide you with the very best and most current guidance on how you can effectively begin to learn more about CGP. - -## Blog Posts - -The most accurate and up-to-date resources concerning CGP are currently available in the form of our [blog posts](/blog). Specifically, we recommend that the blog posts starting from the [**v0.7.0 release onward**](/blog/v0.7.0-release) will give you a significantly more concise and modern explanation of what CGP is all about. - -## Hello World Tutorial - -The hands-on [Hello World Tutorial](/docs/tutorials/hello) provides a high-level and clear walkthrough of various fundamental CGP features by using a familiar, simple hello-world style example. - -## Book - -If your preference is to rigorously understand CGP from its **first principles**, without relying on the specific implementations within the [`cgp` crate](https://github.com/contextgeneric/cgp), your best approach is to dive into our comprehensive book, [Context-Generic Programming Patterns](https://patterns.contextgeneric.dev/). This resource provides a deep, thorough guide to understanding the complex inner workings of CGP. - -Please note that this book has not been updated for a while, and you might consider skipping the book entirely if your primary goal is to start using CGP quickly with the absolute minimal learning curve! - -## Resources - -Make sure to check out the dedicated [Resources](/docs/resources) page, which contains more supplementary materials and various learning tools to help you get up to speed with CGP. +*This page was revised by an AI agent using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/overview.md b/docs/overview.md index fa64f6b1..71e95c3f 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -4,86 +4,178 @@ sidebar_position: 2 # Overview -This page provides a quick overview and highlight the key features of CGP. For a deeper dive into the concepts and patterns of CGP, explore our comprehensive book, [Context-Generic Programming Patterns](https://patterns.contextgeneric.dev/). +CGP lets you choose trait implementations at compile time and reuse application logic across those +choices. This page explains its main capabilities, the problems they address, and the trade-offs to +consider. Each section links to a fuller explanation; for a working example, start with the +[Hello World tutorial](/docs/tutorials/hello). -# Key Features +## Key Features -This section highlights some of the key advantages that Context-Generic Programming (CGP) offers. +CGP builds on Rust's traits and associated types to separate reusable logic from the concrete choices +an application makes. A **context** is the type that holds those choices. A **provider** is a named +implementation, and wiring selects the provider for each component interface. -## Modular Component System +### One Interface, Many Implementations -CGP leverages Rust's powerful trait system to define generic component _interfaces_ that decouple the code that _consumes_ an interface from the code that _implements_ it. This is achieved by introducing: +CGP lets several implementations of the same interface coexist, even when they apply to the same +types. Each context selects the implementation it needs. For example, a production application can +send email while a test application records messages, with both exposing the same interface to +callers. -- **Provider traits**, which define the implementation of a component interface. -- **Consumer traits**, which specify how a component interface is consumed. +CGP separates the trait callers use, the consumer trait, from the provider trait that named +implementations implement. Each provider uses its own marker type, so the implementations remain +distinct under Rust's coherence rules. Read +[consumer and provider traits](/docs/concepts/consumer-and-provider-traits) for the mechanism and +[coherence](/docs/concepts/coherence) for the rules it works within. -By separating provider traits from consumer traits, CGP enables multiple context-generic provider implementations to coexist. This approach circumvents Rust's usual limitation on overlapping or orphaned trait implementations, offering greater flexibility and modularity. +### Zero-Cost Abstraction -## Highly Expressive Macros +The compiler resolves CGP wiring into statically dispatched calls. Selecting a provider does not +require a runtime registry, reflection, or a virtual method table. The implementation you select +still has its own runtime costs, and generic composition can increase compilation time and generated +code size. -CGP empowers developers to write _abstract programs_ that are generic over a context, including all its associated types and methods. This capability eliminates the need to explicitly specify an extensive list of generic parameters in type signatures, streamlining code structure and readability. +### Type-Safe Wiring -Additionally, CGP offers powerful _macros_ for defining component interfaces and simplifies the process of wiring component implementations for use with a specific context. +Rust checks that a selected provider satisfies the requirements of the code using it. Missing +dependencies become compile errors when the component is used or explicitly checked. Wiring alone +does not force that verification, so use +[check traits](/docs/concepts/check-traits) to check a context's components where you assemble them. -With CGP, Rust code can achieve a level of expressiveness comparable to, if not exceeding, that of other popular programming paradigms, such as object-oriented programming and dynamically typed programming. +These checks establish that components fit together; they do not prove application logic correct. +[cargo-cgp](/docs/cargo-cgp) helps explain wiring failures by showing the root cause and dependency +chain. It is an early pre-release and does not rewrite every kind of compiler error. -## Type-Safe Composition +### Abstract Over Every Dependency -CGP leverages Rust's robust type system to guarantee that all component wiring is _type-safe_, ensuring that any missing dependencies are caught at compile time. It operates entirely within safe Rust, avoiding dynamic typing techniques such as `dyn traits`, `Any`, or runtime reflection. +CGP lets reusable logic state the capabilities it needs while each application supplies concrete +implementations. Those choices can include I/O, storage, error handling, and runtime operations. +Providers declare their requirements where they use them, through +[impl-side dependencies](/docs/concepts/impl-side-dependencies). -This strict adherence to type safety ensures that no CGP-specific errors can occur during application runtime, providing developers with greater confidence in their code's reliability. +Keeping platform dependencies behind these interfaces can make the shared logic usable in `no_std` +environments. CGP itself supports `no_std`, but portability also depends on the providers and other +dependencies you select. A provider that requires an operating-system service still needs that +service on its target platform. -## No-Std Friendly +### Still Ordinary Rust -CGP enables the creation of _fully abstract programs_ that can be defined without relying on any concrete dependencies — except for other abstract CGP components. This abstraction extends to dependencies such as I/O, runtime, cryptographic operations, and encoding schemes, allowing these concerns to be separated from the core application logic. +CGP's macros generate ordinary Rust traits and implementations that compile on stable Rust. You can +implement a consumer trait directly, introduce providers where you need them, and keep the rest of +your project unchanged. Contexts can contain ordinary generic types, enums, and trait objects. -As a result, the core logic of an application can be seamlessly instantiated with specialized dependencies, making it compatible with no-std environments. These include embedded systems, operating system kernels, sandboxed environments like WebAssembly, and symbolic execution platforms such as Kani. +The additional structure has a cost: you need to learn the provider model and maintain the wiring. +For an interface with a single implementation, an ordinary trait often supplies all the abstraction +you need. The [modularity hierarchy](/docs/concepts/modularity-hierarchy) explains how to choose the +amount of separation your code needs. -## Zero-Cost Abstraction +### Abstract Types -CGP operates entirely at compile-time, leveraging Rust's type system to ensure correctness without introducing runtime overhead. This approach upholds Rust's hallmark of _zero-cost abstraction_, enabling developers to use CGP's features without sacrificing runtime performance. +An abstract type lets each context choose a concrete type, such as its error type, without passing +that choice as a separate generic parameter through every layer. Code names the associated type +where it needs it. A caller that only invokes a capability can depend on that capability without +listing the types used inside its implementation. +These are Rust associated types, so their guarantees depend on the bounds you declare. Using `f64` +for both a distance and a weight does not create distinct concrete types or enforce units. Use +newtypes when you need that distinction. See [abstract types](/docs/concepts/abstract-types). -# Problems Solved +### Extensible Records and Variants -Here are some common problems in Rust that CGP helps to address. +CGP lets generic code build records by field and handle enums by variant. Types opt in through +derives that expose their structure to the trait system. A library can then assemble records from +independent field providers or combine handlers for the variants an application uses. -## Error Handling +The compiler checks this composition against the selected types. It does not discover new fields or +variants at runtime. Read [extensible records](/docs/concepts/extensible-records), +[extensible variants](/docs/concepts/extensible-variants), and +[dispatching](/docs/concepts/dispatching) for the patterns and their limits. -Rather than being tied to a specific error crate like `anyhow` or `eyre`, CGP's `HasErrorType` and `CanRaiseError` traits allow the decoupling of core application logic from error handling. This enables concrete applications to choose their preferred error library and select the error-handling strategy that best suits their needs, such as deciding whether or not to include stack traces in errors. +### Composable Handlers -For more detailed information on error handling, refer to the [error handling chapter](https://patterns.contextgeneric.dev/error-handling.html) in our book +CGP provides components for synchronous, asynchronous, fallible, and infallible computations. +Providers can implement individual steps and combine them into a pipeline whose adjacent input and +output types must agree. An application chooses the steps through its wiring. -## Async Runtime +The [handler family](/docs/concepts/handlers) covers these interfaces and their composition. Ordinary +function calls remain a simpler choice when a sequence has no need for interchangeable steps. -Rather than committing to a specific runtime crate like `tokio` or `async-std`, CGP enables the application core logic to rely on an abstract runtime context that provides only the features required by the application. +## Problems Solved -Unlike monolithic runtime traits, an abstract runtime context in CGP does _not_ require a comprehensive or upfront design of all possible runtime features any application might need. This flexibility allows easy switching between concrete runtime implementations, depending on the specific runtime features the application utilizes. +CGP is most useful when a program already needs several implementations or dependency choices. The +following cases show how its capabilities address those needs. -## Overlapping Implementations +### Error Handling -A common frustration among Rust programmers is the restriction on overlapping trait implementations. A typical workaround is to use newtype wrappers, but this can become cumbersome when dealing with multiple composite types that need to be extended. +Reusable logic can return errors without committing to a particular error library. `HasErrorType` +supplies the context's error type, and `CanRaiseError` converts a source error into it. An application +chooses both the error representation and the conversion behavior, allowing the same logic to use a +custom error enum or a general-purpose error library. -Rust requires a crate to own either the type or the trait for a trait implementation, which often places a significant burden on the author of a new type to implement all the common traits their users might need. This can lead to bloated type definitions, with excessive trait implementations such as `Eq`, `Clone`, `TryFrom`, `Hash`, and `Serialize`. Despite careful design, libraries may still face requests from users to implement less common traits, which can only be implemented by the crate that owns the type. +Changing the error type also requires compatible conversion providers. CGP makes those choices +explicit; it does not invent conversions between arbitrary errors. See +[modular error handling](/docs/concepts/modular-error-handling). -With the introduction of _provider traits_, CGP removes these restrictions on overlapping implementations. Both the owner and non-owners of a type can define custom implementations for that type. When multiple provider implementations are available, users can choose one and wire it up easily using CGP constructs. +### Async Runtime -CGP also favors the use of _abstract types_ over newtype wrappers. For instance, a type like `f64` can be directly used for both `Context::Distance` and `Context::Weight`, with the associated types still treated as distinct within the abstract code. CGP also enables specialized provider implementations, even if the crate does not own the primitive type (e.g., `f64`) or the provider trait. +Application logic can depend on the runtime operations it uses without naming a particular executor. +For example, a provider that needs a timer can require a timer capability, leaving the application to +supply its implementation. Another application can reuse that provider with a different compatible +timer implementation. -## Dynamic Dispatch +Changing runtimes requires providers for the operations the application needs, with compatible types +and behavior. It can also require attention to +[`Send` bounds](/docs/concepts/send-bounds) when futures move between threads. CGP separates these +choices but does not make runtime APIs interchangeable by itself. -A common approach for newcomers to support polymorphism in Rust is to use dynamic dispatch with `dyn Trait` objects. However, this severely limits the functionality to a restricted subset of _dyn-compatible_ (object-safe) features in Rust. Often, this limitation spreads throughout the entire codebase, requiring non-trivial workarounds for non-dyn-compatible constructs, such as `Clone`. +### Overlapping Implementations -Even when dynamic dispatch is not used, many Rust programmers rely on ad-hoc polymorphism, defining enums to represent all potential variants of types in the application. This results in numerous `match` expressions scattered across the codebase, making it difficult to decouple logic for each branch. Additionally, adding new variants to the enum becomes challenging, as every branch must be updated, even when the new variant is only used in a small portion of the code. +Rust rejects blanket implementations that could apply to the same type, even when different +applications want different choices. CGP gives each implementation a provider name and makes the +choice explicit in the context's wiring. A crate can also implement a provider trait for its own +provider type even when the trait and the data being handled come from other crates. -CGP provides several solutions to address the dynamic dispatch problem by delegating the "assembly" of the variant collection to the concrete context. The core application logic can be written generically over the context and the associated type representing the abstract enum. CGP also facilitates powerful datatype-generic patterns that allow providers for each variant to be implemented separately and combined to work with enums that contain any combination of variants. +This applies to interfaces that support CGP. It does not let you add arbitrary implementations of +unchanged foreign traits, such as the standard library's `Hash`, to foreign types. The +[coherence explanation](/docs/concepts/coherence) shows how providers stay within Rust's rules. -## Monolithic Traits +### Dynamic Dispatch -Even without CGP, Rust's trait system provides powerful mechanisms for building abstractions that would be difficult to achieve in other mainstream languages. One common best practice is to write abstract code that is generic over a context type, but this often involves an implicit trait bound tied directly to the generic context. +CGP offers static composition when an application's implementation choices are known at build time. +For enum-based designs, it can combine separate variant handlers so generic logic works across enums +containing different sets of variants. This lets each handler be reused without duplicating its +logic in every matching operation. -Unlike CGP, traits in this pattern are typically designed as monolithic, encompassing all the dependencies that the core application might need. Without CGP, an abstract caller must also include all trait bounds required by the generic functions it invokes. As a result, any additional generic trait bounds tend to propagate throughout the codebase, leading developers to combine all these trait bounds into one monolithic trait for convenience. +Runtime choices can still use enums or `dyn Trait` inside a CGP context. A program that loads +implementations dynamically needs a runtime mechanism for doing so. CGP's +[dispatching](/docs/concepts/dispatching) selects the composition at compile time; an enum's active +variant is still determined at runtime. -Monolithic traits can quickly become bottlenecks that prevent large projects from scaling. It's not uncommon for such traits to become bloated with dozens or even hundreds of methods and types. This overgrowth makes it increasingly difficult to introduce new implementations or modify existing ones. Additionally, with Rust's current practices, breaking down or decoupling these monolithic traits into smaller, more manageable traits can be challenging. +### Monolithic Traits -CGP offers significant improvements over this traditional pattern, making it possible to write abstract Rust code without the risk of creating unwieldy, monolithic traits. CGP enables the decomposition of large traits into many small, focused traits, each ideally consisting of just a single method or type. This is made possible by the dependency injection pattern used in CGP, which allows implementations to introduce only the minimal trait bounds they need directly within the implementation, rather than bundling everything into a single, monolithic structure. +A large trait can force every implementation to supply capabilities it never uses. CGP lets you +split independently chosen behavior into smaller components, each with its own providers. A +provider declares the dependencies its implementation needs, while callers depend on the interface +they use. + +Group methods and associated types when one implementation choice should decide them together. +Splitting every item into a separate component adds wiring without necessarily improving reuse. +See [impl-side dependencies](/docs/concepts/impl-side-dependencies) and the +[modularity hierarchy](/docs/concepts/modularity-hierarchy). + +### Generic Parameters Through Every Layer + +An error type, runtime, and storage backend can become generic parameters that intermediate code +must repeat even when it only forwards a call. CGP lets the context select those types and expose +the required operations as capabilities. Intermediate code can then name the capability it calls, +while the implementation names the dependencies it actually uses. + +Types that appear in an interface, such as a returned error, still belong in that interface. +[Abstract types](/docs/concepts/abstract-types) reduce repeated parameters; they do not remove the +need to state type relationships. For a function with one or two independent type parameters, +ordinary generics may be clearer. + +--- + +*This page was revised by an AI agent using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* From a5ce79835612461fa19c9d7da8ca0b0568b85146 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 14 Sep 2026 09:45:54 +0000 Subject: [PATCH 072/516] Standardize AI disclosure footers across website pages Use direct, consistent wording in all 223 existing footers while preserving authorship distinctions, verification claims, and disclosure links. Co-Authored-By: GPT-6 --- docs/ai/disclaimer.md | 2 +- docs/ai/skills/index.md | 2 +- docs/cargo-cgp/check.md | 4 ++-- docs/cargo-cgp/expand.md | 4 ++-- docs/cargo-cgp/index.md | 5 +++-- docs/cargo-cgp/installation.md | 4 ++-- docs/cargo-cgp/troubleshooting.md | 2 +- docs/concepts/abstract-types.md | 4 +++- docs/concepts/aggregate-providers.md | 4 +++- docs/concepts/check-traits.md | 4 +++- docs/concepts/coherence.md | 4 +++- docs/concepts/consumer-and-provider-traits.md | 4 +++- docs/concepts/dispatching.md | 4 +++- docs/concepts/extensible-records.md | 4 +++- docs/concepts/extensible-variants.md | 4 +++- docs/concepts/handlers.md | 4 +++- docs/concepts/higher-order-providers.md | 4 +++- docs/concepts/impl-side-dependencies.md | 4 +++- docs/concepts/implicit-arguments.md | 4 +++- docs/concepts/index.md | 4 +++- docs/concepts/modular-error-handling.md | 4 +++- docs/concepts/modularity-hierarchy.md | 4 +++- docs/concepts/monadic-handlers.md | 4 +++- docs/concepts/namespaces.md | 4 +++- docs/concepts/send-bounds.md | 4 +++- docs/concepts/type-level-dsls.md | 4 +++- docs/index.md | 2 +- docs/overview.md | 2 +- docs/reference/attributes/default_impl.md | 4 +++- docs/reference/attributes/derive_delegate.md | 4 +++- docs/reference/attributes/extend.md | 4 +++- docs/reference/attributes/extend_where.md | 4 +++- docs/reference/attributes/impl_generics.md | 4 +++- docs/reference/attributes/implicit.md | 4 +++- docs/reference/attributes/prefix.md | 4 +++- docs/reference/attributes/use_provider.md | 4 +++- docs/reference/attributes/use_type.md | 4 +++- docs/reference/attributes/uses.md | 4 +++- docs/reference/components/can_raise_error.md | 4 +++- docs/reference/components/can_wrap_error.md | 4 +++- docs/reference/components/handler/async_computer.md | 4 +++- docs/reference/components/handler/async_computer_ref.md | 4 +++- docs/reference/components/handler/computer.md | 4 +++- docs/reference/components/handler/computer_ref.md | 4 +++- docs/reference/components/handler/handler.md | 4 +++- docs/reference/components/handler/handler_ref.md | 4 +++- docs/reference/components/handler/index.md | 4 +++- docs/reference/components/handler/producer.md | 4 +++- docs/reference/components/handler/try_computer.md | 4 +++- docs/reference/components/handler/try_computer_ref.md | 4 +++- docs/reference/components/has_error_type.md | 4 +++- docs/reference/components/has_runtime.md | 4 +++- docs/reference/components/has_runtime_type.md | 4 +++- docs/reference/components/has_type.md | 4 +++- docs/reference/components/index.md | 4 +++- docs/reference/components/runner.md | 4 +++- docs/reference/components/send_runner.md | 4 +++- docs/reference/derives/derive_build_field.md | 4 +++- docs/reference/derives/derive_cgp_data.md | 4 +++- docs/reference/derives/derive_cgp_record.md | 4 +++- docs/reference/derives/derive_cgp_variant.md | 4 +++- docs/reference/derives/derive_extract_field.md | 4 +++- docs/reference/derives/derive_from_variant.md | 4 +++- docs/reference/derives/derive_has_field.md | 4 +++- docs/reference/derives/derive_has_fields.md | 4 +++- docs/reference/errors.md | 4 +++- docs/reference/index.md | 4 +++- docs/reference/macros/async_trait.md | 4 +++- docs/reference/macros/blanket_trait.md | 4 +++- docs/reference/macros/cgp_auto_dispatch.md | 4 +++- docs/reference/macros/cgp_auto_getter.md | 4 +++- docs/reference/macros/cgp_component.md | 4 +++- docs/reference/macros/cgp_computer.md | 4 +++- docs/reference/macros/cgp_fn.md | 4 +++- docs/reference/macros/cgp_getter.md | 4 +++- docs/reference/macros/cgp_impl.md | 4 +++- docs/reference/macros/cgp_namespace.md | 4 +++- docs/reference/macros/cgp_producer.md | 4 +++- docs/reference/macros/cgp_provider.md | 4 +++- docs/reference/macros/cgp_type.md | 4 +++- docs/reference/macros/check_components.md | 4 +++- docs/reference/macros/delegate_and_check_components.md | 4 +++- docs/reference/macros/delegate_components.md | 4 +++- docs/reference/macros/path.md | 4 +++- docs/reference/macros/product.md | 4 +++- docs/reference/macros/sum.md | 4 +++- docs/reference/macros/symbol.md | 4 +++- docs/reference/providers/chain_getters.md | 4 +++- docs/reference/providers/dispatch/build_and_merge.md | 4 +++- docs/reference/providers/dispatch/build_and_merge_outputs.md | 4 +++- docs/reference/providers/dispatch/build_and_set_field.md | 4 +++- docs/reference/providers/dispatch/build_with_handlers.md | 4 +++- docs/reference/providers/dispatch/downcast_and_handle.md | 4 +++- .../reference/providers/dispatch/extract_field_and_handle.md | 4 +++- docs/reference/providers/dispatch/handle_field_value.md | 4 +++- docs/reference/providers/dispatch/index.md | 4 +++- .../providers/dispatch/match_first_with_handlers.md | 4 +++- .../providers/dispatch/match_with_field_handlers.md | 4 +++- docs/reference/providers/dispatch/match_with_handlers.md | 4 +++- .../providers/dispatch/match_with_value_handlers.md | 4 +++- docs/reference/providers/error/debug_error.md | 4 +++- docs/reference/providers/error/discard_detail.md | 4 +++- docs/reference/providers/error/display_error.md | 4 +++- docs/reference/providers/error/index.md | 4 +++- docs/reference/providers/error/panic_on_error.md | 4 +++- docs/reference/providers/error/raise_from.md | 4 +++- docs/reference/providers/error/raise_infallible.md | 4 +++- docs/reference/providers/error/return_error.md | 4 +++- docs/reference/providers/handler/compose_handlers.md | 4 +++- docs/reference/providers/handler/index.md | 4 +++- docs/reference/providers/handler/pipe_handlers.md | 4 +++- docs/reference/providers/handler/promote.md | 4 +++- docs/reference/providers/handler/promote_async.md | 4 +++- docs/reference/providers/handler/promote_async_computer.md | 4 +++- docs/reference/providers/handler/promote_computer.md | 4 +++- docs/reference/providers/handler/promote_handler.md | 4 +++- docs/reference/providers/handler/promote_producer.md | 4 +++- docs/reference/providers/handler/promote_ref.md | 4 +++- docs/reference/providers/handler/promote_try_computer.md | 4 +++- docs/reference/providers/handler/return_input.md | 4 +++- docs/reference/providers/handler/try_promote.md | 4 +++- docs/reference/providers/handler/use_input_delegate.md | 4 +++- docs/reference/providers/index.md | 4 +++- docs/reference/providers/monad/bind_err.md | 4 +++- docs/reference/providers/monad/bind_ok.md | 4 +++- docs/reference/providers/monad/index.md | 4 +++- docs/reference/providers/monad/pipe_monadic.md | 4 +++- docs/reference/providers/redirect_lookup.md | 4 +++- docs/reference/providers/use_context.md | 4 +++- docs/reference/providers/use_default.md | 4 +++- docs/reference/providers/use_delegate.md | 4 +++- docs/reference/providers/use_delegated_type.md | 4 +++- docs/reference/providers/use_field.md | 4 +++- docs/reference/providers/use_field_ref.md | 4 +++- docs/reference/providers/use_fields.md | 4 +++- docs/reference/providers/use_type.md | 4 +++- docs/reference/providers/with_context.md | 4 +++- docs/reference/providers/with_delegated_type.md | 4 +++- docs/reference/providers/with_field.md | 4 +++- docs/reference/providers/with_field_ref.md | 4 +++- docs/reference/providers/with_provider.md | 4 +++- docs/reference/providers/with_type.md | 4 +++- docs/reference/traits/builder/build_field.md | 4 +++- docs/reference/traits/builder/finalize_build.md | 4 +++- docs/reference/traits/builder/has_builder.md | 4 +++- docs/reference/traits/builder/index.md | 4 +++- docs/reference/traits/builder/into_builder.md | 4 +++- docs/reference/traits/builder/partial_data.md | 4 +++- docs/reference/traits/builder/take_field.md | 4 +++- docs/reference/traits/builder/update_field.md | 4 +++- docs/reference/traits/casting/can_build_from.md | 4 +++- docs/reference/traits/casting/can_downcast.md | 4 +++- docs/reference/traits/casting/can_downcast_fields.md | 4 +++- docs/reference/traits/casting/can_upcast.md | 4 +++- docs/reference/traits/casting/index.md | 4 +++- docs/reference/traits/field-access/field_getter.md | 4 +++- docs/reference/traits/field-access/field_mapper.md | 4 +++- docs/reference/traits/field-access/has_field.md | 4 +++- docs/reference/traits/field-access/has_field_mut.md | 4 +++- docs/reference/traits/field-access/index.md | 4 +++- docs/reference/traits/field-access/map_field.md | 4 +++- docs/reference/traits/field-access/mut_field_getter.md | 4 +++- docs/reference/traits/formatting/concat_path.md | 4 +++- docs/reference/traits/formatting/index.md | 4 +++- docs/reference/traits/formatting/static_format.md | 4 +++- docs/reference/traits/formatting/static_string.md | 4 +++- docs/reference/traits/index.md | 4 +++- docs/reference/traits/monad/contains_value.md | 4 +++- docs/reference/traits/monad/index.md | 4 +++- docs/reference/traits/monad/lift_value.md | 4 +++- docs/reference/traits/monad/monadic_bind.md | 4 +++- docs/reference/traits/monad/monadic_trans.md | 4 +++- docs/reference/traits/namespace/default_impls1.md | 4 +++- docs/reference/traits/namespace/default_impls2.md | 4 +++- docs/reference/traits/namespace/default_namespace.md | 4 +++- docs/reference/traits/namespace/index.md | 4 +++- docs/reference/traits/optional/can_build_with_default.md | 4 +++- docs/reference/traits/optional/can_finalize_with_default.md | 4 +++- docs/reference/traits/optional/finalize_optional.md | 4 +++- docs/reference/traits/optional/has_optional_builder.md | 4 +++- docs/reference/traits/optional/index.md | 4 +++- docs/reference/traits/optional/set_optional.md | 4 +++- docs/reference/traits/optional/to_optional.md | 4 +++- docs/reference/traits/optional/transform_map_default.md | 4 +++- docs/reference/traits/optional/transform_optional.md | 4 +++- docs/reference/traits/shape/from_fields.md | 4 +++- docs/reference/traits/shape/has_fields.md | 4 +++- docs/reference/traits/shape/has_fields_ref.md | 4 +++- docs/reference/traits/shape/index.md | 4 +++- docs/reference/traits/shape/to_fields.md | 4 +++- docs/reference/traits/shape/to_fields_ref.md | 4 +++- docs/reference/traits/type-level/append_product.md | 4 +++- docs/reference/traits/type-level/concat_product.md | 4 +++- docs/reference/traits/type-level/index.md | 4 +++- docs/reference/traits/type-level/map_fields.md | 4 +++- docs/reference/traits/type-level/map_type.md | 4 +++- docs/reference/traits/type-level/map_type_ref.md | 4 +++- docs/reference/traits/type-level/transform_map.md | 4 +++- docs/reference/traits/type-level/transform_map_fields.md | 4 +++- docs/reference/traits/variant/extract_field.md | 4 +++- docs/reference/traits/variant/finalize_extract.md | 4 +++- docs/reference/traits/variant/finalize_extract_result.md | 4 +++- docs/reference/traits/variant/from_variant.md | 4 +++- docs/reference/traits/variant/has_extractor.md | 4 +++- docs/reference/traits/variant/has_extractor_mut.md | 4 +++- docs/reference/traits/variant/has_extractor_ref.md | 4 +++- docs/reference/traits/variant/index.md | 4 +++- docs/reference/traits/wiring/can_use_component.md | 4 +++- docs/reference/traits/wiring/delegate_component.md | 4 +++- docs/reference/traits/wiring/index.md | 4 +++- docs/reference/traits/wiring/is_provider_for.md | 4 +++- docs/reference/types/chars.md | 4 +++- docs/reference/types/cons.md | 4 +++- docs/reference/types/either.md | 4 +++- docs/reference/types/field.md | 4 +++- docs/reference/types/index.md | 4 +++- docs/reference/types/index_type.md | 4 +++- docs/reference/types/life.md | 4 +++- docs/reference/types/mref.md | 4 +++- docs/reference/types/nil.md | 4 +++- docs/reference/types/path_cons.md | 4 +++- docs/reference/types/phantom_data.md | 4 +++- docs/reference/types/void.md | 4 +++- 223 files changed, 656 insertions(+), 227 deletions(-) diff --git a/docs/ai/disclaimer.md b/docs/ai/disclaimer.md index 5e4c3460..124949dc 100644 --- a/docs/ai/disclaimer.md +++ b/docs/ai/disclaimer.md @@ -99,6 +99,6 @@ The absence of a note does not mean a page was written without AI assistance. --- -*This page was written and revised by an AI agent using the +*An AI agent wrote and revised this page using the [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base). See [Documentation and reference pages](#documentation-and-reference-pages).* diff --git a/docs/ai/skills/index.md b/docs/ai/skills/index.md index b44715fb..4b136c12 100644 --- a/docs/ai/skills/index.md +++ b/docs/ai/skills/index.md @@ -53,5 +53,5 @@ install. --- -*This page was written and revised by an AI agent using the CGP knowledge base. See +*An AI agent wrote and revised this page using the CGP knowledge base. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index d19b5219..77614986 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -173,6 +173,6 @@ If the command itself will not run, see [Troubleshooting](./troubleshooting.md). --- -*This page was written by an AI agent from the CGP knowledge base; its example and both outputs were -produced by running the tool — see +*An AI agent wrote this page using the CGP knowledge base. The example and both outputs were +produced by running the tool. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 0191dedd..4fd35c5a 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -179,6 +179,6 @@ Four situations, all of them cases where the answer is in the generated code rat --- -*This page was written by an AI agent from the CGP knowledge base; its example output was produced by -running the tool — see +*An AI agent wrote this page using the CGP knowledge base. The example output was produced by +running the tool. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index 694abdac..89672249 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -123,5 +123,6 @@ still the tools that localize it. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the tool's own -output — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +tool's output. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index 12e6c38a..146df2ab 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -186,5 +186,5 @@ rustup toolchain uninstall --- -*This page was written by an AI agent from the CGP knowledge base and verified against the tool — see -[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +tool. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index 69f668ed..4979ca34 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -238,5 +238,5 @@ Failures that are not covered here are worth reporting on the --- -*This page was written by an AI agent from the CGP knowledge base — see +*An AI agent wrote this page using the CGP knowledge base. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index f3748dce..0a42a044 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -186,4 +186,6 @@ For the constructs, [`#[cgp_type]`](/docs/reference/macros/cgp_type) defines an --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index dd1cc22a..54f932d9 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -164,4 +164,6 @@ consumes a bundle through its `new` keyword and its array-key form, and --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index 8795ecb9..46065d8f 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -222,4 +222,6 @@ version for basic wiring. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 453a4309..d34a97f0 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -237,4 +237,6 @@ is correct before working around it. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index fbb9fc60..3b60f9af 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -285,4 +285,6 @@ For the exact syntax and the full generated code, the reference pages for --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index d41cfea0..d2dd2cb2 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -126,4 +126,6 @@ catalogue of matchers, builders, and per-element adapters, and --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index 07e14ad3..84a941dd 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -139,4 +139,6 @@ shape is made of. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 05581324..eee1d8ed 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -155,4 +155,6 @@ by name. [`ExtractField`](/docs/reference/traits/variant/extract_field) is the e --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 4010f518..7bb12191 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -174,4 +174,6 @@ For the constructs, [`Computer`](/docs/reference/components/handler/computer), --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index 25d9d31c..88423760 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -187,4 +187,6 @@ last example uses. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index cf147b3d..09414ab6 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -273,4 +273,6 @@ page starts from. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index fdfdafe4..f4eb2858 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -176,4 +176,6 @@ them. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/index.md b/docs/concepts/index.md index fee1f521..d5f47a6e 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -71,4 +71,6 @@ turns into a decision guide, and it is the page to reach for when the question i --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index 6b850320..58e35aed 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -184,4 +184,6 @@ bound each one places on the context. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index a11d67f0..5f80795e 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -400,4 +400,6 @@ you need: a capability from a function, no wiring, nothing to reverse later. If --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index 477c103c..74a81b3c 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -118,4 +118,6 @@ defining what a monad is here: [`MonadicBind`](/docs/reference/traits/monad/mona --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index c0878302..d3d851bf 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -212,4 +212,6 @@ routing, and [`Path!`](/docs/reference/macros/path) is the path type underneath. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index 9995ae23..37f69731 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -142,4 +142,6 @@ bound, and its own page records the same gap from the macro's side. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index c3e21f40..00f9c870 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -149,4 +149,6 @@ generic path keys, and [`Product!`](/docs/reference/macros/product) and --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/index.md b/docs/index.md index 7c55198a..66258ba9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -64,5 +64,5 @@ the library as it was when they were published. --- -*This page was revised by an AI agent using the CGP knowledge base. See +*An AI agent revised this page using the CGP knowledge base. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/overview.md b/docs/overview.md index 71e95c3f..ad634216 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -177,5 +177,5 @@ ordinary generics may be clearer. --- -*This page was revised by an AI agent using the CGP knowledge base. See +*An AI agent revised this page using the CGP knowledge base. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index af832f14..a142a07c 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -332,4 +332,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 4a364cba..95cabef6 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -304,4 +304,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 7da668b8..3df778b6 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -254,4 +254,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 60b5701a..4714ed4c 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -251,4 +251,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 579163bf..454cf44b 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -316,4 +316,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 48934711..3f74d188 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -310,4 +310,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index 513cdb98..61577296 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -410,4 +410,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index c770d205..b3895100 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -305,4 +305,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 261bf81f..aeaef4c2 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -390,4 +390,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index c8ffda4a..f7487969 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -240,4 +240,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md index 32c031de..889eb595 100644 --- a/docs/reference/components/can_raise_error.md +++ b/docs/reference/components/can_raise_error.md @@ -150,4 +150,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/can_wrap_error.md b/docs/reference/components/can_wrap_error.md index e5fd027b..fa8e52d1 100644 --- a/docs/reference/components/can_wrap_error.md +++ b/docs/reference/components/can_wrap_error.md @@ -141,4 +141,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/async_computer.md b/docs/reference/components/handler/async_computer.md index 3947379c..3fac9025 100644 --- a/docs/reference/components/handler/async_computer.md +++ b/docs/reference/components/handler/async_computer.md @@ -116,4 +116,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/async_computer_ref.md b/docs/reference/components/handler/async_computer_ref.md index 92d785d5..c02514c3 100644 --- a/docs/reference/components/handler/async_computer_ref.md +++ b/docs/reference/components/handler/async_computer_ref.md @@ -109,4 +109,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md index ef1c8a3e..e5c1504c 100644 --- a/docs/reference/components/handler/computer.md +++ b/docs/reference/components/handler/computer.md @@ -146,4 +146,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/computer_ref.md b/docs/reference/components/handler/computer_ref.md index 42a8b224..11f0274b 100644 --- a/docs/reference/components/handler/computer_ref.md +++ b/docs/reference/components/handler/computer_ref.md @@ -110,4 +110,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md index 288369db..4a7b0612 100644 --- a/docs/reference/components/handler/handler.md +++ b/docs/reference/components/handler/handler.md @@ -147,4 +147,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/handler_ref.md b/docs/reference/components/handler/handler_ref.md index 28e041df..72351b0b 100644 --- a/docs/reference/components/handler/handler_ref.md +++ b/docs/reference/components/handler/handler_ref.md @@ -125,4 +125,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/index.md b/docs/reference/components/handler/index.md index 85ec1d8f..508ba706 100644 --- a/docs/reference/components/handler/index.md +++ b/docs/reference/components/handler/index.md @@ -49,4 +49,6 @@ whole family, and they are composed and routed with the --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/producer.md b/docs/reference/components/handler/producer.md index 6083b764..89ee7f02 100644 --- a/docs/reference/components/handler/producer.md +++ b/docs/reference/components/handler/producer.md @@ -132,4 +132,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/try_computer.md b/docs/reference/components/handler/try_computer.md index 7fa12b8b..1496b4af 100644 --- a/docs/reference/components/handler/try_computer.md +++ b/docs/reference/components/handler/try_computer.md @@ -150,4 +150,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/handler/try_computer_ref.md b/docs/reference/components/handler/try_computer_ref.md index bbad598a..4a1fcc63 100644 --- a/docs/reference/components/handler/try_computer_ref.md +++ b/docs/reference/components/handler/try_computer_ref.md @@ -120,4 +120,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index b6cb44b0..40377d1e 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -154,4 +154,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index 8eb0a319..26720e47 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -149,4 +149,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md index 1f4aa49f..661f9cf1 100644 --- a/docs/reference/components/has_runtime_type.md +++ b/docs/reference/components/has_runtime_type.md @@ -126,4 +126,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index acfb7beb..b8e65b05 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -141,4 +141,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/index.md b/docs/reference/components/index.md index a275ecee..5ef6776e 100644 --- a/docs/reference/components/index.md +++ b/docs/reference/components/index.md @@ -69,4 +69,6 @@ a thread boundary. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index a8c581f5..302c7bbe 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -145,4 +145,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/components/send_runner.md b/docs/reference/components/send_runner.md index 4f2670fa..f62fd777 100644 --- a/docs/reference/components/send_runner.md +++ b/docs/reference/components/send_runner.md @@ -142,4 +142,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 93e528fe..211a092e 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -349,4 +349,6 @@ The implementation is defined in these source files: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index cb6915c7..a4938d67 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -201,4 +201,6 @@ The implementation is defined in these source files: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index e3eaa88a..9cf9d3f4 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -214,4 +214,6 @@ The implementation is defined in these source files: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index b3345a45..fde79c06 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -257,4 +257,6 @@ The implementation is defined in these source files: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 82e070d0..899bb25e 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -360,4 +360,6 @@ The implementation is defined in these source files: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index dfda3c47..a86a684d 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -241,4 +241,6 @@ The implementation is defined in these source files: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index cd58232c..4c39e302 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -303,4 +303,6 @@ The implementation is defined in these source files: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 87cd699a..bcc549d1 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -340,4 +340,6 @@ The implementation is defined in these source files: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 8c66b7f2..2f4b6668 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -668,4 +668,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/index.md b/docs/reference/index.md index 3930b4cd..b460b243 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -249,4 +249,6 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 2cd298ea..61e38f06 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -270,4 +270,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index b6b90f2f..39c08055 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -311,4 +311,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 07b7f098..ae62d454 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -278,4 +278,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 6ae2c531..1acd2466 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -365,4 +365,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 843247f0..ad6ee334 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -458,4 +458,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 2ac6bd2e..e7fc3dcb 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -296,4 +296,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 31bba9f0..ce5b6589 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -363,4 +363,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 674355ce..766190f4 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -321,4 +321,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 563599e6..d5b9fb84 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -447,4 +447,6 @@ and `#[cgp_impl]` up from the same coherence failure that --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 5a30206d..647f5413 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -413,4 +413,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 0a0dbdb7..bf3a5d89 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -267,4 +267,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 9fba5f06..89dfa3b7 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -392,4 +392,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 1ac6fc1d..802254fe 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -331,4 +331,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 7157eeef..82e6e600 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -398,4 +398,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 2a708f5a..b7bf3f1d 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -412,4 +412,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 1cb6fdb6..3903b203 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -727,4 +727,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 10824eb4..5d3862e2 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -236,4 +236,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 12a7accc..13a70c93 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -216,4 +216,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index fe784929..dc43f00a 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -189,4 +189,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index d16aa11e..e1d57966 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -232,4 +232,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index a01906ba..d154641a 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -182,4 +182,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/build_and_merge.md b/docs/reference/providers/dispatch/build_and_merge.md index 05317379..2443aa4c 100644 --- a/docs/reference/providers/dispatch/build_and_merge.md +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -80,4 +80,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/build_and_merge_outputs.md b/docs/reference/providers/dispatch/build_and_merge_outputs.md index 99ab50b9..86c1b395 100644 --- a/docs/reference/providers/dispatch/build_and_merge_outputs.md +++ b/docs/reference/providers/dispatch/build_and_merge_outputs.md @@ -73,4 +73,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/build_and_set_field.md b/docs/reference/providers/dispatch/build_and_set_field.md index ccb59dd3..b961276b 100644 --- a/docs/reference/providers/dispatch/build_and_set_field.md +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -78,4 +78,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/build_with_handlers.md b/docs/reference/providers/dispatch/build_with_handlers.md index f6669265..513cdf77 100644 --- a/docs/reference/providers/dispatch/build_with_handlers.md +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -93,4 +93,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/downcast_and_handle.md b/docs/reference/providers/dispatch/downcast_and_handle.md index b2e2748a..78b26dc6 100644 --- a/docs/reference/providers/dispatch/downcast_and_handle.md +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -72,4 +72,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/extract_field_and_handle.md b/docs/reference/providers/dispatch/extract_field_and_handle.md index dba6022f..9de30c66 100644 --- a/docs/reference/providers/dispatch/extract_field_and_handle.md +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -89,4 +89,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/handle_field_value.md b/docs/reference/providers/dispatch/handle_field_value.md index 0634fe45..be73f9b2 100644 --- a/docs/reference/providers/dispatch/handle_field_value.md +++ b/docs/reference/providers/dispatch/handle_field_value.md @@ -77,4 +77,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/index.md b/docs/reference/providers/dispatch/index.md index 294e6a68..f600184b 100644 --- a/docs/reference/providers/dispatch/index.md +++ b/docs/reference/providers/dispatch/index.md @@ -88,4 +88,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/match_first_with_handlers.md b/docs/reference/providers/dispatch/match_first_with_handlers.md index e395ff8b..01bbe5f3 100644 --- a/docs/reference/providers/dispatch/match_first_with_handlers.md +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -106,4 +106,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/match_with_field_handlers.md b/docs/reference/providers/dispatch/match_with_field_handlers.md index 1352f5a5..d6d0a59f 100644 --- a/docs/reference/providers/dispatch/match_with_field_handlers.md +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -105,4 +105,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/match_with_handlers.md b/docs/reference/providers/dispatch/match_with_handlers.md index f37706c8..481224c4 100644 --- a/docs/reference/providers/dispatch/match_with_handlers.md +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -146,4 +146,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index 835e9e29..74b77952 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -100,4 +100,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index 178c8981..a7e572b3 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -108,4 +108,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/discard_detail.md b/docs/reference/providers/error/discard_detail.md index e660500c..7b09df7e 100644 --- a/docs/reference/providers/error/discard_detail.md +++ b/docs/reference/providers/error/discard_detail.md @@ -82,4 +82,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md index 005e690b..d899787a 100644 --- a/docs/reference/providers/error/display_error.md +++ b/docs/reference/providers/error/display_error.md @@ -101,4 +101,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/index.md b/docs/reference/providers/error/index.md index fa372935..4f5b250a 100644 --- a/docs/reference/providers/error/index.md +++ b/docs/reference/providers/error/index.md @@ -89,4 +89,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/panic_on_error.md b/docs/reference/providers/error/panic_on_error.md index a3b2968d..e155a2c8 100644 --- a/docs/reference/providers/error/panic_on_error.md +++ b/docs/reference/providers/error/panic_on_error.md @@ -82,4 +82,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/raise_from.md b/docs/reference/providers/error/raise_from.md index 2d783a44..58cb9839 100644 --- a/docs/reference/providers/error/raise_from.md +++ b/docs/reference/providers/error/raise_from.md @@ -111,4 +111,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/raise_infallible.md b/docs/reference/providers/error/raise_infallible.md index 45143734..0d6b8360 100644 --- a/docs/reference/providers/error/raise_infallible.md +++ b/docs/reference/providers/error/raise_infallible.md @@ -86,4 +86,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md index dc5c8d38..feee6531 100644 --- a/docs/reference/providers/error/return_error.md +++ b/docs/reference/providers/error/return_error.md @@ -100,4 +100,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/compose_handlers.md b/docs/reference/providers/handler/compose_handlers.md index dd8e7c90..9e315cbb 100644 --- a/docs/reference/providers/handler/compose_handlers.md +++ b/docs/reference/providers/handler/compose_handlers.md @@ -112,4 +112,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md index 04263402..cd3003f5 100644 --- a/docs/reference/providers/handler/index.md +++ b/docs/reference/providers/handler/index.md @@ -92,4 +92,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/pipe_handlers.md b/docs/reference/providers/handler/pipe_handlers.md index d147cb31..88625038 100644 --- a/docs/reference/providers/handler/pipe_handlers.md +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -126,4 +126,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote.md b/docs/reference/providers/handler/promote.md index 882f901e..6f1d3707 100644 --- a/docs/reference/providers/handler/promote.md +++ b/docs/reference/providers/handler/promote.md @@ -91,4 +91,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_async.md b/docs/reference/providers/handler/promote_async.md index 65f51084..057e8e58 100644 --- a/docs/reference/providers/handler/promote_async.md +++ b/docs/reference/providers/handler/promote_async.md @@ -80,4 +80,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md index 50fdf53d..966e5ef8 100644 --- a/docs/reference/providers/handler/promote_async_computer.md +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -71,4 +71,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md index 8d0f707b..e02febc6 100644 --- a/docs/reference/providers/handler/promote_computer.md +++ b/docs/reference/providers/handler/promote_computer.md @@ -102,4 +102,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_handler.md b/docs/reference/providers/handler/promote_handler.md index ceaa0ad2..2ab9fd8c 100644 --- a/docs/reference/providers/handler/promote_handler.md +++ b/docs/reference/providers/handler/promote_handler.md @@ -69,4 +69,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_producer.md b/docs/reference/providers/handler/promote_producer.md index 91b865a1..d1bc0863 100644 --- a/docs/reference/providers/handler/promote_producer.md +++ b/docs/reference/providers/handler/promote_producer.md @@ -75,4 +75,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_ref.md b/docs/reference/providers/handler/promote_ref.md index c5ed85fb..5f4af4fc 100644 --- a/docs/reference/providers/handler/promote_ref.md +++ b/docs/reference/providers/handler/promote_ref.md @@ -85,4 +85,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md index d3c03caf..9ef5a396 100644 --- a/docs/reference/providers/handler/promote_try_computer.md +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -72,4 +72,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/return_input.md b/docs/reference/providers/handler/return_input.md index 6f94a7b1..f6b3c606 100644 --- a/docs/reference/providers/handler/return_input.md +++ b/docs/reference/providers/handler/return_input.md @@ -89,4 +89,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/try_promote.md b/docs/reference/providers/handler/try_promote.md index 896785c3..f86f8b5f 100644 --- a/docs/reference/providers/handler/try_promote.md +++ b/docs/reference/providers/handler/try_promote.md @@ -85,4 +85,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/handler/use_input_delegate.md b/docs/reference/providers/handler/use_input_delegate.md index d1898c4d..a9e8e508 100644 --- a/docs/reference/providers/handler/use_input_delegate.md +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -121,4 +121,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/index.md b/docs/reference/providers/index.md index 664c9532..ad96a677 100644 --- a/docs/reference/providers/index.md +++ b/docs/reference/providers/index.md @@ -62,4 +62,6 @@ subsection here with one page per provider and its own overview. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad/bind_err.md b/docs/reference/providers/monad/bind_err.md index 5c30e89a..fd638ed8 100644 --- a/docs/reference/providers/monad/bind_err.md +++ b/docs/reference/providers/monad/bind_err.md @@ -75,4 +75,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad/bind_ok.md b/docs/reference/providers/monad/bind_ok.md index 453ed29a..33485616 100644 --- a/docs/reference/providers/monad/bind_ok.md +++ b/docs/reference/providers/monad/bind_ok.md @@ -75,4 +75,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad/index.md b/docs/reference/providers/monad/index.md index f6360455..ea02919a 100644 --- a/docs/reference/providers/monad/index.md +++ b/docs/reference/providers/monad/index.md @@ -77,4 +77,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index f52d7a03..e0bbe662 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -113,4 +113,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 82e70b87..9ca592bc 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -176,4 +176,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index a0172f87..b7f305be 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -199,4 +199,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index de748525..4ec65e32 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -158,4 +158,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index ef9e47c3..55625690 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -182,4 +182,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index 3ba2d32f..b211427b 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -91,4 +91,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index e00d8abd..6f1619f1 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -172,4 +172,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index fbb06da9..cb3c5d9c 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -104,4 +104,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 3151f7b1..2949e607 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -159,4 +159,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index ea750c20..f9e0ae2f 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -162,4 +162,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md index 56e59108..760f1055 100644 --- a/docs/reference/providers/with_context.md +++ b/docs/reference/providers/with_context.md @@ -78,4 +78,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md index 3b93d315..2952e3d0 100644 --- a/docs/reference/providers/with_delegated_type.md +++ b/docs/reference/providers/with_delegated_type.md @@ -130,4 +130,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_field.md b/docs/reference/providers/with_field.md index 01fa2191..6d695581 100644 --- a/docs/reference/providers/with_field.md +++ b/docs/reference/providers/with_field.md @@ -108,4 +108,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md index 993d643a..ddf5c56a 100644 --- a/docs/reference/providers/with_field_ref.md +++ b/docs/reference/providers/with_field_ref.md @@ -128,4 +128,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 93ba129a..8bcfdab5 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -183,4 +183,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/providers/with_type.md b/docs/reference/providers/with_type.md index e43b312d..4c67c854 100644 --- a/docs/reference/providers/with_type.md +++ b/docs/reference/providers/with_type.md @@ -103,4 +103,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index a9320812..c53e9401 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -166,4 +166,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/builder/finalize_build.md b/docs/reference/traits/builder/finalize_build.md index 4e6c7903..ab01cc80 100644 --- a/docs/reference/traits/builder/finalize_build.md +++ b/docs/reference/traits/builder/finalize_build.md @@ -189,4 +189,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/builder/has_builder.md b/docs/reference/traits/builder/has_builder.md index b9ca46d5..02e041f8 100644 --- a/docs/reference/traits/builder/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -213,4 +213,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/builder/index.md b/docs/reference/traits/builder/index.md index e298deb4..1bf34073 100644 --- a/docs/reference/traits/builder/index.md +++ b/docs/reference/traits/builder/index.md @@ -39,4 +39,6 @@ generic builder code knows what it is building before the build is complete. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/builder/into_builder.md b/docs/reference/traits/builder/into_builder.md index be4374a0..7040e59b 100644 --- a/docs/reference/traits/builder/into_builder.md +++ b/docs/reference/traits/builder/into_builder.md @@ -150,4 +150,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/builder/partial_data.md b/docs/reference/traits/builder/partial_data.md index 17fefe79..1e8d983f 100644 --- a/docs/reference/traits/builder/partial_data.md +++ b/docs/reference/traits/builder/partial_data.md @@ -161,4 +161,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/builder/take_field.md b/docs/reference/traits/builder/take_field.md index 1db8f03c..c2b7ba56 100644 --- a/docs/reference/traits/builder/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -162,4 +162,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/builder/update_field.md b/docs/reference/traits/builder/update_field.md index dd33d03a..bae334c1 100644 --- a/docs/reference/traits/builder/update_field.md +++ b/docs/reference/traits/builder/update_field.md @@ -182,4 +182,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/casting/can_build_from.md b/docs/reference/traits/casting/can_build_from.md index 8ac1aacf..239f689f 100644 --- a/docs/reference/traits/casting/can_build_from.md +++ b/docs/reference/traits/casting/can_build_from.md @@ -152,4 +152,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/casting/can_downcast.md b/docs/reference/traits/casting/can_downcast.md index 8aa481da..68819e42 100644 --- a/docs/reference/traits/casting/can_downcast.md +++ b/docs/reference/traits/casting/can_downcast.md @@ -151,4 +151,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/casting/can_downcast_fields.md b/docs/reference/traits/casting/can_downcast_fields.md index a5cbd62a..e4dd9a30 100644 --- a/docs/reference/traits/casting/can_downcast_fields.md +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -148,4 +148,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/casting/can_upcast.md b/docs/reference/traits/casting/can_upcast.md index b3aab02d..946b98ec 100644 --- a/docs/reference/traits/casting/can_upcast.md +++ b/docs/reference/traits/casting/can_upcast.md @@ -153,4 +153,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/casting/index.md b/docs/reference/traits/casting/index.md index eafa6cba..ac40d077 100644 --- a/docs/reference/traits/casting/index.md +++ b/docs/reference/traits/casting/index.md @@ -33,4 +33,6 @@ another record, so several sources can be merged into one target before it is fi --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field-access/field_getter.md b/docs/reference/traits/field-access/field_getter.md index 92c19ccd..1f1f06bb 100644 --- a/docs/reference/traits/field-access/field_getter.md +++ b/docs/reference/traits/field-access/field_getter.md @@ -193,4 +193,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field-access/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md index 0fe66add..a9220fa9 100644 --- a/docs/reference/traits/field-access/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -187,4 +187,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index de4d27f8..3ab0d5d6 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -228,4 +228,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index 3a94b964..b23e7a08 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -163,4 +163,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field-access/index.md b/docs/reference/traits/field-access/index.md index e48457b8..cf102e4f 100644 --- a/docs/reference/traits/field-access/index.md +++ b/docs/reference/traits/field-access/index.md @@ -38,4 +38,6 @@ nested context. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field-access/map_field.md b/docs/reference/traits/field-access/map_field.md index 0001f12e..9a60a5a3 100644 --- a/docs/reference/traits/field-access/map_field.md +++ b/docs/reference/traits/field-access/map_field.md @@ -190,4 +190,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/field-access/mut_field_getter.md b/docs/reference/traits/field-access/mut_field_getter.md index 14d9bc83..8809de59 100644 --- a/docs/reference/traits/field-access/mut_field_getter.md +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -153,4 +153,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md index 9f0726a3..1b3bb539 100644 --- a/docs/reference/traits/formatting/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -158,4 +158,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/formatting/index.md b/docs/reference/traits/formatting/index.md index 68180d1e..465d068a 100644 --- a/docs/reference/traits/formatting/index.md +++ b/docs/reference/traits/formatting/index.md @@ -31,4 +31,6 @@ is the group's sharpest edge: one is in the prelude and the other two each need --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/formatting/static_format.md b/docs/reference/traits/formatting/static_format.md index 8092bf22..4e0f0a5e 100644 --- a/docs/reference/traits/formatting/static_format.md +++ b/docs/reference/traits/formatting/static_format.md @@ -181,4 +181,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/formatting/static_string.md b/docs/reference/traits/formatting/static_string.md index 45dad562..df776226 100644 --- a/docs/reference/traits/formatting/static_string.md +++ b/docs/reference/traits/formatting/static_string.md @@ -143,4 +143,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/index.md b/docs/reference/traits/index.md index 19d59ef6..719f387d 100644 --- a/docs/reference/traits/index.md +++ b/docs/reference/traits/index.md @@ -55,4 +55,6 @@ Three smaller groups each serve one area: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index 15c6c60a..d6f2c3e7 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -152,4 +152,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monad/index.md b/docs/reference/traits/monad/index.md index 49bb0ecc..cecf3c20 100644 --- a/docs/reference/traits/monad/index.md +++ b/docs/reference/traits/monad/index.md @@ -34,4 +34,6 @@ the output type on either branch. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monad/lift_value.md b/docs/reference/traits/monad/lift_value.md index 3fa9606a..0315f533 100644 --- a/docs/reference/traits/monad/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -161,4 +161,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index 69b2584e..5d1a6fb7 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -166,4 +166,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index 4d4f7acf..2dbb49a6 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -156,4 +156,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index cb8fa748..681f0b3a 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -236,4 +236,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/namespace/default_impls2.md b/docs/reference/traits/namespace/default_impls2.md index e494277f..f61fd313 100644 --- a/docs/reference/traits/namespace/default_impls2.md +++ b/docs/reference/traits/namespace/default_impls2.md @@ -184,4 +184,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index e59fe072..d5167694 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -186,4 +186,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/namespace/index.md b/docs/reference/traits/namespace/index.md index 77a5314f..5a6e240e 100644 --- a/docs/reference/traits/namespace/index.md +++ b/docs/reference/traits/namespace/index.md @@ -36,4 +36,6 @@ works it out. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md index 94e595c2..72ea406d 100644 --- a/docs/reference/traits/optional/can_build_with_default.md +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -156,4 +156,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/can_finalize_with_default.md b/docs/reference/traits/optional/can_finalize_with_default.md index fcb5e5c8..06913fa1 100644 --- a/docs/reference/traits/optional/can_finalize_with_default.md +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -171,4 +171,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md index 1dbc541f..dd468773 100644 --- a/docs/reference/traits/optional/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -167,4 +167,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/has_optional_builder.md b/docs/reference/traits/optional/has_optional_builder.md index aea91b2b..88893847 100644 --- a/docs/reference/traits/optional/has_optional_builder.md +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -175,4 +175,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/index.md b/docs/reference/traits/optional/index.md index 8921335c..151bb94f 100644 --- a/docs/reference/traits/optional/index.md +++ b/docs/reference/traits/optional/index.md @@ -41,4 +41,6 @@ The **transform markers** carry the per-field conversions the endings run. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/set_optional.md b/docs/reference/traits/optional/set_optional.md index 02b2bf62..e3380bef 100644 --- a/docs/reference/traits/optional/set_optional.md +++ b/docs/reference/traits/optional/set_optional.md @@ -161,4 +161,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/to_optional.md b/docs/reference/traits/optional/to_optional.md index 3effcd11..d161dc7b 100644 --- a/docs/reference/traits/optional/to_optional.md +++ b/docs/reference/traits/optional/to_optional.md @@ -162,4 +162,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/transform_map_default.md b/docs/reference/traits/optional/transform_map_default.md index 6ac30046..5aedbdb5 100644 --- a/docs/reference/traits/optional/transform_map_default.md +++ b/docs/reference/traits/optional/transform_map_default.md @@ -185,4 +185,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index 1f56c48b..9b3bd407 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -179,4 +179,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/shape/from_fields.md b/docs/reference/traits/shape/from_fields.md index 49b1ca80..34dc1edb 100644 --- a/docs/reference/traits/shape/from_fields.md +++ b/docs/reference/traits/shape/from_fields.md @@ -155,4 +155,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index f2575bd3..9510e151 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -212,4 +212,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/shape/has_fields_ref.md b/docs/reference/traits/shape/has_fields_ref.md index 56153cf5..979aa4f3 100644 --- a/docs/reference/traits/shape/has_fields_ref.md +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -165,4 +165,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/shape/index.md b/docs/reference/traits/shape/index.md index 3d6a9b95..500931c3 100644 --- a/docs/reference/traits/shape/index.md +++ b/docs/reference/traits/shape/index.md @@ -32,4 +32,6 @@ that reads a shape without consuming the value. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index d4a783fe..9a4809db 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -160,4 +160,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/shape/to_fields_ref.md b/docs/reference/traits/shape/to_fields_ref.md index 12b175a3..12c90f8e 100644 --- a/docs/reference/traits/shape/to_fields_ref.md +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -152,4 +152,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md index 0970e7c7..87d50ad9 100644 --- a/docs/reference/traits/type-level/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -163,4 +163,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/type-level/concat_product.md b/docs/reference/traits/type-level/concat_product.md index 2bed1b90..267ada52 100644 --- a/docs/reference/traits/type-level/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -155,4 +155,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/type-level/index.md b/docs/reference/traits/type-level/index.md index 41932d72..b84d8075 100644 --- a/docs/reference/traits/type-level/index.md +++ b/docs/reference/traits/type-level/index.md @@ -34,4 +34,6 @@ one entry to a product and [`ConcatProduct`](concat_product.md) splices two toge --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index b602e3e3..eab3a924 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -175,4 +175,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/type-level/map_type.md b/docs/reference/traits/type-level/map_type.md index b6691670..ea63286e 100644 --- a/docs/reference/traits/type-level/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -186,4 +186,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/type-level/map_type_ref.md b/docs/reference/traits/type-level/map_type_ref.md index aa1ea003..625a69ff 100644 --- a/docs/reference/traits/type-level/map_type_ref.md +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -185,4 +185,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/type-level/transform_map.md b/docs/reference/traits/type-level/transform_map.md index 84146f24..a8b546bd 100644 --- a/docs/reference/traits/type-level/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -172,4 +172,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index 22ac48b6..cb98b72b 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -169,4 +169,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index 4cb4f8a1..ad70d863 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -204,4 +204,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/variant/finalize_extract.md b/docs/reference/traits/variant/finalize_extract.md index 49fd0d38..40828d8f 100644 --- a/docs/reference/traits/variant/finalize_extract.md +++ b/docs/reference/traits/variant/finalize_extract.md @@ -159,4 +159,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/variant/finalize_extract_result.md b/docs/reference/traits/variant/finalize_extract_result.md index aced8593..226f8b66 100644 --- a/docs/reference/traits/variant/finalize_extract_result.md +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -168,4 +168,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index 485778c0..cffa7525 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -213,4 +213,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/variant/has_extractor.md b/docs/reference/traits/variant/has_extractor.md index ced27411..54329631 100644 --- a/docs/reference/traits/variant/has_extractor.md +++ b/docs/reference/traits/variant/has_extractor.md @@ -176,4 +176,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/variant/has_extractor_mut.md b/docs/reference/traits/variant/has_extractor_mut.md index 23cb4fb0..52e212fa 100644 --- a/docs/reference/traits/variant/has_extractor_mut.md +++ b/docs/reference/traits/variant/has_extractor_mut.md @@ -153,4 +153,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/variant/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md index e3091550..b5ebd6af 100644 --- a/docs/reference/traits/variant/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -152,4 +152,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/variant/index.md b/docs/reference/traits/variant/index.md index bf7b1f52..a57e0a91 100644 --- a/docs/reference/traits/variant/index.md +++ b/docs/reference/traits/variant/index.md @@ -38,4 +38,6 @@ result. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md index 2a549ec3..d1db09da 100644 --- a/docs/reference/traits/wiring/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -239,4 +239,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index a888c3ac..06af16e7 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -269,4 +269,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/wiring/index.md b/docs/reference/traits/wiring/index.md index 415603e8..89e36425 100644 --- a/docs/reference/traits/wiring/index.md +++ b/docs/reference/traits/wiring/index.md @@ -39,4 +39,6 @@ provider's requirements hold? --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/traits/wiring/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md index c0a35c1c..016f3659 100644 --- a/docs/reference/traits/wiring/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -271,4 +271,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index ff86936f..e4c6ad78 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -146,4 +146,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/cons.md b/docs/reference/types/cons.md index 32c33c19..55f65ffa 100644 --- a/docs/reference/types/cons.md +++ b/docs/reference/types/cons.md @@ -147,4 +147,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/either.md b/docs/reference/types/either.md index 3da6783e..77cc1710 100644 --- a/docs/reference/types/either.md +++ b/docs/reference/types/either.md @@ -149,4 +149,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index f8e11dba..e7056069 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -157,4 +157,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index b442ef90..15807c88 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -53,4 +53,6 @@ you write yourself. --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index 66a0cb55..e7ce1a4a 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -146,4 +146,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index ebaec580..e332cc10 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -135,4 +135,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index e4ba54be..15796f35 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -141,4 +141,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/nil.md b/docs/reference/types/nil.md index 4ce9e309..575a158b 100644 --- a/docs/reference/types/nil.md +++ b/docs/reference/types/nil.md @@ -112,4 +112,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/path_cons.md b/docs/reference/types/path_cons.md index dcc55882..cce76cfd 100644 --- a/docs/reference/types/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -151,4 +151,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/phantom_data.md b/docs/reference/types/phantom_data.md index 7668c617..5d06cba6 100644 --- a/docs/reference/types/phantom_data.md +++ b/docs/reference/types/phantom_data.md @@ -204,4 +204,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/types/void.md b/docs/reference/types/void.md index d0185a08..805624d8 100644 --- a/docs/reference/types/void.md +++ b/docs/reference/types/void.md @@ -122,4 +122,6 @@ The ideas behind it: --- -*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* From dc847e0df622cb4bf30b17e67b7bf6c1f5b61cbc Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 14 Sep 2026 11:13:27 +0000 Subject: [PATCH 073/516] Update namespace syntax --- blog/2026-05-10-v0.8.0-release.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index 12d8b87c..2c05f5f4 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -484,7 +484,7 @@ We have also experimented on a multiple-inheritance-like feature with CGP preset Fortunately, with CGP v0.8.0, we have managed to solve the long-standing problem and devise a way to group component keys through a new feature called **namespaces**. -The way CGP namespaces work is as follows. For each CGP component definition, we can define a namespace prefix like follows: +The way CGP namespaces work is as follows. For each CGP component definition, we can define a **namespace prefix** like follows: ```rust #[cgp_component(UserCreator)] @@ -494,13 +494,13 @@ pub trait CanCreateUser { } ``` -In the code above, we add a new `#[namespace]` attribute to the `UserCreator` component, with a prefix `@app.core.user`. This prefix acts as the new group "key" that we will use later in `delegate_components!`. +In the code above, we add a new `#[prefix]` attribute to the `UserCreator` component, with a prefix `@app.core.user`. This prefix acts as the new group "key" that we will use later in `delegate_components!`. CGP allows the same namespace prefix to be used by multiple traits. For example, we can also apply the `@app.core.user` prefix to `UserGetter`, and similarly to `UserUpdater`: ```rust #[cgp_component(UserGetter)] -#[namespace(@app.core.user)] +#[prefix(@app.core.user)] pub trait CanGetUser { fn get_user(&self, user_id: &UserId) -> Result; } @@ -510,7 +510,7 @@ Similarly, we can assign the prefix `@app.core.post` to `PostCreator`, and other ```rust #[cgp_component(PostCreator)] -#[namespace(@app.core.post)] +#[prefix(@app.core.post)] pub trait CanCreatePost { fn create_post(&self, title: &str, content: &str) -> Result; } @@ -523,7 +523,7 @@ After assigning the namespace prefixes, we can now use them to bulk delegate the ```rust delegate_components! { ProductionApp { - namespace default; + namespace DefaultNamespace; @app.core.user: PostgresUserComponents, @app.core.post: PostgresPostComponents, @@ -532,7 +532,7 @@ delegate_components! { } ``` -Compared to before, our new definition for `ProductionApp` becomes significantly shorter and concise. Since namespace is an opt-in feature, we explicitly enable it using the `namespace` keyword inside the `delegate_components!` block. The `default` namespace is used here, but as we will see in later sections, it is also possible to define custom namespaces and assign different prefixes to CGP components. +Compared to before, our new definition for `ProductionApp` becomes significantly shorter and concise. Since namespace is an opt-in feature, we explicitly enable it using the `namespace` keyword inside the `delegate_components!` block. The `DefaultNamespace` namespace is used here, but as we will see in later sections, it is also possible to define custom namespaces and assign different prefixes to CGP components. Following that, a delegate key like `@app.core.user` implicitly forwards all implementation of the user-related CGP traits to the aggregated provider `PostgresUserComponents`. Similarly, the next two entries delegate the corresponding CGP components to the respective aggregated providers. @@ -547,7 +547,7 @@ With this, we can for example define an aggregated provider for all core compone ```rust delegate_components! { new PostgresCoreComponents { - namespace default; + namespace DefaultNamespace; @app.core.user: PostgresUserComponents, @app.core.post: PostgresPostComponents, @@ -557,7 +557,7 @@ delegate_components! { delegate_components! { new ProductionExtraComponents { - namespace default; + namespace DefaultNamespace; @app.extra.content_filter: AiContentFilterComponents, // other extra components @@ -570,7 +570,7 @@ With these intermediary aggregated providers, our top-level wiring for `Producti ```rust delegate_components! { ProductionApp { - namespace default; + namespace DefaultNamespace; @app.core: PostgresCoreComponents, @app.extra: ProductionExtraComponents, @@ -583,7 +583,7 @@ A key benefit for this hierarchical separation is that it also becomes much easi ```rust delegate_components! { TestApp { - namespace default; + namespace DefaultNamespace; @app.core: PostgresCoreComponents, @app.extra: DummyExtraComponents, @@ -598,7 +598,7 @@ Similarly, if we see another definition of `LocalApp` like: ```rust delegate_components! { LocalApp { - namespace default; + namespace DefaultNamespace; @app.core: SqliteCoreComponents, @app.extra: ProductionExtraComponents, From 1b96bb8ae58aec9d9f28011eb5408ae5b6028bfa Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 14 Sep 2026 13:50:31 +0000 Subject: [PATCH 074/516] Draft default implementations --- blog/2026-05-10-v0.8.0-release.md | 91 +++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index 2c05f5f4..3015df0c 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -609,3 +609,94 @@ delegate_components! { We know that all PostgreSQL-specific core logic has been replaced by an SQLite-specific database backend. If we were to define the same 3 contexts without namespaces, the difference in developer experience is stark. A new developer would need to scan through the dozens of lines of component wirings between the 3 contexts. Worse yet, the component wirings may be defined in different orders, making it extremely difficult to compare using humen eyes. + +## Default implementations + +In the earlier examples, we defined aggregated providers like `PostgresUserComponents`, `PostgresPostComponents`, and `PostgresCoreComponents` to group related provider implementations together, and then bulk delegate a prefix like `@app.core` to the aggregated provider. This provides great flexibility in customizing an application stack with different implementation bundles, such as `SqliteCoreComponents` or `PostgresWithLoggingCoreComponents`. + +However, such flexibility is not often needed during the early phase of application development. For example, it might be premature to define a `PostgresUserComponents`, if we are very sure that the initial version of the application will only use Postgres to store the user information. In other words, developers tend to prefer *singleton* implementations of a feature with intentional coupling between the interface and the implementation to make it easier to reason about the application. + +With namespaces, CGP now offers **default implementation** as a way to tightly couple a particular provider with the component *within a namespace*. To demonstrate how it works, let's first define a new custom namespace for our application: + +```rust +cgp_namespace! { + new DefaultAppComponents: DefaultNamespace +} +``` + +In the code above, we use `cgp_namespace!` to define a new namespace called `DefaultAppComponents` that **inherits** from `DefaultNamespace` as its parent namespace. This means that all prefixes and default implementations defined in `DefaultNamespace` would also automatically apply to `DefaultAppComponents`. + +With the new `DefaultAppComponents` namespace defined, we can now designate our provider implementations as default implementations in `DefaultAppComponents`, such as: + +```rust +#[cgp_impl(new GetUserWithPostgres)] +#[default_impl(@app.core.user.UserGetterComponent in DefaultAppComponents)] +impl UserGetter { + fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { + // ... + } +} +``` + +Compared to earlier, we added a new `#[default_impl]` attribute when defining the `GetUserWithPostgres` provider. Inside the attribute, we designate `@app.core.user.UserGetterComponent` as the component key which `GetUserWithPostgres` would be set as the default provider. Following that, `in DefaultAppComponents` indicates that this default provider is only applicable when the namespace `DefaultAppComponents` is used in `delegate_components!`. + + +The above use of `#[default_impl]` essentially expands into the following use of `cgp_namespace!`: + +```rust +cgp_namespace! { + DefaultAppComponents { + @app.core.user.UserGetterComponent: + GetUserWithPostgres, + } +} +``` + +The use of `cgp_namespace!` is similar to `delegate_components!`, with each key-value mapping being bound to a namespace instead of a context or provider. Notice that we use the prefixed key `@app.core.user.UserGetterComponent` instead of the bare `UserGetterComponent`, as `DefaultAppComponents` extends from `DefaultNamespace`, which redirects the use of `UserGetterComponent` to the prefixed key. + +When we want to assign a composite provider as the default implementation, we can do so by using `cgp_namespace!` directly. For example: + +```rust +cgp_namespace! { + DefaultAppComponents { + @app.core.user.UserCreatorComponent: + FilterCensoredUsername, + } +} +``` + +would mean that the default user creator component would always be the combined provider `FilterCensoredUsername`. + +With default implementations, we can now omit the delegation of the relevant components entirely, if we use a namespace that contains the default implementations. For example: + +```rust +delegate_components! { + ProductionApp { + namespace DefaultAppComponents; + + @app.extra.content_filter: ContentFilterComponents, + } +} +``` + +Assuming that we also assign default implementations for every user and post providers in `DefaultAppComponents`, now there is almost no explicit wiring needed in `ProductionApp`, which uses `DefaultAppComponents` as the namespace. + +Notice that in the example, we still exclude the content filter components from the namespace. This may be useful if we still want to customize the implementation, such as using mocked implementations inside a `TestApp`. + +By using default implementations, CGP allows developers to focus on wirings that truly require variations between application contexts, and allow omitting of wirings that do not change by setting them as default implementations in a given namespace. + +At the same time, the use of namespaces means that developers still have the option to opt out of a given default implementation, by choosing to use a different namespace. + +### Caveats with default implementations + +Although default implementations provide the convenience of omitting explicit wirings, the coherence restrictions in Rust makes it tricky to use default implementations as an application grows large. + +A key caveat is that in most cases, a default implementation assignment would only succeed if the crate owns the namespace and/or the component trait. Otherwise, developers can run into coherence restriction errors, if the constructs are scattered across multiple crates. + +Furthermore, once a default implementation is defined, it is not possible to opt out of that particular default from the rest of the bindings in a namespace. This means that opting out even one default implementation requires you to completely opt out of that specific namespace. + +This means that default implementations is mostly a beginner-oriented feature, where the entire application can fit in one crate, and that the user don't care that much about reusability at the moment. + +In such single-crate use cases, CGP do not offer much value. However, with default implementations serving as a bridge, it enables the possibility for one to transition an project from having a single-crate monolithic application into having multiple crates with modular applications. + +Default implementations allows such transition to be gradually rolled out, by first refactoring all monolithic code into CGP components with default implementations, without significantly disrupting the original code organization. From 7b6cd3c3ef081ddb2eba3cfae46111438b003d1e Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 15 Sep 2026 10:41:06 +0000 Subject: [PATCH 075/516] Use cgp from git --- blog/2026-05-10-v0.8.0-release.md | 2 ++ docs/reference/macros/cgp_namespace.md | 24 ++++++++++--- example-code/Cargo.toml | 4 ++- .../compile_fail/cargo_cgp/check_check.stderr | 8 ++--- ...traits_where_the_failure_surfaces_2.stderr | 8 ++--- ...handlers_plain_composition_is_wrong.stderr | 4 +-- ...eld_rejected_read_of_an_unset_field.stderr | 4 +-- ...t_field_rejected_premature_finalize.stderr | 4 +-- .../reference/errors_the_fix_1.stderr | 8 ++--- .../concepts/consumer_and_provider_traits.rs | 7 +--- example-code/tests/concepts/dispatching.rs | 8 ++++- .../tests/concepts/extensible_records.rs | 4 ++- .../tests/concepts/extensible_variants.rs | 11 +++--- example-code/tests/concepts/handlers.rs | 15 ++++++-- .../tests/concepts/higher_order_providers.rs | 5 ++- .../tests/concepts/impl_side_dependencies.rs | 4 ++- .../tests/concepts/modular_error_handling.rs | 5 ++- .../reference/derives/derive_build_field.rs | 24 +++++-------- .../reference/derives/derive_cgp_data.rs | 18 ++++------ .../reference/derives/derive_cgp_record.rs | 6 ++-- .../reference/derives/derive_extract_field.rs | 9 ++--- .../reference/derives/derive_from_variant.rs | 18 ++++------ .../reference/derives/derive_has_fields.rs | 35 ++++++------------- .../dispatch/extract_field_and_handle.rs | 8 ++++- .../dispatch/match_with_field_handlers.rs | 5 ++- .../providers/dispatch/match_with_handlers.rs | 8 ++++- .../dispatch/match_with_value_handlers.rs | 8 ++++- .../providers/error/discard_detail.rs | 4 ++- .../providers/error/display_error.rs | 5 ++- .../reference/providers/error/raise_from.rs | 10 ++++-- .../reference/providers/error/return_error.rs | 4 ++- .../providers/handler/pipe_handlers.rs | 6 +++- .../providers/handler/promote_handler.rs | 5 ++- .../providers/handler/promote_try_computer.rs | 5 ++- .../providers/handler/try_promote.rs | 5 ++- .../providers/handler/use_input_delegate.rs | 8 ++++- example-code/tests/reference/providers/mod.rs | 2 +- .../tests/reference/traits/concat_product.rs | 8 ++--- .../tests/reference/traits/has_builder.rs | 9 ++--- .../tests/reference/traits/map_fields.rs | 4 ++- 40 files changed, 198 insertions(+), 141 deletions(-) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index 3015df0c..5ad1d0a0 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -10,6 +10,8 @@ tags: [release] +## Introducing cargo-cgp + ## The challenges of scaling CGP Up until now, one of main challenges of using CGP is on the boilerplate of using `delegate_components!` to wire CGP providers, especially as the number of CGP components grow within an application. When there are too many entries inside `delegate_components!`, developers quickly get lost on what they should pay attention to, and it gives the impression that the application becomes too complex. diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 647f5413..b35365a3 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -109,6 +109,20 @@ cgp_namespace! { The parent may itself be parameterized. The child's entries layer on top, and a path-rewriting entry like the one above reroutes a whole subtree of the parent's namespace rather than a single component. +A namespace with nothing of its own to add may stop at the header. The braces are optional when the body +would be empty, which is the usual shape of a namespace that exists only to inherit: + +```rust +cgp_namespace! { + new ExtendedNamespace: BaseNamespace +} +``` + +This is the same as writing `{}` after the parent, and `new BaseNamespace` on its own emits just the +trait and struct the same way. Only the end of the input may follow the header; any other token there is +an `expected curly braces` error. The shorthand is this macro's alone, since +[`delegate_components!`](./delegate_components.md) keeps its braces even when its table is empty. + ### The other two halves: registering, and joining Defining a namespace is only one part of the pattern. A component **registers into** one with the @@ -195,7 +209,7 @@ joining the child inherits the whole chain: ```rust cgp_namespace! { new BaseNamespace {} } -cgp_namespace! { new ExtendedNamespace: BaseNamespace {} } +cgp_namespace! { new ExtendedNamespace: BaseNamespace } delegate_components! { MyApp { @@ -299,11 +313,11 @@ A couple of naming details appear verbatim in errors and are worth recognizing: ## Formal grammar -The body is a header and a table, in the Rust Reference's +The body is a header and an optional table, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): ```ebnf -CgpNamespace -> Generics? `new`? NamespaceName ( `:` ParentNamespace )? `{` NamespaceBody `}` +CgpNamespace -> Generics? `new`? NamespaceName ( `:` ParentNamespace )? ( `{` NamespaceBody `}` )? NamespaceName -> IDENTIFIER GenericArgs? ParentNamespace -> TypePath GenericArgs? @@ -315,7 +329,9 @@ NamespaceBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? so its `Statement` and `Mapping` rules, covering every operator, every key form, and every value form, are defined on that page rather than restated here. The two a namespace normally uses are `=>` to an `@`-path and `:` to a provider. The `:` between `NamespaceName` and `ParentNamespace` is the inheritance colon, distinct from a -mapping's. `NamespaceName` becomes both a trait and, with `new`, a struct. +mapping's. `NamespaceName` becomes both a trait and, with `new`, a struct. The table is optional: a header +followed by nothing is an empty `NamespaceBody`, and a header followed by anything other than `{` is a +parse error. Two statement forms in that shared production exist for this macro, because their job is joining a context's table to a namespace. A `NamespaceStmt`, `namespace SomeNamespace;`, forwards every diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index 5f9d2e0b..9494249d 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -12,4 +12,6 @@ cgp = "0.8.0-alpha" futures = "0.3" trybuild = "1" -[workspace] + +[patch.crates-io] +cgp = { git = "https://github.com/contextgeneric/cgp.git" } diff --git a/example-code/tests/compile_fail/cargo_cgp/check_check.stderr b/example-code/tests/compile_fail/cargo_cgp/check_check.stderr index 9e680bac..2c7c07cc 100644 --- a/example-code/tests/compile_fail/cargo_cgp/check_check.stderr +++ b/example-code/tests/compile_fail/cargo_cgp/check_check.stderr @@ -6,10 +6,10 @@ error[E0277]: the trait bound `Rectangle: CanUseComponent>>>>>>>` is not implemented for `Rectangle` but trait `HasField>>>>>>` is implemented for it - --> tests/compile_fail/cargo_cgp/check_check.rs:16:10 + --> tests/compile_fail/cargo_cgp/check_check.rs:18:9 | -16 | #[derive(HasField)] - | ^^^^^^^^ +18 | pub width: f64, + | ^^^^^ note: required for `RectangleArea` to implement `IsProviderFor` --> tests/compile_fail/cargo_cgp/check_check.rs:8:1 | @@ -25,4 +25,4 @@ note: required by a bound in `__CheckRectangle` 30 | | } 31 | | } | |_^ required by this bound in `__CheckRectangle` - = note: this error originates in the derive macro `HasField` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr index 1e7c73c8..58cad28f 100644 --- a/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr +++ b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr @@ -6,10 +6,10 @@ error[E0277]: the trait bound `BrokenApp: CanUseComponent` | help: the trait `HasField>>>>>>>>>>>>` is not implemented for `BrokenApp` but trait `HasField>>>>>>>>>>>>` is implemented for it - --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:18:10 + --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:20:9 | -18 | #[derive(HasField)] - | ^^^^^^^^ +20 | pub smtp_server: String, + | ^^^^^^^^^^^ note: required for `RecordEmails` to implement `IsProviderFor` --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:10:1 | @@ -25,4 +25,4 @@ note: required by a bound in `__CheckBrokenApp` 29 | | } 30 | | } | |_^ required by this bound in `__CheckBrokenApp` - = note: this error originates in the derive macro `HasField` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr index 97ad2ad9..e4b06044 100644 --- a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr +++ b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr @@ -4,9 +4,9 @@ error[E0599]: the associated function or constant `compute` exists for struct `P 12 | let _ = PipeHandlers::::compute(&(), PhantomData::<()>, 1u8); | ^^^^^^^ associated function or constant cannot be called due to unsatisfied trait bounds | - ::: $CARGO/cgp-handler-$VERSION/src/providers/pipe.rs + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/providers/pipe.rs:7:1 | - | pub struct PipeHandlers(pub PhantomData); + 7 | pub struct PipeHandlers(pub PhantomData); | ---------------------------------- doesn't satisfy `_: Computer<_, _, _>` or `_: IsProviderFor` | = note: the following trait bounds were not satisfied: diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr index 3235b125..f8e5e7bd 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr @@ -9,7 +9,7 @@ error[E0308]: mismatched types = note: expected struct `std::marker::PhantomData>>>>>>>>>>>` found struct `std::marker::PhantomData>>>>>>>>>>` note: method defined here - --> $CARGO/cgp-field-$VERSION/src/traits/has_field.rs + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/has_field.rs:49:8 | - | fn get_field(&self, _tag: PhantomData) -> &Self::Value; +49 | fn get_field(&self, _tag: PhantomData) -> &Self::Value; | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr index bf431dcf..00df801a 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr @@ -22,7 +22,7 @@ error[E0599]: the method `finalize_extract_result` exists for enum `Result: FinalizeExtract` which is required by `Result>: FinalizeExtractResult` note: the trait `FinalizeExtract` must be implemented - --> $CARGO/cgp-field-$VERSION/src/traits/extract_field.rs + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:38:1 | - | pub trait FinalizeExtract { +38 | pub trait FinalizeExtract { | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr b/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr index ceba3f39..8aad0a3e 100644 --- a/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr +++ b/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr @@ -6,10 +6,10 @@ error[E0277]: the trait bound `Person: CanUseComponent` is not | help: the trait `HasField>>>>>` is not implemented for `Person` but trait `HasField>>>>` is implemented for it - --> tests/compile_fail/reference/errors_the_fix_1.rs:21:10 + --> tests/compile_fail/reference/errors_the_fix_1.rs:23:9 | -21 | #[derive(HasField)] - | ^^^^^^^^ +23 | pub age: u8, + | ^^^ note: required for `Person` to implement `HasName` --> tests/compile_fail/reference/errors_the_fix_1.rs:8:1 | @@ -34,4 +34,4 @@ note: required by a bound in `__CheckPerson` 38 | | } 39 | | } | |_^ required by this bound in `__CheckPerson` - = note: this error originates in the derive macro `HasField` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the attribute macro `cgp_auto_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/concepts/consumer_and_provider_traits.rs b/example-code/tests/concepts/consumer_and_provider_traits.rs index 0310e2d3..ecd03b53 100644 --- a/example-code/tests/concepts/consumer_and_provider_traits.rs +++ b/example-code/tests/concepts/consumer_and_provider_traits.rs @@ -180,12 +180,7 @@ pub mod writing_it { #[cgp_impl(new RecordEmails)] impl EmailSender { - fn send_email( - &self, - #[implicit] sent_emails: &RefCell>, - to: &str, - body: &str, - ) { + fn send_email(&self, #[implicit] sent_emails: &RefCell>, to: &str, body: &str) { sent_emails.borrow_mut().push(format!("{to}: {body}")); } } diff --git a/example-code/tests/concepts/dispatching.rs b/example-code/tests/concepts/dispatching.rs index 10814bf5..e931474f 100644 --- a/example-code/tests/concepts/dispatching.rs +++ b/example-code/tests/concepts/dispatching.rs @@ -71,7 +71,13 @@ pub mod matching_one_handler_per_variant { let code = PhantomData::<()>; assert_eq!( - app.compute(code, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), + app.compute( + code, + Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0 + }) + ), 12.0, ); diff --git a/example-code/tests/concepts/extensible_records.rs b/example-code/tests/concepts/extensible_records.rs index c261aa79..e10bac2f 100644 --- a/example-code/tests/concepts/extensible_records.rs +++ b/example-code/tests/concepts/extensible_records.rs @@ -16,7 +16,9 @@ pub mod a_struct_as_a_list_of_named_fields { fn the_shape_is_a_type() { fn assert_shape() where - T: HasFields, Field]>, + T: HasFields< + Fields = Product![Field, Field], + >, { } diff --git a/example-code/tests/concepts/extensible_variants.rs b/example-code/tests/concepts/extensible_variants.rs index bae62333..40b9020b 100644 --- a/example-code/tests/concepts/extensible_variants.rs +++ b/example-code/tests/concepts/extensible_variants.rs @@ -29,9 +29,9 @@ pub mod an_enum_as_a_list_of_named_variants { where T: HasFields< Fields = Sum![ - Field, - Field, - ], + Field, + Field, + ], >, { } @@ -98,7 +98,10 @@ pub mod one_handler_per_variant { let code = PhantomData::<()>; assert_eq!(app.compute(code, Reading::Temperature(21)), "21"); - assert_eq!(app.compute(code, Reading::Label("north".to_owned())), "north"); + assert_eq!( + app.compute(code, Reading::Label("north".to_owned())), + "north" + ); // The wider enum works through the same wiring, with no new arm anywhere. assert_eq!(app.compute(code, ExtendedReading::Flag(true)), "true"); diff --git a/example-code/tests/concepts/handlers.rs b/example-code/tests/concepts/handlers.rs index 6ae4a4c9..17a12a65 100644 --- a/example-code/tests/concepts/handlers.rs +++ b/example-code/tests/concepts/handlers.rs @@ -31,8 +31,14 @@ pub mod one_function_the_whole_family { assert_eq!(Add::compute(&app, PhantomData::<()>, (1, 2)), 3); assert_eq!(Add::try_compute(&app, PhantomData::<()>, (1, 2)), Ok(3)); - assert_eq!(block_on(Add::compute_async(&app, PhantomData::<()>, (1, 2))), 3); - assert_eq!(block_on(Add::handle(&app, PhantomData::<()>, (1, 2))), Ok(3)); + assert_eq!( + block_on(Add::compute_async(&app, PhantomData::<()>, (1, 2))), + 3 + ); + assert_eq!( + block_on(Add::handle(&app, PhantomData::<()>, (1, 2))), + Ok(3) + ); } } @@ -60,7 +66,10 @@ pub mod a_fallible_function { fn the_error_path_surfaces_through_the_fallible_members() { let app = App; - assert_eq!(CheckedAdd::try_compute(&app, PhantomData::<()>, (1, 2)), Ok(3)); + assert_eq!( + CheckedAdd::try_compute(&app, PhantomData::<()>, (1, 2)), + Ok(3) + ); assert_eq!( CheckedAdd::try_compute(&app, PhantomData::<()>, (u64::MAX, 1)), Err("overflow".to_owned()), diff --git a/example-code/tests/concepts/higher_order_providers.rs b/example-code/tests/concepts/higher_order_providers.rs index dd6a8089..572e4342 100644 --- a/example-code/tests/concepts/higher_order_providers.rs +++ b/example-code/tests/concepts/higher_order_providers.rs @@ -206,7 +206,10 @@ pub mod falling_back_to_the_context { #[use_provider(Inner: ShapeAreaCalculator)] impl ShapeAreaCalculator> { fn shape_area(&self, shapes: &Vec) -> f64 { - shapes.iter().map(|shape| Inner::shape_area(self, shape)).sum() + shapes + .iter() + .map(|shape| Inner::shape_area(self, shape)) + .sum() } } diff --git a/example-code/tests/concepts/impl_side_dependencies.rs b/example-code/tests/concepts/impl_side_dependencies.rs index e1f2891f..b9593cad 100644 --- a/example-code/tests/concepts/impl_side_dependencies.rs +++ b/example-code/tests/concepts/impl_side_dependencies.rs @@ -83,7 +83,9 @@ pub mod two_providers_two_requirements { #[uses(HasSentEmails)] impl EmailSender { fn send_email(&self, to: &str, body: &str) { - self.sent_emails().borrow_mut().push(format!("{to}: {body}")); + self.sent_emails() + .borrow_mut() + .push(format!("{to}: {body}")); } } diff --git a/example-code/tests/concepts/modular_error_handling.rs b/example-code/tests/concepts/modular_error_handling.rs index 56cd1005..bb98970f 100644 --- a/example-code/tests/concepts/modular_error_handling.rs +++ b/example-code/tests/concepts/modular_error_handling.rs @@ -62,7 +62,10 @@ pub mod code_that_fails_without_knowing { ); // Raised as a `ParseIntError`, formatted and then routed through the `String` entry. - assert!(App.parse_port("http").unwrap_err().contains("ParseIntError")); + assert!(App + .parse_port("http") + .unwrap_err() + .contains("ParseIntError")); } } diff --git a/example-code/tests/reference/derives/derive_build_field.rs b/example-code/tests/reference/derives/derive_build_field.rs index e53e130e..9f967f8a 100644 --- a/example-code/tests/reference/derives/derive_build_field.rs +++ b/example-code/tests/reference/derives/derive_build_field.rs @@ -11,8 +11,7 @@ pub mod what_its_for { use cgp::prelude::*; - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct Person { pub first_name: String, pub last_name: String, @@ -65,23 +64,19 @@ pub mod rejected_build_from_without_has_fields {} pub mod using_it { use cgp::prelude::*; - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct Person { pub first_name: String, pub last_name: String, } - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct Pair(pub u32, pub u32); - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct NoConfig {} - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct Generic { pub value: T, } @@ -123,23 +118,20 @@ pub mod examples { // `build_from` recurses over the *source's* field list, so the source needs `HasFields` as // well as the builder. The page says so under *The three ways to fill a field*. - #[derive(HasFields, BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(HasFields, BuildField, Debug, Eq, PartialEq)] pub struct FooBar { pub foo: u64, pub bar: String, } - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct FooBarBaz { pub foo: u64, pub bar: String, pub baz: bool, } - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct Person { pub first_name: String, pub last_name: String, diff --git a/example-code/tests/reference/derives/derive_cgp_data.rs b/example-code/tests/reference/derives/derive_cgp_data.rs index c92282d3..cb65f642 100644 --- a/example-code/tests/reference/derives/derive_cgp_data.rs +++ b/example-code/tests/reference/derives/derive_cgp_data.rs @@ -22,41 +22,35 @@ pub mod using_it { pub height: u32, } - #[derive(CgpData)] - #[derive(Debug, Eq, PartialEq)] + #[derive(CgpData, Debug, Eq, PartialEq)] pub struct Person { pub first_name: String, pub last_name: String, } - #[derive(CgpData)] - #[derive(Debug, Eq, PartialEq)] + #[derive(CgpData, Debug, Eq, PartialEq)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } /// The shape-specific faces, which the page says emit what the umbrella emits. - #[derive(CgpRecord)] - #[derive(Debug, Eq, PartialEq)] + #[derive(CgpRecord, Debug, Eq, PartialEq)] pub struct RecordFace { pub value: u32, } - #[derive(CgpVariant)] - #[derive(Debug, Eq, PartialEq)] + #[derive(CgpVariant, Debug, Eq, PartialEq)] pub enum VariantFace { One(Circle), } /// The degenerate struct shape: a parameterless companion, so `builder()` finalizes at once. - #[derive(CgpData)] - #[derive(Debug, Eq, PartialEq)] + #[derive(CgpData, Debug, Eq, PartialEq)] pub struct NoConfig {} /// A tuple struct, whose builder steps are keyed by position rather than by name. - #[derive(CgpData)] - #[derive(Debug, Eq, PartialEq)] + #[derive(CgpData, Debug, Eq, PartialEq)] pub struct Pair(pub u32, pub u32); #[test] diff --git a/example-code/tests/reference/derives/derive_cgp_record.rs b/example-code/tests/reference/derives/derive_cgp_record.rs index 2e8da729..0da0b85c 100644 --- a/example-code/tests/reference/derives/derive_cgp_record.rs +++ b/example-code/tests/reference/derives/derive_cgp_record.rs @@ -10,15 +10,13 @@ pub mod examples { use cgp::core::field::impls::CanBuildFrom; use cgp::prelude::*; - #[derive(CgpRecord)] - #[derive(Debug, Eq, PartialEq)] + #[derive(CgpRecord, Debug, Eq, PartialEq)] pub struct Person { pub first_name: String, pub last_name: String, } - #[derive(CgpRecord)] - #[derive(Debug, Eq, PartialEq)] + #[derive(CgpRecord, Debug, Eq, PartialEq)] pub struct Employee { pub employee_id: u64, pub first_name: String, diff --git a/example-code/tests/reference/derives/derive_extract_field.rs b/example-code/tests/reference/derives/derive_extract_field.rs index 94a09189..1c3f8e95 100644 --- a/example-code/tests/reference/derives/derive_extract_field.rs +++ b/example-code/tests/reference/derives/derive_extract_field.rs @@ -22,8 +22,7 @@ pub mod what_its_for { pub height: u32, } - #[derive(ExtractField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(ExtractField, Debug, Eq, PartialEq)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), @@ -65,8 +64,7 @@ pub mod using_it { #[derive(Debug, PartialEq)] pub struct Empty; - #[derive(ExtractField)] - #[derive(Debug, PartialEq)] + #[derive(ExtractField, Debug, PartialEq)] pub enum Shape { Circle(Circle), Empty(Empty), @@ -127,8 +125,7 @@ pub mod examples { pub height: f64, } - #[derive(ExtractField)] - #[derive(Debug, PartialEq)] + #[derive(ExtractField, Debug, PartialEq)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), diff --git a/example-code/tests/reference/derives/derive_from_variant.rs b/example-code/tests/reference/derives/derive_from_variant.rs index ed03d39f..9b20213d 100644 --- a/example-code/tests/reference/derives/derive_from_variant.rs +++ b/example-code/tests/reference/derives/derive_from_variant.rs @@ -22,8 +22,7 @@ pub mod what_its_for { pub height: u32, } - #[derive(FromVariant)] - #[derive(Debug, Eq, PartialEq)] + #[derive(FromVariant, Debug, Eq, PartialEq)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), @@ -48,14 +47,12 @@ pub mod using_it { pub radius: u32, } - #[derive(FromVariant)] - #[derive(Debug, Eq, PartialEq)] + #[derive(FromVariant, Debug, Eq, PartialEq)] pub enum Shape { Circle(Circle), } - #[derive(FromVariant)] - #[derive(Debug, Eq, PartialEq)] + #[derive(FromVariant, Debug, Eq, PartialEq)] pub enum Generic { Item(T), } @@ -95,8 +92,7 @@ pub mod examples { pub height: f64, } - #[derive(FromVariant)] - #[derive(Debug, PartialEq)] + #[derive(FromVariant, Debug, PartialEq)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), @@ -145,15 +141,13 @@ pub mod examples_upcast { pub struct Literal(pub u64); /// The narrow enum an implementation constructs into. - #[derive(CgpData)] - #[derive(Debug, PartialEq)] + #[derive(CgpData, Debug, PartialEq)] pub enum LispSubExpr { Ident(Ident), } /// The full enum it is widened into. - #[derive(CgpData)] - #[derive(Debug, PartialEq)] + #[derive(CgpData, Debug, PartialEq)] pub enum LispExpr { Ident(Ident), Literal(Literal), diff --git a/example-code/tests/reference/derives/derive_has_fields.rs b/example-code/tests/reference/derives/derive_has_fields.rs index 879521de..d7b91ba5 100644 --- a/example-code/tests/reference/derives/derive_has_fields.rs +++ b/example-code/tests/reference/derives/derive_has_fields.rs @@ -11,16 +11,14 @@ pub mod what_its_for { use cgp::prelude::*; - #[derive(Clone, Debug, Eq, PartialEq)] - #[derive(HasFields)] + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] pub struct Person { pub name: String, pub age: u8, } // The page writes this type out; asserting the equality is what checks it. - pub type ExpectedFields = - Product![Field, Field]; + pub type ExpectedFields = Product![Field, Field]; pub fn assert_fields(fields: ::Fields) -> ExpectedFields { fields @@ -47,35 +45,29 @@ pub mod what_its_for { pub mod using_it { use cgp::prelude::*; - #[derive(Clone, Debug, Eq, PartialEq)] - #[derive(HasFields)] + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] pub struct Named { pub name: String, pub age: u8, } - #[derive(Clone, Debug, Eq, PartialEq)] - #[derive(HasFields)] + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] pub struct Tuple(pub u32, pub u32); - #[derive(Clone, Debug, Eq, PartialEq)] - #[derive(HasFields)] + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] pub struct Unit; /// The newtype special case: `Fields` is the inner type directly. - #[derive(Clone, Debug, Eq, PartialEq)] - #[derive(HasFields)] + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] pub struct Newtype(pub String); - #[derive(Clone, Debug, Eq, PartialEq)] - #[derive(HasFields)] + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] pub struct Generic { pub value: T, } /// The four variant shapes, all accepted by this derive and by no other in the family. - #[derive(Clone, Debug, Eq, PartialEq)] - #[derive(HasFields)] + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] pub enum Shape { Empty, Circle(u32), @@ -141,10 +133,7 @@ pub mod using_it { Shape::Empty, Shape::Circle(2), Shape::Rectangle(3, 4), - Shape::Triangle { - base: 6, - height: 5, - }, + Shape::Triangle { base: 6, height: 5 }, ] { assert_eq!(Shape::from_fields(shape.clone().to_fields()), shape); } @@ -157,8 +146,7 @@ pub mod using_it { pub mod examples { use cgp::prelude::*; - #[derive(Clone, Debug, Eq, PartialEq)] - #[derive(HasField, HasFields)] + #[derive(Clone, Debug, Eq, PartialEq, HasField, HasFields)] pub struct Config { pub host: String, pub port: u16, @@ -176,8 +164,7 @@ pub mod examples { pub height: f64, } - #[derive(Clone, Debug, PartialEq)] - #[derive(HasFields)] + #[derive(Clone, Debug, PartialEq, HasFields)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), diff --git a/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs b/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs index 3cfab232..8480342c 100644 --- a/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs +++ b/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs @@ -76,7 +76,13 @@ pub mod one_adapter_per_variant { let code = PhantomData::<()>; assert_eq!( - app.compute(code, Shape::Rectangle(Rectangle { width: 2.0, height: 5.0 })), + app.compute( + code, + Shape::Rectangle(Rectangle { + width: 2.0, + height: 5.0 + }) + ), 10.0, ); } diff --git a/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs index 6a22fbe0..e7aa2452 100644 --- a/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs @@ -63,7 +63,10 @@ pub mod matching_with_the_tag_attached { let code = PhantomData::<()>; assert_eq!(app.compute(code, Reading::Temperature(21)), "21"); - assert_eq!(app.compute(code, Reading::Label("north".to_owned())), "north"); + assert_eq!( + app.compute(code, Reading::Label("north".to_owned())), + "north" + ); assert_eq!(app.compute(code, ExtendedReading::Flag(true)), "true"); } } diff --git a/example-code/tests/reference/providers/dispatch/match_with_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_handlers.rs index 3b07cf6a..69092cd7 100644 --- a/example-code/tests/reference/providers/dispatch/match_with_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/match_with_handlers.rs @@ -76,7 +76,13 @@ pub mod matching_an_explicit_list { let code = PhantomData::<()>; assert_eq!( - app.compute(code, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), + app.compute( + code, + Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0 + }) + ), 12.0, ); diff --git a/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs index 0caa2274..44ec6e71 100644 --- a/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs @@ -78,7 +78,13 @@ pub mod matching_by_value { let code = PhantomData::<()>; assert_eq!( - app.compute(code, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), + app.compute( + code, + Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0 + }) + ), 12.0, ); diff --git a/example-code/tests/reference/providers/error/discard_detail.rs b/example-code/tests/reference/providers/error/discard_detail.rs index 7d95900e..f7a0e656 100644 --- a/example-code/tests/reference/providers/error/discard_detail.rs +++ b/example-code/tests/reference/providers/error/discard_detail.rs @@ -6,7 +6,9 @@ /// Here a base error is raised and then wrapped with a detail string; because the wrapper is /// `DiscardDetail`, the detail is discarded and the base error propagates unchanged. pub mod wrapping_by_discarding { - use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapperComponent}; + use cgp::core::error::{ + ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapperComponent, + }; use cgp::extra::error::{DiscardDetail, RaiseFrom}; use cgp::prelude::*; diff --git a/example-code/tests/reference/providers/error/display_error.rs b/example-code/tests/reference/providers/error/display_error.rs index 79c0e3ec..333722c8 100644 --- a/example-code/tests/reference/providers/error/display_error.rs +++ b/example-code/tests/reference/providers/error/display_error.rs @@ -50,6 +50,9 @@ pub mod formatting_through_display { fn a_parse_error_is_carried_as_its_display_message() { assert_eq!(App.parse("42").unwrap(), 42); // The `Display` of `ParseIntError` reads "invalid digit found in string". - assert_eq!(App.parse("nope").unwrap_err(), "invalid digit found in string"); + assert_eq!( + App.parse("nope").unwrap_err(), + "invalid digit found in string" + ); } } diff --git a/example-code/tests/reference/providers/error/raise_from.rs b/example-code/tests/reference/providers/error/raise_from.rs index c66bd55a..a4a045fc 100644 --- a/example-code/tests/reference/providers/error/raise_from.rs +++ b/example-code/tests/reference/providers/error/raise_from.rs @@ -59,7 +59,13 @@ pub mod raising_through_from { #[test] fn a_string_is_converted_and_a_parse_error_is_formatted() { assert_eq!(App.parse_port("8080").unwrap(), 8080); - assert_eq!(App.parse_port("70000").unwrap_err(), "port 70000 out of range"); - assert!(App.parse_port("nope").unwrap_err().contains("ParseIntError")); + assert_eq!( + App.parse_port("70000").unwrap_err(), + "port 70000 out of range" + ); + assert!(App + .parse_port("nope") + .unwrap_err() + .contains("ParseIntError")); } } diff --git a/example-code/tests/reference/providers/error/return_error.rs b/example-code/tests/reference/providers/error/return_error.rs index 7eff7232..134da5b8 100644 --- a/example-code/tests/reference/providers/error/return_error.rs +++ b/example-code/tests/reference/providers/error/return_error.rs @@ -73,7 +73,9 @@ pub mod returning_the_error_itself { assert_eq!(App.check("8080").unwrap(), 8080); assert_eq!( App.check("0").unwrap_err(), - AppError { message: "port 0 is reserved".to_owned() }, + AppError { + message: "port 0 is reserved".to_owned() + }, ); } } diff --git a/example-code/tests/reference/providers/handler/pipe_handlers.rs b/example-code/tests/reference/providers/handler/pipe_handlers.rs index 166e3482..7a352502 100644 --- a/example-code/tests/reference/providers/handler/pipe_handlers.rs +++ b/example-code/tests/reference/providers/handler/pipe_handlers.rs @@ -67,7 +67,11 @@ pub mod a_pipeline_of_field_readers { fn the_stages_run_left_to_right() { use cgp::extra::handler::CanCompute; - let app = App { foo: 2, bar: 3, baz: 4 }; + let app = App { + foo: 2, + bar: 3, + baz: 4, + }; // ((5 * 2) + 3) * 4 assert_eq!(app.compute(PhantomData::<()>, 5u64), 52); } diff --git a/example-code/tests/reference/providers/handler/promote_handler.rs b/example-code/tests/reference/providers/handler/promote_handler.rs index 5f91fe69..cbab4873 100644 --- a/example-code/tests/reference/providers/handler/promote_handler.rs +++ b/example-code/tests/reference/providers/handler/promote_handler.rs @@ -45,6 +45,9 @@ pub mod filling_the_family_from_a_handler { let code = PhantomData::<()>; assert_eq!(block_on(app.handle(code, (1u64, 2u64))), Ok(3)); - assert_eq!(block_on(app.handle(code, (u64::MAX, 1u64))), Err("overflow".to_owned())); + assert_eq!( + block_on(app.handle(code, (u64::MAX, 1u64))), + Err("overflow".to_owned()) + ); } } diff --git a/example-code/tests/reference/providers/handler/promote_try_computer.rs b/example-code/tests/reference/providers/handler/promote_try_computer.rs index f5b85670..799dcf54 100644 --- a/example-code/tests/reference/providers/handler/promote_try_computer.rs +++ b/example-code/tests/reference/providers/handler/promote_try_computer.rs @@ -46,7 +46,10 @@ pub mod filling_the_family_from_a_try_computer { let code = PhantomData::<()>; assert_eq!(app.try_compute(code, (1u64, 2u64)), Ok(3)); - assert_eq!(app.try_compute(code, (u64::MAX, 1u64)), Err("overflow".to_owned())); + assert_eq!( + app.try_compute(code, (u64::MAX, 1u64)), + Err("overflow".to_owned()) + ); assert_eq!(block_on(app.handle(code, (1u64, 2u64))), Ok(3)); } } diff --git a/example-code/tests/reference/providers/handler/try_promote.rs b/example-code/tests/reference/providers/handler/try_promote.rs index a189b999..8beab3c7 100644 --- a/example-code/tests/reference/providers/handler/try_promote.rs +++ b/example-code/tests/reference/providers/handler/try_promote.rs @@ -44,6 +44,9 @@ pub mod unwrapping_a_result_output { let code = PhantomData::<()>; assert_eq!(app.try_compute(code, (1u64, 2u64)), Ok(3)); - assert_eq!(app.try_compute(code, (u64::MAX, 1u64)), Err("overflow".to_owned())); + assert_eq!( + app.try_compute(code, (u64::MAX, 1u64)), + Err("overflow".to_owned()) + ); } } diff --git a/example-code/tests/reference/providers/handler/use_input_delegate.rs b/example-code/tests/reference/providers/handler/use_input_delegate.rs index 379e71ed..3cde51a9 100644 --- a/example-code/tests/reference/providers/handler/use_input_delegate.rs +++ b/example-code/tests/reference/providers/handler/use_input_delegate.rs @@ -56,7 +56,13 @@ pub mod dispatching_on_the_input_type { let code = PhantomData::<()>; assert_eq!( - app.compute(code, Rectangle { width: 3.0, height: 4.0 }), + app.compute( + code, + Rectangle { + width: 3.0, + height: 4.0 + } + ), 12.0, ); diff --git a/example-code/tests/reference/providers/mod.rs b/example-code/tests/reference/providers/mod.rs index 097bef3b..b613a799 100644 --- a/example-code/tests/reference/providers/mod.rs +++ b/example-code/tests/reference/providers/mod.rs @@ -4,8 +4,8 @@ //! or reviewed rather than the section's full inventory. pub mod chain_getters; -pub mod error; pub mod dispatch; +pub mod error; pub mod handler; pub mod monad; pub mod redirect_lookup; diff --git a/example-code/tests/reference/traits/concat_product.rs b/example-code/tests/reference/traits/concat_product.rs index e403f82e..976e9616 100644 --- a/example-code/tests/reference/traits/concat_product.rs +++ b/example-code/tests/reference/traits/concat_product.rs @@ -21,10 +21,10 @@ pub mod examples { pub fn assert_full( fields: Full, ) -> Product![ - Field, - Field, - Field, - ] { + Field, + Field, + Field, + ] { fields } diff --git a/example-code/tests/reference/traits/has_builder.rs b/example-code/tests/reference/traits/has_builder.rs index ef192b8f..f610866b 100644 --- a/example-code/tests/reference/traits/has_builder.rs +++ b/example-code/tests/reference/traits/has_builder.rs @@ -11,23 +11,20 @@ pub mod examples { use cgp::prelude::*; // `build_from` walks the *source's* field list, so the source needs `HasFields` too. - #[derive(HasFields, BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(HasFields, BuildField, Debug, Eq, PartialEq)] pub struct FooBar { pub foo: u64, pub bar: String, } - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct FooBarBaz { pub foo: u64, pub bar: String, pub baz: bool, } - #[derive(BuildField)] - #[derive(Debug, Eq, PartialEq)] + #[derive(BuildField, Debug, Eq, PartialEq)] pub struct Person { pub first_name: String, pub last_name: String, diff --git a/example-code/tests/reference/traits/map_fields.rs b/example-code/tests/reference/traits/map_fields.rs index 7cebe2ea..e85fb86f 100644 --- a/example-code/tests/reference/traits/map_fields.rs +++ b/example-code/tests/reference/traits/map_fields.rs @@ -35,7 +35,9 @@ pub mod examples { fields } - pub fn assert_nothing(fields: >::Mapped) -> Product![(), (), ()] { + pub fn assert_nothing( + fields: >::Mapped, + ) -> Product![(), (), ()] { fields } } From eca67a21a031dd5670da4e9b3bb1244c6ac407da Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 15 Sep 2026 10:49:30 +0000 Subject: [PATCH 076/516] Mirror the `cgp_namespace!` reference page in example-code Add one module per code-bearing heading of the page, including the header-only `new Child: Parent` form, and four compile-fail fixtures for the errors the page quotes and for a stray token after a braceless header. Co-Authored-By: Claude Fable 5.1 --- example-code/README.md | 2 +- ...space_common_mistakes_inheritance_cycle.rs | 9 + ...e_common_mistakes_inheritance_cycle.stderr | 41 +++ ...mespace_common_mistakes_self_inheriting.rs | 7 + ...ace_common_mistakes_self_inheriting.stderr | 7 + ...e_common_mistakes_two_namespaces_joined.rs | 18 + ...mmon_mistakes_two_namespaces_joined.stderr | 15 + ...ce_inheriting_from_a_parent_stray_token.rs | 8 + ...nheriting_from_a_parent_stray_token.stderr | 5 + .../tests/reference/macros/cgp_namespace.rs | 323 ++++++++++++++++++ example-code/tests/reference/macros/mod.rs | 1 + 11 files changed, 435 insertions(+), 1 deletion(-) create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.stderr create mode 100644 example-code/tests/reference/macros/cgp_namespace.rs diff --git a/example-code/README.md b/example-code/README.md index 45c30362..92c11bf3 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -30,7 +30,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, `macros/cgp_namespace.md` and `macros/delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs new file mode 100644 index 00000000..12839498 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// A inherits B and B inherits A, so each forwarding impl's `where` clause requires the other and +// the trait solver overflows at both definitions. +cgp_namespace! { new A: B {} } + +cgp_namespace! { new B: A {} } + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.stderr new file mode 100644 index 00000000..58419560 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.stderr @@ -0,0 +1,41 @@ +error[E0275]: overflow evaluating the requirement `__Key__: A<__BComponents>` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs:5:1 + | +5 | cgp_namespace! { new A: B {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`$CRATE`) +note: required for `__Key__` to implement `B<__AComponents>` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs:7:1 + | +7 | cgp_namespace! { new B: A {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required for `__Key__` to implement `A<__AComponents>` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs:5:1 + | +5 | cgp_namespace! { new A: B {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: 3 redundant requirements hidden + = note: required for `__Key__` to implement `B<__Table__>` + = note: this error originates in the macro `cgp_namespace` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0275]: overflow evaluating the requirement `__Key__: B<__AComponents>` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs:7:1 + | +7 | cgp_namespace! { new B: A {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`$CRATE`) +note: required for `__Key__` to implement `A<__BComponents>` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs:5:1 + | +5 | cgp_namespace! { new A: B {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required for `__Key__` to implement `B<__BComponents>` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs:7:1 + | +7 | cgp_namespace! { new B: A {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: 3 redundant requirements hidden + = note: required for `__Key__` to implement `A<__Table__>` + = note: this error originates in the macro `cgp_namespace` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs new file mode 100644 index 00000000..bcf26b83 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs @@ -0,0 +1,7 @@ +use cgp::prelude::*; + +// A namespace inheriting itself does not overflow; its forwarding impl has a value parameter +// nothing can determine. +cgp_namespace! { new A: A {} } + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr new file mode 100644 index 00000000..8a75c1f5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr @@ -0,0 +1,7 @@ +error[E0207]: the type parameter `__Value__` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs:5:1 + | +5 | cgp_namespace! { new A: A {} } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unconstrained type parameter + | + = note: this error originates in the macro `cgp_namespace` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.rs b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.rs new file mode 100644 index 00000000..519d03d5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.rs @@ -0,0 +1,18 @@ +use cgp::prelude::*; + +cgp_namespace! { new FirstNamespace {} } + +cgp_namespace! { new SecondNamespace {} } + +pub struct App; + +// Each `namespace` line emits a blanket `DelegateComponent` impl covering every key, so the two +// forwarding impls overlap. +delegate_components! { + App { + namespace FirstNamespace; + namespace SecondNamespace; + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.stderr new file mode 100644 index 00000000..4e499e23 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.stderr @@ -0,0 +1,15 @@ +error[E0119]: conflicting implementations of trait `DelegateComponent<_>` for type `App` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.rs:14:19 + | +13 | namespace FirstNamespace; + | -------------- first implementation here +14 | namespace SecondNamespace; + | ^^^^^^^^^^^^^^^ conflicting implementation for `App` + +error[E0119]: conflicting implementations of trait `IsProviderFor<_, _, _>` for type `App` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.rs:14:19 + | +13 | namespace FirstNamespace; + | -------------- first implementation here +14 | namespace SecondNamespace; + | ^^^^^^^^^^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.rs b/example-code/tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.rs new file mode 100644 index 00000000..0ca21199 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.rs @@ -0,0 +1,8 @@ +use cgp::prelude::*; + +cgp_namespace! { new BaseNamespace {} } + +// A header may be followed by a braced table or by nothing. A `;` is neither. +cgp_namespace! { new ExtendedNamespace: BaseNamespace; } + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.stderr new file mode 100644 index 00000000..705f9a25 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.stderr @@ -0,0 +1,5 @@ +error: expected curly braces + --> tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.rs:6:54 + | +6 | cgp_namespace! { new ExtendedNamespace: BaseNamespace; } + | ^ diff --git a/example-code/tests/reference/macros/cgp_namespace.rs b/example-code/tests/reference/macros/cgp_namespace.rs new file mode 100644 index 00000000..5fcf82a3 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_namespace.rs @@ -0,0 +1,323 @@ +//! Code from `docs/reference/macros/cgp_namespace.md` — *`cgp_namespace!`*. + +/// ## Overview +/// +/// The opening snippet: a namespace lifted out of any one context. The page elides the body as +/// `// shared wiring lives here`; it is empty here, since the shared wiring is the subject of the +/// sections below. +pub mod overview { + use cgp::prelude::*; + + cgp_namespace! { + new AppNamespace { + // The page elides the body. Nothing is wired here. + } + } +} + +/// ## Usage +/// +/// The `new` namespace with one redirect. The page names `FooProviderComponent` and +/// `MyFooComponent` without declaring them, so the component and the path marker are declared +/// here, and a context joins the namespace and binds the redirected path so the route can be +/// checked end to end. +pub mod usage { + use cgp::prelude::*; + + #[cgp_component(FooProvider)] + pub trait Foo { + fn foo(&self) -> String; + } + + #[cgp_impl(new DummyFoo)] + impl FooProvider { + fn foo(&self) -> String { + "foo".to_owned() + } + } + + /// The type the `@MyFooComponent` path segment names. + pub struct MyFooComponent; + + cgp_namespace! { + new MyNamespace { + FooProviderComponent => + @MyFooComponent, + } + } + + pub struct App; + + delegate_components! { + App { + namespace MyNamespace; + + @MyFooComponent: DummyFoo, + } + } + + mod check_app { + use super::*; + check_components! { App { FooProviderComponent } } + } + + #[test] + fn the_redirect_lands_on_the_bound_path() { + assert_eq!(App.foo(), "foo"); + } +} + +/// ## Inheriting from a parent +/// +/// The child that rewrites the `@cgp.core.error` prefix onto `@app`, and the header-only child +/// with nothing of its own to add. The page does not declare `BaseNamespace`; here it inherits +/// `DefaultNamespace`, which is where CGP's error components register under `@cgp.core.error`, so +/// the rewrite has a subtree to reroute and a joining context can wire the error components under +/// the shorter `@app.*` path. +pub mod inheriting_from_a_parent { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + cgp_namespace! { new BaseNamespace: DefaultNamespace {} } + + cgp_namespace! { + new ExtendedNamespace: BaseNamespace { + @cgp.core.error => + @app, + } + } + + pub struct App; + + delegate_components! { + App { + namespace ExtendedNamespace; + + @app.ErrorTypeProviderComponent: UseType, + @app.ErrorRaiserComponent.String: RaiseFrom, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ErrorTypeProviderComponent, + ErrorRaiserComponent: String, + } + } + } + + /// The braceless header. It expands to what `new ExtendedNamespace: BaseNamespace {}` does, + /// so a context joining it resolves everything `BaseNamespace` does, and the error components + /// stay under their full `@cgp.core.error.*` path because nothing rewrites it. + pub mod header_only { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + use super::BaseNamespace; + + cgp_namespace! { + new ExtendedNamespace: BaseNamespace + } + + pub struct App; + + delegate_components! { + App { + namespace ExtendedNamespace; + + @cgp.core.error.ErrorTypeProviderComponent: UseType, + @cgp.core.error.ErrorRaiserComponent.String: RaiseFrom, + } + } + + mod check_app { + use super::*; + check_components! { + App { + ErrorTypeProviderComponent, + ErrorRaiserComponent: String, + } + } + } + } +} + +/// ## The other two halves: registering, and joining +/// +/// A component registered under a prefix, and a context joining the namespace and binding the +/// prefixed path. `AppNamespace` and `ShowWithDebug` are named by the page without being declared +/// in this section (the provider appears under *Examples*), so both are declared here. +pub mod the_other_two_halves_registering_and_joining { + use cgp::prelude::*; + + cgp_namespace! { new AppNamespace {} } + + #[cgp_component(ShowImpl)] + #[prefix(@show in AppNamespace)] + pub trait CanShow { + fn show(&self) -> String; + } + + #[cgp_impl(new ShowWithDebug)] + #[uses(core::fmt::Debug)] + impl ShowImpl { + fn show(&self) -> String { + format!("{:?}", self) + } + } + + #[derive(Debug)] + pub struct MyApp; + + delegate_components! { + MyApp { + namespace AppNamespace; + + @show.ShowImplComponent: ShowWithDebug, + } + } + + mod check_my_app { + use super::*; + check_components! { MyApp { ShowImplComponent } } + } +} + +/// ## Examples +/// +/// The complete program, exactly as the page shows it, followed by the inheritance example. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(ShowImpl)] + #[prefix(@show in AppNamespace)] + pub trait CanShow { + fn show(&self) -> String; + } + + #[cgp_impl(new ShowWithDebug)] + #[uses(core::fmt::Debug)] + impl ShowImpl { + fn show(&self) -> String { + format!("{:?}", self) + } + } + + cgp_namespace! { + new AppNamespace {} + } + + #[derive(Debug)] + pub struct MyApp; + + delegate_components! { + MyApp { + namespace AppNamespace; + + @show.ShowImplComponent: ShowWithDebug, + } + } + + check_components! { + MyApp { + ShowImplComponent, + } + } + + #[test] + fn the_context_owns_the_provider() { + assert_eq!(MyApp.show(), "MyApp"); + } + + /// The inheritance example. The page continues from the program above with the component + /// registered into the base; a context joining the header-only child inherits the whole chain, + /// so the component is re-declared here with its prefix in `BaseNamespace`. + pub mod inheritance { + use cgp::prelude::*; + + #[cgp_component(ShowImpl)] + #[prefix(@show in BaseNamespace)] + pub trait CanShow { + fn show(&self) -> String; + } + + #[cgp_impl(new ShowWithDebug)] + #[uses(core::fmt::Debug)] + impl ShowImpl { + fn show(&self) -> String { + format!("{:?}", self) + } + } + + cgp_namespace! { new BaseNamespace {} } + + cgp_namespace! { new ExtendedNamespace: BaseNamespace } + + #[derive(Debug)] + pub struct MyApp; + + delegate_components! { + MyApp { + namespace ExtendedNamespace; + + @show.ShowImplComponent: ShowWithDebug, + } + } + + mod check_my_app { + use super::*; + check_components! { MyApp { ShowImplComponent } } + } + + #[test] + fn the_child_inherits_the_chain() { + assert_eq!(MyApp.show(), "MyApp"); + } + } +} + +/// ## Under the hood +/// +/// The input whose expansion the page walks through. Only the input is checked here; the generated +/// items the page shows are the job of `cargo cgp expand`, which this crate does not replace. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_component(FooProvider)] + pub trait Foo { + fn foo(&self) -> String; + } + + pub struct MyFooComponent; + + cgp_namespace! { + new MyNamespace { + FooProviderComponent => + @MyFooComponent, + } + } +} + +/// ## Common Mistakes +/// +/// The page quotes four errors; three carry a snippet the compiler must refuse, each a trybuild +/// fixture. The fourth, a registered component with no provider bound anywhere, is the fixture on +/// the `#[prefix(...)]` page. +/// +/// Joining two namespaces on one context, `E0119` — +/// `tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.rs`. +/// +/// Two namespaces inheriting each other, `E0275` — +/// `tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_inheritance_cycle.rs`. +/// +/// A namespace inheriting itself, `E0207` — +/// `tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs`. +/// +/// The *Inheriting from a parent* section also states that only the end of the input may follow a +/// header written without braces; the macro's `expected curly braces` rejection of a stray token is +/// `tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.rs`. +pub mod common_mistakes {} diff --git a/example-code/tests/reference/macros/mod.rs b/example-code/tests/reference/macros/mod.rs index b992d150..274d7c38 100644 --- a/example-code/tests/reference/macros/mod.rs +++ b/example-code/tests/reference/macros/mod.rs @@ -1,3 +1,4 @@ //! Code from the pages under `docs/reference/macros/`. +pub mod cgp_namespace; pub mod delegate_components; From fe06a0d5e04f3f2226e16f2fe793555de5ca2117 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 19 Sep 2026 10:58:10 +0000 Subject: [PATCH 077/516] docs: clarify CGP concept explanations --- docs/concepts/abstract-types.md | 169 +++++++------ docs/concepts/aggregate-providers.md | 145 +++++------ docs/concepts/check-traits.md | 185 +++++++------- docs/concepts/coherence.md | 219 +++++++--------- docs/concepts/consumer-and-provider-traits.md | 236 ++++++++---------- docs/concepts/dispatching.md | 153 +++++++----- docs/concepts/extensible-records.md | 150 ++++++----- docs/concepts/extensible-variants.md | 171 +++++++------ docs/concepts/handlers.md | 202 ++++++++------- docs/concepts/higher-order-providers.md | 171 +++++++------ docs/concepts/impl-side-dependencies.md | 213 ++++++++-------- docs/concepts/index.md | 114 +++++---- example-code/tests/concepts/coherence.rs | 144 +++-------- 13 files changed, 1113 insertions(+), 1159 deletions(-) diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index 0a42a044..3a3bb08a 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -5,18 +5,15 @@ sidebar_position: 5 # Abstract types -Naming a type in generic code, such as an error type, a scalar, or a runtime, and letting each context -decide what it actually is. - -This page answers *how does code name a type it does not choose?* It starts from the ordinary Rust -feature that already does this, shows what CGP adds to it, and works through the two things abstract -types buy: a type several pieces of code can agree on, and signatures that stop growing. It closes on -the costs, which are mostly about what an abstract type is *not*. +An **abstract type** lets generic code name a type while each context chooses its concrete form. +Several providers can share the same scalar or error type without taking a separate type parameter +for it. This page starts with Rust's associated types, explains how CGP wires and shares them, and +ends with the limits of that abstraction. ## Rust already has this -An abstract type in CGP is an ordinary associated type: a type a trait names but leaves each implementer -to fill in. It is worth starting there, because half of what follows is a feature you already use: +Rust's associated types let a trait name a type that each implementer supplies. For example, +`HasScalarType` can leave the scalar open while two contexts make different choices: ```rust pub trait HasScalarType { @@ -32,19 +29,18 @@ impl HasScalarType for Embedded { } ``` -Generic code names `Context::Scalar` and never commits to `f32` or `f64`. Each type answers for itself, -the compiler resolves the answer where a concrete type is known, and nothing costs anything at runtime. -That is the whole idea, and CGP does not replace it. A context can implement an abstract-type trait -directly, exactly as above, and everything else on this page still works. +Generic code with a `Context: HasScalarType` bound can use `Context::Scalar` without choosing `f32` +or `f64`. The compiler resolves that associated type when the context is known. CGP uses this same +mechanism, and a context can implement an abstract-type trait directly as shown above. -The *direction* is worth noticing. A generic parameter is an input the caller supplies; an -associated type is an output the implementing type determines. That difference is small in one function -and decides how a codebase ages, which the last section of this page is about. +A generic parameter lets a caller choose a type for each use; an associated type ties the choice to +an implementing type. With `HasScalarType`, every use of `HighPrecision::Scalar` means `f64`. +That shared choice becomes useful when several providers need to agree on a type. ## Choosing the type by wiring -What CGP adds is that the choice can be made in the same place as every other choice a context makes. -[`#[cgp_type]`](/docs/reference/macros/cgp_type) turns an abstract-type trait into a component: +CGP lets a context select its associated types in the same table as its behavior providers. +[`#[cgp_type]`](/docs/reference/macros/cgp_type) turns an associated-type trait into a component: ```rust #[cgp_type] @@ -53,7 +49,8 @@ pub trait HasScalarType { } ``` -and a context then names its concrete type in its wiring table rather than in a hand-written impl: +The generated `ScalarTypeProviderComponent` is the wiring key, and `UseType` supplies the concrete +type. These tables make the same choices as the direct implementations above: ```rust delegate_components! { @@ -69,27 +66,19 @@ delegate_components! { } ``` -`UseType` says "the type is `f64`", and that is all it says. Every abstract type is answered the -same trivial way, so `#[cgp_type]` generates that answer once and a context supplies the type as an -argument to it. The bound on the associated type carries through, and the compiler enforces it on -whatever the context chooses: wiring `UseType` against a `Copy` scalar is an error reading -`the trait bound String: Copy is not satisfied`. Like every other wiring choice it is -[checked lazily](./check-traits.md), so that error appears where the component is checked or used rather -than on the wiring line itself. +`UseType` sets `Scalar` to `f64`. The macro generates the provider implementation that makes +this work, so the context only needs to name the type. Other providers can compute the choice from +further type information, but `UseType` suffices for a fixed choice. -This is a small win on its own. It buys two things. A context's type choices sit beside its behaviour -choices, in one table, rather than scattered across `impl` blocks. And a type can be chosen by -something more interesting than a fixed answer, since `UseType` is just one provider among the ones a -component can be wired to. +The selected type must satisfy the associated type's bounds. Here `Scalar: Copy` accepts `f32` and +`f64`, but rejects `String`. Wiring `UseType` would produce a `String: Copy` error when the +component is checked or used. Like other component wiring, the table is +[checked lazily](./check-traits.md). ## One type, agreed on by everything that needs it -The idea compounds as soon as more than one piece of code needs the same type, because they all name the -*same* `Self::Scalar` and the context fixes it once. - -That matters most when the code that needs the type is generic over something else entirely. A shape -calculator works over rectangles, circles, and whatever else, and none of those shapes should have to -carry a scalar type or agree with the others about one: +Providers that refer to the same context's `Scalar` share one type choice. An area-calculation +component can use this to return a common scalar for several shape types: ```rust #[cgp_component(ShapeAreaCalculator)] @@ -99,19 +88,35 @@ pub trait CanCalculateShapeArea { } ``` -`Rectangle` declares nothing. The application declares the scalar, every shape interoperates through it, -and switching the application from `UseType` to `UseType` changes the arithmetic for every -shape at once. The application here is a type standing for the program rather than a piece of data, and -`struct App;` with no fields is a complete one, which is the shape most CGP code is in. +Here the context represents an application, while `Shape` is the data being measured. The application +chooses the result type through `HasScalarType`; the shape types do not need to implement that trait. +A fieldless `struct App;` can serve as the context if its providers need only its type choices and wiring. + +Changing the application's wiring from `UseType` to `UseType` changes the declared result +type for every shape. The selected providers must support that choice: a provider restricted to +`Scalar = f64` cannot also serve a context that selects `f32`. Abstracting the result type does not +supply conversions or arithmetic implementations automatically. + +`#[use_type(HasScalarType.Scalar)]` lets the signature use `Scalar` as a local shorthand for +`::Scalar`. It also adds the required trait bound. On this component, that +bound is part of the interface because its return type depends on it. + +## Type dependencies without extra parameters -The `#[use_type(HasScalarType.Scalar)]` line lets the signature say `Scalar` instead of -`::Scalar`. It imports the type and adds the requirement in one line, and it -reads like a `use` for a type because it is one. +A context can collect type choices that would otherwise become separate generic parameters. +Code that needs a scalar refers to `Context::Scalar`; it does not need an additional `Scalar` +parameter alongside `Context`. Providers can use the same approach for an error type or a runtime. -## The canonical one: a context's error type +An implementation can keep a type dependency out of its caller's interface when the type is used +only inside the implementation. If the type appears in a public argument or result, the interface +must expose enough information to name it, as `CanCalculateShapeArea` does above. +[Impl-side dependencies](./impl-side-dependencies.md) explains that distinction. -The abstract type CGP leans on hardest is the error type, and it is the clearest case of code naming -something it refuses to choose: +## A shared error type {#the-canonical-one-a-contexts-error-type} + +`HasErrorType` gives fallible providers a common error type selected by their context. A provider +can report a concrete source error through `CanRaiseError` while returning the context's abstract +`Error`: ```rust #[cgp_component(Loader)] @@ -133,56 +138,54 @@ impl Loader { } ``` -`LoadOrFail` fails, and never learns what failing means in this application. The context decides, -whether `anyhow::Error`, a domain enum, or a plain `String`, and every fallible provider in that context -refers to the same one, so errors compose instead of needing conversion at each boundary. -[Modular error handling](./modular-error-handling.md) is the page for what else follows from that. +`LoadOrFail` reports an empty path without choosing the application's error representation. +The context supplies both the error type and a provider that converts the source `String` into it. +The resulting type could be `anyhow::Error`, a domain enum, or `String`, provided the selected +conversion supports it. + +Providers that return this context's `Error` can pass errors between them without converting at +every boundary. Errors from external libraries still need conversion into that common type. +[Modular error handling](./modular-error-handling.md) develops this example further. -## Two things called `UseType` +## The provider and the import attribute {#two-things-called-usetype} -One collision is worth naming before you meet it in a compiler error, because the two are complementary -and easy to conflate. **`UseType` is a provider**: it goes in a wiring table and says what a -context's abstract type is. **`#[use_type(...)]` is an attribute**: it goes on a definition and imports -somebody's abstract type so the code can name it as a bare alias. +`UseType` and `#[use_type(...)]` perform complementary jobs despite their similar names: -A context uses the first; code that consumes an abstract type uses the second. They appear in the same -program constantly and never in the same position. +- **`UseType`:** A provider placed in a wiring table to select a concrete type. +- **`#[use_type(...)]`:** An attribute placed on a definition to import an associated type and its bound. + +The wiring chooses the type; the import lets generic code refer to that choice by a short name. ## What it costs -**It is deferral, not encapsulation.** An abstract type leaves the choice open; it does not hide the -answer. Once a context wires `UseType`, code with that context in hand sees `f64` and can do -anything `f64` allows. If the goal is that callers must *not* know the representation, that is Rust's -module privacy, and an abstract type is the wrong tool for it. That distinction is worth being precise -about with anyone arriving from ML modules. +An abstract type defers the concrete choice without hiding its representation. Code that knows +`HighPrecision` uses `f64` can use the operations available on `f64`. Use Rust's module privacy when +callers must not access a representation. -**A bound on the associated type is the only thing generic code can rely on.** `type Scalar: Copy` means -generic code can copy a scalar and nothing else: no arithmetic and no comparison, unless those bounds are -declared too. Adding one later is a change every context has to satisfy, so the bounds are worth -thinking about when the trait is written. +Generic code can rely only on the bounds available where it uses the type. `Scalar: Copy` permits +copying but does not imply arithmetic or comparison. Those operations need additional bounds on the +associated type or on the code that uses it. Adding a bound to the trait requires every context's +chosen type to satisfy it. -**The type is one per context, not one per use.** All the code in a context sharing one `Error` is the -point, and it is also a constraint: a context needing two genuinely different error types needs two -components, or two contexts. +A non-generic abstract-type trait supplies one choice per context. If one context needs distinct +error types for separate purposes, represent those choices with separate components or a tagged +component, or use separate contexts. -**And it is another thing that can be left unwired.** A context that never names its error type compiles -until something needs one, at which point the failure is a missing type rather than a missing field, and -looks much the same. [`check_components!`](/docs/reference/macros/check_components) catches it at the -wiring line, like everything else. +An abstract-type component can remain unwired until a use exposes the missing choice. Add +[`check_components!`](/docs/reference/macros/check_components) beside the context's wiring to verify +that the required type is available and satisfies its bounds. ## Where to go next -[Impl-side dependencies](./impl-side-dependencies.md) puts this page in its place: an abstract type is -the type-shaped version of a requirement stated on the implementation, beside the capability leg and the -value leg. [Implicit arguments](./implicit-arguments.md) is that value leg. - -[Modular error handling](./modular-error-handling.md) develops the canonical case at length: the error -type, how a foreign error becomes it, and what detail it carries, as three separate choices. +These pages explain related dependencies and the constructs used here: -For the constructs, [`#[cgp_type]`](/docs/reference/macros/cgp_type) defines an abstract-type component, -[`UseType`](/docs/reference/providers/use_type) supplies the concrete type in a wiring table, -[`#[use_type]`](/docs/reference/attributes/use_type) imports one into a definition, and -[`HasType`](/docs/reference/components/has_type) is the built-in component the rest is built on. +- [Impl-side dependencies](./impl-side-dependencies.md): Which requirements can stay inside a provider. +- [Implicit arguments](./implicit-arguments.md): How a provider obtains values from its context. +- [Modular error handling](./modular-error-handling.md): Sharing, constructing, and enriching errors. +- [`#[cgp_type]`](/docs/reference/macros/cgp_type) and + [`UseType`](/docs/reference/providers/use_type): Declaring and selecting an abstract type. +- [`#[use_type]`](/docs/reference/attributes/use_type): Importing an associated type into a definition. +- [`HasType`](/docs/reference/components/has_type): The built-in component for tagged type choices. --- diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index 54f932d9..63a96730 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -5,18 +5,15 @@ sidebar_position: 8 # Aggregate providers -Bundling a group of wiring choices into one reusable provider that other contexts adopt as a unit. - -This page answers *how do several contexts share a set of choices without repeating them?* It shows the -bundle, traces a call through it to establish the one fact everything else follows from, and ends on the -rule about checking, which is the only place a bundle behaves unlike anything else. It closes on when to -reach for the heavier alternative instead. +An **aggregate provider** bundles wiring choices so several contexts can reuse them. Each context +names the bundle for the components it needs, and the bundled providers still operate on that context. +This page explains how delegation preserves the context, where to check the result, and when a +namespace is a better fit. ## A table whose target is not a context -A wiring table usually belongs to a context. It does not have to. - -Add `new` and the table gets a fresh type of its own: +`delegate_components!` can give a wiring table to a provider type. The `new` keyword declares that +type alongside its table: ```rust delegate_components! { @@ -27,11 +24,11 @@ delegate_components! { } ``` -`GeometryComponents` is an **aggregate provider**: a zero-sized type whose entire content is that table. -Nothing constructs it, it holds no data, and it does not stand for an application. It is a name for a -group of decisions, so that the decisions can be adopted together. +`GeometryComponents` groups the choices of `RectangleArea` and `RectanglePerimeter` under one name. +It is a zero-sized marker used for delegation; the program does not construct it or store data in it. +The context remains the type whose data those providers use. -A context then takes the whole group in one line: +A context adopts the group by delegating the relevant components to the bundle: ```rust delegate_components! { @@ -44,51 +41,48 @@ delegate_components! { } ``` -`Rectangle` now has both capabilities, and the choices behind them live in one place. Change the bundle -and every context using it changes with it. +`Rectangle` gets both capabilities if it meets the bundled providers' requirements. The provider +choices live in `GeometryComponents`, so changing that table changes the choices for every context +that delegates those components to it. ## The context stays the context -Everything else on this page follows from one fact, and tracing a call is the quickest way to establish -it. When `rectangle.area()` resolves: +Delegation through a bundle preserves the original context. The compiler resolves +`rectangle.area()` through this chain: -- `Rectangle` gets the capability because it implements the provider trait *for itself*; -- it implements that because its table sends the component to `GeometryComponents`; -- and `GeometryComponents` implements it because *its* table sends the component to `RectangleArea`. +1. `Rectangle` delegates `AreaCalculatorComponent` to `GeometryComponents`. +2. `GeometryComponents` delegates the same component to `RectangleArea`. +3. `RectangleArea` calculates the area using `Rectangle` as its context. -At every step the context is `Rectangle`. `GeometryComponents` only ever appears as the thing being -delegated to. So when `RectangleArea` reads a `width`, it reads it from `Rectangle`. The bundle has no -`width`, is never asked for one, and would not be consulted if it had one. +When `RectangleArea` reads `width` and `height`, it reads them from `Rectangle`. The bundle selects +the implementation but does not supply the field values. Another context can reuse the bundle if it +satisfies the same provider requirements. -This is why a bundle is a *provider* rather than a context: it is something delegated **to**, never -something used **as**. Bundles nest for the same reason: a table entry may name another table, and -resolution walks each in turn while the context argument stays fixed on the real context at the end of -the chain. +Bundles can delegate to other bundles using the same mechanism. The compiler follows each table +while keeping the context argument fixed. It resolves the entire chain at compile time, without a +runtime lookup for each table. ## Checking a bundle asks the wrong question -There is one place a bundle behaves unlike anything else, and it is worth knowing before you meet it. +Checking a bundle as a context does not verify that an application can use it. In particular, +[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) checks the +type receiving the table. Applied to `GeometryComponents`, it asks whether the bundle itself can +supply everything its providers require. -**Never wire a bundle with the fused -[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components).** That macro -derives a check asking whether the target can *use* each component as a context. For a bundle that is a -question about a role it never plays, so the answer carries no information, and which answer comes back -depends on what is inside: +The result depends on those requirements: -- If the bundled providers need nothing from their context, they implement the capability for *every* - context, the bundle included. The check passes. It has proved nothing, and it looks like it has. -- If a bundled provider needs a field or a type, the check fails, reporting that `GeometryComponents` - does not have a `width`, blaming the bundle for something the real context would have supplied. +- A provider without context dependencies accepts `GeometryComponents` as its context, so the check + passes without checking any application that will use the bundle. +- A provider that needs `width` fails because `GeometryComponents` lacks that field, even if + `Rectangle` supplies it correctly. -The silent case is the dangerous one. Wire a bundle with plain -[`delegate_components!`](/docs/reference/macros/delegate_components) and let it be verified where the -question means something. +Define bundles with plain [`delegate_components!`](/docs/reference/macros/delegate_components). +Verify their requirements against a context that will actually use them. ## Verifying one properly -A bundle is checked through a context that uses it. Checking `Rectangle` walks the whole chain, through -the bundle's table, down to `RectangleArea`'s requirements, against `Rectangle`'s fields, so a gap -several bundles deep still surfaces: +A check on `Rectangle` follows the bundle's delegation and checks the providers against +`Rectangle`'s fields and capabilities: ```rust check_components! { @@ -99,9 +93,11 @@ check_components! { } ``` -When the bundle itself needs pinning down, usually to find which layer of a nested stack is broken, -the [`#[check_providers]`](/docs/reference/macros/check_components) form asserts the provider-side -question instead, naming the bundle *for a concrete context*: +This verifies the full chain, including nested bundles. A missing requirement fails at the check +site even if the provider requiring it is several tables away. + +`#[check_providers]` lets you check the bundle and an individual provider separately against the +same context. This helps locate a failure within a chain: ```rust check_components! { @@ -115,52 +111,45 @@ check_components! { } ``` -Both routes go through a real context. Neither treats the bundle as one. +Each named provider gets its own assertion for `Rectangle`. The bundle is checked in the role it +serves: supplying an implementation for that context. ## When a namespace is the better tool -A bundle and a [namespace](./namespaces.md) both package reusable wiring, and they differ in how a -context takes it on. +A bundle suits a small group whose components you want to name explicitly. The entry +`[A, B]: TheBundle` shows which choices the context adopts. As the group grows, each context must +still list every component it takes from the bundle. -A context adopts a bundle by **delegating named components to it**, `[A, B]: TheBundle`, so the -context spells out which components come from where. That is direct, obvious to read, and it scales -linearly: twenty components from a bundle means twenty names in the brackets. +A [namespace](./namespaces.md) lets a context inherit shared wiring by joining a named table. +It also organizes lookups under paths, which helps when a library supplies wiring for many components. +Customization requires the namespace to leave the relevant paths unbound; a direct context entry +cannot override a key the inherited namespace already binds. -A context adopts a namespace by **joining it**, after which everything it does not wire itself falls -through, and a direct entry overrides just that key. You want that once the count is large or -the defaults should be inherited and selectively replaced. - -Reach for a bundle when the group is small and you want the delegation visible. Reach for a namespace -when the table has outgrown reading, or when a library is publishing defaults for applications to -customize. +Use a bundle for explicit delegation of a group of components. Consider a namespace when many +contexts need a shared table and a path structure that separates fixed wiring from application choices. ## What it costs -**It adds a hop.** Finding what answers a capability now means reading two tables instead of one, and -nested bundles mean more. The wiring is still explicit and still greppable, and it is one more step -between the call and the code. - -**It pays only when the repetition is real.** A bundle used by one context is a table split in two for -nothing. The threshold is a second context wanting the same group, not the anticipation of one. +A bundle adds a table to inspect when tracing a capability. Nested bundles add further tables, even +though the compiler resolves them statically. Keep a bundle when centralizing shared choices is worth +that extra reading. -**It is the construct whose checking rule is a genuine trap**, per the section above, and the failure -mode is a check that passes. Nothing in the code marks a bundle as different from a context, since both -are `delegate_components!` on a type, so the distinction has to be held by the person writing it. +A bundle used by only one context may add little value. Repeated wiring across contexts gives a +clear reason to introduce one; anticipated reuse alone may not justify it. -**And the type name carries no clue.** `GeometryComponents` is a struct like any other; only its usage -says it is a bundle. Naming the group rather than a thing, with a `…Components` suffix, is the convention -that keeps it legible. +The type system does not distinguish a bundle from a context by declaration. Both can receive a +delegation table, so the author must check the bundle against its intended context. A name such as +`GeometryComponents` helps identify its role, but does not enforce it. ## Where to go next -[Namespaces](./namespaces.md) is the heavier sibling, and the one to read if the reason you are here is -a table that has grown too long. [Consumer and provider traits](./consumer-and-provider-traits.md) is -where the provider-versus-context distinction this page rests on comes from, and -[Checking your wiring](./check-traits.md) covers both check forms in full. +These pages explain related wiring choices and checks: -For the constructs, [`delegate_components!`](/docs/reference/macros/delegate_components) defines and -consumes a bundle through its `new` keyword and its array-key form, and -[`check_components!`](/docs/reference/macros/check_components) carries `#[check_providers]`. +- [Namespaces](./namespaces.md): Sharing tables through paths and inheritance. +- [Consumer and provider traits](./consumer-and-provider-traits.md): How delegation preserves the context. +- [Checking your wiring](./check-traits.md): Context checks and checks on individual providers. +- [`delegate_components!`](/docs/reference/macros/delegate_components): The `new` and grouped-key forms. +- [`check_components!`](/docs/reference/macros/check_components): The `#[check_providers]` form. --- diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index 46065d8f..542de672 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -5,22 +5,26 @@ sidebar_position: 6 # Checking your wiring -Why a wiring mistake still compiles, and how a compile-time assertion turns the resulting error into -one that names the real cause. - -This page answers *why did my mistake not fail where I made it?* It follows one broken context through -three stages, unchecked, checked, and checked through the error toolchain, quoting what the compiler -actually reports at each. It closes on what checking does not fix, which is the honest version of CGP's -most-cited cost. +CGP wiring records provider choices without checking their requirements immediately. A compile-time +check verifies those requirements at a location you choose and helps expose missing dependencies. +This page follows one broken context from a method-call error through an explicit check and +`cargo cgp check`, then explains what each can and cannot verify. ## A context can be wrong and still compile -Wiring records a choice. It does not verify one. - -Here is an application wired to a provider that records outgoing email, and an application that has -nowhere to record it: +A wiring table can name a provider even when the context lacks a field that provider needs. +In this example, `RecordEmails` implements the `EmailSender` component by recording messages in +`sent_emails`, but `BrokenApp` supplies only `smtp_server`: ```rust +use cgp::prelude::*; +use core::cell::RefCell; + +#[cgp_component(EmailSender)] +pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); +} + #[cgp_impl(new RecordEmails)] impl EmailSender { fn send_email(&self, #[implicit] sent_emails: &RefCell>, to: &str, body: &str) { @@ -36,22 +40,19 @@ pub struct BrokenApp { delegate_components! { BrokenApp { EmailSenderComponent: RecordEmails } } ``` -`RecordEmails` needs a `sent_emails` field. `BrokenApp` has a `smtp_server`. **This compiles**, and it -is meant to: the table stores "this key points to this provider" as a type-level fact, and nothing has -asked yet whether the provider's own requirements hold for this particular context. - -That laziness is not an oversight. It lets a provider be written once against every possible -context, lets a bundle of wiring be reused by applications the bundle has never heard of, and lets a -table be assembled from pieces that never meet. Checking each entry as it was written would mean every -entry knowing its final context, which is the coupling the whole design exists to avoid. +The table compiles because it records only the mapping from `EmailSenderComponent` to `RecordEmails`. +The compiler has not yet been asked to prove that `RecordEmails` can send email for `BrokenApp`. +That proof will fail: the `#[implicit]` argument requires a `sent_emails` field. -The price is that a context can look finished and be broken. +This deferred checking lets reusable wiring exist before its final context is known. +An [aggregate provider](./aggregate-providers.md), for example, can group provider choices for +contexts defined elsewhere. Each context must satisfy the providers' requirements when it uses +them, but the bundle does not need to supply those dependencies itself. ## Where the failure surfaces instead -The compiler asks the question the first time something uses the capability, which may be in another -module, another crate, or a test somebody runs next week. And the answer arrives in a form that does -not name the problem: +An unchecked wiring error appears when code first requires the capability. A call to +`app.send_email(to, body)` on `&BrokenApp` produces an error like this abbreviated diagnostic: ```text error[E0599]: the method `send_email` exists for reference `&BrokenApp`, @@ -65,29 +66,26 @@ note: the following trait bounds were not satisfied: `BrokenApp: EmailSender` ``` -Read it closely and it says only that the capability is unavailable, restated twice. The word -`sent_emails` does not appear. Neither does anything about a field. The compiler answered the question -it was asked, *does this type have this method?*, and discarded the reasoning that produced "no" on the -way out. - -This is the single worst experience CGP offers a newcomer, and it is worth being blunt that a mis-wire -looks like this by default. +The diagnostic reports that `BrokenApp` lacks `CanSendEmail` and `EmailSender`, but does +not identify the missing `sent_emails` field. The failed requirement is hidden behind the generated +trait implementations. The error location may also be far from the wiring, in another module or crate. ## Asking the question at a line you chose -A **check** forces the same question early, at the wiring, where you can see it. It is not a new -mechanism. The plain-Rust form is a trait that demands something and an impl with nothing in it: +A check trait forces the compiler to verify a bound where you write its implementation. The basic +technique uses an ordinary Rust supertrait and an empty implementation: ```rust trait CanUseApp: CanSendEmail {} impl CanUseApp for App {} ``` -The impl has nothing to prove on its own, so it compiles exactly when `App: CanSendEmail` holds and -fails otherwise. Put it beside the table and a latent gap becomes an error on a known line. +The empty implementation compiles only if `App: CanSendEmail` holds. Placing it beside the wiring +catches the failure there, although checking the consumer trait alone can still produce the vague +error shown above. -[`check_components!`](/docs/reference/macros/check_components) writes that for you, from a list of the -components to verify: +[`check_components!`](/docs/reference/macros/check_components) generates a check that exposes the +selected provider's requirements more directly: ```rust check_components! { @@ -97,10 +95,8 @@ check_components! { } ``` -But the important part is not the convenience. A check asserts something *stronger* than the consumer -trait, and that stronger assertion changes the error. Asking "does `BrokenApp` implement -`CanSendEmail`?" gets the answer above. Asking "can `BrokenApp` use this component?" makes the compiler -evaluate the provider's actual requirements and report the one that failed: +The macro checks `CanUseComponent`, which requires a wiring entry and the selected provider's +dependency bounds for this context. That path makes the missing field visible in the diagnostic: ```text error[E0277]: the trait bound `BrokenApp: CanUseComponent` @@ -115,15 +111,16 @@ note: required for `RecordEmails` to implement `IsProviderFor` ``` -The cause is in there now. A field is missing, one *is* present, and the provider that wanted it is -named. Two things still stand between that and a usable message: the field names are spelled as -type-level character lists, `sent_emails` and `smtp_server` at one character per layer, and the headline -is about a trait nobody wrote. +The error now identifies a missing `HasField` implementation and names `RecordEmails` as the +provider requiring it. The expanded field names remain hard to read: `sent_emails` and `smtp_server` +appear as nested character types. The headline also names the generated `CanUseComponent` bound +rather than the public capability. ## Reading it through the toolchain -[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) runs in place of `cargo check` and -reshapes the classes it recognizes. On the same code: +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) rewrites recognized CGP diagnostics +with readable field names and dependency chains. For this missing-field case, its abbreviated output +identifies both the unavailable capability and its cause: ```text error[E0277]: [CGP-E001] the consumer trait `CanSendEmail` is not implemented @@ -137,19 +134,19 @@ error[E0277]: [CGP-E001] the consumer trait `CanSendEmail` is not implemented └─ [CGP-E106] missing field `sent_emails` on `BrokenApp` ``` -Missing field `sent_emails` on `BrokenApp`, and the path that wanted it. That is the mistake, in the -words you would use to describe it. +The root cause is now explicit: `BrokenApp` lacks `sent_emails`, which `RecordEmails` requires. +The dependency chain connects that missing field to the `CanSendEmail` capability the application needs. -The tool does more than reformat: for the worst class it turns on the compiler's next-generation trait -solver to recover a cause the default solver discards entirely, which is why the first error on this -page had nothing to reshape. It is a `v0.1.0-alpha`, it covers the core wiring errors rather than every -class, and some still pass through as the compiler wrote them, orphan-rule failures among them. -Dramatically better and actively improving, not solved. +The tool can also recover causes that ordinary compiler output omits. It uses the compiler's +next-generation trait solver for diagnostic recovery, then translates the recognized CGP structures. +Its `v0.1.0-alpha` release covers core wiring errors, but some classes, including orphan-rule +failures, still pass through unchanged. Output details depend on the compiler and tool version. ## Checking a stack one layer at a time -When providers are built from other providers, checking the context tells you *something* is broken and -not which layer. A variant of the check asserts against each provider rather than against the context: +Checks on individual providers help distinguish a wrapper's requirements from its inner provider's +requirements. Suppose `RectangleArea` needs `width` and `height`, while +`ScaledArea` also needs a scale factor. Both can be checked against `App`: ```rust check_components! { @@ -163,62 +160,58 @@ check_components! { } ``` -Each provider is now verified on its own line. A requirement missing from the inner `RectangleArea` -fails on both lines, since the outer one needs it too; one missing only from the wrapper fails on the -wrapper alone. The difference between those two shapes is how you find the layer at fault, and it is the -practical tool for debugging a [higher-order provider](./higher-order-providers.md). +A missing `width` requirement fails both assertions because the wrapper also needs its inner +provider to work. A missing scale factor fails only the wrapper's assertion. Separate diagnostic +locations make that difference easier to see when debugging a +[higher-order provider](./higher-order-providers.md). ## What to check, and when to fuse it -The rule that does not bend is that a context's wiring is checked **somehow**. Which macro does it -scales with how complicated the wiring is. +Check each context's required components when you define its wiring. This catches missing entries +and unsatisfied dependencies before a later caller happens to exercise them. -For a starter context, or a table of plain `Component: Provider` entries, -[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) does both at -once, so the check cannot be forgotten and cannot drift from the table. Its reach stops at that basic -form: it cannot derive checks for per-type dispatch, for namespaced wiring, or for individual provider -layers, because those need parameters or provider names it has no way to infer. +[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) combines +wiring and checking for basic `Component: Provider` entries. For generic components, its +`#[check_params(...)]` attribute supplies parameter sets to check. Keeping the assertion beside the +entry helps prevent the two from drifting apart. -For anything past that, keep the two apart. A standalone check is where concrete parameters for a -generic component go, where `#[check_providers]` goes, and where opened or namespaced wiring is -verified. +Separate checks are needed for advanced mappings and individual provider layers. The combined +macro does not derive checks for `open` statements, namespace joins, or path-based entries; those +forms can remain unchecked even inside a combined table. Use `check_components!` to name the +components and parameters you need to verify, and `#[check_providers]` to inspect provider layers. -One case is not a matter of taste: **never fuse the check onto a -[bundle of wiring](./aggregate-providers.md)**. A bundle is a provider other contexts delegate to, not a -context, so a context-side check on it asks a question it was never meant to answer, and gets an answer -that means nothing either way. It passes vacuously when the bundled providers need nothing from their -context, and fails blaming the bundle when any of them does. Verify a bundle through a context that -delegates to it. +Check an [aggregate provider](./aggregate-providers.md) through a context that uses it. Applying +the combined macro to the bundle checks the bundle as a context instead. It can pass when the +providers need nothing from their context, or fail because the bundle lacks fields the actual +context supplies. Neither result verifies the intended application. ## What it costs -**A check is something you write.** Nothing generates it from the table unless you fuse the two, so a -component nobody listed is a component nobody verified. In practice the discipline is to add the check -when the context is created, not when it breaks. - -**It moves the error; it does not shrink it.** The output above is better because it names the cause, -not because it is short. A context wired wrong in several places reports several failures, and one deep -mistake reaching many providers can report at each of them. +Explicit checks cover only the components and parameter sets you list. Add them as you add wiring; +otherwise an omitted component can still fail only when a caller uses it. Generic wiring may need +several checks to cover the concrete uses an application depends on. -**A check verifies wiring, not everything.** Some of what a provider needs is an ordinary Rust trait -rather than a CGP component, and a bound like `Value: Display` failing looks like any other unsatisfied -bound. There is nothing CGP-specific to route it through. +A check can expose a cause without making the diagnostic short. Several invalid entries can produce +several errors, and one shared missing dependency can appear in multiple provider failures. +`cargo cgp check` makes recognized cases easier to read, but raw compiler diagnostics remain verbose. -**And the raw diagnostics remain verbose** for anyone not running the toolchain, which is why this page -quotes all three stages rather than only the last. A reader who meets stage one with no idea stages two -and three exist is the reader CGP loses. +Checks verify trait requirements rather than runtime behavior. Ordinary bounds such as `Value: Display` +can still fail as dependencies of a provider, and those traits need ordinary Rust implementations. +They cannot be listed as components in a wiring check unless they have the corresponding CGP component +machinery. Tests remain necessary for behavior such as whether an email was recorded correctly. ## Where to go next -[Impl-side dependencies](./impl-side-dependencies.md) is why the requirement was hidden in the first -place, the design decision this page pays for. [Higher-order providers](./higher-order-providers.md) is -where per-layer checking earns its keep, and [Aggregate providers](./aggregate-providers.md) is the case -where the context-side check is the wrong one. +These pages explain the dependencies being checked and the available check forms: -For the constructs, [`check_components!`](/docs/reference/macros/check_components) carries every form -including `#[check_providers]` and per-component parameters, and -[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) is the fused -version for basic wiring. +- [Impl-side dependencies](./impl-side-dependencies.md): Why provider requirements can be absent from + the caller's interface. +- [Higher-order providers](./higher-order-providers.md): Composing providers and checking their layers. +- [Aggregate providers](./aggregate-providers.md): Verifying shared wiring against a real context. +- [`check_components!`](/docs/reference/macros/check_components): Component parameters and + `#[check_providers]` assertions. +- [`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components): Combined + wiring and checking, including its coverage limits. --- diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index d34a97f0..442e4319 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -5,21 +5,15 @@ sidebar_position: 1 # Bypassing coherence -Rust allows one implementation of a trait per type. Why that rule exists, what it costs, and how CGP -writes many implementations and lets each type pick the one it wants. - -This page answers *why can't Rust do this already?* It builds up what the trait system gives you, shows -what that costs when you want two implementations of one thing, and works through the move CGP makes, -which is smaller than it first appears and does not discard the rule. It closes on what that move costs in -turn. It is the page everything else in this section is downstream of. +Rust's coherence rules keep trait implementation selection unambiguous. CGP works within those rules +by giving alternative implementations separate provider types, then letting each context select one. +This page explains what coherence provides, why overlapping blanket implementations are rejected, +and how the provider arrangement allows reuse without ambiguous calls. ## The trait system is already a dependency-injection mechanism -Start with what Rust does well, because the rule that blocks this later is the same rule that makes -it work. - -When you write a generic function with a bound, you are asking the compiler to find an implementation for -you: +Rust resolves trait dependencies for generic code at compile time. A function can require an +implementation through a bound without asking its caller to pass that implementation explicitly: ```rust pub fn describe(value: &T) -> String { @@ -27,13 +21,12 @@ pub fn describe(value: &T) -> String { } ``` -There is no need to pass `Display` when `describe` is called. The caller writes `describe(&42)`, and the -compiler goes looking for `impl Display for i32`, finds it, and wires it up. That is dependency injection, -done by the type system at compile time, and it is so ordinary in Rust that Rust programmers rarely call -it that. +Calling `describe(&42)` makes the compiler resolve `i32: Display`. The caller supplies the value; +the type system determines which formatting implementation the function uses. This serves as a form +of dependency injection within ordinary Rust. -It is worth noticing that the compiler resolves the `T: Display` bound **transitively**. Suppose a pair -implements `Display` whenever both of its components do: +Trait resolution also follows an implementation's dependencies. A pair can implement `Display` +whenever both of its fields implement it: ```rust struct Pair(A, B); @@ -45,24 +38,20 @@ impl Display for Pair { } ``` -Now `describe(&Pair("foo", 42u32))` asks the compiler for `Pair<&str, u32>: Display`, and to satisfy that -it resolves `&str: Display` and `u32: Display` in turn, without the caller naming either. The chain runs -as deep as the types do: add a requirement four layers down, and callers four layers up are unaffected. -That reach makes Rust's generics composable rather than a bookkeeping exercise. +Calling `describe(&Pair("foo", 42u32))` requires `Pair<&str, u32>: Display`, which in turn requires +`&str: Display` and `u32: Display`. The caller need not list those transitive requirements separately. +If an implementation acquires another dependency, generic callers can retain their existing bounds, +provided the concrete types still satisfy the full chain. ## That only works because every lookup finds the same answer -Transitive resolution depends on something easy to overlook: when the compiler looks up `Display for i32`, -it must get the same answer no matter where it asks from. If one crate could see one implementation and -another crate a different one, the same generic function would mean different things depending on who -called it, and a program combining both would be incoherent: two halves compiled against -irreconcilable answers. +Coherence gives trait resolution a consistent answer across a program. For a given trait, including +its type arguments, and an implementing type, Rust permits at most one applicable implementation. +Generic code can therefore rely on the same implementation wherever it is called. -**Coherence is the property that guarantees this**, and Rust enforces it with two rules. - -The **overlap rule** forbids two implementations that could both apply to the same type. Given a trait you -own and two blanket implementations (each a single `impl` written once for every type that meets a bound), -the compiler rejects the second: +Rust enforces coherence through overlap and orphan rules. The **overlap rule** rejects implementations +that could apply to the same type. These blanket implementations each cover every type satisfying +their bound, so they conflict: ```rust pub trait CanEncode { @@ -80,11 +69,13 @@ impl> CanEncode for T { } ``` -`String` satisfies both bounds, so the compiler would have no principled way to choose. The rule exists -precisely to prevent the alternative: silently picking whichever implementation happens to be in scope. +`String` satisfies both bounds. Both implementations would apply to `String: CanEncode`, and Rust +does not let a call site select one of them. Each blanket implementation is valid alone; defining +both for the same trait causes the conflict. -The **orphan rule** forbids implementing a trait for a type unless your crate owns one of the two. -Neither `Display` nor `Vec` is yours, so this is rejected: +The **orphan rule** restricts implementations involving foreign traits and types. For a trait without +type parameters, your crate must define either the trait or the implementing type. Neither `Display` +nor `Vec` belongs to this crate, so Rust rejects this implementation: ```rust // error[E0117]: only traits defined in the current crate can be implemented @@ -94,36 +85,35 @@ impl Display for Vec { } ``` -Without it, two unrelated crates could each add their own `Display for Vec`, and any program -depending on both would be unbuildable, with neither crate at fault. +This restriction prevents unrelated crates from independently defining conflicting implementations +for the same foreign trait and type. Traits with type parameters have additional cases involving a +local type in those parameters; the +[Rust Reference](https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules) +specifies the full rule. -**Both rules are correct.** They are not conservatism or an unfinished corner of the language; they are -the price of transitive resolution, and the trade is a good one. Any account of CGP that opens by -calling coherence a limitation has the argument backwards. +Together, these rules let crates compose without making implementation selection depend on which +crate asks. CGP retains that guarantee while changing how alternative implementations are represented. ## What the guarantee costs -The price is that some perfectly reasonable code is unwritable, and the two rules cost you in different -ways. - -The overlap rule costs you **alternative implementations**. In the encoding example above, the author knows -exactly which implementation they want for which type. The ambiguity is the compiler's, not theirs, and -there is no way to say so. The trait admits exactly one blanket implementation. +The overlap rule prevents the encoding trait from carrying both blanket implementations above. +Even if an application author knows which behavior each type should use, the trait system does not +provide a selection table for those conflicting implementations. Multiple blanket implementations +are allowed when Rust can establish that they do not overlap. -The orphan rule costs you **reach**. A crate that wants to add a capability to another crate's type has to -wrap it in a newtype and re-expose everything it still needs, which is boilerplate with no upside and a -type your callers now have to know about. +A newtype provides an ordinary Rust way to choose a distinct implementation for a foreign type. +The wrapper is local, so it can implement a foreign trait such as `Display`. It also makes the +semantic distinction explicit. Its cost is that callers must use the wrapper, and operations on the +underlying type may need forwarding methods or trait implementations. -These pains are sharp enough that Rust developers work around them by hand, and at least one has -arrived independently at the pattern CGP is built on. The next section shows how CGP makes that pattern -first-class. +Named helper types provide another way to represent implementation choices. Each helper implements +a trait parameterized by the data type, so the helpers can coexist. CGP uses this pattern and adds +wiring that connects a type's normal method calls to its chosen helper. ## The move: make `Self` a type you own -CGP's move is to split the trait in two and change what `Self` means on the side that implements it. One -definition becomes two traits. The **consumer trait** is the caller's view, `CanEncode` unchanged, so -`value.encode()` stays a method call. The **provider trait** carries the same method with the former -`Self` moved into a parameter, and each implementation targets a small type it declares for itself: +CGP separates the caller's interface from the provider's implementation interface. The +**consumer trait** keeps the method callers use: ```rust #[cgp_component(Encoder)] @@ -132,9 +122,8 @@ pub trait CanEncode { } ``` -`#[cgp_component]` generates the provider trait `Encoder` from that one definition, where the -type being encoded is now the `Context` parameter. Each implementation targets a dummy struct of its own, -so the two implementations that clashed a moment ago can both be written: +`#[cgp_component]` also generates a **provider trait**, `Encoder`. The value being encoded +becomes its `Context` parameter, while each provider supplies a distinct implementing type: ```rust #[cgp_impl(new EncodeAsText)] @@ -150,90 +139,76 @@ impl Encoder { } ``` -**Both compile.** `EncodeAsText` and `EncodeAsHex` are different `Self` types, so the two impls no longer -overlap, however many bounds they share, and any number more would compile too. The orphan rule does not -enter either, because that `Self` is always a struct this crate declared, which is how a crate adds a -capability to a type it did not define. Coherence only ever looked at `Self`, and `Self` is now a local -dummy struct, so there is nothing left for the rules to reject. +`EncodeAsText` and `EncodeAsHex` can both implement `Encoder` because their implementing +types differ. Their context requirements may overlap without the Rust implementations overlapping. +A crate can also implement a foreign provider trait for its own provider type, even when the context +comes from another crate. The generated implementations still satisfy Rust's coherence rules. -`#[cgp_impl]` lets a provider keep the consumer trait's `self` receiver, so inside `EncodeAsText` the -`self` is the value being encoded, and `#[uses(Display)]` records that this provider needs that value to -be `Display`. Neither rule was repealed; the implementations simply stopped being the kind of thing the -rules are about. [Consumer and provider traits](./consumer-and-provider-traits.md) works through the two -halves and how a call crosses between them. +`#[cgp_impl]` lets provider code retain a familiar `self` receiver. Within that macro's input, +`self` refers to the value being encoded, and `#[uses(Display)]` requires that value's type to +implement `Display`. The macro translates this into a provider implementation with an explicit +context parameter. ## Coherence comes back, one type at a time -Making the implementations incoherent would be no use if it also made *using* them incoherent. A caller -still needs `value.encode()` to mean one definite thing. - -So the second half brings coherence back at a smaller scale. A type chooses one provider for the -component, in a small wiring table: +Each type selects one provider for the component through a wiring table: ```rust delegate_components! { String { EncoderComponent: EncodeAsText } } delegate_components! { Vec { EncoderComponent: EncodeAsHex } } ``` -Now `String` implements `CanEncode` through `EncodeAsText` and `Vec` through `EncodeAsHex`, so a -`value.encode()` call resolves to the provider its type named. The two providers still overlap freely, yet -no call is ambiguous, because each type records its own choice. +`String` implements `CanEncode` through `EncodeAsText`, while `Vec` uses `EncodeAsHex`. +A call to `value.encode()` resolves to the provider selected for that value's type. Both providers +remain available, but each wired type has an unambiguous choice. -That is the whole trade. **You want incoherence while writing implementations, and coherence while using -them.** While writing them, overlapping providers coexist with no global conflict. While using them, each -type names exactly one, and resolution is unambiguous. +The component key's ownership still matters when wiring foreign types. Here `EncoderComponent` is +generated in the crate defining `CanEncode`, so that crate can wire it onto `String` and `Vec`. +A downstream crate cannot independently wire that foreign key onto those foreign types. This example +therefore makes one choice per value type across the program. -**Coherence is not repealed; it is scoped.** That line is the whole page in a sentence. +CGP preserves coherence while making provider selection explicit. Alternative providers can apply +to the same context, and the wiring chooses which one supplies the consumer trait. Defining a second +conflicting entry for the same type and component remains an error. -How far the idea scales is a separate question. Here each type picks one provider, which is the simplest -shape. A type you define to stand for your own application can pick its own providers, and the same -capability can even resolve differently for the same data in two applications. Those are higher tiers of -the same hierarchy, worked out in [Modularity Hierarchy](./modularity-hierarchy.md). +Separate application contexts allow independent choices for the same data type. That arrangement +requires moving the data into a component parameter; [Modularity Hierarchy](./modularity-hierarchy.md) +explains when to use it and how it differs from the value-type wiring shown here. ## What it costs -**It is more machinery than one trait.** A component is two traits, a marker type, and a wiring line per -type that uses it. For a capability with a single implementation that is pure overhead, and a plain trait -is the right tool. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the CGP construct for that case, and it -needs no wiring at all. +A component introduces more declarations than a plain trait: a provider trait, a component marker, +and wiring for the types that use it. For a capability with one implementation, a plain trait or +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) may provide the required reuse without wiring. -**A wired choice is local, not global.** This is a real limit rather than a technicality. When a program -genuinely needs one answer program-wide, per-type choice is the wrong shape and a coherent trait is safer. -Consider a single consistent `Ord` for a map key, where two orderings in one program would corrupt the -map. CGP does not make coherence optional; it moves where the single answer is decided. +Provider selection belongs to CGP's component interface. It does not give an existing trait such as +`Ord` multiple implementations, nor change how standard collections select that trait's behavior. +Use ordinary traits when one consistent implementation per type expresses the intended contract. -**The choice is explicit, which is both the point and a cost.** Nothing is inferred. A type that has not -named a provider does not get a default, and adding a capability means adding a line. That is the property -the whole design rests on, and it is also more to write and read than a trait with one implementation. +Explicit wiring adds configuration to read and maintain. In the tables above, each type needs an +entry naming its provider. Shared bundles and namespaces can reduce repetition, but they introduce +further places to inspect when tracing a choice. -**Wiring is checked lazily.** A table naming a provider whose requirements the wired type cannot meet -still compiles; the failure appears later, where the capability is used, and can be long. -[`check_components!`](/docs/reference/macros/check_components) forces it to the wiring line and names the -actual missing requirement, and -[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) leads with the root cause for the classes -it recognizes. It is a `v0.1.0-alpha` that reshapes the core wiring errors rather than all of them. -[Checking your wiring](./check-traits.md) is the fuller account. +Wiring checks are deferred until the capability is checked or used. A table can name a provider +whose requirements the context does not satisfy, and a later call can produce a verbose error. +[`check_components!`](/docs/reference/macros/check_components) verifies requirements beside the +wiring. [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) makes recognized causes +easier to read; its `v0.1.0-alpha` release covers core wiring errors rather than every class. +[Checking your wiring](./check-traits.md) shows the diagnostics and their limits. ## Where to go next -[Modularity Hierarchy](./modularity-hierarchy.md) is the page to read next if this argument landed, because -a reader who has just been told coherence can be escaped needs to hear immediately that most code should -not bother. It lays out the range from a plain trait to fully wired components and argues for climbing no -higher than a problem needs. - -[Consumer and provider traits](./consumer-and-provider-traits.md) develops the trait split this page -introduced: what each half is for, and how a method call crosses between them. - -To see it working rather than argued, the [Hello World tutorial](/docs/tutorials/hello) is five minutes and -one durable idea, and the [Area calculation series](/docs/tutorials/area-calculation/) builds the split up -from plain functions. For the constructs themselves, -[`#[cgp_component]`](/docs/reference/macros/cgp_component) generates the pair, -[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) writes a provider, and -[`delegate_components!`](/docs/reference/macros/delegate_components) is the table. - -The fullest public account of why coherence exists is the -[RustLab 2025 talk](/blog/rustlab-2025-coherence), which spends its first third establishing that the rule -is correct before working around it. +Choose the next page according to whether you want to evaluate, understand, or use the arrangement: + +- [Modularity Hierarchy](./modularity-hierarchy.md): When a plain trait is enough and when further + provider choices are useful. +- [Consumer and provider traits](./consumer-and-provider-traits.md): How a method call reaches its provider. +- [Hello World tutorial](/docs/tutorials/hello) and + [Area calculation series](/docs/tutorials/area-calculation/): Working examples of the component model. +- [`#[cgp_component]`](/docs/reference/macros/cgp_component), + [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), and + [`delegate_components!`](/docs/reference/macros/delegate_components): The constructs used here. +- [RustLab 2025 talk](/blog/rustlab-2025-coherence): A longer account of coherence and CGP's approach. --- diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index 3b60f9af..cc4af286 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -5,20 +5,19 @@ sidebar_position: 2 # Consumer and provider traits -One trait definition in CGP becomes two traits: a **consumer trait** that callers use, and a -**provider trait** that implementations target. This page explains why the split exists, what each -half is for, and how a plain method call finds its way from one to the other. It closes on what the -arrangement costs, which is the part worth reading before adopting it. +CGP separates the trait callers use from the trait providers implement. A **consumer trait** exposes +a capability on a context, while a **provider trait** lets reusable implementations supply that +capability. This page motivates the split, traces a method call through its wiring, and shows the +generated Rust before discussing the costs. ## What an ordinary Rust trait does, and where it stops -A Rust trait joins two jobs that are usually the same job. The type that implements `Display` is the -type callers format, and that identity lets the compiler resolve a `where T: Display` bound without -anyone naming an implementation: it looks the type up, finds the one implementation, and is done. -Almost all Rust code wants exactly this, which is why the language is built around it. +An ordinary Rust trait connects a type to an implementation of a capability. A `T: Display` bound, +for example, lets the compiler select the formatting implementation for `T`. This is sufficient when +each type needs one implementation and you do not need to choose among reusable alternatives. -The consequence is that a trait offers one implementation per type, and that limit shows up sooner -than it sounds. Consider an application that sends email, with a test harness that must not: +Separate application types can implement the same trait differently using ordinary Rust. +A production application might send email, while a test application records it: ```rust use core::cell::RefCell; @@ -48,35 +47,34 @@ impl CanSendEmail for TestApp { } ``` -This compiles, and it is worth noticing that it already does what you want: two application types, -two behaviours, no CGP anywhere. `App` and `TestApp` here are types that stand for a whole -application. Their job is to carry the choices and the data the program needs, not to be operated -on. That shape is legal Rust and nothing about it is unusual. +`App` and `TestApp` already provide different behavior without CGP. Each is a context representing +an application and carrying the data its implementation needs. The SMTP body is omitted here; +`TestApp` shows the recording behavior in full. -Sharing is where it fails. Try to lift a body out into something reusable, so that a second -application could adopt the SMTP behaviour without copying it, and the two implementations collide: +Overlapping blanket implementations prevent those behaviors from being offered as interchangeable +trait implementations. If the SMTP implementation applies to every type with `HasSmtpConfig`, and +the recording implementation applies to every type with `HasRecordedEmails`, they conflict: ```rust impl CanSendEmail for T { /* over SMTP */ } impl CanSendEmail for T { /* record it */ } // error[E0119] ``` -The compiler rejects the second impl because a type could satisfy both bounds, and it has no -principled way to choose. So the arrangement above survives, but every application must hand-write -every body, and nothing can be factored out. It is available and unrewarding, which is why almost -nobody builds on it. That is the gap CGP fills. +A type could satisfy both bounds, so Rust rejects the pair. The bodies can still be shared through +helper functions or other composition techniques, but each application must connect its trait +implementation to the chosen behavior. CGP provides a reusable provider interface and wiring for +that choice. ## Splitting one trait in two -CGP's move is to stop implementing the trait for the type the capability is about. A single -definition produces two traits with the two jobs pulled apart: +CGP gives callers and implementers separate trait interfaces: -- The **consumer trait** is the caller's view. It keeps the original name, the original `self` - receiver, and the original signatures, so a caller writes `app.send_email(..)` as before. -- The **provider trait** is the implementer's view. It is the same interface with `Self` moved out - into an explicit leading `Context` type parameter, and every `self` rewritten to `context`. +- The **consumer trait** keeps the original methods, so callers use `app.send_email(..)`. +- The **provider trait** moves the consumer's `Self` into an explicit `Context` parameter and + replaces the receiver with a context argument. -For the example above, the pair is: +The simplified pair for email sending looks like this. The provider's generated checking bound is +omitted here and explained below: ```rust // what callers use @@ -90,55 +88,55 @@ pub trait EmailSender { } ``` -Moving `Self` is the whole change. An implementation no longer says "this type sends email"; it says -"this *named implementation* sends email, for any context". The name is a small type the -implementing crate declares for the purpose: +The provider trait lets a named implementation supply behavior for a context. Each implementation +uses its own marker type in the `Self` position: ```rust impl EmailSender for SendViaSmtp { /* ... */ } impl EmailSender for RecordEmails { /* ... */ } ``` -Both compile, and any number more would. There is no overlap, because each `impl` has a different -`Self`. There is no orphan-rule problem either, because that `Self` is a type the crate writing the -impl owns, which means a crate can add behaviour for a type it did not define. Neither rule was -repealed; the implementations simply stopped being the kind of thing the rules are about. The wider -argument for why that is a fair trade is [Bypassing coherence](./coherence.md). +The implementations have distinct `Self` types, so they can accept the same contexts without +conflicting with one another. Owning the provider type also lets a crate implement a provider trait +from another crate. These are ordinary coherent Rust implementations; +[Bypassing coherence](./coherence.md) explains the rules behind the arrangement. + +A component can contain several methods, associated types, and constants. The single-method example +keeps the split visible; it is not a restriction imposed by CGP. Group items when one provider choice +should determine their implementation. ## A provider is a name, not a value -A **provider** is one of those named implementations: `SendViaSmtp`, `RecordEmails`. It is a -zero-sized type that exists only to be named. Nothing constructs it, nothing stores it, and there is -no field in it to read; at runtime it does not exist at all. +A provider such as `SendViaSmtp` or `RecordEmails` is a zero-sized type used to name an implementation. +CGP does not construct a provider value or store state in it. The context supplies the values the +implementation needs. -That has one consequence worth fixing in mind before reading any provider code. Inside a provider, -`self` and `Self` refer to the **context**, the application type the method is running against, -never to the provider. When you write a provider with -[`#[cgp_impl]`](/docs/reference/macros/cgp_impl), the macro keeps `self` in the source and rewrites -it to the context underneath, precisely because the context is the only value that exists when the -method runs. +Within [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), `self` and `Self` refer to the context. +The macro rewrites them into the explicit context argument and type parameter shown above. +In a raw Rust provider implementation, `Self` instead has its ordinary meaning: the provider type +following `for`. ## How a call finds its provider -Two pieces connect the halves: a table on the context that names its choice, and a pair of generated -implementations that follow it. - -A context writes the table. It maps each **component**, one capability defined once that -implementations can be wired for, to the provider that should supply it, and it is the one place a -choice is recorded: +A context's wiring selects a provider for each component, much like a settings table whose keys and +values are types. The compiler resolves this table at compile time: ```rust delegate_components! { App { EmailSenderComponent: SendViaSmtp } } delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } ``` -`EmailSenderComponent` is a marker type generated alongside the two traits, used purely as the key. -The table itself is a set of trait implementations rather than a runtime structure: the compiler -performs the lookup, and nothing survives into the program. +`EmailSenderComponent` is the generated marker used as the key. A **component** groups the consumer +trait, provider trait, and that marker. The wiring maps its key to `SendViaSmtp` for `App` and to +`RecordEmails` for `TestApp`. + +A method call follows the selected entry. For `app.send_email("a@b.c", "hi")`, the compiler resolves +`App`'s email-sending capability through its table to `SendViaSmtp`, then checks that provider's +requirements against `App`. The call uses static dispatch; the compiled program does not need a +runtime wiring table or provider lookup. -The two generated implementations then chain through it. The first says that any context which -implements the *provider* trait for itself gets the *consumer* trait, so `app.send_email(..)` becomes -a legal call: +The generated consumer implementation connects method syntax to the provider interface. Any context +that implements the provider trait for itself gets the consumer trait: ```rust impl CanSendEmail for Context @@ -151,8 +149,8 @@ where } ``` -The second says that anything with a table entry for this component inherits the provider trait from -whatever the entry names: +The generated delegation implementation then connects a table entry to its selected provider. +`DelegateComponent` represents that entry, and its `Delegate` associated type names the provider: ```rust impl EmailSender for Provider @@ -167,34 +165,26 @@ where } ``` -Put together, `app.send_email("a@b.c", "hi")` resolves in three steps. `App` implements -`CanSendEmail` because it implements `EmailSender` for itself; it implements `EmailSender` -because its table maps `EmailSenderComponent` to `SendViaSmtp`; and `SendViaSmtp` implements -`EmailSender` directly. Every step is trait resolution, so the finished call is a direct call to -`SendViaSmtp::send_email`: no lookup happens while the program runs, and a provider no context uses -never reaches the binary. - -The one piece of that listing not yet explained is -[`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for), which is also a supertrait on the provider -trait. Every provider implements it under exactly the bounds it needs, and requiring it here carries -those bounds back down the chain, so when a context is missing something a provider requires, the -compiler can name the missing requirement instead of reporting only that the provider trait is not -implemented. It is generated, never written by hand. - -Three liberties in the listings above are worth knowing before you read a real error message. The -generated type parameters carry reserved names: the context is `__Context__` and the provider -`__Provider__`, and the delegate is spelled out in full as -`<__Provider__ as DelegateComponent>::Delegate`. `Context`, `Provider`, and -`Provider::Delegate` here are for legibility. And the provider trait printed earlier on this page omitted -its `IsProviderFor` supertrait, which the real `EmailSender<__Context__>` carries. `cargo cgp expand` will -show you all of it as the macros actually emit it. +Together, these implementations resolve `App: CanSendEmail` through `App: EmailSender` to +`SendViaSmtp: EmailSender`. The context remains `App` throughout, so the final provider receives +the application value on which the caller invoked the method. + +[`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for) carries the provider's dependency +bounds for checking. The provider macros generate an implementation with those bounds, and the +provider trait also requires it as a supertrait. Explicit component checks use this path to expose +missing requirements that a consumer-trait error can hide. + +The listings simplify generated names for readability. Actual expansions use `__Context__` and +`__Provider__`, and spell the delegate as +`<__Provider__ as DelegateComponent>::Delegate`. The earlier simplified +`EmailSender` declaration also omitted its `IsProviderFor` supertrait. `cargo cgp expand` shows the +full expansion for a concrete example. ## Writing it -In practice you write neither trait by hand. [`#[cgp_component]`](/docs/reference/macros/cgp_component) -generates the pair, the marker, and the two blanket implementations from one trait definition, and -[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) lets a provider be written in the consumer trait's -shape, keeping `self` and the original signatures, and rewrites it into the provider form: +The macros generate the trait pair and forwarding implementations from a consumer trait definition. +`#[cgp_component]` creates the component, and `#[cgp_impl]` defines each provider using context-style +method syntax: ```rust use cgp::prelude::*; @@ -233,55 +223,51 @@ delegate_components! { App { EmailSenderComponent: SendViaSmtp } } delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } ``` -Two details of that listing are worth pointing out. The -[`#[implicit]`](/docs/reference/attributes/implicit) arguments are how each provider reaches into its -context: they read a same-named field and disappear from the method's public signature, so -`app.send_email(to, body)` still takes two arguments. And the two providers depend on *different* -fields: `SendViaSmtp` needs an `smtp_server` and `RecordEmails` needs somewhere to record, with -neither requirement appearing in `CanSendEmail`. That is -[impl-side dependency injection](./impl-side-dependencies.md), and it stops a context paying -for the needs of implementations it did not choose. +Each `#[implicit]` argument reads a same-named field exposed by the context's `HasField` derive. +The macro removes these arguments from the public signature, so callers still write +`app.send_email(to, body)`. The SMTP body remains a placeholder; the recording provider stores the +message in the test application's vector. -A consumer trait remains an ordinary Rust trait throughout. Nothing stops a context from implementing -it directly, exactly as in the very first listing on this page, and skipping providers and wiring -entirely. The split is something you opt into for the capabilities that need more than one -implementation, not a replacement for how traits already work. +Each provider declares only the fields it needs. `SendViaSmtp` requires `smtp_server`, while +`RecordEmails` requires `sent_emails`; neither requirement appears in `CanSendEmail`. +These are [impl-side dependencies](./impl-side-dependencies.md), which let implementations have +different requirements without changing the caller's interface. + +A context can also implement the consumer trait directly, using the ordinary Rust form shown at +the start of the page. For that capability it can omit providers and wiring. This allows adoption +one capability at a time, subject to Rust's usual restriction against conflicting implementations. ## What it costs -**It is more machinery than a plain trait.** One capability becomes two traits, a marker type, and a -line of wiring per context. For a capability with a single implementation, that is pure overhead: -write a plain trait, or reach for [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), which builds a -capability from a function with no component and no wiring at all. - -**Wiring is checked lazily.** A table with a missing entry, or one naming a provider whose own -requirements the context cannot meet, still compiles; the failure surfaces later, wherever the -capability is finally used, and the error can be long. This is real, and it has an answer: -[`check_components!`](/docs/reference/macros/check_components) forces the check at the wiring line so -the error names the actual gap, and -[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reshapes the recognized failures to -lead with the root cause, though it is a `v0.1.0-alpha` and covers the core wiring errors rather than -every class. Neither makes the raw diagnostics pleasant. See -[Checking your wiring](./check-traits.md) for what to expect. - -**There is a hop between the call and the code that runs.** `app.send_email(..)` no longer points at -one body you can jump to. Unlike runtime dispatch the indirection is fully resolved at compile time -and never ambiguous, and the wiring table is a single greppable place naming exactly one provider per -component. But it is a hop, and a reader unfamiliar with the codebase has to follow it. +A component adds declarations and wiring beyond a plain trait. For a capability with one +implementation, use a plain trait or consider [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), which +creates a blanket-implemented capability from a function without component wiring. + +Wiring does not immediately verify the selected provider's requirements. A missing entry or +unsatisfied dependency can remain undetected until a caller needs the capability. +[`check_components!`](/docs/reference/macros/check_components) verifies the requirements where you +place the check, usually beside the table. +[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reports recognized failures with +readable causes; its `v0.1.0-alpha` release covers core wiring errors rather than every class. +[Checking your wiring](./check-traits.md) shows what to expect with and without those tools. + +Tracing a method call requires following the wiring to its provider. Static dispatch avoids runtime +lookup costs, but a reader still has to find the table entry and the implementation it names. +The separation pays for itself when those implementations are reused or selected differently across +contexts. ## Where to go next -[Bypassing coherence](./coherence.md) is the argument underneath this page: why Rust's rule exists, -why it is correct, and why scoping it per context is a fair trade rather than a loophole. -[Impl-side dependencies](./impl-side-dependencies.md) develops the other half of what makes providers -reusable: how an implementation states what it needs without the interface carrying it. - -To write this rather than read about it, the [Area calculation tutorial](/docs/tutorials/area-calculation/) -builds the same split up from plain functions, and calls providers by name before any wiring exists. -For the exact syntax and the full generated code, the reference pages for -[`#[cgp_component]`](/docs/reference/macros/cgp_component), -[`#[cgp_impl]`](/docs/reference/macros/cgp_impl), and -[`delegate_components!`](/docs/reference/macros/delegate_components) are the complete account. +These pages develop the trait model and show how to use it: + +- [Bypassing coherence](./coherence.md): Why distinct provider types permit reusable alternatives. +- [Impl-side dependencies](./impl-side-dependencies.md): How a provider states requirements without + adding them to the caller's interface. +- [Area calculation tutorial](/docs/tutorials/area-calculation/): Building the same split from plain + functions and calling providers before introducing wiring. +- [`#[cgp_component]`](/docs/reference/macros/cgp_component), + [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), and + [`delegate_components!`](/docs/reference/macros/delegate_components): Exact syntax and generated code. --- diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index d2dd2cb2..8b8134a6 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -5,39 +5,36 @@ sidebar_position: 15 # Dispatching -Routing each field of a record, or the current variant of an enum, to the handler responsible for -it. +Dispatching connects a record's fields or an enum's variants to the providers that process them. +A generic dispatcher can build several record types or handle several enum types while each provider +implements one part of the work. This page explains matching, building, and their compile-time +guarantees, then shows how to derive dispatch from an ordinary trait. -This page answers *what actually runs the per-variant and per-field handlers?* It is the layer that -turns [extensible records](./extensible-records.md) and -[extensible variants](./extensible-variants.md) into working code, and it assumes both. It covers the -two directions, the guarantee each carries, and the shortcut for the common case. It closes on the costs, -including the one piece of ceremony that appears once the data is recursive. +The examples build on [extensible records](./extensible-records.md) and +[extensible variants](./extensible-variants.md). Those pages explain how CGP exposes fields and +variants to generic code; dispatching chooses and runs the computations that use them. ## Two directions, one idea -The extensible-data machinery can take an enum apart one variant at a time and can assemble a record one -field at a time. Neither decides *what to do* with each piece. Dispatching is that decision: a -type-level list of handlers, one per element, run as an ordinary -[handler provider](./handlers.md). +Dispatchers combine generic data operations with a list of handlers. The data traits describe how +to extract a variant or set a field. A handler supplies the computation to perform on the extracted +payload or to produce the field's value. -It runs in two directions, and they are mirror images. +Matching and building use these pieces differently: -**Matching** consumes a sum. The value is converted into its extractor, and the handlers are tried in -turn until one matches, so the list stops at the first success. **Building** produces a product. The -builder starts empty, and every handler runs, each setting one field, so the list runs to the end. +- **Matching:** Try variants until the current one is found, then run its handler. +- **Building:** Run handlers in sequence, adding their outputs to a partial record until it can be finalized. -Both come out as `Computer` or `Handler` providers, which is the point: a dispatcher goes anywhere a -computation goes. It can be wired to a context, nested inside another dispatcher to handle a group of -variants with a sub-matcher, or chained with other combinators. +Dispatchers implement the same computation interfaces as other +[handler providers](./handlers.md). They can be selected through context wiring, composed with other +computations, or nested to delegate a group of variants to another matcher. The available interfaces +depend on the dispatcher and the providers it contains. ## Matching, and why it is exhaustive -The matcher is a chain of attempts, sequenced by the ok monad from -[monadic handlers](./monadic-handlers.md): each step returns success or a remainder, the chain -short-circuits on the first success, and a miss threads the narrowed remainder forward. - -Wiring it means naming a handler per payload type, plus an entry routing the enum itself to the matcher: +A matcher selects the handler for an enum's current variant. For a `Shape` enum deriving `CgpData` +with `Circle(Circle)` and `Rectangle(Rectangle)` variants, input-based wiring can select both the +matcher and the payload handlers: ```rust delegate_components! { @@ -53,33 +50,51 @@ delegate_components! { } ``` -`app.compute(code, shape)` now reaches `CircleArea` or `RectangleArea` according to the variant in hand, -and no code anywhere contains a `match` over `Shape`. +`UseInputDelegate` selects a provider by the input type. A call to `app.compute(code, shape)` first +reaches `MatchWithValueHandlers`. The matcher extracts the current variant's payload and delegates +it through the same context: a `Circle` reaches `CircleArea`, and a `Rectangle` reaches +`RectangleArea`. The application does not write a `match` over `Shape`. + +The matcher tracks unhandled variants through the extractor's remainder type. Each extraction +attempt returns either a payload to handle or a remainder that excludes that variant. The next +attempt receives the narrowed remainder. After every variant has been covered, the remainder is +uninhabited, so finalization can eliminate it without a wildcard or a runtime panic. + +A missing handler prevents the matcher from compiling for that enum. An automatically generated +handler list requires a suitable provider for every payload; an explicit list must leave an +uninhabited remainder. Adding a variant therefore requires either an existing generic handler that +covers it or an additional handler. -Exhaustiveness survives the indirection, for the reason -[extensible variants](./extensible-variants.md) gives: each failed attempt rules out one variant in the -type, so after the last handler the remainder is uninhabited and is discharged by a `match` with no -arms. Add a variant without a handler and the remainder becomes inhabited again, so the code stops -compiling. The dispatcher proves it covered everything. +The attempts are sequenced by the `OkMonadic` pipeline described in +[monadic handlers](./monadic-handlers.md). A successful extraction stops the search; a miss passes +the remainder onward. Here the `Err` branch means “try another variant,” rather than an application +error. Provider selection and exhaustiveness are checked at compile time, while testing the actual +variant and running its handler happen at runtime. ## Building, and why it is complete -The mirror image applies to a record. The builder threads a partial record through the handler list, -each one computing and setting a field, with later handlers able to read fields already set. At the end -the record is finalized into the concrete struct. +A builder dispatcher runs handlers over a partial record and finalizes the result. The partial +record's type tracks which fields are present after each step. `BuildWithHandlers` starts the +builder, passes it through the handler list, and calls `finalize_build` at the end. -The guarantee is the mirror image too: finalizing is available only when every field is present, so a -builder missing a handler cannot finalize and does not compile. A matcher proves it covered every -variant; a builder proves it filled every field. +Field adapters let a handler produce either one field or a group of fields. `BuildAndSetField` +computes and sets a named field; `BuildAndMerge` computes a source record and merges its fields. +Both pass the current builder by reference to the inner provider, so a later provider can read +fields an earlier step supplied. -This is the machinery under the [extensible builder](./extensible-records.md): the dispatcher runs -each subsystem's provider and merges the outputs. +Finalization requires every field in the strict builder to be present. Omitting a required field +prevents the pipeline from compiling. Fallible handlers can still return runtime errors while +computing values; completeness guarantees that a successful build supplies every field, not that +construction cannot fail. + +This supports the [extensible builder pattern](./extensible-records.md): independent providers +produce parts of a result, and a dispatcher assembles them into a target record. The handler order +must respect any dependencies on fields produced by earlier steps. ## The shortcut for the common case -Much of the time the per-variant logic is an ordinary Rust trait with one implementation per payload -type, and setting up a dispatcher by hand for that is disproportionate. -`#[cgp_auto_dispatch]` generates the wiring instead: +`#[cgp_auto_dispatch]` forwards an enum's trait methods to its payloads. Use it when each payload +already implements an ordinary trait and the enum should expose that same behavior: ```rust #[cgp_auto_dispatch] @@ -88,41 +103,47 @@ pub trait CanDescribe { } ``` -Implement `CanDescribe` for `Circle` and for `Rectangle`, and any enum whose variants all implement it -gets it too: `shape.describe()` works with no wiring, no combinator named, and no `match`. It is the -form to reach for first, and the rest of this page shows what it does underneath. +If `Circle` and `Rectangle` implement `CanDescribe`, a `Shape` enum with the required extensible-data +support gains the trait through a generated blanket implementation. A call to `shape.describe()` +forwards to the current payload's implementation without application wiring or a handwritten `match`. +Deriving `CgpData` on `Shape` supplies that data support. + +Explicit dispatch combinators provide more control when the context must choose different handlers +or when several variants should be handled as a group. The automatic trait form is a simpler entry +point when forwarding to payload methods is all the operation needs. ## What it costs -**A recursive shape needs an extra hop written by hand.** The table above names the matcher directly, -which works because a `Shape` never contains another `Shape`. When a variant's payload *is* the enum -again, as in an expression language or a tree, the matcher dispatches back through the same component, -and a thin wrapper provider has to sit between the enum's entry and the matcher to break the resolution -cycle. It is ceremony with no conceptual content, and it is the piece of a hand-wired dispatcher most -likely to puzzle a reader. +Recursive data can create a trait-resolution cycle in directly wired matchers. A payload handler +may require the enum's computation, which requires the matcher, which in turn requires the payload +handler. A context-specific wrapper provider can break that cycle by declaring the enum's provider +implementation and calling the matcher inside its method body. Non-recursive `Shape` wiring does +not need that extra provider. -**A missing handler reports as a shape, not as a name.** The failure is an unsatisfiable bound over a -partial-variant or partial-record type, which is accurate about what is missing and does not say -"`Rectangle` has no handler". +Missing handlers can produce errors involving partial-variant types or unsatisfied provider bounds. +An incomplete builder similarly reports bounds involving its partial-record state. These diagnostics +can be longer and less direct than an ordinary non-exhaustive `match` or missing struct field. -**There is one hop per element.** Each variant tried is a resolution step, and the whole chain is -resolved at compile time, so this costs compile time rather than run time, and a wide enum -dispatched at many types is somewhere that cost shows. +Dispatching adds type-level work for each field or variant. The compiler resolves the handler chain +and checks its changing types; wide shapes and many instantiations can increase that work. Runtime +variant tests and handler calls still occur, and their optimization depends on the generated code +and compiler. Static wiring alone does not guarantee that dispatch has zero runtime cost. -**And a `match` is still usually right.** Dispatching pays when the shape is not known where the logic is -written, or when handlers must be contributed independently. For a closed enum handled in one place, the -language's own construct is clearer and free. +An ordinary `match` or struct literal is usually clearer when one place owns the whole operation. +Dispatching becomes useful when generic code must work over different shapes or when independently +written providers need to contribute parts of an operation. ## Where to go next -[Extensible variants](./extensible-variants.md) and [extensible records](./extensible-records.md) are -the two halves this operates on, and both are worth reading first. -[Handlers](./handlers.md) is the interface every dispatcher and every per-element handler speaks, and -[monadic handlers](./monadic-handlers.md) is the chaining the matcher is built from. +These pages explain the data operations and computation interfaces behind dispatch: -For the constructs, [the dispatch combinators](/docs/reference/providers/dispatch) is the -catalogue of matchers, builders, and per-element adapters, and -[`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch) is the shortcut above. +- [Extensible variants](./extensible-variants.md): Extraction, remainders, and exhaustiveness. +- [Extensible records](./extensible-records.md): Partial records and complete construction. +- [Handlers](./handlers.md): The computation interfaces dispatchers implement. +- [Monadic handlers](./monadic-handlers.md): Sequencing attempts and stopping on a result. +- [Dispatch combinators](/docs/reference/providers/dispatch): Matchers, builders, and per-element adapters. +- [`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch): Automatic forwarding from an enum + to its payloads. --- diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index 84a941dd..60e72ba2 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -5,19 +5,15 @@ sidebar_position: 13 # Extensible records -Building and reading a struct through the names of its fields, without naming the struct. - -This page answers *how does code assemble a struct it does not know the type of?* It shows what a -struct becomes when its shape is a type, how a value is built one field at a time with the compiler -tracking what is still missing, and the pattern that follows: independent pieces of a program each -contributing part of a whole. It closes on the opt-in requirement, which is the honest limit of all of -this. +Extensible records let generic code read and assemble structs through their field names and types. +Independent providers can contribute fields without knowing the final struct, while the compiler +checks that construction is complete. This page explains the field representation, partial-record +builders, and the limits of matching fields by name. ## What a closed struct cannot do -A Rust struct is closed against incremental construction. A struct literal names the concrete type and -supplies every field at once, so building one is something a single place has to do, and that place -grows a line for every subsystem the program acquires: +A struct literal assembles a known type by supplying its fields in one expression. Individual field +values can come from reusable functions, as in this application constructor: ```rust let app = App { @@ -28,16 +24,19 @@ let app = App { }; ``` -Everything about that is fine until the subsystems want to be independent of each other and of `App`. -A database module that could build its own piece without knowing what it is a piece *of* would be -reusable across applications; written this way it cannot be, because the only thing that can name a -field of `App` is code that names `App`. +This approach works well when the assembly code should know `App` and its complete set of fields. +The database and HTTP helpers can already be independent of `App`; the constructor connects their +outputs to the application's fields. + +Generic assembly needs a way to make those connections without naming the target struct's fields +in the assembly code. For example, a subsystem might return a small configuration record whose +fields should populate any compatible application. CGP exposes field names and types through traits +so a reusable builder can perform that merge. ## A struct as a list of named fields -The move is to give the shape a type. -[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) gives a struct a description of itself -that generic code can read: +[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) gives a struct the traits needed for +generic field access, structural conversion, and incremental construction: ```rust #[derive(CgpData)] @@ -47,22 +46,25 @@ pub struct DatabaseClient { } ``` -Its shape is now available as a type-level list, one entry per field, each pairing the field's name -with the field's type: +The generated `HasFields::Fields` associated type describes the struct as a product of named fields: ```rust Product![Field, Field] ``` -`Symbol!("url")` is the field name lifted into a type, so the trait system can match *by name*. Nothing -here is inspected at run time; the list exists during compilation and is gone afterwards. This is the -same field-name-as-type idea behind an [implicit argument](./implicit-arguments.md), scaled from one -field to a whole struct. +Each `Field` pairs a name tag with a value type. `Symbol!("url")` encodes the name as a type, allowing +trait bounds to identify the field during compilation. A product contains every listed field; +this differs from an enum's sum, which contains one variant at a time. + +Generic code can use either the complete field representation or a single-field bound. `HasFields` +describes the whole structure, while `HasField` provides access to one field. The latter is +also the mechanism used by [implicit arguments](./implicit-arguments.md). These operations use +generated Rust implementations rather than inspecting field names at runtime. ## Built one field at a time, checked all the way -With the shape available, a value can be assembled by parts that never meet. Building goes through a -**partial record**, a companion type carrying, per field, whether that field is present yet: +A **partial record** stores field values while its type tracks which fields have been supplied. +The builder can merge several source records before producing the final struct: ```rust let app: App = App::builder() @@ -71,12 +73,18 @@ let app: App = App::builder() .finalize_build(); ``` -`builder()` produces the partial record with every field absent. Each `build_from` merges a smaller -struct's fields into it, matching them by name and flipping each from absent to present. The types -change at every step, tracking what has been filled in. +Here `database` and `http` are smaller records whose fields together supply `App`. `builder()` +creates a partial record with every field absent. Each `build_from` moves the source fields into +matching target fields and returns a builder type that marks those fields present. -That tracking is the whole safety argument. `finalize_build` exists **only** for the configuration with -every field present, so finalizing early is not a runtime panic or a `None`. It does not compile: +Merging requires matching names and value types. Every source field must be accepted by the target +builder; `build_from` does not silently discard fields the target lacks. The source needs the +whole-field and extraction support supplied by `CgpData`, and the target needs the builder support. +The `CanBuildFrom` trait providing the method is imported from `cgp::core::field::impls`. + +`finalize_build` is available only when every field in the strict builder is present. If `App` +requires an `http_timeout` field, supplying only the database configuration leaves construction +incomplete: ```rust // `http_timeout` has never been set, so there is no `finalize_build` to call. @@ -85,57 +93,65 @@ let app: App = App::builder() .finalize_build(); ``` -And because presence is tracked per field rather than by position, the order the pieces arrive in does -not matter. +That final call fails to compile because the partial record does not implement the required +finalization trait. The error occurs before the program runs, rather than producing a partially +initialized `App` or a runtime failure. + +Independent field contributions can arrive in any order. A provider that reads a previously built +field must still run after the provider that supplies it. The field-state types enforce that +requirement as well as final completeness. ## The pattern this is for -The machinery buys the **extensible builder**: each subsystem is a provider producing its own -small struct, knowing nothing about the target or about its siblings, and a dispatcher runs them all and -merges the outputs into the whole. +The **extensible builder pattern** assembles a target from independent providers, each producing a +small record. A dispatcher runs the providers, merges their outputs, and finalizes the target. +Each provider needs to know its own output fields, but not the final target or the other contributors. -The list of contributors is then wiring, so swapping a subsystem is a line, and a second application -built from a different mix of the same providers is another table. The same thing as above guarantees -the mix is complete: if the providers between them do not supply every field, the build does not -finalize and the code does not compile. +Wiring chooses the target and its contributors. Replacing a subsystem provider changes the assembly +without changing the generic dispatcher, and another application can reuse the same providers for a +different compatible target. The compiler checks that the chosen outputs supply the required fields. -The dispatcher is one of the [dispatch combinators](./dispatching.md), which is where the general form -of "run a handler per field" lives. +[Dispatching](./dispatching.md) explains how `BuildWithHandlers`, `BuildAndSetField`, and +`BuildAndMerge` sequence field computations. `BuildAndMergeOutputs` provides the related convenience +form for assembling a target from provider outputs. ## What it costs -**Only types that opted in.** All of this works on a struct that derives the shape. A struct from -another crate that has not is invisible to it. That is the honest difference between this and runtime -reflection, and the thing to say first when someone reads "generic over any type's structure". +Generic construction requires the corresponding traits. Deriving `CgpData` supplies them for a +supported struct, but a foreign struct without that support does not become accessible automatically. +A local wrapper or explicit conversion may be needed at that boundary. + +Field names and types form the contract between contributors and the target. Two subsystems that +use `timeout: u32` for different purposes still describe the same field. The compiler checks type +compatibility and builder state, not the intended meaning. Renaming a required field breaks the +merge or leaves the target incomplete when checked. -**Fields match by name and type, with nothing checking intent.** Two subsystems that both produce a -`timeout: u32` are producing the same field as far as merging is concerned. The decoupling depends on -exactly that, and it means a rename in one place silently stops matching in another. +Partial-record types can produce verbose diagnostics. An error may include the target's fields and +presence markers instead of a short message naming the omitted field. Checking smaller assembly +steps can help locate the contribution that is missing or incompatible. -**The error messages are the worst in CGP.** A missing field surfaces as an unsatisfiable bound over a -partial record whose type spells out every field and its presence marker. It is accurate, it is long, -and there is no version of it that reads like "you forgot `http_timeout`" without the toolchain's help. +The strict builder requires every field, even if an application considers some optional. An +`Option` field still needs a value such as `None`. CGP also provides optional-field and default +extensions, but those use additional conventions beyond the strict construction shown here. -**And it is a lot of machinery for a constructor.** An application assembled in one place, by code that -is allowed to know the type, should be assembled with a struct literal. This earns its keep when the -contributors must not know the whole: a plugin set, a framework building a user's type, or several -applications sharing subsystems. +A struct literal or ordinary constructor is simpler when the assembly code can name the target. +Extensible construction is useful when a framework builds user-defined records or when several +applications reuse independently written subsystem providers. ## Where to go next -[Extensible variants](./extensible-variants.md) is the dual: an enum as a sum of named variants, with -the same tracking used for exhaustiveness instead of completeness. [Dispatching](./dispatching.md) is -what runs a handler per field and assembles the result, and is the page that makes the builder pattern -above concrete. - -For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) is the umbrella -derive and its slices are [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) for reading -one field, [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) for the whole shape, and -[`#[derive(BuildField)]`](/docs/reference/derives/derive_build_field) for the builder. -[`HasFields`](/docs/reference/traits/shape/has_fields) is the whole-shape view those produce, -[`HasBuilder`](/docs/reference/traits/builder/has_builder) is the builder family, and -[`Field`](/docs/reference/types/field) and [`Symbol!`](/docs/reference/macros/symbol) are the pieces a -shape is made of. +These pages explain related data operations and the traits used here: + +- [Extensible variants](./extensible-variants.md): Tracking excluded enum variants to prove exhaustiveness. +- [Dispatching](./dispatching.md): Running the providers that construct and merge fields. +- [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data): The combined extensible-data derive. +- [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) and + [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields): Individual field access and the + whole-structure representation. +- [`#[derive(BuildField)]`](/docs/reference/derives/derive_build_field) and + [`HasBuilder`](/docs/reference/traits/builder/has_builder): Partial records and construction. +- [`HasFields`](/docs/reference/traits/shape/has_fields), [`Field`](/docs/reference/types/field), and + [`Symbol!`](/docs/reference/macros/symbol): The types that describe a record's fields. --- diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index eee1d8ed..a7d0e2f8 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -5,34 +5,32 @@ sidebar_position: 14 # Extensible variants -Constructing and matching an enum through the names of its variants, with exhaustiveness still -checked by the compiler. - -This page answers *how does code handle an enum whose variants it does not know?* It is the dual of -[extensible records](./extensible-records.md) and assumes it. It shows the shape of an enum as a type, -the technique that keeps exhaustiveness checked without a wildcard, and the conversions between enums -that share variants. It closes on the one restriction the derive imposes. +Extensible variants let generic code construct and handle enums through variant names and payload +types. Handlers can be reused across compatible enums, while the compiler still checks that every +variant is covered. This page explains the structural representation, exhaustiveness, and conversions +between enums that share variants. [Extensible records](./extensible-records.md) introduces the +related field representation. ## The problem a `match` builds in -A concrete `enum` plus a `match` puts the full set of variants into every function that consumes it. Add -a variant and every `match` has to change; that is Rust's exhaustiveness check doing its job, and it is -usually what you want. +An exhaustive `match` makes an operation's cases explicit. Adding a variant to an enum makes existing +matches fail to compile unless they already have a pattern that covers it. This is useful when each +operation should be reviewed as the enum changes. -It stops being what you want at exactly two moments. When new variants should be addable **without -editing the code that handles the others**: a plugin adding a message kind, or a downstream crate -extending an expression language. And when a variant is defined **upstream**, where handling it means -forking rather than extending. +Reusable per-variant logic does not always need to change with the enum. A circle-area calculation, +for example, can serve several shape enums, including one extended with triangles. Ordinary helper +functions can share that calculation, but each concrete `match` still has to connect its enum's +variants to the helpers. -This is the [expression problem](https://en.wikipedia.org/wiki/Expression_problem), and the usual -trade is that you can add variants easily or add operations easily, never both. Extensible variants -decouple each variant's handling from the enum itself so that both are additions. +CGP separates the payload handlers from the generic dispatcher that selects them. An operation can +then support another enum by supplying handlers for its additional payloads, leaving existing +handlers unchanged. The enum definitions remain ordinary closed Rust enums: a downstream crate +extends the design by defining another enum, not by adding variants to an upstream definition. ## An enum as a list of named variants -The move is the same as for a record: give the shape a type with -[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data). Where a record is a *product* of named -fields, an enum is a *sum* of named variants: +[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) exposes an enum's structure and +provides generic construction and extraction operations: ```rust #[derive(CgpData)] @@ -42,34 +40,41 @@ pub enum Shape { } ``` +For `Shape`, the generated `HasFields::Fields` associated type is a sum of named payloads: + ```rust Sum![Field, Field] ``` -Each entry pairs the variant's name, lifted into a type, with its payload. Generic code can now be -written against "an enum containing a `Circle` variant" rather than against `Shape`. +Each `Field` pairs a variant-name tag with its payload type. A sum holds one of those alternatives, +where a record's product holds all its fields. Generic code can require an operation on the +`Circle` variant without naming `Shape` itself. -## Exhaustiveness without a wildcard +Construction uses the same tags. A `FromVariant` bound lets generic code supply a payload for a +named variant, while the implementing enum determines how to construct the value. Extraction +provides the corresponding operation for taking a payload out. -Taking a value apart runs through a **partial variant**, and this is where the design earns its keep. +## Exhaustiveness without a wildcard -The value is first converted into a form in which every variant is still possible. Then each variant is -tried in turn. If the value is that variant, its payload comes out. If not, the result is a *remainder*: -the same value, with that one variant ruled out **in the type**. +A **partial variant** tracks which alternatives remain possible during extraction. Converting an +enum value to its extractor starts with every variant possible. Each extraction attempt either +returns the requested payload or returns a remainder whose type excludes that variant. -Each miss therefore narrows the type. After every variant has been tried, the remainder is a type that -rules out everything, and a type that rules out everything is uninhabited: a value that cannot exist. -The final step discharges it with a `match` that has no arms, which is sound precisely because there is -nothing to handle. No wildcard arm, no `unreachable!()`. +An unsuccessful attempt narrows the remainder type without losing the value. For `Shape`, failing +to extract `Circle` leaves only `Rectangle` possible. If every variant has been excluded, the +remainder is uninhabited: its type cannot contain a value. -And the guarantee is the one a concrete `match` gives. Add a variant to the enum without handling it and -the final remainder becomes inhabited again, so the code stops compiling until the new variant is -covered. The guarantee is recovered for generic code that never named the enum. +Finalization requires an uninhabited remainder, so the compiler verifies that extraction covers +every variant. The final operation eliminates that impossible remainder without a wildcard arm or +`unreachable!()`. Adding an unhandled variant leaves a possible case and prevents finalization from +compiling. Borrowed and mutable extractor forms preserve the same tracking without consuming the +original enum. ## One handler, many enums -Put together, a per-variant handler set is written once and applied to any enum whose variants it -covers: +A generic handler can cover several payload types and therefore serve several enums. This handler +converts any `Display` payload to a string, while `MatchWithFieldHandlers` generates an extraction +step for each variant: ```rust #[cgp_computer] @@ -87,71 +92,79 @@ delegate_components! { } ``` -`App` can now stringify a two-variant `Reading` and a three-variant `ExtendedReading` through the same -wiring, with no arm added anywhere, because the handler is written against a variant rather than against -an enum. That is the **extensible visitor**: the logic for each variant lives on its own, and a dispatcher -routes a value to whichever one matches. [Dispatching](./dispatching.md) is the page for the dispatcher -itself. +Suppose `Reading` contains `Temperature(u64)` and `Label(String)`, while `ExtendedReading` also +contains `Flag(bool)`. The same wiring handles both enums because every payload implements `Display`. +The handler ignores the variant tag and formats its value. An added payload without `Display` would +make this wiring fail to satisfy the enum's computation. + +Separate providers can supply different behavior for different payloads. In the **extensible +visitor pattern**, those providers remain independent of the full enum, and a dispatcher routes the +current variant to its handler. [Dispatching](./dispatching.md) explains how the context selects them. -## Enums that share variants convert for free +## Converting enums that share variants {#enums-that-share-variants-convert-for-free} -Because variants are matched by name, two enums with overlapping variants interconvert with no -hand-written conversion. +Structural casts convert compatible enums without a handwritten conversion implementation. They +match variant names and payload types; sharing names alone is insufficient. The generated code +selects the current variant and reconstructs it in the target enum at runtime. -**Widening always succeeds**, because every variant of the narrow enum has a place in the wide one: +Widening always succeeds when the target supports every source variant with the same payload type. +For the `Reading` and `ExtendedReading` types above: ```rust let wide: ExtendedReading = narrow.upcast(PhantomData::); ``` -**Narrowing may not**, so it returns a `Result`, with the failure carrying a remainder that can be tried -against another candidate: +Narrowing checks whether the current variant belongs to the smaller target enum. It returns the +target value on success or an extraction remainder on failure: ```rust let narrow: Result = wide.downcast(PhantomData::); ``` -Widening is also how a provider constructs a value using only the variants it knows about: build a small -local enum, lift it into the full one. That is the variant-side counterpart of reading a field through a -getter: code touching part of a shape without naming the whole. +`ExtendedReading::Label` can become `Reading::Label`, but `ExtendedReading::Flag` cannot become a +`Reading`. The remainder preserves the unmatched value, and `CanDowncastFields` can try it against +another target. Import the cast traits from `cgp::core::field::impls` when using these methods. + +A provider can also construct a small local enum and widen it into a compatible application enum. +The provider then needs to know only the variants it produces, while the application chooses the +complete result type. ## What it costs -**One unnamed field per variant.** A derivable enum must be a sum of products: each variant holds -exactly one unnamed payload. A richer variant wraps its data in a dedicated struct, which is why the -example above is `Circle(Circle)` rather than `Circle { radius: u64 }`. It is a real constraint on how -the enum is written, and it is the first thing anyone hits. The constraint comes from constructing and -deconstructing rather than from the shape itself: -[`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) accepts every variant shape, so an -enum that cannot take the full family can still have a structural representation, with no generic -constructor and no extractor. +The full construction and extraction derives require exactly one unnamed payload per variant. +A richer case must wrap its fields in a payload type, such as `Circle(Circle)` instead of +`Circle { radius: u64 }`. Unit variants also need a payload if they are to use these derives. +[`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) can describe all variant shapes, +but that structural description alone does not supply generic constructors or extractors. -**Only types that opted in**, as with records. An enum from a crate that has not derived the shape is -invisible to all of this. +An enum must implement the traits used by the generic operation. A foreign enum without them is +not automatically available to the dispatcher, and CGP does not permit adding variants to it. +A local enum with the required support can provide the extensible boundary and convert to other +representations where necessary. -**The errors are long, and this is where they are longest.** An unhandled variant surfaces as a bound on -a partial-variant type spelling out every variant and its presence marker. It is the accurate report of -"you did not cover everything", and it does not read like one. +Unhandled variants can produce long trait errors. The diagnostic may name a missing payload-handler +bound or a partial-variant type whose markers describe the remaining cases. This is less direct to +read than an ordinary non-exhaustive `match` error. -**And a closed enum with fixed operations should stay one.** A `match` is clearer, faster to read, and -free. This pays when the variant set is genuinely open, or when independent modules must each contribute -one, not when an enum merely has several variants. +A concrete `match` is usually easier to follow when an enum and its operations are maintained +together. Extensible variants help when operations must work across different enum definitions or +when new cases should reuse existing handlers without editing them. ## Where to go next -[Extensible records](./extensible-records.md) is the other half, and worth reading first if the shape -type above was unfamiliar. [Dispatching](./dispatching.md) is the machinery that runs a handler per -variant, and [Type-level DSLs](./type-level-dsls.md) is the largest thing this pattern builds: a -language whose terms are types and whose interpreter is the trait system. - -For the constructs, [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) is the umbrella -derive and its slices are [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) for the -whole shape, [`#[derive(ExtractField)]`](/docs/reference/derives/derive_extract_field) for the -narrowing, and [`#[derive(FromVariant)]`](/docs/reference/derives/derive_from_variant) for construction -by name. [`ExtractField`](/docs/reference/traits/variant/extract_field) is the extractor family those produce, -[`FromVariant`](/docs/reference/traits/variant/from_variant) constructs a variant generically, and -[the casts](/docs/reference/traits/casting/can_upcast) are `CanUpcast` and -[`CanDowncast`](/docs/reference/traits/casting/can_downcast). +These pages explain the related representations and operations: + +- [Extensible records](./extensible-records.md): Field-based construction and completeness. +- [Dispatching](./dispatching.md): Connecting variants to handlers. +- [Type-level DSLs](./type-level-dsls.md): Using composable handlers to interpret typed programs. +- [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) and + [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields): Structural support and its subsets. +- [`#[derive(ExtractField)]`](/docs/reference/derives/derive_extract_field) and + [`ExtractField`](/docs/reference/traits/variant/extract_field): Extraction and narrowed remainders. +- [`#[derive(FromVariant)]`](/docs/reference/derives/derive_from_variant) and + [`FromVariant`](/docs/reference/traits/variant/from_variant): Construction by variant name. +- [`CanUpcast`](/docs/reference/traits/casting/can_upcast) and + [`CanDowncast`](/docs/reference/traits/casting/can_downcast): Widening and narrowing compatible enums. --- diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 7bb12191..8a47ac84 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -5,62 +5,62 @@ sidebar_position: 11 # Handlers -The family of computation components, and the three axes that tell them apart: synchronous or async, -fallible or not, and taking an input or not. - -This page answers *why does CGP ship a dozen computation components instead of one?* It gives the shape -they share, the three axes that separate them, the promotion that means you only ever write the -simplest one, and how a pipeline becomes a wiring entry. It closes on when a plain function is the -better answer. +CGP's handler components let a context select and compose computations through wiring. Separate +interfaces describe whether a computation is synchronous or async, returns a fallible result, and +consumes or borrows its input. This page explains those choices, the adapters between them, and how +providers form a pipeline. ## Computation as something a context decides -Most CGP components are capabilities an application has: send email, query a user, load a file. The -handler family is for a different thing: a *computation* the application performs on a value, where -the interesting question is not "can it" but "which one, and composed how". - -Everything in the family shares one shape: +Handler components provide a common interface for computations that a context can choose. +An application-specific component might expose `send_email` or `load_file`; handlers expose a +uniform input-and-output interface that generic combinators can connect. -> given a context, a `Code` tag, and an `Input`, produce an `Output`. +An input-taking handler receives a context, a `Code` tag, and an `Input`, then produces an `Output`. +The context supplies dependencies and wiring. The tag identifies the computation, and the input +contains the value being processed. The provider selects `Output` through an associated type. -The `Code` is a phantom type carrying no data. Its job is to let one context host many different -computations, each keyed by a distinct tag, so wiring can dispatch on it. The `Output` is an -*associated* type rather than a parameter, so the provider decides what a given `Code` and `Input` -produce and downstream wiring reads that decision back. +The `Code` tag lets one context select several computations for the same input type. It is passed +as `PhantomData`, which carries type information without storing a `Code` value. A program +with only one computation can use `()` as its tag. -That is the whole model. The family exists because computations differ along a few axes, and forcing -every one into the most general signature would make a pure function claim capabilities it does not -have. +Different interfaces keep unnecessary requirements out of simple computations. An addition provider +can return its output synchronously without requiring an error type or returning a future. Adapters +can expose that provider through a more general interface when composition requires it. ## Three axes, and the names that encode them -**Synchronous or asynchronous.** A synchronous member returns immediately; an asynchronous one returns -a future and carries `Async` in its name, as `AsyncComputer` beside `Computer`. +The main input-taking components vary by execution and error handling. Their consumer traits give +callers the corresponding methods: -**Infallible or fallible.** A fallible member returns a `Result` against the context's -[abstract error type](./modular-error-handling.md), and carries `Try`, as `TryComputer` beside `Computer`. +| Provider trait | Consumer method | Execution | Result | +| --- | --- | --- | --- | +| [`Computer`](/docs/reference/components/handler/computer) | `compute` | Synchronous | `Output` | +| `AsyncComputer` | `compute_async` | Async | `Output` | +| [`TryComputer`](/docs/reference/components/handler/try_computer) | `try_compute` | Synchronous | `Result` | +| [`Handler`](/docs/reference/components/handler/handler) | `handle` | Async | `Result` | -**Owned or borrowed input.** A `*Ref` variant takes `&Input` where the base takes `Input`, for a -computation that only reads its argument. +Synchronous methods finish their work before returning; async methods return futures that perform +work when polled. Fallible interfaces use the context's +[abstract error type](./modular-error-handling.md). “Infallible” describes the interface's lack of an +error channel; it does not guarantee that the implementation cannot panic or perform side effects. -Cross those and you get the members that are documented separately: -[`Computer`](/docs/reference/components/handler/computer) is the pure synchronous corner, -[`TryComputer`](/docs/reference/components/handler/try_computer) the fallible synchronous one, and -[`Handler`](/docs/reference/components/handler/handler), async *and* fallible, the general workhorse, which is -why it needs no qualifier. [`Producer`](/docs/reference/components/handler/producer) sits slightly apart: a -computation with no input at all, producing a value from the context and a tag. +Input ownership supplies the other distinction. The base components take `Input` by value, while +siblings such as `ComputerRef` and `HandlerRef` take `&Input`. This lets the interface express +whether the computation consumes or borrows its argument. -The point of the spread is that a provider declares exactly the capabilities it has. A function adding -two numbers is a `Computer`, and nothing about it should mention futures or errors. +[`Producer`](/docs/reference/components/handler/producer) supplies a value without an input +argument. It uses the context and tag alone, which suits constants and context-derived values. +Producer adapters can expose that behavior through input-taking interfaces by ignoring the input. -## Write the weakest one; the rest come free +## Write the simplest suitable provider {#write-the-weakest-one-the-rest-come-free} -Which raises the obvious objection: if wiring wants a `Handler` and you wrote a `Computer`, have you -picked wrong? No. The inclusions between the axes are real (an infallible computation is a fallible one -that never fails, a synchronous one is an async one that never awaits), and CGP encodes each as a -combinator that lifts a provider from one member into another. +Promotion adapters let a provider support another computation interface without duplicating its +body. An infallible result can be wrapped in `Ok`, and synchronous work can be performed inside an +async method. These adaptations preserve the computation; wrapping blocking work in a future does +not make the work nonblocking. -The practical result is that one definition answers the whole family: +`#[cgp_computer]` generates a provider and its promotion wiring from a function: ```rust #[cgp_computer] @@ -69,9 +69,12 @@ fn add(a: u64, b: u64) -> u64 { } ``` -`Add` is now callable as `compute`, `try_compute`, `compute_async`, and `handle`, plus their -by-reference forms. A body that returns a `Result` promotes the same way, with its error path surfacing -through the fallible members: +The macro preserves `add` and creates an `Add` provider. Its input is the tuple `(u64, u64)`, so a +direct call takes the form `Add::compute(&app, PhantomData::<()>, (1, 2))`. Promotion also exposes +`try_compute`, `compute_async`, and `handle`; the fallible forms require the context's error-type +support even though this function does not return an error. + +A `Result`-returning function can also expose its error through the fallible interfaces: ```rust #[cgp_computer] @@ -80,14 +83,23 @@ fn checked_add(a: u64, b: u64) -> Result { } ``` -So the rule when writing is simply: **write the weakest member that fits, and let the wiring ask for -whatever it needs.** You do not have to predict which one a caller will want. +`CheckedAdd::compute` returns `Result` as its output value. The promoted +`try_compute` and `handle` forms treat that result as success or failure and require a context whose +error type matches `String`. Promotion does not automatically convert an arbitrary source error into +another error type. + +Borrowed interfaces require a compatible borrowed-input implementation. Promotion does not let a +provider consume an arbitrary value through a shared reference. Likewise, an async provider does +not gain a synchronous implementation merely by being placed in a promotion table. + +Choose the simplest interface that expresses the computation, then use the adapters supported by +its signature. The function macros generate suitable promotion wiring; a manually implemented +provider needs explicit adapters when another interface is required. ## A pipeline is a wiring entry -Because every member is an ordinary component, composing computations is composing providers, and the -combinators that do it are [higher-order providers](./higher-order-providers.md), so a whole chain has a -name and lives in a table: +A handler pipeline is a provider that passes each stage's output to the next stage. Because the +stages share the handler interface, the context can select the whole pipeline through one entry: ```rust delegate_components! { @@ -103,19 +115,23 @@ delegate_components! { } ``` -`PipeHandlers` runs the stages left to right, threading each output into the next input. Each stage here -reads one field from the context and folds it into the running value, so `app.compute(…, 5)` evaluates -`((5 * foo) + bar) * baz`, and the shape of the computation is a line of wiring rather than a function -body. Changing the order, dropping a stage, or swapping one for another is an edit to a type. +Here `Multiply` and `Add` are field-reading providers: each reads the context field +identified by `Tag` and combines it with the input. This `Add` is separate from the +function-generated `Add` in the previous example. The pipeline computes `((5 * foo) + bar) * baz` +when given input `5`. + +`PipeHandlers` runs the listed providers from left to right. Each stage's output type must satisfy +the next stage's input requirements, and the final stage determines the pipeline's output. The +fallible forms stop on the first error; async forms await each stage in sequence. -`ComposeHandlers` nests rather than chains, `ReturnInput` passes a value through, and the `Promote*` -adapters are the lifts from the previous section made explicit. They are catalogued together in -[handler combinators](/docs/reference/providers/handler). +`ComposeHandlers` is the two-stage form: run `A`, then pass its result to `B`. `PipeHandlers` +constructs nested compositions from its provider list. `ReturnInput` passes its input through +unchanged, and the `Promote*` adapters connect compatible interfaces. The +[handler combinator reference](/docs/reference/providers/handler) describes their bounds. ## Many computations on one context -The `Code` tag stops a context being limited to one computation per member of the family. Two -tags, two providers, one table: +Different `Code` tags let the same context select different computations for the same input type: ```rust delegate_components! { @@ -128,49 +144,53 @@ delegate_components! { } ``` -`App.compute(PhantomData::, 21)` and `App.compute(PhantomData::, 21)` reach different -providers. Dispatch can key on the `Input` type as readily as on the `Code`. That is how -[dispatching](./dispatching.md) over extensible data works, and how a program written as types becomes -interpretable, as [type-level DSLs](./type-level-dsls.md) shows. +`App.compute(PhantomData::, 21i64)` selects `ComputeDoubled`, while the `Negated` tag selects +`ComputeNegated`. This table names a code tag followed by the input type for each entry, so the +compiler can resolve the requested pair. + +Input-driven dispatch can instead use `UseInputDelegate` with a table keyed by input type. +[Dispatching](./dispatching.md) uses that form to route an enum and its payloads to different +providers. The tag can also describe a larger program, as in [type-level DSLs](./type-level-dsls.md). ## What it costs -**The `PhantomData` at every call site.** `app.compute(PhantomData::<()>, input)` is the price of the -tag being a type. For a context with one computation it is pure ceremony, and it does more than anything -else to make handler code look unlike ordinary Rust. +A handler call needs a type tag even when the application has only one computation. +`PhantomData::<()>` supplies it, but adds syntax compared with an ordinary function call. + +The family introduces several component and adapter names. The execution, error, and ownership +choices explain their relationships, but reading a pipeline still requires knowing which +interfaces each stage supports. Start with the form the computation needs and consult the adapter +bounds when connecting it to another form. -**The family is a lot of names to hold.** Twelve or so components across three axes, plus the promotion -combinators, is more surface than any other part of CGP. The mitigation is the rule above, to write the -weakest member and ignore the rest, but reading someone else's handler wiring means knowing which -member each name belongs to. +Type-level composition makes some failures harder to locate. A mismatched stage can produce a trait +error involving an associated `Output` type rather than a line in a function body. +[Provider checks](./check-traits.md) help isolate the incompatible stage. Runtime debugging remains +possible inside each provider's method body, although the wiring table itself is not executable +code where a breakpoint or log statement can be placed. -**A pipeline in a type is harder to debug than a function body.** There is no line to step through and -no place to add a print. A wrong stage shows up as a type mismatch between two providers, phrased in -terms of an `Output` associated type, and localizing it means the per-layer checks from -[checking your wiring](./check-traits.md). +Async handler interfaces do not promise that their returned futures are `Send`. Spawning a task on +an executor that requires `Send` needs an additional guarantee, described in +[Recovering `Send` bounds](./send-bounds.md). -**And most computations should stay functions.** This family earns its keep when the *steps* need to be -chosen by wiring: when different contexts run different pipelines, or a program is data. A computation -with one implementation is a function, and [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is how to write -one that still reads its inputs from a context. +A plain function is simpler when a computation does not need interchangeable stages or context-specific +composition. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) provides a lighter option when a single +implementation needs values or capabilities from a context without handler wiring. ## Where to go next -[Monadic handlers](./monadic-handlers.md) is the next thing a pipeline needs: what happens when a stage -produces a result the chain should stop on. [Dispatching](./dispatching.md) is the family applied to the -shape of a record or an enum, and the family becomes a [type-level DSL](./type-level-dsls.md) when the -`Code` tag carries a whole program. - -[Higher-order providers](./higher-order-providers.md) is the mechanism the combinators are built from, -and worth reading first if `PipeHandlers` looked like new machinery. - -For the constructs, [`Computer`](/docs/reference/components/handler/computer), -[`TryComputer`](/docs/reference/components/handler/try_computer), -[`Handler`](/docs/reference/components/handler/handler), and -[`Producer`](/docs/reference/components/handler/producer) are the corners; -[`#[cgp_computer]`](/docs/reference/macros/cgp_computer) and -[`#[cgp_producer]`](/docs/reference/macros/cgp_producer) build a provider from a function; and -[handler combinators](/docs/reference/providers/handler) is the full catalogue. +These pages explain composition and specify the handler interfaces: + +- [Monadic handlers](./monadic-handlers.md): Pipelines whose results decide which branch continues. +- [Dispatching](./dispatching.md): Handlers applied to record construction and enum variants. +- [Type-level DSLs](./type-level-dsls.md): Tags that represent programs. +- [Higher-order providers](./higher-order-providers.md): The provider composition used by combinators. +- [`Computer`](/docs/reference/components/handler/computer), + [`TryComputer`](/docs/reference/components/handler/try_computer), + [`Handler`](/docs/reference/components/handler/handler), and + [`Producer`](/docs/reference/components/handler/producer): Component signatures and requirements. +- [`#[cgp_computer]`](/docs/reference/macros/cgp_computer) and + [`#[cgp_producer]`](/docs/reference/macros/cgp_producer): Generating providers from functions. +- [Handler combinators](/docs/reference/providers/handler): Composition and promotion adapters. --- diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index 88423760..de2a8507 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -5,22 +5,16 @@ sidebar_position: 7 # Higher-order providers -Providers parameterized by other providers, so one implementation can be expressed in terms of -another. - -This page answers *how does one implementation build on another without choosing which one?* It shows -the shape, the one piece of syntax that makes it look strange, and the two things it buys: composition -without a context, and a wrapper that falls back to whatever the context already decided. It closes on -why this is the step most often taken too early. +A **higher-order provider** takes another provider as a type parameter and uses it to perform part +of its work. A wrapper can then reuse the same transformation with different inner implementations. +This page explains the inner-provider bound, composition before a context is chosen, and delegation +back to the context through `UseContext`. ## Choosing is not the only thing you can do with a provider -Wiring picks one implementation from several. That covers a lot, and it does not cover the case where -you want *the same transformation over any of them*. - -A scaled area is that case. Scaling knows how to multiply by a factor squared; it does not know how to -compute an area, and there is no reason for it to. The base calculation is not something the wrapper -should choose. It is something the wrapper should take: +A provider parameter separates a reusable transformation from the calculation it transforms. +For example, scaling an area requires multiplying a base area by a scale factor squared. The +scaling logic can accept any provider that calculates the base area: ```rust #[cgp_impl(new ScaledArea)] @@ -33,27 +27,32 @@ impl AreaCalculator { } ``` -`ScaledArea` is a **higher-order provider**: a provider with another provider as a parameter, bound to -supply part of the work. Wiring `ScaledArea` reads as "compute the rectangle area, then -scale it", and `ScaledArea` reuses the same scaling over a different base: +`ScaledArea` requires `Inner` to implement `AreaCalculator` for the same context. +It passes that context to `Inner::area`, then applies the `scale` value read from the context's +field. The wrapper supplies the scaling logic; its type parameter selects the base calculation. + +Wiring chooses the combination for each context. A rectangle and a circle can reuse the wrapper +with different inner providers: ```rust delegate_components! { ScaledRectangle { AreaCalculatorComponent: ScaledArea } } delegate_components! { ScaledCircle { AreaCalculatorComponent: ScaledArea } } ``` -This is passing a function to a function, done in types. And because a provider is a name rather than a -value, nesting them costs nothing at runtime: the composition resolves during compilation, and only -a direct call executes. +Here `ScaledRectangle` and `ScaledCircle` hold the shape data and the scale factor. Each must +satisfy both the wrapper's field requirement and its selected inner provider's requirements. +`RectangleArea` needs the rectangle's dimensions, while `CircleArea` needs the circle's radius. -## The extra ``, and the attribute that fills it in +Provider composition uses types rather than stored provider values. The compiler resolves the +inner call statically, without a runtime provider lookup. The selected methods still execute their +calculations; inlining and other optimizations determine the final machine code. -One detail makes these look stranger than they are, and it is worth meeting deliberately rather than in -an error message. +## The extra ``, and the attribute that fills it in -The [trait split](./consumer-and-provider-traits.md) gives a provider trait the context as an explicit -parameter. So when a wrapper requires its inner provider to implement the same capability, the -requirement has to name that context slot: +An inner-provider bound must identify the context on which the provider operates. The +[consumer/provider split](./consumer-and-provider-traits.md) gives `AreaCalculator` a leading +context parameter. Inside `#[cgp_impl]`, `Self` names that context, so the explicit bound is +`Inner: AreaCalculator`: ```rust #[cgp_impl(new ScaledArea)] @@ -67,36 +66,43 @@ where } ``` -`AreaCalculator` has no counterpart in the consumer trait a reader has been looking at, so it -arrives as an unexplained argument. [`#[use_provider]`](/docs/reference/attributes/use_provider) exists -to remove it: write `Inner: AreaCalculator` and the attribute supplies the ``, which is the whole -of what it does. That is the version in the first snippet, and it is the one to write. +[`#[use_provider]`](/docs/reference/attributes/use_provider) generates that bound from the shorter +`Inner: AreaCalculator` form in the first example. It inserts the context argument and adds the +requirement to the implementation's `where` clause. Prefer this form when declaring an inner +provider dependency. -The attribute does *not* change the call. `Inner::area(self)` stays as it is: you invoke the inner -provider as an associated function with the context passed explicitly, because that is the shape the -provider trait actually has. It is the one place in a well-written provider where the trait split is -still visible, and trying to make it read as `self.area()` would be calling the context's own wiring, -which is a different thing entirely. +The attribute changes bounds, not calls. `Inner::area(self)` invokes the selected inner provider +with the context passed explicitly. A call to `self.area()` would instead use the context's consumer +trait implementation, which may route back to the wrapper rather than to `Inner`. ## Composition without a context to name -The quiet payoff is that composing two providers costs nothing to declare: +A type alias can name a provider composition before any context uses it: ```rust pub type ScaledScaledRectangleArea = ScaledArea>; ``` -A type alias, with no bounds on it at all. Compare what composing two constrained generic functions -normally takes: the composed signature restating both sets of constraints, in Rust as much as in -Haskell. Here the requirements are discharged where a context wires the stack, not where the stack is -written, so a composition is just a name for a shape and can be published, reused, and further wrapped -without accumulating a `where` clause. +The provider structs carry their dependencies on their trait implementations, so this alias does +not need to repeat those bounds. It names a composition that can be published, reused, and wrapped +again without selecting a context or proving that a particular context satisfies it. + +The requirements are checked when code uses the composition or explicitly checks it for a context. +A wiring entry alone does not prove they hold. For this alias, the context needs the dimensions +required by `RectangleArea` and the `scale` field used by both wrappers. Both layers read the same +scale value, so nesting them applies its square twice. For base area `12` and scale `2`, the result +is `192`. ## Falling back to what the context already decided -A wrapper often wants a default: use whatever the context is already wired to, unless told otherwise. -[`UseContext`](/docs/reference/providers/use_context) is the provider that means exactly that, and a -default parameter makes it the fallback: +[`UseContext`](/docs/reference/providers/use_context) lets an inner step use the context's existing +consumer-trait implementation. A default type parameter makes that the wrapper's behavior unless +the wiring names another provider. + +Summing areas illustrates a useful default because the collection and its elements need different +implementations. In this example, `ShapeAreaCalculator` calculates the area of a +separate `Shape` value. The context represents an application that chooses how to measure each +shape, rather than the shape itself: ```rust pub struct SumAreas(pub PhantomData); @@ -110,8 +116,9 @@ impl ShapeAreaCalculator> { } ``` -Written unparameterized in a table, `SumAreas` means `SumAreas`, so summing a collection -asks the context how to measure each element: +`SumAreas` means `SumAreas` when its type argument is omitted. The wrapper asks the +context to calculate each element's area, then adds the results. An application can select a +rectangle provider and reuse the summing provider for vectors: ```rust delegate_components! { @@ -124,15 +131,24 @@ delegate_components! { } ``` -Naming an inner provider instead, `SumAreas`, pins that step regardless of what the -context would have said, which is how one entry overrides a nested decision without disturbing the rest -of the table. The default only exists when the provider is declared with an explicit struct; one -declared inline by the attribute has no parameter to default. +`open ShapeAreaCalculatorComponent;` enables provider selection by the component's shape parameter. +A call for `Vec` selects `SumAreas`. Each inner call then asks for the `Rectangle` +capability and reaches `RectangleArea`. The inner lookup is different from the collection lookup, +so it has an independent implementation to resolve to. + +An explicit `SumAreas` uses that provider directly for each element, bypassing +the context's choice for that inner step. It still passes the same context, which must satisfy +`AnotherCalculator`'s requirements. + +Declare the provider struct explicitly to give its parameter the `UseContext` default. The +`#[cgp_impl(SumAreas)]` block implements that existing struct; the `new` form declares a +provider but does not supply this default. ## Not every generic provider is one of these -A provider with a type parameter is not automatically higher-order, and the distinction is worth -keeping because most generic providers are the other kind: +A generic provider is higher-order when its parameter represents a provider used to perform work. +Other parameters may select data, field names, or configuration. This getter uses `Tag` as a field +name: ```rust #[cgp_impl(new GetName)] @@ -146,44 +162,41 @@ where } ``` -`Tag` here is a field name, used as a key. Nothing is delegated to it, nothing implements a capability -on its behalf, and none of the machinery on this page applies. A provider is higher-order when a -parameter is *bound to a provider trait* and invoked to do part of the work. +`GetName` requires the context to supply a `String` field identified by `Tag`. It does not +require `Tag` to implement a provider trait or invoke it as a provider. By contrast, `ScaledArea` +both constrains `Inner` with a provider-trait bound and calls it for the base calculation. ## What it costs -**It is the step most often taken too early.** A provider that is not wrapping anything has nothing to -gain from a parameter, and adding one buys a type argument at every wiring site, a bound to get right, -and a call form that reads unlike the rest of the code. Reach for this when one implementation should -genuinely be expressed in terms of another, not when it merely could be. +An inner-provider parameter adds a choice to the API and a bound to the implementation. Use it when +one transformation needs to work with independently selected implementations. A fixed implementation +with nothing to vary does not benefit from an extra provider parameter. -**A failure names the stack, not the layer.** Checking a context tells you `ScaledArea` -does not work; it does not say which half is at fault. The -[`#[check_providers]`](/docs/reference/macros/check_components) form fixes that by asserting against -each layer separately, and a nested stack is the main reason it exists. But it is another thing to -remember, and without it a deep stack is genuinely hard to debug. +`UseContext` can create a resolution cycle if the inner request selects the same wrapper again. +For example, a wrapper wired for a capability cannot use that same capability as its only base +implementation. The summing example avoids this by requesting the element capability from the +collection provider. Ensure that the inner lookup resolves to an independently available implementation. -**Compile-time work grows with depth.** Each layer is another round of trait resolution, and a stack -that is several deep and instantiated at many types is one of the places CGP's compile-time cost is most -visible. +A nested composition can make failures harder to locate. An error on `ScaledArea` +may not immediately distinguish the scaling requirement from the rectangle requirements. +The [`#[check_providers]`](/docs/reference/macros/check_components) form gives each provider a +separate assertion against the same context, helping identify which layer lacks a dependency. -**And the call form stays visible.** `Inner::area(self)` is the one construct here that still reads -inside-out, and no attribute hides it. It is a small cost on every higher-order provider written. +Deeper compositions add trait-resolution work, especially when instantiated for many contexts. +They also add types and delegation steps for a reader to follow. The explicit `Inner::area(self)` +call makes the inner choice visible, but requires familiarity with provider-style calls. ## Where to go next -[Aggregate providers](./aggregate-providers.md) is the other thing a provider parameter is confused -with: bundling several wiring choices under one name, which composes tables rather than behaviour. -[Checking your wiring](./check-traits.md) covers the per-layer check this page needs. - -[Handlers](./handlers.md) is where composition of this kind is the whole point: a family of -computation components whose combinators are higher-order providers, chained into pipelines. +These pages explain related forms of composition and their checks: -For the constructs, [`#[use_provider]`](/docs/reference/attributes/use_provider) completes the inner -bound, [`UseContext`](/docs/reference/providers/use_context) is the fallback, -[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) writes the provider, and -[`delegate_components!`](/docs/reference/macros/delegate_components) carries the `open` statement the -last example uses. +- [Aggregate providers](./aggregate-providers.md): Sharing a group of wiring choices through one provider. +- [Checking your wiring](./check-traits.md): Checking the context and individual provider layers. +- [Handlers](./handlers.md): Higher-order providers used as computation and pipeline combinators. +- [`#[use_provider]`](/docs/reference/attributes/use_provider): Inner-provider bounds and context arguments. +- [`UseContext`](/docs/reference/providers/use_context): Forwarding to the context's consumer trait. +- [`#[cgp_impl]`](/docs/reference/macros/cgp_impl): Provider definitions and explicit provider structs. +- [`delegate_components!`](/docs/reference/macros/delegate_components): Wiring and `open` dispatch. --- diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index 09414ab6..ed0d4b5d 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -5,17 +5,15 @@ sidebar_position: 3 # Impl-side dependencies -Declaring what an implementation needs in the implementation itself, so the requirement never -reaches the callers of the interface. - -This page answers *how does an implementation say what it needs, without every caller having to know?* -It starts from a technique already available in ordinary Rust, shows why CGP is built on it, and works -through the three kinds of thing an implementation can ask its context for. It closes on what the -arrangement costs, which is mostly paid in error messages. +An **impl-side dependency** is a requirement stated on an implementation without being part of its +trait interface. Callers can require the capability they use while the compiler checks the selected +implementation's dependencies. This page starts with ordinary Rust blanket implementations, then +shows how CGP providers require capabilities, field values, and context-selected types. ## What a `where` clause costs the callers above it -A generic function that needs something says so in its signature, and that is the whole difficulty: +A generic function exposes its requirements through its signature. This greeting function needs +`HasName` to obtain the name it formats: ```rust pub trait HasName { @@ -30,8 +28,8 @@ where } ``` -Nothing is wrong with this until something calls it. A caller that is itself generic cannot satisfy -`Context: HasName` on its own, so it has to demand the same thing from *its* caller: +A generic caller must establish that requirement too. If it has nothing else that implies +`HasName`, it can add the same bound: ```rust pub fn greet_twice(context: &Context) -> String @@ -42,17 +40,15 @@ where } ``` -`greet_twice` never touches a name. It declares the requirement because the function it calls does, and -the function above `greet_twice` will declare it for the same reason. Add a requirement four layers -down and every layer above grows a bound it has no interest in. This is why a mature generic API -tends to accumulate signatures nobody can read, and why adding a dependency deep in a library is a -change that reaches its users. +`greet_twice` does not read the name itself, but its calls to `greet` require the bound. +Further generic callers must also supply or imply it. Adding a dependency to `greet` can therefore +require changes to callers that only forward the call. This is straightforward for a small API; +it becomes harder to maintain when many layers repeat implementation-specific requirements. ## Moving the requirement onto the implementation -Rust already has the answer, and most Rust programmers have used it without naming it. Put the logic in -a **blanket implementation**, one `impl` covering every type that meets a bound, and the requirement -moves out of the interface and onto the implementation: +A blanket implementation lets callers depend on a capability without naming the dependencies used +to implement it. The trait declares the operation, and the implementation states when it is available: ```rust pub trait CanGreet { @@ -69,8 +65,9 @@ where } ``` -`CanGreet` mentions nothing. Any type with a `name` gets `greet` for free, and a caller says only what -it actually uses: +`CanGreet` promises a greeting method without requiring `HasName` as a supertrait. The blanket +implementation supplies that method for every context implementing `HasName`. A generic caller +can require only the greeting capability: ```rust pub fn greet_twice(context: &Context) -> String @@ -81,24 +78,24 @@ where } ``` -The requirement did not disappear: the compiler still checks it, at the point where a concrete type -meets the impl. It has only stopped being part of the contract. That is an **impl-side -dependency**: something an implementation needs, stated where the implementation lives rather than -where the interface is declared. +The compiler still checks `HasName` when it uses that blanket implementation to establish +`Context: CanGreet` for a concrete type. The requirement remains necessary for the implementation; +it is absent from the caller's trait contract. That separation is the impl-side dependency. -This is the construct CGP is built out of, which is worth saying plainly, because it makes the -foundation something you already have. If you have used `Itertools` or `StreamExt`, you have used a -blanket impl over every `Iterator` or every `Stream`. That is why a method appears on a type whose -author never wrote it. CGP adds not the mechanism but the ability to have more than one of them and -choose between them. +Keeping the interface stable can protect generic callers from implementation changes. If greeting +later needs another dependency, the blanket implementation can add a bound while `greet_twice` +continues to require only `CanGreet`. Concrete contexts must still satisfy the new requirement, +so this does not make every dependency change backward-compatible. -## Two providers, two sets of requirements, one interface +Ordinary Rust already supports this technique. CGP adds separate provider types and wiring when +several implementations need to coexist, including implementations whose context requirements overlap. +[Consumer and provider traits](./consumer-and-provider-traits.md) explains that extension. -The payoff arrives once a capability has more than one implementation, because each one asks for -something different and the interface still says nothing. +## Two providers, two sets of requirements, one interface -Two ways of sending email need entirely different things from the application. One needs a server -address; the other needs somewhere to record what it would have sent: +Each CGP provider can require different context capabilities while implementing the same interface. +An email sender might need an SMTP server getter, while a test implementation needs access to a +recording buffer: ```rust #[cgp_component(EmailSender)] @@ -123,13 +120,13 @@ impl EmailSender { } ``` -`#[uses(...)]` is how a provider declares a capability it needs. It reads like an import, and that is -the right way to take it: the provider is saying *this code relies on the context being able to do -this*. Underneath it becomes a bound on the implementation, exactly as in the blanket impl above. +`#[uses(HasSmtpServer)]` adds a context bound to `SendViaSmtp`'s implementation. +`#[uses(HasSentEmails)]` adds a different bound to `RecordEmails`. Here `HasSmtpServer` supplies +`smtp_server()`, and `HasSentEmails` supplies `sent_emails()` as a reference to a mutable recording +buffer. The SMTP body is omitted; the recording body stores each message in that buffer. -The consequence is worth stating precisely. `CanSendEmail` says nothing about SMTP servers. A -function bounded on it accepts both applications, even though they satisfy it for reasons that have -nothing in common: +`CanSendEmail` exposes neither dependency. A caller needs only that trait, regardless of which +provider supplies it: ```rust pub fn notify(context: &Context) @@ -140,20 +137,24 @@ where } ``` -Both examples here wire a type standing for an application, `App` for production and `TestApp` for a -test harness, rather than a piece of data. That is where most CGP code lives, and it makes the point -clearly: the two applications differ in what they can supply, and the interface between them and -`notify` does not record the difference. +A production `App` can select `SendViaSmtp`, while a `TestApp` selects `RecordEmails`. These contexts +represent applications and supply their chosen provider's dependencies. `notify` accepts either +context through the same bound; the test context does not need an SMTP server merely because +another provider uses one. ## The three things an implementation can ask for -Everything above is one kind of requirement, a capability. There are three, they all work the same -way, and each has a syntax that keeps the bound out of sight. +Provider dependencies commonly describe capabilities, values, or types. CGP expresses them with +attributes that generate the corresponding Rust bounds: -**A capability** is the kind `#[uses]` declares, as above. It covers other CGP capabilities and ordinary -Rust traits alike: `#[uses(AsRef<[u8]>)]` is as valid as `#[uses(HasSmtpServer)]`. +- **Capabilities:** `#[uses(Trait)]` requires the context to implement a trait. It accepts ordinary + Rust traits such as `AsRef<[u8]>` as well as CGP consumer traits. +- **Values:** An `#[implicit]` argument reads a field from the context and generates the field-access + requirement on the implementation. +- **Types:** `#[use_type(Trait.Type)]` names an associated type chosen by the context and adds the + bound needed to use it. Whether that bound belongs in the interface depends on where the type appears. -**A value** is a field the implementation reads; you declare it by writing it as an argument: +An implicit argument lets the implementation ask for a value without adding a public method argument: ```rust #[cgp_impl(new GreetByName)] @@ -164,18 +165,16 @@ impl Greeter { } ``` -The caller does not pass the `name` argument. The provider reads it from a `name` field on the context, -and the macro turns the argument's name and type into a requirement on the implementation, so `greet()` -still takes nothing from the outside. [Implicit arguments](./implicit-arguments.md) develops this one. - -**A type** is the third, and it buys the most, because it displaces not a leaked bound but a leaked -*parameter*. +`GreetByName` reads `name` through the context's field-access implementation. The macro removes the +implicit argument from the method signature, so callers still use `greet()` without passing a name. +[Implicit arguments](./implicit-arguments.md) explains how field names, types, and borrowing determine +that generated requirement. ## Type dependencies, and why they need no parameter -Suppose a job runner should not commit to an error type, a runtime, or a storage backend. The ordinary -way to leave a type open is a generic parameter, and a parameter is an **input**: the caller supplies -it, so it has to appear in the signature. +Associated types let a context collect type choices that would otherwise be separate generic +parameters. A job runner, for example, might leave its error type, runtime, and storage backend +open. A function interface can expose those choices directly; with its body omitted, it looks like this: ```rust pub fn run_job(store: &S, runtime: &R) -> Result<(), E> @@ -188,14 +187,13 @@ where } ``` -This is the leak from the first section, and worse, because a parameter *cannot* be moved onto an impl. -It is part of the interface by construction. Every intermediate function that merely passes a value -along declares all three and repeats their bounds, and adding a fourth open type is a breaking change -for every caller. +A generic forwarding function may need to carry `E`, `R`, and `S` and establish the same bounds. +Concrete callers can often infer or fix these types, so the declarations do not necessarily spread +to every caller. The maintenance problem arises where intermediate generic layers must preserve +choices they do not otherwise use. -An **abstract type** inverts the direction. Rather than the caller supplying the type, the context -determines it. It is an associated type on a trait the context implements, so an implementation can -name it without anyone choosing it at a call site: +A context-based interface can expose the operation while letting the context determine its error +type. `HasErrorType` supplies an associated `Error`, which the component imports into its signature: ```rust #[cgp_component(JobRunner)] @@ -205,8 +203,12 @@ pub trait CanRunJob { } ``` -`#[use_type(HasErrorType.Error)]` imports the context's error type and lets the signature name it as a -bare `Error`. The intermediate layer then has nothing to declare at all: +`CanRunJob` now has a `HasErrorType` supertrait because its return type names `Error`. +This type dependency is part of the interface, not hidden on the implementation. The runtime and +storage requirements can remain on the job provider if its public methods do not expose their types. + +A forwarding capability can use that same associated error without introducing a separate `E` +parameter: ```rust #[cgp_fn] @@ -218,58 +220,51 @@ pub fn run_jobs(&self) -> Result<(), Error> { } ``` -A parameter is an input and propagates everywhere; an abstract type is an output and propagates -nowhere. That asymmetry is why a CGP codebase can keep accumulating type dependencies without its -signatures growing: **the number of types a context decides can rise freely, because deciding is not -passing.** [Abstract types](./abstract-types.md) is the page for that half. +`run_jobs` still declares the requirements it uses: `CanRunJob` for calling the job and `HasErrorType` +for naming its result. The `#[use_type]` attribute lets it write `Error` instead of a qualified +associated-type projection. The context determines the concrete error type shared by both operations. -One thing to be accurate about: when a capability's own signature names the type, the owning trait does -become part of the contract: `CanRunJob` really does imply `HasErrorType`. But a caller bounding on -`CanRunJob` gets that implication for free, never restates it, and names the type only if it handles -one. Compare `trait CanRunJob`, which forces `` onto every caller and every caller's caller -whether they touch an error or not. The bound is on the implementation; the parameter would be on -everyone. +A type used only inside a provider can remain an impl-side dependency. A type appearing in a public +argument or result must be available through the interface. Associated types reduce separate type +parameters and tie related choices to the context; they do not eliminate all type dependencies from +signatures. [Abstract types](./abstract-types.md) explains that choice and its limits. ## What it costs -**A hidden requirement is hidden from you too.** The point of all this is that `CanSendEmail` does not -say what its implementations need, which also means reading the interface tells you nothing about what -a context must supply. The answer is in the provider, and finding it means knowing which provider the -context wired. +The trait interface does not tell a context author everything a selected provider needs. +To assemble a context, follow its wiring to the provider and inspect that provider's requirements. +The smaller caller contract comes with more work when configuring an implementation. -**The requirement is checked late.** Nothing verifies that a context can satisfy the provider it named -until something uses the capability, so a context can be wired wrong and still compile. That is -[lazy wiring](./check-traits.md), and it is the source of CGP's least pleasant errors. +Wiring alone does not verify that the context satisfies the provider's dependencies. A missing +capability or field can remain undetected until a check or use requires it. Changing a provider's +bounds can also make an existing context stop compiling even if the consumer trait is unchanged. -**When it does fail, the error is about a bound you did not write.** A missing `name` field surfaces as -an unsatisfied field bound naming a type-level spelling of the field name, several layers from the line -that caused it. [`check_components!`](/docs/reference/macros/check_components) forces the failure to the -wiring line and names the actual gap, and -[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) leads with the root cause for the -classes it recognizes. It is a `v0.1.0-alpha` covering the core wiring errors rather than all of them. -Both help substantially; neither makes the raw output pleasant. +Errors may refer to generated bounds rather than the requirement as written in the provider. +A missing implicit field, for example, can appear as an unsatisfied `HasField` bound with a +nested type-level field name. [`check_components!`](/docs/reference/macros/check_components) +checks selected components where you place it, usually beside the wiring, and helps expose the +missing dependency. [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reports readable +causes for recognized cases; its `v0.1.0-alpha` release covers core wiring errors rather than every +class. [Checking your wiring](./check-traits.md) shows the diagnostics and their limits. -**And it is more machinery than a plain function needs.** For a capability with one implementation, the -blanket impl in the second section is the whole of what is useful here, and it is ordinary Rust. -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) writes exactly that from a function, with no component and -no wiring. +A component and wiring are unnecessary when one blanket implementation provides all the reuse you +need. Write that implementation in ordinary Rust, or use +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) to generate a capability from a function. A plain generic +function remains suitable when its explicit parameters and bounds are the interface callers should see. ## Where to go next -The three legs each have a page. [Implicit arguments](./implicit-arguments.md) is the value leg, where a -context field arrives as a function parameter. [Abstract types](./abstract-types.md) is the type leg, -and the one that changes how a codebase's signatures age. - -[Consumer and provider traits](./consumer-and-provider-traits.md) is the other half of what a component -is: this page covers how an implementation states what it needs, and that one covers how a call reaches -the implementation at all. [Checking your wiring](./check-traits.md) takes up the cost above: why the -check is late, and what to do about it. - -For the constructs themselves, [`#[uses]`](/docs/reference/attributes/uses) declares a capability, -[`#[implicit]`](/docs/reference/attributes/implicit) a value, and -[`#[use_type]`](/docs/reference/attributes/use_type) a type; -[`#[blanket_trait]`](/docs/reference/macros/blanket_trait) generates the plain-Rust blanket impl this -page starts from. +These pages develop the dependency forms and explain how providers are selected and checked: + +- [Implicit arguments](./implicit-arguments.md): Reading context values without public method arguments. +- [Abstract types](./abstract-types.md): Sharing context-selected types and deciding which reach the interface. +- [Consumer and provider traits](./consumer-and-provider-traits.md): Connecting a caller to its implementation. +- [Checking your wiring](./check-traits.md): Verifying the selected provider's requirements. +- [`#[uses]`](/docs/reference/attributes/uses), + [`#[implicit]`](/docs/reference/attributes/implicit), and + [`#[use_type]`](/docs/reference/attributes/use_type): The dependency syntax used here. +- [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) and + [`#[blanket_trait]`](/docs/reference/macros/blanket_trait): Generating blanket implementations. --- diff --git a/docs/concepts/index.md b/docs/concepts/index.md index d5f47a6e..1ce8ea40 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -5,69 +5,75 @@ sidebar_position: 0 # Concepts -This section explains the ideas behind CGP: why it is built the way it is, what each of its ideas -actually does, and where the boundaries of each one lie. It is written to be read away from a -keyboard. There is nothing here to follow along with, and nothing to install first. +CGP lets a type choose reusable trait implementations through compile-time wiring. These pages +explain why that design works, what you can build with it, and when its costs outweigh the benefits. +They assume familiarity with Rust traits and generic bounds; you can read them without running code. -It sits alongside the other two parts of the documentation. The [tutorials](/docs/tutorials/hello) -teach by building something, so they show a construct at the moment it is needed and move on. The -[reference](/docs/reference/) explains one construct completely, for a reader who already knows the -name of the thing they want. A concept page answers the question neither of those is shaped for: -*why does CGP work this way, and when is it the right thing to reach for?* Each page names the -constructs it involves and links to the reference for their exact syntax, rather than repeating it. +The [tutorials](/docs/tutorials/hello) introduce CGP by building working programs. The +[reference](/docs/reference/) specifies individual constructs and their syntax. Concepts connects +those constructs to the problems they solve, with examples, tradeoffs, and links to both. ## Where to start -**Read [Bypassing coherence](./coherence.md) first if you want to know why CGP exists.** It explains -the rule in Rust's trait system that allows only one implementation per type, why that rule is -correct, what it costs in practice, and the move CGP makes to work around it without giving up what -the rule buys. Almost everything else here is downstream of it. +Choose an entry point for the question you want answered: -**Read [Consumer and provider traits](./consumer-and-provider-traits.md) first if you want to know -how CGP works.** It covers the trait split at the centre of the design, one trait you call and another -you implement, and how a call finds its way from one to the other. +- **Why does CGP exist?** [Bypassing coherence](./coherence.md) explains how Rust keeps trait + implementations unambiguous and how CGP allows reusable alternatives within those rules. +- **How does CGP work?** [Consumer and provider traits](./consumer-and-provider-traits.md) explains + the split between the trait callers use and the trait providers implement, then traces a method call. +- **Should I use CGP?** [Modularity Hierarchy](./modularity-hierarchy.md) compares ordinary traits, + blanket implementations, and wired components so you can choose what your problem requires. -**Read [Modularity Hierarchy](./modularity-hierarchy.md) first if you are deciding whether to adopt -it.** It lays out the range from an ordinary Rust trait to fully wired components as a hierarchy of -five tiers, and argues for going no higher than a problem requires. - -**New to Rust's traits and generics?** These pages explain the reasoning behind CGP and assume you are -comfortable with traits and generic bounds. If you are not yet, the [tutorials](/docs/tutorials/hello) -build the ideas up from working code and are the gentler way in; come back here for the *why* behind -them. +If traits and generic bounds are unfamiliar, start with the [tutorials](/docs/tutorials/hello). +They introduce the ideas through working code and provide the background these explanations assume. ## The ideas, grouped -The pages below are ordered in the sidebar roughly as a reader meets them, and grouped here by what -they are about. - -**The foundation** is the coherence problem and CGP's answer to it. -[Bypassing coherence](./coherence.md) states the problem; -[Consumer and provider traits](./consumer-and-provider-traits.md) is the mechanism that solves it. - -**Dependency injection** is how an implementation gets what it needs without the interface carrying -it. [Impl-side dependencies](./impl-side-dependencies.md) is the general idea; -[Implicit arguments](./implicit-arguments.md) is how it looks for a value read from a field, and -[Abstract types](./abstract-types.md) is how it looks for a type the context chooses. - -**Composition and scale** cover what happens as a program grows. -[Checking your wiring](./check-traits.md) explains why a wiring mistake compiles and how to make it -fail loudly instead. [Higher-order providers](./higher-order-providers.md) build one implementation -out of another, [Aggregate providers](./aggregate-providers.md) bundle a group of choices into one, -and [Namespaces](./namespaces.md) keep a large wiring table readable. - -**Applied ideas** are the places CGP's machinery is put to a specific use. -[Modular error handling](./modular-error-handling.md) separates the error type from how errors are -built. [Handlers](./handlers.md) and [Monadic handlers](./monadic-handlers.md) model computation as -components that compose. [Extensible records](./extensible-records.md), -[Extensible variants](./extensible-variants.md), and [Dispatching](./dispatching.md) let generic code -work over the shape of a struct or an enum. [Type-level DSLs](./type-level-dsls.md) push that as far -as it goes, turning a small language into types the compiler interprets. - -**Two pages stand slightly apart.** [Recovering `Send` bounds](./send-bounds.md) is a workaround for a -gap in stable Rust rather than a CGP idea, and it matters as soon as an async CGP task is spawned. -[Modularity Hierarchy](./modularity-hierarchy.md) explains the five tiers of the hierarchy and then -turns into a decision guide, and it is the page to reach for when the question is how far to go. +The sidebar follows a suggested reading order. The groups below let you find related ideas directly. + +### Traits and implementation choices + +These pages explain the problem CGP addresses and the mechanism it uses: + +- [Bypassing coherence](./coherence.md): Why Rust restricts overlapping implementations and how + separate provider types let alternative implementations coexist. +- [Consumer and provider traits](./consumer-and-provider-traits.md): How the trait split and wiring + connect a method call to a provider. +- [Modularity Hierarchy](./modularity-hierarchy.md): How to choose how much of CGP a program needs. + +### Dependencies + +A provider can state requirements that its callers do not need to carry. These pages explain the +forms those requirements take: + +- [Impl-side dependencies](./impl-side-dependencies.md): Capabilities required by an implementation + without appearing in its public interface. +- [Implicit arguments](./implicit-arguments.md): Values read from context fields. +- [Abstract types](./abstract-types.md): Types selected by a context and shared by generic code. + +### Composition and wiring + +These pages explain how to combine implementations, share wiring, and verify the result: + +- [Checking your wiring](./check-traits.md): Why wiring errors can remain undetected until use, and + how compile-time checks report missing requirements near the wiring. +- [Higher-order providers](./higher-order-providers.md): Providers that take other providers as parameters. +- [Aggregate providers](./aggregate-providers.md): Groups of provider choices reused across contexts. +- [Namespaces](./namespaces.md): Shared wiring organized by paths and inherited by contexts. + +### Applications of the design + +These pages apply the same component model to errors, computations, and data: + +- [Modular error handling](./modular-error-handling.md): Choosing an error type and the providers + that construct errors and attach detail. +- [Handlers](./handlers.md): Computations represented as composable components. +- [Monadic handlers](./monadic-handlers.md): Composing computations through a monad. +- [Extensible records](./extensible-records.md): Generic operations over struct fields. +- [Extensible variants](./extensible-variants.md): Generic operations over enum variants. +- [Dispatching](./dispatching.md): Routing variants to their handlers. +- [Type-level DSLs](./type-level-dsls.md): Representing a small language as types resolved by the compiler. +- [Recovering `Send` bounds](./send-bounds.md): Requiring sendable futures when spawning async CGP tasks. --- diff --git a/example-code/tests/concepts/coherence.rs b/example-code/tests/concepts/coherence.rs index aa953de7..57871310 100644 --- a/example-code/tests/concepts/coherence.rs +++ b/example-code/tests/concepts/coherence.rs @@ -1,159 +1,83 @@ //! Code from `docs/concepts/coherence.md` — *Bypassing coherence*. -//! -//! Module names follow the page's headings. Code the page **rejects** — the blocks whose comment -//! quotes an `error[E…]` — is carried as a `compile_fail` doctest rather than as code, since the -//! crate could not compile otherwise; each one records the code the compiler actually reports. /// ## The trait system is already a dependency-injection mechanism pub mod trait_system_as_dependency_injection { - use core::fmt::Display; + use core::fmt::{self, Display, Formatter}; pub fn describe(value: &T) -> String { format!("{value}") } + struct Pair(A, B); + + impl Display for Pair { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "({}, {})", self.0, self.1) + } + } + #[test] fn the_caller_names_no_implementation() { assert_eq!(describe(&42), "42"); + assert_eq!(describe(&Pair("foo", 42u32)), "(foo, 42)"); } } /// ## That only works because every lookup finds the same answer /// -/// Both blocks in this section are rejected by the compiler, which is the point of showing them, so -/// neither can be code in this crate. The bodies the page elides are filled in below so that the -/// quoted error is the *only* thing wrong with each — a `/* ... */` body would fail on its own and -/// the doctest would pass for the wrong reason. -/// -/// The overlap rule. `String` is both `Display` and `AsRef<[u8]>`: -/// -/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_1.rs`. -/// -/// The orphan rule. Neither `Display` nor `Vec` belongs to this crate: -/// -/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/coherence_every_lookup_finds_the_same_answer_2.rs`. +/// Rejected snippets are covered by the trybuild fixtures +/// `coherence_every_lookup_finds_the_same_answer_1.rs` (overlap) and +/// `coherence_every_lookup_finds_the_same_answer_2.rs` (orphan rule). pub mod every_lookup_finds_the_same_answer {} /// ## The move: make `Self` a type you own -/// -/// … together with **## Coherence comes back, one context at a time**, which wires the component -/// this section defines. The page splits them across two headings; they are one program. +/// ## Coherence comes back, one type at a time pub mod the_move { use core::fmt::Display; use cgp::prelude::*; #[cgp_component(Encoder)] - pub trait CanEncodeValue { - fn encode(&self, value: &Value) -> Vec; + pub trait CanEncode { + fn encode(&self) -> Vec; } #[cgp_impl(new EncodeAsText)] - impl Encoder - where - Value: Display, - { - fn encode(&self, value: &Value) -> Vec { - value.to_string().into_bytes() + #[uses(Display)] + impl Encoder { + fn encode(&self) -> Vec { + self.to_string().into_bytes() } } #[cgp_impl(new EncodeAsHex)] - impl Encoder - where - Value: AsRef<[u8]>, - { - // The page elides this body as `/* hex-encode the bytes */`. - fn encode(&self, value: &Value) -> Vec { - value - .as_ref() + #[uses(AsRef<[u8]>)] + impl Encoder { + // The page elides the hexadecimal encoding body. + fn encode(&self) -> Vec { + self.as_ref() .iter() .flat_map(|byte| format!("{byte:02x}").into_bytes()) .collect() } } - // The page uses these two contexts without declaring them, since by that point it has only - // introduced the word "context". - pub struct ApiServer; - pub struct Firmware; - - delegate_components! { - ApiServer { - open EncoderComponent; - @EncoderComponent.String: EncodeAsText, - } - } - - delegate_components! { - Firmware { - open EncoderComponent; - @EncoderComponent.String: EncodeAsHex, - } - } + delegate_components! { String { EncoderComponent: EncodeAsText } } + delegate_components! { Vec { EncoderComponent: EncodeAsHex } } - mod check_api_server { + mod check_string { use super::*; - check_components! { ApiServer { EncoderComponent: String } } + check_components! { String { EncoderComponent } } } - mod check_firmware { + mod check_bytes { use super::*; - check_components! { Firmware { EncoderComponent: String } } + check_components! { Vec { EncoderComponent } } } - /// The page quotes the output of this in a ```` ```text ```` block, so the two lines are pinned - /// here rather than left to be re-derived by eye. #[test] - fn the_two_contexts_encode_the_same_string_differently() { - let value = "hi".to_owned(); - - assert_eq!( - String::from_utf8(ApiServer.encode(&value)).unwrap(), - "hi", // ApiServer: hi - ); - assert_eq!( - String::from_utf8(Firmware.encode(&value)).unwrap(), - "6869", // Firmware: 6869 - ); + fn each_value_type_selects_its_encoding() { + assert_eq!("hi".to_owned().encode(), b"hi"); + assert_eq!(b"hi".to_vec().encode(), b"6869"); } } - -/// ### The shape this depends on -/// -/// The arrangement of [`the_move`] with the CGP taken back out: two application types, one value -/// type, two encodings, and no CGP at all. It compiles, which is the section's whole point. -pub mod the_shape_this_depends_on { - pub trait CanEncodeValue { - fn encode(&self, value: &Value) -> Vec; - } - - pub struct ApiServer; - pub struct Firmware; - - impl CanEncodeValue for ApiServer { - // The page elides this body as `/* as text */`. - fn encode(&self, value: &String) -> Vec { - value.clone().into_bytes() - } - } - - impl CanEncodeValue for Firmware { - // The page elides this body as `/* as hexadecimal */`. - fn encode(&self, value: &String) -> Vec { - value - .as_bytes() - .iter() - .flat_map(|byte| format!("{byte:02x}").into_bytes()) - .collect() - } - } -} - -/// ### The shape this depends on — where it stops scaling -/// -/// The second block of that section: factoring the shared logic into a blanket implementation runs -/// into the overlap rule, this time on an application type. Rejected, so it is a doctest. -/// -/// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/coherence_the_shape_stops_scaling.rs`. -pub mod the_shape_stops_scaling {} From a9f3970f63371ad4fdeda2938bec093571ace788 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 19 Sep 2026 13:33:16 +0000 Subject: [PATCH 078/516] Retire "capability" as the word for CGP's own constructs Every docs page now says trait, method, or operation for what a component or `#[cgp_fn]` defines, trait dependency for what `#[uses]` imports, blanket trait for a non-component `#[cgp_fn]` trait, and feature for what CGP offers as a product. The reference pages' context gloss reads "the type the method runs on", with the abstract-type pages saying "the type that implements the trait". The word names a different construct in the object-capability model and in Rust's context-and-capabilities proposal, so it is reserved for those. The `[CGP-E012]` message quoted on the errors page follows the tool's new wording. Blog posts are untouched, and the published skill snapshot picks up the change when the submodule is next advanced. Co-Authored-By: Claude Fable 5.1 --- docs/cargo-cgp/index.md | 2 +- docs/concepts/aggregate-providers.md | 6 +-- docs/concepts/check-traits.md | 8 ++-- docs/concepts/coherence.md | 4 +- docs/concepts/consumer-and-provider-traits.md | 18 ++++---- docs/concepts/handlers.md | 2 +- docs/concepts/higher-order-providers.md | 6 +-- docs/concepts/impl-side-dependencies.md | 20 ++++----- docs/concepts/implicit-arguments.md | 12 +++--- docs/concepts/index.md | 3 +- docs/concepts/modular-error-handling.md | 4 +- docs/concepts/modularity-hierarchy.md | 35 ++++++++-------- docs/concepts/namespaces.md | 4 +- docs/concepts/send-bounds.md | 4 +- docs/index.md | 4 +- docs/overview.md | 14 +++---- docs/reference/attributes/default_impl.md | 2 +- docs/reference/attributes/derive_delegate.md | 2 +- docs/reference/attributes/extend.md | 29 +++++++------ docs/reference/attributes/extend_where.md | 20 ++++----- docs/reference/attributes/impl_generics.md | 26 ++++++------ docs/reference/attributes/implicit.md | 11 ++--- docs/reference/attributes/index.md | 2 +- docs/reference/attributes/prefix.md | 4 +- docs/reference/attributes/use_provider.md | 4 +- docs/reference/attributes/use_type.md | 8 ++-- docs/reference/attributes/uses.md | 32 +++++++-------- docs/reference/components/can_raise_error.md | 6 +-- docs/reference/components/can_wrap_error.md | 8 ++-- .../components/handler/async_computer.md | 4 +- .../components/handler/async_computer_ref.md | 4 +- docs/reference/components/handler/computer.md | 6 +-- .../components/handler/computer_ref.md | 4 +- docs/reference/components/handler/handler.md | 11 ++--- .../components/handler/handler_ref.md | 6 +-- docs/reference/components/handler/index.md | 2 +- docs/reference/components/handler/producer.md | 6 +-- .../components/handler/try_computer.md | 4 +- .../components/handler/try_computer_ref.md | 4 +- docs/reference/components/has_error_type.md | 7 ++-- docs/reference/components/has_runtime.md | 10 ++--- docs/reference/components/has_runtime_type.md | 10 ++--- docs/reference/components/has_type.md | 3 +- docs/reference/components/index.md | 6 +-- docs/reference/components/runner.md | 4 +- docs/reference/components/send_runner.md | 4 +- docs/reference/derives/derive_cgp_data.md | 2 +- docs/reference/derives/derive_has_field.md | 2 +- docs/reference/errors.md | 12 +++--- docs/reference/index.md | 10 ++--- docs/reference/macros/async_trait.md | 5 ++- docs/reference/macros/blanket_trait.md | 14 +++---- docs/reference/macros/cgp_auto_dispatch.md | 2 +- docs/reference/macros/cgp_auto_getter.md | 6 +-- docs/reference/macros/cgp_component.md | 28 ++++++------- docs/reference/macros/cgp_computer.md | 12 +++--- docs/reference/macros/cgp_fn.md | 41 ++++++++++--------- docs/reference/macros/cgp_getter.md | 6 +-- docs/reference/macros/cgp_impl.md | 10 ++--- docs/reference/macros/cgp_namespace.md | 4 +- docs/reference/macros/cgp_producer.md | 4 +- docs/reference/macros/cgp_provider.md | 2 +- docs/reference/macros/cgp_type.md | 10 ++--- docs/reference/macros/check_components.md | 9 ++-- .../macros/delegate_and_check_components.md | 2 +- docs/reference/macros/delegate_components.md | 8 ++-- docs/reference/macros/index.md | 6 +-- docs/reference/macros/symbol.md | 2 +- docs/reference/providers/chain_getters.md | 2 +- .../providers/dispatch/build_and_merge.md | 2 +- .../dispatch/build_and_merge_outputs.md | 2 +- .../providers/dispatch/build_and_set_field.md | 2 +- .../providers/dispatch/build_with_handlers.md | 2 +- .../providers/dispatch/downcast_and_handle.md | 4 +- .../dispatch/extract_field_and_handle.md | 2 +- .../providers/dispatch/handle_field_value.md | 2 +- docs/reference/providers/dispatch/index.md | 2 +- .../dispatch/match_first_with_handlers.md | 2 +- .../dispatch/match_with_field_handlers.md | 2 +- .../providers/dispatch/match_with_handlers.md | 2 +- .../dispatch/match_with_value_handlers.md | 2 +- docs/reference/providers/error/debug_error.md | 2 +- .../providers/error/discard_detail.md | 6 +-- .../providers/error/display_error.md | 2 +- docs/reference/providers/error/index.md | 7 ++-- .../providers/error/panic_on_error.md | 2 +- docs/reference/providers/error/raise_from.md | 4 +- .../providers/error/raise_infallible.md | 2 +- .../reference/providers/error/return_error.md | 2 +- .../providers/handler/compose_handlers.md | 4 +- docs/reference/providers/handler/index.md | 2 +- .../providers/handler/pipe_handlers.md | 2 +- docs/reference/providers/handler/promote.md | 4 +- .../providers/handler/promote_async.md | 2 +- .../handler/promote_async_computer.md | 2 +- .../providers/handler/promote_computer.md | 2 +- .../providers/handler/promote_handler.md | 2 +- .../providers/handler/promote_producer.md | 2 +- .../providers/handler/promote_ref.md | 4 +- .../providers/handler/promote_try_computer.md | 4 +- .../providers/handler/return_input.md | 2 +- .../providers/handler/try_promote.md | 2 +- .../providers/handler/use_input_delegate.md | 2 +- docs/reference/providers/index.md | 2 +- docs/reference/providers/monad/bind_err.md | 2 +- docs/reference/providers/monad/bind_ok.md | 4 +- docs/reference/providers/monad/index.md | 2 +- .../reference/providers/monad/pipe_monadic.md | 2 +- docs/reference/providers/redirect_lookup.md | 4 +- docs/reference/providers/use_context.md | 14 +++---- docs/reference/providers/use_default.md | 2 +- docs/reference/providers/use_delegate.md | 2 +- .../reference/providers/use_delegated_type.md | 2 +- docs/reference/providers/use_field.md | 2 +- docs/reference/providers/use_field_ref.md | 4 +- docs/reference/providers/use_fields.md | 2 +- docs/reference/providers/use_type.md | 2 +- docs/reference/providers/with_context.md | 2 +- .../providers/with_delegated_type.md | 2 +- docs/reference/providers/with_field.md | 2 +- docs/reference/providers/with_field_ref.md | 2 +- docs/reference/providers/with_provider.md | 2 +- docs/reference/providers/with_type.md | 2 +- .../traits/field-access/field_getter.md | 2 +- .../traits/field-access/has_field.md | 6 +-- docs/reference/traits/field-access/index.md | 2 +- docs/reference/traits/monad/contains_value.md | 2 +- docs/reference/traits/monad/index.md | 4 +- docs/reference/traits/monad/lift_value.md | 2 +- docs/reference/traits/monad/monadic_bind.md | 2 +- docs/reference/traits/monad/monadic_trans.md | 2 +- .../traits/namespace/default_namespace.md | 2 +- .../optional/can_finalize_with_default.md | 2 +- docs/reference/traits/optional/to_optional.md | 2 +- .../traits/optional/transform_map_default.md | 12 +++--- .../traits/optional/transform_optional.md | 10 ++--- .../traits/type-level/transform_map.md | 2 +- .../traits/type-level/transform_map_fields.md | 6 +-- .../traits/wiring/can_use_component.md | 4 +- .../traits/wiring/delegate_component.md | 6 +-- docs/reference/traits/wiring/index.md | 2 +- .../traits/wiring/is_provider_for.md | 4 +- docs/reference/types/index_type.md | 2 +- docs/reference/types/mref.md | 4 +- docs/reference/types/path_cons.md | 4 +- docs/reference/types/phantom_data.md | 2 +- .../context-generic-functions.md | 6 +-- docs/tutorials/hello.md | 4 +- example-code/tests/concepts/abstract_types.rs | 2 +- example-code/tests/concepts/check_traits.rs | 4 +- .../tests/concepts/impl_side_dependencies.rs | 2 +- .../tests/concepts/implicit_arguments.rs | 2 +- .../tests/concepts/modular_error_handling.rs | 2 +- .../tests/concepts/modularity_hierarchy.rs | 2 +- .../reference/macros/delegate_components.rs | 2 +- .../providers/error/discard_detail.rs | 2 +- 156 files changed, 432 insertions(+), 423 deletions(-) diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index 89672249..1dc6b0a4 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -12,7 +12,7 @@ generate. CGP's wiring is **lazy**. A `delegate_components!` entry is accepted without checking that the provider it names can actually do the job, so a context with a missing field or an unmet dependency compiles -fine and fails somewhere else entirely — usually at the first call to the capability, in a message +fine and fails somewhere else entirely — usually at the first call to the trait's method, in a message about types you never wrote. Here is the whole of a mistake: a `Rectangle` that lost its `height` field while a provider still reads diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index 63a96730..caa7778a 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -41,7 +41,7 @@ delegate_components! { } ``` -`Rectangle` gets both capabilities if it meets the bundled providers' requirements. The provider +`Rectangle` gets both traits if it meets the bundled providers' requirements. The provider choices live in `GeometryComponents`, so changing that table changes the choices for every context that delegates those components to it. @@ -82,7 +82,7 @@ Verify their requirements against a context that will actually use them. ## Verifying one properly A check on `Rectangle` follows the bundle's delegation and checks the providers against -`Rectangle`'s fields and capabilities: +`Rectangle`'s fields and traits: ```rust check_components! { @@ -130,7 +130,7 @@ contexts need a shared table and a path structure that separates fixed wiring fr ## What it costs -A bundle adds a table to inspect when tracing a capability. Nested bundles add further tables, even +A bundle adds a table to inspect when tracing a method call. Nested bundles add further tables, even though the compiler resolves them statically. Keep a bundle when centralizing shared choices is worth that extra reading. diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index 542de672..ed8e2d6b 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -51,7 +51,7 @@ them, but the bundle does not need to supply those dependencies itself. ## Where the failure surfaces instead -An unchecked wiring error appears when code first requires the capability. A call to +An unchecked wiring error appears when code first requires the trait. A call to `app.send_email(to, body)` on `&BrokenApp` produces an error like this abbreviated diagnostic: ```text @@ -114,13 +114,13 @@ note: required for `RecordEmails` to implement The error now identifies a missing `HasField` implementation and names `RecordEmails` as the provider requiring it. The expanded field names remain hard to read: `sent_emails` and `smtp_server` appear as nested character types. The headline also names the generated `CanUseComponent` bound -rather than the public capability. +rather than the public trait. ## Reading it through the toolchain [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) rewrites recognized CGP diagnostics with readable field names and dependency chains. For this missing-field case, its abbreviated output -identifies both the unavailable capability and its cause: +identifies both the unavailable trait and its cause: ```text error[E0277]: [CGP-E001] the consumer trait `CanSendEmail` is not implemented @@ -135,7 +135,7 @@ error[E0277]: [CGP-E001] the consumer trait `CanSendEmail` is not implemented ``` The root cause is now explicit: `BrokenApp` lacks `sent_emails`, which `RecordEmails` requires. -The dependency chain connects that missing field to the `CanSendEmail` capability the application needs. +The dependency chain connects that missing field to the `CanSendEmail` trait the application needs. The tool can also recover causes that ordinary compiler output omits. It uses the compiler's next-generation trait solver for diagnostic recovery, then translates the recognized CGP structures. diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 442e4319..4ca05932 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -178,7 +178,7 @@ explains when to use it and how it differs from the value-type wiring shown here ## What it costs A component introduces more declarations than a plain trait: a provider trait, a component marker, -and wiring for the types that use it. For a capability with one implementation, a plain trait or +and wiring for the types that use it. For a trait with one implementation, a plain trait or [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) may provide the required reuse without wiring. Provider selection belongs to CGP's component interface. It does not give an existing trait such as @@ -189,7 +189,7 @@ Explicit wiring adds configuration to read and maintain. In the tables above, ea entry naming its provider. Shared bundles and namespaces can reduce repetition, but they introduce further places to inspect when tracing a choice. -Wiring checks are deferred until the capability is checked or used. A table can name a provider +Wiring checks are deferred until the trait is checked or used. A table can name a provider whose requirements the context does not satisfy, and a later call can produce a verbose error. [`check_components!`](/docs/reference/macros/check_components) verifies requirements beside the wiring. [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) makes recognized causes diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index cc4af286..a2b6b7a2 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -6,13 +6,13 @@ sidebar_position: 2 # Consumer and provider traits CGP separates the trait callers use from the trait providers implement. A **consumer trait** exposes -a capability on a context, while a **provider trait** lets reusable implementations supply that -capability. This page motivates the split, traces a method call through its wiring, and shows the +a set of methods on a context, while a **provider trait** lets reusable implementations supply those +methods. This page motivates the split, traces a method call through its wiring, and shows the generated Rust before discussing the costs. ## What an ordinary Rust trait does, and where it stops -An ordinary Rust trait connects a type to an implementation of a capability. A `T: Display` bound, +An ordinary Rust trait connects a type to one implementation of its methods. A `T: Display` bound, for example, lets the compiler select the formatting implementation for `T`. This is sufficient when each type needs one implementation and you do not need to choose among reusable alternatives. @@ -131,7 +131,7 @@ trait, provider trait, and that marker. The wiring maps its key to `SendViaSmtp` `RecordEmails` for `TestApp`. A method call follows the selected entry. For `app.send_email("a@b.c", "hi")`, the compiler resolves -`App`'s email-sending capability through its table to `SendViaSmtp`, then checks that provider's +`App`'s email-sending trait through its table to `SendViaSmtp`, then checks that provider's requirements against `App`. The call uses static dispatch; the compiled program does not need a runtime wiring table or provider lookup. @@ -234,17 +234,17 @@ These are [impl-side dependencies](./impl-side-dependencies.md), which let imple different requirements without changing the caller's interface. A context can also implement the consumer trait directly, using the ordinary Rust form shown at -the start of the page. For that capability it can omit providers and wiring. This allows adoption -one capability at a time, subject to Rust's usual restriction against conflicting implementations. +the start of the page. For that trait it can omit providers and wiring. This allows adoption +one trait at a time, subject to Rust's usual restriction against conflicting implementations. ## What it costs -A component adds declarations and wiring beyond a plain trait. For a capability with one +A component adds declarations and wiring beyond a plain trait. For a trait with one implementation, use a plain trait or consider [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), which -creates a blanket-implemented capability from a function without component wiring. +creates a blanket-implemented trait from a function without component wiring. Wiring does not immediately verify the selected provider's requirements. A missing entry or -unsatisfied dependency can remain undetected until a caller needs the capability. +unsatisfied dependency can remain undetected until a caller needs the trait. [`check_components!`](/docs/reference/macros/check_components) verifies the requirements where you place the check, usually beside the table. [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reports recognized failures with diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 8a47ac84..95c5fe32 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -174,7 +174,7 @@ an executor that requires `Send` needs an additional guarantee, described in A plain function is simpler when a computation does not need interchangeable stages or context-specific composition. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) provides a lighter option when a single -implementation needs values or capabilities from a context without handler wiring. +implementation needs values or traits from a context without handler wiring. ## Where to go next diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index de2a8507..4895fabf 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -133,7 +133,7 @@ delegate_components! { `open ShapeAreaCalculatorComponent;` enables provider selection by the component's shape parameter. A call for `Vec` selects `SumAreas`. Each inner call then asks for the `Rectangle` -capability and reaches `RectangleArea`. The inner lookup is different from the collection lookup, +trait and reaches `RectangleArea`. The inner lookup is different from the collection lookup, so it has an independent implementation to resolve to. An explicit `SumAreas` uses that provider directly for each element, bypassing @@ -173,8 +173,8 @@ one transformation needs to work with independently selected implementations. A with nothing to vary does not benefit from an extra provider parameter. `UseContext` can create a resolution cycle if the inner request selects the same wrapper again. -For example, a wrapper wired for a capability cannot use that same capability as its only base -implementation. The summing example avoids this by requesting the element capability from the +For example, a wrapper wired for a component cannot use that same component as its only base +implementation. The summing example avoids this by requesting the element trait from the collection provider. Ensure that the inner lookup resolves to an independently available implementation. A nested composition can make failures harder to locate. An error on `ScaledArea` diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index ed0d4b5d..9ecf005d 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -6,9 +6,9 @@ sidebar_position: 3 # Impl-side dependencies An **impl-side dependency** is a requirement stated on an implementation without being part of its -trait interface. Callers can require the capability they use while the compiler checks the selected +trait interface. Callers can require the trait they use while the compiler checks the selected implementation's dependencies. This page starts with ordinary Rust blanket implementations, then -shows how CGP providers require capabilities, field values, and context-selected types. +shows how CGP providers require traits, field values, and context-selected types. ## What a `where` clause costs the callers above it @@ -47,7 +47,7 @@ it becomes harder to maintain when many layers repeat implementation-specific re ## Moving the requirement onto the implementation -A blanket implementation lets callers depend on a capability without naming the dependencies used +A blanket implementation lets callers depend on a trait without naming the dependencies used to implement it. The trait declares the operation, and the implementation states when it is available: ```rust @@ -67,7 +67,7 @@ where `CanGreet` promises a greeting method without requiring `HasName` as a supertrait. The blanket implementation supplies that method for every context implementing `HasName`. A generic caller -can require only the greeting capability: +can require only the greeting trait: ```rust pub fn greet_twice(context: &Context) -> String @@ -93,7 +93,7 @@ several implementations need to coexist, including implementations whose context ## Two providers, two sets of requirements, one interface -Each CGP provider can require different context capabilities while implementing the same interface. +Each CGP provider can require different traits of the context while implementing the same interface. An email sender might need an SMTP server getter, while a test implementation needs access to a recording buffer: @@ -144,10 +144,10 @@ another provider uses one. ## The three things an implementation can ask for -Provider dependencies commonly describe capabilities, values, or types. CGP expresses them with +Provider dependencies commonly describe traits, values, or types. CGP expresses them with attributes that generate the corresponding Rust bounds: -- **Capabilities:** `#[uses(Trait)]` requires the context to implement a trait. It accepts ordinary +- **Traits:** `#[uses(Trait)]` requires the context to implement a trait. It accepts ordinary Rust traits such as `AsRef<[u8]>` as well as CGP consumer traits. - **Values:** An `#[implicit]` argument reads a field from the context and generates the field-access requirement on the implementation. @@ -207,7 +207,7 @@ pub trait CanRunJob { This type dependency is part of the interface, not hidden on the implementation. The runtime and storage requirements can remain on the job provider if its public methods do not expose their types. -A forwarding capability can use that same associated error without introducing a separate `E` +A forwarding trait can use that same associated error without introducing a separate `E` parameter: ```rust @@ -236,7 +236,7 @@ To assemble a context, follow its wiring to the provider and inspect that provid The smaller caller contract comes with more work when configuring an implementation. Wiring alone does not verify that the context satisfies the provider's dependencies. A missing -capability or field can remain undetected until a check or use requires it. Changing a provider's +trait or field can remain undetected until a check or use requires it. Changing a provider's bounds can also make an existing context stop compiling even if the consumer trait is unchanged. Errors may refer to generated bounds rather than the requirement as written in the provider. @@ -249,7 +249,7 @@ class. [Checking your wiring](./check-traits.md) shows the diagnostics and their A component and wiring are unnecessary when one blanket implementation provides all the reuse you need. Write that implementation in ordinary Rust, or use -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) to generate a capability from a function. A plain generic +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) to generate a trait from a function. A plain generic function remains suitable when its explicit parameters and bounds are the interface callers should see. ## Where to go next diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index f4eb2858..112c3949 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -33,7 +33,7 @@ where This works, and everything in it is doing something. `Symbol!("name")` is the field's name as a type, so one trait can describe every field rather than needing one trait per field. `PhantomData` carries that type to the call so inference knows which field is meant. The bound is an -[impl-side dependency](./impl-side-dependencies.md), which is why the capability's own trait says +[impl-side dependency](./impl-side-dependencies.md), which is why the generated trait itself says nothing about names. It is also four unfamiliar things stacked in front of a one-line function, and a reader meeting them @@ -63,10 +63,10 @@ the rest from it. Someone who understands functions and arguments can write a co meeting a type-level anything, which is why this is the recommended way to read a context field and the starting point most introductions to CGP should use. -## A capability from a function alone +## A trait from a function alone Combined with [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), an implicit argument gets you a working CGP -capability with no trait, no provider, and no wiring line: +method with no hand-written trait, no provider, and no wiring line: ```rust #[cgp_fn] @@ -76,7 +76,7 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> ``` Any context with a `width` and a `height` can now call `rectangle_area()`. That is the whole program. -There is no component to define and nothing to choose, because this capability has one implementation +There is no component to define and nothing to choose, because this trait has one implementation and needs none. It is the smallest useful thing CGP does, and the right place to start a codebase that may never need more. @@ -129,7 +129,7 @@ where ``` `HasAuthHeader` there is a getter on `Request`, not on the application, and no implicit argument can -express that. The accessor may also need to exist as a **named capability** that other code depends on +express that. The accessor may also need to exist as a **named trait** that other code depends on through `#[uses(...)]` or a supertrait, because a name is something you can require and an argument is not. Or the getter may carry an **associated type inferred from the field**, so callers stay generic over what the value actually is. @@ -170,7 +170,7 @@ this shape. For the constructs, [`#[implicit]`](/docs/reference/attributes/implicit) carries the full list of accepted forms and access rules, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the no-wiring -capability, [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter) is the getter to reach for in +trait, [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter) is the getter to reach for in the three cases above, and [`HasField`](/docs/reference/traits/field-access/has_field) is the trait underneath all of them. diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 1ce8ea40..64c5720f 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -46,7 +46,8 @@ These pages explain the problem CGP addresses and the mechanism it uses: A provider can state requirements that its callers do not need to carry. These pages explain the forms those requirements take: -- [Impl-side dependencies](./impl-side-dependencies.md): Capabilities required by an implementation +- [Impl-side dependencies](./impl-side-dependencies.md): Traits, values, and types required by an + implementation without appearing in its public interface. - [Implicit arguments](./implicit-arguments.md): Values read from context fields. - [Abstract types](./abstract-types.md): Types selected by a context and shared by generic code. diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index 58e35aed..4981db08 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -37,7 +37,7 @@ CGP makes each of the three a wiring choice, and the code that fails makes none ## Code that fails without knowing what failing means -The capability names its error abstractly, and the provider raises into it: +The trait names its error abstractly, and the provider raises into it: ```rust #[cgp_component(PortParser)] @@ -129,7 +129,7 @@ the wiring rather than in any code that fails. ## An application's own error vocabulary None of this is confined to CGP's built-in components, and the clearest sign of that is defining your -own. A service that wants every failure to carry an HTTP status declares a capability for it: +own. A service that wants every failure to carry an HTTP status declares a component for it: ```rust #[cgp_component(HttpErrorRaiser)] diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index 5f80795e..16d13ad0 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -5,11 +5,11 @@ sidebar_position: 18 # Modularity Hierarchy -How much CGP does a capability need? The answer is a tier in a five-tier hierarchy, where each tier +How much CGP does an operation need? The answer is a tier in a five-tier hierarchy, where each tier allows more independent implementations of one interface than the tier below, at a matching cost in syntax or coupling. The right tier is the lowest one that still expresses the problem. -This page explains each tier in turn on one running capability, encoding a value, so the only thing +This page explains each tier in turn on one running operation, encoding a value, so the only thing that changes from tier to tier is the modularity, not the problem. It then turns to the decision: how to pick a tier, when a plainer tool is the better choice, and what the machinery costs. If you are still deciding whether CGP is for you at all, read to the end of the decision guide. @@ -48,7 +48,7 @@ impl> CanEncode for Value { Every type that is `AsRef<[u8]>` now encodes the same way, and no second strategy is possible. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds this same tier from a plain function, and hides -the bound behind a clean interface. Reach for tier 1 when a capability genuinely has one +the bound behind a clean interface. Reach for tier 1 when a trait genuinely has one implementation for all types. ## Tier 2: one implementation per type @@ -77,7 +77,7 @@ impl CanEncode for Vec { Each type varies, but the choice is global: once `u32` encodes one way, that is the only way for the whole program. A blanket implementation that would share logic across several types is rejected, because it could overlap. This is where Rust's coherence guarantee delivers its value, and also where -it starts to bind. Tier 2 is the right tier for a capability that varies by type but never by +it starts to bind. Tier 2 is the right tier for an operation that varies by type but never by application. ## Tier 3: many implementations, one wired per type @@ -123,11 +123,11 @@ readers most often miss, because nothing in a signature marks it. In the **retrofit** shape the wired type is the data itself, as `u32` is above. That type is usually one you do not own, so it gets one wiring for the whole program. This is the right shape when the -capability belongs to the data, or when an existing trait cannot change its signature. +operation belongs to the data, or when an existing trait cannot change its signature. In the **application** shape the wired type stands for the application rather than for data, and it often has no fields at all. Here the "one wiring per type" limit stops mattering, because you decide -how many application types exist. The capability is about the application, such as sending an email or +how many application types exist. The operation is about the application, such as sending an email or querying a user, rather than about a value: ```rust @@ -236,9 +236,9 @@ The guiding rule is to settle at the lowest tier that expresses the use case, be tier trades simplicity for modularity that may not be needed. Most code has one implementation of most things, and for that code a plain trait is the right answer rather than a compromise. -Two questions place a capability faster than working through the tiers one by one. +Two questions place an operation faster than working through the tiers one by one. -**Is the capability about the data, or about the application?** About the data means the wired type +**Is the operation about the data, or about the application?** About the data means the wired type *is* the thing being operated on, as `Rectangle: CanCalculateArea` is. About the application means the wired type is one you define to carry choices, often with no fields at all. @@ -254,7 +254,7 @@ right answer to a different question. | About the application | **Application** (tier 3) | One choice per context you define, and you can define as many as you like. | | About a foreign type, differing per application | **Fully modular** (tiers 4–5) | One choice per context, per target type. | -**The application shape is where most CGP code lives.** A capability about the application, such as +**The application shape is where most CGP code lives.** An operation about the application, such as sending an email or running the server, wired per application with no type parameter anywhere, is the ordinary case rather than the elaborate one. @@ -270,14 +270,14 @@ alternative wins, because in most rows it does. | The alternative | Prefer it when | Reach for CGP when | |---|---|---| -| **A plain trait or generic** | A capability has one implementation, or one per type with a single global choice. **This is most code.** | The implementations multiply, the choice must differ per context, or threading a generic through every layer has started to hurt. | +| **A plain trait or generic** | A trait has one implementation, or one per type with a single global choice. **This is most code.** | The implementations multiply, the choice must differ per context, or threading a generic through every layer has started to hurt. | | **A direct impl on the context** | A provider would have exactly one user. Two contexts that each have their own single implementation need no providers and no wiring at all. | A second context wants the *same* implementation, or the implementation should compose with a wrapper. | | **An enum** | The variant set is small, closed, and known, with fixed operations. A `match` is clearer than any machinery. | The variant set is open, or independent modules must each contribute one. | | **`dyn Trait`** | The set of implementations is not known until runtime. CGP gives up exactly that openness. | The set *is* known at build time, and you want the decoupling without the dispatch cost. | | **A dependency-injection crate** | You specifically want a container's lifecycle and object-graph semantics. | You want compile-time-checked, reflection-free injection, which is the traits-and-generics approach, not a framework. | | **A generic-programming library such as `frunk`** | A one-off manipulation of a heterogeneous list. The lighter, focused library is less to learn and enough. | The structural machinery is part of a larger component-and-wiring design. | | **A hand-rolled macro** | The generation is narrow and local. | You notice you are reinventing marker types plus a helper trait, which is CGP's own mechanism. | -| **Waiting for a language feature** | A first-class facility would serve better and you can afford to wait. Rust's effects and reflection work is pursuing ground CGP covers. | You need the capability now, on stable Rust. CGP is complementary to what the language is building rather than a bet against it. | +| **Waiting for a language feature** | A first-class facility would serve better and you can afford to wait. Rust's effects and reflection work is pursuing ground CGP covers. | You need the feature now, on stable Rust. CGP is complementary to what the language is building rather than a bet against it. | That last row is worth taking seriously rather than reading as a formality. Some of what CGP does is plausibly better as a language feature eventually, and a project that can wait should. @@ -290,7 +290,7 @@ Four cases are not trade-offs. Naming them is more useful than any argument in C redefinition while the program runs. Its wiring is fixed at build time. That lives on the runtime side, where `dyn Trait` and the dynamic languages remain right. -**Exactly one implementation.** A capability with one definition belongs in a plain trait, which is +**Exactly one implementation.** A trait with one definition belongs in a plain trait, which is tier 1 or tier 2. If you want it to read like CGP anyway, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds it from a function with no component, no provider, and no wiring, and it keeps working unchanged if a second implementation ever arrives. @@ -317,7 +317,8 @@ Three things do pay with one context. application touches, not along its contexts, so a single application with several types to encode, serialize, or validate already has more than one implementation to place. That is [bypassing coherence](./coherence.md), and it needs no second context at all. -- **The orphan-rule escape.** Adding a capability to a type from another crate needs one context and +- **The orphan-rule escape.** Adding a trait implementation to a type from another crate needs one + context and a foreign type. No newtype wrapper, and no second application. - **Dependencies declared where the implementation is.** A `&self` method on a concrete struct may read any field and call any other method, so nothing short of reading the body tells you what it @@ -328,7 +329,7 @@ And then the second context you probably already have: **the test harness.** It to justify and the one nobody argues about. **If none of that applies, the honest recommendation is to stay put.** A codebase with one -application, no capability needing more than one implementation, and no foreign type to extend is one +application, no trait needing more than one implementation, and no foreign type to extend is one where CGP's central bargain does not pay. Reach for `#[cgp_fn]` alone, or nothing. ## "Won't I end up with a context per configuration?" @@ -347,7 +348,7 @@ variations are worth their own type; the tools you already use handle the ones t There is a payoff here worth naming if you are writing a library. An enum you expose for supported backends is normally a ceiling on what downstream users can have: a new variant means a pull request -or a fork. When the context-generic code is written against capabilities rather than against the +or a fork. When the context-generic code is written against traits on the context rather than against the enum, a downstream crate defines its own wider enum and its own context and reuses everything, with nothing to petition for. @@ -371,7 +372,7 @@ them. **Dramatically better and actively improving, not solved.** could not be cited. The honest reframing is that resolution costing at compile time is resolution that would otherwise cost at runtime or not be checked at all. -**There is a learning curve.** The first useful thing, a capability written as a function used with +**There is a learning curve.** The first useful thing, an operation written as a function used with no wiring, needs only ordinary Rust knowledge, so the first step is small. The curve past it is real. Three of those costs, the learning curve, decoding the diagnostics, and the volume of wiring to write @@ -394,7 +395,7 @@ far*. through 5 are built on, and closes with the same costs stated for that construct specifically. If the answer here was "not yet", [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the whole of what -you need: a capability from a function, no wiring, nothing to reverse later. If it was "yes", the +you need: a trait from a function, no wiring, nothing to reverse later. If it was "yes", the [Area calculation series](/docs/tutorials/area-calculation/) works up the tiers in order, and [`#[cgp_component]`](/docs/reference/macros/cgp_component) is where the component machinery starts. diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index d3d851bf..a1ac6692 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -59,7 +59,7 @@ pub trait CanGreet { } ``` -`AppNamespace` now knows that anything asking for this capability should look under +`AppNamespace` now knows that anything asking for this component should look under `@app.GreeterComponent`. It does not know what it will find there. A context joins the namespace and supplies the answer at that path: @@ -187,7 +187,7 @@ in CGP, because the mistake is not visible until a context wants to differ. **It is another hop, and a less obvious one.** With an [aggregate provider](./aggregate-providers.md) the context says which components come from the bundle. With a namespace it says nothing, since everything not wired locally falls through, so answering -"where does this capability come from?" means knowing the namespace and its parents. +"where does this implementation come from?" means knowing the namespace and its parents. **Paths are a second vocabulary.** `@app.GreeterComponent` is a type-level path, and it appears in error messages spelled out at length. The toolchain resugars it for the classes it recognizes; a plain diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index 37f69731..5dfe9aa7 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -76,7 +76,7 @@ where ``` `CanHandleApiSend` is **not a component**. It adds nothing to any wiring table and has no providers; it -exists to carry a stronger signature. It inherits the whole capability from `CanHandleApi` as a +exists to carry a stronger signature. It inherits the whole interface from `CanHandleApi` as a supertrait, additionally requires the response and the context to be `Send`, and writes `+ Send` on the future directly. @@ -125,7 +125,7 @@ endpoints and two contexts writes sixteen forwarding bodies. generic blanket impl, and that does not compile. A macro could generate the impls, but they would still be there. -**And it is a second trait to keep in step.** Adding a method to the capability means adding it here +**And it is a second trait to keep in step.** Adding a method to the original trait means adding it here too, and nothing enforces that the two stay aligned beyond the supertrait. The one consolation is that the whole thing disappears when Return Type Notation stabilizes. This is a diff --git a/docs/index.md b/docs/index.md index 66258ba9..c8bdfd7e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -22,7 +22,7 @@ how this separation works. You can adopt CGP one component at a time. A consumer trait remains an ordinary Rust trait that you can implement directly. Providers and wiring become useful when you need interchangeable implementations or want to reuse an implementation across contexts. The -[Overview](/docs/overview) covers those capabilities, along with abstract types, extensible data, and +[Overview](/docs/overview) covers those features, along with abstract types, extensible data, and composable handlers. ## Current Status @@ -38,7 +38,7 @@ other diagnostics retain the compiler's wording. CGP also publishes an [agent skill](/docs/ai/skills) to help coding assistants read, write, and debug CGP code. You still need to review the code an assistant produces. -Start with a small part of your project whose implementation choices already vary. For a capability +Start with a small part of your project whose implementation choices already vary. For a trait with one implementation, a plain trait may be enough. CGP particularly welcomes [early adopters and contributors](/docs/contribute) who want to experiment and help improve the library, tools, and documentation. diff --git a/docs/overview.md b/docs/overview.md index ad634216..72cf70c1 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -5,7 +5,7 @@ sidebar_position: 2 # Overview CGP lets you choose trait implementations at compile time and reuse application logic across those -choices. This page explains its main capabilities, the problems they address, and the trade-offs to +choices. This page explains its main features, the problems they address, and the trade-offs to consider. Each section links to a fuller explanation; for a working example, start with the [Hello World tutorial](/docs/tutorials/hello). @@ -48,7 +48,7 @@ chain. It is an early pre-release and does not rewrite every kind of compiler er ### Abstract Over Every Dependency -CGP lets reusable logic state the capabilities it needs while each application supplies concrete +CGP lets reusable logic state the traits it needs while each application supplies concrete implementations. Those choices can include I/O, storage, error handling, and runtime operations. Providers declare their requirements where they use them, through [impl-side dependencies](/docs/concepts/impl-side-dependencies). @@ -73,7 +73,7 @@ amount of separation your code needs. An abstract type lets each context choose a concrete type, such as its error type, without passing that choice as a separate generic parameter through every layer. Code names the associated type -where it needs it. A caller that only invokes a capability can depend on that capability without +where it needs it. A caller that only invokes a trait's method can depend on that trait without listing the types used inside its implementation. These are Rust associated types, so their guarantees depend on the bounds you declare. Using `f64` @@ -103,7 +103,7 @@ function calls remain a simpler choice when a sequence has no need for interchan ## Problems Solved CGP is most useful when a program already needs several implementations or dependency choices. The -following cases show how its capabilities address those needs. +following cases show how its features address those needs. ### Error Handling @@ -119,7 +119,7 @@ explicit; it does not invent conversions between arbitrary errors. See ### Async Runtime Application logic can depend on the runtime operations it uses without naming a particular executor. -For example, a provider that needs a timer can require a timer capability, leaving the application to +For example, a provider that needs a timer can require a timer trait, leaving the application to supply its implementation. Another application can reuse that provider with a different compatible timer implementation. @@ -153,7 +153,7 @@ variant is still determined at runtime. ### Monolithic Traits -A large trait can force every implementation to supply capabilities it never uses. CGP lets you +A large trait can force every implementation to supply methods it never uses. CGP lets you split independently chosen behavior into smaller components, each with its own providers. A provider declares the dependencies its implementation needs, while callers depend on the interface they use. @@ -167,7 +167,7 @@ See [impl-side dependencies](/docs/concepts/impl-side-dependencies) and the An error type, runtime, and storage backend can become generic parameters that intermediate code must repeat even when it only forwards a call. CGP lets the context select those types and expose -the required operations as capabilities. Intermediate code can then name the capability it calls, +the required operations as traits on the context. Intermediate code can then name the trait it calls, while the implementation names the dependencies it actually uses. Types that appear in an interface, such as a returned error, still belong in that interface. diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index a142a07c..abd33643 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -12,7 +12,7 @@ Register a provider as a namespace's default for a key. `#[default_impl(...)]` lets a *provider* register itself as a [namespace](/docs/concepts/namespaces)'s default for a key, at the point where the provider is defined. A namespace is a reusable table of default wirings that a **context** can opt into and then override entry by entry. (The context is the type the -capability runs against.) Ordinarily you write a namespace's entries in its own body. This attribute +method runs on.) Ordinarily you write a namespace's entries in its own body. This attribute moves one entry onto the provider: ```rust diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 95cabef6..8fa4c96b 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -43,7 +43,7 @@ pub trait CanCalculateArea { A **context** then points the component at [`UseDelegate`](../providers/use_delegate.md) over a table naming one implementation per shape, and the generated dispatcher does the lookup. (The context is the -type the capability runs against, and it also owns the wiring.) +type the method runs on, and it also owns the wiring.) `open` replaced this because the indirection turned out to be unnecessary. Every [`#[cgp_component]`](../macros/cgp_component.md) already generates a diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 3df778b6..cb540471 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -5,13 +5,14 @@ sidebar_position: 5 # `#[extend]` -Add a capability as a supertrait of a generated trait, so callers can rely on it too. +Add a trait as a supertrait of a generated trait, so callers can rely on it too. ## Overview -`#[extend]` declares that a capability is part of what a trait *guarantees*, rather than something its +`#[extend]` declares that a trait is part of what a generated trait *guarantees*, rather than +something its implementation happens to need. Where [`#[uses]`](uses.md) adds a private requirement, `#[extend]` adds a -supertrait. Every **context** implementing the trait, meaning every type the capability runs against, +supertrait. Every **context** implementing the trait, meaning every type the method runs on, must also satisfy it, and every caller may rely on it. ```rust @@ -20,13 +21,13 @@ must also satisfy it, and every caller may rely on it. **`#[extend]` relates to `#[uses]` as `pub use` relates to `use`.** This comparison is the clearest way to tell the pair apart. Both take the same syntax and both read as imports. But `#[uses]` imports a -capability for the implementation's own use and keeps it private, whereas `#[extend]` re-exports it as +trait for the implementation's own use and keeps it private, whereas `#[extend]` re-exports it as part of the contract. The same comparison explains why CGP prefers `#[extend]` over Rust's native supertrait syntax on a [`#[cgp_component]`](../macros/cgp_component.md). Writing `pub trait CanGreet: HasName` reads as inheritance from a parent, an is-a relationship that a CGP supertrait is not. `#[extend(HasName)]` reads -as importing a capability the trait passes on, which is the accurate description. The two generate the +as importing a trait that `CanGreet` passes on to its callers, which is the accurate description. The two generate the same trait, so this is a choice about how the definition reads. On [`#[cgp_fn]`](../macros/cgp_fn.md) the attribute is necessary, not only preferred. The `#[cgp_fn]` @@ -69,12 +70,12 @@ pub trait CanLoad { } ``` -`#[extend]` is therefore for a **capability** supertrait, one whose methods matter and whose associated +`#[extend]` is therefore for a **method** supertrait, one whose methods matter and whose associated types the signatures do not name. ## Examples -A `#[cgp_fn]` capability that guarantees two getters alongside its own method: +A `#[cgp_fn]` trait that guarantees two getters alongside its own method: ```rust use cgp::prelude::*; @@ -100,7 +101,8 @@ The body can call both getters, and so can anyone holding a `T: FullLabel`. That `#[uses]`. A function that takes a labelled value can format its name without asking for `HasName` separately. -On a component the effect is on the consumer trait, and the supertrait becomes part of the capability: +On a component the effect is on the consumer trait, and the supertrait becomes part of the consumer +trait's contract: ```rust #[cgp_component(Greeter)] @@ -115,8 +117,8 @@ available, and so may every caller. ## When to use it -**Reach for `#[extend]` when callers of the trait must be able to rely on the capability too**, and for -a capability supertrait on a `#[cgp_component]` in preference to native `:` syntax. Use something else +**Reach for `#[extend]` when callers of the trait must be able to rely on the supertrait too**, and for +a method supertrait on a `#[cgp_component]` in preference to native `:` syntax. Use something else when the requirement belongs elsewhere. The choice turns on where the requirement should be visible. - **The implementation needs it privately.** Use [`#[uses]`](uses.md). This is the common case by a wide @@ -129,7 +131,7 @@ when the requirement belongs elsewhere. The choice turns on where the requiremen clause. A supertrait widens the contract permanently, and that cost decides whether to promote a requirement. -You cannot later remove it without breaking every implementor, and it demands the capability from +You cannot later remove it without breaking every implementor, and it demands the supertrait from contexts that only call the one method the trait declares. Prefer `#[uses]` unless callers need the guarantee. @@ -223,7 +225,8 @@ impl Greeter { error: cannot find attribute `extend` in this scope ``` -Expect a second error alongside it, because the bound was never added. The body's calls to the capability +Expect a second error alongside it, because the bound was never added. The body's calls to the +trait's method then fail with `E0599`, reporting that the method exists but its trait bounds were not satisfied. Both errors have the same cause, and one fix removes both: move the requirement to [`#[uses]`](uses.md), or onto the component's trait where supertraits belong. @@ -239,7 +242,7 @@ is the practical reason to default to `#[uses]`. - [`#[use_type]`](use_type.md) — preferred when the supertrait exists to supply a type. - [`#[cgp_fn]`](../macros/cgp_fn.md) — where `#[extend]` is the only way to declare a supertrait. - [`#[cgp_component]`](../macros/cgp_component.md) — where it is preferred over native `:` syntax. -- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — defines the getter capabilities most often extended. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — defines the getter traits most often extended. The ideas behind it: diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 4714ed4c..c7455f43 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -12,13 +12,13 @@ Add `where` predicates to a generated trait's own definition, not just to its im `#[extend_where]` moves a `where` predicate onto the trait that a [`#[cgp_fn]`](../macros/cgp_fn.md) generates, so the predicate becomes a condition of naming the trait at all. By default, `#[cgp_fn]` treats the `where` clause you write on the function as an implementation detail: the bounds land on the -generated implementation and never appear on the generated trait. That default keeps a capability's +generated implementation and never appear on the generated trait. That default keeps a trait's requirements private to its implementation, and it is almost always right. The cost of that default is that an unsatisfiable requirement becomes invisible. A bound on the implementation only decides which **contexts** the implementation covers. (A context is the type the -capability runs against, and it supplies the values the capability needs as its fields.) So the compiler -accepts a caller that names the capability for a type that can never satisfy it. The bound stays +method runs on, and it supplies the values the method needs as its fields.) So the compiler +accepts a caller that names the trait for a type that can never satisfy it. The bound stays unproven, and the error appears later, at a different place. `#[extend_where]` puts the predicate where the compiler checks it as soon as the trait is named: @@ -57,7 +57,7 @@ an ordinary `where` clause there. ## Examples -A generic capability whose parameter carries a bound that belongs to the contract: +A generic trait whose parameter carries a bound that belongs to the contract: ```rust use cgp::prelude::*; @@ -78,7 +78,7 @@ checks it wherever `Scale` is named. `Scalar: Mul` stay because multiplication is a detail of how *this* body computes a scale and no use site needs to know it. The promotion's effect is visible at the boundary. The compiler rejects a caller that names the -capability for a type it cannot satisfy, at the place the bound is written, and names the trait that +trait for a type it cannot satisfy, at the place the bound is written, and names the trait that demanded it: ```rust @@ -110,13 +110,13 @@ where ## When to use it -**Reach for `#[extend_where]` when a predicate is part of what the capability means**, and you want the +**Reach for `#[extend_where]` when a predicate is part of what the trait means**, and you want the compiler to enforce it where the trait is named, rather than letting it narrow which contexts the implementation covers without a report. That is a real but uncommon need, and the default of leaving bounds on the implementation is right for almost everything. The useful test is who the bound is *about*. A bound describing how the body computes its answer belongs on -the implementation. A bound describing what the capability requires of its own type parameters, something +the implementation. A bound describing what the trait requires of its own type parameters, something that would be part of the signature if you were writing the trait by hand, belongs on the trait. Other constructs carry the requirements that belong elsewhere. @@ -125,11 +125,11 @@ Other constructs carry the requirements that belong elsewhere. but a supertrait reads as what it is, and unlike a predicate Rust *does* hand it to callers by elaboration. - **A private requirement**, the overwhelmingly common case, belongs in the function's own `where` clause, - or in [`#[uses]`](uses.md) when it is a capability. + or in [`#[uses]`](uses.md) when it is a trait on the context. - **An abstract type pinned to a concrete one** is [`#[use_type]`](use_type.md)'s equality form, which adds the bound and lets the signature name the type as a bare word. -Do not use it to spare callers a bound, because it has the opposite effect. If holding the capability +Do not use it to spare callers a bound, because it has the opposite effect. If holding the trait should imply something, use a supertrait, which requires the bound to be on `Self`. ## Under the hood @@ -234,7 +234,7 @@ has the effect this attribute exists to produce elsewhere. ## Related constructs - [`#[extend]`](extend.md) — the supertrait sibling, and the one callers do receive. -- [`#[uses]`](uses.md) — a private capability bound on the implementation. +- [`#[uses]`](uses.md) — a private trait bound on the implementation. - [`#[use_type]`](use_type.md) — for pinning an abstract type, which this could express but should not. - [`#[cgp_fn]`](../macros/cgp_fn.md) — the only host, and the reason the attribute exists. - [`#[implicit]`](implicit.md) — contributes the bounds that always sort last. diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 454cf44b..1a9eba24 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -15,9 +15,9 @@ through a field and callers never name it. `#[cgp_fn]` puts every generic parameter you write on the function onto both the trait and its implementation. That is right for a type the caller chooses. But a body often needs a type that nobody chooses: a database handle, a name that only has to be printable, a scalar read from a field. The -**context**, the type the capability runs against and the owner of the fields the body reads, already +**context**, the type the method runs on and the owner of the fields the body reads, already fixes that type through the field. A parameter on the trait would then make every caller, and every -capability built on this one, declare a parameter and repeat its bounds for a type they never touch. +trait built on this one, declare a parameter and repeat its bounds for a type they never touch. With `#[impl_generics]`, the trait stays free of parameters, and the compiler infers the parameter from the field the body reads: @@ -36,7 +36,7 @@ wiring or any declaration beyond the field itself. The cost is that the type is hidden rather than named. It exists only where a value of it flows through an [`#[implicit]`](./implicit.md) argument, so nothing else can refer to it: not this -capability's own signature, not another capability, and not a second provider. When the type must be +trait's own signature, not another trait, and not a second provider. When the type must be named, promote it to an abstract type with [`#[cgp_type]`](../macros/cgp_type.md) and import it with [`#[use_type]`](./use_type.md). [When to use it](#when-to-use-it) says where that boundary lies. @@ -75,7 +75,7 @@ have an implementation of its own to carry one. ## Examples -A capability whose one type dependency each context fixes through a field: +A trait whose one type dependency each context fixes through a field: ```rust use cgp::prelude::*; @@ -107,7 +107,7 @@ pub fn greet_both(person: &Person, robot: &Robot) { wiring. For `Person` the compiler resolves `Name` to `String`, and for `Robot` to `u32`. Neither type appears anywhere except in the field. -A capability built on `greet` never learns that `Name` exists: +A trait built on `greet` never learns that `Name` exists: ```rust #[cgp_fn] @@ -127,24 +127,24 @@ the shortest form, it does not need wiring, and it reads as "this works with any compatible type". You must move to an abstract type once the type has to be *named* somewhere the inferred form cannot reach. -- **The type appears in the capability's signature.** An impl-only parameter is not in scope on the +- **The type appears in the trait's signature.** An impl-only parameter is not in scope on the trait, so a return type or an explicit parameter cannot mention it. This condition applies as soon as - a capability returns a value of the type to its caller. -- **Two capabilities must agree on the type.** A transaction type only means something relative to - its database, so the capability that opens one and the capability that commits it must mean the + a method returns a value of the type to its caller. +- **Two traits must agree on the type.** A transaction type only means something relative to + its database, so the trait that opens one and the trait that commits it must mean the same type. Each implementation infers its own parameter, so inferred parameters cannot state the agreement. In both cases declare the type with [`#[cgp_type]`](../macros/cgp_type.md), import it with [`#[use_type]`](./use_type.md), and let the context supply it by wiring. Do not answer either condition with a generic parameter on the function. Such a parameter lands on the trait, so every -caller and every intermediate capability must declare it and repeat its bounds whether they touch it +caller and every intermediate trait must declare it and repeat its bounds whether they touch it or not. It also puts the decision in the wrong place: `` on a trait says the caller chooses the database type, though the application determines it. Some neighbours cover what this attribute is not for. -- **A bound on `Self`** is a capability dependency; write it with [`#[uses]`](./uses.md). +- **A bound on `Self`** is a trait dependency; write it with [`#[uses]`](./uses.md). - **A bound on one of the trait's own parameters** that callers must see is [`#[extend_where]`](./extend_where.md)'s job, on the trait side. - **A type the caller should choose per call site** is a plain generic parameter on the function. @@ -220,7 +220,7 @@ error[E0207]: the type parameter `Name` is not constrained by the impl trait, se Either read a field whose type mentions the parameter, or, if the caller should choose the type, make it a generic parameter on the function instead. -**A parameter cannot appear in the capability's signature.** Only the implementation declares it, so a +**A parameter cannot appear in the trait's signature.** Only the implementation declares it, so a return type or an explicit parameter that names it refers to nothing on the trait: ```rust @@ -297,7 +297,7 @@ parameter in the block's own generic list, which is already impl-only. - [`#[implicit]`](./implicit.md) — the argument whose field type pins the parameter. - [`#[cgp_fn]`](../macros/cgp_fn.md) — the only host, and where the generics split is explained. - [`#[extend_where]`](./extend_where.md) — the trait-side sibling: a predicate callers must see. -- [`#[uses]`](./uses.md) — a capability bound on `Self`, the other kind of private requirement. +- [`#[uses]`](./uses.md) — a trait bound on `Self`, the other kind of private requirement. - [`#[use_type]`](./use_type.md) and [`#[cgp_type]`](../macros/cgp_type.md) — the abstract-type form to move to when the type must be named. - [`HasField`](../traits/field-access/has_field.md) — the bound that carries the inference. diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 3f74d188..86681376 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -31,7 +31,8 @@ how a type-level [`Symbol!`](../macros/symbol.md) and a `PhantomData` tag work. all of that behind an argument that reads as `width: f64`, and the argument's *name* names the field. So `#[implicit]` is the recommended way to read a context's own field, and usually the first piece of -CGP anyone writes. A reader who understands functions and arguments can write a working capability and +CGP anyone writes. A reader who understands functions and arguments can write a working +context-generic function and learn the machinery later, when they need it. ## Usage @@ -109,7 +110,7 @@ a mutable field borrow rather than a mutable local copy. ## Examples -A complete capability, and a context that qualifies for it by having the right fields: +A complete trait, and a context that qualifies for it by having the right fields: ```rust use cgp::prelude::*; @@ -166,7 +167,7 @@ A **getter trait** covers the cases an implicit argument cannot reach. - **The field is on a different type.** An implicit argument reads only from `self`, so a value living on a request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type. The value does not live on `self` at all. -- **The accessor must be a named capability.** When other code depends on "this context can tell you its +- **The accessor must be a named trait.** When other code depends on "this context can tell you its name" rather than on a field, that dependency needs a trait to point at, importable with [`#[uses]`](uses.md) or usable as a supertrait. - **The getter carries a type inferred from the field.** A getter may declare an associated type and @@ -287,13 +288,13 @@ error: a `&mut` implicit argument must be the only implicit argument, since its ## Related constructs -- [`#[cgp_fn]`](../macros/cgp_fn.md) — the usual host, turning a function into a capability. +- [`#[cgp_fn]`](../macros/cgp_fn.md) — the usual host, turning a function into a trait. - [`#[cgp_impl]`](../macros/cgp_impl.md) — the other host, for a component's provider. - [`#[derive(HasField)]`](../derives/derive_has_field.md) — what a context derives to qualify. - [`HasField`](../traits/field-access/has_field.md) — the trait the generated bounds are written against. - [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — the getter form, for the cases above. - [`#[cgp_getter]`](../macros/cgp_getter.md) — a getter whose source field is chosen by wiring. -- [`#[uses]`](uses.md) — imports a capability rather than a value. +- [`#[uses]`](uses.md) — imports a trait rather than a value. - [`#[use_type]`](use_type.md) — imports a type rather than a value. - [`Symbol!`](../macros/symbol.md) — the type-level field name the bounds are keyed on. diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index df4f7a68..a7c8e4eb 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -17,7 +17,7 @@ is the fuller guide, for a reader who already knows the essentials. ## Reading a value from the context [`#[implicit]`](./implicit.md) marks a function argument that the macro reads from a same-named field -on the context rather than from the caller. The context is the type the capability runs against. A +on the context rather than from the caller. The context is the type the method runs on. A provider that needs a value then reads like an ordinary function that takes it. Almost every provider uses the attribute, and it is usually the first piece of CGP anyone writes. diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index 61577296..63693f95 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -14,7 +14,7 @@ namespace addresses the component by that path. prefix. Written on the component's trait beside [`#[cgp_component]`](../macros/cgp_component.md), it adds the component's own route to the namespace. A namespace is a reusable wiring table that a **context** joins with one line and then overrides where it needs to. (The context is the type the -capability runs against.) A namespace answers a lookup by *routing* it: asked for a component, it says +method runs on.) A namespace answers a lookup by *routing* it: asked for a component, it says where to look next. ```rust @@ -146,7 +146,7 @@ check_components! { Reading the resolution: `app.greet()` looks up `GreeterComponent`. `App` does not wire it directly, so the lookup falls through to `DefaultNamespace`, which redirects to `@app.GreeterComponent`, and `App`'s own table binds that path to `GreetHello`. **Environmental context, self-targeted**: `App` -exists to carry the wiring and a `name` field, and the capability is about `App` itself. +exists to carry the wiring and a `name` field, and the operation is about `App` itself. A second context joins the same namespace and binds a different provider at the same path, without repeating anything from the first: diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index b3895100..1d7e8976 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -22,7 +22,7 @@ That reads as *`InnerCalculator` is an `AreaCalculator` for this context*, and i counterpart to [`#[uses]`](uses.md). `#[uses]` imports a consumer trait (or an ordinary Rust trait) that the **context** must satisfy. `#[use_provider]` imports a provider trait that a named provider must satisfy for the context. The context is the type the implementation runs against. Both attributes read -as importing a dependency. They differ only in whether the dependency is a capability of the context or +as importing a dependency. They differ only in whether the dependency is a trait of the context or a provider. The inner provider is a named type rather than a method on the context, so the body calls it as an @@ -150,7 +150,7 @@ generated code and older wiring rather than write it. The choice against its neighbours turns on *what* the implementation depends on, and one distinction is easy to miss because both spellings compile. -- **A capability of the context** is [`#[uses]`](uses.md), which imports a consumer trait or an ordinary +- **A trait of the context** is [`#[uses]`](uses.md), which imports a consumer trait or an ordinary trait the context satisfies. `#[use_provider]` imports a provider trait instead, one that a separate provider satisfies for the context. - **Whatever the context already chose** needs no attribute at all. Calling `self.area()` in the body diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index aeaef4c2..9d639c61 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -189,7 +189,7 @@ a hand-written supertrait plus `Self::`-qualified paths in existing code rather Its neighbours handle the requirements that are not types, and one of them declares the type this attribute imports. -- **A capability** is [`#[uses]`](uses.md) for a private bound or [`#[extend]`](extend.md) for a +- **A trait on the context** is [`#[uses]`](uses.md) for a private bound or [`#[extend]`](extend.md) for a supertrait. Use `#[extend]` specifically when the supertrait's methods matter and its associated types are not named in your signatures, the case where `#[use_type]` has nothing to rewrite. - **A value from a field** is an [`#[implicit]`](implicit.md) argument. @@ -207,8 +207,8 @@ qualified, the imported one bare. Prefer an inferred parameter over an abstract type when the type only ever flows through values the body reads: [`#[impl_generics]`](./impl_generics.md) on a `#[cgp_fn]` is shorter and does not need -wiring. Move to an abstract type when the type must be named in the capability's own signature, or when -two capabilities have to +wiring. Move to an abstract type when the type must be named in the trait's own signature, or when +two traits have to [agree that they mean the same one](/docs/concepts/abstract-types#one-type-agreed-on-by-everything-that-needs-it). ## Under the hood @@ -367,7 +367,7 @@ Write `Self::Output`, and do not list it in a `#[use_type]` attribute. - [`UseType`](../providers/use_type.md) — the provider a context wires to supply the concrete type; a different thing from this attribute despite the name. - [`HasType`](../components/has_type.md) — the built-in abstract-type component underneath. -- [`#[uses]`](uses.md) — imports a capability rather than a type. +- [`#[uses]`](uses.md) — imports a trait rather than a type. - [`#[extend]`](extend.md) — adds a supertrait without rewriting any type names. - [`#[implicit]`](implicit.md) — imports a value from a field. - [`#[cgp_fn]`](../macros/cgp_fn.md), [`#[cgp_impl]`](../macros/cgp_impl.md), and diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index f7487969..ea44e679 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -5,7 +5,7 @@ sidebar_position: 2 # `#[uses]` -Import the capabilities an implementation depends on, reading like a `use` statement. +Import the traits an implementation depends on, reading like a `use` statement. ## Overview @@ -17,13 +17,13 @@ against: #[uses(RectangleArea)] ``` -That reads as *this implementation uses the `RectangleArea` capability*, the same meaning a `use` +That reads as *this implementation uses the `RectangleArea` trait*, the same meaning a `use` statement has for a name. The body can then call `self.rectangle_area()` as though it had imported -the capability. `#[uses]` is the consumer-side counterpart to [`#[use_provider]`](use_provider.md). +the trait. `#[uses]` is the consumer-side counterpart to [`#[use_provider]`](use_provider.md). `#[use_provider]` imports a provider trait that a named provider must satisfy for the context, whereas `#[uses]` imports a trait that the context itself must satisfy. -The requirement stays private to the implementation. A caller who depends on the capability never sees +The requirement stays private to the implementation. A caller who depends on the trait never sees it and never has to repeat it. That is the point of declaring the dependency where the implementation lives rather than on its public interface. Prefer `#[uses]` over a hand-written bound. The equivalent `where` clause is the older form you meet in existing code, and [Under the hood](#under-the-hood) @@ -38,12 +38,12 @@ implementation: #[uses(RectangleArea, CanCalculateArea)] ``` -Each entry is a capability, optionally with type arguments: a bare `RectangleArea` becomes +Each entry is a trait, optionally with type arguments: a bare `RectangleArea` becomes `Self: RectangleArea`, and `CanCompute` becomes `Self: CanCompute`. **The trait need not be a CGP construct.** `#[uses(Display)]` and `#[uses(AsRef<[u8]>)]` are accepted and preferred over the equivalent hand-written clause. The attribute only requires that the bound is one a -context can satisfy, so an ordinary Rust trait imports exactly as a capability does. +context can satisfy, so an ordinary Rust trait imports exactly as a CGP trait does. **Prefer one attribute carrying every dependency**, as in `#[uses(RectangleArea, Display)]`, because a single list reads as a single set of requirements. You may also split entries across several @@ -52,7 +52,7 @@ attribute only when there is a reason. `#[uses(...)]` is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on [`#[cgp_impl]`](../macros/cgp_impl.md). In both, it imports into the item being defined, and it does not -matter how the imported capability was itself produced. +matter how the imported trait was itself produced. ### Bounds beyond the simple form @@ -69,7 +69,7 @@ type as a bare `Error`. To put a bound on the generated trait rather than only o ## Examples -A capability built on top of a component, without knowing which provider supplies it: +A trait built on top of a component, without knowing which provider supplies it: ```rust use cgp::prelude::*; @@ -91,7 +91,7 @@ than on any particular provider, so every context that can calculate an area get regardless of how it does so. A context that swaps its area provider keeps `scaled_area` working unchanged. -The same attribute inside a provider, this time importing a plain function-style capability: +The same attribute inside a provider, this time importing a plain function-style trait: ```rust #[cgp_fn] @@ -109,17 +109,17 @@ impl AreaCalculator { ``` This provider is a short adapter: it satisfies the `AreaCalculator` component by calling whatever -`rectangle_area` computes. Any context with the fields that capability needs can wire it. +`rectangle_area` computes. Any context with the fields that trait needs can wire it. ## When to use it -**Use `#[uses]` for every capability dependency**, in preference to writing the `Self:` bound by hand. +**Use `#[uses]` for every trait dependency**, in preference to writing the `Self:` bound by hand. You read the hand-written form in existing code rather than write it. The choice between `#[uses]` and its neighbours turns on *what* the implementation depends on, and on *where* the requirement should be visible. -- **A value from the context** is not a capability. Use an [`#[implicit]`](implicit.md) argument, which +- **A value from the context** is not a trait. Use an [`#[implicit]`](implicit.md) argument, which reads a field directly rather than routing through a trait. - **A type from the context** is imported with [`#[use_type]`](use_type.md), which adds the bound and additionally lets the signature write the type as a bare name instead of a qualified path. @@ -221,14 +221,14 @@ the missing argument. - [`#[cgp_fn]`](../macros/cgp_fn.md) and [`#[cgp_impl]`](../macros/cgp_impl.md) — the two hosts. - [`#[extend]`](extend.md) — the same syntax, but as a public supertrait rather than a private bound. - [`#[extend_where]`](extend_where.md) — a predicate on the generated trait's own `where` clause. -- [`#[use_type]`](use_type.md) — imports a type rather than a capability, and rewrites its uses. +- [`#[use_type]`](use_type.md) — imports a type rather than a trait, and rewrites its uses. - [`#[use_provider]`](use_provider.md) — imports an inner provider, filling in its context argument. -- [`#[implicit]`](implicit.md) — imports a value from a field rather than a capability. -- [`#[cgp_component]`](../macros/cgp_component.md) — defines the capabilities most often imported. +- [`#[implicit]`](implicit.md) — imports a value from a field rather than a trait. +- [`#[cgp_component]`](../macros/cgp_component.md) — defines the traits most often imported. The ideas behind it: -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — what an imported capability +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — what an imported trait becomes, and why callers never see it. ## Source diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md index 889eb595..369f81b4 100644 --- a/docs/reference/components/can_raise_error.md +++ b/docs/reference/components/can_raise_error.md @@ -12,7 +12,7 @@ Turn a concrete source error into the context's abstract `Self::Error`. `CanRaiseError` lets generic CGP code produce its context's abstract error from any concrete error it meets. A provider that calls a fallible operation gets back a specific error type, a parse error, an I/O error, a string message, but it must return the **context's** abstract `Self::Error`, -whose concrete identity it does not know. The context here is the type a capability runs against, which +whose concrete identity it does not know. The context here is the type a method runs on, which supplies the values an implementation needs as its own fields, and it decides how each source error maps into its chosen error type. `CanRaiseError` bridges the gap: generic code writes `Context::raise_error(source)` and the context converts the concrete `SourceError` into `Self::Error`. @@ -53,7 +53,7 @@ context type rather than of any particular value: fn raise_error(error: SourceError) -> Error; ``` -A context gains the capability by wiring `ErrorRaiserComponent`, whose key lives under +A context gains the operation by wiring `ErrorRaiserComponent`, whose key lives under `cgp::core::error`, to a provider. Because the trait dispatches per source-error type, the natural wiring is a table keyed on `SourceError`, most idiomatically an [`open` statement](../macros/delegate_components.md) that routes each concrete error to a provider that @@ -110,7 +110,7 @@ The provider `LoadOrFail` names neither the context nor its concrete error type. `CanRaiseError` through [`#[uses]`](../attributes/uses.md) to turn a `String` message into the abstract error, and any wired context that satisfies that bound, typically by plugging in an error backend, makes `load` produce errors in that context's chosen type. The context is an **environmental -context**, and the capability targets it rather than a value. +context**, and the component targets it rather than a value. ## When to use it diff --git a/docs/reference/components/can_wrap_error.md b/docs/reference/components/can_wrap_error.md index fa8e52d1..612e5a90 100644 --- a/docs/reference/components/can_wrap_error.md +++ b/docs/reference/components/can_wrap_error.md @@ -12,8 +12,8 @@ Attach a piece of detail to an error the context already holds, enriching it as `CanWrapError` enriches an error as it travels up a call stack. Where [`CanRaiseError`](./can_raise_error.md) converts a *foreign* error into the context's abstract error, `CanWrapError` takes an error the **context** already holds and folds a piece of `Detail` into it, a -message, a span, a path, producing an enriched `Self::Error`. The context is the type a capability runs -against, which supplies the values an implementation needs as its own fields, and it decides how detail +message, a span, a path, producing an enriched `Self::Error`. The context is the type a method runs +on, which supplies the values an implementation needs as its own fields, and it decides how detail is combined with an existing error. Together the two components cover the common error-handling motions in CGP: raise a foreign error in, then wrap context onto it as it bubbles up. @@ -51,7 +51,7 @@ error plus a detail and returns a new error with the detail folded in: fn wrap_error(error: Error, detail: Detail) -> Error; ``` -A context gains the capability by wiring `ErrorWrapperComponent`, whose key lives under +A context gains the operation by wiring `ErrorWrapperComponent`, whose key lives under `cgp::core::error`, to a provider. The trait dispatches per detail type, so the natural wiring is a table keyed on `Detail`, most idiomatically an [`open` statement](../macros/delegate_components.md): @@ -102,7 +102,7 @@ The provider `LoadOrFail` first raises a `String` into the context's abstract er [`CanRaiseError`](./can_raise_error.md), then wraps a further message onto it with `CanWrapError`. Both dependencies are declared with [`#[uses]`](../attributes/uses.md), so neither appears on the public `CanLoad` signature, and any context that satisfies them makes `load` produce enriched errors in its own -error type. The context is an **environmental context**, and the capability targets it. +error type. The context is an **environmental context**, and the component targets it. ## When to use it diff --git a/docs/reference/components/handler/async_computer.md b/docs/reference/components/handler/async_computer.md index 3fac9025..2d66fc8c 100644 --- a/docs/reference/components/handler/async_computer.md +++ b/docs/reference/components/handler/async_computer.md @@ -13,7 +13,7 @@ The asynchronous, infallible member of the handler family: a [`Computer`](./comp already in memory is a [`Computer`](./computer.md); awaiting a timer or a channel that always yields is an `AsyncComputer`. It is the async point on the family's synchronicity axis with the failure path still absent, so it transforms an `Input` into an `Output` under a phantom `Code` tag, against a **context** -(the type a capability runs against, which supplies the values an implementation needs as its own +(the type a method runs on, which supplies the values an implementation needs as its own fields), and returns the `Output` directly rather than a `Result`. It sits between [`Computer`](./computer.md), which drops the asynchrony, and [`Handler`](./handler.md), @@ -54,7 +54,7 @@ method is `async` and takes the input by value: async fn compute_async(&self, _code: PhantomData, input: Input) -> Self::Output; ``` -A context gains the capability by wiring `AsyncComputerComponent` to a provider, and it dispatches on +A context gains the operation by wiring `AsyncComputerComponent` to a provider, and it dispatches on both the `Code` tag and the `Input` type. In everyday code the provider comes from [`#[cgp_computer]`](../../macros/cgp_computer.md), which wires the promotion table so a synchronous function also answers `CanComputeAsync`, and the crate ships a [`UseField`](../../providers/use_field.md) diff --git a/docs/reference/components/handler/async_computer_ref.md b/docs/reference/components/handler/async_computer_ref.md index c02514c3..24797d86 100644 --- a/docs/reference/components/handler/async_computer_ref.md +++ b/docs/reference/components/handler/async_computer_ref.md @@ -14,7 +14,7 @@ borrows its input. [`AsyncComputer`](./async_computer.md) and takes its input by reference like [`ComputerRef`](./computer_ref.md). A computation that must await and only *reads* its argument, while still never failing, fits it: its method is `async`, receives `&Input`, and returns the `Output` directly -with no failure path. It runs against a **context**, the type a capability runs against that supplies the +with no failure path. It runs against a **context**, the type a method runs on that supplies the values an implementation needs as its own fields. It is the async by-reference corner of the infallible computers. Like the other computers it never names @@ -54,7 +54,7 @@ The method is `async` and borrows the input: async fn compute_async_ref(&self, _code: PhantomData, input: &Input) -> Self::Output; ``` -A context gains the capability by wiring `AsyncComputerRefComponent` to a provider, and it dispatches on +A context gains the operation by wiring `AsyncComputerRefComponent` to a provider, and it dispatches on both the `Code` tag and the `Input` type. It is the least commonly wired member of the family, reached when a computation is at once async, infallible, and read-only over its input. A simpler variant is usually promoted into it through the [handler combinators](../../providers/handler/index.md). diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md index e5c1504c..84f5050b 100644 --- a/docs/reference/components/handler/computer.md +++ b/docs/reference/components/handler/computer.md @@ -11,8 +11,8 @@ The pure synchronous transform of the handler family: infallible, and the simple `Computer` is for computations that always succeed and need no error type. A computation that adds two numbers, formats a value, or projects a field never fails and never needs the **context's** abstract -error, so forcing it to return a `Result` would be noise. The context is the type a capability runs -against, which supplies the values an implementation needs as its own fields. `Computer` captures the +error, so forcing it to return a `Result` would be noise. The context is the type a method runs +on, which supplies the values an implementation needs as its own fields. `Computer` captures the succeeds-always case: a provider names an `Output` type and produces it from the context, a phantom `Code` tag, and an `Input`, with no failure path. @@ -53,7 +53,7 @@ value, returning the associated `Output`: fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; ``` -A context gains the capability by wiring `ComputerComponent` to a provider. In everyday code the +A context gains the operation by wiring `ComputerComponent` to a provider. In everyday code the provider comes from [`#[cgp_computer]`](../../macros/cgp_computer.md), which turns a plain function such as `fn double(input: u64) -> u64` into a `Computer` provider and wires the promotion table so the same function also answers `CanTryCompute`, `CanComputeAsync`, `CanHandle`, and the by-reference forms. diff --git a/docs/reference/components/handler/computer_ref.md b/docs/reference/components/handler/computer_ref.md index 11f0274b..c6623443 100644 --- a/docs/reference/components/handler/computer_ref.md +++ b/docs/reference/components/handler/computer_ref.md @@ -13,7 +13,7 @@ The by-reference member of the handler family: a [`Computer`](./computer.md) tha synchronous, infallible computation that only *reads* its argument and should not take ownership of it fits `ComputerRef`, whose method receives `&Input` where `CanCompute` receives `Input`. Everything else is the same: it transforms toward an `Output` under a phantom `Code` tag, against a **context** (the type -a capability runs against, which supplies the values an implementation needs as its own fields), and +a method runs on, which supplies the values an implementation needs as its own fields), and returns the `Output` directly with no failure path. It is the owned-versus-borrowed variant of the pure computer, differing on the input axis alone. Like @@ -52,7 +52,7 @@ borrows the input: fn compute_ref(&self, _code: PhantomData, input: &Input) -> Self::Output; ``` -A context gains the capability by wiring `ComputerRefComponent` to a provider, and it dispatches on both +A context gains the operation by wiring `ComputerRefComponent` to a provider, and it dispatches on both the `Code` tag and the `Input` type. A provider that reads rather than consumes its input reaches for this variant; a [`Computer`](./computer.md) can also be bridged to it by the [`PromoteRef`](../../providers/handler/index.md) combinator, which supplies an owned input by diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md index 4a7b0612..58201d25 100644 --- a/docs/reference/components/handler/handler.md +++ b/docs/reference/components/handler/handler.md @@ -14,10 +14,10 @@ The general computation component: asynchronous, fallible, and error-aware. family can: a computation that runs asynchronously *and* can fail. A handler that calls a remote service must await the response and must report failures, so it lives where the family is both async and fallible. It transforms an `Input` into an `Output` under a phantom `Code` tag, returning a `Result` -against the **context's** abstract error type, where the context is the type a capability runs against +against the **context's** abstract error type, where the context is the type a method runs on that supplies the values an implementation needs as its own fields. -Every other handler component is a special case of `Handler` obtained by dropping one capability: drop +Every other handler component is a special case of `Handler` obtained by dropping one property: drop the failure path and it becomes an [`AsyncComputer`](./computer.md); drop the asynchrony and it becomes a [`TryComputer`](./try_computer.md); drop both and it becomes a [`Computer`](./computer.md). This is why generic pipeline code bounds against `Handler`: it is the one bound *every* member of the family can @@ -63,7 +63,7 @@ method is `async` and returns a `Result` against the context's error type: async fn handle(&self, _tag: PhantomData, input: Input) -> Result; ``` -A context gains the capability by wiring `HandlerComponent` to a provider. In practice most `Handler` +A context gains the operation by wiring `HandlerComponent` to a provider. In practice most `Handler` implementations are not written directly but produced by *promoting* a simpler provider: a function written as a [`#[cgp_computer]`](../../macros/cgp_computer.md) or [`#[cgp_producer]`](../../macros/cgp_producer.md) wires the promotion table so the same function answers `CanHandle` too, and the @@ -78,7 +78,7 @@ that its `handle_ref` method borrows the input as `&Input`. ## Examples A generic consumer that bounds its context by `CanHandle` accepts any wired computation, whatever its -underlying capabilities: +underlying properties: ```rust use core::marker::PhantomData; @@ -105,7 +105,8 @@ pipeline code targets `Handler`. The example is **parameter-targeted**: the comp ## When to use it **Bound generic pipeline code against `CanHandle` when it should accept any computation regardless of -which capabilities the provider actually uses.** Because every simpler member promotes up to a handler, +which of those properties the provider actually has.** Because every simpler member promotes up to +a handler, a consumer written against `Handler` is the most reusable, and it is the right target for I/O steps, request handlers, and composed pipelines. diff --git a/docs/reference/components/handler/handler_ref.md b/docs/reference/components/handler/handler_ref.md index 72351b0b..dabbe38f 100644 --- a/docs/reference/components/handler/handler_ref.md +++ b/docs/reference/components/handler/handler_ref.md @@ -12,8 +12,8 @@ its input. `HandlerRef` is a [`Handler`](./handler.md) that takes its input by reference. It is asynchronous and fallible like the general handler, so it awaits and may return the **context's** abstract error, but its -method receives `&Input` where `CanHandle` receives `Input`. The context is the type a capability runs -against, which supplies the values an implementation needs as its own fields. `HandlerRef` is the +method receives `&Input` where `CanHandle` receives `Input`. The context is the type a method runs +on, which supplies the values an implementation needs as its own fields. `HandlerRef` is the owned-versus-borrowed variant of the family's most general member, differing on the input axis alone, for an async-and-fallible computation that reads rather than consumes its argument. @@ -60,7 +60,7 @@ Its attributes: async fn handle_ref(&self, _tag: PhantomData, input: &Input) -> Result; ``` -A context gains the capability by wiring `HandlerRefComponent` to a provider, and it dispatches on both +A context gains the operation by wiring `HandlerRefComponent` to a provider, and it dispatches on both the `Code` tag and the `Input` type. Because the consumer trait supertraits `HasErrorType`, the context must also wire an error type. A [`Handler`](./handler.md) is bridged to `HandlerRef` by the [`PromoteRef`](../../providers/handler/index.md) combinator, which supplies an owned input by dereferencing diff --git a/docs/reference/components/handler/index.md b/docs/reference/components/handler/index.md index 508ba706..c034bed6 100644 --- a/docs/reference/components/handler/index.md +++ b/docs/reference/components/handler/index.md @@ -8,7 +8,7 @@ sidebar_position: 0 The handler family models a computation as a swappable component, so a pipeline step, an I/O call, or a type-level interpreter is wired and composed the same way as any other component. Every member transforms an `Input` into an `Output` under a phantom `Code` tag, against a **context**, the type a -capability runs against that supplies the values an implementation needs as its own fields. The members +method runs on that supplies the values an implementation needs as its own fields. The members differ along three axes: synchronous or async, infallible or fallible, and taking an input or not. This page maps the family; each member has its own page for the full detail. diff --git a/docs/reference/components/handler/producer.md b/docs/reference/components/handler/producer.md index 89ee7f02..153cf87b 100644 --- a/docs/reference/components/handler/producer.md +++ b/docs/reference/components/handler/producer.md @@ -12,7 +12,7 @@ The input-free member of the handler family: a synchronous, infallible source of `Producer` is for computations that take nothing to compute and simply yield a value. A handler that supplies a default configuration, a constant, or a value read entirely from the **context** has no `Input` to transform: it needs only the context and a phantom `Code` tag to know which value to produce. -The context is the type a capability runs against, which supplies the values an implementation needs as +The context is the type a method runs on, which supplies the values an implementation needs as its own fields. The rest of the [handler family](/docs/concepts/handlers) threads an `Input` through every method; `Producer` is the case where that input is absent. It is the simplest component in the family, synchronous and infallible, producing an `Output` directly. @@ -52,7 +52,7 @@ method takes only the context and a `Code` tag, with no `Input`: fn produce(&self, _code: PhantomData) -> Self::Output; ``` -A context gains the capability by wiring `ProducerComponent` to a provider. In everyday use the provider +A context gains the operation by wiring `ProducerComponent` to a provider. In everyday use the provider comes from [`#[cgp_producer]`](../../macros/cgp_producer.md), which turns a zero-argument function such as `fn magic_number() -> u64 { 42 }` into a `Producer` provider and wires `PromoteProducer` so the same function also answers the input-taking components. Because there is no input to dispatch on, the @@ -91,7 +91,7 @@ fn run(app: &App) -> u64 { ``` `MagicNumber` produces `42` from the `Code` tag alone, and `App` delegates `ProducerComponent` to it, -giving `App` the `CanProduce<(), Output = u64>` capability. The example is **parameter-targeted**: the +giving `App` the `CanProduce<(), Output = u64>` implementation. The example is **parameter-targeted**: the context decides which provider answers, and no value is operated on. In practice the provider is written with [`#[cgp_producer]`](../../macros/cgp_producer.md), which also wires the promotion so the same function answers the input-taking components while ignoring their input. diff --git a/docs/reference/components/handler/try_computer.md b/docs/reference/components/handler/try_computer.md index 1496b4af..746ec8f1 100644 --- a/docs/reference/components/handler/try_computer.md +++ b/docs/reference/components/handler/try_computer.md @@ -13,7 +13,7 @@ The fallible synchronous member of the handler family: a computer that can retur 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`](./computer.md) returns its `Output` directly, `TryComputer` returns `Result`, where the error is the **context's** shared abstract error type. The context is -the type a capability runs against, which supplies the values an implementation needs as its own fields. +the type a method runs on, which supplies the values an implementation needs as its own fields. This places `TryComputer` one step up from `Computer` on the fallibility axis of the [handler family](/docs/concepts/handlers), still synchronous but now able to fail, and one step below [`Handler`](./handler.md), which adds asynchrony on top. @@ -61,7 +61,7 @@ consumer method mirrors `compute` but returns a `Result`: fn try_compute(&self, _code: PhantomData, input: Input) -> Result; ``` -A context gains the capability by wiring `TryComputerComponent` to a provider. In everyday use the +A context gains the operation by wiring `TryComputerComponent` to a provider. In everyday use the provider comes from [`#[cgp_computer]`](../../macros/cgp_computer.md), which turns a function returning `Result` into a `TryComputer` provider and wires the promotion table so the same function also answers `CanCompute`, `CanHandle`, and the by-reference forms. diff --git a/docs/reference/components/handler/try_computer_ref.md b/docs/reference/components/handler/try_computer_ref.md index 4a1fcc63..3fe88f4d 100644 --- a/docs/reference/components/handler/try_computer_ref.md +++ b/docs/reference/components/handler/try_computer_ref.md @@ -13,7 +13,7 @@ that borrows its input. `TryComputerRef` is a [`TryComputer`](./try_computer.md) that takes its input by reference. A synchronous computation that can fail and only *reads* its argument fits it: its method receives `&Input` and returns `Result`, where the error is the **context's** abstract error type. The context is the -type a capability runs against, which supplies the values an implementation needs as its own fields. +type a method runs on, which supplies the values an implementation needs as its own fields. `TryComputerRef` is the owned-versus-borrowed variant of the fallible synchronous computer, differing on the input axis alone. @@ -58,7 +58,7 @@ method borrows the input and returns a `Result`: fn try_compute_ref(&self, _code: PhantomData, input: &Input) -> Result; ``` -A context gains the capability by wiring `TryComputerRefComponent` to a provider, and it dispatches on +A context gains the operation by wiring `TryComputerRefComponent` to a provider, and it dispatches on both the `Code` tag and the `Input` type. Because the consumer trait supertraits `HasErrorType`, the context must also wire an error type before it can call `try_compute_ref`. A provider that reads rather than consumes its input reaches for this variant; the owned-input [`TryComputer`](./try_computer.md) is diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index 40377d1e..32c6146d 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -10,8 +10,7 @@ Give a context one shared, abstract `Error` type, so fallible generic code never ## Overview `HasErrorType` lets generic CGP code fail without committing to a concrete error type. A provider that -may error has to produce *some* error, but it runs against a **context**, the type a capability runs -against that supplies the values an implementation needs, and it cannot know whether that context wants +may error has to produce *some* error, but it runs against a **context**, the type that implements the trait that supplies the values an implementation needs, and it cannot know whether that context wants `anyhow::Error`, `std::io::Error`, or an enum of its own. `HasErrorType` resolves this by giving the context one abstract `Self::Error` type that every fallible operation refers to. Generic code returns `Result`, and the concrete error is decided once, at wiring time, by whichever error @@ -108,12 +107,12 @@ Here [`#[use_type(HasErrorType.Error)]`](../attributes/use_type.md) adds `HasErr of `CanValidate` and rewrites the bare `Error` to `::Error`, so `validate` returns the context's shared error without spelling `Self::Error`. `App` wires its error type to `String`, which satisfies the `Debug` bound. `App` is an **environmental context**, a type that stands for the -application and carries its choices, and the capability targets that context rather than a value. +application and carries its choices, and the component targets that context rather than a value. ## When to use it **Reach for `HasErrorType` in any fallible component whose error type the context should choose.** It is -the foundation of CGP's error handling and is a supertrait of every other fallible capability, so a +the foundation of CGP's error handling and is a supertrait of every other fallible trait, so a component that returns a `Result` almost always wants the context's abstract error rather than a concrete one. Import it with [`#[use_type(HasErrorType.Error)]`](../attributes/use_type.md) rather than writing a `: HasErrorType` supertrait and a `Self::Error` path by hand. diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index 26720e47..ba466426 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -10,11 +10,11 @@ Hand out a borrow of the context's runtime value, so effectful code reaches it g ## Overview `HasRuntime` lets context-generic code obtain the runtime it runs against without naming a concrete one. -A runtime here is whatever object provides the capabilities an application needs at execution time, +A runtime here is whatever object provides the services an application needs at execution time, spawning tasks, sleeping, opening sockets, reading the clock, and different deployments want different runtimes: Tokio in production, a mock in tests, a single-threaded executor in a benchmark. Rather than -thread a concrete runtime type through every signature, the **context**, the type a capability runs -against that supplies the values an implementation needs as its own fields, stores one runtime value, +thread a concrete runtime type through every signature, the **context**, the type a method runs +on that supplies the values an implementation needs as its own fields, stores one runtime value, and `HasRuntime` is the getter that borrows it. `HasRuntime` answers *how to obtain the runtime value*; its companion @@ -106,7 +106,7 @@ where `HasRuntime` by reading its `runtime` field through `UseField`. `runtime_of` names neither `TokioRuntime` nor any field, so swapping `UseType` for `UseType` in a test context retargets it at the mock with no change to its body. `App` is an **environmental context**, and -the capability targets it. +the component targets it. ## When to use it @@ -117,7 +117,7 @@ runtime, and it makes the same task-running code reusable across a Tokio context test executor with only a wiring change. Reach for [`HasRuntimeType`](./has_runtime_type.md) alone when code names the runtime type but never -touches a value, which asks for exactly the capability it uses. Do not reach for `HasRuntime` when a +touches a value, which asks for exactly the trait it uses. Do not reach for `HasRuntime` when a value the provider needs is not really the runtime but an ordinary context field, where an [`#[implicit]`](../attributes/implicit.md) argument is simpler. diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md index 661f9cf1..1ac7e7e9 100644 --- a/docs/reference/components/has_runtime_type.md +++ b/docs/reference/components/has_runtime_type.md @@ -10,9 +10,9 @@ Declare the abstract runtime *type* a context runs against, chosen per context t ## Overview `HasRuntimeType` lets context-generic code name the runtime type a context uses without committing to a -concrete one. A runtime is whatever object supplies the capabilities an application needs at execution +concrete one. A runtime is whatever object supplies the services an application needs at execution time, and different deployments want different runtimes: Tokio in production, a mock in tests, an -executor in a benchmark. `HasRuntimeType` gives the **context**, the type a capability runs against that +executor in a benchmark. `HasRuntimeType` gives the **context**, the type that implements the trait that supplies the values an implementation needs as its own fields, an abstract associated `Runtime` type, resolved to a concrete one at wiring time. @@ -21,7 +21,7 @@ are independent. `HasRuntimeType` answers *what the runtime type is*, while its [`HasRuntime`](./has_runtime.md) answers *how to obtain the runtime value* from a borrow of the context. Some code is generic only over the runtime type: it names types the runtime exposes but never touches a runtime value, and it needs `HasRuntimeType` alone. Keeping the type separate means such a bound asks -for exactly the capability it uses. +for exactly the trait it uses. ## Definition @@ -89,12 +89,12 @@ where `App` resolves `HasRuntimeType` with `Runtime = TokioRuntime` through `UseType`, so `RuntimeOf` is `TokioRuntime`. `describe` names only the runtime type and never a runtime value, which is exactly the -case `HasRuntimeType` serves alone. `App` is an **environmental context**, and the capability targets it. +case `HasRuntimeType` serves alone. `App` is an **environmental context**, and the component targets it. ## When to use it **Reach for `HasRuntimeType` when code names the runtime type but never touches a runtime value.** That -is the narrower of the two runtime capabilities, and asking for it alone keeps a bound honest about what +is the narrower of the two runtime components, and asking for it alone keeps a bound honest about what it uses. It is also the type half a context must wire before it can satisfy [`HasRuntime`](./has_runtime.md), because the getter borrows a value of this type. diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index b8e65b05..4caed4dd 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -13,8 +13,7 @@ CGP's single built-in abstract-type component: a tag-indexed type a context reso concrete one. An abstract type in CGP is a [trait](https://doc.rust-lang.org/book/ch10-02-traits.html) with a single [associated type](https://doc.rust-lang.org/reference/items/associated-items.html), and `HasType` -is the foundational, tag-indexed instance of that pattern. A **context**, the type a capability runs -against, can carry many distinct abstract types, one per `Tag`, and resolve each to a concrete type +is the foundational, tag-indexed instance of that pattern. A **context**, the type that implements the trait, can carry many distinct abstract types, one per `Tag`, and resolve each to a concrete type through wiring. Generic code names `Self::Type` (or the alias `TypeOf`), the concrete type stays hidden behind the tag, and any context that wires the tag to a type satisfies the bound. diff --git a/docs/reference/components/index.md b/docs/reference/components/index.md index 5ef6776e..76a4bf22 100644 --- a/docs/reference/components/index.md +++ b/docs/reference/components/index.md @@ -5,16 +5,16 @@ sidebar_position: 0 # Components -A component is one capability, defined once, that a context can wire to any of several +A component is one trait, defined once, that a context can wire to any of several implementations. The constructs on the other pages of this reference are the tools you use to *build* your own components; the pages in this section document the components CGP already ships. Each is a consumer trait you call, a provider trait an implementation targets, and a wiring key a context delegates, exactly like a component you define yourself, so you wire a built-in error type or runtime with the same [`delegate_components!`](../macros/delegate_components.md) table as everything else. -A context is the type a capability runs against, which supplies whatever values an implementation needs +A context is the type a method runs on, which supplies whatever values an implementation needs as its own fields. You wire these components onto a context and call them the way you call any CGP -capability. This page groups them by the job they do, in roughly the order most CGP code reaches for +trait. This page groups them by the job they do, in roughly the order most CGP code reaches for them. If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here. ## Handle errors diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index 302c7bbe..069ccdf3 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -11,7 +11,7 @@ Run a task named at the type level to a `Result<(), Error>`, with the behavior c `CanRun` gives a context a uniform way to *execute a unit of work* selected at the type level. The unit of work is identified by a `Code` type parameter, a phantom tag rather than a value, so a single -**context**, the type a capability runs against that supplies the values an implementation needs as its +**context**, the type a method runs on that supplies the values an implementation needs as its own fields, can host many distinct tasks, one per `Code`, and dispatch each to its own provider. Running a task here means invoking the provider wired for that `Code` and awaiting an asynchronous `Result<(), Error>`: the task either completes or produces the context's abstract error. The component @@ -54,7 +54,7 @@ Its attributes: async fn run(&self, _code: PhantomData) -> Result<(), Error>; ``` -A context gains the capability by wiring `RunnerComponent` to a provider. Because the component dispatches +A context gains the operation by wiring `RunnerComponent` to a provider. Because the component dispatches on `Code`, the idiomatic way a context hosts several tasks is the `open` statement, routing each task tag to its own provider: diff --git a/docs/reference/components/send_runner.md b/docs/reference/components/send_runner.md index f62fd777..ea378437 100644 --- a/docs/reference/components/send_runner.md +++ b/docs/reference/components/send_runner.md @@ -12,7 +12,7 @@ The runner variant whose returned future is `Send`, for work that must cross a t `CanSendRun` is [`CanRun`](./runner.md) with one added guarantee: the future its method returns is [`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html), so it can be handed to a spawner such as `tokio::spawn`. It exists to solve a specific Rust limitation. A generic `async fn` over abstract -**context** types (the context being the type a capability runs against that supplies the values an +**context** types (the context being the type a method runs on that supplies the values an implementation needs as its own fields) cannot promise its future is `Send` without annotating `Send` bounds on every abstract type in scope, and those bounds pollute every interface. `CanSendRun` sidesteps that by returning an explicit @@ -59,7 +59,7 @@ return, an explicit `Send` future rather than a plain `async fn`: fn send_run(&self, _code: PhantomData) -> impl Future> + Send; ``` -A context gains the capability by wiring `SendRunnerComponent`, or, in the common case, by supplying a +A context gains the operation by wiring `SendRunnerComponent`, or, in the common case, by supplying a proxy impl on the concrete context that forwards to its own `run`. The proxy discharges the `Send` bound: diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index a4938d67..71604b89 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -104,7 +104,7 @@ constructors, and an extractor. Worked examples of each half are on the ## When to use it Use `CgpData` when generic code needs both a type's structure and its incremental operations. For -reading individual values from a context (the type a capability runs against, which supplies values +reading individual values from a context (the type a method runs on, which supplies values as fields), [`#[derive(HasField)]`](./derive_has_field.md) is sufficient. The full derive supports these uses: diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 4c39e302..c4c24ae4 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -173,7 +173,7 @@ Choose the field-access syntax according to what the implementation needs: - **[`#[implicit]`](../attributes/implicit.md)**: use by default to read a field from the implementation's own context as a parameter, without declaring a getter trait. - **[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md)**: use when the read should be a named - capability, the field belongs to another type, or the getter needs a type inferred from the field. + trait, the field belongs to another type, or the getter needs a type inferred from the field. - **A hand-written `HasField` bound**: use when the higher-level forms do not fit. Add `Value = T` to constrain the field type. - **[`#[derive(HasFields)]`](./derive_has_fields.md)**: use for processing the whole structure, such diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 2f4b6668..eed93955 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -30,7 +30,7 @@ wrote it, this page says so and shows the raw form instead. knowing which one you are looking at decides whether there is a cause in the message to find at all. CGP wiring is lazy: [`delegate_components!`](./macros/delegate_components.md) records that a **context** -— the type the capability runs against, which supplies the values it needs as its fields — uses some +— the type the method runs on, which supplies the values it needs as its fields — uses some provider, and nothing checks that the provider's own requirements hold. That check happens later, and *how* it happens decides what you see. @@ -191,7 +191,7 @@ cannot, because no field is implemented. ### When the missing bound is an ordinary Rust trait -A provider's dependency may be a plain Rust trait rather than a CGP capability — `Scalar: Eq`, +A provider's dependency may be a plain Rust trait rather than a CGP trait — `Scalar: Eq`, `Item: Ord` — unmet by the type the context wired. Here the tool deliberately keeps rustc's own headline, because it was already the clearest statement, and tidies only the frames beneath it: @@ -552,10 +552,10 @@ A group with one cause: the body of a [`#[cgp_fn]`](./macros/cgp_fn.md) or anything the body calls must be *declared* as a bound on it. Rust's raw errors here are unhelpful because they talk about that generated parameter; the tool names the missing declaration instead. -**A capability used without `#[uses]`:** +**A trait used without `#[uses]`:** ```text -error[E0599]: [CGP-E012] the capability `GetCount` is used but not declared as a dependency +error[E0599]: [CGP-E012] the trait `GetCount` is used but not declared as a dependency | 44 | format!("{} ({})", self.get_name(), self.get_count()) | ^^^^^^^^^ @@ -617,10 +617,10 @@ code in the **root-cause tree** labels one link in the chain. | `CGP-E006` | More than one namespace joined on one context | | `CGP-E007` | An `open` redirect colliding with an explicit entry | | `CGP-E008` | The same key redirected twice | -| `CGP-E009` | A non-component trait — a wrapper, or a `#[cgp_fn]` capability — blocked by a CGP dependency | +| `CGP-E009` | A non-component trait — a wrapper, or a `#[cgp_fn]` blanket trait — blocked by a CGP dependency | | `CGP-E010` | The wiring recurses without terminating | | `CGP-E011` | An orphan-rule namespace registration | -| `CGP-E012` | A capability used but not declared with `#[uses]` | +| `CGP-E012` | A trait used but not declared with `#[uses]` | | `CGP-E013` | A consumer trait named in a provider impl header | | `CGP-E014` | `#[cgp_impl]` applied to a trait that is not a component | | `CGP-E015` | A consumer trait named in an inner-provider bound | diff --git a/docs/reference/index.md b/docs/reference/index.md index b460b243..3385d5c3 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -26,12 +26,12 @@ these. | [`#[cgp_impl]`](./macros/cgp_impl.md) | Writes one of those implementations | | [`delegate_components!`](./macros/delegate_components.md) | Chooses which implementation a given type uses | | [`check_components!`](./macros/check_components.md) | Verifies that choice at compile time | -| [`#[cgp_fn]`](./macros/cgp_fn.md) | Defines a capability that only ever needs one implementation | +| [`#[cgp_fn]`](./macros/cgp_fn.md) | Defines a trait that only ever needs one implementation | | [`#[implicit]`](./attributes/implicit.md) | Reads a value out of the context as if it were a function argument | The first four are the full component cycle: define, implement, wire, verify. The last two are how most code avoids needing that cycle at all — reach for them first, and climb to a full component when -a capability genuinely needs a second implementation. +a trait genuinely needs a second implementation. ## By what you are trying to do @@ -39,13 +39,13 @@ The rest of the reference is grouped by the job a construct does rather than by is. If you know which *file* you want rather than which job, the sidebar groups the same pages by kind — macros, attributes, derives, and so on. -### Define a capability, and implement it +### Define a trait, and implement it [`#[cgp_component]`](./macros/cgp_component.md) is the foundational macro, turning one trait into the consumer trait callers use and the provider trait implementations target. A provider is then written with [`#[cgp_impl]`](./macros/cgp_impl.md), which keeps `self` and the consumer method signatures; [`#[cgp_provider]`](./macros/cgp_provider.md) is the lower-level form underneath it, which you will -read in generated code more often than you write. When a capability needs only one implementation and +read in generated code more often than you write. When a trait needs only one implementation and no wiring at all, [`#[cgp_fn]`](./macros/cgp_fn.md) builds it straight from a function, and [`#[blanket_trait]`](./macros/blanket_trait.md) does the same from a trait with default methods. [`#[async_trait]`](./macros/async_trait.md) is how a CGP trait declares an `async fn`. @@ -85,7 +85,7 @@ chosen by wiring, through [`UseField` and its siblings](./providers/use_field.md ### Declare what an implementation needs These attributes state what an implementation needs, and they divide by whether the requirement stays -private to it. [`#[uses]`](./attributes/uses.md) imports the capabilities the body depends on and +private to it. [`#[uses]`](./attributes/uses.md) imports the traits the body depends on and [`#[use_provider]`](./attributes/use_provider.md) does the same for an inner provider in a higher-order provider — both landing on the implementation alone, so a caller never sees them. Where a requirement should instead be part of what the trait promises, [`#[extend]`](./attributes/extend.md) adds it as a diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 61e38f06..75885764 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -33,7 +33,8 @@ The trait reads as async code, and the declaration the compiler sees is the lint **The rewrite is a plain desugaring, not a framework.** Unlike the widely-used `async-trait` crate, nothing here boxes the future or allocates: it is return-position `impl Trait` in traits, so the future is exactly the one the body produces and the call costs what a hand-written future-returning method costs. That is why the -macro is used throughout CGP wherever a capability is asynchronous: it is simply how an async method is +macro is used throughout CGP wherever a trait's methods are asynchronous: it is simply how an async +method is spelled. One thing it does *not* do is add a `Send` bound, and that omission has consequences the moment a future is @@ -143,7 +144,7 @@ The decisions worth making are around it rather than about it. trait definitions. Harmless, but it suggests a misunderstanding of where the lint comes from. - **Use the `Send`-recovery pattern when a future is spawned**, not a different macro. No attribute can add the bound, for the reason in the [Common Mistakes](#common-mistakes). -- **Consider whether the capability needs to be async at all.** The [handler family](./cgp_computer.md) has +- **Consider whether the trait needs to be async at all.** The [handler family](./cgp_computer.md) has synchronous members, and the [promotion combinators](../providers/handler/index.md) lift a synchronous provider into an async one where a caller needs it. So a computation that does no I/O is better declared synchronous and promoted than declared async out of habit. diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 39c08055..289d761d 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -13,7 +13,7 @@ The pattern CGP is built on is an **extension trait**: a trait with a clean inte [blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) carries the real requirements in its `where` clause. A trait declared `FooBar: Foo + Bar` with a default `foo_bar` method exposes only `foo_bar` to callers, while the `Foo + Bar` requirements live on the impl. So any type -satisfying them gains the capability, and nobody calling `foo_bar` has to know or repeat what it needed. +satisfying them gains the trait, and nobody calling `foo_bar` has to know or repeat what it needed. That is worth doing rather than writing a generic function, because a function's `where` clause propagates: every generic caller repeats it, and so does every caller of *those*. Hiding the requirement on an impl stops @@ -34,7 +34,7 @@ pub trait FooBar: Foo + Bar { ``` **This is not a CGP component.** There is no consumer/provider split, no component marker, and no wiring: -just an ordinary Rust trait and an ordinary blanket impl. It is the tool for a capability with exactly one +just an ordinary Rust trait and an ordinary blanket impl. It is the tool for a trait with exactly one definition, where you want extension-trait ergonomics without committing to the component machinery. When a second implementation becomes necessary, the trait can be promoted to a [`#[cgp_component]`](./cgp_component.md). @@ -61,8 +61,8 @@ pub trait FooBar: Foo + Bar { } ``` -The attribute takes an optional identifier naming the generic **context** type (the type the capability runs -against) in the generated impl. Omitted, it is the reserved `__Context__`, chosen so it cannot collide with +The attribute takes an optional identifier naming the generic **context** type (the type the method runs +on) in the generated impl. Omitted, it is the reserved `__Context__`, chosen so it cannot collide with one of your own type parameters: ```rust @@ -146,14 +146,14 @@ Any type that is `Foo + Bar` is now `FooBar`, and a signature can say so in one ## When to use it -**Use `#[blanket_trait]` when a capability has one definition and its dependencies are other traits.** +**Use `#[blanket_trait]` when a trait has one definition and its dependencies are other traits.** That last clause is the real discriminator, separating this macro from its closest neighbour. - **[`#[cgp_fn]`](./cgp_fn.md) when the dependencies are context *fields*.** Both macros produce a - single-implementation capability with a blanket impl and no wiring, so the choice is about the input. + single-implementation trait with a blanket impl and no wiring, so the choice is about the input. `#[cgp_fn]` derives the trait and body from a function, reading values through [`#[implicit]`](../attributes/implicit.md) arguments; `#[blanket_trait]` takes a trait with supertraits and - default bodies. Values point to `#[cgp_fn]`, capabilities point here. + default bodies. Values point to `#[cgp_fn]`, trait dependencies point here. - **[`#[cgp_component]`](./cgp_component.md) when a second implementation is needed.** A blanket impl covers every type satisfying its bounds, which leaves nowhere for an alternative to live. Promoting later is cheap (the trait keeps its name and method), so starting here costs nothing if that changes. diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index ae62d454..2c20f6e3 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -29,7 +29,7 @@ trait, its per-type impls, and a derive on the enum. **Its value is narrower than it looks, and worth naming precisely.** It fits when the per-variant behaviour is *exactly* "call the same trait method on the payload". The moment a variant needs different handling, or -the dispatch should be chosen by a **context** (the type the capability runs against) rather than fixed on +the dispatch should be chosen by a **context** (the type the method runs on) rather than fixed on the enum, use the combinators directly. This is the convenient front end to [dispatching](../providers/dispatch/index.md), not a replacement for it. diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 1acd2466..d5dc940e 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -11,7 +11,7 @@ Define a getter as a blanket impl over `HasField`, keyed by the method name. `#[cgp_auto_getter]` publishes a context field as a named, reusable accessor. You write a trait of getter methods, and the macro implements it for every **context** that happens to carry fields of the matching -names. The context is the type the capability runs against, and it supplies the values it needs as its +names. The context is the type the method runs on, and it supplies the values it needs as its own fields. For example: ```rust @@ -33,7 +33,7 @@ able to state the same thing as `fn name(&self) -> &str;` is the point. **Use it sparingly.** For the ordinary case, a provider reading a field of its own context, an [`#[implicit]`](../attributes/implicit.md) argument does the same job with no trait to declare, using the same field access and the same conversion rules, so a getter trait declared only to read a field adds a -name and gives nothing back. A getter trait *does* give you one thing: a capability other code can depend on by name. +name and gives nothing back. A getter trait *does* give you one thing: an accessor other code can depend on by name. The cases where that matters are in [When to use it](#when-to-use-it). @@ -216,7 +216,7 @@ A getter trait is worth declaring in a few cases an implicit argument cannot rea - **The field lives on another type.** An implicit argument reads only from `self`, so a value held by a request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type, as in `Request: HasBasicAuthHeader`. There is no `self` field to read. -- **The accessor must be a named capability.** When other code depends on "this context can tell you its +- **The accessor must be a named trait.** When other code depends on "this context can tell you its name" rather than on a field, that dependency needs a trait to point at, importable with [`#[uses]`](../attributes/uses.md) or usable as a supertrait via [`#[extend]`](../attributes/extend.md). - **The getter carries a type inferred from the field.** The associated-type form above keeps the type diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index ad6ee334..cb3257ba 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -10,20 +10,20 @@ target, and the key that wires them together. ## Overview -You can apply `#[cgp_component]` to any Rust trait definition to give that trait the full set of -CGP's capabilities. Applying it takes nothing away. The trait you wrote keeps working exactly as it +You can apply `#[cgp_component]` to any Rust trait definition to make that trait wireable, with +every implementation chosen per context. Applying it takes nothing away. The trait you wrote keeps working exactly as it did, now under the name CGP calls the **consumer trait**, and every call site that already uses it keeps compiling unchanged. The macro adds a matching **provider trait** for implementations to target, -a small marker type called the **component** that names the capability for wiring, and a pair of +a small marker type called the **component** that names the trait for wiring, and a pair of [**blanket implementations**](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) that connect them without requiring you to write anything. -`#[cgp_component]` makes it possible to define several overlapping implementations of one capability +`#[cgp_component]` makes it possible to define several overlapping implementations of one trait at once. An ordinary Rust trait does not allow this. A [trait](https://doc.rust-lang.org/book/ch10-02-traits.html) can have only one implementation per type, a rule called [coherence](/docs/concepts/coherence). That rule is usually the right one, because it lets the compiler resolve a `where T: Display` bound without anyone naming which implementation -applies. But it also means a capability with several plausible implementations cannot hold the +applies. But it also means a trait with several plausible implementations cannot hold the alternatives. A type can send real email or record it for a test, but never both at once. Switching between the two means editing the impl itself rather than choosing between them at the point of use. @@ -35,12 +35,12 @@ implementation no longer target the same trait. kept exactly as you wrote it. - An implementation targets the **provider trait** instead. It repeats the same methods with `Self` moved into an explicit type parameter. So you write an implementation for a small named type of its - own, rather than for the type the capability is about. + own, rather than for the type the operation acts on. Moving `Self` into a parameter lets more than one implementation coexist, because each one now targets its own small type instead of the single `Self` slot every plain trait has. A **provider** is one of those targets: a zero-sized type such as `RectangleArea` without data of its own that exists only -to name one implementation. The type the capability runs against is called the **context**. It +to name one implementation. The type the methods run on is called the **context**. It supplies whatever values an implementation needs as its own fields, and it picks the provider it wants through [`delegate_components!`](./delegate_components.md). The generated blanket implementations then route a call on the consumer trait through to that choice automatically. This costs nothing at @@ -48,8 +48,8 @@ runtime. Wiring fixes the provider once, at compile time, and the compiler turns direct, statically-dispatched call, exactly as if you had written the implementation yourself. The macro's remaining output is the **component** itself, a marker type such as -`AreaCalculatorComponent` that names the capability and is the key `delegate_components!` wires -against. You see it in every wiring entry and in most compiler errors that involve this capability, so +`AreaCalculatorComponent` that names the trait and is the key `delegate_components!` wires +against. You see it in every wiring entry and in most compiler errors that involve this trait, so learn to recognize it, even though you never write its definition yourself. ## Usage @@ -125,7 +125,7 @@ so the macro rejects it with *Type equality constraints cannot be used in compon Every other form of the attribute works on a component exactly as it does elsewhere. For a supertrait without an associated type to import, use `#[extend(...)]` in preference to native -`: Supertrait` syntax. `#[extend(HasName)]` reads as importing a capability, whereas +`: Supertrait` syntax. `#[extend(HasName)]` reads as importing a trait, whereas `pub trait CanGreet: HasName` reads as inheritance, which a CGP supertrait is not. An associated type the trait declares *itself* is not imported and stays written as `Self::Output`. @@ -181,13 +181,13 @@ does, and nothing else in the program changes. ## When to use it -Use `#[cgp_component]` when a capability needs **more than one implementation, and the +Use `#[cgp_component]` when a trait needs **more than one implementation, and the choice belongs to the type using it.** The macro exists for that case, and it has a cost: a component is a trait, a second trait, a marker type, and a line of wiring per type. Prefer something simpler when you can. -- **One implementation, ever.** Use [`#[cgp_fn]`](./cgp_fn.md) instead. It builds the capability +- **One implementation, ever.** Use [`#[cgp_fn]`](./cgp_fn.md) instead. It builds the trait straight from a function and does not need wiring. If a second implementation ever arrives, you promote it to a component and its call sites keep working unchanged. That makes it the right starting point rather than a lesser one. @@ -197,7 +197,7 @@ Prefer something simpler when you can. - **A closed set of variants with fixed operations.** An `enum` and a `match` are clearer than any machinery. -One more distinction matters. A capability may need several implementations while each individual +One more distinction matters. A trait may need several implementations while each individual implementation serves exactly one type. In that case you can implement the consumer trait directly on each concrete type, as you would any Rust trait, and skip providers entirely. Named providers become worth their cost once a second type wants the *same* implementation, or once an implementation should @@ -259,7 +259,7 @@ pub trait AreaCalculator: `IsProviderFor` *replaces* the supertrait list rather than joining it. Any supertrait the consumer trait had, whether written natively or added by `#[extend]` or `#[use_type]`, becomes a `where` predicate on the context instead. This follows from the `Self`-to-`Context` move: a supertrait -constrains the type the capability is about, and on the provider side that type is the context +constrains the type the operation acts on, and on the provider side that type is the context parameter. So `#[extend(HasName)]` on a `CanGreet` component produces: ```rust diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index e7fc3dcb..bd57ef2c 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -11,7 +11,7 @@ Define a `Computer` provider from a plain function. CGP models computation as a family of components varying along three axes: synchronous or async, fallible or not, taking an input or not. A provider in that family is a struct with one or more impls threading a -**context** (the type the capability runs against, which supplies the values it needs as its fields), a +**context** (the type the method runs on, which supplies the values it needs as its fields), a phantom `Code` tag, and an `Input`. Written by hand for a computation as small as "add two numbers", that is far more code than the task needs. @@ -31,7 +31,7 @@ that makes the *same function* answer the whole family. That wiring is the part implementing any of them. That last property is the whole reason for the macro. The family exists so a provider can declare exactly -the capabilities it has, and the [promotion combinators](../providers/handler/index.md) exist so a +the properties it has, and the [promotion combinators](../providers/handler/index.md) exist so a simpler provider can stand in where a more capable one is expected: an infallible computation is a fallible one that never fails, a synchronous one is an async one that never awaits. `#[cgp_computer]` picks the narrowest @@ -146,17 +146,17 @@ exists for, and it is the simplest way into the handler family. - **Write the provider by hand with [`#[cgp_impl]`](./cgp_impl.md) when the body needs the context.** This is the real boundary. A `#[cgp_computer]` function has no receiver and no access to the context, so it can only transform its inputs. The moment the computation needs a field, an abstract type, or another - capability, it wants a provider impl of `Computer` or `Handler` written with `#[cgp_impl]`, where `self` is + trait, it wants a provider impl of `Computer` or `Handler` written with `#[cgp_impl]`, where `self` is the context and [`#[implicit]`](../attributes/implicit.md) and [`#[uses]`](../attributes/uses.md) work normally. -- **Use [`#[cgp_fn]`](./cgp_fn.md) when you want a capability on the context, not a pipeline step.** +- **Use [`#[cgp_fn]`](./cgp_fn.md) when you want a method on the context, not a pipeline step.** The two look similar and differ in what they produce: `#[cgp_fn]` gives a trait a context implements, called as `self.thing()`; `#[cgp_computer]` gives a *provider* that gets wired into a handler component and composed with combinators. If you are not building a pipeline, use `#[cgp_fn]` instead. - **Wire the [handler combinators](../providers/handler/index.md) directly for composition.** The macro produces one step; `PipeHandlers` and friends chain them. -One thing not to do is use the handler family just because a capability happens to transform a value. The +One thing not to do is use the handler family just because an operation happens to transform a value. The family is worth using when computations are *composed*: piped, dispatched on a `Code` tag, promoted between variants. A single transform with one caller is a method. @@ -278,7 +278,7 @@ short-circuits. - [Handler combinators](../providers/handler/index.md) — the `Promote*` bundles this wires, plus `PipeHandlers` and `ComposeHandlers` for composing steps. - [`#[cgp_impl]`](./cgp_impl.md) — for a handler provider that needs its context. -- [`#[cgp_fn]`](./cgp_fn.md) — for a capability on the context rather than a pipeline step. +- [`#[cgp_fn]`](./cgp_fn.md) — for a method on the context rather than a pipeline step. - [`#[cgp_new_provider]`](./cgp_provider.md) — what the generated impl is emitted through. - [`#[cgp_auto_dispatch]`](./cgp_auto_dispatch.md) — generates per-variant computers from a trait. diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index ce5b6589..d08b2fa5 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -5,13 +5,13 @@ sidebar_position: 3 # `#[cgp_fn]` -Define a single-implementation capability as a blanket-impl trait, straight from a function. +Define a trait with a single blanket implementation, straight from a function. ## Overview `#[cgp_fn]` is the simplest CGP construct that does anything useful. You write a plain function and -mark the values it needs from the **context**. The context is the type the capability runs against, -and it supplies those values as its own fields. The macro turns the function into a capability that +mark the values it needs from the **context**. The context is the type the method runs on, +and it supplies those values as its own fields. The macro turns the function into a trait that every type with those fields gets automatically: ```rust @@ -29,11 +29,12 @@ covering every context that satisfies the field requirements. The macro makes one tradeoff, and you should know it. A [`#[cgp_component]`](./cgp_component.md) supports many interchangeable implementations, one chosen per context, and this costs extra boilerplate. `#[cgp_fn]` supports exactly one implementation, the function -body, and costs nothing. Most capabilities have one natural definition, so `#[cgp_fn]` is the better +body, and costs nothing. Most traits have one natural definition, so `#[cgp_fn]` is the better choice for them and the recommended place to start, rather than a lesser form of the real thing. It is also the easiest introduction to CGP, because nothing in it is unfamiliar. A reader who -understands functions and arguments can write a working capability without first meeting trait bounds, +understands functions and arguments can write a working context-generic function without first +meeting trait bounds, blanket implementations, or type-level field names. An [`#[implicit]`](../attributes/implicit.md) parameter hides all of that and looks like an ordinary parameter. @@ -86,7 +87,7 @@ most of what you need to learn about the macro. | [`#[extend_where(...)]`](../attributes/extend_where.md) | Both the trait and the impl | By default, generics land on both the trait and the impl, and the `where` clause lands on the impl -alone. This hides a capability's requirements from its callers: a caller bounds on the clean trait, +alone. This hides a trait's requirements from its callers: a caller bounds on the clean trait, and the constraints the body actually needs stay one level down on the implementation: ```rust @@ -119,7 +120,7 @@ The `Describe` trait is not generic. A context becomes eligible purely by carryi some `Display` type, and the compiler resolves the type from that field. The type is then concealed rather than named, so it cannot appear in this function's own signature, -and two capabilities cannot agree on it. The [`#[impl_generics]`](../attributes/impl_generics.md) +and two traits cannot agree on it. The [`#[impl_generics]`](../attributes/impl_generics.md) page says when to promote such a type to an abstract type instead. ### Companion attributes @@ -127,12 +128,12 @@ page says when to promote such a type to an abstract type instead. Several attributes shape what the macro generates, and together they are how a `#[cgp_fn]` states what it depends on. -- [`#[uses(...)]`](../attributes/uses.md) imports the capabilities the body calls on `self`, reading +- [`#[uses(...)]`](../attributes/uses.md) imports the traits the body calls on `self`, reading like a `use` statement rather than a hand-written `where Self: Trait` bound. It accepts ordinary Rust traits as readily as CGP ones. - [`#[use_type(Trait.Type)]`](../attributes/use_type.md) imports an abstract type so the signature can name it bare, and adds the owning trait as a supertrait. -- [`#[extend(...)]`](../attributes/extend.md) adds a capability supertrait to the generated trait. Here +- [`#[extend(...)]`](../attributes/extend.md) adds a method supertrait to the generated trait. Here it is the *only* way to add one, since a `where` clause in a `#[cgp_fn]` is an implementation detail rather than part of the interface. - [`#[extend_where(...)]`](../attributes/extend_where.md) puts a predicate on the generated trait's own @@ -146,7 +147,7 @@ it depends on. ## Examples -A capability, another capability built on it, and a context that gets both without wiring anything: +A trait, another trait built on it, and a context that gets both without wiring anything: ```rust use cgp::prelude::*; @@ -176,30 +177,30 @@ pub fn report(rect: &Rectangle) { ``` `scaled_rectangle_area` calls `self.rectangle_area()` because `#[uses(RectangleArea)]` declared the -dependency. It does not know or care how that capability is implemented. `Rectangle` derives +dependency. It does not know or care how that trait is implemented. `Rectangle` derives [`HasField`](../derives/derive_has_field.md) and happens to carry the three fields the two functions read, and that is its entire qualification. This program does not use `delegate_components!` anywhere, and adding one would change nothing. ## When to use it -**Use `#[cgp_fn]` first.** When a capability has one natural definition, this is the form to write. +**Use `#[cgp_fn]` first.** When a trait has one natural definition, this is the form to write. Starting here costs nothing if that changes later, because the trait keeps its name and its method, so promoting it to a [`#[cgp_component]`](./cgp_component.md) leaves every call site untouched. At that point you add the component, a named provider, and a line of wiring per context. Use something else in these cases: -- **The capability needs a second implementation, chosen per context.** +- **The trait needs a second implementation, chosen per context.** [`#[cgp_component]`](./cgp_component.md) is for that, and `#[cgp_fn]` cannot provide it: its blanket impl already covers every context, so an alternative cannot coexist with it. - **The dependencies are traits rather than fields.** [`#[blanket_trait]`](./blanket_trait.md) builds - the same kind of single-implementation, no-wiring capability from a trait with supertraits and - default method bodies. Use it when the body needs other capabilities, and use `#[cgp_fn]` when it + the same kind of single-implementation, no-wiring trait from a trait with supertraits and + default method bodies. Use it when the body needs other traits, and use `#[cgp_fn]` when it needs values. - **A generic must vary per call.** A generic parameter here goes on the trait rather than the method, so whatever satisfies the bounds for a given context fixes it, rather than each call site choosing - it. A capability that needs a per-call type parameter needs a hand-written blanket impl or a + it. A trait that needs a per-call type parameter needs a hand-written blanket impl or a component instead. Make one decision inside the macro deliberately rather than by default: **where a type the body needs @@ -207,9 +208,9 @@ should live.** Start with [`#[impl_generics]`](../attributes/impl_generics.md) w ever flows through implicit arguments. It is shorter, does not need wiring, and reads as "this works with any `database` field of a compatible type". Move up to an [abstract type](./cgp_type.md) when the type must appear in the -capability's own signature, or when two capabilities must agree that they mean the same one. Avoid a +trait's own signature, or when two traits must agree that they mean the same one. Avoid a plain generic parameter on the function in both cases: it lands on the trait and makes every caller, -and every intermediate capability built on it, declare the parameter and repeat its bounds whether +and every intermediate trait built on it, declare the parameter and repeat its bounds whether they touch it or not. ## Under the hood @@ -329,7 +330,7 @@ error: a `&mut` implicit argument must be the only implicit argument, since its borrow of the context conflicts with reading any other field ``` -**An `#[impl_generics]` parameter cannot appear in the capability's own signature.** Only the generated +**An `#[impl_generics]` parameter cannot appear in the trait's own signature.** Only the generated impl declares it, so a return type or an explicit parameter that names it leaves it unresolved in the trait. A bare `Db` reports `E0425` and a qualified path such as `Db::Row` reports `E0433`, both under the headline *cannot find type `Db` in this scope*, so search for both codes. Either the type belongs @@ -346,7 +347,7 @@ parameter. The [`#[impl_generics]`](../attributes/impl_generics.md) page shows b - [`#[blanket_trait]`](./blanket_trait.md) — the same idea built from a trait rather than a function. - [`#[cgp_impl]`](./cgp_impl.md) — shares the `#[implicit]` mechanism, for writing a component's provider. - [`#[derive(HasField)]`](../derives/derive_has_field.md) — what a context derives to satisfy the bounds. -- [`#[async_trait]`](./async_trait.md) — how an `async fn` capability is declared. +- [`#[async_trait]`](./async_trait.md) — how an `async fn` trait method is declared. The ideas behind it: diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 766190f4..29350235 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -15,7 +15,7 @@ always, and it has one hard limitation: a context that stores the value under a getter at all. `#[cgp_getter]` removes that coupling by making the getter a real component. The **context** is the -type the capability runs against, and it supplies the values it needs as its own fields. It then says +type the method runs on, and it supplies the values it needs as its own fields. It then says in its wiring which field the getter should read: ```rust @@ -157,12 +157,12 @@ the last resort, and the ordering is worth keeping whole: 1. **An [`#[implicit]`](../attributes/implicit.md) argument** for a provider reading a field of its own context. No trait, no wiring. This covers most reads. 2. **[`#[cgp_auto_getter]`](./cgp_auto_getter.md)** when the accessor has to exist as a *named - capability* other code depends on, when the field lives on another type, or when the getter carries a + trait* other code depends on, when the field lives on another type, or when the getter carries a type inferred from the field. One blanket impl, still no wiring. 3. **`#[cgp_getter]`** only when a context must control *how the getter is satisfied*. That third condition is narrow, and it has two real forms. One is a **field name that differs per -context**: the same capability reading `first_name` on one type and `display_name` on another. The other +context**: the same trait reading `first_name` on one type and `display_name` on another. The other is a context that supplies the value **some way other than a plain field read**, through `WithProvider` or a hand-written impl, while other contexts still read a field. diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index d5b9fb84..b2f2c7ab 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -12,7 +12,7 @@ already know. A [provider trait](./cgp_component.md) has a different shape from the trait it came from. The original `Self` has moved into an explicit leading type parameter, the implementation targets a small -marker type rather than the type the capability is about, and the method receiver is a plain parameter. +marker type rather than the type the operation acts on, and the method receiver is a plain parameter. Written by hand it looks like this: ```rust @@ -29,7 +29,7 @@ where Every part of that is correct, and almost every part of it is unfamiliar. The trait carries a parameter you did not write, `Self` is a type without values, and the block does not mention `self` anywhere. Written this way, the code does not read as an implementation of `CanCalculateArea`, even -though it is exactly that. The trait needs a `Self` it owns, instead of the type the capability is +though it is exactly that. The trait needs a `Self` it owns, instead of the type the operation is really about, so that it can [bypass coherence](/docs/concepts/coherence). `#[cgp_impl]` gives you back the familiar shape. Write the implementation as though you were @@ -52,7 +52,7 @@ Write providers this way. The macro performs the rewrite for you and produces th which you will see in generated code. This convenience has one rule you must keep in mind: **inside a `#[cgp_impl]` block, `self` and -`Self` mean the context, not the provider.** The context is the type the capability runs against, and +`Self` mean the context, not the provider.** The context is the type the method runs on, and it supplies the values it needs as its own fields. The provider is a type-level name without fields or values. The program never constructs it, and it holds nothing to read. The macro rewrites `self` to the context value and `Self` to the context type because the context is the only thing that exists when @@ -174,7 +174,7 @@ they let an idiomatic provider state what it needs. - [`#[implicit]`](../attributes/implicit.md) on a parameter removes it from the signature and fills it from a same-named field on the context. -- [`#[uses(...)]`](../attributes/uses.md) adds the capabilities the provider depends on, reading like +- [`#[uses(...)]`](../attributes/uses.md) adds the traits the provider depends on, reading like a `use` statement instead of a hand-written `where Self: Trait` clause. - [`#[use_type(Trait.Type)]`](../attributes/use_type.md) imports an abstract type and rewrites its occurrences to fully qualified form. @@ -278,7 +278,7 @@ any other. The `Self` form does not produce a provider at all. Use something else in these cases: -- **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain +- **The trait has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain function without a component, a provider, or wiring, which is the bottom tier of [Modularity Hierarchy](/docs/concepts/modularity-hierarchy). - **You want to implement the consumer trait directly on one concrete type.** Use the diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index b35365a3..bc1ce2ed 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -9,8 +9,8 @@ Define a reusable, inheritable wiring table that many contexts can join. ## Overview -With [`delegate_components!`](./delegate_components.md) alone, every **context** (the type the capability -runs against, which supplies the values it needs as its fields) spells out its own wiring entry by entry. +With [`delegate_components!`](./delegate_components.md) alone, every **context** (the type the method +runs on, which supplies the values it needs as its fields) spells out its own wiring entry by entry. Two contexts that should share the same providers repeat the same lines, and a table grows with the number of components until the wiring is the largest thing in the file. diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index bf3a5d89..5d236671 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -22,7 +22,7 @@ fn magic_number() -> u64 { ``` That produces the provider struct `MagicNumber` and an impl of [`Producer`](../components/handler/producer.md), the -family member whose method takes only a **context** (the type the capability runs against) and a phantom +family member whose method takes only a **context** (the type the method runs on) and a phantom `Code` tag, with no input value at all. A dedicated macro is worth having because **a producer can stand in for any handler**: a handler that @@ -120,7 +120,7 @@ within it there is nothing simpler. same macro with the restrictions lifted, and it handles generics, `async`, and `Result` returns. - **Write the provider by hand with [`#[cgp_impl]`](./cgp_impl.md) when the value comes from the context.** This is the boundary that matters. A `#[cgp_producer]` function has no receiver, so it cannot read a field, - name an abstract type, or call a capability. It can only return something it computes from nothing. A + name an abstract type, or call another trait. It can only return something it computes from nothing. A producer that draws on its context is an impl of `Producer` written with `#[cgp_impl]`, where `self` is the context and [`#[implicit]`](../attributes/implicit.md) works normally. **In practice that covers most producers**, which makes this macro narrower than it first looks: it is for constants and pure seeds. diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 89dfa3b7..81b8bc21 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -12,7 +12,7 @@ declaring the provider struct. A provider trait is not shaped like the trait it came from. [`#[cgp_component]`](./cgp_component.md) moves the original `Self` into an explicit leading type parameter for the **context**. The context is -the type the capability runs against, and it supplies the values it needs as its own fields. An +the type the method runs on, and it supplies the values it needs as its own fields. An implementation targets a small named struct instead. Written out, a provider looks like this: ```rust diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 802254fe..b880e262 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -20,7 +20,7 @@ An abstract type in CGP is exactly that trait and nothing more exotic. `#[cgp_ty fill the slot by **wiring** rather than by writing an impl. Without it, giving a context a concrete scalar means writing a provider by hand: a whole impl whose only content is `type Scalar = f64;`. Since every abstract-type provider has that same trivial shape, `#[cgp_type]` -generates it once and for all. A **context** is the type the capability runs against, and it supplies +generates it once and for all. A **context** is the type that implements the trait, and it supplies the values and types it needs. It names the concrete type directly in its wiring table: ```rust @@ -156,7 +156,7 @@ impl HasScalarType for App { **Use `#[cgp_type]` whenever generic code has to name a type the context should choose.** The error type is the canonical instance. CGP's own [`HasErrorType`](../components/has_error_type.md) is defined -exactly this way, which is why every fallible capability can say `Error` and mean whatever the +exactly this way, which is why every fallible trait can say `Error` and mean whatever the application picked. The decision worth making deliberately is **whether the type needs to be abstract at all**, because @@ -167,10 +167,10 @@ there is a cheaper option that does more than it looks. [`#[impl_generics]`](../attributes/impl_generics.md) on a `#[cgp_fn]` puts a parameter on the implementation alone. Nothing is wired, nothing is declared, and a context qualifies just by carrying a field of a compatible type. -- **Move up to an abstract type when the type must be nameable.** Two things force it: the capability's own - signature has to mention the type, or two capabilities have to agree they mean the *same* type. An +- **Move up to an abstract type when the type must be nameable.** Two things force it: the trait's own + signature has to mention the type, or two traits have to agree they mean the *same* type. An inferred parameter can do neither, since it exists only where a value of it passes through. -- **Never thread it as a generic parameter on the capability.** A parameter is an input the caller +- **Never thread it as a generic parameter on the trait.** A parameter is an input the caller supplies, so it lands in every intermediate signature whether that layer touches the type or not. An abstract type is determined by the context and propagates nowhere. That difference is the whole benefit of the construct, and it is why a context can decide many types without any signature diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 82e6e600..6fd393a4 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -10,14 +10,14 @@ Assert at compile time that a context can actually use each component it wires. ## Overview **CGP's wiring is lazy, and this macro is the answer to that.** The **context** is the type the -capability runs against, and it supplies the values it needs as its own fields. When +method runs on, and it supplies the values it needs as its own fields. When [`delegate_components!`](./delegate_components.md) records that a context delegates a component to some provider, nothing checks that the provider can do the job. The entry is stored as a type-level fact and believed. Whether the chosen provider's own requirements hold *for this context* is a separate question, and it is not asked until something tries to use the component. So a context can look completely wired, compile, and still be broken. Every entry is accepted, the struct -compiles, the module compiles. Then the first call to the capability fails, often in a file far from +compiles, the module compiles. Then the first call to the trait's method fails, often in a file far from the mistake. `check_components!` forces the question at a line you choose: @@ -31,7 +31,7 @@ check_components! { ``` That block has no runtime existence. It compiles if `Person` really can use the component and fails if it -cannot, at the wiring site rather than wherever the capability first gets called. +cannot, at the wiring site rather than wherever the trait first gets called. The other thing it gives you is a *readable* failure, and that is the part worth understanding. Asking the obvious question, "does `Person` implement `CanGreet`?", makes the compiler report only the last link in @@ -368,7 +368,8 @@ error[E0428]: the name `__CheckPerson` is defined multiple times Use `#[check_trait(...)]` on one of them. -**A passing check is not a claim that the capability is correct**, only that it resolves. It proves the +**A passing check is not a claim that the implementation is correct**, only that it resolves. It +proves the provider was found and its dependencies are satisfiable, not that the provider does what you meant. ## Related constructs diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index b7bf3f1d..cbd8188a 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -11,7 +11,7 @@ Wire a context and check that wiring in one macro. CGP's wiring is [lazy](./delegate_components.md#common-mistakes): a [`delegate_components!`](./delegate_components.md) entry is accepted without verifying that the provider it -names can actually satisfy the component, so a **context** (the type the capability runs against, which +names can actually satisfy the component, so a **context** (the type the method runs on, which supplies the values it needs as its own fields) can compile while being broken. The fix is a [`check_components!`](./check_components.md) block, and the problem with the fix is that keeping it in step with the wiring is manual. Add a delegation, remember to add its check. diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 3903b203..1084576d 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -24,7 +24,7 @@ delegate_components! { ``` Think of the result as a **table**: a compact list saying which implementation supplies each -capability. But one point needs precision, because the analogy suggests a wrong conclusion. This looks +trait. But one point needs precision, because the analogy suggests a wrong conclusion. This looks like an object's method table, but the compiler resolves it entirely at compile time: the keys and values are types, the lookup happens during trait resolution, and the result monomorphizes to a direct call. The compiled program contains neither a table nor dynamic dispatch, and the binary holds nothing @@ -377,7 +377,7 @@ fn print_area(rect: &Rectangle) { } ``` -The benefit shows up when a second context wants the same capability answered differently. It +The benefit shows up when a second context wants the same trait answered differently. It writes its own provider and its own table entry, and the code that calls `area()` does not change: ```rust @@ -428,7 +428,7 @@ delegate_components! { Use `delegate_components!` whenever a context needs to choose providers, which is any time you use [`#[cgp_component]`](./cgp_component.md) at all. The real decision is not whether to wire but **how to check the wiring**, because CGP's wiring is *lazy*: a table with a missing or wrong entry still -compiles, and the failure only surfaces later, where the capability is used. +compiles, and the failure only surfaces later, where the trait is used. - **Pair it with [`check_components!`](./check_components.md)** for anything beyond simple wiring. A separate check gives you full control over what it asserts: concrete parameters for generic keys, @@ -655,7 +655,7 @@ it finds. ## Common Mistakes **Wiring is lazy.** A table with a missing entry, or one naming a provider whose own dependencies are -unmet, still compiles. The failure appears later, at the place where code uses the capability, often +unmet, still compiles. The failure appears later, at the place where code uses the trait, often as a long error naming types you did not write. This is the single most common source of confusion with CGP. The answer is to check the table (see [`check_components!`](./check_components.md)) and to run [`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`, which leads with the root cause diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md index 0363a363..8152a76d 100644 --- a/docs/reference/macros/index.md +++ b/docs/reference/macros/index.md @@ -16,14 +16,14 @@ than here; this page is the fuller reference for once those six are familiar. ## Defining a component, and writing its providers -[`#[cgp_component]`](./cgp_component.md) is the macro every wired capability starts from: it turns one +[`#[cgp_component]`](./cgp_component.md) is the macro every wired trait starts from: it turns one trait into the consumer trait callers use, the provider trait implementations target, and the marker that wiring keys against. A provider is then written with [`#[cgp_impl]`](./cgp_impl.md), which keeps `self`, `Self`, and the consumer trait's own method signatures; [`#[cgp_provider]` and `#[cgp_new_provider]`](./cgp_provider.md) are the lower-level forms underneath it, mostly met in generated code rather than written by hand. -When a capability has exactly one implementation and needs no wiring at all, +When a trait has exactly one implementation and needs no wiring at all, [`#[cgp_fn]`](./cgp_fn.md) builds it straight from a function, and [`#[blanket_trait]`](./blanket_trait.md) does the same starting from a trait with default methods and supertrait dependencies. [`#[async_trait]`](./async_trait.md) is how any of these traits declares an @@ -46,7 +46,7 @@ input to a per-type trait's own implementations. [`delegate_components!`](./delegate_components.md) is where a concrete type says which provider answers each component, in a table that is a compile-time fact rather than a runtime lookup. Because that wiring is lazy, [`check_components!`](./check_components.md) forces a missing or broken -choice to fail at the table rather than wherever the capability is finally called, and +choice to fail at the table rather than wherever the trait is finally called, and [`delegate_and_check_components!`](./delegate_and_check_components.md) fuses the two for a newcomer or a simple table, so the check cannot be forgotten. [`cgp_namespace!`](./cgp_namespace.md) lifts a table out of any one type and gives it a name other types can join, which is how CGP expresses reusable diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index e1d57966..6d1e56b6 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -22,7 +22,7 @@ HasField ``` Encoding a string as a type lets field access take part in trait resolution. A **context** is the type -the capability runs against, and it supplies the values it needs as its own fields. It can carry a +the method runs on, and it supplies the values it needs as its own fields. It can carry a `HasField` impl and a `HasField` impl side by side, and the compiler picks the right one from the tag alone. Nothing is compared at runtime, because there is nothing at runtime: the tag exists only during compilation. diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index d154641a..79a141f2 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -10,7 +10,7 @@ Compose a list of field getters into one, reaching a field several hops inside a ## Overview `ChainGetters` reaches a field that does not live directly on the context but several levels -inside it. The **context** is the type a capability runs against, and a single +inside it. The **context** is the type a method runs on, and a single [`UseField`](use_field.md) reads one field of one context. But CGP contexts often nest: a context holds a config, the config holds a connection, the connection holds a timeout, and a getter may need the innermost value. Writing one provider that walks the whole path by hand is tedious and couples the diff --git a/docs/reference/providers/dispatch/build_and_merge.md b/docs/reference/providers/dispatch/build_and_merge.md index 2443aa4c..c70c65e4 100644 --- a/docs/reference/providers/dispatch/build_and_merge.md +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -13,7 +13,7 @@ the builder at once. `BuildAndMerge` is the bulk counterpart of [`BuildAndSetField`](build_and_set_field.md). Instead of setting one field, it runs `Provider` over a reference to the builder to produce another record, then copies every shared field from that result into the builder in one step. It runs on a -**context**, the type a capability runs against, and is the field-list analogue of setting a single +**context**, the type a method runs on, and is the field-list analogue of setting a single field. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/dispatch/build_and_merge_outputs.md b/docs/reference/providers/dispatch/build_and_merge_outputs.md index 86c1b395..f10ac198 100644 --- a/docs/reference/providers/dispatch/build_and_merge_outputs.md +++ b/docs/reference/providers/dispatch/build_and_merge_outputs.md @@ -15,7 +15,7 @@ automatically. field-producing providers rather than builder adapters. It wraps each provider in [`BuildAndMerge`](build_and_merge.md) for you, so a caller supplies result-producing providers and each one is merged into the builder without the caller writing the merge step. It runs on a **context**, the -type a capability runs against. Like every CGP provider, it carries no runtime value. +type a method runs on. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/dispatch/build_and_set_field.md b/docs/reference/providers/dispatch/build_and_set_field.md index b961276b..c0c8239a 100644 --- a/docs/reference/providers/dispatch/build_and_set_field.md +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -13,7 +13,7 @@ The builder adapter that computes one field's value and sets it on a partial rec record, runs `Provider` over a *reference* to that builder to compute the value for `Tag`, then sets that field and returns the advanced builder. Because the provider sees `&Builder`, it can read fields already set on the partial record while computing the next one. It runs on a **context**, the type a -capability runs against. Like every CGP provider, it carries no runtime value. +method runs on. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/dispatch/build_with_handlers.md b/docs/reference/providers/dispatch/build_with_handlers.md index 513cdf77..c31925f1 100644 --- a/docs/reference/providers/dispatch/build_with_handlers.md +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -13,7 +13,7 @@ the fully-populated result. `BuildWithHandlers` is the entry point on the builder side. It starts from an empty partial record, pipes that builder through a list of builder adapters so each one sets its field, and finalizes the fully-populated result into the concrete `Output`. It runs on a **context**, the type a -capability runs against. Because the finalize step is available only when every field is present, +method runs on. Because the finalize step is available only when every field is present, omitting a handler for some field is a compile error rather than a runtime failure. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/dispatch/downcast_and_handle.md b/docs/reference/providers/dispatch/downcast_and_handle.md index 78b26dc6..da6d3e3b 100644 --- a/docs/reference/providers/dispatch/downcast_and_handle.md +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -12,8 +12,8 @@ The adapter that matches a whole group of variants at once by narrowing to a sma `DowncastAndHandle` is the matcher adapter that handles a *group* of variants in one step rather than a single variant. Instead of extracting one field, it tries to narrow the input to a smaller enum type `Inner`. On success it hands the whole `Inner` value to `Provider` and returns `Ok`; -on failure it returns `Err` of the remainder. It runs on a **context**, the type a capability runs -against, and lets a matcher delegate several variants to one sub-matcher in a single step. Like every +on failure it returns `Err` of the remainder. It runs on a **context**, the type a method runs +on, and lets a matcher delegate several variants to one sub-matcher in a single step. Like every CGP provider, it carries no runtime value. `Provider` defaults to [`UseContext`](../use_context.md). diff --git a/docs/reference/providers/dispatch/extract_field_and_handle.md b/docs/reference/providers/dispatch/extract_field_and_handle.md index 9de30c66..8de79a05 100644 --- a/docs/reference/providers/dispatch/extract_field_and_handle.md +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -13,7 +13,7 @@ The per-variant adapter that tries one variant and forwards its matched payload tries to extract the variant named `Tag` from the input. On success it wraps the payload in a `Field` and hands it to `Provider`, returning `Ok` of the provider's output. On failure it returns `Err` of the remainder, the extractor with that variant ruled out. It runs on a **context**, the -type a capability runs against. It returns the `Result` shape the +type a method runs on. It returns the `Result` shape the matcher loop expects, so a [`Product!`](../../macros/product.md) of these adapters is the list a matcher consumes. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/dispatch/handle_field_value.md b/docs/reference/providers/dispatch/handle_field_value.md index be73f9b2..84b1b0e5 100644 --- a/docs/reference/providers/dispatch/handle_field_value.md +++ b/docs/reference/providers/dispatch/handle_field_value.md @@ -13,7 +13,7 @@ Strip the variant tag from a matched payload and pass the bare value to an inner handler that does the work. An extract adapter such as [`ExtractFieldAndHandle`](extract_field_and_handle.md) delivers a `Field`, so the variant name stays attached to the payload. `HandleFieldValue` strips the `Field` wrapper and passes the bare -`Value` to `Provider`, on a **context**, the type a capability runs against. This lets an +`Value` to `Provider`, on a **context**, the type a method runs on. This lets an ordinary computer over the payload type serve as a per-variant handler. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/dispatch/index.md b/docs/reference/providers/dispatch/index.md index f600184b..bce7e17f 100644 --- a/docs/reference/providers/dispatch/index.md +++ b/docs/reference/providers/dispatch/index.md @@ -15,7 +15,7 @@ variants is not known at the call site and the handling logic for each one lives provider. A hand-written `match` names every variant in one place; these combinators instead drive the extractor and builder trait families to do the same work over a value whose shape is only known at the type level, dispatching each field or variant to a handler chosen by type. They run on a **context**, -the type a capability runs against, and are all [`Computer`](../../components/handler/computer.md)-family +the type a method runs on, and are all [`Computer`](../../components/handler/computer.md)-family providers, several also [`Handler`](../../components/handler/handler.md) and [`TryComputer`](../../components/handler/try_computer.md) providers. Like every CGP provider, each is zero-sized. diff --git a/docs/reference/providers/dispatch/match_first_with_handlers.md b/docs/reference/providers/dispatch/match_first_with_handlers.md index 01bbe5f3..333e89ed 100644 --- a/docs/reference/providers/dispatch/match_first_with_handlers.md +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -13,7 +13,7 @@ alongside the value. `MatchFirstWithHandlers` is the matcher for the calling convention where the input is a tuple `(Input, Args)`: the value being matched, together with extra arguments to pass to each handler. It threads `Args` through the loop unchanged, so on a miss both the shrinking remainder and the still-owned -arguments carry to the next handler. It runs on a **context**, the type a capability runs against. The +arguments carry to the next handler. It runs on a **context**, the type a method runs on. The "first" in the name reflects that the value being matched is the *first* element of the input tuple. Like every CGP provider, it carries no runtime value; the handler list rides in `PhantomData`. diff --git a/docs/reference/providers/dispatch/match_with_field_handlers.md b/docs/reference/providers/dispatch/match_with_field_handlers.md index d6d0a59f..5553d923 100644 --- a/docs/reference/providers/dispatch/match_with_field_handlers.md +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -13,7 +13,7 @@ variant tag still attached. `MatchWithFieldHandlers` synthesizes the per-variant handler list from the input type's own field list, like [`MatchWithValueHandlers`](match_with_value_handlers.md), but hands each matched payload to `Provider` as a `Field` with the variant name still attached rather than as a -bare value. It runs on a **context**, the type a capability runs against. Reach for it when the handler +bare value. It runs on a **context**, the type a method runs on. Reach for it when the handler needs to know which variant it received. Like every CGP provider, it carries no runtime value. The two matchers differ by exactly one [`HandleFieldValue`](handle_field_value.md) wrapper: diff --git a/docs/reference/providers/dispatch/match_with_handlers.md b/docs/reference/providers/dispatch/match_with_handlers.md index 481224c4..90dc969d 100644 --- a/docs/reference/providers/dispatch/match_with_handlers.md +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -12,7 +12,7 @@ wildcard arm. `MatchWithHandlers` is the owned-input matcher. Given a value, it converts the value to its extractor and runs a list of handlers over it, stopping at the first one that matches. It runs on a -**context**, the type a capability runs against. When the list is exhausted the remaining type has every +**context**, the type a method runs on. When the list is exhausted the remaining type has every variant ruled out and is therefore uninhabited, which lets the matcher return the bare output with no fallback arm. Like every CGP provider, it carries no runtime value; the handler list rides in `PhantomData`. diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index 74b77952..de5a783f 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -15,7 +15,7 @@ out one adapter per variant, it synthesizes the handler list from the input type adding a variant needs no change to the wiring. Each matched payload reaches `Provider` as a bare value, which is the form to use when the per-variant handler is an ordinary computer over the payload type, such as one generated by [`#[cgp_computer]`](../../macros/cgp_computer.md). It runs on a **context**, -the type a capability runs against. Like every CGP provider, it carries no runtime value. +the type a method runs on. Like every CGP provider, it carries no runtime value. It is the value-passing sibling of [`MatchWithFieldHandlers`](match_with_field_handlers.md): the two differ by exactly one [`HandleFieldValue`](handle_field_value.md) wrapper, which diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index a7e572b3..2ace4609 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -13,7 +13,7 @@ string handling. `DebugError` implements both error components by redirecting through a string. Rather than producing the abstract error directly, it formats the source error or the detail with the `Debug` trait into a `String`, then forwards to the **context**'s own `CanRaiseError` or `CanWrapError`, -where the context is the type a capability runs against. It does not know the context's error type: it +where the context is the type a method runs on. It does not know the context's error type: it only knows how to turn a `Debug` value into a `String` and hand it off, leaving the final step to whatever string-handling provider the context already wires. Like every CGP provider, `DebugError` carries no runtime value. diff --git a/docs/reference/providers/error/discard_detail.md b/docs/reference/providers/error/discard_detail.md index 7b09df7e..b39a154f 100644 --- a/docs/reference/providers/error/discard_detail.md +++ b/docs/reference/providers/error/discard_detail.md @@ -10,8 +10,8 @@ Wrap an error by throwing the detail away and returning the error unchanged. ## Overview `DiscardDetail` is the `ErrorWrapper` provider that ignores whatever detail is attached and returns the -error as it was. It satisfies the `CanWrapError` capability of a **context**, the type a capability runs -against, without enriching the error. This is useful when a context's error type cannot carry extra +error as it was. It satisfies the `CanWrapError` trait of a **context**, the type a method runs +on, without enriching the error. This is useful when a context's error type cannot carry extra context, or when the wrapping detail is deliberately not kept. It is the wrapping counterpart of a no-op: the error propagates unchanged. Like every CGP provider, `DiscardDetail` carries no runtime value. @@ -37,7 +37,7 @@ Wired this way, any call to `Context::wrap_error(error, detail)` on `App` return ## When to use it **Reach for `DiscardDetail` when a context's error type cannot hold extra detail, or when a call site -attaches detail that this context has no use for.** It keeps the `CanWrapError` capability satisfiable +attaches detail that this context has no use for.** It keeps the `CanWrapError` trait satisfiable without storing anything. Reach for [`DebugError`](debug_error.md) or [`DisplayError`](display_error.md) when the detail should be diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md index d899787a..fb8cdb09 100644 --- a/docs/reference/providers/error/display_error.md +++ b/docs/reference/providers/error/display_error.md @@ -13,7 +13,7 @@ string handling. `DisplayError` is the `Display` counterpart of [`DebugError`](debug_error.md). It implements both error components by formatting the source error or the detail with the `Display` trait into a `String`, then forwarding to the **context**'s own `CanRaiseError` or `CanWrapError`, where the context -is the type a capability runs against. It carries the source's user-facing message rather than its debug +is the type a method runs on. It carries the source's user-facing message rather than its debug representation. Like every CGP provider, `DisplayError` carries no runtime value. As with `DebugError`, it does not know the context's error type. It reduces any `Display` source to the diff --git a/docs/reference/providers/error/index.md b/docs/reference/providers/error/index.md index 4f5b250a..39abcb85 100644 --- a/docs/reference/providers/error/index.md +++ b/docs/reference/providers/error/index.md @@ -10,8 +10,9 @@ concrete error type the context chose. ## Overview -The error providers supply common error-handling strategies to any **context**, the type a capability -runs against. [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) define *what* a +The error providers supply common error-handling strategies to any **context**, the type a method +runs on. [`CanRaiseError`](../../components/can_raise_error.md) and +[`CanWrapError`](../../components/can_wrap_error.md) define *what* a context can do with an error: turn a source error into its abstract `Self::Error`, or attach detail to one it already holds. They say nothing about *how*. These providers supply the how for the cases that need no particular error library. Each one is generic over the context, so it works with whatever error @@ -76,7 +77,7 @@ still defined with [`#[derive_delegate]`](../../attributes/derive_delegate.md), The ideas behind it: - [Modular error handling](/docs/concepts/modular-error-handling) — how the abstract error type, the - raise and wrap capabilities, and these strategies fit together as interchangeable wiring decisions. + raise and wrap components, and these strategies fit together as interchangeable wiring decisions. ## Source diff --git a/docs/reference/providers/error/panic_on_error.md b/docs/reference/providers/error/panic_on_error.md index e155a2c8..02bd1287 100644 --- a/docs/reference/providers/error/panic_on_error.md +++ b/docs/reference/providers/error/panic_on_error.md @@ -10,7 +10,7 @@ Abort with the source error's debug output instead of producing an abstract erro ## Overview `PanicOnError` is the `ErrorRaiser` provider that panics rather than returning an error. When a -**context**, the type a capability runs against, treats an error as a programming fault that should stop +**context**, the type a method runs on, treats an error as a programming fault that should stop the program, `PanicOnError` raises by calling `panic!` with the source error's debug representation. Its signature promises to return the abstract error, but the body never does, because `panic!` diverges. This suits tests and fail-fast tooling. Like every CGP provider, `PanicOnError` carries no runtime value. diff --git a/docs/reference/providers/error/raise_from.md b/docs/reference/providers/error/raise_from.md index 58cb9839..4a8b4e3d 100644 --- a/docs/reference/providers/error/raise_from.md +++ b/docs/reference/providers/error/raise_from.md @@ -9,8 +9,8 @@ Raise a source error by converting it into the context's error type through the ## Overview -`RaiseFrom` is the `ErrorRaiser` provider for the common case: the **context**, the type a capability -runs against, already knows how to build its abstract `Error` from the source error through `From`. +`RaiseFrom` is the `ErrorRaiser` provider for the common case: the **context**, the type a method +runs on, already knows how to build its abstract `Error` from the source error through `From`. Wiring it means "convert every source error the abstract error has a `From` impl for". It is the default choice whenever that `From` impl exists, which covers most error raising in practice. diff --git a/docs/reference/providers/error/raise_infallible.md b/docs/reference/providers/error/raise_infallible.md index 0d6b8360..e9e4dff7 100644 --- a/docs/reference/providers/error/raise_infallible.md +++ b/docs/reference/providers/error/raise_infallible.md @@ -11,7 +11,7 @@ Absorb `core::convert::Infallible`, the error type that can never be constructed `RaiseInfallible` is the `ErrorRaiser` provider for `core::convert::Infallible`, an error type with no values. It lets generic code that is parameterized over a fallible operation be wired uniformly on a -**context**, the type a capability runs against, even when the operation chosen for that context cannot +**context**, the type a method runs on, even when the operation chosen for that context cannot fail. Because an `Infallible` value cannot exist, the raising method is never actually called at runtime. Like every CGP provider, `RaiseInfallible` carries no runtime value. diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md index feee6531..4af6c04d 100644 --- a/docs/reference/providers/error/return_error.md +++ b/docs/reference/providers/error/return_error.md @@ -10,7 +10,7 @@ Raise a source error that already is the context's abstract error, so raising is ## Overview `ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly the abstract -error the **context** chose, where the context is the type a capability runs against. Raising then has +error the **context** chose, where the context is the type a method runs on. Raising then has nothing to convert: it returns its argument untouched. A context uses it when generic code raises a value that is already of the context's own error type. Like every CGP provider, `ReturnError` carries no runtime value. diff --git a/docs/reference/providers/handler/compose_handlers.md b/docs/reference/providers/handler/compose_handlers.md index 9e315cbb..17bd1a83 100644 --- a/docs/reference/providers/handler/compose_handlers.md +++ b/docs/reference/providers/handler/compose_handlers.md @@ -10,8 +10,8 @@ Run two handlers back to back, feeding the output of the first as the input of t ## Overview `ComposeHandlers` is the fundamental sequencing combinator. It runs `ProviderA`, -then runs `ProviderB` on `ProviderA`'s output, under one **context**, the type a capability runs -against, and one `Code` tag. It implements every member of the handler family by threading the +then runs `ProviderB` on `ProviderA`'s output, under one **context**, the type a method runs +on, and one `Code` tag. It implements every member of the handler family by threading the intermediary value through both providers. Only the value flowing between them changes type. Like every CGP provider, it carries no runtime value; the two inner providers ride in `PhantomData`. diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md index cd3003f5..aa99db3d 100644 --- a/docs/reference/providers/handler/index.md +++ b/docs/reference/providers/handler/index.md @@ -15,7 +15,7 @@ code is rarely written against all of them at once. A provider author writes a p [`Computer`](../../components/handler/computer.md), a fallible [`TryComputer`](../../components/handler/try_computer.md), or an async [`Handler`](../../components/handler/handler.md), depending on the computation. The combinators let those single-shape providers be wired where a different shape is expected, and let several providers be -glued into a larger one, on a **context**, the type a capability runs against. Like every CGP provider, +glued into a larger one, on a **context**, the type a method runs on. Like every CGP provider, each combinator is zero-sized: its type parameters are inner providers carried in `PhantomData`. ## The handler family diff --git a/docs/reference/providers/handler/pipe_handlers.md b/docs/reference/providers/handler/pipe_handlers.md index 88625038..45028687 100644 --- a/docs/reference/providers/handler/pipe_handlers.md +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -13,7 +13,7 @@ next. `PipeHandlers` generalizes [`ComposeHandlers`](compose_handlers.md) from two handlers to a list of them. It takes a [`Product!`](../../macros/product.md) list of providers and folds the whole pipeline into one nested `ComposeHandlers`, so the input flows through each stage in turn, on one -**context**, the type a capability runs against. It is the combinator to reach for when wiring a +**context**, the type a method runs on. It is the combinator to reach for when wiring a multi-stage transformation: list the stages in order and let `PipeHandlers` build the composition. Like every CGP provider, it carries no runtime value; the list rides in `PhantomData`. diff --git a/docs/reference/providers/handler/promote.md b/docs/reference/providers/handler/promote.md index 6f1d3707..864a0331 100644 --- a/docs/reference/providers/handler/promote.md +++ b/docs/reference/providers/handler/promote.md @@ -24,7 +24,7 @@ handler family one slot at a time. This page explains what that wiring emits. `Promote` re-exposes one inner provider under a more capable member of the handler family, treating a less capable provider as a more capable one without introducing error or async behavior -itself. The **context**, the type a capability runs against, sees the promoted shape while the inner +itself. The **context**, the type a method runs on, sees the promoted shape while the inner provider does the same work. Like every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. @@ -67,7 +67,7 @@ pub struct Promote(pub PhantomData); - As a `TryComputer`, it requires `Provider: Computer` and wraps the infallible result in `Ok`. - As a `Handler`, it requires `Provider: AsyncComputer` and wraps the awaited result in `Ok`. -Each promotion adds the missing capability, either discarding an input or introducing an always-`Ok` +Each promotion adds the missing behavior, either discarding an input or introducing an always-`Ok` result, without changing what the inner provider computes. ## Related constructs diff --git a/docs/reference/providers/handler/promote_async.md b/docs/reference/providers/handler/promote_async.md index 057e8e58..12020311 100644 --- a/docs/reference/providers/handler/promote_async.md +++ b/docs/reference/providers/handler/promote_async.md @@ -21,7 +21,7 @@ the handler family one slot at a time. This page explains what that wiring emits ## Overview `PromoteAsync` runs a synchronous inner provider inside an async method, so a synchronous -handler serves an asynchronous slot on a **context**, the type a capability runs against. The returned +handler serves an asynchronous slot on a **context**, the type a method runs on. The returned future is ready immediately, so no actual asynchrony is added. Like every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. diff --git a/docs/reference/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md index 966e5ef8..7f5f110f 100644 --- a/docs/reference/providers/handler/promote_async_computer.md +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -21,7 +21,7 @@ whose base is the asynchronous infallible computer. You name it by hand only whe `PromoteAsyncComputer` starts from a provider that implements `AsyncComputer`, the asynchronous infallible base, and fills in the rest of the handler family on a **context**, the type a -capability runs against. It is the async-base counterpart of [`PromoteComputer`](promote_computer.md). +method runs on. It is the async-base counterpart of [`PromoteComputer`](promote_computer.md). Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md index e02febc6..82f0f76c 100644 --- a/docs/reference/providers/handler/promote_computer.md +++ b/docs/reference/providers/handler/promote_computer.md @@ -23,7 +23,7 @@ page explains what that wiring emits. `PromoteComputer` starts from a provider that implements `Computer`, the by-value synchronous infallible base, and fills in every other member of the handler family by promotion, on a **context**, -the type a capability runs against. It is a delegation table that routes each remaining handler +the type a method runs on. It is a delegation table that routes each remaining handler component to the right single-step promotion. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/handler/promote_handler.md b/docs/reference/providers/handler/promote_handler.md index 2ab9fd8c..dd488067 100644 --- a/docs/reference/providers/handler/promote_handler.md +++ b/docs/reference/providers/handler/promote_handler.md @@ -21,7 +21,7 @@ family explicitly. This page explains what that wiring emits. `PromoteHandler` starts from the most general base, a provider that implements [`Handler`](../../components/handler/handler.md), and fills in the rest of the family on a **context**, the -type a capability runs against. Like every CGP provider, it carries no runtime value. +type a method runs on. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/handler/promote_producer.md b/docs/reference/providers/handler/promote_producer.md index d1bc0863..98c4221b 100644 --- a/docs/reference/providers/handler/promote_producer.md +++ b/docs/reference/providers/handler/promote_producer.md @@ -22,7 +22,7 @@ family explicitly. This page explains what that wiring emits. `PromoteProducer` starts from a [`Producer`](../../components/handler/producer.md), a provider that takes no input, and fills in every input-taking member of the handler family on a **context**, the -type a capability runs against. The single produced value flows out of every handler shape regardless +type a method runs on. The single produced value flows out of every handler shape regardless of the input, which the promotion discards. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/handler/promote_ref.md b/docs/reference/providers/handler/promote_ref.md index 5f4af4fc..fc75a86f 100644 --- a/docs/reference/providers/handler/promote_ref.md +++ b/docs/reference/providers/handler/promote_ref.md @@ -23,8 +23,8 @@ explains what that wiring emits. `PromoteRef` lets a provider written to take a value serve a slot that takes a reference, and the reverse, without manual dereference code. It is the most thoroughly implemented promotion: it -covers all four handler families in both directions, on a **context**, the type a capability runs -against. Like every CGP provider, it carries no runtime value; the inner provider rides in +covers all four handler families in both directions, on a **context**, the type a method runs +on. Like every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. ## Usage diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md index 9ef5a396..61ce6374 100644 --- a/docs/reference/providers/handler/promote_try_computer.md +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -20,8 +20,8 @@ that implements the fallible synchronous base. You name it by hand only when wir ## Overview `PromoteTryComputer` starts from a provider that implements `TryComputer`, the synchronous -fallible base, and fills in the rest of the handler family on a **context**, the type a capability runs -against. It first turns the fallible base into a plain computer, then derives the rest of the family +fallible base, and fills in the rest of the handler family on a **context**, the type a method runs +on. It first turns the fallible base into a plain computer, then derives the rest of the family from there. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/handler/return_input.md b/docs/reference/providers/handler/return_input.md index f6b3c606..024682a0 100644 --- a/docs/reference/providers/handler/return_input.md +++ b/docs/reference/providers/handler/return_input.md @@ -9,7 +9,7 @@ The identity handler: return the input unchanged as the output. ## Overview -`ReturnInput` ignores the **context**, the type a capability runs against, and the `Code` tag, and +`ReturnInput` ignores the **context**, the type a method runs on, and the `Code` tag, and returns its input as its output. It is the neutral element of handler composition: putting it before or after any other handler leaves that handler's behavior unchanged. It fills a handler slot where no transformation is wanted, serves as the base case of a conditionally-built pipeline, and stands in as a diff --git a/docs/reference/providers/handler/try_promote.md b/docs/reference/providers/handler/try_promote.md index f86f8b5f..83b74fc5 100644 --- a/docs/reference/providers/handler/try_promote.md +++ b/docs/reference/providers/handler/try_promote.md @@ -22,7 +22,7 @@ wiring the handler family one slot at a time. This page explains what that wirin `TryPromote` unifies the two ways of expressing fallibility: a handler that *returns* a `Result`, and a genuinely fallible handler trait. It converts between them in both directions on a -**context**, the type a capability runs against. Every impl requires the context to have an error type. +**context**, the type a method runs on. Every impl requires the context to have an error type. Like every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. ## Usage diff --git a/docs/reference/providers/handler/use_input_delegate.md b/docs/reference/providers/handler/use_input_delegate.md index a9e8e508..09a2add6 100644 --- a/docs/reference/providers/handler/use_input_delegate.md +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -12,7 +12,7 @@ Dispatch a handler to a different inner provider per input type, through a looku `UseInputDelegate` chooses a handler provider by the type of the value being handled. An ordinary handler component is answered by one provider. `UseInputDelegate` performs a second lookup: it treats the handler's `Input` type as a key and reads the matching inner provider out of a table, so a -single wiring entry on a **context**, the type a capability runs against, fans out to many +single wiring entry on a **context**, the type a method runs on, fans out to many input-specific providers. Like every CGP provider, it holds no runtime value; the table rides in `PhantomData`. diff --git a/docs/reference/providers/index.md b/docs/reference/providers/index.md index ad96a677..c347ba23 100644 --- a/docs/reference/providers/index.md +++ b/docs/reference/providers/index.md @@ -53,7 +53,7 @@ to a component. ## The computation-family combinators The handler family has its own providers, which build, route, and lift computations rather than wire a -single capability. The [error providers](./error/index.md) raise and wrap a context's abstract +single trait. The [error providers](./error/index.md) raise and wrap a context's abstract error, the [handler combinators](./handler/index.md) compose and promote handlers across the family's synchronous, async, and fallible shapes, the [dispatch combinators](./dispatch/index.md) route an extensible-data value to per-field or per-variant handlers, and the diff --git a/docs/reference/providers/monad/bind_err.md b/docs/reference/providers/monad/bind_err.md index fd638ed8..8330cbc0 100644 --- a/docs/reference/providers/monad/bind_err.md +++ b/docs/reference/providers/monad/bind_err.md @@ -13,7 +13,7 @@ short-circuit on `Err`. `BindErr` implements a single bind step of the err monad, the ordinary `?`-style behavior. [`PipeMonadic`](pipe_monadic.md) composes it for you when it folds a pipeline under [`ErrMonadic`](index.md#the-monad-markers), so most code never names it. It is usable directly as a -handler provider on a **context**, the type a capability runs against, when a pipeline is built step by +handler provider on a **context**, the type a method runs on, when a pipeline is built step by step through [`PipeHandlers`](../handler/pipe_handlers.md). Like every CGP provider, it carries no runtime value; the two parameters ride in `PhantomData`. diff --git a/docs/reference/providers/monad/bind_ok.md b/docs/reference/providers/monad/bind_ok.md index 33485616..59467bfe 100644 --- a/docs/reference/providers/monad/bind_ok.md +++ b/docs/reference/providers/monad/bind_ok.md @@ -12,8 +12,8 @@ short-circuit on `Ok`. `BindOk` implements a single bind step of the ok monad. [`PipeMonadic`](pipe_monadic.md) composes it for you when it folds a pipeline under [`OkMonadic`](index.md#the-monad-markers), so most -code never names it. It is usable directly as a handler provider on a **context**, the type a capability -runs against, when a pipeline is built step by step through +code never names it. It is usable directly as a handler provider on a **context**, the type a method +runs on, when a pipeline is built step by step through [`PipeHandlers`](../handler/pipe_handlers.md) rather than through `PipeMonadic`. Like every CGP provider, it carries no runtime value; the two parameters ride in `PhantomData`. diff --git a/docs/reference/providers/monad/index.md b/docs/reference/providers/monad/index.md index ea02919a..beb2406e 100644 --- a/docs/reference/providers/monad/index.md +++ b/docs/reference/providers/monad/index.md @@ -15,7 +15,7 @@ The monad providers build [monadic handler composition](/docs/concepts/monadic-h "continue" case and a "stop" case be chained without pattern-matching each step by hand: the monad decides which case threads forward and which short-circuits. A built pipeline is itself a provider for `Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires into a **context**, the type a -capability runs against, exactly like any other handler. +method runs on, exactly like any other handler. The providers divide into three groups: diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index e0bbe662..c0f164b2 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -11,7 +11,7 @@ branch. ## Overview `PipeMonadic` composes a handler list `Providers` under a monad `M` into one -short-circuiting handler, on a **context**, the type a capability runs against. Each step runs only on +short-circuiting handler, on a **context**, the type a method runs on. Each step runs only on the previous step's continue branch, and the monad decides which branch that is. The result is a provider for `Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires like any other handler. Like every CGP provider, it carries no runtime value; `M` and the list ride in `PhantomData`. diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 9ca592bc..ef5e7d4e 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -25,8 +25,8 @@ this provider is legible. `RedirectLookup` separates *which key* a component is looked up under from *which table* answers it. The ordinary provider blanket impl looks a component up in the **context**'s own -delegation table, keyed by the component marker, where the context is the type the capability runs -against. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed by a +delegation table, keyed by the component marker, where the context is the type the method runs +on. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed by a type-level `Path`, then delegates to whatever provider that entry holds. This indirection lets one component's resolution be redirected to a different key in a different table, which is the basis for organizing wiring into namespaces. diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index b7f305be..2ff8f293 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -10,9 +10,9 @@ Satisfy a provider trait by routing back through the context's own consumer-trai ## Overview `UseContext` turns a context's existing consumer-trait implementation into a provider that other -providers can call. The **context** is the type a capability runs against, and it normally *uses* a +providers can call. The **context** is the type a method runs on, and it normally *uses* a provider through its consumer trait. Sometimes the implementation another provider wants for a -capability is exactly the one the context already supplies that way. `UseContext` is that bridge: it is +trait is exactly the one the context already supplies that way. `UseContext` is that bridge: it is a provider whose method bodies call the consumer method on the context, so handing a component `UseContext` means "use whatever this context already does for this trait." @@ -26,7 +26,7 @@ consumer trait to a provider; the other forwards a provider trait back to the co `UseContext` matters most with [higher-order providers](/docs/concepts/higher-order-providers), which take another provider as a type parameter. Such a provider can default its inner-provider parameter to `UseContext`, so when no inner provider is named, the inner step falls back to whatever the context -already wires for it. That inner step may be a different capability, or the same capability at a +already wires for it. That inner step may be a different trait, or the same trait at a different type, as the example below shows by encoding a `Vec` through the context's own encoder for `T`. Like every CGP provider, `UseContext` carries no runtime value: it is a unit marker whose `self` position is never read. @@ -46,7 +46,7 @@ implementation, which is how the [dispatch combinators](dispatch/index.md) defau per-variant provider. `UseContext` stands in for a provider trait only where that trait resolves to a *different* -implementation than the one being wired: a wrapper over another capability, or a per-type dispatch entry +implementation than the one being wired: a wrapper over another trait, or a per-type dispatch entry for a different type. ## Examples @@ -115,12 +115,12 @@ back to, and the inner provider must always be named. **Reach for `UseContext` as the default inner provider of a higher-order provider**, so the wrapper reuses the context's own wiring for the inner step when no inner provider is named. The inner step may -be a different capability, or the same capability at a different type, as `EncodeVec` delegates +be a different trait, or the same trait at a different type, as `EncodeVec` delegates `Encoder>` to the context's `Encoder`. The one shape `UseContext` cannot serve is a component whose only implementation on the context is that same delegation, which loops; [Common Mistakes](#common-mistakes) explains it. When you want a wrapper -over the *same* capability and the *same* type, name the inner provider explicitly rather than +over the *same* trait and the *same* type, name the inner provider explicitly rather than defaulting to `UseContext`. ## Under the hood @@ -163,7 +163,7 @@ creates a cycle.** If `App` wired `@EncoderComponent.u32: UseContext`, then `App would be implemented by delegating to `UseContext`, whose `Encoder` impl in turn calls `App`'s `CanEncode`. The trait solver chases this in a loop and reports it as an overflow or an unsatisfied bound. `UseContext` belongs where the provider trait resolves to a *different* implementation, such as a -wrapper over another capability or a per-type dispatch entry for a different type. The `EncodeVec` +wrapper over another trait or a per-type dispatch entry for a different type. The `EncodeVec` example above is safe for exactly that reason: it is wired for `Vec`, but its inner `UseContext` resolves `Encoder`, a different entry. diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index 4ec65e32..fdc7d1d9 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -19,7 +19,7 @@ dedicated provider. This keeps a default-only component consistent with the rest of wiring. Without it, a component whose methods are all defaulted would still need some provider type and some [`delegate_components!`](../macros/delegate_components.md) entry to take part in the table. `UseDefault` -is the shared name for that role, so a **context** (the type the capability runs against) that wants +is the shared name for that role, so a **context** (the type the method runs on) that wants the defaults wires the component to `UseDefault` and writes no method bodies of its own. `UseDefault` is a bare marker that CGP defines but does not implement for any trait. Unlike diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 55625690..6beb41c0 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -28,7 +28,7 @@ It is expected to be deprecated once `open` is shown to cover every dispatch cas `UseDelegate` chooses a provider based on a type argument rather than on the component alone. An ordinary component picks its provider by looking the component name up in the **context**'s delegation -table, where the context is the type the capability runs against. But when a provider trait carries an +table, where the context is the type the method runs on. But when a provider trait carries an extra generic parameter, such as a `SourceError` to convert or a `Shape` to measure, the right provider often depends on which concrete type that parameter is. `UseDelegate` performs a second lookup: it treats one generic parameter as a key and reads the matching inner provider out of a table, so a single diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index b211427b..983077f8 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -15,7 +15,7 @@ type to one fixed `T`. But sometimes a single provider must answer several abstr once, or route each type tag to a different concrete type chosen elsewhere, such as when a namespace or a higher-order provider supplies a coherent bundle of types. Hand-writing one `UseType` entry per tag would scatter that decision; `UseDelegatedType` concentrates it into one `Components` table the provider -consults. As always, the **context** (the type a capability runs against) points its type +consults. As always, the **context** (the type that implements the trait) points its type components at the provider. The mechanism is the same indirection [`UseDelegate`](use_delegate.md) provides for behavioral diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index 6f1619f1..dfe0cd57 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -12,7 +12,7 @@ decision rather than the method name. `UseField` decouples a getter's method name from the field it reads. A getter component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes a value the context can supply, such as -`fn name(&self) -> &str`. The **context** is the type the capability runs against, and it supplies +`fn name(&self) -> &str`. The **context** is the type the method runs on, and it supplies that value as one of its own fields. But the context may store the value under a different field name, say `first_name`, and different contexts may store it under different names. `UseField` carries the field name as its type parameter, so wiring a getter to `UseField` makes it diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index cb3c5d9c..ca44c1be 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -10,8 +10,8 @@ stored type differs from the getter's return type. ## Overview -`UseFieldRef` reads the field named by `Tag` from the **context** (the type the capability -runs against, which supplies the field) and borrows it through `AsRef` to produce a `&Value`, where the +`UseFieldRef` reads the field named by `Tag` from the **context** (the type the method +runs on, which supplies the field) and borrows it through `AsRef` to produce a `&Value`, where the stored field type implements `AsRef`. It exists for a getter whose return type is reached *through* a field rather than being the field's own type: a `&Config` from a stored `Arc`, for example, where the field is not a `Config` but can be borrowed as one. diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 2949e607..222f5ddf 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -13,7 +13,7 @@ method. `UseFields` is the provider form of the convention "the method `name` reads the field `name`." A getter component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes one or more values the **context** can supply, and the most common arrangement is that each value lives in a same-named field. -The context is the type the capability runs against, and it supplies those values as its own fields. +The context is the type the method runs on, and it supplies those values as its own fields. `UseFields` is the provider that realizes the arrangement: wiring a getter to `UseFields` makes every method read the context field whose name equals the method name, looked up through [`HasField`](../traits/field-access/has_field.md) keyed by a [`Symbol!`](../macros/symbol.md). diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index f9e0ae2f..1dd0becd 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -23,7 +23,7 @@ different jobs. ## Overview `UseType` removes the need to hand-write a provider every time a **context** wants to fix an -abstract type to a concrete one. The context is the type a capability runs against, and it decides what +abstract type to a concrete one. The context is the type that implements the trait, and it decides what each abstract type resolves to. An abstract type in CGP is a trait with a single associated type, defined with [`#[cgp_type]`](../macros/cgp_type.md), such as `trait HasScalarType { type Scalar; }`. Generic code refers to the type without committing to any particular one, and a concrete context diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md index 760f1055..5cca1a66 100644 --- a/docs/reference/providers/with_context.md +++ b/docs/reference/providers/with_context.md @@ -10,7 +10,7 @@ The `WithProvider`-adapted spelling of `UseContext`, defined for completeness of ## Overview `WithContext` is the alias `WithProvider`. It pairs the [`WithProvider`](with_provider.md) -adapter with [`UseContext`](use_context.md) on a **context**, the type a capability runs against. +adapter with [`UseContext`](use_context.md) on a **context**, the type a method runs on. [`UseContext`](use_context.md) carries a foundational [`FieldGetter`](../traits/field-access/field_getter.md), and [`WithProvider`](with_provider.md) adapts a foundational provider into a named component's provider, so `WithContext` is the two composed. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md index 2952e3d0..31254dee 100644 --- a/docs/reference/providers/with_delegated_type.md +++ b/docs/reference/providers/with_delegated_type.md @@ -11,7 +11,7 @@ Resolve one or more abstract-type components from a shared table, through the `W `WithDelegatedType` is the alias `WithProvider>`. It answers a context's abstract-type components by looking each type tag up in the `Components` table, on a -**context**, the type a capability runs against, by adapting the foundational +**context**, the type that implements the trait, by adapting the foundational [`UseDelegatedType`](use_delegated_type.md) provider through the [`WithProvider`](with_provider.md) layer. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/with_field.md b/docs/reference/providers/with_field.md index 6d695581..4a60f2a3 100644 --- a/docs/reference/providers/with_field.md +++ b/docs/reference/providers/with_field.md @@ -10,7 +10,7 @@ Wire a getter component to a named context field, through the `WithProvider` ada ## Overview `WithField` is the alias `WithProvider>`. It implements a getter component by reading -the context field named by `Tag`, on a **context**, the type a capability runs against, by adapting the +the context field named by `Tag`, on a **context**, the type a method runs on, by adapting the foundational [`UseField`](use_field.md) getter through the [`WithProvider`](with_provider.md) layer. It reads the same field the plain [`UseField`](use_field.md) provider does, and both are interchangeable in wiring. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md index ddf5c56a..a045d8af 100644 --- a/docs/reference/providers/with_field_ref.md +++ b/docs/reference/providers/with_field_ref.md @@ -10,7 +10,7 @@ Wire a getter component to a field borrowed through `AsRef`, through the `WithPr ## Overview `WithFieldRef` is the alias `WithProvider>`. It implements a getter -component by reading the field named by `Tag` from the **context**, the type a capability runs against, +component by reading the field named by `Tag` from the **context**, the type a method runs on, and borrowing it through `AsRef` to produce a `&Value`, where the stored field type implements `AsRef`. It adapts the foundational [`UseFieldRef`](use_field_ref.md) getter through the [`WithProvider`](with_provider.md) layer. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 8bcfdab5..69daf0f7 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -15,7 +15,7 @@ specific named component. component-agnostic mechanisms: a `TypeProvider` supplies *some* abstract type for *some* tag, and a `FieldGetter` reads *some* field for *some* output tag, without either knowing which named component it serves. A named component, by contrast, has a specific provider trait, such as `NameTypeProvider` or -`NameGetter`, that a **context** wires to, where the context is the type the capability runs against. +`NameGetter`, that a **context** wires to, where the context is the type the method runs on. `WithProvider` is the adapter that lets a foundational provider stand in as the provider for one of those named components: it implements the component's provider trait by forwarding to the foundational provider's method. diff --git a/docs/reference/providers/with_type.md b/docs/reference/providers/with_type.md index 4c67c854..32535d09 100644 --- a/docs/reference/providers/with_type.md +++ b/docs/reference/providers/with_type.md @@ -10,7 +10,7 @@ Bind an abstract-type component to a concrete type, through the `WithProvider` a ## Overview `WithType` is the alias `WithProvider>`. It binds an abstract-type component to the -concrete `Type` on a **context**, the type a capability runs against, by adapting the foundational +concrete `Type` on a **context**, the type that implements the trait, by adapting the foundational [`UseType`](use_type.md) provider through the [`WithProvider`](with_provider.md) layer. It sets the same abstract type the plain [`UseType`](use_type.md) provider does, and both are interchangeable in wiring. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/traits/field-access/field_getter.md b/docs/reference/traits/field-access/field_getter.md index 1f1f06bb..36670d20 100644 --- a/docs/reference/traits/field-access/field_getter.md +++ b/docs/reference/traits/field-access/field_getter.md @@ -107,7 +107,7 @@ advanced case. Everything else is better served higher up. - **Use an [`#[implicit]`](../../attributes/implicit.md) argument** for a field an implementation reads from its own context. It generates a [`HasField`](./has_field.md) bound and involves no provider at all. -- **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a named capability, +- **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a named trait, keyed by the method name. It generates a blanket impl over `HasField` and needs no wiring. - **Use [`#[cgp_getter]`](../../macros/cgp_getter.md)** when the source field must be chosen per context. That is what makes the getter a full component with a `FieldGetter` provider trait, and it costs a diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index 3ab0d5d6..42db8ebc 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -9,7 +9,7 @@ Reading a field by a type-level name, from a context you cannot name. ## Overview -An implementation written against a **context**, the type the capability runs against, which supplies +An implementation written against a **context**, the type the method runs on, which supplies the values it needs as its fields, is generic over that context and cannot name its concrete type. So it cannot write `self.name`. Yet reading a value out of the context is the commonest thing such an implementation does. @@ -98,7 +98,7 @@ delegate_components! { ``` `Person` derives the access, so it satisfies exactly the bound `GreetHello` requires and the wiring -compiles. **Value context, self-targeted**: the wired type is the data the capability runs against. +compiles. **Value context, self-targeted**: the wired type is the data the method runs on. **Written idiomatically, none of that bound is visible.** The same read is an [`#[implicit]`](../../attributes/implicit.md) argument: @@ -132,7 +132,7 @@ ordering is settled and worth following. - **Use an [`#[implicit]`](../../attributes/implicit.md) argument by default.** It reads a field of the implementation's own context as a plain parameter, generating this bound for you. It covers the common case, including a field several implementations each read. -- **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a *named* capability, +- **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a *named* trait, when the field lives on a type other than the context, or when the getter should carry a type inferred from the field. An implicit argument cannot reach those cases. - **Use [`#[cgp_getter]`](../../macros/cgp_getter.md) with [`UseField`](../../providers/use_field.md)** only diff --git a/docs/reference/traits/field-access/index.md b/docs/reference/traits/field-access/index.md index cf102e4f..3a6aee2f 100644 --- a/docs/reference/traits/field-access/index.md +++ b/docs/reference/traits/field-access/index.md @@ -9,7 +9,7 @@ Reading one field of a context by its type-level name, from code that cannot nam ## Overview -A CGP implementation most often reads a value out of its **context**, the type a capability runs against, +A CGP implementation most often reads a value out of its **context**, the type a method runs on, without naming that type. It reads the field by keying on the field's *name as a type*, so any context with a matching field satisfies the bound. These traits are the foundation the ergonomic surface stands on: an [`#[implicit]`](../../attributes/implicit.md) argument, a diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index d6f2c3e7..0c07eca1 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -31,7 +31,7 @@ It is one of four traits that give a monad marker its meaning, and it pairs with back *in*. The other two, [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline rather than run a step of it. -**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is +**This is a plain trait, not a CGP component.** It has no generated provider trait and is never wired. ## Definition diff --git a/docs/reference/traits/monad/index.md b/docs/reference/traits/monad/index.md index cecf3c20..efb5e1db 100644 --- a/docs/reference/traits/monad/index.md +++ b/docs/reference/traits/monad/index.md @@ -11,8 +11,8 @@ The traits that give a monad marker its meaning for monadic handler composition. A [monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue or short-circuit, the `?`-style behaviour, expressed as composable providers. A monad in CGP is a -zero-sized marker, and these four traits are what give that marker meaning. They are plain capability -traits rather than CGP components: they have no generated provider trait and are never wired. The +zero-sized marker, and these four traits are what give that marker meaning. They are plain traits +rather than CGP components: they have no generated provider trait and are never wired. The [monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a pipeline at compile time, so you name a trait here only when defining a monad of your own. Import each from `cgp::extra::monad::traits`. diff --git a/docs/reference/traits/monad/lift_value.md b/docs/reference/traits/monad/lift_value.md index 0315f533..f5e4816f 100644 --- a/docs/reference/traits/monad/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -30,7 +30,7 @@ It is the counterpart of [`ContainsValue`](./contains_value.md): that one says h output type, this one how to get back *in*. Together they run one step; the other two monad traits, [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline instead. -**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is +**This is a plain trait, not a CGP component.** It has no generated provider trait and is never wired. ## Definition diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index 5d1a6fb7..ac7ba24c 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -31,7 +31,7 @@ It is one of four traits that give a monad marker its meaning, alongside [`ContainsValue`](./contains_value.md), [`LiftValue`](./lift_value.md), and [`MonadicTrans`](./monadic_trans.md). Keeping them apart lets one marker serve all four roles. -**This is a plain capability trait, not a CGP component.** It has no generated provider trait, no +**This is a plain trait, not a CGP component.** It has no generated provider trait, no `…Component` marker, and is never wired through [`delegate_components!`](../../macros/delegate_components.md): the [monad providers](../../providers/monad/index.md) consume it as an ordinary trait bound while folding a diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index 2dbb49a6..12e448a4 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -29,7 +29,7 @@ It is one of four traits that give a monad marker its meaning, and it belongs wi composed provider, while [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) run each step. -**This is a plain capability trait, not a CGP component.** It has no generated provider trait and is +**This is a plain trait, not a CGP component.** It has no generated provider trait and is never wired. ## Definition diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index d5167694..93859381 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -23,7 +23,7 @@ generates, including why a direct entry can shadow an inherited default without ## Overview A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** (the -type the capability runs against) can opt into and then selectively override. Resolving one of those +type the method runs on) can opt into and then selectively override. Resolving one of those defaults means asking: *for this component, what does the namespace delegate to?* `DefaultNamespace` answers that. It is the simplest of three lookup traits, keyed on the component alone. diff --git a/docs/reference/traits/optional/can_finalize_with_default.md b/docs/reference/traits/optional/can_finalize_with_default.md index 06913fa1..152e142a 100644 --- a/docs/reference/traits/optional/can_finalize_with_default.md +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -122,7 +122,7 @@ Read the bounds together: the first says every field can be re-marked to `IsPres Its mirror image is [`ToOptional`](./to_optional.md), which runs the same [`TransformMapFields`](../type-level/transform_map_fields.md) walk with -[`TransformOptional`](./transform_optional.md) toward `IsOptional`. **Both capabilities are the same +[`TransformOptional`](./transform_optional.md) toward `IsOptional`. **Both operations are the same recursion with a different marker**, which is why the defaulted and optional workflows behave so symmetrically. diff --git a/docs/reference/traits/optional/to_optional.md b/docs/reference/traits/optional/to_optional.md index d161dc7b..f9008011 100644 --- a/docs/reference/traits/optional/to_optional.md +++ b/docs/reference/traits/optional/to_optional.md @@ -115,7 +115,7 @@ transform, and writes it back under `IsOptional`. The transform's own impls are `IsPresent` becomes `Some(value)`, `IsNothing` becomes `None`, and `IsOptional` passes through. Its mirror image is [`CanFinalizeWithDefault`](./can_finalize_with_default.md), which runs the same walk -with [`TransformMapDefault`](./transform_map_default.md) toward `IsPresent`. **Both capabilities are the +with [`TransformMapDefault`](./transform_map_default.md) toward `IsPresent`. **Both operations are the same recursion with a different marker**, which is why the defaulted and optional workflows behave so symmetrically. diff --git a/docs/reference/traits/optional/transform_map_default.md b/docs/reference/traits/optional/transform_map_default.md index 5aedbdb5..119ad443 100644 --- a/docs/reference/traits/optional/transform_map_default.md +++ b/docs/reference/traits/optional/transform_map_default.md @@ -61,7 +61,7 @@ use cgp::extra::field::impls::TransformMapDefault; ``` There is nothing to call. The marker exists to be named in a -[`TransformMapFields`](../type-level/transform_map_fields.md) bound, which is where a capability says *which* +[`TransformMapFields`](../type-level/transform_map_fields.md) bound, which is where an operation says *which* conversion it drives: ```rust @@ -103,8 +103,8 @@ Writing a marker of your own follows the same three-impl shape; the ## When to use it -**Name it only when writing a capability that drives the defaulting conversion.** Everything else is -served by the two capabilities already built on it. +**Name it only when writing an operation that drives the defaulting conversion.** Everything else is +served by the two operations already built on it. - **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** to finalize a partial record, defaulting gaps. @@ -158,7 +158,7 @@ moment that field is unset, and the error names the missing `TransformMap` impl **It always targets `IsPresent`.** It cannot be used to reach any other configuration; that is [`TransformOptional`](./transform_optional.md)'s job. -**It is a marker, not a capability.** There is no method to call and nothing to wire. It is named in a +**It is a marker, not an operation.** There is no method to call and nothing to wire. It is named in a bound. **A defaulted field is indistinguishable from one set to the default value** in the result, which is the @@ -166,7 +166,7 @@ trade against [`FinalizeOptional`](./finalize_optional.md). ## Related constructs -- [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the capability built directly on it. +- [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the operation built directly on it. - [`CanBuildWithDefault`](./can_build_with_default.md): merge plus that finalize. - [`TransformOptional`](./transform_optional.md): the counterpart marker, targeting `IsOptional`. - [`TransformMap`](../type-level/transform_map.md): the trait it implements three times. @@ -181,7 +181,7 @@ The ideas behind it: ## Source - [`build_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-field-extra/src/impls/build_default.rs): - `TransformMapDefault` and the capabilities built on it + `TransformMapDefault` and the operations built on it --- diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index 9b3bd407..e77e77f0 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -14,7 +14,7 @@ The transform marker that makes every field optional. **You are not expected to name `TransformOptional` directly.** It is the marker [`ToOptional`](./to_optional.md) and [`HasOptionalBuilder`](./has_optional_builder.md) drive, and calling one of those is what you write. This page explains the conversion behind them, and why it needs -less of a field's type than its defaulting counterpart does. The one case for naming it is writing a capability of your own that drives the optional conversion. +less of a field's type than its defaulting counterpart does. The one case for naming it is writing an operation of your own that drives the optional conversion. ::: @@ -64,7 +64,7 @@ use cgp::extra::field::impls::TransformOptional; ``` There is nothing to call. The marker is named in a -[`TransformMapFields`](../type-level/transform_map_fields.md) bound, which is where a capability says which +[`TransformMapFields`](../type-level/transform_map_fields.md) bound, which is where an operation says which conversion it drives: ```rust @@ -96,7 +96,7 @@ use cgp::prelude::*; Swap the marker for [`TransformMapDefault`](./transform_map_default.md) and the target for `IsPresent`, add a [`finalize_build`](../builder/finalize_build.md), and you have -[`CanFinalizeWithDefault`](./can_finalize_with_default.md). The two capabilities differ by exactly that +[`CanFinalizeWithDefault`](./can_finalize_with_default.md). The two operations differ by exactly that much. Writing a marker of your own follows the same shape; the @@ -104,7 +104,7 @@ Writing a marker of your own follows the same shape; the ## When to use it -**Name it only when writing a capability that drives the optional conversion.** +**Name it only when writing an operation that drives the optional conversion.** - **[`ToOptional`](./to_optional.md)** to relax an existing partial value. - **[`HasOptionalBuilder`](./has_optional_builder.md)** to start an all-optional builder, which is @@ -147,7 +147,7 @@ makes [`SetOptional`](./set_optional.md) resolve and the strict **It always targets `IsOptional`.** Reaching `IsPresent` is [`TransformMapDefault`](./transform_map_default.md)'s job. -**It is a marker, not a capability.** There is no method and nothing to wire. It is named in a bound. +**It is a marker, not an operation.** There is no method and nothing to wire. It is named in a bound. **It requires nothing of the field types**, which is the one place the two markers genuinely differ in what they can be applied to. diff --git a/docs/reference/traits/type-level/transform_map.md b/docs/reference/traits/type-level/transform_map.md index a8b546bd..399c87d7 100644 --- a/docs/reference/traits/type-level/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -155,7 +155,7 @@ layer's payoff comes from every field landing in one state, usually `IsPresent`. half of. - [`TransformMapDefault`](../optional/transform_map_default.md) and [`TransformOptional`](../optional/transform_optional.md): the two markers CGP ships, and the models to copy. -- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md): the capability built from the first of +- [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md): the operation built from the first of them. - [`UpdateField`](../builder/update_field.md): the primitive the walk uses to take a field out and write it back. - [`FinalizeBuild`](../builder/finalize_build.md): what an all-`IsPresent` result is accepted by. diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index cb98b72b..1f5128c1 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -14,7 +14,7 @@ Applying one per-field transform across a whole partial record. **You are not expected to call `transform_map_fields` directly.** It is the recursion the optional-field layer is built from, and [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and [`ToOptional`](../optional/to_optional.md) are what -you call. This page explains the walk, which makes those two behave so symmetrically. The one case for bounding on it is writing a capability of your own that re-marks a whole record. +you call. This page explains the walk, which makes those two behave so symmetrically. The one case for bounding on it is writing an operation of your own that re-marks a whole record. ::: @@ -92,7 +92,7 @@ Applying a transform of your own follows the same shape, with your marker in pla ## When to use it -**Bound on it when writing a capability that re-marks a whole record.** Extending the optional-field +**Bound on it when writing an operation that re-marks a whole record.** Extending the optional-field layer requires exactly that. - **Use [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) or @@ -154,7 +154,7 @@ with [`HasBuilder`](../builder/has_builder.md) or [`IntoBuilder`](../builder/int - [`PartialData`](../builder/partial_data.md): what a partial value is, and the bound this requires. - [`FinalizeBuild`](../builder/finalize_build.md): what an all-`IsPresent` result is accepted by. - [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and [`ToOptional`](../optional/to_optional.md): the - two capabilities built directly on this. + two operations built directly on this. - [`MapFields`](./map_fields.md): the type-level counterpart. - [`HasFields`](../shape/has_fields.md): the shape the walk follows. diff --git a/docs/reference/traits/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md index d1db09da..b22900aa 100644 --- a/docs/reference/traits/wiring/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -22,11 +22,11 @@ failure is legible. ## Overview CGP's wiring is lazy: writing a wiring line does not check that the chosen implementation's own requirements -are met. That check happens the first time the capability is actually called, which is usually somewhere far +are met. That check happens the first time the trait is actually called, which is usually somewhere far from the wiring and produces a bad error when it fails. `CanUseComponent` is the bound that forces the check early, and it exists because the obvious way of asking -does not work. Asking "does this **context** (the type the capability runs against) implement the consumer +does not work. Asking "does this **context** (the type the method runs on) implement the consumer trait?" makes the compiler report the outermost unmet bound, usually a bare "the provider does not implement the provider trait", and hide the reasoning behind it. The root cause, often one absent field, never appears. diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index 06af16e7..2aaf1bf1 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -21,8 +21,8 @@ wiring error naming this trait is legible. ## Overview -Wiring a **context** (the type the capability runs against, which supplies the values it needs as its -fields) means recording which implementation it uses for each capability. `DelegateComponent` is the trait +Wiring a **context** (the type the method runs on, which supplies the values it needs as its +fields) means recording which implementation it uses for each trait. `DelegateComponent` is the trait that record is made of. One impl is one entry: ```rust @@ -195,7 +195,7 @@ There are narrow reasons to name the trait yourself. and knowing the trait is how you read it. And the alternative to reach for instead: **implement the consumer trait directly on the context** when a -capability has exactly one implementation for it. A CGP consumer trait is an ordinary trait, so +trait has exactly one implementation for it. A CGP consumer trait is an ordinary trait, so `impl CanGreet for App { … }` is legal and needs no table entry at all. Wiring earns its keep when the implementation is one of several, or is shared, or should compose with a wrapper. diff --git a/docs/reference/traits/wiring/index.md b/docs/reference/traits/wiring/index.md index 89e36425..92b3df64 100644 --- a/docs/reference/traits/wiring/index.md +++ b/docs/reference/traits/wiring/index.md @@ -9,7 +9,7 @@ The three traits every context's wiring rests on, and the ones a wiring error na ## Overview -Wiring a **context**, the type a capability runs against, records which provider it uses for each +Wiring a **context**, the type a method runs on, records which provider it uses for each component and checks that the provider's own requirements are met. These traits carry that, and you read them far more often than you write them, because a [`delegate_components!`](../../macros/delegate_components.md) table generates the first two and a diff --git a/docs/reference/traits/wiring/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md index 016f3659..feb5151f 100644 --- a/docs/reference/traits/wiring/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -20,8 +20,8 @@ names, and reading that error is the reason to know it exists. ## Overview -An implementation in CGP states what it needs from its **context**, the type the capability runs against, -in its own `where` clause: a field, an abstract type, another capability. When one of those requirements is +An implementation in CGP states what it needs from its **context**, the type the method runs on, +in its own `where` clause: a field, an abstract type, another trait. When one of those requirements is not met, you want the compiler to say *which*. Left to itself, it will not. The reason is a specific behaviour of Rust's diagnostics. Asking "does this provider implement the provider diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index e7ce1a4a..ca426725 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -18,7 +18,7 @@ parameter and nothing else, so `Index<0>`, `Index<1>`, and `Index<2>` are distin tuple struct's positional fields. Encoding the position as a type lets positional field access resolve through traits. Here a **context** is -the type the capability runs against. It supplies the values the capability needs as its own fields. +the type the method runs on. It supplies the values the method needs as its own fields. Because `Index<0>` is a type, a context can carry a [`HasField>`](../traits/field-access/has_field.md) impl for its first field and a `HasField>` impl for its second, side by side. The compiler selects the right one from the tag diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 15796f35..646e8a2b 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -11,8 +11,8 @@ whichever it has without forcing every implementor to one or the other. ## Overview `MRef<'a, T>` lets one getter signature serve both the context that already stores a value and the -context that must produce one. Here a **context** is the type the capability runs against. It supplies the -values the capability needs as its own fields. A getter that returns `&'a T` forces every context to keep +context that must produce one. Here a **context** is the type the method runs on. It supplies the +values the method needs as its own fields. A getter that returns `&'a T` forces every context to keep a `T` it can lend. A getter that returns `T` forces every context to give up ownership, and to clone even when it could share a reference. `MRef<'a, T>` avoids both constraints by being either case at run time. A context with the value in a field returns `MRef::Ref` and lends it. A context that computes or assembles diff --git a/docs/reference/types/path_cons.md b/docs/reference/types/path_cons.md index cce76cfd..b39ca603 100644 --- a/docs/reference/types/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -11,8 +11,8 @@ lookup can reach an entry several layers deep. ## Overview `PathCons` expresses a *route* through nested delegation tables as a single type. A bare -component name picks one entry out of a context's table. Here the **context** is the type the capability -runs against, and its table records which provider it uses for each component. Sometimes the entry a +component name picks one entry out of a context's table. Here the **context** is the type the method +runs on, and its table records which provider it uses for each component. Sometimes the entry a lookup wants sits behind a layer of indirection: inside a namespace, behind a namespace it inherits from, or under a prefix. A path names such a route as a list of segments read left to right, and each segment narrows the lookup a step further. `PathCons` is the cell of that list, and [`Nil`](nil.md) terminates diff --git a/docs/reference/types/phantom_data.md b/docs/reference/types/phantom_data.md index 5d06cba6..8066dbdf 100644 --- a/docs/reference/types/phantom_data.md +++ b/docs/reference/types/phantom_data.md @@ -95,7 +95,7 @@ let name = self.get_field(PhantomData::); let output = context.compute(PhantomData::, input); ``` -Here the **context** is the type the capability runs against. It supplies the values the capability +Here the **context** is the type the method runs on. It supplies the values the method needs as its own fields. The `PhantomData` argument carries nothing. It exists so that type inference selects the right [`HasField`](../traits/field-access/has_field.md) impl or the right handler. In effect, the call passes a type where a value is expected, and `PhantomData::` is the diff --git a/docs/tutorials/area-calculation/context-generic-functions.md b/docs/tutorials/area-calculation/context-generic-functions.md index 8c574d79..6beb8e90 100644 --- a/docs/tutorials/area-calculation/context-generic-functions.md +++ b/docs/tutorials/area-calculation/context-generic-functions.md @@ -41,7 +41,7 @@ pub struct PlainRectangle { } ``` -To enable context-generic capabilities on a context, we first need to apply `#[derive(HasField)]` on `PlainRectangle` to generate generic field access implementations. After that, we can just call `rectangle_area` on it: +To let context-generic functions run on a context, we first need to apply `#[derive(HasField)]` on `PlainRectangle` to generate generic field access implementations. After that, we can just call `rectangle_area` on it: ```rust let rectangle = PlainRectangle { @@ -70,9 +70,9 @@ pub fn scaled_rectangle_area( } ``` -Compared to `rectangle_area`, the implementation of `scaled_rectangle_area` contains an additional `#[uses(RectangleArea)]` attribute, which is used for us to "import" the capability to call `self.rectangle_area()`. The import identifier is in CamelCase, because `#[cgp_fn]` converts a function like `rectangle_area` into a *trait* called `RectangleArea`. +Compared to `rectangle_area`, the implementation of `scaled_rectangle_area` contains an additional `#[uses(RectangleArea)]` attribute, which is used for us to "import" the trait so that we can call `self.rectangle_area()`. The import identifier is in CamelCase, because `#[cgp_fn]` converts a function like `rectangle_area` into a *trait* called `RectangleArea`. -In the argument, we can also see that we only need to specify an implicit `scale_factor` argument. In general, there is no need for us to know which capabilities are required by an imported construct like `RectangleArea`. That is, we can just define `scaled_rectangle_area` without knowing the internal details of `rectangle_area`. +In the argument, we can also see that we only need to specify an implicit `scale_factor` argument. In general, there is no need for us to know which fields or traits are required by an imported construct like `RectangleArea`. That is, we can just define `scaled_rectangle_area` without knowing the internal details of `rectangle_area`. With `scaled_rectangle_area` defined, we can now define a *second* `ScaledRectangle` context that contains both the rectangle fields and the `scale_factor` field: diff --git a/docs/tutorials/hello.md b/docs/tutorials/hello.md index bb40c832..2ac08a79 100644 --- a/docs/tutorials/hello.md +++ b/docs/tutorials/hello.md @@ -113,7 +113,7 @@ Notice that `greet` works identically for both contexts, even though `PersonWith ## Behind the Scenes -The hello world example demonstrates how CGP unlocks new capabilities for writing context-generic constructs in Rust. You might wonder how the underlying machinery works, and whether CGP employs some magic that requires unsafe code or runtime overhead. This section offers a brief look at the mechanics to dispel those concerns. +The hello world example demonstrates how CGP lets you write context-generic constructs in Rust. You might wonder how the underlying machinery works, and whether CGP employs some magic that requires unsafe code or runtime overhead. This section offers a brief look at the mechanics to dispel those concerns. A full explanation of how CGP works is beyond this tutorial, but you can think of the `greet` function as being roughly equivalent to the following plain Rust definition: @@ -158,7 +158,7 @@ There is more advanced machinery involved in the actual desugared CGP code, but The plain Rust expansion above illustrates a few key properties of CGP. Firstly, CGP makes heavy use of the existing machinery provided by Rust's trait system to implement context-generic abstractions. It is also worth understanding that CGP macros like `#[cgp_fn]` and `#[derive(HasField)]` act primarily as **syntactic sugar** that performs a straightforward desugaring of CGP code into plain Rust constructs, just as shown above. -This means there is **no hidden logic at either compile time or runtime** used by CGP to resolve dependencies like `name`. The main contribution of CGP is that it introduces new language syntax and leverages Rust's trait system to enable new capabilities. You do not need to understand any new machinery beyond the trait system to understand how CGP works. +This means there is **no hidden logic at either compile time or runtime** used by CGP to resolve dependencies like `name`. The main contribution of CGP is that it introduces new language syntax and leverages Rust's trait system to make that syntax work. You do not need to understand any new machinery beyond the trait system to understand how CGP works. Furthermore, implicit arguments like `#[implicit] name: &str` are automatically desugared by CGP to use getter traits similar to `HasName`. Contexts like `Person` implement those getter traits by simply returning a *reference* to the field value. This means that implicit argument access is **zero cost** and is as cheap as direct field access from a concrete context. diff --git a/example-code/tests/concepts/abstract_types.rs b/example-code/tests/concepts/abstract_types.rs index d31195a1..46d636ca 100644 --- a/example-code/tests/concepts/abstract_types.rs +++ b/example-code/tests/concepts/abstract_types.rs @@ -74,7 +74,7 @@ pub mod choosing_the_type_by_wiring { /// ## One type, agreed on by everything that needs it /// -/// The shapes carry no scalar type of their own. The context supplies one, and every capability +/// The shapes carry no scalar type of their own. The context supplies one, and every trait /// that mentions it means the same type. pub mod one_type_agreed_on_by_everything { use cgp::prelude::*; diff --git a/example-code/tests/concepts/check_traits.rs b/example-code/tests/concepts/check_traits.rs index 52ad6228..04186123 100644 --- a/example-code/tests/concepts/check_traits.rs +++ b/example-code/tests/concepts/check_traits.rs @@ -32,7 +32,7 @@ pub mod a_context_can_be_wrong_and_still_compile { /// ## Where the failure surfaces instead /// -/// Calling the capability is the first thing that forces the question, so the error arrives at the +/// Calling the trait's method is the first thing that forces the question, so the error arrives at the /// call rather than at the wiring — and names a field requirement the caller never wrote. /// /// Rejected snippet — trybuild fixture `tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_1.rs`. @@ -73,7 +73,7 @@ pub mod a_check_is_an_empty_impl { impl CanUseApp for App {} // What `check_components!` writes instead, which reports the missing requirement rather than - // only that the capability is unavailable. + // only that the trait is unavailable. mod generated_form { use super::*; check_components! { diff --git a/example-code/tests/concepts/impl_side_dependencies.rs b/example-code/tests/concepts/impl_side_dependencies.rs index b9593cad..01aaf656 100644 --- a/example-code/tests/concepts/impl_side_dependencies.rs +++ b/example-code/tests/concepts/impl_side_dependencies.rs @@ -112,7 +112,7 @@ pub mod two_providers_two_requirements { check_components! { TestApp { EmailSenderComponent } } } - /// Neither requirement reaches a caller: this function bounds on the capability alone, and it + /// Neither requirement reaches a caller: this function bounds on the trait alone, and it /// accepts both contexts even though they satisfy it for entirely different reasons. pub fn notify(context: &Context) where diff --git a/example-code/tests/concepts/implicit_arguments.rs b/example-code/tests/concepts/implicit_arguments.rs index 6c1c6dda..81198722 100644 --- a/example-code/tests/concepts/implicit_arguments.rs +++ b/example-code/tests/concepts/implicit_arguments.rs @@ -74,7 +74,7 @@ pub mod the_same_provider_as_a_function { } } -/// ## A capability from a function alone +/// ## A trait from a function alone /// /// `#[cgp_fn]` needs no trait, no provider, and no wiring — the blanket impl applies to any context /// carrying the fields. diff --git a/example-code/tests/concepts/modular_error_handling.rs b/example-code/tests/concepts/modular_error_handling.rs index bb98970f..8355493d 100644 --- a/example-code/tests/concepts/modular_error_handling.rs +++ b/example-code/tests/concepts/modular_error_handling.rs @@ -122,7 +122,7 @@ pub mod the_same_providers_under_a_different_error_type { } } -/// ## An application's own error capability +/// ## An application's own error component /// /// Nothing about the pattern is confined to CGP's built-in components. A service that wants every /// failure to carry a status code declares its own, and wires it the same way. diff --git a/example-code/tests/concepts/modularity_hierarchy.rs b/example-code/tests/concepts/modularity_hierarchy.rs index 713d69f1..1cd7788d 100644 --- a/example-code/tests/concepts/modularity_hierarchy.rs +++ b/example-code/tests/concepts/modularity_hierarchy.rs @@ -1,6 +1,6 @@ //! Code from `docs/concepts/modularity-hierarchy.md` — *Modularity Hierarchy*. //! -//! One module per tier. The page walks the five tiers on one running capability — encoding a value — +//! One module per tier. The page walks the five tiers on one running operation — encoding a value — //! so each module encodes the same kind of thing with more modularity than the one before it. The //! `CanEncode` / `Encoder` / `EncodeAsText` names are the site's shared encoding example, carried over //! from the front page and *Bypassing coherence*. diff --git a/example-code/tests/reference/macros/delegate_components.rs b/example-code/tests/reference/macros/delegate_components.rs index 4546ba76..f1def9bf 100644 --- a/example-code/tests/reference/macros/delegate_components.rs +++ b/example-code/tests/reference/macros/delegate_components.rs @@ -508,7 +508,7 @@ pub mod statements_come_first { /// ## Examples /// -/// The two-context payoff the page builds to: the same capability answered differently by two +/// The two-context payoff the page builds to: the same trait answered differently by two /// contexts, and a generic function serving both. pub mod examples { use cgp::prelude::*; diff --git a/example-code/tests/reference/providers/error/discard_detail.rs b/example-code/tests/reference/providers/error/discard_detail.rs index f7a0e656..6d3434d4 100644 --- a/example-code/tests/reference/providers/error/discard_detail.rs +++ b/example-code/tests/reference/providers/error/discard_detail.rs @@ -2,7 +2,7 @@ /// ## Usage and Examples /// -/// `DiscardDetail` satisfies the wrapping capability by returning the error and dropping the detail. +/// `DiscardDetail` satisfies the wrapping trait by returning the error and dropping the detail. /// Here a base error is raised and then wrapped with a detail string; because the wrapper is /// `DiscardDetail`, the detail is discarded and the base error propagates unchanged. pub mod wrapping_by_discarding { From b3cfd92b104f50319ca1a6e2ff7cf9d1a895da85 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 19 Sep 2026 13:42:14 +0000 Subject: [PATCH 079/516] Update cgp-skills --- cgp-skills | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgp-skills b/cgp-skills index 80cbf512..85481690 160000 --- a/cgp-skills +++ b/cgp-skills @@ -1 +1 @@ -Subproject commit 80cbf5123fa2b27717953d0a3fec38ccdafbafe6 +Subproject commit 85481690c389efc9ba2e7550db53df7e37a0822e From 6994b58772241ae4a1926638a52eb694b434328a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 20 Sep 2026 05:51:43 +0000 Subject: [PATCH 080/516] Add the Comparisons section Publish eleven comparison pages and a hand-written index under docs/comparisons/, one page per internal related-work document: Rust's own proposals, policy-based design, type classes, ML modules, implicit parameters, algebraic effects, row polymorphism, dependency injection, dynamic dispatch, reflection, and capabilities. Each page maps CGP into the reader's vocabulary, shows the two side by side, states what each costs, and says where the other tool is the better choice. Place the category after Concepts and renumber Reference, cargo-cgp, AI, Resources, and Contribute. Add a comparison link to the onward reading of the fourteen Concepts pages whose idea has one. Mirror every page's CGP code in example-code/tests/comparisons/ with a check per wired context, pin RFC 1210's specialization snippet as a compile-fail fixture, and add anyhow and cap-std as dev-dependencies. State on the disclosure page that the author reads each comparison page's two judging sections in full. Co-Authored-By: Claude Fable 5.1 --- docs/ai/_category_.json | 2 +- docs/ai/disclaimer.md | 7 +- docs/cargo-cgp/_category_.json | 2 +- docs/comparisons/_category_.json | 8 + docs/comparisons/algebraic-effects.md | 407 +++++++++++++++++ docs/comparisons/capabilities.md | 385 ++++++++++++++++ docs/comparisons/dependency-injection.md | 294 ++++++++++++ docs/comparisons/dynamic-dispatch.md | 332 ++++++++++++++ docs/comparisons/implicit-parameters.md | 325 ++++++++++++++ docs/comparisons/index.md | 57 +++ docs/comparisons/ml-modules.md | 339 ++++++++++++++ docs/comparisons/policy-based-design.md | 425 ++++++++++++++++++ docs/comparisons/reflection.md | 372 +++++++++++++++ docs/comparisons/row-polymorphism.md | 346 ++++++++++++++ docs/comparisons/rust-language-proposals.md | 406 +++++++++++++++++ docs/comparisons/type-classes.md | 383 ++++++++++++++++ docs/concepts/abstract-types.md | 2 + docs/concepts/aggregate-providers.md | 1 + docs/concepts/check-traits.md | 1 + docs/concepts/coherence.md | 2 + docs/concepts/consumer-and-provider-traits.md | 2 + docs/concepts/extensible-records.md | 2 + docs/concepts/extensible-variants.md | 1 + docs/concepts/handlers.md | 1 + docs/concepts/higher-order-providers.md | 2 + docs/concepts/impl-side-dependencies.md | 2 + docs/concepts/implicit-arguments.md | 2 + docs/concepts/modular-error-handling.md | 1 + docs/concepts/modularity-hierarchy.md | 1 + docs/concepts/namespaces.md | 1 + docs/contribute.md | 2 +- docs/reference/_category_.json | 2 +- docs/resources.md | 2 +- example-code/Cargo.toml | 2 + example-code/README.md | 2 + .../tests/comparisons/algebraic_effects.rs | 129 ++++++ .../tests/comparisons/capabilities.rs | 98 ++++ .../tests/comparisons/dependency_injection.rs | 196 ++++++++ .../tests/comparisons/dynamic_dispatch.rs | 211 +++++++++ .../tests/comparisons/implicit_parameters.rs | 110 +++++ example-code/tests/comparisons/ml_modules.rs | 113 +++++ example-code/tests/comparisons/mod.rs | 17 + .../tests/comparisons/policy_based_design.rs | 164 +++++++ example-code/tests/comparisons/reflection.rs | 118 +++++ .../tests/comparisons/row_polymorphism.rs | 117 +++++ .../comparisons/rust_language_proposals.rs | 159 +++++++ .../tests/comparisons/type_classes.rs | 118 +++++ example-code/tests/comparisons_tests.rs | 10 + .../rust_language_proposals_specialization.rs | 16 + ...t_language_proposals_specialization.stderr | 18 + 50 files changed, 5708 insertions(+), 7 deletions(-) create mode 100644 docs/comparisons/_category_.json create mode 100644 docs/comparisons/algebraic-effects.md create mode 100644 docs/comparisons/capabilities.md create mode 100644 docs/comparisons/dependency-injection.md create mode 100644 docs/comparisons/dynamic-dispatch.md create mode 100644 docs/comparisons/implicit-parameters.md create mode 100644 docs/comparisons/index.md create mode 100644 docs/comparisons/ml-modules.md create mode 100644 docs/comparisons/policy-based-design.md create mode 100644 docs/comparisons/reflection.md create mode 100644 docs/comparisons/row-polymorphism.md create mode 100644 docs/comparisons/rust-language-proposals.md create mode 100644 docs/comparisons/type-classes.md create mode 100644 example-code/tests/comparisons/algebraic_effects.rs create mode 100644 example-code/tests/comparisons/capabilities.rs create mode 100644 example-code/tests/comparisons/dependency_injection.rs create mode 100644 example-code/tests/comparisons/dynamic_dispatch.rs create mode 100644 example-code/tests/comparisons/implicit_parameters.rs create mode 100644 example-code/tests/comparisons/ml_modules.rs create mode 100644 example-code/tests/comparisons/mod.rs create mode 100644 example-code/tests/comparisons/policy_based_design.rs create mode 100644 example-code/tests/comparisons/reflection.rs create mode 100644 example-code/tests/comparisons/row_polymorphism.rs create mode 100644 example-code/tests/comparisons/rust_language_proposals.rs create mode 100644 example-code/tests/comparisons/type_classes.rs create mode 100644 example-code/tests/comparisons_tests.rs create mode 100644 example-code/tests/compile_fail/comparisons/rust_language_proposals_specialization.rs create mode 100644 example-code/tests/compile_fail/comparisons/rust_language_proposals_specialization.stderr diff --git a/docs/ai/_category_.json b/docs/ai/_category_.json index 826f60f3..81b2fb9d 100644 --- a/docs/ai/_category_.json +++ b/docs/ai/_category_.json @@ -1,6 +1,6 @@ { "label": "AI Assisted Development", - "position": 7, + "position": 8, "link": { "type": "generated-index" } diff --git a/docs/ai/disclaimer.md b/docs/ai/disclaimer.md index 124949dc..c0645fb2 100644 --- a/docs/ai/disclaimer.md +++ b/docs/ai/disclaimer.md @@ -39,8 +39,11 @@ produced. It provides a record of contributions, not a guarantee that every stat **Human review varies by page.** The author sets the writing rules and priorities and reads the front page, Concepts explanation pages, reference index, this disclosure, and every blog post in full -before publication. Individual construct reference pages follow a writing guide and receive spot -checks; the author does not read each one line by line. +before publication. On each Comparisons page, which describes another community's tool beside CGP, +the author reads in full the two sections that judge that tool: what each approach costs, and where +the other tool is the better choice. Individual construct reference pages, and the remaining sections +of a comparison page, follow a writing guide and receive spot checks; the author does not read each +one line by line. Source verification and human review serve different purposes. Checking a macro expansion against the source can reveal a technical mistake, while reading an explanation can reveal a misleading diff --git a/docs/cargo-cgp/_category_.json b/docs/cargo-cgp/_category_.json index b839d716..0c0e9b09 100644 --- a/docs/cargo-cgp/_category_.json +++ b/docs/cargo-cgp/_category_.json @@ -1,6 +1,6 @@ { "label": "cargo-cgp", - "position": 6, + "position": 7, "link": { "type": "doc", "id": "cargo-cgp/index" diff --git a/docs/comparisons/_category_.json b/docs/comparisons/_category_.json new file mode 100644 index 00000000..641f0b5c --- /dev/null +++ b/docs/comparisons/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Comparisons", + "position": 5, + "link": { + "type": "doc", + "id": "comparisons/index" + } +} diff --git a/docs/comparisons/algebraic-effects.md b/docs/comparisons/algebraic-effects.md new file mode 100644 index 00000000..5e5ed0f0 --- /dev/null +++ b/docs/comparisons/algebraic-effects.md @@ -0,0 +1,407 @@ +--- +sidebar_label: 'Algebraic effects' +sidebar_position: 6 +description: 'CGP read against the effect handlers of Koka, OCaml 5, Flix, and Eff: the exactly-once fragment it shares and the continuation power it does not.' +--- + +# Algebraic effects and handlers + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows +algebraic effects and handlers from Koka, OCaml 5, Flix, or Eff. CGP shares the split between an +operation and its interpretation, and the idea of choosing the interpretation from the surroundings, +but it keeps only the fragment in which the continuation is used exactly once and in place. The +literature identifies that fragment as dynamic binding, and CGP resolves it statically per context +rather than dynamically down a call stack. The page covers the correspondence, the boundary, where +effect handlers remain the only tool, and what to expect that differs. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. In most CGP code it is a type you define to stand for an application, and it plays the part +of the dynamic scope in which handlers are installed. + +| In an effect system | In CGP | +| --- | --- | +| An effect signature | A **component**: one trait with many possible implementations | +| An operation | A method of that trait | +| A handler | A **provider**: a named implementation, always tail-resumptive | +| Installing a handler with `with` or `run ... with handler` | **Wiring** the provider on a context | +| The effect row a function performs | The provider's **impl-side dependencies**, declared with `#[uses]` | +| A type error for an unhandled effect | A `check_components!` failure at the wiring site | +| The continuation | Nothing: a provider returns exactly once | + +## The idea, briefly + +Algebraic effects let code perform an effect without fixing how the effect is carried out. A function +that reads configuration, logs, throws, or suspends normally commits to a concrete mechanism, and +that commitment leaks into its type. With algebraic effects the function *performs an operation* +named by an abstract effect, and a *handler* installed up the call stack gives the operation its +meaning, so the same code runs against a real logger, a test collector, or a no-op. + +### Operations, handlers, and the continuation + +An *effect* is a signature of *operations*, and a computation produces the effect by performing one +of them. Plotkin and Power founded the idea, and the account is *algebraic* because each effect came +with an equational theory whose free model induces the monad for that effect +([Plotkin & Pretnar, *Handling Algebraic Effects*](https://homepages.inf.ed.ac.uk/gdp/publications/handling-algebraic-effects.pdf)). +A *handler* interprets the operations, and its defining power is that it receives the *continuation*: +the suspended rest of the computation from the point where the operation was performed +([Pretnar, *An Introduction to Algebraic Effects and Handlers*](https://www.eff-lang.org/handlers-tutorial.pdf)). +An exception handler can only abandon the computation; an effect handler can resume it. + +How many times a handler invokes the continuation determines the effect it realizes, and the three +cases mark where CGP can and cannot follow: + +- **Zero times.** The handler discards the continuation. This is exception behavior. +- **Once.** The handler resumes with a result. This is the ordinary case: reading state, dynamic + binding, logging, any call that yields a value and lets the caller carry on. +- **Many times.** The handler resumes more than once. This is nondeterminism, generators, and + cooperative scheduling, and it cannot be expressed as an ordinary function return. + +### Effect typing + +Languages differ sharply in whether a computation's type records the effects it may perform. Koka +types effects as a *row*, so `` in a signature means the function may throw and diverge +([Leijen, *Algebraic Effects for Functional Programming*](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/08/algeff-tr-2016-v2.pdf)); +the [row polymorphism](./row-polymorphism.md) page covers the row machinery. Flix types effects as a +set and uses the result for purity reflection +([Madsen et al., *Programming with Purity Reflection*](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2023.18)). +Eff and OCaml 5 track no effects in types: the OCaml manual states that "the compiler does not +statically ensure that all the effects performed by the program are handled", and an unhandled effect +raises `Effect.Unhandled` at run time ([OCaml manual](https://ocaml.org/manual/5.5/effects.html)). + +### The same effect in three languages + +In **Koka**, an operation is declared `ctl` (may resume any number of times), `fun` (resumes exactly +once in place), or `val`. A handler is installed with `with`: + +```koka +effect fun ask() : int // one `fun` operation; the effect is also named `ask` + +fun add-twice() : ask int + ask() + ask() + +fun main() : console () + with fun ask() 21 // install a handler that supplies 21 + println( add-twice() ) // 42 +``` + +The Koka book describes `with fun ask() 21` as a "statically typed dynamic binding" and notes that a +`fun` operation "behaves just like a regular function without changing the control-flow" +([Koka book](https://koka-lang.github.io/koka/doc/book.html#sec-opfun)). A `ctl` operation is the +multi-shot form; the book's `choice` handler resumes twice to collect every outcome: + +```koka +effect ctl choice() : bool + +fun choice-all(action : () -> a) : e list + with handler + return(x) [x] + ctl choice() resume(False) ++ resume(True) + action() +``` + +In **OCaml 5**, an effect extends the type `Effect.t`, is performed with `perform`, and is handled +with a `match` whose `effect` cases bind the continuation `k`. The `effect` pattern syntax arrived in +OCaml 5.3; earlier code used `Effect.Deep.try_with`: + +```ocaml +open Effect + +type _ Effect.t += Ask : int Effect.t + +let add_twice () = perform Ask + perform Ask + +let () = + let result = + match add_twice () with + | v -> v + | effect Ask, k -> Effect.Deep.continue k 21 + in + print_int result (* 42 *) +``` + +OCaml's continuations are one-shot: "every captured continuation must be resumed either with a +`continue` or `discontinue` exactly once" ([OCaml manual](https://ocaml.org/manual/5.5/effects.html)). + +In **Flix**, an effect is declared with `eff`, appears in a function type after a backslash, and is +handled with `run ... with handler`: + +```flix +eff Ask { + def ask(): Int32 +} + +def addTwice(): Int32 \ Ask = + Ask.ask() + Ask.ask() + +def main(): Unit \ IO = + let result = run { + addTwice() + } with handler Ask { + def ask(k) = k(21) + }; + println(result) // 42 +``` + +`\ Ask` is part of `addTwice`'s type, and `main` must discharge it +([Flix documentation](https://doc.flix.dev/effects-and-handlers.html)). + +### The fragment CGP corresponds to + +A handler that resumes the continuation exactly once, in tail position, is dynamic binding. The +literature names its canonical example outright: **the canonical tail-resumptive handler is dynamic +binding** ([Xie et al., *Effect Handlers, Evidently*](https://www.microsoft.com/en-us/research/wp-content/uploads/2020/07/evidently-5f0b7dbc1a998.pdf)). +Such a handler never needs to capture the continuation, so a compiler can run the operation in place +and replace the dynamic search for a handler with a constant-offset lookup into an *evidence vector* +passed down like a dictionary ([Xie & Leijen, *Generalized Evidence Passing*](https://xnning.github.io/papers/multip.pdf)). +The efficient compilation of the exactly-once fragment *is* dictionary passing, and that is the +fragment CGP occupies directly, with no dynamic search underneath. Effekt and Scala's capture checking +describe the same fragment as *effects as capabilities*; the [capabilities](./capabilities.md) page +places CGP against that reading. + +## How CGP expresses it + +CGP reproduces the operations-and-handlers structure with its consumer and provider split, and every +CGP "handler" is an ordinary function that returns once. The correspondence is exact for the +tail-resumptive case and stops wherever an effect would reach for the continuation. The contexts below +are **environmental contexts**: the `App` that installs a `Loader` or a `Greeter` stands for an +application, as a handler's dynamic scope does, and every component shown is self-targeted. + +### Components are effect signatures; providers are tail-resumptive handlers + +Declaring a component names an operation without giving it meaning, and a provider interprets it: + +```rust +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) { + println!("Hello!"); + } +} + +delegate_components! { App { GreeterComponent: GreetHello } } +``` + +`CanGreet` is the effect signature, `greet` the operation, `GreetHello` the handler, and the wiring +line its installation. The provider's body receives no continuation and cannot choose whether to +resume: it computes a value and returns, and the caller resumes in place, exactly once. In Koka's +terms every CGP provider is a `fun` operation and never a `ctl` one. + +### Reading from the context is dynamic binding, exactly + +Koka's `with fun ask() 21` installs a tail-resumptive handler that supplies a value to deeply nested +code without threading it through every call. CGP's [implicit arguments](/docs/concepts/implicit-arguments) +do the same by reading a field from the context that every provider receives as `self`: + +```rust +#[cgp_fn] +pub fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") +} +``` + +The context supplies `name`, not the caller, as the enclosing `ask` handler supplies Koka's `ask()`. +The equivalence is exact rather than an analogy: the reader effect is the canonical tail-resumptive +handler, and reading a context field is CGP's whole realization of it. The two part ways on how the +value is found. Koka searches the dynamic handler stack; CGP reads a field of a statically known +context. The [implicit parameters](./implicit-parameters.md) page covers the same pattern from +Scala's side. + +### Raising an error looks like `raise` but passes a value, not control + +CGP's error handling shows the boundary most sharply. `CanRaiseError` reads like the +`raise` operation, and a provider raises without knowing the concrete error type: + +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} + +#[cgp_impl(new LoadOrFail)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + return Err(Self::raise_error("empty path".to_owned())); + } + Ok(format!("contents of {path}")) + } +} +``` + +The raise components dispatch per source type, so a context routes each source error to a different +strategy, which reads like installing one exception handler per exception type: + +```rust +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + LoaderComponent: LoadOrFail, + + @ErrorRaiserComponent.String: RaiseFrom, + } +} +``` + +The resemblance stops at *selection*. An effect `raise` is the zero-resume handler: it abandons the +continuation and unwinds to the handler. CGP's `raise_error` unwinds nothing. It constructs and +returns a value of the abstract `Error` type, and the abort is Rust's own `return` or `?`, outside +the wiring. CGP selects the interpretation of the error and leaves the control flow to `Result`. The +[Modular error handling](/docs/concepts/modular-error-handling) page develops the construct. + +### Impl-side dependencies are the effect row; `check_components!` is "all effects handled" + +A provider states its needs as [impl-side dependencies](/docs/concepts/impl-side-dependencies), such +as the `#[uses(CanRaiseError)]` above. That list is CGP's counterpart of the effect row Koka +would infer for a function that performs `raise`, and a generic provider is effect-polymorphic in a +loose sense, since the context type variable stands for "whatever else this context can do". +[`check_components!`](/docs/reference/macros/check_components) is the discharge check: + +```rust +check_components! { + App { + LoaderComponent, + } +} +``` + +This asserts that `App` supplies every trait `LoadOrFail` transitively needs, and it fails to compile +naming the missing one if not. That is Koka's guarantee that an unhandled effect is a type error, and +the opposite of OCaml's runtime `Effect.Unhandled`. + +### Configuring abstract types through the same wiring + +CGP extends the operations-and-handlers wiring to something effect systems do not touch: abstract +*types*. Alongside choosing the provider for an operation, a context chooses the concrete type behind +an [abstract type](/docs/concepts/abstract-types) through the same table: + +```rust +use cgp::core::error::ErrorTypeProviderComponent; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} +``` + +An effect handler interprets operations, which are values and computations. It has no notion of +supplying a *type member* the way `HasErrorType` supplies `Error`. The table that says "raise errors +this way" also says "and the error type is `anyhow::Error`". + +### A closer theoretical fit: coeffects + +The *coeffect* framework may describe CGP more precisely than the effect framework does. Where an +effect describes what a computation produces or performs, a coeffect describes what a computation +*requires from its environment* ([Petricek, *Coeffects*](https://tomasp.net/coeffects/)). A CGP +context carries exactly such requirements, resolved all at once when a concrete context is defined, +and the framing also accounts for the abstract-type extension above, which an effect handler has no +place for. The connection is a pointer rather than a developed account. + +## What each approach costs + +Algebraic effects are valued for ending *function coloring*, since code between the operation and its +handler needs no awareness of the effect +([Abramov, *Algebraic Effects for the Rest of Us*](https://overreacted.io/algebraic-effects-for-the-rest-of-us/)), +for separating an effect's interface from its semantics, and for composing handlers where monad +transformers are painful ([*Why Algebraic Effects?*, Ante](https://antelang.org/blog/why_effects/)). +Their costs, as their users state them, fall into three clusters. Unfamiliarity and control-flow +opacity: following control from a `perform` to the handler that catches it is as hard as reasoning +about a distant exception handler ([Ante](https://antelang.org/blog/why_effects/)). Performance: +general handlers must capture continuations, and non-tail handlers remain more expensive than native +control flow even after evidence passing ([Xie & Leijen, 2021](https://xnning.github.io/papers/multip.pdf)). +And, in the untyped designs, an unhandled effect is a runtime crash rather than a compile error, and +OCaml's one-shot restriction rules out the multi-shot uses ([OCaml manual](https://ocaml.org/manual/5.5/effects.html)). +Readers who reach effects from Haskell know the type-class-based effect libraries and their +n²-instances problem, which handler-based systems avoid +([`fused-effects`](https://hackage.haskell.org/package/fused-effects)). + +CGP's costs are the ordinary ones. A component has to be declared before it can have providers, and +the wiring is code somebody writes. The compile-time work is real. And the raw diagnostics are +trait-solver output over generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the +root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape +every class. CGP also keeps even less of the "algebraic" than the practical effect languages do: it +has no equational theory relating its operations. Since Koka, OCaml, and Flix mostly drop the laws +too, this is a shared simplification. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) +page weighs CGP's costs against the alternatives. + +## Where effect handlers are the only tool + +When a program needs the continuation, for a scheduler, a generator, a backtracking solver, or a +suspendable coroutine, algebraic effects are the right and only tool of the two. Emulating them with +CGP is not possible, because a provider never captures a continuation. CGP does have an +[async handler family](/docs/concepts/handlers) and [type-level DSLs](/docs/concepts/type-level-dsls) +that interpret a `Code` tag by dispatching to a provider, which is the closest CGP comes to the +operations-and-interpreters shape, but even there the interpretation is a straight call chain resolved +at compile time. Async in CGP is Rust's own `async` and `await` threaded through provider calls. + +## What to expect that differs + +**A provider returns exactly once.** There is no `resume` to call zero times or twice, because there +is no reified continuation. CGP takes the fragment of effect handlers the literature identifies as +dynamic binding, the fragment that compiles to direct calls, and builds everything on it. + +**Handlers are chosen by the context's type, not by dynamic scope.** The nearest handler on the +runtime stack does not win, because there is no stack of handlers. A CGP provider is fixed once in a +wiring table and resolved through the trait system. + +**The wiring is a set, not a stack.** An effect handler stack is ordered, and reordering handlers +changes results: state over nondeterminism and nondeterminism over state compute different things +([Kammar, Lindley & Oury, *Handlers in Action*](https://denotational.co.uk/publications/kammar-lindley-oury-handlers-in-action.pdf)). +CGP's table has one provider per component with no nesting to shadow an outer handler and no order to +permute, and because dispatch is exactly-once and resume-in-place, the non-commutativity never arises. + +**Abstract types are a requirement kind effect systems lack.** A context fixes a type as well as an +operation's interpretation, through the same table. + +**CGP is not an effect system.** It has no continuations, no dynamic scope, and no effect kind in the +type system. It is the exactly-once, resume-in-place fragment of effect handlers, which is dynamic +binding, made into a compile-time, per-context, type-directed wiring mechanism that also configures +abstract types. + +## Where to go next + +- [Modular error handling](/docs/concepts/modular-error-handling): the error type, its raising, and + its wrapping as three wiring decisions. +- [Implicit arguments](/docs/concepts/implicit-arguments): the dynamic-binding fragment on its own + terms. +- [Handlers](/docs/concepts/handlers): CGP's computation family, and where async lives in it. +- [Capabilities](./capabilities.md): the effects-as-capabilities reading of the same fragment. +- [Row polymorphism](./row-polymorphism.md): the row types Koka uses for its effect rows. + +## Sources + +The Koka `ask` snippet was compiled with Koka 3.2.3, and the `choice` handler follows the Koka book's +own example; the OCaml snippet was compiled with OCaml 5.5.0 and the Flix snippet run with Flix +0.76.0. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` +assertion per wired context. + +- [Plotkin & Pretnar, *Handling Algebraic Effects* (LMCS 2013)](https://homepages.inf.ed.ac.uk/gdp/publications/handling-algebraic-effects.pdf) and [*Handlers of Algebraic Effects* (ESOP 2009)](https://homepages.inf.ed.ac.uk/gdp/publications/Effect_Handlers.pdf): effects as operations with an equational theory and handlers interpreting them through the continuation. +- [Pretnar, *An Introduction to Algebraic Effects and Handlers*](https://www.eff-lang.org/handlers-tutorial.pdf): the tutorial account and the Eff language. +- [Leijen, *Algebraic Effects for Functional Programming*](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/08/algeff-tr-2016-v2.pdf) and [the Koka book](https://koka-lang.github.io/koka/doc/book.html): row-typed effects, the `ctl`/`fun`/`val` kinds, and evidence passing for `fun` operations. +- [Xie et al., *Effect Handlers, Evidently* (ICFP 2020)](https://www.microsoft.com/en-us/research/wp-content/uploads/2020/07/evidently-5f0b7dbc1a998.pdf) and [Xie & Leijen, *Generalized Evidence Passing for Effect Handlers* (ICFP 2021)](https://xnning.github.io/papers/multip.pdf): the tail-resumptive handler as dynamic binding, and its dictionary-passing compilation. +- [OCaml manual, *Effect handlers* (5.5)](https://ocaml.org/manual/5.5/effects.html) and [Sivaramakrishnan et al., *Retrofitting Effect Handlers onto OCaml*](https://kcsrk.info/slides/handlers_edinburgh.pdf): the 5.3 syntax, one-shot continuations, and the absence of effect typing. +- [Flix, *Effects and Handlers*](https://doc.flix.dev/effects-and-handlers.html) and [Madsen et al., *Programming with Purity Reflection* (ECOOP 2023)](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2023.18): the set-based effect system and purity reflection. +- [Kammar, Lindley & Oury, *Handlers in Action* (ICFP 2013)](https://denotational.co.uk/publications/kammar-lindley-oury-handlers-in-action.pdf): handler composition and the significance of handler order. +- [Petricek, *Coeffects*](https://tomasp.net/coeffects/): the framework describing what a computation requires from its environment. +- [Abramov, *Algebraic Effects for the Rest of Us*](https://overreacted.io/algebraic-effects-for-the-rest-of-us/) and [*Why Algebraic Effects?* (Ante)](https://antelang.org/blog/why_effects/): community accounts of what users value and dislike. +- [`fused-effects`](https://hackage.haskell.org/package/fused-effects): the type-class-based effect libraries and the n²-instances problem. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/capabilities.md b/docs/comparisons/capabilities.md new file mode 100644 index 00000000..357c2238 --- /dev/null +++ b/docs/comparisons/capabilities.md @@ -0,0 +1,385 @@ +--- +sidebar_label: 'Capabilities' +sidebar_position: 11 +description: 'The five things "capability" names, and which of them CGP resembles: object capabilities, capability-based security, effects as capabilities, and the Rust community''s uses.' +--- + +# Capabilities + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows +"capabilities" in one of the several senses the word carries: the object-capability model of E and +Pony, capability-based security in seL4, WASI, or `cap-std`, effects as capabilities in Effekt and +Scala, or the Rust community's use of the word for an allocator or runtime a function should receive +without a parameter. CGP is capability-like in the last two senses and is not a capability system in +the first. The page separates the senses, says which requirements CGP meets, and gives a compact way +to say "capability-like, but not a capability system". + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. In most CGP code it is a type you define to stand for an application. + +| In a capability system | In CGP | +| --- | --- | +| A requirement a computation places on its context (Effekt, Scala) | An **impl-side dependency**: `#[uses]` for a trait, `#[implicit]` for a value | +| The handler or scope that supplies it | The context, and constructing a value of it | +| A capability value passed to code that needs it | A field of the context, read by the providers that declare it | +| Static discharge of every requirement | `check_components!` | +| An unforgeable reference (E, Pony, WASI) | No counterpart: a CGP bound is a requirement, not a token | +| Removal of ambient authority | No counterpart: Rust keeps `std` and globals reachable | + +## The idea, briefly + +"Capability" names at least five different things, and a reader who asks for capabilities in Rust +rarely says which. The senses are separated below by the property each insists on. + +### The object-capability model + +A capability, in the sense Dennis and Van Horn introduced in 1966 and Mark Miller made precise for +programming languages, is "a communicable, unforgeable token of authority" that refers to an object +together with the rights to use it ([Wikipedia, *Capability-based security*](https://en.wikipedia.org/wiki/Capability-based_security)). +The object-capability model identifies that token with an ordinary object reference: to hold the +reference is to hold the authority. Three properties define it. *No designation without authority*: +naming a resource and being allowed to use it are the same act. *No ambient authority*: a request +either carries a capability or fails, so global functions such as `open()` are the counterexample +([Miller, Yee & Shapiro, *Capability Myths Demolished*](https://papers.agoric.com/assets/pdf/papers/capability-myths-demolished.pdf)). +And authority spreads only along existing references: "only connectivity begets connectivity" +([Miller, *Robust Composition*](https://papers.agoric.com/assets/pdf/papers/robust-composition.pdf)), +so reachability in the object graph bounds what any object can do, which is the reasoning the +*principle of least authority* rests on. Delegation is passing the reference, attenuation is wrapping +it, and revocation is closing a gate in the wrapper, all runtime acts on runtime values. The languages +built on the model, E, Pony, Newspeak, Austral, and Hardened JavaScript, remove global mutable state +and global I/O, because a global is ambient authority. Pony's tutorial states the rule: global +variables are "ambient authority", so Pony has none, and a program obtains file access only from the +`env.root` authority its `Main` actor is handed +([Pony tutorial, *Object Capabilities*](https://tutorial.ponylang.io/object-capabilities/object-capabilities.html)): + +```pony +use "files" + +actor Main + new create(env: Env) => + // `env.root` is the only source of authority; it is passed in, never global. + let auth: FileAuth = FileAuth(env.root) + let path = FilePath(auth, "/var/app/config.txt") + match OpenFile(path) + | let file: File => env.out.print(file.read_string(100)) + else env.out.print("could not open") + end +``` + +### Capability-based security in systems + +The same model applied below the language gives a process handles to kernel objects and no other way +to name them: KeyKOS, seL4, Fuchsia, and Capsicum, with CHERI moving it into hardware +([CHERI](https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/)). WASI "has no ambient +authorities" and its handles "are unforgeable" +([WASI design principles](https://github.com/WebAssembly/WASI/blob/main/docs/DesignPrinciples.md)). +Rust's `cap-std` brings the discipline to the standard library's surface: its APIs "don't access +files, directories, network addresses, clocks, or other external resources implicitly, but instead +operate on handles that are explicitly passed in", the one exercise of ambient authority is marked by +an explicit `ambient_authority()` argument, and the crate is candid that it "can't prevent arbitrary +Rust code from using `std::fs`'s path-oriented APIs" +([Gohman, *Introducing cap-std*](https://blog.sunfishcode.online/introducing-cap-std/)). Compiled with +`cap-std` 3: + +```rust +use cap_std::ambient_authority; +use cap_std::fs::Dir; + +fn read_config(dir: &Dir) -> std::io::Result { + // `dir` is the only authority this function holds; it cannot reach outside it. + let mut text = String::new(); + std::io::Read::read_to_string(&mut dir.open("config.txt")?, &mut text)?; + Ok(text) +} + +// Ambient authority is exercised once, and the call marks it. +let dir = Dir::open_ambient_dir("/var/app", ambient_authority())?; +read_config(&dir)?; +dir.open("../secret.txt") // Err: a path led outside of the filesystem +``` + +### Two senses that share only the word + +Linux "capabilities" divide the superuser's privileges into units such as `CAP_NET_BIND_SERVICE`, +held as a per-thread attribute ([capabilities(7)](https://man7.org/linux/man-pages/man7/capabilities.7.html)). +They are privilege bits, not references to resources. Pony's *reference capabilities*, `iso`, `trn`, +`ref`, `val`, `box`, and `tag`, are aliasing qualifiers whose purpose is data-race freedom +([Pony tutorial, *Reference Capabilities*](https://tutorial.ponylang.io/reference-capabilities/)). A +Rust reader already has that second thing as ownership, `&`, and `&mut`. Neither sense enters the CGP +comparison. + +### Effects as capabilities + +Effekt's designers describe their language as "effects as capabilities": "effect types express which +capabilities a computation requires from its context", given semantics by translation to a calculus in +explicit capability-passing style +([Brachthäuser, Schuster & Ostermann, OOPSLA 2020](https://dl.acm.org/doi/10.1145/3428194)). A +capability here is a value a handler introduces and that must be in scope for an operation to be +performed, and to keep this sound Effekt treats capabilities as second-class: passable down, not +returned or stored. Scala 3's experimental *capture checking* reaches the same place: a capability is +a parameter or local whose type carries a capture set, and the checker prevents it escaping the scope +that introduced it ([Scala 3 Reference, *Capture Checking*](https://docs.scala-lang.org/scala3/reference/experimental/cc.html)). +The concrete application is `CanThrow`, an erased class: a `throw` requires a `CanThrow[E]`, and a +`try` creates one. Compiled with Scala 3.8.4: + +```scala +import language.experimental.saferExceptions + +class LimitExceeded extends Exception +val limit = 10e9 + +def f(x: Double): Double throws LimitExceeded = + if x < limit then x * x else throw LimitExceeded() + +try println(List(1.0, 2.0, 3.0).map(f).sum) // the try supplies the CanThrow capability +catch case ex: LimitExceeded => println("too large") +``` + +This sense keeps one thing from the object-capability model, that authority to perform an operation is +a value the context supplies, and drops the runtime half. It is a *static* discipline, which is why it +is the sense CGP can be compared with directly. + +### The Rust community's word + +Rust programmers use the word in three threads. The first is *implicit values*: Tyler Mandry's +contexts-and-capabilities proposal declares a `capability` such as an arena and lets an impl require it +in a `with` clause, so an allocator or logger need not be threaded through every signature +([Mandry](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)), and Yoshua Wuyts +describes the pain: "the global allocator acts, in a capability-sense, as an ambient authority" +([Wuyts, *Nesting Allocators*](https://blog.yoshuawuyts.com/nesting-allocators)). The second is +*sandboxing*, the object-capability sense proper, as in `cap-std` and WASI. The third is *ownership +tokens*: the embedded Rust book makes each peripheral a value obtained once, so that "to call the +`read_speed()` method, we must have ownership or a reference to a `SerialPort` structure" +([Embedded Rust Book](https://docs.rust-embedded.org/book/peripherals/singletons.html)), and PermRust +generalizes the idea into a token-based permission system +([Gehring, Rehms & Tschorsch](https://arxiv.org/abs/2506.11701)). A reader who wants "capabilities in +Rust" may mean any of the three. + +### The properties that tell the senses apart + +| Property | Object capabilities | Effects as capabilities | Rust contexts proposal | Ownership tokens | +| --- | --- | --- | --- | --- | +| Designation and authority are one reference | yes | partly | no: a named implicit value | yes, for the resource the token stands for | +| No ambient authority, enforced | yes, by removing globals | no, unless the language also removes them | no | no | +| Unforgeable | yes | yes, by private constructors or erasure | not addressed | yes, by a private constructor | +| Provisioned at runtime | yes | value at runtime, scope lexical | value at runtime, binding lexical | value at runtime | +| Delegation, attenuation, revocation | all three, at runtime | delegation and attenuation; no revocation | delegation by scope | delegation by move or borrow | +| Confinement reasoning | reachability in the object graph | capture sets bound escape | not addressed | ownership bounds aliasing | + +## How CGP expresses it + +CGP shares the effects-as-capabilities reading almost exactly and the object-capability reading only in +part. A provider's [impl-side dependencies](/docs/concepts/impl-side-dependencies) are the requirements +a computation places on its context, the context supplies them, and +[`check_components!`](/docs/reference/macros/check_components) verifies that every requirement is met. +CGP does not remove ambient authority, does not make its requirements unforgeable, and does not +provision them at runtime. + +### A requirement on the context is a capability in the effect-system sense + +A provider declares what it needs with `#[uses]` for traits and `#[implicit]` for values, and the +consumer trait a caller invokes hides both: + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} + +#[derive(HasField)] +pub struct App { + pub name: String, +} + +delegate_components! { + App { + GreeterComponent: GreetHello, + } +} + +check_components! { App { GreeterComponent } } +``` + +Read as an effect type, `GreetHello` requires one thing of its context, a `name` field, and `App` +supplies it. Constructing `App { name }` is the `try` that supplies a `CanThrow`, or the `with` block +that supplies Mandry's arena. The parallel extends to the type level: an +[abstract type](/docs/concepts/abstract-types) such as a context's `Error` is a requirement the +context discharges by wiring, which no capability system expresses. `App` here is an **environmental +context**, a type standing for an application, and `GreetHello` is self-targeted. + +### An object capability can live in the context + +Where the value a provider requires is itself an object capability, CGP carries it and adds a static +check that it reaches the code that needs it. A `cap-std` `Dir` stored as a context field is an object +capability in the model's sense, and a provider that reads configuration through it holds no other +filesystem authority in its body. This compiles against `cgp` `0.8.0-alpha` and `cap-std` 3: + +```rust +use cap_std::fs::Dir; + +#[cgp_component(ConfigReader)] +pub trait CanReadConfig { + fn read_config(&self) -> std::io::Result; +} + +#[cgp_impl(new ReadConfigFromDir)] +impl ConfigReader { + fn read_config(&self, #[implicit] config_dir: &Dir) -> std::io::Result { + let mut text = String::new(); + std::io::Read::read_to_string(&mut config_dir.open("config.txt")?, &mut text)?; + Ok(text) + } +} + +#[derive(HasField)] +pub struct App { + pub config_dir: Dir, +} + +delegate_components! { + App { + ConfigReaderComponent: ReadConfigFromDir, + } +} + +check_components! { App { ConfigReaderComponent } } +``` + +The division of labor is the point. `cap-std` supplies the unforgeable handle and the runtime +confinement; CGP supplies the declaration that `ReadConfigFromDir` needs a `Dir` and the compile-time +check that `App` has one. The same arrangement serves an arena-allocating deserializer, where the +arena is a context field and the provider reads it as an implicit argument, which the +[Rust proposals](./rust-language-proposals.md) page relates to Mandry's example. + +### CGP does not remove ambient authority + +The property that makes a language capability-safe is that code can reach only what it is handed, and +Rust does not have it. `ReadConfigFromDir` could call `std::fs::File::open("/etc/passwd")` in its +body and CGP would neither notice nor object. The provider's declared requirements bound what it +reaches *through the context*, which is useful for reading and for testing, but they do not bound what +it reaches through `std`, through statics, or through the global allocator. A capability-safe language +forbids the global; CGP is a library in a language that permits it. A page that suggested a CGP +provider is confined to its declared dependencies would be claiming something Rust cannot deliver. + +### A requirement is not an unforgeable token + +An object capability is unforgeable because the only way to obtain the reference is to be given it. A +CGP requirement is a trait bound on the context, and any context that carries a field of the right +name and type satisfies a `HasField` bound. The bound says what the provider +needs; it does not certify who may construct the context. Authority, where there is any, lives in the +*value* stored in the field: a `Dir` is unforgeable because `cap-std` made it so, and a `String` named +`name` is not a capability at all. Rust can express unforgeable tokens as types with private +constructors, and CGP can carry such a token as a field or fix one as an abstract type, but the token +pattern is Rust's. + +### Provisioning is fixed per context type + +In the object-capability model authority is provisioned at runtime and the graph changes while the +program runs. In CGP the set of requirements a context satisfies, and the providers it satisfies them +with, are part of the context *type*, fixed when `delegate_components!` is written. Only the field +*values* are dynamic: two `App` values may carry two different `Dir` handles, and a test may carry a +`Dir` opened on a temporary directory. That is provisioning of values, not of authority structure. +Attenuation means a [higher-order provider](/docs/concepts/higher-order-providers) that wraps an inner +one, decided statically; revocation has no counterpart; and bindings are flat, with no nested scope in +which a provider could be shadowed. + +## What each approach costs + +Object capabilities are valued for what their reasoning buys: least authority as a property of the +object graph rather than a policy someone maintains, structural immunity to confused-deputy attacks, +and delegation and attenuation as ordinary programming +([Miller, *Robust Composition*](https://papers.agoric.com/assets/pdf/papers/robust-composition.pdf)). +The effects-as-capabilities line is valued for lightweight effect polymorphism +([Brachthäuser, Schuster & Ostermann, 2020](https://dl.acm.org/doi/10.1145/3428194)). Their costs, +as their users state them, are the costs of removing what everyone is used to. Ambient authority is +convenient, and passing an allocator by hand "doesn't exactly seem ideal" +([Wuyts](https://blog.yoshuawuyts.com/nesting-allocators)). Retrofitting is hard: `cap-std` cannot +sandbox code that still has `std::fs`, and Pony and Austral removed globals from the language, which +no established ecosystem can do after the fact. The effect-system designs pay in restrictions and +maturity: Effekt's capabilities cannot be returned or stored, and Scala's capture checking is, by its +own documentation, "still highly experimental and unstable". And the word itself is a cost, since the +senses are conflated so often that a 2003 paper set out to demolish the resulting myths +([Miller, Yee & Shapiro](https://papers.agoric.com/assets/pdf/papers/capability-myths-demolished.pdf)). + +CGP's costs on this page are the properties it lacks. A reader who wants confinement gets none from +CGP alone and must bring `cap-std`, WASI, or a token type of their own. A reader who wants nested +scopes that shadow a binding gets a single flat context. A reader who wants a capability that can be +returned, stored, and revoked gets a field value with none of those semantics attached. Beyond these, +the ordinary costs apply: the wiring is code somebody writes, and the raw diagnostics are trait-solver +output over generated types. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for +the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs CGP's costs against the +alternatives. + +## Where a capability system is the better choice + +Where a program needs a capability-safe language, Pony, Austral, or Hardened JavaScript is the tool, +and where it needs sandboxed I/O in Rust, `cap-std` and WASI are. Where it needs privilege bits or +aliasing control, Linux capabilities and Rust's ownership already exist and CGP does not touch them. +CGP is the better tool where a program wants its implementations to state what they require and a +compiler to check that each context supplies it, on stable Rust, with the choice of implementation made +per application, and it combines with the object-capability libraries rather than competing with them. + +## What to expect that differs + +**CGP does not remove ambient authority.** A provider's bounds bound what it reaches through the +context, and nothing else. Rust's `std` and globals remain reachable from any body. + +**A CGP bound is a requirement, not a token.** Any context with the right field satisfies it. Where +authority matters, it lives in the field's value, and a type with a private constructor is how Rust +makes such a value unforgeable. + +**The authority structure is fixed per context type.** Field values vary at runtime; which providers +a context has, and what they require, does not. There is no runtime delegation, attenuation, or +revocation, and there is no nested scope. + +**There is no escape check.** A context field can be cloned out and used elsewhere. Effekt's +second-class capabilities and Scala's capture sets prevent that; CGP does not. + +**CGP does not "give Rust capabilities" in any single sense.** If the reader means implicit passing of +an allocator or a runtime, CGP's implicit arguments do that now, and the +[Rust proposals](./rust-language-proposals.md) page says what the contexts proposal would add. If the +reader means sandboxing, `cap-std` and WASI are the tools and CGP carries their handles. If the reader +means ownership tokens, Rust already has them and CGP can fix one as an abstract type. In CGP's own +vocabulary, a component defines a *trait*, a provider *requires* traits and *reads* fields, and a +context *supplies* what providers need; none of these is called a capability. + +## Where to go next + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the construct this page reads as a + capability requirement. +- [Implicit arguments](/docs/concepts/implicit-arguments): reading a value from the context. +- [Algebraic effects](./algebraic-effects.md): the effects-as-capabilities fragment from the effect + handler side. +- [Rust's own proposals](./rust-language-proposals.md): the contexts-and-capabilities proposal in + full. + +## Sources + +The `cap-std` snippets were compiled with `cap-std` 3 and the CGP snippet against `cgp` `0.8.0-alpha` +with a `check_components!` assertion per wired context; the Scala snippet was compiled with Scala +3.8.4. The Pony snippet was checked against the standard library's documented signatures for +`FileAuth`, `FilePath`, and `OpenFile` rather than compiled. + +- [Dennis & Van Horn, *Programming Semantics for Multiprogrammed Computations* (CACM 1966)](https://dl.acm.org/doi/10.1145/365230.365252): the origin of the capability. +- [Miller, *Robust Composition* (PhD thesis, 2006)](https://papers.agoric.com/assets/pdf/papers/robust-composition.pdf) and [Miller, Yee & Shapiro, *Capability Myths Demolished* (2003)](https://papers.agoric.com/assets/pdf/papers/capability-myths-demolished.pdf): the object-capability model, its defining properties, delegation, attenuation, revocation, and the myths. +- [Wikipedia, *Object-capability model*](https://en.wikipedia.org/wiki/Object-capability_model) and [*Capability-based security*](https://en.wikipedia.org/wiki/Capability-based_security): the definitions and the systems implementing the model. +- [Pony tutorial, *Object Capabilities*](https://tutorial.ponylang.io/object-capabilities/object-capabilities.html) and [*Reference Capabilities*](https://tutorial.ponylang.io/reference-capabilities/): the unforgeable-token definition, `env.root`, and the aliasing qualifiers that share the word. +- [Austral specification](https://austral-lang.org/spec/spec.html), [CHERI](https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/), and [WASI design principles](https://github.com/WebAssembly/WASI/blob/main/docs/DesignPrinciples.md): linear capability values, architectural capabilities, and unforgeable handles without ambient authority. +- [Gohman, *Introducing cap-std*](https://blog.sunfishcode.online/introducing-cap-std/) and the [cap-std README](https://github.com/bytecodealliance/cap-std): capability-oriented APIs, `ambient_authority()`, and the limit that a library cannot sandbox arbitrary Rust code. +- [capabilities(7)](https://man7.org/linux/man-pages/man7/capabilities.7.html): Linux capabilities as privilege units. +- [Brachthäuser, Schuster & Ostermann, *Effects as Capabilities* (OOPSLA 2020)](https://dl.acm.org/doi/10.1145/3428194), [Odersky et al., *Scoped Capabilities for Polymorphic Effects* (2022)](https://arxiv.org/abs/2207.03402), [Scala 3 Reference, *Capture Checking*](https://docs.scala-lang.org/scala3/reference/experimental/cc.html), and [*CanThrow Capabilities*](https://docs.scala-lang.org/scala3/reference/experimental/canthrow.html): effect types as capabilities a computation requires, capture sets, and the erased `CanThrow`. +- [Mandry, *Contexts and capabilities in Rust*](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/) and [Wuyts, *Nesting Allocators*](https://blog.yoshuawuyts.com/nesting-allocators): the implicit-value sense and the global allocator as ambient authority. +- [Embedded Rust Book, *Peripherals as singletons*](https://docs.rust-embedded.org/book/peripherals/singletons.html) and [Gehring, Rehms & Tschorsch, *PermRust*](https://arxiv.org/abs/2506.11701): ownership tokens as static capabilities. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/dependency-injection.md b/docs/comparisons/dependency-injection.md new file mode 100644 index 00000000..72349dd5 --- /dev/null +++ b/docs/comparisons/dependency-injection.md @@ -0,0 +1,294 @@ +--- +sidebar_label: 'Dependency injection' +sidebar_position: 8 +description: 'CGP read against Spring, Guice, and Dagger: injection without a container, reflection, or runtime graph.' +--- + +# Dependency injection + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows +dependency injection (DI) from Spring, Guice, Dagger, or their kin. CGP solves the same decoupling +problem, at compile time and without a container, and the vocabulary maps almost directly. The page +covers that mapping, what changes when resolution moves from runtime to types, where a DI framework +remains the better tool, and what to expect that differs. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. In DI terms it is the assembled object graph, made a type you define to stand for an +application. + +| In a DI framework | In CGP | +| --- | --- | +| A bean or a binding | A **provider**: an interchangeable implementation of a trait | +| The `@Configuration` class or the Guice module | **Wiring**, written in a `delegate_components!` table | +| A constructor parameter | An **impl-side dependency**, declared with `#[uses]` or `#[implicit]` | +| The interface a bean is bound to | A **component**: one trait with many possible implementations | +| Graph validation at startup or build time | `check_components!`, at compile time | +| The container | The type system; nothing exists at runtime | + +## The idea, briefly + +Dependency injection gives an object its collaborators from the outside instead of letting it +construct them. A class that names only the *interfaces* it needs can be handed fakes in a test and +different implementations in a different deployment, and never changes. The frameworks automate the +supplying, which in a large object graph is elaborate enough that they exist for it. + +### The IoC container and beans + +Spring's core is an *inversion-of-control container* that instantiates, configures, and connects the +application's objects, its *beans*. A class becomes a bean with an annotation, and a `@Configuration` +class spells out which implementation stands in for an interface: + +```java +@Service +public class UserService { + // business logic lives here +} + +@Configuration +public class AppConfig { + @Bean + public StorageClient storageClient() { + return new S3StorageClient(/* ... */); + } +} +``` + +### Constructor, setter, and field injection + +The container injects each bean's dependencies by one of three mechanisms. *Constructor injection* +passes them as constructor arguments, so they are required and the fields can be `final`: + +```java +@Service +public class ProfilePictureService { + private final StorageClient storage; + private final UserRepository users; + + public ProfilePictureService(StorageClient storage, UserRepository users) { + this.storage = storage; + this.users = users; + } +} +``` + +*Setter injection* supplies a dependency after construction, and *field injection* writes it into a +private field by reflection, marked `@Autowired`. The Spring reference and the wider community +recommend constructor injection for required dependencies, because it makes a class's dependencies +explicit in its signature and lets the object be built without a container in a test +([Spring Framework reference](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html)). + +### Modules and bindings + +Guice and Dagger express the same wiring by explicit *bindings* in a *module*: + +```java +public class StorageModule extends AbstractModule { + @Override + protected void configure() { + bind(StorageClient.class).to(S3StorageClient.class); + } +} +``` + +Spring and Guice resolve bindings at runtime through reflection. Dagger resolves them at *compile +time*: its annotation processor generates the wiring code during the build, so a missing binding is a +compile error and there is no reflection at runtime. That split is the sharpest axis of variation +among DI frameworks, and CGP sits at the compile-time end of it. + +### Dependency injection without a framework + +Rust practitioners generally hold that the language needs no DI framework, because traits and +generics already decouple a component from its collaborators: + +```rust +trait StorageClient { + fn fetch(&self, object_id: &str) -> Vec; +} + +struct ProfilePictureService { + storage: S, +} +``` + +This is dependency injection in the original sense, with the compiler doing the checking +([jmmv.dev, *Rust traits and dependency injection*](https://jmmv.dev/2022/04/rust-traits-and-dependency-injection.html)). +Its limitation is the one CGP lifts. A bound like `S: StorageClient` leaks into every caller's +signature, and coherence permits one `impl StorageClient` per type, so offering several +interchangeable implementations of one interface runs into the rules the +[Bypassing coherence](/docs/concepts/coherence) page explains. CGP is the next step along the line +Rust already accepts, not an import of the container model. + +## How CGP expresses it + +CGP performs dependency injection through two mechanisms working together. A provider declares what +it needs as [impl-side dependencies](/docs/concepts/impl-side-dependencies), and a context supplies +them by wiring each component to a provider. Both are resolved by the compiler, so the "container" +has no runtime existence. Every context below is an **environmental context**: a type standing for an +application, carrying the application's choices and dependencies rather than being the data operated +on. + +### Impl-side dependencies are the injected constructor parameters + +Where a Spring service lists `StorageClient` and `UserRepository` as constructor parameters, a CGP +provider lists its trait dependencies with `#[uses]` and its value dependencies as `#[implicit]` +arguments. A user-creation provider that needs a database connection and a censorship service declares +both: + +```rust +#[cgp_impl(new PostgresUserManager)] +#[uses(CanCensorUsername)] +impl UserManager { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + // ... insert the user with `database` + } +} +``` + +`#[uses(CanCensorUsername)]` injects a *trait dependency*, the role a `UserRepository` collaborator +plays in the constructor. The `#[implicit] database` argument injects a *value* pulled from the +context's `database` field, the role a configuration bean plays. Neither appears in the +`CanManageUser` consumer trait a caller invokes, so, unlike a leaked generic bound, they do not +cascade to callers. That is the decoupling a DI framework promises, delivered by declaring the +requirements one level down in the provider rather than in a container. `Error` here is the +application's own enum, and the insert body is elided. + +### Wiring is the container configuration + +A context selects which provider satisfies each component in a +[`delegate_components!`](/docs/reference/macros/delegate_components) table, the direct analogue of a +`@Configuration` class or a Guice module. Two contexts map the same component to different providers +with no conflict, because the choice is keyed on the context type: + +```rust +#[cgp_component(StorageObjectFetcher)] +pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; +} + +delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } +} + +delegate_components! { + GCloudApp { + StorageObjectFetcherComponent: FetchGCloudObject, + } +} +``` + +`FetchS3Object` and `FetchGCloudObject` are interchangeable providers of the same trait, the +equivalent of two beans bound to one interface, and the wiring picks one per context. Because the +selection is resolved during type checking and monomorphized to a direct call, the `App` binary +contains only the S3 code path and the `GCloudApp` binary only the GCloud one. A container makes the +same substitution by holding both implementations and choosing at startup. + +### Checking replaces the container's startup validation + +A container discovers a missing or ambiguous binding when it assembles the graph: at startup for +Spring and Guice, at build time for Dagger. CGP's counterpart is +[`check_components!`](/docs/reference/macros/check_components), which asserts at compile time that a +context's wiring is complete and every provider's transitive dependencies are satisfied: + +```rust +check_components! { + App { + StorageObjectFetcherComponent, + } +} +``` + +If `FetchS3Object` needs a field or trait the `App` context does not supply, this fails to compile +with the missing dependency named, rather than surfacing as a startup exception or a null reference +deep in a request. It is the guarantee Dagger gives, reached through the trait system instead of an +annotation processor. CGP wiring is [lazy](/docs/concepts/check-traits), so this check turns a latent gap into an +early error. + +## What each approach costs + +DI frameworks are valued for decoupling components from their collaborators, which makes code testable +and swappable, for centralizing wiring in one readable place, and, in Spring's case, for the ecosystem +keyed off the same bean model. Their costs, as their users state them, cluster around the runtime, +reflective nature of the popular frameworks. Dependencies can become hidden: with field injection a +class's signature says nothing about what it needs, and a missing binding is a runtime failure rather +than a compile error, which is why the community steers toward constructor injection +([Nuri, *Field injection is not recommended*](https://blog.marcnuri.com/field-injection-is-not-recommended)). +Classpath scanning and reflective graph construction cost startup time, which is why Dagger's +compile-time generation exists. And the frameworks do so much automatically that when something goes +wrong the developer has little visibility into why +([Shore, *The Problem With Dependency Injection Frameworks*](https://www.jamesshore.com/v2/blog/2023/the-problem-with-dependency-injection-frameworks)). + +CGP resolves everything at compile time, and that is its central cost as well as its benefit. It +cannot reconfigure an application without recompiling, load plugins chosen at startup from a config +file, or build a graph whose shape is not known until the program runs. It is confined to Rust. Its +machinery, the consumer and provider split, the wiring, and the type-level tables, has a learning +curve of its own. And its raw diagnostics are trait-solver output over generated types: +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +alternatives, including plain traits and generics. + +## Where a DI framework is the better choice + +A DI framework remains the better choice when the application needs runtime reconfiguration, when it +lives in a JVM or .NET ecosystem whose libraries assume the container, or when the team's familiarity +with the framework outweighs the benefits of static wiring. Within Rust, plain traits and generics are +the better choice when one implementation per type suffices and the bound does not spread far. CGP is +the better tool where the graph is known at build time and the guarantees and zero runtime cost +matter: systems programming, latency-sensitive services, and libraries that must not impose a runtime. + +## What to expect that differs + +**There is no container object.** A DI reader will look for something holding the graph and resolving +dependencies by reflection at startup. CGP's container is the type system, the graph is a set of +trait impls, and the resolution happens during compilation and compiles to direct calls. There is no +runtime cost and no runtime failure mode to look for. + +**There is no scanning or auto-registration.** CGP asks for explicit wiring. There is no classpath +scan, no `@Component` discovery, and no runtime rebinding, and the graph must be known at compile +time. This is the price of the guarantees, the same trade Dagger made, carried to its conclusion. + +**The same interface can resolve differently per context.** A single global binding graph cannot +express two applications binding one interface two ways. In CGP that is one wiring line each. + +**Dependencies are never hidden.** They are stated in `#[uses]` and `#[implicit]` and enforced by the +compiler, which gives the explicitness the community prizes in constructor injection by default. + +## Where to go next + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the construct this page maps onto + constructor parameters. +- [Checking your wiring](/docs/concepts/check-traits): why wiring is lazy and what the check catches. +- [Implicit arguments](/docs/concepts/implicit-arguments): value injection from context fields. +- [ML modules](./ml-modules.md) and [Policy-based design](./policy-based-design.md): the same + centralized wiring seen from two other traditions. + +## Sources + +The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per +wired context. The Java snippets follow the framework documentation cited below. + +- [Spring Framework reference, *Dependency Injection*](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html): the IoC container, beans, and the constructor and setter injection mechanisms. +- [Baeldung, *Inversion of Control and Dependency Injection in Spring*](https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring): the distinction between IoC and DI and `@Autowired` resolution by type. +- [Comparing Dependency Injection Frameworks](https://medium.com/@AlexanderObregon/comparing-dependency-injection-frameworks-spring-guice-and-dagger-a614dccd5859) and [Dagger vs Guice](https://www.hackingnote.com/en/versus/dagger-vs-guice/): the runtime-versus-compile-time split across frameworks. +- [Nuri, *Field injection is not recommended*](https://blog.marcnuri.com/field-injection-is-not-recommended) and [Shore, *The Problem With Dependency Injection Frameworks*](https://www.jamesshore.com/v2/blog/2023/the-problem-with-dependency-injection-frameworks): the hidden-dependency and runtime-failure concerns, and the case for constructor injection. +- [jmmv.dev, *Rust traits and dependency injection*](https://jmmv.dev/2022/04/rust-traits-and-dependency-injection.html): the position that Rust performs dependency injection through traits and generics without a framework. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/dynamic-dispatch.md b/docs/comparisons/dynamic-dispatch.md new file mode 100644 index 00000000..99225277 --- /dev/null +++ b/docs/comparisons/dynamic-dispatch.md @@ -0,0 +1,332 @@ +--- +sidebar_label: 'Dynamic dispatch' +sidebar_position: 9 +description: 'CGP read against dynamic dispatch, duck typing, vtables, and prototypal inheritance: the same openness, resolved at compile time.' +--- + +# Dynamic dispatch, dynamic typing, and prototypal inheritance + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who thinks in +objects, messages, vtables, and prototypes: Python, Ruby, JavaScript, Smalltalk, or the virtual +dispatch of C++ and Java. CGP reproduces the openness those mechanisms buy, many implementations +behind one interface, behavior assembled by delegation, defaults inherited from a shared table, and +provider code that reads as if it sends messages to an object, and resolves every bit of it at +compile time into direct calls. The page covers the correspondence, the one change from which the +rest follows, where runtime dispatch remains the right tool, and what to expect that differs. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. It plays the object's part. + +| In a dynamic language | In CGP | +| --- | --- | +| An object | The context | +| A message or method | A **component**: one trait with many possible implementations | +| A method implementation | A **provider** | +| The object's method table or vtable | The **wiring table**, written with `delegate_components!` and erased before runtime | +| A prototype the object delegates to | An aggregate provider or a namespace | +| `respond_to?` before a call | `check_components!`, made total and moved to compile time | + +## The idea, briefly + +Dynamic dispatch decouples a call site from the implementation it invokes, so one piece of code works +over many implementations chosen later. Dynamically typed languages take this to its limit: a value is +whatever it can *do*, behavior is shared by pointing one object at another, and the program is +malleable at runtime. + +### Dynamic typing and duck typing + +A dynamically typed language checks types at runtime, and *duck typing* is the style this permits: an +object's usability is decided by the methods it has, not by a class it declares. A function that +calls `x.quack()` works for any `x` that responds to `quack` +([Wikipedia, *Duck typing*](https://en.wikipedia.org/wiki/Duck_typing)). Its appeal is that an +interface need never be spelled out. + +### Dynamic dispatch and late binding + +Dynamic dispatch is the runtime selection of which implementation a method call invokes, based on the +receiver ([Wikipedia, *Dynamic dispatch*](https://en.wikipedia.org/wiki/Dynamic_dispatch)). Smalltalk +gave the purest form: every call is a message send, resolved at call time by consulting the receiver's +class method dictionary. Statically typed object languages offer the same late binding for methods +marked virtual, and a few languages (CLOS, Julia) generalize to *multiple dispatch* on several +arguments. + +### Vtables and method dictionaries + +Compiled languages implement dynamic dispatch with a *virtual method table*: a per-class array of +function pointers that each object reaches through a hidden pointer. A virtual call loads the vtable +pointer, indexes to the method's slot, and calls the function found there +([Wikipedia, *Virtual method table*](https://en.wikipedia.org/wiki/Virtual_method_table)). Rust's own +dynamic dispatch works this way: a `dyn Trait` value is a fat pointer pairing a data pointer with a +vtable pointer ([The Rust Book, *Trait objects*](https://doc.rust-lang.org/book/ch18-02-trait-objects.html)). +The indirect call defeats inlining and adds a load per dispatch. Dynamically typed languages pay more, +resolving a method by name up a class or prototype chain, which is why their engines invest in inline +caches and hidden classes ([V8, *Maps*](https://v8.dev/docs/hidden-classes)). + +### Prototypal inheritance and delegation + +Prototype-based languages share behavior by *delegation*: an object holds a link to a prototype, and a +message the object does not handle is forwarded along the chain. Lieberman introduced the model in +1986 and the Self language realized it +([Lieberman, *Using Prototypical Objects*](https://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html)). +In JavaScript every object has a `[[Prototype]]` link, a lookup walks the chain, and an own property +*shadows* an inherited one ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain)). + +The property that distinguishes delegation from mere forwarding matters most for CGP: `self` stays +bound to the original receiver. When a prototype's method refers to `self`, it denotes the object that +originally received the message, so an inherited method still sees the receiver's own state. +Forwarding rebinds `self` to the object the message was passed to and loses that connection. + +## How CGP expresses it + +CGP reproduces dynamic dispatch, vtables, and prototypal delegation, and resolves each at compile +time. What is a runtime lookup in a dynamic language is a type-resolution step in CGP that +monomorphizes to a direct call. + +### CGP code reads like a duck-typed program + +A CGP provider is written against an unknown context and reads like duck-typed code that sends +messages to a receiver and trusts it to respond: + +```rust +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } +} +``` + +The body `self.name()` is a message send to a context whose type is not written down. With an +[implicit argument](/docs/concepts/implicit-arguments) the resemblance is stronger still: a value +appears from the context, as an unbound name would in Ruby or Python: + +```rust +#[cgp_fn] +pub fn greet_implicitly(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") +} +``` + +Ordinary generic Rust would demand `fn greet(c: &C)`, naming the trait in the signature. +CGP moves the bound into `#[uses]` and abstracts the context away, so the provider body carries less +visible type ceremony than a plain generic function. The decisive difference is *when* the trust is +discharged. A duck-typed program finds out at runtime whether the object responds, and fails with a +`NoMethodError` if not. CGP finds out at compile time, because trait resolution and +[`check_components!`](/docs/reference/macros/check_components) check the `#[uses(HasName)]` +dependency and the field access. The `Person` these run on is a **value context**: the type being +greeted carries the `name` field and the wiring. + +### Static dispatch with the flexibility of dynamic dispatch + +A caller writes `context.area()` against the `CanCalculateArea` consumer trait without naming an +implementation, as a dynamic call names a method and lets the receiver decide. In CGP the receiver +decides during type checking: the consumer trait's generated impl routes the call through the +context's wiring table to the provider, and the compiler monomorphizes the whole route to a direct +call, with no fat pointer and no vtable load. Rust already offers real dynamic dispatch through +`dyn Trait`, and CGP is its static sibling: both let an implementation be chosen after the calling +code is written, and one pays a runtime indirection while the other resolves it away. Where a +component carries a generic parameter, the [`open` statement](/docs/reference/macros/delegate_components) +selects a provider per value of that parameter, which reproduces *multiple* dispatch, decided at +compile time. + +### `DelegateComponent` is a compile-time vtable + +The type-level table a context carries is a vtable that exists only during compilation. Each entry +maps one component key to the provider that implements it, as a vtable slot maps a method to its +implementation: + +```rust +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +// expands to the type-level table entry: +// impl DelegateComponent for Rectangle { +// type Delegate = RectangleArea; +// } +``` + +The mapping is exact on structure and opposite on timing. The context type plays the class, a +`DelegateComponent` impl is a slot, and the provider is the function the slot points to. But the key +is a type rather than an offset, the compiler performs the lookup once rather than the CPU on every +call, and the table is erased before the program runs. The honest cost is that CGP loses the runtime +heterogeneity a real vtable enables: a `Vec>` can hold different shapes and +dispatch each at runtime, whereas a CGP context is one monomorphic type resolved once. The +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) page traces a call +through the table. + +### Component delegation is delegation, with `self` bound + +CGP's delegation chain is delegation in Lieberman's sense, because the context stays bound to the +original as lookup walks the chain. An [aggregate provider](/docs/concepts/aggregate-providers) +bundles a group of wirings, and a context delegates a whole group to it in one entry: + +```rust +delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } +} + +delegate_components! { + Rectangle { + [AreaCalculatorComponent, PerimeterCalculatorComponent]: GeometryComponents, + } +} +``` + +When `rect.area()` resolves, the lookup walks `Rectangle`, then `GeometryComponents`, then +`RectangleArea`, and the context stays `Rectangle` at every step: `GeometryComponents` appears only in +the delegate position, never as the context, so the leaf provider reads `width` and `height` from +`Rectangle`. That is delegation's defining property. The delegate chain supplies the *behavior* while +`self` remains the original *identity*. The [`UseContext`](/docs/reference/providers/use_context) +provider is the same relationship pointed the other way, letting a provider route a call back to the +context's own wiring. + +### Namespaces are shared prototypes with open slots, not shadowable ones + +A CGP [namespace](/docs/concepts/namespaces) is a shared table of wirings that many contexts inherit, +which is the prototype's job. But the override rule differs from JavaScript's. In a prototype chain +an own property *shadows* an inherited one. In CGP, a key the namespace binds is not overridable: +joining a namespace generates a forwarding impl covering every key it answers, so a direct entry for +one of those keys is rejected with `E0119`. What a context may supply is a path the namespace routes +to but leaves unbound, an open slot left for each context to fill: + +```rust +// The shared prototype: it binds the farewell and leaves the greeting path open. +cgp_namespace! { + new AppDefaults: AppNamespace { + @app.FarewellComponent: SayGoodbye, + } +} + +delegate_components! { + AppA { + namespace AppDefaults; // inherit every wiring the namespace binds + + @app.GreeterComponent: GreetHello, // fill a slot the namespace leaves open + } +} +``` + +Namespaces inherit from one another, so a child may bind an open path the parent leaves; it may not +redefine a key the parent binds: + +```rust +cgp_namespace! { + new QuietDefaults: AppDefaults { + @app.GreeterComponent: GreetQuietly, + } +} + +delegate_components! { + AppB { + namespace QuietDefaults; + } +} +``` + +The lookup that walks these layers is the [`RedirectLookup`](/docs/reference/providers/redirect_lookup) +provider tracing a type-level path, which is the prototype chain being walked. The closer +object-oriented analogy is an abstract base class rather than a prototype: the namespace fixes what +every context agrees on and declares slots each context must fill, and it does not let a child +silently redefine a concrete inherited member. `AppA` and `AppB` are **environmental contexts**, types +standing for an application. + +## What each approach costs + +Dynamic dispatch and dynamic typing are valued for immediacy and flexibility. Duck typing lets a +function work over any object that responds to its messages, which programmers value for reuse, +shorter code, and rapid prototyping +([SitePoint, *Making Ruby Quack*](https://www.sitepoint.com/making-ruby-quack-why-we-love-duck-typing/)). +Prototypal inheritance lets objects be created, linked, and reshaped at runtime, and hooks such as +`method_missing` let one object answer messages it was never written to handle. Their costs, as their +users state them, follow from the same deferral. A mistake surfaces as a runtime error discovered only when the +offending line runs, which makes refactoring hazardous, and the standard mitigation is tests or a +`respond_to?` guard ([DevGex, *Duck Typing*](https://devgex.com/en/article/00035033)). The vtable +indirection defeats inlining, and dictionary-based lookup is worse, which is why so much engineering +goes into inline caches ([V8](https://v8.dev/docs/hidden-classes)). A mutable prototype chain is easy +to get confused about, and JavaScript's `this` binding, the same self-binding that makes delegation +work, is lost when a method is detached from its receiver and called on its own. + +CGP's costs are the ones dynamic dispatch exists to avoid. It cannot hold a heterogeneous collection +of implementations and choose among them at runtime; Rust's `dyn Trait` exists for that. It +cannot load an implementation chosen at runtime from configuration, patch a live object, or answer a +message it was not built to handle, because there is no runtime object graph and no runtime dispatch +to intercept. Its wiring is code somebody writes. And its errors, though caught early, are trait-solver +output over generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause +for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. +The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +alternatives. + +## Where runtime dispatch is the better choice + +When a program needs runtime openness, plugins discovered at startup, objects of mixed types in one +collection, behavior reshaped live, or the metaprogramming that proxies and DSLs rely on, dynamic +dispatch is the right tool, and emulating it with compile-time wiring is impossible rather than +awkward, since the whole point is deferral to runtime. In Rust that means `dyn Trait`, and a CGP +context may hold one. CGP is the better tool when the set of implementations is known at build time +and the program wants the decoupling of dynamic dispatch with none of the cost or the runtime failure +modes. + +## What to expect that differs + +**Nothing happens at runtime.** A reader from this background will assume a vtable is a data +structure the program carries, that dispatch chooses at the moment of the call, that a prototype chain +is walked when a property is missing, and that the object graph can change while the program runs. In +CGP the table is erased after compilation, the type checker resolves the dispatch and the compiler +inlines it, the chain is walked during type resolution, and the wiring is fixed once the program is +built. + +**Late binding is late to the wiring site, not to runtime.** The flexibility is real, and it is spent +at compile time, at the place a context declares its providers. + +**A missing method is a compile error.** A context that lacks a trait a provider needs fails at the +wiring site, named by `check_components!`, rather than as a `NoMethodError` in production. + +**A namespace's bound entries cannot be shadowed.** The inherit-and-customize pattern works through +slots the namespace leaves open, not through override. + +**CGP is not a dynamic language with the types added.** It is the static resolution of the mechanisms +this reader knows, trading runtime malleability for zero cost and compile-time safety. + +## Where to go next + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): how a call finds its + provider through the table. +- [Aggregate providers](/docs/concepts/aggregate-providers) and [Namespaces](/docs/concepts/namespaces): + the delegation chain and the shared table. +- [Row polymorphism](./row-polymorphism.md): the type-system side of duck typing, structural versus + nominal. +- [Reflection](./reflection.md): the introspection counterpart to this page's runtime mechanisms. + +## Sources + +The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per +wired context. This page shows no code in another language. + +- [Wikipedia, *Dynamic dispatch*](https://en.wikipedia.org/wiki/Dynamic_dispatch), [*Virtual method table*](https://en.wikipedia.org/wiki/Virtual_method_table), and [*Duck typing*](https://en.wikipedia.org/wiki/Duck_typing): late binding, the vtable, and usability decided by the methods an object has. +- [The Rust Programming Language, *Trait objects*](https://doc.rust-lang.org/book/ch18-02-trait-objects.html) and [geo-ant, *Rust Dyn Trait Objects and Fat Pointers*](https://geo-ant.github.io/blog/2023/rust-dyn-trait-objects-fat-pointers/): Rust's own dynamic dispatch as a fat pointer and a vtable. +- [Lieberman, *Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems* (OOPSLA 1986)](https://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html): delegation, and the rule that `self` stays bound to the original receiver. +- [MDN, *Inheritance and the prototype chain*](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain): JavaScript's prototype chain and own-property shadowing. +- [V8, *Maps (Hidden Classes)*](https://v8.dev/docs/hidden-classes): the engineering that dynamic dispatch's runtime cost demands. +- [SitePoint, *Making Ruby Quack*](https://www.sitepoint.com/making-ruby-quack-why-we-love-duck-typing/), [GeeksforGeeks, *Type Systems*](https://www.geeksforgeeks.org/python/type-systemsdynamic-typing-static-typing-duck-typing/), and [DevGex, *Duck Typing*](https://devgex.com/en/article/00035033): community sentiment on what duck typing buys and costs. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/implicit-parameters.md b/docs/comparisons/implicit-parameters.md new file mode 100644 index 00000000..3e3b3541 --- /dev/null +++ b/docs/comparisons/implicit-parameters.md @@ -0,0 +1,325 @@ +--- +sidebar_label: 'Implicit parameters' +sidebar_position: 5 +description: "CGP read against Scala's given and using, Haskell's ImplicitParams, and the type-class resolution both build on." +--- + +# Implicit parameters + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows +implicit parameters: Scala's `given` and `using`, Haskell's `ImplicitParams`, and the type-class +resolution both languages build on. CGP shares the goal of threading context through code without +explicit plumbing, and supplies the values from a context's fields and wiring rather than from a +compiler-driven search. The page covers the correspondence, the coherence trade underneath it, where +implicit resolution remains the better tool, and what to expect that differs. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. It is the implicit environment you already reason about, the set of `given`s in scope or +the `Reader` you thread, made a single explicit type that every provider receives. + +| In Scala or Haskell | In CGP | +| --- | --- | +| A `using` parameter or a `?x` implicit parameter | An `#[implicit]` argument, read from a context field | +| A `given` value in scope | A field of the context | +| A type class | A **component**: one trait with many possible implementations | +| An instance | A **provider**: a named implementation | +| Instance resolution by the compiler | **Wiring**, written in a `delegate_components!` table | +| A functional dependency (`m -> e`) or associated type family | An abstract type, chosen by the context | + +## The idea, briefly + +Some values are needed everywhere and interesting nowhere: a configuration, a logger, a comparison +strategy, an error type. Passing them through every function that transitively needs them clutters +signatures and forces intermediate functions to forward parameters they only pass along. Implicit +parameters remove that: the caller omits the argument, the compiler fills it in from scope, and the +declaration still records the dependency in the type. + +### Context parameters in Scala + +Scala 3 marks a parameter list `using`, and the compiler supplies a matching `given` from scope: + +```scala +case class Config(port: Int, baseUrl: String) + +def renderWebsite(path: String)(using config: Config): String = + "" + renderWidget(List("cart")) + "" // config passed implicitly + +def renderWidget(items: List[String])(using config: Config): String = ??? + +given Config = Config(8080, "docs.scala-lang.org") + +renderWebsite("/home") // the given Config is supplied automatically +``` + +The same mechanism serves type classes. A `given` can be defined for a type, and a method with a +`using` parameter of that type resolves the instance from the call site. Scala 3.6 changed the syntax +for a given with a body to a colon form; the older `given Comparator[Int] with` is still accepted +([Scala 3 Reference, *Given Instances*](https://docs.scala-lang.org/scala3/reference/contextual/givens.html)): + +```scala +trait Comparator[A]: + def compare(x: A, y: A): Int + +given Comparator[Int]: + def compare(x: Int, y: Int): Int = x - y + +def max[A](x: A, y: A)(using c: Comparator[A]): A = + if c.compare(x, y) > 0 then x else y + +max(1, 2) // Comparator[Int] resolved and passed implicitly +``` + +Scala 2 wrote all of this with the single `implicit` keyword, and Scala 3 split it into `given` and +`using` because the one keyword was overloaded +([Baeldung, *Scala 3 Implicit Redesign*](https://www.baeldung.com/scala/scala-3-implicit-redesign)). +Rust's own contexts-and-capabilities proposal is the nearest thing to a `using Config` for Rust; the +[Rust proposals](./rust-language-proposals.md) page compares it. + +### Implicit parameters in Haskell + +Haskell's `ImplicitParams` extension is the more literal form. A function names a dynamically bound +variable `?x`, which appears as a constraint on its signature and is filled from the binding in +scope. This version uses the real `Data.List.sortBy` and compiles with GHC 9.10: + +```haskell +{-# LANGUAGE ImplicitParams #-} +import Data.List (sortBy) + +sort :: (?cmp :: a -> a -> Ordering) => [a] -> [a] +sort = sortBy ?cmp + +least :: (?cmp :: a -> a -> Ordering) => [a] -> a +least xs = head (sort xs) + +min' :: Ord a => [a] -> a +min' = let ?cmp = compare in least +``` + +The constraint propagates to any caller that does not bind it, and a `let` binding discharges it. +The GHC User's Guide records the restrictions: the constraints leak into every signature, there is no +way to declare a default, an implicit parameter may not appear in a class or instance context, and the +monomorphism restriction applies +([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/implicit_parameters.html)). +Haskell programmers reach for the `Reader` monad or for type classes instead. + +### Type classes as implicit dictionary passing + +Type classes are the mechanism both languages use for implicit resolution in practice. A `class` +declares an interface, an `instance` provides it for a type, and a constrained call receives the +instance as a hidden *dictionary* argument. The resolution is type-directed and automatic, and it is +governed by *coherence*: for a given type there is exactly one instance, so the compiler can inject +it silently without two pieces of code disagreeing. Its price is the one CGP was built to escape. A +program cannot have two legitimate orderings of `Int` as first-class instances without a `newtype`, +and a module cannot add an instance for a type and class it does not own. The +[type classes](./type-classes.md) page develops the mechanism and its extensions. + +## How CGP expresses it + +CGP threads context through code and lets deep code read what it needs, through the context that is +already the `self` of every provider rather than through a scope search. Two constructs map onto the +two forms of implicit parameter: an `#[implicit]` argument corresponds to an implicit *value* +parameter, and a component with its wiring corresponds to a type class. + +### Implicit arguments are implicit value parameters + +An `#[implicit]` argument is written as an ordinary function parameter but is supplied from the +context's fields rather than by the caller: + +```rust +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} +``` + +Where Scala's `renderWebsite` obtains its `Config` from a `given`, this function obtains `width` and +`height` from the context threaded through it as `self`. The parameter disappears from the public +signature and is bound from the surroundings before the body runs, which is why CGP calls the feature +by the same name. The difference is where "the surroundings" live. A `using` parameter searches the +implicit scope by type; an `#[implicit]` argument reads the context field of the matching name, so +resolution is by *field*, decided when the context is defined. `Rectangle` here is a **value +context**: the type carrying `width` and `height` is the rectangle itself. The +[Implicit arguments](/docs/concepts/implicit-arguments) page develops the construct. + +### A shared context value is a threaded environment + +When several pieces of code must agree on one value, Scala uses a single `given Config` and Haskell +the `Reader` monad. CGP has them all read the same field or the same abstract type from the shared +context. CGP's error type is the standing instance: every fallible provider imports the context's +error type with `#[use_type(HasErrorType.Error)]` and names it as the bare `Error`, so all of them +agree on one type the context supplies once. That is a threaded `Reader` environment at the type +level, resolved at compile time. + +### Abstract types are implicit type parameters + +The correspondence runs one level up, and a reader from these languages will recognize this half +fastest. An [abstract type](/docs/concepts/abstract-types) is a type the context determines rather +than one a caller supplies. Haskell's `mtl` achieves the same with a functional dependency: in +`class MonadReader r m | m -> r` the environment type is fixed *by* the monad, and +`MonadError e m | m -> e` says the same for the error type +([`mtl`, `Control.Monad.Error.Class`](https://hackage.haskell.org/package/mtl/docs/Control-Monad-Error-Class.html)). +An associated type family states it more directly still, and is the closest thing in either language +to a `#[cgp_type]` component: + +```haskell +class Monad m => MonadError e m | m -> e where + throwError :: e -> m a +``` + +```rust +#[cgp_type] +pub trait HasErrorType { + type Error: Debug; +} +``` + +Both exist for the same reason. A plain type *parameter* propagates: a signature that mentions `e` +and `r` carries them through every intermediate function that only passes a value along, as a Rust +generic function's `where` clause does. Making the type determined by the context, whether by a +functional dependency, an associated type, or a CGP abstract type, stops it propagating, because a +determined type is an output rather than an input. Two differences follow the same axes as the value +case. On *selection*, an `mtl` instance for a given monad is unique program-wide, whereas CGP's is a +wiring entry and two contexts may bind the same abstract type differently. On *propagation*, CGP +hides more: a CGP consumer trait declares the abstract-type trait as a supertrait, so a caller +bounding on the consumer gets it implied without restating it. + +### Components and wiring are type classes without coherence + +A CGP component is a type class, a provider is an instance, and wiring is the resolution step. Because +a provider's `Self` is its own marker type, many providers for the same component coexist, which +instances cannot do. Two encoders that both apply to `Vec` are selected per context: + +```rust +#[cgp_component(Encoder)] +pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; +} + +#[cgp_impl(new EncodeAsHex)] +impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value.as_ref().iter().flat_map(|byte| format!("{byte:02x}").into_bytes()).collect() + } +} + +#[cgp_impl(new EncodeBytes)] +impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value.as_ref().to_vec() + } +} + +delegate_components! { + AppA { + open EncoderComponent; + @EncoderComponent.Vec: EncodeAsHex, + } +} + +delegate_components! { + AppB { + open EncoderComponent; + @EncoderComponent.Vec: EncodeBytes, + } +} +``` + +The `Comparator[Int]` that Scala can define once becomes any number of interchangeable providers, +each selected per context. `AppA` and `AppB` are **environmental contexts**, types standing for an +application, and the component is parameter-targeted: `Self` is the application and the encoded value +is the `Value` parameter. The freedom has the cost the type-class trade predicts: CGP will not +*find* the provider for you by type. A context names its choice in a table, where Scala and +Haskell would resolve the instance from the type. + +## What each approach costs + +Implicit parameters and the type classes built on them are valued for erasing boilerplate: a +`Config` or a comparator threads through a deep call graph without appearing at every call, and one +generic function works over any type with an instance. Their costs, as their users state them, come +from the same generality. The recurring Scala complaint is that a value appears from nowhere, and tracking +down which `given` was selected, or why an expected one was not, takes time; Scala 2's single +overloaded keyword made it worse, and Scala 3 split the keyword apart to address it +([Baeldung](https://www.baeldung.com/scala/scala-3-implicit-redesign)). Haskell's `ImplicitParams` +is little used for the concrete reasons its manual records: leaking constraints, no defaults, and the +monomorphism restriction +([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/implicit_parameters.html)). +And coherence itself is a persistent source of friction: the orphan rule shapes module structure, and +the one-instance-per-type limit forces `newtype` wrappers whenever a second interpretation of a type +is wanted ([Yang, 2014](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). + +CGP pays with the wiring itself. There is no automatic search, so the choice must be written down, +once per context, and a component must be declared before it can have providers. The compile-time +work is real. And the raw diagnostics are trait-solver output over generated types: +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +alternatives. + +## Where implicit resolution is the better choice + +When a program wants one canonical instance per type, one `Ord`, one `Show`, one serialization, and +values automatic resolution above all, type classes are the better tool, and fighting their coherence +with CGP-style wiring would be over-engineering. The same holds in Rust: a trait with one +implementation per type is an ordinary trait. CGP's explicit wiring is the better tool when a program +needs several interchangeable implementations, per-deployment or per-context choice, or must +implement a behavior for types and traits it does not own. + +## What to expect that differs + +**CGP does not find the provider by type.** A reader used to `given` resolution will expect the +compiler to locate the implementation. In CGP the provider is named in a table, once per context. +Because CGP does not resolve by type, it is free of coherence, and that freedom lets it host the +overlapping instances these languages forbid. + +**Which implementation was chosen is a line you can read.** The value still arrives without being +threaded by hand, but the choice is a wiring entry rather than the outcome of a scope search, so there +are no priority rules and no ambiguity to debug. + +**An abstract type is chosen per context, not per type.** An `mtl` instance fixes the environment +type once for a monad program-wide. A CGP abstract type is a wiring entry, and two contexts may bind +it differently. + +**Resolution is by field name, not by type.** An `#[implicit]` argument reads the context field with +the matching name. Two fields of the same type are distinct arguments, where a `using` parameter of +that type would be ambiguous. + +## Where to go next + +- [Implicit arguments](/docs/concepts/implicit-arguments): the construct this page maps onto a + `using` parameter, with its borrowing rules. +- [Abstract types](/docs/concepts/abstract-types): why a determined type propagates nowhere while a + parameter propagates everywhere. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): how a provider's requirements + stay out of the caller's signature. +- [Type classes](./type-classes.md): the coherence trade in full. +- [Rust's own proposals](./rust-language-proposals.md): the contexts-and-capabilities proposal as + Rust's `using Config`. + +## Sources + +The Haskell snippets were compiled with GHC 9.10 and the Scala snippets with Scala 3.8.4. The CGP +snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per wired +context. + +- [Scala 3 Book, *Context Parameters*](https://docs.scala-lang.org/scala3/book/ca-context-parameters.html) and [Scala 3 Reference, *Given Instances*](https://docs.scala-lang.org/scala3/reference/contextual/givens.html): `using` clauses, `given` instances, and the 3.6 syntax change. +- [Baeldung, *Scala 3 Implicit Redesign*](https://www.baeldung.com/scala/scala-3-implicit-redesign): the rename from `implicit` to `given`/`using` and the reasons for it. +- [GHC User's Guide, *Implicit Parameters*](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/implicit_parameters.html): the `?x` syntax, `let` binding, propagation, and the documented restrictions. +- [Type class (Wikipedia)](https://en.wikipedia.org/wiki/Type_class) and [okmij.org, *Implementing, and Understanding Type Classes*](https://okmij.org/ftp/Computation/typeclass.html): type classes as dictionary-passing elaboration. +- [Yang, *Type classes: confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/) and [Bottu et al., *Coherence of Type Class Resolution*](https://xnning.github.io/papers/coherence-class.pdf): the definition of coherence and why it constrains instances to one per type. +- [`mtl`, `Control.Monad.Error.Class`](https://hackage.haskell.org/package/mtl/docs/Control-Monad-Error-Class.html): the `MonadError e m | m -> e` functional dependency. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/index.md b/docs/comparisons/index.md new file mode 100644 index 00000000..2909d622 --- /dev/null +++ b/docs/comparisons/index.md @@ -0,0 +1,57 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'CGP placed against the ideas its readers already know, one page per idea.' +--- + +# Comparisons + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time. It is a +library on stable Rust, and a CGP trait is an ordinary Rust trait; the [Introduction](/docs/) says +what that means. These pages are for a reader who already knows a related idea from another language +or paradigm and wants CGP placed in it. Each page maps CGP into that idea's vocabulary, shows the two +side by side in code, states what each costs, and says where the reader's own tool is the better +choice. + +## Which page to read + +Start from what you already know. The first two pages are the ones a Rust programmer compares CGP +to before anything else; the rest are grouped by the tradition they come from. + +| If you know | Read | +| --- | --- | +| Rust's coherence debates: specialization, named impls, contexts and capabilities | [Rust's own proposals](./rust-language-proposals.md) | +| C++ templates, policy classes, CRTP, and concepts | [Policy-based design](./policy-based-design.md) | +| Haskell, Agda, or Lean type classes | [Type classes](./type-classes.md) | +| OCaml or Standard ML signatures, structures, and functors | [ML modules](./ml-modules.md) | +| Scala `given`/`using`, Haskell `ImplicitParams`, or the `Reader` monad | [Implicit parameters](./implicit-parameters.md) | +| Koka, OCaml 5, Flix, or Eff effect handlers | [Algebraic effects](./algebraic-effects.md) | +| PureScript rows, OCaml polymorphic variants, or structural typing | [Row polymorphism](./row-polymorphism.md) | +| Spring, Guice, Dagger, or constructor injection | [Dependency injection](./dependency-injection.md) | +| Python, Ruby, JavaScript, Smalltalk, vtables, or prototypes | [Dynamic dispatch](./dynamic-dispatch.md) | +| Bevy reflection, Zig `comptime`, or Rust's reflection work | [Reflection](./reflection.md) | +| Object capabilities, `cap-std`, WASI, Effekt, or Scala capture checking | [Capabilities](./capabilities.md) | + +## What every page shares + +Each page follows the same shape, so a reader who has read one can skim the next by habit. It opens +with a short table that maps the idea's vocabulary onto CGP's. It refreshes the idea in a few cited +snippets, shows the same problems written in CGP, and names which of CGP's context shapes each +snippet uses. It then states what each approach costs, in the words its own community uses for its +costs, and gives the cases where the compared tool is the better choice their own section. A closing +section lists the expectations a reader of that background holds that CGP does not meet, each with +the reason CGP is arranged as it is. + +Every page cites its sources, and every snippet in another language was compiled against the +toolchain the page names. The CGP code on every page compiles against the current release. + +## Where to go next + +The [Concepts](/docs/concepts/) pages explain CGP's own ideas without reference to another paradigm, +and each comparison links the concept pages it rests on. The [tutorials](/docs/tutorials/hello) build +working programs, and the [reference](/docs/reference/) specifies each construct a comparison names. + +--- + +*An AI agent wrote this page using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/ml-modules.md b/docs/comparisons/ml-modules.md new file mode 100644 index 00000000..e65488be --- /dev/null +++ b/docs/comparisons/ml-modules.md @@ -0,0 +1,339 @@ +--- +sidebar_label: 'ML modules' +sidebar_position: 4 +description: 'CGP read against OCaml and Standard ML signatures, structures, functors, and modular implicits.' +--- + +# ML modules and modular implicits + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows +the signature, structure, and functor system of OCaml or Standard ML, and the *modular implicits* +extension that adds type-directed resolution over it. CGP's components, providers, and higher-order +providers line up with signatures, structures, and functors, and CGP replaces the manual, ordered +functor application that assembling a large ML program requires with a declarative wiring table. The +page covers that correspondence, the one thing ML does that CGP does not, and what an ML reader +should expect to differ. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. In most CGP code it is a type you define to stand for an application, and it is where the +functor applications an ML program writes by hand are recorded instead. + +| In ML | In CGP | +| --- | --- | +| A signature | A **component**: one trait with many possible implementations | +| A structure ascribing to it | A **provider**: a named implementation | +| A functor | A **higher-order provider**, parameterized by another provider | +| A signature's abstract `type t` | An abstract type, chosen by the context through `#[cgp_type]` | +| The sequence of functor applications | The **wiring table**, written with `delegate_components!` | +| Checking an argument against a functor's parameter signature | `check_components!` at the wiring site | +| Modular implicits' type-directed search | Nothing: the table names each choice | + +## The idea, briefly + +ML modules build large programs from interchangeable, separately specified parts with real type +abstraction. A *signature* states what a component provides without fixing representations, a +*structure* implements it, and a *functor* is a module parameterized by another module. The module +system is widely regarded as one of the most expressive in any language +([Dreyer, *Understanding and Evolving the ML Module System*](https://people.mpi-sws.org/~dreyer/thesis/main.pdf)). +The snippets below are OCaml, compiled with OCaml 5.5.0, except the modular-implicits one, which +follows the proposal paper because that extension has never shipped in mainline OCaml. + +### Signatures, structures, and abstract types + +A signature specifying an abstract type `t` and a `compare` over it, and a structure implementing it: + +```ocaml +module type OrderedType = sig + type t + val compare : t -> t -> int +end + +module StringCompare = struct + type t = string + let compare = String.compare +end +``` + +The `type t` left without a definition is the core of ML data abstraction. When a structure is +*sealed* with a signature that keeps `t` abstract, clients cannot see the representation, and the +type system enforces representation independence +([*Modules and Data Abstraction in OCaml*](https://cs.wellesley.edu/~cs251/s12/handouts/modules.pdf)). +Sealing hides a *known* type's representation rather than abstracting over an unknown one. + +### Functors + +A functor takes a module of some signature and produces a module built on top of it: + +```ocaml +module Make (O : OrderedType) = struct + (* ... a set implementation using O.compare ... *) +end + +module StringSet = Make (StringCompare) +``` + +The application is explicit and by name, and OCaml's standard library uses the shape throughout, as +in `Set.Make(String)` ([OCaml, *Functors*](https://ocaml.org/docs/functors)). Two subtleties make +functors heavier than the shape suggests. When a functor result's abstract type must be known to +equal another type, the programmer writes a *sharing constraint* with `with type`, a recurring source +of type errors. And OCaml functors are *applicative* by default while SML's are *generative*, so +whether two applications yield equal abstract types depends on the language and on a trailing `()` +argument ([OCaml manual](https://ocaml.org/manual/5.5/firstclassmodules.html)). + +### Assembling a program: manual functor plumbing + +Building a whole application from functors means applying each one by hand, in dependency order. +The MirageOS project makes the cost concrete: the unikernel running its website "contains more than +70 modules and a functor application depth of up to 10", and the community built a DSL, Functoria, +to organize the applications, because "OCaml's module language is much less flexible than its +expression language" ([*Functor Driven Development*](https://arxiv.org/pdf/1905.02529)). A mature +ecosystem writing a configuration DSL to escape manual functor application is the clearest evidence +of the limitation CGP's wiring addresses. + +### Modular implicits + +Modular implicits extends OCaml so that module arguments can be marked implicit and resolved by type. +A function takes an implicit module parameter in braces, and the compiler searches the implicit +modules in scope for one of the required signature +([White, Bour & Yallop, *Modular implicits*](https://arxiv.org/abs/1512.01895)): + +```ocaml +module type Show = sig + type t + val show : t -> string +end + +let show {S : Show} x = S.show x + +implicit module Show_int = struct + type t = int + let show x = string_of_int x +end + +implicit module Show_list {S : Show} = struct + type t = S.t list + let show x = "[" ^ String.concat ", " (List.map S.show x) ^ "]" +end + +let () = + print_endline (show 5); (* resolves Show_int *) + print_endline (show [1; 2; 3]) (* resolves Show_list(Show_int) *) +``` + +`Show_list` is an *implicit functor*, applied during resolution, which is the module-system +counterpart of Haskell resolving `Show [Int]` from `Show Int`. The proposal remains an +[experimental fork](https://github.com/ocamllabs/ocaml-modular-implicits). + +### Classes as signatures + +The mapping this page rests on is a known result. Dreyer, Harper, and Chakravarty's *Modular Type +Classes* treats classes as signatures and instances as structures and functors +([*Modular Type Classes*](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf)). The +[type classes](./type-classes.md) page develops the result and the canonicity-versus-modularity +tension it exposes. + +## How CGP expresses it + +CGP reproduces the signature, structure, and functor triad with its consumer and provider machinery, +then replaces manual functor application with a declarative table. + +### Components are signatures; providers are structures + +Declaring a component states the interface, and a provider supplies the implementation: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} +``` + +`CanCalculateArea` is the signature and `RectangleArea` is a structure ascribing to it. One piece +has no ML counterpart: CGP splits the trait into a consumer side callers use and a provider side +implementers target, whereas an ML signature is one interface used from both sides. The split exists +because Rust has coherence and ML does not. ML holds many structures of one signature by *naming +them*, so it never needs the maneuver CGP uses to escape the one-implementation-per-type rule; the +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) page explains it. A CGP +component is also typically a small signature with one operation, where an ML signature bundles many +values and types; a rich ML signature corresponds to several components combined through `#[uses]`. +The wired type here is a `Rectangle` carrying `width` and `height`, a **value context**: the type +being measured also carries the wiring. + +### Abstract-type components are a signature's abstract types + +An abstract-type component is CGP's version of a signature's abstract `type t`, defined with +[`#[cgp_type]`](/docs/reference/macros/cgp_type). CGP's own error type is the standing example: + +```rust +#[cgp_type] +pub trait HasErrorType { + type Error: Debug; +} +``` + +`HasErrorType` declares an abstract `Error` the way `OrderedType` declares an abstract `t`, and +generic code imports it with `#[use_type(HasErrorType.Error)]` and names it as the bare `Error`, +as a functor body refers to `O.t`. The abstraction is the parametric kind, generic code polymorphic +over the type it is given. What CGP does not reproduce is *sealing*: once a context wires `Error` to +a concrete type, no type-system boundary hides that representation from other code. CGP leaves +representation hiding to Rust's module privacy. The [Abstract types](/docs/concepts/abstract-types) +page develops the construct. + +### Higher-order providers are functors + +A [higher-order provider](/docs/concepts/higher-order-providers) is a provider parameterized by +another provider, as a functor is a module parameterized by another module: + +```rust +#[cgp_impl(new ScaledArea)] +#[use_provider(InnerCalculator: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } +} +``` + +`ScaledArea` is `Make (StringCompare)` in CGP form. Two differences favour CGP's +ergonomics. A higher-order provider can default its inner parameter to +[`UseContext`](/docs/reference/providers/use_context), so an unparameterized `ScaledArea` falls back +to whatever the context wires for that component, an open, recursive application a plain functor +cannot express without recursive modules. And CGP sidesteps the sharing-constraint problem: its +abstract types are supplied by the shared context, so every provider in a context agrees on `Error` +with no `with type` annotation to write. + +### `delegate_components!` replaces manual functor application + +The decisive difference is that CGP wires a program declaratively where ML applies functors by hand +in order. A context lists its choices in any order, and the trait system resolves each provider's +dependencies through the context: + +```rust +use cgp::core::error::ErrorTypeProviderComponent; + +delegate_components! { + App { + EmailSenderComponent: SendViaSmtp, + ErrorTypeProviderComponent: UseType, + // ... further components, in any order + } +} +``` + +This is CGP's built-in Functoria. A provider states what it needs as +[impl-side dependencies](/docs/concepts/impl-side-dependencies), and the compiler threads each +requirement to whatever provider the context wires for it, with no application order to get right. +The counterpart to ML's check that a functor argument satisfies its parameter signature is +[`check_components!`](/docs/reference/macros/check_components), which verifies at compile time that a +context supplies every trait its providers transitively need. A reusable bundle of wirings is an +[aggregate provider](/docs/concepts/aggregate-providers) or a [namespace](/docs/concepts/namespaces), +CGP's way of packaging a sub-assembly. `App` here is an **environmental context**, a type standing +for an application, with an `smtp_server` field the email provider reads. + +### Modular implicits and CGP wiring: the same problem, opposite selection + +Modular implicits and `delegate_components!` both answer the limitation that assembling a program from +functors is manual, and they select implementations by opposite means. Modular implicits resolves by +*implicit search*, which shares type classes' coherence-leaning character: a search can be ambiguous, +and canonicity fights abstraction. CGP resolves by *explicit table*: a context names one provider per +component, so there is no search and no ambiguity, and each context may choose differently. The +mechanism the two share is *recursive composition*. An implicit functor such as `Show_list {S : Show}` +builds `Show` of a list from `Show` of its element, as a higher-order provider builds its behavior +from an inner provider resolved through the context. + +## What each approach costs + +ML modules are valued for genuine data abstraction through sealing, for functors as reusable +components against an interface, for separate compilation, and for first-class modules where an +implementation must be chosen at runtime +([OCaml manual, *First-class modules*](https://ocaml.org/manual/5.5/firstclassmodules.html)). Their +costs, as their users state them, cluster around weight and plumbing. Assembling a large application +means applying functors by hand in dependency order, painful enough that MirageOS built Functoria, +and rooted in the *stratification* of ML: the module language is a second, weaker language above the +expression language ([*Functor Driven Development*](https://arxiv.org/pdf/1905.02529); +[Rossberg, *1ML*](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/1ml-core-and-modules-united/47B10882829E4B32F98FBA93B28CEF30)). +Sharing constraints and the applicative-versus-generative distinction are recurring sources of +confusion. Base ML has no ad-hoc polymorphism, the gap that motivated modular implicits, whose paper +opens on OCaml's separate `+` and `+.` ([White, Bour & Yallop, 2015](https://arxiv.org/abs/1512.01895)), +and that extension remains an experimental fork. + +CGP gives up ML's sealing: its abstract types defer and configure a type but do not hide a +representation behind a type-system boundary. Its wiring is trait resolution, which compiles to +direct calls but produces verbose, generated-type errors: [`cargo cgp check`](/docs/cargo-cgp/check) +leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not +yet reshape every class. It resolves at compile time and monomorphizes, so a runtime-chosen +implementation needs a different tool. And its table-driven resolution is more automatic but less +locally obvious than ML's explicit by-name linking. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +alternatives. + +## Where ML modules are the better choice + +When a program needs representation hiding enforced by the type system, separately compiled modules, +runtime selection through first-class modules, or the explicit control of by-name linking, ML modules +are the better tool, and reaching for CGP would forgo abstraction guarantees ML provides natively. CGP +is the better tool when a program needs many interchangeable implementations chosen per deployment, a +dependency graph the compiler wires rather than the programmer, abstract types unified into the same +selection mechanism, and all of it in one language with no module stratum, and can accept Rust as the +platform. + +## What to expect that differs + +**There is no application order.** An ML reader expects to apply functors in dependency order. The +CGP table is unordered, and the compiler resolves each provider's dependencies through the context. +This is Functoria's job done by the type system. + +**Abstract types are not sealed.** A CGP abstract type defers and configures a type but does not +hide a known one. Representation hiding is Rust's module privacy, separate from the abstract-type +mechanism, and a reader who assumes sealing will look for a guarantee CGP does not make through this +feature. + +**Selection is a table, not a search.** Unlike modular implicits, CGP never resolves a provider from +what is in scope. Each context names its choice, and that lets two contexts choose differently +with no ambiguity. + +**Every construct is ordinary Rust.** Providers and contexts are types and traits, wired in Rust, so +there is no separate module language. CGP is a library on stable Rust and a consumer trait can still +be implemented directly, without wiring. + +## Where to go next + +- [Higher-order providers](/docs/concepts/higher-order-providers): the functor correspondence in + full, including the `UseContext` default. +- [Abstract types](/docs/concepts/abstract-types): what an abstract-type component does and does not + hide. +- [Namespaces](/docs/concepts/namespaces): packaging a reusable sub-assembly of wirings. +- [Type classes](./type-classes.md): the modular-type-classes result and where CGP sits on its + spectrum. +- [Dependency injection](./dependency-injection.md): the same wiring seen from the container side. + +## Sources + +The OCaml snippets were compiled with OCaml 5.5.0; the modular-implicits snippet follows the proposal +paper, since the extension has not shipped. The CGP snippets were compiled against `cgp` +`0.8.0-alpha` with a `check_components!` assertion per wired context. + +- [OCaml, *Functors*](https://ocaml.org/docs/functors) and [OCaml manual, *First-class modules* (5.5)](https://ocaml.org/manual/5.5/firstclassmodules.html): signatures, structures, functors, sharing constraints, and the applicative/generative distinction. +- [*Modules and Data Abstraction in OCaml* (Wellesley CS251)](https://cs.wellesley.edu/~cs251/s12/handouts/modules.pdf): sealing for data abstraction. +- [Dreyer, *Understanding and Evolving the ML Module System*](https://people.mpi-sws.org/~dreyer/thesis/main.pdf) and [Rossberg, *1ML*](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/1ml-core-and-modules-united/47B10882829E4B32F98FBA93B28CEF30): the depth of the module system and the critique of its stratification. +- [Dreyer, Harper & Chakravarty, *Modular Type Classes* (POPL 2007)](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf): classes as signatures, instances as structures and functors. +- [White, Bour & Yallop, *Modular implicits* (2014)](https://arxiv.org/abs/1512.01895) and the [experimental fork](https://github.com/ocamllabs/ocaml-modular-implicits): implicit module parameters, implicit functors, and the `Show` example. +- [*Programming Unikernels in the Large via Functor Driven Development*](https://arxiv.org/pdf/1905.02529): functor plumbing at scale in MirageOS and the Functoria DSL. +- [Applicative vs. generative functors (OCaml discussion)](https://discuss.ocaml.org/t/practical-example-of-applicative-vs-generative-functors/13777): the practical distinction. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/policy-based-design.md b/docs/comparisons/policy-based-design.md new file mode 100644 index 00000000..9f4ea29b --- /dev/null +++ b/docs/comparisons/policy-based-design.md @@ -0,0 +1,425 @@ +--- +sidebar_label: 'Policy-based design' +sidebar_position: 2 +description: 'CGP read against C++ policy classes, host templates, CRTP, and concepts, for a reader who composes behavior with templates.' +--- + +# C++ policy-based design + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows C++ +policy-based design, the curiously recurring template pattern (CRTP), and C++20 concepts. CGP's +context, providers, and wiring table are the same compile-time composition with the same zero +runtime cost, and this page shows where the two agree, where CGP declares and checks what a template +leaves implicit, and what a template can do that CGP cannot. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. It plays the host class's part. + +| In C++ | In CGP | +| --- | --- | +| A policy class | A **provider**: a zero-sized type implementing one component | +| The policy interface, documented by hand | A **component**: the interface written as a trait | +| The host class | The context | +| A host class template with policies as type parameters | A **higher-order provider** | +| The template argument list `Host` | The **wiring table** written with `delegate_components!` | +| `static_cast(this)` in a CRTP base | `self` inside `#[cgp_impl]`, which already means the context | +| A concept check at instantiation | `check_components!` at the wiring site | + +## The idea, briefly + +Policy-based design builds a class from interchangeable *policy* classes supplied as template +parameters, so a *host* class composes its behavior at compile time from parts a user chooses. +Andrei Alexandrescu named the technique in *Modern C++ Design*: decompose a class's behavior into +orthogonal policies, each a small class implementing one aspect, and write the main class as a +template that takes the policies as parameters and derives from or holds them. A library "can +support an exponential number of different behavior combinations, resolved at compile time" +([Wikipedia, *Modern C++ Design*](https://en.wikipedia.org/wiki/Modern_C%2B%2B_Design)). The +technique is "a compile-time variant of the strategy pattern" +([Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design)): a policy +selects an algorithm through a template argument, and the compiler inlines the result. + +### Policies and the host class + +The reference example composes a greeting from an output policy and a language policy: + +```cpp +template +class HelloWorld : private OutputPolicy, private LanguagePolicy { +public: + void run() const { + write(message()); + } +}; + +class WriteToStdout { +protected: + void write(std::string&& message) const { + std::println("{}", message); + } +}; + +class EnglishMessage { +protected: + [[nodiscard]] std::string message() const noexcept { return "Hello, World!"; } +}; + +class GermanMessage { +protected: + [[nodiscard]] std::string message() const noexcept { return "Hallo Welt!"; } +}; + +int main() { + HelloWorld helloWorld; + helloWorld.run(); + + HelloWorld helloWorld2; + helloWorld2.run(); +} +``` + +`HelloWorld` is a distinct type from +`HelloWorld`, each with its own inlined `run`. The host's `run` +calls `write` and `message` without knowing which policy supplies them, and the compiler checks that +the chosen policies supply them only when `run` is instantiated. + +### The policy interface is implicit + +A policy has no declared interface. Any class with members of the right names and types qualifies. +The policy interface "doesn't have a direct, explicit representation in code, but rather is defined +implicitly, via duck typing, and must be documented separately and manually" +([Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design)). The +consequence is the classic template failure mode: a policy missing a member produces an error inside +the host's body, after instantiation, phrased in terms of the substituted types rather than the +requirement that was violated. The [row polymorphism](./row-polymorphism.md) page places this duck +typing in the wider structural-versus-nominal landscape. + +### CRTP: a base that knows its derived class + +The curiously recurring template pattern lets a base class template call into the class deriving +from it, statically. The derived class passes itself as the base's template argument, and the base +reaches it with a `static_cast`: + +```cpp +template +struct Base { + void name() { static_cast(this)->impl(); } +protected: + Base() = default; +}; + +struct D1 : public Base { void impl() { std::puts("D1::impl()"); } }; +struct D2 : public Base { void impl() { std::puts("D2::impl()"); } }; +``` + +The pattern gives static polymorphism with no virtual call, because `Derived` is known at compile +time, and policies and mixins use it whenever they need the host's own type. C++23's *deducing this* +removes the manual parameter and cast for the common case +([cppreference, *CRTP*](https://en.cppreference.com/w/cpp/language/crtp)). Its limit is +homogeneity: `Base` and `Base` are unrelated types, so a `std::vector` cannot hold +both. + +### Concepts: making the requirements explicit + +C++20 concepts give a template's requirements a name and let the compiler check them before entering +the body: + +```cpp +template +concept Hashable = requires(T a) { + { std::hash{}(a) } -> std::convertible_to; +}; + +template +void f(T) {} +``` + +The gain is in diagnostics: instead of dozens of lines about an invalid expression deep inside an +algorithm, the error reads that a named concept was not satisfied, at the call +([cppreference, *Constraints and concepts*](https://en.cppreference.com/w/cpp/language/constraints)). +What concepts do not change is *when* the body is checked. Satisfaction is checked by substitution at +instantiation, and a template body is not verified against its concepts at definition, so a host may +use a member its concept never mentions and compile until a policy without that member is +substituted. + +## How CGP expresses it + +CGP is policy-based design with the policy interface declared as a trait, the composition gathered +into a wired context, and the checking moved to the provider's definition. The correspondence is +construct for construct, and the differences fall out of Rust's trait system doing the job that C++ +templates leave to duck typing. + +### Providers are policies; the context is the host + +Each policy becomes a provider of a component, and the host becomes a context that wires one provider +per component. The greeting example declares the two policy interfaces as components, writes each +policy as a provider, and writes the host's `run` as a function over any context that supplies both: + +```rust +#[cgp_component(MessageProvider)] +pub trait HasMessage { + fn message(&self) -> String; +} + +#[cgp_component(Writer)] +pub trait CanWrite { + fn write(&self, message: String); +} + +#[cgp_impl(new EnglishMessage)] +impl MessageProvider { + fn message(&self) -> String { + "Hello, World!".to_owned() + } +} + +#[cgp_impl(new GermanMessage)] +impl MessageProvider { + fn message(&self) -> String { + "Hallo Welt!".to_owned() + } +} + +#[cgp_impl(new WriteToStdout)] +impl Writer { + fn write(&self, message: String) { + println!("{message}"); + } +} + +#[cgp_fn] +#[uses(HasMessage, CanWrite)] +pub fn run(&self) { + self.write(self.message()); +} +``` + +Two hosts are two contexts, each selecting its policies in a wiring table where the C++ version +passes them as template arguments: + +```rust +pub struct EnglishApp; +pub struct GermanApp; + +delegate_components! { + EnglishApp { + MessageProviderComponent: EnglishMessage, + WriterComponent: WriteToStdout, + } +} + +delegate_components! { + GermanApp { + MessageProviderComponent: GermanMessage, + WriterComponent: WriteToStdout, + } +} + +EnglishApp.run(); // Hello, World! +GermanApp.run(); // Hallo Welt! +``` + +`EnglishApp` and `GermanApp` are **environmental contexts**: fieldless types whose only job is to +carry the choice, as `HelloWorld` is a type whose only job is to fix +the policies. Both compositions resolve at compile time, both monomorphize `run` per host, and both +emit a direct call to the chosen `message` and `write`. The difference is in the declarations +around them. `HasMessage` and `CanWrite` are the policy interfaces written down, and +`#[uses(HasMessage, CanWrite)]` is the host stating which policies its body relies on. + +### Policies as type parameters are higher-order providers + +The wiring table is not the only place CGP can put a policy choice. C++ passes policies as template +parameters of the host, and CGP has the same form in the +[higher-order provider](/docs/concepts/higher-order-providers): a provider whose type parameters are +other providers, bound with `#[use_provider]`. The `HelloWorld` host template translates almost +token for token: + +```rust +#[cgp_component(Runner)] +pub trait CanRun { + fn run(&self); +} + +#[cgp_impl(new HelloWorld)] +#[use_provider(W: Writer)] +#[use_provider(M: MessageProvider)] +impl Runner { + fn run(&self) { + W::write(self, M::message(self)) + } +} + +pub struct App; + +delegate_components! { + App { + RunnerComponent: HelloWorld, + } +} + +App.run(); // Hallo Welt! +``` + +The wiring entry names the C++ instantiation as a Rust type: `HelloWorld` +on both sides. The `#[use_provider(W: Writer)]` bound is the concept the C++ version lacks, spelled +out: `W` must implement the `Writer` provider trait for this context, and the body calls +`W::write(self, ...)` as an associated function. The same shape works on a function, which is the +closer reading of a C++ function template that takes policy types. A +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) may be generic over providers, and the caller +instantiates it the way C++ instantiates a template: + +```rust +#[cgp_fn] +#[use_provider(W: Writer)] +#[use_provider(M: MessageProvider)] +pub fn hello(&self) { + W::write(self, M::message(self)) +} + +>::hello(&App); // Hello, World! +``` + +CGP therefore offers both placements. Passing policies as type parameters keeps the choice at the +instantiation site and repeats it wherever the type is named, which is the C++ arrangement with its +costs and its flexibility. Wiring the policies as components on the context names each choice once +and lets generic code require only the traits it uses. A higher-order provider may also default its +inner parameter to [`UseContext`](/docs/reference/providers/use_context), which routes the inner +call back to whatever the context wires for that component. That is a default template argument +whose default is "whatever the host is wired with", and it has no C++ counterpart. + +### `#[cgp_impl]` is CRTP with the cast done for you + +A CGP provider's body refers to the context as `self` and `Self`. CRTP arranges the same thing for a +base class through `static_cast(this)`. The [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) +macro rewrites a provider written in consumer-trait shape into a provider-trait impl whose `Self` is +the provider's own marker and whose context is an explicit parameter, so the `self` a provider body +uses is the context. A policy that needs the host's data reads it as an +[implicit argument](/docs/concepts/implicit-arguments): + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} +``` + +In CRTP terms, `GreetHello` is the base template, the context is `Derived`, and the `#[implicit]` +argument is `static_cast(this)->name` with the cast replaced by a `HasField` bound the +compiler checks. CGP never has the CRTP hazard of passing the wrong derived class, because the +context is supplied by the wiring rather than named at each derivation. The `Person` this provider is +wired on is a **value context**: the type being greeted also carries the wiring. + +### Checked at definition, not at instantiation + +The deepest difference is when a mistake surfaces. A C++ host body is checked when it is instantiated +with concrete policies, and even with concepts the body is not verified against the concept at +definition. A CGP provider is checked when it is written. The `#[uses(HasMessage, CanWrite)]` bounds +are the whole contract `run` may rely on, and a call to a method outside them is an error at `run`'s +definition, for every context at once. The instantiation-time question that remains, whether a +particular context supplies what its providers need, is answered by +[`check_components!`](/docs/reference/macros/check_components) at the wiring site, with the missing +dependency named rather than inside a monomorphized body. The +[type classes](./type-classes.md) and [reflection](./reflection.md) pages draw out the same +property against Haskell's neighbours and Zig's `comptime`. + +### One wired context instead of a repeated parameter list + +A policy-based host carries its policies in its type, so every place that names the host names the +policies: `SmartPtr` appears wherever such a pointer +is declared, and a helper generic over the host repeats the parameter list. CGP can reproduce that +arrangement with a higher-order provider, and it carries the same cost there. The alternative CGP adds +is to wire the policies as components on the context, so the choices live in one +`delegate_components!` table on a context type named once, and code generic over the context requires +only the traits it uses through `#[uses]`. Adding a policy to a host is then a new wiring line rather +than a new template parameter threaded through every signature that mentions the host. The +[dependency injection](./dependency-injection.md) page develops this centralization from the +container side. + +## What each approach costs + +Policy-based design's costs are the familiar costs of C++ templates, as its users state them. The +policy interface is implicit and must be documented by hand, so a wrong policy fails deep inside the +host with an error about substituted types +([Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design)). Long +parameter lists spread through every signature that names a policy-heavy host. Every combination of +policies is a distinct type, so code generic over the host must itself be a template, and +heterogeneous collections need a separate virtual interface. CRTP adds the derived class passed to +the wrong base and a base that cannot see members of a still-incomplete derived class +([Wikipedia, *CRTP*](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)). Concepts +improve diagnostics but leave template bodies checked only at instantiation +([cppreference](https://en.cppreference.com/w/cpp/language/constraints)). Compile times grow with the +number of instantiations, which is a cost CGP's monomorphized wiring shares. + +CGP's costs are of the same species. A provider needs a component to implement, so CGP cannot accept +an arbitrary existing type as a policy the way a template accepts any class with the right members. +Its type-level programming is narrower than template metaprogramming, and its policies cannot +contribute data members to the host by inheritance. The wiring table is more ceremony than a template +argument list for a host with one or two policies. And its raw diagnostics are trait-solver output +over generated types, which a C++ programmer will recognize as the same species as a template error: +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +alternatives. + +## Where a template is the better choice + +Where a class has a few orthogonal policies and its users name the instantiation in one place, a +policy-based template is the smaller tool. Where a policy must contribute data members or types to the +host by inheritance, or where the composition needs value-level template metaprogramming, templates +express what CGP's type level cannot. Where any existing class must be accepted as a policy with no +declaration, structural composition is the requirement and CGP's declared provider traits are in the +way. And where a program needs a heterogeneous collection of hosts with different policies, both +systems fall back to runtime dispatch: virtual functions in C++, `dyn Trait` in Rust, as the +[dynamic dispatch](./dynamic-dispatch.md) page describes. + +## What to expect that differs + +**A provider needs an impl.** A reader used to dropping an existing class in as a policy will find +that CGP requires a provider impl for a declared component. The declaration lets the compiler check +the body once, at its definition, for every context. + +**CGP's type level is types and associated types only.** There is no value-level computation and no +data-member contribution from a provider. CGP is composition of behavior and of abstract types, not a +metaprogramming language. + +**The common form is the wiring table, not the parameter list.** A reader may expect to name policies +at every use, as a template argument list does. CGP can, through a higher-order provider, but the +idiomatic form names each choice once on the context, and a provider that must pin an inner choice +locally is the exception. + +**CGP is not templates done right.** Templates are the more general mechanism. CGP is policy-based +design with declared interfaces, definition-time checking, and a centralized wiring table, on a +language whose trait system already does the checking templates leave to instantiation. + +## Where to go next + +- [Higher-order providers](/docs/concepts/higher-order-providers): the construct this page maps onto + a host template, including the `UseContext` default. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): what the declared + policy interface is made of. +- [Dependency injection](./dependency-injection.md): the same centralization of choices, seen from + the container side. +- [Checking your wiring](/docs/concepts/check-traits): how the instantiation-time question is + answered at the wiring site. + +## Sources + +The C++ snippets are the reference examples from Wikipedia and cppreference, compiled with GCC 15.3 +in C++23 mode. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` +assertion per wired context. + +- [Wikipedia, *Modern C++ Design*](https://en.wikipedia.org/wiki/Modern_C%2B%2B_Design): Alexandrescu's book, the policy and host-class vocabulary, and the exponential-combinations argument. +- [Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design): the `HelloWorld` example, policies as a compile-time strategy pattern, and the statement that the policy interface is implicit. +- [Wikipedia, *Curiously recurring template pattern*](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) and [cppreference, *CRTP*](https://en.cppreference.com/w/cpp/language/crtp): the pattern's mechanism, static polymorphism, the C++23 deducing-`this` alternative, and the homogeneous-container limit. +- [cppreference, *Constraints and concepts*](https://en.cppreference.com/w/cpp/language/constraints): concept syntax, satisfaction checked at instantiation, and the improvement in diagnostics. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md new file mode 100644 index 00000000..af5d497d --- /dev/null +++ b/docs/comparisons/reflection.md @@ -0,0 +1,372 @@ +--- +sidebar_label: 'Reflection' +sidebar_position: 10 +description: "CGP's type-level shapes read against Bevy's runtime reflection, Zig's comptime, and Rust's compile-time reflection work." +--- + +# Reflection and compile-time introspection + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who thinks in +`TypeInfo`, `@typeInfo`, or `TypeId::field`: Bevy's runtime reflection, Zig's `comptime`, Go or +Java reflection, or Rust's own compile-time reflection effort. CGP reaches the same payoff as +compile-time reflection, one generic routine that works over any type's fields, but takes the +structure not as data a routine inspects but as *types* the trait system resolves against. The page +covers the spectrum from runtime to compile-time reflection, where CGP sits on it, what the type-level +encoding buys and costs, and what to expect that differs. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. On this page the context is an application type that wires how each field type is written, +and the reflected struct is a value the context operates on. + +| In a reflection system | In CGP | +| --- | --- | +| A type descriptor: `TypeInfo`, `Shape`, `std.builtin.Type`, `FieldId` | A `#[derive(HasFields)]` type's `Fields`, a type rather than a value | +| A field's name, as a runtime or `comptime` string | `Tag::VALUE`, a `&'static str` recovered from a type-level string | +| A field's type, as an opaque `TypeId` or `Shape` | The field's type, carried as a real type parameter | +| `inline for` over `@typeInfo`, or a walk over a descriptor | A trait recursion over the `Cons`/`Nil` field list | +| A registry mapping types to behavior | The **wiring table**, written with `delegate_components!` | +| An access that fails at runtime | A `check_components!` failure at compile time | + +## The idea, briefly + +Reflection lets one piece of code work over the *shape* of a type it was not written for. Serializers, +DI containers, ORMs, editors, and debuggers all need to walk an arbitrary type's fields by name and +type, and reflection supplies that by making a type's structure available as something the program can +read. Systems span a spectrum. At the runtime end a type carries metadata the program inspects while it +runs (Java, Go, C#, Python, Bevy). In the middle a derive generates a static descriptor that runtime +code walks (Rust's facet). At the compile-time end the compiler evaluates the introspection and emits +only the specialized result (Zig's `comptime`, D, C++26's static reflection +([P2996](https://isocpp.org/files/papers/P2996R13.html)), and Rust's nightly effort). CGP sits just +past the compile-time end, where the structure is not even a compile-time *value* but a *type*. + +### Runtime reflection: Bevy + +`bevy_reflect` is the prominent Rust runtime-reflection system. A type opts in with +`#[derive(Reflect)]`, after which a value can be handled as a `Box`, accessed by string +field name through the `Struct` trait, and downcast back to its concrete type at runtime +([`bevy_reflect` documentation](https://docs.rs/bevy_reflect/latest/bevy_reflect/)). Behind the +dynamic access is `TypeInfo`, a description of a type's shape available without an instance, and a +runtime `TypeRegistry` that maps types to their `TypeInfo` and to associated behavior, so Bevy can +serialize an arbitrary registered component into a scene or drive an editor over types it was never +specialized for ([`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html)). +Every reflective access goes through dynamic dispatch, a downcast, or a registry lookup, and a +mismatch surfaces at run time as a `None` or a panic. + +### Compile-time metaprogramming: Zig's `comptime` + +Zig's `comptime` is the reference design for compile-time reflection. Types are ordinary compile-time +values, `@typeInfo(T)` decomposes a type into a `std.builtin.Type` describing its shape, `inline for` +unrolls a loop over a compile-time collection, and `@field` accesses a field by a compile-time-known +name ([Zig language reference](https://ziglang.org/documentation/master/#typeInfo)). Since Zig 0.14 +the type tags are lowercase, so a struct is matched as `.@"struct"`. This writes any struct as a +JSON-like object and compiles with Zig 0.16: + +```zig +const std = @import("std"); + +fn jsonStringify(value: anytype, writer: anytype) !void { + try writer.writeAll("{"); + inline for (std.meta.fields(@TypeOf(value)), 0..) |field, i| { + if (i > 0) try writer.writeAll(", "); + try writer.print("\"{s}\": {any}", .{ field.name, @field(value, field.name) }); + } + try writer.writeAll("}"); +} +``` + +Because `inline for` unrolls at compile time and `@field` resolves statically, it compiles to the +code a hand-written serializer would. `@Type` runs the introspection in reverse and constructs a type +from a `std.builtin.Type` value, which CGP cannot do. The defining trade of `comptime` is that it is +zero-cost but checked late: a `comptime` routine is fully type-checked only when applied to a concrete +type, so an error surfaces at the use site, per instantiation, as with C++ templates. + +### Compile-time reflection comes to Rust + +Rust filled the absence of reflection with derive macros that generate specialized code per type. The +[facet](https://fasterthanli.me/articles/introducing-facet-reflection-for-rust) crate objects to the +cost: serde's derives monomorphize the serializer anew for every type, so facet's derive generates +*data* instead, a `const SHAPE` descriptor that shared runtime reflection code walks once. + +The nightly compiler effort is the more consequential development, and it is unstable and will +change. Under `#![feature(type_info)]`, `TypeId::of::()` gains query methods that reach a type's +variants and fields by source order, each `FieldId` answering `name()`, `type_id()`, and `offset()`. +The source's own doc tests read: + +```rust +#![feature(type_info)] +use std::any::TypeId; + +struct Point { x: u32, y: u32 } + +assert_eq!(const { TypeId::of::().fields(0) }, 2); +assert_eq!(const { TypeId::of::().field(0, 0).name() }, "x"); +assert_eq!(const { TypeId::of::().field(0, 0).type_id() }, TypeId::of::()); +``` + +The single most important design decision is that this reflection is callable *only at compile time*: +every query carries a `#[rustc_comptime]` marker, because supporting runtime calls would require "some +global table somewhere that maps all `TypeId`s to their repr" +([Rust project goal, *Reflection and comptime*](https://rust-lang.github.io/rust-project-goals/2026/reflection-and-comptime.html)). +The goal names Zig as the model and declines full `comptime` for now, estimating the architectural +change at more than five years away. The [tracking issue](https://github.com/rust-lang/rust/issues/146922) +lists every stabilization step as open, and the plan runs from 2026 to 2028, with the ambition that +crates like Bevy will work with arbitrary types instead of requiring a derive. Everything in this +subsection was read from the compiler source and tracking issues on the day of writing; check them +before relying on a detail. + +## How CGP expresses it + +CGP reaches compile-time reflection's payoff by a different route. It encodes a type's structure as +types and processes them with trait resolution, so the type system does the "reflection" rather than a +routine inspecting a descriptor. The worked example below is a self-contained field writer modeled on +[`cgp-serde`](https://github.com/contextgeneric/cgp-serde)'s `SerializeFields` provider, which does the +same over serde's `Serializer`. Its context is an **environmental context**: the `App` that wires how +each field type is written stands for an application, and the written `Value` is a parameter. + +### A type's shape becomes a type, not a descriptor + +`#[derive(HasFields)]` lifts a struct's structure into the type system as a type-level list, CGP's form +of the `TypeInfo`, `Shape`, and `FieldId` descriptors the reflection systems build: + +```rust +#[derive(HasFields)] +pub struct Config { + pub host: String, + pub port: u16, +} + +// generated: +// impl HasFields for Config { +// type Fields = Product![ +// Field, +// Field, +// ]; +// } +``` + +This is the same information a descriptor carries, each field's name and type, but it is a *type*. +The Rust MVP's `FieldId` answers `type_id()` with an opaque `TypeId` value. CGP's `Field` +carries the field's actual type as a type parameter, and that difference lets CGP dispatch on +it. The [Extensible records](/docs/concepts/extensible-records) page develops the derive. + +### Reflection-driven serialization in the trait system + +One generic writer works over any `HasFields` type, the counterpart of the Zig `jsonStringify` +above. It delegates to a trait that recurses over the field list: + +```rust +#[cgp_component(ValueWriter)] +pub trait CanWriteValue { + fn write_value(&self, value: &Value) -> String; +} + +#[cgp_impl(new WriteFields)] +impl ValueWriter +where + Value: HasFields, + Value::Fields: FieldsWriter, +{ + fn write_value(&self, value: &Value) -> String { + format!("{{{}}}", Value::Fields::write_fields(self, value)) + } +} +``` + +The `FieldsWriter` trait is the `inline for` of CGP: a recursion over the +[`Cons`/`Nil`](/docs/reference/types/cons) list, with a step for a non-empty list and a base case for +the empty one: + +```rust +pub trait FieldsWriter { + fn write_fields(context: &Context, value: &Value) -> String; +} + +impl FieldsWriter + for Cons, Rest> +where + Tag: StaticString, // the field name, as a const &'static str + Value: HasField, // read this field from the value + Context: CanWriteValue, // write the field through the context's wiring + Rest: FieldsWriter, // recurse on the remaining fields +{ + fn write_fields(context: &Context, value: &Value) -> String { + let field_value = value.get_field(PhantomData); + let entry = format!("\"{}\": {}", Tag::VALUE, context.write_value(field_value)); + let rest = Rest::write_fields(context, value); + if rest.is_empty() { entry } else { format!("{entry}, {rest}") } + } +} + +impl FieldsWriter for Nil { + fn write_fields(_context: &Context, _value: &Value) -> String { + String::new() + } +} +``` + +Every reflection concept has a counterpart here. The recursion over `Cons`/`Nil` is the loop over the +field list. `Tag::VALUE`, recovered through the +[`StaticString`](/docs/reference/traits/formatting/static_string) trait, is the `field.name` a +reflection system reads, produced with no runtime metadata. `value.get_field(PhantomData)` is the +by-name access, resolved statically through [`HasField`](/docs/reference/traits/field-access/has_field). +And `Context: CanWriteValue` is the recursive step: writing each field's value by +dispatching on the field's type, through the context's wiring: + +```rust +delegate_components! { + App { + open ValueWriterComponent; + + @ValueWriterComponent.[String, u16]: WriteWithDebug, + @ValueWriterComponent.Config: WriteFields, + } +} + +App.write_value(&config); // {"host": "localhost", "port": 8080} +``` + +The struct also derives `HasField` so the recursion can read each field; `WriteWithDebug` formats a +value with `Debug`. `cgp-serde`'s [`SerializeFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs) +is this same recursion over a `serde::Serializer`, and its deserialization dual reads a field name as +a runtime string and compares it against each field's compile-time `Tag::VALUE`. + +### Against facet and the reflection MVP + +Four approaches solve the same problem, writing serialization once rather than per type, and comparing +what each turns a type's shape into shows where CGP sits. serde's derive generates *code*, a bespoke +impl per struct. facet generates *data*, a `const SHAPE` walked by a shared runtime routine, which +avoids re-monomorphizing per type at the cost of runtime reflection work. The Rust MVP has the +compiler provide the data, consumed by `const`-evaluated code with no derive. CGP generates +*type-level data*, walked by a shared compile-time routine that monomorphizes to direct code. + +Two differences make CGP's position distinct. First, the field's type is preserved as a type. Facet's +`Shape` and the MVP's `FieldId::type_id()` carry it as an opaque descriptor from which a generic +function cannot be instantiated directly, so recursion into a field's own type is mediated by stored +function pointers or is not yet expressible. CGP's `Field` carries `FieldValue` as a +real type parameter, so `WriteFields` can require `Context: CanWriteValue` and recurse +into a fully typed, statically checked writer for the field's type. Second, CGP dispatches each field +through the *context's* wiring, so the same type is written differently under different application +contexts, the [per-context choice](/docs/concepts/coherence) that facet, serde, and the MVP do not +have. + +The costs are equally clear. Unlike facet, CGP does not solve the monomorphization problem: the +recursion instantiates per field list, so it produces specialized code per type as serde's output +does. What it saves is the authoring duplication, and what it gains is configurability, not binary +size. And unlike the Rust MVP, CGP requires the `#[derive(HasFields)]` opt-in and cannot see a foreign +type that did not derive it. + +### Checked when the code is written, not when it is instantiated + +Zig's `comptime` and the MVP's `const fn` reflection are checked at instantiation: a routine is fully +checked only when applied to a concrete type, so an error surfaces at the use site. CGP's generic code +is checked at its definition. The `where` clause on the `FieldsWriter` impl is verified once against +the bounds, and [`check_components!`](/docs/reference/macros/check_components) verifies that a context +supplies everything its wiring transitively needs. This is the modular checking traits give and +templates do not, and the [type classes](./type-classes.md) page draws it out against Haskell's +neighbours. + +### Reflection that also selects behavior and configures types + +CGP applies the same type-level idea to two things a structural reflection facility does not directly +address. Frameworks do select behavior by reflection, Spring by annotations and Bevy through +`TypeData` in its registry, but as a runtime, registry-mediated act layered on the introspection. CGP +folds behavior selection into the same compile-time table that carries its structural information, and +the [`#[cgp_type]`](/docs/reference/macros/cgp_type) machinery lets a context fix an abstract *type* +through that table too. The `Context: CanWriteValue` bound above shows it: the reflection +that walks the shape and the wiring that interprets each field are one mechanism. + +## What each approach costs + +Reflection is relied upon because a framework written once works over every user type, and runtime +reflection additionally works on types the framework author never saw. Compile-time reflection is +valued for "the expressiveness of runtime reflection with the performance of hand-written code" +([*Compile-Time Reflection with @typeInfo*](https://hive.blog/hive-196387/@scipio/learn-zig-series-32-compile-time-reflection-with-typeinfo)), +and facet and the Rust effort are motivated by cutting derive codegen's compile-time and binary cost. +The costs, as their users state them, split by when the reflection runs. Runtime reflection pays in +performance, since Go's `encoding/json` re-inspects types on every call +([*The Hidden Cost of Reflection in Go*](https://dev.to/devflex-pro/the-hidden-cost-of-reflection-in-go-why-your-code-is-slower-than-you-think-41ee)), +in type safety, since a field named by a string tag fails at runtime +([Go reflection guide](https://medium.com/@mojimich2015/golang-reflection-the-guide-to-runtime-type-inspection-manipulation-and-best-practices-303087684576)), +and in tooling, since renaming a field silently breaks reflective access. Compile-time reflection +answers those and trades them for instantiation-time error messages, added compile-time work, and, as +the Rust tracking issue itself asks, the risk of "monomorphization-time errors" deep inside +instantiation. + +CGP's costs are the ordinary ones plus two specific to this page. It introspects only types that opted +in by deriving its machinery, and only at compile time. It does not reduce the specialized code per +type the way facet does. Its wiring is code somebody writes. And its raw diagnostics are trait-solver +output over generated types, which for a deep field recursion can be long: +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +alternatives. + +## Where reflection is the better choice + +When a program must inspect types at runtime, to deserialize into a type chosen from a config file, +serialize a heterogeneous registry of components, build an editor or a debugger over live values, or +reflect over a foreign type that cannot be made to derive anything, runtime reflection is the right +and only tool of the two, and `bevy_reflect` or facet is the tool to reach for. When a program needs to +construct a new nominal type from computed structure, Zig's `@Type` and C++26's splicers do what CGP's +type-level lists cannot. CGP is the better tool when a program wants generic-over-structure code that +costs nothing at runtime, is checked when written, recurses into field types with full type +information, and drives behavior and type selection as well as data walking. + +CGP and Rust's emerging compile-time reflection are more complementary than competing. The MVP +produces reflection as *const values*, which value-reflection libraries consume natively. CGP consumes +reflection as *types*, a different projection the MVP does not supply, so for CGP to shed its derive +the compiler would need to expose a type's shape as types. Until then CGP's derive stands in for the +compiler-provided reflection Rust is still building. + +## What to expect that differs + +**There is no reflection API.** No `TypeInfo` to hold, no field list to iterate imperatively, no +`TypeId::of::()` to call. The structure is a type that trait impls dispatch on, so reflecting over +it means writing a recursive impl. + +**A field's type is a type, not a `TypeId`.** This is why CGP can recurse into a typed, checked +writer for each field and the raw MVP cannot yet. + +**Shapes are opt-in.** A type exposes its structure only by deriving `HasFields` or `CgpData`. A +foreign type without the derive is invisible. + +**No type synthesis.** CGP's `Product!` and `Sum!` are the `@typeInfo` result reified as types, and +its trait recursion is the `inline for`, but CGP cannot `@Type`-construct a new nominal type. + +**CGP is not a reflection system.** It is compile-time structural reflection encoded as types, +resolved by the trait system, checked at the definition site, and erased before runtime. + +## Where to go next + +- [Extensible records](/docs/concepts/extensible-records) and + [Extensible variants](/docs/concepts/extensible-variants): the derives and what they enable. +- [Row polymorphism](./row-polymorphism.md): the structural-typing theory beneath the type-level + shapes. +- [Dynamic dispatch](./dynamic-dispatch.md): the runtime-mechanism counterpart to this page. +- [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields), + [`Field`](/docs/reference/types/field), and [`StaticString`](/docs/reference/traits/formatting/static_string): + the constructs this page names. + +## Sources + +The Zig snippet was compiled with Zig 0.16; the Rust snippet is the nightly source's own doc test and +is unstable. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` +assertion on the wired context. + +- [`bevy_reflect` documentation](https://docs.rs/bevy_reflect/latest/bevy_reflect/), [`TypeInfo`](https://docs.rs/bevy/latest/bevy/reflect/enum.TypeInfo.html), and [`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html): the `Reflect` trait, the shape descriptor, and the runtime registry. +- [Zig language reference](https://ziglang.org/documentation/master/), [Comptime (zig.guide)](https://zig.guide/language-basics/comptime/), and [*Compile-Time Reflection with @typeInfo*](https://hive.blog/hive-196387/@scipio/learn-zig-series-32-compile-time-reflection-with-typeinfo): `comptime`, `@typeInfo`, `@Type`, `inline for`, and `@field`. +- [Rust tracking issue #146922](https://github.com/rust-lang/rust/issues/146922), the source at [`library/core/src/mem/type_info.rs`](https://github.com/rust-lang/rust/blob/master/library/core/src/mem/type_info.rs), and the [*Reflection and comptime* project goal](https://rust-lang.github.io/rust-project-goals/2026/reflection-and-comptime.html): the `type_info` API, the compile-time-only restriction, and the stabilization plan. +- [fasterthanli.me, *Introducing facet*](https://fasterthanli.me/articles/introducing-facet-reflection-for-rust): the derive-generates-data approach and its motivation. +- [`cgp-serde`, `SerializeFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs): the production version of this page's field recursion, over serde. +- [P2996R13, *Reflection for C++26*](https://isocpp.org/files/papers/P2996R13.html): C++'s static reflection with `std::meta::info` and splicers. +- [*The Hidden Cost of Reflection in Go*](https://dev.to/devflex-pro/the-hidden-cost-of-reflection-in-go-why-your-code-is-slower-than-you-think-41ee) and [*Golang Reflection guide*](https://medium.com/@mojimich2015/golang-reflection-the-guide-to-runtime-type-inspection-manipulation-and-best-practices-303087684576): the runtime performance and type-safety costs of reflection. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md new file mode 100644 index 00000000..8a87e2b5 --- /dev/null +++ b/docs/comparisons/row-polymorphism.md @@ -0,0 +1,346 @@ +--- +sidebar_label: 'Row polymorphism' +sidebar_position: 7 +description: "CGP's extensible records and variants read against PureScript rows, OCaml polymorphic variants, structural typing, and row theory." +--- + +# Row polymorphism, structural typing, and extensible data types + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows +row polymorphism, structural typing, or extensible data types: PureScript's rows, OCaml's polymorphic +variants, TypeScript's structural checking, or the row-theory literature. CGP brings field-and-variant +driven extensibility to Rust's nominal structs and enums, not through a built-in row kind but by +deriving a type-level view of a type's shape and matching names through the trait system. The page +covers the correspondence, the one place the analogy breaks, where a real row system is the better +tool, and what to expect that differs. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. On this page every context is a **value context**: the record being built or the enum being +cast is the type that carries the shape and the wiring, and each component targets `Self`. + +| In a row system | In CGP | +| --- | --- | +| A closed row | A struct's derived `Fields`, a `Product!` of `Field` entries | +| A row variable, "the rest of the fields" | The context type variable, constrained by trait bounds and never named as a row | +| Row containment (`ρ₁ ≲ ρ₂`) | A `HasField` bound, usually written as an `#[implicit]` argument | +| Record concatenation (`ρ₁ ⊙ ρ₂ ~ ρ₃`) | `CanBuildFrom` and the `ConcatProduct` type-level operation | +| A presence flag per label | The `IsPresent` and `IsNothing` markers on a partial record | +| A row-typed sum | An enum's derived `Fields`, a `Sum!` over `Either` and `Void` | +| Variant injection and branching | `CanUpcast`, and the extensible visitor's dispatch | + +## The idea, briefly + +Nominal type systems, Rust's included, force code to name the concrete type it works on. A function +that reads a `name` field must take a specific struct, and two structs with identical fields but +different names are incompatible. The features on this page let a type's structure, not its name, +decide what operations apply. + +### Structural versus nominal typing + +A structural type system decides compatibility by a type's members rather than its name +([Wikipedia, *Structural type system*](https://en.wikipedia.org/wiki/Structural_type_system)). +TypeScript is the mainstream face of it: an object satisfies an interface by having the required +members ([TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-oop.html)), +though TypeScript approximates rather than has row polymorphism +([Bornea](https://medium.com/@gabriel-bornea/approximating-row-type-polymorphism-in-typescript-495ebd5a623d)). +Rust sits at the nominal end: its structs and enums are nominal, and row polymorphism "is notably +absent from Rust's struct system" +([Andreas, *Structural vs Nominal Typing in Rust*](https://felixandreas.me/blog/nominal-vs-structural-types/)). +That absence is the ground CGP works on. + +### Row polymorphism proper, in PureScript + +Row polymorphism is structural flexibility delivered by a *row variable* rather than a subtype +relation: a function accepts any record that has at least the fields it names, and a type variable +carries the others through unchanged ([Wikipedia, *Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism)). +In PureScript a *row* is "an unordered collection of named types", of kind `Row k`, and a record is a +row wrapped by `Record` ([PureScript language reference](https://github.com/purescript/documentation/blob/master/language/Types.md)). +An open row adds a tail variable after a pipe: + +```purescript +-- accepts any record that has at least firstName and lastName; +-- `r` captures whatever other fields the caller's record carries +fullName :: forall r. { firstName :: String, lastName :: String | r } -> String +fullName p = p.firstName <> " " <> p.lastName + +fullName { firstName: "Ada", lastName: "Lovelace" } -- ok +fullName { firstName: "Ada", lastName: "Lovelace", age: 36 } -- also ok; age flows through `r` +``` + +The `Prim.Row` type classes `Cons`, `Union`, `Nub`, and `Lacks` govern the row operations, resolved +during type checking ([Pursuit, *Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row)). +PureScript's design descends from Wand's row variables (1987), Rémy's principal types for rows +(1989), and Leijen's scoped labels (2005), which PureScript adopts directly +([Leijen, *Extensible records with scoped labels*](https://www.microsoft.com/en-us/research/publication/extensible-records-with-scoped-labels/)). + +### Rows as a kind versus rows as predicates + +Two designs realize row polymorphism. PureScript makes rows a *built-in kind* with its own +unification. Gaster and Jones instead encode rows through *qualified types*: a function is polymorphic +over an ordinary type variable, and the *lacks* and *has* predicates it must satisfy are discharged by +the same machinery that resolves type-class instances, with no new kind +([Gaster & Jones](http://web.cecs.pdx.edu/~mpj/pubs/polyrec.html)). CGP most closely resembles this +second design. CGP has no row kind and no row variable, but it does have row *predicates*: a +`HasField` bound is a has-predicate over a context's row, resolved +by the trait solver. Rémy's *presence polymorphism* adds a per-label flag recording presence or +absence, which CGP reproduces with the markers shown below. + +### Extensible variants: the sum-side dual + +Where a row-polymorphic record function accepts "at least these fields", a row-polymorphic variant +value promises "at most these cases". OCaml's *polymorphic variants* are the industrial home of the +dual, needing no central type declaration; OCaml 5.5 infers the type in the comment: + +```ocaml +(* no type declaration needed; the variant type is inferred and reusable *) +let to_int = function + | `On -> 1 + | `Off -> 0 + | `Number n -> n +(* inferred: [< `Number of int | `Off | `On ] -> int *) +``` + +Extensible records and variants are the classic answer to Wadler's *expression problem*: adding both +new cases to a datatype and new operations over it "without recompiling existing code, and while +retaining static type safety" ([Wadler, 1998](https://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt)). +Haskell's *Data types à la carte* is the constraint-based route for sums: a coproduct of signature +functors with a `:<:` constraint whose evidence supplies an injection `inj` and a partial projection +`prj` ([Swierstra](https://www.cs.tufts.edu/~nr/cs257/archive/wouter-swierstra/DataTypesALaCarte.pdf)). + +### The unifying theory + +Morris and McKinna's *rows by any other name* generalizes the designs into *row theories*, "a monoidal +generalization of row types", with two predicates: **combination** `ρ₁ ⊙ ρ₂ ~ ρ₃` and **containment** +`ρ₁ ≲ ρ₂`. Records are built by combination and read by containment; variants are built by +containment and consumed by combination. Its deepest idea for the CGP comparison is that "evidence for +type qualifiers has computational content": the proof that a row contains a label *is* the projection +code ([Morris & McKinna, POPL 2019](https://dl.acm.org/doi/10.1145/3290325)). Koka applies the same +rows to effects ([Leijen, *Koka*](https://arxiv.org/pdf/1406.2061)), which the +[algebraic effects](./algebraic-effects.md) page covers. + +## How CGP expresses it + +CGP keeps Rust's nominal structs and enums and *derives* a type-level description of a type's shape, +then matches field and variant names through the trait system. The row predicates become trait +constraints the trait solver resolves, in the Gaster and Jones style, carried by Rust's traits. + +### A struct is a closed row; `HasField` is row containment + +`#[derive(HasFields)]` gives a struct the type-level equivalent of a closed row, one +`Field` entry per field, tagged by a type-level string: + +```rust +#[derive(HasField, HasFields)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +// generated: +// type Fields = Product![ +// Field, +// Field, +// ]; +``` + +Where PureScript's `fullName` names its required fields with an open row, a CGP function names them +as [implicit arguments](/docs/concepts/implicit-arguments), and any context whose derived row includes +the fields satisfies it: + +```rust +#[cgp_fn] +pub fn full_name(&self, #[implicit] first_name: &str, #[implicit] last_name: &str) -> String { + format!("{first_name} {last_name}") +} + +#[derive(HasField)] +pub struct Employee { + pub first_name: String, + pub last_name: String, + pub badge: u32, +} + +person.full_name(); // "Ada Lovelace" +employee.full_name(); // "Ada Lovelace"; `badge` plays the part of `r` +``` + +The bound each argument desugars to, `HasField`, is the +containment predicate, and the context's other fields play the role of the tail variable. The +difference from PureScript is that the row variable is implicit and never named: CGP does not infer or +carry a residual row, it resolves the containment bound against whatever concrete context is used. + +### Building a record is row combination + +Assembling a struct field by field is CGP's record concatenation. The +[builder family](/docs/reference/traits/builder/has_builder) walks a *partial record* from empty to +complete, and [`CanBuildFrom`](/docs/reference/traits/casting/can_build_from) absorbs the shared +fields of one struct into another's builder in one step, the analogue of PureScript's `Record.union`: + +```rust +let combined: FooBarBaz = FooBarBaz::builder() + .build_from(FooBar { foo: 1, bar: "bar".into() }) // splice one row in + .build_from(Baz { baz: true }) // splice another + .finalize_build(); // exists only when the row is complete +``` + +The underlying type-level operations are a row algebra: [`ConcatProduct`](/docs/reference/traits/type-level/concat_product) +splices two products, `AppendProduct` adds one field, and `MapFields` rewrites every entry, all +evaluated during type checking. That `finalize_build` type-checks only when every field is present is +the completeness guarantee a closed row gives, recovered for generic Rust. The +[Extensible records](/docs/concepts/extensible-records) page develops the pattern. + +### Presence markers are presence polymorphism + +CGP tracks field presence with the per-field flags Rémy's presence polymorphism introduced, as +[`MapType`](/docs/reference/traits/type-level/map_type) markers on a partial record: `IsPresent` +stores the value, `IsNothing` stores nothing, and the +[optional-field extensions](/docs/reference/traits/optional/) add `IsOptional`. A builder starts at +all-`IsNothing`, each step flips one marker, and `FinalizeBuild` exists only at the all-`IsPresent` +configuration. The variant side uses `IsVoid` to mark a case ruled out during extraction. + +### An enum is a row-typed sum; upcast and downcast are injection and branching + +The variant side is the exact dual. The derive represents an enum as a `Sum!` of `Field` entries, and +the [structural casts](/docs/reference/traits/casting/can_upcast) implement the row-theory operations +directly. `CanUpcast` lifts a narrow enum into a wider one, which is variant *injection* and always +succeeds. `CanDowncast` narrows the other way, guarded by containment: + +```rust +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum Reading { + Temperature(u64), + Label(String), +} + +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum ExtendedReading { + Temperature(u64), + Label(String), + Flag(bool), +} + +// upcast: variant injection, always succeeds +let wide = Reading::Temperature(21).upcast(PhantomData::); + +// downcast: succeeds only for variants the target still has +ExtendedReading::Flag(true).downcast(PhantomData::).is_err(); // true +``` + +Branching, the combination predicate on the sum side, is CGP's +[extensible visitor](/docs/concepts/extensible-variants). The `MatchWithValueHandlers` dispatcher +derives one extract-and-handle step per variant from the enum's row and runs them as a pipeline, and +because each failed extraction rules out a variant at the type level, the final match is provably +exhaustive with no wildcard arm. In *Data types à la carte* terms, `CanUpcast` is `inj` and +`CanDowncast` is `prj`, but where à la carte's `prj` returns a `Maybe` with no exhaustiveness check, +CGP's branching consumes the whole sum and proves it covered every case. + +### Providers are the theory's computational evidence + +CGP lines up with the theory on one point more than with any implementing language: Morris and +McKinna's insight that a row predicate's evidence has computational content. In CGP that evidence is +visible. The `HasField` impl a derive generates *is* the projection code, the `CanBuildFrom` recursion +*is* the concatenation code, and a wired provider *is* the witness that a context can perform an +operation. Where a row-typed language elaborates the evidence invisibly, CGP surfaces it as ordinary +traits and impls a programmer can read. + +## What each approach costs + +Row polymorphism is valued because one function serves many record shapes, which "can greatly reduce +refactoring" ([Fowler, *Row Polymorphism without the Jargon*](https://jadon.io/blog/row-polymorphism/)), +and because rows drive codec-free JSON decoding and type-safe bindings +([Nguyen](https://hgiasac.github.io/posts/2018-11-18-Record-Row-Type-and-Row-Polymorphism.html)). Its +costs, as its users state them, cluster in three places. The loudest is error messages: row +unification produces large diagnostics, and one PureScript thread records outputs of around 152 KB +([PureScript Discourse](https://discourse.purescript.org/t/upcoming-changes-to-error-messages-for-large-records-rows/3696)). +The second is complexity: extensible records are widely seen as a specialist tool, and one user who +modeled a domain with them wished afterwards for separate functions per nominal type +([PureScript Discourse](https://discourse.purescript.org/t/when-to-use-extensible-types-when-modeling-a-domain/217)). +The third is specific to pure structural typing: a structurally valid call can be semantically wrong, +"like finding the `area` of a `Fish`" ([Fowler](https://jadon.io/blog/row-polymorphism/)), and OCaml's +manual warns that polymorphic variants "result in a weaker type discipline" and recommends core +variants for simple programs ([OCaml manual](https://ocaml.org/manual/5.5/polyvariant.html)). Two +languages retreated from rows for the first reason: PureScript replaced its row-typed effect monad +because "getting the effect rows to line up was sometimes quite tricky" +([PureScript-Resources](https://purescript-resources.readthedocs.io/en/latest/eff-to-effect.html)), +and Gleam removed row-typed records to become "less structural and more nominal in style" +([Gleam v0.4](https://gleam.run/news/gleam-v0.4-released/)). + +CGP inherits the first two costs in its own idiom. A mis-wired or incomplete structural operation +surfaces as a long, generated-type trait error, and CGP asks for derives, type-level tags, and wiring +where a row system would infer everything. Its mitigations are +[`check_components!`](/docs/reference/macros/check_components), which names the missing field or +variant at the wiring site, and [`cargo cgp check`](/docs/cargo-cgp/check): `cargo cgp check` leads +with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet +reshape every class. The diagnostics remain heavier than a nominal `match`. The third cost CGP largely avoids: because a +provider still binds to a context it was wired for, structure grants access without erasing identity. +The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +alternatives. + +## Where a row system is the better choice + +Where a program wants terse anonymous records with full inference, and can pay the error-message cost, +a real row system such as PureScript's is the better tool, and reaching for CGP's machinery to emulate +it would be over-engineering. Where a program is already in nominal Rust and wants structural +field-and-variant access at a few chosen points, a builder assembled from independent parts, a +visitor over an open set of variants, a cast between sibling enums, CGP delivers row polymorphism's +payoff without adopting a new kind system, and pays the complexity only where it is used. + +## What to expect that differs + +**CGP does not infer rows.** A reader expects `{ name :: String | r }` to be inferred and rows to be +unified. CGP has no row variable and no row inference: a provider names its required fields as +bounds, and a context's shape comes from a derive. Because CGP does not unify open rows, it also does +not produce the row-unification messages that drove PureScript off effect rows and Gleam off row-typed +records; its verbose errors have a different shape and a different mitigation. + +**Structure grants access, not identity.** A row-trained reader may expect any shape-compatible value +to work anywhere. In CGP a provider reads a context's fields structurally, but which providers a +context has is a nominal, wired decision, so the "area of a `Fish`" call is not automatically +expressible. + +**Shapes are opt-in.** Only a type that derives `HasFields` or `CgpData` exposes its row. A foreign +type without the derive has no shape CGP can see. + +**The predicates are traits.** A `HasField` bound is a has-predicate, `CanUpcast` and `CanDowncast` +are `inj` and `prj`, and the trait solver plays the part of qualified-type inference. A reader from +the Gaster and Jones tradition, or from `row-types` in Haskell, will find the mechanism they already +reach for. + +## Where to go next + +- [Extensible records](/docs/concepts/extensible-records): the builder pattern in full. +- [Extensible variants](/docs/concepts/extensible-variants): the visitor pattern and the expression + problem. +- [Reflection](./reflection.md): the same type-level shapes read against runtime and compile-time + reflection. +- [Algebraic effects](./algebraic-effects.md): rows applied to effects, and how CGP's dependencies + compare. +- [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) and + [`CanBuildFrom`](/docs/reference/traits/casting/can_build_from): the constructs this page names. + +## Sources + +The PureScript snippet was compiled with PureScript 0.15.15 against the prelude and the OCaml snippet +with OCaml 5.5.0. The CGP snippets were compiled against `cgp` `0.8.0-alpha`. + +- [Wikipedia, *Structural type system*](https://en.wikipedia.org/wiki/Structural_type_system), [*Nominal type system*](https://en.wikipedia.org/wiki/Nominal_type_system), and [*Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism): the definitions and their contrast. +- [PureScript language reference, *Types*](https://github.com/purescript/documentation/blob/master/language/Types.md), [Pursuit, *Prim*](https://pursuit.purescript.org/builtins/docs/Prim), and [*Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row): rows, records, open-row syntax, and the row type classes. +- [Wand (1987)](https://www.ccs.neu.edu/home/wand/papers/wand-lics-87.pdf), [Rémy (1989)](https://dl.acm.org/doi/10.1145/75277.75284), and [Leijen, *Extensible records with scoped labels* (2005)](https://www.microsoft.com/en-us/research/publication/extensible-records-with-scoped-labels/): the row-polymorphism lineage and presence flags. +- [Gaster & Jones, *A Polymorphic Type System for Extensible Records and Variants* (1996)](http://web.cecs.pdx.edu/~mpj/pubs/polyrec.html): rows as qualified-type predicates, the design CGP's bounds resemble. +- [Swierstra, *Data types à la carte* (JFP 2008)](https://www.cs.tufts.edu/~nr/cs257/archive/wouter-swierstra/DataTypesALaCarte.pdf) and [Wadler, *The Expression Problem* (1998)](https://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt): the constraint-based sum solution and the problem it answers. +- [Morris & McKinna, *Abstracting extensible data types: or, rows by any other name* (POPL 2019)](https://dl.acm.org/doi/10.1145/3290325): row theories, the combination and containment predicates, and evidence with computational content. +- [Leijen, *Koka: Programming with Row-Polymorphic Effect Types* (2014)](https://arxiv.org/pdf/1406.2061): rows applied to effects. +- [OCaml manual, *Polymorphic variants* (5.5)](https://ocaml.org/manual/5.5/polyvariant.html): open and closed variant bounds and the documented weaker discipline. +- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-oop.html), [Bornea](https://medium.com/@gabriel-bornea/approximating-row-type-polymorphism-in-typescript-495ebd5a623d), and [Andreas, *Structural vs Nominal Typing in Rust*](https://felixandreas.me/blog/nominal-vs-structural-types/): the wider structural landscape and Rust's nominal baseline. +- [PureScript-Resources, *Eff to Effect*](https://purescript-resources.readthedocs.io/en/latest/eff-to-effect.html) and [Gleam v0.4 release notes](https://gleam.run/news/gleam-v0.4-released/): two retreats from rows and their reasons. +- [Fowler, *Row Polymorphism without the Jargon*](https://jadon.io/blog/row-polymorphism/), [Nguyen, *Record Row Type and Row Polymorphism*](https://hgiasac.github.io/posts/2018-11-18-Record-Row-Type-and-Row-Polymorphism.html), and PureScript Discourse threads on [error messages](https://discourse.purescript.org/t/upcoming-changes-to-error-messages-for-large-records-rows/3696) and [when to use extensible types](https://discourse.purescript.org/t/when-to-use-extensible-types-when-modeling-a-domain/217): community sentiment. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md new file mode 100644 index 00000000..13ccdb45 --- /dev/null +++ b/docs/comparisons/rust-language-proposals.md @@ -0,0 +1,406 @@ +--- +sidebar_label: "Rust's own proposals" +sidebar_position: 1 +description: 'CGP read against specialization, named impls, dictionary passing, and contexts and capabilities, for a reader who follows the coherence debate.' +--- + +# Rust's own proposals + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who has +followed Rust's own debate about relaxing coherence: *specialization*, the *dictionary-passing* +account of traits, *named or incoherent impls*, and *contexts and capabilities*. It shows which +fragment of each proposal CGP provides today, how the correspondence runs construct by construct, +and the two places where CGP cannot follow the proposals. It ends with what to expect that differs +and where to read further. + +## In your terms + +The proposals and CGP share a vocabulary once the names are lined up. A **context** in CGP is the +type the method runs on, which supplies the values it needs as its fields; in most CGP code it is a +type you define to stand for an application. + +| In the proposals | In CGP | +| --- | --- | +| A named impl (`impl Name = Trait for T`) | A **provider**: a zero-sized type that implements a component's provider trait | +| An `incoherent trait` bound passed at a call | A consumer-trait bound on the context, resolved by the context's **wiring** | +| An impl passed as a parameter (`impl TDrop: Drop` in Cairo) | A **higher-order provider**, bound with `#[use_provider]` | +| A capability in a `with` clause | An `#[implicit]` argument read from a context field | +| The `with` block that binds everything | The definition of a context type and its `delegate_components!` table | +| The root dictionary of a dictionary-passing elaboration | The context itself | + +## The idea, briefly + +Rust's Reference gives the two rules every proposal here relaxes. The *orphan rule* says an +`impl Trait for T0` is valid only if `Trait` is a local trait, or at least one of +the types `T0..=Tn` is a local type and no uncovered type parameter appears before it. The *overlap +rule* rejects two implementations that "can be instantiated with the same type" +([Rust Reference](https://doc.rust-lang.org/reference/items/implementations.html); +[RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). Together they +guarantee that any trait lookup finds exactly one impl, and that guarantee lets generic code resolve +`T: Hash` transitively and keeps a `HashMap` sound. The +[type classes](./type-classes.md) page covers why coherence exists in the wider tradition; this page +takes it as given. + +### Specialization + +RFC 1210 proposes letting two impls overlap when one is *strictly more specific*, with the compiler +picking the specific one. Its own example refines a blanket `AddAssign`: + +```rust +impl + Clone> AddAssign for T { + default fn add_assign(&mut self, rhs: R) { + let tmp = self.clone() + rhs; + *self = tmp; + } +} +``` + +The `default` keyword marks an item that a more specific impl may override +([RFC 1210](https://rust-lang.github.io/rfcs/1210-impl-specialization.html)). The feature has been +unstable since 2016. Its tracking issue states that the full feature "as implemented currently is +*unsound*", because dispatch information about lifetimes is erased before code generation, and the +`min_specialization` subset the standard library uses internally is the usable fragment +([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). On a stable toolchain +the snippet above fails with `E0658`. + +Specialization also does not address the case CGP starts from. Two impls of equal generality, such as +`Hash for T: Display` and `Hash for T: AsRef<[u8]>`, are not ordered by specificity, so specialization +rejects them as coherence does. And generic code can bind a blanket impl through a bound that never +mentions the trait, so by the time the concrete type is known the specialization is invisible. The +[RustLab 2025 talk](/blog/rustlab-2025-coherence) builds this argument on a hash-table example. + +### Dictionary passing + +A second line of thought treats the trait system as sugar over *dictionary passing*: a trait becomes +a struct of function pointers, an impl becomes a value of that struct, and a trait bound becomes an +argument the caller passes. Nadrieril works it out for Rust: + +```rust +struct Clone { + clone: fn(&Self) -> Self, +} + +const CLONE_U32: Clone = Clone { clone: |x: &u32| *x }; +``` + +Trait solving is then the process that supplies these values, and coherence is the point of +friction, since a global impl constrains a caller in ways the caller cannot see +([Nadrieril, *Dictionary-passing style*](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). +Once impls are values, *choosing* an impl is passing a different value, which is the freedom +coherence forbids. + +### Named and incoherent impls + +Boxy's *An Incoherent Rust* proposes dropping the coherence rules in favour of explicit impl +selection. The motivation is *ecosystem evolution*: once a foundational crate such as `serde` +establishes the trait impls for common types, an alternative cannot gain adoption, because downstream +crates cannot implement the competing trait for types they do not own. The sketch names an impl and +passes it where a bound is required: + +```rust +impl Name = Trait for T { /* ... */ } + +function:: + OtherTraitImpl>(/* ... */) +``` + +The post answers the two classic justifications for coherence on their own terms. The `HashMap` +problem is solved by moving the `Hash` and `Eq` bounds onto the type definition, so every operation +on one map agrees on one impl. Associated-type soundness holds because the impl is part of the type. +It names the remaining challenges as substantial: syntax, ergonomics, migration, and whether the +complexity is worth it ([Boxy, *An Incoherent Rust*](https://www.boxyuwu.blog/posts/an-incoherent-rust/)). + +### Contexts and capabilities + +Tyler Mandry's 2021 proposal addresses a different limitation: a function or impl cannot reach a value +from its caller's environment, such as an allocator or a logger, except by threading it as a +parameter or storing it in a global. A `with` clause on a declaration names the context it requires, +and a `with` block at a call site supplies it: + +```rust +fn deserialize<'a>(bytes: &[u8]) -> Result<&'a Foo, Error> +with + arena::basic_arena: &'a arena::BasicArena, +{ + arena::basic_arena.alloc(Foo::from_bytes(bytes)?) +} + +with arena::basic_arena = &arena::BasicArena::new() { + let foo: &Foo = deserialize(bytes)?; +} +``` + +The distinctive power is a *context-dependent trait impl*, valid only when a given capability is in +scope. The mechanism compiles to ordinary function arguments, so it costs nothing at runtime, and the +open questions concern thread boundaries and scope validity +([Mandry, *Contexts and capabilities in Rust*](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). +The proposal borrows the word "capability" from a security model whose other properties it does not +claim; the [capabilities](./capabilities.md) page separates the senses. Nadrieril's follow-up extends +dictionary passing so a trait bound may carry a runtime value, and names the difficulties that follow: +ownership modes for the carried value, the same type satisfying a trait differently in different +scopes, and methods that become closures +([*What If Traits Carried Values*](https://nadrieril.github.io/blog/2026/03/22/what-if-traits-carried-values.html)). + +### Cairo: a Rust-like language that shipped named impls + +Cairo borrows Rust's surface syntax and gives every impl a name, so it is the nearest thing to a +shipped Incoherent Rust. A generic function may take an impl as an explicit parameter, named or +anonymous: + +```rust +// Cairo +fn largest_list>(l1: Array, l2: Array) -> Array { /* ... */ } + +fn smallest_element, +Copy, +Drop>(list: @Array) -> T { /* ... */ } +``` + +A caller does not pass the impl: the compiler infers it from the impls visible at the call site +([Cairo Book, *Traits*](https://www.starknet.io/cairo-book/ch08-02-traits-in-cairo.html); +[*Generic Data Types*](https://www.starknet.io/cairo-book/ch08-01-generic-data-types.html)). That +inference is the design decision that matters for the comparison, because resolving from scope means +the set of imports decides which implementation a call uses. + +## How CGP expresses it + +CGP provides a fragment of each proposal as a library, and the correspondence is close enough to +state construct by construct. What the proposals would add to the language, CGP adds as a library, +with one standing restriction: every binding lives in one place, the context. + +### A named impl is a provider + +A CGP provider is the thing Boxy's proposal names with `impl Name = Trait for T`. Every +implementation gets its own zero-sized type, so two overlapping impls of one trait coexist because +each implements the provider trait for its own name. The encoder pair from the +[Introduction](/docs/) shows it. Rust rejects two blanket impls of one trait for `T: Display` and +`T: AsRef<[u8]>`, since `String` satisfies both. As providers, both compile: + +```rust +#[cgp_component(Encoder)] +pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; +} + +#[cgp_impl(new EncodeWithDisplay)] +impl Encoder { + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() + } +} + +#[cgp_impl(new EncodeBytes)] +impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value.as_ref().to_vec() + } +} +``` + +`EncodeWithDisplay` and `EncodeBytes` are named impls in the proposal's sense. They overlap on +`String`, they are selected by name, and a crate that owns neither `Display` nor `String` may define +more, because the provider trait is always implemented for a type the crate owns. This is the +overlap and orphan relief specialization cannot give, since the two providers are equally general. +The encoded value has moved from `Self` into the `Value` parameter, so `Self` is free to be an +application: the contexts below are **environmental contexts**, types that stand for an application, +and the component is parameter-targeted. + +### An incoherent bound resolves through the context, not at each call site + +Boxy's `function::>` passes the impl at every call. CGP lets generic code require +the consumer trait on the context and defers the choice to the place the context is defined. Two +applications answer differently for the same type: + +```rust +pub struct ApiServer; +pub struct Firmware; + +delegate_components! { + ApiServer { + open EncoderComponent; + @EncoderComponent.String: EncodeWithDisplay, + } +} + +delegate_components! { + Firmware { + open EncoderComponent; + @EncoderComponent.String: EncodeBytes, + } +} +``` + +This is the proposal's incoherence with a different resolution point. Boxy and Cairo resolve at the +call site, explicitly or from what is in scope. CGP resolves at the context, so every call through +`ApiServer` agrees. That is also how CGP answers the `HashMap` concern: a context selects one +provider per component, so all code sharing a context agrees on one impl, which is the property the +proposal recovers by moving `Hash` onto the type definition. The [type classes](./type-classes.md) +page develops this as incoherent instances made deterministic. + +### Passing an impl explicitly is a higher-order provider + +Where the proposals and Cairo let a caller pass an impl as a parameter, CGP has +[higher-order providers](/docs/concepts/higher-order-providers). A provider takes another provider as +a type parameter and binds it with `#[use_provider]`, which is Cairo's `impl TDrop: Drop` as a +Rust generic: + +```rust +#[cgp_impl(new ScaledArea)] +#[use_provider(InnerCalculator: AreaCalculator)] +impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } +} +``` + +A context wires `AreaCalculatorComponent: ScaledArea`, naming the inner impl where a +Cairo caller would have the compiler infer it. Assembling providers at every call site is possible in +CGP but verbose, and idiomatic CGP defers the assembly to the context. A higher-order provider is the +form for a provider that must fix its inner choice locally, and it defaults its inner parameter to +[`UseContext`](/docs/reference/providers/use_context) so the context's wiring is the fallback. The +wired type here is a `ScaledRectangle` carrying `width`, `height`, and `scale_factor`, a **value +context**: the type being measured also carries the wiring. + +### A capability is a context field; the `with` block is the context + +Mandry's `with arena: &BasicArena` clause declares a value the function needs from its environment. +CGP declares the same thing as an [implicit argument](/docs/concepts/implicit-arguments), which +reads a field of the context every provider receives as `self`: + +```rust +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} +``` + +The `with` block that supplies the capability becomes a context type carrying the field, and the +binding happens when a value of that type is constructed: + +```rust +#[derive(HasField)] +pub struct App { + pub name: String, +} + +delegate_components! { + App { + GreeterComponent: GreetHello, + } +} + +let app = App { name: "World".to_owned() }; +app.greet(); // "Hello, World!" +``` + +`App` is the context, and constructing it is the `with` binding. Two properties of the proposal carry +over exactly: the binding costs nothing at runtime, since a field read compiles to a load, and it is +checked statically, since a missing field is a compile error that +[`check_components!`](/docs/reference/macros/check_components) names at the wiring site. `App` here +is an environmental context with one field, and `GreetHello` is self-targeted. + +### The context is the dictionary + +The dictionary-passing account and CGP meet in one observation: the context is the top-level +dictionary. In Nadrieril's elaboration every dictionary is a value passed alongside the data. In CGP +every provider receives the context, and the context's wiring table is a type-level record of +dictionaries, one `DelegateComponent` entry per component. Lowering a CGP program to +dictionary-passing form turns the context into a struct whose fields are the other dictionaries, with +a near one-to-one correspondence between a `delegate_components!` entry and a field of that struct. +The arrangement has a practical consequence the proposals have to solve separately: because every +dictionary reaches the others through the context, a dependency graph with cycles resolves without +an instantiation order, since the context is one stable root from which all of them are reachable. +The [ML modules](./ml-modules.md) page contrasts this with manual functor application. + +## What each approach costs + +The proposals are language changes that have not shipped, and their costs are the ones their authors +name. Specialization has an accepted RFC, a soundness hole open since 2016, and no path to +stabilization ([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). The +named-impl and dictionary-passing designs are blog posts and design sketches, and their authors list +syntax, ergonomics, migration of the existing ecosystem, and the loss of the guarantees coherence +gives for free as the open problems ([Boxy](https://www.boxyuwu.blog/posts/an-incoherent-rust/); +[Nadrieril](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). Contexts +and capabilities is a research direction from 2021 with open questions about thread boundaries and +scope ([Mandry](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). Cairo's +scope-based inference means a caller must import the whole chain of impls a generic impl needs, and +two call sites in one project can resolve the same type differently. + +CGP's costs are the ordinary ones. The provider trait has to be defined through +[`#[cgp_component]`](/docs/reference/macros/cgp_component), so CGP cannot retrofit an existing +foreign trait such as `serde::Serialize` without a parallel component, where a language change would +apply to every trait. The wiring is code somebody writes and reads, where a language feature would +infer it. The compile-time work is real. And the raw diagnostics are trait-solver output over +generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes +it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page is where these costs are weighed +against the alternatives in full. + +## Where a proposal, or a smaller tool, is the better choice + +Where a program needs exactly a specialized fast path for one type under a blanket impl, +`min_specialization` on nightly, or a manual dispatch trick on stable, is the smaller tool, and CGP +would add wiring specialization would infer. Where a program needs one globally consistent +implementation, such as the `Ord` a map's keys rely on, coherence as it stands is the right +arrangement and CGP's per-context choice is not an improvement on it. And where a program can wait, +a language feature that infers the impl from scope or nests bindings dynamically would express these +patterns with less ceremony than a library can. Where the need is several equally valid impls chosen +per application, impls for types the program does not own, or environment values reaching deep code +without parameters, CGP is the one option available on stable Rust today, and its explicitness is the +price of that. + +## What to expect that differs + +**CGP does not infer an impl from scope.** Cairo and the named-impl sketch let the compiler pick an +impl from those visible at a call site. CGP has no such search: a context names every provider it +uses in its wiring table. This is deliberate, and it keeps two call sites in one program from +resolving the same type differently by accident. + +**Bindings are flat.** Mandry's `with` blocks nest, and an inner scope can shadow an outer binding. In +CGP every binding lives at the one place the concrete context is defined, so an inner scope cannot +shadow a provider without defining a new context type. All bindings for a context are readable in one +place, and that is the trade. + +**A provider receives `&self`.** A capability that must be `&mut` or owned needs interior mutability +or cloning, rather than the ownership-aware design the proposals discuss. + +**CGP is not specialization for stable Rust.** It does not pick a more specific impl, it does not +touch existing traits, and it asks for wiring specialization would infer. It addresses the two +problems specialization leaves open, equally general overlap and orphans, by naming implementations +and choosing them per context. + +## Where to go next + +- [Bypassing coherence](/docs/concepts/coherence): the coherence rules and the provider move, without + reference to the proposals. +- [Higher-order providers](/docs/concepts/higher-order-providers) and + [implicit arguments](/docs/concepts/implicit-arguments): the two constructs this page maps onto + passed impls and capabilities. +- [Type classes](./type-classes.md): the same trade seen from Haskell's side, including the + `INCOHERENT` and overlapping-instance extensions. +- [RustLab 2025 talk](/blog/rustlab-2025-coherence): why coherence exists and why specialization does + not remove the overlap problem, argued on a hash-table example. + +## Sources + +The Rust snippets from the proposals are quoted from their authors' posts and the Cairo book. The +specialization snippet was compiled against a stable toolchain to confirm it is rejected with +`E0658`; the CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` +assertion per wired context. + +- [Rust Reference, *Implementations*](https://doc.rust-lang.org/reference/items/implementations.html) and [RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html): the orphan and overlap rules. +- [RFC 1210, *impl specialization*](https://rust-lang.github.io/rfcs/1210-impl-specialization.html) and [tracking issue #31844](https://github.com/rust-lang/rust/issues/31844): the strictly-more-specific rule, the `default` keyword, the lifetime soundness hole, and the `min_specialization` subset. +- [Boxy, *An Incoherent Rust*](https://www.boxyuwu.blog/posts/an-incoherent-rust/): named impls, `incoherent trait`, the ecosystem-evolution motivation, and the `HashMap` and associated-type answers. +- [Nadrieril, *Elaborating Rust Traits to Dictionary-Passing Style*](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html) and [*What If Traits Carried Values*](https://nadrieril.github.io/blog/2026/03/22/what-if-traits-carried-values.html): traits as structs and impls as values, and the extension that carries values. +- [Mandry, *Contexts and capabilities in Rust*](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/): the `with` clause and block, context-dependent trait impls, and the open questions. +- [Cairo Book, *Traits in Cairo*](https://www.starknet.io/cairo-book/ch08-02-traits-in-cairo.html) and [*Generic Data Types*](https://www.starknet.io/cairo-book/ch08-01-generic-data-types.html): named and anonymous impl parameters and compiler inference of the impl. +- [Ixrec, *rust-orphan-rules*](https://github.com/Ixrec/rust-orphan-rules) and [Greyblake, *Alternative blanket implementations for a single Rust trait*](https://www.greyblake.com/blog/alternative-blanket-implementations-for-single-rust-trait/): the orphan rule as a durable frustration and the hand-rolled marker-struct workaround for overlap. +- [RustLab 2025, *How to stop fighting with coherence*](/blog/rustlab-2025-coherence): why specialization does not solve overlap, and the connection to the contexts-and-capabilities proposal. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md new file mode 100644 index 00000000..0cfec37c --- /dev/null +++ b/docs/comparisons/type-classes.md @@ -0,0 +1,383 @@ +--- +sidebar_label: 'Type classes' +sidebar_position: 3 +description: 'CGP read against Haskell, Agda, and Lean type classes, coherence, and the overlapping and incoherent instance extensions.' +--- + +# Type classes + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a +library on stable Rust in which a trait can have several named implementations and each context +selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows type +classes from Haskell, Agda, or Lean. Rust traits are Rust's type classes, so CGP already lives inside +a type-class system, and its one change is to the *coherence* rule: it makes instances first-class +values selected explicitly per context, which is the freedom overlapping and incoherent instances +reach for without making it safe. The page covers the class and instance correspondence, the +coherence trade, where coherent type classes remain the better tool, and what a type-class reader +should expect to differ. + +## In your terms + +A **context** in CGP is the type the method runs on, which supplies the values it needs as its +fields. In the dictionary-passing account it is the dictionary that carries every other dictionary. + +| In a type-class language | In CGP | +| --- | --- | +| A class | A **component**: one trait with many possible implementations | +| An instance, anonymous and canonical | A **provider**: a named, selectable implementation | +| Instance resolution by the compiler | **Wiring**, written by hand in a `delegate_components!` table | +| A class constraint on a function | An **impl-side dependency**, declared with `#[uses]` | +| The dictionary passed as a hidden argument | The context | +| A class's associated type | An abstract type, chosen by the context | + +## The idea, briefly + +Type classes make overloading principled. A class declares an interface, an instance implements it +for a type, and a constrained function works for every type with an instance, with the compiler +finding the instance. Wadler and Blott introduced them to "make ad-hoc polymorphism less ad hoc" +([Wadler & Blott, 1989](https://dl.acm.org/doi/10.1145/75277.75283)): + +```haskell +class Show a where + show :: a -> String + +instance Show Bool where + show True = "True" + show False = "False" + +describe :: Show a => a -> String +describe x = "value: " ++ show x +``` + +Underneath, the class is a *dictionary*, a record of the class methods; an instance is a dictionary +value; and `describe` elaborates to a function that takes the dictionary as an extra hidden argument. +Dictionary passing is the implementation model behind every system on this page, and behind CGP. It +is the same idea as the evidence passing on the [algebraic effects](./algebraic-effects.md) page and +the qualified-type constraints on the [row polymorphism](./row-polymorphism.md) page. + +### Coherence: one instance per type, globally + +*Coherence* makes silent, automatic resolution safe. For a given class and type there is one +instance, and every resolution anywhere in the program finds the same one. The property decomposes +into *confluence*, *coherence*, and *global uniqueness*; GHC guarantees the first two within a +compilation and does not enforce the third across a whole program +([Yang, *Type classes: confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). +The canonical benefit is a `Set` of an ordered element type: with one `Ord` for that type, values +inserted under one ordering and read under another can never disagree. + +Rust makes the same choice and *enforces* it where Haskell advises. Rust traits are type classes with +a hard orphan rule, so an impl is allowed only when the crate owns the trait or the type +([RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). That strictness +is the rule CGP is built to work within, and the [Rust proposals](./rust-language-proposals.md) page +covers what Rust itself has considered doing about it. + +### Overlapping instances + +The first extension lets instances overlap when one is strictly more specific. GHC exposes it through +per-instance pragmas: + +```haskell +instance {-# OVERLAPPABLE #-} Show a => Show [a] where -- lists in general + show xs = "[" ++ intercalate "," (map show xs) ++ "]" + +instance {-# OVERLAPPING #-} Show [Char] where -- but strings specially + show s = s +``` + +Resolution commits to an instance only when it is strictly more specific than every other match. +GHC's own manual warns that "overlapping instances must be used with care as they can give rise to +incoherence (different instance choices are made in different parts of the program)" +([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). + +### Incoherent instances + +The second extension lets the compiler commit to an instance even when the choice is not unique. An +instance marked `{-# INCOHERENT #-}` may be selected where a more specific one could later apply, so +different parts of a program can resolve the same constraint to different dictionaries. The manual +states the danger: GHC's optimiser "assumes that type-classes are coherent, and hence it may replace +any type-class dictionary argument with another dictionary of the same type", so incoherence "may +cause unexpected results" ([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). + +### Instance arguments in Agda + +Agda offers class-style overloading without a class construct and without coherence. A record plays +the class, and a double-braced argument is resolved from the call-site scope +([Devriese & Piessens, 2011](https://dl.acm.org/doi/10.1145/2034574.2034796)): + +```agda +record Show (A : Set) : Set where + field show : A → String + +instance + showBool : Show Bool + showBool = record { show = λ b → if b then "true" else "false" } + +print : {A : Set} → {{Show A}} → A → String +print {{s}} x = Show.show s x +``` + +Resolution succeeds when exactly one instance in scope matches, and an ambiguity is a local error at +that use site rather than a program-wide guarantee. + +### Type classes in Lean: search, priorities, and the diamond problem + +Lean resolves classes by a backtracking tabled search with per-instance priorities: + +```lean +class Show (α : Type) where + display : α → String + +instance : Show Bool where + display b := if b then "true" else "false" + +#eval Show.display true -- "true" +``` + +Because Lean allows multiple instances, the same constraint can be satisfiable in more than one way, +and when two resolution paths disagree, a *diamond*, inference can pick the wrong one or diverge +([Selsam, Ullrich & de Moura, *Tabled Typeclass Resolution*](https://arxiv.org/pdf/2001.04301)). In +a proof assistant two instances that are not definitionally equal break proofs that assume they +coincide, so the Mathlib community keeps overlapping instances definitionally equal as a standing +discipline ([Baanen, 2022](https://arxiv.org/pdf/2202.01629)). + +### Modular type classes + +Dreyer, Harper, and Chakravarty showed that type classes are ML modules plus a resolution layer: +**classes as signatures and instances as structures and functors**, with certain instance modules +designated *canonical* within a scope so the compiler can resolve them implicitly +([*Modular Type Classes*](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf)). The paper +names the tension every design on this page negotiates: **canonicity fights modularity.** A canonical +instance makes implicit resolution safe, and it is a non-modular property, since two modules can each +supply a different one. The design space is a spectrum. At one end sits Haskell: fully +implicit resolution, global coherence, one instance per type. In the middle sit modular type classes, +OCaml's modular implicits, Agda instance arguments, and Scala implicits: implicit resolution with +canonicity scoped or dropped, paid for in ambiguity. CGP sits at the far end: no canonicity, no +search, and explicit per-context selection. The [ML modules](./ml-modules.md) page develops the +module side. + +## How CGP expresses it + +CGP is a type-class system with the coherence rule removed and explicit per-context selection in its +place, built by splitting each class into a consumer trait callers use and a provider trait +implementations target. The consumer trait is an ordinary Rust type class. The provider trait and the +wiring are what make instances first-class values. + +### A component is a class; a provider is a first-class instance + +Declaring a component is declaring a class: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} +``` + +`CanCalculateArea` is the class interface, as `class Show a` is. The two systems differ in what an +instance may be. A Haskell instance is anonymous and canonical: there is one `Show Bool`, chosen by the +compiler. A CGP provider is a named marker type carrying a provider-trait impl, a *first-class +dictionary* you can name and choose among: + +```rust +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { Rectangle { AreaCalculatorComponent: RectangleArea } } +``` + +Moving the implementation off the context and onto a provider marker is the single device that lifts +the one-instance-per-type limit: because a provider implements the provider trait for *its own* type, +coherence never forbids a second one. The wiring line plays the role of resolution, explicitly, where +Haskell's compiler would search for the canonical instance. A provider's `#[uses]` imports are the +class constraints threaded by dictionary passing, and the context is the dictionary that carries them. +`Rectangle` here is a **value context**: the type being measured also carries the wiring, and the +component is self-targeted. + +### Overlapping instances are the default, with no heuristic + +Where Haskell needs pragmas and a most-specific heuristic to permit overlap, CGP permits unlimited +overlapping providers by construction and resolves them by naming rather than guessing. Two encoders +that both apply to `String` compile side by side: + +```rust +#[cgp_component(Encoder)] +pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; +} + +#[cgp_impl(new EncodeWithDisplay)] +impl Encoder { + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() + } +} + +#[cgp_impl(new EncodeBytes)] +impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value.as_ref().to_vec() + } +} + +#[cgp_impl(new EncodeAsHex)] +impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value.as_ref().iter().flat_map(|byte| format!("{byte:02x}").into_bytes()).collect() + } +} +``` + +As type-class instances two of these would be rejected, since `String` matches the first pair and +`Vec` matches the second, and even with `OVERLAPPING` the compiler would need one to be strictly +more specific. As providers all three compile, because each implements the provider trait for its +own marker. There is no most-specific rule and therefore no ambiguity. The fragility +GHC warns about, overlap silently producing incoherence, cannot arise, because the choice is never +inferred. Here the encoded value has moved from `Self` into the `Value` parameter, so the contexts +that wire these providers are **environmental contexts**, types standing for an application, and the +component is parameter-targeted. + +### Incoherent instances made deterministic and local + +CGP keeps the many-instances-for-one-type situation that type-class languages fear and makes it safe +by moving the choice from a global search to an explicit per-context table: + +```rust +pub struct AppA; +pub struct AppB; + +delegate_components! { + AppA { + open EncoderComponent; + @EncoderComponent.String: EncodeWithDisplay, + @EncoderComponent.Vec: EncodeAsHex, + } +} + +delegate_components! { + AppB { + open EncoderComponent; + @EncoderComponent.String: EncodeBytes, + @EncoderComponent.Vec: EncodeBytes, + } +} +``` + +Each context selects one provider per component and per value type, so two contexts resolve the same +type differently *on purpose*, and within one context the choice is unambiguous and fixed. `AppA` +encoding a `Vec` as hexadecimal and `AppB` passing the bytes through are two coherent local +scopes, not a global incoherence. The different-choice-in-different-places that is a hazard in +Haskell and a diamond in Lean is a feature here because it is written down. In one line, CGP is +incoherent instances with the incoherence made deterministic and the selection made explicit. The +`open` statement and the `@`-path keys are documented on the +[`delegate_components!`](/docs/reference/macros/delegate_components) page. + +### No orphan rule, no newtype + +Two everyday frustrations disappear because a provider's `Self` is always a type its crate owns. The +orphan rule never applies, so a downstream crate can supply a provider for a component and a type it +did not define. And the newtype a type needs for a second instance, such as `Sum` and `Product` +wrapping `Int`, is unnecessary: a second behavior for a type is a second provider, named directly. +The [Bypassing coherence](/docs/concepts/coherence) page shows both on the encoder example. + +## What each approach costs + +Type classes are valued for principled, inferred overloading and for global uniqueness, and their +costs, as their users state them, follow from the same rules. The one-instance-per-type limit forces +the newtype workaround, which "breaks down when the type is embedded in another type" +([Yang, 2014](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). +The orphan rule shapes module structure ([Queensland FP Lab](https://qfpl.io/posts/orphans-and-fundeps/)). +Overlapping instances are subtle and incoherent instances are, by GHC's own account, indeterministic +([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). Haskell +has no easy local instance, because local instances reintroduce a coherence problem. In Agda and Lean +the absence of enforced coherence surfaces as the diamond problem and the work of keeping overlapping +instances definitionally equal ([Baanen, 2022](https://arxiv.org/pdf/2202.01629)). Some practitioners +argue the coherence bargain is wrong and prefer explicit dictionaries +([Chiusano, *The trouble with typeclasses*](https://pchiusano.github.io/2018-02-13/typeclasses.html)), +and a recent survey compares how Swift, Rust, Scala, and Haskell each draw the line +([Racordon, Flesselle & Pham, 2025](https://arxiv.org/pdf/2502.20546)). + +CGP pays with the wiring. There is no search, so the selection must be written down, once per context. +A component has to be declared with [`#[cgp_component]`](/docs/reference/macros/cgp_component) +before it can have providers, which adds declarations a plain trait does not need. The compile-time +work is real. And the raw diagnostics are trait-solver output over generated types: +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +alternatives. + +## Where coherent type classes are the better choice + +When a program wants one canonical instance per type program-wide, one `Ord`, one `Show`, one +serialization, so that a `Set` cannot be corrupted and generic code needs no wiring, coherent type +classes are the right tool. Simulating that with CGP's per-context wiring reintroduces by hand the +uniqueness the compiler gives for free. The same holds in Rust: a trait with one implementation per +type is an ordinary trait, and CGP's [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) +page says so first. CGP's explicit selection is the better tool when a program needs several +interchangeable instances, per-context choice, instances for types and traits it does not own, or an +escape from the diamond and orphan problems. + +## What to expect that differs + +**CGP does not find the instance by type.** The provider is named in a table. This is the consequence +of the property a type-class reader will find most striking: because CGP does not resolve by type, it +is free of coherence, so it hosts the overlapping and orphan instances Haskell forbids or makes +fragile. + +**Uniqueness is per context, not program-wide.** A type-class reader may expect that once a type has +an instance it is the instance everywhere. CGP promises agreement within a context and lets two +contexts differ, and that scoping lets two applications encode one type two ways without conflict. + +**Selection can be keyed on the context rather than the type.** Haskell keys `Show Bool` on `Bool`, +so there is one of it. CGP's decisive shape moves the type being operated on into a parameter and +keys the choice on the context, and that change of key makes per-context selection more than a rewording of +per-type instances. CGP can also key on the type in the Haskell manner, and then it inherits the same +one-per-type limit. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page works out +the difference between the two arrangements. + +**The verification you gave up is replaced, not removed.** Where a type-class compiler proves an +instance exists, [`check_components!`](/docs/reference/macros/check_components) proves a context's +wiring is complete, at the wiring site, naming the missing dependency. + +## Where to go next + +- [Bypassing coherence](/docs/concepts/coherence): the coherence rules and the provider move, on the + encoder example. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the two traits one + class becomes, and how a call finds its provider. +- [ML modules](./ml-modules.md): the module side of the modular-type-classes correspondence. +- [Implicit parameters](./implicit-parameters.md): the same trade seen from Scala's `given` and + Haskell's `ImplicitParams`. +- [Rust's own proposals](./rust-language-proposals.md): what Rust has considered doing about its own + coherence rules. + +## Sources + +The Haskell snippets were compiled with GHC 9.10, the Agda snippet type-checked with Agda 2.8.0, and +the Lean snippet evaluated with Lean 4.34.0. The CGP snippets were compiled against `cgp` +`0.8.0-alpha` with a `check_components!` assertion per wired context. + +- [Wadler & Blott, *How to make ad-hoc polymorphism less ad hoc* (POPL 1989)](https://dl.acm.org/doi/10.1145/75277.75283): the origin of type classes and the dictionary-passing translation. +- [GHC User's Guide, *Instance declarations and resolution*](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html): the one-instance rule, the orphan-instance rule, the overlap pragmas, and GHC's own warnings about incoherence. +- [Yang, *Type classes: confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/): the decomposition of coherence, the `Set`/`Ord` argument, and the newtype workaround's limits. +- [Rust RFC 2451, *re-rebalancing coherence*](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html): Rust traits as type classes with an enforced orphan rule. +- [Devriese & Piessens, *On the Bright Side of Type Classes: Instance Arguments in Agda* (ICFP 2011)](https://dl.acm.org/doi/10.1145/2034574.2034796): scoped, type-directed resolution without a coherence guarantee. +- [Selsam, Ullrich & de Moura, *Tabled Typeclass Resolution*](https://arxiv.org/pdf/2001.04301) and [Baanen, *Use and abuse of instance parameters in the Lean mathematical library*](https://arxiv.org/pdf/2202.01629): Lean's resolution, the diamond problem, and Mathlib's definitional-equality discipline. +- [Dreyer, Harper & Chakravarty, *Modular Type Classes* (POPL 2007)](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf): classes as signatures, instances as structures and functors, and the canonicity-versus-modularity tension. +- [Chiusano, *The trouble with typeclasses*](https://pchiusano.github.io/2018-02-13/typeclasses.html), [Racordon, Flesselle & Pham, *On the State of Coherence in the Land of Type Classes* (2025)](https://arxiv.org/pdf/2502.20546), and [Queensland FP Lab, *Multi-Parameter Type Classes and their Orphan Rules*](https://qfpl.io/posts/orphans-and-fundeps/): community sentiment on coherence, the case for explicit dictionaries, and the orphan-instance pain. +- [Kmett, *Typeclasses vs the World* (2015)](https://www.youtube.com/watch?v=hIZxTQP1ifo): what coherence buys and costs, and the alternatives that trade it for first-class instances. CGP's author names this talk as a core inspiration in the [RustLab 2025 talk](/blog/rustlab-2025-coherence). + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its CGP code was verified against the +library's source and its other snippets against the toolchains named in Sources. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index 3a3bb08a..7969d4c2 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -186,6 +186,8 @@ These pages explain related dependencies and the constructs used here: [`UseType`](/docs/reference/providers/use_type): Declaring and selecting an abstract type. - [`#[use_type]`](/docs/reference/attributes/use_type): Importing an associated type into a definition. - [`HasType`](/docs/reference/components/has_type): The built-in component for tagged type choices. +- [Comparison: ML modules](/docs/comparisons/ml-modules): abstract-type components beside a signature's abstract `type t`, and what sealing CGP does not do. +- [Comparison: Implicit parameters](/docs/comparisons/implicit-parameters): an abstract type as a functional dependency: a type the context determines. --- diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index caa7778a..d6d2ebac 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -150,6 +150,7 @@ These pages explain related wiring choices and checks: - [Checking your wiring](./check-traits.md): Context checks and checks on individual providers. - [`delegate_components!`](/docs/reference/macros/delegate_components): The `new` and grouped-key forms. - [`check_components!`](/docs/reference/macros/check_components): The `#[check_providers]` form. +- [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch): delegation through a bundle with `self` still bound to the context. --- diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index ed8e2d6b..9df358b7 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -212,6 +212,7 @@ These pages explain the dependencies being checked and the available check forms `#[check_providers]` assertions. - [`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components): Combined wiring and checking, including its coverage limits. +- [Comparison: Dependency injection](/docs/comparisons/dependency-injection): `check_components!` beside a container's startup validation and Dagger's build-time check. --- diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 4ca05932..ae38458d 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -209,6 +209,8 @@ Choose the next page according to whether you want to evaluate, understand, or u [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), and [`delegate_components!`](/docs/reference/macros/delegate_components): The constructs used here. - [RustLab 2025 talk](/blog/rustlab-2025-coherence): A longer account of coherence and CGP's approach. +- [Comparison: Type classes](/docs/comparisons/type-classes): the same coherence trade seen from Haskell, Agda, and Lean. +- [Comparison: Rust's own proposals](/docs/comparisons/rust-language-proposals): what Rust itself has considered doing about its coherence rules. --- diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index a2b6b7a2..7fad0c16 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -268,6 +268,8 @@ These pages develop the trait model and show how to use it: - [`#[cgp_component]`](/docs/reference/macros/cgp_component), [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), and [`delegate_components!`](/docs/reference/macros/delegate_components): Exact syntax and generated code. +- [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch): the wiring table read as a vtable that exists only at compile time. +- [Comparison: Policy-based design](/docs/comparisons/policy-based-design): the same split in C++ policy classes and host templates. --- diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index 60e72ba2..df9647a8 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -152,6 +152,8 @@ These pages explain related data operations and the traits used here: [`HasBuilder`](/docs/reference/traits/builder/has_builder): Partial records and construction. - [`HasFields`](/docs/reference/traits/shape/has_fields), [`Field`](/docs/reference/types/field), and [`Symbol!`](/docs/reference/macros/symbol): The types that describe a record's fields. +- [Comparison: Row polymorphism](/docs/comparisons/row-polymorphism): records as rows: containment, concatenation, and presence flags. +- [Comparison: Reflection](/docs/comparisons/reflection): a derived shape beside runtime and compile-time reflection descriptors. --- diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index a7d0e2f8..ef8d4a92 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -165,6 +165,7 @@ These pages explain the related representations and operations: [`FromVariant`](/docs/reference/traits/variant/from_variant): Construction by variant name. - [`CanUpcast`](/docs/reference/traits/casting/can_upcast) and [`CanDowncast`](/docs/reference/traits/casting/can_downcast): Widening and narrowing compatible enums. +- [Comparison: Row polymorphism](/docs/comparisons/row-polymorphism): variants as row-typed sums: injection, branching, and the expression problem. --- diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 95c5fe32..583c1e9d 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -191,6 +191,7 @@ These pages explain composition and specify the handler interfaces: - [`#[cgp_computer]`](/docs/reference/macros/cgp_computer) and [`#[cgp_producer]`](/docs/reference/macros/cgp_producer): Generating providers from functions. - [Handler combinators](/docs/reference/providers/handler): Composition and promotion adapters. +- [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): the handler family beside effect handlers, and the continuation CGP never captures. --- diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index 4895fabf..222c0ec4 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -197,6 +197,8 @@ These pages explain related forms of composition and their checks: - [`UseContext`](/docs/reference/providers/use_context): Forwarding to the context's consumer trait. - [`#[cgp_impl]`](/docs/reference/macros/cgp_impl): Provider definitions and explicit provider structs. - [`delegate_components!`](/docs/reference/macros/delegate_components): Wiring and `open` dispatch. +- [Comparison: ML modules](/docs/comparisons/ml-modules): higher-order providers as functors, and the wiring table in place of functor application. +- [Comparison: Policy-based design](/docs/comparisons/policy-based-design): a host template with policy parameters as a higher-order provider. --- diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index 9ecf005d..5b434efe 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -265,6 +265,8 @@ These pages develop the dependency forms and explain how providers are selected [`#[use_type]`](/docs/reference/attributes/use_type): The dependency syntax used here. - [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) and [`#[blanket_trait]`](/docs/reference/macros/blanket_trait): Generating blanket implementations. +- [Comparison: Dependency injection](/docs/comparisons/dependency-injection): impl-side dependencies as constructor parameters, without a container. +- [Comparison: Capabilities](/docs/comparisons/capabilities): requirements on the context read against the several senses of "capability". --- diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index 112c3949..fbfbebf8 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -173,6 +173,8 @@ accepted forms and access rules, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is trait, [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter) is the getter to reach for in the three cases above, and [`HasField`](/docs/reference/traits/field-access/has_field) is the trait underneath all of them. +- [Comparison: Implicit parameters](/docs/comparisons/implicit-parameters): implicit arguments beside Scala's `using` and Haskell's `ImplicitParams`. +- [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): reading a context field as the dynamic-binding fragment of effect handlers. --- diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index 4981db08..1fdca011 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -181,6 +181,7 @@ For the constructs, [`HasErrorType`](/docs/reference/components/has_error_type) type, [`CanRaiseError`](/docs/reference/components/can_raise_error) covers raising and wrapping, and [the error providers](/docs/reference/providers/error) is the catalogue of strategies with the bound each one places on the context. +- [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): why `raise_error` selects an interpretation but passes no control. --- diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index 16d13ad0..c53dccb4 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -398,6 +398,7 @@ If the answer here was "not yet", [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) i you need: a trait from a function, no wiring, nothing to reverse later. If it was "yes", the [Area calculation series](/docs/tutorials/area-calculation/) works up the tiers in order, and [`#[cgp_component]`](/docs/reference/macros/cgp_component) is where the component machinery starts. +- [Comparison: Type classes](/docs/comparisons/type-classes): why keying selection on the context rather than the type is the decisive shape. --- diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index a1ac6692..4f685756 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -209,6 +209,7 @@ carries the `#[prefix(...)]` registration attribute, [`delegate_components!`](/docs/reference/macros/delegate_components) carries the `namespace` and `open` statements, [`RedirectLookup`](/docs/reference/providers/redirect_lookup) is the provider doing the routing, and [`Path!`](/docs/reference/macros/path) is the path type underneath. +- [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch): a namespace as a shared prototype whose bound entries cannot be shadowed. --- diff --git a/docs/contribute.md b/docs/contribute.md index cb8ed21d..59b1e490 100644 --- a/docs/contribute.md +++ b/docs/contribute.md @@ -1,5 +1,5 @@ --- -sidebar_position: 9 +sidebar_position: 10 --- # Contribute to CGP diff --git a/docs/reference/_category_.json b/docs/reference/_category_.json index ddf34ddc..a2975f3e 100644 --- a/docs/reference/_category_.json +++ b/docs/reference/_category_.json @@ -1,6 +1,6 @@ { "label": "Reference", - "position": 5, + "position": 6, "link": { "type": "doc", "id": "reference/index" diff --git a/docs/resources.md b/docs/resources.md index e2020fd6..8af19371 100644 --- a/docs/resources.md +++ b/docs/resources.md @@ -1,5 +1,5 @@ --- -sidebar_position: 8 +sidebar_position: 9 --- # Resources diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index 9494249d..6f1d1165 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -9,6 +9,8 @@ description = "Compiled counterparts of the code shown on contextgeneric.dev. No cgp = "0.8.0-alpha" [dev-dependencies] +anyhow = "1" +cap-std = "3" futures = "0.3" trybuild = "1" diff --git a/example-code/README.md b/example-code/README.md index 92c11bf3..5814178a 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -23,6 +23,7 @@ pulls in a module tree that mirrors that section's pages: - `tests/concepts_tests.rs` → `tests/concepts/`, mirroring `docs/concepts/` - `tests/reference_tests.rs` → `tests/reference/`, mirroring `docs/reference/` - `tests/cargo_cgp_tests.rs` → `tests/cargo_cgp/`, mirroring `docs/cargo-cgp/` +- `tests/comparisons_tests.rs` → `tests/comparisons/`, mirroring `docs/comparisons/` - `tests/compile_fail_tests.rs` → `tests/compile_fail/`, the snippets the pages **reject** (see below) One file per page, at the matching path with the file name in `snake_case`: @@ -32,6 +33,7 @@ One file per page, at the matching path with the file name in `snake_case`: | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | | `docs/reference/` | partial — `errors.md`, `macros/cgp_namespace.md` and `macros/delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | +| `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/tests/comparisons/algebraic_effects.rs b/example-code/tests/comparisons/algebraic_effects.rs new file mode 100644 index 00000000..615716d6 --- /dev/null +++ b/example-code/tests/comparisons/algebraic_effects.rs @@ -0,0 +1,129 @@ +//! Code from `docs/comparisons/algebraic-effects.md` — *Algebraic effects and handlers*. + +/// ## Components are effect signatures; providers are tail-resumptive handlers +pub mod components_are_effect_signatures { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) { + println!("Hello!"); + } + } + + pub struct App; + + delegate_components! { App { GreeterComponent: GreetHello } } + + mod check_app { + use super::*; + check_components! { App { GreeterComponent } } + } +} + +/// ## Reading from the context is dynamic binding, exactly +pub mod reading_from_the_context_is_dynamic_binding { + use cgp::prelude::*; + + #[cgp_fn] + pub fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + #[test] + fn the_context_supplies_the_value() { + let app = App { + name: "World".to_owned(), + }; + assert_eq!(app.greet(), "Hello, World!"); + } +} + +/// ## Raising an error looks like `raise` but passes a value, not control +/// ## Impl-side dependencies are the effect row; `check_components!` is "all effects handled" +pub mod raising_an_error { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self, path: &str) -> Result; + } + + #[cgp_impl(new LoadOrFail)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl Loader { + fn load(&self, path: &str) -> Result { + if path.is_empty() { + return Err(Self::raise_error("empty path".to_owned())); + } + Ok(format!("contents of {path}")) + } + } + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + LoaderComponent: LoadOrFail, + + @ErrorRaiserComponent.String: RaiseFrom, + } + } + + mod check_app { + use super::*; + check_components! { + App { + LoaderComponent, + } + } + } + + #[test] + fn raise_error_returns_a_value_and_the_question_mark_does_the_abort() { + assert_eq!(App.load("config.toml").unwrap(), "contents of config.toml"); + assert_eq!(App.load("").unwrap_err(), "empty path"); + } +} + +/// ## Configuring abstract types through the same wiring +pub mod configuring_abstract_types { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } + } + + mod check_app { + use super::*; + check_components! { App { ErrorTypeProviderComponent } } + } + + #[test] + fn the_context_fixes_the_type() { + fn assert_error_type>() {} + assert_error_type::(); + } +} diff --git a/example-code/tests/comparisons/capabilities.rs b/example-code/tests/comparisons/capabilities.rs new file mode 100644 index 00000000..18dfbe2d --- /dev/null +++ b/example-code/tests/comparisons/capabilities.rs @@ -0,0 +1,98 @@ +//! Code from `docs/comparisons/capabilities.md` — *Capabilities*. + +/// ## A requirement on the context is a capability in the effect-system sense +pub mod a_requirement_on_the_context { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { + App { + GreeterComponent: GreetHello, + } + } + + check_components! { App { GreeterComponent } } + + #[test] + fn the_context_discharges_the_requirement() { + let app = App { + name: "World".to_owned(), + }; + assert_eq!(app.greet(), "Hello, World!"); + } +} + +/// ## An object capability can live in the context +pub mod an_object_capability_can_live_in_the_context { + use cap_std::fs::Dir; + use cgp::prelude::*; + + #[cgp_component(ConfigReader)] + pub trait CanReadConfig { + fn read_config(&self) -> std::io::Result; + } + + #[cgp_impl(new ReadConfigFromDir)] + impl ConfigReader { + fn read_config(&self, #[implicit] config_dir: &Dir) -> std::io::Result { + let mut text = String::new(); + std::io::Read::read_to_string(&mut config_dir.open("config.txt")?, &mut text)?; + Ok(text) + } + } + + #[derive(HasField)] + pub struct App { + pub config_dir: Dir, + } + + delegate_components! { + App { + ConfigReaderComponent: ReadConfigFromDir, + } + } + + check_components! { App { ConfigReaderComponent } } + + #[test] + fn the_handle_reaches_only_the_provider_that_declares_it() { + use cap_std::ambient_authority; + + let root = std::env::temp_dir().join(format!( + "cgp-comparisons-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join("config.txt"), "port = 8080\n").unwrap(); + + // Ambient authority is exercised once, and the call marks it. + let config_dir = Dir::open_ambient_dir(&root, ambient_authority()).unwrap(); + let app = App { config_dir }; + + assert_eq!(app.read_config().unwrap(), "port = 8080\n"); + // A path that would leave the directory is refused by the handle itself. + assert!(app.config_dir.open("../secret.txt").is_err()); + + std::fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/example-code/tests/comparisons/dependency_injection.rs b/example-code/tests/comparisons/dependency_injection.rs new file mode 100644 index 00000000..022bc970 --- /dev/null +++ b/example-code/tests/comparisons/dependency_injection.rs @@ -0,0 +1,196 @@ +//! Code from `docs/comparisons/dependency-injection.md` — *Dependency injection*. + +/// ## Dependency injection without a framework (Rust) +pub mod without_a_framework { + pub trait StorageClient { + fn fetch(&self, object_id: &str) -> Vec; + } + + pub struct ProfilePictureService { + pub storage: S, + } +} + +/// ## Impl-side dependencies are the injected constructor parameters +pub mod impl_side_dependencies_are_constructor_parameters { + use cgp::prelude::*; + + // Types the page names without declaring. + pub struct PostgresDb; + pub struct Email(pub String); + #[derive(Debug, PartialEq)] + pub struct User { + pub username: String, + } + #[derive(Debug, PartialEq)] + pub enum Error { + InvalidUsername, + } + #[derive(Debug, PartialEq, PartialOrd)] + pub struct Probability(f64); + impl Probability { + pub fn new(value: f64) -> Self { + Probability(value) + } + } + + #[cgp_component(UsernameCensor)] + pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; + } + + #[cgp_impl(new CensorByWordList)] + impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + if username.contains("spam") { + Probability::new(0.99) + } else { + Probability::new(0.0) + } + } + } + + #[cgp_component(UserManager)] + pub trait CanManageUser { + fn create_user(&self, username: &str, email: &Email) -> Result; + } + + #[cgp_impl(new PostgresUserManager)] + #[uses(CanCensorUsername)] + impl UserManager { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + // The page elides the insert through `database`. + let _ = (database, email); + Ok(User { + username: username.to_owned(), + }) + } + } + + #[derive(HasField)] + pub struct App { + pub database: PostgresDb, + } + + delegate_components! { + App { + UserManagerComponent: PostgresUserManager, + UsernameCensorComponent: CensorByWordList, + } + } + + mod check_app { + use super::*; + check_components! { App { UserManagerComponent } } + } + + #[test] + fn the_dependencies_are_supplied_by_the_context() { + let app = App { + database: PostgresDb, + }; + let email = Email("ada@example.com".to_owned()); + assert!(app.create_user("ada", &email).is_ok()); + assert_eq!( + app.create_user("spam-bot", &email), + Err(Error::InvalidUsername) + ); + } +} + +/// ## Wiring is the container configuration +/// ## Checking replaces the container's startup validation +pub mod wiring_is_the_container_configuration { + use cgp::prelude::*; + + #[cgp_component(StorageObjectFetcher)] + pub trait CanFetchStorageObject { + fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + } + + #[cgp_impl(new FetchS3Object)] + impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] s3_bucket: &str, + object_id: &str, + ) -> anyhow::Result> { + // The page elides the request to S3. + Ok(format!("s3://{s3_bucket}/{object_id}").into_bytes()) + } + } + + #[cgp_impl(new FetchGCloudObject)] + impl StorageObjectFetcher { + fn fetch_storage_object( + &self, + #[implicit] gcloud_bucket: &str, + object_id: &str, + ) -> anyhow::Result> { + // The page elides the request to Google Cloud Storage. + Ok(format!("gs://{gcloud_bucket}/{object_id}").into_bytes()) + } + } + + #[derive(HasField)] + pub struct App { + pub s3_bucket: String, + } + + #[derive(HasField)] + pub struct GCloudApp { + pub gcloud_bucket: String, + } + + delegate_components! { + App { + StorageObjectFetcherComponent: FetchS3Object, + } + } + + delegate_components! { + GCloudApp { + StorageObjectFetcherComponent: FetchGCloudObject, + } + } + + mod check_app { + use super::*; + check_components! { + App { + StorageObjectFetcherComponent, + } + } + } + + mod check_gcloud_app { + use super::*; + check_components! { GCloudApp { StorageObjectFetcherComponent } } + } + + #[test] + fn two_deployments_two_bindings() { + let app = App { + s3_bucket: "pictures".to_owned(), + }; + let gcloud = GCloudApp { + gcloud_bucket: "pictures".to_owned(), + }; + assert_eq!( + app.fetch_storage_object("ada.png").unwrap(), + b"s3://pictures/ada.png".to_vec() + ); + assert_eq!( + gcloud.fetch_storage_object("ada.png").unwrap(), + b"gs://pictures/ada.png".to_vec() + ); + } +} diff --git a/example-code/tests/comparisons/dynamic_dispatch.rs b/example-code/tests/comparisons/dynamic_dispatch.rs new file mode 100644 index 00000000..b9c29e20 --- /dev/null +++ b/example-code/tests/comparisons/dynamic_dispatch.rs @@ -0,0 +1,211 @@ +//! Code from `docs/comparisons/dynamic-dispatch.md` — *Dynamic dispatch, dynamic typing, and +//! prototypal inheritance*. + +/// ## CGP code reads like a duck-typed program +pub mod cgp_code_reads_like_a_duck_typed_program { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + #[uses(HasName)] + impl Greeter { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } + } + + #[cgp_fn] + pub fn greet_implicitly(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { Person { GreeterComponent: GreetHello } } + + mod check_person { + use super::*; + check_components! { Person { GreeterComponent } } + } + + #[test] + fn the_context_responds_to_the_message() { + let person = Person { + name: "Ada".to_owned(), + }; + assert_eq!(person.greet(), "Hello, Ada!"); + assert_eq!(person.greet_implicitly(), "Hello, Ada!"); + } +} + +/// ## `DelegateComponent` is a compile-time vtable +/// ## Component delegation is delegation, with `self` bound +pub mod delegate_component_is_a_compile_time_vtable { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(new RectanglePerimeter)] + impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } + } + + delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + PerimeterCalculatorComponent: RectanglePerimeter, + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + [AreaCalculatorComponent, PerimeterCalculatorComponent]: GeometryComponents, + } + } + + mod check_rectangle { + use super::*; + check_components! { + Rectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } + } + } + + #[test] + fn self_stays_bound_to_the_original_receiver() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + // `RectangleArea` reads `width` and `height` from `Rectangle`, not from the bundle. + assert_eq!(rectangle.area(), 12.0); + assert_eq!(rectangle.perimeter(), 14.0); + } +} + +/// ## Namespaces are shared prototypes with open slots, not shadowable ones +pub mod namespaces_are_shared_prototypes { + use cgp::prelude::*; + + cgp_namespace! { new AppNamespace {} } + + #[cgp_component(Greeter)] + #[prefix(@app.GreeterComponent in AppNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_component(Farewell)] + #[prefix(@app.FarewellComponent in AppNamespace)] + pub trait CanSayGoodbye { + fn goodbye(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + #[cgp_impl(new GreetQuietly)] + impl Greeter { + fn greet(&self) -> String { + "hello".to_owned() + } + } + + #[cgp_impl(new SayGoodbye)] + impl Farewell { + fn goodbye(&self) -> String { + "Goodbye!".to_owned() + } + } + + // The shared prototype: it binds the farewell and leaves the greeting path open. + cgp_namespace! { + new AppDefaults: AppNamespace { + @app.FarewellComponent: SayGoodbye, + } + } + + pub struct AppA; + + delegate_components! { + AppA { + namespace AppDefaults; // inherit every wiring the namespace binds + + @app.GreeterComponent: GreetHello, // fill a slot the namespace leaves open + } + } + + // A child namespace may bind an open path; it may not redefine a bound one. + cgp_namespace! { + new QuietDefaults: AppDefaults { + @app.GreeterComponent: GreetQuietly, + } + } + + pub struct AppB; + + delegate_components! { + AppB { + namespace QuietDefaults; + } + } + + mod check_app_a { + use super::*; + check_components! { AppA { GreeterComponent, FarewellComponent } } + } + + mod check_app_b { + use super::*; + check_components! { AppB { GreeterComponent, FarewellComponent } } + } + + #[test] + fn the_chain_is_walked_by_the_type_checker() { + assert_eq!(AppA.greet(), "Hello!"); + assert_eq!(AppA.goodbye(), "Goodbye!"); + assert_eq!(AppB.greet(), "hello"); + assert_eq!(AppB.goodbye(), "Goodbye!"); + } +} diff --git a/example-code/tests/comparisons/implicit_parameters.rs b/example-code/tests/comparisons/implicit_parameters.rs new file mode 100644 index 00000000..dd26f70b --- /dev/null +++ b/example-code/tests/comparisons/implicit_parameters.rs @@ -0,0 +1,110 @@ +//! Code from `docs/comparisons/implicit-parameters.md` — *Implicit parameters*. + +/// ## Implicit arguments are implicit value parameters +pub mod implicit_arguments_are_implicit_value_parameters { + use cgp::prelude::*; + + #[cgp_fn] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[test] + fn the_context_supplies_the_arguments() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + assert_eq!(rectangle.rectangle_area(), 12.0); + } +} + +/// ## Abstract types are implicit type parameters +pub mod abstract_types_are_implicit_type_parameters { + use core::fmt::Debug; + + use cgp::prelude::*; + + // The page shows CGP's own `HasErrorType`; the local declaration shadows the prelude's here. + #[cgp_type] + pub trait HasErrorType { + type Error: Debug; + } +} + +/// ## Components and wiring are type classes without coherence +pub mod components_and_wiring_are_type_classes { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_component(Encoder)] + pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; + } + + #[cgp_impl(new EncodeWithDisplay)] + impl Encoder { + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() + } + } + + #[cgp_impl(new EncodeBytes)] + impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value.as_ref().to_vec() + } + } + + #[cgp_impl(new EncodeAsHex)] + impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value + .as_ref() + .iter() + .flat_map(|byte| format!("{byte:02x}").into_bytes()) + .collect() + } + } + + pub struct AppA; + pub struct AppB; + + delegate_components! { + AppA { + open EncoderComponent; + @EncoderComponent.Vec: EncodeAsHex, + } + } + + delegate_components! { + AppB { + open EncoderComponent; + @EncoderComponent.Vec: EncodeBytes, + } + } + + mod check_app_a { + use super::*; + check_components! { AppA { EncoderComponent: Vec } } + } + + mod check_app_b { + use super::*; + check_components! { AppB { EncoderComponent: Vec } } + } + + #[test] + fn the_same_type_two_encodings_two_contexts() { + let bytes = vec![0xabu8]; + assert_eq!(AppA.encode(&bytes), b"ab".to_vec()); + assert_eq!(AppB.encode(&bytes), vec![0xab]); + } +} diff --git a/example-code/tests/comparisons/ml_modules.rs b/example-code/tests/comparisons/ml_modules.rs new file mode 100644 index 00000000..d93682b9 --- /dev/null +++ b/example-code/tests/comparisons/ml_modules.rs @@ -0,0 +1,113 @@ +//! Code from `docs/comparisons/ml-modules.md` — *ML modules and modular implicits*. + +/// ## Components are signatures; providers are structures +pub mod components_are_signatures { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + /// ## Higher-order providers are functors + #[cgp_impl(new ScaledArea)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } + } + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_components! { + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } + } + + mod check_scaled_rectangle { + use super::*; + check_components! { ScaledRectangle { AreaCalculatorComponent } } + } + + #[test] + fn the_functor_is_applied_in_the_wiring() { + let rectangle = ScaledRectangle { + width: 2.0, + height: 5.0, + scale_factor: 3.0, + }; + assert_eq!(rectangle.area(), 90.0); + } +} + +/// ## Abstract-type components are a signature's abstract types +pub mod abstract_type_components { + use core::fmt::Debug; + + use cgp::prelude::*; + + // The page shows CGP's own `HasErrorType`; declaring it locally shows the shape the library's + // definition has, and the local name shadows the prelude's within this module. + #[cgp_type] + pub trait HasErrorType { + type Error: Debug; + } +} + +/// ## `delegate_components!` replaces manual functor application +pub mod delegate_components_replaces_functor_application { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + #[cgp_component(EmailSender)] + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + #[cgp_impl(new SendViaSmtp)] + impl EmailSender { + fn send_email(&self, #[implicit] smtp_server: &str, to: &str, body: &str) { + // The page elides the body; a real provider opens a connection to `smtp_server`. + let _ = (smtp_server, to, body); + } + } + + #[derive(HasField)] + pub struct App { + pub smtp_server: String, + } + + delegate_components! { + App { + EmailSenderComponent: SendViaSmtp, + ErrorTypeProviderComponent: UseType, + } + } + + mod check_app { + use super::*; + check_components! { App { EmailSenderComponent, ErrorTypeProviderComponent } } + } + + #[test] + fn the_table_is_resolved_in_any_order() { + let app = App { + smtp_server: "smtp.example.com".to_owned(), + }; + app.send_email("ada@example.com", "hello"); + } +} diff --git a/example-code/tests/comparisons/mod.rs b/example-code/tests/comparisons/mod.rs new file mode 100644 index 00000000..24fc130a --- /dev/null +++ b/example-code/tests/comparisons/mod.rs @@ -0,0 +1,17 @@ +//! Code from the pages under `docs/comparisons/`, one module per page. +//! +//! Every page in that section shows CGP code beside code in another language. Only the CGP side is +//! checked here; the other side was compiled against the toolchain each page names in its Sources. +//! The section index shows no code, so it has no module. + +pub mod algebraic_effects; +pub mod capabilities; +pub mod dependency_injection; +pub mod dynamic_dispatch; +pub mod implicit_parameters; +pub mod ml_modules; +pub mod policy_based_design; +pub mod reflection; +pub mod row_polymorphism; +pub mod rust_language_proposals; +pub mod type_classes; diff --git a/example-code/tests/comparisons/policy_based_design.rs b/example-code/tests/comparisons/policy_based_design.rs new file mode 100644 index 00000000..f48bfa8c --- /dev/null +++ b/example-code/tests/comparisons/policy_based_design.rs @@ -0,0 +1,164 @@ +//! Code from `docs/comparisons/policy-based-design.md` — *C++ policy-based design*. + +use cgp::prelude::*; + +#[cgp_component(MessageProvider)] +pub trait HasMessage { + fn message(&self) -> String; +} + +#[cgp_component(Writer)] +pub trait CanWrite { + fn write(&self, message: String); +} + +#[cgp_impl(new EnglishMessage)] +impl MessageProvider { + fn message(&self) -> String { + "Hello, World!".to_owned() + } +} + +#[cgp_impl(new GermanMessage)] +impl MessageProvider { + fn message(&self) -> String { + "Hallo Welt!".to_owned() + } +} + +#[cgp_impl(new WriteToStdout)] +impl Writer { + fn write(&self, message: String) { + println!("{message}"); + } +} + +/// ## Providers are policies; the context is the host +pub mod providers_are_policies { + use super::*; + + #[cgp_fn] + #[uses(HasMessage, CanWrite)] + pub fn run(&self) { + self.write(self.message()); + } + + pub struct EnglishApp; + pub struct GermanApp; + + delegate_components! { + EnglishApp { + MessageProviderComponent: EnglishMessage, + WriterComponent: WriteToStdout, + } + } + + delegate_components! { + GermanApp { + MessageProviderComponent: GermanMessage, + WriterComponent: WriteToStdout, + } + } + + mod check_english { + use super::*; + check_components! { EnglishApp { MessageProviderComponent, WriterComponent } } + } + + mod check_german { + use super::*; + check_components! { GermanApp { MessageProviderComponent, WriterComponent } } + } + + #[test] + fn two_hosts_two_policy_sets() { + assert_eq!(EnglishApp.message(), "Hello, World!"); + assert_eq!(GermanApp.message(), "Hallo Welt!"); + EnglishApp.run(); + GermanApp.run(); + } +} + +/// ## Policies as type parameters are higher-order providers +pub mod policies_as_type_parameters { + use super::*; + + #[cgp_component(Runner)] + pub trait CanRun { + fn run(&self); + } + + #[cgp_impl(new HelloWorld)] + #[use_provider(W: Writer)] + #[use_provider(M: MessageProvider)] + impl Runner { + fn run(&self) { + W::write(self, M::message(self)) + } + } + + pub struct App; + + delegate_components! { + App { + RunnerComponent: HelloWorld, + } + } + + mod check_app { + use super::*; + check_components! { App { RunnerComponent } } + } + + /// The same shape on a function: the generic parameters move onto the generated trait, so the + /// caller instantiates it the way C++ instantiates a template. + #[cgp_fn] + #[use_provider(W: Writer)] + #[use_provider(M: MessageProvider)] + pub fn hello(&self) { + W::write(self, M::message(self)) + } + + #[test] + fn the_wiring_entry_names_the_instantiation() { + App.run(); + >::hello(&App); + } +} + +/// ## `#[cgp_impl]` is CRTP with the cast done for you +pub mod cgp_impl_is_crtp { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { Person { GreeterComponent: GreetHello } } + + mod check_person { + use super::*; + check_components! { Person { GreeterComponent } } + } + + #[test] + fn the_provider_reads_the_hosts_data() { + let person = Person { + name: "Ada".to_owned(), + }; + assert_eq!(person.greet(), "Hello, Ada!"); + } +} diff --git a/example-code/tests/comparisons/reflection.rs b/example-code/tests/comparisons/reflection.rs new file mode 100644 index 00000000..f17dad1a --- /dev/null +++ b/example-code/tests/comparisons/reflection.rs @@ -0,0 +1,118 @@ +//! Code from `docs/comparisons/reflection.md` — *Reflection and compile-time introspection*. +//! +//! The page's worked example is a self-contained field writer modeled on `cgp-serde`'s +//! `SerializeFields` provider, so it can be compiled here without a `serde` dependency. + +/// ## A type's shape becomes a type, not a descriptor +pub mod a_types_shape_becomes_a_type { + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Config { + pub host: String, + pub port: u16, + } + + #[test] + fn the_shape_is_a_type_level_list() { + fn assert_fields, Field]>>( + ) { + } + assert_fields::(); + } +} + +/// ## Reflection-driven serialization in the trait system +pub mod reflection_driven_serialization { + use core::fmt::Debug; + + use cgp::core::field::traits::StaticString; + use cgp::prelude::*; + + #[cgp_component(ValueWriter)] + pub trait CanWriteValue { + fn write_value(&self, value: &Value) -> String; + } + + #[cgp_impl(new WriteWithDebug)] + impl ValueWriter { + fn write_value(&self, value: &Value) -> String { + format!("{value:?}") + } + } + + #[cgp_impl(new WriteFields)] + impl ValueWriter + where + Value: HasFields, + Value::Fields: FieldsWriter, + { + fn write_value(&self, value: &Value) -> String { + format!("{{{}}}", Value::Fields::write_fields(self, value)) + } + } + + pub trait FieldsWriter { + fn write_fields(context: &Context, value: &Value) -> String; + } + + impl FieldsWriter + for Cons, Rest> + where + Tag: StaticString, // the field name, as a const &'static str + Value: HasField, // read this field from the value + Context: CanWriteValue, // write the field through the context's wiring + Rest: FieldsWriter, // recurse on the remaining fields + { + fn write_fields(context: &Context, value: &Value) -> String { + let field_value = value.get_field(PhantomData); + let entry = format!("\"{}\": {}", Tag::VALUE, context.write_value(field_value)); + let rest = Rest::write_fields(context, value); + if rest.is_empty() { + entry + } else { + format!("{entry}, {rest}") + } + } + } + + impl FieldsWriter for Nil { + fn write_fields(_context: &Context, _value: &Value) -> String { + String::new() + } + } + + #[derive(HasField, HasFields)] + pub struct Config { + pub host: String, + pub port: u16, + } + + pub struct App; + + delegate_components! { + App { + open ValueWriterComponent; + + @ValueWriterComponent.[String, u16]: WriteWithDebug, + @ValueWriterComponent.Config: WriteFields, + } + } + + mod check_app { + use super::*; + check_components! { App { ValueWriterComponent: Config } } + } + + #[test] + fn one_writer_walks_any_derived_struct() { + let config = Config { + host: "localhost".to_owned(), + port: 8080, + }; + assert_eq!( + App.write_value(&config), + r#"{"host": "localhost", "port": 8080}"# + ); + } +} diff --git a/example-code/tests/comparisons/row_polymorphism.rs b/example-code/tests/comparisons/row_polymorphism.rs new file mode 100644 index 00000000..36e9f90b --- /dev/null +++ b/example-code/tests/comparisons/row_polymorphism.rs @@ -0,0 +1,117 @@ +//! Code from `docs/comparisons/row-polymorphism.md` — *Row polymorphism, structural typing, and +//! extensible data types*. + +/// ## A struct is a closed row; `HasField` is row containment +pub mod a_struct_is_a_closed_row { + use cgp::prelude::*; + + #[derive(HasField, HasFields)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[cgp_fn] + pub fn full_name(&self, #[implicit] first_name: &str, #[implicit] last_name: &str) -> String { + format!("{first_name} {last_name}") + } + + #[derive(HasField)] + pub struct Employee { + pub first_name: String, + pub last_name: String, + pub badge: u32, + } + + #[test] + fn any_context_with_the_fields_qualifies() { + let person = Person { + first_name: "Ada".to_owned(), + last_name: "Lovelace".to_owned(), + }; + let employee = Employee { + first_name: "Ada".to_owned(), + last_name: "Lovelace".to_owned(), + badge: 36, + }; + assert_eq!(person.full_name(), "Ada Lovelace"); + assert_eq!(employee.full_name(), "Ada Lovelace"); + } +} + +/// ## Building a record is row combination +pub mod building_a_record_is_row_combination { + use cgp::prelude::*; + + #[derive(CgpData)] + pub struct FooBar { + pub foo: u64, + pub bar: String, + } + + #[derive(CgpData)] + pub struct Baz { + pub baz: bool, + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, + } + + #[test] + fn two_rows_combine_into_one() { + use cgp::core::field::impls::CanBuildFrom; + + let combined: FooBarBaz = FooBarBaz::builder() + .build_from(FooBar { + foo: 1, + bar: "bar".into(), + }) + .build_from(Baz { baz: true }) + .finalize_build(); + + assert_eq!( + combined, + FooBarBaz { + foo: 1, + bar: "bar".into(), + baz: true, + } + ); + } +} + +/// ## An enum is a row-typed sum; upcast and downcast are injection and branching +pub mod an_enum_is_a_row_typed_sum { + use cgp::prelude::*; + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum Reading { + Temperature(u64), + Label(String), + } + + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum ExtendedReading { + Temperature(u64), + Label(String), + Flag(bool), + } + + #[test] + fn upcast_is_injection_and_downcast_is_guarded_projection() { + use cgp::core::field::impls::{CanDowncast, CanUpcast}; + + let wide = Reading::Temperature(21).upcast(PhantomData::); + assert_eq!(wide, ExtendedReading::Temperature(21)); + + let narrow = ExtendedReading::Label("north".to_owned()).downcast(PhantomData::); + assert_eq!(narrow.ok(), Some(Reading::Label("north".to_owned()))); + + let narrow = ExtendedReading::Flag(true).downcast(PhantomData::); + assert!(narrow.is_err()); + } +} diff --git a/example-code/tests/comparisons/rust_language_proposals.rs b/example-code/tests/comparisons/rust_language_proposals.rs new file mode 100644 index 00000000..4e26e4c1 --- /dev/null +++ b/example-code/tests/comparisons/rust_language_proposals.rs @@ -0,0 +1,159 @@ +//! Code from `docs/comparisons/rust-language-proposals.md` — *Rust's own proposals*. +//! +//! The specialization snippet the page quotes from RFC 1210 is rejected on stable Rust; it is the +//! trybuild fixture `tests/compile_fail/comparisons/rust_language_proposals_specialization.rs`. + +/// ## A named impl is a provider +pub mod a_named_impl_is_a_provider { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_component(Encoder)] + pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; + } + + #[cgp_impl(new EncodeWithDisplay)] + impl Encoder { + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() + } + } + + #[cgp_impl(new EncodeBytes)] + impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value.as_ref().to_vec() + } + } + + /// ## An incoherent bound resolves through the context + pub struct ApiServer; + pub struct Firmware; + + delegate_components! { + ApiServer { + open EncoderComponent; + @EncoderComponent.String: EncodeWithDisplay, + } + } + + delegate_components! { + Firmware { + open EncoderComponent; + @EncoderComponent.String: EncodeBytes, + } + } + + mod check_api_server { + use super::*; + check_components! { ApiServer { EncoderComponent: String } } + } + + mod check_firmware { + use super::*; + check_components! { Firmware { EncoderComponent: String } } + } + + #[test] + fn two_contexts_name_two_overlapping_impls_for_one_type() { + let value = String::from("hello"); + assert_eq!(ApiServer.encode(&value), b"hello".to_vec()); + assert_eq!(Firmware.encode(&value), b"hello".to_vec()); + } +} + +/// ## Passing an impl explicitly is a higher-order provider +pub mod passing_an_impl_explicitly { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(new ScaledArea)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } + } + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_components! { + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } + } + + mod check_scaled_rectangle { + use super::*; + check_components! { ScaledRectangle { AreaCalculatorComponent } } + } + + #[test] + fn the_inner_impl_is_named_in_the_wiring() { + let rectangle = ScaledRectangle { + width: 3.0, + height: 4.0, + scale_factor: 2.0, + }; + assert_eq!(rectangle.area(), 48.0); + } +} + +/// ## A capability is a context field; the `with` block is the context +pub mod a_capability_is_a_context_field { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { + App { + GreeterComponent: GreetHello, + } + } + + mod check_app { + use super::*; + check_components! { App { GreeterComponent } } + } + + #[test] + fn constructing_the_context_binds_the_value() { + let app = App { + name: "World".to_owned(), + }; + assert_eq!(app.greet(), "Hello, World!"); + } +} diff --git a/example-code/tests/comparisons/type_classes.rs b/example-code/tests/comparisons/type_classes.rs new file mode 100644 index 00000000..8db3ebd5 --- /dev/null +++ b/example-code/tests/comparisons/type_classes.rs @@ -0,0 +1,118 @@ +//! Code from `docs/comparisons/type-classes.md` — *Type classes*. + +/// ## A component is a class; a provider is a first-class instance +pub mod a_component_is_a_class { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { Rectangle { AreaCalculatorComponent: RectangleArea } } + + mod check_rectangle { + use super::*; + check_components! { Rectangle { AreaCalculatorComponent } } + } + + #[test] + fn the_instance_is_named_in_the_wiring() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + assert_eq!(rectangle.area(), 12.0); + } +} + +/// ## Overlapping instances are the default, with no heuristic +/// ## Incoherent instances made deterministic and local +pub mod overlapping_instances { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_component(Encoder)] + pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; + } + + #[cgp_impl(new EncodeWithDisplay)] + impl Encoder { + fn encode(&self, value: &Value) -> Vec { + value.to_string().into_bytes() + } + } + + #[cgp_impl(new EncodeBytes)] + impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value.as_ref().to_vec() + } + } + + #[cgp_impl(new EncodeAsHex)] + impl> Encoder { + fn encode(&self, value: &Value) -> Vec { + value + .as_ref() + .iter() + .flat_map(|byte| format!("{byte:02x}").into_bytes()) + .collect() + } + } + + pub struct AppA; + pub struct AppB; + + delegate_components! { + AppA { + open EncoderComponent; + @EncoderComponent.String: EncodeWithDisplay, + @EncoderComponent.Vec: EncodeAsHex, + } + } + + delegate_components! { + AppB { + open EncoderComponent; + @EncoderComponent.String: EncodeBytes, + @EncoderComponent.Vec: EncodeBytes, + } + } + + mod check_app_a { + use super::*; + check_components! { AppA { EncoderComponent: [String, Vec] } } + } + + mod check_app_b { + use super::*; + check_components! { AppB { EncoderComponent: [String, Vec] } } + } + + #[test] + fn two_local_scopes_each_coherent() { + let bytes = vec![0xffu8, 0x00]; + assert_eq!(AppA.encode(&bytes), b"ff00".to_vec()); + assert_eq!(AppB.encode(&bytes), vec![0xff, 0x00]); + + let text = String::from("hi"); + assert_eq!(AppA.encode(&text), b"hi".to_vec()); + assert_eq!(AppB.encode(&text), b"hi".to_vec()); + } +} diff --git a/example-code/tests/comparisons_tests.rs b/example-code/tests/comparisons_tests.rs new file mode 100644 index 00000000..4b35f52a --- /dev/null +++ b/example-code/tests/comparisons_tests.rs @@ -0,0 +1,10 @@ +//! Runnable checks for the code shown on the `docs/comparisons/` pages. +//! +//! One module per page, under `tests/comparisons/`. See the crate `README.md` for the layout and for +//! how the rejected snippets are handled (they live under `tests/compile_fail/`). + +// A page shows the shape of a program rather than a whole one, so its code carries items nothing calls +// and parameters nothing reads once an elided body is filled in. A genuinely unused import still warns. +#![allow(dead_code, unused_variables)] + +mod comparisons; diff --git a/example-code/tests/compile_fail/comparisons/rust_language_proposals_specialization.rs b/example-code/tests/compile_fail/comparisons/rust_language_proposals_specialization.rs new file mode 100644 index 00000000..ea590255 --- /dev/null +++ b/example-code/tests/compile_fail/comparisons/rust_language_proposals_specialization.rs @@ -0,0 +1,16 @@ +// RFC 1210's own example. Specialization has never stabilized, so the `default` item is rejected +// on a stable toolchain. +use core::ops::{Add, AddAssign}; + +pub trait MyAddAssign { + fn my_add_assign(&mut self, rhs: Rhs); +} + +impl + Clone> MyAddAssign for T { + default fn my_add_assign(&mut self, rhs: R) { + let tmp = self.clone() + rhs; + *self = tmp; + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/comparisons/rust_language_proposals_specialization.stderr b/example-code/tests/compile_fail/comparisons/rust_language_proposals_specialization.stderr new file mode 100644 index 00000000..85bd8991 --- /dev/null +++ b/example-code/tests/compile_fail/comparisons/rust_language_proposals_specialization.stderr @@ -0,0 +1,18 @@ +error[E0658]: specialization is experimental + --> tests/compile_fail/comparisons/rust_language_proposals_specialization.rs:10:5 + | +10 | / default fn my_add_assign(&mut self, rhs: R) { +11 | | let tmp = self.clone() + rhs; +12 | | *self = tmp; +13 | | } + | |_____^ + | + = note: see issue #31844 for more information + +warning: unused import: `AddAssign` + --> tests/compile_fail/comparisons/rust_language_proposals_specialization.rs:3:22 + | +3 | use core::ops::{Add, AddAssign}; + | ^^^^^^^^^ + | + = note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default From e71169452bba1d2bda8167455ae8e18e9b7e2715 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 20 Sep 2026 06:31:59 +0000 Subject: [PATCH 081/516] Revise concept explanations for clarity and technical accuracy --- docs/concepts/implicit-arguments.md | 171 ++++---- docs/concepts/modular-error-handling.md | 169 +++---- docs/concepts/modularity-hierarchy.md | 411 ++++++++---------- docs/concepts/monadic-handlers.md | 142 +++--- docs/concepts/namespaces.md | 162 ++++--- docs/concepts/send-bounds.md | 131 +++--- docs/concepts/type-level-dsls.md | 168 +++---- .../tests/concepts/type_level_dsls.rs | 16 +- 8 files changed, 670 insertions(+), 700 deletions(-) diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index fbfbebf8..5af29087 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -5,17 +5,16 @@ sidebar_position: 4 # Implicit arguments -Writing a provider as an ordinary function whose arguments are filled from fields of the context. +Implicit arguments let a provider declare the context values it needs as function parameters. +CGP reads those values from the context, so callers pass only the method's explicit arguments. +This page explains the field access behind that shorthand, how argument types control borrowing +and cloning, and when a getter trait is a better fit. -This page answers *how does an implementation get a value out of its context, without that becoming a -thing to learn?* It shows what reading a field costs when spelled out, the argument that replaces it, -and the rules deciding how the value arrives. It closes on where an implicit argument stops working and -a getter is the right tool instead. +## Reading a field explicitly -## What reading a field costs, spelled out - -A provider almost always needs data from its context, and the underlying mechanism is a trait keyed by -the field's name lifted into a type: +A generic provider reads a context field through `HasField`, a trait keyed by the field's name. +The following fragment assumes a `Greeter` component with a `greet(&self) -> String` method and +imports from `cgp::prelude::*`: ```rust #[cgp_impl(new GreetByName)] @@ -30,19 +29,18 @@ where } ``` -This works, and everything in it is doing something. `Symbol!("name")` is the field's name as a type, so -one trait can describe every field rather than needing one trait per field. `PhantomData` carries that -type to the call so inference knows which field is meant. The bound is an -[impl-side dependency](./impl-side-dependencies.md), which is why the generated trait itself says -nothing about names. +`HasField` requires the context to expose a `String` field named +`name`. `Symbol!("name")` represents the name as a type, and `PhantomData` supplies that type to +`get_field` so Rust can select the field. The bound is an +[impl-side dependency](./impl-side-dependencies.md): it constrains this provider without adding a +field requirement to the consumer trait. -It is also four unfamiliar things stacked in front of a one-line function, and a reader meeting them -before they have a reason to care about type-level tags will conclude that CGP *is* that. The value the -provider wants is a `String` called `name`; nothing in the paragraph above is about that. +The explicit form separates the requirement from the read. For a provider that only needs a local +value, an implicit argument can express both together. -## The same provider, written as a function +## The same provider with an implicit argument -An **implicit argument** says the same thing as a parameter: +An **implicit argument** names a field and declares the type the method body needs: ```rust #[cgp_impl(new GreetByName)] @@ -53,20 +51,18 @@ impl Greeter { } ``` -Nobody passes the argument. `#[implicit]` removes it from the method's public signature, adds -the field requirement to the implementation, and binds the value at the top of the body, so a caller -still writes `app.greet()` with no arguments, and the body reads a plain local. +`#[implicit]` removes `name` from the method's public signature and generates the field bound and +read. The body receives a local `name`, while a caller still writes `app.greet()`. Here, `&str` +borrows the contents of a `String` field. -Nothing was hidden that was not already hidden. The bound, the tag, and the read are the same three -things; the change is that the author writes the name of the value they want and the macro derives -the rest from it. Someone who understands functions and arguments can write a complete provider without -meeting a type-level anything, which is why this is the recommended way to read a context field and the -starting point most introductions to CGP should use. +Implicit arguments are the usual choice for reading fields from a provider's own context. They +keep each value's name and type beside the method that uses it, while the macro supplies the +`HasField` bound and tagged access. ## A trait from a function alone -Combined with [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), an implicit argument gets you a working CGP -method with no hand-written trait, no provider, and no wiring line: +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) combines implicit arguments with a single blanket +implementation, so the operation needs neither a named provider nor wiring: ```rust #[cgp_fn] @@ -75,46 +71,48 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> } ``` -Any context with a `width` and a `height` can now call `rectangle_area()`. That is the whole program. -There is no component to define and nothing to choose, because this trait has one implementation -and needs none. It is the smallest useful thing CGP does, and the right place to start a codebase that -may never need more. +The macro generates a `RectangleArea` trait and implements it for contexts exposing `width` and +`height` through `HasField`, both with type `f64`. A struct can supply those implementations by +carrying the matching fields and deriving [`HasField`](/docs/reference/derives/derive_has_field). +Its values can then call `rectangle_area()`. + +This form suits an operation with one shared implementation. A component becomes useful when +contexts need to select among alternative implementations of the same operation. ## The declared type decides how the field is read -The type on the argument says what the body wants, and the macro inserts whatever bridges it to the -field the context stores. Three cases cover nearly everything: +The argument type determines whether the body receives an owned value or a borrow. These common +forms follow the same access rules as CGP's automatic getters: ```rust #[cgp_fn] pub fn describe( &self, - // Owned: read by reference and cloned, so the context keeps its field. + // Cloned from the context's String field. #[implicit] name: String, - // `&str`: backed by a `String` field, borrowed rather than cloned. + // Borrows the contents of the context's String field. #[implicit] title: &str, - // Any other borrow: taken as it stands. + // Borrows the Vec field directly. #[implicit] tags: &Vec, ) -> String { format!("{title} {name} {tags:?}") } ``` -The rule of thumb is that the body works with the declared type and the conversion is the -macro's problem. Prefer a borrow where the body only reads, `&str` over `String`, since that is free -while an owned argument clones. Further forms exist for options and slices, and they are enumerated on -the [`#[implicit]`](/docs/reference/attributes/implicit) reference page rather than here. - -These are the same rules a getter follows, so learning them once covers both. +An owned argument calls `.clone()` on the field, leaving the stored value in the context. A `&str` +argument reads a `String` field with `.as_str()`, and `&Vec` borrows the vector directly. +Prefer a borrow when the body only needs to read the value, especially when cloning would allocate +or copy substantial data. -## When a getter trait is still the right thing +The macro supports specific access forms rather than arbitrary conversions between types. The +[`#[implicit]` reference](/docs/reference/attributes/implicit) covers options, slices, mutable +access, and the other supported forms. -An implicit argument reads from the provider's own `self`. That covers every value a provider wants -from its own context, including one that several providers each read, declared as the same argument in -each, so it is the default, and a getter trait is the exception. +## When a getter trait is useful -Three cases fall outside it. The value may live on a **type other than the context**, where there is no -`self` field to read and the requirement is a bound on that other type: +A getter trait is useful when field access must be expressed as a named interface. Implicit +arguments read from the provider's own `self`, so they cannot directly read a field from a separate +argument. For example, this provider requires a getter on `Request`: ```rust #[cgp_impl(new AuthenticateByHeader)] @@ -128,53 +126,50 @@ where } ``` -`HasAuthHeader` there is a getter on `Request`, not on the application, and no implicit argument can -express that. The accessor may also need to exist as a **named trait** that other code depends on -through `#[uses(...)]` or a supertrait, because a name is something you can require and an argument is -not. Or the getter may carry an **associated type inferred from the field**, so callers stay generic -over what the value actually is. +This fragment assumes `RequestAuthenticator` and `HasAuthHeader` are defined elsewhere. +`HasAuthHeader` describes access on the request, while `self` is the application context. An +implicit argument on `authenticate` would read the application instead. -Outside those three, prefer the argument. A getter trait declared only so a provider can read a field of -its own context is a trait, an impl, and an import bought for nothing. +A named getter also lets other code require the accessor through a trait bound or supertrait. +A getter with an associated type can keep the field's type abstract for callers. These are reasons +to use [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter); sharing a context field +between several providers alone is not. Each provider can declare the same implicit argument. -## What it costs +A wireable getter supports a further choice: which field supplies the value in each context. +Use [`#[cgp_getter]`](/docs/reference/macros/cgp_getter) when that mapping must vary, rather than +fixing the field name in the implicit argument. -**The field name is part of the interface, silently.** Renaming a struct field breaks every provider -whose argument was named after it, and the failure surfaces as a missing-field error at whatever site -forces the check rather than at the rename. Nothing in the struct definition marks the coupling. +## What it costs -**The requirement is invisible at the call site.** `app.greet()` gives no hint that the context must -carry a `name`. That is the point, since it keeps the requirement off the interface, and it is also -why the answer to "what does this context need?" lives in the providers it wired rather than in the -traits it implements. +Field names become dependencies of providers. Renaming `name` breaks providers whose implicit +argument requires that name, and the error appears where Rust checks the provider's requirements. +The struct definition does not list the providers that depend on its fields. -**Matching by name is looser than matching by type.** Two unrelated values with the same name and type -are the same implicit argument as far as the machinery is concerned, so a context that happens to have a -field called `name` satisfies a provider written for something else. In practice that looseness makes -the mechanism cheap; it is still worth knowing that nobody is checking your intent. +The call site omits those field requirements. `app.greet()` does not show that `GreetByName` needs +`name`; you find that requirement in the selected provider. Rust checks the name and type, but it +cannot tell whether two fields with the same name and type have the same intended meaning. -**The clone is real.** An owned argument copies the field on every call. Usually that is nothing; on -a large value in a hot path it is not, so declare a borrow. +Owned arguments incur the cost of cloning on each call. For a small scalar this is a copy; for a +`String` or a large collection it may allocate and copy data. Declare a borrow when ownership is +unnecessary. ## Where to go next -[Impl-side dependencies](./impl-side-dependencies.md) is the general idea an implicit argument is one leg -of: a requirement stated on the implementation rather than on the interface. -[Abstract types](./abstract-types.md) is the third leg, where what the implementation needs is a type -rather than a value. - -To write this rather than read about it, the [Hello World tutorial](/docs/tutorials/hello) reaches an -implicit argument within its first few minutes, and the -[Area calculation series](/docs/tutorials/area-calculation/) builds up from plain functions of exactly -this shape. - -For the constructs, [`#[implicit]`](/docs/reference/attributes/implicit) carries the full list of -accepted forms and access rules, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the no-wiring -trait, [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter) is the getter to reach for in -the three cases above, and [`HasField`](/docs/reference/traits/field-access/has_field) is the trait underneath all of -them. -- [Comparison: Implicit parameters](/docs/comparisons/implicit-parameters): implicit arguments beside Scala's `using` and Haskell's `ImplicitParams`. -- [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): reading a context field as the dynamic-binding fragment of effect handlers. +These pages connect implicit arguments to the rest of CGP: + +- [Impl-side dependencies](./impl-side-dependencies.md): Why a provider's field requirements stay + out of the consumer interface. +- [Abstract types](./abstract-types.md): Context-selected types shared by generic code. +- [Hello World](/docs/tutorials/hello) and [Area calculation](/docs/tutorials/area-calculation/): + Working examples built from functions with implicit arguments. +- [`#[implicit]`](/docs/reference/attributes/implicit) and + [`#[cgp_fn]`](/docs/reference/macros/cgp_fn): Accepted forms and generated code. +- [`HasField`](/docs/reference/traits/field-access/has_field): The field-access trait underlying + implicit arguments and automatic getters. +- [Comparison: Implicit parameters](/docs/comparisons/implicit-parameters): How the design compares + with Scala's `using` and Haskell's `ImplicitParams`. +- [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): The relationship between + context field access and dynamic binding. --- diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index 1fdca011..a8795e30 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -5,39 +5,34 @@ sidebar_position: 10 # Modular error handling -The error type, how a foreign error becomes it, and what detail it carries: three choices a context -makes independently of the code that fails. +CGP lets reusable fallible code use an error type chosen by its context. The context selects the +error type, how source errors become that type, and how additional detail is attached. This page +follows a port parser through those choices, then applies the pattern to application-specific errors +and explains its costs. -This page answers *how does fallible code avoid committing to an error type?* It separates the three -decisions error handling actually contains, shows a provider that makes none of them, and ends with the -same pattern applied to an application's own error vocabulary. It closes on where the separation stops -paying. +## Separating failure from error representation {#why-the-error-type-is-the-hard-one} -## Why the error type is the hard one +A reusable parser can detect a failure without deciding how every application should represent it. +One application may want a string, another a domain enum, and another an error-library type. Fixing +that choice inside the parser limits where the same implementation can be reused. -Every fallible function has to return *something*, and generic code should not decide what. A -provider parsing a port number does not know whether the application wants `anyhow::Error`, a domain -enum, or a plain string, and hard-coding any of them commits every caller in every application to that -choice. +Ordinary Rust offers several ways to expose the choice. A function can return a concrete error for +callers to convert, take a generic error parameter, or use an associated error type. CGP combines a +shared associated type with interchangeable providers for constructing and enriching errors. -The usual answers each cost something. A concrete error type in a library is a decision imposed on -users. A generic `` parameter is an input the caller supplies, so it lands in every intermediate -signature along with its bounds, which is the leak [impl-side dependencies](./impl-side-dependencies.md) -describes. Converting by hand at each boundary is the boilerplate error-handling crates exist to remove, -and it comes back the moment the boundary is generic. +The built-in components separate these responsibilities: -This becomes tractable once you notice that "error handling" is not one decision but three, and that -they are independent: +- **`HasErrorType`:** Names the context's shared `Error` type, which must implement `Debug`. +- **`CanRaiseError`:** Converts a source error into that shared type. +- **`CanWrapError`:** Attaches detail to an existing error. -- **what the error type is**: a type the context names; -- **how a foreign error becomes it**: `ParseIntError`, `io::Error`, or a `String` from a domain rule; -- **what detail is attached** as it propagates. +A provider declares the raising and wrapping operations it needs. The context then selects +compatible implementations, so these choices can vary without changing the provider's source. -CGP makes each of the three a wiring choice, and the code that fails makes none of them. +## A parser with an abstract error type -## Code that fails without knowing what failing means - -The trait names its error abstractly, and the provider raises into it: +The parser names its return error abstractly and raises the concrete failures it encounters. +This fragment assumes `cgp::prelude::*` and `core::num::ParseIntError` are imported: ```rust #[cgp_component(PortParser)] @@ -63,16 +58,18 @@ impl PortParser { ``` `Error` is the context's [abstract type](./abstract-types.md), imported by `#[use_type]`. -`Self::raise_error` turns a concrete failure into it, and the `#[uses]` line declares which failures -this provider raises, two of them, a parse error and a string, as requirements on the implementation -rather than on the interface. A caller bounding on `CanParsePort` learns none of it. +`Self::raise_error` converts either a `ParseIntError` or a `String` into it. The `#[uses]` line +requires those conversions on the implementation; a caller bounded by `CanParsePort` needs only +the parser interface and its shared error type. -The provider calls `raise_error` on the *type* rather than on a value, because constructing an error is -something the context knows how to do rather than something a particular value does. +`raise_error` is an associated function called on the context type. Error construction therefore +uses the context's selected implementation without requiring a context value. -## Three sources, three strategies, one table +## Selecting a strategy for each source -The context supplies the answers, making the second and third decisions per source error type: +The context can route different source errors through different providers. This table assumes an +`App` context, the error component keys imported from `cgp::core::error`, and `RaiseFrom` and +`DebugError` imported from `cgp::extra::error`: ```rust delegate_components! { @@ -88,21 +85,19 @@ delegate_components! { } ``` -Three lines, three decisions. The error type is `String`. A raised `String` is converted straight -through with `From`. A `ParseIntError` is formatted with `Debug` into a `String`, then handed back -to the context's own `String` route, so the two compose rather than each needing to know the final -type. +`App` uses `String` as its error type. `RaiseFrom` converts a raised `String` through `From`, which +returns the same string here. `DebugError` formats a `ParseIntError` into a string, then calls the +context's `String` raiser. The formatting provider thus relies on the conversion selected by the +context instead of naming the final error type itself. -The per-source dispatch buys exactly that last point. A real application raises a dozen unrelated -failures, and most of them want the same treatment; naming a strategy per source type lets the -interesting ones differ without a match arm anywhere. CGP ships the strategies as ordinary providers: -`RaiseFrom` for a `From` conversion, `DebugError` and `DisplayError` for formatting, `ReturnError` when -the source already is the error type, and `RaiseInfallible` for a step that cannot fail. They stay -generic over whatever error type the context chose. +Other providers express different policies. `DisplayError` uses `Display` formatting, +`ReturnError` accepts a source that already has the context's error type, and `RaiseInfallible` +handles `Infallible`. Per-source dispatch lets a context combine these strategies where needed. -## Changing the answer changes nothing else +## Changing the error type -Because the decisions are separate, moving to a different error type is a change to the table: +The same parser can return a domain error when another context supplies compatible conversions. +In this fragment, `AppError` must implement `Debug` and `From`: ```rust delegate_components! { @@ -118,18 +113,31 @@ delegate_components! { } ``` -`ParsePortFromStr` is the same provider, unmodified and un-recompiled in any meaningful sense. It never -named `String`, so nothing in it referred to the thing that changed. Swapping `anyhow` for `eyre`, or a -prototype's `String` for a real domain type, is this edit. +`ParsePortFromStr` can be reused unchanged because it never fixed its return error to `String`. +It still raises a `String` for an out-of-range port, and `RaiseFrom` now converts that message into +`AppError`. Rust checks and monomorphizes the provider for the new context as usual. + +Error-library backends package compatible type providers, raisers, and wrappers. For example, +`cgp-error-anyhow` supplies providers for `anyhow::Error`, while `cgp-error-eyre` supplies the +corresponding `eyre` integration. Choosing a backend keeps those concrete dependencies in the +application's wiring rather than in reusable providers. + +## Attaching detail as an error propagates -Concrete backends come as separate crates for the same reason: `cgp-error-anyhow` and its siblings each -supply a type-setting provider and the raisers that go with it, so the dependency on `anyhow` lives in -the wiring rather than in any code that fails. +`CanWrapError` lets a provider enrich an error it did not construct. A caller might attach +the configuration path after a port parser fails. The provider declares the wrapping requirement +and calls `Self::wrap_error(error, detail)`; the context chooses how the detail is stored or formatted. + +Wrapping is separate from raising because a source error and propagation detail serve different +purposes. A source explains what failed, while detail can identify which request or resource was +involved. `DiscardDetail` can deliberately ignore that detail, and a backend wrapper can preserve it. +The parser above only raises errors, so its context does not need a wrapper until another provider +requires one. ## An application's own error vocabulary -None of this is confined to CGP's built-in components, and the clearest sign of that is defining your -own. A service that wants every failure to carry an HTTP status declares a component for it: +Application-specific components can express failures that need more structure than a message. +A service can define a raising operation that takes a status marker and detail: ```rust #[cgp_component(HttpErrorRaiser)] @@ -139,49 +147,46 @@ pub trait CanRaiseHttpError { } ``` -`ErrUnauthorized` and `ErrNotFound` are empty structs standing for status codes, and a provider per code -builds the concrete error. A handler deep in the request pipeline then writes +Markers such as `ErrUnauthorized` and `ErrNotFound` identify domain failures. Providers map them to +status codes and construct the context's error. A handler requiring the appropriate +`CanRaiseHttpError` implementation can then call: ```rust Self::raise_http_error(ErrUnauthorized, "you must first login") ``` -and knows neither the status number nor the error type. The two are decided in the table, in the same -place as everything else the application decides. This is the whole pattern, applied to a vocabulary -the built-in components know nothing about. +The handler names the failure and its detail. Its selected provider determines the numeric status +and concrete error representation, just as the built-in raiser determines how a parse error is stored. ## What it costs -**The imports are not in the prelude, deliberately.** `HasErrorType` and `CanRaiseError` are, but the -wiring keys live under `cgp::core::error` and the strategy providers under `cgp::extra::error`. That is -a real annoyance the first time, and it is the price of the error components not being forced on code -that does not use them. - -**Three decisions means three ways to be under-wired.** A context can name an error type and forget a -raiser for a source some provider raises, and it compiles until something raises one. -[`check_components!`](/docs/reference/macros/check_components) catches it, as with any other -wiring. +The selected error type must satisfy every chosen provider's requirements. A formatting route can +lose the original error's structure, and a `From` route requires a suitable conversion. Changing +the type may therefore require changing strategies as well as the type-setting entry. -**The error type is one per context.** All the code in a context sharing one `Error` lets errors -compose without conversion; it also means a context genuinely needing two unrelated error types needs -two components or two contexts. +Missing raisers and wrappers can remain undetected until the relevant operation is checked or used. +Use [`check_components!`](/docs/reference/macros/check_components) to verify the parser and other +application components against their contexts. Naming an error type alone does not establish that +all required conversions exist. -**And it does not decide what a good error is.** CGP makes the type swappable and the construction -routable. Whether your errors carry useful context, whether they are matchable, whether the messages -help: all of that is the same design problem it always was, and wiring answers none of it. +`HasErrorType` selects one shared error type per context. That makes component errors compose, but +an application needing independent error types must model them with separate type components or +contexts. CGP also leaves error design to the application: useful messages, preserved causes, and +matchable variants depend on the chosen representations and providers. ## Where to go next -[Abstract types](./abstract-types.md) is the mechanism the error type rests on, and worth reading first -if `#[use_type]` above was unfamiliar. [Impl-side dependencies](./impl-side-dependencies.md) is why the -`#[uses(CanRaiseError<…>)]` line does not reach callers, and -[Dispatching](./dispatching.md) is the general form of the per-source routing. - -For the constructs, [`HasErrorType`](/docs/reference/components/has_error_type) is the abstract error -type, [`CanRaiseError`](/docs/reference/components/can_raise_error) covers raising and wrapping, and -[the error providers](/docs/reference/providers/error) is the catalogue of strategies with the -bound each one places on the context. -- [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): why `raise_error` selects an interpretation but passes no control. +These pages explain the supporting mechanisms and available strategies: + +- [Abstract types](./abstract-types.md): How the context selects a shared type. +- [Impl-side dependencies](./impl-side-dependencies.md): Why conversion requirements stay on the + provider. +- [Dispatching](./dispatching.md): Selecting providers by type. +- [`HasErrorType`](/docs/reference/components/has_error_type) and + [`CanRaiseError` / `CanWrapError`](/docs/reference/components/can_raise_error): The error interfaces. +- [Error providers](/docs/reference/providers/error): Strategies and their requirements. +- [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): Why raising selects an + interpretation while ordinary Rust control flow still propagates the error. --- diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index c53dccb4..509fc5b8 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -5,34 +5,35 @@ sidebar_position: 18 # Modularity Hierarchy -How much CGP does an operation need? The answer is a tier in a five-tier hierarchy, where each tier -allows more independent implementations of one interface than the tier below, at a matching cost in -syntax or coupling. The right tier is the lowest one that still expresses the problem. +Choose the least complex implementation model that supports the choices your program needs. +Rust traits and CGP components offer a progression from one shared implementation to providers +selected independently by context, target type, and enclosing provider. Each additional choice +requires more structure. -This page explains each tier in turn on one running operation, encoding a value, so the only thing -that changes from tier to tier is the modularity, not the problem. It then turns to the decision: how -to pick a tier, when a plainer tool is the better choice, and what the machinery costs. If you are -still deciding whether CGP is for you at all, read to the end of the decision guide. +This page follows encoding through the tiers, then gives a decision guide for choosing among them +and ordinary Rust alternatives. The examples are fragments: imports from `cgp::prelude::*`, context +structs, and some provider bodies are omitted to keep the implementation choices visible. -## The five tiers at a glance +## The tiers at a glance -The table is the summary; the sections below explain each tier in full. +The tiers differ in where a program can select an implementation: -| Tier | What it allows | The construct | The coherence limit it escapes | -|---|---|---|---| -| **1** | One implementation for every type | a blanket impl, or [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) | none: one implementation only | -| **2** | One implementation per type | a plain Rust trait | none: one implementation per type | -| **3** | Many implementations, one wired per type | [`#[cgp_component]`](/docs/reference/macros/cgp_component) and [`delegate_components!`](/docs/reference/macros/delegate_components) | the overlap rule | -| **4** | Many implementations, one per type per context | a type parameter and the [`open` statement](/docs/reference/macros/delegate_components) | the orphan rule as well | -| **5** | Many implementations, per type per provider | a [higher-order provider](./higher-order-providers.md) | none new: a local override within tier 4 | +| Tier | Implementation choice | Construct | Main constraint | +| --- | --- | --- | --- | +| **1** | One shared implementation for types satisfying its bounds | A blanket impl or [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) | Matching types share the same logic | +| **2** | One implementation per target type | A plain Rust trait | Selection follows the trait and target type | +| **3** | One provider per wired type | A CGP component and wiring | Each wired type still has one choice for that component | +| **4** | One provider per target type in each context | A parameter-targeted component and `open` | The interface must separate context from target | +| **5** | An inner provider chosen by an enclosing provider | A higher-order provider | The enclosing provider depends on the inner provider interface | -Tiers 1 and 2 are ordinary Rust. Tiers 3 through 5 are CGP, and each one loosens a coherence -constraint that the tier below still obeys. +All tiers obey Rust's coherence rules. CGP permits reusable alternatives by placing their +implementations on distinct provider types, then using wiring to select one unambiguously. +Tier 5 adds a local composition choice rather than relaxing another coherence rule. -## Tier 1: one implementation for every type +## Tier 1: one implementation for matching types -The lowest tier is a single implementation that applies to every type meeting a bound. A blanket -trait implementation captures one piece of logic and offers no alternative to it. +A blanket implementation shares one body across every type satisfying its bounds. Here, all +byte-like values encode by copying their bytes: ```rust pub trait CanEncode { @@ -46,15 +47,18 @@ impl> CanEncode for Value { } ``` -Every type that is `AsRef<[u8]>` now encodes the same way, and no second strategy is possible. -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds this same tier from a plain function, and hides -the bound behind a clean interface. Reach for tier 1 when a trait genuinely has one -implementation for all types. +Every matching type receives this implementation. A second implementation for a type covered by +that blanket would overlap it and be rejected. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) +expresses the same arrangement from a function and keeps the implementation's bounds off the +consumer interface. + +Use this tier when matching types should share one implementation. It requires neither named +providers nor wiring. ## Tier 2: one implementation per type -A plain Rust trait raises the ceiling to one implementation per type. Each type supplies its own -body, and coherence still allows only one. +A plain trait allows different types to supply different bodies. With this non-generic interface, +each type still has one implementation: ```rust pub trait CanEncode { @@ -74,17 +78,18 @@ impl CanEncode for Vec { } ``` -Each type varies, but the choice is global: once `u32` encodes one way, that is the only way for the -whole program. A blanket implementation that would share logic across several types is rejected, -because it could overlap. This is where Rust's coherence guarantee delivers its value, and also where -it starts to bind. Tier 2 is the right tier for an operation that varies by type but never by -application. +`u32` encodes as decimal text, while `Vec` copies its bytes. The choice is shared wherever +that trait is used for that type. Blanket implementations remain possible where they do not +overlap other impls; coherence prevents ambiguous combinations. + +This tier fits behavior that varies by type but does not need an independent choice per application. +Rust's orphan rules also determine which crate may supply an implementation. -## Tier 3: many implementations, one wired per type +## Tier 3: reusable providers, one selected per wired type -The first CGP tier splits the trait into a consumer trait you call and a provider trait you -implement. Many overlapping implementations become legal, each one a named provider, and every type -wires the one it uses. +A CGP component separates the consumer trait callers use from the provider trait implementations +supply. Distinct provider types can support the same target without their implementations +overlapping: ```rust #[cgp_component(SelfEncoder)] @@ -101,9 +106,9 @@ impl SelfEncoder { } ``` -`EncodeSelfAsText` and a bytes-based `EncodeSelfAsBytes` can both exist, even on a type that matches -both, because each provider is its own name rather than an implementation of the trait itself. A type -then wires one provider: +`EncodeSelfAsText` requires the context to implement `Display`. A separate `EncodeSelfAsBytes` +provider can require `AsRef<[u8]>`, even if some types satisfy both bounds. Wiring selects the +provider for a concrete type: ```rust delegate_components! { @@ -113,22 +118,25 @@ delegate_components! { } ``` -Add [`check_components!`](/docs/reference/macros/check_components) when you wire. The wiring is checked -lazily, so an unchecked table is the main source of confusing errors. +Here, `u32` uses `EncodeSelfAsText`. The example defines the component locally, which permits this +wiring on a foreign value type. A downstream crate cannot independently rewire both a foreign +component and a foreign value type. + +Check concrete wiring with [`check_components!`](/docs/reference/macros/check_components). +A table entry alone does not force Rust to verify all of the selected provider's dependencies. -### Tier 3 holds two shapes +### Value contexts and application contexts -This tier behaves differently depending on what the wired type *is*, and the difference is the one -readers most often miss, because nothing in a signature marks it. +The wired type can represent either the value being operated on or an application environment. +That distinction changes what “one choice per type” means without necessarily changing the method +signature. -In the **retrofit** shape the wired type is the data itself, as `u32` is above. That type is usually -one you do not own, so it gets one wiring for the whole program. This is the right shape when the -operation belongs to the data, or when an existing trait cannot change its signature. +In the **value-context** arrangement, `Self` is the data, as `u32` is in the encoding example. +The provider operates on that value, and wiring selects one provider for it. This arrangement suits +adding reusable behavior to a value while retaining a self-targeted interface. -In the **application** shape the wired type stands for the application rather than for data, and it -often has no fields at all. Here the "one wiring per type" limit stops mattering, because you decide -how many application types exist. The operation is about the application, such as sending an email or -querying a user, rather than about a value: +In the **environmental-context** arrangement, `Self` carries an application's dependencies and +implementation choices. An operation such as sending email belongs to that context: ```rust #[cgp_component(EmailSender)] @@ -146,16 +154,22 @@ delegate_components! { App { EmailSenderComponent: SendViaSmtp } } delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } ``` -`App` and `TestApp` are both yours, so each wires its own provider with no type parameter anywhere. -Notice the crossing: `u32` in the first example is data in the `Self` position, while `App` here is a -type that stands for the application. **The application shape is where most CGP code lives**, so a -reader who takes tier 3 to be only the retrofit shape has undersold it. +The provider bodies are elided here. An SMTP provider would require connection settings or a client; +a recording provider would require storage for captured messages. `App` and `TestApp` supply those +dependencies and select different providers for the same consumer trait. + +Application contexts make independent choices possible without parameterizing the trait over a +target value. Both contexts belong to the application, so it can define and wire them separately. +This is a common CGP arrangement for services, test environments, and application operations. + +Components may group methods, associated types, and consts, just as ordinary traits do. The examples +use one method to isolate provider selection; the appropriate grouping depends on which items a +provider should implement and reuse together. -## Tier 4: many implementations, one per type per context +## Tier 4: one provider per target type per context -Tier 4 moves the target type out of `Self` and into a parameter, so `Self` is always an application -context. This lifts the orphan rule and lets each context choose a provider per target type, -including for types it does not own. +A parameter-targeted component separates the application context from the value it operates on. +`Self` selects the implementation, while `Value` identifies the target: ```rust #[cgp_component(Encoder)] @@ -164,9 +178,8 @@ pub trait CanEncodeValue { } ``` -Two applications can now encode the same foreign type differently. With an `EncodeAsText` provider -for `Display` types and an `EncodeAsHex` provider for `AsRef<[u8]>` types, `ApiServer` writes a -`String` as text where `Firmware` writes it as hexadecimal: +Each application can now choose how the same foreign type is encoded. Assume `EncodeAsText` +supports `Display` values and `EncodeAsHex` supports `AsRef<[u8]>` values: ```rust delegate_components! { @@ -184,19 +197,19 @@ delegate_components! { } ``` -Because the wiring keys on the context rather than on `String`, a crate that owns neither the trait -nor `String` can still wire it, as long as it owns the context. The cost is that the trait must carry -the extra parameter from the start, so it cannot be added to an existing trait such as -`serde::Serialize` without a breaking change, and every value type a context uses must be wired. -Reach for tier 4 when different applications must treat the same foreign type differently. Most code -does not need it. +`ApiServer` encodes a `String` as text, while `Firmware` encodes its bytes as hexadecimal. A crate +owning either context can supply that wiring even when it owns neither the component nor `String`. +Ownership of the context satisfies Rust's rules for the wiring implementation. -## Tier 5: many implementations, per type per provider +The extra choice requires a compatible interface. An existing self-targeted trait cannot acquire +this context-and-target separation merely by changing wiring. The context must also supply entries +covering the target types it uses, although generic entries can cover families of types. +Use this tier when target behavior must vary independently between contexts. -The top tier lets one provider fix the wiring of a nested type on its own, without routing that -choice back through the context. It takes the inner provider as a parameter, which makes it a -[higher-order provider](./higher-order-providers.md). An encoder for a `Vec` encodes each -element through an inner provider, and defaults that inner provider to the context when none is named: +## Tier 5: an inner provider chosen locally + +A higher-order provider can select an inner implementation independently of the context's default +choice. This vector encoder accepts an element encoder as a type parameter: ```rust pub struct EncodeVecWith(pub PhantomData); @@ -210,8 +223,8 @@ impl Encoder> { } ``` -A context can then pin the inner encoding for one collection while leaving others to its general -wiring: +`Inner = UseContext` makes element encoding use the context's ordinary selection unless wiring +supplies another inner provider. A context can choose both forms: ```rust delegate_components! { @@ -224,181 +237,141 @@ delegate_components! { } ``` -The `Vec` entry omits the parameter, so each `u32` routes back through the context to -`EncodeAsText`. The `Vec>` entry pins its inner encoding to `EncodeAsHex`, whatever the -context does with `Vec` elsewhere. The `UseContext` default is what makes both entries read the -same. This tier adds coupling and higher-order machinery, so reach for it only when a local override -genuinely matters. - -## Choosing a tier - -The guiding rule is to settle at the lowest tier that expresses the use case, because each higher -tier trades simplicity for modularity that may not be needed. Most code has one implementation of -most things, and for that code a plain trait is the right answer rather than a compromise. +`Vec` uses the default, so each element goes through the context's `u32` route to +`EncodeAsText`. `Vec>` explicitly selects `EncodeAsHex` for each inner byte vector, +regardless of how the context encodes `Vec` elsewhere. -Two questions place an operation faster than working through the tiers one by one. +The local override lets a collection or wrapper impose a specific inner interpretation while +other operations retain the context's general choice. It also adds another provider parameter and +interface dependency. Use it when that local choice is part of the operation's design. -**Is the operation about the data, or about the application?** About the data means the wired type -*is* the thing being operated on, as `Rectangle: CanCalculateArea` is. About the application means the -wired type is one you define to carry choices, often with no fields at all. - -**Does it concern a type you do not own, which different applications must treat differently?** If so, -that type moves out of `Self` and becomes a parameter. If not, targeting `Self` is enough. - -The answers name one of three shapes, and none of them is more advanced than the others. Each is the -right answer to a different question. - -| Answers | The shape | What it gives you | -|---|---|---| -| About the data | **Retrofit** (tier 3) | Alternative implementations for an existing type, without changing its trait. One choice per type, program-wide. | -| About the application | **Application** (tier 3) | One choice per context you define, and you can define as many as you like. | -| About a foreign type, differing per application | **Fully modular** (tiers 4–5) | One choice per context, per target type. | +## Choosing a tier -**The application shape is where most CGP code lives.** An operation about the application, such as -sending an email or running the server, wired per application with no type parameter anywhere, is the -ordinary case rather than the elaborate one. +Start with a plain trait or blanket implementation and add provider selection where there is a +concrete need for reuse or alternatives. A consumer trait can also be implemented directly on a +context; using CGP does not require turning every implementation into a provider. -As wiring grows, [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) and aggregate providers keep -it readable by grouping shared wiring into reusable tables. Both add a hop between a component and its -provider, so neither pays until the repetition is real. +When providers are useful, identify what the context represents and whether the operation targets +another type. These arrangements answer different needs: -## CGP, or the tool already in place? +| Need | Arrangement | Selection scope | +| --- | --- | --- | +| Reusable behavior on the value itself | Value context, self-targeted component (tier 3) | One choice per wired value type | +| Application operations with selectable dependencies | Environmental context, self-targeted component (tier 3) | One choice per application context | +| Behavior for a target type that differs by application | Environmental context, parameter-targeted component (tier 4) | One choice per context and target type | +| A wrapper needs a particular inner implementation | Higher-order provider (tier 5) | A choice within that provider composition | -Deciding a tier assumes CGP is the right tool at all, and often it is not. The useful question is -never "is CGP good" but "CGP, or the thing already in place?". Each row below concedes where the -alternative wins, because in most rows it does. +An application-level operation does not need a target parameter merely to support testing. +Separate `App` and `TestApp` contexts can select different email providers at tier 3. A target +parameter becomes useful when the operation acts on types whose treatment must vary independently +of those types' own trait implementations. -| The alternative | Prefer it when | Reach for CGP when | -|---|---|---| -| **A plain trait or generic** | A trait has one implementation, or one per type with a single global choice. **This is most code.** | The implementations multiply, the choice must differ per context, or threading a generic through every layer has started to hurt. | -| **A direct impl on the context** | A provider would have exactly one user. Two contexts that each have their own single implementation need no providers and no wiring at all. | A second context wants the *same* implementation, or the implementation should compose with a wrapper. | -| **An enum** | The variant set is small, closed, and known, with fixed operations. A `match` is clearer than any machinery. | The variant set is open, or independent modules must each contribute one. | -| **`dyn Trait`** | The set of implementations is not known until runtime. CGP gives up exactly that openness. | The set *is* known at build time, and you want the decoupling without the dispatch cost. | -| **A dependency-injection crate** | You specifically want a container's lifecycle and object-graph semantics. | You want compile-time-checked, reflection-free injection, which is the traits-and-generics approach, not a framework. | -| **A generic-programming library such as `frunk`** | A one-off manipulation of a heterogeneous list. The lighter, focused library is less to learn and enough. | The structural machinery is part of a larger component-and-wiring design. | -| **A hand-rolled macro** | The generation is narrow and local. | You notice you are reinventing marker types plus a helper trait, which is CGP's own mechanism. | -| **Waiting for a language feature** | A first-class facility would serve better and you can afford to wait. Rust's effects and reflection work is pursuing ground CGP covers. | You need the feature now, on stable Rust. CGP is complementary to what the language is building rather than a bet against it. | +Shared wiring is a separate concern from the tier. [Aggregate providers](./aggregate-providers.md) +and [namespaces](./namespaces.md) group repeated selections; they become useful when the shared +table is worth maintaining as a unit. -That last row is worth taking seriously rather than reading as a formality. Some of what CGP does is -plausibly better as a language feature eventually, and a project that can wait should. +## Comparing ordinary alternatives -## Where CGP is the wrong tool +Choose the tool that supplies the variation you actually need. These alternatives remain useful +alongside CGP: -Four cases are not trade-offs. Naming them is more useful than any argument in CGP's favour. +| Alternative | Prefer it when | Consider CGP when | +| --- | --- | --- | +| **Plain traits and generics** | One shared implementation or one implementation per type is sufficient. | Reusable alternatives must coexist, or implementation dependencies should stay out of intermediate interfaces. | +| **A direct impl on the context** | The body is specific to that context. | Another context can reuse the body, or a provider wrapper needs to compose with it. | +| **An enum and `match`** | The alternatives are a small, closed set with fixed operations. | Independent modules need to contribute handlers reused across different variant sets. | +| **`dyn Trait`** | Implementations must be selected at runtime or stored behind a common runtime interface. | Provider selection can be fixed at compilation. | +| **A dependency-injection library** | Its object construction, lifecycle, or configuration model matches the application. | Rust traits and compile-time wiring express the needed dependency choices. | +| **A focused generic-programming library** | Structural operations on heterogeneous data are the main requirement. | Those operations need to compose with a broader provider-and-wiring design. | +| **A local macro** | The generated pattern is narrow and specific to the crate. | Repeated helper traits and marker types amount to a reusable component system. | -**Runtime dynamism.** CGP cannot give you plugins loaded at startup, heterogeneous collections, or -redefinition while the program runs. Its wiring is fixed at build time. That lives on the runtime -side, where `dyn Trait` and the dynamic languages remain right. +Runtime choices can live inside a CGP context. For example, a provider can call through a trait +object stored in a field. Static wiring selects that provider; the trait object still performs +its own runtime dispatch. -**Exactly one implementation.** A trait with one definition belongs in a plain trait, which is -tier 1 or tier 2. If you want it to read like CGP anyway, -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) builds it from a function with no component, no provider, -and no wiring, and it keeps working unchanged if a second implementation ever arrives. +## Where provider wiring does not help -**A small closed set of variants.** An enum and a `match` are clearer, faster to read, and free. +Static wiring cannot load previously unknown implementations at runtime. A plugin system or +runtime-open collection needs an appropriate dynamic interface. CGP can participate in such a +program, but its wiring does not supply that runtime extensibility. -**One instance program-wide.** When a program genuinely wants a single globally consistent answer, -such as one `Ord` for a map key where two orderings in one program would corrupt the map, per-context -choice is the wrong shape. Coherent traits are safer, and this is the limit of CGP's central bargain. +An operation with one suitable implementation does not need provider selection. +A plain impl, blanket impl, or [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) can express it directly. +Likewise, a small closed enum usually needs only a `match` rather than generic variant dispatch. -## "I only have one application — what does this buy me?" +Some APIs depend on one consistent interpretation of a value. Ordering within a map, for example, +must remain consistent across its operations. Independent provider choices are useful only when +the surrounding design preserves such invariants; they are not a reason to replace a coherent +trait that already expresses the required contract. -This is the question most people reach in their first week, looking at the single context their -codebase contains, and it deserves a straight answer rather than a prediction about the future. +## Evaluating a single-context application -**Concede the obvious part first: with one context, the swappability payoff is not available.** Every -wiring line has one plausible value and every provider one user. Nothing about that is going to feel -worthwhile, and being told you will want a second context later asks you to spend now for a benefit -you cannot check. +One context does not demonstrate the benefit of selecting different providers across contexts. +It may still have needs that provider-based code addresses: -Three things do pay with one context. +- **Alternative implementations for target types:** Distinct providers can coexist where ordinary + blanket impls would overlap. +- **Behavior for foreign targets:** A locally owned context can select a provider for a foreign + component and target type. +- **Implementation-specific dependencies:** A provider's bounds state which operations and values + its body may use without adding those requirements to the consumer interface. -- **Overlapping implementations Rust rejects outright.** These multiply along the *target types* one - application touches, not along its contexts, so a single application with several types to encode, - serialize, or validate already has more than one implementation to place. That is - [bypassing coherence](./coherence.md), and it needs no second context at all. -- **The orphan-rule escape.** Adding a trait implementation to a type from another crate needs one - context and - a foreign type. No newtype wrapper, and no second application. -- **Dependencies declared where the implementation is.** A `&self` method on a concrete struct may - read any field and call any other method, so nothing short of reading the body tells you what it - depends on. A provider's declared requirements *are* that answer, and the compiler enforces them. - This is worth something in one context and more in each one added. +A test environment may provide another concrete use for separate choices, but it should justify +its own context. The possibility of future variation alone does not justify present wiring. +If these needs are absent, use a simpler implementation form. -And then the second context you probably already have: **the test harness.** It is the cheapest one -to justify and the one nobody argues about. +## Representing configuration choices -**If none of that applies, the honest recommendation is to stay put.** A codebase with one -application, no trait needing more than one implementation, and no foreign type to extend is one -where CGP's central bargain does not pay. Reach for `#[cgp_fn]` alone, or nothing. +A separate handwritten context is not required for every combination of settings. +A generic context definition can share structure across backend types, though each concrete +instantiation remains a distinct Rust type. Enums and trait objects can represent choices made +from runtime configuration. -## "Won't I end up with a context per configuration?" +Use distinct context types where the distinction should be checked statically. For example, +separating a test client from a production client can prevent accidental substitution. Keep other +choices as fields or generic parameters when that gives the program the flexibility it needs. -Partly justified, and the answer is composition rather than reassurance. Separating every axis really -would multiply: four independent binary choices would mean sixteen types. +Context-generic libraries can also leave backend representation to downstream applications. +When providers depend on context traits rather than a fixed backend enum, a downstream crate can +define its own context and backend representation. It can reuse the providers whose requirements +that context satisfies without changing the upstream enum. -CGP does not ask you to separate an axis you do not need separated, and it composes with the patterns -that collapse one. A generic parameter on the context struct keeps a single type across several -database engines. An enum keeps a single type for a choice made from configuration at runtime. A -context holds either of those and wires its components normally. +## What it costs -A real application lands on separation for the axis where a wrong combination must be **impossible**, -such as a mock client never reaching production, and collapse for everything else. CGP decides which -variations are worth their own type; the tools you already use handle the ones that are not. +Provider selection adds declarations and another step when reading a call. A component generates +consumer and provider traits plus a wiring key; the context's table identifies the provider that +runs. Wrappers and namespaces can add further steps to that trace even though selection is static. -There is a payoff here worth naming if you are writing a library. An enum you expose for supported -backends is normally a ceiling on what downstream users can have: a new variant means a pull request -or a fork. When the context-generic code is written against traits on the context rather than against the -enum, a downstream crate defines its own wider enum and its own context and reuses everything, with -nothing to petition for. +Wiring failures can produce verbose diagnostics involving generated types and transitive bounds. +[`check_components!`](/docs/reference/macros/check_components) forces selected requirements to be +checked near the wiring. `cargo cgp check` leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[cargo-cgp documentation](/docs/cargo-cgp/) explains the checking workflow. -## What it costs +Macros, trait resolution, and monomorphization add compile-time work. The effect depends on the +program and should be measured for the codebase being evaluated. Static dispatch removes runtime +provider lookup, but that does not mean every added compilation cost replaces a runtime cost. -**Every tier above a plain trait costs syntax and indirection.** Two traits, a marker type, and a -wiring line per context, plus a hop between a call and the code that runs. The wiring table is a -single greppable place naming exactly one provider per component, and it is still a hop a reader has -to follow. - -**Diagnostics are the sharpest cost, and honesty here matters more than elsewhere.** A mis-wired -context can produce a wall of generated types. -[`check_components!`](/docs/reference/macros/check_components) forces the failure to the wiring line -and names the actual missing requirement, and -[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) un-hides the root cause the default -trait solver suppresses and leads with it. Both help substantially. Neither makes the raw output -pleasant, and the tool is a `v0.1.0-alpha` that reshapes the classes it recognizes rather than all of -them. **Dramatically better and actively improving, not solved.** - -**Compile-time cost goes up.** CGP does more work at compile time, and no number is quoted here that -could not be cited. The honest reframing is that resolution costing at compile time is resolution -that would otherwise cost at runtime or not be checked at all. - -**There is a learning curve.** The first useful thing, an operation written as a function used with -no wiring, needs only ordinary Rust knowledge, so the first step is small. The curve past it is real. - -Three of those costs, the learning curve, decoding the diagnostics, and the volume of wiring to write -and read, are mechanical work over a vocabulary that is written down, which is the kind of thing a -coding assistant handles well. CGP publishes an -[agent skill](https://github.com/contextgeneric/cgp-skills) that teaches one that vocabulary, and a -reader who already works with an assistant can attach it and judge for themselves within the hour. It -makes those three costs **smaller, not absent**: the diagnostics are still verbose, the vocabulary -still has to be learned by whoever reviews the code, and none of it moves any boundary on this page. A -codebase that will only ever have one application still belongs on `#[cgp_fn]` alone, regardless of -who writes the wiring. +The vocabulary and generated code take time to learn. CGP's +[agent skill](https://github.com/contextgeneric/cgp-skills) can help a coding assistant explain +providers, trace wiring, and diagnose missing requirements. Reviewers still need to understand the +result, and assistance does not make an unnecessary abstraction worthwhile. ## Where to go next -[Bypassing coherence](./coherence.md) is the argument behind the hierarchy: why Rust allows one -implementation per type, and what CGP does about it. Read it if the question is *why* rather than *how -far*. - -[Consumer and provider traits](./consumer-and-provider-traits.md) covers the mechanism tiers 3 -through 5 are built on, and closes with the same costs stated for that construct specifically. - -If the answer here was "not yet", [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) is the whole of what -you need: a trait from a function, no wiring, nothing to reverse later. If it was "yes", the -[Area calculation series](/docs/tutorials/area-calculation/) works up the tiers in order, and -[`#[cgp_component]`](/docs/reference/macros/cgp_component) is where the component machinery starts. -- [Comparison: Type classes](/docs/comparisons/type-classes): why keying selection on the context rather than the type is the decisive shape. +These pages explain the mechanisms and develop working examples: + +- [Bypassing coherence](./coherence.md): Why Rust requires unambiguous implementations and how + distinct providers allow alternatives. +- [Consumer and provider traits](./consumer-and-provider-traits.md): How calls reach selected + implementations. +- [Higher-order providers](./higher-order-providers.md): Inner provider choices and composition. +- [`#[cgp_fn]`](/docs/reference/macros/cgp_fn): A single implementation generated from a function. +- [Area calculation](/docs/tutorials/area-calculation/): A tutorial progressing from functions to + components and composition. +- [`#[cgp_component]`](/docs/reference/macros/cgp_component): Component definitions and generated traits. +- [Comparison: Type classes](/docs/comparisons/type-classes): How context-based selection changes + the scope of implementation choices. --- diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index 74a81b3c..dda7855b 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -5,20 +5,16 @@ sidebar_position: 12 # Monadic handlers -Chaining handlers into a pipeline that stops at the first step producing a result the chain should -return. +Monadic handlers let a pipeline choose whether to continue based on each step's result. A pipeline +can stop at the first error, stop at the first success, or pass every output onward. This page +builds on [handlers](./handlers.md) to explain those choices, how CGP composes them, and when an +ordinary function is simpler. -This page answers *how does a pipeline handle a step that should end it?* It is short, and it assumes -[handlers](./handlers.md). It shows where plain composition stops working, what a monad supplies that -fixes it, and the three CGP ships. It closes on when this is more machinery than a `?` operator. +## When direct composition does not fit -## Where plain composition stops - -Chaining handlers works by feeding each output into the next input, which is right exactly when every -step always wants to continue. - -The moment a step can produce a value meaning *stop, this is the answer*, it is wrong. Take a -computation that can overflow: +Direct composition through `Computer` passes each step's entire output to the next step. +That does not fit a chain whose steps return `Result` but accept only `T`. Consider this +computer, defined with imports from `cgp::prelude::*`: ```rust #[cgp_computer] @@ -27,50 +23,62 @@ pub fn increment(value: u8) -> Result { } ``` -Chaining two of these plainly does not even compile: the first produces a `Result` and the second -wants a `u8`. And forcing the types to match would be worse than the type error, because the later -steps would run on a value they were never meant to see. +`Increment` accepts a `u8` and produces a `Result`. Directly composing two copies +through `Computer` fails because the second expects a `u8`, not the complete `Result`. The chain +needs a rule that passes the value inside `Ok` onward and returns an `Err` immediately. -`Result` is the familiar case, and the shape is more general than `Result`. Any output type carrying two -possibilities, one to carry on with and one to return immediately, has the same problem. +The handler interface matters here. Ordinary composition through `TryComputer` or `Handler` +already propagates its outer error with `?`. Monadic composition makes the continuation rule a +separate choice, including when `Result` is the output of a `Computer` or when success should end +the chain. -## What a monad supplies +## Choosing the continuation rule -A **monad**, in this setting, is a small answer to three questions about an output type: which case -threads forward into the next step, which case short-circuits out as the final result, and how a plain -value is lifted back into the type. Nothing more abstract than that is needed to read this page. +A **monad** describes how to compose computations through a surrounding type. In CGP's result-based +monads, it determines which branch supplies the next input, which branch ends the pipeline, and how +a value is placed into the result type. The identity monad supplies ordinary composition without a +result wrapper. -Given those answers, a list of handlers can be composed so each step runs only on the "continue" branch -of the one before, and a "stop" value flows untouched to the end: +`PipeMonadic` combines that choice with a type-level list of providers. This type fragment uses +`PipeMonadic` from `cgp::extra::monad::providers` and `ErrMonadic` from +`cgp::extra::monad::monadic::err`: ```rust -PipeMonadic:: +PipeMonadic ``` -Starting from `1` this produces `Ok(4)`. Starting from `253` the third step overflows, so the pipeline's -output is `Err("overflow")` and the remaining steps do not run. That is the `?` operator, expressed as a -type. +`ErrMonadic` passes each `Ok` value to the next `Increment` and stops on `Err`. Starting from `1` +produces `Ok(4)`. Starting from `253` reaches `254`, then `255`, then returns `Err("overflow")`. +Starting from `255` fails in the first step and skips the other two. This is the control flow of +successive `?` expressions, assembled from provider types. + +## The built-in monads -## The three CGP ships +Choose the marker according to which result should end the pipeline: -**The err monad** continues on `Ok` and short-circuits on `Err`, the `?`-style early return above, -where the first failure wins. It is the one most pipelines want. +| Marker | Input passed to the next step | Result that ends the pipeline | +| --- | --- | --- | +| `ErrMonadic` | The value inside `Ok` | `Err` | +| `OkMonadic` | The value inside `Err` | `Ok` | +| `IdentMonadic` | The complete output | Every step continues | -**The ok monad** is its mirror: it continues on `Err` and stops on `Ok`. That sounds backwards until you -want a chain of attempts where the first *success* ends it: a lookup tried against several sources, a -parser trying alternatives. +`OkMonadic` supports a sequence of attempts where the first success wins. Each failed attempt must +return, in `Err`, the input the next attempt needs. For example, variant dispatch can pass the +unmatched remainder onward until one handler accepts it. -**The identity monad** never short-circuits and threads every value forward, which recovers plain -composition. It exists so that "no short-circuiting" is a choice you make rather than a different -combinator you reach for, and a `Result`-producing chain almost never wants it. +`IdentMonadic` lets a pipeline use the same composition interface without short-circuiting. +It forwards the whole output, so the next provider must accept that exact type. Using it with +`Increment` does not resolve the `Result`-versus-`u8` mismatch. -They also stack, so a pipeline over a nested `Result, F>` can short-circuit on the outer -error while threading the inner result. +Monad transformers combine continuation rules for nested results. For +`Result, F>`, `OkMonadicTrans` stops on an outer `Err(F)` or an inner +`Ok(T)` and continues with the `E` inside `Ok(Err(E))`. Both result layers affect whether another +step runs; their nesting order determines how the output is interpreted. -## It is still just a provider +## A pipeline is an ordinary provider -The pipeline that comes out is an ordinary provider for the [handler family](./handlers.md), so it goes -in a table like anything else and nothing downstream knows a monad was involved: +The composed pipeline fits into the same wiring as any other handler provider. This fragment +assumes an `App` context and imports `ComputerComponent` from `cgp::extra::handler`: ```rust delegate_components! { @@ -80,41 +88,41 @@ delegate_components! { } ``` -The whole construction lives in types: the monad is a zero-sized marker, the handler list is a -type-level list, and the pipeline carries no runtime value, so the only branching at run time is the -branching the logic actually asked for. +Callers use the ordinary `CanCompute` interface. For this example, the code tag is `()` and the +input is `u8`; the output is `Result`. The context's wiring selects the pipeline, +and its callers do not need a separate monadic interface. -## What it costs +Provider selection happens at compile time, while the increments and result branches execute when +the pipeline runs. The marker and provider list require neither runtime instances nor a runtime +lookup table. `PipeMonadic` also supports the async and fallible handler forms; those forms retain +their own execution and error behavior. -**It is a word that scares people, for something small.** "Monad" here means the three answers in the -section above and nothing else: no laws to check, no `do` notation, no theory required. It is still a -word that will cost you a reader, and a piece of CGP writing is usually better off describing the -behaviour than naming it. +## What it costs -**A `?` in a function body is simpler, and usually right.** This pays when the *steps are chosen by -wiring*: when different contexts run different chains, or the chain is assembled from parts that do not -know each other. When the steps are fixed, write a function and use `?`. +A fixed sequence of fallible operations is usually clearer as a function using `?`. Monadic +composition is useful when contexts select different sequences or when reusable steps need a +continuation rule such as stopping at the first success. -**The type errors are among CGP's worst.** A stage whose output does not match the next stage's input -fails inside the monad machinery, in terms of `Output` associated types and monad traits, and the -message rarely names the stage. Building a long pipeline one stage at a time is the practical defence. +Pipeline errors can be difficult to locate. An incompatible stage can produce a trait-resolution +error involving associated output types and monad traits rather than identifying the stage directly. +Checking a short pipeline before adding more stages narrows the source of a mismatch. -**And nesting monads compounds that.** A stacked monad over a nested `Result` is expressive and is the -point at which a reader who has followed everything else will stop being able to predict what the -pipeline does. +Nested monads require readers to track each result layer separately. Use a transformer when those +layers express distinct decisions, and document which cases continue. The provider type alone may +not make that behavior obvious to a reader unfamiliar with the chosen transformer. ## Where to go next -[Handlers](./handlers.md) is the family this composes, and the page to read first if `PipeMonadic` above -looked like it came from nowhere. [Dispatching](./dispatching.md) is the other big user of the ok monad: -matching an enum variant is a chain of attempts where the first success ends it. +These pages cover the computations, applications, and traits behind the pipeline: -For the constructs, [monad providers](/docs/reference/providers/monad) carries `PipeMonadic`, -the three markers, and the per-step `BindOk` / `BindErr` forms. The four monad traits are the layer -defining what a monad is here: [`MonadicBind`](/docs/reference/traits/monad/monadic_bind), -[`ContainsValue`](/docs/reference/traits/monad/contains_value), -[`LiftValue`](/docs/reference/traits/monad/lift_value), and -[`MonadicTrans`](/docs/reference/traits/monad/monadic_trans). +- [Handlers](./handlers.md): The computation interfaces and ordinary composition. +- [Dispatching](./dispatching.md): Variant matching as a sequence of attempts. +- [Monad providers](/docs/reference/providers/monad): `PipeMonadic`, marker and transformer types, + and the per-step `BindOk` and `BindErr` providers. +- [`MonadicBind`](/docs/reference/traits/monad/monadic_bind), + [`ContainsValue`](/docs/reference/traits/monad/contains_value), + [`LiftValue`](/docs/reference/traits/monad/lift_value), and + [`MonadicTrans`](/docs/reference/traits/monad/monadic_trans): The composition and lifting interfaces. --- diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index 4f685756..965a8b29 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -5,18 +5,15 @@ sidebar_position: 9 # Namespaces -Reusable, inheritable wiring tables that keep a context's own table short as the number of -components grows. +Namespaces share wiring across contexts while leaving selected provider choices to each context. +They are useful when related contexts repeat large parts of the same table. This page explains +path-based routing, inherited bindings, and the rule that determines what can vary: a context can +fill an unbound path, but it cannot replace an inherited binding. -This page answers *how does wiring stay readable once there is a lot of it?* It shows what a table -looks like when it has outgrown its usefulness, the routing that fixes it, and the one rule that -decides how a namespace has to be designed, a rule most people discover from a compiler error. It -closes on when the lighter alternative is the better buy. +## Repeated wiring obscures the differences -## When a table stops being readable - -Wiring is meant to be the one place a context's choices are visible. That works while the table is -short, and stops working when two contexts want almost the same table: +Separate wiring tables can repeat choices that are intended to stay together. These fragments +assume the named components, providers, and context types are defined, with CGP's prelude imported: ```rust delegate_components! { @@ -36,18 +33,14 @@ delegate_components! { } ``` -Two entries out of three are duplicated, and nothing records that they are meant to stay the same. -Scale that to the thirty components a real application accumulates and the interesting difference, one -line, is buried in twenty-nine identical ones, which is the opposite of what the table was for. - -A **namespace** is a table lifted out of any one context and given a name, so that contexts can share -it. +Only the greeter differs, but each table repeats the shared farewell and announcer choices. +As the shared portion grows, maintaining the tables requires checking that those entries still +agree. A namespace gives the shared wiring a name that contexts can inherit. ## Lookups follow a path -The mechanism that makes sharing work is that a namespace resolves **paths** rather than bare -component names. A component registers itself at a path, and the path is a *route* rather than an -answer: +A namespace can register a route for a component while leaving the provider at its destination +unspecified. This example registers the greeter under an application path: ```rust cgp_namespace! { new AppNamespace {} } @@ -59,9 +52,8 @@ pub trait CanGreet { } ``` -`AppNamespace` now knows that anything asking for this component should look under -`@app.GreeterComponent`. It does not know what it will find there. A context joins the namespace and -supplies the answer at that path: +`AppNamespace` routes requests for the greeter through `@app.GreeterComponent`. A context joins the +namespace and supplies the provider at that path: ```rust delegate_components! { @@ -73,16 +65,18 @@ delegate_components! { } ``` -The `namespace` line makes everything `App` does not wire itself fall through to `AppNamespace`. -Routing through paths rather than flat keys also lets a whole group be redirected at once and makes -inheritance possible, since a path has structure a name does not. +The namespace supplies the route, and `App` supplies its destination binding. Rust resolves both +at compile time. The context's entry must not overlap an entry the namespace already binds; +joining a namespace does not give local entries priority over inherited ones. -On its own this is more machinery for the same result. The payoff arrives next. +Paths also let wiring redirect a group of related lookups. A shared prefix can route a subsystem +to another prefix, with the remaining path identifying its component and parameters. The +[`cgp_namespace!` reference](/docs/reference/macros/cgp_namespace) specifies that redirection syntax. -## Binding what is shared, leaving open what varies +## Bind shared choices and leave varying paths open -A namespace can also **bind** a path, supplying the provider itself rather than routing to it. This -turns it into a set of defaults: +A child namespace can inherit routes and bind the choices its contexts share. Assume `Farewell` +is registered in `AppNamespace` at `@app.FarewellComponent`, just as the greeter is registered above: ```rust cgp_namespace! { @@ -92,26 +86,21 @@ cgp_namespace! { } ``` -`AppDefaults` inherits the routing from `AppNamespace` and answers the farewell path itself. A context -joining it supplies only what is left: +`AppDefaults` supplies the farewell provider and leaves the greeter path unbound. Contexts joining +it choose only their greeter: ```rust delegate_components! { App { namespace AppDefaults; @app.GreeterComponent: GreetHello } } delegate_components! { TestApp { namespace AppDefaults; @app.GreeterComponent: GreetQuietly } } ``` -The two contexts now differ by exactly the thing that differs between them. Everything they share is -stated once, in a place that can be published by a library and adopted by applications that library has -never heard of. +Both contexts inherit `SayGoodbye`, and each states its own greeting choice. A library can publish +this shared configuration for applications to use without knowing those applications' context types. ## A bound entry cannot be overridden -Here is the rule, and it is worth learning from this page rather than from the error: -**once a namespace binds a key, no one downstream can rebind it. Only a path the namespace leaves open -is available to a context.** - -The natural thing to reach for, "the namespace sets this, I want something different", does not -compile: +A context or child namespace cannot rebind a key supplied by its parent namespace. The following +separate example deliberately binds the greeter directly, then tries to replace that binding: ```rust cgp_namespace! { @@ -131,32 +120,30 @@ delegate_components! { } ``` -The same rejection catches a child namespace redefining a key it inherits. The reason is coherence -rather than policy: joining a namespace generates an implementation covering *every* key the namespace -answers, and a specific entry for one of those keys overlaps it. The compiler cannot see that you meant -the specific one to win. +Rust rejects the overlapping implementations. Joining the namespace generates a forwarding +implementation for its keys, and the direct `GreeterComponent` entry would implement the same +lookup again. A child namespace redefining an inherited key has the same problem. -So a namespace is designed around the question *what varies?*, and this is the practical shape: -**bind what every context agrees on, and leave open what any context might need to differ on.** Where a -key varies, do not bind it in the shared namespace at all. Inherit and bind it per configuration -instead: +Keep configurable paths unbound in the shared base. Returning to the path-based example, each +configuration can bind the open greeter path in its own child namespace: ```rust cgp_namespace! { new ProductionDefaults: AppDefaults { @app.GreeterComponent: GreetHello } } cgp_namespace! { new TestDefaults: AppDefaults { @app.GreeterComponent: GreetQuietly } } ``` -Each child binds the open path rather than overriding a bound one, and a context becomes a single line -naming which configuration it is. +`ProductionDefaults` and `TestDefaults` both inherit the shared farewell choice and supply different +greeters. A context then joins the configuration it needs. Neither child replaces a parent binding. -## Namespaces are how CGP does presets +## Presets and per-type dispatch -There is no separate preset construct, and no `cgp_preset!` to look for. A preset, a curated bundle of -defaults you adopt and then adjust, is exactly the inherit-and-adjust behaviour above, so a namespace -*is* one. +A namespace can serve as a preset by grouping shared choices and exposing unbound paths for +configuration. Inheritance adds the remaining choices. The distinction between a fixed binding +and an open path determines which parts an application can customize. -The same machinery serves a much smaller case. Dispatching a single component per type, with the -`open` statement, is path routing applied to one component on one context: +The `open` statement uses related path routing for a smaller task: selecting a provider for each +type parameter of one component. This standalone fragment assumes an encoder component without a +namespace prefix: ```rust delegate_components! { @@ -168,48 +155,45 @@ delegate_components! { } ``` -`open` roots a route at the bare component name and puts the per-type entries in the context's own -table, with no shared namespace involved. It is the lightweight end of the same mechanism, and most -code uses it, which is why [bypassing coherence](./coherence.md) and -[dispatching](./dispatching.md) can use it without mentioning namespaces at all. - -The two do not combine for the same component: once a component is registered behind a namespace -prefix, `open` would root the route at the wrong place, and only the full prefixed path reaches its -entries. +`open` roots the route at `EncoderComponent`, and the context supplies entries beneath that root. +It does not require a shared namespace. Once a component is registered through a namespace prefix, +its entries must use that full prefixed route instead; opening the same component at its bare name +does not reach them. ## What it costs -**The design decision comes first, and it is hard to revise.** Which keys a namespace binds and which -it leaves open is fixed by the rule above, and changing your mind means changing the namespace, which -reaches every context that joined it. A bundle of wiring is easier to get wrong here than anywhere else -in CGP, because the mistake is not visible until a context wants to differ. +Binding a shared key commits every joining context to that choice. If a later context needs a +different provider, the namespace design must expose an unbound destination for it. Changing that +design can affect existing contexts, so decide which choices vary before publishing the shared table. -**It is another hop, and a less obvious one.** With an -[aggregate provider](./aggregate-providers.md) the context says which components come from the bundle. -With a namespace it says nothing, since everything not wired locally falls through, so answering -"where does this implementation come from?" means knowing the namespace and its parents. +Inherited wiring takes more work to trace. An [aggregate provider](./aggregate-providers.md) +lets the context list which components it delegates to a bundle. A namespace can supply those +routes through its registration and parent chain, so finding the selected provider may require +reading several tables. -**Paths are a second vocabulary.** `@app.GreeterComponent` is a type-level path, and it appears in -error messages spelled out at length. The toolchain resugars it for the classes it recognizes; a plain -`cargo check` still shows the raw form. +Path types can make diagnostics longer, and joining a namespace does not verify every inherited +component's dependencies. Use separate [`check_components!`](/docs/reference/macros/check_components) +assertions for the components a concrete context needs. -**And it pays only at scale.** For three components shared by two contexts, the duplication at the top -of this page is fine and a namespace is not worth its cost. The threshold is a table that has outgrown -reading, or a library publishing defaults for applications to adopt. +Small tables often remain clearer when written directly. Namespaces become useful when sharing a +configuration or grouping routes reduces enough repetition to justify the inheritance and path +structure. An aggregate provider offers a simpler way to share a named group of implementations. ## Where to go next -[Aggregate providers](./aggregate-providers.md) is the lighter way to package reusable wiring, and the -right one until a table is genuinely long. [Bypassing coherence](./coherence.md) and -[Dispatching](./dispatching.md) both use the `open` form of path routing without needing anything on -this page. - -For the constructs, [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) defines a namespace and -carries the `#[prefix(...)]` registration attribute, -[`delegate_components!`](/docs/reference/macros/delegate_components) carries the `namespace` and `open` -statements, [`RedirectLookup`](/docs/reference/providers/redirect_lookup) is the provider doing the -routing, and [`Path!`](/docs/reference/macros/path) is the path type underneath. -- [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch): a namespace as a shared prototype whose bound entries cannot be shadowed. +These pages cover simpler grouping and the namespace constructs: + +- [Aggregate providers](./aggregate-providers.md): Reusing selected groups of providers. +- [Bypassing coherence](./coherence.md) and [Dispatching](./dispatching.md): Provider selection + and per-type dispatch. +- [`cgp_namespace!`](/docs/reference/macros/cgp_namespace): Namespace definitions and inheritance. +- [`#[prefix]`](/docs/reference/attributes/prefix): Registering component routes. +- [`delegate_components!`](/docs/reference/macros/delegate_components): Joining a namespace and + using `open`. +- [`RedirectLookup`](/docs/reference/providers/redirect_lookup) and + [`Path!`](/docs/reference/macros/path): The routing provider and path types. +- [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch): Shared defaults and the + differences between namespace inheritance and runtime prototype lookup. --- diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index 5dfe9aa7..f188ef94 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -5,18 +5,15 @@ sidebar_position: 17 # Recovering `Send` bounds -Restoring the guarantee an async trait method drops, so the future it returns can be spawned on a -multi-threaded runtime. +A generic caller needs an explicit guarantee that an async method returns a `Send` future before +it can move that future between threads. CGP's `#[async_trait]` does not add that guarantee. +This page explains the trait-bound gap and a companion-trait workaround, including why it requires +forwarding implementations for concrete context and API pairs. -This page answers *why will my async CGP handler not spawn?* It is short, and it is about a gap in -stable Rust rather than about CGP. CGP just meets it sooner than most code does. It explains where the -guarantee goes, the bound that would fix it and does not exist yet, and the workaround. It closes on -what that workaround costs, which is repetition. +## What the async trait promises -## Where the guarantee goes - -An async method in a CGP trait is declared with `#[async_trait]`, which rewrites it into a method -returning `impl Future`: +CGP's `#[async_trait]` rewrites an async method into a method returning `impl Future`. This +component fragment assumes imports from `cgp::prelude::*`: ```rust #[cgp_component(ApiHandler)] @@ -28,24 +25,26 @@ pub trait CanHandleApi { } ``` -That rewrite is faithful and costs nothing: no boxing and no allocation. It also drops every auto-trait -bound. The returned future is `Send` when the concrete future the body produces happens to be, and a -caller working through the trait has no way to *require* it. +The generated return type is `impl Future`. The rewrite adds neither +boxing nor allocation, and it does not promise that the future implements `Send`. A concrete +implementation may return a `Send` future, but the generic bound `App: CanHandleApi` alone +does not establish that fact. -The opacity is the trade. Return-position `impl Trait` is zero-cost precisely because the caller does -not see the concrete type, and the future's `Send`-ness is part of what is hidden. +The missing guarantee comes from the trait signature. Opaque return types can explicitly carry +`+ Send`; this particular signature leaves that requirement open so implementations can also use +futures that are not sendable. -## Why that matters, and what you cannot write +## Why spawning needs a stronger bound -It matters the moment the future is spawned. A work-stealing runtime, the default Tokio runtime an Axum -server runs on, may move a task between threads while it is suspended, so every future it drives must -be `Send`. A generic handler awaiting `handle_api` produces a task that is `Send` only if that future -is. +Spawning APIs may require both the future and its output to be sendable. For example, +[`tokio::spawn`](https://docs.rs/tokio/latest/tokio/task/fn.spawn.html) requires both to be +`Send + 'static`. An async task that awaits `handle_api` needs to satisfy those bounds as a whole. -For a *concrete* context the compiler checks this itself. For a generic one it cannot, because the fact -in question is the one the trait refuses to expose. +A generic caller cannot infer the awaited future's `Send` implementation from +`App: CanHandleApi`. Giving `App` itself a `Send` bound does not constrain every future its +methods return. -The bound you want has a name and is not stable: +Return Type Notation would let a caller state the missing requirement directly: ```rust // Not available on stable Rust: @@ -56,14 +55,15 @@ where } ``` -Return Type Notation, `handle_api(..): Send`, says exactly the right thing: whatever arguments the -method is called with, its future is `Send`. It is not stabilized, so this cannot be written in -production code today. +The `handle_api(..): Send` clause constrains the method's return type. The function body is omitted +here to isolate that bound. Return Type Notation is an +[unstable Rust feature](https://doc.rust-lang.org/unstable-book/language-features/return-type-notation.html), +so stable code needs another way to expose the guarantee. -## Recovering it with a second trait +## A companion trait with a sendable future -The workaround is to declare an ordinary trait whose method spells the bound out in its own return type, -where the notation is not needed: +A companion trait can state `+ Send` directly on its method's return type. This declaration also +requires a sendable response and a `Send + Sync` context, and assumes `core::future::Future` is imported: ```rust pub trait CanHandleApiSend: CanHandleApi + Send + Sync @@ -75,29 +75,32 @@ where } ``` -`CanHandleApiSend` is **not a component**. It adds nothing to any wiring table and has no providers; it -exists to carry a stronger signature. It inherits the whole interface from `CanHandleApi` as a -supertrait, additionally requires the response and the context to be `Send`, and writes `+ Send` on the -future directly. - -A spawning caller can now say what it needs, in one bound with no missing notation: +`CanHandleApiSend` is an ordinary trait that adds a stronger method signature. It inherits the +original response type and needs neither a component key nor provider wiring. A generic caller can +require it with these bounds: ```rust where App: CanHandleApiSend, + App::Response: Send, ``` -## Why the implementation cannot be generic +The caller must use `handle_api_send` to obtain the advertised future. The companion trait does not +change the signature of `handle_api`. Its response bound is repeated here because a bound on an +associated type in a trait's `where` clause must also be established at the generic use site. + +This trait addresses the future's sendability, not every condition for spawning. The surrounding +task must still satisfy the executor's lifetime and output requirements. A future borrowing a local +`app` is not automatically `'static` merely because it implements `Send`. -The obvious next step is one blanket implementation covering every context that already handles the API. -It does not compile, and the reason is worth following, because it is the same gap in another form. +## Why forwarding implementations need concrete types -Such an impl would wrap `self.handle_api(..)` in an `async` block, and that block is `Send` only if the -future it awaits is. For a generic `App` and `Api` the awaited future is an opaque `impl Future` whose -auto-traits are unknown, so the impl cannot prove its own `+ Send` return type. A generic blanket impl -*is* Return Type Notation, and it is blocked for the same reason. +A blanket forwarding implementation cannot prove `Send` from the original trait bound alone. +Its body would await `self.handle_api(api)`, whose future the original signature does not guarantee +to be sendable. Wrapping that call in another async block preserves the same missing requirement. -Dropping to a concrete context and a concrete API closes it: +A concrete context and API let Rust check the actual selected implementation. In this fragment, +`MockApp` is wired to a `QueryBalance` provider whose response is `u64` and whose future is sendable: ```rust impl CanHandleApiSend for MockApp { @@ -107,38 +110,34 @@ impl CanHandleApiSend for MockApp { } ``` -Now `Self` is a fixed type and `Api` is a fixed marker, so the call resolves through the wiring to a -concrete provider producing a concrete future, and the compiler computes that future's auto-traits and -finds it `Send`. No annotation is needed, because the compiler infers `Send` structurally for a known -type. - -Each of these impls is mechanical: forward, and await. Each is also a *proof*, accepted only because at -this instantiation the future really is `Send`. +The compiler resolves this call through the concrete wiring and checks that the returned future +satisfies the companion trait's `Send` promise. A provider that holds a non-sendable value across +an await can still make this implementation fail. The forwarding method verifies the property; +it does not make an otherwise non-sendable future safe to transfer. ## What it costs -**One impl per context per API.** That is the price of the missing notation, and it is the whole cost: -where RTN would have allowed a single generic impl, this needs one for every pair. A service with eight -endpoints and two contexts writes sixteen forwarding bodies. - -**It is boilerplate that cannot be abstracted away.** The abstraction that would remove it is the -generic blanket impl, and that does not compile. A macro could generate the impls, but they would still -be there. +This forwarding pattern needs an implementation for each context and API pair that exposes the +stronger interface. A macro can generate the repetitive bodies, but each generated implementation +still needs to satisfy the bound independently. -**And it is a second trait to keep in step.** Adding a method to the original trait means adding it here -too, and nothing enforces that the two stay aligned beyond the supertrait. +The companion trait adds an interface to maintain. Methods that need the stronger guarantee need +corresponding signatures and forwarding bodies. Other methods can remain available through the +original supertrait without being duplicated. -The one consolation is that the whole thing disappears when Return Type Notation stabilizes. This is a -workaround with a known expiry, not a design. +A companion trait is useful when the base interface must support both sendable and non-sendable +futures. If every implementation must return a `Send` future, an explicit `impl Future + Send` +return type on the base trait can express that requirement directly. If the task can stay on a +local executor, the additional guarantee may be unnecessary. ## Where to go next -[Handlers](./handlers.md) is the family whose futures most often need this, since it is where CGP's -async I/O lives. [Consumer and provider traits](./consumer-and-provider-traits.md) explains the wiring -the concrete impl forwards through, which turns the resolved future into a concrete, checkable type. +These pages explain the async components and the wiring checked by a concrete forwarding impl: -For the constructs, [`#[async_trait]`](/docs/reference/macros/async_trait) is the rewrite that drops the -bound, and its own page records the same gap from the macro's side. +- [Handlers](./handlers.md): CGP's async computation interfaces. +- [Consumer and provider traits](./consumer-and-provider-traits.md): How a context call reaches + the selected provider. +- [`#[async_trait]`](/docs/reference/macros/async_trait): The unboxed future rewrite and its bounds. --- diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index 00f9c870..3953ce6d 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -5,20 +5,17 @@ sidebar_position: 16 # Type-level DSLs -Encoding a small language as Rust types and interpreting it during compilation, with no interpreter -left at runtime. +A type-level domain-specific language represents a program as Rust types and uses CGP wiring to +select implementations for its operations. The compiler checks and resolves the program's structure; +the selected operations run when called. This page develops a small arithmetic language, explains +how its syntax and interpretation can vary independently, and identifies the limits of the approach. +It assumes familiarity with [handlers](./handlers.md). -This page answers *what happens when the `Code` tag carries a whole program?* It is the furthest thing -CGP's pieces are put to, and it assumes [handlers](./handlers.md). It shows a small language built from -types, why separating its syntax from its meaning is the point, and how a third party extends it. It -closes on the boundary: the programs this cannot express. +## A program represented as a type -## A program that is a type - -The [handler family](./handlers.md) threads a phantom `Code` tag so one context can host many -computations. Nothing says the tag has to be small. - -Make it the program: +The handler family's `Code` parameter can describe a whole program. Each syntax form becomes a +marker type, and its parameters describe the program's structure. These fragments assume +`PhantomData` and CGP's prelude are imported: ```rust pub struct Literal; @@ -26,45 +23,46 @@ pub struct Add(pub PhantomData<(Left, Right)>); pub struct Multiply(pub PhantomData<(Left, Right)>); ``` -Three structs with no data and no methods. They exist to be *named in a type*, and nesting them writes a -program: +Nesting the markers represents a compound expression: ```rust type Program = Multiply, Literal<3>>, Literal<4>>; ``` -That is `(2 + 3) * 4` as a type. It is the language's **abstract syntax**, and this is the whole idea: -it says nothing at all about what any of it means. +`Program` represents `(2 + 3) * 4`. The marker types form the language's **abstract syntax**: +they describe the expression without implementing its evaluation. An evaluator can compute its +value, while a different interpreter could format the same expression as text. -For a real language the fragments carry more: a -[`Product!`](/docs/reference/macros/product) list for a pipeline of stages, a -[`Symbol!`](/docs/reference/macros/symbol) where a string literal would go, since a `&str` value cannot -appear where only types are allowed. +Larger languages can use type-level collections and strings within their syntax. +[`Product!`](/docs/reference/macros/product) can hold a pipeline's stages, and +[`Symbol!`](/docs/reference/macros/symbol) can represent a string in a type position. +These describe the fixed program; handlers can still receive runtime values as their inputs. -## The meaning is a set of providers +## Providers give syntax its behavior -Meaning arrives separately, one provider per fragment, each matching its own shape of `Code`: +A provider implements one syntax form and asks the context to interpret its subexpressions. +This addition provider assumes the `Computer` provider trait is imported from `cgp::extra::handler`: ```rust -#[cgp_new_provider] -impl Computer, ()> for EvalAdd -where - Context: CanCompute + CanCompute, -{ +#[cgp_impl(new EvalAdd)] +#[uses(CanCompute, CanCompute)] +impl Computer, ()> { type Output = u64; - fn compute(context: &Context, _code: PhantomData>, _input: ()) -> u64 { - context.compute(PhantomData::, ()) + context.compute(PhantomData::, ()) + fn compute(&self, _code: PhantomData>, _input: ()) -> u64 { + self.compute(PhantomData::, ()) + self.compute(PhantomData::, ()) } } ``` -`EvalAdd` interprets *any* addition, whatever its operands, and it evaluates them by asking the context. -Asking the context, rather than evaluating the operands itself, both drives the recursion and keeps the -provider from knowing the rest of the language. Its requirements say only "the context can evaluate my -operands". +`EvalAdd` handles any `Add` whose operands the context can compute as `u64`. +Its requirements describe those computations without naming the providers that perform them. +Calling the context for each operand lets the addition provider work with syntax introduced by +other crates. -The context then assembles the language, one row per fragment: +The context assembles an interpreter by selecting a provider for each syntax form. This fragment +assumes an `Interpreter` context, matching `EvalLiteral` and `EvalMultiply` providers, and an import +of `ComputerComponent`: ```rust delegate_components! { @@ -78,74 +76,84 @@ delegate_components! { } ``` -And running a program is one call: +Each generic entry covers a family of expressions. The addition entry applies to every +`Add` with unit input, subject to the selected provider's requirements. Running the +program then uses the ordinary consumer method: ```rust Interpreter.compute(PhantomData::, ()) // 20 ``` -Because the keys are types with structure, a single row captures a whole family of programs, every -`Add<_, _>` there will ever be. A value-level lookup table cannot do that. +## What the compiler resolves -## What the separation buys +Rust resolves provider selection recursively through the program type. For `Program`, it checks +that multiplication can compute its operands, that addition can compute its operands, and that +each literal has an implementation. The resulting calls use static dispatch without a runtime +syntax-tree lookup or interpreter dispatch loop. -There is no parser, no syntax tree walked at run time, and no dispatch loop. **Type checking the call -is the interpretation**: the compiler resolves the wiring recursively through the program's structure, -and only the arithmetic is left in the binary. +The computation itself remains ordinary Rust execution. `compute` is not a `const fn`; type +checking does not evaluate its arithmetic. An optimizer may fold this constant example, but the +DSL does not guarantee that. A provider performing I/O or processing runtime input does that work +when the program runs. -The more interesting consequence is that syntax and meaning vary independently. +## Syntax and interpretation can vary independently -**One program, several meanings.** A second context wiring the same fragments to different providers -interprets the same program differently: evaluate it, pretty-print it, cost it, or run it against a test -double. Nothing in the program changes, because the program never said what it meant. +Different contexts can assign different meanings to the same program type. One context may +evaluate arithmetic while another pretty-prints it or estimates its cost. Each interpretation +needs providers with mutually compatible input and output types; the syntax stays unchanged. -**One meaning, extended syntax.** A crate that does not own the language defines a new fragment and a -provider for it, and a context that wants both wires both. The base language is not patched, forked, or -even recompiled. The extension is a row. That is the [expression problem](./extensible-variants.md) -answered on the syntax side, and it is why a DSL built this way can have third-party dialects. +An independent crate can extend the syntax by defining another marker and its provider. +A context includes that form by adding wiring, without editing the base language's source. +Existing providers such as `EvalAdd` can accept the new form as an operand when it satisfies their +computation requirements. This addresses the syntax-extension side of the +[expression problem](./extensible-variants.md). -At scale the rows themselves become a [namespace](./namespaces.md), so a context joins a language rather -than listing its fragments, and an extension is a namespace inheriting the base. +Namespaces package a language's shared wiring for reuse. A child namespace can add entries for +new forms while inheriting the base language. Alternative interpretations must still respect the +[namespace rule](./namespaces.md#a-bound-entry-cannot-be-overridden): an inherited bound entry +cannot be replaced, so paths that need different providers must remain open in the shared base. -## A readable surface is optional +## An optional surface syntax -A procedural macro can sit on top, turning an infix pipe into a nested type or a string literal into a -`Symbol!`. Such a macro does shallow token rewriting and emits the same types a programmer could write -by hand. +A procedural macro can make programs easier to write by translating syntax into the same marker +types. For example, it might turn a pipeline expression into nested types or a string literal into +`Symbol!`. Interpretation remains in the providers, so handwritten types and macro-generated types +use the same implementations. -Keeping it that thin is deliberate: because the macro carries no meaning, the language stays fully -usable and fully extensible without it, and the grammar can evolve without touching either the macro or -the interpreters. +Separating syntax translation from execution keeps provider changes independent of the macro. +A generic surface syntax may also accept new fragments without a macro change. New grammatical +forms can still require changes to the parser or macro; type-level representation alone does not +make every syntax extension automatic. ## What it costs -**The program must be known at compile time.** This is the boundary, and it is absolute. A script read -from a file, a pipeline configured at startup, or a user-supplied expression cannot be a type. -If programs arrive at run time you need a runtime interpreter, and this technique is not one. +The program's type structure must be known at compile time. Runtime inputs and branches inside +providers are possible, but an arbitrary script loaded from a file cannot become a new Rust type +inside the running binary. Such a script needs a runtime interpreter or a separate compilation step. -**The diagnostics are the worst CGP produces.** A malformed program is a trait-resolution failure over a -deeply nested type, reported in terms of the whole program rather than the fragment at fault. Checks -localize it and the toolchain reshapes what it recognizes; a badly nested program is still hard reading. +Nested program types can produce long trait-resolution errors. Missing wiring or incompatible +operand outputs may appear through several layers of provider bounds. Checking smaller expressions +before combining them helps locate the mismatch. -**Compile times go up.** Every fragment of every program is resolution work, and a large program -instantiated several ways is where CGP's compile-time cost is most visible. - -**And it is the most advanced thing here.** Everything else in this section is worth reaching for -routinely. This is worth reaching for when a language is genuinely the right shape for a problem, such -as build pipelines, protocol descriptions, or shell-like scripting, and when the programs are fixed when -the binary is. +Compilation must resolve the bounds and generate code for the concrete programs used. Large +programs and multiple interpretations can increase compile time and generated code size. The +tradeoff is most useful when reusable, extensible program descriptions justify those costs, such +as fixed build pipelines or protocol descriptions. Direct Rust functions are simpler for a small +set of fixed computations that does not need a language of its own. ## Where to go next -[Handlers](./handlers.md) is the family this rests on, and the page to read first. -[Dispatching](./dispatching.md) is the same routing applied to data rather than to programs, and -[namespaces](./namespaces.md) is how a language is packaged once it outgrows a table. - -For the constructs, [`Computer`](/docs/reference/components/handler/computer) and -[`Handler`](/docs/reference/components/handler/handler) are the interpreter interfaces, -[`delegate_components!`](/docs/reference/macros/delegate_components) carries the `open` statement and -generic path keys, and [`Product!`](/docs/reference/macros/product) and -[`Symbol!`](/docs/reference/macros/symbol) are how a real language carries lists and strings. +These pages explain the constructs used to build and package the language: + +- [Handlers](./handlers.md): Computations parameterized by `Code` and input. +- [Dispatching](./dispatching.md): Type-directed selection applied to data. +- [Namespaces](./namespaces.md): Sharing and extending interpreter wiring. +- [`Computer`](/docs/reference/components/handler/computer) and + [`Handler`](/docs/reference/components/handler/handler): Synchronous and async fallible + interpreter interfaces. +- [`delegate_components!`](/docs/reference/macros/delegate_components): `open` and generic path keys. +- [`Product!`](/docs/reference/macros/product) and [`Symbol!`](/docs/reference/macros/symbol): + Type-level lists and strings. --- diff --git a/example-code/tests/concepts/type_level_dsls.rs b/example-code/tests/concepts/type_level_dsls.rs index 606d3b16..2cf50721 100644 --- a/example-code/tests/concepts/type_level_dsls.rs +++ b/example-code/tests/concepts/type_level_dsls.rs @@ -26,15 +26,13 @@ impl Computer, ()> for EvalLiteral { } } -#[cgp_new_provider] -impl Computer, ()> for EvalAdd -where - Context: CanCompute + CanCompute, -{ +#[cgp_impl(new EvalAdd)] +#[uses(CanCompute, CanCompute)] +impl Computer, ()> { type Output = u64; - fn compute(context: &Context, _code: PhantomData>, _input: ()) -> u64 { - context.compute(PhantomData::, ()) + context.compute(PhantomData::, ()) + fn compute(&self, _code: PhantomData>, _input: ()) -> u64 { + self.compute(PhantomData::, ()) + self.compute(PhantomData::, ()) } } @@ -80,9 +78,9 @@ mod check_interpreter { } } -/// ## Running a program is type checking it +/// The program structure selects providers statically; calling them evaluates the expression. #[test] -fn the_program_is_a_type_and_the_answer_is_computed_at_compile_time() { +fn the_program_type_selects_the_providers_that_compute_the_answer() { // (2 + 3) * 4 type Program = Multiply, Literal<3>>, Literal<4>>; From 95b49efba30df893f75618ccf15c652ed8c9258f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 20 Sep 2026 12:49:46 +0000 Subject: [PATCH 082/516] Revise comparison docs with Astra --- docs/comparisons/algebraic-effects.md | 362 ++++++++------- docs/comparisons/capabilities.md | 413 +++++++++--------- docs/comparisons/dependency-injection.md | 244 +++++------ docs/comparisons/dynamic-dispatch.md | 341 +++++++-------- docs/comparisons/implicit-parameters.md | 305 +++++++------ docs/comparisons/index.md | 37 +- docs/comparisons/ml-modules.md | 348 ++++++++------- docs/comparisons/policy-based-design.md | 383 ++++++++-------- .../tests/comparisons/algebraic_effects.rs | 8 +- .../tests/comparisons/capabilities.rs | 2 +- .../tests/comparisons/dependency_injection.rs | 6 +- .../tests/comparisons/dynamic_dispatch.rs | 8 +- .../tests/comparisons/implicit_parameters.rs | 6 +- example-code/tests/comparisons/ml_modules.rs | 2 +- .../tests/comparisons/policy_based_design.rs | 2 +- 15 files changed, 1227 insertions(+), 1240 deletions(-) diff --git a/docs/comparisons/algebraic-effects.md b/docs/comparisons/algebraic-effects.md index 5e5ed0f0..8c144022 100644 --- a/docs/comparisons/algebraic-effects.md +++ b/docs/comparisons/algebraic-effects.md @@ -1,81 +1,78 @@ --- sidebar_label: 'Algebraic effects' sidebar_position: 6 -description: 'CGP read against the effect handlers of Koka, OCaml 5, Flix, and Eff: the exactly-once fragment it shares and the continuation power it does not.' +description: 'Compare CGP providers with algebraic effect handlers: shared operation interfaces, static selection, and the continuation boundary.' --- # Algebraic effects and handlers -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows -algebraic effects and handlers from Koka, OCaml 5, Flix, or Eff. CGP shares the split between an -operation and its interpretation, and the idea of choosing the interpretation from the surroundings, -but it keeps only the fragment in which the continuation is used exactly once and in place. The -literature identifies that fragment as dynamic binding, and CGP resolves it statically per context -rather than dynamically down a call stack. The page covers the correspondence, the boundary, where -effect handlers remain the only tool, and what to expect that differs. +CGP separates operations from their implementations, much as algebraic effects separate operations +from handlers, but CGP does not capture continuations. It is a language extension for Rust, with +pluggable trait implementations at compile-time, implemented as a library on stable Rust whose +consumer traits are ordinary Rust traits; the [Introduction](/docs/) covers the basics. For readers +familiar with Koka, OCaml 5, Flix, or Eff, this page develops the correspondence with handlers that +resume in place, its limits, and the costs of each approach. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. In most CGP code it is a type you define to stand for an application, and it plays the part -of the dynamic scope in which handlers are installed. +A **context** is the type a CGP method runs on, supplying data through fields and implementations +through wiring. In these examples it represents an application and selects the implementations its +operations use. This plays part of a handler environment's role, but the choices are attached to a +Rust type rather than installed on the runtime call stack. | In an effect system | In CGP | | --- | --- | -| An effect signature | A **component**: one trait with many possible implementations | -| An operation | A method of that trait | -| A handler | A **provider**: a named implementation, always tail-resumptive | -| Installing a handler with `with` or `run ... with handler` | **Wiring** the provider on a context | -| The effect row a function performs | The provider's **impl-side dependencies**, declared with `#[uses]` | -| A type error for an unhandled effect | A `check_components!` failure at the wiring site | -| The continuation | Nothing: a provider returns exactly once | +| An effect signature | A **component**, with a consumer trait declaring operations | +| An operation | A method of the consumer trait | +| A handler interpreting an operation | A **provider** implementing the corresponding method | +| Installing a handler | **Wiring** a provider on a context | +| Requirements recorded in an effect row | **Impl-side dependencies**, with a narrower guarantee than effect typing | +| Checking that required operations have handlers | `check_components!` verifies declared provider dependencies | +| A captured continuation | Without a direct counterpart; provider methods use ordinary Rust control flow | ## The idea, briefly -Algebraic effects let code perform an effect without fixing how the effect is carried out. A function -that reads configuration, logs, throws, or suspends normally commits to a concrete mechanism, and -that commitment leaks into its type. With algebraic effects the function *performs an operation* -named by an abstract effect, and a *handler* installed up the call stack gives the operation its -meaning, so the same code runs against a real logger, a test collector, or a no-op. +Algebraic effects let a computation request an operation without choosing its implementation. +A handler supplies the operation's meaning and can control how the computation continues. This lets +the same computation use different implementations of configuration access, logging, state, or +more general control flow. ### Operations, handlers, and the continuation -An *effect* is a signature of *operations*, and a computation produces the effect by performing one -of them. Plotkin and Power founded the idea, and the account is *algebraic* because each effect came -with an equational theory whose free model induces the monad for that effect -([Plotkin & Pretnar, *Handling Algebraic Effects*](https://homepages.inf.ed.ac.uk/gdp/publications/handling-algebraic-effects.pdf)). -A *handler* interprets the operations, and its defining power is that it receives the *continuation*: -the suspended rest of the computation from the point where the operation was performed -([Pretnar, *An Introduction to Algebraic Effects and Handlers*](https://www.eff-lang.org/handlers-tutorial.pdf)). -An exception handler can only abandon the computation; an effect handler can resume it. +An effect signature declares operations, while a handler interprets them. In the algebraic account, +equations describe relationships between operations; the resulting theory connects effects to +monads. [Plotkin and Pretnar](https://homepages.inf.ed.ac.uk/gdp/publications/handling-algebraic-effects.pdf) +develop this account and the interpretation of operations by handlers. -How many times a handler invokes the continuation determines the effect it realizes, and the three -cases mark where CGP can and cannot follow: +A general effect handler receives the continuation: the suspended remainder of the computation. +It can decide whether and when to resume that computation, subject to the language's restrictions. +[Pretnar's tutorial](https://www.eff-lang.org/handlers-tutorial.pdf) explains the main possibilities: -- **Zero times.** The handler discards the continuation. This is exception behavior. -- **Once.** The handler resumes with a result. This is the ordinary case: reading state, dynamic - binding, logging, any call that yields a value and lets the caller carry on. -- **Many times.** The handler resumes more than once. This is nondeterminism, generators, and - cooperative scheduling, and it cannot be expressed as an ordinary function return. +- **Discard it:** abort the suspended computation, as an exception handler does. +- **Resume it once:** continue with a supplied result, either immediately or after suspension. +- **Resume it more than once:** explore alternatives, as in nondeterministic search. + +Resuming once does not necessarily mean resuming in place. A scheduler can store a continuation and +resume it later, and a generator can suspend before its next resumption. CGP's closest correspondence +is narrower: an operation completes and its caller continues through an ordinary return. ### Effect typing -Languages differ sharply in whether a computation's type records the effects it may perform. Koka -types effects as a *row*, so `` in a signature means the function may throw and diverge -([Leijen, *Algebraic Effects for Functional Programming*](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/08/algeff-tr-2016-v2.pdf)); -the [row polymorphism](./row-polymorphism.md) page covers the row machinery. Flix types effects as a -set and uses the result for purity reflection -([Madsen et al., *Programming with Purity Reflection*](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2023.18)). -Eff and OCaml 5 track no effects in types: the OCaml manual states that "the compiler does not -statically ensure that all the effects performed by the program are handled", and an unhandled effect -raises `Effect.Unhandled` at run time ([OCaml manual](https://ocaml.org/manual/5.5/effects.html)). +Effect typing records which effects a computation may perform, but languages differ in whether +they provide it. Koka uses effect rows; Flix uses effect sets and supports purity reflection. +These systems can check whether a computation's effects are handled. See +[Leijen's Koka account](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/08/algeff-tr-2016-v2.pdf) +and [Madsen et al. on Flix](https://drops.dagstuhl.de/entities/document/10.4230/LIPIcs.ECOOP.2023.18). + +OCaml 5 and Eff provide handlers without statically tracking all performed effects in function +types. In OCaml, an unhandled effect raises `Effect.Unhandled` at runtime. The +[OCaml manual](https://ocaml.org/manual/5.5/effects.html) states this limit, while the +[row polymorphism](./row-polymorphism.md) comparison explains the row machinery used by Koka. ### The same effect in three languages -In **Koka**, an operation is declared `ctl` (may resume any number of times), `fun` (resumes exactly -once in place), or `val`. A handler is installed with `with`: +Koka distinguishes operations by their control-flow behavior. A `fun` operation resumes once in +place; `ctl` allows general resumption. This `ask` handler supplies a value: ```koka effect fun ask() : int // one `fun` operation; the effect is also named `ask` @@ -88,10 +85,8 @@ fun main() : console () println( add-twice() ) // 42 ``` -The Koka book describes `with fun ask() 21` as a "statically typed dynamic binding" and notes that a -`fun` operation "behaves just like a regular function without changing the control-flow" -([Koka book](https://koka-lang.github.io/koka/doc/book.html#sec-opfun)). A `ctl` operation is the -multi-shot form; the book's `choice` handler resumes twice to collect every outcome: +A Koka `ctl` handler can resume more than once. The following handler explores both results of a +Boolean choice and concatenates the outcomes: ```koka effect ctl choice() : bool @@ -103,9 +98,12 @@ fun choice-all(action : () -> a) : e list action() ``` -In **OCaml 5**, an effect extends the type `Effect.t`, is performed with `perform`, and is handled -with a `match` whose `effect` cases bind the continuation `k`. The `effect` pattern syntax arrived in -OCaml 5.3; earlier code used `Effect.Deep.try_with`: +The [Koka book](https://koka-lang.github.io/koka/doc/book.html#sec-opfun) explains why `fun` operations +behave like ordinary calls and how `ctl` provides additional control over resumption. + +OCaml 5 declares operations by extending `Effect.t` and performs them with `perform`. An effect +pattern binds a continuation that the handler can resume. This syntax requires OCaml 5.3 or later; +earlier code uses functions such as `Effect.Deep.try_with`: ```ocaml open Effect @@ -123,11 +121,13 @@ let () = print_int result (* 42 *) ``` -OCaml's continuations are one-shot: "every captured continuation must be resumed either with a -`continue` or `discontinue` exactly once" ([OCaml manual](https://ocaml.org/manual/5.5/effects.html)). +OCaml continuations are one-shot: they cannot be resumed repeatedly to explore alternatives. +They can still be suspended and resumed later, which is sufficient for uses such as cooperative +scheduling. The [manual](https://ocaml.org/manual/5.5/effects.html) also explains the need to resume +or discontinue a captured continuation to release its resources. -In **Flix**, an effect is declared with `eff`, appears in a function type after a backslash, and is -handled with `run ... with handler`: +Flix declares an effect with `eff` and records it after a backslash in a function's type. A handler +supplies the result and resumes the continuation: ```flix eff Ask { @@ -146,33 +146,35 @@ def main(): Unit \ IO = println(result) // 42 ``` -`\ Ask` is part of `addTwice`'s type, and `main` must discharge it -([Flix documentation](https://doc.flix.dev/effects-and-handlers.html)). +`addTwice` performs `Ask`, while the handler in `main` handles that effect. Flix supports multiple +resumptions as well as the single resumption shown here. See the +[Flix documentation](https://doc.flix.dev/effects-and-handlers.html). ### The fragment CGP corresponds to -A handler that resumes the continuation exactly once, in tail position, is dynamic binding. The -literature names its canonical example outright: **the canonical tail-resumptive handler is dynamic -binding** ([Xie et al., *Effect Handlers, Evidently*](https://www.microsoft.com/en-us/research/wp-content/uploads/2020/07/evidently-5f0b7dbc1a998.pdf)). -Such a handler never needs to capture the continuation, so a compiler can run the operation in place -and replace the dynamic search for a handler with a constant-offset lookup into an *evidence vector* -passed down like a dictionary ([Xie & Leijen, *Generalized Evidence Passing*](https://xnning.github.io/papers/multip.pdf)). -The efficient compilation of the exactly-once fragment *is* dictionary passing, and that is the -fragment CGP occupies directly, with no dynamic search underneath. Effekt and Scala's capture checking -describe the same fragment as *effects as capabilities*; the [capabilities](./capabilities.md) page -places CGP against that reading. +Tail-resumptive handlers provide the closest comparison to CGP. They resume exactly once in tail +position, so the operation can run in place without capturing the rest of the computation. +[Xie et al.](https://www.microsoft.com/en-us/research/wp-content/uploads/2020/07/evidently-5f0b7dbc1a998.pdf) +identify dynamic binding as the canonical example. Evidence-passing implementations can make +handler selection efficient by passing evidence of the selected handler, as developed in +[Generalized Evidence Passing](https://xnning.github.io/papers/multip.pdf). + +CGP uses a related separation of operation and implementation, with selection resolved through +Rust traits. This is a comparison of programming structure, not a claim that CGP implements the +same effect calculus or dynamic scoping rules. The [capabilities](./capabilities.md) page explores +the related view of computations declaring what they require from an environment. ## How CGP expresses it -CGP reproduces the operations-and-handlers structure with its consumer and provider split, and every -CGP "handler" is an ordinary function that returns once. The correspondence is exact for the -tail-resumptive case and stops wherever an effect would reach for the continuation. The contexts below -are **environmental contexts**: the `App` that installs a `Loader` or a `Greeter` stands for an -application, as a handler's dynamic scope does, and every component shown is self-targeted. +CGP represents an operation with a consumer trait and its implementation with a provider. +The examples use environmental contexts: types representing applications and supplying the +implementations for self-targeted components. Supporting declarations and imports are omitted +where they do not affect the comparison. -### Components are effect signatures; providers are tail-resumptive handlers +### Components declare operations; providers implement them -Declaring a component names an operation without giving it meaning, and a provider interprets it: +A component declares an operation independently of its implementation. A context then selects a +provider through wiring: ```rust #[cgp_component(Greeter)] @@ -190,16 +192,16 @@ impl Greeter { delegate_components! { App { GreeterComponent: GreetHello } } ``` -`CanGreet` is the effect signature, `greet` the operation, `GreetHello` the handler, and the wiring -line its installation. The provider's body receives no continuation and cannot choose whether to -resume: it computes a value and returns, and the caller resumes in place, exactly once. In Koka's -terms every CGP provider is a `fun` operation and never a `ctl` one. +`CanGreet` declares `greet`, `GreetHello` implements it, and `App` selects that implementation. +The provider receives the context rather than a continuation. If the method returns normally, +its caller continues once at the call site. Like any Rust function, the method can also panic or +diverge; CGP does not enforce termination or an exactly-once return guarantee. -### Reading from the context is dynamic binding, exactly +### Context fields supply an environment value -Koka's `with fun ask() 21` installs a tail-resumptive handler that supplies a value to deeply nested -code without threading it through every call. CGP's [implicit arguments](/docs/concepts/implicit-arguments) -do the same by reading a field from the context that every provider receives as `self`: +CGP's [implicit arguments](/docs/concepts/implicit-arguments) let nested implementations read +values from a shared context. This resembles a reader effect whose handler supplies an environment +value: ```rust #[cgp_fn] @@ -208,17 +210,16 @@ pub fn greet(&self, #[implicit] name: &str) -> String { } ``` -The context supplies `name`, not the caller, as the enclosing `ask` handler supplies Koka's `ask()`. -The equivalence is exact rather than an analogy: the reader effect is the canonical tail-resumptive -handler, and reading a context field is CGP's whole realization of it. The two part ways on how the -value is found. Koka searches the dynamic handler stack; CGP reads a field of a statically known -context. The [implicit parameters](./implicit-parameters.md) page covers the same pattern from -Scala's side. +The `name` argument comes from the context's field. Koka's `ask` example supplies a value through +an installed handler; CGP supplies it through `self`. The similarity is that intermediate callers +do not forward the individual value. The difference is selection: a CGP field dependency is +resolved against a context type, without dynamic handler installation. The +[implicit parameters](./implicit-parameters.md) comparison develops that distinction. -### Raising an error looks like `raise` but passes a value, not control +### Raising an error constructs a value -CGP's error handling shows the boundary most sharply. `CanRaiseError` reads like the -`raise` operation, and a provider raises without knowing the concrete error type: +CGP's error components choose how to construct an error, while Rust's `Result` controls propagation. +This provider can produce an error without fixing the context's concrete error type: ```rust #[cgp_component(Loader)] @@ -240,8 +241,7 @@ impl Loader { } ``` -The raise components dispatch per source type, so a context routes each source error to a different -strategy, which reads like installing one exception handler per exception type: +The context chooses both the error type and the provider used for each source error type: ```rust delegate_components! { @@ -256,19 +256,17 @@ delegate_components! { } ``` -The resemblance stops at *selection*. An effect `raise` is the zero-resume handler: it abandons the -continuation and unwinds to the handler. CGP's `raise_error` unwinds nothing. It constructs and -returns a value of the abstract `Error` type, and the abort is Rust's own `return` or `?`, outside -the wiring. CGP selects the interpretation of the error and leaves the control flow to `Result`. The -[Modular error handling](/docs/concepts/modular-error-handling) page develops the construct. +`Self::raise_error(...)` returns an error value; the surrounding `return Err(...)` exits `load`. +A caller can then propagate that result with `?`. An aborting effect handler instead abandons the +captured continuation. CGP's wiring supplies error-construction behavior without adding that +control-flow mechanism. [Modular error handling](/docs/concepts/modular-error-handling) explains +the error components in detail. -### Impl-side dependencies are the effect row; `check_components!` is "all effects handled" +### Dependency checks verify the selected providers -A provider states its needs as [impl-side dependencies](/docs/concepts/impl-side-dependencies), such -as the `#[uses(CanRaiseError)]` above. That list is CGP's counterpart of the effect row Koka -would infer for a function that performs `raise`, and a generic provider is effect-polymorphic in a -loose sense, since the context type variable stands for "whatever else this context can do". -[`check_components!`](/docs/reference/macros/check_components) is the discharge check: +A provider's impl-side dependencies state the traits and fields it needs from a context. +For example, `LoadOrFail` requires `CanRaiseError`. A check verifies those requirements +transitively for the selected implementation: ```rust check_components! { @@ -278,15 +276,16 @@ check_components! { } ``` -This asserts that `App` supplies every trait `LoadOrFail` transitively needs, and it fails to compile -naming the missing one if not. That is Koka's guarantee that an unhandled effect is a type error, and -the opposite of OCaml's runtime `Effect.Unhandled`. +The compiler rejects this check if `App` cannot satisfy a required dependency. This resembles +checking that required operations have implementations, but it is not an effect-row check. +CGP does not track every effect a provider body can perform: the body may still print, mutate +state, or panic through ordinary Rust APIs. The +[impl-side dependencies](/docs/concepts/impl-side-dependencies) page explains the guarantee. ### Configuring abstract types through the same wiring -CGP extends the operations-and-handlers wiring to something effect systems do not touch: abstract -*types*. Alongside choosing the provider for an operation, a context chooses the concrete type behind -an [abstract type](/docs/concepts/abstract-types) through the same table: +CGP wiring can select associated types as well as operation implementations. This independent +configuration chooses the context's error type: ```rust use cgp::core::error::ErrorTypeProviderComponent; @@ -298,89 +297,80 @@ delegate_components! { } ``` -An effect handler interprets operations, which are values and computations. It has no notion of -supplying a *type member* the way `HasErrorType` supplies `Error`. The table that says "raise errors -this way" also says "and the error type is `anyhow::Error`". +The same table can therefore select error-construction behavior and the concrete `Error` type. +This follows from Rust's associated types and CGP's +[abstract-type components](/docs/concepts/abstract-types). It is an additional use of the wiring +mechanism, separate from the comparison with handlers interpreting operations. -### A closer theoretical fit: coeffects +### A related theoretical view: coeffects -The *coeffect* framework may describe CGP more precisely than the effect framework does. Where an -effect describes what a computation produces or performs, a coeffect describes what a computation -*requires from its environment* ([Petricek, *Coeffects*](https://tomasp.net/coeffects/)). A CGP -context carries exactly such requirements, resolved all at once when a concrete context is defined, -and the framing also accounts for the abstract-type extension above, which an effect handler has no -place for. The connection is a pointer rather than a developed account. +Coeffects offer another way to describe CGP's declared context dependencies. An effect describes +what a computation does; a coeffect describes what it requires from its environment. +[Petricek's coeffects work](https://tomasp.net/coeffects/) develops that distinction. CGP's field +and trait requirements suggest such a comparison, but CGP does not implement a coeffect calculus. ## What each approach costs -Algebraic effects are valued for ending *function coloring*, since code between the operation and its -handler needs no awareness of the effect -([Abramov, *Algebraic Effects for the Rest of Us*](https://overreacted.io/algebraic-effects-for-the-rest-of-us/)), -for separating an effect's interface from its semantics, and for composing handlers where monad -transformers are painful ([*Why Algebraic Effects?*, Ante](https://antelang.org/blog/why_effects/)). -Their costs, as their users state them, fall into three clusters. Unfamiliarity and control-flow -opacity: following control from a `perform` to the handler that catches it is as hard as reasoning -about a distant exception handler ([Ante](https://antelang.org/blog/why_effects/)). Performance: -general handlers must capture continuations, and non-tail handlers remain more expensive than native -control flow even after evidence passing ([Xie & Leijen, 2021](https://xnning.github.io/papers/multip.pdf)). -And, in the untyped designs, an unhandled effect is a runtime crash rather than a compile error, and -OCaml's one-shot restriction rules out the multi-shot uses ([OCaml manual](https://ocaml.org/manual/5.5/effects.html)). -Readers who reach effects from Haskell know the type-class-based effect libraries and their -n²-instances problem, which handler-based systems avoid -([`fused-effects`](https://hackage.haskell.org/package/fused-effects)). - -CGP's costs are the ordinary ones. A component has to be declared before it can have providers, and -the wiring is code somebody writes. The compile-time work is real. And the raw diagnostics are -trait-solver output over generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the -root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape -every class. CGP also keeps even less of the "algebraic" than the practical effect languages do: it -has no equational theory relating its operations. Since Koka, OCaml, and Flix mostly drop the laws -too, this is a shared simplification. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) -page weighs CGP's costs against the alternatives. - -## Where effect handlers are the only tool - -When a program needs the continuation, for a scheduler, a generator, a backtracking solver, or a -suspendable coroutine, algebraic effects are the right and only tool of the two. Emulating them with -CGP is not possible, because a provider never captures a continuation. CGP does have an -[async handler family](/docs/concepts/handlers) and [type-level DSLs](/docs/concepts/type-level-dsls) -that interpret a `Code` tag by dispatching to a provider, which is the closest CGP comes to the -operations-and-interpreters shape, but even there the interpretation is a straight call chain resolved -at compile time. Async in CGP is Rust's own `async` and `await` threaded through provider calls. +Effect handlers separate operation use from interpretation and support reusable control-flow +abstractions. Their flexibility also makes control flow less local: understanding a `perform` may +require locating the handler and following its resumption behavior. The +[Ante language's account](https://antelang.org/blog/why_effects/) discusses both the modularity +benefit and the difficulty of following effects across a program. + +Handler costs depend on the language and the resumption pattern. General handlers may capture +continuations, while tail-resumptive handlers admit simpler compilation. The evidence-passing +research documents those implementation choices and their performance trade-offs +([Xie and Leijen](https://xnning.github.io/papers/multip.pdf)). OCaml additionally restricts +continuations to one use and reports unhandled effects at runtime. Effect-typed languages move +that handling check into the type system. + +CGP requires component declarations, wiring, and compile-time trait resolution. It also requires +readers to learn the consumer/provider split. Its raw diagnostics expose generated types: +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. CGP does not provide +continuation handling, effect typing, or checked algebraic laws for its operations. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) weighs its machinery against simpler +Rust abstractions. + +## Where effect handlers are the better choice + +Effect handlers fit abstractions that need access to the suspended computation, such as a +scheduler, generator, or backtracking interpreter. The chosen language must support the required +resumption pattern; one-shot handlers do not provide multi-shot search directly. CGP wiring alone +cannot supply this control over a continuation. + +CGP can still participate in asynchronous Rust programs. Its +[async handler family](/docs/concepts/handlers) uses Rust futures and `async`/`await`, and its +[type-level DSLs](/docs/concepts/type-level-dsls) select interpreters through providers. These +constructs compose ordinary Rust computations; they do not add general algebraic effect handlers. ## What to expect that differs -**A provider returns exactly once.** There is no `resume` to call zero times or twice, because there -is no reified continuation. CGP takes the fragment of effect handlers the literature identifies as -dynamic binding, the fragment that compiles to direct calls, and builds everything on it. - -**Handlers are chosen by the context's type, not by dynamic scope.** The nearest handler on the -runtime stack does not win, because there is no stack of handlers. A CGP provider is fixed once in a -wiring table and resolved through the trait system. +Provider calls use ordinary Rust control flow. A provider receives its context rather than a captured continuation it could +store or resume repeatedly. Normal return resumes the caller in place, while panic and divergence +retain their usual Rust meanings. -**The wiring is a set, not a stack.** An effect handler stack is ordered, and reordering handlers -changes results: state over nondeterminism and nondeterminism over state compute different things -([Kammar, Lindley & Oury, *Handlers in Action*](https://denotational.co.uk/publications/kammar-lindley-oury-handlers-in-action.pdf)). -CGP's table has one provider per component with no nesting to shadow an outer handler and no order to -permute, and because dispatch is exactly-once and resume-in-place, the non-commutativity never arises. +The context type determines provider selection. CGP does not choose the nearest handler on the +runtime stack. Different context values may carry different data while sharing the same wiring. -**Abstract types are a requirement kind effect systems lack.** A context fixes a type as well as an -operation's interpretation, through the same table. +A wiring table does not impose a handler-stack order. Each entry selects a provider for its key. +Provider composition can still be order-sensitive: a wrapper may act before or after an inner +provider. Static selection does not make arbitrary operations commute. -**CGP is not an effect system.** It has no continuations, no dynamic scope, and no effect kind in the -type system. It is the exactly-once, resume-in-place fragment of effect handlers, which is dynamic -binding, made into a compile-time, per-context, type-directed wiring mechanism that also configures -abstract types. +Dependency checks cover declared requirements rather than every effect in a method body. +They establish that the selected providers can be used with a context. They do not establish +purity or confinement, and they do not turn CGP into an effect system. ## Where to go next -- [Modular error handling](/docs/concepts/modular-error-handling): the error type, its raising, and - its wrapping as three wiring decisions. -- [Implicit arguments](/docs/concepts/implicit-arguments): the dynamic-binding fragment on its own - terms. -- [Handlers](/docs/concepts/handlers): CGP's computation family, and where async lives in it. -- [Capabilities](./capabilities.md): the effects-as-capabilities reading of the same fragment. -- [Row polymorphism](./row-polymorphism.md): the row types Koka uses for its effect rows. +These pages expand the CGP mechanisms and nearby comparisons: + +- [Modular error handling](/docs/concepts/modular-error-handling): selecting error types and + error-construction behavior. +- [Implicit arguments](/docs/concepts/implicit-arguments): reading values from a context. +- [Handlers](/docs/concepts/handlers): CGP's computation family and its async forms. +- [Capabilities](./capabilities.md): requirements on an environment and the limits of that analogy. +- [Row polymorphism](./row-polymorphism.md): the row types used by effect-typed languages. ## Sources diff --git a/docs/comparisons/capabilities.md b/docs/comparisons/capabilities.md index 357c2238..e8dac1b9 100644 --- a/docs/comparisons/capabilities.md +++ b/docs/comparisons/capabilities.md @@ -1,60 +1,59 @@ --- sidebar_label: 'Capabilities' sidebar_position: 11 -description: 'The five things "capability" names, and which of them CGP resembles: object capabilities, capability-based security, effects as capabilities, and the Rust community''s uses.' +description: 'Distinguish capability models and compare their guarantees with CGP dependency checks and context fields.' --- # Capabilities -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows -"capabilities" in one of the several senses the word carries: the object-capability model of E and -Pony, capability-based security in seL4, WASI, or `cap-std`, effects as capabilities in Effekt and -Scala, or the Rust community's use of the word for an allocator or runtime a function should receive -without a parameter. CGP is capability-like in the last two senses and is not a capability system in -the first. The page separates the senses, says which requirements CGP meets, and gives a compact way -to say "capability-like, but not a capability system". +CGP can declare dependencies and carry capability values, but it does not enforce a security +boundary. It is a language extension for Rust, with pluggable trait implementations at +compile-time, implemented as a library on stable Rust whose consumer traits are ordinary Rust +traits; the [Introduction](/docs/) covers the basics. This page separates object capabilities, +effects as capabilities, and other uses of the term, then explains which properties CGP shares +and which must come from another system. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. In most CGP code it is a type you define to stand for an application. +A **context** is the type a CGP method runs on, supplying data through fields and implementations +through wiring. In these examples it represents an application. A context field can hold an +object-capability value, while a provider's declared dependencies describe what it needs from +that context. -| In a capability system | In CGP | +| In capability-oriented code | In CGP | | --- | --- | -| A requirement a computation places on its context (Effekt, Scala) | An **impl-side dependency**: `#[uses]` for a trait, `#[implicit]` for a value | -| The handler or scope that supplies it | The context, and constructing a value of it | -| A capability value passed to code that needs it | A field of the context, read by the providers that declare it | -| Static discharge of every requirement | `check_components!` | -| An unforgeable reference (E, Pony, WASI) | No counterpart: a CGP bound is a requirement, not a token | -| Removal of ambient authority | No counterpart: Rust keeps `std` and globals reachable | +| A requirement on a computation's environment | An **impl-side dependency**, declared with `#[uses]` or `#[implicit]` | +| An environment supplying a required value | A context value with the required field | +| A capability value passed to an operation | A context field borrowed by a provider | +| Checking that requirements are supplied | `check_components!` verifies declared dependencies | +| An unforgeable authority-bearing reference | Must be supplied by the field's value type; a trait bound alone does not provide it | +| Excluding ambient authority | Not enforced by CGP; ordinary Rust APIs and globals remain accessible | ## The idea, briefly -"Capability" names at least five different things, and a reader who asks for capabilities in Rust -rarely says which. The senses are separated below by the property each insists on. +The word capability describes several different mechanisms. Object capabilities concern authority +over resources; effect capabilities concern operations available in a scope; other uses concern +privileges, ownership, or implicit dependencies. Their different guarantees determine how each +relates to CGP. ### The object-capability model -A capability, in the sense Dennis and Van Horn introduced in 1966 and Mark Miller made precise for -programming languages, is "a communicable, unforgeable token of authority" that refers to an object -together with the rights to use it ([Wikipedia, *Capability-based security*](https://en.wikipedia.org/wiki/Capability-based_security)). -The object-capability model identifies that token with an ordinary object reference: to hold the -reference is to hold the authority. Three properties define it. *No designation without authority*: -naming a resource and being allowed to use it are the same act. *No ambient authority*: a request -either carries a capability or fails, so global functions such as `open()` are the counterexample -([Miller, Yee & Shapiro, *Capability Myths Demolished*](https://papers.agoric.com/assets/pdf/papers/capability-myths-demolished.pdf)). -And authority spreads only along existing references: "only connectivity begets connectivity" -([Miller, *Robust Composition*](https://papers.agoric.com/assets/pdf/papers/robust-composition.pdf)), -so reachability in the object graph bounds what any object can do, which is the reasoning the -*principle of least authority* rests on. Delegation is passing the reference, attenuation is wrapping -it, and revocation is closing a gate in the wrapper, all runtime acts on runtime values. The languages -built on the model, E, Pony, Newspeak, Austral, and Hardened JavaScript, remove global mutable state -and global I/O, because a global is ambient authority. Pony's tutorial states the rule: global -variables are "ambient authority", so Pony has none, and a program obtains file access only from the -`env.root` authority its `Main` actor is handed -([Pony tutorial, *Object Capabilities*](https://tutorial.ponylang.io/object-capabilities/object-capabilities.html)): +An object capability combines a reference to a resource with authority to use it. Code obtains +access through references it is given or can derive from existing authority. This makes the +reference graph relevant to the principle of least authority: give each component only the access +it needs. [Miller's account](https://papers.agoric.com/assets/pdf/papers/robust-composition.pdf) +and [Capability Myths Demolished](https://papers.agoric.com/assets/pdf/papers/capability-myths-demolished.pdf) +explain the model and its security properties. + +A capability-safe environment excludes ambient authority that would bypass those references. +An unrestricted global file-opening function would violate that rule. Passing a reference delegates +authority; a wrapper can expose fewer operations or mediate access so it can later revoke it. +These are properties of the supplied objects and their environment, rather than of a dependency +annotation alone. + +Pony gives its main actor an environment from which it obtains authority. The following fragment +uses `env.root` to create file access, following the +[Pony tutorial](https://tutorial.ponylang.io/object-capabilities/object-capabilities.html): ```pony use "files" @@ -72,25 +71,22 @@ actor Main ### Capability-based security in systems -The same model applied below the language gives a process handles to kernel objects and no other way -to name them: KeyKOS, seL4, Fuchsia, and Capsicum, with CHERI moving it into hardware -([CHERI](https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/)). WASI "has no ambient -authorities" and its handles "are unforgeable" -([WASI design principles](https://github.com/WebAssembly/WASI/blob/main/docs/DesignPrinciples.md)). -Rust's `cap-std` brings the discipline to the standard library's surface: its APIs "don't access -files, directories, network addresses, clocks, or other external resources implicitly, but instead -operate on handles that are explicitly passed in", the one exercise of ambient authority is marked by -an explicit `ambient_authority()` argument, and the crate is candid that it "can't prevent arbitrary -Rust code from using `std::fs`'s path-oriented APIs" -([Gohman, *Introducing cap-std*](https://blog.sunfishcode.online/introducing-cap-std/)). Compiled with -`cap-std` 3: +Capability systems can enforce authority below the language level. Examples include kernel-object +handles in seL4, hardware support in [CHERI](https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/), +and the handles supplied through [WASI](https://github.com/WebAssembly/WASI/blob/main/docs/DesignPrinciples.md). +Their enforcement mechanisms differ, so a library that accepts handles should not be assumed to +provide the same isolation as an operating system or sandbox. + +Rust's `cap-std` exposes resource access through explicit handles. Its `Dir` API limits file +operations to a directory, while opening a directory through ambient authority requires an explicit +marker. This fragment illustrates the distinction: ```rust use cap_std::ambient_authority; use cap_std::fs::Dir; fn read_config(dir: &Dir) -> std::io::Result { - // `dir` is the only authority this function holds; it cannot reach outside it. + // File access through `dir` stays within the directory it represents. let mut text = String::new(); std::io::Read::read_to_string(&mut dir.open("config.txt")?, &mut text)?; Ok(text) @@ -102,29 +98,33 @@ read_config(&dir)?; dir.open("../secret.txt") // Err: a path led outside of the filesystem ``` -### Two senses that share only the word +The confinement applies to operations performed through `dir`. Arbitrary Rust code can still call +`std::fs` directly if its execution environment permits it. The +[cap-std README](https://github.com/bytecodealliance/cap-std) explains both the handle-based APIs and +the limit of a library-level discipline. -Linux "capabilities" divide the superuser's privileges into units such as `CAP_NET_BIND_SERVICE`, -held as a per-thread attribute ([capabilities(7)](https://man7.org/linux/man-pages/man7/capabilities.7.html)). -They are privilege bits, not references to resources. Pony's *reference capabilities*, `iso`, `trn`, -`ref`, `val`, `box`, and `tag`, are aliasing qualifiers whose purpose is data-race freedom -([Pony tutorial, *Reference Capabilities*](https://tutorial.ponylang.io/reference-capabilities/)). A -Rust reader already has that second thing as ownership, `&`, and `&mut`. Neither sense enters the CGP -comparison. +### Privilege bits and reference qualifiers + +Linux capabilities divide superuser privileges into units such as `CAP_NET_BIND_SERVICE`. +They are per-thread privilege attributes, rather than references to individual resources. The +[capabilities manual](https://man7.org/linux/man-pages/man7/capabilities.7.html) describes that model. + +Pony's reference capabilities describe aliasing and access to values. Qualifiers such as `iso`, +`val`, and `ref` support safe sharing and data-race prevention. Rust ownership and borrowing address +related concerns through different rules. The +[Pony reference-capability tutorial](https://tutorial.ponylang.io/reference-capabilities/) +explains these qualifiers. Neither these qualifiers nor Linux privilege bits are mechanisms CGP adds. ### Effects as capabilities -Effekt's designers describe their language as "effects as capabilities": "effect types express which -capabilities a computation requires from its context", given semantics by translation to a calculus in -explicit capability-passing style -([Brachthäuser, Schuster & Ostermann, OOPSLA 2020](https://dl.acm.org/doi/10.1145/3428194)). A -capability here is a value a handler introduces and that must be in scope for an operation to be -performed, and to keep this sound Effekt treats capabilities as second-class: passable down, not -returned or stored. Scala 3's experimental *capture checking* reaches the same place: a capability is -a parameter or local whose type carries a capture set, and the checker prevents it escaping the scope -that introduced it ([Scala 3 Reference, *Capture Checking*](https://docs.scala-lang.org/scala3/reference/experimental/cc.html)). -The concrete application is `CanThrow`, an erased class: a `throw` requires a `CanThrow[E]`, and a -`try` creates one. Compiled with Scala 3.8.4: +Effect-capability systems make an operation depend on access to a handler-provided capability. +Effekt expresses the capabilities a computation requires through its effect types and controls +how they can escape their scope. The paper +[Effects as Capabilities](https://dl.acm.org/doi/10.1145/3428194) develops this approach. + +Scala's capture checking tracks references to capabilities in types, while its safer-exceptions +feature uses `CanThrow` to express permission to throw a checked exception. The following example +uses the experimental safer-exceptions feature in Scala 3.8.4: ```scala import language.experimental.saferExceptions @@ -139,50 +139,54 @@ try println(List(1.0, 2.0, 3.0).map(f).sum) // the try supplies the CanThrow c catch case ex: LimitExceeded => println("too large") ``` -This sense keeps one thing from the object-capability model, that authority to perform an operation is -a value the context supplies, and drops the runtime half. It is a *static* discipline, which is why it -is the sense CGP can be compared with directly. - -### The Rust community's word - -Rust programmers use the word in three threads. The first is *implicit values*: Tyler Mandry's -contexts-and-capabilities proposal declares a `capability` such as an arena and lets an impl require it -in a `with` clause, so an allocator or logger need not be threaded through every signature -([Mandry](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)), and Yoshua Wuyts -describes the pain: "the global allocator acts, in a capability-sense, as an ambient authority" -([Wuyts, *Nesting Allocators*](https://blog.yoshuawuyts.com/nesting-allocators)). The second is -*sandboxing*, the object-capability sense proper, as in `cap-std` and WASI. The third is *ownership -tokens*: the embedded Rust book makes each peripheral a value obtained once, so that "to call the -`read_speed()` method, we must have ownership or a reference to a `SerialPort` structure" -([Embedded Rust Book](https://docs.rust-embedded.org/book/peripherals/singletons.html)), and PermRust -generalizes the idea into a token-based permission system -([Gehring, Rehms & Tschorsch](https://arxiv.org/abs/2506.11701)). A reader who wants "capabilities in -Rust" may mean any of the three. - -### The properties that tell the senses apart - -| Property | Object capabilities | Effects as capabilities | Rust contexts proposal | Ownership tokens | -| --- | --- | --- | --- | --- | -| Designation and authority are one reference | yes | partly | no: a named implicit value | yes, for the resource the token stands for | -| No ambient authority, enforced | yes, by removing globals | no, unless the language also removes them | no | no | -| Unforgeable | yes | yes, by private constructors or erasure | not addressed | yes, by a private constructor | -| Provisioned at runtime | yes | value at runtime, scope lexical | value at runtime, binding lexical | value at runtime | -| Delegation, attenuation, revocation | all three, at runtime | delegation and attenuation; no revocation | delegation by scope | delegation by move or borrow | -| Confinement reasoning | reachability in the object graph | capture sets bound escape | not addressed | ownership bounds aliasing | +The surrounding `try` supplies the `CanThrow` evidence needed by `f`. This illustrates static +permission to perform an operation, rather than a runtime operating-system privilege. See Scala's +[CanThrow documentation](https://docs.scala-lang.org/scala3/reference/experimental/canthrow.html) +and [capture-checking reference](https://docs.scala-lang.org/scala3/reference/experimental/cc.html). +CGP's declared requirements resemble part of this structure, but CGP does not supply capture checking. + +### Capabilities in Rust discussions + +Rust discussions use capability terminology for implicit dependencies, sandboxed resources, and +ownership tokens. The intended guarantee matters more than the shared word: + +- **Implicit dependencies:** the contexts-and-capabilities proposal supplies values such as an + arena through a context, reducing parameter forwarding. See + [Mandry's proposal](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/). +- **Sandboxed resources:** `cap-std` and WASI express access through handles, with different + enforcement boundaries. +- **Ownership tokens:** a value with a controlled constructor represents access to a resource, + such as a peripheral. The [Embedded Rust Book](https://docs.rust-embedded.org/book/peripherals/singletons.html) + explains the singleton pattern, and [PermRust](https://arxiv.org/abs/2506.11701) explores token-based + permissions. + +A request for capabilities in Rust can therefore mean either a more convenient API or a stronger +restriction on what code may do. CGP addresses dependency declaration and selection; its wiring +alone does not impose the latter restriction. + +### The properties that distinguish the models + +The following properties help identify which mechanism a program needs: + +| Mechanism | What it represents | Where its guarantee comes from | +| --- | --- | --- | +| Object capability | Authority carried by a reference | Controlled references and an environment that excludes bypasses | +| Effect capability | Access to an operation or handler | The language's effect, scope, or capture rules | +| Rust contexts proposal | An implicitly supplied dependency | The proposed context-binding and type-checking rules | +| Ownership token | Access represented by a value | Controlled construction and ownership or borrowing | +| CGP dependency | A trait or field an implementation requires | Rust trait checking against the selected context | ## How CGP expresses it -CGP shares the effects-as-capabilities reading almost exactly and the object-capability reading only in -part. A provider's [impl-side dependencies](/docs/concepts/impl-side-dependencies) are the requirements -a computation places on its context, the context supplies them, and -[`check_components!`](/docs/reference/macros/check_components) verifies that every requirement is met. -CGP does not remove ambient authority, does not make its requirements unforgeable, and does not -provision them at runtime. +CGP declares what a provider needs from its context and checks that the context supplies it. +Those requirements may include authority-bearing values, but CGP does not make every dependency +an authority token. It also does not restrict access to globals or check the escape of capability +references beyond Rust's ordinary type and lifetime rules. -### A requirement on the context is a capability in the effect-system sense +### Providers declare requirements on a context -A provider declares what it needs with `#[uses]` for traits and `#[implicit]` for values, and the -consumer trait a caller invokes hides both: +A provider uses `#[uses]` for trait dependencies and `#[implicit]` for field dependencies. +This fragment assumes a `CanGreet` component whose method returns a `String`: ```rust #[cgp_impl(new GreetHello)] @@ -206,19 +210,19 @@ delegate_components! { check_components! { App { GreeterComponent } } ``` -Read as an effect type, `GreetHello` requires one thing of its context, a `name` field, and `App` -supplies it. Constructing `App { name }` is the `try` that supplies a `CanThrow`, or the `with` block -that supplies Mandry's arena. The parallel extends to the type level: an -[abstract type](/docs/concepts/abstract-types) such as a context's `Error` is a requirement the -context discharges by wiring, which no capability system expresses. `App` here is an **environmental -context**, a type standing for an application, and `GreetHello` is self-targeted. +`GreetHello` needs a `name` field, and `App` supplies it. `check_components!` verifies the field +requirement for the selected provider; constructing `App { name }` supplies its runtime value. +`App` is an environmental context representing an application, and the component is self-targeted. +This is a dependency relationship: the `String` does not confer protected authority. + +Contexts can also determine [abstract types](/docs/concepts/abstract-types), such as the error type +shared by their providers. Selecting such a type is separate from supplying an authority-bearing +value of that type. A type choice alone does not grant access to a resource. ### An object capability can live in the context -Where the value a provider requires is itself an object capability, CGP carries it and adds a static -check that it reaches the code that needs it. A `cap-std` `Dir` stored as a context field is an object -capability in the model's sense, and a provider that reads configuration through it holds no other -filesystem authority in its body. This compiles against `cgp` `0.8.0-alpha` and `cap-std` 3: +A context can carry a `cap-std` directory handle to a provider that declares it as a dependency. +This example reads configuration using that handle: ```rust use cap_std::fs::Dir; @@ -251,114 +255,105 @@ delegate_components! { check_components! { App { ConfigReaderComponent } } ``` -The division of labor is the point. `cap-std` supplies the unforgeable handle and the runtime -confinement; CGP supplies the declaration that `ReadConfigFromDir` needs a `Dir` and the compile-time -check that `App` has one. The same arrangement serves an arena-allocating deserializer, where the -arena is a context field and the provider reads it as an implicit argument, which the -[Rust proposals](./rust-language-proposals.md) page relates to Mandry's example. +`cap-std` constrains file access performed through `config_dir`, while CGP verifies that `App` +supplies the required field. `App` is again an environmental context with a self-targeted component. +The mechanisms compose: the value type supplies resource-access behavior, and CGP supplies the +dependency declaration and static wiring check. An allocator or arena can be passed through a context +field in the same way, as discussed in [Rust's own proposals](./rust-language-proposals.md). ### CGP does not remove ambient authority -The property that makes a language capability-safe is that code can reach only what it is handed, and -Rust does not have it. `ReadConfigFromDir` could call `std::fs::File::open("/etc/passwd")` in its -body and CGP would neither notice nor object. The provider's declared requirements bound what it -reaches *through the context*, which is useful for reading and for testing, but they do not bound what -it reaches through `std`, through statics, or through the global allocator. A capability-safe language -forbids the global; CGP is a library in a language that permits it. A page that suggested a CGP -provider is confined to its declared dependencies would be claiming something Rust cannot deliver. - -### A requirement is not an unforgeable token - -An object capability is unforgeable because the only way to obtain the reference is to be given it. A -CGP requirement is a trait bound on the context, and any context that carries a field of the right -name and type satisfies a `HasField` bound. The bound says what the provider -needs; it does not certify who may construct the context. Authority, where there is any, lives in the -*value* stored in the field: a `Dir` is unforgeable because `cap-std` made it so, and a `String` named -`name` is not a capability at all. Rust can express unforgeable tokens as types with private -constructors, and CGP can carry such a token as a field or fix one as an abstract type, but the token -pattern is Rust's. - -### Provisioning is fixed per context type - -In the object-capability model authority is provisioned at runtime and the graph changes while the -program runs. In CGP the set of requirements a context satisfies, and the providers it satisfies them -with, are part of the context *type*, fixed when `delegate_components!` is written. Only the field -*values* are dynamic: two `App` values may carry two different `Dir` handles, and a test may carry a -`Dir` opened on a temporary directory. That is provisioning of values, not of authority structure. -Attenuation means a [higher-order provider](/docs/concepts/higher-order-providers) that wraps an inner -one, decided statically; revocation has no counterpart; and bindings are flat, with no nested scope in -which a provider could be shadowed. +A provider can access ordinary Rust APIs beyond its context dependencies. `ReadConfigFromDir` +could call `std::fs::File::open(...)` directly if the execution environment allows it, and CGP +would not reject the call. Its declared bounds describe requirements on the context, not a complete +list of effects or authority exercised by the body. + +### A trait bound does not create an authority token + +A `HasField` bound establishes access to a field of a particular name and type. It does not +establish who may create the field's value. When the field contains a capability, the relevant +construction and access restrictions come from that value's type and execution environment. +Rust types with private constructors can implement controlled tokens; CGP can carry those tokens +without changing their guarantees. + +### Wiring is static; capability values can vary at runtime + +A concrete context type fixes its provider selections and field types. Its values can still hold +different handles: two `App` instances can refer to different directories, including a temporary +directory used by a test. Their filesystem authority therefore differs even though their wiring +is identical. + +Delegation, attenuation, and revocation must come from the capability implementation. A context +can hold a wrapper that limits access or checks whether access has been revoked. A +[higher-order provider](/docs/concepts/higher-order-providers) can also wrap behavior, but wrapping +alone is not proof of attenuation if other access paths remain available. CGP does not add these +security properties or prevent runtime capability values from implementing them. ## What each approach costs -Object capabilities are valued for what their reasoning buys: least authority as a property of the -object graph rather than a policy someone maintains, structural immunity to confused-deputy attacks, -and delegation and attenuation as ordinary programming -([Miller, *Robust Composition*](https://papers.agoric.com/assets/pdf/papers/robust-composition.pdf)). -The effects-as-capabilities line is valued for lightweight effect polymorphism -([Brachthäuser, Schuster & Ostermann, 2020](https://dl.acm.org/doi/10.1145/3428194)). Their costs, -as their users state them, are the costs of removing what everyone is used to. Ambient authority is -convenient, and passing an allocator by hand "doesn't exactly seem ideal" -([Wuyts](https://blog.yoshuawuyts.com/nesting-allocators)). Retrofitting is hard: `cap-std` cannot -sandbox code that still has `std::fs`, and Pony and Austral removed globals from the language, which -no established ecosystem can do after the fact. The effect-system designs pay in restrictions and -maturity: Effekt's capabilities cannot be returned or stored, and Scala's capture checking is, by its -own documentation, "still highly experimental and unstable". And the word itself is a cost, since the -senses are conflated so often that a 2003 paper set out to demolish the resulting myths -([Miller, Yee & Shapiro](https://papers.agoric.com/assets/pdf/papers/capability-myths-demolished.pdf)). - -CGP's costs on this page are the properties it lacks. A reader who wants confinement gets none from -CGP alone and must bring `cap-std`, WASI, or a token type of their own. A reader who wants nested -scopes that shadow a binding gets a single flat context. A reader who wants a capability that can be -returned, stored, and revoked gets a field value with none of those semantics attached. Beyond these, -the ordinary costs apply: the wiring is code somebody writes, and the raw diagnostics are trait-solver -output over generated types. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for -the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs CGP's costs against the -alternatives. +Object capabilities support reasoning about authority through references, but that reasoning needs +an enforcement boundary. Retrofitting a handle-based API into an unrestricted language does not +remove other APIs that exercise ambient authority. Applications must account for those bypasses +or use an environment that excludes them. The +[cap-std documentation](https://github.com/bytecodealliance/cap-std) makes this library-level limit +explicit. + +Effect-capability systems add scope and escape rules that programmers must understand. +Effekt's second-class treatment restricts where capabilities can be stored or returned, while +Scala's capture checking tracks their use through types. These rules support guarantees that a +plain dependency declaration does not provide. The +[Effekt paper](https://dl.acm.org/doi/10.1145/3428194) and +[Scala reference](https://docs.scala-lang.org/scala3/reference/experimental/cc.html) explain the +respective designs. + +CGP adds declarations, wiring, and compile-time work without supplying confinement or capture +checking. Programs that need those properties must obtain them elsewhere. Its generated trait +machinery also affects diagnostics: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root +cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every +class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) compares this machinery +with simpler Rust abstractions. ## Where a capability system is the better choice -Where a program needs a capability-safe language, Pony, Austral, or Hardened JavaScript is the tool, -and where it needs sandboxed I/O in Rust, `cap-std` and WASI are. Where it needs privilege bits or -aliasing control, Linux capabilities and Rust's ownership already exist and CGP does not touch them. -CGP is the better tool where a program wants its implementations to state what they require and a -compiler to check that each context supplies it, on stable Rust, with the choice of implementation made -per application, and it combines with the object-capability libraries rather than competing with them. +Use an enforcing capability system when the requirement is to limit what code may access. +A capability-safe language or sandbox can exclude ambient access paths. Within Rust, `cap-std` +helps express handle-based access, while an appropriate sandbox is needed to constrain code that +could otherwise bypass those handles. Ownership tokens address controlled access to resources +through Rust's construction and borrowing rules. + +CGP fits the separate requirement of reusable implementations with declared dependencies and +choices per context. It can carry capability values from those systems, but a wiring check is not +a security audit or proof of confinement. ## What to expect that differs -**CGP does not remove ambient authority.** A provider's bounds bound what it reaches through the -context, and nothing else. Rust's `std` and globals remain reachable from any body. +CGP checks declared context requirements rather than all authority used by a body. +Ordinary Rust globals and APIs remain available unless another mechanism restricts them. -**A CGP bound is a requirement, not a token.** Any context with the right field satisfies it. Where -authority matters, it lives in the field's value, and a type with a private constructor is how Rust -makes such a value unforgeable. +A field dependency identifies a value the implementation needs. Whether that value grants +protected authority depends on its type and how it was obtained. A `String` and a directory handle +can both be dependencies without having the same security meaning. -**The authority structure is fixed per context type.** Field values vary at runtime; which providers -a context has, and what they require, does not. There is no runtime delegation, attenuation, or -revocation, and there is no nested scope. +The context type fixes wiring, while runtime values determine which resources its handles reach. +Any delegation or revocation behavior belongs to those handles and wrappers, not to the wiring +macro. -**There is no escape check.** A context field can be cloned out and used elsewhere. Effekt's -second-class capabilities and Scala's capture sets prevent that; CGP does not. +CGP does not add an escape checker. Rust's ownership, borrowing, and lifetime rules still apply, +and a value can be cloned or moved only when its type and the surrounding code permit it. +CGP adds neither Effekt's second-class restriction nor Scala's capture sets. -**CGP does not "give Rust capabilities" in any single sense.** If the reader means implicit passing of -an allocator or a runtime, CGP's implicit arguments do that now, and the -[Rust proposals](./rust-language-proposals.md) page says what the contexts proposal would add. If the -reader means sandboxing, `cap-std` and WASI are the tools and CGP carries their handles. If the reader -means ownership tokens, Rust already has them and CGP can fix one as an abstract type. In CGP's own -vocabulary, a component defines a *trait*, a provider *requires* traits and *reads* fields, and a -context *supplies* what providers need; none of these is called a capability. +CGP terminology keeps these distinctions visible. A component defines a trait, a provider requires +traits and reads fields, and a context supplies those requirements. The term capability is reserved +for the external mechanisms and values whose properties justify it. ## Where to go next -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the construct this page reads as a - capability requirement. -- [Implicit arguments](/docs/concepts/implicit-arguments): reading a value from the context. -- [Algebraic effects](./algebraic-effects.md): the effects-as-capabilities fragment from the effect - handler side. -- [Rust's own proposals](./rust-language-proposals.md): the contexts-and-capabilities proposal in - full. +These pages explain the dependencies and related language proposals: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): requirements declared by providers. +- [Implicit arguments](/docs/concepts/implicit-arguments): reading values from context fields. +- [Algebraic effects](./algebraic-effects.md): operations, handlers, and the continuation boundary. +- [Rust's own proposals](./rust-language-proposals.md): the contexts-and-capabilities proposal. ## Sources diff --git a/docs/comparisons/dependency-injection.md b/docs/comparisons/dependency-injection.md index 72349dd5..159e2461 100644 --- a/docs/comparisons/dependency-injection.md +++ b/docs/comparisons/dependency-injection.md @@ -1,46 +1,45 @@ --- sidebar_label: 'Dependency injection' sidebar_position: 8 -description: 'CGP read against Spring, Guice, and Dagger: injection without a container, reflection, or runtime graph.' +description: 'Compare CGP with Spring, Guice, Dagger, and plain Rust injection: dependency declarations, wiring, validation, and runtime values.' --- # Dependency injection -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows -dependency injection (DI) from Spring, Guice, Dagger, or their kin. CGP solves the same decoupling -problem, at compile time and without a container, and the vocabulary maps almost directly. The page -covers that mapping, what changes when resolution moves from runtime to types, where a DI framework -remains the better tool, and what to expect that differs. +CGP supports dependency injection through reusable providers selected by each application. It is a language extension for Rust, with pluggable trait implementations at +compile-time, implemented as a library on stable Rust whose consumer traits are ordinary Rust +traits; the [Introduction](/docs/) explains the basics. For readers familiar with Spring, Guice, +Dagger, or constructor injection, this page compares dependency declarations, wiring, validation, +and the cases that still call for a container. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. In DI terms it is the assembled object graph, made a type you define to stand for an -application. +A **context** is the type a CGP method runs on, supplying its data through fields and its +implementations through wiring. In the examples here, it represents an application and holds the +runtime values its providers need. The compiler resolves provider selection, while application code +constructs and manages those values. | In a DI framework | In CGP | | --- | --- | -| A bean or a binding | A **provider**: an interchangeable implementation of a trait | -| The `@Configuration` class or the Guice module | **Wiring**, written in a `delegate_components!` table | -| A constructor parameter | An **impl-side dependency**, declared with `#[uses]` or `#[implicit]` | -| The interface a bean is bound to | A **component**: one trait with many possible implementations | +| An implementation bound to an interface | A **provider**: a named, interchangeable implementation | +| A configuration class or module | **Wiring**, written in a `delegate_components!` table | +| A constructor dependency | An **impl-side dependency**, declared with `#[uses]` or `#[implicit]` | +| The interface a bean implements | A consumer trait, grouped with its provider trait into a **component** | | Graph validation at startup or build time | `check_components!`, at compile time | -| The container | The type system; nothing exists at runtime | +| Container-managed instances and lifetimes | Context fields and ordinary Rust construction, ownership, and borrowing | ## The idea, briefly -Dependency injection gives an object its collaborators from the outside instead of letting it -construct them. A class that names only the *interfaces* it needs can be handed fakes in a test and -different implementations in a different deployment, and never changes. The frameworks automate the -supplying, which in a large object graph is elaborate enough that they exist for it. +Dependency injection supplies an object's collaborators from outside the object. A class that +requires a storage interface can receive a production client or a test fake without changing its +business logic. DI frameworks automate the construction and connection of these objects, which +becomes useful as the dependency graph grows. ### The IoC container and beans -Spring's core is an *inversion-of-control container* that instantiates, configures, and connects the -application's objects, its *beans*. A class becomes a bean with an annotation, and a `@Configuration` -class spells out which implementation stands in for an interface: +Spring's inversion-of-control container constructs, configures, and connects application objects +called beans. An annotation can register a class for discovery, while a configuration class can +provide a factory for a particular interface. These fragments illustrate both forms: ```java @Service @@ -59,8 +58,8 @@ public class AppConfig { ### Constructor, setter, and field injection -The container injects each bean's dependencies by one of three mechanisms. *Constructor injection* -passes them as constructor arguments, so they are required and the fields can be `final`: +Constructor injection makes required dependencies visible in the constructor's signature. The +container passes them as arguments, and the object can keep them in `final` fields: ```java @Service @@ -75,15 +74,16 @@ public class ProfilePictureService { } ``` -*Setter injection* supplies a dependency after construction, and *field injection* writes it into a -private field by reflection, marked `@Autowired`. The Spring reference and the wider community -recommend constructor injection for required dependencies, because it makes a class's dependencies -explicit in its signature and lets the object be built without a container in a test -([Spring Framework reference](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html)). +Setter and field injection supply dependencies after construction. A setter exposes an assignment +method; field injection lets the framework populate an annotated field. Spring recommends +constructor injection for required dependencies because it supports immutable objects and ensures +that an object starts with those dependencies supplied. The same constructor can be called directly +in a test. See the +[Spring reference](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html). ### Modules and bindings -Guice and Dagger express the same wiring by explicit *bindings* in a *module*: +Guice modules explicitly bind interfaces to implementations. This module selects a storage client: ```java public class StorageModule extends AbstractModule { @@ -94,15 +94,16 @@ public class StorageModule extends AbstractModule { } ``` -Spring and Guice resolve bindings at runtime through reflection. Dagger resolves them at *compile -time*: its annotation processor generates the wiring code during the build, so a missing binding is a -compile error and there is no reflection at runtime. That split is the sharpest axis of variation -among DI frameworks, and CGP sits at the compile-time end of it. +DI frameworks differ in when and how they resolve bindings. Spring and Guice commonly assemble +objects at runtime, using reflective mechanisms. Dagger generates construction and wiring code at +compile time and validates the bindings needed by a component. CGP also resolves implementation +choices at compile time, but uses Rust's trait system rather than an annotation processor. See the +[Dagger developer guide](https://dagger.dev/dev-guide/). ### Dependency injection without a framework -Rust practitioners generally hold that the language needs no DI framework, because traits and -generics already decouple a component from its collaborators: +Rust traits and generics already support dependency injection. A service can receive any storage +value implementing its required interface: ```rust trait StorageClient { @@ -114,29 +115,24 @@ struct ProfilePictureService { } ``` -This is dependency injection in the original sense, with the compiler doing the checking -([jmmv.dev, *Rust traits and dependency injection*](https://jmmv.dev/2022/04/rust-traits-and-dependency-injection.html)). -Its limitation is the one CGP lifts. A bound like `S: StorageClient` leaks into every caller's -signature, and coherence permits one `impl StorageClient` per type, so offering several -interchangeable implementations of one interface runs into the rules the -[Bypassing coherence](/docs/concepts/coherence) page explains. CGP is the next step along the line -Rust already accepts, not an import of the container model. +This design is often sufficient. Different storage types can implement `StorageClient`, so replacing +one collaborator does not itself require CGP. The additional work appears when generic parameters +spread through enclosing types, or when reusable implementations overlap for the same target type. +CGP addresses those cases with a shared context and separately named providers. The +[coherence explanation](/docs/concepts/coherence) develops the latter problem. ## How CGP expresses it -CGP performs dependency injection through two mechanisms working together. A provider declares what -it needs as [impl-side dependencies](/docs/concepts/impl-side-dependencies), and a context supplies -them by wiring each component to a provider. Both are resolved by the compiler, so the "container" -has no runtime existence. Every context below is an **environmental context**: a type standing for an -application, carrying the application's choices and dependencies rather than being the data operated -on. +CGP separates a provider's dependency requirements from an application's implementation choices. +The provider declares [impl-side dependencies](/docs/concepts/impl-side-dependencies), and the +context supplies the required traits and fields. Every context below is an environmental context: +a type representing an application, with self-targeted components that operate through it. +The snippets omit supporting application types and some implementation bodies. -### Impl-side dependencies are the injected constructor parameters +### Impl-side dependencies declare what an implementation needs -Where a Spring service lists `StorageClient` and `UserRepository` as constructor parameters, a CGP -provider lists its trait dependencies with `#[uses]` and its value dependencies as `#[implicit]` -arguments. A user-creation provider that needs a database connection and a censorship service declares -both: +A CGP provider declares trait dependencies with `#[uses]` and field dependencies with `#[implicit]`. +This user-creation implementation needs a username-censorship operation and a database value: ```rust #[cgp_impl(new PostgresUserManager)] @@ -156,20 +152,17 @@ impl UserManager { } ``` -`#[uses(CanCensorUsername)]` injects a *trait dependency*, the role a `UserRepository` collaborator -plays in the constructor. The `#[implicit] database` argument injects a *value* pulled from the -context's `database` field, the role a configuration bean plays. Neither appears in the -`CanManageUser` consumer trait a caller invokes, so, unlike a leaked generic bound, they do not -cascade to callers. That is the decoupling a DI framework promises, delivered by declaring the -requirements one level down in the provider rather than in a container. `Error` here is the -application's own enum, and the insert body is elided. +`#[uses(CanCensorUsername)]` requires the context to implement the censorship trait. The +`#[implicit] database` parameter borrows the context's `database` field. Neither requirement appears +in the `CanManageUser` consumer trait, so a generic caller can require that trait without repeating +the database and censorship bounds. The dependencies remain explicit in the implementation and are +checked when the concrete context's wiring is checked or used. `Error` is the application's enum; +the database insertion is omitted here. -### Wiring is the container configuration +### Wiring selects implementations for an application -A context selects which provider satisfies each component in a -[`delegate_components!`](/docs/reference/macros/delegate_components) table, the direct analogue of a -`@Configuration` class or a Guice module. Two contexts map the same component to different providers -with no conflict, because the choice is keyed on the context type: +A [`delegate_components!`](/docs/reference/macros/delegate_components) table selects a provider +for each component. These contexts choose different storage implementations for the same interface: ```rust #[cgp_component(StorageObjectFetcher)] @@ -190,18 +183,16 @@ delegate_components! { } ``` -`FetchS3Object` and `FetchGCloudObject` are interchangeable providers of the same trait, the -equivalent of two beans bound to one interface, and the wiring picks one per context. Because the -selection is resolved during type checking and monomorphized to a direct call, the `App` binary -contains only the S3 code path and the `GCloudApp` binary only the GCloud one. A container makes the -same substitution by holding both implementations and choosing at startup. +`App` routes storage calls to `FetchS3Object`, while `GCloudApp` routes them to `FetchGCloudObject`. +The compiler resolves both routes statically. A program may use either context or both; the wiring +does not require separate binaries or guarantee that one implementation is absent from a binary. +The providers identify behavior, while the contexts hold values such as client connections and +bucket names. -### Checking replaces the container's startup validation +### Checking validates the declared dependencies -A container discovers a missing or ambiguous binding when it assembles the graph: at startup for -Spring and Guice, at build time for Dagger. CGP's counterpart is -[`check_components!`](/docs/reference/macros/check_components), which asserts at compile time that a -context's wiring is complete and every provider's transitive dependencies are satisfied: +[`check_components!`](/docs/reference/macros/check_components) verifies that the selected provider's +transitive requirements are satisfied for a context: ```rust check_components! { @@ -211,76 +202,81 @@ check_components! { } ``` -If `FetchS3Object` needs a field or trait the `App` context does not supply, this fails to compile -with the missing dependency named, rather than surfacing as a startup exception or a null reference -deep in a request. It is the guarantee Dagger gives, reached through the trait system instead of an -annotation processor. CGP wiring is [lazy](/docs/concepts/check-traits), so this check turns a latent gap into an -early error. +This check fails to compile if `FetchS3Object` needs a field or trait that `App` does not supply. +Like Dagger's graph validation, it catches missing declared dependencies during the build. It does +not validate credentials, network availability, or other runtime conditions. CGP wiring is +[lazy](/docs/concepts/check-traits), so an explicit check catches a missing dependency even before +application code calls the component. ## What each approach costs -DI frameworks are valued for decoupling components from their collaborators, which makes code testable -and swappable, for centralizing wiring in one readable place, and, in Spring's case, for the ecosystem -keyed off the same bean model. Their costs, as their users state them, cluster around the runtime, -reflective nature of the popular frameworks. Dependencies can become hidden: with field injection a -class's signature says nothing about what it needs, and a missing binding is a runtime failure rather -than a compile error, which is why the community steers toward constructor injection -([Nuri, *Field injection is not recommended*](https://blog.marcnuri.com/field-injection-is-not-recommended)). -Classpath scanning and reflective graph construction cost startup time, which is why Dagger's -compile-time generation exists. And the frameworks do so much automatically that when something goes -wrong the developer has little visibility into why -([Shore, *The Problem With Dependency Injection Frameworks*](https://www.jamesshore.com/v2/blog/2023/the-problem-with-dependency-injection-frameworks)). - -CGP resolves everything at compile time, and that is its central cost as well as its benefit. It -cannot reconfigure an application without recompiling, load plugins chosen at startup from a config -file, or build a graph whose shape is not known until the program runs. It is confined to Rust. Its -machinery, the consumer and provider split, the wiring, and the type-level tables, has a learning -curve of its own. And its raw diagnostics are trait-solver output over generated types: +DI frameworks centralize object construction and wiring, but their automation takes work to trace. +Field injection can hide dependencies from a class's constructor, and runtime graph assembly can +report missing bindings only when that graph is built. Constructor injection makes dependencies +visible; compile-time generation, as in Dagger, moves binding validation into the build. These costs +therefore depend on the framework and injection style. The +[Spring reference](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html) +explains the injection trade-offs, and +[Shore's critique](https://www.jamesshore.com/v2/blog/2023/the-problem-with-dependency-injection-frameworks) +argues that framework automation can make a dependency graph harder to follow. + +CGP requires declarations, wiring, and compile-time trait resolution. Developers must learn the +consumer/provider split and trace dependencies through the context. Its wiring selects providers +statically; runtime reconfiguration requires ordinary Rust mechanisms, such as enums or trait +objects, inside or alongside that wiring. CGP also leaves object construction and lifecycle +management to the application. + +CGP's raw errors can be difficult to read because they include generated traits and types. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the -alternatives, including plain traits and generics. +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) weighs the additional machinery against +plain traits, generics, and other alternatives. ## Where a DI framework is the better choice -A DI framework remains the better choice when the application needs runtime reconfiguration, when it -lives in a JVM or .NET ecosystem whose libraries assume the container, or when the team's familiarity -with the framework outweighs the benefits of static wiring. Within Rust, plain traits and generics are -the better choice when one implementation per type suffices and the bound does not spread far. CGP is -the better tool where the graph is known at build time and the guarantees and zero runtime cost -matter: systems programming, latency-sensitive services, and libraries that must not impose a runtime. +A DI framework fits applications that rely on its object lifecycle support, runtime configuration, +or surrounding ecosystem. A JVM application built around Spring's bean model already has reasons +to use that model beyond selecting implementations. Dagger is an option when that application wants +compile-time graph validation. + +Plain Rust traits and generics fit dependencies that can be expressed without extensive parameter +propagation or overlapping implementations. CGP becomes useful when reusable providers need +independent implementation choices per context and static wiring justifies the extra declarations. +A build-time dependency graph alone does not make CGP necessary. ## What to expect that differs -**There is no container object.** A DI reader will look for something holding the graph and resolving -dependencies by reflection at startup. CGP's container is the type system, the graph is a set of -trait impls, and the resolution happens during compilation and compiles to direct calls. There is no -runtime cost and no runtime failure mode to look for. +CGP resolves provider selection without a container object. The wiring consists of trait impls; +context fields still contain runtime values that application code must construct and manage. -**There is no scanning or auto-registration.** CGP asks for explicit wiring. There is no classpath -scan, no `@Component` discovery, and no runtime rebinding, and the graph must be known at compile -time. This is the price of the guarantees, the same trade Dagger made, carried to its conclusion. +CGP uses declared wiring rather than classpath scanning or bean discovery. Changing a wiring entry +requires compilation. Runtime choices can be represented by values or dispatch mechanisms that a +selected provider uses. -**The same interface can resolve differently per context.** A single global binding graph cannot -express two applications binding one interface two ways. In CGP that is one wiring line each. +Each context type can choose a different provider for the same component. DI frameworks can also +support separate configurations or graphs; CGP records this distinction in Rust types. -**Dependencies are never hidden.** They are stated in `#[uses]` and `#[implicit]` and enforced by the -compiler, which gives the explicitness the community prizes in constructor injection by default. +Provider declarations expose their context dependencies. These declarations do not describe every +possible influence on the body: a provider can still access globals or perform I/O through ordinary +Rust APIs. ## Where to go next -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the construct this page maps onto - constructor parameters. -- [Checking your wiring](/docs/concepts/check-traits): why wiring is lazy and what the check catches. -- [Implicit arguments](/docs/concepts/implicit-arguments): value injection from context fields. -- [ML modules](./ml-modules.md) and [Policy-based design](./policy-based-design.md): the same - centralized wiring seen from two other traditions. +These pages explain the mechanisms behind the comparison: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): requirements declared by an + implementation and hidden behind its consumer trait. +- [Checking your wiring](/docs/concepts/check-traits): why wiring is lazy and what a check verifies. +- [Implicit arguments](/docs/concepts/implicit-arguments): reading values from context fields. +- [ML modules](./ml-modules.md) and [Policy-based design](./policy-based-design.md): other approaches + to choosing implementations and assembling dependencies. ## Sources The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per wired context. The Java snippets follow the framework documentation cited below. +- [Dagger developer guide](https://dagger.dev/dev-guide/): generated wiring, component graphs, and compile-time validation. - [Spring Framework reference, *Dependency Injection*](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html): the IoC container, beans, and the constructor and setter injection mechanisms. - [Baeldung, *Inversion of Control and Dependency Injection in Spring*](https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring): the distinction between IoC and DI and `@Autowired` resolution by type. - [Comparing Dependency Injection Frameworks](https://medium.com/@AlexanderObregon/comparing-dependency-injection-frameworks-spring-guice-and-dagger-a614dccd5859) and [Dagger vs Guice](https://www.hackingnote.com/en/versus/dagger-vs-guice/): the runtime-versus-compile-time split across frameworks. diff --git a/docs/comparisons/dynamic-dispatch.md b/docs/comparisons/dynamic-dispatch.md index 99225277..23b04ba7 100644 --- a/docs/comparisons/dynamic-dispatch.md +++ b/docs/comparisons/dynamic-dispatch.md @@ -1,95 +1,93 @@ --- sidebar_label: 'Dynamic dispatch' sidebar_position: 9 -description: 'CGP read against dynamic dispatch, duck typing, vtables, and prototypal inheritance: the same openness, resolved at compile time.' +description: 'Compare CGP static wiring with dynamic dispatch, duck typing, and prototype delegation, including how trait objects can coexist with CGP.' --- # Dynamic dispatch, dynamic typing, and prototypal inheritance -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who thinks in -objects, messages, vtables, and prototypes: Python, Ruby, JavaScript, Smalltalk, or the virtual -dispatch of C++ and Java. CGP reproduces the openness those mechanisms buy, many implementations -behind one interface, behavior assembled by delegation, defaults inherited from a shared table, and -provider code that reads as if it sends messages to an object, and resolves every bit of it at -compile time into direct calls. The page covers the correspondence, the one change from which the -rest follows, where runtime dispatch remains the right tool, and what to expect that differs. +CGP supports interchangeable implementations and delegation while resolving provider selection at +compile time. It is a language extension for Rust, with pluggable trait implementations at +compile-time, implemented as a library on stable Rust whose consumer traits are ordinary Rust +traits; the [Introduction](/docs/) covers the basics. For readers familiar with objects, messages, +vtables, or prototypes, this page explains the shared structure, the limits of static selection, +and where runtime dispatch remains useful. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. It plays the object's part. +A **context** is the type a CGP method runs on, supplying data through fields and implementations +through wiring. It plays the receiver's role: a provider operates on that context even when several +layers of delegation lead to the provider. -| In a dynamic language | In CGP | +| In object-oriented code | In CGP | | --- | --- | -| An object | The context | -| A message or method | A **component**: one trait with many possible implementations | -| A method implementation | A **provider** | -| The object's method table or vtable | The **wiring table**, written with `delegate_components!` and erased before runtime | -| A prototype the object delegates to | An aggregate provider or a namespace | -| `respond_to?` before a call | `check_components!`, made total and moved to compile time | +| An object receiving a method call | A context value | +| An interface declaring methods | A consumer trait within a **component** | +| An implementation of that interface | A **provider** | +| A method table or vtable | A **wiring table**, resolved by the compiler | +| Shared behavior reached through delegation | An aggregate provider or namespace | +| Checking that a receiver supports an operation | Trait bounds and `check_components!` | ## The idea, briefly -Dynamic dispatch decouples a call site from the implementation it invokes, so one piece of code works -over many implementations chosen later. Dynamically typed languages take this to its limit: a value is -whatever it can *do*, behavior is shared by pointing one object at another, and the program is -malleable at runtime. +Dynamic dispatch lets a call site invoke an implementation selected at runtime. Dynamic typing and +prototypal inheritance address related but separate questions: when operations are type-checked, +and how objects share behavior. Keeping these distinctions clear makes it possible to compare +CGP with each mechanism without treating them as one feature. ### Dynamic typing and duck typing -A dynamically typed language checks types at runtime, and *duck typing* is the style this permits: an -object's usability is decided by the methods it has, not by a class it declares. A function that -calls `x.quack()` works for any `x` that responds to `quack` -([Wikipedia, *Duck typing*](https://en.wikipedia.org/wiki/Duck_typing)). Its appeal is that an -interface need never be spelled out. +Duck typing accepts an object according to the operations it supports. In a dynamically typed +language, a call such as `x.quack()` can work without a declared interface as long as the receiver +responds appropriately at runtime. This makes generic behavior convenient, but an unsupported +operation may fail only when the call executes. Python's +[glossary](https://docs.python.org/3/glossary.html#term-duck-typing) describes this style. ### Dynamic dispatch and late binding -Dynamic dispatch is the runtime selection of which implementation a method call invokes, based on the -receiver ([Wikipedia, *Dynamic dispatch*](https://en.wikipedia.org/wiki/Dynamic_dispatch)). Smalltalk -gave the purest form: every call is a message send, resolved at call time by consulting the receiver's -class method dictionary. Statically typed object languages offer the same late binding for methods -marked virtual, and a few languages (CLOS, Julia) generalize to *multiple dispatch* on several -arguments. +Dynamic dispatch selects an implementation using runtime information about the receiver. +Smalltalk expresses calls as message sends; statically typed languages also support late binding +through virtual methods or trait objects. Multiple-dispatch systems extend the selection to more +than one argument. The timing of implementation selection is distinct from whether the language +checks the call's interface statically. ### Vtables and method dictionaries -Compiled languages implement dynamic dispatch with a *virtual method table*: a per-class array of -function pointers that each object reaches through a hidden pointer. A virtual call loads the vtable -pointer, indexes to the method's slot, and calls the function found there -([Wikipedia, *Virtual method table*](https://en.wikipedia.org/wiki/Virtual_method_table)). Rust's own -dynamic dispatch works this way: a `dyn Trait` value is a fat pointer pairing a data pointer with a -vtable pointer ([The Rust Book, *Trait objects*](https://doc.rust-lang.org/book/ch18-02-trait-objects.html)). -The indirect call defeats inlining and adds a load per dispatch. Dynamically typed languages pay more, -resolving a method by name up a class or prototype chain, which is why their engines invest in inline -caches and hidden classes ([V8, *Maps*](https://v8.dev/docs/hidden-classes)). +A vtable stores the method implementations used for dynamic calls. Rust's trait-object pointers +pair a pointer to the value with a pointer to a vtable containing the relevant method pointers. +The call therefore follows an indirect route, as described in the +[Rust Reference](https://doc.rust-lang.org/reference/types/trait-object.html). + +Indirect dispatch can limit optimization, but its cost depends on the call and compiler. +Devirtualization can recover a direct call when the target is known. Dynamic-language runtimes +also optimize property and method lookup; V8's hidden classes help it identify object layouts. +The [V8 documentation](https://v8.dev/docs/hidden-classes) describes that mechanism. A comparison +of dispatch mechanisms alone does not establish a performance ranking for whole programs. ### Prototypal inheritance and delegation -Prototype-based languages share behavior by *delegation*: an object holds a link to a prototype, and a -message the object does not handle is forwarded along the chain. Lieberman introduced the model in -1986 and the Self language realized it -([Lieberman, *Using Prototypical Objects*](https://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html)). -In JavaScript every object has a `[[Prototype]]` link, a lookup walks the chain, and an own property -*shadows* an inherited one ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain)). +Prototypal inheritance shares behavior by linking objects. JavaScript property lookup follows an +object's prototype chain when the property is absent from the object itself, and an own property +shadows an inherited one. The +[MDN guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain) +explains these rules. -The property that distinguishes delegation from mere forwarding matters most for CGP: `self` stays -bound to the original receiver. When a prototype's method refers to `self`, it denotes the object that -originally received the message, so an inherited method still sees the receiver's own state. -Forwarding rebinds `self` to the object the message was passed to and loses that connection. +Delegation preserves the original receiver while obtaining behavior elsewhere. An inherited method +can therefore read the receiving object's state. This is the property of +[Lieberman's delegation model](https://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html) +that matters for CGP: selecting another implementation does not replace the context it operates on. +JavaScript's actual `this` binding also depends on how the function is called. ## How CGP expresses it -CGP reproduces dynamic dispatch, vtables, and prototypal delegation, and resolves each at compile -time. What is a runtime lookup in a dynamic language is a type-resolution step in CGP that -monomorphizes to a direct call. +CGP combines generic provider code with statically selected implementations. Its wiring resembles +a method table in purpose, but the table consists of trait impls and is resolved during compilation. +The examples below omit supporting declarations where the surrounding prose identifies their roles. -### CGP code reads like a duck-typed program +### Provider code calls methods on a generic receiver -A CGP provider is written against an unknown context and reads like duck-typed code that sends -messages to a receiver and trusts it to respond: +A CGP provider can call a method on a context without naming that context's concrete type. +The trait dependency makes the required operation explicit: ```rust #[cgp_auto_getter] @@ -106,9 +104,8 @@ impl Greeter { } ``` -The body `self.name()` is a message send to a context whose type is not written down. With an -[implicit argument](/docs/concepts/implicit-arguments) the resemblance is stronger still: a value -appears from the context, as an unbound name would in Ruby or Python: +`self.name()` calls the context's `HasName` method. An implicit argument provides a shorter form +when the implementation simply needs a field value: ```rust #[cgp_fn] @@ -117,33 +114,31 @@ pub fn greet_implicitly(&self, #[implicit] name: &str) -> String { } ``` -Ordinary generic Rust would demand `fn greet(c: &C)`, naming the trait in the signature. -CGP moves the bound into `#[uses]` and abstracts the context away, so the provider body carries less -visible type ceremony than a plain generic function. The decisive difference is *when* the trust is -discharged. A duck-typed program finds out at runtime whether the object responds, and fails with a -`NoMethodError` if not. CGP finds out at compile time, because trait resolution and -[`check_components!`](/docs/reference/macros/check_components) check the `#[uses(HasName)]` -dependency and the field access. The `Person` these run on is a **value context**: the type being -greeted carries the `name` field and the wiring. - -### Static dispatch with the flexibility of dynamic dispatch - -A caller writes `context.area()` against the `CanCalculateArea` consumer trait without naming an -implementation, as a dynamic call names a method and lets the receiver decide. In CGP the receiver -decides during type checking: the consumer trait's generated impl routes the call through the -context's wiring table to the provider, and the compiler monomorphizes the whole route to a direct -call, with no fat pointer and no vtable load. Rust already offers real dynamic dispatch through -`dyn Trait`, and CGP is its static sibling: both let an implementation be chosen after the calling -code is written, and one pays a runtime indirection while the other resolves it away. Where a -component carries a generic parameter, the [`open` statement](/docs/reference/macros/delegate_components) -selects a provider per value of that parameter, which reproduces *multiple* dispatch, decided at -compile time. - -### `DelegateComponent` is a compile-time vtable - -The type-level table a context carries is a vtable that exists only during compilation. Each entry -maps one component key to the provider that implements it, as a vtable slot maps a method to its -implementation: +Both forms declare a dependency that Rust checks statically. The first requires `HasName`; the +second requires access to a field named `name`. The method body may resemble duck-typed code, +but it relies on declared traits and generated bounds. Ordinary generic Rust can express these +bounds too; CGP's macros supply the context parameter and supporting impls. + +A `Person` type with the required field and wiring is a value context in this example. +It is the value being greeted, rather than an application environment selecting behavior for a +separate target. [Implicit arguments](/docs/concepts/implicit-arguments) explains the field-based form. + +### Implementation choice is deferred to wiring + +A generic caller can invoke `context.area()` through `CanCalculateArea` without choosing an +implementation. The context's wiring supplies that choice, and monomorphization resolves the route +to a static call. This allows provider selection after the generic caller has been written, +while keeping that selection fixed for each concrete context type. + +Generic components can also select providers by their type parameters. The +[`open` statement](/docs/reference/macros/delegate_components) supports entries for different +parameter types, giving a form of type-directed selection across several inputs. This is a +compile-time comparison with multiple dispatch; it does not inspect the runtime types of objects. + +### Wiring serves the selection role of a vtable + +A wiring entry maps a component key to a provider. This resembles the mapping from a vtable slot +to an implementation, except that both the key and selected provider are Rust types: ```rust delegate_components! { @@ -158,20 +153,21 @@ delegate_components! { // } ``` -The mapping is exact on structure and opposite on timing. The context type plays the class, a -`DelegateComponent` impl is a slot, and the provider is the function the slot points to. But the key -is a type rather than an offset, the compiler performs the lookup once rather than the CPU on every -call, and the table is erased before the program runs. The honest cost is that CGP loses the runtime -heterogeneity a real vtable enables: a `Vec>` can hold different shapes and -dispatch each at runtime, whereas a CGP context is one monomorphic type resolved once. The -[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) page traces a call -through the table. +`Rectangle` is a value context, and the self-targeted area component operates on that rectangle. +The compiler resolves `AreaCalculatorComponent` to `RectangleArea` through the shown trait impl. +The program does not store or consult this wiring table at runtime. Components can group several +methods, associated types, and consts, so an entry is not necessarily equivalent to one method slot. + +Runtime heterogeneity remains available through ordinary Rust trait objects. If the consumer trait +is dyn-compatible, a collection such as `Vec>` can contain different +context types and dispatch to their consumer methods dynamically. Each concrete context can still +use CGP wiring internally. The [consumer/provider explanation](/docs/concepts/consumer-and-provider-traits) +traces that internal route. -### Component delegation is delegation, with `self` bound +### Delegation preserves the original context -CGP's delegation chain is delegation in Lieberman's sense, because the context stays bound to the -original as lookup walks the chain. An [aggregate provider](/docs/concepts/aggregate-providers) -bundles a group of wirings, and a context delegates a whole group to it in one entry: +An [aggregate provider](/docs/concepts/aggregate-providers) groups wiring entries for reuse. +A context can delegate several components to the aggregate: ```rust delegate_components! { @@ -188,22 +184,17 @@ delegate_components! { } ``` -When `rect.area()` resolves, the lookup walks `Rectangle`, then `GeometryComponents`, then -`RectangleArea`, and the context stays `Rectangle` at every step: `GeometryComponents` appears only in -the delegate position, never as the context, so the leaf provider reads `width` and `height` from -`Rectangle`. That is delegation's defining property. The delegate chain supplies the *behavior* while -`self` remains the original *identity*. The [`UseContext`](/docs/reference/providers/use_context) -provider is the same relationship pointed the other way, letting a provider route a call back to the -context's own wiring. +An area call follows `Rectangle` to `GeometryComponents` and then `RectangleArea`, with `Rectangle` +as the context at every step. The area provider reads the rectangle's `width` and `height`; +`GeometryComponents` holds neither value. This preserves the receiver in the same sense as +prototypal delegation, with the route resolved statically. [`UseContext`](/docs/reference/providers/use_context) +allows a provider to call back through the context's consumer-trait implementation. -### Namespaces are shared prototypes with open slots, not shadowable ones +### Namespaces share bindings and leave paths for contexts to fill -A CGP [namespace](/docs/concepts/namespaces) is a shared table of wirings that many contexts inherit, -which is the prototype's job. But the override rule differs from JavaScript's. In a prototype chain -an own property *shadows* an inherited one. In CGP, a key the namespace binds is not overridable: -joining a namespace generates a forwarding impl covering every key it answers, so a direct entry for -one of those keys is rejected with `E0119`. What a context may supply is a path the namespace routes -to but leaves unbound, an open slot left for each context to fill: +A CGP [namespace](/docs/concepts/namespaces) shares wiring across contexts. Its inheritance differs +from JavaScript property shadowing: a bound key cannot be redefined by a conflicting impl. +A context can instead fill a path the namespace leaves unbound: ```rust // The shared prototype: it binds the farewell and leaves the greeting path open. @@ -222,8 +213,8 @@ delegate_components! { } ``` -Namespaces inherit from one another, so a child may bind an open path the parent leaves; it may not -redefine a key the parent binds: +`AppDefaults` supplies the farewell provider, while `AppA` supplies the greeting provider at the +open path. A child namespace can fill that path for contexts that join it: ```rust cgp_namespace! { @@ -239,85 +230,85 @@ delegate_components! { } ``` -The lookup that walks these layers is the [`RedirectLookup`](/docs/reference/providers/redirect_lookup) -provider tracing a type-level path, which is the prototype chain being walked. The closer -object-oriented analogy is an abstract base class rather than a prototype: the namespace fixes what -every context agrees on and declares slots each context must fill, and it does not let a child -silently redefine a concrete inherited member. `AppA` and `AppB` are **environmental contexts**, types -standing for an application. +`AppA` and `AppB` are environmental contexts representing applications. Their providers are found +through [`RedirectLookup`](/docs/reference/providers/redirect_lookup), which follows type-level +paths. This resembles sharing defaults through a prototype, but customization fills unbound paths +rather than shadowing already-bound entries. An attempt to bind the same key again conflicts under +Rust's coherence rules. ## What each approach costs -Dynamic dispatch and dynamic typing are valued for immediacy and flexibility. Duck typing lets a -function work over any object that responds to its messages, which programmers value for reuse, -shorter code, and rapid prototyping -([SitePoint, *Making Ruby Quack*](https://www.sitepoint.com/making-ruby-quack-why-we-love-duck-typing/)). -Prototypal inheritance lets objects be created, linked, and reshaped at runtime, and hooks such as -`method_missing` let one object answer messages it was never written to handle. Their costs, as their -users state them, follow from the same deferral. A mistake surfaces as a runtime error discovered only when the -offending line runs, which makes refactoring hazardous, and the standard mitigation is tests or a -`respond_to?` guard ([DevGex, *Duck Typing*](https://devgex.com/en/article/00035033)). The vtable -indirection defeats inlining, and dictionary-based lookup is worse, which is why so much engineering -goes into inline caches ([V8](https://v8.dev/docs/hidden-classes)). A mutable prototype chain is easy -to get confused about, and JavaScript's `this` binding, the same self-binding that makes delegation -work, is lost when a method is detached from its receiver and called on its own. - -CGP's costs are the ones dynamic dispatch exists to avoid. It cannot hold a heterogeneous collection -of implementations and choose among them at runtime; Rust's `dyn Trait` exists for that. It -cannot load an implementation chosen at runtime from configuration, patch a live object, or answer a -message it was not built to handle, because there is no runtime object graph and no runtime dispatch -to intercept. Its wiring is code somebody writes. And its errors, though caught early, are trait-solver -output over generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause -for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. -The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the -alternatives. +Dynamic dispatch supports runtime choice, including mixed collections of implementations. +Dynamically typed languages also allow programs to accept objects without an explicit interface +declaration, and mutable object systems can change behavior while running. Those freedoms are +useful for interactive work and runtime extensibility. + +Dynamic typing can defer unsupported-operation errors until execution. That cost does not apply +to every form of dynamic dispatch: Rust checks a trait object's interface at compile time. +Runtime lookup and indirect calls also have costs, though optimizations can reduce them. +Prototype mutation and call-dependent `this` binding add separate reasoning demands, as the +[MDN guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain) +explains. + +CGP moves implementation selection into compilation and requires declarations and wiring to express +it. The learning cost includes tracing consumer traits through provider tables; the compile-time +cost includes trait resolution and monomorphization. Static wiring itself cannot discover plugins, +replace a provider on a live value, or handle an undeclared operation. Those features need other +runtime mechanisms, which CGP code can use alongside its wiring. + +CGP's raw diagnostics expose generated traits and types. +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) compares these costs with ordinary +traits, generics, and trait objects. ## Where runtime dispatch is the better choice -When a program needs runtime openness, plugins discovered at startup, objects of mixed types in one -collection, behavior reshaped live, or the metaprogramming that proxies and DSLs rely on, dynamic -dispatch is the right tool, and emulating it with compile-time wiring is impossible rather than -awkward, since the whole point is deferral to runtime. In Rust that means `dyn Trait`, and a CGP -context may hold one. CGP is the better tool when the set of implementations is known at build time -and the program wants the decoupling of dynamic dispatch with none of the cost or the runtime failure -modes. +Runtime dispatch fits implementations chosen while the program runs, such as mixed collections or +runtime-selected services. Dynamic object systems additionally support changing object behavior +and intercepting otherwise unknown messages. Plugin loading requires an appropriate loading and +interface mechanism as well as dispatch; a vtable alone does not provide it. -## What to expect that differs +Rust's `dyn Trait` is useful for runtime polymorphism and can coexist with CGP. A context may hold a +trait object, or a dyn-compatible consumer trait may be used as a trait object. CGP wiring fits +implementation choices known at build time, where reusable providers justify the additional tables. -**Nothing happens at runtime.** A reader from this background will assume a vtable is a data -structure the program carries, that dispatch chooses at the moment of the call, that a prototype chain -is walked when a property is missing, and that the object graph can change while the program runs. In -CGP the table is erased after compilation, the type checker resolves the dispatch and the compiler -inlines it, the chain is walked during type resolution, and the wiring is fixed once the program is -built. +## What to expect that differs -**Late binding is late to the wiring site, not to runtime.** The flexibility is real, and it is spent -at compile time, at the place a context declares its providers. +CGP resolves wiring during compilation, while provider bodies execute at runtime. +Static selection removes the wiring lookup from execution; it does not guarantee that every call +is inlined or that the provider's work is free. -**A missing method is a compile error.** A context that lacks a trait a provider needs fails at the -wiring site, named by `check_components!`, rather than as a `NoMethodError` in production. +The context type fixes its provider choices. Two values of that type can contain different state, +but changing their fields does not rewrite the type's wiring. Runtime variation must be expressed +through the selected implementation or another Rust dispatch mechanism. -**A namespace's bound entries cannot be shadowed.** The inherit-and-customize pattern works through -slots the namespace leaves open, not through override. +A dependency check catches missing declared operations before execution. +`check_components!` forces validation at the check site; a wiring declaration alone is lazy. +This is a guarantee about declared dependencies, not about every possible runtime failure. -**CGP is not a dynamic language with the types added.** It is the static resolution of the mechanisms -this reader knows, trading runtime malleability for zero cost and compile-time safety. +Namespaces preserve bindings that are already defined. Contexts and child namespaces customize +paths left unbound rather than shadowing inherited entries. This restriction follows from the +ordinary trait impls used to represent wiring. ## Where to go next -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): how a call finds its - provider through the table. +These pages explain the static mechanisms and related comparisons: + +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): how a call reaches + its provider. - [Aggregate providers](/docs/concepts/aggregate-providers) and [Namespaces](/docs/concepts/namespaces): - the delegation chain and the shared table. -- [Row polymorphism](./row-polymorphism.md): the type-system side of duck typing, structural versus - nominal. -- [Reflection](./reflection.md): the introspection counterpart to this page's runtime mechanisms. + sharing and following wiring tables. +- [Row polymorphism](./row-polymorphism.md): structural interfaces and field requirements. +- [Reflection](./reflection.md): inspecting data and types at compile time or runtime. ## Sources The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per -wired context. This page shows no code in another language. +wired context. This page contains only Rust snippets. +- [The Rust Reference, *Trait object types*](https://doc.rust-lang.org/reference/types/trait-object.html): trait-object pointers and dynamic dispatch. +- [Python glossary, *Duck typing*](https://docs.python.org/3/glossary.html#term-duck-typing): using an object through the operations it supports. - [Wikipedia, *Dynamic dispatch*](https://en.wikipedia.org/wiki/Dynamic_dispatch), [*Virtual method table*](https://en.wikipedia.org/wiki/Virtual_method_table), and [*Duck typing*](https://en.wikipedia.org/wiki/Duck_typing): late binding, the vtable, and usability decided by the methods an object has. - [The Rust Programming Language, *Trait objects*](https://doc.rust-lang.org/book/ch18-02-trait-objects.html) and [geo-ant, *Rust Dyn Trait Objects and Fat Pointers*](https://geo-ant.github.io/blog/2023/rust-dyn-trait-objects-fat-pointers/): Rust's own dynamic dispatch as a fat pointer and a vtable. - [Lieberman, *Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems* (OOPSLA 1986)](https://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html): delegation, and the rule that `self` stays bound to the original receiver. diff --git a/docs/comparisons/implicit-parameters.md b/docs/comparisons/implicit-parameters.md index 3e3b3541..f1b1cc0c 100644 --- a/docs/comparisons/implicit-parameters.md +++ b/docs/comparisons/implicit-parameters.md @@ -1,46 +1,45 @@ --- sidebar_label: 'Implicit parameters' sidebar_position: 5 -description: "CGP read against Scala's given and using, Haskell's ImplicitParams, and the type-class resolution both build on." +description: 'Compare CGP context fields and wiring with Scala contextual parameters, Haskell implicit parameters, and type-class selection.' --- # Implicit parameters -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows -implicit parameters: Scala's `given` and `using`, Haskell's `ImplicitParams`, and the type-class -resolution both languages build on. CGP shares the goal of threading context through code without -explicit plumbing, and supplies the values from a context's fields and wiring rather than from a -compiler-driven search. The page covers the correspondence, the coherence trade underneath it, where -implicit resolution remains the better tool, and what to expect that differs. +CGP supplies implicit arguments from a context's fields and selects implementations through wiring. +It is a language extension for Rust, with pluggable trait implementations at compile-time, +implemented as a library on stable Rust whose consumer traits are ordinary Rust traits; the +[Introduction](/docs/) explains the basics. For readers familiar with Scala's `given` and `using`, +Haskell's `ImplicitParams`, or `Reader`, this page compares how dependencies travel through a +program, how implementations are selected, and what each approach costs. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. It is the implicit environment you already reason about, the set of `given`s in scope or -the `Reader` you thread, made a single explicit type that every provider receives. +A **context** is the type a CGP method runs on, supplying data through fields and implementations +through wiring. It gives providers an explicit environment through `self`. This serves some of the +same purposes as contextual parameters or a `Reader` environment, with the available fields and +provider choices determined by the context's type. | In Scala or Haskell | In CGP | | --- | --- | | A `using` parameter or a `?x` implicit parameter | An `#[implicit]` argument, read from a context field | -| A `given` value in scope | A field of the context | -| A type class | A **component**: one trait with many possible implementations | -| An instance | A **provider**: a named implementation | -| Instance resolution by the compiler | **Wiring**, written in a `delegate_components!` table | -| A functional dependency (`m -> e`) or associated type family | An abstract type, chosen by the context | +| An implicit environment value | A field of the context | +| A type-class interface | A consumer trait within a **component** | +| A type-class implementation | A **provider**: a named implementation | +| Instance selection | **Wiring**, written in a `delegate_components!` table | +| A functional dependency (`m -> e`) or associated type family | An abstract type determined by the context | ## The idea, briefly -Some values are needed everywhere and interesting nowhere: a configuration, a logger, a comparison -strategy, an error type. Passing them through every function that transitively needs them clutters -signatures and forces intermediate functions to forward parameters they only pass along. Implicit -parameters remove that: the caller omits the argument, the compiler fills it in from scope, and the -declaration still records the dependency in the type. +Implicit parameters let callers omit arguments that the compiler can supply from the surrounding +scope. Configuration, loggers, and comparison strategies can pass through a call chain without an +explicit argument at every call. Functions still declare the dependencies in their types, and the +language's resolution rules determine which values reach them. ### Context parameters in Scala -Scala 3 marks a parameter list `using`, and the compiler supplies a matching `given` from scope: +Scala 3 marks a contextual parameter list with `using`. When a caller omits that list, the compiler +searches for matching `given` values: ```scala case class Config(port: Int, baseUrl: String) @@ -55,10 +54,11 @@ given Config = Config(8080, "docs.scala-lang.org") renderWebsite("/home") // the given Config is supplied automatically ``` -The same mechanism serves type classes. A `given` can be defined for a type, and a method with a -`using` parameter of that type resolves the instance from the call site. Scala 3.6 changed the syntax -for a given with a body to a colon form; the older `given Comparator[Int] with` is still accepted -([Scala 3 Reference, *Given Instances*](https://docs.scala-lang.org/scala3/reference/contextual/givens.html)): +Scala uses contextual parameters for type classes as well as configuration values. A +`given Comparator[Int]` supplies the implementation required by a `using Comparator[A]` parameter. +Scala 3.6 introduced the colon form for a given with a body; the older +`given Comparator[Int] with` form is also accepted. See the +[Scala reference](https://docs.scala-lang.org/scala3/reference/contextual/givens.html). ```scala trait Comparator[A]: @@ -73,17 +73,17 @@ def max[A](x: A, y: A)(using c: Comparator[A]): A = max(1, 2) // Comparator[Int] resolved and passed implicitly ``` -Scala 2 wrote all of this with the single `implicit` keyword, and Scala 3 split it into `given` and -`using` because the one keyword was overloaded -([Baeldung, *Scala 3 Implicit Redesign*](https://www.baeldung.com/scala/scala-3-implicit-redesign)). -Rust's own contexts-and-capabilities proposal is the nearest thing to a `using Config` for Rust; the -[Rust proposals](./rust-language-proposals.md) page compares it. +Scala's selection depends on scope as well as type. Different scopes can supply different givens +for the same requested type, and a caller can pass a contextual argument explicitly. CGP's +per-context choice therefore differs in how it is recorded, rather than being a choice Scala cannot +express. Scala 2 uses `implicit` where Scala 3 distinguishes `given` definitions from `using` +parameters. Rust's proposed equivalent is discussed in [Rust's own proposals](./rust-language-proposals.md). ### Implicit parameters in Haskell -Haskell's `ImplicitParams` extension is the more literal form. A function names a dynamically bound -variable `?x`, which appears as a constraint on its signature and is filled from the binding in -scope. This version uses the real `Data.List.sortBy` and compiles with GHC 9.10: +Haskell's `ImplicitParams` extension binds named parameters such as `?cmp` through constraints. +The following example passes a comparison function to `sort` and `least`, then supplies it in a +`let` binding: ```haskell {-# LANGUAGE ImplicitParams #-} @@ -99,35 +99,35 @@ min' :: Ord a => [a] -> a min' = let ?cmp = compare in least ``` -The constraint propagates to any caller that does not bind it, and a `let` binding discharges it. -The GHC User's Guide records the restrictions: the constraints leak into every signature, there is no -way to declare a default, an implicit parameter may not appear in a class or instance context, and the -monomorphism restriction applies -([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/implicit_parameters.html)). -Haskell programmers reach for the `Reader` monad or for type classes instead. +The `?cmp` constraint propagates to callers that do not supply a binding. The extension does not +provide default bindings, and implicit parameters cannot appear in class or instance declaration +contexts. Type inference and the monomorphism restriction also affect which bindings remain +polymorphic. The [GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/implicit_parameters.html) +explains these restrictions. `Reader` and type classes offer other ways to pass dependencies in +Haskell, with different rules for binding and propagation. ### Type classes as implicit dictionary passing -Type classes are the mechanism both languages use for implicit resolution in practice. A `class` -declares an interface, an `instance` provides it for a type, and a constrained call receives the -instance as a hidden *dictionary* argument. The resolution is type-directed and automatic, and it is -governed by *coherence*: for a given type there is exactly one instance, so the compiler can inject -it silently without two pieces of code disagreeing. Its price is the one CGP was built to escape. A -program cannot have two legitimate orderings of `Int` as first-class instances without a `newtype`, -and a module cannot add an instance for a type and class it does not own. The -[type classes](./type-classes.md) page develops the mechanism and its extensions. +Type classes pass implementations as implicit dictionaries of methods. A class declares an +interface, an instance implements it for a type, and a constrained function receives the selected +dictionary. This explains how generic code can invoke an operation without naming its implementation. + +Haskell and Scala differ in how they select those dictionaries. Haskell ordinarily uses a global +instance for a class and its type arguments, with overlapping instances controlled by extensions. +Scala selects contextual values using scope and priority rules. Coherence concerns whether valid +resolutions agree in meaning; global instance uniqueness is one way to support it, rather than a +rule shared unchanged by both languages. The [type classes](./type-classes.md) comparison develops +these distinctions. ## How CGP expresses it -CGP threads context through code and lets deep code read what it needs, through the context that is -already the `self` of every provider rather than through a scope search. Two constructs map onto the -two forms of implicit parameter: an `#[implicit]` argument corresponds to an implicit *value* -parameter, and a component with its wiring corresponds to a type class. +CGP makes a context available to generic implementations through `self`. An `#[implicit]` argument +reads a value from that context, while component wiring selects an implementation. Both choices are +checked through Rust traits; neither requires searching the caller's lexical scope for a value. -### Implicit arguments are implicit value parameters +### Implicit arguments read named context fields -An `#[implicit]` argument is written as an ordinary function parameter but is supplied from the -context's fields rather than by the caller: +An `#[implicit]` parameter names a field that the implementation reads from its context: ```rust #[cgp_fn] @@ -142,34 +142,30 @@ pub struct Rectangle { } ``` -Where Scala's `renderWebsite` obtains its `Config` from a `given`, this function obtains `width` and -`height` from the context threaded through it as `self`. The parameter disappears from the public -signature and is bound from the surroundings before the body runs, which is why CGP calls the feature -by the same name. The difference is where "the surroundings" live. A `using` parameter searches the -implicit scope by type; an `#[implicit]` argument reads the context field of the matching name, so -resolution is by *field*, decided when the context is defined. `Rectangle` here is a **value -context**: the type carrying `width` and `height` is the rectangle itself. The -[Implicit arguments](/docs/concepts/implicit-arguments) page develops the construct. - -### A shared context value is a threaded environment - -When several pieces of code must agree on one value, Scala uses a single `given Config` and Haskell -the `Reader` monad. CGP has them all read the same field or the same abstract type from the shared -context. CGP's error type is the standing instance: every fallible provider imports the context's -error type with `#[use_type(HasErrorType.Error)]` and names it as the bare `Error`, so all of them -agree on one type the context supplies once. That is a threaded `Reader` environment at the type -level, resolved at compile time. - -### Abstract types are implicit type parameters - -The correspondence runs one level up, and a reader from these languages will recognize this half -fastest. An [abstract type](/docs/concepts/abstract-types) is a type the context determines rather -than one a caller supplies. Haskell's `mtl` achieves the same with a functional dependency: in -`class MonadReader r m | m -> r` the environment type is fixed *by* the monad, and -`MonadError e m | m -> e` says the same for the error type -([`mtl`, `Control.Monad.Error.Class`](https://hackage.haskell.org/package/mtl/docs/Control-Monad-Error-Class.html)). -An associated type family states it more directly still, and is the closest thing in either language -to a `#[cgp_type]` component: +`rectangle_area()` obtains `width` and `height` from `self`, so callers omit both arguments. +`Rectangle` is a value context: the rectangle itself holds the data the method operates on. +The generated implementation requires field access with the matching names and types. Scala's +`using Config` instead asks the compiler to resolve a contextual value by type; Haskell's `?cmp` +refers to a named implicit binding. The +[Implicit arguments](/docs/concepts/implicit-arguments) page explains CGP's field access and borrowing. + +### A shared context carries a common environment + +Several providers can read the same runtime value from a shared context. For example, a context +can store configuration once and expose it to each implementation that declares the corresponding +field dependency. This serves the environment-passing role of `Reader` without requiring each +intermediate call to forward individual values. + +A context can also determine types shared by its providers. Fallible implementations can import +`HasErrorType.Error` and use the alias `Error`, agreeing on the type selected for that context. +Runtime fields and associated types serve different roles, but both keep related choices attached +to one context. + +### Abstract types are determined by the context + +A CGP [abstract type](/docs/concepts/abstract-types) is an associated type supplied by the context. +Haskell's functional dependencies express a related relationship: `m -> e` in `MonadError` says +that the monad determines its error type. These declarations illustrate the two forms: ```haskell class Monad m => MonadError e m | m -> e where @@ -183,21 +179,23 @@ pub trait HasErrorType { } ``` -Both exist for the same reason. A plain type *parameter* propagates: a signature that mentions `e` -and `r` carries them through every intermediate function that only passes a value along, as a Rust -generic function's `where` clause does. Making the type determined by the context, whether by a -functional dependency, an associated type, or a CGP abstract type, stops it propagating, because a -determined type is an output rather than an input. Two differences follow the same axes as the value -case. On *selection*, an `mtl` instance for a given monad is unique program-wide, whereas CGP's is a -wiring entry and two contexts may bind the same abstract type differently. On *propagation*, CGP -hides more: a CGP consumer trait declares the abstract-type trait as a supertrait, so a caller -bounding on the consumer gets it implied without restating it. +Both forms avoid making the error type an independent choice at every use. Haskell determines `e` +from `m`; Rust refers to the associated `Error` of the context. A CGP consumer trait can require +`HasErrorType` as a supertrait, making that requirement available to generic callers through their +consumer-trait bound. The type dependency still exists; its relationship to the context makes it +unnecessary to carry a separate error-type parameter. + +Different contexts can select different error types, just as different Haskell monads can determine +different error types. CGP additionally lets a context choose the provider for its abstract-type +component through the same wiring mechanism it uses for operations. See +[`mtl`'s `MonadError` documentation](https://hackage.haskell.org/package/mtl/docs/Control-Monad-Error-Class.html) +for the functional-dependency form. -### Components and wiring are type classes without coherence +### Components and wiring make instance selection explicit -A CGP component is a type class, a provider is an instance, and wiring is the resolution step. Because -a provider's `Self` is its own marker type, many providers for the same component coexist, which -instances cannot do. Two encoders that both apply to `Vec` are selected per context: +CGP gives each interchangeable implementation its own provider type. Rust therefore treats these +as distinct impls, even when both providers support the same target. The following fragments define +two encoders and select one for each application: ```rust #[cgp_component(Encoder)] @@ -234,76 +232,77 @@ delegate_components! { } ``` -The `Comparator[Int]` that Scala can define once becomes any number of interchangeable providers, -each selected per context. `AppA` and `AppB` are **environmental contexts**, types standing for an -application, and the component is parameter-targeted: `Self` is the application and the encoded value -is the `Value` parameter. The freedom has the cost the type-class trade predicts: CGP will not -*find* the provider for you by type. A context names its choice in a table, where Scala and -Haskell would resolve the instance from the type. +`AppA` encodes `Vec` as hexadecimal text; `AppB` copies its bytes. Both are environmental +contexts representing applications. The component is parameter-targeted: `Value` is the data being +encoded, while `self` supplies the application's choice of implementation. + +CGP records the provider choice in a wiring table and keeps Rust's coherence checks. Separate +provider types let alternatives coexist; they do not permit conflicting entries for the same key +on one context. Scala can express alternative implementations through scoped givens, while CGP +attaches the selection to the context type. ## What each approach costs -Implicit parameters and the type classes built on them are valued for erasing boilerplate: a -`Config` or a comparator threads through a deep call graph without appearing at every call, and one -generic function works over any type with an instance. Their costs, as their users state them, come -from the same generality. The recurring Scala complaint is that a value appears from nowhere, and tracking -down which `given` was selected, or why an expected one was not, takes time; Scala 2's single -overloaded keyword made it worse, and Scala 3 split the keyword apart to address it -([Baeldung](https://www.baeldung.com/scala/scala-3-implicit-redesign)). Haskell's `ImplicitParams` -is little used for the concrete reasons its manual records: leaking constraints, no defaults, and the -monomorphism restriction -([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/implicit_parameters.html)). -And coherence itself is a persistent source of friction: the orphan rule shapes module structure, and -the one-instance-per-type limit forces `newtype` wrappers whenever a second interpretation of a type -is wanted ([Yang, 2014](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). - -CGP pays with the wiring itself. There is no automatic search, so the choice must be written down, -once per context, and a component must be declared before it can have providers. The compile-time -work is real. And the raw diagnostics are trait-solver output over generated types: -[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the -alternatives. +Implicit resolution reduces argument passing but requires readers to trace the selected binding. +Scala's givens can come from local scope, imports, or implicit scope, so understanding a call may +require following the search rules. The +[Scala reference](https://docs.scala-lang.org/scala3/reference/contextual/using-clauses.html) +describes how arguments are supplied. Haskell's `ImplicitParams` makes dependencies visible as +constraints, which must propagate until a binding supplies them; its inference restrictions can +also affect behavior. See the +[GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/implicit_parameters.html). + +Global type-class instances favor a canonical interpretation of a type. In Haskell, an alternative +ordering or rendering often needs a `newtype` to distinguish it from the existing instance. +That trade differs from Scala's scoped selection. The +[coherence analysis by Yang](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/) +separates global uniqueness from coherence and confluence. + +CGP requires component declarations and provider selection through wiring or declared defaults. +This adds code to maintain and trait-resolution work during compilation. Tracing a selection can +also require following delegation through several tables. Raw diagnostics expose generated traits +and types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it +recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) weighs these costs against simpler forms. ## Where implicit resolution is the better choice -When a program wants one canonical instance per type, one `Ord`, one `Show`, one serialization, and -values automatic resolution above all, type classes are the better tool, and fighting their coherence -with CGP-style wiring would be over-engineering. The same holds in Rust: a trait with one -implementation per type is an ordinary trait. CGP's explicit wiring is the better tool when a program -needs several interchangeable implementations, per-deployment or per-context choice, or must -implement a behavior for types and traits it does not own. +Implicit resolution fits code that benefits from the surrounding language's instance conventions +or local contextual bindings. Haskell type classes work well for a canonical ordering or rendering; +Scala's givens support contextual choices without a separate CGP-style wiring table. Within Rust, +an ordinary trait is sufficient when one implementation per type expresses the intended behavior. + +CGP helps when Rust code needs separately reusable implementations and explicit choices per context. +Those benefits must justify its additional declarations. It does not replace the scope rules or +inference mechanisms of Scala and Haskell. ## What to expect that differs -**CGP does not find the provider by type.** A reader used to `given` resolution will expect the -compiler to locate the implementation. In CGP the provider is named in a table, once per context. -Because CGP does not resolve by type, it is free of coherence, and that freedom lets it host the -overlapping instances these languages forbid. +CGP selects providers through type-level wiring, including any declared defaults and delegation. +It does not search a caller's scope for an implicit value. Rust still rejects overlapping impls; +CGP separates implementations by giving them distinct provider types. -**Which implementation was chosen is a line you can read.** The value still arrives without being -threaded by hand, but the choice is a wiring entry rather than the outcome of a scope search, so there -are no priority rules and no ambiguity to debug. +A provider choice can be traced from a context's wiring. A direct entry names it immediately; +forwarding entries and namespaces require following the route. Explicit wiring makes the route +inspectable without making every route short. -**An abstract type is chosen per context, not per type.** An `mtl` instance fixes the environment -type once for a monad program-wide. A CGP abstract type is a wiring entry, and two contexts may bind -it differently. +An abstract type is determined by the context type. Two contexts may choose different error types, +but two values of the same concrete context type share the same associated error type. -**Resolution is by field name, not by type.** An `#[implicit]` argument reads the context field with -the matching name. Two fields of the same type are distinct arguments, where a `using` parameter of -that type would be ambiguous. +An implicit argument selects a field by name and checks its type. Two fields of the same type can +supply distinct arguments, such as `width` and `height`. Scala's contextual search instead resolves +a requested type using its scope and priority rules. ## Where to go next -- [Implicit arguments](/docs/concepts/implicit-arguments): the construct this page maps onto a - `using` parameter, with its borrowing rules. -- [Abstract types](/docs/concepts/abstract-types): why a determined type propagates nowhere while a - parameter propagates everywhere. -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): how a provider's requirements - stay out of the caller's signature. -- [Type classes](./type-classes.md): the coherence trade in full. -- [Rust's own proposals](./rust-language-proposals.md): the contexts-and-capabilities proposal as - Rust's `using Config`. +These pages develop the mechanisms and related comparisons: + +- [Implicit arguments](/docs/concepts/implicit-arguments): field selection and borrowing rules. +- [Abstract types](/docs/concepts/abstract-types): types determined by a context. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): keeping implementation + requirements out of a consumer interface. +- [Type classes](./type-classes.md): dictionary passing and instance selection. +- [Rust's own proposals](./rust-language-proposals.md): the contexts-and-capabilities proposal. ## Sources @@ -315,7 +314,7 @@ context. - [Baeldung, *Scala 3 Implicit Redesign*](https://www.baeldung.com/scala/scala-3-implicit-redesign): the rename from `implicit` to `given`/`using` and the reasons for it. - [GHC User's Guide, *Implicit Parameters*](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/implicit_parameters.html): the `?x` syntax, `let` binding, propagation, and the documented restrictions. - [Type class (Wikipedia)](https://en.wikipedia.org/wiki/Type_class) and [okmij.org, *Implementing, and Understanding Type Classes*](https://okmij.org/ftp/Computation/typeclass.html): type classes as dictionary-passing elaboration. -- [Yang, *Type classes: confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/) and [Bottu et al., *Coherence of Type Class Resolution*](https://xnning.github.io/papers/coherence-class.pdf): the definition of coherence and why it constrains instances to one per type. +- [Yang, *Type classes: confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/) and [Bottu et al., *Coherence of Type Class Resolution*](https://xnning.github.io/papers/coherence-class.pdf): the distinctions between coherence, confluence, and global instance uniqueness. - [`mtl`, `Control.Monad.Error.Class`](https://hackage.haskell.org/package/mtl/docs/Control-Monad-Error-Class.html): the `MonadError e m | m -> e` functional dependency. --- diff --git a/docs/comparisons/index.md b/docs/comparisons/index.md index 2909d622..1b61b990 100644 --- a/docs/comparisons/index.md +++ b/docs/comparisons/index.md @@ -1,22 +1,25 @@ --- sidebar_label: 'Overview' sidebar_position: 0 -description: 'CGP placed against the ideas its readers already know, one page per idea.' +description: 'Compare CGP with familiar programming models through vocabulary, examples, trade-offs, and limits.' --- # Comparisons -CGP is a language extension for Rust, with pluggable trait implementations at compile-time. It is a -library on stable Rust, and a CGP trait is an ordinary Rust trait; the [Introduction](/docs/) says -what that means. These pages are for a reader who already knows a related idea from another language -or paradigm and wants CGP placed in it. Each page maps CGP into that idea's vocabulary, shows the two -side by side in code, states what each costs, and says where the reader's own tool is the better -choice. +These pages explain CGP through related ideas you may already know: dependency injection, +type classes, effect handlers, dynamic dispatch, and other approaches to reusable implementations. +Each comparison maps the vocabulary, illustrates the mechanisms, and explains the costs and cases +where the other approach fits better. + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time. +It is a library on stable Rust, and its consumer traits are ordinary Rust traits. The +[Introduction](/docs/) explains those foundations; the comparisons focus on how they relate to +other programming models. ## Which page to read -Start from what you already know. The first two pages are the ones a Rust programmer compares CGP -to before anything else; the rest are grouped by the tradition they come from. +Choose the page that matches your background. Rust's proposals and C++ policy-based design come +first, followed by type-system concepts, dependency injection, and runtime or security mechanisms. | If you know | Read | | --- | --- | @@ -34,16 +37,14 @@ to before anything else; the rest are grouped by the tradition they come from. ## What every page shares -Each page follows the same shape, so a reader who has read one can skim the next by habit. It opens -with a short table that maps the idea's vocabulary onto CGP's. It refreshes the idea in a few cited -snippets, shows the same problems written in CGP, and names which of CGP's context shapes each -snippet uses. It then states what each approach costs, in the words its own community uses for its -costs, and gives the cases where the compared tool is the better choice their own section. A closing -section lists the expectations a reader of that background holds that CGP does not meet, each with -the reason CGP is arranged as it is. +Each page begins with a vocabulary map and a brief account of the related idea. It then shows +how CGP expresses comparable behavior, identifies the context and target in its examples, and +explains where the analogy stops. Separate sections cover costs, cases favoring the other tool, +and behavior that may differ from your expectations. -Every page cites its sources, and every snippet in another language was compiled against the -toolchain the page names. The CGP code on every page compiles against the current release. +Each comparison cites its sources and records how its examples were checked. The Sources section +distinguishes compiled snippets from examples checked against documentation or taken from a +proposal. CGP examples have compiled counterparts in the website's verification suite. ## Where to go next diff --git a/docs/comparisons/ml-modules.md b/docs/comparisons/ml-modules.md index e65488be..b27c01a2 100644 --- a/docs/comparisons/ml-modules.md +++ b/docs/comparisons/ml-modules.md @@ -6,45 +6,44 @@ description: 'CGP read against OCaml and Standard ML signatures, structures, fun # ML modules and modular implicits -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows -the signature, structure, and functor system of OCaml or Standard ML, and the *modular implicits* -extension that adds type-directed resolution over it. CGP's components, providers, and higher-order -providers line up with signatures, structures, and functors, and CGP replaces the manual, ordered -functor application that assembling a large ML program requires with a declarative wiring table. The -page covers that correspondence, the one thing ML does that CGP does not, and what an ML reader -should expect to differ. +CGP lets Rust programs assemble named implementations through a context's wiring table. For an +ML programmer, its components, providers, and higher-order providers play roles similar to +signatures, structures, and functors. The correspondence explains how to compose implementations; +ML's sealing and module type identities need a separate account. + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time. It is +implemented as a library on stable Rust, and its consumer traits are ordinary Rust traits. The +[Introduction](/docs/) covers the basics. This page assumes familiarity with OCaml or Standard ML +modules and also compares the proposed OCaml modular-implicits extension. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. In most CGP code it is a type you define to stand for an application, and it is where the -functor applications an ML program writes by hand are recorded instead. +A **context** is the type on which CGP's consumer methods operate. It supplies runtime data and +selects providers for its components. An application context can gather the choices that an ML +program records through module bindings and functor applications. + +The vocabulary maps by role, with limits explained below: | In ML | In CGP | | --- | --- | -| A signature | A **component**: one trait with many possible implementations | -| A structure ascribing to it | A **provider**: a named implementation | -| A functor | A **higher-order provider**, parameterized by another provider | -| A signature's abstract `type t` | An abstract type, chosen by the context through `#[cgp_type]` | -| The sequence of functor applications | The **wiring table**, written with `delegate_components!` | -| Checking an argument against a functor's parameter signature | `check_components!` at the wiring site | -| Modular implicits' type-directed search | Nothing: the table names each choice | +| A signature | A **component** declaring an interface | +| A structure satisfying a signature | A **provider** implementing a declared provider trait | +| A functor | A **higher-order provider** parameterized by providers | +| An abstract `type t` in a signature | An associated type supplied through an abstract-type component | +| Module bindings and functor applications assembling a program | Provider choices in `delegate_components!` | +| Checking a functor argument against its signature | Provider trait bounds, with `check_components!` checking a concrete context's dependencies | +| Modular implicits' type-directed selection | Explicit provider selection per context and component | ## The idea, briefly -ML modules build large programs from interchangeable, separately specified parts with real type -abstraction. A *signature* states what a component provides without fixing representations, a -*structure* implements it, and a *functor* is a module parameterized by another module. The module -system is widely regarded as one of the most expressive in any language -([Dreyer, *Understanding and Evolving the ML Module System*](https://people.mpi-sws.org/~dreyer/thesis/main.pdf)). -The snippets below are OCaml, compiled with OCaml 5.5.0, except the modular-implicits one, which -follows the proposal paper because that extension has never shipped in mainline OCaml. +ML modules separate an implementation from the interface its clients can use. Signatures describe +types and operations, structures supply them, and functors build modules from other modules. This +separation supports reusable implementations and representation hiding. ### Signatures, structures, and abstract types -A signature specifying an abstract type `t` and a `compare` over it, and a structure implementing it: +A signature can require operations on a type without exposing the type's representation. Here, +`OrderedType` requires a type `t` and a comparison operation, while `StringCompare` supplies both: ```ocaml module type OrderedType = sig @@ -58,15 +57,14 @@ module StringCompare = struct end ``` -The `type t` left without a definition is the core of ML data abstraction. When a structure is -*sealed* with a signature that keeps `t` abstract, clients cannot see the representation, and the -type system enforces representation independence -([*Modules and Data Abstraction in OCaml*](https://cs.wellesley.edu/~cs251/s12/handouts/modules.pdf)). -Sealing hides a *known* type's representation rather than abstracting over an unknown one. +`StringCompare.t` remains visibly equal to `string` in this example. Ascribing the structure to a +signature that leaves `t` abstract would hide that equality from clients. This is the distinction +between providing a type and sealing its representation behind an interface. ### Functors -A functor takes a module of some signature and produces a module built on top of it: +A functor makes a module depend on another module through a signature. The following skeleton +shows the application shape; OCaml's `Set.Make` supplies the complete set implementation: ```ocaml module Make (O : OrderedType) = struct @@ -76,30 +74,32 @@ end module StringSet = Make (StringCompare) ``` -The application is explicit and by name, and OCaml's standard library uses the shape throughout, as -in `Set.Make(String)` ([OCaml, *Functors*](https://ocaml.org/docs/functors)). Two subtleties make -functors heavier than the shape suggests. When a functor result's abstract type must be known to -equal another type, the programmer writes a *sharing constraint* with `with type`, a recurring source -of type errors. And OCaml functors are *applicative* by default while SML's are *generative*, so -whether two applications yield equal abstract types depends on the language and on a trailing `()` -argument ([OCaml manual](https://ocaml.org/manual/5.5/firstclassmodules.html)). +`Make (StringCompare)` explicitly chooses the implementation of the dependency. When clients need +to know that a result type equals an argument type, a signature can expose that equality with a +constraint such as `with type elt = O.t`. These equalities let independently described modules +exchange values of the same type. [OCaml's functor guide](https://ocaml.org/docs/functors) develops +the set example and dependency injection through modules. + +Functor application also determines which abstract types are equal. OCaml's applicative functors +can preserve result type equality across applications to the same module path. Generative functors +can introduce fresh type identities; OCaml provides unit-parameter functors for this purpose. +Standard ML uses generative semantics, but an explicitly shared or manifest type need not become +fresh at every application. The distinction concerns type identity, not merely the syntax for +calling a functor. See the [OCaml manual on generative functors](https://ocaml.org/manual/5.5/generativefunctors.html). -### Assembling a program: manual functor plumbing +### Assembling a program -Building a whole application from functors means applying each one by hand, in dependency order. -The MirageOS project makes the cost concrete: the unikernel running its website "contains more than -70 modules and a functor application depth of up to 10", and the community built a DSL, Functoria, -to organize the applications, because "OCaml's module language is much less flexible than its -expression language" ([*Functor Driven Development*](https://arxiv.org/pdf/1905.02529)). A mature -ecosystem writing a configuration DSL to escape manual functor application is the clearest evidence -of the limitation CGP's wiring addresses. +A large graph of functor applications can require substantial configuration code. MirageOS uses +Functoria to describe and assemble such graphs, including configuration choices. Its authors' +[*Functor Driven Development*](https://arxiv.org/pdf/1905.02529) paper explains the application +structure that motivated the tool. This is a useful comparison for CGP's wiring, though Functoria +also handles concerns beyond selecting an implementation for an interface. ### Modular implicits -Modular implicits extends OCaml so that module arguments can be marked implicit and resolved by type. -A function takes an implicit module parameter in braces, and the compiler searches the implicit -modules in scope for one of the required signature -([White, Bour & Yallop, *Modular implicits*](https://arxiv.org/abs/1512.01895)): +Modular implicits proposes automatic selection of module arguments from implicit modules in scope. +The function declares an implicit module parameter, and resolution uses the signature and type +constraints to find an argument: ```ocaml module type Show = sig @@ -124,26 +124,32 @@ let () = print_endline (show [1; 2; 3]) (* resolves Show_list(Show_int) *) ``` -`Show_list` is an *implicit functor*, applied during resolution, which is the module-system -counterpart of Haskell resolving `Show [Int]` from `Show Int`. The proposal remains an -[experimental fork](https://github.com/ocamllabs/ocaml-modular-implicits). +`Show_list` composes an implementation for lists from an implementation for their elements. In this +example, resolution applies it to `Show_int`. The proposal allows different implementations in +different scopes; it does not require a single global instance for each type. Resolution must +still reject ambiguous choices. See [White, Bour, and Yallop's proposal](https://arxiv.org/abs/1512.01895). -### Classes as signatures +This syntax belongs to the modular-implicits proposal and its +[experimental implementation](https://github.com/ocamllabs/ocaml-modular-implicits). It is not a +standard OCaml example. The other OCaml snippets retain the verification record in Sources. -The mapping this page rests on is a known result. Dreyer, Harper, and Chakravarty's *Modular Type -Classes* treats classes as signatures and instances as structures and functors -([*Modular Type Classes*](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf)). The -[type classes](./type-classes.md) page develops the result and the canonicity-versus-modularity -tension it exposes. +### Modules and type classes + +The relationship between module interfaces and type-class interfaces has a formal precedent. +Dreyer, Harper, and Chakravarty's +[*Modular Type Classes*](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf) presents classes +as signatures and instances through structures and functors. That work helps explain the analogy +here; it is not a formal equivalence between ML modules and CGP. The +[type classes](./type-classes.md) comparison develops the related selection tradeoffs. ## How CGP expresses it -CGP reproduces the signature, structure, and functor triad with its consumer and provider machinery, -then replaces manual functor application with a declarative table. +CGP uses Rust traits to declare interfaces and provider types to name implementations. A context's +wiring selects those providers, while provider bounds state which other interfaces they require. ### Components are signatures; providers are structures -Declaring a component states the interface, and a provider supplies the implementation: +A component and its providers separate the interface from its named implementations: ```rust #[cgp_component(AreaCalculator)] @@ -159,21 +165,24 @@ impl AreaCalculator { } ``` -`CanCalculateArea` is the signature and `RectangleArea` is a structure ascribing to it. One piece -has no ML counterpart: CGP splits the trait into a consumer side callers use and a provider side -implementers target, whereas an ML signature is one interface used from both sides. The split exists -because Rust has coherence and ML does not. ML holds many structures of one signature by *naming -them*, so it never needs the maneuver CGP uses to escape the one-implementation-per-type rule; the -[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) page explains it. A CGP -component is also typically a small signature with one operation, where an ML signature bundles many -values and types; a rich ML signature corresponds to several components combined through `#[uses]`. -The wired type here is a `Rectangle` carrying `width` and `height`, a **value context**: the type -being measured also carries the wiring. +`CanCalculateArea` is the interface callers use, and `RectangleArea` implements its generated +provider trait, `AreaCalculator`. The provider reads `width` and `height` from the context through +[implicit arguments](/docs/concepts/implicit-arguments). A `Rectangle` wired to this provider is a +**value context**: the value being measured also determines the implementation. + +The consumer/provider split is specific to CGP's use of Rust traits. Distinct provider types can +implement the same provider trait for a context while respecting Rust's coherence rules; wiring +then selects one for consumer calls. ML already names different structures satisfying a signature. +The [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) page explains this +split in detail. + +Components can group multiple methods, associated types, and constants. This example uses one +operation because it is independently replaceable. A larger ML signature may correspond to one +component or several, depending on which choices should vary together. ### Abstract-type components are a signature's abstract types -An abstract-type component is CGP's version of a signature's abstract `type t`, defined with -[`#[cgp_type]`](/docs/reference/macros/cgp_type). CGP's own error type is the standing example: +An abstract-type component lets generic code use a type that the context supplies: ```rust #[cgp_type] @@ -182,18 +191,19 @@ pub trait HasErrorType { } ``` -`HasErrorType` declares an abstract `Error` the way `OrderedType` declares an abstract `t`, and -generic code imports it with `#[use_type(HasErrorType.Error)]` and names it as the bare `Error`, -as a functor body refers to `O.t`. The abstraction is the parametric kind, generic code polymorphic -over the type it is given. What CGP does not reproduce is *sealing*: once a context wires `Error` to -a concrete type, no type-system boundary hides that representation from other code. CGP leaves -representation hiding to Rust's module privacy. The [Abstract types](/docs/concepts/abstract-types) -page develops the construct. +`HasErrorType` declares an `Error` with a `Debug` bound. Generic code can import it through +`#[use_type(HasErrorType.Error)]` and use the name `Error`, much as a functor uses `O.t` without +knowing its representation. Wiring chooses the associated type for a concrete context. + +This mechanism does not itself seal the selected type. If wiring exposes an equality with a +concrete public type, clients can use that equality. Rust's module privacy and types with private +representations remain available for data abstraction. The +[Abstract types](/docs/concepts/abstract-types) page distinguishes configuring a type from hiding +its representation. ### Higher-order providers are functors -A [higher-order provider](/docs/concepts/higher-order-providers) is a provider parameterized by -another provider, as a functor is a module parameterized by another module: +A higher-order provider composes behavior from another provider supplied as a type parameter: ```rust #[cgp_impl(new ScaledArea)] @@ -205,19 +215,25 @@ impl AreaCalculator { } ``` -`ScaledArea` is `Make (StringCompare)` in CGP form. Two differences favour CGP's -ergonomics. A higher-order provider can default its inner parameter to -[`UseContext`](/docs/reference/providers/use_context), so an unparameterized `ScaledArea` falls back -to whatever the context wires for that component, an open, recursive application a plain functor -cannot express without recursive modules. And CGP sidesteps the sharing-constraint problem: its -abstract types are supplied by the shared context, so every provider in a context agrees on `Error` -with no `with type` annotation to write. +`ScaledArea` chooses `RectangleArea` as the inner implementation and uses the same +context for both calls. Its `AreaCalculator` bound plays the role of a functor's parameter +signature. The context supplies the rectangle dimensions and `scale_factor`. + +The example requires an explicit `InnerCalculator` argument. A provider can separately declare a +default parameter of [`UseContext`](/docs/reference/providers/use_context), which forwards that +dependency through the context's wiring. The macro's `new` form above does not add such a default. +Forwarding also needs a dependency path that terminates: wiring an area wrapper back to itself +through `UseContext` would not select a different inner area calculator. + +A shared context can reduce the need to repeat type equalities between providers. Providers that +use the same context's `HasErrorType` refer to the same associated `Error`. Other relationships +between associated types may still require equality bounds. This convenience does not replace +ML's full account of sharing constraints or abstract type identity. -### `delegate_components!` replaces manual functor application +### `delegate_components!` records the assembly choices -The decisive difference is that CGP wires a program declaratively where ML applies functors by hand -in order. A context lists its choices in any order, and the trait system resolves each provider's -dependencies through the context: +A wiring table names the provider for each component without listing those entries in dependency +order. Providers obtain their declared dependencies through the same context: ```rust use cgp::core::error::ErrorTypeProviderComponent; @@ -231,92 +247,85 @@ delegate_components! { } ``` -This is CGP's built-in Functoria. A provider states what it needs as -[impl-side dependencies](/docs/concepts/impl-side-dependencies), and the compiler threads each -requirement to whatever provider the context wires for it, with no application order to get right. -The counterpart to ML's check that a functor argument satisfies its parameter signature is -[`check_components!`](/docs/reference/macros/check_components), which verifies at compile time that a -context supplies every trait its providers transitively need. A reusable bundle of wirings is an -[aggregate provider](/docs/concepts/aggregate-providers) or a [namespace](/docs/concepts/namespaces), -CGP's way of packaging a sub-assembly. `App` here is an **environmental context**, a type standing -for an application, with an `smtp_server` field the email provider reads. - -### Modular implicits and CGP wiring: the same problem, opposite selection - -Modular implicits and `delegate_components!` both answer the limitation that assembling a program from -functors is manual, and they select implementations by opposite means. Modular implicits resolves by -*implicit search*, which shares type classes' coherence-leaning character: a search can be ambiguous, -and canonicity fights abstraction. CGP resolves by *explicit table*: a context names one provider per -component, so there is no search and no ambiguity, and each context may choose differently. The -mechanism the two share is *recursive composition*. An implicit functor such as `Show_list {S : Show}` -builds `Show` of a list from `Show` of its element, as a higher-order provider builds its behavior -from an inner provider resolved through the context. +`App` is an **environmental context** representing the application. Its `smtp_server` field supplies +the runtime data used by `SendViaSmtp`, while the table selects behavior and the error type. The +entry order has no execution meaning: the table does not construct objects or schedule startup. +This is the part of functor assembly that the comparison covers, rather than all of Functoria's +configuration and build functions. + +Concrete wiring needs a dependency check as well as a provider selection. Rust checks each provider +body against its declared bounds; [`check_components!`](/docs/reference/macros/check_components) +asserts that a specified context satisfies the selected components' transitive requirements. +Writing a table alone does not force every entry to be usable. An +[aggregate provider](/docs/concepts/aggregate-providers) or +[namespace](/docs/concepts/namespaces) can package choices for reuse. + +### Modular implicits select by scope; CGP selects through the context + +Modular implicits and CGP both support composing implementations from other implementations. Their +selection mechanisms differ: modular implicits searches the implicit modules in scope under type +constraints, while CGP's wiring names a provider for a context and component. Both allow alternative +implementations; they place the choice in different parts of the program. + +Explicit wiring makes CGP's selected provider visible, but Rust still resolves trait bounds and +checks coherence. Wiring does not eliminate every possible ambiguity or trait-resolution failure. +Likewise, an implicit functor's recursive resolution is only an analogy for provider composition; +it is not CGP's implementation mechanism. ## What each approach costs -ML modules are valued for genuine data abstraction through sealing, for functors as reusable -components against an interface, for separate compilation, and for first-class modules where an -implementation must be chosen at runtime -([OCaml manual, *First-class modules*](https://ocaml.org/manual/5.5/firstclassmodules.html)). Their -costs, as their users state them, cluster around weight and plumbing. Assembling a large application -means applying functors by hand in dependency order, painful enough that MirageOS built Functoria, -and rooted in the *stratification* of ML: the module language is a second, weaker language above the -expression language ([*Functor Driven Development*](https://arxiv.org/pdf/1905.02529); -[Rossberg, *1ML*](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/1ml-core-and-modules-united/47B10882829E4B32F98FBA93B28CEF30)). -Sharing constraints and the applicative-versus-generative distinction are recurring sources of -confusion. Base ML has no ad-hoc polymorphism, the gap that motivated modular implicits, whose paper -opens on OCaml's separate `+` and `+.` ([White, Bour & Yallop, 2015](https://arxiv.org/abs/1512.01895)), -and that extension remains an experimental fork. - -CGP gives up ML's sealing: its abstract types defer and configure a type but do not hide a -representation behind a type-system boundary. Its wiring is trait resolution, which compiles to -direct calls but produces verbose, generated-type errors: [`cargo cgp check`](/docs/cargo-cgp/check) -leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not -yet reshape every class. It resolves at compile time and monomorphizes, so a runtime-chosen -implementation needs a different tool. And its table-driven resolution is more automatic but less -locally obvious than ML's explicit by-name linking. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the -alternatives. +ML modules make interfaces, type abstraction, and module application explicit. That gives clients +control over which type equalities and implementations are visible. Larger assemblies can require +more module bindings and sharing constraints, and the distinction between applicative and generative +functors adds another type-level concern. Tools such as Functoria organize that assembly work. + +CGP moves many assembly choices into a context, at the cost of generated traits and indirect +dependency resolution. A reader may need to follow the wiring to find an implementation, and a +failed bound can produce a long diagnostic. [`cargo cgp check`](/docs/cargo-cgp/check) helps explain +the error classes it recognizes. Monomorphization can also increase compile time and generated code; +static provider selection permits direct calls but does not guarantee that every call is inlined. + +CGP wiring supplies neither ML sealing nor runtime module selection. Rust's ordinary abstraction +and runtime-polymorphism tools can coexist with CGP, but they address those needs separately. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) helps decide when the wiring machinery +is worth introducing. ## Where ML modules are the better choice -When a program needs representation hiding enforced by the type system, separately compiled modules, -runtime selection through first-class modules, or the explicit control of by-name linking, ML modules -are the better tool, and reaching for CGP would forgo abstraction guarantees ML provides natively. CGP -is the better tool when a program needs many interchangeable implementations chosen per deployment, a -dependency graph the compiler wires rather than the programmer, abstract types unified into the same -selection mechanism, and all of it in one language with no module stratum, and can accept Rust as the -platform. +ML modules fit programs whose design relies on signature sealing, precise control of module type +equalities, or explicit module application. In OCaml, first-class modules also package an +implementation for use as a runtime value. Those are native module-system features, and CGP does +not reproduce them as a bundle. + +CGP is useful in Rust when many providers share a context and applications need to vary the +implementation choices independently. For a smaller Rust interface, ordinary traits and generic +parameters may already express the needed dependency. The choice depends on the assembly problem +as well as the language's abstraction facilities. ## What to expect that differs -**There is no application order.** An ML reader expects to apply functors in dependency order. The -CGP table is unordered, and the compiler resolves each provider's dependencies through the context. -This is Functoria's job done by the type system. +**Wiring order does not determine execution order.** Component entries select providers. Runtime +initialization and execution remain ordinary Rust code. -**Abstract types are not sealed.** A CGP abstract type defers and configures a type but does not -hide a known one. Representation hiding is Rust's module privacy, separate from the abstract-type -mechanism, and a reader who assumes sealing will look for a guarantee CGP does not make through this -feature. +**Type selection and representation hiding are separate.** An abstract-type component supplies an +associated type; Rust privacy determines which representation details clients can access. -**Selection is a table, not a search.** Unlike modular implicits, CGP never resolves a provider from -what is in scope. Each context names its choice, and that lets two contexts choose differently -with no ambiguity. +**Alternative implementations exist in both systems.** ML names structures, modular implicits uses +scope and type-directed resolution, and CGP records choices on a context. -**Every construct is ordinary Rust.** Providers and contexts are types and traits, wired in Rust, so -there is no separate module language. CGP is a library on stable Rust and a consumer trait can still -be implemented directly, without wiring. +**Consumer traits remain ordinary Rust traits.** Code can implement them directly when provider +wiring would add no useful flexibility. ## Where to go next -- [Higher-order providers](/docs/concepts/higher-order-providers): the functor correspondence in - full, including the `UseContext` default. -- [Abstract types](/docs/concepts/abstract-types): what an abstract-type component does and does not - hide. -- [Namespaces](/docs/concepts/namespaces): packaging a reusable sub-assembly of wirings. -- [Type classes](./type-classes.md): the modular-type-classes result and where CGP sits on its - spectrum. -- [Dependency injection](./dependency-injection.md): the same wiring seen from the container side. +These pages expand the constructs and comparisons used here: + +- [Higher-order providers](/docs/concepts/higher-order-providers): explicit provider parameters and + forwarding through `UseContext`. +- [Abstract types](/docs/concepts/abstract-types): selecting types through a context. +- [Namespaces](/docs/concepts/namespaces): reusable groups of wiring choices. +- [Type classes](./type-classes.md): interfaces, instances, and implementation selection. +- [Dependency injection](./dependency-injection.md): wiring viewed through dependency declarations. ## Sources @@ -324,11 +333,14 @@ The OCaml snippets were compiled with OCaml 5.5.0; the modular-implicits snippet paper, since the extension has not shipped. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per wired context. +These references support the module semantics and comparison: + +- [OCaml manual, *Generative functors*](https://ocaml.org/manual/5.5/generativefunctors.html): unit-parameter functors and fresh result type identities. - [OCaml, *Functors*](https://ocaml.org/docs/functors) and [OCaml manual, *First-class modules* (5.5)](https://ocaml.org/manual/5.5/firstclassmodules.html): signatures, structures, functors, sharing constraints, and the applicative/generative distinction. - [*Modules and Data Abstraction in OCaml* (Wellesley CS251)](https://cs.wellesley.edu/~cs251/s12/handouts/modules.pdf): sealing for data abstraction. - [Dreyer, *Understanding and Evolving the ML Module System*](https://people.mpi-sws.org/~dreyer/thesis/main.pdf) and [Rossberg, *1ML*](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/1ml-core-and-modules-united/47B10882829E4B32F98FBA93B28CEF30): the depth of the module system and the critique of its stratification. - [Dreyer, Harper & Chakravarty, *Modular Type Classes* (POPL 2007)](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf): classes as signatures, instances as structures and functors. -- [White, Bour & Yallop, *Modular implicits* (2014)](https://arxiv.org/abs/1512.01895) and the [experimental fork](https://github.com/ocamllabs/ocaml-modular-implicits): implicit module parameters, implicit functors, and the `Show` example. +- [White, Bour & Yallop, *Modular implicits* (ML/OCaml 2014; published 2015)](https://arxiv.org/abs/1512.01895) and the [experimental fork](https://github.com/ocamllabs/ocaml-modular-implicits): implicit module parameters, implicit functors, and the `Show` example. - [*Programming Unikernels in the Large via Functor Driven Development*](https://arxiv.org/pdf/1905.02529): functor plumbing at scale in MirageOS and the Functoria DSL. - [Applicative vs. generative functors (OCaml discussion)](https://discuss.ocaml.org/t/practical-example-of-applicative-vs-generative-functors/13777): the practical distinction. diff --git a/docs/comparisons/policy-based-design.md b/docs/comparisons/policy-based-design.md index 9f4ea29b..ca684bf2 100644 --- a/docs/comparisons/policy-based-design.md +++ b/docs/comparisons/policy-based-design.md @@ -6,52 +6,52 @@ description: 'CGP read against C++ policy classes, host templates, CRTP, and con # C++ policy-based design -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows C++ -policy-based design, the curiously recurring template pattern (CRTP), and C++20 concepts. CGP's -context, providers, and wiring table are the same compile-time composition with the same zero -runtime cost, and this page shows where the two agree, where CGP declares and checks what a template -leaves implicit, and what a template can do that CGP cannot. +CGP and C++ policy-based design compose behavior from implementations chosen at compile time. A CGP +provider plays a policy's role, and a context supplies the host's data and implementation choices. +The main differences are how interfaces are declared, how generic bodies are checked, and where +an application records its choices. + +CGP is a language extension for Rust, with pluggable trait implementations at compile-time. It is +implemented as a library on stable Rust, and its consumer traits are ordinary Rust traits. The +[Introduction](/docs/) covers the basics. This page assumes familiarity with policy classes, the +curiously recurring template pattern (CRTP), and C++20 concepts. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. It plays the host class's part. +A **context** is the type on which CGP's consumer methods operate. It holds runtime data and selects +providers for its components. A provider implements behavior for the context without becoming a +base class or contributing fields to it. + +The vocabulary maps by role rather than by an exact translation of language features: | In C++ | In CGP | | --- | --- | -| A policy class | A **provider**: a zero-sized type implementing one component | -| The policy interface, documented by hand | A **component**: the interface written as a trait | -| The host class | The context | -| A host class template with policies as type parameters | A **higher-order provider** | -| The template argument list `Host` | The **wiring table** written with `delegate_components!` | -| `static_cast(this)` in a CRTP base | `self` inside `#[cgp_impl]`, which already means the context | -| A concept check at instantiation | `check_components!` at the wiring site | +| A policy class | A **provider** implementing a provider trait | +| A policy interface, possibly expressed as a concept | A **component** declaring the interface as a trait | +| The host object | The context value | +| A template taking policy types | A **higher-order provider** taking provider types | +| Policy arguments selecting host behavior | Component choices in `delegate_components!`, or explicit provider parameters | +| Access to the derived object through CRTP | Access to the context parameter, written as `self` inside `#[cgp_impl]` | +| Checking constraints for a concrete instantiation | Checking trait bounds, with `check_components!` asserting a context's dependencies | ## The idea, briefly -Policy-based design builds a class from interchangeable *policy* classes supplied as template -parameters, so a *host* class composes its behavior at compile time from parts a user chooses. -Andrei Alexandrescu named the technique in *Modern C++ Design*: decompose a class's behavior into -orthogonal policies, each a small class implementing one aspect, and write the main class as a -template that takes the policies as parameters and derives from or holds them. A library "can -support an exponential number of different behavior combinations, resolved at compile time" -([Wikipedia, *Modern C++ Design*](https://en.wikipedia.org/wiki/Modern_C%2B%2B_Design)). The -technique is "a compile-time variant of the strategy pattern" -([Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design)): a policy -selects an algorithm through a template argument, and the compiler inlines the result. +Policy-based design lets a host class vary independent aspects of its behavior through template +arguments. A smart pointer might parameterize ownership and checking, while a greeting program +might parameterize its message and output destination. The resulting types fix those choices at +compile time, avoiding virtual dispatch for the policy calls. ### Policies and the host class -The reference example composes a greeting from an output policy and a language policy: +A host composes its policies by inheriting from them or holding their values. This greeting example +uses an output policy and a language policy: ```cpp template class HelloWorld : private OutputPolicy, private LanguagePolicy { public: void run() const { - write(message()); + this->write(this->message()); } }; @@ -81,27 +81,26 @@ int main() { } ``` -`HelloWorld` is a distinct type from -`HelloWorld`, each with its own inlined `run`. The host's `run` -calls `write` and `message` without knowing which policy supplies them, and the compiler checks that -the chosen policies supply them only when `run` is instantiated. +The English and German instantiations are distinct types with different message implementations. +The `this->` qualifiers make the member lookups depend on the template instantiation, where the +compiler can find the inherited policy members. The calls can be inlined, but choosing policies +statically does not itself guarantee inlining. + +### Policy interfaces can be implicit or constrained -### The policy interface is implicit +An unconstrained host expresses its requirements through the operations its body uses. In the +example, the policies must supply compatible `message` and `write` members. A class can satisfy +those requirements without declaring that it implements a particular interface. -A policy has no declared interface. Any class with members of the right names and types qualifies. -The policy interface "doesn't have a direct, explicit representation in code, but rather is defined -implicitly, via duck typing, and must be documented separately and manually" -([Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design)). The -consequence is the classic template failure mode: a policy missing a member produces an error inside -the host's body, after instantiation, phrased in terms of the substituted types rather than the -requirement that was violated. The [row polymorphism](./row-polymorphism.md) page places this duck -typing in the wider structural-versus-nominal landscape. +C++20 concepts can give those requirements explicit names. Policy-based design therefore does not +require an undocumented interface: a host can constrain its policy arguments and report a failed +requirement before its body is instantiated. The distinction from Rust traits concerns both +structural matching and how the generic body is checked. -### CRTP: a base that knows its derived class +### CRTP gives a base access to its derived object -The curiously recurring template pattern lets a base class template call into the class deriving -from it, statically. The derived class passes itself as the base's template argument, and the base -reaches it with a `static_cast`: +CRTP passes the derived class as an argument to its base template. The base can then call a derived +member through a cast to that known type: ```cpp template @@ -115,17 +114,19 @@ struct D1 : public Base { void impl() { std::puts("D1::impl()"); } }; struct D2 : public Base { void impl() { std::puts("D2::impl()"); } }; ``` -The pattern gives static polymorphism with no virtual call, because `Derived` is known at compile -time, and policies and mixins use it whenever they need the host's own type. C++23's *deducing this* -removes the manual parameter and cast for the common case -([cppreference, *CRTP*](https://en.cppreference.com/w/cpp/language/crtp)). Its limit is -homogeneity: `Base` and `Base` are unrelated types, so a `std::vector` cannot hold -both. +`Base` and `Base` call their respective `impl` methods without virtual dispatch. A policy or +mixin can use the same technique when it needs access to its host. The cast relies on the object +having the expected derived type. C++23's explicit object parameters offer another way to express +some of these member functions, without repeating the CRTP inheritance pattern. -### Concepts: making the requirements explicit +The two base instantiations do not form a shared runtime interface. A heterogeneous collection +needs another representation, such as a virtual interface, type erasure, or a `std::variant` for a +closed set of alternatives. CRTP alone does not choose that representation. -C++20 concepts give a template's requirements a name and let the compiler check them before entering -the body: +### Concepts state requirements without fully checking a generic body + +A concept names a predicate over template arguments. Here, `Hashable` requires a hash expression +whose result is convertible to `std::size_t`: ```cpp template @@ -137,26 +138,23 @@ template void f(T) {} ``` -The gain is in diagnostics: instead of dozens of lines about an invalid expression deep inside an -algorithm, the error reads that a named concept was not satisfied, at the call -([cppreference, *Constraints and concepts*](https://en.cppreference.com/w/cpp/language/constraints)). -What concepts do not change is *when* the body is checked. Satisfaction is checked by substitution at -instantiation, and a template body is not verified against its concepts at definition, so a host may -use a member its concept never mentions and compile until a policy without that member is -substituted. +Constraint satisfaction determines whether a candidate is eligible for particular arguments. +It does not prove that every operation in the template body follows from the stated constraints. +A body can use an additional dependent member that works for one argument and fails for another. +C++ checks nondependent constructs when the template is defined; dependent checks can wait until +instantiation. The [C++ draft's template name-resolution rules](https://eel.is/c++draft/temp.res) +describe that split. ## How CGP expresses it -CGP is policy-based design with the policy interface declared as a trait, the composition gathered -into a wired context, and the checking moved to the provider's definition. The correspondence is -construct for construct, and the differences fall out of Rust's trait system doing the job that C++ -templates leave to duck typing. +CGP declares policy interfaces as traits and supplies implementations through provider types. +Applications can select providers through context wiring or pass them explicitly as type +parameters. Rust checks the generic implementation against its declared bounds in either form. ### Providers are policies; the context is the host -Each policy becomes a provider of a component, and the host becomes a context that wires one provider -per component. The greeting example declares the two policy interfaces as components, writes each -policy as a provider, and writes the host's `run` as a function over any context that supplies both: +The greeting can declare its message and output interfaces separately, then implement each choice +as a provider: ```rust #[cgp_component(MessageProvider)] @@ -197,8 +195,12 @@ pub fn run(&self) { } ``` -Two hosts are two contexts, each selecting its policies in a wiring table where the C++ version -passes them as template arguments: +`HasMessage` and `CanWrite` are the interfaces that `run` uses. Their generated provider traits, +`MessageProvider` and `Writer`, let named types supply alternative implementations. A provider type +can implement more than one component, and a component can contain more than one operation; the +split here makes the message and output choices independent. + +Contexts select those choices in wiring tables: ```rust pub struct EnglishApp; @@ -222,20 +224,20 @@ EnglishApp.run(); // Hello, World! GermanApp.run(); // Hallo Welt! ``` -`EnglishApp` and `GermanApp` are **environmental contexts**: fieldless types whose only job is to -carry the choice, as `HelloWorld` is a type whose only job is to fix -the policies. Both compositions resolve at compile time, both monomorphize `run` per host, and both -emit a direct call to the chosen `message` and `write`. The difference is in the declarations -around them. `HasMessage` and `CanWrite` are the policy interfaces written down, and -`#[uses(HasMessage, CanWrite)]` is the host stating which policies its body relies on. +`EnglishApp` and `GermanApp` are fieldless **environmental contexts**. Their role is to choose +behavior; an application with runtime configuration could store it in context fields. Both +compositions use static provider selection, so policy calls need no runtime lookup or vtable. +Whether the optimizer inlines a particular call remains a separate question. + +The `#[uses(HasMessage, CanWrite)]` declaration states the generic dependencies of `run`. +`check_components!` then checks that each concrete context supplies the requested components and +their dependencies. This separates checking the reusable body from checking an application's +assembly. ### Policies as type parameters are higher-order providers -The wiring table is not the only place CGP can put a policy choice. C++ passes policies as template -parameters of the host, and CGP has the same form in the -[higher-order provider](/docs/concepts/higher-order-providers): a provider whose type parameters are -other providers, bound with `#[use_provider]`. The `HelloWorld` host template translates almost -token for token: +A higher-order provider keeps policy choices local to a parameterized implementation. The greeting +can use the familiar `HelloWorld` shape: ```rust #[cgp_component(Runner)] @@ -263,13 +265,13 @@ delegate_components! { App.run(); // Hallo Welt! ``` -The wiring entry names the C++ instantiation as a Rust type: `HelloWorld` -on both sides. The `#[use_provider(W: Writer)]` bound is the concept the C++ version lacks, spelled -out: `W` must implement the `Writer` provider trait for this context, and the body calls -`W::write(self, ...)` as an associated function. The same shape works on a function, which is the -closer reading of a C++ function template that takes policy types. A -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) may be generic over providers, and the caller -instantiates it the way C++ instantiates a template: +`W` must implement `Writer` for the context, and `M` must implement `MessageProvider` for it. +The `#[use_provider]` attributes declare those bounds and allow calls such as `W::write(self, ...)`. +Only `RunnerComponent` is wired on `App`; the inner provider choices are explicit arguments to +`HelloWorld`. + +A generic CGP function can take providers in the same way. Its provider parameters become parameters +of the generated consumer trait, which the caller can specify explicitly: ```rust #[cgp_fn] @@ -282,22 +284,21 @@ pub fn hello(&self) { >::hello(&App); // Hello, World! ``` -CGP therefore offers both placements. Passing policies as type parameters keeps the choice at the -instantiation site and repeats it wherever the type is named, which is the C++ arrangement with its -costs and its flexibility. Wiring the policies as components on the context names each choice once -and lets generic code require only the traits it uses. A higher-order provider may also default its -inner parameter to [`UseContext`](/docs/reference/providers/use_context), which routes the inner -call back to whatever the context wires for that component. That is a default template argument -whose default is "whatever the host is wired with", and it has no C++ counterpart. +Explicit parameters suit a provider that must fix an inner choice locally. Context wiring suits +dependencies that several providers should obtain from the application's shared choices. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) explains when the additional control of +a higher-order provider is useful. + +A manually declared provider struct can default an inner parameter to +[`UseContext`](/docs/reference/providers/use_context), forwarding that dependency through the +context's wiring. The `new` declarations above do not introduce defaults automatically. This is a +CGP forwarding convention; C++ can also express policies that obtain behavior through their host. -### `#[cgp_impl]` is CRTP with the cast done for you +### Providers access the context without an inheritance cast -A CGP provider's body refers to the context as `self` and `Self`. CRTP arranges the same thing for a -base class through `static_cast(this)`. The [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) -macro rewrites a provider written in consumer-trait shape into a provider-trait impl whose `Self` is -the provider's own marker and whose context is an explicit parameter, so the `self` a provider body -uses is the context. A policy that needs the host's data reads it as an -[implicit argument](/docs/concepts/implicit-arguments): +Inside `#[cgp_impl]`, `self` refers to the context on which the operation runs. The macro rewrites +that source form into a provider implementation with an explicit context parameter. A provider can +request a field through an implicit argument: ```rust #[cgp_impl(new GreetHello)] @@ -308,114 +309,116 @@ impl Greeter { } ``` -In CRTP terms, `GreetHello` is the base template, the context is `Derived`, and the `#[implicit]` -argument is `static_cast(this)->name` with the cast replaced by a `HasField` bound the -compiler checks. CGP never has the CRTP hazard of passing the wrong derived class, because the -context is supplied by the wiring rather than named at each derivation. The `Person` this provider is -wired on is a **value context**: the type being greeted also carries the wiring. - -### Checked at definition, not at instantiation - -The deepest difference is when a mistake surfaces. A C++ host body is checked when it is instantiated -with concrete policies, and even with concepts the body is not verified against the concept at -definition. A CGP provider is checked when it is written. The `#[uses(HasMessage, CanWrite)]` bounds -are the whole contract `run` may rely on, and a call to a method outside them is an error at `run`'s -definition, for every context at once. The instantiation-time question that remains, whether a -particular context supplies what its providers need, is answered by -[`check_components!`](/docs/reference/macros/check_components) at the wiring site, with the missing -dependency named rather than inside a monomorphized body. The -[type classes](./type-classes.md) and [reflection](./reflection.md) pages draw out the same -property against Haskell's neighbours and Zig's `comptime`. - -### One wired context instead of a repeated parameter list - -A policy-based host carries its policies in its type, so every place that names the host names the -policies: `SmartPtr` appears wherever such a pointer -is declared, and a helper generic over the host repeats the parameter list. CGP can reproduce that -arrangement with a higher-order provider, and it carries the same cost there. The alternative CGP adds -is to wire the policies as components on the context, so the choices live in one -`delegate_components!` table on a context type named once, and code generic over the context requires -only the traits it uses through `#[uses]`. Adding a policy to a host is then a new wiring line rather -than a new template parameter threaded through every signature that mentions the host. The -[dependency injection](./dependency-injection.md) page develops this centralization from the -container side. +`GreetHello` asks its context for `name`; it does not contain a `name` field itself. A `Person` that +stores the field and wires the greeter is a **value context**. The generated field-access bounds +make the requirement explicit to Rust's type checker. + +This addresses a need that CRTP often serves: reusable behavior accessing the host's data. The +mechanism is different. CGP passes the context to provider functions, so there is no inheritance +relationship or base-to-derived cast in this correspondence. + +### Generic bodies and concrete wiring have separate checks + +Rust checks a generic provider body using the bounds available at its definition. For example, +`run` can rely on the `HasMessage` and `CanWrite` bounds declared by `#[uses]`. If it calls an +operation that needs an additional bound, the generic definition must supply that requirement. +This is stronger than merely checking whether particular C++ arguments satisfy a concept whose +requirements may not cover the body's dependent uses. + +A valid generic provider may still be unusable with a particular context. The context might lack a +field, another component, or a required relationship between associated types. +[`check_components!`](/docs/reference/macros/check_components) forces that dependency check for the +listed components. A wiring table alone does not validate every possible use, and the resulting +diagnostics can still involve generated traits and Rust's trait solver. + +### Wiring gathers choices under a context type + +Context wiring lets generic consumers name the interfaces they need without enumerating the +application's provider types. Adding another independently selected component can leave those +consumer signatures unchanged. The choices remain visible together in `delegate_components!`. + +C++ aliases and default template arguments already reduce repetition in policy-heavy types. +CGP's distinction is how dependencies are addressed: a provider can ask the shared context for a +component while the application selects its implementation elsewhere. Explicit provider parameters +remain available when that indirection is undesirable. The +[dependency injection](./dependency-injection.md) comparison examines this arrangement from the +application's side. ## What each approach costs -Policy-based design's costs are the familiar costs of C++ templates, as its users state them. The -policy interface is implicit and must be documented by hand, so a wrong policy fails deep inside the -host with an error about substituted types -([Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design)). Long -parameter lists spread through every signature that names a policy-heavy host. Every combination of -policies is a distinct type, so code generic over the host must itself be a template, and -heterogeneous collections need a separate virtual interface. CRTP adds the derived class passed to -the wrong base and a base that cannot see members of a still-incomplete derived class -([Wikipedia, *CRTP*](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)). Concepts -improve diagnostics but leave template bodies checked only at instantiation -([cppreference](https://en.cppreference.com/w/cpp/language/constraints)). Compile times grow with the -number of instantiations, which is a cost CGP's monomorphized wiring shares. - -CGP's costs are of the same species. A provider needs a component to implement, so CGP cannot accept -an arbitrary existing type as a policy the way a template accepts any class with the right members. -Its type-level programming is narrower than template metaprogramming, and its policies cannot -contribute data members to the host by inheritance. The wiring table is more ceremony than a template -argument list for a host with one or two policies. And its raw diagnostics are trait-solver output -over generated types, which a C++ programmer will recognize as the same species as a template error: -[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the -alternatives. +C++ policies compose structurally, so existing classes with compatible operations can often be +used directly. Concepts improve the interface declaration and diagnostics, but dependent errors +can still appear during body instantiation. Many policy combinations can increase compilation +work and code size. Aliases and defaults contain long parameter lists without changing the +underlying types. + +CGP requires declared provider traits and implementations for them. That gives generic bodies +checked contracts, but adapting an existing type can require an impl or wrapper. Wiring introduces +more declarations than a small set of ordinary Rust generic parameters. Following a dependency may +also require reading several component and provider mappings. + +CGP shares the costs of monomorphized generic code, including compilation work and potentially +larger binaries. Its generated types can make trait errors difficult to read; +[`cargo cgp check`](/docs/cargo-cgp/check) explains the error classes it recognizes. These costs +belong alongside the benefits of independently selected implementations. ## Where a template is the better choice -Where a class has a few orthogonal policies and its users name the instantiation in one place, a -policy-based template is the smaller tool. Where a policy must contribute data members or types to the -host by inheritance, or where the composition needs value-level template metaprogramming, templates -express what CGP's type level cannot. Where any existing class must be accepted as a policy with no -declaration, structural composition is the requirement and CGP's declared provider traits are in the -way. And where a program needs a heterogeneous collection of hosts with different policies, both -systems fall back to runtime dispatch: virtual functions in C++, `dyn Trait` in Rust, as the -[dynamic dispatch](./dynamic-dispatch.md) page describes. +A C++ host with a few policies and a convenient alias may already provide all the needed +composition. Templates also support inheritance-based contributions to object layout and C++'s +broader template metaprogramming facilities. CGP does not add fields from a provider to a context or +reproduce that language's template system. + +Rust still supplies const generics and constant evaluation when CGP is in use. The boundary is +therefore not that CGP programs can compute only with types; it is that CGP's provider wiring is a +particular composition mechanism within Rust. For a small Rust API, ordinary traits and generics +can be the simpler choice. + +Runtime selection needs an additional representation in either language. Virtual interfaces or +type erasure in C++, and trait objects in Rust, can support open sets of runtime implementations. +Variants and enums can represent closed sets. The [dynamic dispatch](./dynamic-dispatch.md) page +explains how static wiring and runtime polymorphism can coexist. ## What to expect that differs -**A provider needs an impl.** A reader used to dropping an existing class in as a policy will find -that CGP requires a provider impl for a declared component. The declaration lets the compiler check -the body once, at its definition, for every context. +**Providers implement declared traits.** Matching member names alone does not make an existing type +a CGP provider. The declared interface supplies the contract used to check generic code. -**CGP's type level is types and associated types only.** There is no value-level computation and no -data-member contribution from a provider. CGP is composition of behavior and of abstract types, not a -metaprogramming language. +**The context owns runtime state.** A provider implements operations over that state; it does not +contribute base-class fields to the context. -**The common form is the wiring table, not the parameter list.** A reader may expect to name policies -at every use, as a template argument list does. CGP can, through a higher-order provider, but the -idiomatic form names each choice once on the context, and a provider that must pin an inner choice -locally is the exception. +**Wiring and explicit parameters are both available.** Choose context wiring for shared application +choices and provider parameters when an implementation needs to fix a dependency locally. -**CGP is not templates done right.** Templates are the more general mechanism. CGP is policy-based -design with declared interfaces, definition-time checking, and a centralized wiring table, on a -language whose trait system already does the checking templates leave to instantiation. +**Checking has more than one stage.** Definition-time checking establishes that a provider's body +works under its bounds. Concrete dependency checks establish that a particular context satisfies +those bounds. ## Where to go next -- [Higher-order providers](/docs/concepts/higher-order-providers): the construct this page maps onto - a host template, including the `UseContext` default. -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): what the declared - policy interface is made of. -- [Dependency injection](./dependency-injection.md): the same centralization of choices, seen from - the container side. -- [Checking your wiring](/docs/concepts/check-traits): how the instantiation-time question is - answered at the wiring site. +These pages expand the mechanisms used in the examples: + +- [Higher-order providers](/docs/concepts/higher-order-providers): provider parameters and + forwarding through `UseContext`. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): declared interfaces + and named implementations. +- [Dependency injection](./dependency-injection.md): gathering choices on a context. +- [Checking your wiring](/docs/concepts/check-traits): validating a concrete composition. ## Sources -The C++ snippets are the reference examples from Wikipedia and cppreference, compiled with GCC 15.3 -in C++23 mode. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` -assertion per wired context. +The C++ snippets are adapted from the reference examples from Wikipedia and cppreference. They were +compiled and run with GCC 15.2.0 in C++23 mode, with standard-library headers and small drivers added +where omitted. The greeting qualifies inherited member calls with `this->` for dependent-base lookup. +The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per +wired context. + +These references support the C++ mechanisms and example origins: +- [C++ working draft, *Name resolution*](https://eel.is/c++draft/temp.res) and [*Constraints and concepts*](https://eel.is/c++draft/temp.constr): dependent lookup, template checking, and constraint satisfaction. - [Wikipedia, *Modern C++ Design*](https://en.wikipedia.org/wiki/Modern_C%2B%2B_Design): Alexandrescu's book, the policy and host-class vocabulary, and the exponential-combinations argument. -- [Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design): the `HelloWorld` example, policies as a compile-time strategy pattern, and the statement that the policy interface is implicit. -- [Wikipedia, *Curiously recurring template pattern*](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) and [cppreference, *CRTP*](https://en.cppreference.com/w/cpp/language/crtp): the pattern's mechanism, static polymorphism, the C++23 deducing-`this` alternative, and the homogeneous-container limit. +- [Wikipedia, *Policy-based design*](https://en.wikipedia.org/wiki/Policy-based_design): the `HelloWorld` example, policies as a compile-time strategy pattern, and implicit interfaces in unconstrained hosts. +- [Wikipedia, *Curiously recurring template pattern*](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) and [cppreference, *CRTP*](https://en.cppreference.com/w/cpp/language/crtp): the pattern's mechanism, static polymorphism, the C++23 deducing-`this` alternative, and the distinct types produced by CRTP instantiations. - [cppreference, *Constraints and concepts*](https://en.cppreference.com/w/cpp/language/constraints): concept syntax, satisfaction checked at instantiation, and the improvement in diagnostics. --- diff --git a/example-code/tests/comparisons/algebraic_effects.rs b/example-code/tests/comparisons/algebraic_effects.rs index 615716d6..fbcdd731 100644 --- a/example-code/tests/comparisons/algebraic_effects.rs +++ b/example-code/tests/comparisons/algebraic_effects.rs @@ -1,6 +1,6 @@ //! Code from `docs/comparisons/algebraic-effects.md` — *Algebraic effects and handlers*. -/// ## Components are effect signatures; providers are tail-resumptive handlers +/// ## Components declare operations; providers implement them pub mod components_are_effect_signatures { use cgp::prelude::*; @@ -26,7 +26,7 @@ pub mod components_are_effect_signatures { } } -/// ## Reading from the context is dynamic binding, exactly +/// ## Context fields supply an environment value pub mod reading_from_the_context_is_dynamic_binding { use cgp::prelude::*; @@ -49,8 +49,8 @@ pub mod reading_from_the_context_is_dynamic_binding { } } -/// ## Raising an error looks like `raise` but passes a value, not control -/// ## Impl-side dependencies are the effect row; `check_components!` is "all effects handled" +/// ## Raising an error constructs a value +/// ## Dependency checks verify the selected providers pub mod raising_an_error { use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::error::RaiseFrom; diff --git a/example-code/tests/comparisons/capabilities.rs b/example-code/tests/comparisons/capabilities.rs index 18dfbe2d..fe05dcf0 100644 --- a/example-code/tests/comparisons/capabilities.rs +++ b/example-code/tests/comparisons/capabilities.rs @@ -1,6 +1,6 @@ //! Code from `docs/comparisons/capabilities.md` — *Capabilities*. -/// ## A requirement on the context is a capability in the effect-system sense +/// ## Providers declare requirements on a context pub mod a_requirement_on_the_context { use cgp::prelude::*; diff --git a/example-code/tests/comparisons/dependency_injection.rs b/example-code/tests/comparisons/dependency_injection.rs index 022bc970..4b1089f1 100644 --- a/example-code/tests/comparisons/dependency_injection.rs +++ b/example-code/tests/comparisons/dependency_injection.rs @@ -11,7 +11,7 @@ pub mod without_a_framework { } } -/// ## Impl-side dependencies are the injected constructor parameters +/// ## Impl-side dependencies declare what an implementation needs pub mod impl_side_dependencies_are_constructor_parameters { use cgp::prelude::*; @@ -106,8 +106,8 @@ pub mod impl_side_dependencies_are_constructor_parameters { } } -/// ## Wiring is the container configuration -/// ## Checking replaces the container's startup validation +/// ## Wiring selects implementations for an application +/// ## Checking validates the declared dependencies pub mod wiring_is_the_container_configuration { use cgp::prelude::*; diff --git a/example-code/tests/comparisons/dynamic_dispatch.rs b/example-code/tests/comparisons/dynamic_dispatch.rs index b9c29e20..c31b42e5 100644 --- a/example-code/tests/comparisons/dynamic_dispatch.rs +++ b/example-code/tests/comparisons/dynamic_dispatch.rs @@ -1,7 +1,7 @@ //! Code from `docs/comparisons/dynamic-dispatch.md` — *Dynamic dispatch, dynamic typing, and //! prototypal inheritance*. -/// ## CGP code reads like a duck-typed program +/// ## Provider code calls methods on a generic receiver pub mod cgp_code_reads_like_a_duck_typed_program { use cgp::prelude::*; @@ -50,8 +50,8 @@ pub mod cgp_code_reads_like_a_duck_typed_program { } } -/// ## `DelegateComponent` is a compile-time vtable -/// ## Component delegation is delegation, with `self` bound +/// ## Wiring serves the selection role of a vtable +/// ## Delegation preserves the original context pub mod delegate_component_is_a_compile_time_vtable { use cgp::prelude::*; @@ -120,7 +120,7 @@ pub mod delegate_component_is_a_compile_time_vtable { } } -/// ## Namespaces are shared prototypes with open slots, not shadowable ones +/// ## Namespaces share bindings and leave paths for contexts to fill pub mod namespaces_are_shared_prototypes { use cgp::prelude::*; diff --git a/example-code/tests/comparisons/implicit_parameters.rs b/example-code/tests/comparisons/implicit_parameters.rs index dd26f70b..1310bc08 100644 --- a/example-code/tests/comparisons/implicit_parameters.rs +++ b/example-code/tests/comparisons/implicit_parameters.rs @@ -1,6 +1,6 @@ //! Code from `docs/comparisons/implicit-parameters.md` — *Implicit parameters*. -/// ## Implicit arguments are implicit value parameters +/// ## Implicit arguments read named context fields pub mod implicit_arguments_are_implicit_value_parameters { use cgp::prelude::*; @@ -25,7 +25,7 @@ pub mod implicit_arguments_are_implicit_value_parameters { } } -/// ## Abstract types are implicit type parameters +/// ## Abstract types are determined by the context pub mod abstract_types_are_implicit_type_parameters { use core::fmt::Debug; @@ -38,7 +38,7 @@ pub mod abstract_types_are_implicit_type_parameters { } } -/// ## Components and wiring are type classes without coherence +/// ## Components and wiring make instance selection explicit pub mod components_and_wiring_are_type_classes { use core::fmt::Display; diff --git a/example-code/tests/comparisons/ml_modules.rs b/example-code/tests/comparisons/ml_modules.rs index d93682b9..7d1be224 100644 --- a/example-code/tests/comparisons/ml_modules.rs +++ b/example-code/tests/comparisons/ml_modules.rs @@ -68,7 +68,7 @@ pub mod abstract_type_components { } } -/// ## `delegate_components!` replaces manual functor application +/// ## `delegate_components!` records the assembly choices pub mod delegate_components_replaces_functor_application { use cgp::core::error::ErrorTypeProviderComponent; use cgp::prelude::*; diff --git a/example-code/tests/comparisons/policy_based_design.rs b/example-code/tests/comparisons/policy_based_design.rs index f48bfa8c..76ebbb6a 100644 --- a/example-code/tests/comparisons/policy_based_design.rs +++ b/example-code/tests/comparisons/policy_based_design.rs @@ -126,7 +126,7 @@ pub mod policies_as_type_parameters { } } -/// ## `#[cgp_impl]` is CRTP with the cast done for you +/// ## Providers access the context without an inheritance cast pub mod cgp_impl_is_crtp { use cgp::prelude::*; From 2b7e645e54b31241dc68d7aa43fac3ef446518e4 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 20 Sep 2026 14:51:29 +0000 Subject: [PATCH 083/516] Add a glossary and link the context-shape terms to it The site used its vocabulary far more widely than it defined it. Terms like "environmental context" appeared on twenty-six pages, each time with an ad-hoc inline gloss and never once linked, while their only expository definition sat in a subsection of Modularity Hierarchy under a heading naming application contexts instead. Add docs/reference/glossary.md: seventy terms across CGP's own vocabulary, the Rust concepts the site assumes, and the borrowed terms the comparison pages trade in. Each entry is a definition and a route rather than an explanation, so the pages that own each idea stay the single place it is argued. Rust entries defer to Rust's own documentation; related-concept entries carry both the comparison page and a source that comparison already cites. Every term is an h3 directly under its section, because this MDX setup rejects {#custom-id} and Docusaurus anchors h2 and h3 only, so grouping terms by theme would cost each of them its anchor. toc_max_heading_level keeps the contents list to the three sections. Link the context-shape terms on first use across thirty-nine pages, leaving the inline gloss beside each, and route to the glossary from the reference, Concepts and Comparisons indexes and the Introduction. Co-Authored-By: Claude Opus 5 --- docs/comparisons/algebraic-effects.md | 4 +- docs/comparisons/capabilities.md | 2 +- docs/comparisons/dependency-injection.md | 4 +- docs/comparisons/dynamic-dispatch.md | 6 +- docs/comparisons/implicit-parameters.md | 4 +- docs/comparisons/index.md | 2 + docs/comparisons/ml-modules.md | 6 +- docs/comparisons/policy-based-design.md | 4 +- docs/comparisons/reflection.md | 2 +- docs/comparisons/row-polymorphism.md | 2 +- docs/comparisons/rust-language-proposals.md | 6 +- docs/comparisons/type-classes.md | 8 +- docs/concepts/coherence.md | 2 +- docs/concepts/implicit-arguments.md | 2 +- docs/concepts/index.md | 4 + docs/index.md | 1 + docs/reference/attributes/default_impl.md | 2 +- docs/reference/attributes/prefix.md | 2 +- docs/reference/components/can_wrap_error.md | 2 +- .../components/handler/async_computer.md | 2 +- .../components/handler/async_computer_ref.md | 2 +- docs/reference/components/handler/computer.md | 2 +- .../components/handler/computer_ref.md | 2 +- docs/reference/components/handler/handler.md | 2 +- .../components/handler/handler_ref.md | 2 +- docs/reference/components/handler/producer.md | 2 +- .../components/handler/try_computer.md | 2 +- .../components/handler/try_computer_ref.md | 2 +- docs/reference/components/has_error_type.md | 2 +- docs/reference/components/has_runtime.md | 2 +- docs/reference/components/has_runtime_type.md | 2 +- docs/reference/components/has_type.md | 2 +- docs/reference/components/runner.md | 2 +- docs/reference/components/send_runner.md | 2 +- docs/reference/glossary.md | 584 ++++++++++++++++++ docs/reference/index.md | 4 + .../traits/field-access/field_getter.md | 2 +- .../traits/field-access/field_mapper.md | 2 +- .../traits/field-access/has_field.md | 2 +- .../traits/field-access/has_field_mut.md | 2 +- .../traits/field-access/mut_field_getter.md | 2 +- .../traits/namespace/default_impls1.md | 2 +- .../traits/namespace/default_impls2.md | 2 +- .../traits/namespace/default_namespace.md | 2 +- 44 files changed, 647 insertions(+), 52 deletions(-) create mode 100644 docs/reference/glossary.md diff --git a/docs/comparisons/algebraic-effects.md b/docs/comparisons/algebraic-effects.md index 8c144022..0e9c8ccf 100644 --- a/docs/comparisons/algebraic-effects.md +++ b/docs/comparisons/algebraic-effects.md @@ -167,8 +167,8 @@ the related view of computations declaring what they require from an environment ## How CGP expresses it CGP represents an operation with a consumer trait and its implementation with a provider. -The examples use environmental contexts: types representing applications and supplying the -implementations for self-targeted components. Supporting declarations and imports are omitted +The examples use [environmental contexts](/docs/reference/glossary#environmental-context): types representing applications and supplying the +implementations for [self-targeted](/docs/reference/glossary#self-targeted-component) components. Supporting declarations and imports are omitted where they do not affect the comparison. ### Components declare operations; providers implement them diff --git a/docs/comparisons/capabilities.md b/docs/comparisons/capabilities.md index e8dac1b9..60d77a22 100644 --- a/docs/comparisons/capabilities.md +++ b/docs/comparisons/capabilities.md @@ -212,7 +212,7 @@ check_components! { App { GreeterComponent } } `GreetHello` needs a `name` field, and `App` supplies it. `check_components!` verifies the field requirement for the selected provider; constructing `App { name }` supplies its runtime value. -`App` is an environmental context representing an application, and the component is self-targeted. +`App` is an [environmental context](/docs/reference/glossary#environmental-context) representing an application, and the component is [self-targeted](/docs/reference/glossary#self-targeted-component). This is a dependency relationship: the `String` does not confer protected authority. Contexts can also determine [abstract types](/docs/concepts/abstract-types), such as the error type diff --git a/docs/comparisons/dependency-injection.md b/docs/comparisons/dependency-injection.md index 159e2461..a9178c72 100644 --- a/docs/comparisons/dependency-injection.md +++ b/docs/comparisons/dependency-injection.md @@ -125,8 +125,8 @@ CGP addresses those cases with a shared context and separately named providers. CGP separates a provider's dependency requirements from an application's implementation choices. The provider declares [impl-side dependencies](/docs/concepts/impl-side-dependencies), and the -context supplies the required traits and fields. Every context below is an environmental context: -a type representing an application, with self-targeted components that operate through it. +context supplies the required traits and fields. Every context below is an [environmental context](/docs/reference/glossary#environmental-context): +a type representing an application, with [self-targeted](/docs/reference/glossary#self-targeted-component) components that operate through it. The snippets omit supporting application types and some implementation bodies. ### Impl-side dependencies declare what an implementation needs diff --git a/docs/comparisons/dynamic-dispatch.md b/docs/comparisons/dynamic-dispatch.md index 23b04ba7..951887a8 100644 --- a/docs/comparisons/dynamic-dispatch.md +++ b/docs/comparisons/dynamic-dispatch.md @@ -119,7 +119,7 @@ second requires access to a field named `name`. The method body may resemble duc but it relies on declared traits and generated bounds. Ordinary generic Rust can express these bounds too; CGP's macros supply the context parameter and supporting impls. -A `Person` type with the required field and wiring is a value context in this example. +A `Person` type with the required field and wiring is a [value context](/docs/reference/glossary#value-context) in this example. It is the value being greeted, rather than an application environment selecting behavior for a separate target. [Implicit arguments](/docs/concepts/implicit-arguments) explains the field-based form. @@ -153,7 +153,7 @@ delegate_components! { // } ``` -`Rectangle` is a value context, and the self-targeted area component operates on that rectangle. +`Rectangle` is a value context, and the [self-targeted](/docs/reference/glossary#self-targeted-component) area component operates on that rectangle. The compiler resolves `AreaCalculatorComponent` to `RectangleArea` through the shown trait impl. The program does not store or consult this wiring table at runtime. Components can group several methods, associated types, and consts, so an entry is not necessarily equivalent to one method slot. @@ -230,7 +230,7 @@ delegate_components! { } ``` -`AppA` and `AppB` are environmental contexts representing applications. Their providers are found +`AppA` and `AppB` are [environmental contexts](/docs/reference/glossary#environmental-context) representing applications. Their providers are found through [`RedirectLookup`](/docs/reference/providers/redirect_lookup), which follows type-level paths. This resembles sharing defaults through a prototype, but customization fills unbound paths rather than shadowing already-bound entries. An attempt to bind the same key again conflicts under diff --git a/docs/comparisons/implicit-parameters.md b/docs/comparisons/implicit-parameters.md index f1b1cc0c..5adb1801 100644 --- a/docs/comparisons/implicit-parameters.md +++ b/docs/comparisons/implicit-parameters.md @@ -143,7 +143,7 @@ pub struct Rectangle { ``` `rectangle_area()` obtains `width` and `height` from `self`, so callers omit both arguments. -`Rectangle` is a value context: the rectangle itself holds the data the method operates on. +`Rectangle` is a [value context](/docs/reference/glossary#value-context): the rectangle itself holds the data the method operates on. The generated implementation requires field access with the matching names and types. Scala's `using Config` instead asks the compiler to resolve a contextual value by type; Haskell's `?cmp` refers to a named implicit binding. The @@ -233,7 +233,7 @@ delegate_components! { ``` `AppA` encodes `Vec` as hexadecimal text; `AppB` copies its bytes. Both are environmental -contexts representing applications. The component is parameter-targeted: `Value` is the data being +contexts representing applications. The component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component): `Value` is the data being encoded, while `self` supplies the application's choice of implementation. CGP records the provider choice in a wiring table and keeps Rust's coherence checks. Separate diff --git a/docs/comparisons/index.md b/docs/comparisons/index.md index 1b61b990..2bc26723 100644 --- a/docs/comparisons/index.md +++ b/docs/comparisons/index.md @@ -51,6 +51,8 @@ proposal. CGP examples have compiled counterparts in the website's verification The [Concepts](/docs/concepts/) pages explain CGP's own ideas without reference to another paradigm, and each comparison links the concept pages it rests on. The [tutorials](/docs/tutorials/hello) build working programs, and the [reference](/docs/reference/) specifies each construct a comparison names. +The [glossary](/docs/reference/glossary) defines the terms used across all of them, CGP's own and the +borrowed ones alike. --- diff --git a/docs/comparisons/ml-modules.md b/docs/comparisons/ml-modules.md index b27c01a2..20332631 100644 --- a/docs/comparisons/ml-modules.md +++ b/docs/comparisons/ml-modules.md @@ -19,7 +19,7 @@ modules and also compares the proposed OCaml modular-implicits extension. ## In your terms A **context** is the type on which CGP's consumer methods operate. It supplies runtime data and -selects providers for its components. An application context can gather the choices that an ML +selects providers for its components. An [application context](/docs/reference/glossary#application-context) can gather the choices that an ML program records through module bindings and functor applications. The vocabulary maps by role, with limits explained below: @@ -168,7 +168,7 @@ impl AreaCalculator { `CanCalculateArea` is the interface callers use, and `RectangleArea` implements its generated provider trait, `AreaCalculator`. The provider reads `width` and `height` from the context through [implicit arguments](/docs/concepts/implicit-arguments). A `Rectangle` wired to this provider is a -**value context**: the value being measured also determines the implementation. +**[value context](/docs/reference/glossary#value-context)**: the value being measured also determines the implementation. The consumer/provider split is specific to CGP's use of Rust traits. Distinct provider types can implement the same provider trait for a context while respecting Rust's coherence rules; wiring @@ -247,7 +247,7 @@ delegate_components! { } ``` -`App` is an **environmental context** representing the application. Its `smtp_server` field supplies +`App` is an **[environmental context](/docs/reference/glossary#environmental-context)** representing the application. Its `smtp_server` field supplies the runtime data used by `SendViaSmtp`, while the table selects behavior and the error type. The entry order has no execution meaning: the table does not construct objects or schedule startup. This is the part of functor assembly that the comparison covers, rather than all of Functoria's diff --git a/docs/comparisons/policy-based-design.md b/docs/comparisons/policy-based-design.md index ca684bf2..1a21320e 100644 --- a/docs/comparisons/policy-based-design.md +++ b/docs/comparisons/policy-based-design.md @@ -224,7 +224,7 @@ EnglishApp.run(); // Hello, World! GermanApp.run(); // Hallo Welt! ``` -`EnglishApp` and `GermanApp` are fieldless **environmental contexts**. Their role is to choose +`EnglishApp` and `GermanApp` are fieldless **[environmental contexts](/docs/reference/glossary#environmental-context)**. Their role is to choose behavior; an application with runtime configuration could store it in context fields. Both compositions use static provider selection, so policy calls need no runtime lookup or vtable. Whether the optimizer inlines a particular call remains a separate question. @@ -310,7 +310,7 @@ impl Greeter { ``` `GreetHello` asks its context for `name`; it does not contain a `name` field itself. A `Person` that -stores the field and wires the greeter is a **value context**. The generated field-access bounds +stores the field and wires the greeter is a **[value context](/docs/reference/glossary#value-context)**. The generated field-access bounds make the requirement explicit to Rust's type checker. This addresses a need that CRTP often serves: reusable behavior accessing the host's data. The diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index af5d497d..b5dc362e 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -124,7 +124,7 @@ CGP reaches compile-time reflection's payoff by a different route. It encodes a types and processes them with trait resolution, so the type system does the "reflection" rather than a routine inspecting a descriptor. The worked example below is a self-contained field writer modeled on [`cgp-serde`](https://github.com/contextgeneric/cgp-serde)'s `SerializeFields` provider, which does the -same over serde's `Serializer`. Its context is an **environmental context**: the `App` that wires how +same over serde's `Serializer`. Its context is an **[environmental context](/docs/reference/glossary#environmental-context)**: the `App` that wires how each field type is written stands for an application, and the written `Value` is a parameter. ### A type's shape becomes a type, not a descriptor diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index 8a87e2b5..c8fe2d15 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -19,7 +19,7 @@ tool, and what to expect that differs. ## In your terms A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. On this page every context is a **value context**: the record being built or the enum being +fields. On this page every context is a **[value context](/docs/reference/glossary#value-context)**: the record being built or the enum being cast is the type that carries the shape and the wiring, and each component targets `Self`. | In a row system | In CGP | diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md index 13ccdb45..9c9fa039 100644 --- a/docs/comparisons/rust-language-proposals.md +++ b/docs/comparisons/rust-language-proposals.md @@ -201,8 +201,8 @@ impl> Encoder { more, because the provider trait is always implemented for a type the crate owns. This is the overlap and orphan relief specialization cannot give, since the two providers are equally general. The encoded value has moved from `Self` into the `Value` parameter, so `Self` is free to be an -application: the contexts below are **environmental contexts**, types that stand for an application, -and the component is parameter-targeted. +application: the contexts below are **[environmental contexts](/docs/reference/glossary#environmental-context)**, types that stand for an application, +and the component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component). ### An incoherent bound resolves through the context, not at each call site @@ -299,7 +299,7 @@ app.greet(); // "Hello, World!" over exactly: the binding costs nothing at runtime, since a field read compiles to a load, and it is checked statically, since a missing field is a compile error that [`check_components!`](/docs/reference/macros/check_components) names at the wiring site. `App` here -is an environmental context with one field, and `GreetHello` is self-targeted. +is an environmental context with one field, and `GreetHello` is [self-targeted](/docs/reference/glossary#self-targeted-component). ### The context is the dictionary diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md index 0cfec37c..3f00fc0c 100644 --- a/docs/comparisons/type-classes.md +++ b/docs/comparisons/type-classes.md @@ -200,8 +200,8 @@ the one-instance-per-type limit: because a provider implements the provider trai coherence never forbids a second one. The wiring line plays the role of resolution, explicitly, where Haskell's compiler would search for the canonical instance. A provider's `#[uses]` imports are the class constraints threaded by dictionary passing, and the context is the dictionary that carries them. -`Rectangle` here is a **value context**: the type being measured also carries the wiring, and the -component is self-targeted. +`Rectangle` here is a **[value context](/docs/reference/glossary#value-context)**: the type being measured also carries the wiring, and the +component is [self-targeted](/docs/reference/glossary#self-targeted-component). ### Overlapping instances are the default, with no heuristic @@ -243,8 +243,8 @@ more specific. As providers all three compile, because each implements the provi own marker. There is no most-specific rule and therefore no ambiguity. The fragility GHC warns about, overlap silently producing incoherence, cannot arise, because the choice is never inferred. Here the encoded value has moved from `Self` into the `Value` parameter, so the contexts -that wire these providers are **environmental contexts**, types standing for an application, and the -component is parameter-targeted. +that wire these providers are **[environmental contexts](/docs/reference/glossary#environmental-context)**, types standing for an application, and the +component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component). ### Incoherent instances made deterministic and local diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index ae38458d..c84832c2 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -171,7 +171,7 @@ CGP preserves coherence while making provider selection explicit. Alternative pr to the same context, and the wiring chooses which one supplies the consumer trait. Defining a second conflicting entry for the same type and component remains an error. -Separate application contexts allow independent choices for the same data type. That arrangement +Separate [application contexts](/docs/reference/glossary#application-context) allow independent choices for the same data type. That arrangement requires moving the data into a component parameter; [Modularity Hierarchy](./modularity-hierarchy.md) explains when to use it and how it differs from the value-type wiring shown here. diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index 5af29087..e4e8bea4 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -127,7 +127,7 @@ where ``` This fragment assumes `RequestAuthenticator` and `HasAuthHeader` are defined elsewhere. -`HasAuthHeader` describes access on the request, while `self` is the application context. An +`HasAuthHeader` describes access on the request, while `self` is the [application context](/docs/reference/glossary#application-context). An implicit argument on `authenticate` would read the application instead. A named getter also lets other code require the accessor through a trait bound or supertrait. diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 64c5720f..9e91caa2 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -76,6 +76,10 @@ These pages apply the same component model to errors, computations, and data: - [Type-level DSLs](./type-level-dsls.md): Representing a small language as types resolved by the compiler. - [Recovering `Send` bounds](./send-bounds.md): Requiring sendable futures when spawning async CGP tasks. +If you came here because a page used a term you did not recognize, the +[glossary](/docs/reference/glossary) defines the vocabulary used across this documentation and points +at the page that explains each term. + --- *An AI agent wrote this page using the CGP knowledge base. Its content was verified against the diff --git a/docs/index.md b/docs/index.md index c8bdfd7e..cf0e8ed2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -54,6 +54,7 @@ Use the documentation according to the question you need to answer: - [Overview](/docs/overview): what CGP offers and where it helps. - [Concepts](/docs/concepts): how its ideas work and fit together. - [Reference](/docs/reference): the syntax and behavior of individual constructs. +- [Glossary](/docs/reference/glossary): short definitions of the terms used across this documentation. - [Resources](/docs/resources): libraries, projects, talks, and further reading. The [Context-Generic Programming Patterns book](https://patterns.contextgeneric.dev/) develops CGP diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index abd33643..d4541ba5 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -130,7 +130,7 @@ delegate_components! { } ``` -**Environmental context, parameter-targeted**: `App` carries the wiring and the shown value is a +**[Environmental context](/docs/reference/glossary#environmental-context), [parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: `App` carries the wiring and the shown value is a parameter. The loop wires every type with a registered default, and the direct `u64` line shadows whatever the namespace would otherwise supply for that one type. `ShowWithDisplay` is wired directly rather than registered, because its impl is generic over `T`, and a generic impl cannot register a diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index 63693f95..84659915 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -145,7 +145,7 @@ check_components! { Reading the resolution: `app.greet()` looks up `GreeterComponent`. `App` does not wire it directly, so the lookup falls through to `DefaultNamespace`, which redirects to `@app.GreeterComponent`, and -`App`'s own table binds that path to `GreetHello`. **Environmental context, self-targeted**: `App` +`App`'s own table binds that path to `GreetHello`. **[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component)**: `App` exists to carry the wiring and a `name` field, and the operation is about `App` itself. A second context joins the same namespace and binds a different provider at the same path, without diff --git a/docs/reference/components/can_wrap_error.md b/docs/reference/components/can_wrap_error.md index 612e5a90..827da45a 100644 --- a/docs/reference/components/can_wrap_error.md +++ b/docs/reference/components/can_wrap_error.md @@ -102,7 +102,7 @@ The provider `LoadOrFail` first raises a `String` into the context's abstract er [`CanRaiseError`](./can_raise_error.md), then wraps a further message onto it with `CanWrapError`. Both dependencies are declared with [`#[uses]`](../attributes/uses.md), so neither appears on the public `CanLoad` signature, and any context that satisfies them makes `load` produce enriched errors in its own -error type. The context is an **environmental context**, and the component targets it. +error type. The context is an **[environmental context](/docs/reference/glossary#environmental-context)**, and the component targets it. ## When to use it diff --git a/docs/reference/components/handler/async_computer.md b/docs/reference/components/handler/async_computer.md index 2d66fc8c..5034d489 100644 --- a/docs/reference/components/handler/async_computer.md +++ b/docs/reference/components/handler/async_computer.md @@ -79,7 +79,7 @@ where ``` `run` works for any context that wires an async computer for the given `Code` and `u64` input. The -example is **parameter-targeted**: the computation acts on the `Input`, while the context decides the +example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the provider. A provider is usually generated from a function with [`#[cgp_computer]`](../../macros/cgp_computer.md) rather than written by hand. diff --git a/docs/reference/components/handler/async_computer_ref.md b/docs/reference/components/handler/async_computer_ref.md index 24797d86..7419a3c9 100644 --- a/docs/reference/components/handler/async_computer_ref.md +++ b/docs/reference/components/handler/async_computer_ref.md @@ -77,7 +77,7 @@ where ``` `scan` awaits the computation while keeping ownership of the `String` with the caller. The example is -**parameter-targeted**: the computation acts on the `Input`, while the context decides the provider. +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the provider. ## When to use it diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md index 84f5050b..04b0ee0d 100644 --- a/docs/reference/components/handler/computer.md +++ b/docs/reference/components/handler/computer.md @@ -99,7 +99,7 @@ fn run(app: &App) -> u64 { `Double` implements the `Computer` provider trait for any context and any `Code`, fixing `Input` and `Output` to `u64`. `App` delegates `ComputerComponent` to it, and the call passes `PhantomData::<()>` as -the `Code` tag. The example is **parameter-targeted**: the computation acts on the `Input` value, while +the `Code` tag. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input` value, while the context decides the provider. In practice a provider like this is written with [`#[cgp_computer]`](../../macros/cgp_computer.md) rather than by hand. diff --git a/docs/reference/components/handler/computer_ref.md b/docs/reference/components/handler/computer_ref.md index c6623443..76e4d4f8 100644 --- a/docs/reference/components/handler/computer_ref.md +++ b/docs/reference/components/handler/computer_ref.md @@ -76,7 +76,7 @@ where ``` `measure` passes the input by reference, so the caller keeps ownership of the `String`. The example is -**parameter-targeted**: the computation acts on the `Input`, while the context decides the provider. +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the provider. ## When to use it diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md index 58201d25..9ab7edbc 100644 --- a/docs/reference/components/handler/handler.md +++ b/docs/reference/components/handler/handler.md @@ -99,7 +99,7 @@ where `run_with` works for any context that wires a handler for the given `Code` and `String` input, whether the wired provider is a pure `Computer`, a fallible `TryComputer`, an `AsyncComputer`, or a genuine `Handler`, because the promotion combinators make each of them satisfy `CanHandle`. This is why generic -pipeline code targets `Handler`. The example is **parameter-targeted**: the computation acts on the +pipeline code targets `Handler`. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input` type, while the context decides which provider answers. ## When to use it diff --git a/docs/reference/components/handler/handler_ref.md b/docs/reference/components/handler/handler_ref.md index dabbe38f..6e84740c 100644 --- a/docs/reference/components/handler/handler_ref.md +++ b/docs/reference/components/handler/handler_ref.md @@ -87,7 +87,7 @@ where ``` `serve` passes the request by reference, so the caller keeps ownership, and returns the context's -abstract error on failure. The example is **parameter-targeted**: the computation acts on the `Input`, +abstract error on failure. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the provider and the error type. ## When to use it diff --git a/docs/reference/components/handler/producer.md b/docs/reference/components/handler/producer.md index 153cf87b..03939e8c 100644 --- a/docs/reference/components/handler/producer.md +++ b/docs/reference/components/handler/producer.md @@ -91,7 +91,7 @@ fn run(app: &App) -> u64 { ``` `MagicNumber` produces `42` from the `Code` tag alone, and `App` delegates `ProducerComponent` to it, -giving `App` the `CanProduce<(), Output = u64>` implementation. The example is **parameter-targeted**: the +giving `App` the `CanProduce<(), Output = u64>` implementation. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the context decides which provider answers, and no value is operated on. In practice the provider is written with [`#[cgp_producer]`](../../macros/cgp_producer.md), which also wires the promotion so the same function answers the input-taking components while ignoring their input. diff --git a/docs/reference/components/handler/try_computer.md b/docs/reference/components/handler/try_computer.md index 746ec8f1..a727dfdc 100644 --- a/docs/reference/components/handler/try_computer.md +++ b/docs/reference/components/handler/try_computer.md @@ -105,7 +105,7 @@ delegate_components! { `ParseU64` returns its `u64` output or the context's abstract error, converting the concrete `ParseIntError` into that error with [`CanRaiseError`](../can_raise_error.md). Because the consumer trait supertraits `HasErrorType`, `App` must also wire an error type and an error raiser before it can call -`try_compute`. The example is **parameter-targeted**: the computation acts on the `Input`, while the +`try_compute`. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the provider and the error type. ## When to use it diff --git a/docs/reference/components/handler/try_computer_ref.md b/docs/reference/components/handler/try_computer_ref.md index 3fe88f4d..ad71a1c3 100644 --- a/docs/reference/components/handler/try_computer_ref.md +++ b/docs/reference/components/handler/try_computer_ref.md @@ -85,7 +85,7 @@ where ``` `check` passes the input by reference, so the caller keeps the `String`, and returns the context's -abstract error on failure. The example is **parameter-targeted**: the computation acts on the `Input`, +abstract error on failure. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the provider and the error type. ## When to use it diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index 32c6146d..f5a5ccb9 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -106,7 +106,7 @@ delegate_components! { Here [`#[use_type(HasErrorType.Error)]`](../attributes/use_type.md) adds `HasErrorType` as a supertrait of `CanValidate` and rewrites the bare `Error` to `::Error`, so `validate` returns the context's shared error without spelling `Self::Error`. `App` wires its error type to `String`, which -satisfies the `Debug` bound. `App` is an **environmental context**, a type that stands for the +satisfies the `Debug` bound. `App` is an **[environmental context](/docs/reference/glossary#environmental-context)**, a type that stands for the application and carries its choices, and the component targets that context rather than a value. ## When to use it diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index ba466426..2779eb75 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -105,7 +105,7 @@ where `App` resolves `HasRuntimeType` with `Runtime = TokioRuntime` through `UseType`, and resolves `HasRuntime` by reading its `runtime` field through `UseField`. `runtime_of` names neither `TokioRuntime` nor any field, so swapping `UseType` for `UseType` in a test -context retargets it at the mock with no change to its body. `App` is an **environmental context**, and +context retargets it at the mock with no change to its body. `App` is an **[environmental context](/docs/reference/glossary#environmental-context)**, and the component targets it. ## When to use it diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md index 1ac7e7e9..f3dadcdd 100644 --- a/docs/reference/components/has_runtime_type.md +++ b/docs/reference/components/has_runtime_type.md @@ -89,7 +89,7 @@ where `App` resolves `HasRuntimeType` with `Runtime = TokioRuntime` through `UseType`, so `RuntimeOf` is `TokioRuntime`. `describe` names only the runtime type and never a runtime value, which is exactly the -case `HasRuntimeType` serves alone. `App` is an **environmental context**, and the component targets it. +case `HasRuntimeType` serves alone. `App` is an **[environmental context](/docs/reference/glossary#environmental-context)**, and the component targets it. ## When to use it diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index 4caed4dd..23088211 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -96,7 +96,7 @@ where ``` `App` wires `TypeProviderComponent` to `UseType`, so the `UseType` impl makes `App` implement -`HasType` with `Type = f64`. `App` is an **environmental context** here, a type standing for +`HasType` with `Type = f64`. `App` is an **[environmental context](/docs/reference/glossary#environmental-context)** here, a type standing for the application that carries its type choices. In real code you would write the named `#[cgp_type]` layer; this page documents the substrate it rests on. diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index 069ccdf3..995cbedc 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -104,7 +104,7 @@ where The spawner requires a `Send + 'static` future, which `context.send_run(PhantomData::)` returns, so the bound `Self: CanSendRun` makes the spawn type-check. None of the abstract task or error types carry `Send` bounds; that requirement is discharged only at the concrete -[`CanSendRun`](./send_runner.md) proxy. `App` is an **environmental context**, and the task is a +[`CanSendRun`](./send_runner.md) proxy. `App` is an **[environmental context](/docs/reference/glossary#environmental-context)**, and the task is a type-level `Code` selector the wiring dispatches on. ## When to use it diff --git a/docs/reference/components/send_runner.md b/docs/reference/components/send_runner.md index ea378437..b3be82d0 100644 --- a/docs/reference/components/send_runner.md +++ b/docs/reference/components/send_runner.md @@ -105,7 +105,7 @@ The spawner requires a `Send + 'static` future, which `context.send_run(PhantomData::)` returns, so the bound `Context: CanSendRun` makes the spawn type-check. The context wires its [`CanRun`](./runner.md) tasks and supplies a `SendRunner` proxy for the inner task, and the `Send` bound is discharged only at that concrete proxy, -never on the abstract task or error types. `App` is an **environmental context**, and the task is a +never on the abstract task or error types. `App` is an **[environmental context](/docs/reference/glossary#environmental-context)**, and the task is a type-level `Code` selector. ## When to use it diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md new file mode 100644 index 00000000..a9659566 --- /dev/null +++ b/docs/reference/glossary.md @@ -0,0 +1,584 @@ +--- +sidebar_label: 'Glossary' +sidebar_position: 91 +toc_max_heading_level: 2 +description: 'Short definitions of the CGP, Rust, and related terms used across this documentation, each linking to the page that explains it.' +--- + +# Glossary + +Short definitions of the words used across this documentation, each pointing at the page that +explains the idea properly. It is a place to look a term up, not a place to learn CGP: every entry is +a sentence or two and a link onward. + +If you arrived knowing the name of a *construct* rather than a word — `IsPresent`, +`#[cgp_new_provider]` — the [reference index](./index.md) is the page that routes those. + +## CGP terms + +The vocabulary this documentation uses for CGP's own constructs and roles. + +### abstract type + +A type that generic code names without fixing, leaving each context to choose it. An error type, a +runtime, or a scalar can be abstract, so intermediate code refers to it without taking it as a +separate type parameter. + +[Abstract types](/docs/concepts/abstract-types) · [`#[cgp_type]`](./macros/cgp_type.md) + +### aggregate provider + +A zero-sized provider holding a wiring table of its own, so a bundle of components can be delegated to +it as one reusable unit. It is dispatched *to* by contexts and is never its own context. + +[Aggregate providers](/docs/concepts/aggregate-providers) · +[`delegate_components!`](./macros/delegate_components.md) + +### application context + +An environmental context standing for one application, where that application's choices live. It may +carry runtime values such as a client or a configuration, or be an empty `struct App;` whose only job +is to be a name the wiring hangs off. + +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) + +### blanket trait + +A trait with a single blanket implementation covering every type that satisfies its bounds, rather +than a component with interchangeable providers. `#[cgp_fn]` and `#[blanket_trait]` generate these. + +[`#[cgp_fn]`](./macros/cgp_fn.md) · [`#[blanket_trait]`](./macros/blanket_trait.md) + +### check trait + +A generated trait whose supertraits assert that a context can use the components listed, turning a +latent wiring gap into a compile error at the wiring site. Wiring is otherwise **lazy**: a delegation +entry alone does not verify that the provider's dependencies hold. + +[Checking your wiring](/docs/concepts/check-traits) · +[`check_components!`](./macros/check_components.md) + +### component + +An interface for which a context can select an implementation, generated from one trait as a consumer +trait, a provider trait, and a marker used as the wiring key. A component may contain several methods, +associated types, and consts, exactly as an ordinary trait may. + +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · +[`#[cgp_component]`](./macros/cgp_component.md) + +### component marker + +The zero-sized type naming a component in a wiring table, such as `GreeterComponent`. It is the key +the table looks a provider up by, and it carries no behavior of its own. + +[`#[cgp_component]`](./macros/cgp_component.md) · +[`DelegateComponent`](./traits/wiring/delegate_component.md) + +### consumer trait + +The ordinary, `self`-style trait that callers use, such as `CanGreet`. It stays a normal Rust trait +and can also be implemented directly on a type, without any provider machinery. + +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · +[`#[cgp_component]`](./macros/cgp_component.md) + +### context + +The type the method runs on, which supplies the values it needs as its fields. It is also the type +that owns the wiring, so it decides which provider each of its components uses. + +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) + +### context-generic programming + +The name of the paradigm: writing implementations against what a context provides rather than against +a concrete type, so a context selects among them at compile time. + +[Introduction](/docs/) · [Bypassing coherence](/docs/concepts/coherence) + +### delegation + +An entry in a wiring table, mapping one component to the provider that supplies it. Delegating a +component does not by itself check that the provider's dependencies hold — that is what a check trait +is for. + +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · +[`DelegateComponent`](./traits/wiring/delegate_component.md) + +### dispatch + +Routing an input to the handler that matches it, chosen by the wiring rather than by a runtime test +of the value. Variant dispatch is checked for exhaustiveness at compile time, without a wildcard arm. + +[Dispatching](/docs/concepts/dispatching) · +[Dispatch combinators](./providers/dispatch/index.md) + +### environmental context + +A context standing for an application or an environment rather than for the data being operated on, +carrying the implementation choices and dependencies its providers need. Most CGP code is written this +way. + +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) · +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) + +### expansion + +The ordinary Rust a CGP macro generates — the traits, impls, and marker types behind a construct, +also called what a construct desugars to. `cargo cgp expand` prints it with CGP's type-level +constructs restored to readable macro notation. + +[`cargo cgp expand`](/docs/cargo-cgp/expand) · +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) + +### extensible record + +A struct whose fields are exposed to generic code as type-level data, so a value can be built or read +field by field without naming its concrete type. + +[Extensible records](/docs/concepts/extensible-records) · +[`#[derive(CgpRecord)]`](./derives/derive_cgp_record.md) + +### extensible variant + +An enum whose variants are exposed to generic code as type-level data, so a value can be constructed +or matched variant by variant without naming its concrete type. + +[Extensible variants](/docs/concepts/extensible-variants) · +[`#[derive(CgpVariant)]`](./derives/derive_cgp_variant.md) + +### getter trait + +A trait declaring a named accessor for a value the context holds, used where an implicit argument +cannot reach — a field on another type, an accessor other code requires by name, or a return type +inferred from the field. + +[Implicit arguments](/docs/concepts/implicit-arguments) · +[`#[cgp_auto_getter]`](./macros/cgp_auto_getter.md) + +### handler + +A component in CGP's computation family, which models a computation along the axes of synchronous +versus async, fallible versus infallible, and input-taking versus input-free. `Handler` itself is the +general async, fallible case. + +[Handlers](/docs/concepts/handlers) · [`Handler`](./components/handler/handler.md) + +### higher-order provider + +A provider taking another provider as a generic parameter and constraining it with a provider-trait +bound, so its inner behavior is chosen by wiring rather than fixed. + +[Higher-order providers](/docs/concepts/higher-order-providers) · +[`#[use_provider]`](./attributes/use_provider.md) + +### impl-side dependency + +A requirement an implementation declares without adding it to the interface callers see. A provider +can require `HasName` while the consumer trait says nothing about it, so the bound never reaches a +caller. + +[Impl-side dependencies](/docs/concepts/impl-side-dependencies) · [`#[uses]`](./attributes/uses.md) + +### implicit argument + +A provider argument that looks like an ordinary function parameter but is read from a same-named field +on the context. It is the default way to read a context field. + +[Implicit arguments](/docs/concepts/implicit-arguments) · [`#[implicit]`](./attributes/implicit.md) + +### marker type + +A zero-sized type carrying no data, used as a name the compiler can resolve rather than as a value. +Providers and component markers are both marker types, and neither is ever instantiated. + +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · +[`PhantomData`](./types/phantom_data.md) + +### namespace + +A reusable wiring table a context can join, optionally inheriting from a parent, so a growing +configuration stays short. Lookups without a direct entry on the context forward through it. + +[Namespaces](/docs/concepts/namespaces) · [`cgp_namespace!`](./macros/cgp_namespace.md) + +### parameter-targeted component + +A component whose target is a type parameter, while the context selects the implementation, as in +`CanEncode`. Different applications can treat the same target type differently. + +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) + +### partial record + +The intermediate value produced while a record is being built or taken apart field by field, carrying +markers recording which fields are present so far. + +[Extensible records](/docs/concepts/extensible-records) · +[`MapType`](./traits/type-level/map_type.md) + +### provider + +A named implementation a context can select, written as a zero-sized marker type that exists only at +the type level. Two providers whose implementations would otherwise overlap can coexist, because each +implements the provider trait on its own type. + +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · +[`#[cgp_impl]`](./macros/cgp_impl.md) + +### provider trait + +The interface a provider implements, with `Self` moved out into an explicit context parameter, as in +`Greeter`. Writing a provider with `#[cgp_impl]` means you rarely write this form by hand. + +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · +[`#[cgp_impl]`](./macros/cgp_impl.md) + +### selector + +A type parameter used to choose an implementation rather than to identify the value being operated on. +In `CanCompute`, `Code` is the selector and `Input` is the target. + +[Handlers](/docs/concepts/handlers) · [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) + +### self-targeted component + +A component whose operation acts on, or describes, the context itself, as in `CanGreet` or +`HasErrorType`. Most components are self-targeted. + +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) + +### target + +The thing a component's operation acts on: the context itself for a self-targeted component, or a type +parameter for a parameter-targeted one. A generic parameter alone does not make a component +parameter-targeted. + +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) + +### type-level string + +A string encoded as a type, used to name a field or a path so that the compiler can resolve it. It is +written with the `Symbol!` macro and recovered as ordinary text where a runtime name is needed. + +[`Symbol!`](./macros/symbol.md) · [`Chars`](./types/chars.md) + +### value context + +A context that *is* the data being operated on, as `String` is in `String: CanEncode`. One type is +both the target and the context, so it has one implementation of that component program-wide. + +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) + +### wiring + +The type-level table on a context recording which provider supplies each component. The compiler +resolves it during type checking, so a wired call compiles to a direct call with no runtime lookup. + +[Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · +[`delegate_components!`](./macros/delegate_components.md) + +## Rust terms + +Rust concepts this documentation assumes, defined only as far as reading these pages requires. Each +links to Rust's own documentation, which explains them properly. + +### associated type + +A type declared by a trait and chosen by each implementation, so the implementation decides it rather +than the caller. + +[Rust Reference: Associated items](https://doc.rust-lang.org/reference/items/associated-items.html) + +### blanket implementation + +An implementation written for every type satisfying a set of bounds, such as `impl Foo for T`, +rather than for one named type. CGP's generated code rests on these. + +[Rust Reference: Implementations](https://doc.rust-lang.org/reference/items/implementations.html) + +### coherence + +Rust's guarantee that any given trait and type have at most one implementation, so every lookup +resolves the same way anywhere in a program. The overlap and orphan rules are what buy it. + +[Rust Reference: Implementations](https://doc.rust-lang.org/reference/items/implementations.html) · +[Bypassing coherence](/docs/concepts/coherence) + +### dynamic dispatch + +Choosing an implementation at run time through a pointer to a method table, as `dyn Trait` does. + +[Rust Book: Trait objects](https://doc.rust-lang.org/book/ch18-02-trait-objects.html) + +### generic parameter + +A type, lifetime, or const a definition is written against and a caller supplies, so the definition +works for many concrete arguments. + +[Rust Book: Generic data types](https://doc.rust-lang.org/book/ch10-01-syntax.html) + +### lifetime + +A named region of code for which a reference is valid, which the compiler uses to check that borrowed +data outlives the borrow. + +[Rust Book: Lifetime syntax](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html) + +### monomorphization + +The compiler generating a separate copy of generic code for each set of concrete type arguments it is +used with. + +[Rust Book: Generic data types](https://doc.rust-lang.org/book/ch10-01-syntax.html) + +### orphan rule + +The restriction that an implementation must be written in the crate owning either the trait or the +type, which stops two crates implementing the same trait for the same type. + +[Rust Reference: Implementations](https://doc.rust-lang.org/reference/items/implementations.html) + +### `PhantomData` + +A zero-sized marker letting a type carry a parameter it does not store a value of. CGP uses it to pass +type-level names into a method and to parameterize provider structs. + +[std: `PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html) + +### procedural macro + +A macro implemented as Rust code that reads and produces token streams, which is how CGP's attributes +and derives are built. + +[Rust Reference: Procedural macros](https://doc.rust-lang.org/reference/procedural-macros.html) + +### static dispatch + +Resolving a call at compile time to a direct call to a known function, with no runtime lookup. CGP +wiring resolves this way. + +[Rust Book: Generic data types](https://doc.rust-lang.org/book/ch10-01-syntax.html) + +### supertrait + +A trait required by another trait, so implementing the second means the first is available too. CGP +adds one with `#[extend]` rather than native `:` syntax, which keeps the generated trait's bounds +together. + +[Rust Reference: Traits](https://doc.rust-lang.org/reference/items/traits.html) · +[`#[extend]`](./attributes/extend.md) + +### trait + +A named set of methods and associated items a type can implement, and the interface generic code is +written against. + +[Rust Book: Traits](https://doc.rust-lang.org/book/ch10-02-traits.html) + +### trait bound + +A requirement that a type parameter implement a given trait, written as `T: Display` or in a `where` +clause. + +[Rust Book: Traits](https://doc.rust-lang.org/book/ch10-02-traits.html) + +### trait object + +A value accessed through a trait rather than its concrete type, written `dyn Trait`, with its methods +resolved at run time. + +[Rust Reference: Trait objects](https://doc.rust-lang.org/reference/types/trait-object.html) + +## Related concepts + +Ideas from other languages and paradigms that readers often arrive holding. Each entry defines the +term as its own community uses it, and links both to that community's documentation and to the +comparison page that places CGP against it. + +### algebraic effect + +An operation whose meaning is supplied by a handler installed by the caller, rather than by the code +performing it, letting effectful code be written without committing to an interpretation. + +[Comparison: Algebraic effects](/docs/comparisons/algebraic-effects) · +[Koka: the book](https://koka-lang.github.io/koka/doc/book.html) + +### capability + +An unforgeable value that both designates a resource and authorizes its use, so holding it *is* the +permission. CGP's arrangement resembles it in that a provider reaches only what its declared +dependencies supply, and the comparison page sets out how far the resemblance goes. + +[Comparison: Capabilities](/docs/comparisons/capabilities) · +[Object-capability model](https://en.wikipedia.org/wiki/Object-capability_model) + +### CRTP + +The curiously recurring template pattern: a C++ base class parameterized by its own derived class, so +a base can call into the derived type with calls resolved at compile time. + +[Comparison: Policy-based design](/docs/comparisons/policy-based-design) · +[CRTP](https://en.cppreference.com/w/cpp/language/crtp) + +### dependency injection + +Supplying a component's dependencies from outside rather than having it construct them, so the choice +of implementation is made by the code assembling the program. + +[Comparison: Dependency injection](/docs/comparisons/dependency-injection) · +[Baeldung: IoC and dependency injection](https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring) + +### dictionary passing + +The implementation strategy in which a type-class constraint becomes a hidden argument carrying the +chosen implementation's methods, passed down through calls. + +[Comparison: Type classes](/docs/comparisons/type-classes) · +[How to make ad-hoc polymorphism less ad hoc](https://dl.acm.org/doi/10.1145/75277.75283) + +### effect handler + +The construct interpreting an algebraic effect's operations, deciding what each one does and where +control resumes afterwards. + +[Comparison: Algebraic effects](/docs/comparisons/algebraic-effects) · +[Plotkin and Pretnar: Handling algebraic effects](https://homepages.inf.ed.ac.uk/gdp/publications/Effect_Handlers.pdf) + +### functor + +In ML, a module parameterized by another module: given a structure satisfying a signature, it produces +a new structure. + +[Comparison: ML modules](/docs/comparisons/ml-modules) · +[OCaml: functors](https://ocaml.org/docs/functors) + +### implicit parameter + +An argument the compiler supplies from context rather than the caller writing it, as Scala's `using` +parameters and Haskell's `ImplicitParams` do. + +[Comparison: Implicit parameters](/docs/comparisons/implicit-parameters) · +[Scala 3: context parameters](https://docs.scala-lang.org/scala3/book/ca-context-parameters.html) + +### instance resolution + +The compiler's search for the implementation satisfying a type-class constraint, which in a coherent +system finds at most one and does not ask the programmer to choose. + +[Comparison: Type classes](/docs/comparisons/type-classes) · +[GHC: instance declarations](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html) + +### IoC container + +The runtime registry in a dependency-injection framework that holds bindings from interfaces to +implementations and constructs the object graph from them. + +[Comparison: Dependency injection](/docs/comparisons/dependency-injection) · +[Spring: the IoC container](https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html) + +### modular implicits + +A proposed OCaml feature allowing modules to be passed implicitly, bringing type-class-style +resolution to the module system. + +[Comparison: ML modules](/docs/comparisons/ml-modules) · +[Modular implicits](https://arxiv.org/abs/1512.01895) + +### named impl + +An implementation given a name so that it can be selected explicitly, rather than being anonymous and +resolved by coherence. Several Rust proposals and Cairo's shipped feature take this shape. + +[Comparison: Rust's own proposals](/docs/comparisons/rust-language-proposals) · +[An Incoherent Rust](https://www.boxyuwu.blog/posts/an-incoherent-rust/) + +### object capability + +A capability in the object-capability model, where a reference to an object is itself the authority to +invoke it, and authority spreads only by passing references. + +[Comparison: Capabilities](/docs/comparisons/capabilities) · +[Robust composition](https://papers.agoric.com/assets/pdf/papers/robust-composition.pdf) + +### policy-based design + +The C++ technique of assembling a class from interchangeable policy classes supplied as template +arguments, so behavior is composed at compile time. + +[Comparison: Policy-based design](/docs/comparisons/policy-based-design) · +[Policy-based design](https://en.wikipedia.org/wiki/Policy-based_design) + +### reflection + +Inspecting a type's structure — its fields, variants, and names — from within the program. CGP's +equivalent is encoded in types and resolved at compile time rather than read from runtime metadata. + +[Comparison: Reflection](/docs/comparisons/reflection) · +[Rust: reflection and comptime goal](https://rust-lang.github.io/rust-project-goals/2026/reflection-and-comptime.html) + +### row polymorphism + +A type system in which a record or variant type is parameterized by a *row* of labelled fields, so +code can be written against types that have at least the fields it needs. + +[Comparison: Row polymorphism](/docs/comparisons/row-polymorphism) · +[Row polymorphism](https://en.wikipedia.org/wiki/Row_polymorphism) + +### row variable + +The variable standing for "the rest of the fields" in a row-polymorphic type, letting one definition +apply to records that differ in the fields it does not mention. + +[Comparison: Row polymorphism](/docs/comparisons/row-polymorphism) · +[PureScript: types](https://github.com/purescript/documentation/blob/master/language/Types.md) + +### signature and structure + +In ML, a signature is the interface a module satisfies, and a structure is a module satisfying it — +roughly a type and its implementation, related by ascription rather than by declaration. + +[Comparison: ML modules](/docs/comparisons/ml-modules) · +[ML modules, explained](https://cs.wellesley.edu/~cs251/s12/handouts/modules.pdf) + +### specialization + +A proposed Rust feature letting a more specific implementation override a more general one, which +would relax the overlap rule in a controlled way. It remains unstable. + +[Comparison: Rust's own proposals](/docs/comparisons/rust-language-proposals) · +[RFC 1210](https://rust-lang.github.io/rfcs/1210-impl-specialization.html) · +[Tracking issue](https://github.com/rust-lang/rust/issues/31844) + +### structural typing + +Treating types as compatible when their structure matches, rather than when they were declared to be +related; its dynamic-language cousin is duck typing. Rust remains nominal, and CGP's wiring is +explicit, so the resemblance is partial. + +[Comparison: Row polymorphism](/docs/comparisons/row-polymorphism) · +[Structural type system](https://en.wikipedia.org/wiki/Structural_type_system) + +### type class + +An interface a type can be declared to satisfy after the fact, with the compiler selecting the +implementation from the types at a call site. + +[Comparison: Type classes](/docs/comparisons/type-classes) · +[Type class](https://en.wikipedia.org/wiki/Type_class) + +### vtable + +The table of function pointers behind a dynamically dispatched call, consulted at run time to find the +implementation. CGP wiring has no runtime counterpart to it. + +[Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch) · +[Virtual method table](https://en.wikipedia.org/wiki/Virtual_method_table) + +--- + +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/index.md b/docs/reference/index.md index 3385d5c3..fdc4156f 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -224,6 +224,10 @@ When wiring fails, three traits are what you will see named: name, and [`CanUseComponent`](./traits/wiring/can_use_component.md), which is what a check asserts. The [compile errors](./errors.md) page covers the recurring failures and how to read them. +If what you are missing is a *word* rather than a construct — environmental context, impl-side +dependency, type class — the [glossary](./glossary.md) defines the terms this documentation uses and +links to the page that explains each one. + ## Looking for a name you don't see? Almost every construct has a page of its own. The exceptions are names that are not separately diff --git a/docs/reference/traits/field-access/field_getter.md b/docs/reference/traits/field-access/field_getter.md index 36670d20..e8dd06fc 100644 --- a/docs/reference/traits/field-access/field_getter.md +++ b/docs/reference/traits/field-access/field_getter.md @@ -95,7 +95,7 @@ delegate_components! { } ``` -`person.name()` now returns the `first_name` field. **Value context, self-targeted.** +`person.name()` now returns the `first_name` field. **[Value context](/docs/reference/glossary#value-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** A second context can answer the same getter from a different field by changing one wiring line, which the provider-side shape buys and a plain [`HasField`](./has_field.md) bound cannot express. diff --git a/docs/reference/traits/field-access/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md index a9220fa9..7bf234d6 100644 --- a/docs/reference/traits/field-access/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -97,7 +97,7 @@ delegate_components! { } ``` -**Environmental context, self-targeted.** [`ChainGetters`](../../providers/chain_getters.md) descends into +**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** [`ChainGetters`](../../providers/chain_getters.md) descends into `inner` with `FieldMapper::map_field` and then applies the inner provider to what it finds, so `outer.name()` resolves to `outer.inner.name` with no lifetime obligations leaking into either type. diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index 42db8ebc..fbe66f77 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -98,7 +98,7 @@ delegate_components! { ``` `Person` derives the access, so it satisfies exactly the bound `GreetHello` requires and the wiring -compiles. **Value context, self-targeted**: the wired type is the data the method runs on. +compiles. **[Value context](/docs/reference/glossary#value-context), [self-targeted](/docs/reference/glossary#self-targeted-component)**: the wired type is the data the method runs on. **Written idiomatically, none of that bound is visible.** The same read is an [`#[implicit]`](../../attributes/implicit.md) argument: diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index b23e7a08..4b4a8d4f 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -88,7 +88,7 @@ delegate_components! { } ``` -**Environmental context, self-targeted**: `App` stands for the application and carries the wiring. +**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component)**: `App` stands for the application and carries the wiring. Mutable access passes through a smart pointer too, via a `DerefMut` forwarding impl, so a `Box` resolves the write to the inner struct. diff --git a/docs/reference/traits/field-access/mut_field_getter.md b/docs/reference/traits/field-access/mut_field_getter.md index 8809de59..98499833 100644 --- a/docs/reference/traits/field-access/mut_field_getter.md +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -85,7 +85,7 @@ delegate_components! { } ``` -**Environmental context, self-targeted.** The getter reads `request_count` though it is named `counter`, +**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** The getter reads `request_count` though it is named `counter`, and because [`UseField`](../../providers/use_field.md) implements `MutFieldGetter` as well, a provider that holds `&mut App` can write through the same wiring. diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index 681f0b3a..60803bbf 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -129,7 +129,7 @@ delegate_components! { } ``` -**Environmental context, parameter-targeted.** `App` carries the wiring and the shown value is a +**[Environmental context](/docs/reference/glossary#environmental-context), [parameter-targeted](/docs/reference/glossary#parameter-targeted-component).** `App` carries the wiring and the shown value is a parameter. The loop wires every type with a registered default by projecting `T: DefaultImpls1`, and the direct `u64` line shadows whatever the namespace would otherwise supply for that one type. diff --git a/docs/reference/traits/namespace/default_impls2.md b/docs/reference/traits/namespace/default_impls2.md index f61fd313..48c411af 100644 --- a/docs/reference/traits/namespace/default_impls2.md +++ b/docs/reference/traits/namespace/default_impls2.md @@ -104,7 +104,7 @@ delegate_components! { } ``` -**Environmental context, parameter-targeted.** The loop variable must still appear in the key, exactly as +**[Environmental context](/docs/reference/glossary#environmental-context), [parameter-targeted](/docs/reference/glossary#parameter-targeted-component).** The loop variable must still appear in the key, exactly as for the one-type form. ## When to use it diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index 93859381..0bab9c4b 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -92,7 +92,7 @@ delegate_components! { } ``` -**Environmental context, self-targeted.** The header forwards `App`'s unwired lookups through the +**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** The header forwards `App`'s unwired lookups through the namespace, and the direct entry shadows whatever the namespace would otherwise supply for that one key, the inheritance-with-override shape presets rely on. From 96ef34259deb23ff1ec16a8cc2246f27475b0c88 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 20 Sep 2026 15:04:18 +0000 Subject: [PATCH 084/516] Link the rest of the glossary's vocabulary from the pages that use it Seventeen more terms linked on first use where a page uses them bare: the CGP terms with an expository home elsewhere, and the Rust concepts the site assumes. 289 links across 136 pages, each leaving the inline gloss beside it. Three rules decided what was left alone, and they are recorded in the knowledge base as settled rather than as unfinished work. A page that owns a term does not link it, so Bypassing coherence does not link coherence. A compound use is not the general term, so CGP's own consumer and provider blanket impls keep their abbreviated spelling and only the full "blanket implementation" links. And the basic vocabulary is already glossed per page, so context, component, provider, wiring and the two trait names are left as the section's working words. Links go in page bodies, never in the closing Related constructs lists, which are curated routes carrying one destination per line. Terms appearing only in such a list get no link. Co-Authored-By: Claude Opus 5 --- docs/cargo-cgp/expand.md | 2 +- docs/comparisons/algebraic-effects.md | 2 +- docs/comparisons/capabilities.md | 2 +- docs/comparisons/dependency-injection.md | 2 +- docs/comparisons/dynamic-dispatch.md | 6 +++--- docs/comparisons/implicit-parameters.md | 6 +++--- docs/comparisons/ml-modules.md | 8 ++++---- docs/comparisons/policy-based-design.md | 4 ++-- docs/comparisons/reflection.md | 4 ++-- docs/comparisons/row-polymorphism.md | 6 +++--- docs/comparisons/rust-language-proposals.md | 6 +++--- docs/comparisons/type-classes.md | 8 ++++---- docs/concepts/check-traits.md | 2 +- docs/concepts/coherence.md | 4 ++-- docs/concepts/consumer-and-provider-traits.md | 4 ++-- docs/concepts/dispatching.md | 4 ++-- docs/concepts/impl-side-dependencies.md | 4 ++-- docs/concepts/implicit-arguments.md | 4 ++-- docs/concepts/modularity-hierarchy.md | 12 ++++++------ docs/concepts/namespaces.md | 2 +- docs/concepts/send-bounds.md | 2 +- docs/overview.md | 8 ++++---- docs/reference/attributes/default_impl.md | 2 +- docs/reference/attributes/derive_delegate.md | 4 ++-- docs/reference/attributes/extend.md | 2 +- docs/reference/attributes/extend_where.md | 4 ++-- docs/reference/attributes/impl_generics.md | 4 ++-- docs/reference/attributes/implicit.md | 6 +++--- docs/reference/attributes/index.md | 6 +++--- docs/reference/attributes/prefix.md | 8 ++++---- docs/reference/attributes/use_provider.md | 2 +- docs/reference/attributes/use_type.md | 4 ++-- docs/reference/attributes/uses.md | 6 +++--- docs/reference/components/can_raise_error.md | 2 +- docs/reference/components/can_wrap_error.md | 2 +- docs/reference/components/handler/async_computer.md | 2 +- .../components/handler/async_computer_ref.md | 2 +- docs/reference/components/handler/computer.md | 2 +- docs/reference/components/handler/computer_ref.md | 2 +- docs/reference/components/handler/handler.md | 2 +- docs/reference/components/handler/handler_ref.md | 2 +- docs/reference/components/handler/index.md | 2 +- docs/reference/components/handler/try_computer.md | 2 +- .../reference/components/handler/try_computer_ref.md | 2 +- docs/reference/components/has_error_type.md | 4 ++-- docs/reference/components/has_runtime.md | 4 ++-- docs/reference/components/has_runtime_type.md | 4 ++-- docs/reference/components/has_type.md | 2 +- docs/reference/components/index.md | 2 +- docs/reference/components/runner.md | 2 +- docs/reference/components/send_runner.md | 4 ++-- docs/reference/derives/derive_cgp_record.md | 2 +- docs/reference/derives/derive_has_field.md | 8 ++++---- docs/reference/errors.md | 8 ++++---- docs/reference/macros/async_trait.md | 2 +- docs/reference/macros/blanket_trait.md | 6 +++--- docs/reference/macros/cgp_auto_dispatch.md | 2 +- docs/reference/macros/cgp_auto_getter.md | 8 ++++---- docs/reference/macros/cgp_component.md | 6 +++--- docs/reference/macros/cgp_computer.md | 2 +- docs/reference/macros/cgp_fn.md | 8 ++++---- docs/reference/macros/cgp_getter.md | 2 +- docs/reference/macros/cgp_impl.md | 8 ++++---- docs/reference/macros/cgp_namespace.md | 2 +- docs/reference/macros/cgp_producer.md | 2 +- docs/reference/macros/cgp_provider.md | 2 +- docs/reference/macros/cgp_type.md | 2 +- docs/reference/macros/check_components.md | 4 ++-- .../macros/delegate_and_check_components.md | 4 ++-- docs/reference/macros/delegate_components.md | 6 +++--- docs/reference/macros/index.md | 2 +- docs/reference/macros/path.md | 2 +- docs/reference/macros/product.md | 2 +- docs/reference/macros/sum.md | 2 +- docs/reference/macros/symbol.md | 2 +- .../providers/dispatch/build_and_set_field.md | 2 +- .../providers/dispatch/build_with_handlers.md | 2 +- docs/reference/providers/index.md | 4 ++-- docs/reference/providers/redirect_lookup.md | 2 +- docs/reference/providers/use_context.md | 8 ++++---- docs/reference/providers/use_delegated_type.md | 4 ++-- docs/reference/providers/use_field.md | 6 +++--- docs/reference/providers/use_fields.md | 4 ++-- docs/reference/providers/use_type.md | 4 ++-- docs/reference/providers/with_context.md | 2 +- docs/reference/providers/with_delegated_type.md | 2 +- docs/reference/providers/with_provider.md | 4 ++-- docs/reference/providers/with_type.md | 2 +- docs/reference/traits/builder/build_field.md | 2 +- docs/reference/traits/builder/finalize_build.md | 4 ++-- docs/reference/traits/builder/index.md | 2 +- docs/reference/traits/builder/partial_data.md | 4 ++-- docs/reference/traits/builder/take_field.md | 2 +- docs/reference/traits/builder/update_field.md | 2 +- docs/reference/traits/field-access/field_mapper.md | 2 +- docs/reference/traits/field-access/has_field_mut.md | 2 +- docs/reference/traits/field-access/map_field.md | 2 +- .../traits/field-access/mut_field_getter.md | 2 +- docs/reference/traits/formatting/index.md | 2 +- docs/reference/traits/formatting/static_format.md | 2 +- docs/reference/traits/formatting/static_string.md | 2 +- docs/reference/traits/namespace/default_impls1.md | 2 +- docs/reference/traits/namespace/default_impls2.md | 2 +- docs/reference/traits/namespace/default_namespace.md | 2 +- .../traits/optional/can_build_with_default.md | 2 +- .../traits/optional/can_finalize_with_default.md | 4 ++-- docs/reference/traits/optional/finalize_optional.md | 4 ++-- .../traits/optional/has_optional_builder.md | 4 ++-- docs/reference/traits/optional/index.md | 2 +- docs/reference/traits/optional/set_optional.md | 2 +- docs/reference/traits/optional/to_optional.md | 2 +- .../traits/optional/transform_map_default.md | 2 +- docs/reference/traits/optional/transform_optional.md | 2 +- docs/reference/traits/shape/from_fields.md | 2 +- docs/reference/traits/shape/to_fields.md | 2 +- docs/reference/traits/shape/to_fields_ref.md | 2 +- docs/reference/traits/type-level/index.md | 2 +- docs/reference/traits/type-level/map_fields.md | 2 +- .../traits/type-level/transform_map_fields.md | 2 +- docs/reference/traits/wiring/can_use_component.md | 2 +- docs/reference/traits/wiring/delegate_component.md | 4 ++-- docs/reference/traits/wiring/is_provider_for.md | 6 +++--- docs/reference/types/chars.md | 2 +- docs/reference/types/field.md | 2 +- docs/reference/types/life.md | 2 +- docs/reference/types/path_cons.md | 2 +- .../area-calculation/context-generic-functions.md | 8 ++++---- docs/tutorials/area-calculation/index.md | 2 +- docs/tutorials/area-calculation/static-dispatch.md | 2 +- docs/tutorials/hello.md | 2 +- 130 files changed, 220 insertions(+), 220 deletions(-) diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 4fd35c5a..73eaffd5 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -131,7 +131,7 @@ where you learn it exists. CGP's generated code is dominated by *type-level constructs*, and a general expander prints them as the compiler stores them. -**A field name is the clearest case.** CGP encodes it as a type-level string — one type parameter per +**A field name is the clearest case.** CGP encodes it as a [type-level string](/docs/reference/glossary#type-level-string) — one type parameter per character. Expanded generically, the `height` tag above reads: ```text diff --git a/docs/comparisons/algebraic-effects.md b/docs/comparisons/algebraic-effects.md index 0e9c8ccf..e6e2ae6c 100644 --- a/docs/comparisons/algebraic-effects.md +++ b/docs/comparisons/algebraic-effects.md @@ -26,7 +26,7 @@ Rust type rather than installed on the runtime call stack. | An operation | A method of the consumer trait | | A handler interpreting an operation | A **provider** implementing the corresponding method | | Installing a handler | **Wiring** a provider on a context | -| Requirements recorded in an effect row | **Impl-side dependencies**, with a narrower guarantee than effect typing | +| Requirements recorded in an effect row | **[Impl-side dependencies](/docs/reference/glossary#impl-side-dependency)**, with a narrower guarantee than effect typing | | Checking that required operations have handlers | `check_components!` verifies declared provider dependencies | | A captured continuation | Without a direct counterpart; provider methods use ordinary Rust control flow | diff --git a/docs/comparisons/capabilities.md b/docs/comparisons/capabilities.md index 60d77a22..726ec690 100644 --- a/docs/comparisons/capabilities.md +++ b/docs/comparisons/capabilities.md @@ -22,7 +22,7 @@ that context. | In capability-oriented code | In CGP | | --- | --- | -| A requirement on a computation's environment | An **impl-side dependency**, declared with `#[uses]` or `#[implicit]` | +| A requirement on a computation's environment | An **[impl-side dependency](/docs/reference/glossary#impl-side-dependency)**, declared with `#[uses]` or `#[implicit]` | | An environment supplying a required value | A context value with the required field | | A capability value passed to an operation | A context field borrowed by a provider | | Checking that requirements are supplied | `check_components!` verifies declared dependencies | diff --git a/docs/comparisons/dependency-injection.md b/docs/comparisons/dependency-injection.md index a9178c72..f60faa31 100644 --- a/docs/comparisons/dependency-injection.md +++ b/docs/comparisons/dependency-injection.md @@ -23,7 +23,7 @@ constructs and manages those values. | --- | --- | | An implementation bound to an interface | A **provider**: a named, interchangeable implementation | | A configuration class or module | **Wiring**, written in a `delegate_components!` table | -| A constructor dependency | An **impl-side dependency**, declared with `#[uses]` or `#[implicit]` | +| A constructor dependency | An **[impl-side dependency](/docs/reference/glossary#impl-side-dependency)**, declared with `#[uses]` or `#[implicit]` | | The interface a bean implements | A consumer trait, grouped with its provider trait into a **component** | | Graph validation at startup or build time | `check_components!`, at compile time | | Container-managed instances and lifetimes | Context fields and ordinary Rust construction, ownership, and borrowing | diff --git a/docs/comparisons/dynamic-dispatch.md b/docs/comparisons/dynamic-dispatch.md index 951887a8..8995a819 100644 --- a/docs/comparisons/dynamic-dispatch.md +++ b/docs/comparisons/dynamic-dispatch.md @@ -25,7 +25,7 @@ layers of delegation lead to the provider. | An interface declaring methods | A consumer trait within a **component** | | An implementation of that interface | A **provider** | | A method table or vtable | A **wiring table**, resolved by the compiler | -| Shared behavior reached through delegation | An aggregate provider or namespace | +| Shared behavior reached through delegation | An [aggregate provider](/docs/reference/glossary#aggregate-provider) or namespace | | Checking that a receiver supports an operation | Trait bounds and `check_components!` | ## The idea, briefly @@ -126,7 +126,7 @@ separate target. [Implicit arguments](/docs/concepts/implicit-arguments) explain ### Implementation choice is deferred to wiring A generic caller can invoke `context.area()` through `CanCalculateArea` without choosing an -implementation. The context's wiring supplies that choice, and monomorphization resolves the route +implementation. The context's wiring supplies that choice, and [monomorphization](/docs/reference/glossary#monomorphization) resolves the route to a static call. This allows provider selection after the generic caller has been written, while keeping that selection fixed for each concrete context type. @@ -234,7 +234,7 @@ delegate_components! { through [`RedirectLookup`](/docs/reference/providers/redirect_lookup), which follows type-level paths. This resembles sharing defaults through a prototype, but customization fills unbound paths rather than shadowing already-bound entries. An attempt to bind the same key again conflicts under -Rust's coherence rules. +Rust's [coherence](/docs/reference/glossary#coherence) rules. ## What each approach costs diff --git a/docs/comparisons/implicit-parameters.md b/docs/comparisons/implicit-parameters.md index 5adb1801..ebf3e333 100644 --- a/docs/comparisons/implicit-parameters.md +++ b/docs/comparisons/implicit-parameters.md @@ -27,7 +27,7 @@ provider choices determined by the context's type. | A type-class interface | A consumer trait within a **component** | | A type-class implementation | A **provider**: a named implementation | | Instance selection | **Wiring**, written in a `delegate_components!` table | -| A functional dependency (`m -> e`) or associated type family | An abstract type determined by the context | +| A functional dependency (`m -> e`) or associated type family | An [abstract type](/docs/reference/glossary#abstract-type) determined by the context | ## The idea, briefly @@ -114,7 +114,7 @@ dictionary. This explains how generic code can invoke an operation without namin Haskell and Scala differ in how they select those dictionaries. Haskell ordinarily uses a global instance for a class and its type arguments, with overlapping instances controlled by extensions. -Scala selects contextual values using scope and priority rules. Coherence concerns whether valid +Scala selects contextual values using scope and priority rules. [Coherence](/docs/reference/glossary#coherence) concerns whether valid resolutions agree in meaning; global instance uniqueness is one way to support it, rather than a rule shared unchanged by both languages. The [type classes](./type-classes.md) comparison develops these distinctions. @@ -181,7 +181,7 @@ pub trait HasErrorType { Both forms avoid making the error type an independent choice at every use. Haskell determines `e` from `m`; Rust refers to the associated `Error` of the context. A CGP consumer trait can require -`HasErrorType` as a supertrait, making that requirement available to generic callers through their +`HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait), making that requirement available to generic callers through their consumer-trait bound. The type dependency still exists; its relationship to the context makes it unnecessary to carry a separate error-type parameter. diff --git a/docs/comparisons/ml-modules.md b/docs/comparisons/ml-modules.md index 20332631..d4bfe492 100644 --- a/docs/comparisons/ml-modules.md +++ b/docs/comparisons/ml-modules.md @@ -7,7 +7,7 @@ description: 'CGP read against OCaml and Standard ML signatures, structures, fun # ML modules and modular implicits CGP lets Rust programs assemble named implementations through a context's wiring table. For an -ML programmer, its components, providers, and higher-order providers play roles similar to +ML programmer, its components, providers, and [higher-order providers](/docs/reference/glossary#higher-order-provider) play roles similar to signatures, structures, and functors. The correspondence explains how to compose implementations; ML's sealing and module type identities need a separate account. @@ -80,7 +80,7 @@ constraint such as `with type elt = O.t`. These equalities let independently des exchange values of the same type. [OCaml's functor guide](https://ocaml.org/docs/functors) develops the set example and dependency injection through modules. -Functor application also determines which abstract types are equal. OCaml's applicative functors +Functor application also determines which [abstract types](/docs/reference/glossary#abstract-type) are equal. OCaml's applicative functors can preserve result type equality across applications to the same module path. Generative functors can introduce fresh type identities; OCaml provides unit-parameter functors for this purpose. Standard ML uses generative semantics, but an explicitly shared or manifest type need not become @@ -171,7 +171,7 @@ provider trait, `AreaCalculator`. The provider reads `width` and `height` from t **[value context](/docs/reference/glossary#value-context)**: the value being measured also determines the implementation. The consumer/provider split is specific to CGP's use of Rust traits. Distinct provider types can -implement the same provider trait for a context while respecting Rust's coherence rules; wiring +implement the same provider trait for a context while respecting Rust's [coherence](/docs/reference/glossary#coherence) rules; wiring then selects one for consumer calls. ML already names different structures satisfying a signature. The [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) page explains this split in detail. @@ -282,7 +282,7 @@ functors adds another type-level concern. Tools such as Functoria organize that CGP moves many assembly choices into a context, at the cost of generated traits and indirect dependency resolution. A reader may need to follow the wiring to find an implementation, and a failed bound can produce a long diagnostic. [`cargo cgp check`](/docs/cargo-cgp/check) helps explain -the error classes it recognizes. Monomorphization can also increase compile time and generated code; +the error classes it recognizes. [Monomorphization](/docs/reference/glossary#monomorphization) can also increase compile time and generated code; static provider selection permits direct calls but does not guarantee that every call is inlined. CGP wiring supplies neither ML sealing nor runtime module selection. Rust's ordinary abstraction diff --git a/docs/comparisons/policy-based-design.md b/docs/comparisons/policy-based-design.md index 1a21320e..6596a4da 100644 --- a/docs/comparisons/policy-based-design.md +++ b/docs/comparisons/policy-based-design.md @@ -29,7 +29,7 @@ The vocabulary maps by role rather than by an exact translation of language feat | A policy class | A **provider** implementing a provider trait | | A policy interface, possibly expressed as a concept | A **component** declaring the interface as a trait | | The host object | The context value | -| A template taking policy types | A **higher-order provider** taking provider types | +| A template taking policy types | A **[higher-order provider](/docs/reference/glossary#higher-order-provider)** taking provider types | | Policy arguments selecting host behavior | Component choices in `delegate_components!`, or explicit provider parameters | | Access to the derived object through CRTP | Access to the context parameter, written as `self` inside `#[cgp_impl]` | | Checking constraints for a concrete instantiation | Checking trait bounds, with `check_components!` asserting a context's dependencies | @@ -375,7 +375,7 @@ particular composition mechanism within Rust. For a small Rust API, ordinary tra can be the simpler choice. Runtime selection needs an additional representation in either language. Virtual interfaces or -type erasure in C++, and trait objects in Rust, can support open sets of runtime implementations. +type erasure in C++, and [trait objects](/docs/reference/glossary#trait-object) in Rust, can support open sets of runtime implementations. Variants and enums can represent closed sets. The [dynamic dispatch](./dynamic-dispatch.md) page explains how static wiring and runtime polymorphism can coexist. diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index b5dc362e..4fd26d2a 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -25,7 +25,7 @@ and the reflected struct is a value the context operates on. | In a reflection system | In CGP | | --- | --- | | A type descriptor: `TypeInfo`, `Shape`, `std.builtin.Type`, `FieldId` | A `#[derive(HasFields)]` type's `Fields`, a type rather than a value | -| A field's name, as a runtime or `comptime` string | `Tag::VALUE`, a `&'static str` recovered from a type-level string | +| A field's name, as a runtime or `comptime` string | `Tag::VALUE`, a `&'static str` recovered from a [type-level string](/docs/reference/glossary#type-level-string) | | A field's type, as an opaque `TypeId` or `Shape` | The field's type, carried as a real type parameter | | `inline for` over `@typeInfo`, or a walk over a descriptor | A trait recursion over the `Cons`/`Nil` field list | | A registry mapping types to behavior | The **wiring table**, written with `delegate_components!` | @@ -253,7 +253,7 @@ through the *context's* wiring, so the same type is written differently under di contexts, the [per-context choice](/docs/concepts/coherence) that facet, serde, and the MVP do not have. -The costs are equally clear. Unlike facet, CGP does not solve the monomorphization problem: the +The costs are equally clear. Unlike facet, CGP does not solve the [monomorphization](/docs/reference/glossary#monomorphization) problem: the recursion instantiates per field list, so it produces specialized code per type as serde's output does. What it saves is the authoring duplication, and what it gains is configurability, not binary size. And unlike the Rust MVP, CGP requires the `#[derive(HasFields)]` opt-in and cannot see a foreign diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index c8fe2d15..11a72be3 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -28,7 +28,7 @@ cast is the type that carries the shape and the wiring, and each component targe | A row variable, "the rest of the fields" | The context type variable, constrained by trait bounds and never named as a row | | Row containment (`ρ₁ ≲ ρ₂`) | A `HasField` bound, usually written as an `#[implicit]` argument | | Record concatenation (`ρ₁ ⊙ ρ₂ ~ ρ₃`) | `CanBuildFrom` and the `ConcatProduct` type-level operation | -| A presence flag per label | The `IsPresent` and `IsNothing` markers on a partial record | +| A presence flag per label | The `IsPresent` and `IsNothing` markers on a [partial record](/docs/reference/glossary#partial-record) | | A row-typed sum | An enum's derived `Fields`, a `Sum!` over `Either` and `Void` | | Variant injection and branching | `CanUpcast`, and the extensible visitor's dispatch | @@ -104,7 +104,7 @@ let to_int = function (* inferred: [< `Number of int | `Off | `On ] -> int *) ``` -Extensible records and variants are the classic answer to Wadler's *expression problem*: adding both +[Extensible records](/docs/reference/glossary#extensible-record) and variants are the classic answer to Wadler's *expression problem*: adding both new cases to a datatype and new operations over it "without recompiling existing code, and while retaining static type safety" ([Wadler, 1998](https://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt)). Haskell's *Data types à la carte* is the constraint-based route for sums: a coproduct of signature @@ -131,7 +131,7 @@ constraints the trait solver resolves, in the Gaster and Jones style, carried by ### A struct is a closed row; `HasField` is row containment `#[derive(HasFields)]` gives a struct the type-level equivalent of a closed row, one -`Field` entry per field, tagged by a type-level string: +`Field` entry per field, tagged by a [type-level string](/docs/reference/glossary#type-level-string): ```rust #[derive(HasField, HasFields)] diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md index 9c9fa039..6b5f1718 100644 --- a/docs/comparisons/rust-language-proposals.md +++ b/docs/comparisons/rust-language-proposals.md @@ -9,7 +9,7 @@ description: 'CGP read against specialization, named impls, dictionary passing, CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a library on stable Rust in which a trait can have several named implementations and each context selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who has -followed Rust's own debate about relaxing coherence: *specialization*, the *dictionary-passing* +followed Rust's own debate about relaxing [coherence](/docs/reference/glossary#coherence): *specialization*, the *dictionary-passing* account of traits, *named or incoherent impls*, and *contexts and capabilities*. It shows which fragment of each proposal CGP provides today, how the correspondence runs construct by construct, and the two places where CGP cannot follow the proposals. It ends with what to expect that differs @@ -25,14 +25,14 @@ type you define to stand for an application. | --- | --- | | A named impl (`impl Name = Trait for T`) | A **provider**: a zero-sized type that implements a component's provider trait | | An `incoherent trait` bound passed at a call | A consumer-trait bound on the context, resolved by the context's **wiring** | -| An impl passed as a parameter (`impl TDrop: Drop` in Cairo) | A **higher-order provider**, bound with `#[use_provider]` | +| An impl passed as a parameter (`impl TDrop: Drop` in Cairo) | A **[higher-order provider](/docs/reference/glossary#higher-order-provider)**, bound with `#[use_provider]` | | A capability in a `with` clause | An `#[implicit]` argument read from a context field | | The `with` block that binds everything | The definition of a context type and its `delegate_components!` table | | The root dictionary of a dictionary-passing elaboration | The context itself | ## The idea, briefly -Rust's Reference gives the two rules every proposal here relaxes. The *orphan rule* says an +Rust's Reference gives the two rules every proposal here relaxes. The *[orphan rule](/docs/reference/glossary#orphan-rule)* says an `impl Trait for T0` is valid only if `Trait` is a local trait, or at least one of the types `T0..=Tn` is a local type and no uncovered type parameter appears before it. The *overlap rule* rejects two implementations that "can be instantiated with the same type" diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md index 3f00fc0c..fb820f81 100644 --- a/docs/comparisons/type-classes.md +++ b/docs/comparisons/type-classes.md @@ -10,7 +10,7 @@ CGP is a language extension for Rust, with pluggable trait implementations at co library on stable Rust in which a trait can have several named implementations and each context selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows type classes from Haskell, Agda, or Lean. Rust traits are Rust's type classes, so CGP already lives inside -a type-class system, and its one change is to the *coherence* rule: it makes instances first-class +a type-class system, and its one change is to the *[coherence](/docs/reference/glossary#coherence)* rule: it makes instances first-class values selected explicitly per context, which is the freedom overlapping and incoherent instances reach for without making it safe. The page covers the class and instance correspondence, the coherence trade, where coherent type classes remain the better tool, and what a type-class reader @@ -26,9 +26,9 @@ fields. In the dictionary-passing account it is the dictionary that carries ever | A class | A **component**: one trait with many possible implementations | | An instance, anonymous and canonical | A **provider**: a named, selectable implementation | | Instance resolution by the compiler | **Wiring**, written by hand in a `delegate_components!` table | -| A class constraint on a function | An **impl-side dependency**, declared with `#[uses]` | +| A class constraint on a function | An **[impl-side dependency](/docs/reference/glossary#impl-side-dependency)**, declared with `#[uses]` | | The dictionary passed as a hidden argument | The context | -| A class's associated type | An abstract type, chosen by the context | +| A class's associated type | An [abstract type](/docs/reference/glossary#abstract-type), chosen by the context | ## The idea, briefly @@ -66,7 +66,7 @@ The canonical benefit is a `Set` of an ordered element type: with one `Ord` for inserted under one ordering and read under another can never disagree. Rust makes the same choice and *enforces* it where Haskell advises. Rust traits are type classes with -a hard orphan rule, so an impl is allowed only when the crate owns the trait or the type +a hard [orphan rule](/docs/reference/glossary#orphan-rule), so an impl is allowed only when the crate owns the trait or the type ([RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). That strictness is the rule CGP is built to work within, and the [Rust proposals](./rust-language-proposals.md) page covers what Rust itself has considered doing about it. diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index 9df358b7..d519616d 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -73,7 +73,7 @@ trait implementations. The error location may also be far from the wiring, in an ## Asking the question at a line you chose A check trait forces the compiler to verify a bound where you write its implementation. The basic -technique uses an ordinary Rust supertrait and an empty implementation: +technique uses an ordinary Rust [supertrait](/docs/reference/glossary#supertrait) and an empty implementation: ```rust trait CanUseApp: CanSendEmail {} diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index c84832c2..9cc35b95 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -7,7 +7,7 @@ sidebar_position: 1 Rust's coherence rules keep trait implementation selection unambiguous. CGP works within those rules by giving alternative implementations separate provider types, then letting each context select one. -This page explains what coherence provides, why overlapping blanket implementations are rejected, +This page explains what coherence provides, why overlapping [blanket implementations](/docs/reference/glossary#blanket-implementation) are rejected, and how the provider arrangement allows reuse without ambiguous calls. ## The trait system is already a dependency-injection mechanism @@ -177,7 +177,7 @@ explains when to use it and how it differs from the value-type wiring shown here ## What it costs -A component introduces more declarations than a plain trait: a provider trait, a component marker, +A component introduces more declarations than a plain trait: a provider trait, a [component marker](/docs/reference/glossary#component-marker), and wiring for the types that use it. For a trait with one implementation, a plain trait or [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) may provide the required reuse without wiring. diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index 7fad0c16..53cd2e70 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -51,7 +51,7 @@ impl CanSendEmail for TestApp { an application and carrying the data its implementation needs. The SMTP body is omitted here; `TestApp` shows the recording behavior in full. -Overlapping blanket implementations prevent those behaviors from being offered as interchangeable +Overlapping [blanket implementations](/docs/reference/glossary#blanket-implementation) prevent those behaviors from being offered as interchangeable trait implementations. If the SMTP implementation applies to every type with `HasSmtpConfig`, and the recording implementation applies to every type with `HasRecordedEmails`, they conflict: @@ -171,7 +171,7 @@ the application value on which the caller invoked the method. [`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for) carries the provider's dependency bounds for checking. The provider macros generate an implementation with those bounds, and the -provider trait also requires it as a supertrait. Explicit component checks use this path to expose +provider trait also requires it as a [supertrait](/docs/reference/glossary#supertrait). Explicit component checks use this path to expose missing requirements that a consumer-trait error can hide. The listings simplify generated names for readability. Actual expansions use `__Context__` and diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index 8b8134a6..3451878f 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -23,7 +23,7 @@ payload or to produce the field's value. Matching and building use these pieces differently: - **Matching:** Try variants until the current one is found, then run its handler. -- **Building:** Run handlers in sequence, adding their outputs to a partial record until it can be finalized. +- **Building:** Run handlers in sequence, adding their outputs to a [partial record](/docs/reference/glossary#partial-record) until it can be finalized. Dispatchers implement the same computation interfaces as other [handler providers](./handlers.md). They can be selected through context wiring, composed with other @@ -104,7 +104,7 @@ pub trait CanDescribe { ``` If `Circle` and `Rectangle` implement `CanDescribe`, a `Shape` enum with the required extensible-data -support gains the trait through a generated blanket implementation. A call to `shape.describe()` +support gains the trait through a generated [blanket implementation](/docs/reference/glossary#blanket-implementation). A call to `shape.describe()` forwards to the current payload's implementation without application wiring or a handwritten `match`. Deriving `CgpData` on `Shape` supplies that data support. diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index 5b434efe..cb68d520 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -7,7 +7,7 @@ sidebar_position: 3 An **impl-side dependency** is a requirement stated on an implementation without being part of its trait interface. Callers can require the trait they use while the compiler checks the selected -implementation's dependencies. This page starts with ordinary Rust blanket implementations, then +implementation's dependencies. This page starts with ordinary Rust [blanket implementations](/docs/reference/glossary#blanket-implementation), then shows how CGP providers require traits, field values, and context-selected types. ## What a `where` clause costs the callers above it @@ -65,7 +65,7 @@ where } ``` -`CanGreet` promises a greeting method without requiring `HasName` as a supertrait. The blanket +`CanGreet` promises a greeting method without requiring `HasName` as a [supertrait](/docs/reference/glossary#supertrait). The blanket implementation supplies that method for every context implementing `HasName`. A generic caller can require only the greeting trait: diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index e4e8bea4..8e47c40c 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -8,7 +8,7 @@ sidebar_position: 4 Implicit arguments let a provider declare the context values it needs as function parameters. CGP reads those values from the context, so callers pass only the method's explicit arguments. This page explains the field access behind that shorthand, how argument types control borrowing -and cloning, and when a getter trait is a better fit. +and cloning, and when a [getter trait](/docs/reference/glossary#getter-trait) is a better fit. ## Reading a field explicitly @@ -130,7 +130,7 @@ This fragment assumes `RequestAuthenticator` and `HasAuthHeader` are defined els `HasAuthHeader` describes access on the request, while `self` is the [application context](/docs/reference/glossary#application-context). An implicit argument on `authenticate` would read the application instead. -A named getter also lets other code require the accessor through a trait bound or supertrait. +A named getter also lets other code require the accessor through a trait bound or [supertrait](/docs/reference/glossary#supertrait). A getter with an associated type can keep the field's type abstract for callers. These are reasons to use [`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter); sharing a context field between several providers alone is not. Each provider can declare the same implicit argument. diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index 509fc5b8..efdf16fc 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -24,15 +24,15 @@ The tiers differ in where a program can select an implementation: | **2** | One implementation per target type | A plain Rust trait | Selection follows the trait and target type | | **3** | One provider per wired type | A CGP component and wiring | Each wired type still has one choice for that component | | **4** | One provider per target type in each context | A parameter-targeted component and `open` | The interface must separate context from target | -| **5** | An inner provider chosen by an enclosing provider | A higher-order provider | The enclosing provider depends on the inner provider interface | +| **5** | An inner provider chosen by an enclosing provider | A [higher-order provider](/docs/reference/glossary#higher-order-provider) | The enclosing provider depends on the inner provider interface | -All tiers obey Rust's coherence rules. CGP permits reusable alternatives by placing their +All tiers obey Rust's [coherence](/docs/reference/glossary#coherence) rules. CGP permits reusable alternatives by placing their implementations on distinct provider types, then using wiring to select one unambiguously. Tier 5 adds a local composition choice rather than relaxing another coherence rule. ## Tier 1: one implementation for matching types -A blanket implementation shares one body across every type satisfying its bounds. Here, all +A [blanket implementation](/docs/reference/glossary#blanket-implementation) shares one body across every type satisfying its bounds. Here, all byte-like values encode by copying their bytes: ```rust @@ -83,7 +83,7 @@ that trait is used for that type. Blanket implementations remain possible where overlap other impls; coherence prevents ambiguous combinations. This tier fits behavior that varies by type but does not need an independent choice per application. -Rust's orphan rules also determine which crate may supply an implementation. +Rust's [orphan rules](/docs/reference/glossary#orphan-rule) also determine which crate may supply an implementation. ## Tier 3: reusable providers, one selected per wired type @@ -286,7 +286,7 @@ alongside CGP: | **A local macro** | The generated pattern is narrow and specific to the crate. | Repeated helper traits and marker types amount to a reusable component system. | Runtime choices can live inside a CGP context. For example, a provider can call through a trait -object stored in a field. Static wiring selects that provider; the trait object still performs +object stored in a field. Static wiring selects that provider; the [trait object](/docs/reference/glossary#trait-object) still performs its own runtime dispatch. ## Where provider wiring does not help @@ -348,7 +348,7 @@ checked near the wiring. `cargo cgp check` leads with the root cause for the cla and the tool is a v0.1.0-alpha that does not yet reshape every class. The [cargo-cgp documentation](/docs/cargo-cgp/) explains the checking workflow. -Macros, trait resolution, and monomorphization add compile-time work. The effect depends on the +Macros, trait resolution, and [monomorphization](/docs/reference/glossary#monomorphization) add compile-time work. The effect depends on the program and should be measured for the codebase being evaluated. Static dispatch removes runtime provider lookup, but that does not mean every added compilation cost replaces a runtime cost. diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index 965a8b29..066cbab8 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -177,7 +177,7 @@ assertions for the components a concrete context needs. Small tables often remain clearer when written directly. Namespaces become useful when sharing a configuration or grouping routes reduces enough repetition to justify the inheritance and path -structure. An aggregate provider offers a simpler way to share a named group of implementations. +structure. An [aggregate provider](/docs/reference/glossary#aggregate-provider) offers a simpler way to share a named group of implementations. ## Where to go next diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index f188ef94..17c6ba12 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -123,7 +123,7 @@ still needs to satisfy the bound independently. The companion trait adds an interface to maintain. Methods that need the stronger guarantee need corresponding signatures and forwarding bodies. Other methods can remain available through the -original supertrait without being duplicated. +original [supertrait](/docs/reference/glossary#supertrait) without being duplicated. A companion trait is useful when the base interface must support both sendable and non-sendable futures. If every implementation must return a `Send` future, an explicit `impl Future + Send` diff --git a/docs/overview.md b/docs/overview.md index 72cf70c1..613c7b8d 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -24,7 +24,7 @@ callers. CGP separates the trait callers use, the consumer trait, from the provider trait that named implementations implement. Each provider uses its own marker type, so the implementations remain -distinct under Rust's coherence rules. Read +distinct under Rust's [coherence](/docs/reference/glossary#coherence) rules. Read [consumer and provider traits](/docs/concepts/consumer-and-provider-traits) for the mechanism and [coherence](/docs/concepts/coherence) for the rules it works within. @@ -62,7 +62,7 @@ service on its target platform. CGP's macros generate ordinary Rust traits and implementations that compile on stable Rust. You can implement a consumer trait directly, introduce providers where you need them, and keep the rest of -your project unchanged. Contexts can contain ordinary generic types, enums, and trait objects. +your project unchanged. Contexts can contain ordinary generic types, enums, and [trait objects](/docs/reference/glossary#trait-object). The additional structure has a cost: you need to learn the provider model and maintain the wiring. For an interface with a single implementation, an ordinary trait often supplies all the abstraction @@ -71,7 +71,7 @@ amount of separation your code needs. ### Abstract Types -An abstract type lets each context choose a concrete type, such as its error type, without passing +An [abstract type](/docs/reference/glossary#abstract-type) lets each context choose a concrete type, such as its error type, without passing that choice as a separate generic parameter through every layer. Code names the associated type where it needs it. A caller that only invokes a trait's method can depend on that trait without listing the types used inside its implementation. @@ -130,7 +130,7 @@ choices but does not make runtime APIs interchangeable by itself. ### Overlapping Implementations -Rust rejects blanket implementations that could apply to the same type, even when different +Rust rejects [blanket implementations](/docs/reference/glossary#blanket-implementation) that could apply to the same type, even when different applications want different choices. CGP gives each implementation a provider name and makes the choice explicit in the context's wiring. A crate can also implement a provider trait for its own provider type even when the trait and the data being handled come from other crates. diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index d4541ba5..c12b7261 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -177,7 +177,7 @@ the provider is written.** The alternatives differ in where the entry lives. not. - **Do not use a namespace at all** until the top-level wiring is long enough to be a problem. -**Rust's orphan rule, not a CGP choice, decides where you may write the attribute.** The emitted impl is +**Rust's [orphan rule](/docs/reference/glossary#orphan-rule), not a CGP choice, decides where you may write the attribute.** The emitted impl is `impl Namespace<..> for Key`, and Rust accepts it when the crate owns the namespace trait, or when a local type appears in the impl header ahead of the table parameter. That local type may be the key itself, or a component named inside the namespace path, so a crate that owns `ShowImplComponent` may diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 8fa4c96b..74c3abf4 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -213,7 +213,7 @@ Rust reads the key as the bare `Shape`. That is why the table's entries are writ the table is `__Components__` and the looked-up entry `__Delegate__`, alongside the provider trait's own `__Context__`. -**A component's supertraits carry into the dispatcher.** The provider trait records each supertrait as a +**A component's [supertraits](/docs/reference/glossary#supertrait) carry into the dispatcher.** The provider trait records each supertrait as a `Context:` predicate, and because the dispatcher reuses the provider trait's generics that predicate appears here too, so a component declaring an error type through [`#[use_type]`](use_type.md) yields a dispatcher whose `where` clause also requires @@ -261,7 +261,7 @@ The usual cause is putting the attribute on a component that has no type paramet there is nothing for it to do. **One component gets one dispatch mechanism.** Wiring the same component both with `open` and with a -`UseDelegate` table is a coherence conflict, because each produces its own table entry for that key. A +`UseDelegate` table is a [coherence](/docs/reference/glossary#coherence) conflict, because each produces its own table entry for that key. A wiring entry expands to two impls, and both of them collide, so the compiler reports the conflict twice, once for `IsProviderFor` and once for `DelegateComponent`. The `DelegateComponent` report is the readable one, because its trait argument names the component at issue: diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index cb540471..07ffd9e9 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -5,7 +5,7 @@ sidebar_position: 5 # `#[extend]` -Add a trait as a supertrait of a generated trait, so callers can rely on it too. +Add a trait as a [supertrait](/docs/reference/glossary#supertrait) of a generated trait, so callers can rely on it too. ## Overview diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index c7455f43..0d45450f 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -33,7 +33,7 @@ against the trait instead of deferring it. `#[extend_where]` is the `where`-clause sibling of [`#[extend]`](extend.md). Both put a requirement into the trait's public interface. They differ in position, and in what the reader gets. `#[extend]` adds a -**supertrait**, a bound on `Self`, which callers do receive, because Rust elaborates a supertrait bound +**[supertrait](/docs/reference/glossary#supertrait)**, a bound on `Self`, which callers do receive, because Rust elaborates a supertrait bound automatically. `#[extend_where]` adds a **predicate**, which can bound anything, most usefully one of the trait's own generic parameters, which a supertrait cannot reach. @@ -126,7 +126,7 @@ Other constructs carry the requirements that belong elsewhere. elaboration. - **A private requirement**, the overwhelmingly common case, belongs in the function's own `where` clause, or in [`#[uses]`](uses.md) when it is a trait on the context. -- **An abstract type pinned to a concrete one** is [`#[use_type]`](use_type.md)'s equality form, which adds +- **An [abstract type](/docs/reference/glossary#abstract-type) pinned to a concrete one** is [`#[use_type]`](use_type.md)'s equality form, which adds the bound and lets the signature name the type as a bare word. Do not use it to spare callers a bound, because it has the opposite effect. If holding the trait diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 1a9eba24..972f5b07 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -37,7 +37,7 @@ wiring or any declaration beyond the field itself. The cost is that the type is hidden rather than named. It exists only where a value of it flows through an [`#[implicit]`](./implicit.md) argument, so nothing else can refer to it: not this trait's own signature, not another trait, and not a second provider. When the type must be -named, promote it to an abstract type with [`#[cgp_type]`](../macros/cgp_type.md) and import it with +named, promote it to an [abstract type](/docs/reference/glossary#abstract-type) with [`#[cgp_type]`](../macros/cgp_type.md) and import it with [`#[use_type]`](./use_type.md). [When to use it](#when-to-use-it) says where that boundary lies. ## Usage @@ -103,7 +103,7 @@ pub fn greet_both(person: &Person, robot: &Robot) { } ``` -`Person` and `Robot` both implement `Greet` through the one blanket implementation, without any +`Person` and `Robot` both implement `Greet` through the one [blanket implementation](/docs/reference/glossary#blanket-implementation), without any wiring. For `Person` the compiler resolves `Name` to `String`, and for `Robot` to `u32`. Neither type appears anywhere except in the field. diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 86681376..c86f2771 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -86,7 +86,7 @@ with one lifetime argument and one type argument. Anything else spelled `MRef` f and the macro clones it. This is the one place where a small change to the type changes the read without a warning. -The same rules govern the getter traits, so learning them once covers everywhere CGP reads a field. +The same rules govern the [getter traits](/docs/reference/glossary#getter-trait), so learning them once covers everywhere CGP reads a field. ### Mutable arguments @@ -169,7 +169,7 @@ A **getter trait** covers the cases an implicit argument cannot reach. The value does not live on `self` at all. - **The accessor must be a named trait.** When other code depends on "this context can tell you its name" rather than on a field, that dependency needs a trait to point at, importable with - [`#[uses]`](uses.md) or usable as a supertrait. + [`#[uses]`](uses.md) or usable as a [supertrait](/docs/reference/glossary#supertrait). - **The getter carries a type inferred from the field.** A getter may declare an associated type and return it, which keeps the type abstract for callers in a way a concrete argument cannot. @@ -216,7 +216,7 @@ where ``` The macro inserts the bindings in argument order, ahead of every original statement, so the names are in -scope for the whole body. [`Symbol!("width")`](../macros/symbol.md) is a type-level string standing for the +scope for the whole body. [`Symbol!("width")`](../macros/symbol.md) is a [type-level string](/docs/reference/glossary#type-level-string) standing for the field name. The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and `cargo cgp expand` resugars it back. The context parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours. diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index a7c8e4eb..f63de80d 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -29,13 +29,13 @@ dependencies belong on the implementation, where callers never see them. `#[exte rely on it. [`#[uses]`](./uses.md) imports a consumer trait, or an ordinary Rust trait, that the context must -satisfy. This is the common case. [`#[use_type]`](./use_type.md) imports an abstract type that another +satisfy. This is the common case. [`#[use_type]`](./use_type.md) imports an [abstract type](/docs/reference/glossary#abstract-type) that another component supplies, such as an error type, and lets the signature name it as a bare word instead of a qualified path. [`#[use_provider]`](./use_provider.md) imports a provider trait that a named inner -provider must satisfy, which is the dependency a higher-order provider declares. +provider must satisfy, which is the dependency a [higher-order provider](/docs/reference/glossary#higher-order-provider) declares. [`#[extend]`](./extend.md) and [`#[extend_where]`](./extend_where.md) put the requirement on the generated -trait rather than on the implementation, so every caller inherits it. `#[extend]` adds a supertrait, and +trait rather than on the implementation, so every caller inherits it. `#[extend]` adds a [supertrait](/docs/reference/glossary#supertrait), and `#[extend_where]` adds a `where` predicate that a supertrait cannot express. ## Naming a type the body needs diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index 84659915..b400fb3a 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -54,13 +54,13 @@ of the macros built on it, [`#[cgp_type]`](../macros/cgp_type.md) and | `in` | Required keyword. | | `NamespacePath` | The namespace to register into: `DefaultNamespace`, or one defined with [`cgp_namespace!`](../macros/cgp_namespace.md). It may be a qualified path and may carry generic arguments. | -**The path is a prefix, and the macro appends the component marker for you.** +**The path is a prefix, and the macro appends the [component marker](/docs/reference/glossary#component-marker) for you.** `#[prefix(@app in DefaultNamespace)]` on `CanGreet` registers `GreeterComponent` at `@app.GreeterComponent`. Writing the marker yourself doubles it. See [Common Mistakes](#common-mistakes). Segments follow [`Path!`](../macros/path.md)'s convention. A lowercase identifier that is not a -primitive type name becomes a type-level string, so `@app` and `@cgp.core.error` are strings. Any +primitive type name becomes a [type-level string](/docs/reference/glossary#type-level-string), so `@app` and `@cgp.core.error` are strings. Any other segment names a type, so `@MyApp.MyBarComponent` is two types. Case decides the meaning. A segment cannot declare generic parameters, and the parser accepts neither of the `[…]` and `{…}` grouping forms a [`delegate_components!`](../macros/delegate_components.md) key allows. One @@ -83,7 +83,7 @@ appends them to the path, so a context joining the namespace wires a `CanShow do not appear in the path. **Any crate may register its own components into any namespace.** The emitted impl is for the -component's marker, a type the component's crate owns, so Rust's orphan rule is satisfied even when +component's marker, a type the component's crate owns, so Rust's [orphan rule](/docs/reference/glossary#orphan-rule) is satisfied even when the namespace comes from another crate. That is why an application can register into `DefaultNamespace`. It is also the difference from [`#[default_impl]`](./default_impl.md), whose key on a prefixed component is a foreign path. @@ -93,7 +93,7 @@ on a prefixed component is a foreign path. A prefix is part of the component's public surface, and costly to change once wiring depends on it. So choose it with every implementation the component might have in mind, not only the one you are writing now. Give components separate sub-paths whenever they are likely to need separate providers, -even when the current wiring happens to treat them alike. Abstract types belong under a `types` sub-path +even when the current wiring happens to treat them alike. [Abstract types](/docs/reference/glossary#abstract-type) belong under a `types` sub-path of their layer, such as `@app.auth.types`, because a production context typically points the logic under `@app.auth` at a database while leaving the types on the same concrete choices. diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 1d7e8976..faf19d43 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -34,7 +34,7 @@ let base_area = InnerCalculator::area(self); `#[use_provider]` writes the bound behind that call. It does not rewrite the call. Writing `self.area()` instead would route through whatever provider the context has itself wired for `AreaCalculator`, which is -a different choice and usually not what a higher-order provider wants. +a different choice and usually not what a [higher-order provider](/docs/reference/glossary#higher-order-provider) wants. ## Usage diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 9d639c61..aa5f069d 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -29,7 +29,7 @@ The method never names any of those. The context names one, in its wiring. `#[use_type]` reads like a `use` statement for a type, and [Under the hood](#under-the-hood) shows how the bare name resolves. It also has advanced forms that a bare identifier could not express, covered [below](#importing-from-another-type): pinning the type to a concrete one, importing it from a -parameter rather than the context, and tying two abstract types together. +parameter rather than the context, and tying two [abstract types](/docs/reference/glossary#abstract-type) together. ## Usage @@ -144,7 +144,7 @@ impl AreaCalculator { } ``` -The component gains `HasScalarType` as a supertrait, and the provider gains it as a bound. Every +The component gains `HasScalarType` as a [supertrait](/docs/reference/glossary#supertrait), and the provider gains it as a bound. Every `Scalar` in both becomes the same qualified projection, so the fields the provider reads and the value it returns are guaranteed to agree on whatever scalar the context chose. diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index ea44e679..1923c1c2 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -61,11 +61,11 @@ entry may nonetheless be any bound a `where` clause accepts: an associated-type `HasErrorType`, a higher-ranked bound, or a lifetime bound. Each lands on the `where` clause verbatim. -Use that generality sparingly, and prefer a more specific tool where one exists. To pin an abstract type +Use that generality sparingly, and prefer a more specific tool where one exists. To pin an [abstract type](/docs/reference/glossary#abstract-type) to a concrete one, [`#[use_type]`](use_type.md)'s equality form `#[use_type(HasErrorType.{Error = anyhow::Error})]` adds the same bound *and* lets the signature name the type as a bare `Error`. To put a bound on the generated trait rather than only on its implementation, use -[`#[extend]`](extend.md) for a supertrait or [`#[extend_where]`](extend_where.md) for a predicate. +[`#[extend]`](extend.md) for a [supertrait](/docs/reference/glossary#supertrait) or [`#[extend_where]`](extend_where.md) for a predicate. ## Examples @@ -123,7 +123,7 @@ The choice between `#[uses]` and its neighbours turns on *what* the implementati reads a field directly rather than routing through a trait. - **A type from the context** is imported with [`#[use_type]`](use_type.md), which adds the bound and additionally lets the signature write the type as a bare name instead of a qualified path. -- **An inner provider** in a higher-order provider needs [`#[use_provider]`](use_provider.md), because a +- **An inner provider** in a [higher-order provider](/docs/reference/glossary#higher-order-provider) needs [`#[use_provider]`](use_provider.md), because a provider trait carries a context argument that `#[uses]` would not fill in. - **A requirement callers should see** belongs on the trait rather than on the implementation: [`#[extend]`](extend.md) makes it a supertrait, and [`#[extend_where]`](extend_where.md) a predicate. diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md index 369f81b4..7b552ca5 100644 --- a/docs/reference/components/can_raise_error.md +++ b/docs/reference/components/can_raise_error.md @@ -41,7 +41,7 @@ Its attributes: - [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `ErrorRaiser` that implementations target and the wiring key `ErrorRaiserComponent`, while `CanRaiseError` stays the consumer trait callers use. - [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. - [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `SourceError` type, so a context can route each `SourceError` to its own provider; the `open` statement is the modern sugar for the same dispatch. -- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. ## Usage diff --git a/docs/reference/components/can_wrap_error.md b/docs/reference/components/can_wrap_error.md index 827da45a..63a3ea91 100644 --- a/docs/reference/components/can_wrap_error.md +++ b/docs/reference/components/can_wrap_error.md @@ -40,7 +40,7 @@ Its attributes: - [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `ErrorWrapper` that implementations target and the wiring key `ErrorWrapperComponent`, while `CanWrapError` stays the consumer trait callers use. - [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. - [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Detail` type, so a context can route each `Detail` to its own provider; the `open` statement is the modern sugar for the same dispatch. -- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. ## Usage diff --git a/docs/reference/components/handler/async_computer.md b/docs/reference/components/handler/async_computer.md index 5034d489..e3eeca1f 100644 --- a/docs/reference/components/handler/async_computer.md +++ b/docs/reference/components/handler/async_computer.md @@ -18,7 +18,7 @@ fields), and returns the `Output` directly rather than a `Result`. It sits between [`Computer`](./computer.md), which drops the asynchrony, and [`Handler`](./handler.md), which adds a failure path on top of the asynchrony. Like the pure computer, it never names an error type, -so it does not supertrait [`HasErrorType`](../has_error_type.md). See the +so it does not [supertrait](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md). See the [handler family overview](./index.md) for how the members relate and promote. ## Definition diff --git a/docs/reference/components/handler/async_computer_ref.md b/docs/reference/components/handler/async_computer_ref.md index 7419a3c9..5a5bcc3b 100644 --- a/docs/reference/components/handler/async_computer_ref.md +++ b/docs/reference/components/handler/async_computer_ref.md @@ -18,7 +18,7 @@ with no failure path. It runs against a **context**, the type a method runs on t values an implementation needs as its own fields. It is the async by-reference corner of the infallible computers. Like the other computers it never names -an error type, so it does not supertrait [`HasErrorType`](../has_error_type.md). See the +an error type, so it does not [supertrait](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md). See the [handler family overview](./index.md) for how the members relate and promote. ## Definition diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md index 04b0ee0d..85e0cc45 100644 --- a/docs/reference/components/handler/computer.md +++ b/docs/reference/components/handler/computer.md @@ -62,7 +62,7 @@ The component dispatches on both the `Code` tag and the `Input` type. It has thr differing from `Computer` by one axis and documented on its own page: [`ComputerRef`](./computer_ref.md) borrows the input, [`AsyncComputer`](./async_computer.md) is the async counterpart, and [`AsyncComputerRef`](./async_computer_ref.md) combines the two. None of the four -supertrait [`HasErrorType`](../has_error_type.md), because none of them can fail. +[supertrait](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md), because none of them can fail. ## Examples diff --git a/docs/reference/components/handler/computer_ref.md b/docs/reference/components/handler/computer_ref.md index 76e4d4f8..2c398e09 100644 --- a/docs/reference/components/handler/computer_ref.md +++ b/docs/reference/components/handler/computer_ref.md @@ -17,7 +17,7 @@ a method runs on, which supplies the values an implementation needs as its own f returns the `Output` directly with no failure path. It is the owned-versus-borrowed variant of the pure computer, differing on the input axis alone. Like -`Computer` it never names an error type, so it does not supertrait +`Computer` it never names an error type, so it does not [supertrait](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md). See the [handler family overview](./index.md) for how the members relate. diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md index 9ab7edbc..081fbd7f 100644 --- a/docs/reference/components/handler/handler.md +++ b/docs/reference/components/handler/handler.md @@ -52,7 +52,7 @@ Its attributes: - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Handler` that implementations target and the wiring key `HandlerComponent`, while `CanHandle` stays the consumer trait callers use. - [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. - [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. -- [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. +- [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. ## Usage diff --git a/docs/reference/components/handler/handler_ref.md b/docs/reference/components/handler/handler_ref.md index 6e84740c..0f4e5c72 100644 --- a/docs/reference/components/handler/handler_ref.md +++ b/docs/reference/components/handler/handler_ref.md @@ -17,7 +17,7 @@ on, which supplies the values an implementation needs as its own fields. `Handle owned-versus-borrowed variant of the family's most general member, differing on the input axis alone, for an async-and-fallible computation that reads rather than consumes its argument. -Because it can fail, it supertraits [`HasErrorType`](../has_error_type.md), which supplies the +Because it can fail, it [supertraits](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md), which supplies the `Self::Error` it names in its `Result`. See the [handler family overview](./index.md) for how the members relate and promote. diff --git a/docs/reference/components/handler/index.md b/docs/reference/components/handler/index.md index c034bed6..f9db374d 100644 --- a/docs/reference/components/handler/index.md +++ b/docs/reference/components/handler/index.md @@ -43,7 +43,7 @@ which turn a plain function into a provider and wire the promotion table so one whole family, and they are composed and routed with the [handler combinators](../../providers/handler/index.md), the [dispatch combinators](../../providers/dispatch/index.md), and the -[monad providers](../../providers/monad/index.md). A fallible member supertraits +[monad providers](../../providers/monad/index.md). A fallible member [supertraits](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md), and an effectful one reaches the runtime through [`HasRuntime`](../has_runtime.md). diff --git a/docs/reference/components/handler/try_computer.md b/docs/reference/components/handler/try_computer.md index a727dfdc..43b0ddbf 100644 --- a/docs/reference/components/handler/try_computer.md +++ b/docs/reference/components/handler/try_computer.md @@ -20,7 +20,7 @@ This places `TryComputer` one step up from `Computer` on the fallibility axis of 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 -`Self::Error`, and the concrete type is decided at wiring time. This is why the component supertraits +`Self::Error`, and the concrete type is decided at wiring time. This is why the component [supertraits](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md): the supertrait supplies the `Self::Error` it names in its `Result`, and it ties every fallible component in a context to the same error so their results compose. diff --git a/docs/reference/components/handler/try_computer_ref.md b/docs/reference/components/handler/try_computer_ref.md index ad71a1c3..d60c3455 100644 --- a/docs/reference/components/handler/try_computer_ref.md +++ b/docs/reference/components/handler/try_computer_ref.md @@ -17,7 +17,7 @@ type a method runs on, which supplies the values an implementation needs as its `TryComputerRef` is the owned-versus-borrowed variant of the fallible synchronous computer, differing on the input axis alone. -Because it can fail, it supertraits [`HasErrorType`](../has_error_type.md), which supplies the +Because it can fail, it [supertraits](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md), which supplies the `Self::Error` it names in its `Result` and ties it to the same error every other fallible component in the context uses. See the [handler family overview](./index.md) for how the members relate and promote. diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index f5a5ccb9..439291f0 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -18,7 +18,7 @@ backend the context plugs in. Putting the error type on one component also keeps errors composable. If each fallible trait declared its own associated `Error`, a context bounded by several of them would face several unrelated `Self::Error` -types with no way to unify them. Because the fallible components all supertrait `HasErrorType`, every one +types with no way to unify them. Because the fallible components all [supertrait](/docs/reference/glossary#supertrait) `HasErrorType`, every one of them names the *same* `Self::Error`, so their results combine. This single shared abstract error is the anchor that [`CanRaiseError`](./can_raise_error.md) and [`CanWrapError`](./can_wrap_error.md) build on. @@ -39,7 +39,7 @@ pub type ErrorOf = ::Error; Its attributes: -- [`#[cgp_type]`](../macros/cgp_type.md) — makes this an abstract-type component rather than a plain trait: it generates the provider trait, the component marker, and a [`UseType`](../providers/use_type.md) impl, so a context binds the concrete type by wiring. +- [`#[cgp_type]`](../macros/cgp_type.md) — makes this an abstract-type component rather than a plain trait: it generates the provider trait, the [component marker](/docs/reference/glossary#component-marker), and a [`UseType`](../providers/use_type.md) impl, so a context binds the concrete type by wiring. - [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. ## Usage diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index 2779eb75..6c426706 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -20,7 +20,7 @@ and `HasRuntime` is the getter that borrows it. `HasRuntime` answers *how to obtain the runtime value*; its companion [`HasRuntimeType`](./has_runtime_type.md) answers *what the runtime type is*. The two are split because the questions are independent: some code names only the runtime type and never touches a value, and -needs `HasRuntimeType` alone, while code that performs effects needs `HasRuntime`, which supertraits +needs `HasRuntimeType` alone, while code that performs effects needs `HasRuntime`, which [supertraits](/docs/reference/glossary#supertrait) `HasRuntimeType` so the value's type is always in scope. `HasRuntime` is the seam where context-generic logic meets the concrete async machinery, which is why it underpins the [`CanRun`](./runner.md) family of task runners. @@ -45,7 +45,7 @@ Its attributes: ## Usage `HasRuntime` is imported from `cgp::extra::runtime`. It is a getter component: its method borrows the -runtime value out of a borrow of the context, returning `&Runtime`, where `Runtime` is the abstract type +runtime value out of a borrow of the context, returning `&Runtime`, where `Runtime` is the [abstract type](/docs/reference/glossary#abstract-type) supplied by [`HasRuntimeType`](./has_runtime_type.md): ```rust diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md index f3dadcdd..38488eb4 100644 --- a/docs/reference/components/has_runtime_type.md +++ b/docs/reference/components/has_runtime_type.md @@ -38,7 +38,7 @@ pub type RuntimeOf = ::Runtime; Its attributes: -- [`#[cgp_type]`](../macros/cgp_type.md) — makes this an abstract-type component rather than a plain trait: it generates the provider trait, the component marker, and a [`UseType`](../providers/use_type.md) impl, so a context binds the concrete type by wiring. +- [`#[cgp_type]`](../macros/cgp_type.md) — makes this an abstract-type component rather than a plain trait: it generates the provider trait, the [component marker](/docs/reference/glossary#component-marker), and a [`UseType`](../providers/use_type.md) impl, so a context binds the concrete type by wiring. ## Usage @@ -99,7 +99,7 @@ it uses. It is also the type half a context must wire before it can satisfy [`HasRuntime`](./has_runtime.md), because the getter borrows a value of this type. Reach for [`HasRuntime`](./has_runtime.md) instead when a provider actually performs an effect and needs -the runtime *value*, since `HasRuntime` supertraits this one and gives access to both. For an abstract +the runtime *value*, since `HasRuntime` [supertraits](/docs/reference/glossary#supertrait) this one and gives access to both. For an abstract type that is not the runtime, define your own component with [`#[cgp_type]`](../macros/cgp_type.md) rather than reusing this one. diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index 23088211..68f55bf8 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -10,7 +10,7 @@ CGP's single built-in abstract-type component: a tag-indexed type a context reso ## Overview `HasType` lets generic code refer to a type that is chosen per context without committing to a -concrete one. An abstract type in CGP is a +concrete one. An [abstract type](/docs/reference/glossary#abstract-type) in CGP is a [trait](https://doc.rust-lang.org/book/ch10-02-traits.html) with a single [associated type](https://doc.rust-lang.org/reference/items/associated-items.html), and `HasType` is the foundational, tag-indexed instance of that pattern. A **context**, the type that implements the trait, can carry many distinct abstract types, one per `Tag`, and resolve each to a concrete type diff --git a/docs/reference/components/index.md b/docs/reference/components/index.md index 76a4bf22..6b0e9863 100644 --- a/docs/reference/components/index.md +++ b/docs/reference/components/index.md @@ -35,7 +35,7 @@ crate rather than by hand. ## Let each context choose a type [`HasType`](./has_type.md) is CGP's single built-in abstract-type component: a tag-indexed trait whose -associated type a context resolves to a concrete one through wiring. Every named abstract type a program +associated type a context resolves to a concrete one through wiring. Every named [abstract type](/docs/reference/glossary#abstract-type) a program defines with [`#[cgp_type]`](../macros/cgp_type.md), including `HasErrorType` and [`HasRuntimeType`](./has_runtime_type.md) below, is built on this substrate, and the same [`UseType`](../providers/use_type.md) marker resolves all of them. You reach for `HasType` directly diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index 995cbedc..e69f8012 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -44,7 +44,7 @@ Its attributes: - [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Runner` that implementations target and the wiring key `RunnerComponent`, while `CanRun` stays the consumer trait callers use. - [`#[async_trait]`](../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. - [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Code` type, so a context can route each `Code` to its own provider; the `open` statement is the modern sugar for the same dispatch. -- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. ## Usage diff --git a/docs/reference/components/send_runner.md b/docs/reference/components/send_runner.md index b3be82d0..e708e524 100644 --- a/docs/reference/components/send_runner.md +++ b/docs/reference/components/send_runner.md @@ -14,7 +14,7 @@ The runner variant whose returned future is `Send`, for work that must cross a t `tokio::spawn`. It exists to solve a specific Rust limitation. A generic `async fn` over abstract **context** types (the context being the type a method runs on that supplies the values an implementation needs as its own fields) cannot promise its future is `Send` without annotating `Send` -bounds on every abstract type in scope, and those bounds pollute every interface. +bounds on every [abstract type](/docs/reference/glossary#abstract-type) in scope, and those bounds pollute every interface. `CanSendRun` sidesteps that by returning an explicit `impl Future> + Send`, so the `Send` requirement lives on this one trait rather than spreading across the abstract types. @@ -48,7 +48,7 @@ Its attributes: - [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `SendRunner` that implementations target and the wiring key `SendRunnerComponent`, while `CanSendRun` stays the consumer trait callers use. - [`#[async_trait]`](../macros/async_trait.md) — the attribute CGP's async trait methods carry; it rewrites an `async fn` into a lint-clean `-> impl Future` method. Here `send_run` is already written in that form so it can add the `+ Send` bound that [`CanRun`](./runner.md)'s `run` omits. - [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Code` type, so a context can route each `Code` to its own provider; the `open` statement is the modern sugar for the same dispatch. -- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. +- [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. ## Usage diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index 9cf9d3f4..03ca573d 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -12,7 +12,7 @@ sidebar_position: 4 Generic code needs traits to read and assemble fields across different structs. A type parameter alone does not let it refer to a field such as `first_name`. -`#[derive(CgpRecord)]` supplies those traits, making the struct an **extensible record**. It generates +`#[derive(CgpRecord)]` supplies those traits, making the struct an **[extensible record](/docs/reference/glossary#extensible-record)**. It generates per-field access, a representation of the whole struct, and a builder that fills fields individually. Generic code can use these operations without naming the concrete struct. diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index c4c24ae4..4b7ea42b 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -47,7 +47,7 @@ It accepts any struct shape. The shapes differ only in how each field's tag is c ### Named fields -A named field is keyed by [`Symbol!`](../macros/symbol.md), the type-level string of its identifier. The +A named field is keyed by [`Symbol!`](../macros/symbol.md), the [type-level string](/docs/reference/glossary#type-level-string) of its identifier. The struct above gains access keyed by `Symbol!("name")` and `Symbol!("age")`. A field written as a [raw identifier](https://doc.rust-lang.org/reference/identifiers.html) is keyed by @@ -160,7 +160,7 @@ The implicit form generates a `HasField` bound and reads the field for you. Pref ordinary field read; the explicit form is useful when reading generated code or diagnostics. Field access passes through smart pointers without an additional derive. `Box` and -newtypes that dereference to `Person` can read its fields through the library's blanket implementations. +newtypes that dereference to `Person` can read its fields through the library's [blanket implementations](/docs/reference/glossary#blanket-implementation). ## When to use it @@ -171,7 +171,7 @@ derive, but its fields need corresponding trait implementations to support gener Choose the field-access syntax according to what the implementation needs: - **[`#[implicit]`](../attributes/implicit.md)**: use by default to read a field from the - implementation's own context as a parameter, without declaring a getter trait. + implementation's own context as a parameter, without declaring a [getter trait](/docs/reference/glossary#getter-trait). - **[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md)**: use when the read should be a named trait, the field belongs to another type, or the getter needs a type inferred from the field. - **A hand-written `HasField` bound**: use when the higher-level forms do not fit. Add `Value = T` to @@ -181,7 +181,7 @@ Choose the field-access syntax according to what the implementation needs: Incremental construction requires [`BuildField`](./derive_build_field.md). `HasField` provides access to existing fields; [`CgpData`](./derive_cgp_data.md) combines it with the representation and builder -needed for an extensible record. +needed for an [extensible record](/docs/reference/glossary#extensible-record). ## Under the hood diff --git a/docs/reference/errors.md b/docs/reference/errors.md index eed93955..510f216d 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -60,12 +60,12 @@ Match the compiler's code and the shape of the message. | `E0119` conflicting implementations | Two wiring entries claim one key | [The wiring itself does not compile](#the-wiring-itself-does-not-compile) | | `E0428` the name … is defined multiple times | A generated name declared twice | [Two entries claim one key](#two-entries-claim-one-key) | | `E0275` overflow evaluating the requirement | A wiring or inheritance cycle | [A lookup that never terminates](#a-lookup-that-never-terminates) | -| `E0210` / `E0117` orphan rule | Registering into a namespace you do not own | [Registering into a namespace you do not own](#registering-into-a-namespace-you-do-not-own) | +| `E0210` / `E0117` [orphan rule](/docs/reference/glossary#orphan-rule) | Registering into a namespace you do not own | [Registering into a namespace you do not own](#registering-into-a-namespace-you-do-not-own) | | `E0207` type parameter is not constrained | A per-entry generic that never reaches the key | [A generic that reaches nothing](#a-generic-that-reaches-nothing) | | `E0107` trait takes N generic arguments but N+1 supplied | A consumer trait written where a provider trait belongs | [Naming the wrong half of a component](#naming-the-wrong-half-of-a-component) | | `E0433` / `E0425` cannot find type | A name the generated code cannot see | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | | `E0576` cannot find associated type … in trait | A `#[use_type]` import with a wrong name | [An imported type that does not exist](#an-imported-type-that-does-not-exist) | -| `E0404` expected trait, found type parameter | An abstract type named after its own bound | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | +| `E0404` expected trait, found type parameter | An [abstract type](/docs/reference/glossary#abstract-type) named after its own bound | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | ## A dependency is not met @@ -350,7 +350,7 @@ Two carets, two lines to reconcile. Related codes cover the neighbouring shapes: Two things are worth knowing when reading the raw form. A context-wiring entry generates *two* impls, so one duplicate prints a **pair** of `E0119`s — one conflict, not two. And a blanket-versus-specific collision often carries a "downstream crates may implement …" note: that is the compiler explaining that -coherence must allow for impls a future crate could add, not a second problem. +[coherence](/docs/reference/glossary#coherence) must allow for impls a future crate could add, not a second problem. A duplicate **name** rather than a duplicate key is an `E0428` instead, and passes through uncoded — it already points precisely at both definitions. @@ -393,7 +393,7 @@ unclaimed in the namespace so the context can supply it, or change the binding i The same mistake one level up — a child namespace redefining a key it inherits — produces a bare `conflicting implementations of trait ChildNs<_> for type GreeterComponent`, which the tool does not yet -rewrite. The tell is that the conflicting *self type* is a component marker rather than a context. The +rewrite. The tell is that the conflicting *self type* is a [component marker](/docs/reference/glossary#component-marker) rather than a context. The fix there is to leave the key unbound in the base so each child can bind it. ### Registering into a namespace you do not own diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 75885764..240f7cec 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -149,7 +149,7 @@ The decisions worth making are around it rather than about it. provider into an async one where a caller needs it. So a computation that does no I/O is better declared synchronous and promoted than declared async out of habit. - **Use the `async-trait` crate instead only if you need `dyn` compatibility.** Boxing makes an - async trait object-safe, and this macro deliberately does not box. CGP resolves providers statically, so it + async [trait object](/docs/reference/glossary#trait-object)-safe, and this macro deliberately does not box. CGP resolves providers statically, so it does not need `dyn`; a codebase that does for other reasons is outside what this macro is for. ## Under the hood diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 289d761d..c4af1e53 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -5,7 +5,7 @@ sidebar_position: 11 # `#[blanket_trait]` -Generate a blanket impl from a trait with default methods and supertrait dependencies. +Generate a blanket impl from a trait with default methods and [supertrait](/docs/reference/glossary#supertrait) dependencies. ## Overview @@ -33,7 +33,7 @@ pub trait FooBar: Foo + Bar { } ``` -**This is not a CGP component.** There is no consumer/provider split, no component marker, and no wiring: +**This is not a CGP component.** There is no consumer/provider split, no [component marker](/docs/reference/glossary#component-marker), and no wiring: just an ordinary Rust trait and an ordinary blanket impl. It is the tool for a trait with exactly one definition, where you want extension-trait ergonomics without committing to the component machinery. When a second implementation becomes necessary, the trait can be promoted to a @@ -164,7 +164,7 @@ That last clause is the real discriminator, separating this macro from its close and no caller is generic over the type, a function with a `where` clause is simpler and the propagation problem never arises. -One caution specific to this construct: a blanket impl is **coherence-visible**, so it competes with any +One caution specific to this construct: a blanket impl is **[coherence](/docs/reference/glossary#coherence)-visible**, so it competes with any other impl of the same trait. That is why the pattern admits exactly one definition, and why two `#[blanket_trait]` traits whose bounds can both hold for one type cannot both cover that type for the same trait. Needing that is the signal to move to a component. diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 2c20f6e3..f27b5a75 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -44,7 +44,7 @@ pub trait HasArea { } ``` -The trait may have generic parameters and supertraits. Each method may take `self` by value, by shared +The trait may have generic parameters and [supertraits](/docs/reference/glossary#supertrait). Each method may take `self` by value, by shared reference, or by mutable reference; may take further value or reference arguments; and may be `async`. A couple of restrictions are enforced when the macro expands: diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index d5dc940e..efa78a3a 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -27,12 +27,12 @@ wired and no impl is written: the macro emits one covering every qualifying context, keyed on each method's own name. It hides the field-access trait CGP reads fields through, which is precise and unpleasant to write by -hand: a bound naming the field as a type-level string, and a `PhantomData` tag at every read. Being +hand: a bound naming the field as a [type-level string](/docs/reference/glossary#type-level-string), and a `PhantomData` tag at every read. Being able to state the same thing as `fn name(&self) -> &str;` is the point. **Use it sparingly.** For the ordinary case, a provider reading a field of its own context, an [`#[implicit]`](../attributes/implicit.md) argument does the same job with no trait to declare, using the -same field access and the same conversion rules, so a getter trait declared only to read a field adds a +same field access and the same conversion rules, so a [getter trait](/docs/reference/glossary#getter-trait) declared only to read a field adds a name and gives nothing back. A getter trait *does* give you one thing: an accessor other code can depend on by name. The cases where that matters are in [When to use it](#when-to-use-it). @@ -218,7 +218,7 @@ A getter trait is worth declaring in a few cases an implicit argument cannot rea as in `Request: HasBasicAuthHeader`. There is no `self` field to read. - **The accessor must be a named trait.** When other code depends on "this context can tell you its name" rather than on a field, that dependency needs a trait to point at, importable with - [`#[uses]`](../attributes/uses.md) or usable as a supertrait via [`#[extend]`](../attributes/extend.md). + [`#[uses]`](../attributes/uses.md) or usable as a [supertrait](/docs/reference/glossary#supertrait) via [`#[extend]`](../attributes/extend.md). - **The getter carries a type inferred from the field.** The associated-type form above keeps the type abstract for callers in a way a concrete implicit parameter cannot. @@ -259,7 +259,7 @@ where ``` A few things to recognize. The context parameter is literally `__Context__`, a reserved name chosen so it -cannot collide with one of yours. [`Symbol!("name")`](./symbol.md) is a type-level string standing for the +cannot collide with one of yours. [`Symbol!("name")`](./symbol.md) is a [type-level string](/docs/reference/glossary#type-level-string) standing for the field name. The compiler prints its expanded `Symbol<4, Chars<'n', …>>` form in errors, and `cargo cgp expand` resugars it back to this. And because the return type is `&str`, the bound asks for a `String` field and the body appends `.as_str()`, which is the conversion table in action. diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index cb3257ba..9d423cb4 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -42,7 +42,7 @@ its own small type instead of the single `Self` slot every plain trait has. A ** those targets: a zero-sized type such as `RectangleArea` without data of its own that exists only to name one implementation. The type the methods run on is called the **context**. It supplies whatever values an implementation needs as its own fields, and it picks the provider it wants -through [`delegate_components!`](./delegate_components.md). The generated blanket implementations then +through [`delegate_components!`](./delegate_components.md). The generated [blanket implementations](/docs/reference/glossary#blanket-implementation) then route a call on the consumer trait through to that choice automatically. This costs nothing at runtime. Wiring fixes the provider once, at compile time, and the compiler turns the call into a direct, statically-dispatched call, exactly as if you had written the implementation yourself. @@ -87,7 +87,7 @@ for setting `provider` alone. | Key | What it sets | Default | |---|---|---| | `provider` | The provider trait's name | *required* | -| `name` | The component marker type | The provider name plus `Component` | +| `name` | The [component marker](/docs/reference/glossary#component-marker) type | The provider name plus `Component` | | `context` | The identifier used for the generated context type parameter | `__Context__` | The `context` default is deliberately unusual so that it cannot collide with a type parameter of your @@ -101,7 +101,7 @@ comma-separated list inside one attribute. | Attribute | What it adds | |---|---| -| [`#[use_type(Trait.Type)]`](../attributes/use_type.md) | Imports an abstract type: adds the supertrait *and* rewrites the bare name in your signatures | +| [`#[use_type(Trait.Type)]`](../attributes/use_type.md) | Imports an [abstract type](/docs/reference/glossary#abstract-type): adds the [supertrait](/docs/reference/glossary#supertrait) *and* rewrites the bare name in your signatures | | [`#[extend(Trait)]`](../attributes/extend.md) | Adds a supertrait with no type to import | | [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) | Generates dispatch impls for a component generic over a parameter | | [`#[prefix(@path in Namespace)]`](../attributes/prefix.md) | Registers the component into a namespace under a type-level path | diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index bd57ef2c..c5666223 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -145,7 +145,7 @@ exists for, and it is the simplest way into the handler family. drawn from the context alone. It is the input-free sibling and produces a `Producer`. - **Write the provider by hand with [`#[cgp_impl]`](./cgp_impl.md) when the body needs the context.** This is the real boundary. A `#[cgp_computer]` function has no receiver and no access to the context, so it can - only transform its inputs. The moment the computation needs a field, an abstract type, or another + only transform its inputs. The moment the computation needs a field, an [abstract type](/docs/reference/glossary#abstract-type), or another trait, it wants a provider impl of `Computer` or `Handler` written with `#[cgp_impl]`, where `self` is the context and [`#[implicit]`](../attributes/implicit.md) and [`#[uses]`](../attributes/uses.md) work normally. diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index d08b2fa5..dae6b1cd 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -5,7 +5,7 @@ sidebar_position: 3 # `#[cgp_fn]` -Define a trait with a single blanket implementation, straight from a function. +Define a trait with a single [blanket implementation](/docs/reference/glossary#blanket-implementation), straight from a function. ## Overview @@ -121,7 +121,7 @@ some `Display` type, and the compiler resolves the type from that field. The type is then concealed rather than named, so it cannot appear in this function's own signature, and two traits cannot agree on it. The [`#[impl_generics]`](../attributes/impl_generics.md) -page says when to promote such a type to an abstract type instead. +page says when to promote such a type to an [abstract type](/docs/reference/glossary#abstract-type) instead. ### Companion attributes @@ -132,7 +132,7 @@ it depends on. like a `use` statement rather than a hand-written `where Self: Trait` bound. It accepts ordinary Rust traits as readily as CGP ones. - [`#[use_type(Trait.Type)]`](../attributes/use_type.md) imports an abstract type so the signature can - name it bare, and adds the owning trait as a supertrait. + name it bare, and adds the owning trait as a [supertrait](/docs/reference/glossary#supertrait). - [`#[extend(...)]`](../attributes/extend.md) adds a method supertrait to the generated trait. Here it is the *only* way to add one, since a `where` clause in a `#[cgp_fn]` is an implementation detail rather than part of the interface. @@ -254,7 +254,7 @@ where Learn to recognize a few details of the real output. The context type parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours, and the impl refers to -it as `Self`. [`Symbol!("width")`](./symbol.md) is a type-level string standing for the field name. +it as `Self`. [`Symbol!("width")`](./symbol.md) is a [type-level string](/docs/reference/glossary#type-level-string) standing for the field name. The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and `cargo cgp expand` resugars it back to this. An *owned* implicit argument compiles to a trailing `.clone()`. A `&str` argument ends in `.as_str()` instead, and a plain `&T` in nothing at all. diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 29350235..2599e656 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -37,7 +37,7 @@ need neither. The [When to use it](#when-to-use-it) section draws the line. ## Usage -Apply the attribute to a getter trait, exactly as with [`#[cgp_auto_getter]`](./cgp_auto_getter.md). It +Apply the attribute to a [getter trait](/docs/reference/glossary#getter-trait), exactly as with [`#[cgp_auto_getter]`](./cgp_auto_getter.md). It accepts the same method forms: every receiver shape, including a [typed reference to another type](./cgp_auto_getter.md#reading-a-field-of-another-type) in place of `self` and an [optional `PhantomData` argument](./cgp_auto_getter.md#an-optional-phantomdata-argument); diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index b2f2c7ab..f6bbbf49 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -151,7 +151,7 @@ provider becomes a tuple struct with one public generic parameters together, always `pub` and never with a default. You must write by hand anything the struct needs outside those shapes. -The case you see most often is a default on a higher-order provider's inner parameter, so an +The case you see most often is a default on a [higher-order provider](/docs/reference/glossary#higher-order-provider)'s inner parameter, so an application can omit the inner provider and fall back to [`UseContext`](../providers/use_context.md), which routes back through the context's own implementation of the component. If `ScaledAreaCalculator` from [Usage](#usage) should default this @@ -176,10 +176,10 @@ they let an idiomatic provider state what it needs. from a same-named field on the context. - [`#[uses(...)]`](../attributes/uses.md) adds the traits the provider depends on, reading like a `use` statement instead of a hand-written `where Self: Trait` clause. -- [`#[use_type(Trait.Type)]`](../attributes/use_type.md) imports an abstract type and rewrites its +- [`#[use_type(Trait.Type)]`](../attributes/use_type.md) imports an [abstract type](/docs/reference/glossary#abstract-type) and rewrites its occurrences to fully qualified form. - [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound in a - higher-order provider. + [higher-order provider](/docs/reference/glossary#higher-order-provider). - [`#[default_impl(...)]`](../attributes/default_impl.md) registers the provider as a namespace's per-type default, emitting a delegation impl alongside it, for use with [`cgp_namespace!`](./cgp_namespace.md). @@ -351,7 +351,7 @@ so a provider for `ComputerRef` gets provider that supplies `type Output`, because it gathers the block's own associated-type names first and skips any `Self::` path starting with one. In the emitted impl, `Self` is the provider struct, which is the type that declares `Output`, so the path still resolves. The macro still rewrites every -other `Self` in the block, including one naming an abstract type the *context* supplies. The exemption +other `Self` in the block, including one naming an [abstract type](/docs/reference/glossary#abstract-type) the *context* supplies. The exemption does not cover associated consts; see [Common Mistakes](#common-mistakes). **The rewrite is scoped to the block's own method bodies.** An item nested *inside* a body, such as a diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index bc1ce2ed..b1cb5967 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -66,7 +66,7 @@ A namespace body accepts two kinds of entry, and they do different things. Redirection makes namespaces composable: because a lookup is keyed by a *path* rather than a bare component name, a whole subtree can be rerouted at once, and a more specific path takes precedence over an inherited one. Paths are written with the `@` sigil as dotted sequences, such as `@MyFooComponent`, -`@app.ErrorRaiserComponent`, and `@cgp.core.error`, where lowercase segments become type-level strings and +`@app.ErrorRaiserComponent`, and `@cgp.core.error`, where lowercase segments become [type-level strings](/docs/reference/glossary#type-level-string) and capitalized segments name types. [`Path!`](./path.md) covers the syntax in full. ### The rest of the body grammar diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 5d236671..57068737 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -120,7 +120,7 @@ within it there is nothing simpler. same macro with the restrictions lifted, and it handles generics, `async`, and `Result` returns. - **Write the provider by hand with [`#[cgp_impl]`](./cgp_impl.md) when the value comes from the context.** This is the boundary that matters. A `#[cgp_producer]` function has no receiver, so it cannot read a field, - name an abstract type, or call another trait. It can only return something it computes from nothing. A + name an [abstract type](/docs/reference/glossary#abstract-type), or call another trait. It can only return something it computes from nothing. A producer that draws on its context is an impl of `Producer` written with `#[cgp_impl]`, where `self` is the context and [`#[implicit]`](../attributes/implicit.md) works normally. **In practice that covers most producers**, which makes this macro narrower than it first looks: it is for constants and pure seeds. diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 81b8bc21..a87aaac0 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -103,7 +103,7 @@ pub struct SpawnAndRun(pub ::core::marker::PhantomData); This is also the limit of what the attribute form can express, and the reason `#[cgp_provider]` is still needed. A struct that needs a **default** generic parameter has to be written by hand, and so does one shared by several impls. The common shape is -`pub struct IterSum(PhantomData);`, which a higher-order provider uses so it +`pub struct IterSum(PhantomData);`, which a [higher-order provider](/docs/reference/glossary#higher-order-provider) uses so it can fall back to the context's own wiring. ## Examples diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index b880e262..70689bfa 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -16,7 +16,7 @@ written once for many applications cannot decide which. Rust's answer is an `trait HasScalarType { type Scalar; }`, and code written against it says `Self::Scalar` while leaving the actual type open. -An abstract type in CGP is exactly that trait and nothing more exotic. `#[cgp_type]` adds the ability to +An [abstract type](/docs/reference/glossary#abstract-type) in CGP is exactly that trait and nothing more exotic. `#[cgp_type]` adds the ability to fill the slot by **wiring** rather than by writing an impl. Without it, giving a context a concrete scalar means writing a provider by hand: a whole impl whose only content is `type Scalar = f64;`. Since every abstract-type provider has that same trivial shape, `#[cgp_type]` diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 6fd393a4..a8020e02 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -219,7 +219,7 @@ the unsatisfied bound, but you cannot ask for it directly. ## Under the hood -A check table expands to one marker trait plus one empty impl per entry. The trait's supertrait *is* the +A check table expands to one marker trait plus one empty impl per entry. The trait's [supertrait](/docs/reference/glossary#supertrait) *is* the assertion; the impl has nothing of its own to prove, so it compiles exactly when the supertrait holds. From this input: @@ -324,7 +324,7 @@ is no diagnostic, and it is worth a second look if a table appears to pass witho ## Common Mistakes -**A check on an aggregate provider asks the wrong question, and how it fails depends on the provider.** A +**A check on an [aggregate provider](/docs/reference/glossary#aggregate-provider) asks the wrong question, and how it fails depends on the provider.** A `new`-keyword bundle is not a context, so a context-side check demands that the *bundle* satisfy the leaf provider's dependencies. If that provider has none, the check passes vacuously and proves nothing. If it needs anything from its context, such as a field or a type, the check fails, blaming the bundle: diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index cbd8188a..3c0e9a18 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -257,7 +257,7 @@ beginner-proof way to guarantee that for simple contexts; the two separate macro ## Under the hood The macro emits the delegation impls exactly as [`delegate_components!`](./delegate_components.md) would, -then appends a check trait and one impl per non-skipped entry exactly as +then appends a [check trait](/docs/reference/glossary#check-trait) and one impl per non-skipped entry exactly as [`check_components!`](./check_components.md) would. From this input: ```rust @@ -345,7 +345,7 @@ component's check needs, and `#[skip_check]` wires the entry with no check at al ## Common Mistakes -**Used on an aggregate provider, this macro reports a failure that describes nothing real.** A `new`-keyword +**Used on an [aggregate provider](/docs/reference/glossary#aggregate-provider), this macro reports a failure that describes nothing real.** A `new`-keyword bundle is not a context, so the derived check asks whether the *bundle* satisfies the leaf provider's dependencies. When the bundled provider needs nothing, the check passes and proves nothing; when it needs anything from its context, the check fails and blames the bundle: diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 1084576d..8c101f2e 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -73,7 +73,7 @@ delegate_components! { } ``` -Use this form to build an **aggregate provider**: a zero-sized provider whose only job is to hold a +Use this form to build an **[aggregate provider](/docs/reference/glossary#aggregate-provider)**: a zero-sized provider whose only job is to hold a table dispatching each component to a sub-provider, so that other contexts can delegate a whole group of components to it as one unit. An aggregate provider is a *provider*, not a context. It forwards each component's provider trait onward, and a call never resolves with the bundle in the context @@ -180,7 +180,7 @@ redirect: the per-value slots an `open` statement opens, or the prefixed routes [namespace](./cgp_namespace.md) registers. `@AreaCalculatorComponent.Rectangle: RectangleArea` stores `RectangleArea` where the `AreaCalculatorComponent` redirect lands when the dispatch type is `Rectangle`. Segments follow [`Path!`](./path.md)'s convention: a lowercase, non-primitive identifier -becomes a type-level string, and anything else names a type. A segment may also carry generics, as in +becomes a [type-level string](/docs/reference/glossary#type-level-string), and anything else names a type. A segment may also carry generics, as in `@SomeComponent.<'a, T> &'a T: SomeProvider`. Two grouping forms expand one path key into several, and **they are not interchangeable**: @@ -688,7 +688,7 @@ end. [`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared it separately. The error names an unresolved type rather than anything about wiring. -**Two entries claiming one key conflict**, and the compiler reports it as a coherence error rather than +**Two entries claiming one key conflict**, and the compiler reports it as a [coherence](/docs/reference/glossary#coherence) error rather than as a wiring one. This covers the obvious duplicate, an `open` header colliding with an explicit mapping for the same component, and a generic ` AreaCalculatorComponent` entry overlapping a specific `AreaCalculatorComponent` one. The same applies to a direct entry for a path a diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md index 8152a76d..b8f4c3b9 100644 --- a/docs/reference/macros/index.md +++ b/docs/reference/macros/index.md @@ -26,7 +26,7 @@ generated code rather than written by hand. When a trait has exactly one implementation and needs no wiring at all, [`#[cgp_fn]`](./cgp_fn.md) builds it straight from a function, and [`#[blanket_trait]`](./blanket_trait.md) does the same starting from a trait with default methods and -supertrait dependencies. [`#[async_trait]`](./async_trait.md) is how any of these traits declares an +[supertrait](/docs/reference/glossary#supertrait) dependencies. [`#[async_trait]`](./async_trait.md) is how any of these traits declares an `async fn` without tripping the lint a bare one produces. A few macros specialize `#[cgp_component]` for a narrower job. [`#[cgp_type]`](./cgp_type.md) is for a diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 5d3862e2..268a263f 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -23,7 +23,7 @@ Path!(@app.error.ErrorRaiserComponent) ``` It is the path-shaped sibling of CGP's other type-level construction macros. Where -[`Symbol!`](./symbol.md) turns a literal into a type-level string and [`Product!`](./product.md) and +[`Symbol!`](./symbol.md) turns a literal into a [type-level string](/docs/reference/glossary#type-level-string) and [`Product!`](./product.md) and [`Sum!`](./sum.md) build record and variant lists, `Path!` builds the routing list, sharing their right-nested, `Nil`-terminated shape. diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 13a70c93..d9b2a820 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -72,7 +72,7 @@ pub struct Person { // } ``` -The names are [`Symbol!`](./symbol.md) type-level strings and each entry is a [`Field`](../types/field.md), so +The names are [`Symbol!`](./symbol.md) [type-level strings](/docs/reference/glossary#type-level-string) and each entry is a [`Field`](../types/field.md), so the whole `Product!` is a complete type-level description of `Person`'s layout. Generic code walks that list to build or read a `Person` without being written against `Person`. diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index dc43f00a..f767292b 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -71,7 +71,7 @@ pub enum Shape { // } ``` -A couple of things to notice. The variant names are [`Symbol!`](./symbol.md) type-level strings, exactly as field names +A couple of things to notice. The variant names are [`Symbol!`](./symbol.md) [type-level strings](/docs/reference/glossary#type-level-string), exactly as field names are. And a struct-like variant nests a [`Product!`](./product.md) of its own fields, so an enum's full shape is a sum of variants whose payloads may themselves be records. Generic code walks the `Sum!` to find which variant a value holds, then walks the nested `Product!` to reach that variant's fields. diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 6d1e56b6..ae8abb84 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -5,7 +5,7 @@ sidebar_position: 16 # `Symbol!` -A type-level string, used as a field-name tag. +A [type-level string](/docs/reference/glossary#type-level-string), used as a field-name tag. ## Overview diff --git a/docs/reference/providers/dispatch/build_and_set_field.md b/docs/reference/providers/dispatch/build_and_set_field.md index c0c8239a..b2a22554 100644 --- a/docs/reference/providers/dispatch/build_and_set_field.md +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -5,7 +5,7 @@ sidebar_position: 8 # `BuildAndSetField` -The builder adapter that computes one field's value and sets it on a partial record. +The builder adapter that computes one field's value and sets it on a [partial record](/docs/reference/glossary#partial-record). ## Overview diff --git a/docs/reference/providers/dispatch/build_with_handlers.md b/docs/reference/providers/dispatch/build_with_handlers.md index c31925f1..32ca57ea 100644 --- a/docs/reference/providers/dispatch/build_with_handlers.md +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -11,7 +11,7 @@ the fully-populated result. ## Overview `BuildWithHandlers` is the entry point on the builder side. It starts from an empty -partial record, pipes that builder through a list of builder adapters so each one sets its field, and +[partial record](/docs/reference/glossary#partial-record), pipes that builder through a list of builder adapters so each one sets its field, and finalizes the fully-populated result into the concrete `Output`. It runs on a **context**, the type a method runs on. Because the finalize step is available only when every field is present, omitting a handler for some field is a compile error rather than a runtime failure. Like every CGP diff --git a/docs/reference/providers/index.md b/docs/reference/providers/index.md index c347ba23..c2e64bac 100644 --- a/docs/reference/providers/index.md +++ b/docs/reference/providers/index.md @@ -16,7 +16,7 @@ is the fuller map for once the essentials are familiar. ## Wiring an everyday component [`UseContext`](./use_context.md) implements a provider trait by routing back through the context's own -consumer-trait implementation. A higher-order provider falls back to it, and a dispatch combinator +consumer-trait implementation. A [higher-order provider](/docs/reference/glossary#higher-order-provider) falls back to it, and a dispatch combinator routes each matched case through it as its default per-variant provider. [`UseType`](./use_type.md) supplies a concrete type for an abstract-type component, so a context binds its error type or runtime with one wiring line. @@ -46,7 +46,7 @@ Both are read in wiring far more often than written. a getter that returns a view of a field the context stores as a different type. [`ChainGetters`](./chain_getters.md) composes a list of getters to reach a field several hops inside a nested context. -[`UseDelegatedType`](./use_delegated_type.md) resolves an abstract type through a table rather than +[`UseDelegatedType`](./use_delegated_type.md) resolves an [abstract type](/docs/reference/glossary#abstract-type) through a table rather than fixing it to one concrete type. Each is reached through [`WithProvider`](./with_provider.md) when wired to a component. diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index ef5e7d4e..1594837b 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -25,7 +25,7 @@ this provider is legible. `RedirectLookup` separates *which key* a component is looked up under from *which table* answers it. The ordinary provider blanket impl looks a component up in the **context**'s own -delegation table, keyed by the component marker, where the context is the type the method runs +delegation table, keyed by the [component marker](/docs/reference/glossary#component-marker), where the context is the type the method runs on. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed by a type-level `Path`, then delegates to whatever provider that entry holds. This indirection lets one component's resolution be redirected to a different key in a different table, which is the basis for diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index 2ff8f293..7c1cf44f 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -16,7 +16,7 @@ trait is exactly the one the context already supplies that way. `UseContext` is a provider whose method bodies call the consumer method on the context, so handing a component `UseContext` means "use whatever this context already does for this trait." -This makes `UseContext` the exact dual of the consumer-trait blanket implementation that +This makes `UseContext` the exact dual of the consumer-trait [blanket implementation](/docs/reference/glossary#blanket-implementation) that [`#[cgp_component]`](../macros/cgp_component.md) generates. That blanket impl runs in the consumer-to-provider direction: a context implements `CanEncode` by delegating to whichever provider implements `Encoder` for it. `UseContext` runs the other way: it implements the provider trait @@ -34,7 +34,7 @@ position is never read. ## Usage `UseContext` is in the prelude, so `use cgp::prelude::*;` is enough. It takes no type parameter and -appears in two places. Most often it is a higher-order provider's default inner provider, written in +appears in two places. Most often it is a [higher-order provider](/docs/reference/glossary#higher-order-provider)'s default inner provider, written in the provider's struct definition: ```rust @@ -127,7 +127,7 @@ defaulting to `UseContext`. [`#[cgp_component]`](../macros/cgp_component.md) emits a `UseContext` implementation of the provider trait for every component it defines, alongside the consumer blanket impl, the provider blanket impl, -the component marker, and the [`RedirectLookup`](redirect_lookup.md) impl. The generated impl bounds the +the [component marker](/docs/reference/glossary#component-marker), and the [`RedirectLookup`](redirect_lookup.md) impl. The generated impl bounds the context on the consumer trait and forwards each method to it. For a component such as ```rust @@ -153,7 +153,7 @@ where The provider method takes the context explicitly and calls the context's own `CanGreet::greet`. Each `UseContext` impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl carrying the same `where` clause, so delegation propagates the dependency and a check reports a missing -consumer-trait implementation precisely. Any supertrait bound on the consumer trait is reproduced in the +consumer-trait implementation precisely. Any [supertrait](/docs/reference/glossary#supertrait) bound on the consumer trait is reproduced in the `where` clause, so a context must satisfy it before `UseContext` can stand in as a provider. ## Common Mistakes diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index 983077f8..3f19062a 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -5,7 +5,7 @@ sidebar_position: 11 # `UseDelegatedType` -Resolve an abstract type by looking its tag up in a table, instead of fixing it to one concrete type. +Resolve an [abstract type](/docs/reference/glossary#abstract-type) by looking its tag up in a table, instead of fixing it to one concrete type. ## Overview @@ -13,7 +13,7 @@ Resolve an abstract type by looking its tag up in a table, instead of fixing it should itself be decided by a table. The plain [`UseType`](use_type.md) provider binds an abstract type to one fixed `T`. But sometimes a single provider must answer several abstract-type components at once, or route each type tag to a different concrete type chosen elsewhere, such as when a namespace or -a higher-order provider supplies a coherent bundle of types. Hand-writing one `UseType` entry per tag +a [higher-order provider](/docs/reference/glossary#higher-order-provider) supplies a coherent bundle of types. Hand-writing one `UseType` entry per tag would scatter that decision; `UseDelegatedType` concentrates it into one `Components` table the provider consults. As always, the **context** (the type that implements the trait) points its type components at the provider. diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index dfe0cd57..31a0bdd0 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -25,7 +25,7 @@ so a context picks the field by writing `UseField` in its wiring itself is the general provider underneath: it works for any tag the context's [`HasField`](../traits/field-access/has_field.md) implementation supports. -The `Tag` is usually a type-level string built with [`Symbol!`](../macros/symbol.md), such as +The `Tag` is usually a [type-level string](/docs/reference/glossary#type-level-string) built with [`Symbol!`](../macros/symbol.md), such as `Symbol!("name")`, or a type-level integer wrapped in `Index` for a tuple field. These are the tags that [`#[derive(HasField)]`](../derives/derive_has_field.md) produces `HasField` implementations for. Like every CGP provider, `UseField` carries no runtime value: it is a `PhantomData` marker named @@ -97,7 +97,7 @@ needs full control over which field a getter reads from. That is the advanced ca For the common case of reading a field, prefer an [`#[implicit]`](../attributes/implicit.md) argument instead, which reads a same-named field and looks like an ordinary function parameter with no getter -trait at all. Where a getter trait is genuinely needed but the field name matches the method name, use +trait at all. Where a [getter trait](/docs/reference/glossary#getter-trait) is genuinely needed but the field name matches the method name, use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md), or wire [`UseFields`](use_fields.md), which keys each method on its own name. The [`#[cgp_getter]`](../macros/cgp_getter.md) page works the choice through in full. @@ -136,7 +136,7 @@ the returned reference is to the real field. `UseField` also implements the mutable getter [`MutFieldGetter`](../traits/field-access/mut_field_getter.md) the same way, requiring `Context: HasFieldMut` and returning `&mut Value`. And it implements -[`TypeProvider`](../components/has_type.md), reporting the field's `Value` type as an abstract type, so +[`TypeProvider`](../components/has_type.md), reporting the field's `Value` type as an [abstract type](/docs/reference/glossary#abstract-type), so the *type* of a field can itself be wired as a context's abstract type. Each implementation is paired with an [`IsProviderFor`](../traits/wiring/is_provider_for.md) implementation carrying the same `HasField` bound, so delegation propagates the dependency and a check reports a missing field precisely. diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 222f5ddf..56c372b4 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -18,7 +18,7 @@ The context is the type the method runs on, and it supplies those values as its method read the context field whose name equals the method name, looked up through [`HasField`](../traits/field-access/has_field.md) keyed by a [`Symbol!`](../macros/symbol.md). -This is the provider analogue of the blanket implementation that +This is the provider analogue of the [blanket implementation](/docs/reference/glossary#blanket-implementation) that [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) emits. `#[cgp_auto_getter]` produces a single blanket implementation that fires automatically for any context whose field names match the method names, with nothing to wire. `UseFields` packages the same field-by-method-name behavior as a provider @@ -93,7 +93,7 @@ case where the getter is a full component rather than a blanket impl. Prefer [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) when the getter does not need to be a wireable component, and prefer an [`#[implicit]`](../attributes/implicit.md) argument when a provider -simply needs a value from its own context, which is the common case and needs no getter trait at all. +simply needs a value from its own context, which is the common case and needs no [getter trait](/docs/reference/glossary#getter-trait) at all. Reach for [`UseField`](use_field.md) instead when the field name must differ from the method name. ## Under the hood diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index 1dd0becd..27de0556 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -13,7 +13,7 @@ Supply a concrete type as the value of an abstract-type component, binding it pu This page documents the `UseType` **provider**, the struct `UseType`. It is a different construct from the [`#[use_type]` attribute](../attributes/use_type.md), which rewrites bare type names inside a -definition and adds the owning trait as a bound. The attribute is about *referring to* an abstract type +definition and adds the owning trait as a bound. The attribute is about *referring to* an [abstract type](/docs/reference/glossary#abstract-type) ergonomically; the provider here is about *choosing the concrete type* an abstract type resolves to. They share a name because both concern abstract types, but they live in different places and do different jobs. @@ -52,7 +52,7 @@ delegate_components! { ``` A `#[cgp_type]` trait such as `HasScalarType` generates the provider trait `ScalarTypeProvider` and the -component marker `ScalarTypeProviderComponent`; wiring that marker to `UseType` sets the context's +[component marker](/docs/reference/glossary#component-marker) `ScalarTypeProviderComponent`; wiring that marker to `UseType` sets the context's `Scalar` to `f64`. Any bound on the associated type, such as `type Scalar: Copy`, is enforced against the concrete type at the wiring site. diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md index 5cca1a66..d073d22a 100644 --- a/docs/reference/providers/with_context.md +++ b/docs/reference/providers/with_context.md @@ -17,7 +17,7 @@ adapter with [`UseContext`](use_context.md) on a **context**, the type a method `WithContext` is distinct from the bare [`UseContext`](use_context.md), and the two play different roles. `UseContext` implements a component's provider trait *directly* by routing back to the context's -consumer trait, which is how it serves as a higher-order provider's default inner provider. `WithContext` +consumer trait, which is how it serves as a [higher-order provider](/docs/reference/glossary#higher-order-provider)'s default inner provider. `WithContext` instead wraps `UseContext` in the [`WithProvider`](with_provider.md) adapter. It is the least-used member of the `With…` family: the library defines it for completeness, and the common ways to serve a component from the context's own state are the constructs named below rather than this alias. diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md index 31254dee..df30a9cc 100644 --- a/docs/reference/providers/with_delegated_type.md +++ b/docs/reference/providers/with_delegated_type.md @@ -82,7 +82,7 @@ delegate_components! { `App` routes both its scalar and index type components through `WithDelegatedType`. For `App`'s `Scalar` the provider finds `f64` in `AppTypes`, and for `Index` it finds `usize`. One provider entry on -`App` answers two abstract types, with the concrete choices held in one place where they can be reused, +`App` answers two [abstract types](/docs/reference/glossary#abstract-type), with the concrete choices held in one place where they can be reused, swapped, or supplied by a namespace. ## When to use it diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 69daf0f7..6553b3ca 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -12,7 +12,7 @@ specific named component. `WithProvider` bridges CGP's two layers of provider trait. Foundational traits like [`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field-access/field_getter.md) are generic, -component-agnostic mechanisms: a `TypeProvider` supplies *some* abstract type for *some* tag, and a +component-agnostic mechanisms: a `TypeProvider` supplies *some* [abstract type](/docs/reference/glossary#abstract-type) for *some* tag, and a `FieldGetter` reads *some* field for *some* output tag, without either knowing which named component it serves. A named component, by contrast, has a specific provider trait, such as `NameTypeProvider` or `NameGetter`, that a **context** wires to, where the context is the type the method runs on. @@ -135,7 +135,7 @@ where } ``` -In both cases the bound names the foundational trait, keyed by the component marker, and the method or +In both cases the bound names the foundational trait, keyed by the [component marker](/docs/reference/glossary#component-marker), and the method or associated type forwards to it. `#[cgp_getter]` generates the `WithProvider` impl only when the getter has exactly one method, since a single foundational getter cannot serve several methods at once. Each impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl. diff --git a/docs/reference/providers/with_type.md b/docs/reference/providers/with_type.md index 32535d09..bdb3beb6 100644 --- a/docs/reference/providers/with_type.md +++ b/docs/reference/providers/with_type.md @@ -12,7 +12,7 @@ Bind an abstract-type component to a concrete type, through the `WithProvider` a `WithType` is the alias `WithProvider>`. It binds an abstract-type component to the concrete `Type` on a **context**, the type that implements the trait, by adapting the foundational [`UseType`](use_type.md) provider through the [`WithProvider`](with_provider.md) layer. It sets -the same abstract type the plain [`UseType`](use_type.md) provider does, and both are interchangeable in +the same [abstract type](/docs/reference/glossary#abstract-type) the plain [`UseType`](use_type.md) provider does, and both are interchangeable in wiring. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index c53e9401..16b5558c 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -10,7 +10,7 @@ Setting one currently-absent field of a builder. ## Overview `BuildField` is the direction of the [builder family](./has_builder.md) you write most: take a partial -record with a field absent, supply the value, and get back a partial record with that field present. +record with a field absent, supply the value, and get back a [partial record](/docs/reference/glossary#partial-record) with that field present. `Output` is a **different type** from `Self` (the same partial record with one marker flipped), which is what makes the compiler track completeness. A chain of `build_field` calls walks through as many distinct diff --git a/docs/reference/traits/builder/finalize_build.md b/docs/reference/traits/builder/finalize_build.md index ab01cc80..197c287b 100644 --- a/docs/reference/traits/builder/finalize_build.md +++ b/docs/reference/traits/builder/finalize_build.md @@ -5,7 +5,7 @@ sidebar_position: 6 # `FinalizeBuild` -Turning a fully-built partial record back into the concrete struct. +Turning a fully-built [partial record](/docs/reference/glossary#partial-record) back into the concrete struct. ## Overview @@ -24,7 +24,7 @@ let person = Person::builder() Delete a middle line and this does not compile. There is nothing to run and nothing to panic: the method is simply not in scope for a value with a field still absent. -The destination type comes from its supertrait [`PartialData`](./partial_data.md), which every +The destination type comes from its [supertrait](/docs/reference/glossary#supertrait) [`PartialData`](./partial_data.md), which every configuration implements. That division is deliberate: **one names where you are going, the other says you have arrived.** diff --git a/docs/reference/traits/builder/index.md b/docs/reference/traits/builder/index.md index 1bf34073..1d828bd7 100644 --- a/docs/reference/traits/builder/index.md +++ b/docs/reference/traits/builder/index.md @@ -34,7 +34,7 @@ generic builder code knows what it is building before the build is complete. ## The ideas behind them -- [Extensible records](/docs/concepts/extensible-records): partial records and the extensible builder +- [Extensible records](/docs/concepts/extensible-records): [partial records](/docs/reference/glossary#partial-record) and the extensible builder pattern. --- diff --git a/docs/reference/traits/builder/partial_data.md b/docs/reference/traits/builder/partial_data.md index 1e8d983f..37c7e0a7 100644 --- a/docs/reference/traits/builder/partial_data.md +++ b/docs/reference/traits/builder/partial_data.md @@ -21,7 +21,7 @@ where that projection comes from. The one case for bounding on it is generic cod ## Overview -A partial record is a companion type (`__PartialPerson`), and generic code holding +A [partial record](/docs/reference/glossary#partial-record) is a companion type (`__PartialPerson`), and generic code holding one often needs to know what it will *become* before it is complete: to name the return type of a routine, to state a bound, to decide what to do next. `PartialData` answers that: its single `Target` associated type is the concrete struct or enum the partial value corresponds to. **It is implemented for @@ -69,7 +69,7 @@ directly. ## Examples -Its most visible use is as [`FinalizeBuild`](./finalize_build.md)'s supertrait, which is how a finalize +Its most visible use is as [`FinalizeBuild`](./finalize_build.md)'s [supertrait](/docs/reference/glossary#supertrait), which is how a finalize knows what to return: ```rust diff --git a/docs/reference/traits/builder/take_field.md b/docs/reference/traits/builder/take_field.md index c2b7ba56..f50ee1a5 100644 --- a/docs/reference/traits/builder/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -10,7 +10,7 @@ Removing one currently-present field from a builder. ## Overview `TakeField` is the reverse of [`BuildField`](./build_field.md): it removes a field that is currently set, -handing back the value and the partial record without it. The value comes out owned, and the remainder is +handing back the value and the [partial record](/docs/reference/glossary#partial-record) without it. The value comes out owned, and the remainder is the partial record with that one field flipped back to absent, so it can no longer be finalized until the field is put back. diff --git a/docs/reference/traits/builder/update_field.md b/docs/reference/traits/builder/update_field.md index bae334c1..03bde2e6 100644 --- a/docs/reference/traits/builder/update_field.md +++ b/docs/reference/traits/builder/update_field.md @@ -5,7 +5,7 @@ sidebar_position: 5 # `UpdateField` -The primitive that moves one field of a partial record between states. +The primitive that moves one field of a [partial record](/docs/reference/glossary#partial-record) between states. :::info diff --git a/docs/reference/traits/field-access/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md index 7bf234d6..3f311ac4 100644 --- a/docs/reference/traits/field-access/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -47,7 +47,7 @@ pub trait FieldMapper: FieldGetter { } ``` -`Self` is the provider and `Context` is the type being read from. It is a supertrait extension of +`Self` is the provider and `Context` is the type being read from. It is a [supertrait](/docs/reference/glossary#supertrait) extension of [`FieldGetter`](./field_getter.md), exactly as [`MapField`](./map_field.md) extends [`HasField`](./has_field.md), so `Value` comes from the supertrait. `map_field` takes the context by shared reference, the `PhantomData` that names the field, and a `mapper` closure whose higher-ranked diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index 4b4a8d4f..9aa65637 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -28,7 +28,7 @@ pub trait HasFieldMut: HasField { } ``` -It is a **supertrait extension** rather than an alternative: `HasFieldMut` requires `HasField`, +It is a **[supertrait](/docs/reference/glossary#supertrait) extension** rather than an alternative: `HasFieldMut` requires `HasField`, so the field's type comes from that supertrait's `Value`, and bounding on the mutable form gives you the read as well. `get_field_mut` takes `&mut self` and returns `&mut Self::Value`, with the `PhantomData` argument naming the field exactly as [`HasField`](./has_field.md)'s `get_field` does. diff --git a/docs/reference/traits/field-access/map_field.md b/docs/reference/traits/field-access/map_field.md index 9a60a5a3..48497a36 100644 --- a/docs/reference/traits/field-access/map_field.md +++ b/docs/reference/traits/field-access/map_field.md @@ -45,7 +45,7 @@ pub trait MapField: HasField { } ``` -It is a supertrait extension of [`HasField`](./has_field.md), so `Value` comes from the supertrait. +It is a [supertrait](/docs/reference/glossary#supertrait) extension of [`HasField`](./has_field.md), so `Value` comes from the supertrait. `map_field` takes `&self`, the `PhantomData` that names the field, and a `mapper` closure, and it returns `&T`. The higher-ranked `for<'a>` bound on the closure is the whole trick: the closure must work for *any* lifetime, so the compiler ties the returned borrow to the field's own lifetime rather than diff --git a/docs/reference/traits/field-access/mut_field_getter.md b/docs/reference/traits/field-access/mut_field_getter.md index 98499833..eb1b73a7 100644 --- a/docs/reference/traits/field-access/mut_field_getter.md +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -12,7 +12,7 @@ The provider-side mirror of `HasFieldMut`: wired field access that can mutate. ### Generated machinery **You are not expected to implement `MutFieldGetter`.** -[`#[cgp_getter]`](../../macros/cgp_getter.md) generates it alongside its supertrait, and +[`#[cgp_getter]`](../../macros/cgp_getter.md) generates it alongside its [supertrait](/docs/reference/glossary#supertrait), and [`UseField`](../../providers/use_field.md) satisfies both. What you write is the wiring entry; this page explains what the mutable half of that entry provides. The one case for implementing it by hand is a provider whose mutable access is not a plain field read. diff --git a/docs/reference/traits/formatting/index.md b/docs/reference/traits/formatting/index.md index 465d068a..0640742c 100644 --- a/docs/reference/traits/formatting/index.md +++ b/docs/reference/traits/formatting/index.md @@ -17,7 +17,7 @@ is the group's sharpest edge: one is in the prelude and the other two each need - [`StaticString`](static_string.md) decodes a [`Symbol!`](../../macros/symbol.md) into a compile-time `&'static str` constant. This is the one to reach for when you need a name as data. Import it from `cgp::core::field::traits`. -- [`StaticFormat`](static_format.md) writes a type-level string into a formatter, and backs the +- [`StaticFormat`](static_format.md) writes a [type-level string](/docs/reference/glossary#type-level-string) into a formatter, and backs the `Display` impl on `Symbol`, so a `Display` bound is usually all you need. Reach for the trait itself only where there is no value to format. Import it from `cgp::core::base::traits`. - [`ConcatPath`](concat_path.md) joins two type-level [`Path!`](../../macros/path.md) routes, the diff --git a/docs/reference/traits/formatting/static_format.md b/docs/reference/traits/formatting/static_format.md index 4e0f0a5e..41b3d5af 100644 --- a/docs/reference/traits/formatting/static_format.md +++ b/docs/reference/traits/formatting/static_format.md @@ -5,7 +5,7 @@ sidebar_position: 2 # `StaticFormat` -Writing a type-level string into a formatter: the trait behind `Display` on `Symbol`. +Writing a [type-level string](/docs/reference/glossary#type-level-string) into a formatter: the trait behind `Display` on `Symbol`. :::info diff --git a/docs/reference/traits/formatting/static_string.md b/docs/reference/traits/formatting/static_string.md index df776226..8f906042 100644 --- a/docs/reference/traits/formatting/static_string.md +++ b/docs/reference/traits/formatting/static_string.md @@ -5,7 +5,7 @@ sidebar_position: 1 # `StaticString` -Recovering a type-level string as a compile-time `&'static str`. +Recovering a [type-level string](/docs/reference/glossary#type-level-string) as a compile-time `&'static str`. ## Overview diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index 60803bbf..bd11a236 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -160,7 +160,7 @@ same projection. [`#[default_impl]`](../../attributes/default_impl.md) accepts any path, so these three are conveniences rather than the only options. -**One constraint decides where a `#[default_impl]` may be written, and it is Rust's orphan rule rather +**One constraint decides where a `#[default_impl]` may be written, and it is Rust's [orphan rule](/docs/reference/glossary#orphan-rule) rather than anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, and Rust accepts it when the crate owns the namespace trait, or when a local type appears in the impl header ahead of the table parameter. That local type may be the key itself, or the component named inside the namespace path, so diff --git a/docs/reference/traits/namespace/default_impls2.md b/docs/reference/traits/namespace/default_impls2.md index 48c411af..1bca1a0c 100644 --- a/docs/reference/traits/namespace/default_impls2.md +++ b/docs/reference/traits/namespace/default_impls2.md @@ -137,7 +137,7 @@ The loop variables appear only in that bound and in the key, so **the key must m the parameter is unconstrained and the compiler rejects the impl with `E0207`. The registration impl carries only the parameters naming the key and provider plus the table, never the -provider's own `where` clause, so a provider with impl-side dependencies registers cleanly and its bounds +provider's own `where` clause, so a provider with [impl-side dependencies](/docs/reference/glossary#impl-side-dependency) registers cleanly and its bounds are checked when a real context resolves it. Because nothing in the library emits this trait, there is no generated code to compare against. The diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index 0bab9c4b..f1553616 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -154,7 +154,7 @@ type takes the `Self` position instead. The inconsistency is the family's sharpe **There is no method.** Resolving a default is a type projection. -**Registering into a foreign namespace is bound by the orphan rule.** See +**Registering into a foreign namespace is bound by the [orphan rule](/docs/reference/glossary#orphan-rule).** See [`DefaultImpls1`](./default_impls1.md#when-to-use-it), where the [`#[default_impl]`](../../attributes/default_impl.md) attribute's placement constraint is worked out. diff --git a/docs/reference/traits/optional/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md index 72ea406d..6a21203e 100644 --- a/docs/reference/traits/optional/can_build_with_default.md +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -33,7 +33,7 @@ pub trait CanBuildWithDefault { `Source` is the narrower record and `Self` is the target. `build_with_default` is an associated function with no receiver, and it returns a fully built `Self`. The trait declares no associated type and no -supertrait; it is a blanket impl chaining a builder, a merge, and a defaulted finalize, shown in +[supertrait](/docs/reference/glossary#supertrait); it is a blanket impl chaining a builder, a merge, and a defaulted finalize, shown in [*Under the hood*](#under-the-hood). Two requirements follow from that chain: the source needs [`HasFields`](../shape/has_fields.md), because the merge walks its field list, and every field the source does not supply needs `Default`, because the finalize fills it. It is not in the prelude; import it from diff --git a/docs/reference/traits/optional/can_finalize_with_default.md b/docs/reference/traits/optional/can_finalize_with_default.md index 152e142a..05a5af21 100644 --- a/docs/reference/traits/optional/can_finalize_with_default.md +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -5,7 +5,7 @@ sidebar_position: 5 # `CanFinalizeWithDefault` -Finalizing a partial record, filling whatever is unset from `Default`. +Finalizing a [partial record](/docs/reference/glossary#partial-record), filling whatever is unset from `Default`. ## Overview @@ -42,7 +42,7 @@ pub trait CanFinalizeWithDefault { from [`builder()`](../builder/has_builder.md) as well as an optional one from [`optional_builder()`](./has_optional_builder.md). `Output` is the concrete struct being built. `finalize_with_default` takes `self`, consuming the builder, and returns that struct with every unset -field filled from `Default`. The trait has no supertrait; it is a blanket impl over the +field filled from `Default`. The trait has no [supertrait](/docs/reference/glossary#supertrait); it is a blanket impl over the transform-then-finalize shown in [*Under the hood*](#under-the-hood). It is not in the prelude; import it from `cgp-field-extra`. diff --git a/docs/reference/traits/optional/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md index dd468773..d49326ed 100644 --- a/docs/reference/traits/optional/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -24,7 +24,7 @@ rather than when the builder is created: ## Definition -`FinalizeOptional` supertraits [`PartialData`](../builder/partial_data.md) and finalizes an optional +`FinalizeOptional` [supertraits](/docs/reference/glossary#supertrait) [`PartialData`](../builder/partial_data.md) and finalizes an optional builder into its concrete struct: ```rust @@ -33,7 +33,7 @@ pub trait FinalizeOptional: PartialData { } ``` -The `PartialData` supertrait supplies `Target`, the concrete struct being built, so the method projects +The `PartialData` [supertrait](/docs/reference/glossary#supertrait) supplies `Target`, the concrete struct being built, so the method projects its return type through it and declares no associated type of its own. `finalize_optional` takes `self`, consuming the builder, and returns `Result`: the built struct on success, or, on failure, the first missing field's own name, recovered from its type-level tag as a `&'static diff --git a/docs/reference/traits/optional/has_optional_builder.md b/docs/reference/traits/optional/has_optional_builder.md index 88893847..d9760019 100644 --- a/docs/reference/traits/optional/has_optional_builder.md +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -10,7 +10,7 @@ Starting a builder in which every field is already optional. ## Overview The core [builder family](../builder/has_builder.md) is deliberately strict: a field is set exactly once, and a -partial record becomes its concrete struct only when **every** field is present. That strictness is what +[partial record](/docs/reference/glossary#partial-record) becomes its concrete struct only when **every** field is present. That strictness is what catches a missing field at compile time, and it is too rigid for a record whose fields arrive in an unpredictable order, or more than once. @@ -39,7 +39,7 @@ pub trait HasOptionalBuilder { `Builder` names the partial companion type the derive generated, with every field marked `IsOptional`. It is the same companion the core builder produces, at a configuration the core builder never starts from. `optional_builder` is an associated function with no receiver, so a caller writes -`Context::optional_builder()`. The trait carries no supertrait, and it is implemented as a blanket impl +`Context::optional_builder()`. The trait carries no [supertrait](/docs/reference/glossary#supertrait), and it is implemented as a blanket impl over the core builder machinery, so any record that derives the builder gains it. It is not in the prelude; the whole optional-field layer lives in `cgp-field-extra`. diff --git a/docs/reference/traits/optional/index.md b/docs/reference/traits/optional/index.md index 151bb94f..908bb6a9 100644 --- a/docs/reference/traits/optional/index.md +++ b/docs/reference/traits/optional/index.md @@ -10,7 +10,7 @@ Relaxing the strict record builder, so a field can be set in any order or left u ## Overview The core [record builder](../builder/index.md) is deliberately strict: a field is set once, and a -partial record becomes its struct only when every field is present. That strictness catches a missing +[partial record](/docs/reference/glossary#partial-record) becomes its struct only when every field is present. That strictness catches a missing field at compile time, and it is too rigid for a record whose fields arrive unpredictably or have sensible defaults. These traits, from `cgp-field-extra`, relax it while reusing the same machinery underneath. Nothing here is in the prelude. Import each from `cgp::extra::field::impls`. diff --git a/docs/reference/traits/optional/set_optional.md b/docs/reference/traits/optional/set_optional.md index e3380bef..01d0989e 100644 --- a/docs/reference/traits/optional/set_optional.md +++ b/docs/reference/traits/optional/set_optional.md @@ -38,7 +38,7 @@ argument. `Value` is the field's declared type, so a caller passes an ordinary v `Option`. Both methods take `self` and return `Self`: the field's marker stays `IsOptional` before and after, so the builder's type does not change and an optional field can be set repeatedly. The two methods differ only in what they do with whatever was already there. `set` discards it; `set_optional` -returns it as an `Option` alongside the rebuilt builder. The trait has no supertrait. It is +returns it as an `Option` alongside the rebuilt builder. The trait has no [supertrait](/docs/reference/glossary#supertrait). It is not in the prelude; import it from `cgp-field-extra`. ## Usage diff --git a/docs/reference/traits/optional/to_optional.md b/docs/reference/traits/optional/to_optional.md index f9008011..8d714583 100644 --- a/docs/reference/traits/optional/to_optional.md +++ b/docs/reference/traits/optional/to_optional.md @@ -35,7 +35,7 @@ pub trait ToOptional { `Self` is any partial builder, and `Output` is the same partial companion type with every marker set to `IsOptional`. `to_optional` takes `self`, consuming the builder and returning the re-marked one. The -trait has no supertrait; it is a blanket impl over +trait has no [supertrait](/docs/reference/glossary#supertrait); it is a blanket impl over [`TransformMapFields`](../type-level/transform_map_fields.md), so any partial value whose fields can be re-marked gains it, with nothing to implement by hand. It is not in the prelude; the optional-field layer lives in `cgp-field-extra`. diff --git a/docs/reference/traits/optional/transform_map_default.md b/docs/reference/traits/optional/transform_map_default.md index 119ad443..3f41dce9 100644 --- a/docs/reference/traits/optional/transform_map_default.md +++ b/docs/reference/traits/optional/transform_map_default.md @@ -106,7 +106,7 @@ Writing a marker of your own follows the same three-impl shape; the **Name it only when writing an operation that drives the defaulting conversion.** Everything else is served by the two operations already built on it. -- **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** to finalize a partial record, defaulting +- **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** to finalize a [partial record](/docs/reference/glossary#partial-record), defaulting gaps. - **[`CanBuildWithDefault`](./can_build_with_default.md)** to merge from a source and default the rest, in one call. diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index e77e77f0..12fe7c0d 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -20,7 +20,7 @@ less of a field's type than its defaulting counterpart does. The one case for na ## Overview -[`ToOptional`](./to_optional.md) re-marks every field of a partial record to `IsOptional`, so it can then +[`ToOptional`](./to_optional.md) re-marks every field of a [partial record](/docs/reference/glossary#partial-record) to `IsOptional`, so it can then be set freely and finalized either way. `TransformOptional` is the marker carrying the per-field conversions that make that possible. diff --git a/docs/reference/traits/shape/from_fields.md b/docs/reference/traits/shape/from_fields.md index 34dc1edb..d64da179 100644 --- a/docs/reference/traits/shape/from_fields.md +++ b/docs/reference/traits/shape/from_fields.md @@ -25,7 +25,7 @@ pub trait FromFields: HasFields { } ``` -It supertraits [`HasFields`](./has_fields.md), so `from_fields` takes that trait's `Fields` shape and a +It [supertraits](/docs/reference/glossary#supertrait) [`HasFields`](./has_fields.md), so `from_fields` takes that trait's `Fields` shape and a bound on `FromFields` gives you `Fields` as well. It is an associated function rather than a method, because there is no value to call it on, so the call reads `Person::from_fields(fields)`, or `T::from_fields(fields)` in generic code. diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index 9a4809db..26327e5c 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -33,7 +33,7 @@ pub trait ToFields: HasFields { } ``` -It supertraits [`HasFields`](./has_fields.md), so `to_fields` returns that trait's `Fields` shape and a +It [supertraits](/docs/reference/glossary#supertrait) [`HasFields`](./has_fields.md), so `to_fields` returns that trait's `Fields` shape and a bound on `ToFields` gives you `Fields` as well. The method takes `self` by value, so it consumes the value to produce the owned shape. diff --git a/docs/reference/traits/shape/to_fields_ref.md b/docs/reference/traits/shape/to_fields_ref.md index 12c90f8e..785cca20 100644 --- a/docs/reference/traits/shape/to_fields_ref.md +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -30,7 +30,7 @@ pub trait ToFieldsRef: HasFieldsRef { } ``` -It supertraits [`HasFieldsRef`](./has_fields_ref.md) rather than [`HasFields`](./has_fields.md), which is +It [supertraits](/docs/reference/glossary#supertrait) [`HasFieldsRef`](./has_fields_ref.md) rather than [`HasFields`](./has_fields.md), which is the one structural difference from its owning counterpart [`ToFields`](./to_fields.md): the borrowed shape and the owned shape are named by two independent traits, and each conversion supertraits the one it produces. The method borrows `self` for `'a` and returns the borrowed diff --git a/docs/reference/traits/type-level/index.md b/docs/reference/traits/type-level/index.md index b84d8075..d51dafee 100644 --- a/docs/reference/traits/type-level/index.md +++ b/docs/reference/traits/type-level/index.md @@ -29,7 +29,7 @@ one entry to a product and [`ConcatProduct`](concat_product.md) splices two toge ## The ideas behind them -- [Extensible records](/docs/concepts/extensible-records): presence tracking on a partial record. +- [Extensible records](/docs/concepts/extensible-records): presence tracking on a [partial record](/docs/reference/glossary#partial-record). - [Extensible variants](/docs/concepts/extensible-variants): possibility tracking on a partial variant. --- diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index eab3a924..d208f0fb 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -12,7 +12,7 @@ Rewriting every entry of a type-level list through one marker. ### Generated machinery **You are not expected to use `MapFields` directly.** It is the type-level operation -behind a partial record's shape, computed by the machinery +behind a [partial record](/docs/reference/glossary#partial-record)'s shape, computed by the machinery [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) generates. You will most likely meet it in an error message; this page explains what it produces, and how it differs from the two similarly-named traits beside it. The one case for naming it is generic code that must describe a uniformly re-wrapped shape. diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index 1f5128c1..c61fc0fd 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -5,7 +5,7 @@ sidebar_position: 4 # `TransformMapFields` -Applying one per-field transform across a whole partial record. +Applying one per-field transform across a whole [partial record](/docs/reference/glossary#partial-record). :::info diff --git a/docs/reference/traits/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md index b22900aa..1ed50031 100644 --- a/docs/reference/traits/wiring/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -74,7 +74,7 @@ The trait is in the prelude. You do not name it directly; you assert it through ### Asserting it You assert it through a macro. A [`check_components!`](../../macros/check_components.md) table reduces to one -impl of a private check trait per entry, whose supertrait is this bound, so the impl compiles only if the +impl of a private [check trait](/docs/reference/glossary#check-trait) per entry, whose [supertrait](/docs/reference/glossary#supertrait) is this bound, so the impl compiles only if the bound holds: ```rust diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index 2aaf1bf1..5d626484 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -91,7 +91,7 @@ where The bound is the "get"; `

`](../providers/with_provider.md) | whatever the field-getter provider `P` supplies | -`UseField` is the one to reach for, and the reason the construct exists. `UseFields` is useful when a -trait has several methods and the names all happen to match, and it is the only one of the three that +`UseField` is the one to use, and the reason the construct exists. `UseFields` is useful when a +trait has several methods and the names all happen to match, and it is the only one of them that works for a multi-method trait: the other two presuppose a single field. A `#[cgp_getter]` trait can also be implemented directly on a concrete context, like any Rust trait, when @@ -148,8 +148,8 @@ consumer trait can be implemented like any Rust trait. ## When to use it -**Do not reach for `#[cgp_getter]` by default.** Among the three ways to read a value from a context it is -the last resort, and the ordering is worth holding whole: +**Do not use `#[cgp_getter]` by default.** Among the ways to read a value from a context it is +the last resort, and the ordering is worth keeping whole: 1. **An [`#[implicit]`](../attributes/implicit.md) argument** for a provider reading a field of its own context. No trait, no wiring. This covers most reads. @@ -163,9 +163,9 @@ context**: the same capability reading `first_name` on one type and `display_nam is a context that supplies the value **some way other than a plain field read**, through `WithProvider` or a hand-written impl, while other contexts still read a field. -Reach for something else in these cases. +Use something else in these cases. -- **Every context stores the field under the method's name.** Then the wiring line is pure ceremony: +- **Every context stores the field under the method's name.** Then the wiring line is pure overhead: `#[cgp_auto_getter]` gives the same result with nothing to wire, and wiring `UseFields` here is a sign the component was not needed. - **Only one provider reads the value.** An `#[implicit]` argument is shorter and keeps the requirement diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 71f37efd..c7b87721 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -49,7 +49,7 @@ where ``` The macro performs the rewrite for you. Write providers this way. The macro produces the inside-out -form shown earlier, and you will meet that form in generated code. +form shown earlier, and you will see that form in generated code. This convenience has one exception worth stating plainly: **inside a `#[cgp_impl]` block, `self` and `Self` mean the context, not the provider.** The context is the type the capability runs against, and @@ -152,7 +152,7 @@ a generic provider becomes a tuple struct with one public generic parameters together, always `pub` and never with a default. Anything the struct needs outside that shape has to be written by hand. -The case you meet most often is a default on a higher-order provider's inner parameter, so an +The case you see most often is a default on a higher-order provider's inner parameter, so an application can omit the inner provider and fall back to [`UseContext`](../providers/use_context.md), which routes back through the context's own implementation of the component. If `ScaledAreaCalculator` from [Usage](#usage) should default this @@ -275,7 +275,7 @@ choice worth keeping distinct from the something else. The concrete-context form still produces a named provider that a context wires like any other. The `Self` form produces no provider at all. -Reach for something else in two cases. +Use something else in these cases: - **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain function with no component, no provider, and no wiring, which is the bottom tier of @@ -285,7 +285,7 @@ Reach for something else in two cases. attributes while emitting an ordinary impl. Needing to [declare the provider struct separately](#declaring-the-provider-struct-separately) is not -by itself a reason to drop to [`#[cgp_provider]`](./cgp_provider.md). Reach for the raw form only when +by itself a reason to drop to [`#[cgp_provider]`](./cgp_provider.md). Use the raw form only when you need the inside-out provider-trait shape itself: a bound the sugar cannot express, or a rare construct `#[cgp_impl]`'s rewrite does not support, whether from a limitation or a bug. @@ -319,7 +319,7 @@ impl IsProviderFor for ValueToString pub struct ValueToString; ``` -Three things changed. The trait gained `Context` as its leading argument. The `Self` type became the +A few things changed. The trait gained `Context` as its leading argument. The `Self` type became the provider. `&self` became the explicit parameter `__context__: &Context`. The receiver identifier is the snake-cased context type wrapped in double underscores, so both `Context` and the default `__Context__` become `__context__`. The macro rewrites every `self` in a body to that identifier, and diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 693771de..4858884e 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -88,7 +88,7 @@ is why the two forms in the table above are the ones worth writing, and why the - **`namespace Other;`** is accepted, but inheritance is written with the `: ParentNamespace` header above. That is the form overriding and the cycle diagnostics are defined in terms of. - **A nested table value**, `UseDelegate`, works, and is the one legacy form with a - reason to live in a namespace: the macro lifts the inner table out into its own struct and impls, so + reason to keep in a namespace: the macro lifts the inner table out into its own struct and impls, so every context joining the namespace inherits the per-type dispatch without restating it. It still needs [`#[derive_delegate]`](../attributes/derive_delegate.md) on the component, as it does anywhere. @@ -111,7 +111,7 @@ the one above reroutes a whole subtree of the parent's namespace rather than a s ### The other two halves: registering, and joining -Defining a namespace is only a third of the pattern. A component **registers into** one with the +Defining a namespace is only one part of the pattern. A component **registers into** one with the `#[prefix(...)]` attribute on its trait, which puts that component's lookups under a path: ```rust @@ -135,7 +135,7 @@ delegate_components! { } ``` -A third statement form, `for in SomeTable { … }`, reads each entry of another lookup table and +Another statement form, `for in SomeTable { … }`, reads each entry of another lookup table and emits one mapping per entry, which is how per-type defaults are pulled in wholesale. ## Examples @@ -207,27 +207,27 @@ delegate_components! { ## When to use it -**Reach for a namespace when the same wiring is repeated across contexts, or when a top-level table has -grown too long to read.** Those are the two problems it solves, and below that threshold it costs more than +**Use a namespace when the same wiring is repeated across contexts, or when a top-level table has +grown too long to read.** Those are the problems it solves, and below that threshold it costs more than it saves: a namespace adds a layer of indirection between a component and its provider, which is one more hop for a reader tracing what runs. -Three lighter tools cover most cases, and it is worth knowing where each stops. +A few lighter tools cover most cases, and it is worth knowing where each stops. - **A plain [`delegate_components!`](./delegate_components.md) table** is right while each context's wiring is short and not shared. Most applications never outgrow this. - **The [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement)** is the lightweight special case of the same path machinery, for dispatching *one* component on its type parameter - directly on a context. It needs no namespace, no prefix, and no shared table; reach for it when the goal + directly on a context. It needs no namespace, no prefix, and no shared table; use it when the goal is per-type dispatch rather than shared wiring. - **An [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time)**, the `new`-keyword bundle, packages a group of wirings that contexts adopt by *delegating* named components to it, rather than by joining and inheriting. It is the more direct mechanism and the better choice for a - small, explicitly-delegated bundle. A namespace earns its extra machinery when there are many components, + small, explicitly-delegated bundle. A namespace is worth its extra machinery when there are many components, when inheritance is wanted, or when a library is publishing defaults for applications it does not know about. -Two things a namespace is *not* for. It will not make a single context's wiring shorter on its own; the +A couple of things a namespace is *not* for. It will not make a single context's wiring shorter on its own; the entries still have to exist somewhere. And it is not how one component gets per-type dispatch, which is `open`'s job; the two do not combine on the same component, as the [Common Mistakes](#common-mistakes) explain. @@ -298,7 +298,7 @@ where For any key the parent resolves, the child resolves it to the same value. The child's own entries are emitted after this impl and win where their keys are more specific. -Two naming details appear verbatim in errors and are worth recognizing: the table parameter is literally +A couple of naming details appear verbatim in errors and are worth recognizing: the table parameter is literally `__Table__`, and the inheritance impl uses `__Key__` and `__Value__`. And every `@` path is a [type-level list](../types/path_cons.md) built by [`Path!`](./path.md); `expand` resugars it to `Path!(@…)` form, while a raw compiler error prints the underlying list. @@ -323,7 +323,7 @@ defined on that page rather than restated here. The two a namespace normally use and `:` to a provider. The `:` between `NamespaceName` and `ParentNamespace` is the inheritance colon, distinct from a mapping's. `NamespaceName` becomes both a trait and, with `new`, a struct. -Two of the three statement forms in that shared production exist for this macro, because their job is +Two statement forms in that shared production exist for this macro, because their job is joining a context's table to a namespace. A `NamespaceStmt`, `namespace SomeNamespace;`, forwards every unwired lookup through the named namespace. A `ForStmt`, `for in SomeTable where … { … }`, binds a key variable and a provider variable, reads each @@ -397,7 +397,7 @@ error[E0277]: the trait bound `PathCons>, ...>: AppNam ``` The `Symbol<4, …>` is the prefix, `show`, so the message is saying "this route is not something the -namespace resolves". This is the lazy-wiring problem in namespace clothing, and the answer is the same: check +namespace resolves". This is the lazy-wiring problem in a namespace setting, and the answer is the same: check the context. ## Related constructs diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index a3136b12..0a0dbdb7 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -50,8 +50,8 @@ fn magic_number() -> u64 { Omitted, the provider struct takes the function name in PascalCase: `magic_number` becomes `MagicNumber`. Given, the argument is used verbatim. The function's return type becomes the producer's output. -**The function is constrained tightly, to exactly what a producer can be.** All three restrictions are -enforced at expansion time with their own messages: +**The function is constrained tightly, to exactly what a producer can be.** Each restriction is +enforced at expansion time with its own message: | Restriction | Why | |---|---| @@ -59,8 +59,8 @@ enforced at expansion time with their own messages: | Not `async` | The producer trait is synchronous. | | No generic parameters | There is nothing to infer them from. | -That third restriction is the one most likely to bite, and it is the sharpest difference from -[`#[cgp_computer]`](./cgp_computer.md), which carries generics through happily. A producer has no input, so a +That last restriction is the one most likely to cause trouble, and it is the biggest difference from +[`#[cgp_computer]`](./cgp_computer.md), which carries generics through fine. A producer has no input, so a type parameter would be determined by nothing at all. ## Examples @@ -113,7 +113,7 @@ delegate_components! { ## When to use it -**Reach for `#[cgp_producer]` when a pipeline step needs no input.** That is the whole of its remit, and +**Use `#[cgp_producer]` when a pipeline step needs no input.** That is all it is for, and within it there is nothing simpler. - **Use [`#[cgp_computer]`](./cgp_computer.md) as soon as there is an input**, even a trivial one. It is the @@ -126,7 +126,7 @@ within it there is nothing simpler. producers**, which makes this macro narrower than it first looks: it is for constants and pure seeds. - **Use [`ReturnInput`](../providers/handler/return_input.md) rather than a producer that ignores its input.** If the goal is to pass a value through a pipeline unchanged, that combinator says so directly. -- **Do not reach for the handler family at all for a plain constant.** A `const` or a function is clearer +- **Do not use the handler family at all for a plain constant.** A `const` or a function is clearer unless the value is being composed into a pipeline or dispatched on a `Code` tag. ## Under the hood @@ -158,7 +158,7 @@ impl<__Context__, __Code__> Producer<__Context__, __Code__> for MagicNumber { [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl, whose parameter tuple here holds just the code tag. The context and code parameters carry the reserved names `__Context__` and `__Code__`. -Then the wiring, which reaches **all eight** other components: +Then the wiring, which reaches **all the other** components: ```rust delegate_components! { @@ -178,7 +178,7 @@ delegate_components! { } ``` -Two things differ from `#[cgp_computer]`'s block. `ComputerComponent` **is** in the list, because a producer +A couple of things differ from `#[cgp_computer]`'s block. `ComputerComponent` **is** in the list, because a producer does not implement it directly. A computer takes an input and the producer has none, so the promotion discards it. And the operator is **`:`** rather than `->`, delegating each component straight to [`PromoteProducer`](../providers/handler/promote_producer.md) rather than to that bundle's own entry for the @@ -206,7 +206,7 @@ verbatim. The annotated function is plain Rust, constrained to a producer's shap ## Common Mistakes -**All three shape restrictions have their own message**, so the macro tells you which one you broke: +**Each shape restriction has its own message**, so the macro tells you which one you broke: ```text error: Producer functions cannot have parameters @@ -221,7 +221,7 @@ is no macro alternative: write the provider by hand. expressible this way at all. That rules out most real producers, which is worth knowing before reaching for the macro: write an impl of `Producer` with [`#[cgp_impl]`](./cgp_impl.md) instead. -**A `Result` return is not interpreted**, and this is the sharpest trap on the page. Unlike +**A `Result` return is not interpreted**, and this is the most confusing case on the page. Unlike `#[cgp_computer]`, the macro does not inspect the output for fallibility, so a `#[cgp_producer]` returning `Result` produces a `Producer` whose `Output` *is* that `Result`, and the fallible members wrap it again rather than treating it as failure: diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 1a8daabf..9fba5f06 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -100,8 +100,8 @@ pub struct RectangleArea; pub struct SpawnAndRun(pub ::core::marker::PhantomData); ``` -This is also the limit of what the attribute form can express, and the reason `#[cgp_provider]` still -has a job. A struct that needs a **default** generic parameter has to be written by hand, and so does +This is also the limit of what the attribute form can express, and the reason `#[cgp_provider]` is +still needed. A struct that needs a **default** generic parameter has to be written by hand, and so does one shared by several impls. The common shape is `pub struct IterSum(PhantomData);`, which a higher-order provider uses so it can fall back to the context's own wiring. @@ -190,7 +190,7 @@ the source. source that reads like an ordinary trait impl, so it is the recommended form. You mostly *read* these two instead: in generated code, in a desugaring, and in CGP's own crates. -Two cases call for writing the raw form yourself. +A couple of cases call for writing the raw form yourself: - **You need the inside-out provider-trait shape itself**, not merely a separately-declared struct: a bound `#[cgp_impl]`'s sugar cannot express, or a rare construct its rewrite does not support, whether @@ -241,7 +241,7 @@ where The derived impl is your impl with the body and associated types removed and the trait swapped. It keeps the same generic parameters and the same bounds, so it holds under precisely the conditions the -real impl holds. This is the whole point: a check evaluates +real impl holds. This is the reason for it: a check evaluates [`IsProviderFor`](../traits/wiring/is_provider_for.md) to find out *why* a provider does not apply. The macro assembles its three trait arguments from the provider trait's own. The first is the @@ -250,7 +250,7 @@ attribute argument said). The second is the **context**. The third is a **tuple over**: `(Code, Input)` here, and the empty `()` for a provider trait that takes nothing but a context. -Two rules decide that split, and they only become visible on a provider trait that carries a +A couple of rules decide that split, and they only become visible on a provider trait that carries a [lifetime](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html). The context is the first *type* argument rather than the first argument, because Rust puts lifetime arguments first and a lifetime cannot be a context. And the macro lifts a lifetime into [`Life<'a>`](../types/life.md) to @@ -291,7 +291,7 @@ described [above](#the-struct-cgp_new_provider-declares). ### Input the macros refuse -Both macros reject four shapes at expansion, rather than lowering them into code that fails later. An +Both macros reject several shapes at expansion, rather than lowering them into code that fails later. An **inherent impl**, with no trait, has no provider trait to read the component and context from. A **provider trait with no type argument** leaves nothing to be the context. A **const argument** in the provider trait's argument list has nowhere to live in the type-only params tuple. This is about the diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index d36ab750..503e4122 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -31,11 +31,11 @@ delegate_components! { } ``` -That is the payoff: `App` now implements `HasScalarType` with `Scalar = f64`, and no provider was written +That is the benefit: `App` now implements `HasScalarType` with `Scalar = f64`, and no provider was written anywhere. The arrangement mirrors what [`#[cgp_getter]`](./cgp_getter.md) does for values: one general-purpose provider, parameterized by the thing the context wants to supply. -Two consequences are worth having early. Because the type is chosen per context, two applications can +A couple of consequences are worth knowing early. Because the type is chosen per context, two applications can pick differently from the same generic code. And because the trait is an ordinary Rust trait, a context can skip the wiring entirely and write `impl HasScalarType for App { type Scalar = f64; }`, barely longer, and the clearest way to see that nothing unusual is happening. @@ -150,26 +150,26 @@ impl HasScalarType for App { ## When to use it -**Reach for `#[cgp_type]` whenever generic code has to name a type the context should choose.** The error +**Use `#[cgp_type]` whenever generic code has to name a type the context should choose.** The error type is the canonical instance. CGP's own [`HasErrorType`](../components/has_error_type.md) is defined exactly this way, which is why every fallible capability can say `Error` and mean whatever the application picked. The decision worth making deliberately is **whether the type needs to be abstract at all**, because -there is a cheaper option covering more ground than it looks. +there is a cheaper option that does more than it looks. - **Prefer an inferred impl parameter while the type only flows through values.** If the type appears solely because a provider reads a field of it, [`#[impl_generics]`](./cgp_fn.md#a-type-the-caller-should-not-name) on a `#[cgp_fn]` puts a parameter on the implementation alone. Nothing is wired, nothing is declared, and a context qualifies just by carrying a field of a compatible type. -- **Climb to an abstract type when the type must be nameable.** Two things force it: the capability's own +- **Move up to an abstract type when the type must be nameable.** Two things force it: the capability's own signature has to mention the type, or two capabilities have to agree they mean the *same* type. An inferred parameter can do neither, since it exists only where a value of it passes through. - **Never thread it as a generic parameter on the capability.** A parameter is an input the caller supplies, so it lands in every intermediate signature whether that layer touches the type or not. An abstract type is determined by the context and propagates nowhere. That difference is the whole - payoff of the construct, and it is why a context can decide a dozen types without any signature + benefit of the construct, and it is why a context can decide many types without any signature growing. - **Use plain [`#[cgp_component]`](./cgp_component.md) when the trait carries methods.** `#[cgp_type]` is only for a trait whose entire content is one associated type. A trait with a method *and* a type it @@ -196,7 +196,7 @@ pub trait ScalarTypeProvider<__Context__>: } ``` -The first addition is the **`UseType` impl**, and it is the heart of the macro. It implements the provider +The first addition is the **`UseType` impl**, and it is the core of the macro. It implements the provider trait for `UseType` by setting the abstract type to the generic parameter: ```rust diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 05ab7f8b..7157eeef 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -33,12 +33,12 @@ check_components! { That block has no runtime existence. It compiles if `Person` really can use the component and fails if it cannot, at the wiring site rather than wherever the capability first gets called. -The second thing it buys is a *readable* failure, and that is the part worth understanding. Asking the +The other thing it gives you is a *readable* failure, and that is the part worth understanding. Asking the obvious question, "does `Person` implement `CanGreet`?", makes the compiler report only the last link in the chain, typically that some provider does not implement its provider trait, with no word about why. The macro instead routes the assertion through [`CanUseComponent`](../traits/wiring/can_use_component.md), which holds only when the context both delegates the component *and* the chosen provider's real bounds are satisfied. -Because those bounds ride explicitly on a marker trait, the compiler evaluates them and names the one that +Because those bounds are carried explicitly on a marker trait, the compiler evaluates them and names the one that failed. A missing `name` field surfaces as a missing `name` field, not as an opaque "trait not implemented". @@ -243,7 +243,7 @@ impl __CheckPerson for Person {} The impl holds only if `Person: CanUseComponent`, which in turn requires that `Person` delegates the component and that its delegate satisfies [`IsProviderFor`](../traits/wiring/is_provider_for.md) for -`Person`. That indirection is the entire point: because the marker carries the provider's real bounds, an +`Person`. That indirection is the whole reason for it: because the marker carries the provider's real bounds, an unmet one is reported specifically rather than as a bare missing implementation. The generic parameters are literally `__Component__` and `__Params__` in the emitted code. @@ -317,7 +317,7 @@ and any other attribute is rejected by name rather than ignored. `#[check_trait( which is merged with the table's before the impl is emitted. `Generics`, `WhereClause`, and `Type` are Rust grammar productions. -Both bracketed lists accept **zero** elements, and the two empty forms behave differently. An empty value +Both bracketed lists accept **zero** elements, and the empty forms behave differently. An empty value list, `FooComponent: []`, falls back to the no-parameter check, exactly as omitting the colon would. An empty *key* list, `[]: Rectangle`, produces no entries at all, so the line silently checks nothing; there is no diagnostic, and it is worth a second look if a table appears to pass without doing anything. diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index fdf6ea89..2a708f5a 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -31,7 +31,7 @@ Every entry is wired *and* proven, in one place, with nothing to keep in sync. I writing both macros by hand would emit. **It is aimed at simple wiring and at getting started, not at being the default everywhere.** Its value is -that a newcomer cannot forget the check and then meet the confusing errors lazy wiring produces. The +that a newcomer cannot forget the check and then run into the confusing errors lazy wiring produces. The derivation understands only a mapping keyed on a component *name*, though, so a codebase whose wiring grows past that keeps the two macros separate. The reasons are in [When to use it](#when-to-use-it). @@ -224,17 +224,17 @@ check_components! { } ``` -That pairing is the usual reason to reach for `#[skip_check]`: the fused derivation can only check the +That pairing is the usual reason to use `#[skip_check]`: the fused derivation can only check the context, and a nested stack is better checked per layer. ## When to use it -**Reach for it while getting started, and for tables that are plain `Component: Provider` entries.** It is +**Use it while getting started, and for tables that are plain `Component: Provider` entries.** It is the form that makes forgetting a check impossible, which is worth more than the control it gives up when the wiring is simple. **Keep the two macros separate once the wiring is not simple.** The derivation reads delegation keys, so -there are three things it cannot do, and each is a reason a larger codebase writes +there are a few things it cannot do, and each is a reason a larger codebase writes [`delegate_components!`](./delegate_components.md) and [`check_components!`](./check_components.md) apart: - **Per-layer checks.** Only a standalone block can use `#[check_providers(...)]`, which localizes a @@ -331,7 +331,7 @@ TableAttr -> `#` `[` `check_trait` `(` IDENTIFIER `)` `]` TableBody -> Statement* ( CheckedMapping ( `,` CheckedMapping )* `,`? )? CheckedMapping -> EntryAttr? Mapping // Mapping, Key, ProviderValue, Statement - // — see delegate_components! + // see delegate_components! EntryAttr -> `#` `[` `check_params` `(` Type ( `,` Type )* `,`? `)` `]` | `#` `[` `skip_check` `]` @@ -368,8 +368,8 @@ error: Expected at most one `#[check_params]` or `#[skip_check]` attribute **A generic component without `#[check_params(...)]` cannot be checked, and the error does not say so.** The delegation succeeds; the derived check is emitted with an empty parameter tuple, which a component expecting a -type parameter can never satisfy. What surfaces is an ordinary unsatisfied-marker complaint against the -provider: +type parameter can never satisfy. An ordinary unsatisfied-marker complaint against the +provider surfaces instead: ```text error[E0277]: the trait bound `RectArea: IsProviderFor` is not satisfied diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index ea8ad4ca..99721649 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -42,9 +42,9 @@ error instead of a dead end. [Under the hood](#under-the-hood) shows both. ## Usage The macro takes a target type and a brace-delimited body. The body holds any number of **statements** -followed by any number of **mappings**, and a mapping is a **key**, an **operator**, and a **value**: -three choices you make independently. There are three operators, three key forms, two value forms, and -three statements, and this section takes them in that order. +followed by any number of **mappings**, and a mapping is a **key**, an **operator**, and a **value**, +chosen independently. This section covers the operators, the key forms, the value forms, and the +statements, in that order. **Every one of these forms combines with the others inside a single block.** A table routinely opens a component for per-type dispatch, joins a namespace, and still maps plain component names to providers @@ -183,7 +183,7 @@ redirect: the per-value slots an `open` statement opens, or the prefixed routes becomes a type-level string, and anything else names a type. A segment may also carry generics, as in `@SomeComponent.<'a, T> &'a T: SomeProvider`. -Two grouping forms fan one path key out into several, and **they are not interchangeable**: +A couple of grouping forms expand one path key into several, and **they are not interchangeable**: - **`[…]` groups alternatives for one segment**, and the path may continue after it. `@app.[AreaCalculatorComponent, PerimeterCalculatorComponent].[u64, String]: RectangleGeometry` @@ -214,11 +214,11 @@ exists, and it is legacy. :::info -### Legacy — read, don't write +### Legacy: read, don't write Older code dispatches per type by nesting a table inside a [`UseDelegate`](../providers/use_delegate.md) value instead of using the `open` statement below. **Prefer `open` for anything new**: it needs no -separate table type and no wrapper. This form is here because you will meet it in existing code, +separate table type and no wrapper. This form is here because you will see it in existing code, including in CGP's own error and handler components, which are still defined this way. ::: @@ -237,7 +237,7 @@ delegate_components! { } ``` -Three details of the form are easy to miss. The inner braces hold a **full table body**, so an inner +A few details of the form are easy to miss. The inner braces hold a **full table body**, so an inner table accepts everything an outer one does, nesting included. The **wrapper is not fixed to `UseDelegate`**: any single-parameter wrapper type is accepted, which is how a component dispatched on a tuple of parameters gets wired to a matching `UseDelegate2`. And the **inner table's name may carry @@ -288,7 +288,7 @@ the component carries a `#[prefix(...)]`. ### The namespace statements -Two further statements opt a context into a [`cgp_namespace!`](./cgp_namespace.md), and both are +A couple of further statements opt a context into a [`cgp_namespace!`](./cgp_namespace.md), and both are described in full on that page, where they are most often written. **`namespace SomeNamespace;`** joins the namespace, so every lookup the table does not wire directly @@ -366,7 +366,7 @@ fn print_area(rect: &Rectangle) { } ``` -The payoff shows up when a second context wants the same capability answered differently. It +The benefit shows up when a second context wants the same capability answered differently. It writes its own provider and its own table entry, and no code that calls `area()` changes: ```rust @@ -432,9 +432,9 @@ compiles, and the failure only surfaces later, where the capability is used. question: it either passes vacuously or blames the bundle for requirements a real context would have met. Verify it through a context that delegates to it instead. -Two choices inside the table are worth naming as well. Prefer the **`open` statement** over the legacy +A couple of choices inside the table are worth naming as well. Prefer the **`open` statement** over the legacy nested `UseDelegate` table for per-type dispatch: it needs no separate table type and no wrapper. And -reach for a **[namespace](./cgp_namespace.md)** rather than a longer table once the same wiring is +use a **[namespace](./cgp_namespace.md)** rather than a longer table once the same wiring is repeated across contexts, or once one table has grown too long to read. Below that threshold, the extra hop costs more than it saves. @@ -473,7 +473,7 @@ the `where` bounds it needs, so an unsatisfied requirement flows back through th the point of use. Note that these parameters are literally named `__Context__` and `__Params__` in the emitted code. -**Every other form on this page lowers to that same pair.** What a form changes is how many pairs one +**Every other form on this page lowers to that same pair.** A form changes only how many pairs one line produces and what the `Delegate` type is. **A list key repeats the pair per name.** A table pairing @@ -546,7 +546,7 @@ keys of different lengths. `delegate_components!` blocks, the inner one carrying `new`. Its per-value entries key on the same parameter `open` keys on; the difference is only that they live in a separate table type. -**The two namespace statements** share one lowering: an impl generic over a `__Key__` and a `__Value__`, +**The namespace statements** share one lowering: an impl generic over a `__Key__` and a `__Value__`, bounded on the namespace trait with a `Delegate = __Value__` binding. This makes the namespace's answer the context's answer. A bare `namespace DefaultNamespace;` produces the blanket form: @@ -614,12 +614,12 @@ struct. The operator choice is independent of the key form: `:` maps a key to a to the value's own entry for that key, and `=>` redirects along a path. `NormalMapping` is named separately because a `ForStmt` body admits only that form. -The two grouping forms inside a `PathHead` differ in what they group and in whether the path may +The grouping forms inside a `PathHead` differ in what they group and in whether the path may continue. A bracketed group holds alternative segments for one position and may be followed by `.` and more path; a braced group holds alternative whole remainders and terminates the path, which is why only -the braced form can nest. Both fan out to the cartesian product with the rest of the path. +the braced form can nest. Both expand to the cartesian product with the rest of the path. -The three segment productions differ in what they permit, which is why they are named apart. A +The segment productions differ in what they permit, which is why they are named apart. A `KeySegment` (inside a `PathKey`) may carry its own generic list, and the parameters of every segment along one path are merged onto that entry's impls. A `PathSegment` (inside a `PathValue`, the right-hand side of a `=>`) carries none, and admits no groups. It is [`Path!`](./path.md)'s own diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md index 36adc7e7..0363a363 100644 --- a/docs/reference/macros/index.md +++ b/docs/reference/macros/index.md @@ -5,14 +5,14 @@ sidebar_position: 0 # Macros -CGP's procedural macros fall into three jobs: defining a component and writing the providers that +CGP's procedural macros cover a few kinds of work: defining a component and writing the providers that implement it, wiring a concrete type to the providers it uses and checking that wiring holds, and building the type-level values (strings, lists, paths) that the rest of the system runs on. This -page groups every macro in this section by which of the three it does, in roughly the order most CGP -code reaches for them. +page groups every macro in this section by the kind of work it does, in roughly the order most CGP +code uses them. If you are new to CGP, start with the [reference overview](/docs/reference/)'s six essentials rather -than here; this page is the fuller map for once those six are familiar. +than here; this page is the fuller reference for once those six are familiar. ## Defining a component, and writing its providers @@ -29,13 +29,13 @@ When a capability has exactly one implementation and needs no wiring at all, supertrait dependencies. [`#[async_trait]`](./async_trait.md) is how any of these traits declares an `async fn` without tripping the lint a bare one produces. -Three macros specialize `#[cgp_component]` for a narrower job. [`#[cgp_type]`](./cgp_type.md) is for a +A few macros specialize `#[cgp_component]` for a narrower job. [`#[cgp_type]`](./cgp_type.md) is for a component that supplies a type a context chooses rather than a value it computes. [`#[cgp_auto_getter]`](./cgp_auto_getter.md) publishes a context field as a named accessor with a blanket impl and no wiring, and [`#[cgp_getter]`](./cgp_getter.md) is its wireable counterpart, for the rarer case where a context needs to choose which field a getter reads. -Three more build a provider from a plain function for CGP's computation family. +Others build a provider from a plain function for CGP's computation family. [`#[cgp_computer]`](./cgp_computer.md) and [`#[cgp_producer]`](./cgp_producer.md) wire one function to answer every member of that family at once, synchronous, async, fallible, and infallible alike, and [`#[cgp_auto_dispatch]`](./cgp_auto_dispatch.md) generates a handler that routes an extensible-data @@ -58,7 +58,7 @@ presets without a separate construct for them. [`Product!`](./product.md) and its value-level twin `product!` build a type-level list for a struct's fields or a handler pipeline's steps, [`Sum!`](./sum.md) builds the dual list for an enum's variants, and [`Path!`](./path.md) builds the routing list that namespaces and redirected lookups resolve -against. All four are mostly generated for you, by a derive, by the ergonomic macros above, or by the -`open` statement inside `delegate_components!`, and the skill worth having is reading one back out of +against. All of them are mostly generated for you, by a derive, by the ergonomic macros above, or by the +`open` statement inside `delegate_components!`, and the useful skill is reading one back out of a compiler error rather than writing it, since a diagnostic actually prints the raw list each expands to (`Cons`/`Nil`, `Either`/`Void`, `PathCons`). diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 63ec72bc..10824eb4 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -114,7 +114,7 @@ different things. ## When to use it -**Write the `@`-path syntax wherever a namespace or a wiring key asks for a route**, and reach for the bare +**Write the `@`-path syntax wherever a namespace or a wiring key asks for a route**, and use the bare `Path!` macro only when a route needs to be a named type on its own, which is rare. - **Prefer the embedded form.** A namespace entry, a `#[prefix]`, or an `@`-path wiring key is where a route @@ -122,7 +122,7 @@ different things. usually makes the wiring harder to follow rather than easier. - **Never hand-write the list.** The macro expands to `PathCons>`, and writing it out is longer and identical in meaning. -- **Reach for the [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement) +- **Use the [`open` statement](./delegate_components.md#choosing-a-provider-per-type-the-open-statement) rather than constructing paths yourself** when the goal is per-type dispatch on one component. `open` builds the route for you, and its `@Component.Key` entries are the paths: you write the keys, not the routing. - **Do not use `Path!` as a general type-level list.** [`Product!`](./product.md) is the list for a sequence of @@ -138,7 +138,7 @@ lowercase-versus-capitalized rule: // before Path!(@app.error.ErrorRaiserComponent) -// after — readable form +// after (readable form) PathCons< Symbol!("app"), PathCons< diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index ad9b0660..12a7accc 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -109,7 +109,7 @@ a provider list. Everywhere else it is generated for you. [`Sum!`](./sum.md)'s list. - **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for a struct's shape** rather than declaring the list yourself. Writing it by hand means restating the struct, and the two will disagree eventually. -- **Use a tuple when nothing generic consumes it.** A `Product!` earns its keep only where code recurses over +- **Use a tuple when nothing generic consumes it.** A `Product!` is worth using only where code recurses over the list; for a fixed group of values passed between known functions, a tuple or a struct is clearer and needs no machinery. - **Use [`Sum!`](./sum.md) for a choice rather than a collection.** `Product!` holds a value for *every* diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 4d0aa631..fe784929 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -13,7 +13,7 @@ A type-level sum, the dual of `Product!`. of an **enum**, the list of its variants, the way [`Product!`](./product.md) describes the fields of a struct. -The pairing is exact and worth holding onto. A `Product!` holds a value for **every** element at once, which is +The pairing is exact and worth remembering. A `Product!` holds a value for **every** element at once, which is a record. A `Sum!` holds a value for exactly **one** element, which is a tagged union: ```rust @@ -71,7 +71,7 @@ pub enum Shape { // } ``` -Two things to notice. The variant names are [`Symbol!`](./symbol.md) type-level strings, exactly as field names +A couple of things to notice. The variant names are [`Symbol!`](./symbol.md) type-level strings, exactly as field names are. And a struct-like variant nests a [`Product!`](./product.md) of its own fields, so an enum's full shape is a sum of variants whose payloads may themselves be records. Generic code walks the `Sum!` to find which variant a value holds, then walks the nested `Product!` to reach that variant's fields. @@ -95,7 +95,7 @@ use. longer and identical in meaning. - **Use [`Product!`](./product.md) for a collection rather than a choice.** They are duals: every element versus exactly one. A type error is the usual consequence of confusing them, which is at least loud. -- **Use a plain `enum` and `match` when the variant set is closed and known.** The machinery earns its keep +- **Use a plain `enum` and `match` when the variant set is closed and known.** The machinery is worth using when independent code has to handle variants it did not define, or when the variant set is open. For a fixed enum consumed in one place, a `match` is clearer and free. diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index fc442af7..d16aa11e 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -125,12 +125,12 @@ That is the honest summary: the construct is essential and mostly generated. - **Use an [`#[implicit]`](../attributes/implicit.md) argument to read a field.** The parameter's name becomes the tag, so you never type one. - **Use [`#[cgp_auto_getter]`](./cgp_auto_getter.md) for a named accessor.** The method name becomes the tag. -- **Write `Symbol!` explicitly with [`UseField`](../providers/use_field.md)**, where the whole point is that +- **Write `Symbol!` explicitly with [`UseField`](../providers/use_field.md)**, where the reason for it is that the field name is a wiring decision rather than fixed to a method name. This is its main hand-written use. - **Use [`Index`](../types/index_type.md) for a tuple field**, not a `Symbol!` of `"0"`. They are different types and the derive generates the former. -Two things it is not. It is **not a runtime string**: there is no `&str` inside it, and the `Display` impl +A couple of things it is not. It is **not a runtime string**: there is no `&str` inside it, and the `Display` impl above reconstructs the text from the type rather than reading a stored value. And it is **not a general type-level string facility** to build programs out of; it exists to key field and variant lookups, and the [`StaticFormat`](../traits/formatting/static_format.md) traits recover text from one when that is @@ -171,7 +171,7 @@ through the list. The expansion is built by folding the characters right to left onto `Nil` and wrapping the result, so the empty string `Symbol!("")` becomes `Symbol<0, Nil>`. -**What this means for reading errors** is the practical payoff. A missing field on a context is reported +**What this means for reading errors** is the practical benefit. A missing field on a context is reported against the expanded tag, so an error mentioning `HasField>>>` is telling you the field `width` is missing. Counting the characters is enough to decode it, and `cargo cgp check` resugars the common cases. From 27911125afbf4b0e5e18f263521e007066bc4f6d Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 19:46:00 +0200 Subject: [PATCH 059/516] docs(reference/macros): point-first revision of the four core macro pages Revise the prose of cgp_component, cgp_impl, cgp_fn, and delegate_components without changing any code block, table, or technical claim. - Lead each paragraph with its point and name the real actor (the macro, the compiler, the parser) instead of an unnamed passive. - Remove pseudo-clefts, flat "no [noun]" negations, idioms and figures of speech ("inside-out", "sugar falls short", "dead end"). - Drop ordinal counting in the cgp_component expansion walkthrough and the counts in the delegate_components subsection headings. - Split multi-point sentences and semicolon joins; turn the cgp_fn attribute-placement paragraph into a framed list. - Fix small inaccuracies: "each key has a default" beside a required key, "every example omits for Context", the contradictory "same headline" note on E0425/E0433, and the claim that a cgp_fn keeps working unchanged when a second implementation arrives. - Point the #[default_impl] links at its attribute page. Co-Authored-By: Claude Fable 5.1 --- docs/reference/macros/cgp_component.md | 255 +++++++++---------- docs/reference/macros/cgp_fn.md | 153 +++++------ docs/reference/macros/cgp_impl.md | 150 +++++------ docs/reference/macros/delegate_components.md | 245 +++++++++--------- 4 files changed, 403 insertions(+), 400 deletions(-) diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 7129d237..3a513abd 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -10,48 +10,47 @@ target, and the key that wires them together. ## Overview -`#[cgp_component]` can be applied to any Rust trait definition to give that trait the full set of -CGP's capabilities. Applying it takes nothing away: the trait you wrote keeps working exactly as it +You can apply `#[cgp_component]` to any Rust trait definition to give that trait the full set of +CGP's capabilities. Applying it takes nothing away. The trait you wrote keeps working exactly as it did, now under the name CGP calls the **consumer trait**, and every call site that already uses it keeps compiling unchanged. The macro adds a matching **provider trait** for implementations to target, a small marker type called the **component** that names the capability for wiring, and a pair of [**blanket implementations**](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) -that connect the three without requiring you to write them. +that connect them without requiring you to write anything. `#[cgp_component]` makes it possible to define several overlapping implementations of one capability at once. An ordinary Rust trait does not allow this. A [trait](https://doc.rust-lang.org/book/ch10-02-traits.html) can have only one implementation per -type, a rule called [coherence](/docs/concepts/coherence). That rule is usually the right one: it lets -the compiler resolve a `where T: Display` bound without anyone naming which implementation applies. -But it also means a capability with several plausible implementations has nowhere to put the -alternatives. A type can send real email or record it for a test, never both at once, and switching +type, a rule called [coherence](/docs/concepts/coherence). That rule is usually the right one, because +it lets the compiler resolve a `where T: Display` bound without anyone naming which implementation +applies. But it also means a capability with several plausible implementations cannot hold the +alternatives. A type can send real email or record it for a test, but never both at once. Switching between the two means editing the impl itself rather than choosing between them at the point of use. -`#[cgp_component]` solves that by splitting the one trait into two: the -[consumer and provider traits](/docs/concepts/consumer-and-provider-traits), so that *using* a -capability and *implementing* it stop being the same act. +`#[cgp_component]` solves that by splitting the one trait into two, the +[consumer and provider traits](/docs/concepts/consumer-and-provider-traits), so that a caller and an +implementation no longer target the same trait. -- The **consumer trait** is the trait callers write, such as `rect.area()`. It is your original - trait, kept exactly as you wrote it. +- The **consumer trait** is the trait callers use, as in `rect.area()`. It is your original trait, + kept exactly as you wrote it. - An implementation targets the **provider trait** instead. It repeats the same methods with `Self` - moved into an explicit type parameter, so you write an implementation for a small named type of its - own rather than for the type the capability is actually about. - -Moving `Self` out of the way lets more than one implementation coexist: each one now targets its own -small type instead of competing for the single `Self` slot every plain trait has. A **provider** is -one of those targets: a zero-sized type such as `RectangleArea` that carries no data of its own and -exists only to name one implementation. The type the capability actually runs against is called the -**context**. It supplies whatever values an implementation needs as its own fields, then picks the -provider it wants through [`delegate_components!`](./delegate_components.md), and the generated -blanket implementations route a call on the consumer trait through to that choice automatically. None -of this costs anything at runtime. Wiring fixes the provider once, at compile time, and the compiler -turns the call into a direct, statically-dispatched call, exactly as if you had written the -implementation yourself. - -The macro's last piece is the **component** itself, a marker type such as `AreaCalculatorComponent` -that names the capability and is the key `delegate_components!` wires against. You see it in -every wiring entry and in most compiler errors that involve this capability, so you should be able to -recognize it at once, even though you never write its definition yourself. + moved into an explicit type parameter. So you write an implementation for a small named type of its + own, rather than for the type the capability is about. + +Moving `Self` into a parameter lets more than one implementation coexist, because each one now targets +its own small type instead of the single `Self` slot every plain trait has. A **provider** is one of +those targets: a zero-sized type such as `RectangleArea` without data of its own that exists only +to name one implementation. The type the capability runs against is called the **context**. It +supplies whatever values an implementation needs as its own fields, and it picks the provider it wants +through [`delegate_components!`](./delegate_components.md). The generated blanket implementations then +route a call on the consumer trait through to that choice automatically. This costs nothing at +runtime. Wiring fixes the provider once, at compile time, and the compiler turns the call into a +direct, statically-dispatched call, exactly as if you had written the implementation yourself. + +The macro's remaining output is the **component** itself, a marker type such as +`AreaCalculatorComponent` that names the capability and is the key `delegate_components!` wires +against. You see it in every wiring entry and in most compiler errors that involve this capability, so +learn to recognize it, even though you never write its definition yourself. ## Usage @@ -65,9 +64,9 @@ pub trait CanCalculateArea { } ``` -`CanCalculateArea` is the consumer trait and `AreaCalculator` is the provider trait. The naming -convention is worth following: a consumer trait reads as a verb (`CanDoSomething`) and a provider trait -as a noun (`SomethingDoer`, or `…Provider` when no noun fits). +`CanCalculateArea` is the consumer trait and `AreaCalculator` is the provider trait. Follow the naming +convention: a consumer trait reads as a verb (`CanDoSomething`) and a provider trait as a noun +(`SomethingDoer`, or `…Provider` when a noun does not fit). When you need more control, the macro accepts a key/value form instead: @@ -82,8 +81,8 @@ pub trait CanCalculateArea { } ``` -Each key has a default and only `provider` is required. Passing a bare identifier is shorthand for -setting it alone. +Only `provider` is required, and the other keys have defaults. Passing a bare identifier is shorthand +for setting `provider` alone. | Key | What it sets | Default | |---|---|---| @@ -96,9 +95,9 @@ own. ### Companion attributes -Four attributes may be written above the trait, beside `#[cgp_component]`, and each changes what the -macro generates. Any of them may be repeated, and the first three also accept a comma-separated list -inside one attribute. +The attributes below may be written above the trait, beside `#[cgp_component]`, and each changes what +the macro generates. Any of them may be repeated, and all except `#[prefix]` also accept a +comma-separated list inside one attribute. | Attribute | What it adds | |---|---| @@ -119,27 +118,25 @@ pub trait CanLoad { } ``` -One form of `#[use_type]` is refused here. The equality form -`#[use_type(HasScalarType.{Scalar = f64})]`, which pins an imported type to a concrete one, belongs to -a provider that has decided the type rather than to the definition every provider has to satisfy, so -the macro rejects it with *Type equality constraints cannot be used in component trait definition*. +The macro refuses one form of `#[use_type]` here. The equality form +`#[use_type(HasScalarType.{Scalar = f64})]` pins an imported type to a concrete one. That decision +belongs to a provider that has chosen the type, not to the definition every provider has to satisfy, +so the macro rejects it with *Type equality constraints cannot be used in component trait definition*. Every other form of the attribute works on a component exactly as it does elsewhere. -For a supertrait with no associated type to import, use `#[extend(...)]` in preference to native -`: Supertrait` syntax. `#[extend(HasName)]` reads as importing a capability, while -`pub trait CanGreet: HasName` reads as inheritance, which is not what a CGP supertrait is. An -associated type the trait declares *itself* is not imported and stays written as `Self::Output`. +For a supertrait without an associated type to import, use `#[extend(...)]` in preference to native +`: Supertrait` syntax. `#[extend(HasName)]` reads as importing a capability, whereas +`pub trait CanGreet: HasName` reads as inheritance, which a CGP supertrait is not. An associated type +the trait declares *itself* is not imported and stays written as `Self::Output`. -`#[derive_delegate(...)]` is superseded by the `open` statement of -[`delegate_components!`](./delegate_components.md) and is mostly something you read in existing code -rather than write. +The `open` statement of [`delegate_components!`](./delegate_components.md) supersedes +`#[derive_delegate(...)]`, so you mostly read it in existing code rather than write it. -A few attributes that look like they belong here do not, and the error is confusing enough to be worth -naming: `#[uses(...)]`, `#[extend_where(...)]`, and `#[use_provider(...)]` are read by -[`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_fn]`](./cgp_fn.md) but not by `#[cgp_component]`. None of -them is an attribute in its own right, so writing one here leaves a name nothing can resolve; see -[Common Mistakes](#common-mistakes). The equivalent of `#[uses]` on a component is a supertrait, written with -`#[extend]`. +`#[uses(...)]`, `#[extend_where(...)]`, and `#[use_provider(...)]` look like they belong here, but +only [`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_fn]`](./cgp_fn.md) read them. None of them is an +attribute in its own right, so writing one above a component leaves a name nothing can resolve, and +the error is confusing; see [Common Mistakes](#common-mistakes). The equivalent of `#[uses]` on a +component is a supertrait, written with `#[extend]`. ## Examples @@ -185,45 +182,46 @@ does, and nothing else in the program changes. ## When to use it Use `#[cgp_component]` when a capability needs **more than one implementation, and the -choice belongs to the type using it.** That is the case it exists for, and its machinery is not free: -a component is a trait, a second trait, a marker type, and a line of wiring per type. +choice belongs to the type using it.** The macro exists for that case, and it has a cost: a component +is a trait, a second trait, a marker type, and a line of wiring per type. Prefer something simpler when you can. - **One implementation, ever.** Use [`#[cgp_fn]`](./cgp_fn.md) instead. It builds the capability - straight from a function, needs no wiring at all, and keeps working unchanged if a second - implementation ever arrives, which makes it the right starting point rather than a lesser one. + straight from a function and does not need wiring. If a second implementation ever arrives, you + promote it to a component and its call sites keep working unchanged. That makes it the right + starting point rather than a lesser one. - **One implementation per type, chosen globally.** A plain Rust trait already does this well. Use a component when two *different* applications must make different choices for the same type, or when the implementations must overlap in a way the compiler rejects. - **A closed set of variants with fixed operations.** An `enum` and a `match` are clearer than any machinery. -There is also a finer line worth knowing: a capability may need several implementations -while each individual implementation serves exactly one type. In that case you can implement the -consumer trait directly on each concrete type, as you would any Rust trait, and skip providers -entirely. Named providers become worth their cost once a second type wants the *same* implementation, or once -an implementation should compose with a wrapper. +One more distinction matters. A capability may need several implementations while each individual +implementation serves exactly one type. In that case you can implement the consumer trait directly on +each concrete type, as you would any Rust trait, and skip providers entirely. Named providers become +worth their cost once a second type wants the *same* implementation, or once an implementation should +compose with a wrapper. ### How many items should a component have? A component trait is an ordinary trait. It takes as many methods, associated types, and associated -consts as any other, and every one of them is reproduced on the provider trait. CGP's own -[`CanCompute`](../components/handler/computer.md) declares an associated `Output` beside its method, and there -is no cap. +consts as any other, and the macro reproduces every one of them on the provider trait. CGP's own +[`CanCompute`](../components/handler/computer.md) declares an associated `Output` beside its method, +and the macro does not limit the count. -How much to group is a judgement rather than a rule, and the useful question is: **everything in one -component is answered by one provider choice.** Items a single choice settles belong together: a +How much to group is a judgement rather than a rule, and the useful test is this: **one provider +choice should answer everything in one component.** Items a single choice settles belong together: a method and the associated type it returns, or several field reads one getter provider answers by name. -Items that separate choices settle are better apart, because grouping them costs reuse: every provider +Items that separate choices settle are better apart, because grouping them costs reuse. Every provider then carries the union of the dependencies of all the methods, a wrapper must forward the methods it does not touch, and a type that needs only part of the surface must still supply the rest. The usual sign of a component that has grown past one decision is a consumer trait named after a noun rather than a verb, such as `Shape` carrying `area`, `perimeter`, `scale`, and `rotate`. It compiles, -but very little of it is reusable. A good check before committing: could a second type plausibly reuse one of -this trait's providers *whole*? If not, implement the trait directly on the concrete type and skip the -machinery. +but very little of it is reusable. So check before committing: could a second type plausibly reuse +one of this trait's providers *whole*? If not, implement the trait directly on the concrete type and +skip the machinery. ## Under the hood @@ -236,7 +234,7 @@ pub trait CanCalculateArea { } ``` -the macro emits five items. First, the **consumer trait**, unchanged: +the macro emits the items below. The **consumer trait** comes out unchanged: ```rust pub trait CanCalculateArea { @@ -244,11 +242,11 @@ pub trait CanCalculateArea { } ``` -Second, the **provider trait**: the same interface with `Self` replaced by a leading `Context` type +The **provider trait** repeats the same interface with `Self` replaced by a leading `Context` type parameter and every `self`/`Self` rewritten to `context`/`Context`. Its [`IsProviderFor`](../traits/wiring/is_provider_for.md) supertrait makes an unmet dependency report -itself by name rather than as a bare "trait not implemented"; its third argument is a tuple of the -component's extra type parameters, empty here: +itself by name rather than as a bare "trait not implemented". The supertrait's third argument is a +tuple of the component's extra type parameters, empty here: ```rust pub trait AreaCalculator: @@ -259,10 +257,10 @@ pub trait AreaCalculator: ``` `IsProviderFor` *replaces* the supertrait list rather than joining it. Any supertrait the consumer -trait had, whether written natively or added by `#[extend]` or `#[use_type]`, becomes a `where` predicate -on the context instead, which follows from the `Self`-to-`Context` move: a supertrait constrains the -type the capability is about, and on the provider side that type is the context parameter. So -`#[extend(HasName)]` on a `CanGreet` component produces: +trait had, whether written natively or added by `#[extend]` or `#[use_type]`, becomes a `where` +predicate on the context instead. This follows from the `Self`-to-`Context` move: a supertrait +constrains the type the capability is about, and on the provider side that type is the context +parameter. So `#[extend(HasName)]` on a `CanGreet` component produces: ```rust pub trait Greeter: IsProviderFor @@ -273,14 +271,14 @@ where } ``` -That predicate is added to every emitted item that mentions the context: the two blanket impls below and -the `UseContext` and `RedirectLookup` impls further down each gain their own `Context: HasName`, since -none of them can apply where the supertrait does not hold. +The macro adds that predicate to every emitted item that mentions the context. The two blanket impls +below and the `UseContext` and `RedirectLookup` impls further down each gain their own +`Context: HasName`, because none of them can apply where the supertrait does not hold. -**A method may carry a default body, and the body moves to the provider trait.** This is the other thing -the `Self`-to-`Context` move reaches, and it is worth knowing because it lets a provider inherit a -default at all. Given `fn greet(&self) -> String { format!("Hello, {}!", self.name()) }` on the consumer -trait, the provider trait gets `fn greet(context: &Context) -> String { format!("Hello, {}!", context.name()) }`, +**A method may carry a default body, and the body moves to the provider trait.** The +`Self`-to-`Context` move reaches the body as well, and that move lets a provider inherit a default. +Given `fn greet(&self) -> String { format!("Hello, {}!", self.name()) }` on the consumer trait, the +provider trait gets `fn greet(context: &Context) -> String { format!("Hello, {}!", context.name()) }`, rewritten but still a default. The consumer trait keeps its copy too, so the body appears twice in an expansion. @@ -292,8 +290,8 @@ This is why an **empty provider impl** is meaningful, and it is how impl Greeter for Context {} ``` -Third, the **consumer blanket impl**, the bridge that lets callers write `context.area()`: any context -implementing the provider trait *for itself* gets the consumer trait. +The **consumer blanket impl** lets callers write `context.area()`: any context implementing the +provider trait *for itself* gets the consumer trait. ```rust impl CanCalculateArea for Context @@ -306,9 +304,9 @@ where } ``` -Fourth, the **provider blanket impl**, which makes wiring work: anything that delegates this -component through [`DelegateComponent`](../traits/wiring/delegate_component.md) inherits the provider trait -from whatever it delegates to. +The **provider blanket impl** makes wiring work: anything that delegates this component through +[`DelegateComponent`](../traits/wiring/delegate_component.md) inherits the provider trait from +whatever it delegates to. ```rust impl AreaCalculator for Provider @@ -323,21 +321,23 @@ where } ``` -The `IsProviderFor` bound sits on `Provider` itself rather than on `Provider::Delegate`, which threads -a provider's dependencies down the delegation chain so they still appear in an error message. +The `IsProviderFor` bound sits on `Provider` itself rather than on `Provider::Delegate`. That +placement carries a provider's dependencies along the delegation chain, so they still appear in an +error message. -Fifth, the **component marker**, the key wiring uses: +The **component marker** is the key wiring uses: ```rust pub struct AreaCalculatorComponent; ``` -Those five are emitted in the order consumer trait, consumer impl, provider trait, provider impl, +The macro emits these items in the order consumer trait, consumer impl, provider trait, provider impl, marker. The listings above instead pair each trait with the impl that routes to it, which reads better than the order they actually appear in. -Beyond the five, the macro emits the provider impls that let the component take part in CGP's usual -patterns. The first two below are always emitted; the last two are generated one per attribute: +The macro also emits the provider impls that let the component take part in CGP's usual patterns. It +always emits the `UseContext` and `RedirectLookup` impls, and it generates the `UseDelegate` and +namespace impls one per attribute: - A [`UseContext`](../providers/use_context.md) impl, so the provider trait can be satisfied by routing back through the context's own implementation. Its only bound is @@ -349,19 +349,19 @@ patterns. The first two below are always emitted; the last two are generated one - One namespace impl per [`#[prefix(@path in Namespace)]`](./cgp_namespace.md) attribute, binding the component's key inside that namespace to a redirect down the given path. -The `RedirectLookup` impl is where a component's own type parameters earn a place in a path, and it is -what makes `@AreaCalculatorComponent.Rectangle` resolve. For a component with type parameters the -impl does not look the incoming path up directly: it appends the parameters to it first, so a lookup -that arrives at `AreaCalculatorComponent` carrying no path ends up looking for `Rectangle`. Only -*type* parameters take part; a lifetime or a const parameter cannot key a path and is left out. +The `RedirectLookup` impl puts a component's own type parameters into a path, and it makes +`@AreaCalculatorComponent.Rectangle` resolve. For a component with type parameters the impl does not +look the incoming path up directly. It appends the parameters to the path first, so a lookup that +arrives at `AreaCalculatorComponent` without a path ends up looking for `Rectangle`. Only *type* +parameters take part. A lifetime or a const parameter cannot key a path, so the impl leaves it out. -Some details of the real output differ from the listings above, and each is easy to misread when reading an +Some details of the real output differ from the listings above, and each is easy to misread in an error. The generated parameters carry **reserved names**: the context is literally `__Context__` unless you override it, and the provider parameter is `__Provider__`. The readable `Context` and -`Provider` here are for legibility only. And a component with parameters of its own appends them -*after* the context in the provider trait, except lifetimes, which Rust requires to lead, and groups -them into the `IsProviderFor` parameter tuple. That tuple holds types, so a lifetime is lifted into -[`Life<'a>`](../types/life.md): +`Provider` here are for legibility only. Also, a component with parameters of its own appends them +*after* the context in the provider trait. Lifetimes are the exception, because Rust requires them to +lead. The macro also groups those parameters into the `IsProviderFor` parameter tuple. That tuple +holds types, so it lifts a lifetime into [`Life<'a>`](../types/life.md): | Component | Provider trait | `IsProviderFor` params | |---|---|---| @@ -370,8 +370,8 @@ them into the `IsProviderFor` parameter tuple. That tuple holds types, so a life | `CanEncode` | `Encoder<__Context__, Value, Format>` | `(Value, Format)` | | `HasReference<'a, T>` | `ReferenceGetter<'a, __Context__, T>` | `(Life<'a>, T)` | -Bounds and defaults are dropped from the tuple, which names the parameters positionally and nothing -more. A const parameter has no place in it at all, which is why the macro rejects one; see +The tuple drops bounds and defaults, and it names the parameters positionally and nothing more. A +const parameter cannot appear in it at all, which is why the macro rejects one; see [Common Mistakes](#common-mistakes). ## Formal grammar @@ -396,38 +396,37 @@ ComponentName -> IDENTIFIER GenericArgs? most once, in any order, and `provider` is required. `IDENTIFIER` is a Rust identifier token, and `GenericArgs` is the Rust grammar's `< … >` argument list, so the component name may carry generic parameters while the provider name may not. The attribute delimiter, `(...)` for the bare form and -`{...}` for the key/value form, is ordinary Rust attribute syntax and does not change how the -arguments inside are parsed. +`{...}` for the key/value form, is ordinary Rust attribute syntax and does not change how the macro +parses the arguments inside. ## Common Mistakes -**A const generic parameter on the trait is rejected**, by the macro rather than by the compiler: +**The macro, not the compiler, rejects a const generic parameter on the trait:** ```text error: const generic parameters are not supported on CGP component traits ``` -A component's extra parameters are recorded as a tuple of *types* in the `IsProviderFor` supertrait, and -CGP's wiring dispatches on types rather than values, so a const value has nowhere to live in that -machinery. +The `IsProviderFor` supertrait records a component's extra parameters as a tuple of *types*, and +CGP's wiring dispatches on types rather than values, so that machinery cannot hold a const value. -An associated `const` *item* is unaffected. `const LIMIT: u64;` as a trait member is an +The rule does not affect an associated `const` *item*. `const LIMIT: u64;` as a trait member is an [associated const](https://doc.rust-lang.org/reference/items/associated-items.html), not a generic parameter, and a provider supplies it in the ordinary way. Naming your own associated const from -*inside* a [`#[cgp_impl]`](./cgp_impl.md) body has a wrinkle of its own, covered in that page's +*inside* a [`#[cgp_impl]`](./cgp_impl.md) body has one complication of its own, covered in that page's [Common Mistakes](./cgp_impl.md#common-mistakes). -**The attribute must be applied to a trait.** A struct, an enum, or a free function is refused at -parse time with an error naming the trait the macro expected, rather than being lowered into code that +**The attribute must be applied to a trait.** The macro refuses a struct, an enum, or a free function +at parse time, with an error that names the trait it expected, instead of lowering it into code that fails to compile later. -**A misplaced companion attribute is reported by the compiler, not by the macro, and reported several -times.** An attribute `#[cgp_component]` does not recognize is carried onto *every* item the macro -generates: the consumer trait, the provider trait, and the impls built from each. For `#[allow(...)]` or -a doc comment, that repetition is welcome. For `#[uses(HasName)]` written above a component -trait, it means one *cannot find attribute* resolution error per generated item, none of which mentions -`#[cgp_component]`. Read the repetition as the signal: it is the same error a typo in an attribute name -gives, so the fix is to move the attribute rather than to add an import. +**The compiler, not the macro, reports a misplaced companion attribute, and it reports it several +times.** The macro carries an attribute it does not recognize onto *every* item it generates: the +consumer trait, the provider trait, and the impls built from each. For `#[allow(...)]` or a doc +comment, that repetition is welcome. For `#[uses(HasName)]` written above a component trait, it means +one *cannot find attribute* resolution error per generated item, and none of them mentions +`#[cgp_component]`. Read the repetition as the signal. It is the same error a typo in an attribute +name gives, so the fix is to move the attribute rather than to add an import. ## Related constructs diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 49bf2ca5..2771477c 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -21,17 +21,16 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> } ``` -Any struct with a `width` and a `height` can now call `.rectangle_area()`. There is no component to -define, no provider to name, and no wiring table anywhere. The macro emits a trait and one +Any struct with a `width` and a `height` can now call `.rectangle_area()`. You do not define a +component, name a provider, or write a wiring table. The macro emits a trait and one [blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) covering every context that satisfies the field requirements. -That is the tradeoff it makes, and it is worth being explicit about. A +The macro makes one tradeoff, and you should know it. A [`#[cgp_component]`](./cgp_component.md) supports many interchangeable implementations, one chosen per context, and this costs extra boilerplate. `#[cgp_fn]` supports exactly one implementation, the function -body, and costs nothing. For the large share of capabilities that have one natural definition, that is -the better choice, which is why `#[cgp_fn]` is the recommended place to start rather than a lesser form -of the real thing. +body, and costs nothing. Most capabilities have one natural definition, so `#[cgp_fn]` is the better +choice for them and the recommended place to start, rather than a lesser form of the real thing. It is also the easiest introduction to CGP, because nothing in it is unfamiliar. A reader who understands functions and arguments can write a working capability without first meeting trait bounds, @@ -45,10 +44,10 @@ form becomes the trait name: `rectangle_area` generates a `RectangleArea` trait `rectangle_area` method. Almost every `#[cgp_fn]` takes `self` as its first parameter, because reading a field from the context -is most of what these functions do, and a receiver is *required* the moment any parameter is -`#[implicit]`. Omitting it is accepted, and produces a trait whose item is an associated function -rather than a method; it is rarely what you want here, since a function that reads nothing from its -context computes the same answer for every context that gets it. +is most of what these functions do. A receiver is *required* as soon as any parameter is +`#[implicit]`. The macro accepts a function without a receiver and produces a trait whose item is an +associated function rather than a method. But you rarely want that here, because a function that reads +nothing from its context computes the same answer for every context that gets it. Pass an identifier to override the trait name, which is useful when a verb-style name reads better than the function's: @@ -65,19 +64,19 @@ argument and write through it. ### Implicit arguments -An [`#[implicit]`](../attributes/implicit.md) parameter is removed from the method's signature and -filled from a same-named field on the context instead. The parameter's *name* is the field name, and -its *type* decides how the field is read: an owned type is cloned out, a `&str` is borrowed from a -`String` field, and a plain `&T` is borrowed with no conversion. The full set of forms, including +The macro removes an [`#[implicit]`](../attributes/implicit.md) parameter from the method's signature +and fills it from a same-named field on the context instead. The parameter's *name* is the field name, +and its *type* decides how the macro reads the field: it clones an owned type out, borrows a `&str` +from a `String` field, and borrows a plain `&T` without conversion. The full set of forms, including options, slices, and the mutable variants, is on the [`#[implicit]`](../attributes/implicit.md) page. -Because these parameters disappear from the signature, `rectangle_area` above is called with no -arguments at all: `rect.rectangle_area()`. +Because these parameters disappear from the signature, you call `rectangle_area` above without any +arguments: `rect.rectangle_area()`. ### Generics, and where each bound lands A `#[cgp_fn]` splits its generics and its `where` clause deliberately, and knowing which goes where is -most of what there is to learn about the macro. +most of what you need to learn about the macro. | You write | It lands on | |---|---| @@ -87,8 +86,8 @@ most of what there is to learn about the macro. | [`#[extend_where(...)]`](../attributes/extend_where.md) | Both the trait and the impl | By default, generics land on both the trait and the impl, and the `where` clause lands on the impl -alone. This keeps a capability's requirements out of sight of its callers: a caller bounds on the -clean trait, and the constraints the body actually needs stay one level down on the implementation: +alone. This hides a capability's requirements from its callers: a caller bounds on the clean trait, +and the constraints the body actually needs stay one level down on the implementation: ```rust #[cgp_fn] @@ -100,13 +99,13 @@ where } ``` -`Scale` is the trait; `Scalar: Mul + Copy` appears only on the impl. +`Scale` is the trait, and `Scalar: Mul + Copy` appears only on the impl. #### A type the caller should not name When the function needs a type that should be inferred rather than chosen, such as a database handle -or a displayable value, declare it with `#[impl_generics(...)]`. The parameter goes on the impl alone, so -the trait stays unparameterized and no caller mentions it: +or a displayable value, declare it with `#[impl_generics(...)]`. The parameter goes on the impl alone, +so the trait stays unparameterized and callers never mention it: ```rust #[cgp_fn] @@ -116,15 +115,15 @@ pub fn describe(&self, #[implicit] name: &Name) -> String { } ``` -`Describe` has no type parameter. A context becomes eligible purely by carrying a `name` field of some -`Display` type, and the type is resolved from that field. +The `Describe` trait is not generic. A context becomes eligible purely by carrying a `name` field of +some `Display` type, and the compiler resolves the type from that field. The cost is that the type is concealed rather than named. It exists only where a value of it flows through an implicit argument, so nothing else can refer to it, including this function's own signature. Naming it in a return type or an explicit parameter does not compile, as the -[Common Mistakes](#common-mistakes) explain. When the type must be nameable, or when two capabilities have to agree -that they mean the same type, promote it to an abstract type with [`#[cgp_type]`](./cgp_type.md) and -import it with [`#[use_type]`](../attributes/use_type.md). +[Common Mistakes](#common-mistakes) explain. When the type must be nameable, or when two capabilities +have to agree that they mean the same type, promote it to an abstract type with +[`#[cgp_type]`](./cgp_type.md) and import it with [`#[use_type]`](../attributes/use_type.md). ### Companion attributes @@ -143,12 +142,12 @@ it depends on. `where` clause, for a bound callers need to see. - [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound when the function delegates to one. -- [`#[async_trait]`](./async_trait.md) goes directly beneath `#[cgp_fn]` on an `async fn`. It is copied - onto both generated items, so the trait ends up declaring a lint-clean `-> impl Future`. +- [`#[async_trait]`](./async_trait.md) goes directly beneath `#[cgp_fn]` on an `async fn`. The macro + copies it onto both generated items, so the trait ends up declaring a lint-clean `-> impl Future`. ## Examples -Two capabilities, the second built on the first, and a context that gets both without wiring anything: +A capability, another capability built on it, and a context that gets both without wiring anything: ```rust use cgp::prelude::*; @@ -178,36 +177,36 @@ pub fn report(rect: &Rectangle) { ``` `scaled_rectangle_area` calls `self.rectangle_area()` because `#[uses(RectangleArea)]` declared the -dependency; it does not know or care how that capability is implemented. `Rectangle` derives +dependency. It does not know or care how that capability is implemented. `Rectangle` derives [`HasField`](../derives/derive_has_field.md) and happens to carry the three fields the two functions -read, and that is its entire qualification. There is no `delegate_components!` anywhere in this -program, and adding one would change nothing. +read, and that is its entire qualification. This program does not use `delegate_components!` +anywhere, and adding one would change nothing. ## When to use it -**Use `#[cgp_fn]` first.** When a capability has one natural definition, this is the form to -write, and starting here costs nothing if that changes later: the trait keeps its name and its method, -so promoting it to a [`#[cgp_component]`](./cgp_component.md) leaves every call site untouched. What -you add at that point is the component, a named provider, and a line of wiring per context. +**Use `#[cgp_fn]` first.** When a capability has one natural definition, this is the form to write. +Starting here costs nothing if that changes later, because the trait keeps its name and its method, so +promoting it to a [`#[cgp_component]`](./cgp_component.md) leaves every call site untouched. At that +point you add the component, a named provider, and a line of wiring per context. Use something else in these cases: - **The capability needs a second implementation, chosen per context.** - [`#[cgp_component]`](./cgp_component.md) is for that, and no amount of `#[cgp_fn]` will get you - there: its blanket impl already covers every context, so there is nowhere for an alternative to live. + [`#[cgp_component]`](./cgp_component.md) is for that, and `#[cgp_fn]` cannot provide it: its + blanket impl already covers every context, so an alternative cannot coexist with it. - **The dependencies are traits rather than fields.** [`#[blanket_trait]`](./blanket_trait.md) builds the same kind of single-implementation, no-wiring capability from a trait with supertraits and - default method bodies. Use it when the body needs other capabilities; use `#[cgp_fn]` - when it needs values. + default method bodies. Use it when the body needs other capabilities, and use `#[cgp_fn]` when it + needs values. - **A generic must vary per call.** A generic parameter here goes on the trait rather than the method, - so it is fixed by whatever satisfies the bounds for a given context rather than chosen at each call - site. A capability that needs a per-call type parameter wants a hand-written blanket impl - or a component. - -One decision inside the macro is worth making deliberately rather than by default: **where a type the -body needs should live.** Start with `#[impl_generics]` while the type only ever flows through implicit -arguments. It is shorter, needs no wiring, and reads as "this works with any `database` field of a -compatible type". Move up to an [abstract type](./cgp_type.md) when the type must appear in the + so whatever satisfies the bounds for a given context fixes it, rather than each call site choosing + it. A capability that needs a per-call type parameter needs a hand-written blanket impl or a + component instead. + +Make one decision inside the macro deliberately rather than by default: **where a type the body needs +should live.** Start with `#[impl_generics]` while the type only ever flows through implicit +arguments. It is shorter, does not need wiring, and reads as "this works with any `database` field of +a compatible type". Move up to an [abstract type](./cgp_type.md) when the type must appear in the capability's own signature, or when two capabilities must agree that they mean the same one. Avoid a plain generic parameter on the function in both cases: it lands on the trait and makes every caller, and every intermediate capability built on it, declare the parameter and repeat its bounds whether @@ -252,16 +251,17 @@ where } ``` -A few details of the real output are worth recognizing. The context type parameter is literally -`__Context__`, a reserved name chosen so it cannot collide with one of yours, and it is referred to as -`Self` inside the impl. [`Symbol!("width")`](./symbol.md) is a type-level string standing for the field -name. The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and -`cargo cgp expand` resugars it back to this. An *owned* implicit argument compiles to a trailing -`.clone()`; a `&str` argument ends in `.as_str()` instead, and a plain `&T` in nothing at all. +Learn to recognize a few details of the real output. The context type parameter is literally +`__Context__`, a reserved name chosen so it cannot collide with one of yours, and the impl refers to +it as `Self`. [`Symbol!("width")`](./symbol.md) is a type-level string standing for the field name. +The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form in errors, and `cargo cgp expand` +resugars it back to this. An *owned* implicit argument compiles to a trailing `.clone()`. A `&str` +argument ends in `.as_str()` instead, and a plain `&T` in nothing at all. The generics split shows up in the same impl. Given the `scale` function above, the generic goes on both items while the function's `where` bound stays on the impl, ordered *before* the implicit field -bounds. Attribute-contributed predicates always come first, and the implicit ones are appended last: +bounds. Attribute-contributed predicates always come first, and the macro appends the implicit ones +last: ```rust pub trait Scale { @@ -277,16 +277,20 @@ where } ``` -The companion attributes layer into these same two items. `#[uses(Trait)]` adds a `Self: Trait` -predicate to the impl; `#[extend(Trait)]` adds it to the impl *and* to the trait's supertraits; -`#[extend_where(P)]` adds `P` to both `where` clauses; `#[impl_generics(T: Bound)]` inserts `T: Bound` -into the impl's generic list alone (its argument is a comma-separated list of ordinary generic -parameters, so a lifetime or a const parameter is accepted there too); and -`#[use_type(Trait.Type)]` adds the supertrait and rewrites every bare mention of the type into its -fully qualified form. The macro appends the implicit-argument bounds last, after whatever the -attributes contributed. +The companion attributes layer into these same two items, and each lands in a fixed place: -A couple of smaller placements are worth knowing because neither is visible in the source you wrote. **The +- `#[uses(Trait)]` adds a `Self: Trait` predicate to the impl. +- `#[extend(Trait)]` adds it to the impl *and* to the trait's supertraits. +- `#[extend_where(P)]` adds `P` to both `where` clauses. +- `#[impl_generics(T: Bound)]` inserts `T: Bound` into the impl's generic list alone. Its argument is a + comma-separated list of ordinary generic parameters, so a lifetime or a const parameter is accepted + there too. +- `#[use_type(Trait.Type)]` adds the supertrait and rewrites every bare mention of the type into its + fully qualified form. + +The macro appends the implicit-argument bounds last, after whatever the attributes contributed. + +Two smaller placements matter because neither is visible in the source you wrote. **The function's visibility becomes the trait's**, and the impl's method keeps inherited visibility. So `pub fn rectangle_area` yields `pub trait RectangleArea`, and a private `fn` yields a private trait usable only in its own module. And **the macro copies an attribute it does not recognize onto both @@ -309,16 +313,16 @@ of their own, documented on their own pages. ## Common Mistakes -**A function with implicit arguments must take `self` first.** Without a receiver there is no context -to read a field from, and the macro says so rather than emitting a bound that fails later: +**A function with implicit arguments must take `self` first.** Without a receiver the macro cannot +find a context to read a field from, so it reports that rather than emitting a bound that fails later: ```text error: The first argument of a function with implicit arguments must be `self` ``` **A mutable implicit argument must be the only one.** Reading a field mutably borrows the whole context -exclusively, so it cannot coexist with any other field read. Immutable implicit arguments carry no such -restriction and combine freely, in any number: +exclusively, so it cannot coexist with any other field read. Immutable implicit arguments do not have +this restriction and combine freely, in any number: ```text error: a `&mut` implicit argument must be the only implicit argument, since its mutable @@ -327,17 +331,16 @@ error: a `&mut` implicit argument must be the only implicit argument, since its **An `#[impl_generics]` parameter cannot appear in the capability's own signature.** Only the generated impl declares it, so naming it in a return type or an explicit parameter leaves it unresolved in the -trait. Both spellings report the same headline: +trait. A bare `Db` reports: ```text error[E0425]: cannot find type `Db` in this scope ``` -The error code differs, and that is the part worth noticing, since you are likely to search for it. A -bare `Db` reports `E0425` as above; a qualified path such as `Db::Row` reports `E0433`, and the -compiler labels its span *use of undeclared type `Db`* instead. Both mean the same thing: either the -type belongs out of the signature, or it needs to be an [abstract type](./cgp_type.md) rather than an -inferred impl parameter. +A qualified path such as `Db::Row` reports `E0433` instead, and the compiler labels its span *use of +undeclared type `Db`*. The code differs, and that matters because you are likely to search for it. +Both mean the same thing: either the type belongs out of the signature, or it needs to be an +[abstract type](./cgp_type.md) rather than an inferred impl parameter. ## Related constructs diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index c7b87721..0c4ad32d 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -10,7 +10,7 @@ already know. ## Overview -A [provider trait](./cgp_component.md) is shaped inside-out compared with the trait it came from. The +A [provider trait](./cgp_component.md) has a different shape from the trait it came from. The original `Self` has moved into an explicit leading type parameter, the implementation targets a small marker type rather than the type the capability is about, and the method receiver is a plain parameter. Written by hand it looks like this: @@ -27,10 +27,10 @@ where ``` Every part of that is correct, and almost every part of it is unfamiliar. The trait carries a -parameter you did not write, `Self` is a type with no values, and there is no `self` anywhere. Written -this way, the code does not read as an implementation of `CanCalculateArea`, even though that is -exactly what it is. [Bypassing coherence](/docs/concepts/coherence) is why the trait needs a `Self` it -owns instead of the type the capability is really about. +parameter you did not write, `Self` is a type without values, and the block does not mention `self` +anywhere. Written this way, the code does not read as an implementation of `CanCalculateArea`, even +though it is exactly that. The trait needs a `Self` it owns, instead of the type the capability is +really about, so that it can [bypass coherence](/docs/concepts/coherence). `#[cgp_impl]` gives you back the familiar shape. Write the implementation as though you were implementing the consumer trait directly, with `self` and `Self` and the signatures from the original @@ -48,20 +48,20 @@ where } ``` -The macro performs the rewrite for you. Write providers this way. The macro produces the inside-out -form shown earlier, and you will see that form in generated code. +Write providers this way. The macro performs the rewrite for you and produces the form shown earlier, +which you will see in generated code. -This convenience has one exception worth stating plainly: **inside a `#[cgp_impl]` block, `self` and +This convenience has one rule you must keep in mind: **inside a `#[cgp_impl]` block, `self` and `Self` mean the context, not the provider.** The context is the type the capability runs against, and -it supplies the values it needs as its own fields. The provider is a type-level name with no fields -and no value: it is never constructed, and there is nothing in it to read. The macro rewrites `self` -to the context value and `Self` to the context type because the context is the only thing that exists -when the method runs. +it supplies the values it needs as its own fields. The provider is a type-level name without fields or +values. The program never constructs it, and it holds nothing to read. The macro rewrites `self` to the +context value and `Self` to the context type because the context is the only thing that exists when +the method runs. ## Usage -Apply the attribute to an `impl` block. Its argument names the provider. The argument has three parts, -and only the name is required. +Apply the attribute to an `impl` block. Its argument names the provider. The argument has the parts +listed below, and only the name is required. ```rust #[cgp_impl(new RectangleArea)] @@ -81,13 +81,12 @@ where | provider name | Required. The type that takes the `Self` position in the generated provider impl. | | `: ComponentType` | Optional. Overrides which component this provider is registered as implementing. Defaults to the provider trait's name plus `Component`. | -The `for Context` clause is optional. Omitting it, as every example on this page does, lets the macro +The `for Context` clause is optional. Omitting it, as most examples on this page do, lets the macro insert a generic context parameter for you: write `impl AreaCalculator`, not `impl AreaCalculator for Context`. Name the context explicitly only to bound it in a way the omitted form cannot express, such as a lifetime or a higher-ranked bound, or to serve one *concrete* context alone, as in `impl AreaCalculator for Rectangle`. -[When to use it](#when-to-use-it) says more about choosing between these -forms. +[When to use it](#when-to-use-it) says more about choosing between these forms. Without `new`, the provider struct must already exist. A wiring entry naming a struct nothing declares is a common and confusing first error. @@ -108,8 +107,8 @@ impl AreaCalculator { ### Declaring the provider struct separately -`new` is convenient for a provider used once, but a struct implementing several provider traits, or -one whose shape `new` cannot express, is usually declared on its own instead. +`new` is convenient for a provider used once. But you usually declare the struct yourself when it +implements several provider traits, or when it needs a shape `new` cannot express. **A provider often implements more than one component.** Each provider trait still needs its own `#[cgp_impl]` block, but only one of those blocks should declare the struct. Write `new` on exactly @@ -131,32 +130,32 @@ impl PerimeterCalculator { } ``` -The first block's `new` declares `pub struct RectangleGeometry;`; the second block names the same +The first block's `new` declares `pub struct RectangleGeometry;`. The second block names the same struct without `new` and adds a second impl to it. Writing `new` on more than one block for the same struct is a duplicate-definition error. Declaring the struct explicitly is an equally valid style for this same case: write `pub struct RectangleGeometry;` once, above both blocks, and omit `new` from all of them rather than -from just the second. Either style works; declaring the struct explicitly reads more consistently once -there are more than two or three blocks, since a reader does not have to find the one block carrying +from just the second. Either style works. Declaring the struct explicitly reads more consistently once +there are more than two or three blocks, because a reader does not have to find the one block carrying `new` to know where the struct comes from. Neither style requires -[`#[cgp_provider]`](./cgp_provider.md): the struct is only being declared once and reused, and the body -of every block still reads as an ordinary trait impl. +[`#[cgp_provider]`](./cgp_provider.md): the struct is only declared once and reused, and the body of +every block still reads as an ordinary trait impl. **A struct whose shape `new` cannot express must be declared explicitly, because `new`'s own grammar is narrow.** `#[cgp_impl(new ...)]` desugars to [`#[cgp_new_provider]`](./cgp_provider.md#the-struct-cgp_new_provider-declares), and that macro can -only emit one of two shapes: a plain provider name becomes a unit struct with no fields, and -a generic provider becomes a tuple struct with one public +only emit two shapes. A plain provider name becomes a unit struct without fields, and a generic +provider becomes a tuple struct with one public [`PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html) field wrapping all of its -generic parameters together, always `pub` and never with a default. Anything the struct needs outside -that shape has to be written by hand. +generic parameters together, always `pub` and never with a default. You must write by hand anything +the struct needs outside those shapes. The case you see most often is a default on a higher-order provider's inner parameter, so an application can omit the inner provider and fall back to [`UseContext`](../providers/use_context.md), which routes back through the context's own implementation of the component. If `ScaledAreaCalculator` from [Usage](#usage) should default this -way, `new` has no syntax for it, and the struct has to be declared by hand instead: +way, `new` cannot express it, and you must declare the struct by hand instead: ```rust pub struct ScaledAreaCalculator(PhantomData); @@ -164,14 +163,14 @@ pub struct ScaledAreaCalculator(PhantomData)]` block implementing a component for it then looks exactly like the block shown in [Usage](#usage), minus `new`. The same reasoning covers any other -shape `new` cannot spell: an extra derive, a visibility narrower than `pub`, or fields beyond that one -blanket `PhantomData`. Declare the struct with whatever shape it needs, and keep every implementing +shape `new` cannot express: an extra derive, a visibility narrower than `pub`, or fields beyond that +one blanket `PhantomData`. Declare the struct with whatever shape it needs, and keep every implementing block written with `#[cgp_impl(ProviderName)]`. ### Companion attributes -Several attributes are processed on a `#[cgp_impl]` block before the rewrite happens. Together they -let an idiomatic provider state what it needs. +The macro processes several attributes on a `#[cgp_impl]` block before the rewrite happens. Together +they let an idiomatic provider state what it needs. - [`#[implicit]`](../attributes/implicit.md) on a parameter removes it from the signature and fills it from a same-named field on the context. @@ -181,30 +180,31 @@ let an idiomatic provider state what it needs. occurrences to fully qualified form. - [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound in a higher-order provider. -- [`#[default_impl(...)]`](../traits/namespace/default_namespace.md) registers the provider as a namespace's +- [`#[default_impl(...)]`](../attributes/default_impl.md) registers the provider as a namespace's per-type default, emitting a delegation impl alongside it, for use with [`cgp_namespace!`](./cgp_namespace.md). Each may be repeated. All except `#[use_provider]` also take a comma-separated list inside one attribute, which is the form to prefer: `#[uses(HasName, CanRaiseError)]` reads as one dependency list. `#[use_provider]` is the exception because its own argument already ends in a bound -list, so a second pair after a comma has nowhere to go; write one attribute per inner provider. +list, so the parser could not tell where a second pair begins. Write one attribute per inner provider. -`#[cgp_impl]` does not read three attributes you may see on other CGP macros: `#[extend]`, -`#[extend_where]`, and `#[impl_generics]`. All three act on a *generated trait definition*, which a -provider impl does not have, so they belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to +`#[cgp_impl]` does not read `#[extend]`, `#[extend_where]`, or `#[impl_generics]`, although you may +see them on other CGP macros. Each of them acts on a *generated trait definition*, which a provider +impl does not have, so they belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to [`#[cgp_component]`](./cgp_component.md). Writing one here leaves a name nothing resolves; see -[Common Mistakes](#common-mistakes). An impl-side bound that really is impl-side goes in the block's own `where` -clause, which passes through untouched. +[Common Mistakes](#common-mistakes). An impl-side bound that really is impl-side goes in the block's +own `where` clause, which passes through untouched. ### Implementing the consumer trait directly Naming `Self` as the provider bypasses the rewrite entirely and emits the block unchanged as an -ordinary consumer-trait impl on a concrete type. This form requires the `for Context` clause. Omitting -it is rejected with an `Expected context type to be specified` error, since there is no context left to -find. The form is useful when you want a hand-written impl while still applying the companion -attributes. Because the macro does not generate a provider struct here, `new` and the component -override have no effect; see [Common Mistakes](#common-mistakes) for what happens if you write them anyway. +ordinary consumer-trait impl on a concrete type. This form requires the `for Context` clause. The +macro rejects an omitted clause with an `Expected context type to be specified` error, because it then +lacks a context to find. The form is useful when you want a hand-written impl while still applying the +companion attributes. Because the macro does not generate a provider struct here, `new` and the +component override do nothing; see [Common Mistakes](#common-mistakes) for what happens if you write +them anyway. ```rust #[cgp_impl(Self)] @@ -264,21 +264,21 @@ fn print_area(rect: &Rectangle) { **Write providers with `#[cgp_impl]`.** It is the recommended form for every provider, and the cases that call for something else are narrower than they look. -Prefer the unqualified header from [Usage](#usage), `impl AreaCalculator` with no `for Context`, -letting the macro insert the context parameter, which keeps a provider reading like an ordinary trait -impl. Name the context explicitly only when the sugar falls short, such as a lifetime or a +Prefer the unqualified header from [Usage](#usage), `impl AreaCalculator` without `for Context`, and +let the macro insert the context parameter. This keeps a provider reading like an ordinary trait impl. +Name the context explicitly only when the short form cannot express a bound, such as a lifetime or a higher-ranked bound. Naming a *concrete* type as that context, as in `impl AreaCalculator for Rectangle`, is a different -choice worth keeping distinct from the +choice. Keep it distinct from the [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which looks similar but does something else. The concrete-context form still produces a named provider that a context wires like -any other. The `Self` form produces no provider at all. +any other. The `Self` form does not produce a provider at all. Use something else in these cases: - **The capability has only one implementation.** [`#[cgp_fn]`](./cgp_fn.md) builds it from a plain - function with no component, no provider, and no wiring, which is the bottom tier of + function without a component, a provider, or wiring, which is the bottom tier of [Modularity Hierarchy](/docs/concepts/modularity-hierarchy). - **You want to implement the consumer trait directly on one concrete type.** Use the [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which keeps the companion @@ -286,8 +286,8 @@ Use something else in these cases: Needing to [declare the provider struct separately](#declaring-the-provider-struct-separately) is not by itself a reason to drop to [`#[cgp_provider]`](./cgp_provider.md). Use the raw form only when -you need the inside-out provider-trait shape itself: a bound the sugar cannot express, or a rare -construct `#[cgp_impl]`'s rewrite does not support, whether from a limitation or a bug. +you need the provider-trait shape itself: a bound the short form cannot express, or a rare construct +`#[cgp_impl]`'s rewrite does not support, whether from a limitation or a bug. ## Under the hood @@ -304,8 +304,8 @@ impl FooProvider for Context { } ``` -Because `new` was given, the macro also produces the provider struct alongside the provider impl and -its `IsProviderFor` impl: +Because the attribute includes `new`, the macro also produces the provider struct alongside the +provider impl and its `IsProviderFor` impl: ```rust impl FooProvider for ValueToString { @@ -325,7 +325,7 @@ the snake-cased context type wrapped in double underscores, so both `Context` an `__Context__` become `__context__`. The macro rewrites every `self` in a body to that identifier, and every `Self` to the context type. -When `for Context` is omitted the only difference is that the inserted parameter is `__Context__`. The +When you omit `for Context`, the only difference is that the inserted parameter is `__Context__`. The earlier `RectangleArea` example is exactly equivalent to writing it out: ```rust @@ -349,14 +349,14 @@ so a provider for `ComputerRef` gets **An associated type the block declares is exempt.** The macro leaves `Self::Output` alone in a provider that supplies `type Output`, because it gathers the block's own associated-type names first and skips any `Self::` path starting with one. In the emitted impl, `Self` is the provider struct, -which is the type that declares `Output`, so the path still resolves. Every other `Self` in the block is -still rewritten, including one naming an abstract type the *context* supplies. Associated consts are -not covered by the exemption; see [Common Mistakes](#common-mistakes). +which is the type that declares `Output`, so the path still resolves. The macro still rewrites every +other `Self` in the block, including one naming an abstract type the *context* supplies. The exemption +does not cover associated consts; see [Common Mistakes](#common-mistakes). **The rewrite is scoped to the block's own method bodies.** An item nested *inside* a body, such as a local `struct` with its own impl, a helper `fn`, or an inline `trait`, introduces a fresh `self`/`Self` -that belongs to that item, exactly as in ordinary Rust, and the macro leaves it alone. Closures, which -capture the enclosing `self`, are rewritten like any other expression. +that belongs to that item, exactly as in ordinary Rust, and the macro leaves it alone. The macro +rewrites closures, which capture the enclosing `self`, like any other expression. ## Formal grammar @@ -378,10 +378,10 @@ defaulting to the provider trait's name plus `Component`. Both are Rust `Type` p ## Common Mistakes -**A provider's own associated const is awkward to name inside its body**, and this follows directly -from the rewrite. The exemption described above covers associated *types* only, so a provider that -declares `const LIMIT: u64 = 100;` cannot then write `Self::LIMIT` in a method body: that `Self` is -rewritten to the context, which has no such const. The error reads: +**A provider's own associated const needs a qualified path inside its body**, and this follows +directly from the rewrite. The exemption described above covers associated *types* only. So a provider +that declares `const LIMIT: u64 = 100;` cannot then write `Self::LIMIT` in a method body, because the +macro rewrites that `Self` to the context, which lacks the const. The error reads: ```text error[E0599]: no associated function or constant named `LIMIT` found for type parameter `__Context__` in the current scope @@ -400,17 +400,17 @@ its `self`/`Self` rewritten too, because a token-level rewrite cannot see the sc eventually create. A `self::` *module* path inside a macro invocation is safe: the trailing `::` distinguishes the two meanings of `self`, and only the value form is rewritten. -**A misplaced companion attribute is reported by the compiler, not by the macro.** An attribute -`#[cgp_impl]` does not recognize is re-attached to the generated provider impl rather than dropped, so +**The compiler, not the macro, reports a misplaced companion attribute.** The macro re-attaches an +attribute it does not recognize to the generated provider impl rather than dropping it, so `#[allow(...)]` and similar attributes carry over unaffected. A stray `#[extend(HasName)]` therefore -produces a *cannot find attribute* resolution error pointing at the impl, with no mention of +produces a *cannot find attribute* resolution error pointing at the impl, and it does not mention `#[cgp_impl]`. -**`new` and a component override are accepted, and ignored, on the `Self` form.** Writing +**The `Self` form accepts `new` and a component override, then ignores both.** Writing `#[cgp_impl(new Self)]` or `#[cgp_impl(Self: SomeComponent)]` parses and compiles, but has exactly the -same effect as a plain `#[cgp_impl(Self)]`: no struct is declared, and the component override is never -consulted, because this form builds neither a provider nor an `IsProviderFor` impl for either one to -apply to. Leave both out. +same effect as a plain `#[cgp_impl(Self)]`. The macro does not declare a struct, and it never consults +the component override, because this form builds neither a provider nor an `IsProviderFor` impl for +either one to apply to. Leave both out. ## Related constructs @@ -422,12 +422,12 @@ apply to. Leave both out. - [`check_components!`](./check_components.md) — verifies the wiring resolves. - [`#[implicit]`](../attributes/implicit.md), [`#[uses]`](../attributes/uses.md), [`#[use_type]`](../attributes/use_type.md), [`#[use_provider]`](../attributes/use_provider.md), - [`#[default_impl]`](../traits/namespace/default_namespace.md) — the companion attributes. + [`#[default_impl]`](../attributes/default_impl.md) — the companion attributes. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the inside-out shape - this macro hides. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the provider-trait + shape this macro hides. - [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — what the block's `where` clause is really doing. diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 99721649..8aa46bae 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -23,28 +23,28 @@ delegate_components! { } ``` -The mental model is a **table**: a compact list saying which implementation supplies each capability. -It is worth being precise about one thing, because the analogy invites the wrong conclusion. This looks -like an object's method table, but it is resolved entirely at compile time: the keys and values are -types, the lookup happens during trait resolution, and the result monomorphizes to a direct call. -There is no table in the compiled program, no dynamic dispatch, and nothing in the binary for a -provider you did not choose. - -The type this table is attached to is a **context**: the type that owns the wiring. Often it is a type +Think of the result as a **table**: a compact list saying which implementation supplies each +capability. But one point needs precision, because the analogy suggests a wrong conclusion. This looks +like an object's method table, but the compiler resolves it entirely at compile time: the keys and +values are types, the lookup happens during trait resolution, and the result monomorphizes to a direct +call. The compiled program contains neither a table nor dynamic dispatch, and the binary holds nothing +for a provider you did not choose. + +The type that carries this table is a **context**: the type that owns the wiring. Often it is a type standing for your whole application, whose job is to carry choices rather than data. `struct App;` -with no fields is a perfectly good context. Sometimes, as above, it is the data type itself. +without fields is a perfectly good context. Sometimes, as above, it is the data type itself. -A macro is worth having here because each entry expands to two impls rather than one. Besides the impl +You need a macro here because each entry expands to two impls rather than one. Besides the impl that stores the choice, the macro emits a second one that forwards the chosen provider's own -dependencies back through the table. This makes a missing transitive requirement produce a usable -error instead of a dead end. [Under the hood](#under-the-hood) shows both. +dependencies back through the table. So a missing transitive requirement produces a usable error +instead of one that does not name the cause. [Under the hood](#under-the-hood) shows both. ## Usage The macro takes a target type and a brace-delimited body. The body holds any number of **statements** followed by any number of **mappings**, and a mapping is a **key**, an **operator**, and a **value**, -chosen independently. This section covers the operators, the key forms, the value forms, and the -statements, in that order. +chosen independently. This section covers the target forms first, then the operators, the key forms, +the value forms, and the statements. **Every one of these forms combines with the others inside a single block.** A table routinely opens a component for per-type dispatch, joins a namespace, and still maps plain component names to providers @@ -73,13 +73,13 @@ delegate_components! { } ``` -This is how you build an **aggregate provider**: a zero-sized provider whose only job is to hold a +Use this form to build an **aggregate provider**: a zero-sized provider whose only job is to hold a table dispatching each component to a sub-provider, so that other contexts can delegate a whole group of components to it as one unit. An aggregate provider is a *provider*, not a context. It forwards -each component's provider trait onward, and no call ever resolves with the bundle in the context -position. That is why it must be wired with plain `delegate_components!` and never with -[`delegate_and_check_components!`](./delegate_and_check_components.md), whose check asks whether the -bundle can use each component *as* a context and so proves nothing either way. +each component's provider trait onward, and a call never resolves with the bundle in the context +position. So you must wire it with plain `delegate_components!` and never with +[`delegate_and_check_components!`](./delegate_and_check_components.md). That macro's check asks whether +the bundle can use each component *as* a context, so it proves nothing either way. ### One table for a family of types @@ -93,10 +93,10 @@ delegate_components! { } ``` -### The three operators +### The operators The operator between a key and its value decides what the entry resolves to. The parser accepts any -operator against any key form; which pairings are actually worth writing is noted below. +operator with any key form. The notes below say which pairings are worth writing. | Operator | Reads as | The entry resolves to | |---|---|---| @@ -108,8 +108,8 @@ Nearly all wiring uses `:`, and the rest of this page's examples assume it unles otherwise. **`->` is direct delegation.** Instead of naming a provider it forwards the lookup one hop into another -table, and the macro adds a bound requiring that the named table actually has an entry for that key. It -is how one table adopts a single choice from another rather than repeating it: +table, and the macro adds a bound requiring that the named table actually has an entry for that key. +This is how one table adopts a single choice from another rather than repeating it: ```rust delegate_components! { @@ -122,16 +122,16 @@ delegate_components! { } ``` -Those two lines are worth reading against each other, because the difference is easy to miss. The `:` -entry names `ScaledAreaCalculator` outright, so `ScaledGeometryComponents` scales the -area calculation; the `->` entry reaches into `GeometryComponents`'s table and copies out whatever it -holds for `PerimeterCalculatorComponent`, so the perimeter is left exactly as `GeometryComponents` -already computes it, unscaled. +Compare the two lines, because the difference is easy to miss. The `:` entry names +`ScaledAreaCalculator` outright, so `ScaledGeometryComponents` scales the area +calculation. The `->` entry reaches into `GeometryComponents`'s table and copies out whatever it holds +for `PerimeterCalculatorComponent`, so the perimeter stays exactly as `GeometryComponents` already +computes it, unscaled. **`=>` is redirection.** It sends the lookup along a type-level [path](./path.md) rather than to a -provider, so the provider is decided wherever the path finally lands. On a context, that path names a -slot in the context's own table, so several components can be pointed at one shared slot and answered -from a single entry: +provider, so the place where the path finally lands decides the provider. On a context, that path names +a slot in the context's own table, so you can point several components at one shared slot and answer +them from a single entry: ```rust delegate_components! { @@ -144,12 +144,12 @@ delegate_components! { } ``` -This is also the mechanism the `open` statement below is built on: `open AreaCalculatorComponent;` is +The `open` statement below uses this same mechanism: `open AreaCalculatorComponent;` is another spelling of `AreaCalculatorComponent => @AreaCalculatorComponent,` and generates the same impl. -Its other use is rerouting a whole path *prefix* at once, which is a [namespace](./cgp_namespace.md) -concern more than a per-context one. +The other use of `=>` is rerouting a whole path *prefix* at once, which is a +[namespace](./cgp_namespace.md) concern more than a per-context one. -### The three key forms +### The key forms **A single key** is one component name, and may carry generics of its own: ` ShapeAreaCalculatorComponent: SumAreas` adds a parameter to just that entry. @@ -171,9 +171,9 @@ delegate_components! { Each bracketed element is a full key, so an element may carry its own generics: in `[WidthKey, HeightKey]: RectangleValue` only the second key introduces `T2`. The -list is a key form rather than an operator, so `[A, B] -> SomeTable` and `[A, B] => @somewhere` are as legal as -`[A, B]: Provider`; the first adopts several of another table's entries at once, the second points -several components at one shared slot. +list is a key form rather than an operator, so `[A, B] -> SomeTable` and `[A, B] => @somewhere` are as +legal as `[A, B]: Provider`. The `->` form adopts several of another table's entries at once, and the +`=>` form points several components at one shared slot. **A path key** is an `@`-prefixed route rather than a bare name, and it addresses a slot behind a redirect: the per-value slots an `open` statement opens, or the prefixed routes a @@ -183,7 +183,7 @@ redirect: the per-value slots an `open` statement opens, or the prefixed routes becomes a type-level string, and anything else names a type. A segment may also carry generics, as in `@SomeComponent.<'a, T> &'a T: SomeProvider`. -A couple of grouping forms expand one path key into several, and **they are not interchangeable**: +Two grouping forms expand one path key into several, and **they are not interchangeable**: - **`[…]` groups alternatives for one segment**, and the path may continue after it. `@app.[AreaCalculatorComponent, PerimeterCalculatorComponent].[u64, String]: RectangleGeometry` @@ -204,10 +204,9 @@ delegate_components! { } ``` -The shorthand worth remembering is that `[…]` is a choice *within* a segment and `{…}` is a choice *of -tails*. +Remember it this way: `[…]` is a choice *within* a segment and `{…}` is a choice *of tails*. -### The two value forms +### The value forms A value is normally just a type: the provider, or the table a `->` forwards into. One other form exists, and it is legacy. @@ -217,9 +216,9 @@ exists, and it is legacy. ### Legacy: read, don't write Older code dispatches per type by nesting a table inside a [`UseDelegate`](../providers/use_delegate.md) -value instead of using the `open` statement below. **Prefer `open` for anything new**: it needs no -separate table type and no wrapper. This form is here because you will see it in existing code, -including in CGP's own error and handler components, which are still defined this way. +value instead of using the `open` statement below. **Prefer `open` for anything new**: it needs neither +a separate table type nor a wrapper. This page keeps the form because you will see it in existing +code, including in CGP's own error and handler components, which are still defined this way. ::: @@ -239,9 +238,9 @@ delegate_components! { A few details of the form are easy to miss. The inner braces hold a **full table body**, so an inner table accepts everything an outer one does, nesting included. The **wrapper is not fixed to -`UseDelegate`**: any single-parameter wrapper type is accepted, which is how a component dispatched on -a tuple of parameters gets wired to a matching `UseDelegate2`. And the **inner table's name may carry -generics**, which a per-entry generic on the outer key threads into: +`UseDelegate`**: the macro accepts any single-parameter wrapper type, which is how a component +dispatched on a tuple of parameters gets wired to a matching `UseDelegate2`. And the **inner table's +name may carry generics**, which a per-entry generic on the outer key threads into: ```rust delegate_components! { @@ -277,10 +276,10 @@ delegate_components! { ``` Braces are optional when opening a single component, so `open AreaCalculatorComponent;` and -`open { AreaCalculatorComponent };` are the same; the braced list is needed to open several at once, -and a braceless header naming more than one component is rejected. +`open { AreaCalculatorComponent };` are the same. The braced list is needed to open several at once, +and the macro rejects a braceless header naming more than one component. -`open` needs no extra attribute on the component: it works through the +`open` does not need an extra attribute on the component, because it works through the [`RedirectLookup`](../providers/redirect_lookup.md) impl that every `#[cgp_component]` already generates. It is a lightweight special case of the full [namespace](./cgp_namespace.md) feature, suited to a context wiring its own components directly, and it does not combine with a joined namespace where @@ -288,18 +287,19 @@ the component carries a `#[prefix(...)]`. ### The namespace statements -A couple of further statements opt a context into a [`cgp_namespace!`](./cgp_namespace.md), and both are -described in full on that page, where they are most often written. +The remaining statements opt a context into a [`cgp_namespace!`](./cgp_namespace.md), and that page +describes them in full, since they are most often written there. **`namespace SomeNamespace;`** joins the namespace, so every lookup the table does not wire directly -falls through to it. **`for in SomeTable { … }`** reads each entry of another lookup table -and emits one mapping per entry, which is how per-type defaults are adopted wholesale; its body holds -only `:` mappings, and an optional `where` clause on the loop constrains the entries it wires. +falls through to it. **`for in SomeTable { … }`** reads each entry of another lookup +table and emits one mapping per entry, which is how a context adopts per-type defaults wholesale. Its +body holds only `:` mappings, and an optional `where` clause on the loop constrains the entries it +wires. ### Statements come first **Every statement must precede every mapping.** Putting one after a mapping is a *parse* error, so the -message names the unexpected token rather than the ordering rule. Beyond that there is no restriction: +message names the unexpected token rather than the ordering rule. Beyond that the order is free: several statements may appear in any order, and they mix freely with the mappings that follow. ```rust @@ -320,14 +320,14 @@ delegate_components! { } ``` -Read as a whole, that is still one table. Every line lowers to the same pair of impls; the forms differ -only in how many entries a line produces and in what each entry resolves to. +Read as a whole, that is still one table. Every line lowers to the same pair of impls. The forms +differ only in how many entries a line produces and in what each entry resolves to. ### Attributes -The macro accepts **no attributes** anywhere: not on the table, not on a key, and not on a key inside a -`for` loop or a nested table. It rejects any it finds rather than ignoring them. Attribute-driven -variants such as `#[check_params(...)]` and `#[skip_check]` belong to +The macro **does not accept attributes** anywhere: not on the table, not on a key, and not on a key +inside a `for` loop or a nested table. It rejects any it finds rather than ignoring them. +Attribute-driven variants such as `#[check_params(...)]` and `#[skip_check]` belong to [`delegate_and_check_components!`](./delegate_and_check_components.md). ## Examples @@ -367,7 +367,7 @@ fn print_area(rect: &Rectangle) { ``` The benefit shows up when a second context wants the same capability answered differently. It -writes its own provider and its own table entry, and no code that calls `area()` changes: +writes its own provider and its own table entry, and the code that calls `area()` does not change: ```rust #[cgp_impl(new SquareArea)] @@ -391,8 +391,8 @@ delegate_components! { `Rectangle` and `Square` now both implement `CanCalculateArea`, through different providers reading different fields. A function generic over `CanCalculateArea` serves both without knowing that any of it -happened. Each context's choice stays one greppable line, which is all a reader needs to find to know -which implementation runs. +happened. Each context's choice stays one line a reader can search for, and finding that line tells +them which implementation runs. When one context needs a different provider *per type* rather than one provider outright, it opens the component and fills the slots: @@ -418,33 +418,33 @@ check the wiring**, because CGP's wiring is *lazy*: a table with a missing or wr compiles, and the failure only surfaces later, where the capability is used. - **Pair it with [`check_components!`](./check_components.md)** for anything beyond simple wiring. A - separate check gives you full control over what is asserted: concrete parameters for generic keys, + separate check gives you full control over what it asserts: concrete parameters for generic keys, per-provider layers, and opened or namespaced wiring. This is why larger codebases keep the two macros apart. - **Use [`delegate_and_check_components!`](./delegate_and_check_components.md)** when you are getting - started or the wiring is plain `Component: Provider` entries. It fuses the two so the check cannot be - forgotten. It accepts this whole grammar, but it derives checks only from mappings keyed on a - component *name*, so opened, redirected, and namespaced entries are wired and left unchecked with no - warning. -- **Use plain `delegate_components!` with no check** for an **aggregate provider** (the + started or the wiring is plain `Component: Provider` entries. It fuses the two so you cannot forget + the check. It accepts this whole grammar, but it derives checks only from mappings keyed on a + component *name*, so it wires opened, redirected, and namespaced entries and leaves them unchecked + without a warning. +- **Use plain `delegate_components!` without a check** for an **aggregate provider** (the [`new`-keyword form](#defining-the-target-at-the-same-time)). That target is a provider other contexts delegate to rather than a context in its own right, so a context-side check on it asks the wrong question: it either passes vacuously or blames the bundle for requirements a real context would have met. Verify it through a context that delegates to it instead. -A couple of choices inside the table are worth naming as well. Prefer the **`open` statement** over the legacy -nested `UseDelegate` table for per-type dispatch: it needs no separate table type and no wrapper. And -use a **[namespace](./cgp_namespace.md)** rather than a longer table once the same wiring is -repeated across contexts, or once one table has grown too long to read. Below that threshold, the -extra hop costs more than it saves. +Two more choices inside the table have a clear default. Prefer the **`open` statement** over the +legacy nested `UseDelegate` table for per-type dispatch, because it needs neither a separate table type +nor a wrapper. And use a **[namespace](./cgp_namespace.md)** rather than a longer table once the same +wiring is repeated across contexts, or once one table has grown too long to read. Below that +threshold, the extra hop costs more than it saves. -The one thing not to do is leave a context's wiring unchecked. Which macro you use to check it scales -with how complicated the wiring is; that it is checked somehow does not. +Never leave a context's wiring unchecked. The macro you use to check it depends on how complicated the +wiring is, but the need for a check does not. ## Under the hood -Each entry becomes a pair of impls. From the single-entry table above, first the -[`DelegateComponent`](../traits/wiring/delegate_component.md) impl that records the choice: +Each entry becomes a pair of impls. From the single-entry table above, the +[`DelegateComponent`](../traits/wiring/delegate_component.md) impl records the choice: ```rust impl DelegateComponent for Rectangle { @@ -457,8 +457,7 @@ That impl alone is the whole lookup. The provider blanket impl generated by from `RectangleArea`, and the consumer blanket impl then gives `Rectangle` the `CanCalculateArea` trait. The hand-written equivalent of one wiring entry is exactly that block. -Second, the [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl that forwards the provider's -requirements: +The [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl forwards the provider's requirements: ```rust impl<__Context__, __Params__> @@ -526,14 +525,14 @@ The [`RedirectLookup`](../providers/redirect_lookup.md) impl appends the dispatc path and reads the result back, so `MyApp: CanCalculateArea` resolves to `RectangleArea`. The tail of that key is a **generic `__Wildcard__` parameter rather than `Nil`**, and this makes it -work: the entry matches any path *beginning* with this component and this dispatch type, whatever the -lookup appends after it, so one entry answers the redirect without having to predict the exact length of -the path reaching it. +work. The entry matches any path *beginning* with this component and this dispatch type, whatever the +lookup appends after it. So one entry answers the redirect without having to predict the exact length +of the path reaching it. -One presentational quirk is worth knowing before you compare these listings against your own expansion. -Both paths above are [`PathCons`](../types/path_cons.md) lists, but `cargo cgp expand` prints -them differently: it resugars the header's redirect target to [`Path!`](./path.md) form while leaving -the per-entry key as the raw list. So the same kind of type appears in two spellings in one expansion. +Know one display difference before you compare these listings against your own expansion. Both paths +above are [`PathCons`](../types/path_cons.md) lists, but `cargo cgp expand` prints them differently. +It resugars the header's redirect target to [`Path!`](./path.md) form while leaving the per-entry key +as the raw list, so the same kind of type appears in two spellings in one expansion. **A grouped path key expands to the cartesian product**, one impl pair per combination, each keyed on a full prefix ending in `__Wildcard__`. So @@ -544,7 +543,7 @@ keys of different lengths. **A nested-table value lifts its inner table out** into its own definition, wiring the outer entry to `UseDelegate` over the generated type. So the legacy form is equivalent to writing two separate `delegate_components!` blocks, the inner one carrying `new`. Its per-value entries key on the same -parameter `open` keys on; the difference is only that they live in a separate table type. +parameter `open` keys on. The only difference is that they live in a separate table type. **The namespace statements** share one lowering: an impl generic over a `__Key__` and a `__Value__`, bounded on the namespace trait with a `Delegate = __Value__` binding. This makes the namespace's answer @@ -609,46 +608,48 @@ ProviderValue -> Type InnerTable -> IDENTIFIER BoundFreeGenerics? `{` TableBody `}` ``` -A leading `Generics` list makes the table generic over the target; `new` additionally emits the target -struct. The operator choice is independent of the key form: `:` maps a key to a provider, `->` delegates -to the value's own entry for that key, and `=>` redirects along a path. `NormalMapping` is named -separately because a `ForStmt` body admits only that form. +A leading `Generics` list makes the table generic over the target, and `new` additionally emits the +target struct. The operator choice is independent of the key form: `:` maps a key to a provider, `->` +delegates to the value's own entry for that key, and `=>` redirects along a path. `NormalMapping` is +named separately because a `ForStmt` body admits only that form. The grouping forms inside a `PathHead` differ in what they group and in whether the path may continue. A bracketed group holds alternative segments for one position and may be followed by `.` and -more path; a braced group holds alternative whole remainders and terminates the path, which is why only +more path. A braced group holds alternative whole remainders and terminates the path, which is why only the braced form can nest. Both expand to the cartesian product with the rest of the path. The segment productions differ in what they permit, which is why they are named apart. A -`KeySegment` (inside a `PathKey`) may carry its own generic list, and the parameters of every segment -along one path are merged onto that entry's impls. A `PathSegment` (inside a `PathValue`, the -right-hand side of a `=>`) carries none, and admits no groups. It is [`Path!`](./path.md)'s own -production, which keeps the two in step. And every `Generics` list on a key is an impl-position -list, so a bound is accepted (` WidthKey: WidthProvider`) and a parameter *default* is not: -`` fails with `invalid impl generics syntax`. +`KeySegment` (inside a `PathKey`) may carry its own generic list, and the macro merges the parameters +of every segment along one path onto that entry's impls. A `PathSegment` (inside a `PathValue`, the +right-hand side of a `=>`) cannot carry a generic list or a group. It is [`Path!`](./path.md)'s own +production, which keeps the two in step. And every `Generics` list on a key is an impl-position list, +so the parser accepts a bound (` WidthKey: WidthProvider`) and rejects a parameter +*default*: `` fails with `invalid impl generics syntax`. A `ProviderValue`'s nested-table form carries a full `TableBody`, so an inner table accepts every form an outer one does. An `InnerTable` is an identifier with an optional generic list rather than a full -`TargetType` (a nested table always names a fresh struct the macro declares), and its -`BoundFreeGenerics` is a definition-position list: no bounds, no defaults, and a `const` parameter -written as the bare name. Put a bound on the entry's own generics instead. A bound written on the inner -table is rejected as `expected ','`, because the value parser tries the nested-table form speculatively -and then falls back to reading the whole value as a plain type. An `OpenStmt` may omit its braces when -opening exactly one component. Every `Statement` precedes every `Mapping`. `NamespaceStmt` and -`ForStmt` are described under [`cgp_namespace!`](./cgp_namespace.md). The macro accepts no attributes -anywhere and rejects any it finds. +`TargetType`, because a nested table always names a fresh struct the macro declares. Its +`BoundFreeGenerics` is a definition-position list: it allows neither bounds nor defaults, and a `const` +parameter is written as the bare name. Put a bound on the entry's own generics instead. The parser +rejects a bound written on the inner table as `expected ','`, because the value parser tries the +nested-table form speculatively and then falls back to reading the whole value as a plain type. + +The remaining rules restate points made above. An `OpenStmt` may omit its braces when opening exactly +one component. Every `Statement` precedes every `Mapping`. [`cgp_namespace!`](./cgp_namespace.md) +describes `NamespaceStmt` and `ForStmt`. The macro does not accept attributes anywhere and rejects any +it finds. ## Common Mistakes **Wiring is lazy.** A table with a missing entry, or one naming a provider whose own dependencies are -unmet, still compiles. The failure appears later, at the place the capability is used, often as a long -error naming types you did not write. This is the single most common source of confusion with CGP, and -the answer is to check the table (see [`check_components!`](./check_components.md)) and to run -[`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`, which leads -with the root cause for the classes it recognizes. - -**Statements must lead the block**, and getting it wrong produces a misleading message. Once the -statements are consumed the parser expects only mappings, so it reads the `open` keyword as a *key* and +unmet, still compiles. The failure appears later, at the place where code uses the capability, often +as a long error naming types you did not write. This is the single most common source of confusion with CGP. The +answer is to check the table (see [`check_components!`](./check_components.md)) and to run +[`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`, which leads with the root cause +for the classes it recognizes. + +**Statements must lead the block**, and getting it wrong produces a misleading message. Once the parser +has consumed the statements it expects only mappings, so it reads the `open` keyword as a *key* and then complains about the component name where it wanted an operator: ```text @@ -659,9 +660,9 @@ The caret sits on the component being opened, so the message blames it rather th `open`, and never mentions the ordering rule. **`[…]` and `{…}` in a path are not the same group.** A bracketed group holds alternatives for one -segment and may be followed by more path; a braced group holds whole tails and ends the path. So -`@AreaCalculatorComponent.{String, u32}.bool: RectangleGeometry` does not parse, and the message says -nothing about groups: it reports the trailing `.bool` sitting where the operator should be: +segment and may be followed by more path. A braced group holds whole tails and ends the path. So +`@AreaCalculatorComponent.{String, u32}.bool: RectangleGeometry` does not parse, and the message does +not mention groups. It reports the trailing `.bool` sitting where the operator should be: ```text error: expected `:` @@ -670,8 +671,8 @@ error: expected `:` Use a bracketed group when the path must continue past the alternatives, and a braced group only at the end. -**Naming a provider struct that does not exist** is easy to do when a provider was written with -[`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared separately. The error +**Naming a provider struct that does not exist** is easy to do when you wrote a provider with +[`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared it separately. The error names an unresolved type rather than anything about wiring. **Two entries claiming one key conflict**, and the compiler reports it as a coherence error rather than From 57797ae9a818c87fbfb4c232ce7fc1087124d260 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 20:57:14 +0200 Subject: [PATCH 060/516] docs(reference/attributes): add #[impl_generics] and #[prefix] pages, correct #[default_impl] Give the two attributes that were routed to their host macro pages a page of their own, and fix the existing #[default_impl] page against the parser. - New pages impl_generics.md and prefix.md, following the six-section layout, with every claim verified against the macro source. - #[default_impl]: the grammar omitted the `@`-path key form (the key is a UniPathOrType), and the page claimed the attribute is not repeatable (each attribute emits one registration). Both corrected; path-key usage, example, and expansion added; Common Mistakes now carry the verified E0207 (generic impl) and E0119 (duplicate key) diagnostics. - Orphan-rule paragraphs on the #[default_impl] and DefaultImpls1 pages now state the rule the tests exercise: a local type must appear in the impl header ahead of the table parameter, either as the key or inside the namespace path; a path key never qualifies. - Re-point every mention of the three attributes to their own pages, collapse the explanations the #[cgp_fn] and cgp_namespace! pages duplicated into links, and note on #[cgp_type] and #[cgp_getter] that the component's companion attributes apply. - Both reference indexes updated; the "names you don't see" rows removed; sidebar renumbered. - example-code: compiled counterparts for the three attribute pages and nine compile-fail fixtures pinning the diagnostics the pages quote. Co-Authored-By: Claude Fable 5.1 --- docs/reference/attributes/default_impl.md | 137 ++++++- docs/reference/attributes/derive_delegate.md | 6 +- docs/reference/attributes/impl_generics.md | 299 ++++++++++++++ docs/reference/attributes/index.md | 21 +- docs/reference/attributes/prefix.md | 377 ++++++++++++++++++ docs/reference/attributes/use_type.md | 2 +- docs/reference/errors.md | 9 +- docs/reference/index.md | 11 +- docs/reference/macros/cgp_component.md | 9 +- docs/reference/macros/cgp_fn.md | 36 +- docs/reference/macros/cgp_getter.md | 3 + docs/reference/macros/cgp_impl.md | 7 +- docs/reference/macros/cgp_namespace.md | 35 +- docs/reference/macros/cgp_type.md | 6 +- docs/reference/macros/delegate_components.md | 2 +- docs/reference/providers/redirect_lookup.md | 18 +- .../traits/namespace/default_impls1.md | 19 +- .../traits/namespace/default_namespace.md | 9 +- docs/reference/traits/namespace/index.md | 2 +- example-code/README.md | 2 +- .../default_impl_rejected_duplicate_key.rs | 27 ++ ...default_impl_rejected_duplicate_key.stderr | 8 + .../default_impl_rejected_generic_impl.rs | 25 ++ .../default_impl_rejected_generic_impl.stderr | 8 + ...cs_rejected_bare_parameter_in_signature.rs | 15 + ...ejected_bare_parameter_in_signature.stderr | 5 + .../impl_generics_rejected_default.rs | 12 + .../impl_generics_rejected_default.stderr | 9 + ...enerics_rejected_parameter_in_signature.rs | 19 + ...ics_rejected_parameter_in_signature.stderr | 5 + ...rejected_parameter_named_after_function.rs | 15 + ...cted_parameter_named_after_function.stderr | 10 + ...nerics_rejected_unconstrained_parameter.rs | 13 + ...cs_rejected_unconstrained_parameter.stderr | 5 + .../prefix_rejected_duplicate_namespace.rs | 15 + ...prefix_rejected_duplicate_namespace.stderr | 10 + .../prefix_rejected_unbound_path.rs | 33 ++ .../prefix_rejected_unbound_path.stderr | 43 ++ .../reference/attributes/default_impl.rs | 229 +++++++++++ .../reference/attributes/impl_generics.rs | 176 ++++++++ .../tests/reference/attributes/mod.rs | 5 + .../tests/reference/attributes/prefix.rs | 293 ++++++++++++++ example-code/tests/reference/mod.rs | 1 + 43 files changed, 1881 insertions(+), 110 deletions(-) create mode 100644 docs/reference/attributes/impl_generics.md create mode 100644 docs/reference/attributes/prefix.md create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_default.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_default.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.stderr create mode 100644 example-code/tests/reference/attributes/default_impl.rs create mode 100644 example-code/tests/reference/attributes/impl_generics.rs create mode 100644 example-code/tests/reference/attributes/mod.rs create mode 100644 example-code/tests/reference/attributes/prefix.rs diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index d731197c..53768cb5 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -1,6 +1,6 @@ --- sidebar_label: '#[default_impl]' -sidebar_position: 7 +sidebar_position: 9 --- # `#[default_impl(...)]` @@ -48,6 +48,36 @@ impl DefaultImpls1 for String { That rule is worth internalizing, because the trait's own parameter names suggest the opposite arrangement (see [`DefaultImpls1`](../traits/namespace/default_impls1.md#the-one-thing-to-get-right)). +**The key is a type or a `@`-path.** A type key, as above, is the usual form for a per-type default: +the type is the value of the component's dispatch parameter, and the component is named inside the +lookup trait's arguments. A path key, in [`Path!`](../macros/path.md)'s syntax, binds the provider at a +full path inside the namespace. Its common use is a prefixed component's own path, so that a context +which joins the namespace resolves the component with no `for` loop at all: + +```rust +#[cgp_component(Greeter)] +#[prefix(@app in DefaultNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +#[default_impl(@app.GreeterComponent in AppNamespace)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} +``` + +Unlike [`#[prefix]`](./prefix.md), the macro appends nothing to a path key. You write the whole path, +marker included, and any dispatch type after it, as in `@test.ShowImplComponent.u32`. A path key +cannot declare generic parameters, and it takes neither of the `[…]` and `{…}` grouping forms a +[`delegate_components!`](../macros/delegate_components.md) key allows. + +**Repeat the attribute to register into several tables**, one attribute per table. The argument +itself is not comma-separated: each attribute carries exactly one `Key in NamespacePath` pair. + **The path may name any trait**, not only the three CGP ships. A trait of your own with the right shape works identically, which is why [`DefaultImpls2`](../traits/namespace/default_impls2.md) needed no new construct to be usable. @@ -102,6 +132,33 @@ delegate_components! { parameter. The loop wires every type with a registered default, and the direct `u64` line shadows whatever the namespace would otherwise supply for that one type. +A path key does not need a loop. With `CanGreet` registered under `@app` and `GreetHello` bound at +`@app.GreeterComponent` as in [Usage](#usage), a context resolves the component by joining the +namespace alone: + +```rust +cgp_namespace! { + new AppNamespace: DefaultNamespace {} +} + +pub struct App; + +delegate_components! { + App { + namespace AppNamespace; + } +} + +check_components! { + App { + GreeterComponent, + } +} +``` + +The prefix routes `GreeterComponent` to `@app.GreeterComponent`, and the registration answers that path +with `GreetHello`. + ## When to use it **Reach for it when a provider is the natural default for its key and you want that recorded where the @@ -116,12 +173,14 @@ provider is written.** - **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. **One constraint decides where the attribute may be written, and it is Rust's orphan rule rather than -anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, so a crate may register a default -when it owns either the namespace trait or the key type. For an unprefixed component the key is the -component's own marker, so a downstream crate owning the component can register into a foreign namespace. -For a [`#[prefix]`](../macros/cgp_namespace.md)-ed component the key is a path built from `cgp`-owned -types plus the marker, so the attribute is orphan-legal **only in the namespace's own crate**. Wiring -that must live downstream goes in the namespace body of the crate that owns it instead. +anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, and Rust accepts it when the +crate owns the namespace trait, or when a local type appears in the impl header ahead of the table +parameter. That local type may be the key itself, or a component named inside the namespace path, so a +crate that owns `ShowImplComponent` may write `String in DefaultImpls1` against the +foreign `DefaultImpls1`. A path key is a `PathCons` list, which is never a local type even when it +contains a local marker, so a [`#[prefix]`](./prefix.md)-ed component's path can be registered **only +in the namespace's own crate**. Wiring that must live downstream goes in the namespace body of the crate +that owns it, or into a local namespace that inherits the foreign one. ## Under the hood @@ -134,7 +193,18 @@ impl DefaultImpls1 for String { ``` The `Components` parameter is the table the lookup runs against, appended by the macro and left generic -so one registration serves every context. +so one registration serves every context. A path key emits the same impl for the path type, a +[`PathCons`](../types/path_cons.md) list that `cargo cgp expand` prints as `Path!(@app.GreeterComponent)`: + +```rust +impl AppNamespace for Path!(@app.GreeterComponent) { + type Delegate = GreetHello; +} +``` + +A context that joins `AppNamespace` resolves such a key without a loop: the join forwards every lookup +through the namespace, the component's prefix redirects `GreeterComponent` to the path, and this impl +answers it. **The registration impl carries only the parameters naming the key and the provider, plus the table, never the provider's own `where` clause.** That is deliberate, and it lets the attribute work with @@ -160,13 +230,21 @@ The attribute argument is a key type, the keyword `in`, and a namespace path, in [notation](https://doc.rust-lang.org/reference/notation.html): ```ebnf -DefaultImplArgs -> Type `in` TypePath +DefaultImplArgs -> Key `in` NamespacePath + +Key -> Type | Path + +Path -> `@` PathSegment ( `.` PathSegment )* +PathSegment -> Type + +NamespacePath -> TypePath GenericArgs? ``` -`Type` is the key that becomes the emitted impl's `Self`, and `TypePath` is the lookup trait with its -leading generic arguments written out. The table parameter is appended by the macro and must not be -given. The attribute takes exactly one such argument; it is neither comma-separated nor repeatable for -several tables on one provider. +`Key` is either a Rust `Type`, which becomes the emitted impl's `Self`, or a `Path`, which is +[`Path!`](../macros/path.md)'s own production and lowers to a `PathCons` list in the same position; the +leading `@` tells them apart. `NamespacePath` is the lookup trait with its leading generic arguments +written out. The table parameter is appended by the macro and must not be given. Each attribute takes +exactly one such argument, and the attribute may be repeated. ## Common Mistakes @@ -184,7 +262,32 @@ something to work around: put the wiring in the namespace body instead. [`DefaultImpls1`](../traits/namespace/default_impls1.md) and [`DefaultImpls2`](../traits/namespace/default_impls2.md) need `use cgp::core::component::…`; [`DefaultNamespace`](../traits/namespace/default_namespace.md) is in the prelude. -**It takes one argument and is not repeatable** for several tables on one provider. +**A provider whose impl is generic cannot register a default.** The registration impl copies the +provider impl's generic parameters but drops its `where` clause, so a parameter of the impl appears +nowhere in `impl DefaultImpls1 for String`: + +```text +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates + | + | impl ShowImpl { + | ^ unconstrained type parameter +``` + +This holds even when the provider struct is not generic. Write per-type defaults for concrete impls, +and wire a generic provider in a namespace body or directly on the context instead. + +**Two registrations for one key conflict.** Each emits an impl of the lookup trait for the same key, +and the compiler rejects the second, with both carets on the keys inside the attributes: + +```text +error[E0119]: conflicting implementations of trait `DefaultImpls1` for type `String` + | + | #[default_impl(String in DefaultImpls1)] + | ------ first implementation here +... + | #[default_impl(String in DefaultImpls1)] + | ^^^^^^ conflicting implementation for `String` +``` **A registered default is a fallback, not an assignment.** A context's direct entry silently shadows it. @@ -194,8 +297,10 @@ something to work around: put the wiring in the namespace body instead. worked out. - [`DefaultNamespace`](../traits/namespace/default_namespace.md) and [`DefaultImpls2`](../traits/namespace/default_impls2.md) — the component-only and two-type targets. -- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and documents - `#[prefix(...)]`. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines a namespace, and the path-key form's usual + target. +- [`#[prefix(...)]`](./prefix.md) — the component-side registration this attribute pairs with: it + routes, where this attribute binds. - [`delegate_components!`](../macros/delegate_components.md) — carries the `namespace` header and the `for … in` loop that consume a registration. - [`#[cgp_impl]`](../macros/cgp_impl.md) — the host this attribute goes on. diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 94c8fb81..3e7ba08a 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -1,6 +1,6 @@ --- sidebar_label: '#[derive_delegate]' -sidebar_position: 8 +sidebar_position: 10 --- # `#[derive_delegate]` @@ -275,8 +275,8 @@ error[E0119]: conflicting implementations of trait `DelegateComponent String { + format!("Hello, {name}!") +} +``` + +The `Greet` trait is not generic. A context qualifies by carrying a `name` field of some type that +implements `Display`, and the compiler resolves `Name` from that field's type. Nothing is wired, and +nothing is declared beyond the field itself. + +The cost is that the type is concealed rather than named. It exists only where a value of it flows +through an [`#[implicit]`](./implicit.md) argument, so nothing else can refer to it: not this +capability's own signature, not another capability, and not a second provider. When the type must be +named, promote it to an abstract type with [`#[cgp_type]`](../macros/cgp_type.md) and import it with +[`#[use_type]`](./use_type.md). [When to use it](#when-to-use-it) says where that line falls. + +## Usage + +Write the attribute beneath `#[cgp_fn]` and pass a comma-separated list of generic parameters, each +written as it would be inside an `impl<...>` list: + +```rust +#[cgp_fn] +#[impl_generics(Name: Display, Count: Display)] +pub fn describe(&self, #[implicit] name: &Name, #[implicit] count: &Count) -> String { + format!("{count} × {name}") +} +``` + +Each parameter joins the implementation's generic list, after the context parameter and after any +generics the function declares itself. A bound written inline, as `Name: Display` above, stays with +the parameter. A bound may also go in the function's own `where` clause, which lands on the +implementation as well. The attribute may be repeated, and the lists are concatenated, but one +attribute with a comma-separated list reads as one declaration and is the form to prefer. + +**Every parameter must be pinned by the type of an implicit argument.** The compiler accepts a +parameter on an impl only where the impl determines it, and the only place a `#[cgp_fn]` +implementation determines one is the field bound an `#[implicit]` argument produces. `&Name` pins +`Name`, and a nested position such as `&Pool` pins `Db`. A parameter absent from every implicit +argument is rejected with `E0207`; see [Common Mistakes](#common-mistakes). + +The list accepts a lifetime or a const parameter as well as a type parameter, because the macro reads +ordinary generic parameters. Type parameters are the case the attribute exists for. + +**Only [`#[cgp_fn]`](../macros/cgp_fn.md) reads `#[impl_generics]`.** A +[`#[cgp_impl]`](../macros/cgp_impl.md) block's own generic list is already impl-only, so a provider +declares such a parameter there directly. A [`#[cgp_component]`](../macros/cgp_component.md) has no +implementation of its own to carry one. + +## Examples + +A capability whose one type dependency each context fixes through a field: + +```rust +use cgp::prelude::*; +use core::fmt::Display; + +#[cgp_fn] +#[impl_generics(Name: Display)] +pub fn greet(&self, #[implicit] name: &Name) -> String { + format!("Hello, {name}!") +} + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +#[derive(HasField)] +pub struct Robot { + pub name: u32, +} + +pub fn greet_both(person: &Person, robot: &Robot) { + println!("{}", person.greet()); // Hello, Alice! + println!("{}", robot.greet()); // Hello, 42! +} +``` + +`Person` and `Robot` both implement `Greet` through the one blanket implementation, with nothing +wired. For `Person` the compiler resolves `Name` to `String`, and for `Robot` to `u32`. Neither type +appears anywhere except in the field. + +A capability built on `greet` never learns that `Name` exists: + +```rust +#[cgp_fn] +#[uses(Greet)] +pub fn announce(&self) -> String { + format!("{} Welcome aboard.", self.greet()) +} +``` + +Had `greet` taken `Name` as a function generic instead, `announce` would have to declare ``, +repeat `Name: Display`, and pass the parameter on to everything that calls it. + +## When to use it + +**Start with `#[impl_generics]` for a type that only ever flows through implicit arguments.** It is +the shortest form, it does not need wiring, and it reads as "this works with any `name` field of a +compatible type". Two conditions force a climb to an abstract type, and each is about needing to +*name* the type somewhere the inferred form cannot reach. + +- **The type appears in the capability's signature.** An impl-only parameter is not in scope on the + trait, so a return type or an explicit parameter cannot mention it. This condition arrives the + moment a capability hands a value of the type back to its caller. +- **Two capabilities must agree on the type.** A transaction type only means something relative to + its database, so the capability that opens one and the capability that commits it must mean the + same type. Each implementation infers its own parameter, so inferred parameters cannot state the + agreement. + +In both cases declare the type with [`#[cgp_type]`](../macros/cgp_type.md), import it with +[`#[use_type]`](./use_type.md), and let the context supply it by wiring. Do not answer either +condition with a generic parameter on the function. Such a parameter lands on the trait, so every +caller and every intermediate capability must declare it and repeat its bounds whether they touch it +or not. It also misplaces the decision: `` on a trait says the caller chooses the database type, +when the application determines it. + +Some neighbours cover what this attribute is not for. + +- **A bound on `Self`** is a capability dependency; write it with [`#[uses]`](./uses.md). +- **A bound on one of the trait's own parameters** that callers must see is + [`#[extend_where]`](./extend_where.md)'s job, on the trait side. +- **A type the caller should choose per call site** is a plain generic parameter on the function. + +## Under the hood + +The macro emits the trait without the parameter and the implementation with it. From the `greet` +input above: + +```rust +pub trait Greet { + fn greet(&self) -> String; +} + +impl<__Context__, Name: Display> Greet for __Context__ +where + Self: HasField, +{ + fn greet(&self) -> String { + let name: &Name = self.get_field(PhantomData::); + format!("Hello, {name}!") + } +} +``` + +The `Value = Name` binding makes the implementation legal. Rust accepts a parameter on an impl only +when the self type, the trait, or an associated-type binding in the `where` clause determines it, +and here the field bound from the implicit argument is that binding. The bound on `Name` travels with +the parameter, exactly as written. + +The parameter list is ordered. The context comes first, then any generics the function declared, +then the `#[impl_generics]` parameters, so a function `fn scale` with `#[impl_generics(Db)]` +emits `impl<__Context__, Scalar, Db>`. Rust requires lifetimes to lead a generic list, and the +emitted list keeps that rule whatever order the parameters were declared in. + +The `where` clause is ordered too: the function's own predicates first, then the bounds the +companion attributes contribute, then the `HasField` bounds from the implicit arguments, always last. +The parameter's name is yours. The context, by contrast, is literally `__Context__` in the emitted +code and appears as `Self` inside the implementation. + +## Formal grammar + +The attribute argument is a comma-separated list of generic parameters, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +ImplGenericsArgs -> GenericParam ( `,` GenericParam )* `,`? +``` + +`GenericParam` is the Rust grammar's own production for one entry of a generic parameter list: a +lifetime, a type parameter with optional bounds, or a const parameter. The list may be empty, and the +attribute may be repeated. Because the production is Rust's, a parameter default such as `T = u32` +parses, and the compiler then rejects it; see [Common Mistakes](#common-mistakes). + +## Common Mistakes + +**A parameter must be pinned by an implicit argument, or it is unconstrained.** The trait does not +mention it and neither does the self type, so only a field bound can determine it. Declaring `Name` +without reading a field whose type mentions `Name` fails at the implementation: + +```text +error[E0207]: the type parameter `Name` is not constrained by the impl trait, self type, or predicates +``` + +Either read a field whose type mentions the parameter, or, if the caller should choose the type, make +it a generic parameter on the function instead. + +**A parameter cannot appear in the capability's signature.** Only the implementation declares it, so a +return type or an explicit parameter that names it refers to nothing on the trait: + +```rust +#[cgp_fn] +#[impl_generics(Db: Database)] +pub fn fetch_row(&self, #[implicit] database: &Pool) -> Db::Row { /* ... */ } +``` + +```text +error[E0433]: cannot find type `Db` in this scope + | + | pub fn fetch_row(&self, #[implicit] database: &Pool) -> Db::Row { + | ^^ use of undeclared type `Db` +``` + +The `&Pool` argument is fine, because the macro strips it into a field bound on the +implementation, where `Db` is in scope. The `Db::Row` return type stays on the trait, and fails. A +bare `Db` in the signature reports the same headline under `E0425` instead, so search for both +codes. The fix is a decision the macro cannot make for you: promote the type to an +[abstract type](../macros/cgp_type.md) so it can be named everywhere, or keep `#[impl_generics]` and +stop naming it. The [compile errors](../errors.md#a-name-the-generated-code-cannot-see) page reads +the full diagnostic. + +**A parameter default parses and then fails.** `#[impl_generics(T = u32)]` is a valid +`GenericParam`, so the macro accepts it and copies it onto the implementation, where Rust forbids +defaults: + +```text +error: defaults for generic parameters are not allowed here +``` + +Drop the default. An implementation infers its parameters and cannot use one. + +**A parameter named after the function shadows the generated trait.** The trait takes the function's +name in PascalCase, so `fn count` with `#[impl_generics(Count: Display)]` puts a trait `Count` and a +parameter `Count` in the same scope, and inside the generated impl the trait's name resolves to the +parameter: + +```text +error[E0404]: expected trait, found type parameter `Count` + | + | #[impl_generics(Count: Display)] + | ----- found this type parameter + | pub fn count(&self, #[implicit] count: &Count) -> String { + | ^^^^^ not a trait +``` + +Rename the parameter, or give the trait another name with `#[cgp_fn(CanCount)]`. + +**On any host other than `#[cgp_fn]` the attribute is unknown**, rather than accepted and ignored. +Nothing consumes it, so it reaches the compiler as an attribute that does not exist: + +```text +error: cannot find attribute `impl_generics` in this scope +``` + +On a [`#[cgp_component]`](../macros/cgp_component.md) the error repeats once per item the macro +generates. On a [`#[cgp_impl]`](../macros/cgp_impl.md) block, delete the attribute and declare the +parameter in the block's own generic list, which is already impl-only. + +## Related constructs + +- [`#[implicit]`](./implicit.md) — the argument whose field type pins the parameter. +- [`#[cgp_fn]`](../macros/cgp_fn.md) — the only host, and where the generics split is explained. +- [`#[extend_where]`](./extend_where.md) — the trait-side sibling: a predicate callers must see. +- [`#[uses]`](./uses.md) — a capability bound on `Self`, the other kind of private requirement. +- [`#[use_type]`](./use_type.md) and [`#[cgp_type]`](../macros/cgp_type.md) — the abstract-type + form to climb to when the type must be named. +- [`HasField`](../traits/field-access/has_field.md) — the bound that carries the inference. + +The ideas behind it: + +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a requirement carried on the + implementation never reaches a caller. +- [Abstract types](/docs/concepts/abstract-types) — the other home for a type dependency. + +## Source + +- Parsing: [`types/attributes/function.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/function.rs) +- Insertion into the implementation's generic list: [`types/cgp_fn/preprocessed.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_fn/preprocessed.rs) +- Expansion snapshot: [`generic_components/fn_impl_generics.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/tests/cgp-tests/tests/generic_components/fn_impl_generics.rs) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index bf95cce4..bbe43082 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -37,11 +37,22 @@ must satisfy, the dependency a higher-order provider declares. trait rather than on the implementation, so every caller inherits it: `#[extend]` adds a supertrait, and `#[extend_where]` adds a `where` predicate a supertrait cannot express. -## Registering a namespace default - -[`#[default_impl]`](./default_impl.md) lets a provider register itself as a namespace's default for a -key, at the point where the provider is defined rather than in the namespace's own body. Reach for it -once per-type defaults accumulate. +## Naming a type the body needs + +[`#[impl_generics]`](./impl_generics.md) declares a generic parameter on the generated implementation +alone, for a type that a field of the context fixes: a database handle, a printable name. The trait +stays free of the parameter, so callers never name the type, and the compiler infers it from the field an +implicit argument reads. It is the first form to reach for when a body needs a type nobody chooses, and +[`#[use_type]`](./use_type.md) is the form to climb to once the type must be named in a signature. + +## Registering into a namespace + +Two attributes let a definition register itself into a [namespace](/docs/concepts/namespaces) at the +point where it is written, rather than in the namespace's own body. [`#[prefix]`](./prefix.md) goes on +a component and routes it under a path prefix, so contexts that join the namespace address it by that +path and a wiring table reads as a tree. [`#[default_impl]`](./default_impl.md) goes on a provider and +binds it as the namespace's default for a key. Reach for the prefix as soon as grouping helps a reader, +and for the default once per-type defaults accumulate. ## Legacy diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md new file mode 100644 index 00000000..95598832 --- /dev/null +++ b/docs/reference/attributes/prefix.md @@ -0,0 +1,377 @@ +--- +sidebar_label: '#[prefix]' +sidebar_position: 8 +--- + +# `#[prefix(...)]` + +Register a component into a namespace under a type-level path, so every context that joins the +namespace addresses the component by that path. + +## Overview + +A [namespace](/docs/concepts/namespaces) is a reusable wiring table that a **context**, the type the +capability runs against, joins with one line and then overrides where it needs to. A namespace answers +a lookup by *routing* it: asked for a component, it says where to look next. `#[prefix(...)]` is how +a component contributes its own route. Written on the component's trait beside +[`#[cgp_component]`](../macros/cgp_component.md), it registers the component into the named namespace +under a path prefix: + +```rust +#[cgp_component(Greeter)] +#[prefix(@app in AppNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} +``` + +Read that as: *in `AppNamespace`, `GreeterComponent` is found at `@app.GreeterComponent`.* A context +that joins `AppNamespace` and asks for `GreeterComponent` is sent to that path, and whatever is bound +there is the provider that runs. The attribute records only the route. A provider is bound at the +path somewhere else: by a direct `@app.GreeterComponent: GreetHello` entry on the context, by an +entry in the namespace's body, or by a [`#[default_impl]`](./default_impl.md) on a provider. + +Prefixes turn a flat wiring table into a tree. With components registered under `@app.auth`, +`@app.finance`, and `@app.error`, related entries sort together, a reader finds the auth wiring +without reading the finance wiring, and a library can register its components into a shared +namespace for applications it will never see. CGP's own components do this. `HasErrorType` and the +error components carry `#[prefix(@cgp.core.error in DefaultNamespace)]`, and the handler family +carries `#[prefix(@cgp.extra.handler in DefaultNamespace)]`. + +## Usage + +Apply the attribute to a trait that carries [`#[cgp_component]`](../macros/cgp_component.md), or one +of the macros built on it, [`#[cgp_type]`](../macros/cgp_type.md) and +[`#[cgp_getter]`](../macros/cgp_getter.md). The argument has two parts joined by the keyword `in`: + +```rust +#[prefix(@path.segments in NamespacePath)] +``` + +| Part | Meaning | +|---|---| +| `@path.segments` | The prefix: a `@`-sigil path of one or more dot-separated segments, in [`Path!`](../macros/path.md)'s syntax. The macro appends the component's marker after it. | +| `in` | Required keyword. | +| `NamespacePath` | The namespace to register into: `DefaultNamespace`, or one defined with [`cgp_namespace!`](../macros/cgp_namespace.md). It may be a qualified path and may carry generic arguments. | + +**The path is a prefix, and the macro appends the component marker for you.** +`#[prefix(@app in DefaultNamespace)]` on `CanGreet` registers `GreeterComponent` at +`@app.GreeterComponent`. Writing the marker yourself doubles it; see +[Common Mistakes](#common-mistakes). + +Segments follow [`Path!`](../macros/path.md)'s convention. A lowercase identifier that is not a +primitive type name becomes a type-level string, so `@app` and `@cgp.core.error` are strings. Any +other segment names a type, so `@MyApp.MyBarComponent` is two types. Case decides the meaning. A +segment cannot declare generic parameters, and the parser accepts neither of the `[…]` and `{…}` +grouping forms a [`delegate_components!`](../macros/delegate_components.md) key allows. One +attribute registers under exactly one prefix. + +**Repeat the attribute to register into several namespaces**, one attribute per namespace: + +```rust +#[cgp_component(BarProvider)] +#[prefix(@MyApp.MyBarComponent in MyNamespace)] +#[prefix(@my_app.MyBarComponent in OtherNamespace)] +pub trait Bar { + fn bar(&self); +} +``` + +**A component with type parameters is addressed with the parameters after the marker.** The lookup +appends them to the path, so a context joining the namespace wires a `CanShow` registered under +`@app` with entries such as `@app.ShowImplComponent.String: ShowWithDisplay`. Lifetime parameters +do not appear in the path. + +**Any crate may register its own components into any namespace.** The emitted impl is for the +component's marker, a type the component's crate owns, so Rust's orphan rule is satisfied even when +the namespace comes from another crate. That is why an application can register into +`DefaultNamespace`. It is also the difference from [`#[default_impl]`](./default_impl.md), whose key +on a prefixed component is a foreign path. + +### Choosing a prefix + +A prefix is part of the component's public surface, and expensive to change once wiring depends on +it, so choose it for every implementation the component might have rather than for the one in front +of you. Give components separate sub-paths whenever they are likely to need separate providers, even +when the current wiring happens to treat them alike. Abstract types belong under a `types` sub-path +of their layer, such as `@app.auth.types`, because a production context typically points the logic +under `@app.auth` at a database while leaving the types on the same concrete choices. + +Register prefixes into a **base** namespace, `DefaultNamespace` or a namespace that describes the +application's structure, and bind providers in a namespace that inherits it. A namespace's entry for +a key cannot be overridden once defined, so a namespace that held both the prefixes and one backend's +providers could not lend its prefixes to a second backend. + +## Examples + +A component registered under a prefix, a provider, and a context that joins the namespace and binds +the provider at the prefixed path: + +```rust +use cgp::prelude::*; + +#[cgp_component(Greeter)] +#[prefix(@app in DefaultNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} + +#[derive(HasField)] +pub struct App { + pub name: String, +} + +delegate_components! { + App { + namespace DefaultNamespace; + + @app.GreeterComponent: GreetHello, + } +} + +check_components! { + App { + GreeterComponent, + } +} +``` + +Reading the resolution: `app.greet()` looks up `GreeterComponent`. `App` does not wire it directly, +so the lookup falls through to `DefaultNamespace`, which redirects to `@app.GreeterComponent`, and +`App`'s own table binds that path to `GreetHello`. **Environmental context, self-targeted**: `App` +exists to carry the wiring and a `name` field, and the capability is about `App` itself. + +A second context joins the same namespace and binds a different provider at the same path, with +nothing repeated between the two: + +```rust +#[cgp_impl(new GreetFormally)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Good day, {name}.") + } +} + +#[derive(HasField)] +pub struct FormalApp { + pub name: String, +} + +delegate_components! { + FormalApp { + namespace DefaultNamespace; + + @app.GreeterComponent: GreetFormally, + } +} +``` + +The prefixes CGP's own components carry are wired the same way. A context that joins +`DefaultNamespace` chooses its error type and an error strategy by full path, with the dispatch type +of the generic `CanRaiseError` component written after its marker: + +```rust +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::ReturnError; + +pub struct Service; + +delegate_components! { + Service { + namespace DefaultNamespace; + + @cgp.core.error.ErrorTypeProviderComponent: UseType, + @cgp.core.error.ErrorRaiserComponent.String: ReturnError, + } +} +``` + +## When to use it + +**Reach for `#[prefix]` as soon as a wiring table has enough components that grouping helps a +reader.** It costs nothing at the point of use, it is the one namespace tool without a downstream +restriction, and it pays off at once in a table that reads as a directory listing. It is also the +form a library uses to publish its components into a shared namespace. + +Some situations call for something else. + +- **A component only ever wired directly on a context** needs no prefix. The `open` statement of + [`delegate_components!`](../macros/delegate_components.md) dispatches it per type without a + namespace, and the two do not combine on one component. +- **Binding a provider at a path** is the job of the wiring, not of the component. Use a direct entry + on the context, a [`cgp_namespace!`](../macros/cgp_namespace.md) body entry, or + [`#[default_impl]`](./default_impl.md) on the provider. +- **A small, explicitly delegated bundle** is an + [aggregate provider](../macros/delegate_components.md#defining-the-target-at-the-same-time), + which contexts adopt by delegating named components to it. Namespaces and prefixes earn their extra + indirection when there are many components, when inheritance is wanted, or when a library publishes + defaults for applications it does not know about. + +## Under the hood + +The attribute adds one impl to `#[cgp_component]`'s output, after the standard provider impls: an +impl of the namespace trait for the component marker, whose `Delegate` is a +[`RedirectLookup`](../providers/redirect_lookup.md) down the prefixed path. From +`#[prefix(@app in DefaultNamespace)]` on `CanGreet`: + +```rust +impl<__Components__> DefaultNamespace<__Components__> for GreeterComponent { + type Delegate = RedirectLookup<__Components__, Path!(@app.GreeterComponent)>; +} +``` + +`__Components__` is the table the lookup runs against. The macro appends it as the namespace trait's +last generic argument and leaves it generic, so one registration serves every context that joins. A +namespace defined with `cgp_namespace!` gets the same shape against its own trait: +`impl<__Components__> MyNamespace<__Components__> for BarProviderComponent`. + +The path is the prefix with the marker appended, a [`PathCons`](../types/path_cons.md) list. +`cargo cgp expand` prints it as `Path!(@app.GreeterComponent)`, and a raw compiler error prints the +underlying `PathCons>, PathCons>`. + +Resolution then runs in three hops. Joining the namespace emits, on the context, a blanket +`DelegateComponent` impl whose `Delegate` is whatever the namespace answers, so asking `App` for +`GreeterComponent` yields `RedirectLookup`. That provider's impl +of `Greeter` looks the path up in `App`'s own table, as `App: DelegateComponent`, and +forwards to the delegate it finds there, `GreetHello`. For a component with type parameters, +`RedirectLookup` appends the parameters to the path before the lookup, which is why per-type entries +carry them after the marker. + +The impl has the same shape as a `=>` entry written in a namespace body: +`GreeterComponent => @app.GreeterComponent` inside `cgp_namespace!` emits the same item. The +attribute lets the component's own crate contribute that entry, which a foreign crate could not write +into the namespace's body. + +Two details are easy to misread. The namespace's key is the *marker*, not the path, so a `help:` +list in an error names `GreeterComponent` as implementing the namespace trait even when the path it +routes to is empty. And a component marker declared with generics through the `name:` key of +`#[cgp_component]` carries those generics onto the impl after `__Components__`. + +## Formal grammar + +The attribute argument is a path, the keyword `in`, and a namespace path, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +PrefixArgs -> Path `in` NamespacePath + +Path -> `@` PathSegment ( `.` PathSegment )* +PathSegment -> Type + +NamespacePath -> TypePath GenericArgs? +``` + +`Path` is [`Path!`](../macros/path.md)'s own production: a leading `@`, then one or more segments, +each parsed as a Rust `Type` and encoded as a type-level string or a named type by the rule above. A +segment cannot declare generic parameters, and the parser does not accept the `[…]` and `{…}` groups +of a [`delegate_components!`](../macros/delegate_components.md) path key. `NamespacePath` is a Rust +type path with optional generic arguments, and the macro appends the table argument itself. Both +parts are required, the attribute takes exactly one such argument, and it is repeated for several +namespaces. + +## Common Mistakes + +**The marker is appended for you, so do not write it.** `#[prefix(@app.GreeterComponent in Ns)]` +registers the component at `@app.GreeterComponent.GreeterComponent`. It compiles, and a context that +binds `@app.GreeterComponent` then finds its entry never consulted, because the route and the binding +name different paths. Write the prefix alone. + +**Registering routes a component and binds nothing.** A prefixed component compiles even when +nothing binds its path, and so does a context that joins the namespace. Only a +[`check_components!`](../macros/check_components.md) reports it, as an unsatisfied bound on the +*path* rather than on a provider: + +```text +error[E0277]: the trait bound `PathCons>, PathCons>: DefaultNamespace` is not satisfied + | + | GreeterComponent, + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the following other types implement trait `DefaultNamespace`: + ErrorRaiserComponent + GreeterComponent +``` + +The `help:` list names `GreeterComponent` itself, which reads like a contradiction and is in fact the +diagnosis: the registration worked, and only the binding at the leaf is missing. + +The [compile errors](../errors.md#nothing-is-wired-there) page reads this diagnostic in full. The +fix is to bind a provider at the path: a direct entry on the context, a namespace body entry, or a +`#[default_impl]` on the provider. + +**Two attributes naming the same namespace conflict.** Each emits an impl of that namespace's trait +for the same marker, and the compiler rejects the second: + +```text +error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` +``` + +A component has one route per namespace. To reach it under two paths, define two namespaces. + +**`open` does not reach a prefixed component in a joined namespace.** `open` roots the route at the +bare marker, while the prefix routes under the path, so the per-type entries `open` expects are never +consulted. Write the entries with the full prefixed path instead, as +[`cgp_namespace!`](../macros/cgp_namespace.md#common-mistakes) explains. + +**Case decides a segment's meaning silently.** `@app` is a type-level string and `@App` is a type, +both are valid, and a capitalization slip routes to a path nothing binds. The failure surfaces as the +unbound path above, without a hint about the letter; see +[`Path!`](../macros/path.md#common-mistakes). + +**On `#[cgp_auto_getter]` the attribute is accepted and dropped.** That macro runs the same attribute +collector as `#[cgp_component]`, to apply `#[extend]` and `#[use_type]`, but it generates no +component to register, so a `#[prefix]` on it registers nothing and reports nothing. A getter that +must live in a namespace is a [`#[cgp_getter]`](../macros/cgp_getter.md) component. + +**On `#[cgp_impl]` or `#[cgp_fn]` the attribute is unknown.** Nothing consumes it there, so it +reaches the compiler as an attribute that does not exist: + +```text +error: cannot find attribute `prefix` in this scope +``` + +The provider-side counterpart is [`#[default_impl]`](./default_impl.md), which binds a provider at a +path rather than routing a component to one. + +## Related constructs + +- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines the namespaces a prefix registers into, + and the `=>` body entry that emits the same impl. +- [`delegate_components!`](../macros/delegate_components.md) — the `namespace` statement that joins, + and the `@`-path entries that bind a provider at a prefixed path. +- [`#[default_impl]`](./default_impl.md) — the provider-side registration: it binds, where this + attribute routes. +- [`DefaultNamespace`](../traits/namespace/default_namespace.md) — the built-in namespace CGP's own + components register into. +- [`RedirectLookup`](../providers/redirect_lookup.md) — the delegate every registration resolves + through. +- [`Path!`](../macros/path.md) and [`PathCons`](../types/path_cons.md) — the path syntax and the + type-level list it builds. +- [`#[cgp_component]`](../macros/cgp_component.md), [`#[cgp_type]`](../macros/cgp_type.md), and + [`#[cgp_getter]`](../macros/cgp_getter.md) — the hosts. +- [`check_components!`](../macros/check_components.md) — the only thing that catches a route bound to + nothing. + +The ideas behind it: + +- [Namespaces](/docs/concepts/namespaces) — reusable, inheritable wiring tables, and why presets need + no separate construct. + +## Source + +- The attribute: [`types/attributes/prefix.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/prefix.rs) +- Collection on the component: [`types/attributes/cgp_component_attributes.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/cgp_component_attributes.rs) +- Emission, after the standard provider impls: [`types/cgp_component/evaluated/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_component/evaluated/item.rs) +- A library use: [`has_error_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/traits/has_error_type.rs) +- Expansion snapshots: [`namespaces/`](https://github.com/contextgeneric/cgp/tree/main/crates/tests/cgp-tests/tests/namespaces/) + +--- + +*This page was written by an AI agent from the CGP knowledge base and verified against the library's source — see [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 236a5f58..6764694a 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -203,7 +203,7 @@ such as `Result` is therefore correct and idiomatic: the lo imported one bare. Finally, prefer an inferred parameter over an abstract type when the type only ever flows through values -the body reads: [`#[impl_generics]`](../macros/cgp_fn.md) on a `#[cgp_fn]` is shorter and needs no wiring. +the body reads: [`#[impl_generics]`](./impl_generics.md) on a `#[cgp_fn]` is shorter and needs no wiring. Climb to an abstract type when the type must be named in the capability's own signature, or when two capabilities have to [agree that they mean the same one](/docs/concepts/abstract-types#one-type-agreed-on-by-everything-that-needs-it). diff --git a/docs/reference/errors.md b/docs/reference/errors.md index b262605c..8c66b7f2 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -293,8 +293,8 @@ A neighbouring failure that reads like a dependency problem but is not: no provi rather than one being found whose requirements fail. The common case is a component registered into a [namespace](./macros/cgp_namespace.md) under a path that -nothing ever binds — a `#[prefix]` routes the lookup somewhere, and no `#[default_impl]`, namespace entry, -or direct wiring puts a provider there: +nothing ever binds: a [`#[prefix]`](./attributes/prefix.md) routes the lookup somewhere, and no +`#[default_impl]`, namespace entry, or direct wiring puts a provider there: ```text = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `@app.GreeterComponent` @@ -487,8 +487,9 @@ The caret lands on the name *you* wrote — the macro copies the identifier's sp ### A name the generated code cannot see -`#[impl_generics]` adds a parameter to the generated *impl* alone, so the generated trait cannot see it. -Naming it in the signature, which stays on the trait, refers to nothing: +[`#[impl_generics]`](./attributes/impl_generics.md) adds a parameter to the generated *impl* alone, so +the generated trait cannot see it. Naming it in the signature, which stays on the trait, refers to +nothing: ```text error[E0433]: cannot find type `Db` in this scope diff --git a/docs/reference/index.md b/docs/reference/index.md index 9bb4a615..3930b4cd 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -90,7 +90,9 @@ private to it. [`#[uses]`](./attributes/uses.md) imports the capabilities the bo provider — both landing on the implementation alone, so a caller never sees them. Where a requirement should instead be part of what the trait promises, [`#[extend]`](./attributes/extend.md) adds it as a supertrait and [`#[extend_where]`](./attributes/extend_where.md) as a predicate on the generated trait -itself. +itself. When the body needs a type that a field of the context fixes, +[`#[impl_generics]`](./attributes/impl_generics.md) declares the parameter on the implementation alone, +so callers never name it. ### Let each context choose a type @@ -188,8 +190,9 @@ through [`RedirectLookup`](./providers/redirect_lookup.md), which re-routes a lo [`Path!`](./macros/path.md), together with the three lookup traits that resolve inherited and per-type defaults — [`DefaultNamespace`](./traits/namespace/default_namespace.md) for a key that is a component alone, and [`DefaultImpls1`](./traits/namespace/default_impls1.md) and [`DefaultImpls2`](./traits/namespace/default_impls2.md) when the -key carries one further type or two. A provider registers itself as one of those defaults with -[`#[default_impl(...)]`](./attributes/default_impl.md). The `open` statement of +key carries one further type or two. A component registers into a namespace under a path prefix with +[`#[prefix(...)]`](./attributes/prefix.md), and a provider registers itself as one of those defaults +with [`#[default_impl(...)]`](./attributes/default_impl.md). The `open` statement of [`delegate_components!`](./macros/delegate_components.md) is a lightweight special case of the same mechanism, and it supersedes the older [`UseDelegate`](./providers/use_delegate.md) tables and the @@ -241,8 +244,6 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w | `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` | [`MapType`](./traits/type-level/map_type.md) | | `IsRef`, `IsMut`, `IsOwned` | [`MapTypeRef`](./traits/type-level/map_type_ref.md) | | `product!` (the value-level form) | [`Product!`](./macros/product.md) | -| `#[impl_generics(...)]` | [`#[cgp_fn]`](./macros/cgp_fn.md) | -| `#[prefix(...)]` | [`cgp_namespace!`](./macros/cgp_namespace.md) | | `#[check_trait(...)]`, `#[check_providers(...)]` | [`check_components!`](./macros/check_components.md) | | `#[check_params(...)]`, `#[skip_check]` | [`delegate_and_check_components!`](./macros/delegate_and_check_components.md) | diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 3a513abd..e4bb3fbc 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -104,7 +104,7 @@ comma-separated list inside one attribute. | [`#[use_type(Trait.Type)]`](../attributes/use_type.md) | Imports an abstract type: adds the supertrait *and* rewrites the bare name in your signatures | | [`#[extend(Trait)]`](../attributes/extend.md) | Adds a supertrait with no type to import | | [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) | Generates dispatch impls for a component generic over a parameter | -| [`#[prefix(@path in Namespace)]`](./cgp_namespace.md) | Registers the component into a namespace under a type-level path | +| [`#[prefix(@path in Namespace)]`](../attributes/prefix.md) | Registers the component into a namespace under a type-level path | When a component depends on a type another component supplies, most often the error type from [`HasErrorType`](../components/has_error_type.md), import it with `#[use_type]` rather than writing @@ -346,7 +346,7 @@ namespace impls one per attribute: [namespaces](./cgp_namespace.md) resolve through. - One [`UseDelegate`](../providers/use_delegate.md) impl per [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) attribute. -- One namespace impl per [`#[prefix(@path in Namespace)]`](./cgp_namespace.md) attribute, binding the +- One namespace impl per [`#[prefix(@path in Namespace)]`](../attributes/prefix.md) attribute, binding the component's key inside that namespace to a redirect down the given path. The `RedirectLookup` impl puts a component's own type parameters into a path, and it makes @@ -437,8 +437,9 @@ name gives, so the fix is to move the attribute rather than to add an import. - [`check_components!`](./check_components.md) — verifies that wiring at compile time. - [`#[cgp_type]`](./cgp_type.md) — the specialized form for a component that supplies a type. - [`#[cgp_getter]`](./cgp_getter.md) — the specialized form for a component that reads a field. -- [`#[use_type]`](../attributes/use_type.md), [`#[extend]`](../attributes/extend.md), and - [`#[derive_delegate]`](../attributes/derive_delegate.md) — attributes that change what it generates. +- [`#[use_type]`](../attributes/use_type.md), [`#[extend]`](../attributes/extend.md), + [`#[derive_delegate]`](../attributes/derive_delegate.md), and [`#[prefix]`](../attributes/prefix.md) — + attributes that change what it generates. The ideas behind it: diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 2771477c..31bba9f0 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -82,7 +82,7 @@ most of what you need to learn about the macro. |---|---| | A generic parameter on the function | Both the trait and the impl | | A `where` clause on the function | The impl only | -| [`#[impl_generics(T: Bound)]`](#a-type-the-caller-should-not-name) | The impl only | +| [`#[impl_generics(T: Bound)]`](../attributes/impl_generics.md) | The impl only | | [`#[extend_where(...)]`](../attributes/extend_where.md) | Both the trait and the impl | By default, generics land on both the trait and the impl, and the `where` clause lands on the impl @@ -104,8 +104,8 @@ where #### A type the caller should not name When the function needs a type that should be inferred rather than chosen, such as a database handle -or a displayable value, declare it with `#[impl_generics(...)]`. The parameter goes on the impl alone, -so the trait stays unparameterized and callers never mention it: +or a displayable value, declare it with [`#[impl_generics(...)]`](../attributes/impl_generics.md). +The parameter goes on the impl alone, so the trait stays unparameterized and callers never mention it: ```rust #[cgp_fn] @@ -118,12 +118,9 @@ pub fn describe(&self, #[implicit] name: &Name) -> String { The `Describe` trait is not generic. A context becomes eligible purely by carrying a `name` field of some `Display` type, and the compiler resolves the type from that field. -The cost is that the type is concealed rather than named. It exists only where a value of it flows -through an implicit argument, so nothing else can refer to it, including this function's own -signature. Naming it in a return type or an explicit parameter does not compile, as the -[Common Mistakes](#common-mistakes) explain. When the type must be nameable, or when two capabilities -have to agree that they mean the same type, promote it to an abstract type with -[`#[cgp_type]`](./cgp_type.md) and import it with [`#[use_type]`](../attributes/use_type.md). +The type is then concealed rather than named, so it cannot appear in this function's own signature, +and two capabilities cannot agree on it. The [`#[impl_generics]`](../attributes/impl_generics.md) +page says when to promote such a type to an abstract type instead. ### Companion attributes @@ -140,6 +137,8 @@ it depends on. rather than part of the interface. - [`#[extend_where(...)]`](../attributes/extend_where.md) puts a predicate on the generated trait's own `where` clause, for a bound callers need to see. +- [`#[impl_generics(...)]`](../attributes/impl_generics.md) declares a generic parameter on the + generated impl alone, for a type that a field of the context fixes and callers should never name. - [`#[use_provider(...)]`](../attributes/use_provider.md) completes an inner provider's bound when the function delegates to one. - [`#[async_trait]`](./async_trait.md) goes directly beneath `#[cgp_fn]` on an `async fn`. The macro @@ -204,7 +203,8 @@ Use something else in these cases: component instead. Make one decision inside the macro deliberately rather than by default: **where a type the body needs -should live.** Start with `#[impl_generics]` while the type only ever flows through implicit +should live.** Start with [`#[impl_generics]`](../attributes/impl_generics.md) while the type only +ever flows through implicit arguments. It is shorter, does not need wiring, and reads as "this works with any `database` field of a compatible type". Move up to an [abstract type](./cgp_type.md) when the type must appear in the capability's own signature, or when two capabilities must agree that they mean the same one. Avoid a @@ -330,17 +330,11 @@ error: a `&mut` implicit argument must be the only implicit argument, since its ``` **An `#[impl_generics]` parameter cannot appear in the capability's own signature.** Only the generated -impl declares it, so naming it in a return type or an explicit parameter leaves it unresolved in the -trait. A bare `Db` reports: - -```text -error[E0425]: cannot find type `Db` in this scope -``` - -A qualified path such as `Db::Row` reports `E0433` instead, and the compiler labels its span *use of -undeclared type `Db`*. The code differs, and that matters because you are likely to search for it. -Both mean the same thing: either the type belongs out of the signature, or it needs to be an -[abstract type](./cgp_type.md) rather than an inferred impl parameter. +impl declares it, so a return type or an explicit parameter that names it leaves it unresolved in the +trait. A bare `Db` reports `E0425` and a qualified path such as `Db::Row` reports `E0433`, both under +the headline *cannot find type `Db` in this scope*, so search for both codes. Either the type belongs +out of the signature, or it needs to be an [abstract type](./cgp_type.md) rather than an inferred impl +parameter. The [`#[impl_generics]`](../attributes/impl_generics.md) page shows both diagnostics. ## Related constructs diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index e72bef7b..674355ce 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -57,6 +57,9 @@ and derives one from the **trait** name: a leading `Has` is stripped and `Getter yields the provider trait `NameGetter` and the marker `NameGetterComponent`. The macro is therefore at its most ergonomic when getter traits follow the `Has{Field}` convention. +The companion attributes of `#[cgp_component]` apply here too, so +[`#[prefix(...)]`](../attributes/prefix.md) registers the getter into a namespace. + Pass an identifier to override it, as with `#[cgp_component]`: ```rust diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 0c4ad32d..ac7a3989 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -189,9 +189,10 @@ attribute, which is the form to prefer: `#[uses(HasName, CanRaiseError)] dependency list. `#[use_provider]` is the exception because its own argument already ends in a bound list, so the parser could not tell where a second pair begins. Write one attribute per inner provider. -`#[cgp_impl]` does not read `#[extend]`, `#[extend_where]`, or `#[impl_generics]`, although you may -see them on other CGP macros. Each of them acts on a *generated trait definition*, which a provider -impl does not have, so they belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to +`#[cgp_impl]` does not read `#[extend]`, `#[extend_where]`, or +[`#[impl_generics]`](../attributes/impl_generics.md), although you may see them on other CGP macros. +Each of them acts on a *generated trait definition*, which a provider impl does not have, so they +belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to [`#[cgp_component]`](./cgp_component.md). Writing one here leaves a name nothing resolves; see [Common Mistakes](#common-mistakes). An impl-side bound that really is impl-side goes in the block's own `where` clause, which passes through untouched. diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 4858884e..5a30206d 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -112,7 +112,8 @@ the one above reroutes a whole subtree of the parent's namespace rather than a s ### The other two halves: registering, and joining Defining a namespace is only one part of the pattern. A component **registers into** one with the -`#[prefix(...)]` attribute on its trait, which puts that component's lookups under a path: +[`#[prefix(...)]`](../attributes/prefix.md) attribute on its trait, which puts that component's +lookups under a path: ```rust #[cgp_component(ShowImpl)] @@ -270,18 +271,11 @@ inside whatever `__Table__` is". The namespace names no provider; it only rerout decided wherever the path finally lands. A `:` entry skips the indirection and maps the key straight to a provider, one impl per key when the array form is used. -`#[prefix(...)]` is the other side of this, and it generates an impl of exactly the same shape. From -`#[prefix(@show in AppNamespace)]` on a `CanShow` component: - -```rust -impl<__Components__> AppNamespace<__Components__> for ShowImplComponent { - type Delegate = RedirectLookup<__Components__, Path!(@show.ShowImplComponent)>; -} -``` - -So the component contributes its own route into the namespace, under the prefix, ending at its own component -name. That is why a joining context binds `@show.ShowImplComponent` rather than the bare component. A -component may carry several `#[prefix]` attributes to register into several namespaces. +[`#[prefix(...)]`](../attributes/prefix.md) is the other side of this, and it generates an impl of +exactly the same shape for the component's marker, with the path ending at the component's own name. +So `#[prefix(@show in AppNamespace)]` on a `CanShow` component routes `ShowImplComponent` to +`@show.ShowImplComponent`, which is why a joining context binds that path rather than the bare +component. The attribute's page shows the emitted impl. When a parent is named, the macro prepends a blanket impl forwarding every key the parent resolves: @@ -332,17 +326,8 @@ and its optional `where` clause is merged into every impl the loop generates. Li `delegate_components!`, the body accepts **no attributes** on any entry and rejects any it finds. The `#[prefix(...)]` attribute, which registers a component into a namespace and is written on a -[`#[cgp_component]`](./cgp_component.md) trait, has a grammar of its own: - -```ebnf -PrefixArgs -> Path `in` NamespacePath - -NamespacePath -> TypePath GenericArgs? -``` - -`Path` is [`Path!`](./path.md)'s own `@`-prefixed dotted production, so its segments take no generics and -neither grouping form is accepted: one attribute registers under exactly one prefix, and the attribute -is repeated to register into several namespaces. `NamespacePath` may itself be parameterized. +[`#[cgp_component]`](./cgp_component.md) trait, has a grammar of its own, given on +[its page](../attributes/prefix.md#formal-grammar). ## Common Mistakes @@ -408,6 +393,8 @@ the context. - [`RedirectLookup`](../providers/redirect_lookup.md) — the provider every redirect resolves through. - [`DefaultNamespace`](../traits/namespace/default_namespace.md) — inherited and per-type default resolution, including `#[default_impl(...)]`. +- [`#[prefix(...)]`](../attributes/prefix.md) — registers a component into a namespace under a path + prefix, the other half of the pattern. - [`#[cgp_component]`](./cgp_component.md) — the host of the `#[prefix(...)]` attribute. - [`DelegateComponent`](../traits/wiring/delegate_component.md) — the per-key table a redirect finally walks. - [`check_components!`](./check_components.md) — the only thing that catches a route bound to nothing. diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 503e4122..1ac6fc1d 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -57,6 +57,10 @@ Like [`#[cgp_component]`](./cgp_component.md), the component needs a provider tr `ScalarTypeProviderComponent`. This is worth fixing in mind, because every other macro derives its default from the trait name. +The companion attributes of `#[cgp_component]` apply unchanged, so +[`#[prefix(...)]`](../attributes/prefix.md) registers the abstract type into a namespace. CGP's own +`HasErrorType` carries `#[prefix(@cgp.core.error in DefaultNamespace)]` this way. + Pass an identifier to override it, exactly as with `#[cgp_component]`: ```rust @@ -160,7 +164,7 @@ there is a cheaper option that does more than it looks. - **Prefer an inferred impl parameter while the type only flows through values.** If the type appears solely because a provider reads a field of it, - [`#[impl_generics]`](./cgp_fn.md#a-type-the-caller-should-not-name) on a `#[cgp_fn]` puts a parameter on + [`#[impl_generics]`](../attributes/impl_generics.md) on a `#[cgp_fn]` puts a parameter on the implementation alone. Nothing is wired, nothing is declared, and a context qualifies just by carrying a field of a compatible type. - **Move up to an abstract type when the type must be nameable.** Two things force it: the capability's own diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 8aa46bae..ecbfdaae 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -283,7 +283,7 @@ and the macro rejects a braceless header naming more than one component. [`RedirectLookup`](../providers/redirect_lookup.md) impl that every `#[cgp_component]` already generates. It is a lightweight special case of the full [namespace](./cgp_namespace.md) feature, suited to a context wiring its own components directly, and it does not combine with a joined namespace where -the component carries a `#[prefix(...)]`. +the component carries a [`#[prefix(...)]`](../attributes/prefix.md). ### The namespace statements diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 0a59089b..82e70b87 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -14,7 +14,7 @@ and `open`. **You are not expected to write `RedirectLookup` entries.** [`#[cgp_component]`](../macros/cgp_component.md) generates a `RedirectLookup` impl for every component, -and the [`#[prefix]`](../macros/cgp_namespace.md) attribute and the `open` and `namespace` statements of +and the [`#[prefix]`](../attributes/prefix.md) attribute and the `open` and `namespace` statements of [`delegate_components!`](../macros/delegate_components.md) generate the delegation entries that target it. This page explains what those generated entries *are*, so that an expansion or a wiring error naming this provider is legible. @@ -47,7 +47,7 @@ generated entries is where this provider appears. Like every CGP provider, it ca `RedirectLookup` is in the prelude, but you do not name it directly. It appears where the namespace and `open` machinery generate it. A component is registered under a path with the -[`#[prefix(@path in Namespace)]`](../macros/cgp_namespace.md) attribute, and a context joins a namespace +[`#[prefix(@path in Namespace)]`](../attributes/prefix.md) attribute, and a context joins a namespace or opens a component for per-type dispatch: ```rust @@ -139,17 +139,19 @@ delegate. When the consumer trait carries generic type parameters, the impl addi the lookup, letting the redirected key encode the generic arguments. As always, the impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl. -The `#[prefix(@path in Namespace)]` attribute populates the path side: it generates a namespace -impl whose delegate is `RedirectLookup`, with the prefix path joined onto the -component marker, so resolving the component under that namespace follows the prefixed path into the -table. +The [`#[prefix(@path in Namespace)]`](../attributes/prefix.md) attribute populates the path side: it +generates a namespace impl whose delegate is `RedirectLookup`, with the prefix path +joined onto the component marker, so resolving the component under that namespace follows the +prefixed path into the table. ## Related constructs - [`#[cgp_component]`](../macros/cgp_component.md) — generates a `RedirectLookup` impl for every component. -- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines namespaces and the `#[prefix]` attribute that - target `RedirectLookup`. +- [`cgp_namespace!`](../macros/cgp_namespace.md) — defines the namespaces whose entries target + `RedirectLookup`. +- [`#[prefix]`](../attributes/prefix.md) — registers a component under a path that resolves through + it. - [`delegate_components!`](../macros/delegate_components.md) — the `open` and `namespace` statements that generate the redirect entries. - [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table the lookup reads. diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index 523ca83d..cb8fa748 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -152,7 +152,7 @@ same projection. **Use it for a per-type default, and reach for the simpler trait when the key is a component alone.** - **[`DefaultNamespace`](./default_namespace.md)** when one component has one default. That is the common - case, and it is what [`#[prefix(...)]`](../../macros/cgp_namespace.md) registers a component into. + case, and it is what [`#[prefix(...)]`](../../attributes/prefix.md) registers a component into. - **`DefaultImpls1`** when the same component resolves differently per type. [`#[default_impl]`](../../attributes/default_impl.md) is usually pointed at it. - **[`DefaultImpls2`](./default_impls2.md)** for a two-type key. @@ -161,12 +161,14 @@ same projection. rather than the only options. **One constraint decides where a `#[default_impl]` may be written, and it is Rust's orphan rule rather -than anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, so a crate may register a -default when it owns either the namespace trait or the key type. For an unprefixed component the key is -the component's own marker, so a downstream crate owning the component can register into a foreign -namespace. For a [`#[prefix]`](../../macros/cgp_namespace.md)-ed component the key is a path built from -`cgp`-owned types plus the marker, so the impl is orphan-legal **only in the namespace's own crate**. -Wiring that must live downstream goes in the namespace body of the crate that owns it instead. +than anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, and Rust accepts it when +the crate owns the namespace trait, or when a local type appears in the impl header ahead of the table +parameter. That local type may be the key itself, or the component named inside the namespace path, so +a crate that owns `ShowImplComponent` may write `String in DefaultImpls1` against +the foreign `DefaultImpls1`. A path key is a `PathCons` list, which is never a local type even when it +contains a local marker, so a [`#[prefix]`](../../attributes/prefix.md)-ed component's path can be +registered **only in the namespace's own crate**. Wiring that must live downstream goes in the namespace +body of the crate that owns it, or into a local namespace that inherits the foreign one. ## Under the hood @@ -213,7 +215,8 @@ where the provider is used rather than where it is registered. - [`DefaultNamespace`](./default_namespace.md): the one-key form, and the common case. - [`DefaultImpls2`](./default_impls2.md): the two-type form. - [`#[default_impl(...)]`](../../attributes/default_impl.md): the attribute that emits impls of this trait. -- [`cgp_namespace!`](../../macros/cgp_namespace.md): defines a namespace, and documents `#[prefix(...)]`. +- [`cgp_namespace!`](../../macros/cgp_namespace.md): defines a namespace. +- [`#[prefix(...)]`](../../attributes/prefix.md): registers a component into a namespace under a path. - [`delegate_components!`](../../macros/delegate_components.md): carries the `for … in` loop. - [`DelegateComponent`](../wiring/delegate_component.md): what the loop ultimately writes. - [`IsProviderFor`](../wiring/is_provider_for.md): where a registered provider's real bounds are checked. diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index 33a50fcc..e59fe072 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -13,7 +13,7 @@ Resolving a namespace's default provider for a component. **You do not implement `DefaultNamespace`.** [`cgp_namespace!`](../../macros/cgp_namespace.md) and its -[`#[prefix(...)]`](../../macros/cgp_namespace.md) attribute emit the impls. You name the trait in exactly +[`#[prefix(...)]`](../../attributes/prefix.md) attribute emit the impls. You name the trait in exactly one place, a `namespace` header inside [`delegate_components!`](../../macros/delegate_components.md), and this page explains what that header generates, including why a direct entry can shadow an inherited default without conflicting with it. @@ -65,7 +65,7 @@ delegate_components! { ``` after which every lookup `App` does not wire directly forwards through the namespace. A component -registers into one with the [`#[prefix(...)]`](../../macros/cgp_namespace.md) attribute on its +registers into one with the [`#[prefix(...)]`](../../attributes/prefix.md) attribute on its `#[cgp_component]` trait. ## Examples @@ -102,7 +102,7 @@ the inheritance-with-override shape presets rely on. where the syntax requires it.** It appears in a `namespace` header and nowhere else in ordinary code. - **Use `DefaultNamespace`** for a namespace whose defaults are per component, which is the common case - and what [`#[prefix(...)]`](../../macros/cgp_namespace.md) registers into. + and what [`#[prefix(...)]`](../../attributes/prefix.md) registers into. - **Use [`DefaultImpls1`](./default_impls1.md)** for a per-type default, where one component resolves differently per type. - **Define your own namespace trait instead** when you want a named table of your own; @@ -164,7 +164,8 @@ type takes the `Self` position instead. The inconsistency is the family's sharpe per-pair variants. - [`#[default_impl(...)]`](../../attributes/default_impl.md): the attribute that registers a provider as a default. -- [`cgp_namespace!`](../../macros/cgp_namespace.md): defines a namespace, and documents `#[prefix(...)]`. +- [`cgp_namespace!`](../../macros/cgp_namespace.md): defines a namespace. +- [`#[prefix(...)]`](../../attributes/prefix.md): registers a component into a namespace under a path. - [`delegate_components!`](../../macros/delegate_components.md): carries the `namespace` header. - [`DelegateComponent`](../wiring/delegate_component.md): what a namespace header forwards *into*. - [`IsProviderFor`](../wiring/is_provider_for.md): forwarded alongside, so dependency errors stay readable. diff --git a/docs/reference/traits/namespace/index.md b/docs/reference/traits/namespace/index.md index 80277ea2..77a5314f 100644 --- a/docs/reference/traits/namespace/index.md +++ b/docs/reference/traits/namespace/index.md @@ -17,7 +17,7 @@ inside [`delegate_components!`](../../macros/delegate_components.md), and the [`#[default_impl]`](../../attributes/default_impl.md) attribute. The macros generate the impls. - [`DefaultNamespace`](default_namespace.md) keys a default on the component alone, the common case that - [`#[prefix(...)]`](../../macros/cgp_namespace.md) registers into. It is the one member of the group + [`#[prefix(...)]`](../../attributes/prefix.md) registers into. It is the one member of the group that is in the prelude. - [`DefaultImpls1`](default_impls1.md) adds one further type, for a per-type default where the same component resolves differently for `String` than for `u64`. diff --git a/example-code/README.md b/example-code/README.md index d5046070..45c30362 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -30,7 +30,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, `macros/delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/tutorials/` | none yet | | front page, orientation pages | none yet | diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.rs b/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.rs new file mode 100644 index 00000000..64eb9c37 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.rs @@ -0,0 +1,27 @@ +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; + +#[cgp_component(ShowImpl)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} + +// error[E0119]: conflicting implementations of trait `DefaultImpls1` for +// type `String` +#[cgp_impl(new ShowStringLoudly)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.to_uppercase() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.stderr new file mode 100644 index 00000000..3c87d382 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.stderr @@ -0,0 +1,8 @@ +error[E0119]: conflicting implementations of trait `DefaultImpls1` for type `String` + --> tests/compile_fail/reference/attributes/default_impl_rejected_duplicate_key.rs:20:16 + | +10 | #[default_impl(String in DefaultImpls1)] + | ------ first implementation here +... +20 | #[default_impl(String in DefaultImpls1)] + | ^^^^^^ conflicting implementation for `String` diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.rs b/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.rs new file mode 100644 index 00000000..7249ddd7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.rs @@ -0,0 +1,25 @@ +use core::fmt::Display; + +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; + +#[cgp_component(ShowImpl)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +// error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or +// predicates +// +// The registration impl copies the provider impl's generic parameters but drops its `where` +// clause, and nothing in `impl DefaultImpls1 for String { type Delegate = +// ShowWithDisplay; }` mentions `T`. +#[cgp_impl(new ShowWithDisplay)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + format!("{value}") + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.stderr new file mode 100644 index 00000000..9003ee3f --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.stderr @@ -0,0 +1,8 @@ +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/attributes/default_impl_rejected_generic_impl.rs:19:6 + | +17 | #[cgp_impl(new ShowWithDisplay)] + | -------------------------------- help: remove the unused type parameter `T` +18 | #[default_impl(String in DefaultImpls1)] +19 | impl ShowImpl { + | ^ unconstrained type parameter diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.rs b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.rs new file mode 100644 index 00000000..83d7ddd6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.rs @@ -0,0 +1,15 @@ +use core::fmt::Display; + +use cgp::prelude::*; + +// error[E0425]: cannot find type `Name` in this scope +// +// The same failure as `impl_generics_rejected_parameter_in_signature.rs`, with the parameter named +// bare rather than as the qualifier of a path, which the compiler reports under a different code. +#[cgp_fn] +#[impl_generics(Name: Display + Clone)] +pub fn owned_name(&self, #[implicit] name: &Name) -> Name { + name.clone() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.stderr b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.stderr new file mode 100644 index 00000000..8d31db5c --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.stderr @@ -0,0 +1,5 @@ +error[E0425]: cannot find type `Name` in this scope + --> tests/compile_fail/reference/attributes/impl_generics_rejected_bare_parameter_in_signature.rs:11:54 + | +11 | pub fn owned_name(&self, #[implicit] name: &Name) -> Name { + | ^^^^ not found in this scope diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_default.rs b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_default.rs new file mode 100644 index 00000000..426186bf --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_default.rs @@ -0,0 +1,12 @@ +use core::fmt::Display; + +use cgp::prelude::*; + +// error: defaults for generic parameters are not allowed here +#[cgp_fn] +#[impl_generics(Total: Display = u32)] +pub fn describe_total(&self, #[implicit] total: &Total) -> String { + format!("{total}") +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_default.stderr b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_default.stderr new file mode 100644 index 00000000..844383f8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_default.stderr @@ -0,0 +1,9 @@ +error: defaults for generic parameters are not allowed here + --> tests/compile_fail/reference/attributes/impl_generics_rejected_default.rs:7:17 + | +7 | #[impl_generics(Total: Display = u32)] + | ^^^^^^^^^^^^^^^^^^^^ + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #36887 + = note: `#[deny(invalid_type_param_default)]` (part of `#[deny(future_incompatible)]`) on by default diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.rs b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.rs new file mode 100644 index 00000000..7dc8fbe2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.rs @@ -0,0 +1,19 @@ +use core::marker::PhantomData; + +use cgp::prelude::*; + +pub trait Database { + type Row; +} + +pub struct Pool(PhantomData); + +// error[E0433]: cannot find type `Db` in this scope +#[cgp_fn] +#[impl_generics(Db: Database)] +pub fn fetch_row(&self, #[implicit] database: &Pool) -> Db::Row { + let _ = database; + todo!() // the page elides this body +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.stderr b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.stderr new file mode 100644 index 00000000..37ef6f1f --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.stderr @@ -0,0 +1,5 @@ +error[E0433]: cannot find type `Db` in this scope + --> tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_in_signature.rs:14:61 + | +14 | pub fn fetch_row(&self, #[implicit] database: &Pool) -> Db::Row { + | ^^ use of undeclared type `Db` diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.rs b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.rs new file mode 100644 index 00000000..141d8cae --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.rs @@ -0,0 +1,15 @@ +use core::fmt::Display; + +use cgp::prelude::*; + +// error[E0404]: expected trait, found type parameter `Count` +// +// The generated trait is named `Count` after the function, and so is the parameter, so inside the +// generated impl the trait's name resolves to the parameter. +#[cgp_fn] +#[impl_generics(Count: Display)] +pub fn count(&self, #[implicit] count: &Count) -> String { + format!("{count}") +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.stderr b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.stderr new file mode 100644 index 00000000..80826ff8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.stderr @@ -0,0 +1,10 @@ +error[E0404]: expected trait, found type parameter `Count` + --> tests/compile_fail/reference/attributes/impl_generics_rejected_parameter_named_after_function.rs:11:8 + | +10 | #[impl_generics(Count: Display)] + | ----- found this type parameter +11 | pub fn count(&self, #[implicit] count: &Count) -> String { + | ^^^^^ + | | + | you might have meant to refer to this trait + | not a trait diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs new file mode 100644 index 00000000..afe60f54 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs @@ -0,0 +1,13 @@ +use core::fmt::Display; + +use cgp::prelude::*; + +// error[E0207]: the type parameter `Name` is not constrained by the impl trait, self type, or +// predicates +#[cgp_fn] +#[impl_generics(Name: Display)] +pub fn greet(&self, #[implicit] label: &str) -> String { + format!("Hello, {label}!") +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.stderr b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.stderr new file mode 100644 index 00000000..46532381 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.stderr @@ -0,0 +1,5 @@ +error[E0207]: the type parameter `Name` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs:8:17 + | +8 | #[impl_generics(Name: Display)] + | ^^^^ unconstrained type parameter diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs new file mode 100644 index 00000000..410b922f --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs @@ -0,0 +1,15 @@ +use cgp::prelude::*; + +cgp_namespace! { + new AppNamespace {} +} + +// error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` +#[cgp_component(Greeter)] +#[prefix(@app in AppNamespace)] +#[prefix(@other in AppNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.stderr b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.stderr new file mode 100644 index 00000000..b0f71b33 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.stderr @@ -0,0 +1,10 @@ +error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` + --> tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs:8:1 + | +8 | #[cgp_component(Greeter)] + | ^^^^^^^^^^^^^^^^^^^^^^^ + | | + | first implementation here + | conflicting implementation for `GreeterComponent` + | + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.rs b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.rs new file mode 100644 index 00000000..84d07f79 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.rs @@ -0,0 +1,33 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +#[prefix(@app in DefaultNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +pub struct App; + +// App joins the namespace, so the lookup follows the redirect to `@app.GreeterComponent`, but +// nothing binds a provider at that path. +delegate_components! { + App { + namespace DefaultNamespace; + } +} + +// error[E0277]: the trait bound `PathCons<...>: DefaultNamespace` is not satisfied +check_components! { + App { + GreeterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.stderr b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.stderr new file mode 100644 index 00000000..01491efa --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.stderr @@ -0,0 +1,43 @@ +error[E0277]: the trait bound `PathCons>>>, PathCons>: cgp::prelude::DefaultNamespace` is not satisfied + --> tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.rs:29:9 + | +29 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `cgp::prelude::DefaultNamespace` is not implemented for `PathCons>>>, PathCons>` + = help: the following other types implement trait `cgp::prelude::DefaultNamespace`: + AsyncComputerComponent + AsyncComputerRefComponent + ComputerComponent + ComputerRefComponent + ErrorRaiserComponent + ErrorTypeProviderComponent + ErrorWrapperComponent + GreeterComponent + and $N others +note: required for `App` to implement `DelegateComponent>>>, PathCons>>` + --> tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.rs:20:1 + | +20 | / delegate_components! { +21 | | App { + | | ^^^ +22 | | namespace DefaultNamespace; +23 | | } +24 | | } + | |_^ +note: required for `RedirectLookup>>>, PathCons>>` to implement `IsProviderFor` + --> tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.rs:3:1 + | + 3 | #[cgp_component(Greeter)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/attributes/prefix_rejected_unbound_path.rs:27:1 + | +27 | / check_components! { +28 | | App { +29 | | GreeterComponent, +30 | | } +31 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `delegate_components` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/attributes/default_impl.rs b/example-code/tests/reference/attributes/default_impl.rs new file mode 100644 index 00000000..18a169e5 --- /dev/null +++ b/example-code/tests/reference/attributes/default_impl.rs @@ -0,0 +1,229 @@ +//! Code from `docs/reference/attributes/default_impl.md` — *`#[default_impl(...)]`*. + +/// ## Examples +/// +/// The page's chain: a per-type default registered on the provider and pulled into a context by a +/// `for … in` loop, with one direct override. `ShowWithDisplay` is named by the page without being +/// introduced, so it is declared here. +pub mod examples { + use core::fmt::Display; + + use cgp::core::component::DefaultImpls1; + use cgp::prelude::*; + + #[cgp_component(ShowImpl)] + #[prefix(@test in DefaultNamespace)] + pub trait Show { + fn show(&self, value: &T) -> String; + } + + #[cgp_impl(new ShowString)] + #[default_impl(String in DefaultImpls1)] + impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } + } + + #[cgp_impl(new ShowWithDisplay)] + impl ShowImpl { + fn show(&self, value: &T) -> String { + format!("{value}") + } + } + + pub struct App; + + delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + @test.ShowImplComponent.u64: ShowWithDisplay, + } + } + + check_components! { + App { + ShowImplComponent: [String, u64], + } + } + + #[test] + fn default_and_override_resolve() { + assert_eq!(App.show(&"text".to_owned()), "text"); + assert_eq!(App.show(&7u64), "7"); + } +} + +/// ## Usage: a path key +/// +/// The key may be a `@`-path, which binds the provider at a prefixed component's own path so a +/// context that joins the namespace resolves it with no loop at all. +pub mod path_key { + use cgp::prelude::*; + + cgp_namespace! { + new AppNamespace: DefaultNamespace {} + } + + #[cgp_component(Greeter)] + #[prefix(@app in DefaultNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + #[default_impl(@app.GreeterComponent in AppNamespace)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { + App { + namespace AppNamespace; + } + } + + check_components! { + App { + GreeterComponent, + } + } + + #[test] + fn path_key_resolves_through_the_joined_namespace() { + let app = App { + name: "Alice".to_owned(), + }; + assert_eq!(app.greet(), "Hello, Alice!"); + } +} + +/// ## Usage: repeated attributes and a user-defined lookup trait +/// +/// One provider registers into two tables, one attribute each, and the second table is a trait +/// of the reader's own with the lookup shape. +pub mod repeated { + use cgp::core::component::DefaultImpls1; + use cgp::prelude::*; + + #[cgp_component(ShowImpl)] + #[prefix(@test in DefaultNamespace)] + pub trait Show { + fn show(&self, value: &T) -> String; + } + + pub trait LoudDefaults { + type Delegate; + } + + #[cgp_impl(new ShowString)] + #[default_impl(String in DefaultImpls1)] + #[default_impl(String in LoudDefaults)] + impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } + } + + pub struct Quiet; + + delegate_components! { + Quiet { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + } + } + + pub struct Loud; + + delegate_components! { + Loud { + namespace DefaultNamespace; + + for in LoudDefaults { + @test.ShowImplComponent.T: Provider, + } + } + } + + check_components! { + Quiet { + ShowImplComponent: String, + } + } + + check_components! { + Loud { + ShowImplComponent: String, + } + } + + #[test] + fn both_tables_hold_the_registration() { + assert_eq!(Quiet.show(&"a".to_owned()), "a"); + assert_eq!(Loud.show(&"b".to_owned()), "b"); + } +} + +/// ## Under the hood +/// +/// The path-key registration impl the page shows, written by hand in the resugared `Path!` spelling +/// against a component that carries no `#[default_impl]`, and checked to resolve the same way. +pub mod under_the_hood { + use cgp::prelude::*; + + cgp_namespace! { + new AppNamespace: DefaultNamespace {} + } + + #[cgp_component(Greeter)] + #[prefix(@app in DefaultNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + impl AppNamespace for Path!(@app.GreeterComponent) { + type Delegate = GreetHello; + } + + pub struct App; + + delegate_components! { + App { + namespace AppNamespace; + } + } + + check_components! { + App { + GreeterComponent, + } + } + + #[test] + fn hand_written_registration_resolves() { + assert_eq!(App.greet(), "Hello!"); + } +} diff --git a/example-code/tests/reference/attributes/impl_generics.rs b/example-code/tests/reference/attributes/impl_generics.rs new file mode 100644 index 00000000..18c0ba55 --- /dev/null +++ b/example-code/tests/reference/attributes/impl_generics.rs @@ -0,0 +1,176 @@ +//! Code from `docs/reference/attributes/impl_generics.md` — *`#[impl_generics(...)]`*. + +/// ## Overview +/// +/// The opening snippet, plus a context so the blanket impl has something to resolve against. +pub mod overview { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_fn] + #[impl_generics(Name: Display)] + pub fn greet(&self, #[implicit] name: &Name) -> String { + format!("Hello, {name}!") + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[test] + fn greets_by_field() { + let person = Person { + name: "Alice".to_owned(), + }; + assert_eq!(person.greet(), "Hello, Alice!"); + } +} + +/// ## Usage +/// +/// Two parameters, each pinned by its own implicit argument. The section's `#[cgp_impl]` remark +/// is checked here too: a provider declares the parameter in the block's own generic list. +pub mod usage { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_fn] + #[impl_generics(Name: Display, Count: Display)] + pub fn describe(&self, #[implicit] name: &Name, #[implicit] count: &Count) -> String { + format!("{count} × {name}") + } + + #[derive(HasField)] + pub struct Inventory { + pub name: String, + pub count: u32, + } + + #[test] + fn describes_two_fields() { + let inventory = Inventory { + name: "bolts".to_owned(), + count: 12, + }; + assert_eq!(inventory.describe(), "12 × bolts"); + } + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetByField)] + impl Greeter { + fn greet(&self, #[implicit] name: &Name) -> String { + format!("Hello, {name}!") + } + } + + delegate_components! { + Inventory { + GreeterComponent: GreetByField, + } + } + + check_components! { + Inventory { + GreeterComponent, + } + } + + #[test] + fn provider_declares_the_parameter_itself() { + let inventory = Inventory { + name: "bolts".to_owned(), + count: 12, + }; + assert_eq!(inventory.greet(), "Hello, bolts!"); + } +} + +/// ## Examples +pub mod examples { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_fn] + #[impl_generics(Name: Display)] + pub fn greet(&self, #[implicit] name: &Name) -> String { + format!("Hello, {name}!") + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[derive(HasField)] + pub struct Robot { + pub name: u32, + } + + pub fn greet_both(person: &Person, robot: &Robot) { + println!("{}", person.greet()); // Hello, Alice! + println!("{}", robot.greet()); // Hello, 42! + } + + #[cgp_fn] + #[uses(Greet)] + pub fn announce(&self) -> String { + format!("{} Welcome aboard.", self.greet()) + } + + #[test] + fn both_contexts_greet() { + let person = Person { + name: "Alice".to_owned(), + }; + let robot = Robot { name: 42 }; + assert_eq!(person.greet(), "Hello, Alice!"); + assert_eq!(robot.greet(), "Hello, 42!"); + assert_eq!(robot.announce(), "Hello, 42! Welcome aboard."); + greet_both(&person, &robot); + } +} + +/// ## Under the hood +/// +/// The expansion the page shows, written by hand, and checked to resolve the same way. +pub mod under_the_hood { + use core::fmt::Display; + use core::marker::PhantomData; + + use cgp::prelude::*; + + pub trait Greet { + fn greet(&self) -> String; + } + + impl<__Context__, Name: Display> Greet for __Context__ + where + Self: HasField, + { + fn greet(&self) -> String { + let name: &Name = self.get_field(PhantomData::); + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[test] + fn hand_written_expansion_resolves() { + let person = Person { + name: "Alice".to_owned(), + }; + assert_eq!(person.greet(), "Hello, Alice!"); + } +} diff --git a/example-code/tests/reference/attributes/mod.rs b/example-code/tests/reference/attributes/mod.rs new file mode 100644 index 00000000..9194b15d --- /dev/null +++ b/example-code/tests/reference/attributes/mod.rs @@ -0,0 +1,5 @@ +//! Code from the pages under `docs/reference/attributes/`. + +pub mod default_impl; +pub mod impl_generics; +pub mod prefix; diff --git a/example-code/tests/reference/attributes/prefix.rs b/example-code/tests/reference/attributes/prefix.rs new file mode 100644 index 00000000..56964df3 --- /dev/null +++ b/example-code/tests/reference/attributes/prefix.rs @@ -0,0 +1,293 @@ +//! Code from `docs/reference/attributes/prefix.md` — *`#[prefix(...)]`*. + +/// ## Overview +/// +/// The opening registration. The page names `AppNamespace` without defining it, so it is defined +/// here, and a context joins it and binds the path so the route resolves. +pub mod overview { + use cgp::prelude::*; + + cgp_namespace! { + new AppNamespace {} + } + + #[cgp_component(Greeter)] + #[prefix(@app in AppNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + pub struct App; + + delegate_components! { + App { + namespace AppNamespace; + + @app.GreeterComponent: GreetHello, + } + } + + check_components! { + App { + GreeterComponent, + } + } + + #[test] + fn resolves_through_the_prefix() { + assert_eq!(App.greet(), "Hello!"); + } +} + +/// ## Usage +/// +/// The two-namespace registration, and a generic component addressed with its parameter after +/// the marker. +pub mod usage { + use core::fmt::Display; + + use cgp::prelude::*; + + cgp_namespace! { + new MyNamespace {} + } + + cgp_namespace! { + new OtherNamespace {} + } + + pub struct MyApp; + + pub struct MyBarComponent; + + #[cgp_component(BarProvider)] + #[prefix(@MyApp.MyBarComponent in MyNamespace)] + #[prefix(@my_app.MyBarComponent in OtherNamespace)] + pub trait Bar { + fn bar(&self); + } + + #[cgp_impl(new DummyBar)] + impl BarProvider { + fn bar(&self) {} + } + + pub struct AppA; + + delegate_components! { + AppA { + namespace MyNamespace; + + @MyApp.MyBarComponent.BarProviderComponent: DummyBar, + } + } + + pub struct AppB; + + delegate_components! { + AppB { + namespace OtherNamespace; + + @my_app.MyBarComponent.BarProviderComponent: DummyBar, + } + } + + check_components! { + AppA { + BarProviderComponent, + } + } + + check_components! { + AppB { + BarProviderComponent, + } + } + + #[cgp_component(ShowImpl)] + #[prefix(@app in MyNamespace)] + pub trait CanShow { + fn show(&self, value: &T) -> String; + } + + #[cgp_impl(new ShowWithDisplay)] + impl ShowImpl { + fn show(&self, value: &T) -> String { + format!("{value}") + } + } + + pub struct AppC; + + delegate_components! { + AppC { + namespace MyNamespace; + + @app.ShowImplComponent.String: ShowWithDisplay, + } + } + + check_components! { + AppC { + ShowImplComponent: String, + } + } + + #[test] + fn shows_by_prefixed_path() { + AppA.bar(); + AppB.bar(); + assert_eq!(AppC.show(&"hi".to_owned()), "hi"); + } +} + +/// ## Examples +pub mod examples { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::ReturnError; + use cgp::prelude::*; + + #[cgp_component(Greeter)] + #[prefix(@app in DefaultNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { + App { + namespace DefaultNamespace; + + @app.GreeterComponent: GreetHello, + } + } + + check_components! { + App { + GreeterComponent, + } + } + + #[cgp_impl(new GreetFormally)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Good day, {name}.") + } + } + + #[derive(HasField)] + pub struct FormalApp { + pub name: String, + } + + delegate_components! { + FormalApp { + namespace DefaultNamespace; + + @app.GreeterComponent: GreetFormally, + } + } + + check_components! { + FormalApp { + GreeterComponent, + } + } + + pub struct Service; + + delegate_components! { + Service { + namespace DefaultNamespace; + + @cgp.core.error.ErrorTypeProviderComponent: UseType, + @cgp.core.error.ErrorRaiserComponent.String: ReturnError, + } + } + + check_components! { + Service { + ErrorTypeProviderComponent, + ErrorRaiserComponent: String, + } + } + + #[test] + fn two_contexts_bind_the_same_path_differently() { + let app = App { + name: "Alice".to_owned(), + }; + let formal = FormalApp { + name: "Alice".to_owned(), + }; + assert_eq!(app.greet(), "Hello, Alice!"); + assert_eq!(formal.greet(), "Good day, Alice."); + } +} + +/// ## Under the hood +/// +/// The impl the attribute emits, written by hand for an unprefixed component, resolves the same +/// way as the attribute's own output. +pub mod under_the_hood { + use cgp::prelude::*; + + cgp_namespace! { + new AppNamespace {} + } + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + impl<__Components__> AppNamespace<__Components__> for GreeterComponent { + type Delegate = RedirectLookup<__Components__, Path!(@app.GreeterComponent)>; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + pub struct App; + + delegate_components! { + App { + namespace AppNamespace; + + @app.GreeterComponent: GreetHello, + } + } + + check_components! { + App { + GreeterComponent, + } + } + + #[test] + fn hand_written_registration_resolves() { + assert_eq!(App.greet(), "Hello!"); + } +} diff --git a/example-code/tests/reference/mod.rs b/example-code/tests/reference/mod.rs index dabc50fe..7522f13f 100644 --- a/example-code/tests/reference/mod.rs +++ b/example-code/tests/reference/mod.rs @@ -3,6 +3,7 @@ //! The section is filled in lazily, so the modules here are the pages someone has written, revised, //! or reviewed rather than the section's full inventory. +pub mod attributes; pub mod components; pub mod derives; pub mod errors; From cdc16fb2f64c1ce6b189c02c8c278b8ffcd419c9 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 21:22:06 +0200 Subject: [PATCH 061/516] docs(reference): make the per-type examples name their component, record attribute corner cases - delegate_components! and #[cgp_component]: the `open` and RedirectLookup examples dispatch a generic `CanCalculateArea`, which the pages now define and say so, instead of implying the parameterless component defined earlier on each page. - #[cgp_impl], #[default_impl]: the `#[cgp_impl(Self)]` form still emits a #[default_impl] registration with `Delegate = Self`, naming the key. - #[cgp_auto_getter]: #[prefix] and #[derive_delegate] are accepted and dropped silently. - example-code: a fixture pins the lifetime-ordering claim on the #[impl_generics] page, and a compiled check pins the Self-form registration claim. Co-Authored-By: Claude Fable 5.1 --- docs/reference/attributes/default_impl.md | 4 ++ docs/reference/macros/cgp_auto_getter.md | 5 +++ docs/reference/macros/cgp_component.md | 10 +++-- docs/reference/macros/cgp_impl.md | 4 +- docs/reference/macros/delegate_components.md | 17 +++++++- .../reference/attributes/default_impl.rs | 41 +++++++++++++++++++ .../reference/attributes/impl_generics.rs | 30 ++++++++++++++ 7 files changed, 104 insertions(+), 7 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 53768cb5..3c593b4f 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -291,6 +291,10 @@ error[E0119]: conflicting implementations of trait `DefaultImpls1`, as in the table below, rather than the parameterless component this page +defines. For such a component the impl does not look the incoming path up directly. It appends the +parameters to the path first, so a lookup for `CanCalculateArea` that arrives at +`@AreaCalculatorComponent` ends up looking for `@AreaCalculatorComponent.Rectangle`. Only *type* parameters take part. A lifetime or a const parameter cannot key a path, so the impl leaves it out. Some details of the real output differ from the listings above, and each is easy to misread in an diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index ac7a3989..563599e6 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -411,7 +411,9 @@ produces a *cannot find attribute* resolution error pointing at the impl, and it `#[cgp_impl(new Self)]` or `#[cgp_impl(Self: SomeComponent)]` parses and compiles, but has exactly the same effect as a plain `#[cgp_impl(Self)]`. The macro does not declare a struct, and it never consults the component override, because this form builds neither a provider nor an `IsProviderFor` impl for -either one to apply to. Leave both out. +either one to apply to. Leave both out. A [`#[default_impl]`](../attributes/default_impl.md) on this +form is not ignored: the macro still emits its registration, with `type Delegate = Self`, which inside +that impl names the key rather than a provider. Leave it out too. ## Related constructs diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index ecbfdaae..1cb6fdb6 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -261,6 +261,17 @@ check with an unsatisfied `IsProviderFor` that never mentions the missing attrib When a component is generic over a type parameter, you usually want a different provider for each value of it. The `open` statement folds those per-value entries straight into the context's own table. +The per-type wiring on this page therefore dispatches a generic `CanCalculateArea`, whose +provider trait is `AreaCalculator`, rather than the parameterless component the +opening example wires: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} +``` + A leading `open …;` header opens one or more components, and `@`-path entries then assign a provider per key: @@ -394,8 +405,10 @@ different fields. A function generic over `CanCalculateArea` serves both without happened. Each context's choice stays one line a reader can search for, and finding that line tells them which implementation runs. -When one context needs a different provider *per type* rather than one provider outright, it opens the -component and fills the slots: +When one context needs a different provider *per type* rather than one provider outright, the +component carries the type as a parameter, as the generic `CanCalculateArea` under +[Usage](#choosing-a-provider-per-type-the-open-statement) does. The context then opens the component +and fills the slots: ```rust pub struct MyApp; diff --git a/example-code/tests/reference/attributes/default_impl.rs b/example-code/tests/reference/attributes/default_impl.rs index 18a169e5..dd932212 100644 --- a/example-code/tests/reference/attributes/default_impl.rs +++ b/example-code/tests/reference/attributes/default_impl.rs @@ -227,3 +227,44 @@ pub mod under_the_hood { assert_eq!(App.greet(), "Hello!"); } } + +/// ## Common Mistakes: the `#[cgp_impl(Self)]` form +/// +/// The page says the attribute is still lowered on the passthrough form, with `Delegate = Self`, +/// which names the key. This compiles and pins that reading: the registration exists and its +/// delegate is the key itself, not a provider. +pub mod common_mistakes_self_form { + use core::marker::PhantomData; + + use cgp::prelude::*; + + cgp_namespace! { + new AppNamespace {} + } + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + pub struct App; + + #[cgp_impl(Self)] + #[default_impl(GreeterComponent in AppNamespace)] + impl CanGreet for App { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + fn same_type(_: PhantomData, _: PhantomData) {} + + #[test] + fn the_registration_names_the_key_as_its_own_delegate() { + same_type( + PhantomData::<>::Delegate>, + PhantomData::, + ); + assert_eq!(App.greet(), "Hello!"); + } +} diff --git a/example-code/tests/reference/attributes/impl_generics.rs b/example-code/tests/reference/attributes/impl_generics.rs index 18c0ba55..71f52311 100644 --- a/example-code/tests/reference/attributes/impl_generics.rs +++ b/example-code/tests/reference/attributes/impl_generics.rs @@ -174,3 +174,33 @@ pub mod under_the_hood { assert_eq!(person.greet(), "Hello, Alice!"); } } + +/// ## Under the hood: lifetime ordering +/// +/// The page says a lifetime declared in the attribute lands ahead of the context parameter because +/// `syn` prints lifetimes first. If it did not, the emitted `impl<__Context__, 'a, …>` would be a +/// syntax error, so compiling this is the check. +pub mod lifetime_ordering { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_fn] + #[impl_generics('a, Name: Display + 'a)] + pub fn greet_for_a_while(&self, #[implicit] name: &Name) -> String { + format!("Hello, {name}!") + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[test] + fn lifetime_parameter_is_accepted() { + let person = Person { + name: "Alice".to_owned(), + }; + assert_eq!(person.greet_for_a_while(), "Hello, Alice!"); + } +} From a3a8b888f224d0985fdfc66f3b2cce7287648731 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 21:53:47 +0200 Subject: [PATCH 062/516] docs(reference/attributes): point-first pass over the attribute pages Split punctuation joins that hid a relationship (semicolons and one stacked grammar sentence), drop bare count lead-ins before lists and one positional ordinal, move a negation onto its verb, and change one heading's em-dash pivot to a colon. Left the sanctioned list-item separators and the site-wide footer untouched. Co-Authored-By: Claude Opus 4.8 --- docs/reference/attributes/default_impl.md | 12 ++++++------ docs/reference/attributes/derive_delegate.md | 4 ++-- docs/reference/attributes/extend.md | 4 ++-- docs/reference/attributes/extend_where.md | 2 +- docs/reference/attributes/implicit.md | 2 +- docs/reference/attributes/index.md | 4 ++-- docs/reference/attributes/use_type.md | 2 +- docs/reference/attributes/uses.md | 4 ++-- 8 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 3c593b4f..f3ad9a0e 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -240,10 +240,10 @@ PathSegment -> Type NamespacePath -> TypePath GenericArgs? ``` -`Key` is either a Rust `Type`, which becomes the emitted impl's `Self`, or a `Path`, which is -[`Path!`](../macros/path.md)'s own production and lowers to a `PathCons` list in the same position; the -leading `@` tells them apart. `NamespacePath` is the lookup trait with its leading generic arguments -written out. The table parameter is appended by the macro and must not be given. Each attribute takes +`Key` is either a Rust `Type` or a `Path`, and the leading `@` tells them apart. A `Type` becomes the +emitted impl's `Self`. A `Path` is [`Path!`](../macros/path.md)'s own production and lowers to a +`PathCons` list in the same position. `NamespacePath` is the lookup trait with its leading generic +arguments written out. The table parameter is appended by the macro and must not be given. Each attribute takes exactly one such argument, and the attribute may be repeated. ## Common Mistakes @@ -252,8 +252,8 @@ exactly one such argument, and the attribute may be repeated. and the trait's positions follow. The parameter names on [`DefaultImpls1`](../traits/namespace/default_impls1.md) suggest otherwise. -**Do not write the table parameter.** The macro appends it; supplying it yourself makes the path's arity -wrong. +**Do not write the table parameter.** The macro appends it, so supplying it yourself makes the path's +arity wrong. **On a prefixed component it is confined to the namespace's crate**, by the orphan rule. This is not something to work around: put the wiring in the namespace body instead. diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 3e7ba08a..4774ab38 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -9,7 +9,7 @@ Generate the `UseDelegate` dispatcher impl for a component. Superseded by the `o :::info -### Legacy — read, don't write +### Legacy: read, don't write `#[derive_delegate]` and the [`UseDelegate`](../providers/use_delegate.md) provider it generates are the older way to choose an implementation per type. A component no longer needs this attribute to be @@ -164,7 +164,7 @@ parameter and resolve to the same implementations. [`delegate_components!`](../macros/delegate_components.md), which needs no attribute and no table type. That is the recommendation without qualification for new code. -Three situations still involve it, and only the first is a reason to write it. +A few situations still involve it, and only one is a reason to write it. - **Keeping compatibility with existing wiring.** The attribute makes `UseDelegate` wiring possible, so removing it from a published component is a breaking diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index fb737e51..d7850da9 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -30,7 +30,7 @@ same trait, so this is a choice about how the definition reads. On [`#[cgp_fn]`](../macros/cgp_fn.md) the attribute is not merely preferred but necessary. The `#[cgp_fn]` macro treats a `where` clause you write as an implementation detail and never puts it on the generated -trait, so there is no way to spell a supertrait by hand. `#[extend]` is the only mechanism for one. +trait, so you cannot spell a supertrait by hand. `#[extend]` is the only mechanism for one. ## Usage @@ -114,7 +114,7 @@ available, and so may every caller. **Reach for `#[extend]` when callers of the trait should be able to rely on the capability too**, and for a capability supertrait on a `#[cgp_component]` in preference to native `:` syntax. Reach for something -else in three cases, and the choice turns on where the requirement should be visible. +else when the requirement belongs elsewhere, and the choice turns on where it should be visible. - **The implementation needs it privately.** Use [`#[uses]`](uses.md). This is the common case by a wide margin: most dependencies are private to the implementation, and putting one on the trait forces it on diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 3b1e6bb0..217bef56 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -119,7 +119,7 @@ The useful test is who the bound is *about*. A bound describing how the body com the implementation. A bound describing what the capability requires of its own type parameters, something that would be part of the signature if you were writing the trait by hand, belongs on the trait. -Three neighbours cover what this attribute should not be used for. +Other constructs cover what this attribute should not be used for. - **A bound on `Self`** is a supertrait, so use [`#[extend]`](extend.md). `#[extend_where]` can express it, but a supertrait reads as what it is, and unlike a predicate it *is* handed to callers by elaboration. diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 9d325a83..7ac35b58 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -276,7 +276,7 @@ error: a `&mut` implicit argument must be the only implicit argument, since its - [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) — the getter form, for the cases above. - [`#[cgp_getter]`](../macros/cgp_getter.md) — a getter whose source field is chosen by wiring. - [`#[uses]`](uses.md) — imports a capability rather than a value. -- [`#[use_type]`](use_type.md) — imports a type rather than a value; the third of the three. +- [`#[use_type]`](use_type.md) — imports a type rather than a value. - [`Symbol!`](../macros/symbol.md) — the type-level field name the bounds are keyed on. The ideas behind it: diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index bbe43082..6bf22b8c 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -11,8 +11,8 @@ An attribute here is a modifier, not a macro of its own. Each one is an option a generates. This page groups every attribute in this section by the job it does, in roughly the order most CGP code reaches for them. -If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here; this page -is the fuller map for once the essentials are familiar. +If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here. This page +is the fuller map, for once the essentials are familiar. ## Reading a value from the context diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 6764694a..c37f3fbf 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -183,7 +183,7 @@ separates them. recommended form; you read a hand-written supertrait plus `Self::`-qualified paths in existing code rather than write them. -Two neighbours cover requirements that are not types, and one further construct is the one `#[use_type]` +Its neighbours cover requirements that are not types, and one further construct is the one `#[use_type]` imports *from*. - **A capability** is [`#[uses]`](uses.md) for a private bound or [`#[extend]`](extend.md) for a diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 368170db..cf129a9e 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -26,7 +26,7 @@ imports a trait the context itself must satisfy. The requirement stays private to the implementation. A caller who depends on the capability never sees it and never has to repeat it, which is the point of declaring the dependency where the implementation lives rather than on its public interface. Preferring `#[uses]` over a hand-written bound is the -recommendation; the equivalent `where` clause is the older form you meet in existing code, and +recommendation. The equivalent `where` clause is the older form you meet in existing code, and [Under the hood](#under-the-hood) shows the two desugar identically. ## Usage @@ -114,7 +114,7 @@ This provider is a two-line adapter: it satisfies the `AreaCalculator` component ## When to use it **Use `#[uses]` for every capability dependency**, in preference to writing the `Self:` bound by hand. -That is the recommendation; you read the hand-written form in existing code rather than write it. +That is the recommendation. You read the hand-written form in existing code rather than write it. Two questions decide between `#[uses]` and its neighbours: *what* is being depended on, and *where the requirement should be visible*. From 51a5f7052f06ba573f81a747f44babd90b482ac3 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 22:08:45 +0200 Subject: [PATCH 063/516] docs(reference/attributes): second point-first pass over the attribute pages Revise prose only across all eleven pages. No heading, code block, table, diagnostic, or link changed, and the site still builds with onBrokenLinks set to throw. - Replace the remaining count lead-ins ("Three rules constrain", "Two rules follow", "Two details are easy to misread", "runs in three hops", "in three steps") with sentences that name what they introduce. - Replace positional back-references ("the second of those two", "the first asks the context, the second names", "The second is the readable one") with the construct's own name. - Lead paragraphs with their point in use_type, extend, and extend_where, and drop the "That is the recommendation" lines that only restated a bolded imperative. - Move flat negations onto the verb: "There is no call-site rewriting" becomes "The attribute does not rewrite call sites", and likewise in implicit, use_provider, extend_where and derive_delegate. - Replace vague or figurative wording: "gives better ergonomics", "worth internalizing", "the one in front of you", "it pays off at once", "Consumption is the mirror", "dropped in". Kept "climb", which is settled vocabulary across the concepts tier and the knowledge base. - Reorder default_impl's When-to-use list so the "use it" case leads, and give it a lead-in sentence. - Add the missing "context" gloss to the group index. Co-Authored-By: Claude Opus 5 --- docs/reference/attributes/default_impl.md | 16 ++--- docs/reference/attributes/derive_delegate.md | 39 ++++++------ docs/reference/attributes/extend.md | 25 ++++---- docs/reference/attributes/extend_where.md | 45 +++++++------- docs/reference/attributes/impl_generics.md | 6 +- docs/reference/attributes/implicit.md | 63 ++++++++++---------- docs/reference/attributes/index.md | 14 ++--- docs/reference/attributes/prefix.md | 23 +++---- docs/reference/attributes/use_provider.md | 36 +++++------ docs/reference/attributes/use_type.md | 47 +++++++-------- docs/reference/attributes/uses.md | 18 +++--- 11 files changed, 168 insertions(+), 164 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index f3ad9a0e..72284fa9 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -23,8 +23,8 @@ impl ShowImpl { /* … */ } Read that as: *`ShowString` is the default for `String`, in the `DefaultImpls1` table.* A context that pulls that table in gets this provider without naming it. -Registering at the definition keeps the provider and its default together, so adding a new per-type -implementation is one place to edit rather than two. +Registering at the definition keeps the provider and its default together, so a new per-type +implementation is one edit rather than two. ## Usage @@ -45,7 +45,7 @@ impl DefaultImpls1 for String { } ``` -That rule is worth internalizing, because the trait's own parameter names suggest the opposite +That rule is worth remembering, because the trait's own parameter names suggest the opposite arrangement (see [`DefaultImpls1`](../traits/namespace/default_impls1.md#the-one-thing-to-get-right)). **The key is a type or a `@`-path.** A type key, as above, is the usual form for a per-type default: @@ -162,14 +162,14 @@ with `GreetHello`. ## When to use it **Reach for it when a provider is the natural default for its key and you want that recorded where the -provider is written.** +provider is written.** The alternatives differ in where the entry lives. -- **Write the entry in the namespace body instead** when the defaults belong together as a set, or when - the provider is one of several candidates and none is obviously *the* default. A - [`cgp_namespace!`](../macros/cgp_namespace.md) body reads as a table; scattered attributes do not. - **Use it** when per-type defaults accumulate (a conversion, a formatter, a codec with one provider per type), because then the alternative is a namespace body that has to be edited every time a type is added. +- **Write the entry in the namespace body instead** when the defaults belong together as a set, or when + the provider is one of several candidates and none is obviously *the* default. A + [`cgp_namespace!`](../macros/cgp_namespace.md) body reads as a table; scattered attributes do not. - **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. **One constraint decides where the attribute may be written, and it is Rust's orphan rule rather than @@ -213,7 +213,7 @@ ordinary providers: a provider whose bounds come from [`#[use_type]`](./use_type registers cleanly, because those bounds stay on the provider's impl and its [`IsProviderFor`](../traits/wiring/is_provider_for.md) and are checked when a real context resolves it. -Consumption is the mirror. A `for in DefaultImpls1 { … }` loop inside +Consumption runs the other way. A `for in DefaultImpls1 { … }` loop inside [`delegate_components!`](../macros/delegate_components.md) emits a [`DelegateComponent`](../traits/wiring/delegate_component.md) impl whose `where` clause projects the default: diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 4774ab38..642fd435 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -27,10 +27,10 @@ component that keeps it stays compatible with existing wiring. It is expected to ## Overview A component generic over a type parameter usually wants a different implementation per value of it: -`Rectangle` handled one way, `Circle` another. Something has to look at the type and pick, and written by -hand that dispatcher is an implementation of the provider trait that reads a lookup table, finds the entry -for the type, and forwards every method to it. That code is mechanical, identical in shape for every -component, differing only in which parameter is the key. +`Rectangle` handled one way, `Circle` another. Something has to look at the type and pick. Written by +hand, that dispatcher is an implementation of the provider trait that reads a lookup table, finds the +entry for the type, and forwards every method to it. That code is mechanical, identical in shape for +every component, differing only in which parameter is the key. `#[derive_delegate]` generates it: @@ -42,14 +42,14 @@ pub trait CanCalculateArea { } ``` -A **context**, the type the capability runs against and owns the wiring, then points the component at -[`UseDelegate`](../providers/use_delegate.md) over a table naming one implementation per shape, and the -generated dispatcher does the lookup. +A **context**, the type the capability runs against, which also owns the wiring, then points the +component at [`UseDelegate`](../providers/use_delegate.md) over a table naming one implementation per +shape, and the generated dispatcher does the lookup. `open` replaced this because the indirection turned out to be unnecessary. Every [`#[cgp_component]`](../macros/cgp_component.md) already generates a [`RedirectLookup`](../providers/redirect_lookup.md) impl, and `open` routes through that instead, so the -per-type entries live on the context itself, there is no second table type to name, and the component +per-type entries live on the context itself, the wiring names no second table type, and the component needs no attribute at all. ## Usage @@ -155,16 +155,16 @@ delegate_components! { } ``` -No wrapper, no second table type, and nothing on the component. The two forms dispatch on the same -parameter and resolve to the same implementations. +This form needs no wrapper, no second table type, and nothing on the component. The two forms dispatch +on the same parameter and resolve to the same implementations. ## When to use it **Do not add `#[derive_delegate]` to a new component.** Use the `open` statement of [`delegate_components!`](../macros/delegate_components.md), which needs no attribute and no table type. -That is the recommendation without qualification for new code. -A few situations still involve it, and only one is a reason to write it. +A few situations still involve the attribute, and only the dispatcher that `open` cannot express is a +reason to write it. - **Keeping compatibility with existing wiring.** The attribute makes `UseDelegate` wiring possible, so removing it from a published component is a breaking @@ -204,11 +204,12 @@ names something that is itself a provider for that `Shape`, and the method simpl same trait ordinary wiring is made of, which is why you write the table with [`delegate_components!`](../macros/delegate_components.md) like any other. -Two details of the real output are worth recognizing. **The key is wrapped in a tuple**, as -`DelegateComponent<(Shape), …>`, so that a single-parameter key and a multi-parameter one compose -uniformly: a `UseDelegate<(Code, Input)>` declaration produces `DelegateComponent<(Code, Input), …>` with -no other change. And the generics carry reserved names: the table is `__Components__` and the looked-up -entry `__Delegate__`, alongside the provider trait's own `__Context__`. +The tuple key and the reserved generic names are worth recognizing in the real output. **The key is +wrapped in a tuple**, as `DelegateComponent<(Shape), …>`, so that a single-parameter key and a +multi-parameter one compose uniformly: a `UseDelegate<(Code, Input)>` declaration produces +`DelegateComponent<(Code, Input), …>` with no other change. And the generics carry reserved names: the +table is `__Components__` and the looked-up entry `__Delegate__`, alongside the provider trait's own +`__Context__`. **A component's supertraits carry into the dispatcher.** The provider trait records each supertrait as a `Context:` predicate, and because the dispatcher reuses the provider trait's generics that predicate @@ -260,8 +261,8 @@ there is nothing for it to do. **One component gets one dispatch mechanism.** Wiring the same component both with `open` and with a `UseDelegate` table is a coherence conflict, because each produces its own table entry for that key. A wiring entry expands to two impls, and both of them collide, so the compiler reports the conflict twice, once -for `IsProviderFor` and once for `DelegateComponent`. The second is the readable one, since its trait -argument names the component at issue: +for `IsProviderFor` and once for `DelegateComponent`. The `DelegateComponent` report is the readable +one, since its trait argument names the component at issue: ```text error[E0119]: conflicting implementations of trait `DelegateComponent` diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index d7850da9..ba62e05b 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -18,9 +18,10 @@ must also satisfy it, and every caller may rely on it. #[extend(HasName)] ``` -The clearest way to hold the pair apart is that **`#[extend]` is the `pub use` to `#[uses]`'s `use`**. -Both take the same syntax and both read as imports, but one imports a capability for the implementation's -own use and keeps it out of sight, while the other re-exports it as part of the contract. +**`#[extend]` is the `pub use` to `#[uses]`'s `use`**, which is the clearest way to tell the pair apart. +Both take the same syntax and both read as imports. But `#[uses]` imports a capability for the +implementation's own use and keeps it out of sight, where `#[extend]` re-exports it as part of the +contract. That framing is also why `#[extend]` is preferred over Rust's native supertrait syntax on a [`#[cgp_component]`](../macros/cgp_component.md). Writing `pub trait CanGreet: HasName` reads as @@ -125,10 +126,10 @@ else when the requirement belongs elsewhere, and the choice turns on where it sh on `Self`. Use [`#[extend_where]`](extend_where.md), which puts it on the generated trait's own `where` clause. -Weigh one cost before promoting anything. A supertrait widens the contract permanently: you cannot later -narrow it without breaking every implementor, and it demands the capability from contexts that only ever -call the one method the trait actually declares. Prefer `#[uses]` unless callers genuinely need the -guarantee. +A supertrait widens the contract permanently, and that is the cost to weigh before promoting anything. +You cannot later narrow it without breaking every implementor, and it demands the capability from +contexts that only ever call the one method the trait actually declares. Prefer `#[uses]` unless callers +genuinely need the guarantee. ## Under the hood @@ -159,8 +160,8 @@ where ``` Callers see the supertrait, and the predicate on the implementation lets the body call the methods. -Compare [`#[uses]`](uses.md), which emits only the second of those two and leaves the trait declaration -bare. That single difference is the whole of the distinction. +Compare [`#[uses]`](uses.md), which emits only the predicate and leaves the trait declaration bare. +That single difference is the whole of the distinction. On a `#[cgp_component]` the supertrait goes on the consumer trait, and it also joins the `where` clause of the generated consumer blanket implementation, since that implementation can only apply where the @@ -183,9 +184,9 @@ where ``` Here the result is identical to `pub trait CanGreet: HasName`, so on a component -`#[extend]` generates nothing the language cannot already spell. It remains the preferred form for the -reason given above: it presents the bound as an import rather than as inheritance, and it keeps the -`use`/`pub use` pairing with `#[uses]` reading consistently across both macros. +`#[extend]` generates nothing the language cannot already spell. It remains the preferred form because +it presents the bound as an import rather than as inheritance, and because it keeps the `use`/`pub use` +pairing with `#[uses]` reading consistently across both macros. ## Formal grammar diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 217bef56..47279d9d 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -11,8 +11,8 @@ Add `where` predicates to a generated trait's own definition, not just to its im A [`#[cgp_fn]`](../macros/cgp_fn.md) treats the `where` clause you write on the function as an implementation detail: the bounds land on the generated implementation and never appear on the generated -trait. That default keeps a capability's requirements out of sight of its callers, and it is right almost -always. +trait. That default keeps a capability's requirements out of sight of its callers, and it is almost +always right. The cost is that an unsatisfiable requirement becomes invisible. A bound on the implementation only decides which **contexts** the implementation covers, a context being the type the capability runs @@ -25,17 +25,17 @@ condition of naming the trait at all: #[extend_where(Scalar: Clone)] ``` -The distinction is worth being exact about, because it is easy to get backwards. Promoting a predicate -does **not** hand it to callers. A trait's `where` clause is a precondition they must prove, not a -guarantee they receive, so a caller naming the trait still writes the bound themselves. Promotion changes -two things: callers are now *made* to write the bound, and getting it wrong is reported against the trait -rather than deferred. +Promoting a predicate does **not** hand it to callers, and the distinction is worth being exact about, +because it is easy to get backwards. A trait's `where` clause is a precondition they must prove, not a +guarantee they receive, so a caller naming the trait still writes the bound themselves. Promotion +instead makes callers write the bound, and reports a wrong one against the trait rather than deferring +it. -It is the `where`-clause sibling of [`#[extend]`](extend.md). Both put a requirement into the trait's -public interface; they differ in position, and in what the reader gets. `#[extend]` adds a **supertrait**, -a bound on `Self`, which callers do receive by elaboration. `#[extend_where]` adds a **predicate**, which -can bound anything, most usefully one of the trait's own generic parameters, which a supertrait cannot -reach. +`#[extend_where]` is the `where`-clause sibling of [`#[extend]`](extend.md). Both put a requirement into +the trait's public interface; they differ in position, and in what the reader gets. `#[extend]` adds a +**supertrait**, a bound on `Self`, which callers do receive by elaboration. `#[extend_where]` adds a +**predicate**, which can bound anything, most usefully one of the trait's own generic parameters, which +a supertrait cannot reach. ## Usage @@ -52,7 +52,7 @@ verbatim, and keeps it on the implementation as well. **`#[extend_where]` is supported only on [`#[cgp_fn]`](../macros/cgp_fn.md).** It has no meaning on [`#[cgp_impl]`](../macros/cgp_impl.md) or [`#[cgp_component]`](../macros/cgp_component.md), because in -those the `where` clause you write is already part of the definition. There is nothing to promote, so +those the `where` clause you write is already part of the definition. Nothing needs promoting, so write the bound as an ordinary `where` clause directly. ## Examples @@ -73,9 +73,9 @@ where } ``` -Two bounds, two destinations. The macro promotes `Scalar: Clone` onto the trait, so the compiler checks -it wherever `Scale` is named. `Scalar: Mul` stays on the implementation, because -multiplication is a detail of how *this* body computes a scale and no use site needs to know it. +Each bound has its own destination. The macro promotes `Scalar: Clone` onto the trait, so the compiler +checks it wherever `Scale` is named. `Scalar: Mul` stays on the implementation, +because multiplication is a detail of how *this* body computes a scale and no use site needs to know it. The promotion's effect is visible at the boundary. The compiler rejects a caller that names the capability for a type it cannot satisfy, at the place the bound is written, and names the trait that @@ -96,7 +96,7 @@ where all: `Ctx: Scale` is simply a bound no type can ever prove, and nothing says so until somebody tries to call `scale_it` with a concrete context. The attribute exists to remove that silence. -A caller who *can* satisfy the predicate states it as usual, and there is no way around stating it: +A caller who *can* satisfy the predicate states it as usual, and cannot avoid stating it: ```rust pub fn scale_it(ctx: &Ctx) -> Scalar @@ -119,7 +119,7 @@ The useful test is who the bound is *about*. A bound describing how the body com the implementation. A bound describing what the capability requires of its own type parameters, something that would be part of the signature if you were writing the trait by hand, belongs on the trait. -Other constructs cover what this attribute should not be used for. +Other constructs carry the requirements that belong elsewhere. - **A bound on `Self`** is a supertrait, so use [`#[extend]`](extend.md). `#[extend_where]` can express it, but a supertrait reads as what it is, and unlike a predicate it *is* handed to callers by elaboration. @@ -157,10 +157,11 @@ where The trait carries only the promoted predicate; the function's own bound is absent from it, which is the default this attribute overrides. -The implementation carries three, and their **order is fixed**: the function's own `where` clause first, -then whatever the attributes contribute, then the [`HasField`](../traits/field-access/has_field.md) bounds from -[`#[implicit]`](implicit.md) arguments, which are always appended last. That order is worth knowing when -reading a long `where` clause in an expansion, since it tells you where each bound came from. +The implementation carries all of them, and their **order is fixed**: the function's own `where` clause +first, then whatever the attributes contribute, then the +[`HasField`](../traits/field-access/has_field.md) bounds from [`#[implicit]`](implicit.md) arguments, +which are always appended last. That order is worth knowing when reading a long `where` clause in an +expansion, since it tells you where each bound came from. The context parameter is literally `__Context__` in the emitted code and appears as `Self` inside the implementation. diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 78e900ae..102ebf3f 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -123,8 +123,8 @@ repeat `Name: Display`, and pass the parameter on to everything that calls it. **Start with `#[impl_generics]` for a type that only ever flows through implicit arguments.** It is the shortest form, it does not need wiring, and it reads as "this works with any `name` field of a -compatible type". Two conditions force a climb to an abstract type, and each is about needing to -*name* the type somewhere the inferred form cannot reach. +compatible type". You must climb to an abstract type once the type has to be *named* somewhere the +inferred form cannot reach. - **The type appears in the capability's signature.** An impl-only parameter is not in scope on the trait, so a return type or an explicit parameter cannot mention it. This condition arrives the @@ -139,7 +139,7 @@ In both cases declare the type with [`#[cgp_type]`](../macros/cgp_type.md), impo condition with a generic parameter on the function. Such a parameter lands on the trait, so every caller and every intermediate capability must declare it and repeat its bounds whether they touch it or not. It also misplaces the decision: `` on a trait says the caller chooses the database type, -when the application determines it. +though the application determines it. Some neighbours cover what this attribute is not for. diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 7ac35b58..6e5c29cf 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -24,16 +24,16 @@ A call like `rect.rectangle_area()` does not require the arguments to be passed `width` and `height` fields are automatically extracted from the `rect` value. Any type carrying a `width` and a `height` field can call it. -`#[implicit]` gives better ergonomics than the alternatives, such as +`#[implicit]` is shorter to write than the alternatives, such as [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) or the direct use of -[`HasField`](../traits/field-access/has_field.md). With those, you declare that the context has each field and then -fetch it by hand, so you have to understand the mechanism behind field access, such as how a type-level -[`Symbol!`](../macros/symbol.md) and a `PhantomData` tag work. `#[implicit]` keeps all of that behind an -argument that reads as `width: f64`, and the argument's *name* names the field. +[`HasField`](../traits/field-access/has_field.md). With those, you declare that the context has each +field and then fetch it by hand, so you have to understand the mechanism behind field access, such as +how a type-level [`Symbol!`](../macros/symbol.md) and a `PhantomData` tag work. `#[implicit]` keeps +all of that behind an argument that reads as `width: f64`, and the argument's *name* names the field. -That is why it is the recommended way to read a context's own field, and why it is usually the first -piece of CGP anyone writes. A reader who understands functions and arguments can write a working -capability and meet the machinery later, when they have a reason to care. +So `#[implicit]` is the recommended way to read a context's own field, and usually the first piece of +CGP anyone writes. A reader who understands functions and arguments can write a working capability and +meet the machinery later, when they have a reason to care. ## Usage @@ -50,9 +50,9 @@ fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { [`#[cgp_fn]`](../macros/cgp_fn.md) and the methods of a [`#[cgp_impl]`](../macros/cgp_impl.md) block. It is not a macro of its own, so it does nothing on an ordinary function. -Three rules constrain where it may appear. The function must take `self` first, since the field is read -from `self`. The argument must be a bare identifier, not a destructuring or `mut` pattern. And a -**mutable** implicit argument carries two further requirements of its own, covered in +The macro constrains where the attribute may appear. The function must take `self` first, since the +field is read from `self`. The argument must be a bare identifier, not a destructuring or `mut` +pattern. And a **mutable** implicit argument carries further requirements of its own, covered in [Mutable arguments](#mutable-arguments) below. ### How the argument's type decides the read @@ -74,12 +74,12 @@ stored field. The table below is the whole mapping: | `Option<&mut str>` | `Option` | `.as_deref_mut()` | | [`MRef<'a, T>`](../types/mref.md) | `T` | by reference, wrapped as `MRef::Ref(…)` | -Three of those rows are easy to misread. `&str` is the case most often wanted and least obvious: the -field is a `String`, and the argument borrows from it, so a context never has to store a `&str`. An -owned argument *clones* the value. That is cheap for an `f64` and less so for a large `String`, which -is a reason to take `&str` or `&T` wherever the body only needs to read. And `MRef` is the -owned-or-borrowed form: it reads a plain `T` field, hands the body a value that may be either, and is -the one reference-shaped row with no mutable counterpart. +The rows for `&str`, for an owned type, and for `MRef` are the ones most easily misread. `&str` is the +case most often wanted and least obvious: the field is a `String`, and the argument borrows from it, so +a context never has to store a `&str`. An owned argument *clones* the value. That is cheap for an +`f64` and less so for a large `String`, which is a reason to take `&str` or `&T` wherever the body only +needs to read. And `MRef` is the owned-or-borrowed form: it reads a plain `T` field, hands the body a +value that may be either, and is the one reference-shaped row with no mutable counterpart. The macro matches the `MRef` row by *shape* rather than by resolving the name: a single-segment `MRef` with one lifetime argument and one type argument. Anything else spelled `MRef` falls into the owned row @@ -94,10 +94,9 @@ An implicit argument is mutable when its type carries a `&mut`: the outer refere reads through [`HasFieldMut`](../traits/field-access/has_field_mut.md) and `get_field_mut` rather than through [`HasField`](../traits/field-access/has_field.md) and `get_field`, so it borrows the field for writing. -Two rules follow. A mutable argument requires a `&mut self` receiver, since a function cannot borrow a -field mutably through a shared `&self`. And it must be the only implicit argument on its function, -because reading one field mutably borrows the whole context exclusively and cannot coexist with any -other field read. +A mutable argument requires a `&mut self` receiver, since a function cannot borrow a field mutably +through a shared `&self`. It must also be the only implicit argument on its function, because reading +one field mutably borrows the whole context exclusively and cannot coexist with any other field read. Mutability follows the *argument's* type rather than the receiver's. An argument carrying a `&mut` reads mutably, and every other argument, an `MRef` included, reads through a shared borrow. A `&mut self` @@ -132,7 +131,7 @@ pub fn print_area(rect: &Rectangle) { ``` `Rectangle` derives [`HasField`](../derives/derive_has_field.md), which is its entire qualification. -There is no wiring anywhere in this program. +This program wires nothing. Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) provider the attribute behaves identically and mixes freely with the method's real arguments. The implicit ones vanish from the signature while `to` and @@ -162,11 +161,11 @@ clone, so it suits a large value as well as a small one. A field that several pr declared as the same implicit argument in each of them, which costs nothing and keeps every provider's requirements visible where the provider is written. -A **getter trait** is worth using in the three cases an implicit argument cannot reach. +A **getter trait** covers the cases an implicit argument cannot reach. - **The field is on a different type.** An implicit argument reads only from `self`, so a value living on a request, a payload, or any other type needs a getter that can be demanded as a bound on *that* type. - There is no `self` field to read. + The value does not live on `self` at all. - **The accessor must be a named capability.** When other code depends on "this context can tell you its name" rather than on a field, that dependency needs a trait to point at, importable with [`#[uses]`](uses.md) or usable as a supertrait. @@ -179,8 +178,8 @@ reach for it only when the *field a getter reads* should be chosen per context a ## Under the hood -Each marked argument becomes two things: a field bound on the generated implementation, and a `let` -binding at the top of the body. From this input: +Each marked argument becomes a field bound on the generated implementation and a `let` binding at the +top of the body. From this input: ```rust #[cgp_fn] @@ -221,12 +220,12 @@ field name. The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form i `cargo cgp expand` resugars it back. The context parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours. -Two shapes in the table above generate something other than a `Value = T` equality, which is worth -recognizing because it reads oddly at first. A slice argument bounds the *associated type* instead, so -`&[u8]` emits `HasField + 'static>`, so any field whose value can be -viewed as a `[u8]` qualifies rather than one exact type. And every mutable form swaps the trait as well -as the accessor: `&mut u64` emits `HasFieldMut` and reads through -`get_field_mut`. +The slice rows and the mutable rows generate something other than a `Value = T` equality, which is +worth recognizing because it reads oddly at first. A slice argument bounds the *associated type* +instead, so `&[u8]` emits `HasField + 'static>`. Any field whose +value can be viewed as a `[u8]` then qualifies, rather than one exact type. And every mutable form +swaps the trait as well as the accessor: `&mut u64` emits +`HasFieldMut` and reads through `get_field_mut`. Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the rewrite is the same, except the bounds join that provider's `where` clause. One addition shows only in a multi-method block: the macro collects the diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index 6bf22b8c..eb5513d4 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -16,16 +16,16 @@ is the fuller map, for once the essentials are familiar. ## Reading a value from the context -[`#[implicit]`](./implicit.md) is the one almost every provider uses, and usually the first piece of CGP -anyone writes. It marks a function argument that the macro reads from a same-named field on the context -rather than from the caller, so a provider that needs a value reads like an ordinary function that takes -it. +[`#[implicit]`](./implicit.md) marks a function argument that the macro reads from a same-named field +on the context, the type the capability runs against, rather than from the caller. A provider that needs +a value then reads like an ordinary function that takes it. Almost every provider uses the attribute, +and it is usually the first piece of CGP anyone writes. ## Importing a dependency These attributes declare what an implementation depends on, each reading like an import. Most -dependencies belong on the implementation, out of sight of callers, and two of the attributes put one on -the generated trait instead, for when every caller must rely on it. +dependencies belong on the implementation, out of sight of callers, and `#[extend]` and +`#[extend_where]` put one on the generated trait instead, for when every caller must rely on it. [`#[uses]`](./uses.md) imports a consumer trait, or an ordinary Rust trait, that the context must satisfy, which is the common case. [`#[use_type]`](./use_type.md) imports an abstract type another @@ -47,7 +47,7 @@ implicit argument reads. It is the first form to reach for when a body needs a t ## Registering into a namespace -Two attributes let a definition register itself into a [namespace](/docs/concepts/namespaces) at the +These attributes let a definition register itself into a [namespace](/docs/concepts/namespaces) at the point where it is written, rather than in the namespace's own body. [`#[prefix]`](./prefix.md) goes on a component and routes it under a path prefix, so contexts that join the namespace address it by that path and a wiring table reads as a tree. [`#[default_impl]`](./default_impl.md) goes on a provider and diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index 95598832..e0791132 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -91,9 +91,9 @@ on a prefixed component is a foreign path. ### Choosing a prefix A prefix is part of the component's public surface, and expensive to change once wiring depends on -it, so choose it for every implementation the component might have rather than for the one in front -of you. Give components separate sub-paths whenever they are likely to need separate providers, even -when the current wiring happens to treat them alike. Abstract types belong under a `types` sub-path +it, so choose it for every implementation the component might have rather than for the one you are +writing now. Give components separate sub-paths whenever they are likely to need separate providers, +even when the current wiring happens to treat them alike. Abstract types belong under a `types` sub-path of their layer, such as `@app.auth.types`, because a production context typically points the logic under `@app.auth` at a database while leaving the types on the same concrete choices. @@ -197,7 +197,7 @@ delegate_components! { **Reach for `#[prefix]` as soon as a wiring table has enough components that grouping helps a reader.** It costs nothing at the point of use, it is the one namespace tool without a downstream -restriction, and it pays off at once in a table that reads as a directory listing. It is also the +restriction, and the table it produces reads at once as a directory listing. It is also the form a library uses to publish its components into a shared namespace. Some situations call for something else. @@ -236,9 +236,10 @@ The path is the prefix with the marker appended, a [`PathCons`](../types/path_co `cargo cgp expand` prints it as `Path!(@app.GreeterComponent)`, and a raw compiler error prints the underlying `PathCons>, PathCons>`. -Resolution then runs in three hops. Joining the namespace emits, on the context, a blanket -`DelegateComponent` impl whose `Delegate` is whatever the namespace answers, so asking `App` for -`GreeterComponent` yields `RedirectLookup`. That provider's impl +Resolution then runs through the namespace, then the redirect, then the context's own table. Joining +the namespace emits, on the context, a blanket `DelegateComponent` impl whose `Delegate` is whatever +the namespace answers, so asking `App` for `GreeterComponent` yields +`RedirectLookup`. That provider's impl of `Greeter` looks the path up in `App`'s own table, as `App: DelegateComponent`, and forwards to the delegate it finds there, `GreetHello`. For a component with type parameters, `RedirectLookup` appends the parameters to the path before the lookup, which is why per-type entries @@ -249,10 +250,10 @@ The impl has the same shape as a `=>` entry written in a namespace body: attribute lets the component's own crate contribute that entry, which a foreign crate could not write into the namespace's body. -Two details are easy to misread. The namespace's key is the *marker*, not the path, so a `help:` -list in an error names `GreeterComponent` as implementing the namespace trait even when the path it -routes to is empty. And a component marker declared with generics through the `name:` key of -`#[cgp_component]` carries those generics onto the impl after `__Components__`. +The namespace's key is the *marker* rather than the path, which is easy to misread: a `help:` list in +an error names `GreeterComponent` as implementing the namespace trait even when the path it routes +to is empty. A component marker declared with generics through the `name:` key of +`#[cgp_component]` also carries those generics onto the impl after `__Components__`. ## Formal grammar diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 84ed387d..0506d5bb 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -48,7 +48,8 @@ a different choice and usually not what a higher-order provider wants. `AreaCalculator` is the provider trait it must satisfy. The trait may carry further arguments of its own, and the macro preserves those in order. -Two forms cover more than one bound, and which you need depends on what is being multiplied. +The form to use depends on whether one provider must satisfy several traits, or several providers must +each satisfy one. **One provider, several traits: join them with `+`.** @@ -146,7 +147,7 @@ pub fn rect_area(&self) -> f64 { preference to writing the bound by hand. You read the explicit `Inner: AreaCalculator` form in generated code and older wiring rather than write it. -The choice against its neighbours is about *what* is being depended on, and one of the distinctions is +The choice against its neighbours turns on *what* the implementation depends on, and one distinction is easy to miss because both spellings compile. - **A capability of the context** is [`#[uses]`](uses.md), which imports a consumer trait or an ordinary @@ -154,16 +155,17 @@ easy to miss because both spellings compile. provider satisfies for the context. - **Whatever the context already chose** needs no attribute at all. Calling `self.area()` in the body routes through the context's own wiring, which is a *different dispatch* from - `InnerCalculator::area(self)`: the first asks the context, the second names an implementation - statically. Reach for `#[use_provider]` only when you want the second. + `InnerCalculator::area(self)`: the method call asks the context, and the associated-function call + names an implementation statically. Reach for `#[use_provider]` only when you want the named + implementation. - **A choice made per type rather than fixed** is dispatch rather than parameterization, so it belongs in the wiring: the `open` statement of [`delegate_components!`](../macros/delegate_components.md) maps each type to its own implementation. -One ergonomic option is worth knowing when writing the provider struct by hand. Giving the parameter a -default of [`UseContext`](../providers/use_context.md), as in `pub struct IterSum(...)`, -makes an unparameterized `IterSum` fall back to the context's own wiring, so the wrapper can be dropped in -without naming a base case. +Giving the parameter a default of [`UseContext`](../providers/use_context.md), as in +`pub struct IterSum(...)`, makes an unparameterized `IterSum` fall back to the +context's own wiring, so the wrapper can be used without naming a base case. That option is worth +knowing when writing the provider struct by hand. ## Under the hood @@ -240,12 +242,12 @@ Both parts are required. `ProviderType` names the generic parameter the inner pr `ProviderBound` is the provider trait to require of it, written *without* its leading context argument, which the attribute inserts. -Two restrictions follow from those productions and account for every parse failure this attribute -produces. **`ProviderBound` is a path with plain generic arguments**, not a full `TypeParamBound`, so a -turbofish or an associated-type binding in that position does not parse; a bound of that shape belongs in -the block's own `where` clause. And **the argument holds exactly one provider**, because the -`+`-separated bound list runs to the end of the attribute, so a comma after the first pair lands where a -`+` was expected. That makes this attribute the one exception to the comma-separated convention its +Those productions carry the restrictions that account for every parse failure this attribute produces. +**`ProviderBound` is a path with plain generic arguments**, not a full `TypeParamBound`, so a turbofish +or an associated-type binding in that position does not parse; a bound of that shape belongs in the +block's own `where` clause. And **the argument holds exactly one provider**, because the `+`-separated +bound list runs to the end of the attribute, so a comma after the first pair lands where a `+` was +expected. That makes this attribute the one exception to the comma-separated convention its siblings follow: bind several inner providers by stacking one attribute each. See [Common Mistakes](#common-mistakes). ## Common Mistakes @@ -264,8 +266,8 @@ Use one attribute per provider instead. This is the opposite of the convention f [`#[uses]`](uses.md) and [`#[use_type]`](use_type.md), which do take comma-separated lists, so the habit transfers wrongly. -**The provider and the trait are both required.** There is no bare form naming a provider alone, and -omitting the bound reports the missing colon: +**The provider and the trait are both required.** The attribute accepts no bare form naming a provider +alone, and omitting the bound reports the missing colon: ```text error: expected `:` @@ -274,7 +276,7 @@ error: expected `:` | ^ ``` -**There is no call-site rewriting.** The attribute never turns `self.area()` into +**The attribute does not rewrite call sites.** It never turns `self.area()` into `InnerCalculator::area(self)`, so a body that calls the method on `self` compiles but does something different: it dispatches through the context's own wiring rather than through the parameter. When the intent is to use the inner implementation, spell out the associated-function call. diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index c37f3fbf..a487fc2c 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -22,15 +22,14 @@ bare `Error`: #[use_type(HasErrorType.Error)] ``` -A method can then return `Result`, and the code that writes it is reused as is: it -compiles whether the context chose `anyhow::Error`, `Box`, or a plain `String` as -its error type. The code never names any of those; the context does, in its wiring. +A method can then return `Result`, and that method compiles unchanged whether the +context chose `anyhow::Error`, `Box`, or a plain `String` as its error type. +The method never names any of those; the context does, in its wiring. -`#[use_type]` reads like a `use` statement for a type, which is what it is, and -[Under the hood](#under-the-hood) shows how the bare name resolves. It also has advanced forms a bare -identifier could not express, covered [below](#importing-from-another-type): pinning the type to a -concrete one, importing it from a parameter rather than the context, and tying two abstract types -together. +`#[use_type]` reads like a `use` statement for a type, and [Under the hood](#under-the-hood) shows how +the bare name resolves. It also has advanced forms a bare identifier could not express, covered +[below](#importing-from-another-type): pinning the type to a concrete one, importing it from a +parameter rather than the context, and tying two abstract types together. ## Usage @@ -67,8 +66,9 @@ a local alias: ``` Stacking several `#[use_type]` attributes behaves identically, because the macro collects every -attribute's entries into one list before it resolves any of them, so an alias declared in one is -available to another regardless of which comes first. Reach for a second attribute only when there is a reason. +attribute's entries into one list before it resolves any of them. So an alias declared in one is +available to another regardless of which comes first. Reach for a second attribute only when there is +a reason. ### Pinning a type to a concrete one @@ -179,12 +179,11 @@ separates them. ## When to use it -**Use `#[use_type]` whenever a definition names an abstract type another component supplies.** It is the -recommended form; you read a hand-written supertrait plus `Self::`-qualified paths in existing code rather -than write them. +**Use `#[use_type]` whenever a definition names an abstract type another component supplies.** You read +a hand-written supertrait plus `Self::`-qualified paths in existing code rather than write them. -Its neighbours cover requirements that are not types, and one further construct is the one `#[use_type]` -imports *from*. +Its neighbours handle the requirements that are not types, and one of them declares the type this +attribute imports. - **A capability** is [`#[uses]`](uses.md) for a private bound or [`#[extend]`](extend.md) for a supertrait. Reach for `#[extend]` specifically when the supertrait's methods matter and its associated @@ -196,22 +195,22 @@ imports *from*. the shared name: the provider supplies a type to a context, and the attribute imports one into a definition. -One boundary is worth stating plainly, because getting it wrong produces a confusing error. `#[use_type]` -does not import a construct's **own** associated type, so it stays qualified as `Self::Output`. It -rewrites only the names it was given, so a local type written bare resolves to nothing. A mixed signature -such as `Result` is therefore correct and idiomatic: the local type qualified, the -imported one bare. +`#[use_type]` does not import a construct's **own** associated type, so it stays qualified as +`Self::Output`. That boundary is worth stating plainly, because getting it wrong produces a confusing +error. The attribute rewrites only the names it was given, so a local type written bare resolves to +nothing. A mixed signature such as `Result` is therefore correct and idiomatic: +the local type qualified, the imported one bare. -Finally, prefer an inferred parameter over an abstract type when the type only ever flows through values -the body reads: [`#[impl_generics]`](./impl_generics.md) on a `#[cgp_fn]` is shorter and needs no wiring. +Prefer an inferred parameter over an abstract type when the type only ever flows through values the +body reads: [`#[impl_generics]`](./impl_generics.md) on a `#[cgp_fn]` is shorter and needs no wiring. Climb to an abstract type when the type must be named in the capability's own signature, or when two capabilities have to [agree that they mean the same one](/docs/concepts/abstract-types#one-type-agreed-on-by-everything-that-needs-it). ## Under the hood -`#[use_type]` runs before the surrounding macro, in three steps: it **grounds** each import's own type -positions, **substitutes** every matching bare identifier, then **adds the bound**. +`#[use_type]` runs before the surrounding macro: it **grounds** each import's own type positions, +**substitutes** every matching bare identifier, then **adds the bound**. From this input: diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index cf129a9e..4afefc23 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -9,9 +9,9 @@ Import the capabilities an implementation depends on, reading like a `use` state ## Overview -`#[uses]` imports the capabilities an implementation depends on. It names a -[consumer trait](../macros/cgp_component.md) (or an ordinary Rust trait) that `Self` must satisfy, so the -body can call it. `Self` here is the **context**, the type the implementation runs against: +`#[uses]` names a [consumer trait](../macros/cgp_component.md), or an ordinary Rust trait, that `Self` +must satisfy, so the body can call it. `Self` here is the **context**, the type the implementation runs +against: ```rust #[uses(RectangleArea)] @@ -25,9 +25,9 @@ imports a trait the context itself must satisfy. The requirement stays private to the implementation. A caller who depends on the capability never sees it and never has to repeat it, which is the point of declaring the dependency where the implementation -lives rather than on its public interface. Preferring `#[uses]` over a hand-written bound is the -recommendation. The equivalent `where` clause is the older form you meet in existing code, and -[Under the hood](#under-the-hood) shows the two desugar identically. +lives rather than on its public interface. Prefer `#[uses]` over a hand-written bound. The equivalent +`where` clause is the older form you meet in existing code, and [Under the hood](#under-the-hood) +shows that the two desugar identically. ## Usage @@ -114,10 +114,10 @@ This provider is a two-line adapter: it satisfies the `AreaCalculator` component ## When to use it **Use `#[uses]` for every capability dependency**, in preference to writing the `Self:` bound by hand. -That is the recommendation. You read the hand-written form in existing code rather than write it. +You read the hand-written form in existing code rather than write it. -Two questions decide between `#[uses]` and its neighbours: *what* is being depended on, and *where the -requirement should be visible*. +The choice between `#[uses]` and its neighbours turns on *what* the implementation depends on, and on +*where* the requirement should be visible. - **A value from the context** is not a capability. Use an [`#[implicit]`](implicit.md) argument, which reads a field directly rather than routing through a trait. From 7c122a7a1bdedd8aa8c5ba1bb5bdf227b884f02f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 22:36:14 +0200 Subject: [PATCH 064/516] Revise the attributes reference pages for point-first prose Rewrite the prose of all eleven pages under docs/reference/attributes so that each paragraph leads with its point, names its real subject, and uses plain English. The edits replace pseudo-clefts and "is how" sentences, split semicolon-joined and multi-point sentences, name the actor behind unnamed passives, remove figurative phrases, and move flat "no " negations onto the verb. Four overviews now open with the attribute itself rather than with background. Code blocks, headings, and link targets are unchanged. One factual correction rides along: `#[derive_delegate]` wraps the key list in parentheses, so a single-parameter key `(Shape)` is the bare type rather than a one-element tuple. The page previously said the key is wrapped in a tuple. Co-Authored-By: Claude Fable 5.1 --- docs/reference/attributes/default_impl.md | 86 ++++++++++--------- docs/reference/attributes/derive_delegate.md | 70 ++++++++-------- docs/reference/attributes/extend.md | 66 +++++++-------- docs/reference/attributes/extend_where.md | 82 +++++++++--------- docs/reference/attributes/impl_generics.md | 64 +++++++------- docs/reference/attributes/implicit.md | 88 ++++++++++---------- docs/reference/attributes/index.md | 47 ++++++----- docs/reference/attributes/prefix.md | 68 +++++++-------- docs/reference/attributes/use_provider.md | 69 +++++++-------- docs/reference/attributes/use_type.md | 71 ++++++++-------- docs/reference/attributes/uses.md | 42 +++++----- 11 files changed, 383 insertions(+), 370 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 72284fa9..2ca51272 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -9,10 +9,11 @@ Register a provider as a namespace's default for a key. ## Overview -A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context**, the -type the capability runs against, can opt into and then selectively override. Ordinarily you write a -namespace's entries in its own body. `#[default_impl(...)]` lets a *provider* register itself instead, -at the point where it is defined: +`#[default_impl(...)]` lets a *provider* register itself as a [namespace](/docs/concepts/namespaces)'s +default for a key, at the point where the provider is defined. A namespace is a reusable table of default +wirings that a **context** can opt into and then override entry by entry. (The context is the type the +capability runs against.) Ordinarily you write a namespace's entries in its own body. This attribute +moves one entry onto the provider: ```rust #[cgp_impl(new ShowString)] @@ -45,14 +46,14 @@ impl DefaultImpls1 for String { } ``` -That rule is worth remembering, because the trait's own parameter names suggest the opposite -arrangement (see [`DefaultImpls1`](../traits/namespace/default_impls1.md#the-one-thing-to-get-right)). +Remember that rule, because the trait's own parameter names suggest the opposite arrangement (see +[`DefaultImpls1`](../traits/namespace/default_impls1.md#the-one-thing-to-get-right)). **The key is a type or a `@`-path.** A type key, as above, is the usual form for a per-type default: the type is the value of the component's dispatch parameter, and the component is named inside the lookup trait's arguments. A path key, in [`Path!`](../macros/path.md)'s syntax, binds the provider at a full path inside the namespace. Its common use is a prefixed component's own path, so that a context -which joins the namespace resolves the component with no `for` loop at all: +which joins the namespace resolves the component without any `for` loop: ```rust #[cgp_component(Greeter)] @@ -70,21 +71,21 @@ impl Greeter { } ``` -Unlike [`#[prefix]`](./prefix.md), the macro appends nothing to a path key. You write the whole path, -marker included, and any dispatch type after it, as in `@test.ShowImplComponent.u32`. A path key +Unlike [`#[prefix]`](./prefix.md), the macro does not append anything to a path key. You write the whole +path, marker included, and any dispatch type after it, as in `@test.ShowImplComponent.u32`. A path key cannot declare generic parameters, and it takes neither of the `[…]` and `{…}` grouping forms a [`delegate_components!`](../macros/delegate_components.md) key allows. **Repeat the attribute to register into several tables**, one attribute per table. The argument itself is not comma-separated: each attribute carries exactly one `Key in NamespacePath` pair. -**The path may name any trait**, not only the three CGP ships. A trait of your own with the right shape -works identically, which is why [`DefaultImpls2`](../traits/namespace/default_impls2.md) needed no new construct to -be usable. +**The path may name any trait**, not only the ones CGP ships. A trait of your own with the right shape +works the same way. That is why [`DefaultImpls2`](../traits/namespace/default_impls2.md) did not need a +new construct to be usable. -The three built-in targets are [`DefaultNamespace`](../traits/namespace/default_namespace.md) for a component-only -key, [`DefaultImpls1`](../traits/namespace/default_impls1.md) for a per-type default (the usual choice), and -[`DefaultImpls2`](../traits/namespace/default_impls2.md) for a two-type key. +The built-in targets are [`DefaultNamespace`](../traits/namespace/default_namespace.md) for a +component-only key, [`DefaultImpls1`](../traits/namespace/default_impls1.md) for a per-type default (the +usual choice), and [`DefaultImpls2`](../traits/namespace/default_impls2.md) for a two-type key. ## Examples @@ -161,26 +162,27 @@ with `GreetHello`. ## When to use it -**Reach for it when a provider is the natural default for its key and you want that recorded where the -provider is written.** The alternatives differ in where the entry lives. +**Reach for it when a provider is the natural default for its key and you want that fact recorded where +the provider is written.** The alternatives differ in where the entry lives. - **Use it** when per-type defaults accumulate (a conversion, a formatter, a codec with one provider per type), because then the alternative is a namespace body that has to be edited every time a type is added. - **Write the entry in the namespace body instead** when the defaults belong together as a set, or when the provider is one of several candidates and none is obviously *the* default. A - [`cgp_namespace!`](../macros/cgp_namespace.md) body reads as a table; scattered attributes do not. -- **Do not reach for a namespace at all** until the top-level wiring is long enough to be a problem. - -**One constraint decides where the attribute may be written, and it is Rust's orphan rule rather than -anything CGP chose.** The emitted impl is `impl Namespace<..> for Key`, and Rust accepts it when the -crate owns the namespace trait, or when a local type appears in the impl header ahead of the table -parameter. That local type may be the key itself, or a component named inside the namespace path, so a -crate that owns `ShowImplComponent` may write `String in DefaultImpls1` against the -foreign `DefaultImpls1`. A path key is a `PathCons` list, which is never a local type even when it -contains a local marker, so a [`#[prefix]`](./prefix.md)-ed component's path can be registered **only -in the namespace's own crate**. Wiring that must live downstream goes in the namespace body of the crate -that owns it, or into a local namespace that inherits the foreign one. + [`cgp_namespace!`](../macros/cgp_namespace.md) body reads as a table, whereas scattered attributes do + not. +- **Do not use a namespace at all** until the top-level wiring is long enough to be a problem. + +**Rust's orphan rule, not a CGP choice, decides where you may write the attribute.** The emitted impl is +`impl Namespace<..> for Key`, and Rust accepts it when the crate owns the namespace trait, or when a +local type appears in the impl header ahead of the table parameter. That local type may be the key +itself, or a component named inside the namespace path, so a crate that owns `ShowImplComponent` may +write `String in DefaultImpls1` against the foreign `DefaultImpls1`. A path key is a +`PathCons` list, which is never a local type even when it contains a local marker, so only **the +namespace's own crate** can register a [`#[prefix]`](./prefix.md)-ed component's path. Wiring that must +live downstream goes in the namespace body of the crate that owns it, or into a local namespace that +inherits the foreign one. ## Under the hood @@ -208,13 +210,14 @@ answers it. **The registration impl carries only the parameters naming the key and the provider, plus the table, never the provider's own `where` clause.** That is deliberate, and it lets the attribute work with -ordinary providers: a provider whose bounds come from [`#[use_type]`](./use_type.md), +ordinary providers. A provider whose bounds come from [`#[use_type]`](./use_type.md), [`#[uses]`](./uses.md), [`#[implicit]`](./implicit.md), or [`#[use_provider]`](./use_provider.md) registers cleanly, because those bounds stay on the provider's impl and its -[`IsProviderFor`](../traits/wiring/is_provider_for.md) and are checked when a real context resolves it. +[`IsProviderFor`](../traits/wiring/is_provider_for.md), and the compiler checks them when a real context +resolves the provider. -Consumption runs the other way. A `for in DefaultImpls1 { … }` loop inside -[`delegate_components!`](../macros/delegate_components.md) emits a +A context consumes a registration from the other side. A `for in DefaultImpls1 { … }` +loop inside [`delegate_components!`](../macros/delegate_components.md) emits a [`DelegateComponent`](../traits/wiring/delegate_component.md) impl whose `where` clause projects the default: ```rust @@ -243,7 +246,7 @@ NamespacePath -> TypePath GenericArgs? `Key` is either a Rust `Type` or a `Path`, and the leading `@` tells them apart. A `Type` becomes the emitted impl's `Self`. A `Path` is [`Path!`](../macros/path.md)'s own production and lowers to a `PathCons` list in the same position. `NamespacePath` is the lookup trait with its leading generic -arguments written out. The table parameter is appended by the macro and must not be given. Each attribute takes +arguments written out. The macro appends the table parameter, so do not write it. Each attribute takes exactly one such argument, and the attribute may be repeated. ## Common Mistakes @@ -255,12 +258,12 @@ and the trait's positions follow. The parameter names on **Do not write the table parameter.** The macro appends it, so supplying it yourself makes the path's arity wrong. -**On a prefixed component it is confined to the namespace's crate**, by the orphan rule. This is not -something to work around: put the wiring in the namespace body instead. +**On a prefixed component it is confined to the namespace's crate**, by the orphan rule. Do not try to +work around this. Put the wiring in the namespace body instead. **The lookup trait must be imported.** The emitted impl names it, so [`DefaultImpls1`](../traits/namespace/default_impls1.md) and [`DefaultImpls2`](../traits/namespace/default_impls2.md) need -`use cgp::core::component::…`; [`DefaultNamespace`](../traits/namespace/default_namespace.md) is in the prelude. +`use cgp::core::component::…`. [`DefaultNamespace`](../traits/namespace/default_namespace.md) is in the prelude. **A provider whose impl is generic cannot register a default.** The registration impl copies the provider impl's generic parameters but drops its `where` clause, so a parameter of the impl appears @@ -289,11 +292,12 @@ error[E0119]: conflicting implementations of trait `DefaultImpls1 { } ``` -A **context**, the type the capability runs against, which also owns the wiring, then points the -component at [`UseDelegate`](../providers/use_delegate.md) over a table naming one implementation per -shape, and the generated dispatcher does the lookup. +A **context** then points the component at [`UseDelegate`](../providers/use_delegate.md) over a table +naming one implementation per shape, and the generated dispatcher does the lookup. (The context is the +type the capability runs against, and it also owns the wiring.) `open` replaced this because the indirection turned out to be unnecessary. Every [`#[cgp_component]`](../macros/cgp_component.md) already generates a -[`RedirectLookup`](../providers/redirect_lookup.md) impl, and `open` routes through that instead, so the -per-type entries live on the context itself, the wiring names no second table type, and the component -needs no attribute at all. +[`RedirectLookup`](../providers/redirect_lookup.md) impl, and `open` routes through that instead. So the +per-type entries live on the context itself, the wiring does not name a second table type, and the +component does not need an attribute. ## Usage @@ -69,8 +68,8 @@ once: ``` **To dispatch on several parameters independently, repeat the attribute**, one per dispatcher. Each names -its own wrapper type, and only the parameter in that wrapper's brackets is used as its key. The rest flow -through unchanged: +its own wrapper type, and the macro uses only the parameter in that wrapper's brackets as its key. The +rest flow through unchanged: ```rust #[cgp_component(Computer)] @@ -84,7 +83,7 @@ pub trait CanCompute { ``` `UseDelegate` is the wrapper CGP provides, but the machinery is not tied to it. Any struct of the same -shape works, which is how you add a second, independent dispatcher: a user-defined +shape works, so you add a second, independent dispatcher by defining your own wrapper. A user-defined `pub struct UseInputDelegate(pub PhantomData);` is all the second line above needs. @@ -155,13 +154,14 @@ delegate_components! { } ``` -This form needs no wrapper, no second table type, and nothing on the component. The two forms dispatch -on the same parameter and resolve to the same implementations. +This form does not need a wrapper, a second table type, or an attribute on the component. The two forms +dispatch on the same parameter and resolve to the same implementations. ## When to use it **Do not add `#[derive_delegate]` to a new component.** Use the `open` statement of -[`delegate_components!`](../macros/delegate_components.md), which needs no attribute and no table type. +[`delegate_components!`](../macros/delegate_components.md), which needs neither an attribute nor a table +type. A few situations still involve the attribute, and only the dispatcher that `open` cannot express is a reason to write it. @@ -204,11 +204,13 @@ names something that is itself a provider for that `Shape`, and the method simpl same trait ordinary wiring is made of, which is why you write the table with [`delegate_components!`](../macros/delegate_components.md) like any other. -The tuple key and the reserved generic names are worth recognizing in the real output. **The key is -wrapped in a tuple**, as `DelegateComponent<(Shape), …>`, so that a single-parameter key and a -multi-parameter one compose uniformly: a `UseDelegate<(Code, Input)>` declaration produces -`DelegateComponent<(Code, Input), …>` with no other change. And the generics carry reserved names: the -table is `__Components__` and the looked-up entry `__Delegate__`, alongside the provider trait's own +The parenthesized key and the reserved generic names are worth recognizing in the real output. **The +macro wraps the key list in parentheses**, so a multi-parameter key becomes a tuple: a +`UseDelegate<(Code, Input)>` declaration produces `DelegateComponent<(Code, Input), …>` with no other +change. With one parameter, the parentheses in `DelegateComponent<(Shape), …>` are only grouping, and +Rust reads the key as the bare `Shape`. That is why the table's entries are written as +`Rectangle: RectangleArea` rather than as one-element tuples. And the generics carry reserved names: +the table is `__Components__` and the looked-up entry `__Delegate__`, alongside the provider trait's own `__Context__`. **A component's supertraits carry into the dispatcher.** The provider trait records each supertrait as a @@ -218,8 +220,8 @@ appears here too, so a component declaring an error type through `__Context__: HasErrorType`. When several `#[derive_delegate]` attributes are present, the macro generates one impl per attribute, -each keyed on its own parameter and otherwise identical. The two are independent, so a context may dispatch on either -or nest one table inside the other. +each keyed on its own parameter and otherwise identical. The impls are independent, so a context may +dispatch on either or nest one table inside the other. ## Formal grammar @@ -238,9 +240,9 @@ KeyParams -> IDENTIFIER Both parts are required. `Wrapper` is a bare identifier rather than a path, so a wrapper reached through a module path has to be imported first. `KeyParams` are **identifiers**, not types: each must name a generic parameter the trait declares, and a type expression such as `Vec` in that position does not parse. The -parenthesized form must list at least one parameter (an empty `()` is rejected with *expect non-empty -tuple list of identifiers in use_delegate_spec*), and a single parameter written bare is keyed the same way -a one-element tuple would be. The attribute may be repeated, once per dispatcher. +parenthesized form must list at least one parameter (the parser rejects an empty `()` with *expect +non-empty tuple list of identifiers in use_delegate_spec*), and a single parameter written bare is keyed +the same way a one-element list would be. The attribute may be repeated, once per dispatcher. ## Common Mistakes @@ -262,7 +264,7 @@ there is nothing for it to do. `UseDelegate` table is a coherence conflict, because each produces its own table entry for that key. A wiring entry expands to two impls, and both of them collide, so the compiler reports the conflict twice, once for `IsProviderFor` and once for `DelegateComponent`. The `DelegateComponent` report is the readable -one, since its trait argument names the component at issue: +one, because its trait argument names the component at issue: ```text error[E0119]: conflicting implementations of trait `DelegateComponent` diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index ba62e05b..e4d2444d 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -18,20 +18,20 @@ must also satisfy it, and every caller may rely on it. #[extend(HasName)] ``` -**`#[extend]` is the `pub use` to `#[uses]`'s `use`**, which is the clearest way to tell the pair apart. -Both take the same syntax and both read as imports. But `#[uses]` imports a capability for the -implementation's own use and keeps it out of sight, where `#[extend]` re-exports it as part of the -contract. +**`#[extend]` relates to `#[uses]` as `pub use` relates to `use`.** This comparison is the clearest way +to tell the pair apart. Both take the same syntax and both read as imports. But `#[uses]` imports a +capability for the implementation's own use and keeps it private, whereas `#[extend]` re-exports it as +part of the contract. -That framing is also why `#[extend]` is preferred over Rust's native supertrait syntax on a +The same comparison explains why CGP prefers `#[extend]` over Rust's native supertrait syntax on a [`#[cgp_component]`](../macros/cgp_component.md). Writing `pub trait CanGreet: HasName` reads as inheritance from a parent, an is-a relationship that a CGP supertrait is not. `#[extend(HasName)]` reads as importing a capability the trait passes on, which is the accurate description. The two generate the same trait, so this is a choice about how the definition reads. -On [`#[cgp_fn]`](../macros/cgp_fn.md) the attribute is not merely preferred but necessary. The `#[cgp_fn]` +On [`#[cgp_fn]`](../macros/cgp_fn.md) the attribute is necessary, not only preferred. The `#[cgp_fn]` macro treats a `where` clause you write as an implementation detail and never puts it on the generated -trait, so you cannot spell a supertrait by hand. `#[extend]` is the only mechanism for one. +trait, so you cannot write a supertrait by hand. `#[extend]` is the only way to add one. ## Usage @@ -47,17 +47,17 @@ them across attributes, and they accumulate. Prefer one attribute carrying the w [`#[uses]`](uses.md). The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on -[`#[cgp_component]`](../macros/cgp_component.md). It is **not** available on -[`#[cgp_impl]`](../macros/cgp_impl.md), which has no trait definition of its own to attach a supertrait to. -The supertraits belong to the component's trait, and a provider states its private needs with -[`#[uses]`](uses.md) instead. +[`#[cgp_component]`](../macros/cgp_component.md). The macro does **not** accept it on +[`#[cgp_impl]`](../macros/cgp_impl.md), because a provider does not define a trait that a supertrait +could attach to. The supertraits belong to the component's trait, and a provider states its private needs +with [`#[uses]`](uses.md) instead. ### When the supertrait supplies a type If the reason for the supertrait is that the trait's signatures name a type the other component provides -(an error type, a scalar, a runtime), reach for [`#[use_type]`](use_type.md) instead. It adds the -supertrait *and* rewrites bare mentions of the type into their fully qualified form, so the signature -reads `Result` rather than `Result::Error>`: +(an error type, a scalar, a runtime), use [`#[use_type]`](use_type.md) instead. It adds the supertrait +*and* rewrites bare mentions of the type into their fully qualified form, so the signature reads +`Result` rather than `Result::Error>`: ```rust #[cgp_component(Loader)] @@ -94,7 +94,7 @@ pub fn full_label(&self) -> String { } ``` -The body can call both getters, and so can anyone holding a `T: FullLabel`, which is the difference from +The body can call both getters, and so can anyone holding a `T: FullLabel`. That is the difference from `#[uses]`. A function that takes a labelled value can format its name without asking for `HasName` separately. @@ -113,9 +113,9 @@ available, and so may every caller. ## When to use it -**Reach for `#[extend]` when callers of the trait should be able to rely on the capability too**, and for -a capability supertrait on a `#[cgp_component]` in preference to native `:` syntax. Reach for something -else when the requirement belongs elsewhere, and the choice turns on where it should be visible. +**Reach for `#[extend]` when callers of the trait must be able to rely on the capability too**, and for +a capability supertrait on a `#[cgp_component]` in preference to native `:` syntax. Use something else +when the requirement belongs elsewhere. The choice turns on where the requirement should be visible. - **The implementation needs it privately.** Use [`#[uses]`](uses.md). This is the common case by a wide margin: most dependencies are private to the implementation, and putting one on the trait forces it on @@ -126,15 +126,15 @@ else when the requirement belongs elsewhere, and the choice turns on where it sh on `Self`. Use [`#[extend_where]`](extend_where.md), which puts it on the generated trait's own `where` clause. -A supertrait widens the contract permanently, and that is the cost to weigh before promoting anything. -You cannot later narrow it without breaking every implementor, and it demands the capability from -contexts that only ever call the one method the trait actually declares. Prefer `#[uses]` unless callers -genuinely need the guarantee. +A supertrait widens the contract permanently, and that cost decides whether to promote a requirement. +You cannot later remove it without breaking every implementor, and it demands the capability from +contexts that only call the one method the trait declares. Prefer `#[uses]` unless callers need the +guarantee. ## Under the hood -On a `#[cgp_fn]`, each entry lands in **two** places: as a supertrait of the generated trait, and as a -`Self:` predicate on the generated implementation. From this input: +On a `#[cgp_fn]`, each entry lands on both the generated trait, as a supertrait, and the generated +implementation, as a `Self:` predicate. From this input: ```rust #[cgp_fn] @@ -164,7 +164,7 @@ Compare [`#[uses]`](uses.md), which emits only the predicate and leaves the trai That single difference is the whole of the distinction. On a `#[cgp_component]` the supertrait goes on the consumer trait, and it also joins the `where` clause of -the generated consumer blanket implementation, since that implementation can only apply where the +the generated consumer blanket implementation, because that implementation can only apply where the supertrait holds: ```rust @@ -183,10 +183,10 @@ where } ``` -Here the result is identical to `pub trait CanGreet: HasName`, so on a component -`#[extend]` generates nothing the language cannot already spell. It remains the preferred form because -it presents the bound as an import rather than as inheritance, and because it keeps the `use`/`pub use` -pairing with `#[uses]` reading consistently across both macros. +Here the result is identical to `pub trait CanGreet: HasName`, so on a component `#[extend]` generates +only what the language can already express. It remains the preferred form because it presents the bound +as an import rather than as inheritance, and because it keeps the `use`/`pub use` pairing with `#[uses]` +reading consistently across both macros. ## Formal grammar @@ -204,8 +204,8 @@ differ in where the bounds land, not in the grammar. ## Common Mistakes -**On a `#[cgp_impl]` the attribute is not recognized at all**, rather than being accepted and ignored. -Nothing consumes it, so it falls through to the compiler as an unknown attribute: +**On a `#[cgp_impl]` the compiler does not recognize the attribute**, rather than accepting and ignoring +it. The macro does not consume it, so it reaches the compiler as an unknown attribute: ```text error: cannot find attribute `extend` in this scope @@ -213,8 +213,8 @@ error: cannot find attribute `extend` in this scope Expect a second error alongside it, because the bound was never added. The body's calls to the capability then fail with `E0599`, reporting that the method exists but its trait bounds were not satisfied. Both -errors have the same cause: move the requirement to [`#[uses]`](uses.md), or onto the component's trait -where supertraits belong. +errors have the same cause, and one fix removes both: move the requirement to [`#[uses]`](uses.md), or +onto the component's trait where supertraits belong. **A supertrait cannot be narrowed later.** Because every implementor and every caller may now rely on it, removing an entry from `#[extend]` is a breaking change in a way removing one from `#[uses]` is not. This diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 47279d9d..749e5bc7 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -9,33 +9,33 @@ Add `where` predicates to a generated trait's own definition, not just to its im ## Overview -A [`#[cgp_fn]`](../macros/cgp_fn.md) treats the `where` clause you write on the function as an -implementation detail: the bounds land on the generated implementation and never appear on the generated -trait. That default keeps a capability's requirements out of sight of its callers, and it is almost -always right. - -The cost is that an unsatisfiable requirement becomes invisible. A bound on the implementation only -decides which **contexts** the implementation covers, a context being the type the capability runs -against, which supplies the values it needs as its fields. So naming the capability for a type that can -never satisfy it is not an error. It is a bound nobody can prove, accepted quietly, and the complaint -arrives later and somewhere else. `#[extend_where]` moves the predicate onto the trait, where it becomes a -condition of naming the trait at all: +`#[extend_where]` moves a `where` predicate onto the trait that a [`#[cgp_fn]`](../macros/cgp_fn.md) +generates, so the predicate becomes a condition of naming the trait at all. By default, `#[cgp_fn]` +treats the `where` clause you write on the function as an implementation detail: the bounds land on the +generated implementation and never appear on the generated trait. That default keeps a capability's +requirements private to its implementation, and it is almost always right. + +The cost of that default is that an unsatisfiable requirement becomes invisible. A bound on the +implementation only decides which **contexts** the implementation covers. (A context is the type the +capability runs against, and it supplies the values the capability needs as its fields.) So the compiler +accepts a caller that names the capability for a type that can never satisfy it. The bound stays +unproven, and the error appears later, at a different place. `#[extend_where]` puts the predicate where +the compiler checks it as soon as the trait is named: ```rust #[extend_where(Scalar: Clone)] ``` -Promoting a predicate does **not** hand it to callers, and the distinction is worth being exact about, -because it is easy to get backwards. A trait's `where` clause is a precondition they must prove, not a -guarantee they receive, so a caller naming the trait still writes the bound themselves. Promotion -instead makes callers write the bound, and reports a wrong one against the trait rather than deferring -it. +Promoting a predicate does **not** give it to callers as a guarantee, and this distinction is easy to +reverse. A trait's `where` clause is a precondition callers must prove, not a guarantee they receive. So a +caller that names the trait still writes the bound itself, and the compiler reports a missing bound +against the trait instead of deferring it. `#[extend_where]` is the `where`-clause sibling of [`#[extend]`](extend.md). Both put a requirement into -the trait's public interface; they differ in position, and in what the reader gets. `#[extend]` adds a -**supertrait**, a bound on `Self`, which callers do receive by elaboration. `#[extend_where]` adds a -**predicate**, which can bound anything, most usefully one of the trait's own generic parameters, which -a supertrait cannot reach. +the trait's public interface. They differ in position, and in what the reader gets. `#[extend]` adds a +**supertrait**, a bound on `Self`, which callers do receive, because Rust elaborates a supertrait bound +automatically. `#[extend_where]` adds a **predicate**, which can bound anything, most usefully one of the +trait's own generic parameters, which a supertrait cannot reach. ## Usage @@ -50,10 +50,10 @@ these are arbitrary predicates: a bound on any type in scope, including an assoc higher-ranked bound, or a lifetime bound. The macro adds each to the generated trait's `where` clause verbatim, and keeps it on the implementation as well. -**`#[extend_where]` is supported only on [`#[cgp_fn]`](../macros/cgp_fn.md).** It has no meaning on -[`#[cgp_impl]`](../macros/cgp_impl.md) or [`#[cgp_component]`](../macros/cgp_component.md), because in -those the `where` clause you write is already part of the definition. Nothing needs promoting, so -write the bound as an ordinary `where` clause directly. +**Only [`#[cgp_fn]`](../macros/cgp_fn.md) supports `#[extend_where]`.** On +[`#[cgp_impl]`](../macros/cgp_impl.md) or [`#[cgp_component]`](../macros/cgp_component.md) the `where` +clause you write is already part of the definition, so there is nothing to promote. Write the bound as +an ordinary `where` clause there. ## Examples @@ -92,9 +92,9 @@ where } ``` -**Leave `Clone` on the implementation instead and that same function compiles**, with no diagnostic at -all: `Ctx: Scale` is simply a bound no type can ever prove, and nothing says so until somebody -tries to call `scale_it` with a concrete context. The attribute exists to remove that silence. +**With `Clone` left on the implementation instead, that same function compiles** without a diagnostic. +`Ctx: Scale` is then a bound that no type can prove, and the compiler says so only when somebody +calls `scale_it` with a concrete context. The attribute exists to report that error earlier. A caller who *can* satisfy the predicate states it as usual, and cannot avoid stating it: @@ -110,10 +110,10 @@ where ## When to use it -**Reach for `#[extend_where]` when a predicate is part of what the capability means**, and you want it -enforced where the trait is named rather than silently narrowing which contexts the implementation covers. -That is a real but uncommon need, and the default of leaving bounds on the implementation is right for -almost everything. +**Reach for `#[extend_where]` when a predicate is part of what the capability means**, and you want the +compiler to enforce it where the trait is named, rather than letting it narrow which contexts the +implementation covers without a report. That is a real but uncommon need, and the default of leaving +bounds on the implementation is right for almost everything. The useful test is who the bound is *about*. A bound describing how the body computes its answer belongs on the implementation. A bound describing what the capability requires of its own type parameters, something @@ -122,14 +122,15 @@ that would be part of the signature if you were writing the trait by hand, belon Other constructs carry the requirements that belong elsewhere. - **A bound on `Self`** is a supertrait, so use [`#[extend]`](extend.md). `#[extend_where]` can express it, - but a supertrait reads as what it is, and unlike a predicate it *is* handed to callers by elaboration. + but a supertrait reads as what it is, and unlike a predicate Rust *does* hand it to callers by + elaboration. - **A private requirement**, the overwhelmingly common case, belongs in the function's own `where` clause, or in [`#[uses]`](uses.md) when it is a capability. - **An abstract type pinned to a concrete one** is [`#[use_type]`](use_type.md)'s equality form, which adds the bound and lets the signature name the type as a bare word. -Do not reach for it to spare callers a bound: it has the opposite effect. If the goal is that holding the -capability should imply something, a supertrait does that, and the bound has to be on `Self` for it to work. +Do not use it to spare callers a bound, because it has the opposite effect. If holding the capability +should imply something, use a supertrait, which requires the bound to be on `Self`. ## Under the hood @@ -154,14 +155,14 @@ where } ``` -The trait carries only the promoted predicate; the function's own bound is absent from it, which is the +The trait carries only the promoted predicate. The function's own bound is absent from it, which is the default this attribute overrides. The implementation carries all of them, and their **order is fixed**: the function's own `where` clause first, then whatever the attributes contribute, then the [`HasField`](../traits/field-access/has_field.md) bounds from [`#[implicit]`](implicit.md) arguments, -which are always appended last. That order is worth knowing when reading a long `where` clause in an -expansion, since it tells you where each bound came from. +which are always appended last. That order helps when you read a long `where` clause in an expansion, +because it tells you where each bound came from. The context parameter is literally `__Context__` in the emitted code and appears as `Self` inside the implementation. @@ -198,11 +199,12 @@ error[E0277]: the trait bound `Scalar: Clone` is not satisfied note: required by a bound in `Scale` ``` -Adding `Scalar: Clone` to the caller's own `where` clause is the fix, and is expected rather than a +The fix is to add `Scalar: Clone` to the caller's own `where` clause. This is the expected use, not a workaround. -**On any host other than `#[cgp_fn]` the attribute is not recognized**, rather than accepted and ignored. -Nothing consumes it, so it reaches the compiler as an unknown attribute: +**On any host other than `#[cgp_fn]` the compiler does not recognize the attribute**, rather than +accepting and ignoring it. The macro does not consume it, so it reaches the compiler as an unknown +attribute: ```text error: cannot find attribute `extend_where` in this scope diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 102ebf3f..0a5413ff 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -10,16 +10,17 @@ through a field and callers never name it. ## Overview -A [`#[cgp_fn]`](../macros/cgp_fn.md) puts every generic parameter you write on the function onto -both the generated trait and its implementation. That is right for a type the caller chooses. But a -body often needs a type that nobody chooses: a database handle, a name that only has to be printable, -a scalar read from a field. The **context**, the type the capability runs against and the owner of the -fields the body reads, already fixes that type through the field. A parameter on the trait would then -make every caller, and every capability built on this one, declare a parameter and repeat its bounds -for a type they never touch. - -`#[impl_generics(...)]` declares such a parameter on the implementation only. The trait stays free of -parameters, and the compiler infers the parameter from the field the body reads: +`#[impl_generics(...)]` declares a generic parameter on the implementation that a +[`#[cgp_fn]`](../macros/cgp_fn.md) generates, and keeps it off the generated trait. By default, +`#[cgp_fn]` puts every generic parameter you write on the function onto both the trait and its +implementation. That is right for a type the caller chooses. But a body often needs a type that nobody +chooses: a database handle, a name that only has to be printable, a scalar read from a field. The +**context**, the type the capability runs against and the owner of the fields the body reads, already +fixes that type through the field. A parameter on the trait would then make every caller, and every +capability built on this one, declare a parameter and repeat its bounds for a type they never touch. + +With `#[impl_generics]`, the trait stays free of parameters, and the compiler infers the parameter from +the field the body reads: ```rust #[cgp_fn] @@ -30,14 +31,14 @@ pub fn greet(&self, #[implicit] name: &Name) -> String { ``` The `Greet` trait is not generic. A context qualifies by carrying a `name` field of some type that -implements `Display`, and the compiler resolves `Name` from that field's type. Nothing is wired, and -nothing is declared beyond the field itself. +implements `Display`, and the compiler resolves `Name` from that field's type. The context does not need +wiring or any declaration beyond the field itself. -The cost is that the type is concealed rather than named. It exists only where a value of it flows +The cost is that the type is hidden rather than named. It exists only where a value of it flows through an [`#[implicit]`](./implicit.md) argument, so nothing else can refer to it: not this capability's own signature, not another capability, and not a second provider. When the type must be named, promote it to an abstract type with [`#[cgp_type]`](../macros/cgp_type.md) and import it with -[`#[use_type]`](./use_type.md). [When to use it](#when-to-use-it) says where that line falls. +[`#[use_type]`](./use_type.md). [When to use it](#when-to-use-it) says where that boundary lies. ## Usage @@ -55,22 +56,22 @@ pub fn describe(&self, #[implicit] name: &Name, #[implicit] count: &Count) -> St Each parameter joins the implementation's generic list, after the context parameter and after any generics the function declares itself. A bound written inline, as `Name: Display` above, stays with the parameter. A bound may also go in the function's own `where` clause, which lands on the -implementation as well. The attribute may be repeated, and the lists are concatenated, but one +implementation as well. You may repeat the attribute, and the macro concatenates the lists, but one attribute with a comma-separated list reads as one declaration and is the form to prefer. **Every parameter must be pinned by the type of an implicit argument.** The compiler accepts a parameter on an impl only where the impl determines it, and the only place a `#[cgp_fn]` implementation determines one is the field bound an `#[implicit]` argument produces. `&Name` pins -`Name`, and a nested position such as `&Pool` pins `Db`. A parameter absent from every implicit -argument is rejected with `E0207`; see [Common Mistakes](#common-mistakes). +`Name`, and a nested position such as `&Pool` pins `Db`. The compiler rejects a parameter that does +not appear in any implicit argument with `E0207`. See [Common Mistakes](#common-mistakes). The list accepts a lifetime or a const parameter as well as a type parameter, because the macro reads ordinary generic parameters. Type parameters are the case the attribute exists for. **Only [`#[cgp_fn]`](../macros/cgp_fn.md) reads `#[impl_generics]`.** A [`#[cgp_impl]`](../macros/cgp_impl.md) block's own generic list is already impl-only, so a provider -declares such a parameter there directly. A [`#[cgp_component]`](../macros/cgp_component.md) has no -implementation of its own to carry one. +declares such a parameter there directly. A [`#[cgp_component]`](../macros/cgp_component.md) does not +have an implementation of its own to carry one. ## Examples @@ -102,8 +103,8 @@ pub fn greet_both(person: &Person, robot: &Robot) { } ``` -`Person` and `Robot` both implement `Greet` through the one blanket implementation, with nothing -wired. For `Person` the compiler resolves `Name` to `String`, and for `Robot` to `u32`. Neither type +`Person` and `Robot` both implement `Greet` through the one blanket implementation, without any +wiring. For `Person` the compiler resolves `Name` to `String`, and for `Robot` to `u32`. Neither type appears anywhere except in the field. A capability built on `greet` never learns that `Name` exists: @@ -123,12 +124,12 @@ repeat `Name: Display`, and pass the parameter on to everything that calls it. **Start with `#[impl_generics]` for a type that only ever flows through implicit arguments.** It is the shortest form, it does not need wiring, and it reads as "this works with any `name` field of a -compatible type". You must climb to an abstract type once the type has to be *named* somewhere the +compatible type". You must move to an abstract type once the type has to be *named* somewhere the inferred form cannot reach. - **The type appears in the capability's signature.** An impl-only parameter is not in scope on the - trait, so a return type or an explicit parameter cannot mention it. This condition arrives the - moment a capability hands a value of the type back to its caller. + trait, so a return type or an explicit parameter cannot mention it. This condition applies as soon as + a capability returns a value of the type to its caller. - **Two capabilities must agree on the type.** A transaction type only means something relative to its database, so the capability that opens one and the capability that commits it must mean the same type. Each implementation infers its own parameter, so inferred parameters cannot state the @@ -138,8 +139,8 @@ In both cases declare the type with [`#[cgp_type]`](../macros/cgp_type.md), impo [`#[use_type]`](./use_type.md), and let the context supply it by wiring. Do not answer either condition with a generic parameter on the function. Such a parameter lands on the trait, so every caller and every intermediate capability must declare it and repeat its bounds whether they touch it -or not. It also misplaces the decision: `` on a trait says the caller chooses the database type, -though the application determines it. +or not. It also puts the decision in the wrong place: `` on a trait says the caller chooses the +database type, though the application determines it. Some neighbours cover what this attribute is not for. @@ -196,7 +197,7 @@ ImplGenericsArgs -> GenericParam ( `,` GenericParam )* `,`? `GenericParam` is the Rust grammar's own production for one entry of a generic parameter list: a lifetime, a type parameter with optional bounds, or a const parameter. The list may be empty, and the attribute may be repeated. Because the production is Rust's, a parameter default such as `T = u32` -parses, and the compiler then rejects it; see [Common Mistakes](#common-mistakes). +parses, and the compiler then rejects it. See [Common Mistakes](#common-mistakes). ## Common Mistakes @@ -230,7 +231,7 @@ error[E0433]: cannot find type `Db` in this scope The `&Pool` argument is fine, because the macro strips it into a field bound on the implementation, where `Db` is in scope. The `Db::Row` return type stays on the trait, and fails. A bare `Db` in the signature reports the same headline under `E0425` instead, so search for both -codes. The fix is a decision the macro cannot make for you: promote the type to an +codes. You must decide the fix, because the macro cannot: promote the type to an [abstract type](../macros/cgp_type.md) so it can be named everywhere, or keep `#[impl_generics]` and stop naming it. The [compile errors](../errors.md#a-name-the-generated-code-cannot-see) page reads the full diagnostic. @@ -261,8 +262,9 @@ error[E0404]: expected trait, found type parameter `Count` Rename the parameter, or give the trait another name with `#[cgp_fn(CanCount)]`. -**On any host other than `#[cgp_fn]` the attribute is unknown**, rather than accepted and ignored. -Nothing consumes it, so it reaches the compiler as an attribute that does not exist: +**On any host other than `#[cgp_fn]` the compiler does not recognize the attribute**, rather than +accepting and ignoring it. The macro does not consume it, so it reaches the compiler as an attribute +that does not exist: ```text error: cannot find attribute `impl_generics` in this scope @@ -279,7 +281,7 @@ parameter in the block's own generic list, which is already impl-only. - [`#[extend_where]`](./extend_where.md) — the trait-side sibling: a predicate callers must see. - [`#[uses]`](./uses.md) — a capability bound on `Self`, the other kind of private requirement. - [`#[use_type]`](./use_type.md) and [`#[cgp_type]`](../macros/cgp_type.md) — the abstract-type - form to climb to when the type must be named. + form to move to when the type must be named. - [`HasField`](../traits/field-access/has_field.md) — the bound that carries the inference. The ideas behind it: diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 6e5c29cf..d23c99c7 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -10,8 +10,8 @@ Source a function argument from a same-named field on the context. ## Overview `#[implicit]` lets a CGP construct read a field value from a generic **context** by naming the field -like an ordinary function argument. The context is the type the construct runs against, and the -implicit argument is hidden from the public signature. +like an ordinary function argument. The context is the type the construct runs against, and the macro +hides the implicit argument from the public signature. ```rust #[cgp_fn] @@ -20,25 +20,24 @@ pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> } ``` -A call like `rect.rectangle_area()` does not require the arguments to be passed explicitly. Instead, the -`width` and `height` fields are automatically extracted from the `rect` value. Any type carrying a -`width` and a `height` field can call it. +A caller writes `rect.rectangle_area()` and passes nothing. The macro reads `width` and `height` from +the fields of `rect`. Any type with a `width` and a `height` field can call the method. `#[implicit]` is shorter to write than the alternatives, such as [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) or the direct use of [`HasField`](../traits/field-access/has_field.md). With those, you declare that the context has each -field and then fetch it by hand, so you have to understand the mechanism behind field access, such as +field and then fetch it by hand. So you have to understand the mechanism behind field access, such as how a type-level [`Symbol!`](../macros/symbol.md) and a `PhantomData` tag work. `#[implicit]` keeps all of that behind an argument that reads as `width: f64`, and the argument's *name* names the field. So `#[implicit]` is the recommended way to read a context's own field, and usually the first piece of CGP anyone writes. A reader who understands functions and arguments can write a working capability and -meet the machinery later, when they have a reason to care. +learn the machinery later, when they need it. ## Usage -`#[implicit]` is a bare marker on a typed argument. It takes no arguments in any form, and a list or -name-value spelling is rejected rather than ignored: +`#[implicit]` is a bare marker on a typed argument. It takes no arguments of its own, and the macro +rejects a list or name-value spelling rather than ignoring it: ```rust fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { @@ -46,19 +45,19 @@ fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { } ``` -`#[implicit]` works only inside the two macros that rewrite a function body into an implementation: +`#[implicit]` works only inside the macros that rewrite a function body into an implementation: [`#[cgp_fn]`](../macros/cgp_fn.md) and the methods of a [`#[cgp_impl]`](../macros/cgp_impl.md) block. It is not a macro of its own, so it does nothing on an ordinary function. -The macro constrains where the attribute may appear. The function must take `self` first, since the -field is read from `self`. The argument must be a bare identifier, not a destructuring or `mut` +The macro constrains where the attribute may appear. The function must take `self` first, because the +macro reads the field from `self`. The argument must be a bare identifier, not a destructuring or `mut` pattern. And a **mutable** implicit argument carries further requirements of its own, covered in [Mutable arguments](#mutable-arguments) below. ### How the argument's type decides the read -The body works with the argument's type, and the macro inserts whatever conversion bridges it to the -stored field. The table below is the whole mapping: +The body works with the argument's type, and the macro inserts the conversion from the stored field to +that type. The table below lists every case: | The argument's type | The field's type | How it is read | |---|---|---| @@ -74,16 +73,17 @@ stored field. The table below is the whole mapping: | `Option<&mut str>` | `Option` | `.as_deref_mut()` | | [`MRef<'a, T>`](../types/mref.md) | `T` | by reference, wrapped as `MRef::Ref(…)` | -The rows for `&str`, for an owned type, and for `MRef` are the ones most easily misread. `&str` is the +The rows for `&str`, for an owned type, and for `MRef` are the ones most often misread. `&str` is the case most often wanted and least obvious: the field is a `String`, and the argument borrows from it, so a context never has to store a `&str`. An owned argument *clones* the value. That is cheap for an -`f64` and less so for a large `String`, which is a reason to take `&str` or `&T` wherever the body only -needs to read. And `MRef` is the owned-or-borrowed form: it reads a plain `T` field, hands the body a -value that may be either, and is the one reference-shaped row with no mutable counterpart. +`f64` and costly for a large `String`, so take `&str` or `&T` wherever the body only needs to read. And +`MRef` is the owned-or-borrowed form. It reads a plain `T` field, gives the body a value that may be +either, and is the one reference-shaped row without a mutable counterpart. The macro matches the `MRef` row by *shape* rather than by resolving the name: a single-segment `MRef` -with one lifetime argument and one type argument. Anything else spelled `MRef` falls into the owned row -and is cloned, which is the one place a small change to the type silently changes the read. +with one lifetime argument and one type argument. Anything else spelled `MRef` falls into the owned row, +and the macro clones it. This is the one place where a small change to the type changes the read without +a warning. The same rules govern the getter traits, so learning them once covers everywhere CGP reads a field. @@ -94,7 +94,7 @@ An implicit argument is mutable when its type carries a `&mut`: the outer refere reads through [`HasFieldMut`](../traits/field-access/has_field_mut.md) and `get_field_mut` rather than through [`HasField`](../traits/field-access/has_field.md) and `get_field`, so it borrows the field for writing. -A mutable argument requires a `&mut self` receiver, since a function cannot borrow a field mutably +A mutable argument requires a `&mut self` receiver, because a function cannot borrow a field mutably through a shared `&self`. It must also be the only implicit argument on its function, because reading one field mutably borrows the whole context exclusively and cannot coexist with any other field read. @@ -130,12 +130,12 @@ pub fn print_area(rect: &Rectangle) { } ``` -`Rectangle` derives [`HasField`](../derives/derive_has_field.md), which is its entire qualification. -This program wires nothing. +`Rectangle` derives [`HasField`](../derives/derive_has_field.md), and that derive is all it needs to +qualify. The program does not wire anything. -Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) provider the attribute behaves identically and mixes -freely with the method's real arguments. The implicit ones vanish from the signature while `to` and -`body` remain: +Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) provider the attribute behaves the same way and mixes +with the method's ordinary arguments. The macro removes the implicit arguments from the signature and +keeps `to` and `body`: ```rust #[cgp_impl(new SendViaSmtp)] @@ -153,13 +153,13 @@ calls. ## When to use it **Reach for `#[implicit]` by default whenever a provider needs a value from its own context.** It is the -shortest form, it introduces no new declaration, and it uses the same field access a getter would, so a -getter trait declared only to read a field adds a name for no benefit. +shortest form, it does not add a declaration, and it uses the same field access a getter would. A getter +trait declared only to read a field therefore adds a name without a benefit. -That reach is wider than it first appears. An implicit argument reads a plain `&T` by reference with no -clone, so it suits a large value as well as a small one. A field that several providers each need is -declared as the same implicit argument in each of them, which costs nothing and keeps every provider's -requirements visible where the provider is written. +The default covers more cases than it first appears to. An implicit argument reads a plain `&T` by +reference without a clone, so it suits a large value as well as a small one. When several providers +need the same field, each declares the same implicit argument. That costs nothing, and it keeps every +provider's requirements visible where the provider is written. A **getter trait** covers the cases an implicit argument cannot reach. @@ -173,8 +173,8 @@ A **getter trait** covers the cases an implicit argument cannot reach. return it, which keeps the type abstract for callers in a way a concrete argument cannot. For those, use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md), which generates the getter from the -method name. [`#[cgp_getter]`](../macros/cgp_getter.md) goes further still and is genuinely advanced: -reach for it only when the *field a getter reads* should be chosen per context at wiring time. +method name. [`#[cgp_getter]`](../macros/cgp_getter.md) is the advanced form. Use it only when the +*field a getter reads* should be chosen per context at wiring time. ## Under the hood @@ -220,36 +220,36 @@ field name. The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form i `cargo cgp expand` resugars it back. The context parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours. -The slice rows and the mutable rows generate something other than a `Value = T` equality, which is -worth recognizing because it reads oddly at first. A slice argument bounds the *associated type* -instead, so `&[u8]` emits `HasField + 'static>`. Any field whose -value can be viewed as a `[u8]` then qualifies, rather than one exact type. And every mutable form -swaps the trait as well as the accessor: `&mut u64` emits -`HasFieldMut` and reads through `get_field_mut`. +The slice rows and the mutable rows generate a different bound from the `Value = T` equality, and it +reads oddly at first. A slice argument bounds the *associated type* instead, so `&[u8]` emits +`HasField + 'static>`. Any field whose value can be viewed as a +`[u8]` then qualifies, rather than one exact type. And every mutable form swaps the trait as well as the +accessor: `&mut u64` emits `HasFieldMut` and reads through +`get_field_mut`. Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the rewrite is the same, except the bounds join that provider's `where` clause. One addition shows only in a multi-method block: the macro collects the bounds across *every* method and de-duplicates them, so two methods each taking `#[implicit] name: &str` add one `HasField` bound rather than two. The macro still emits the -`let` bindings per method, since each body needs its own. +`let` bindings per method, because each body needs its own. ## Common Mistakes -**The attribute takes no arguments**, and says so rather than ignoring what it was given: +**The attribute takes no arguments**, and the macro says so rather than ignoring the argument: ```text error: `#[implicit]` does not take any arguments; write it as a bare `#[implicit]` ``` **The argument must be a plain identifier.** A destructuring pattern reports `Expected an identifier`, -and a `mut` binding is rejected with the fix in the message: +and the macro rejects a `mut` binding with the fix in the message: ```text error: Mutable variables are not allowed in implicit arguments. (Explicitly clone a `&` reference if you want a mutable local copy of the value) ``` -**A function with implicit arguments must take `self` first**, since there is otherwise no context to +**A function with implicit arguments must take `self` first**, because there is otherwise no context to read from: ```text diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index eb5513d4..df4f7a68 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -5,45 +5,46 @@ sidebar_position: 0 # Attributes -An attribute here is a modifier, not a macro of its own. Each one is an option a host macro reads, -[`#[cgp_impl]`](../macros/cgp_impl.md), [`#[cgp_fn]`](../macros/cgp_fn.md), or -[`#[cgp_component]`](../macros/cgp_component.md), to refine the trait or implementation that macro -generates. This page groups every attribute in this section by the job it does, in roughly the order -most CGP code reaches for them. +An attribute here is a modifier, not a macro of its own. Each one is an option that a host macro reads +to refine the trait or implementation it generates. The hosts are +[`#[cgp_impl]`](../macros/cgp_impl.md), [`#[cgp_fn]`](../macros/cgp_fn.md), and +[`#[cgp_component]`](../macros/cgp_component.md). This page groups every attribute in this section by +the job it does, in roughly the order most CGP code uses them. If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here. This page -is the fuller map, for once the essentials are familiar. +is the fuller guide, for a reader who already knows the essentials. ## Reading a value from the context [`#[implicit]`](./implicit.md) marks a function argument that the macro reads from a same-named field -on the context, the type the capability runs against, rather than from the caller. A provider that needs -a value then reads like an ordinary function that takes it. Almost every provider uses the attribute, -and it is usually the first piece of CGP anyone writes. +on the context rather than from the caller. The context is the type the capability runs against. A +provider that needs a value then reads like an ordinary function that takes it. Almost every provider +uses the attribute, and it is usually the first piece of CGP anyone writes. ## Importing a dependency -These attributes declare what an implementation depends on, each reading like an import. Most -dependencies belong on the implementation, out of sight of callers, and `#[extend]` and -`#[extend_where]` put one on the generated trait instead, for when every caller must rely on it. +These attributes declare what an implementation depends on, and each reads like an import. Most +dependencies belong on the implementation, where callers never see them. `#[extend]` and +`#[extend_where]` put a dependency on the generated trait instead, for the case where every caller must +rely on it. [`#[uses]`](./uses.md) imports a consumer trait, or an ordinary Rust trait, that the context must -satisfy, which is the common case. [`#[use_type]`](./use_type.md) imports an abstract type another +satisfy. This is the common case. [`#[use_type]`](./use_type.md) imports an abstract type that another component supplies, such as an error type, and lets the signature name it as a bare word instead of a -qualified path. [`#[use_provider]`](./use_provider.md) imports a provider trait a named inner provider -must satisfy, the dependency a higher-order provider declares. +qualified path. [`#[use_provider]`](./use_provider.md) imports a provider trait that a named inner +provider must satisfy, which is the dependency a higher-order provider declares. [`#[extend]`](./extend.md) and [`#[extend_where]`](./extend_where.md) put the requirement on the generated -trait rather than on the implementation, so every caller inherits it: `#[extend]` adds a supertrait, and -`#[extend_where]` adds a `where` predicate a supertrait cannot express. +trait rather than on the implementation, so every caller inherits it. `#[extend]` adds a supertrait, and +`#[extend_where]` adds a `where` predicate that a supertrait cannot express. ## Naming a type the body needs [`#[impl_generics]`](./impl_generics.md) declares a generic parameter on the generated implementation -alone, for a type that a field of the context fixes: a database handle, a printable name. The trait +alone, for a type that a field of the context fixes: a database handle, or a printable name. The trait stays free of the parameter, so callers never name the type, and the compiler infers it from the field an -implicit argument reads. It is the first form to reach for when a body needs a type nobody chooses, and -[`#[use_type]`](./use_type.md) is the form to climb to once the type must be named in a signature. +implicit argument reads. Use it first when a body needs a type that nobody chooses. Move to +[`#[use_type]`](./use_type.md) once a signature must name the type. ## Registering into a namespace @@ -51,12 +52,12 @@ These attributes let a definition register itself into a [namespace](/docs/conce point where it is written, rather than in the namespace's own body. [`#[prefix]`](./prefix.md) goes on a component and routes it under a path prefix, so contexts that join the namespace address it by that path and a wiring table reads as a tree. [`#[default_impl]`](./default_impl.md) goes on a provider and -binds it as the namespace's default for a key. Reach for the prefix as soon as grouping helps a reader, -and for the default once per-type defaults accumulate. +binds it as the namespace's default for a key. Use the prefix as soon as grouping helps a reader, and +the default once per-type defaults accumulate. ## Legacy [`#[derive_delegate]`](./derive_delegate.md) generates the older `UseDelegate` dispatcher for a component generic over a type parameter. The `open` statement of -[`delegate_components!`](../macros/delegate_components.md) replaced it for new code; the page is here +[`delegate_components!`](../macros/delegate_components.md) replaced it for new code. The page remains because you will meet the form in existing wiring and in CGP's own error and handler components. diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index e0791132..e8116dd8 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -10,12 +10,12 @@ namespace addresses the component by that path. ## Overview -A [namespace](/docs/concepts/namespaces) is a reusable wiring table that a **context**, the type the -capability runs against, joins with one line and then overrides where it needs to. A namespace answers -a lookup by *routing* it: asked for a component, it says where to look next. `#[prefix(...)]` is how -a component contributes its own route. Written on the component's trait beside -[`#[cgp_component]`](../macros/cgp_component.md), it registers the component into the named namespace -under a path prefix: +`#[prefix(...)]` registers a component into a [namespace](/docs/concepts/namespaces) under a path +prefix. Written on the component's trait beside [`#[cgp_component]`](../macros/cgp_component.md), it +adds the component's own route to the namespace. A namespace is a reusable wiring table that a +**context** joins with one line and then overrides where it needs to. (The context is the type the +capability runs against.) A namespace answers a lookup by *routing* it: asked for a component, it says +where to look next. ```rust #[cgp_component(Greeter)] @@ -25,11 +25,11 @@ pub trait CanGreet { } ``` -Read that as: *in `AppNamespace`, `GreeterComponent` is found at `@app.GreeterComponent`.* A context -that joins `AppNamespace` and asks for `GreeterComponent` is sent to that path, and whatever is bound -there is the provider that runs. The attribute records only the route. A provider is bound at the -path somewhere else: by a direct `@app.GreeterComponent: GreetHello` entry on the context, by an -entry in the namespace's body, or by a [`#[default_impl]`](./default_impl.md) on a provider. +Read that as: *in `AppNamespace`, `GreeterComponent` is found at `@app.GreeterComponent`.* When a +context joins `AppNamespace` and asks for `GreeterComponent`, the namespace sends it to that path, and +the provider bound there is the one that runs. The attribute records only the route. Something else +binds a provider at the path: a direct `@app.GreeterComponent: GreetHello` entry on the context, an +entry in the namespace's body, or a [`#[default_impl]`](./default_impl.md) on a provider. Prefixes turn a flat wiring table into a tree. With components registered under `@app.auth`, `@app.finance`, and `@app.error`, related entries sort together, a reader finds the auth wiring @@ -56,7 +56,7 @@ of the macros built on it, [`#[cgp_type]`](../macros/cgp_type.md) and **The path is a prefix, and the macro appends the component marker for you.** `#[prefix(@app in DefaultNamespace)]` on `CanGreet` registers `GreeterComponent` at -`@app.GreeterComponent`. Writing the marker yourself doubles it; see +`@app.GreeterComponent`. Writing the marker yourself doubles it. See [Common Mistakes](#common-mistakes). Segments follow [`Path!`](../macros/path.md)'s convention. A lowercase identifier that is not a @@ -90,8 +90,8 @@ on a prefixed component is a foreign path. ### Choosing a prefix -A prefix is part of the component's public surface, and expensive to change once wiring depends on -it, so choose it for every implementation the component might have rather than for the one you are +A prefix is part of the component's public surface, and costly to change once wiring depends on +it. So choose it with every implementation the component might have in mind, not only the one you are writing now. Give components separate sub-paths whenever they are likely to need separate providers, even when the current wiring happens to treat them alike. Abstract types belong under a `types` sub-path of their layer, such as `@app.auth.types`, because a production context typically points the logic @@ -148,8 +148,8 @@ so the lookup falls through to `DefaultNamespace`, which redirects to `@app.Gree `App`'s own table binds that path to `GreetHello`. **Environmental context, self-targeted**: `App` exists to carry the wiring and a `name` field, and the capability is about `App` itself. -A second context joins the same namespace and binds a different provider at the same path, with -nothing repeated between the two: +A second context joins the same namespace and binds a different provider at the same path, without +repeating anything from the first: ```rust #[cgp_impl(new GreetFormally)] @@ -197,22 +197,22 @@ delegate_components! { **Reach for `#[prefix]` as soon as a wiring table has enough components that grouping helps a reader.** It costs nothing at the point of use, it is the one namespace tool without a downstream -restriction, and the table it produces reads at once as a directory listing. It is also the -form a library uses to publish its components into a shared namespace. +restriction, and the table it produces reads like a directory listing. It is also the form a library +uses to publish its components into a shared namespace. Some situations call for something else. -- **A component only ever wired directly on a context** needs no prefix. The `open` statement of - [`delegate_components!`](../macros/delegate_components.md) dispatches it per type without a +- **A component only ever wired directly on a context** does not need a prefix. The `open` statement + of [`delegate_components!`](../macros/delegate_components.md) dispatches it per type without a namespace, and the two do not combine on one component. -- **Binding a provider at a path** is the job of the wiring, not of the component. Use a direct entry - on the context, a [`cgp_namespace!`](../macros/cgp_namespace.md) body entry, or - [`#[default_impl]`](./default_impl.md) on the provider. +- **The wiring binds a provider at a path**, not the component. Use a direct entry on the context, a + [`cgp_namespace!`](../macros/cgp_namespace.md) body entry, or [`#[default_impl]`](./default_impl.md) + on the provider. - **A small, explicitly delegated bundle** is an [aggregate provider](../macros/delegate_components.md#defining-the-target-at-the-same-time), - which contexts adopt by delegating named components to it. Namespaces and prefixes earn their extra - indirection when there are many components, when inheritance is wanted, or when a library publishes - defaults for applications it does not know about. + which contexts adopt by delegating named components to it. Namespaces and prefixes justify their + extra indirection when there are many components, when inheritance is wanted, or when a library + publishes defaults for applications it does not know about. ## Under the hood @@ -279,13 +279,13 @@ namespaces. ## Common Mistakes -**The marker is appended for you, so do not write it.** `#[prefix(@app.GreeterComponent in Ns)]` +**The macro appends the marker, so do not write it.** `#[prefix(@app.GreeterComponent in Ns)]` registers the component at `@app.GreeterComponent.GreeterComponent`. It compiles, and a context that binds `@app.GreeterComponent` then finds its entry never consulted, because the route and the binding name different paths. Write the prefix alone. -**Registering routes a component and binds nothing.** A prefixed component compiles even when -nothing binds its path, and so does a context that joins the namespace. Only a +**Registering routes a component but does not bind a provider.** A prefixed component compiles even +when nothing binds its path, and so does a context that joins the namespace. Only a [`check_components!`](../macros/check_components.md) reports it, as an unsatisfied bound on the *path* rather than on a provider: @@ -321,9 +321,9 @@ bare marker, while the prefix routes under the path, so the per-type entries `op consulted. Write the entries with the full prefixed path instead, as [`cgp_namespace!`](../macros/cgp_namespace.md#common-mistakes) explains. -**Case decides a segment's meaning silently.** `@app` is a type-level string and `@App` is a type, -both are valid, and a capitalization slip routes to a path nothing binds. The failure surfaces as the -unbound path above, without a hint about the letter; see +**Case decides a segment's meaning without a warning.** `@app` is a type-level string and `@App` is a +type, both are valid, and a capitalization slip routes to a path nothing binds. The failure surfaces +as the unbound path above, without a hint about the letter. See [`Path!`](../macros/path.md#common-mistakes). **On `#[cgp_auto_getter]` the attribute is accepted and dropped.** That macro runs the same attribute @@ -331,8 +331,8 @@ collector as `#[cgp_component]`, to apply `#[extend]` and `#[use_type]`, but it component to register, so a `#[prefix]` on it registers nothing and reports nothing. A getter that must live in a namespace is a [`#[cgp_getter]`](../macros/cgp_getter.md) component. -**On `#[cgp_impl]` or `#[cgp_fn]` the attribute is unknown.** Nothing consumes it there, so it -reaches the compiler as an attribute that does not exist: +**On `#[cgp_impl]` or `#[cgp_fn]` the compiler does not recognize the attribute.** Neither macro +consumes it, so it reaches the compiler as an attribute that does not exist: ```text error: cannot find attribute `prefix` in this scope diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 0506d5bb..c770d205 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -9,21 +9,21 @@ Depend on another provider by name, importing the provider trait it must satisfy ## Overview -An implementation can depend on *another* implementation: a wrapper that scales whatever an inner -calculator produces, a retry layer over whatever performs a request. This shape is a -[higher-order provider](/docs/concepts/higher-order-providers), and `#[use_provider]` declares its -dependency by importing the [provider trait](../macros/cgp_component.md) the inner provider must satisfy: +`#[use_provider]` declares that an implementation depends on *another* implementation, by importing the +[provider trait](../macros/cgp_component.md) the inner provider must satisfy. An implementation with such +a dependency is a [higher-order provider](/docs/concepts/higher-order-providers): a wrapper that scales +whatever an inner calculator produces, or a retry layer over whatever performs a request. ```rust #[use_provider(InnerCalculator: AreaCalculator)] ``` That reads as *`InnerCalculator` is an `AreaCalculator` for this context*, and it is the provider-side -counterpart to [`#[uses]`](uses.md). Where `#[uses]` imports a **consumer trait** (or an ordinary Rust -trait) that the **context** must satisfy, `#[use_provider]` imports a **provider trait** that a named -provider must satisfy for the context. The context is the type the implementation runs against. Both read -as importing a dependency; they differ only in whether the thing depended on is a capability of the -context or a provider. +counterpart to [`#[uses]`](uses.md). `#[uses]` imports a consumer trait (or an ordinary Rust trait) that +the **context** must satisfy. `#[use_provider]` imports a provider trait that a named provider must +satisfy for the context. The context is the type the implementation runs against. Both attributes read +as importing a dependency. They differ only in whether the dependency is a capability of the context or +a provider. The inner provider is a named type rather than a method on the context, so the body calls it as an associated function and passes the context: @@ -32,7 +32,7 @@ associated function and passes the context: let base_area = InnerCalculator::area(self); ``` -`#[use_provider]` writes the bound behind that call; it does not rewrite the call. Writing `self.area()` +`#[use_provider]` writes the bound behind that call. It does not rewrite the call. Writing `self.area()` instead would route through whatever provider the context has itself wired for `AreaCalculator`, which is a different choice and usually not what a higher-order provider wants. @@ -64,10 +64,10 @@ each satisfy one. #[use_provider(P: PerimeterCalculator)] ``` -Stacking is the intended form here rather than a fallback, because a comma-separated list of -provider-and-trait pairs is *not* accepted (see [Common Mistakes](#common-mistakes)). This differs from -[`#[uses]`](uses.md) and [`#[use_type]`](use_type.md), where commas are the preferred way to carry several -entries, so it is worth remembering as the exception. +Stacking is the intended form here rather than a fallback, because the parser does *not* accept a +comma-separated list of provider-and-trait pairs (see [Common Mistakes](#common-mistakes)). This differs +from [`#[uses]`](uses.md) and [`#[use_type]`](use_type.md), where commas are the preferred way to carry +several entries, so remember `#[use_provider]` as the exception. `#[use_provider]` is accepted on [`#[cgp_impl]`](../macros/cgp_impl.md) and on [`#[cgp_fn]`](../macros/cgp_fn.md), and it works the same way on both. @@ -126,7 +126,7 @@ delegate_components! { ``` Because the wrapper never names a particular inner implementation, the same `ScaledArea` composes over any -of them. Composition is itself a type, so `type ScaledRectangle = ScaledArea;` is a +of them. The composition is itself a type, so `type ScaledRectangle = ScaledArea;` is a complete way to name the combination. The attribute is also useful for depending on one *specific* implementation rather than a parameter. A @@ -156,25 +156,25 @@ easy to miss because both spellings compile. - **Whatever the context already chose** needs no attribute at all. Calling `self.area()` in the body routes through the context's own wiring, which is a *different dispatch* from `InnerCalculator::area(self)`: the method call asks the context, and the associated-function call - names an implementation statically. Reach for `#[use_provider]` only when you want the named + names an implementation statically. Use `#[use_provider]` only when you want the named implementation. - **A choice made per type rather than fixed** is dispatch rather than parameterization, so it belongs in the wiring: the `open` statement of [`delegate_components!`](../macros/delegate_components.md) maps each type to its own implementation. -Giving the parameter a default of [`UseContext`](../providers/use_context.md), as in +A default of [`UseContext`](../providers/use_context.md) on the parameter, as in `pub struct IterSum(...)`, makes an unparameterized `IterSum` fall back to the -context's own wiring, so the wrapper can be used without naming a base case. That option is worth -knowing when writing the provider struct by hand. +context's own wiring, so a context can use the wrapper without naming a base case. This option matters +when you write the provider struct by hand. ## Under the hood -A [provider trait](../macros/cgp_component.md) is not shaped like the consumer trait it came from: the +A [provider trait](../macros/cgp_component.md) is not shaped like the consumer trait it came from. The original `Self` moves into an explicit leading type parameter for the context, so the real bound on an -inner provider is `InnerCalculator: AreaCalculator`, with a context argument the consumer trait has -no counterpart for. `#[use_provider]` writes that `` for you. It inserts the context type as the -provider trait's leading argument and appends the completed bound to the `where` clause, and nothing else -changes: the macro emits the body as written. From the `ScaledArea` example: +inner provider is `InnerCalculator: AreaCalculator`. The consumer trait has no counterpart for that +context argument. `#[use_provider]` writes that `` for you: it inserts the context type as the +provider trait's leading argument and appends the completed bound to the `where` clause. Nothing else +changes, and the macro emits the body as written. From the `ScaledArea` example: ```rust #[cgp_impl(new ScaledArea)] @@ -209,8 +209,8 @@ The `Self` you wrote in the attribute is the context, so it appears as `__Contex name the surrounding macro inserted. Writing `#[use_provider(InnerCalculator: AreaCalculator)]` is therefore exactly equivalent to writing `where InnerCalculator: AreaCalculator` by hand. -On a [`#[cgp_fn]`](../macros/cgp_fn.md) the same insertion happens, and because that macro's -implementation is written *for* the context the bound reads with `Self` directly: +On a [`#[cgp_fn]`](../macros/cgp_fn.md) the same insertion happens. Because that macro's implementation +is written *for* the context, the bound reads with `Self` directly: ```rust impl<__Context__> RectArea for __Context__ @@ -244,11 +244,12 @@ which the attribute inserts. Those productions carry the restrictions that account for every parse failure this attribute produces. **`ProviderBound` is a path with plain generic arguments**, not a full `TypeParamBound`, so a turbofish -or an associated-type binding in that position does not parse; a bound of that shape belongs in the +or an associated-type binding in that position does not parse. A bound of that shape belongs in the block's own `where` clause. And **the argument holds exactly one provider**, because the `+`-separated bound list runs to the end of the attribute, so a comma after the first pair lands where a `+` was -expected. That makes this attribute the one exception to the comma-separated convention its -siblings follow: bind several inner providers by stacking one attribute each. See [Common Mistakes](#common-mistakes). +expected. That makes this attribute the one exception to the comma-separated convention its siblings +follow: bind several inner providers by stacking one attribute each. See +[Common Mistakes](#common-mistakes). ## Common Mistakes @@ -264,10 +265,10 @@ error: expected `+` Use one attribute per provider instead. This is the opposite of the convention for [`#[uses]`](uses.md) and [`#[use_type]`](use_type.md), which do take comma-separated lists, so the habit -transfers wrongly. +from those attributes leads to this error. -**The provider and the trait are both required.** The attribute accepts no bare form naming a provider -alone, and omitting the bound reports the missing colon: +**The provider and the trait are both required.** The attribute does not accept a bare provider name, +and omitting the bound reports the missing colon: ```text error: expected `:` @@ -279,7 +280,7 @@ error: expected `:` **The attribute does not rewrite call sites.** It never turns `self.area()` into `InnerCalculator::area(self)`, so a body that calls the method on `self` compiles but does something different: it dispatches through the context's own wiring rather than through the parameter. When the -intent is to use the inner implementation, spell out the associated-function call. +intent is to use the inner implementation, write the associated-function call. ## Related constructs @@ -289,7 +290,7 @@ intent is to use the inner implementation, spell out the associated-function cal - [`UseContext`](../providers/use_context.md) — the usual default for an inner-provider parameter. - [`delegate_components!`](../macros/delegate_components.md) — where a composed wrapper is wired. - [`check_components!`](../macros/check_components.md) — its `#[check_providers(...)]` form checks each - layer of a nested stack separately, which is how a broken layer is localized. + layer of a nested stack separately, which localizes a broken layer. The ideas behind it: diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index a487fc2c..30763cbc 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -24,10 +24,10 @@ bare `Error`: A method can then return `Result`, and that method compiles unchanged whether the context chose `anyhow::Error`, `Box`, or a plain `String` as its error type. -The method never names any of those; the context does, in its wiring. +The method never names any of those. The context names one, in its wiring. `#[use_type]` reads like a `use` statement for a type, and [Under the hood](#under-the-hood) shows how -the bare name resolves. It also has advanced forms a bare identifier could not express, covered +the bare name resolves. It also has advanced forms that a bare identifier could not express, covered [below](#importing-from-another-type): pinning the type to a concrete one, importing it from a parameter rather than the context, and tying two abstract types together. @@ -40,7 +40,7 @@ Apply `#[use_type]` beside the macro it modifies, naming a trait and the associa ``` The part before the `.` is the trait and the identifier after it is the type. The **separator is a dot, -not `::`**, and that is deliberate: it leaves `::` free for the trait's own path, so +not `::`**, and that is deliberate. It leaves `::` free for the trait's own path, so `#[use_type(errors::HasErrorType.Error)]` imports from a trait named by path and `#[use_type(HasFooType.Foo)]` imports from a particular generic instantiation. @@ -51,7 +51,7 @@ The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md), ### Importing several types -Separate entries with commas, and **prefer one attribute carrying the whole list**, since it reads as a +Separate entries with commas, and **prefer one attribute carrying the whole list**, because it reads as a single import list: ```rust @@ -67,26 +67,27 @@ a local alias: Stacking several `#[use_type]` attributes behaves identically, because the macro collects every attribute's entries into one list before it resolves any of them. So an alias declared in one is -available to another regardless of which comes first. Reach for a second attribute only when there is -a reason. +available to another regardless of which comes first. Use a second attribute only when there is a +reason. ### Pinning a type to a concrete one -An `= Type` clause imports the type *and* constrains it, which is how a provider says "this only works when +An `= Type` clause imports the type *and* constrains it. A provider uses it to say "this only works when the error type is `anyhow::Error`": ```rust #[use_type(HasErrorType.{Error = anyhow::Error})] ``` -That emits `Self: HasErrorType` in place of the plain bound. The macro substitutes the -right-hand side too, so it may name another import, which is how two abstract types are tied together: +That emits `Self: HasErrorType` in place of the plain bound. The macro substitutes +the right-hand side too, so it may name another import. One import can therefore tie two abstract types +together: ```rust #[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})] ``` -The pin is an implementation-side constraint, so it is **rejected on +The pin is an implementation-side constraint, so the macro **rejects it on [`#[cgp_component]`](../macros/cgp_component.md)**, whose trait definition has nowhere to put it. ### Importing from another type @@ -99,8 +100,8 @@ parameter rather than on `Self`: ``` `Scalar` now expands to `::Scalar`. The clause scopes over the whole entry, so a -braced group projects every type in it against the same target, and because `in` is a reserved word it can -never be mistaken for a type name. +braced group projects every type in it against the same target. And because `in` is a reserved word, the +parser can never mistake it for a type name. This form also lets an import parameterize the trait it comes from. An alias may appear in another entry's `in` clause *or* in its trait arguments, and the macro resolves the chain for you: @@ -114,7 +115,7 @@ order (see [Under the hood](#under-the-hood)), provided they do not form a cycle ## Examples -One abstract scalar threaded through a component and a provider, with neither writing `Self::` anywhere: +One abstract scalar shared by a component and a provider, with neither writing `Self::` anywhere: ```rust use cgp::prelude::*; @@ -140,7 +141,7 @@ impl AreaCalculator { } ``` -The component gains `HasScalarType` as a supertrait and the provider gains it as a bound, and every +The component gains `HasScalarType` as a supertrait, and the provider gains it as a bound. Every `Scalar` in both becomes the same qualified projection, so the fields the provider reads and the value it returns are guaranteed to agree on whatever scalar the context chose. @@ -186,7 +187,7 @@ Its neighbours handle the requirements that are not types, and one of them decla attribute imports. - **A capability** is [`#[uses]`](uses.md) for a private bound or [`#[extend]`](extend.md) for a - supertrait. Reach for `#[extend]` specifically when the supertrait's methods matter and its associated + supertrait. Use `#[extend]` specifically when the supertrait's methods matter and its associated types are not named in your signatures, the case where `#[use_type]` has nothing to rewrite. - **A value from a field** is an [`#[implicit]`](implicit.md) argument. - **The type itself** is declared with [`#[cgp_type]`](../macros/cgp_type.md) and bound to a concrete type @@ -196,15 +197,15 @@ attribute imports. definition. `#[use_type]` does not import a construct's **own** associated type, so it stays qualified as -`Self::Output`. That boundary is worth stating plainly, because getting it wrong produces a confusing -error. The attribute rewrites only the names it was given, so a local type written bare resolves to -nothing. A mixed signature such as `Result` is therefore correct and idiomatic: -the local type qualified, the imported one bare. +`Self::Output`. This rule is worth stating plainly, because breaking it produces a confusing error. The +attribute rewrites only the names it was given, so a local type written bare resolves to nothing. A +mixed signature such as `Result` is therefore correct and idiomatic: the local type +qualified, the imported one bare. Prefer an inferred parameter over an abstract type when the type only ever flows through values the -body reads: [`#[impl_generics]`](./impl_generics.md) on a `#[cgp_fn]` is shorter and needs no wiring. -Climb to an abstract type when the type must be named in the capability's own signature, or when two -capabilities have to +body reads: [`#[impl_generics]`](./impl_generics.md) on a `#[cgp_fn]` is shorter and does not need +wiring. Move to an abstract type when the type must be named in the capability's own signature, or when +two capabilities have to [agree that they mean the same one](/docs/concepts/abstract-types#one-type-agreed-on-by-everything-that-needs-it). ## Under the hood @@ -242,8 +243,8 @@ where **Where the bound lands depends on the target.** When the type is projected from `Self` it becomes a *supertrait* of the generated trait, and also a `where` bound on the implementation. When an `in Context` clause names some other type, a supertrait of `Self` would be wrong, so the macro adds a plain -`Context: Trait` predicate. That predicate goes on the implementation, and on `#[cgp_fn]` and -`#[cgp_component]` it goes on the generated trait's own `where` clause as well, since the trait's +`Context: Trait` predicate. That predicate goes on the implementation. On `#[cgp_fn]` and +`#[cgp_component]` it goes on the generated trait's own `where` clause as well, because the trait's signatures now mention the projection and would not otherwise be well-formed. A plain unbounded `` on your function is therefore enough: @@ -261,7 +262,7 @@ An equality pin is the exception: it stays on the implementation, and the macro **What substitution touches.** The rewrite matches a single-segment type path with no arguments whose identifier is an imported name or alias, anywhere it appears: a return type, an argument, a `where` predicate, a local binding. It also reaches an alias used to *qualify* a path, so `Transaction::begin()` -becomes `<::Transaction>::begin()`, since `::Assoc::method` is +becomes `<::Transaction>::begin()`, because `::Assoc::method` is not valid syntax. The rewrite leaves one position alone: a **bare alias in expression position**, which names a value, @@ -275,10 +276,10 @@ let typed: Marker = todo!(); // becomes ::Marker **Grounding, and why order does not matter.** The macro resolves each import against the imports it *depends on* rather than the ones written before it, so every arrangement of the same entries produces -the same substitutions and the same bounds. Only the order the bounds are listed in follows the source. A chain like -`#[use_type(HasC.C in B, HasB.B in A, HasA.A)]` grounds exactly as its front-to-back spelling does, -and two imports may share one target as readily as chain through it. Only a **cycle** has no valid order; -see [Common Mistakes](#common-mistakes). +the same substitutions and the same bounds. Only the order the bounds are listed in follows the source. A +chain like `#[use_type(HasC.C in B, HasB.B in A, HasA.A)]` grounds exactly as its front-to-back +spelling does, and two imports may share one target as readily as chain through it. A **cycle** is the +only arrangement without a valid order. See [Common Mistakes](#common-mistakes). ## Formal grammar @@ -300,11 +301,11 @@ UseTypeIdent -> IDENTIFIER ( `as` IDENTIFIER )? ( `=` Type )? ``` `TraitPath` and `ContextPath` are ordinary Rust `TypePath`s, whose final segment may carry generic -arguments; their `::` segments belong to the path, while the `.` after the trait begins the +arguments. Their `::` segments belong to the path, while the `.` after the trait begins the associated-type list. An omitted `in ContextPath` defaults the target to `Self`. In each `UseTypeIdent` the leading `IDENTIFIER` is the associated type's own name, `as` gives it a local alias to write in -signatures, and `= Type` pins it with an equality bound, accepted on `#[cgp_fn]` and `#[cgp_impl]` and -rejected on `#[cgp_component]`. +signatures, and `= Type` pins it with an equality bound. The pin is accepted on `#[cgp_fn]` and +`#[cgp_impl]` and rejected on `#[cgp_component]`. ## Common Mistakes @@ -327,7 +328,7 @@ acyclic, since a cycle has no valid grounding order. A self-referential import such as `#[use_type(HasAType.A in A)]` is the degenerate case and reports the same way. -**An equality pin is rejected on a component trait**, since a trait definition cannot carry an +**An equality pin is rejected on a component trait**, because a trait definition cannot carry an implementation-side constraint: ```text @@ -338,8 +339,8 @@ Pin the type on the provider with [`#[cgp_impl]`](../macros/cgp_impl.md) instead [`#[cgp_fn]`](../macros/cgp_fn.md). **A construct's own associated type must stay qualified.** Writing a local `type Output` as a bare -`Output` leaves an identifier the substitution has no entry for, so it resolves to nothing. Write -`Self::Output`, and do not list it in a `#[use_type]` attribute. +`Output` leaves an identifier that the substitution has no entry for, so the compiler cannot resolve it. +Write `Self::Output`, and do not list it in a `#[use_type]` attribute. ## Related constructs diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 4afefc23..5d4293e7 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -17,14 +17,14 @@ against: #[uses(RectangleArea)] ``` -That reads as *this implementation uses the `RectangleArea` capability*, the same thing a `use` -statement means for a name, and the body can then call `self.rectangle_area()` as though the capability -had been imported. It is the consumer-side counterpart to [`#[use_provider]`](use_provider.md): where -`#[use_provider]` imports a provider trait a named provider must satisfy for the context, `#[uses]` -imports a trait the context itself must satisfy. +That reads as *this implementation uses the `RectangleArea` capability*, the same meaning a `use` +statement has for a name. The body can then call `self.rectangle_area()` as though it had imported +the capability. `#[uses]` is the consumer-side counterpart to [`#[use_provider]`](use_provider.md). +`#[use_provider]` imports a provider trait that a named provider must satisfy for the context, whereas +`#[uses]` imports a trait that the context itself must satisfy. The requirement stays private to the implementation. A caller who depends on the capability never sees -it and never has to repeat it, which is the point of declaring the dependency where the implementation +it and never has to repeat it. That is the point of declaring the dependency where the implementation lives rather than on its public interface. Prefer `#[uses]` over a hand-written bound. The equivalent `where` clause is the older form you meet in existing code, and [Under the hood](#under-the-hood) shows that the two desugar identically. @@ -42,17 +42,17 @@ Each entry is a capability, optionally with type arguments: a bare `RectangleAre `Self: RectangleArea`, and `CanCompute` becomes `Self: CanCompute`. **The trait need not be a CGP construct.** `#[uses(Display)]` and `#[uses(AsRef<[u8]>)]` are accepted and -preferred over the equivalent hand-written clause: the attribute only cares that the bound is one a +preferred over the equivalent hand-written clause. The attribute only requires that the bound is one a context can satisfy, so an ordinary Rust trait imports exactly as a capability does. -**Prefer one attribute carrying every dependency**, as in `#[uses(RectangleArea, Display)]`, since a -single list reads as a single set of requirements. Entries may also be split across several -`#[uses(...)]` attributes on the same item, and they accumulate into one bound, but reach for a second -attribute only when there is a reason rather than by default. +**Prefer one attribute carrying every dependency**, as in `#[uses(RectangleArea, Display)]`, because a +single list reads as a single set of requirements. You may also split entries across several +`#[uses(...)]` attributes on the same item, and the macro merges them into one bound. Use a second +attribute only when there is a reason. `#[uses(...)]` is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on -[`#[cgp_impl]`](../macros/cgp_impl.md). In both it imports into the thing being defined, and it does not -care how the imported capability was itself produced. +[`#[cgp_impl]`](../macros/cgp_impl.md). In both, it imports into the item being defined, and it does not +matter how the imported capability was itself produced. ### Bounds beyond the simple form @@ -108,7 +108,7 @@ impl AreaCalculator { } ``` -This provider is a two-line adapter: it satisfies the `AreaCalculator` component by deferring to whatever +This provider is a short adapter: it satisfies the `AreaCalculator` component by calling whatever `rectangle_area` computes. Any context with the fields that capability needs can wire it. ## When to use it @@ -158,8 +158,8 @@ where } ``` -That asymmetry is the mechanism rather than a detail: callers name `DescribeArea`, and it says nothing -about `BaseArea` or `Display`, so a caller bounding on it inherits no requirement to pass on. Writing +That asymmetry is the whole mechanism. Callers name `DescribeArea`, which says nothing about `BaseArea` +or `Display`, so a caller bounding on it does not inherit a requirement to pass on. Writing `#[uses(BaseArea, Display)]` is therefore exactly equivalent to writing `where Self: BaseArea + Display` on the function, and the two desugar identically. @@ -190,9 +190,9 @@ to write. ## Common Mistakes -**Naming a provider trait instead of a consumer trait does not work**, and it is the most likely way to -reach for `#[uses]` when you actually wanted [`#[use_provider]`](use_provider.md). A provider trait -carries an explicit context parameter, and `#[uses]` does not fill it in, so the bound is incomplete: +**Naming a provider trait instead of a consumer trait does not work**, and it is the most common way to +write `#[uses]` when you wanted [`#[use_provider]`](use_provider.md). A provider trait carries an +explicit context parameter, and `#[uses]` does not fill it in, so the bound is incomplete: ```text error[E0107]: missing generics for trait `AreaCalculator` @@ -205,8 +205,8 @@ note: trait defined here, with 1 generic parameter: `__Context__` The `__Context__` in that note points to the mistake. Depend on the **consumer** trait, as in `#[uses(CanCalculateArea)]`, when you want "whatever this context has wired", which is almost always the -case. Use [`#[use_provider]`](use_provider.md) when you genuinely mean a named implementation, and it -will supply the missing argument. +case. Use [`#[use_provider]`](use_provider.md) when you mean a named implementation, and it will supply +the missing argument. ## Related constructs From b11b294366880d504bc37b5926fd67fda22f5586 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 6 Sep 2026 22:45:03 +0200 Subject: [PATCH 065/516] Fix content gaps on the attributes reference pages Complete the host lists on the #[extend] and #[use_type] pages: both attributes are also accepted on #[cgp_type], #[cgp_getter], and #[cgp_auto_getter], which run #[cgp_component]'s attribute collector. The equality-pin rejection is stated for those macros too. Restore the ShowWithDisplay provider that the #[default_impl] example wires but never defined, explain why it is wired directly rather than registered, and drop the emitted-impl block that Usage duplicated from Under the hood. Add the triggering snippet to every quoted diagnostic that lacked one, across the implicit, uses, use_type, extend, extend_where, impl_generics, and prefix pages. Co-Authored-By: Claude Fable 5.1 --- docs/reference/attributes/default_impl.md | 25 ++++++++------- docs/reference/attributes/extend.md | 16 ++++++++-- docs/reference/attributes/extend_where.md | 19 ++++++++++- docs/reference/attributes/impl_generics.md | 18 +++++++++++ docs/reference/attributes/implicit.md | 27 +++++++++++++--- docs/reference/attributes/prefix.md | 37 +++++++++++++++++++++- docs/reference/attributes/use_type.md | 28 +++++++++++++--- docs/reference/attributes/uses.md | 8 +++++ 8 files changed, 155 insertions(+), 23 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index 2ca51272..af832f14 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -37,16 +37,10 @@ parts, joined by the keyword `in`: ``` **`Key` becomes the emitted impl's `Self`**, and `NamespacePath` names the lookup trait plus whatever -leading arguments you write inside it. The macro appends the table parameter for you. So the example above -emits: - -```rust -impl DefaultImpls1 for String { - type Delegate = ShowString; -} -``` - -Remember that rule, because the trait's own parameter names suggest the opposite arrangement (see +leading arguments you write inside it. The macro appends the table parameter for you. So the example +above registers `ShowString` as the `DefaultImpls1` entry for the key `String`, and +[Under the hood](#under-the-hood) shows the impl it emits. Remember that rule, because the trait's own +parameter names suggest the opposite arrangement (see [`DefaultImpls1`](../traits/namespace/default_impls1.md#the-one-thing-to-get-right)). **The key is a type or a `@`-path.** A type key, as above, is the usual form for a per-type default: @@ -109,6 +103,13 @@ impl ShowImpl { value.clone() } } + +#[cgp_impl(new ShowWithDisplay)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + format!("{value}") + } +} ``` Then the context: @@ -131,7 +132,9 @@ delegate_components! { **Environmental context, parameter-targeted**: `App` carries the wiring and the shown value is a parameter. The loop wires every type with a registered default, and the direct `u64` line shadows -whatever the namespace would otherwise supply for that one type. +whatever the namespace would otherwise supply for that one type. `ShowWithDisplay` is wired directly +rather than registered, because its impl is generic over `T`, and a generic impl cannot register a +default (see [Common Mistakes](#common-mistakes)). A path key does not need a loop. With `CanGreet` registered under `@app` and `GreetHello` bound at `@app.GreeterComponent` as in [Usage](#usage), a context resolves the component by joining the diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index e4d2444d..7da668b8 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -46,8 +46,10 @@ Each entry names a trait, optionally with type arguments. You may list several i them across attributes, and they accumulate. Prefer one attribute carrying the whole list, as with [`#[uses]`](uses.md). -The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on -[`#[cgp_component]`](../macros/cgp_component.md). The macro does **not** accept it on +The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md), on +[`#[cgp_component]`](../macros/cgp_component.md), and on the macros built on it: +[`#[cgp_type]`](../macros/cgp_type.md), [`#[cgp_getter]`](../macros/cgp_getter.md), and +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md). The macro does **not** accept it on [`#[cgp_impl]`](../macros/cgp_impl.md), because a provider does not define a trait that a supertrait could attach to. The supertraits belong to the component's trait, and a provider states its private needs with [`#[uses]`](uses.md) instead. @@ -207,6 +209,16 @@ differ in where the bounds land, not in the grammar. **On a `#[cgp_impl]` the compiler does not recognize the attribute**, rather than accepting and ignoring it. The macro does not consume it, so it reaches the compiler as an unknown attribute: +```rust +#[cgp_impl(new GreetHello)] +#[extend(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} +``` + ```text error: cannot find attribute `extend` in this scope ``` diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 749e5bc7..60b5701a 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -188,7 +188,16 @@ repeated. **A promoted predicate does not reach callers as a guarantee.** This is the mistake the attribute most invites: because `#[extend]` gives callers its supertrait, it is natural to assume `#[extend_where]` gives them its predicate. It does not. Naming a trait whose `where` clause is unproven is an error against the -bound, so a caller generic over the parameter must state the predicate too: +bound, so a caller generic over the parameter must state the predicate too. This caller omits it: + +```rust +pub fn scale_it(ctx: &Ctx) -> Scalar +where + Ctx: Scale, +{ + ctx.scale() +} +``` ```text error[E0277]: the trait bound `Scalar: Clone` is not satisfied @@ -206,6 +215,14 @@ workaround. accepting and ignoring it. The macro does not consume it, so it reaches the compiler as an unknown attribute: +```rust +#[cgp_component(Scaler)] +#[extend_where(Scalar: Clone)] +pub trait CanScale { + fn scale(&self) -> Scalar; +} +``` + ```text error: cannot find attribute `extend_where` in this scope ``` diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 0a5413ff..579163bf 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -205,6 +205,14 @@ parses, and the compiler then rejects it. See [Common Mistakes](#common-mistakes mention it and neither does the self type, so only a field bound can determine it. Declaring `Name` without reading a field whose type mentions `Name` fails at the implementation: +```rust +#[cgp_fn] +#[impl_generics(Name: Display)] +pub fn greet(&self) -> String { + "Hello!".to_owned() +} +``` + ```text error[E0207]: the type parameter `Name` is not constrained by the impl trait, self type, or predicates ``` @@ -266,6 +274,16 @@ Rename the parameter, or give the trait another name with `#[cgp_fn(CanCount)]`. accepting and ignoring it. The macro does not consume it, so it reaches the compiler as an attribute that does not exist: +```rust +#[cgp_impl(new GreetHello)] +#[impl_generics(Name: Display)] +impl Greeter { + fn greet(&self, #[implicit] name: &Name) -> String { + format!("Hello, {name}!") + } +} +``` + ```text error: cannot find attribute `impl_generics` in this scope ``` diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index d23c99c7..48934711 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -237,12 +237,22 @@ add one `HasField` bound rather than two. The m **The attribute takes no arguments**, and the macro says so rather than ignoring the argument: +```rust +fn area(&self, #[implicit(width)] width: f64) -> f64 { width } +``` + ```text error: `#[implicit]` does not take any arguments; write it as a bare `#[implicit]` ``` -**The argument must be a plain identifier.** A destructuring pattern reports `Expected an identifier`, -and the macro rejects a `mut` binding with the fix in the message: +**The argument must be a plain identifier.** The destructuring pattern on the first line below reports +`Expected an identifier`, and the macro rejects the `mut` binding on the second line with the fix in the +message: + +```rust +fn area(&self, #[implicit] (width, height): (f64, f64)) -> f64 { width * height } +fn area(&self, #[implicit] mut width: f64) -> f64 { width += 1.0; width } +``` ```text error: Mutable variables are not allowed in implicit arguments. (Explicitly clone a `&` reference if you @@ -252,12 +262,21 @@ error: Mutable variables are not allowed in implicit arguments. (Explicitly clon **A function with implicit arguments must take `self` first**, because there is otherwise no context to read from: +```rust +fn area(#[implicit] width: f64, #[implicit] height: f64) -> f64 { width * height } +``` + ```text error: The first argument of a function with implicit arguments must be `self` ``` -**A mutable argument needs a `&mut self` receiver, and must be the only implicit argument.** The two -mistakes report separately: +**A mutable argument needs a `&mut self` receiver, and must be the only implicit argument.** The `&self` +receiver on the first function below and the extra implicit argument on the second report separately: + +```rust +fn bump(&self, #[implicit] counter: &mut u64) { *counter += 1; } +fn bump(&mut self, #[implicit] counter: &mut u64, #[implicit] step: u64) { *counter += step; } +``` ```text error: &mut self is required for mutable field reference `& mut u64` diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index e8116dd8..513cdb98 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -287,7 +287,23 @@ name different paths. Write the prefix alone. **Registering routes a component but does not bind a provider.** A prefixed component compiles even when nothing binds its path, and so does a context that joins the namespace. Only a [`check_components!`](../macros/check_components.md) reports it, as an unsatisfied bound on the -*path* rather than on a provider: +*path* rather than on a provider. With the `CanGreet` component from [Examples](#examples) and a +context that joins the namespace without binding the path: + +```rust +delegate_components! { + App { + namespace DefaultNamespace; + // nothing binds @app.GreeterComponent + } +} + +check_components! { + App { + GreeterComponent, + } +} +``` ```text error[E0277]: the trait bound `PathCons>, PathCons>: DefaultNamespace` is not satisfied @@ -310,6 +326,15 @@ fix is to bind a provider at the path: a direct entry on the context, a namespac **Two attributes naming the same namespace conflict.** Each emits an impl of that namespace's trait for the same marker, and the compiler rejects the second: +```rust +#[cgp_component(Greeter)] +#[prefix(@app in AppNamespace)] +#[prefix(@greeting in AppNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} +``` + ```text error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` ``` @@ -334,6 +359,16 @@ must live in a namespace is a [`#[cgp_getter]`](../macros/cgp_getter.md) compone **On `#[cgp_impl]` or `#[cgp_fn]` the compiler does not recognize the attribute.** Neither macro consumes it, so it reaches the compiler as an attribute that does not exist: +```rust +#[cgp_impl(new GreetHello)] +#[prefix(@app in DefaultNamespace)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} +``` + ```text error: cannot find attribute `prefix` in this scope ``` diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 30763cbc..261bf81f 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -47,7 +47,9 @@ not `::`**, and that is deliberate. It leaves `::` free for the trait's own path By default the macro projects the type from `Self`, so `Scalar` expands to `::Scalar`. The attribute is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md), -[`#[cgp_impl]`](../macros/cgp_impl.md), and [`#[cgp_component]`](../macros/cgp_component.md). +[`#[cgp_impl]`](../macros/cgp_impl.md), [`#[cgp_component]`](../macros/cgp_component.md), and the +macros built on `#[cgp_component]`: [`#[cgp_type]`](../macros/cgp_type.md), +[`#[cgp_getter]`](../macros/cgp_getter.md), and [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md). ### Importing several types @@ -88,7 +90,8 @@ together: ``` The pin is an implementation-side constraint, so the macro **rejects it on -[`#[cgp_component]`](../macros/cgp_component.md)**, whose trait definition has nowhere to put it. +[`#[cgp_component]`](../macros/cgp_component.md)** and on the macros built on it, whose trait +definitions have nowhere to put it. ### Importing from another type @@ -305,13 +308,17 @@ arguments. Their `::` segments belong to the path, while the `.` after the trait associated-type list. An omitted `in ContextPath` defaults the target to `Self`. In each `UseTypeIdent` the leading `IDENTIFIER` is the associated type's own name, `as` gives it a local alias to write in signatures, and `= Type` pins it with an equality bound. The pin is accepted on `#[cgp_fn]` and -`#[cgp_impl]` and rejected on `#[cgp_component]`. +`#[cgp_impl]` and rejected on `#[cgp_component]` and the macros built on it. ## Common Mistakes **Two imports may not share a name or alias.** The substitution could only pick one, so the macro rejects a collision rather than resolving it: +```rust +#[use_type(HasFooType.Foo, HasBarType.Bar as Foo)] +``` + ```text error: Multiple abstract types cannot share the same identifier or alias ``` @@ -319,6 +326,10 @@ error: Multiple abstract types cannot share the same identifier or alias **Imports may not resolve through one another in a cycle.** An `in` clause or a trait argument may name another import only if the resulting chain is acyclic, and the message names the loop: +```rust +#[use_type(HasAType.A in B, HasBType.B in A)] +``` + ```text error: cannot ground `#[use_type]` imports: they resolve through one another in a cycle `B` -> `A` -> `B`. An `in Context` clause or a trait argument may name another import's alias only if the resulting chain is @@ -331,6 +342,14 @@ same way. **An equality pin is rejected on a component trait**, because a trait definition cannot carry an implementation-side constraint: +```rust +#[cgp_component(Loader)] +#[use_type(HasErrorType.{Error = anyhow::Error})] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} +``` + ```text error: Type equality constraints cannot be used in component trait definition ``` @@ -352,7 +371,8 @@ Write `Self::Output`, and do not list it in a `#[use_type]` attribute. - [`#[extend]`](extend.md) — adds a supertrait without rewriting any type names. - [`#[implicit]`](implicit.md) — imports a value from a field. - [`#[cgp_fn]`](../macros/cgp_fn.md), [`#[cgp_impl]`](../macros/cgp_impl.md), and - [`#[cgp_component]`](../macros/cgp_component.md) — the three hosts. + [`#[cgp_component]`](../macros/cgp_component.md) — the hosts, together with the macros built on + `#[cgp_component]`. The ideas behind it: diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 5d4293e7..c8ffda4a 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -194,6 +194,14 @@ to write. write `#[uses]` when you wanted [`#[use_provider]`](use_provider.md). A provider trait carries an explicit context parameter, and `#[uses]` does not fill it in, so the bound is incomplete: +```rust +#[cgp_fn] +#[uses(AreaCalculator)] +pub fn scaled_area(&self, #[implicit] scale_factor: f64) -> f64 { + self.area() * scale_factor * scale_factor +} +``` + ```text error[E0107]: missing generics for trait `AreaCalculator` | From ae2391ac9d78ad609c04941d5e89c9085edeec52 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Thu, 10 Sep 2026 21:11:20 +0000 Subject: [PATCH 066/516] Use new truncate syntax --- blog/2024-12-19-early-preview-announcement.md | 4 ++-- blog/2025-01-09-v0.3.0-release.md | 2 +- blog/2025-05-09-v0.4.0-release.md | 2 +- blog/2025-06-14-hypershell-release/index.md | 2 +- blog/2025-06-14-v0.4.1-release.md | 2 +- blog/2025-07-07-extensible-datatypes-part-1.md | 2 +- blog/2025-07-09-extensible-datatypes-part-2.md | 2 +- blog/2025-07-12-extensible-datatypes-part-3.md | 2 +- blog/2025-07-30-extensible-datatypes-part-4.md | 2 +- blog/2025-10-12-v0.5.0-release.md | 2 +- blog/2025-10-26-v0.6.0-release.md | 2 +- blog/2025-11-03-cgp-serde-release.md | 2 +- blog/2026-02-01-v0.6.1-release.md | 2 +- blog/2026-02-21-new-website.md | 4 ++-- blog/2026-02-28-v0.7.0-release.md | 4 ++-- blog/2026-03-07-rustlab-2025-coherence/index.md | 2 +- blog/2026-05-10-v0.8.0-release.md | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/blog/2024-12-19-early-preview-announcement.md b/blog/2024-12-19-early-preview-announcement.md index 11fe46d8..c70efcec 100644 --- a/blog/2024-12-19-early-preview-announcement.md +++ b/blog/2024-12-19-early-preview-announcement.md @@ -8,7 +8,7 @@ tags: [release] Welcome everyone! This blog post marks the launch of the _context-generic programming_ (CGP) project, to introduce a new modular programming paradigm for Rust. -{/* truncate */} + ## A Quick Overview of Context-Generic Programming @@ -252,4 +252,4 @@ Following are some links to the discussions on this blog post: - [Reddit](https://www.reddit.com/r/rust/comments/1hkzaiu/announcing_contextgeneric_programming_a_new/) - [Lobsters](https://lobste.rs/s/a5wfid/context_generic_programming) -- [Hacker News](https://news.ycombinator.com/item?id=42498176) \ No newline at end of file +- [Hacker News](https://news.ycombinator.com/item?id=42498176) diff --git a/blog/2025-01-09-v0.3.0-release.md b/blog/2025-01-09-v0.3.0-release.md index aa407438..a2810a74 100644 --- a/blog/2025-01-09-v0.3.0-release.md +++ b/blog/2025-01-09-v0.3.0-release.md @@ -7,7 +7,7 @@ tags: [release] I'm excited to announce the release of [v0.3.0](https://github.com/contextgeneric/cgp/releases/tag/v0.3.0) of the [`cgp`](https://docs.rs/cgp/0.3.0/cgp/) crate, along with several [new](https://patterns.contextgeneric.dev/error-handling.html) [chapters](https://patterns.contextgeneric.dev/field-accessors.html) of the [CGP Patterns](https://patterns.contextgeneric.dev/) book! This post highlights some of the key features and updates included in this release. -{/* truncate */} + ## New Book Chapters diff --git a/blog/2025-05-09-v0.4.0-release.md b/blog/2025-05-09-v0.4.0-release.md index 8936fa4e..08c6b05d 100644 --- a/blog/2025-05-09-v0.4.0-release.md +++ b/blog/2025-05-09-v0.4.0-release.md @@ -9,7 +9,7 @@ It's been a while since the last update, but the wait is over! I'm thrilled to a This post highlights the major updates developed over the past few months. -{/* truncate */} + ## Game-Changing Improvement: Debugging is Finally Easy! diff --git a/blog/2025-06-14-hypershell-release/index.md b/blog/2025-06-14-hypershell-release/index.md index 0782bf45..be043fc7 100644 --- a/blog/2025-06-14-hypershell-release/index.md +++ b/blog/2025-06-14-hypershell-release/index.md @@ -7,7 +7,7 @@ tags: [release, deepdive] I am thrilled to introduce [**Hypershell**](https://github.com/contextgeneric/hypershell), a modular, *type-level* domain-specific language (DSL) for writing shell-script-like programs in Rust. Hypershell is powered by [**context-generic programming**](/) (CGP), which makes it possible for users to *extend* or *modify* both the language syntax and semantics. -{/* truncate */} + ## Discussion diff --git a/blog/2025-06-14-v0.4.1-release.md b/blog/2025-06-14-v0.4.1-release.md index 9440e68b..73283b88 100644 --- a/blog/2025-06-14-v0.4.1-release.md +++ b/blog/2025-06-14-v0.4.1-release.md @@ -14,7 +14,7 @@ Here are some of the highlights: - **`#[cgp_component]` macro improvement**: Now supports automated derivation of `UseDelegate`. - **Improved Documentation**: Added inline Rust documentation for common CGP constructs. -{/* truncate */} + Below we will go through some of the most significant changes in this release. diff --git a/blog/2025-07-07-extensible-datatypes-part-1.md b/blog/2025-07-07-extensible-datatypes-part-1.md index 13ff960f..0d429bc1 100644 --- a/blog/2025-07-07-extensible-datatypes-part-1.md +++ b/blog/2025-07-07-extensible-datatypes-part-1.md @@ -9,7 +9,7 @@ I’m excited to announce the release of [**CGP v0.4.2**](https://github.com/con Extensible records and variants allow developers to write code that operates on *any struct containing specific fields* or *any enum containing specific variants*, without needing their concrete definition. This makes it possible to write truly generic and flexible logic that is decoupled from rigid type definitions. -{/* truncate */} + In earlier versions, CGP already offered a foundational feature through the `HasField` trait, which made it possible to *read* a field from any struct that included it. With version 0.4.2, this functionality is dramatically extended. Not only can you now read fields, but you can also *construct* values onto these fields in a type-safe manner. More importantly, the same level of extensibility is now available for enums, enabling operations over variants in a similarly generic fashion. diff --git a/blog/2025-07-09-extensible-datatypes-part-2.md b/blog/2025-07-09-extensible-datatypes-part-2.md index 95176ee5..3d5e5398 100644 --- a/blog/2025-07-09-extensible-datatypes-part-2.md +++ b/blog/2025-07-09-extensible-datatypes-part-2.md @@ -9,7 +9,7 @@ This is the **second** part of the blog series on **Programming Extensible Data In this second part of the series, we will explore the use of **extensible variants**, by examining how it can be used in an **extensible visitor pattern** to build a modular interpreter for a toy math expression language. -{/* truncate */} + ## Recap diff --git a/blog/2025-07-12-extensible-datatypes-part-3.md b/blog/2025-07-12-extensible-datatypes-part-3.md index cea09390..1ddacbb0 100644 --- a/blog/2025-07-12-extensible-datatypes-part-3.md +++ b/blog/2025-07-12-extensible-datatypes-part-3.md @@ -13,7 +13,7 @@ The next 2 parts of the series are aimed at readers who want to go deeper — th We will first explore the implementation of extensible records in this part, followed by the implementation of extensible variants in the coming Part 4. -{/* truncate */} + ## Recap diff --git a/blog/2025-07-30-extensible-datatypes-part-4.md b/blog/2025-07-30-extensible-datatypes-part-4.md index fa37bb22..20037e43 100644 --- a/blog/2025-07-30-extensible-datatypes-part-4.md +++ b/blog/2025-07-30-extensible-datatypes-part-4.md @@ -11,7 +11,7 @@ In the third part of the series, [**Implementing Extensible Records**](/blog/ext In this final fourth part of the series, we will have the same walk through for the internal implementation details for **extensible variants**. -{/* truncate */} + ## Recap diff --git a/blog/2025-10-12-v0.5.0-release.md b/blog/2025-10-12-v0.5.0-release.md index eb21f116..493dfcc4 100644 --- a/blog/2025-10-12-v0.5.0-release.md +++ b/blog/2025-10-12-v0.5.0-release.md @@ -9,7 +9,7 @@ tags: [release] The highlights of this major release are summarized below. Also check out the [changelog](https://github.com/contextgeneric/cgp/releases/tag/v0.5.0) for the full list of changes. -{/* truncate */} + ## New Features diff --git a/blog/2025-10-26-v0.6.0-release.md b/blog/2025-10-26-v0.6.0-release.md index 4c9a9a9d..3ab98059 100644 --- a/blog/2025-10-26-v0.6.0-release.md +++ b/blog/2025-10-26-v0.6.0-release.md @@ -7,7 +7,7 @@ tags: [release] It has only been two weeks since [v0.5.0 was released](/blog/v0-5-0-release/), yet we are already introducing another major update. [**CGP v0.6.0**](https://github.com/contextgeneric/cgp/releases/tag/v0.6.0) brings significant improvements to the ergonomics of implementing providers and contexts, making it easier and more intuitive for developers to build on top of CGP. -{/* truncate */} + ## Simplified provider implementation with `#[cgp_impl]` diff --git a/blog/2025-11-03-cgp-serde-release.md b/blog/2025-11-03-cgp-serde-release.md index 04422682..73773987 100644 --- a/blog/2025-11-03-cgp-serde-release.md +++ b/blog/2025-11-03-cgp-serde-release.md @@ -11,7 +11,7 @@ In short, `cgp-serde` extends Serde’s original [`Serialize`](https://docs.rs/s Furthermore, `cgp-serde` allows us to leverage the powerful [**context and capabilities**](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/) concepts in stable Rust today. This unlocks the ability to write context-dependent implementations of `Deserialize`, such as one that uses an arena allocator to deserialize a `'a T` value, a concept detailed in the proposal article. -{/* truncate */} + ## Preface diff --git a/blog/2026-02-01-v0.6.1-release.md b/blog/2026-02-01-v0.6.1-release.md index 451b2914..ef053876 100644 --- a/blog/2026-02-01-v0.6.1-release.md +++ b/blog/2026-02-01-v0.6.1-release.md @@ -10,7 +10,7 @@ We're excited to announce the release of [`cgp` v0.6.1](https://crates.io/crates The changes in this release reflect our commitment to lowering the barrier to entry for CGP, while maintaining the power and flexibility that make it such a compelling approach to modular Rust code. Whether you're an experienced CGP user or just getting started, we believe you'll find these improvements meaningful. -{/* truncate */} + ## AI Disclaimer diff --git a/blog/2026-02-21-new-website.md b/blog/2026-02-21-new-website.md index fb0f4569..bd0dc9a6 100644 --- a/blog/2026-02-21-new-website.md +++ b/blog/2026-02-21-new-website.md @@ -7,7 +7,7 @@ tags: [release] If you have visited our website before, you might have noticed that the CGP project website has received a beautiful overhaul redesign with a fresh look and feel. This transformation comes from our migration away from [Zola](https://www.getzola.org/) to [Docusaurus](https://docusaurus.io/), a move driven by our commitment to significantly expand and improve the documentation for CGP. -{/* truncate */} + ## The journey to a better documentation home @@ -49,4 +49,4 @@ Beyond visual design, the text content throughout this website, including this b ## What comes next -With the website redesign now complete, we are excited about what lies ahead for the CGP project. CGP v0.7.0 will introduce support for using [**implicit parameters** in plain Rust function syntax](https://github.com/contextgeneric/cgp/issues/194), a feature that bridges the gap between plain Rust functions and fully context-generic code. Keep watching this website for the upcoming release announcement! \ No newline at end of file +With the website redesign now complete, we are excited about what lies ahead for the CGP project. CGP v0.7.0 will introduce support for using [**implicit parameters** in plain Rust function syntax](https://github.com/contextgeneric/cgp/issues/194), a feature that bridges the gap between plain Rust functions and fully context-generic code. Keep watching this website for the upcoming release announcement! diff --git a/blog/2026-02-28-v0.7.0-release.md b/blog/2026-02-28-v0.7.0-release.md index 75ba1fdc..33b7ba28 100644 --- a/blog/2026-02-28-v0.7.0-release.md +++ b/blog/2026-02-28-v0.7.0-release.md @@ -8,7 +8,7 @@ tags: [release] [**CGP v0.7.0**](https://crates.io/crates/cgp) has been released, bringing a major expansion to the CGP macro toolkit. The centerpiece of this release is a suite of new annotations — `#[cgp_fn]`, `#[implicit]`, `#[uses]`, `#[extend]`, `#[use_provider]`, and `#[use_type]` — that let you write context-generic code in plain function syntax with dramatically less boilerplate than before. -{/* truncate */} + ## Discussion @@ -622,4 +622,4 @@ The generated provider name is `ScalarTypeProvider` and the component name is `S CGP v0.7.0 represents the most significant ergonomics improvement to the library since its initial release. The combination of `#[cgp_fn]`, `#[implicit]`, `#[use_provider]`, and `#[use_type]` removes the most common sources of boilerplate in CGP code — getter traits, manual `where` clauses, and `Self::` prefixes — while keeping the generated code fully transparent and zero cost. -If you are new to CGP, the [**Area Calculation Tutorials**](/docs/tutorials/area-calculation/) are the best place to start. They build up the full picture from plain Rust functions all the way to composable, context-generic providers with pluggable static dispatch. \ No newline at end of file +If you are new to CGP, the [**Area Calculation Tutorials**](/docs/tutorials/area-calculation/) are the best place to start. They build up the full picture from plain Rust functions all the way to composable, context-generic providers with pluggable static dispatch. diff --git a/blog/2026-03-07-rustlab-2025-coherence/index.md b/blog/2026-03-07-rustlab-2025-coherence/index.md index d652ad07..c68dff80 100644 --- a/blog/2026-03-07-rustlab-2025-coherence/index.md +++ b/blog/2026-03-07-rustlab-2025-coherence/index.md @@ -15,7 +15,7 @@ This blog post contains the slides and transcript for my presentation of Context You can also read the [**PDF slides**](./cgp-rustlab-2025-slides.pdf) or watch the video recording of my presentation on [YouTube](https://www.youtube.com/watch?v=gXIfP-W9074). -{/* truncate */} + ## Discussion diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index e0815687..12d8b87c 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -8,7 +8,7 @@ tags: [release] **CGP v0.8.0** has been released, and it comes with major ergonomic improvements to manage CGP components at scale. In this blog post, we will explore the problems with managing CGP components, and how the new namespace feature in CGP v0.8.0 helps solve the problem. -{/* truncate */} + ## The challenges of scaling CGP From 8478916f73f896bec804e81f5fa6e9b7c240e958 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 12 Sep 2026 12:43:29 +0000 Subject: [PATCH 067/516] Revise derive docs with Astra --- docs/reference/derives/derive_build_field.md | 218 ++++++++-------- docs/reference/derives/derive_cgp_data.md | 167 ++++++------ docs/reference/derives/derive_cgp_record.md | 131 +++++----- docs/reference/derives/derive_cgp_variant.md | 138 +++++----- .../reference/derives/derive_extract_field.md | 243 ++++++++---------- docs/reference/derives/derive_from_variant.md | 138 +++++----- docs/reference/derives/derive_has_field.md | 158 ++++++------ docs/reference/derives/derive_has_fields.md | 193 +++++++------- docs/reference/derives/index.md | 67 +++-- 9 files changed, 686 insertions(+), 767 deletions(-) diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 0d9f191d..93e528fe 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -5,19 +5,18 @@ sidebar_position: 6 # `#[derive(BuildField)]` -Builder support for a record. +`#[derive(BuildField)]` generates a struct builder that tracks field presence in its type. ## Overview -A struct literal has to be written in one place that names the concrete type and supplies every field at -once. That is usually what you want. It is exactly wrong when the fields come from several independent -places, none of which should know the whole type. A hand-written constructor that grows a parameter per -subsystem becomes the one file every change has to edit. +A struct literal requires one place to name the concrete type and supply every field. When independent +parts of a program contribute fields, a shared constructor can force each contribution to depend on +the whole struct. -`#[derive(BuildField)]` replaces it with a builder whose completeness is tracked **in the type**. The -derive generates a companion struct that starts out with every field absent, and each step fills one -field in and returns a value of a *different* type: one where that field is now present. Only the -all-present type can be turned back into the real struct: +`#[derive(BuildField)]` lets generic code assemble fields independently while the compiler checks +completeness. It generates a companion struct whose type records which fields are present. Each step +sets a field and returns a new type reflecting that state. The builder can produce the original +struct only once every field is present: ```rust let person = Person::builder() // nothing set yet @@ -26,17 +25,17 @@ let person = Person::builder() // nothing se .finalize_build(); // every field set: closes ``` -Delete either middle line and this does not compile. There is no runtime check, no `Option` per field, -and no panic path: `finalize_build` simply does not exist for a value with a field still missing. A -conventional builder catches a missing field at run time; this catches it while you are typing. +Finalizing an incomplete builder fails to compile. Removing either `build_field` call above leaves a +field absent, so `finalize_build` is unavailable for the resulting type. The presence check does not +require runtime `Option` values or a panic path. -The other half of the payoff is that steps are decoupled. Because each `build_field` names its field by a -type-level tag rather than by calling a method on the concrete type, generic code can fill in a field of a -struct it does not know, and two independent implementations can each contribute part of one value. +Field tags let independent implementations contribute to the same builder. Each `build_field` call +addresses a field by its type-level tag, so generic code can set that field without knowing the +concrete struct. ## Usage -The macro is a plain derive on a struct. It takes no arguments and has no helper attributes: +Apply `BuildField` to a struct without arguments or helper attributes: ```rust use cgp::prelude::*; @@ -54,9 +53,8 @@ tag holds. A tuple struct works the same way with positional tags: a field at po `build_field(PhantomData::>, value)`. Generic parameters, lifetimes, and a `where` clause are carried onto the companion type and every generated impl. -A fieldless struct is the degenerate case rather than an error. Its companion type takes no parameters at -all, so there is exactly one configuration of it and `builder()` is immediately finalizable. The presence -tracking has nothing to track. +A fieldless struct produces a builder that can be finalized immediately. Its companion does not need +field-state parameters because it has nothing to track. The derive parses a struct, so applying it to an enum fails at parse time. The enum counterparts are [`#[derive(ExtractField)]`](./derive_extract_field.md) for taking one apart and @@ -64,26 +62,23 @@ The derive parses a struct, so applying it to an enum fails at parse time. The e ### What it does *not* generate -This is the point of deriving it alone, so it is worth being explicit. `#[derive(BuildField)]` emits the -builder and nothing else: **no** `HasField` accessors on your struct and **no** whole-shape representation. -Those come from [`#[derive(HasField)]`](./derive_has_field.md) and -[`#[derive(HasFields)]`](./derive_has_fields.md), and the umbrella -[`#[derive(CgpData)]`](./derive_cgp_data.md) includes all three. +`BuildField` generates the builder without adding accessors or a structural representation to the +original struct. Derive [`HasField`](./derive_has_field.md) for per-field access and +[`HasFields`](./derive_has_fields.md) for the representation. [`CgpData`](./derive_cgp_data.md) +includes all of these outputs. -So a struct that derives only `BuildField` can be *built* generically and not *read* generically. That is -occasionally exactly right, for an output type a pipeline assembles and hands back, and it is why the -slice exists. +A struct deriving only `BuildField` supports generic construction without generic reads from the +finished value. This suits an output type that a pipeline assembles and returns. ### The three ways to fill a field -The builder is driven through methods that come from the library rather than from the derive, and there are -three of them. +The library provides methods to set a field, merge source fields, and remove a field. The derive +supplies the implementations these methods require. -**`build_field`** sets one absent field to a value, which is the step shown above. +**`build_field`** sets an absent field to a value, as shown above. -**`build_from`** copies every field the target and a source record share, in one step. It comes from -[`CanBuildFrom`](../traits/casting/can_build_from.md), and is imported from -`cgp::core::field::impls`: +**`build_from`** moves fields from a source record into the target builder. It comes from +[`CanBuildFrom`](../traits/casting/can_build_from.md), imported from `cgp::core::field::impls`: ```rust Employee::builder() @@ -92,25 +87,22 @@ Employee::builder() .finalize_build() ``` -**The source of a `build_from` needs [`#[derive(HasFields)]`](./derive_has_fields.md) as well**, and this -is the easiest thing on this page to get wrong. `build_from` walks the *source's* field list to know what -to copy, and that list comes from `HasFields`. A source deriving only `BuildField` has a builder of its -own and still cannot be merged into anything. The target needs only this derive. +The source of `build_from` must also derive [`HasFields`](./derive_has_fields.md). +`build_from` traverses the source's field list, which `BuildField` alone does not provide. The target +needs only `BuildField`. -**`take_field`** goes the other way: it removes a field that is already present, handing back the value -alongside a builder with that field absent again. It is the reverse of `build_field` and comes from -`TakeField`, which unlike the rest of the family is **not in the prelude**. Import it from -`cgp::core::field::traits` when calling it directly. Most code meets it indirectly, since `build_from` -uses it to pull each field out of the source. +**`take_field`** removes a present field and returns its value alongside a builder with that field +absent. It reverses `build_field` and comes from `TakeField`, which is not in the prelude. Import it +from `cgp::core::field::traits` for direct calls. `build_from` uses it internally to remove source +fields. -Two more methods sit at the ends of the process. `builder()` produces the empty builder, and -`into_builder()` goes the other way, turning a finished struct into an all-present builder so its fields -can be redistributed. +`builder()` creates an empty builder, while `into_builder()` turns a finished struct into an +all-present builder. Use `into_builder()` when generic code needs to redistribute existing fields. ## Examples -The clearest use is extending one record into a larger one. Both structs derive the builder, and the smaller -one's fields move across in a single step: +A builder can extend a source record with additional fields. Both types below derive `BuildField`, +and the source also derives `HasFields` so `build_from` can traverse its fields: ```rust use cgp::core::field::impls::CanBuildFrom; @@ -138,11 +130,10 @@ fn extend(foo_bar: FooBar) -> FooBarBaz { } ``` -`FooBarBaz` does not mention `FooBar` and `FooBar` does not mention `FooBarBaz`. They share two field names, -matched at the type level, which is the whole coupling between them. +The conversion relates `FooBar` and `FooBarBaz` through their field names and types. Neither struct +names the other in its definition. -A field that has been set can be read back out mid-build, because the companion type gains a `HasField` impl -per field that is in scope only once that field is present: +The companion's `HasField` implementation allows a field to be read once it has been set: ```rust let partial = Person::builder() @@ -151,10 +142,10 @@ let partial = Person::builder() assert_eq!(partial.get_field(PhantomData::), "Alice"); ``` -Asking for `last_name` there would not compile, since that field's accessor is not in scope until it is set. +Reading `last_name` at this point fails to compile because its field is still absent. -And a finished value can be taken apart and put back together, the operation generic code performs when it -redistributes fields: +`into_builder()` and `take_field()` let generic code remove fields from a finished value and rebuild +it: ```rust use cgp::core::field::traits::TakeField; @@ -171,37 +162,31 @@ let person = remainder ## When to use it -**Derive `BuildField` when a struct is assembled by code that does not know the whole struct.** That is the -case it exists for, and it is a narrower case than "this struct has several fields". - -- **Reach for it when independent parts of a program each contribute fields.** This is the extensible - builder pattern: one implementation per subsystem, each producing a small struct, merged into a target - whose fields the compiler checks are all supplied. -- **Reach for it when the type being built is itself generic.** Code that builds "whatever record these - contributions add up to" needs a builder addressed by tags rather than by method names. -- **Do not reach for it for a struct you construct with a literal.** A struct literal is already checked for - completeness, reads better, and generates nothing. This derive buys the *decoupling*, and if there is - nothing to decouple it is pure cost. -- **Do not reach for it in place of a conventional builder** with defaults and validation. It tracks presence - and nothing else: it has no notion of a default value, no way to run a check at finalize time, and no - optional field unless you make the field's own type optional. The - [optional-field extensions](../traits/optional/has_optional_builder.md) cover the defaulted and optional cases, - and a hand-written builder remains the better fit when the logic is the point. - -Between this derive and its neighbours the choice is about how much of the machinery you want. - -- **[`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpRecord)]`](./derive_cgp_record.md)** if the - struct also needs per-field reads or a whole-shape representation, which is the common case. Those include - this output. -- **`#[derive(BuildField)]` alone** when the struct is only ever built generically and never read - generically. +Use `BuildField` when independent code must assemble a struct without knowing its concrete type. +Choose it for the generic field interface, rather than for the number of fields: + +- **Independent field contributions:** merge outputs from separate implementations and let the + compiler check that the target is complete. +- **A generic target type:** address fields by tags when the builder cannot name the concrete struct. +- **Ordinary construction:** prefer a struct literal when one place already knows the type and fields. + Rust checks its completeness without a generated companion. +- **Defaults or validation:** use the [optional-field extensions](../traits/optional/has_optional_builder.md) + for defaulted and optional fields, or a hand-written builder for custom validation. This derive + tracks presence and does not supply defaults or validation at finalization. An `Option` field + still needs to be set in the plain builder, even when its value is `None`. + +Choose the derive according to the operations the struct needs: + +- **[`CgpData`](./derive_cgp_data.md) or [`CgpRecord`](./derive_cgp_record.md)**: include per-field + access and a structural representation alongside the builder. +- **`BuildField` alone**: provide generic construction when the finished value does not need generic + field access or a structural representation. ## Under the hood -The derive centres on a companion struct named `__Partial{Name}`. It is your struct with one -[`MapType`](../traits/type-level/map_type.md) parameter added per field, and each field's type wrapped in that -parameter's projection. The marker decides how the field is stored: `IsPresent` maps `T` to `T`, `IsNothing` -maps it to `()`, and `IsVoid` maps it to the uninhabited `Void`. From: +The companion struct `__Partial{Name}` stores each field through a +[`MapType`](../traits/type-level/map_type.md) parameter. `IsPresent` maps `T` to `T`, `IsNothing` maps +it to `()`, and `IsVoid` maps it to the uninhabited `Void`. For this input: ```rust #[derive(BuildField)] @@ -211,7 +196,7 @@ pub struct Person { } ``` -it emits: +The generated companion wraps each field in its corresponding marker: ```rust pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { @@ -220,7 +205,8 @@ pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { } ``` -Around that struct come the entry and exit points, and the pair of them is the whole safety argument: +The builder implementations define the initial state, conversion from a finished value, target type, +and finalization. Only the all-present companion implements `FinalizeBuild`: ```rust impl HasBuilder for Person { @@ -246,8 +232,8 @@ impl FinalizeBuild for __PartialPerson { // only at all-p } ``` -Then, per field, an `UpdateField` impl: the primitive everything else is built from. It moves one field's -marker to a new state, returning the old value alongside the rebuilt companion: +Each field gets an `UpdateField` implementation that changes its marker and returns its old value +alongside the updated companion: ```rust impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> @@ -260,8 +246,8 @@ impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> } ``` -And, per field, a `HasField` impl on the companion that is in scope only when that field's marker is -`IsPresent`, which lets a set field be read back mid-build: +Each field also gets a `HasField` implementation on the companion, available when that field's marker +is `IsPresent`: ```rust impl<__F1__: MapType> HasField for __PartialPerson { @@ -270,9 +256,9 @@ impl<__F1__: MapType> HasField for __PartialPerson` covers `UpdateField`, the absent-to-present move. So `build_field` is `update_field` in that one direction. @@ -280,44 +266,44 @@ general form, parameterized by the marker to move *to*: `FinalizeBuild` is likewise a library trait; the derive supplies only the all-present impl of it. -Two properties of the companion follow from how it is built: the derive clones your struct and renames it. -It **keeps your visibility**, yours and each field's, so a `pub struct` yields a `pub struct __PartialPerson` -with `pub` fields. But it **carries none of your attributes**: those are cleared, so a -`#[derive(Debug, Clone)]` on the record does not reach the companion. That is not an oversight. A field's -type is the projection `<__F0__ as MapType>::Map`, so a derived `Debug` would need bounds the macro -has no way to state. But it does mean a half-built value cannot be printed. +The companion preserves the original struct's visibility and each field's visibility. The derive +creates it by cloning and renaming the struct, so a `pub` struct with `pub` fields produces a public +companion with public fields. + +The companion does not inherit the original attributes. A `#[derive(Debug, Clone)]` on the record +therefore does not make the builder printable or cloneable. Its fields use projections such as +`<__F0__ as MapType>::Map`, whose trait bounds depend on the marker. Each generated impl is aimed at the token it came from: a per-field impl at its field, a whole-struct impl at the struct name. ## Common Mistakes -**`finalize_build` missing is the expected error, not a bug.** A field left unset means the all-present impl -does not apply, and the compiler reports a missing method rather than a missing field. Read it as "some field -is still absent" and check the companion type in the error for which marker is `IsNothing`. +**An incomplete builder cannot call `finalize_build`.** The all-present implementation does not apply +while any field is unset. Check the companion type in the diagnostic for `IsNothing` to identify the +missing field. -**The companion cannot be printed or cloned.** Its attributes are cleared, so no `Debug`, no `Clone`, no -`PartialEq`, whatever the original struct derives. Read a set field through the companion's `HasField` impl -instead. +**The companion does not inherit `Debug`, `Clone`, or `PartialEq`.** The derive clears the original +attributes. Read a set field through the companion's `HasField` implementation when inspecting a +partial value. -**`build_from` needs `HasFields` on the source, not just `BuildField`.** Deriving only this macro on both -structs looks symmetric and does not work: `build_from` reads the source's field list, and only -[`#[derive(HasFields)]`](./derive_has_fields.md) provides one. The error names an unsatisfied `HasFields` -bound on the source type. +**`build_from` needs `HasFields` on its source in addition to `BuildField`.** Deriving only +`BuildField` on both structs leaves the source without the field list that the conversion traverses. +The error reports an unsatisfied [`HasFields`](./derive_has_fields.md) bound on the source. **`TakeField` is not in the prelude.** Import it from `cgp::core::field::traits` to call `take_field` directly. `CanBuildFrom`, which provides `build_from`, comes from `cgp::core::field::impls`. -**There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible default -still has to be set explicitly, unless you reach for -[`CanFinalizeWithDefault`](../traits/optional/can_finalize_with_default.md). +**The plain builder tracks presence without defaults or validation.** Set each field explicitly or +use [`CanFinalizeWithDefault`](../traits/optional/can_finalize_with_default.md) to fill unset fields +from their default values. **A tuple struct's steps are keyed by position.** Use `PhantomData::>`, not a `Symbol!` of the number. -**Field order does not matter, but field *names* are the whole interface.** `build_from` matches by name, so -renaming a field in one struct silently stops it being copied from the other. The result is a -`finalize_build` that no longer resolves, reported at the finalize rather than at the rename. +**`build_from` uses field names, regardless of declaration order.** Renaming a source field breaks +the correspondence with the target field. If the target field remains unset, `finalize_build` fails +to resolve, so the error appears at finalization rather than at the rename. **It does not accept an enum.** The enum counterparts are [`#[derive(ExtractField)]`](./derive_extract_field.md) and @@ -325,6 +311,8 @@ renaming a field in one struct silently stops it being copied from the other. Th ## Related constructs +These references cover the related derives, generated traits, and supporting types: + - [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this slice. - [`#[derive(HasField)]`](./derive_has_field.md) — per-field access on the original struct, which this derive does not generate. @@ -343,13 +331,15 @@ renaming a field in one struct silently stops it being copied from the other. Th - [Dispatch combinators](../providers/dispatch/index.md) — the providers that run several builder implementations and merge their outputs. -The ideas behind it: +The ideas behind it are explained on these concept pages: - [Extensible records](/docs/concepts/extensible-records) — partial records, and the extensible builder pattern this derive is the foundation of. ## Source +The implementation is defined in these source files: + - Entry point: [`derive_build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_build_field.rs) - Codegen: [`cgp_data/derive_builder/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_builder) - Traits: [`build_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/build_field.rs), diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 14469ae6..cb6915c7 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -5,29 +5,26 @@ sidebar_position: 3 # `#[derive(CgpData)]` -The umbrella extensible-data derive, for a struct or an enum. +`#[derive(CgpData)]` generates structural access and incremental operations for a struct or enum. ## Overview -A plain Rust struct or enum is opaque to generic code. There is no way to refer to "the `first_name` -field" or "the `Circle` variant" through a type parameter, so anything that must work across several -data types ends up written once per type. +Generic code needs traits to access a struct's fields or an enum's variants. A type parameter alone +does not let it name a `first_name` field or a `Circle` variant. -`#[derive(CgpData)]` is the one-line answer: it turns a struct or an enum into **extensible data**, a -type whose fields or variants generic code can name, read, construct, and take apart without ever -mentioning the concrete type. It is the umbrella derive, and what it generates depends entirely on what -it is applied to: on a struct it emits the record machinery, on an enum the variant machinery. +`#[derive(CgpData)]` supplies those traits by turning the type into **extensible data**. On a struct, +it generates field access, a structural representation, and a builder. On an enum, it generates a +structural representation, constructors, and an extractor. Generic code can then work with the type's +fields or variants without naming the concrete type. -The two things this buys are worth naming separately, because together they define what "extensible" -means here. The **representation** view describes the type as a list of named entries, which lets one -implementation serialize any record or dispatch over any enum. The **incremental** view adds a companion -type that tracks, in its own type parameters, which fields are present or which variants are still -possible. A half-built value and a finished one are therefore *different types*, and using one where the -other belongs is a compile error rather than a runtime panic. +The generated representation and companion types support different operations. The representation +lists the type's named entries so generic code can process its structure. A companion type tracks +which record fields are present or which enum variants remain possible. A partial value and a +finished one therefore have different types, so the compiler rejects an incomplete build or extraction. ## Usage -The derive takes no arguments and has no helper attributes, and it accepts either shape: +Apply `CgpData` to a struct or enum without arguments or helper attributes: ```rust use cgp::prelude::*; @@ -52,32 +49,28 @@ everything generated, including the companion types. ### What each shape emits, and where it is documented -The derive dispatches on the shape of its input and then runs one of two fixed sequences. The -shape-specific derives run those same two sequences, so each is documented on its own page rather than -twice here: +`CgpData` generates the same output as the matching shape-specific derive. These pages document each +output in detail: | Applied to | It emits | Documented on | |---|---|---| | a struct | per-field access, the representation, and the builder | [`#[derive(CgpRecord)]`](./derive_cgp_record.md) | | an enum | the representation, the constructors, and the extractor | [`#[derive(CgpVariant)]`](./derive_cgp_variant.md) | -Read the matching page for the shapes each accepts, the expansion in full, and the corner cases. The one -restriction worth knowing before you get there is on the enum side: **every variant must carry exactly -one unnamed payload**, and there is no per-variant opt-out. +Every enum variant must carry exactly one unnamed payload, and individual variants cannot opt out. +The matching page covers the accepted shapes, generated code, and corner cases. ### Choosing among the three -The three derives are interchangeable wherever the shape allows, so the choice is about what you want -the code to say. There is no output difference to weigh: `CgpData` on a struct emits exactly what -`CgpRecord` emits, and on an enum exactly what `CgpVariant` emits. +Choose `CgpData`, `CgpRecord`, or `CgpVariant` according to the input restriction you want to express. +Their output is identical for the same accepted input: -- **`#[derive(CgpData)]`** is the default. Use it unless you have a reason not to. -- **[`#[derive(CgpRecord)]`](./derive_cgp_record.md)** says "this is always a struct" and rejects - anything else at parse time. -- **[`#[derive(CgpVariant)]`](./derive_cgp_variant.md)** says "this is always an enum", likewise. +- **`#[derive(CgpData)]`**: use as the default for either structs or enums. +- **[`#[derive(CgpRecord)]`](./derive_cgp_record.md)**: accept only structs. +- **[`#[derive(CgpVariant)]`](./derive_cgp_variant.md)**: accept only enums. -Reach for a shape-specific one when the name earns its keep as documentation, or when you want the error -for a wrong shape to arrive at the derive rather than further in. +Use a shape-specific derive when its name documents a constraint on the type. It rejects the wrong +shape at the derive. ## Examples @@ -110,77 +103,71 @@ constructors, and an extractor. Worked examples of each half are on the ## When to use it -**Reach for one of these derives when generic code has to work over the type's own structure.** That is -the test, and it is narrower than it sounds. Most types in a CGP program want -[`#[derive(HasField)]`](./derive_has_field.md) and nothing more, because most of what implementations -need from a context (the type a capability runs against, which supplies values as its own fields) is to -read one value out of it. - -The cases that do earn it are specific. - -- **A record assembled from independent pieces.** When several parts of a program each contribute part - of a struct and no one place should know the whole type, that is the extensible builder pattern, and - this derive runs it. -- **An enum handled one variant at a time by independent code.** When variants and the operations over - them both need to grow without editing each other, this is the extensible visitor pattern. -- **A framework over any user type.** A serializer, a validator, or a mapper written once against the - shape rather than once per type. - -And the cases that do not: - -- **A closed enum with fixed operations.** A `match` is clearer than any machinery, and it already gives - exhaustiveness. -- **A struct whose fields are only ever read.** [`#[derive(HasField)]`](./derive_has_field.md) is the - whole answer, and it is one impl pair per field rather than a companion type and a dozen impls. -- **A one-off structural manipulation.** A lighter generic-programming library is a better fit than - adopting this family for a single conversion. - -When you want only part of the output, the family splits along the lines you would expect, and deriving -the slice is the cheaper choice: [`#[derive(HasField)]`](./derive_has_field.md) for the getters, -[`#[derive(HasFields)]`](./derive_has_fields.md) for the representation, -[`#[derive(BuildField)]`](./derive_build_field.md) for the record builder, -[`#[derive(ExtractField)]`](./derive_extract_field.md) for the extractor, and -[`#[derive(FromVariant)]`](./derive_from_variant.md) for the variant constructors. The umbrella is the -right call once you want most of them. - -One honest cost: this is the heaviest derive in CGP. It generates a companion type and, for an enum, two -of them, plus an impl per field or variant on top of the whole-type impls. That is compile-time work, -and the generated types appear by name in error messages. It buys guarantees a runtime builder cannot -give, and it is not free. +Use `CgpData` when generic code needs both a type's structure and its incremental operations. For +reading individual values from a context (the type a capability runs against, which supplies values +as fields), [`#[derive(HasField)]`](./derive_has_field.md) is sufficient. + +The full derive supports these uses: + +- **Records assembled from independent contributions:** the extensible builder pattern combines fields + without requiring each contributor to know the target struct. +- **Enums handled by independent implementations:** the extensible visitor pattern lets variants and + operations grow without requiring each implementation to know the whole enum. +- **Frameworks over user-defined types:** serializers, validators, and mappers can process the shape + generically. Use `HasFields` alone if the framework only needs representation and conversions. + +Prefer simpler operations in these cases: + +- **Closed enums with fixed operations:** use a `match`, which already checks exhaustiveness. +- **Structs whose fields are only read:** derive [`HasField`](./derive_has_field.md) for per-field access. +- **One-off structural manipulations:** consider a narrower generic-programming library when a single + conversion is the only reason to adopt this family. + +Individual derives let you generate only the operations you need: + +- [`HasField`](./derive_has_field.md): per-field access. +- [`HasFields`](./derive_has_fields.md): the representation and conversions. +- [`BuildField`](./derive_build_field.md): the record builder. +- [`ExtractField`](./derive_extract_field.md): the enum extractor. +- [`FromVariant`](./derive_from_variant.md): the variant constructors. + +`CgpData` adds compilation work and generated types that can appear in diagnostics. It generates one +companion type for a struct or two for an enum, plus whole-type and per-field or per-variant +implementations. Derive only the parts you need when the full set of operations is unnecessary. ## Under the hood -Nothing about the umbrella is special. `#[derive(CgpData)]` inspects the item, dispatches on whether it -is a struct or an enum, and then runs exactly the same code path the matching shape-specific derive -runs. [`#[derive(CgpRecord)]`](./derive_cgp_record.md#under-the-hood) enters the first directly, and -[`#[derive(CgpVariant)]`](./derive_cgp_variant.md#under-the-hood) the second. That shared dispatch is -why all three agree on their output, and why a claim about what `CgpData` emits is always a claim about -one of the other two. +`CgpData` selects the record or variant code path according to its input. +[`CgpRecord`](./derive_cgp_record.md#under-the-hood) and +[`CgpVariant`](./derive_cgp_variant.md#under-the-hood) call those paths directly, which is why their +output matches. Their pages show the generated implementations. -Applied to a union, all three fail: the family models products and sums, and a union is neither. +All three derives reject unions. The family models structs and enums. ## Common Mistakes -**Which mistakes apply depends on the shape**, and the shape pages carry them. The -[record ones](./derive_cgp_record.md#common-mistakes) cover the companion's cleared attributes, -position-keyed tuple builders, and the newtype special case; the -[variant ones](./derive_cgp_variant.md#common-mistakes) cover the one-payload rule and the seven reserved -variant names. Two are worth repeating here because they catch people who reached for the umbrella -without reading either. +The applicable restrictions depend on the input shape. The +[record page](./derive_cgp_record.md#common-mistakes) covers cleared companion attributes, positional +tuple builders, and the newtype representation. The +[variant page](./derive_cgp_variant.md#common-mistakes) covers payload shapes and reserved names. +The following restrictions apply when choosing the combined derive. -**Every enum variant needs exactly one unnamed payload.** A unit, multi-field, or struct-style variant -fails, with no per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in -the family that accepts all four shapes, so an enum with mixed variants gets that derive instead. +**Every enum variant needs exactly one unnamed payload.** Unit, multi-field, and struct-style variants +are rejected, and individual variants cannot opt out. [`HasFields`](./derive_has_fields.md) accepts +all of these shapes when only a representation and whole-value conversions are needed. -**Absence is spelled differently on the two sides.** `IsNothing` for a missing record field, `IsVoid` for -a ruled-out variant, and they are not interchangeable. An error mentioning the wrong one usually means -record and variant machinery have been crossed. +**Record and variant absence use different markers.** `IsNothing` represents a missing record field; +`IsVoid` represents a ruled-out variant. An error mentioning the wrong marker usually means record +and variant operations have been mixed. -**These are the heaviest derives in CGP.** One `#[derive(CgpData)]` on a five-field struct generates a -companion type and roughly twenty impls. If only part of the output is wanted, derive the slice. +**The combined derive generates more code than an individual derive.** A five-field struct gains a +companion type and per-field implementations in addition to its whole-type implementations. Use an +individual derive when only part of that output is needed. ## Related constructs +These references cover the related derives, generated traits, and supporting types: + - [`#[derive(CgpRecord)]`](./derive_cgp_record.md) and [`#[derive(CgpVariant)]`](./derive_cgp_variant.md) — the two faces this dispatches to. - [`#[derive(HasField)]`](./derive_has_field.md) — the per-field access slice, on its own. @@ -193,7 +180,7 @@ companion type and roughly twenty impls. If only part of the output is wanted, d trait families the shapes generate impls for. - [`MapType`](../traits/type-level/map_type.md) — the markers the companion types are parameterized by. -The ideas behind it: +The ideas behind it are explained on these concept pages: - [Extensible records](/docs/concepts/extensible-records) — the struct half, and the extensible builder pattern. @@ -204,6 +191,8 @@ The ideas behind it: ## Source +The implementation is defined in these source files: + - Entry point: [`cgp_data.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_data.rs) - Shape dispatch: [`cgp_data/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/item.rs) - Record and variant codegen: [`cgp_data/record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/record.rs) diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index c5c6d83a..e3eaa88a 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -5,27 +5,23 @@ sidebar_position: 4 # `#[derive(CgpRecord)]` -The extensible-data derive for a struct. +`#[derive(CgpRecord)]` generates field access, a structural representation, and a builder for a struct. ## Overview -A plain Rust struct is opaque to generic code. There is no way to refer to "the `first_name` field" -through a type parameter, so anything that must work across several structs ends up written once per -struct. +Generic code needs traits to read and assemble fields across different structs. A type parameter alone +does not let it refer to a field such as `first_name`. -`#[derive(CgpRecord)]` turns a struct into **extensible data**: a type whose fields generic code can -name, read, and assemble without ever mentioning the concrete type. It produces the whole record half -of the family in one line: per-field access, the whole-shape field list, and an incremental builder -that fills a value one field at a time. +`#[derive(CgpRecord)]` supplies those traits, making the struct an **extensible record**. It generates +per-field access, a representation of the whole struct, and a builder that fills fields individually. +Generic code can use these operations without naming the concrete struct. -It is the struct-only face of [`#[derive(CgpData)]`](./derive_cgp_data.md). The two run the same code -and emit the same output on a struct. The difference is that this one **rejects an enum at parse -time**, so a type that is meant to stay a struct says so and the error arrives at the derive rather -than further along. +`CgpRecord` accepts only structs. It produces the same output as +[`CgpData`](./derive_cgp_data.md) on a struct, but rejects an enum at parse time. ## Usage -The derive takes no arguments and has no helper attributes: +Apply `CgpRecord` to a struct without arguments or helper attributes: ```rust use cgp::prelude::*; @@ -37,18 +33,16 @@ pub struct Person { } ``` -**Every struct shape is accepted.** A named-field struct is keyed by -[`Symbol!`](../macros/symbol.md), a tuple struct by [`Index`](../types/index_type.md), and a fieldless -struct is the degenerate case rather than an error. Its companion type takes no parameters at all, so -`builder()` is immediately finalizable, because there is nothing to track. +Every struct shape is accepted. Named fields use [`Symbol!`](../macros/symbol.md) tags, and tuple +fields use [`Index`](../types/index_type.md) tags. A fieldless struct produces a companion without +field-state parameters, so its `builder()` can be finalized immediately. Generic parameters, lifetimes, and a `where` clause are carried onto everything generated, including the companion type. ### What it generates -Three groups, each of which is also available as a derive of its own when only part of the output is -wanted: +The derive combines these outputs, each also available separately: | Group | The slice on its own | |---|---| @@ -58,8 +52,8 @@ wanted: ## Examples -The record machinery is most useful for assembling one struct out of pieces. Because both structs -derive it, a builder can copy every shared field from another record in one step and fill in the rest: +A record builder can combine fields from another record with fields supplied individually. In this +example, `build_from` moves the shared fields from `Person` into an `Employee` builder: ```rust use cgp::core::field::impls::CanBuildFrom; @@ -86,36 +80,30 @@ fn promote(person: Person, id: u64) -> Employee { } ``` -Neither struct knows about the other. They share two field *names*, matched at the type level, so -[`build_from`](../traits/casting/can_build_from.md) moves those fields across and leaves `employee_id` for the -caller. Remove the `build_field` line and this stops compiling, because -[`finalize_build`](../traits/builder/finalize_build.md) only exists once every field is present. +`build_from` matches the fields by their type-level names, so neither struct needs to name the other. +It moves `first_name` and `last_name` and leaves `employee_id` for the caller. Removing `build_field` +makes the example fail to compile because +[`finalize_build`](../traits/builder/finalize_build.md) is available only after every field is present. +See [`build_from`](../traits/casting/can_build_from.md) for the conversion requirements. ## When to use it -**Reach for it when generic code has to work over the struct's own structure**, and prefer -[`#[derive(CgpData)]`](./derive_cgp_data.md) unless naming the shape earns its keep as documentation. -The two are interchangeable on a struct, so this is a choice about what the code says rather than -about what it emits. - -- **Use `#[derive(CgpRecord)]`** to state that a type is always a struct, and to have a later change - to an enum fail at the derive rather than inside the generated code. -- **Use [`#[derive(CgpData)]`](./derive_cgp_data.md)** as the default, especially in a module where - structs and enums both take the derive. -- **Use [`#[derive(HasField)]`](./derive_has_field.md) alone** when the fields are only ever read. That - is most types in a CGP program, and it is one impl pair per field rather than a companion type and a - dozen impls. -- **Derive the slice you want** when only part of the output is wanted: - [`HasFields`](./derive_has_fields.md) for the representation, - [`BuildField`](./derive_build_field.md) for the builder. The umbrella is the right call once you want - most of them. - -The full argument for when a type earns the extensible-data machinery at all is on the -[umbrella page](./derive_cgp_data.md#when-to-use-it). +Use `CgpRecord` when generic code needs the struct's field access, representation, and builder, and +the derive name should specify that the input is a struct. Choose among the related derives according +to the operations and input restriction you need: + +- **`CgpRecord`**: generate the full record output and reject non-struct inputs. +- **[`CgpData`](./derive_cgp_data.md)**: generate the same output while also accepting enums. +- **[`HasField`](./derive_has_field.md)**: generate per-field access when fields only need to be read. +- **[`HasFields`](./derive_has_fields.md)**: generate the representation and conversions. +- **[`BuildField`](./derive_build_field.md)**: generate the builder alone. + +The [CgpData page](./derive_cgp_data.md#when-to-use-it) explains when generic structural operations +justify the additional generated code. ## Under the hood -The derive emits three groups in order. From: +The derive generates field access, representation traits, and a builder for the input struct: ```rust #[derive(CgpRecord)] @@ -125,12 +113,12 @@ pub struct Person { } ``` -it first emits the **per-field access**: a [`HasField`](../traits/field-access/has_field.md) and a -[`HasFieldMut`](../traits/field-access/has_field_mut.md) impl per field, exactly what -[`#[derive(HasField)]`](./derive_has_field.md) produces on its own. +The field-access output contains a [`HasField`](../traits/field-access/has_field.md) and a +[`HasFieldMut`](../traits/field-access/has_field_mut.md) implementation per field. It matches the output +of [`#[derive(HasField)]`](./derive_has_field.md). -Then the **representation**, exposing the struct as a product of named entries with conversions in both -directions, which is [`#[derive(HasFields)]`](./derive_has_fields.md)'s output: +The representation output describes the struct as a product of named entries and supplies conversions +in both directions. It matches [`#[derive(HasFields)]`](./derive_has_fields.md): ```rust impl HasFields for Person { @@ -143,9 +131,10 @@ impl HasFields for Person { // plus HasFieldsRef, FromFields, ToFields, ToFieldsRef ``` -Then the **builder**, which is [`#[derive(BuildField)]`](./derive_build_field.md)'s output and where the -companion type appears. Each field's type is wrapped in a [`MapType`](../traits/type-level/map_type.md) marker, so -a field can be present (`IsPresent`, holding the value) or absent (`IsNothing`, holding `()`): +The builder output adds a companion type, as documented for +[`#[derive(BuildField)]`](./derive_build_field.md). Each field's type is wrapped in a +[`MapType`](../traits/type-level/map_type.md) marker: `IsPresent` stores its value, and `IsNothing` +stores `()`: ```rust pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { @@ -163,11 +152,11 @@ impl FinalizeBuild for __PartialPerson { } ``` -That pair of impls is the whole safety argument: `builder()` starts at all-absent, each -[`build_field`](../traits/builder/build_field.md) flips one marker, and -[`finalize_build`](../traits/builder/finalize_build.md) exists only at all-present, so finalizing early is a -missing impl rather than a runtime check. The per-field [`UpdateField`](../traits/builder/update_field.md) impls -that move a marker, and the `HasField` impls on the companion that let a set field be read back, follow. +The builder's type prevents incomplete construction. `builder()` starts with every field absent, +[`build_field`](../traits/builder/build_field.md) changes one marker to `IsPresent`, and +[`finalize_build`](../traits/builder/finalize_build.md) applies only when every field is present. +Per-field [`UpdateField`](../traits/builder/update_field.md) implementations change the markers, and +`HasField` implementations on the companion allow reads of fields that have been set. The companion is named `__Partial{Name}` and keeps the original type's visibility, so a `pub` struct yields a `pub` companion. Each generated impl is aimed at the token it came from (a per-field impl at @@ -176,10 +165,9 @@ token rather than the whole derive. ## Common Mistakes -**The companion type carries none of your attributes.** The derive clears them, so a -`#[derive(Debug, Clone)]` on the record does not reach `__Partial{Name}` and a partially-built value can -be neither printed nor cloned. Read a set field back through the companion's -[`HasField`](../traits/field-access/has_field.md) impl instead. +**The companion type does not inherit your attributes.** A `#[derive(Debug, Clone)]` on the record +does not apply to `__Partial{Name}`, so it does not make partial values printable or cloneable. Read a +set field through the companion's [`HasField`](../traits/field-access/has_field.md) implementation. **A tuple struct's builder is keyed by position.** Its companion exposes `UpdateField, _>` rather than symbol-keyed impls, so `build_field` takes `PhantomData::>`. @@ -188,17 +176,20 @@ rather than symbol-keyed impls, so `build_field` takes `PhantomData::>` This is the newtype special case described on the [`#[derive(HasFields)]`](./derive_has_fields.md) page, which this derive inherits. -**A fieldless struct compiles and does nothing useful.** It yields a parameterless companion whose -`builder()` is immediately finalizable. +**A fieldless struct has an immediately finalizable builder.** Its companion does not need field-state +parameters. -**An enum is rejected**, which is the point of the name. Reach for -[`#[derive(CgpVariant)]`](./derive_cgp_variant.md) or the umbrella. +**`CgpRecord` rejects enums.** Use [`CgpVariant`](./derive_cgp_variant.md) or +[`CgpData`](./derive_cgp_data.md) for an enum. -**This is one of the heaviest derives in CGP.** One of these on a five-field struct generates a -companion type and roughly twenty impls. If only part of the output is wanted, derive the slice. +**The full record derive adds compilation work.** It generates a companion type, whole-type +implementations, and per-field implementations. Use an individual derive when only part of the output +is needed. ## Related constructs +These references cover the related derives, generated traits, and supporting types: + - [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella, which dispatches here for a struct. - [`#[derive(CgpVariant)]`](./derive_cgp_variant.md) — the enum face. - [`#[derive(HasField)]`](./derive_has_field.md), [`#[derive(HasFields)]`](./derive_has_fields.md), and @@ -208,13 +199,15 @@ companion type and roughly twenty impls. If only part of the output is wanted, d parameterized by. - [`CanBuildFrom`](../traits/casting/can_build_from.md) — merging one record into another's builder. -The ideas behind it: +The ideas behind it are explained on these concept pages: - [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields, and the extensible builder pattern. ## Source +The implementation is defined in these source files: + - Entry point: [`cgp_record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_record.rs) - Record codegen: [`cgp_data/record.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/record.rs) - Runtime traits: [`cgp-field/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-field/src/traits) diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 7cecbc84..b3345a45 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -5,25 +5,24 @@ sidebar_position: 5 # `#[derive(CgpVariant)]` -The extensible-data derive for an enum. +`#[derive(CgpVariant)]` generates a structural representation, constructors, and an extractor for an enum. ## Overview -A plain Rust enum is opaque to generic code. There is no way to refer to "the `Circle` variant" through -a type parameter, so anything that must work across several enums ends up written once per enum, and -the `match` that would make it exhaustive can only be written where the concrete enum is named. +Generic code needs traits to construct and handle variants across different enums. A type parameter +alone does not let it name a `Circle` variant or match exhaustively on the concrete enum. -`#[derive(CgpVariant)]` turns an enum into **extensible data**: a type whose variants generic code can -name, construct, and take apart without ever mentioning the concrete type. It produces the whole -variant half of the family in one line: the whole-shape variant list, a constructor per variant, and an -incremental extractor that removes variants one at a time while tracking which are still possible. +`#[derive(CgpVariant)]` supplies those traits, making the enum **extensible data**. It generates a +representation of the whole enum, a constructor per variant, and an extractor that handles variants +individually while tracking which remain possible. Generic code can use these operations without +naming the concrete enum. -It is the enum-only face of [`#[derive(CgpData)]`](./derive_cgp_data.md). The two run the same code and -emit the same output on an enum. The difference is that this one **rejects a struct at parse time**. +`CgpVariant` accepts only enums. It produces the same output as +[`CgpData`](./derive_cgp_data.md) on an enum, but rejects a struct at parse time. ## Usage -The derive takes no arguments and has no helper attributes: +Apply `CgpVariant` to an enum without arguments or helper attributes: ```rust use cgp::prelude::*; @@ -40,13 +39,11 @@ and a `where` clause are carried onto everything generated, including the compan ### Every variant needs exactly one unnamed payload -**This is the family's one real restriction.** It comes from the two slices that take an enum apart: -each has to name a single type per variant, and a unit, multi-field, or struct-style variant gives it -none or several. Such a variant fails with `Expected variant to contain exactly one unnamed field`, and -there is **no way to opt one variant out**. An enum that mixes shapes cannot take this derive at all. +Every variant must contain exactly one unnamed field. The constructor and extractor implementations +use that field's type as the payload type. Unit, multi-field, and struct-style variants fail with +`Expected variant to contain exactly one unnamed field`. Individual variants cannot opt out. -The fix is to wrap the richer payload in its own struct, so the variant's value stays a single nameable -type: +Wrap a richer payload in its own struct so the variant contains a single payload type: ```rust // rejected: a struct-style variant has no single payload type @@ -65,17 +62,16 @@ pub enum Shape { } ``` -That is idiomatic rather than a workaround. The payload struct usually wants to be a type in its own -right, and it can derive [`#[derive(CgpRecord)]`](./derive_cgp_record.md) too, which is how a nested -shape becomes reachable. +The payload struct can also derive [`CgpRecord`](./derive_cgp_record.md). This lets generic code +process the payload's fields after extracting it from the enum. -One exception is worth knowing: [`#[derive(HasFields)]`](./derive_has_fields.md) accepts **all four** -variant shapes, because it only describes a variant rather than deconstructing it. So an enum with mixed -variants can still have a structural representation, but not the generic constructor or the extractor. +[`HasFields`](./derive_has_fields.md) accepts every variant shape and provides a structural +representation with whole-value conversions. Use it alone for an enum with mixed variant shapes; +that enum cannot derive the per-variant constructor or extractor. ### What it generates -Three groups, each of which is also available as a derive of its own: +The derive combines these outputs, each also available separately: | Group | The slice on its own | |---|---| @@ -85,8 +81,8 @@ Three groups, each of which is also available as a derive of its own: ## Examples -The variant machinery is most useful for matching generically with a guaranteed-exhaustive end. Each -extraction either yields the payload or hands back a *remainder* whose type has that variant ruled out: +An extraction chain checks exhaustiveness through the type of its remainder. Each attempt returns +either the payload or a remainder whose type rules out that variant: ```rust use cgp::core::field::traits::FinalizeExtractResult; @@ -111,34 +107,32 @@ fn area(shape: Shape) -> f64 { } ``` -There is no wildcard arm and no `unreachable!()`. After the second extraction the remainder's type has -both variants ruled out, which makes it uninhabited, and -[`finalize_extract_result`](../traits/variant/finalize_extract_result.md) discharges a value that cannot exist. -Add a third variant to `Shape` and this function stops compiling until it is handled, which is the same -guarantee a concrete `match` gives, recovered for code that never names the enum. +The final extraction cannot fail because its remainder type is uninhabited: a value of that type +cannot exist. [`finalize_extract_result`](../traits/variant/finalize_extract_result.md) therefore +returns the payload without a wildcard arm or `unreachable!()`. Adding another variant makes the +function fail to compile until that variant is handled. The same operations support generic code +that cannot name the enum. ## When to use it -**Reach for it when generic code has to work over the enum's own structure**, and prefer -[`#[derive(CgpData)]`](./derive_cgp_data.md) unless naming the shape earns its keep as documentation. +Use `CgpVariant` when generic code needs an enum's representation, constructors, and extractor, and +the derive name should specify that the input is an enum. Choose a narrower operation when the full +set is unnecessary: -- **Use `#[derive(CgpVariant)]`** to state that a type is always an enum, and to have a later change to - a struct fail at the derive. -- **Use [`#[derive(CgpData)]`](./derive_cgp_data.md)** as the default. -- **Prefer a `match`** for a closed enum with fixed operations. It is clearer than any machinery and it - already gives exhaustiveness. Reach for the variant derives when the variant set is open, or when - independent modules must each contribute a variant or an operation over one. -- **Derive the slice you want**: [`FromVariant`](./derive_from_variant.md) alone if code only needs to - *construct*, [`ExtractField`](./derive_extract_field.md) alone if it only needs to deconstruct, and - [`HasFields`](./derive_has_fields.md) alone for the shape, which is the only one of the three that - accepts every variant shape. +- **`CgpVariant`**: generate the full variant output and reject non-enum inputs. +- **[`CgpData`](./derive_cgp_data.md)**: generate the same output while also accepting structs. +- **A plain `match`**: handle a closed enum with fixed operations and ordinary exhaustiveness checking. +- **[`FromVariant`](./derive_from_variant.md)**: generate only the constructors. +- **[`ExtractField`](./derive_extract_field.md)**: generate only the extractor. +- **[`HasFields`](./derive_has_fields.md)**: generate only the representation and conversions. This + derive also accepts mixed variant shapes. -The full argument for when a type earns the extensible-data machinery at all is on the -[umbrella page](./derive_cgp_data.md#when-to-use-it). +The [CgpData page](./derive_cgp_data.md#when-to-use-it) explains when generic structural operations +justify the additional generated code. ## Under the hood -The derive emits three groups in order. From: +The derive generates representation traits, constructors, and an extractor for the input enum: ```rust #[derive(CgpVariant)] @@ -148,7 +142,7 @@ pub enum Shape { } ``` -it first emits the **representation**, over a sum rather than a product: +The representation describes the enum as a sum of named variants: ```rust impl HasFields for Shape { @@ -161,8 +155,8 @@ impl HasFields for Shape { // plus HasFieldsRef, FromFields, ToFields, ToFieldsRef ``` -Then the **constructors**, one per variant, which is -[`#[derive(FromVariant)]`](./derive_from_variant.md)'s output: +The constructor output contains an implementation per variant, as documented for +[`#[derive(FromVariant)]`](./derive_from_variant.md): ```rust impl FromVariant for Shape { @@ -174,10 +168,10 @@ impl FromVariant for Shape { } ``` -Then the **extractor**, which is [`#[derive(ExtractField)]`](./derive_extract_field.md)'s output and -where two companion enums appear: `__PartialShape` for owned extraction and `__PartialRefShape` for -borrowed. A variant's payload is wrapped in a [`MapType`](../traits/type-level/map_type.md) marker that is either -`IsPresent` or `IsVoid`, the latter mapping it to the uninhabited `Void`: +The extractor output adds `__PartialShape` for owned extraction and `__PartialRefShape` for borrowed +extraction, as documented for [`#[derive(ExtractField)]`](./derive_extract_field.md). A +[`MapType`](../traits/type-level/map_type.md) marker wraps each payload: `IsPresent` keeps the value, +and `IsVoid` maps it to the uninhabited `Void`: ```rust pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { @@ -195,11 +189,9 @@ impl FinalizeExtract for __PartialShape { // nothing left: un } ``` -**Note the asymmetry with the record side, which is the detail most worth carrying away: a record uses -`IsNothing` for a field that is not there, and a variant uses `IsVoid` for one that has been ruled out.** -`IsNothing` maps a type to `()`, which is inhabited; `IsVoid` maps it to `Void`, which is not. That is -exactly why extraction ends the way it does: once every variant is `IsVoid` the whole companion enum is -uninhabited, so a value of it cannot exist and can be discharged to produce anything. +A ruled-out variant uses `IsVoid`, while an absent record field uses `IsNothing`. `IsNothing` maps a +type to the inhabited `()`; `IsVoid` maps it to the uninhabited `Void`. Once every variant is marked +`IsVoid`, the companion enum is uninhabited, so an empty match on it can return any type. The companion names are reserved: `__Partial{Name}` and `__PartialRef{Name}`. They keep the original type's visibility. Each generated impl is aimed at the token it came from, so a conflict with a @@ -207,9 +199,9 @@ hand-written impl underlines that variant rather than the whole derive. ## Common Mistakes -**Every variant needs exactly one unnamed payload**, with no per-variant opt-out. -[`#[derive(HasFields)]`](./derive_has_fields.md) is the one derive in the family that accepts all four -shapes, so an enum with mixed variants gets that derive instead. +**Every variant needs exactly one unnamed payload.** Individual variants cannot opt out. +[`HasFields`](./derive_has_fields.md) accepts all variant shapes when only the representation and +whole-value conversions are needed. **Seven variant names are reserved.** Because the generated impls name their associated types through `Self::…`, a variant called `Fields`, `FieldsRef`, `Value`, `Remainder`, `Extractor`, `ExtractorRef`, or @@ -220,21 +212,23 @@ while the extractor's are generated for the companion enums and point back at th variant is the fix. Record field names are unaffected, since a field is not in the same namespace as an associated type. -**The companion enums carry none of your attributes.** The derive clears them, so an extraction -remainder is neither `Debug` nor `PartialEq` however the enum is derived. `assert_eq!` over a -`Result` does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. +**The companion enums do not inherit your attributes.** Deriving `Debug` or `PartialEq` on the +original enum does not implement them for the extraction remainder. Use `.ok()`, `.is_ok()`, or a +`match` to inspect an extraction result instead of comparing the whole result with `assert_eq!`. -**Absence is spelled differently on the two sides.** `IsVoid` for a ruled-out variant, `IsNothing` for a -missing record field, and they are not interchangeable. An error naming the wrong one usually means -record and variant machinery have been crossed. +**Record and variant absence use different markers.** Use `IsVoid` for a ruled-out variant and +`IsNothing` for a missing record field. An error naming the wrong marker usually means record and +variant operations have been mixed. -**A variantless enum compiles and does nothing useful.** It yields bare companion enums. +**A variantless enum is accepted.** It produces empty companion enums without field-state parameters. -**A struct is rejected**, which is the point of the name. Reach for -[`#[derive(CgpRecord)]`](./derive_cgp_record.md) or the umbrella. +**`CgpVariant` rejects structs.** Use [`CgpRecord`](./derive_cgp_record.md) or +[`CgpData`](./derive_cgp_data.md) for a struct. ## Related constructs +These references cover the related derives, generated traits, and supporting types: + - [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella, which dispatches here for an enum. - [`#[derive(CgpRecord)]`](./derive_cgp_record.md) — the struct face. - [`#[derive(HasFields)]`](./derive_has_fields.md), [`#[derive(FromVariant)]`](./derive_from_variant.md), @@ -247,7 +241,7 @@ record and variant machinery have been crossed. - [Dispatch combinators](../providers/dispatch/index.md) — the providers that route a variant to the implementation handling it. -The ideas behind it: +The ideas behind it are explained on these concept pages: - [Extensible variants](/docs/concepts/extensible-variants) — the enum half, and the extensible visitor pattern. @@ -255,6 +249,8 @@ The ideas behind it: ## Source +The implementation is defined in these source files: + - Entry point: [`cgp_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_variant.rs) - Variant codegen: [`cgp_data/variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/variant.rs) - Runtime traits: [`cgp-field/src/traits/`](https://github.com/contextgeneric/cgp/tree/main/crates/core/cgp-field/src/traits) diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 93dd8ea8..82e070d0 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -5,18 +5,16 @@ sidebar_position: 7 # `#[derive(ExtractField)]` -Extractor support for a variant. +`#[derive(ExtractField)]` generates an enum extractor that tracks remaining variants in its type. ## Overview -A `match` on an enum is checked for exhaustiveness, which is one of Rust's best properties. But it only -works where the concrete enum is named. Code that is generic over the enum cannot write a `match`, so it -falls back on a wildcard arm and an `unreachable!()`, discarding exactly the guarantee you wanted to -keep. +Generic code cannot match directly on an enum whose concrete type it does not know. It needs a trait +interface that preserves Rust's exhaustiveness checking while handling variants individually. -`#[derive(ExtractField)]` recovers it. It lets an enum be taken apart one variant at a time, and it tracks -which variants are still possible **in the type**. Each attempt either yields the payload or hands back a -*remainder* whose type has that variant ruled out: +`#[derive(ExtractField)]` provides that interface by tracking the remaining variants in the +extractor's type. Each extraction either returns the payload or returns a **remainder** whose type +rules out that variant: ```rust match shape.to_extractor().extract_field(PhantomData::) { @@ -25,19 +23,18 @@ match shape.to_extractor().extract_field(PhantomData::) { } ``` -Keep going and the remainder narrows each time. Once every variant has been ruled out, the remainder's type -is **uninhabited** (a value of it cannot exist), and that closes the chain with no wildcard arm and no panic -path. Add a variant to the enum and the final remainder becomes inhabited again, so the code stops compiling -until the new variant is handled. The exhaustiveness check survives, for code that never names the enum. +The chain is exhaustive when every variant has been ruled out. At that point, the remainder is +**uninhabited**, meaning a value of its type cannot exist, so the chain can finish without a wildcard +arm or a panic. Adding a variant makes the final remainder inhabited again and prevents finalization +until the new variant is handled. -The struct-side counterpart is [`#[derive(BuildField)]`](./derive_build_field.md), which tracks which -fields are present rather than which variants are possible. Both show what "extensible" means in -[extensible data](/docs/concepts/extensible-variants): the type carries the progress, so the compiler -checks it. +[`BuildField`](./derive_build_field.md) provides the corresponding operation for structs: it tracks +which fields are present during construction. Both use types to record progress so the compiler can +check completeness. ## Usage -The macro is a plain derive on an enum. It takes no arguments and has no helper attributes: +Apply `ExtractField` to an enum without arguments or helper attributes: ```rust use cgp::prelude::*; @@ -55,12 +52,11 @@ every generated impl. ### Every variant needs exactly one unnamed payload -**This is the derive's one requirement, and it is strict.** Extraction has to name a single type per variant, -so a unit variant, a multi-field tuple variant, and a struct-style variant all fail with -`Expected variant to contain exactly one unnamed field`. There is no way to opt one variant out, so an enum -that mixes shapes cannot derive the extractor at all. +Every variant must contain exactly one unnamed field. The extractor uses that field's type as its +payload type. Unit, multi-field, and struct-style variants fail with +`Expected variant to contain exactly one unnamed field`. Individual variants cannot opt out. -The fix is to give the payload its own struct: +Wrap the payload in a dedicated struct to give each variant a single payload type: ```rust // rejected: no single payload type @@ -83,43 +79,39 @@ pub enum Shape { } ``` -That is idiomatic rather than a concession. The payload usually deserves to be a type, and it can derive the -extensible-data machinery itself. Note that even a fieldless case has to be given a payload struct, since a -bare `Empty` is a unit variant. +Payload structs can derive extensible-data operations themselves. A fieldless case also needs a +payload type, such as the unit struct `Empty` above; a bare `Empty` variant does not meet the +single-field requirement. -If you want the enum described structurally without deriving the extractor, -[`#[derive(HasFields)]`](./derive_has_fields.md) accepts all four variant shapes. A variantless enum is -accepted here too, and degenerates: the companion enums take no parameters at all. +[`HasFields`](./derive_has_fields.md) accepts every variant shape when only a structural +representation and whole-value conversions are needed. `ExtractField` also accepts a variantless +enum; its companion enums do not need field-state parameters. The derive parses an enum, so applying it to a struct fails at parse time. The struct analogue is [`#[derive(BuildField)]`](./derive_build_field.md). ### What it does *not* generate -Deriving this slice alone gives you deconstruction and nothing else: **no** whole-shape representation and -**no** generic constructors. Those come from [`#[derive(HasFields)]`](./derive_has_fields.md) and -[`#[derive(FromVariant)]`](./derive_from_variant.md), and the umbrella -[`#[derive(CgpData)]`](./derive_cgp_data.md) includes all three. So an enum deriving only `ExtractField` is -taken apart generically but still constructed with its ordinary `Shape::Circle(..)` constructor. +`ExtractField` generates extraction support without a structural representation or generic +constructors. Derive [`HasFields`](./derive_has_fields.md) for the representation and +[`FromVariant`](./derive_from_variant.md) for constructors, or use +[`CgpData`](./derive_cgp_data.md) for all of them. An enum deriving only `ExtractField` still uses +ordinary constructors such as `Shape::Circle(..)`. ### The three extractors -The derive generates three ways in, differing only in how the payload is held. +Choose an extractor according to how the operation needs to access the payload: -**`to_extractor()`** consumes the value and yields payloads by value. This is the one most code uses. +- **`to_extractor()`**: consume the enum and return payloads by value. +- **`extractor_ref()`**: borrow the enum and return shared references to payloads. +- **`extractor_mut()`**: borrow the enum mutably so payloads can be modified in place. -**`extractor_ref()`** borrows, so each payload comes out as a shared reference and the original value is -untouched. Use it for a read-only operation over an enum you do not own. - -**`extractor_mut()`** borrows mutably, so a payload can be modified in place. - -All three then drive the same `extract_field` chain, and `from_extractor` converts an owned extractor back -into the enum. +Each form supports the same `extract_field` chain. `from_extractor` converts an all-present owned +extractor back into the original enum. ## Examples -The chain reads as a sequence of attempts, each handling one variant, with the last one closed by -`finalize_extract_result`: +`finalize_extract_result` returns the last payload once the chain has ruled out every other variant: ```rust use cgp::core::field::traits::FinalizeExtractResult; @@ -144,12 +136,11 @@ fn area(shape: Shape) -> f64 { } ``` -The second `extract_field` returns a `Result` whose error type is uninhabited, so -`finalize_extract_result` collapses it to the value with nothing to handle. That is not a convention. It is -the type. Try to finalize after only the first extraction and it does not compile, because `Rectangle` is -still possible. +The final `extract_field` returns a `Result` with an uninhabited error type, so +`finalize_extract_result` can return its value directly. Finalizing after only the `Circle` attempt +fails to compile because `Rectangle` is still possible. -Reading through a borrow leaves the value intact: +`extractor_ref()` lets the operation read a payload while preserving the original value: ```rust let radius = shape @@ -159,7 +150,7 @@ let radius = shape .ok(); ``` -And the mutable form modifies a payload in place: +`extractor_mut()` lets the operation modify a payload in place: ```rust if let Ok(circle) = shape @@ -170,47 +161,40 @@ if let Ok(circle) = shape } ``` -In practice you rarely write these chains by hand. The -[dispatch combinators](../providers/dispatch/index.md) build them for you from a set of per-variant -implementations, which is the extensible visitor pattern: a chain like the one above, generated, with one -implementation per variant chosen by wiring. +The [dispatch combinators](../providers/dispatch/index.md) generate extraction chains from +per-variant implementations. This supports the extensible visitor pattern: each implementation +handles a variant, and wiring selects which implementation to use. ## When to use it -**Derive an extractor when independent code has to handle one variant each, or when the code doing the -matching cannot name the enum.** Those are the two cases, and outside them a `match` wins on every count. - -- **Reach for it for the extensible visitor pattern.** When variants and the operations over them both need - to grow without editing each other, this derive supports per-variant implementations plus a dispatcher. -- **Reach for it when the enum is a type parameter.** Generic code cannot `match`, so the extractor is the - only route to an exhaustiveness guarantee. -- **Do not reach for it for a closed enum with fixed operations.** A `match` is shorter, reads better, - already gives exhaustiveness, and generates nothing. This derive is not an improvement on `match`; you use - it when `match` is unavailable. -- **Do not reach for it to test which variant a value holds.** `matches!` or an `if let` answers that in one - line. The extractor's value is in the *chain* and what the chain proves. - -Between this derive and its neighbours: - -- **[`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpVariant)]`](./derive_cgp_variant.md)** if the - enum also needs a structural representation or generic construction, which is the common case. Those - include this output. -- **`#[derive(ExtractField)]` alone** when the enum is only ever deconstructed generically. -- **[`#[derive(FromVariant)]`](./derive_from_variant.md)** is the opposite direction, and the two are often - wanted together. - -One honest limit: the single-payload requirement is real friction. An enum whose variants carry no payload, -or several, has to be restructured before it can take this derive, and that restructuring reaches every -construction site. It is worth doing when the visitor pattern is the goal and not worth doing to satisfy a -derive you did not need. +Use `ExtractField` when independent implementations handle individual variants or when generic code +cannot name the enum. Prefer ordinary matching when the concrete enum is available: + +- **The extensible visitor pattern:** combine independent per-variant implementations through a + dispatcher when variants and operations need to grow separately. +- **A generic enum type:** use the extractor's trait interface to check exhaustiveness without naming + the concrete variants in a `match`. +- **A closed enum with fixed operations:** use a `match`, which already checks exhaustiveness. +- **A single variant test:** use `matches!` or `if let` when a complete extraction chain is unnecessary. + +Choose the derive according to the operations the enum needs: + +- **[`CgpData`](./derive_cgp_data.md) or [`CgpVariant`](./derive_cgp_variant.md)**: include the + representation and generic constructors alongside extraction. +- **`ExtractField` alone**: provide only generic extraction. +- **[`FromVariant`](./derive_from_variant.md)**: provide generic construction, often needed alongside + extraction. + +The single-payload requirement can require changes at every construction site. An enum with unit, +multi-field, or struct-style variants must be restructured before it can derive the extractor. +Consider that cost when deciding whether independent variant handling is needed. ## Under the hood -The derive centres on **two** companion enums. `__Partial{Name}` is your enum with one -[`MapType`](../traits/type-level/map_type.md) parameter added per variant and each payload wrapped in that parameter's -projection, where `IsPresent` keeps the payload and `IsVoid` maps it to the uninhabited `Void`. -`__PartialRef{Name}` adds a reserved `'__a__` lifetime and a second marker that selects a shared or a mutable -borrow of each payload. From: +The derive generates an owned companion enum and a borrowed companion enum. `__Partial{Name}` adds +one [`MapType`](../traits/type-level/map_type.md) parameter per variant: `IsPresent` preserves the +payload and `IsVoid` replaces it with the uninhabited `Void`. `__PartialRef{Name}` also adds the +reserved lifetime `'__a__` and a marker selecting shared or mutable references. For this input: ```rust #[derive(ExtractField)] @@ -220,7 +204,7 @@ pub enum Shape { } ``` -it emits: +The companion enums wrap each payload in the corresponding marker projections: ```rust pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { @@ -234,8 +218,8 @@ pub enum __PartialRefShape<'__a__, __R__: MapTypeRef, __F0__: MapType, __F1__: M } ``` -Around them come the three entry points and the exit. `HasExtractor` yields an owned extractor with every -variant present; the borrowed pair yield the ref enum with the borrow marker fixed to `IsRef` or `IsMut`: +`HasExtractor` supplies an owned extractor with every variant still possible. `HasExtractorRef` and +`HasExtractorMut` use the borrowed companion with its borrow marker set to `IsRef` or `IsMut`: ```rust impl HasExtractor for Shape { @@ -253,9 +237,8 @@ impl HasExtractorRef for Shape { // plus HasExtractorMut over __PartialRefShape<'__a__, IsMut, IsPresent, IsPresent> ``` -The exit is the impl the whole design turns on. It exists only for the all-`IsVoid` configuration, and -because that configuration is uninhabited its body is an empty `match`, which is why it can claim to return -*any* type: +`FinalizeExtract` is implemented only for the all-`IsVoid` configuration. That configuration is +uninhabited, so its implementation can return any type through an empty match: ```rust impl FinalizeExtract for __PartialShape { @@ -265,8 +248,8 @@ impl FinalizeExtract for __PartialShape { } ``` -Then, per variant, an `ExtractField` impl in scope only when that variant's marker is `IsPresent`. It returns -`Ok` on a match and, on a miss, an `Err` whose type has that one marker flipped to `IsVoid`: +Each variant gets an `ExtractField` implementation available when its marker is `IsPresent`. +A match returns `Ok(payload)`; a miss returns `Err(remainder)` with that marker changed to `IsVoid`: ```rust impl<__F1__: MapType> ExtractField for __PartialShape { @@ -282,47 +265,45 @@ impl<__F1__: MapType> ExtractField for __PartialShape` into `T`. -**The variantless enum is genuinely special-cased**, and the reason is a Rust subtlety worth knowing. Such an -enum borrows nothing, so the ref companion is emitted as a bare empty enum with neither the lifetime nor the -borrow marker. Leaving them in would make both unused parameters. And every borrowed accessor matches -`*self` rather than `self`, because a reference is always considered inhabited even when its target is not, so -`match self {}` on a `&Self` would be rejected as non-exhaustive. +A variantless enum produces an empty borrowed companion without a lifetime or borrow marker. It +borrows nothing, so those parameters would be unused. Its borrowed accessors match `*self` rather +than `self`: Rust considers a reference inhabited even when its target is uninhabited, so an empty +`match self {}` on `&Self` would fail the exhaustiveness check. Each generated impl is aimed at the token it came from: a per-variant impl at its variant, a whole-enum impl at the enum name. The companion enums are cloned from yours, so their tokens already carry meaningful spans. ## Common Mistakes -**Every variant must carry exactly one unnamed payload.** A unit, multi-field, or struct-style variant fails, -with no per-variant opt-out. Wrap the payload in its own struct, including for a case that carries nothing, -which still needs a payload type. [`#[derive(HasFields)]`](./derive_has_fields.md) is the derive that accepts -all four shapes. - -**Absence here is `IsVoid`, not `IsNothing`.** The record side uses `IsNothing`, which maps a type to `()` -and is inhabited; a ruled-out variant uses `IsVoid`, which maps to the uninhabited `Void`. That difference -matters rather than being cosmetic: it is why a fully-narrowed remainder cannot exist and can be discharged. -An error naming the wrong marker usually means record and variant machinery have been crossed. - -**Five variant names are reserved, and using one does not compile.** The generated impls write -`Self::Value`, `Self::Remainder`, `Self::Extractor`, `Self::ExtractorRef`, and `Self::ExtractorMut` to name -their associated types, so a variant with any of those names makes the path ambiguous. The compiler reports -`ambiguous associated item`, and this is the opaque one in the family: both the headline *and* the -"could refer to the variant defined here" note land on the derive, so nothing in the output names the -variant to rename. That is because these impls are generated for the companion enums rather than for -yours. Check your variant names against the five above. Renaming the variant is the fix. -[`#[derive(HasFields)]`](./derive_has_fields.md) reserves `Fields` and `FieldsRef` for the same reason, so an -enum deriving the whole family should avoid all seven. - -**A remainder carries none of the enum's attributes.** Like the record side's companion, the partial enums -are generated without your derives, so a `Result` cannot be compared or printed as a -whole. Reach for `.ok()`, `.is_ok()`, or a `match` rather than `assert_eq!` on the result. +**Every variant must carry exactly one unnamed payload.** Individual variants cannot opt out. Wrap +richer payloads in structs, and give a fieldless case a payload type too. +[`HasFields`](./derive_has_fields.md) accepts all variant shapes if only a representation is needed. + +**A ruled-out variant uses `IsVoid`.** It maps the payload to uninhabited `Void`, allowing a fully +narrowed remainder to be finalized. The record marker `IsNothing` maps to inhabited `()`, so it cannot +serve that purpose. An error naming `IsNothing` usually means record and variant operations have +been mixed. + +**Reserved variant names make generated associated-type paths ambiguous.** Avoid `Value`, `Remainder`, +`Extractor`, `ExtractorRef`, and `ExtractorMut`. The generated implementations use those names through +`Self::…`, which conflicts with identically named variants and produces `ambiguous associated item`. + +Extractor diagnostics may leave the offending variant unnamed. The implementations target generated +companion enums, so both the headline and the note can point to the derive. Check the names above and +rename the conflicting variant. [`HasFields`](./derive_has_fields.md) also reserves `Fields` and +`FieldsRef`, so an enum deriving the full family must avoid those too. + +**The remainder does not inherit the enum's attributes.** Deriving `Debug` or `PartialEq` on the +enum does not implement them for the companion. Use `.ok()`, `.is_ok()`, or a `match` to inspect the +result instead of printing or comparing the whole `Result`. **`FinalizeExtractResult` is not in the prelude.** Import it from `cgp::core::field::traits` to call `finalize_extract_result`. @@ -331,18 +312,20 @@ whole. Reach for `.ok()`, `.is_ok()`, or a `match` rather than `assert_eq!` on t while any marker is still `IsPresent`, so the compiler reports a missing method. Read the companion type in the message to see which variants are still possible. -**The order of extraction is free but the set is not.** Each step only changes its own variant's marker, so -you may extract in any order. But you must extract *every* variant before the remainder can be finalized. +**Every variant must be ruled out before finalizing the remainder.** Extraction order is unrestricted +because each step changes only its own variant's marker. -**Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the reason -to prefer the [dispatch combinators](../providers/dispatch/index.md), which derive the chain from the -enum's own variant list rather than repeating it at each site. +**Adding a variant makes an existing exhaustive chain incomplete.** Update hand-written chains to +handle the new variant, or use [dispatch combinators](../providers/dispatch/index.md) to generate +chains from the enum's variant list. **It does not accept a struct.** The struct analogue is [`#[derive(BuildField)]`](./derive_build_field.md). ## Related constructs +These references cover the related derives, generated traits, and supporting types: + - [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this slice. - [`#[derive(FromVariant)]`](./derive_from_variant.md) — the opposite direction, generic construction, which this derive does not generate. @@ -360,7 +343,7 @@ enum's own variant list rather than repeating it at each site. - [Dispatch combinators](../providers/dispatch/index.md) — the providers that build an extraction chain for you, one implementation per variant. -The ideas behind it: +The ideas behind it are explained on these concept pages: - [Extensible variants](/docs/concepts/extensible-variants) — partial variants, the exhaustiveness argument, and the extensible visitor pattern. @@ -368,6 +351,8 @@ The ideas behind it: ## Source +The implementation is defined in these source files: + - Entry point: [`derive_extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_extract_field.rs) - Codegen: [`cgp_data/derive_extractor/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_extractor) - Traits: [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index be78f21a..dfda3c47 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -5,31 +5,31 @@ sidebar_position: 8 # `#[derive(FromVariant)]` -Generic construction of an enum from one of its named variants. +`#[derive(FromVariant)]` lets generic code construct an enum variant selected by a type-level tag. ## Overview -`Shape::Circle(circle)` names two things: the enum, and the variant. That is fine at a concrete call site and -useless to code that knows neither: a routine that has been handed a value and told which variant to wrap it -in cannot write that expression. +Generic code needs a trait interface to construct a variant selected by a type parameter. +`Shape::Circle(circle)` fixes both the enum and variant at the call site. -`#[derive(FromVariant)]` gives it a way to. The derive adds one constructor per variant, addressed by the -variant's *name as a type*, so the choice of variant becomes a parameter rather than syntax: +`#[derive(FromVariant)]` generates a constructor for each variant, keyed by its name as a type-level +tag: ```rust Shape::from_variant(PhantomData::, circle) ``` -That call is equivalent to `Shape::Circle(circle)`. The difference is that the tag can come from a type -parameter, so one function can build whichever variant it was asked for, of whichever enum. +The tagged call constructs the same value as `Shape::Circle(circle)`. Because the tag can be a type +parameter, a function can select a variant generically. A bound on the enum type also lets the +function work across different enums. -**This is the simplest derive in the extensible-data family.** It generates no companion type, no state -tracking, and no traits of its own: just a constructor per variant. It is the counterpart to -[`#[derive(ExtractField)]`](./derive_extract_field.md), which takes a variant out; this one puts a variant in. +The derive generates only per-variant trait implementations, without companion types or state +tracking. [`ExtractField`](./derive_extract_field.md) provides the reverse operation: extracting a +payload from an enum. ## Usage -The macro is a plain derive on an enum. It takes no arguments and has no helper attributes: +Apply `FromVariant` to an enum without arguments or helper attributes: ```rust use cgp::prelude::*; @@ -47,12 +47,11 @@ impl. ### Every variant needs exactly one unnamed payload -**The derive shares the extractor's one requirement.** A constructor has to take a single value, so a unit -variant, a multi-field tuple variant, and a struct-style variant all fail with -`Expected variant to contain exactly one unnamed field`. There is no per-variant opt-out, so an enum that -mixes shapes cannot take this derive. +Every variant must contain exactly one unnamed field, whose type becomes the constructor's payload +type. Unit, multi-field, and struct-style variants fail with +`Expected variant to contain exactly one unnamed field`. Individual variants cannot opt out. -Wrapping the payload in its own struct is the fix, and idiomatic CGP enums do it anyway: +Wrap a richer payload in a dedicated struct so the variant contains a single payload type: ```rust pub struct Circle { @@ -65,23 +64,23 @@ pub enum Shape { } ``` -If the enum only needs to be *described* rather than constructed, -[`#[derive(HasFields)]`](./derive_has_fields.md) accepts all four variant shapes instead. A variantless enum -is accepted here and simply produces no impls. +[`HasFields`](./derive_has_fields.md) accepts every variant shape when only a structural +representation and whole-value conversions are needed. `FromVariant` accepts a variantless enum but +does not emit any implementations for it. The derive parses an enum, so applying it to a struct fails at parse time. The struct analogue, setting one field of a value being assembled, is [`#[derive(BuildField)]`](./derive_build_field.md). ### What it does *not* generate -Deriving this slice alone gives you construction and nothing else: **no** whole-shape representation and -**no** extractor. Those come from [`#[derive(HasFields)]`](./derive_has_fields.md) and -[`#[derive(ExtractField)]`](./derive_extract_field.md), and the umbrella -[`#[derive(CgpData)]`](./derive_cgp_data.md) includes all three. +`FromVariant` generates constructors without a structural representation or an extractor. Derive +[`HasFields`](./derive_has_fields.md) for the representation and +[`ExtractField`](./derive_extract_field.md) for extraction, or use +[`CgpData`](./derive_cgp_data.md) for all of them. ## Examples -The capability is a function that stays generic over the variant it builds: +A function can use `FromVariant` to stay generic over the variant it constructs: ```rust use cgp::prelude::*; @@ -100,19 +99,19 @@ where } ``` -One `wrap` builds either variant, and its payload type is *derived from the tag* rather than fixed: +`wrap` constructs either variant, with the payload type determined by the tag: ```rust let circle = wrap(PhantomData::, Circle { radius: 2.0 }); let rect = wrap(PhantomData::, Rectangle { width: 3.0, height: 4.0 }); ``` -No hand-written function can do that, because `Shape::Circle` and `Shape::Rectangle` are different -expressions taking different types. +The `FromVariant` bound connects each tag to its payload type and constructor. Without that +interface, `Shape::Circle` and `Shape::Rectangle` remain separate expressions with different argument +types. -In practice this earns its keep when building a value using only the variants an implementation knows about, -then widening it. A routine that only produces two of a large enum's variants declares a small local enum, -constructs into that, and lifts the result into the full type with an upcast: +Upcasting lets an implementation construct a small local enum and convert it into a larger one. +The implementation only needs to know the variants Each generated implementation selects its constructor through the variant-name tag: ```rust use cgp::core::field::impls::CanUpcast; // not in the prelude @@ -120,36 +119,29 @@ use cgp::core::field::impls::CanUpcast; // not in the prelude let expr = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); ``` -The upcast always succeeds, because every variant of the smaller enum maps to one in the larger one. That is -the construction-side counterpart of reading a field through a getter: the implementation names only what it -needs, and the widening is checked. Upcasting is documented with the other -[structural casts](../traits/casting/can_upcast.md), and it is built on the same per-variant machinery as this derive. +An upcast succeeds when every source variant has a matching variant in the target enum. The compiler +checks this correspondence, so the implementation can name only the variants it needs. See +[`CanUpcast`](../traits/casting/can_upcast.md) for the conversion and its trait requirements. ## When to use it -**Derive it when code that does not name a variant has to construct one.** That is the whole test, and it is -a narrower need than deconstruction. Most code decides which variant to build at a site that can just name -it. - -- **Reach for it when the variant is chosen by a type parameter.** A routine parameterized over the variant - it produces has no other option. -- **Reach for it to make a smaller enum upcastable into a larger one.** Casting between enums is built on - these constructors, so this derive lets an implementation work in a narrow local enum and widen the - result. -- **Do not reach for it for an ordinary constructor call.** `Shape::Circle(circle)` is shorter, clearer, and - generates nothing. This derive adds a *second* way to do the same thing, for callers that cannot use the - first. -- **Do not derive it alone if you also want to take the enum apart**, which is the usual case. Reach for - [`#[derive(CgpData)]`](./derive_cgp_data.md) or [`#[derive(CgpVariant)]`](./derive_cgp_variant.md), which - bundle construction, deconstruction, and the representation. - -The constructor and the extractor divide exactly as their names suggest: this derive puts a value -into an enum, [`#[derive(ExtractField)]`](./derive_extract_field.md) gets one out, and they are commonly -derived together because a generic pipeline usually does both. +Use `FromVariant` when generic code must construct a variant selected by a tag. Prefer a direct +constructor when the call site already knows the variant: + +- **A variant selected by a type parameter:** use `FromVariant` to connect the tag, payload type, + and constructor. +- **An upcast target:** generic casts use these constructors to build the target enum's variants. +- **An ordinary constructor call:** use `Shape::Circle(circle)` when the variant is known directly. +- **Construction and extraction together:** use [`CgpData`](./derive_cgp_data.md) or + [`CgpVariant`](./derive_cgp_variant.md) to include both operations and the representation. + +`FromVariant` constructs an enum from a payload, while +[`ExtractField`](./derive_extract_field.md) extracts a payload from an enum. Generic pipelines that +do both commonly derive both. ## Under the hood -The derive emits **one impl per variant and nothing else**: no companion type, no markers, no state. From: +The derive emits one `FromVariant` implementation per variant. For this input: ```rust #[derive(FromVariant)] @@ -179,13 +171,12 @@ impl FromVariant for Shape { } ``` -Each body is the plain constructor call. The impl adds two things: the *choice* between them is now a type -argument, and the payload type is reachable as `>::Value`, which lets a generic -signature name it without knowing which variant is in play. +Each implementation calls the ordinary variant constructor. It exposes the payload type as +`>::Value`, so a generic signature can name that type without selecting a +concrete variant. -The `PhantomData` parameter carries no value. It exists so a call site can say which impl it means when -several are in scope, which is why the tag is passed as `PhantomData::` rather than -inferred. +`PhantomData` selects the trait implementation without storing a runtime tag value. Specify a +tag such as `PhantomData::` when the call would otherwise be ambiguous. The [`FromVariant`](../traits/variant/from_variant.md) trait itself is defined in the library; the derive supplies only these per-variant impls. Each is aimed at the variant it came from, so a conflict with a hand-written impl @@ -193,16 +184,15 @@ underlines that variant rather than the whole `#[derive(FromVariant)]`. ## Common Mistakes -**Every variant must carry exactly one unnamed payload**, the same requirement the extractor has, with no -per-variant opt-out. [`#[derive(HasFields)]`](./derive_has_fields.md) is the derive that accepts all four -shapes. +**Every variant must carry exactly one unnamed payload.** Individual variants cannot opt out. +[`HasFields`](./derive_has_fields.md) accepts all variant shapes when only a representation is needed. -**The tag has to be written out, not inferred.** `Shape::from_variant(PhantomData::, value)` -needs the turbofish, because nothing in the value determines which variant to build when two variants could -share a payload type. +**Specify the tag when the payload does not determine the variant.** In +`Shape::from_variant(PhantomData::, value)`, the type argument selects `Circle`. +The payload type alone cannot distinguish variants that share that type. -**Two variants with the same payload type are still distinguishable, and only by the tag.** That is the reason -for the previous point, and it means a mistyped tag is a missing-impl error rather than a type mismatch. +**Variants sharing a payload type have distinct tags.** A tag that does not match an implemented +variant produces an unsatisfied `FromVariant` bound. **A variant name is a `Symbol!` of its identifier, matched exactly.** `Symbol!("Circle")` and `Symbol!("circle")` are unrelated types, so a case slip reports as an unsatisfied `FromVariant` bound. @@ -213,14 +203,16 @@ type, and a variant of that name makes the path ambiguous. The compiler reports `Value` is the only name this derive reserves; the [extractor](./derive_extract_field.md) reserves several more, so an enum taking both should avoid all of them. Renaming the variant is the fix. -**A variantless enum produces nothing**, silently. The derive succeeds and emits no impls, which is correct -and, as with the other empty shapes, means a mistake shows up later rather than here. +**A variantless enum is accepted without generating implementations.** It has nothing to construct; +code requiring a `FromVariant` implementation will fail at that use site. **It does not accept a struct.** The struct-side analogue is [`#[derive(BuildField)]`](./derive_build_field.md). ## Related constructs +These references cover the related derives, generated traits, and supporting types: + - [`#[derive(ExtractField)]`](./derive_extract_field.md) — the reverse operation, taking a variant out rather than putting one in; commonly derived alongside this one. - [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this slice. @@ -234,13 +226,15 @@ and, as with the other empty shapes, means a mistake shows up later rather than - [Type-level lists](../types/index.md) — the `Either`/`Void` chain the constructed variants correspond to. -The ideas behind it: +The ideas behind it are explained on these concept pages: - [Extensible variants](/docs/concepts/extensible-variants) — construction by name, and building through a small local enum before widening. ## Source +The implementation is defined in these source files: + - Entry point: [`derive_from_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_from_variant.rs) - Codegen: [`cgp_data/derive_from_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_from_variant.rs) - Trait: [`from_variant.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/from_variant.rs) diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 54aad656..cd58232c 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -5,36 +5,35 @@ sidebar_position: 1 # `#[derive(HasField)]` -Per-field accessors keyed by a type-level tag. +`#[derive(HasField)]` generates shared and mutable field accessors keyed by type-level tags. ## Overview -An implementation written against a **context** cannot name that context's concrete type. The context -is the type the capability runs against, and it supplies the values the implementation needs as its own -fields. Because the implementation is generic over the context, it cannot write `self.name`. Yet reading -a field out of the context is the most common thing such an implementation does. +A generic implementation cannot access fields with expressions such as `self.name`. It runs against +a **context**, the type that supplies the values it needs as fields, but does not know that context's +concrete type. -`#[derive(HasField)]` closes that gap. It gives each of a struct's fields a *type-level name*, so an -implementation can ask for "a `String` field called `name`" as an ordinary trait bound and receive the -field without knowing what type it came from: +`#[derive(HasField)]` lets the implementation request a field through a trait bound. It gives each +struct field a type-level tag, so the implementation can ask for a `String` field named `name` +without knowing the struct: ```rust Self: HasField ``` -Any struct that derives `HasField` and happens to have such a field satisfies that bound. Nothing is -matched by string at runtime. [`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler -resolves the lookup during compilation and the read compiles down to a direct field access. +Any struct deriving `HasField` with a matching name and field type satisfies that bound. +[`Symbol!("name")`](../macros/symbol.md) is a type, so the compiler resolves the tag to a direct field +access without a runtime string lookup. -**You will derive this constantly and almost never name `HasField` by hand.** It is the foundation of -the ergonomic surface: an [`#[implicit]`](../attributes/implicit.md) argument, a -[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method, and a [`UseField`](../providers/use_field.md) -wiring entry all generate the bound above from a name you already wrote. You write only the derive on the -struct. +Higher-level field access constructs generate the `HasField` bound for you. An +[`#[implicit]`](../attributes/implicit.md) argument, a +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method, or a +[`UseField`](../providers/use_field.md) wiring entry uses a field name to obtain the value. The struct +supplies the corresponding implementations by deriving `HasField`. ## Usage -The macro is a plain derive on a struct. It takes no arguments and has no helper attributes: +Apply `HasField` to a struct without arguments or helper attributes: ```rust #[derive(HasField)] @@ -57,8 +56,8 @@ its *logical* name, with the `r#` stripped: a field `r#type` is keyed by `Symbol ### Tuple fields -A tuple field has no name, so it is keyed by [`Index`](../types/index_type.md), the type-level number of -its position: +Tuple fields use [`Index`](../types/index_type.md) tags, where `N` is the field's zero-based +position: ```rust #[derive(HasField)] @@ -70,23 +69,21 @@ of its position, because `Index<0>` and `Symbol!("0")` are different types. ### Unit structs -A unit struct has no fields, so there is nothing to key. The derive accepts it and emits nothing at all -rather than reporting an error: +A unit struct is accepted without generating accessors because it has no fields: ```rust #[derive(HasField)] pub struct App; ``` -This is worth knowing because it is silent. Deriving `HasField` on a fieldless context is harmless and -does nothing. That is the right outcome, since such a context carries choices rather than data. But it -also means a mistake that leaves a struct fieldless produces no complaint here, only an unsatisfied bound -later. +A fieldless context can still supply component choices without storing values. Deriving `HasField` +on it is harmless, but does not satisfy a field-access bound. Code requiring a field will report an +unsatisfied bound at the use site. ### Generic structs -Generic parameters, lifetimes, and a `where` clause are all carried onto the generated access, so a -generic struct works with no extra work: +The generated implementations preserve generic parameters, lifetimes, and the struct's `where` +clause: ```rust #[derive(HasField)] @@ -106,8 +103,8 @@ together. ## Examples -An implementation states the field it needs as a bound, and the derive lets a concrete context satisfy -it. First the implementation, asking for a `String` field called `name`: +An implementation declares the field it needs as a bound. Here, `GreetHello` requires a `String` +field named `name`: ```rust use cgp::prelude::*; @@ -128,7 +125,7 @@ where } ``` -Then a context that derives the access and chooses that implementation: +`Person` supplies the field access and selects `GreetHello` as its implementation: ```rust #[derive(HasField)] @@ -143,12 +140,12 @@ delegate_components! { } ``` -Because `Person` derives `HasField`, it satisfies exactly the bound `GreetHello` requires, so -`person.greet()` compiles and prints the person's name. Remove the `name` field and the wiring stops -compiling: the requirement is checked, not assumed. +`Person` satisfies the field bound required by `GreetHello`, so `person.greet()` prints its name. +Removing the `name` field prevents the call from compiling because the required `HasField` +implementation is missing. -**Written idiomatically, none of that bound is visible.** The same read is an -[`#[implicit]`](../attributes/implicit.md) argument, which looks like an ordinary function parameter: +An [`#[implicit]`](../attributes/implicit.md) argument expresses the field dependency as a function +parameter: ```rust #[cgp_impl(new GreetHello)] @@ -159,37 +156,32 @@ impl Greeter { } ``` -That version generates the same `HasField` bound and the same field read. You *read* the explicit form -above in generated code or in a compiler error; you do not write it. +The implicit form generates a `HasField` bound and reads the field for you. Prefer it for this +ordinary field read; the explicit form is useful when reading generated code or diagnostics. -Field access also passes through smart pointers with no extra derive. `Box` and any newtype that -dereferences to `Person` resolve a field read to the inner struct, so wrapping a context does not break -the implementations that read from it. +Field access passes through smart pointers without an additional derive. `Box` and +newtypes that dereference to `Person` can read its fields through the library's blanket implementations. ## When to use it -**Derive it on every context whose fields an implementation reads.** There is little judgement here: the -derive is how a struct's fields become visible to the trait system, it costs one line, and every -construct that reads a field needs it. A context that derives nothing can still be wired and can still -implement consumer traits. It just cannot supply values. - -The judgement call is how you read the field once the derive is in place, and the ordering is settled. - -- **Use an [`#[implicit]`](../attributes/implicit.md) argument by default.** It reads a field of the - implementation's own context as a plain parameter, with no trait to declare. This covers the common - case, including a field that several implementations each read. -- **Use [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) when the read needs to be a named - capability**, when the field lives on a type other than the context, or when the getter should carry a - type inferred from the field. Those are the three cases an implicit argument cannot reach. -- **Write the `HasField` bound by hand only when neither fits**, which is rare. When you do, remember it - is an ordinary trait bound and can carry `Value = T` to pin the field's type. -- **Reach for [`#[derive(HasFields)]`](./derive_has_fields.md) instead when code must process the whole - shape** rather than one named field: serializing a struct, folding over its fields, building it - generically. The two answer different questions and are often derived together. - -This derive does **not** make a struct an extensible record. It gives indexed access to fields that -already exist. Building a struct up field by field is [`#[derive(BuildField)]`](./derive_build_field.md), -and [`#[derive(CgpData)]`](./derive_cgp_data.md) is the umbrella that includes both. +Derive `HasField` when implementations need to read a context's fields through CGP's field-access +interface. A context can still select implementations and implement consumer traits without the +derive, but its fields need corresponding trait implementations to support generic reads. + +Choose the field-access syntax according to what the implementation needs: + +- **[`#[implicit]`](../attributes/implicit.md)**: use by default to read a field from the + implementation's own context as a parameter, without declaring a getter trait. +- **[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md)**: use when the read should be a named + capability, the field belongs to another type, or the getter needs a type inferred from the field. +- **A hand-written `HasField` bound**: use when the higher-level forms do not fit. Add `Value = T` to + constrain the field type. +- **[`#[derive(HasFields)]`](./derive_has_fields.md)**: use for processing the whole structure, such + as serialization or generic field traversal. Derive both when code also needs individual reads. + +Incremental construction requires [`BuildField`](./derive_build_field.md). `HasField` provides access +to existing fields; [`CgpData`](./derive_cgp_data.md) combines it with the representation and builder +needed for an extensible record. ## Under the hood @@ -204,8 +196,7 @@ pub struct Person { } ``` -it produces, for each field, the field's type as the associated `Value` and a body that simply borrows -it: +Each generated accessor uses the declared field type as `Value` and returns a reference to the field: ```rust impl HasField for Person { @@ -225,10 +216,10 @@ impl HasFieldMut for Person { // and the same pair for `age`, with `Value = u8` ``` -The `PhantomData` parameter carries no value. It exists so a call site can say *which* field it -means when several `HasField` impls are in scope, which is why a call site writes -`PhantomData::`. [`HasFieldMut`](../traits/field-access/has_field_mut.md) extends `HasField` with -`get_field_mut`, and it is always generated alongside the read accessor, whether or not anything uses it. +`PhantomData` selects the field without storing a runtime tag value. A call such as +`get_field(PhantomData::)` selects the `name` accessor. +[`HasFieldMut`](../traits/field-access/has_field_mut.md) extends `HasField` with `get_field_mut`, and +the derive always generates it alongside shared access. A tuple struct produces the same shape with a positional tag: @@ -247,11 +238,11 @@ clause and threaded onto every impl, so `struct Wrapper { value: T }` yields `impl HasField for Wrapper` with `Value = T`. A struct lifetime carries through the same way, and a borrowed field type is kept verbatim as `Value`. -**The smart-pointer behaviour comes from the library, not the derive.** `HasField` and `HasFieldMut` -carry blanket impls for any type whose [`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) -target implements them, so `Box` resolves a field read to the inner struct. Those blanket impls -are marked so the compiler does not suggest them in a diagnostic, which keeps a missing-field error -pointed at the struct that lacks the field rather than at the pointer. +The library supplies smart-pointer access through blanket implementations of `HasField` and +`HasFieldMut`. Shared access requires [`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html), +and mutable access requires `DerefMut`, with the target implementing the corresponding field trait. +The blanket implementations are marked to keep the compiler from recommending them in missing-field +diagnostics, directing attention to the underlying struct. Each generated impl is also aimed at the field it came from, so a compiler error about one field's access underlines that field rather than the whole `#[derive(HasField)]`. That covers a conflict with a @@ -259,13 +250,11 @@ hand-written impl, and the "but the trait is implemented for" hint inside a miss ## Common Mistakes -**A unit struct produces nothing, silently.** There is no field to key, so the derive succeeds and emits -no impls. That is correct, but it means the mistake surfaces later, as an unsatisfied `HasField` bound at -a wiring site rather than as a complaint on the struct. +**A unit struct does not generate field-access implementations.** The derive succeeds, but a later +field read reports an unsatisfied `HasField` bound. -**Two spellings of a field name are unrelated types.** `Symbol!("first_name")` and `Symbol!("firstName")` -have nothing to do with each other, and a mismatch is reported as a missing `HasField` bound rather than -as a typo. This is the usual cause of a read that "should" work. +**Field tags must match exactly.** `Symbol!("first_name")` and `Symbol!("firstName")` are different +types. A spelling mismatch produces an unsatisfied `HasField` bound. **A raw-identifier field is tagged without the `r#`.** The tag for `r#type` is `Symbol!("type")`, so `Symbol!("r#type")` matches nothing. @@ -273,9 +262,8 @@ as a typo. This is the usual cause of a read that "should" work. **A tuple field is keyed by `Index`, never by a `Symbol!` of the number.** `Index<0>` and `Symbol!("0")` are different types, and only the first is generated. -**The mutable accessor is always generated.** There is no way to derive read-only access. If a field must -not be mutated by an implementation, that is a matter of what the implementations declare rather than -something this derive can restrict. +**The mutable accessor is always generated.** The derive does not offer a read-only mode. Limit +mutation through the access bounds and references supplied to implementations. **It does not accept an enum.** `#[derive(HasField)]` parses a struct. The plural [`#[derive(HasFields)]`](./derive_has_fields.md) is the one that takes both, and the near-identical names @@ -283,6 +271,8 @@ are easy to confuse. ## Related constructs +These references cover the related derives, generated traits, and supporting types: + - [`#[derive(HasFields)]`](./derive_has_fields.md) — the whole-shape counterpart, commonly derived alongside this one. - [`HasField`](../traits/field-access/has_field.md) — the trait this generates, with `HasFieldMut` and the provider-side @@ -296,7 +286,7 @@ are easy to confuse. - [`ChainGetters`](../providers/chain_getters.md) — reaching a field on a nested context. - [`#[derive(CgpData)]`](./derive_cgp_data.md) — the umbrella derive, which includes this one. -The ideas behind it: +The ideas behind it are explained on these concept pages: - [Impl-side dependencies](/docs/concepts/impl-side-dependencies) — why a field requirement belongs on the implementation rather than in the interface. @@ -304,6 +294,8 @@ The ideas behind it: ## Source +The implementation is defined in these source files: + - Entry point: [`derive_has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_has_field.rs) - Codegen: [`cgp_data/derive_has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_field.rs) - Traits: [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index eb8b4e83..87cd699a 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -5,18 +5,17 @@ sidebar_position: 2 # `#[derive(HasFields)]` -The whole-struct or whole-enum field-list view. +`#[derive(HasFields)]` generates a structural representation and conversions for a struct or enum. ## Overview -Some code needs one field of a type. Other code needs the *shape* of the type: every field, its name, -and its type, so it can walk them. A serializer, a validator, a builder that merges two structs, a -dispatcher that routes an enum to a handler per variant: none of these can be written against one field -at a time, and none of them can name the concrete type either. +Generic serializers, validators, record conversions, and enum dispatchers need a description of the +whole type. Individual field access does not tell them which fields or variants exist or how to +traverse them. -`#[derive(HasFields)]` gives a type that shape as a single associated type. Where -[`#[derive(HasField)]`](./derive_has_field.md) (singular) answers "give me *this* field", `HasFields` -answers "describe *all* of them at once": +`#[derive(HasFields)]` describes that structure through a single associated type, `Fields`. +[`HasField`](./derive_has_field.md) supplies access to one field selected by a tag; `HasFields` +describes all fields together, for example: ```rust type Fields = Product![ @@ -25,20 +24,17 @@ type Fields = Product![ ]; ``` -That is the whole struct written as a type: a [`Product!`](../macros/product.md) list with one -[`Field`](../types/field.md) entry per field, each pairing a value type with its type-level name. For an -enum it is a [`Sum!`](../macros/sum.md) instead: the same idea for a choice rather than a combination. -Code that is generic over the shape recurses over that list, and everything is resolved during -compilation. +A struct's representation combines its fields in a [`Product!`](../macros/product.md), with a +[`Field`](../types/field.md) entry pairing each value type with its tag. An enum uses a +[`Sum!`](../macros/sum.md) to represent a choice of variants. Generic code can recurse over these +representations, whose types are resolved during compilation. -The derive also generates the conversions that move values in and out of the representation, so it works -in both directions rather than only describing the type. Generic code can take a concrete value apart -into its anonymous shape, work on it, and put a concrete value back together. +The derive also supplies conversions to and from the representation. Generic code can decompose a +concrete value, process its structural form, and reconstruct the concrete type. ## Usage -The macro is a plain derive that takes no arguments and has no helper attributes. Unlike the singular -derive it accepts **both structs and enums**: +Apply `HasFields` to a struct or enum without arguments or helper attributes: ```rust #[derive(HasFields)] @@ -61,31 +57,24 @@ compile error. ### Struct shapes -Every struct shape is accepted, and three of the four behave as you would predict from the field tags -alone. +Every struct shape is accepted, with its representation determined by its fields: -- A **named-field struct** becomes a product of `Field` entries, in declaration order. -- A **multi-field tuple struct** becomes a product keyed by `Index`. -- A **unit struct** becomes the empty product `Nil`. A fieldless struct is a valid, if trivial, record and - round-trips through the representation like any other. -- A **single-field tuple struct** (a newtype) is the special case: its `Fields` is the inner type - *directly*, not wrapped in a one-element product. +- **Named fields:** a product of `Field` entries in declaration order. +- **Multiple tuple fields:** a product with fields keyed by `Index`. +- **Unit struct:** the empty product `Nil`, with conversions to and from the unit value. +- **Single tuple field (newtype):** the inner type directly, without a one-element product wrapper. -The newtype case is worth noting, because it is the one that will surprise you. `struct Wrapper(String)` -has `Fields = String`, not `Product![Field, String>]`. The reason is that a newtype is a -transparent wrapper and generic code almost always wants the inner type rather than the wrapper. The -practical effect is that adding a second field to a newtype changes its `Fields` type in shape rather -than in length. +Adding a second field to a newtype changes the kind of representation. `struct Wrapper(String)` has +`Fields = String`; a tuple struct with multiple fields has a product of indexed entries. Generic code +that depends on the original representation must account for that change. ### Variant shapes -**This is the one derive in the extensible-data family that places no restriction on an enum's variant -shapes.** The derives that take an enum *apart* (that is, -[`#[derive(ExtractField)]`](./derive_extract_field.md) and -[`#[derive(FromVariant)]`](./derive_from_variant.md), and therefore -[`#[derive(CgpData)]`](./derive_cgp_data.md)) require every variant to carry exactly one unnamed payload, -because each has to name a single type per variant. `HasFields` only *describes* a variant, so it accepts -all four shapes and nests that variant's own fields as a product inside its `Field` entry: +`HasFields` accepts unit, newtype, multi-field tuple, and named-field variants. Its representation +applies the struct field rules within each variant. In contrast, the per-variant constructor and +extractor derives ([`FromVariant`](./derive_from_variant.md) and +[`ExtractField`](./derive_extract_field.md), also included by [`CgpData`](./derive_cgp_data.md)) +require exactly one unnamed payload per variant. ```rust #[derive(HasFields)] @@ -97,7 +86,7 @@ pub enum Shape { } ``` -Each variant maps by the same rules a struct's fields do: +The variants above map to these entries in the sum: | Variant | Its entry in the sum | |---|---| @@ -106,14 +95,13 @@ Each variant maps by the same rules a struct's fields do: | `Rectangle(u32, u32)` | `Field, u32>, Field, u32>]>` | | `Triangle { base, height }` | `Field, Field]>` | -So a unit variant becomes the empty product, a newtype variant passes its payload straight through (the -same special case as a newtype struct, applied inside a variant), a multi-field tuple variant becomes an -`Index`-keyed product, and a named-field variant becomes a `Symbol!`-keyed one. All four round-trip -through the conversions. +Every listed shape supports conversion to and from the representation. A unit variant uses `Nil`, a +newtype variant uses its payload type directly, and multi-field variants use products keyed by +position or name. -The consequence is worth stating plainly, because it decides which derive to reach for: **an enum with -mixed variant shapes can have a structural representation but no generic constructor or extractor.** -`#[derive(HasFields)]` succeeds on the enum above; `#[derive(CgpData)]` on the same enum would not. +An enum with mixed variant shapes can derive `HasFields` but cannot derive `CgpData`. It gains a +structural representation and whole-value conversions without per-variant constructors or an +incremental extractor. ### Generic types @@ -147,7 +135,7 @@ let fields = config.to_fields(); // Config -> the product let config_again = Config::from_fields(fields); // the product -> Config ``` -There is a borrowing form too, used by read-only generic code so it does not have to consume the value: +`to_fields_ref()` borrows the fields so generic code can read them without consuming the value: ```rust let config = Config { host: "localhost".to_owned(), port: 8080 }; @@ -167,39 +155,34 @@ pub enum Shape { `Shape::Fields` is `Sum![Field, Field]`. -Generic code binds on the shape rather than on the type. An implementation that works for any record -writes `where Self: HasFields` and recurses over `Self::Fields`, so it applies to `Config`, to `Person`, -and to a struct declared in another crate that happens to derive the same thing. +Generic code can operate on `Self::Fields` under a `Self: HasFields` bound. An implementation that +supports the resulting representation can work with `Config`, `Person`, or a struct in another crate +that supplies the same traits. ## When to use it -**Reach for `#[derive(HasFields)]` when code must process a type's whole shape, and for -[`#[derive(HasField)]`](./derive_has_field.md) when it needs one named field.** That is the whole -distinction, and the two are complementary rather than ranked. Most types that need both derive both, in -one `#[derive(...)]`. - -The finer question is whether to derive it on its own or take the umbrella. - -- **Derive `HasFields` alone** when the type only needs to be *described* and converted: a payload being - serialized, a struct being read structurally, an enum whose shape a dispatcher inspects. This is also - the only choice available for an enum with mixed variant shapes. -- **Reach for [`#[derive(CgpData)]`](./derive_cgp_data.md)** when the type also needs to be built up field - by field or taken apart variant by variant, since that derive includes this one plus the incremental - machinery. If you find yourself deriving `HasFields`, `HasField`, and - [`BuildField`](./derive_build_field.md) together, the umbrella is the shorter way to say it. -- **Do not derive it speculatively.** It generates five impls and a representation type per use, and a - type nothing processes structurally gains nothing from having a shape. Deriving `HasField` for value - reads is the far more common need. - -One misreading to head off: **this is not runtime reflection.** A type has a shape only because it opted -in with a derive, there is nothing to query at runtime, and the shape is a type rather than data. The -gain is that generic code over it is checked when written and costs nothing when run. The cost is that a -type you do not own and cannot patch has no shape at all. +Use `HasFields` when code must process a type's whole structure. Use +[`HasField`](./derive_has_field.md) for access to an individual field. Derive both when both forms of +access are needed. + +Choose the extent of the generated support according to the operations you need: + +- **`HasFields` alone:** describe and convert a type for serialization, structural reads, or dispatch. + This also supports enums with mixed variant shapes. +- **[`CgpData`](./derive_cgp_data.md):** include incremental building or extraction alongside the + representation. For structs, it also includes per-field access. +- **[`HasField`](./derive_has_field.md) alone:** read individual fields when the whole representation + is unnecessary. `HasFields` generates five implementations, so omit it when nothing uses them. + +The representation is a type-level description, not runtime reflection. Generic code uses trait +bounds to access the shape during compilation; it does not query field metadata at runtime. A type +must supply the representation traits before it can participate. If you cannot implement those traits +for a type, this derive cannot expose its shape. ## Under the hood -The derive leaves the type definition untouched and emits **five impls**: the shape, the borrowed shape, -and three conversions. From a named-field struct: +The derive preserves the type definition and adds implementations of `HasFields`, `HasFieldsRef`, +`ToFields`, `FromFields`, and `ToFieldsRef`. For this named-field struct: ```rust #[derive(HasFields)] @@ -209,7 +192,7 @@ pub struct Person { } ``` -the two shape impls name the product and the same product with each value borrowed: +The shape implementations name the product and its borrowed counterpart: ```rust impl HasFields for Person { @@ -229,7 +212,7 @@ impl HasFieldsRef for Person { } ``` -and the three conversions move values between `Person` and that product: +The conversion implementations move or borrow values between `Person` and that product: ```rust impl ToFields for Person { @@ -258,8 +241,8 @@ impl ToFieldsRef for Person { [type-level lists](../types/index.md) page covers that shape, and it is the form printed in an error. -An enum's shape is the dual: an [`Either`](../types/either.md) chain terminated by `Void` -rather than a `Cons` chain terminated by `Nil`, with each arm tagged by the variant name: +An enum's sum representation is an [`Either`](../types/either.md) chain terminated by `Void`. +Each arm carries a field tagged by the variant name: ```rust impl HasFields for Shape { @@ -270,12 +253,11 @@ impl HasFields for Shape { } ``` -The conversions match each concrete variant onto its arm and back. The four variant shapes described -above all fall out of one rule rather than being special-cased: each variant's own fields go through the -same product construction a struct's fields do, which is why a unit variant lands on `Nil`, a newtype -variant on its payload type, and the two multi-field shapes on `Index`- and `Symbol!`-keyed products. +The enum conversions map each variant to its corresponding sum arm and back. Each variant's payload +representation follows the struct rules: `Nil` for a unit variant, the payload itself for a newtype +variant, or a product keyed by `Index` or `Symbol!` for multiple fields. -The empty shapes come from the same construction. A unit struct's `Fields` is `Nil`: +A unit struct uses the empty product `Nil` as its representation: ```rust impl HasFields for Unit { @@ -283,8 +265,8 @@ impl HasFields for Unit { } ``` -and a variantless enum's is `Void`, with its borrowed conversions matching the uninhabited value through -an empty `match`. +A variantless enum uses `Void` as its representation. Its conversions use empty matches because the +value is uninhabited. Each generated impl is aimed at the type name the user wrote, so a conflict with a hand-written `HasFields` impl underlines the struct or enum rather than the whole `#[derive(HasFields)]`. @@ -295,36 +277,35 @@ Each generated impl is aimed at the type name the user wrote, so a conflict with `Fields = String`. Generic code written against `Cons, _>, Nil>` will not match it, and adding a second field changes the shape rather than lengthening it. -**A named-field variant is not a newtype variant.** `Circle { radius: f64 }` carries a one-entry product, -while `Circle(Circle)` carries its payload type directly. The two read almost alike and produce different -shapes. +**Named-field and newtype variants have different representations.** `Circle { radius: f64 }` uses a +one-entry product, while `Circle(Circle)` uses its payload type directly. -**Accepting every variant shape is specific to this derive.** An enum with a unit, multi-field, or -struct-style variant takes `#[derive(HasFields)]` and rejects `#[derive(CgpData)]`, -`#[derive(CgpVariant)]`, `#[derive(ExtractField)]`, and `#[derive(FromVariant)]`. If you want the whole -family, wrap each richer payload in its own struct so every variant has a single nameable type. +**Only `HasFields` accepts every variant shape in this family.** Unit, multi-field, and struct-style +variants are rejected by `CgpData`, `CgpVariant`, `ExtractField`, and `FromVariant`. Wrap richer +payloads in dedicated structs to use those derives. -**The borrowed shape layers borrows rather than collapsing them.** A field already of type `&'a Name` -appears as `&'__a &'a Name` in the borrowed form, which is correct and occasionally surprising in an error -message. `'__a` is the reserved name the derive introduces so it cannot collide with a lifetime of yours. +**The borrowed shape adds a reference to each field's declared type.** A field of type `&'a Name` +appears as `&'__a &'a Name` in the borrowed form. The derive introduces the reserved lifetime `'__a` +for that additional borrow. **Field order is declaration order, and it is part of the type.** Two structs with the same field names in different orders have different `Fields` types. Structural conversions that match on names cope with that; code written against a literal `Cons` chain does not. -**Two variant names are reserved, and using one does not compile.** The generated impls write -`Self::Fields` and `Self::FieldsRef`, so an enum with a variant called `Fields` or `FieldsRef` makes the -path ambiguous. The compiler reports `ambiguous associated item` with its headline on the derive, and a -note pointing at the offending variant, so following the note tells you which one to rename. The -[extractor](./derive_extract_field.md) and [constructor](./derive_from_variant.md) derives reserve five -more names, so an enum taking the whole family should avoid all seven. +**Variants named `Fields` or `FieldsRef` make generated paths ambiguous.** The implementations use +`Self::Fields` and `Self::FieldsRef`, which conflict with variants of those names. The compiler +reports `ambiguous associated item` at the derive and points to the offending variant in a note. +Rename that variant. The [extractor](./derive_extract_field.md) and +[constructor](./derive_from_variant.md) derives reserve additional names, so check their restrictions +when deriving the full family. -**It is a different derive from the singular one.** `#[derive(HasField)]` gives per-field access and takes -only structs; `#[derive(HasFields)]` gives the whole shape and takes structs and enums. The names differ -by one letter and the outputs do not overlap. +**`HasField` and `HasFields` generate different interfaces.** The singular derive provides per-field +access for structs. The plural derive provides a whole-type representation for structs and enums. ## Related constructs +These references cover the related derives, generated traits, and supporting types: + - [`#[derive(HasField)]`](./derive_has_field.md) — the singular counterpart, per-field access, commonly derived alongside this one. - [`HasFields`](../traits/shape/has_fields.md) — the traits this generates and the conversions between a value @@ -340,7 +321,7 @@ by one letter and the outputs do not overlap. - [`AppendProduct`](../traits/type-level/append_product.md) — operations over a shape once you have one. - [`CanUpcast`](../traits/casting/can_upcast.md) — converting between two types whose shapes overlap. -The ideas behind it: +The ideas behind it are explained on these concept pages: - [Extensible records](/docs/concepts/extensible-records) — a struct as a product of named fields, and what generic code does with one. @@ -349,6 +330,8 @@ The ideas behind it: ## Source +The implementation is defined in these source files: + - Entry point: [`derive_has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/derive_has_fields.rs) - Codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) - Traits: [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs), diff --git a/docs/reference/derives/index.md b/docs/reference/derives/index.md index fc5b6c6c..2e3e7f06 100644 --- a/docs/reference/derives/index.md +++ b/docs/reference/derives/index.md @@ -5,25 +5,21 @@ sidebar_position: 0 # Derives -A derive here turns an ordinary struct or enum into data that generic CGP code can work with, without -that code ever naming the concrete type. Each one generates trait impls beside the type rather than -changing the type itself, so a struct stays an ordinary struct and gains the machinery alongside it. -This page groups every derive in this section by the job it does, in roughly the order most CGP code -reaches for them. +CGP derives let generic code access, describe, build, and deconstruct structs and enums without naming +their concrete types. Each derive adds trait implementations alongside the original type. Choose one +according to the operations your generic code needs. -If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here; this page -is the fuller map for once the essentials are familiar. +Start with the [reference overview](/docs/reference/) if you are new to CGP. This page compares the +derives once you are familiar with the essentials. ## Reading a value from a context -The two field-access derives are the ones nearly every CGP program uses. +Use `HasField` to access individual fields and `HasFields` to process a type's whole structure. -[`#[derive(HasField)]`](./derive_has_field.md) is the foundational one, and usually the first derive -anyone writes. It gives each field a type-level name, so an implementation can ask for a field by name as -a trait bound and read it without knowing the concrete type. Every ergonomic value read stands on it: an +[`#[derive(HasField)]`](./derive_has_field.md) lets an implementation read a struct field by a +type-level tag. The implementation declares the field it needs as a trait bound. An [`#[implicit]`](../attributes/implicit.md) argument and a -[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method both generate a `HasField` bound from a name -you already wrote. +[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method generate that bound from the field name. [`#[derive(HasFields)]`](./derive_has_fields.md) gives the whole shape instead of one field: the struct or enum described as a single type-level list, plus the conversions that move values in and out of it. @@ -32,34 +28,35 @@ two records. It is often derived alongside `HasField`. ## Turning a type into extensible data -These three derives add the machinery for building a value up field by field, or taking one apart variant -by variant, with the progress tracked in the type so the compiler checks it. Each includes the field -access and representation above and adds the incremental half on top. +The extensible-data derives combine a structural representation with incremental operations checked +by the compiler. Structs gain per-field access and a builder; enums gain constructors and an extractor +that handles variants individually. -[`#[derive(CgpData)]`](./derive_cgp_data.md) is the umbrella and the default. On a struct it emits the -record machinery; on an enum, the variant machinery. Use it unless you have a reason to name the shape. +[`#[derive(CgpData)]`](./derive_cgp_data.md) is the default when you need the full set of operations. +It generates the record implementations for a struct and the variant implementations for an enum. -[`#[derive(CgpRecord)]`](./derive_cgp_record.md) is the struct-only face, and -[`#[derive(CgpVariant)]`](./derive_cgp_variant.md) the enum-only face. Each emits exactly what `CgpData` -emits for that shape and rejects the other shape at parse time, so a type that is meant to stay one kind -says so and a wrong shape fails at the derive. +[`#[derive(CgpRecord)]`](./derive_cgp_record.md) accepts only structs, and +[`#[derive(CgpVariant)]`](./derive_cgp_variant.md) accepts only enums. Each emits the same output as +`CgpData` for its accepted shape. Use the specific name to document that constraint and reject a +different input shape at the derive. ## Deriving one slice on its own -Each half of the extensible-data output is also available as its own derive, for a type that needs only -part of the machinery. +Use an individual derive when generic code needs only construction or extraction. -[`#[derive(BuildField)]`](./derive_build_field.md) is the record builder alone: assemble a struct one -field at a time, from code that does not know the whole struct. [`#[derive(ExtractField)]`](./derive_extract_field.md) -is the enum extractor alone: take an enum apart one variant at a time, with a provably exhaustive end. -[`#[derive(FromVariant)]`](./derive_from_variant.md) is the variant constructors alone: build an enum -from a variant chosen by name. The first belongs to structs; the last two belong to enums and are -commonly derived together. +The individual derives provide these operations: + +- [`#[derive(BuildField)]`](./derive_build_field.md): assemble a struct one field at a time. +- [`#[derive(ExtractField)]`](./derive_extract_field.md): handle enum variants one at a time, with + compile-time exhaustiveness checking. +- [`#[derive(FromVariant)]`](./derive_from_variant.md): construct an enum from a variant selected by name. + +`BuildField` accepts structs. `ExtractField` and `FromVariant` accept enums and are commonly derived +together. ## One restriction to know before you reach for them -The derives that take an enum apart, `#[derive(ExtractField)]` and `#[derive(FromVariant)]` and therefore -`#[derive(CgpData)]` and `#[derive(CgpVariant)]`, require every enum variant to carry exactly one unnamed -payload, with no per-variant opt-out. `#[derive(HasFields)]` is the exception: it only describes a -variant, so it accepts every variant shape, which makes it the derive an enum with mixed variants can -still use. +The enum constructor and extractor derives require every variant to carry exactly one unnamed +payload. This restriction applies to `FromVariant`, `ExtractField`, `CgpData`, and `CgpVariant`; +individual variants cannot opt out. `HasFields` accepts every variant shape and provides a structural +representation with whole-value conversions, so it can be used with enums that mix variant shapes. \ No newline at end of file From 5096d79d622aa4f1d68b65f0b187cb329d84ab38 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 14 Sep 2026 09:04:50 +0000 Subject: [PATCH 068/516] Move cgp-skills submodule --- .gitmodules | 2 +- docs/ai/skills/cgp-skills => cgp-skills | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename docs/ai/skills/cgp-skills => cgp-skills (100%) diff --git a/.gitmodules b/.gitmodules index dace63f4..6871eb40 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "cgp-skills"] - path = docs/ai/skills/cgp-skills + path = cgp-skills url = https://github.com/contextgeneric/cgp-skills.git diff --git a/docs/ai/skills/cgp-skills b/cgp-skills similarity index 100% rename from docs/ai/skills/cgp-skills rename to cgp-skills From 7dcf7c70c409241dec0863cf8f0a000b68b8539c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 14 Sep 2026 09:05:35 +0000 Subject: [PATCH 069/516] Update cgp-skills --- cgp-skills | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgp-skills b/cgp-skills index 82caa3d4..80cbf512 160000 --- a/cgp-skills +++ b/cgp-skills @@ -1 +1 @@ -Subproject commit 82caa3d40149dcb3d8ddebd4b3ce2c66ad5069bf +Subproject commit 80cbf5123fa2b27717953d0a3fec38ccdafbafe6 From 3c765c261ebeee5d85c42bd74e8816a70f2349a5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 14 Sep 2026 09:12:16 +0000 Subject: [PATCH 070/516] Link to cgp-skills --- docs/ai/skills/SKILL.md | 1122 +---------------- docs/ai/skills/references/abstract-types.md | 168 +-- docs/ai/skills/references/checking.md | 210 +-- docs/ai/skills/references/components.md | 258 +--- docs/ai/skills/references/error-extraction.md | 89 +- docs/ai/skills/references/error-handling.md | 139 +- docs/ai/skills/references/extensible-data.md | 164 +-- .../references/functions-and-getters.md | 315 +---- docs/ai/skills/references/handlers.md | 267 +--- .../references/higher-order-providers.md | 162 +-- docs/ai/skills/references/macro-grammar.md | 342 +---- docs/ai/skills/references/modern-idioms.md | 285 +---- .../skills/references/modularity-hierarchy.md | 205 +-- docs/ai/skills/references/namespaces.md | 174 +-- .../references/type-level-primitives.md | 207 +-- docs/ai/skills/references/wiring.md | 195 +-- 16 files changed, 16 insertions(+), 4286 deletions(-) mode change 100644 => 120000 docs/ai/skills/SKILL.md mode change 100644 => 120000 docs/ai/skills/references/abstract-types.md mode change 100644 => 120000 docs/ai/skills/references/checking.md mode change 100644 => 120000 docs/ai/skills/references/components.md mode change 100644 => 120000 docs/ai/skills/references/error-extraction.md mode change 100644 => 120000 docs/ai/skills/references/error-handling.md mode change 100644 => 120000 docs/ai/skills/references/extensible-data.md mode change 100644 => 120000 docs/ai/skills/references/functions-and-getters.md mode change 100644 => 120000 docs/ai/skills/references/handlers.md mode change 100644 => 120000 docs/ai/skills/references/higher-order-providers.md mode change 100644 => 120000 docs/ai/skills/references/macro-grammar.md mode change 100644 => 120000 docs/ai/skills/references/modern-idioms.md mode change 100644 => 120000 docs/ai/skills/references/modularity-hierarchy.md mode change 100644 => 120000 docs/ai/skills/references/namespaces.md mode change 100644 => 120000 docs/ai/skills/references/type-level-primitives.md mode change 100644 => 120000 docs/ai/skills/references/wiring.md diff --git a/docs/ai/skills/SKILL.md b/docs/ai/skills/SKILL.md deleted file mode 100644 index d4002383..00000000 --- a/docs/ai/skills/SKILL.md +++ /dev/null @@ -1,1121 +0,0 @@ ---- -name: cgp -description: >- - Read, write, debug, and explain Context-Generic Programming (CGP) code in Rust. - Use this skill whenever you encounter or are asked to work with CGP — any code that - uses `cgp::prelude::*`, the `#[cgp_component]`, `#[cgp_impl]`, `#[cgp_provider]`, - `#[cgp_fn]`, `#[cgp_type]`, `#[cgp_getter]`, `#[cgp_auto_getter]`, `#[cgp_computer]`, - `#[cgp_producer]`, or `cgp_namespace!` macros, the `delegate_components!`, - `check_components!`, or `delegate_and_check_components!` macros, the `Symbol!`, - `Product!`, `Sum!`, or `Path!` type-level macros, the `HasField`/`HasFields` traits or - their derives, providers such as `UseContext`/`UseDelegate`/`UseField`/`UseType`, the - handler family (`Computer`/`Producer`/`Handler`), or terms like consumer trait, - provider trait, provider, wiring, impl-side dependency, or context-generic. Trigger it - even when the user does not say "CGP" by name but is clearly working with these - constructs, when a Rust trait error mentions `IsProviderFor`/`DelegateComponent`, or - when someone wants modular, dependency-injected, multiple-implementation Rust traits. ---- - -# Context-Generic Programming (CGP) in Rust - -CGP is a modular programming paradigm for Rust that works around the language's coherence -restrictions, letting you write many overlapping or "orphan" trait implementations and then -choose which one applies by **wiring** them onto a concrete context type. This file is a -self-contained primer: read it top to bottom and you hold the whole mental model — every core term, -the shape of every construct, and enough of each expansion to read, write, and debug the majority of -CGP code. It is longer than a typical skill on purpose, because CGP's surface is broad and an agent -who stops here should still be competent, not lost. - -**This primer is the map, not the territory — load the sub-skill before you act on any construct it -covers.** The primer gives you the shape of each construct; the `references/` sub-skills give you the -exact grammar, the full expansion, the corner cases, and the worked examples that keep you from -writing subtly wrong code. The gap between the two is where mistakes live: the primer tells you -`#[cgp_impl]` writes a provider, but [components](references/components.md) tells you what `self` -rewrites to, [macro-grammar](references/macro-grammar.md) tells you which attribute forms parse, and -only reading them stops you from emitting an impl that fails to compile in a way the error message -will not explain. So before you write, modify, review, or debug code using a construct — even one -that looks simple — **open the sub-skill that owns it.** Each entry in [the sub-skill -index](#sub-skills-load-the-one-that-owns-your-task) below says exactly what it adds beyond this -primer, so you can tell what you would be guessing at without it. Treat "I already read the primer" -as insufficient: the primer is calibrated to make you *know what you do not know*, and the sub-skill -is where that gap is closed. - -CGP is implemented almost entirely as procedural macros. Every macro desugars to ordinary Rust -traits and impls, so the reliable way to understand any construct is to know the code it expands -to. This primer shows those expansions where they matter and keeps them out of the way where they -do not. - -## Tooling: use cargo-cgp for readable errors and expansions - -**Before debugging any CGP compile error, use `cargo-cgp` if it is available.** It has two commands -you will want: `check`, which reshapes the errors, and -[`expand`](#reading-what-a-macro-generated-cargo-cgp-expand), which shows the code the macros generated. `cargo-cgp` is CGP's -first-class toolchain — a cargo subcommand that stands in for `cargo check` and rewrites CGP's -compiler errors into a compact, root-cause-first form, tagging each rewritten message with a -`[CGP-Exxx]` code. A raw CGP error is often a wall of generated types with the real cause buried or -hidden entirely; `cargo-cgp` names the cause and renders the dependency chain that leads to it. -Recommend it to the user for building and checking CGP code, and prefer it over plain `cargo check` -whenever a wiring failure needs diagnosing. - -**Check whether it is installed** with `cargo cgp --version` (or just run `cargo cgp check` in a CGP -project). If the subcommand is missing, it is not installed. - -**If it is not installed, recommend installing it** — tell the user it makes CGP errors far more -readable — and **install it on their behalf only with their approval**, since it provisions a nightly -toolchain and builds a compiler-linked driver (heavy). - -**Prefer the cargo path**, which is the default for almost every machine: `cargo install cargo-cgp` -then `cargo cgp setup` (the first installs the small front-end on whatever toolchain is present; -`setup` provisions the pinned nightly and builds the matching driver in lockstep). It needs rustup. - -**Reach for Nix only if the host actually has it** — a `nix` command on `PATH` or a `flake.nix` in the -project — or if the user explicitly asks for it; otherwise do not bring Nix up at all. When Nix *is* -present but cargo-cgp is not installed, the lightest move is to **not install** and instead run the -tool through the flake from the project directory: -`nix run github:contextgeneric/cargo-cgp/v0.1.0-alpha -- check` (arguments after `--` go to -`cargo check`). To install into a Nix profile instead, use -`nix profile install github:contextgeneric/cargo-cgp/v0.1.0-alpha`. - -cargo-cgp requires a specific pinned Rust nightly, installed by `cargo cgp setup` (or built by the -Nix flake), and forces it only for its own check, so the user's project keeps its own toolchain -untouched. Full instructions: -. - -**Using it:** run it wherever you would run `cargo check` (arguments after `check` are forwarded): -`cargo cgp check`, `cargo cgp check --workspace`. It keeps rustc's own error code and adds a -`[CGP-Exxx]` tag, leading with the root cause over a `cargo tree`-style dependency chain; the codes -are catalogued at -. - -### Reading what a macro generated: `cargo cgp expand` - -**When a CGP error stops making sense, read the code the macros produced rather than reasoning about -what you think they produce.** A wiring failure is always "the emitted impls do not resolve," and the -impls are generated, so the fastest way past a confusing diagnostic is often to look at them. -`cargo cgp expand` prints the crate after macro expansion, with CGP's type-level constructs -**resugared** — a field tag reads `Symbol!("width")`, not the raw `Symbol<5, Chars<'w', …>>` -spine the compiler prints; a pipeline reads `Product![StepOne, StepTwo]`; a namespace key reads -`Path!(@app.GreeterComponent)` — so the generated code is legible in the same vocabulary as the -source. - -Reach for it in four situations, each one where the answer is in the generated code rather than in the -message: - -- **A diagnostic names a type you did not write** (`IsProviderFor<…>`, a `PathCons<…>` key, a - `__Context__` parameter) and you need to see the impl it came from. -- **A wiring table does not resolve** and you want the real `DelegateComponent` keys and `Delegate` - values it produced, rather than inferring them from the table's syntax. -- **You are unsure what a construct emits** — the exact `where` clauses of a provider impl, whether a - getter's blanket impl requires the field you think it does. Reading the expansion beats guessing, and - beats trusting a remembered expansion. -- **Two forms differ and only one compiles.** Expand both and diff; the delta is the bug. - -Run it on one target, narrowed to what you care about: - -```sh -cargo cgp expand --lib # the whole library target -cargo cgp expand --lib --item contexts::MockApp # one module, type, or trait -``` - -**Target selection is required when a package has several targets** — pass `--lib` or `--bin NAME`, or -cargo declines with "extra arguments to `rustc` can only be passed to one target". Other arguments -(`-p`, `--features`) forward to `cargo rustc`, and the expansion goes to stdout, so redirect it to a -file when it is long and read that instead of flooding your context. - -**`--item ` is what makes the output manageable**, and which of three rules applies depends on -what the path names. The path is `::`-separated, may carry a leading `crate::`, and names something -inside the crate being expanded: - -- a **module** → its contents (`--item contexts`); -- a **type** → its declaration and every impl written *for* it. For a context that is its struct, the - `HasField`/`HasFieldMut` impls the derive generated, and its `DelegateComponent` wiring entries with - the real key and provider types (`--item Rectangle`); -- a **trait** → its definition and every impl *of* it, which is usually the rule you want. Naming a - component's *provider* trait (`--item AreaCalculator`) gives the provider trait, the delegation - blanket impl, the `UseContext` and `RedirectLookup` impls, and each wired provider's impl; naming the - *consumer* trait (`--item CanCalculateArea`) gives just the consumer trait and its routing blanket. - -Two limits matter when you read the output. **`expand` is not a check**: it stops once the macros are -expanded, so it reports nothing about wiring — use `cargo cgp check` for that, and expect `expand` to -succeed even on a crate that does not type-check (which is exactly what makes it useful mid-debugging). -And the output is for reading, not compiling: the `cgp::macro_prelude::` qualifier is stripped, and an -`open` statement's per-key entry keeps its raw `PathCons<…>` key. - -One availability note: `expand` is newer than cargo-cgp v0.1.0-alpha, so a crates.io install does -not carry it yet. Until the next release it comes from the Nix flake without a tag -(`nix run github:contextgeneric/cargo-cgp -- expand --lib`) or from a source checkout; see -. - -**Scope:** cargo-cgp is optional and adds only `check` and `expand` — there is no -`cargo cgp build`/`run`/`test`, so build, run, and test the project with plain cargo. CGP itself -compiles on any **stable Rust ≥ 1.89**, so plain `cargo check` works on a CGP project too; reach for -`cargo cgp check` specifically when you hit or expect a wiring error and want it made readable. - -`cargo-cgp` can also be Rust Analyzer's on-save check backend, via -`rust-analyzer.check.overrideCommand` set to -`["cargo","cgp","check","--workspace","--all-targets","--message-format=json"]`. But **never modify -the user's Rust Analyzer settings implicitly** — mention this option and let them opt in, and only -edit their editor configuration when they explicitly ask you to. - -**When cargo-cgp is not available, or leaves an error largely unrewritten**, fall back to reading the -raw compiler output by hand — and only then load the [error-extraction sub-skill](references/error-extraction.md), -the technique for reducing a raw CGP cascade to its root cause. When cargo-cgp *has* reshaped the -error, its `[CGP-Exxx]` headline and root-cause tree are already the compact summary that sub-skill -would produce, so you do not need it. - -### Versions and keeping this skill current - -This skill is written for **CGP v0.8.0** and **cargo-cgp v0.1.0-alpha**. Check both on the host and -act on a mismatch: - -- Read the user's `cgp` version (its `Cargo.toml`/`Cargo.lock` entry) and run `cargo cgp --version` - for the tool. -- **If either is older than recorded here**, recommend updating it — `cargo update -p cgp` for the - library, `cargo cgp update` (or a Nix flake refresh) for the tool — so its behavior matches this - skill. -- **If the host's `cgp` is *newer* than v0.8.0**, this skill is behind the library: tell the user the - **skill should be upgraded** to match their `cgp`, rather than changing their code to fit an older - skill. Treat the newer `cgp` as authoritative and flag the gap instead of guessing. - -## The problem CGP solves - -Rust's coherence rules permit at most one implementation of a trait for a given type, and forbid -implementing a foreign trait for a foreign type (the orphan rule). This makes it hard to offer -several interchangeable implementations of one interface, or to let a downstream crate choose an -implementation for a type it does not own. CGP sidesteps both limits with a two-trait split: an -implementation is written against a **provider trait** whose `Self` is a dummy marker type the -crate owns, so coherence never blocks it, and a concrete **context** type later picks which -provider it uses through a small type-level table. The choice is local to the context, so two -different contexts can wire the same interface to different implementations. - -## Blanket traits and impl-side dependencies - -CGP grows out of blanket trait implementations (extension traits), and the single most important -idea to internalize is the **impl-side dependency**: a blanket impl can require constraints in its -`where` clause that are *not* part of the trait interface. Those hidden requirements are the -paradigm's form of dependency injection. For example: - -```rust -pub trait CanGreet { - fn greet(&self); -} - -pub trait HasName { - fn name(&self) -> &str; -} - -impl CanGreet for Context -where - Context: HasName, -{ - fn greet(&self) { - println!("Hello, {}!", self.name()); - } -} -``` - -`CanGreet` hides its `HasName` dependency inside the blanket impl, so a caller that is itself -generic does not have to forward `HasName` the way it would with a free generic function. In CGP -you typically start by writing generic logic as a blanket trait like this, and promote it to a -full CGP component later only when you need more than one implementation. Blanket traits are not -themselves CGP components, but the technique recurs throughout CGP. - -## The core vocabulary - -CGP code is readable once you hold five terms in mind. A **consumer trait** is the ordinary, -`self`-style trait you call (`CanGreet`, `CanCalculateArea`); it reads as a verb (`CanDoX`). A -**provider trait**, generated by `#[cgp_component]`, is the same interface with `Self` moved to an -explicit `Context` generic parameter (`Greeter`, `AreaCalculator`); it reads as -a noun (`SomethingDoer`, or `…Provider` when no noun fits). A **provider** is a zero-sized marker -struct (e.g. `GreetHello`, `RectangleArea`) that implements a provider trait — it carries no -runtime value and exists only as a name at the type level. **Wiring** is the act of telling a -context which provider implements each component, recorded in a type-level table. An -**impl-side dependency** is a `where`-clause constraint a provider needs but the consumer trait -does not expose. A **component** is the whole bundle a macro generates: consumer trait, provider -trait, and a `…Component` marker type that keys the wiring table. - -The duality is the crux: a consumer trait is what you *use*, a provider trait is what you -*implement*, and the macro-generated blanket impls connect them so that wiring a context to a -provider makes the context implement the consumer trait. When you see a provider trait method take -`context: &Context` where the consumer took `&self`, that is the same method — `self` became -`context`. - -**"Context" covers two situations that look alike and behave very differently, and this is the most -common place a reader's model of CGP breaks.** A **value context** is a context that *is* the data the -capability operates on — the `String` in `String: CanEncode`, the `Rectangle` in -`Rectangle: CanCalculateArea`. An **environmental context** is a type that exists to supply choices and -capabilities rather than to be operated on: an application, a test harness, a service. It is the far more -common kind in real CGP code, and it frequently has no fields at all — `struct App;` is a complete -context, because its whole job is to be a name the wiring table hangs off. Both sit in the `Self` position -and both carry a wiring table, so nothing in a signature distinguishes them. - -A second, independent distinction describes the **component** rather than its context. A component is -**self-targeted** when the capability is about the `Self` type (`CanGreet`, `HasErrorType`, every getter), -and **parameter-targeted** when it is about a type parameter while `Self` only decides -(`CanEncodeValue`, `CanCalculateArea`). A parameter alone does not settle it: in -`CanCompute` the target is `Input` while `Code` is a *selector* the wiring dispatches on, and -a component may carry both. Which pair a capability uses decides how many independent choices are -available — a self-targeted component wired on a foreign value type gets one provider program-wide, while -an environmental context can be defined as many times as needed — and -[modularity-hierarchy](references/modularity-hierarchy.md) works out which to reach for. **When you -explain CGP to a user, say which arrangement the example is in**, because moving from a value context to -an environmental one changes no signature and readers otherwise lose track of what a context is. - -A persistent source of confusion to avoid: inside a provider, `self`/`Self` (in `#[cgp_impl]`) or -the `context`/`Context` parameter (in the raw provider-trait form) always refer to the **context**, -never to the provider struct. The provider struct is a pure type-level name with no fields and no -runtime value — you cannot store state in it, and any attempt to read a "field" of a provider at -runtime is a mistake. - -## Reading CGP code on sight - -To follow most CGP code you only need to recognize a handful of shapes: - -- `#[cgp_component(Greeter)] trait CanGreet { fn greet(&self); }` defines a component. `CanGreet` - is the consumer trait you call; `Greeter` is the provider trait implementations target; - `GreeterComponent` is the wiring key. -- `#[cgp_impl(new GreetHello)] #[uses(HasName)] impl Greeter { fn greet(&self) { … } }` writes a - provider named `GreetHello` for the `Greeter` component. Inside, `self`/`Self` mean the - *context*, and `#[uses]` lists the impl-side dependencies — it desugars to `where Self: HasName`, - which is the form you read in older code. -- `#[cgp_fn] fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { … }` - defines a single-implementation capability as a blanket-impl trait, pulling `width`/`height` from - the context's fields automatically. -- `delegate_components! { Person { GreeterComponent: GreetHello } }` wires the `Person` context: it - says "for the `Greeter` component, `Person` uses the `GreetHello` provider." After this, `Person` - implements `CanGreet`. -- `check_components! { Person { GreeterComponent } }` is a compile-time assertion that the wiring is - complete and all transitive dependencies are satisfied. - -A consumer trait can also be implemented directly on a context like any normal Rust trait -(`impl CanGreet for Person { … }`) — CGP traits are a superset of vanilla traits, and the macros -only save boilerplate. - -## Which construct to use: prefer this, not that - -When two constructs can express the same thing, CGP has a preferred one, and choosing wrong produces -code that compiles but reads as dated or misuses an advanced tool. This table is the quick answer, so -you pick the right pattern even without reading further. Each preference is a default with narrow -exceptions, spelled out under [Writing providers](#writing-providers) below and, with full before/after -examples, in the [modern-idioms](references/modern-idioms.md) sub-skill; the "avoid" column is not -wrong, it is what you *read* in generated code and legacy wiring, not what you *write* anew. - -| To… | Prefer | Not (legacy / advanced / read-only) | -|---|---|---| -| write a provider | `#[cgp_impl]`, header `impl Trait` (omit `for Context`) | raw `#[cgp_provider]` / `#[cgp_new_provider]` | -| read a field from your own context | an `#[implicit]` argument | `#[cgp_auto_getter]` / any getter trait declared just to read it | -| declare a getter (field on *another* type, or a named shared capability) | `#[cgp_auto_getter]`, used sparingly | `#[cgp_getter]` (only for per-context field choice) | -| require a capability | `#[uses(Trait)]` | `where Self: Trait` | -| require an inner provider | `#[use_provider(P: Trait)]` | `where P: Trait` | -| name an abstract type (e.g. `Error`) | `#[use_type(Trait.Type)]` + the bare alias | `: Trait` supertrait + `Self::Type` | -| pass several args to `#[uses]` / `#[use_type]` | one attribute, comma-separated | repeating the same attribute | -| bind several inner providers with `#[use_provider]` | one attribute per provider | a comma-separated list of pairs — it does not parse | -| add a capability supertrait | `#[extend(Trait)]` | native `pub trait …: Supertrait` | -| dispatch a component per type | the `open` statement (or a namespace) | `#[derive_delegate]` + `UseDelegate` tables | -| verify a context is fully wired | separate `check_components!` (or `delegate_and_check_components!` for a basic starter context) | leaving a context's wiring unchecked | -| build a field/list/string/path type | `Symbol!` / `Product!` / `Sum!` / `Path!` sugar | hand-written `Cons`/`Nil`/`Chars`/`Either`/`PathCons` | - -Two names are gone entirely, not merely dated: never write `#[cgp_context]` (removed — assemble a -context with `delegate_components!` and the derives instead) or `ProvideType` (renamed to -`TypeProvider`). One caveat carries across the whole table: a construct's *own* local associated type -stays qualified as `Self::Output` — only an *imported* abstract type is written bare via `#[use_type]`. - -## The prelude and version - -Almost everything CGP exports comes through one import, which belongs at the top of every module -that uses CGP: - -```rust -use cgp::prelude::*; -``` - -This skill describes CGP **v0.8.0** (and cargo-cgp **v0.1.0-alpha** — see -[Tooling](#tooling-use-cargo-cgp-for-readable-errors-and-expansions) for checking both versions on the host and -reconciling a mismatch). A few names are intentionally *not* in the prelude and must be -imported from their module — most notably the error-handling wiring keys and backends (see Error -handling below). Inside documentation code blocks you may omit the prelude import for brevity. - ---- - -## Components: the heart of CGP - -A component is what `#[cgp_component]` builds from one trait so that *using* a capability and -*implementing* it become separate, swappable things. Applying it to a consumer trait: - -```rust -#[cgp_component(Greeter)] -pub trait CanGreet { - fn greet(&self); -} -``` - -generates five items, of which you write or call only the first. The **consumer trait** `CanGreet` -is emitted unchanged — callers write `person.greet()`. The **provider trait** is the same interface -with `Self` moved to a leading `Context` parameter and `self` rewritten to `context`: - -```rust -pub trait Greeter: IsProviderFor { - fn greet(context: &Context); -} -``` - -The **component marker** `pub struct GreeterComponent;` is the zero-sized key into the wiring table. -Two **blanket impls** connect the sides: one makes any context that implements the provider trait -*for itself* automatically implement the consumer trait; the other lets a context that delegates -this component (via `DelegateComponent`) inherit the provider trait from whatever provider it -delegates to. You never write these blanket impls; they are the routing machinery, and it is enough -to think of wiring as a table lookup. Crucially, that lookup is resolved **entirely at compile -time**: the table is a set of trait impls, so the compiler picks the provider during type -resolution and monomorphizes the call to a direct, statically-dispatched one. CGP wiring is -therefore zero-cost — there is no runtime table, no dynamic dispatch, and no `vtable` in the -generated code, even though "table lookup" is a useful mental model. In real generated code the -context parameter is named `__Context__` and the provider parameter `__Provider__` (reserved -identifiers chosen so they never clash with your types); the names `Context`/`Provider` here are -for readability. - -The attribute's argument sets those three generated names. The bare `#[cgp_component(Greeter)]` form -names only the provider trait; the component marker defaults to that name plus `Component` -(`GreeterComponent`) and the context to `__Context__`. A key/value form with brace delimiters -overrides any of the three — `#[cgp_component { name: GreeterComponent, provider: Greeter, context: Context }]` -— where only `provider` is required. One limitation to know: a **const generic parameter** on the -trait is rejected, because a component's extra parameters are recorded as a tuple of *types* in -`IsProviderFor` and a const value has nowhere to live there (an associated `const` *item* on the -trait is fine — it is supplied by a const-generic provider struct as usual). See -[macro-grammar](references/macro-grammar.md) for the full argument grammar and -[components](references/components.md) for the complete expansion. - -**A component trait may declare as many items as any Rust trait; what to group is the items one provider -choice decides together.** Everything in one component is answered by one provider, so items settled by one -decision belong together and items settled by different decisions do not. Most application capabilities are -one decision and so one method — which is why single-method components dominate — but a method plus the -associated type it produces is one decision too, which is why CGP's own `CanCompute` and `CanHandle` -declare `type Output` beside their method, and a getter component groups several field reads because one -`UseFields` provider answers them all by name. What costs reuse is grouping *different* decisions, as an -entity trait does (`Shape` with `area`, `perimeter`, `scale`, `rotate`): each provider then carries the -union of every method's dependencies, a higher-order provider must forward the methods it has no opinion -about, and a context needing part of the surface must still answer all of it with placeholder types and -`unimplemented!()` bodies. A consumer trait named after a noun rather than a verb is the usual sign. When -you write or review one, check that a second context could plausibly reuse one of its providers *whole*; if -not, implement the trait directly on the concrete context and skip the machinery. -[components](references/components.md) carries the two multi-item cases, the costs, and the procedure for -splitting a trait that has grown past one decision. - -### `IsProviderFor` and error messages - -`IsProviderFor` is an empty marker trait that rides as a supertrait on -every provider trait. Its only purpose is good error messages: a provider lists its dependencies in -a `where` clause, and the macros implement `IsProviderFor` for the provider under the *same* bounds, -so when a dependency is unmet the compiler can name the missing bound instead of vaguely saying "the -trait is not implemented." When you see an error that some provider does not implement -`IsProviderFor<…>`, read it as "the provider trait is not implemented, because the named dependency -is missing." You never write `IsProviderFor` yourself — the provider macros generate it. - -### Writing providers - -A provider can be written at three levels of sugar over the same machinery. **`#[cgp_impl]` is the -form to prefer**, because it lets you write the provider in consumer-style syntax — keeping `self`, -`Self`, and the consumer method signatures — and the macro rewrites it into the provider-trait -shape: - -```rust -#[cgp_impl(new GreetHello)] -#[uses(HasName)] -impl Greeter { - fn greet(&self) { - println!("Hello, {}!", self.name()); - } -} -``` - -The provider name goes in the attribute argument; a leading `new` keyword also declares the -`struct GreetHello;`. The dependency is declared with [`#[uses]`](#uses-extend-extend_where) rather than a -hand-written `where Self: HasName` clause, which is the preferred form and desugars to exactly that bound. -**Prefer the unqualified `impl Greeter` form and let the macro insert the -context parameter** — omitting `for Context` is what makes a provider read like an ordinary trait -impl. Write the explicit `impl Greeter for Context` only when you must bound or name the -context readably (for example a lifetime or HRTB the sugar cannot express); it must then be declared -in the impl generics. Remember that `self`/`Self` here mean the context. `#[cgp_impl]` desugars to: - -```rust -#[cgp_new_provider] -impl Greeter for GreetHello -where - Context: HasName, -{ - fn greet(context: &Context) { - println!("Hello, {}!", context.name()); - } -} -``` - -The lower forms are what you mostly *read* rather than write. `#[cgp_provider]` is applied to a -provider-trait impl written directly on an existing provider struct; it passes the impl through and -auto-generates the matching `IsProviderFor` impl from the same `where` clause. -`#[cgp_new_provider]` is the same but also declares the provider struct (a generic provider gets a -`PhantomData` field over its parameters, e.g. `pub struct Multiply(PhantomData);`). -The attribute argument can override the component name, which otherwise defaults to the provider -trait's name plus `Component`. One special `#[cgp_impl]` form, `#[cgp_impl(Self)]`, bypasses the -provider rewrite entirely and emits the block as a *direct* consumer-trait impl on the concrete -context (the `for Context` clause is then required) — useful when you want to implement a consumer -trait by hand while still applying companion attributes such as `#[use_provider]`. - -**Strongly prefer the modern, vanilla-looking idioms when you write CGP, and reach for the explicit -forms only when a construct genuinely cannot express the case.** Each idiom below trades a piece of -visible machinery for syntax that reads like ordinary Rust: - -- **Write providers with `#[cgp_impl]`** (not `#[cgp_provider]`/`#[cgp_new_provider]`), omitting - `for Context` so the header reads `impl Greeter`. -- **Declare dependencies with attributes, not hand-written bounds:** capability dependencies with - [`#[uses(...)]`](references/functions-and-getters.md), inner-provider dependencies with - [`#[use_provider(...)]`](references/higher-order-providers.md), instead of raw `Self:` / - `Provider: …` `where` clauses. When one of these attributes — or - [`#[use_type]`](references/abstract-types.md) — carries several arguments, put them all in one - attribute separated by commas (`#[uses(A, B)]`, `#[use_type(T.X, U.Y)]`) rather than stacking the - same attribute repeatedly; one attribute reads as a single dependency list. -- **Read context fields with [`#[implicit]`](references/functions-and-getters.md) arguments** rather - than a getter trait — this is the default for *any* field a provider reads from its own context, - including one several providers each read. An implicit argument reads only from `self` and takes a - plain `&T` by reference without cloning. Use `#[cgp_auto_getter]` sparingly, only where an implicit - argument cannot reach: a getter for a field on *another* type required as a `where` bound on it - (`Request: HasBasicAuthHeader`), an accessor other code depends on as a named capability, or a - getter carrying an associated type inferred from the field. Reserve `#[cgp_getter]` for the advanced - case of choosing the source field per context. -- **Add non-type capability supertraits with [`#[extend(...)]`](references/functions-and-getters.md)** - rather than native `: Supertrait` syntax, which reads as OOP-style inheritance rather than a - capability import. -- **Import abstract types with [`#[use_type]`](references/abstract-types.md)**, writing the bare - alias (`Scalar`, `Error`) instead of a hand-written `: HasScalarType` supertrait and a qualified - `Self::Scalar` at every use. This holds even in `#[cgp_component]` definitions: prefer - `#[use_type(HasErrorType.Error)]` over `: HasErrorType` + `Self::Error`. When a provider *pins* an - abstract type to a concrete one — a `where Self: HasErrorType` clause — express - that with the equality form `#[use_type(HasErrorType.{Error = AppError})]`, which emits the same - `Self: HasErrorType` bound; the right-hand side is substituted too, so an - imported alias is grounded wherever it appears in it — naming one outright unifies two abstract - types (`#[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})]`), - and one nested inside a type is grounded in place - (`#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits - `Self: HasTransactionType::Db>>`). The equality form is a - `#[cgp_impl]`/`#[cgp_fn]` tool — it is rejected on `#[cgp_component]`. -- **Dispatch a generic-parameter component with the `open` statement or a namespace**, skipping - `#[derive_delegate]`/`UseDelegate` when defining a new component. - -The explicit forms remain correct and are what you *read* in generated code and desugaring; the -exceptions that still need them are narrow — an associated-type-equality bound on a **non-abstract-type** -trait (`Iterator`, `From`), which `#[use_type]` cannot spell and which reads more clearly -as an explicit `where` clause than crammed into an import-shaped `#[uses]` (which now accepts it), a -lifetime or HRTB that forces a named context, or a **local** associated type such as `Self::Output`, -which stays qualified because it is the trait's own type, not an imported abstract one. Do *not* leave an -equality bound on an **abstract-type** trait (`Self: HasErrorType`) as a hand-written -`where` clause — that is exactly what the `#[use_type]` equality form `#[use_type(HasErrorType.{Error = AppError})]` -replaces; only equality on a trait you would never `#[use_type]` from stays an explicit `where`. For the full legacy-to-modern before/after mapping of each idiom — the -reference to load whenever you read or modernize existing CGP — see -[modern-idioms](references/modern-idioms.md). - -The provider's `where` clause is where **impl-side dependencies** live, whether you write it by hand or let -`#[uses]` generate it: `GreetHello` requires `Self: HasName`, but `CanGreet` exposes no such bound, so a -caller bounding on `CanGreet` never sees `HasName`. The wiring satisfies each dependency by resolving it -through the same context. - -A consumer trait is still an ordinary trait: when you don't need multiple implementations, write -`impl CanGreet for Person { … }` directly and skip the provider machinery entirely. - ---- - -## Wiring: connecting a context to providers - -Wiring records, on a context type, which provider supplies each component. The underlying mechanism -is the `DelegateComponent` trait — a type-level table whose key is the `…Component` marker and whose -`Delegate` associated type is the chosen provider — but you almost always write it through -`delegate_components!`: - -```rust -#[derive(HasField)] -pub struct Person { - pub name: String, -} - -delegate_components! { - Person { - GreeterComponent: GreetHello, - } -} -``` - -After this, `Person` implements `CanGreet` and `person.greet()` resolves through the table to -`GreetHello`. Swapping the table entry is the only change needed to swap behavior. - -The macro has a few shorthands. An **array key** maps several components to one provider: -`[FooComponent, BarComponent]: FooBarProvider`. A leading **`new`** keyword -(`delegate_components! { new MyComponents { … } }`) also defines `struct MyComponents;`, which is how -you build an **aggregate provider** — a zero-sized provider that holds a table dispatching each -component to a sub-provider, so other contexts can delegate a whole group of components to it as one -reusable unit. A leading **generic list** (`delegate_components! { MyContext { … } }`) wires a -whole family of contexts at once. - -Two further **operators** stand where the `:` does, and you will meet both when reading real wiring. -`Key -> OtherTable` forwards the key to *that table's* own entry for the same key instead of naming a -provider, and `Key => @path` redirects the lookup along a type-level path, of which the `open` -statement below is the sugared special case. Those, the `@`-path key forms, and the `namespace` and -`for` statements are the rest of one shared body grammar that `cgp_namespace!` and -`delegate_and_check_components!` reuse wholesale; [wiring](references/wiring.md) and -[macro-grammar](references/macro-grammar.md) carry it in full, and all of the forms combine inside a -single block. - -The target of `delegate_components!` is therefore not always a context: it is either a concrete -context (as `Person` is above) or an aggregate provider (as `MyComponents` is). This distinction -governs checking — an aggregate provider is dispatched *to* by contexts and is never its own context, -so it must be wired with plain `delegate_components!` and never `delegate_and_check_components!`; the -next section explains why. - -To understand what wiring *does*, picture the explicit version: `delegate_components!` is equivalent -to implementing the consumer trait by hand and forwarding to the provider — -`impl CanGreet for Person { fn greet(&self) { >::greet(self) } }`. -The macro just generates that plumbing (plus the `IsProviderFor` propagation) for you. - -### `UseContext` - -`UseContext` is a provider that implements a provider trait by routing back through the context's -*own* consumer-trait impl — the dual of the consumer blanket impl. Wiring a component to -`UseContext` means "use whatever this context already does for this trait," which is mainly useful -as the default inner provider of a higher-order provider (below). Delegating a component directly to -`UseContext` when the context's only implementation of that component *is* that delegation creates a -circular dependency and fails to compile. - -### Dispatching a generic-parameter component per type with `open` - -When a component is generic over a type parameter, you often want a different provider per value of -that parameter. The modern, preferred way is the **`open` statement** inside `delegate_components!`. -Given a component `CanCalculateArea` (provider `AreaCalculator`), a context dispatches per -shape like this: - -```rust -delegate_components! { - MyApp { - open AreaCalculatorComponent; - - @AreaCalculatorComponent.Rectangle: RectangleArea, - @AreaCalculatorComponent.Circle: CircleArea, - } -} -``` - -The `open … ;` header opens one or more components for per-value wiring and **must lead** the -block (it comes before any plain `Component: Provider` mappings, or the macro fails to parse). The -braces are optional when opening a single component (`open AreaCalculatorComponent;`); use the -braced list `open { A, B };` to open several at once. Each -`@Component.Key: Provider` entry then assigns a provider for one value of the dispatch parameter. Two -grouping forms share one provider across several values and are **not** interchangeable: a braced group -holds whole path *tails* and ends the path (`@AreaCalculatorComponent.{u32, u64, bool}: SomeProvider`), -while a bracketed group holds alternatives for *one segment* and may be followed by more path -(`@app.[FooComponent, BarComponent].[u64, String]: P` writes all four combinations). A key may also -carry generics (`@SomeComponent.<'a, T> &'a T: SomeProvider`). `open` works through the `RedirectLookup` impl that -every `#[cgp_component]` already generates, so it needs no extra attribute on the component. It does -not combine with a joined namespace (`#[prefix(...)]`); that is the full namespace feature. - -**Legacy form (read but don't write):** older code dispatches the same way by wrapping a nested -table in the `UseDelegate` provider — -`AreaCalculatorComponent: UseDelegate` -— generated by a `#[derive_delegate(UseDelegate)]` attribute on the component. This still -works and is common in existing code, but it is slated for deprecation; prefer `open` for new code. -Note that some CGP-shipped components (the error and handler families) are still *defined* with -`#[derive_delegate]` in the library, so you will see `UseDelegate` tables wiring them. - ---- - -## Checking: verifying wiring at compile time - -CGP wiring is **lazy**: defining a `delegate_components!` entry does not itself check that the -provider's transitive dependencies are satisfied. A missing dependency therefore surfaces only when -the consumer trait is finally used, often as a confusing error. To catch it early and clearly, assert -the wiring with a check: - -```rust -check_components! { - Person { - GreeterComponent, - } -} -``` - -This generates a check trait whose supertrait is `CanUseComponent` for -`Person`; if `Person` cannot actually use the component, the compiler reports the missing dependency -at this site, walking through `IsProviderFor` so the real cause (e.g. a missing -`HasField`) is named rather than hidden. For a component with generic parameters, -list the parameter after the component (`GreeterComponent: Rectangle`), group multiple parameters as -a tuple (`(Rectangle, f64)`), and use array syntax to check several at once. - -`delegate_and_check_components!` fuses wiring and checking in one step, so every delegation is -verified the moment it is written: - -```rust -delegate_and_check_components! { - Person { - GreeterComponent: GreetHello, - } -} -``` - -Its check trait is named `__CanUse{Context}` (vs. `__Check{Context}` for `check_components!`), so -both macros can appear once per module without clashing; override with `#[check_trait(Name)]`. When -the delegated component has generic parameters, add `#[check_params(...)]` on the entry; skip a -single entry's check with `#[skip_check]`. - -**This fused macro is a convenience for basic wiring and for getting started — not the default for -advanced code.** It exists so a newcomer cannot forget to write a separate `check_components!` and -then hit confusing lazy-wiring errors, and it derives a check only for the plain `Component: Provider` -delegation form. It cannot easily derive checks for advanced mappings — generic-parameter dispatch -(the `open` statement and `@`-path keys), namespaces, or per-layer higher-order checks. **In larger, -more advanced codebases, keep `delegate_components!` and `check_components!` separate**, which gives -full control over what is checked: `#[check_providers(...)]` per provider layer, concrete parameters -for generic keys, and checks over opened or namespaced wiring. The one non-negotiable is that a -context's wiring *is* checked somehow; which macro you use to do it scales with the wiring's -complexity. - -One case makes `delegate_and_check_components!` not just unnecessary but wrong: an **aggregate -provider** (the `new MyComponents { … }` table above). That target is a provider other contexts -delegate to, not a context itself, so the check's `CanUseComponent` assertion asks whether the bundle -can use each component *as a context* — a role it never plays, making the answer uninformative either -way. It passes vacuously when the bundled providers need nothing from their context, and fails -blaming the bundle when any of them needs a field or a type the real context would have supplied. -Wire an aggregate provider with plain `delegate_components!`; it is verified indirectly when a real -context that delegates to it is checked, or directly with a `#[check_providers(...)]` block that -asserts `IsProviderFor` on it. Finally, not every unsatisfied -bound is a CGP component — some are ordinary or blanket traits that `check_components!` cannot verify. - -For a nested [higher-order provider](references/higher-order-providers.md), checking the context -tells you a layer is broken but not which one. The `#[check_providers(...)]` attribute on a -`check_components!` table changes the assertion from `CanUseComponent` on the context to -`IsProviderFor` on each named provider, so a dependency missing only from the outer wrapper errors on -its line alone while one missing from the inner provider errors on both — pinpointing the layer. See -[checking](references/checking.md) for the debugging playbook. - ---- - -## Functions and getters: the ergonomic surface - -Most basic CGP reads and writes values from the context, and the constructs here make that look like -plain Rust. - -### `HasField` and `#[derive(HasField)]` - -`HasField` is tag-keyed field access. The `Tag` is a type-level name: `Symbol!("width")` for a -named field or `Index<0>` for a tuple field. `#[derive(HasField)]` generates one impl per field: - -```rust -#[derive(HasField)] -pub struct Rectangle { - pub width: f64, - pub height: f64, -} -// generates HasField and HasField -``` - -Field values are read with `self.get_field(PhantomData::)`; the `PhantomData` -carries the tag so type inference knows which field is meant. - -### `#[cgp_fn]` and `#[implicit]` arguments - -`#[cgp_fn]` turns one function into a single-implementation blanket-impl trait — the simplest entry -point to CGP. Arguments marked `#[implicit]` are removed from the signature and pulled from context -fields via `HasField`: - -```rust -#[cgp_fn] -fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height -} -``` - -This generates a `RectangleArea` trait (named from the function in PascalCase; override with -`#[cgp_fn(MyName)]`) with a blanket impl for any context that has `width: f64` and `height: f64` -fields. Implicit arguments get `.clone()` added automatically for owned values and `.as_str()` for -`&str`. Generic parameters on the function move to the trait and impl; the `where` clause becomes -impl-side dependencies on the impl only; generic *method* parameters are intentionally unsupported. -Prefer implicit arguments for basic code — they make CGP look like ordinary functions. - -### `#[uses]`, `#[extend]`, `#[extend_where]` - -`#[uses(TraitA, TraitB)]` (on `#[cgp_fn]` or `#[cgp_impl]`) imports `Self` trait bounds, read -like a `use` statement. The simple `Trait` form is idiomatic, but any `where`-clause bound is -accepted, including associated-type equality (`HasErrorType`) — prefer `#[use_type]`'s -equality form for abstract-type pins: - -```rust -#[cgp_fn] -#[uses(RectangleArea)] -fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 { - self.rectangle_area() * scale_factor * scale_factor -} -``` - -`#[extend(Trait)]` adds *supertrait* bounds to the generated trait — the only way to add supertraits -in `#[cgp_fn]` (whose `where` clauses are impl-side dependencies), and the **preferred** way to add a -*non-type capability* supertrait on `#[cgp_component]` too: `#[extend(HasName)]` reads as importing a -capability, whereas the native `pub trait CanGreet: HasName` syntax reads as OOP-style inheritance -from a parent class, which a CGP supertrait is not. (When the supertrait is an abstract-type component -whose associated type the signatures name, prefer `#[use_type]` instead — it adds the supertrait *and* -rewrites the type, and is the recommended form for abstract-type components.) `#[extend_where(Bound)]` -adds `where` clauses to the generated trait definition (`#[cgp_fn]` only), and accepts arbitrary -predicates including associated-type equality, unlike `#[uses]`/`#[extend]`. A fourth `#[cgp_fn]`-only -attribute, `#[impl_generics(Param: Bound)]`, adds a bounded generic parameter to the generated *impl* -alone — not the trait — which is how a `#[cgp_fn]` body borrows a generic value it does not want to -expose as a trait parameter (e.g. `#[impl_generics(Name: Display)]` over an `#[implicit] name: &Name`). - -### Getters: `#[cgp_auto_getter]`, `#[cgp_getter]`, `UseField` - -An `#[implicit]` argument (above) is the default way to read a context field, so a getter trait is -used *sparingly* — only where an implicit argument cannot reach. Because an implicit argument reads -only from the provider's own `self` (and takes a plain `&T` by reference, no clone), it covers every -same-context read, even a field several providers each consume. A getter trait earns its keep in -three cases it cannot handle: a field that lives on a type *other* than the provider's context, where -the getter is required as a `where` bound on that type (`Request: HasBasicAuthHeader`, so there -is no `self` field to read); an accessor other code depends on as a *named* capability through -`#[uses(HasName)]` or a supertrait; and a getter carrying an *associated type inferred from the -field* so the type stays abstract for callers. - -`#[cgp_auto_getter]` generates a blanket getter impl over `HasField`, with the field name taken from -the method name, and is the getter form to prefer for those cases: - -```rust -#[cgp_auto_getter] -pub trait HasName { - fn name(&self) -> &str; -} -// blanket impl for any context with a `name` field; &str/&String shorthands handled -``` - -A single-getter trait may instead declare a local associated type used as the return type, inferred -from the field — `trait HasName { type Name; fn name(&self) -> &Self::Name; }`. - -`#[cgp_getter]` is an **advanced** tool, reserved for when a context needs full control over which -field a getter reads from — most getters should use `#[cgp_auto_getter]` or an implicit argument -instead. It is like `#[cgp_component]` but also provides a `UseField` blanket impl, so the -getter's source field can be chosen by *wiring* rather than fixed to the method name. The -`UseField` provider implements a getter by reading the field named `Tag`, which may differ from -the method name: - -```rust -delegate_components! { - Person { - NameGetterComponent: UseField, - } -} -// Person::name() now returns the `first_name` field -``` - -`UseFieldRef` is the `AsRef`/`AsMut`-based variant. Any getter can also be implemented by hand — the -macros only save boilerplate. - ---- - -## Abstract types - -CGP abstracts over types with associated types in components. `#[cgp_type]` is the dedicated macro -(use it instead of `#[cgp_component]` for an abstract-type trait): - -```rust -#[cgp_type] -pub trait HasNameType { - type Name; -} -``` - -This defaults the provider name to the type name plus `TypeProvider` (here `NameTypeProvider`, marker -`NameTypeProviderComponent`) and additionally generates a `UseType` blanket impl. A context fixes the -type by wiring the component to `UseType`: - -```rust -delegate_components! { - Person { - NameTypeProviderComponent: UseType, - } -} -// or directly: impl HasNameType for Person { type Name = String; } -``` - -The direct impl is just as valid and shows that abstract types are ordinary associated-type traits. - -The `#[use_type(HasScalarType.Scalar)]` attribute is the recommended way to *use* an abstract type -inside `#[cgp_fn]`/`#[cgp_impl]`/`#[cgp_component]`: it rewrites bare `Scalar` to the fully-qualified -`::Scalar` everywhere and adds the supertrait/where bound, removing `Self::` -boilerplate and ambiguity. CGP's built-in abstract-type component is `HasType` (provider -`TypeProvider`). - ---- - -## Higher-order providers - -A **higher-order provider** takes another provider as a generic parameter and constrains it with a -provider-trait bound, so its inner behavior is chosen by wiring rather than fixed: - -```rust -#[cgp_impl(new ScaledAreaCalculator)] -#[use_provider(InnerCalculator: AreaCalculator)] -impl AreaCalculator { - fn area(&self, #[implicit] scale_factor: f64) -> f64 { - let base_area = InnerCalculator::area(self); - base_area * scale_factor * scale_factor - } -} -``` - -`#[use_provider(InnerCalculator: AreaCalculator)]` completes the inner provider's bound by adding the -`Self` parameter for you (you write `: AreaCalculator`, it means `AreaCalculator`) and moves it -into the `where` clause — that is the *only* thing the attribute does. Inside the body you still call -the provider explicitly with the associated-function form `InnerCalculator::area(self)`; there is no -call-site rewriting. A context then chooses the inner provider when wiring, e.g. -`AreaCalculatorComponent: ScaledAreaCalculator`. - -A higher-order provider often defaults its inner parameter to `UseContext` -(`pub struct IterSumArea(PhantomData);`), so that when no inner provider is -named, the inner step falls back to the context's own wiring. Not every provider with a generic -parameter is higher-order: a provider like `GetName` that uses `Tag` only as a `HasField` key -(no provider-trait bound) is not. - -When a component itself is generic (`#[cgp_component(AreaCalculator)] trait CanCalculateArea`), -the provider trait appends the parameters after the context (`AreaCalculator`), -`IsProviderFor` groups them into its `Params` tuple, and lifetimes are lifted into the `Life<'a>` -type. Such a component is most useful for **cross-context dependencies**: when the main target is a -generic parameter (e.g. `CanCalculateArea: HasScalarType`), individual shape types need not -implement shared capabilities — the common context supplies the shared abstract type, value-level -injection (a global scale factor via a getter), and lazy per-context provider binding, so two apps -can wire the same shape to different providers. - ---- - -## Error handling - -CGP makes the error type abstract so generic code can fail without naming a concrete error. -`HasErrorType` (an abstract-type component, `type Error: Debug`) gives a context one shared -error type; `CanRaiseError` constructs it from a concrete source error -(`Context::raise_error(source)`); `CanWrapError` attaches detail. Both build on -`HasErrorType` and are associated-function (no `self`) components that dispatch per source/detail -type. An error-aware trait imports that error type with `#[use_type(HasErrorType.Error)]`, so it -names the error as the bare `Error` instead of writing `: HasErrorType` and `Self::Error` by hand: - -```rust -#[cgp_component(Loader)] -#[use_type(HasErrorType.Error)] -pub trait CanLoad { - fn load(&self, path: &str) -> Result; -} - -#[cgp_impl(new LoadOrFail)] -#[uses(CanRaiseError)] -#[use_type(HasErrorType.Error)] -impl Loader { - fn load(&self, path: &str) -> Result { - if path.is_empty() { - return Err(Self::raise_error("empty path".to_owned())); - } - Ok(format!("contents of {path}")) - } -} -``` - -A context wires its error type and the raise/wrap behavior. The backend providers — `RaiseFrom` -(convert via `From`), `ReturnError`, `RaiseInfallible`, `PanicOnError`, `DebugError`/`DisplayError` -(format into a `String` and forward), `DiscardDetail` — plug in per source type, modern-style with -`open`: - -```rust -delegate_components! { - App { - open ErrorRaiserComponent; - - ErrorTypeProviderComponent: UseType, - @ErrorRaiserComponent.String: RaiseFrom, - @ErrorRaiserComponent.ParseError: DebugError, - } -} -``` - -**Imports:** `HasErrorType`, `CanRaiseError`, and `CanWrapError` come from the prelude, but the -wiring keys (`ErrorTypeProviderComponent`, `ErrorRaiserComponent`, `ErrorWrapperComponent`) live -under `cgp::core::error`, and the backend providers (`RaiseFrom`, `DebugError`, …) under -`cgp::extra::error` — import the specific names you wire. Standalone backends (`cgp-error-anyhow`, -`cgp-error-eyre`, `cgp-error-std`) provide ready error types. - ---- - -## Handlers: the computation family - -CGP models computation as a family of components along three axes — synchronous vs. async, -infallible vs. fallible, and input-taking vs. input-free: - -- **`Computer` / `CanCompute`** — a synchronous, infallible transform `compute(&self, PhantomData, input) -> Output`. By-reference (`ComputerRef`) and async (`AsyncComputer`) variants exist. -- **`TryComputer` / `CanTryCompute`** — the fallible computer. -- **`Producer` / `CanProduce`** — input-free production (only a context and a `Code` tag). -- **`Handler` / `CanHandle`** — the general **async, fallible, error-aware** computation; the workhorse for I/O and pipelines. It supertraits `HasErrorType`. -- **`CanRun` / `CanSendRun`** — task runners. - -Any CGP trait with async methods — a handler, a runner, or one you define — declares them under the -`#[async_trait]` attribute, which rewrites each `async fn` to `-> impl Future` (the lint-clean, -allocation-free form). The generated future carries no `Send` bound, so spawning it on a -work-stealing executor needs the `Send`-recovery pattern in [handlers](references/handlers.md). - -`#[cgp_computer]` and `#[cgp_producer]` define a `Computer`/`Producer` provider from a function. -Providers compose through combinators: `PipeHandlers` chains handlers -left-to-right, `ComposeHandlers` nests them, `ReturnInput` passes input through, and the `Promote*` -adapters lift a simpler handler (e.g. a sync `Computer`) into a more capable one (an async -`Handler`). For example, a context wires a pipeline of field-reading computers: - -```rust -delegate_components! { - MyContext { - ComputerComponent: - PipeHandlers, - Add, - Multiply, - ]>, - } -} -// context.compute(PhantomData::<()>, 5) runs ((5*foo)+bar)*baz -``` - -Dispatch routes an extensible-data input to per-variant handlers: `#[cgp_auto_dispatch]` generates a -handler from a trait, and the combinators `MatchWithHandlers` / `MatchWithValueHandlers` / -`ExtractFieldAndHandle` match an enum's variants to sub-handlers, proving exhaustiveness without a -wildcard. Monadic handlers (`PipeMonadic`, `BindOk`, `BindErr`, the identity/ok/err monads) compose -handlers through a monad. The handler family is broad — read [handlers](references/handlers.md) for -the full set, including `Send`-bound recovery for async trait methods. - ---- - -## Extensible data - -CGP can build and read structs and enums generically, by their named fields and variants. The -`#[derive(HasFields)]` derive exposes a type's whole field list; `#[derive(CgpData)]` (and the -record/variant-specific `CgpRecord`/`CgpVariant`) derive the full extensible-data machinery: - -```rust -#[derive(CgpData)] -pub struct Person { - pub first_name: String, - pub last_name: String, -} -``` - -Records are built field-by-field through the builder family (`HasBuilder`, `BuildField`) — the -**extensible builder pattern** assembles a context from independent per-field outputs. Variants are -constructed with `FromVariant`, deconstructed with the `ExtractField` extractor family, and the -**extensible visitor pattern** handles each variant. The type-level spines underneath are the -product list (`Product![A, B, C]` over `Cons`/`Nil`) for records and the sum list (`Sum![A, B]` over -`Either`/`Void`) for variants. Structural **casts** convert between shapes — `CanUpcast` widens a -smaller enum into a larger one, `CanDowncast` narrows, `CanBuildFrom` rebuilds a record from a -superset. Dispatching extensible-data inputs to handlers uses the dispatch combinators above. - ---- - -## Namespaces - -Namespaces are reusable, inheritable wiring tables (a preset mechanism) that keep top-level wiring -short as component counts grow. `cgp_namespace! { new MyNs: ParentNs { … } }` defines a namespace -(optionally inheriting a parent after the colon); a context then **joins** it inside -`delegate_components!` with a `namespace MyNs;` statement, after which every lookup it does not wire -directly forwards through the namespace, so any direct entry overrides just that key. A component -**registers into** a namespace with the `#[prefix(@path in MyNs)]` attribute on its `#[cgp_component]` -trait, and a `#[cgp_impl]` provider registers as a per-type default with `#[default_impl(T in DefaultImpls1)]`, -which a context pulls in with a `for in Table { … }` loop. - -The underlying mechanism is the `RedirectLookup` provider, which re-routes a component lookup along a -type-level `Path!`; the `open` statement above is a lightweight special case of it. `DefaultNamespace` -resolves a default provider when a context does not override one. Read -[namespaces](references/namespaces.md) for the preset and inheritance syntax. - ---- - -## Type-level primitives: a decoder ring - -CGP encodes lists, strings, and numbers as types. You mostly use the sugared macros and only need to -*recognize* the expanded forms in errors: - -- **`Symbol!("name")`** — a type-level string (field-name tag). Expands to `Symbol<4, Chars<'n', Chars<'a', Chars<'m', Chars<'e', Nil>>>>`. The leading length works around missing const-generics. -- **`Product![A, B, C]`** — a type-level list. Expands to `Cons>>`. `product![…]` is the value-level form. Used for field lists and handler pipelines. -- **`Sum![A, B]`** — a type-level sum (the dual of `Product!`), over the `Either`/`Void` spine. Used for enum variant lists. -- **`Index`** — a type-level natural number, tags tuple-struct fields. -- **`Field`** — a value paired with its type-level name tag. -- **`Path!`** / `PathCons` — a type-level path, used by namespaces and `RedirectLookup`. -- **`Life<'a>`** — a lifetime lifted into a type, used when a component has lifetime parameters. -- **`MRef`** — an owned-or-borrowed value. - -Prefer the sugar (`Symbol!`, `Product!`) and the readable names (`Cons`/`Nil`) in anything you write. - ---- - -## Sub-skills: load the one that owns your task - -The primer gave you the shape of every construct; each sub-skill below is the ground truth for one -area — the exact grammar, the full expansion, the corner cases, and worked examples. **Loading the -relevant sub-skill is not optional polish; it is the step that turns a plausible guess into correct -code.** Every entry names what it adds beyond this primer *and* what you would be guessing at without -it, so you can see the risk of skipping it. Load a sub-skill whenever your task touches its area — -reading it, writing it, reviewing it, or debugging an error that mentions it — and re-load it when -you move into an unfamiliar corner. When a task spans several areas, load each one; they cross-link, -and following those links is expected, not a detour. - -Two of the sub-skills are cross-cutting rather than construct-specific, and one of them applies to almost every task. Start with **[references/macro-grammar.md](references/macro-grammar.md)** for any task that writes, edits, or debugs CGP syntax: it is the single reference for the formal grammar of every macro, the invariant each expansion preserves, and a decoder for the compiler errors CGP produces. *Without it* you are guessing which attribute forms parse, what a macro emits, and what an `IsProviderFor` or `DelegateComponent` error is actually telling you. Reach for **[references/modern-idioms.md](references/modern-idioms.md)** whenever you read or modernize existing CGP: it maps every legacy, explicit form to the modern idiom you should prefer, both to write vanilla-looking code and to decode the inside-out provider impls, hand-written `where` bounds, `Self::Type` paths, and `UseDelegate` tables you meet in older code. *Without it* you will either propagate outdated syntax or fail to recognize that legacy code and modern code mean the same thing. - -The remaining sub-skills each own one construct family: - -- **[references/components.md](references/components.md)** — `#[cgp_component]` and the full expansion (consumer/provider traits, the two blanket impls, the `…Component` marker), why `IsProviderFor` exists, the three provider-writing macros (`#[cgp_impl]`, `#[cgp_provider]`, `#[cgp_new_provider]`), and how many methods a component should carry — with the three costs a monolithic entity trait pays and how to split one. *Without it* you will misjudge what `self`/`Self` mean inside a provider, how the blanket impls route a call, and how coarse a component can get before its providers stop being reusable. Load it before writing any component or provider. -- **[references/wiring.md](references/wiring.md)** — `DelegateComponent`, every `delegate_components!` form (arrays, `new`, generic tables), `open` per-type dispatch, direct consumer-trait impls, `UseContext` and its circular-dependency trap, the legacy `UseDelegate` tables, and the other providers you see in tables (`WithProvider` and its `WithField`/`WithType`/`WithContext` aliases, `UseDefault`). *Without it* you will not know when a hand-written impl collides with the table, why `UseContext` overflows, or what a `WithField<…>` entry means. Load it before wiring any context. -- **[references/checking.md](references/checking.md)** — why wiring is lazy, how check traits and `CanUseComponent` force readable errors, every `check_components!` / `delegate_and_check_components!` option (`#[check_trait]`, `#[check_providers]`, `#[check_params]`, `#[skip_check]`), and a debugging playbook. *Without it* you cannot localize a broken wiring or read the error it throws. Load it whenever a wiring fails to compile. -- **[references/error-extraction.md](references/error-extraction.md)** — the **fallback for when `cargo-cgp` is not available, or leaves an error largely unrewritten** (see [Tooling](#tooling-use-cargo-cgp-for-readable-errors-and-expansions) first — `cargo-cgp`'s `[CGP-Exxx]` headline and root-cause tree already are the compact summary this sub-skill produces, so reach for the sub-skill only when the tool is absent or passes the error through). It covers how to reduce a long raw CGP compile error to a compact, root-cause-first summary, the hidden-versus-surfaced distinction that decides whether the root cause is even present in the output, how to confirm a suspected cause by grepping for one signature line, and how to delegate the reading to a sub-agent so a wall of generated-type errors does not consume your context. *Without it* you will read a cascade inline, chase a cause a hidden error does not contain, or hand back raw output instead of the few facts that matter. -- **[references/functions-and-getters.md](references/functions-and-getters.md)** — `HasField`/`#[derive(HasField)]`, `#[cgp_fn]`, `#[implicit]` and its access rules, `#[uses]`/`#[extend]`/`#[extend_where]`/`#[impl_generics]`, the getters `#[cgp_auto_getter]`/`#[cgp_getter]`/`UseField`/`WithField`, and `ChainGetters` for nested-context fields. *Without it* you will reach for a getter trait where an implicit argument is idiomatic, or misapply the `.clone()`/`.as_str()`/`&mut` field-access rules. Load it for the ergonomic day-to-day surface. -- **[references/abstract-types.md](references/abstract-types.md)** — `#[cgp_type]`, the built-in `HasType`/`TypeProvider`, wiring with `UseType` (and `UseDelegatedType` for table-chosen types), importing types with the `#[use_type]` attribute (distinct from the `UseType` provider), and the `WithType`/`WithDelegatedType` adapters. *Without it* you will confuse the provider and the attribute and write `Self::` paths by hand. Load it for any associated-type abstraction. -- **[references/higher-order-providers.md](references/higher-order-providers.md)** — providers parameterized by other providers, the stray `` on the inner bound, `#[use_provider]`, `UseContext` defaults, generic-parameter components, and cross-context dependencies. *Without it* you will call the inner provider as a method instead of `Provider::method(self)` and misplace the context slot. Load it before composing providers. -- **[references/error-handling.md](references/error-handling.md)** — `HasErrorType`, `CanRaiseError`/`CanWrapError`, the backend providers (`RaiseFrom`, `DebugError`, …), and — critically — which names come from the prelude versus `cgp::core::error` / `cgp::extra::error`. *Without it* you will fail to import the wiring keys and backends. Load it for any fallible CGP code. -- **[references/handlers.md](references/handlers.md)** — the `Computer`/`TryComputer`/`Producer`/`Handler`/runner family across its three axes, `#[cgp_computer]`/`#[cgp_producer]`/`#[cgp_auto_dispatch]`, the combinators (`PipeHandlers`, `Promote*`, dispatch matchers), monadic handlers, the `HasRuntime`/`HasRuntimeType` runtime components, and the `Send`-recovery pattern. *Without it* you will pick the wrong family member or miswire a pipeline. Load it for computation and I/O pipelines. -- **[references/extensible-data.md](references/extensible-data.md)** — the `CgpData`/`CgpRecord`/`CgpVariant` derives, the builder and extractor families (with the optional/defaulted-field extension), `Product!`/`Sum!` spines and their `AppendProduct`/`ConcatProduct`/`MapFields` algebra, structural casts (`CanUpcast`/`CanDowncast`/`CanBuildFrom`), and the builder/visitor patterns. *Without it* you will miss the compile-time exhaustiveness guarantees and the single-payload variant rule. Load it for generic struct/enum manipulation. -- **[references/namespaces.md](references/namespaces.md)** — `cgp_namespace!`, the `namespace`/`for … in` statements that join a namespace, the `#[prefix]`/`#[default_impl]` attributes that register into one, `RedirectLookup`, `Path!`, and the `DefaultNamespace` family. *Without it* you cannot read or write preset/inheritance wiring. Load it whenever wiring is grouped or inherited. -- **[references/type-level-primitives.md](references/type-level-primitives.md)** — `Symbol!`/`Chars`, `Product!`/`Cons`/`Nil`, `Sum!`/`Either`/`Void`, `Index`, `Field`, `Path!`/`PathCons`, `Life`, `MRef`, and the `StaticFormat` recovery traits. *Without it* you cannot decode the long nested types in error messages and expansions. Load it as the decoder ring. -- **[references/modularity-hierarchy.md](references/modularity-hierarchy.md)** — the five-level spectrum from a plain blanket trait to per-provider wiring, and which coherence rule each level escapes. *Without it* you will reach for more CGP machinery than a problem needs. Load it when deciding *how much* CGP to apply. - -### Exhaustive online reference - -For the exact macro expansion of any construct, every accepted syntax form, corner cases, or the -implementing source, consult the online knowledge base at -**https://github.com/contextgeneric/cgp-knowledge-base** — CGP's own section is -[`cgp/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp), whose `reference/`, -`concepts/`, `guides/`, and `errors/` directories are the authoritative, exhaustive record, and the -worked [`examples/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/examples) sit at -the base's top level beside it. The base also documents `cargo-cgp`, under -[`cargo-cgp/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cargo-cgp). Fetch the -relevant page when a detail is not covered here; do not assume a local copy exists, since this skill -is deployed on its own. - ---- - -## Instructions for explaining CGP to users - -Assume by default that the user has only basic Rust experience and is new to CGP, but do not -over-explain: when code merely uses CGP concepts, write or modify it without lecturing, and add -explanation only when asked. When you do explain, assume unfamiliarity with advanced Rust (generics, -traits, blanket impls, coherence) and with functional/type-level programming — describe type-level -tables, lists, and strings through familiar analogies such as a map or a lookup table, and expand on -advanced Rust as needed. Keep the simplified picture front and center: present wiring as choosing a -table entry, and keep `IsProviderFor`, `DelegateComponent`, and generated blanket impls out of the -explanation unless the user is asking specifically about the internals. One caveat when you reach -for an analogy: the "table lookup" is resolved at compile time and compiles down to direct static -calls, so if you use a runtime-flavored analogy like a vtable, say explicitly that — unlike a real -vtable — CGP's resolution is static and zero-cost, with no runtime table or dynamic dispatch. Never -leave a reader thinking CGP wiring has runtime lookup overhead. - -**Never leave a reader thinking a CGP trait is limited to one item, either.** Because single-decision -components dominate idiomatic CGP, an explanation built only from one-method traits reads as a restriction -the macros impose, and a reader who believes their traits are being capped pushes back on the whole -paradigm rather than on the guidance. So say plainly, whenever the subject comes up, that a component trait -is an ordinary trait taking as many methods, associated types, and consts as any other — CGP's own -`CanCompute` and `CanHandle` carry an associated `Output` beside their method — and present the grouping -guidance the way [components](references/components.md) frames it: a trade-off about how much reuse a -provider can collect, decided by the author, never a rule about item counts. - -When asked to explain a specific piece of code, look up the definitions it depends on before -answering. To explain a `delegate_components!` entry, find the consumer and provider traits behind -the component key and the body of the provider it maps to. To explain a provider, read its own -definition and the definitions of every capability in its `where` clause. To explain how a context -implements something, follow its wiring to see which providers are chosen and trace a method call -through them — for instance, if `NameGetterComponent` is wired to `UseField`, -then a `self.name()` call inside another provider returns the context's `first_name` field. diff --git a/docs/ai/skills/SKILL.md b/docs/ai/skills/SKILL.md new file mode 120000 index 00000000..0c9d929c --- /dev/null +++ b/docs/ai/skills/SKILL.md @@ -0,0 +1 @@ +../../../cgp-skills/cgp/SKILL.md \ No newline at end of file diff --git a/docs/ai/skills/references/abstract-types.md b/docs/ai/skills/references/abstract-types.md deleted file mode 100644 index 906492b8..00000000 --- a/docs/ai/skills/references/abstract-types.md +++ /dev/null @@ -1,167 +0,0 @@ -# Abstract types - -An abstract type is a CGP trait carrying a single associated type that generic code names as `Self::Foo` without committing to a concrete type, leaving the concrete choice to wiring so it can differ from one context to another. - -## The idea - -An abstract type lets generic code name a type it does not fix. Instead of hard-coding `f64` or `String`, a trait declares one associated type — `trait HasNameType { type Name; }` — and code written against it refers to `Self::Name`, leaving the actual type open. The trait is the abstraction; the associated type is the slot a context fills in. This is the type-level analogue of an impl-side dependency: just as a getter lets a context supply a *value* a provider needs, an abstract-type trait lets a context supply a *type* a provider builds on. - -The payoff is the same one CGP gives for behavior. A provider written in terms of `Self::Name` works unchanged whether a context chooses `String`, `&'static str`, or a custom name type, and two contexts can make different choices from the same generic code. Under the hood an abstract type is nothing more than an ordinary Rust trait with one associated type — generic functions constrain `Context: HasNameType` and use `Context::Name` exactly as they would any associated type. The CGP machinery only makes declaring and wiring these traits cheap. - -## Direct implementation: it's just a trait - -Because an abstract type is a vanilla associated-type trait, the most transparent way to bind it is to implement it directly on a concrete context. Given the trait, a context names the concrete type in a plain `impl`: - -```rust -#[cgp_type] -pub trait HasNameType { - type Name; -} - -pub struct Person; - -impl HasNameType for Person { - type Name = String; -} -``` - -This makes `Person::Name` resolve to `String`, and any generic code constrained on `HasNameType` sees that choice. The direct form is the right mental model for newcomers — there is no hidden machinery, just an associated type pinned to a concrete one — and it is barely longer than the wired form shown below. The rest of this reference explains the `#[cgp_type]` macro and the wiring conveniences that make the choice swappable through a delegation table instead. - -## Making a type swappable with `#[cgp_type]` - -The `#[cgp_type]` macro turns an abstract-type trait into a full component, so the concrete type can be chosen through wiring rather than a hand-written impl. It is the abstract-type specialization of `#[cgp_component]`: applied to a trait with exactly one associated type and no methods, it produces everything `#[cgp_component]` would — the consumer trait, the provider trait, the blanket impls, the `…Component` marker — but each impl forwards the *associated type* rather than a method. - -```rust -#[cgp_type] -pub trait HasNameType { - type Name; -} -``` - -The default provider name is keyed off the *associated type* name, not the trait name, with a `TypeProvider` suffix. So `type Name;` yields the provider `NameTypeProvider` and the component marker `NameTypeProviderComponent`. A bound on the associated type — `type Name: Clone;` — is carried everywhere the type appears in the expansion and enforced on whatever concrete type a context chooses. You can override the derived provider name by passing one, exactly as with `#[cgp_component]`: `#[cgp_type(ProvideName)]`. - -The construct that distinguishes `#[cgp_type]` from a plain component is an extra blanket impl it generates for the `UseType` provider, described next, which is what lets a context pick a concrete type without writing a provider of its own. - -## Wiring a concrete type with `UseType` - -A context binds an abstract type to a concrete one by wiring its provider component to `UseType`. Because every abstract-type provider has the same trivial shape — "the associated type *is* this concrete type" — `#[cgp_type]` generates that shape once as a blanket impl of the provider trait for `UseType`, setting the associated type to the generic parameter. The context then names the concrete type directly in its delegation table: - -```rust -delegate_components! { - Person { - NameTypeProviderComponent: UseType, - } -} -``` - -Wiring `NameTypeProviderComponent` to `UseType` makes `Person` implement `HasNameType` with `Name = String`, with no bespoke provider, and any bound on the associated type is checked against `String` at the wiring site. `UseType` is a zero-sized marker struct carrying no runtime value — it exists only to be named in a delegation table, never constructed. This is the type-level mirror of how `UseField` supplies a value-level getter (see [functions and getters](functions-and-getters.md)). - -The blanket impl that `#[cgp_type]` generates for the example above is: - -```rust -impl NameTypeProvider<__Context__> for UseType { - type Name = Name; -} -``` - -This says `UseType` is a provider that supplies `T` as the abstract type, for any context. If the associated type carried a bound, that bound would be copied into the impl's `where` clause so the concrete type must satisfy it. - -A word of caution on the name: the `UseType` *provider struct* shown here is a different construct from the `#[use_type]` *attribute* covered below. The provider wires a concrete type *into* a context; the attribute imports an abstract type *into* a definition and rewrites bare mentions of it. They share a name because both center on abstract types, but they live in different places and do different jobs. - -## The built-in `HasType` / `TypeProvider` component - -Underneath every named abstract type sits CGP's single built-in abstract-type component, `HasType`. It is tag-indexed: `HasType` is the consumer trait, `TypeProvider` is its provider trait, and a context can carry many distinct abstract types — one per `Tag` — resolving each through wiring. - -```rust -#[cgp_component(TypeProvider)] -pub trait HasType { - type Type; -} -``` - -Every `#[cgp_type]` component you define is wired on top of this substrate: the macro generates an internal `WithProvider` impl that adapts a `TypeProvider` into the named component, so the same `UseType` marker satisfies both the built-in `HasType` and any user-defined abstract type at once. In practice you rarely name `HasType` directly — you define a readable `HasNameType` with `#[cgp_type]` and get `Self::Name` and its own provider, all resolving down to this `HasType` machinery. The takeaway is that `UseType` is itself a `TypeProvider`, which is why one marker serves every abstract type. When you do want to name that adapter explicitly, its alias is `WithType` (the `WithProvider` family from [wiring](wiring.md)). - -## Choosing the concrete type from a table with `UseDelegatedType` - -`UseDelegatedType` is the type-level analogue of the `UseDelegate` dispatcher: where `UseType` binds an abstract type to one fixed `T`, `UseDelegatedType` looks the concrete type up in an inner `DelegateComponent` table keyed by the type tag, so one provider can answer several abstract-type components at once or route each tag to a type chosen elsewhere. It reads an entry out of the same kind of table `UseDelegate` reads, but yields a *type* rather than a method — the abstract-type mirror of the per-value behavioral dispatch in [wiring](wiring.md). Its `WithProvider` alias is `WithDelegatedType`. Reach for it only when a bundle of related types must be decided together; for a single concrete type per component, `UseType` is simpler. - -## Abstract type as a getter return type - -When an abstract type's only role is to be the return type of a getter, you can declare it inline with `#[cgp_auto_getter]` rather than defining a separate `#[cgp_type]` trait. The getter trait carries the associated type locally, and the field's type is inferred from it: - -```rust -#[cgp_auto_getter] -pub trait HasName { - type Name; - - fn name(&self) -> &Self::Name; -} -``` - -A context implementing this through its field wiring supplies both the concrete `Name` and the value. This keeps a one-off abstract type local to the getter that uses it instead of promoting it to a shared, wired component. See [functions and getters](functions-and-getters.md) for how `#[cgp_auto_getter]` derives the getter from a field. - -## Importing an abstract type with `#[use_type]` - -The strongly recommended way to *refer to* an abstract type from another definition is the `#[use_type]` attribute. A provider or component often needs a type that lives on a different trait — a `Scalar` from `HasScalarType`, an `Error` from `HasErrorType` — and Rust requires every mention to be written in fully-qualified form, `::Scalar`, because a bare `Scalar` is not a type the compiler knows. Writing that prefix on every occurrence is verbose and easy to get wrong. - -`#[use_type]` lets you write the bare identifier everywhere and have the macro expand it. You declare the import once alongside `#[cgp_fn]`, `#[cgp_impl]`, or `#[cgp_component]` as `#[use_type(Trait.AssocType)]` — a `.` (not `::`) separates the trait from the associated type — and the macro rewrites each standalone `Scalar` into `::Scalar` while also adding `HasScalarType` as a supertrait (for `#[cgp_component]`) or a `where`-clause bound (for `#[cgp_impl]` and `#[cgp_fn]`). The `.` separator keeps the trait unambiguous even when it is a full path or carries generic arguments (`errors::HasErrorType.Error`, `HasFooType.Foo`). Consider a `rectangle_area` function that multiplies two implicit fields: - -```rust -pub trait HasScalarType { - type Scalar: Clone + Mul; -} - -#[cgp_fn] -#[use_type(HasScalarType.Scalar)] -fn rectangle_area( - &self, - #[implicit] width: Scalar, - #[implicit] height: Scalar, -) -> Scalar { - width * height -} -``` - -The macro rewrites every bare `Scalar` to the qualified path and adds the supertrait/bound, so the effective trait and impl read: - -```rust -pub trait RectangleArea: HasScalarType { - fn rectangle_area(&self) -> ::Scalar; -} - -impl RectangleArea for Context -where - Self: HasField::Scalar> - + HasField::Scalar>, - Self: HasScalarType, -{ - fn rectangle_area(&self) -> ::Scalar { - let width: ::Scalar = - self.get_field(PhantomData::).clone(); - let height: ::Scalar = - self.get_field(PhantomData::).clone(); - width * height - } -} -``` - -The substitution is purely textual at the type level — it matches single-segment, argument-free type paths whose identifier equals the imported name — so a bare `Scalar` in the return type, an implicit-argument annotation, or a `let` binding inside the body is all rewritten the same way. Beyond saving keystrokes, the always-qualified rewrite removes the ambiguity the bare form cannot express, which is why this is the default way to import abstract types in all three macros. - -The attribute has a few richer forms worth knowing. A trailing `in Context` clause changes the rewrite target from `Self` to a named type, which imports a *foreign* abstract type from a generic parameter: `#[use_type(HasScalarType.Scalar in Types)]` rewrites `Scalar` to `::Scalar` and adds `Types: HasScalarType` as a `where` bound rather than a supertrait. That bound lands on the generated impl *and*, on `#[cgp_fn]`/`#[cgp_component]`, on the generated trait itself, so a plain unbounded `` parameter is enough — you do not restate `Types: HasScalarType` by hand. The `in Context` clause may also point at another abstract type imported in the same attribute, chaining through several hops (`HasTypes.Types, HasScalarType.Scalar in Types` yields the two-hop `<::Types as HasScalarType>::Scalar`), and so may a *generic argument of the imported trait*, so an alias can parameterize the trait it is imported from (`HasDbType.Db, HasPoolType.Pool` projects against `HasPoolType<::Db>`). Either way the order you write the imports in does not matter, and two imports may share one context; the one arrangement rejected is a **cycle**, where the contexts or trait arguments resolve through each other (`HasA.A in B, HasB.B in A`, or the degenerate `HasAType.A in A`), which is a compile error naming the cycle rather than a confusing unresolved-name error later. A braced list imports several types from one trait, each optionally renamed with `as` or constrained with `=`: `#[use_type(HasScalarType.{Scalar = f64})]` both imports `Scalar` and emits `Self: HasScalarType`, pinning it (and when the trait is generic the pin joins its existing arguments, so `HasFooType.{Foo = u32}` emits `Self: HasFooType`). This equality form is the modern replacement for a hand-written `where Self: HasScalarType` clause on a `#[cgp_impl]` or `#[cgp_fn]` — prefer moving such a pin into the attribute rather than leaving it as an explicit `where`. The right-hand side of `=` is substituted too, so an imported alias is grounded wherever it appears in it: naming another alias outright *unifies* two abstract types (`#[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})]` emits `Self: HasHashedPasswordType::Password>`), while an alias nested inside the type is grounded in place (`#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits `Self: HasTransactionType::Db>>`). To import types from *several* traits, separate the trait paths with commas inside one attribute — `#[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasErrorType.Error)]` — and prefer that combined form over stacking one `#[use_type]` attribute per trait, since it reads as a single import list; stacked attributes behave identically but are for when a real reason calls for it. The `= ...` equality form is rejected on `#[cgp_component]`, since a trait definition cannot carry the impl-side equality constraint it produces; it belongs on `#[cgp_fn]` and `#[cgp_impl]`. Two imports may not resolve to the same identifier or alias — across specs or within one braced list — since the substitution could then match only one; a collision is a compile error on every host macro, as is the import cycle described above. - -## Sharing one type across contexts - -The value of an abstract type compounds when several pieces of generic code share it. Because the type lives on a trait the context implements, every provider and trait that needs a `Scalar` refers to the *same* `Self::Scalar`, so a context fixes the choice once and all of them agree. This is sharpest when a trait's main subject is a generic parameter rather than the context itself — a `CanCalculateAreaOfShape` implemented by one context for many shapes. The shapes carry no scalar type of their own; the shared context supplies a single `Scalar` through its `HasScalarType` wiring, and switching `UseType` to `UseType` changes the scalar for every shape at once. The same arrangement is how CGP shares one error type across an application: `HasErrorType` is itself defined with `#[cgp_type]`, and every fallible provider refers to the same `Self::Error` (see [error handling](error-handling.md)). - -## Related references - -Abstract types are wired into a context with [components](components.md) and consumed by [functions and getters](functions-and-getters.md). `UseType` is one of the higher-order providers described in [higher-order providers](higher-order-providers.md), and the shared error type pattern is covered in [error handling](error-handling.md). - -## Further reference - -Online docs: -[`#[cgp_type]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_type.md), -[`HasType`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/has_type.md), -[`UseType` provider](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_type.md), -[`#[use_type]` -attribute](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/use_type.md). diff --git a/docs/ai/skills/references/abstract-types.md b/docs/ai/skills/references/abstract-types.md new file mode 120000 index 00000000..4953d226 --- /dev/null +++ b/docs/ai/skills/references/abstract-types.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/abstract-types.md \ No newline at end of file diff --git a/docs/ai/skills/references/checking.md b/docs/ai/skills/references/checking.md deleted file mode 100644 index 0387657e..00000000 --- a/docs/ai/skills/references/checking.md +++ /dev/null @@ -1,209 +0,0 @@ -# Checking wiring - -How to verify at compile time that a context's [wiring](wiring.md) is complete, using check traits and the `check_components!` / `delegate_and_check_components!` macros to turn confusing use-site errors into precise ones at the wiring site. - -## Why wiring is lazy - -CGP wiring is lazy: recording that a context delegates a [component](components.md) to a provider does not verify that the provider can actually satisfy that component for that context. When you write a `DelegateComponent` entry mapping `GreeterComponent` to `GreetHello`, the type system stores "this key points to this provider" as an associated type and asks no further questions. Whether the provider's own `where` bounds — its impl-side dependencies — hold for this particular context is simply not checked at the point of delegation. The check is deferred until something downstream actually *uses* the component, which is the first moment the compiler is forced to evaluate the provider's bounds against the concrete context. - -This laziness is what makes CGP composable, but it has a cost: a context can look fully wired and still be broken. Every entry compiles, the struct compiles, the whole module compiles — and then the first call to a consumer trait method fails, often far from the wiring that caused it. A missing field, a missing abstract type, an unsatisfied transitive bound three providers deep: none of these surface where the mistake was made. - -Consider a greeter provider that depends on a `name` field, wired onto a context whose field is misnamed: - -```rust -#[cgp_auto_getter] -pub trait HasName { - fn name(&self) -> &str; -} - -#[cgp_component(Greeter)] -pub trait CanGreet { - fn greet(&self); -} - -#[cgp_impl(new GreetHello)] -#[uses(HasName)] -impl Greeter { - fn greet(&self) { - println!("Hello, {}!", self.name()); - } -} - -#[derive(HasField)] -pub struct Person { - pub first_name: String, // mismatch: GreetHello needs `name` -} - -delegate_components! { - Person { - GreeterComponent: GreetHello, - } -} -``` - -This whole block compiles. `GreetHello` needs `HasName`, `Person` has no `name` field, and nothing complains — until some distant `person.greet()` call fails to typecheck. - -## Why the resulting errors are poor - -When a lazily-wired context is finally used and a dependency is missing, the compiler reports the outermost unmet conclusion and hides the reasoning behind it. Asking the plain question "does `Person` implement `CanGreet`?" makes Rust answer with the last link in the chain — typically that `GreetHello` does not implement the provider trait for `Person` — without explaining *why* the provider's bounds were not met. The provider blanket impl is a competing candidate that suppresses the detailed diagnostic. The root cause, a single missing `name` getter, is buried beneath a conclusion that points at the provider rather than at the gap, and the surface error spells field names in their verbose type-level form (`Symbol<…, Chars<…>>`), making even that hard to read. - -The fix is to force the compiler to evaluate the provider's bounds *and report them in detail*, at a location you control — the wiring site — rather than wherever the component happens to be used first. - -## How check traits force readable errors - -A check trait is a dummy trait whose supertrait is the requirement being asserted; implementing it for a context with an empty body compiles only if that requirement holds. The hand-written form is plain Rust: - -```rust -trait CanUsePerson: CanGreet {} -impl CanUsePerson for Person {} -``` - -The `impl` block has nothing to prove on its own, so it succeeds exactly when `Person: CanGreet` holds and fails otherwise. Placed next to the wiring, it converts a latent gap into an immediate compile error at a known line. But asserting the *consumer* trait directly is not enough: it reproduces the same vague error as before, naming the provider rather than the missing dependency. The remedy is to route the assertion through `CanUseComponent` instead. - -`CanUseComponent` is satisfied only when the context both delegates the component and the delegated provider satisfies `IsProviderFor` for that context. The crucial property is that `IsProviderFor` carries the provider's *real* `where` bounds — the same impl-side dependencies the provider needs to implement its provider trait. Routing a check through `CanUseComponent` therefore forces the compiler to evaluate those bounds and, because they are stated explicitly through the marker, to report the specific one that failed. A missing `name` field surfaces as an unsatisfied `HasName`/`HasField` bound pointing at the context, not as a bare "provider not implemented." The two bounds also distinguish the two ways wiring goes wrong: failing the `DelegateComponent` bound means the component was never wired (add the delegation), while failing the `IsProviderFor` bound means it was wired to a provider whose dependencies are unmet (supply the missing dependency). You rarely name `CanUseComponent` directly — its job is to be the bound the check macros emit. - -## Generating checks with `check_components!` - -Rather than spell out check traits by hand, `check_components!` generates them from a short table of components to verify. Given a context and a list of components, it emits a marker trait aliasing `CanUseComponent` and one empty impl per component: - -```rust -check_components! { - Person { - GreeterComponent, - } -} -``` - -The generated impl compiles only if `Person: CanUseComponent`, which drags in `GreetHello`'s `IsProviderFor` bounds and reports the first that fails — here, the missing `name` field, pinpointed at the wiring site instead of at a future `person.greet()`. A successful build *is* the passing assertion; these checks have no runtime existence. - -The check trait is named `__Check{Context}` by default — `__CheckPerson` here. When two `check_components!` tables in the same module would collide on that name, override it with `#[check_trait(Name)]` on the table: - -```rust -check_components! { - #[check_trait(CheckPersonGreeting)] - Person { - GreeterComponent, - } -} -``` - -A component with generic parameters cannot be checked bare, because the check must name concrete parameters to have anything to verify. List them after a colon: a single parameter bare, multiple parameters grouped into a tuple, mirroring how the provider trait groups them in its `IsProviderFor` `Params` slot. Given an area calculator generic over a shape: - -```rust -#[cgp_component(AreaOfShapeCalculator)] -pub trait CanCalculateAreaOfShape { - fn area(&self, shape: &Shape) -> f64; -} - -check_components! { - MyApp { - AreaOfShapeCalculatorComponent: Rectangle, // one parameter - TransformCalculatorComponent: (Rectangle, f64), // two, as a tuple - } -} -``` - -Array syntax on either side of the colon expands to the cartesian product, so a set of components can be checked against a set of parameters in one line. A bracketed value checks one component against several parameter sets; a bracketed key checks several components against one set; bracketing both checks every combination: - -```rust -check_components! { - MyApp { - AreaOfShapeCalculatorComponent: [Rectangle, Circle], // one component, two shapes - } -} -``` - -This verifies `MyApp: CanCalculateAreaOfShape` and `MyApp: CanCalculateAreaOfShape` in one entry. - -## Checking providers directly with `#[check_providers(...)]` - -For [higher-order providers](higher-order-providers.md), checking the context as a whole tells you a layer is broken but not which one. The `#[check_providers(...)]` attribute changes what is checked: instead of asserting `CanUseComponent` on the context, it asserts `IsProviderFor` directly on each named provider, so each layer is verified on its own impl: - -```rust -check_components! { - #[check_trait(CheckScaledRectangleProviders)] - #[check_providers( - RectangleAreaCalculator, - ScaledAreaCalculator, - )] - ScaledRectangle { - AreaCalculatorComponent, - } -} -``` - -Because each provider is checked independently, a dependency missing only from the outer `ScaledAreaCalculator` wrapper errors on the wrapper's line alone, while one missing from the inner `RectangleAreaCalculator` errors on both lines — which narrows down where in a nested stack the gap lives. - -## Wiring and checking together with `delegate_and_check_components!` - -For basic wiring, and especially while getting started with CGP, `delegate_and_check_components!` removes the bookkeeping of keeping a standalone `check_components!` block in sync with the delegations. It fuses the two — wiring each entry exactly as `delegate_components!` would and deriving a check for each delegated key — so a simple context is proven the moment it is written and a newcomer cannot forget the check. (Its reach stops at that basic form, which is why advanced codebases keep the two macros separate; see the recommendation at the end of this section.) - -```rust -#[derive(HasField)] -pub struct MyContext { - pub name: String, -} - -delegate_and_check_components! { - MyContext { - NameTypeProviderComponent: UseType, - NameGetterComponent: UseField, - } -} -``` - -If `MyContext` were missing the `name` field, the derived check on `NameGetterComponent` would fail to compile and report the missing bound, rather than letting the gap slip through to a later use. - -Its check trait is named `__CanUse{Context}` by default — deliberately distinct from `check_components!`'s `__Check{Context}` — so one of each macro can appear in the same module without a clash. As with `check_components!`, `#[check_trait(Name)]` overrides the derived name. - -Because the delegation half is generic over a component's parameters but the check half needs concrete ones, an entry for a component with generic parameters *requires* a `#[check_params(...)]` attribute supplying them, using the same single-versus-tuple convention: - -```rust -delegate_and_check_components! { - MyApp { - #[check_params(Rectangle, Circle)] - AreaOfShapeCalculatorComponent: - UseDelegate, - } -} -``` - -The nested `UseDelegate` table shown here is the legacy form of per-type dispatch; the modern equivalent opens the component with the `open` statement of `delegate_components!` (see [wiring](wiring.md)). The `#[check_params(...)]` requirement is the same either way — whichever wiring form supplies the dispatch entries, the check half still needs the concrete parameters spelled out. - -To wire an entry without checking it — for instance a higher-order delegation you verify separately with a `#[check_providers(...)]` block — mark it `#[skip_check]`. The two attributes are mutually exclusive on a given entry: - -```rust -delegate_and_check_components! { - ScaledRectangle { - AreaCalculatorComponent: - ScaledAreaCalculator, - - #[skip_check] - TransformCalculatorComponent: - ComplexTransform, // checked in a dedicated check_components! block - } -} -``` - -Where `delegate_and_check_components!` fits is narrower than its convenience suggests: it is the beginner-friendly, basic-wiring form, not the default for advanced code. Its value is that a newcomer cannot forget to write a separate `check_components!` and then be tripped by the confusing lazy-wiring errors that follow; it derives a check for each entry keyed on a component *name* — the plain `Component: Provider` form and its `->` sibling — so getting-started code is checked by construction. But the derivation only understands a key that names a component. The advanced forms still *wire*, and are left **silently unchecked**: generic-parameter dispatch through the `open` statement and `@`-path keys, `=>` redirects, and namespace joins all produce delegation impls and no check entry, with nothing warning that a table is only partly verified. Per-layer higher-order checks are not expressible here at all. Each of these needs concrete parameters or providers the fused derivation cannot infer from a delegation alone. So in larger, more advanced codebases, keep `delegate_components!` and `check_components!` separate: the standalone `check_components!` block is where `#[check_providers(...)]`, concrete parameters for generic keys, and checks over opened or namespaced wiring all live. The rule that does not bend is that a context's wiring is checked *somehow*; `delegate_and_check_components!` is simply the training-wheels way to guarantee that for simple contexts, and the two separate macros are the way that scales. - -There is also a case where `delegate_and_check_components!` is not merely unnecessary but outright *wrong*: an **aggregate provider**. A `delegate_components!` table need not describe a context at all — a `new SomeComponents { … }` table (see [wiring](wiring.md)) defines a zero-sized provider that dispatches each component to a sub-provider, which other contexts then delegate to as a reusable bundle. Such an aggregate provider is always wired with plain `delegate_components!`, never the checked variant, because the check asserts that the target can *use* each component as a context — `Target: CanUseComponent` — which is a role the bundle never plays, so the answer is uninformative whichever way it goes. **Which way it goes depends on the bundled provider, and this is worth knowing, because one of the two failures is silent.** A leaf provider with no impl-side dependencies implements its provider trait for *every* context, the bundle included, so the assertion holds vacuously and the check passes while proving nothing about the bundle. A leaf provider that needs a field or an abstract type makes the assertion fail and blames the bundle: a bundled `RectangleArea` reading a `width` field reports that `GeometryComponents: CanUseComponent` is unsatisfied because `GeometryComponents` does not implement `HasField`, which names neither the real mistake nor the real context. An aggregate provider is verified indirectly instead, when a real context that delegates to it is checked, or directly with a `#[check_providers(...)]` block that names the aggregate and asserts `IsProviderFor` on it for a real context — the provider-side check, not the context-side one. - -## Debugging an unsatisfied check - -When a check fails, the error names the unmet bound — read it as a thread to pull rather than a final verdict. The reported bound is the first impl-side dependency the compiler could not satisfy; walk the transitive dependencies from there. If `GreetHello` requires `HasName`, the error names `HasName` on the context, and the fix is to supply that field or wire the getter component. A bound several providers deep names the innermost requirement, so trace from the failing component through each provider it delegates into. - -When a large `delegate_and_check_components!` table reports a tangle of errors, narrow it down by adding the suspect component to a separate `check_components!` block on its own. Checking one component in isolation, with its parameters spelled out, strips away the noise from the other entries and forces the compiler to report just that component's unmet dependency. For a higher-order stack, switch to `#[check_providers(...)]` to see which layer fails on its own line. - -Finally, remember that not every unsatisfied bound is a CGP component. A check trait only verifies wiring routed through `CanUseComponent` — it cannot prove a plain trait or a blanket-impl bound that a provider also depends on. If the error names a trait that has no `…Component` marker and no entry in any delegation table, no amount of checking will surface it through the wiring; that bound must be satisfied by ordinary Rust means (an `impl`, a derive, a `where` clause on the context), and the check will pass only once it is. - -## Further reference - -Online docs: -[`check_components.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/check_components.md), -[`delegate_and_check_components.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/delegate_and_check_components.md), -and the conceptual overview -[`concepts/check-traits.md`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/check-traits.md). diff --git a/docs/ai/skills/references/checking.md b/docs/ai/skills/references/checking.md new file mode 120000 index 00000000..25971218 --- /dev/null +++ b/docs/ai/skills/references/checking.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/checking.md \ No newline at end of file diff --git a/docs/ai/skills/references/components.md b/docs/ai/skills/references/components.md deleted file mode 100644 index 12f016be..00000000 --- a/docs/ai/skills/references/components.md +++ /dev/null @@ -1,257 +0,0 @@ -# Components - -A CGP **component** is the bundle that `#[cgp_component]` generates from one trait so that *using* a capability and *implementing* it become separate, swappable things — this is the central reference; read it first. - -## What a component is - -A component is a single trait definition compiled into a small machine: a **consumer trait** that callers invoke, a **provider trait** that implementations target, a `…Component` marker key, and the blanket impls that connect them. An ordinary Rust trait conflates using a capability with implementing it — the type you call `.area()` on is the same type that supplies the `area` body — and Rust's coherence rules then allow only one implementation per type. A component breaks that conflation, which is what lets many independent implementations of the same capability coexist and lets you implement a capability for a type you do not own. - -The split is produced by `#[cgp_component]`, applied to an ordinary trait. Throughout this file the running examples are the greeting component (`CanGreet` / `Greeter` / `GreetHello`, on a `Person`) and the area component (`CanCalculateArea` / `AreaCalculator` / `RectangleArea`, on a `Rectangle`). Assume `use cgp::prelude::*;` in every snippet; the CGP version is v0.8.0. - -## What `#[cgp_component(Greeter)]` generates - -Applying the macro to a consumer trait produces five items: the consumer trait, the provider trait, two blanket impls, and the marker struct. Start from the trait, naming the provider trait in the attribute argument: - -```rust -#[cgp_component(Greeter)] -pub trait CanGreet { - fn greet(&self); -} -``` - -The first item is the **consumer trait**, emitted unchanged. This is the self-style trait callers use (`CanDoX`), so a caller writes `person.greet()` exactly as with any trait: - -```rust -pub trait CanGreet { - fn greet(&self); -} -``` - -The second item is the **provider trait**, the same interface with `Self` moved out into an explicit leading `Context` type parameter and every `self`/`Self` rewritten to `context`/`Context`. It is named in noun form (`SomethingDoer`, or `…Provider` when no noun fits), and it carries an `IsProviderFor` supertrait that captures the component, the context, and a `Params` tuple of any extra type parameters — `()` when there are none: - -```rust -pub trait Greeter: - IsProviderFor -{ - fn greet(context: &Context); -} -``` - -A provider trait is implemented not for the context but for a dedicated zero-sized **provider** -struct — a type-level marker that is never instantiated and carries no runtime value. Because a -provider implements `Greeter` for *its own* struct over a generic `Context`, the orphan and -overlap rules never bite, so `GreetHello`, `GreetGoodbye`, and any number of further providers for -the same component can all exist at once. See -[bypassing coherence](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/coherence.md) -(online) for why moving `Self` to a parameter is what sidesteps the rules, and -[modularity hierarchy](modularity-hierarchy.md) for the spectrum of how far to take the split. - -## How the two traits connect - -Two generated blanket impls bridge the consumer and provider sides, and together they make `person.greet()` resolve to a chosen provider without the caller naming it. Read them as the wiring machinery; you never write them. - -The first is the **consumer blanket impl**, which says that any context implementing the provider trait *for itself* automatically gets the consumer trait. It forwards `context.greet()` to `Context::greet(self)`: - -```rust -impl CanGreet for Context -where - Context: Greeter, -{ - fn greet(&self) { - Context::greet(self) - } -} -``` - -The second is the **provider blanket impl**, which lets any provider that delegates this component inherit the provider trait from whatever it delegates to. The delegation is a type-level table lookup through `DelegateComponent`, keyed on the `GreeterComponent` marker: - -```rust -impl Greeter for Provider -where - Provider: DelegateComponent - + IsProviderFor, - Provider::Delegate: Greeter, -{ - fn greet(context: &Context) { - Provider::Delegate::greet(context) - } -} -``` - -The fifth item is the **component marker**, a zero-sized key into those delegation tables: - -```rust -pub struct GreeterComponent; -``` - -These two examples use readable names for clarity; the emitted code uses reserved identifiers — `__Context__` for the context parameter (overridable) and `__Provider__` for the provider parameter — chosen so they never clash with a user's own type names. - -## Wiring is the table lookup that ties it all together - -**Wiring** is the step that supplies the delegation the provider blanket impl reads, by making a context into a type-level table whose entry for each component names the chosen provider. With the greeting component wired, the chain resolves end to end: `person.greet()` goes through the consumer impl to `Person` implementing the provider trait for itself, which goes through the provider impl to the table entry, landing on the selected provider's `greet`. Swapping the table entry is the only change needed to swap behavior; no caller is touched. - -```rust -#[derive(HasField)] -pub struct Person { - pub name: String, -} - -delegate_components! { - Person { - GreeterComponent: GreetHello, - } -} -``` - -The full table grammar — including per-value dispatch and presets — lives in [wiring](wiring.md). This file shows only the single-entry form needed to make the resolution concrete. - -## Why `IsProviderFor` exists - -`IsProviderFor` is an empty marker trait that rides along on every provider trait as a supertrait, and its only job is to make a missing dependency produce a readable error. A provider lists what it needs from the context in a `where` clause; when that clause is unmet, the bare question "does this provider implement the provider trait?" yields only "trait not implemented", because the provider blanket impl is also a candidate and Rust suppresses its detailed reasoning whenever more than one impl could apply. - -`IsProviderFor` is the second, independent path that un-hides the real reason. The macros implement it for a provider under *exactly the same* `where` bounds as the provider trait, and because that impl is the only candidate (no competing blanket), Rust commits to it and prints the precise unsatisfied constraint. The practical translation a reader needs: an `IsProviderFor` not implemented error means the provider trait is not implemented, and the named bound is the missing dependency. The trait is generated and consumed entirely by the macros — you observe it in errors, you never write it. - -```rust -#[diagnostic::on_unimplemented( - note = "You need to add `#[cgp_provider({Component})]` on the impl block for CGP provider traits" -)] -pub trait IsProviderFor {} -``` - -## Writing providers - -A provider can be written at three levels of sugar over the same machinery, and `#[cgp_impl]` is the one to reach for. The lower forms exist for when the native provider-trait shape is wanted explicitly, and they are what `#[cgp_impl]` desugars to. - -The lowest form is `#[cgp_provider]`, applied to a provider-trait impl written directly on a provider struct. It passes the impl through unchanged and auto-generates the matching `IsProviderFor` impl from the same `where` clause, so the dependency set can never drift. The provider struct must already exist: - -```rust -pub struct RectangleArea; - -#[cgp_provider] -impl AreaCalculator for RectangleArea -where - Context: HasDimensions, -{ - fn area(context: &Context) -> f64 { - context.width() * context.height() - } -} -``` - -That expands to the impl above plus the empty marker impl carrying the same bound, which is what surfaces a missing `HasDimensions` as a named error: - -```rust -impl IsProviderFor for RectangleArea -where - Context: HasDimensions, -{} -``` - -The optional attribute argument overrides the component type, defaulting otherwise to the provider trait's name plus a `Component` suffix; pass it explicitly only when the trait name does not follow that convention. - -The middle form is `#[cgp_new_provider]`, identical to `#[cgp_provider]` but it also declares the provider struct, folding `pub struct RectangleArea;` into the same block. Use it when introducing a fresh provider so you need not write the struct separately; a generic provider yields a struct with a `PhantomData` field over its parameters. - -The preferred form is `#[cgp_impl]`, which lets you write the provider in **consumer-style syntax** — keeping `self`, `Self`, and the consumer trait's method signatures — and mechanically rewrites it into the provider-trait shape. The provider name moves into the attribute argument instead of the `Self` position; a leading `new` keyword declares the struct; and you may omit `for Context` entirely, letting the macro insert the context parameter for you: - -```rust -#[cgp_impl(new RectangleArea)] -impl AreaCalculator -where - Self: HasDimensions, -{ - fn area(&self) -> f64 { - self.width() * self.height() - } -} -``` - -The one rule this convenience must not let you forget: inside a `#[cgp_impl]` block, `self` and `Self` mean the **context**, never the provider struct. The provider has no runtime value, so the macro rewrites every `self` to the context value and every `Self` to the context type — those are the only things that exist when the method runs. - -`#[cgp_impl]` desugars to `#[cgp_provider]` (or `#[cgp_new_provider]` when `new` is given). The block above is equivalent to writing the context out by hand and lowering it: - -```rust -#[cgp_new_provider] -impl<__Context__> AreaCalculator<__Context__> for RectangleArea -where - __Context__: HasDimensions, -{ - fn area(__context__: &__Context__) -> f64 { - __context__.width() * __context__.height() - } -} -``` - -The receiver `&self` became `__context__: &__Context__` — the receiver identifier is the snake-cased context name wrapped in double underscores — and `Self` in the `where` clause became the context type. When you write `for Context` explicitly, that name is used instead of `__Context__`, which is worth doing when you need to bound or refer to the context readably. - -## Impl-side dependencies - -A provider states what it needs from the context as bounds in its `where` clause, and those bounds — -**impl-side dependencies** — are constraints the consumer trait never exposes. `CanCalculateArea` -declares only `area`, while `RectangleArea` requires `Context: HasDimensions`; a caller bounding on -`CanCalculateArea` never sees `HasDimensions`, so the requirement stays one level down and does not -cascade through transitive callers. This is dependency injection through the `where` clause: any -context satisfying the bound gains the capability automatically, and the wiring satisfies each bound -by resolving it through the same context. See -[impl-side dependencies](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/impl-side-dependencies.md) -(online) for the full treatment, and [functions and getters](functions-and-getters.md) for the -value-injection forms (`#[implicit]` arguments and getters) that read fields off the context through -the same mechanism. - -## Which items belong in one component - -**A component trait may declare as many items as any Rust trait — the question is not how many, but how -many independent *choices* they represent.** Everything in one component is answered by one provider, so -group the items a single provider choice decides together and separate the ones different choices decide. -Most application capabilities are one decision and therefore one method, which is why single-method -components dominate; the count follows from the principle rather than being a limit. - -Two groupings of several items are right rather than merely allowed. **A method plus the associated type it -produces**: a provider that answers *how* also answers *what comes back*, which is why CGP's own -`CanCompute`, `CanHandle`, and `CanProduce` each declare `type Output` beside their method, and why a -`CanQueryDatabase` with `type Row` and `query` is good design — splitting `Row` out would let a context -pair the Postgres querier with the SQLite row type. **A getter component grouping several field reads**: a -getter is answered by its own method name rather than by a strategy, so one `UseFields` provider satisfies -every method at once, and there is nothing to split. The trade-off there is that `UseField` and -`WithProvider` are emitted only for a single-method getter trait, so a getter wired to a differently named -field needs its own component. - -Grouping items that answer to *different* choices costs three things, and the cost rises with how unrelated -they are rather than with the count. Every provider carries the **union of its methods' dependencies**, so -a capability one method needs is imposed on all of them and on every context wiring that provider. A -[higher-order provider](higher-order-providers.md) must **implement every item**, forwarding the ones it -has no opinion about — a single-decision component wraps in four lines, while a wrapper over an entity -trait is mostly passthrough that grows with every method added. And a context or provider needing part of -the surface must **still answer all of it**, which in practice means placeholder associated types and -`unimplemented!()` bodies, most often in mock contexts written for tests. - -Two checks catch a component that has grown past one decision. A consumer trait named after a noun rather -than a verb usually holds several. And if no provider for the trait could ever be reused *whole* by a -second context, the machinery is not paying for itself — implement the trait directly on the concrete -context instead, per the section below. To break one up, split along the axis on which the contexts you -actually want differ: the methods whose dependencies are shared across those contexts become components -with reusable providers, and the ones that must differ get a direct impl on each context. The full -procedure and its costs are in -[sizing a component](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/guides/sizing-a-component.md) -(online). - -## A consumer trait is still an ordinary trait - -A consumer trait can also be implemented directly on a context, exactly like a vanilla Rust trait, when code reuse across providers is not the goal. The consumer/provider split is a superset of ordinary traits, not a replacement: the provider machinery is what you opt into when a capability needs more than one implementation, and skipping it costs nothing for the simple case. You write `impl CanGreet for Person { ... }` as usual, and `person.greet()` resolves to that direct impl with no wiring involved. - -## Further reference - -For the full expansion and accepted syntax of each macro, see the online docs: -[`#[cgp_component]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_component.md), -[`#[cgp_impl]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_impl.md), -[`#[cgp_provider]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_provider.md), -[`#[cgp_new_provider]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_new_provider.md), -and -[`IsProviderFor`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/is_provider_for.md). -For the concepts behind the split, see -[consumer and provider traits](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/consumer-and-provider-traits.md), -[bypassing coherence](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/coherence.md), -and -[impl-side dependencies](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/impl-side-dependencies.md). -For sibling sub-skills, see [wiring](wiring.md), [checking](checking.md), -[functions and getters](functions-and-getters.md), and -[higher-order providers](higher-order-providers.md). diff --git a/docs/ai/skills/references/components.md b/docs/ai/skills/references/components.md new file mode 120000 index 00000000..c3371b1b --- /dev/null +++ b/docs/ai/skills/references/components.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/components.md \ No newline at end of file diff --git a/docs/ai/skills/references/error-extraction.md b/docs/ai/skills/references/error-extraction.md deleted file mode 100644 index ef58267b..00000000 --- a/docs/ai/skills/references/error-extraction.md +++ /dev/null @@ -1,88 +0,0 @@ -# Extracting CGP compile errors - -How to turn a CGP compile error — often a wall of repeated failures naming generated types — into a compact, root-cause-first summary. This skill serves two roles, and which one applies depends on your task: an agent **extracting** an error reads raw compiler output and reduces it to a few facts, while an agent **delegating** hands a long error to a sub-agent so it never touches the main context. Both roles rely on the same shape knowledge, so read [The two shapes](#the-two-shapes-to-recognize) first, then jump to [Role 1 — extracting](#role-1--extracting-an-error-yourself) or [Role 2 — delegating](#role-2--delegating-the-extraction-to-a-sub-agent). - -**Prefer `cargo-cgp` first — this sub-skill is the fallback.** When -[`cargo-cgp`](https://github.com/contextgeneric/cargo-cgp) is available, it has already done this -extraction: it rewrites a recognized CGP error into a `[CGP-Exxx]` headline over a root-cause -dependency tree, which *is* the compact summary below. Reach for the manual technique here only when -the tool is not installed, or when it leaves an error largely as `rustc` wrote it (a class it does -not yet rewrite). The main [SKILL.md tooling section](../SKILL.md) covers installing and running the -tool; everything below is for reading raw compiler output by hand. - -## Why extraction is a skill of its own - -CGP error output is disproportionately large and disproportionately misleading, so reading it well is a distinct task from fixing the code. Wiring is resolved [lazily](checking.md), so one broken link surfaces at every place that transitively needs it, and each failure quotes *generated* code — `IsProviderFor`, `DelegateComponent`, `CanUseComponent`, and the type-level `Symbol`/`Chars`/`PathCons` spines you never wrote. A single missing field can print screens of near-identical errors. Worse, some of that output is actively deceptive: a whole class of CGP errors reports that a trait's bounds are unsatisfied while *hiding* the dependency that actually failed. Reading such output inline, in the agent trying to fix the code, wastes context on noise and risks chasing a cause the output does not contain. - -## The two shapes to recognize - -Before decoding any nested type, read the *trait* in the error and decide which of two shapes you are looking at, because the shapes differ in whether the root cause is even present. The [macro-grammar](macro-grammar.md) decoder and the [checking](checking.md) playbook cover the full set; extraction needs the one binary distinction. - -A **surfaced** error carries the root cause. It is an `E0277` note chain, typically topped by `CanUseComponent` or `IsProviderFor`, that names a concrete missing bound such as `HasField`. This is what a [`check_components!`](checking.md) assertion produces, because the check requires `IsProviderFor` as a *direct* bound and forces the compiler to evaluate the provider's `where` clause. The concrete bound is the fact to extract — the compiler names it in a `help:`/"is not implemented" note, and the `required for …` notes trace the dependency path from it back to the check. - -A **hidden** error does not. It is an `E0599` "the method `greet` exists for struct `Person`, but its trait bounds were not satisfied", or an `E0277` that a consumer trait like `Person: CanGreet` is unsatisfied, and it names the consumer or provider trait and then stops — with no note descending to the missing field or dependency. This happens when broken wiring is exercised by *calling the consumer-trait method directly* rather than through a check: the compiler sees the consumer trait's blanket impl among the candidate impls, finds it inapplicable, and suppresses the nested bound that made it so. The cause is **absent**, not buried. Do not scan a hidden error for a root cause; there is none to find. The fix is to *promote* it into a surfaced error — add a `check_components!` for the failing component at the wiring site — and read that instead. - -## The cheap first move: grep for the suspected line - -Before committing to either role, try to answer your question with a grep, because the main agent can often confirm or dismiss a hypothesis without reading the log itself or spawning a sub-agent to read it. This is the move to reach for whenever you have a specific suspicion — a field you think you forgot, a key you think you wired twice, a `UseContext` you think is a cycle — and the failing build is captured to a file. Grep is not a third role so much as the way to avoid needing Role 2: a targeted search costs a few lines of output where delegating costs a whole sub-agent turn, so a hypothesis you can phrase as a pattern is one you should grep for rather than delegate. - -Grep the error headlines first, because that one search does the classifying. -`grep -nE '^error' /tmp/cgp-error.txt` prints one line per error block — the code and the trait each -names — which decides the [shape](#the-two-shapes-to-recognize) and, with the -[macro-grammar decoder](macro-grammar.md), the class. A second grep for the class's signature then -confirms the cause: `grep -n 'help:'` for a surfaced dependency leaf (a `HasField>` spells -the field name letter-by-letter on one line), `conflicting implementation` for a duplicate key, -`overflow evaluating` for a cycle, `does not contain any DelegateComponent entry` for an unwired -component, `is not constrained` for an unconstrained generic, and so on. The -[debugging guide's grep table](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/guides/debugging.md#grep-for-the-suspected-line-instead-of-reading-the-whole-log) -lists the signature line for every class. - -Two limits decide when grep gives way to a full read or a delegation. A **hidden** error cannot be grepped: if the only headline is an `E0599` "method … exists … but its trait bounds were not satisfied", the cause is absent from the output, so promote it with a `check_components!` and re-run rather than searching for a leaf that is not there. And when the headline grep shows several unrelated classes at once, or the cause hides behind an elided `...` whose full form sits in a `long-type-….txt` file, the search will not converge — that is the point to escalate to [Role 2](#role-2--delegating-the-extraction-to-a-sub-agent) and let a sub-agent absorb the whole log. The rule is the same throughout: a targeted question is a grep, an open-ended read is a delegation. - -## Role 1 — extracting an error yourself - -You are in this role whenever you are the one reading the raw output — as a sub-agent handed the job, or as the main agent facing an error short enough to read inline. Your product is the [compact summary](#reduce-to-the-compact-summary) below, never the raw dump. - -### Capture the output without flooding context - -Capture the compiler output to a file rather than letting it stream into your transcript, and target the smallest unit that reproduces the failure. A whole-workspace build multiplies the cascade across crates; a single crate, test, example, or ten-line scratch module shrinks it to the one thing you care about. The commands are just your project's ordinary build and test invocations — nothing CGP-specific: - -```bash -# Target the smallest failing unit and redirect everything to a scratch file. -cargo check -p 2>&1 | tee /tmp/cgp-error.txt - -# or a single test / example that exercises the failing wiring: -cargo test -p --test 2>&1 | tee /tmp/cgp-error.txt -``` - -Two details recur, both plain `rustc` behavior rather than anything CGP-specific. When a type in the error is elided as `...`, the compiler writes its full form to a file named in a final note (`the full name for the type has been written to '….long-type-….txt'`); that elided middle is frequently the one segment that reveals *which* context or path the error is about, so read that file when the cause hinges on a long type. And watch for the **near-contradiction** shape — "the trait `X` is not implemented for `T`" immediately followed by a `help:` note that `X` *is* implemented for `T` — which means an impl exists but a nested bound it carries does not hold, or two candidates are ambiguous; trust the error, not the `help:`. - -When the cause hinges on *what the macro emitted* rather than on the message itself, stop reading the error and read the expansion. Reach for `cargo cgp expand` first: it prints the crate after macro expansion with CGP's type-level constructs resugared, so a field tag that the error rendered as a `Chars` spine reads `Symbol!("height")` in the expansion — the generated code is often easier to read than the diagnostic about it. Narrow it to the part you care about, since a whole crate's expansion is long and a filtered one keeps your context clear: - -```sh -cargo cgp expand --lib --item AreaCalculator # a trait: every impl of it — what a component generated -cargo cgp expand --lib --item contexts::MockApp # a type: its HasField impls and its wiring entries -cargo cgp expand --lib > /tmp/expanded.rs # or redirect the whole thing and grep it -``` - -Pass `--lib` or `--bin NAME` when the package has several targets, or cargo refuses to run. Plain `cargo expand` is the fallback where `cargo cgp expand` is unavailable — it shows the same expansion without the resugaring — and in a project set up with the CGP test utilities the `snapshot_*!` helpers from `cgp-macro-test-util` additionally pin an expansion as a reviewable snapshot. The [macro-grammar](macro-grammar.md) skill covers how to read the expanded impls once you have them. - -### Reduce to the compact summary - -Reduce the output to the same few facts — the anatomy a CGP error catalog records — and nothing more: - -- **Class and code** — the error code(s) and the trait(s) named (`E0599` on a provider trait, `E0277` through `CanUseComponent`, `E0119` conflicting `DelegateComponent`, `E0207` unconstrained generic, and so on). -- **Hidden or surfaced** — whether the root cause is present in the output at all. -- **Root cause and position** — if surfaced, the concrete failing bound and where it sits (in the compiler's `help:` note, near the last or second-to-last block of a cascade, or inside the `long-type-….txt` file); if hidden, say so plainly. -- **Recommended next action** — fix the named field or wiring, promote a hidden error with a `check_components!`, break a cycle, remove a duplicate key — whatever the class implies. - -A good summary is a few lines, not a transcript. Never hand back the raw output; that defeats the purpose of extracting it. - -## Role 2 — delegating the extraction to a sub-agent - -You are in this role when you are the main agent and the error is long — a deep cascade, many crates, or output that runs to screens. Spawn a sub-agent to read it and return only the [compact summary](#reduce-to-the-compact-summary); the sub-agent absorbs the wall of text while you keep your own context clean. Give the sub-agent three things: the exact command to run (or the path to an already-captured output file), this skill so it knows the two shapes and the summary format, and the instruction to return *only* the summary. This is the intended workflow both when documenting an error class — where a sub-agent gathers the facts from a failing reproduction — and in an ordinary debugging session, where a sub-agent reads an error too long to justify reading inline. When the returned summary says the error is hidden, the follow-up is almost always to add a check and re-run, which itself may be worth delegating. - -## Further reference - -- Sibling skills: [checking](checking.md) for why wiring is lazy and how checks force a surfaced error; [macro-grammar](macro-grammar.md) for the full error decoder and how to read an expansion; [wiring](wiring.md) for the delegation mechanics behind a conflict or cycle. -- Online: the [error catalog](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp/errors) documents each error class and where its root cause sits, and the [debugging guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/guides/debugging.md) is the full tracing playbook. diff --git a/docs/ai/skills/references/error-extraction.md b/docs/ai/skills/references/error-extraction.md new file mode 120000 index 00000000..9cc46637 --- /dev/null +++ b/docs/ai/skills/references/error-extraction.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/error-extraction.md \ No newline at end of file diff --git a/docs/ai/skills/references/error-handling.md b/docs/ai/skills/references/error-handling.md deleted file mode 100644 index 1e80d523..00000000 --- a/docs/ai/skills/references/error-handling.md +++ /dev/null @@ -1,138 +0,0 @@ -# Error handling - -CGP's modular error handling: one shared abstract `Error` type per context, plus pluggable behavior for constructing that error from a source error and for attaching detail to it. - -Generic CGP code must be able to fail without naming a concrete error type. A provider that hits a fallible operation gets back a `parse error`, an `io::Error`, or a string, yet it is generic over the context and cannot commit to `anyhow::Error` or any other choice — that choice belongs to the application assembling the context. CGP resolves this with three cooperating [components](components.md): `HasErrorType` gives the context one abstract `Self::Error`, `CanRaiseError` constructs that abstract error from a concrete source error, and `CanWrapError` enriches an existing abstract error with extra detail. The concrete error type and the raising/wrapping behavior are decided once, at [wiring](wiring.md) time, by whichever error backend the context plugs in. - -A note on imports: the consumer traits `HasErrorType`, `CanRaiseError`, and `CanWrapError` come through `use cgp::prelude::*;`, but the wiring keys and backend providers below do not. The component markers (`ErrorTypeProviderComponent`, `ErrorRaiserComponent`, `ErrorWrapperComponent`) live under `cgp::core::error`, and the backend providers (`RaiseFrom`, `ReturnError`, `DebugError`, `DisplayError`, and the rest) live under `cgp::extra::error`, so a module that wires error handling imports the specific names it uses, for example `use cgp::core::error::ErrorRaiserComponent;` and `use cgp::extra::error::RaiseFrom;`. - -## `HasErrorType`: the shared abstract error - -`HasErrorType` is the abstract-type component that gives a context a single shared `Error` type, and every fallible CGP operation refers to it. It is declared with `#[cgp_type]`, so it behaves like any other [abstract type](abstract-types.md) — a trait with one associated type, wired through a provider rather than hand-implemented: - -```rust -#[cgp_type] -pub trait HasErrorType { - type Error: Debug; -} - -pub type ErrorOf = ::Error; -``` - -The `Debug` bound lets `Self::Error` flow into `.unwrap()` and straightforward logging without an extra constraint, and it is enforced on whatever concrete type a context chooses. `ErrorOf` is the convenient spelling of the associated-type path. Generic code that may fail returns `Result` (or `Result>`) and never names a concrete error. - -Centralizing the error type on one trait is what lets errors compose. A context trait that may fail depends on `HasErrorType`, so every such trait refers to the *same* error; if each declared its own associated `Error`, a context bounded by several of them would face several incompatible error types with no way to unify them. `HasErrorType` carries no methods — it only declares the type. The behavior of producing errors lives in the traits that build on it. The preferred way to author such a trait is [`#[use_type(HasErrorType.Error)]`](abstract-types.md), which adds `HasErrorType` as a supertrait *and* rewrites a bare `Error` in the signatures to `::Error` — so you write neither `: HasErrorType` nor `Self::Error` by hand. - -Because `#[cgp_type]` generates a `UseType` blanket impl, a context fixes its error type by wiring the error-type component to `UseType`, exactly as for any abstract type: - -```rust -#[cgp_component(Validator)] -#[use_type(HasErrorType.Error)] -pub trait CanValidate { - fn validate(&self) -> Result<(), Error>; -} - -pub struct App; - -delegate_components! { - App { - ErrorTypeProviderComponent: UseType, - } -} -``` - -Here `#[use_type(HasErrorType.Error)]` makes `CanValidate` depend on the shared abstract error and lets `validate` name it as the bare `Error`, and `App` fixes that error to `String`. The standalone backends (`cgp-error-anyhow`, `cgp-error-eyre`, `cgp-error-std`) supply ready-made providers that set `Error` to their respective library types instead. A context can equally implement the trait directly — `impl HasErrorType for App { type Error = String; }` — which makes plain that it is an ordinary trait with a `Debug`-bounded associated type. - -## `CanRaiseError` and `CanWrapError`: producing and enriching the error - -`CanRaiseError` is the consumer trait for turning a concrete source error into the context's abstract error, and `CanWrapError` is the companion that attaches detail to an existing one. Both import the error type with `#[use_type(HasErrorType.Error)]` — so they name it as the bare `Error` and gain `HasErrorType` as a supertrait — and both are `#[cgp_component]`s that delegate per type so a context can handle each source error or detail with a different provider: - -```rust -#[cgp_component(ErrorRaiser)] -#[derive_delegate(UseDelegate)] -#[use_type(HasErrorType.Error)] -pub trait CanRaiseError { - fn raise_error(error: SourceError) -> Error; -} - -#[cgp_component(ErrorWrapper)] -#[derive_delegate(UseDelegate)] -#[use_type(HasErrorType.Error)] -pub trait CanWrapError { - fn wrap_error(error: Error, detail: Detail) -> Error; -} -``` - -`raise_error` takes the source error by value and returns the abstract error; `wrap_error` takes the current abstract error plus a `Detail` and returns an enriched one. Both are associated functions with no `self` receiver — raising and wrapping are properties of the context *type*, so generic code calls `Context::raise_error(source)` and `Context::wrap_error(err, detail)` where only the type parameter is in scope. The `#[cgp_component(...)]` attribute names the provider traits `ErrorRaiser` and `ErrorWrapper`, and `#[derive_delegate(UseDelegate<...>)]` makes each dispatch per `SourceError` or `Detail` type through a delegation table. - -A provider written against these bounds names neither the context nor its concrete error type: - -```rust -#[cgp_component(Loader)] -#[use_type(HasErrorType.Error)] -pub trait CanLoad { - fn load(&self, path: &str) -> Result; -} - -#[cgp_impl(new LoadOrFail)] -#[uses(CanRaiseError, CanWrapError)] -#[use_type(HasErrorType.Error)] -impl Loader { - fn load(&self, path: &str) -> Result { - if path.is_empty() { - let err = Self::raise_error("empty path".to_owned()); - return Err(Self::wrap_error(err, format!("while loading {path}"))); - } - Ok(format!("contents of {path}")) - } -} -``` - -The provider requires `CanRaiseError` to turn a message into the abstract error and `CanWrapError` to attach context as it propagates — both [impl-side dependencies](components.md) that any wired context satisfies by plugging in providers. The context decides, through wiring, what concrete error type `load` actually produces. - -## Wiring the behavior: error-backend providers - -A context gains raising and wrapping by wiring `ErrorRaiserComponent` and `ErrorWrapperComponent` to providers, exactly like any other component. The `cgp-error-extra` crate supplies a family of zero-sized providers (the [providers](components.md) are markers with no runtime value) that are generic over the context's error type and capture cross-cutting strategies independent of any one error library; they sit alongside the standalone backends, which specialize to a concrete library error such as `anyhow::Error`. A typical context wires a mix: a backend for the concrete error type plus these generic providers for the strategies. The raisers, wrappers, and their bounds are: - -- `RaiseFrom` implements `ErrorRaiser` by converting through `From` — it raises any source error whose `Context::Error: From`, the default choice when the abstract error already absorbs the source. -- `ReturnError` implements `ErrorRaiser` for the case where the source *is* the abstract error (`HasErrorType`), returning it untouched. -- `RaiseInfallible` implements `ErrorRaiser` for `core::convert::Infallible`, producing the error by an empty `match` that can never run — letting code parameterized over a fallible operation be wired uniformly even when the chosen operation cannot fail. -- `PanicOnError` implements `ErrorRaiser` by `panic!`-ing with the source error's `Debug` output instead of returning a value — for contexts that treat an error as a fail-fast fault, such as tests. -- `DiscardDetail` implements `ErrorWrapper` by dropping the detail and returning the error unchanged — the wrapping no-op, for error types that cannot carry extra context. -- `DebugError` and `DisplayError` implement *both* components by formatting the source error or detail into a `String` and forwarding to the context's own `CanRaiseError` / `CanWrapError` — `DebugError` via `Debug`, `DisplayError` via `Display`/`to_string()`. Both live behind the crate's `alloc` feature. - -The simplest wiring delegates to a single provider. Wiring `RaiseFrom` lets `App` raise any source error its abstract error implements `From` for: - -```rust -delegate_components! { - App { - ErrorRaiserComponent: RaiseFrom, - } -} -``` - -The string-formatting providers are designed to *compose* with the others rather than replace them: `DebugError` and `DisplayError` do not know the context's error type, they only reduce a `Debug` or `Display` value to a `String` and hand it off, so the context must separately wire a provider that handles the `String` source. Because both components dispatch per source-error type, the idiomatic wiring lists one entry per source error — a concrete string-raising rule plus formatting redirects for everything else — opened on the component with the `open` statement of `delegate_components!`: - -```rust -delegate_components! { - App { - open ErrorRaiserComponent; - - @ErrorRaiserComponent.String: RaiseFrom, - @ErrorRaiserComponent.ParseError: DebugError, - } -} -``` - -The `open ErrorRaiserComponent;` header opens the component for per-type wiring, and each `@ErrorRaiserComponent.: Provider` entry assigns the provider for one source-error type, folded directly into `App`'s own table — `open` needs no `#[derive_delegate]` of its own because every `#[cgp_component]` already generates the `RedirectLookup` impl it dispatches through. The legacy equivalent writes the same per-type entries into a separate `UseDelegate` nested table; that form is still common in existing code but is slated for deprecation, so prefer `open` for new wiring. See [wiring](wiring.md) for both forms. - -A raised `String` is converted straight into the abstract error by `RaiseFrom`, while a raised `ParseError` is formatted with `Debug` by `DebugError` and then routed back through the `String` entry — which `RaiseFrom` handles — yielding one coherent error type from two unrelated sources. The choice of provider is therefore also a statement about which source errors the context accepts and how, and each wiring is verified with `check_components!` like any other. - -## Related constructs - -`HasErrorType` is an [abstract type](abstract-types.md) declared with `#[cgp_type]`, so it is wired with `UseType` or a backend provider the same way every abstract type is. `CanRaiseError` and `CanWrapError` are ordinary [components](components.md) that supertrait it, wired with `delegate_components!` as covered in [wiring](wiring.md), and their `#[derive_delegate(UseDelegate<...>)]` is what lets a context dispatch raising and wrapping per source-error or detail type through a delegation table. - -Further reference (online): -[components/has_error_type.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/has_error_type.md), -[components/can_raise_error.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/can_raise_error.md), -[providers/error_providers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/error_providers.md). diff --git a/docs/ai/skills/references/error-handling.md b/docs/ai/skills/references/error-handling.md new file mode 120000 index 00000000..b03d7f1c --- /dev/null +++ b/docs/ai/skills/references/error-handling.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/error-handling.md \ No newline at end of file diff --git a/docs/ai/skills/references/extensible-data.md b/docs/ai/skills/references/extensible-data.md deleted file mode 100644 index 2c1272b1..00000000 --- a/docs/ai/skills/references/extensible-data.md +++ /dev/null @@ -1,163 +0,0 @@ -# Extensible data - -Treat a struct as a product of named fields and an enum as a sum of named variants, so that generic code can read, build, deconstruct, and convert any data type by its type-level field and variant names rather than by naming the concrete type. - -A plain Rust `struct` or `enum` is opaque to generic code: nothing about "the `first_name` field" or "the `Circle` variant" can be named through a type parameter, so a struct literal must list every field at one site and a `match` must spell out every variant. Extensible data breaks that by deriving a type-level description of a type's shape — its fields or variants, each tagged by name — and the machinery to build, take apart, and convert values through that description. This brings row polymorphism and structural sum types to Rust, resolved entirely at compile time, and it is what lets independent components each contribute one field or handle one variant without knowing the whole type. The result feeds directly into CGP wiring: builders, variant dispatchers, and structural casts all consume the field-level machinery these derives generate. A context is just such a data type when it flows through providers this way. - -The whole family is dual. A record is a product (every field present at once); an enum is a sum (exactly one variant present). The two share their presence markers, their casting traits, and their dispatch machinery, so reading one half tells you the shape of the other. - -## The umbrella derive and its shape-specific faces - -`#[derive(CgpData)]` is the high-level entry point: applied to a struct it emits the full record machinery, applied to an enum the full variant machinery, dispatching on the item kind. `#[derive(CgpRecord)]` and `#[derive(CgpVariant)]` are the same code paths restricted to one shape — use them when the type is always a struct or always an enum and you want the name to say so; applying the wrong one is a type error. The narrower building-block derives (`HasFields`, `HasField`, `BuildField`, `ExtractField`, `FromVariant`) each emit one slice of that output when you want only part of it. - -```rust -#[derive(CgpData)] -pub struct Person { pub first_name: String, pub last_name: String } - -#[derive(CgpData)] -pub enum Shape { Circle(Circle), Rectangle(Rectangle) } -``` - -Field tags drive everything generated. A named struct field or an enum variant is keyed by the type-level string `Symbol!("name")`, and an unnamed field of a tuple struct by its positional `Index`; that tag is what addresses the field across every generated impl. One restriction shapes the variant side: a derivable enum must follow the sum-of-products form, where each variant holds exactly one unnamed payload — wrap a richer payload in a dedicated struct so the variant's value stays a single nameable type. A fieldless, multi-field, or struct-style variant is a compile error. - -## Records: the whole-struct field view - -`#[derive(HasFields)]` gives a type its whole-shape view, the foundation everything else builds on. For a struct it implements `HasFields` with a `Fields` associated type that is a [`Product!`](type-level-primitives.md) of `Field` entries — the type-level spelling of the struct's layout, one entry per field tagged by name: - -```rust -impl HasFields for Person { - type Fields = Product![ - Field, - Field, - ]; -} -``` - -The derive also emits the conversions that move values in and out of that representation: `ToFields` turns an owned value into its `Fields` product, `FromFields` rebuilds the value from one, and `ToFieldsRef` borrows it as a product of references. Generic algorithms bound `Context: HasFields` (or `ToFields`/`FromFields`) and fold over `Context::Fields` structurally, never naming the concrete struct. This whole-shape view is distinct from per-field indexed access: reading a single field by name is `HasField`, the dependency-injection capability that getter traits resolve against (see [functions and getters](functions-and-getters.md)). A struct that wants both derives both. - -## Records: building a struct field by field - -The capability `#[derive(CgpRecord)]` and `#[derive(BuildField)]` add on top of reading is incremental, type-checked construction, exposed through the builder trait family. Construction runs through a *partial record* — a generated companion struct `__Partial{Name}` carrying one `MapType` marker per field that records whether that field is present yet. The marker `IsPresent` stores the field's real value, `IsNothing` stores `()`, so a partial record with every marker `IsNothing` is an empty builder and one with every marker `IsPresent` is a fully populated value. The family walks between these states. - -```rust -let employee: Employee = Employee::builder() // every field IsNothing - .build_from(person) // first_name + last_name now IsPresent - .build_field(PhantomData::, 1) // employee_id now IsPresent - .finalize_build(); // exists only at the all-present configuration -``` - -`HasBuilder::builder()` produces the empty partial record; `BuildField::build_field` flips one marker from `IsNothing` to `IsPresent`; and `FinalizeBuild::finalize_build` turns the partial record back into the concrete struct. Underneath, both `BuildField` and its reverse `TakeField` (the `IsPresent → IsNothing` direction) are blanket impls over a single per-field primitive `UpdateField`, which changes one field's marker and returns the old value alongside the rebuilt partial. The tracking is what makes the pattern safe: `finalize_build` is implemented *only* for the all-`IsPresent` configuration, so finalizing with any field still absent is a compile error rather than a runtime panic, and the order in which fields are built does not matter. The reverse direction is equally useful — `IntoBuilder` turns a complete struct into an all-present partial, and `TakeField` removes fields one at a time. - -That all-present strictness is sometimes too rigid — a record may have fields with sensible defaults or ones genuinely allowed to be absent. The `cgp-field-extra` **optional-field** extension relaxes it in two controlled ways while reusing the same `UpdateField` machinery: it can fill an unset field with `Default::default()` at finalize time, and it can track a field as an `Option` (the `IsOptional` marker) so absence becomes a runtime value rather than a compile error. Reach for it when a struct has optional or defaulted fields; the strict all-present builder above remains the default. - -## Records: the extensible builder pattern - -`CanBuildFrom` (one of the structural casts below) is what lets a builder absorb the shared fields of an entire source struct in one `build_from` step: it recurses over the source's field product, using `TakeField` to pull each field out and `BuildField` to write it into the target builder. So a small struct like a database client can be merged into a larger application struct without either type naming the other — they share only field names, matched at the type level. This is the basis of the *extensible builder pattern*, where the construction of one context is split across several independent providers, one per subsystem, none of which knows the final type or each other. Each provider builds a small output struct, and a dispatcher merges every output into the target's builder before finalizing. - -```rust -delegate_components! { - FullAppBuilder { - HandlerComponent: - BuildAndMergeOutputs, - } -} -``` - -Because the dispatcher is generic over the target struct and the provider list, swapping a subsystem means changing one entry, and selecting among several target structs is a matter of code-based dispatch. The `BuildAndMergeOutputs` combinator and the rest of this routing live in [handlers](handlers.md). - -## Variants: constructing and deconstructing an enum - -For an enum, `#[derive(HasFields)]` produces a `Fields` that is a [`Sum!`](type-level-primitives.md) of `Field` entries built on the `Either`/`Void` spine, mirroring the product side. Construction is `FromVariant`, generated per variant by `#[derive(FromVariant)]`: it builds the enum from one variant chosen by a type-level tag, so generic code parameterized over a `Tag` can construct whichever variant it was asked for. - -```rust -fn wrap_circle(circle: Circle) -> Shape { - Shape::from_variant(PhantomData::, circle) // == Shape::Circle(circle) -} -``` - -Deconstruction is the dual of the builder and runs through a *partial variant* — the companion enum `__Partial{Name}` generated by `#[derive(ExtractField)]`, carrying one `MapType` marker per variant just as a partial record carries one per field. The crucial difference is the absence marker: a record uses `IsNothing` (storing `()`), while a variant uses `IsVoid`, mapping a ruled-out variant to the uninhabited `Void` type. `HasExtractor::to_extractor` converts the enum into a partial variant with every variant still `IsPresent`, and `ExtractField::extract_field` tries to pull out one variant, returning `Ok(value)` if the value is that variant or `Err(remainder)` — the partial variant with that variant flipped to `IsVoid` — otherwise. - -```rust -fn area(shape: Shape) -> f64 { - match shape.to_extractor().extract_field(PhantomData::) { - Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, - Err(remainder) => { - // remainder's type now has Circle ruled out (IsVoid); try the next variant - let rect = remainder - .extract_field(PhantomData::) - .finalize_extract_result(); // remainder is now empty; this cannot fail - rect.width * rect.height - } - } -} -``` - -Marking extracted variants as `IsVoid` is what gives compile-time exhaustiveness without a wildcard arm. Each failed `extract_field` rules out one more variant in the type, so after every variant has been tried the remainder has every marker `IsVoid` and is therefore uninhabited. `FinalizeExtract::finalize_extract` discharges such a remainder with an empty `match`, sound precisely because no value can reach it — and `FinalizeExtractResult::finalize_extract_result` is the convenience wrapper that collapses the final `Result` into its `Ok` value. Add a variant to the enum without handling it and the final remainder becomes inhabited again, so the code fails to compile until the new variant is covered, recovering the guarantee a concrete `match` gives. `HasExtractorRef` and `HasExtractorMut` provide the same machinery over borrows. - -## Variants: the extensible visitor pattern - -Routing a value to the handler for its current variant is the *extensible visitor pattern*, which solves the expression problem: new variants can be added without touching the handlers for the others, and the same handler set can serve several enums that share variants. The logic for each variant lives in its own provider, and a dispatcher derives one extract-and-handle step per variant from the enum's `Fields`, running them as a pipeline that short-circuits on the first matching variant and threads the remainder forward otherwise. - -```rust -delegate_components! { - Interpreter { - ComputerComponent: - UseInputDelegate: EvalAdd, // one provider per variant - Times: EvalMultiply, - Literal: EvalLiteral, - }>, - } -} -``` - -The `MathExpr` entry routes the whole enum through a thin context-specific provider that defers to the matcher combinator; that wrapper exists to break the trait-resolution cycle between the matcher and the per-variant providers it dispatches to. The matcher combinators (`MatchWithValueHandlers` and its by-reference form) and the per-variant handler families live in [handlers](handlers.md). - -## The type-level spines underneath - -Both halves rest on the same right-nested type-level lists, kept brief here and covered fully in [type-level primitives](type-level-primitives.md). A struct's `Fields` is a `Product![A, B, C]`, which desugars to `Cons>>` over the `Cons`/`Nil` record spine — a list terminated by the constructible empty `Nil`, because an empty record is a valid value. An enum's `Fields` is a `Sum![A, B]`, which desugars to `Either>` over the `Either`/`Void` variant spine — a chain that branches at each step and terminates in the uninhabited `Void`, because an empty choice has no value to pick. The lowercase `product![..]` builds a value of the matching `Product!` type. Generic providers walk these spines one element at a time, which is exactly what no plain tuple or enum permits in generic code. - -The machinery above computes new spines from old ones through a small type-level list algebra you will meet in the traits it expands to: `AppendProduct` adds one field to the end of a product, `ConcatProduct` splices two products together, and `MapFields` rewrites every entry uniformly (the operation behind producing a partial record from a full one). All three are pure functions from type lists to type lists, evaluated by the compiler during type checking at no runtime cost — building a record appends, merging records concatenates, and forming a partial record maps a marker over every field. - -## Structural casts between records and variants - -Two types that share a subset of named fields or variants convert into one another generically, with no hand-written `From`/`TryFrom`, through the casting traits — every conversion is just routing each named entry to the matching slot in the target. `CanUpcast` lifts a value of a narrow enum into a wider one whose variants are a superset; it always succeeds, since every source variant has a home in the target, and it walks the source's variants, extracting each and reconstructing it via `FromVariant`. `CanDowncast` goes the other way, narrowing a wide enum into a smaller one and succeeding only if the value's current variant exists in the target, otherwise handing back a remainder; `CanDowncastFields` is the same operation on a remainder, so downcasting against several candidates chains a `downcast` followed by `downcast_fields`. `CanBuildFrom` is the record counterpart already met above, assembling a target builder out of the fields of one or more sources. - -```rust -let wide = FooBar::Foo(1).upcast(PhantomData::); // always succeeds -assert_eq!(wide, FooBarBaz::Foo(1)); - -FooBarBaz::Bar("hi".into()).downcast(PhantomData::).ok(); // Some(FooBar::Bar(..)) -FooBarBaz::Baz(true).downcast(PhantomData::).ok(); // None — Baz has no home in FooBar -``` - -Upcasting is also how a provider constructs a value using only the subset of variants it cares about: it builds a small local enum and upcasts it into the full type — the variant-side analog of reading a field through a getter. - -## Dispatching over extensible data - -The payoff of exposing data shape at the type level is that *dispatch* becomes generic: a record builder routes each field to the provider that produces it, and a variant visitor routes each value to the provider for its current variant. Both are realized with the dispatch combinators — `BuildAndMergeOutputs` on the record side, `MatchWithValueHandlers` on the variant side — which derive one per-field or per-variant step from the type's `Fields` and sequence them. Those combinators and the handler families they build on are documented in [handlers](handlers.md); the wiring tables that name a provider per [component](components.md) are the ordinary `delegate_components!` entries shown above. - -## Further reference - -Online docs (current as of CGP v0.8.0): -[concepts/extensible-records.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/extensible-records.md), -[concepts/extensible-variants.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/extensible-variants.md), -the derive references under -[reference/derives/](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/cgp/reference/derives) -(`derive_cgp_data.md`, `derive_cgp_record.md`, `derive_cgp_variant.md`, `derive_has_fields.md`, -`derive_build_field.md`, `derive_extract_field.md`, `derive_from_variant.md`), the trait references -[traits/has_builder.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/has_builder.md), -[traits/extract_field.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/extract_field.md), -[traits/from_variant.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/from_variant.md), -[traits/has_fields.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/has_fields.md), -and -[traits/cast.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/cast.md), -and the type macros -[macros/product.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/product.md) -and -[macros/sum.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/sum.md). diff --git a/docs/ai/skills/references/extensible-data.md b/docs/ai/skills/references/extensible-data.md new file mode 120000 index 00000000..d98e77d5 --- /dev/null +++ b/docs/ai/skills/references/extensible-data.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/extensible-data.md \ No newline at end of file diff --git a/docs/ai/skills/references/functions-and-getters.md b/docs/ai/skills/references/functions-and-getters.md deleted file mode 100644 index 187cc04e..00000000 --- a/docs/ai/skills/references/functions-and-getters.md +++ /dev/null @@ -1,314 +0,0 @@ -# Functions and Getters - -The ergonomic surface of basic CGP — `HasField` field access, `#[cgp_fn]` single-implementation capabilities, `#[implicit]` arguments, and getter traits — the constructs that let CGP code read like ordinary Rust functions and accessors. - -## How field access works underneath: `HasField` - -Every value a provider reads out of its context flows through one tiny consumer trait, `HasField`, which keys a single field by a *type-level* name rather than by the concrete struct it lives in. A provider is generic over its context and cannot reach into a struct it does not know, so instead of naming the field directly it demands one by tag: a `where`-clause bound `Context: HasField` says "any context wired to me must carry a `String` field called `name`," and the trait system supplies it. This makes field access an [impl-side dependency](components.md) — a requirement hidden from the trait interface and satisfied automatically by any matching context. Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. - -The trait carries the field's type as an associated `Value` and returns a reference, taking a `PhantomData` argument whose only job is to tell the compiler which field is meant when several `HasField` impls are in scope: - -```rust -pub trait HasField { - type Value; - fn get_field(&self, _tag: PhantomData) -> &Self::Value; -} -``` - -The `Tag` is a type-level name, and CGP has two kinds. A named struct field is keyed by `Symbol!("field_name")`, the type-level string of its identifier; a tuple field is keyed by `Index`, the type-level natural number of its position. Both are [type-level primitives](type-level-primitives.md) — types with no values — which is exactly why `get_field` needs the `PhantomData` argument to carry one at the call site. A `HasFieldMut: HasField` companion adds `get_field_mut` returning `&mut Self::Value` for the rarer mutable case. - -Reading a field is the PhantomData tag-inference trick in practice. Inside a provider body you write `self.get_field(PhantomData)` and let Rust infer the tag from the surrounding bound, or pin it explicitly with `self.get_field(PhantomData::)` when more than one field could match: - -```rust -#[cgp_impl(new GreetHello)] -impl Greeter -where - Self: HasField, -{ - fn greet(&self) { - println!("Hello, {}!", self.get_field(PhantomData)); - } -} -``` - -You almost never write `HasField` impls by hand. The companion derive does it for you. - -## Generating field access: `#[derive(HasField)]` - -`#[derive(HasField)]` turns a struct's concrete fields into the type-level entries the trait system looks up, emitting one `HasField` and one `HasFieldMut` impl per field and leaving the struct definition untouched. It is the bridge between an ordinary Rust struct and constraint-based field access: without it, a struct's fields are invisible to CGP, and every getter would be hand-written. For a named struct, - -```rust -#[derive(HasField)] -pub struct Person { - pub name: String, - pub age: u8, -} -``` - -the derive emits a `Symbol!`-keyed pair per field — `impl HasField for Person { type Value = String; … }` reading `&self.name`, and the same for `age` — so `Person` satisfies `HasField` exactly as the `GreetHello` bound above requires. A tuple struct expands identically except each field is keyed by its positional `Index` instead of a `Symbol!`: - -```rust -#[derive(HasField)] -pub struct Rectangle(pub f64, pub f64); -// → impl HasField> for Rectangle { type Value = f64; … &self.0 } -// → impl HasField> for Rectangle { type Value = f64; … &self.1 } -``` - -Generic parameters thread through faithfully, and field access also flows through smart pointers — `HasField` has a blanket impl over any `Deref` target that has the field, so a `Box` resolves `get_field` to the inner struct. Deriving `HasField` is the one thing a context must do for every higher-level construct on this page — `#[cgp_fn]`, `#[implicit]`, and both getter macros all desugar into `HasField` bounds. - -## Single-implementation capabilities: `#[cgp_fn]` - -`#[cgp_fn]` turns a plain function into a CGP capability that every context gains automatically, with no wiring step at all. A full [component](components.md) defines a consumer trait, a provider trait, and a delegation table so that many providers can be swapped per context; `#[cgp_fn]` is the lightweight counterpart for the common case where a capability has a single natural definition. You write the body as if `self` were concrete, and the macro emits a trait plus a *blanket* impl over a generic context — so the method becomes available on every type that satisfies the body's impl-side dependencies, with no `delegate_components!` block and no provider struct anywhere. - -The function name in snake case becomes the method name, and the trait name defaults to that name in PascalCase. Given: - -```rust -#[cgp_fn] -pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height -} -``` - -the macro emits a `RectangleArea` trait whose method takes no arguments, and a blanket impl over the reserved context type `__Context__` in which each `#[implicit]` parameter became a `HasField` bound and a `get_field` binding at the top of the body: - -```rust -pub trait RectangleArea { - fn rectangle_area(&self) -> f64; -} - -impl<__Context__> RectangleArea for __Context__ -where - Self: HasField - + HasField, -{ - fn rectangle_area(&self) -> f64 { - let width: f64 = self.get_field(PhantomData::).clone(); - let height: f64 = self.get_field(PhantomData::).clone(); - width * height - } -} -``` - -That generated blanket impl is the whole point of the macro, so it is worth seeing: the context type parameter is literally `__Context__` and references to it inside the impl read as `Self`. Pass an identifier to override the default trait name, which is useful when a verb-style name reads better — `#[cgp_fn(CanCalculateRectangleArea)]` generates `CanCalculateRectangleArea` instead of `RectangleArea`. - -Generics and `where` clauses are handled with a deliberate split: every generic parameter in the function's `<...>` list goes onto *both* the trait and the impl, while the function's `where` bounds land only on the impl, hidden from the trait as impl-side dependencies. A generic area function makes this concrete: - -```rust -#[cgp_fn] -pub fn rectangle_area( - &self, - #[implicit] width: Scalar, - #[implicit] height: Scalar, -) -> Scalar -where - Scalar: Mul + Copy, -{ - width * height -} -``` - -Here `Scalar` appears on `RectangleArea` and its impl, while `Scalar: Mul + Copy` stays on the impl only, ordered before the implicit `HasField` bounds (which are always appended last). One restriction is intentional: `#[cgp_fn]` does not support generics on the *method* itself — method-level generics belong to the trait and impl, and the rare genuine need for them is an advanced case better written as an explicit blanket impl or a full component. - -## Field access dressed as a function argument: `#[implicit]` - -The `#[implicit]` attribute marks a function argument as sourced from a context field instead of from the caller, so a provider reads like a function taking parameters while behaving like one injecting dependencies. This is the recommended on-ramp to CGP: a programmer who understands functions and arguments can write a complete provider without first meeting `HasField`, `Symbol!`, or `PhantomData`. Strongly prefer implicit arguments in basic code — they keep CGP looking like ordinary Rust. The argument name doubles as the field name, so `#[implicit] width: f64` reads as "this function needs a `width` of type `f64`," and the macro removes the argument from the signature, adds the matching `HasField` bound, and binds the value at the top of the body (as the `#[cgp_fn]` expansion above shows). - -The argument type controls how the field is read, following a small set of rules so the body always receives exactly the declared type. An owned type such as `f64` or `String` reads the field by reference and appends `.clone()`, leaving the context's field intact; the one special case to memorize is `&str`, which is backed by a `String` field and read with `.as_str()` rather than `.clone()`, letting the body borrow without forcing the context to store a `&str`: - -```rust -#[cgp_fn] -pub fn greet(&self, #[implicit] name: &str) { - println!("Hello, {}!", name); -} -// bound: HasField -// binding: let name: &str = self.get_field(PhantomData::).as_str(); -``` - -Three rules constrain where `#[implicit]` may appear. The function must take `self` as its first argument, since the field is read from it; the argument pattern must be a bare identifier, not a destructuring or `mut` pattern (clone inside the body for a mutable local); and a mutable implicit argument — one whose type carries a `&mut` (a `&mut T`, `&mut [T]`, `Option<&mut T>`, or `Option<&mut str>`) — must be the *only* implicit argument (and needs a `&mut self` receiver), since it reads through `get_field_mut` and borrows the whole context exclusively — immutable implicits are shared borrows and combine freely in any number. The access mode follows the argument's own type, not the receiver's: only an argument carrying a `&mut` reads through `get_field_mut` (a `&mut [T]` via an `AsMut<[T]>` field, an `Option<&mut T>` via `.as_mut()`, an `Option<&mut str>` via `.as_deref_mut()` on an `Option` field). `#[implicit]` is usable in both `#[cgp_fn]` and the methods of a `#[cgp_impl]` provider, with the same desugaring in each — inside `#[cgp_impl]` the `HasField` bounds simply join the provider impl's `where` clause. - -## Importing capabilities: `#[uses]` - -`#[uses(...)]` adds `Self: Trait<...>` bounds to a provider's `where` clause, written to read like a `use` import of the capabilities the body depends on. A provider that calls another `#[cgp_fn]` capability, or a [component](components.md) consumer trait, must require the context to implement it — a `where Self: SomeTrait` bound that reads as machinery. `#[uses(RectangleArea)]` instead reads as "this function uses the `RectangleArea` capability," and the macro turns each listed name into the corresponding `Self` bound on the impl so the body can call those methods directly on `self`. **The listed trait need not be a CGP construct**: `#[uses(Display)]` and `#[uses(AsRef<[u8]>)]` are accepted and preferred over the equivalent hand-written clause, since the attribute only cares that the bound is one a context can satisfy — so an ordinary Rust trait imports exactly as a capability does. Building a scaled area on top of the base one: - -```rust -#[cgp_fn] -#[uses(RectangleArea)] -pub fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 { - self.rectangle_area() * scale_factor * scale_factor -} -``` - -This adds `Self: RectangleArea` to the generated impl's `where` clause, alongside the `HasField` bound from the implicit `scale_factor` — the imported bound lands on the impl only, never on the trait, exactly like writing `where Self: RectangleArea` by hand. The simple `TraitIdent` form is the idiomatic one, since the attribute is meant to read like an import, but an entry may be any bound a `where` clause accepts, including an associated-type-equality binding such as `HasErrorType`. Reach for that sparingly: to pin an *abstract type*, prefer the [`#[use_type]` equality form](abstract-types.md) `#[use_type(HasErrorType.{Error = AppError})]`, which adds the bound *and* rewrites the type, over spelling the equality in `#[uses]`. When a provider imports several capabilities, list them all in one attribute separated by commas — `#[uses(CanQueryUserBalance, CanRaiseHttpError)]` — rather than stacking `#[uses(...)]` repeatedly; the combined form reads as a single dependency list. `#[uses(...)]` works in both `#[cgp_fn]` and `#[cgp_impl]`, and the imported capability may itself be defined either way. - -## Adding supertraits and trait bounds: `#[extend]` and `#[extend_where]` - -In `#[cgp_fn]`, the function's own `where` clauses are impl-side dependencies kept off the trait, so there is no place to write a supertrait by hand — `#[extend(...)]` is the only way to add one. Where `#[uses]` adds a hidden impl-side bound (the `use` equivalent), `#[extend]` promotes its bound to a *supertrait* of the generated trait — a public requirement every implementor satisfies and every caller may rely on (the `pub use` equivalent). The bound appears in two places: as a supertrait on the trait, so an associated type like `Self::Scalar` resolves and callers know the bound holds, and in the impl's `where` clause so the body can use it. The example below uses the abstract-type trait `HasScalarType` to make that two-placement behavior visible in one signature, but for an abstract-type supertrait like this, `#[use_type]` is the production form (see the note after it) and `#[extend]` is reserved for a non-type capability supertrait. A `#[cgp_fn]` over an abstract scalar type: - -```rust -pub trait HasScalarType { - type Scalar: Clone + Mul; -} - -#[cgp_fn] -#[extend(HasScalarType)] -pub fn rectangle_area( - &self, - #[implicit] width: Self::Scalar, - #[implicit] height: Self::Scalar, -) -> Self::Scalar { - width * height -} -// → pub trait RectangleArea: HasScalarType { fn rectangle_area(&self) -> Self::Scalar; } -``` - -`#[extend]` accepts the same simplified `TraitIdent` syntax as `#[uses]`, and is also usable on `#[cgp_component]`, where it is the preferred way to add a *non-type capability* supertrait: writing `#[extend(HasName)]` reads as importing a capability, whereas the native `pub trait CanGreet: HasName` syntax reads as OOP-style inheritance from a parent class, which a CGP supertrait is not. (For an abstract-type component whose associated type the signatures name, prefer `#[use_type]` instead, which adds the supertrait *and* rewrites the type — the recommended form for abstract-type components.) Its sibling `#[extend_where(...)]` adds *`where`-clause* predicates to the generated trait definition rather than supertraits, and is `#[cgp_fn]`-only. Unlike `#[uses]` and `#[extend]`, it accepts arbitrary predicates — including associated-type equality — so a generic parameter can carry a publicly visible bound: - -```rust -#[cgp_fn] -#[extend_where(Scalar: Clone)] -pub fn rectangle_area(/* … */) -> Scalar -where - Scalar: Mul, -{ /* … */ } -// → pub trait RectangleArea where Scalar: Clone { fn rectangle_area(&self) -> Scalar; } -``` - -The `Scalar: Mul` bound from the body stays an impl-side dependency, while `Scalar: Clone` from `#[extend_where]` is promoted onto the trait. **What that promotion buys is enforcement at the use site, not a bound callers inherit** — the distinction is easy to state backwards. A trait's `where` clause is a *precondition* on naming the trait rather than something elaborated to whoever holds it, so code generic over `Scalar` must still write `Scalar: Clone` in its own `where` clause; only a supertrait added with `#[extend]` is handed to callers. What promotion changes is that an unsatisfiable requirement is caught where the trait is named — `Ctx: RectangleArea` becomes an `E0277` with a `required by a bound in RectangleArea` note — whereas the same bound left on the impl alone is accepted in silence, since an impl-side bound only decides where the impl applies and nothing complains until a concrete context is supplied. - -## Getter traits: `#[cgp_auto_getter]` - -A getter trait exposes a context field as a reusable `self.name()` accessor, and `#[cgp_auto_getter]` generates its single blanket impl by reading the field whose name matches the method name. Use it *sparingly* — an [implicit argument](#field-access-dressed-as-a-function-argument-implicit) is the default for reading a field, since it injects the value as an ordinary-looking parameter with no separate trait to declare, reads only from the provider's own `self`, and takes a plain `&T` by reference without cloning. Because that covers every same-context read — even a field several providers each consume, written as the same implicit argument in each — a getter trait earns its keep only in the cases an implicit argument cannot reach: the field lives on a type *other* than the provider's context, so the getter is required as a `where` bound on that type (`Request: HasBasicAuthHeader`, with no `self` field to read); the accessor must exist as a *named* capability other code depends on through `#[uses(HasName)]` or a supertrait; or the getter carries an associated type inferred from the field so the type stays abstract for callers. The macro takes no arguments and re-emits the trait verbatim, adding a blanket impl over `__Context__` keyed by the method name as a `Symbol!`: - -```rust -#[cgp_auto_getter] -pub trait HasName { - fn name(&self) -> &str; -} - -// generated: -impl<__Context__> HasName for __Context__ -where - __Context__: HasField, -{ - fn name(&self) -> &str { - self.get_field(PhantomData::).as_str() - } -} -``` - -That generated blanket impl is the point of the macro, and it follows the same access rules as `#[implicit]`: a plain `&T` return reads a `T` field directly, while the `&str` shorthand reads a `String` field and appends `.as_str()`. Other shorthands include `Option<&T>` (an `Option` field via `.as_ref()`), `Option<&str>` (an `Option` field via `.as_deref()`), `&[T]` (a field implementing `AsRef<[T]>`), an owned type — path, tuple, or array — via `.clone()`, and, with a `&mut self` receiver, the mutable mirrors `&mut T`, `&mut [T]` (a field implementing `AsMut<[T]>`, via `.as_mut()`), `Option<&mut T>` (via `.as_mut()`), and `Option<&mut str>` (an `Option` field via `.as_deref_mut()`) — all through `get_field_mut`. A trait may declare several methods, each mapping independently to its own field — `fn width(&self) -> &f64; fn height(&self) -> &f64;` produces one `where` predicate and one body per field in the same impl. - -A single getter may also declare a local associated type and use it as its return type, which lets the abstract type be inferred from the field. The trait must then contain exactly one method returning `&Self::AssocType`; the macro lifts the type into a generic parameter on the impl and binds it through the `HasField` `Value`: - -```rust -#[cgp_auto_getter] -pub trait HasName { - type Name: Display; - fn name(&self) -> &Self::Name; -} -// → impl<__Context__, Name> HasName for __Context__ -// where Name: Display, __Context__: HasField -// { type Name = Name; … } -``` - -A context gains the getter just by deriving `HasField` with a matching field — `person.name()` resolves through the blanket impl with no wiring. The cost of that simplicity is rigidity: the field name *must* equal the method name, and there is no way to swap the implementation. When you need either, `#[cgp_getter]` provides it — but that is an advanced tool, not a routine next step. - -When the getter's return type names an abstract type that lives on a *foreign* type — a generic parameter of the trait rather than `Self` — prefer importing it with [`#[use_type]`](abstract-types.md)'s `in Context` clause over a hand-written `where` bound and a qualified path. Write - -```rust -#[cgp_auto_getter] -#[use_type(HasUserIdType.UserId in App)] -pub trait HasLoggedInUser { - fn logged_in_user(&self) -> &Option; -} -``` - -rather than declaring `where App: HasUserIdType` and returning `&Option`. The `in App` clause supplies `App: HasUserIdType` on the generated trait and rewrites the bare `UserId` to `::UserId`, so the plain `` parameter and the bare alias are enough — the same benefit `#[use_type]` gives on `Self`, extended to a parameter. - -## Wireable getters: `#[cgp_getter]` and `UseField` - -`#[cgp_getter]` defines a getter as a full CGP [component](components.md) instead of a blanket impl, so the field name can differ from the method name and the getter can be swapped per context through [wiring](wiring.md). It is a specialized, advanced tool: reserve it for when a context genuinely needs full control over which field a getter reads from, and prefer an implicit argument or `#[cgp_auto_getter]` for the ordinary case of a same-named field. It accepts the same getter-method forms as `#[cgp_auto_getter]`, but because it is an extension of `#[cgp_component]` it needs a provider trait name. The default derives one from the trait name by stripping a leading `Has` and appending `Getter`, so `HasName` yields the provider `NameGetter` and the component marker `NameGetterComponent`; pass an argument like `#[cgp_getter(GetName)]` to override it. - -The decoupling is delivered by an automatically generated `UseField` provider impl. `UseField` is a zero-sized provider (a `PhantomData`-only marker named in wiring, carrying no runtime value) that implements the getter by reading the field named `Tag` from the context — and crucially, `Tag` need not be the method name: - -```rust -#[cgp_getter] -pub trait HasName { - fn name(&self) -> &str; -} - -#[derive(HasField)] -pub struct Person { - pub first_name: String, -} - -delegate_components! { - Person { - NameGetterComponent: UseField, - } -} -// person.name() now reads the first_name field -``` - -The trait method is `name` but the context stores the value in `first_name`, and the wiring `NameGetterComponent: UseField` bridges the two — the field name lives in the wiring, not in the trait. Internally `#[cgp_getter]` generates a `UseField` impl whose tag is left as a free parameter, in contrast to the `#[cgp_auto_getter]` blanket impl that hard-codes the tag to the method name. The macro also emits a `UseFields` provider (the provider-side analogue of the auto-getter blanket impl, keyed by method name) and, for single-method getters, a `WithProvider` adapter. - -For getters whose return type is reached *through* a field by `AsRef`/`AsMut` rather than being the field itself, the related `UseFieldRef` provider reads the field at `Tag` and calls `as_ref()` to expose `&Value` — for example `UseFieldRef` exposes `&str` from a `String` field. It decouples the exposed type from the stored type as well as the field name from the method name. Unlike `UseField`, it is not re-exported through the prelude; reach it through `cgp::core::field::impls`. - -`UseField` and `UseFieldRef` are the foundational field-getter providers; their `WithProvider` aliases `WithField` and `WithFieldRef` (see [wiring](wiring.md)) are what you often see wired directly onto a getter component, reading `NameGetterComponent: WithField` as "serve this getter from the named field." - -## Reaching a nested field with `ChainGetters` - -When the value a getter needs is not on the context but several hops inside it — the context holds a config, the config holds a connection, the connection holds the timeout — `ChainGetters` walks the path. It takes a `Product!` list of getters and applies them in order, threading the reference each step produces into the next, so the chain reads like the path it traverses: - -```rust -delegate_components! { - App { - TimeoutGetterComponent: ChainGetters Config - GetConnection, // Config -> Connection - GetTimeout, // Connection -> Duration - ]>, - } -} -``` - -Each element is itself a field getter for the value the previous step produced, and like every provider `ChainGetters` is a zero-sized marker named in wiring. It saves writing a bespoke provider that hand-walks the nesting whenever a getter must reach into a sub-context. - -## Getters are just traits: explicit implementation - -Every getter the macros produce is an ordinary trait, and explicit implementation is always available — the macros only save boilerplate. This matters when a context does not derive `HasField`, or stores the value under a name no tag matches. Because `#[cgp_auto_getter]` adds only a blanket impl and `#[cgp_getter]` a component whose consumer trait is plain Rust, you can write the impl by hand on a concrete type: - -```rust -pub struct Person { - pub full_name: String, -} - -impl HasName for Person { - fn name(&self) -> &str { - &self.full_name - } -} -``` - -The explicit form is more verbose but requires no understanding of `HasField` or blanket impls — a reminder that the whole apparatus on this page is convenience layered over vanilla Rust traits. - -## Choosing between the constructs - -For reading a field into a provider — the common case — an `#[implicit]` argument is the default: it keeps the access local and the code reading like a plain function, whether the value is used once or throughout the body, and it applies to any field on the provider's own context, even one several providers each read. Promote a field to a getter trait only when an implicit argument cannot reach it — the field lives on another type and the getter is a `where` bound on it, the accessor must be a named capability other code depends on, or it carries an associated type inferred from the field — and then use `#[cgp_auto_getter]` when the field name matches the method name (the usual getter), and `#[cgp_getter]` (with `UseField`) as the advanced tool reserved for when the source field name must be chosen per context at wiring time. For a whole capability rather than a single field, `#[cgp_fn]` defines one with no wiring when a single implementation suffices, and a full [component](components.md) when many providers must coexist. All of them rest on the same `HasField` machinery and the same access rules, so mixing them carries no conceptual overhead. - -## Further reference - -Online docs (current v0.8.0): -[`#[cgp_fn]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_fn.md), -[`HasField`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/traits/has_field.md), -[`#[derive(HasField)]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/derives/derive_has_field.md), -[`#[implicit]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/implicit.md), -[`#[uses]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/uses.md), -[`#[extend]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/extend.md), -[`#[extend_where]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/extend_where.md), -[`#[cgp_auto_getter]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_auto_getter.md), -[`#[cgp_getter]`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_getter.md), -[`UseField`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_field.md), -[`UseFieldRef`](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_field_ref.md), -and the -[implicit-arguments concept](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/implicit-arguments.md). diff --git a/docs/ai/skills/references/functions-and-getters.md b/docs/ai/skills/references/functions-and-getters.md new file mode 120000 index 00000000..42954a3f --- /dev/null +++ b/docs/ai/skills/references/functions-and-getters.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/functions-and-getters.md \ No newline at end of file diff --git a/docs/ai/skills/references/handlers.md b/docs/ai/skills/references/handlers.md deleted file mode 100644 index 823087e4..00000000 --- a/docs/ai/skills/references/handlers.md +++ /dev/null @@ -1,266 +0,0 @@ -# Handlers - -The handler family is a spectrum of CGP components that all transform an `Input` into an `Output` under a phantom `Code` tag, varying along three axes — synchronous vs. async, infallible vs. fallible, and input vs. no-input — together with the macros that build handlers from functions, the combinators that compose and lift them, the dispatchers that route over extensible data, and the monads that chain them. - -Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. Every handler is an ordinary [component](components.md) — a consumer trait the context calls, a provider trait a zero-sized provider implements, and a `…Component` marker that [wiring](wiring.md) maps to a provider — so nothing here needs machinery beyond what you already know. - -## The shared shape and the three axes - -Every handler maps `(context, Code, Input) -> Output`, where `Code` is a phantom tag carried as `PhantomData` and `Output` is an *associated type* the provider chooses, not a parameter the caller fixes. The `Code` tag holds no data; it exists so one context can host many handlers keyed by distinct tags, and so wiring can dispatch on it. The family is large because real computations differ along three independent axes, and each combination gets its own component so a provider declares exactly the capabilities it has. - -The first axis is **synchronous vs. async**: an async component returns a future and its method is `async`, marked by `Async` in the name (`AsyncComputer` is the async `Computer`). The second is **infallible vs. fallible**: a fallible component returns `Result` against the context's abstract error and so supertraits [`HasErrorType`](abstract-types.md), marked by the `Try` prefix. The third is **owned vs. by-reference input**: every base component has a `*Ref` sibling that borrows `&Input` instead of consuming `Input`. The general principle is that you write the *weakest* variant that fits and let combinators promote it upward, because an infallible computation is trivially fallible, a sync one trivially async, and an owned-input one can serve a borrow — but never the reverse. - -The components, by corner, are these. `Computer`/`CanCompute` is the pure-computation base — synchronous and infallible, with `AsyncComputer` and the `*Ref` variants alongside it. `TryComputer`/`CanTryCompute` is fallible but synchronous. `Handler`/`CanHandle` is the fully general async-and-fallible computation, the bound a generic consumer targets because every simpler provider promotes up to it. `Producer`/`CanProduce` sits apart as the no-input case, producing a value from the context and `Code` alone. A related pair, `CanRun`/`CanSendRun`, runs a named task rather than transforming a value. - -## The computation components - -`CanCompute` is the simplest member and the one to reach for first. Its method takes the `Code` tag and the input by value and returns the chosen `Output` with no failure path: - -```rust -#[cgp_component(Computer)] -#[derive_delegate(UseDelegate)] -#[derive_delegate(UseInputDelegate)] -pub trait CanCompute { - type Output; - fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; -} -``` - -The provider trait `Computer` moves the context into an explicit first parameter, as for any component; the marker is `ComputerComponent`. The two `#[derive_delegate]` directives let a context route to different providers by `Code` (via `UseDelegate`) or by `Input` type (via the family's `UseInputDelegate`), the basis of [dispatching](#dispatching-over-extensible-data). `AsyncComputer`/`CanComputeAsync` is identical but declares `async fn compute_async` under `#[async_trait]`, and `ComputerRef`/`AsyncComputerRef` borrow the input as `&Input`. None of the four supertrait `HasErrorType`, because none can fail. - -`CanTryCompute` adds the failure path. It supertraits `HasErrorType` so its `Result` can name the context's abstract error, which is what keeps a provider generic over the error backend: - -```rust -#[cgp_component(TryComputer)] -#[derive_delegate(UseDelegate)] -#[derive_delegate(UseInputDelegate)] -#[use_type(HasErrorType.Error)] -pub trait CanTryCompute { - type Output; - fn try_compute(&self, _code: PhantomData, input: Input) - -> Result; -} -``` - -A `TryComputer` provider carries a `Context: HasErrorType` bound and typically converts a concrete source error into the abstract one with [`CanRaiseError`](error-handling.md). `TryComputerRef` is the by-reference sibling. - -`CanHandle` is the general corner — async *and* fallible — and is the bound generic pipeline code targets, since `Computer`, `AsyncComputer`, and `TryComputer` all promote up to it: - -```rust -#[async_trait] -#[cgp_component(Handler)] -#[derive_delegate(UseDelegate)] -#[derive_delegate(UseInputDelegate)] -#[use_type(HasErrorType.Error)] -pub trait CanHandle { - type Output; - async fn handle(&self, _tag: PhantomData, input: Input) - -> Result; -} -``` - -A function bounded by `Context: CanHandle` accepts any wired computation regardless of which capabilities the underlying provider actually uses. `HandlerRef` borrows the input. - -`CanProduce` is the no-input case: it threads no `Input`, only the context and a `Code` tag, and so carries a single `#[derive_delegate(UseDelegate)]` with no `UseInputDelegate` counterpart and does not supertrait `HasErrorType`: - -```rust -#[cgp_component(Producer)] -#[derive_delegate(UseDelegate)] -pub trait CanProduce { - type Output; - fn produce(&self, _code: PhantomData) -> Self::Output; -} -``` - -A producer is the natural source of values that flow into a pipeline — a constant or a context-derived default — and promotes into any input-taking handler by ignoring the supplied input. - -A handler provider is an ordinary zero-sized provider implementing the provider trait for a generic context. The built-in `UseField` is a `Computer` that forwards the computation to the value held in the context's `Tag` field; beyond it, the combinators below supply the rest. - -## Task runners: `CanRun` and `CanSendRun` - -The runner pair executes a unit of work selected by a `Code` tag rather than transforming a value, completing to `Result<(), Error>`. `CanRun` is the base async form; `CanSendRun` exists to recover a `Send` future for spawning: - -```rust -#[cgp_component(Runner)] -#[async_trait] -#[derive_delegate(UseDelegate)] -#[use_type(HasErrorType.Error)] -pub trait CanRun { - async fn run(&self, _code: PhantomData) -> Result<(), Error>; -} - -#[cgp_component(SendRunner)] -#[async_trait] -#[derive_delegate(UseDelegate)] -#[use_type(HasErrorType.Error)] -pub trait CanSendRun { - fn send_run(&self, _code: PhantomData) - -> impl Future> + Send; -} -``` - -A context hosts many tasks by wiring `RunnerComponent` to a `UseDelegate` table keyed on `Code`, so `app.run(PhantomData::)` and `app.run(PhantomData::)` reach distinct providers. A runner provider reaches the runtime through `HasRuntime` to spawn or await work; the `CanSendRun` variant is the mechanism for the `Send`-recovery pattern described under [recovering `Send` bounds](#recovering-send-bounds). - -## The runtime: `HasRuntimeType` and `HasRuntime` - -A runner needs something to run *against* — an executor that can spawn, sleep, open sockets, or read the clock — and CGP keeps that runtime abstract so the same code runs on Tokio in production, a mock in tests, or a single-threaded executor in a benchmark. Two built-in components express it, split because the two questions are independent. `HasRuntimeType` is an [abstract type](abstract-types.md) (`type Runtime`) answering *what* the runtime type is, chosen per context through wiring like any `#[cgp_type]` component. `HasRuntime` is a getter that supertraits `HasRuntimeType` and answers *how to obtain* the runtime value from a borrow of the context (`fn runtime(&self) -> &Self::Runtime`). Code that only names types the runtime exposes bounds on `HasRuntimeType` alone; code that performs effects bounds on `HasRuntime`. This pair is the seam where context-generic logic meets concrete async machinery, which is why the runner providers reach through it to do their work. - -## Defining handlers from functions - -`#[cgp_computer]` turns a plain function into a `Computer` provider and wires the rest of the family by promotion, so a computation as small as "add two numbers" needs no hand-written plumbing: - -```rust -#[cgp_computer] -fn add(a: u64, b: u64) -> u64 { - a + b -} -``` - -The function name becomes the provider name in PascalCase (`Add`), unless an explicit name is given as `#[cgp_computer(MyAdder)]`. The parameters are collected into a tuple that becomes the single `Input` type and destructured back inside the generated method; the return type becomes `Output`. The macro emits the function unchanged, a `#[cgp_new_provider]` impl of the base trait, and a `delegate_components!` block routing every other handler component to a promotion bundle: - -```rust -#[cgp_new_provider] -impl<__Context__, __Code__> Computer<__Context__, __Code__, (u64, u64)> for Add { - type Output = u64; - fn compute(_context: &__Context__, _code: PhantomData<__Code__>, - (arg_0, arg_1): (u64, u64)) -> Self::Output { - add(arg_0, arg_1) - } -} -// delegate_components! routes the rest of the family to PromoteComputer -``` - -The base trait and bundle are chosen from two axes the macro reads off the signature. A synchronous plain-value function uses `Computer` + `PromoteComputer`; a synchronous `Result`-returning one keeps `Computer` as the base (its `Output` is the `Result`) but uses `PromoteTryComputer`, which surfaces the `Ok`/`Err` as genuine success/failure; an `async` plain-value function uses `AsyncComputer` + `PromoteAsyncComputer`; an `async` `Result` function uses `AsyncComputer` + `PromoteHandler`. Generic parameters and `where` clauses carry onto the impl; a `&Value` parameter makes the input tuple borrow and the bundle's `PromoteRef` entries serve the `*Ref` components. The result is that one `add` answers `compute`, `try_compute`, `compute_async`, and `handle`. - -`#[cgp_producer]` is the input-less sibling, turning a zero-argument function into a `Producer` and wiring `PromoteProducer` across the whole family: - -```rust -#[cgp_producer] -fn magic_number() -> u64 { - 42 -} -``` - -The function must take no parameters, must not be `async`, and must have no generics — a producer's shape is fixed, so there is no variation in the expansion. The generated `MagicNumber` answers `produce` and, because `PromoteProducer` discards the input that each computer slot supplies, also `compute`, `try_compute`, `handle`, and the `*Ref` forms, every one yielding `42`. - -## Composing and promoting with handler combinators - -The handler combinators are zero-sized providers of `cgp-handler` that build, sequence, and lift handlers, carrying their inner providers in `PhantomData`. They divide into composition, the identity element, and promotion. - -`ComposeHandlers` runs two handlers back to back, pinning the second's input to the first's output and exposing the pair as a member of every handler family; the fallible variants `?`-short-circuit and the async variants `.await` each step. `PipeHandlers` generalizes it to a `Product![...]` list, folding right to left so `PipeHandlers` behaves as `ComposeHandlers>` and serves whichever handler shape the wiring asks for, provided every stage supports it: - -```rust -delegate_components! { - MyContext { - ComputerComponent: - PipeHandlers, - Add, - Multiply, - ]>, - } -} -// input 5 over foo=2, bar=3, baz=4 -> ((5 * 2) + 3) * 4 -``` - -`ReturnInput` is the identity handler — it ignores the context and `Code` and returns its input unchanged (wrapped in `Ok` for the fallible variants) — and is the neutral element of composition, useful as a placeholder stage. - -The promotion combinators each take one inner provider and re-expose it under a different, more capable family member, encoding the one-directional lifts the axes permit. `Promote` lifts upward without adding behavior: a `Producer` into a `Computer` (ignoring the input), a `Computer` into a `TryComputer` (wrapping in `Ok`), an `AsyncComputer` into a `Handler`. `PromoteAsync` lifts a sync provider into an async one whose future is immediately ready. `PromoteRef` bridges value and reference handlers by dereferencing or re-borrowing. `TryPromote` bridges a `Result`-valued `Computer` and a genuine `TryComputer` in both directions. You rarely name these one at a time; instead the *promotion bundles* — `PromoteComputer`, `PromoteTryComputer`, `PromoteProducer`, `PromoteAsyncComputer`, `PromoteHandler` — are `delegate_components!` tables that wire a whole cluster of components to the right single-step promoter from a given base. These are exactly what `#[cgp_computer]` and `#[cgp_producer]` wire for you, and reaching for `PromoteComputer` by hand achieves the same when wiring explicitly. - -## Dispatching over extensible data - -Dispatching routes an [extensible-data](extensible-data.md) value to per-variant or per-field handlers: for an enum, match the current variant and run its handler; for a record, run a handler per field to build it. It keeps the per-variant/per-field structure of a concrete `match` or struct literal but lets the shape and handlers be chosen by type, so the same matcher serves many enums. - -`#[cgp_auto_dispatch]` is the highest-level entry point. Written above a trait that already has one impl per payload type, it generates a blanket impl of that trait for any extensible enum of those types, dispatching each variant to that payload's impl: - -```rust -#[cgp_auto_dispatch] -pub trait HasArea { - fn area(&self) -> f64; -} -// with impls for Circle and Rectangle, and a #[derive(CgpData)] enum Shape, -// HasArea is now implemented for Shape too: -let shape = Shape::Rectangle(Rectangle { width: 2.0, height: 2.0 }); -assert_eq!(shape.area(), 4.0); -``` - -For each method it emits a per-variant computer via `#[cgp_computer]` (named `Compute` plus the method name) and an enum-level impl that runs the appropriate value-handler matcher — `MatchWithValueHandlers` for `&self`, its `Mut` form for `&mut self`, and the `MatchFirstWith…` family when the method takes extra arguments, with the `Async` form for `async` methods. A method may not have non-lifetime generic parameters, since the generated impl would need a quantified bound Rust lacks; such a method must use the combinators directly. - -Underneath, the dispatch combinators of `cgp-dispatch` express both directions as handler providers. On the matching side, `MatchWithHandlers` (with `Ref`/`Mut` and `MatchFirstWith…` forms) converts the input to its extractor and runs a list of per-variant adapters — `ExtractFieldAndHandle` tries one variant and forwards its payload, `HandleFieldValue` strips the `Field` wrapper to hand the bare value to a computer, and `DowncastAndHandle` matches a group of variants to a sub-matcher. The list runs as a monadic pipeline that short-circuits on the first match and proves exhaustiveness without a wildcard, because each miss rules out one variant until the final remainder is uninhabited. `MatchWithValueHandlers` builds that list automatically from the enum's own field list. Dispatch on the *input* type uses the `Computer` component's `UseInputDelegate` directive, wired as a nested table with one entry per input type: - -```rust -delegate_components! { - App { - ComputerComponent: - UseInputDelegate, - } -} -``` - -Each entry routes one input type (the array form sharing a provider across several), so a `Circle` or `Rectangle` input reaches `ComputeArea` while a whole `Shape` enum reaches the matcher. This input-type dispatch keys on the `Input` parameter through the component's `UseInputDelegate` directive, which is why it is written as a nested table rather than through the `open` statement — `open` rides the default `RedirectLookup` that keys on the primary `Code` parameter (see [wiring](wiring.md) for the `open` form, which is the modern way to do `Code`-keyed dispatch). The nested-table form is the established way to dispatch on the input type, and this concerns only the *wiring* — the dispatch combinators above are unaffected. - -On the building side, `BuildWithHandlers` starts from an empty builder, pipes it through per-field adapters — `BuildAndSetField` computes and sets one field, `BuildAndMerge` merges a whole record's shared fields — and finalizes. Because finalization is available only when every field is present, omitting a handler for a field is a compile error rather than a runtime half-built value. - -## Composing through a monad - -Plain composition feeds each output straight into the next step, which is wrong the moment a step can produce a value meaning "stop here." Monadic handlers solve this: the monad decides which branch of a step's output threads forward and which short-circuits out as the final result. `PipeMonadic` is the entry point — a monad marker plus a `Product![...]` list — and the pipeline it builds is itself a `Computer`-family provider: - -```rust -PipeMonadic::::compute(&context, code, 253) -// 253 -> Ok(254) -> Ok(255) -> Err("overflow"); the third overflow becomes the output -``` - -CGP ships three monad markers. `IdentMonadic` threads every value forward and never short-circuits, recovering plain `PipeHandlers` composition. `ErrMonadic` short-circuits on `Err` and continues on `Ok` — the `?`-style early return where the first error wins. `OkMonadic` is the mirror, stopping at the first `Ok`, which suits retry-until-success and is what the dispatch matcher loop runs under. The two `Result`-branching markers have transformer forms, `OkMonadicTrans` and `ErrMonadicTrans`, that stack their behavior on a base monad so a pipeline over a nested `Result, F>` can short-circuit on the outer error while threading the inner result. - -The per-step providers `BindOk` and `BindErr` implement a single bind and are what `PipeMonadic` composes internally; they can also be dropped into a `PipeHandlers` list directly for step-by-step control. `BindErr` runs `Cont` on an `Ok` payload and short-circuits an `Err`; `BindOk` is its mirror. `PipeMonadic` also implements the fallible and async-fallible components by demoting each provider through `TryPromote`, applying `ErrMonadic` as a transformer over `M`, and re-wrapping — so a monadic pipeline reached through `try_compute` or `handle` short-circuits on the context's error type as well. - -## Recovering `Send` bounds - -An async trait method advertises a future whose auto-traits the caller cannot name. The `#[async_trait]` rewrite turns `async fn handle(..)` into `fn handle(..) -> impl Future<..>` with no boxing and no `Send`, which is faithful and zero-cost but drops the `Send` guarantee. The bound becomes load-bearing when the future is spawned onto a work-stealing executor (the default Tokio runtime an Axum server uses), which may migrate a suspended task between threads. The clause you want — "the future of `handle` is `Send` for any arguments" — is Return Type Notation (`handle(..): Send`), which stable Rust does not yet offer. - -The workaround is a second, ordinary trait whose method states `+ Send` directly in its return type, sidestepping RTN: - -```rust -pub trait CanHandleApiSend: - CanHandleApi + Send + Sync -{ - fn handle_api_send(&self, _api: PhantomData, request: Self::Request) - -> impl Future> + Send; -} -``` - -This is a plain trait, not a component — it adds nothing to the wiring and exists only to carry the stronger bound. It cannot be implemented with a single generic blanket impl, because the body wraps `self.handle_api(..)` in an `async` block whose `Send`-ness depends on the opaque future it awaits — the same gap restated, just RTN in disguise. The impl must therefore be written per *concrete* `(context, API)` pair, where `self.handle_api(api, request)` resolves through the wiring to a concrete future whose auto-traits the compiler computes structurally and finds `Send`: - -```rust -impl CanHandleApiSend for MockApp { - async fn handle_api_send(&self, api: PhantomData, request: Self::Request) - -> Result { - self.handle_api(api, request).await - } -} -``` - -Each impl is mechanical forwarding, yet each is also a proof accepted only because the future really is `Send` at that instantiation. One concrete impl per API per context replaces the single generic impl RTN would have allowed — the cost of the missing notation. The built-in `CanSendRun` runner applies the same pattern as a `SendRunner` proxy on the concrete context, letting a spawning runner provider clone the context into a `Send` future without `Send` bounds leaking into any abstract interface. - -## Further reference - -Online docs: -[concepts/handlers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/handlers.md), -[concepts/dispatching.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/dispatching.md), -[concepts/monadic-handlers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/monadic-handlers.md), -[concepts/send-bounds.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/send-bounds.md); -reference docs -[components/computer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/computer.md), -[components/try_computer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/try_computer.md), -[components/handler.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/handler.md), -[components/producer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/producer.md), -[components/runner.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/components/runner.md), -[macros/cgp_computer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_computer.md), -[macros/cgp_producer.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_producer.md), -[macros/cgp_auto_dispatch.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/macros/cgp_auto_dispatch.md), -[providers/handler_combinators.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/handler_combinators.md), -[providers/dispatch_combinators.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/dispatch_combinators.md), -[providers/monad_providers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/monad_providers.md). diff --git a/docs/ai/skills/references/handlers.md b/docs/ai/skills/references/handlers.md new file mode 120000 index 00000000..3440c41b --- /dev/null +++ b/docs/ai/skills/references/handlers.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/handlers.md \ No newline at end of file diff --git a/docs/ai/skills/references/higher-order-providers.md b/docs/ai/skills/references/higher-order-providers.md deleted file mode 100644 index 973513dc..00000000 --- a/docs/ai/skills/references/higher-order-providers.md +++ /dev/null @@ -1,161 +0,0 @@ -# Higher-order providers - -How one provider takes another provider as a generic parameter and builds on whatever that inner provider computes — the type-level counterpart to passing a function to a function. - -A higher-order provider is a [provider](components.md) parameterized by another provider, so part of its behavior is supplied by an inner provider it delegates to rather than fixed in its own code. The motivating shape is a wrapper that transforms the output of an existing implementation: a `ScaledArea` that multiplies whatever area an inner calculator produces, an `IterSumArea` that sums the areas an inner calculator returns over a collection, a `GloballyScaledArea` that applies a context-wide factor on top of a base calculation. In each case the outer provider knows the *transformation* but not the *base case* — the base case is a parameter. Because a provider carries no runtime value (it is a zero-sized marker naming an implementation), nesting providers costs nothing: the composition happens entirely in types. Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. - -## The shape, and the stray `` - -A higher-order provider is written like any other provider with `#[cgp_impl]`, with the inner provider declared as a generic parameter in the provider's `Self` position and bound to a *provider trait* in the `where` clause. The detail that makes it look stranger than it is the extra `` on that inner bound. Recall that a [provider trait](components.md) moves the consumer trait's `Self` into an explicit leading `Context` parameter — `AreaCalculator`, not the consumer trait's `CanCalculateArea`. So when the outer provider depends on its inner provider, the bound must name that context argument explicitly: - -```rust -#[cgp_impl(new ScaledArea)] -impl AreaCalculator -where - InnerCalculator: AreaCalculator, -{ - fn area(&self, #[implicit] scale_factor: f64) -> f64 { - InnerCalculator::area(self) * scale_factor * scale_factor - } -} -``` - -The `` in `InnerCalculator: AreaCalculator` is exactly that leading context slot, filled with the context the outer provider is implementing for. Inside `#[cgp_impl]`, `self`/`Self` mean the *context*, so `` is the context type. The same asymmetry shows at the call site: the inner provider is invoked as the associated function `InnerCalculator::area(self)`, not as a method `self.area()`, because the provider trait's method takes the context as an explicit first argument. A reader who thinks of a provider as "just the consumer trait implemented elsewhere" is caught off guard by both the bound and the call. - -## Hiding the friction with `#[use_provider]` - -The `#[use_provider]` attribute exists to erase the bound surprise, and is the idiomatic way to write higher-order providers — always reach for it, since it preserves the illusion that a provider trait has the same shape as the consumer trait it came from. Written alongside `#[cgp_impl]`, it takes the inner bound *without* the context argument and fills the `` back in for you: - -```rust -#[cgp_impl(new ScaledArea)] -#[use_provider(InnerCalculator: AreaCalculator)] -impl AreaCalculator { - fn area(&self, #[implicit] scale_factor: f64) -> f64 { - let base_area = InnerCalculator::area(self); - base_area * scale_factor * scale_factor - } -} -``` - -The author writes `InnerCalculator: AreaCalculator` and the macro inserts the context type at index 0 of the trait's generic arguments, emitting `InnerCalculator: AreaCalculator` into the `where` clause — the two snippets above are equivalent. The shape it parses is `Provider: Trait`: a provider type, a colon, and one or more provider-trait bounds joined by `+`; the trait may carry further generic arguments after the context slot, preserved in order behind the inserted `Self`. To bind several inner providers, write **one attribute per provider**: - -```rust -#[use_provider(A: AreaCalculator)] -#[use_provider(P: PerimeterCalculator)] -``` - -Stacking is the intended form here rather than a fallback, because a comma-separated list of pairs does *not* parse — after the first trait the parser is continuing that provider's bound list, so `#[use_provider(A: TraitA, B: TraitB)]` fails with `expected +`. What the `+` does join is several trait bounds on *one* provider: `#[use_provider(Inner: AreaCalculator + PerimeterCalculator)]`. This makes `#[use_provider]` the exception to the one-attribute-comma-separated convention that `#[uses]` and `#[use_type]` follow, so the habit transfers wrongly. The same attribute works on `#[cgp_fn]`. - -What `#[use_provider]` does *not* do is rewrite the body. It completes the bound only; the inner provider is still invoked as the associated function `InnerCalculator::area(self)`, with `self` passed as the explicit context. There is no call-site form — a bare `#[use_provider(InnerCalculator)]` on an expression is not accepted, and no pass turns `receiver.method(args)` into `Provider::method(receiver, args)`. The body must spell the associated-function call out itself. Calling the inner provider as a method (`self.area()`) would instead route through whatever provider the context has wired for the component, a different dispatch and usually not what a higher-order provider wants. - -## `UseContext` as a default inner provider - -A higher-order provider can default its inner provider to [`UseContext`](wiring.md) so that, absent an explicit choice, it falls back to whatever the context itself is already wired to. This requires giving the provider an explicit struct definition with a default generic parameter: - -```rust -pub struct IterSumArea(pub PhantomData); -``` - -`UseContext` is the provider that implements any provider trait by deferring to the context's own consumer-trait implementation — the dual of the consumer blanket impl. With `IterSumArea` as the default, an unparameterized `IterSumArea` computes each inner element through the context's existing area wiring, so the wrapper drops in without restating the base case. Overriding the parameter — `IterSumArea` — instead binds the inner behavior statically, bypassing the context's wiring, which is useful for overriding or short-circuiting what the context would otherwise resolve. This default exists *only* when the provider has an explicit struct carrying the default parameter; a provider defined purely through `#[cgp_impl(new ...)]` has no default and must always have its inner provider named. - -## Not every generic provider is higher-order - -A provider that merely has generic parameters is not a higher-order provider; it becomes one only when a parameter is constrained to implement a provider trait. Many providers are generic for unrelated reasons. The `UseField`-style getter provider is generic over a field tag: - -```rust -#[cgp_impl(new GetName)] -impl NameGetter -where - Self: HasField, -{ - fn name(&self) -> &str { - self.get_field(PhantomData) - } -} -``` - -Here `Tag` is a type-level field name used only as a `HasField` key, with no provider-trait bound — so `GetName` is an ordinary parameterized provider, not a higher-order one. The defining trait of a higher-order provider is that a generic parameter appears in a *provider-trait* bound and is invoked to do part of the work, as `InnerCalculator: AreaCalculator` does. When that bound is absent, `#[use_provider]` has nothing to fill in and none of the machinery applies. - -## Generic-parameter CGP traits - -A component's trait may itself carry generic parameters, and `#[cgp_component]` appends them after the context slot. Declaring the area component to dispatch on a `Shape`: - -```rust -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self, shape: &Shape) -> f64; -} -``` - -generates the provider trait `AreaCalculator` — the original trait's parameters land *after* the leading `Context`, in declaration order. The `IsProviderFor` supertrait that every provider trait carries groups all those extra parameters into a single tuple in its `Params` slot (`()` when there are none), and any lifetime parameters are lifted into the `Life<'a>` type rather than appearing as bare lifetimes. A provider then writes `impl AreaCalculator for RectangleArea`, naming the concrete `Shape` it handles. - -## Dispatching on a generic parameter with `open` - -When the right provider depends on *which* concrete type a generic parameter is — `Rectangle` handled by one provider, `Circle` by another — the choice is made by a second lookup keyed on that parameter rather than on the component marker. The modern way a context writes this per-type dispatch is the `open` statement of `delegate_components!`, which folds the per-value entries directly into the context's own table. Given a `CanCalculateArea` consumer trait whose `Shape` parameter selects the area formula, a context opens the component and then assigns a provider per shape: - -```rust -delegate_components! { - MyApp { - open AreaCalculatorComponent; - - @AreaCalculatorComponent.Rectangle: RectangleArea, - @AreaCalculatorComponent.Circle: CircleArea, - } -} -``` - -The leading `open AreaCalculatorComponent;` header opens the component for per-value wiring, and each `@AreaCalculatorComponent.Key: Provider` entry assigns a provider for one value of the dispatch parameter: when `Shape` is `Rectangle`, `MyApp` calculates area through `RectangleArea`, and `Circle` resolves to `CircleArea`. After this wiring, `MyApp` implements `CanCalculateArea` through `RectangleArea` and `CanCalculateArea` through `CircleArea`, with the dispatch parameter selecting between them. Adding a shape is one more entry; the providers stay untouched. The `open` form needs no extra macro on the component — it rides the `RedirectLookup` impl that every `#[cgp_component]` already generates, so dispatching a component per type requires no `#[derive_delegate]` on the trait. Two shorthands keep the entries compact: an array on the final path segment shares one provider across several values (`@AreaCalculatorComponent.[Rectangle, Circle]: SomeProvider`), and generic parameters precede the dispatch value when it needs them (`@AreaCalculatorComponent.<'a, T> &'a T: SomeProvider`). The [wiring](wiring.md) reference is the canonical home of the `open` statement and its grammar. - -### Legacy: `derive_delegate` and `UseDelegate` nested tables - -An older form generates a `UseDelegate` provider and wires the per-type entries into a separate table it points at. The `#[derive_delegate(...)]` attribute asks `#[cgp_component]` to generate that provider: - -```rust -#[cgp_component(AreaCalculator)] -#[derive_delegate(UseDelegate)] -pub trait CanCalculateArea { - fn area(&self, shape: &Shape) -> f64; -} -``` - -`UseDelegate` is a zero-sized provider that treats its `Components` type as a type-level table — a `DelegateComponent` table keyed on the named parameter (`Shape`) — and forwards each method to the delegate that table maps the concrete type to. A context wires it through a nested table inside `delegate_components!`, building the outer entry and the inner lookup in one place: - -```rust -delegate_components! { - MyApp { - AreaCalculatorComponent: - UseDelegate, - } -} -``` - -This reads in two layers: `MyApp` delegates `AreaCalculatorComponent` to `UseDelegate`, and the inner table — defined inline by `new` — maps `Rectangle` to `RectangleArea` and `Circle` to `CircleArea`. The end effect matches the `open` example above, but the dispatch values live in a named side table reached through `UseDelegate` instead of in `MyApp`'s table directly. This is a legacy dispatch mechanism, retained for compatibility and expected to be deprecated; prefer `open` for new code, but expect to still encounter the `derive_delegate`/`UseDelegate` form when reading existing wiring (see [wiring](wiring.md) for both forms side by side). - -A component may dispatch on more than one parameter by stacking several `#[derive_delegate(...)]` attributes, one per dispatcher. Writing `#[derive_delegate(UseDelegate)]` and `#[derive_delegate(UseInputDelegate)]` generates one impl per dispatcher — the default `UseDelegate` keying on `Code`, plus a user-defined `UseInputDelegate` (an ordinary struct of the same single-parameter shape) keying on `Input` — so each parameter is looked up through its own table. Only the parameter named in a dispatcher's angle brackets is used as the key; the others flow through. Per-type dispatch and higher-order providers compose either way: an `open` entry or a nested delegation table can map each shape to a different `ScaledArea<...>`. - -## Cross-context dependencies through a shared context - -The real leverage of generic-parameter dispatch appears when the main target of a capability is itself a generic parameter, and a supertrait constrains the *context* rather than each parameter type. Consider an area component whose result type is an abstract scalar the context supplies: - -```rust -#[cgp_component(AreaCalculator)] -#[use_type(HasScalarType.Scalar)] -pub trait CanCalculateAreaOfShape { - fn area_of_shape(&self, shape: &Shape) -> Scalar; -} -``` - -Because the shared capability — `HasScalarType` and any value-level injection — lives on the common context, the individual shape types (`Rectangle`, `Circle`) need not implement it themselves; they only know their own geometry. The context provides the shared abstract type ([abstract types](abstract-types.md)): one app might wire `Scalar` to `f64`, another to a fixed-point type, and every shape provider produces that scalar. The context also provides value-level injection — a `GloballyScaledArea` provider can read a global scale factor from a field on the context through an implicit argument and multiply every shape's area by it, so the scale is configured once per context rather than per shape. Most importantly, provider binding is *lazy and per-context*: a `BaseApp` and a `ScaledApp` can wire the very same `Shape` to different providers — `BaseApp` opening `AreaOfShapeCalculatorComponent` and mapping `@AreaOfShapeCalculatorComponent.Rectangle: RectangleArea` to a plain `RectangleArea`, `ScaledApp` mapping `@AreaOfShapeCalculatorComponent.Rectangle: GloballyScaledArea` instead — so the same generic capability resolves to different behavior in each context without either app's shapes knowing about the other. Each context writes its per-shape choices with the `open` statement detailed in [wiring](wiring.md); the legacy `derive_delegate`/`UseDelegate` nested-table form wires the same dispatch and still appears in existing code. Each layer of such nesting can be verified independently with the `#[check_providers]` form of `check_components!`, which is what makes higher-order wiring debuggable; see [checking](checking.md). - -## Related constructs - -Higher-order providers build on the consumer/provider split and the `IsProviderFor` propagation described in [components](components.md), and they are connected to contexts through [wiring](wiring.md), where `UseContext`, the `open` statement, and the legacy nested-table `UseDelegate` forms all live. `UseContext` lets the inner provider fall back to the context's own consumer-trait impl; the `open` statement dispatches a component on a generic parameter by folding per-value entries into the context's own table, with the legacy `UseDelegate` provider (generated by the `derive_delegate` option) doing the same through a separate side table; the abstract result types that make cross-context dependencies work are covered in [abstract types](abstract-types.md) and the type-level keys in [type-level primitives](type-level-primitives.md). Each layer of a nested provider is checked independently through [checking](checking.md). - -Further reference (online docs): -[concepts/higher-order-providers.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/concepts/higher-order-providers.md), -[reference/attributes/use_provider.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/use_provider.md), -[reference/providers/use_delegate.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/providers/use_delegate.md), -[reference/attributes/derive_delegate.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/cgp/reference/attributes/derive_delegate.md). diff --git a/docs/ai/skills/references/higher-order-providers.md b/docs/ai/skills/references/higher-order-providers.md new file mode 120000 index 00000000..ca4f5efc --- /dev/null +++ b/docs/ai/skills/references/higher-order-providers.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/higher-order-providers.md \ No newline at end of file diff --git a/docs/ai/skills/references/macro-grammar.md b/docs/ai/skills/references/macro-grammar.md deleted file mode 100644 index ecd90694..00000000 --- a/docs/ai/skills/references/macro-grammar.md +++ /dev/null @@ -1,341 +0,0 @@ -# Macro grammar and expansion rules - -The grammar every CGP macro parses, the code each one expands to, and how to read the compiler errors that result — the reference for writing CGP that parses, and for decoding what goes wrong when it does not. - -CGP is almost entirely procedural macros, so "valid CGP code" means two separate things: input the macro's own parser accepts, and output that expands to Rust the compiler accepts. This file covers both. It gives the formal grammar of each macro's custom syntax, states the invariant each expansion preserves, and closes with a decoder for the error messages the two layers produce. Read it to check a form you are unsure about, to predict what a macro emits, or to trace an error back to its cause. Assume `use cgp::prelude::*;` throughout; the CGP version is v0.8.0. - -## How to read the grammars - -The grammars use the notation of the [Rust Reference](https://doc.rust-lang.org/nightly/reference/notation.html), in production-rule form. A production is `Name -> Expression`, one per line inside an `ebnf` block. `x?` is optional, `x*` is zero-or-more, `x+` is one-or-more, `A | B` is a choice, `( … )` groups, and juxtaposition is sequence. A terminal is written in backticks (`` `new` ``, `` `:` ``, `` `@` ``); a nonterminal is a CamelCase name. - -A CamelCase name this file does not define is a production of the **Rust grammar**, reused rather than re-specified — `Type`, `Generics` (the `< … >` parameter list), `GenericArgs` (the `< … >` argument list), `WhereClause`, `TypePath`, and `Expression`. An `ALL_CAPS` name is a Rust lexer token: `IDENTIFIER` is a Rust identifier and `STRING_LITERAL` a string literal. Each grammar describes only the tokens the macro itself parses — the argument tokens inside an attribute's `#[name(…)]` or `#[name{…}]` delimiters, or the body tokens inside a function-like macro's `name!{ … }` — never the delimiters themselves, and never the plain Rust item an attribute is applied to. - -## Reserved identifiers the expansions introduce - -Every macro that turns a trait or impl "inside out" invents identifiers, and it wraps them in double underscores so they cannot collide with a user's names. Recognizing them is what lets you read raw expansions and the errors that quote them. The context type parameter is `__Context__` (overridable), the provider parameter is `__Provider__`, a rewritten `self` receiver is `__context__`, the component key generic is `__Component__`, an inner delegation table is `__Components__`, a looked-up delegate is `__Delegate__`, the `IsProviderFor` params tuple is `__Params__`, a getter's free field tag is `__Tag__`, and a namespace's table generic is `__Table__`. Throughout this file the readable names `Context`/`Provider`/`Params` stand in for these where clarity is served, but the emitted code uses the reserved forms. - -Two more names appear in expansions and resolve through the prelude: any CGP construct the output references is emitted as `::cgp::macro_prelude::`, so an expansion compiles in a crate that has only `cgp` in scope. You never write that path yourself. - ---- - -## Component-definition macros - -### `#[cgp_component]` - -The argument is either a bare provider name or a comma-separated set of keyed values: - -```ebnf -CgpComponentArgs -> ProviderName - | KeyValueArg ( `,` KeyValueArg )* `,`? - -ProviderName -> IDENTIFIER - -KeyValueArg -> `name` `:` ComponentName - | `provider` `:` IDENTIFIER - | `context` `:` IDENTIFIER - -ComponentName -> IDENTIFIER GenericArgs? -``` - -`ProviderName` is shorthand for setting `provider` alone. In the keyed form — written with brace delimiters, `#[cgp_component { … }]` — each of the three keys appears at most once, in any order, and `provider` is required. The `name` key defaults to the provider name with a `Component` suffix (`AreaCalculator` → `AreaCalculatorComponent`), and `context` defaults to `__Context__`. The provider name may not carry generics; the component name may. - -**Expansion invariant.** From one trait, `#[cgp_component]` emits five items plus standard provider impls, and this shape never varies: the **consumer trait** unchanged; the **provider trait** with `Self` moved to a leading `Context` parameter, every `self`/`Self` rewritten to `context`/`Context`, and an `IsProviderFor<{Name}Component, Context, Params>` supertrait; the **consumer blanket impl** (`Context: {Provider}` ⟹ consumer trait); the **provider blanket impl** (delegates through `DelegateComponent<{Name}Component>`); and the zero-sized **`{Name}Component` marker**. Alongside these it emits a `UseContext` impl, a `RedirectLookup` impl (what the `open` statement and namespaces dispatch through), one `UseDelegate` impl per `#[derive_delegate]`, and prefix impls per `#[prefix]`. Any trait generics land *after* the context in the provider trait and are grouped into the `IsProviderFor` `Params` tuple. See [components](components.md) for the full worked expansion. - -### `#[cgp_type]` and `#[cgp_getter]` - -Both reuse `CgpComponentArgs` verbatim and differ only in the default when `provider` is omitted: - -```ebnf -CgpTypeArgs -> CgpComponentArgs // default provider: {AssocType}TypeProvider -CgpGetterArgs -> CgpComponentArgs // default provider: strip leading `Has`, append `Getter` -``` - -`#[cgp_type]` keys its default off the *associated type's* name (`type Scalar;` → `ScalarTypeProvider`, marker `ScalarTypeProviderComponent`); `#[cgp_getter]` strips a leading `Has` from the trait name and appends `Getter` (`HasName` → `NameGetter`). Beyond the shared component output, `#[cgp_type]` adds a `UseType` blanket impl (the associated type *is* `T`) and a `WithProvider` impl adapting the built-in `TypeProvider`; `#[cgp_getter]` adds a `UseFields` impl (always) plus a `UseField` impl and a `WithProvider` impl (only when the trait has exactly one method). See [abstract-types](abstract-types.md) and [functions-and-getters](functions-and-getters.md). - ---- - -## Provider-writing macros - -### `#[cgp_impl]` - -The argument names the provider, optionally preceded by `new` and followed by a component override: - -```ebnf -CgpImplArgs -> `new`? ProviderType ( `:` ComponentType )? - -ProviderType -> Type -ComponentType -> Type -``` - -`new` makes the macro also emit `pub struct ;`. `ProviderType` takes the `Self` position of the generated provider impl — a plain name, a generic provider (`ScaledArea`), or the literal `Self`. The optional `: ComponentType` overrides the component in the generated `IsProviderFor` impl, defaulting to the provider trait name plus `Component`. - -Two forms of the impl header matter. **Omit `for Context`** and the macro inserts `__Context__` for you — this is the preferred form, and it reads like an ordinary trait impl. Write `impl Trait for Context` explicitly only to bound or name the context readably (a lifetime or HRTB the sugar cannot spell). Naming the provider **`Self`** — `#[cgp_impl(Self)]` — is a passthrough: it emits the block unchanged as a direct consumer-trait impl on the concrete context (the `for Context` clause is then *required*), which is how you apply companion attributes like `#[use_provider]` to a hand-written impl; `new` and the component override are ignored in this form. - -**Expansion invariant.** `#[cgp_impl]` desugars to `#[cgp_provider]` (or `#[cgp_new_provider]` with `new`): it moves the context back to the provider trait's leading position, swaps the provider name into `Self`, rewrites `&self` to `__context__: &__Context__`, every `self` to `__context__`, and every `Self` to the context type. The rewrite is scoped to the method bodies — a nested item's own `self`/`Self` is left alone (except inside a `macro!(…)` invocation, which the token rewrite cannot scope and so rewrites anyway). See [components](components.md). - -### `#[cgp_provider]` and `#[cgp_new_provider]` - -Both take a single optional component type; `#[cgp_new_provider]` additionally declares the provider struct (implied by the name, not the argument): - -```ebnf -CgpProviderArgs -> ComponentType? -CgpNewProviderArgs -> ComponentType? - -ComponentType -> Type -``` - -Applied to a provider-trait impl written directly on a provider struct, the macro passes the impl through unchanged and derives the matching `IsProviderFor` impl from it — a copy with the body and associated types stripped, the trait swapped to `IsProviderFor`, and the same `where` clause kept. The trait arguments become `IsProviderFor<{Component}, {Context}, ({trailing params})>`: component first (the argument overrides the default), context second (the provider trait's leading argument), and a tuple of every remaining provider-trait parameter third (`()` when none). A **const argument in the provider trait's own argument list is rejected** with a spanned error, because a const cannot key the type-based `Params` tuple; a const generic on the provider *struct* flows through untouched. - ---- - -## Function, getter, and handler macros - -These macros are applied to a plain Rust function or trait, so most take only an optional name and read the rest of their behavior off the item's shape. Their grammars are small: - -```ebnf -CgpFnArgs -> TraitName? // #[cgp_fn]: default = fn name in PascalCase -CgpComputerArgs -> ProviderName? // #[cgp_computer]: default = fn name in PascalCase -CgpProducerArgs -> ProviderName? // #[cgp_producer]: default = fn name in PascalCase -BlanketTraitArgs -> ContextName? // #[blanket_trait]: default = __Context__ - -TraitName -> IDENTIFIER -ProviderName -> IDENTIFIER -ContextName -> IDENTIFIER -``` - -`#[cgp_auto_getter]`, `#[cgp_auto_dispatch]`, and `#[async_trait]` take **no argument** — they are plain attributes on a trait, with no custom grammar. Their behavior comes entirely from the annotated trait and from separate companion attributes. - -The rest of each function macro's contract is read from the item, not the argument. `#[cgp_fn]` lifts function generics onto both the generated trait and impl while keeping the `where` clause impl-only, turns `#[implicit]` parameters into `HasField` reads, and forbids generics on the desugared *method* (a method-level generic is silently treated as a trait/impl generic). `#[cgp_computer]` collects the function's parameters into one tuple `Input`, chooses the base component and promotion bundle from whether the function is `async` and whether it returns `Result`, and wires the rest of the handler family by promotion; `#[cgp_producer]` requires a zero-parameter, non-`async`, non-generic function. `#[async_trait]` rewrites each `async fn` to `-> impl Future`. See [functions-and-getters](functions-and-getters.md) and [handlers](handlers.md) for the expansions. - ---- - -## Attribute modifiers - -These attributes refine what a host macro generates; none is a standalone macro. The table names each one's form, what it contributes, and which host macros accept it. - -- **`#[implicit]`** — a bare marker on a typed, plain-identifier function argument (`#[implicit] width: f64`); no argument of its own, and `#[implicit(x)]` or `#[implicit = "x"]` is rejected. Removes the argument, adds a `HasField` bound, and binds the value at the top of the body. A *mutable* implicit (its type carries a `&mut`) must be the sole implicit and needs `&mut self`. Host: `#[cgp_fn]`, `#[cgp_impl]`. -- **`#[uses(Trait, Trait

>::Delegate` is the value it returns. Because Rust forbids two impls of one trait for the same `Self` and `Key`, each key maps to exactly one value. This -makes the structure a map rather than a relation, and it turns a duplicate wiring entry into a coherence +makes the structure a map rather than a relation, and it turns a duplicate wiring entry into a [coherence](/docs/reference/glossary#coherence) error rather than a silent overwrite. ### What can be a key @@ -188,7 +188,7 @@ the error message. There are narrow reasons to name the trait yourself. - **Reading an entry in generic code.** A provider that must resolve a key itself (a dispatcher, a - higher-order provider walking a table) bounds on `DelegateComponent` and projects `Delegate`. This + [higher-order provider](/docs/reference/glossary#higher-order-provider) walking a table) bounds on `DelegateComponent` and projects `Delegate`. This is the one legitimate hand-written use, and it is a *read*. - **Recognizing it in an error.** `the trait bound App: DelegateComponent is not satisfied` means the context never wired that component. That is the most common wiring error there is, diff --git a/docs/reference/traits/wiring/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md index feb5151f..1ab6344b 100644 --- a/docs/reference/traits/wiring/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -5,7 +5,7 @@ sidebar_position: 2 # `IsProviderFor` -The marker supertrait that makes a provider's missing dependency show up by name. +The marker [supertrait](/docs/reference/glossary#supertrait) that makes a provider's missing dependency show up by name. :::info @@ -21,7 +21,7 @@ names, and reading that error is the reason to know it exists. ## Overview An implementation in CGP states what it needs from its **context**, the type the method runs on, -in its own `where` clause: a field, an abstract type, another trait. When one of those requirements is +in its own `where` clause: a field, an [abstract type](/docs/reference/glossary#abstract-type), another trait. When one of those requirements is not met, you want the compiler to say *which*. Left to itself, it will not. The reason is a specific behaviour of Rust's diagnostics. Asking "does this provider implement the provider @@ -149,7 +149,7 @@ an error and, occasionally, assert it through a check. Two situations do put its name in your hands, and both are about diagnosis rather than construction. -- **Localizing a broken layer in a higher-order provider stack.** Checking the context proves *something* +- **Localizing a broken layer in a [higher-order provider](/docs/reference/glossary#higher-order-provider) stack.** Checking the context proves *something* in the stack is unsatisfied. `#[check_providers(...)]` asserts `IsProviderFor` on each named provider instead, so a dependency missing only from the outer wrapper errors on its line alone while one missing from the inner provider errors on both, which pins the layer. diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index e4c6ad78..39dcc496 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -5,7 +5,7 @@ sidebar_position: 9 # `Chars` -One character of a type-level string: the list that spells a field name out one character at a time so +One character of a [type-level string](/docs/reference/glossary#type-level-string): the list that spells a field name out one character at a time so the name can be a type. ## Overview diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index e7056069..3063d13a 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -41,7 +41,7 @@ pub struct Field { ``` `Tag` is the type-level name of the field. It appears only inside `PhantomData`, never in a stored -field. It is usually a type-level string such as `Symbol!("name")` for a named field, or a type-level +field. It is usually a [type-level string](/docs/reference/glossary#type-level-string) such as `Symbol!("name")` for a named field, or a type-level number such as `Index<0>` for a tuple position. `Value` is the field's actual type, and `value` is the only data the struct keeps. Apart from the tag, a `Field` is a thin wrapper around its `Value`. diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index e332cc10..c086bcd8 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -104,7 +104,7 @@ carries a lifetime. invariance keeps the compiler from confusing providers wired for different lifetimes, so it is intended rather than an over-restriction. -**A higher-order provider with a lifetime loses its dependency propagation.** When the component carries a +**A [higher-order provider](/docs/reference/glossary#higher-order-provider) with a lifetime loses its dependency propagation.** When the component carries a lifetime, the inner-provider bound of such a stack does not get a marker counterpart, because the rewrite reads the bound's first generic argument as the context and finds a lifetime there. The stack still compiles and runs. But it loses the propagation that lets `#[check_providers]` localize a broken layer. diff --git a/docs/reference/types/path_cons.md b/docs/reference/types/path_cons.md index b39ca603..e7cb9922 100644 --- a/docs/reference/types/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -25,7 +25,7 @@ size. A product list keys a struct's fields, and its elements are always sized v lookup, and its segments are pure type-level markers that never need to be `Sized`. The segments are the markers CGP uses elsewhere. A lowercase dotted name becomes a -[`Symbol`](chars.md) type-level string, and a capitalized name becomes that named type, usually a +[`Symbol`](chars.md) [type-level string](/docs/reference/glossary#type-level-string), and a capitalized name becomes that named type, usually a component key such as `FooProviderComponent` or a namespace marker. So a path interleaves symbols and component names, in the form `@a.B.c`, assembled into a `PathCons` chain. You write paths through the [`Path!`](../macros/path.md) macro. This page covers the list type, and that macro's page covers the diff --git a/docs/tutorials/area-calculation/context-generic-functions.md b/docs/tutorials/area-calculation/context-generic-functions.md index 6beb8e90..338553d9 100644 --- a/docs/tutorials/area-calculation/context-generic-functions.md +++ b/docs/tutorials/area-calculation/context-generic-functions.md @@ -179,7 +179,7 @@ As we can see from the desugared code, there are actually very little magic happ First, a `RectangleArea` trait is defined with the CamelCase name derived from the function name. The trait contains similar function signature as `rectangle_area`, except that the implicit arguments are removed from the interface. -Secondly, a *getter trait* that resembles the `RectangleFields` above is used to access the `width` and `height` fields of a generic context. +Secondly, a *[getter trait](/docs/reference/glossary#getter-trait)* that resembles the `RectangleFields` above is used to access the `width` and `height` fields of a generic context. Finally, a [**blanket implementation**](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) of `RectangleArea` is defined to work with any `Context` type that contains both the `width` and `height` fields. This means that there is no need for any context type to implement `RectangleArea` manually. @@ -222,7 +222,7 @@ impl RectangleFields for PlainRectangle { } ``` -With the getter traits implemented, the requirements for the blanket implementation of `RectangleArea` are satisfied. And thus we can now call `rectangle_area()` on a `PlainRectangle` value. +With the getter traits implemented, the requirements for the [blanket implementation](/docs/reference/glossary#blanket-implementation) of `RectangleArea` are satisfied. And thus we can now call `rectangle_area()` on a `PlainRectangle` value. ### Zero cost field access @@ -281,7 +281,7 @@ where Compared to `rectangle_area`, the desugared code for `scaled_rectangle_area` contains an additional trait bound `Self: RectangleArea`, which is generated from the `#[uses(RectangleArea)]` attribute. This also shows that importing a CGP construct is equivalent to applying it as a trait bound on `Self`. -It is also worth noting that trait bounds like `RectangleFields` only appear in the `impl` block but not on the trait definition. This implies that they are *impl-side dependencies* that hide the dependencies behind a trait impl without revealing it in the trait interface. +It is also worth noting that trait bounds like `RectangleFields` only appear in the `impl` block but not on the trait definition. This implies that they are *[impl-side dependencies](/docs/reference/glossary#impl-side-dependency)* that hide the dependencies behind a trait impl without revealing it in the trait interface. Aside from that, `ScaledRectangleArea` also depends on field access traits that are equivalent to `ScaleFactorField` to retrieve the `scale_factor` field from the context. In actual, it also uses `HasField` to retrieve the `scale_factor` field value, and there is no extra getter trait generated. @@ -291,4 +291,4 @@ In this tutorial, we have introduced `#[cgp_fn]` and the `#[implicit]` attribute Throughout, all of this happened through ordinary Rust traits and blanket implementations. The `#[cgp_fn]` macro is purely syntactic sugar — the desugared code it generates is straightforward Rust that follows the zero-cost abstraction principle. -In the next tutorial, Static Dispatch, we will extend the area calculation example to support a second shape — the circle — and introduce the `CanCalculateArea` trait as a unified interface for all shapes. We will encounter Rust's coherence restrictions when trying to write blanket implementations for overlapping cases, and see how CGP's `#[cgp_component]` macro and named providers resolve this problem cleanly, enabling configurable static dispatch with `delegate_components!`. \ No newline at end of file +In the next tutorial, Static Dispatch, we will extend the area calculation example to support a second shape — the circle — and introduce the `CanCalculateArea` trait as a unified interface for all shapes. We will encounter Rust's [coherence](/docs/reference/glossary#coherence) restrictions when trying to write blanket implementations for overlapping cases, and see how CGP's `#[cgp_component]` macro and named providers resolve this problem cleanly, enabling configurable static dispatch with `delegate_components!`. \ No newline at end of file diff --git a/docs/tutorials/area-calculation/index.md b/docs/tutorials/area-calculation/index.md index b0b59c5e..2c63aa6b 100644 --- a/docs/tutorials/area-calculation/index.md +++ b/docs/tutorials/area-calculation/index.md @@ -83,4 +83,4 @@ We have now identified the two core limitations of conventional Rust approaches: In the first tutorial, Context-Generic Functions, we will see how the `#[cgp_fn]` macro and `#[implicit]` arguments address both of these limitations at once, allowing us to write a single `rectangle_area` function that works cleanly across any context that provides the required fields. We will also explore how CGP functions can import each other via `#[uses]`, and take an optional look at how the macro desugars into plain Rust traits under the hood. -In the second tutorial, Static Dispatch, we will introduce a second shape — the circle — and define a unified `CanCalculateArea` trait as a common interface across all shapes. We will run into Rust's coherence restrictions when trying to provide blanket implementations, and then resolve this with CGP's `#[cgp_component]` macro and named providers. Finally, we will see how `delegate_components!` wires contexts to providers at compile time, and how higher-order providers allow provider implementations to compose generically, with zero runtime overhead. +In the second tutorial, Static Dispatch, we will introduce a second shape — the circle — and define a unified `CanCalculateArea` trait as a common interface across all shapes. We will run into Rust's [coherence](/docs/reference/glossary#coherence) restrictions when trying to provide [blanket implementations](/docs/reference/glossary#blanket-implementation), and then resolve this with CGP's `#[cgp_component]` macro and named providers. Finally, we will see how `delegate_components!` wires contexts to providers at compile time, and how [higher-order providers](/docs/reference/glossary#higher-order-provider) allow provider implementations to compose generically, with zero runtime overhead. diff --git a/docs/tutorials/area-calculation/static-dispatch.md b/docs/tutorials/area-calculation/static-dispatch.md index 2795fd65..c3bd9005 100644 --- a/docs/tutorials/area-calculation/static-dispatch.md +++ b/docs/tutorials/area-calculation/static-dispatch.md @@ -6,7 +6,7 @@ sidebar_position: 2 In the previous tutorial, we learned how `#[cgp_fn]` and `#[implicit]` arguments let us define context-generic functions that extract field values automatically from any conforming context. We came away with `rectangle_area` and `scaled_rectangle_area` working cleanly across multiple rectangle contexts, all without any manual forwarding or per-context implementation. -In this tutorial, we will introduce a second shape — the circle — and motivate the need for a unified `CanCalculateArea` interface that works across all shapes. We will then run into one of Rust's most well-known limitations when trying to generalize this: the coherence problem. After examining why plain blanket implementations fall short, we will see how CGP's `#[cgp_component]` macro and named providers resolve the problem. Finally, we will wire everything together using `delegate_components!` for concise, compile-time static dispatch, and generalize further with higher-order providers that compose behavior without duplication. +In this tutorial, we will introduce a second shape — the circle — and motivate the need for a unified `CanCalculateArea` interface that works across all shapes. We will then run into one of Rust's most well-known limitations when trying to generalize this: the [coherence](/docs/reference/glossary#coherence) problem. After examining why plain [blanket implementations](/docs/reference/glossary#blanket-implementation) fall short, we will see how CGP's `#[cgp_component]` macro and named providers resolve the problem. Finally, we will wire everything together using `delegate_components!` for concise, compile-time static dispatch, and generalize further with [higher-order providers](/docs/reference/glossary#higher-order-provider) that compose behavior without duplication. ## Using CGP functions with Rust traits diff --git a/docs/tutorials/hello.md b/docs/tutorials/hello.md index 2ac08a79..b345cf87 100644 --- a/docs/tutorials/hello.md +++ b/docs/tutorials/hello.md @@ -136,7 +136,7 @@ where } ``` -The plain-Rust version is considerably more verbose, but it can be understood with a straightforward explanation. `HasName` is a *getter trait* that a context implements to expose its `name` value. `Greet` is defined as a trait with a [**blanket implementation**](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) that works for any context type `T` that implements `HasName`. +The plain-Rust version is considerably more verbose, but it can be understood with a straightforward explanation. `HasName` is a *[getter trait](/docs/reference/glossary#getter-trait)* that a context implements to expose its `name` value. `Greet` is defined as a trait with a [**blanket implementation**](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) that works for any context type `T` that implements `HasName`. When we use `#[derive(HasField)]` on a context like `Person`, we are effectively automatically implementing the `HasName` trait for it: From 5676e9d5bc8290f6aeec465e158ed42ccb053f80 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 21 Sep 2026 03:07:46 +0000 Subject: [PATCH 085/516] Land the copy corrections, and repair the migration's dead URLs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces the retired "Modular programming paradigm for Rust" tagline with the settled line, repoints the announcement bar at the v0.8.0 post, and pins the Hello World tutorial to 0.8.0. Rewrites the Resources page, which omitted cargo-cgp entirely — the error toolchain is the direct answer to the most-cited obstacle to adopting CGP, and Resources is where an evaluator looks for it. It now has a Tooling section carrying the install path and the tool's own alpha qualification, the full error-crate list, cgp-serde by its crates.io entry, and the Hermes SDK promoted out of a bare list into the social proof an evaluator came for. Adds seven static redirect stubs for the URLs the Zola-to-Docusaurus migration left behind. Search Console records 1,934 impressions and 10 clicks a year still landing on /overview/, /tutorials/hello/, /resources/, /contribute/ and /tutorials/, at positions between 6.5 and 8 — all of them 404 today. GitHub Pages cannot issue a 301, so each stub carries a canonical link and a meta refresh. Adds robots.txt, which the site has never served, so that nothing pointed a crawler at the sitemap. The stubs are static files rather than routes, so the sitemap stays at 292 URLs. The reasoning is in the knowledge base's website/seo.md. Co-Authored-By: Claude Opus 5 --- docs/resources.md | 25 +++++++++++++++++++++---- docs/tutorials/hello.md | 2 +- docusaurus.config.ts | 4 ++-- static/atom/index.html | 14 ++++++++++++++ static/contribute/index.html | 14 ++++++++++++++ static/feed/index.html | 14 ++++++++++++++ static/overview/index.html | 14 ++++++++++++++ static/resources/index.html | 14 ++++++++++++++ static/robots.txt | 4 ++++ static/tutorials/hello/index.html | 14 ++++++++++++++ static/tutorials/index.html | 14 ++++++++++++++ 11 files changed, 126 insertions(+), 7 deletions(-) create mode 100644 static/atom/index.html create mode 100644 static/contribute/index.html create mode 100644 static/feed/index.html create mode 100644 static/overview/index.html create mode 100644 static/resources/index.html create mode 100644 static/robots.txt create mode 100644 static/tutorials/hello/index.html create mode 100644 static/tutorials/index.html diff --git a/docs/resources.md b/docs/resources.md index 8af19371..d8277844 100644 --- a/docs/resources.md +++ b/docs/resources.md @@ -10,7 +10,17 @@ This page lists some resources related to CGP. More resources will be added as t - [`cgp`](https://crates.io/crates/cgp) - The main Rust crate that provides the core constructs for programming using CGP. - [`cgp-error-anyhow`](https://crates.io/crates/cgp-error-anyhow) - A CGP crate for handling modular errors using `anyhow`. -- [`cgp-serde`](https://github.com/contextgeneric/cgp-serde) - Modular serialization library for Serde. +- [`cgp-error-eyre`](https://crates.io/crates/cgp-error-eyre) - The same, using `eyre`. +- [`cgp-error-std`](https://crates.io/crates/cgp-error-std) - The same, using only the standard library. +- [`cgp-serde`](https://crates.io/crates/cgp-serde) - Modular serialization library for Serde. + +## Tooling + +- [`cargo-cgp`](https://crates.io/crates/cargo-cgp) - CGP's error toolchain. Its `check` command replaces `cargo check` when you are diagnosing a wiring failure, and its `expand` command shows the ordinary Rust that CGP's macros generate. + +Install it with `cargo install cargo-cgp`, then run `cargo cgp setup` to provision the pinned nightly its driver needs. CGP itself compiles on stable Rust without it; the tool is optional. + +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The [`cargo-cgp` section](/docs/cargo-cgp/) covers installation, both commands, and troubleshooting. ## Tutorials @@ -29,10 +39,17 @@ This page lists some resources related to CGP. More resources will be added as t ## Books -- [Context-Generic Programming Patterns](https://patterns.contextgeneric.dev/) - The main book for learning CGP and understand various design patterns for CGP. +- [Context-Generic Programming Patterns](https://patterns.contextgeneric.dev/) - Builds CGP's constructs from first principles, for readers who want to understand what happens behind the macros. Its early chapters explain the ideas in ordinary Rust and remain accurate; its later chapters were written against an earlier release and show syntax that has since changed. + +## CGP in production + +[Hermes SDK](https://github.com/informalsystems/hermes-sdk/) is the system CGP was built for and the +largest real-world use of it. It is an inter-blockchain relayer developed at +[Informal Systems](https://informal.systems/), and its need to support many chains and configurations +from one codebase is the problem the paradigm grew out of. If you are evaluating whether CGP holds up +beyond small examples, this is the codebase to read. ## Projects - [CGP Examples](https://github.com/contextgeneric/cgp-examples) - A repository hosting various examples of using CGP. -- [Hypershell](https://github.com/contextgeneric/hypershell) - A type-level DSL for shell-scripting in Rust. -- [Hermes SDK](https://github.com/informalsystems/hermes-sdk/) - The first project that uses CGP for real world applications. +- [Hypershell](https://github.com/contextgeneric/hypershell) - A type-level DSL for shell-scripting in Rust, built with CGP. diff --git a/docs/tutorials/hello.md b/docs/tutorials/hello.md index b345cf87..6c492f2f 100644 --- a/docs/tutorials/hello.md +++ b/docs/tutorials/hello.md @@ -11,7 +11,7 @@ In this tutorial, we will build a small working program that greets people by na To get started, first include the latest version of the [`cgp` crate](https://crates.io/crates/cgp) as your dependency in `Cargo.toml`: ```toml title="Cargo.toml" -cgp = "0.7.0" +cgp = "0.8.0" ``` ## The CGP Prelude diff --git a/docusaurus.config.ts b/docusaurus.config.ts index 5ff1c027..632f14db 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -6,7 +6,7 @@ import type * as Preset from '@docusaurus/preset-classic'; const config: Config = { title: 'Context-Generic Programming', - tagline: 'Modular programming paradigm for Rust', + tagline: 'A language extension for Rust, with pluggable trait implementations at compile-time', favicon: 'img/favicon.png', // Future flags, see https://docusaurus.io/docs/api/docusaurus-config#future @@ -114,7 +114,7 @@ const config: Config = { announcementBar: { id: 'announcement', content: - '🚀 New Release: Supercharge Rust functions with implicit arguments using CGP v0.7.0 🚀', + '🚀 New Release: Group components with namespaces and paths in CGP v0.8.0 🚀', backgroundColor: '#fcefe1', textColor: '#5D0705', isCloseable: true, diff --git a/static/atom/index.html b/static/atom/index.html new file mode 100644 index 00000000..4aa02f18 --- /dev/null +++ b/static/atom/index.html @@ -0,0 +1,14 @@ + + + + + Page moved | Context-Generic Programming + + + + +

+ This page has moved to /blog/atom.xml. +

+ + diff --git a/static/contribute/index.html b/static/contribute/index.html new file mode 100644 index 00000000..50482bc8 --- /dev/null +++ b/static/contribute/index.html @@ -0,0 +1,14 @@ + + + + + Page moved | Context-Generic Programming + + + + +

+ This page has moved to /docs/contribute. +

+ + diff --git a/static/feed/index.html b/static/feed/index.html new file mode 100644 index 00000000..90a7a248 --- /dev/null +++ b/static/feed/index.html @@ -0,0 +1,14 @@ + + + + + Page moved | Context-Generic Programming + + + + +

+ This page has moved to /blog/rss.xml. +

+ + diff --git a/static/overview/index.html b/static/overview/index.html new file mode 100644 index 00000000..02de65d4 --- /dev/null +++ b/static/overview/index.html @@ -0,0 +1,14 @@ + + + + + Page moved | Context-Generic Programming + + + + +

+ This page has moved to /docs/overview. +

+ + diff --git a/static/resources/index.html b/static/resources/index.html new file mode 100644 index 00000000..ef1e4b7e --- /dev/null +++ b/static/resources/index.html @@ -0,0 +1,14 @@ + + + + + Page moved | Context-Generic Programming + + + + +

+ This page has moved to /docs/resources. +

+ + diff --git a/static/robots.txt b/static/robots.txt new file mode 100644 index 00000000..a79d38f8 --- /dev/null +++ b/static/robots.txt @@ -0,0 +1,4 @@ +User-agent: * +Allow: / + +Sitemap: https://contextgeneric.dev/sitemap.xml diff --git a/static/tutorials/hello/index.html b/static/tutorials/hello/index.html new file mode 100644 index 00000000..e85f1571 --- /dev/null +++ b/static/tutorials/hello/index.html @@ -0,0 +1,14 @@ + + + + + Page moved | Context-Generic Programming + + + + +

+ This page has moved to /docs/tutorials/hello. +

+ + diff --git a/static/tutorials/index.html b/static/tutorials/index.html new file mode 100644 index 00000000..e85f1571 --- /dev/null +++ b/static/tutorials/index.html @@ -0,0 +1,14 @@ + + + + + Page moved | Context-Generic Programming + + + + +

+ This page has moved to /docs/tutorials/hello. +

+ + From 812599b9483e37d717b3fbed6ebf05d510aea3c0 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 21 Sep 2026 03:21:16 +0000 Subject: [PATCH 086/516] Add the Quickstart, and order the sidebar as intended MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The front page's first call to action and every launch post ask the reader to try CGP, and the only honest destination for that ask is a page that gets them to a running program without teaching them anything. Until now that link fell back to the Hello World tutorial, which teaches an idea and is a different page for a different reader. The Quickstart is four parts: cargo add cgp, one complete program for src/main.rs, the exact output to expect, and one link onward. It stops before the second context, which is the whole boundary against Hello World — the tutorial's payoff is running greet unchanged on a second context, and this page has no payoff at all. The two deliberately show similar code so a reader arriving at the tutorial recognizes where they are and sees what is new. Its program is compiled rather than eyeballed, in example-code at tests/quickstart.rs. That is the crate's first standalone test binary, since a standalone page has no section tree to sit in, and the README now records the form and when to use it. Adding the page at position 2 was the occasion to renumber the sidebar into the order information-architecture.md wants: Introduction, Quickstart, Overview, Tutorials, Concepts, Comparisons, Reference, cargo-cgp, Resources, Contribute, and AI last. The page type is specified in the knowledge base's website/writing-guides/orientation.md, written before the page because a new kind of page needs its guide first. Co-Authored-By: Claude Opus 5 --- docs/ai/_category_.json | 2 +- docs/cargo-cgp/_category_.json | 2 +- docs/comparisons/_category_.json | 2 +- docs/concepts/_category_.json | 2 +- docs/overview.md | 2 +- docs/quickstart.md | 80 ++++++++++++++++++++++++++++++++ docs/reference/_category_.json | 2 +- docs/tutorials/_category_.json | 2 +- example-code/README.md | 7 ++- example-code/tests/quickstart.rs | 27 +++++++++++ 10 files changed, 120 insertions(+), 8 deletions(-) create mode 100644 docs/quickstart.md create mode 100644 example-code/tests/quickstart.rs diff --git a/docs/ai/_category_.json b/docs/ai/_category_.json index 81b2fb9d..1039fd64 100644 --- a/docs/ai/_category_.json +++ b/docs/ai/_category_.json @@ -1,6 +1,6 @@ { "label": "AI Assisted Development", - "position": 8, + "position": 11, "link": { "type": "generated-index" } diff --git a/docs/cargo-cgp/_category_.json b/docs/cargo-cgp/_category_.json index 0c0e9b09..fbd8d827 100644 --- a/docs/cargo-cgp/_category_.json +++ b/docs/cargo-cgp/_category_.json @@ -1,6 +1,6 @@ { "label": "cargo-cgp", - "position": 7, + "position": 8, "link": { "type": "doc", "id": "cargo-cgp/index" diff --git a/docs/comparisons/_category_.json b/docs/comparisons/_category_.json index 641f0b5c..fcbbb426 100644 --- a/docs/comparisons/_category_.json +++ b/docs/comparisons/_category_.json @@ -1,6 +1,6 @@ { "label": "Comparisons", - "position": 5, + "position": 6, "link": { "type": "doc", "id": "comparisons/index" diff --git a/docs/concepts/_category_.json b/docs/concepts/_category_.json index 3aa120fc..d2f73f5f 100644 --- a/docs/concepts/_category_.json +++ b/docs/concepts/_category_.json @@ -1,6 +1,6 @@ { "label": "Concepts", - "position": 4, + "position": 5, "link": { "type": "doc", "id": "concepts/index" diff --git a/docs/overview.md b/docs/overview.md index 613c7b8d..03106e92 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,5 +1,5 @@ --- -sidebar_position: 2 +sidebar_position: 3 --- # Overview diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 00000000..ffb35a7d --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,80 @@ +--- +title: 'Quickstart: install CGP and run a program' +sidebar_label: 'Quickstart' +sidebar_position: 2 +description: 'Install Context-Generic Programming and get a working Rust program running, with nothing to configure and no concepts to learn first.' +--- + +# Quickstart + +Context-Generic Programming (CGP) is a language extension for Rust, with pluggable trait +implementations at compile-time. This page does one thing: it gets a program that uses CGP compiling +and running on your machine. It explains nothing along the way. The [Introduction](/docs/) says what +CGP is, and the [Hello World tutorial](/docs/tutorials/hello) teaches the idea behind the code below. + +You need Rust installed, and nothing else. CGP is an ordinary library on the stable toolchain. + +## Install + +In a new or existing project, add the crate: + +```bash +cargo add cgp +``` + +That writes the dependency into your `Cargo.toml`: + +```toml title="Cargo.toml" +[dependencies] +cgp = "0.8.0" +``` + +## The program + +Put this in `src/main.rs`: + +```rust title="src/main.rs" +use cgp::prelude::*; + +#[cgp_fn] +pub fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); +} + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +fn main() { + let person = Person { + name: "World".to_owned(), + }; + + person.greet(); +} +``` + +## Run it + +```bash +cargo run +``` + +You should see: + +```text +Hello, World! +``` + +That is the whole program. CGP is installed and working in your project. + +## Next + +The [Hello World tutorial](/docs/tutorials/hello) walks through the same program and then does the +thing that makes it worth using: it runs `greet` unchanged on a second, different context. + +--- + +*An AI agent wrote this page using the CGP knowledge base, and its program was verified by compiling +and running it. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/_category_.json b/docs/reference/_category_.json index a2975f3e..b5a10e03 100644 --- a/docs/reference/_category_.json +++ b/docs/reference/_category_.json @@ -1,6 +1,6 @@ { "label": "Reference", - "position": 6, + "position": 7, "link": { "type": "doc", "id": "reference/index" diff --git a/docs/tutorials/_category_.json b/docs/tutorials/_category_.json index 9a4cef89..e7daa0e4 100644 --- a/docs/tutorials/_category_.json +++ b/docs/tutorials/_category_.json @@ -1,6 +1,6 @@ { "label": "Tutorials", - "position": 3, + "position": 4, "link": { "type": "generated-index" } diff --git a/example-code/README.md b/example-code/README.md index 5814178a..7ec01581 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -26,6 +26,10 @@ pulls in a module tree that mirrors that section's pages: - `tests/comparisons_tests.rs` → `tests/comparisons/`, mirroring `docs/comparisons/` - `tests/compile_fail_tests.rs` → `tests/compile_fail/`, the snippets the pages **reject** (see below) +**A standalone page gets a test binary of its own instead**, since there is no section tree for it to +sit in: `tests/quickstart.rs` answers `docs/quickstart.md`. Use this form only for a page that has no +section — a page inside one belongs in that section's module tree. + One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | @@ -35,7 +39,8 @@ One file per page, at the matching path with the file name in `snake_case`: | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | none yet | -| front page, orientation pages | none yet | +| `docs/quickstart.md` | complete — `tests/quickstart.rs`, a standalone binary rather than a section tree | +| front page, remaining orientation pages | none yet | Within a covered section the mapping is mechanical: `docs/concepts/coherence.md` is answered by `tests/concepts/coherence.rs`, and `docs/concepts/consumer-and-provider-traits.md` by diff --git a/example-code/tests/quickstart.rs b/example-code/tests/quickstart.rs new file mode 100644 index 00000000..1411d5d9 --- /dev/null +++ b/example-code/tests/quickstart.rs @@ -0,0 +1,27 @@ +//! Runnable check for the code shown on `docs/quickstart.md`. +//! +//! The Quickstart is a standalone page rather than a section, so it gets its own test binary rather +//! than a module tree under a section entry point. The page's entire claim is that this program +//! compiles and runs, so that is what this checks. The page's `fn main` is a `#[test]` here; nothing +//! else differs from what the page shows. + +use cgp::prelude::*; + +#[cgp_fn] +pub fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); +} + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +#[test] +fn quickstart_program_runs() { + let person = Person { + name: "World".to_owned(), + }; + + person.greet(); +} From 992a174dfe766fe8d596f5df3c6312a3b7fd4725 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 21 Sep 2026 03:34:50 +0000 Subject: [PATCH 087/516] Teach checking and debugging as the fourth area-calculation tutorial MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Neither tutorial told the reader that CGP wiring is lazy, named check_components!, or mentioned cargo-cgp — so a reader who mis-wired a context met a wall of generated types at a call site with no idea that either mitigation existed. That was the largest gap in the site's teaching material, and it is the objection that has cost the project the most readers. The page carries one mistake through three diagnostics. PlainCircle is wired to RectangleAreaCalculator, which computes width * height on a shape that has neither, and the program compiles — which is the lesson, because an entry is checked when the component is used rather than when it is written. The raw E0599 at the call site then names neither the missing field nor the provider and points at the line that is correct; check_components! moves the failure to the wiring and names the chain, but spells the field as a Chars list; and cargo cgp check leads with the missing fields in English. Each stage is strictly better than the last, which is what makes the tool's value legible rather than asserted. Every diagnostic was produced by compiling the program, not remembered. The fixed program and the mis-wired one both live in example-code, at tests/tutorials/ and tests/compile_fail/tutorials/, so the checked error the page quotes is pinned by a blessed .stderr. That is the crate's first tutorial coverage. The optional How it works section's claim — that a check is an ordinary trait bound asserted on purpose — was compiled too, and rejects the broken wiring at the impl. The series index now describes the new part, and Static Dispatch routes forward to it instead of closing the series with a summary that stopped being true. Co-Authored-By: Claude Opus 5 --- docs/tutorials/area-calculation/checking.md | 244 ++++++++++++++++++ docs/tutorials/area-calculation/index.md | 5 + .../area-calculation/static-dispatch.md | 6 +- example-code/README.md | 3 +- .../area_calculation_checking_miswired.rs | 70 +++++ .../area_calculation_checking_miswired.stderr | 37 +++ .../tutorials/area_calculation_checking.rs | 99 +++++++ example-code/tests/tutorials_tests.rs | 12 + 8 files changed, 473 insertions(+), 3 deletions(-) create mode 100644 docs/tutorials/area-calculation/checking.md create mode 100644 example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.rs create mode 100644 example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.stderr create mode 100644 example-code/tests/tutorials/area_calculation_checking.rs create mode 100644 example-code/tests/tutorials_tests.rs diff --git a/docs/tutorials/area-calculation/checking.md b/docs/tutorials/area-calculation/checking.md new file mode 100644 index 00000000..75fdedcf --- /dev/null +++ b/docs/tutorials/area-calculation/checking.md @@ -0,0 +1,244 @@ +--- +title: 'Checking and debugging CGP wiring errors' +sidebar_label: 'Checking and Debugging' +sidebar_position: 3 +description: 'Wiring is lazy, so a mis-wired context still compiles. Catch the mistake where you made it with check_components!, and read the error with cargo cgp check.' +--- + +# Checking and Debugging + +In the previous tutorial, we wired each shape context to the area calculator it needs with +`delegate_components!`. Every context we wrote happened to be wired correctly, which left one +question unasked: what happens when it is not? + +In this tutorial we will make a wiring mistake on purpose and watch where Rust reports it. We will +find that it is reported nowhere useful, add `check_components!` to move the failure to the line where +we made it, and then read the same failure through `cargo cgp check`, which names the missing field in +plain English. By the end you will be able to wire a context and know immediately whether you got it +right. + +We continue from the program the previous tutorial ended with, so the line numbers in the errors below +refer to that file rather than to yours. + +## A mis-wired context still compiles + +Here is the mistake. We wire `PlainCircle` to `RectangleAreaCalculator` — the provider that computes +`width * height` — instead of to `CircleAreaCalculator`: + +```rust +delegate_components! { + PlainCircle { + AreaCalculatorComponent: RectangleAreaCalculator, + } +} +``` + +A circle has a `radius` and no `width` or `height`, so this cannot possibly work. Run `cargo check` +anyway: + +```text +Finished `dev` profile [unoptimized + debuginfo] target(s) +``` + +It compiles. Nothing warns, nothing fails, and the mistake sits in the code waiting. + +This is worth understanding rather than working around, because it is not a bug. CGP wiring is +**lazy**: writing a `delegate_components!` entry records which provider a context uses, and Rust +checks whether that provider's requirements are met only when something actually asks the context to +do the work. Until then there is nothing to check against. The entry is a promise, and nobody has +called it in. + +## Where the mistake surfaces instead + +The promise is called in the moment we use the component. Add a line that asks the circle for its +area: + +```rust +fn main() { + let circle = PlainCircle { radius: 2.0 }; + println!("{}", circle.area()); +} +``` + +Now `cargo check` fails, and this is what it says: + +```text +error[E0599]: the method `area` exists for struct `PlainCircle`, but its trait bounds were not satisfied + --> src/main.rs:61:27 + | +42 | pub struct PlainCircle { + | ---------------------- method `area` not found for this struct because it doesn't satisfy + | `PlainCircle: AreaCalculator` or `PlainCircle: CanCalculateArea` +... +61 | println!("{}", circle.area()); + | ^^^^ this is an associated function, not a method +``` + +The full error runs to about thirty lines. Read what it tells us: the method is not available, and two +trait bounds are unsatisfied. Now read what it does not tell us. It does not mention `width`. It does +not mention `height`. It does not mention `RectangleAreaCalculator`, which is the thing we got wrong. +And it points at `main.rs` line 61, which is the line that is *correct* — asking a circle for its area +is a perfectly reasonable thing to do. + +The mistake is fifteen lines earlier, in the wiring, and the compiler has no way to know that. It was +asked whether `PlainCircle` can do the work, found that it cannot, and said so at the place the +question was asked. + +## Asking the question where you wired it + +If the error appears wherever the component is used, then we should ask the question ourselves, at the +line where the wiring lives. That is what `check_components!` does: + +```rust +check_components! { + PlainCircle { + AreaCalculatorComponent, + } +} +``` + +This adds no behavior and generates nothing you will call. It is an assertion: *this context can use +this component*. Put it directly beneath the `delegate_components!` block it checks. + +With that in place, `cargo check` reports the failure at the assertion instead: + +```text +error[E0277]: the trait bound `PlainCircle: CanUseComponent` is not satisfied + --> src/main.rs:61:9 + | +61 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>` + is not implemented for `PlainCircle` + but trait `HasField>>>>>>>` + is implemented for it +... +note: required for `PlainCircle` to implement `RectangleArea` +note: required for `RectangleAreaCalculator` to implement `IsProviderFor` +``` + +Two things improved, and one did not. + +The error now points at **our line**, the one we should be looking at, and the notes at the bottom +name the chain: `PlainCircle` was required to implement `RectangleArea`, which was required for +`RectangleAreaCalculator` to serve this context. That is the actual story of the mistake. + +The cause is in there too, and this is the part that did not improve. That `Symbol<5, Chars<'w', +Chars<'i', ...>>>` is how CGP writes the field name `width` as a type, so that the compiler can +reason about field names at all. Read character by character it says `width`, and the second one says +`radius` — but you have to read it character by character, in the middle of a paragraph of angle +brackets, and the compiler abbreviates the display differently depending on how it is invoked. + +## Reading it with `cargo cgp check` + +Decoding type-level strings by hand is exactly the job a tool should do, and CGP ships one: + +```bash +cargo install cargo-cgp +cargo cgp setup +``` + +The [installation page](/docs/cargo-cgp/installation) covers the other ways to get it, including the +Nix flake, and explains why `setup` is a separate step. `cargo cgp check` then runs the same check as +`cargo check` and rewrites the errors it recognizes. On the same broken program: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `PlainCircle` + --> src/main.rs:61:9 + | +61 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root causes: + - [CGP-E106] missing field `height` on `PlainCircle` + - [CGP-E106] missing field `width` on `PlainCircle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `PlainCircle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `PlainCircle` for provider `RectangleAreaCalculator` + └─ [CGP-E105] trait impl `RectangleArea` for `PlainCircle` + ├─ [CGP-E106] missing field `height` on `PlainCircle` + └─ [CGP-E106] missing field `width` on `PlainCircle` +``` + +This is the same failure a third time, and now it leads with the answer: `PlainCircle` is missing the +fields `width` and `height`. The tree beneath shows how the requirement arrived — through +`RectangleAreaCalculator`, which is the provider we wired by mistake. + +One thing to keep in mind as you use it: `cargo cgp check` leads with the root cause for the classes +it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. When you meet an +error it has not rewritten, you will be reading the raw compiler output, which is why the previous +section is worth understanding rather than skipping. + +## Fixing it + +The error named the provider, so the fix is the line the error pointed at: + +```rust +delegate_components! { + PlainCircle { + AreaCalculatorComponent: CircleAreaCalculator, + } +} + +check_components! { + PlainCircle { + AreaCalculatorComponent, + } +} +``` + +`cargo run` now prints the circle's area: + +```text +12.566370614359172 +``` + +The check stays in the code. It costs nothing at runtime — it generates a trait and an impl and no +values — and it means the next person to touch this wiring finds out immediately if they break it. +Write one for every context you wire. + +## How it works + +*This section explains what `check_components!` generates. You can skip it and come back later.* + +A check is an ordinary trait bound that you assert on purpose. Written by hand, the check above is +close to this: + +```rust +pub trait CanUseAreaCalculator: CanCalculateArea {} + +impl CanUseAreaCalculator for PlainCircle {} +``` + +The trait requires `CanCalculateArea`, and the impl claims `PlainCircle` satisfies it. If it does +not, the compiler rejects the impl — at the impl, which is a line we chose. Nothing calls +`CanUseAreaCalculator` and nothing needs to; writing the impl is the whole point, because writing it +is what forces the compiler to evaluate the bound. + +`check_components!` adds precision about *why* a bound failed. It asserts a bound named +`CanUseComponent` rather than the consumer trait directly, and CGP's providers carry their +requirements in a marker called `IsProviderFor`. Those two are why the error above could name +`RectangleArea` and the missing field rather than stopping at "`CanCalculateArea` is not +implemented". You do not write either of them yourself — they exist so the failure can explain +itself. + +## Summary + +Wiring in CGP is lazy: a `delegate_components!` entry is checked when the component is used, not when +it is written, so a mis-wired context compiles until something asks it to work. The failure then +surfaces at the call site, which is the one place the mistake is not. + +`check_components!` moves the question to the line you chose, directly beneath the wiring it checks, +and turns a latent mistake into a compile error where you can see it. `cargo cgp check` then reads the +result for you, naming the missing field and the chain that required it, for the error classes it +recognizes. + +Neither is optional equipment once a context has more than a couple of components. Wire a context, +check it, and you will never be more than one line away from knowing whether it works. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its code and every diagnostic it quotes +were produced by compiling and running the program. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/tutorials/area-calculation/index.md b/docs/tutorials/area-calculation/index.md index 2c63aa6b..89fbfdc6 100644 --- a/docs/tutorials/area-calculation/index.md +++ b/docs/tutorials/area-calculation/index.md @@ -84,3 +84,8 @@ We have now identified the two core limitations of conventional Rust approaches: In the first tutorial, Context-Generic Functions, we will see how the `#[cgp_fn]` macro and `#[implicit]` arguments address both of these limitations at once, allowing us to write a single `rectangle_area` function that works cleanly across any context that provides the required fields. We will also explore how CGP functions can import each other via `#[uses]`, and take an optional look at how the macro desugars into plain Rust traits under the hood. In the second tutorial, Static Dispatch, we will introduce a second shape — the circle — and define a unified `CanCalculateArea` trait as a common interface across all shapes. We will run into Rust's [coherence](/docs/reference/glossary#coherence) restrictions when trying to provide [blanket implementations](/docs/reference/glossary#blanket-implementation), and then resolve this with CGP's `#[cgp_component]` macro and named providers. Finally, we will see how `delegate_components!` wires contexts to providers at compile time, and how [higher-order providers](/docs/reference/glossary#higher-order-provider) allow provider implementations to compose generically, with zero runtime overhead. + +In the third tutorial, Checking and Debugging, we will make a wiring mistake on purpose. We will find +that CGP wiring is *lazy* — a mis-wired context compiles until something asks it to do the work — and +learn to catch the mistake at the line that made it with `check_components!`, then read the resulting +error with `cargo cgp check`. diff --git a/docs/tutorials/area-calculation/static-dispatch.md b/docs/tutorials/area-calculation/static-dispatch.md index c3bd9005..f418c213 100644 --- a/docs/tutorials/area-calculation/static-dispatch.md +++ b/docs/tutorials/area-calculation/static-dispatch.md @@ -607,7 +607,7 @@ This also shows that CGP providers are just plain Rust types. By leveraging gene ## Summary -Over the course of this tutorial series, we have worked through the full arc from plain Rust code to configurable static dispatch with CGP. +Over the course of this tutorial so far, we have worked through the arc from plain Rust code to configurable static dispatch with CGP. In the introduction, we identified the two fundamental limitations of conventional Rust approaches: explicit parameter threading and tight coupling between methods and concrete context structs. @@ -615,4 +615,6 @@ In the first tutorial, we addressed those limitations with `#[cgp_fn]`, which le In this tutorial, we resolved the remaining boilerplate using CGP components. We annotated `CanCalculateArea` with `#[cgp_component]` to generate a provider trait, defined named provider implementations with `#[cgp_impl]`, and wired them to contexts using `delegate_components!`. We then saw how `#[use_provider]` enables providers to compose with other providers, and how higher-order providers like `ScaledAreaCalculator` use Rust generics to work across all inner calculators without duplication. -Every step of this process is safe, zero-cost Rust: all wiring happens at compile time through the trait system, with no runtime overhead and no unsafe code. \ No newline at end of file +Every step of this process is safe, zero-cost Rust: all wiring happens at compile time through the trait system, with no runtime overhead and no unsafe code. + +One question remains unasked. Every context we wired happened to be wired correctly — so what happens when one is not? In [Checking and Debugging](/docs/tutorials/area-calculation/checking), we will make that mistake on purpose and find out where Rust reports it. \ No newline at end of file diff --git a/example-code/README.md b/example-code/README.md index 7ec01581..de2d9438 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -24,6 +24,7 @@ pulls in a module tree that mirrors that section's pages: - `tests/reference_tests.rs` → `tests/reference/`, mirroring `docs/reference/` - `tests/cargo_cgp_tests.rs` → `tests/cargo_cgp/`, mirroring `docs/cargo-cgp/` - `tests/comparisons_tests.rs` → `tests/comparisons/`, mirroring `docs/comparisons/` +- `tests/tutorials_tests.rs` → `tests/tutorials/`, mirroring `docs/tutorials/` - `tests/compile_fail_tests.rs` → `tests/compile_fail/`, the snippets the pages **reject** (see below) **A standalone page gets a test binary of its own instead**, since there is no section tree for it to @@ -38,7 +39,7 @@ One file per page, at the matching path with the file name in `snake_case`: | `docs/reference/` | partial — `errors.md`, `macros/cgp_namespace.md` and `macros/delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | -| `docs/tutorials/` | none yet | +| `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | | `docs/quickstart.md` | complete — `tests/quickstart.rs`, a standalone binary rather than a section tree | | front page, remaining orientation pages | none yet | diff --git a/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.rs b/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.rs new file mode 100644 index 00000000..6c60cf05 --- /dev/null +++ b/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.rs @@ -0,0 +1,70 @@ +//! `docs/tutorials/area-calculation/checking.md` — the mis-wired program the page starts from. +//! +//! `PlainCircle` is wired to `RectangleAreaCalculator`, which needs `width` and `height` that a +//! circle does not have. The page's point is that this compiles until something checks it, so the +//! `check_components!` below is what turns it into the error the page quotes. + +use cgp::prelude::*; +use core::f64::consts::PI; + +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} + +#[cgp_fn] +pub fn circle_area(&self, #[implicit] radius: f64) -> f64 { + PI * radius * radius +} + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleAreaCalculator)] +#[uses(RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + self.rectangle_area() + } +} + +#[cgp_impl(new CircleAreaCalculator)] +#[uses(CircleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + self.circle_area() + } +} + +#[derive(HasField)] +pub struct PlainRectangle { + pub width: f64, + pub height: f64, +} + +#[derive(HasField)] +pub struct PlainCircle { + pub radius: f64, +} + +delegate_components! { + PlainRectangle { + AreaCalculatorComponent: RectangleAreaCalculator, + } +} + +delegate_components! { + PlainCircle { + AreaCalculatorComponent: RectangleAreaCalculator, + } +} + +check_components! { + PlainCircle { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.stderr b/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.stderr new file mode 100644 index 00000000..515e4dda --- /dev/null +++ b/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.stderr @@ -0,0 +1,37 @@ +error[E0277]: the trait bound `PlainCircle: CanUseComponent` is not satisfied + --> tests/compile_fail/tutorials/area_calculation_checking_miswired.rs:66:9 + | +66 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>` is not implemented for `PlainCircle` + but trait `HasField>>>>>>>` is implemented for it + --> tests/compile_fail/tutorials/area_calculation_checking_miswired.rs:49:9 + | +49 | pub radius: f64, + | ^^^^^^ +note: required for `PlainCircle` to implement `RectangleArea` + --> tests/compile_fail/tutorials/area_calculation_checking_miswired.rs:10:1 + | +10 | #[cgp_fn] + | ^^^^^^^^^ +11 | pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + | ^^^^^^^^^^^^^^ +note: required for `RectangleAreaCalculator` to implement `IsProviderFor` + --> tests/compile_fail/tutorials/area_calculation_checking_miswired.rs:25:1 + | +25 | #[cgp_impl(new RectangleAreaCalculator)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +26 | #[uses(RectangleArea)] + | ------------- unsatisfied trait bound introduced here + = note: required for `PlainCircle` to implement `CanUseComponent` +note: required by a bound in `__CheckPlainCircle` + --> tests/compile_fail/tutorials/area_calculation_checking_miswired.rs:64:1 + | +64 | / check_components! { +65 | | PlainCircle { +66 | | AreaCalculatorComponent, +67 | | } +68 | | } + | |_^ required by this bound in `__CheckPlainCircle` + = note: this error originates in the attribute macro `cgp_fn` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/tutorials/area_calculation_checking.rs b/example-code/tests/tutorials/area_calculation_checking.rs new file mode 100644 index 00000000..f9c93bf9 --- /dev/null +++ b/example-code/tests/tutorials/area_calculation_checking.rs @@ -0,0 +1,99 @@ +//! `docs/tutorials/area-calculation/checking.md` +//! +//! The page walks one mistake through three diagnostics and then fixes it. What is checked here is +//! the fixed program, plus the hand-written equivalent of `check_components!` that the page's +//! "How it works" section claims is close to what the macro generates. The mis-wired program the +//! page starts from is a compile-fail fixture, at +//! `tests/compile_fail/tutorials/area_calculation_checking_miswired.rs`. + +use cgp::prelude::*; +use core::f64::consts::PI; + +#[cgp_fn] +pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} + +#[cgp_fn] +pub fn circle_area(&self, #[implicit] radius: f64) -> f64 { + PI * radius * radius +} + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleAreaCalculator)] +#[uses(RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + self.rectangle_area() + } +} + +#[cgp_impl(new CircleAreaCalculator)] +#[uses(CircleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + self.circle_area() + } +} + +#[derive(HasField)] +pub struct PlainRectangle { + pub width: f64, + pub height: f64, +} + +#[derive(HasField)] +pub struct PlainCircle { + pub radius: f64, +} + +delegate_components! { + PlainRectangle { + AreaCalculatorComponent: RectangleAreaCalculator, + } +} + +delegate_components! { + PlainCircle { + AreaCalculatorComponent: CircleAreaCalculator, + } +} + +check_components! { + PlainRectangle { + AreaCalculatorComponent, + } +} + +check_components! { + PlainCircle { + AreaCalculatorComponent, + } +} + +// The page's "How it works" section: a check is an ordinary trait bound asserted on purpose. This +// compiles only because the wiring above is correct, which is the whole of what it demonstrates. +pub trait CanUseAreaCalculator: CanCalculateArea {} + +impl CanUseAreaCalculator for PlainCircle {} + +#[test] +fn the_fixed_wiring_computes_a_circle_area() { + let circle = PlainCircle { radius: 2.0 }; + + assert_eq!(circle.area(), PI * 4.0); +} + +#[test] +fn the_rectangle_still_works() { + let rectangle = PlainRectangle { + width: 3.0, + height: 4.0, + }; + + assert_eq!(rectangle.area(), 12.0); +} diff --git a/example-code/tests/tutorials_tests.rs b/example-code/tests/tutorials_tests.rs new file mode 100644 index 00000000..c66890cd --- /dev/null +++ b/example-code/tests/tutorials_tests.rs @@ -0,0 +1,12 @@ +//! Runnable checks for the code shown on the `docs/tutorials/` pages. +//! +//! One module per page, under `tests/tutorials/`. See the crate `README.md` for the layout and for +//! how the rejected snippets are handled (they live under `tests/compile_fail/`). + +// A page shows the shape of a program rather than a whole one, so its code carries items nothing calls +// and parameters nothing reads once an elided body is filled in. A genuinely unused import still warns. +#![allow(dead_code, unused_variables)] + +mod tutorials { + mod area_calculation_checking; +} From 946c36d2444989a25b22ed2573665eefc3c17dae Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 21 Sep 2026 04:02:22 +0000 Subject: [PATCH 088/516] Write the page titles and descriptions search results actually show The measured failure is presentation rather than rank: the property draws 81,117 impressions a year outside one anomalous month and converts 1.09% of them, at positions where it is already being shown. Titles and descriptions are the only levers that move that without needing links, authority, or a ranking change. Sixty pages rendered a missing or useless description, several of them literal garbage: the #[cgp_component] page advertised itself in a search result as "[cgp_component]`". Docusaurus derives a description from the first line of content when the front matter omits one, and on a construct page that line is a heading made mostly of punctuation. Fifty-five pages now carry a written description, and the construct pages also carry a search-facing title. Front-matter title sets the metadata and only becomes a heading when the Markdown has none, so each page keeps its construct name as the h1 a reader scans for while its title says what the construct is for. Sidebar labels are untouched. Three generated category indexes gained a description through their _category_.json. All seventeen blog posts are included, because the blog draws three quarters of the property's impressions and had the worst snippets on the site: the second extensible-datatypes post, at 11,340 impressions and a 0.09% click-through rate, advertised itself as "This is the second part of the blog series... You can read the first part here", and the v0.7.0 post's derived snippet stripped the backticks from its identifiers and offered #[cgpfn]. A description is metadata rather than a claim, so this does not reach the dated-artifact rule; each one is self-dating so a post teaching a removed construct reads as a record. Note that Docusaurus also uses it as the feed summary, in place of the excerpt. Every description was audited against its own page body, which caught two that claimed more than their page did and one that said cgp-runtime was anyhow-backed. Co-Authored-By: Claude Opus 5 --- blog/2024-12-19-early-preview-announcement.md | 1 + blog/2025-01-09-v0.3.0-release.md | 1 + blog/2025-05-09-v0.4.0-release.md | 1 + blog/2025-06-14-hypershell-release/index.md | 1 + blog/2025-06-14-v0.4.1-release.md | 1 + blog/2025-07-07-extensible-datatypes-part-1.md | 1 + blog/2025-07-09-extensible-datatypes-part-2.md | 1 + blog/2025-07-12-extensible-datatypes-part-3.md | 1 + blog/2025-07-30-extensible-datatypes-part-4.md | 1 + blog/2025-10-12-v0.5.0-release.md | 1 + blog/2025-10-26-v0.6.0-release.md | 1 + blog/2025-11-03-cgp-serde-release.md | 1 + blog/2026-02-01-v0.6.1-release.md | 1 + blog/2026-02-21-new-website.md | 1 + blog/2026-02-28-v0.7.0-release.md | 1 + blog/2026-03-07-rustlab-2025-coherence/index.md | 1 + blog/2026-05-10-v0.8.0-release.md | 1 + docs/ai/_category_.json | 3 ++- docs/ai/skills/references/_category_.json | 3 ++- docs/reference/attributes/default_impl.md | 2 ++ docs/reference/attributes/derive_delegate.md | 2 ++ docs/reference/attributes/extend.md | 2 ++ docs/reference/attributes/extend_where.md | 2 ++ docs/reference/attributes/impl_generics.md | 2 ++ docs/reference/attributes/implicit.md | 2 ++ docs/reference/attributes/index.md | 2 ++ docs/reference/attributes/prefix.md | 2 ++ docs/reference/attributes/use_provider.md | 2 ++ docs/reference/attributes/use_type.md | 2 ++ docs/reference/attributes/uses.md | 2 ++ docs/reference/derives/derive_build_field.md | 2 ++ docs/reference/derives/derive_cgp_data.md | 2 ++ docs/reference/derives/derive_cgp_record.md | 2 ++ docs/reference/derives/derive_cgp_variant.md | 2 ++ docs/reference/derives/derive_extract_field.md | 2 ++ docs/reference/derives/derive_from_variant.md | 2 ++ docs/reference/derives/derive_has_field.md | 2 ++ docs/reference/derives/derive_has_fields.md | 2 ++ docs/reference/derives/index.md | 2 ++ docs/reference/macros/async_trait.md | 2 ++ docs/reference/macros/blanket_trait.md | 2 ++ docs/reference/macros/cgp_auto_dispatch.md | 2 ++ docs/reference/macros/cgp_auto_getter.md | 2 ++ docs/reference/macros/cgp_component.md | 2 ++ docs/reference/macros/cgp_computer.md | 2 ++ docs/reference/macros/cgp_fn.md | 2 ++ docs/reference/macros/cgp_getter.md | 2 ++ docs/reference/macros/cgp_impl.md | 2 ++ docs/reference/macros/cgp_namespace.md | 2 ++ docs/reference/macros/cgp_producer.md | 2 ++ docs/reference/macros/cgp_provider.md | 2 ++ docs/reference/macros/cgp_type.md | 2 ++ docs/reference/macros/check_components.md | 2 ++ docs/reference/macros/delegate_and_check_components.md | 2 ++ docs/reference/macros/delegate_components.md | 2 ++ docs/reference/macros/index.md | 2 ++ docs/reference/macros/path.md | 2 ++ docs/reference/macros/product.md | 2 ++ docs/reference/macros/sum.md | 2 ++ docs/reference/macros/symbol.md | 2 ++ docs/reference/traits/builder/build_field.md | 2 ++ docs/reference/traits/builder/has_builder.md | 2 ++ docs/reference/traits/casting/can_downcast_fields.md | 2 ++ docs/reference/traits/field-access/field_mapper.md | 2 ++ docs/reference/traits/field-access/has_field_mut.md | 2 ++ docs/reference/traits/formatting/concat_path.md | 2 ++ docs/reference/traits/monad/monadic_trans.md | 2 ++ docs/reference/traits/shape/from_fields.md | 2 ++ docs/reference/traits/shape/has_fields.md | 2 ++ docs/reference/traits/shape/has_fields_ref.md | 2 ++ docs/reference/traits/shape/to_fields.md | 2 ++ docs/reference/traits/shape/to_fields_ref.md | 2 ++ docs/reference/traits/variant/has_extractor.md | 2 ++ docs/reference/types/mref.md | 2 ++ docs/tutorials/_category_.json | 3 ++- 75 files changed, 133 insertions(+), 3 deletions(-) diff --git a/blog/2024-12-19-early-preview-announcement.md b/blog/2024-12-19-early-preview-announcement.md index c70efcec..97e50844 100644 --- a/blog/2024-12-19-early-preview-announcement.md +++ b/blog/2024-12-19-early-preview-announcement.md @@ -3,6 +3,7 @@ slug: early-preview-announcement title: 'Announcing Context-Generic Programming (Early Preview)' authors: [soares] tags: [release] +description: 'The launch post for context-generic programming: what CGP is, the Hermes relayer work it grew out of, and the modular Rust it was built to enable.' --- Welcome everyone! This blog post marks the launch of the _context-generic programming_ (CGP) project, diff --git a/blog/2025-01-09-v0.3.0-release.md b/blog/2025-01-09-v0.3.0-release.md index a2810a74..50c2d886 100644 --- a/blog/2025-01-09-v0.3.0-release.md +++ b/blog/2025-01-09-v0.3.0-release.md @@ -3,6 +3,7 @@ slug: v0-3-0-release title: 'CGP Updates: v0.3.0 Release and New Chapters' authors: [soares] tags: [release] +description: 'CGP v0.3.0 added abstract types, the first getter macros, error wrapping, and the cgp-error-anyhow and cgp-runtime crates.' --- I'm excited to announce the release of [v0.3.0](https://github.com/contextgeneric/cgp/releases/tag/v0.3.0) of the [`cgp`](https://docs.rs/cgp/0.3.0/cgp/) crate, along with several [new](https://patterns.contextgeneric.dev/error-handling.html) [chapters](https://patterns.contextgeneric.dev/field-accessors.html) of the [CGP Patterns](https://patterns.contextgeneric.dev/) book! This post highlights some of the key features and updates included in this release. diff --git a/blog/2025-05-09-v0.4.0-release.md b/blog/2025-05-09-v0.4.0-release.md index 08c6b05d..8f778c21 100644 --- a/blog/2025-05-09-v0.4.0-release.md +++ b/blog/2025-05-09-v0.4.0-release.md @@ -3,6 +3,7 @@ slug: v0-4-0-release title: 'CGP v0.4.0 Release: Unlocking Easier Debugging, Extensible Presets, and More' authors: [soares] tags: [release] +description: 'CGP v0.4.0, the release that made CGP debuggable: IsProviderFor, compile-time wiring checks, and the preset system for reusable configuration.' --- It's been a while since the last update, but the wait is over! I'm thrilled to announce the release of [`v0.4.0`](https://github.com/contextgeneric/cgp/releases/tag/v0.4.0) of the [`cgp`](https://docs.rs/cgp/0.4.0/cgp/) crate. This version is packed with tons of new features and delivers a dramatically smoother developer experience! diff --git a/blog/2025-06-14-hypershell-release/index.md b/blog/2025-06-14-hypershell-release/index.md index be043fc7..407fcf28 100644 --- a/blog/2025-06-14-hypershell-release/index.md +++ b/blog/2025-06-14-hypershell-release/index.md @@ -3,6 +3,7 @@ slug: hypershell-release title: 'Hypershell: A Type-Level DSL for Shell-Scripting in Rust' authors: [soares] tags: [release, deepdive] +description: 'Hypershell is a type-level DSL for shell-scripting in Rust, where a program is a type the compiler interprets. Built with CGP, with its costs stated.' --- I am thrilled to introduce [**Hypershell**](https://github.com/contextgeneric/hypershell), a modular, *type-level* domain-specific language (DSL) for writing shell-script-like programs in Rust. Hypershell is powered by [**context-generic programming**](/) (CGP), which makes it possible for users to *extend* or *modify* both the language syntax and semantics. diff --git a/blog/2025-06-14-v0.4.1-release.md b/blog/2025-06-14-v0.4.1-release.md index 73283b88..d566399f 100644 --- a/blog/2025-06-14-v0.4.1-release.md +++ b/blog/2025-06-14-v0.4.1-release.md @@ -3,6 +3,7 @@ slug: v0-4-1-release title: 'CGP v0.4.1 Release: new cgp-handler crate, improved preset macros, and more.' authors: [soares] tags: [release] +description: 'CGP v0.4.1 introduced the cgp-handler crate, with the Handler, Computer and Producer components the whole computation family rests on.' --- We are excited to announce the release of CGP v0.4.1! This release brings several new features, quality-of-life improvements for macro usages, and a new crate `cgp-handler`. diff --git a/blog/2025-07-07-extensible-datatypes-part-1.md b/blog/2025-07-07-extensible-datatypes-part-1.md index 0d429bc1..aa9e4da1 100644 --- a/blog/2025-07-07-extensible-datatypes-part-1.md +++ b/blog/2025-07-07-extensible-datatypes-part-1.md @@ -3,6 +3,7 @@ slug: extensible-datatypes-part-1 title: 'Programming Extensible Data Types in Rust with CGP - Part 1: Modular App Construction and Extensible Builders' authors: [soares] tags: [release, deepdive] +description: 'Extensible records in CGP v0.4.2: code that works on any struct with the right fields, safe enum casting, and apps built from independent providers.' --- I’m excited to announce the release of [**CGP v0.4.2**](https://github.com/contextgeneric/cgp/releases/tag/v0.4.2), a major milestone that significantly expands the expressive power of generic programming in Rust. With this release, CGP introduces full support for **extensible records and variants**, unlocking a range of new capabilities for developers working with highly modular and reusable code. diff --git a/blog/2025-07-09-extensible-datatypes-part-2.md b/blog/2025-07-09-extensible-datatypes-part-2.md index 3d5e5398..7715924f 100644 --- a/blog/2025-07-09-extensible-datatypes-part-2.md +++ b/blog/2025-07-09-extensible-datatypes-part-2.md @@ -3,6 +3,7 @@ slug: extensible-datatypes-part-2 title: 'Programming Extensible Data Types in Rust with CGP - Part 2: Modular Interpreters and Extensible Visitors' authors: [soares] tags: [deepdive] +description: 'Extensible variants applied to the expression problem: a modular arithmetic interpreter built with the extensible visitor pattern.' --- This is the **second** part of the blog series on **Programming Extensible Data Types in Rust with CGP**. You can read the [first part here](/blog/extensible-datatypes-part-1). diff --git a/blog/2025-07-12-extensible-datatypes-part-3.md b/blog/2025-07-12-extensible-datatypes-part-3.md index 1ddacbb0..0cccef83 100644 --- a/blog/2025-07-12-extensible-datatypes-part-3.md +++ b/blog/2025-07-12-extensible-datatypes-part-3.md @@ -3,6 +3,7 @@ slug: extensible-datatypes-part-3 title: 'Programming Extensible Data Types in Rust with CGP - Part 3: Implementing Extensible Records' authors: [soares] tags: [deepdive] +description: 'How extensible records are implemented: partial records, constraint propagation, and the builder dispatchers underneath them.' --- This is the **third** part of the blog series on **Programming Extensible Data Types in Rust with CGP**. You can read the [first](/blog/extensible-datatypes-part-1) and [second](/blog/extensible-datatypes-part-2) parts here. diff --git a/blog/2025-07-30-extensible-datatypes-part-4.md b/blog/2025-07-30-extensible-datatypes-part-4.md index 20037e43..3dc5ae89 100644 --- a/blog/2025-07-30-extensible-datatypes-part-4.md +++ b/blog/2025-07-30-extensible-datatypes-part-4.md @@ -3,6 +3,7 @@ slug: extensible-datatypes-part-4 title: 'Programming Extensible Data Types in Rust with CGP - Part 4: Implementing Extensible Variants' authors: [soares] tags: [deepdive] +description: 'How extensible variants are implemented: the empty Void type, exhaustive extraction, the enum casts, and the monadic visitor dispatchers.' --- This is the **fourth** part of the blog series on **Programming Extensible Data Types in Rust with CGP**. You can read the [first](/blog/extensible-datatypes-part-1), [second](/blog/extensible-datatypes-part-2) and [third](/blog/extensible-datatypes-part-3) parts here. diff --git a/blog/2025-10-12-v0.5.0-release.md b/blog/2025-10-12-v0.5.0-release.md index 493dfcc4..a2c0a8a4 100644 --- a/blog/2025-10-12-v0.5.0-release.md +++ b/blog/2025-10-12-v0.5.0-release.md @@ -3,6 +3,7 @@ slug: v0-5-0-release title: 'CGP v0.5.0 Release: Auto dispatchers, extensible datatype improvements, monadic computation, RTN emulation, modular serde, and more' authors: [soares] tags: [release] +description: 'CGP v0.5.0: the CgpData derive, automatic dispatch, monadic computation, and the removal of the Async trait in favour of Send recovery.' --- [CGP v0.5.0](https://crates.io/crates/cgp/0.5.0) has been released, bringing a range of new features and some breaking changes as part of the ongoing effort toward stabilization. This version introduces several improvements to make CGP more practical, expressive, and easier to use in real-world Rust projects. diff --git a/blog/2025-10-26-v0.6.0-release.md b/blog/2025-10-26-v0.6.0-release.md index 3ab98059..377d364c 100644 --- a/blog/2025-10-26-v0.6.0-release.md +++ b/blog/2025-10-26-v0.6.0-release.md @@ -3,6 +3,7 @@ slug: v0-6-0-release title: 'CGP v0.6.0 Release: Major ergonomic improvements for provider and context implementations' authors: [soares] tags: [release] +description: 'CGP v0.6.0 brought cgp_impl and direct delegation on the context, the release that made CGP code start to look like ordinary Rust.' --- It has only been two weeks since [v0.5.0 was released](/blog/v0-5-0-release/), yet we are already introducing another major update. [**CGP v0.6.0**](https://github.com/contextgeneric/cgp/releases/tag/v0.6.0) brings significant improvements to the ergonomics of implementing providers and contexts, making it easier and more intuitive for developers to build on top of CGP. diff --git a/blog/2025-11-03-cgp-serde-release.md b/blog/2025-11-03-cgp-serde-release.md index 73773987..32664fa2 100644 --- a/blog/2025-11-03-cgp-serde-release.md +++ b/blog/2025-11-03-cgp-serde-release.md @@ -3,6 +3,7 @@ slug: cgp-serde-release title: 'Announcing cgp-serde: A modular serialization library for Serde powered by CGP' authors: [soares] tags: [release] +description: 'cgp-serde rebuilds Serde''s Serialize and Deserialize as CGP components, so two applications can encode the same data in different formats.' --- I am excited to announce the release of [**cgp-serde**](https://github.com/contextgeneric/cgp-serde), a modular serialization library for [Serde](https://serde.rs/) that leverages the power of [**Context-Generic Programming**](/) (CGP). diff --git a/blog/2026-02-01-v0.6.1-release.md b/blog/2026-02-01-v0.6.1-release.md index ef053876..97e3e98b 100644 --- a/blog/2026-02-01-v0.6.1-release.md +++ b/blog/2026-02-01-v0.6.1-release.md @@ -2,6 +2,7 @@ slug: v0-6-1-release authors: [soares] tags: [release] +description: 'CGP v0.6.1: implicit context types in provider impls, an attribute for checking individual provider layers, and associated types in getter traits.' --- # CGP v0.6.1 Release: Improving Ergonomics and Debugging diff --git a/blog/2026-02-21-new-website.md b/blog/2026-02-21-new-website.md index bd0dc9a6..d38bc044 100644 --- a/blog/2026-02-21-new-website.md +++ b/blog/2026-02-21-new-website.md @@ -1,6 +1,7 @@ --- authors: [soares] tags: [release] +description: 'Why the CGP site moved from Zola to Docusaurus, the decision to keep the installation stock, and how LLM assistance was used in the redesign.' --- # CGP has a new website, and why we moved from Zola to Docusaurus diff --git a/blog/2026-02-28-v0.7.0-release.md b/blog/2026-02-28-v0.7.0-release.md index 33b7ba28..35a5da1e 100644 --- a/blog/2026-02-28-v0.7.0-release.md +++ b/blog/2026-02-28-v0.7.0-release.md @@ -2,6 +2,7 @@ slug: 'v0.7.0-release' authors: [soares] tags: [release] +description: 'CGP v0.7.0 added cgp_fn, implicit, uses and use_type, the attributes that made providers read like ordinary Rust functions, and removed cgp_context.' --- # Supercharge Rust functions with implicit arguments using CGP v0.7.0 diff --git a/blog/2026-03-07-rustlab-2025-coherence/index.md b/blog/2026-03-07-rustlab-2025-coherence/index.md index c68dff80..7370b9d5 100644 --- a/blog/2026-03-07-rustlab-2025-coherence/index.md +++ b/blog/2026-03-07-rustlab-2025-coherence/index.md @@ -1,6 +1,7 @@ --- slug: 'rustlab-2025-coherence' authors: [soares] +description: 'The RustLab 2025 talk, with slides and full transcript: why Rust''s coherence rules exist, and how provider traits let implementations coexist.' --- # How to stop fighting with coherence and start writing context-generic trait impls - RustLab 2025 transcript diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index 5ad1d0a0..e3e5e3cd 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -2,6 +2,7 @@ slug: 'v0.8.0-release' authors: [soares] tags: [release] +description: 'CGP v0.8.0 groups components with namespaces and paths, so a wiring table stays readable as an application''s component count grows.' --- # CGP v0.8.0 - Grouping components with namespaces and paths diff --git a/docs/ai/_category_.json b/docs/ai/_category_.json index 1039fd64..204966aa 100644 --- a/docs/ai/_category_.json +++ b/docs/ai/_category_.json @@ -2,6 +2,7 @@ "label": "AI Assisted Development", "position": 11, "link": { - "type": "generated-index" + "type": "generated-index", + "description": "CGP's published agent skill, for handing to a coding assistant, and how the project discloses its own use of AI." } } diff --git a/docs/ai/skills/references/_category_.json b/docs/ai/skills/references/_category_.json index 517c7c33..89db67f3 100644 --- a/docs/ai/skills/references/_category_.json +++ b/docs/ai/skills/references/_category_.json @@ -1,6 +1,7 @@ { "label": "References", "link": { - "type": "generated-index" + "type": "generated-index", + "description": "The CGP agent skill's reference pages, published from the cgp-skills repository for assistants to read." } } diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index c12b7261..acc5b494 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -1,6 +1,8 @@ --- +title: '#[default_impl] — a namespace''s default provider' sidebar_label: '#[default_impl]' sidebar_position: 9 +description: 'Register a provider as a namespace''s default for a key, from the provider''s own definition rather than from the namespace table.' --- # `#[default_impl(...)]` diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 74c3abf4..d0755e0e 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -1,6 +1,8 @@ --- +title: '#[derive_delegate] — the legacy dispatch table' sidebar_label: '#[derive_delegate]' sidebar_position: 10 +description: 'Generate the UseDelegate dispatcher for a component generic over a parameter. Superseded by the open statement, and documented for reading existing code.' --- # `#[derive_delegate]` diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 07ffd9e9..d0462855 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -1,6 +1,8 @@ --- +title: '#[extend] — add a supertrait' sidebar_label: '#[extend]' sidebar_position: 5 +description: 'Add a trait as a supertrait of a generated trait, so callers can rely on it too, which is the only way to declare one on a CGP function.' --- # `#[extend]` diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 0d45450f..801cec1b 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -1,6 +1,8 @@ --- +title: '#[extend_where] — bounds on a generated trait' sidebar_label: '#[extend_where]' sidebar_position: 6 +description: 'Add where predicates to a generated trait''s own definition rather than only to its implementation, for bounds callers must prove.' --- # `#[extend_where]` diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 972f5b07..f677679e 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -1,6 +1,8 @@ --- +title: '#[impl_generics] — a parameter on the impl alone' sidebar_label: '#[impl_generics]' sidebar_position: 7 +description: 'Declare a generic parameter on the generated implementation alone, so a context supplies the type through a field and callers never name it.' --- # `#[impl_generics(...)]` diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index c86f2771..e104c214 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -1,6 +1,8 @@ --- +title: '#[implicit] — arguments from context fields' sidebar_label: '#[implicit]' sidebar_position: 1 +description: 'Source a function argument from a same-named field on the context, so an implementation reads what it needs without the caller passing it.' --- # `#[implicit]` diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index f63de80d..2d62ed89 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -1,6 +1,8 @@ --- +title: 'Attribute reference' sidebar_label: 'Overview' sidebar_position: 0 +description: 'The modifier attributes that refine what a CGP macro generates: declaring dependencies, importing abstract types, and sourcing arguments from fields.' --- # Attributes diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index b400fb3a..678a4f62 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -1,6 +1,8 @@ --- +title: '#[prefix] — register into a namespace' sidebar_label: '#[prefix]' sidebar_position: 8 +description: 'Register a component into a namespace under a type-level path, so every context joining that namespace addresses the component by that path.' --- # `#[prefix(...)]` diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index faf19d43..ab40a2de 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -1,6 +1,8 @@ --- +title: '#[use_provider] — depend on a provider' sidebar_label: '#[use_provider]' sidebar_position: 4 +description: 'Depend on another provider by name in a higher-order provider, importing the provider trait it must satisfy.' --- # `#[use_provider]` diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index aa5f069d..6394b55f 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -1,6 +1,8 @@ --- +title: '#[use_type] — import an abstract type' sidebar_label: '#[use_type]' sidebar_position: 3 +description: 'Import an abstract associated type into an implementation and write it as a bare name, with the equality form that pins it to a concrete type.' --- # `#[use_type]` diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 1923c1c2..a33b0dc0 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -1,6 +1,8 @@ --- +title: '#[uses] — declare trait dependencies' sidebar_label: '#[uses]' sidebar_position: 2 +description: 'Import the traits an implementation depends on, reading like a use statement, instead of writing the bounds out in a where clause.' --- # `#[uses]` diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 211a092e..ed6e4b94 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -1,6 +1,8 @@ --- +title: '#[derive(BuildField)] — a typed struct builder' sidebar_label: '#[derive(BuildField)]' sidebar_position: 6 +description: 'Generate a builder that tracks in its own type which fields of a struct have been supplied, so an incomplete record cannot be finalized.' --- # `#[derive(BuildField)]` diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 71604b89..7fd3cdbd 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -1,6 +1,8 @@ --- +title: '#[derive(CgpData)] — all extensible-data traits' sidebar_label: '#[derive(CgpData)]' sidebar_position: 3 +description: 'Generate structural access and the incremental building and extraction operations for a struct or enum, as the umbrella over the narrower derives.' --- # `#[derive(CgpData)]` diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index 03ca573d..48d40ff1 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -1,6 +1,8 @@ --- +title: '#[derive(CgpRecord)] — extensible records' sidebar_label: '#[derive(CgpRecord)]' sidebar_position: 4 +description: 'Generate field access, a structural representation, and a builder for a struct, as the record half of the extensible-data derives.' --- # `#[derive(CgpRecord)]` diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index fde79c06..7c4462ef 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -1,6 +1,8 @@ --- +title: '#[derive(CgpVariant)] — extensible variants' sidebar_label: '#[derive(CgpVariant)]' sidebar_position: 5 +description: 'Generate a structural representation, constructors, and an extractor for an enum, as the variant half of the extensible-data derives.' --- # `#[derive(CgpVariant)]` diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 899bb25e..43966808 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -1,6 +1,8 @@ --- +title: '#[derive(ExtractField)] — a typed enum extractor' sidebar_label: '#[derive(ExtractField)]' sidebar_position: 7 +description: 'Generate an extractor that tracks in its own type which variants of an enum remain, so exhaustiveness is checked without a wildcard arm.' --- # `#[derive(ExtractField)]` diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index a86a684d..ab1c2e06 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -1,6 +1,8 @@ --- +title: '#[derive(FromVariant)] — construct a variant' sidebar_label: '#[derive(FromVariant)]' sidebar_position: 8 +description: 'Let generic code construct an enum variant selected by a type-level tag, without naming the variant or the enum.' --- # `#[derive(FromVariant)]` diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 4b7ea42b..5f24d58c 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -1,6 +1,8 @@ --- +title: '#[derive(HasField)] — field access by tag' sidebar_label: '#[derive(HasField)]' sidebar_position: 1 +description: 'Generate shared and mutable accessors for every field of a struct, keyed by type-level tags, which is what lets an implicit argument find a field.' --- # `#[derive(HasField)]` diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index bcc549d1..33d5cf8b 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -1,6 +1,8 @@ --- +title: '#[derive(HasFields)] — a type''s whole shape' sidebar_label: '#[derive(HasFields)]' sidebar_position: 2 +description: 'Generate a structural representation of a struct or enum and the conversions to and from it, exposing its whole field or variant list to generic code.' --- # `#[derive(HasFields)]` diff --git a/docs/reference/derives/index.md b/docs/reference/derives/index.md index 2e3e7f06..18bb607e 100644 --- a/docs/reference/derives/index.md +++ b/docs/reference/derives/index.md @@ -1,6 +1,8 @@ --- +title: 'Derive reference' sidebar_label: 'Overview' sidebar_position: 0 +description: 'The derives that let generic code access, describe, build and deconstruct a struct or enum without naming its concrete type.' --- # Derives diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 240f7cec..9be1fc4c 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -1,6 +1,8 @@ --- +title: '#[async_trait] — async methods in CGP traits' sidebar_label: '#[async_trait]' sidebar_position: 12 +description: 'Rewrite a trait''s async fn declarations into the lint-clean impl Future form that CGP''s async methods use, without allocating.' --- # `#[async_trait]` diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index c4af1e53..60f03172 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -1,6 +1,8 @@ --- +title: '#[blanket_trait] — generate a blanket impl' sidebar_label: '#[blanket_trait]' sidebar_position: 11 +description: 'Generate a blanket implementation from a Rust trait with default methods and supertrait dependencies.' --- # `#[blanket_trait]` diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index f27b5a75..9095b819 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_auto_dispatch] — dispatch over variants' sidebar_label: '#[cgp_auto_dispatch]' sidebar_position: 15 +description: 'Generate a handler that dispatches over an extensible-data input from a per-type trait, routing each variant to its own implementation.' --- # `#[cgp_auto_dispatch]` diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index efa78a3a..bef1a35f 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_auto_getter] — getters from field names' sidebar_label: '#[cgp_auto_getter]' sidebar_position: 8 +description: 'Define a getter as a blanket implementation over HasField, keyed by the method name, for reading a field from any context that has one.' --- # `#[cgp_auto_getter]` diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 9d423cb4..d97a833b 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_component] — define a component' sidebar_label: '#[cgp_component]' sidebar_position: 1 +description: 'Turn one Rust trait into a CGP component: the consumer trait callers use, the provider trait implementations target, and the key that wires them together.' --- # `#[cgp_component]` diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index c5666223..c0edd3de 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_computer] — a Computer from a function' sidebar_label: '#[cgp_computer]' sidebar_position: 13 +description: 'Define a Computer provider from a plain Rust function, with the promotion tables that let one function answer the rest of the handler family.' --- # `#[cgp_computer]` diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index dae6b1cd..bdc81c11 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_fn] — a trait from a function' sidebar_label: '#[cgp_fn]' sidebar_position: 3 +description: 'Turn a plain Rust function into a trait with a single blanket implementation, so it runs on any context that supplies the fields it needs.' --- # `#[cgp_fn]` diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 2599e656..6b8d6eaa 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_getter] — getters chosen by wiring' sidebar_label: '#[cgp_getter]' sidebar_position: 9 +description: 'Define a getter as a full CGP component, so the field it reads is chosen when a context is wired rather than fixed to the method name.' --- # `#[cgp_getter]` diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index f6bbbf49..f74e031a 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_impl] — write a provider' sidebar_label: '#[cgp_impl]' sidebar_position: 2 +description: 'Write a CGP provider in ordinary consumer-trait shape, keeping self, Self and the method signatures you already know, instead of the inside-out form.' --- # `#[cgp_impl]` diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index b1cb5967..026e670c 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -1,6 +1,8 @@ --- +title: 'cgp_namespace! — reusable wiring tables' sidebar_label: 'cgp_namespace!' sidebar_position: 10 +description: 'Define a reusable, inheritable wiring table that many contexts can join, so a configuration stays short as the component count grows.' --- # `cgp_namespace!` diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 57068737..a354b57d 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_producer] — a Producer from a function' sidebar_label: '#[cgp_producer]' sidebar_position: 14 +description: 'Define a Producer provider from an input-free function, for a computation that takes only a context and a code tag.' --- # `#[cgp_producer]` diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index a87aaac0..d9056e97 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_provider] and #[cgp_new_provider]' sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' sidebar_position: 20 +description: 'Implement a provider trait directly, in the inside-out shape the ergonomic macros desugar to, with or without declaring the provider struct.' --- # `#[cgp_provider]` & `#[cgp_new_provider]` diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 70689bfa..43bfe29a 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -1,6 +1,8 @@ --- +title: '#[cgp_type] — abstract types per context' sidebar_label: '#[cgp_type]' sidebar_position: 7 +description: 'Define an abstract-type component whose concrete type each context chooses for itself, for an error type, a runtime, or any type generic code has to name.' --- # `#[cgp_type]` diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index a8020e02..eaa36edd 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -1,6 +1,8 @@ --- +title: 'check_components! — verify a context''s wiring' sidebar_label: 'check_components!' sidebar_position: 5 +description: 'Assert at compile time that a context can use the components it wires, so a missing dependency fails at the assertion rather than at a distant call site.' --- # `check_components!` diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 3c0e9a18..dfc9b0ab 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -1,6 +1,8 @@ --- +title: 'delegate_and_check_components! — wire and check' sidebar_label: 'delegate_and_check_components!' sidebar_position: 6 +description: 'Wire a context and check that wiring in one macro, for getting started and for plain Component: Provider tables. Wrong for an aggregate provider.' --- # `delegate_and_check_components!` diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 8c101f2e..d0cf1d7a 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -1,6 +1,8 @@ --- +title: 'delegate_components! — wire a context' sidebar_label: 'delegate_components!' sidebar_position: 4 +description: 'Build a context''s wiring table, naming the provider that implements each component, plus the operators, path keys and statements its body accepts.' --- # `delegate_components!` diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md index b8f4c3b9..13200c05 100644 --- a/docs/reference/macros/index.md +++ b/docs/reference/macros/index.md @@ -1,6 +1,8 @@ --- +title: 'Macro reference' sidebar_label: 'Overview' sidebar_position: 0 +description: 'Every CGP macro grouped by the job it does: defining a component and its providers, wiring and checking a context, and building type-level values.' --- # Macros diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 268a263f..bafbf049 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -1,6 +1,8 @@ --- +title: 'Path! — type-level paths' sidebar_label: 'Path!' sidebar_position: 19 +description: 'A type-level path, used by CGP namespaces and by component lookups that are redirected along one.' --- # `Path!` diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index d9b2a820..5f5c519e 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -1,6 +1,8 @@ --- +title: 'Product! — type-level lists' sidebar_label: 'Product! & product!' sidebar_position: 17 +description: 'A type-level list and its value-level counterpart, used for the field lists of a record and for handler pipelines.' --- # `Product!` & `product!` diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index f767292b..b5ce46cf 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -1,6 +1,8 @@ --- +title: 'Sum! — type-level sums' sidebar_label: 'Sum!' sidebar_position: 18 +description: 'A type-level sum, the dual of Product!, used for the variant lists of an extensible enum.' --- # `Sum!` diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index ae8abb84..9e65c45e 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -1,6 +1,8 @@ --- +title: 'Symbol! — type-level strings' sidebar_label: 'Symbol!' sidebar_position: 16 +description: 'A type-level string, used as the tag that names a struct field in CGP''s field-access traits.' --- # `Symbol!` diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index 16b5558c..84088ae8 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -1,6 +1,8 @@ --- +title: 'BuildField — set one field of a builder' sidebar_label: 'BuildField' sidebar_position: 3 +description: 'Set a currently-absent field on a partial record, which is the direction of the builder family you write most when assembling a struct field by field.' --- # `BuildField` diff --git a/docs/reference/traits/builder/has_builder.md b/docs/reference/traits/builder/has_builder.md index 02e041f8..ffde1632 100644 --- a/docs/reference/traits/builder/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -1,6 +1,8 @@ --- +title: 'HasBuilder — start an empty builder' sidebar_label: 'HasBuilder' sidebar_position: 1 +description: 'Start an empty builder for a record, as the entry point to assembling a struct field by field rather than through a struct literal that names the type.' --- # `HasBuilder` diff --git a/docs/reference/traits/casting/can_downcast_fields.md b/docs/reference/traits/casting/can_downcast_fields.md index e4dd9a30..264dbecf 100644 --- a/docs/reference/traits/casting/can_downcast_fields.md +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -1,6 +1,8 @@ --- +title: 'CanDowncastFields — continue a narrowing' sidebar_label: 'CanDowncastFields' sidebar_position: 3 +description: 'Continue narrowing on the remainder a failed downcast hands back, so a value can be tried against a second target and a third. Never used on its own.' --- # `CanDowncastFields` diff --git a/docs/reference/traits/field-access/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md index 3f311ac4..90da9e4e 100644 --- a/docs/reference/traits/field-access/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -1,6 +1,8 @@ --- +title: 'FieldMapper — the provider side of MapField' sidebar_label: 'FieldMapper' sidebar_position: 6 +description: 'The provider-side mirror of MapField, generated as a blanket implementation over every field getter. You meet it in an expansion rather than call it.' --- # `FieldMapper` diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index 9aa65637..f07cb666 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -1,6 +1,8 @@ --- +title: 'HasFieldMut — mutable field access by tag' sidebar_label: 'HasFieldMut' sidebar_position: 2 +description: 'Mutable tag-keyed field access, letting an implementation change a field of a context it cannot name, as the mutable counterpart of HasField.' --- # `HasFieldMut` diff --git a/docs/reference/traits/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md index 1b3bb539..3b3fb7ad 100644 --- a/docs/reference/traits/formatting/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -1,6 +1,8 @@ --- +title: 'ConcatPath — join two type-level paths' sidebar_label: 'ConcatPath' sidebar_position: 3 +description: 'Join two type-level paths, which CGP''s namespace machinery uses to address a component. You are not expected to call it directly.' --- # `ConcatPath` diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index 12e448a4..a24bf4db 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -1,6 +1,8 @@ --- +title: 'MonadicTrans — stack one monad on another' sidebar_label: 'MonadicTrans' sidebar_position: 4 +description: 'Stack one monad on top of another, which the monadic handler combinators resolve for you rather than asking you to name the stack yourself.' --- # `MonadicTrans` diff --git a/docs/reference/traits/shape/from_fields.md b/docs/reference/traits/shape/from_fields.md index d64da179..914bf420 100644 --- a/docs/reference/traits/shape/from_fields.md +++ b/docs/reference/traits/shape/from_fields.md @@ -1,6 +1,8 @@ --- +title: 'FromFields — rebuild a value from its shape' sidebar_label: 'FromFields' sidebar_position: 4 +description: 'Rebuild a concrete struct or enum from the anonymous shape ToFields produced, as the return journey of a structural operation.' --- # `FromFields` diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index 9510e151..1dafa3da 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -1,6 +1,8 @@ --- +title: 'HasFields — a type''s whole shape' sidebar_label: 'HasFields' sidebar_position: 1 +description: 'Name a type''s whole shape as a single type, every field with its name and type, so generic code can walk a struct or enum it cannot name.' --- # `HasFields` diff --git a/docs/reference/traits/shape/has_fields_ref.md b/docs/reference/traits/shape/has_fields_ref.md index 979aa4f3..361ca672 100644 --- a/docs/reference/traits/shape/has_fields_ref.md +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -1,6 +1,8 @@ --- +title: 'HasFieldsRef — a borrowed whole shape' sidebar_label: 'HasFieldsRef' sidebar_position: 2 +description: 'Name a type''s whole shape with every value borrowed, so generic code can read a struct or enum without consuming it. Derived rather than written.' --- # `HasFieldsRef` diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index 26327e5c..dc33f856 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -1,6 +1,8 @@ --- +title: 'ToFields — take a value apart into its shape' sidebar_label: 'ToFields' sidebar_position: 3 +description: 'Produce a value in the shape HasFields names, taking a struct or enum apart into an anonymous list of named entries.' --- # `ToFields` diff --git a/docs/reference/traits/shape/to_fields_ref.md b/docs/reference/traits/shape/to_fields_ref.md index 785cca20..2594aab5 100644 --- a/docs/reference/traits/shape/to_fields_ref.md +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -1,6 +1,8 @@ --- +title: 'ToFieldsRef — read a shape without consuming' sidebar_label: 'ToFieldsRef' sidebar_position: 5 +description: 'Walk a value''s shape without consuming it, for code that only reads the fields of a struct or enum it cannot name.' --- # `ToFieldsRef` diff --git a/docs/reference/traits/variant/has_extractor.md b/docs/reference/traits/variant/has_extractor.md index 54329631..42d7c216 100644 --- a/docs/reference/traits/variant/has_extractor.md +++ b/docs/reference/traits/variant/has_extractor.md @@ -1,6 +1,8 @@ --- +title: 'HasExtractor — an enum as an extractor' sidebar_label: 'HasExtractor' sidebar_position: 2 +description: 'Turn an enum into the extractor the variant-narrowing traits operate on, and back, since ExtractField narrows an extractor rather than an enum.' --- # `HasExtractor` diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 646e8a2b..ea0f6cf2 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -1,6 +1,8 @@ --- +title: 'MRef — a borrowed or owned value' sidebar_label: 'MRef' sidebar_position: 11 +description: 'A value that is either a borrow of a T or an owned T, so one getter signature serves both the context that stores a value and the one that computes it.' --- # `MRef` diff --git a/docs/tutorials/_category_.json b/docs/tutorials/_category_.json index e7daa0e4..516bd6d4 100644 --- a/docs/tutorials/_category_.json +++ b/docs/tutorials/_category_.json @@ -2,6 +2,7 @@ "label": "Tutorials", "position": 4, "link": { - "type": "generated-index" + "type": "generated-index", + "description": "Guided walkthroughs that build working CGP programs, from a first greeting to wiring a context and debugging it." } } From 46d0c2089ea8d96f1b75fd1212f3a77c1fb3aefd Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 21 Sep 2026 04:19:28 +0000 Subject: [PATCH 089/516] Lead every page title with CGP, and give the front page its own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Search Console shows the acronym drawing seven times the impressions of the full term and a twelfth of the intent — 1,698 impressions and 23 clicks against 245 and 41 — because most of that volume is people looking for a different CGP. Even so, a reader who searches cgp rust or cgp dsl should see the term they typed in the result, which is a click-through argument rather than a matching one. The site title is now "CGP — Context-Generic Programming", so every page renders as {Page} | CGP — Context-Generic Programming. The acronym sits immediately after the separator rather than at the end, which matters because 72 of 285 titles already exceed the roughly 60 characters a result shows: appended to the end of the suffix it would have been the first thing cut. It now falls inside the visible portion on 280 of 286 pages. That made the acronym redundant in fifteen page titles which had carried it for the same reason, rendering it twice in one title, so those are reverted. The titles that still repeat it are the ones whose subject is CGP, where the page's own words stand alone. The front page names the project first instead, which Docusaurus cannot format: passing title to Layout renders {title} | {siteTitle}. It sets the tag directly with @docusaurus/Head, and og:title with it. Its title had been the tagline, which with the suffix ran to 119 characters and pushed every distinguishing word past what a result shows, and its description still carried the retired "modular programming paradigm" line; the description now opens with the settled tag line verbatim. Co-Authored-By: Claude Opus 5 --- docs/reference/macros/check_components.md | 2 +- docs/reference/types/mref.md | 2 +- docs/tutorials/area-calculation/checking.md | 2 +- docusaurus.config.ts | 2 +- src/pages/index.tsx | 21 +++++++++++++++++---- 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index eaa36edd..dfbf242e 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -1,5 +1,5 @@ --- -title: 'check_components! — verify a context''s wiring' +title: 'check_components! — verify your wiring' sidebar_label: 'check_components!' sidebar_position: 5 description: 'Assert at compile time that a context can use the components it wires, so a missing dependency fails at the assertion rather than at a distant call site.' diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index ea0f6cf2..1b439427 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -1,5 +1,5 @@ --- -title: 'MRef — a borrowed or owned value' +title: 'MRef — a borrowed or owned getter value' sidebar_label: 'MRef' sidebar_position: 11 description: 'A value that is either a borrow of a T or an owned T, so one getter signature serves both the context that stores a value and the one that computes it.' diff --git a/docs/tutorials/area-calculation/checking.md b/docs/tutorials/area-calculation/checking.md index 75fdedcf..d74144eb 100644 --- a/docs/tutorials/area-calculation/checking.md +++ b/docs/tutorials/area-calculation/checking.md @@ -1,5 +1,5 @@ --- -title: 'Checking and debugging CGP wiring errors' +title: 'Checking and debugging your wiring' sidebar_label: 'Checking and Debugging' sidebar_position: 3 description: 'Wiring is lazy, so a mis-wired context still compiles. Catch the mistake where you made it with check_components!, and read the error with cargo cgp check.' diff --git a/docusaurus.config.ts b/docusaurus.config.ts index 632f14db..6b2e1afb 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -5,7 +5,7 @@ import type * as Preset from '@docusaurus/preset-classic'; // This runs in Node.js - Don't use client-side code here (browser APIs, JSX...) const config: Config = { - title: 'Context-Generic Programming', + title: 'CGP — Context-Generic Programming', tagline: 'A language extension for Rust, with pluggable trait implementations at compile-time', favicon: 'img/favicon.png', diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 36e0245c..1dd2a102 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -1,7 +1,7 @@ import type {ReactNode} from 'react'; import clsx from 'clsx'; import Link from '@docusaurus/Link'; -import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; +import Head from '@docusaurus/Head'; import useBaseUrl from '@docusaurus/useBaseUrl'; import Layout from '@theme/Layout'; import HomepageFeatures from '@site/src/components/HomepageFeatures'; @@ -171,11 +171,24 @@ function CallToActionSection() { } export default function Home(): ReactNode { - const {siteConfig} = useDocusaurusContext(); return ( + description="A language extension for Rust, with pluggable trait implementations at compile-time. Give one interface several implementations and choose per application."> + {/* + The front page names the project first, which Docusaurus's own title formatter cannot do: + passing `title` to Layout renders `{title} | {siteTitle}`, so the project name could only ever + come last. Setting the tag here replaces that entirely, and og:title is set with it so a + shared link carries the same words. + */} + + + Context-Generic Programming (CGP) - Pluggable trait implementations for Rust + + +
From 4a41c184c3fc6c89a94198cf2b08048a4c2894b4 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 21 Sep 2026 04:43:19 +0000 Subject: [PATCH 090/516] Say to check the build's exit status rather than its output A failed build leaves the previous run's build/ directory in place, so inspecting the generated files after a failure reports the old site and reads as success. Name the likeliest cause while recording it, since an unescaped apostrophe inside a single-quoted front-matter string is the one that has actually happened, and give the invocation for an environment where yarn is not on the path. Co-Authored-By: Claude Opus 5 --- AGENTS.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index da96c72d..b5459ad8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,9 +108,14 @@ decision recorded in the [new-website post](https://contextgeneric.dev/blog/new- no React beyond the landing page, so that effort goes into Markdown rather than theming. An agent adding site machinery is working against a stated policy and should raise it rather than assume it. -Run `yarn start` for a live-reloading dev server and `yarn build` to produce the static output. -Deployment runs from the GitHub Actions workflows in `.github/`, publishing to GitHub Pages under the -domain fixed by `static/CNAME`. +Run `yarn start` for a live-reloading dev server and `yarn build` to produce the static output. Where +`yarn` is not on the path, `node_modules/.bin/docusaurus start` and `node_modules/.bin/docusaurus build` +are the same commands. **Check the build's exit status rather than its output.** A failed build leaves +the previous run's `build/` directory in place, so inspecting the generated files after a failure +reports the old site and reads as success. The likeliest cause is a YAML error in front matter — an +unescaped apostrophe inside a single-quoted `title` or `description` is the one that has actually +happened, and it is escaped by doubling it. Deployment runs from the GitHub Actions workflows in +`.github/`, publishing to GitHub Pages under the domain fixed by `static/CNAME`. Three configuration details matter when editing. `onBrokenLinks` is set to `throw`, so a dangling internal link fails the build — a change that renames or moves a page must fix every reference to it in From ce5987c8a8072a59bad82f965d2befe9e201c6e6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Wed, 23 Sep 2026 07:09:58 +0000 Subject: [PATCH 091/516] Revise the reflection, row-polymorphism, proposals, and type-class comparisons Rewrite the four remaining comparison pages in the plain, point-first style of the other revised pages, with the settled descriptor and the ordinary-traits frame in each opening. Soften claims the sources do not support, qualify the #[cgp_fn] exception to structural safety, correct the shared-context ownership limit, and rename the mirror modules' headings to match. Co-Authored-By: Claude Opus 5.5 --- docs/comparisons/reflection.md | 379 ++++++++++-------- docs/comparisons/row-polymorphism.md | 298 +++++++------- docs/comparisons/rust-language-proposals.md | 334 +++++++-------- docs/comparisons/type-classes.md | 292 +++++++------- example-code/tests/comparisons/reflection.rs | 2 +- .../comparisons/rust_language_proposals.rs | 2 +- .../tests/comparisons/type_classes.rs | 4 +- 7 files changed, 695 insertions(+), 616 deletions(-) diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index 4fd26d2a..0ac84d9d 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -6,21 +6,21 @@ description: "CGP's type-level shapes read against Bevy's runtime reflection, Zi # Reflection and compile-time introspection -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who thinks in -`TypeInfo`, `@typeInfo`, or `TypeId::field`: Bevy's runtime reflection, Zig's `comptime`, Go or -Java reflection, or Rust's own compile-time reflection effort. CGP reaches the same payoff as -compile-time reflection, one generic routine that works over any type's fields, but takes the -structure not as data a routine inspects but as *types* the trait system resolves against. The page -covers the spectrum from runtime to compile-time reflection, where CGP sits on it, what the type-level -encoding buys and costs, and what to expect that differs. +CGP lets one generic routine work over any type's fields, as compile-time reflection does, but it +represents a type's structure as types rather than as data a routine inspects. It is a language +extension for Rust, with pluggable trait implementations at compile-time, implemented as a library +on stable Rust whose consumer traits are ordinary Rust traits; the [Introduction](/docs/) covers the +basics. For readers familiar with Bevy's `TypeInfo`, Zig's `@typeInfo`, Go or Java reflection, or +Rust's `TypeId::field` work, this page places CGP among runtime and compile-time reflection systems, +compares a field writer in each style, and states what the type-level encoding gains and costs. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. On this page the context is an application type that wires how each field type is written, -and the reflected struct is a value the context operates on. +A **context** is the type a CGP method runs on, supplying its data through fields and its +implementations through wiring. On this page the context is an application type that chooses how +each field type is written, and the struct being reflected over is a value passed to it. + +The reflection vocabulary maps onto CGP by role: | In a reflection system | In CGP | | --- | --- | @@ -33,37 +33,43 @@ and the reflected struct is a value the context operates on. ## The idea, briefly -Reflection lets one piece of code work over the *shape* of a type it was not written for. Serializers, -DI containers, ORMs, editors, and debuggers all need to walk an arbitrary type's fields by name and -type, and reflection supplies that by making a type's structure available as something the program can -read. Systems span a spectrum. At the runtime end a type carries metadata the program inspects while it -runs (Java, Go, C#, Python, Bevy). In the middle a derive generates a static descriptor that runtime -code walks (Rust's facet). At the compile-time end the compiler evaluates the introspection and emits -only the specialized result (Zig's `comptime`, D, C++26's static reflection -([P2996](https://isocpp.org/files/papers/P2996R13.html)), and Rust's nightly effort). CGP sits just -past the compile-time end, where the structure is not even a compile-time *value* but a *type*. +Reflection lets code work over the shape of a type it was not written for. Serializers, DI +containers, ORMs, editors, and debuggers all walk an arbitrary type's fields by name and type, and +reflection makes that structure available for the program to read. Systems differ in when the +structure is read: + +- **At runtime:** A type carries metadata that the program inspects while it runs, as in Java, Go, + C#, Python, and Bevy. +- **Through a generated descriptor:** A derive generates a static descriptor that runtime code + walks, as in Rust's facet crate. +- **At compile time:** The compiler evaluates the introspection and emits only the specialized + result, as in Zig's `comptime`, D, C++26's static reflection + ([P2996](https://isocpp.org/files/papers/P2996R13.html)), and Rust's nightly work. + +CGP belongs with the compile-time systems, with one difference: the structure is a type rather than +a compile-time value. ### Runtime reflection: Bevy -`bevy_reflect` is the prominent Rust runtime-reflection system. A type opts in with -`#[derive(Reflect)]`, after which a value can be handled as a `Box`, accessed by string -field name through the `Struct` trait, and downcast back to its concrete type at runtime -([`bevy_reflect` documentation](https://docs.rs/bevy_reflect/latest/bevy_reflect/)). Behind the -dynamic access is `TypeInfo`, a description of a type's shape available without an instance, and a -runtime `TypeRegistry` that maps types to their `TypeInfo` and to associated behavior, so Bevy can -serialize an arbitrary registered component into a scene or drive an editor over types it was never -specialized for ([`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html)). -Every reflective access goes through dynamic dispatch, a downcast, or a registry lookup, and a -mismatch surfaces at run time as a `None` or a panic. +`bevy_reflect` is a widely used runtime-reflection system in Rust. A type opts in with +`#[derive(Reflect)]`. A value can then be handled as a `Box`, accessed by string field +name through the `Struct` trait, and downcast to its concrete type at runtime +([`bevy_reflect` documentation](https://docs.rs/bevy_reflect/latest/bevy_reflect/)). `TypeInfo` +describes a type's shape without an instance, and a runtime `TypeRegistry` maps types to their +`TypeInfo` and to associated behavior. With these, Bevy can serialize any registered component into +a scene or drive an editor over types it was not specialized for +([`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html)). Every +reflective access goes through dynamic dispatch, a downcast, or a registry lookup, so a mismatch +surfaces at runtime as a `None` or a panic. ### Compile-time metaprogramming: Zig's `comptime` -Zig's `comptime` is the reference design for compile-time reflection. Types are ordinary compile-time -values, `@typeInfo(T)` decomposes a type into a `std.builtin.Type` describing its shape, `inline for` -unrolls a loop over a compile-time collection, and `@field` accesses a field by a compile-time-known -name ([Zig language reference](https://ziglang.org/documentation/master/#typeInfo)). Since Zig 0.14 -the type tags are lowercase, so a struct is matched as `.@"struct"`. This writes any struct as a -JSON-like object and compiles with Zig 0.16: +Zig's `comptime` is the usual reference design for compile-time reflection. Types are ordinary +compile-time values: `@typeInfo(T)` decomposes a type into a `std.builtin.Type` describing its +shape, `inline for` unrolls a loop over a compile-time collection, and `@field` accesses a field by a +name known at compile time ([Zig language reference](https://ziglang.org/documentation/master/#typeInfo)). +From Zig 0.14 the type tags are lowercase, so a struct is matched as `.@"struct"`. This function +writes any struct as a JSON-like object and compiles with Zig 0.16: ```zig const std = @import("std"); @@ -78,23 +84,26 @@ fn jsonStringify(value: anytype, writer: anytype) !void { } ``` -Because `inline for` unrolls at compile time and `@field` resolves statically, it compiles to the -code a hand-written serializer would. `@Type` runs the introspection in reverse and constructs a type -from a `std.builtin.Type` value, which CGP cannot do. The defining trade of `comptime` is that it is -zero-cost but checked late: a `comptime` routine is fully type-checked only when applied to a concrete -type, so an error surfaces at the use site, per instantiation, as with C++ templates. +The loop unrolls at compile time and `@field` resolves statically, so the function compiles to the +code a hand-written serializer would contain. `@Type` runs the introspection in reverse: it +constructs a type from a `std.builtin.Type` value, which CGP cannot do. + +`comptime` costs nothing at runtime, but its checks happen late. A `comptime` routine is fully +type-checked only when it is applied to a concrete type, so an error surfaces at the use site, once +per instantiation, as with C++ templates. ### Compile-time reflection comes to Rust -Rust filled the absence of reflection with derive macros that generate specialized code per type. The -[facet](https://fasterthanli.me/articles/introducing-facet-reflection-for-rust) crate objects to the -cost: serde's derives monomorphize the serializer anew for every type, so facet's derive generates -*data* instead, a `const SHAPE` descriptor that shared runtime reflection code walks once. +Rust programs have used derive macros that generate specialized code per type in place of +reflection. The [facet](https://fasterthanli.me/articles/introducing-facet-reflection-for-rust) +crate responds to the cost of that approach. serde's derives monomorphize the serializer anew for +every type, so facet's derive generates *data* instead: a `const SHAPE` descriptor that shared +runtime reflection code walks. -The nightly compiler effort is the more consequential development, and it is unstable and will -change. Under `#![feature(type_info)]`, `TypeId::of::()` gains query methods that reach a type's -variants and fields by source order, each `FieldId` answering `name()`, `type_id()`, and `offset()`. -The source's own doc tests read: +The nightly compiler work goes further, and it is unstable and subject to change. Under +`#![feature(type_info)]`, `TypeId::of::()` gains query methods that reach a type's variants and +fields in source order. Each `FieldId` answers `name()`, `type_id()`, and `offset()`. The source's +own doc tests read: ```rust #![feature(type_info)] @@ -107,30 +116,32 @@ assert_eq!(const { TypeId::of::().field(0, 0).name() }, "x"); assert_eq!(const { TypeId::of::().field(0, 0).type_id() }, TypeId::of::()); ``` -The single most important design decision is that this reflection is callable *only at compile time*: -every query carries a `#[rustc_comptime]` marker, because supporting runtime calls would require "some -global table somewhere that maps all `TypeId`s to their repr" +These queries can be called only at compile time, and that restriction shapes the whole design. +Each query carries a `#[rustc_comptime]` marker, because supporting runtime calls would require +"some global table somewhere that maps all `TypeId`s to their repr" ([Rust project goal, *Reflection and comptime*](https://rust-lang.github.io/rust-project-goals/2026/reflection-and-comptime.html)). -The goal names Zig as the model and declines full `comptime` for now, estimating the architectural -change at more than five years away. The [tracking issue](https://github.com/rust-lang/rust/issues/146922) -lists every stabilization step as open, and the plan runs from 2026 to 2028, with the ambition that -crates like Bevy will work with arbitrary types instead of requiring a derive. Everything in this -subsection was read from the compiler source and tracking issues on the day of writing; check them -before relying on a detail. +The goal names Zig as its model but does not pursue full `comptime` for now, estimating that +architectural change as more than five years away. The +[tracking issue](https://github.com/rust-lang/rust/issues/146922) lists every stabilization step as +open. The plan runs from 2026 to 2028, with the aim that crates such as Bevy can work with arbitrary +types instead of requiring a derive. The details in this subsection come from the compiler source and +the tracking issue as they stood when this page was written, so check them before relying on one. ## How CGP expresses it -CGP reaches compile-time reflection's payoff by a different route. It encodes a type's structure as -types and processes them with trait resolution, so the type system does the "reflection" rather than a -routine inspecting a descriptor. The worked example below is a self-contained field writer modeled on -[`cgp-serde`](https://github.com/contextgeneric/cgp-serde)'s `SerializeFields` provider, which does the -same over serde's `Serializer`. Its context is an **[environmental context](/docs/reference/glossary#environmental-context)**: the `App` that wires how -each field type is written stands for an application, and the written `Value` is a parameter. +CGP encodes a type's structure as types and processes it with trait resolution. The trait system +therefore does the work that a reflection routine does when it inspects a descriptor. The example +below is a self-contained field writer modeled on +[`cgp-serde`](https://github.com/contextgeneric/cgp-serde)'s `SerializeFields` provider, which does +the same over serde's `Serializer`. Its context is an +[environmental context](/docs/reference/glossary#environmental-context): `App` stands for an +application and chooses how each field type is written. The written `Value` is a type parameter, so +the component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component). ### A type's shape becomes a type, not a descriptor -`#[derive(HasFields)]` lifts a struct's structure into the type system as a type-level list, CGP's form -of the `TypeInfo`, `Shape`, and `FieldId` descriptors the reflection systems build: +`#[derive(HasFields)]` represents a struct's structure as a type-level list. The list plays the role +of the `TypeInfo`, `Shape`, and `FieldId` descriptors above: ```rust #[derive(HasFields)] @@ -148,15 +159,15 @@ pub struct Config { // } ``` -This is the same information a descriptor carries, each field's name and type, but it is a *type*. -The Rust MVP's `FieldId` answers `type_id()` with an opaque `TypeId` value. CGP's `Field` -carries the field's actual type as a type parameter, and that difference lets CGP dispatch on -it. The [Extensible records](/docs/concepts/extensible-records) page develops the derive. +The list carries the same information as a descriptor, each field's name and type, but it is a +*type*. The Rust MVP's `FieldId` answers `type_id()` with an opaque `TypeId` value. CGP's +`Field` carries the field's actual type as a type parameter, so CGP can dispatch on it. +The [Extensible records](/docs/concepts/extensible-records) page develops the derive. -### Reflection-driven serialization in the trait system +### Serializing through the trait system -One generic writer works over any `HasFields` type, the counterpart of the Zig `jsonStringify` -above. It delegates to a trait that recurses over the field list: +One generic writer works over any `HasFields` type, as the Zig `jsonStringify` above works over any +struct. It delegates to a trait that recurses over the field list: ```rust #[cgp_component(ValueWriter)] @@ -176,9 +187,9 @@ where } ``` -The `FieldsWriter` trait is the `inline for` of CGP: a recursion over the -[`Cons`/`Nil`](/docs/reference/types/cons) list, with a step for a non-empty list and a base case for -the empty one: +The `FieldsWriter` trait takes the place of `inline for`. It recurses over the +[`Cons`/`Nil`](/docs/reference/types/cons) list, with one impl for a non-empty list and a base case +for the empty one: ```rust pub trait FieldsWriter { @@ -208,13 +219,17 @@ impl FieldsWriter for Nil { } ``` -Every reflection concept has a counterpart here. The recursion over `Cons`/`Nil` is the loop over the -field list. `Tag::VALUE`, recovered through the -[`StaticString`](/docs/reference/traits/formatting/static_string) trait, is the `field.name` a -reflection system reads, produced with no runtime metadata. `value.get_field(PhantomData)` is the -by-name access, resolved statically through [`HasField`](/docs/reference/traits/field-access/has_field). -And `Context: CanWriteValue` is the recursive step: writing each field's value by -dispatching on the field's type, through the context's wiring: +Each step of a reflective serializer has a counterpart in this code: + +- **The loop over fields:** The recursion over `Cons` and `Nil`. +- **The field name:** `Tag::VALUE`, recovered through the + [`StaticString`](/docs/reference/traits/formatting/static_string) trait without runtime metadata. +- **Access by name:** `value.get_field(PhantomData)`, resolved statically through + [`HasField`](/docs/reference/traits/field-access/has_field). +- **Writing each field's value:** The `Context: CanWriteValue` bound, which dispatches + on the field's type through the context's wiring. + +The context's wiring then chooses a writer for each type: ```rust delegate_components! { @@ -229,122 +244,136 @@ delegate_components! { App.write_value(&config); // {"host": "localhost", "port": 8080} ``` -The struct also derives `HasField` so the recursion can read each field; `WriteWithDebug` formats a -value with `Debug`. `cgp-serde`'s [`SerializeFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs) -is this same recursion over a `serde::Serializer`, and its deserialization dual reads a field name as -a runtime string and compares it against each field's compile-time `Tag::VALUE`. +The struct also derives `HasField` so the recursion can read each field, and `WriteWithDebug` +formats a value with `Debug`. `cgp-serde`'s +[`SerializeFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs) +performs the same recursion over a `serde::Serializer`. Its deserialization counterpart reads a +field name as a runtime string and compares it with each field's compile-time `Tag::VALUE`. ### Against facet and the reflection MVP -Four approaches solve the same problem, writing serialization once rather than per type, and comparing -what each turns a type's shape into shows where CGP sits. serde's derive generates *code*, a bespoke -impl per struct. facet generates *data*, a `const SHAPE` walked by a shared runtime routine, which -avoids re-monomorphizing per type at the cost of runtime reflection work. The Rust MVP has the -compiler provide the data, consumed by `const`-evaluated code with no derive. CGP generates -*type-level data*, walked by a shared compile-time routine that monomorphizes to direct code. - -Two differences make CGP's position distinct. First, the field's type is preserved as a type. Facet's -`Shape` and the MVP's `FieldId::type_id()` carry it as an opaque descriptor from which a generic -function cannot be instantiated directly, so recursion into a field's own type is mediated by stored -function pointers or is not yet expressible. CGP's `Field` carries `FieldValue` as a -real type parameter, so `WriteFields` can require `Context: CanWriteValue` and recurse -into a fully typed, statically checked writer for the field's type. Second, CGP dispatches each field -through the *context's* wiring, so the same type is written differently under different application -contexts, the [per-context choice](/docs/concepts/coherence) that facet, serde, and the MVP do not -have. - -The costs are equally clear. Unlike facet, CGP does not solve the [monomorphization](/docs/reference/glossary#monomorphization) problem: the -recursion instantiates per field list, so it produces specialized code per type as serde's output -does. What it saves is the authoring duplication, and what it gains is configurability, not binary -size. And unlike the Rust MVP, CGP requires the `#[derive(HasFields)]` opt-in and cannot see a foreign -type that did not derive it. - -### Checked when the code is written, not when it is instantiated +serde, facet, the Rust MVP, and CGP all let serialization be written once rather than per type. +They differ in what they turn a type's shape into and in what walks the result: + +| Approach | What the type's shape becomes | What processes it | +| --- | --- | --- | +| serde | Code: a separate generated impl per struct | Nothing; the generated impl is the serializer | +| facet | Data: a `const SHAPE` generated by a derive | A shared routine, at runtime | +| Rust MVP | Data provided by the compiler, without a derive | `const`-evaluated code, at compile time | +| CGP | Type-level data generated by a derive | A shared trait recursion, monomorphized to direct code | + +CGP's position differs from facet's and the MVP's in two ways. The field's type stays a type. +facet's `Shape` and the MVP's `FieldId::type_id()` carry it as an opaque descriptor, and a generic +function cannot be instantiated directly from a descriptor, so recursing into a field's own type +needs stored function pointers or is not yet expressible. CGP's `Field` carries +`FieldValue` as a real type parameter. `WriteFields` can therefore require +`Context: CanWriteValue` and recurse into a typed, statically checked writer for the +field's type. CGP also dispatches each field through the *context's* wiring, so the same type can be +written differently under different application contexts. facet, serde, and the MVP do not provide +this [per-context choice](/docs/concepts/coherence). + +The encoding also has costs. Unlike facet, CGP does not reduce +[monomorphization](/docs/reference/glossary#monomorphization): the recursion is instantiated per +field list, so it produces specialized code per type, as serde's output does. CGP removes the +duplicated authoring and adds configurability, but it does not reduce binary size. Unlike the Rust +MVP, CGP requires the `#[derive(HasFields)]` opt-in and cannot see a foreign type that does not +derive it. + +### Checked where the code is written, not where it is instantiated Zig's `comptime` and the MVP's `const fn` reflection are checked at instantiation: a routine is fully -checked only when applied to a concrete type, so an error surfaces at the use site. CGP's generic code -is checked at its definition. The `where` clause on the `FieldsWriter` impl is verified once against -the bounds, and [`check_components!`](/docs/reference/macros/check_components) verifies that a context -supplies everything its wiring transitively needs. This is the modular checking traits give and -templates do not, and the [type classes](./type-classes.md) page draws it out against Haskell's -neighbours. - -### Reflection that also selects behavior and configures types - -CGP applies the same type-level idea to two things a structural reflection facility does not directly -address. Frameworks do select behavior by reflection, Spring by annotations and Bevy through -`TypeData` in its registry, but as a runtime, registry-mediated act layered on the introspection. CGP -folds behavior selection into the same compile-time table that carries its structural information, and -the [`#[cgp_type]`](/docs/reference/macros/cgp_type) machinery lets a context fix an abstract *type* -through that table too. The `Context: CanWriteValue` bound above shows it: the reflection -that walks the shape and the wiring that interprets each field are one mechanism. +checked only when it is applied to a concrete type, so an error surfaces at the use site. CGP's +generic code is checked where it is defined. The compiler checks the `FieldsWriter` impl once against +the bounds in its `where` clause, as it checks any generic Rust impl. Wiring is +[lazy](/docs/concepts/check-traits), so [`check_components!`](/docs/reference/macros/check_components) +verifies that a context supplies everything its wiring transitively needs and reports a missing +dependency at the wiring site. Trait bounds give this modular checking, and templates do not. The +[type classes](./type-classes.md) page compares CGP with the type-class systems that Rust's traits +come from. + +### Selecting behavior and types through the same wiring + +CGP uses the same type-level mechanism for two jobs that a structural reflection facility does not +handle directly. Frameworks do select behavior through reflection, Spring through annotations and +Bevy through `TypeData` in its registry, but they do so at runtime, through a registry built on top +of the introspection. CGP selects behavior at compile time through the context's wiring, which trait +resolution processes together with the structure. The [`#[cgp_type]`](/docs/reference/macros/cgp_type) +machinery also lets a context fix an abstract *type* through the same wiring. The +`Context: CanWriteValue` bound above shows the combination: one mechanism walks the shape +and chooses how each field is written. ## What each approach costs -Reflection is relied upon because a framework written once works over every user type, and runtime -reflection additionally works on types the framework author never saw. Compile-time reflection is -valued for "the expressiveness of runtime reflection with the performance of hand-written code" -([*Compile-Time Reflection with @typeInfo*](https://hive.blog/hive-196387/@scipio/learn-zig-series-32-compile-time-reflection-with-typeinfo)), -and facet and the Rust effort are motivated by cutting derive codegen's compile-time and binary cost. -The costs, as their users state them, split by when the reflection runs. Runtime reflection pays in -performance, since Go's `encoding/json` re-inspects types on every call -([*The Hidden Cost of Reflection in Go*](https://dev.to/devflex-pro/the-hidden-cost-of-reflection-in-go-why-your-code-is-slower-than-you-think-41ee)), -in type safety, since a field named by a string tag fails at runtime -([Go reflection guide](https://medium.com/@mojimich2015/golang-reflection-the-guide-to-runtime-type-inspection-manipulation-and-best-practices-303087684576)), -and in tooling, since renaming a field silently breaks reflective access. Compile-time reflection -answers those and trades them for instantiation-time error messages, added compile-time work, and, as -the Rust tracking issue itself asks, the risk of "monomorphization-time errors" deep inside -instantiation. - -CGP's costs are the ordinary ones plus two specific to this page. It introspects only types that opted -in by deriving its machinery, and only at compile time. It does not reduce the specialized code per -type the way facet does. Its wiring is code somebody writes. And its raw diagnostics are trait-solver -output over generated types, which for a deep field recursion can be long: -[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The +Reflection is widely used because a framework written once works over every user type, and runtime +reflection also works on types the framework author never saw. Compile-time reflection is valued for +"the expressiveness of runtime reflection with the performance of hand-written code" +([*Compile-Time Reflection with @typeInfo*](https://hive.blog/hive-196387/@scipio/learn-zig-series-32-compile-time-reflection-with-typeinfo)). +facet and the Rust effort aim to reduce the compile-time and binary-size cost of derive-generated +code. + +The costs users describe depend on when the reflection runs. Runtime reflection costs performance, +because Go's `encoding/json` re-inspects types on every call +([*The Hidden Cost of Reflection in Go*](https://dev.to/devflex-pro/the-hidden-cost-of-reflection-in-go-why-your-code-is-slower-than-you-think-41ee)). +It weakens type safety, because a field named by a string tag fails at runtime +([Go reflection guide](https://medium.com/@mojimich2015/golang-reflection-the-guide-to-runtime-type-inspection-manipulation-and-best-practices-303087684576)). +It also affects tooling, because renaming a field can silently break reflective access. Compile-time +reflection addresses these costs but has its own: errors appear at instantiation, compilation does +more work, and, as the Rust tracking issue itself asks, "monomorphization-time errors" can arise deep +inside an instantiation. + +Two of CGP's costs are specific to this comparison. CGP introspects only types that derive its +machinery, and only at compile time. It also does not reduce the specialized code per type, as facet +does. Its other costs are the ordinary ones: the wiring is code someone writes and maintains, and the +raw diagnostics are trait-solver output over generated types, which can be long for a deep field +recursion. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it +recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the alternatives. ## Where reflection is the better choice -When a program must inspect types at runtime, to deserialize into a type chosen from a config file, -serialize a heterogeneous registry of components, build an editor or a debugger over live values, or -reflect over a foreign type that cannot be made to derive anything, runtime reflection is the right -and only tool of the two, and `bevy_reflect` or facet is the tool to reach for. When a program needs to -construct a new nominal type from computed structure, Zig's `@Type` and C++26's splicers do what CGP's -type-level lists cannot. CGP is the better tool when a program wants generic-over-structure code that -costs nothing at runtime, is checked when written, recurses into field types with full type -information, and drives behavior and type selection as well as data walking. - -CGP and Rust's emerging compile-time reflection are more complementary than competing. The MVP -produces reflection as *const values*, which value-reflection libraries consume natively. CGP consumes -reflection as *types*, a different projection the MVP does not supply, so for CGP to shed its derive -the compiler would need to expose a type's shape as types. Until then CGP's derive stands in for the -compiler-provided reflection Rust is still building. +Runtime reflection is the right tool when a program must inspect types at runtime, which CGP cannot +do. Examples include deserializing into a type chosen from a configuration file, serializing a +heterogeneous registry of components, building an editor or debugger over live values, and +reflecting over a foreign type that cannot be made to derive anything. `bevy_reflect` and facet serve +these cases. A program that must construct a new nominal type from computed structure needs Zig's +`@Type` or C++26's splicers, since CGP's type-level lists cannot do it. CGP fits generic code over a +type's structure that costs nothing at runtime, is checked where it is written, recurses into field +types with full type information, and selects behavior and types as well as walking data. + +CGP and Rust's emerging compile-time reflection complement each other more than they compete. The +MVP produces reflection as *const values*, which libraries that reflect over values can consume +directly. CGP consumes reflection as *types*, which the MVP does not supply. For CGP to drop its +derive, the compiler would need to expose a type's shape as types. Until then, CGP's derive stands in +for that compiler-provided view. ## What to expect that differs -**There is no reflection API.** No `TypeInfo` to hold, no field list to iterate imperatively, no -`TypeId::of::()` to call. The structure is a type that trait impls dispatch on, so reflecting over -it means writing a recursive impl. +**CGP has no reflection API.** It has no `TypeInfo` value to hold, no field list to iterate +imperatively, and no `TypeId::of::()` to call. The structure is a type that trait impls dispatch +on, so reflecting over it means writing a recursive impl. -**A field's type is a type, not a `TypeId`.** This is why CGP can recurse into a typed, checked -writer for each field and the raw MVP cannot yet. +**A field's type is a type, not a `TypeId`.** This lets CGP recurse into a typed, checked writer for +each field, which the MVP's `TypeId`-based API cannot yet do. -**Shapes are opt-in.** A type exposes its structure only by deriving `HasFields` or `CgpData`. A -foreign type without the derive is invisible. +**Shapes are opt-in.** A type exposes its structure only by deriving `HasFields` or `CgpData`, so CGP +cannot see the fields of a foreign type without the derive. -**No type synthesis.** CGP's `Product!` and `Sum!` are the `@typeInfo` result reified as types, and -its trait recursion is the `inline for`, but CGP cannot `@Type`-construct a new nominal type. +**CGP cannot synthesize types.** `Product!` and `Sum!` correspond to the result of `@typeInfo`, and +trait recursion corresponds to `inline for`, but CGP has no counterpart to `@Type` for constructing a +new nominal type. -**CGP is not a reflection system.** It is compile-time structural reflection encoded as types, -resolved by the trait system, checked at the definition site, and erased before runtime. +**CGP is not a reflection system.** It encodes a type's structure as types, resolves operations +over it with the trait system, checks generic code where it is defined, and leaves no reflection +metadata in the compiled program. ## Where to go next +These pages develop the constructs and the neighbouring comparisons: + - [Extensible records](/docs/concepts/extensible-records) and [Extensible variants](/docs/concepts/extensible-variants): the derives and what they enable. -- [Row polymorphism](./row-polymorphism.md): the structural-typing theory beneath the type-level +- [Row polymorphism](./row-polymorphism.md): the structural-typing theory behind the type-level shapes. - [Dynamic dispatch](./dynamic-dispatch.md): the runtime-mechanism counterpart to this page. - [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields), diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index 11a72be3..6084edbd 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -6,21 +6,23 @@ description: "CGP's extensible records and variants read against PureScript rows # Row polymorphism, structural typing, and extensible data types -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows -row polymorphism, structural typing, or extensible data types: PureScript's rows, OCaml's polymorphic -variants, TypeScript's structural checking, or the row-theory literature. CGP brings field-and-variant -driven extensibility to Rust's nominal structs and enums, not through a built-in row kind but by -deriving a type-level view of a type's shape and matching names through the trait system. The page -covers the correspondence, the one place the analogy breaks, where a real row system is the better -tool, and what to expect that differs. +CGP lets code work over the fields and variants of Rust's nominal structs and enums, much as row +polymorphism lets code work over any record with the right fields. It does not add a row kind: +it derives a type-level view of each type's shape and matches names through the trait system. It is +a language extension for Rust, with pluggable trait implementations at compile-time, implemented as +a library on stable Rust whose consumer traits are ordinary Rust traits; the [Introduction](/docs/) +covers the basics. For readers familiar with PureScript's rows, OCaml's polymorphic variants, +TypeScript's structural checking, or the row-theory literature, this page maps row operations onto +CGP, shows where the analogy stops, and states where a row system is the better tool. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. On this page every context is a **[value context](/docs/reference/glossary#value-context)**: the record being built or the enum being -cast is the type that carries the shape and the wiring, and each component targets `Self`. +A **context** is the type a CGP method runs on, supplying its data through fields and its +implementations through wiring. Every context on this page is a +**[value context](/docs/reference/glossary#value-context)**: the record being built or the enum +being cast carries both the shape and the wiring, and each component targets `Self`. + +The row operations map onto CGP constructs as follows: | In a row system | In CGP | | --- | --- | @@ -34,31 +36,31 @@ cast is the type that carries the shape and the wiring, and each component targe ## The idea, briefly -Nominal type systems, Rust's included, force code to name the concrete type it works on. A function -that reads a `name` field must take a specific struct, and two structs with identical fields but -different names are incompatible. The features on this page let a type's structure, not its name, -decide what operations apply. +Nominal type systems, including Rust's, require code to name the concrete type it works on. A +function that reads a `name` field must take a specific struct, and two structs with identical fields +but different names are incompatible. The features on this page let a type's structure, rather than +its name, decide which operations apply. ### Structural versus nominal typing A structural type system decides compatibility by a type's members rather than its name ([Wikipedia, *Structural type system*](https://en.wikipedia.org/wiki/Structural_type_system)). -TypeScript is the mainstream face of it: an object satisfies an interface by having the required +TypeScript is the most widely used example: an object satisfies an interface by having the required members ([TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-oop.html)), -though TypeScript approximates rather than has row polymorphism +though TypeScript only approximates row polymorphism ([Bornea](https://medium.com/@gabriel-bornea/approximating-row-type-polymorphism-in-typescript-495ebd5a623d)). -Rust sits at the nominal end: its structs and enums are nominal, and row polymorphism "is notably -absent from Rust's struct system" -([Andreas, *Structural vs Nominal Typing in Rust*](https://felixandreas.me/blog/nominal-vs-structural-types/)). -That absence is the ground CGP works on. - -### Row polymorphism proper, in PureScript - -Row polymorphism is structural flexibility delivered by a *row variable* rather than a subtype -relation: a function accepts any record that has at least the fields it names, and a type variable -carries the others through unchanged ([Wikipedia, *Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism)). -In PureScript a *row* is "an unordered collection of named types", of kind `Row k`, and a record is a -row wrapped by `Record` ([PureScript language reference](https://github.com/purescript/documentation/blob/master/language/Types.md)). +Rust's structs and enums are nominal, and row polymorphism "is notably absent from Rust's struct +system" ([Andreas, *Structural vs Nominal Typing in Rust*](https://felixandreas.me/blog/nominal-vs-structural-types/)). +CGP works within that nominal system rather than replacing it. + +### Row polymorphism in PureScript + +Row polymorphism provides structural flexibility through a *row variable* rather than a subtype +relation. A function accepts any record that has at least the fields it names, and a type variable +carries the other fields through unchanged +([Wikipedia, *Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism)). In PureScript a +*row* is "an unordered collection of named types", of kind `Row k`, and a record is a row wrapped by +`Record` ([PureScript language reference](https://github.com/purescript/documentation/blob/master/language/Types.md)). An open row adds a tail variable after a pipe: ```purescript @@ -71,29 +73,32 @@ fullName { firstName: "Ada", lastName: "Lovelace" } -- ok fullName { firstName: "Ada", lastName: "Lovelace", age: 36 } -- also ok; age flows through `r` ``` -The `Prim.Row` type classes `Cons`, `Union`, `Nub`, and `Lacks` govern the row operations, resolved -during type checking ([Pursuit, *Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row)). -PureScript's design descends from Wand's row variables (1987), Rémy's principal types for rows -(1989), and Leijen's scoped labels (2005), which PureScript adopts directly +The `Prim.Row` type classes `Cons`, `Union`, `Nub`, and `Lacks` govern the row operations, and the +compiler resolves them during type checking +([Pursuit, *Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row)). PureScript's design +descends from Wand's row variables (1987), Rémy's principal types for rows (1989), and Leijen's +scoped labels (2005), which PureScript adopts directly ([Leijen, *Extensible records with scoped labels*](https://www.microsoft.com/en-us/research/publication/extensible-records-with-scoped-labels/)). -### Rows as a kind versus rows as predicates +### Rows as a kind or as predicates + +Row polymorphism has two main designs. PureScript makes rows a *built-in kind* with its own +unification. Gaster and Jones instead encode rows through *qualified types*: a function is +polymorphic over an ordinary type variable, and the *lacks* and *has* predicates it requires are +discharged by the machinery that resolves type-class instances, without a new kind +([Gaster & Jones](http://web.cecs.pdx.edu/~mpj/pubs/polyrec.html)). -Two designs realize row polymorphism. PureScript makes rows a *built-in kind* with its own -unification. Gaster and Jones instead encode rows through *qualified types*: a function is polymorphic -over an ordinary type variable, and the *lacks* and *has* predicates it must satisfy are discharged by -the same machinery that resolves type-class instances, with no new kind -([Gaster & Jones](http://web.cecs.pdx.edu/~mpj/pubs/polyrec.html)). CGP most closely resembles this -second design. CGP has no row kind and no row variable, but it does have row *predicates*: a -`HasField` bound is a has-predicate over a context's row, resolved -by the trait solver. Rémy's *presence polymorphism* adds a per-label flag recording presence or -absence, which CGP reproduces with the markers shown below. +CGP most closely resembles the second design. It has no row kind and no row variable, but it has +row *predicates*: a `HasField` bound is a has-predicate over a +context's fields, and the trait solver resolves it. Rémy's *presence polymorphism* adds a flag for +each label recording whether it is present, and CGP reproduces this with the markers shown below. -### Extensible variants: the sum-side dual +### Extensible variants -Where a row-polymorphic record function accepts "at least these fields", a row-polymorphic variant -value promises "at most these cases". OCaml's *polymorphic variants* are the industrial home of the -dual, needing no central type declaration; OCaml 5.5 infers the type in the comment: +Variants are the dual of records. A row-polymorphic record function accepts "at least these +fields", while a row-polymorphic variant value promises "at most these cases". OCaml's *polymorphic +variants* provide these variants in a production language, without a central type declaration. +OCaml 5.5 infers the type shown in the comment: ```ocaml (* no type declaration needed; the variant type is inferred and reusable *) @@ -104,34 +109,36 @@ let to_int = function (* inferred: [< `Number of int | `Off | `On ] -> int *) ``` -[Extensible records](/docs/reference/glossary#extensible-record) and variants are the classic answer to Wadler's *expression problem*: adding both -new cases to a datatype and new operations over it "without recompiling existing code, and while -retaining static type safety" ([Wadler, 1998](https://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt)). -Haskell's *Data types à la carte* is the constraint-based route for sums: a coproduct of signature +[Extensible records](/docs/reference/glossary#extensible-record) and variants are a standard answer +to Wadler's *expression problem*: adding both new cases to a datatype and new operations over it +"without recompiling existing code, and while retaining static type safety" +([Wadler, 1998](https://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt)). Haskell's +*Data types à la carte* solves the sum side with constraints. It builds a coproduct of signature functors with a `:<:` constraint whose evidence supplies an injection `inj` and a partial projection `prj` ([Swierstra](https://www.cs.tufts.edu/~nr/cs257/archive/wouter-swierstra/DataTypesALaCarte.pdf)). ### The unifying theory -Morris and McKinna's *rows by any other name* generalizes the designs into *row theories*, "a monoidal -generalization of row types", with two predicates: **combination** `ρ₁ ⊙ ρ₂ ~ ρ₃` and **containment** -`ρ₁ ≲ ρ₂`. Records are built by combination and read by containment; variants are built by -containment and consumed by combination. Its deepest idea for the CGP comparison is that "evidence for -type qualifiers has computational content": the proof that a row contains a label *is* the projection -code ([Morris & McKinna, POPL 2019](https://dl.acm.org/doi/10.1145/3290325)). Koka applies the same +Morris and McKinna's *rows by any other name* generalizes these designs into *row theories*, "a +monoidal generalization of row types", with two predicates: **combination** `ρ₁ ⊙ ρ₂ ~ ρ₃` and +**containment** `ρ₁ ≲ ρ₂`. Records are built by combination and read by containment; variants are +built by containment and consumed by combination. The idea most relevant to CGP is that "evidence +for type qualifiers has computational content": the proof that a row contains a label *is* the +projection code ([Morris & McKinna, POPL 2019](https://dl.acm.org/doi/10.1145/3290325)). Koka applies rows to effects ([Leijen, *Koka*](https://arxiv.org/pdf/1406.2061)), which the [algebraic effects](./algebraic-effects.md) page covers. ## How CGP expresses it -CGP keeps Rust's nominal structs and enums and *derives* a type-level description of a type's shape, -then matches field and variant names through the trait system. The row predicates become trait -constraints the trait solver resolves, in the Gaster and Jones style, carried by Rust's traits. +CGP keeps Rust's nominal structs and enums, derives a type-level description of each type's shape, +and matches field and variant names through the trait system. The row predicates become trait +constraints that the trait solver resolves, as in the Gaster and Jones design. ### A struct is a closed row; `HasField` is row containment -`#[derive(HasFields)]` gives a struct the type-level equivalent of a closed row, one -`Field` entry per field, tagged by a [type-level string](/docs/reference/glossary#type-level-string): +`#[derive(HasFields)]` gives a struct the type-level equivalent of a closed row, with one +`Field` entry per field, each tagged by a +[type-level string](/docs/reference/glossary#type-level-string): ```rust #[derive(HasField, HasFields)] @@ -147,9 +154,9 @@ pub struct Person { // ]; ``` -Where PureScript's `fullName` names its required fields with an open row, a CGP function names them -as [implicit arguments](/docs/concepts/implicit-arguments), and any context whose derived row includes -the fields satisfies it: +PureScript's `fullName` names its required fields with an open row. A CGP function names them as +[implicit arguments](/docs/concepts/implicit-arguments), and any context with those fields satisfies +it: ```rust #[cgp_fn] @@ -168,17 +175,17 @@ person.full_name(); // "Ada Lovelace" employee.full_name(); // "Ada Lovelace"; `badge` plays the part of `r` ``` -The bound each argument desugars to, `HasField`, is the -containment predicate, and the context's other fields play the role of the tail variable. The -difference from PureScript is that the row variable is implicit and never named: CGP does not infer or -carry a residual row, it resolves the containment bound against whatever concrete context is used. +Each implicit argument desugars to a bound such as `HasField`, +which is the containment predicate. The context's other fields play the role of the tail variable. +Unlike PureScript, CGP never names the row variable. It does not infer or carry a residual row; it +resolves each containment bound against the concrete context in use. ### Building a record is row combination -Assembling a struct field by field is CGP's record concatenation. The -[builder family](/docs/reference/traits/builder/has_builder) walks a *partial record* from empty to -complete, and [`CanBuildFrom`](/docs/reference/traits/casting/can_build_from) absorbs the shared -fields of one struct into another's builder in one step, the analogue of PureScript's `Record.union`: +Assembling a struct field by field is CGP's form of record concatenation. The +[builder family](/docs/reference/traits/builder/has_builder) takes a *partial record* from empty to +complete. [`CanBuildFrom`](/docs/reference/traits/casting/can_build_from) adds the shared fields of +one struct to another's builder in one step, much as PureScript's `Record.union` joins two records: ```rust let combined: FooBarBaz = FooBarBaz::builder() @@ -187,27 +194,29 @@ let combined: FooBarBaz = FooBarBaz::builder() .finalize_build(); // exists only when the row is complete ``` -The underlying type-level operations are a row algebra: [`ConcatProduct`](/docs/reference/traits/type-level/concat_product) -splices two products, `AppendProduct` adds one field, and `MapFields` rewrites every entry, all -evaluated during type checking. That `finalize_build` type-checks only when every field is present is -the completeness guarantee a closed row gives, recovered for generic Rust. The -[Extensible records](/docs/concepts/extensible-records) page develops the pattern. +The underlying type-level operations form a row algebra that is evaluated during type checking. +[`ConcatProduct`](/docs/reference/traits/type-level/concat_product) joins two products, +`AppendProduct` adds one field, and `MapFields` rewrites every entry. `finalize_build` type-checks +only when every field is present, which gives generic Rust the completeness guarantee of a closed +row. The [Extensible records](/docs/concepts/extensible-records) page develops the pattern. ### Presence markers are presence polymorphism -CGP tracks field presence with the per-field flags Rémy's presence polymorphism introduced, as +CGP tracks field presence with a flag per field, as Rémy's presence polymorphism does. The flags are [`MapType`](/docs/reference/traits/type-level/map_type) markers on a partial record: `IsPresent` stores the value, `IsNothing` stores nothing, and the -[optional-field extensions](/docs/reference/traits/optional/) add `IsOptional`. A builder starts at -all-`IsNothing`, each step flips one marker, and `FinalizeBuild` exists only at the all-`IsPresent` -configuration. The variant side uses `IsVoid` to mark a case ruled out during extraction. +[optional-field extensions](/docs/reference/traits/optional/) add `IsOptional`. A builder starts with +every field marked `IsNothing`, and each step changes one marker. `FinalizeBuild` is implemented only +when every marker is `IsPresent`. On the variant side, `IsVoid` marks a case that extraction has +ruled out. ### An enum is a row-typed sum; upcast and downcast are injection and branching -The variant side is the exact dual. The derive represents an enum as a `Sum!` of `Field` entries, and -the [structural casts](/docs/reference/traits/casting/can_upcast) implement the row-theory operations -directly. `CanUpcast` lifts a narrow enum into a wider one, which is variant *injection* and always -succeeds. `CanDowncast` narrows the other way, guarded by containment: +The variant side mirrors the record side. The derive represents an enum as a `Sum!` of `Field` +entries, and the [structural casts](/docs/reference/traits/casting/can_upcast) implement the +row-theory operations. `CanUpcast` converts a narrower enum into a wider one. This is variant +*injection*, and it always succeeds. `CanDowncast` converts the other way, and it succeeds only for +variants the target contains: ```rust #[derive(Debug, Eq, PartialEq, CgpData)] @@ -230,92 +239,99 @@ let wide = Reading::Temperature(21).upcast(PhantomData::); ExtendedReading::Flag(true).downcast(PhantomData::).is_err(); // true ``` -Branching, the combination predicate on the sum side, is CGP's +Branching, the sum side's combination predicate, is CGP's [extensible visitor](/docs/concepts/extensible-variants). The `MatchWithValueHandlers` dispatcher -derives one extract-and-handle step per variant from the enum's row and runs them as a pipeline, and -because each failed extraction rules out a variant at the type level, the final match is provably -exhaustive with no wildcard arm. In *Data types à la carte* terms, `CanUpcast` is `inj` and -`CanDowncast` is `prj`, but where à la carte's `prj` returns a `Maybe` with no exhaustiveness check, -CGP's branching consumes the whole sum and proves it covered every case. +derives one extract-and-handle step per variant from the enum's shape and runs the steps as a +pipeline. Each failed extraction rules out a variant at the type level, so the final match is +provably exhaustive without a wildcard arm. In *Data types à la carte* terms, `CanUpcast` is `inj` +and `CanDowncast` is `prj`. À la carte's `prj` returns a `Maybe` without an exhaustiveness check, +while CGP's branching consumes the whole sum and proves that every case was handled. ### Providers are the theory's computational evidence -CGP lines up with the theory on one point more than with any implementing language: Morris and -McKinna's insight that a row predicate's evidence has computational content. In CGP that evidence is -visible. The `HasField` impl a derive generates *is* the projection code, the `CanBuildFrom` recursion -*is* the concatenation code, and a wired provider *is* the witness that a context can perform an -operation. Where a row-typed language elaborates the evidence invisibly, CGP surfaces it as ordinary -traits and impls a programmer can read. +CGP makes visible the evidence that Morris and McKinna describe. In a row-typed language, the +compiler elaborates the evidence for a row predicate internally. In CGP the evidence is ordinary code +that a programmer can read: the `HasField` impl a derive generates *is* the projection code, the +`CanBuildFrom` recursion *is* the concatenation code, and a wired provider *is* the witness that a +context can perform an operation. ## What each approach costs Row polymorphism is valued because one function serves many record shapes, which "can greatly reduce refactoring" ([Fowler, *Row Polymorphism without the Jargon*](https://jadon.io/blog/row-polymorphism/)), -and because rows drive codec-free JSON decoding and type-safe bindings -([Nguyen](https://hgiasac.github.io/posts/2018-11-18-Record-Row-Type-and-Row-Polymorphism.html)). Its -costs, as its users state them, cluster in three places. The loudest is error messages: row -unification produces large diagnostics, and one PureScript thread records outputs of around 152 KB +and because rows support codec-free JSON decoding and type-safe bindings +([Nguyen](https://hgiasac.github.io/posts/2018-11-18-Record-Row-Type-and-Row-Polymorphism.html)). + +Its users report costs in three areas. The first is error messages: row unification can produce +very large diagnostics, and one PureScript thread records outputs of around 152 KB ([PureScript Discourse](https://discourse.purescript.org/t/upcoming-changes-to-error-messages-for-large-records-rows/3696)). -The second is complexity: extensible records are widely seen as a specialist tool, and one user who -modeled a domain with them wished afterwards for separate functions per nominal type +The second is complexity. Extensible records are widely seen as a specialist tool, and one user who +modeled a domain with them later wished for separate functions per nominal type ([PureScript Discourse](https://discourse.purescript.org/t/when-to-use-extensible-types-when-modeling-a-domain/217)). -The third is specific to pure structural typing: a structurally valid call can be semantically wrong, -"like finding the `area` of a `Fish`" ([Fowler](https://jadon.io/blog/row-polymorphism/)), and OCaml's -manual warns that polymorphic variants "result in a weaker type discipline" and recommends core -variants for simple programs ([OCaml manual](https://ocaml.org/manual/5.5/polyvariant.html)). Two -languages retreated from rows for the first reason: PureScript replaced its row-typed effect monad -because "getting the effect rows to line up was sometimes quite tricky" +The third cost is specific to pure structural typing: a structurally valid call can be semantically +wrong, "like finding the `area` of a `Fish`" ([Fowler](https://jadon.io/blog/row-polymorphism/)). +OCaml's manual warns that polymorphic variants "result in a weaker type discipline" and recommends +core variants for simple programs ([OCaml manual](https://ocaml.org/manual/5.5/polyvariant.html)). + +Two languages have moved away from rows. PureScript replaced its row-typed effect monad because +"getting the effect rows to line up was sometimes quite tricky" ([PureScript-Resources](https://purescript-resources.readthedocs.io/en/latest/eff-to-effect.html)), and Gleam removed row-typed records to become "less structural and more nominal in style" ([Gleam v0.4](https://gleam.run/news/gleam-v0.4-released/)). -CGP inherits the first two costs in its own idiom. A mis-wired or incomplete structural operation -surfaces as a long, generated-type trait error, and CGP asks for derives, type-level tags, and wiring -where a row system would infer everything. Its mitigations are -[`check_components!`](/docs/reference/macros/check_components), which names the missing field or -variant at the wiring site, and [`cargo cgp check`](/docs/cargo-cgp/check): `cargo cgp check` leads -with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet -reshape every class. The diagnostics remain heavier than a nominal `match`. The third cost CGP largely avoids: because a -provider still binds to a context it was wired for, structure grants access without erasing identity. -The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the +CGP has the first two costs in its own form. A mis-wired or incomplete structural operation surfaces +as a long trait error over generated types, and CGP asks for derives, type-level tags, and wiring +where a row system infers the shape. [`check_components!`](/docs/reference/macros/check_components) +names the missing field or variant at the wiring site. [`cargo cgp check`](/docs/cargo-cgp/check) +leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not +yet reshape every class. Even so, the diagnostics are heavier than those of a nominal `match`. + +CGP avoids the third cost for components. A provider applies only to a context whose wiring selects +it, so a shape-compatible context does not acquire a component's behavior without being wired for +it. A `#[cgp_fn]` function such as `full_name` is different: its single blanket implementation +applies to any context with the named fields, as a row-polymorphic function does. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the alternatives. ## Where a row system is the better choice -Where a program wants terse anonymous records with full inference, and can pay the error-message cost, -a real row system such as PureScript's is the better tool, and reaching for CGP's machinery to emulate -it would be over-engineering. Where a program is already in nominal Rust and wants structural -field-and-variant access at a few chosen points, a builder assembled from independent parts, a -visitor over an open set of variants, a cast between sibling enums, CGP delivers row polymorphism's -payoff without adopting a new kind system, and pays the complexity only where it is used. +A row system such as PureScript's is the better tool when a program wants concise anonymous records +with full inference and can accept the error-message cost. Emulating that style with CGP's machinery +would add declarations and wiring without a matching benefit. + +CGP fits a program that is already written in nominal Rust and wants structural access to fields and +variants at a few chosen points: a builder assembled from independent parts, a visitor over an open +set of variants, or a cast between related enums. There it provides the main benefit of row +polymorphism without a new kind system, and it adds complexity only where it is used. ## What to expect that differs -**CGP does not infer rows.** A reader expects `{ name :: String | r }` to be inferred and rows to be -unified. CGP has no row variable and no row inference: a provider names its required fields as -bounds, and a context's shape comes from a derive. Because CGP does not unify open rows, it also does -not produce the row-unification messages that drove PureScript off effect rows and Gleam off row-typed -records; its verbose errors have a different shape and a different mitigation. +**CGP does not infer rows.** It has no row variable and no row inference. A provider names its +required fields as bounds, and a context's shape comes from a derive. Because CGP does not unify open +rows, it does not produce row-unification errors either; its long errors come from trait resolution +and have different mitigations. -**Structure grants access, not identity.** A row-trained reader may expect any shape-compatible value -to work anywhere. In CGP a provider reads a context's fields structurally, but which providers a -context has is a nominal, wired decision, so the "area of a `Fish`" call is not automatically -expressible. +**Wiring decides which components a context has.** A provider reads a context's fields +structurally, but which providers a context uses is a nominal decision recorded in its wiring. This +keeps a component's behavior tied to the contexts that chose it. A `#[cgp_fn]` blanket trait is the +exception, since it applies wherever the fields exist. -**Shapes are opt-in.** Only a type that derives `HasFields` or `CgpData` exposes its row. A foreign -type without the derive has no shape CGP can see. +**Shapes are opt-in.** Only a type that derives `HasFields` or `CgpData` exposes its fields as a +type-level list, so CGP cannot see the shape of a foreign type without the derive. **The predicates are traits.** A `HasField` bound is a has-predicate, `CanUpcast` and `CanDowncast` -are `inj` and `prj`, and the trait solver plays the part of qualified-type inference. A reader from -the Gaster and Jones tradition, or from `row-types` in Haskell, will find the mechanism they already -reach for. +correspond to `inj` and `prj`, and the trait solver does the work of qualified-type inference. +Readers who know the Gaster and Jones design or Haskell's `row-types` library will recognize the +mechanism. ## Where to go next +These pages develop the patterns and the neighbouring comparisons: + - [Extensible records](/docs/concepts/extensible-records): the builder pattern in full. - [Extensible variants](/docs/concepts/extensible-variants): the visitor pattern and the expression problem. -- [Reflection](./reflection.md): the same type-level shapes read against runtime and compile-time +- [Reflection](./reflection.md): the same type-level shapes compared with runtime and compile-time reflection. - [Algebraic effects](./algebraic-effects.md): rows applied to effects, and how CGP's dependencies compare. diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md index 6b5f1718..4d53673a 100644 --- a/docs/comparisons/rust-language-proposals.md +++ b/docs/comparisons/rust-language-proposals.md @@ -6,20 +6,21 @@ description: 'CGP read against specialization, named impls, dictionary passing, # Rust's own proposals -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who has -followed Rust's own debate about relaxing [coherence](/docs/reference/glossary#coherence): *specialization*, the *dictionary-passing* -account of traits, *named or incoherent impls*, and *contexts and capabilities*. It shows which -fragment of each proposal CGP provides today, how the correspondence runs construct by construct, -and the two places where CGP cannot follow the proposals. It ends with what to expect that differs -and where to read further. +CGP provides, as a library, part of what several proposals to relax Rust's +[coherence](/docs/reference/glossary#coherence) rules would add to the language. It is a language +extension for Rust, with pluggable trait implementations at compile-time, implemented as a library +on stable Rust whose consumer traits are ordinary Rust traits; the [Introduction](/docs/) covers the +basics. For readers who follow *specialization*, the *dictionary-passing* account of traits, *named +or incoherent impls*, and *contexts and capabilities*, this page shows which part of each proposal +CGP provides, maps the constructs one by one, and states where CGP cannot follow the proposals. ## In your terms -The proposals and CGP share a vocabulary once the names are lined up. A **context** in CGP is the -type the method runs on, which supplies the values it needs as its fields; in most CGP code it is a -type you define to stand for an application. +A **context** is the type a CGP method runs on, supplying its data through fields and its +implementations through wiring. In most CGP code it is a type you define to stand for an +application. + +The proposals' constructs map onto CGP as follows: | In the proposals | In CGP | | --- | --- | @@ -32,21 +33,23 @@ type you define to stand for an application. ## The idea, briefly -Rust's Reference gives the two rules every proposal here relaxes. The *[orphan rule](/docs/reference/glossary#orphan-rule)* says an -`impl Trait for T0` is valid only if `Trait` is a local trait, or at least one of -the types `T0..=Tn` is a local type and no uncovered type parameter appears before it. The *overlap -rule* rejects two implementations that "can be instantiated with the same type" +Every proposal on this page relaxes one or both of the coherence rules in the Rust Reference. The +*[orphan rule](/docs/reference/glossary#orphan-rule)* says an `impl Trait for T0` +is valid only if `Trait` is a local trait, or at least one of the types `T0..=Tn` is a local type and +no uncovered type parameter appears before it. The *overlap rule* rejects two implementations that +"can be instantiated with the same type" ([Rust Reference](https://doc.rust-lang.org/reference/items/implementations.html); -[RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). Together they -guarantee that any trait lookup finds exactly one impl, and that guarantee lets generic code resolve -`T: Hash` transitively and keeps a `HashMap` sound. The -[type classes](./type-classes.md) page covers why coherence exists in the wider tradition; this page -takes it as given. +[RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). + +Together the two rules guarantee that any trait lookup finds exactly one impl. That guarantee lets +generic code resolve `T: Hash` transitively and keeps a `HashMap` sound. The +[type classes](./type-classes.md) page covers why coherence exists in the wider type-class +tradition; this page takes it as given. ### Specialization RFC 1210 proposes letting two impls overlap when one is *strictly more specific*, with the compiler -picking the specific one. Its own example refines a blanket `AddAssign`: +choosing the more specific one. Its own example refines a blanket `AddAssign`: ```rust impl + Clone> AddAssign for T { @@ -60,22 +63,23 @@ impl + Clone> AddAssign for T { The `default` keyword marks an item that a more specific impl may override ([RFC 1210](https://rust-lang.github.io/rfcs/1210-impl-specialization.html)). The feature has been unstable since 2016. Its tracking issue states that the full feature "as implemented currently is -*unsound*", because dispatch information about lifetimes is erased before code generation, and the -`min_specialization` subset the standard library uses internally is the usable fragment -([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). On a stable toolchain -the snippet above fails with `E0658`. - -Specialization also does not address the case CGP starts from. Two impls of equal generality, such as -`Hash for T: Display` and `Hash for T: AsRef<[u8]>`, are not ordered by specificity, so specialization -rejects them as coherence does. And generic code can bind a blanket impl through a bound that never -mentions the trait, so by the time the concrete type is known the specialization is invisible. The -[RustLab 2025 talk](/blog/rustlab-2025-coherence) builds this argument on a hash-table example. +*unsound*", because dispatch information about lifetimes is erased before code generation. The +`min_specialization` subset, which the standard library uses internally, is the usable part +([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). On a stable toolchain the +snippet above fails with `E0658`. + +Specialization also does not address the case CGP starts from. Two impls of equal generality, such +as `Hash for T: Display` and `Hash for T: AsRef<[u8]>`, are not ordered by specificity, so +specialization rejects them as coherence does. In addition, generic code can select a blanket impl +through a bound that never mentions the trait. By the time the concrete type is known, that code can +no longer see the more specific impl. The [RustLab 2025 talk](/blog/rustlab-2025-coherence) develops +this argument with a hash-table example. ### Dictionary passing -A second line of thought treats the trait system as sugar over *dictionary passing*: a trait becomes -a struct of function pointers, an impl becomes a value of that struct, and a trait bound becomes an -argument the caller passes. Nadrieril works it out for Rust: +Another line of work treats the trait system as a shorthand for *dictionary passing*. A trait +becomes a struct of function pointers, an impl becomes a value of that struct, and a trait bound +becomes an argument the caller passes. Nadrieril works this out for Rust: ```rust struct Clone { @@ -85,19 +89,19 @@ struct Clone { const CLONE_U32: Clone = Clone { clone: |x: &u32| *x }; ``` -Trait solving is then the process that supplies these values, and coherence is the point of -friction, since a global impl constrains a caller in ways the caller cannot see +In this account, trait solving is the process that supplies these values. Coherence becomes a source +of friction, because a global impl constrains a caller in ways the caller cannot see ([Nadrieril, *Dictionary-passing style*](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). -Once impls are values, *choosing* an impl is passing a different value, which is the freedom -coherence forbids. +Once impls are values, choosing a different impl means passing a different value, and coherence +forbids exactly that choice. ### Named and incoherent impls -Boxy's *An Incoherent Rust* proposes dropping the coherence rules in favour of explicit impl -selection. The motivation is *ecosystem evolution*: once a foundational crate such as `serde` -establishes the trait impls for common types, an alternative cannot gain adoption, because downstream -crates cannot implement the competing trait for types they do not own. The sketch names an impl and -passes it where a bound is required: +Boxy's *An Incoherent Rust* proposes replacing the coherence rules with explicit impl selection. The +motivation is *ecosystem evolution*. The post argues that once a foundational crate such as `serde` +establishes the trait impls for common types, an alternative cannot gain adoption, because +downstream crates cannot implement the competing trait for types they do not own. The sketch names an +impl and passes it where a bound is required: ```rust impl Name = Trait for T { /* ... */ } @@ -105,18 +109,18 @@ impl Name = Trait for T { /* ... */ } function:: + OtherTraitImpl>(/* ... */) ``` -The post answers the two classic justifications for coherence on their own terms. The `HashMap` -problem is solved by moving the `Hash` and `Eq` bounds onto the type definition, so every operation -on one map agrees on one impl. Associated-type soundness holds because the impl is part of the type. -It names the remaining challenges as substantial: syntax, ergonomics, migration, and whether the -complexity is worth it ([Boxy, *An Incoherent Rust*](https://www.boxyuwu.blog/posts/an-incoherent-rust/)). +The post answers the two classic justifications for coherence directly. It solves the `HashMap` +problem by moving the `Hash` and `Eq` bounds onto the type definition, so every operation on one map +uses the same impl. It keeps associated types sound by making the impl part of the type. It names +the remaining challenges as substantial: syntax, ergonomics, migration, and whether the added +complexity is worthwhile ([Boxy, *An Incoherent Rust*](https://www.boxyuwu.blog/posts/an-incoherent-rust/)). ### Contexts and capabilities -Tyler Mandry's 2021 proposal addresses a different limitation: a function or impl cannot reach a value -from its caller's environment, such as an allocator or a logger, except by threading it as a -parameter or storing it in a global. A `with` clause on a declaration names the context it requires, -and a `with` block at a call site supplies it: +Tyler Mandry's 2021 proposal addresses a different limitation. A function or impl can reach a value +from its caller's environment, such as an allocator or a logger, only by taking it as a parameter or +reading a global. The proposal adds a `with` clause on a declaration, which names the context value +it requires, and a `with` block at a call site, which supplies it: ```rust fn deserialize<'a>(bytes: &[u8]) -> Result<&'a Foo, Error> @@ -131,22 +135,23 @@ with arena::basic_arena = &arena::BasicArena::new() { } ``` -The distinctive power is a *context-dependent trait impl*, valid only when a given capability is in -scope. The mechanism compiles to ordinary function arguments, so it costs nothing at runtime, and the -open questions concern thread boundaries and scope validity +The proposal's distinctive feature is a *context-dependent trait impl*, which is valid only while a +given capability is in scope. The mechanism compiles to ordinary function arguments, so it adds no +runtime cost. Its open questions concern thread boundaries and scope validity ([Mandry, *Contexts and capabilities in Rust*](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). The proposal borrows the word "capability" from a security model whose other properties it does not -claim; the [capabilities](./capabilities.md) page separates the senses. Nadrieril's follow-up extends -dictionary passing so a trait bound may carry a runtime value, and names the difficulties that follow: -ownership modes for the carried value, the same type satisfying a trait differently in different -scopes, and methods that become closures +claim; the [capabilities](./capabilities.md) page separates the senses. + +Nadrieril's follow-up extends dictionary passing so that a trait bound can carry a runtime value. It +names the difficulties that follow: ownership modes for the carried value, the same type satisfying a +trait differently in different scopes, and methods that become closures ([*What If Traits Carried Values*](https://nadrieril.github.io/blog/2026/03/22/what-if-traits-carried-values.html)). ### Cairo: a Rust-like language that shipped named impls -Cairo borrows Rust's surface syntax and gives every impl a name, so it is the nearest thing to a -shipped Incoherent Rust. A generic function may take an impl as an explicit parameter, named or -anonymous: +Cairo borrows Rust's surface syntax and gives every impl a name, which makes it the closest shipped +counterpart to Incoherent Rust. A generic function can take an impl as an explicit parameter, named +or anonymous: ```rust // Cairo @@ -155,25 +160,25 @@ fn largest_list>(l1: Array, l2: Array) -> Array fn smallest_element, +Copy, +Drop>(list: @Array) -> T { /* ... */ } ``` -A caller does not pass the impl: the compiler infers it from the impls visible at the call site +A caller does not pass the impl. The compiler infers it from the impls visible at the call site ([Cairo Book, *Traits*](https://www.starknet.io/cairo-book/ch08-02-traits-in-cairo.html); -[*Generic Data Types*](https://www.starknet.io/cairo-book/ch08-01-generic-data-types.html)). That -inference is the design decision that matters for the comparison, because resolving from scope means -the set of imports decides which implementation a call uses. +[*Generic Data Types*](https://www.starknet.io/cairo-book/ch08-01-generic-data-types.html)). This +inference matters for the comparison: because resolution uses what is in scope, a call site's +imports decide which implementation it uses. ## How CGP expresses it -CGP provides a fragment of each proposal as a library, and the correspondence is close enough to -state construct by construct. What the proposals would add to the language, CGP adds as a library, -with one standing restriction: every binding lives in one place, the context. +The correspondence can be stated construct by construct. The main difference is where bindings live. The proposals bind an impl at a call site or +within a scope, while CGP records every binding in one place: the context. ### A named impl is a provider -A CGP provider is the thing Boxy's proposal names with `impl Name = Trait for T`. Every -implementation gets its own zero-sized type, so two overlapping impls of one trait coexist because -each implements the provider trait for its own name. The encoder pair from the -[Introduction](/docs/) shows it. Rust rejects two blanket impls of one trait for `T: Display` and -`T: AsRef<[u8]>`, since `String` satisfies both. As providers, both compile: +A CGP provider corresponds to an impl named with `impl Name = Trait for T` in Boxy's proposal. +Each implementation has its own zero-sized type. Overlapping implementations of one trait can +therefore coexist, because each implements the provider trait for its own type. The encoder pair +from the [Introduction](/docs/) shows this. Rust rejects two blanket impls of one trait for +`T: Display` and `T: AsRef<[u8]>`, since `String` satisfies both. Written as providers, both +compile: ```rust #[cgp_component(Encoder)] @@ -197,18 +202,21 @@ impl> Encoder { ``` `EncodeWithDisplay` and `EncodeBytes` are named impls in the proposal's sense. They overlap on -`String`, they are selected by name, and a crate that owns neither `Display` nor `String` may define -more, because the provider trait is always implemented for a type the crate owns. This is the -overlap and orphan relief specialization cannot give, since the two providers are equally general. -The encoded value has moved from `Self` into the `Value` parameter, so `Self` is free to be an -application: the contexts below are **[environmental contexts](/docs/reference/glossary#environmental-context)**, types that stand for an application, -and the component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component). +`String`, and a context selects one by name. A crate that owns neither `Display` nor `String` can +define more of them, because each provider trait is implemented for a provider type the defining +crate owns. Specialization cannot provide this relief from the overlap and orphan rules, because the +two providers are equally general. + +The encoded value is the `Value` parameter rather than `Self`, so `Self` can stand for an +application. The contexts below are +**[environmental contexts](/docs/reference/glossary#environmental-context)**, and the component is +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component). ### An incoherent bound resolves through the context, not at each call site Boxy's `function::>` passes the impl at every call. CGP lets generic code require -the consumer trait on the context and defers the choice to the place the context is defined. Two -applications answer differently for the same type: +the consumer trait on the context and makes the choice where the context is defined. Two +applications can choose differently for the same type: ```rust pub struct ApiServer; @@ -229,19 +237,19 @@ delegate_components! { } ``` -This is the proposal's incoherence with a different resolution point. Boxy and Cairo resolve at the -call site, explicitly or from what is in scope. CGP resolves at the context, so every call through -`ApiServer` agrees. That is also how CGP answers the `HashMap` concern: a context selects one -provider per component, so all code sharing a context agrees on one impl, which is the property the -proposal recovers by moving `Hash` onto the type definition. The [type classes](./type-classes.md) -page develops this as incoherent instances made deterministic. +CGP provides the proposal's incoherence with a different resolution point. Boxy and Cairo resolve at +the call site, explicitly or from what is in scope. CGP resolves at the context, so every call +through `ApiServer` uses the same choice. This also answers the `HashMap` concern: a context selects +one provider per component, so all code sharing a context uses one impl. The proposal gets the same +property by moving `Hash` onto the type definition. The [type classes](./type-classes.md) page +develops this comparison with Haskell's incoherent instances. ### Passing an impl explicitly is a higher-order provider -Where the proposals and Cairo let a caller pass an impl as a parameter, CGP has -[higher-order providers](/docs/concepts/higher-order-providers). A provider takes another provider as -a type parameter and binds it with `#[use_provider]`, which is Cairo's `impl TDrop: Drop` as a -Rust generic: +Where the proposals and Cairo let a caller pass an impl as a parameter, CGP uses +[higher-order providers](/docs/concepts/higher-order-providers). A provider takes another provider +as a type parameter and binds it with `#[use_provider]`, which corresponds to Cairo's +`impl TDrop: Drop` written as a Rust generic: ```rust #[cgp_impl(new ScaledArea)] @@ -253,19 +261,19 @@ impl AreaCalculator { } ``` -A context wires `AreaCalculatorComponent: ScaledArea`, naming the inner impl where a -Cairo caller would have the compiler infer it. Assembling providers at every call site is possible in -CGP but verbose, and idiomatic CGP defers the assembly to the context. A higher-order provider is the -form for a provider that must fix its inner choice locally, and it defaults its inner parameter to -[`UseContext`](/docs/reference/providers/use_context) so the context's wiring is the fallback. The -wired type here is a `ScaledRectangle` carrying `width`, `height`, and `scale_factor`, a **value -context**: the type being measured also carries the wiring. +A context wires `AreaCalculatorComponent: ScaledArea`, naming the inner impl that a +Cairo compiler would infer. CGP can assemble providers at each call site, but doing so is verbose, +and idiomatic CGP leaves the assembly to the context. A higher-order provider suits a provider that +must fix its inner choice locally. Such providers often default the inner parameter to +[`UseContext`](/docs/reference/providers/use_context), so that the context's wiring is the fallback. +The wired type here is a `ScaledRectangle` with `width`, `height`, and `scale_factor` fields. It is a +**value context**: the type being measured also carries the wiring. -### A capability is a context field; the `with` block is the context +### A `with` clause becomes a context field Mandry's `with arena: &BasicArena` clause declares a value the function needs from its environment. -CGP declares the same thing as an [implicit argument](/docs/concepts/implicit-arguments), which -reads a field of the context every provider receives as `self`: +CGP declares the same need as an [implicit argument](/docs/concepts/implicit-arguments), which reads +a field of the context that every provider receives as `self`: ```rust #[cgp_impl(new GreetHello)] @@ -276,8 +284,8 @@ impl Greeter { } ``` -The `with` block that supplies the capability becomes a context type carrying the field, and the -binding happens when a value of that type is constructed: +The `with` block that supplies the value becomes a context type that carries the field. Constructing +a value of that type makes the binding: ```rust #[derive(HasField)] @@ -295,89 +303,97 @@ let app = App { name: "World".to_owned() }; app.greet(); // "Hello, World!" ``` -`App` is the context, and constructing it is the `with` binding. Two properties of the proposal carry -over exactly: the binding costs nothing at runtime, since a field read compiles to a load, and it is -checked statically, since a missing field is a compile error that -[`check_components!`](/docs/reference/macros/check_components) names at the wiring site. `App` here -is an environmental context with one field, and `GreetHello` is [self-targeted](/docs/reference/glossary#self-targeted-component). +`App` is the context, and constructing it plays the role of the `with` block. Two properties of the +proposal carry over. The binding adds no runtime cost, since a field read compiles to a load. It is +also checked statically: a missing field is a compile error, which +[`check_components!`](/docs/reference/macros/check_components) reports at the wiring site. `App` here +is an environmental context with one field, and the greeter component is +[self-targeted](/docs/reference/glossary#self-targeted-component). ### The context is the dictionary The dictionary-passing account and CGP meet in one observation: the context is the top-level -dictionary. In Nadrieril's elaboration every dictionary is a value passed alongside the data. In CGP -every provider receives the context, and the context's wiring table is a type-level record of -dictionaries, one `DelegateComponent` entry per component. Lowering a CGP program to -dictionary-passing form turns the context into a struct whose fields are the other dictionaries, with -a near one-to-one correspondence between a `delegate_components!` entry and a field of that struct. -The arrangement has a practical consequence the proposals have to solve separately: because every -dictionary reaches the others through the context, a dependency graph with cycles resolves without -an instantiation order, since the context is one stable root from which all of them are reachable. -The [ML modules](./ml-modules.md) page contrasts this with manual functor application. +dictionary. In Nadrieril's elaboration, every dictionary is a value passed alongside the data. In +CGP, every provider receives the context, and the context's wiring table is a type-level record of +dictionaries, with one `DelegateComponent` entry per component. Lowering a CGP program to +dictionary-passing form would turn the context into a struct whose fields are the other +dictionaries, with close to one field per `delegate_components!` entry. + +This arrangement also handles a problem the proposals must solve separately. Every dictionary +reaches the others through the context, so components that depend on each other resolve without an +instantiation order: the context is one stable root from which all of them are reachable. The +[ML modules](./ml-modules.md) page contrasts this with manual functor application. ## What each approach costs -The proposals are language changes that have not shipped, and their costs are the ones their authors -name. Specialization has an accepted RFC, a soundness hole open since 2016, and no path to +The proposals are language changes that have not shipped, and their authors name their costs. +Specialization has an accepted RFC, a soundness hole open since 2016, and no announced path to stabilization ([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). The -named-impl and dictionary-passing designs are blog posts and design sketches, and their authors list -syntax, ergonomics, migration of the existing ecosystem, and the loss of the guarantees coherence -gives for free as the open problems ([Boxy](https://www.boxyuwu.blog/posts/an-incoherent-rust/); -[Nadrieril](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). Contexts -and capabilities is a research direction from 2021 with open questions about thread boundaries and +named-impl and dictionary-passing designs are blog posts and design sketches. Their authors list the +open problems: syntax, ergonomics, migration of the existing ecosystem, and the loss of the +guarantees that coherence provides automatically +([Boxy](https://www.boxyuwu.blog/posts/an-incoherent-rust/); +[Nadrieril](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). Contexts and +capabilities is a research direction from 2021, with open questions about thread boundaries and scope ([Mandry](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). Cairo's -scope-based inference means a caller must import the whole chain of impls a generic impl needs, and -two call sites in one project can resolve the same type differently. +resolution from scope means that a caller must import every impl a generic impl needs, directly or +indirectly, and two call sites in one project can resolve the same type differently. -CGP's costs are the ordinary ones. The provider trait has to be defined through +CGP's costs are the ordinary ones. A provider trait must be defined through [`#[cgp_component]`](/docs/reference/macros/cgp_component), so CGP cannot retrofit an existing -foreign trait such as `serde::Serialize` without a parallel component, where a language change would -apply to every trait. The wiring is code somebody writes and reads, where a language feature would -infer it. The compile-time work is real. And the raw diagnostics are trait-solver output over -generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes -it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page is where these costs are weighed +foreign trait such as `serde::Serialize` without a parallel component, while a language change would +apply to every trait. The wiring is code that someone writes and reads, where a language feature +would infer it. Trait resolution over the wiring adds compile-time work. The raw diagnostics are +trait-solver output over generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the +root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape +every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the alternatives in full. ## Where a proposal, or a smaller tool, is the better choice -Where a program needs exactly a specialized fast path for one type under a blanket impl, -`min_specialization` on nightly, or a manual dispatch trick on stable, is the smaller tool, and CGP -would add wiring specialization would infer. Where a program needs one globally consistent -implementation, such as the `Ord` a map's keys rely on, coherence as it stands is the right -arrangement and CGP's per-context choice is not an improvement on it. And where a program can wait, -a language feature that infers the impl from scope or nests bindings dynamically would express these -patterns with less ceremony than a library can. Where the need is several equally valid impls chosen -per application, impls for types the program does not own, or environment values reaching deep code -without parameters, CGP is the one option available on stable Rust today, and its explicitness is the -price of that. +A smaller tool fits a program that needs only a specialized fast path for one type under a blanket +impl. `min_specialization` on nightly, or a manual dispatch technique on stable, handles that case, +while CGP would require wiring that specialization infers. Coherence as it stands fits a program +that needs one globally consistent implementation, such as the `Ord` that a map's keys rely on; +CGP's per-context choice does not improve that arrangement. A program that can wait for a language +feature may get one that infers the impl from scope or nests bindings dynamically, which would +express these patterns with less ceremony than a library can. + +CGP fits a program that needs several equally valid impls chosen per application, impls for types +the program does not own, or environment values that reach deep code without extra parameters. It +provides these on stable Rust today, and its explicit wiring is the cost. ## What to expect that differs -**CGP does not infer an impl from scope.** Cairo and the named-impl sketch let the compiler pick an -impl from those visible at a call site. CGP has no such search: a context names every provider it -uses in its wiring table. This is deliberate, and it keeps two call sites in one program from -resolving the same type differently by accident. +**CGP does not infer an impl from scope.** Cairo and the named-impl sketch let the compiler choose +among the impls visible at a call site. CGP has no such search: a context names every provider it +uses in its wiring table. This design prevents two call sites in one program from resolving the same +type differently by accident. -**Bindings are flat.** Mandry's `with` blocks nest, and an inner scope can shadow an outer binding. In -CGP every binding lives at the one place the concrete context is defined, so an inner scope cannot -shadow a provider without defining a new context type. All bindings for a context are readable in one -place, and that is the trade. +**Bindings are flat.** Mandry's `with` blocks nest, and an inner scope can shadow an outer binding. +In CGP every binding lives where the concrete context is defined, so an inner scope cannot replace a +provider without defining a new context type. In return, all bindings for a context can be read in +one place. -**A provider receives `&self`.** A capability that must be `&mut` or owned needs interior mutability -or cloning, rather than the ownership-aware design the proposals discuss. +**Providers share one context value.** A provider method can take `&self` or `&mut self`, but a +`&mut self` method can borrow only one field mutably through its implicit arguments. A value that +several providers must mutate or own independently needs interior mutability or cloning; the +proposals discuss designs that track ownership modes directly. -**CGP is not specialization for stable Rust.** It does not pick a more specific impl, it does not -touch existing traits, and it asks for wiring specialization would infer. It addresses the two -problems specialization leaves open, equally general overlap and orphans, by naming implementations -and choosing them per context. +**CGP is not specialization for stable Rust.** It does not choose a more specific impl, it does not +change existing traits, and it asks for wiring that specialization would infer. It addresses the two +problems specialization leaves open, overlap between equally general impls and the orphan rule, by +naming implementations and choosing them per context. ## Where to go next +These pages develop the constructs and the neighbouring comparisons: + - [Bypassing coherence](/docs/concepts/coherence): the coherence rules and the provider move, without reference to the proposals. - [Higher-order providers](/docs/concepts/higher-order-providers) and [implicit arguments](/docs/concepts/implicit-arguments): the two constructs this page maps onto - passed impls and capabilities. + passed impls and `with` clauses. - [Type classes](./type-classes.md): the same trade seen from Haskell's side, including the `INCOHERENT` and overlapping-instance extensions. - [RustLab 2025 talk](/blog/rustlab-2025-coherence): why coherence exists and why specialization does diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md index fb820f81..f19eadc5 100644 --- a/docs/comparisons/type-classes.md +++ b/docs/comparisons/type-classes.md @@ -6,20 +6,22 @@ description: 'CGP read against Haskell, Agda, and Lean type classes, coherence, # Type classes -CGP is a language extension for Rust, with pluggable trait implementations at compile-time: a -library on stable Rust in which a trait can have several named implementations and each context -selects one. The [Introduction](/docs/) covers the basics. This page is for the reader who knows type -classes from Haskell, Agda, or Lean. Rust traits are Rust's type classes, so CGP already lives inside -a type-class system, and its one change is to the *[coherence](/docs/reference/glossary#coherence)* rule: it makes instances first-class -values selected explicitly per context, which is the freedom overlapping and incoherent instances -reach for without making it safe. The page covers the class and instance correspondence, the -coherence trade, where coherent type classes remain the better tool, and what a type-class reader -should expect to differ. +CGP lets one Rust trait have several named implementations and lets each context choose among them, +which relaxes the one-instance-per-type limit that type-class coherence imposes. It is a language +extension for Rust, with pluggable trait implementations at compile-time, implemented as a library +on stable Rust whose consumer traits are ordinary Rust traits; the [Introduction](/docs/) covers the +basics. Rust traits are Rust's type classes, so CGP works inside a type-class system and changes only +how an implementation is chosen. For readers who know type classes from Haskell, Agda, or Lean, this +page maps classes and instances onto CGP, compares CGP with overlapping and incoherent instances, +and states where coherent type classes remain the better tool. ## In your terms -A **context** in CGP is the type the method runs on, which supplies the values it needs as its -fields. In the dictionary-passing account it is the dictionary that carries every other dictionary. +A **context** is the type a CGP method runs on, supplying its data through fields and its +implementations through wiring. In the dictionary-passing account, the context is the dictionary +that carries every other dictionary. + +The type-class vocabulary maps onto CGP as follows: | In a type-class language | In CGP | | --- | --- | @@ -32,10 +34,10 @@ fields. In the dictionary-passing account it is the dictionary that carries ever ## The idea, briefly -Type classes make overloading principled. A class declares an interface, an instance implements it -for a type, and a constrained function works for every type with an instance, with the compiler -finding the instance. Wadler and Blott introduced them to "make ad-hoc polymorphism less ad hoc" -([Wadler & Blott, 1989](https://dl.acm.org/doi/10.1145/75277.75283)): +Type classes give overloading a principled basis. A class declares an interface, an instance +implements it for a type, and a constrained function works for every type with an instance, with the +compiler finding the instance. Wadler and Blott introduced them to "make ad-hoc polymorphism less ad +hoc" ([Wadler & Blott, 1989](https://dl.acm.org/doi/10.1145/75277.75283)): ```haskell class Show a where @@ -49,32 +51,33 @@ describe :: Show a => a -> String describe x = "value: " ++ show x ``` -Underneath, the class is a *dictionary*, a record of the class methods; an instance is a dictionary -value; and `describe` elaborates to a function that takes the dictionary as an extra hidden argument. -Dictionary passing is the implementation model behind every system on this page, and behind CGP. It -is the same idea as the evidence passing on the [algebraic effects](./algebraic-effects.md) page and -the qualified-type constraints on the [row polymorphism](./row-polymorphism.md) page. +Underneath, the class is a *dictionary*, a record of the class methods. An instance is a dictionary +value, and `describe` elaborates to a function that takes the dictionary as an extra hidden argument. +Dictionary passing is the implementation model behind every system on this page, including CGP. It is +the same idea as the evidence passing on the [algebraic effects](./algebraic-effects.md) page and the +qualified-type constraints on the [row polymorphism](./row-polymorphism.md) page. ### Coherence: one instance per type, globally -*Coherence* makes silent, automatic resolution safe. For a given class and type there is one -instance, and every resolution anywhere in the program finds the same one. The property decomposes -into *confluence*, *coherence*, and *global uniqueness*; GHC guarantees the first two within a -compilation and does not enforce the third across a whole program +*Coherence* makes automatic resolution safe. For a given class and type there is one instance, and +every resolution anywhere in the program finds the same one. The property divides into +*confluence*, *coherence*, and *global uniqueness*. GHC guarantees the first two within a compilation +and does not enforce the third across a whole program ([Yang, *Type classes: confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). -The canonical benefit is a `Set` of an ordered element type: with one `Ord` for that type, values -inserted under one ordering and read under another can never disagree. +The standard example of the benefit is a `Set` of an ordered element type. With one `Ord` for that +type, values inserted under one ordering can never be read back under another. -Rust makes the same choice and *enforces* it where Haskell advises. Rust traits are type classes with -a hard [orphan rule](/docs/reference/glossary#orphan-rule), so an impl is allowed only when the crate owns the trait or the type -([RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). That strictness -is the rule CGP is built to work within, and the [Rust proposals](./rust-language-proposals.md) page -covers what Rust itself has considered doing about it. +Rust makes the same choice and enforces it more strictly. Rust traits are type classes with a hard +[orphan rule](/docs/reference/glossary#orphan-rule): an impl is allowed only when the crate owns the +trait or the type ([RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)), +while GHC permits orphan instances and can warn about them. CGP is built to work within Rust's +rule, and the [Rust proposals](./rust-language-proposals.md) page covers what Rust itself has +considered doing about it. ### Overlapping instances -The first extension lets instances overlap when one is strictly more specific. GHC exposes it through -per-instance pragmas: +GHC's first extension to the rule lets instances overlap when one is strictly more specific. It is +enabled through per-instance pragmas: ```haskell instance {-# OVERLAPPABLE #-} Show a => Show [a] where -- lists in general @@ -100,8 +103,8 @@ cause unexpected results" ([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc ### Instance arguments in Agda -Agda offers class-style overloading without a class construct and without coherence. A record plays -the class, and a double-braced argument is resolved from the call-site scope +Agda provides class-style overloading without a class construct and without coherence. A record +plays the role of the class, and a double-braced argument is resolved from the scope at the call site ([Devriese & Piessens, 2011](https://dl.acm.org/doi/10.1145/2034574.2034796)): ```agda @@ -116,12 +119,12 @@ print : {A : Set} → {{Show A}} → A → String print {{s}} x = Show.show s x ``` -Resolution succeeds when exactly one instance in scope matches, and an ambiguity is a local error at -that use site rather than a program-wide guarantee. +Resolution succeeds when exactly one instance in scope matches. An ambiguity is an error at that use +site rather than a violation of a program-wide guarantee. ### Type classes in Lean: search, priorities, and the diamond problem -Lean resolves classes by a backtracking tabled search with per-instance priorities: +Lean resolves classes with a backtracking, tabled search that respects per-instance priorities: ```lean class Show (α : Type) where @@ -133,38 +136,42 @@ instance : Show Bool where #eval Show.display true -- "true" ``` -Because Lean allows multiple instances, the same constraint can be satisfiable in more than one way, -and when two resolution paths disagree, a *diamond*, inference can pick the wrong one or diverge -([Selsam, Ullrich & de Moura, *Tabled Typeclass Resolution*](https://arxiv.org/pdf/2001.04301)). In -a proof assistant two instances that are not definitionally equal break proofs that assume they -coincide, so the Mathlib community keeps overlapping instances definitionally equal as a standing -discipline ([Baanen, 2022](https://arxiv.org/pdf/2202.01629)). +Lean allows multiple instances, so the same constraint can be satisfied in more than one way. When +two resolution paths disagree, which is called a *diamond*, inference can pick the wrong instance or +diverge ([Selsam, Ullrich & de Moura, *Tabled Typeclass Resolution*](https://arxiv.org/pdf/2001.04301)). +In a proof assistant, two instances that are not definitionally equal break proofs that assume they +coincide. The Mathlib community therefore keeps overlapping instances definitionally equal as a +standing practice ([Baanen, 2022](https://arxiv.org/pdf/2202.01629)). ### Modular type classes -Dreyer, Harper, and Chakravarty showed that type classes are ML modules plus a resolution layer: -**classes as signatures and instances as structures and functors**, with certain instance modules -designated *canonical* within a scope so the compiler can resolve them implicitly -([*Modular Type Classes*](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf)). The paper -names the tension every design on this page negotiates: **canonicity fights modularity.** A canonical -instance makes implicit resolution safe, and it is a non-modular property, since two modules can each -supply a different one. The design space is a spectrum. At one end sits Haskell: fully -implicit resolution, global coherence, one instance per type. In the middle sit modular type classes, -OCaml's modular implicits, Agda instance arguments, and Scala implicits: implicit resolution with -canonicity scoped or dropped, paid for in ambiguity. CGP sits at the far end: no canonicity, no -search, and explicit per-context selection. The [ML modules](./ml-modules.md) page develops the -module side. +Dreyer, Harper, and Chakravarty showed that type classes can be expressed as ML modules with a +resolution layer added: **classes as signatures, and instances as structures and functors**. Certain +instance modules are designated *canonical* within a scope, so the compiler can resolve them +implicitly ([*Modular Type Classes*](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf)). + +The paper identifies a tension that every design on this page must resolve: **canonicity conflicts +with modularity.** A canonical instance makes implicit resolution safe, but canonicity is not a +modular property, since two modules can each supply a different instance. The designs fall along a +range: + +- **Haskell:** Fully implicit resolution, global coherence, and one instance per type. +- **Modular type classes, OCaml's modular implicits, Agda instance arguments, and Scala implicits:** + Implicit resolution with canonicity scoped or dropped, at the cost of possible ambiguity. +- **CGP:** No canonicity and no search. Each context selects its implementations explicitly. + +The [ML modules](./ml-modules.md) page develops the module side. ## How CGP expresses it -CGP is a type-class system with the coherence rule removed and explicit per-context selection in its -place, built by splitting each class into a consumer trait callers use and a provider trait -implementations target. The consumer trait is an ordinary Rust type class. The provider trait and the -wiring are what make instances first-class values. +CGP keeps Rust's type classes and replaces the automatic choice of an implementation with explicit +selection per context. It splits each class into a consumer trait that callers use and a provider +trait that implementations target. The consumer trait is an ordinary Rust trait. The provider trait +and the wiring let implementations be named and chosen. ### A component is a class; a provider is a first-class instance -Declaring a component is declaring a class: +Declaring a component declares a class: ```rust #[cgp_component(AreaCalculator)] @@ -174,9 +181,9 @@ pub trait CanCalculateArea { ``` `CanCalculateArea` is the class interface, as `class Show a` is. The two systems differ in what an -instance may be. A Haskell instance is anonymous and canonical: there is one `Show Bool`, chosen by the -compiler. A CGP provider is a named marker type carrying a provider-trait impl, a *first-class -dictionary* you can name and choose among: +instance can be. A Haskell instance is anonymous and canonical: there is one `Show Bool`, and the +compiler chooses it. A CGP provider is a named marker type that carries a provider-trait impl, a +*first-class dictionary* that code can name and choose among: ```rust #[cgp_impl(new RectangleArea)] @@ -195,19 +202,20 @@ pub struct Rectangle { delegate_components! { Rectangle { AreaCalculatorComponent: RectangleArea } } ``` -Moving the implementation off the context and onto a provider marker is the single device that lifts -the one-instance-per-type limit: because a provider implements the provider trait for *its own* type, -coherence never forbids a second one. The wiring line plays the role of resolution, explicitly, where -Haskell's compiler would search for the canonical instance. A provider's `#[uses]` imports are the -class constraints threaded by dictionary passing, and the context is the dictionary that carries them. -`Rectangle` here is a **[value context](/docs/reference/glossary#value-context)**: the type being measured also carries the wiring, and the -component is [self-targeted](/docs/reference/glossary#self-targeted-component). +Implementing the provider trait on a provider type, rather than on the context, removes the +one-instance-per-type limit. Each provider implements the provider trait for its *own* type, so +coherence does not forbid a second provider. The wiring line takes the place of resolution: it states +the choice that Haskell's compiler would find by searching for the canonical instance. A provider's +`#[uses]` imports correspond to the class constraints that dictionary passing threads through, and +the context carries them. `Rectangle` here is a +**[value context](/docs/reference/glossary#value-context)**: the type being measured also carries +the wiring, and the component is [self-targeted](/docs/reference/glossary#self-targeted-component). -### Overlapping instances are the default, with no heuristic +### Overlapping providers need no specificity rule -Where Haskell needs pragmas and a most-specific heuristic to permit overlap, CGP permits unlimited -overlapping providers by construction and resolves them by naming rather than guessing. Two encoders -that both apply to `String` compile side by side: +Haskell needs pragmas and a most-specific rule to permit overlap. CGP allows any number of +overlapping providers, and a context chooses among them by name rather than by specificity. Three +encoders that apply to overlapping sets of types compile side by side: ```rust #[cgp_component(Encoder)] @@ -237,19 +245,23 @@ impl> Encoder { } ``` -As type-class instances two of these would be rejected, since `String` matches the first pair and -`Vec` matches the second, and even with `OVERLAPPING` the compiler would need one to be strictly -more specific. As providers all three compile, because each implements the provider trait for its -own marker. There is no most-specific rule and therefore no ambiguity. The fragility -GHC warns about, overlap silently producing incoherence, cannot arise, because the choice is never -inferred. Here the encoded value has moved from `Self` into the `Value` parameter, so the contexts -that wire these providers are **[environmental contexts](/docs/reference/glossary#environmental-context)**, types standing for an application, and the -component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component). +As type-class instances these would conflict: `String` matches the first pair, and `Vec` matches +the second. Even with `OVERLAPPING`, the compiler would need one instance to be strictly more +specific. As providers, all three compile, because each implements the provider trait for its own +marker type. CGP has no most-specific rule, so the overlap creates no ambiguity. The problem GHC +warns about, overlap that silently produces incoherence, does not arise here, because CGP never +infers the choice. -### Incoherent instances made deterministic and local +The encoded value is the `Value` parameter rather than `Self`, so the contexts that wire these +providers are **[environmental contexts](/docs/reference/glossary#environmental-context)**, types that +stand for an application. The component is +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component). -CGP keeps the many-instances-for-one-type situation that type-class languages fear and makes it safe -by moving the choice from a global search to an explicit per-context table: +### Incoherent choices made explicit and local + +CGP allows several implementations for one type, the situation that type-class languages guard +against, and makes it safe by moving the choice from a global search to an explicit table in each +context: ```rust pub struct AppA; @@ -272,44 +284,46 @@ delegate_components! { } ``` -Each context selects one provider per component and per value type, so two contexts resolve the same -type differently *on purpose*, and within one context the choice is unambiguous and fixed. `AppA` -encoding a `Vec` as hexadecimal and `AppB` passing the bytes through are two coherent local -scopes, not a global incoherence. The different-choice-in-different-places that is a hazard in -Haskell and a diamond in Lean is a feature here because it is written down. In one line, CGP is -incoherent instances with the incoherence made deterministic and the selection made explicit. The -`open` statement and the `@`-path keys are documented on the -[`delegate_components!`](/docs/reference/macros/delegate_components) page. +Each context selects one provider per component and per value type. Two contexts can therefore +resolve the same type differently *on purpose*, while the choice within one context is unambiguous +and fixed. `AppA` encodes a `Vec` as hexadecimal and `AppB` passes the bytes through, and each +context is consistent on its own terms. In Haskell, different choices in different parts of a program +are a hazard, and in Lean they produce a diamond. In CGP each choice is written in a context's table, +so a reader can see which one applies. The `open` statement and the `@`-path keys are documented on +the [`delegate_components!`](/docs/reference/macros/delegate_components) page. -### No orphan rule, no newtype +### Providers avoid orphan conflicts and newtypes -Two everyday frustrations disappear because a provider's `Self` is always a type its crate owns. The -orphan rule never applies, so a downstream crate can supply a provider for a component and a type it -did not define. And the newtype a type needs for a second instance, such as `Sum` and `Product` -wrapping `Int`, is unnecessary: a second behavior for a type is a second provider, named directly. -The [Bypassing coherence](/docs/concepts/coherence) page shows both on the encoder example. +A provider's `Self` is always a type that its crate owns, and this removes two common workarounds. +The orphan rule is always satisfied, so a downstream crate can supply a provider for a component and +a type it did not define. A second behavior for a type is a second provider, named directly, so the +type does not need a newtype such as the `Sum` and `Product` wrappers around `Int`. The +[Bypassing coherence](/docs/concepts/coherence) page shows both on the encoder example. ## What each approach costs -Type classes are valued for principled, inferred overloading and for global uniqueness, and their -costs, as their users state them, follow from the same rules. The one-instance-per-type limit forces -the newtype workaround, which "breaks down when the type is embedded in another type" +Type classes are valued for principled, inferred overloading and for global uniqueness. The costs +their users describe follow from the same rules. The one-instance-per-type limit requires the +newtype workaround, which "breaks down when the type is embedded in another type" ([Yang, 2014](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). The orphan rule shapes module structure ([Queensland FP Lab](https://qfpl.io/posts/orphans-and-fundeps/)). -Overlapping instances are subtle and incoherent instances are, by GHC's own account, indeterministic -([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). Haskell -has no easy local instance, because local instances reintroduce a coherence problem. In Agda and Lean -the absence of enforced coherence surfaces as the diamond problem and the work of keeping overlapping -instances definitionally equal ([Baanen, 2022](https://arxiv.org/pdf/2202.01629)). Some practitioners -argue the coherence bargain is wrong and prefer explicit dictionaries -([Chiusano, *The trouble with typeclasses*](https://pchiusano.github.io/2018-02-13/typeclasses.html)), -and a recent survey compares how Swift, Rust, Scala, and Haskell each draw the line +Overlapping instances are subtle, and incoherent instances, by GHC's own account, "may cause +unexpected results" ([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). +Haskell has no simple form of local instance, because local instances reintroduce a coherence +problem. + +In Agda and Lean, which do not enforce coherence, the costs appear as the diamond problem and the work +of keeping overlapping instances definitionally equal ([Baanen, 2022](https://arxiv.org/pdf/2202.01629)). +Some practitioners argue that the coherence bargain is the wrong one and prefer explicit dictionaries +([Chiusano, *The trouble with typeclasses*](https://pchiusano.github.io/2018-02-13/typeclasses.html)). +A recent survey compares where Swift, Rust, Scala, and Haskell each draw the line ([Racordon, Flesselle & Pham, 2025](https://arxiv.org/pdf/2502.20546)). -CGP pays with the wiring. There is no search, so the selection must be written down, once per context. -A component has to be declared with [`#[cgp_component]`](/docs/reference/macros/cgp_component) -before it can have providers, which adds declarations a plain trait does not need. The compile-time -work is real. And the raw diagnostics are trait-solver output over generated types: +CGP's main cost is the wiring. CGP does not search for an implementation, so each context must write +its selection down. A component must be declared with +[`#[cgp_component]`](/docs/reference/macros/cgp_component) before it can have providers, which adds +declarations that a plain trait does not need. Trait resolution over the wiring adds compile-time +work. The raw diagnostics are trait-solver output over generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the @@ -317,39 +331,43 @@ alternatives. ## Where coherent type classes are the better choice -When a program wants one canonical instance per type program-wide, one `Ord`, one `Show`, one -serialization, so that a `Set` cannot be corrupted and generic code needs no wiring, coherent type -classes are the right tool. Simulating that with CGP's per-context wiring reintroduces by hand the -uniqueness the compiler gives for free. The same holds in Rust: a trait with one implementation per -type is an ordinary trait, and CGP's [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) -page says so first. CGP's explicit selection is the better tool when a program needs several -interchangeable instances, per-context choice, instances for types and traits it does not own, or an -escape from the diamond and orphan problems. +Coherent type classes are the right tool when a program wants one canonical instance per type across +the whole program: one `Ord`, one `Show`, one serialization. They guarantee that a `Set` cannot be +corrupted by a second ordering, and generic code needs no wiring. Reproducing that uniqueness with +CGP's per-context wiring would mean maintaining by hand what the compiler already guarantees. The +same holds in Rust: a trait with one implementation per type is an ordinary trait, and the +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page starts from that case. + +CGP's explicit selection fits a program that needs several interchangeable instances, a different +choice per context, instances for types and traits it does not own, or a way around the diamond and +orphan problems. ## What to expect that differs -**CGP does not find the instance by type.** The provider is named in a table. This is the consequence -of the property a type-class reader will find most striking: because CGP does not resolve by type, it -is free of coherence, so it hosts the overlapping and orphan instances Haskell forbids or makes -fragile. +**CGP does not find the instance by type.** A context names the provider in its table. Because CGP +does not search for an instance, it does not depend on each type having a unique one, so it can hold +the overlapping and orphan implementations that Haskell forbids or treats as fragile. **Uniqueness is per context, not program-wide.** A type-class reader may expect that once a type has -an instance it is the instance everywhere. CGP promises agreement within a context and lets two -contexts differ, and that scoping lets two applications encode one type two ways without conflict. +an instance, it is the instance everywhere. CGP guarantees one choice within a context and lets two +contexts differ, so two applications can encode one type in two ways without conflict. **Selection can be keyed on the context rather than the type.** Haskell keys `Show Bool` on `Bool`, -so there is one of it. CGP's decisive shape moves the type being operated on into a parameter and -keys the choice on the context, and that change of key makes per-context selection more than a rewording of -per-type instances. CGP can also key on the type in the Haskell manner, and then it inherits the same -one-per-type limit. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page works out -the difference between the two arrangements. +so there is one such instance. The encoder example moves the type being operated on into a +parameter and keys the choice on the context. Changing the key makes per-context selection different +from per-type instances, rather than a new name for them. CGP can also key the choice on the type, as +the `Rectangle` example does, and then it has the same one-choice-per-type limit. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page works out the difference between the +two arrangements. -**The verification you gave up is replaced, not removed.** Where a type-class compiler proves an -instance exists, [`check_components!`](/docs/reference/macros/check_components) proves a context's -wiring is complete, at the wiring site, naming the missing dependency. +**Wiring checks take the place of instance resolution's checks.** A type-class compiler proves that +an instance exists at each use. [`check_components!`](/docs/reference/macros/check_components) +proves that a context's wiring is complete, and it names any missing dependency at the wiring site. ## Where to go next +These pages develop the constructs and the neighbouring comparisons: + - [Bypassing coherence](/docs/concepts/coherence): the coherence rules and the provider move, on the encoder example. - [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the two traits one diff --git a/example-code/tests/comparisons/reflection.rs b/example-code/tests/comparisons/reflection.rs index f17dad1a..6c654b76 100644 --- a/example-code/tests/comparisons/reflection.rs +++ b/example-code/tests/comparisons/reflection.rs @@ -22,7 +22,7 @@ pub mod a_types_shape_becomes_a_type { } } -/// ## Reflection-driven serialization in the trait system +/// ## Serializing through the trait system pub mod reflection_driven_serialization { use core::fmt::Debug; diff --git a/example-code/tests/comparisons/rust_language_proposals.rs b/example-code/tests/comparisons/rust_language_proposals.rs index 4e26e4c1..5dd3e61f 100644 --- a/example-code/tests/comparisons/rust_language_proposals.rs +++ b/example-code/tests/comparisons/rust_language_proposals.rs @@ -117,7 +117,7 @@ pub mod passing_an_impl_explicitly { } } -/// ## A capability is a context field; the `with` block is the context +/// ## A `with` clause becomes a context field pub mod a_capability_is_a_context_field { use cgp::prelude::*; diff --git a/example-code/tests/comparisons/type_classes.rs b/example-code/tests/comparisons/type_classes.rs index 8db3ebd5..f88a40d5 100644 --- a/example-code/tests/comparisons/type_classes.rs +++ b/example-code/tests/comparisons/type_classes.rs @@ -39,8 +39,8 @@ pub mod a_component_is_a_class { } } -/// ## Overlapping instances are the default, with no heuristic -/// ## Incoherent instances made deterministic and local +/// ## Overlapping providers need no specificity rule +/// ## Incoherent choices made explicit and local pub mod overlapping_instances { use core::fmt::Display; From d326baaf811dcb096df2f2281b281c6c6fb315dd Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Wed, 23 Sep 2026 07:20:04 +0000 Subject: [PATCH 092/516] Simplify four CGP comparison pages --- docs/comparisons/reflection.md | 114 +++++++++----------- docs/comparisons/row-polymorphism.md | 91 +++++++--------- docs/comparisons/rust-language-proposals.md | 94 ++++++++-------- docs/comparisons/type-classes.md | 97 ++++++++--------- 4 files changed, 172 insertions(+), 224 deletions(-) diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index 0ac84d9d..9512447f 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -6,19 +6,17 @@ description: "CGP's type-level shapes read against Bevy's runtime reflection, Zi # Reflection and compile-time introspection -CGP lets one generic routine work over any type's fields, as compile-time reflection does, but it -represents a type's structure as types rather than as data a routine inspects. It is a language -extension for Rust, with pluggable trait implementations at compile-time, implemented as a library -on stable Rust whose consumer traits are ordinary Rust traits; the [Introduction](/docs/) covers the -basics. For readers familiar with Bevy's `TypeInfo`, Zig's `@typeInfo`, Go or Java reflection, or -Rust's `TypeId::field` work, this page places CGP among runtime and compile-time reflection systems, -compares a field writer in each style, and states what the type-level encoding gains and costs. +CGP lets you write a generic operation over a type's fields by representing those fields as types. +It is a language extension built as a [stable Rust library](/docs/), with pluggable trait +implementations at compile time and ordinary Rust consumer traits. This page +compares CGP with Bevy's runtime reflection, Zig's `comptime`, and Rust's emerging compile-time +reflection. It uses a field writer to show what CGP can express and where reflection is more useful. ## In your terms -A **context** is the type a CGP method runs on, supplying its data through fields and its -implementations through wiring. On this page the context is an application type that chooses how -each field type is written, and the struct being reflected over is a value passed to it. +A **context** is the type a CGP method runs on. It supplies data through fields and chooses +implementations through wiring. Here an application context chooses how to write each field type; +the struct being written is passed to it as a value. The reflection vocabulary maps onto CGP by role: @@ -33,10 +31,9 @@ The reflection vocabulary maps onto CGP by role: ## The idea, briefly -Reflection lets code work over the shape of a type it was not written for. Serializers, DI -containers, ORMs, editors, and debuggers all walk an arbitrary type's fields by name and type, and -reflection makes that structure available for the program to read. Systems differ in when the -structure is read: +Reflection lets code inspect a type's shape without knowing that type in advance. Serializers, +editors, and debuggers use it to find fields by name and type. Systems differ in when they inspect +the shape: - **At runtime:** A type carries metadata that the program inspects while it runs, as in Java, Go, C#, Python, and Bevy. @@ -46,8 +43,7 @@ structure is read: result, as in Zig's `comptime`, D, C++26's static reflection ([P2996](https://isocpp.org/files/papers/P2996R13.html)), and Rust's nightly work. -CGP belongs with the compile-time systems, with one difference: the structure is a type rather than -a compile-time value. +CGP also processes shapes at compile time. Its shape is a type, rather than a compile-time value. ### Runtime reflection: Bevy @@ -84,12 +80,11 @@ fn jsonStringify(value: anytype, writer: anytype) !void { } ``` -The loop unrolls at compile time and `@field` resolves statically, so the function compiles to the -code a hand-written serializer would contain. `@Type` runs the introspection in reverse: it -constructs a type from a `std.builtin.Type` value, which CGP cannot do. +The loop unrolls and `@field` resolves at compile time. Zig's `@Type` also constructs a type from a +`std.builtin.Type` value; CGP cannot construct a new nominal type this way. -`comptime` costs nothing at runtime, but its checks happen late. A `comptime` routine is fully -type-checked only when it is applied to a concrete type, so an error surfaces at the use site, once +Compile-time introspection adds no runtime lookup, but its checks happen late. A `comptime` routine +is fully type-checked only when applied to a concrete type, so an error surfaces at the use site, once per instantiation, as with C++ templates. ### Compile-time reflection comes to Rust @@ -129,9 +124,8 @@ the tracking issue as they stood when this page was written, so check them befor ## How CGP expresses it -CGP encodes a type's structure as types and processes it with trait resolution. The trait system -therefore does the work that a reflection routine does when it inspects a descriptor. The example -below is a self-contained field writer modeled on +CGP encodes a type's structure as types and processes it with trait resolution. The example is a +self-contained field writer modeled on [`cgp-serde`](https://github.com/contextgeneric/cgp-serde)'s `SerializeFields` provider, which does the same over serde's `Serializer`. Its context is an [environmental context](/docs/reference/glossary#environmental-context): `App` stands for an @@ -159,10 +153,9 @@ pub struct Config { // } ``` -The list carries the same information as a descriptor, each field's name and type, but it is a -*type*. The Rust MVP's `FieldId` answers `type_id()` with an opaque `TypeId` value. CGP's -`Field` carries the field's actual type as a type parameter, so CGP can dispatch on it. -The [Extensible records](/docs/concepts/extensible-records) page develops the derive. +The list records each field's name and type. Unlike the Rust MVP's opaque `TypeId` value, +`Field` carries the field's actual type as a type parameter. CGP can therefore dispatch +on that type. The [Extensible records](/docs/concepts/extensible-records) page develops the derive. ### Serializing through the trait system @@ -262,22 +255,17 @@ They differ in what they turn a type's shape into and in what walks the result: | Rust MVP | Data provided by the compiler, without a derive | `const`-evaluated code, at compile time | | CGP | Type-level data generated by a derive | A shared trait recursion, monomorphized to direct code | -CGP's position differs from facet's and the MVP's in two ways. The field's type stays a type. -facet's `Shape` and the MVP's `FieldId::type_id()` carry it as an opaque descriptor, and a generic -function cannot be instantiated directly from a descriptor, so recursing into a field's own type -needs stored function pointers or is not yet expressible. CGP's `Field` carries -`FieldValue` as a real type parameter. `WriteFields` can therefore require -`Context: CanWriteValue` and recurse into a typed, statically checked writer for the -field's type. CGP also dispatches each field through the *context's* wiring, so the same type can be -written differently under different application contexts. facet, serde, and the MVP do not provide -this [per-context choice](/docs/concepts/coherence). - -The encoding also has costs. Unlike facet, CGP does not reduce -[monomorphization](/docs/reference/glossary#monomorphization): the recursion is instantiated per -field list, so it produces specialized code per type, as serde's output does. CGP removes the -duplicated authoring and adds configurability, but it does not reduce binary size. Unlike the Rust -MVP, CGP requires the `#[derive(HasFields)]` opt-in and cannot see a foreign type that does not -derive it. +CGP keeps each field's type available to the trait solver. facet's `Shape` and the MVP's +`FieldId::type_id()` describe it through an opaque value. CGP's `Field` instead +carries `FieldValue` as a type parameter, letting `WriteFields` require a statically checked writer +for that field type. The context's wiring can also select different writers for the same type in +different applications. facet, serde, and the MVP do not supply this +[per-context choice](/docs/concepts/coherence). + +CGP still [monomorphizes](/docs/reference/glossary#monomorphization) the recursion for each field +list. It avoids writing a serializer per type and adds per-context choice, but it does not provide +facet's shared runtime code. CGP also needs `#[derive(HasFields)]`; it cannot inspect a foreign type +that lacks the derive. ### Checked where the code is written, not where it is instantiated @@ -304,42 +292,36 @@ and chooses how each field is written. ## What each approach costs -Reflection is widely used because a framework written once works over every user type, and runtime -reflection also works on types the framework author never saw. Compile-time reflection is valued for -"the expressiveness of runtime reflection with the performance of hand-written code" +Reflection lets a framework inspect user types it was not written for. Compile-time reflection aims +for "the expressiveness of runtime reflection with the performance of hand-written code" ([*Compile-Time Reflection with @typeInfo*](https://hive.blog/hive-196387/@scipio/learn-zig-series-32-compile-time-reflection-with-typeinfo)). facet and the Rust effort aim to reduce the compile-time and binary-size cost of derive-generated code. -The costs users describe depend on when the reflection runs. Runtime reflection costs performance, -because Go's `encoding/json` re-inspects types on every call +The costs depend on when reflection runs. Runtime lookup and dynamic dispatch can add work compared +with direct field access ([*The Hidden Cost of Reflection in Go*](https://dev.to/devflex-pro/the-hidden-cost-of-reflection-in-go-why-your-code-is-slower-than-you-think-41ee)). -It weakens type safety, because a field named by a string tag fails at runtime +A field named by a string tag can fail at runtime ([Go reflection guide](https://medium.com/@mojimich2015/golang-reflection-the-guide-to-runtime-type-inspection-manipulation-and-best-practices-303087684576)). It also affects tooling, because renaming a field can silently break reflective access. Compile-time reflection addresses these costs but has its own: errors appear at instantiation, compilation does more work, and, as the Rust tracking issue itself asks, "monomorphization-time errors" can arise deep inside an instantiation. -Two of CGP's costs are specific to this comparison. CGP introspects only types that derive its -machinery, and only at compile time. It also does not reduce the specialized code per type, as facet -does. Its other costs are the ordinary ones: the wiring is code someone writes and maintains, and the -raw diagnostics are trait-solver output over generated types, which can be long for a deep field -recursion. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it -recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the -alternatives. +CGP requires derives and compile-time knowledge of the type, and it still generates specialized +code per type. Its wiring also needs maintenance. Deep field recursion can produce long trait +errors; [`cargo cgp check`](/docs/cargo-cgp/check) identifies the root cause for errors it +recognizes, but does not yet handle every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against simpler +approaches. ## Where reflection is the better choice -Runtime reflection is the right tool when a program must inspect types at runtime, which CGP cannot -do. Examples include deserializing into a type chosen from a configuration file, serializing a -heterogeneous registry of components, building an editor or debugger over live values, and -reflecting over a foreign type that cannot be made to derive anything. `bevy_reflect` and facet serve -these cases. A program that must construct a new nominal type from computed structure needs Zig's -`@Type` or C++26's splicers, since CGP's type-level lists cannot do it. CGP fits generic code over a -type's structure that costs nothing at runtime, is checked where it is written, recurses into field -types with full type information, and selects behavior and types as well as walking data. +Runtime reflection fits programs that inspect types while running: an editor over live values, a +heterogeneous component registry, or deserialization into a type chosen from configuration. Some +language reflection systems can also inspect foreign types without a CGP derive. Constructing a new +nominal type from a computed shape calls for a facility such as Zig's `@Type` or C++26's splicers. +CGP fits generic operations over known shapes when static field types and per-context behavior matter. CGP and Rust's emerging compile-time reflection complement each other more than they compete. The MVP produces reflection as *const values*, which libraries that reflect over values can consume diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index 6084edbd..bb4c07b8 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -6,18 +6,15 @@ description: "CGP's extensible records and variants read against PureScript rows # Row polymorphism, structural typing, and extensible data types -CGP lets code work over the fields and variants of Rust's nominal structs and enums, much as row -polymorphism lets code work over any record with the right fields. It does not add a row kind: -it derives a type-level view of each type's shape and matches names through the trait system. It is -a language extension for Rust, with pluggable trait implementations at compile-time, implemented as -a library on stable Rust whose consumer traits are ordinary Rust traits; the [Introduction](/docs/) -covers the basics. For readers familiar with PureScript's rows, OCaml's polymorphic variants, -TypeScript's structural checking, or the row-theory literature, this page maps row operations onto -CGP, shows where the analogy stops, and states where a row system is the better tool. +CGP gives Rust's nominal structs and enums some of the flexibility of row polymorphism. It derives +their shape as types and uses trait bounds to match fields and variants. CGP is a language extension +built as a [stable Rust library](/docs/), with pluggable trait implementations at compile time and +ordinary Rust consumer traits. This page compares CGP with PureScript rows, OCaml polymorphic variants, and +structural typing. It shows which row operations CGP supports and where a row system works better. ## In your terms -A **context** is the type a CGP method runs on, supplying its data through fields and its +A **context** is the type a CGP method runs on. It supplies data through fields and chooses implementations through wiring. Every context on this page is a **[value context](/docs/reference/glossary#value-context)**: the record being built or the enum being cast carries both the shape and the wiring, and each component targets `Self`. @@ -36,10 +33,9 @@ The row operations map onto CGP constructs as follows: ## The idea, briefly -Nominal type systems, including Rust's, require code to name the concrete type it works on. A -function that reads a `name` field must take a specific struct, and two structs with identical fields -but different names are incompatible. The features on this page let a type's structure, rather than -its name, decide which operations apply. +Rust's nominal types are distinct even when they have the same fields. Code that reads a `name` +field normally names a particular struct. Row polymorphism lets code depend on the field instead; +CGP offers selected forms of that flexibility within Rust's nominal type system. ### Structural versus nominal typing @@ -55,9 +51,8 @@ CGP works within that nominal system rather than replacing it. ### Row polymorphism in PureScript -Row polymorphism provides structural flexibility through a *row variable* rather than a subtype -relation. A function accepts any record that has at least the fields it names, and a type variable -carries the other fields through unchanged +Row polymorphism uses a *row variable* to describe the fields a function does not name. The function +accepts any record with its required fields, while the variable carries the remaining fields ([Wikipedia, *Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism)). In PureScript a *row* is "an unordered collection of named types", of kind `Row k`, and a record is a row wrapped by `Record` ([PureScript language reference](https://github.com/purescript/documentation/blob/master/language/Types.md)). @@ -88,10 +83,9 @@ polymorphic over an ordinary type variable, and the *lacks* and *has* predicates discharged by the machinery that resolves type-class instances, without a new kind ([Gaster & Jones](http://web.cecs.pdx.edu/~mpj/pubs/polyrec.html)). -CGP most closely resembles the second design. It has no row kind and no row variable, but it has -row *predicates*: a `HasField` bound is a has-predicate over a -context's fields, and the trait solver resolves it. Rémy's *presence polymorphism* adds a flag for -each label recording whether it is present, and CGP reproduces this with the markers shown below. +CGP resembles the predicate design. It has no row kind or row variable. Instead, a +`HasField` bound says that a context has a field, and Rust's trait +solver checks it. CGP also uses markers like Rémy's presence flags to track which fields are present. ### Extensible variants @@ -130,9 +124,8 @@ rows to effects ([Leijen, *Koka*](https://arxiv.org/pdf/1406.2061)), which the ## How CGP expresses it -CGP keeps Rust's nominal structs and enums, derives a type-level description of each type's shape, -and matches field and variant names through the trait system. The row predicates become trait -constraints that the trait solver resolves, as in the Gaster and Jones design. +CGP derives type-level shapes for Rust's nominal structs and enums. Trait bounds then express the +field and variant requirements that row predicates express in a row system. ### A struct is a closed row; `HasField` is row containment @@ -257,21 +250,20 @@ context can perform an operation. ## What each approach costs -Row polymorphism is valued because one function serves many record shapes, which "can greatly reduce -refactoring" ([Fowler, *Row Polymorphism without the Jargon*](https://jadon.io/blog/row-polymorphism/)), -and because rows support codec-free JSON decoding and type-safe bindings +Row polymorphism lets one function serve many record shapes. Users value the reduced refactoring +([Fowler, *Row Polymorphism without the Jargon*](https://jadon.io/blog/row-polymorphism/)) and uses +such as codec-free JSON decoding and type-safe bindings ([Nguyen](https://hgiasac.github.io/posts/2018-11-18-Record-Row-Type-and-Row-Polymorphism.html)). -Its users report costs in three areas. The first is error messages: row unification can produce -very large diagnostics, and one PureScript thread records outputs of around 152 KB +Row systems can make errors and domain models harder to understand. Row unification can produce very +large diagnostics; a PureScript discussion reports outputs around 152 KB ([PureScript Discourse](https://discourse.purescript.org/t/upcoming-changes-to-error-messages-for-large-records-rows/3696)). -The second is complexity. Extensible records are widely seen as a specialist tool, and one user who -modeled a domain with them later wished for separate functions per nominal type -([PureScript Discourse](https://discourse.purescript.org/t/when-to-use-extensible-types-when-modeling-a-domain/217)). -The third cost is specific to pure structural typing: a structurally valid call can be semantically -wrong, "like finding the `area` of a `Fish`" ([Fowler](https://jadon.io/blog/row-polymorphism/)). -OCaml's manual warns that polymorphic variants "result in a weaker type discipline" and recommends -core variants for simple programs ([OCaml manual](https://ocaml.org/manual/5.5/polyvariant.html)). +One user who modeled a domain with extensible records later preferred separate functions for nominal +types ([PureScript Discourse](https://discourse.purescript.org/t/when-to-use-extensible-types-when-modeling-a-domain/217)). +Structural compatibility can also admit a call that makes little sense for the domain +([Fowler](https://jadon.io/blog/row-polymorphism/)). OCaml's manual warns that polymorphic variants +"result in a weaker type discipline" and recommends core variants for simple programs +([OCaml manual](https://ocaml.org/manual/5.5/polyvariant.html)). Two languages have moved away from rows. PureScript replaced its row-typed effect monad because "getting the effect rows to line up was sometimes quite tricky" @@ -279,30 +271,27 @@ Two languages have moved away from rows. PureScript replaced its row-typed effec and Gleam removed row-typed records to become "less structural and more nominal in style" ([Gleam v0.4](https://gleam.run/news/gleam-v0.4-released/)). -CGP has the first two costs in its own form. A mis-wired or incomplete structural operation surfaces -as a long trait error over generated types, and CGP asks for derives, type-level tags, and wiring -where a row system infers the shape. [`check_components!`](/docs/reference/macros/check_components) -names the missing field or variant at the wiring site. [`cargo cgp check`](/docs/cargo-cgp/check) -leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not -yet reshape every class. Even so, the diagnostics are heavier than those of a nominal `match`. +CGP trades row inference for derives, type-level tags, and wiring. An incomplete operation can +produce a long trait error over generated types. +[`check_components!`](/docs/reference/macros/check_components) +checks wiring at its definition, and [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root +cause for errors it recognizes. Diagnostics can still be heavier than those of a nominal `match`. -CGP avoids the third cost for components. A provider applies only to a context whose wiring selects -it, so a shape-compatible context does not acquire a component's behavior without being wired for -it. A `#[cgp_fn]` function such as `full_name` is different: its single blanket implementation +CGP limits accidental structural matches for components. A provider applies only to a context whose +wiring selects it, so matching fields alone do not add that behavior. A `#[cgp_fn]` function such as +`full_name` is different: its single blanket implementation applies to any context with the named fields, as a row-polymorphic function does. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the alternatives. ## Where a row system is the better choice -A row system such as PureScript's is the better tool when a program wants concise anonymous records -with full inference and can accept the error-message cost. Emulating that style with CGP's machinery -would add declarations and wiring without a matching benefit. +A row system such as PureScript's fits programs that rely on concise anonymous records and full row +inference. CGP requires more declarations to express that style. -CGP fits a program that is already written in nominal Rust and wants structural access to fields and -variants at a few chosen points: a builder assembled from independent parts, a visitor over an open -set of variants, or a cast between related enums. There it provides the main benefit of row -polymorphism without a new kind system, and it adds complexity only where it is used. +CGP fits nominal Rust code that needs structural access at selected points: a builder assembled from +parts, a visitor over an open set of variants, or a cast between related enums. These operations use +trait bounds and derives without changing Rust's type system. ## What to expect that differs diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md index 4d53673a..086f5a6f 100644 --- a/docs/comparisons/rust-language-proposals.md +++ b/docs/comparisons/rust-language-proposals.md @@ -6,19 +6,16 @@ description: 'CGP read against specialization, named impls, dictionary passing, # Rust's own proposals -CGP provides, as a library, part of what several proposals to relax Rust's -[coherence](/docs/reference/glossary#coherence) rules would add to the language. It is a language -extension for Rust, with pluggable trait implementations at compile-time, implemented as a library -on stable Rust whose consumer traits are ordinary Rust traits; the [Introduction](/docs/) covers the -basics. For readers who follow *specialization*, the *dictionary-passing* account of traits, *named -or incoherent impls*, and *contexts and capabilities*, this page shows which part of each proposal -CGP provides, maps the constructs one by one, and states where CGP cannot follow the proposals. +CGP overlaps with Rust proposals for trait selection and values supplied by a caller's environment. +It is a language extension built as a [stable Rust library](/docs/), with pluggable trait +implementations at compile time and ordinary Rust consumer traits. This page compares CGP with +specialization, dictionary passing, named impls, and contexts and capabilities. It shows where the +designs meet and what CGP cannot express. ## In your terms -A **context** is the type a CGP method runs on, supplying its data through fields and its -implementations through wiring. In most CGP code it is a type you define to stand for an -application. +A **context** is the type a CGP method runs on. It supplies data through fields and chooses +implementations through wiring. Often it is a type defined to represent an application. The proposals' constructs map onto CGP as follows: @@ -33,7 +30,8 @@ The proposals' constructs map onto CGP as follows: ## The idea, briefly -Every proposal on this page relaxes one or both of the coherence rules in the Rust Reference. The +The proposals on this page explore changes to trait selection or how values reach generic code. +Rust's coherence rules set the starting point. The *[orphan rule](/docs/reference/glossary#orphan-rule)* says an `impl Trait for T0` is valid only if `Trait` is a local trait, or at least one of the types `T0..=Tn` is a local type and no uncovered type parameter appears before it. The *overlap rule* rejects two implementations that @@ -41,8 +39,8 @@ no uncovered type parameter appears before it. The *overlap rule* rejects two im ([Rust Reference](https://doc.rust-lang.org/reference/items/implementations.html); [RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). -Together the two rules guarantee that any trait lookup finds exactly one impl. That guarantee lets -generic code resolve `T: Hash` transitively and keeps a `HashMap` sound. The +Together the rules give each trait lookup one impl. Generic code can therefore use `T: Hash` +consistently, including inside a `HashMap`. The [type classes](./type-classes.md) page covers why coherence exists in the wider type-class tradition; this page takes it as given. @@ -168,8 +166,9 @@ imports decide which implementation it uses. ## How CGP expresses it -The correspondence can be stated construct by construct. The main difference is where bindings live. The proposals bind an impl at a call site or -within a scope, while CGP records every binding in one place: the context. +CGP records provider choices on a context. Named-impl designs can instead select an impl at a call +site, and capability designs can bind a value within a scope. The examples below show the practical +effect of that difference. ### A named impl is a provider @@ -237,12 +236,11 @@ delegate_components! { } ``` -CGP provides the proposal's incoherence with a different resolution point. Boxy and Cairo resolve at -the call site, explicitly or from what is in scope. CGP resolves at the context, so every call -through `ApiServer` uses the same choice. This also answers the `HashMap` concern: a context selects -one provider per component, so all code sharing a context uses one impl. The proposal gets the same -property by moving `Hash` onto the type definition. The [type classes](./type-classes.md) page -develops this comparison with Haskell's incoherent instances. +CGP makes the choice on the context, so every call through `ApiServer` uses the same provider. +Boxy's design selects explicitly at a call, while Cairo infers from the impls in scope. A context +selects one provider per component, keeping code that shares that context consistent. The proposal +addresses the `HashMap` concern by putting `Hash` on the type definition. The +[type classes](./type-classes.md) page develops the comparison with Haskell's incoherent instances. ### Passing an impl explicitly is a higher-order provider @@ -326,42 +324,34 @@ instantiation order: the context is one stable root from which all of them are r ## What each approach costs -The proposals are language changes that have not shipped, and their authors name their costs. -Specialization has an accepted RFC, a soundness hole open since 2016, and no announced path to -stabilization ([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). The -named-impl and dictionary-passing designs are blog posts and design sketches. Their authors list the -open problems: syntax, ergonomics, migration of the existing ecosystem, and the loss of the -guarantees that coherence provides automatically +These proposals have different levels of maturity and different open questions. Specialization has +an accepted RFC but remains unstable because of a soundness problem +([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). Named impls and dictionary +passing remain design sketches whose authors discuss syntax, ergonomics, migration, and coherence ([Boxy](https://www.boxyuwu.blog/posts/an-incoherent-rust/); [Nadrieril](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). Contexts and -capabilities is a research direction from 2021, with open questions about thread boundaries and -scope ([Mandry](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). Cairo's -resolution from scope means that a caller must import every impl a generic impl needs, directly or -indirectly, and two call sites in one project can resolve the same type differently. - -CGP's costs are the ordinary ones. A provider trait must be defined through -[`#[cgp_component]`](/docs/reference/macros/cgp_component), so CGP cannot retrofit an existing -foreign trait such as `serde::Serialize` without a parallel component, while a language change would -apply to every trait. The wiring is code that someone writes and reads, where a language feature -would infer it. Trait resolution over the wiring adds compile-time work. The raw diagnostics are -trait-solver output over generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the -root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape -every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs -against the alternatives in full. +capabilities has open questions about thread boundaries and scope +([Mandry](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). Cairo's +scope-based resolution requires the caller to import the needed impls; two call sites can then +resolve the same type differently. + +CGP requires a component definition and explicit wiring. A provider trait created by +[`#[cgp_component]`](/docs/reference/macros/cgp_component) cannot retrofit a foreign trait such as +`serde::Serialize` without a parallel component. Wiring adds compile-time work and can produce long +trait errors over generated types. [`cargo cgp check`](/docs/cargo-cgp/check) identifies the root +cause for errors it recognizes. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page +weighs these costs against simpler approaches. ## Where a proposal, or a smaller tool, is the better choice -A smaller tool fits a program that needs only a specialized fast path for one type under a blanket -impl. `min_specialization` on nightly, or a manual dispatch technique on stable, handles that case, -while CGP would require wiring that specialization infers. Coherence as it stands fits a program -that needs one globally consistent implementation, such as the `Ord` that a map's keys rely on; -CGP's per-context choice does not improve that arrangement. A program that can wait for a language -feature may get one that infers the impl from scope or nests bindings dynamically, which would -express these patterns with less ceremony than a library can. - -CGP fits a program that needs several equally valid impls chosen per application, impls for types -the program does not own, or environment values that reach deep code without extra parameters. It -provides these on stable Rust today, and its explicit wiring is the cost. +A smaller tool fits a single specialized fast path under a blanket impl. `min_specialization` on +nightly, or manual dispatch on stable Rust, handles that case without CGP wiring. Ordinary coherence +fits a program that needs one global implementation, such as the `Ord` used by map keys. A future +language feature may express scoped or inferred choices with less code than a library can. + +CGP fits programs that need several valid implementations chosen per application, providers for +foreign types, or environment values available in deep code. It offers these choices on stable Rust +through explicit wiring. ## What to expect that differs diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md index f19eadc5..d4cf616f 100644 --- a/docs/comparisons/type-classes.md +++ b/docs/comparisons/type-classes.md @@ -6,20 +6,17 @@ description: 'CGP read against Haskell, Agda, and Lean type classes, coherence, # Type classes -CGP lets one Rust trait have several named implementations and lets each context choose among them, -which relaxes the one-instance-per-type limit that type-class coherence imposes. It is a language -extension for Rust, with pluggable trait implementations at compile-time, implemented as a library -on stable Rust whose consumer traits are ordinary Rust traits; the [Introduction](/docs/) covers the -basics. Rust traits are Rust's type classes, so CGP works inside a type-class system and changes only -how an implementation is chosen. For readers who know type classes from Haskell, Agda, or Lean, this -page maps classes and instances onto CGP, compares CGP with overlapping and incoherent instances, -and states where coherent type classes remain the better tool. +CGP lets a context choose among named implementations of a Rust trait. It is a language extension +built as a [stable Rust library](/docs/), with pluggable trait implementations at compile time and +ordinary Rust consumer traits. This page maps type classes and instances from Haskell, Agda, and Lean onto +CGP. It explains how explicit selection compares with coherent, overlapping, and incoherent +instances, and when ordinary traits are enough. ## In your terms -A **context** is the type a CGP method runs on, supplying its data through fields and its -implementations through wiring. In the dictionary-passing account, the context is the dictionary -that carries every other dictionary. +A **context** is the type a CGP method runs on. It supplies data through fields and chooses +implementations through wiring. In dictionary-passing terms, its wiring records which dictionaries +to use. The type-class vocabulary maps onto CGP as follows: @@ -34,10 +31,10 @@ The type-class vocabulary maps onto CGP as follows: ## The idea, briefly -Type classes give overloading a principled basis. A class declares an interface, an instance -implements it for a type, and a constrained function works for every type with an instance, with the -compiler finding the instance. Wadler and Blott introduced them to "make ad-hoc polymorphism less ad -hoc" ([Wadler & Blott, 1989](https://dl.acm.org/doi/10.1145/75277.75283)): +Type classes let a compiler choose an implementation for a type. A class declares an interface, an +instance implements it for a type, and a constrained function works for every type with an instance. +Wadler and Blott introduced them to "make ad-hoc polymorphism less ad hoc" +([Wadler & Blott, 1989](https://dl.acm.org/doi/10.1145/75277.75283)): ```haskell class Show a where @@ -51,18 +48,17 @@ describe :: Show a => a -> String describe x = "value: " ++ show x ``` -Underneath, the class is a *dictionary*, a record of the class methods. An instance is a dictionary -value, and `describe` elaborates to a function that takes the dictionary as an extra hidden argument. -Dictionary passing is the implementation model behind every system on this page, including CGP. It is -the same idea as the evidence passing on the [algebraic effects](./algebraic-effects.md) page and the -qualified-type constraints on the [row polymorphism](./row-polymorphism.md) page. +Dictionary passing explains how a class constraint supplies behavior. The class becomes a record of +methods, an instance supplies that record, and `describe` receives it as a hidden argument. CGP +uses the same idea, with the context carrying the choices. The [algebraic effects](./algebraic-effects.md) +and [row polymorphism](./row-polymorphism.md) pages compare other forms of passed evidence. -### Coherence: one instance per type, globally +### Coherence and canonical instances -*Coherence* makes automatic resolution safe. For a given class and type there is one instance, and -every resolution anywhere in the program finds the same one. The property divides into -*confluence*, *coherence*, and *global uniqueness*. GHC guarantees the first two within a compilation -and does not enforce the third across a whole program +*Coherence* makes automatic resolution predictable: uses of a class constraint should agree on the +instance they select. That goal has distinct parts: *confluence*, *coherence*, and +*global uniqueness*. GHC guarantees the first two within a compilation but does not enforce global +uniqueness across a whole program ([Yang, *Type classes: confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). The standard example of the benefit is a `Set` of an ordered element type. With one `Ord` for that type, values inserted under one ordering can never be read back under another. @@ -150,10 +146,9 @@ resolution layer added: **classes as signatures, and instances as structures and instance modules are designated *canonical* within a scope, so the compiler can resolve them implicitly ([*Modular Type Classes*](https://people.mpi-sws.org/~dreyer/papers/mtc/main-long.pdf)). -The paper identifies a tension that every design on this page must resolve: **canonicity conflicts -with modularity.** A canonical instance makes implicit resolution safe, but canonicity is not a -modular property, since two modules can each supply a different instance. The designs fall along a -range: +The paper identifies a tension between **canonicity and modularity**. A canonical instance makes +implicit resolution predictable, but two modules can each supply a different instance. The designs +make different choices: - **Haskell:** Fully implicit resolution, global coherence, and one instance per type. - **Modular type classes, OCaml's modular implicits, Agda instance arguments, and Scala implicits:** @@ -164,10 +159,9 @@ The [ML modules](./ml-modules.md) page develops the module side. ## How CGP expresses it -CGP keeps Rust's type classes and replaces the automatic choice of an implementation with explicit -selection per context. It splits each class into a consumer trait that callers use and a provider -trait that implementations target. The consumer trait is an ordinary Rust trait. The provider trait -and the wiring let implementations be named and chosen. +CGP makes implementation choice explicit per context. A component has a consumer trait for callers +and a provider trait for implementations. The consumer trait is an ordinary Rust trait; providers and +wiring make several implementations selectable. ### A component is a class; a provider is a first-class instance @@ -180,10 +174,9 @@ pub trait CanCalculateArea { } ``` -`CanCalculateArea` is the class interface, as `class Show a` is. The two systems differ in what an -instance can be. A Haskell instance is anonymous and canonical: there is one `Show Bool`, and the -compiler chooses it. A CGP provider is a named marker type that carries a provider-trait impl, a -*first-class dictionary* that code can name and choose among: +`CanCalculateArea` is the class interface, as `class Show a` is. A Haskell instance is anonymous, +and the compiler chooses it. A CGP provider is a named marker type with a provider-trait impl, so a +context can select it explicitly: ```rust #[cgp_impl(new RectangleArea)] @@ -319,28 +312,22 @@ Some practitioners argue that the coherence bargain is the wrong one and prefer A recent survey compares where Swift, Rust, Scala, and Haskell each draw the line ([Racordon, Flesselle & Pham, 2025](https://arxiv.org/pdf/2502.20546)). -CGP's main cost is the wiring. CGP does not search for an implementation, so each context must write -its selection down. A component must be declared with -[`#[cgp_component]`](/docs/reference/macros/cgp_component) before it can have providers, which adds -declarations that a plain trait does not need. Trait resolution over the wiring adds compile-time -work. The raw diagnostics are trait-solver output over generated types: -[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the -alternatives. +CGP requires explicit wiring because it does not search for an implementation. Providers also need +a component declared with [`#[cgp_component]`](/docs/reference/macros/cgp_component), adding code +beyond a plain trait. Trait resolution adds compile-time work and can produce long errors over +generated types. [`cargo cgp check`](/docs/cargo-cgp/check) identifies the root cause for errors it +recognizes. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page compares these +costs with simpler approaches. ## Where coherent type classes are the better choice -Coherent type classes are the right tool when a program wants one canonical instance per type across -the whole program: one `Ord`, one `Show`, one serialization. They guarantee that a `Set` cannot be -corrupted by a second ordering, and generic code needs no wiring. Reproducing that uniqueness with -CGP's per-context wiring would mean maintaining by hand what the compiler already guarantees. The -same holds in Rust: a trait with one implementation per type is an ordinary trait, and the -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page starts from that case. +Coherent type classes fit programs that need one canonical instance per type, such as the `Ord` used +by a `Set`. The compiler keeps generic code consistent without wiring. In Rust, an ordinary trait +already provides that guarantee. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) +page starts from this simpler case. -CGP's explicit selection fits a program that needs several interchangeable instances, a different -choice per context, instances for types and traits it does not own, or a way around the diamond and -orphan problems. +CGP fits programs that need several interchangeable implementations or a different choice per +context. Providers can also cover types the program does not own without orphan-rule conflicts. ## What to expect that differs From 46c1ae1e4faf981ebdc61b8db223cd8686224c11 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Wed, 23 Sep 2026 15:16:09 +0000 Subject: [PATCH 093/516] Clarify and simplify language comparison pages --- docs/comparisons/reflection.md | 238 ++++++++---------- docs/comparisons/row-polymorphism.md | 236 +++++++++--------- docs/comparisons/rust-language-proposals.md | 258 +++++++++----------- docs/comparisons/type-classes.md | 253 +++++++++---------- 4 files changed, 462 insertions(+), 523 deletions(-) diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index 9512447f..cb3fee9c 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -1,16 +1,16 @@ --- sidebar_label: 'Reflection' sidebar_position: 10 -description: "CGP's type-level shapes read against Bevy's runtime reflection, Zig's comptime, and Rust's compile-time reflection work." +description: "How CGP compares with runtime reflection, Zig comptime, and Rust compile-time reflection." --- # Reflection and compile-time introspection -CGP lets you write a generic operation over a type's fields by representing those fields as types. -It is a language extension built as a [stable Rust library](/docs/), with pluggable trait -implementations at compile time and ordinary Rust consumer traits. This page -compares CGP with Bevy's runtime reflection, Zig's `comptime`, and Rust's emerging compile-time -reflection. It uses a field writer to show what CGP can express and where reflection is more useful. +CGP represents a struct's fields as types, letting generic code read them and select behavior at +compile time. It is a language extension built as a [stable Rust library](/docs/) , with pluggable +implementations behind ordinary Rust traits. This page compares that approach with Bevy's runtime +reflection, Zig's `comptime` , and Rust's experimental reflection API through a generic field +writer. ## In your terms @@ -27,7 +27,7 @@ The reflection vocabulary maps onto CGP by role: | A field's type, as an opaque `TypeId` or `Shape` | The field's type, carried as a real type parameter | | `inline for` over `@typeInfo`, or a walk over a descriptor | A trait recursion over the `Cons`/`Nil` field list | | A registry mapping types to behavior | The **wiring table**, written with `delegate_components!` | -| An access that fails at runtime | A `check_components!` failure at compile time | +| Checking that an operation supports a field type | Trait bounds, verified when used or asserted with `check_components!` | ## The idea, briefly @@ -47,25 +47,21 @@ CGP also processes shapes at compile time. Its shape is a type, rather than a co ### Runtime reflection: Bevy -`bevy_reflect` is a widely used runtime-reflection system in Rust. A type opts in with -`#[derive(Reflect)]`. A value can then be handled as a `Box`, accessed by string field -name through the `Struct` trait, and downcast to its concrete type at runtime +Bevy lets code inspect values through a common runtime interface. A type opts in with +`#[derive(Reflect)]` ; code can then access its fields by name or downcast it to a concrete type ([`bevy_reflect` documentation](https://docs.rs/bevy_reflect/latest/bevy_reflect/)). `TypeInfo` -describes a type's shape without an instance, and a runtime `TypeRegistry` maps types to their -`TypeInfo` and to associated behavior. With these, Bevy can serialize any registered component into -a scene or drive an editor over types it was not specialized for -([`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html)). Every -reflective access goes through dynamic dispatch, a downcast, or a registry lookup, so a mismatch -surfaces at runtime as a `None` or a panic. +describes the shape, and a +[`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html) associates types +with metadata and behavior. These facilities support scene serialization and editors that work +across registered types. A lookup for a missing field or an incorrect downcast can fail at runtime. ### Compile-time metaprogramming: Zig's `comptime` -Zig's `comptime` is the usual reference design for compile-time reflection. Types are ordinary -compile-time values: `@typeInfo(T)` decomposes a type into a `std.builtin.Type` describing its -shape, `inline for` unrolls a loop over a compile-time collection, and `@field` accesses a field by a -name known at compile time ([Zig language reference](https://ziglang.org/documentation/master/#typeInfo)). -From Zig 0.14 the type tags are lowercase, so a struct is matched as `.@"struct"`. This function -writes any struct as a JSON-like object and compiles with Zig 0.16: +Zig makes types available as compile-time values. `@typeInfo(T)` decomposes a type into a +`std.builtin.Type` describing its shape, `inline for` unrolls a loop over a compile-time collection, +and `@field` accesses a field by a name known at compile time ([Zig language +reference](https://ziglang.org/documentation/master/#typeInfo)). This Zig 0.16 example writes a +struct as a JSON-like object: ```zig const std = @import("std"); @@ -80,25 +76,22 @@ fn jsonStringify(value: anytype, writer: anytype) !void { } ``` -The loop unrolls and `@field` resolves at compile time. Zig's `@Type` also constructs a type from a -`std.builtin.Type` value; CGP cannot construct a new nominal type this way. - -Compile-time introspection adds no runtime lookup, but its checks happen late. A `comptime` routine -is fully type-checked only when applied to a concrete type, so an error surfaces at the use site, once -per instantiation, as with C++ templates. +Zig resolves the loop and field accesses at compile time, without runtime lookup. A generic +`comptime` routine is checked for each concrete instantiation, so type-dependent errors appear when +it is used. Zig can also construct a new nominal type from a `std.builtin.Type` value through +`@Type` ; CGP does not offer that operation. ### Compile-time reflection comes to Rust -Rust programs have used derive macros that generate specialized code per type in place of -reflection. The [facet](https://fasterthanli.me/articles/introducing-facet-reflection-for-rust) -crate responds to the cost of that approach. serde's derives monomorphize the serializer anew for -every type, so facet's derive generates *data* instead: a `const SHAPE` descriptor that shared -runtime reflection code walks. +Rust libraries can generate either code or metadata from a type declaration. Serde's derives +generate serialization implementations that are specialized for each type and serializer. +[facet](https://fasterthanli.me/articles/introducing-facet-reflection-for-rust) generates a +`const SHAPE` descriptor that shared runtime code can inspect, aiming to reduce that duplication. -The nightly compiler work goes further, and it is unstable and subject to change. Under -`#![feature(type_info)]`, `TypeId::of::()` gains query methods that reach a type's variants and -fields in source order. Each `FieldId` answers `name()`, `type_id()`, and `offset()`. The source's -own doc tests read: +Rust's experimental `type_info` feature supplies metadata directly from the compiler. Under +`#![feature(type_info)]` , `TypeId::of::()` gains query methods that reach a type's variants and +fields in source order. Each `FieldId` answers `name()` , `type_id()` , and `offset()` . The +source's own doc tests read: ```rust #![feature(type_info)] @@ -111,31 +104,26 @@ assert_eq!(const { TypeId::of::().field(0, 0).name() }, "x"); assert_eq!(const { TypeId::of::().field(0, 0).type_id() }, TypeId::of::()); ``` -These queries can be called only at compile time, and that restriction shapes the whole design. -Each query carries a `#[rustc_comptime]` marker, because supporting runtime calls would require -"some global table somewhere that maps all `TypeId`s to their repr" -([Rust project goal, *Reflection and comptime*](https://rust-lang.github.io/rust-project-goals/2026/reflection-and-comptime.html)). -The goal names Zig as its model but does not pursue full `comptime` for now, estimating that -architectural change as more than five years away. The -[tracking issue](https://github.com/rust-lang/rust/issues/146922) lists every stabilization step as -open. The plan runs from 2026 to 2028, with the aim that crates such as Bevy can work with arbitrary -types instead of requiring a derive. The details in this subsection come from the compiler source and -the tracking issue as they stood when this page was written, so check them before relying on one. +The API shown here restricts these queries to compile time. Its `#[rustc_comptime]` marker avoids +requiring a runtime table of type descriptions. The +[Reflection and comptime project goal](https://rust-lang.github.io/rust-project-goals/2026/reflection-and-comptime.html) +aims to let libraries such as Bevy inspect types without requiring derives, while leaving full +Zig-style `comptime` outside its immediate scope. The feature remains experimental; consult the +[tracking issue](https://github.com/rust-lang/rust/issues/146922) before relying on its API. ## How CGP expresses it -CGP encodes a type's structure as types and processes it with trait resolution. The example is a -self-contained field writer modeled on -[`cgp-serde`](https://github.com/contextgeneric/cgp-serde)'s `SerializeFields` provider, which does -the same over serde's `Serializer`. Its context is an -[environmental context](/docs/reference/glossary#environmental-context): `App` stands for an +CGP encodes a type's structure as types and processes it with trait resolution. The example +fragments form a field writer modeled on [`cgp-serde`](https://github.com/contextgeneric/cgp-serde) +'s `SerializeFields` provider, which does the same over serde's `Serializer` . Its context is an +[environmental context](/docs/reference/glossary#environmental-context) : `App` stands for an application and chooses how each field type is written. The written `Value` is a type parameter, so -the component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component). +the component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component) . -### A type's shape becomes a type, not a descriptor +### Representing a struct as a field list {#a-types-shape-becomes-a-type-not-a-descriptor} `#[derive(HasFields)]` represents a struct's structure as a type-level list. The list plays the role -of the `TypeInfo`, `Shape`, and `FieldId` descriptors above: +of the `TypeInfo` , `Shape` , and `FieldId` descriptors above: ```rust #[derive(HasFields)] @@ -157,10 +145,10 @@ The list records each field's name and type. Unlike the Rust MVP's opaque `TypeI `Field` carries the field's actual type as a type parameter. CGP can therefore dispatch on that type. The [Extensible records](/docs/concepts/extensible-records) page develops the derive. -### Serializing through the trait system +### Writing fields through trait recursion {#serializing-through-the-trait-system} -One generic writer works over any `HasFields` type, as the Zig `jsonStringify` above works over any -struct. It delegates to a trait that recurses over the field list: +The `WriteFields` provider writes any type whose field list implements `FieldsWriter` . That bound +requires readable fields and a writer for each field type: ```rust #[cgp_component(ValueWriter)] @@ -180,7 +168,7 @@ where } ``` -The `FieldsWriter` trait takes the place of `inline for`. It recurses over the +The `FieldsWriter` trait takes the place of `inline for` . It recurses over the [`Cons`/`Nil`](/docs/reference/types/cons) list, with one impl for a non-empty list and a base case for the empty one: @@ -237,20 +225,20 @@ delegate_components! { App.write_value(&config); // {"host": "localhost", "port": 8080} ``` -The struct also derives `HasField` so the recursion can read each field, and `WriteWithDebug` -formats a value with `Debug`. `cgp-serde`'s +To complete these fragments, `Config` also needs `#[derive(HasField)]` , `App` needs a declaration, +and `config` needs a value. The `WriteWithDebug` provider formats a value with `Debug` ; this +illustrates traversal and dispatch rather than a complete JSON serializer. `cgp-serde` 's [`SerializeFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs) -performs the same recursion over a `serde::Serializer`. Its deserialization counterpart reads a -field name as a runtime string and compares it with each field's compile-time `Tag::VALUE`. +performs the same recursion over a `serde::Serializer` . Its deserialization counterpart reads a +field name as a runtime string and compares it with each field's compile-time `Tag::VALUE` . ### Against facet and the reflection MVP -serde, facet, the Rust MVP, and CGP all let serialization be written once rather than per type. -They differ in what they turn a type's shape into and in what walks the result: +These approaches differ in how they represent and process a type's structure: | Approach | What the type's shape becomes | What processes it | | --- | --- | --- | -| serde | Code: a separate generated impl per struct | Nothing; the generated impl is the serializer | +| serde | A generated serialization impl per struct | The impl calls a chosen serializer | | facet | Data: a `const SHAPE` generated by a derive | A shared routine, at runtime | | Rust MVP | Data provided by the compiler, without a derive | `const`-evaluated code, at compile time | | CGP | Type-level data generated by a derive | A shared trait recursion, monomorphized to direct code | @@ -259,60 +247,54 @@ CGP keeps each field's type available to the trait solver. facet's `Shape` and t `FieldId::type_id()` describe it through an opaque value. CGP's `Field` instead carries `FieldValue` as a type parameter, letting `WriteFields` require a statically checked writer for that field type. The context's wiring can also select different writers for the same type in -different applications. facet, serde, and the MVP do not supply this -[per-context choice](/docs/concepts/coherence). +different applications. That [per-context choice](/docs/concepts/coherence) comes from CGP wiring; +structural metadata alone does not provide it. CGP still [monomorphizes](/docs/reference/glossary#monomorphization) the recursion for each field list. It avoids writing a serializer per type and adds per-context choice, but it does not provide -facet's shared runtime code. CGP also needs `#[derive(HasFields)]`; it cannot inspect a foreign type -that lacks the derive. +facet's shared runtime code. CGP also requires a `HasFields` implementation, usually supplied by a +derive; it cannot inspect an arbitrary foreign type without that implementation. + +### Checking generic code and concrete wiring {#checked-where-the-code-is-written-not-where-it-is-instantiated} -### Checked where the code is written, not where it is instantiated +Rust checks CGP's generic implementations against their declared trait bounds. For example, it +checks `FieldsWriter` without knowing which concrete struct it will process. Zig's `comptime` +routines are checked at instantiation, and Rust's reflection experiment can also produce errors +during evaluation for a concrete type. Rust still checks a `const fn` 's body against its declared +types and bounds. -Zig's `comptime` and the MVP's `const fn` reflection are checked at instantiation: a routine is fully -checked only when it is applied to a concrete type, so an error surfaces at the use site. CGP's -generic code is checked where it is defined. The compiler checks the `FieldsWriter` impl once against -the bounds in its `where` clause, as it checks any generic Rust impl. Wiring is -[lazy](/docs/concepts/check-traits), so [`check_components!`](/docs/reference/macros/check_components) -verifies that a context supplies everything its wiring transitively needs and reports a missing -dependency at the wiring site. Trait bounds give this modular checking, and templates do not. The -[type classes](./type-classes.md) page compares CGP with the type-class systems that Rust's traits -come from. +CGP checks concrete dependencies when an operation is used or explicitly asserted. Wiring is +[lazy](/docs/concepts/check-traits) , so a delegation entry alone does not prove that its provider +can run. [`check_components!`](/docs/reference/macros/check_components) forces that check for the +listed components and parameters, reporting missing dependencies beside the wiring. The +[type classes](./type-classes.md) page explains the trait-system connection. ### Selecting behavior and types through the same wiring -CGP uses the same type-level mechanism for two jobs that a structural reflection facility does not -handle directly. Frameworks do select behavior through reflection, Spring through annotations and -Bevy through `TypeData` in its registry, but they do so at runtime, through a registry built on top -of the introspection. CGP selects behavior at compile time through the context's wiring, which trait -resolution processes together with the structure. The [`#[cgp_type]`](/docs/reference/macros/cgp_type) -machinery also lets a context fix an abstract *type* through the same wiring. The -`Context: CanWriteValue` bound above shows the combination: one mechanism walks the shape -and chooses how each field is written. +CGP combines structural access with implementation selection. The +`Context: CanWriteValue` bound lets the same traversal use different field writers in +different contexts. [`#[cgp_type]`](/docs/reference/macros/cgp_type) also lets a context select an +abstract type through wiring. Reflection frameworks can associate behavior with metadata too; Bevy, +for example, stores `TypeData` in its runtime registry. CGP resolves its choices through traits at +compile time. ## What each approach costs -Reflection lets a framework inspect user types it was not written for. Compile-time reflection aims -for "the expressiveness of runtime reflection with the performance of hand-written code" -([*Compile-Time Reflection with @typeInfo*](https://hive.blog/hive-196387/@scipio/learn-zig-series-32-compile-time-reflection-with-typeinfo)). -facet and the Rust effort aim to reduce the compile-time and binary-size cost of derive-generated -code. - -The costs depend on when reflection runs. Runtime lookup and dynamic dispatch can add work compared -with direct field access -([*The Hidden Cost of Reflection in Go*](https://dev.to/devflex-pro/the-hidden-cost-of-reflection-in-go-why-your-code-is-slower-than-you-think-41ee)). -A field named by a string tag can fail at runtime -([Go reflection guide](https://medium.com/@mojimich2015/golang-reflection-the-guide-to-runtime-type-inspection-manipulation-and-best-practices-303087684576)). -It also affects tooling, because renaming a field can silently break reflective access. Compile-time -reflection addresses these costs but has its own: errors appear at instantiation, compilation does -more work, and, as the Rust tracking issue itself asks, "monomorphization-time errors" can arise deep -inside an instantiation. - -CGP requires derives and compile-time knowledge of the type, and it still generates specialized -code per type. Its wiring also needs maintenance. Deep field recursion can produce long trait -errors; [`cargo cgp check`](/docs/cargo-cgp/check) identifies the root cause for errors it -recognizes, but does not yet handle every class. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against simpler +Reflection reduces the need to write inspection code for each user type. Runtime descriptors can +also support shared code, as facet does, while compile-time introspection can generate direct +accesses. Neither approach guarantees a particular compile time or binary size. + +Runtime reflection moves some checks into execution. A field lookup by string can fail after a +rename, and dynamic dispatch or registry lookup can add runtime work. Compile-time reflection moves +those operations into compilation, but type-dependent failures may surface only for a concrete +instantiation. Rust's [tracking issue](https://github.com/rust-lang/rust/issues/146922) explicitly +raises this concern. + +CGP requires exposed field shapes, explicit wiring, and specialized code for each field list. +Learning the type-level representation and tracing recursive trait errors are additional costs. +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) compares these costs with simpler approaches. ## Where reflection is the better choice @@ -321,33 +303,27 @@ Runtime reflection fits programs that inspect types while running: an editor ove heterogeneous component registry, or deserialization into a type chosen from configuration. Some language reflection systems can also inspect foreign types without a CGP derive. Constructing a new nominal type from a computed shape calls for a facility such as Zig's `@Type` or C++26's splicers. -CGP fits generic operations over known shapes when static field types and per-context behavior matter. +CGP fits generic operations over known shapes when static field types and per-context behavior +matter. CGP and Rust's emerging compile-time reflection complement each other more than they compete. The MVP produces reflection as *const values*, which libraries that reflect over values can consume directly. CGP consumes reflection as *types*, which the MVP does not supply. For CGP to drop its -derive, the compiler would need to expose a type's shape as types. Until then, CGP's derive stands in -for that compiler-provided view. +derive, the compiler would need to expose a type's shape as types. Until then, CGP's derive stands +in for that compiler-provided view. ## What to expect that differs -**CGP has no reflection API.** It has no `TypeInfo` value to hold, no field list to iterate -imperatively, and no `TypeId::of::()` to call. The structure is a type that trait impls dispatch -on, so reflecting over it means writing a recursive impl. - -**A field's type is a type, not a `TypeId`.** This lets CGP recurse into a typed, checked writer for -each field, which the MVP's `TypeId`-based API cannot yet do. - -**Shapes are opt-in.** A type exposes its structure only by deriving `HasFields` or `CgpData`, so CGP -cannot see the fields of a foreign type without the derive. - -**CGP cannot synthesize types.** `Product!` and `Sum!` correspond to the result of `@typeInfo`, and -trait recursion corresponds to `inline for`, but CGP has no counterpart to `@Type` for constructing a -new nominal type. +CGP's structural interface differs from a reflection API in several ways: -**CGP is not a reflection system.** It encodes a type's structure as types, resolves operations -over it with the trait system, checks generic code where it is defined, and leaves no reflection -metadata in the compiled program. +- **Shapes are types.** A recursive trait implementation processes a field list; there is no + descriptor value to iterate over imperatively. +- **Field types remain available.** A `Field` carries `Value` as a type parameter, so + trait bounds can require an operation for that exact type. +- **Shapes must be exposed.** Derives such as `HasFields` and `CgpData` provide the required traits. + CGP cannot inspect an arbitrary foreign type that lacks those implementations. +- **Nominal types must be declared.** CGP can compose products and sums, but it cannot generate a + new nominal struct or enum from a computed shape as Zig's `@Type` can. ## Where to go next @@ -364,9 +340,9 @@ These pages develop the constructs and the neighbouring comparisons: ## Sources -The Zig snippet was compiled with Zig 0.16; the Rust snippet is the nightly source's own doc test and -is unstable. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` -assertion on the wired context. +The Zig snippet was compiled with Zig 0.16; the Rust snippet is the nightly source's own doc test +and is unstable. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a +`check_components!` assertion on the wired context. - [`bevy_reflect` documentation](https://docs.rs/bevy_reflect/latest/bevy_reflect/), [`TypeInfo`](https://docs.rs/bevy/latest/bevy/reflect/enum.TypeInfo.html), and [`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html): the `Reflect` trait, the shape descriptor, and the runtime registry. - [Zig language reference](https://ziglang.org/documentation/master/), [Comptime (zig.guide)](https://zig.guide/language-basics/comptime/), and [*Compile-Time Reflection with @typeInfo*](https://hive.blog/hive-196387/@scipio/learn-zig-series-32-compile-time-reflection-with-typeinfo): `comptime`, `@typeInfo`, `@Type`, `inline for`, and `@field`. diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index bb4c07b8..33f6e986 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -1,30 +1,28 @@ --- sidebar_label: 'Row polymorphism' sidebar_position: 7 -description: "CGP's extensible records and variants read against PureScript rows, OCaml polymorphic variants, structural typing, and row theory." +description: "How CGP expresses field access, record building, and variant operations compared with row polymorphism." --- # Row polymorphism, structural typing, and extensible data types -CGP gives Rust's nominal structs and enums some of the flexibility of row polymorphism. It derives -their shape as types and uses trait bounds to match fields and variants. CGP is a language extension -built as a [stable Rust library](/docs/), with pluggable trait implementations at compile time and -ordinary Rust consumer traits. This page compares CGP with PureScript rows, OCaml polymorphic variants, and -structural typing. It shows which row operations CGP supports and where a row system works better. +CGP gives Rust structs and enums selected forms of structural reuse through derived field lists and +trait bounds. It is a language extension built as a [stable Rust library](/docs/) , with pluggable +implementations behind ordinary Rust traits. This page compares its field access, builders, and +variant operations with PureScript rows and OCaml polymorphic variants. ## In your terms -A **context** is the type a CGP method runs on. It supplies data through fields and chooses -implementations through wiring. Every context on this page is a -**[value context](/docs/reference/glossary#value-context)**: the record being built or the enum -being cast carries both the shape and the wiring, and each component targets `Self`. +A **context** is the type a CGP method runs on. The examples here operate directly on records and +enums, so their contexts are [value contexts](/docs/reference/glossary#value-context) . Field access +uses derived traits; component-based operations can also use wiring to select providers. The row operations map onto CGP constructs as follows: | In a row system | In CGP | | --- | --- | | A closed row | A struct's derived `Fields`, a `Product!` of `Field` entries | -| A row variable, "the rest of the fields" | The context type variable, constrained by trait bounds and never named as a row | +| An open row with required fields | A context type variable with field-access bounds; the remaining fields are not represented by a row variable | | Row containment (`ρ₁ ≲ ρ₂`) | A `HasField` bound, usually written as an `#[implicit]` argument | | Record concatenation (`ρ₁ ⊙ ρ₂ ~ ρ₃`) | `CanBuildFrom` and the `ConcatProduct` type-level operation | | A presence flag per label | The `IsPresent` and `IsNothing` markers on a [partial record](/docs/reference/glossary#partial-record) | @@ -39,24 +37,21 @@ CGP offers selected forms of that flexibility within Rust's nominal type system. ### Structural versus nominal typing -A structural type system decides compatibility by a type's members rather than its name -([Wikipedia, *Structural type system*](https://en.wikipedia.org/wiki/Structural_type_system)). -TypeScript is the most widely used example: an object satisfies an interface by having the required -members ([TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-oop.html)), -though TypeScript only approximates row polymorphism -([Bornea](https://medium.com/@gabriel-bornea/approximating-row-type-polymorphism-in-typescript-495ebd5a623d)). -Rust's structs and enums are nominal, and row polymorphism "is notably absent from Rust's struct -system" ([Andreas, *Structural vs Nominal Typing in Rust*](https://felixandreas.me/blog/nominal-vs-structural-types/)). -CGP works within that nominal system rather than replacing it. +Structural typing makes types compatible when they have the required members. For example, +TypeScript accepts an object as an interface when its members satisfy that interface ([TypeScript +Handbook](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-oop.html)). Row +polymorphism adds a way to name and preserve the remaining fields. Rust structs and enums have +nominal identities even when their fields match; CGP adds structural operations through traits. ### Row polymorphism in PureScript Row polymorphism uses a *row variable* to describe the fields a function does not name. The function accepts any record with its required fields, while the variable carries the remaining fields ([Wikipedia, *Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism)). In PureScript a -*row* is "an unordered collection of named types", of kind `Row k`, and a record is a row wrapped by -`Record` ([PureScript language reference](https://github.com/purescript/documentation/blob/master/language/Types.md)). -An open row adds a tail variable after a pipe: +*row* is "an unordered collection of named types", of kind `Row k` , and a record is a row wrapped +by `Record` ([PureScript language +reference](https://github.com/purescript/documentation/blob/master/language/Types.md)). An open row +adds a tail variable after a pipe: ```purescript -- accepts any record that has at least firstName and lastName; @@ -68,31 +63,30 @@ fullName { firstName: "Ada", lastName: "Lovelace" } -- ok fullName { firstName: "Ada", lastName: "Lovelace", age: 36 } -- also ok; age flows through `r` ``` -The `Prim.Row` type classes `Cons`, `Union`, `Nub`, and `Lacks` govern the row operations, and the -compiler resolves them during type checking -([Pursuit, *Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row)). PureScript's design -descends from Wand's row variables (1987), Rémy's principal types for rows (1989), and Leijen's -scoped labels (2005), which PureScript adopts directly -([Leijen, *Extensible records with scoped labels*](https://www.microsoft.com/en-us/research/publication/extensible-records-with-scoped-labels/)). +PureScript checks row operations through the `Prim.Row` classes `Cons` , `Union` , `Nub` , and +`Lacks` ([Pursuit, *Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row)). PureScript's +design descends from Wand's row variables (1987), Rémy's principal types for rows (1989), and +Leijen's scoped labels (2005), which PureScript adopts directly ([Leijen, *Extensible records with +scoped +labels*](https://www.microsoft.com/en-us/research/publication/extensible-records-with-scoped-labels/)). ### Rows as a kind or as predicates -Row polymorphism has two main designs. PureScript makes rows a *built-in kind* with its own -unification. Gaster and Jones instead encode rows through *qualified types*: a function is -polymorphic over an ordinary type variable, and the *lacks* and *has* predicates it requires are -discharged by the machinery that resolves type-class instances, without a new kind -([Gaster & Jones](http://web.cecs.pdx.edu/~mpj/pubs/polyrec.html)). +Row systems can represent field requirements through built-in rows or through predicates. PureScript +gives rows their own kind and unification rules. Gaster and Jones use *qualified types*: ordinary +type variables constrained by predicates such as *has* and *lacks*, checked through instance +resolution ([Gaster & Jones](http://web.cecs.pdx.edu/~mpj/pubs/polyrec.html)). -CGP resembles the predicate design. It has no row kind or row variable. Instead, a -`HasField` bound says that a context has a field, and Rust's trait -solver checks it. CGP also uses markers like Rémy's presence flags to track which fields are present. +CGP resembles the predicate design. A `HasField` bound says that a +context has a field, and Rust's trait solver checks it. CGP uses ordinary Rust types throughout, +without a separate row kind or row variable. ### Extensible variants -Variants are the dual of records. A row-polymorphic record function accepts "at least these -fields", while a row-polymorphic variant value promises "at most these cases". OCaml's *polymorphic -variants* provide these variants in a production language, without a central type declaration. -OCaml 5.5 infers the type shown in the comment: +Variants are the dual of records. A row-polymorphic record function accepts "at least these fields", +while a row-polymorphic variant value promises "at most these cases". OCaml's *polymorphic variants* +provide these variants in a production language, without a central type declaration. OCaml 5.5 +infers the type shown in the comment: ```ocaml (* no type declaration needed; the variant type is inferred and reusable *) @@ -105,33 +99,36 @@ let to_int = function [Extensible records](/docs/reference/glossary#extensible-record) and variants are a standard answer to Wadler's *expression problem*: adding both new cases to a datatype and new operations over it -"without recompiling existing code, and while retaining static type safety" -([Wadler, 1998](https://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt)). Haskell's -*Data types à la carte* solves the sum side with constraints. It builds a coproduct of signature -functors with a `:<:` constraint whose evidence supplies an injection `inj` and a partial projection -`prj` ([Swierstra](https://www.cs.tufts.edu/~nr/cs257/archive/wouter-swierstra/DataTypesALaCarte.pdf)). - -### The unifying theory - -Morris and McKinna's *rows by any other name* generalizes these designs into *row theories*, "a -monoidal generalization of row types", with two predicates: **combination** `ρ₁ ⊙ ρ₂ ~ ρ₃` and -**containment** `ρ₁ ≲ ρ₂`. Records are built by combination and read by containment; variants are -built by containment and consumed by combination. The idea most relevant to CGP is that "evidence -for type qualifiers has computational content": the proof that a row contains a label *is* the -projection code ([Morris & McKinna, POPL 2019](https://dl.acm.org/doi/10.1145/3290325)). Koka applies -rows to effects ([Leijen, *Koka*](https://arxiv.org/pdf/1406.2061)), which the -[algebraic effects](./algebraic-effects.md) page covers. +"without recompiling existing code, and while retaining static type safety" ([Wadler, +1998](https://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt)). Haskell's *Data +types à la carte* solves the sum side with constraints. It builds a coproduct of signature functors +with a `:<:` constraint whose evidence supplies an injection `inj` and a partial projection `prj` +([Swierstra](https://www.cs.tufts.edu/~nr/cs257/archive/wouter-swierstra/DataTypesALaCarte.pdf)). + +### Combination, containment, and their implementations {#the-unifying-theory} + +Row theory connects records and variants through combination and containment. In Morris and +McKinna's *rows by any other name*, **combination** (`ρ₁ ⊙ ρ₂ ~ ρ₃`) describes joining rows, and +**containment** (`ρ₁ ≲ ρ₂`) describes one row fitting inside another. Records use combination to +build values and containment to read them; variants reverse those roles ([Morris & McKinna, POPL +2019](https://dl.acm.org/doi/10.1145/3290325)). + +The evidence for these relationships can also implement the operation. Evidence that a record +contains a field supplies the code that reads it. This connection matters for CGP because its trait +implementations both satisfy constraints and perform field access or conversion. Rows also describe +effect sets, as in [Koka](https://arxiv.org/pdf/1406.2061) ; the +[algebraic effects](./algebraic-effects.md) page covers that use. ## How CGP expresses it CGP derives type-level shapes for Rust's nominal structs and enums. Trait bounds then express the field and variant requirements that row predicates express in a row system. -### A struct is a closed row; `HasField` is row containment +### Field lists and field requirements {#a-struct-is-a-closed-row-hasfield-is-row-containment} `#[derive(HasFields)]` gives a struct the type-level equivalent of a closed row, with one `Field` entry per field, each tagged by a -[type-level string](/docs/reference/glossary#type-level-string): +[type-level string](/docs/reference/glossary#type-level-string) : ```rust #[derive(HasField, HasFields)] @@ -148,8 +145,8 @@ pub struct Person { ``` PureScript's `fullName` names its required fields with an open row. A CGP function names them as -[implicit arguments](/docs/concepts/implicit-arguments), and any context with those fields satisfies -it: +[implicit arguments](/docs/concepts/implicit-arguments) , and any context with those fields +satisfies it: ```rust #[cgp_fn] @@ -168,12 +165,12 @@ person.full_name(); // "Ada Lovelace" employee.full_name(); // "Ada Lovelace"; `badge` plays the part of `r` ``` -Each implicit argument desugars to a bound such as `HasField`, -which is the containment predicate. The context's other fields play the role of the tail variable. +Each implicit argument desugars to a bound such as `HasField` +, which is the containment predicate. The context's other fields play the role of the tail variable. Unlike PureScript, CGP never names the row variable. It does not infer or carry a residual row; it resolves each containment bound against the concrete context in use. -### Building a record is row combination +### Combining fields in a builder {#building-a-record-is-row-combination} Assembling a struct field by field is CGP's form of record concatenation. The [builder family](/docs/reference/traits/builder/has_builder) takes a *partial record* from empty to @@ -187,23 +184,23 @@ let combined: FooBarBaz = FooBarBaz::builder() .finalize_build(); // exists only when the row is complete ``` -The underlying type-level operations form a row algebra that is evaluated during type checking. +Type-level operations describe how fields combine. [`ConcatProduct`](/docs/reference/traits/type-level/concat_product) joins two products, `AppendProduct` adds one field, and `MapFields` rewrites every entry. `finalize_build` type-checks only when every field is present, which gives generic Rust the completeness guarantee of a closed row. The [Extensible records](/docs/concepts/extensible-records) page develops the pattern. -### Presence markers are presence polymorphism +### Tracking which fields are present {#presence-markers-are-presence-polymorphism} CGP tracks field presence with a flag per field, as Rémy's presence polymorphism does. The flags are [`MapType`](/docs/reference/traits/type-level/map_type) markers on a partial record: `IsPresent` stores the value, `IsNothing` stores nothing, and the -[optional-field extensions](/docs/reference/traits/optional/) add `IsOptional`. A builder starts with -every field marked `IsNothing`, and each step changes one marker. `FinalizeBuild` is implemented only -when every marker is `IsPresent`. On the variant side, `IsVoid` marks a case that extraction has -ruled out. +[optional-field extensions](/docs/reference/traits/optional/) add `IsOptional` . A builder starts +with every field marked `IsNothing` , and each step changes one marker. `FinalizeBuild` is +implemented only when every marker is `IsPresent` . On the variant side, `IsVoid` marks a case that +extraction has ruled out. -### An enum is a row-typed sum; upcast and downcast are injection and branching +### Widening, narrowing, and handling variants {#an-enum-is-a-row-typed-sum-upcast-and-downcast-are-injection-and-branching} The variant side mirrors the record side. The derive represents an enum as a `Sum!` of `Field` entries, and the [structural casts](/docs/reference/traits/casting/can_upcast) implement the @@ -232,21 +229,20 @@ let wide = Reading::Temperature(21).upcast(PhantomData::); ExtendedReading::Flag(true).downcast(PhantomData::).is_err(); // true ``` -Branching, the sum side's combination predicate, is CGP's -[extensible visitor](/docs/concepts/extensible-variants). The `MatchWithValueHandlers` dispatcher -derives one extract-and-handle step per variant from the enum's shape and runs the steps as a -pipeline. Each failed extraction rules out a variant at the type level, so the final match is -provably exhaustive without a wildcard arm. In *Data types à la carte* terms, `CanUpcast` is `inj` -and `CanDowncast` is `prj`. À la carte's `prj` returns a `Maybe` without an exhaustiveness check, -while CGP's branching consumes the whole sum and proves that every case was handled. +CGP's [extensible visitor](/docs/concepts/extensible-variants) combines handlers to cover every +variant, corresponding to branching in row theory. The `MatchWithValueHandlers` dispatcher derives +one extract-and-handle step per variant from the enum's shape and runs the steps as a pipeline. Each +failed extraction rules out a variant at the type level, so the final match is provably exhaustive +without a wildcard arm. `CanUpcast` and `CanDowncast` play roles similar to `inj` and `prj` in *Data +types à la carte*. A projection can fail; exhaustiveness comes from combining handlers that cover +the whole sum. -### Providers are the theory's computational evidence +### Trait implementations supply the evidence {#providers-are-the-theorys-computational-evidence} -CGP makes visible the evidence that Morris and McKinna describe. In a row-typed language, the -compiler elaborates the evidence for a row predicate internally. In CGP the evidence is ordinary code -that a programmer can read: the `HasField` impl a derive generates *is* the projection code, the -`CanBuildFrom` recursion *is* the concatenation code, and a wired provider *is* the witness that a -context can perform an operation. +CGP's trait implementations connect constraints to executable code. A generated `HasField` impl both +proves that a field is available and reads it. `CanBuildFrom` both requires compatible fields and +copies or moves them into a builder. These are concrete examples of the computational evidence +described by row theory; the correspondence does not give CGP a full row type system. ## What each approach costs @@ -256,31 +252,33 @@ such as codec-free JSON decoding and type-safe bindings ([Nguyen](https://hgiasac.github.io/posts/2018-11-18-Record-Row-Type-and-Row-Polymorphism.html)). Row systems can make errors and domain models harder to understand. Row unification can produce very -large diagnostics; a PureScript discussion reports outputs around 152 KB -([PureScript Discourse](https://discourse.purescript.org/t/upcoming-changes-to-error-messages-for-large-records-rows/3696)). +large diagnostics; a PureScript discussion reports outputs around 152 KB ([PureScript +Discourse](https://discourse.purescript.org/t/upcoming-changes-to-error-messages-for-large-records-rows/3696)). One user who modeled a domain with extensible records later preferred separate functions for nominal -types ([PureScript Discourse](https://discourse.purescript.org/t/when-to-use-extensible-types-when-modeling-a-domain/217)). +types ([PureScript +Discourse](https://discourse.purescript.org/t/when-to-use-extensible-types-when-modeling-a-domain/217)). Structural compatibility can also admit a call that makes little sense for the domain ([Fowler](https://jadon.io/blog/row-polymorphism/)). OCaml's manual warns that polymorphic variants -"result in a weaker type discipline" and recommends core variants for simple programs -([OCaml manual](https://ocaml.org/manual/5.5/polyvariant.html)). +"result in a weaker type discipline" and recommends core variants for simple programs ([OCaml +manual](https://ocaml.org/manual/5.5/polyvariant.html)). -Two languages have moved away from rows. PureScript replaced its row-typed effect monad because -"getting the effect rows to line up was sometimes quite tricky" +Some languages have narrowed their use of rows. PureScript replaced its row-typed effect monad +because "getting the effect rows to line up was sometimes quite tricky" ([PureScript-Resources](https://purescript-resources.readthedocs.io/en/latest/eff-to-effect.html)), -and Gleam removed row-typed records to become "less structural and more nominal in style" -([Gleam v0.4](https://gleam.run/news/gleam-v0.4-released/)). - -CGP trades row inference for derives, type-level tags, and wiring. An incomplete operation can -produce a long trait error over generated types. -[`check_components!`](/docs/reference/macros/check_components) -checks wiring at its definition, and [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root -cause for errors it recognizes. Diagnostics can still be heavier than those of a nominal `match`. - -CGP limits accidental structural matches for components. A provider applies only to a context whose -wiring selects it, so matching fields alone do not add that behavior. A `#[cgp_fn]` function such as -`full_name` is different: its single blanket implementation -applies to any context with the named fields, as a row-polymorphic function does. The +and Gleam removed row-typed records to become "less structural and more nominal in style" ([Gleam +v0.4](https://gleam.run/news/gleam-v0.4-released/)). + +CGP requires derives and type-level tags, plus wiring for operations supplied by components. Missing +dependencies can produce long trait errors. +[`check_components!`](/docs/reference/macros/check_components) checks the listed components beside +the wiring. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it +recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. A direct `match` +can still be easier to understand and debug. + +CGP separates a provider's field requirements from the context's choice to use it. Matching fields +can satisfy the requirements, but they do not automatically select the provider. A `#[cgp_fn]` +function such as `full_name` is different: its single blanket implementation applies to any context +with the named fields, as a row-polymorphic function does. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against the alternatives. @@ -295,23 +293,17 @@ trait bounds and derives without changing Rust's type system. ## What to expect that differs -**CGP does not infer rows.** It has no row variable and no row inference. A provider names its -required fields as bounds, and a context's shape comes from a derive. Because CGP does not unify open -rows, it does not produce row-unification errors either; its long errors come from trait resolution -and have different mitigations. +CGP expresses structural requirements within Rust's existing type system: -**Wiring decides which components a context has.** A provider reads a context's fields -structurally, but which providers a context uses is a nominal decision recorded in its wiring. This -keeps a component's behavior tied to the contexts that chose it. A `#[cgp_fn]` blanket trait is the -exception, since it applies wherever the fields exist. - -**Shapes are opt-in.** Only a type that derives `HasFields` or `CgpData` exposes its fields as a -type-level list, so CGP cannot see the shape of a foreign type without the derive. - -**The predicates are traits.** A `HasField` bound is a has-predicate, `CanUpcast` and `CanDowncast` -correspond to `inj` and `prj`, and the trait solver does the work of qualified-type inference. -Readers who know the Gaster and Jones design or Haskell's `row-types` library will recognize the -mechanism. +- **Field requirements are trait bounds.** Rust checks each `HasField` bound without inferring a + residual row. Errors therefore come from trait resolution, rather than row unification. +- **Component behavior requires selection.** Matching fields can satisfy a provider's requirements, + but the context must select that provider. A `#[cgp_fn]` blanket implementation applies wherever + its bounds hold and does not require wiring. +- **Shapes must be exposed.** `HasFields` and `CgpData` derives supply the structural traits. CGP + cannot inspect an arbitrary foreign type without the required implementations. +- **Structural operations keep nominal identities.** Builders and casts operate between declared + Rust types; they do not introduce anonymous record types or full row inference. ## Where to go next @@ -329,8 +321,8 @@ These pages develop the patterns and the neighbouring comparisons: ## Sources -The PureScript snippet was compiled with PureScript 0.15.15 against the prelude and the OCaml snippet -with OCaml 5.5.0. The CGP snippets were compiled against `cgp` `0.8.0-alpha`. +The PureScript snippet was compiled with PureScript 0.15.15 against the prelude and the OCaml +snippet with OCaml 5.5.0. The CGP snippets were compiled against `cgp` `0.8.0-alpha` . - [Wikipedia, *Structural type system*](https://en.wikipedia.org/wiki/Structural_type_system), [*Nominal type system*](https://en.wikipedia.org/wiki/Nominal_type_system), and [*Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism): the definitions and their contrast. - [PureScript language reference, *Types*](https://github.com/purescript/documentation/blob/master/language/Types.md), [Pursuit, *Prim*](https://pursuit.purescript.org/builtins/docs/Prim), and [*Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row): rows, records, open-row syntax, and the row type classes. diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md index 086f5a6f..476761f2 100644 --- a/docs/comparisons/rust-language-proposals.md +++ b/docs/comparisons/rust-language-proposals.md @@ -1,16 +1,16 @@ --- sidebar_label: "Rust's own proposals" sidebar_position: 1 -description: 'CGP read against specialization, named impls, dictionary passing, and contexts and capabilities, for a reader who follows the coherence debate.' +description: 'How CGP compares with Rust proposals for specialization, named implementations, dictionary passing, and contexts and capabilities.' --- # Rust's own proposals -CGP overlaps with Rust proposals for trait selection and values supplied by a caller's environment. -It is a language extension built as a [stable Rust library](/docs/), with pluggable trait -implementations at compile time and ordinary Rust consumer traits. This page compares CGP with -specialization, dictionary passing, named impls, and contexts and capabilities. It shows where the -designs meet and what CGP cannot express. +CGP offers explicit implementation selection and access to context values through a +[stable Rust library](/docs/) . It is a language extension with pluggable implementations behind +ordinary Rust traits. This page compares those choices with specialization, named impls, dictionary +passing, and contexts and capabilities, including what each language proposal can express beyond +CGP. ## In your terms @@ -31,23 +31,22 @@ The proposals' constructs map onto CGP as follows: ## The idea, briefly The proposals on this page explore changes to trait selection or how values reach generic code. -Rust's coherence rules set the starting point. The -*[orphan rule](/docs/reference/glossary#orphan-rule)* says an `impl Trait for T0` -is valid only if `Trait` is a local trait, or at least one of the types `T0..=Tn` is a local type and -no uncovered type parameter appears before it. The *overlap rule* rejects two implementations that -"can be instantiated with the same type" -([Rust Reference](https://doc.rust-lang.org/reference/items/implementations.html); -[RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). - -Together the rules give each trait lookup one impl. Generic code can therefore use `T: Hash` -consistently, including inside a `HashMap`. The -[type classes](./type-classes.md) page covers why coherence exists in the wider type-class -tradition; this page takes it as given. +Rust's coherence rules set the starting point. The *[orphan +rule](/docs/reference/glossary#orphan-rule)* says an `impl Trait for T0` is valid +only if `Trait` is a local trait, or at least one of the types `T0..=Tn` is a local type and no +uncovered type parameter appears before it. The *overlap rule* rejects two implementations that "can +be instantiated with the same type" ([Rust +Reference](https://doc.rust-lang.org/reference/items/implementations.html); +[RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html) ). + +These rules keep trait selection consistent across a program. For example, operations on a +`HashMap` must agree on the hashing and equality implementations for `K` . The +[type classes](./type-classes.md) page explains the broader reasons for coherence. ### Specialization RFC 1210 proposes letting two impls overlap when one is *strictly more specific*, with the compiler -choosing the more specific one. Its own example refines a blanket `AddAssign`: +choosing the more specific one. Its own example refines a blanket `AddAssign` : ```rust impl + Clone> AddAssign for T { @@ -58,26 +57,24 @@ impl + Clone> AddAssign for T { } ``` -The `default` keyword marks an item that a more specific impl may override -([RFC 1210](https://rust-lang.github.io/rfcs/1210-impl-specialization.html)). The feature has been -unstable since 2016. Its tracking issue states that the full feature "as implemented currently is -*unsound*", because dispatch information about lifetimes is erased before code generation. The -`min_specialization` subset, which the standard library uses internally, is the usable part +The `default` keyword marks an item that a more specific impl may override ([RFC +1210](https://rust-lang.github.io/rfcs/1210-impl-specialization.html)). The full feature remains +unstable, with soundness problems involving lifetime information that is erased before code +generation. The standard library uses the more restricted `min_specialization` feature internally ([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). On a stable toolchain the -snippet above fails with `E0658`. +snippet above fails with `E0658` . -Specialization also does not address the case CGP starts from. Two impls of equal generality, such -as `Hash for T: Display` and `Hash for T: AsRef<[u8]>`, are not ordered by specificity, so -specialization rejects them as coherence does. In addition, generic code can select a blanket impl -through a bound that never mentions the trait. By the time the concrete type is known, that code can -no longer see the more specific impl. The [RustLab 2025 talk](/blog/rustlab-2025-coherence) develops -this argument with a hash-table example. +Specialization cannot choose between overlapping impls when neither is more specific. For example, +`T: Display` and `T: AsRef<[u8]>` describe intersecting sets of types, but neither set contains the +other. CGP addresses this case by letting the context name its choice. The +[RustLab 2025 talk](/blog/rustlab-2025-coherence) develops the distinction through a hash-table +example. ### Dictionary passing -Another line of work treats the trait system as a shorthand for *dictionary passing*. A trait -becomes a struct of function pointers, an impl becomes a value of that struct, and a trait bound -becomes an argument the caller passes. Nadrieril works this out for Rust: +Dictionary passing models a trait implementation as data supplied to generic code. A trait becomes a +record of methods, an impl supplies that record, and a trait bound becomes an extra argument. +Nadrieril illustrates this model with the following Rust-like pseudocode: ```rust struct Clone { @@ -87,19 +84,19 @@ struct Clone { const CLONE_U32: Clone = Clone { clone: |x: &u32| *x }; ``` -In this account, trait solving is the process that supplies these values. Coherence becomes a source -of friction, because a global impl constrains a caller in ways the caller cannot see -([Nadrieril, *Dictionary-passing style*](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). -Once impls are values, choosing a different impl means passing a different value, and coherence -forbids exactly that choice. +Trait resolution supplies the dictionary in this model. Passing dictionaries explicitly would let +callers choose different implementations, while coherence restricts that choice. Nadrieril uses the +translation to examine which restrictions belong to Rust's design and which follow from the +underlying mechanism ([*Dictionary-passing +style*](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). ### Named and incoherent impls Boxy's *An Incoherent Rust* proposes replacing the coherence rules with explicit impl selection. The motivation is *ecosystem evolution*. The post argues that once a foundational crate such as `serde` establishes the trait impls for common types, an alternative cannot gain adoption, because -downstream crates cannot implement the competing trait for types they do not own. The sketch names an -impl and passes it where a bound is required: +downstream crates cannot implement the competing trait for types they do not own. The sketch names +an impl and passes it where a bound is required: ```rust impl Name = Trait for T { /* ... */ } @@ -107,11 +104,10 @@ impl Name = Trait for T { /* ... */ } function:: + OtherTraitImpl>(/* ... */) ``` -The post answers the two classic justifications for coherence directly. It solves the `HashMap` -problem by moving the `Hash` and `Eq` bounds onto the type definition, so every operation on one map -uses the same impl. It keeps associated types sound by making the impl part of the type. It names -the remaining challenges as substantial: syntax, ergonomics, migration, and whether the added -complexity is worthwhile ([Boxy, *An Incoherent Rust*](https://www.boxyuwu.blog/posts/an-incoherent-rust/)). +The sketch preserves agreement within a `HashMap` by putting its `Hash` and `Eq` choices on the type +definition. It also makes impl identity part of types to distinguish associated-type choices. These +are proposed answers, with syntax, ergonomics, migration, and complexity still open ([Boxy, *An +Incoherent Rust*](https://www.boxyuwu.blog/posts/an-incoherent-rust/)). ### Contexts and capabilities @@ -134,22 +130,22 @@ with arena::basic_arena = &arena::BasicArena::new() { ``` The proposal's distinctive feature is a *context-dependent trait impl*, which is valid only while a -given capability is in scope. The mechanism compiles to ordinary function arguments, so it adds no -runtime cost. Its open questions concern thread boundaries and scope validity -([Mandry, *Contexts and capabilities in Rust*](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). -The proposal borrows the word "capability" from a security model whose other properties it does not -claim; the [capabilities](./capabilities.md) page separates the senses. +given capability is in scope. The proposed mechanism compiles to ordinary function arguments, +without a runtime lookup. Its open questions concern thread boundaries and scope validity ([Mandry, +*Contexts and capabilities in +Rust*](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). The proposal borrows +the word "capability" from a security model whose other properties it does not claim; the +[capabilities](./capabilities.md) page separates the senses. Nadrieril's follow-up extends dictionary passing so that a trait bound can carry a runtime value. It -names the difficulties that follow: ownership modes for the carried value, the same type satisfying a -trait differently in different scopes, and methods that become closures -([*What If Traits Carried Values*](https://nadrieril.github.io/blog/2026/03/22/what-if-traits-carried-values.html)). +names the difficulties that follow: ownership modes for the carried value, the same type satisfying +a trait differently in different scopes, and methods that become closures ([*What If Traits Carried +Values*](https://nadrieril.github.io/blog/2026/03/22/what-if-traits-carried-values.html)). ### Cairo: a Rust-like language that shipped named impls -Cairo borrows Rust's surface syntax and gives every impl a name, which makes it the closest shipped -counterpart to Incoherent Rust. A generic function can take an impl as an explicit parameter, named -or anonymous: +Cairo provides a working example of named impls in a language with Rust-like syntax. A generic +function can take an impl as an explicit parameter, named or anonymous: ```rust // Cairo @@ -158,9 +154,9 @@ fn largest_list>(l1: Array, l2: Array) -> Array fn smallest_element, +Copy, +Drop>(list: @Array) -> T { /* ... */ } ``` -A caller does not pass the impl. The compiler infers it from the impls visible at the call site -([Cairo Book, *Traits*](https://www.starknet.io/cairo-book/ch08-02-traits-in-cairo.html); -[*Generic Data Types*](https://www.starknet.io/cairo-book/ch08-01-generic-data-types.html)). This +A caller can let the compiler infer the impl from those visible at the call site ([Cairo Book, +*Traits*](https://www.starknet.io/cairo-book/ch08-02-traits-in-cairo.html); +[*Generic Data Types*](https://www.starknet.io/cairo-book/ch08-01-generic-data-types.html) ). This inference matters for the comparison: because resolution uses what is in scope, a call site's imports decide which implementation it uses. @@ -170,13 +166,13 @@ CGP records provider choices on a context. Named-impl designs can instead select site, and capability designs can bind a value within a scope. The examples below show the practical effect of that difference. -### A named impl is a provider +### Naming implementations with providers {#a-named-impl-is-a-provider} A CGP provider corresponds to an impl named with `impl Name = Trait for T` in Boxy's proposal. Each implementation has its own zero-sized type. Overlapping implementations of one trait can therefore coexist, because each implements the provider trait for its own type. The encoder pair from the [Introduction](/docs/) shows this. Rust rejects two blanket impls of one trait for -`T: Display` and `T: AsRef<[u8]>`, since `String` satisfies both. Written as providers, both +`T: Display` and `T: AsRef<[u8]>` , since `String` satisfies both. Written as providers, both compile: ```rust @@ -200,18 +196,17 @@ impl> Encoder { } ``` -`EncodeWithDisplay` and `EncodeBytes` are named impls in the proposal's sense. They overlap on -`String`, and a context selects one by name. A crate that owns neither `Display` nor `String` can -define more of them, because each provider trait is implemented for a provider type the defining -crate owns. Specialization cannot provide this relief from the overlap and orphan rules, because the -two providers are equally general. +`EncodeWithDisplay` and `EncodeBytes` play the role of named impls. Both accept `String` , and a +context selects one. A downstream crate can define another provider even if it owns neither the +component nor the value type, because it implements the provider trait for its own marker type. +Rust's coherence rules still apply to those generated impls. -The encoded value is the `Value` parameter rather than `Self`, so `Self` can stand for an -application. The contexts below are -**[environmental contexts](/docs/reference/glossary#environmental-context)**, and the component is -[parameter-targeted](/docs/reference/glossary#parameter-targeted-component). +The encoded value is the `Value` parameter rather than `Self` , so `Self` can stand for an +application. The contexts below are **[environmental +contexts](/docs/reference/glossary#environmental-context)**, and the component is +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component) . -### An incoherent bound resolves through the context, not at each call site +### Selecting implementations on a context {#an-incoherent-bound-resolves-through-the-context-not-at-each-call-site} Boxy's `function::>` passes the impl at every call. CGP lets generic code require the consumer trait on the context and makes the choice where the context is defined. Two @@ -236,17 +231,16 @@ delegate_components! { } ``` -CGP makes the choice on the context, so every call through `ApiServer` uses the same provider. -Boxy's design selects explicitly at a call, while Cairo infers from the impls in scope. A context -selects one provider per component, keeping code that shares that context consistent. The proposal -addresses the `HashMap` concern by putting `Hash` on the type definition. The -[type classes](./type-classes.md) page develops the comparison with Haskell's incoherent instances. +Every call through `ApiServer` uses its selected provider for `String` ; `Firmware` has its own +choice. This gives consistency per context, component, and dispatch key. Boxy's sketch permits +explicit choices at calls, while Cairo can infer them from scope. The +[type classes](./type-classes.md) page compares these choices with Haskell's instance resolution. -### Passing an impl explicitly is a higher-order provider +### Passing providers as type parameters {#passing-an-impl-explicitly-is-a-higher-order-provider} Where the proposals and Cairo let a caller pass an impl as a parameter, CGP uses -[higher-order providers](/docs/concepts/higher-order-providers). A provider takes another provider -as a type parameter and binds it with `#[use_provider]`, which corresponds to Cairo's +[higher-order providers](/docs/concepts/higher-order-providers) . A provider takes another provider +as a type parameter and binds it with `#[use_provider]` , which corresponds to Cairo's `impl TDrop: Drop` written as a Rust generic: ```rust @@ -259,19 +253,21 @@ impl AreaCalculator { } ``` -A context wires `AreaCalculatorComponent: ScaledArea`, naming the inner impl that a -Cairo compiler would infer. CGP can assemble providers at each call site, but doing so is verbose, -and idiomatic CGP leaves the assembly to the context. A higher-order provider suits a provider that -must fix its inner choice locally. Such providers often default the inner parameter to -[`UseContext`](/docs/reference/providers/use_context), so that the context's wiring is the fallback. -The wired type here is a `ScaledRectangle` with `width`, `height`, and `scale_factor` fields. It is a -**value context**: the type being measured also carries the wiring. +Wiring `AreaCalculatorComponent: ScaledArea` selects both the wrapper and its inner +implementation. The example assumes an `AreaCalculator` component and a `RectangleArea` provider +that reads `width` and `height` . A `ScaledRectangle` context would supply those fields plus +`scale_factor` . It is a **value context** because the measured value carries the wiring. + +Higher-order providers let a wrapper fix or parameterize its inner choice. An inner parameter can +also default to [`UseContext`](/docs/reference/providers/use_context) , which delegates that step +back to the context's selected implementation. ### A `with` clause becomes a context field Mandry's `with arena: &BasicArena` clause declares a value the function needs from its environment. -CGP declares the same need as an [implicit argument](/docs/concepts/implicit-arguments), which reads -a field of the context that every provider receives as `self`: +CGP expresses an environmental dependency as an +[implicit argument](/docs/concepts/implicit-arguments) read from the context. This fragment assumes +a `Greeter` component whose method returns a `String` : ```rust #[cgp_impl(new GreetHello)] @@ -301,36 +297,33 @@ let app = App { name: "World".to_owned() }; app.greet(); // "Hello, World!" ``` -`App` is the context, and constructing it plays the role of the `with` block. Two properties of the -proposal carry over. The binding adds no runtime cost, since a field read compiles to a load. It is -also checked statically: a missing field is a compile error, which -[`check_components!`](/docs/reference/macros/check_components) reports at the wiring site. `App` here -is an environmental context with one field, and the greeter component is -[self-targeted](/docs/reference/glossary#self-targeted-component). +Constructing `App` supplies the value that `GreetHello` reads. The access resolves statically to a +field read, and a missing field causes a compile error when the component is checked or used. +[`check_components!`](/docs/reference/macros/check_components) lets you request that check beside +the wiring. `App` is an environmental context; the greeter is +[self-targeted](/docs/reference/glossary#self-targeted-component) because its method acts on `self` +. ### The context is the dictionary -The dictionary-passing account and CGP meet in one observation: the context is the top-level -dictionary. In Nadrieril's elaboration, every dictionary is a value passed alongside the data. In -CGP, every provider receives the context, and the context's wiring table is a type-level record of -dictionaries, with one `DelegateComponent` entry per component. Lowering a CGP program to -dictionary-passing form would turn the context into a struct whose fields are the other -dictionaries, with close to one field per `delegate_components!` entry. +A CGP context serves a role similar to a root dictionary: it connects generic code to its +dependencies. Each provider receives the context, whose wiring selects other providers. The analogy +describes how dependencies are organized; CGP resolves the selections statically and does not store +a runtime record of function pointers. -This arrangement also handles a problem the proposals must solve separately. Every dictionary -reaches the others through the context, so components that depend on each other resolve without an -instantiation order: the context is one stable root from which all of them are reachable. The -[ML modules](./ml-modules.md) page contrasts this with manual functor application. +Providers can refer to each other's operations through the shared context. This avoids a manual +order for constructing separate dictionaries. Rust still checks the resulting trait dependencies. +The [ML modules](./ml-modules.md) page compares this with explicit functor application. ## What each approach costs These proposals have different levels of maturity and different open questions. Specialization has -an accepted RFC but remains unstable because of a soundness problem -([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). Named impls and dictionary -passing remain design sketches whose authors discuss syntax, ergonomics, migration, and coherence +an accepted RFC but remains unstable because of a soundness problem ([tracking issue +#31844](https://github.com/rust-lang/rust/issues/31844)). Named impls and dictionary passing remain +design sketches whose authors discuss syntax, ergonomics, migration, and coherence ([Boxy](https://www.boxyuwu.blog/posts/an-incoherent-rust/); -[Nadrieril](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html)). Contexts and -capabilities has open questions about thread boundaries and scope +[Nadrieril](https://nadrieril.github.io/blog/2026/03/20/dictionary-passing-style.html) ). Contexts +and capabilities has open questions about thread boundaries and scope ([Mandry](https://tmandry.gitlab.io/blog/posts/2021-12-21-context-capabilities/)). Cairo's scope-based resolution requires the caller to import the needed impls; two call sites can then resolve the same type differently. @@ -338,16 +331,17 @@ resolve the same type differently. CGP requires a component definition and explicit wiring. A provider trait created by [`#[cgp_component]`](/docs/reference/macros/cgp_component) cannot retrofit a foreign trait such as `serde::Serialize` without a parallel component. Wiring adds compile-time work and can produce long -trait errors over generated types. [`cargo cgp check`](/docs/cargo-cgp/check) identifies the root -cause for errors it recognizes. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page -weighs these costs against simpler approaches. +trait errors over generated types. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root +cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every +class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs +against simpler approaches. ## Where a proposal, or a smaller tool, is the better choice -A smaller tool fits a single specialized fast path under a blanket impl. `min_specialization` on -nightly, or manual dispatch on stable Rust, handles that case without CGP wiring. Ordinary coherence -fits a program that needs one global implementation, such as the `Ord` used by map keys. A future -language feature may express scoped or inferred choices with less code than a library can. +A single specialized fast path may need only manual dispatch on stable Rust. On nightly, +`min_specialization` supports a restricted set of specialization cases without CGP wiring. Ordinary +coherence fits a program that needs one global implementation, such as the `Ord` used by map keys. A +future language feature may express scoped or inferred choices with less code than a library can. CGP fits programs that need several valid implementations chosen per application, providers for foreign types, or environment values available in deep code. It offers these choices on stable Rust @@ -355,25 +349,17 @@ through explicit wiring. ## What to expect that differs -**CGP does not infer an impl from scope.** Cairo and the named-impl sketch let the compiler choose -among the impls visible at a call site. CGP has no such search: a context names every provider it -uses in its wiring table. This design prevents two call sites in one program from resolving the same -type differently by accident. - -**Bindings are flat.** Mandry's `with` blocks nest, and an inner scope can shadow an outer binding. -In CGP every binding lives where the concrete context is defined, so an inner scope cannot replace a -provider without defining a new context type. In return, all bindings for a context can be read in -one place. - -**Providers share one context value.** A provider method can take `&self` or `&mut self`, but a -`&mut self` method can borrow only one field mutably through its implicit arguments. A value that -several providers must mutate or own independently needs interior mutability or cloning; the -proposals discuss designs that track ownership modes directly. +CGP's explicit context introduces limits that the proposals address differently: -**CGP is not specialization for stable Rust.** It does not choose a more specific impl, it does not -change existing traits, and it asks for wiring that specialization would infer. It addresses the two -problems specialization leaves open, overlap between equally general impls and the orphan rule, by -naming implementations and choosing them per context. +- **Imports do not select providers.** Wiring records the choice for a context. Rust still resolves + trait bounds, but CGP does not choose a provider by searching the impls imported at each call. +- **Bindings belong to types.** A lexical block does not shadow a context's wiring. A different + selection requires another context type or a context adapter. +- **Implicit arguments borrow the context.** A method can take `&self` or `&mut self`, but implicit + a mutable implicit argument must be the only implicit argument in that method. Independent ownership or mutation + may need a different data layout, interior mutability, or cloning. +- **Existing traits retain their rules.** CGP introduces provider traits and wiring; it does not + enable specialization or additional impls of an arbitrary foreign trait. ## Where to go next @@ -393,7 +379,7 @@ These pages develop the constructs and the neighbouring comparisons: The Rust snippets from the proposals are quoted from their authors' posts and the Cairo book. The specialization snippet was compiled against a stable toolchain to confirm it is rejected with -`E0658`; the CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` +`E0658` ; the CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per wired context. - [Rust Reference, *Implementations*](https://doc.rust-lang.org/reference/items/implementations.html) and [RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html): the orphan and overlap rules. diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md index d4cf616f..aeb9edf2 100644 --- a/docs/comparisons/type-classes.md +++ b/docs/comparisons/type-classes.md @@ -1,16 +1,15 @@ --- sidebar_label: 'Type classes' sidebar_position: 3 -description: 'CGP read against Haskell, Agda, and Lean type classes, coherence, and the overlapping and incoherent instance extensions.' +description: 'How CGP provider selection compares with type classes, coherence, and overlapping instances in Haskell, Agda, and Lean.' --- # Type classes -CGP lets a context choose among named implementations of a Rust trait. It is a language extension -built as a [stable Rust library](/docs/), with pluggable trait implementations at compile time and -ordinary Rust consumer traits. This page maps type classes and instances from Haskell, Agda, and Lean onto -CGP. It explains how explicit selection compares with coherent, overlapping, and incoherent -instances, and when ordinary traits are enough. +CGP lets each context select named implementations at compile time. It is a language extension built +as a [stable Rust library](/docs/) , with ordinary Rust traits as its caller interfaces. This page +compares explicit wiring with type-class resolution in Haskell, Agda, and Lean, and explains when a +single canonical implementation is the simpler choice. ## In your terms @@ -22,10 +21,10 @@ The type-class vocabulary maps onto CGP as follows: | In a type-class language | In CGP | | --- | --- | -| A class | A **component**: one trait with many possible implementations | -| An instance, anonymous and canonical | A **provider**: a named, selectable implementation | +| A class interface | A component's consumer trait, used by callers | +| A class instance | A **provider**: a named implementation of the provider trait | | Instance resolution by the compiler | **Wiring**, written by hand in a `delegate_components!` table | -| A class constraint on a function | An **[impl-side dependency](/docs/reference/glossary#impl-side-dependency)**, declared with `#[uses]` | +| A constraint needed by an implementation | An [impl-side dependency](/docs/reference/glossary#impl-side-dependency), often declared with `#[uses]` | | The dictionary passed as a hidden argument | The context | | A class's associated type | An [abstract type](/docs/reference/glossary#abstract-type), chosen by the context | @@ -33,8 +32,8 @@ The type-class vocabulary maps onto CGP as follows: Type classes let a compiler choose an implementation for a type. A class declares an interface, an instance implements it for a type, and a constrained function works for every type with an instance. -Wadler and Blott introduced them to "make ad-hoc polymorphism less ad hoc" -([Wadler & Blott, 1989](https://dl.acm.org/doi/10.1145/75277.75283)): +Wadler and Blott introduced them to "make ad-hoc polymorphism less ad hoc" ([Wadler & Blott, +1989](https://dl.acm.org/doi/10.1145/75277.75283)): ```haskell class Show a where @@ -50,30 +49,29 @@ describe x = "value: " ++ show x Dictionary passing explains how a class constraint supplies behavior. The class becomes a record of methods, an instance supplies that record, and `describe` receives it as a hidden argument. CGP -uses the same idea, with the context carrying the choices. The [algebraic effects](./algebraic-effects.md) -and [row polymorphism](./row-polymorphism.md) pages compare other forms of passed evidence. +organizes choices through a context and resolves calls statically, without runtime dictionaries. The +[algebraic effects](./algebraic-effects.md) and [row polymorphism](./row-polymorphism.md) pages +compare other forms of passed evidence. ### Coherence and canonical instances -*Coherence* makes automatic resolution predictable: uses of a class constraint should agree on the -instance they select. That goal has distinct parts: *confluence*, *coherence*, and -*global uniqueness*. GHC guarantees the first two within a compilation but does not enforce global -uniqueness across a whole program -([Yang, *Type classes: confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). -The standard example of the benefit is a `Set` of an ordered element type. With one `Ord` for that -type, values inserted under one ordering can never be read back under another. - -Rust makes the same choice and enforces it more strictly. Rust traits are type classes with a hard -[orphan rule](/docs/reference/glossary#orphan-rule): an impl is allowed only when the crate owns the -trait or the type ([RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)), -while GHC permits orphan instances and can warn about them. CGP is built to work within Rust's -rule, and the [Rust proposals](./rust-language-proposals.md) page covers what Rust itself has -considered doing about it. +Coherence keeps implementation choices consistent as generic code is compiled and composed. A `Set` +, for example, relies on insertion and lookup agreeing on its element ordering. Global uniqueness of +instances is one way to support that agreement. GHC's guarantees within a compilation are distinct +from enforcing uniqueness across every separately compiled part of a program ([Yang, *Type classes: +confluence, coherence and global +uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). + +Rust enforces coherence through overlap and [orphan rules](/docs/reference/glossary#orphan-rule) . +An impl needs a local trait or a qualifying local type, subject to restrictions on uncovered type +parameters ([RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). GHC +permits orphan instances and can warn about them. CGP works within Rust's rules; the +[Rust proposals](./rust-language-proposals.md) page explores proposed alternatives. ### Overlapping instances -GHC's first extension to the rule lets instances overlap when one is strictly more specific. It is -enabled through per-instance pragmas: +GHC permits some overlapping instances when one is more specific than another. Per-instance pragmas +control which overlaps are allowed: ```haskell instance {-# OVERLAPPABLE #-} Show a => Show [a] where -- lists in general @@ -83,25 +81,24 @@ instance {-# OVERLAPPING #-} Show [Char] where -- but strings speciall show s = s ``` -Resolution commits to an instance only when it is strictly more specific than every other match. -GHC's own manual warns that "overlapping instances must be used with care as they can give rise to -incoherence (different instance choices are made in different parts of the program)" -([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). +GHC normally requires a single most-specific candidate and may defer resolution if a type variable +could allow a competing match. Its manual warns that overlapping instances can still produce +inconsistent choices across a program ([GHC User's +Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). ### Incoherent instances -The second extension lets the compiler commit to an instance even when the choice is not unique. An -instance marked `{-# INCOHERENT #-}` may be selected where a more specific one could later apply, so -different parts of a program can resolve the same constraint to different dictionaries. The manual -states the danger: GHC's optimiser "assumes that type-classes are coherent, and hence it may replace -any type-class dictionary argument with another dictionary of the same type", so incoherence "may -cause unexpected results" ([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). +`INCOHERENT` relaxes resolution further, allowing a choice even when later type information could +favor another instance. Different parts of a program can then use different dictionaries for the +same constraint. GHC's optimizer assumes coherence and may substitute dictionaries of the same type, +so such choices can lead to unexpected results ([GHC User's +Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). ### Instance arguments in Agda Agda provides class-style overloading without a class construct and without coherence. A record -plays the role of the class, and a double-braced argument is resolved from the scope at the call site -([Devriese & Piessens, 2011](https://dl.acm.org/doi/10.1145/2034574.2034796)): +plays the role of the class, and a double-braced argument is resolved from the scope at the call +site ([Devriese & Piessens, 2011](https://dl.acm.org/doi/10.1145/2034574.2034796)): ```agda record Show (A : Set) : Set where @@ -132,12 +129,12 @@ instance : Show Bool where #eval Show.display true -- "true" ``` -Lean allows multiple instances, so the same constraint can be satisfied in more than one way. When -two resolution paths disagree, which is called a *diamond*, inference can pick the wrong instance or -diverge ([Selsam, Ullrich & de Moura, *Tabled Typeclass Resolution*](https://arxiv.org/pdf/2001.04301)). -In a proof assistant, two instances that are not definitionally equal break proofs that assume they -coincide. The Mathlib community therefore keeps overlapping instances definitionally equal as a -standing practice ([Baanen, 2022](https://arxiv.org/pdf/2202.01629)). +Lean allows multiple instances, so the same constraint can be satisfied in more than one way. +Multiple resolution paths can form a *diamond*. If they produce instances that are not +definitionally equal, code expecting those instances to coincide can fail ([Selsam, Ullrich & de +Moura, *Tabled Typeclass Resolution*](https://arxiv.org/pdf/2001.04301)). Mathlib therefore keeps +overlapping instances definitionally equal as a standing practice ([Baanen, +2022](https://arxiv.org/pdf/2202.01629)). ### Modular type classes @@ -150,22 +147,23 @@ The paper identifies a tension between **canonicity and modularity**. A canonica implicit resolution predictable, but two modules can each supply a different instance. The designs make different choices: -- **Haskell:** Fully implicit resolution, global coherence, and one instance per type. +- **Haskell:** Implicit resolution with a preference for a canonical instance and extensions that + relax the rules. - **Modular type classes, OCaml's modular implicits, Agda instance arguments, and Scala implicits:** Implicit resolution with canonicity scoped or dropped, at the cost of possible ambiguity. -- **CGP:** No canonicity and no search. Each context selects its implementations explicitly. +- **CGP:** Each context selects providers explicitly, and Rust resolves the resulting trait bounds. The [ML modules](./ml-modules.md) page develops the module side. ## How CGP expresses it CGP makes implementation choice explicit per context. A component has a consumer trait for callers -and a provider trait for implementations. The consumer trait is an ordinary Rust trait; providers and -wiring make several implementations selectable. +and a provider trait for implementations. The consumer trait is an ordinary Rust trait; providers +and wiring make several implementations selectable. -### A component is a class; a provider is a first-class instance +### Components define interfaces; providers name implementations {#a-component-is-a-class-a-provider-is-a-first-class-instance} -Declaring a component declares a class: +A component declares the interface callers use and generates a provider trait for implementations: ```rust #[cgp_component(AreaCalculator)] @@ -195,20 +193,20 @@ pub struct Rectangle { delegate_components! { Rectangle { AreaCalculatorComponent: RectangleArea } } ``` -Implementing the provider trait on a provider type, rather than on the context, removes the -one-instance-per-type limit. Each provider implements the provider trait for its *own* type, so -coherence does not forbid a second provider. The wiring line takes the place of resolution: it states -the choice that Haskell's compiler would find by searching for the canonical instance. A provider's -`#[uses]` imports correspond to the class constraints that dictionary passing threads through, and -the context carries them. `Rectangle` here is a -**[value context](/docs/reference/glossary#value-context)**: the type being measured also carries -the wiring, and the component is [self-targeted](/docs/reference/glossary#self-targeted-component). +Separate provider types let alternative implementations coexist under Rust's coherence rules. The +wiring selects `RectangleArea` for `Rectangle` ; another provider could implement the same provider +trait on its own marker type. + +This example still makes one choice for `Rectangle` . It is a +[value context](/docs/reference/glossary#value-context) : the measured type also carries the wiring, +and the component is [self-targeted](/docs/reference/glossary#self-targeted-component) . Independent +choices for the same value type require moving selection to separate contexts, as the next example +does. -### Overlapping providers need no specificity rule +### Providers can accept overlapping sets of types {#overlapping-providers-need-no-specificity-rule} -Haskell needs pragmas and a most-specific rule to permit overlap. CGP allows any number of -overlapping providers, and a context chooses among them by name rather than by specificity. Three -encoders that apply to overlapping sets of types compile side by side: +CGP gives each encoder its own provider type, so their accepted value types can overlap. These +providers illustrate distinct choices for display output, raw bytes, and hexadecimal output: ```rust #[cgp_component(Encoder)] @@ -238,23 +236,19 @@ impl> Encoder { } ``` -As type-class instances these would conflict: `String` matches the first pair, and `Vec` matches -the second. Even with `OVERLAPPING`, the compiler would need one instance to be strictly more -specific. As providers, all three compile, because each implements the provider trait for its own -marker type. CGP has no most-specific rule, so the overlap creates no ambiguity. The problem GHC -warns about, overlap that silently produces incoherence, does not arise here, because CGP never -infers the choice. +These providers accept overlapping inputs: `String` supports display and byte access, while +`Vec` supports both byte encoders. A Haskell-style instance system would need a way to +distinguish those choices; constraints alone do not make one instance more specific. CGP keeps the +choices separate through provider types and records the selection in wiring. -The encoded value is the `Value` parameter rather than `Self`, so the contexts that wire these -providers are **[environmental contexts](/docs/reference/glossary#environmental-context)**, types that -stand for an application. The component is -[parameter-targeted](/docs/reference/glossary#parameter-targeted-component). +The encoded value is the `Value` parameter rather than `Self` , so the contexts that wire these +providers are **[environmental contexts](/docs/reference/glossary#environmental-context)**, types +that stand for an application. The component is +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component) . -### Incoherent choices made explicit and local +### Selecting a provider per context and value type {#incoherent-choices-made-explicit-and-local} -CGP allows several implementations for one type, the situation that type-class languages guard -against, and makes it safe by moving the choice from a global search to an explicit table in each -context: +Separate application contexts can select different providers for the same value type: ```rust pub struct AppA; @@ -277,52 +271,50 @@ delegate_components! { } ``` -Each context selects one provider per component and per value type. Two contexts can therefore -resolve the same type differently *on purpose*, while the choice within one context is unambiguous -and fixed. `AppA` encodes a `Vec` as hexadecimal and `AppB` passes the bytes through, and each -context is consistent on its own terms. In Haskell, different choices in different parts of a program -are a hazard, and in Lean they produce a diamond. In CGP each choice is written in a context's table, -so a reader can see which one applies. The `open` statement and the `@`-path keys are documented on -the [`delegate_components!`](/docs/reference/macros/delegate_components) page. +`AppA` encodes `Vec` as hexadecimal, while `AppB` returns its bytes directly. Each choice is +fixed for the context, component, and value type. This makes the difference explicit without +relaxing Rust's coherence rules. The `open` statement and `@` paths are explained in +[`delegate_components!`](/docs/reference/macros/delegate_components) . ### Providers avoid orphan conflicts and newtypes -A provider's `Self` is always a type that its crate owns, and this removes two common workarounds. -The orphan rule is always satisfied, so a downstream crate can supply a provider for a component and -a type it did not define. A second behavior for a type is a second provider, named directly, so the -type does not need a newtype such as the `Sum` and `Product` wrappers around `Int`. The -[Bypassing coherence](/docs/concepts/coherence) page shows both on the encoder example. +A downstream crate can define a provider for a foreign component and value type by owning the +provider's marker type. This satisfies the orphan rule without wrapping the value in a newtype. +Alternative behaviors get their own provider types, rather than wrappers such as Haskell's `Sum` and +`Product` . The [Bypassing coherence](/docs/concepts/coherence) page develops this pattern. ## What each approach costs -Type classes are valued for principled, inferred overloading and for global uniqueness. The costs -their users describe follow from the same rules. The one-instance-per-type limit requires the -newtype workaround, which "breaks down when the type is embedded in another type" -([Yang, 2014](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). -The orphan rule shapes module structure ([Queensland FP Lab](https://qfpl.io/posts/orphans-and-fundeps/)). -Overlapping instances are subtle, and incoherent instances, by GHC's own account, "may cause -unexpected results" ([GHC User's Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). -Haskell has no simple form of local instance, because local instances reintroduce a coherence -problem. - -In Agda and Lean, which do not enforce coherence, the costs appear as the diamond problem and the work -of keeping overlapping instances definitionally equal ([Baanen, 2022](https://arxiv.org/pdf/2202.01629)). -Some practitioners argue that the coherence bargain is the wrong one and prefer explicit dictionaries -([Chiusano, *The trouble with typeclasses*](https://pchiusano.github.io/2018-02-13/typeclasses.html)). -A recent survey compares where Swift, Rust, Scala, and Haskell each draw the line -([Racordon, Flesselle & Pham, 2025](https://arxiv.org/pdf/2502.20546)). - -CGP requires explicit wiring because it does not search for an implementation. Providers also need -a component declared with [`#[cgp_component]`](/docs/reference/macros/cgp_component), adding code -beyond a plain trait. Trait resolution adds compile-time work and can produce long errors over -generated types. [`cargo cgp check`](/docs/cargo-cgp/check) identifies the root cause for errors it -recognizes. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page compares these -costs with simpler approaches. +Canonical instances simplify calls but make alternative implementations harder to use. A newtype can +select another instance, though that workaround becomes awkward when the wrapped type appears inside +other types ([Yang, +2014](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). The +orphan rule shapes module structure ([Queensland FP +Lab](https://qfpl.io/posts/orphans-and-fundeps/)). Overlapping instances are subtle, and incoherent +instances, by GHC's own account, "may cause unexpected results" ([GHC User's +Guide](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html)). Local instances +also require a way to preserve consistency when values cross scopes. + +Systems that allow multiple instances must manage ambiguity or disagreement between resolution +paths. Mathlib addresses this by keeping overlapping instances definitionally equal ([Baanen, +2022](https://arxiv.org/pdf/2202.01629)). Some practitioners argue that the coherence bargain is the +wrong one and prefer explicit dictionaries ([Chiusano, *The trouble with +typeclasses*](https://pchiusano.github.io/2018-02-13/typeclasses.html)). A 2025 survey compares +where Swift, Rust, Scala, and Haskell each draw the line ([Racordon, Flesselle & Pham, +2025](https://arxiv.org/pdf/2502.20546)). + +CGP requires explicit wiring to choose providers. Providers also need a component declared with +[`#[cgp_component]`](/docs/reference/macros/cgp_component), adding code beyond a plain trait. Trait +resolution adds compile-time work and can produce long errors over generated types. +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page compares these costs with simpler +approaches. ## Where coherent type classes are the better choice Coherent type classes fit programs that need one canonical instance per type, such as the `Ord` used -by a `Set`. The compiler keeps generic code consistent without wiring. In Rust, an ordinary trait +by a `Set` . The compiler keeps generic code consistent without wiring. In Rust, an ordinary trait already provides that guarantee. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page starts from this simpler case. @@ -331,25 +323,18 @@ context. Providers can also cover types the program does not own without orphan- ## What to expect that differs -**CGP does not find the instance by type.** A context names the provider in its table. Because CGP -does not search for an instance, it does not depend on each type having a unique one, so it can hold -the overlapping and orphan implementations that Haskell forbids or treats as fragile. - -**Uniqueness is per context, not program-wide.** A type-class reader may expect that once a type has -an instance, it is the instance everywhere. CGP guarantees one choice within a context and lets two -contexts differ, so two applications can encode one type in two ways without conflict. - -**Selection can be keyed on the context rather than the type.** Haskell keys `Show Bool` on `Bool`, -so there is one such instance. The encoder example moves the type being operated on into a -parameter and keys the choice on the context. Changing the key makes per-context selection different -from per-type instances, rather than a new name for them. CGP can also key the choice on the type, as -the `Rectangle` example does, and then it has the same one-choice-per-type limit. The -[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page works out the difference between the -two arrangements. - -**Wiring checks take the place of instance resolution's checks.** A type-class compiler proves that -an instance exists at each use. [`check_components!`](/docs/reference/macros/check_components) -proves that a context's wiring is complete, and it names any missing dependency at the wiring site. +CGP changes where implementation choices are recorded: + +- **Wiring selects providers.** Rust still resolves trait bounds, but a context names the provider + instead of relying on a globally canonical implementation for the value type. +- **Consistency is scoped to the context and key.** Two contexts can encode the same type + differently. Code that needs shared behavior must use the same selection. +- **Context placement controls flexibility.** Wiring on `Rectangle` gives that type one choice. + Wiring on `AppA` and `AppB`, with the value passed separately, permits independent choices. The + [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) explains these arrangements. +- **Explicit checks validate dependencies early.** A delegation entry alone does not prove that + its provider can be used. [`check_components!`](/docs/reference/macros/check_components) asserts + the required components and parameters beside the wiring; ordinary calls also force checking. ## Where to go next From 15fb055e085768c994b0edab30b837a13d6d5218 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 26 Sep 2026 03:23:17 +0000 Subject: [PATCH 094/516] Clarify async_trait placement and project snippet sources State that #[async_trait] also works below #[cgp_component], as the cgp-examples transfer crate shows, while keeping outermost as the conventional form. Point agents at the knowledge base's projects/ section when a page quotes a project built with CGP. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 ++++- docs/reference/macros/async_trait.md | 9 +++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b5459ad8..0d50b6b7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,10 @@ base's document for each post lists exactly what is stale in it, and its a removal ledger that dates every renamed or deleted construct in one table. The safest source of verified snippets is the knowledge base's [`examples/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/examples) directory, -which exists partly to be quoted. +which exists partly to be quoted. When a page quotes a project built with CGP, such as a crate of +`cgp-examples`, check the snippet against that project's section under +[`projects/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/projects), which records +the project's current code and whether it uses current idioms. ## Consult the communication strategy before writing public prose diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 9be1fc4c..807043a8 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -61,8 +61,8 @@ the same trait pass through unchanged, so a trait can mix them freely. When stacked with another macro, the order follows what that macro needs, and the two cases differ. -With [`#[cgp_component]`](./cgp_component.md), put `#[async_trait]` **outermost**, so it rewrites the trait -before the component macro reads it: +With [`#[cgp_component]`](./cgp_component.md), the conventional placement is **outermost**, so it rewrites +the trait before the component macro reads it: ```rust #[async_trait] @@ -72,6 +72,11 @@ pub trait CanFetchStorageObject { } ``` +Placing it after `#[cgp_component]` also works, because the component macro copies an attribute it does +not recognize onto each trait it generates, where `#[async_trait]` then rewrites it. The async components +of the [`transfer`](https://github.com/contextgeneric/cgp-examples/blob/v0.8.0/transfer/src/interfaces/finance.rs) +example are written that way. + With [`#[cgp_fn]`](./cgp_fn.md), which *generates* the trait from a function, put it **below** `#[cgp_fn]` on the `async fn`. `#[cgp_fn]` copies the attribute onto both items it generates: From 0a18902834eb760ebff4801cfad5a5337ba64357 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 26 Sep 2026 09:45:19 +0000 Subject: [PATCH 095/516] Correct the namespace pages' claim that a direct entry shadows a default A context's direct entry for a key its namespace binds, or for a type a per-type default loop already wires, is rejected with E0119; it never shadows the default. The namespace trait pages, the default_impl, cgp_namespace, delegate_component, and path pages now say a context adds entries only where the namespace leaves a gap, and the examples' u64 entry is described as filling one. The default_impl example-code comment and test name follow. Co-Authored-By: Claude Opus 5.5 --- docs/reference/attributes/default_impl.md | 17 +++++----- docs/reference/macros/cgp_namespace.md | 30 +++++++++--------- docs/reference/macros/path.md | 9 +++--- .../traits/namespace/default_impls1.md | 14 +++++---- .../traits/namespace/default_impls2.md | 3 +- .../traits/namespace/default_namespace.md | 31 ++++++++++--------- docs/reference/traits/namespace/index.md | 8 ++--- .../traits/wiring/delegate_component.md | 10 +++--- .../reference/attributes/default_impl.rs | 5 +-- 9 files changed, 69 insertions(+), 58 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index acc5b494..c9b36273 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -13,9 +13,9 @@ Register a provider as a namespace's default for a key. `#[default_impl(...)]` lets a *provider* register itself as a [namespace](/docs/concepts/namespaces)'s default for a key, at the point where the provider is defined. A namespace is a reusable table of default -wirings that a **context** can opt into and then override entry by entry. (The context is the type the -method runs on.) Ordinarily you write a namespace's entries in its own body. This attribute -moves one entry onto the provider: +wirings that a **context** can opt into and then complete with the entries it leaves open. (The context +is the type the method runs on.) Ordinarily you write a namespace's entries in its own body. This +attribute moves one entry onto the provider: ```rust #[cgp_impl(new ShowString)] @@ -127,14 +127,14 @@ delegate_components! { @test.ShowImplComponent.T: Provider, } - @test.ShowImplComponent.u64: ShowWithDisplay, // overrides the inherited default + @test.ShowImplComponent.u64: ShowWithDisplay, // u64 has no registered default } } ``` **[Environmental context](/docs/reference/glossary#environmental-context), [parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: `App` carries the wiring and the shown value is a -parameter. The loop wires every type with a registered default, and the direct `u64` line shadows -whatever the namespace would otherwise supply for that one type. `ShowWithDisplay` is wired directly +parameter. The loop wires every type with a registered default, only `String` here, and the direct +`u64` line adds a type the registry does not cover. `ShowWithDisplay` is wired directly rather than registered, because its impl is generic over `T`, and a generic impl cannot register a default (see [Common Mistakes](#common-mistakes)). @@ -297,8 +297,9 @@ error[E0119]: conflicting implementations of trait `DefaultImpls1 @Component,` generates; it is occasionally a convenient spelling for rooting a component's route at its own name. - **`namespace Other;`** is accepted, but inheritance is written with the `: ParentNamespace` header - above. That is the form overriding and the cycle diagnostics are defined in terms of. + above. That is the form the override rule and the cycle diagnostics are defined in terms of. - **A nested table value**, `UseDelegate`, works, and is the one legacy form with a reason to keep in a namespace: the macro lifts the inner table out into its own struct and impls, so every context joining the namespace inherits the per-type dispatch without restating it. It still @@ -350,12 +352,12 @@ The `#[prefix(...)]` attribute, which registers a component into a namespace and ## Common Mistakes **A context cannot override a path its namespace itself terminates.** Joining with `namespace N;` emits a -blanket `DelegateComponent` impl covering every path `N` resolves, so a direct entry for one of those paths -is a second impl for the same key and the compiler rejects the overlap with `E0119`. Overriding works only on -a path the namespace *routes to* without binding, which is why the example above has the namespace own the -route and the context own the provider. A path the namespace binds with a `:` entry or a `#[default_impl]` -has to be changed in the namespace instead. The same restriction stops a child namespace from redefining a -key its parent binds. +blanket `DelegateComponent` impl covering every path `N` resolves, so a direct entry for one of those +paths is a second impl for the same key and the compiler rejects the overlap with `E0119`. A context can +wire only a path the namespace *routes to* without binding, which is why the example above has the +namespace own the route and the context own the provider. A path the namespace binds with a `:` entry or +a `#[default_impl]` has to be changed in the namespace instead. The same restriction stops a child +namespace from redefining a key its parent binds. **Joining two namespaces on one context conflicts, for the same reason.** Each namespace produces a blanket forwarding impl covering every key, so joining two collides them: diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index bafbf049..cf2c2ce2 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -15,10 +15,11 @@ A type-level path, used by namespaces and redirected lookups. Read left to right, each segment narrows a lookup one step: through a namespace, through a prefix, down to a component key. -CGP needs such routes because [namespaces](./cgp_namespace.md) resolve lookups by path rather than by bare -component name, which lets a whole subtree be rerouted at once and a single inherited entry be shadowed -without disturbing the rest. Written as the underlying list, those routes are unreadable -(`PathCons<…, PathCons<…, Nil>>` nested several deep), so `Path!` lets one be written the way it reads: +CGP needs such routes because [namespaces](./cgp_namespace.md) resolve lookups by path rather than by +bare component name, which lets a whole subtree be rerouted at once and a context supply a single path +the namespace leaves open without disturbing the rest. Written as the underlying list, those routes are +unreadable (`PathCons<…, PathCons<…, Nil>>` nested several deep), so `Path!` lets one be written the way +it reads: ```rust Path!(@app.error.ErrorRaiserComponent) diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index bd11a236..9ed4300f 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -88,8 +88,8 @@ simply whatever you wrote inside the path. The same rule is why the `for … in` ## Examples -The whole chain, from a provider declaring itself a default to a context pulling it in and overriding one -entry: +The whole chain, from a provider declaring itself a default to a context pulling it in and adding an entry +for a type the registry does not cover: ```rust use cgp::core::component::DefaultImpls1; @@ -124,15 +124,16 @@ delegate_components! { @test.ShowImplComponent.T: Provider, } - @test.ShowImplComponent.u64: ShowWithDisplay, // overrides the inherited default + @test.ShowImplComponent.u64: ShowWithDisplay, // u64 has no registered default } } ``` **[Environmental context](/docs/reference/glossary#environmental-context), [parameter-targeted](/docs/reference/glossary#parameter-targeted-component).** `App` carries the wiring and the shown value is a parameter. The loop wires every type with a registered default by projecting -`T: DefaultImpls1`, and the direct `u64` line shadows -whatever the namespace would otherwise supply for that one type. +`T: DefaultImpls1`. Only `String` has a registered default, +so the direct `u64` line adds a type beside it. Had `u64` a registered default too, the loop's impl and +the direct entry would both cover its path, and the compiler would reject them with `E0119`. A whole namespace can also be the loop target: @@ -205,7 +206,8 @@ resolves it. **`#[default_impl]` on a prefixed component is confined to the namespace's crate**, by the orphan rule. Put downstream wiring in the namespace body instead. -**A default is a fallback, not an assignment.** A direct entry silently shadows it. +**A registered default cannot be overridden from the context.** A direct entry for a type the loop +already wires overlaps the loop's impl and is rejected with `E0119`. **The registration impl carries none of the provider's bounds**, which is deliberate: they are checked where the provider is used rather than where it is registered. diff --git a/docs/reference/traits/namespace/default_impls2.md b/docs/reference/traits/namespace/default_impls2.md index 1bca1a0c..86dfa608 100644 --- a/docs/reference/traits/namespace/default_impls2.md +++ b/docs/reference/traits/namespace/default_impls2.md @@ -155,7 +155,8 @@ library example. **A `for … in` loop's key must mention the loop variables**, or the impl is rejected with `E0207`. -**A default is a fallback, not an assignment.** A direct entry silently shadows it. +**A registered default cannot be overridden from the context.** A direct entry for a pair the loop +already wires overlaps the loop's impl and is rejected with `E0119`. **Two keys are usually one key too many.** If the second type is fixed for a whole application, a [`DefaultImpls1`](./default_impls1.md) default plus a wiring entry is easier to read. diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index f1553616..c3c970a2 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -16,14 +16,15 @@ Resolving a namespace's default provider for a component. [`#[prefix(...)]`](../../attributes/prefix.md) attribute emit the impls. You name the trait in exactly one place, a `namespace` header inside [`delegate_components!`](../../macros/delegate_components.md), and this page explains what that header -generates, including why a direct entry can shadow an inherited default without conflicting with it. +generates, including why a direct entry can fill a path the namespace leaves open but cannot replace +one it binds. ::: ## Overview A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** (the -type the method runs on) can opt into and then selectively override. Resolving one of those +type the method runs on) can opt into and then complete. Resolving one of those defaults means asking: *for this component, what does the namespace delegate to?* `DefaultNamespace` answers that. It is the simplest of three lookup traits, keyed on the component alone. @@ -87,14 +88,14 @@ delegate_components! { App { namespace DefaultNamespace; - @test.ShowImplComponent.u64: ShowWithDisplay, // overrides the inherited default + @test.ShowImplComponent.u64: ShowWithDisplay, // fills a path the namespace leaves open } } ``` -**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** The header forwards `App`'s unwired lookups through the -namespace, and the direct entry shadows whatever the namespace would otherwise supply for that one key, -the inheritance-with-override shape presets rely on. +**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** The header forwards `App`'s lookups through the +namespace. `DefaultNamespace` routes `ShowImplComponent` to `@test.ShowImplComponent` but binds no +provider there, so the direct entry supplies the one for `u64`. ## When to use it @@ -130,21 +131,23 @@ where paired with the matching [`IsProviderFor`](../wiring/is_provider_for.md) forwarding so dependencies stay diagnosable. -**That blanket makes override work.** A directly-wired entry is a *concrete* impl for one key, -and a concrete impl is more specific than the blanket, so it resolves first, shadowing the inherited -default for that key and leaving the rest untouched. Two *concrete* entries for one key would conflict; a -concrete entry against a blanket does not. +**That blanket is why a context cannot override a namespace entry.** A directly-wired entry is a second +`DelegateComponent` impl for its key, and Rust has no specialization to prefer one impl over another. +Where the namespace binds that key, the blanket covers it too, and the compiler rejects the overlap with +`E0119`. A direct entry compiles only for a key the blanket does not cover: a path the namespace routes +to but leaves unbound, like `@test.ShowImplComponent.u64` above. Inheritance composes on top. A namespace declared `new Child: Parent { … }` emits a blanket impl forwarding any key the parent resolves, so the child resolves everything the parent does plus its own -entries, and a context's direct entry still shadows either. All of it is projections, resolved at +entries. The same rule holds at each level: a child cannot rebind a key its parent binds, and a context +cannot rebind a key either one binds. All of it is projections, resolved at compile time, with nothing at run time. ## Common Mistakes -**A namespace default is a fallback, not an assignment.** It resolves only for keys the context does not -wire directly, which is the intent, and it means a stray direct entry can silently shadow a default you -expected to apply. +**A namespace entry cannot be overridden from the context.** A direct entry for a key the namespace +binds is rejected with `E0119` rather than preferred. To vary a choice between contexts, leave its path +unbound in the namespace and wire it on each context, or give the contexts different namespaces. **`Self` is the component here**, as you would expect, but **not** in [`DefaultImpls1`](./default_impls1.md) and [`DefaultImpls2`](./default_impls2.md), where the instance diff --git a/docs/reference/traits/namespace/index.md b/docs/reference/traits/namespace/index.md index 5a6e240e..88a5fcc5 100644 --- a/docs/reference/traits/namespace/index.md +++ b/docs/reference/traits/namespace/index.md @@ -10,10 +10,10 @@ The lookup traits behind a namespace and a per-type default. ## Overview A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a context opts into -and then selectively overrides. Resolving one of those defaults means asking, for a given key, what the -namespace delegates to, and these three traits answer it, differing only in how many types take part -in the key. You name them where the syntax requires it: a `namespace` header or a `for … in` loop -inside [`delegate_components!`](../../macros/delegate_components.md), and the +and then completes with the entries the namespace leaves open. Resolving one of those defaults means +asking, for a given key, what the namespace delegates to, and these three traits answer it, differing +only in how many types take part in the key. You name them where the syntax requires it: a `namespace` +header or a `for … in` loop inside [`delegate_components!`](../../macros/delegate_components.md), and the [`#[default_impl]`](../../attributes/default_impl.md) attribute. The macros generate the impls. - [`DefaultNamespace`](default_namespace.md) keys a default on the component alone, the common case that diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index 5d626484..33694922 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -214,8 +214,8 @@ Two further facts about the generated impls are worth carrying away. Each entry is both resolvable and checkable, and [`CanUseComponent`](./can_use_component.md) then combines the pair into a single assertion. And a namespace's `namespace N;` header emits not one entry but a *blanket* `DelegateComponent` impl that forwards every key -through the namespace, which is how a context inherits a whole table while still letting a direct entry -shadow one key. +through the namespace, which is how a context inherits a whole table while still adding direct entries +at the keys the namespace leaves open. ## Common Mistakes @@ -225,9 +225,9 @@ elsewhere, through [`IsProviderFor`](./is_provider_for.md). Reading which one yo add a wiring line or supply a dependency. **Two entries for the same key is a coherence error, not an override.** Wiring one component twice on one -context reports `E0119` conflicting implementations. A namespace *can* be shadowed by a direct entry, -because the namespace side is a blanket impl rather than a second concrete one, but two concrete entries -always conflict. +context reports `E0119` conflicting implementations. A direct entry for a key the context's namespace +binds conflicts the same way, with the namespace's blanket impl, so a context adds entries only at keys +the namespace leaves open. **`Self` is not always a context.** A provider bundle declared with `new` owns a table too, and reading an error that names one as the table's `Self` does not mean something is being used as a context. diff --git a/example-code/tests/reference/attributes/default_impl.rs b/example-code/tests/reference/attributes/default_impl.rs index dd932212..850d4c52 100644 --- a/example-code/tests/reference/attributes/default_impl.rs +++ b/example-code/tests/reference/attributes/default_impl.rs @@ -3,7 +3,8 @@ /// ## Examples /// /// The page's chain: a per-type default registered on the provider and pulled into a context by a -/// `for … in` loop, with one direct override. `ShowWithDisplay` is named by the page without being +/// `for … in` loop, with one direct entry for `u64`, which the registry does not cover. +/// `ShowWithDisplay` is named by the page without being /// introduced, so it is declared here. pub mod examples { use core::fmt::Display; @@ -53,7 +54,7 @@ pub mod examples { } #[test] - fn default_and_override_resolve() { + fn default_and_direct_entry_resolve() { assert_eq!(App.show(&"text".to_owned()), "text"); assert_eq!(App.show(&7u64), "7"); } From ed389d8324baeaab41dccb296270b2596e6f4144 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 26 Sep 2026 09:46:24 +0000 Subject: [PATCH 096/516] Update cgp-skills --- cgp-skills | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgp-skills b/cgp-skills index 85481690..51d37f68 160000 --- a/cgp-skills +++ b/cgp-skills @@ -1 +1 @@ -Subproject commit 85481690c389efc9ba2e7550db53df7e37a0822e +Subproject commit 51d37f68b8d47e28e97220363ae93deaa6f47227 From 9563729e066fc16d62b670af44cb22d8073664b9 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 26 Sep 2026 13:07:37 +0000 Subject: [PATCH 097/516] Teach input dispatch with open keys, one segment per type parameter The Dispatching and Handlers concept pages, the MatchWithValueHandlers, UseInputDelegate, UseDelegate, and handler-index reference pages, and the derive_delegate page now wire dispatch on a handler's input with `open` keys such as `@ComputerComponent. Code.Circle`, and correct the claim that input dispatch has no `open` equivalent. The delegate_components! page gains the one-segment-per-parameter rule and the overlap restriction. The example-code mirrors are updated. Co-Authored-By: Claude Opus 5.5 --- docs/concepts/dispatching.md | 27 +++--- docs/concepts/handlers.md | 9 +- docs/reference/attributes/derive_delegate.md | 12 +-- docs/reference/macros/delegate_components.md | 36 +++++++- .../dispatch/match_with_value_handlers.md | 25 +++--- docs/reference/providers/handler/index.md | 3 +- .../providers/handler/use_input_delegate.md | 35 +++++--- docs/reference/providers/use_delegate.md | 5 +- example-code/tests/concepts/dispatching.rs | 22 +++-- .../reference/macros/delegate_components.rs | 85 +++++++++++++++++++ .../dispatch/match_with_value_handlers.rs | 13 ++- .../providers/handler/use_input_delegate.rs | 22 +++++ 12 files changed, 226 insertions(+), 68 deletions(-) diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index 3451878f..a3765ff0 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -33,27 +33,28 @@ depend on the dispatcher and the providers it contains. ## Matching, and why it is exhaustive A matcher selects the handler for an enum's current variant. For a `Shape` enum deriving `CgpData` -with `Circle(Circle)` and `Rectangle(Rectangle)` variants, input-based wiring can select both the -matcher and the payload handlers: +with `Circle(Circle)` and `Rectangle(Rectangle)` variants, wiring keyed on the input type can select +both the matcher and the payload handlers: ```rust delegate_components! { App { - ComputerComponent: UseInputDelegate< - new AreaComponents { - Shape: MatchWithValueHandlers, - Circle: CircleArea, - Rectangle: RectangleArea, - } - >, + open ComputerComponent; + + @ComputerComponent. Code.Shape: MatchWithValueHandlers, + @ComputerComponent. Code.Circle: CircleArea, + @ComputerComponent. Code.Rectangle: RectangleArea, } } ``` -`UseInputDelegate` selects a provider by the input type. A call to `app.compute(code, shape)` first -reaches `MatchWithValueHandlers`. The matcher extracts the current variant's payload and delegates -it through the same context: a `Circle` reaches `CircleArea`, and a `Rectangle` reaches -`RectangleArea`. The application does not write a `match` over `Shape`. +The [`open` statement](/docs/reference/macros/delegate_components#choosing-a-provider-per-type-the-open-statement) +keys each entry by one path segment per type parameter of `CanCompute`. The first +segment, ` Code`, matches any code, so the second segment selects a provider by the input type +alone. A call to `app.compute(code, shape)` first reaches `MatchWithValueHandlers`. The matcher +extracts the current variant's payload and delegates it through the same context: a `Circle` reaches +`CircleArea`, and a `Rectangle` reaches `RectangleArea`. The application does not write a `match` +over `Shape`. The matcher tracks unhandled variants through the extractor's remainder type. Each extraction attempt returns either a payload to handle or a remainder that excludes that variant. The next diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 583c1e9d..8cfbb39e 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -148,9 +148,12 @@ delegate_components! { `ComputeNegated`. This table names a code tag followed by the input type for each entry, so the compiler can resolve the requested pair. -Input-driven dispatch can instead use `UseInputDelegate` with a table keyed by input type. -[Dispatching](./dispatching.md) uses that form to route an enum and its payloads to different -providers. The tag can also describe a larger program, as in [type-level DSLs](./type-level-dsls.md). +Dispatch on the input alone uses a generic first segment: `@ComputerComponent. Code.i64` +matches every code and selects by the input type. [Dispatching](./dispatching.md) uses that form to +route an enum and its payloads to different providers. A shorter or generic key covers every key it +matches, so that entry could not share a table with the two above, since it also covers +`@ComputerComponent.Doubled.i64`. The tag can also describe a larger program, as in +[type-level DSLs](./type-level-dsls.md). ## What it costs diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index d0755e0e..1f33eaad 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -165,17 +165,17 @@ dispatch on the same parameter and resolve to the same implementations. [`delegate_components!`](../macros/delegate_components.md), which needs neither an attribute nor a table type. -A few situations still involve the attribute, and only the dispatcher that `open` cannot express is a -reason to write it. +A few situations still involve the attribute, though none of them is a reason to write it on a new +component. - **Keeping compatibility with existing wiring.** The attribute makes `UseDelegate` wiring possible, so removing it from a published component is a breaking change for any downstream user who wires that way. Removing it is still the right direction, but it is a breaking change to schedule rather than a cleanup to make in passing. -- **A dispatcher `open` cannot express.** `open` resolves through the `RedirectLookup` impl a component - generates, which keys on the parameter that impl dispatches on. A *second*, independently keyed - dispatcher, the `UseInputDelegate` case above, has no `open` equivalent, so a component wanting - one still declares it here. +- **Dispatch on a later parameter.** This needs no attribute either. The `RedirectLookup` impl that + `open` resolves through appends every type parameter of the component to the lookup path, so a key + with one segment per parameter dispatches on any of them. `@ComputerComponent. Code.Circle` + selects by the input whatever the code, which is what a `UseInputDelegate` table does. - **Reading existing code.** CGP's own error and handler components are defined with this attribute, so `UseDelegate` tables appear in wiring you did not write. Understanding the form matters more than being able to author it. diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index d0cf1d7a..f79f8d51 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -292,6 +292,36 @@ Braces are optional when opening a single component, so `open AreaCalculatorComp `open { AreaCalculatorComponent };` are the same. The braced list is needed to open several at once, and the macro rejects a braceless header naming more than one component. +**A key has one path segment per type parameter of the component, so `open` dispatches on any of +them.** The redirect appends every type parameter to the lookup path, in declaration order, so a +lookup of `CanCompute` follows `@ComputerComponent.Code.Input`. A key that stops after +the first segment matches that value of the first parameter with every value of the rest, and a +per-entry generic in a segment matches any value there. A handler can therefore be chosen by its +input alone, by its code alone, or by both: + +```rust +delegate_components! { + MyApp { + open ComputerComponent; + + @ComputerComponent. Code.Circle: DescribeCircle, + @ComputerComponent.Area.Rectangle: RectangleArea, + @ComputerComponent.Perimeter.Rectangle: RectanglePerimeter, + } +} +``` + +A `Circle` input reaches `DescribeCircle` whatever code the caller passes, while a `Rectangle` input +is dispatched on both parameters. This replaces the legacy +[`UseInputDelegate`](../providers/handler/use_input_delegate.md) table, and a +[`UseDelegate`](../providers/use_delegate.md) table nested around `UseInputDelegate` tables. + +**A shorter key covers every longer key beneath it.** Each key ends in a wildcard, and a generic +segment matches every value in its position. So `@ComputerComponent.Area` overlaps +`@ComputerComponent.Area.Rectangle`, and it also overlaps `@ComputerComponent. Code.Circle`, +which covers `Area` among its codes. Within one table, key a first-parameter value either on its own +or per later parameter, never both. + `open` does not need an extra attribute on the component, because it works through the [`RedirectLookup`](../providers/redirect_lookup.md) impl that every `#[cgp_component]` already generates. It is a lightweight special case of the full [namespace](./cgp_namespace.md) feature, suited @@ -692,8 +722,10 @@ names an unresolved type rather than anything about wiring. **Two entries claiming one key conflict**, and the compiler reports it as a [coherence](/docs/reference/glossary#coherence) error rather than as a wiring one. This covers the obvious duplicate, an `open` header colliding with an explicit mapping -for the same component, and a generic ` AreaCalculatorComponent` entry overlapping a -specific `AreaCalculatorComponent` one. The same applies to a direct entry for a path a +for the same component, a generic ` AreaCalculatorComponent` entry overlapping a +specific `AreaCalculatorComponent` one, and a path key covering a longer one, as +`@ComputerComponent.Area` beside `@ComputerComponent.Area.Rectangle` or +`@ComputerComponent. Code.Circle`. The same applies to a direct entry for a path a joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#common-mistakes). ## Related constructs diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index de5a783f..5cf80fab 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -30,26 +30,27 @@ The borrowed and multi-argument variants are `MatchWithValueHandlersRef` (over ` ## Usage It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one optional type parameter, the -per-variant provider, and is most often wired through -[`UseInputDelegate`](../handler/use_input_delegate.md) so it is selected when the input is a given enum: +per-variant provider, and is most often wired by input type with the +[`open` statement](../../macros/delegate_components.md#choosing-a-provider-per-type-the-open-statement), +so it is selected when the input is a given enum: ```rust delegate_components! { App { - ComputerComponent: UseInputDelegate, + open ComputerComponent; + + @ComputerComponent. Code.[Circle, Rectangle]: ComputeArea, + @ComputerComponent. Code.Shape: MatchWithValueHandlers, } } ``` -A `Circle` input is handled directly by `ComputeArea`, while a `Shape` input is handled by -`MatchWithValueHandlers`, which synthesizes an adapter for each variant and routes each payload back -through the context's own `ComputerComponent`, so the `Circle` and `Rectangle` payloads reach -`ComputeArea` after all. `UseInputDelegate` is the correct wiring here because it keys on the input -type; it has no `open`-statement equivalent. +Each key has one segment per type parameter of `CanCompute`, and the generic first +segment matches any code, so the second selects by the input type. A `Circle` input is handled +directly by `ComputeArea`, while a `Shape` input is handled by `MatchWithValueHandlers`, which +synthesizes an adapter for each variant and routes each payload back through the context's own +`ComputerComponent`, so the `Circle` and `Rectangle` payloads reach `ComputeArea` after all. Older +code wires the same dispatch as a [`UseInputDelegate`](../handler/use_input_delegate.md) table. ## When to use it diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md index aa99db3d..96531391 100644 --- a/docs/reference/providers/handler/index.md +++ b/docs/reference/providers/handler/index.md @@ -66,7 +66,8 @@ wire automatically: **Input dispatch** chooses a handler by the type of the value: -- [`UseInputDelegate`](use_input_delegate.md) keys a lookup table on the handler's `Input` type. +- [`UseInputDelegate`](use_input_delegate.md) keys a lookup table on the handler's `Input` type. It is + the legacy form; the `open` statement of `delegate_components!` dispatches on the input directly. ## Related constructs diff --git a/docs/reference/providers/handler/use_input_delegate.md b/docs/reference/providers/handler/use_input_delegate.md index 09a2add6..b7da1672 100644 --- a/docs/reference/providers/handler/use_input_delegate.md +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -19,7 +19,10 @@ input-specific providers. Like every CGP provider, it holds no runtime value; th It is the sibling of [`UseDelegate`](../use_delegate.md). Where `UseDelegate` keys on the first generic parameter of a provider trait, the `Code` for a handler, `UseInputDelegate` keys on the `Input` parameter, so the provider that handles a value is chosen by the type of that value. The handler -components enable both dispatchers at once. +components enable both dispatchers at once. Both are legacy forms: the `open` statement of +[`delegate_components!`](../../macros/delegate_components.md#choosing-a-provider-per-type-the-open-statement) +dispatches on the code, the input, or both with no table type, as the next section shows for the +input. ## Usage @@ -40,18 +43,30 @@ delegate_components! { ``` The outer entry routes the handler component to `UseInputDelegate`, and the inner table -maps each input type to the provider responsible for it. Unlike the per-`Code` dispatch of -[`UseDelegate`](../use_delegate.md), input dispatch has no `open`-statement equivalent, so the nested -table is the current form rather than a legacy one. +maps each input type to the provider responsible for it. The current form stores the same entries on +the context with `open`. Each key has one path segment per type parameter of +`CanCompute`, and a generic first segment matches any code, so the second selects by the +input type: + +```rust +delegate_components! { + App { + open ComputerComponent; + + @ComputerComponent. Code.Circle: ComputeCircleArea, + @ComputerComponent. Code.Rectangle: ComputeRectangleArea, + } +} +``` ## When to use it -**Reach for `UseInputDelegate` when a handler should run a different provider depending on the type of -its input**, which is common in the [dispatch combinators](../dispatch/index.md), where a matcher routes -each variant of an enum to a handler chosen by the payload type. For dispatch on the `Code` selector -rather than the input, use the `open` statement of -[`delegate_components!`](../../macros/delegate_components.md), or the legacy -[`UseDelegate`](../use_delegate.md) it supersedes. +**Read `UseInputDelegate` when you meet it in existing code, and write the `open` form instead.** +Dispatch by input type is common with the [dispatch combinators](../dispatch/index.md), where a matcher +routes each variant of an enum to a handler chosen by the payload type, and `open` expresses it +without a table type. The table form still works, since every handler component keeps the +`#[derive_delegate(UseInputDelegate)]` that generates it, so existing wiring does not need to +change. ## Under the hood diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 6beb41c0..7150c4f6 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -122,8 +122,9 @@ defined with [`#[derive_delegate]`](../attributes/derive_delegate.md), including handler families. The dispatching-per-type choice is worked through in [`#[derive_delegate]`](../attributes/derive_delegate.md). -For dispatching on the *input* type of a handler rather than a `Code` parameter, the sibling provider is -[`UseInputDelegate`](handler/use_input_delegate.md). +For dispatching on the *input* type of a handler rather than a `Code` parameter, the legacy sibling +provider is [`UseInputDelegate`](handler/use_input_delegate.md). The `open` statement covers that case +too, with a key that has one path segment per type parameter. ## Under the hood diff --git a/example-code/tests/concepts/dispatching.rs b/example-code/tests/concepts/dispatching.rs index e931474f..2b6f6d2f 100644 --- a/example-code/tests/concepts/dispatching.rs +++ b/example-code/tests/concepts/dispatching.rs @@ -6,7 +6,7 @@ pub mod matching_one_handler_per_variant { use cgp::core::error::ErrorTypeProviderComponent; use cgp::extra::dispatch::MatchWithValueHandlers; - use cgp::extra::handler::{ComputerComponent, UseInputDelegate}; + use cgp::extra::handler::ComputerComponent; use cgp::prelude::*; #[derive(CgpData)] @@ -38,19 +38,17 @@ pub mod matching_one_handler_per_variant { delegate_components! { App { + open ComputerComponent; + ErrorTypeProviderComponent: UseType, - ComputerComponent: UseInputDelegate< - // The whole enum routes to the matcher; each variant's payload routes to its own - // handler. No indirection is needed here — a *recursive* language, where a - // variant's payload contains the enum again, is the case that needs a thin - // wrapper between the two to break the resolution cycle. - new AreaComponents { - Shape: MatchWithValueHandlers, - Circle: CircleArea, - Rectangle: RectangleArea, - } - >, + // The whole enum routes to the matcher; each variant's payload routes to its own + // handler. No indirection is needed here — a *recursive* language, where a variant's + // payload contains the enum again, is the case that needs a thin wrapper between the + // two to break the resolution cycle. + @ComputerComponent. Code.Shape: MatchWithValueHandlers, + @ComputerComponent. Code.Circle: CircleArea, + @ComputerComponent. Code.Rectangle: RectangleArea, } } diff --git a/example-code/tests/reference/macros/delegate_components.rs b/example-code/tests/reference/macros/delegate_components.rs index f1def9bf..fa3aceba 100644 --- a/example-code/tests/reference/macros/delegate_components.rs +++ b/example-code/tests/reference/macros/delegate_components.rs @@ -420,6 +420,91 @@ pub mod choosing_a_provider_per_type_the_open_statement { ], } } + + /// A component with two type parameters, dispatched on the input alone and on both parameters + /// in one table. Its own module, so its provider names do not clash with the ones above. + pub mod later_parameters { + use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::prelude::*; + + pub struct Area; + pub struct Perimeter; + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(new DescribeCircle)] + impl Computer { + type Output = f64; + + fn compute(&self, _code: PhantomData, circle: Circle) -> f64 { + circle.radius + } + } + + #[cgp_impl(new RectangleArea)] + impl Computer { + type Output = f64; + + fn compute(&self, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + #[cgp_impl(new RectanglePerimeter)] + impl Computer { + type Output = f64; + + fn compute(&self, _code: PhantomData, rectangle: Rectangle) -> f64 { + 2.0 * (rectangle.width + rectangle.height) + } + } + + pub struct MyApp; + + delegate_components! { + MyApp { + open ComputerComponent; + + @ComputerComponent. Code.Circle: DescribeCircle, + @ComputerComponent.Area.Rectangle: RectangleArea, + @ComputerComponent.Perimeter.Rectangle: RectanglePerimeter, + } + } + + check_components! { + MyApp { + ComputerComponent: [ + (Area, Circle), + (Perimeter, Circle), + (Area, Rectangle), + (Perimeter, Rectangle), + ], + } + } + + #[test] + fn the_input_or_both_parameters_select_the_provider() { + use cgp::extra::handler::CanCompute; + + let app = MyApp; + let rectangle = || Rectangle { + width: 2.0, + height: 3.0, + }; + + assert_eq!(app.compute(PhantomData::, Circle { radius: 1.5 }), 1.5); + assert_eq!(app.compute(PhantomData::, Circle { radius: 1.5 }), 1.5); + assert_eq!(app.compute(PhantomData::, rectangle()), 6.0); + assert_eq!(app.compute(PhantomData::, rectangle()), 10.0); + } + } } /// ## Statements come first diff --git a/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs index 44ec6e71..4697ec3d 100644 --- a/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs @@ -3,7 +3,7 @@ /// ## Usage and Examples /// /// `MatchWithValueHandlers` builds the per-variant handler list from the enum's own fields and passes -/// each payload as a bare value. Wired through `UseInputDelegate`, it is selected when the input is a +/// each payload as a bare value. Wired by input type with `open`, it is selected when the input is a /// `Shape`, and each payload routes back through the context's own `ComputerComponent` to its handler. pub mod matching_by_value { use core::convert::Infallible; @@ -11,7 +11,7 @@ pub mod matching_by_value { use cgp::core::error::ErrorTypeProviderComponent; use cgp::extra::dispatch::MatchWithValueHandlers; - use cgp::extra::handler::{Computer, ComputerComponent, UseInputDelegate}; + use cgp::extra::handler::{Computer, ComputerComponent}; use cgp::prelude::*; #[derive(CgpData)] @@ -51,13 +51,12 @@ pub mod matching_by_value { delegate_components! { App { + open ComputerComponent; + ErrorTypeProviderComponent: UseType, - ComputerComponent: UseInputDelegate, + @ComputerComponent. Code.[Circle, Rectangle]: ComputeArea, + @ComputerComponent. Code.Shape: MatchWithValueHandlers, } } diff --git a/example-code/tests/reference/providers/handler/use_input_delegate.rs b/example-code/tests/reference/providers/handler/use_input_delegate.rs index 3cde51a9..cc83d900 100644 --- a/example-code/tests/reference/providers/handler/use_input_delegate.rs +++ b/example-code/tests/reference/providers/handler/use_input_delegate.rs @@ -48,6 +48,28 @@ pub mod dispatching_on_the_input_type { } } + /// The same dispatch in the current form, with `open` keys whose generic first segment matches + /// any code. The page names the providers `ComputeCircleArea` and `ComputeRectangleArea`. + pub struct OpenApp; + + delegate_components! { + OpenApp { + open ComputerComponent; + + @ComputerComponent. Code.Circle: CircleArea, + @ComputerComponent. Code.Rectangle: RectangleArea, + } + } + + mod check_open_app { + use super::*; + check_components! { + OpenApp { + ComputerComponent: [((), Circle), ((), Rectangle)], + } + } + } + #[test] fn each_input_reaches_its_own_handler() { use cgp::extra::handler::CanCompute; From 4191b5d1015e125cc42b8db46324728d25ff8feb Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 02:41:37 +0000 Subject: [PATCH 098/516] Correct the promotion bundle and monad transformer claims PromoteTryComputer starts from a Computer returning Result, PromoteRef passes a borrow to an owned-input base rather than dereferencing, a bundle's parameter must be wired to the bundle, and OkMonadicTrans over ErrMonadic stops on an outer Err or an inner Ok. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/providers/handler/index.md | 4 ++-- docs/reference/providers/handler/promote_computer.md | 11 +++++++---- .../providers/handler/promote_try_computer.md | 10 +++++----- docs/reference/providers/monad/index.md | 10 +++++----- 4 files changed, 19 insertions(+), 16 deletions(-) diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md index 96531391..36d55114 100644 --- a/docs/reference/providers/handler/index.md +++ b/docs/reference/providers/handler/index.md @@ -33,8 +33,8 @@ operation, and an input, producing an associated `Output`. The members differ on Each of the first four has a `…Ref` companion whose method takes the input by reference. The promotion combinators trade on the natural orderings among these: a `Computer` is also a valid `TryComputer` and a -valid `AsyncComputer`, a `TryComputer` is a valid `Handler`, and a value handler can serve a reference -handler by dereferencing. +valid `AsyncComputer`, a `TryComputer` is a valid `Handler`, and a reference handler can serve a value +handler by dereferencing the input. ## The combinators, by role diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md index 82f0f76c..fd6ad137 100644 --- a/docs/reference/providers/handler/promote_computer.md +++ b/docs/reference/providers/handler/promote_computer.md @@ -13,9 +13,12 @@ Fill in every member of the handler family from a provider that implements `Comp **You are not expected to name `PromoteComputer` directly.** [`#[cgp_computer]`](../../macros/cgp_computer.md) wires it across the family for the provider it -generates, so one written `Computer` impl answers the whole handler surface. You name -`PromoteComputer` by hand only when wiring a hand-written computer's family explicitly. This -page explains what that wiring emits. +generates, so one written `Computer` impl answers the whole handler surface. A bundle +expects its parameter to be a provider wired to that same bundle, as the macro does with `Self`, because +some entries reach the base through a sibling: the `Handler` entry is `PromoteAsync`, which +needs `Provider` to be a `TryComputer`. To lift a hand-written `Computer` without wiring it to the +bundle, chain the one-step adapters, as in `PromoteAsync>`. This page explains what +the bundle emits. ::: @@ -61,7 +64,7 @@ from a `TryComputer`, [`PromoteProducer`](promote_producer.md) from a `Producer` `PromoteComputer` is defined with [`delegate_components!`](../../macros/delegate_components.md) over a generic inner `Provider`. It routes the fallible slot to [`Promote`](promote.md) (wrap in `Ok`), the async slots to [`PromoteAsync`](promote_async.md) (run synchronously in an async method), and every -`…Ref` slot to [`PromoteRef`](promote_ref.md) (dereference, then defer to the base): +`…Ref` slot to [`PromoteRef`](promote_ref.md) (pass the borrow to the base as its input): ```rust delegate_components! { diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md index 61ce6374..645ef82e 100644 --- a/docs/reference/providers/handler/promote_try_computer.md +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -19,15 +19,15 @@ that implements the fallible synchronous base. You name it by hand only when wir ## Overview -`PromoteTryComputer` starts from a provider that implements `TryComputer`, the synchronous -fallible base, and fills in the rest of the handler family on a **context**, the type a method runs -on. It first turns the fallible base into a plain computer, then derives the rest of the family +`PromoteTryComputer` starts from a `Computer` whose output is a `Result`, the base +[`#[cgp_computer]`](../../macros/cgp_computer.md) generates for a function returning `Result`, and fills in the rest of the handler family on a **context**, the type a method runs +on. It turns that base into a `TryComputer` through [`TryPromote`](try_promote.md), then derives the rest of the family from there. Like every CGP provider, it carries no runtime value. ## Usage It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base -`TryComputer` provider: +provider, a `Computer` returning `Result`: ```rust delegate_components! { @@ -39,7 +39,7 @@ delegate_components! { ## When to use it -**Reach for `PromoteTryComputer` when the base provider is a synchronous fallible `TryComputer`** and +**Reach for `PromoteTryComputer` when the base provider is a synchronous `Computer` returning `Result`** and you wire its family by hand. For a plain `Computer` base use [`PromoteComputer`](promote_computer.md); for the other bases use [`PromoteProducer`](promote_producer.md), [`PromoteAsyncComputer`](promote_async_computer.md), or [`PromoteHandler`](promote_handler.md). diff --git a/docs/reference/providers/monad/index.md b/docs/reference/providers/monad/index.md index beb2406e..3c1f5092 100644 --- a/docs/reference/providers/monad/index.md +++ b/docs/reference/providers/monad/index.md @@ -45,11 +45,11 @@ exactly when you expected it to stop: **`OkMonadic` continues on `Err`, and `Err `Ok`**. `ErrMonadic` is the one that behaves like `?`. **`OkMonadicTrans`** and **`ErrMonadicTrans`** are transformer forms that apply the same behavior -on top of a base monad `M`, so monads can stack over nested result types. Writing -`OkMonadicTrans` builds a monad that short-circuits on an outer `Ok` while threading an -inner `Result` through the err monad beneath it. A single layer of branching needs no explicit -transformer, because the bare markers produce their own transformer form over `IdentMonadic` when used -as transformers. The trait layer that gives a marker its meaning is documented under +on top of a base monad `M`, so monads can stack over nested result types. In +`OkMonadicTrans`, the err monad handles the outer `Result` of each output and the ok layer +the inner one, so over `Result, E2>` it stops on an outer `Err` or an inner `Ok` and +continues with the `E1` of an `Ok(Err(e1))`. A single layer of branching needs no explicit +transformer: used on its own, each bare marker binds as its transformer over `IdentMonadic`. The trait layer that gives a marker its meaning is documented under [`MonadicBind`](../../traits/monad/monadic_bind.md) and [`MonadicTrans`](../../traits/monad/monadic_trans.md). ## Related constructs From 692c611eb1cba81af7116e6f54d10eab42a3ce2c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 02:50:19 +0000 Subject: [PATCH 099/516] Remove the DelegateComponent on_unimplemented claim The attribute was removed from cgp; a missed lookup is the plain DelegateComponent error, which cargo cgp check turns into a CGP message. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../traits/wiring/delegate_component.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index 33694922..278b9b4b 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -47,14 +47,9 @@ walks. One trait covers both, which is why it underlies both ordinary wiring and ## Definition -`DelegateComponent` carries a single associated type and no method, and it wears a diagnostic attribute -that shapes the error when a lookup misses: +`DelegateComponent` carries a single associated type and no method: ```rust -#[diagnostic::on_unimplemented( - message = "{Self} does not contain any DelegateComponent entry for {Key}", - note = "You might want to implement the provider trait for {Key} on {Self}" -)] pub trait DelegateComponent { type Delegate; } @@ -64,9 +59,9 @@ pub trait DelegateComponent { looked up, and it is `?Sized` so that an unsized marker can serve as one. `Delegate` is the value stored at that key, the provider or the further table the entry resolves to. There is no method and no data; the trait only associates one value type with one key type on a carrier type, so the whole lookup happens -while the compiler type-checks. The `#[diagnostic::on_unimplemented]` attribute reports a missed lookup as -a missing *entry* rather than an opaque "trait not implemented", one of the few diagnostics CGP improves -without a tool. +while the compiler type-checks. A missed lookup is reported as the plain +``the trait `DelegateComponent` is not implemented for `App` ``, which names the missing +entry; [`cargo cgp check`](/docs/cargo-cgp/check) turns such errors into CGP-specific messages. ## Usage @@ -205,9 +200,7 @@ The trait is the plainest thing in CGP (one associated type, no method), so the reads it. The provider blanket impl generated by [`#[cgp_component]`](../../macros/cgp_component.md) is the reader, and its body is itself a table lookup: it bounds the provider on `DelegateComponent` and forwards each method to `>::Delegate`. So the "routing" is -literally the projection, and the call it forwards to is resolved statically and inlined. The -[`#[diagnostic::on_unimplemented]`](#definition) message shown above turns an unwired component into a -readable missing-*entry* error rather than an opaque unimplemented trait. +literally the projection, and the call it forwards to is resolved statically and inlined. Two further facts about the generated impls are worth carrying away. Each entry is emitted **alongside** an [`IsProviderFor`](./is_provider_for.md) impl that forwards the chosen provider's requirements, so the entry From 1240390bf4d6e287a2b520a4aac3948f7725d02f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 04:25:02 +0000 Subject: [PATCH 100/516] Add the Projects section with the Hypershell pages Add a Projects category between Reference and cargo-cgp, with a section index and 21 Hypershell pages: an overview, eleven example pages written as short tutorials, four architecture pages, the writing and debugging guides, and a limitations page of high-level limits. Renumber the categories below it, and link the section from Resources. Every snippet was checked against the hypershell v0.8.0 source, and every quoted diagnostic was re-run with cargo-cgp built from source. Co-Authored-By: Claude Opus 5.5 --- docs/ai/_category_.json | 2 +- docs/cargo-cgp/_category_.json | 2 +- docs/contribute.md | 2 +- docs/projects/_category_.json | 8 + docs/projects/hypershell/_category_.json | 8 + .../hypershell/architecture/_category_.json | 8 + .../architecture/abstract-syntax.md | 113 +++++++ .../hypershell/architecture/assembly.md | 167 +++++++++++ .../hypershell/architecture/crate-layout.md | 75 +++++ .../projects/hypershell/architecture/index.md | 119 ++++++++ .../streams-and-input-dispatch.md | 164 ++++++++++ .../hypershell/examples/_category_.json | 8 + .../hypershell/examples/bluesky-websocket.md | 173 +++++++++++ docs/projects/hypershell/examples/bluesky.md | 107 +++++++ .../hypershell/examples/github-issues.md | 139 +++++++++ .../hypershell/examples/hello-name.md | 170 +++++++++++ docs/projects/hypershell/examples/hello.md | 163 ++++++++++ .../hypershell/examples/http-checksum-cli.md | 150 ++++++++++ .../examples/http-checksum-client.md | 172 +++++++++++ .../examples/http-checksum-native.md | 187 ++++++++++++ docs/projects/hypershell/examples/index.md | 78 +++++ .../hypershell/examples/nix-manual.md | 126 ++++++++ .../hypershell/examples/rust-playground.md | 141 +++++++++ .../hypershell/examples/save-webpage.md | 108 +++++++ .../hypershell/guides/_category_.json | 8 + docs/projects/hypershell/guides/debugging.md | 279 ++++++++++++++++++ .../hypershell/guides/writing-a-program.md | 161 ++++++++++ docs/projects/hypershell/index.md | 176 +++++++++++ docs/projects/hypershell/limitations.md | 87 ++++++ docs/projects/index.md | 56 ++++ docs/resources.md | 4 +- 31 files changed, 3156 insertions(+), 5 deletions(-) create mode 100644 docs/projects/_category_.json create mode 100644 docs/projects/hypershell/_category_.json create mode 100644 docs/projects/hypershell/architecture/_category_.json create mode 100644 docs/projects/hypershell/architecture/abstract-syntax.md create mode 100644 docs/projects/hypershell/architecture/assembly.md create mode 100644 docs/projects/hypershell/architecture/crate-layout.md create mode 100644 docs/projects/hypershell/architecture/index.md create mode 100644 docs/projects/hypershell/architecture/streams-and-input-dispatch.md create mode 100644 docs/projects/hypershell/examples/_category_.json create mode 100644 docs/projects/hypershell/examples/bluesky-websocket.md create mode 100644 docs/projects/hypershell/examples/bluesky.md create mode 100644 docs/projects/hypershell/examples/github-issues.md create mode 100644 docs/projects/hypershell/examples/hello-name.md create mode 100644 docs/projects/hypershell/examples/hello.md create mode 100644 docs/projects/hypershell/examples/http-checksum-cli.md create mode 100644 docs/projects/hypershell/examples/http-checksum-client.md create mode 100644 docs/projects/hypershell/examples/http-checksum-native.md create mode 100644 docs/projects/hypershell/examples/index.md create mode 100644 docs/projects/hypershell/examples/nix-manual.md create mode 100644 docs/projects/hypershell/examples/rust-playground.md create mode 100644 docs/projects/hypershell/examples/save-webpage.md create mode 100644 docs/projects/hypershell/guides/_category_.json create mode 100644 docs/projects/hypershell/guides/debugging.md create mode 100644 docs/projects/hypershell/guides/writing-a-program.md create mode 100644 docs/projects/hypershell/index.md create mode 100644 docs/projects/hypershell/limitations.md create mode 100644 docs/projects/index.md diff --git a/docs/ai/_category_.json b/docs/ai/_category_.json index 204966aa..20b1b6dc 100644 --- a/docs/ai/_category_.json +++ b/docs/ai/_category_.json @@ -1,6 +1,6 @@ { "label": "AI Assisted Development", - "position": 11, + "position": 12, "link": { "type": "generated-index", "description": "CGP's published agent skill, for handing to a coding assistant, and how the project discloses its own use of AI." diff --git a/docs/cargo-cgp/_category_.json b/docs/cargo-cgp/_category_.json index fbd8d827..7de5623a 100644 --- a/docs/cargo-cgp/_category_.json +++ b/docs/cargo-cgp/_category_.json @@ -1,6 +1,6 @@ { "label": "cargo-cgp", - "position": 8, + "position": 9, "link": { "type": "doc", "id": "cargo-cgp/index" diff --git a/docs/contribute.md b/docs/contribute.md index 59b1e490..d5a798de 100644 --- a/docs/contribute.md +++ b/docs/contribute.md @@ -1,5 +1,5 @@ --- -sidebar_position: 10 +sidebar_position: 11 --- # Contribute to CGP diff --git a/docs/projects/_category_.json b/docs/projects/_category_.json new file mode 100644 index 00000000..5553e048 --- /dev/null +++ b/docs/projects/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Projects", + "position": 8, + "link": { + "type": "doc", + "id": "projects/index" + } +} diff --git a/docs/projects/hypershell/_category_.json b/docs/projects/hypershell/_category_.json new file mode 100644 index 00000000..12f3231e --- /dev/null +++ b/docs/projects/hypershell/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Hypershell", + "position": 1, + "link": { + "type": "doc", + "id": "projects/hypershell/index" + } +} diff --git a/docs/projects/hypershell/architecture/_category_.json b/docs/projects/hypershell/architecture/_category_.json new file mode 100644 index 00000000..66c2f863 --- /dev/null +++ b/docs/projects/hypershell/architecture/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Architecture", + "position": 2, + "link": { + "type": "doc", + "id": "projects/hypershell/architecture/index" + } +} diff --git a/docs/projects/hypershell/architecture/abstract-syntax.md b/docs/projects/hypershell/architecture/abstract-syntax.md new file mode 100644 index 00000000..09b73bba --- /dev/null +++ b/docs/projects/hypershell/architecture/abstract-syntax.md @@ -0,0 +1,113 @@ +--- +sidebar_label: 'Abstract syntax' +sidebar_position: 1 +description: 'What a Hypershell program is made of: empty Rust structs that name what to do, the four kinds of syntax, and the macro that gives them a shell-like look.' +--- + +# Abstract syntax + +Why would anyone write a program as a Rust type made of empty structs? Because a program that +contains no code can be given its meaning by something else, and changed without being edited. +[Hypershell](../index.md) is a small shell-scripting language built with [CGP](/docs/). This page +shows what a Hypershell program is made of, the kinds of pieces it can contain, and the macro that +lets it be written like a shell pipeline. + +## A piece of syntax is an empty struct + +Every piece of a Hypershell program is a struct with no fields and no methods. Its type parameters +hold the parts nested inside it, stored in `PhantomData` so the struct stays empty: + +```rust +pub struct SimpleExec(pub PhantomData<(Path, Args)>); + +pub struct StreamToStdout; +``` + +`SimpleExec` means "run the command `Path` with the arguments `Args`", and `Path` and +`Args` are themselves pieces of syntax. So a whole program is one large nested type, and nothing in +it says *how* to run a command or print a stream. That is left to the providers the running context +chooses, as the [overview](./index.md) explains. Replace the provider for `SimpleExec`, and every +program that uses `SimpleExec` behaves differently, without any program being edited. + +A program is also never created as a value. It is passed to a context as `PhantomData::`, a +zero-sized marker that carries only the type. The only data that flows at run time is the program's +input, such as the bytes fed to the first command. + +## Four kinds of syntax + +Hypershell's syntax falls into four kinds. They nest inside each other, and each kind is interpreted +by its own kind of provider: + +| Kind | What it does | Examples | +|---|---|---| +| **Stages** | take an input and produce an output, like the commands in a shell pipeline | `SimpleExec`, `StreamingExec`, `SimpleHttpRequest`, `ReadFile`, `WriteFile`, `EncodeJson`, `StreamToStdout` | +| **Arguments** | produce one value for a stage: a string, a path, a URL, or an HTTP method | `StaticArg<"echo">`, `FieldArg<"url">`, `JoinArgs[…]`, `UrlEncodeArg<…>`, `GetMethod` | +| **Argument lists** | configure a command or a request | `WithArgs[…]`, `WithStaticArgs[…]`, `WithHeaders[…]` | +| **Control** | combine other programs | `Pipe`, which the `\|` builds, and `Use`, `ConvertTo`, `Box` | + +The arguments are worth a closer look, because they are how a program gets values it cannot contain. +A literal such as a command name is a `StaticArg`. A value known only at run time, such as a URL, +lives in a field of the context, and `FieldArg<"url">` reads it; see +[`hello_name`](../examples/hello-name.md). Arguments nest, so `UrlEncodeArg>` reads +a field and encodes it for use in a URL. + +Some syntax exists for the language's own use rather than for programs. Both command stages, for +instance, start their process through one shared internal step, which is written as syntax too, so +that a single provider decides how every command is started. + +## The macro only changes the notation + +Writing nested types by hand is tiring, so the `hypershell!` macro accepts a shell-like notation and +rewrites it into the type. It follows three rules: `|` joins stages into a pipeline, a bracketed +list after a name becomes a type-level list, and a string literal becomes a type-level string. So +this program + +```rust +pub type Program = hypershell! { + SimpleExec< + StaticArg<"echo">, + WithStaticArgs["hello", "world!"], + > + | StreamToStdout +}; +``` + +is exactly this type, which can be written without the macro: + +```rust +pub type Program = Pipe, + WithStaticArgs, + >, + StreamToStdout, +]>; +``` + +[`Product!`](/docs/reference/macros/product) and [`Symbol!`](/docs/reference/macros/symbol) are +CGP's type-level list and string. The macro knows nothing about what `SimpleExec` means, which is +deliberate: the language works without the macro, and new syntax can be added without changing it. + +## What it costs + +A program that is a type is checked and fixed at compile time. That is the benefit, since a +mismatched pipeline is a compile error rather than a failure halfway through a run, and it is also +the limit, since a program cannot be read from a file or changed while an application runs. Programs +that must change at run time are better expressed as data, run by a shell or by a plain Rust +function. + +Large nested types also cost compile time, and when something is wrong the compiler reports the +whole type, so error messages are long. The macro's output also needs `hypershell::prelude::*` in +scope, which every example imports. + +## Where to go next + +- [Assembly](./assembly.md): how a context gets a provider for every piece of syntax. +- [`hello`](../examples/hello.md): the program above, run. +- [Type-level DSLs](/docs/concepts/type-level-dsls): the same technique with a smaller language. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/architecture/assembly.md b/docs/projects/hypershell/architecture/assembly.md new file mode 100644 index 00000000..bafe3831 --- /dev/null +++ b/docs/projects/hypershell/architecture/assembly.md @@ -0,0 +1,167 @@ +--- +sidebar_label: 'Assembly' +sidebar_position: 2 +description: 'How one line of wiring gives a Hypershell context the whole language: providers gathered into bundles, and bundles into a namespace a context joins.' +--- + +# Assembly + +How does one line of wiring give a context the whole Hypershell language? The language has dozens of +pieces of syntax, and each needs a provider, so something must gather them. +[Hypershell](../index.md) is a small shell-scripting language built with [CGP](/docs/). This page +explains the three layers that do the gathering, how a context can add to them, and how one piece of +syntax is traced through all three to its provider. + +## Three layers, from providers to a context + +The wiring is built up in three layers, each collecting the one below it: + +- **A bundle** collects the providers of one backend. The Tokio bundle knows how to run commands and + read files; the `reqwest` bundle knows how to send HTTP requests. +- **The namespace**, `HypershellNamespace`, collects the bundles into the whole language, and adds + the few choices that are not tied to one backend, such as the error type. +- **A context** joins the namespace, and gets everything it collects. + +The split lets each layer be reused. A bundle can serve any namespace that points at it, and a +namespace serves every context that joins it. The rest of this page takes the layers in turn. + +## A bundle maps syntax to providers + +A bundle is a table, written with CGP's +[`delegate_components!`](/docs/reference/macros/delegate_components), with one entry per piece of +syntax. These two entries are from the Tokio bundle, `HypershellTokioProvider`: + +```rust +@HandlerComponent. SimpleExec: + HandleSimpleExec, + +@HandlerComponent. StreamingExec: + PipeHandlers, +``` + +Each entry reads as "for this syntax, use this provider". `@HandlerComponent` at the start names the +part of CGP that runs stages, CGP's [`Handler`](/docs/reference/components/handler/handler) +interface, so these are the entries for running stages. The first says that `SimpleExec`, whatever +its command and arguments, is run by the provider `HandleSimpleExec`. The `` in front of +it makes the entry cover every `SimpleExec`, the way a generic parameter does in a Rust impl. The +second entry chains three providers for `StreamingExec`, for reasons the +[streams](./streams-and-input-dispatch.md) page explains. + +CGP calls a table like this an [aggregate provider](/docs/concepts/aggregate-providers): a bundle of +choices that other wiring can point at as one unit. Hypershell has one per backend crate: the base +bundle for the control syntax and arguments, and bundles for Tokio, `reqwest`, JSON, and WebSockets. + +## The namespace gathers the bundles + +A [namespace](/docs/concepts/namespaces) is a reusable wiring table that contexts can join. +`HypershellNamespace` routes each group of syntax to the bundle that handles it. This excerpt routes +the Tokio syntax to the Tokio bundle: + +```rust +@cgp.extra.handler.HandlerComponent.[ + SimpleExec, + StreamingExec, + CoreExec, + ReadFile, + WriteFile, + StreamToBytes, + StreamToString, + BytesToStream, + StreamToStdout, + ToTokioAsyncRead, +]: + HypershellTokioProvider, +``` + +The bracketed list gives several pieces of syntax one destination. The long prefix, +`@cgp.extra.handler.HandlerComponent`, is the full name under which CGP registers the part that runs +stages, and a namespace's entries are written with such full names. `CoreExec` in the list is the +internal step both command stages start their process through. + +The namespace also makes the choices that belong to the language as a whole. It sets the error type +to `anyhow::Error`, and it says where to find the HTTP client: in a field named `http_client`, which +is why every context that sends requests has one. + +## A context joins the namespace + +A context joins the namespace with one statement. Hypershell provides two ready-made contexts, which +differ only in their fields: + +```rust +pub struct HypershellCli; + +delegate_components! { + HypershellCli { + namespace HypershellNamespace; + } +} + +#[derive(HasField)] +pub struct HypershellHttp { + pub http_client: Client, +} + +delegate_components! { + HypershellHttp { + namespace HypershellNamespace; + } +} +``` + +A context of your own follows the same pattern, adding a field for each value its programs read. + +A context can also add entries of its own next to the `namespace` statement, to use syntax the +namespace does not include. [`bluesky_websocket`](../examples/bluesky-websocket.md) adds a WebSocket +stage this way. When several contexts need the same additions, a namespace that inherits +`HypershellNamespace` and adds them is the tidier choice, as +[`http_checksum_native`](../examples/http-checksum-native.md) shows. + +## Following one piece of syntax + +Running `SimpleExec` on `HypershellCli` passes through all three layers: + +1. `HypershellCli` has no entry for `SimpleExec` itself, so the question goes to the namespace it + joined. +2. `HypershellNamespace` routes `SimpleExec` to the Tokio bundle. +3. The Tokio bundle maps `SimpleExec` to its provider, `HandleSimpleExec`. +4. `HandleSimpleExec` needs things of its own, such as a way to start a process, and each is found + by the same walk, starting again from the context. + +The compiler does this walk while it type-checks the program, so none of it happens at run time: the +call becomes a direct call to `HandleSimpleExec`. When something along the way is missing, +[`cargo cgp check`](/docs/cargo-cgp/check) prints the same walk step by step, which is what the +[debugging guide](../guides/debugging.md) teaches a reader to follow. + +## What it costs + +The layers make the language easy to reuse and harder to trace. To answer "what runs for +`SimpleExec`?" a reader looks in the context, the namespace, and a bundle, where a plain Rust +program would have one function to read. The walk above is short once it is familiar, but it is +three tables rather than one. + +Adding a piece of syntax to the language means registering it twice, once in a bundle and once in +the namespace, and nothing checks that the two agree until a program uses the new syntax. That is +the price of letting bundles be reused by other namespaces. + +A namespace also fixes the choices it makes. A context that joins `HypershellNamespace` can add +syntax, but it cannot swap the provider for syntax the namespace already covers, such as +`SimpleExec`; CGP treats that as a conflict. The [namespaces](/docs/concepts/namespaces) page +explains the rule. + +## Where to go next + +- [Streams and input dispatch](./streams-and-input-dispatch.md): why some entries chain several + providers. +- [Namespaces](/docs/concepts/namespaces) and [Aggregate + providers](/docs/concepts/aggregate-providers): the CGP ideas behind the layers. +- [`hello`](../examples/hello.md): the one-line context, running a program. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/architecture/crate-layout.md b/docs/projects/hypershell/architecture/crate-layout.md new file mode 100644 index 00000000..07acea66 --- /dev/null +++ b/docs/projects/hypershell/architecture/crate-layout.md @@ -0,0 +1,75 @@ +--- +sidebar_label: 'Crate layout' +sidebar_position: 4 +description: 'Why Hypershell is split into a crate per backend, what each crate adds, what a program file imports, and the nightly toolchain the workspace builds with.' +--- + +# Crate layout + +Why is a small language split into nine crates? So that each backend library lives in a crate of its +own, and a program compiles only the backends it uses. [Hypershell](../index.md) is a small +shell-scripting language built with [CGP](/docs/). This page lists the crates and what each adds, +what a program file imports, and what the workspace needs to build. + +## One crate per backend + +The syntax, and the interfaces its providers implement, live in one crate that depends only on CGP. +Each backend then adds one external library in a crate of its own: + +| Crate | What it adds | +|---|---| +| `hypershell-components` | the syntax, the argument handling, and the control syntax such as `Pipe` | +| `hypershell-tokio-components` | commands, files, and streams, using Tokio | +| `hypershell-reqwest-components` | HTTP requests, using `reqwest` | +| `hypershell-json-components` | JSON encoding and decoding, using `serde_json` | +| `hypershell-hash-components` | checksums, using `sha2` and `hex` | +| `hypershell-tungstenite-components` | WebSockets, using `tokio-tungstenite` | +| `hypershell-macro` | the `hypershell!` macro | +| `hypershell` | the namespace that assembles the language, its error handling, the two ready-made contexts, and the prelude | +| `hypershell-examples` | the runnable examples, and a small extension used by some of them | + +The split works because providers do not name the context they will run on, or its error type. Those +are chosen last, in the `hypershell` crate. So the Tokio crate builds without `reqwest`, and the +JSON crate builds without Tokio. The HTTP and WebSocket crates do depend on the Tokio crate, because +they reuse its stream types. + +The `hypershell` crate does not include the checksum and WebSocket extensions. A program that uses +them adds their crates and joins a larger language, as +[`http_checksum_native`](../examples/http-checksum-native.md) and +[`bluesky_websocket`](../examples/bluesky-websocket.md) show. + +## What a program imports + +A program file needs one import, `hypershell::prelude::*`. It brings the syntax, the `hypershell!` +macro, the two contexts `HypershellCli` and `HypershellHttp`, the `anyhow` error type as `Error`, +and the CGP names a program uses. Two things are imported separately: `HypershellNamespace`, from +`hypershell::namespaces`, which a context of your own joins; and `ToTokioAsyncRead`, from +`hypershell_tokio_components::dsl`, the adapter an HTTP stream needs before `StreamToString`. + +## What the workspace needs to build + +The repository pins nightly Rust in its `rust-toolchain.toml`, and its `.cargo/config.toml` turns on +the compiler's next-generation trait solver with `-Z next-solver=globally`. The setting matters for +the largest programs, the ones that nest whole programs inside others. Checked on stable Rust +without it, the two largest examples grew the compiler to about 7 GB of memory before they were +stopped; on nightly with the new solver, `parallel_compare`, one of the two, checked in about 9 +seconds and 460 MB. Why the solvers differ so much was not investigated. A crate of your own with +large programs should use the same settings. + +## What it costs + +The split keeps each crate's dependencies small, at the price of more crates to depend on: a program +using an extension imports from several Hypershell crates and from the library the extension wraps, +such as `sha2` for checksums. The nightly requirement is the larger cost, because it applies to +every crate that builds Hypershell programs of any size, not only to Hypershell itself. + +## Where to go next + +- [How Hypershell works](./index.md): the design these crates implement. +- [Writing a program](../guides/writing-a-program.md): the imports and toolchain in practice. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/architecture/index.md b/docs/projects/hypershell/architecture/index.md new file mode 100644 index 00000000..52b70192 --- /dev/null +++ b/docs/projects/hypershell/architecture/index.md @@ -0,0 +1,119 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'How Hypershell works, in outline: a program written as a Rust type, a context that decides what each part does, and a language built from reusable parts.' +--- + +# How Hypershell works + +A Hypershell program looks like a shell pipeline, but it is a Rust type, and the compiler turns it +into ordinary function calls. [Hypershell](../index.md) is a small shell-scripting language built +with [CGP](/docs/), a language extension for Rust with pluggable trait implementations at +compile-time. This page explains, in outline, how a type can be a program, what decides what that +program does, and how the language is put together. Each idea has a page of its own with the +details. + +## The program only says what to do + +In a shell script, a pipeline is text. The shell reads it, works out which programs to start, and +connects them. A Hypershell pipeline is written in Rust instead, as a type: + +```rust +pub type Program = hypershell! { + SimpleExec, WithStaticArgs["hello", "world!"]> + | StreamToStdout +}; +``` + +Each name in it, such as `SimpleExec` or `StreamToStdout`, is an empty struct. It records *what* the +program asks for, "run `echo`" and "print the result", and contains no code for doing either. The +`hypershell!` macro only turns the shell-like notation into that type. The [abstract +syntax](./abstract-syntax.md) page describes every kind of piece a program can contain. + +## The context decides how it is done + +Because the program contains no code, something else must supply it. That is the **context**: the +type the program is run on, as in `HypershellCli.handle(PhantomData::, input)`. For each +piece of the program, the context's wiring picks an implementation, called a **provider**. One +provider knows how to run a command, another how to print a stream, another how to send an HTTP +request. + +The compiler makes these choices while it type-checks the program. By the time the program runs, +each piece has become a direct call into its provider, with no interpreter and no lookup at run +time. This is what CGP is for: letting a type choose among implementations of the same interface, +and resolving the choice at compile time. + +The context makes one more choice: the error type. Providers report failures without naming an error +type of their own, and the context decides what those failures become. Hypershell's standard wiring +turns them all into `anyhow::Error`, using CGP's [modular error +handling](/docs/concepts/modular-error-handling). + +Two consequences follow, and they are why the design is interesting. The same program can behave +differently on two contexts that choose different providers. And a new piece of syntax, with a +provider for it, can be added from any crate, without touching the crates that define the language. + +## The language is assembled from reusable parts + +A context does not list a provider for every piece of the language itself. Hypershell supplies its +choices in layers, so that a user's context needs one line: + +```rust +pub struct HypershellCli; + +delegate_components! { + HypershellCli { + namespace HypershellNamespace; + } +} +``` + +Each backend, such as the one that runs processes with Tokio or the one that sends HTTP requests, +publishes its providers as a bundle. `HypershellNamespace` gathers the bundles into the whole +language, and a context that joins it gets everything in it. The [assembly](./assembly.md) page +explains the layers, and how a context can add to them. + +## Stages are typed, and fit together like functions + +Each stage of a pipeline receives the previous stage's output, as in a shell, but here the output +has a Rust type. One stage produces bytes, another a stream, another a decoded JSON value. The +compiler checks that every stage can accept what the one before it produces, and it chooses a +stage's provider by that type as well as by the syntax. Most stages accept both bytes and streams, +so they chain freely. The [streams and input dispatch](./streams-and-input-dispatch.md) page +explains how, and where they do not. + +## Each backend lives in its own crate + +The syntax lives in a crate that depends only on CGP, and each backend (Tokio, `reqwest`, +`serde_json`, and the rest) lives in a crate of its own. A program's crate compiles only the +backends it uses, and no provider names the context or the error type it will run with; those are +chosen last. The [crate layout](./crate-layout.md) page lists the crates and what the workspace +needs to build. + +## What the design costs + +The flexibility is paid for in indirection. To find out what a piece of syntax does, a reader +follows it from the program to the context, to the namespace, to a bundle, and finally to a +provider. The compiler does that in an instant, but a person reading the code, or reading a long +compile error, has to do it too. The [debugging guide](../guides/debugging.md) shows how to read +such an error. + +It also moves work to compile time. A program is fixed when it is compiled, so it cannot be loaded +or changed while an application runs, and large programs make the compiler work hard: the biggest +examples need nightly Rust's newer trait solver to type-check in reasonable memory. + +For a pipeline written once and run by hand, a shell script is simpler, and for a single command a +few lines of `std::process::Command` are. The design earns its cost when a pipeline's parts should +be reusable, checked by the compiler, and replaceable without editing the program. + +## Where to go next + +- [Abstract syntax](./abstract-syntax.md): what a program is made of. +- [`hello`](../examples/hello.md): the design at its smallest, in a running program. +- [Type-level DSLs](/docs/concepts/type-level-dsls): the CGP technique behind Hypershell, explained + with a smaller language. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/architecture/streams-and-input-dispatch.md b/docs/projects/hypershell/architecture/streams-and-input-dispatch.md new file mode 100644 index 00000000..526837a8 --- /dev/null +++ b/docs/projects/hypershell/architecture/streams-and-input-dispatch.md @@ -0,0 +1,164 @@ +--- +sidebar_label: 'Streams and input dispatch' +sidebar_position: 3 +description: 'How Hypershell stages of different kinds fit together: bytes and three kinds of stream, stages that adapt to their input, and what each accepts.' +--- + +# Streams and input dispatch + +In a shell, every program in a pipeline reads bytes and writes bytes, so any two can be connected. +In Hypershell, stages pass typed Rust values, so how do stages of different kinds fit together? +[Hypershell](../index.md) is a small shell-scripting language built with [CGP](/docs/). This page +explains what stages pass to each other, how a stage adapts to the kind of input it receives, and +which stages accept which inputs. + +## What stages pass to each other + +A stage passes either all of its output at once, as bytes, or a stream that the next stage reads as +it arrives. The simple stages, such as `SimpleExec` and `SimpleHttpRequest`, collect their whole +output and pass a `Vec`. The streaming stages, such as `StreamingExec` and +`StreamingHttpRequest`, pass a stream as soon as they start, which is what lets a pipeline run all +its stages at once. + +Streams come in more than one kind, because Rust's async libraries define more than one reader +trait. A process started with Tokio produces a Tokio reader, while `reqwest` produces a reader from +the `futures` crate. Hypershell wraps each kind in its own type, so the next stage can tell which +one it received: + +| Wrapper type | What it holds | Produced by | +|---|---|---| +| `TokioAsyncReadStream` | a Tokio reader | `StreamingExec`, `ReadFile`, `BytesToStream` | +| `FuturesAsyncReadStream` | a `futures` reader | `StreamingHttpRequest`, `WebSocket` | +| `FuturesStream` | a `futures` stream of chunks | the adapter in front of `Checksum` | + +## A stage adapts to the type it receives + +A stage that runs a command needs a Tokio reader to feed the command's input. To accept bytes or a +`futures` reader as well, it starts with a small converter, called an **input dispatcher**, that +looks at the type it receives and converts it. This is `HandleToTokioAsyncRead`, the dispatcher in +front of the Tokio stages: + +```rust +delegate_components! { + new HandleToTokioAsyncRead { + open HandlerComponent; + + @HandlerComponent + . Code + . FuturesAsyncReadStream: + FuturesToTokioAsyncRead, + @HandlerComponent + . Code + . TokioAsyncReadStream: + ReturnInput, + @HandlerComponent + . Code.[ + Vec, + String, + ]: + HandleBytesToTokioAsyncRead, + } +} +``` + +It is an ordinary CGP wiring table, where each entry names a provider for one kind of input. After +`@HandlerComponent`, each key has two parts: the syntax, here the generic ` Code` that matches +any syntax, and then the input type. So the table reads: a `futures` reader is converted, a Tokio +reader is passed through unchanged, and bytes or a `String` are wrapped as a reader. Any other input +type has no entry, and the program fails to compile. The `open` statement at the top is what lets a +table choose by these parameters; the reference for +[`delegate_components!`](/docs/reference/macros/delegate_components) describes it. + +This is also why the stream kinds each have a wrapper type. The table can only tell two kinds of +reader apart if they are different types; an entry for "any reader" would match every input and +conflict with the others. + +## Stages are built from small steps + +A streaming stage is usually three providers run in order. Under Hypershell's wiring, +`StreamingExec` is: + +```rust +@HandlerComponent. StreamingExec: + PipeHandlers, +``` + +The first step converts the input, the second runs the command, and the third wraps the command's +output as a `TokioAsyncReadStream`, so the *next* stage can tell what it received. +[`PipeHandlers`](/docs/reference/providers/handler/pipe_handlers) is CGP's way of running providers +in order, each one's output feeding the next. `WriteFile`, `StreamToStdout`, and `WebSocket` are +built the same way. + +The HTTP request stage also chooses by input type. Given bytes or a `String`, it sends them as an +ordinary request body; given a stream, it streams the body as it reads it. + +## Which stages accept which inputs + +This table is the practical summary. It lists what each stage accepts and what it passes on. Here +*bytes* means a `Vec` or a `String`, and *either reader* means either reader type above. The +stages that accept only bytes, such as `SimpleExec`, take anything else that can be read as bytes +too: + +| Stage | Accepts | Passes on | +|---|---|---| +| `SimpleExec` | bytes | `Vec` | +| `StreamingExec` | bytes or either reader | `TokioAsyncReadStream` | +| `SimpleHttpRequest` | a request body, such as bytes | `Vec` | +| `StreamingHttpRequest` | bytes or either reader | `FuturesAsyncReadStream` | +| `ReadFile` | `()`, since it has no input | `TokioAsyncReadStream` | +| `WriteFile` | bytes or either reader | `()` | +| `StreamToStdout` | bytes or either reader | `()` | +| `StreamToBytes`, `StreamToString` | a Tokio reader only | `Vec`, `String` | +| `BytesToStream` | bytes | `TokioAsyncReadStream` | +| `BytesToString` | bytes | `String` | +| `EncodeJson` | any value that implements `Serialize` | `Vec` | +| `DecodeJson` | bytes | `T` | +| `Checksum` | bytes or either reader | the digest, as bytes | +| `BytesToHex` | bytes | `String` | +| `WebSocket` | a `Vec` or either reader | `FuturesAsyncReadStream` | + +Two pairings come up often enough to remember: + +- **A streaming stage cannot feed a simple one directly**, since `SimpleExec` takes bytes and a + streaming stage passes a stream. Put `StreamToBytes` between them. +- **`StreamToBytes` and `StreamToString` accept only a Tokio reader**, so they cannot follow an HTTP + or WebSocket stage directly. Put `ToTokioAsyncRead`, from `hypershell_tokio_components::dsl`, in + front of them. + +## How a streaming stage runs + +A streaming command stage starts its process and passes on the process's output straight away, while +a background task feeds the process its input. So consecutive streaming stages run at the same time, +as they do in a shell. A failed command is reported when its output stream ends: the stage reading +the stream fails the program, with the command's error output in the message. These stages start +background tasks on Tokio, so a program that uses them must run inside a Tokio runtime, as every +example does with `#[tokio::main]`. + +## What it costs + +Typed stages catch mismatches that a shell would only reveal while running, and sometimes never. The +price is that a Hypershell pipeline is less forgiving: two stages connect only if the second accepts +what the first produces, and when they do not, the program has to name an adapter such as +`StreamToBytes`. A shell never asks for one. + +The set of inputs each stage accepts is also fixed by its wiring. A stage accepts a new kind of +stream only once its dispatcher gains an entry for it, which is a change to the language rather than +to the program. + +## Where to go next + +- [`http_checksum_client`](../examples/http-checksum-client.md): an HTTP stream converted for a + command, in a running program. +- [Crate layout](./crate-layout.md): which crate each stage lives in. +- [Handlers](/docs/concepts/handlers): the CGP computation interface each stage implements, and the + combinators that chain them. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/_category_.json b/docs/projects/hypershell/examples/_category_.json new file mode 100644 index 00000000..0ac9b3af --- /dev/null +++ b/docs/projects/hypershell/examples/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Examples", + "position": 1, + "link": { + "type": "doc", + "id": "projects/hypershell/examples/index" + } +} diff --git a/docs/projects/hypershell/examples/bluesky-websocket.md b/docs/projects/hypershell/examples/bluesky-websocket.md new file mode 100644 index 00000000..c9919da7 --- /dev/null +++ b/docs/projects/hypershell/examples/bluesky-websocket.md @@ -0,0 +1,173 @@ +--- +sidebar_label: 'bluesky_websocket' +sidebar_position: 11 +description: 'A Hypershell program that adds a WebSocket stage and its error type to one context with two wiring entries, instead of joining an extension namespace.' +--- + +# Add a WebSocket stage to one context + +This program reads the same Bluesky firehose as [`bluesky`](./bluesky.md), with `websocat` replaced +by a native WebSocket stage. It is an example from [Hypershell](../index.md), a shell-scripting +language whose programs are Rust types, built with [CGP](/docs/). The WebSocket stage is an +extension that the base language does not include, and this page shows how one context, the type a +program runs on, adds it with two wiring entries, where +[`http_checksum_native`](./http-checksum-native.md) joined an extended namespace. + +:::tip + +### New to CGP? + +This page builds on [`http_checksum_native`](./http-checksum-native.md), which introduces extending +the language. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) is the quickest +start. The page uses CGP's [modular error handling](/docs/concepts/modular-error-handling), in which +the context chooses the error type, and explains what it needs of it. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example bluesky_websocket +``` + +It needs the network and `grep`. It prints firehose events that contain `love` as they arrive, and +runs until it is stopped with Ctrl-C. + +## The program + +From +[`bluesky_websocket.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/bluesky_websocket.rs): + +```rust +use cgp::core::error::ErrorRaiserComponent; +use cgp_error_anyhow::RaiseAnyhowError; +use hypershell::namespaces::HypershellNamespace; +use hypershell::prelude::*; +use hypershell_tokio_components::types::TokioAsyncReadStream; +use hypershell_tungstenite_components::providers::HypershellTungsteniteProvider; +use tokio::io::simplex; +use tokio_tungstenite::tungstenite::Error as TungsteniteError; + +pub type Program = hypershell! { + WebSocket< + StaticArg<"wss://jetstream1.us-west.bsky.network/subscribe">, + (), + > + | StreamingExec< + StaticArg<"grep">, + WithArgs [ FieldArg<"keyword"> ], + > + | StreamToStdout +}; +``` + +`WebSocket` connects to the URL and produces the messages it receives as a stream. Its second +parameter is `()` in this program. + +## Two entries beside the namespace + +The context joins `HypershellNamespace` and adds two entries of its own: + +```rust +#[derive(HasField)] +pub struct MyApp { + pub keyword: String, +} + +delegate_components! { + MyApp { + namespace HypershellNamespace; + + @cgp.core.error.ErrorRaiserComponent.TungsteniteError: + RaiseAnyhowError, + + @cgp.extra.handler.HandlerComponent. WebSocket: + HypershellTungsteniteProvider, + } +} +``` + +The second entry routes the `WebSocket` syntax to `HypershellTungsteniteProvider`, the bundle of +providers that the `hypershell-tungstenite-components` crate publishes. It uses the same full path +the namespace uses for its own routes, starting from `@cgp.extra.handler`, the prefix under which +CGP's handler component is registered. + +The first entry is needed because the WebSocket provider can fail with an error type the base +language has never seen. Every provider reports failure through the context's error type, which +`HypershellNamespace` sets to `anyhow::Error`, and it converts each kind of source error through a +route listed for that type. The namespace lists the errors the base language raises, so an extension +that raises a new one must add its route: here `tungstenite`'s error, converted by +`RaiseAnyhowError` from the `cgp-error-anyhow` crate, which accepts any type implementing +`std::error::Error`. The entry names `ErrorRaiserComponent` in its path, so that component is +imported even though the code never mentions it otherwise. + +Entries like these work for syntax the namespace does not already route. A context cannot use the +same form to give `SimpleExec` a different provider, because the namespace already binds that path; +see the [limitations](../limitations.md#extensions-add-to-the-language-rather-than-replace-it). + +## An input that stays open + +`main` passes an input that never ends: + +```rust +let (read, _write) = simplex(102400); +let input = TokioAsyncReadStream::from(read); + +app.handle(PhantomData::, input).await?; +``` + +The WebSocket stage forwards its input to the socket and closes the connection when the input ends. +An empty `Vec` would therefore end the stream at once. The program instead passes the reading +half of an in-memory pipe whose writing half is kept alive and never written, so the connection +stays open. + +## Try a change + +Remove the error route, keeping the `WebSocket` entry. Checked with `check_components!` as on the +[`hello_name`](./hello-name.md#try-a-change) page, keyed on the program and the pipe's reader type, +[`cargo cgp check`](/docs/cargo-cgp/check) reports the missing route, shown here with the long types +abridged: + +```text +error[E0277]: [CGP-E002] the provider trait `Handler, TokioAsyncReadStream>>` with context `MyApp` is not implemented for provider `ComposeHandlers<…>` + = note: root cause: [CGP-E107] context `MyApp` does not contain any delegate entry for `@cgp.core.error.ErrorRaiserComponent.Error` +``` + +The path's last segment is the error type the provider raises, written by its own name. That type is +`tungstenite::Error`, which the program imports as `TungsteniteError`, so the `Error` in the message +is `tungstenite`'s error rather than the context's own. Adding the route back fixes it. +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a +v0.1.0-alpha that does not yet reshape every class. + +## The pattern + +This program shows **extending one context rather than the whole language**. Entries next to the +`namespace` statement add syntax for that context alone, with no new type to define. A namespace +that inherits the standard one, as in [`http_checksum_native`](./http-checksum-native.md), does the +same for every context that joins it. The first suits a single application, and the second an +extension that several applications share. + +It also shows how errors work in CGP: code reports its own kinds of error, and the context decides +how each one becomes the application's error type. See [modular error +handling](/docs/concepts/modular-error-handling). + +The cost is bookkeeping. Every new kind of error an extension can produce needs its own entry, and a +context that forgets one finds out from a compile error, which names the missing error type as shown +above. + +## Where to go next + +- [Examples](./index.md): every example, in teaching order. +- [Writing a program](../guides/writing-a-program.md): the steps every example shares, as a guide. +- [Error handling in CGP](/docs/concepts/modular-error-handling): how a context chooses its error + type and how source errors reach it. +- [Assembly](../architecture/assembly.md#a-context-joins-the-namespace): context entries and + extension namespaces. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/bluesky.md b/docs/projects/hypershell/examples/bluesky.md new file mode 100644 index 00000000..901d17f2 --- /dev/null +++ b/docs/projects/hypershell/examples/bluesky.md @@ -0,0 +1,107 @@ +--- +sidebar_label: 'bluesky' +sidebar_position: 10 +description: 'A Hypershell pipeline that streams the Bluesky firehose through grep until it is stopped, with a tool provisioned on the fly by nix-shell.' +--- + +# Stream a live feed through `grep` + +This program reads the Bluesky firehose, a live stream of every public post, and prints the events +that mention a keyword, until it is stopped. It is an example from [Hypershell](../index.md), a +shell-scripting language whose programs are Rust types, built with [CGP](/docs/). The page shows a +pipeline that never ends on its own, and a stage that passes a whole shell command line to another +program. + +:::tip + +### New to CGP? + +This page builds on [`http_checksum_cli`](./http-checksum-cli.md), which introduces streaming +stages. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) is the quickest start, and +[Type-level DSLs](/docs/concepts/type-level-dsls) explains how a program written as a type still +processes data at run time. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example bluesky +``` + +It needs the network, `grep`, and `nix-shell`, which fetches the `websocat` WebSocket client the +first time it runs. It prints firehose events that contain `love` as they arrive, and runs until it +is stopped with Ctrl-C. In one two-minute run it printed about 45 KB. + +## The program + +From +[`bluesky.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/bluesky.rs): + +```rust +pub type Program = hypershell! { + StreamingExec< + StaticArg<"nix-shell">, + WithStaticArgs [ + "-p", + "websocat", + "--run", + "websocat -nU wss://jetstream1.us-west.bsky.network/subscribe", + ], + > + | StreamingExec< + StaticArg<"grep">, + WithArgs [ FieldArg<"keyword"> ], + > + | StreamToStdout +}; + +#[derive(HasField)] +pub struct MyApp { + pub keyword: String, +} +``` + +The context, the type the program runs on, joins `HypershellNamespace`, and `main` sets `keyword` to +`"love"`. + +## A pipeline that does not end + +Both stages are `StreamingExec`, which returns its command's output as a stream at once and keeps it +flowing while the command runs; see +[`http_checksum_cli`](./http-checksum-cli.md#each-stage-streams). `websocat` never closes the +connection, so the first stage's output never ends, and neither does the program. Each event reaches +`grep`, and each matching line reaches standard output, as soon as it arrives. + +The first stage's last argument is a whole command line, passed as one literal to `nix-shell --run`. +Hypershell passes arguments to a process without a shell, so the string is not split; `nix-shell` +runs it in its own shell with `websocat` available. + +## The pattern + +This program shows that a Hypershell pipeline has the **streaming behavior of a shell pipeline**: +stages run concurrently and data flows through them as it is produced, with no stage waiting for the +one before it to finish. It is what makes the language suitable for long-running feeds and large +downloads rather than only for commands that finish quickly. + +The cost is in how failures surface. A streaming stage has returned before its command finishes, so +a failing command is reported only when its output stream ends, and a stream that never ends never +reports; a stalled feed here looks the same as a quiet one. + +## Where to go next + +- [`bluesky_websocket`](./bluesky-websocket.md): the next example, which reads the same feed with a + native WebSocket stage instead of `websocat`. +- [Streams and input + dispatch](../architecture/streams-and-input-dispatch.md#how-a-streaming-stage-runs): how a + streaming stage runs and reports failure. +- [Type-level DSLs](/docs/concepts/type-level-dsls): how a program fixed at compile time still + processes data as it arrives. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/github-issues.md b/docs/projects/hypershell/examples/github-issues.md new file mode 100644 index 00000000..930a3ce3 --- /dev/null +++ b/docs/projects/hypershell/examples/github-issues.md @@ -0,0 +1,139 @@ +--- +sidebar_label: 'github_issues' +sidebar_position: 8 +description: 'A Hypershell program that calls the GitHub API with a URL built from context fields and decodes the JSON reply into a Rust type.' +--- + +# Call a JSON API and decode the response + +This program asks the GitHub API for the open issues of a repository and decodes the JSON reply into +Rust values. It is an example from [Hypershell](../index.md), a shell-scripting language whose +programs are Rust types, built with [CGP](/docs/). The page shows a URL assembled from several +arguments, a request header, and a program whose output is a Rust type it names itself. + +:::tip + +### New to CGP? + +This page builds on [`nix_manual`](./nix-manual.md), which introduces Hypershell's argument syntax. +For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) is the quickest start, and +[Impl-side dependencies](/docs/concepts/impl-side-dependencies) explains the requirements that let +arguments nest. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example github_issues +``` + +It needs the network and unauthenticated access to `api.github.com`, which GitHub rate-limits. It +prints the open issues of `rust-lang/rust` as a debug-formatted list of `Issue` values. + +## The program + +From +[`github_issues.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/github_issues.rs): + +```rust +pub type Program = hypershell! { + SimpleHttpRequest< + GetMethod, + JoinArgs [ + FieldArg<"base_url">, + StaticArg<"/repos/">, + UrlEncodeArg>, + StaticArg<"/">, + UrlEncodeArg>, + StaticArg<"/issues">, + ], + WithHeaders [ + Header< + StaticArg<"User-Agent">, + StaticArg<"hypershells">, + > + ], + > + | DecodeJson> +}; + +#[derive(HasField)] +pub struct MyApp { + pub http_client: Client, + pub base_url: String, + pub github_org: String, + pub github_repo: String, +} + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +pub struct Issue { + pub id: u64, + pub state: String, + pub title: String, +} +``` + +The context, the type the program runs on, joins `HypershellNamespace`, and `main` sets the three +fields to `https://api.github.com`, `rust-lang`, and `rust`. + +## A URL built from parts + +`JoinArgs` joins a list of arguments into one value. In the URL position it concatenates them, so +the URL is the base from a field, a literal path segment, and the organization and repository names +from two more fields. Each name is wrapped in `UrlEncodeArg`, which percent-encodes it for use in a +URL. The same `JoinArgs` in a file-path position joins path segments instead, because the path +interpreter gives it that meaning. + +Arguments nest because each one is interpreted through the context. `UrlEncodeArg>` +works because the encoder asks the context for its inner argument's value, and the context's wiring +answers with the field. Any argument the context can interpret may appear inside another. + +## A header, and a response decoded by type + +`WithHeaders` is a list of `Header` entries, each a name and a value given as arguments. GitHub's +API rejects requests without a `User-Agent`, so the program sends one. + +`SimpleHttpRequest` collects the whole response body as bytes, and `DecodeJson>` decodes +those bytes with `serde_json` into the type it names. `Issue` is an ordinary Rust struct that +derives `Deserialize`; the program names it as a type parameter, so the JSON's shape is part of the +program. Because the last stage produces a `Vec`, that is what `handle` returns, and `main` +prints it without any conversion: + +```rust +let response = app.handle(PhantomData::, Vec::new()).await?; + +println!("List of GitHub issues: {response:#?}"); +``` + +A request that fails, such as one refused by the rate limit, returns an error for the non-success +status rather than handing the error page to the decoder. + +## The pattern + +This program shows **nested interpretation through the context**: an argument expression built from +other expressions, each resolved by the context's wiring at every level. It is the same pattern the +pipeline uses for its stages, applied to a smaller language inside the larger one. In CGP terms, +each interpreter asks the context for the traits it needs for its inner parts, as [impl-side +dependencies](/docs/concepts/impl-side-dependencies), so nesting needs no special support. + +The cost is the depth of what the compiler resolves. Every level of nesting is another lookup +through the context, so a mistake deep in an argument, such as a field the context lacks, is +reported at the end of a long chain of lookups, which is why checking the program first helps. + +## Where to go next + +- [`rust_playground`](./rust-playground.md): the next example, whose input is a Rust value too. +- [Writing a program](../guides/writing-a-program.md#read-runtime-values-from-a-custom-context): + every kind of argument. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the requirements that make nested + interpretation work. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/hello-name.md b/docs/projects/hypershell/examples/hello-name.md new file mode 100644 index 00000000..64f1db6b --- /dev/null +++ b/docs/projects/hypershell/examples/hello-name.md @@ -0,0 +1,170 @@ +--- +sidebar_label: 'hello_name' +sidebar_position: 2 +description: 'A Hypershell program that reads a runtime value from a field of its context with FieldArg, and the error cargo cgp check reports when the field is missing.' +--- + +# Read a runtime value from the context + +This program runs `echo` with a greeting whose name comes from a field of the context, the type the +program runs on, at run time. It is an example from [Hypershell](../index.md), a shell-scripting +language whose programs are Rust types, built with [CGP](/docs/). Because a program is a type, it +cannot hold a value such as a name or a URL; this page shows where such values live instead, and +what the compiler reports when one is missing. + +:::tip + +### New to CGP? + +[`hello`](./hello.md) introduces the program-as-a-type idea this page builds on. For CGP itself, the +[Hello World tutorial](/docs/tutorials/hello) shows a context supplying a value from its fields, the +same idea in its simplest form, and [Implicit arguments](/docs/concepts/implicit-arguments) explains +reading fields in ordinary CGP code. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example hello_name +``` + +It needs only the `echo` command, and prints: + +```text +Hello, Alice +``` + +## An argument list with a field in it + +The program is `echo` with two arguments, from +[`hello_name.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/hello_name.rs): + +```rust +use hypershell::namespaces::HypershellNamespace; +use hypershell::prelude::*; + +pub type Program = hypershell! { + SimpleExec< + StaticArg<"echo">, + WithArgs[ + StaticArg<"Hello,">, + FieldArg<"name">, + ], + > + | StreamToStdout +}; +``` + +[`hello`](./hello.md) used `WithStaticArgs`, which takes a list of literals. `WithArgs` takes a list +of argument *expressions*, so literals and other kinds of argument can be mixed. +`StaticArg<"Hello,">` is a literal, and `FieldArg<"name">` is the value of the context's field named +`name`, formatted with `Display`. + +The arguments form a small language of their own inside the program. Each kind of argument is +interpreted through the context, so the same program reads its `name` from whichever context runs +it. + +## A context of its own + +`HypershellCli` has no fields, so this program runs on a context defined next to it: + +```rust +#[derive(HasField)] +pub struct MyApp { + pub name: String, +} + +delegate_components! { + MyApp { + namespace HypershellNamespace; + } +} +``` + +`MyApp` is a type that stands for this application, which is where its choices and its data live. It +has two parts. The wiring is the same one line `HypershellCli` has, so `MyApp` runs the same +language. The field is the value the program needs, and +[`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) exposes it to generic code by +name, which is how `FieldArg<"name">` reaches it. + +`main` builds the context with a value and runs the program on it: + +```rust +#[tokio::main] +async fn main() -> Result<(), Error> { + let app = MyApp { + name: "Alice".to_owned(), + }; + + app.handle(PhantomData::, Vec::new()).await?; + + Ok(()) +} +``` + +The program reads the field through CGP's field access rather than through an ordinary method, and +it names the field itself. That is why a context needs no code beyond the derive: the program +decides which field it reads, and the context only has to have it. + +## Try a change + +Run the program on `HypershellCli` instead, which has no `name` field. The quickest way to see what +the compiler says is to check the pairing on its own, with +[`check_components!`](/docs/reference/macros/check_components), keyed on the program and its input: + +```rust +use cgp::extra::handler::HandlerComponent; + +check_components! { + #[check_trait(CheckHypershellCli)] + HypershellCli { + HandlerComponent: (Program, Vec), + } +} +``` + +[`cargo cgp check`](/docs/cargo-cgp/check) reports the failure with its root cause, shown here with +the long types abridged: + +```text +error[E0277]: [CGP-E002] the provider trait `Handler, Vec>` with context `HypershellCli` is not implemented for provider `ComposeHandlers<…>` + = note: root cause: [CGP-E106] missing field `name` on `HypershellCli` +``` + +The full output continues with the dependency chain that leads there, from the pipeline through +`SimpleExec`, the command's argument list, and the `FieldArg` that asked for the field. The fix is +the one `MyApp` already applies: run the program on a context that derives `HasField` and has the +field. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a +v0.1.0-alpha that does not yet reshape every class. + +## The pattern + +This program shows a **context supplying the values its implementations need**. The program and the +providers that interpret it state what they require, a field named `name`, without that requirement +appearing in how the program is run. Any context that joins the namespace and has the field can run +it. The idea is CGP's [impl-side dependencies](/docs/concepts/impl-side-dependencies), and reading a +context's fields in ordinary CGP code is covered by [implicit +arguments](/docs/concepts/implicit-arguments). + +Hypershell uses `FieldArg` rather than an implicit argument because the field name is part of the +program: two programs run on one context can read different fields. The cost is that a missing field +is found at compile time only where the program is checked or run, which is why checking a program +against its context, as above, is worth doing. + +## Where to go next + +- [`http_checksum_cli`](./http-checksum-cli.md): the next example, a pipeline of three streaming + commands. +- [Writing a program](../guides/writing-a-program.md): every kind of argument, and how to check a + program. +- [Checking your wiring](/docs/concepts/check-traits): why CGP wiring is checked lazily, and what + `check_components!` forces. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/hello.md b/docs/projects/hypershell/examples/hello.md new file mode 100644 index 00000000..af5f3749 --- /dev/null +++ b/docs/projects/hypershell/examples/hello.md @@ -0,0 +1,163 @@ +--- +sidebar_label: 'hello' +sidebar_position: 1 +description: 'The smallest Hypershell program: echo hello world! written as a Rust type, run on a context whose whole definition is one line of wiring.' +--- + +# Run a shell command from a program written as a type + +This program runs `echo hello world!` and prints the result. It is the smallest program in +[Hypershell](../index.md), a shell-scripting language whose programs are Rust types, built with +[CGP](/docs/), a language extension for Rust with pluggable trait implementations at compile-time. +The page shows the two ideas every other Hypershell example builds on: a program is a type, and the +context it runs on, itself a type, gets the whole language from one line of wiring. + +:::tip + +### New to CGP? + +This page can be read without knowing CGP. For background, the [Hello World +tutorial](/docs/tutorials/hello) introduces CGP's contexts and wiring, and [Type-level +DSLs](/docs/concepts/type-level-dsls) explains how a program can be a type, using a smaller language +than this one. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example hello +``` + +It needs only the `echo` command, and prints: + +```text +hello world! +``` + +## The program is a type + +The whole program is one type alias, from +[`hello.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/hello.rs): + +```rust +use hypershell::prelude::*; + +pub type Program = hypershell! { + SimpleExec< + StaticArg<"echo">, + WithStaticArgs["hello", "world!"], + > + | StreamToStdout +}; +``` + +`SimpleExec` runs a command and collects its output, `StaticArg` is a literal argument, and +`StreamToStdout` writes whatever it receives to standard output. The `|` connects them as a +pipeline, as in a shell. + +Each of these names is an empty struct. `SimpleExec` holds its two parameters in `PhantomData` and +has no methods, so nothing in the program says how a command is run. That choice is made by the +context that runs the program, which is the reason the language can be reinterpreted or extended +without editing it. The [abstract syntax](../architecture/abstract-syntax.md) page describes every +kind of syntax the language has. + +## The macro only rewrites tokens + +`hypershell!` gives the program its shell-like look, and it does nothing else. It turns the `|` into +a `Pipe` over a type-level list, each bracketed list into a +[`Product!`](/docs/reference/macros/product), and each string literal into a +[`Symbol!`](/docs/reference/macros/symbol), a string encoded as a type. The program above is exactly +this type, which can be written without the macro: + +```rust +pub type Program = Pipe, + WithStaticArgs, + >, + StreamToStdout, +]>; +``` + +The macro emits `Pipe`, `Product!`, and `Symbol!` without qualifying them, which is why the program +imports `hypershell::prelude::*` rather than the macro alone. + +## One call runs the program + +The program runs with one call to `handle`: + +```rust +#[tokio::main] +async fn main() -> Result<(), Error> { + HypershellCli + .handle(PhantomData::, Vec::new()) + .await?; + + Ok(()) +} +``` + +The program is passed as `PhantomData::`, since it is a type and has no value. The second +argument is the pipeline's input, here an empty byte buffer that becomes `echo`'s standard input. +`handle` is the method of CGP's [`Handler`](/docs/reference/components/handler/handler) component, +the asynchronous and fallible member of CGP's [handler family](/docs/concepts/handlers), which +Hypershell uses as its interpreter interface. The compiler works out the output type from the +program: `StreamToStdout` produces `()`, so the call returns `Result<(), Error>`. + +## A context that is one line of wiring + +`HypershellCli` is the **context**: the type the program runs on. It is a type that stands for one +set of language choices, and it has no fields, because this program reads no runtime values. Its +entire definition, in the `hypershell` crate, is this: + +```rust +pub struct HypershellCli; + +delegate_components! { + HypershellCli { + namespace HypershellNamespace; + } +} +``` + +[`delegate_components!`](/docs/reference/macros/delegate_components) records a context's wiring, +which is the choice of implementation, or **provider**, for each piece of behavior. The one +`namespace` statement joins `HypershellNamespace`, a reusable wiring table that routes every piece +of the base language to the provider that interprets it. So `SimpleExec` reaches a provider that +spawns a Tokio process, and `StreamToStdout` one that copies bytes to standard output. + +The compiler resolves all of these choices while it type-checks `main`. The call to `handle` +compiles to direct calls into those providers, with no interpreter running at run time and no lookup +table. How the namespace is built from the language's parts is on the +[assembly](../architecture/assembly.md) page. + +## The pattern + +This program shows a **type-level DSL**: a language whose programs are types made of empty syntax +structs, with the meaning of each piece chosen by the wiring of the context that runs it. The +technique is explained with a small arithmetic language in [Type-level +DSLs](/docs/concepts/type-level-dsls). The other half of the pattern is a library shipping its whole +language as a [namespace](/docs/concepts/namespaces), so that a user's context needs one line to run +it. + +The costs are the ones that come with the technique. A program is fixed at compile time, the +compiler does real work to resolve a large program, and a mistake in one is a compile error that can +be long to read. For a single fixed command, `std::process::Command` is simpler; Hypershell pays off +when a program's parts should be reusable and its meaning replaceable. + +## Where to go next + +- [`hello_name`](./hello-name.md): the next example, which reads a runtime value from the context. +- [Abstract syntax](../architecture/abstract-syntax.md): every kind of syntax, and the macro's + rules. +- [Assembly](../architecture/assembly.md): how `HypershellNamespace` routes each piece of syntax. +- [Type-level DSLs](/docs/concepts/type-level-dsls): the CGP technique behind the language. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/http-checksum-cli.md b/docs/projects/hypershell/examples/http-checksum-cli.md new file mode 100644 index 00000000..d818f803 --- /dev/null +++ b/docs/projects/hypershell/examples/http-checksum-cli.md @@ -0,0 +1,150 @@ +--- +sidebar_label: 'http_checksum_cli' +sidebar_position: 3 +description: 'The shell pipeline curl | sha256sum | cut written as three streaming Hypershell stages that run concurrently, with typed stages that must line up.' +--- + +# Pipe three commands together, streaming + +This program is the shell pipeline `curl $url | sha256sum | cut -d ' ' -f 1`: it downloads a web +page and prints its SHA-256 digest. It is an example from [Hypershell](../index.md), a +shell-scripting language whose programs are Rust types, built with [CGP](/docs/). The page shows how +streaming stages run concurrently, and why each stage's input type decides what may come before it. + +:::tip + +### New to CGP? + +Read [`hello`](./hello.md) and [`hello_name`](./hello-name.md) first, which introduce programs as +types and contexts with fields. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) is +the quickest start, and [Handlers](/docs/concepts/handlers) explains the family of computations each +stage belongs to. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example http_checksum_cli +``` + +It needs the network and the `curl`, `sha256sum`, and `cut` commands. It prints the SHA-256 digest +of the Nixpkgs manual page as a line of hexadecimal, the same digest the next two examples print by +other means. + +## Three streaming stages + +The program is three `StreamingExec` stages and a final `StreamToStdout`, from +[`http_checksum_cli.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/http_checksum_cli.rs): + +```rust +pub type Program = hypershell! { + StreamingExec< + StaticArg<"curl">, + WithArgs [ + FieldArg<"url">, + ], + > + | StreamingExec< + StaticArg<"sha256sum">, + WithStaticArgs [], + > + | StreamingExec< + StaticArg<"cut">, + WithStaticArgs [ + "-d", + " ", + "-f", + "1", + ], + > + | StreamToStdout +}; + +#[derive(HasField)] +pub struct MyApp { + pub url: String, +} + +delegate_components! { + MyApp { + namespace HypershellNamespace; + } +} +``` + +`curl` reads its URL from the `url` field of the context, the type the program runs on, as +[`hello_name`](./hello-name.md) read its name. `WithStaticArgs []` is an empty argument list. `main` +builds `MyApp` with the manual's URL and calls `handle` with an empty `Vec` as the input. + +## Each stage streams + +`StreamingExec` differs from the `SimpleExec` the earlier examples used in when it returns. +`SimpleExec` waits for its command to finish and produces the whole output as bytes. `StreamingExec` +spawns its command and returns the command's standard output as a stream at once, while a background +task copies the stage's input into the command's standard input. So the three commands run at the +same time, each reading the previous one's output as it arrives, as they would in a shell. + +That changes when a failure is reported. A streaming stage has already returned by the time its +command fails, so a non-zero exit is reported when its output stream ends, and the stage reading +that stream fails the program. The command's standard error becomes part of the message. + +## The stages must line up + +Every stage's output is the next stage's input, and the compiler checks that each pair agrees. A +`StreamingExec` stage produces a Tokio reader, wrapped in Hypershell's `TokioAsyncReadStream` type, +and the next `StreamingExec` accepts it. The first stage accepts the `Vec` that `main` passes, +and `StreamToStdout` at the end accepts the stream. + +A stage accepts several input types because its wiring puts a small **input dispatcher** in front of +the provider that does the work. Under `HypershellNamespace`, `StreamingExec` is interpreted by +three providers run in sequence: + +```rust +@HandlerComponent. StreamingExec: + PipeHandlers, +``` + +The first converts whatever input arrives, bytes or either kind of stream, into a Tokio reader. The +second runs the command. The third wraps its output in `TokioAsyncReadStream`, so that the next +stage can tell what kind of stream it received. +[`PipeHandlers`](/docs/reference/providers/handler/pipe_handlers) is CGP's combinator for running +providers in sequence, each one's output feeding the next. + +The simpler stages have no dispatcher. `SimpleExec` accepts only bytes, so a `StreamingExec` stage +cannot feed it directly: the compiler rejects the pair until a `StreamToBytes` stage collects the +stream in between. The [streams and input dispatch](../architecture/streams-and-input-dispatch.md) +page has the table of what every stage accepts and produces. + +## The pattern + +This program shows a **typed pipeline**: stages connected in order, with the compiler checking that +each stage can accept what the one before it produces. The check happens when the program is +compiled, so a pipeline whose stages do not fit never runs. The next example, +[`http_checksum_client`](./http-checksum-client.md), shows how a stage accepts more than one kind of +input. + +The cost is the strictness that types bring. A shell passes bytes between any two commands, while a +Hypershell pipeline rejects a pair of stages that do not fit, and the program has to add an adapter +stage between them. + +## Where to go next + +- [`http_checksum_client`](./http-checksum-client.md): the next example, with `curl` replaced by a + native HTTP request. +- [Streams and input dispatch](../architecture/streams-and-input-dispatch.md): the stream types and + the dispatchers. +- [Handlers](/docs/concepts/handlers): CGP's family of computation components, including the + combinators that compose them. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/http-checksum-client.md b/docs/projects/hypershell/examples/http-checksum-client.md new file mode 100644 index 00000000..74e8c1af --- /dev/null +++ b/docs/projects/hypershell/examples/http-checksum-client.md @@ -0,0 +1,172 @@ +--- +sidebar_label: 'http_checksum_client' +sidebar_position: 4 +description: 'A native Hypershell HTTP request feeding external commands, with input dispatch converting one kind of stream into another.' +--- + +# Replace a command with a native HTTP request + +This program computes the same digest as [`http_checksum_cli`](./http-checksum-cli.md), with the +`curl` command replaced by a native HTTP request. It is an example from [Hypershell](../index.md), a +shell-scripting language whose programs are Rust types, built with [CGP](/docs/). The page shows how +a native stage and an external command share one stream, even though they produce different kinds of +stream, and where the HTTP client comes from. + +:::tip + +### New to CGP? + +This page builds on [`http_checksum_cli`](./http-checksum-cli.md). For CGP itself, the [Hello World +tutorial](/docs/tutorials/hello) introduces contexts and wiring. The dispatch this page describes is +the `open` statement of [`delegate_components!`](/docs/reference/macros/delegate_components), and +the page explains what it does here without assuming that reference. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example http_checksum_client +``` + +It needs the network and the `sha256sum` and `cut` commands, and prints the same digest of the +Nixpkgs manual page as `http_checksum_cli`. + +## A native first stage + +Only the first stage changes, from +[`http_checksum_client.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/http_checksum_client.rs): + +```rust +pub type Program = hypershell! { + StreamingHttpRequest< + GetMethod, + FieldArg<"url">, + WithHeaders[ ], + > + | StreamingExec< + StaticArg<"sha256sum">, + WithStaticArgs [], + > + | StreamingExec< + StaticArg<"cut">, + WithStaticArgs [ + "-d", + " ", + "-f", + "1", + ], + > + | StreamToStdout +}; +``` + +`StreamingHttpRequest` sends a request with the `reqwest` crate and produces the response body as a +stream. Its parameters are the method, the URL, and a list of headers, here empty. The URL is a +`FieldArg`, read from the context, the type the program runs on, as before. + +## The client lives in a field + +The context gains a second field: + +```rust +#[derive(HasField)] +pub struct MyApp { + pub http_client: Client, + pub url: String, +} + +delegate_components! { + MyApp { + namespace HypershellNamespace; + } +} +``` + +The HTTP stage needs a `reqwest::Client`, and it gets one from the context rather than creating its +own. `HypershellNamespace` wires the client lookup to a field by name: + +```rust +@hypershell.reqwest.ReqwestClientGetterComponent: + UseField, +``` + +[`UseField`](/docs/reference/providers/use_field) is the CGP provider that implements a getter by +reading a named field. So any context that joins the namespace and has a `Client` field named +exactly `http_client` can run HTTP programs, and a context without one fails to compile with a root +cause naming the missing field. `main` builds the context with `Client::new()`. + +## The stream kinds are converted by dispatch + +The request produces a different kind of stream from the command stages. `reqwest` returns a reader +from the `futures` crate, which Hypershell wraps as `FuturesAsyncReadStream`, while a command reads +from a Tokio reader. The program never converts one into the other, and it does not need to. + +The conversion happens in the input dispatcher that `StreamingExec` starts with, +`HandleToTokioAsyncRead`. It is a small table from the Tokio backend crate, with one entry per input +type it accepts: + +```rust +delegate_components! { + new HandleToTokioAsyncRead { + open HandlerComponent; + + @HandlerComponent + . Code + . FuturesAsyncReadStream: + FuturesToTokioAsyncRead, + @HandlerComponent + . Code + . TokioAsyncReadStream: + ReturnInput, + @HandlerComponent + . Code.[ + Vec, + String, + ]: + HandleBytesToTokioAsyncRead, + } +} +``` + +Each key is a path with two segments after `@HandlerComponent`: the syntax, then the input. The +`open` statement makes a lookup for `CanHandle` follow that path, so an entry can +select a provider by the input type alone. The first segment of every entry here is the generic +` Code`, which matches any syntax. The second picks the conversion: a futures reader is +converted, a Tokio reader passes through unchanged with `ReturnInput`, and bytes are wrapped as a +reader. + +This is why Hypershell wraps each stream kind in its own type. Entries keyed on +`FuturesAsyncReadStream` and `TokioAsyncReadStream` never overlap, where a single entry for +"anything that is a reader" would overlap every other entry and conflict. An input type the table +does not list fails to compile, with a root cause naming the missing entry. + +## The pattern + +This program shows **a stage choosing its implementation by the type of its input**. The same stage +works after a command, after an HTTP request, or at the start of a program, because a small +converter in front of it picks the right conversion for whatever arrives. The choice is ordinary CGP +wiring, made by the compiler, and it is why stages written by different people chain without the +program naming the conversions. The wiring form it uses is the `open` statement of +[`delegate_components!`](/docs/reference/macros/delegate_components). + +The cost is that each stage accepts a fixed list of input types. A new kind of stream works only +once the converters have an entry for it, which is a change to the language, not to the program. + +## Where to go next + +- [`http_checksum_native`](./http-checksum-native.md): the next example, with the two commands + replaced by native stages from an extension. +- [Streams and input dispatch](../architecture/streams-and-input-dispatch.md): every dispatcher, and + what each stage accepts. +- [`UseField`](/docs/reference/providers/use_field): the provider behind the client field. +- [Handlers](/docs/concepts/handlers): the computation interface whose second parameter, the input, + the dispatch keys on. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/http-checksum-native.md b/docs/projects/hypershell/examples/http-checksum-native.md new file mode 100644 index 00000000..4810ba47 --- /dev/null +++ b/docs/projects/hypershell/examples/http-checksum-native.md @@ -0,0 +1,187 @@ +--- +sidebar_label: 'http_checksum_native' +sidebar_position: 5 +description: 'A fully native Hypershell checksum pipeline, run on a context that joins a language extended with new syntax through an inheriting namespace.' +--- + +# Extend the language with native checksums + +This program computes the same digest as the two before it with every stage native: an HTTP request, +a SHA-256 checksum, and hexadecimal encoding. It is an example from [Hypershell](../index.md), a +shell-scripting language whose programs are Rust types, built with [CGP](/docs/). The checksum +stages are not part of the base language. The page shows how a language extension defined in other +crates is joined by changing one namespace name. + +:::tip + +### New to CGP? + +This page builds on [`http_checksum_client`](./http-checksum-client.md). For CGP itself, the [Hello +World tutorial](/docs/tutorials/hello) is the quickest start. The page uses CGP's +[namespaces](/docs/concepts/namespaces), reusable wiring tables that a namespace or a context can +inherit, and explains what it needs of them. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example http_checksum_native +``` + +It needs the network and no other tools, and prints the same digest of the Nixpkgs manual page as +[`http_checksum_cli`](./http-checksum-cli.md). + +## Two stages from an extension crate + +The program replaces `sha256sum` and `cut` with `Checksum` and `BytesToHex`, from +[`http_checksum_native.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/http_checksum_native.rs): + +```rust +use hypershell::prelude::*; +use hypershell_examples::namespaces::HypershellChecksumNamespace; +use hypershell_hash_components::dsl::{BytesToHex, Checksum}; +use reqwest::Client; +use sha2::Sha256; + +pub type Program = hypershell! { + StreamingHttpRequest< + GetMethod, + FieldArg<"url">, + WithHeaders[ ], + > + | Checksum + | BytesToHex + | StreamToStdout +}; +``` + +The two new stages come from `hypershell-hash-components`, a crate that depends on neither the +Hypershell core nor Tokio. `Checksum` names its hash algorithm as a type from the `sha2` +crate, and produces the digest as raw bytes, which `BytesToHex` encodes as text for printing. + +## Joining the extended language + +The context, the type the program runs on, differs from the previous example's in one name: + +```rust +#[derive(HasField)] +pub struct MyApp { + pub http_client: Client, + pub url: String, +} + +delegate_components! { + MyApp { + namespace HypershellChecksumNamespace; + } +} +``` + +`HypershellNamespace` does not route `Checksum` or `BytesToHex`, so a context joined to it cannot +run this program. `HypershellChecksumNamespace` is a namespace defined in the examples crate that +inherits `HypershellNamespace` and adds routes for the two new stages: + +```rust +cgp_namespace! { + new HypershellChecksumNamespace: HypershellNamespace { + @cgp.extra.handler.HandlerComponent.[ + Checksum, + BytesToHex, + ]: + HypershellChecksumProvider, + } +} +``` + +[`cgp_namespace!`](/docs/reference/macros/cgp_namespace) defines the namespace, and the part after +the colon names the namespace it inherits. Its one entry routes both syntaxes to +`HypershellChecksumProvider`, a bundle of providers, or **aggregate provider**, also defined in the +examples crate: + +```rust +delegate_components! { + new HypershellChecksumProvider { + open {HandlerComponent}; + + @HandlerComponent. Checksum: + PipeHandlers, + + @HandlerComponent.BytesToHex: + HandleBytesToHex, + } +} +``` + +`HandleStreamChecksum` and `HandleBytesToHex` are the providers from the hash crate that do the +work. `HandleToFuturesStream` in front of the checksum is an input dispatcher, the counterpart of +the one in [`http_checksum_client`](./http-checksum-client.md), so `Checksum` accepts bytes or +either kind of stream. The same two-layer shape, a bundle that maps syntax to providers and a +namespace route that points at the bundle, is how the whole base language is assembled; see +[assembly](../architecture/assembly.md). + +## Try a change + +Remove the `BytesToHex` stage, so that the raw digest flows straight into `StreamToStdout`: + +```rust +pub type Program = hypershell! { + StreamingHttpRequest< + GetMethod, + FieldArg<"url">, + WithHeaders[ ], + > + | Checksum + | StreamToStdout +}; +``` + +Checked with `check_components!`, as on the [`hello_name`](./hello-name.md#try-a-change) page, +[`cargo cgp check`](/docs/cargo-cgp/check) names the missing entry, shown here with the long types +abridged: + +```text +error[E0277]: [CGP-E002] the provider trait `Handler, GenericArray>` with context `MyApp` is not implemented for provider `Call` + = note: root cause: [CGP-E110] provider `HandleToTokioAsyncRead` does not contain any delegate entry for `@HandlerComponent.StreamToStdout.GenericArray` +``` + +The digest is a `GenericArray`, and `StreamToStdout`'s input dispatcher has no entry for that +type. The path in the message is the syntax followed by the input type, which is exactly the key the +dispatcher failed to match. The fix is to convert the value into a type the dispatcher lists, which +is what `BytesToHex` does. `cargo cgp check` leads with the root cause for the classes it +recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. + +## The pattern + +This program shows **extending a language through a namespace that inherits it**. A library +publishes its language as a namespace, and anyone can publish a larger language that inherits it and +adds new syntax, from their own crates and without editing the library. A context chooses which +language it runs by the namespace it joins, and extensions can build on each other: the examples +crate has a second extension built on this one. The ideas are explained in +[Namespaces](/docs/concepts/namespaces) and [Aggregate +providers](/docs/concepts/aggregate-providers). + +The limit is that an extension can only add. It cannot change what the syntax it inherits does, +because CGP does not let an inheriting namespace override a choice its parent has made. The +[limitations](../limitations.md#extensions-add-to-the-language-rather-than-replace-it) page says +more about what this means. + +## Where to go next + +- [`nix_manual`](./nix-manual.md): the next example, with a static URL and a mixed argument list. +- [`bluesky_websocket`](./bluesky-websocket.md): an extension wired onto one context instead of a + namespace. +- [Assembly](../architecture/assembly.md): the bundles and routes the base language is built from. +- [Namespaces](/docs/concepts/namespaces): inheriting a namespace, and why an inherited binding + cannot be overridden. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/index.md b/docs/projects/hypershell/examples/index.md new file mode 100644 index 00000000..e8a35d9d --- /dev/null +++ b/docs/projects/hypershell/examples/index.md @@ -0,0 +1,78 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'Runnable Hypershell programs, each walked through as a short tutorial on a CGP design pattern, from a one-line context to a language extension.' +--- + +# Hypershell examples + +These pages walk through the runnable programs in the [Hypershell +repository](https://github.com/contextgeneric/hypershell), one program per page. +[Hypershell](../index.md) is a shell-scripting language whose programs are Rust types, built with +[CGP](/docs/). Each page runs a program, explains how its wiring produces what it prints, and names +the CGP pattern it shows, so the pages work as short tutorials on those patterns. + +The pages are in the order they teach. Each stands alone, but a reader new to Hypershell should +start with [`hello`](./hello.md), since the later pages build on the ideas it introduces. + +:::tip + +### New to CGP? + +These pages explain Hypershell's code without deriving CGP from first principles. The [Hello World +tutorial](/docs/tutorials/hello) introduces CGP in a few minutes, and [Type-level +DSLs](/docs/concepts/type-level-dsls) explains the technique Hypershell is built on with a much +smaller language. Neither is required reading; each page links what it relies on. + +::: + +## Running an example + +Clone the repository and run an example from its root with `cargo run --example `. The +repository selects nightly Rust and the new trait solver itself; see the [project +overview](../index.md#running-it). Most examples also need the network and some common command-line +tools, which each page lists. + +## The examples + +The first two programs run commands with no network access: + +- [`hello`](./hello.md) — `echo hello world!`, run on a context, the type a program runs on, whose + whole definition is one line of wiring. +- [`hello_name`](./hello-name.md) — a program that reads a runtime value from a field of its + context. + +The next three are one pipeline written three ways, each replacing more of the shell with native +stages: + +- [`http_checksum_cli`](./http-checksum-cli.md) — `curl | sha256sum | cut` as three streaming + commands. +- [`http_checksum_client`](./http-checksum-client.md) — `curl` replaced by a native HTTP request. +- [`http_checksum_native`](./http-checksum-native.md) — every stage native, from a language extended + with checksums. + +The rest show the language's other parts: + +- [`nix_manual`](./nix-manual.md) — a static URL and an argument list that mixes literals and + fields. +- [`save_webpage`](./save-webpage.md) — a streaming download written to a file. +- [`github_issues`](./github-issues.md) — a URL built from fields, a request header, and JSON + decoded into a Rust type. +- [`rust_playground`](./rust-playground.md) — a program whose input and output are Rust values. +- [`bluesky`](./bluesky.md) — a pipeline that streams until it is stopped. +- [`bluesky_websocket`](./bluesky-websocket.md) — the same feed read by a WebSocket stage added to + one context. + +Two more programs in the repository, `parallel_compare` and `compare_and_branch`, add control syntax +that runs whole programs as operands. Their pages are still being written. + +## Where to go next + +- [Architecture](../architecture/index.md): the design behind every example, one idea per page. +- [Writing a program](../guides/writing-a-program.md): the steps the examples share, as a guide. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/nix-manual.md b/docs/projects/hypershell/examples/nix-manual.md new file mode 100644 index 00000000..083dda42 --- /dev/null +++ b/docs/projects/hypershell/examples/nix-manual.md @@ -0,0 +1,126 @@ +--- +sidebar_label: 'nix_manual' +sidebar_position: 6 +description: 'A Hypershell program that filters a web page through tr and grep, with a static URL and an argument list mixing literals and fields.' +--- + +# Filter a web page through two commands + +This program downloads the Nixpkgs manual, converts it to upper case with `tr`, and prints the lines +that mention a keyword, found with `grep`. It is an example from [Hypershell](../index.md), a +shell-scripting language whose programs are Rust types, built with [CGP](/docs/). The page looks at +Hypershell's argument syntax: a URL written as a literal, and an argument list that mixes a literal +with a field. + +:::tip + +### New to CGP? + +This page builds on [`hello_name`](./hello-name.md), which introduces `FieldArg`, and +[`http_checksum_client`](./http-checksum-client.md), which introduces the HTTP stage. For CGP +itself, the [Hello World tutorial](/docs/tutorials/hello) is the quickest start, and [Impl-side +dependencies](/docs/concepts/impl-side-dependencies) explains how an interpreter asks its context +for what it needs. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example nix_manual +``` + +It needs the network and the `tr` and `grep` commands. It prints, in upper case, the lines of the +manual page that contain `Nix`. + +## The program + +From +[`nix_manual.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/nix_manual.rs): + +```rust +pub type Program = hypershell! { + StreamingHttpRequest< + GetMethod, + StaticArg<"https://nixos.org/manual/nixpkgs/unstable/">, + WithHeaders, + > + | StreamingExec< + StaticArg<"tr">, + WithStaticArgs [ + "[:lower:]", + "[:upper:]", + ], + > + | StreamingExec< + StaticArg<"grep">, + WithArgs [ + StaticArg<"-i">, + FieldArg<"keyword">, + ], + > + | StreamToStdout +}; + +#[derive(HasField)] +pub struct MyApp { + pub http_client: Client, + pub keyword: String, +} +``` + +The context, the type the program runs on, joins `HypershellNamespace` as in the earlier examples, +and `main` sets `keyword` to `"Nix"`. + +## Arguments are a language of their own + +Every argument in a Hypershell program is an expression that the context interprets, and the kind of +value it must produce depends on where it appears. + +**A URL can be a literal.** The request's URL is a `StaticArg`, where the earlier examples read it +from a field. It is still interpreted when the program runs: the URL position asks for a parsed +`url::Url`, so the literal string is parsed, and a malformed one is an error raised through the +context. + +**Headers can be written without the macro's brackets.** `WithHeaders` is the empty header list +written as the plain type. It is exactly what `WithHeaders[]` expands to, since an empty +[`Product!`](/docs/reference/macros/product) list is `Nil`. Either form may be used; the macro only +rewrites the bracketed form into this one. + +**One argument list can mix kinds.** `grep`'s arguments are `WithArgs`, so the literal flag `-i` and +the `keyword` field sit in one list, as in [`hello_name`](./hello-name.md). `tr`'s arguments are all +literals, so they use `WithStaticArgs`. + +Each kind of argument, a literal, a field, a joined value, an encoded value, has its own +interpreter, chosen by the context's wiring in the same way as the pipeline's stages are. Which +interpreter runs depends on the position as well: command arguments and file paths come from one +extractor and URLs from another, which is why the same `StaticArg` becomes a path in one place and a +parsed URL in another. The [abstract +syntax](../architecture/abstract-syntax.md#four-kinds-of-syntax) page lists every kind. + +## The pattern + +This program shows **one piece of syntax meaning different things in different places**. `StaticArg` +is always a literal, but whether it becomes a string, a file path, or a parsed URL depends on where +it appears, because each place asks the context for a different kind of value. In CGP terms, each +position requires a different trait, and the context's wiring implements each one for the same +syntax. + +The cost is that a piece of syntax has no single definition to read. To know what `StaticArg` does +in a URL, a reader looks at how URLs are produced, rather than at one definition of `StaticArg`. + +## Where to go next + +- [`save_webpage`](./save-webpage.md): the next example, a download written to a file. +- [Writing a program](../guides/writing-a-program.md#read-runtime-values-from-a-custom-context): + every kind of argument and where it may appear. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): how each interpreter asks the + context for what it needs. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/rust-playground.md b/docs/projects/hypershell/examples/rust-playground.md new file mode 100644 index 00000000..7908eed1 --- /dev/null +++ b/docs/projects/hypershell/examples/rust-playground.md @@ -0,0 +1,141 @@ +--- +sidebar_label: 'rust_playground' +sidebar_position: 9 +description: 'A Hypershell program whose input and output are Rust values: a struct sent as JSON to the Rust Playground, and the reply decoded into another.' +--- + +# Send a Rust value as JSON and decode the reply + +This program takes a Rust struct holding some code, posts it as JSON to the Rust Playground's gist +API, and decodes the reply into another struct. It is an example from [Hypershell](../index.md), a +shell-scripting language whose programs are Rust types, built with [CGP](/docs/). The page shows a +program whose input and output are both Rust values rather than bytes, run on a context, the type a +program runs on, that the library provides. + +:::tip + +### New to CGP? + +This page builds on [`github_issues`](./github-issues.md), which introduces decoding JSON into a +Rust type. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) is the quickest start, +and [Handlers](/docs/concepts/handlers) explains how a computation's output type follows from its +input and its code. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example rust_playground +``` + +It needs the network. **Running it publishes a public GitHub gist** containing a hello-world +program, through the Playground's API, so these pages do not record its output; the program compiles +against the current code, and its behavior follows from the stages described below. + +## The program + +From +[`rust_playground.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/rust_playground.rs): + +```rust +pub type Program = hypershell! { + EncodeJson + | SimpleHttpRequest< + PostMethod, + StaticArg<"https://play.rust-lang.org/meta/gist">, + WithHeaders [ + Header< + StaticArg<"Content-Type">, + StaticArg<"application/json">, + > + ], + > + | DecodeJson +}; + +#[derive(Serialize)] +pub struct Request { + pub code: String, +} + +#[derive(Debug, Deserialize)] +pub struct Response { + pub id: String, + pub url: String, + pub code: String, +} +``` + +## Rust values at both ends + +The program starts with `EncodeJson`, so its input is any value that implements `Serialize`, encoded +into JSON bytes. Those bytes are the body of the `POST` request, since `SimpleHttpRequest` accepts +anything that `reqwest` can send as a body. The reply is decoded by `DecodeJson`, so the +program's output is a `Response`. + +`main` passes a `Request` as the input and receives a `Response` as the output: + +```rust +let app = HypershellHttp { + http_client: Client::new(), +}; + +let input = Request { + code: "fn main() { println!(\"Hello, world!\"); }".to_owned(), +}; + +let output = app.handle(PhantomData::, input).await?; +``` + +So a Hypershell program is not limited to bytes and streams. The first stage decides what the +program accepts, and the last decides what it returns, and both can be Rust types checked by the +compiler. + +## A context the library provides + +The program reads no field except the HTTP client, so it runs on `HypershellHttp`, the second +context the `hypershell` crate defines. It is `HypershellCli` with one field: + +```rust +#[derive(HasField)] +pub struct HypershellHttp { + pub http_client: Client, +} + +delegate_components! { + HypershellHttp { + namespace HypershellNamespace; + } +} +``` + +The two predefined contexts are wired identically. They differ only in their fields, which is all a +context needs to add for the programs it runs. + +## The pattern + +This program shows **a program's type fixing its interface**: the first stage's accepted input and +the last stage's output are the program's signature, worked out by the compiler from the wiring. The +same `handle` call serves a program of bytes, of streams, or of Rust structs, and a caller passing +the wrong input type gets a compile error rather than a runtime failure. + +The cost is the one [`save_webpage`](./save-webpage.md) names: the signature is never written down. +It lives in the first and last stages' wiring, so a reader finds a program's input and output types +by following that wiring rather than by reading a declaration. + +## Where to go next + +- [`bluesky`](./bluesky.md): the next example, a pipeline that never ends on its own. +- [Assembly](../architecture/assembly.md#a-context-joins-the-namespace): the two predefined contexts + and how a context joins the language. +- [Handlers](/docs/concepts/handlers): how a computation's output type follows from its code and + input. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/examples/save-webpage.md b/docs/projects/hypershell/examples/save-webpage.md new file mode 100644 index 00000000..7da7087f --- /dev/null +++ b/docs/projects/hypershell/examples/save-webpage.md @@ -0,0 +1,108 @@ +--- +sidebar_label: 'save_webpage' +sidebar_position: 7 +description: 'A Hypershell program that streams an HTTP download straight into a file whose path comes from a field of the context.' +--- + +# Download a web page to a file + +This program downloads the Nixpkgs manual and writes it to a file as it arrives, without holding the +whole page in memory. It is an example from [Hypershell](../index.md), a shell-scripting language +whose programs are Rust types, built with [CGP](/docs/). The page shows a pipeline whose last stage +produces nothing, and a file path read from the context, the type the program runs on. + +:::tip + +### New to CGP? + +This page builds on [`http_checksum_client`](./http-checksum-client.md), which introduces the HTTP +stage and its input dispatch. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) is +the quickest start, and [Handlers](/docs/concepts/handlers) explains the computations whose output +types a pipeline chains. + +::: + +## Run it + +From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): + +```sh +cargo run --example save_webpage +``` + +It needs the network. It writes the manual page to `nix_manual.html` in the directory the command is +run from, and then prints: + +```text +Webpage saved to nix_manual.html +``` + +Run from the repository root, it writes the file into the checkout. + +## The program + +From +[`save_webpage.rs`](https://github.com/contextgeneric/hypershell/blob/main/crates/hypershell-examples/examples/save_webpage.rs): + +```rust +pub type Program = hypershell! { + StreamingHttpRequest< + GetMethod, + FieldArg<"url">, + WithHeaders[ ], + > + | WriteFile> +}; + +#[derive(HasField)] +pub struct MyApp { + pub http_client: Client, + pub url: String, + pub file_path: String, +} +``` + +The context joins `HypershellNamespace`, and `main` sets `file_path` to the relative path +`nix_manual.html`. + +## A stage that ends the pipeline + +`WriteFile` takes the path to write as its parameter, and the stage's input as the content. Its path +is a `FieldArg`, so the program reads it from the context like any other runtime value. The path +position asks for a file path rather than a string, so the same argument syntax that produced a URL +in [`nix_manual`](./nix-manual.md) produces a path here. + +The request's output is a futures reader, and `WriteFile` accepts it because its wiring starts with +the same input dispatcher as `StreamingExec`, described in +[`http_checksum_client`](./http-checksum-client.md#the-stream-kinds-are-converted-by-dispatch). The +file is written as the response streams in. + +`WriteFile` produces `()`, so the program's output is `()` and `handle` returns `Result<(), Error>`. +The compiler computes that from the last stage; `main` only prints its message once the call +returns. + +## The pattern + +This program shows a **pipeline whose output type follows from its last stage**. A caller of +`handle` chooses only the input; what comes back is decided by the stages the program names, through +their providers. A program ending in `WriteFile` returns nothing, and one ending in a decoding stage +returns the decoded value, as [`github_issues`](./github-issues.md) shows. + +The cost is that the signature is implicit. Nothing in `Program` names its output type; a reader +works it out from the last stage's provider, and a caller who expects the wrong type learns so from +a compile error at the call rather than from a declaration. + +## Where to go next + +- [`github_issues`](./github-issues.md): the next example, which calls a JSON API. +- [Streams and input + dispatch](../architecture/streams-and-input-dispatch.md#which-stages-accept-which-inputs): what + each stage accepts and produces. +- [Handlers](/docs/concepts/handlers): the computation interface whose output type the program's + signature follows from. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/guides/_category_.json b/docs/projects/hypershell/guides/_category_.json new file mode 100644 index 00000000..c84e856e --- /dev/null +++ b/docs/projects/hypershell/guides/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Guides", + "position": 3, + "link": { + "type": "generated-index", + "description": "How to write, check, and debug a Hypershell program." + } +} diff --git a/docs/projects/hypershell/guides/debugging.md b/docs/projects/hypershell/guides/debugging.md new file mode 100644 index 00000000..e554df81 --- /dev/null +++ b/docs/projects/hypershell/guides/debugging.md @@ -0,0 +1,279 @@ +--- +sidebar_label: 'Debugging' +sidebar_position: 2 +description: 'The common mistakes in a Hypershell program or its wiring, each with the code that triggers it, the root cause cargo cgp check reports, and the fix.' +--- + +# Debugging a program + +A mistake in a Hypershell program or its wiring is a compile error, and the raw compiler output for +one spans every layer of wiring between the context, the type the program runs on, and the part that +failed. [Hypershell](../index.md) is a shell-scripting language whose programs are Rust types, built +with [CGP](/docs/). This guide shows the common mistakes, each with the code that triggers it, the +root cause [`cargo cgp check`](/docs/cargo-cgp/check) reports, and the fix. Each output below was +produced by running the check and is trimmed to its headline and root cause, with long types +abridged. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is +a v0.1.0-alpha that does not yet reshape every class. + +## Check first, then read the root cause + +**Put the program in a `check_components!` before reading any error, and read the result with +`cargo cgp check`.** A failure reported at the `handle` call often carries no root cause at all: the +missing-field mistake below, reported at its call site, produces only headlines about the pipeline's +combinators. Through a check, the same mistake names its cause. The check is keyed on the program +and its input: + +```rust +use cgp::extra::handler::HandlerComponent; + +check_components! { + #[check_trait(CheckHypershellCli)] + HypershellCli { + HandlerComponent: (Program, Vec), + } +} +``` + +Below the root cause, `cargo cgp check` prints the chain of lookups that led to it, one line per +step, which follows the walk on the +[assembly](../architecture/assembly.md#following-one-piece-of-syntax) page. Read it from the bottom: +the last line is the part that failed. Each step names the table it looked in, so the chain shows +whether the failure is in the context, in a bundle, or in an input dispatcher. The codes in brackets +are listed in the [compile errors](/docs/reference/errors#the-cgp-exxx-codes) page. + +## A context lacks a field + +A `FieldArg` names a field the context does not have. Here `HypershellCli`, which has no fields, +runs a program that reads `name`: + +```rust +pub type Program = hypershell! { + SimpleExec, WithArgs[StaticArg<"Hello,">, FieldArg<"name">]> + | StreamToStdout +}; +``` + +```text +error[E0277]: [CGP-E002] the provider trait `Handler, Vec>` with context `HypershellCli` is not implemented for provider `ComposeHandlers<…>` + = note: root cause: [CGP-E106] missing field `name` on `HypershellCli` +``` + +The chain runs through the pipeline, `SimpleExec`, the command's argument list, and the extractor +for `FieldArg<"name">`. **Fix:** run the program on a context with the field, deriving `HasField`, +as [`hello_name`](../examples/hello-name.md) does. The same error names `http_client` when an HTTP +program runs on a context without a client. + +## A stage cannot accept the previous stage's output + +The input type of a stage is the previous stage's output, and the error takes one of two forms, +depending on whether the stage has an input dispatcher. + +**A stage without a dispatcher reports the unmet bound.** `SimpleExec` needs bytes, and a streaming +stage produces a stream: + +```rust +pub type Program = hypershell! { + StreamingExec, WithStaticArgs["hello"]> + | SimpleExec, WithStaticArgs["-c"]> + | StreamToStdout +}; +``` + +```text + = note: root cause: [CGP-E201] the trait bound `TokioAsyncReadStream: AsRef<[u8]>` is not satisfied +``` + +**Fix:** insert `StreamToBytes` between the two stages. With it, the program compiles and prints +`6`, the byte count of `hello` and its newline. + +**A stage with a dispatcher reports the entry it lacks.** Removing `BytesToHex` from +[`http_checksum_native`](../examples/http-checksum-native.md) leaves the raw digest flowing into +`StreamToStdout`: + +```rust +pub type Program = hypershell! { + StreamingHttpRequest, WithHeaders[ ]> + | Checksum + | StreamToStdout +}; +``` + +```text + = note: root cause: [CGP-E110] provider `HandleToTokioAsyncRead` does not contain any delegate entry for `@HandlerComponent.StreamToStdout.GenericArray` +``` + +The path names the syntax and then the input type, which is exactly what the dispatcher could not +match; see [streams and input +dispatch](../architecture/streams-and-input-dispatch.md#a-stage-adapts-to-the-type-it-receives). +**Fix:** convert the value into one of the types the dispatcher accepts, here with `BytesToHex`. The +same form appears for an input the caller passes: `StreamingExec` given a `&'static str` reports a +missing `@HandlerComponent.StreamingExec<…>.&str` entry, and the fix is to pass a `String` or a +`Vec`. + +## A syntax has no route + +A syntax that no route reaches fails at the missing route, even when a provider for it exists. +`Checksum` has a provider in the hash crate, but `HypershellNamespace` does not route it, so a +program using it fails on `HypershellCli`: + +```rust +pub type Program = hypershell! { + StreamingExec, WithStaticArgs["Cargo.toml"]> + | Checksum +}; +``` + +```text +error[E0277]: [CGP-E001] the consumer trait `CanHandle, Vec>` is not implemented for context `HypershellCli` + = note: root cause: [CGP-E107] context `HypershellCli` does not contain any delegate entry for `@cgp.extra.handler.HandlerComponent.Checksum<…>` +``` + +`WebSocket` fails the same way on such a context. **Fix:** add the route, either on a namespace that +inherits `HypershellNamespace`, as [`http_checksum_native`](../examples/http-checksum-native.md) +joins, or as an entry beside the context's `namespace` statement, as +[`bluesky_websocket`](../examples/bluesky-websocket.md) adds. + +## A raised error type has no route + +A provider raises an error type the namespace does not know. This custom stage raises `TooLong` when +its input is longer than 16 bytes: + +```rust +use cgp::extra::handler::Handler; +use hypershell::namespaces::HypershellNamespace; +use hypershell::prelude::*; + +pub struct CheckLength; + +#[derive(Debug)] +pub struct TooLong; + +#[cgp_impl(new HandleCheckLength)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Handler +where + Input: Send + AsRef<[u8]>, +{ + type Output = Input; + + async fn handle(&self, _code: PhantomData, input: Input) -> Result { + if input.as_ref().len() > 16 { + return Err(Self::raise_error(TooLong)); + } + Ok(input) + } +} + +pub struct App; + +delegate_components! { + App { + namespace HypershellNamespace; + @cgp.extra.handler.HandlerComponent.CheckLength: HandleCheckLength, + } +} +``` + +```text +error[E0277]: [CGP-E001] the consumer trait `CanHandle>` is not implemented for context `App` + = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `@cgp.core.error.ErrorRaiserComponent.TooLong` +``` + +The provider requires the context to raise `TooLong` into its error type, and `HypershellNamespace` +routes only the error types the base language raises. **Fix:** route the new type to a way of +converting it, beside the `namespace` statement: + +```rust +@cgp.core.error.ErrorRaiserComponent.TooLong: DebugAnyhowError, +``` + +`DebugAnyhowError`, from `cgp_error_anyhow`, formats any `Debug` value into the `anyhow::Error` the +namespace uses, and `RaiseAnyhowError` converts a type that implements `std::error::Error`. The path +names `ErrorRaiserComponent`, so it must be imported from `cgp::core::error`. The idea behind the +routes is CGP's [modular error handling](/docs/concepts/modular-error-handling). + +## A routed provider does not implement `Handler` + +A route that exists can still lead to a provider of the wrong kind, as when a syntax is routed +straight to a synchronous [`Computer`](/docs/reference/components/handler/computer) provider. Here +`App` routes a custom `Shout` syntax to `ShoutText`: + +```rust +use cgp::extra::handler::Computer; + +pub struct Shout; + +#[cgp_impl(new ShoutText)] +impl Computer { + type Output = String; + + fn compute(&self, _code: PhantomData, input: String) -> String { + input.to_uppercase() + } +} + +delegate_components! { + App { + namespace HypershellNamespace; + @cgp.extra.handler.HandlerComponent.Shout: ShoutText, + } +} +``` + +```text +error[E0277]: [CGP-E002] the provider trait `Handler` with context `App` is not implemented for provider `ShoutText` + = note: root cause: [CGP-E111] the provider trait `Handler` is not implemented for `ShoutText` +``` + +**Fix:** lift the provider into a handler, as `Promote>`, with both imported +from `cgp::extra::handler`. [`PromoteAsync`](/docs/reference/providers/handler/promote_async) makes +the synchronous computer an asynchronous one, and +[`Promote`](/docs/reference/providers/handler/promote) makes that a `Handler`. Hypershell wires its +own `ConvertTo` syntax the same way. + +## Rebinding a syntax conflicts + +An entry for a syntax the namespace already routes conflicts with the namespace: + +```rust +delegate_components! { + App { + namespace HypershellNamespace; + @cgp.extra.handler.HandlerComponent. SimpleExec: FakeSimpleExec, + } +} +``` + +```text +error[E0119]: [CGP-E005] `App` cannot wire `@cgp.extra.handler.HandlerComponent.SimpleExec.*` that is already set through `HypershellNamespace` +``` + +A namespace that inherits `HypershellNamespace` and binds the same path fails in the same way. +**Fix:** there is no wiring-only fix, because a namespace's bindings cannot be overridden. Choose +the provider in the program instead, with `Use>`, which runs the named +provider for that one stage, or write a namespace of your own that routes every syntax itself. The +[namespaces](/docs/concepts/namespaces) page explains why a shared namespace's choices cannot be +overridden. + +## The macro cannot find its names + +A program written with `hypershell!` can fail with "cannot find macro `Product` in this scope" or +"cannot find type `Pipe` in this scope". The message comes from the macro rather than from the +wiring, and does not mention CGP. It means the prelude is not imported: the macro writes `Pipe`, +`Product!`, and `Symbol!` without qualifying them, so they must be in scope. **Fix:** import +`hypershell::prelude::*`. + +## Where to go next + +- [Checking your wiring](/docs/concepts/check-traits): why CGP wiring is checked lazily, and what a + check forces. +- [Compile errors](/docs/reference/errors): the classes of CGP compile error, each with the program + behind it. +- [`cargo cgp check`](/docs/cargo-cgp/check): installing and running the checker. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/guides/writing-a-program.md b/docs/projects/hypershell/guides/writing-a-program.md new file mode 100644 index 00000000..d2fceab9 --- /dev/null +++ b/docs/projects/hypershell/guides/writing-a-program.md @@ -0,0 +1,161 @@ +--- +sidebar_label: 'Writing a program' +sidebar_position: 1 +description: 'How to write a Hypershell program: the prelude and a context, values from fields, simple and streaming stages, adapters, the input, and checks.' +--- + +# Writing a program + +This guide is for writing Hypershell programs rather than extending the language: how to choose the +context, which is the type a program runs on, and then how to feed the program its values, make its +stages agree, and check it before running it. [Hypershell](../index.md) is a shell-scripting +language whose programs are Rust types, built with [CGP](/docs/). The +[examples](../examples/index.md) show each step in a running program. + +## Start from the prelude and a context + +**Import `hypershell::prelude::*`, and run the program on `HypershellCli` if it reads no runtime +values.** The prelude brings the syntax, the `hypershell!` macro and the names its output uses, +`CanHandle`, `PhantomData`, and the error type. Run the program with `handle`, inside a Tokio +runtime: + +```rust +use hypershell::prelude::*; + +pub type Program = hypershell! { + SimpleExec, WithStaticArgs["hello", "world!"]> + | StreamToStdout +}; + +#[tokio::main] +async fn main() -> Result<(), Error> { + HypershellCli.handle(PhantomData::, Vec::new()).await?; + Ok(()) +} +``` + +Import the prelude rather than the macro alone. The macro's output names `Pipe`, `Product!`, and +`Symbol!` without qualifying them, so a file without them in scope fails with "cannot find macro +`Product` in this scope". Use `HypershellHttp` instead of `HypershellCli` when the program makes +HTTP requests and reads no other value; it carries the `http_client` field those requests need. + +## Read runtime values from a custom context + +**A value a program needs at run time lives in a field of the context, and the program names the +field.** A program is a type, so it cannot hold a URL or a name. Define a struct with the fields, +derive [`HasField`](/docs/reference/derives/derive_has_field), and join `HypershellNamespace`: + +```rust +use hypershell::namespaces::HypershellNamespace; +use hypershell::prelude::*; + +#[derive(HasField)] +pub struct MyApp { + pub http_client: reqwest::Client, + pub url: String, +} + +delegate_components! { + MyApp { + namespace HypershellNamespace; + } +} +``` + +Name the client field `http_client`, since the namespace reads the HTTP client from a field of +exactly that name. Then reach the fields from the program with the argument syntax: + +- **`FieldArg<"name">`** — one value, formatted with `Display`, wherever an argument is expected. +- **`FieldArgs<"args">`** — every item of an iterable field, as a command's whole argument list. +- **`JoinArgs[…]`** — several arguments joined into one. For a URL or a header it concatenates them, + and for a command path or a file path it joins them as path segments. +- **`UrlEncodeArg<…>`** — a value percent-encoded for a URL. Use it inside the `JoinArgs` that + builds the URL. + +## Choose simple or streaming stages + +**Use a simple stage when the data is small or a command must finish before the next one starts, and +a streaming stage for large data or concurrent processes.** `SimpleExec` and `SimpleHttpRequest` +collect the whole output and produce bytes. `StreamingExec` and `StreamingHttpRequest` produce a +stream at once, and consecutive streaming stages run at the same time, as in a shell. + +The choice changes when a failure is reported. `SimpleExec` fails as soon as its command exits with +a failure status, reporting its standard error. `StreamingExec` reports the same failure when its +output stream ends, so the stage reading the stream fails with it, after any output the command +wrote has flowed through the stages in between. + +## Make adjacent stages agree + +**Each stage's output is the next stage's input, and a stage accepts only the input types its wiring +lists.** Most stages accept bytes or any kind of stream, so they chain freely. Three boundaries need +an adapter: + +- **A streaming stage before a simple stage** — insert `StreamToBytes`, as in + `StreamingExec<…> | StreamToBytes | SimpleExec<…>`. +- **An HTTP or WebSocket stream before `StreamToBytes` or `StreamToString`** — insert + `ToTokioAsyncRead`, imported from `hypershell_tokio_components::dsl`. +- **Raw bytes to print as text** — `BytesToString` decodes UTF-8, and `BytesToHex` encodes bytes + such as a digest. + +The full table of what each stage accepts and produces is on the [streams and input +dispatch](../architecture/streams-and-input-dispatch.md#which-stages-accept-which-inputs) page. + +## Pass the right input + +**The input argument is the first stage's input, and its type must be one the first stage accepts.** +The common cases are: + +- **`Vec::::new()`** for a program whose first stage runs a command or sends a request with an + empty body. +- **`()`** for a program starting with `ReadFile`, which accepts nothing else. +- **A Rust value** for a program starting with `EncodeJson`. + +When a program fails to compile, the errors reported at the `handle` call show some of their types +as unresolved `_`, whether the input is written `Vec::new()` or `Vec::::new()`. Checking the +program, as the last section shows, avoids them. + +The program's output type is computed from its last stage, so `handle` on a program ending in +`DecodeJson>` returns a `Vec` with no conversion. + +## Check the program before running it + +**Assert that a context can run a program with +[`check_components!`](/docs/reference/macros/check_components), keyed on the program and its +input.** The check forces the whole resolution where it is written, and a failure there carries a +root cause: + +```rust +use cgp::extra::handler::HandlerComponent; + +check_components! { + #[check_trait(CheckMyApp)] + MyApp { + HandlerComponent: (Program, Vec), + } +} +``` + +One check can list several programs, or several inputs, as an array: +`HandlerComponent: [(Hello, Vec), (Cat, ())]`. Read failures with +[`cargo cgp check`](/docs/cargo-cgp/check); the [debugging guide](./debugging.md) shows the common +ones. A failure reported at the `handle` call itself often carries no root cause, which is the +practical reason to check. `cargo cgp check` leads with the root cause for the classes it +recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. + +## Build with nightly and the new trait solver + +The Hypershell repository pins nightly Rust and passes `-Z next-solver=globally` to the compiler, +and a crate of your own whose programs nest sub-programs should do the same. On stable Rust the +simpler programs type-check, but the largest examples exhausted memory while type-checking; see +[crate layout](../architecture/crate-layout.md#what-the-workspace-needs-to-build). + +## Where to go next + +- [Debugging](./debugging.md): the common mistakes, with the error each one produces and its fix. +- [`hello_name`](../examples/hello-name.md): a custom context and a check, in a running program. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/index.md b/docs/projects/hypershell/index.md new file mode 100644 index 00000000..12754a49 --- /dev/null +++ b/docs/projects/hypershell/index.md @@ -0,0 +1,176 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'Hypershell is a Rust DSL for shell-script-like programs, where a pipeline is a Rust type and the context that runs it is its interpreter, built with CGP.' +--- + +# Hypershell + +Hypershell is a small language for writing shell-script-like programs in Rust, built with +[CGP](/docs/), a language extension for Rust with pluggable trait implementations at compile-time. A +Hypershell program is a Rust *type*, and the context that runs it, a type whose wiring chooses how +each piece behaves, is its interpreter. So both the language's syntax and its meaning can be +extended without editing the crates that define it. + +Hypershell is an experimental proof of concept. It is not a replacement for a shell, and it builds +only on nightly Rust. It is also the most complete example of a type-level language built with CGP, +and these pages show what its design makes possible while being candid about its gaps. + +## A program that is a type + +This is the smallest Hypershell program. It runs `echo hello world!` and prints the output: + +```rust +use hypershell::prelude::*; + +pub type Program = hypershell! { + SimpleExec< + StaticArg<"echo">, + WithStaticArgs["hello", "world!"], + > + | StreamToStdout +}; + +#[tokio::main] +async fn main() -> Result<(), Error> { + HypershellCli + .handle(PhantomData::, Vec::new()) + .await?; + + Ok(()) +} +``` + +```text +hello world! +``` + +`Program` is a type alias, not a value. Each piece of it, such as `SimpleExec` or `StreamToStdout`, +is an empty struct that says nothing about how it runs. The `hypershell!` macro only rewrites the +shell-like surface into that type: the `|` becomes a pipeline, the brackets a type-level list, and +each string a type-level string. + +Running the program is a single `handle` call on a context. `HypershellCli` is the context here, and +this is its entire definition: + +```rust +pub struct HypershellCli; + +delegate_components! { + HypershellCli { + namespace HypershellNamespace; + } +} +``` + +The one line joins `HypershellNamespace`, which routes each piece of syntax to the implementation, +or **provider**, that interprets it. The compiler resolves every choice while it type-checks the +program, so the call compiles to direct calls to those providers, with no interpreter running and no +lookup at run time. + +## What the design shows + +Hypershell exists to show that CGP's wiring is a general mechanism, and it shows three things a +reader can reuse in their own code. + +**A language's meaning can live entirely in its wiring.** Because a program only names syntax, the +same program can run differently under two contexts that wire different providers. The +[architecture](./architecture/index.md) explains how one provider interprets each piece of syntax +and how the language is assembled from bundles of providers. + +**A library can hand its users a whole language in one line.** `HypershellNamespace` collects every +route the language needs, so a context that joins it can run any program in the base language. A +context that adds fields for its programs to read is still a few lines long; see +[`hello_name`](./examples/hello-name.md). + +**Anyone can extend the language.** New syntax, a new provider, and a new namespace that inherits +the base can all live in another crate. The +[`http_checksum_native`](./examples/http-checksum-native.md) example joins a language extended with +native checksums by changing one namespace name. + +Writing a program uses the language's syntax, and running one uses a context, so a user who only +writes programs meets little of CGP. Extending the language is where CGP's providers and wiring +become the subject, and that is where the learning cost falls. + +## Status and costs + +Hypershell is a demonstration, and these are the costs a reader evaluating it should know first: + +- **Nightly Rust.** The repository pins nightly and enables the next-generation trait solver with + `-Z next-solver=globally`. The largest examples, which nest whole programs inside others, + exhausted memory while type-checking on stable Rust without it, growing `rustc` to about 7 GB. On + nightly with the new solver, the same check took about 9 seconds and 460 MB. See [crate + layout](./architecture/crate-layout.md#what-the-workspace-needs-to-build). +- **Programs are fixed at compile time.** A program is a type, so it cannot be loaded or changed + while the application runs. Values a program needs at run time, such as a URL, come from fields of + its context. +- **Error messages are long.** A mistake in a program is a compile error, and the compiler's raw + message lists every step it took before it failed. Checking the program with `check_components!` + and reading the error with [`cargo cgp check`](/docs/cargo-cgp/check) helps: `cargo cgp check` + leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does + not yet reshape every class. The [debugging guide](./guides/debugging.md) shows the common + failures. +- **It is a demonstration.** Hypershell is lightly tested and not meant for production use; its + value is as a worked example. The [limitations page](./limitations.md) describes the limits of its + design. + +## The examples + +The examples are the best way into Hypershell. Each is a runnable program from the repository, +walked through as a short tutorial, in the order they teach: + +- [`hello`](./examples/hello.md) — a program is a type, and a context runs the whole language from + one line of wiring. +- [`hello_name`](./examples/hello-name.md) — a context supplies the runtime values a program reads + from its fields. +- [`http_checksum_cli`](./examples/http-checksum-cli.md) — three streaming commands running + concurrently, as in a shell pipeline. +- [`http_checksum_client`](./examples/http-checksum-client.md) — a native HTTP request feeding + external commands, with the stream types converted by dispatch on the input. +- [`http_checksum_native`](./examples/http-checksum-native.md) — the same pipeline in native stages, + from a language extended through an inheriting namespace. +- [`nix_manual`](./examples/nix-manual.md) — a static URL and an argument list mixing literals and + fields. +- [`save_webpage`](./examples/save-webpage.md) — a streaming download written to a file. +- [`github_issues`](./examples/github-issues.md) — a URL built from fields, a header, and JSON + decoded into a Rust type. +- [`rust_playground`](./examples/rust-playground.md) — a program whose input and output are Rust + values encoded as JSON. +- [`bluesky`](./examples/bluesky.md) — a pipeline that streams indefinitely. +- [`bluesky_websocket`](./examples/bluesky-websocket.md) — a language extension wired onto a single + context rather than a namespace. + +## The rest of the section + +The [architecture](./architecture/index.md) pages explain the design one idea at a time: programs as +types, how the language is assembled, how stages dispatch on their input, and how the crates split. +The guides cover [writing a program](./guides/writing-a-program.md) and [debugging +one](./guides/debugging.md), and the [limitations page](./limitations.md) describes the limits of +its design. + +## Running it + +Clone the [repository](https://github.com/contextgeneric/hypershell) and run an example from its +root, such as `cargo run --example hello`. The repository's toolchain file selects nightly Rust, and +its `.cargo/config.toml` enables the new trait solver, so no setup is needed beyond `rustup`. Most +examples need the network and a few common command-line tools; each example page says which. + +To use Hypershell from your own crate, depend on the repository by git, and copy its +`rust-toolchain.toml` and `.cargo/config.toml` so that your crate builds with the same toolchain and +solver. The `hypershell` crates published on crates.io are an earlier release, built on an older +version of CGP with a different design, and the code on these pages does not compile against them. + +## Where to go next + +- [`hello`](./examples/hello.md): the first example, and the one to read first. +- [Type-level DSLs](/docs/concepts/type-level-dsls): the CGP technique behind Hypershell, explained + with a smaller language. +- [Hello World](/docs/tutorials/hello): a first CGP program, for a reader new to CGP. +- [Hypershell: a type-level DSL for shell-scripting](/blog/hypershell-release): the post that + announced the project, with its history and motivation. Its code predates the current design. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/limitations.md b/docs/projects/hypershell/limitations.md new file mode 100644 index 00000000..928890f7 --- /dev/null +++ b/docs/projects/hypershell/limitations.md @@ -0,0 +1,87 @@ +--- +sidebar_label: 'Limitations' +sidebar_position: 10 +description: 'The limits of Hypershell: a proof of concept, programs fixed at compile time, a nightly toolchain, and when a shell or plain Rust fits better.' +--- + +# Limitations + +Hypershell is a proof of concept built to show what CGP makes possible, and its design has limits +that are worth knowing before reading further. [Hypershell](./index.md) is a small shell-scripting +language built with [CGP](/docs/). This page describes those limits, and the cases where another +tool is the better choice. + +## It is a demonstration, not a tool to depend on + +Hypershell is an experiment. It is not a replacement for a shell, it is lightly tested, and it is +not meant for production use. Its value is as a worked example: the most complete program on this +site that shows CGP's wiring used to build and extend a language. Read it to learn the patterns, and +expect rough edges if you try to build on it. + +## Programs are fixed at compile time + +A Hypershell program is a Rust type, so it is checked and compiled with the rest of the program. +That is the source of its guarantees, since a pipeline whose stages do not fit is a compile error +rather than a failure halfway through a run. It also means a program cannot be read from a file, +typed by a user, or changed while an application runs. Values a program needs at run time, such as a +URL or a file name, come from fields of the context, but the shape of the pipeline itself is fixed. + +## Typed stages are stricter than a shell + +A shell passes bytes between any two commands. Hypershell stages pass typed values, such as bytes or +one of several kinds of stream, and two stages connect only if the second accepts what the first +produces. Most stages accept bytes and any kind of stream, so they chain freely, but some pairings +need an adapter stage in between, which the program has to name. The [streams and input +dispatch](./architecture/streams-and-input-dispatch.md) page lists what each stage accepts. + +## Extensions add to the language rather than replace it + +Anyone can add new syntax to Hypershell, from their own crate, by publishing a namespace that +inherits the standard one or by adding entries to a single context. What an extension cannot do is +give the standard syntax a different implementation, because CGP does not let a context or an +inheriting namespace override a choice the shared namespace has already made. So a context decides +what new syntax means, but the base language's own syntax always means what the standard wiring +says. The [assembly](./architecture/assembly.md) page explains the layers this follows from, and the +[namespaces](/docs/concepts/namespaces) page explains the rule. + +## Building it needs nightly Rust + +The repository builds with nightly Rust and the compiler's next-generation trait solver. The largest +examples nest whole programs inside others, and on stable Rust they exhausted the compiler's memory +while type-checking. A crate of your own with programs of that size needs the same toolchain. Large +programs also take noticeable time to compile, since the compiler resolves every piece of every +program. + +## Mistakes produce long compile errors + +A mistake in a program or its wiring is a compile error, and the compiler's raw message lists every +step it took through the wiring before it failed. Checking a program with `check_components!` and +reading the error with [`cargo cgp check`](/docs/cargo-cgp/check) gets to the cause faster: +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a +v0.1.0-alpha that does not yet reshape every class. The [debugging guide](./guides/debugging.md) +shows the common mistakes. + +## When another tool is the better choice + +Most tasks Hypershell can express are simpler another way: + +- **A shell script** is shorter to write, runs without compiling, and can be changed at any time. + For a pipeline written once and run by hand, it is the right tool. +- **Plain Rust with `std::process::Command`** runs a command from a program with no framework and no + nightly toolchain, and a few lines of it are easier to read than a Hypershell program. + +Hypershell's design earns its cost where a pipeline's parts should be reusable and replaceable, and +checked by the compiler. Those are also the properties that make it worth reading as an example of +CGP, even for a reader who never writes a Hypershell program. + +## Where to go next + +- [How Hypershell works](./architecture/index.md): the design these limits follow from. +- [Type-level DSLs](/docs/concepts/type-level-dsls): the CGP technique, and where it pays off in + general. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/index.md b/docs/projects/index.md new file mode 100644 index 00000000..9e2ab0f7 --- /dev/null +++ b/docs/projects/index.md @@ -0,0 +1,56 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'Projects built with CGP, with their runnable examples written as short tutorials on the patterns they use, and a table from each pattern to its example.' +--- + +# Projects + +These pages document projects built with [CGP](/docs/), a language extension for Rust with pluggable +trait implementations at compile-time. Where the [Concepts](/docs/concepts/) pages explain each CGP +idea with the smallest code that shows it, these pages show the ideas working together in programs +that do something real, and each project's examples are written as short tutorials on the patterns +they use. + +The projects are experiments rather than products. Each section says on its first page what state +its project is in, what it needs to build, and where its design stops, so that a reader weighing CGP +can judge the evidence for what it is. + +## The projects + +- **[Hypershell](./hypershell/index.md)** — a shell-scripting language whose programs are Rust + types, interpreted at compile time through CGP wiring. A proof of concept that builds on nightly + Rust, and the most complete example of a type-level language built with CGP. + +## Find a pattern + +Each row names a CGP design pattern and the example page that shows it in a running program, with +the Concepts page that explains the idea: + +| Pattern | Shown in | Explained in | +|---|---|---| +| A program written as a type, interpreted by wiring | [`hello`](./hypershell/examples/hello.md) | [Type-level DSLs](/docs/concepts/type-level-dsls) | +| A library's wiring shipped as a namespace a context joins in one line | [`hello`](./hypershell/examples/hello.md) | [Namespaces](/docs/concepts/namespaces) | +| A context supplying the values its implementations read from its fields | [`hello_name`](./hypershell/examples/hello-name.md) | [Impl-side dependencies](/docs/concepts/impl-side-dependencies) | +| Providers composed in sequence, with each output checked against the next input | [`http_checksum_cli`](./hypershell/examples/http-checksum-cli.md) | [Handlers](/docs/concepts/handlers) | +| A provider chosen by the type of the value it receives | [`http_checksum_client`](./hypershell/examples/http-checksum-client.md) | [`delegate_components!`](/docs/reference/macros/delegate_components) | +| A language extended through a namespace that inherits the base | [`http_checksum_native`](./hypershell/examples/http-checksum-native.md) | [Namespaces](/docs/concepts/namespaces) | +| Providers bundled into an aggregate provider that routes point at | [`http_checksum_native`](./hypershell/examples/http-checksum-native.md) | [Aggregate providers](/docs/concepts/aggregate-providers) | +| Nested expressions, each resolved through the context | [`github_issues`](./hypershell/examples/github-issues.md) | [Impl-side dependencies](/docs/concepts/impl-side-dependencies) | +| One context extended with its own wiring entries, including a new error type | [`bluesky_websocket`](./hypershell/examples/bluesky-websocket.md) | [Modular error handling](/docs/concepts/modular-error-handling) | + +## Where to start + +- **To see CGP's ideas in a real program**, read [`hello`](./hypershell/examples/hello.md), then + follow the examples in order. +- **To weigh whether CGP holds up past a toy**, read the [Hypershell + overview](./hypershell/index.md) and its [limitations](./hypershell/limitations.md), which state + the costs first. +- **To learn CGP from the beginning**, start with the [Hello World tutorial](/docs/tutorials/hello) + instead; these pages assume it rather than teach it. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/resources.md b/docs/resources.md index d8277844..10224f23 100644 --- a/docs/resources.md +++ b/docs/resources.md @@ -1,5 +1,5 @@ --- -sidebar_position: 9 +sidebar_position: 10 --- # Resources @@ -52,4 +52,4 @@ beyond small examples, this is the codebase to read. ## Projects - [CGP Examples](https://github.com/contextgeneric/cgp-examples) - A repository hosting various examples of using CGP. -- [Hypershell](https://github.com/contextgeneric/hypershell) - A type-level DSL for shell-scripting in Rust, built with CGP. +- [Hypershell](https://github.com/contextgeneric/hypershell) - A type-level DSL for shell-scripting in Rust, built with CGP. Documented on this site in the [Projects](/docs/projects/hypershell/) section, with its examples walked through as short tutorials. From b8f74e771ac401838a1162304620bba6119f15f7 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 05:29:24 +0000 Subject: [PATCH 101/516] Add the cgp-serde pages to the Projects section Forty-five pages: the overview, the basic and messages examples, the architecture, four guides, the reference, the comparison with Serde, and the limitations page. The two arena examples and three component pages wait on the cgp-serde code changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HvLfWEnrK9PnjZSdoLbHG5 --- docs/projects/cgp-serde/_category_.json | 8 + .../cgp-serde/architecture/_category_.json | 8 + .../architecture/component-design.md | 160 ++++++++++ .../architecture/context-services.md | 154 ++++++++++ .../cgp-serde/architecture/crate-layout.md | 87 ++++++ .../architecture/derive-free-records.md | 110 +++++++ docs/projects/cgp-serde/architecture/index.md | 113 +++++++ .../architecture/reentrant-providers.md | 168 ++++++++++ .../cgp-serde/architecture/serde-bridge.md | 129 ++++++++ .../cgp-serde/examples/_category_.json | 8 + docs/projects/cgp-serde/examples/basic.md | 270 ++++++++++++++++ docs/projects/cgp-serde/examples/index.md | 57 ++++ docs/projects/cgp-serde/examples/messages.md | 290 ++++++++++++++++++ .../projects/cgp-serde/guides/_category_.json | 8 + .../cgp-serde/guides/debugging-wiring.md | 271 ++++++++++++++++ docs/projects/cgp-serde/guides/formats.md | 100 ++++++ .../cgp-serde/guides/wiring-a-context.md | 227 ++++++++++++++ .../cgp-serde/guides/writing-a-provider.md | 160 ++++++++++ docs/projects/cgp-serde/index.md | 165 ++++++++++ docs/projects/cgp-serde/limitations.md | 96 ++++++ .../cgp-serde/reference/_category_.json | 8 + .../reference/components/_category_.json | 5 + .../reference/components/can_alloc.md | 84 +++++ docs/projects/cgp-serde/reference/index.md | 105 +++++++ .../reference/providers/_category_.json | 5 + .../providers/allocate_with_arena.md | 97 ++++++ .../providers/deserialize_and_allocate.md | 86 ++++++ .../providers/deserialize_default.md | 90 ++++++ .../reference/providers/deserialize_extend.md | 86 ++++++ .../providers/deserialize_from_json_reader.md | 115 +++++++ .../providers/deserialize_from_json_string.md | 101 ++++++ .../providers/deserialize_record_fields.md | 116 +++++++ .../providers/deserialize_with_from_str.md | 86 ++++++ .../reference/providers/serialize_base64.md | 86 ++++++ .../reference/providers/serialize_bytes.md | 96 ++++++ .../reference/providers/serialize_deref.md | 82 +++++ .../reference/providers/serialize_fields.md | 104 +++++++ .../reference/providers/serialize_from.md | 96 ++++++ .../reference/providers/serialize_hex.md | 96 ++++++ .../reference/providers/serialize_iterator.md | 94 ++++++ .../providers/serialize_rfc3339_date.md | 80 +++++ .../reference/providers/serialize_string.md | 92 ++++++ .../providers/serialize_timestamp.md | 91 ++++++ .../providers/serialize_to_json_string.md | 113 +++++++ .../providers/serialize_with_display.md | 81 +++++ .../providers/try_deserialize_bytes.md | 81 +++++ .../reference/providers/try_serialize_from.md | 91 ++++++ .../reference/providers/use_serde.md | 102 ++++++ .../cgp-serde/reference/types/_category_.json | 5 + .../types/can_deserialize_json_string.md | 90 ++++++ .../types/deserialize_with_context.md | 94 ++++++ .../reference/types/serialize_with_context.md | 94 ++++++ docs/projects/cgp-serde/serde-comparison.md | 119 +++++++ docs/projects/index.md | 15 +- docs/resources.md | 2 +- 55 files changed, 5373 insertions(+), 4 deletions(-) create mode 100644 docs/projects/cgp-serde/_category_.json create mode 100644 docs/projects/cgp-serde/architecture/_category_.json create mode 100644 docs/projects/cgp-serde/architecture/component-design.md create mode 100644 docs/projects/cgp-serde/architecture/context-services.md create mode 100644 docs/projects/cgp-serde/architecture/crate-layout.md create mode 100644 docs/projects/cgp-serde/architecture/derive-free-records.md create mode 100644 docs/projects/cgp-serde/architecture/index.md create mode 100644 docs/projects/cgp-serde/architecture/reentrant-providers.md create mode 100644 docs/projects/cgp-serde/architecture/serde-bridge.md create mode 100644 docs/projects/cgp-serde/examples/_category_.json create mode 100644 docs/projects/cgp-serde/examples/basic.md create mode 100644 docs/projects/cgp-serde/examples/index.md create mode 100644 docs/projects/cgp-serde/examples/messages.md create mode 100644 docs/projects/cgp-serde/guides/_category_.json create mode 100644 docs/projects/cgp-serde/guides/debugging-wiring.md create mode 100644 docs/projects/cgp-serde/guides/formats.md create mode 100644 docs/projects/cgp-serde/guides/wiring-a-context.md create mode 100644 docs/projects/cgp-serde/guides/writing-a-provider.md create mode 100644 docs/projects/cgp-serde/index.md create mode 100644 docs/projects/cgp-serde/limitations.md create mode 100644 docs/projects/cgp-serde/reference/_category_.json create mode 100644 docs/projects/cgp-serde/reference/components/_category_.json create mode 100644 docs/projects/cgp-serde/reference/components/can_alloc.md create mode 100644 docs/projects/cgp-serde/reference/index.md create mode 100644 docs/projects/cgp-serde/reference/providers/_category_.json create mode 100644 docs/projects/cgp-serde/reference/providers/allocate_with_arena.md create mode 100644 docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md create mode 100644 docs/projects/cgp-serde/reference/providers/deserialize_default.md create mode 100644 docs/projects/cgp-serde/reference/providers/deserialize_extend.md create mode 100644 docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md create mode 100644 docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md create mode 100644 docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md create mode 100644 docs/projects/cgp-serde/reference/providers/deserialize_with_from_str.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_base64.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_bytes.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_deref.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_fields.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_from.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_hex.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_iterator.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_string.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_timestamp.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_with_display.md create mode 100644 docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md create mode 100644 docs/projects/cgp-serde/reference/providers/try_serialize_from.md create mode 100644 docs/projects/cgp-serde/reference/providers/use_serde.md create mode 100644 docs/projects/cgp-serde/reference/types/_category_.json create mode 100644 docs/projects/cgp-serde/reference/types/can_deserialize_json_string.md create mode 100644 docs/projects/cgp-serde/reference/types/deserialize_with_context.md create mode 100644 docs/projects/cgp-serde/reference/types/serialize_with_context.md create mode 100644 docs/projects/cgp-serde/serde-comparison.md diff --git a/docs/projects/cgp-serde/_category_.json b/docs/projects/cgp-serde/_category_.json new file mode 100644 index 00000000..11cf88f6 --- /dev/null +++ b/docs/projects/cgp-serde/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "cgp-serde", + "position": 2, + "link": { + "type": "doc", + "id": "projects/cgp-serde/index" + } +} diff --git a/docs/projects/cgp-serde/architecture/_category_.json b/docs/projects/cgp-serde/architecture/_category_.json new file mode 100644 index 00000000..e64be334 --- /dev/null +++ b/docs/projects/cgp-serde/architecture/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Architecture", + "position": 2, + "link": { + "type": "doc", + "id": "projects/cgp-serde/architecture/index" + } +} diff --git a/docs/projects/cgp-serde/architecture/component-design.md b/docs/projects/cgp-serde/architecture/component-design.md new file mode 100644 index 00000000..ac3f35eb --- /dev/null +++ b/docs/projects/cgp-serde/architecture/component-design.md @@ -0,0 +1,160 @@ +--- +sidebar_label: 'Component design' +sidebar_position: 2 +description: 'Why cgp-serde moves the encoded value out of Self so the application chooses its encoding, one provider for both directions, and the reading lifetime.' +--- + +# Component design + +Why does moving one type out of `Self` change who chooses how a value is encoded? +[cgp-serde](../index.md) rebuilds Serde's `Serialize` and `Deserialize` as components of +[CGP](/docs/), and its components differ from Serde's traits in exactly that move. This page +explains the move and what it makes possible, how one provider can serve both directions, and how +deserializing carries Serde's lifetime. + +## Serde's trait belongs to the value + +Serde's `Serialize` is implemented by the type being serialized. Its method takes the value as +`self`: + +```rust +// Serde: implemented by the value's type +fn serialize(&self, serializer: S) -> Result +where + S: serde::Serializer; +``` + +So a type has one `Serialize` impl in the whole program, and Rust's coherence rules decide who may +write it: the crate that owns the type, or the crate that owns the trait. `Vec` is serialized as +a list of numbers because Serde's impl says so, and a program that wants hex has to wrap the type or +annotate every field. + +## cgp-serde's belongs to the context + +cgp-serde's serializing component, `CanSerializeValue`, keeps the method and adds one +parameter: + +```rust +// cgp-serde: implemented by a context, for each Value +fn serialize(&self, value: &Value, serializer: S) -> Result +where + S: serde::Serializer; +``` + +The value is now an argument, and `self` is a **context**, a type that stands for an application and +holds its choices. The deserializing component, `CanDeserializeValue<'de, Value>`, makes the same +change to `Deserialize`. Each is a CGP [component](/docs/concepts/consumer-and-provider-traits): a +trait that callers use, paired with a trait that providers implement, joined by the context's +wiring. + +The consequence is that each context chooses, for each value type, which provider serializes it: + +```rust +delegate_components! { + AppA { + open {ValueSerializerComponent}; + + @ValueSerializerComponent.Vec: + SerializeHex, + // ... + } +} +``` + +A second context can wire `Vec` to `SerializeBase64`, and the two do not conflict, because +each impl is for a different context. Nor does either context need to own `Vec` or the +component, since owning the context is enough to wire it. [Coherence](/docs/concepts/coherence) +explains why that is allowed. + +In the terms of the [modularity hierarchy](/docs/concepts/modularity-hierarchy), the contexts are +environmental, standing for applications rather than for data, and the serialized value is the +component's target. The hierarchy places this shape at the tier for a target whose behavior must +vary between contexts, and serialization is its motivating case: the types being encoded are usually +from other crates, and different applications need them encoded differently. + +## One provider can serve both directions + +A provider in CGP is a type that names an implementation, so one struct can implement both the +serializing and the deserializing component. cgp-serde does this wherever the two directions are one +decision. [`SerializeHex`](../reference/providers/serialize_hex.md) is one struct with two impls, +one that writes bytes as a hex string and one that reads a hex string back, and a context names it +once in each table: + +```rust +@ValueSerializerComponent.Vec: SerializeHex, +@ValueDeserializerComponent.Vec: SerializeHex, +``` + +The names follow from this. A provider named `Serialize…` may implement both directions, while one +named `Deserialize…` implements only reading. Where the two directions work differently, they are +separate providers named for how they work: a struct is written by reading its fields, and read by +building it field by field. This table pairs each provider that writes with the one that reads the +same encoding: + +| Writing | Reading | +|---|---| +| [`UseSerde`](../reference/providers/use_serde.md) | the same provider | +| [`SerializeString`](../reference/providers/serialize_string.md) | the same provider, for `String` | +| [`SerializeBytes`](../reference/providers/serialize_bytes.md) | the same provider, or [`TryDeserializeBytes`](../reference/providers/try_deserialize_bytes.md) for a fallible conversion | +| [`SerializeWithDisplay`](../reference/providers/serialize_with_display.md) | [`DeserializeWithFromStr`](../reference/providers/deserialize_with_from_str.md) | +| [`SerializeFrom`](../reference/providers/serialize_from.md) | the same provider | +| [`TrySerializeFrom`](../reference/providers/try_serialize_from.md) | the same provider | +| [`SerializeDeref`](../reference/providers/serialize_deref.md) | [`DeserializeAndAllocate`](../reference/providers/deserialize_and_allocate.md), for a reference | +| [`SerializeIterator`](../reference/providers/serialize_iterator.md) | [`DeserializeExtend`](../reference/providers/deserialize_extend.md) | +| [`SerializeFields`](../reference/providers/serialize_fields.md) | [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) | +| none | [`DeserializeDefault`](../reference/providers/deserialize_default.md), which wraps another reader | +| [`SerializeHex`](../reference/providers/serialize_hex.md), [`SerializeBase64`](../reference/providers/serialize_base64.md), [`SerializeRfc3339Date`](../reference/providers/serialize_rfc3339_date.md), [`SerializeTimestamp`](../reference/providers/serialize_timestamp.md) | the same providers | + +Sharing one struct makes agreement the intent, and a context still wires each direction on its own. +Nothing stops a context from writing with one encoding and reading with another, so a round trip in +a test is what confirms that the two halves match. + +## Deserializing carries Serde's lifetime + +Serde's `Deserialize<'de>` has a lifetime, so that a value can borrow from its input, such as a +`&'de str` pointing into the JSON text. `CanDeserializeValue<'de, Value>` keeps it as a parameter of +the component. That makes the lifetime part of what a context is checked for: a check on the +deserializing component lists each type paired with the lifetime, written as +[`Life<'de>`](/docs/reference/types/life). This check is from [`basic`](../examples/basic.md): + +```rust +check_components! { + #[check_trait(CanDeserializeApp)] + <'de> App { + ValueDeserializerComponent: [ + (Life<'de>, u64), + (Life<'de>, String), + (Life<'de>, Vec), + (Life<'de>, Payload), + ] + } +} +``` + +The serializing component has no lifetime, since writing a value never borrows from the output. + +## What it costs + +The move cannot be made to Serde's own traits without breaking every impl of them, so cgp-serde +defines new traits and connects them to Serde's, as [the bridge to Serde](./serde-bridge.md) +explains. Code that expects a `Serialize` value gets one through an adapter, not directly. + +The larger cost is that choice has to be exercised. Where Serde finds a type's impl automatically, a +cgp-serde context names a provider for every type it encodes, in each direction it encodes it. The +table is the price of each application being able to choose, and for a program that would make the +same choice everywhere, it is a cost with no return. + +## Where to go next + +- [Re-entrant providers](./reentrant-providers.md): how a context's choice for a type reaches every + place the type appears. +- [`basic`](../examples/basic.md): both components wired on one context, with `SerializeHex` in + both directions. +- [Modularity hierarchy](/docs/concepts/modularity-hierarchy): the tiers of choice CGP offers, and + when to move a value out of `Self`. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/architecture/context-services.md b/docs/projects/cgp-serde/architecture/context-services.md new file mode 100644 index 00000000..7bd9ac8b --- /dev/null +++ b/docs/projects/cgp-serde/architecture/context-services.md @@ -0,0 +1,154 @@ +--- +sidebar_label: 'Context services' +sidebar_position: 5 +description: 'How a cgp-serde deserializer takes a service such as an arena from its context, in layers that make the allocator a wiring choice.' +--- + +# Context services + +How does a deserializer get hold of something it needs while it works, such as an arena to allocate +into, when Serde's `Deserialize` receives nothing but the input? [cgp-serde](../index.md) rebuilds +Serde's `Serialize` and `Deserialize` as components of [CGP](/docs/), and every provider in it +receives the context. This page explains how a provider uses that to take a service from the +context, the layers the library's arena support is built in, and the lifetimes that let deserialized +values outlive the context. + +## A provider can ask the context for anything + +Serde's `Deserialize` has no receiver, and `serde_json::from_str` has no argument for extra state, +so a deserializer that needs an allocator, a lookup table, or a setting has nowhere to receive it. A +cgp-serde provider receives the **context**, the type that holds an application's choices, and it +can require any trait the context implements, not only the serialization components. It declares the +requirement with [`#[uses]`](/docs/reference/attributes/uses) and calls it on `self`, as it would +any method. This is CGP's [impl-side dependencies](/docs/concepts/impl-side-dependencies), applied +to a problem Serde's traits have no room for. + +The library's worked case is deserializing borrowed values. A `Payload<'a>` holding a +`Vec<&'a Coord>` points at `Coord` values that must live somewhere, and allocating them all into one +arena is cheaper than giving each a `Box`. The deserializer needs the arena while it runs, and it +takes it from the context. + +## Three layers, so the allocator is a choice + +The work is split into three layers, each a separate piece of wiring, so that the deserializer does +not decide how memory is allocated. + +**The deserializer** reads an owned value and asks the context to allocate it. +[`DeserializeAndAllocate`](../reference/providers/deserialize_and_allocate.md) is the whole of it: + +```rust +#[cgp_impl(new DeserializeAndAllocate)] +#[uses(CanAlloc<'a, Value>, CanDeserializeValue<'de, Value>)] +impl<'de, 'a, Value> ValueDeserializer<'de, &'a Value> { + fn deserialize(&self, deserializer: D) -> Result<&'a Value, D::Error> + where + D: serde::Deserializer<'de>, + { + let value = self.deserialize(deserializer)?; + let value = self.alloc(value); + + Ok(value) + } +} +``` + +It deserializes a `&'a Value` by asking the context to deserialize a `Value`, then to allocate it. +It knows nothing about arenas. + +**The allocation component** is what it asks for. +[`CanAlloc`](../reference/components/can_alloc.md) moves a value into storage that lives for `'a` +and returns a reference to it: + +```rust +#[cgp_component(Allocator)] +pub trait CanAlloc<'a, T> { + fn alloc(&self, value: T) -> &'a mut T; +} +``` + +**The implementation** answers it. +[`AllocateWithArena`](../reference/providers/allocate_with_arena.md) allocates into a +`typed_arena::Arena` that it gets from the context through an arena getter, a component whose +provider reads the arena from a field: + +```rust +#[cgp_impl(new AllocateWithArena)] +#[uses(HasArena<'a, Value>)] +impl<'a, Value: 'a> Allocator<'a, Value> { + fn alloc(&self, value: Value) -> &'a mut Value { + self.arena().alloc(value) + } +} +``` + +A context wires all three. These are the relevant entries from the repository's arena test, where +the context holds the arena in a field named `arena`: + +```rust +#[derive(HasField)] +pub struct App<'a> { + pub arena: &'a Arena, +} + +delegate_components! { + <'a> App<'a> { + open { + ValueDeserializerComponent, + // ... + }; + + ArenaGetterComponent: + UseField, + AllocatorComponent: + AllocateWithArena, + + @ValueDeserializerComponent.<'b> &'b Coord: + DeserializeAndAllocate, + + @ValueDeserializerComponent.<'b> Vec<&'b Coord>: + DeserializeExtend, + // ... + } +} +``` + +[`UseField`](/docs/reference/providers/use_field) points the arena getter at the `arena` field. +Swapping the allocator means wiring `AllocatorComponent` to a different provider, and neither the +deserializer nor any data type changes. The allocation component and the arena implementation are +in separate crates for the same reason, so that a program with its own allocator depends on the +component alone. + +## The values outlive the context + +A deserialized `Payload<'a>` stays valid after the context is gone, because the context only borrows +the arena. The caller creates the arena first and hands the context a reference to it, as +`&'a Arena`. `CanAlloc<'a, T>` returns references tied to that `'a`, not to the context, so +the values live as long as the arena does. + +The input's lifetime, `'de`, is separate from `'a`. The input can be dropped as soon as +deserializing finishes, because the values borrow from the arena rather than from the input. + +## What it costs + +Every service a provider draws from the context is one more thing the context must supply and wire, +and the layers add entries of their own: the arena version needs a getter entry and an allocator +entry besides the per-type entries. A single provider that reached into a field directly would be +shorter to read, at the price of fixing the allocator inside it. + +The pay-off is that a deserializer can depend on its surroundings without its caller threading the +dependency through every call. The context carries the arena, and every provider that needs it finds +it there. + +## Where to go next + +- [Crate layout](./crate-layout.md): why allocation is two crates, and what each crate depends on. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the CGP idea of a provider + declaring what it needs from its context. +- [Rust language proposals](/docs/comparisons/rust-language-proposals): the proposal for passing + context through Rust code, which this pattern resembles at the library level. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/architecture/crate-layout.md b/docs/projects/cgp-serde/architecture/crate-layout.md new file mode 100644 index 00000000..462ef50c --- /dev/null +++ b/docs/projects/cgp-serde/architecture/crate-layout.md @@ -0,0 +1,87 @@ +--- +sidebar_label: 'Crate layout' +sidebar_position: 6 +description: 'Why cgp-serde is five crates split along their external dependencies, what each adds, where items are imported from, and what it builds with.' +--- + +# Crate layout + +Why is a serialization library split into five crates? So that each external library it builds on +lives in a crate of its own, and an application compiles only the ones its wiring names. +[cgp-serde](../index.md) rebuilds Serde's `Serialize` and `Deserialize` as components of +[CGP](/docs/). This page lists its crates and what each adds, where items are imported from, and +what the workspace needs to build. + +## One crate per external dependency + +The core crate depends only on `cgp` and `serde`, and holds what every **context**, the type whose +wiring holds an application's choices, uses to serialize. Each other crate adds the external +libraries its own providers need, and nothing else: + +| Crate | What it adds | Depends on, beyond `cgp` and `serde` | +|---|---|---| +| `cgp-serde` | the two components, the two adapter types, and the core providers | nothing | +| `cgp-serde-extra` | the hex, base64, RFC 3339, and Unix-timestamp encodings | `cgp-serde`, `hex`, `base64`, `chrono` | +| `cgp-serde-json` | JSON serializing and deserializing as operations on the context | `cgp-serde`, `serde_json` | +| `cgp-serde-alloc` | the allocation component, and the deserializer that allocates through it | `cgp-serde` | +| `cgp-serde-typed-arena` | an implementation of allocation over an arena | `cgp-serde`, `cgp-serde-alloc`, `typed-arena` | + +Choosing an encoding is therefore also choosing a dependency: an application that wires hex and not +base64 compiles `hex` and not `base64`. None of the library crates names an error type either. The +JSON providers raise their errors into whatever error type the context wires, so the application +chooses it, as the [`basic`](../examples/basic.md) example does with `anyhow`. + +The repository's sixth crate, `cgp-serde-tests`, holds the tests the +[examples](../examples/index.md) walk through. + +## A data crate needs none of them + +A crate that only defines data types depends on `cgp`, to derive the field traits the struct +providers read, and on no cgp-serde crate and not on `serde`. The encoding is chosen by the +applications that use the types; see [derive-free records](./derive-free-records.md). + +## Why allocation is two crates + +The allocation component and its arena implementation are separate so that the allocator is a wiring +choice rather than a dependency of the deserializer. `cgp-serde-alloc` defines what allocating +means, and the deserializer that uses it, with no external dependency. `cgp-serde-typed-arena` is +one way to provide it, over the `typed-arena` crate. A program with a different allocator implements +the component itself and depends on `cgp-serde-alloc` alone; see [context +services](./context-services.md). + +## Where to import items from + +Every crate sorts its items into modules by kind, so an item's kind says where to import it from: + +- **`components`** — the serialization components, in `cgp-serde`. +- **`providers`** — the providers, in every crate, as in `cgp_serde::providers::SerializeFields` or + `cgp_serde_extra::providers::SerializeHex`. +- **`types`** — the adapter types, in `cgp-serde`. +- **`traits`** — components that support a provider, such as the allocation component in + `cgp-serde-alloc` and the arena getter in `cgp-serde-typed-arena`. +- **`code`** — the marker types that select the JSON operations, in `cgp-serde-json`. +- **`impls`** — the JSON convenience method, in `cgp-serde-json`. + +## What the workspace needs to build + +The workspace builds on stable Rust. Its `rust-toolchain.toml` pins the version it is developed +with, and its crates declare a minimum of Rust 1.90, with the 2024 edition. Every library crate is +`no_std`, and those that need `String` or `Vec` use `alloc`, so the library runs where the standard +library does not. + +## What it costs + +The split keeps each dependency optional, at the price of more crates to add: an application that +uses the extra encodings, JSON, and an arena depends on five cgp-serde crates and imports from each. +The examples use two to four of them. + +## Where to go next + +- [How cgp-serde works](./index.md): the design these crates implement. +- [Wiring a context](../guides/wiring-a-context.md): the crates in use, in a context's table. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/architecture/derive-free-records.md b/docs/projects/cgp-serde/architecture/derive-free-records.md new file mode 100644 index 00000000..b9bdc9bd --- /dev/null +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -0,0 +1,110 @@ +--- +sidebar_label: 'Derive-free records' +sidebar_position: 4 +description: 'How cgp-serde serializes a struct that derives only CGP''s general field traits, so a data crate needs no serde dependency, and what that approach gives up.' +--- + +# Derive-free records + +Can a struct be serialized if it derives nothing from Serde? [cgp-serde](../index.md) rebuilds +Serde's `Serialize` and `Deserialize` as components of [CGP](/docs/), and it serializes structs +that derive only CGP's general-purpose field traits. This page explains why that matters, what a +struct still has to derive, and what the approach gives up compared with Serde's derive. + +## With Serde, the type's owner decides + +A type is serializable with Serde only if its owner derives or implements Serde's traits for it. +Rust's orphan rule stops any other crate from implementing `Serialize` for it, so a library whose +types should be serializable has to depend on `serde` and derive the traits itself. An application +that wants a library's type encoded differently has to wrap it in a newtype or copy it. + +## With cgp-serde, one general derive is enough + +A struct that derives CGP's [`CgpData`](/docs/reference/derives/derive_cgp_data) exposes its fields +to generic code: the list of field names and types, a way to read each field, and a way to build the +struct one field at a time. This is CGP's [extensible records](/docs/concepts/extensible-records), +and it is not specific to serialization. The `basic` example's struct derives nothing else: + +```rust +#[derive(Debug, Eq, PartialEq, CgpData)] +pub struct Payload { + pub quantity: u64, + pub message: String, + pub data: Vec, +} +``` + +Two generic providers are written once against what `CgpData` exposes. +[`SerializeFields`](../reference/providers/serialize_fields.md) walks the field list and writes the +struct as a map from each field's name to its value, asking the **context**, the type whose wiring +holds an application's choices, to serialize each value. +[`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) reads the map back, +asking the context to deserialize each value, and fills the struct in field by field, reporting any +field the input left out. A context wires the struct to them like any other type: + +```rust +@ValueSerializerComponent.Payload: + SerializeFields, + +@ValueDeserializerComponent.Payload: + DeserializeRecordFields, +``` + +So a crate that defines data types needs to depend only on `cgp`, and each application that uses +them decides, in its own wiring, how they are encoded. + +## What a struct still derives + +The approach removes the serialization derive, not every derive. Each direction needs particular +field traits: writing needs the field list, from +[`HasFields`](/docs/reference/traits/shape/has_fields), and access to each field, from +[`HasField`](/docs/reference/traits/field-access/has_field); reading needs the field list and the +field-by-field builder, from [`BuildField`](/docs/reference/traits/builder/build_field). `CgpData` +derives all three. A struct that derives only the narrower ones, as the arena tests' structs derive +`HasFields` and `BuildField` for reading, works in the directions they cover. + +The same derive serves every other generic CGP code that works over fields, such as builders and +conversions between struct shapes, so one opt-in covers more than serialization. A type whose owner +has not derived the field traits, including any type from a crate that does not use CGP, cannot use +the struct providers; it is encoded through its own Serde impl with +[`UseSerde`](../reference/providers/use_serde.md) instead. + +## What it gives up + +The generic providers know only what the field list tells them: each field's name, its type, and +their order. They have no equivalent of the attributes Serde's derive reads, so every field is +written under its Rust name, and a field cannot be renamed, skipped, flattened, or given a default +when it is missing. Choices are made per type instead, through the context: a `Vec` field is +encoded however the context encodes `Vec`. + +The providers also cover one shape of type: structs with named fields. Tuple structs and enums are +not handled by them, and an enum is encoded through its own Serde impl, with `UseSerde`. The +[comparison with Serde](../serde-comparison.md) lists what Serde's derive does that cgp-serde's +struct providers do not. + +## What it costs + +A derive-free record trades Serde's per-field control for per-application control. Where Serde lets +the type's author annotate each field once, cgp-serde lets each application choose each type's +encoding, and that suits types whose encoding is the application's business rather than the +author's. For a type that has one right encoding, the author's annotations are the simpler place to +say it. + +The generic code is also compiled for each struct, as Serde's derived code is, so the approach saves +writing the code rather than compiling it. + +## Where to go next + +- [Context services](./context-services.md): deserializers that take something from the context + while they work. +- [`basic`](../examples/basic.md): a derive-free struct written to JSON and read back. +- [Extensible records](/docs/concepts/extensible-records): the CGP idea behind reading and building + a struct generically. +- [Reflection](/docs/comparisons/reflection): how this compares with Serde's derive and with + reflection in other languages. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/architecture/index.md b/docs/projects/cgp-serde/architecture/index.md new file mode 100644 index 00000000..3c94bcc9 --- /dev/null +++ b/docs/projects/cgp-serde/architecture/index.md @@ -0,0 +1,113 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'How cgp-serde works, in outline: Serde''s data-type layer replaced by components, the encoded value moved out of Self, and providers that ask the context.' +--- + +# How cgp-serde works + +How can one type be serialized two different ways in two applications, when Rust allows it only one +`Serialize` impl? [cgp-serde](../index.md) answers by rebuilding Serde's `Serialize` and +`Deserialize` as components of [CGP](/docs/), a language extension for Rust with pluggable trait +implementations at compile-time. This page explains the design in outline: which part of Serde it +replaces, what decides a type's encoding, and how that decision reaches every value nested inside +another. Each idea has a page of its own with the details. + +## It replaces one layer of Serde + +Serde has two sides. Formats such as `serde_json` implement its `Serializer` and `Deserializer` +traits, which know how to write strings, numbers, maps, and sequences. Data types implement its +`Serialize` and `Deserialize` traits, which decide how a value is described in those terms. + +cgp-serde replaces only the data-type side. Its implementations call the same format methods a +hand-written `Serialize` impl would, so every Serde format works with it unchanged, and any type +that already implements `Serialize` can keep using that impl. The [bridge to +Serde](./serde-bridge.md) page explains how values cross between the two in each direction. + +## The application decides how a type is encoded + +In Serde, `Serialize` is implemented by the type being serialized, so the type gets one encoding for +the whole program. cgp-serde's version turns this around. Its serializing component takes the value +as a parameter, and it is implemented by a **context**, a type that stands for an application and +holds that application's choices: + +```rust +pub struct AppA; + +delegate_components! { + AppA { + open {ValueSerializerComponent}; + + @ValueSerializerComponent.Vec: SerializeHex, + // ... + } +} +``` + +The context's wiring table names an implementation, called a **provider**, for each value type. So +`AppA` can write `Vec` as hex while another context writes it as base64, and neither needs to +own `Vec`. The compiler resolves each choice while it type-checks the program, so there is no +lookup at run time. The [component design](./component-design.md) page explains the move and why +one provider can serve both directions. + +## Providers hand nested values back to the context + +A provider for a struct or a collection does not encode the values inside it. It asks the context to +encode each one, and the context's table chooses the provider for that value's type. That is how +`AppA`'s choice for `Vec` reaches a byte field three structs deep, without any provider on the +way knowing about it. The [re-entrant providers](./reentrant-providers.md) page explains the two +ways a provider does this, and what it asks of the context's table. + +## A struct needs only CGP's field derive + +A struct becomes serializable by deriving CGP's general-purpose field traits, with +[`CgpData`](/docs/reference/derives/derive_cgp_data), and nothing from Serde. Two generic providers +read the field list those traits expose, one to write a struct and one to read it back. So a crate +can define data types without depending on `serde`, and each application decides how to encode them. +The [derive-free records](./derive-free-records.md) page explains what that gives and what it gives +up. + +## A provider can draw on its context + +Every provider method receives the context, so a provider can use anything the context offers. A +deserializer that needs somewhere to allocate borrowed values can take an arena from the context, +which Serde's `Deserialize` has no way to receive. The [context services](./context-services.md) +page explains this, and how the allocator itself becomes a wiring choice. + +## Each dependency lives in its own crate + +The core crate depends only on CGP and Serde. The hex, base64, and date encodings, the JSON helpers, +and the arena allocator each live in a crate of their own, so an application compiles only the +libraries its wiring names. The [crate layout](./crate-layout.md) page lists them. + +## What the design costs + +The flexibility is paid for in wiring. An application writes out a table naming a provider for every +type it encodes, including types that exist only along the way, such as a `Vec` of structs or the +string a hex encoding produces. A type the table misses is a compile error, and the error can be +long, since the compiler reports the whole path from the top-level value down to the missing entry. + +It also sets aside what Serde's derive does per field. The generic struct providers know a field's +name and type and nothing else, so there are no attributes for renaming or skipping a field; a +choice is made per type, for every field of that type. + +For a program that encodes each type one way, Serde's derive is simpler and more complete. The +design earns its cost when different applications need different encodings of the same types, when +the types belong to crates that should not depend on `serde`, or when deserializing needs something +from its surroundings. The [comparison with Serde](../serde-comparison.md) sets the two side by +side. + +## Where to go next + +- [The bridge to Serde](./serde-bridge.md): which part of Serde cgp-serde replaces, and how it + connects to the rest. +- [`messages`](../examples/messages.md): the design in a running program, two applications and one + value. +- [Modularity hierarchy](/docs/concepts/modularity-hierarchy): the CGP idea of moving a value out of + `Self`, with smaller examples. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/architecture/reentrant-providers.md b/docs/projects/cgp-serde/architecture/reentrant-providers.md new file mode 100644 index 00000000..acb8de03 --- /dev/null +++ b/docs/projects/cgp-serde/architecture/reentrant-providers.md @@ -0,0 +1,168 @@ +--- +sidebar_label: 'Re-entrant providers' +sidebar_position: 3 +description: 'How a cgp-serde provider hands each nested value back to the context, so one wiring choice reaches every level of a value.' +--- + +# Re-entrant providers + +When an application wires `Vec` to hex, how does that choice reach a byte field three structs +deep, when none of the providers in between knows about it? [cgp-serde](../index.md) rebuilds +Serde's `Serialize` and `Deserialize` as components of [CGP](/docs/), and its providers never encode +the values nested inside the one they are given. They hand each one back to the **context**, the +type whose wiring holds an application's choices, which is called re-entering it. This page explains +the two ways a provider re-enters the context, and what that asks of the context's wiring. + +## A provider asks the context, not the next impl + +In Serde, a struct's `Serialize` impl calls each field's own `Serialize` impl, so a `Vec` field +is written however Serde's impl for `Vec` writes it. The choice is fixed where that impl was +written. + +A cgp-serde provider makes the same call on the context instead. The struct provider, +[`SerializeFields`](../reference/providers/serialize_fields.md), serializes each field by asking the +context to serialize the field's type. The collection provider, +[`SerializeIterator`](../reference/providers/serialize_iterator.md), does the same for each item. +The context answers each request from its wiring table, so a context that wires `Vec` to hex +gets hex for every `Vec` it serializes: a top-level value, a field, or an item in a list inside +a field. + +This also keeps each provider small. `SerializeFields` knows how to walk a struct and nothing about +the fields' types, and `SerializeIterator` knows how to walk a collection and nothing about the +items. Each is written once, generically, and the context composes them. + +## Re-entering directly + +A provider that converts a value and encodes the result calls the context directly. +[`SerializeHex`](../reference/providers/serialize_hex.md) turns bytes into a hex string, then asks +the context to serialize the string: + +```rust +#[cgp_impl(SerializeHex)] +#[uses(CanSerializeValue)] +impl ValueSerializer +where + Value: ToHex, +{ + fn serialize(&self, value: &Value, serializer: S) -> Result + where + S: serde::Serializer, + { + let str_value = value.encode_hex::(); + self.serialize(&str_value, serializer) + } +} +``` + +Inside the impl, `self` is the context. [`#[uses]`](/docs/reference/attributes/uses) declares what +the provider needs from it, here the ability to serialize a `String`, and `self.serialize` is the +call. The requirement is resolved from the context's own wiring, which is CGP's +[impl-side dependencies](/docs/concepts/impl-side-dependencies). So even the string a hex encoding +produces is written the way the context says strings are written. + +## Re-entering through an adapter + +A provider that hands values to Serde needs another route. Serde's compound writers, such as the one +behind `serialize_seq`, take each element as a value implementing Serde's `Serialize`, and there is +no place to pass a context. So the provider wraps the element and the context together in +[`SerializeWithContext`](../reference/types/serialize_with_context.md), an adapter whose `Serialize` +impl calls the context. This is `SerializeIterator`: + +```rust +#[cgp_impl(new SerializeIterator)] +impl ValueSerializer +where + for<'a> &'a Value: IntoIterator, + Self: for<'a> CanSerializeValue<<&'a Value as IntoIterator>::Item>, +{ + fn serialize(&self, value: &Value, serializer: S) -> Result + where + S: serde::Serializer, + { + let items = value.into_iter(); + let mut serializer = serializer.serialize_seq(None)?; + for item in items { + serializer.serialize_element(&SerializeWithContext { + context: self, + value: &item, + })? + } + + serializer.end() + } +} +``` + +The `where` clause says the context must be able to serialize whatever iterating the collection +yields. It is written there rather than in `#[uses]` because the item type depends on the lifetime +of the borrow. Deserializing works the same way in the other direction, with +[`DeserializeWithContext`](../reference/types/deserialize_with_context.md) as the adapter that +Serde's readers accept. + +## What the context must wire + +Because every nested value goes back through the context, the context needs an entry for every type +the traversal reaches, which is more than the types in the data. Three kinds are easy to miss: + +- **Collections.** A `Vec` field needs an entry of its own, `SerializeIterator`, + besides the entry for `EncryptedMessage`. +- **References.** `SerializeIterator` walks a collection by reference, so a `Vec` + yields `&EncryptedMessage`, and the context must serialize that. One generic entry covers every + reference, forwarding it to the value behind it: + + ```rust + @ValueSerializerComponent.<'a, T> &'a T: + SerializeDeref, + ``` + +- **What an encoding produces.** Hex, base64, and RFC 3339 dates each produce a `String` and ask the + context to serialize it, and Unix timestamps produce an `i64`. A context wires those types even + when no field has them. + +Each provider's reference page says what it asks the context for. The rule of thumb is to start from +each top-level type and follow what each provider asks for until every request lands on a provider, +such as [`UseSerde`](../reference/providers/use_serde.md), that asks for nothing. The [wiring +guide](../guides/wiring-a-context.md) turns this into steps. + +## Mistakes are found at compile time + +The compiler follows these requests while it type-checks the program, so none of the traversal is +looked up at run time, and a type with no entry is a compile error rather than a failure while +serializing. The error names the whole path from the top-level type down to the missing entry, +which [the debugging guide](../guides/debugging-wiring.md) shows how to read. + +The same compile-time resolution rules out two shapes. A provider that re-enters the context for the +very type it handles, such as `String` wired to a provider that formats a value into a `String` and +serializes that, asks for itself forever, and the compiler reports that the lookup never resolves. +And a **recursive data type**, such as a tree node whose children are nodes, cannot be serialized by +the generic providers. Serializing the node requires serializing its children, which requires +serializing the node, and Rust's trait solver treats that cycle as an error, even with every entry +present. Such a type needs a provider written for it, one that walks the recursion itself and asks +the context only for the parts that are not recursive. + +## What it costs + +Re-entry is what makes one wiring line decide a type's encoding everywhere, and it is also why a +context's table is long: every type the traversal passes through is a question the table must +answer, including references and in-between strings that never appear in the data. The table is +checked completely by the compiler, but a reader has to understand the traversal to know why an +entry such as `i64` is there. + +A context also cannot make an exception for one place. Every `Vec` a context serializes gets the +same encoding, so two fields of the same type in one struct cannot be encoded differently, short of +giving one of them a distinct type. + +## Where to go next + +- [Derive-free records](./derive-free-records.md): the struct providers that re-enter for each + field. +- [`messages`](../examples/messages.md): re-entry through three levels of nesting, and the `i64` + entry left out. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the CGP idea behind a provider + asking its context for what it needs. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/architecture/serde-bridge.md b/docs/projects/cgp-serde/architecture/serde-bridge.md new file mode 100644 index 00000000..f32d3b8b --- /dev/null +++ b/docs/projects/cgp-serde/architecture/serde-bridge.md @@ -0,0 +1,129 @@ +--- +sidebar_label: 'The bridge to Serde' +sidebar_position: 1 +description: 'Which layer of Serde cgp-serde replaces and which it keeps, how values cross between cgp-serde and ordinary Serde code, and where errors are reported.' +--- + +# The bridge to Serde + +How can a library replace `Serialize` and still work with `serde_json`, and with every type that +already implements `Serialize`? [cgp-serde](../index.md) rebuilds Serde's data-type traits as +components of [CGP](/docs/), and keeps the rest of Serde as it is. This page explains which layer +it replaces, how values cross between cgp-serde and ordinary Serde code in each direction, and where +errors are reported. + +## Serde has two sides, and cgp-serde replaces one + +Serde separates what a value is from how a format writes it. On one side, formats such as +`serde_json` and RON implement the `Serializer` and `Deserializer` traits, which can write and read +a small set of shapes: strings, numbers, byte arrays, sequences, maps, and a few more. On the other +side, data types implement `Serialize` and `Deserialize`, which describe a value in those shapes. +The shapes are the contract between the two sides, and Serde calls them its data model. + +cgp-serde replaces the data-type side only. Its two components take the place of `Serialize` and +`Deserialize`, and its providers receive an ordinary Serde `Serializer` or `Deserializer` and call +the same methods a hand-written impl would, such as `serialize_str` or `serialize_map`. So a format +needs no changes to work with cgp-serde, and cgp-serde has no code for any particular format. + +## Going in: using a type's own Serde impl + +The bridge carries values in two directions. Going in, the provider +[`UseSerde`](../reference/providers/use_serde.md) lets a **context**, the type whose wiring holds an +application's choices, use a type's existing Serde impl. Its serializing half is one line of work: + +```rust +#[cgp_impl(UseSerde)] +impl ValueSerializer +where + Value: SerdeSerialize, +{ + fn serialize(&self, value: &Value, serializer: S) -> Result + where + S: serde::Serializer, + { + value.serialize(serializer) + } +} +``` + +`SerdeSerialize` is Serde's `Serialize`, imported under another name. Every `Serialize` impl, in the +standard library or in any crate, is therefore available to a context without a cgp-serde provider +being written for it; the context wires the type to `UseSerde`. This is also how a context handles a +type that cgp-serde's generic providers do not cover, such as an enum with a derived impl. + +The trade is that the context's choices stop at that value. The type's own impl serializes its +contents, so a `Vec` inside it is written the way that impl writes it, whatever the context +wires for `Vec`. + +## Going out: handing a context to a Serde API + +Going out, two adapter types let a context and a value enter any Serde API. +[`SerializeWithContext`](../reference/types/serialize_with_context.md) pairs a context with a value +and implements Serde's `Serialize`, so it can be passed to `serde_json::to_string` or any other +format's entry point: + +```rust +let serialized = + serde_json::to_string_pretty(&SerializeWithContext::new(&AppA, &archive)).unwrap(); +``` + +[`DeserializeWithContext`](../reference/types/deserialize_with_context.md) does the same for +reading. It implements Serde's `DeserializeSeed`, the trait for deserializing with state, where the +state is the context. Serde's convenience functions such as `serde_json::from_str` accept only a +type that implements `Deserialize`, not a seed, so a program builds the format's deserializer itself +and drives the seed with it. The [JSON +providers](../reference/providers/deserialize_from_json_reader.md) do this for `serde_json`, and +[using a format](../guides/formats.md) shows the few lines another format needs. + +The same two adapters work inside cgp-serde. When a provider hands a nested value to one of Serde's +compound writers or readers, it wraps the value in an adapter, which is how the context's choices +reach nested values; see [re-entrant providers](./reentrant-providers.md). + +## Where errors are reported + +Errors are reported at two levels. Inside a serialization, a provider reports a failure through the +format's own error type, with Serde's `Error::custom`, exactly as a hand-written Serde impl does. An +invalid hex digit or a missing struct field is reported this way, and the format adds its position +to the message. + +At the edge, the JSON providers turn the finished `serde_json::Error` into the context's own error +type, using CGP's [modular error handling](/docs/concepts/modular-error-handling), so a caller gets +whatever error type the context wires, such as `anyhow::Error`. A program that calls `serde_json` +through the adapters directly skips this level and gets `serde_json`'s error unchanged. + +## What the output looks like to a format + +Because cgp-serde writes values through Serde's ordinary methods, a format sees the shapes its +providers choose, and two of those choices affect which formats accept the output: + +- **Structs are written as maps.** The generic struct provider writes a map from field names to + values, where Serde's derive writes a struct. JSON writes both the same way. A format with its own + struct syntax, such as RON, writes a map. +- **Lengths are not declared.** The generic struct and collection providers start a map or sequence + without saying how long it is. Self-describing formats such as JSON and RON do not need to know, + but a length-prefixed binary format such as postcard does, and rejects the output. + +## What it costs + +Keeping Serde's formats means keeping Serde's interface for them, and that interface was designed +for stateless types. Serializing needs only the adapter, but deserializing through a context needs a +seed, which Serde's one-line helpers do not accept, so every format gets a few lines of entry-point +code, written once. And a value handed to `UseSerde` is outside the context's reach, so the boundary +between the two layers is a decision a context makes type by type. + +The benefit is that adoption can be partial. A program can use cgp-serde for the types whose +encoding it wants to choose, and Serde's derive for the rest, in the same value and the same format. + +## Where to go next + +- [Component design](./component-design.md): the two components that replace `Serialize` and + `Deserialize`. +- [Using a format](../guides/formats.md): serializing and deserializing with `serde_json` and other + formats. +- [`messages`](../examples/messages.md): the adapter handing two contexts to `serde_json`. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/examples/_category_.json b/docs/projects/cgp-serde/examples/_category_.json new file mode 100644 index 00000000..acf6d786 --- /dev/null +++ b/docs/projects/cgp-serde/examples/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Examples", + "position": 1, + "link": { + "type": "doc", + "id": "projects/cgp-serde/examples/index" + } +} diff --git a/docs/projects/cgp-serde/examples/basic.md b/docs/projects/cgp-serde/examples/basic.md new file mode 100644 index 00000000..f0434e20 --- /dev/null +++ b/docs/projects/cgp-serde/examples/basic.md @@ -0,0 +1,270 @@ +--- +sidebar_label: 'basic' +sidebar_position: 1 +description: 'A cgp-serde test that writes a struct to JSON and reads it back, with no serialization derive and each field type''s encoding chosen by the context.' +--- + +# Write a struct to JSON and read it back + +This test writes a struct to a JSON string and reads it back, through a **context**, the type whose +wiring holds the application's choices, which decides how each of the struct's field types is +encoded. It is an example from +[cgp-serde](../index.md), which rebuilds Serde's `Serialize` and `Deserialize` traits as components +of [CGP](/docs/). The struct derives nothing from Serde, and its bytes come out as hex because one +wiring line says so. + +:::tip + +### New to CGP? + +The [Hello World tutorial](/docs/tutorials/hello) introduces contexts, providers, and wiring with a +smaller program. [Coherence](/docs/concepts/coherence) explains why Rust gives a type only one +`Serialize` impl, which is the limit this library removes. This page can be read without either. + +::: + +## Run it + +From the root of the [cgp-serde repository](https://github.com/contextgeneric/cgp-serde): + +```sh +cargo test -p cgp-serde-tests basic +``` + +The test passes: + +```text +test tests::basic::test_basic_serialization ... ok +``` + +It asserts that the struct serializes to exactly this JSON, and that reading the JSON back gives the +original value: + +```json +{"quantity":42,"message":"hello","data":"010203"} +``` + +## The struct derives nothing from Serde + +The data type is an ordinary struct, from +[`basic.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-tests/src/tests/basic.rs): + +```rust +#[derive(Debug, Eq, PartialEq, CgpData)] +pub struct Payload { + pub quantity: u64, + pub message: String, + pub data: Vec, +} +``` + +`Debug`, `Eq`, and `PartialEq` are there for the test's assertions. The only other derive is CGP's +[`CgpData`](/docs/reference/derives/derive_cgp_data), which exposes the struct's field names and +types to generic code and lets generic code build the struct one field at a time. It is not specific +to serialization, and nothing in the struct says how any field is encoded. cgp-serde's record +providers read what `CgpData` exposes, as [derive-free +records](../architecture/derive-free-records.md) explains. + +## One context holds every choice + +The test runs on `App`, a type that stands for this application, which is where its choices live. It +has no fields, because every choice it makes is in its wiring: + +```rust +pub struct App; + +delegate_components! { + App { + open { + ValueSerializerComponent, + ValueDeserializerComponent, + TryComputerComponent, + }; + + ErrorTypeProviderComponent: + UseAnyhowError, + + ErrorRaiserComponent: + RaiseAnyhowError, + + @ValueSerializerComponent.u64: + UseSerde, + + @ValueSerializerComponent.String: + SerializeString, + + @ValueSerializerComponent.Vec: + SerializeHex, + + @ValueSerializerComponent.Payload: + SerializeFields, + + @ValueDeserializerComponent.[ + u64, + String, + ]: + UseSerde, + + @ValueDeserializerComponent.Payload: + DeserializeRecordFields, + + @ValueDeserializerComponent.Vec: SerializeHex, + + @TryComputerComponent.SerializeJson: + SerializeToJsonString, + + @TryComputerComponent. DeserializeJson: + DeserializeFromJsonString, + } +} +``` + +[`delegate_components!`](/docs/reference/macros/delegate_components) writes the wiring table. The +`open` statement at the top lets the table choose a different provider for each value type, and +each `@` entry makes one choice. `@ValueSerializerComponent.u64: UseSerde` reads "to serialize a +`u64`, use `UseSerde`". `ValueSerializerComponent` and `ValueDeserializerComponent` are cgp-serde's +two components, its versions of `Serialize` and `Deserialize`. + +The value being encoded is a parameter of the component, not the type that implements it. That is +the difference from Serde, where `Payload` itself would implement `Serialize`. Here `App` implements +serialization *for* `Payload`, `u64`, and the rest, so a second application could wire the same +types to different providers without either conflicting with the other. + +The providers each do one job: + +- [`UseSerde`](../reference/providers/use_serde.md) uses the type's own Serde impl, which suits + `u64`. +- [`SerializeString`](../reference/providers/serialize_string.md) writes anything string-like as a + string. +- [`SerializeHex`](../reference/providers/serialize_hex.md) writes bytes as a hex string, and reads + them back. +- [`SerializeFields`](../reference/providers/serialize_fields.md) writes a struct as a map from + field names to values, and + [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) reads one back. + +The two directions are wired separately, so they can name different providers. `String` is written +by `SerializeString` and read by `UseSerde`, which agree on the JSON. `Vec` names `SerializeHex` +in both directions, because one struct implements both halves of the hex encoding. + +## The struct's provider asks the context for its fields + +`SerializeFields` knows how to walk a struct, but not how to encode any field. For each field, it +asks the context to serialize the field's type, and the context's wiring answers. That is why `App` +has entries for `u64`, `String`, and `Vec` as well as for `Payload`: they are the types the +struct's provider hands back. + +The same handing back is what lets a choice reach every level of a nested value. Wire `Vec` to +`SerializeHex`, and every `Vec` the context serializes is hex, wherever it sits. +[Re-entrant providers](../architecture/reentrant-providers.md) explains the mechanism, and +[`messages`](./messages.md) shows it through three levels of nesting. + +## JSON is an operation the context runs + +The last two entries make JSON encoding something `App` can do. They are keyed on CGP's +[`TryComputer`](/docs/reference/components/handler/try_computer), an interface for a fallible +computation chosen by a marker type, and the markers `SerializeJson` and `DeserializeJson` pick +the JSON providers. The test calls both through `try_compute`: + +```rust +let serialized = context + .try_compute(PhantomData::, &value) + .unwrap(); + +let deserialized: Payload = context + .try_compute(PhantomData::>, &serialized) + .unwrap(); +``` + +The generic ` DeserializeJson` entry sends every target type to one provider. The providers +run `serde_json` through the context's serialization wiring, so the JSON follows every choice above. + +A JSON error needs an error type to become, and the two error entries supply it. They make the +context's error type `anyhow::Error`, using the providers of the `cgp-error-anyhow` crate, so the +calls return `anyhow::Error` with `serde_json`'s message inside. With the `data` field removed from +the input, reading it back fails with: + +```text +missing field: data at line 1 column 33 +``` + +The providers do not name an error type of their own; the context chooses it. [Modular error +handling](/docs/concepts/modular-error-handling) explains how. + +## Checking both directions + +Wiring is checked when it is used, so the test asserts that every entry resolves with +[`check_components!`](/docs/reference/macros/check_components), once per direction: + +```rust +check_components! { + #[check_trait(CanUseAppSerializer)] + App { + ValueSerializerComponent: [ + u64, + String, + Vec, + Payload, + ], + } +} + +check_components! { + #[check_trait(CanDeserializeApp)] + <'de> App { + ValueDeserializerComponent: [ + (Life<'de>, u64), + (Life<'de>, String), + (Life<'de>, Vec), + (Life<'de>, Payload), + ] + } +} +``` + +The deserializing component carries Serde's `'de` lifetime as a parameter, so its entries pair each +type with the lifetime, written as [`Life<'de>`](/docs/reference/types/life). Each table has its +own `#[check_trait]` name, because two checks of one context in one module would otherwise derive +the same name. + +## Try a change + +Change the encoding of the bytes from hex to base64 by replacing `SerializeHex` with +`SerializeBase64` in both `Vec` entries, and importing it from `cgp_serde_extra::providers`. +Nothing else changes. Run the test again, and its first assertion fails, printing the new JSON: + +```text +assertion `left == right` failed + left: "{\"quantity\":42,\"message\":\"hello\",\"data\":\"AQID\"}" + right: "{\"quantity\":42,\"message\":\"hello\",\"data\":\"010203\"}" +``` + +The bytes `[1, 2, 3]` are now `"AQID"`. Update the expected string to match, and the test passes +again, reading the base64 back into the same `Payload`. The struct and the calls were not touched; +the encoding lived only in the wiring. + +## The pattern + +This test shows **serialization as a choice made by the context, one type at a time**. The +component takes the encoded value as a parameter, so the context, not the data type, chooses the +provider for each value type, and a provider for a struct asks the context about the struct's +fields. The same move makes the error type the context's choice too. [Modularity +hierarchy](/docs/concepts/modularity-hierarchy#tier-4-one-provider-per-target-type-per-context) +places this shape among CGP's options, as the one for a target type whose behavior must vary between +contexts. + +The cost is the table. Every type the context encodes needs an entry in each direction, and the two +directions are wired separately, so nothing but a round trip checks that they agree. For a program +that encodes each type one way, Serde's derive is shorter. + +## Where to go next + +- [`messages`](./messages.md): the next example, two applications encoding one value differently. +- [Wiring a context](../guides/wiring-a-context.md): how to build and check a table like `App`'s. +- [Coherence](/docs/concepts/coherence): why moving the value out of `Self` lets implementations + overlap. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/examples/index.md b/docs/projects/cgp-serde/examples/index.md new file mode 100644 index 00000000..ad44d88f --- /dev/null +++ b/docs/projects/cgp-serde/examples/index.md @@ -0,0 +1,57 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'The cgp-serde tests as short tutorials: a JSON round trip with no serialization derive, and one value encoded two ways by two applications.' +--- + +# cgp-serde examples + +These pages walk through the tests in the [cgp-serde +repository](https://github.com/contextgeneric/cgp-serde), one test per page. The tests are the +repository's runnable examples. [cgp-serde](../index.md) rebuilds Serde's `Serialize` and +`Deserialize` traits as components of [CGP](/docs/), so that each application chooses how a type is +encoded. Each page runs a test, explains how its wiring produces what it prints, and names the CGP +pattern it shows, so the pages work as short tutorials on those patterns. + +The pages are in the order they teach. Each stands alone, but a reader new to cgp-serde should start +with [`basic`](./basic.md), since the later pages build on the wiring it introduces. + +:::tip + +### New to CGP? + +These pages explain cgp-serde's code without deriving CGP from first principles. The [Hello World +tutorial](/docs/tutorials/hello) introduces CGP in a few minutes, and +[Coherence](/docs/concepts/coherence) explains the Rust rule that cgp-serde works around, with a +smaller encoding example. Neither is required reading; each page links what it relies on. + +::: + +## Running an example + +Clone the repository and run an example from its root with `cargo test -p cgp-serde-tests `. +Add `-- --nocapture` to see what a test prints. The repository's toolchain file selects the Rust +version, and no example needs a network or any program outside the build. + +## The examples + +- [`basic`](./basic.md) — one struct written to JSON and read back by a context, the type that holds + an application's choices, with the struct's bytes as hex and a missing field reported as an error. +- [`messages`](./messages.md) — one nested archive encoded by two contexts that differ in three + wiring lines, with hex bytes and RFC 3339 dates from one and base64 bytes and Unix timestamps from + the other. + +Two more tests, `arena_simplified` and `arena`, deserialize borrowed values into an arena that the +context supplies. Their pages are still being written; [context +services](../architecture/context-services.md) explains the design they show. + +## Where to go next + +- [Architecture](../architecture/index.md): the design behind every example, one idea per page. +- [Wiring a context](../guides/wiring-a-context.md): the steps the examples share, as a guide. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md new file mode 100644 index 00000000..d7138f85 --- /dev/null +++ b/docs/projects/cgp-serde/examples/messages.md @@ -0,0 +1,290 @@ +--- +sidebar_label: 'messages' +sidebar_position: 2 +description: 'A cgp-serde test in which two application contexts encode one nested value differently, hex and RFC 3339 against base64 and Unix time.' +--- + +# Encode one value two ways in two applications + +This test serializes one nested archive of messages twice, under two applications that disagree +about how bytes and dates should look. It is an example from [cgp-serde](../index.md), which +rebuilds Serde's `Serialize` and `Deserialize` traits as components of [CGP](/docs/). The data types +name no encoding, and the two applications differ in three wiring lines, which is the whole +difference between the two JSON documents they produce. + +:::tip + +### New to CGP? + +[`basic`](./basic.md) introduces the wiring table this page builds on. For CGP itself, the [Hello +World tutorial](/docs/tutorials/hello) shows contexts and wiring with a smaller program, and +[Coherence](/docs/concepts/coherence) explains why plain Rust allows only one encoding per type, +which is what two applications here get around. This page can be read without them. + +::: + +## Run it + +From the root of the [cgp-serde repository](https://github.com/contextgeneric/cgp-serde), run the +test and show what it prints: + +```sh +cargo test -p cgp-serde-tests messages -- --nocapture +``` + +It prints the same archive twice. From the first application, `AppA`, bytes are hex and dates are +RFC 3339 strings: + +```text +serialized with A: { + "decryption_key": "746f702d736563726574", + "messages_by_topics": [ + { + "encrypted_topic": "416c6c2061626f757420434750", + "messages": [ + { + "message_id": 1, + "author_id": 2, + "date": "2025-11-03T14:15:00+00:00", + "encrypted_data": "48656c6c6f2066726f6d20527573744c616221" + }, + { + "message_id": 4, + "author_id": 8, + "date": "2025-12-19T23:45:00+00:00", + "encrypted_data": "4f6e65207965617220616e6e697665727361727921" + } + ] + } + ] +} +``` + +From the second, `AppB`, bytes are base64 and dates are Unix timestamps: + +```text +serialized with B: { + "decryption_key": "dG9wLXNlY3JldA==", + "messages_by_topics": [ + { + "encrypted_topic": "QWxsIGFib3V0IENHUA==", + "messages": [ + { + "message_id": 1, + "author_id": 2, + "date": 1762179300, + "encrypted_data": "SGVsbG8gZnJvbSBSdXN0TGFiIQ==" + }, + { + "message_id": 4, + "author_id": 8, + "date": 1766187900, + "encrypted_data": "T25lIHllYXIgYW5uaXZlcnNhcnkh" + } + ] + } + ] +} +``` + +The test prints the documents rather than asserting them, and passes when both serialize. + +## The data names no encoding + +The archive is three nested structs, from +[`messages.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-tests/src/tests/messages.rs): + +```rust +#[derive(CgpData)] +pub struct EncryptedMessage { + pub message_id: u64, + pub author_id: u64, + pub date: DateTime, + pub encrypted_data: Vec, +} + +#[derive(CgpData)] +pub struct MessagesByTopic { + pub encrypted_topic: Vec, + pub messages: Vec, +} + +#[derive(CgpData)] +pub struct MessagesArchive { + pub decryption_key: Vec, + pub messages_by_topics: Vec, +} +``` + +Byte fields appear at every level, and dates in the innermost struct. Nothing in the structs says +how either is written. [`CgpData`](/docs/reference/derives/derive_cgp_data) only exposes the fields +to generic code, and `Vec` and `DateTime` belong to other crates, so in Serde their +encoding would be whatever those crates' `Serialize` impls chose. + +## Each application is a context with its own table + +`AppA` is a type that stands for the first application, which is where its choices live. It has no +fields, and its wiring table names a provider for each type the archive contains: + +```rust +pub struct AppA; + +delegate_components! { + AppA { + open {ValueSerializerComponent}; + + @ValueSerializerComponent.<'a, T> &'a T: + SerializeDeref, + + @ValueSerializerComponent.[ + u64, + String, + ]: + UseSerde, + + @ValueSerializerComponent.Vec: + SerializeHex, + + @ValueSerializerComponent.DateTime: + SerializeRfc3339Date, + + @ValueSerializerComponent.[ + Vec, + Vec, + ]: + SerializeIterator, + + @ValueSerializerComponent.[ + MessagesArchive, + MessagesByTopic, + EncryptedMessage, + ]: + SerializeFields, + } +} +``` + +The `open` statement lets the table choose by the type being serialized, and each `@` entry makes +one choice, as in [`basic`](./basic.md). A bracketed list gives several types the same provider. + +`AppB` is a second context with the same table, except for three entries: + +```rust +@ValueSerializerComponent.[ + i64, + u64, + String, +]: + UseSerde, + +@ValueSerializerComponent.Vec: + SerializeBase64, + +@ValueSerializerComponent.DateTime: + SerializeTimestamp, +``` + +[`SerializeHex`](../reference/providers/serialize_hex.md) and +[`SerializeBase64`](../reference/providers/serialize_base64.md) are two providers for the same type, +`Vec`, and so are [`SerializeRfc3339Date`](../reference/providers/serialize_rfc3339_date.md) +and [`SerializeTimestamp`](../reference/providers/serialize_timestamp.md) for `DateTime`. As +Serde impls they would conflict, since a type can have only one. As entries in two contexts' tables +they do not, because each choice holds only within the context that makes it. +[Coherence](/docs/concepts/coherence) explains why that is allowed. + +## A choice reaches every level of nesting + +Neither table says anything about where a `Vec` appears, and yet every byte field in the +archive, at all three levels, follows its context's choice. That is because no provider encodes the +values inside the one it is given. [`SerializeFields`](../reference/providers/serialize_fields.md) +walks a struct and asks the context to serialize each field, and +[`SerializeIterator`](../reference/providers/serialize_iterator.md) walks a collection and asks the +context to serialize each item. Each of those requests goes back through the same table, so the +context's choice for a type applies wherever the type turns up. [Re-entrant +providers](../architecture/reentrant-providers.md) explains the mechanism. + +## Entries the traversal needs + +Because every nested value goes back through the table, the table needs an entry for every type the +traversal reaches, not only for the fields in the data. Four entries exist for that reason: + +- **Each vector of structs** gets `SerializeIterator`. A `Vec` is a value the + traversal reaches, so it needs an entry of its own besides the one for `EncryptedMessage`. +- **The generic reference entry**, `<'a, T> &'a T`, sends every reference to + [`SerializeDeref`](../reference/providers/serialize_deref.md), which serializes the value behind + it. Walking a borrowed `Vec` yields `&EncryptedMessage`, and this one entry + covers every such reference. +- **`String`** is wired, although no field is a `String`, because the hex, base64, and RFC 3339 + providers each produce a string and ask the context to serialize it. +- **`i64`** is wired in `AppB`, although no field is an `i64`, because `SerializeTimestamp` turns + the date into an `i64` and asks the context to serialize that. + +The last point is the easiest to miss, and the change at the end of this page shows what happens +without it. + +## Serializing through an ordinary Serde API + +Each context's wiring is asserted by a +[`check_components!`](/docs/reference/macros/check_components) table listing the seven types it +serializes. Then the test hands each context and the archive to `serde_json`: + +```rust +let serialized = + serde_json::to_string_pretty(&SerializeWithContext::new(&AppA, &archive)).unwrap(); +println!("serialized with A: {serialized}"); +``` + +[`SerializeWithContext`](../reference/types/serialize_with_context.md) pairs a context with a value +and implements Serde's own `Serialize` trait, so any Serde format accepts it unchanged. Any error is +`serde_json`'s own, which is why neither context wires an error type. + +## Try a change + +Remove `i64` from `AppB`'s `UseSerde` entry, leaving `[u64, String]`, and run +[`cargo cgp check`](/docs/cargo-cgp/check). The check on `AppB` fails, and the tool names the +missing entry as the root cause: + +```text +error[E0277]: [CGP-E001] the consumer traits `CanSerializeValue>`, `CanSerializeValue`, `CanSerializeValue`, and `CanSerializeValue` are not implemented for context `AppB` + = note: root cause: [CGP-E107] context `AppB` does not contain any delegate entry for `@ValueSerializerComponent.i64` +``` + +Every checked type that contains a date fails, and all for one reason. Below the root cause, the +tool prints the chain that leads to it: from `MessagesArchive` through `SerializeFields`, the +vectors, the references, and `EncryptedMessage`, down to `SerializeTimestamp`, which asks `AppB` for +an `i64` it has no entry for. The fix is to put `i64` back. `cargo cgp check` leads with the root +cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every +class. + +## The pattern + +This test shows **two applications choosing different implementations for the same types, without +a conflict**. Each application is a context, the serialized value is a parameter of the component, +and a context's table decides the provider for each value type, including types from other crates. +Because every provider hands nested values back to the context, one entry decides a type's encoding +everywhere in the value. The idea is CGP's local answer to Rust's coherence rule, explained in +[Coherence](/docs/concepts/coherence), and [Modularity +hierarchy](/docs/concepts/modularity-hierarchy#tier-4-one-provider-per-target-type-per-context) +places it among the alternatives. + +The cost is the table each application writes. `AppA` and `AppB` share all but three entries and +still list every one, and both carry entries, such as the reference entry and `AppB`'s `i64`, that +serve the traversal rather than the data. The shared entries can move into a namespace the two +contexts join, as the last step of [wiring a +context](../guides/wiring-a-context.md#6-share-entries-between-contexts-with-a-namespace) shows, but +the traversal's entries are still there to write. A program that needs one encoding per type gets it +from Serde's derive with none of this. + +## Where to go next + +- [Architecture](../architecture/index.md): the design this example rests on, one idea per page. +- [Wiring a context](../guides/wiring-a-context.md): how to find every type a traversal reaches, and + how to check the table. +- [Coherence](/docs/concepts/coherence): the Rust rule that gives a type one impl, and how CGP + restores choice one context at a time. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/guides/_category_.json b/docs/projects/cgp-serde/guides/_category_.json new file mode 100644 index 00000000..415fc227 --- /dev/null +++ b/docs/projects/cgp-serde/guides/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Guides", + "position": 3, + "link": { + "type": "generated-index", + "description": "How to wire a cgp-serde context, write a provider, use a format, and debug the wiring." + } +} diff --git a/docs/projects/cgp-serde/guides/debugging-wiring.md b/docs/projects/cgp-serde/guides/debugging-wiring.md new file mode 100644 index 00000000..be5604dd --- /dev/null +++ b/docs/projects/cgp-serde/guides/debugging-wiring.md @@ -0,0 +1,271 @@ +--- +sidebar_label: 'Debugging the wiring' +sidebar_position: 4 +description: 'The common cgp-serde wiring mistakes, each with the code that makes it, the error cargo cgp check reports, and the fix.' +--- + +# Debugging the wiring + +Most compile errors in a [cgp-serde](../index.md) **context**, the type whose wiring holds an +application's choices, come from a handful of wiring mistakes, and each has an error that is easy to +recognize once seen. cgp-serde rebuilds Serde's `Serialize` and `Deserialize` as components of +[CGP](/docs/). This guide shows each mistake with the code that makes it, the error, and the fix. + +The errors below come from [`cargo cgp check`](/docs/cargo-cgp/check), CGP's error tool, run in +place of `cargo check`. `cargo cgp check` leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. Each mistake is caught by a +[`check_components!`](/docs/reference/macros/check_components) table listing the context's types, +as [wiring a context](./wiring-a-context.md#5-check-every-value-type) recommends, and the errors are +shorter and clearer there than at the first call. + +## A type the traversal reaches has no entry + +**The most common mistake is a missing entry for a nested type.** Here `Payload` is wired to +[`SerializeFields`](../reference/providers/serialize_fields.md), but the type of its `data` field +has no entry: + +```rust +#[derive(CgpData)] +pub struct Payload { + pub quantity: u64, + pub data: Vec, +} + +pub struct App; + +delegate_components! { + App { + open ValueSerializerComponent; + @ValueSerializerComponent.u64: UseSerde, + @ValueSerializerComponent.Payload: SerializeFields, + } +} + +check_components! { + App { + ValueSerializerComponent: [u64, Payload], + } +} +``` + +The check fails on `Payload`, and the tool names the missing entry, then the path that leads to it: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanSerializeValue` is not implemented for context `App` + = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `@ValueSerializerComponent.Vec` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanSerializeValue` for context `App` + └─ [CGP-E104] redirect lookup to `@ValueSerializerComponent` in `App` + └─ [CGP-E102] provider trait impl `ValueSerializer` with context `App` for provider `SerializeFields` + └─ [CGP-E105] trait impl `FieldsSerializer` for `Struct! { quantity: u64, data: Vec }` + └─ [CGP-E105] trait impl `FieldsSerializer` for `Struct! { data: Vec }` + └─ [CGP-E101] consumer trait impl `CanSerializeValue>` for context `App` + └─ [CGP-E104] redirect lookup to `@ValueSerializerComponent` in `App` + └─ [CGP-E107] context `App` does not contain any delegate entry for `@ValueSerializerComponent.Vec` +``` + +The chain reads from the top down: serializing `Payload` goes to `SerializeFields`, which walks the +fields to `data`, which asks the context for a `Vec`, which the table does not have. However +deep the missing type sits, the root cause names it. The fix is an entry for `Vec`, such as +`@ValueSerializerComponent.Vec: SerializeHex`. + +## An entry for a type no field has + +The same error, naming a different type, covers three entries that are easy to miss because no field +in the data has the type. + +**A reference, for `SerializeIterator`.** Wiring a `Vec` to +[`SerializeIterator`](../reference/providers/serialize_iterator.md) with only a `u64` entry fails, +because walking the vector by reference yields `&u64`: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanSerializeValue>` is not implemented for context `Ctx` + = note: root cause: [CGP-E107] context `Ctx` does not contain any delegate entry for `@ValueSerializerComponent.&u64` +``` + +The fix is the generic reference entry, `@ValueSerializerComponent.<'a, T> &'a T: SerializeDeref`, +which covers every reference at once. + +**What an encoding produces.** Wiring `DateTime` to +[`SerializeTimestamp`](../reference/providers/serialize_timestamp.md) without an `i64` entry fails +with a missing `@ValueSerializerComponent.i64`, because the timestamp is serialized through the +context. Hex, base64, and RFC 3339 dates need `String` the same way. The +[`messages`](../examples/messages.md#try-a-change) example shows this case in full. + +**A service a provider takes from the context.** Wiring `&'b Coord` to +[`DeserializeAndAllocate`](../reference/providers/deserialize_and_allocate.md) without an entry for +`AllocatorComponent` fails, because the provider allocates through the context. In the repository's +arena test, with the allocator entry removed, the check on the borrowed types reports: + +```text +error[E0277]: [CGP-E001] the consumer traits `CanDeserializeValue<&Coord>` and `CanDeserializeValue>` are not implemented for context `App<'_>` + = note: root cause: [CGP-E107] context `App<'_>` does not contain any delegate entry for `AllocatorComponent` +``` + +The fix is the entry `AllocatorComponent: AllocateWithArena`, or another allocation provider; see +[context services](../architecture/context-services.md). + +## A reading check leaves out the lifetime + +**A check on the deserializing component without `Life<'de>` reports a provider that does not +implement the component, rather than a missing entry.** Here `u64` is wired, and the check still +fails: + +```rust +check_components! { + App { + ValueDeserializerComponent: u64, + } +} +``` + +```text +error[E0277]: [CGP-E002] the provider trait `ValueDeserializer` with context `App` is not implemented for provider `RedirectLookup` +``` + +The clue is further down the error, in the list of what the provider does implement, which includes +`IsProviderFor, Value)>`. The component's +parameters are a lifetime and a type, and the check gave only the type. The fix is to write the +entry as `(Life<'de>, u64)`, with `<'de>` declared on the table: + +```rust +check_components! { + <'de> App { + ValueDeserializerComponent: (Life<'de>, u64), + } +} +``` + +## The JSON method is missing its error wiring + +**`deserialize_json_string` needs the context's error components**, and a context without them +cannot call it: + +```rust +pub struct Ctx; + +delegate_components! { + Ctx { + open ValueDeserializerComponent; + @ValueDeserializerComponent.u64: UseSerde, + } +} + +let r: Result = Ctx.deserialize_json_string("1"); +``` + +Plain `cargo check` reports only that the method exists for `Ctx` but its trait bounds were not +satisfied. `cargo cgp check` names what is missing: + +```text +error[E0599]: [CGP-E009] the trait `CanDeserializeJsonString<_>` is not implemented for context `Ctx` + = note: root causes: + - [CGP-E107] context `Ctx` does not contain any delegate entry for `@ValueDeserializerComponent` + - [CGP-E107] context `Ctx` does not contain any delegate entry for `ErrorTypeProviderComponent` + - [CGP-E107] context `Ctx` does not contain any delegate entry for `ErrorRaiserComponent` +``` + +The two error entries are the real causes. The first cause appears because the call failed before +the compiler worked out the target type, so the tree asks for an unknown type; it goes away once +the error entries are wired. The fix is the two entries from [wiring a +context](./wiring-a-context.md#4-wire-an-error-type-when-the-json-providers-are-used). + +## A provider depends on itself + +**Wiring a type to a provider that asks the context for the same type makes the lookup circular.** +[`SerializeWithDisplay`](../reference/providers/serialize_with_display.md) formats a value into a +`String` and asks the context to serialize the `String`, so wiring `String` itself to it leads +straight back: + +```rust +delegate_components! { + Ctx { + open ValueSerializerComponent; + @ValueSerializerComponent.String: SerializeWithDisplay, + } +} + +check_components! { + Ctx { + ValueSerializerComponent: String, + } +} +``` + +The check reports that the wiring never resolves: + +```text +error[E0275]: [CGP-E010] the wiring for the consumer trait `CanSerializeValue` on context `Ctx` never resolves — the lookup recurses without terminating +``` + +The help line printed below it suggests a component delegated back to the context itself, as with +`UseContext`, which is the usual cause of this class; here the cycle runs through the provider +instead, and the headline's consumer trait names the type to look at. Without the check, the first +call reports the compiler's raw overflow error instead, `E0275`, +"overflow evaluating the requirement", naming the adapter that was passed to `serde_json`. The fix +is a provider for the in-between type that asks for nothing, such as +[`UseSerde`](../reference/providers/use_serde.md) or +[`SerializeString`](../reference/providers/serialize_string.md) for `String`. + +## The data type is recursive + +**A type that contains itself reports the same error, even with every entry present.** A tree node +whose children are nodes, wired in full: + +```rust +#[derive(CgpData)] +pub struct Node { + pub id: u64, + pub children: Vec, +} + +delegate_components! { + Ctx { + open ValueSerializerComponent; + @ValueSerializerComponent.<'a, T> &'a T: SerializeDeref, + @ValueSerializerComponent.u64: UseSerde, + @ValueSerializerComponent.Vec: SerializeIterator, + @ValueSerializerComponent.Node: SerializeFields, + } +} +``` + +```text +error[E0275]: [CGP-E010] the wiring for the consumer trait `CanSerializeValue` on context `Ctx` never resolves — the lookup recurses without terminating +``` + +Serializing a `Node` requires serializing its `Vec`, which requires `&Node`, which requires +`Node` again, and the compiler treats that cycle as an error. No entry fixes it. The type needs a +provider written for it, one that walks the recursion itself and asks the context only for the +parts that are not recursive; see [writing a provider](./writing-a-provider.md) and [re-entrant +providers](../architecture/reentrant-providers.md#mistakes-are-found-at-compile-time). + +## A key does not parse + +**A key the wiring syntax cannot read fails inside the macro, before any trait is checked.** The +case serialization runs into is a fixed-size array: + +```rust +@ValueDeserializerComponent.[u8; 32]: UseSerde, +``` + +```text +error: expected `,` +``` + +Square brackets are the syntax for a list of keys, so the semicolon is read as a broken list. Key +the array on a type alias instead, as [wiring a +context](./wiring-a-context.md#3-write-keys-for-references-lifetimes-and-arrays) describes. + +## Where to go next + +- [Wiring a context](./wiring-a-context.md): the steps that avoid these mistakes. +- [`cargo cgp check`](/docs/cargo-cgp/check): the tool, and the error classes it recognizes. +- [Checking your wiring](/docs/concepts/check-traits): why CGP checks wiring lazily, and what a + check forces. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/guides/formats.md b/docs/projects/cgp-serde/guides/formats.md new file mode 100644 index 00000000..608cc6a8 --- /dev/null +++ b/docs/projects/cgp-serde/guides/formats.md @@ -0,0 +1,100 @@ +--- +sidebar_label: 'Using a format' +sidebar_position: 3 +description: 'How to use a cgp-serde context with serde_json, RON, and other Serde formats, which formats fit its output, and the entry point a format needs for reading.' +--- + +# Using a format + +A [cgp-serde](../index.md) **context**, the type whose wiring holds an application's choices, works +with any Serde format through the format's ordinary `Serializer` and `Deserializer`, so using one is +a matter of handing the format a value that carries the context. cgp-serde rebuilds Serde's +`Serialize` and `Deserialize` as components of [CGP](/docs/). This guide shows how to write and read +with `serde_json` and another format, and which formats fit the library's output. + +## Write with any format + +**Wrap the context and the value in +[`SerializeWithContext`](../reference/types/serialize_with_context.md), and pass it wherever the +format expects a `Serialize` value.** The adapter implements Serde's own `Serialize`, so no format +needs changes: + +```rust +let compact = serde_json::to_string(&SerializeWithContext::new(&app, &archive))?; +let pretty = serde_json::to_string_pretty(&SerializeWithContext::new(&app, &archive))?; +let ron = ron::to_string(&SerializeWithContext::new(&app, &archive))?; +``` + +Each call returns the format's own error, since the adapter involves none of CGP's error handling. +A context that wants writing JSON to be an operation that returns the context's own error type uses +[`SerializeToJsonString`](../reference/providers/serialize_to_json_string.md) through +`try_compute` instead, as [`basic`](../examples/basic.md) does; it writes compact JSON. + +## Read with `serde_json` + +Reading needs the context too, and `serde_json`'s `from_str` has no place for one, so cgp-serde +offers three ways in. The choice depends on where the input comes from and whether the result +borrows from it: + +- **`deserialize_json_string`**, a method on the context from + [`CanDeserializeJsonString`](../reference/types/can_deserialize_json_string.md). It takes a `&str` + and needs no `TryComputer` entries, only an error type. Annotate the result's type, as in + `let payload: Payload = app.deserialize_json_string(&text)?;`, since the method takes no + turbofish. The result cannot borrow from the string. +- **[`DeserializeFromJsonReader`](../reference/providers/deserialize_from_json_reader.md)**, a + provider wired under `@TryComputerComponent. DeserializeJson` and called with `try_compute`. + It takes any `serde_json` reader: a `StrRead` for a string, a `SliceRead` for bytes, or an + `IoRead` for a stream. A result can borrow from a string or byte input. +- **The seed directly.** Build a `serde_json::Deserializer`, drive a + [`DeserializeWithContext`](../reference/types/deserialize_with_context.md) seed with it, and call + `end` to reject anything after the value. This needs no error wiring at all. + +The first two turn `serde_json`'s errors into the context's error type, so the context wires one; +see [wiring a context](./wiring-a-context.md#4-wire-an-error-type-when-the-json-providers-are-used). + +## Read with another format + +**A format without cgp-serde helpers needs only the few lines the seed takes.** Build the format's +deserializer, drive the seed with it, and check for trailing input if the format supports it. With +RON: + +```rust +let mut deserializer = ron::Deserializer::from_str(&text)?; +let value: Rec = DeserializeWithContext::new(&app).deserialize(&mut deserializer)?; +deserializer.end()?; +``` + +`deserialize` here is Serde's `DeserializeSeed::deserialize`, so `serde::de::DeserializeSeed` must +be in scope. To make reading a format an operation on the context, write a provider on the model of +`DeserializeFromJsonReader`: it takes the format's input, deserializes through the context, and +turns the format's error into the context's error type. + +## Choose a format that fits the output + +**Self-describing formats work with cgp-serde's output as it is.** Two properties of that output +decide which formats fit: + +- **Structs are maps.** The generic struct provider writes a struct as a map from field names to + values, so JSON is unaffected, and RON writes `{"a":1}` rather than its struct syntax. Reading + expects a map in return. +- **Lengths are not declared.** Structs and collections are started without a length, so a format + that must write the length before the elements, such as postcard, rejects them. + +For bytes in a text format, wire a text encoding such as +[`SerializeHex`](../reference/providers/serialize_hex.md) or +[`SerializeBase64`](../reference/providers/serialize_base64.md). A byte string written with Serde's +`serialize_bytes`, which [`SerializeBytes`](../reference/providers/serialize_bytes.md) uses, is an +array of numbers in JSON. + +## Where to go next + +- [The bridge to Serde](../architecture/serde-bridge.md): why the adapters are all a format needs. +- [Wiring a context](./wiring-a-context.md): the error wiring the JSON providers need. +- [Modular error handling](/docs/concepts/modular-error-handling): how a provider raises an error + into the context's error type. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/guides/wiring-a-context.md b/docs/projects/cgp-serde/guides/wiring-a-context.md new file mode 100644 index 00000000..80a31010 --- /dev/null +++ b/docs/projects/cgp-serde/guides/wiring-a-context.md @@ -0,0 +1,227 @@ +--- +sidebar_label: 'Wiring a context' +sidebar_position: 1 +description: 'How to build a cgp-serde context''s wiring table: opening the components, finding every type a traversal reaches, writing keys, and checking the result.' +--- + +# Wiring a context + +A cgp-serde context is a type that stands for an application, and its wiring table names a provider +for every type the application encodes. [cgp-serde](../index.md) rebuilds Serde's `Serialize` and +`Deserialize` as components of [CGP](/docs/). This guide gives the steps for building the table, +the key syntax some types need, and the checks that prove it complete. + +## 1. Open the components and choose per type + +Open each serialization component with the `open` statement, then write one entry per value type. +The statement comes first in the block: + +```rust +pub struct AppA; + +delegate_components! { + AppA { + open {ValueSerializerComponent}; + + @ValueSerializerComponent.<'a, T> &'a T: + SerializeDeref, + + @ValueSerializerComponent.[ + u64, + String, + ]: + UseSerde, + + @ValueSerializerComponent.Vec: + SerializeHex, + + @ValueSerializerComponent.DateTime: + SerializeRfc3339Date, + + @ValueSerializerComponent.[ + Vec, + Vec, + ]: + SerializeIterator, + + @ValueSerializerComponent.[ + MessagesArchive, + MessagesByTopic, + EncryptedMessage, + ]: + SerializeFields, + } +} +``` + +This is the table of `AppA` from the [`messages`](../examples/messages.md) example. Each `@` entry +reads "to serialize this type, use this provider", and a bracketed list gives several types one +provider. [`delegate_components!`](/docs/reference/macros/delegate_components) documents the syntax +in full. + +Open both components when the context reads as well as writes, as in +`open { ValueSerializerComponent, ValueDeserializerComponent };`, and write the reading entries +under `@ValueDeserializerComponent`. A context that runs the JSON providers through `try_compute` +opens `TryComputerComponent` too, as [`basic`](../examples/basic.md) does. + +## 2. Wire every type the traversal reaches + +List the types a traversal touches, not only the types the data names. Start from each top-level +type, and follow what each provider asks the context for, which each provider's +[reference page](../reference/index.md) states: + +- **A struct** wired to [`SerializeFields`](../reference/providers/serialize_fields.md) or + [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) needs an entry + for each field's type. +- **A collection** needs an entry of its own, besides its item type's. Writing one with + [`SerializeIterator`](../reference/providers/serialize_iterator.md) also asks for the item as a + reference, which one generic entry covers: + `@ValueSerializerComponent.<'a, T> &'a T: SerializeDeref`. +- **An encoding** asks for the type it produces. The hex, base64, and RFC 3339 providers ask for + `String`, and [`SerializeTimestamp`](../reference/providers/serialize_timestamp.md) asks for + `i64`, so a context wires those types even when no field has them. +- **A leaf**, a type the application does not want to customize, goes to + [`UseSerde`](../reference/providers/use_serde.md), which uses the type's own Serde impl and asks + for nothing. + +A type the table misses is a compile error rather than a runtime failure, and [debugging the +wiring](./debugging-wiring.md) shows what each kind of omission reports. + +## 3. Write keys for references, lifetimes, and arrays + +Three kinds of type need care in a key: + +- **References and borrowed types** declare their lifetime in the entry: + `@ValueSerializerComponent.<'a, T> &'a T`, `@ValueDeserializerComponent.<'a> &'a str`, or + `@ValueDeserializerComponent.<'b> Vec<&'b Coord>`. Inside a list, each type declares its own, as + in `[Coord, <'b> Payload<'b>]`. A key with a fixed lifetime such as `&'static str` also works, but + matches only that lifetime. +- **A context with a lifetime** declares it on the table, as in `<'a> App<'a> { … }`, and the + entries use lifetime names of their own. +- **A fixed-size array** cannot be written as a key, because square brackets are the syntax for a + list of keys, so `@ValueDeserializerComponent.[u8; 32]` fails to parse. Define a type alias, such + as `type Digest = [u8; 32];`, and key on the alias. + +## 4. Wire an error type when the JSON providers are used + +The JSON providers and the `deserialize_json_string` method turn `serde_json`'s errors into the +context's error type, so a context that uses them wires one. With the `anyhow` backend from the +[`cgp-error-anyhow`](https://docs.rs/cgp-error-anyhow) crate, that is two plain entries: + +```rust +ErrorTypeProviderComponent: + UseAnyhowError, + +ErrorRaiserComponent: + RaiseAnyhowError, +``` + +The components are imported from `cgp::core::error`, and the providers from `cgp_error_anyhow`. +[Modular error handling](/docs/concepts/modular-error-handling) explains the two components. A +context that only serializes through +[`SerializeWithContext`](../reference/types/serialize_with_context.md) needs neither, since the +format's own error comes back. + +## 5. Check every value type + +Assert the wiring with a [`check_components!`](/docs/reference/macros/check_components) table that +lists every type the context encodes. CGP checks wiring when it is used, so without a check a +missing entry surfaces only at the first call, with a longer error. List the reading side with the +component's lifetime, written as [`Life<'de>`](/docs/reference/types/life): + +```rust +check_components! { + #[check_trait(CanUseAppSerializer)] + App { + ValueSerializerComponent: [ + u64, + String, + Vec, + Payload, + ], + } +} + +check_components! { + #[check_trait(CanDeserializeApp)] + <'de> App { + ValueDeserializerComponent: [ + (Life<'de>, u64), + (Life<'de>, String), + (Life<'de>, Vec), + (Life<'de>, Payload), + ] + } +} +``` + +Give each table its own `#[check_trait]` name when one module checks the same context more than +once, since both would otherwise take the same default name. Prefer a separate `check_components!` +to [`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components), which +checks only plain entries and leaves every `@` entry under an `open` statement unchecked. + +## 6. Share entries between contexts with a namespace + +Two applications that make most of the same choices can put the shared entries in a +[namespace](/docs/concepts/namespaces), a reusable wiring table that contexts join, and keep only +their differences in their own tables. This is `AppA` and `AppB` from `messages`, reduced to two of +their structs, with the shared entries moved into a namespace: + +```rust +cgp_namespace! { + new MessagesNamespace { + @ValueSerializerComponent.<'a, T> &'a T: + SerializeDeref, + @ValueSerializerComponent.[i64, u64, String]: + UseSerde, + @ValueSerializerComponent.Vec: + SerializeIterator, + @ValueSerializerComponent.[MessagesByTopic, EncryptedMessage]: + SerializeFields, + } +} + +pub struct AppA; + +delegate_components! { + AppA { + namespace MessagesNamespace; + open ValueSerializerComponent; + + @ValueSerializerComponent.Vec: SerializeHex, + @ValueSerializerComponent.DateTime: SerializeRfc3339Date, + } +} + +pub struct AppB; + +delegate_components! { + AppB { + namespace MessagesNamespace; + open ValueSerializerComponent; + + @ValueSerializerComponent.Vec: SerializeBase64, + @ValueSerializerComponent.DateTime: SerializeTimestamp, + } +} +``` + +Each context still opens the component, and a context's own entries only fill what the namespace +leaves out: a context cannot replace an entry the namespace makes. So put in the namespace only the +choices every joining context shares, and leave each point of difference, here the bytes and the +dates, to the contexts. [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) documents the +syntax. + +## Where to go next + +- [Debugging the wiring](./debugging-wiring.md): what each kind of mistake reports. +- [Re-entrant providers](../architecture/reentrant-providers.md): why the traversal asks for the + types it does. +- [Checking your wiring](/docs/concepts/check-traits): why CGP checks wiring lazily, and what a + check forces. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/guides/writing-a-provider.md b/docs/projects/cgp-serde/guides/writing-a-provider.md new file mode 100644 index 00000000..f95dbb5b --- /dev/null +++ b/docs/projects/cgp-serde/guides/writing-a-provider.md @@ -0,0 +1,160 @@ +--- +sidebar_label: 'Writing a provider' +sidebar_position: 2 +description: 'How to write a new cgp-serde provider: one struct for both directions, nested values handed back to the context, and errors reported through Serde.' +--- + +# Writing a provider + +A new encoding in [cgp-serde](../index.md) is a new provider: a type that implements one or both of +the library's serialization components, which a **context**, the type whose wiring holds an +application's choices, then names in its wiring. cgp-serde rebuilds Serde's `Serialize` and +`Deserialize` as components of [CGP](/docs/). This guide shows a provider pair, then how to +structure one, how to hand nested values back to the context, and how to report errors. + +## Start from an example + +This provider writes a `Duration` as a whole number of milliseconds. It converts to an in-between +type, `u64`, and asks the context to encode that, so how the number is finally written stays the +context's choice: + +```rust +use core::time::Duration; + +use cgp::prelude::*; +use cgp_serde::components::{ + CanDeserializeValue, CanSerializeValue, ValueDeserializer, ValueDeserializerComponent, + ValueSerializer, ValueSerializerComponent, +}; +use serde::ser::Error; + +pub struct SerializeMillis; + +#[cgp_impl(SerializeMillis)] +#[uses(CanSerializeValue)] +impl ValueSerializer { + fn serialize(&self, value: &Duration, serializer: S) -> Result + where + S: serde::Serializer, + { + let millis = u64::try_from(value.as_millis()).map_err(S::Error::custom)?; + self.serialize(&millis, serializer) + } +} + +#[cgp_impl(SerializeMillis)] +#[uses(CanDeserializeValue<'de, u64>)] +impl<'de> ValueDeserializer<'de, Duration> { + fn deserialize(&self, deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let millis = self.deserialize(deserializer)?; + Ok(Duration::from_millis(millis)) + } +} +``` + +Inside each impl, `self` is the context. A context wires the provider like any other, beside an +entry for `u64` in each direction: + +```rust +delegate_components! { + App { + open { ValueSerializerComponent, ValueDeserializerComponent }; + @ValueSerializerComponent.u64: UseSerde, + @ValueSerializerComponent.Duration: SerializeMillis, + @ValueDeserializerComponent.u64: UseSerde, + @ValueDeserializerComponent.Duration: SerializeMillis, + } +} +``` + +A `Duration` of 1,500 milliseconds is then written to JSON as `1500` and read back unchanged. + +## Structure the provider + +**Implement both directions on one struct when they are one decision.** Declare the struct once, +then write each direction as its own [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) naming it, as +above. A context names the same provider in both tables, and the two impls sit together, so they are +written to agree. Use `#[cgp_impl(new Name)]` only for a provider with one direction, since `new` +declares the struct, and a second `new` would declare it twice. + +**Follow the library's naming.** Name a provider that implements both directions, or only writing, +`Serialize…`, and one that implements only reading `Deserialize…`; see [component +design](../architecture/component-design.md#one-provider-can-serve-both-directions). + +**Write the impl in the consumer-trait shape**, `impl ValueSerializer` with `self` as +the context, as the library's own providers do. `#[cgp_impl]` fills in the context parameter. + +## Hand nested values back to the context + +**Encode anything that is not a leaf through the context.** A provider that writes a nested value +itself, by calling Serde's impl or writing the bytes directly, fixes that value's encoding for every +application that uses the provider. Asking the context keeps it a choice, which is the property the +whole library rests on; see [re-entrant providers](../architecture/reentrant-providers.md). There +are two ways, and the choice depends on who makes the nested call: + +- **Converting to another type.** Call `self.serialize(&converted, serializer)` or + `self.deserialize(deserializer)` yourself, and declare what you need with + [`#[uses]`](/docs/reference/attributes/uses), as `SerializeMillis` does for `u64`. +- **Passing items to one of Serde's compound writers or readers.** Wrap each item in + [`SerializeWithContext`](../reference/types/serialize_with_context.md) for `serialize_element` or + `serialize_entry`, or pass a + [`DeserializeWithContext`](../reference/types/deserialize_with_context.md) seed to + `next_element_seed` or `next_value_seed`. + +When the nested type depends on the lifetime of a borrow, as an iterator's items do, write the +requirement as a higher-ranked bound in the `where` clause, `Self: for<'a> CanSerializeValue<…>`, +since `#[uses]` does not express one. + +**Never ask the context for the type you are handling.** A provider for `String` that asks the +context to serialize a `String` depends on itself, and the context fails to compile. When a provider +needs another provider for the same type, take it as a type parameter, as +[`DeserializeDefault`](../reference/providers/deserialize_default.md) does, and bind it with +[`#[use_provider]`](/docs/reference/attributes/use_provider). + +## Report errors through Serde + +**Report a failure with the format's own error**, not with CGP's error components. Map it with +`S::Error::custom` or `D::Error::custom`, from `serde::ser::Error` and `serde::de::Error`, using any +error that implements `Display`, as `SerializeMillis` does for a duration too long for a `u64`. The +format adds its position to the message, and the error reaches the caller the way a failure inside +Serde's own impls does. CGP's [error handling](/docs/concepts/modular-error-handling) belongs at the +edge, where the JSON providers turn the finished `serde_json::Error` into the context's error type; +see [the bridge to Serde](../architecture/serde-bridge.md#where-errors-are-reported). + +## Make it work with every input a format sends + +A few habits keep a provider working across formats and inputs: + +- **Ask the context for owned in-between types.** Ask for a `String` rather than a `&'de str` unless + the result must borrow from the input. A format can lend a string only when it is stored in the + input as is, so a JSON string with an escape in it, or any input read from a stream, has no + `&'de str` to lend. +- **Accept owned data in a visitor.** A Serde visitor that implements `visit_borrowed_bytes` should + also implement `visit_bytes` and `visit_byte_buf`, and likewise for strings, so that input the + format had to copy is accepted. +- **Declare lengths when they are known.** Pass `Some(len)` to `serialize_seq` or `serialize_map` + when the value knows its length, so length-prefixed binary formats can write it. +- **Make the two directions agree.** Check that what the serializing half writes is what the + deserializing half reads, in each format you target. + +## Test the provider + +Wire the provider on a test context, assert the wiring with +[`check_components!`](/docs/reference/macros/check_components), listing the reading side with +[`Life<'de>`](/docs/reference/types/life), and round-trip at least one value through a real format. + +## Where to go next + +- [Wiring a context](./wiring-a-context.md): wiring the new provider beside the library's. +- [Re-entrant providers](../architecture/reentrant-providers.md): the two ways a provider hands a + nested value back. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the CGP idea behind `#[uses]`. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/index.md b/docs/projects/cgp-serde/index.md new file mode 100644 index 00000000..8483cb59 --- /dev/null +++ b/docs/projects/cgp-serde/index.md @@ -0,0 +1,165 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'cgp-serde rebuilds Serde''s Serialize and Deserialize as CGP components, so each application chooses how a type is encoded, with no conflicting impls.' +--- + +# cgp-serde + +cgp-serde rebuilds [Serde](https://serde.rs/)'s `Serialize` and `Deserialize` traits as components +of [CGP](/docs/), a language extension for Rust with pluggable trait implementations at +compile-time. With Serde, a type has one encoding for the whole program, chosen by whoever owns the +type. With cgp-serde, the encoding of each type is chosen by the application instead, so two +applications can write the same value differently, and neither needs to own the type or wrap it. + +cgp-serde is a proof of concept. It replaces Serde's per-type implementations and keeps everything +else: Serde's data model, its formats such as `serde_json`, and any `Serialize` impl a type already +has. Its generic providers cover structs with named fields and the standard collections, and +scalars, enums, and every other type are encoded through their own Serde impls. These pages show +what the design makes possible and where it stops. + +## One value, two encodings + +The library's own demonstration encodes one nested archive of messages under two applications, +`AppA` and `AppB`. The data types derive nothing from Serde. Each application is a **context**, a +type that stands for that application and holds its choices, and its wiring table names an +implementation, or **provider**, for each type it encodes. The two tables are the same except for +three lines. `AppA` has these: + +```rust +@ValueSerializerComponent.[u64, String]: UseSerde, +@ValueSerializerComponent.Vec: SerializeHex, +@ValueSerializerComponent.DateTime: SerializeRfc3339Date, +``` + +and `AppB` has these: + +```rust +@ValueSerializerComponent.[i64, u64, String]: UseSerde, +@ValueSerializerComponent.Vec: SerializeBase64, +@ValueSerializerComponent.DateTime: SerializeTimestamp, +``` + +Serialized through `serde_json`, the first message of the archive comes out like this from `AppA`: + +```json +{ + "message_id": 1, + "author_id": 2, + "date": "2025-11-03T14:15:00+00:00", + "encrypted_data": "48656c6c6f2066726f6d20527573744c616221" +} +``` + +and like this from `AppB`: + +```json +{ + "message_id": 1, + "author_id": 2, + "date": 1762179300, + "encrypted_data": "SGVsbG8gZnJvbSBSdXN0TGFiIQ==" +} +``` + +Bytes are hex in one and base64 in the other, and dates are RFC 3339 strings in one and Unix +timestamps in the other, at every level of nesting. In Serde, `Vec` and `DateTime` each +have one `Serialize` impl in the whole program, and a struct's derive fixes how its fields are +written, so producing both documents from the same structs needs a second set of wrapper types. Here +each choice is one wiring line in the application that makes it. The +[`messages`](./examples/messages.md) example walks through the whole program. + +## What the design shows + +cgp-serde exists to show what CGP's per-context wiring does to a trait every Rust developer knows, +and it shows three things. + +**The application chooses the encoding.** The serialized value becomes a parameter of the +component, and the context becomes the type that implements it, so each application makes its own +choice for each value type, including types it does not own. The +[component design](./architecture/component-design.md) page explains the move, and +[Coherence](/docs/concepts/coherence) explains why it lets choices overlap without conflicting. + +**A data type needs no serialization derive.** A struct that derives CGP's general-purpose +[`CgpData`](/docs/reference/derives/derive_cgp_data) is serialized by generic providers that read +its fields, so a crate can define serializable types without depending on `serde` at all. See +[derive-free records](./architecture/derive-free-records.md). + +**A deserializer can draw on its context.** Every provider receives the context, so a deserializer +can take a service from it while it works, such as an arena to allocate borrowed values into. +Serde's traits have no place to pass one. See [context +services](./architecture/context-services.md). + +A user who only wires a context meets little of CGP beyond one wiring table. Writing a provider is +where CGP's traits become the subject, and that is where the learning cost falls. + +## Status and costs + +cgp-serde is a demonstration of the design, and these are the costs a reader evaluating it should +know first: + +- **It is a proof of concept.** The library is lightly tested and not meant for production use. The + [limitations page](./limitations.md) describes the limits of its design. +- **A context names every type it encodes.** The wiring table has an entry for each type a value + contains, including in-between types such as a `Vec` of structs, so it is longer than the data + definitions it serves. A type with no entry is a compile error, not a runtime surprise. +- **Mistakes produce long compile errors.** A missing entry deep inside a nested type fails to + compile, and the compiler's raw message lists every step it took to find it. Checking the context + with `check_components!` and reading the error with [`cargo cgp check`](/docs/cargo-cgp/check) + names the missing entry: `cargo cgp check` leads with the root cause for the classes it + recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The [debugging + guide](./guides/debugging-wiring.md) shows the common mistakes. +- **Its output suits self-describing formats.** JSON and RON work with it as they are. + Length-prefixed binary formats, such as postcard, do not accept the maps and sequences its generic + providers write. See [using a format](./guides/formats.md). +- **It builds on stable Rust.** The repository pins its toolchain, and nothing needs nightly. + +## The examples + +The examples are the repository's tests, walked through as short tutorials in the order they teach: + +- [`basic`](./examples/basic.md) — one struct written to JSON and read back, with its bytes as hex + and its errors in the context's error type. +- [`messages`](./examples/messages.md) — one nested archive encoded two ways by two contexts that + differ in three wiring lines. + +Two more tests deserialize borrowed values into an arena that the context supplies. Their pages are +still being written, and [context services](./architecture/context-services.md) explains the design +they show. + +## The rest of the section + +The [architecture](./architecture/index.md) pages explain the design one idea at a time. The guides +cover [wiring a context](./guides/wiring-a-context.md), [writing a +provider](./guides/writing-a-provider.md), [using a format](./guides/formats.md), and [debugging the +wiring](./guides/debugging-wiring.md). The [reference](./reference/index.md) has a page for each +provider. The [comparison with Serde](./serde-comparison.md) sets out what cgp-serde keeps, adds, +and lacks, and when plain Serde is the better choice, and the [limitations page](./limitations.md) +describes where the design stops. + +## Running it + +Clone the [repository](https://github.com/contextgeneric/cgp-serde) and run the examples from its +root with `cargo test -p cgp-serde-tests`. The repository's toolchain file selects the Rust version, +and no example needs a network or any program outside the build. + +To use cgp-serde from your own crate, depend on its crates from the repository by git: `cgp-serde` +for the components and core providers, and `cgp-serde-extra`, `cgp-serde-json`, `cgp-serde-alloc`, +or `cgp-serde-typed-arena` for the providers your wiring names. The crates published on crates.io +are an earlier release, built on an older version of CGP, and the code on these pages does not +compile against them. + +## Where to go next + +- [`basic`](./examples/basic.md): the first example, and the one to read first. +- [Modularity hierarchy](/docs/concepts/modularity-hierarchy): where cgp-serde's shape sits among + the ways CGP lets code choose an implementation. +- [Hello World](/docs/tutorials/hello): a first CGP program, for a reader new to CGP. +- [Announcing cgp-serde](/blog/cgp-serde-release): the post that announced the library, with its + motivation. Its code predates the current design. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/limitations.md b/docs/projects/cgp-serde/limitations.md new file mode 100644 index 00000000..80cd5093 --- /dev/null +++ b/docs/projects/cgp-serde/limitations.md @@ -0,0 +1,96 @@ +--- +sidebar_label: 'Limitations' +sidebar_position: 10 +description: 'The limits of cgp-serde: a proof of concept, the part of Serde it replaces, the types and formats it covers, and when Serde fits better.' +--- + +# Limitations + +cgp-serde is a proof of concept built to show what CGP's wiring does for serialization, and its +design has limits worth knowing before relying on it. [cgp-serde](./index.md) rebuilds Serde's +`Serialize` and `Deserialize` as components of [CGP](/docs/). This page describes those limits, +and the cases where plain Serde is the better choice. + +## It is a demonstration, not a library to depend on + +cgp-serde is lightly tested and not meant for production use. Its value is as a worked example: the +clearest demonstration on this site of CGP letting different applications choose different +implementations for the same types. Read it to learn the pattern, and expect rough edges if you +build on it. + +## It replaces one layer of Serde, not Serde + +cgp-serde replaces the traits data types implement, `Serialize` and `Deserialize`, and keeps +everything else. Its output is whatever Serde's data model can express, written by an ordinary Serde +format. It cannot make a format do something the format does not do, and a program still depends on +`serde` and on the format crates it uses. See [the bridge to Serde](./architecture/serde-bridge.md). + +## The generic providers cover structs with named fields + +The providers that walk a type generically handle structs with named fields, the standard +collections, references, and types that convert to or from another type. They do not handle enums, +tuple structs, or tuples. Those types, and any other type that already implements Serde's traits, +are encoded through their own Serde impl, with `UseSerde`, and the choices of the **context**, the +type whose wiring holds an application's choices, do not reach inside them. + +A recursive type, such as a tree whose nodes contain nodes, cannot be encoded by the generic +providers at all, because the compiler cannot resolve the cycle in the wiring. It needs a provider +written for it. See [re-entrant providers](./architecture/reentrant-providers.md). + +## Choices are per type, not per field + +A context chooses one provider for each type, and every value of that type follows it, so two fields +of the same type in one struct are encoded the same way. There are no per-field attributes: a field +is written under its Rust name, and cannot be renamed, skipped, flattened, or defaulted when +missing. A field that needs different treatment needs a type of its own. See [derive-free +records](./architecture/derive-free-records.md). + +## The output suits self-describing formats + +The generic providers write structs as maps and start maps and sequences without declaring their +length. Self-describing formats such as JSON and RON accept that. Length-prefixed binary formats, +such as postcard, do not. See [using a format](./guides/formats.md). + +## Every type needs an entry + +A context names a provider for every type it encodes, in each direction, including types that +appear only along the way, such as a `Vec` of structs, the references a collection yields, and the +string an encoding produces. Nothing is found automatically. The table is checked completely at +compile time, but it is longer than the data it serves, and it grows with every type the data +reaches. See [wiring a context](./guides/wiring-a-context.md). + +## Mistakes produce long compile errors + +A missing entry is a compile error, and the compiler's raw message lists every step from the +top-level type down to the entry it could not find. Checking the context with `check_components!` +and reading the error with [`cargo cgp check`](/docs/cargo-cgp/check) gets to the cause faster: +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a +v0.1.0-alpha that does not yet reshape every class. The [debugging +guide](./guides/debugging-wiring.md) shows the common mistakes. + +## When plain Serde is the better choice + +Most programs are better served by Serde's derive: + +- **A program that encodes each type one way** needs no choice per application, and Serde's derive + gives it that encoding with no wiring to write. +- **A type that needs Serde's attributes or enum representations** is better with Serde's derive, + and can still sit inside a cgp-serde value through `UseSerde`. +- **A binary format**, or any format that needs lengths declared, needs Serde's derived impls. + +cgp-serde's design earns its cost where the same types must be encoded differently by different +applications, where a crate should not depend on `serde`, or where deserializing needs something +from its surroundings. The [comparison with Serde](./serde-comparison.md) sets out the trade in +full. + +## Where to go next + +- [How cgp-serde works](./architecture/index.md): the design these limits follow from. +- [Modularity hierarchy](/docs/concepts/modularity-hierarchy): the CGP idea behind cgp-serde, and + when a simpler tier is enough. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/_category_.json b/docs/projects/cgp-serde/reference/_category_.json new file mode 100644 index 00000000..4cdacf32 --- /dev/null +++ b/docs/projects/cgp-serde/reference/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Reference", + "position": 4, + "link": { + "type": "doc", + "id": "projects/cgp-serde/reference/index" + } +} diff --git a/docs/projects/cgp-serde/reference/components/_category_.json b/docs/projects/cgp-serde/reference/components/_category_.json new file mode 100644 index 00000000..7ffec906 --- /dev/null +++ b/docs/projects/cgp-serde/reference/components/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Components", + "position": 3, + "collapsed": true +} diff --git a/docs/projects/cgp-serde/reference/components/can_alloc.md b/docs/projects/cgp-serde/reference/components/can_alloc.md new file mode 100644 index 00000000..5db74ec2 --- /dev/null +++ b/docs/projects/cgp-serde/reference/components/can_alloc.md @@ -0,0 +1,84 @@ +--- +title: 'CanAlloc — the allocation component in cgp-serde' +sidebar_label: 'CanAlloc' +sidebar_position: 1 +description: 'The cgp-serde component that moves a value into storage living for a lifetime and returns a reference, so a deserializer allocates through a wiring choice.' +--- + +# `CanAlloc` + +Move a value into storage that lives for `'a`, and return a reference to it. + +## Overview + +`CanAlloc<'a, T>` separates what a deserializer needs, somewhere to put a value, from how that is +provided. [`DeserializeAndAllocate`](../providers/deserialize_and_allocate.md) asks the context for +it, and a **context**, the type whose wiring holds an application's choices, wires it to an +allocation provider such as [`AllocateWithArena`](../providers/allocate_with_arena.md). So swapping +the allocator is one wiring entry, and no deserializer changes. + +## Definition + +```rust +#[cgp_component(Allocator)] +pub trait CanAlloc<'a, T> { + fn alloc(&self, value: T) -> &'a mut T; +} +``` + +[`#[cgp_component]`](/docs/reference/macros/cgp_component) also generates the provider trait +`Allocator` and the wiring key `AllocatorComponent`. All three live in `cgp_serde_alloc::traits`. + +## Usage + +Wire the component to a provider in the context's table: + +```rust +AllocatorComponent: + AllocateWithArena, +``` + +A provider of your own implements `Allocator` with [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), +as `AllocateWithArena` does. + +## Behavior + +The trait says only that the value lives for `'a`, typically a lifetime parameter of the context, +not where it goes. The returned reference is tied to `'a` rather than to the context, so values +allocated through it can outlive the context. + +## Context dependencies + +None of its own; a context wires `AllocatorComponent` to a provider, which brings its own +requirements. + +## Pairing + +Not applicable. + +## When to use it + +**Reach for `CanAlloc` when a provider needs to allocate values that outlive the call.** Depending +on the component, rather than on an arena, keeps the provider usable with any allocator. + +## Related constructs + +- [`DeserializeAndAllocate`](../providers/deserialize_and_allocate.md), the deserializer that uses + it. +- [`AllocateWithArena`](../providers/allocate_with_arena.md), the library's provider for it. + +## The ideas behind it + +- [Context services](../../architecture/context-services.md): the layered design this component is + the middle of. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): what a component is. + +## Source + +- [`crates/cgp-serde-alloc/src/traits/alloc.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-alloc/src/traits/alloc.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/index.md b/docs/projects/cgp-serde/reference/index.md new file mode 100644 index 00000000..d4f51a5c --- /dev/null +++ b/docs/projects/cgp-serde/reference/index.md @@ -0,0 +1,105 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'Every cgp-serde provider, adapter type, and component, with what each handles, what it asks the context for, and the crate to import it from.' +--- + +# cgp-serde reference + +This reference documents the public items of [cgp-serde](../index.md), one page per item. cgp-serde +rebuilds Serde's `Serialize` and `Deserialize` as components of [CGP](/docs/), so most of its items +are **providers**: implementations a **context**, the type whose wiring holds an application's +choices, names in its wiring table to say how a type is encoded. The tables below list every +provider by what it handles and what it asks the context for, which is what a context must also +wire. + +:::tip + +### New to CGP? + +A provider page assumes the wiring that [`basic`](../examples/basic.md) walks through. For CGP +itself, the [Hello World tutorial](/docs/tutorials/hello) introduces contexts, providers, and +wiring, and the site's [reference](/docs/reference/) documents the CGP constructs these pages link +to. + +::: + +## Serialization providers + +Every provider below implements the serializing component, the deserializing one, or both, and is +imported from its crate's `providers` module, such as `cgp_serde::providers::SerializeFields`. The +last column is what the provider asks the context to encode in turn; see [re-entrant +providers](../architecture/reentrant-providers.md). + +| Provider | Crate | Direction | Handles | Asks the context for | +|---|---|---|---|---| +| [`UseSerde`](./providers/use_serde.md) | `cgp-serde` | both | any type with Serde's traits | nothing | +| [`SerializeString`](./providers/serialize_string.md) | `cgp-serde` | both | writes any `AsRef`; reads `String` | nothing | +| [`SerializeBytes`](./providers/serialize_bytes.md) | `cgp-serde` | both | writes any `AsRef<[u8]>`; reads any `From<&[u8]>` | nothing | +| [`TryDeserializeBytes`](./providers/try_deserialize_bytes.md) | `cgp-serde` | reads | any `TryFrom<&[u8]>` | nothing | +| [`SerializeWithDisplay`](./providers/serialize_with_display.md) | `cgp-serde` | writes | any `Display` type | `String` | +| [`DeserializeWithFromStr`](./providers/deserialize_with_from_str.md) | `cgp-serde` | reads | any `FromStr` type | `&str` | +| [`SerializeFrom`](./providers/serialize_from.md) | `cgp-serde` | both | a type converted with `Into` | the converted type | +| [`TrySerializeFrom`](./providers/try_serialize_from.md) | `cgp-serde` | both | a type converted with `TryInto` | the converted type | +| [`SerializeDeref`](./providers/serialize_deref.md) | `cgp-serde` | writes | a reference or smart pointer | the value it points to | +| [`SerializeIterator`](./providers/serialize_iterator.md) | `cgp-serde` | writes | a collection iterable by reference | each item it yields | +| [`DeserializeExtend`](./providers/deserialize_extend.md) | `cgp-serde` | reads | a collection that can be extended | each item | +| [`SerializeFields`](./providers/serialize_fields.md) | `cgp-serde` | writes | a struct with named fields | each field's type | +| [`DeserializeRecordFields`](./providers/deserialize_record_fields.md) | `cgp-serde` | reads | a struct with named fields | each field's type | +| [`DeserializeDefault`](./providers/deserialize_default.md) | `cgp-serde` | reads | a `Default` type that may be null | nothing; wraps another provider | +| [`SerializeHex`](./providers/serialize_hex.md) | `cgp-serde-extra` | both | bytes, as hex | `String` | +| [`SerializeBase64`](./providers/serialize_base64.md) | `cgp-serde-extra` | both | bytes, as base64 | `String` | +| [`SerializeRfc3339Date`](./providers/serialize_rfc3339_date.md) | `cgp-serde-extra` | both | `DateTime`, as an RFC 3339 string | `String` | +| [`SerializeTimestamp`](./providers/serialize_timestamp.md) | `cgp-serde-extra` | both | `DateTime`, as a Unix timestamp | `i64` | +| [`DeserializeAndAllocate`](./providers/deserialize_and_allocate.md) | `cgp-serde-alloc` | reads | a reference, allocated through the context | the owned value, and an allocator | + +## JSON and allocation providers + +Four more providers implement other components. The JSON providers make writing and reading JSON an +operation the context runs, and the arena provider implements allocation: + +| Provider | Crate | What it does | Asks the context for | +|---|---|---|---| +| [`SerializeToJsonString`](./providers/serialize_to_json_string.md) | `cgp-serde-json` | writes a value as a compact JSON string | the value's serializer, and an error type | +| [`DeserializeFromJsonReader`](./providers/deserialize_from_json_reader.md) | `cgp-serde-json` | reads a value from any `serde_json` reader | the value's deserializer, and an error type | +| [`DeserializeFromJsonString`](./providers/deserialize_from_json_string.md) | `cgp-serde-json` | reads a value from a string | what its inner provider asks for | +| [`AllocateWithArena`](./providers/allocate_with_arena.md) | `cgp-serde-typed-arena` | allocates into an arena held by the context | the arena | + +## Types and components + +- [`SerializeWithContext`](./types/serialize_with_context.md) — pairs a context with a value as a + Serde `Serialize` value, the way into any Serde format. +- [`DeserializeWithContext`](./types/deserialize_with_context.md) — pairs a context with a target + type as a Serde `DeserializeSeed`. +- [`CanDeserializeJsonString`](./types/can_deserialize_json_string.md) — gives a context a + `deserialize_json_string` method. +- [`CanAlloc`](./components/can_alloc.md) — the component a deserializer allocates through. + +The pages for the two serialization components, `CanSerializeValue` and +`CanDeserializeValue<'de, Value>`, and for the arena getter `HasArena`, are still being written. The +[component design](../architecture/component-design.md) page explains the two components, and +[`AllocateWithArena`](./providers/allocate_with_arena.md) shows the arena getter in use. + +## Looking for a name you don't see? + +Some names belong to a construct documented under another name: + +| Name | Where it is documented | +|---|---| +| `ValueSerializer`, `ValueSerializerComponent` | the provider trait and wiring key of `CanSerializeValue`; see [component design](../architecture/component-design.md) | +| `ValueDeserializer`, `ValueDeserializerComponent` | the provider trait and wiring key of `CanDeserializeValue`; see [component design](../architecture/component-design.md) | +| `SerializeJson`, `DeserializeJson` | the marker types that select the JSON operations; see [`SerializeToJsonString`](./providers/serialize_to_json_string.md) and [`DeserializeFromJsonReader`](./providers/deserialize_from_json_reader.md) | +| `Allocator`, `AllocatorComponent` | the provider trait and wiring key of [`CanAlloc`](./components/can_alloc.md) | +| `ArenaGetter`, `ArenaGetterComponent` | the provider trait and wiring key of `HasArena`; see [`AllocateWithArena`](./providers/allocate_with_arena.md) | +| `deserialize_json_string` | the method of [`CanDeserializeJsonString`](./types/can_deserialize_json_string.md) | + +## Where to go next + +- [Wiring a context](../guides/wiring-a-context.md): choosing providers for a context's table. +- [Writing a provider](../guides/writing-a-provider.md): adding a provider of your own. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/_category_.json b/docs/projects/cgp-serde/reference/providers/_category_.json new file mode 100644 index 00000000..118ba272 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Providers", + "position": 1, + "collapsed": true +} diff --git a/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md new file mode 100644 index 00000000..36fa0f3c --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md @@ -0,0 +1,97 @@ +--- +title: 'AllocateWithArena — allocate into an arena held by the context in cgp-serde' +sidebar_label: 'AllocateWithArena' +sidebar_position: 23 +description: 'The cgp-serde provider that implements the allocation component by moving values into a typed_arena::Arena the context supplies through an arena getter.' +--- + +# `AllocateWithArena` + +Allocate a value into the arena the context supplies. + +## Overview + +`AllocateWithArena` implements the allocation component, [`CanAlloc`](../components/can_alloc.md), +over the [`typed-arena`](https://docs.rs/typed-arena) crate. It gets a `typed_arena::Arena` from the +**context**, the type whose wiring holds the application's choices, through the arena getter +`HasArena`, and moves each value into it. Every value in an arena is freed together when the arena +is dropped. + +## Definition + +```rust +#[cgp_impl(new AllocateWithArena)] +#[uses(HasArena<'a, Value>)] +impl<'a, Value: 'a> Allocator<'a, Value> { ... } +``` + +`Allocator` is the provider trait of `CanAlloc`. `HasArena<'a, T>`, from +`cgp_serde_typed_arena::traits`, is a getter component whose method returns the context's +`&'a Arena`, and its wiring key is `ArenaGetterComponent`. + +## Usage + +Import it from `cgp_serde_typed_arena::providers`. Wire it as the context's allocator, and point the +arena getter at the field that holds the arena with +[`UseField`](/docs/reference/providers/use_field). From the repository's arena test: + +```rust +#[derive(HasField)] +pub struct App<'a> { + pub arena: &'a Arena, +} + +delegate_components! { + <'a> App<'a> { + // ... + ArenaGetterComponent: + UseField, + AllocatorComponent: + AllocateWithArena, + // ... + } +} +``` + +A context with arenas for several types opens `ArenaGetterComponent` and keys the getter on the +type, as in `@ArenaGetterComponent.Coord: UseField`. + +## Behavior + +The provider calls `self.arena().alloc(value)`, so the value moves into the arena and lives as long +as the arena does. The context holds the arena by reference, borrowed from its caller, which is what +lets allocated values outlive the context. + +## Context dependencies + +`HasArena<'a, Value>`: an arena getter for each type allocated, wired to the field that holds it. + +## Pairing + +Not applicable; it implements allocation, not serialization. + +## When to use it + +**Reach for `AllocateWithArena` when a context deserializes many borrowed values of one type** and +they can all be freed together. A different allocator implements `Allocator` for itself, and the +deserializer is unchanged. + +## Related constructs + +- [`DeserializeAndAllocate`](./deserialize_and_allocate.md), the deserializer that calls it. + +## The ideas behind it + +- [Context services](../../architecture/context-services.md): the layers that make the allocator a + wiring choice, and the lifetimes involved. + +## Source + +- [`crates/cgp-serde-typed-arena/src/providers/alloc.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-typed-arena/src/providers/alloc.rs) +- [`crates/cgp-serde-typed-arena/src/traits/has_arena.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-typed-arena/src/traits/has_arena.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md new file mode 100644 index 00000000..b71fa556 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md @@ -0,0 +1,86 @@ +--- +title: 'DeserializeAndAllocate — read a reference into an allocator in cgp-serde' +sidebar_label: 'DeserializeAndAllocate' +sidebar_position: 22 +description: 'The cgp-serde provider that reads a borrowed &T by reading an owned T through the context and allocating it through the context''s allocation component.' +--- + +# `DeserializeAndAllocate` + +Read a borrowed `&'a Value` by reading an owned `Value` and allocating it through the context. + +## Overview + +`DeserializeAndAllocate` lets a deserialized value hold references to other deserialized values, +such as a `Vec<&'a Coord>`, without the references pointing into the input. It reads each value as +an owned `Value`, then asks the **context**, the type whose wiring holds the application's choices, +to allocate it with [`CanAlloc`](../components/can_alloc.md), and returns the reference. It knows +nothing about where the value is stored, which is the context's choice. + +## Definition + +```rust +#[cgp_impl(new DeserializeAndAllocate)] +#[uses(CanAlloc<'a, Value>, CanDeserializeValue<'de, Value>)] +impl<'de, 'a, Value> ValueDeserializer<'de, &'a Value> { ... } +``` + +## Usage + +Import it from `cgp_serde_alloc::providers`, and wire it for the reference type, beside an entry for +the owned type and an allocator. From the repository's arena test: + +```rust +AllocatorComponent: + AllocateWithArena, + +@ValueDeserializerComponent.[ + Coord, + <'b> Payload<'b>, +]: + DeserializeRecordFields, + +@ValueDeserializerComponent.<'b> &'b Coord: + DeserializeAndAllocate, +``` + +## Behavior + +The provider reads the owned value through the context, passes it to `alloc`, and returns the +reference the allocator gives back. The reference's lifetime `'a` is separate from the input's +`'de`, so the value outlives the input and borrows from the allocator instead. + +## Context dependencies + +`CanDeserializeValue<'de, Value>` for the owned type, and `CanAlloc<'a, Value>`. Without an +allocator entry, the context fails to compile with a missing `AllocatorComponent` entry, as [the +debugging guide](../../guides/debugging-wiring.md#an-entry-for-a-type-no-field-has) shows. + +## Pairing + +It reads only. A reference is written with [`SerializeDeref`](./serialize_deref.md). + +## When to use it + +**Reach for `DeserializeAndAllocate` when deserialized values should share storage**, such as many +small values in one arena rather than a `Box` each. + +## Related constructs + +- [`AllocateWithArena`](./allocate_with_arena.md), an allocator for it to call. +- [`DeserializeExtend`](./deserialize_extend.md), which reads a collection of the references. + +## The ideas behind it + +- [Context services](../../architecture/context-services.md): a deserializer taking a service from + its context, in layers. + +## Source + +- [`crates/cgp-serde-alloc/src/providers/alloc_deserialize.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-alloc/src/providers/alloc_deserialize.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_default.md b/docs/projects/cgp-serde/reference/providers/deserialize_default.md new file mode 100644 index 00000000..b4c1ed53 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_default.md @@ -0,0 +1,90 @@ +--- +title: 'DeserializeDefault — read a null value as the default in cgp-serde' +sidebar_label: 'DeserializeDefault' +sidebar_position: 14 +description: 'The cgp-serde higher-order provider that reads a null input as the type''s Default and passes any other input to an inner provider named in the wiring.' +--- + +# `DeserializeDefault` + +Read a null input as the type's `Default`, and pass any other input to an inner provider. + +## Overview + +`DeserializeDefault` makes a value optional in the input without making it an `Option`. It +is a [higher-order provider](/docs/concepts/higher-order-providers): it takes another provider as a +type parameter and calls it directly, for the same type, whenever the input is not null, instead of +asking the **context**, the type whose wiring holds an application's choices, which provider to use. + +## Definition + +```rust +#[cgp_impl(new DeserializeDefault)] +#[use_provider(Provider: ValueDeserializer<'a, Value>)] +impl<'a, Value, Provider> ValueDeserializer<'a, Value> +where + Value: Default, +{ ... } +``` + +[`#[use_provider]`](/docs/reference/attributes/use_provider) states that the inner `Provider` must +read `Value` for the same context. + +## Usage + +Import it from `cgp_serde::providers`, and name the inner provider in the wiring: + +```rust +@ValueDeserializerComponent.u64: DeserializeDefault, +``` + +## Behavior + +The provider asks the format for an optional value. A null input produces `Value::default()`, so the +entry above reads `null` as `0`, and any other input goes to the inner provider, so `7` reads as +`7`. + +The inner provider is named in the wiring rather than looked up through the context, because asking +the context to read the same `Value` would lead back to `DeserializeDefault` itself. The parameter +has no default, so the inner provider is always named. + +The provider handles a null value, not an absent one. A struct field wired to it still has to appear +in the input for [`DeserializeRecordFields`](./deserialize_record_fields.md), which reports a +missing field before any field's provider runs. + +## Context dependencies + +None through the context. The inner provider must read `Value` for the same context, and brings its +own requirements. + +## Pairing + +It reads only. A default value is written like any other. + +## When to use it + +**Reach for `DeserializeDefault` when the input may carry `null` for a value that has a sensible +default.** It does not cover a field missing from the input altogether, since +`DeserializeRecordFields` requires every field of a struct to be present, including a field whose +type is an `Option`. + +## Related constructs + +- [`UseSerde`](./use_serde.md) is the usual inner provider. + +## The ideas behind it + +- [Higher-order providers](/docs/concepts/higher-order-providers): a provider parameterized by + another provider. +- [Writing a provider](../../guides/writing-a-provider.md#hand-nested-values-back-to-the-context): + why a provider for a type never asks the context for that same type. + +## Source + +- [`crates/cgp-serde/src/providers/default.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/default.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_extend.md b/docs/projects/cgp-serde/reference/providers/deserialize_extend.md new file mode 100644 index 00000000..230e9a73 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_extend.md @@ -0,0 +1,86 @@ +--- +title: 'DeserializeExtend — read a sequence into a collection in cgp-serde' +sidebar_label: 'DeserializeExtend' +sidebar_position: 11 +description: 'The cgp-serde provider that reads a Serde sequence into any collection with a default that can be extended, asking the context to read each item.' +--- + +# `DeserializeExtend` + +Read a sequence into any collection that starts empty and can be extended item by item. + +## Overview + +`DeserializeExtend` reads a Serde sequence into a `Vec`, a set, or any collection that implements +`Default` and `Extend`, and asks the **context**, the type whose wiring holds the application's +choices, to read each item. So the items follow the context's choices, including items that borrow +from an arena through [`DeserializeAndAllocate`](./deserialize_and_allocate.md). + +## Definition + +```rust +pub struct DeserializeExtend; + +#[cgp_impl(DeserializeExtend)] +#[uses(CanDeserializeValue<'de, Item>)] +impl<'de, Value, Item> ValueDeserializer<'de, Value> +where + Value: Default + IntoIterator + Extend, +{ ... } +``` + +The `IntoIterator` bound only names the collection's item type; the provider never iterates. + +## Usage + +Import it from `cgp_serde::providers`, and wire each collection type the context reads, beside its +item type. The repository's arena test reads a vector of references into an arena: + +```rust +@ValueDeserializerComponent.<'b> Vec<&'b Coord>: + DeserializeExtend, +``` + +## Behavior + +The provider asks the format for a sequence, starts from `Value::default()`, and adds each item as +it is read, through the context. Any collection meeting the bounds works: a `BTreeSet` reads +`[3,1,3]` as `{1, 3}`, because the set's own `Extend` drops the repeat. Input that is not a sequence +is the format's type error; with JSON, an object fails with `invalid type: map, expected sequence`. + +A map's items are key-value pairs, so a map is read from a sequence of pairs, the shape +[`SerializeIterator`](./serialize_iterator.md) writes, rather than from a JSON object. + +## Context dependencies + +`CanDeserializeValue<'de, Item>` for the collection's item type. + +## Pairing + +[`SerializeIterator`](./serialize_iterator.md) writes the sequence it reads. + +## When to use it + +**Reach for `DeserializeExtend` for any collection whose items should be read through the +context.** For a collection of plain types, [`UseSerde`](./use_serde.md) reads it without an entry +per item type. + +## Related constructs + +- [`DeserializeRecordFields`](./deserialize_record_fields.md) is the matching provider for a + struct. + +## The ideas behind it + +- [Re-entrant providers](../../architecture/reentrant-providers.md): how each item is read through + the context. + +## Source + +- [`crates/cgp-serde/src/providers/extend.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/extend.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md new file mode 100644 index 00000000..7aadbc53 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md @@ -0,0 +1,115 @@ +--- +title: 'DeserializeFromJsonReader — read JSON from any serde_json reader in cgp-serde' +sidebar_label: 'DeserializeFromJsonReader' +sidebar_position: 20 +description: 'The cgp-serde provider that reads a value from a string, bytes, or a stream through serde_json and the context''s wiring, rejecting trailing input.' +--- + +# `DeserializeFromJsonReader` + +Read a value from any `serde_json` reader through the context, and reject anything after it. + +## Overview + +`DeserializeFromJsonReader` makes reading JSON an operation the **context**, the type whose wiring +holds an application's choices, runs through CGP's +[`TryComputer`](/docs/reference/components/handler/try_computer). It reads from any of +`serde_json`'s input sources: a string, a byte slice, or a stream. It is keyed on the marker type +`DeserializeJson`, from `cgp_serde_json::code`, which names the type to read. + +## Definition + +```rust +#[cgp_impl(new DeserializeFromJsonReader)] +#[use_type(HasErrorType.Error)] +#[uses(CanDeserializeValue<'de, Value>, CanRaiseError)] +impl TryComputer, R> +where + R: Read<'de>, +{ + type Output = Value; + + fn try_compute( + &self, + _code: PhantomData>, + source: R, + ) -> Result { ... } +} +``` + +`Read` is `serde_json::de::Read`, implemented by `serde_json`'s `StrRead`, `SliceRead`, and +`IoRead`. The marker types are defined as: + +```rust +pub struct DeserializeJson(pub PhantomData); +pub struct SerializeJson; +``` + +## Usage + +Import it from `cgp_serde_json::providers`, and wire it under `TryComputerComponent` for every +target type with one generic entry: + +```rust +@TryComputerComponent. DeserializeJson: + DeserializeFromJsonReader, +``` + +A caller passes a reader: + +```rust +let payload: Payload = app + .try_compute(PhantomData::>, StrRead::new(&text))?; +``` + +## Behavior + +The provider builds a `serde_json::Deserializer` over the reader, reads the value through the +context, and then checks that nothing follows it, so `"a" x` fails with +`trailing characters at line 1 column 5`. Every `serde_json` error is turned into the context's +error type with `raise_error`. + +The reader's lifetime flows through to the value's deserializer, so a reader over a string or a byte +slice can produce a value that borrows from the input, such as a `&str`. A stream cannot lend its +input, so a value that borrows from it cannot be read from a stream, as with plain `serde_json`. + +## Context dependencies + +`CanDeserializeValue<'de, Value>` for the target type, and an error type that can be raised from a +`serde_json::Error`: `HasErrorType` and `CanRaiseError`. + +## Pairing + +[`SerializeToJsonString`](./serialize_to_json_string.md) writes JSON. + +## When to use it + +**Reach for `DeserializeFromJsonReader` to read JSON from bytes or a stream, or to produce a value +that borrows from its input.** For a string, +[`DeserializeFromJsonString`](./deserialize_from_json_string.md) takes the string directly and wraps +it in a reader itself. + +## Related constructs + +- [`DeserializeWithContext`](../types/deserialize_with_context.md), the seed the provider drives. +- [`CanDeserializeJsonString`](../types/can_deserialize_json_string.md), a method for reading a + string with no `TryComputer` entry. + +## The ideas behind it + +- [The bridge to + Serde](../../architecture/serde-bridge.md#going-out-handing-a-context-to-a-serde-api): why reading + needs a seed and a format's own deserializer. +- [Modular error handling](/docs/concepts/modular-error-handling): raising into the context's error + type. + +## Source + +- [`crates/cgp-serde-json/src/providers/from_reader.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-json/src/providers/from_reader.rs) +- [`crates/cgp-serde-json/src/code/`](https://github.com/contextgeneric/cgp-serde/tree/main/crates/cgp-serde-json/src/code) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md new file mode 100644 index 00000000..b7f1135c --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md @@ -0,0 +1,101 @@ +--- +title: 'DeserializeFromJsonString — read JSON from a string in cgp-serde' +sidebar_label: 'DeserializeFromJsonString' +sidebar_position: 21 +description: 'The cgp-serde provider that reads a value from any string-like input by wrapping it in a serde_json reader and handing it to an inner provider.' +--- + +# `DeserializeFromJsonString` + +Read a value from a string by wrapping it in a `serde_json` reader and handing it to an inner +provider. + +## Overview + +`DeserializeFromJsonString` saves a caller from building a reader. It is wired in the table of a +**context**, the type whose wiring holds an application's choices, and accepts a `String`, a `&str`, +or any `AsRef`, wraps it in `serde_json`'s string reader, and passes it to an inner provider, +[`DeserializeFromJsonReader`](./deserialize_from_json_reader.md) unless another is named. It is a +small [higher-order provider](/docs/concepts/higher-order-providers), parameterized by the provider +it delegates to. + +## Definition + +```rust +pub struct DeserializeFromJsonString( + pub PhantomData, +); + +#[cgp_impl(DeserializeFromJsonString)] +#[use_type(HasErrorType.Error)] +impl TryComputer +where + InDeserializer: for<'a> TryComputer, Output = Value>, + S: AsRef, +{ + type Output = Value; + + fn try_compute(&self, code: PhantomData, source: S) -> Result { ... } +} +``` + +## Usage + +Import it from `cgp_serde_json::providers`, and wire it under `TryComputerComponent` for every +target type. From the [`basic`](../../examples/basic.md) example: + +```rust +@TryComputerComponent. DeserializeJson: + DeserializeFromJsonString, +``` + +A caller passes the string, here a `&String`: + +```rust +let deserialized: Payload = context + .try_compute(PhantomData::>, &serialized) + .unwrap(); +``` + +## Behavior + +The provider wraps the string in a `StrRead` and calls the inner provider with it, which reads the +value and checks for trailing input. Because it must work for a reader of any lifetime, the value it +produces cannot borrow from the input string. A value that borrows from elsewhere is unaffected: the +repository's arena test reads a `Payload<'a>` that borrows from the context's arena through this +provider. + +## Context dependencies + +Whatever the inner provider requires. For the default, that is a deserializer for the target type +for every lifetime, and an error type that can be raised from a `serde_json::Error`. + +## Pairing + +[`SerializeToJsonString`](./serialize_to_json_string.md) writes JSON. + +## When to use it + +**Reach for `DeserializeFromJsonString` to read an owned value from a string.** For a value that +borrows from its input, wire [`DeserializeFromJsonReader`](./deserialize_from_json_reader.md) and +pass it a string reader directly. + +## Related constructs + +- [`CanDeserializeJsonString`](../types/can_deserialize_json_string.md), a method that calls this + provider without a `TryComputer` entry. + +## The ideas behind it + +- [Higher-order providers](/docs/concepts/higher-order-providers): a provider that delegates to + another named in its type. + +## Source + +- [`crates/cgp-serde-json/src/providers/from_str.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-json/src/providers/from_str.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md new file mode 100644 index 00000000..3317b138 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md @@ -0,0 +1,116 @@ +--- +title: 'DeserializeRecordFields — read a struct with no serialization derive in cgp-serde' +sidebar_label: 'DeserializeRecordFields' +sidebar_position: 13 +description: 'The cgp-serde provider that reads a struct deriving CGP''s field traits from a map, reading each field through the context.' +--- + +# `DeserializeRecordFields` + +Read a struct from a map, reading each field through the context and building the struct field by +field. + +## Overview + +`DeserializeRecordFields` is the reading half of [`SerializeFields`](./serialize_fields.md). It +reads a map, asks the **context**, the type whose wiring holds the application's choices, to read +each field's value, and collects the values in CGP's builder for the struct until every field is +present. The struct derives only CGP's field traits, through +[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) or the narrower +[`HasFields`](/docs/reference/traits/shape/has_fields) and +[`BuildField`](/docs/reference/traits/builder/build_field) derives. + +## Definition + +```rust +pub struct DeserializeRecordFields; + +#[cgp_impl(DeserializeRecordFields)] +impl<'de, Record, Builder> ValueDeserializer<'de, Record> +where + Record: HasOptionalBuilder + HasFields, + Record::Fields: HandleMapEntry<'de, Self, Builder>, + Builder: FinalizeOptional, +{ ... } +``` + +[`HasOptionalBuilder`](/docs/reference/traits/optional/has_optional_builder) gives a builder that +holds each field as an `Option`, so fields can arrive in any order, and +[`FinalizeOptional`](/docs/reference/traits/optional/finalize_optional) turns it into the struct +once every field is set. `HandleMapEntry` is a private trait that matches a key against the field +list, and it requires, for each field, that the context can read the field's type. + +## Usage + +Import it from `cgp_serde::providers`, and wire it beside an entry for each field's type. From the +[`basic`](../../examples/basic.md) example: + +```rust +@ValueDeserializerComponent.[ + u64, + String, +]: + UseSerde, + +@ValueDeserializerComponent.Payload: + DeserializeRecordFields, + +@ValueDeserializerComponent.Vec: SerializeHex, +``` + +## Behavior + +The provider asks the format for a map and reads it entry by entry. It compares each key with the +field names, and on a match reads the value through the context and stores it in the builder. A key +that matches no field is skipped, with its value. When the map ends, the builder is finished, which +succeeds only if every field was set. The order of the keys does not matter. + +The provider reports three failures, each through Serde's `Error::custom`, so the format adds its +position to the message: + +- **A field is missing**, after the whole map is read. With JSON, `{"a":1}` read as a struct with + fields `a` and `b` fails with `missing field: b at line 1 column 7`. A field whose type is an + `Option` is no exception: it may be `null`, but it must be present. +- **A field appears twice**, at the second occurrence: `{"a":1,"a":2,"b":3}` fails with + `duplicate field: a at line 1 column 12`. +- **The input is not a map**, as the format's type error; with JSON, an array fails with + `invalid type: sequence, expected map`. + +Only structs with named fields work, since a field's name is its key. A struct with a lifetime works +the same way: the arena test's `Payload<'a>` is read with this provider, its `Vec<&'a Coord>` field +through [`DeserializeExtend`](./deserialize_extend.md). + +## Context dependencies + +`CanDeserializeValue<'de, F>` for the type `F` of every field. + +## Pairing + +[`SerializeFields`](./serialize_fields.md) writes the map it reads. + +## When to use it + +**Reach for `DeserializeRecordFields` to read a struct whose fields should follow the context's +choices.** Every field is required: a field wired to +[`DeserializeDefault`](./deserialize_default.md) still has to appear in the input, since that +provider replaces a null value, not a missing one. + +## Related constructs + +- [`DeserializeExtend`](./deserialize_extend.md) is the matching provider for a collection. + +## The ideas behind it + +- [Derive-free records](../../architecture/derive-free-records.md): reading a struct through CGP's + field traits. +- [Extensible records](/docs/concepts/extensible-records): the builder the provider fills in. + +## Source + +- [`crates/cgp-serde/src/providers/record.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/record.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_with_from_str.md b/docs/projects/cgp-serde/reference/providers/deserialize_with_from_str.md new file mode 100644 index 00000000..5521856d --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_with_from_str.md @@ -0,0 +1,86 @@ +--- +title: 'DeserializeWithFromStr — read a value by parsing a string in cgp-serde' +sidebar_label: 'DeserializeWithFromStr' +sidebar_position: 6 +description: 'The cgp-serde provider that reads a string borrowed from the input through the context and parses it with FromStr.' +--- + +# `DeserializeWithFromStr` + +Read any `FromStr` value by parsing a string. + +## Overview + +`DeserializeWithFromStr` is the reading half of an encoding through text. It asks the **context**, +the type whose wiring holds the application's choices, to read a `&str` borrowed from the input, +then parses it with `FromStr`. It reads back what +[`SerializeWithDisplay`](./serialize_with_display.md) writes, for a type whose `Display` and +`FromStr` agree. + +## Definition + +```rust +#[cgp_impl(new DeserializeWithFromStr)] +#[uses(CanDeserializeValue<'a, &'a str>)] +impl<'a, Value> ValueDeserializer<'a, Value> +where + Value: FromStr, +{ ... } +``` + +## Usage + +Import it from `cgp_serde::providers`, and wire the borrowed string it asks for, usually to +[`UseSerde`](./use_serde.md): + +```rust +@ValueDeserializerComponent.Celsius: DeserializeWithFromStr, +@ValueDeserializerComponent.<'a> &'a str: UseSerde, +``` + +## Behavior + +The provider reads a `&str` through the context and parses it, reporting the parse error's +`Display` message through Serde's `Error::custom`. With `&'a str` wired to `UseSerde`, a `u64` wired +to this provider reads from the JSON string `"42"`, and `"x"` fails with +`invalid digit found in string`. + +Because it asks for a string borrowed from the input, it reads only strings the input can lend. A +JSON string that `serde_json` has to rebuild in a new buffer, such as one containing an escaped +quote or newline, cannot be lent, and fails with `expected a borrowed string` before any parsing. +Neither can input read from a stream, where every string fails the same way. + +## Context dependencies + +`CanDeserializeValue<'de, &'de str>`, usually met by wiring `<'a> &'a str` to `UseSerde`. + +## Pairing + +[`SerializeWithDisplay`](./serialize_with_display.md) writes the string it reads. + +## When to use it + +**Reach for `DeserializeWithFromStr` for text-encoded values read from a string or a byte slice**, +where the strings are plain, such as numbers, identifiers, and codes. For input read from a stream, +or strings that may contain escapes, write a provider that asks the context for an owned `String` +and parses that; [writing a provider](../../guides/writing-a-provider.md) shows the shape. + +## Related constructs + +- [`TrySerializeFrom`](./try_serialize_from.md) reads through any type that converts into the + value. + +## The ideas behind it + +- [Re-entrant providers](../../architecture/reentrant-providers.md#re-entering-directly): a provider + that reads another type through the context and converts it. + +## Source + +- [`crates/cgp-serde/src/providers/display.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/display.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_base64.md b/docs/projects/cgp-serde/reference/providers/serialize_base64.md new file mode 100644 index 00000000..586f4c54 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_base64.md @@ -0,0 +1,86 @@ +--- +title: 'SerializeBase64 — encode bytes as base64 in cgp-serde' +sidebar_label: 'SerializeBase64' +sidebar_position: 16 +description: 'The cgp-serde provider that writes bytes as a standard padded base64 string and reads one back into a Vec.' +--- + +# `SerializeBase64` + +Write bytes as a standard, padded base64 string, and read one back into a `Vec`. + +## Overview + +`SerializeBase64` is the compact text encoding of bytes in `cgp-serde-extra`. It converts bytes to a +base64 `String` and asks the **context**, the type whose wiring holds the application's choices, to +write that string, and it reads a string through the context and decodes it. One struct implements +both directions. + +## Definition + +```rust +pub struct SerializeBase64; + +#[cgp_impl(SerializeBase64)] +#[uses(CanSerializeValue)] +impl ValueSerializer +where + Value: AsRef<[u8]>, +{ ... } + +#[cgp_impl(SerializeBase64)] +#[uses(CanDeserializeValue<'de, String>)] +impl<'de> ValueDeserializer<'de, Vec> { ... } +``` + +Writing accepts any `AsRef<[u8]>`; reading produces a `Vec`. + +## Usage + +Import it from `cgp_serde_extra::providers`. The second application in the +[`messages`](../../examples/messages.md) example writes its bytes with it: + +```rust +@ValueSerializerComponent.Vec: + SerializeBase64, +``` + +## Behavior + +Both directions use the standard base64 alphabet with padding, from the +[`base64`](https://docs.rs/base64) crate. Writing turns `b"hi"` into `"aGk="`, and reading turns +`"aGk="` back into the bytes. Input without its padding, such as `"aGk"`, fails with +`Invalid padding`. + +## Context dependencies + +`CanSerializeValue` and `CanDeserializeValue<'de, String>`. + +## Pairing + +The same provider reads what it writes, for `Vec`. + +## When to use it + +**Reach for `SerializeBase64` for bytes in a text format when size matters more than readability.** +The encoding is the standard padded one; a format that expects URL-safe or unpadded base64 needs a +provider of its own, which [writing a provider](../../guides/writing-a-provider.md) shows how to +write. + +## Related constructs + +- [`SerializeHex`](./serialize_hex.md), the readable encoding of bytes. + +## The ideas behind it + +- [`messages`](../../examples/messages.md): base64 in one application and hex in another. + +## Source + +- [`crates/cgp-serde-extra/src/providers/base64.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-extra/src/providers/base64.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_bytes.md b/docs/projects/cgp-serde/reference/providers/serialize_bytes.md new file mode 100644 index 00000000..3bc12cb7 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_bytes.md @@ -0,0 +1,96 @@ +--- +title: 'SerializeBytes — write bytes with Serde''s byte method in cgp-serde' +sidebar_label: 'SerializeBytes' +sidebar_position: 3 +description: 'The cgp-serde provider that writes any AsRef<[u8]> value with Serde''s byte method and reads bytes the input can lend, for formats with a byte type.' +--- + +# `SerializeBytes` + +Write anything that can be viewed as a byte slice with Serde's byte method, and read bytes the input +can lend. + +## Overview + +`SerializeBytes` is a leaf provider for binary data. It hands the bytes to the format's own byte +method, so the format decides how bytes look, and it reads a value back from a byte slice. It asks +the **context**, the type whose wiring holds an application's choices, for nothing. + +## Definition + +```rust +pub struct SerializeBytes; + +#[cgp_impl(SerializeBytes)] +impl ValueSerializer +where + Value: AsRef<[u8]>, +{ ... } + +#[cgp_impl(SerializeBytes)] +impl<'a, Value> ValueDeserializer<'a, Value> +where + Value: From<&'a [u8]>, +{ ... } +``` + +The struct also implements Serde's `Visitor` for a `&'a [u8]` borrowed from the input, which both +its reading impl and [`TryDeserializeBytes`](./try_deserialize_bytes.md) use. + +## Usage + +Import it from `cgp_serde::providers`, and wire it for a byte type in a format with a byte +representation of its own: + +```rust +@ValueSerializerComponent.Vec: SerializeBytes, +@ValueDeserializerComponent.Vec: SerializeBytes, +``` + +## Behavior + +Writing calls `serialize_bytes`, so the output is the format's byte form. JSON has no byte type, and +`serde_json` writes bytes as an array of numbers, so `vec![1, 2, 3]` becomes `[1,2,3]`. + +Reading asks the format for bytes, and accepts them only when the format can lend them straight +from its input. With `serde_json` reading a string, an unescaped JSON string is lent as its raw +bytes, so `"abc"` reads as `[97, 98, 99]`. A JSON array is not a byte string to `serde_json`, so it +is rejected with `invalid type: sequence, expected bytes`, and so is a string the format had to +copy, such as one with an escape in it. + +## Context dependencies + +None. + +## Pairing + +The same provider implements both directions. [`TryDeserializeBytes`](./try_deserialize_bytes.md) +reads through a fallible conversion instead. + +## When to use it + +**Reach for `SerializeBytes` in a format with a native byte type**, where the format's own byte +encoding is what the application wants. + +For bytes in a text format such as JSON, reach for [`SerializeHex`](./serialize_hex.md) or +[`SerializeBase64`](./serialize_base64.md) instead. They write the bytes as a string, and read that +string back. + +## Related constructs + +- [`SerializeString`](./serialize_string.md) is the leaf provider for text. + +## The ideas behind it + +- [Using a format](../../guides/formats.md#choose-a-format-that-fits-the-output): how the output + meets each format. + +## Source + +- [`crates/cgp-serde/src/providers/bytes.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/bytes.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_deref.md b/docs/projects/cgp-serde/reference/providers/serialize_deref.md new file mode 100644 index 00000000..1fecb954 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_deref.md @@ -0,0 +1,82 @@ +--- +title: 'SerializeDeref — write a reference as the value behind it in cgp-serde' +sidebar_label: 'SerializeDeref' +sidebar_position: 9 +description: 'The cgp-serde provider that writes a reference or smart pointer as the value it points to, and the generic reference entry a collection needs.' +--- + +# `SerializeDeref` + +Write a reference or smart pointer as the value it points to. + +## Overview + +`SerializeDeref` dereferences a value and asks the **context**, the type whose wiring holds the +application's choices, to write the target. Its main use is one generic entry that forwards every +reference to the context's choice for the referenced type, which a context needs whenever it writes +a collection with [`SerializeIterator`](./serialize_iterator.md), since walking a collection by +reference yields references. + +## Definition + +```rust +#[cgp_impl(new SerializeDeref)] +#[uses(CanSerializeValue)] +impl ValueSerializer +where + Value: Deref, +{ ... } +``` + +## Usage + +Import it from `cgp_serde::providers`, and wire it for every reference at once with a generic entry, +as the [`messages`](../../examples/messages.md) example does: + +```rust +@ValueSerializerComponent.<'a, T> &'a T: + SerializeDeref, +``` + +It also works for a smart pointer wired as its own type, such as `Box`. + +## Behavior + +The provider dereferences the value and writes the target through the context, so `&u64` and +`Box` are written exactly as `u64` is. The target must be a sized type, so `&str` and `&[T]` +are not forwarded this way; wire them to a provider for the reference type itself, such as +[`SerializeString`](./serialize_string.md) for `&'a str`. + +## Context dependencies + +`CanSerializeValue`, the type behind the reference. + +## Pairing + +It writes only. Reading into a reference needs somewhere for the value to live, which is what +[`DeserializeAndAllocate`](./deserialize_and_allocate.md) provides. + +## When to use it + +**Reach for the generic `&'a T` entry in any context that writes a collection with +`SerializeIterator`.** Without it, the context has no entry for the items the collection yields. + +## Related constructs + +- [`SerializeFrom`](./serialize_from.md) encodes through a converted value rather than a + dereferenced one. + +## The ideas behind it + +- [Re-entrant providers](../../architecture/reentrant-providers.md#what-the-context-must-wire): why + a collection needs the reference entry. + +## Source + +- [`crates/cgp-serde/src/providers/deref.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/deref.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_fields.md b/docs/projects/cgp-serde/reference/providers/serialize_fields.md new file mode 100644 index 00000000..85ac596e --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_fields.md @@ -0,0 +1,104 @@ +--- +title: 'SerializeFields — write a struct with no serialization derive in cgp-serde' +sidebar_label: 'SerializeFields' +sidebar_position: 12 +description: 'The cgp-serde provider that writes any struct deriving CGP''s field traits as a map from field names to values, asking the context to write each field.' +--- + +# `SerializeFields` + +Write a struct as a map from each field's name to its value, asking the context to write each value. + +## Overview + +`SerializeFields` serializes a struct that derives nothing from Serde. It reads the struct's field +list through CGP's field traits, which +[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) provides, and asks the **context**, +the type whose wiring holds the application's choices, to write each field's value. So one generic +provider serves every struct, and each field is encoded however the context encodes its type. + +## Definition + +```rust +#[cgp_impl(new SerializeFields)] +impl ValueSerializer +where + Value: HasFields, + Value::Fields: FieldsSerializer, +{ ... } +``` + +[`HasFields`](/docs/reference/traits/shape/has_fields) gives the struct's field list as a type. +`FieldsSerializer` is a private trait that walks that list, and it requires, for each field, that +the struct exposes it through [`HasField`](/docs/reference/traits/field-access/has_field) and that +the context can serialize the field's type. + +## Usage + +Import it from `cgp_serde::providers`. Derive the field traits on the struct, and wire it beside an +entry for each field's type, as in the [`basic`](../../examples/basic.md) example: + +```rust +#[derive(Debug, Eq, PartialEq, CgpData)] +pub struct Payload { + pub quantity: u64, + pub message: String, + pub data: Vec, +} + +// in the context's table: +@ValueSerializerComponent.u64: UseSerde, +@ValueSerializerComponent.String: SerializeString, +@ValueSerializerComponent.Vec: SerializeHex, +@ValueSerializerComponent.Payload: SerializeFields, +``` + +That context writes a `Payload` as `{"quantity":42,"message":"hello","data":"010203"}`. + +## Behavior + +The provider starts a map and writes one entry per field, in declaration order. Each key is the +Rust field name exactly as written, and each value is the field wrapped with the context in +[`SerializeWithContext`](../types/serialize_with_context.md). The provider writes a map, with +`serialize_map`, where a derived `Serialize` impl writes a struct, and starts it without a declared +length. JSON shows no difference; see [using a +format](../../guides/formats.md#choose-a-format-that-fits-the-output) for formats that do. + +Only structs with named fields work, since a field's name is its key. + +## Context dependencies + +`CanSerializeValue` for the type `F` of every field: an entry in the context's table for each +field type the struct uses. + +## Pairing + +[`DeserializeRecordFields`](./deserialize_record_fields.md) reads the map back. The two agree on the +shape: a map keyed by Rust field names. + +## When to use it + +**Reach for `SerializeFields` for a struct whose fields should follow the context's choices**, and +for any struct whose crate should not depend on `serde`. For a struct that already derives Serde's +`Serialize` and needs no per-application choice, [`UseSerde`](./use_serde.md) uses that derive. + +## Related constructs + +- [`SerializeIterator`](./serialize_iterator.md) is the matching provider for a collection. + +## The ideas behind it + +- [Derive-free records](../../architecture/derive-free-records.md): serializing a struct through + CGP's field traits. +- [Extensible records](/docs/concepts/extensible-records): the CGP idea of treating a struct's + fields generically. + +## Source + +- [`crates/cgp-serde/src/providers/fields.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_from.md b/docs/projects/cgp-serde/reference/providers/serialize_from.md new file mode 100644 index 00000000..393b49bb --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_from.md @@ -0,0 +1,96 @@ +--- +title: 'SerializeFrom — encode a value through a converted type in cgp-serde' +sidebar_label: 'SerializeFrom' +sidebar_position: 7 +description: 'The cgp-serde provider that encodes a value through another type it converts to or from with Into, asking the context for that type.' +--- + +# `SerializeFrom` + +Encode a value through another type it converts to or from with `Into`. + +## Overview + +`SerializeFrom` lets a type borrow another type's encoding. Writing converts the value into +`Target` and asks the **context**, the type whose wiring holds the application's choices, to write +the `Target`; reading asks the context for the other type and converts from it. So a newtype or a +narrow integer can be encoded exactly as a wider type the context already knows how to write. + +## Definition + +```rust +pub struct SerializeFrom(pub PhantomData); + +#[cgp_impl(SerializeFrom)] +#[uses(CanSerializeValue)] +impl ValueSerializer +where + Value: Clone + Into, +{ ... } + +#[cgp_impl(SerializeFrom)] +#[uses(CanDeserializeValue<'a, Source>)] +impl<'a, Value, Source> ValueDeserializer<'a, Value> +where + Source: Into, +{ ... } +``` + +The type parameter plays opposite roles in the two directions: it is the type the value converts +into when writing, and the type it converts from when reading. + +## Usage + +Import it from `cgp_serde::providers`, and name the in-between type as its parameter: + +```rust +@ValueSerializerComponent.u32: SerializeFrom, +@ValueDeserializerComponent.u32: SerializeFrom, +@ValueSerializerComponent.u64: UseSerde, +@ValueDeserializerComponent.u8: UseSerde, +``` + +Here a `u32` is written as a `u64`, and read as a `u8` that is widened. A context that wires one +type in both directions usually names two different parameters, since `Into` rarely holds both ways. + +## Behavior + +Writing clones the value, converts the clone with `Into`, and writes the result through the context. +The clone is needed because `Into` consumes its input and the provider holds only a reference, so +the value type must implement `Clone`. Reading reads the other type through the context and converts +it with `Into`. + +## Context dependencies + +`CanSerializeValue` when writing, and `CanDeserializeValue<'de, Target>` when reading. + +## Pairing + +The same provider implements both directions. [`TrySerializeFrom`](./try_serialize_from.md) is the +fallible form. + +## When to use it + +**Reach for `SerializeFrom` when a type should be encoded as another type it converts to without +loss**, such as a newtype around a number. For a conversion that can fail, such as narrowing an +integer, reach for [`TrySerializeFrom`](./try_serialize_from.md). + +## Related constructs + +- [`SerializeWithDisplay`](./serialize_with_display.md) encodes through a string. +- [`SerializeDeref`](./serialize_deref.md) encodes through the value a reference points to. + +## The ideas behind it + +- [Re-entrant providers](../../architecture/reentrant-providers.md#re-entering-directly): a provider + that converts and asks the context to encode the result. + +## Source + +- [`crates/cgp-serde/src/providers/from.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/from.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_hex.md b/docs/projects/cgp-serde/reference/providers/serialize_hex.md new file mode 100644 index 00000000..371fb8fc --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_hex.md @@ -0,0 +1,96 @@ +--- +title: 'SerializeHex — encode bytes as hex in cgp-serde' +sidebar_label: 'SerializeHex' +sidebar_position: 15 +description: 'The cgp-serde provider that writes bytes as a lowercase hex string and reads a hex string back, asking the context to write and read the String.' +--- + +# `SerializeHex` + +Write bytes as a lowercase hexadecimal string, and read a hex string back. + +## Overview + +`SerializeHex` is one of the four encodings in `cgp-serde-extra` that an application commonly wants +to choose for itself. It converts bytes to a hex `String` and asks the **context**, the type whose +wiring holds the application's choices, to write that string, and it reads a string through the +context and decodes it. One struct implements both directions, so a context names it in both tables. + +## Definition + +```rust +pub struct SerializeHex; + +#[cgp_impl(SerializeHex)] +#[uses(CanSerializeValue)] +impl ValueSerializer +where + Value: ToHex, +{ ... } + +#[cgp_impl(SerializeHex)] +#[uses(CanDeserializeValue<'de, String>)] +impl<'de, Value> ValueDeserializer<'de, Value> +where + Value: FromHex, +{ ... } +``` + +`ToHex` and `FromHex` are the traits of the [`hex`](https://docs.rs/hex) crate, implemented for byte +containers such as `Vec`, and `FromHex` also for fixed-size byte arrays. + +## Usage + +Import it from `cgp_serde_extra::providers`, and wire it in both directions beside an entry for +`String`, as the [`basic`](../../examples/basic.md) example does: + +```rust +@ValueSerializerComponent.String: SerializeString, +@ValueSerializerComponent.Vec: SerializeHex, + +@ValueDeserializerComponent.[u64, String]: UseSerde, +@ValueDeserializerComponent.Vec: SerializeHex, +``` + +## Behavior + +Writing turns the bytes into lowercase hex and writes the string through the context, so `b"hi"` is +written as `"6869"`. Reading reads a `String` through the context and decodes it, accepting +uppercase digits too, and reports the `hex` crate's message for bad input: `"6G"` fails with +`Invalid character 'G' at position 1`. The two directions read back what they write. + +## Context dependencies + +`CanSerializeValue` and `CanDeserializeValue<'de, String>`, usually wired to +[`UseSerde`](./use_serde.md) or [`SerializeString`](./serialize_string.md). + +## Pairing + +The same provider reads what it writes. + +## When to use it + +**Reach for `SerializeHex` for bytes in a text format when the output should be easy to read**, such +as keys and digests. [`SerializeBase64`](./serialize_base64.md) is the more compact text encoding. + +## Related constructs + +- [`SerializeBase64`](./serialize_base64.md), the other encoding of bytes, which `messages` wires in + the second application. +- [`SerializeBytes`](./serialize_bytes.md), for formats with a native byte type. + +## The ideas behind it + +- [Component design](../../architecture/component-design.md#one-provider-can-serve-both-directions): + one provider for both directions. +- [`messages`](../../examples/messages.md): hex in one application and base64 in another. + +## Source + +- [`crates/cgp-serde-extra/src/providers/hex.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-extra/src/providers/hex.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_iterator.md b/docs/projects/cgp-serde/reference/providers/serialize_iterator.md new file mode 100644 index 00000000..367704b1 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_iterator.md @@ -0,0 +1,94 @@ +--- +title: 'SerializeIterator — write a collection as a sequence in cgp-serde' +sidebar_label: 'SerializeIterator' +sidebar_position: 10 +description: 'The cgp-serde provider that writes any collection iterable by reference as a Serde sequence, asking the context to write each item.' +--- + +# `SerializeIterator` + +Write any collection that can be iterated by reference as a sequence of its items. + +## Overview + +`SerializeIterator` writes a `Vec`, a slice, a set, or any other collection as a Serde sequence, +and asks the **context**, the type whose wiring holds the application's choices, to write each item. +So the items follow the context's choices: a `Vec>` in a context that wires `Vec` to hex +is a list of hex strings. + +## Definition + +```rust +#[cgp_impl(new SerializeIterator)] +impl ValueSerializer +where + for<'a> &'a Value: IntoIterator, + Self: for<'a> CanSerializeValue<<&'a Value as IntoIterator>::Item>, +{ ... } +``` + +Both bounds hold for every lifetime of the borrow, because the item type depends on it. That is why +the requirement on the context is written in the `where` clause rather than with +[`#[uses]`](/docs/reference/attributes/uses). + +## Usage + +Import it from `cgp_serde::providers`, and wire each collection type the context writes, beside the +generic reference entry for its items. From the [`messages`](../../examples/messages.md) example: + +```rust +@ValueSerializerComponent.<'a, T> &'a T: + SerializeDeref, + +@ValueSerializerComponent.[ + Vec, + Vec, +]: + SerializeIterator, +``` + +## Behavior + +The provider starts a sequence, then writes each item that iterating `&Value` yields, wrapped with +the context in [`SerializeWithContext`](../types/serialize_with_context.md). With JSON, a `Vec` +or a `BTreeSet` becomes an array, and a nested vector whose inner type is also wired to +`SerializeIterator` becomes a nested array. The sequence is started without a declared length. + +The items are what iterating by reference yields, which for a `Vec`, a slice, or a set is `&T`. +That is why the context needs an entry for the reference, which the generic `&'a T` entry to +[`SerializeDeref`](./serialize_deref.md) provides. A map yields pairs of references, so a map is +written as a sequence of pairs, each pair written by the context's entry for the tuple type. + +## Context dependencies + +`CanSerializeValue` for each item type `I` the collection yields by reference, for every lifetime +of the borrow: usually the reference entry, and through it an entry for the item type. + +## Pairing + +[`DeserializeExtend`](./deserialize_extend.md) reads a sequence back into a collection. + +## When to use it + +**Reach for `SerializeIterator` for any collection whose items should follow the context's +choices.** For a collection of types the application does not customize, such as a `Vec`, +[`UseSerde`](./use_serde.md) writes the same array without an entry per item type. + +## Related constructs + +- [`SerializeFields`](./serialize_fields.md) is the matching provider for a struct. + +## The ideas behind it + +- [Re-entrant providers](../../architecture/reentrant-providers.md#re-entering-through-an-adapter): + handing each item to Serde with the context attached. + +## Source + +- [`crates/cgp-serde/src/providers/iterator.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/iterator.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md b/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md new file mode 100644 index 00000000..6c0eb1e4 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md @@ -0,0 +1,80 @@ +--- +title: 'SerializeRfc3339Date — encode a date as an RFC 3339 string in cgp-serde' +sidebar_label: 'SerializeRfc3339Date' +sidebar_position: 17 +description: 'The cgp-serde provider that writes a DateTime as an RFC 3339 string and reads one back with any offset.' +--- + +# `SerializeRfc3339Date` + +Write a `DateTime` as an RFC 3339 string, and read one back. + +## Overview + +`SerializeRfc3339Date` is one of the two date encodings in `cgp-serde-extra`. It formats a +[`chrono`](https://docs.rs/chrono) `DateTime` as an RFC 3339 `String` and asks the **context**, +the type whose wiring holds the application's choices, to write it, and it reads a string through +the context and parses it. One struct implements both directions. + +## Definition + +```rust +pub struct SerializeRfc3339Date; + +#[cgp_impl(SerializeRfc3339Date)] +#[uses(CanSerializeValue)] +impl ValueSerializer> { ... } + +#[cgp_impl(SerializeRfc3339Date)] +#[uses(CanDeserializeValue<'de, String>)] +impl<'de> ValueDeserializer<'de, DateTime> { ... } +``` + +## Usage + +Import it from `cgp_serde_extra::providers`. The first application in the +[`messages`](../../examples/messages.md) example writes its dates with it: + +```rust +@ValueSerializerComponent.DateTime: + SerializeRfc3339Date, +``` + +## Behavior + +Writing uses `chrono`'s `to_rfc3339`, with a `+00:00` offset and any sub-second part the value has: +14:15 on 3 November 2025 is written as `"2025-11-03T14:15:00+00:00"`. Reading accepts any RFC 3339 +offset and converts to UTC, so `"2025-11-03T16:15:00+02:00"` reads as 14:15 UTC. Input that is not a +full RFC 3339 timestamp fails with `chrono`'s message; a bare date such as `"2025-11-03"` fails with +`premature end of input`. + +## Context dependencies + +`CanSerializeValue` and `CanDeserializeValue<'de, String>`. + +## Pairing + +The same provider reads what it writes, with any offset normalized to UTC. + +## When to use it + +**Reach for `SerializeRfc3339Date` when dates should be readable and keep their precision.** +[`SerializeTimestamp`](./serialize_timestamp.md) writes the same instant as a number of seconds. + +## Related constructs + +- [`SerializeTimestamp`](./serialize_timestamp.md), the numeric date encoding. + +## The ideas behind it + +- [`messages`](../../examples/messages.md): RFC 3339 in one application and timestamps in another. + +## Source + +- [`crates/cgp-serde-extra/src/providers/date.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-extra/src/providers/date.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_string.md b/docs/projects/cgp-serde/reference/providers/serialize_string.md new file mode 100644 index 00000000..0918d17e --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_string.md @@ -0,0 +1,92 @@ +--- +title: 'SerializeString — write any string-like value in cgp-serde' +sidebar_label: 'SerializeString' +sidebar_position: 2 +description: 'The cgp-serde provider that writes any AsRef value as a Serde string and reads an owned String back, asking the context for nothing.' +--- + +# `SerializeString` + +Write anything that can be viewed as a `str` as a Serde string, and read an owned `String`. + +## Overview + +`SerializeString` is a leaf provider for text. It writes any type that implements `AsRef` with +Serde's string method, so `String`, `&str`, and `Box` all come out as plain strings, and it +reads a `String` back. It asks the **context**, the type whose wiring holds an application's +choices, for nothing, which makes it one of the providers a context's table ends on: the hex, +base64, and RFC 3339 encodings each produce a `String` and ask the context to write it, and +`SerializeString` or [`UseSerde`](./use_serde.md) is what writes it. + +## Definition + +```rust +pub struct SerializeString; + +#[cgp_impl(SerializeString)] +impl ValueSerializer +where + Value: AsRef, +{ ... } + +#[cgp_impl(SerializeString)] +impl<'a> ValueDeserializer<'a, String> { ... } +``` + +The struct also implements Serde's `Visitor`, producing a `String` from a borrowed or an owned +string, which is what its reading impl uses. + +## Usage + +Import it from `cgp_serde::providers`. The [`basic`](../../examples/basic.md) example writes its +strings with it: + +```rust +@ValueSerializerComponent.String: SerializeString, +``` + +A borrowed string is wired as its own type, since `str` cannot be wired alone: +`@ValueSerializerComponent.<'a> &'a str: SerializeString`. + +## Behavior + +Writing calls `serialize_str`, so the format escapes the string as it normally would. Reading +produces only `String`, and accepts both a string the input can lend and one the format had to +copy, so an escaped JSON string such as `"a\nb"` reads as a string containing a newline. Input that +is not a string is the format's type error; with JSON, a number fails with +`invalid type: integer ..., expected string`. + +## Context dependencies + +None. + +## Pairing + +The same provider reads what it writes, for `String`. + +## When to use it + +**Reach for `SerializeString` to write a string-like type that does not implement `Serialize` +itself**, or to write several string-like types the same way. For `String` alone, +[`UseSerde`](./use_serde.md) writes the same output. + +## Related constructs + +- [`SerializeWithDisplay`](./serialize_with_display.md) writes any `Display` type as the string it + formats to. +- [`SerializeBytes`](./serialize_bytes.md) is the leaf provider for bytes. + +## The ideas behind it + +- [Re-entrant providers](../../architecture/reentrant-providers.md): why a table needs a leaf for + the strings its encodings produce. + +## Source + +- [`crates/cgp-serde/src/providers/string.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/string.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md b/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md new file mode 100644 index 00000000..d6a343b6 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md @@ -0,0 +1,91 @@ +--- +title: 'SerializeTimestamp — encode a date as a Unix timestamp in cgp-serde' +sidebar_label: 'SerializeTimestamp' +sidebar_position: 18 +description: 'The cgp-serde provider that writes a DateTime as whole seconds since the Unix epoch and reads one back, asking the context to write and read the i64.' +--- + +# `SerializeTimestamp` + +Write a `DateTime` as a Unix timestamp in whole seconds, and read one back. + +## Overview + +`SerializeTimestamp` is the numeric date encoding in `cgp-serde-extra`. It converts a +[`chrono`](https://docs.rs/chrono) `DateTime` to the number of seconds since the Unix epoch, an +`i64`, and asks the **context**, the type whose wiring holds the application's choices, to write +that number. Because it goes through the context, a context that uses it needs an entry for `i64`, +even when no field in its data is an `i64`. + +## Definition + +```rust +pub struct SerializeTimestamp; + +#[cgp_impl(SerializeTimestamp)] +#[uses(CanSerializeValue)] +impl ValueSerializer> { ... } + +#[cgp_impl(SerializeTimestamp)] +#[uses(CanDeserializeValue<'de, i64>)] +impl<'de> ValueDeserializer<'de, DateTime> { ... } +``` + +## Usage + +Import it from `cgp_serde_extra::providers`, and wire `i64` beside it. The second application in the +[`messages`](../../examples/messages.md) example does both: + +```rust +@ValueSerializerComponent.[ + i64, + u64, + String, +]: + UseSerde, + +@ValueSerializerComponent.DateTime: + SerializeTimestamp, +``` + +## Behavior + +Writing writes the whole seconds since the epoch through the context's entry for `i64`, so 14:15 UTC +on 3 November 2025 is written as `1762179300`. Any part of a second is dropped, so a value with +milliseconds is written as the same number as the whole second before it. Reading reads an `i64` and +builds the instant; a number outside the range `chrono` can represent fails with +`invalid timestamp`. + +## Context dependencies + +`CanSerializeValue` and `CanDeserializeValue<'de, i64>`. Leaving out the `i64` entry is the +mistake the [`messages`](../../examples/messages.md#try-a-change) example demonstrates. + +## Pairing + +The same provider reads what it writes, for instants with no part of a second. + +## When to use it + +**Reach for `SerializeTimestamp` when dates should be compact numbers and whole seconds are precise +enough.** For sub-second precision, or dates a person should read, +[`SerializeRfc3339Date`](./serialize_rfc3339_date.md) keeps both. + +## Related constructs + +- [`SerializeRfc3339Date`](./serialize_rfc3339_date.md), the string date encoding. + +## The ideas behind it + +- [Re-entrant providers](../../architecture/reentrant-providers.md#what-the-context-must-wire): why + a context wires `i64` for it. + +## Source + +- [`crates/cgp-serde-extra/src/providers/timestamp.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-extra/src/providers/timestamp.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md b/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md new file mode 100644 index 00000000..6327add9 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md @@ -0,0 +1,113 @@ +--- +title: 'SerializeToJsonString — write JSON as an operation on the context in cgp-serde' +sidebar_label: 'SerializeToJsonString' +sidebar_position: 19 +description: 'The cgp-serde provider that writes a value as a compact JSON string through the context''s wiring, turning serde_json errors into the context''s error type.' +--- + +# `SerializeToJsonString` + +Write a value as a compact JSON string, as a fallible operation the context runs. + +## Overview + +`SerializeToJsonString` makes writing JSON something a **context**, the type whose wiring holds an +application's choices, can do through CGP's +[`TryComputer`](/docs/reference/components/handler/try_computer), an interface for a fallible +computation chosen by a marker type. It runs `serde_json` over the value with the context attached, +so the JSON follows the context's choices, and it turns a `serde_json::Error` into the context's own +error type. + +## Definition + +```rust +#[cgp_impl(new SerializeToJsonString)] +#[use_type(HasErrorType.Error)] +#[uses(CanSerializeValue, CanRaiseError)] +impl TryComputer { + type Output = String; + + fn try_compute(&self, _code: PhantomData, value: &Value) -> Result { ... } +} +``` + +[`#[use_type]`](/docs/reference/attributes/use_type) brings the context's error type into scope as +`Error`, and [`#[uses]`](/docs/reference/attributes/uses) declares what the provider needs: a +serializer for the value, and a way to raise a `serde_json::Error`. + +## Usage + +Import it from `cgp_serde_json::providers`, and wire it under `TryComputerComponent`, keyed on the +marker `SerializeJson` from `cgp_serde_json::code`. The context also needs an error type. From the +[`basic`](../../examples/basic.md) example: + +```rust +open { + ValueSerializerComponent, + ValueDeserializerComponent, + TryComputerComponent, +}; + +ErrorTypeProviderComponent: + UseAnyhowError, + +ErrorRaiserComponent: + RaiseAnyhowError, + +@TryComputerComponent.SerializeJson: + SerializeToJsonString, +``` + +A caller then runs it with `try_compute`, from `cgp::extra::handler::CanTryCompute`: + +```rust +let serialized = context + .try_compute(PhantomData::, &value) + .unwrap(); +``` + +## Behavior + +The provider calls `serde_json::to_string` on the value wrapped with the context in +[`SerializeWithContext`](../types/serialize_with_context.md), so the output is compact JSON shaped +by the context's wiring. A `serde_json::Error`, including one a provider raised during the +traversal, is turned into the context's error type with `raise_error`. The provider accepts any +marker type, so `SerializeJson` is a convention rather than a requirement. + +## Context dependencies + +`CanSerializeValue` for the value, and an error type that can be raised from a +`serde_json::Error`: `HasErrorType` and `CanRaiseError`. + +## Pairing + +[`DeserializeFromJsonString`](./deserialize_from_json_string.md) and +[`DeserializeFromJsonReader`](./deserialize_from_json_reader.md) read JSON back. + +## When to use it + +**Reach for `SerializeToJsonString` when writing JSON should return the context's own error type**, +or be one of the operations a context's wiring chooses. For pretty-printed output or writing to a +stream, call `serde_json` with a [`SerializeWithContext`](../types/serialize_with_context.md) +directly, which returns `serde_json`'s error; see [using a format](../../guides/formats.md). + +## Related constructs + +- [`SerializeWithContext`](../types/serialize_with_context.md), the adapter the provider passes to + `serde_json`. + +## The ideas behind it + +- [Modular error handling](/docs/concepts/modular-error-handling): how a provider raises into the + context's error type. +- [Handlers](/docs/concepts/handlers): CGP's computation interfaces, including `TryComputer`. + +## Source + +- [`crates/cgp-serde-json/src/providers/to_string.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-json/src/providers/to_string.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_with_display.md b/docs/projects/cgp-serde/reference/providers/serialize_with_display.md new file mode 100644 index 00000000..30f62b9d --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_with_display.md @@ -0,0 +1,81 @@ +--- +title: 'SerializeWithDisplay — write a Display value as a string in cgp-serde' +sidebar_label: 'SerializeWithDisplay' +sidebar_position: 5 +description: 'The cgp-serde provider that writes any Display value as the string it formats to, asking the context to write the String.' +--- + +# `SerializeWithDisplay` + +Write any `Display` value as the string it formats to. + +## Overview + +`SerializeWithDisplay` covers every type whose natural encoding is its printed form, such as an +identifier or a unit of measure, with one provider. It formats the value with `Display`, then asks +the **context**, the type whose wiring holds the application's choices, to write the resulting +`String`, so how strings are written stays the context's choice. + +## Definition + +```rust +#[cgp_impl(new SerializeWithDisplay)] +#[uses(CanSerializeValue)] +impl ValueSerializer +where + Value: Display, +{ ... } +``` + +[`#[uses]`](/docs/reference/attributes/uses) declares the one thing it asks of the context: writing +a `String`. + +## Usage + +Import it from `cgp_serde::providers`, and wire it beside an entry for `String`: + +```rust +@ValueSerializerComponent.Celsius: SerializeWithDisplay, +@ValueSerializerComponent.String: UseSerde, +``` + +## Behavior + +The provider formats the value with `to_string` and writes the result through the context's entry +for `String`. A `Celsius(21.5)` whose `Display` writes `21.5C` is written to JSON as `"21.5C"`. The +formatted string is allocated on every call. + +## Context dependencies + +`CanSerializeValue`. Wiring `String` itself to `SerializeWithDisplay` would make the +provider ask for itself, and the context fails to compile; wire `String` to a leaf such as +[`UseSerde`](./use_serde.md) or [`SerializeString`](./serialize_string.md). + +## Pairing + +[`DeserializeWithFromStr`](./deserialize_with_from_str.md) reads the string back with `FromStr`. + +## When to use it + +**Reach for `SerializeWithDisplay` when a type's printed form is its encoding**, and the type has a +`FromStr` that parses it back. For a type that implements `AsRef`, +[`SerializeString`](./serialize_string.md) writes it without formatting. + +## Related constructs + +- [`SerializeFrom`](./serialize_from.md) encodes through any type the value converts into. + +## The ideas behind it + +- [Re-entrant providers](../../architecture/reentrant-providers.md#re-entering-directly): a provider + that converts a value and asks the context to encode the result. + +## Source + +- [`crates/cgp-serde/src/providers/display.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/display.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md b/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md new file mode 100644 index 00000000..7cb5f365 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md @@ -0,0 +1,81 @@ +--- +title: 'TryDeserializeBytes — read a value from bytes by TryFrom in cgp-serde' +sidebar_label: 'TryDeserializeBytes' +sidebar_position: 4 +description: 'The cgp-serde provider that reads a byte slice and converts it with TryFrom, such as into a fixed-size array.' +--- + +# `TryDeserializeBytes` + +Read a value from a byte slice through a fallible `TryFrom` conversion. + +## Overview + +`TryDeserializeBytes` reads bytes the way [`SerializeBytes`](./serialize_bytes.md) does, then +converts them into the target type with `TryFrom`, reporting a failed conversion as an error. A +fixed-size array is the typical target, since a slice converts to one only when the lengths match. +It asks the **context**, the type whose wiring holds an application's choices, for nothing. + +## Definition + +```rust +#[cgp_impl(new TryDeserializeBytes)] +impl<'a, Value> ValueDeserializer<'a, Value> +where + Value: TryFrom<&'a [u8], Error: Display>, +{ ... } +``` + +## Usage + +Import it from `cgp_serde::providers`. A fixed-size array cannot be written as a key, because square +brackets are the syntax for a list of keys, so key it on a type alias: + +```rust +type Digest = [u8; 32]; + +// in the context's table: +@ValueDeserializerComponent.Digest: TryDeserializeBytes, +``` + +## Behavior + +The provider reads a byte slice the input can lend, as `SerializeBytes` does, and converts it, +reporting the conversion error's `Display` message through Serde's `Error::custom`. A `[u8; 3]` +reads from the JSON string `"abc"`, and from `"ab"` fails with `could not convert slice to array`. + +## Context dependencies + +None. + +## Pairing + +It reads only. A value that is `AsRef<[u8]>` is written with +[`SerializeBytes`](./serialize_bytes.md). + +## When to use it + +**Reach for `TryDeserializeBytes` when the target cannot be built from every byte slice**, such as a +fixed-size array. For a type that converts from any slice, such as `Vec`, `SerializeBytes` reads +it without the conversion. + +## Related constructs + +- [`TrySerializeFrom`](./try_serialize_from.md) is the general fallible conversion, through any + type the context can read. + +## The ideas behind it + +- [Wiring a + context](../../guides/wiring-a-context.md#3-write-keys-for-references-lifetimes-and-arrays): why + an array is keyed on an alias. + +## Source + +- [`crates/cgp-serde/src/providers/bytes.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/bytes.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/try_serialize_from.md b/docs/projects/cgp-serde/reference/providers/try_serialize_from.md new file mode 100644 index 00000000..46b8a23e --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/try_serialize_from.md @@ -0,0 +1,91 @@ +--- +title: 'TrySerializeFrom — encode through a fallible conversion in cgp-serde' +sidebar_label: 'TrySerializeFrom' +sidebar_position: 8 +description: 'The cgp-serde provider that encodes a value through another type with TryInto in either direction, reporting a failed conversion as a Serde error.' +--- + +# `TrySerializeFrom` + +Encode a value through another type, with a conversion that can fail. + +## Overview + +`TrySerializeFrom` is the fallible form of [`SerializeFrom`](./serialize_from.md). It +converts with `TryInto` rather than `Into`, and reports a failed conversion as an error, so it can +encode through a type the value does not always fit, such as a narrower integer. Like +`SerializeFrom`, it asks the **context**, the type whose wiring holds an application's choices, to +encode the other type. + +## Definition + +```rust +pub struct TrySerializeFrom(pub PhantomData); + +#[cgp_impl(TrySerializeFrom)] +#[uses(CanSerializeValue)] +impl ValueSerializer +where + Value: Clone + TryInto, +{ ... } + +#[cgp_impl(TrySerializeFrom)] +#[uses(CanDeserializeValue<'a, Source>)] +impl<'a, Value, Source> ValueDeserializer<'a, Value> +where + Source: TryInto, +{ ... } +``` + +## Usage + +Import it from `cgp_serde::providers`, and name the in-between type as its parameter: + +```rust +@ValueSerializerComponent.u16: TrySerializeFrom, +@ValueDeserializerComponent.i8: TrySerializeFrom, +@ValueSerializerComponent.u8: UseSerde, +@ValueDeserializerComponent.u64: UseSerde, +``` + +## Behavior + +The directions mirror `SerializeFrom`, with the conversion error's `Display` message reported +through the serializer's or deserializer's `Error::custom`. A `u16` written as +`TrySerializeFrom` writes `7` for `7`, and for `300` fails with +`out of range integral type conversion attempted`. An `i8` read as `TrySerializeFrom` reads +`5`, and fails on `500` with the same message. Writing clones the value, so the value type must +implement `Clone`. + +## Context dependencies + +`CanSerializeValue` when writing, and `CanDeserializeValue<'de, Target>` when reading. + +## Pairing + +The same provider implements both directions. + +## When to use it + +**Reach for `TrySerializeFrom` when the conversion can fail**, and a failure should be an error +rather than a panic or a silent truncation. When the conversion always succeeds, +[`SerializeFrom`](./serialize_from.md) does the same without the error path. + +## Related constructs + +- [`TryDeserializeBytes`](./try_deserialize_bytes.md) converts from a byte slice with `TryFrom`. + +## The ideas behind it + +- [Writing a provider](../../guides/writing-a-provider.md#report-errors-through-serde): reporting a + failure through the format's error. + +## Source + +- [`crates/cgp-serde/src/providers/try_from.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/try_from.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/use_serde.md b/docs/projects/cgp-serde/reference/providers/use_serde.md new file mode 100644 index 00000000..deb4c677 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/use_serde.md @@ -0,0 +1,102 @@ +--- +title: 'UseSerde — use a type''s own Serde impl in cgp-serde' +sidebar_label: 'UseSerde' +sidebar_position: 1 +description: 'The cgp-serde provider that serializes or deserializes a value through the type''s own Serde impl, so every existing Serde impl is available to a context.' +--- + +# `UseSerde` + +Serialize or deserialize a value through the value type's own Serde impl. + +## Overview + +`UseSerde` is how a cgp-serde context reuses Serde. Wired for a type, it calls that type's +`Serialize` or `Deserialize` impl, so every impl in the standard library and in other crates is +available to a **context**, the type whose wiring holds an application's choices, without a +provider being written for it. It is the usual choice for the scalar types at the bottom of a +context's table, such as `u64`, `i64`, and `String`, where the application has no reason to choose +an encoding. + +## Definition + +```rust +pub struct UseSerde; + +#[cgp_impl(UseSerde)] +impl ValueSerializer +where + Value: SerdeSerialize, +{ ... } + +#[cgp_impl(UseSerde)] +impl<'a, Value> ValueDeserializer<'a, Value> +where + Value: SerdeDeserialize<'a>, +{ ... } +``` + +`SerdeSerialize` and `SerdeDeserialize` are Serde's `Serialize` and `Deserialize`, imported under +those names. One struct implements both directions. + +## Usage + +Import it from `cgp_serde::providers`, and wire the types that should keep their Serde encoding: + +```rust +@ValueSerializerComponent.[u64, String]: UseSerde, +@ValueDeserializerComponent.[u64, String]: UseSerde, +``` + +## Behavior + +The provider ignores the context and calls the Serde impl directly, so the output is exactly what +plain Serde would produce. That also means the context's choices stop at the value. The type's own +impl serializes whatever the value contains, so a struct deriving Serde's `Serialize` with a +`Vec` field writes that field as Serde does, an array of numbers in JSON, even in a context that +wires `Vec` to hex. + +The deserializing impl passes Serde's `'de` lifetime through, so `UseSerde` can produce a value that +borrows from the input when the Serde impl does. Wired for `<'a> &'a str`, it reads a string +borrowed from the input, when the input can lend one. + +## Context dependencies + +None. `UseSerde` asks the context for nothing. + +## Pairing + +The same provider reads what it writes. + +## When to use it + +**Reach for `UseSerde` for a type whose Serde encoding the application is happy with**, which is +most scalar types, and for any type cgp-serde's generic providers do not cover, such as an enum +with a derived Serde impl. + +Reach for [`SerializeFields`](./serialize_fields.md) and +[`DeserializeRecordFields`](./deserialize_record_fields.md) instead when a struct's fields should +follow the context's choices, since `UseSerde` hands the whole struct to its own impl. + +## Related constructs + +- [`SerializeString`](./serialize_string.md) writes any string-like type as a string, where + `UseSerde` needs the exact type to implement `Serialize`. +- [`SerializeWithContext`](../types/serialize_with_context.md) goes the other way, handing a context + to a Serde API. + +## The ideas behind it + +- [The bridge to Serde](../../architecture/serde-bridge.md#going-in-using-a-types-own-serde-impl): + how values cross between cgp-serde and Serde. +- [`#[cgp_impl]`](/docs/reference/macros/cgp_impl): the macro the provider is written with. + +## Source + +- [`crates/cgp-serde/src/providers/serde.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/serde.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/types/_category_.json b/docs/projects/cgp-serde/reference/types/_category_.json new file mode 100644 index 00000000..9d9147fd --- /dev/null +++ b/docs/projects/cgp-serde/reference/types/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Types", + "position": 2, + "collapsed": true +} diff --git a/docs/projects/cgp-serde/reference/types/can_deserialize_json_string.md b/docs/projects/cgp-serde/reference/types/can_deserialize_json_string.md new file mode 100644 index 00000000..9fb43a81 --- /dev/null +++ b/docs/projects/cgp-serde/reference/types/can_deserialize_json_string.md @@ -0,0 +1,90 @@ +--- +title: 'CanDeserializeJsonString — a deserialize_json_string method in cgp-serde' +sidebar_label: 'CanDeserializeJsonString' +sidebar_position: 3 +description: 'The cgp-serde trait that gives any suitably wired context a deserialize_json_string method, reading a value from a JSON string with no TryComputer entries.' +--- + +# `CanDeserializeJsonString` + +Give a context a `deserialize_json_string` method that reads a value from a JSON string. + +## Overview + +`CanDeserializeJsonString` is the shortest way to read JSON with a context. Any **context**, the +type whose wiring holds an application's choices, that can read `T` and has an error type gets the +method automatically, with no `TryComputer` entries to wire. + +## Definition + +```rust +#[cgp_fn(CanDeserializeJsonString)] +#[use_type(HasErrorType.Error)] +pub fn deserialize_json_string(&self, serialized: &str) -> Result +where + DeserializeFromJsonString: for<'a> TryComputer, &'a str, Output = T>, +{ ... } +``` + +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) turns the function into a trait, +`CanDeserializeJsonString`, implemented for every context that meets its bounds. It lives in +`cgp_serde_json::impls`. + +## Usage + +Import the trait, and call the method on a context, giving the target type on the result. The +method takes no turbofish, since `#[cgp_fn]` moves `T` onto the trait. From the repository's arena +test: + +```rust +let deserialized: Payload<'_> = app.deserialize_json_string(&serialized).unwrap(); +``` + +## Behavior + +The method calls [`DeserializeFromJsonString`](../providers/deserialize_from_json_string.md) +directly, rather than through the context's `TryComputerComponent`, so the context needs no +`TryComputer` entries. It shares that provider's behavior: it rejects trailing input, turns +`serde_json` errors into the context's error type, and cannot produce a value that borrows from the +string. + +## Context dependencies + +A deserializer for `T` for every lifetime, and an error type that can be raised from a +`serde_json::Error`: `HasErrorType` and `CanRaiseError`. A context without the +error components does not have the method; [the debugging +guide](../../guides/debugging-wiring.md#the-json-method-is-missing-its-error-wiring) shows the error +and the fix. + +## Pairing + +Writing JSON is done with [`SerializeToJsonString`](../providers/serialize_to_json_string.md) +through `try_compute`, or with `serde_json` and a +[`SerializeWithContext`](./serialize_with_context.md). + +## When to use it + +**Reach for `deserialize_json_string` to read an owned value from a string with the least wiring.** +To read from bytes or a stream, or to produce a value that borrows from the input, wire +[`DeserializeFromJsonReader`](../providers/deserialize_from_json_reader.md) instead. + +## Related constructs + +- [`DeserializeFromJsonString`](../providers/deserialize_from_json_string.md), the provider it + calls. + +## The ideas behind it + +- [`#[cgp_fn]`](/docs/reference/macros/cgp_fn): a function turned into a trait any matching context + implements. +- [Modular error handling](/docs/concepts/modular-error-handling): the error components it needs. + +## Source + +- [`crates/cgp-serde-json/src/impls/deserialize.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-json/src/impls/deserialize.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/types/deserialize_with_context.md b/docs/projects/cgp-serde/reference/types/deserialize_with_context.md new file mode 100644 index 00000000..992c3b33 --- /dev/null +++ b/docs/projects/cgp-serde/reference/types/deserialize_with_context.md @@ -0,0 +1,94 @@ +--- +title: 'DeserializeWithContext — read with a context through any Serde format in cgp-serde' +sidebar_label: 'DeserializeWithContext' +sidebar_position: 2 +description: 'The cgp-serde adapter that pairs a context with a target type as a Serde DeserializeSeed, so any format reads through the context.' +--- + +# `DeserializeWithContext` + +Pair a context with a target type as a Serde `DeserializeSeed`. + +## Overview + +`DeserializeWithContext` is the way to read with any Serde format. Serde's `Deserialize` has no +receiver, so there is nowhere to put a **context**, the type whose wiring holds an application's +choices. Serde's `DeserializeSeed` is the trait for deserializing with state, and this adapter is a +seed whose state is the context: driving it with a format's deserializer reads the target type +through the context's wiring. + +## Definition + +```rust +pub struct DeserializeWithContext<'a, Context, Value> { + pub context: &'a Context, + pub phantom: PhantomData, +} + +impl<'a, Context, Value> DeserializeWithContext<'a, Context, Value> { + pub fn new(context: &'a Context) -> Self { ... } +} + +impl<'de, 'a, Context, Value> DeserializeSeed<'de> for DeserializeWithContext<'a, Context, Value> +where + Context: CanDeserializeValue<'de, Value>, +{ ... } +``` + +It lives in `cgp_serde::types`. + +## Usage + +Serde's convenience functions such as `serde_json::from_str` accept only a `Deserialize` type, not a +seed, so build the format's deserializer, drive the seed with it, and check for trailing input: + +```rust +let mut deserializer = serde_json::Deserializer::from_str(&text); +let value: Rec = DeserializeWithContext::new(&app).deserialize(&mut deserializer)?; +deserializer.end()?; +``` + +`deserialize` here is `DeserializeSeed::deserialize`, so `serde::de::DeserializeSeed` must be in +scope. + +## Behavior + +Driving the seed calls the context's deserializer for `Value` and returns the value. Every nested +value goes back through the same wiring. The format's own error comes back unchanged. The adapter +needs no error wiring on the context. + +## Context dependencies + +`Context: CanDeserializeValue<'de, Value>`. + +## Pairing + +[`SerializeWithContext`](./serialize_with_context.md) is the adapter for writing. + +## When to use it + +**Reach for `DeserializeWithContext` to read with a format that has no cgp-serde helper**, or to +read JSON with no error wiring. For JSON in the context's own error type, +[`DeserializeFromJsonReader`](../providers/deserialize_from_json_reader.md) drives the seed and +checks for trailing input itself. + +## Related constructs + +- [`DeserializeRecordFields`](../providers/deserialize_record_fields.md) uses it for each field. + +## The ideas behind it + +- [The bridge to + Serde](../../architecture/serde-bridge.md#going-out-handing-a-context-to-a-serde-api): why reading + needs a seed. +- [Using a format](../../guides/formats.md#read-with-another-format): the seed with RON. + +## Source + +- [`crates/cgp-serde/src/types/deserialize_with_context.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/types/deserialize_with_context.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/types/serialize_with_context.md b/docs/projects/cgp-serde/reference/types/serialize_with_context.md new file mode 100644 index 00000000..6dcefecb --- /dev/null +++ b/docs/projects/cgp-serde/reference/types/serialize_with_context.md @@ -0,0 +1,94 @@ +--- +title: 'SerializeWithContext — hand a context to any Serde format in cgp-serde' +sidebar_label: 'SerializeWithContext' +sidebar_position: 1 +description: 'The cgp-serde adapter that pairs a context with a value as a Serde Serialize value, so any format writes through the context.' +--- + +# `SerializeWithContext` + +Pair a context with a value as an ordinary Serde `Serialize` value. + +## Overview + +`SerializeWithContext` is the way into Serde's formats. Serde's functions, such as +`serde_json::to_string`, accept a value that implements `Serialize` and have no place for a +**context**, the type whose wiring holds an application's choices. The adapter carries both, and its +`Serialize` impl writes the value through the context's wiring. Providers use the same adapter to +hand each nested value back to the context from inside Serde's compound writers. + +## Definition + +```rust +pub struct SerializeWithContext<'a, Context, T> { + pub context: &'a Context, + pub value: &'a T, +} + +impl<'a, Context, T> SerializeWithContext<'a, Context, T> { + pub fn new(context: &'a Context, value: &'a T) -> Self { ... } +} + +impl<'a, Context, T> serde::Serialize for SerializeWithContext<'a, Context, T> +where + Context: CanSerializeValue, +{ ... } +``` + +It lives in `cgp_serde::types`. + +## Usage + +Build it with `new` and pass it to any Serde format. From the +[`messages`](../../examples/messages.md) example: + +```rust +let serialized = + serde_json::to_string_pretty(&SerializeWithContext::new(&AppA, &archive)).unwrap(); +``` + +Both fields are public, so a provider can build it with a struct literal, as the library's own +providers do. + +## Behavior + +Serializing the adapter calls the context's serializer for `T`, so the context's wiring decides the +output, and every nested value goes back through the same wiring. The format's own error comes back +unchanged, since the adapter involves none of CGP's error handling. `T` must be a sized type. + +## Context dependencies + +`Context: CanSerializeValue`, which needs whatever the provider wired for `T` needs. + +## Pairing + +[`DeserializeWithContext`](./deserialize_with_context.md) is the adapter for reading. + +## When to use it + +**Reach for `SerializeWithContext` to write with any Serde format**, and to hand a nested value to +one of Serde's compound writers inside a provider. For a JSON string in the context's own error +type, [`SerializeToJsonString`](../providers/serialize_to_json_string.md) wraps it. + +## Related constructs + +- [`SerializeIterator`](../providers/serialize_iterator.md) and + [`SerializeFields`](../providers/serialize_fields.md) use it for each item and field. + +## The ideas behind it + +- [The bridge to + Serde](../../architecture/serde-bridge.md#going-out-handing-a-context-to-a-serde-api): how a + context reaches a Serde API. +- [Re-entrant providers](../../architecture/reentrant-providers.md#re-entering-through-an-adapter): + the adapter inside a provider. + +## Source + +- [`crates/cgp-serde/src/types/serialize_with_context.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/types/serialize_with_context.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/serde-comparison.md b/docs/projects/cgp-serde/serde-comparison.md new file mode 100644 index 00000000..721b4c9e --- /dev/null +++ b/docs/projects/cgp-serde/serde-comparison.md @@ -0,0 +1,119 @@ +--- +sidebar_label: 'Compared with Serde' +sidebar_position: 5 +description: 'cgp-serde and Serde compared: what they share, what cgp-serde adds, how Serde''s idioms map onto wiring, and when plain Serde is better.' +--- + +# cgp-serde compared with Serde + +[cgp-serde](./index.md) is built on [Serde](https://serde.rs/) and depends on it, so this is not a +comparison between rival libraries. It compares two ways of implementing one layer of Serde: Serde's +own `Serialize` and `Deserialize` traits with their derive, and cgp-serde's +[CGP](/docs/) components with their providers. Serde is the mature, widely adopted library of +the two, and the foundation cgp-serde stands on. This page sets out what the two share, what +cgp-serde adds, how Serde's idioms map onto it, and when plain Serde is the better choice. + +## What they share + +Everything below the data-type layer is shared rather than compared. cgp-serde uses Serde's data +model, its `Serializer` and `Deserializer` traits, and every format built on them, and it reuses any +existing `Serialize` or `Deserialize` impl through [`UseSerde`](./reference/providers/use_serde.md). +A program can therefore use cgp-serde for some types and Serde's derive for the rest, in the same +value and the same format. [The bridge to Serde](./architecture/serde-bridge.md) explains how the +two meet. + +## What cgp-serde adds + +cgp-serde adds four things that Serde's trait design cannot express, each a consequence of moving +the encoded value out of `Self` and letting a **context**, a type that stands for an application, +choose its providers: + +- **Encodings chosen per application.** Two contexts can encode the same type differently, such as + `Vec` as hex in one application and base64 in another, with the choice reaching every nested + occurrence. With Serde, a type has one `Serialize` impl in the program. +- **Implementations that overlap, and implementations for types a crate does not own.** Providers + such as "any `Display` type, as a string" and "any `AsRef<[u8]>` type, as bytes" coexist, and a + crate can provide an encoding for a type from another crate. Rust's coherence rules allow Serde + neither. +- **Data types with no serialization derive.** A struct that derives CGP's general field traits is + serialized by generic providers, so a crate of data types needs no `serde` dependency; see + [derive-free records](./architecture/derive-free-records.md). +- **Services while deserializing.** A provider can take something from the context as it works, such + as an arena to allocate into; see [context services](./architecture/context-services.md). Serde + supports deserializing with state through hand-written `DeserializeSeed` impls, which its derive + does not produce. + +## How Serde's idioms map + +Many of Serde's features exist to work within the one-impl-per-type rule, and cgp-serde meets the +same needs with wiring instead. The mapping is not one to one, because Serde's attributes are per +field while a cgp-serde context chooses per type: + +| With Serde | With cgp-serde | +|---|---| +| `#[serde(with = "hex")]` on a field | wire the field's type to `SerializeHex` in the context; every field of that type follows | +| `serialize_with` and `deserialize_with` | write a provider, and wire the type to it | +| a newtype to change a type's encoding | wire a different provider in a different context | +| `#[serde(remote = "…")]` for a type from another crate | wire the type to a provider directly | +| `#[derive(Serialize, Deserialize)]` on a struct | derive `CgpData`, and wire the struct to `SerializeFields` and `DeserializeRecordFields` | +| a hand-written `DeserializeSeed` for state | a provider that takes the state from the context | +| a borrowed `&'de str` field | wire `&'a str` to `UseSerde`, and read from input that can lend it | + +## What Serde's derive does that the generic providers do not + +Serde's derive is the product of years of use, and it handles cases that cgp-serde's generic +providers leave to it: + +- **Field and container attributes**, such as `rename`, `skip`, `flatten`, `default`, and + `deny_unknown_fields`. cgp-serde's struct providers write every field under its Rust name and + expect every field to be present. +- **Enums, tuple structs, and tuples.** Serde derives all of them, in several representations for + enums. cgp-serde's struct providers handle structs with named fields. +- **Recursive types**, such as a tree whose nodes contain nodes. Serde derives them without + difficulty; cgp-serde's generic providers cannot express the recursion, and such a type needs a + provider written for it. +- **Binary formats that need lengths.** Serde's derived impls declare lengths, which formats such as + postcard rely on. cgp-serde's generic providers do not, so their output suits self-describing + formats such as JSON and RON. + +Any of these types can still take part in a cgp-serde value: it keeps Serde's derive, and the +context wires it to `UseSerde`. + +## What each approach costs + +Serde's cost is the rule it lives under. A type has one encoding for the whole program, chosen by +the crate that owns the type, and a program that needs another has to wrap the type, annotate every +field that holds it, or ask the owner to change it. For most programs that cost is never felt, +because one encoding per type is all they want. + +cgp-serde's cost is the wiring and CGP itself. Each application writes out a table naming a provider +for every type it encodes, including in-between types such as a `Vec` of structs, and a mistake in +the table is a compile error that can be long. Writing a provider means learning CGP's components +and wiring. The library is also a proof of concept, lightly tested and with none of Serde's history +of use. Provider selection is resolved at compile time, so wiring adds no lookup at run time, but no +benchmark compares the two. + +## When plain Serde is the better choice + +**Plain Serde is the right tool whenever the one-impl-per-type rule does not bind.** A program that +encodes each type one way needs no choice per context, and Serde's derive gives it attributes, +enums, binary formats, and a mature implementation with no wiring to write. It is also the right +choice for a type that needs the attributes or representations above, for binary formats, and for a +team with no other use for CGP, since cgp-serde's wiring and its errors carry CGP's learning cost. + +cgp-serde earns its place where the rule does bind: the same types encoded differently by different +applications, encodings for types a crate does not own, data crates that should not depend on +`serde`, and deserializers that need something Serde's traits have no room for. Because the two +work together through `UseSerde` and the adapters, a program can use each for the types it suits. + +## Where to go next + +- [`messages`](./examples/messages.md): the per-application encoding in a running program. +- [Limitations](./limitations.md): where cgp-serde's design stops. +- [Coherence](/docs/concepts/coherence): the Rust rule behind Serde's one impl per type. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/index.md b/docs/projects/index.md index 9e2ab0f7..02939612 100644 --- a/docs/projects/index.md +++ b/docs/projects/index.md @@ -21,6 +21,9 @@ can judge the evidence for what it is. - **[Hypershell](./hypershell/index.md)** — a shell-scripting language whose programs are Rust types, interpreted at compile time through CGP wiring. A proof of concept that builds on nightly Rust, and the most complete example of a type-level language built with CGP. +- **[cgp-serde](./cgp-serde/index.md)** — Serde's `Serialize` and `Deserialize` rebuilt as CGP + components, so each application chooses how a type is encoded. A proof of concept on stable Rust, + and the clearest example of CGP letting two applications choose differently for the same types. ## Find a pattern @@ -38,14 +41,20 @@ the Concepts page that explains the idea: | Providers bundled into an aggregate provider that routes point at | [`http_checksum_native`](./hypershell/examples/http-checksum-native.md) | [Aggregate providers](/docs/concepts/aggregate-providers) | | Nested expressions, each resolved through the context | [`github_issues`](./hypershell/examples/github-issues.md) | [Impl-side dependencies](/docs/concepts/impl-side-dependencies) | | One context extended with its own wiring entries, including a new error type | [`bluesky_websocket`](./hypershell/examples/bluesky-websocket.md) | [Modular error handling](/docs/concepts/modular-error-handling) | +| A struct encoded with no serialization derive, by providers that read its fields | [`basic`](./cgp-serde/examples/basic.md) | [Extensible records](/docs/concepts/extensible-records) | +| An operation made fallible in the context's own error type | [`basic`](./cgp-serde/examples/basic.md) | [Modular error handling](/docs/concepts/modular-error-handling) | +| Two applications choosing different implementations for the same types | [`messages`](./cgp-serde/examples/messages.md) | [Coherence](/docs/concepts/coherence) | +| A provider chosen by the type of the value it is given, from a table per context | [`messages`](./cgp-serde/examples/messages.md) | [Modularity hierarchy](/docs/concepts/modularity-hierarchy) | +| Providers that hand nested values back to the context, so one choice reaches every level | [`messages`](./cgp-serde/examples/messages.md) | [Impl-side dependencies](/docs/concepts/impl-side-dependencies) | ## Where to start - **To see CGP's ideas in a real program**, read [`hello`](./hypershell/examples/hello.md), then follow the examples in order. -- **To weigh whether CGP holds up past a toy**, read the [Hypershell - overview](./hypershell/index.md) and its [limitations](./hypershell/limitations.md), which state - the costs first. +- **To weigh whether CGP holds up past a toy**, read the [Hypershell](./hypershell/index.md) and + [cgp-serde](./cgp-serde/index.md) overviews and their limitations pages, which state the costs + first. cgp-serde's [comparison with Serde](./cgp-serde/serde-comparison.md) sets it beside the + library it rebuilds. - **To learn CGP from the beginning**, start with the [Hello World tutorial](/docs/tutorials/hello) instead; these pages assume it rather than teach it. diff --git a/docs/resources.md b/docs/resources.md index 10224f23..e8532992 100644 --- a/docs/resources.md +++ b/docs/resources.md @@ -12,7 +12,7 @@ This page lists some resources related to CGP. More resources will be added as t - [`cgp-error-anyhow`](https://crates.io/crates/cgp-error-anyhow) - A CGP crate for handling modular errors using `anyhow`. - [`cgp-error-eyre`](https://crates.io/crates/cgp-error-eyre) - The same, using `eyre`. - [`cgp-error-std`](https://crates.io/crates/cgp-error-std) - The same, using only the standard library. -- [`cgp-serde`](https://crates.io/crates/cgp-serde) - Modular serialization library for Serde. +- [`cgp-serde`](https://crates.io/crates/cgp-serde) - Modular serialization library for Serde. Documented on this site in the [Projects](/docs/projects/cgp-serde/) section, with its examples walked through as short tutorials. ## Tooling From df184c266485f5b2666fa1622cddf0e756267c6a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 06:06:26 +0000 Subject: [PATCH 102/516] Add the cgp-examples pages for expression and web-app The cgp-examples section index, the expression subsection with its four examples and two architecture pages, and the four web-app stages. Also fixes a double space after list markers on ten cgp-serde pages. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HvLfWEnrK9PnjZSdoLbHG5 --- docs/projects/cgp-examples/_category_.json | 8 + .../cgp-examples/expression/_category_.json | 8 + .../expression/architecture/_category_.json | 8 + .../architecture/dispatch-layers.md | 117 +++++++ .../expression/architecture/index.md | 98 ++++++ .../expression/examples/_category_.json | 8 + .../expression/examples/add-mult-binary-op.md | 178 +++++++++++ .../expression/examples/add-mult-code.md | 177 +++++++++++ .../expression/examples/add-mult-neg.md | 179 +++++++++++ .../expression/examples/add-mult.md | 294 ++++++++++++++++++ .../cgp-examples/expression/examples/index.md | 57 ++++ .../projects/cgp-examples/expression/index.md | 117 +++++++ docs/projects/cgp-examples/index.md | 58 ++++ .../cgp-examples/web-app/_category_.json | 8 + .../web-app/examples/_category_.json | 5 + .../web-app/examples/coarse-grained.md | 175 +++++++++++ .../web-app/examples/default-impls.md | 176 +++++++++++ .../web-app/examples/fine-grained.md | 184 +++++++++++ .../web-app/examples/namespaces.md | 167 ++++++++++ docs/projects/cgp-examples/web-app/index.md | 80 +++++ .../architecture/derive-free-records.md | 2 +- .../architecture/reentrant-providers.md | 2 +- docs/projects/cgp-serde/examples/messages.md | 4 +- docs/projects/cgp-serde/guides/formats.md | 4 +- .../cgp-serde/guides/wiring-a-context.md | 4 +- .../cgp-serde/guides/writing-a-provider.md | 2 +- .../providers/deserialize_from_json_reader.md | 2 +- .../providers/try_deserialize_bytes.md | 2 +- .../types/deserialize_with_context.md | 2 +- .../reference/types/serialize_with_context.md | 2 +- docs/projects/index.md | 15 +- docs/resources.md | 2 +- 32 files changed, 2130 insertions(+), 15 deletions(-) create mode 100644 docs/projects/cgp-examples/_category_.json create mode 100644 docs/projects/cgp-examples/expression/_category_.json create mode 100644 docs/projects/cgp-examples/expression/architecture/_category_.json create mode 100644 docs/projects/cgp-examples/expression/architecture/dispatch-layers.md create mode 100644 docs/projects/cgp-examples/expression/architecture/index.md create mode 100644 docs/projects/cgp-examples/expression/examples/_category_.json create mode 100644 docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md create mode 100644 docs/projects/cgp-examples/expression/examples/add-mult-code.md create mode 100644 docs/projects/cgp-examples/expression/examples/add-mult-neg.md create mode 100644 docs/projects/cgp-examples/expression/examples/add-mult.md create mode 100644 docs/projects/cgp-examples/expression/examples/index.md create mode 100644 docs/projects/cgp-examples/expression/index.md create mode 100644 docs/projects/cgp-examples/index.md create mode 100644 docs/projects/cgp-examples/web-app/_category_.json create mode 100644 docs/projects/cgp-examples/web-app/examples/_category_.json create mode 100644 docs/projects/cgp-examples/web-app/examples/coarse-grained.md create mode 100644 docs/projects/cgp-examples/web-app/examples/default-impls.md create mode 100644 docs/projects/cgp-examples/web-app/examples/fine-grained.md create mode 100644 docs/projects/cgp-examples/web-app/examples/namespaces.md create mode 100644 docs/projects/cgp-examples/web-app/index.md diff --git a/docs/projects/cgp-examples/_category_.json b/docs/projects/cgp-examples/_category_.json new file mode 100644 index 00000000..68e1c9dd --- /dev/null +++ b/docs/projects/cgp-examples/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "cgp-examples", + "position": 3, + "link": { + "type": "doc", + "id": "projects/cgp-examples/index" + } +} diff --git a/docs/projects/cgp-examples/expression/_category_.json b/docs/projects/cgp-examples/expression/_category_.json new file mode 100644 index 00000000..18d8b75b --- /dev/null +++ b/docs/projects/cgp-examples/expression/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "expression", + "position": 1, + "link": { + "type": "doc", + "id": "projects/cgp-examples/expression/index" + } +} diff --git a/docs/projects/cgp-examples/expression/architecture/_category_.json b/docs/projects/cgp-examples/expression/architecture/_category_.json new file mode 100644 index 00000000..29c14b76 --- /dev/null +++ b/docs/projects/cgp-examples/expression/architecture/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Architecture", + "position": 2, + "link": { + "type": "doc", + "id": "projects/cgp-examples/expression/architecture/index" + } +} diff --git a/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md b/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md new file mode 100644 index 00000000..5909a94f --- /dev/null +++ b/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md @@ -0,0 +1,117 @@ +--- +sidebar_label: 'Dispatch layers' +sidebar_position: 1 +description: 'The two ways the expression contexts key their dispatch, by input alone or by operation and input, and why every context wraps the dispatcher for its enum.' +--- + +# Dispatch layers + +Every context in [`expression`](../index.md) chooses a provider by the type of the expression it is +given, and some also choose by the operation. Why do they write their tables two different ways, and +why does each one write a small wrapper for its enum? `expression` is an arithmetic interpreter +built with [CGP](/docs/), and a **context** in it is a type that stands for one interpreter and +holds its choices. This page explains both arrangements, and the wrapper that every context needs. + +## Two ways to pick the operation + +The crate runs two operations, evaluation and conversion to Lisp, and its contexts pick between them +in one of two ways: + +| Contexts | How the operation is chosen | Keys fix | +|---|---|---| +| [`add_mult`](../examples/add-mult.md), [`add_mult_binary_op`](../examples/add-mult-binary-op.md) | by which method is called: `compute` evaluates, `compute_ref` converts | the input only | +| [`add_mult_code`](../examples/add-mult-code.md), [`add_mult_neg`](../examples/add-mult-neg.md) | by a marker type passed with the input: `Eval` or `ToLisp` | the marker and the input | + +In the first arrangement, each operation has a component of its own. `Interpreter` in `add_mult` +opens both, and each key's first part is a generic ` Code`, which matches any marker, so only +the input decides: + +```rust +open { ComputerComponent, ComputerRefComponent }; + +@ComputerComponent. Code.MathExpr: DispatchEval, +@ComputerComponent. Code.Plus: EvalAdd, +@ComputerComponent. Code.Times: EvalMultiply, +@ComputerComponent. Code.Literal: EvalLiteral, +``` + +In the second, one component serves every operation, so the marker has to decide. Each key fixes it, +and each operator has one entry per operation, as in `add_mult_code`: + +```rust +@ComputerRefComponent.Eval.Plus: EvalAdd, +@ComputerRefComponent.ToLisp.Plus: BinaryOpToLisp, +``` + +`Eval` and `ToLisp` are empty structs the crate defines to name its operations. Both arrangements +are resolved by the compiler, so the choice between them changes only how the table reads and how a +caller asks for an operation. The first keeps the table short while the operations are few; the +second puts every operation behind one method and makes each operation's providers visible entry by +entry. + +## Every context wraps the dispatcher + +Each context maps its language enum not to CGP's dispatcher, +[`MatchWithValueHandlers`](/docs/reference/providers/dispatch/match_with_value_handlers), but to a +small provider of its own that calls it: + +```rust +#[cgp_impl(new DispatchEval)] +impl Computer for Interpreter { + type Output = Value; + + fn compute(context: &Interpreter, code: PhantomData, expr: MathExpr) -> Self::Output { + ::compute(context, code, expr) + } +} +``` + +The wrapper looks redundant, and it is required. The dispatcher takes a `MathExpr` apart and hands +the operator inside back to the context, and the operator's provider then asks the context to +compute its operands, which are `MathExpr` again. When the dispatcher is wired as the `MathExpr` +entry directly, the compiler has to prove "this context can evaluate a `MathExpr`" by first proving +it for each operand, which is the same question, and it never finishes. With the wiring changed to +`@ComputerComponent. Code.MathExpr: MatchWithValueHandlers`, the context's check reports that +the wiring never resolves: + +```text +error[E0275]: [CGP-E010] the wiring for the consumer trait `CanCompute` on context `Interpreter` never resolves — the lookup recurses without terminating +``` + +The same error follows for `Plus` and `Times`, and two raw overflow errors for the dispatcher +itself. Its help line suggests a component wired back to the context itself, the usual cause of the +class; here the loop runs through the operands instead. + +The wrapper breaks the loop, and the likeliest reason is the shape of its impl: it is written for +one concrete context, with a concrete output type and no conditions. The compiler can then accept +that `Interpreter` evaluates a `MathExpr` from the impl's header alone, and looks into the +dispatcher only when it compiles the body, where the question no longer depends on itself. +Experiments point that way, since a wrapper that states the dispatcher's requirement as a condition +on its impl never finished compiling in them, but they are evidence rather than proof. + +## What it costs + +A wrapper is written per context and per operation, fixed to that context's types, so each module in +the crate defines its own `DispatchEval`, and `DispatchToLisp` where it converts. In the contexts +keyed by marker, the wrappers also fix the marker, since there the marker selects the operation. +They are a few lines each, and they are the kind of code a reader has to be told the reason for, +since nothing in them says why they exist. + +Wiring through a generic dispatcher also means a missing operator entry is reported twice: once at +the context's check, which names the entry, and once at the wrapper, where the dispatcher cannot +find a provider for the variant. The check's error is the one to read, as the [`add_mult` +example](../examples/add-mult.md#try-a-change) shows. + +## Where to go next + +- [How expression works](./index.md): the design these tables serve. +- [`add_mult_code`](../examples/add-mult-code.md): the marker-keyed arrangement in a running + context. +- [Dispatching](/docs/concepts/dispatching): the CGP idea behind the dispatcher, and how it checks + every variant. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/expression/architecture/index.md b/docs/projects/cgp-examples/expression/architecture/index.md new file mode 100644 index 00000000..1b0ce5fd --- /dev/null +++ b/docs/projects/cgp-examples/expression/architecture/index.md @@ -0,0 +1,98 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'How the expression interpreter works: operators as generic structs, one provider per operator, abstract output types, and contexts that wire them up.' +--- + +# How expression works + +How can an interpreter gain a new operator without anyone editing the code that handles the old +ones? [`expression`](../index.md) is an arithmetic interpreter built with [CGP](/docs/), a language +extension for Rust with pluggable trait implementations at compile-time, and its answer is to split +the usual enum and `match` into parts that can each be reused. This page explains the design in +outline: what an operator is, what an operation is, and what puts them together. + +## Each operator is its own type + +A plain interpreter defines its language as one enum, with the operators as its variants. Here each +operator is a struct of its own, generic over the expression type it contains: + +```rust +#[derive(Debug, Eq, PartialEq, HasField)] +pub struct Plus { + pub left: Box, + pub right: Box, +} +``` + +`Plus`, `Times`, `Minus`, and `Negate` hold boxed operands of the type `Expr`, and `Literal` +holds a value of any type. None of them knows which language it belongs to. A language is then an +ordinary enum that wraps them and fills in the type parameter with itself, such as +`Plus(Plus)`. So one `Plus` serves every language that has addition, and so does every +provider written for it. + +## Each operation is one provider per operator + +An operation over the language, such as evaluation, is written as one provider per operator: +`EvalAdd` for `Plus`, `EvalMultiply` for `Times`, and so on. Each implements one of CGP's +computation interfaces, [`Computer`](/docs/reference/components/handler/computer) or its borrowing +form [`ComputerRef`](/docs/reference/components/handler/computer_ref), for its operator, and handles +its operands by asking the context to compute them. So a provider never names the enum, or the +other operators, and it works for any language whose operands it can compute. + +The crate has two operations. Evaluation turns an expression into a number, and conversion to Lisp +turns it into an S-expression tree such as `(* 2 (+ 3 4))`. The evaluation providers implement both +computation interfaces, so a context can evaluate by value or by reference with the same providers. + +## A provider builds a type the context chooses + +The conversion providers have to produce a Lisp expression, and they do it without naming the Lisp +enum. The context declares which concrete type its Lisp expressions are, through an [abstract +type](/docs/concepts/abstract-types), and each provider asks for it with +[`#[use_type]`](/docs/reference/attributes/use_type). The provider builds only the variants it +needs, in a small enum of its own, and converts that into the full type with +[`upcast`](/docs/reference/traits/casting/can_upcast), which works because the small enum's variants +are a subset of the full one's. So `PlusToLisp` serves any Lisp type that has a list and an +identifier. + +## A context puts the pieces together + +A **context** is a type that stands for one interpreter and holds its choices. The crate has four, +each an empty struct in its own module, with its own copy of the enums it uses. A context's wiring +table maps each operator type to its provider, and maps the whole language enum to a small wrapper +that calls CGP's generic dispatcher, +[`MatchWithValueHandlers`](/docs/reference/providers/dispatch/match_with_value_handlers). The +dispatcher finds which variant an expression holds and hands the operator inside back to the +context, whose table sends it on to the operator's provider. That is the `match`, written once, +generically, by CGP. + +The compiler resolves every choice in the table while it type-checks the program, so none of this +is looked up at run time. [Dispatch layers](./dispatch-layers.md) explains the two ways the contexts +key their tables, and why each needs its own wrapper. + +## What the design costs + +The flexibility is paid for in parts. Where a plain interpreter has an enum and a `match` per +operation, this one has an operator struct per operator, a provider per operator per operation, a +wiring table per interpreter, and a wrapper per interpreter per operation. A reader tracing what +happens to a `Plus` follows it from the enum to the table to the provider, where the plain version +has one `match` arm. And a mistake in the wiring is a compile error whose chain runs through CGP's +dispatcher. + +For a language that will not grow, the enum and `match` is simpler and better. The design earns its +cost when the language, or the set of operations over it, is meant to grow from code that cannot +edit the original, such as a second crate adding an operator. + +## Where to go next + +- [Dispatch layers](./dispatch-layers.md): how the contexts key their dispatch, and the wrapper + every context needs. +- [`add_mult`](../examples/add-mult.md): the design in the first context, with its tests. +- [Extensible variants](/docs/concepts/extensible-variants): the CGP idea behind handling one + variant of any enum. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/expression/examples/_category_.json b/docs/projects/cgp-examples/expression/examples/_category_.json new file mode 100644 index 00000000..e55fe8d8 --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Examples", + "position": 1, + "link": { + "type": "doc", + "id": "projects/cgp-examples/expression/examples/index" + } +} diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md b/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md new file mode 100644 index 00000000..fea452a3 --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md @@ -0,0 +1,178 @@ +--- +sidebar_label: 'add_mult_binary_op' +sidebar_position: 2 +description: 'One generic CGP provider converts both binary operators to Lisp, reading its operands through a getter and taking the operator symbol as a type parameter.' +--- + +# Convert every binary operator with one provider + +This **context**, the type that stands for one interpreter and holds its choices, converts +arithmetic expressions to Lisp with one provider for both `+` and `*`, where +[`add_mult`](./add-mult.md) had a provider for each. It is an example from +[`expression`](../index.md), an interpreter from the [cgp-examples](../../index.md) repository, +built with [CGP](/docs/). The change is small, and it shows how a provider can be generic over the +operator it handles. + +:::tip + +### New to CGP? + +[`add_mult`](./add-mult.md) introduces the interpreter, its providers, and its wiring, which this +page reuses. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) introduces providers +and wiring, and [Extensible records](/docs/concepts/extensible-records) explains the field access +the new provider relies on. + +::: + +## Run it + +This context has no test of its own in the repository, so running it takes a test of your own. Save +this as `expression/tests/binary_op.rs` in the [cgp-examples +repository](https://github.com/contextgeneric/cgp-examples): + +```rust +use core::marker::PhantomData; + +use cgp::extra::handler::{CanCompute, CanComputeRef}; +use cgp_example_expression::contexts::add_mult_binary_op::{Interpreter, MathExpr}; +use cgp_example_expression::dsl::{Eval, ToLisp}; +use cgp_example_expression::types::{Literal, Plus, Times}; + +#[test] +fn binary_op() { + let expr = MathExpr::Times(Times { + left: MathExpr::Literal(Literal(2)).into(), + right: MathExpr::Plus(Plus { + left: MathExpr::Literal(Literal(3)).into(), + right: MathExpr::Literal(Literal(4)).into(), + }) + .into(), + }); + + println!("{:?}", Interpreter.compute_ref(PhantomData::, &expr)); + println!("{}", Interpreter.compute(PhantomData::, expr)); +} +``` + +Run it from the repository root, showing what it prints: + +```sh +cargo test -p cgp-example-expression --test binary_op -- --nocapture +``` + +It prints the Lisp tree for `(* 2 (+ 3 4))`, then the value: + +```text +List(List([Ident(Ident("*")), Literal(Literal(2)), List(List([Ident(Ident("+")), Literal(Literal(3)), Literal(Literal(4))]))])) +14 +``` + +## Two entries, one provider + +The context's module, +[`add_mult_binary_op.rs`](https://github.com/contextgeneric/cgp-examples/blob/main/expression/src/contexts/add_mult_binary_op.rs), +has its own copy of `add_mult`'s enums, its context `Interpreter`, and its wrappers. Its wiring +differs in two lines, the conversion entries for the binary operators: + +```rust +@ComputerRefComponent. Code.Plus: BinaryOpToLisp, +@ComputerRefComponent. Code.Times: BinaryOpToLisp, +``` + +Both entries name the same provider, `BinaryOpToLisp`, with a different type parameter. +[`Symbol!`](/docs/reference/macros/symbol) turns a string into a type, so the operator's symbol +travels in the wiring rather than in the provider's code. Evaluation is unchanged: each operator +still has its own evaluation provider, since `+` and `*` compute differently. + +## The provider reads its operands through a getter + +`BinaryOpToLisp` handles any input that has a `left` and a `right` operand. It says so with a getter +trait, from the crate's `providers/to_lisp/binary.rs`: + +```rust +#[cgp_auto_getter] +pub trait BinarySubExpression { + fn left(&self) -> &Box; + fn right(&self) -> &Box; +} +``` + +[`#[cgp_auto_getter]`](/docs/reference/macros/cgp_auto_getter) implements the trait for any type +with fields of those names and types. `Plus` and `Times` derive +[`HasField`](/docs/reference/derives/derive_has_field), which exposes their fields by name, so both +get the trait without writing an impl. Getters usually read a context's fields; this one reads the +provider's input instead. + +The provider then uses the getter, the symbol, and the same local-enum trick as `add_mult`'s +conversion providers: + +```rust +#[cgp_impl(new BinaryOpToLisp)] +#[use_type(HasMathExprType.MathExpr, HasLispExprType.LispExpr)] +#[uses(CanComputeRef)] +impl ComputerRef +where + MathSubExpr: BinarySubExpression, + Operator: Default + Display, + LispSubExpr: CanUpcast, +{ + type Output = LispExpr; + + fn compute_ref(&self, code: PhantomData, expr: &MathSubExpr) -> Self::Output { + let expr_a = self.compute_ref(code, expr.left()); + let expr_b = self.compute_ref(code, expr.right()); + + let ident = LispSubExpr::Ident(Ident(Operator::default().to_string())).upcast(PhantomData); + + LispSubExpr::List(List(vec![ident.into(), expr_a.into(), expr_b.into()])) + .upcast(PhantomData) + } +} +``` + +The input is any `MathSubExpr` with the getter, and `Operator` is any type that can be built and +printed, which a `Symbol!` type is: `Operator::default().to_string()` turns `Symbol!("+")` back into +`"+"`. The provider needs the context's expression type to know what the operands are, so it imports +`MathExpr` with [`#[use_type]`](/docs/reference/attributes/use_type), which the context's +`UseType` entry sets. + +## Try a change + +Change the symbol in the `Plus` entry from `Symbol!("+")` to `Symbol!("add")`, and run the test +again. The inner operator's name changes, and nothing else does: + +```text +List(List([Ident(Ident("*")), Literal(Literal(2)), List(List([Ident(Ident("add")), Literal(Literal(3)), Literal(Literal(4))]))])) +14 +``` + +The provider was not touched; the operator's name lived only in the wiring. + +## The pattern + +This context shows **a provider generic over the variant it handles**, parameterized in the wiring. +Where the variants of an enum differ only in a detail, such as an operator's name, one provider can +serve them all, reading the parts it needs through a getter and taking the detail as a type +parameter. Getters over a provider's input are CGP's [extensible +records](/docs/concepts/extensible-records) put to use, and a provider taking another type as a +parameter is the same move that [higher-order providers](/docs/concepts/higher-order-providers) make +with providers. + +The cost is a less obvious provider. `PlusToLisp` says what it does in its name; `BinaryOpToLisp` +needs its type parameter read in the wiring, and its bounds read in its definition, to know what it +does. For two operators the saving is small, and the generic form pays off as the operators +multiply. + +## Where to go next + +- [`add_mult_code`](./add-mult-code.md): the next example, both operations in one component. +- [How expression works](../architecture/index.md): where the getter and the abstract types fit in + the design. +- [Extensible records](/docs/concepts/extensible-records): the CGP idea behind reading a struct's + fields by name. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-code.md b/docs/projects/cgp-examples/expression/examples/add-mult-code.md new file mode 100644 index 00000000..b61077b0 --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/add-mult-code.md @@ -0,0 +1,177 @@ +--- +sidebar_label: 'add_mult_code' +sidebar_position: 3 +description: 'Both interpreter operations served by one CGP component, each wiring entry keyed by an operation marker and the input type together.' +--- + +# Choose the operation with a marker type + +This **context**, the type that stands for one interpreter and holds its choices, serves both +evaluation and conversion to Lisp through one component, and chooses between them by a marker type +passed with the input. It is an example from [`expression`](../index.md), an interpreter from the +[cgp-examples](../../index.md) repository, built with [CGP](/docs/). Where +[`add_mult`](./add-mult.md) chose the operation by which method was called, this context chooses it +in its wiring, by keying each entry on two things at once. + +:::tip + +### New to CGP? + +[`add_mult`](./add-mult.md) introduces the interpreter and its wiring, which this page reuses. For +CGP itself, the [Hello World tutorial](/docs/tutorials/hello) introduces contexts and wiring, and +[Handlers](/docs/concepts/handlers) explains the `Code` marker that CGP's computation interfaces +carry. + +::: + +## Run it + +This context has no test of its own in the repository, so running it takes a test of your own. Save +this as `expression/tests/code.rs` in the [cgp-examples +repository](https://github.com/contextgeneric/cgp-examples): + +```rust +use core::marker::PhantomData; + +use cgp::extra::handler::CanComputeRef; +use cgp_example_expression::contexts::add_mult_code::{Interpreter, MathExpr}; +use cgp_example_expression::dsl::{Eval, ToLisp}; +use cgp_example_expression::types::{Literal, Plus, Times}; + +#[test] +fn code() { + let expr = MathExpr::Times(Times { + left: MathExpr::Literal(Literal(2)).into(), + right: MathExpr::Plus(Plus { + left: MathExpr::Literal(Literal(3)).into(), + right: MathExpr::Literal(Literal(4)).into(), + }) + .into(), + }); + + println!("{}", Interpreter.compute_ref(PhantomData::, &expr)); + println!("{:?}", Interpreter.compute_ref(PhantomData::, &expr)); +} +``` + +Run it from the repository root, showing what it prints: + +```sh +cargo test -p cgp-example-expression --test code -- --nocapture +``` + +The same method, `compute_ref`, evaluates with one marker and converts with the other: + +```text +14 +List(List([Ident(Ident("*")), Literal(Literal(2)), List(List([Ident(Ident("+")), Literal(Literal(3)), Literal(Literal(4))]))])) +``` + +## The marker is part of the key + +The context's module, +[`add_mult_code.rs`](https://github.com/contextgeneric/cgp-examples/blob/main/expression/src/contexts/add_mult_code.rs), +opens one component, and every entry names both the operation and the input: + +```rust +pub struct Interpreter; + +delegate_components! { + Interpreter { + open ComputerRefComponent; + + MathExprTypeProviderComponent: + UseType, + LispExprTypeProviderComponent: + UseType, + + @ComputerRefComponent.Eval.MathExpr: DispatchEval, + @ComputerRefComponent.Eval.Literal: EvalLiteral, + @ComputerRefComponent.Eval.Plus: EvalAdd, + @ComputerRefComponent.Eval.Times: EvalMultiply, + + @ComputerRefComponent.ToLisp.MathExpr: DispatchToLisp, + @ComputerRefComponent.ToLisp.Literal: LiteralToLisp, + @ComputerRefComponent.ToLisp.Plus: BinaryOpToLisp, + @ComputerRefComponent.ToLisp.Times: BinaryOpToLisp, + } +} +``` + +In `add_mult`, the first part of each key was the generic ` Code`, which matched any marker. +Here it is a concrete marker, `Eval` or `ToLisp`, the two empty structs the crate defines for its +operations. So `@ComputerRefComponent.Eval.Plus: EvalAdd` reads "to compute `Eval` on a +`Plus`, use `EvalAdd`", and each operator has one entry per operation. The table chooses +by two parameters at once, and the compiler resolves both while it type-checks the call. + +## The same providers, borrowed + +Evaluation runs through [`ComputerRef`](/docs/reference/components/handler/computer_ref) here, the +component that borrows its input, where `add_mult` evaluated by value. The evaluation providers +implement both components, so `EvalAdd` and the rest need no change: `EvalAdd` has a by-value impl +and a by-reference impl side by side, and this context uses the second. + +The wrappers for the whole enum fix their marker to match their keys. `DispatchEval` implements the +component only for `Eval`: + +```rust +#[cgp_impl(new DispatchEval)] +impl ComputerRef for Interpreter { + type Output = Value; + + fn compute_ref( + context: &Interpreter, + code: PhantomData, + expr: &MathExpr, + ) -> Self::Output { + ::compute_ref(context, code, expr) + } +} +``` + +`DispatchToLisp` is the same for `ToLisp`, with `LispExpr` as its output. Since the marker passes +through the dispatcher unchanged, every operand of an `Eval` computation is evaluated, and every +operand of a `ToLisp` computation is converted. + +## Try a change + +Remove the conversion entry for `Plus`, the line +`@ComputerRefComponent.ToLisp.Plus: BinaryOpToLisp`, and run +[`cargo cgp check`](/docs/cargo-cgp/check). The check names the missing entry, with both parts of +its key: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanComputeRef>` is not implemented for context `Interpreter` + = note: root cause: [CGP-E107] context `Interpreter` does not contain any delegate entry for `@ComputerRefComponent.ToLisp.Plus` +``` + +Evaluating a `Plus` still has its entry, so only conversion is broken. Two more errors point at the +`ToLisp` wrapper's call to the dispatcher, for the same reason. `cargo cgp check` leads with the +root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape +every class. + +## The pattern + +This context shows **dispatching on two parameters at once**: a wiring key that fixes both the +operation marker and the input type, so one component serves several operations and the table says, +entry by entry, which provider each operation uses on each input. It is how a context runs many +computations through one interface, which [Handlers](/docs/concepts/handlers) describes, and the key +syntax is documented with [`delegate_components!`](/docs/reference/macros/delegate_components). + +The cost is a longer table. Every operator has an entry per operation, so the table grows with +their product, and each context needs a wrapper per operation. Choosing the operation by which +method is called, as `add_mult` does, keeps the table shorter when there are only two. + +## Where to go next + +- [`add_mult_neg`](./add-mult-neg.md): the next example, the language extended with new operators. +- [Dispatch layers](../architecture/dispatch-layers.md): the two ways the contexts key their + dispatch, side by side. +- [Handlers](/docs/concepts/handlers): CGP's computation interfaces, and the `Code` marker they + share. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-neg.md b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md new file mode 100644 index 00000000..b529c790 --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md @@ -0,0 +1,179 @@ +--- +sidebar_label: 'add_mult_neg' +sidebar_position: 4 +description: 'The interpreter''s language extended with subtraction and negation in a new enum and context, reusing every existing CGP provider unchanged.' +--- + +# Extend the language without editing it + +This **context**, the type that stands for one interpreter and holds its choices, evaluates a larger +language, with subtraction and negation added to addition and multiplication, and no existing +provider is edited to do it. It is the last example in [`expression`](../index.md), an interpreter +from the [cgp-examples](../../index.md) repository, built with [CGP](/docs/). It is the pay-off of +the design the earlier examples set up: the language grows by adding types and providers next to the +old ones. + +:::tip + +### New to CGP? + +[`add_mult`](./add-mult.md) introduces the interpreter and its wiring, which this page extends. For +CGP itself, the [Hello World tutorial](/docs/tutorials/hello) introduces contexts and wiring, and +[Extensible variants](/docs/concepts/extensible-variants) explains how one provider can serve +several enums. + +::: + +## Run it + +From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): + +```sh +cargo test -p cgp-example-expression add_mult_neg:: +``` + +The context's test passes: + +```text +test contexts::add_mult_neg::test::test_add_mult_neg ... ok +``` + +It evaluates `2 + 3` to `5`, `2 * 3` to `6`, `2 - 3` to `-1`, and `-2 * (3 + 4)` to `-14`. + +## A new enum, from old parts and new ones + +The context's module, +[`add_mult_neg.rs`](https://github.com/contextgeneric/cgp-examples/blob/main/expression/src/contexts/add_mult_neg.rs), +defines the larger language as a new enum: + +```rust +pub type Value = i64; + +#[derive(Debug, CgpData)] +pub enum MathPlusExpr { + Plus(Plus), + Times(Times), + Literal(Literal), + Negate(Negate), + Minus(Minus), +} +``` + +`Plus`, `Times`, and `Literal` are the same operator structs the base language uses, here +instantiated at `MathPlusExpr` and with `i64` literals, since the language now has negative +numbers. `Negate` and `Minus` are two more operator structs. The base language's `MathExpr` is left +as it was; the new enum sits beside it. + +## The new operators get providers of their own + +Each new operator needs an evaluation provider. `EvalNegate`, from the crate's +`providers/eval/negate.rs`, negates its one operand: + +```rust +#[cgp_impl(new EvalNegate)] +#[uses(CanComputeRef)] +impl ComputerRef> +where + Output: Neg, +{ + type Output = Output; + + fn compute_ref( + &self, + code: PhantomData, + Negate(expr): &Negate, + ) -> Self::Output { + -self.compute_ref(code, expr) + } +} +``` + +`EvalSubtract` does the same for `Minus` with `-` between its two operands. Like every provider in +the crate, each asks the context to evaluate its operands and knows nothing about the enum they sit +in. They could be written in another crate from the one that defines the base language. + +## The context mixes old providers and new + +`InterpreterPlus` is a new context, with a table that wires the old providers for the old operators +and the new providers for the new ones: + +```rust +pub struct InterpreterPlus; + +delegate_components! { + InterpreterPlus { + open ComputerRefComponent; + + @ComputerRefComponent.Eval.MathPlusExpr: DispatchEval, + @ComputerRefComponent.Eval.Plus: EvalAdd, + @ComputerRefComponent.Eval.Times: EvalMultiply, + @ComputerRefComponent.Eval.Literal: EvalLiteral, + @ComputerRefComponent.Eval.Minus: EvalSubtract, + @ComputerRefComponent.Eval.Negate: EvalNegate, + } +} +``` + +`EvalAdd`, `EvalMultiply`, and `EvalLiteral` are the providers `add_mult` wires, unchanged, now at a +different enum and a different number type. The table is keyed on the `Eval` marker and the input, +as in [`add_mult_code`](./add-mult-code.md), and the context has its own `DispatchEval` wrapper for +`MathPlusExpr`, for the reason [`add_mult`](./add-mult.md#a-small-wrapper-takes-the-enum-apart) +gives. + +## Conversion is left unwired + +`InterpreterPlus` wires evaluation only. There is no `ToLisp` entry, and no abstract Lisp type, and +the context compiles and runs regardless: CGP checks wiring where it is used, so an operation that +nothing calls needs no providers. The context's `check_components!` block lists evaluation for all +six input types, and nothing for conversion. + +## Try a change + +Ask for conversion anyway. Add `ToLisp` to the module's `dsl` import, and add an entry to its check +block: + +```rust +(ToLisp, MathPlusExpr), +``` + +Run [`cargo cgp check`](/docs/cargo-cgp/check), and the check reports that conversion was never +wired: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanComputeRef` is not implemented for context `InterpreterPlus` + = note: root cause: [CGP-E107] context `InterpreterPlus` does not contain any delegate entry for `@ComputerRefComponent.ToLisp.MathPlusExpr` +``` + +Supporting it would be a second group of `ToLisp` entries beside the `Eval` ones, with a provider +for each new operator, an entry binding the context's Lisp type, and a `DispatchToLisp` wrapper, as +[`add_mult`](./add-mult.md) has. `cargo cgp check` leads with the root cause +for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. + +## The pattern + +This context shows **the expression problem solved**: a language extended with new variants while +every existing operation's providers stay as they were. The old operators' providers serve the new +enum because they never named an enum; the new operators get providers of their own; and a new +context wires the two together. Adding a new operation instead would be the same move in the other +direction, a new set of providers and a new group of entries. [Extensible +variants](/docs/concepts/extensible-variants) explains the representation that allows it. + +The cost is that the extension is a new language, not a change to the old one. `MathPlusExpr` is a +separate enum and `InterpreterPlus` a separate context, and code that handles `MathExpr` does not +accept `MathPlusExpr` until it is wired for it. The flexibility is in the providers, which are +reused, rather than in the enums, which stay ordinary closed Rust enums. + +## Where to go next + +- [How expression works](../architecture/index.md): the design the four examples share, on one + page. +- [Dispatch layers](../architecture/dispatch-layers.md): why each context, this one included, has + its own wrapper. +- [Extensible variants](/docs/concepts/extensible-variants): the CGP idea that lets one provider + serve several enums. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/expression/examples/add-mult.md b/docs/projects/cgp-examples/expression/examples/add-mult.md new file mode 100644 index 00000000..b292af21 --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/add-mult.md @@ -0,0 +1,294 @@ +--- +sidebar_label: 'add_mult' +sidebar_position: 1 +description: 'An arithmetic interpreter that evaluates and converts expressions with one CGP provider per operator, wired by a context, with no hand-written match.' +--- + +# Evaluate an expression without a `match` + +This context evaluates arithmetic expressions such as `2 * (3 + 4)` and converts them to Lisp, with +one provider per operator and no hand-written `match` over the language. It is the first example in +[`expression`](../index.md), an interpreter from the [cgp-examples](../../index.md) repository, +built with [CGP](/docs/). Each later example changes one thing about this one, so every piece it +introduces comes back. + +:::tip + +### New to CGP? + +The [Hello World tutorial](/docs/tutorials/hello) introduces contexts, providers, and wiring with a +smaller program. [Extensible variants](/docs/concepts/extensible-variants) explains how CGP takes an +enum apart for a provider, which is the idea this page puts to work. This page can be read without +either. + +::: + +## Run it + +From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): + +```sh +cargo test -p cgp-example-expression add_mult:: +``` + +The context's two tests pass: + +```text +test contexts::add_mult::test::test_add_mult ... ok +test contexts::add_mult::test::test_add_mult_to_lisp ... ok +``` + +The first evaluates `2 + 3`, `2 * 3`, and `2 * (3 + 4)` to `5`, `6`, and `14`. The second converts +the same three expressions to Lisp, so `2 * (3 + 4)` becomes the tree for `(* 2 (+ 3 4))`. + +## The language is an enum of operator structs + +The context's module, [`add_mult.rs`](https://github.com/contextgeneric/cgp-examples/blob/main/expression/src/contexts/add_mult.rs), +defines the language and the Lisp output as two enums: + +```rust +pub type Value = u64; + +#[derive(Debug, CgpData)] +pub enum MathExpr { + Plus(Plus), + Times(Times), + Literal(Literal), +} + +#[derive(Eq, PartialEq, Debug, CgpData)] +pub enum LispExpr { + List(List), + Literal(Literal), + Ident(Ident), +} +``` + +Each variant wraps an operator struct defined elsewhere in the crate, such as `Plus` with its +`left` and `right` fields, instantiated here at `MathExpr` itself. So the operator structs, and the +providers written for them, know nothing about this particular language. +[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) exposes each enum's variants to +generic code by name, which is what lets CGP take the enum apart without a `match`. + +## One provider per operator + +Evaluation is written as one provider per operator. This is the one for `Plus`, from the crate's +`providers/eval/add.rs`: + +```rust +#[cgp_impl(new EvalAdd)] +#[uses(CanCompute)] +impl Computer> +where + Output: Add, +{ + type Output = Output; + + fn compute( + &self, + code: PhantomData, + Plus { left, right }: Plus, + ) -> Self::Output { + let output_a = self.compute(code, *left); + let output_b = self.compute(code, *right); + + output_a + output_b + } +} +``` + +`EvalAdd` implements [`Computer`](/docs/reference/components/handler/computer), CGP's interface for +a computation that takes an input and returns an output, keyed by a marker type called the `Code`. +Inside the impl, `self` is the **context**, the type that stands for this interpreter and holds its +choices. [`#[uses]`](/docs/reference/attributes/uses) declares what `EvalAdd` needs from it: the +ability to evaluate each operand. So `EvalAdd` adds two evaluated operands without knowing what kind +of expression they are, or which enum `MathExpr` is. `EvalMultiply` is the same with `*`, and +`EvalLiteral` returns a literal's value. + +## The context wires each operator to its provider + +`Interpreter` is the context. It has no fields, because every choice it makes is in its wiring: + +```rust +pub struct Interpreter; + +delegate_components! { + Interpreter { + open { ComputerComponent, ComputerRefComponent }; + + MathExprTypeProviderComponent: + UseType, + LispExprTypeProviderComponent: + UseType, + + @ComputerComponent. Code.MathExpr: DispatchEval, + @ComputerComponent. Code.Plus: EvalAdd, + @ComputerComponent. Code.Times: EvalMultiply, + @ComputerComponent. Code.Literal: EvalLiteral, + + @ComputerRefComponent. Code.MathExpr: DispatchToLisp, + @ComputerRefComponent. Code.Literal: LiteralToLisp, + @ComputerRefComponent. Code.Plus: PlusToLisp, + @ComputerRefComponent. Code.Times: TimesToLisp, + } +} +``` + +The `open` statement lets the table choose a provider by the computation's parameters, and each `@` +entry makes one choice. A key has two parts after the component: the `Code`, here the generic +` Code` that matches any marker, and then the input type. So +`@ComputerComponent. Code.Plus: EvalAdd` reads "to compute anything on a +`Plus`, use `EvalAdd`". +[`delegate_components!`](/docs/reference/macros/delegate_components) documents the syntax. + +The two operations use two components. Evaluation goes through `ComputerComponent`, which takes its +input by value, and conversion goes through +[`ComputerRefComponent`](/docs/reference/components/handler/computer_ref), which borrows it. Calling +`compute` evaluates and calling `compute_ref` converts, whatever `Code` the caller passes. The two +[`UseType`](/docs/reference/providers/use_type) entries set the context's two [abstract +types](/docs/concepts/abstract-types), type names the context fills in so that providers can use +them without knowing the concrete type. The conversion providers below read the Lisp one, and the +[next example](./add-mult-binary-op.md)'s provider reads the other. + +## A small wrapper takes the enum apart + +The `MathExpr` entries go to a provider the module writes for itself: + +```rust +#[cgp_impl(new DispatchEval)] +impl Computer for Interpreter { + type Output = Value; + + fn compute(context: &Interpreter, code: PhantomData, expr: MathExpr) -> Self::Output { + ::compute(context, code, expr) + } +} +``` + +[`MatchWithValueHandlers`](/docs/reference/providers/dispatch/match_with_value_handlers) is CGP's +generic dispatcher. It finds which variant the enum holds and hands the operator struct inside back +to the context, whose table sends it to `EvalAdd`, `EvalMultiply`, or `EvalLiteral`. That replaces +the `match` a plain interpreter would write, and the compiler still checks that every variant has a +provider. + +The wrapper is there because wiring `MatchWithValueHandlers` as the `MathExpr` entry directly sends +the compiler round a loop it cannot finish: evaluating a `MathExpr` needs evaluating its operands, +which are `MathExpr` again. A wrapper written for one concrete context breaks the loop. [Dispatch +layers](../architecture/dispatch-layers.md) explains why, and every context in the crate has its +own. + +## Conversion builds a type it does not name + +The conversion providers produce a `LispExpr`, but they are written without naming the enum. This is +the one for `Plus`, from `providers/to_lisp/add.rs`: + +```rust +#[derive(CgpData)] +enum LispSubExpr { + List(List), + Ident(Ident), +} + +#[cgp_impl(new PlusToLisp)] +#[use_type(HasLispExprType.LispExpr)] +#[uses(CanComputeRef)] +impl ComputerRef> +where + LispSubExpr: CanUpcast, +{ + type Output = LispExpr; + + fn compute_ref( + &self, + code: PhantomData, + Plus { left, right }: &Plus, + ) -> Self::Output { + let expr_a = self.compute_ref(code, left); + let expr_b = self.compute_ref(code, right); + let ident = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData); + + LispSubExpr::List(List(vec![ident.into(), expr_a.into(), expr_b.into()])) + .upcast(PhantomData) + } +} +``` + +[`#[use_type]`](/docs/reference/attributes/use_type) brings in `LispExpr` as an abstract type the +context defines, which the `UseType` entry above sets. The provider builds only the two +variants it needs, in a small local enum, and [`upcast`](/docs/reference/traits/casting/can_upcast) +turns that into the full `LispExpr`, which works because every variant of `LispSubExpr` is also a +variant of `LispExpr`. So `PlusToLisp` serves any Lisp type that has a list and an identifier. + +## The checks cover every input + +The module asserts its wiring with +[`check_components!`](/docs/reference/macros/check_components), listing each operation and input +pair: + +```rust +check_components! { + Interpreter { + ComputerComponent: [ + (Eval, MathExpr), + (Eval, Literal), + (Eval, Plus), + (Eval, Times), + ], + ComputerRefComponent: [ + (ToLisp, MathExpr), + (ToLisp, Literal), + (ToLisp, Plus), + (ToLisp, Times), + ] + } +} +``` + +`Eval` and `ToLisp` are empty marker structs the crate defines as its codes. Listing each operator, +not only `MathExpr`, is what makes a missing operator entry fail at the check, as the change below +shows. + +## Try a change + +Remove the evaluation entry for `Times`, the line +`@ComputerComponent. Code.Times: EvalMultiply`, and run +[`cargo cgp check`](/docs/cargo-cgp/check). The check names the missing entry: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanCompute>` is not implemented for context `Interpreter` + = note: root cause: [CGP-E107] context `Interpreter` does not contain any delegate entry for `@ComputerComponent.Eval.Times` +``` + +A second, longer error points at the wrapper's call to `MatchWithValueHandlers`, because the +dispatcher cannot find a provider for the `Times` variant either. The first error is the one to +read. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a +v0.1.0-alpha that does not yet reshape every class. Put the line back, and the check passes. + +## The pattern + +This context shows the **extensible visitor pattern**: an operation over an enum written as one +provider per variant, with a generic dispatcher in place of the `match`. Each provider handles one +operator and asks the context about the rest, so it serves every language that contains that +operator, and a new operator is a new provider and a new entry rather than an edit to every +operation. [Extensible variants](/docs/concepts/extensible-variants) explains the representation +that makes this possible, and [Dispatching](/docs/concepts/dispatching) explains the dispatchers. + +The cost is the machinery. Where the plain interpreter has an enum and a `match`, this one has +operator structs, a provider per operator per operation, a wiring table, and a wrapper per context, +and a mistake is a compile error with a long chain behind it. For a language that will not grow, +the `match` is simpler and better. + +## Where to go next + +- [`add_mult_binary_op`](./add-mult-binary-op.md): the next example, one provider for both binary + operators. +- [Dispatch layers](../architecture/dispatch-layers.md): the two ways the contexts key their + dispatch, and why each needs its wrapper. +- [Extensible variants](/docs/concepts/extensible-variants): the CGP idea behind handling one + variant of any enum. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/expression/examples/index.md b/docs/projects/cgp-examples/expression/examples/index.md new file mode 100644 index 00000000..0fdbf1fa --- /dev/null +++ b/docs/projects/cgp-examples/expression/examples/index.md @@ -0,0 +1,57 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'The four expression contexts as short tutorials on the extensible visitor pattern: per-operator providers, a generic one, two-key dispatch, and extension.' +--- + +# expression examples + +These pages walk through the four **contexts**, the types that each stand for one interpreter and +hold its choices, in the `expression` crate of the [cgp-examples +repository](https://github.com/contextgeneric/cgp-examples), one context per page. +[`expression`](../index.md) is an arithmetic interpreter built with [CGP](/docs/), in which each +operator is its own type and each operation is one provider per operator. Each page runs its +context, explains how the wiring produces what it computes, and names the CGP pattern it shows. + +The pages are in the order they teach, and each later page changes one thing about the one before. +Start with [`add_mult`](./add-mult.md), which introduces every piece the others reuse. + +:::tip + +### New to CGP? + +These pages explain the interpreter without deriving CGP from first principles. The [Hello World +tutorial](/docs/tutorials/hello) introduces contexts, providers, and wiring in a few minutes, and +[Extensible variants](/docs/concepts/extensible-variants) explains how CGP takes an enum apart for a +provider. Neither is required reading; each page links what it relies on. + +::: + +## Running an example + +Clone the repository and run the tests from its root with `cargo test -p cgp-example-expression`. +Two contexts have tests of their own; the other two pages give a test to add and the output it +prints. + +## The examples + +- [`add_mult`](./add-mult.md) — evaluation and conversion to Lisp, with one provider per operator + and a context that wires each operator to its provider. +- [`add_mult_binary_op`](./add-mult-binary-op.md) — one generic provider replacing the two + per-operator conversion providers. +- [`add_mult_code`](./add-mult-code.md) — both operations in one component, chosen by an operation + marker and the input type together. +- [`add_mult_neg`](./add-mult-neg.md) — the language extended with subtraction and negation, with + no existing provider edited. + +## Where to go next + +- [How expression works](../architecture/index.md): the design behind every context, on one page. +- [Dispatching](/docs/concepts/dispatching): the CGP idea behind handling each variant with its own + provider. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/expression/index.md b/docs/projects/cgp-examples/expression/index.md new file mode 100644 index 00000000..b327efcd --- /dev/null +++ b/docs/projects/cgp-examples/expression/index.md @@ -0,0 +1,117 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'A modular arithmetic interpreter built with CGP: each operator is its own type, each operation one provider per operator, and new operators need no edits.' +--- + +# expression + +`expression` is a small arithmetic interpreter in which each operator is its own type, and each +operation over the language is a set of providers, one per operator. It is one of the demonstration +crates in [cgp-examples](../index.md), built with [CGP](/docs/), a language extension for Rust with +pluggable trait implementations at compile-time. The crate shows the **extensible visitor pattern**: +new operators and new operations can be added without editing the code that handles the old ones. + +## The starting point: an enum and a `match` + +The crate keeps the ordinary Rust version of the interpreter as the thing it improves on. It is one +enum and one `match` per operation: + +```rust +pub enum Expr { + Plus(Box, Box), + Times(Box, Box), + Literal(u64), +} + +pub fn eval(expr: Expr) -> u64 { + match expr { + Expr::Plus(a, b) => eval(*a) + eval(*b), + Expr::Times(a, b) => eval(*a) * eval(*b), + Expr::Literal(value) => value, + } +} +``` + +This is the right design for a language that never changes. Adding an operation is easy, a new +function with its own `match`, but adding an operator means editing the enum and every `match` over +it, and a crate that does not own the enum cannot add one at all. Keeping both kinds of addition +open at once is the expression problem, and it is what the rest of the crate works around. + +## What the crate does instead + +Each operator becomes a struct of its own, generic over the expression type it contains, so one +`Plus` serves every language that has addition: + +```rust +#[derive(Debug, Eq, PartialEq, HasField)] +pub struct Plus { + pub left: Box, + pub right: Box, +} +``` + +A language is then an ordinary enum whose variants wrap those structs. Each operation is written as +one provider per operator, such as `EvalAdd` for evaluating a `Plus`, which recurses into its +operands without knowing what language they belong to. A **context**, a type that stands for one +interpreter and holds its choices, wires each operator to its provider, and CGP takes the enum apart +for it, with no hand-written `match`. The [architecture](./architecture/index.md) explains the +design in full. + +The crate runs two operations over the language: **evaluation**, which turns an expression into a +number, and **conversion to Lisp**, which turns `2 * (3 + 4)` into the S-expression +`(* 2 (+ 3 4))`. + +## The examples + +The crate holds four contexts, each in its own module and each a different wiring of the same +providers. Each has a page, in the order they teach: + +- [`add_mult`](./examples/add-mult.md) — evaluation and conversion to Lisp, one provider per + operator, dispatched without a `match`. +- [`add_mult_binary_op`](./examples/add-mult-binary-op.md) — one generic provider converting both + binary operators, with the operator's symbol as a type parameter. +- [`add_mult_code`](./examples/add-mult-code.md) — both operations in one component, chosen by an + operation marker and the input type together. +- [`add_mult_neg`](./examples/add-mult-neg.md) — the language extended with subtraction and + negation, reusing every existing provider unchanged. + +## Status + +`expression` is a demonstration, not a library: it is unpublished, and nobody adds it as a +dependency. It has no binary. Its three unit tests are the way to run it, and each example page +shows how to run its context, including the two that have no test of their own. The crate uses +current CGP idioms throughout, so its code is safe to copy for the patterns it shows. + +## Running it + +Clone the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples) and run the tests +from its root: + +```sh +cargo test -p cgp-example-expression +``` + +The workspace builds on stable Rust 1.90 or later, and needs nothing outside the build. The three +tests pass: + +```text +test contexts::add_mult::test::test_add_mult_to_lisp ... ok +test contexts::add_mult_neg::test::test_add_mult_neg ... ok +test contexts::add_mult::test::test_add_mult ... ok +``` + +## Where to go next + +- [`add_mult`](./examples/add-mult.md): the first example, and the one to read first. +- [How expression works](./architecture/index.md): the design every context shares. +- [Extensible variants](/docs/concepts/extensible-variants): the CGP idea that lets a provider + handle one variant of any enum. +- [Extensible data types, part 2](/blog/extensible-datatypes-part-2): the post that developed this + interpreter. Its code predates the current design. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/index.md b/docs/projects/cgp-examples/index.md new file mode 100644 index 00000000..415c722a --- /dev/null +++ b/docs/projects/cgp-examples/index.md @@ -0,0 +1,58 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'Five small demonstration crates built with CGP: an extensible interpreter, an application builder, a web service, a wiring study, and a greeting.' +--- + +# cgp-examples + +`cgp-examples` is a repository of five small programs built with [CGP](/docs/), a language extension +for Rust with pluggable trait implementations at compile-time. Each crate shows one area of CGP +working in code, and between them they cover a wide range of CGP's design patterns. They share a +workspace and nothing else, so each has a section of its own. + +The crates are demonstrations, not libraries. None is published, and nobody adds them as a +dependency: the way to use one is to clone the repository and run it, or read it. Their code uses +current CGP idioms throughout, so it is safe to copy for the patterns it shows. + +## The crates + +| Crate | What it shows | How it runs | +|---|---|---| +| [`expression`](./expression/index.md) | an arithmetic interpreter that gains operators and operations without editing old code: the extensible visitor pattern | three unit tests, and a test to add for each of the other contexts | +| [`web-app`](./web-app/index.md) | one social-media backend wired four ways, from one trait per domain to namespace defaults | a check of its wiring; every provider body is `todo!()` | +| `builder` | an application assembled from per-subsystem builders that never name the struct they build: the extensible builder pattern | compile-time checks of its builders | +| `transfer` | a balance-and-transfer HTTP service whose every domain type and operation is a component, organized with a namespace | a server binary | +| `greet` | a greeting written as a CGP function, as a component with two providers, and over an abstract type | three binaries | + +The pages for `builder`, `transfer`, and `greet` are still being written. Until they are, each crate +is in its own directory of the repository, and `transfer` has a README of its own. + +## Where to start + +- **To see the extensible visitor pattern**, start with [`expression`](./expression/index.md), whose + four examples build on each other. +- **To see how wiring changes as an application grows**, read the four stages of + [`web-app`](./web-app/index.md) in order. +- **To learn CGP from the beginning**, start with the [Hello World tutorial](/docs/tutorials/hello) + instead; these pages assume it rather than teach it. + +## Running the crates + +Clone the [repository](https://github.com/contextgeneric/cgp-examples) and work from its root. The +workspace builds on stable Rust 1.90 or later, with the 2024 edition, and each crate is a package of +its own, such as `cgp-example-expression`, so `cargo test -p cgp-example-expression` runs one +crate's tests. Each crate's pages give the command for its programs. + +## Where to go next + +- [`expression`](./expression/index.md): the extensible visitor pattern, in four contexts. +- [`web-app`](./web-app/index.md): one application's wiring at four scales. +- [Projects](../index.md): the other projects on this site, and a table from each CGP pattern to an + example that shows it. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/web-app/_category_.json b/docs/projects/cgp-examples/web-app/_category_.json new file mode 100644 index 00000000..d2151592 --- /dev/null +++ b/docs/projects/cgp-examples/web-app/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "web-app", + "position": 2, + "link": { + "type": "doc", + "id": "projects/cgp-examples/web-app/index" + } +} diff --git a/docs/projects/cgp-examples/web-app/examples/_category_.json b/docs/projects/cgp-examples/web-app/examples/_category_.json new file mode 100644 index 00000000..42880050 --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Stages", + "position": 1, + "collapsed": false +} diff --git a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md new file mode 100644 index 00000000..e95f0a81 --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md @@ -0,0 +1,175 @@ +--- +sidebar_label: 'coarse_grained' +sidebar_position: 1 +description: 'A CGP application wired with one manager trait per domain, and the cost it shows: a dependency one method needs is carried by every method of the manager.' +--- + +# Wire an application with one trait per domain + +This stage wires a small social-media backend with one trait per domain, a user manager and a post +manager, and shows what that costs as soon as one method needs something the others do not. It is +the first stage of [`web-app`](../index.md), a wiring study from the [cgp-examples](../../index.md) +repository, built with [CGP](/docs/). Nothing in the crate runs; every provider body is `todo!()`, +and the compiler's check of the wiring is what this page runs. + +:::tip + +### New to CGP? + +The [Hello World tutorial](/docs/tutorials/hello) introduces components, providers, and wiring with +a smaller program. [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) +explains what a component is, which is what this stage sizes. This page can be read without either. + +::: + +## Check it + +From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): + +```sh +cargo check -p cgp-example-web-app +``` + +The check passes. For this stage, that means `ProductionApp` has a working provider for each of its +four components, including everything those providers need. + +## One component per domain + +The module, +[`coarse_grained.rs`](https://github.com/contextgeneric/cgp-examples/blob/main/web-app/src/coarse_grained.rs), +defines a manager trait for each domain, and a small trait for each content filter: + +```rust +#[cgp_component(UserManager)] +pub trait CanManageUser { + fn create_user(&self, username: &str, email: &Email) -> Result; + + fn get_user(&self, user_id: &UserId) -> Result; + + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; +} + +#[cgp_component(UsernameCensor)] +pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; +} +``` + +[`#[cgp_component]`](/docs/reference/macros/cgp_component) turns each trait into a component: the +trait callers use, a trait providers implement, and a key that wiring names. `CanManagePost` has +`create_post`, `get_post`, `update_post`, and `delete_post`, and `CanDetectSpamMessage` has +`message_is_spam`. This is the shape most applications start from, since it follows the way the +domain is described. + +## The manager's provider needs the censor + +The user manager's provider stores users in Postgres, and checks new usernames with the censor +before creating them: + +```rust +#[cgp_impl(new PostgresUserManager)] +#[uses(CanCensorUsername)] +impl UserManager { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + todo!() + } + + fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { + todo!() + } + + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() + } +} +``` + +[`#[uses]`](/docs/reference/attributes/uses) declares what the provider needs from the context, here +the censor. [`#[implicit]`](/docs/reference/attributes/implicit) marks the `database` argument as +filled from the context's field of that name, so callers never pass it. Only `create_user` calls the +censor, but `#[uses]` is on the whole impl, so the whole provider depends on it. +`PostgresPostManager` has the same shape, with the spam detector. + +## The context wires and checks in one table + +`ProductionApp` is the context, a type that stands for the application and holds its choices. It +holds the database handle, and wires its four components: + +```rust +#[derive(HasField)] +pub struct ProductionApp { + pub database: PostgresDb, +} + +delegate_and_check_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: DummyUserCensor, + SpamMessageDetectorComponent: DummySpamMessageDetector, + } +} +``` + +[`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) wires each +entry and checks it in the same step, which suits a table of plain entries like this one. +[`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) exposes the `database` field to +the providers that read it. The two filters are wired to placeholder providers here; the next stage +adds real ones. + +## Try a change + +Remove the censor's entry, the line `UsernameCensorComponent: DummyUserCensor,`, and run +[`cargo cgp check`](/docs/cargo-cgp/check). The whole user manager fails: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanManageUser` is not implemented for context `ProductionApp` + = note: root cause: [CGP-E107] context `ProductionApp` does not contain any delegate entry for `UsernameCensorComponent` +``` + +The context has lost `get_user` and `update_user_data` as well as `create_user`, though neither +calls the censor, because the three methods share one provider and one set of requirements. Compare +the same change in the [next stage](./fine-grained.md#try-a-change). `cargo cgp check` leads with +the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet +reshape every class. + +## The pattern + +This stage shows **coarse-grained components**: one component per domain, each implemented by one +provider. The shape is easy to read and short to wire, four entries for the whole application. Its +cost is that a component carries the union of its methods' requirements. A context that wants to +read users, such as a report generator with no censor, cannot use `PostgresUserManager` at all, and +swapping how one method works means writing a whole new manager. + +Coarse components are the right size when a domain's methods are always provided together. When +they start to need different things, the next stage's split is the fix. [Consumer and provider +traits](/docs/concepts/consumer-and-provider-traits) explains what a component is, and +[Impl-side dependencies](/docs/concepts/impl-side-dependencies) explains how `#[uses]` attaches a +requirement to a provider. + +## Where to go next + +- [`fine_grained`](./fine-grained.md): the next stage, one component per operation. +- [web-app overview](../index.md): the four stages side by side. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): how a provider's requirements are + declared and resolved. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/web-app/examples/default-impls.md b/docs/projects/cgp-examples/web-app/examples/default-impls.md new file mode 100644 index 00000000..70652897 --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/default-impls.md @@ -0,0 +1,176 @@ +--- +sidebar_label: 'default_impls' +sidebar_position: 4 +description: 'A CGP namespace that supplies seven of an application''s nine providers as defaults, so the context wires only its filters, and why a default is final.' +--- + +# Supply an application's defaults from a namespace + +This stage moves seven of the backend's nine providers into a namespace as defaults, so the +application's context joins the namespace and wires only what varies: its content filters. It is the +last stage of [`web-app`](../index.md), a wiring study from the [cgp-examples](../../index.md) +repository, built with [CGP](/docs/). Nothing in the crate runs; every provider body is `todo!()`, +and the compiler's check of the wiring is what this page runs. + +:::tip + +### New to CGP? + +[`namespace`](./namespaces.md) introduces the paths this stage builds on. For CGP itself, the [Hello +World tutorial](/docs/tutorials/hello) introduces wiring, and +[Namespaces](/docs/concepts/namespaces) explains inheriting a namespace and binding its paths. + +::: + +## Check it + +From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): + +```sh +cargo check -p cgp-example-web-app +``` + +The check passes. For this stage, that means `ProductionApp`, wired with one entry of its own, +satisfies all nine components. + +## A namespace of defaults + +The module, +[`default_impls.rs`](https://github.com/contextgeneric/cgp-examples/blob/main/web-app/src/default_impls.rs), +keeps the previous stage's components and paths, and declares a namespace of its own that inherits +`DefaultNamespace`: + +```rust +cgp_namespace! { + new DefaultAppComponents: DefaultNamespace +} +``` + +[`cgp_namespace!`](/docs/reference/macros/cgp_namespace) declares `DefaultAppComponents`, and the +`: DefaultNamespace` makes it a child that inherits every path the components registered. So far it +routes lookups and binds nothing. The rest of the module binds providers at its paths, in two ways. + +## Defaults registered on the providers + +Five providers register themselves as the namespace's default for their component, with +[`#[default_impl]`](/docs/reference/attributes/default_impl): + +```rust +#[cgp_impl(new GetUserWithPostgres)] +#[default_impl(@app.core.user.UserGetterComponent in DefaultAppComponents)] +impl UserGetter { + fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { + todo!() + } +} +``` + +The attribute names the full path, the component's prefix followed by its name, and the namespace to +bind it in. `UpdateUserWithPostgres`, `GetPostWithPostgres`, `UpdatePostWithPostgres`, and +`DeletePostWithPostgres` do the same for their components. + +## Defaults written in a namespace block + +The two creators cannot register this way, because their default is not a provider on its own but a +filter wrapped around one. So a second block binds them in the namespace directly: + +```rust +cgp_namespace! { + DefaultAppComponents { + @app.core.user.UserCreatorComponent: + FilterCensoredUsername, + + @app.core.post.PostCreatorComponent: + FilterSpamMessage, + } +} +``` + +With these, the namespace binds every path under `@app.core` and nothing under `@app.extra`. The +content filters are left for each context to choose. + +## The context wires what is left + +`ProductionApp` joins the namespace and wires the content filters, the one group the namespace +leaves open: + +```rust +delegate_components! { + new ContentFilterComponents { + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } +} + +delegate_components! { + ProductionApp { + namespace DefaultAppComponents; + + @app.extra.content_filter: ContentFilterComponents, + } +} +``` + +`ProductionApp` is a type that stands for the application, with the database as its one field, and +this is the whole of its wiring. A check of all nine components passes on it. The filter entry is +still needed: the default creators wrap their filters, so without it the creators fail their checks +for want of a censor and a spam detector. + +## Try a change + +Try to replace one default. Add a provider of your own for the user getter at the end of the module: + +```rust +#[cgp_impl(new GetCachedUser)] +impl UserGetter { + fn get_user(&self, user_id: &UserId) -> Result { + todo!() + } +} +``` + +and wire it in `ProductionApp`, beside the namespace line: + +```rust +@app.core.user.UserGetterComponent: GetCachedUser, +``` + +Run [`cargo cgp check`](/docs/cargo-cgp/check), and the entry is rejected: + +```text +error[E0119]: [CGP-E005] `ProductionApp` cannot wire `@app.core.user.UserGetterComponent.*` that is already set through `DefaultAppComponents` +``` + +A default a namespace binds is final. The context's entry would be a second answer to the same +lookup, and Rust rejects the two as conflicting implementations, which is `E0119` underneath the +tool's message. A context that needs a different getter joins a different namespace, one that does +not bind the getter. `cargo cgp check` leads with the root cause for the classes it recognizes, and +the tool is a v0.1.0-alpha that does not yet reshape every class. + +## The pattern + +This stage shows **defaults supplied by a namespace**: a library, or a part of an application, +publishes a namespace that binds the choices every context shares and leaves open the ones each +context makes, so a context is only its differences. [Namespaces](/docs/concepts/namespaces) +explains binding shared choices and leaving varying paths open. + +The cost is the finality the change above shows. A context that joins the namespace takes every +default it binds, with no way to replace one, so the namespace has to leave open everything a +context might want to vary. Deciding which choices are shared is a design decision made once, for +every context that joins; where it is wrong, the fix is a different namespace, not a local entry. + +## Where to go next + +- [web-app overview](../index.md): the four stages side by side, from one trait per domain to here. +- [`cgp_namespace!`](/docs/reference/macros/cgp_namespace): the macro, including inheritance and + bound entries. +- [Namespaces](/docs/concepts/namespaces): the CGP idea behind shared defaults, and why a bound + entry cannot be overridden. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/web-app/examples/fine-grained.md b/docs/projects/cgp-examples/web-app/examples/fine-grained.md new file mode 100644 index 00000000..7d8adb5c --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/fine-grained.md @@ -0,0 +1,184 @@ +--- +sidebar_label: 'fine_grained' +sidebar_position: 2 +description: 'A CGP application split into one component per operation, with content checks as wrapper providers and the providers grouped into bundles.' +--- + +# Split a manager into one component per operation + +This stage splits the backend's two managers into one component per operation, moves the content +checks into providers that wrap another provider, and groups the result into three bundles. It is +the second stage of [`web-app`](../index.md), a wiring study from the [cgp-examples](../../index.md) +repository, built with [CGP](/docs/). Nothing in the crate runs; every provider body is `todo!()`, +and the compiler's check of the wiring is what this page runs. + +:::tip + +### New to CGP? + +[`coarse_grained`](./coarse-grained.md) is the stage this one splits. For CGP itself, the [Hello +World tutorial](/docs/tutorials/hello) introduces providers and wiring, [Higher-order +providers](/docs/concepts/higher-order-providers) explains the wrappers, and [Aggregate +providers](/docs/concepts/aggregate-providers) explains the bundles. + +::: + +## Check it + +From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): + +```sh +cargo check -p cgp-example-web-app +``` + +The check passes. For this stage, that means `ProductionApp` satisfies all nine of its components. + +## One component per operation + +The module, +[`fine_grained.rs`](https://github.com/contextgeneric/cgp-examples/blob/main/web-app/src/fine_grained.rs), +gives each operation a component of its own, with the one method the manager had: + +```rust +#[cgp_component(UserCreator)] +pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; +} + +#[cgp_component(UserGetter)] +pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; +} +``` + +The users get `UserCreator`, `UserGetter`, and `UserUpdater`, and the posts get `PostCreator`, +`PostGetter`, `PostUpdater`, and `PostDeleter`, with the same two filters as before: nine components +in all. Each can now have its own provider, with its own requirements. + +## The content check becomes a wrapper + +The username check no longer lives inside the Postgres code. It is a provider of its own, which +rejects a censored name and otherwise passes the call to another creator, named as a type parameter: + +```rust +#[cgp_impl(new FilterCensoredUsername)] +#[uses(CanCensorUsername)] +#[use_provider(InnerCreator: UserCreator)] +impl UserCreator { + fn create_user(&self, username: &str, email: &Email) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + InnerCreator::create_user(self, username, email) + } +} +``` + +[`#[use_provider]`](/docs/reference/attributes/use_provider) states that `InnerCreator` must itself +be a `UserCreator` provider, and the wrapper calls it directly. So the Postgres creator, +`CreateUserWithPostgres`, checks nothing, and the check can wrap any creator, a Postgres one or any +other. `FilterSpamMessage` does the same for posts. The other Postgres providers, +`GetUserWithPostgres` and the rest, each implement one operation and read only the database. + +## Bundles group the providers + +Three bundles, each a named wiring table, group the providers by domain: + +```rust +delegate_components! { + new PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + } +} +``` + +The `new` keyword declares `PostgresUserComponents` as a type, and the entries are its wiring. The +creator is wired as the wrapper around the Postgres creator, which is where the two meet. +`PostgresPostComponents` does the same for the four post operations, and +`AiContentFilterComponents` wires the two filters to AI-backed providers. + +## The context forwards to the bundles + +`ProductionApp` is the **context**, a type that stands for the application and holds its choices, +and it forwards each component to the bundle that holds it: + +```rust +delegate_components! { + ProductionApp { + [ + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + ]: + PostgresUserComponents, + [ + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + ]: + PostgresPostComponents, + [ + UsernameCensorComponent, + SpamMessageDetectorComponent, + ]: + AiContentFilterComponents, + } +} +``` + +A bracketed list gives several keys one destination, and a bundle is a valid destination because it +is itself a wiring table: a lookup for `UserGetterComponent` goes to `PostgresUserComponents`, which +answers with `GetUserWithPostgres`. CGP calls a table used this way an [aggregate +provider](/docs/concepts/aggregate-providers). A separate +[`check_components!`](/docs/reference/macros/check_components) block lists all nine components on +`ProductionApp`, and a check of a component covers everything its provider needs, down through the +bundle. + +## Try a change + +Remove `UsernameCensorComponent` from the last list, so the censor has no entry, and run +[`cargo cgp check`](/docs/cargo-cgp/check). This time only the operation that uses the censor fails: + +```text +error[E0277]: [CGP-E001] the consumer traits `CanCreateUser` and `CanCensorUsername` are not implemented for context `ProductionApp` + = note: root cause: [CGP-E107] context `ProductionApp` does not contain any delegate entry for `UsernameCensorComponent` +``` + +Getting and updating users still check, because their providers need only the database. In the +[coarse stage](./coarse-grained.md#try-a-change) the same change took the whole user manager with +it. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a +v0.1.0-alpha that does not yet reshape every class. + +## The pattern + +This stage shows three patterns at once. **Fine-grained components** give each operation its own +provider and its own requirements, so a context can use one operation without paying for the +others. **Higher-order providers** move a check out of a provider into a wrapper that takes the +provider as a parameter, so the check composes with any implementation; see [Higher-order +providers](/docs/concepts/higher-order-providers). And **aggregate providers** group the wiring into +bundles that other contexts can reuse whole; see [Aggregate +providers](/docs/concepts/aggregate-providers). + +The cost is that the context still names every component. The bundles shortened the right-hand +side of the table, but the nine keys are all still listed, and every new operation is a new key in +every context. The [next stage](./namespaces.md) removes that. + +## Where to go next + +- [`namespace`](./namespaces.md): the next stage, the same components grouped under paths. +- [web-app overview](../index.md): the four stages side by side. +- [Higher-order providers](/docs/concepts/higher-order-providers): the CGP idea behind the filter + wrappers. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/web-app/examples/namespaces.md b/docs/projects/cgp-examples/web-app/examples/namespaces.md new file mode 100644 index 00000000..c599fd4e --- /dev/null +++ b/docs/projects/cgp-examples/web-app/examples/namespaces.md @@ -0,0 +1,167 @@ +--- +sidebar_label: 'namespace' +sidebar_position: 3 +description: 'A CGP application whose components sit under paths in a namespace, so a production and a test context each wire it in two lines and differ in one.' +--- + +# Group an application's wiring under paths + +This stage places the backend's nine components under paths, so that a context wires the whole +application in two lines, and a test context differs from production in one. It is the third stage +of [`web-app`](../index.md), a wiring study from the [cgp-examples](../../index.md) repository, +built with [CGP](/docs/). Nothing in the crate runs; every provider body is `todo!()`, and the +compiler's check of the wiring is what this page runs. + +:::tip + +### New to CGP? + +[`fine_grained`](./fine-grained.md) introduces the nine components and the bundles this stage +reuses. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) introduces wiring, and +[Namespaces](/docs/concepts/namespaces) explains the paths and lookups this stage relies on. + +::: + +## Check it + +From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): + +```sh +cargo check -p cgp-example-web-app +``` + +The check passes. For this stage, that means both `ProductionApp` and `TestApp` satisfy all nine +components. + +## Each component gets a path + +The module, +[`namespace.rs`](https://github.com/contextgeneric/cgp-examples/blob/main/web-app/src/namespace.rs), +declares the same nine components as the previous stage, each with a +[`#[prefix]`](/docs/reference/attributes/prefix) that registers it under a path: + +```rust +#[cgp_component(UserCreator)] +#[prefix(@app.core.user in DefaultNamespace)] +pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; +} +``` + +`DefaultNamespace` is the namespace CGP provides for components to register in, and a +[namespace](/docs/concepts/namespaces) is a wiring table that turns a lookup for a component into a +lookup for a path. The nine components fill three paths under two parents: + +| Path | Components | +|---|---| +| `@app.core.user` | `UserCreator`, `UserGetter`, `UserUpdater` | +| `@app.core.post` | `PostCreator`, `PostGetter`, `PostUpdater`, `PostDeleter` | +| `@app.extra.content_filter` | `UsernameCensor`, `SpamMessageDetector` | + +So a context that joins `DefaultNamespace` and is asked for `UserGetterComponent` looks for an entry +at `@app.core.user`, and one entry there can answer for all three user components. + +## Bundles are grouped by path + +The providers and the three bundles of the previous stage return unchanged, along with a fourth +bundle, `DummyContentFilterComponents`, that wires placeholder filters for testing. On top of them +sit three bundles keyed by path: + +```rust +delegate_components! { + new PostgresCoreComponents { + namespace DefaultNamespace; + + @app.core.user: PostgresUserComponents, + @app.core.post: PostgresPostComponents, + } +} + +delegate_components! { + new ProductionExtraComponents { + namespace DefaultNamespace; + + @app.extra.content_filter: AiContentFilterComponents, + } +} +``` + +`PostgresCoreComponents` routes the user and post paths to their bundles, and +`ProductionExtraComponents` routes the content filters to the AI bundle. `DummyExtraComponents` is +the same with the placeholder bundle. Each of these bundles joins `DefaultNamespace` itself, with +its `namespace` line, because a lookup arrives at a bundle by the component's name, and it is the +namespace that turns the name into the path the bundle's entries match. Without the line, the bundle +has no entry for the name. + +## Two contexts, one line apart + +The production and test contexts each join the namespace and route the two top-level paths: + +```rust +delegate_components! { + ProductionApp { + namespace DefaultNamespace; + + @app.core: PostgresCoreComponents, + @app.extra: ProductionExtraComponents, + } +} + +delegate_components! { + TestApp { + namespace DefaultNamespace; + + @app.core: PostgresCoreComponents, + @app.extra: DummyExtraComponents, + } +} +``` + +Each is a type that stands for one configuration of the application, with the database as its one +field. They share the whole core and differ only in their content filters, and the difference is +visible at a glance. One [`check_components!`](/docs/reference/macros/check_components) block +asserts all nine components on each. + +## Try a change + +Remove `TestApp`'s `@app.extra` line, and run [`cargo cgp check`](/docs/cargo-cgp/check). The two +creators fail, each with the filter its wrapper uses: + +```text +error[E0277]: [CGP-E001] the consumer traits `CanCreateUser` and `CanCensorUsername` are not implemented for context `TestApp` + = note: root cause: [CGP-E107] context `TestApp` does not contain any delegate entry for `@app.extra.content_filter.UsernameCensorComponent` +error[E0277]: [CGP-E001] the consumer traits `CanCreatePost` and `CanDetectSpamMessage` are not implemented for context `TestApp` + = note: root cause: [CGP-E107] context `TestApp` does not contain any delegate entry for `@app.extra.content_filter.SpamMessageDetectorComponent` +``` + +Each root cause names the full path the namespace routed the lookup to, which says where the entry +belongs. The other five components still check, since the getters, updaters, and deleter need +nothing from the extras. `cargo cgp check` leads with the root cause for the classes it recognizes, +and the tool is a v0.1.0-alpha that does not yet reshape every class. + +## The pattern + +This stage shows **components grouped under paths in a namespace**, so wiring routes a whole group +with one entry, and a hierarchy of paths lets a parent route its children through a bundle. The +contexts become short enough that their differences are what a reader sees. +[Namespaces](/docs/concepts/namespaces) explains the lookups, and [Aggregate +providers](/docs/concepts/aggregate-providers) explains bundles behind paths. + +The cost is indirection. To find what `TestApp` uses for `UserGetterComponent`, a reader follows the +component's prefix to a path, the path to `PostgresCoreComponents`, that bundle to +`PostgresUserComponents`, and that bundle to `GetUserWithPostgres`. The compiler does this +instantly, and `cargo cgp check` prints the chain when something is missing, but a person reads four +tables where the coarse stage had one line. And every context still names the core bundle; the [next +stage](./default-impls.md) moves that into the namespace too. + +## Where to go next + +- [`default_impls`](./default-impls.md): the next stage, a namespace that supplies the defaults. +- [web-app overview](../index.md): the four stages side by side. +- [Namespaces](/docs/concepts/namespaces): the CGP idea behind paths and the lookups they route. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-examples/web-app/index.md b/docs/projects/cgp-examples/web-app/index.md new file mode 100644 index 00000000..0b0e0f3b --- /dev/null +++ b/docs/projects/cgp-examples/web-app/index.md @@ -0,0 +1,80 @@ +--- +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'One social-media backend wired four ways with CGP, from one trait per domain to namespace defaults, to show how wiring changes as an app grows.' +--- + +# web-app + +`web-app` wires one small social-media backend four times, each time a step further, to show how +the wiring of a CGP application changes as it grows: from one trait per domain, to one trait per +operation grouped into bundles, to wiring grouped under paths, to defaults a namespace supplies. It +is one of the demonstration crates in [cgp-examples](../index.md), built with [CGP](/docs/), a +language extension for Rust with pluggable trait implementations at compile-time. + +**Nothing in the crate runs.** Every provider body is `todo!()`, and there is no binary or test. The +crate is a study of wiring, and the compiler is what checks it, so each page's "run it" step is a +check of the crate's wiring rather than a program's output. + +## The application + +The backend manages users and posts, and filters their content: a username is checked by a censor, +and a post's message by a spam detector, before either is created. The same application is written +in four modules, one per stage, each self-contained, with its own components, providers, and a +context named `ProductionApp`. The context in every stage is a type that stands for the +application, holds its database handle as a field, and holds its wiring: + +```rust +#[derive(HasField)] +pub struct ProductionApp { + pub database: PostgresDb, +} +``` + +The providers read the database as an [implicit argument](/docs/concepts/implicit-arguments), a +parameter filled from the context's field of the same name. + +## The stages + +Each stage has a page, in the order they build on each other: + +- [`coarse_grained`](./examples/coarse-grained.md) — one manager trait per domain, and the cost it + hides: a dependency one method needs is carried by the whole manager. +- [`fine_grained`](./examples/fine-grained.md) — one component per operation, content checks moved + into wrapper providers, and the providers grouped into bundles. +- [`namespace`](./examples/namespaces.md) — the components placed under paths, so a context wires + the whole application in two lines, and a test context differs from production in one. +- [`default_impls`](./examples/default-impls.md) — a namespace that supplies seven of the nine + providers as defaults, and the limit that comes with it. + +## Status + +`web-app` is a demonstration, not a library: it is unpublished, and nobody adds it as a dependency. +Its code uses current CGP idioms, so its wiring is safe to copy. Since every provider body is +`todo!()`, calling any method panics with `not yet implemented`; the value of the crate is in its +wiring, which every stage checks in full. + +## Checking it + +Clone the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples) and check the +crate from its root: + +```sh +cargo check -p cgp-example-web-app +``` + +It builds on stable Rust 1.90 or later. The check passes, which means every context in every stage +satisfies every component it wires. The stage pages make one change each and show what +[`cargo cgp check`](/docs/cargo-cgp/check) then reports. + +## Where to go next + +- [`coarse_grained`](./examples/coarse-grained.md): the first stage, and the one to read first. +- [Namespaces](/docs/concepts/namespaces): the CGP idea the later stages build to. +- [Hello World](/docs/tutorials/hello): a first CGP program, for a reader new to CGP. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/architecture/derive-free-records.md b/docs/projects/cgp-serde/architecture/derive-free-records.md index b9bdc9bd..7e2b2559 100644 --- a/docs/projects/cgp-serde/architecture/derive-free-records.md +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -98,7 +98,7 @@ writing the code rather than compiling it. - [Context services](./context-services.md): deserializers that take something from the context while they work. - [`basic`](../examples/basic.md): a derive-free struct written to JSON and read back. -- [Extensible records](/docs/concepts/extensible-records): the CGP idea behind reading and building +- [Extensible records](/docs/concepts/extensible-records): the CGP idea behind reading and building a struct generically. - [Reflection](/docs/comparisons/reflection): how this compares with Serde's derive and with reflection in other languages. diff --git a/docs/projects/cgp-serde/architecture/reentrant-providers.md b/docs/projects/cgp-serde/architecture/reentrant-providers.md index acb8de03..38245c8d 100644 --- a/docs/projects/cgp-serde/architecture/reentrant-providers.md +++ b/docs/projects/cgp-serde/architecture/reentrant-providers.md @@ -154,7 +154,7 @@ giving one of them a distinct type. ## Where to go next -- [Derive-free records](./derive-free-records.md): the struct providers that re-enter for each +- [Derive-free records](./derive-free-records.md): the struct providers that re-enter for each field. - [`messages`](../examples/messages.md): re-entry through three levels of nesting, and the `i64` entry left out. diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md index d7138f85..1eb9e0a3 100644 --- a/docs/projects/cgp-serde/examples/messages.md +++ b/docs/projects/cgp-serde/examples/messages.md @@ -210,13 +210,13 @@ traversal reaches, not only for the fields in the data. Four entries exist for t - **Each vector of structs** gets `SerializeIterator`. A `Vec` is a value the traversal reaches, so it needs an entry of its own besides the one for `EncryptedMessage`. -- **The generic reference entry**, `<'a, T> &'a T`, sends every reference to +- **The generic reference entry**, `<'a, T> &'a T`, sends every reference to [`SerializeDeref`](../reference/providers/serialize_deref.md), which serializes the value behind it. Walking a borrowed `Vec` yields `&EncryptedMessage`, and this one entry covers every such reference. - **`String`** is wired, although no field is a `String`, because the hex, base64, and RFC 3339 providers each produce a string and ask the context to serialize it. -- **`i64`** is wired in `AppB`, although no field is an `i64`, because `SerializeTimestamp` turns +- **`i64`** is wired in `AppB`, although no field is an `i64`, because `SerializeTimestamp` turns the date into an `i64` and asks the context to serialize that. The last point is the easiest to miss, and the change at the end of this page shows what happens diff --git a/docs/projects/cgp-serde/guides/formats.md b/docs/projects/cgp-serde/guides/formats.md index 608cc6a8..1f0b9924 100644 --- a/docs/projects/cgp-serde/guides/formats.md +++ b/docs/projects/cgp-serde/guides/formats.md @@ -36,12 +36,12 @@ Reading needs the context too, and `serde_json`'s `from_str` has no place for on offers three ways in. The choice depends on where the input comes from and whether the result borrows from it: -- **`deserialize_json_string`**, a method on the context from +- **`deserialize_json_string`**, a method on the context from [`CanDeserializeJsonString`](../reference/types/can_deserialize_json_string.md). It takes a `&str` and needs no `TryComputer` entries, only an error type. Annotate the result's type, as in `let payload: Payload = app.deserialize_json_string(&text)?;`, since the method takes no turbofish. The result cannot borrow from the string. -- **[`DeserializeFromJsonReader`](../reference/providers/deserialize_from_json_reader.md)**, a +- **[`DeserializeFromJsonReader`](../reference/providers/deserialize_from_json_reader.md)**, a provider wired under `@TryComputerComponent. DeserializeJson` and called with `try_compute`. It takes any `serde_json` reader: a `StrRead` for a string, a `SliceRead` for bytes, or an `IoRead` for a stream. A result can borrow from a string or byte input. diff --git a/docs/projects/cgp-serde/guides/wiring-a-context.md b/docs/projects/cgp-serde/guides/wiring-a-context.md index 80a31010..51f96d48 100644 --- a/docs/projects/cgp-serde/guides/wiring-a-context.md +++ b/docs/projects/cgp-serde/guides/wiring-a-context.md @@ -70,10 +70,10 @@ List the types a traversal touches, not only the types the data names. Start fro type, and follow what each provider asks the context for, which each provider's [reference page](../reference/index.md) states: -- **A struct** wired to [`SerializeFields`](../reference/providers/serialize_fields.md) or +- **A struct** wired to [`SerializeFields`](../reference/providers/serialize_fields.md) or [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) needs an entry for each field's type. -- **A collection** needs an entry of its own, besides its item type's. Writing one with +- **A collection** needs an entry of its own, besides its item type's. Writing one with [`SerializeIterator`](../reference/providers/serialize_iterator.md) also asks for the item as a reference, which one generic entry covers: `@ValueSerializerComponent.<'a, T> &'a T: SerializeDeref`. diff --git a/docs/projects/cgp-serde/guides/writing-a-provider.md b/docs/projects/cgp-serde/guides/writing-a-provider.md index f95dbb5b..feabd348 100644 --- a/docs/projects/cgp-serde/guides/writing-a-provider.md +++ b/docs/projects/cgp-serde/guides/writing-a-provider.md @@ -98,7 +98,7 @@ are two ways, and the choice depends on who makes the nested call: - **Converting to another type.** Call `self.serialize(&converted, serializer)` or `self.deserialize(deserializer)` yourself, and declare what you need with [`#[uses]`](/docs/reference/attributes/uses), as `SerializeMillis` does for `u64`. -- **Passing items to one of Serde's compound writers or readers.** Wrap each item in +- **Passing items to one of Serde's compound writers or readers.** Wrap each item in [`SerializeWithContext`](../reference/types/serialize_with_context.md) for `serialize_element` or `serialize_entry`, or pass a [`DeserializeWithContext`](../reference/types/deserialize_with_context.md) seed to diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md index 7aadbc53..123abb63 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md @@ -97,7 +97,7 @@ it in a reader itself. ## The ideas behind it -- [The bridge to +- [The bridge to Serde](../../architecture/serde-bridge.md#going-out-handing-a-context-to-a-serde-api): why reading needs a seed and a format's own deserializer. - [Modular error handling](/docs/concepts/modular-error-handling): raising into the context's error diff --git a/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md b/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md index 7cb5f365..d513b8d6 100644 --- a/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md +++ b/docs/projects/cgp-serde/reference/providers/try_deserialize_bytes.md @@ -66,7 +66,7 @@ it without the conversion. ## The ideas behind it -- [Wiring a +- [Wiring a context](../../guides/wiring-a-context.md#3-write-keys-for-references-lifetimes-and-arrays): why an array is keyed on an alias. diff --git a/docs/projects/cgp-serde/reference/types/deserialize_with_context.md b/docs/projects/cgp-serde/reference/types/deserialize_with_context.md index 992c3b33..0620095e 100644 --- a/docs/projects/cgp-serde/reference/types/deserialize_with_context.md +++ b/docs/projects/cgp-serde/reference/types/deserialize_with_context.md @@ -78,7 +78,7 @@ checks for trailing input itself. ## The ideas behind it -- [The bridge to +- [The bridge to Serde](../../architecture/serde-bridge.md#going-out-handing-a-context-to-a-serde-api): why reading needs a seed. - [Using a format](../../guides/formats.md#read-with-another-format): the seed with RON. diff --git a/docs/projects/cgp-serde/reference/types/serialize_with_context.md b/docs/projects/cgp-serde/reference/types/serialize_with_context.md index 6dcefecb..3ca55a4d 100644 --- a/docs/projects/cgp-serde/reference/types/serialize_with_context.md +++ b/docs/projects/cgp-serde/reference/types/serialize_with_context.md @@ -77,7 +77,7 @@ type, [`SerializeToJsonString`](../providers/serialize_to_json_string.md) wraps ## The ideas behind it -- [The bridge to +- [The bridge to Serde](../../architecture/serde-bridge.md#going-out-handing-a-context-to-a-serde-api): how a context reaches a Serde API. - [Re-entrant providers](../../architecture/reentrant-providers.md#re-entering-through-an-adapter): diff --git a/docs/projects/index.md b/docs/projects/index.md index 02939612..87c4eaaa 100644 --- a/docs/projects/index.md +++ b/docs/projects/index.md @@ -24,6 +24,9 @@ can judge the evidence for what it is. - **[cgp-serde](./cgp-serde/index.md)** — Serde's `Serialize` and `Deserialize` rebuilt as CGP components, so each application chooses how a type is encoded. A proof of concept on stable Rust, and the clearest example of CGP letting two applications choose differently for the same types. +- **[cgp-examples](./cgp-examples/index.md)** — five small demonstration crates, each showing one + area of CGP: an extensible interpreter, a wiring study at four scales, and more. Not libraries, + but programs to clone, run, and read. ## Find a pattern @@ -38,7 +41,7 @@ the Concepts page that explains the idea: | Providers composed in sequence, with each output checked against the next input | [`http_checksum_cli`](./hypershell/examples/http-checksum-cli.md) | [Handlers](/docs/concepts/handlers) | | A provider chosen by the type of the value it receives | [`http_checksum_client`](./hypershell/examples/http-checksum-client.md) | [`delegate_components!`](/docs/reference/macros/delegate_components) | | A language extended through a namespace that inherits the base | [`http_checksum_native`](./hypershell/examples/http-checksum-native.md) | [Namespaces](/docs/concepts/namespaces) | -| Providers bundled into an aggregate provider that routes point at | [`http_checksum_native`](./hypershell/examples/http-checksum-native.md) | [Aggregate providers](/docs/concepts/aggregate-providers) | +| Providers bundled into an aggregate provider that routes point at | [`http_checksum_native`](./hypershell/examples/http-checksum-native.md), [`fine_grained`](./cgp-examples/web-app/examples/fine-grained.md) | [Aggregate providers](/docs/concepts/aggregate-providers) | | Nested expressions, each resolved through the context | [`github_issues`](./hypershell/examples/github-issues.md) | [Impl-side dependencies](/docs/concepts/impl-side-dependencies) | | One context extended with its own wiring entries, including a new error type | [`bluesky_websocket`](./hypershell/examples/bluesky-websocket.md) | [Modular error handling](/docs/concepts/modular-error-handling) | | A struct encoded with no serialization derive, by providers that read its fields | [`basic`](./cgp-serde/examples/basic.md) | [Extensible records](/docs/concepts/extensible-records) | @@ -46,11 +49,21 @@ the Concepts page that explains the idea: | Two applications choosing different implementations for the same types | [`messages`](./cgp-serde/examples/messages.md) | [Coherence](/docs/concepts/coherence) | | A provider chosen by the type of the value it is given, from a table per context | [`messages`](./cgp-serde/examples/messages.md) | [Modularity hierarchy](/docs/concepts/modularity-hierarchy) | | Providers that hand nested values back to the context, so one choice reaches every level | [`messages`](./cgp-serde/examples/messages.md) | [Impl-side dependencies](/docs/concepts/impl-side-dependencies) | +| An operation over an enum written as one provider per variant, with no `match` | [`add_mult`](./cgp-examples/expression/examples/add-mult.md) | [Extensible variants](/docs/concepts/extensible-variants) | +| One provider for several variants, reading them through a getter | [`add_mult_binary_op`](./cgp-examples/expression/examples/add-mult-binary-op.md) | [Extensible records](/docs/concepts/extensible-records) | +| A provider chosen by an operation marker and the input type together | [`add_mult_code`](./cgp-examples/expression/examples/add-mult-code.md) | [Handlers](/docs/concepts/handlers) | +| A language extended with new variants, with no existing provider edited | [`add_mult_neg`](./cgp-examples/expression/examples/add-mult-neg.md) | [Extensible variants](/docs/concepts/extensible-variants) | +| One component per domain, and the requirements it makes every method share | [`coarse_grained`](./cgp-examples/web-app/examples/coarse-grained.md) | [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) | +| A check moved into a provider that wraps another provider | [`fine_grained`](./cgp-examples/web-app/examples/fine-grained.md) | [Higher-order providers](/docs/concepts/higher-order-providers) | +| Components grouped under paths, so a context wires an application in two lines | [`namespace`](./cgp-examples/web-app/examples/namespaces.md) | [Namespaces](/docs/concepts/namespaces) | +| Defaults supplied by a namespace, leaving the context only its differences | [`default_impls`](./cgp-examples/web-app/examples/default-impls.md) | [Namespaces](/docs/concepts/namespaces) | ## Where to start - **To see CGP's ideas in a real program**, read [`hello`](./hypershell/examples/hello.md), then follow the examples in order. +- **To see a single pattern in a small program**, pick a row of the table above, or start with the + [cgp-examples](./cgp-examples/index.md) crates, which are each built around one area of CGP. - **To weigh whether CGP holds up past a toy**, read the [Hypershell](./hypershell/index.md) and [cgp-serde](./cgp-serde/index.md) overviews and their limitations pages, which state the costs first. cgp-serde's [comparison with Serde](./cgp-serde/serde-comparison.md) sets it beside the diff --git a/docs/resources.md b/docs/resources.md index e8532992..cc7283f8 100644 --- a/docs/resources.md +++ b/docs/resources.md @@ -51,5 +51,5 @@ beyond small examples, this is the codebase to read. ## Projects -- [CGP Examples](https://github.com/contextgeneric/cgp-examples) - A repository hosting various examples of using CGP. +- [CGP Examples](https://github.com/contextgeneric/cgp-examples) - A repository hosting various examples of using CGP. Documented on this site in the [Projects](/docs/projects/cgp-examples/) section, with its examples walked through as short tutorials. - [Hypershell](https://github.com/contextgeneric/hypershell) - A type-level DSL for shell-scripting in Rust, built with CGP. Documented on this site in the [Projects](/docs/projects/hypershell/) section, with its examples walked through as short tutorials. From fab2e53a522e430c5bc628429013489217c7f80f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 06:26:15 +0000 Subject: [PATCH 103/516] Add a problem section to every Projects example page Each example page now says what its program solves, what makes it hard, and what solving it takes without CGP, before any of its code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HvLfWEnrK9PnjZSdoLbHG5 --- .../expression/examples/add-mult-binary-op.md | 16 +++++++++ .../expression/examples/add-mult-code.md | 16 +++++++++ .../expression/examples/add-mult-neg.md | 16 +++++++++ .../expression/examples/add-mult.md | 36 +++++++++++++++++++ .../web-app/examples/coarse-grained.md | 16 +++++++++ .../web-app/examples/default-impls.md | 17 +++++++++ .../web-app/examples/fine-grained.md | 18 ++++++++++ .../web-app/examples/namespaces.md | 17 +++++++++ docs/projects/cgp-serde/examples/basic.md | 17 +++++++++ docs/projects/cgp-serde/examples/messages.md | 19 +++++++++- .../hypershell/examples/bluesky-websocket.md | 16 +++++++++ docs/projects/hypershell/examples/bluesky.md | 14 ++++++++ .../hypershell/examples/github-issues.md | 15 ++++++++ .../hypershell/examples/hello-name.md | 19 ++++++++-- docs/projects/hypershell/examples/hello.md | 21 +++++++++-- .../hypershell/examples/http-checksum-cli.md | 15 ++++++++ .../examples/http-checksum-client.md | 15 ++++++++ .../examples/http-checksum-native.md | 15 ++++++++ .../hypershell/examples/nix-manual.md | 15 ++++++++ .../hypershell/examples/rust-playground.md | 13 +++++++ .../hypershell/examples/save-webpage.md | 13 +++++++ 21 files changed, 353 insertions(+), 6 deletions(-) diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md b/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md index fea452a3..c8d58edd 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md @@ -24,6 +24,22 @@ the new provider relies on. ::: +## The problem + +The task is to convert `+` and `*` expressions to Lisp. The two conversions are identical except for +the operator's symbol: each converts its left and right operands and builds a list headed by the +symbol. Written as one provider per operator, as in [`add_mult`](./add-mult.md), the two providers +are copies of each other, and each new binary operator would be a third copy. + +### Without CGP + +In plain Rust, the duplication is removed with a helper function that takes the symbol and the two +operands, and the `match` arm for each operator calls it. That works because the `match` has already +taken the variant apart, so it can hand the helper the operands. A provider that stands on its own +has no `match` around it to do that. To serve every binary operator, it needs a way to reach the +operands of whatever operator it is given, without being written for any one of them, and a way to +receive the symbol from outside. This page shows both. + ## Run it This context has no test of its own in the repository, so running it takes a test of your own. Save diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-code.md b/docs/projects/cgp-examples/expression/examples/add-mult-code.md index b61077b0..c0998e1e 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-code.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-code.md @@ -24,6 +24,22 @@ carry. ::: +## The problem + +The task is to run two operations, evaluation and conversion to Lisp, over the same language. In +[`add_mult`](./add-mult.md), each operation has a method of its own, `compute` and `compute_ref`. +That is fine for two operations, but it ties each operation to a method, and a language with many +operations would want one entry point that takes the operation as a parameter, with each operation's +providers still listed separately, operator by operator. + +### Without CGP + +In plain Rust, two operations are two functions, and that is the simplest design while there are +only a few. Choosing an operation by a type instead means a trait with one impl per operation, each +carrying its own `match` over the language, so the question "what does this operation do with this +operator?" is answered inside a different function for every operation. What this page shows is a +single table that answers it for every pair of operation and operator, keyed on both at once. + ## Run it This context has no test of its own in the repository, so running it takes a test of your own. Save diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-neg.md b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md index b529c790..216be62f 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-neg.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md @@ -24,6 +24,22 @@ several enums. ::: +## The problem + +The task is to add subtraction and negation to the language, and to evaluate the larger language, +without editing the base language's types or any of its existing providers. This is the half of the +expression problem that a plain Rust enum makes hardest: adding a new kind of expression. + +### Without CGP + +With an enum and a `match`, adding `Minus` and `Negate` means adding two variants to `Expr` and an +arm to every function that matches on it, which only the crate that owns `Expr` can do. The usual +workaround for a downstream crate is a new enum that wraps the old one, with a variant for the old +language and one for each new operator. It breaks as soon as the operators mix: the old `Plus` holds +operands of the old `Expr`, so a sum whose operand is a negation cannot be written, and making it +possible means copying every old operator into the new enum along with the code that handles it. +This page adds the operators so that every existing provider works for the new language unchanged. + ## Run it From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): diff --git a/docs/projects/cgp-examples/expression/examples/add-mult.md b/docs/projects/cgp-examples/expression/examples/add-mult.md index b292af21..d1bc686e 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult.md @@ -23,6 +23,42 @@ either. ::: +## The problem + +The task is an interpreter for a small arithmetic language, with two operations over it: evaluating +an expression to a number, and converting it to Lisp. On its own, that is easy. What makes it +interesting is the requirement that the interpreter stay open: new operators and new operations +should be addable later, from code that cannot edit what is already written, such as a second crate. + +### Without CGP + +The crate keeps the ordinary Rust version in its `classic` module, and it is the right design for a +language that will not change: + +```rust +pub enum Expr { + Plus(Box, Box), + Times(Box, Box), + Literal(u64), +} + +pub fn eval(expr: Expr) -> u64 { + match expr { + Expr::Plus(a, b) => eval(*a) + eval(*b), + Expr::Times(a, b) => eval(*a) * eval(*b), + Expr::Literal(value) => value, + } +} +``` + +A new operation is easy here: another function with its own `match`. A new operator is not. It +means adding a variant to `Expr` and an arm to every `match` over it, and a crate that does not own +`Expr` cannot do it at all. The other common Rust design, a trait with one method per operation and +one impl per operator, has the opposite problem: new operators are easy, and every new operation is +an edit to every impl. Keeping both directions open at once, with the compiler still checking that +every case is handled, is known as the expression problem, and it is what this page's design +addresses. + ## Run it From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): diff --git a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md index e95f0a81..b9d8a34a 100644 --- a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md +++ b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md @@ -22,6 +22,22 @@ explains what a component is, which is what this stage sizes. This page can be r ::: +## The problem + +The task is the backend of a small social-media service: create, read, and update users and posts, +store them in Postgres, and reject a username or a post that a content filter flags. This stage +writes it the way most applications start, with one trait per domain, and the problem it shows is +the one that starting point hides: a requirement of one method becomes a requirement of all of them. + +### Without CGP + +In plain Rust, the same design is a `UserManager` trait implemented by a Postgres type that holds +its database and its censor, or takes the censor as a generic parameter. It has the same cost. Only +`create_user` uses the censor, yet every value of the Postgres manager has to be built with one, so +code that only reads users, such as a report generator, still has to supply a censor it never calls. +Splitting the trait fixes it in plain Rust too, which is what the [next stage](./fine-grained.md) +does with CGP. This stage exists to make the cost visible first. + ## Check it From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): diff --git a/docs/projects/cgp-examples/web-app/examples/default-impls.md b/docs/projects/cgp-examples/web-app/examples/default-impls.md index 70652897..8e977fbd 100644 --- a/docs/projects/cgp-examples/web-app/examples/default-impls.md +++ b/docs/projects/cgp-examples/web-app/examples/default-impls.md @@ -22,6 +22,23 @@ World tutorial](/docs/tutorials/hello) introduces wiring, and ::: +## The problem + +The task is to supply the backend's usual choices as defaults, so that an application built on it +wires only what it varies, here its content filters, and gets the storage and the checks without +naming them. This is what a library wants to offer its users: a working configuration, open at the +points where applications differ. + +### Without CGP + +In plain Rust, defaults are usually supplied at run time: a builder or a constructor with default +values and optional overrides, or a `Default` implementation for a configuration struct. That is +flexible, and it is often the right answer. What it does not give is a compile-time check that a +configuration is complete, since the configuration is assembled from values when the program runs. +Trait default methods are compile-time, but they give each trait one default for every implementer, +not a set of defaults an application opts into. This stage publishes the defaults as a namespace an +application joins. + ## Check it From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): diff --git a/docs/projects/cgp-examples/web-app/examples/fine-grained.md b/docs/projects/cgp-examples/web-app/examples/fine-grained.md index 7d8adb5c..f1e352cb 100644 --- a/docs/projects/cgp-examples/web-app/examples/fine-grained.md +++ b/docs/projects/cgp-examples/web-app/examples/fine-grained.md @@ -23,6 +23,24 @@ providers](/docs/concepts/aggregate-providers) explains the bundles. ::: +## The problem + +The task is the same backend as the [coarse stage](./coarse-grained.md), rewired so that each +operation carries only the requirements it uses. That asks for three things at once: an operation +per component, so reading users does not need a censor; the content checks separated from the +storage code, so a check can wrap any way of creating users; and a way to group the result, so an +application does not wire nine components one by one. + +### Without CGP + +Plain Rust can do each of these. A trait per operation splits the requirements, and a decorator, a +struct generic over an inner creator that runs the check and then calls it, separates the check from +the storage. The cost is in putting them together. Each decorator holds its inner value and its +dependencies as fields, so assembling the application means constructor code that builds every layer +by hand in the right order, and a second configuration of the application is a second constructor +that repeats the layers it shares with the first. This stage expresses the same layering as wiring, +where the compiler checks each piece. + ## Check it From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): diff --git a/docs/projects/cgp-examples/web-app/examples/namespaces.md b/docs/projects/cgp-examples/web-app/examples/namespaces.md index c599fd4e..d0a8380a 100644 --- a/docs/projects/cgp-examples/web-app/examples/namespaces.md +++ b/docs/projects/cgp-examples/web-app/examples/namespaces.md @@ -22,6 +22,23 @@ reuses. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) introd ::: +## The problem + +The task is to run the backend in two configurations, a production one with AI-backed content +filters and a test one with placeholder filters, while keeping each configuration's wiring short +enough that the difference between them is obvious. With nine components, the [fine-grained +stage](./fine-grained.md) already names every component in every context, and a second context would +repeat all nine keys to change two of them. + +### Without CGP + +In plain Rust, two configurations are usually one application type made generic over the parts that +vary, such as `App`, with a type alias or a constructor for each configuration. +That works well while one parameter varies. As more parts vary, the application gains a parameter +for each, every function that names the type repeats them, and the configurations are told apart by +reading their constructors. This stage groups the parts under paths instead, so each configuration +is two lines that differ in one. + ## Check it From the root of the [cgp-examples repository](https://github.com/contextgeneric/cgp-examples): diff --git a/docs/projects/cgp-serde/examples/basic.md b/docs/projects/cgp-serde/examples/basic.md index f0434e20..28768b1e 100644 --- a/docs/projects/cgp-serde/examples/basic.md +++ b/docs/projects/cgp-serde/examples/basic.md @@ -23,6 +23,23 @@ smaller program. [Coherence](/docs/concepts/coherence) explains why Rust gives a ::: +## The problem + +The task is ordinary: write a struct to JSON and read it back, with its byte field written as a hex +string rather than as a list of numbers. Two requirements make it more than that. The struct should +derive nothing from Serde, so the crate that defines it need not depend on `serde`. And the byte +encoding should be chosen by the application that serializes the struct, not fixed where the struct +is defined. + +### Without CGP + +With Serde, the struct derives `Serialize` and `Deserialize`, and the byte field carries a +`#[serde(with = …)]` attribute naming a helper module that writes and reads hex. For one program +that encodes the struct one way, that is short, clear, and the right tool. Its costs are the two the +requirements rule out: the struct's crate depends on `serde`, and the hex encoding is written into +the struct's definition, so an application that wants base64 needs a different struct. This page +moves both decisions out of the struct and into the application's wiring. + ## Run it From the root of the [cgp-serde repository](https://github.com/contextgeneric/cgp-serde): diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md index 1eb9e0a3..4b109e95 100644 --- a/docs/projects/cgp-serde/examples/messages.md +++ b/docs/projects/cgp-serde/examples/messages.md @@ -23,6 +23,23 @@ which is what two applications here get around. This page can be read without th ::: +## The problem + +The task is to serialize the same data, an archive of messages with byte fields and dates, for two +applications that disagree about how it should look: one wants bytes as hex and dates as RFC 3339 +strings, the other bytes as base64 and dates as Unix timestamps. Both applications use the same Rust +types, and the choice has to apply at every level of nesting. + +### Without CGP + +With Serde, a type has one `Serialize` impl in the whole program. `Vec` and `DateTime` +already have theirs, in `serde` and in `chrono`, and Rust's orphan rule stops an application from +writing another. So the encoding is chosen per field, with `#[serde(with = …)]` attributes or +wrapper types, and each struct definition carries one set of choices. Two applications that want +different choices need two sets of structs, or code that converts the shared structs into +application-specific copies before serializing. This page keeps one set of structs and gives each +application its own choices. + ## Run it From the root of the [cgp-serde repository](https://github.com/contextgeneric/cgp-serde), run the @@ -119,7 +136,7 @@ pub struct MessagesArchive { Byte fields appear at every level, and dates in the innermost struct. Nothing in the structs says how either is written. [`CgpData`](/docs/reference/derives/derive_cgp_data) only exposes the fields to generic code, and `Vec` and `DateTime` belong to other crates, so in Serde their -encoding would be whatever those crates' `Serialize` impls chose. +encoding would be whatever their existing `Serialize` impls chose. ## Each application is a context with its own table diff --git a/docs/projects/hypershell/examples/bluesky-websocket.md b/docs/projects/hypershell/examples/bluesky-websocket.md index c9919da7..ec6330ba 100644 --- a/docs/projects/hypershell/examples/bluesky-websocket.md +++ b/docs/projects/hypershell/examples/bluesky-websocket.md @@ -24,6 +24,22 @@ the context chooses the error type, and explains what it needs of it. ::: +## The problem + +The task is the same firehose, read with a native WebSocket stage instead of the `websocat` command. +The WebSocket stage is an extension the base language does not include, and it can fail in ways the +base language's error handling does not know about, so the task is to add it, and its errors, to a +single program without changing the language for everyone else. + +### Without CGP + +In a language whose program is an enum interpreted by a `match`, a new stage is an edit to the +language's crate, and its errors are a new case in the language's error type, so the change reaches +every user. Without a language at all, the WebSocket client is a loop written by hand that reads +messages and writes them to the next command's input. This page adds the stage to one context with +two wiring entries, one for the stage and one for its error, and leaves the language and every other +context unchanged. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/bluesky.md b/docs/projects/hypershell/examples/bluesky.md index 901d17f2..b7a5f8d4 100644 --- a/docs/projects/hypershell/examples/bluesky.md +++ b/docs/projects/hypershell/examples/bluesky.md @@ -23,6 +23,20 @@ processes data at run time. ::: +## The problem + +The task is to read the Bluesky firehose, a live stream of every public post, and print the events +that mention a keyword, for as long as the program runs. The pipeline never finishes on its own, so +every stage has to process data as it arrives and keep running. + +### Without CGP + +In a shell, `websocat … | grep "$keyword"` does exactly this, and it is the right tool for watching +a feed by hand. In Rust, the same pipeline means spawning both commands and connecting them by hand, +as in [`http_checksum_cli`](./http-checksum-cli.md), with the added need that nothing waits for a +stage to finish before the next one starts. This page shows the same streaming stages running a +pipeline that has no end. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/github-issues.md b/docs/projects/hypershell/examples/github-issues.md index 930a3ce3..c8c49006 100644 --- a/docs/projects/hypershell/examples/github-issues.md +++ b/docs/projects/hypershell/examples/github-issues.md @@ -22,6 +22,21 @@ arguments nest. ::: +## The problem + +The task is to fetch a repository's open issues from the GitHub API and decode them into Rust +values. The request needs a URL assembled from a base URL and two path segments that must be +URL-encoded, and a `User-Agent` header, and the reply has to become a typed value rather than bytes. + +### Without CGP + +In plain Rust, `reqwest` and `serde` do this in a few lines: format the URL, set the header, send +the request, and decode the body with `.json::>()`. For a one-off call, that is the right +approach, and simpler than this one. What it gives up is the program as a unit of its own: the URL's +parts, the header, and the decoding target are spread through code tied to one HTTP client. This +page writes all three into the program, where each URL part says where its value comes from and the +decoding target is a type the program names. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/hello-name.md b/docs/projects/hypershell/examples/hello-name.md index 64f1db6b..8e980144 100644 --- a/docs/projects/hypershell/examples/hello-name.md +++ b/docs/projects/hypershell/examples/hello-name.md @@ -8,9 +8,8 @@ description: 'A Hypershell program that reads a runtime value from a field of it This program runs `echo` with a greeting whose name comes from a field of the context, the type the program runs on, at run time. It is an example from [Hypershell](../index.md), a shell-scripting -language whose programs are Rust types, built with [CGP](/docs/). Because a program is a type, it -cannot hold a value such as a name or a URL; this page shows where such values live instead, and -what the compiler reports when one is missing. +language whose programs are Rust types, built with [CGP](/docs/). This page shows where such runtime +values live, and what the compiler reports when one is missing. :::tip @@ -23,6 +22,20 @@ reading fields in ordinary CGP code. ::: +## The problem + +The task is to greet a name that is known only when the program runs. A Hypershell program is a +type, so it can name a value it needs but cannot contain one, and the value has to come from +somewhere the program's interpreter can reach while it runs. + +### Without CGP + +A shell script reads the name from a variable, `echo "Hello, $name"`, and a Rust function takes it +as an argument. In a program that is interpreted, the usual answer is an environment passed to every +step of the interpreter, which each step reads from, so every step's signature carries the whole +environment whether it uses it or not. This page puts the value in a field of the context that runs +the program, and only the step that needs the field asks for it. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/hello.md b/docs/projects/hypershell/examples/hello.md index af5f3749..e0fe7dee 100644 --- a/docs/projects/hypershell/examples/hello.md +++ b/docs/projects/hypershell/examples/hello.md @@ -23,6 +23,23 @@ than this one. ::: +## The problem + +The task itself is trivial on purpose: run `echo hello world!` and print what it prints. The problem +this page is about is the shape of the program, not its output. Hypershell's aim is a shell pipeline +written as a value that the compiler checks, that different interpreters can run differently, and +that anyone can extend with new kinds of stage. + +### Without CGP + +For this task alone, a shell script, `echo hello world!`, or a few lines of Rust with +`std::process::Command` are simpler, and they are what a reader should use to run one command. +Neither makes the program a thing of its own that can be inspected or reinterpreted: the shell reads +text, and the Rust code runs the command where it is written. The usual way to make a program a +value in Rust is an enum of its instructions and an interpreter that matches on it, and that design +is closed: a new kind of instruction means editing the enum and the interpreter, in the crate that +owns them. This page shows the smallest program in a language that avoids both limits. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): @@ -145,8 +162,8 @@ it. The costs are the ones that come with the technique. A program is fixed at compile time, the compiler does real work to resolve a large program, and a mistake in one is a compile error that can -be long to read. For a single fixed command, `std::process::Command` is simpler; Hypershell pays off -when a program's parts should be reusable and its meaning replaceable. +be long to read. Hypershell pays off when a program's parts should be reusable and its meaning +replaceable. ## Where to go next diff --git a/docs/projects/hypershell/examples/http-checksum-cli.md b/docs/projects/hypershell/examples/http-checksum-cli.md index d818f803..114b9afa 100644 --- a/docs/projects/hypershell/examples/http-checksum-cli.md +++ b/docs/projects/hypershell/examples/http-checksum-cli.md @@ -22,6 +22,21 @@ stage belongs to. ::: +## The problem + +The task is to download a web page and print its SHA-256 digest by piping three commands together, +`curl`, `sha256sum`, and `cut`, with all three running at once so the page streams through them +rather than being held in memory. + +### Without CGP + +In a shell, this is one line, and for a pipeline run by hand the shell is the right tool. In Rust, +the same pipeline with `std::process::Command` or Tokio's process API means spawning each command, +connecting each one's output to the next one's input by hand, and waiting on all of them and +checking each exit status, so the plumbing outweighs the pipeline. This page declares the pipeline +as a type and leaves the plumbing to the providers that interpret it, which also check that the +stages fit. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/http-checksum-client.md b/docs/projects/hypershell/examples/http-checksum-client.md index 74e8c1af..9a03a79f 100644 --- a/docs/projects/hypershell/examples/http-checksum-client.md +++ b/docs/projects/hypershell/examples/http-checksum-client.md @@ -23,6 +23,21 @@ the page explains what it does here without assuming that reference. ::: +## The problem + +The task is the same digest with `curl` replaced by an HTTP request made from Rust, whose response +streams into the `sha256sum` and `cut` commands. The difficulty is at the join: the HTTP library +produces its body as one kind of stream, and a command's input is fed from another kind, so the two +do not connect directly. + +### Without CGP + +In plain Rust, the join is written by hand: the response body is adapted into the reader type the +command's input needs, with a compatibility wrapper, and the adapting code is tied to the two stages +it sits between. Swap the HTTP stage for a file, or the command for another native stage, and that +code changes too. This page has each stage choose how to convert its input by the input's type, so +any stage can follow any other that produces something it can read. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/http-checksum-native.md b/docs/projects/hypershell/examples/http-checksum-native.md index 4810ba47..bb64753a 100644 --- a/docs/projects/hypershell/examples/http-checksum-native.md +++ b/docs/projects/hypershell/examples/http-checksum-native.md @@ -23,6 +23,21 @@ inherit, and explains what it needs of them. ::: +## The problem + +The task is the same digest again, with every stage native: an HTTP request, a SHA-256 checksum, and +hexadecimal encoding. The base language has no checksum stage, so the task is really to extend a +language from outside the crates that define it, and to run the extended language with as little +change as possible. + +### Without CGP + +A language whose program is an enum of instructions, interpreted by a `match`, can gain a checksum +instruction only in the crate that owns the enum: someone adds the variant, adds an arm to the +interpreter, and releases a new version. A user who cannot wait forks it. This page adds the +checksum stages in crates of their own, with their own syntax and providers, and a program joins the +extended language by naming a different namespace. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/nix-manual.md b/docs/projects/hypershell/examples/nix-manual.md index 083dda42..b6de7d15 100644 --- a/docs/projects/hypershell/examples/nix-manual.md +++ b/docs/projects/hypershell/examples/nix-manual.md @@ -24,6 +24,21 @@ for what it needs. ::: +## The problem + +The task is to download a web page, convert it to upper case, and print the lines that mention a +keyword chosen at run time. The interesting part is the command lines: `tr` takes fixed arguments, +while `grep` takes a mix of a fixed flag and a value from the running application. + +### Without CGP + +In a shell, this is `curl … | tr '[:lower:]' '[:upper:]' | grep -i "$keyword"`, one line that +mixes literals and a variable freely, and for a one-off search it is the simpler tool. In Rust, each +command's argument list is built as a vector of strings before the command is spawned, so the mix of +fixed and runtime values is assembled by hand, in code that sits apart from the pipeline it feeds. +This page writes each argument list inside the program, with each argument saying where its value +comes from. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/rust-playground.md b/docs/projects/hypershell/examples/rust-playground.md index 7908eed1..4a600e6b 100644 --- a/docs/projects/hypershell/examples/rust-playground.md +++ b/docs/projects/hypershell/examples/rust-playground.md @@ -23,6 +23,19 @@ input and its code. ::: +## The problem + +The task is to post a Rust value to the Rust Playground's gist API as JSON and decode the reply into +another Rust value. Unlike the earlier examples, the program's input and its output are both Rust +values, not bytes, so the pipeline has to start and end in Rust's types. + +### Without CGP + +With `reqwest`, the whole task is one chain: `.json(&request)` to encode and send, and +`.json::()` to decode, and for a single call that is simpler than a pipeline. This page +writes the same steps as three stages, encoding, the request, and decoding, so each is a stage the +language provides and the compiler checks that each stage's output is what the next one reads. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): diff --git a/docs/projects/hypershell/examples/save-webpage.md b/docs/projects/hypershell/examples/save-webpage.md index 7da7087f..e0a1efd0 100644 --- a/docs/projects/hypershell/examples/save-webpage.md +++ b/docs/projects/hypershell/examples/save-webpage.md @@ -22,6 +22,19 @@ types a pipeline chains. ::: +## The problem + +The task is to download a web page into a file, writing it as it arrives rather than holding the +whole page in memory, with the URL and the file path both chosen when the program runs. + +### Without CGP + +`curl -o manual.html ` does this in a shell, and it is the simpler tool for a download run by +hand. In Rust, streaming a response to disk means a loop that reads the body chunk by chunk and +writes each chunk to a file, with the URL and the path passed in as arguments. This page expresses +the download as a two-stage pipeline whose last stage writes to a file and produces nothing, so a +download is one more program in the language rather than a loop written for the occasion. + ## Run it From the root of the [Hypershell repository](https://github.com/contextgeneric/hypershell): From fa3fcd4cc14d2006da6bba486c83bc601b73ab65 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 06:38:09 +0000 Subject: [PATCH 104/516] Link the Projects examples and the blog posts they grew out of Each example page links the post that presented its program, and each post that presents a project carries a notice pointing to the maintained pages. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HvLfWEnrK9PnjZSdoLbHG5 --- blog/2025-06-14-hypershell-release/index.md | 8 ++++++++ blog/2025-07-07-extensible-datatypes-part-1.md | 9 +++++++++ blog/2025-07-09-extensible-datatypes-part-2.md | 9 +++++++++ blog/2025-07-12-extensible-datatypes-part-3.md | 8 ++++++++ blog/2025-07-30-extensible-datatypes-part-4.md | 10 ++++++++++ blog/2025-11-03-cgp-serde-release.md | 9 +++++++++ blog/2026-03-07-rustlab-2025-coherence/index.md | 9 +++++++++ .../expression/examples/add-mult-binary-op.md | 2 ++ .../cgp-examples/expression/examples/add-mult-code.md | 2 ++ .../cgp-examples/expression/examples/add-mult-neg.md | 2 ++ .../cgp-examples/expression/examples/add-mult.md | 2 ++ docs/projects/cgp-examples/index.md | 3 +++ .../cgp-examples/web-app/examples/coarse-grained.md | 2 ++ .../cgp-examples/web-app/examples/default-impls.md | 2 ++ .../cgp-examples/web-app/examples/fine-grained.md | 2 ++ .../cgp-examples/web-app/examples/namespaces.md | 2 ++ docs/projects/cgp-examples/web-app/index.md | 2 ++ docs/projects/cgp-serde/examples/basic.md | 3 +++ docs/projects/cgp-serde/examples/messages.md | 6 ++++++ docs/projects/hypershell/examples/bluesky-websocket.md | 3 +++ docs/projects/hypershell/examples/bluesky.md | 2 ++ docs/projects/hypershell/examples/github-issues.md | 2 ++ docs/projects/hypershell/examples/hello-name.md | 3 +++ docs/projects/hypershell/examples/hello.md | 3 +++ docs/projects/hypershell/examples/http-checksum-cli.md | 3 +++ .../hypershell/examples/http-checksum-client.md | 3 +++ .../hypershell/examples/http-checksum-native.md | 3 +++ docs/projects/hypershell/examples/nix-manual.md | 2 ++ docs/projects/hypershell/examples/rust-playground.md | 3 +++ docs/projects/hypershell/examples/save-webpage.md | 2 ++ docs/projects/hypershell/index.md | 2 +- 31 files changed, 122 insertions(+), 1 deletion(-) diff --git a/blog/2025-06-14-hypershell-release/index.md b/blog/2025-06-14-hypershell-release/index.md index 407fcf28..9d28f022 100644 --- a/blog/2025-06-14-hypershell-release/index.md +++ b/blog/2025-06-14-hypershell-release/index.md @@ -6,6 +6,14 @@ tags: [release, deepdive] description: 'Hypershell is a type-level DSL for shell-scripting in Rust, where a program is a type the compiler interprets. Built with CGP, with its costs stated.' --- +:::note + +This post describes Hypershell as it was when the post was published, and its code predates the +current design. The [Hypershell pages](/docs/projects/hypershell/) in the Projects section document +it as it is now, with each example program walked through as a short tutorial. + +::: + I am thrilled to introduce [**Hypershell**](https://github.com/contextgeneric/hypershell), a modular, *type-level* domain-specific language (DSL) for writing shell-script-like programs in Rust. Hypershell is powered by [**context-generic programming**](/) (CGP), which makes it possible for users to *extend* or *modify* both the language syntax and semantics. diff --git a/blog/2025-07-07-extensible-datatypes-part-1.md b/blog/2025-07-07-extensible-datatypes-part-1.md index aa9e4da1..e3286869 100644 --- a/blog/2025-07-07-extensible-datatypes-part-1.md +++ b/blog/2025-07-07-extensible-datatypes-part-1.md @@ -6,6 +6,15 @@ tags: [release, deepdive] description: 'Extensible records in CGP v0.4.2: code that works on any struct with the right fields, safe enum casting, and apps built from independent providers.' --- +:::note + +This post's code predates the current design of CGP. [Extensible +records](/docs/concepts/extensible-records) explains the current design of the feature, and the +application builder this post develops is one of the [cgp-examples](/docs/projects/cgp-examples/) +crates in the Projects section. + +::: + I’m excited to announce the release of [**CGP v0.4.2**](https://github.com/contextgeneric/cgp/releases/tag/v0.4.2), a major milestone that significantly expands the expressive power of generic programming in Rust. With this release, CGP introduces full support for **extensible records and variants**, unlocking a range of new capabilities for developers working with highly modular and reusable code. Extensible records and variants allow developers to write code that operates on *any struct containing specific fields* or *any enum containing specific variants*, without needing their concrete definition. This makes it possible to write truly generic and flexible logic that is decoupled from rigid type definitions. diff --git a/blog/2025-07-09-extensible-datatypes-part-2.md b/blog/2025-07-09-extensible-datatypes-part-2.md index 7715924f..3aeada7a 100644 --- a/blog/2025-07-09-extensible-datatypes-part-2.md +++ b/blog/2025-07-09-extensible-datatypes-part-2.md @@ -6,6 +6,15 @@ tags: [deepdive] description: 'Extensible variants applied to the expression problem: a modular arithmetic interpreter built with the extensible visitor pattern.' --- +:::note + +This post's code predates the current design of CGP. The interpreter it develops is documented as +it is now in the [`expression` pages](/docs/projects/cgp-examples/expression/) of the Projects +section, one page per context, and [Extensible variants](/docs/concepts/extensible-variants) +explains the current design of the feature. + +::: + This is the **second** part of the blog series on **Programming Extensible Data Types in Rust with CGP**. You can read the [first part here](/blog/extensible-datatypes-part-1). In this second part of the series, we will explore the use of **extensible variants**, by examining how it can be used in an **extensible visitor pattern** to build a modular interpreter for a toy math expression language. diff --git a/blog/2025-07-12-extensible-datatypes-part-3.md b/blog/2025-07-12-extensible-datatypes-part-3.md index 0cccef83..365df548 100644 --- a/blog/2025-07-12-extensible-datatypes-part-3.md +++ b/blog/2025-07-12-extensible-datatypes-part-3.md @@ -6,6 +6,14 @@ tags: [deepdive] description: 'How extensible records are implemented: partial records, constraint propagation, and the builder dispatchers underneath them.' --- +:::note + +This post's code predates the current design of CGP. [Extensible +records](/docs/concepts/extensible-records) explains the current design of the feature, and the +[reference](/docs/reference/) documents each of the traits this post walks through. + +::: + This is the **third** part of the blog series on **Programming Extensible Data Types in Rust with CGP**. You can read the [first](/blog/extensible-datatypes-part-1) and [second](/blog/extensible-datatypes-part-2) parts here. At this point, you’ve likely seen how these patterns can make real-world applications more modular and maintainable. If these examples have convinced you of CGP’s practical value, that’s great. But if you still feel the examples are not grounded enough in production use cases, you are welcome to pause here and revisit CGP later. diff --git a/blog/2025-07-30-extensible-datatypes-part-4.md b/blog/2025-07-30-extensible-datatypes-part-4.md index 3dc5ae89..ba28f06b 100644 --- a/blog/2025-07-30-extensible-datatypes-part-4.md +++ b/blog/2025-07-30-extensible-datatypes-part-4.md @@ -6,6 +6,16 @@ tags: [deepdive] description: 'How extensible variants are implemented: the empty Void type, exhaustive extraction, the enum casts, and the monadic visitor dispatchers.' --- +:::note + +This post's code predates the current design of CGP. [Extensible +variants](/docs/concepts/extensible-variants) explains the current design of the feature, the +[reference](/docs/reference/) documents the extraction and casting traits this post walks through, +and the [`expression` pages](/docs/projects/cgp-examples/expression/) show the feature in a running +interpreter. + +::: + This is the **fourth** part of the blog series on **Programming Extensible Data Types in Rust with CGP**. You can read the [first](/blog/extensible-datatypes-part-1), [second](/blog/extensible-datatypes-part-2) and [third](/blog/extensible-datatypes-part-3) parts here. In the third part of the series, [**Implementing Extensible Records**](/blog/extensible-datatypes-part-3), we have walked through the internal implementation of extensible records, and learned about concepts such as partial records and builder dispatchers. diff --git a/blog/2025-11-03-cgp-serde-release.md b/blog/2025-11-03-cgp-serde-release.md index 32664fa2..11f3fc2a 100644 --- a/blog/2025-11-03-cgp-serde-release.md +++ b/blog/2025-11-03-cgp-serde-release.md @@ -6,6 +6,15 @@ tags: [release] description: 'cgp-serde rebuilds Serde''s Serialize and Deserialize as CGP components, so two applications can encode the same data in different formats.' --- +:::note + +This post describes cgp-serde as it was when the post was published, and its code predates the +current design. The [cgp-serde pages](/docs/projects/cgp-serde/) in the Projects section document it +as it is now, with its examples walked through as short tutorials and a reference page for each +provider. + +::: + I am excited to announce the release of [**cgp-serde**](https://github.com/contextgeneric/cgp-serde), a modular serialization library for [Serde](https://serde.rs/) that leverages the power of [**Context-Generic Programming**](/) (CGP). In short, `cgp-serde` extends Serde’s original [`Serialize`](https://docs.rs/serde/latest/serde/trait.Serialize.html) and [`Deserialize`](https://docs.rs/serde/latest/serde/trait.Deserialize.html) traits with CGP, making it possible to write **overlapping** or **orphaned** implementations of these traits and thus bypass the standard Rust **coherence restrictions**. diff --git a/blog/2026-03-07-rustlab-2025-coherence/index.md b/blog/2026-03-07-rustlab-2025-coherence/index.md index 7370b9d5..9aa67271 100644 --- a/blog/2026-03-07-rustlab-2025-coherence/index.md +++ b/blog/2026-03-07-rustlab-2025-coherence/index.md @@ -6,6 +6,15 @@ description: 'The RustLab 2025 talk, with slides and full transcript: why Rust'' # How to stop fighting with coherence and start writing context-generic trait impls - RustLab 2025 transcript +:::note + +The [cgp-serde](/docs/projects/cgp-serde/) library this talk uses as its demonstration is +documented as it is now in the Projects section, including the [two-application +demo](/docs/projects/cgp-serde/examples/messages), and [Coherence](/docs/concepts/coherence) +explains the idea the talk presents. + +::: +

diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md b/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md index c8d58edd..05d9f89b 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-binary-op.md @@ -186,6 +186,8 @@ multiply. the design. - [Extensible records](/docs/concepts/extensible-records): the CGP idea behind reading a struct's fields by name. +- [Extensible data types, part 2](/blog/extensible-datatypes-part-2#binary-operator-provider): the + post that introduced this provider. Its code predates the current design. --- diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-code.md b/docs/projects/cgp-examples/expression/examples/add-mult-code.md index c0998e1e..8f713f8e 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-code.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-code.md @@ -185,6 +185,8 @@ method is called, as `add_mult` does, keeps the table shorter when there are onl dispatch, side by side. - [Handlers](/docs/concepts/handlers): CGP's computation interfaces, and the `Code` marker they share. +- [Extensible data types, part 2](/blog/extensible-datatypes-part-2#code-based-dispatching): the + post that introduced this dispatch. Its code predates the current design. --- diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-neg.md b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md index 216be62f..f5bd573b 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-neg.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md @@ -187,6 +187,8 @@ reused, rather than in the enums, which stay ordinary closed Rust enums. its own wrapper. - [Extensible variants](/docs/concepts/extensible-variants): the CGP idea that lets one provider serve several enums. +- [Extensible data types, part 2](/blog/extensible-datatypes-part-2#extending-mathexpr): the post + that introduced this extension. Its code predates the current design. --- diff --git a/docs/projects/cgp-examples/expression/examples/add-mult.md b/docs/projects/cgp-examples/expression/examples/add-mult.md index d1bc686e..c386a4a3 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult.md @@ -322,6 +322,8 @@ the `match` is simpler and better. dispatch, and why each needs its wrapper. - [Extensible variants](/docs/concepts/extensible-variants): the CGP idea behind handling one variant of any enum. +- [Extensible data types, part 2](/blog/extensible-datatypes-part-2#evaluator-computer): the post + that developed this interpreter. Its code predates the current design. --- diff --git a/docs/projects/cgp-examples/index.md b/docs/projects/cgp-examples/index.md index 415c722a..4ab3b89a 100644 --- a/docs/projects/cgp-examples/index.md +++ b/docs/projects/cgp-examples/index.md @@ -50,6 +50,9 @@ crate's tests. Each crate's pages give the command for its programs. - [`web-app`](./web-app/index.md): one application's wiring at four scales. - [Projects](../index.md): the other projects on this site, and a table from each CGP pattern to an example that shows it. +- [Extensible data types, part 1](/blog/extensible-datatypes-part-1) and + [part 2](/blog/extensible-datatypes-part-2): the posts that developed the `builder` and + `expression` crates. Their code predates the current design. --- diff --git a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md index b9d8a34a..005c46de 100644 --- a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md +++ b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md @@ -183,6 +183,8 @@ requirement to a provider. - [web-app overview](../index.md): the four stages side by side. - [Impl-side dependencies](/docs/concepts/impl-side-dependencies): how a provider's requirements are declared and resolved. +- [CGP v0.8.0](/blog/v0.8.0-release#an-example-social-media-web-app): the release post that develops + this application stage by stage. --- diff --git a/docs/projects/cgp-examples/web-app/examples/default-impls.md b/docs/projects/cgp-examples/web-app/examples/default-impls.md index 8e977fbd..0d7c8803 100644 --- a/docs/projects/cgp-examples/web-app/examples/default-impls.md +++ b/docs/projects/cgp-examples/web-app/examples/default-impls.md @@ -185,6 +185,8 @@ every context that joins; where it is wrong, the fix is a different namespace, n bound entries. - [Namespaces](/docs/concepts/namespaces): the CGP idea behind shared defaults, and why a bound entry cannot be overridden. +- [CGP v0.8.0](/blog/v0.8.0-release#default-implementations): the release post that develops this + application stage by stage. --- diff --git a/docs/projects/cgp-examples/web-app/examples/fine-grained.md b/docs/projects/cgp-examples/web-app/examples/fine-grained.md index f1e352cb..bf2ed699 100644 --- a/docs/projects/cgp-examples/web-app/examples/fine-grained.md +++ b/docs/projects/cgp-examples/web-app/examples/fine-grained.md @@ -194,6 +194,8 @@ every context. The [next stage](./namespaces.md) removes that. - [web-app overview](../index.md): the four stages side by side. - [Higher-order providers](/docs/concepts/higher-order-providers): the CGP idea behind the filter wrappers. +- [CGP v0.8.0](/blog/v0.8.0-release#fine-grained-traits): the release post that develops this + application stage by stage. --- diff --git a/docs/projects/cgp-examples/web-app/examples/namespaces.md b/docs/projects/cgp-examples/web-app/examples/namespaces.md index d0a8380a..ec3be15d 100644 --- a/docs/projects/cgp-examples/web-app/examples/namespaces.md +++ b/docs/projects/cgp-examples/web-app/examples/namespaces.md @@ -176,6 +176,8 @@ stage](./default-impls.md) moves that into the namespace too. - [`default_impls`](./default-impls.md): the next stage, a namespace that supplies the defaults. - [web-app overview](../index.md): the four stages side by side. - [Namespaces](/docs/concepts/namespaces): the CGP idea behind paths and the lookups they route. +- [CGP v0.8.0](/blog/v0.8.0-release#introducing-cgp-namespaces-and-paths): the release post that + develops this application stage by stage. --- diff --git a/docs/projects/cgp-examples/web-app/index.md b/docs/projects/cgp-examples/web-app/index.md index 0b0e0f3b..94d9fc18 100644 --- a/docs/projects/cgp-examples/web-app/index.md +++ b/docs/projects/cgp-examples/web-app/index.md @@ -72,6 +72,8 @@ satisfies every component it wires. The stage pages make one change each and sho - [`coarse_grained`](./examples/coarse-grained.md): the first stage, and the one to read first. - [Namespaces](/docs/concepts/namespaces): the CGP idea the later stages build to. - [Hello World](/docs/tutorials/hello): a first CGP program, for a reader new to CGP. +- [CGP v0.8.0](/blog/v0.8.0-release): the release post that develops this application stage by + stage, and introduces namespaces. --- diff --git a/docs/projects/cgp-serde/examples/basic.md b/docs/projects/cgp-serde/examples/basic.md index 28768b1e..4712f2e6 100644 --- a/docs/projects/cgp-serde/examples/basic.md +++ b/docs/projects/cgp-serde/examples/basic.md @@ -279,6 +279,9 @@ that encodes each type one way, Serde's derive is shorter. - [Wiring a context](../guides/wiring-a-context.md): how to build and check a table like `App`'s. - [Coherence](/docs/concepts/coherence): why moving the value out of `Self` lets implementations overlap. +- [Announcing cgp-serde](/blog/cgp-serde-release#derive-free-serialization-with-derivecgpdata): the + post that announced the library, including derive-free serialization. Its code predates the + current design. --- diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md index 4b109e95..65f1e3a3 100644 --- a/docs/projects/cgp-serde/examples/messages.md +++ b/docs/projects/cgp-serde/examples/messages.md @@ -299,6 +299,12 @@ from Serde's derive with none of this. how to check the table. - [Coherence](/docs/concepts/coherence): the Rust rule that gives a type one impl, and how CGP restores choice one context at a time. +- [Announcing cgp-serde](/blog/cgp-serde-release#modular-serialization-demo): the post that + announced the library, which presents this two-application demo. Its code predates the current + design. +- [How to stop fighting with coherence (RustLab + 2025)](/blog/rustlab-2025-coherence#45---the-cgp-serde-crate): the talk that used this demo live, + with a transcript. --- diff --git a/docs/projects/hypershell/examples/bluesky-websocket.md b/docs/projects/hypershell/examples/bluesky-websocket.md index ec6330ba..5805a2d3 100644 --- a/docs/projects/hypershell/examples/bluesky-websocket.md +++ b/docs/projects/hypershell/examples/bluesky-websocket.md @@ -181,6 +181,9 @@ above. type and how source errors reach it. - [Assembly](../architecture/assembly.md#a-context-joins-the-namespace): context entries and extension namespaces. +- [Hypershell: a type-level DSL for shell-scripting in + Rust](/blog/hypershell-release#extending-hypershell): the post that announced Hypershell, whose + last part covers extending the language. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/bluesky.md b/docs/projects/hypershell/examples/bluesky.md index b7a5f8d4..ccbd43e7 100644 --- a/docs/projects/hypershell/examples/bluesky.md +++ b/docs/projects/hypershell/examples/bluesky.md @@ -113,6 +113,8 @@ reports; a stalled feed here looks the same as a quiet one. streaming stage runs and reports failure. - [Type-level DSLs](/docs/concepts/type-level-dsls): how a program fixed at compile time still processes data as it arrives. +- [Hypershell: a type-level DSL for shell-scripting in Rust](/blog/hypershell-release): the post + that announced Hypershell, with the project's motivation. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/github-issues.md b/docs/projects/hypershell/examples/github-issues.md index c8c49006..5c101a38 100644 --- a/docs/projects/hypershell/examples/github-issues.md +++ b/docs/projects/hypershell/examples/github-issues.md @@ -146,6 +146,8 @@ reported at the end of a long chain of lookups, which is why checking the progra every kind of argument. - [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the requirements that make nested interpretation work. +- [Hypershell: a type-level DSL for shell-scripting in Rust](/blog/hypershell-release): the post + that announced Hypershell, with the project's motivation. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/hello-name.md b/docs/projects/hypershell/examples/hello-name.md index 8e980144..886a5d0b 100644 --- a/docs/projects/hypershell/examples/hello-name.md +++ b/docs/projects/hypershell/examples/hello-name.md @@ -175,6 +175,9 @@ against its context, as above, is worth doing. program. - [Checking your wiring](/docs/concepts/check-traits): why CGP wiring is checked lazily, and what `check_components!` forces. +- [Hypershell: a type-level DSL for shell-scripting in + Rust](/blog/hypershell-release#variable-parameters): the post that announced Hypershell, which + introduced this program. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/hello.md b/docs/projects/hypershell/examples/hello.md index e0fe7dee..403cec22 100644 --- a/docs/projects/hypershell/examples/hello.md +++ b/docs/projects/hypershell/examples/hello.md @@ -172,6 +172,9 @@ replaceable. rules. - [Assembly](../architecture/assembly.md): how `HypershellNamespace` routes each piece of syntax. - [Type-level DSLs](/docs/concepts/type-level-dsls): the CGP technique behind the language. +- [Hypershell: a type-level DSL for shell-scripting in Rust](/blog/hypershell-release#hello-world): + the post that announced Hypershell, which opens with this program. Its code predates the current + design. --- diff --git a/docs/projects/hypershell/examples/http-checksum-cli.md b/docs/projects/hypershell/examples/http-checksum-cli.md index 114b9afa..03d7f8ec 100644 --- a/docs/projects/hypershell/examples/http-checksum-cli.md +++ b/docs/projects/hypershell/examples/http-checksum-cli.md @@ -157,6 +157,9 @@ stage between them. the dispatchers. - [Handlers](/docs/concepts/handlers): CGP's family of computation components, including the combinators that compose them. +- [Hypershell: a type-level DSL for shell-scripting in + Rust](/blog/hypershell-release#streaming-handlers): the post that announced Hypershell, which + introduced this pipeline. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/http-checksum-client.md b/docs/projects/hypershell/examples/http-checksum-client.md index 9a03a79f..e22cfdff 100644 --- a/docs/projects/hypershell/examples/http-checksum-client.md +++ b/docs/projects/hypershell/examples/http-checksum-client.md @@ -179,6 +179,9 @@ once the converters have an entry for it, which is a change to the language, not - [`UseField`](/docs/reference/providers/use_field): the provider behind the client field. - [Handlers](/docs/concepts/handlers): the computation interface whose second parameter, the input, the dispatch keys on. +- [Hypershell: a type-level DSL for shell-scripting in + Rust](/blog/hypershell-release#native-http-request): the post that announced Hypershell, which + introduced this program. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/http-checksum-native.md b/docs/projects/hypershell/examples/http-checksum-native.md index bb64753a..254716ef 100644 --- a/docs/projects/hypershell/examples/http-checksum-native.md +++ b/docs/projects/hypershell/examples/http-checksum-native.md @@ -194,6 +194,9 @@ more about what this means. - [Assembly](../architecture/assembly.md): the bundles and routes the base language is built from. - [Namespaces](/docs/concepts/namespaces): inheriting a namespace, and why an inherited binding cannot be overridden. +- [Hypershell: a type-level DSL for shell-scripting in + Rust](/blog/hypershell-release#extending-hypershell): the post that announced Hypershell, whose + last part builds this extension. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/nix-manual.md b/docs/projects/hypershell/examples/nix-manual.md index b6de7d15..229d2a3a 100644 --- a/docs/projects/hypershell/examples/nix-manual.md +++ b/docs/projects/hypershell/examples/nix-manual.md @@ -133,6 +133,8 @@ in a URL, a reader looks at how URLs are produced, rather than at one definition every kind of argument and where it may appear. - [Impl-side dependencies](/docs/concepts/impl-side-dependencies): how each interpreter asks the context for what it needs. +- [Hypershell: a type-level DSL for shell-scripting in Rust](/blog/hypershell-release): the post + that announced Hypershell, with the project's motivation. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/rust-playground.md b/docs/projects/hypershell/examples/rust-playground.md index 4a600e6b..377e4faf 100644 --- a/docs/projects/hypershell/examples/rust-playground.md +++ b/docs/projects/hypershell/examples/rust-playground.md @@ -146,6 +146,9 @@ by following that wiring rather than by reading a declaration. and how a context joins the language. - [Handlers](/docs/concepts/handlers): how a computation's output type follows from its code and input. +- [Hypershell: a type-level DSL for shell-scripting in + Rust](/blog/hypershell-release#json-encoding): the post that announced Hypershell, which + introduced this program. Its code predates the current design. --- diff --git a/docs/projects/hypershell/examples/save-webpage.md b/docs/projects/hypershell/examples/save-webpage.md index e0a1efd0..074aee56 100644 --- a/docs/projects/hypershell/examples/save-webpage.md +++ b/docs/projects/hypershell/examples/save-webpage.md @@ -113,6 +113,8 @@ a compile error at the call rather than from a declaration. each stage accepts and produces. - [Handlers](/docs/concepts/handlers): the computation interface whose output type the program's signature follows from. +- [Hypershell: a type-level DSL for shell-scripting in Rust](/blog/hypershell-release): the post + that announced Hypershell, with the project's motivation. Its code predates the current design. --- diff --git a/docs/projects/hypershell/index.md b/docs/projects/hypershell/index.md index 12754a49..fdb08b30 100644 --- a/docs/projects/hypershell/index.md +++ b/docs/projects/hypershell/index.md @@ -166,7 +166,7 @@ version of CGP with a different design, and the code on these pages does not com - [Type-level DSLs](/docs/concepts/type-level-dsls): the CGP technique behind Hypershell, explained with a smaller language. - [Hello World](/docs/tutorials/hello): a first CGP program, for a reader new to CGP. -- [Hypershell: a type-level DSL for shell-scripting](/blog/hypershell-release): the post that +- [Hypershell: a type-level DSL for shell-scripting in Rust](/blog/hypershell-release): the post that announced the project, with its history and motivation. Its code predates the current design. --- From 9c6f1ce31cdeed5cffd469f6c80e30f803e9be7a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 10:49:41 +0000 Subject: [PATCH 105/516] Correct reference and comparison pages the KB review found stale - Comparisons: give HasErrorType the #[prefix] line its source carries (implicit parameters, ML modules), make the dependency-injection storage component async like the example it comes from, and import the error keys and RaiseFrom in the algebraic-effects wiring. The example-code mirrors follow and pass. - Reference: drop the #[diagnostic::on_unimplemented] notes IsProviderFor, HasField, and HasFieldMut no longer carry; say MapFields rewrites provider lists rather than building the partial records; say FinalizeOptional names the last unset field; state that the err monad handles the outer Result in OkMonadicTrans across the monad pages; add cgp_component's generic-name rules and its two expansion failures. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/comparisons/algebraic-effects.md | 3 ++ docs/comparisons/dependency-injection.md | 3 +- docs/comparisons/implicit-parameters.md | 1 + docs/comparisons/ml-modules.md | 1 + docs/reference/macros/cgp_component.md | 27 ++++++++++++- .../reference/providers/monad/pipe_monadic.md | 5 ++- .../traits/builder/finalize_build.md | 2 +- .../traits/field-access/has_field.md | 5 +-- .../traits/field-access/has_field_mut.md | 5 +-- docs/reference/traits/monad/contains_value.md | 5 ++- docs/reference/traits/monad/monadic_bind.md | 5 ++- docs/reference/traits/monad/monadic_trans.md | 15 +++---- .../traits/optional/finalize_optional.md | 21 +++++----- .../traits/optional/has_optional_builder.md | 2 +- docs/reference/traits/optional/index.md | 2 +- .../reference/traits/type-level/map_fields.md | 40 ++++++++++--------- .../traits/wiring/is_provider_for.md | 13 ++---- .../tests/comparisons/dependency_injection.rs | 12 +++--- .../tests/comparisons/implicit_parameters.rs | 1 + example-code/tests/comparisons/ml_modules.rs | 1 + 20 files changed, 102 insertions(+), 67 deletions(-) diff --git a/docs/comparisons/algebraic-effects.md b/docs/comparisons/algebraic-effects.md index e6e2ae6c..2fe21ce8 100644 --- a/docs/comparisons/algebraic-effects.md +++ b/docs/comparisons/algebraic-effects.md @@ -244,6 +244,9 @@ impl Loader { The context chooses both the error type and the provider used for each source error type: ```rust +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; + delegate_components! { App { open ErrorRaiserComponent; diff --git a/docs/comparisons/dependency-injection.md b/docs/comparisons/dependency-injection.md index f60faa31..56c26cb0 100644 --- a/docs/comparisons/dependency-injection.md +++ b/docs/comparisons/dependency-injection.md @@ -165,9 +165,10 @@ A [`delegate_components!`](/docs/reference/macros/delegate_components) table sel for each component. These contexts choose different storage implementations for the same interface: ```rust +#[async_trait] #[cgp_component(StorageObjectFetcher)] pub trait CanFetchStorageObject { - fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + async fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; } delegate_components! { diff --git a/docs/comparisons/implicit-parameters.md b/docs/comparisons/implicit-parameters.md index ebf3e333..5e9abcf9 100644 --- a/docs/comparisons/implicit-parameters.md +++ b/docs/comparisons/implicit-parameters.md @@ -174,6 +174,7 @@ class Monad m => MonadError e m | m -> e where ```rust #[cgp_type] +#[prefix(@cgp.core.error in DefaultNamespace)] pub trait HasErrorType { type Error: Debug; } diff --git a/docs/comparisons/ml-modules.md b/docs/comparisons/ml-modules.md index d4bfe492..adfab06c 100644 --- a/docs/comparisons/ml-modules.md +++ b/docs/comparisons/ml-modules.md @@ -186,6 +186,7 @@ An abstract-type component lets generic code use a type that the context supplie ```rust #[cgp_type] +#[prefix(@cgp.core.error in DefaultNamespace)] pub trait HasErrorType { type Error: Debug; } diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index d97a833b..8bfaa564 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -399,7 +399,14 @@ ComponentName -> IDENTIFIER GenericArgs? `ProviderName` is shorthand for setting `provider` alone. In the key/value form each key may appear at most once, in any order, and `provider` is required. `IDENTIFIER` is a Rust identifier token, and `GenericArgs` is the Rust grammar's `< … >` argument list, so the component name may carry generic -parameters while the provider name may not. The attribute delimiter, `(...)` for the bare form and +parameters while the provider name may not. + +The component name's parameters must be bare names, such as `name: ShapeComponent`, which the +marker struct then declares. A bound fails with ``trait bounds (`A: Clone`) are not allowed in type +generics``, a default with ``default type parameters (`A = B`) are not allowed in type generics``, +and a concrete type does not parse. A provider for such a component names the component explicitly, +as in `#[cgp_impl(new SquareArea: AreaCalculatorComponent)]`, because the default +`{Provider}Component` name carries no arguments. The attribute delimiter, `(...)` for the bare form and `{...}` for the key/value form, is ordinary Rust attribute syntax and does not change how the macro parses the arguments inside. @@ -420,6 +427,24 @@ parameter, and a provider supplies it in the ordinary way. Naming your own assoc *inside* a [`#[cgp_impl]`](./cgp_impl.md) body has one complication of its own, covered in that page's [Common Mistakes](./cgp_impl.md#common-mistakes). +**Every method parameter needs a plain name.** The impls the macro generates forward each argument to +the provider by name, so a `_` parameter, which Rust allows in a trait method without a body, or a +destructuring pattern such as `(a, b): (u32, u32)` in a default method fails inside the macro: + +```text +error: expected identifier, found keyword `_` +error: failed to parse internal tokens to type `proc_macro2::Ident`: + _ +``` + +Name the parameter instead, as in `_value: u32`, and destructure inside a default method's body. + +**A const parameter in the `name:` list fails inside the macro.** +`#[cgp_component { provider: Buffer, name: BufferComponent }]` is accepted by the +parser, but the name is then used in type positions, where the const parameter cannot appear, and +the macro fails with ``failed to parse internal tokens to type `syn::generics::TypeParamBound` ``. +Keep the name's parameters to bare type names, as the component's own parameters are. + **The attribute must be applied to a trait.** The macro refuses a struct, an enum, or a free function at parse time, with an error that names the trait it expected, instead of lowering it into code that fails to compile later. diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index c0f164b2..8f6c7147 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -50,8 +50,9 @@ PipeMonadic::::compute(&c ``` Stacking monads handles nested results. Composing handlers that return `Result, &str>` -under `OkMonadicTrans` short-circuits on the outer `Ok` while threading the inner `Result` -through the err monad, and the same list composed under `OkMonadic` can be driven through the fallible +under `OkMonadicTrans` stops on an outer `Err` or an inner `Ok`: the err monad handles the +outer `Result` and the ok layer the one inside it. The same list composed under `OkMonadic` can be +driven through the fallible `try_compute` and async `handle` entry points, because `PipeMonadic` implements `TryComputer` and `Handler` as well: diff --git a/docs/reference/traits/builder/finalize_build.md b/docs/reference/traits/builder/finalize_build.md index 197c287b..89d0da47 100644 --- a/docs/reference/traits/builder/finalize_build.md +++ b/docs/reference/traits/builder/finalize_build.md @@ -108,7 +108,7 @@ forgot, and it is the only place the compiler names it. from `Default` rather than rejected. It re-marks every field to `IsPresent` and then calls this, so the strict check still runs and always passes. - **Use [`FinalizeOptional`](../optional/finalize_optional.md)** when absence should be *reported* at run time - rather than caught at compile time. It returns a `Result` naming the first missing field. + rather than caught at compile time. It returns a `Result` naming a missing field. - **Stay with `FinalizeBuild`** when every field is genuinely required. Moving to either of the other two gives up the compile-time completeness check, which is the reason the family exists. diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index fbe66f77..0073d6ce 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -49,10 +49,7 @@ type so a bound can pin it or leave it open: `HasField` accepts while `HasField` requires a `String`. `get_field` takes `&self` and returns `&Self::Value`, a borrow of the field; its `PhantomData` argument carries no data and only lets a call site say *which* field it means when several `HasField` impls are in scope, which is why a -read is written `self.get_field(PhantomData::)`. The trait also carries a -`#[diagnostic::on_unimplemented]` note pointing at -[`#[derive(HasField)]`](../../derives/derive_has_field.md), so a missing field reads as a missing derive -rather than an opaque trait failure. +read is written `self.get_field(PhantomData::)`. ## Usage diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index f07cb666..eb98b09f 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -52,9 +52,8 @@ An implementation that mutates declares the bound on `Self` the same way it decl Self: HasFieldMut ``` -Like its supertrait it carries a diagnostic note pointing at -[`#[derive(HasField)]`](../../derives/derive_has_field.md), so an unsatisfied bound reads as a missing -derive. +[`#[derive(HasField)]`](../../derives/derive_has_field.md) generates it beside `HasField` for every +field. ## Examples diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index 0c07eca1..afad374f 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -77,8 +77,9 @@ So under `ErrMonadic` a step's continuation receives the `Ok` payload, the ordin under `OkMonadic` it receives the `Err` payload, which is the inverted, run-until-something-succeeds behaviour. -**The transformer forms peel one layer.** `OkMonadicTrans` and `ErrMonadicTrans` remove their own -`Result` layer and hand the rest to `M`, requiring `M: ContainsValue>`. A two-layer +**The transformer forms peel one layer.** `OkMonadicTrans` and `ErrMonadicTrans` let `M` unwrap the +outer layers and then remove their own `Result` from the value `M` exposes, requiring +`M: ContainsValue>`. A two-layer stack therefore unwraps two `Result` layers in order, and an *n*-layer stack unwraps *n*, with no code specific to any depth. diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index ac7ba24c..0ed27034 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -87,8 +87,9 @@ over a `Result`: So `ErrMonadic` gives the ordinary `?` behaviour, and `OkMonadic` the inverted one that runs until something succeeds, useful for a fallback chain. -**The transformer forms delegate one layer down.** `OkMonadicTrans` and `ErrMonadicTrans` bind their -own `Result` layer and hand the rest to `M`, which is how a stack reaches arbitrary depth. +**The transformer forms delegate to their base.** `OkMonadicTrans` and `ErrMonadicTrans` wrap their +own bind provider for the inner `Result` layer and hand it to `M`, which binds the outer layers, and +that is how a stack reaches arbitrary depth. ## When to use it diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index a24bf4db..d10cd204 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -45,9 +45,9 @@ pub trait MonadicTrans { ``` `Self` is the monad being applied, the `M` parameter is the base monad being transformed, and the -associated `M`, which shares the parameter's name, is the resulting stack. That lets `OkMonadic` be -written as `OkMonadicTrans` when a pipeline operates over a nested result, layering one -behaviour on top of another. +associated `M`, which shares the parameter's name, is the resulting stack. Applying `OkMonadic` to +`ErrMonadic` gives `OkMonadicTrans`, for a pipeline that operates over a nested result: +the err monad handles the outer `Result` of each output, and the ok layer the `Result` inside it. ## Usage @@ -69,12 +69,13 @@ What each marker's impl says decides how deeply a pipeline can reach. it the neutral element of a stack as well as of a pipeline. **The transformer forms compose.** `OkMonadicTrans` and `ErrMonadicTrans` implement the running -traits by peeling their own `Result` layer and handing the rest to `M`, and their `MonadicTrans` impls -compose in the same order, so a stack like `OkMonadicTrans` resolves layer by layer: +traits by letting `M` unwrap the outer layers and then peeling their own `Result` from the value `M` +exposes, and their `MonadicTrans` impls compose in the same order, so a stack like +`OkMonadicTrans` resolves layer by layer: ```rust -// conceptually: unwrap the outer Result the OkMonadic way, -// then hand the inner Result to ErrMonadic +// conceptually: ErrMonadic unwraps the outer Result, +// then the Ok layer handles the Result inside it type Stacked = OkMonadicTrans; ``` diff --git a/docs/reference/traits/optional/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md index d49326ed..46c2b9eb 100644 --- a/docs/reference/traits/optional/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -5,14 +5,14 @@ sidebar_position: 4 # `FinalizeOptional` -Finalizing an optional builder, reporting the first missing field. +Finalizing an optional builder, reporting a missing field. ## Overview An [optional builder](./has_optional_builder.md) has given up the compile-time completeness check: every field is `IsOptional`, so the type no longer records what has been set. Something has to check at run time instead, and `FinalizeOptional` is the strict way to do it: it succeeds only if every field holds a -value, and otherwise reports the first missing field by name. +value, and otherwise reports a missing field by name. It is one of two endings for an optional builder, and the choice between them is made at the call site rather than when the builder is created: @@ -36,7 +36,7 @@ pub trait FinalizeOptional: PartialData { The `PartialData` [supertrait](/docs/reference/glossary#supertrait) supplies `Target`, the concrete struct being built, so the method projects its return type through it and declares no associated type of its own. `finalize_optional` takes `self`, consuming the builder, and returns `Result`: the built struct on success, -or, on failure, the first missing field's own name, recovered from its type-level tag as a `&'static +or, on failure, a missing field's own name, recovered from its type-level tag as a `&'static str` with no allocation. The trait carries no other parameter. It is not in the prelude; import it from `cgp-field-extra`. @@ -107,7 +107,8 @@ Unlike its defaulting sibling, `FinalizeOptional` does **not** go through [`TransformMapFields`](../type-level/transform_map_fields.md). It walks the target's [`HasFields`](../shape/has_fields.md) list directly, and the reason is that it has to be able to *stop*. -For each field it pulls the `Option` out with [`UpdateField`](../builder/update_field.md), and: +It checks the rest of the list before the current field, so the fields are checked from last to +first. For each field it pulls the `Option` out with [`UpdateField`](../builder/update_field.md), and: - if it is `Some`, writes the value back as `IsPresent` with [`BuildField`](../builder/build_field.md) and continues; @@ -121,14 +122,16 @@ Only if every field yields a value does the walk reach the all-present configura becomes a concrete struct.** Everything in this layer simply guarantees that configuration is reached before it is invoked, or reports why it could not be. -That short-circuiting is also why only the *first* missing field is named: the walk stops at it rather -than collecting. +That short-circuiting is also why only one missing field is named: the walk stops at the first +`None` it meets rather than collecting. Because the walk runs from the last field back, that is the +last unset field in declaration order: with nothing set on `struct Context { foo: String, bar: u64 }`, +the error is `"bar"`. ## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. -**The error is a `&'static str`.** It names the first missing field and is not a structured error, so it +**The error is a `&'static str`.** It names one missing field and is not a structured error, so it cannot be matched on beyond string comparison. **It reports only the first.** A builder missing three fields yields one name. @@ -139,8 +142,8 @@ finalizes at compile time or does not. **It supertraits [`PartialData`](../builder/partial_data.md)**, so `Target` is projected from there and naming both in a bound is redundant. -**Field order decides which name you get**, since the walk follows declaration order and stops at the -first `None`. +**Field order decides which name you get**, since the walk runs from the last declared field back and +stops at the first `None` it meets, so the name is the last unset field in declaration order. ## Related constructs diff --git a/docs/reference/traits/optional/has_optional_builder.md b/docs/reference/traits/optional/has_optional_builder.md index d9760019..68c03662 100644 --- a/docs/reference/traits/optional/has_optional_builder.md +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -57,7 +57,7 @@ The impls are blanket ones over the core builder machinery, so any record derivi [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md)) gets this for free. There is no separate derive. **Two endings are available**, and picking between them at the call site is the layer's real payoff: -[`FinalizeOptional`](./finalize_optional.md) requires every field and reports the first missing one, while +[`FinalizeOptional`](./finalize_optional.md) requires every field and reports a missing one, while [`CanFinalizeWithDefault`](./can_finalize_with_default.md) fills unset fields from `Default`. ## Examples diff --git a/docs/reference/traits/optional/index.md b/docs/reference/traits/optional/index.md index 908bb6a9..6ef27ca6 100644 --- a/docs/reference/traits/optional/index.md +++ b/docs/reference/traits/optional/index.md @@ -26,7 +26,7 @@ converts an existing builder into one. because an optional field's marker does not change when it is written. The **two endings** are chosen at the finalize call rather than when the builder is made. -[`FinalizeOptional`](finalize_optional.md) requires every field and reports the first missing one, while +[`FinalizeOptional`](finalize_optional.md) requires every field and reports a missing one, while [`CanFinalizeWithDefault`](can_finalize_with_default.md) fills a missing field from `Default`. [`CanBuildWithDefault`](can_build_with_default.md) chains a merge and a defaulted finalize into one call. diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index d208f0fb..6f47f335 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -11,19 +11,22 @@ Rewriting every entry of a type-level list through one marker. ### Generated machinery -**You are not expected to use `MapFields` directly.** It is the type-level operation -behind a [partial record](/docs/reference/glossary#partial-record)'s shape, computed by the machinery -[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) generates. You will most likely meet it in an error -message; this page explains what it produces, and how it differs from the two similarly-named traits -beside it. The one case for naming it is generic code that must describe a uniformly re-wrapped shape. +**You are not expected to use `MapFields` directly.** CGP uses it to rewrite lists of providers: +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) maps its handler list through a promotion +marker, and the record builder's `BuildAndMergeOutputs` maps its handler list the same way. You will +most likely meet it in an error message from one of those; this page explains what it produces, and +how it differs from the two similarly-named traits beside it. The one case for naming it is generic +code that must describe a uniformly re-wrapped shape. ::: ## Overview -A partial record is the same record with every field's storage changed the same way: each value wrapped -in an `Option`, or replaced by `()`, or left alone. Describing that as a type means rewriting every entry -of the shape uniformly, and `MapFields` is that operation. +Some type-level lists need every entry changed the same way: each value wrapped in an `Option`, or +replaced by `()`, or each provider wrapped in an adapter. Describing that as a type means rewriting +every entry of the list uniformly, and `MapFields` is that operation. The partial records and +enums of the extensible-data derives are not computed with it; [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) +generates those types directly. The list's length and order never change. Each entry type `T` becomes `Mapper::Map`, where the mapper is a [`MapType`](./map_type.md) marker, so **the marker decides the whole effect**. With `IsPresent` it @@ -31,8 +34,8 @@ is the identity; with `IsNothing` every entry collapses to `()`; with `IsOptiona `Option<_>`; with `IsVoid` every entry becomes uninhabited. It is the transforming member of the three product operations, and the only one defined over **both** -lists: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum. That lets one -operation produce both a partial record and a partial enum. +lists: it walks `Cons`/`Nil` for a product and `Either`/`Void` for a sum, so one marker applies to +either. ## Definition @@ -63,8 +66,7 @@ use cgp::core::field::traits::MapFields; ## Examples -Applying `IsOptional` turns a product of values into a product of optionals, the shape a partial builder -uses to track what is not yet filled: +Applying `IsOptional` turns a product of values into a product of optionals: ```rust use cgp::core::field::impls::IsOptional; @@ -77,8 +79,7 @@ type Optional = >::Mapped; // = Product![Option, Option, Option] ``` -The same marker applies over a sum, which makes one operation serve both halves of the -extensible-data machinery: +The same marker applies over a sum: ```rust type Variants = Sum![String, u16]; @@ -89,8 +90,8 @@ type OptionalVariants = >::Mapped; ## When to use it -**Reach for it when generic code must name a uniformly re-wrapped shape**, the form a partial -representation takes, and essentially never otherwise. +**Reach for it when generic code must name a uniformly re-wrapped list**, such as a list of +providers each wrapped in the same adapter, and essentially never otherwise. - **Reach for [`AppendProduct`](./append_product.md) or [`ConcatProduct`](./concat_product.md)** when the shape grows rather than changing its wrapping. @@ -139,7 +140,7 @@ needs its own import from `cgp::core::field::impls`. [`ConcatProduct`](./concat_product.md) both expose `Output`, and this one does not. **It computes types, not values.** A `MapFields` result does not wrap anything at run time. -Something still has to build the wrapped values, which on a partial record is +Something still has to build the wrapped values, such as [`TransformMapFields`](./transform_map_fields.md). **A marker with no `MapType` impl does not resolve**, and the error names the missing `MapType` bound @@ -165,8 +166,9 @@ width. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records): presence tracking on a partial record. -- [Extensible variants](/docs/concepts/extensible-variants): possibility tracking on a partial variant. +- [Monadic handlers](/docs/concepts/monadic-handlers): the handler pipelines whose provider lists it + rewrites. +- [Extensible records](/docs/concepts/extensible-records): the builder whose handler list it rewrites. ## Source diff --git a/docs/reference/traits/wiring/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md index 1ab6344b..f9965489 100644 --- a/docs/reference/traits/wiring/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -43,12 +43,9 @@ the mechanism [`check_components!`](../../macros/check_components.md) leans on t ## Definition -`IsProviderFor` is an empty marker trait with three type parameters and a diagnostic note: +`IsProviderFor` is an empty marker trait with three type parameters: ```rust -#[diagnostic::on_unimplemented( - note = "You need to add `#[cgp_provider({Component})]` on the impl block for CGP provider traits" -)] pub trait IsProviderFor {} ``` @@ -60,8 +57,6 @@ several parameters are grouped is covered under [How `Params` is filled](#how-pa trait has no method and no associated item. [`#[cgp_component]`](../../macros/cgp_component.md) attaches it as a supertrait on every provider trait, so using a provider trait requires establishing `IsProviderFor` first, which is why probing the marker probes the provider trait's whole dependency set. -The `#[diagnostic::on_unimplemented]` note points a reader at the missing `#[cgp_provider]` attribute when -the marker impl is absent. ## Usage @@ -159,8 +154,8 @@ Two situations do put its name in your hands, and both are about diagnosis rathe If you find yourself wanting to implement it by hand, the thing you actually want is [`#[cgp_provider]`](../../macros/cgp_provider.md) or [`#[cgp_impl]`](../../macros/cgp_impl.md) on the impl block. -The trait's own diagnostic says so, which is the one case where a missing marker impl is the reported -problem rather than the hidden one. +A provider-trait impl written without either attribute is the one case where a missing marker impl is +the reported problem rather than the hidden one. ## Under the hood @@ -228,7 +223,7 @@ lifetime in a type position, so it is lifted. **A missing marker impl usually means a missing attribute.** If the compiler says a provider does not implement `IsProviderFor`, the likeliest cause is a provider-trait impl written without -[`#[cgp_provider]`](../../macros/cgp_provider.md). The trait's own diagnostic note says exactly this. +[`#[cgp_provider]`](../../macros/cgp_provider.md). **Read it as "because", not as "instead".** `GreetHello: IsProviderFor<…> is not satisfied` does not mean the marker is the problem; it means the provider trait is not implemented *because* the named dependency is diff --git a/example-code/tests/comparisons/dependency_injection.rs b/example-code/tests/comparisons/dependency_injection.rs index 4b1089f1..6527d50d 100644 --- a/example-code/tests/comparisons/dependency_injection.rs +++ b/example-code/tests/comparisons/dependency_injection.rs @@ -111,14 +111,15 @@ pub mod impl_side_dependencies_are_constructor_parameters { pub mod wiring_is_the_container_configuration { use cgp::prelude::*; + #[async_trait] #[cgp_component(StorageObjectFetcher)] pub trait CanFetchStorageObject { - fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; + async fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result>; } #[cgp_impl(new FetchS3Object)] impl StorageObjectFetcher { - fn fetch_storage_object( + async fn fetch_storage_object( &self, #[implicit] s3_bucket: &str, object_id: &str, @@ -130,7 +131,7 @@ pub mod wiring_is_the_container_configuration { #[cgp_impl(new FetchGCloudObject)] impl StorageObjectFetcher { - fn fetch_storage_object( + async fn fetch_storage_object( &self, #[implicit] gcloud_bucket: &str, object_id: &str, @@ -178,6 +179,7 @@ pub mod wiring_is_the_container_configuration { #[test] fn two_deployments_two_bindings() { + use futures::executor::block_on; let app = App { s3_bucket: "pictures".to_owned(), }; @@ -185,11 +187,11 @@ pub mod wiring_is_the_container_configuration { gcloud_bucket: "pictures".to_owned(), }; assert_eq!( - app.fetch_storage_object("ada.png").unwrap(), + block_on(app.fetch_storage_object("ada.png")).unwrap(), b"s3://pictures/ada.png".to_vec() ); assert_eq!( - gcloud.fetch_storage_object("ada.png").unwrap(), + block_on(gcloud.fetch_storage_object("ada.png")).unwrap(), b"gs://pictures/ada.png".to_vec() ); } diff --git a/example-code/tests/comparisons/implicit_parameters.rs b/example-code/tests/comparisons/implicit_parameters.rs index 1310bc08..2781be50 100644 --- a/example-code/tests/comparisons/implicit_parameters.rs +++ b/example-code/tests/comparisons/implicit_parameters.rs @@ -33,6 +33,7 @@ pub mod abstract_types_are_implicit_type_parameters { // The page shows CGP's own `HasErrorType`; the local declaration shadows the prelude's here. #[cgp_type] + #[prefix(@cgp.core.error in DefaultNamespace)] pub trait HasErrorType { type Error: Debug; } diff --git a/example-code/tests/comparisons/ml_modules.rs b/example-code/tests/comparisons/ml_modules.rs index 7d1be224..e9d9bc63 100644 --- a/example-code/tests/comparisons/ml_modules.rs +++ b/example-code/tests/comparisons/ml_modules.rs @@ -63,6 +63,7 @@ pub mod abstract_type_components { // The page shows CGP's own `HasErrorType`; declaring it locally shows the shape the library's // definition has, and the local name shadows the prelude's within this module. #[cgp_type] + #[prefix(@cgp.core.error in DefaultNamespace)] pub trait HasErrorType { type Error: Debug; } From d1f4529414e86c880cfae970792e3a55c1fb4012 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 10:50:10 +0000 Subject: [PATCH 106/516] Correct AGENTS.md on the skill pages and #[cgp_provider] The pages under docs/ai/skills/ are symlinks into the cgp-skills submodule, not a re-inlined copy, and #[cgp_provider] still compiles; it is demoted, not removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- AGENTS.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0d50b6b7..a69ce266 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ The sibling repositories worth knowing about are the same ones the knowledge bas [`cgp`](https://github.com/contextgeneric/cgp) is the library and the ground truth for any code claim, [`cargo-cgp`](https://github.com/contextgeneric/cargo-cgp) is the error toolchain, [`cgp-skills`](https://github.com/contextgeneric/cgp-skills) is the source of the agent skill this -site inlines under `docs/ai/`, and [`hypershell`](https://github.com/contextgeneric/hypershell) and +site publishes under `docs/ai/skills/` through a submodule, and [`hypershell`](https://github.com/contextgeneric/hypershell) and [`cgp-serde`](https://github.com/contextgeneric/cgp-serde) are the projects built with CGP. ## Never link from a published page into the knowledge base @@ -63,7 +63,8 @@ ones that merely still parse. **Never copy current syntax out of an existing blog post on this site.** Almost every post predates the current release, and the drift is not cosmetic — posts from as recently as 2026 show `#[cgp_context]`, `cgp_preset!`, `#[cgp_inherit]`, `HasCgpProvider`, the `Async` trait, `ProvideType`, -`symbol!`, and inside-out `#[cgp_provider]` implementations, none of which are current. The knowledge +and `symbol!`, none of which exist in the current release, and inside-out `#[cgp_provider]` +implementations, which still compile but are what current code reads rather than writes. The knowledge base's document for each post lists exactly what is stale in it, and its [`releases/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/releases) section carries a removal ledger that dates every renamed or deleted construct in one table. The safest source of @@ -137,9 +138,11 @@ existing release slugs are inconsistent — dash-separated versions through v0.6 so match a new post to its neighbours rather than assuming one rule. Docs pages set `sidebar_position` and are grouped by directory, with each directory's label and -position in its `_category_.json`. The `docs/ai/` tree is a **published copy** of the agent skill from -[`cgp-skills`](https://github.com/contextgeneric/cgp-skills); never fix the skill by editing the copy — -correct it upstream and re-inline the result, or the two versions diverge. +position in its `_category_.json`. The pages under `docs/ai/skills/` other than `index.md` are +**symlinks** into the [`cgp-skills`](https://github.com/contextgeneric/cgp-skills) submodule at the +repository root, pinned to one revision. Never edit them, since an edit lands in the submodule's +working tree; correct the skill in `cgp-skills`, and leave the submodule pointer for the author to +advance. The `notes/` directory is working material rather than site content: a local mirror of the [Diátaxis](https://diataxis.fr/) documentation framework, and a research note comparing CGP's implicit From 2457b9e304256947ddd2174fcfe51cc746539b95 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 11:03:09 +0000 Subject: [PATCH 107/516] Say owned implicit arguments are cloned, not copied The Context-Generic Functions tutorial said an owned implicit argument needs Copy. The expansion calls .clone() on the borrowed field, so the requirement is Clone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/tutorials/area-calculation/context-generic-functions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorials/area-calculation/context-generic-functions.md b/docs/tutorials/area-calculation/context-generic-functions.md index 338553d9..f4be1c94 100644 --- a/docs/tutorials/area-calculation/context-generic-functions.md +++ b/docs/tutorials/area-calculation/context-generic-functions.md @@ -189,7 +189,7 @@ Inside the function body, the macro desugars the implicit arguments into local ` ### Borrowed vs owned implicit arguments -The `width()` and `height()` methods on `RectangleFields` return a borrowed `&f64`. This is because all field access are by default done through borrowing the field value from `&self`. However, when the implicit argument is an *owned value*, CGP will automatically copy on the field value and require that the `Copy` bound of the type is satisfied. +The `width()` and `height()` methods on `RectangleFields` return a borrowed `&f64`. This is because all field access are by default done through borrowing the field value from `&self`. However, when the implicit argument is an *owned value*, CGP will automatically call `.clone()` on the borrowed field value, so the field's type must implement `Clone`. We can rewrite the `rectangle_area` to accept the implicit `width` and `height` arguments as *borrowed* references, such as: From 77315c20b9217ade0ff87fc8b6326518a96d0c39 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 11:10:15 +0000 Subject: [PATCH 108/516] Say `cargo cgp expand --help` prints the expand options The tool answers --help in expand itself and documents --item there; the page said the flag was forwarded to cargo rustc and so undiscoverable. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/cargo-cgp/expand.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 73eaffd5..74dba438 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -121,9 +121,9 @@ cargo cgp expand --lib > expanded.rs cargo cgp expand --lib | rg 'Symbol!' ``` -`cargo cgp expand --help` forwards like everything else, so what you get is `cargo rustc`'s own help — -which does **not** mention `--item`, since that flag is the tool's rather than cargo's. This page is -where you learn it exists. +`cargo cgp expand --help` is the one argument the tool answers itself rather than forwarding: it +prints the expand options, including `--item`, with examples. For cargo's own target-selection +options, run `cargo rustc --help`. ## Why not `cargo-expand` From d7b956d97f8ee2fec0aeec21b989b1aeb1a534c2 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 13:34:58 +0000 Subject: [PATCH 109/516] Revise the M1 macro reference pages against the source Resync #[cgp_component], #[cgp_impl], #[cgp_provider]/#[cgp_new_provider], #[cgp_fn], and #[cgp_type] with their internal documents and the macro source, and revise their prose. Probing every quoted error corrected several claims: a forwarded attribute is reported once, a wrong #[cgp_provider] component fails at the impl, #[default_impl] takes one spec per attribute, and #[cgp_fn]'s implicit bounds precede #[use_type] and #[use_provider]. Examples gain check_components! and value-context notes, and #[cgp_impl] now teaches #[uses] and #[implicit]. Add an example-code mirror for all five pages and a trybuild fixture for each rejected snippet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/cgp_component.md | 219 ++++-- docs/reference/macros/cgp_fn.md | 32 +- docs/reference/macros/cgp_impl.md | 124 +++- docs/reference/macros/cgp_provider.md | 90 ++- docs/reference/macros/cgp_type.md | 62 +- example-code/README.md | 2 +- ...common_mistakes_const_generic_parameter.rs | 11 + ...on_mistakes_const_generic_parameter.stderr | 5 + ...common_mistakes_const_parameter_in_name.rs | 11 + ...on_mistakes_const_parameter_in_name.stderr | 14 + ...ommon_mistakes_duplicate_use_type_alias.rs | 12 + ...n_mistakes_duplicate_use_type_alias.stderr | 5 + ...omponent_common_mistakes_misplaced_uses.rs | 17 + ...nent_common_mistakes_misplaced_uses.stderr | 11 + ...p_component_common_mistakes_not_a_trait.rs | 12 + ...mponent_common_mistakes_not_a_trait.stderr | 5 + ...n_mistakes_undeclared_parameter_in_name.rs | 11 + ...stakes_undeclared_parameter_in_name.stderr | 35 + ...onent_common_mistakes_unnamed_parameter.rs | 11 + ...t_common_mistakes_unnamed_parameter.stderr | 12 + ...mon_mistakes_impl_generics_in_signature.rs | 22 + ...mistakes_impl_generics_in_signature.stderr | 25 + ...n_common_mistakes_implicit_without_self.rs | 10 + ...mmon_mistakes_implicit_without_self.stderr | 7 + ...mon_mistakes_mutable_implicit_not_alone.rs | 11 + ...mistakes_mutable_implicit_not_alone.stderr | 5 + ...stakes_default_impl_on_explicit_context.rs | 21 + ...es_default_impl_on_explicit_context.stderr | 8 + ...p_impl_common_mistakes_misplaced_extend.rs | 24 + ...pl_common_mistakes_misplaced_extend.stderr | 5 + ...on_mistakes_provider_const_through_self.rs | 22 + ...istakes_provider_const_through_self.stderr | 16 + ...pl_common_mistakes_self_form_and_wiring.rs | 33 + ...ommon_mistakes_self_form_and_wiring.stderr | 8 + ...l_common_mistakes_self_form_without_for.rs | 18 + ...mmon_mistakes_self_form_without_for.stderr | 5 + ...rovider_common_mistakes_ambiguous_const.rs | 24 + ...der_common_mistakes_ambiguous_const.stderr | 24 + ...gp_provider_common_mistakes_new_keyword.rs | 18 + ...rovider_common_mistakes_new_keyword.stderr | 5 + ...common_mistakes_struct_already_declared.rs | 20 + ...on_mistakes_struct_already_declared.stderr | 10 + ...rovider_common_mistakes_wrong_component.rs | 39 + ...der_common_mistakes_wrong_component.stderr | 44 ++ .../cgp_provider_refused_const_argument.rs | 19 + ...cgp_provider_refused_const_argument.stderr | 5 + .../cgp_provider_refused_inherent_impl.rs | 19 + .../cgp_provider_refused_inherent_impl.stderr | 5 + .../cgp_provider_refused_no_type_argument.rs | 19 + ...p_provider_refused_no_type_argument.stderr | 7 + ...ype_common_mistakes_bound_not_satisfied.rs | 25 + ...common_mistakes_bound_not_satisfied.stderr | 25 + ...common_mistakes_generic_associated_type.rs | 10 + ...on_mistakes_generic_associated_type.stderr | 5 + ..._common_mistakes_guessed_component_name.rs | 19 + ...mon_mistakes_guessed_component_name.stderr | 16 + ...common_mistakes_not_one_associated_type.rs | 13 + ...on_mistakes_not_one_associated_type.stderr | 5 + ...type_common_mistakes_type_shadows_bound.rs | 13 + ..._common_mistakes_type_shadows_bound.stderr | 10 + .../tests/reference/macros/cgp_component.rs | 433 ++++++++++++ example-code/tests/reference/macros/cgp_fn.rs | 268 +++++++ .../tests/reference/macros/cgp_impl.rs | 665 ++++++++++++++++++ .../tests/reference/macros/cgp_provider.rs | 387 ++++++++++ .../tests/reference/macros/cgp_type.rs | 286 ++++++++ example-code/tests/reference/macros/mod.rs | 5 + 66 files changed, 3240 insertions(+), 144 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.stderr create mode 100644 example-code/tests/reference/macros/cgp_component.rs create mode 100644 example-code/tests/reference/macros/cgp_fn.rs create mode 100644 example-code/tests/reference/macros/cgp_impl.rs create mode 100644 example-code/tests/reference/macros/cgp_provider.rs create mode 100644 example-code/tests/reference/macros/cgp_type.rs diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 8bfaa564..9168cd2b 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -12,22 +12,23 @@ target, and the key that wires them together. ## Overview -You can apply `#[cgp_component]` to any Rust trait definition to make that trait wireable, with -every implementation chosen per context. Applying it takes nothing away. The trait you wrote keeps working exactly as it -did, now under the name CGP calls the **consumer trait**, and every call site that already uses it -keeps compiling unchanged. The macro adds a matching **provider trait** for implementations to target, -a small marker type called the **component** that names the trait for wiring, and a pair of +`#[cgp_component]` turns an ordinary Rust trait into a component, so that each type using the trait +chooses which implementation it gets. Applying it takes nothing away. The trait you wrote keeps +working exactly as it did, now under the name CGP calls the **consumer trait**, and every call site +that already uses it keeps compiling unchanged. The macro adds a matching **provider trait** for +implementations to target, a small marker type called the **component** that names the trait for +wiring, and a pair of [**blanket implementations**](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) that connect them without requiring you to write anything. -`#[cgp_component]` makes it possible to define several overlapping implementations of one trait -at once. An ordinary Rust trait does not allow this. A -[trait](https://doc.rust-lang.org/book/ch10-02-traits.html) can have only one implementation per -type, a rule called [coherence](/docs/concepts/coherence). That rule is usually the right one, because -it lets the compiler resolve a `where T: Display` bound without anyone naming which implementation -applies. But it also means a trait with several plausible implementations cannot hold the -alternatives. A type can send real email or record it for a test, but never both at once. Switching -between the two means editing the impl itself rather than choosing between them at the point of use. +The macro lets one trait have several overlapping implementations at the same time, which an +ordinary Rust trait does not allow. A [trait](https://doc.rust-lang.org/book/ch10-02-traits.html) +can have only one implementation per type, a rule called [coherence](/docs/concepts/coherence). +That rule is usually the right one, because it lets the compiler resolve a `where T: Display` bound +without anyone naming which implementation applies. But it also means a trait with several plausible +implementations cannot hold the alternatives. A type can send real email or record it for a test, +but not both. Switching between the two means editing the impl itself rather than choosing between +them at the point of use. `#[cgp_component]` solves that by splitting the one trait into two, the [consumer and provider traits](/docs/concepts/consumer-and-provider-traits), so that a caller and an @@ -42,12 +43,13 @@ implementation no longer target the same trait. Moving `Self` into a parameter lets more than one implementation coexist, because each one now targets its own small type instead of the single `Self` slot every plain trait has. A **provider** is one of those targets: a zero-sized type such as `RectangleArea` without data of its own that exists only -to name one implementation. The type the methods run on is called the **context**. It -supplies whatever values an implementation needs as its own fields, and it picks the provider it wants -through [`delegate_components!`](./delegate_components.md). The generated [blanket implementations](/docs/reference/glossary#blanket-implementation) then -route a call on the consumer trait through to that choice automatically. This costs nothing at -runtime. Wiring fixes the provider once, at compile time, and the compiler turns the call into a -direct, statically-dispatched call, exactly as if you had written the implementation yourself. +to name one implementation. The type the methods run on is called the **context**, and it supplies +the values an implementation needs as its fields. The context picks the provider it wants through +[`delegate_components!`](./delegate_components.md), and the generated +[blanket implementations](/docs/reference/glossary#blanket-implementation) route a call on the +consumer trait through to that choice. Selecting the provider adds no runtime cost: the compiler +resolves the choice when it compiles the call and turns it into a direct, statically dispatched call, +as if you had written the implementation on the context yourself. The macro's remaining output is the **component** itself, a marker type such as `AreaCalculatorComponent` that names the trait and is the key `delegate_components!` wires @@ -93,13 +95,21 @@ for setting `provider` alone. | `context` | The identifier used for the generated context type parameter | `__Context__` | The `context` default is deliberately unusual so that it cannot collide with a type parameter of your -own. +own. The `name` key also accepts a list of generic parameters, as in +`name: AreaCalculatorComponent`, for a component whose marker should carry the trait's own +parameters; [Formal grammar](#formal-grammar) gives the rules. + +The trait body may declare any number of methods, associated types, and associated consts, and the +macro reproduces every one of them on the provider trait. The one declaration it refuses is a const +generic parameter on the trait itself, for the reason given under +[Common Mistakes](#common-mistakes). ### Companion attributes The attributes below may be written above the trait, beside `#[cgp_component]`, and each changes what -the macro generates. Any of them may be repeated, and all except `#[prefix]` also accept a -comma-separated list inside one attribute. +the macro generates. Any of them may be repeated. `#[use_type]` and `#[extend]` also accept a +comma-separated list inside one attribute, while `#[derive_delegate]` and `#[prefix]` take a single +entry each, so a second one needs a second attribute. | Attribute | What it adds | |---|---| @@ -142,7 +152,7 @@ component is a supertrait, written with `#[extend]`. ## Examples -A component, a provider for it, and a type that wires the two together: +A component, a provider for it, and a type that wires the two together and checks the wiring: ```rust use cgp::prelude::*; @@ -171,6 +181,12 @@ delegate_components! { } } +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + fn print_area(rect: &Rectangle) { println!("area = {}", rect.area()); } @@ -179,7 +195,15 @@ fn print_area(rect: &Rectangle) { `rect.area()` is an ordinary method call on the consumer trait. It resolves through `Rectangle`'s table, which maps `AreaCalculatorComponent` to `RectangleArea`, and `RectangleArea::area` reads the two fields to compute the result. Swapping the provider in that one wiring line changes what `rect.area()` -does, and nothing else in the program changes. +does, and nothing else in the program changes. The +[`check_components!`](./check_components.md) block makes a missing field fail at the wiring rather +than at the first call. + +`Rectangle` here is a [value context](/docs/reference/glossary#value-context): the wired type is the +shape whose area is computed. Most CGP code instead wires an +[environmental context](/docs/reference/glossary#environmental-context), a type such as `App` that +stands for one application and carries its choices. The component is written the same way for +either. ## When to use it @@ -187,7 +211,7 @@ Use `#[cgp_component]` when a trait needs **more than one implementation, and th choice belongs to the type using it.** The macro exists for that case, and it has a cost: a component is a trait, a second trait, a marker type, and a line of wiring per type. -Prefer something simpler when you can. +Prefer something simpler when you can: - **One implementation, ever.** Use [`#[cgp_fn]`](./cgp_fn.md) instead. It builds the trait straight from a function and does not need wiring. If a second implementation ever arrives, you @@ -205,6 +229,25 @@ each concrete type, as you would any Rust trait, and skip providers entirely. Na worth their cost once a second type wants the *same* implementation, or once an implementation should compose with a wrapper. +### What the trait is about + +Decide what goes in `Self` before writing the trait, because the choice cannot be revised later +without changing every caller. A component is +[self-targeted](/docs/reference/glossary#self-targeted-component) when its operation acts on `Self`, +as `CanCalculateArea` does. It is +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component) when the operation acts +on a type parameter and `Self` only supplies the choices, as in `CanEncodeValue`. A parameter +alone does not settle this: in `CanCompute` the target is `Input`, while `Code` is a +selector the wiring dispatches on. + +The choice decides how far the wiring can vary. A self-targeted component's wiring is keyed on the +type the operation acts on, so that type gets one provider for the whole program. That is no limit +when `Self` stands for an application you define, since a second application is a second type. So +default to a self-targeted operation on an environmental context. Move the target into a parameter +only when the operation is about a type you do not own *and* different applications must treat that +type differently. [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) works through the +choice. + ### How many items should a component have? A component trait is an ordinary trait. It takes as many methods, associated types, and associated @@ -258,6 +301,10 @@ pub trait AreaCalculator: } ``` +An associated type the trait declares for itself is the one `Self` the rewrite leaves alone. A +`Self::Output` in the consumer trait stays `Self::Output` in the provider trait, where it names the +provider's own `Output`, so each provider chooses the type it returns. + `IsProviderFor` *replaces* the supertrait list rather than joining it. Any supertrait the consumer trait had, whether written natively or added by `#[extend]` or `#[use_type]`, becomes a `where` predicate on the context instead. This follows from the `Self`-to-`Context` move: a supertrait @@ -285,7 +332,8 @@ rewritten but still a default. The consumer trait keeps its copy too, so the bod expansion. This is why an **empty provider impl** is meaningful, and it is how -[`UseDefault`](../providers/use_default.md) works: +[`UseDefault`](../providers/use_default.md) works. `UseDefault` is not in the prelude; import it from +`cgp::core::component`: ```rust #[cgp_impl(UseDefault)] @@ -342,30 +390,45 @@ always emits the `UseContext` and `RedirectLookup` impls, and it generates the ` namespace impls one per attribute: - A [`UseContext`](../providers/use_context.md) impl, so the provider trait can be satisfied by - routing back through the context's own implementation. Its only bound is - `Context: CanCalculateArea`, and each method forwards to the consumer method. + routing back through the context's own implementation. It requires `Context: CanCalculateArea` + on top of any supertrait predicate the provider trait carries, and each method forwards to the + consumer method. - A [`RedirectLookup`](../providers/redirect_lookup.md) impl, which the `open` statement and - [namespaces](./cgp_namespace.md) resolve through. + [namespaces](./cgp_namespace.md) resolve through. It is written for + `RedirectLookup<__Components__, __Path__>` and looks the component up as + `__Components__: DelegateComponent<__Path__>`. - One [`UseDelegate`](../providers/use_delegate.md) impl per [`#[derive_delegate(...)]`](../attributes/derive_delegate.md) attribute. - One namespace impl per [`#[prefix(@path in Namespace)]`](../attributes/prefix.md) attribute, binding the component's key inside that namespace to a redirect down the given path. +Each of the first three comes with a matching `IsProviderFor` impl under the same `where` clause, so +a component wired to `UseContext`, reached through `open`, or dispatched through `UseDelegate` still +reports a missing dependency by name. The `RedirectLookup` one additionally requires the provider it +redirects to to be `IsProviderFor` the component, which is how a missing dependency is reported +through an `open` entry or a namespace path. The namespace impls carry none, since they are table +entries rather than providers. + The `RedirectLookup` impl puts a component's own type parameters into a path, and it makes per-type wiring such as `@AreaCalculatorComponent.Rectangle` resolve. That entry presumes a generic `CanCalculateArea`, as in the table below, rather than the parameterless component this page defines. For such a component the impl does not look the incoming path up directly. It appends the parameters to the path first, so a lookup for `CanCalculateArea` that arrives at -`@AreaCalculatorComponent` ends up looking for `@AreaCalculatorComponent.Rectangle`. Only *type* -parameters take part. A lifetime or a const parameter cannot key a path, so the impl leaves it out. +`@AreaCalculatorComponent` ends up looking for `@AreaCalculatorComponent.Rectangle`. Several type +parameters are appended in declaration order. Only *type* parameters take part: a lifetime or a const +parameter cannot key a path, so the impl leaves it out. Some details of the real output differ from the listings above, and each is easy to misread in an error. The generated parameters carry **reserved names**: the context is literally `__Context__` -unless you override it, and the provider parameter is `__Provider__`. The readable `Context` and -`Provider` here are for legibility only. Also, a component with parameters of its own appends them -*after* the context in the provider trait. Lifetimes are the exception, because Rust requires them to -lead. The macro also groups those parameters into the `IsProviderFor` parameter tuple. That tuple -holds types, so it lifts a lifetime into [`Life<'a>`](../types/life.md): +unless you override it, and the provider parameter is `__Provider__`. The provider trait's receiver +is `__context__`, the context name in snake case. A name that does not already start with an +underscore is wrapped in double underscores, so `context: Ctx` gives a `__ctx__` receiver. The +readable `Context`, `context`, and `Provider` here are for legibility only. + +A component with parameters of its own appends them *after* the context in the provider trait. +Lifetimes are the exception, because Rust requires them to lead. The macro also groups those +parameters into the `IsProviderFor` parameter tuple. That tuple holds types, so it lifts a lifetime +into [`Life<'a>`](../types/life.md): | Component | Provider trait | `IsProviderFor` params | |---|---|---| @@ -374,10 +437,20 @@ holds types, so it lifts a lifetime into [`Life<'a>`](../types/life.md): | `CanEncode` | `Encoder<__Context__, Value, Format>` | `(Value, Format)` | | `HasReference<'a, T>` | `ReferenceGetter<'a, __Context__, T>` | `(Life<'a>, T)` | -The tuple drops bounds and defaults, and it names the parameters positionally and nothing more. A -const parameter cannot appear in it at all, which is why the macro rejects one; see +The tuple drops bounds and defaults, and it names the parameters positionally and nothing more. The +single-parameter `(Shape)` has no trailing comma, so it is the type `Shape` in parentheses rather +than a one-element tuple, and every place the macro writes the tuple agrees on that. A const +parameter cannot appear in it at all, which is why the macro rejects one; see [Common Mistakes](#common-mistakes). +**Attributes on a trait method are copied to the provider trait's declaration of that method.** The +generated impls' methods carry none, and for `#[track_caller]` that is enough, because Rust applies +the attribute on a trait method's declaration to every impl of it. It therefore reaches the blanket +impls, the `UseContext`, `RedirectLookup`, and `UseDelegate` impls, and every provider, so +`Location::caller()` inside a provider reports the line that called the consumer method. +[`CanRaiseError`](../components/can_raise_error.md) relies on this so that an error library records +where an error was raised. + ## Formal grammar The attribute argument is either a bare provider name or a comma-separated set of keyed values, in the @@ -393,19 +466,33 @@ KeyValueArg -> `name` `:` ComponentName | `provider` `:` IDENTIFIER | `context` `:` IDENTIFIER -ComponentName -> IDENTIFIER GenericArgs? +ComponentName -> IDENTIFIER ( `<` NameParam ( `,` NameParam )* `,`? `>` )? + +NameParam -> LIFETIME_OR_LABEL + | IDENTIFIER + | `const` IDENTIFIER `:` Type ``` `ProviderName` is shorthand for setting `provider` alone. In the key/value form each key may appear at -most once, in any order, and `provider` is required. `IDENTIFIER` is a Rust identifier token, and -`GenericArgs` is the Rust grammar's `< … >` argument list, so the component name may carry generic -parameters while the provider name may not. - -The component name's parameters must be bare names, such as `name: ShapeComponent`, which the -marker struct then declares. A bound fails with ``trait bounds (`A: Clone`) are not allowed in type -generics``, a default with ``default type parameters (`A = B`) are not allowed in type generics``, -and a concrete type does not parse. A provider for such a component names the component explicitly, -as in `#[cgp_impl(new SquareArea: AreaCalculatorComponent)]`, because the default +most once, in any order, and `provider` is required. The parser rejects a repeated key with +*duplicate key is not allowed*, an unrecognized one with *unknown key*, and a missing `provider` +with ``the `provider` key must be given``. `IDENTIFIER` is a Rust identifier token. The provider +name and the context name take no generics. + +The component name's parameters are bare names, such as `name: ShapeComponent`, which the +marker struct then declares. Each must be one of the trait's own parameters, since the macro writes +the name wherever the component appears. The parser rejects anything more: + +- a bound fails with ``trait bounds (`A: Clone`) are not allowed in type generics``, and a lifetime + bound with ``lifetime bounds (`'a: 'b`) are not allowed in type generics``; +- a default fails with ``default type parameters (`A = B`) are not allowed in type generics``; +- a type that is not a single identifier, such as `Vec`, fails to parse. A single identifier + such as `u32` is read as a parameter name rather than as the type; +- a const parameter parses, per the grammar, but then fails inside the macro, as + [Common Mistakes](#common-mistakes) records. + +A provider for such a component names the component explicitly, as in +`#[cgp_impl(new SquareArea: AreaCalculatorComponent)]`, because the default `{Provider}Component` name carries no arguments. The attribute delimiter, `(...)` for the bare form and `{...}` for the key/value form, is ordinary Rust attribute syntax and does not change how the macro parses the arguments inside. @@ -445,17 +532,32 @@ parser, but the name is then used in type positions, where the const parameter c the macro fails with ``failed to parse internal tokens to type `syn::generics::TypeParamBound` ``. Keep the name's parameters to bare type names, as the component's own parameters are. -**The attribute must be applied to a trait.** The macro refuses a struct, an enum, or a free function -at parse time, with an error that names the trait it expected, instead of lowering it into code that -fails to compile later. +**A `name:` parameter the trait does not declare fails in the generated code.** In +`#[cgp_component { provider: Shape, name: ShapeComponent }]` on a trait without a `T`, the parser +accepts the name, and the compiler then reports ``error[E0425]: cannot find type `T` in this scope`` +at the `T`, followed by a confusing `E0034` about the generated impls. List only the trait's own +parameters in the name. -**The compiler, not the macro, reports a misplaced companion attribute, and it reports it several -times.** The macro carries an attribute it does not recognize onto *every* item it generates: the -consumer trait, the provider trait, and the impls built from each. For `#[allow(...)]` or a doc -comment, that repetition is welcome. For `#[uses(HasName)]` written above a component trait, it means -one *cannot find attribute* resolution error per generated item, and none of them mentions -`#[cgp_component]`. Read the repetition as the signal. It is the same error a typo in an attribute -name gives, so the fix is to move the attribute rather than to add an import. +**The attribute must be applied to a trait.** The macro refuses a struct, an enum, or a free function +at parse time with ``expected `trait` ``, instead of lowering it into code that fails to compile +later. + +**Two `#[use_type]` rejections are met most often on a component.** Beside the equality form covered +in [Companion attributes](#companion-attributes), two imports may not resolve to the same bare name +or alias, since the rewrite could keep only one: that fails with *Multiple abstract types cannot +share the same identifier or alias*. Imports may also not resolve through one another in a cycle. +The [`#[use_type]`](../attributes/use_type.md) page covers both. + +**The compiler, not the macro, reports a misplaced companion attribute, and the error does not name +`#[cgp_component]`.** The macro carries an attribute it does not recognize onto the items it +generates from the trait: the consumer trait, the provider trait, the two blanket impls, and the +`UseContext`, `RedirectLookup`, and `UseDelegate` impls. For `#[allow(...)]` or a doc comment, that +is what you want. +For `#[uses(HasName)]` written above a component trait, it means a *cannot find attribute `uses` in +this scope* error on the attribute's line, which the compiler reports once because every copy shares +the attribute's span. The compiler may even suggest a built-in attribute with a similar name, such as +`#[used]`. It is the same error a typo in an attribute name gives, so the fix is to move the +attribute rather than to add an import. ## Related constructs @@ -482,6 +584,7 @@ The ideas behind it: - Entry point: [`cgp_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/cgp_component.rs) - Implementation: [`types/cgp_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component/) +- Companion attributes: [`cgp_component_attributes.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/cgp_component_attributes.rs) --- diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index bdc81c11..28571474 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -30,9 +30,10 @@ covering every context that satisfies the field requirements. The macro makes one tradeoff, and you should know it. A [`#[cgp_component]`](./cgp_component.md) supports many interchangeable implementations, one chosen per -context, and this costs extra boilerplate. `#[cgp_fn]` supports exactly one implementation, the function -body, and costs nothing. Most traits have one natural definition, so `#[cgp_fn]` is the better -choice for them and the recommended place to start, rather than a lesser form of the real thing. +context, and this costs extra boilerplate. `#[cgp_fn]` supports exactly one implementation, the +function body, and needs no component, provider, or wiring. Most traits have one natural definition, +so `#[cgp_fn]` is the better choice for them and the recommended place to start, rather than a lesser +form of the real thing. It is also the easiest introduction to CGP, because nothing in it is unfamiliar. A reader who understands functions and arguments can write a working context-generic function without first @@ -147,6 +148,9 @@ it depends on. - [`#[async_trait]`](./async_trait.md) goes directly beneath `#[cgp_fn]` on an `async fn`. The macro copies it onto both generated items, so the trait ends up declaring a lint-clean `-> impl Future`. +Each attribute may be repeated, and each also takes a comma-separated list inside one attribute, as +in `#[uses(RectangleArea, HasName)]`. `#[use_provider]` is the exception in practice, because its +argument ends in a bound list that would swallow a second entry, so write one per inner provider. ## Examples A trait, another trait built on it, and a context that gets both without wiring anything: @@ -182,7 +186,10 @@ pub fn report(rect: &Rectangle) { dependency. It does not know or care how that trait is implemented. `Rectangle` derives [`HasField`](../derives/derive_has_field.md) and happens to carry the three fields the two functions read, and that is its entire qualification. This program does not use `delegate_components!` -anywhere, and adding one would change nothing. +anywhere, and adding one would change nothing. `Rectangle` is a +[value context](/docs/reference/glossary#value-context) here, the shape whose area is computed; a +type such as `App` that stands for an application gets the method the same way, by carrying the +fields. ## When to use it @@ -263,8 +270,7 @@ argument ends in `.as_str()` instead, and a plain `&T` in nothing at all. The generics split shows up in the same impl. Given the `scale` function above, the generic goes on both items while the function's `where` bound stays on the impl, ordered *before* the implicit field -bounds. Attribute-contributed predicates always come first, and the macro appends the implicit ones -last: +bound: ```rust pub trait Scale { @@ -291,7 +297,16 @@ The companion attributes layer into these same two items, and each lands in a fi - `#[use_type(Trait.Type)]` adds the supertrait and rewrites every bare mention of the type into its fully qualified form. -The macro appends the implicit-argument bounds last, after whatever the attributes contributed. +The impl's `where` clause is assembled in a fixed order, which helps when reading an expansion: + +1. the function's own `where` clause; +2. one `Self:` predicate joining every `#[extend]` bound and then every `#[uses]` bound; +3. the `#[extend_where]` predicates; +4. the implicit-argument `HasField` bounds; +5. the predicates `#[use_type]` and then `#[use_provider]` contribute. + +So the field bounds are not the last entries when a function imports an abstract type or a +provider. Two smaller placements matter because neither is visible in the source you wrote. **The function's visibility becomes the trait's**, and the impl's method keeps inherited visibility. So @@ -328,8 +343,7 @@ exclusively, so it cannot coexist with any other field read. Immutable implicit this restriction and combine freely, in any number: ```text -error: a `&mut` implicit argument must be the only implicit argument, since its mutable - borrow of the context conflicts with reading any other field +error: a `&mut` implicit argument must be the only implicit argument, since its mutable borrow of the context conflicts with reading any other field ``` **An `#[impl_generics]` parameter cannot appear in the trait's own signature.** Only the generated diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index f74e031a..8662e254 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -15,7 +15,8 @@ already know. A [provider trait](./cgp_component.md) has a different shape from the trait it came from. The original `Self` has moved into an explicit leading type parameter, the implementation targets a small marker type rather than the type the operation acts on, and the method receiver is a plain parameter. -Written by hand it looks like this: +Written by hand, with `HasDimensions` standing for a trait that supplies `width()` and `height()`, it +looks like this: ```rust impl AreaCalculator for RectangleArea @@ -40,10 +41,8 @@ trait, and put the provider's name in the attribute: ```rust #[cgp_impl(new RectangleArea)] -impl AreaCalculator -where - Self: HasDimensions, -{ +#[uses(HasDimensions)] +impl AreaCalculator { fn area(&self) -> f64 { self.width() * self.height() } @@ -51,7 +50,8 @@ where ``` Write providers this way. The macro performs the rewrite for you and produces the form shown earlier, -which you will see in generated code. +which you will see in generated code. [`#[uses(HasDimensions)]`](../attributes/uses.md) states the +dependency the hand-written form put in its `where` clause. This convenience has one rule you must keep in mind: **inside a `#[cgp_impl]` block, `self` and `Self` mean the context, not the provider.** The context is the type the method runs on, and @@ -63,16 +63,14 @@ the method runs. ## Usage Apply the attribute to an `impl` block. Its argument names the provider. The argument has the parts -listed below, and only the name is required. +listed below, and only the name is required. This provider reads the context's `width` and `height` +fields through [`#[implicit]`](../attributes/implicit.md) arguments, the usual way to read a field: ```rust #[cgp_impl(new RectangleArea)] -impl AreaCalculator -where - Self: HasDimensions, -{ - fn area(&self) -> f64 { - self.width() * self.height() +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height } } ``` @@ -87,7 +85,8 @@ The `for Context` clause is optional. Omitting it, as most examples on this page insert a generic context parameter for you: write `impl AreaCalculator`, not `impl AreaCalculator for Context`. Name the context explicitly only to bound it in a way the omitted form cannot express, such as a lifetime or a higher-ranked bound, or to serve one *concrete* -context alone, as in `impl AreaCalculator for Rectangle`. +context alone, as in `impl AreaCalculator for Rectangle`. That provider then implements +`AreaCalculator` and nothing else, and a context still wires it like any other. [When to use it](#when-to-use-it) says more about choosing between these forms. Without `new`, the provider struct must already exist. A wiring entry naming a struct nothing @@ -186,10 +185,12 @@ they let an idiomatic provider state what it needs. per-type default, emitting a delegation impl alongside it, for use with [`cgp_namespace!`](./cgp_namespace.md). -Each may be repeated. All except `#[use_provider]` also take a comma-separated list inside one -attribute, which is the form to prefer: `#[uses(HasName, CanRaiseError)]` reads as one -dependency list. `#[use_provider]` is the exception because its own argument already ends in a bound -list, so the parser could not tell where a second pair begins. Write one attribute per inner provider. +Each attribute may be repeated. `#[uses]` and `#[use_type]` also take a comma-separated list inside +one attribute, which is the form to prefer: `#[uses(HasName, CanRaiseError)]` reads as one +dependency list. `#[use_provider]` and `#[default_impl]` take one entry per attribute. +`#[use_provider]`'s own argument ends in a bound list, so the parser cannot tell where a second pair +begins, and `#[default_impl]` reads a single `Key in Namespace` spec. Write one attribute per inner +provider and one per registration. `#[cgp_impl]` does not read `#[extend]`, `#[extend_where]`, or [`#[impl_generics]`](../attributes/impl_generics.md), although you may see them on other CGP macros. @@ -205,9 +206,10 @@ Naming `Self` as the provider bypasses the rewrite entirely and emits the block ordinary consumer-trait impl on a concrete type. This form requires the `for Context` clause. The macro rejects an omitted clause with an `Expected context type to be specified` error, because it then lacks a context to find. The form is useful when you want a hand-written impl while still applying the -companion attributes. Because the macro does not generate a provider struct here, `new` and the -component override do nothing; see [Common Mistakes](#common-mistakes) for what happens if you write -them anyway. +companion attributes, which the macro processes before it looks at the provider, so `#[implicit]`, +`#[uses]`, `#[use_type]`, and `#[use_provider]` all work here. Because the macro does not generate a +provider struct here, `new` and the component override do nothing; see +[Common Mistakes](#common-mistakes) for what happens if you write them anyway. ```rust #[cgp_impl(Self)] @@ -219,6 +221,11 @@ impl CanCalculateArea for Rectangle { } ``` +A direct impl competes with the consumer blanket impl that +[`#[cgp_component]`](./cgp_component.md#under-the-hood) generates, so the same type must not also +wire the component in `delegate_components!`. Doing both makes the two impls overlap, and the compiler +rejects them with `E0119`, *conflicting implementations of trait `CanCalculateArea`*. + ## Examples The most idiomatic form of a provider reads almost like a plain function. Given the `AreaCalculator` @@ -242,7 +249,8 @@ impl AreaCalculator { The macro removes the two `#[implicit]` parameters from the signature and replaces them with reads of the `width` and `height` fields, so the provider requires a context that has them. The `new` keyword -defines `RectangleArea`. A concrete type then wires the component and calls through it: +defines `RectangleArea`. A concrete type then wires the component, checks the wiring, and calls +through it: ```rust #[derive(HasField)] @@ -257,11 +265,22 @@ delegate_components! { } } +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + fn print_area(rect: &Rectangle) { println!("area = {}", rect.area()); } ``` +`Rectangle` is a [value context](/docs/reference/glossary#value-context) here: the wired type is the +shape whose area is computed. A provider is written the same way for an +[environmental context](/docs/reference/glossary#environmental-context), a type such as `App` that +stands for one application. + ## When to use it **Write providers with `#[cgp_impl]`.** It is the recommended form for every provider, and the cases @@ -270,7 +289,8 @@ that call for something else are narrower than they look. Prefer the unqualified header from [Usage](#usage), `impl AreaCalculator` without `for Context`, and let the macro insert the context parameter. This keeps a provider reading like an ordinary trait impl. Name the context explicitly only when the short form cannot express a bound, such as a lifetime or a -higher-ranked bound. +higher-ranked bound. State a trait the context must implement with `#[uses]`, not with a +`where Self: Trait` clause. Naming a *concrete* type as that context, as in `impl AreaCalculator for Rectangle`, is a different choice. Keep it distinct from the @@ -285,7 +305,8 @@ Use something else in these cases: [Modularity Hierarchy](/docs/concepts/modularity-hierarchy). - **You want to implement the consumer trait directly on one concrete type.** Use the [`#[cgp_impl(Self)]` form](#implementing-the-consumer-trait-directly), which keeps the companion - attributes while emitting an ordinary impl. + attributes while emitting an ordinary impl. Switch to a named provider once a second type wants the + same implementation. Needing to [declare the provider struct separately](#declaring-the-provider-struct-separately) is not by itself a reason to drop to [`#[cgp_provider]`](./cgp_provider.md). Use the raw form only when @@ -323,16 +344,18 @@ pub struct ValueToString; ``` A few things changed. The trait gained `Context` as its leading argument. The `Self` type became the -provider. `&self` became the explicit parameter `__context__: &Context`. The receiver identifier is -the snake-cased context type wrapped in double underscores, so both `Context` and the default -`__Context__` become `__context__`. The macro rewrites every `self` in a body to that identifier, and -every `Self` to the context type. +provider. `&self` became the explicit parameter `__context__: &Context`. The macro rewrites every +`self` in a body to that identifier, and every `Self` to the context type. + +The receiver identifier is the context type's name in snake case, wrapped in double underscores +unless it already starts with an underscore. Both `Context` and the default `__Context__` become +`__context__`, and a concrete context gets its own name, so `for Rectangle` gives `__rectangle__`. A +context that is not a single identifier, such as `App<'a>`, falls back to `__context__`. When you omit `for Context`, the only difference is that the inserted parameter is `__Context__`. The -earlier `RectangleArea` example is exactly equivalent to writing it out: +`RectangleArea` provider from the [Overview](#overview) expands to: ```rust -#[cgp_new_provider] impl<__Context__> AreaCalculator<__Context__> for RectangleArea where __Context__: HasDimensions, @@ -341,6 +364,32 @@ where __context__.width() * __context__.height() } } + +impl<__Context__> IsProviderFor for RectangleArea +where + __Context__: HasDimensions, +{} + +pub struct RectangleArea; +``` + +The companion attributes run first. `#[uses(HasDimensions)]` became the `__Context__: HasDimensions` +bound above. An [`#[implicit]`](../attributes/implicit.md) argument becomes a `HasField` bound on the +context and a `get_field` read at the top of the body, cloned when the argument is owned. So the +[Examples](#examples) provider expands, with `Symbol!` standing for the type-level field names, to: + +```rust +impl<__Context__> AreaCalculator<__Context__> for RectangleArea +where + __Context__: HasField + + HasField, +{ + fn area(__context__: &__Context__) -> f64 { + let width: f64 = __context__.get_field(PhantomData::).clone(); + let height: f64 = __context__.get_field(PhantomData::).clone(); + width * height + } +} ``` The generated `IsProviderFor` impl copies the provider impl's signature, drops the body, and keeps the @@ -406,8 +455,19 @@ distinguishes the two meanings of `self`, and only the value form is rewritten. **The compiler, not the macro, reports a misplaced companion attribute.** The macro re-attaches an attribute it does not recognize to the generated provider impl rather than dropping it, so `#[allow(...)]` and similar attributes carry over unaffected. A stray `#[extend(HasName)]` therefore -produces a *cannot find attribute* resolution error pointing at the impl, and it does not mention -`#[cgp_impl]`. +produces a *cannot find attribute `extend` in this scope* error on the attribute's own line, and it +does not mention `#[cgp_impl]`. + +**A `#[default_impl]` registration works only when the header omits `for Context`.** The +registration copies the impl's generic parameters as written, before the macro inserts the context. +On the explicit `impl ShowImpl for Context` form, the copied `Context` appears +nowhere in the registration, and the compiler rejects it: + +```text +error[E0207]: the type parameter `Context` is not constrained by the impl trait, self type, or predicates +``` + +Write the header as `impl ShowImpl` instead. **The `Self` form accepts `new` and a component override, then ignores both.** Writing `#[cgp_impl(new Self)]` or `#[cgp_impl(Self: SomeComponent)]` parses and compiles, but has exactly the diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index d9056e97..27b59938 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -72,27 +72,34 @@ Which of the two you use depends only on whether the struct already exists. Both accept the same single optional argument: the **component type** to use in the generated marker impl. Omitted, it defaults to the provider trait's name plus `Component`, so implementing -`AreaCalculator` targets `AreaCalculatorComponent`. Pass it explicitly when the trait's name does not -follow that convention: +`AreaCalculator` targets `AreaCalculatorComponent`. Pass it explicitly when the component's marker +does not follow that convention, as when the component renamed it with the `name:` key: ```rust -#[cgp_provider(RunnerComponent)] -impl Runner for RunWithFooBar -where - Context: CanFetchFoo + CanFetchBar, -{ - fn run(context: &Context, _code: PhantomData) -> Result<(), Context::Error> { - /* ... */ +#[cgp_component { + name: AreaComponent, + provider: AreaCalculator, +}] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_provider(AreaComponent)] +impl AreaCalculator for UnitArea { + fn area(_context: &Context) -> f64 { + 1.0 } } ``` ### The struct `#[cgp_new_provider]` declares -The struct's shape is taken from the `Self` type of the impl. A plain name yields a unit struct. A -generic provider yields a tuple struct holding a +The struct's shape is taken from the `Self` type of the impl, which must be a provider name followed +by bare generic parameter names. A plain name yields a unit struct. A generic provider yields a tuple +struct holding one public [`PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html) over its parameters, so -that the parameters are bound: +that the parameters are bound. Several parameters share one tuple, and a lifetime is lifted into +[`Life<'a>`](../types/life.md), since `PhantomData` needs a type: ```rust // from `... for RectangleArea` @@ -100,6 +107,12 @@ pub struct RectangleArea; // from `... for SpawnAndRun` pub struct SpawnAndRun(pub ::core::marker::PhantomData); + +// from `... for LabelPair` +pub struct LabelPair(pub ::core::marker::PhantomData<(A, B)>); + +// from `... for LabelWithLife<'a>` +pub struct LabelWithLife<'a>(pub ::core::marker::PhantomData>); ``` This is also the limit of what the attribute form can express, and the reason `#[cgp_provider]` is @@ -139,8 +152,9 @@ where } ``` -A context wires it exactly as it would any provider. The derived marker impl makes a missing `width` -field report itself as a missing field: +A context wires it exactly as it would any provider, and the check verifies the wiring. The derived +marker impl makes a missing `width` field report itself as a missing field. `Rectangle` is a +[value context](/docs/reference/glossary#value-context) here, the shape whose area is computed: ```rust #[derive(HasField)] @@ -154,6 +168,12 @@ delegate_components! { AreaCalculatorComponent: RectangleArea, } } + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} ``` The same provider with `#[cgp_new_provider]` drops the separate declaration and nothing else: @@ -215,7 +235,8 @@ subtle. ## Under the hood `#[cgp_provider]` emits two items: your impl, passed through unchanged, and a marker impl derived from -it. From this input: +it. From this input, where `ComputerRef` and `ComputerRefComponent` come from +`cgp::extra::handler`: ```rust #[cgp_provider] @@ -262,7 +283,9 @@ arguments were written in. **The macro rewrites one bound instead of copying it**, and this is the mechanism that makes a nested provider stack diagnosable. A bound naming *this component's provider trait*, the inner-provider bound -of a [higher-order provider](../attributes/use_provider.md), gains its marker counterpart alongside it: +of a [higher-order provider](../attributes/use_provider.md), gains its marker counterpart alongside it, +whether it is written in the `where` clause or inline on the type parameter, as in +`impl>`: ```rust #[cgp_new_provider] @@ -293,12 +316,19 @@ described [above](#the-struct-cgp_new_provider-declares). ### Input the macros refuse -Both macros reject several shapes at expansion, rather than lowering them into code that fails later. An -**inherent impl**, with no trait, has no provider trait to read the component and context from. A -**provider trait with no type argument** leaves nothing to be the context. A **const argument** in the -provider trait's argument list has nowhere to live in the type-only params tuple. This is about the -*trait's* arguments, not about a const generic on the provider struct, which passes through untouched. -And an item that is not an `impl` is refused outright. Each message names what was missing. +Both macros reject several shapes at expansion, rather than lowering them into code that fails later, +and each message names what was missing: + +- An **inherent impl**, with no trait, has no provider trait to read the component and context from. + It fails with *expect provider trait name to be present* when the component is left to its + default, and with *provider impl should contain trait path* when a component type is given. +- A **provider trait with no type argument** leaves nothing to be the context, and fails with + *provider impl should contain trait path containing at least one generic type parameter*. +- A **const argument** in the provider trait's argument list has nowhere to live in the type-only + params tuple, and fails with *const arguments are not supported in provider impl trait arguments*. + This is about the *trait's* arguments, not about a const generic on the provider struct, which + passes through untouched. +- An item that is not an `impl` is refused by the parser. ## Formal grammar @@ -326,7 +356,8 @@ error[E0428]: the name `RectangleArea` is defined multiple times ``` **`new` is not part of this attribute's grammar.** `#[cgp_provider(new RectangleArea)]` does not -declare the struct. It fails to parse, because the argument holds a component type and nothing else. +declare the struct. It fails to parse with *unexpected token* at `RectangleArea`, because the argument +holds a component type and nothing else, and `new` has already been read as that type. Which macro you invoke decides whether the struct is declared, so use `#[cgp_new_provider]`. The `new` keyword you may have seen belongs to [`#[cgp_impl]`](./cgp_impl.md#usage). @@ -339,10 +370,15 @@ inner provider no longer surfaces at the outer one, and `#[check_providers(...)] layer of such a stack is at fault. Components without lifetime parameters are unaffected. **The macro does not check the component argument against the trait.** Passing a component that does -not belong to the provider trait you are implementing produces a marker impl for the wrong key, so the -provider silently fails to satisfy the wiring that names it. The error appears at the wiring site, -saying the provider is not a provider for that component. Omit the argument unless the trait's name -departs from the `{Trait}Component` convention. +not belong to the provider trait you are implementing produces a marker impl for the wrong key. The +provider trait's own `IsProviderFor` supertrait names the real component, so the compiler rejects the +provider impl itself: + +```text +error[E0277]: the trait bound `UnitArea: IsProviderFor` is not satisfied +``` + +Omit the argument unless the component's marker departs from the `{Trait}Component` convention. **A provider's own associated const or type still needs qualifying**, though for a different reason than in [`#[cgp_impl]`](./cgp_impl.md#common-mistakes). Here `Self` really is the provider, and nothing rewrites it. diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index 43bfe29a..cecec7eb 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -59,10 +59,6 @@ Like [`#[cgp_component]`](./cgp_component.md), the component needs a provider tr `ScalarTypeProviderComponent`. This is worth fixing in mind, because every other macro derives its default from the trait name. -The companion attributes of `#[cgp_component]` apply unchanged, so -[`#[prefix(...)]`](../attributes/prefix.md) registers the abstract type into a namespace. CGP's own -`HasErrorType` carries `#[prefix(@cgp.core.error in DefaultNamespace)]` this way. - Pass an identifier to override it, exactly as with `#[cgp_component]`: ```rust @@ -75,6 +71,16 @@ pub trait HasScalarType { The keyed form works here too, so `name`, `provider`, and `context` can each be set explicitly. Only the default for `provider` differs. +The companion attributes of `#[cgp_component]` apply unchanged, so +[`#[prefix(...)]`](../attributes/prefix.md) registers the abstract type into a namespace. CGP's own +`HasErrorType` carries `#[prefix(@cgp.core.error in DefaultNamespace)]` this way. + +The trait may carry generic parameters, which the macro handles exactly as `#[cgp_component]` does: +they follow the context in the provider trait, and a context chooses the type per parameter value, +through `open` or [`#[derive_delegate]`](../attributes/derive_delegate.md). So +`pub trait HasLabelType { type Label; }` lets a context wire +`@LabelTypeProviderComponent.u32: UseType`. + ### Bounds on the associated type A bound on the associated type is carried everywhere the type appears, and enforced on whatever concrete @@ -116,6 +122,12 @@ delegate_components! { } } +check_components! { + App { + ScalarTypeProviderComponent, + } +} + pub fn zero() -> Context::Scalar where Context: HasScalarType, @@ -216,8 +228,8 @@ where Read it as: `UseType` is a provider that supplies `T`. Wiring a context's component to `UseType` therefore gives it `Scalar = f64` with nothing written. Note the declaration's `Copy` bound copied into -the impl's `where` clause: it turns an unsuitable concrete type into an error where the wiring -names it. +the impl's `where` clause: it turns an unsuitable concrete type into an error wherever the context is +required to implement the trait, which a `check_components!` block makes the wiring site. The second addition is a [`WithProvider`](../providers/with_provider.md) impl, which adapts CGP's foundational abstract-type machinery into this component: @@ -264,7 +276,7 @@ derived from the **associated type's** name plus `TypeProvider`, so `type Scalar ## Common Mistakes **The trait must contain exactly one associated type and nothing else.** A method beside the type, a -second type, or no type at all all report the same thing: +second type, or no type at all each report the same thing: ```text error: type trait should contain exactly one associated type item @@ -283,7 +295,21 @@ error: generic associated type and where clause are not supported **The default provider name comes from the type, not the trait.** `HasScalarType` declaring `type Scalar` yields `ScalarTypeProviderComponent`, not `HasScalarTypeComponent`, so a wiring entry guessed from the trait name names a component that does not exist, and the error is an unresolved type -rather than anything about wiring. +rather than anything about wiring: + +```text +error[E0425]: cannot find type `HasScalarTypeComponent` in this scope +``` + +**Do not give the associated type the name of the trait that bounds it.** In +`type Database: Database`, the bound resolves to the associated type being declared, which the +generated impls have turned into a type parameter, rather than to the trait of that name: + +```text +error[E0404]: expected trait, found type parameter `Database` +``` + +Name the two apart, as in `type Db: Database`. **A bound on the type is not enforced at the wiring line.** Wiring `UseType` for a type declared `Copy` compiles; nothing complains until a check evaluates the lookup, and then the primary span is the @@ -291,15 +317,17 @@ component name in the `check_components!` block rather than the offending wiring ```text error[E0277]: the trait bound `String: Copy` is not satisfied - --> src/main.rs:5:27 - | -5 | check_components! { App { ScalarTypeProviderComponent } } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` - | -note: required for `UseType` to implement `IsProviderFor` - | -2 | #[cgp_type] pub trait HasScalarType { type Scalar: Copy; } - | ^^^^^^^^^^^ ---- unsatisfied trait bound introduced here + | + | ScalarTypeProviderComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` + | +note: required for `cgp::prelude::UseType` to implement `IsProviderFor` + | + | #[cgp_type] + | ^^^^^^^^^^^ + | pub trait HasScalarType { + | type Scalar: Copy; + | ---- unsatisfied trait bound introduced here ``` The offending type and the declaration that demanded the bound are both in the notes rather than the diff --git a/example-code/README.md b/example-code/README.md index de2d9438..32b11833 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -36,7 +36,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, `macros/cgp_namespace.md` and `macros/delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, the `macros/` pages `cgp_component.md`, `cgp_impl.md`, `cgp_provider.md`, `cgp_fn.md`, `cgp_type.md`, `cgp_namespace.md`, and `delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.rs new file mode 100644 index 00000000..8faef048 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: a const generic parameter on the +//! trait is rejected by the macro. + +use cgp::prelude::*; + +#[cgp_component(BufferProvider)] +pub trait CanBuffer { + fn buffer(&self) -> [u8; N]; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.stderr new file mode 100644 index 00000000..01378e48 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.stderr @@ -0,0 +1,5 @@ +error: const generic parameters are not supported on CGP component traits + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_generic_parameter.rs:7:21 + | +7 | pub trait CanBuffer { + | ^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs new file mode 100644 index 00000000..597a686f --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: a const parameter in the `name:` +//! list parses, then fails where the name is used as a type. + +use cgp::prelude::*; + +#[cgp_component { provider: Buffer, name: BufferComponent }] +pub trait CanBuffer { + fn buffer(&self); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr new file mode 100644 index 00000000..74038c58 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr @@ -0,0 +1,14 @@ +error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs:6:59 + | +6 | #[cgp_component { provider: Buffer, name: BufferComponent }] + | ^^^^^ + +error: failed to parse internal tokens to type `syn::generics::TypeParamBound`: + IsProviderFor < BufferComponent < const N : usize > , __Context__, () > + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs:6:1 + | +6 | #[cgp_component { provider: Buffer, name: BufferComponent }] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.rs new file mode 100644 index 00000000..e6688546 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.rs @@ -0,0 +1,12 @@ +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: two `#[use_type]` imports that +//! resolve to the same bare name are rejected. + +use cgp::prelude::*; + +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error, HasErrorType.{Error})] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.stderr new file mode 100644 index 00000000..27ccbef2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.stderr @@ -0,0 +1,5 @@ +error: Multiple abstract types cannot share the same identifier or alias + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_duplicate_use_type_alias.rs:7:46 + | +7 | #[use_type(HasErrorType.Error, HasErrorType.{Error})] + | ^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs new file mode 100644 index 00000000..786be384 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs @@ -0,0 +1,17 @@ +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: `#[uses]` above a component trait +//! is carried onto the generated items and reported once as an unresolved attribute. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_component(Greeter)] +#[uses(HasName)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr new file mode 100644 index 00000000..99ce53fd --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr @@ -0,0 +1,11 @@ +error: cannot find attribute `uses` in this scope + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs:12:3 + | +12 | #[uses(HasName)] + | ^^^^ + | +help: a built-in attribute with a similar name exists + | +12 - #[uses(HasName)] +12 + #[used(HasName)] + | diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.rs new file mode 100644 index 00000000..3dc098f3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.rs @@ -0,0 +1,12 @@ +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: the attribute must be applied to a +//! trait. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.stderr new file mode 100644 index 00000000..9fe7d497 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.stderr @@ -0,0 +1,5 @@ +error: expected `trait` + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_not_a_trait.rs:7:5 + | +7 | pub struct Rectangle { + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs new file mode 100644 index 00000000..f26cc0fc --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: a `name:` parameter the trait does +//! not declare passes the parser and fails in the generated code. + +use cgp::prelude::*; + +#[cgp_component { provider: Shape, name: ShapeComponent }] +pub trait CanShape { + fn shape(&self); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr new file mode 100644 index 00000000..3c4309d5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr @@ -0,0 +1,35 @@ +error[E0425]: cannot find type `T` in this scope + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs:6:57 + | +6 | #[cgp_component { provider: Shape, name: ShapeComponent }] + | ^ not found in this scope + +error[E0034]: multiple applicable items in scope + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs:8:8 + | +8 | fn shape(&self); + | ^^^^^ multiple `shape` found + | +note: candidate #1 is defined in the trait `Shape` + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs:8:5 + | +8 | fn shape(&self); + | ^^^^^^^^^^^^^^^^ +note: candidate #2 is defined in an impl of the trait `CanShape` for the type `__Context__` + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs:6:1 + | +6 | #[cgp_component { provider: Shape, name: ShapeComponent }] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use fully-qualified syntax to disambiguate + | +6 - #[cgp_component { provider: Shape, name: ShapeComponent }] +7 - pub trait CanShape { +8 - fn shape(&self); +6 + <<__Components__ as DelegateComponent<__Path__>>::Delegate as Shape>::shape(&self); + | +6 - #[cgp_component { provider: Shape, name: ShapeComponent }] +7 - pub trait CanShape { +8 - fn shape(&self); +6 + CanShape::shape(&self); + | diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs new file mode 100644 index 00000000..28b9790a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: a `_` method parameter fails inside +//! the macro, because the generated impls forward each argument by name. + +use cgp::prelude::*; + +#[cgp_component(Counter)] +pub trait CanCount { + fn count(&self, _: u32) -> u32; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr new file mode 100644 index 00000000..d11026b3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr @@ -0,0 +1,12 @@ +error: expected identifier, found keyword `_` + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs:8:21 + | +8 | fn count(&self, _: u32) -> u32; + | ^ + +error: failed to parse internal tokens to type `proc_macro2::Ident`: + _ + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs:8:21 + | +8 | fn count(&self, _: u32) -> u32; + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.rs b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.rs new file mode 100644 index 00000000..a603f998 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.rs @@ -0,0 +1,22 @@ +//! `docs/reference/macros/cgp_fn.md`, *Common Mistakes*: an `#[impl_generics]` parameter named in the +//! trait's own signature is out of scope there, bare (`E0425`) or qualified (`E0433`). + +use cgp::prelude::*; + +pub trait Database { + type Row; +} + +#[cgp_fn] +#[impl_generics(Db: Database)] +pub fn database_handle(&self, #[implicit] database: &Db) -> Db { + todo!() +} + +#[cgp_fn] +#[impl_generics(Db: Database)] +pub fn fetch_row(&self, #[implicit] database: &Db) -> Db::Row { + todo!() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.stderr b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.stderr new file mode 100644 index 00000000..dbb89ee2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.stderr @@ -0,0 +1,25 @@ +error[E0425]: cannot find type `Db` in this scope + --> tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.rs:12:61 + | +12 | pub fn database_handle(&self, #[implicit] database: &Db) -> Db { + | ^^ not found in this scope + +warning: unused variable: `database` + --> tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.rs:12:43 + | +12 | pub fn database_handle(&self, #[implicit] database: &Db) -> Db { + | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_database` + | + = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default + +warning: unused variable: `database` + --> tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.rs:18:37 + | +18 | pub fn fetch_row(&self, #[implicit] database: &Db) -> Db::Row { + | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_database` + +error[E0433]: cannot find type `Db` in this scope + --> tests/compile_fail/reference/macros/cgp_fn_common_mistakes_impl_generics_in_signature.rs:18:55 + | +18 | pub fn fetch_row(&self, #[implicit] database: &Db) -> Db::Row { + | ^^ use of undeclared type `Db` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.rs b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.rs new file mode 100644 index 00000000..9b5c3c05 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_fn.md`, *Common Mistakes*: implicit arguments need a `self` receiver. + +use cgp::prelude::*; + +#[cgp_fn] +pub fn rectangle_area(#[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.stderr b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.stderr new file mode 100644 index 00000000..d53edf4a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.stderr @@ -0,0 +1,7 @@ +error: The first argument of a function with implicit arguments must be `self` + --> tests/compile_fail/reference/macros/cgp_fn_common_mistakes_implicit_without_self.rs:5:1 + | +5 | #[cgp_fn] + | ^^^^^^^^^ + | + = note: this error originates in the attribute macro `cgp_fn` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.rs b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.rs new file mode 100644 index 00000000..b2d89ad7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_fn.md`, *Common Mistakes*: a mutable implicit argument must be the +//! only implicit argument. + +use cgp::prelude::*; + +#[cgp_fn] +pub fn grow(&mut self, #[implicit] width: &mut f64, #[implicit] height: f64) { + *width *= height; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.stderr b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.stderr new file mode 100644 index 00000000..686c695d --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.stderr @@ -0,0 +1,5 @@ +error: a `&mut` implicit argument must be the only implicit argument, since its mutable borrow of the context conflicts with reading any other field + --> tests/compile_fail/reference/macros/cgp_fn_common_mistakes_mutable_implicit_not_alone.rs:7:13 + | +7 | pub fn grow(&mut self, #[implicit] width: &mut f64, #[implicit] height: f64) { + | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.rs b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.rs new file mode 100644 index 00000000..e406564c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.rs @@ -0,0 +1,21 @@ +//! `docs/reference/macros/cgp_impl.md`, *Common Mistakes*: `#[default_impl]` on the explicit +//! `impl Trait for Context` form copies an unconstrained `Context`. + +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; + +#[cgp_component(ShowImpl)] +#[prefix(@test in DefaultNamespace)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl for Context { + fn show(&self, value: &String) -> String { + value.clone() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.stderr b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.stderr new file mode 100644 index 00000000..cc70a1eb --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.stderr @@ -0,0 +1,8 @@ +error[E0207]: the type parameter `Context` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_default_impl_on_explicit_context.rs:15:6 + | +13 | #[cgp_impl(new ShowString)] + | --------------------------- help: remove the unused type parameter `Context` +14 | #[default_impl(String in DefaultImpls1)] +15 | impl ShowImpl for Context { + | ^^^^^^^ unconstrained type parameter diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.rs b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.rs new file mode 100644 index 00000000..97f32933 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.rs @@ -0,0 +1,24 @@ +//! `docs/reference/macros/cgp_impl.md`, *Common Mistakes*: `#[extend]` is not read by `#[cgp_impl]`, +//! so it reaches the compiler as an unresolved attribute. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +#[extend(HasName)] +impl Greeter { + fn greet(&self) -> String { + "Hello".to_owned() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.stderr b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.stderr new file mode 100644 index 00000000..bd46d785 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.stderr @@ -0,0 +1,5 @@ +error: cannot find attribute `extend` in this scope + --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_misplaced_extend.rs:17:3 + | +17 | #[extend(HasName)] + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs new file mode 100644 index 00000000..37e8da95 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs @@ -0,0 +1,22 @@ +//! `docs/reference/macros/cgp_impl.md`, *Common Mistakes*: `Self::LIMIT` naming the provider's own +//! associated const is rewritten to the context, which lacks it. + +use cgp::prelude::*; + +#[cgp_component(RateLimiter)] +pub trait CanRateLimit { + const LIMIT: u64; + + fn allows(&self, count: u64) -> bool; +} + +#[cgp_impl(new AllowUnderLimit)] +impl RateLimiter { + const LIMIT: u64 = 100; + + fn allows(&self, count: u64) -> bool { + count < Self::LIMIT + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.stderr b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.stderr new file mode 100644 index 00000000..6aef11a9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.stderr @@ -0,0 +1,16 @@ +error[E0599]: no associated function or constant named `LIMIT` found for type parameter `__Context__` in the current scope + --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs:18:23 + | +13 | #[cgp_impl(new AllowUnderLimit)] + | -------------------------------- associated function or constant `LIMIT` not found for this type parameter +... +18 | count < Self::LIMIT + | ^^^^^ associated function or constant cannot be called on `__Context__` due to unsatisfied trait bounds + | + = help: items from traits can only be used if the type parameter is bounded by the trait +help: the following traits define an item `LIMIT`, perhaps you need to restrict type parameter `__Context__` with one of them: + | +13 | #[cgp_impl(new AllowUnderLimit)]: CanRateLimit + | ++++++++++++++ +13 | #[cgp_impl(new AllowUnderLimit)]: RateLimiter + | ++++++++++++++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.rs b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.rs new file mode 100644 index 00000000..7919bf27 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.rs @@ -0,0 +1,33 @@ +//! `docs/reference/macros/cgp_impl.md`, *Implementing the consumer trait directly*: a direct impl +//! and a wiring entry for the same component overlap. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new UnitArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct Square; + +#[cgp_impl(Self)] +impl CanCalculateArea for Square { + fn area(&self) -> f64 { + 1.0 + } +} + +delegate_components! { + Square { + AreaCalculatorComponent: UnitArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.stderr b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.stderr new file mode 100644 index 00000000..f77a6009 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.stderr @@ -0,0 +1,8 @@ +error[E0119]: conflicting implementations of trait `CanCalculateArea` for type `Square` + --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_and_wiring.rs:21:1 + | + 6 | #[cgp_component(AreaCalculator)] + | -------------------------------- first implementation here +... +21 | impl CanCalculateArea for Square { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Square` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.rs b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.rs new file mode 100644 index 00000000..93e5cdb1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.rs @@ -0,0 +1,18 @@ +//! `docs/reference/macros/cgp_impl.md`, *Implementing the consumer trait directly*: the `Self` form +//! needs the `for Context` clause. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(Self)] +impl CanCalculateArea { + fn area(&self) -> f64 { + 1.0 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.stderr b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.stderr new file mode 100644 index 00000000..7984587b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.stderr @@ -0,0 +1,5 @@ +error: Expected context type to be specified + --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_self_form_without_for.rs:12:1 + | +12 | impl CanCalculateArea { + | ^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.rs b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.rs new file mode 100644 index 00000000..cd48285c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.rs @@ -0,0 +1,24 @@ +//! `docs/reference/macros/cgp_provider.md`, *Common Mistakes*: `Self::LIMIT` in a raw provider +//! impl is ambiguous, because the provider struct also gets the consumer trait. + +use cgp::prelude::*; + +#[cgp_component(RateLimiter)] +pub trait CanRateLimit { + const LIMIT: u64; + + fn allowed(&self) -> bool; +} + +pub struct AllowUnderLimit; + +#[cgp_provider] +impl RateLimiter for AllowUnderLimit { + const LIMIT: u64 = 100; + + fn allowed(_context: &Context) -> bool { + Self::LIMIT > 0 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.stderr b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.stderr new file mode 100644 index 00000000..81dde03f --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.stderr @@ -0,0 +1,24 @@ +error[E0034]: multiple applicable items in scope + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.rs:20:15 + | +20 | Self::LIMIT > 0 + | ^^^^^ multiple `LIMIT` found + | +note: candidate #1 is defined in an impl of the trait `RateLimiter` for the type `AllowUnderLimit` + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.rs:17:5 + | +17 | const LIMIT: u64 = 100; + | ^^^^^^^^^^^^^^^^ +note: candidate #2 is defined in an impl of the trait `CanRateLimit` for the type `__Context__` + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_ambiguous_const.rs:8:5 + | + 8 | const LIMIT: u64; + | ^^^^^^^^^^^^^^^^ +help: use fully-qualified syntax to disambiguate + | +20 - Self::LIMIT > 0 +20 + ::LIMIT > 0 + | +20 - Self::LIMIT > 0 +20 + ::LIMIT > 0 + | diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.rs b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.rs new file mode 100644 index 00000000..a4b7e369 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.rs @@ -0,0 +1,18 @@ +//! `docs/reference/macros/cgp_provider.md`, *Common Mistakes*: `new` is not part of +//! `#[cgp_provider]`'s argument. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_provider(new RectangleArea)] +impl AreaCalculator for RectangleArea { + fn area(_context: &Context) -> f64 { + 1.0 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.stderr b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.stderr new file mode 100644 index 00000000..2e956838 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.stderr @@ -0,0 +1,5 @@ +error: unexpected token + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_new_keyword.rs:11:20 + | +11 | #[cgp_provider(new RectangleArea)] + | ^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.rs b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.rs new file mode 100644 index 00000000..faed9e98 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.rs @@ -0,0 +1,20 @@ +//! `docs/reference/macros/cgp_provider.md`, *Common Mistakes*: `#[cgp_new_provider]` over a struct +//! that is already declared defines it twice. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +pub struct RectangleArea; + +#[cgp_new_provider] +impl AreaCalculator for RectangleArea { + fn area(_context: &Context) -> f64 { + 1.0 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.stderr b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.stderr new file mode 100644 index 00000000..c4b0ca84 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.stderr @@ -0,0 +1,10 @@ +error[E0428]: the name `RectangleArea` is defined multiple times + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_struct_already_declared.rs:14:43 + | +11 | pub struct RectangleArea; + | ------------------------- previous definition of the type `RectangleArea` here +... +14 | impl AreaCalculator for RectangleArea { + | ^^^^^^^^^^^^^ `RectangleArea` redefined here + | + = note: `RectangleArea` must be defined only once in the type namespace of this module diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs new file mode 100644 index 00000000..69685034 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs @@ -0,0 +1,39 @@ +//! `docs/reference/macros/cgp_provider.md`, *Common Mistakes*: a component argument that does not +//! belong to the provider trait registers the provider under the wrong key. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +pub struct UnitArea; + +#[cgp_provider(PerimeterCalculatorComponent)] +impl AreaCalculator for UnitArea { + fn area(_context: &Context) -> f64 { + 1.0 + } +} + +pub struct Square; + +delegate_components! { + Square { + AreaCalculatorComponent: UnitArea, + } +} + +check_components! { + Square { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.stderr b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.stderr new file mode 100644 index 00000000..c6a611f5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.stderr @@ -0,0 +1,44 @@ +error[E0277]: the trait bound `UnitArea: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs:19:43 + | +19 | impl AreaCalculator for UnitArea { + | ^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `UnitArea` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs:19:1 + | +19 | impl AreaCalculator for UnitArea { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `PerimeterCalculatorComponent`, found `AreaCalculatorComponent` +note: required by a bound in `AreaCalculator` + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs:6:1 + | + 6 | #[cgp_component(AreaCalculator)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AreaCalculator` + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `UnitArea: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs:35:9 + | +35 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `UnitArea` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs:19:1 + | +19 | impl AreaCalculator for UnitArea { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `PerimeterCalculatorComponent`, found `AreaCalculatorComponent` + = note: required for `Square` to implement `CanUseComponent` +note: required by a bound in `__CheckSquare` + --> tests/compile_fail/reference/macros/cgp_provider_common_mistakes_wrong_component.rs:33:1 + | +33 | / check_components! { +34 | | Square { +35 | | AreaCalculatorComponent, +36 | | } +37 | | } + | |_^ required by this bound in `__CheckSquare` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.rs b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.rs new file mode 100644 index 00000000..a21f8efe --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.rs @@ -0,0 +1,19 @@ +//! `docs/reference/macros/cgp_provider.md`, *Input the macros refuse*: a const argument in the +//! provider trait's argument list. + +use cgp::prelude::*; + +pub trait Sized2 { + fn size() -> usize; +} + +pub struct Provider; + +#[cgp_provider(SomeComponent)] +impl Sized2 for Provider { + fn size() -> usize { + 3 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.stderr b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.stderr new file mode 100644 index 00000000..8a9ff1c1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.stderr @@ -0,0 +1,5 @@ +error: const arguments are not supported in provider impl trait arguments + --> tests/compile_fail/reference/macros/cgp_provider_refused_const_argument.rs:13:31 + | +13 | impl Sized2 for Provider { + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.rs b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.rs new file mode 100644 index 00000000..252001cb --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.rs @@ -0,0 +1,19 @@ +//! `docs/reference/macros/cgp_provider.md`, *Input the macros refuse*: an inherent impl. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +pub struct RectangleArea; + +#[cgp_provider] +impl RectangleArea { + pub fn area() -> f64 { + 1.0 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.stderr b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.stderr new file mode 100644 index 00000000..1a7e89bb --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.stderr @@ -0,0 +1,5 @@ +error: expect provider trait name to be present + --> tests/compile_fail/reference/macros/cgp_provider_refused_inherent_impl.rs:13:1 + | +13 | impl RectangleArea { + | ^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.rs b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.rs new file mode 100644 index 00000000..e66435f1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.rs @@ -0,0 +1,19 @@ +//! `docs/reference/macros/cgp_provider.md`, *Input the macros refuse*: a provider trait with no +//! type argument leaves nothing to be the context. + +use cgp::prelude::*; + +pub trait PlainTrait { + fn value() -> u32; +} + +pub struct Provider; + +#[cgp_provider(SomeComponent)] +impl PlainTrait for Provider { + fn value() -> u32 { + 1 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.stderr b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.stderr new file mode 100644 index 00000000..c87a049b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.stderr @@ -0,0 +1,7 @@ +error: provider impl should contain trait path containing at least one generic type parameter + --> tests/compile_fail/reference/macros/cgp_provider_refused_no_type_argument.rs:12:1 + | +12 | #[cgp_provider(SomeComponent)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: this error originates in the attribute macro `cgp_provider` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.rs b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.rs new file mode 100644 index 00000000..d8de6858 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.rs @@ -0,0 +1,25 @@ +//! `docs/reference/macros/cgp_type.md`, *Common Mistakes*: a bound on the type is enforced at the +//! check, not at the wiring line. + +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar: Copy; +} + +pub struct App; + +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } +} + +check_components! { + App { + ScalarTypeProviderComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.stderr b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.stderr new file mode 100644 index 00000000..5cc31e80 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.stderr @@ -0,0 +1,25 @@ +error[E0277]: the trait bound `String: Copy` is not satisfied + --> tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.rs:21:9 + | +21 | ScalarTypeProviderComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` + | +note: required for `cgp::prelude::UseType` to implement `IsProviderFor` + --> tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.rs:6:1 + | + 6 | #[cgp_type] + | ^^^^^^^^^^^ + 7 | pub trait HasScalarType { + 8 | type Scalar: Copy; + | ---- unsatisfied trait bound introduced here + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/macros/cgp_type_common_mistakes_bound_not_satisfied.rs:19:1 + | +19 | / check_components! { +20 | | App { +21 | | ScalarTypeProviderComponent, +22 | | } +23 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_type` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.rs b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.rs new file mode 100644 index 00000000..f1e5b3ad --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_type.md`, *Common Mistakes*: the associated type may not be generic. + +use cgp::prelude::*; + +#[cgp_type] +pub trait HasContainerType { + type Container; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.stderr new file mode 100644 index 00000000..c305b6ca --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.stderr @@ -0,0 +1,5 @@ +error: generic associated type and where clause are not supported + --> tests/compile_fail/reference/macros/cgp_type_common_mistakes_generic_associated_type.rs:6:1 + | +6 | pub trait HasContainerType { + | ^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.rs b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.rs new file mode 100644 index 00000000..ede89b3c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.rs @@ -0,0 +1,19 @@ +//! `docs/reference/macros/cgp_type.md`, *Common Mistakes*: the default name comes from the +//! associated type, so a key guessed from the trait name does not exist. + +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar; +} + +pub struct App; + +delegate_components! { + App { + HasScalarTypeComponent: UseType, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.stderr new file mode 100644 index 00000000..d63b0007 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.stderr @@ -0,0 +1,16 @@ +error[E0425]: cannot find type `HasScalarTypeComponent` in this scope + --> tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.rs:15:9 + | +15 | HasScalarTypeComponent: UseType, + | ^^^^^^^^^^^^^^^^^^^^^^ not found in this scope + | +help: you might be missing a type parameter + | +15 | HasScalarTypeComponent: UseType, + | ++++++++++++++++++++++++ + +error[E0425]: cannot find type `HasScalarTypeComponent` in this scope + --> tests/compile_fail/reference/macros/cgp_type_common_mistakes_guessed_component_name.rs:15:9 + | +15 | HasScalarTypeComponent: UseType, + | ^^^^^^^^^^^^^^^^^^^^^^ not found in this scope diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.rs b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.rs new file mode 100644 index 00000000..9ef7f20d --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.rs @@ -0,0 +1,13 @@ +//! `docs/reference/macros/cgp_type.md`, *Common Mistakes*: the trait must contain exactly one +//! associated type and nothing else. + +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar; + + fn zero(&self) -> Self::Scalar; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.stderr new file mode 100644 index 00000000..07b935f1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.stderr @@ -0,0 +1,5 @@ +error: type trait should contain exactly one associated type item + --> tests/compile_fail/reference/macros/cgp_type_common_mistakes_not_one_associated_type.rs:7:1 + | +7 | pub trait HasScalarType { + | ^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.rs b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.rs new file mode 100644 index 00000000..f83dea3c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.rs @@ -0,0 +1,13 @@ +//! `docs/reference/macros/cgp_type.md`, *Common Mistakes*: an associated type named after the trait +//! that bounds it shadows that trait. + +use cgp::prelude::*; + +pub trait Database {} + +#[cgp_type] +pub trait HasDatabaseType { + type Database: Database; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.stderr b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.stderr new file mode 100644 index 00000000..0536feff --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.stderr @@ -0,0 +1,10 @@ +error[E0404]: expected trait, found type parameter `Database` + --> tests/compile_fail/reference/macros/cgp_type_common_mistakes_type_shadows_bound.rs:10:20 + | + 6 | pub trait Database {} + | -------- you might have meant to refer to this trait +... +10 | type Database: Database; + | -------- ^^^^^^^^ not a trait + | | + | found this type parameter diff --git a/example-code/tests/reference/macros/cgp_component.rs b/example-code/tests/reference/macros/cgp_component.rs new file mode 100644 index 00000000..aee680cf --- /dev/null +++ b/example-code/tests/reference/macros/cgp_component.rs @@ -0,0 +1,433 @@ +//! Code from `docs/reference/macros/cgp_component.md` — *`#[cgp_component]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`, one fixture +//! per *Common Mistakes* entry. + +/// ## Usage +/// +/// The bare form and the key/value form. The page shows the two as alternative definitions of one +/// trait, so each gets its own module, and a context wires each to prove the generated names are +/// the ones the page gives. +pub mod usage { + pub mod bare_form { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new UnitArea)] + impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } + } + + pub struct Unit; + + delegate_components! { + Unit { + AreaCalculatorComponent: UnitArea, + } + } + + check_components! { + Unit { + AreaCalculatorComponent, + } + } + } + + pub mod key_value_form { + use cgp::prelude::*; + + #[cgp_component { + name: AreaCalculatorComponent, + provider: AreaCalculator, + context: Context, + }] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new UnitArea)] + impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } + } + + pub struct Unit; + + delegate_components! { + Unit { + AreaCalculatorComponent: UnitArea, + } + } + + check_components! { + Unit { + AreaCalculatorComponent, + } + } + } +} + +/// ## Companion attributes +/// +/// The `#[use_type(HasErrorType.Error)]` component. The page shows only the trait, so a provider +/// and a context with a `String` error type are added to prove the bare `Error` resolves. +pub mod companion_attributes { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self, path: &str) -> Result; + } + + #[cgp_impl(new LoadEcho)] + #[use_type(HasErrorType.Error)] + impl Loader { + fn load(&self, path: &str) -> Result { + Ok(format!("contents of {path}")) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + LoaderComponent: LoadEcho, + } + } + + check_components! { + App { + LoaderComponent, + } + } + + #[test] + fn the_component_loads() { + assert_eq!(App.load("a.txt"), Ok("contents of a.txt".to_owned())); + } +} + +/// ## Examples +/// +/// The page's example as written, including its `check_components!` block. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + pub fn print_area(rect: &Rectangle) { + println!("area = {}", rect.area()); + } + + #[test] + fn the_wired_area_is_computed() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + print_area(&rect); + assert_eq!(rect.area(), 6.0); + } +} + +/// ## Under the hood +/// +/// The inputs whose expansions the page lists. The listings themselves are checked with +/// `cargo cgp expand --test reference_tests --item reference::macros::cgp_component::under_the_hood`, +/// not here; these modules prove the inputs compile and the described behavior holds. +pub mod under_the_hood { + /// The parameterless component the listings expand. + pub mod plain { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + } + + /// A local associated type: `Self::Output` stays as written and names the provider's own + /// `Output`. + pub mod local_associated_type { + use cgp::prelude::*; + + #[cgp_component(OutputProducer)] + pub trait CanProduceOutput { + type Output; + + fn produce(&self) -> Self::Output; + } + + #[cgp_impl(new ProduceNumber)] + impl OutputProducer { + type Output = u32; + + fn produce(&self) -> u32 { + 7 + } + } + + pub struct App; + + delegate_components! { + App { + OutputProducerComponent: ProduceNumber, + } + } + + check_components! { + App { + OutputProducerComponent, + } + } + + #[test] + fn the_provider_chooses_the_output() { + assert_eq!(App.produce(), 7); + } + } + + /// `#[extend(HasName)]` on `CanGreet`, with the default body the page describes, and the empty + /// `UseDefault` provider that inherits it. The page names `HasName` without declaring it; it is + /// an auto getter here. + pub mod supertrait_and_default_body { + use cgp::core::component::UseDefault; + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_component(Greeter)] + #[extend(HasName)] + pub trait CanGreet { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } + } + + #[cgp_impl(UseDefault)] + impl Greeter for Context {} + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GreeterComponent: UseDefault, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + #[test] + fn the_empty_provider_inherits_the_default() { + let person = Person { + name: "World".to_owned(), + }; + assert_eq!(person.greet(), "Hello, World!"); + } + } + + /// The `context: Ctx` override, whose provider-trait receiver is `__ctx__`. + pub mod context_override { + use cgp::prelude::*; + + #[cgp_component { provider: Namer, context: Ctx }] + pub trait CanName { + fn name(&self) -> String; + } + } + + /// The components of the parameter table. `CanCalculateArea` is wired per shape with + /// `open`, which is the per-type path the page describes the `RedirectLookup` impl building. + pub mod generic_components { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + #[cgp_component(Encoder)] + pub trait CanEncode { + fn encode(&self, value: &Value, format: &Format) -> Vec; + } + + #[cgp_component(ReferenceGetter)] + pub trait HasReference<'a, T> { + fn reference(&self) -> &'a T; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height + } + } + + pub struct App; + + delegate_components! { + App { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + } + } + + check_components! { + App { + AreaCalculatorComponent: Rectangle, + } + } + + #[test] + fn the_per_type_entry_resolves() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(App.area(&rect), 6.0); + } + } + + /// `#[track_caller]` on a component method reaches every provider, so a provider sees the + /// consumer call's location. + pub mod method_attributes { + use core::panic::Location; + + use cgp::prelude::*; + + #[cgp_component(LineReporter)] + pub trait CanReportLine { + #[track_caller] + fn report_line(&self) -> u32; + } + + #[cgp_impl(new CallerLine)] + impl LineReporter { + fn report_line(&self) -> u32 { + Location::caller().line() + } + } + + pub struct App; + + delegate_components! { + App { + LineReporterComponent: CallerLine, + } + } + + check_components! { + App { + LineReporterComponent, + } + } + + #[test] + fn the_provider_reports_the_calling_line() { + let expected = line!() + 1; + let line = App.report_line(); + assert_eq!(line, expected); + } + } +} + +/// ## Formal grammar +/// +/// A component name carrying the trait's parameter, and the provider that names the component +/// explicitly because the default `{Provider}Component` carries no arguments. The page names +/// `Square` without declaring it. +pub mod formal_grammar { + use cgp::prelude::*; + + #[cgp_component { + provider: AreaCalculator, + name: AreaCalculatorComponent, + }] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Square { + pub side: f64, + } + + #[cgp_impl(new SquareArea: AreaCalculatorComponent)] + impl AreaCalculator { + fn area(&self, shape: &Square) -> f64 { + shape.side * shape.side + } + } + + pub struct App; + + delegate_components! { + App { + AreaCalculatorComponent: SquareArea, + } + } + + check_components! { + App { + AreaCalculatorComponent: Square, + } + } + + #[test] + fn the_parameterized_marker_wires() { + assert_eq!(App.area(&Square { side: 3.0 }), 9.0); + } +} diff --git a/example-code/tests/reference/macros/cgp_fn.rs b/example-code/tests/reference/macros/cgp_fn.rs new file mode 100644 index 00000000..4c73c6be --- /dev/null +++ b/example-code/tests/reference/macros/cgp_fn.rs @@ -0,0 +1,268 @@ +//! Code from `docs/reference/macros/cgp_fn.md` — *`#[cgp_fn]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. + +/// ## Overview +/// +/// The opening function, and a context with the two fields it reads. +pub mod overview { + use cgp::prelude::*; + + #[cgp_fn] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[test] + fn any_struct_with_the_fields_gets_the_method() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.rectangle_area(), 6.0); + } +} + +/// ## Usage +/// +/// The trait-name override, the receiver-less form the page says the macro accepts, and a +/// `&mut self` function writing through a mutable implicit argument. The last two are stated in +/// prose on the page. +pub mod usage { + use cgp::prelude::*; + + #[cgp_fn(CanCalculateRectangleArea)] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[cgp_fn] + pub fn unit_area() -> f64 { + 1.0 + } + + #[cgp_fn] + pub fn grow(&mut self, #[implicit] width: &mut f64) { + *width *= 2.0; + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[test] + fn the_forms_behave_as_described() { + let mut rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(CanCalculateRectangleArea::rectangle_area(&rect), 6.0); + assert_eq!(::unit_area(), 1.0); + rect.grow(); + assert_eq!(rect.width, 4.0); + } +} + +/// ### Generics, and where each bound lands +/// +/// The `scale` function: `Scalar` lands on the trait, its `where` bound on the impl alone. +pub mod generics_and_where_each_bound_lands { + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_fn] + pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + where + Scalar: Mul + Copy, + { + factor * factor + } + + #[derive(HasField)] + pub struct Scaled { + pub factor: f64, + } + + /// A caller bounds on the trait alone, without repeating `Mul`. + pub fn squared>(context: &Context) -> f64 { + context.scale() + } + + #[test] + fn the_caller_needs_only_the_trait() { + assert_eq!(squared(&Scaled { factor: 3.0 }), 9.0); + } +} + +/// #### A type the caller should not name +/// +/// `#[impl_generics(Name: Display)]`: the trait is not generic, and the field fixes `Name`. +pub mod a_type_the_caller_should_not_name { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_fn] + #[impl_generics(Name: Display)] + pub fn describe(&self, #[implicit] name: &Name) -> String { + format!("{name}") + } + + #[derive(HasField)] + pub struct Labeled { + pub name: u32, + } + + #[test] + fn the_field_type_is_inferred() { + assert_eq!(Labeled { name: 7 }.describe(), "7"); + } +} + +/// ### Companion attributes +/// +/// `#[async_trait]` beneath `#[cgp_fn]` on an `async fn`, which the page says lands on both +/// items. The page describes it without a snippet. +pub mod companion_attributes { + use cgp::prelude::*; + + #[cgp_fn] + #[async_trait] + pub async fn fetch_label(&self, #[implicit] label: &str) -> String { + label.to_owned() + } + + #[derive(HasField)] + pub struct Item { + pub label: String, + } + + #[test] + fn the_async_method_runs() { + let item = Item { + label: "x".to_owned(), + }; + assert_eq!(futures::executor::block_on(item.fetch_label()), "x"); + } +} + +/// ## Examples +/// +/// The page's two functions and the context that gets both without wiring. +pub mod examples { + use cgp::prelude::*; + + #[cgp_fn] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[cgp_fn] + #[uses(RectangleArea)] + pub fn scaled_rectangle_area(&self, #[implicit] scale_factor: f64) -> f64 { + self.rectangle_area() * scale_factor * scale_factor + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + pub fn report(rect: &Rectangle) { + println!("base area = {}", rect.rectangle_area()); + println!("scaled area = {}", rect.scaled_rectangle_area()); + } + + #[test] + fn both_traits_apply() { + let rect = Rectangle { + width: 3.0, + height: 4.0, + scale_factor: 2.0, + }; + report(&rect); + assert_eq!(rect.rectangle_area(), 12.0); + assert_eq!(rect.scaled_rectangle_area(), 48.0); + } +} + +/// ## Under the hood +/// +/// The order of the impl's `where` clause, with every contributor present, checked with +/// `cargo cgp expand --item reference::macros::cgp_fn::under_the_hood`. `HasScalarType` and +/// `HasLabel` are declared here to give `#[use_type]` and `#[uses]` something to import. +pub mod under_the_hood { + use core::fmt::Debug; + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Mul + Copy; + } + + #[cgp_auto_getter] + pub trait HasLabel { + fn label(&self) -> &str; + } + + #[cgp_fn] + #[extend(Debug)] + #[uses(HasLabel)] + #[extend_where(Self: Sized)] + #[use_type(HasScalarType.Scalar)] + pub fn labeled_square(&self, #[implicit] side: Scalar, tag: T) -> (String, Scalar) + where + T: Debug, + { + (format!("{}{:?}", self.label(), tag), side * side) + } + + #[derive(Debug, HasField)] + pub struct Square { + pub label: String, + pub side: f64, + } + + delegate_components! { + Square { + ScalarTypeProviderComponent: UseType, + } + } + + #[test] + fn every_contributor_is_satisfied() { + let square = Square { + label: "s".to_owned(), + side: 3.0, + }; + assert_eq!(square.labeled_square(1u8), ("s1".to_owned(), 9.0)); + } + + /// A private function yields a private trait. + #[cgp_fn] + fn private_area(&self, #[implicit] side: f64) -> f64 { + side * side + } + + #[test] + fn the_private_trait_is_usable_here() { + let square = Square { + label: String::new(), + side: 2.0, + }; + assert_eq!(square.private_area(), 4.0); + } +} diff --git a/example-code/tests/reference/macros/cgp_impl.rs b/example-code/tests/reference/macros/cgp_impl.rs new file mode 100644 index 00000000..26ce54ea --- /dev/null +++ b/example-code/tests/reference/macros/cgp_impl.rs @@ -0,0 +1,665 @@ +//! Code from `docs/reference/macros/cgp_impl.md` — *`#[cgp_impl]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`, one fixture +//! per *Common Mistakes* entry that fails to compile. + +/// ## Overview +/// +/// The hand-written provider impl and the `#[cgp_impl]` block that replaces it. The page names +/// `HasDimensions` without declaring it; it is an auto getter over two `f64` fields here, and each +/// form gets its own module since both declare `RectangleArea`. +pub mod overview { + pub mod hand_written { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_auto_getter] + pub trait HasDimensions { + fn width(&self) -> f64; + fn height(&self) -> f64; + } + + pub struct RectangleArea; + + #[cgp_provider] + impl AreaCalculator for RectangleArea + where + Context: HasDimensions, + { + fn area(context: &Context) -> f64 { + context.width() * context.height() + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + } + + pub mod with_cgp_impl { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_auto_getter] + pub trait HasDimensions { + fn width(&self) -> f64; + fn height(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + #[uses(HasDimensions)] + impl AreaCalculator { + fn area(&self) -> f64 { + self.width() * self.height() + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + #[test] + fn the_provider_reads_the_dimensions() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.area(), 6.0); + } + } +} + +/// ## Usage +/// +/// The generic higher-order provider, wired over a base calculator the page names only in prose. +pub mod usage { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(new ScaledAreaCalculator)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + let base_area = InnerCalculator::area(self); + base_area * scale_factor * scale_factor + } + } + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_components! { + ScaledRectangle { + AreaCalculatorComponent: ScaledAreaCalculator, + } + } + + check_components! { + ScaledRectangle { + AreaCalculatorComponent, + } + } + + #[test] + fn the_wrapper_scales_the_inner_area() { + let rect = ScaledRectangle { + width: 3.0, + height: 4.0, + scale_factor: 2.0, + }; + assert_eq!(rect.area(), 48.0); + } +} + +/// ### Declaring the provider struct separately +/// +/// One provider implementing two components, with `new` on one block only, and a higher-order +/// provider whose struct is declared by hand so its inner parameter can default to `UseContext`. +/// The page does not declare `PerimeterCalculator`; it is a second component here. +pub mod declaring_the_provider_struct_separately { + pub mod one_struct_two_components { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + #[cgp_impl(new RectangleGeometry)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(RectangleGeometry)] + impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: RectangleGeometry, + } + } + + check_components! { + Rectangle { + [ + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ], + } + } + + #[test] + fn one_provider_serves_both_components() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.area(), 6.0); + assert_eq!(rect.perimeter(), 10.0); + } + } + + pub mod defaulted_inner_provider { + use core::marker::PhantomData; + + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + pub struct ScaledAreaCalculator(PhantomData); + + #[cgp_impl(ScaledAreaCalculator)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + let base_area = InnerCalculator::area(self); + base_area * scale_factor * scale_factor + } + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_components! { + ScaledRectangle { + AreaCalculatorComponent: ScaledAreaCalculator, + } + } + + check_components! { + ScaledRectangle { + AreaCalculatorComponent, + } + } + + /// The default applies where the inner provider is left out. + pub type DefaultScaled = ScaledAreaCalculator; + + #[test] + fn the_hand_declared_struct_wires() { + let rect = ScaledRectangle { + width: 3.0, + height: 4.0, + scale_factor: 2.0, + }; + assert_eq!(rect.area(), 48.0); + let _: DefaultScaled = ScaledAreaCalculator(PhantomData::); + } + } +} + +/// ### Companion attributes +/// +/// The comma-separated `#[uses(HasName, CanRaiseError)]` list the page recommends, on a +/// provider the page does not show. `CanGreet` and its context are declared here. +pub mod companion_attributes { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_component(Greeter)] + #[use_type(HasErrorType.Error)] + pub trait CanGreet { + fn greet(&self) -> Result; + } + + #[cgp_impl(new GreetNonEmpty)] + #[uses(HasName, CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl Greeter { + fn greet(&self) -> Result { + if self.name().is_empty() { + return Err(Self::raise_error("empty name".to_owned())); + } + Ok(format!("Hello, {}!", self.name())) + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorRaiserComponent.String: RaiseFrom, + GreeterComponent: GreetNonEmpty, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + #[test] + fn both_dependencies_resolve() { + let person = Person { + name: "World".to_owned(), + }; + assert_eq!(person.greet(), Ok("Hello, World!".to_owned())); + } +} + +/// ### Implementing the consumer trait directly +/// +/// The `#[cgp_impl(Self)]` block forwarding to a provider. `Rectangle` does not wire +/// `AreaCalculatorComponent`, since the direct impl would overlap the consumer blanket impl. +pub mod implementing_the_consumer_trait_directly { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(Self)] + #[use_provider(RectangleArea: AreaCalculator)] + impl CanCalculateArea for Rectangle { + fn area(&self) -> f64 { + RectangleArea::area(self) + } + } + + /// The `Self` form still lowers `#[implicit]` arguments, since the companion attributes run + /// before the macro chooses between the two forms. + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + #[cgp_impl(Self)] + impl CanCalculatePerimeter for Rectangle { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } + } + + #[test] + fn the_direct_impls_apply() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.area(), 6.0); + assert_eq!(rect.perimeter(), 10.0); + } +} + +/// ## Examples +/// +/// The page's example, with the `check_components!` block it shows. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + pub fn print_area(rect: &Rectangle) { + println!("area = {}", rect.area()); + } + + #[test] + fn the_wired_area_is_computed() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + print_area(&rect); + assert_eq!(rect.area(), 6.0); + } +} + +/// ## Under the hood +/// +/// The inputs whose expansions the page lists, checked with +/// `cargo cgp expand --test reference_tests --item reference::macros::cgp_impl::under_the_hood`. +/// The page does not declare `FooProvider`; its component is declared here. +pub mod under_the_hood { + pub mod explicit_context { + use cgp::prelude::*; + + #[cgp_component(FooProvider)] + pub trait CanFoo { + fn foo(&self, value: u32) -> String; + } + + #[cgp_impl(new ValueToString)] + impl FooProvider for Context { + fn foo(&self, value: u32) -> String { + value.to_string() + } + } + + pub struct App; + + delegate_components! { + App { + FooProviderComponent: ValueToString, + } + } + + check_components! { + App { + FooProviderComponent, + } + } + + #[test] + fn the_provider_formats_the_value() { + assert_eq!(App.foo(7), "7"); + } + } + + /// A concrete context named in the header, whose receiver becomes `__rectangle__`. + pub mod concrete_context { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(new RectangleOnlyArea)] + impl AreaCalculator for Rectangle { + fn area(&self) -> f64 { + self.width * self.height + } + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleOnlyArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + } + + /// A provider supplying its own `type Output`, which the rewrite leaves as `Self::Output`. + pub mod local_associated_type { + use cgp::prelude::*; + + #[cgp_component(OutputProducer)] + pub trait CanProduceOutput { + type Output; + + fn produce(&self) -> Self::Output; + } + + #[cgp_impl(new ProduceLabel)] + impl OutputProducer { + type Output = String; + + fn produce(&self) -> Self::Output { + "label".to_owned() + } + } + + pub struct App; + + delegate_components! { + App { + OutputProducerComponent: ProduceLabel, + } + } + + check_components! { + App { + OutputProducerComponent, + } + } + + #[test] + fn the_local_type_resolves() { + assert_eq!(App.produce(), "label"); + } + } +} + +/// ## Common Mistakes +/// +/// The compiling halves of the entries: the qualified path that names a provider's own const, and +/// the `Self` form with `new` and a component override, which the macro ignores. `RateLimiter` and +/// its context are declared here from the page's inline names. +pub mod common_mistakes { + pub mod provider_const { + use cgp::prelude::*; + + #[cgp_component(RateLimiter)] + pub trait CanRateLimit { + const LIMIT: u64; + + fn allows(&self, count: u64) -> bool; + } + + #[cgp_impl(new AllowUnderLimit)] + impl RateLimiter { + const LIMIT: u64 = 100; + + fn allows(&self, count: u64) -> bool { + count < >::LIMIT + } + } + + pub struct App; + + delegate_components! { + App { + RateLimiterComponent: AllowUnderLimit, + } + } + + check_components! { + App { + RateLimiterComponent, + } + } + + #[test] + fn the_qualified_const_resolves() { + assert!(App.allows(99)); + assert!(!App.allows(100)); + assert_eq!(::LIMIT, 100); + } + } + + pub mod self_form_ignores_new_and_override { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + pub struct Square; + + #[cgp_impl(new Self)] + impl CanCalculateArea for Square { + fn area(&self) -> f64 { + 1.0 + } + } + + #[cgp_impl(Self: SomeComponent)] + impl CanCalculatePerimeter for Square { + fn perimeter(&self) -> f64 { + 4.0 + } + } + + #[test] + fn both_are_plain_direct_impls() { + assert_eq!(Square.area(), 1.0); + assert_eq!(Square.perimeter(), 4.0); + } + } +} diff --git a/example-code/tests/reference/macros/cgp_provider.rs b/example-code/tests/reference/macros/cgp_provider.rs new file mode 100644 index 00000000..933d8244 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_provider.rs @@ -0,0 +1,387 @@ +//! Code from `docs/reference/macros/cgp_provider.md` — *`#[cgp_provider]` & `#[cgp_new_provider]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. + +/// ## Usage +/// +/// The component override. The component's marker is named `AreaComponent` through the `name:` +/// key, so the default `AreaCalculatorComponent` would name nothing and the override is required. +pub mod usage { + use cgp::prelude::*; + + #[cgp_component { + name: AreaComponent, + provider: AreaCalculator, + }] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + pub struct UnitArea; + + #[cgp_provider(AreaComponent)] + impl AreaCalculator for UnitArea { + fn area(_context: &Context) -> f64 { + 1.0 + } + } + + pub struct Square; + + delegate_components! { + Square { + AreaComponent: UnitArea, + } + } + + check_components! { + Square { + AreaComponent, + } + } + + #[test] + fn the_overridden_component_wires() { + assert_eq!(Square.area(), 1.0); + } +} + +/// ### The struct `#[cgp_new_provider]` declares +/// +/// The unit and generic shapes, plus the two the page states only in prose: several parameters +/// share one `PhantomData` tuple, and a lifetime is lifted into `Life<'a>`. Checked with +/// `cargo cgp expand --item reference::macros::cgp_provider::the_struct_cgp_new_provider_declares`. +pub mod the_struct_cgp_new_provider_declares { + use core::marker::PhantomData; + + use cgp::prelude::*; + + #[cgp_component(Labeler)] + pub trait CanLabel { + fn label(&self, code: PhantomData) -> String; + } + + #[cgp_new_provider] + impl Labeler for FixedLabel { + fn label(_context: &Context, _code: PhantomData) -> String { + "fixed".to_owned() + } + } + + #[cgp_new_provider] + impl Labeler for LabelFor { + fn label(_context: &Context, _code: PhantomData) -> String { + core::any::type_name::().to_owned() + } + } + + #[cgp_new_provider] + impl Labeler for LabelPair { + fn label(_context: &Context, _code: PhantomData) -> String { + format!("{}+{}", core::any::type_name::(), core::any::type_name::()) + } + } + + #[cgp_new_provider] + impl<'a, Context, Code> Labeler for LabelWithLife<'a> { + fn label(_context: &Context, _code: PhantomData) -> String { + "life".to_owned() + } + } + + #[test] + fn the_structs_have_the_stated_shapes() { + let _: FixedLabel = FixedLabel; + let _: LabelFor = LabelFor(PhantomData::); + let _: LabelPair = LabelPair(PhantomData::<(u8, u16)>); + let _: LabelWithLife<'static> = LabelWithLife(PhantomData::>); + } +} + +/// ## Examples +/// +/// The three spellings of the same provider, each in its own module since each declares +/// `RectangleArea`, and each wired and checked on `Rectangle`. +pub mod examples { + pub mod with_cgp_provider { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_auto_getter] + pub trait HasDimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; + } + + pub struct RectangleArea; + + #[cgp_provider] + impl AreaCalculator for RectangleArea + where + Context: HasDimensions, + { + fn area(context: &Context) -> f64 { + context.width() * context.height() + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + #[test] + fn the_provider_computes_the_area() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.area(), 6.0); + } + } + + pub mod with_cgp_new_provider { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_auto_getter] + pub trait HasDimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; + } + + #[cgp_new_provider] + impl AreaCalculator for RectangleArea + where + Context: HasDimensions, + { + fn area(context: &Context) -> f64 { + context.width() * context.height() + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + } + + pub mod with_cgp_impl { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_auto_getter] + pub trait HasDimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; + } + + #[cgp_impl(new RectangleArea)] + #[uses(HasDimensions)] + impl AreaCalculator { + fn area(&self) -> f64 { + self.width() * self.height() + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + } +} + +/// ## Under the hood +/// +/// The `ComputerRef` provider whose marker impl the page lists, a lifetime-carrying provider trait, +/// and the higher-order `Scaled` whose inner bound gains its marker counterpart, both in the +/// `where` clause and inline. Checked with +/// `cargo cgp expand --item reference::macros::cgp_provider::under_the_hood`. +pub mod under_the_hood { + pub mod computer_ref { + use core::fmt::Display; + use core::marker::PhantomData; + + use cgp::extra::handler::{ComputerRef, ComputerRefComponent}; + use cgp::prelude::*; + + pub struct FirstNameToString; + + #[cgp_provider] + impl ComputerRef for FirstNameToString + where + Context: HasField, + { + type Output = String; + + fn compute_ref(context: &Context, _code: PhantomData, _input: &Input) -> String { + context.get_field(PhantomData).to_string() + } + } + } + + pub mod lifetime_provider_trait { + use cgp::prelude::*; + + #[cgp_component(ReferenceGetter)] + pub trait HasReference<'a, T: 'a> { + fn reference(&self) -> &'a T; + } + + #[cgp_new_provider] + impl<'a, Context, T: 'a> ReferenceGetter<'a, Context, T> for Unreachable { + fn reference(_context: &Context) -> &'a T { + unimplemented!("only the marker impl is inspected") + } + } + } + + pub mod higher_order { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_new_provider] + impl AreaCalculator for Scaled + where + Inner: AreaCalculator, + { + fn area(context: &Context) -> f64 { + Inner::area(context) * 2.0 + } + } + + #[cgp_new_provider] + impl> AreaCalculator for Doubled { + fn area(context: &Context) -> f64 { + Inner::area(context) * 2.0 + } + } + + #[cgp_impl(new UnitArea)] + impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } + } + + pub struct App; + + delegate_components! { + App { + AreaCalculatorComponent: Scaled>, + } + } + + check_components! { + App { + AreaCalculatorComponent, + } + } + + #[test] + fn the_stack_computes() { + assert_eq!(App.area(), 4.0); + } + } +} + +/// ## Common Mistakes +/// +/// The disambiguated associated const, which is the compiling half of the `E0034` entry. +/// `RateLimiter` and `App` are declared here from the page's inline names. +pub mod common_mistakes { + use cgp::prelude::*; + + #[cgp_component(RateLimiter)] + pub trait CanRateLimit { + const LIMIT: u64; + + fn allowed(&self) -> bool; + } + + pub struct AllowUnderLimit; + + #[cgp_provider] + impl RateLimiter for AllowUnderLimit { + const LIMIT: u64 = 100; + + fn allowed(_context: &Context) -> bool { + >::LIMIT > 0 + } + } + + pub struct App; + + delegate_components! { + App { + RateLimiterComponent: AllowUnderLimit, + } + } + + check_components! { + App { + RateLimiterComponent, + } + } + + #[test] + fn the_const_reads_through_both_traits() { + assert!(App.allowed()); + assert_eq!(::LIMIT, 100); + } +} diff --git a/example-code/tests/reference/macros/cgp_type.rs b/example-code/tests/reference/macros/cgp_type.rs new file mode 100644 index 00000000..a3dcb017 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_type.rs @@ -0,0 +1,286 @@ +//! Code from `docs/reference/macros/cgp_type.md` — *`#[cgp_type]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. + +/// ## Overview +/// +/// The wiring that supplies the scalar, and the direct impl the page offers as the alternative, +/// each on its own context since a context can take only one of them. +pub mod overview { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar; + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + } + } + + pub struct DirectApp; + + impl HasScalarType for DirectApp { + type Scalar = f64; + } + + #[test] + fn both_contexts_pick_f64() { + let _: ::Scalar = 1.0f64; + let _: ::Scalar = 1.0f64; + } +} + +/// ## Usage +/// +/// The default name, the bare override, the keyed form, and a generic trait parameter, which the +/// page states in prose. Each is its own module since each declares `HasScalarType`. +pub mod usage { + pub mod default_name { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar; + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + } + } + } + + pub mod bare_override { + use cgp::prelude::*; + + #[cgp_type(ProvideScalar)] + pub trait HasScalarType { + type Scalar; + } + + pub struct App; + + delegate_components! { + App { + ProvideScalarComponent: UseType, + } + } + + check_components! { + App { + ProvideScalarComponent, + } + } + } + + pub mod keyed_form { + use cgp::prelude::*; + + #[cgp_type { + name: ScalarComponent, + context: Ctx, + }] + pub trait HasScalarType { + type Scalar; + } + + pub struct App; + + delegate_components! { + App { + ScalarComponent: UseType, + } + } + + check_components! { + App { + ScalarComponent, + } + } + } + + pub mod generic_trait { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasLabelType { + type Label; + } + + pub struct App; + + delegate_components! { + App { + open LabelTypeProviderComponent; + + @LabelTypeProviderComponent.u32: UseType, + } + } + + check_components! { + App { + LabelTypeProviderComponent: u32, + } + } + + #[test] + fn the_label_type_is_chosen_per_parameter() { + let _: >::Label = String::new(); + } + } + + /// The `Copy` bound, satisfied by the wired `f64`. + pub mod bounds_on_the_associated_type { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Copy; + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + } + } + } +} + +/// ## Examples +/// +/// The abstract scalar with its check, the generic `zero`, and the area component importing the +/// scalar. The page names `Rectangle` and `Circle` without declaring them; they are declared and +/// wired per shape here, with the context supplying `f64`. +pub mod examples { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Copy; + } + + pub struct App; + + delegate_components! { + App { + open AreaCalculatorComponent; + + ScalarTypeProviderComponent: UseType, + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + AreaCalculatorComponent: [Rectangle, Circle], + } + } + + pub fn zero() -> Context::Scalar + where + Context: HasScalarType, + Context::Scalar: Default, + { + Default::default() + } + + #[cgp_component(AreaCalculator)] + #[use_type(HasScalarType.Scalar)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> Scalar; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub struct Circle { + pub radius: f64, + } + + #[cgp_impl(new RectangleArea)] + #[use_type(HasScalarType.{Scalar = f64})] + impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> Scalar { + shape.width * shape.height + } + } + + #[cgp_impl(new CircleArea)] + #[use_type(HasScalarType.{Scalar = f64})] + impl AreaCalculator { + fn area(&self, shape: &Circle) -> Scalar { + core::f64::consts::PI * shape.radius * shape.radius + } + } + + #[test] + fn the_context_decides_the_scalar() { + assert_eq!(zero::(), 0.0); + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(App.area(&rect), 6.0); + assert!(App.area(&Circle { radius: 1.0 }) > 3.14); + } +} + +/// ## Under the hood +/// +/// The self-referential bound whose copy on the `UseType` and `WithProvider` impls is rewritten. +/// Checked with `cargo cgp expand --item reference::macros::cgp_type::under_the_hood`. +pub mod under_the_hood { + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Mul + Clone; + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } + } + + check_components! { + App { + ScalarTypeProviderComponent, + } + } +} diff --git a/example-code/tests/reference/macros/mod.rs b/example-code/tests/reference/macros/mod.rs index 274d7c38..618af3d7 100644 --- a/example-code/tests/reference/macros/mod.rs +++ b/example-code/tests/reference/macros/mod.rs @@ -1,4 +1,9 @@ //! Code from the pages under `docs/reference/macros/`. +pub mod cgp_component; +pub mod cgp_fn; +pub mod cgp_impl; pub mod cgp_namespace; +pub mod cgp_provider; +pub mod cgp_type; pub mod delegate_components; From af7a6f95ee1c4f7ef574b33720d8f1fc4b7ec925 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 13:42:55 +0000 Subject: [PATCH 110/516] Review the M1 macro pages Probe the claims the revision stated without testing: a comma in #[use_provider] fails with 'expected +', a wrong #[cgp_impl] component override fails at the impl with E0277, and the Self form takes #[uses] and #[use_type]. Make #[cgp_type]'s mirror generic over the scalar so it tests the page's one-wiring-line claim, and mark the direct impl as an alternative to the wiring. Fix a missing blank line before a heading, a circular sentence, and a few loose phrasings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/cgp_component.md | 6 +- docs/reference/macros/cgp_fn.md | 6 +- docs/reference/macros/cgp_impl.md | 25 ++++-- docs/reference/macros/cgp_provider.md | 26 +++--- docs/reference/macros/cgp_type.md | 11 +-- ...ommon_mistakes_wrong_component_override.rs | 23 +++++ ...n_mistakes_wrong_component_override.stderr | 23 +++++ .../tests/reference/macros/cgp_impl.rs | 39 ++++++++- .../tests/reference/macros/cgp_type.rs | 84 ++++++++++++++----- 9 files changed, 193 insertions(+), 50 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.stderr diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 9168cd2b..ac0d1608 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -238,7 +238,7 @@ as `CanCalculateArea` does. It is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component) when the operation acts on a type parameter and `Self` only supplies the choices, as in `CanEncodeValue`. A parameter alone does not settle this: in `CanCompute` the target is `Input`, while `Code` is a -selector the wiring dispatches on. +[selector](/docs/reference/glossary#selector) the wiring dispatches on. The choice decides how far the wiring can vary. A self-targeted component's wiring is keyed on the type the operation acts on, so that type gets one provider for the whole program. That is no limit @@ -404,8 +404,8 @@ namespace impls one per attribute: Each of the first three comes with a matching `IsProviderFor` impl under the same `where` clause, so a component wired to `UseContext`, reached through `open`, or dispatched through `UseDelegate` still -reports a missing dependency by name. The `RedirectLookup` one additionally requires the provider it -redirects to to be `IsProviderFor` the component, which is how a missing dependency is reported +reports a missing dependency by name. The `RedirectLookup` one also requires the provider at the end +of the redirect to be `IsProviderFor` the component, which is how a missing dependency is reported through an `open` entry or a namespace path. The namespace impls carry none, since they are table entries rather than providers. diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 28571474..7631968d 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -149,8 +149,10 @@ it depends on. copies it onto both generated items, so the trait ends up declaring a lint-clean `-> impl Future`. Each attribute may be repeated, and each also takes a comma-separated list inside one attribute, as -in `#[uses(RectangleArea, HasName)]`. `#[use_provider]` is the exception in practice, because its -argument ends in a bound list that would swallow a second entry, so write one per inner provider. +in `#[uses(RectangleArea, HasName)]`. `#[use_provider]` is the exception: its argument ends in a +bound list joined by `+`, so a comma after it fails to parse with *expected `+`*. Write one +`#[use_provider]` per inner provider. + ## Examples A trait, another trait built on it, and a context that gets both without wiring anything: diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 8662e254..b5af932a 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -188,17 +188,17 @@ they let an idiomatic provider state what it needs. Each attribute may be repeated. `#[uses]` and `#[use_type]` also take a comma-separated list inside one attribute, which is the form to prefer: `#[uses(HasName, CanRaiseError)]` reads as one dependency list. `#[use_provider]` and `#[default_impl]` take one entry per attribute. -`#[use_provider]`'s own argument ends in a bound list, so the parser cannot tell where a second pair -begins, and `#[default_impl]` reads a single `Key in Namespace` spec. Write one attribute per inner -provider and one per registration. +`#[use_provider]`'s own argument ends in a bound list joined by `+`, so a comma after it fails to +parse with *expected `+`*, and `#[default_impl]` reads a single `Key in Namespace` spec. Write one +attribute per inner provider and one per registration. `#[cgp_impl]` does not read `#[extend]`, `#[extend_where]`, or [`#[impl_generics]`](../attributes/impl_generics.md), although you may see them on other CGP macros. Each of them acts on a *generated trait definition*, which a provider impl does not have, so they belong to [`#[cgp_fn]`](./cgp_fn.md) and, for `#[extend]`, to [`#[cgp_component]`](./cgp_component.md). Writing one here leaves a name nothing resolves; see -[Common Mistakes](#common-mistakes). An impl-side bound that really is impl-side goes in the block's -own `where` clause, which passes through untouched. +[Common Mistakes](#common-mistakes). A bound the implementation needs goes in `#[uses]`, or in the +block's own `where` clause, which passes through untouched. ### Implementing the consumer trait directly @@ -223,8 +223,8 @@ impl CanCalculateArea for Rectangle { A direct impl competes with the consumer blanket impl that [`#[cgp_component]`](./cgp_component.md#under-the-hood) generates, so the same type must not also -wire the component in `delegate_components!`. Doing both makes the two impls overlap, and the compiler -rejects them with `E0119`, *conflicting implementations of trait `CanCalculateArea`*. +wire the component in `delegate_components!`. Doing both makes the two impls overlap, and the +compiler rejects them with `E0119`, *conflicting implementations of trait `CanCalculateArea`*. ## Examples @@ -458,6 +458,17 @@ attribute it does not recognize to the generated provider impl rather than dropp produces a *cannot find attribute `extend` in this scope* error on the attribute's own line, and it does not mention `#[cgp_impl]`. +**The macro does not check a `: ComponentType` override against the trait.** A component that +does not belong to the provider trait registers the provider under the wrong key, and the provider +trait's own `IsProviderFor` supertrait, which names the real component, rejects the generated impl: + +```text +error[E0277]: the trait bound `Wrong: IsProviderFor` is not satisfied +``` + +Leave the override out unless the component's marker departs from the `{Trait}Component` +convention. + **A `#[default_impl]` registration works only when the header omits `for Context`.** The registration copies the impl's generic parameters as written, before the macro inserts the context. On the explicit `impl ShowImpl for Context` form, the copied `Context` appears diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 27b59938..016cbb47 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -84,6 +84,8 @@ pub trait CanCalculateArea { fn area(&self) -> f64; } +pub struct UnitArea; + #[cgp_provider(AreaComponent)] impl AreaCalculator for UnitArea { fn area(_context: &Context) -> f64 { @@ -99,7 +101,8 @@ by bare generic parameter names. A plain name yields a unit struct. A generic pr struct holding one public [`PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html) over its parameters, so that the parameters are bound. Several parameters share one tuple, and a lifetime is lifted into -[`Life<'a>`](../types/life.md), since `PhantomData` needs a type: +[`Life<'a>`](../types/life.md), because `PhantomData` takes a type argument and a lifetime is not +one: ```rust // from `... for RectangleArea` @@ -223,7 +226,7 @@ A couple of cases call for writing the raw form yourself: that `new` cannot declare, such as one carrying a default generic parameter (`pub struct IterSum(PhantomData);`) or one shared by several impls, is *not* by itself a reason to write the raw form: declare the struct yourself and keep writing the body - with `#[cgp_impl(ProviderName)]`, just without `new`. + with `#[cgp_impl(ProviderName)]`, without `new`. - **Reading, rather than writing.** A confusing provider error names types from this shape, and `cargo cgp expand` prints it. Recognizing the form is the main reason to read this page. @@ -281,11 +284,11 @@ occupy its slot in the tuple, which holds types. A provider for `ReferenceGetter derives `IsProviderFor, T)>`, keeping the order the arguments were written in. -**The macro rewrites one bound instead of copying it**, and this is the mechanism that makes a nested -provider stack diagnosable. A bound naming *this component's provider trait*, the inner-provider bound -of a [higher-order provider](../attributes/use_provider.md), gains its marker counterpart alongside it, -whether it is written in the `where` clause or inline on the type parameter, as in -`impl>`: +**The macro rewrites one bound instead of copying it**, and this is the mechanism that makes a +nested provider stack diagnosable. A bound naming *this component's provider trait*, the +inner-provider bound of a [higher-order provider](../attributes/use_provider.md), gains its marker +counterpart alongside it, whether it is written in the `where` clause or inline on the type +parameter, as in `impl>`: ```rust #[cgp_new_provider] @@ -356,11 +359,10 @@ error[E0428]: the name `RectangleArea` is defined multiple times ``` **`new` is not part of this attribute's grammar.** `#[cgp_provider(new RectangleArea)]` does not -declare the struct. It fails to parse with *unexpected token* at `RectangleArea`, because the argument -holds a component type and nothing else, and `new` has already been read as that type. -Which macro you invoke decides whether the struct is declared, so use -`#[cgp_new_provider]`. The `new` keyword you may have seen belongs to -[`#[cgp_impl]`](./cgp_impl.md#usage). +declare the struct. It fails to parse with *unexpected token* at `RectangleArea`, because the +argument holds a component type and nothing else, and `new` has already been read as that type. +Which macro you invoke decides whether the struct is declared, so use `#[cgp_new_provider]`. The +`new` keyword you may have seen belongs to [`#[cgp_impl]`](./cgp_impl.md#usage). **A higher-order provider over a lifetime-carrying component loses the inner marker bound.** The rewrite above finds the context by reading the inner bound's first argument. On a component with a diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index cecec7eb..d1b19069 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -78,8 +78,8 @@ The companion attributes of `#[cgp_component]` apply unchanged, so The trait may carry generic parameters, which the macro handles exactly as `#[cgp_component]` does: they follow the context in the provider trait, and a context chooses the type per parameter value, through `open` or [`#[derive_delegate]`](../attributes/derive_delegate.md). So -`pub trait HasLabelType { type Label; }` lets a context wire -`@LabelTypeProviderComponent.u32: UseType`. +`pub trait HasLabelType { type Label; }` lets a context that declares +`open LabelTypeProviderComponent;` wire `@LabelTypeProviderComponent.u32: UseType`. ### Bounds on the associated type @@ -158,7 +158,8 @@ and changing its `UseType` to `UseType` changes the scalar for every s `Scalar` in that signature is [`#[use_type]`](../attributes/use_type.md) at work, which is how an abstract type is *imported* wherever it is used. -Direct implementation stays available, and is often clearer for a single context: +Direct implementation stays available in place of the wiring, and is often clearer for a single +context. A context takes one or the other, since the two impls would overlap: ```rust impl HasScalarType for App { @@ -174,12 +175,12 @@ exactly this way, which is why every fallible trait can say `Error` and mean wha application picked. The decision worth making deliberately is **whether the type needs to be abstract at all**, because -there is a cheaper option that does more than it looks. +a cheaper option often covers the case. - **Prefer an inferred impl parameter while the type only flows through values.** If the type appears solely because a provider reads a field of it, [`#[impl_generics]`](../attributes/impl_generics.md) on a `#[cgp_fn]` puts a parameter on - the implementation alone. Nothing is wired, nothing is declared, and a context qualifies just by + the implementation alone. Nothing is wired, nothing is declared, and a context qualifies by carrying a field of a compatible type. - **Move up to an abstract type when the type must be nameable.** Two things force it: the trait's own signature has to mention the type, or two traits have to agree they mean the *same* type. An diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.rs b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.rs new file mode 100644 index 00000000..51a250cf --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.rs @@ -0,0 +1,23 @@ +//! `docs/reference/macros/cgp_impl.md`, *Common Mistakes*: a `: ComponentType` override that does +//! not belong to the provider trait makes the generated impl fail its `IsProviderFor` supertrait. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new Wrong: PerimeterCalculatorComponent)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.stderr b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.stderr new file mode 100644 index 00000000..1d1efa72 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.stderr @@ -0,0 +1,23 @@ +error[E0277]: the trait bound `Wrong: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.rs:16:16 + | +16 | #[cgp_impl(new Wrong: PerimeterCalculatorComponent)] + | ^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `Wrong` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.rs:17:1 + | +17 | / impl AreaCalculator { +18 | | fn area(&self) -> f64 { +19 | | 1.0 +20 | | } +21 | | } + | |_^ + = help: for that trait implementation, expected `PerimeterCalculatorComponent`, found `AreaCalculatorComponent` +note: required by a bound in `AreaCalculator` + --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_wrong_component_override.rs:6:1 + | + 6 | #[cgp_component(AreaCalculator)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AreaCalculator` + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/macros/cgp_impl.rs b/example-code/tests/reference/macros/cgp_impl.rs index 26ce54ea..d9e59e8f 100644 --- a/example-code/tests/reference/macros/cgp_impl.rs +++ b/example-code/tests/reference/macros/cgp_impl.rs @@ -7,7 +7,9 @@ /// /// The hand-written provider impl and the `#[cgp_impl]` block that replaces it. The page names /// `HasDimensions` without declaring it; it is an auto getter over two `f64` fields here, and each -/// form gets its own module since both declare `RectangleArea`. +/// form gets its own module since both declare `RectangleArea`. The page shows the hand-written +/// impl bare, as the shape `#[cgp_impl]` produces; here it carries `#[cgp_provider]`, which adds the +/// `IsProviderFor` impl a provider needs to be wired, and which the page introduces separately. pub mod overview { pub mod hand_written { use cgp::prelude::*; @@ -402,8 +404,43 @@ pub mod implementing_the_consumer_trait_directly { } } + /// `#[uses]` and `#[use_type]` on the `Self` form, which the page lists among the attributes + /// that still apply. `CanDescribe` is declared here. + #[cgp_auto_getter] + pub trait HasLabel { + fn label(&self) -> &str; + } + + #[cgp_component(Describer)] + #[use_type(HasErrorType.Error)] + pub trait CanDescribe { + fn describe(&self) -> Result; + } + + #[derive(HasField)] + pub struct Labeled { + pub label: String, + } + + impl HasErrorType for Labeled { + type Error = String; + } + + #[cgp_impl(Self)] + #[uses(HasLabel)] + #[use_type(HasErrorType.Error)] + impl CanDescribe for Labeled { + fn describe(&self) -> Result { + Ok(self.label().to_owned()) + } + } + #[test] fn the_direct_impls_apply() { + let labeled = Labeled { + label: "l".to_owned(), + }; + assert_eq!(labeled.describe(), Ok("l".to_owned())); let rect = Rectangle { width: 2.0, height: 3.0, diff --git a/example-code/tests/reference/macros/cgp_type.rs b/example-code/tests/reference/macros/cgp_type.rs index a3dcb017..c73d94d8 100644 --- a/example-code/tests/reference/macros/cgp_type.rs +++ b/example-code/tests/reference/macros/cgp_type.rs @@ -176,9 +176,13 @@ pub mod usage { /// ## Examples /// /// The abstract scalar with its check, the generic `zero`, and the area component importing the -/// scalar. The page names `Rectangle` and `Circle` without declaring them; they are declared and -/// wired per shape here, with the context supplying `f64`. +/// scalar. The page names `Rectangle` and `Circle` without declaring them. They are declared here +/// with `f32` fields, and the providers compute in whatever `Scalar` the context wires, so two +/// contexts differing only in `UseType` and `UseType` test the page's claim that one +/// wiring line changes the scalar for every shape. pub mod examples { + use core::ops::Mul; + use cgp::prelude::*; #[cgp_type] @@ -190,18 +194,13 @@ pub mod examples { delegate_components! { App { - open AreaCalculatorComponent; - ScalarTypeProviderComponent: UseType, - @AreaCalculatorComponent.Rectangle: RectangleArea, - @AreaCalculatorComponent.Circle: CircleArea, } } check_components! { App { ScalarTypeProviderComponent, - AreaCalculatorComponent: [Rectangle, Circle], } } @@ -220,39 +219,84 @@ pub mod examples { } pub struct Rectangle { - pub width: f64, - pub height: f64, + pub width: f32, + pub height: f32, } pub struct Circle { - pub radius: f64, + pub radius: f32, } #[cgp_impl(new RectangleArea)] - #[use_type(HasScalarType.{Scalar = f64})] - impl AreaCalculator { + #[use_type(HasScalarType.Scalar)] + impl AreaCalculator + where + Scalar: From + Mul, + { fn area(&self, shape: &Rectangle) -> Scalar { - shape.width * shape.height + Scalar::from(shape.width) * Scalar::from(shape.height) } } #[cgp_impl(new CircleArea)] - #[use_type(HasScalarType.{Scalar = f64})] - impl AreaCalculator { + #[use_type(HasScalarType.Scalar)] + impl AreaCalculator + where + Scalar: From + Mul, + { fn area(&self, shape: &Circle) -> Scalar { - core::f64::consts::PI * shape.radius * shape.radius + Scalar::from(core::f32::consts::PI) * Scalar::from(shape.radius) * Scalar::from(shape.radius) + } + } + + pub struct ShapesF32; + + pub struct ShapesF64; + + delegate_components! { + ShapesF32 { + open AreaCalculatorComponent; + + ScalarTypeProviderComponent: UseType, + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } + } + + delegate_components! { + ShapesF64 { + open AreaCalculatorComponent; + + ScalarTypeProviderComponent: UseType, + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } + } + + check_components! { + ShapesF32 { + AreaCalculatorComponent: [Rectangle, Circle], + } + } + + check_components! { + ShapesF64 { + AreaCalculatorComponent: [Rectangle, Circle], } } #[test] - fn the_context_decides_the_scalar() { - assert_eq!(zero::(), 0.0); + fn one_wiring_line_decides_the_scalar() { + assert_eq!(zero::(), 0.0f64); let rect = Rectangle { width: 2.0, height: 3.0, }; - assert_eq!(App.area(&rect), 6.0); - assert!(App.area(&Circle { radius: 1.0 }) > 3.14); + let as_f32: f32 = ShapesF32.area(&rect); + let as_f64: f64 = ShapesF64.area(&rect); + assert_eq!(as_f32, 6.0); + assert_eq!(as_f64, 6.0); + let _: f64 = ShapesF64.area(&Circle { radius: 1.0 }); } } From 866b74afc9d26727b123dbef6bf93ec8ab54e6dc Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 14:25:44 +0000 Subject: [PATCH 111/516] Revise the M2 macro reference pages against the source Resync #[cgp_getter], #[cgp_auto_getter], #[blanket_trait], #[async_trait], #[cgp_computer], #[cgp_producer], and #[cgp_auto_dispatch] with their internal documents and the source, and revise their prose. Probing corrected the #[cgp_getter] default name for a trait without Has, the #[cgp_auto_dispatch] supertrait claim and its stale matcher-call listing, and the coherence claims on both blanket macros. The pages gain the rejected method shapes, the Result detection rule, the Option<&[T]> boundary, the helper-name collision, and runnable examples in place of commented calls. Add an example-code mirror for all seven pages and a trybuild fixture for each rejected snippet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/async_trait.md | 39 +- docs/reference/macros/blanket_trait.md | 41 +- docs/reference/macros/cgp_auto_dispatch.md | 89 ++-- docs/reference/macros/cgp_auto_getter.md | 68 ++- docs/reference/macros/cgp_computer.md | 63 ++- docs/reference/macros/cgp_getter.md | 66 ++- docs/reference/macros/cgp_producer.md | 29 +- example-code/README.md | 2 +- ...sync_trait_common_mistakes_default_body.rs | 13 + ..._trait_common_mistakes_default_body.stderr | 10 + ...t_common_mistakes_const_without_default.rs | 12 + ...mmon_mistakes_const_without_default.stderr | 5 + ...trait_common_mistakes_hand_written_impl.rs | 27 ++ ...t_common_mistakes_hand_written_impl.stderr | 10 + ..._common_mistakes_method_without_default.rs | 14 + ...mon_mistakes_method_without_default.stderr | 5 + ...et_trait_common_mistakes_not_in_prelude.rs | 17 + ...rait_common_mistakes_not_in_prelude.stderr | 13 + ..._trait_common_mistakes_unsupported_item.rs | 16 + ...it_common_mistakes_unsupported_item.stderr | 13 + ...ispatch_common_mistakes_associated_type.rs | 27 ++ ...tch_common_mistakes_associated_type.stderr | 5 + ...dispatch_common_mistakes_generic_method.rs | 25 ++ ...atch_common_mistakes_generic_method.stderr | 5 + ...n_mistakes_hand_impl_on_extensible_enum.rs | 31 ++ ...stakes_hand_impl_on_extensible_enum.stderr | 12 + ...ch_common_mistakes_helper_function_name.rs | 27 ++ ...ommon_mistakes_helper_function_name.stderr | 36 ++ ...dispatch_common_mistakes_missing_derive.rs | 39 ++ ...atch_common_mistakes_missing_derive.stderr | 39 ++ ...ch_common_mistakes_missing_variant_impl.rs | 35 ++ ...ommon_mistakes_missing_variant_impl.stderr | 33 ++ ...to_dispatch_common_mistakes_no_receiver.rs | 25 ++ ...ispatch_common_mistakes_no_receiver.stderr | 5 + ...uto_dispatch_common_mistakes_supertrait.rs | 29 ++ ...dispatch_common_mistakes_supertrait.stderr | 16 + ..._dispatch_common_mistakes_two_lifetimes.rs | 25 ++ ...patch_common_mistakes_two_lifetimes.stderr | 19 + ...on_mistakes_associated_type_two_methods.rs | 13 + ...istakes_associated_type_two_methods.stderr | 5 + ...tter_common_mistakes_attribute_argument.rs | 10 + ..._common_mistakes_attribute_argument.stderr | 7 + ...ter_common_mistakes_field_name_mismatch.rs | 19 + ...common_mistakes_field_name_mismatch.stderr | 32 ++ ...n_mistakes_mut_return_under_shared_self.rs | 10 + ...stakes_mut_return_under_shared_self.stderr | 5 + ..._common_mistakes_mut_self_shared_option.rs | 10 + ...mon_mistakes_mut_self_shared_option.stderr | 16 + ...uto_getter_common_mistakes_option_slice.rs | 10 + ...getter_common_mistakes_option_slice.stderr | 30 ++ ...r_common_mistakes_rejected_method_shape.rs | 10 + ...mmon_mistakes_rejected_method_shape.stderr | 5 + ...on_mistakes_second_argument_not_phantom.rs | 10 + ...istakes_second_argument_not_phantom.stderr | 5 + ...o_getter_common_mistakes_third_argument.rs | 10 + ...tter_common_mistakes_third_argument.stderr | 5 + ...uter_common_mistakes_missing_error_type.rs | 19 + ..._common_mistakes_missing_error_type.stderr | 65 +++ .../cgp_computer_common_mistakes_receiver.rs | 14 + ...p_computer_common_mistakes_receiver.stderr | 5 + ...n_mistakes_single_argument_result_alias.rs | 13 + ...stakes_single_argument_result_alias.stderr | 5 + ...ter_common_mistakes_field_type_mismatch.rs | 27 ++ ...common_mistakes_field_type_mismatch.stderr | 28 ++ ..._common_mistakes_mut_self_shared_option.rs | 10 + ...mon_mistakes_mut_self_shared_option.stderr | 16 + ...gp_getter_common_mistakes_no_has_prefix.rs | 10 + ...etter_common_mistakes_no_has_prefix.stderr | 7 + ...ommon_mistakes_use_field_on_two_methods.rs | 29 ++ ...n_mistakes_use_field_on_two_methods.stderr | 47 ++ .../cgp_producer_common_mistakes_async.rs | 10 + .../cgp_producer_common_mistakes_async.stderr | 5 + .../cgp_producer_common_mistakes_generics.rs | 10 + ...p_producer_common_mistakes_generics.stderr | 5 + ...cgp_producer_common_mistakes_parameters.rs | 10 + ...producer_common_mistakes_parameters.stderr | 5 + .../tests/reference/macros/async_trait.rs | 171 ++++++++ .../tests/reference/macros/blanket_trait.rs | 165 ++++++++ .../reference/macros/cgp_auto_dispatch.rs | 171 ++++++++ .../tests/reference/macros/cgp_auto_getter.rs | 400 ++++++++++++++++++ .../tests/reference/macros/cgp_computer.rs | 255 +++++++++++ .../tests/reference/macros/cgp_getter.rs | 325 ++++++++++++++ .../tests/reference/macros/cgp_producer.rs | 161 +++++++ example-code/tests/reference/macros/mod.rs | 7 + 84 files changed, 3083 insertions(+), 109 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs create mode 100644 example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.rs create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.rs create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.rs create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.rs create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.rs create mode 100644 example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.stderr create mode 100644 example-code/tests/reference/macros/async_trait.rs create mode 100644 example-code/tests/reference/macros/blanket_trait.rs create mode 100644 example-code/tests/reference/macros/cgp_auto_dispatch.rs create mode 100644 example-code/tests/reference/macros/cgp_auto_getter.rs create mode 100644 example-code/tests/reference/macros/cgp_computer.rs create mode 100644 example-code/tests/reference/macros/cgp_getter.rs create mode 100644 example-code/tests/reference/macros/cgp_producer.rs diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 807043a8..9f300276 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -11,11 +11,11 @@ Rewrite a trait's `async fn` declarations into the lint-clean `-> impl Future` f ## Overview -Writing a bare `async fn` inside a trait compiles on stable Rust, and the compiler warns about it. The -`async_fn_in_trait` lint fires because the future such a method returns is *opaque*: a caller working through -the trait cannot name it, so they cannot require anything of it, most importantly that it is `Send`. The -hand-written way to silence the lint is to declare the method as a future-returning function instead, which -is correct and obscures the intent: +Writing a bare `async fn` inside a public trait compiles on stable Rust, and the compiler warns +about it. The `async_fn_in_trait` lint fires because the future such a method returns is *opaque*: a +caller working through the trait cannot name it, so they cannot require anything of it, most +importantly that it is `Send`. The hand-written way to silence the lint is to declare the method as +a future-returning function instead, which is correct and obscures the intent: ```rust fn fetch(&self, id: &str) -> impl Future, String>>; @@ -32,12 +32,11 @@ pub trait CanFetch { The trait reads as async code, and the declaration the compiler sees is the lint-clean one. -**The rewrite is a plain desugaring, not a framework.** Unlike the widely-used `async-trait` crate, nothing -here boxes the future or allocates: it is return-position `impl Trait` in traits, so the future is exactly the -one the body produces and the call costs what a hand-written future-returning method costs. That is why the -macro is used throughout CGP wherever a trait's methods are asynchronous: it is simply how an async -method is -spelled. +**The rewrite is a plain desugaring, not a framework.** Unlike the widely-used `async-trait` crate, +nothing here boxes the future or allocates: it is return-position `impl Trait` in traits, so the +future is exactly the one the body produces and the call costs what a hand-written future-returning +method costs. That is why the macro is used throughout CGP wherever a trait's methods are +asynchronous: it is how an async method is spelled. One thing it does *not* do is add a `Send` bound, and that omission has consequences the moment a future is spawned. It is covered under [Common Mistakes](#common-mistakes). @@ -132,8 +131,17 @@ delegate_components! { StorageObjectFetcherComponent: FetchFromBucket, } } + +check_components! { + App { + StorageObjectFetcherComponent, + } +} ``` +`App` is an [environmental context](/docs/reference/glossary#environmental-context): it stands for +the application and holds the bucket name the provider reads. + Notice the provider needs no `#[async_trait]` of its own. An `async fn` is already legal in an impl block, since only a trait *declaration* trips the lint, so the provider keeps the natural body while the trait carries the rewritten signature, and the two agree because an `async fn` desugars to exactly such a future-returning @@ -228,10 +236,11 @@ the rewrite produces a bare `impl Future`, the future is `Send` only happens to be, and the trait does not require it. So code that spawns the future onto a multi-threaded, work-stealing executor cannot express what it needs through this trait. -The bound you would want to write is Return Type Notation (`App: CanFetch`), which is not -stabilized, so it cannot be written today. The workaround is to declare a second, ordinary trait whose method -spells `+ Send` on its return type directly, and to implement it for each concrete context. That pattern is -mechanical but unavoidable; the opacity that makes the rewrite zero-cost is the same opacity that hides the +The bound you would want to write is Return Type Notation (`App: CanFetch`), which +is not stabilized, so stable Rust rejects it with *return type notation is experimental* (`E0658`). +The workaround is to declare a second, ordinary trait whose method spells `+ Send` on its return +type directly, and to implement it for each concrete context. That pattern is mechanical but +unavoidable; the opacity that makes the rewrite zero-cost is the same opacity that hides the auto-traits. **A default-bodied async method is mishandled.** The macro rewrites the *signature* and never the body, so a diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 60f03172..425937a0 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -36,7 +36,7 @@ pub trait FooBar: Foo + Bar { ``` **This is not a CGP component.** There is no consumer/provider split, no [component marker](/docs/reference/glossary#component-marker), and no wiring: -just an ordinary Rust trait and an ordinary blanket impl. It is the tool for a trait with exactly one +only an ordinary Rust trait and an ordinary blanket impl. It is the tool for a trait with exactly one definition, where you want extension-trait ergonomics without committing to the component machinery. When a second implementation becomes necessary, the trait can be promoted to a [`#[cgp_component]`](./cgp_component.md). @@ -72,8 +72,10 @@ one of your own type parameters: pub trait FooBar: Foo + Bar { /* ... */ } ``` -The trait may carry generic parameters, which are copied onto the impl, and associated types, which get the -special treatment described next. +The trait may carry generic parameters, which are copied onto the impl ahead of the context +parameter, so `pub trait Scaled: Foo` gets +`impl Scaled for __Context__`. It may also carry associated types, which +get the special treatment described next. A trait with no supertraits gets an impl for every type. ### Lifting an associated type out of a supertrait @@ -159,17 +161,17 @@ That last clause is the real discriminator, separating this macro from its close - **[`#[cgp_component]`](./cgp_component.md) when a second implementation is needed.** A blanket impl covers every type satisfying its bounds, which leaves nowhere for an alternative to live. Promoting later is cheap (the trait keeps its name and method), so starting here costs nothing if that changes. -- **A trait alias, when one exists.** The empty-body form above is a workaround for a language feature Rust - does not have on stable; it is the right workaround, but do not use the macro if a plain supertrait - bound reads fine at the use site. +- **A plain bound, when it reads well.** The empty-body form stands in for trait aliases, which + stable Rust lacks. If writing `Foo + Bar` where the bound is needed reads well, that needs no macro. - **Nothing at all, for a plain generic function.** If the requirement belongs in the signature and no caller is generic over the type, a function with a `where` clause is simpler and the propagation problem never arises. -One caution specific to this construct: a blanket impl is **[coherence](/docs/reference/glossary#coherence)-visible**, so it competes with any -other impl of the same trait. That is why the pattern admits exactly one definition, and why two -`#[blanket_trait]` traits whose bounds can both hold for one type cannot both cover that type for the same -trait. Needing that is the signal to move to a component. +One caution specific to this construct: a blanket impl is +**[coherence](/docs/reference/glossary#coherence)-visible**, so it competes with any other impl of +the same trait. That is why the pattern admits exactly one definition: a hand-written impl for a +type that could satisfy the bounds conflicts with it. Needing a different implementation for some +type is the signal to move to a component. ## Under the hood @@ -243,7 +245,10 @@ the lifted parameter, which makes it a requirement on the *underlying* type rath about the alias. Associated constants are forwarded like methods: their default expressions become the impl's definitions. A -method or constant with no usable default is an error, since the macro has nothing to forward. +method or constant with no usable default is an error, since the macro has nothing to forward. The +`Self::FooBar` rewrite reaches the whole trait, so a method that names the lifted type, such as +`fn clone_foo(value: &Self::FooBar) -> Self::FooBar`, reads the impl's `FooBar` parameter in the +impl's copy. ## Formal grammar @@ -268,8 +273,8 @@ reported as an unknown attribute rather than as a missing import: error: cannot find attribute `blanket_trait` in this scope ``` -Add `use cgp::core::macros::blanket_trait;`. This is the one macro on this page's family that needs it: -`#[cgp_fn]`, `#[cgp_component]`, and the rest are all re-exported by the prelude. +Add `use cgp::core::macros::blanket_trait;`. It is the one macro in this section that needs an +import: `#[cgp_fn]`, `#[cgp_component]`, and the rest are all re-exported by the prelude. **A method without a default body is an error.** The macro forwards defaults into the impl, so a bare declaration leaves it nothing to emit. This is the opposite of an ordinary trait, where a bodiless method is @@ -284,8 +289,14 @@ mirror each item into the impl and knows only those three shapes. trait and in the impl. Harmless, but worth knowing when reading an expansion and wondering whether the macro duplicated something by mistake. -**The blanket impl blocks any hand-written impl of the same trait.** Because it covers every type satisfying -its bounds, implementing the trait manually for a type that also satisfies them is a coherence conflict. +**The blanket impl blocks any hand-written impl of the same trait.** Because it covers every type +satisfying its bounds, implementing the trait manually for a type that also satisfies them is a +coherence conflict: + +```text +error[E0119]: conflicting implementations of trait `FooExt` for type `Ctx` +``` + Where a type needs different behaviour, the trait wants to be a [component](./cgp_component.md) instead. ## Related constructs diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 9095b819..942c7a6c 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -37,7 +37,8 @@ the enum, use the combinators directly. This is the convenient front end to ## Usage -Write the attribute above a trait definition. It takes no arguments: +Write the attribute above a trait definition. It takes no arguments, and any tokens given as one +are ignored: ```rust #[cgp_auto_dispatch] @@ -46,16 +47,19 @@ pub trait HasArea { } ``` -The trait may have generic parameters and [supertraits](/docs/reference/glossary#supertrait). Each method may take `self` by value, by shared -reference, or by mutable reference; may take further value or reference arguments; and may be `async`. +The trait may have generic parameters. Each method may take `self` by value, by shared reference, or +by mutable reference; may take further value or reference arguments; and may be `async`. -A couple of restrictions are enforced when the macro expands: +The macro enforces three restrictions when it expands: - **Every trait item must be a method.** Associated types and constants are rejected. +- **Every method must have a `self` receiver**, since the receiver is the enum value being matched. - **A method may not have non-lifetime generic parameters.** Lifetimes are fine. The reason is in the [Common Mistakes](#common-mistakes), and it is a real limitation rather than an oversight. -Each method must have a `self` receiver, since the receiver is the enum value being matched. +Two further shapes are accepted and then fail to compile: a +[supertrait](/docs/reference/glossary#supertrait) on the trait, and a method that needs two distinct +lifetimes. [Common Mistakes](#common-mistakes) covers both. The enum also has to be made extensible, with [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or the narrower variant derives, so the machinery can take it apart one variant at a time. @@ -156,8 +160,9 @@ the operation from scratch and expect contexts to configure it, start with a The macro keeps the trait unchanged and appends two kinds of item: one per-method computer, and one blanket impl of the trait for a fresh enum parameter. -For each method it emits a free function turned into a provider by -[`#[cgp_computer]`](./cgp_computer.md), named `Compute` plus the method name in PascalCase: +For each method it emits a free function, named after the method, which +[`#[cgp_computer]`](./cgp_computer.md) turns into a provider named `Compute` plus the method name in +PascalCase: ```rust #[cgp_computer(ComputeArea)] @@ -166,7 +171,7 @@ fn area<'__a__, __Variants__: HasArea>(__Variants__: &'__a__ __Variants__) -> f6 } ``` -The body just calls the trait method on the payload, which makes the per-variant handler "invoke +The body calls the trait method on the payload, which makes the per-variant handler "invoke `HasArea::area` on whatever this variant holds". It is bound by `__Variants__: HasArea` so it applies to every payload type implementing the trait, and borrows through a fresh `'__a__` lifetime to mirror the `&self` receiver. @@ -181,7 +186,7 @@ where __Variants__: HasExtractor, { fn area(&self) -> f64 { - MatchWithValueHandlersRef::::compute( + as Computer<_, _, _>>::compute( &(), PhantomData::<()>, self, @@ -190,11 +195,13 @@ where } ``` -A few things are worth reading off that. The matcher is invoked with a **unit context and unit code** -(`&()` and `PhantomData::<()>`), because the per-variant logic depends only on the payload, which is exactly -why a context cannot influence it. The `__Variants__: HasExtractor` bound requires the enum to be -extensible. And **the first `where` bound is where a missing variant impl is reported**: it says the matcher -must be a `Computer` over this enum, which holds only if every variant's payload can be handled. +A few things are worth reading off that. The matcher is invoked with a **unit context and unit +code** (`&()` and `PhantomData::<()>`), because the per-variant logic depends only on the payload, +which is exactly why a context cannot influence it. The call names the provider trait, with its +arguments inferred, so it stays unambiguous in a module that also imports `CanCompute`. The +`__Variants__: HasExtractor` bound requires the enum to be extensible. And **the first `where` bound +is where a missing variant impl is reported**: it says the matcher must be a `Computer` over this +enum, which holds only if every variant's payload can be handled. Which matcher is chosen depends on the method's receiver and argument list, and every choice comes from the value-handler family so the per-variant computer receives the bare payload: @@ -211,7 +218,7 @@ With arguments, the receiver and the arguments are bundled into the matcher's in // where MatchFirstWithValueHandlersRef: // for<'__a__> Computer<(), (), (&'__a__ __Variants__, (f64, f64)), Output = bool> fn contains(&self, arg_0: f64, arg_1: f64) -> bool { - MatchFirstWithValueHandlersRef::::compute( + as Computer<_, _, _>>::compute( &(), PhantomData::<()>, (self, (arg_0, arg_1)), @@ -227,8 +234,7 @@ the result. **A trait method cannot be generic**, and the macro explains why in the message itself: ```text -error: Dispatch trait methods cannot contain non-lifetime generic parameters due to the lack of - quantified constraints in Rust +error: Dispatch trait methods cannot contain non-lifetime generic parameters due to the lack of quantified constraints in Rust ``` The blanket impl would need a quantified bound ("for every instantiation of the method's type parameter, @@ -242,18 +248,49 @@ parameters are fine. error: Only function items are allowed in a dispatch trait ``` +**A method without a receiver is rejected**, with *Dispatcher method must have a self argument*. + +**A supertrait breaks the expansion.** The blanket impl implements the trait for every +`__Variants__` without requiring the supertrait, so Rust rejects it: + +```text +error[E0277]: the trait bound `__Variants__: Named` is not satisfied +``` + +Declare the dependency on each payload's impl instead of as a supertrait. + +**A method needing two distinct lifetimes fails to compile.** The macro quantifies the generated +bound over only one lifetime, so `fn lookup<'a>(&'a self, key: &str) -> &'a str`, which pairs a +named `'a` with the lifetime the macro gives the elided `&str`, reports +``error[E0261]: use of undeclared lifetime name `'__a__` ``. Name every reference with the same +lifetime, or elide them all. + +**The helper function takes the method's name.** Each method's per-variant function is a free +function called, for example, `area`, in the module where the trait is declared, so a module that +already has an `area` item fails with ``error[E0428]: the name `area` is defined multiple times``. +Declare the trait in a module of its own when the names clash. + **The enum must derive the extensible-data machinery.** Without -[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or the variant derives, the `HasExtractor` bound fails -and the error names that trait rather than the missing derive. +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or the variant derives, the call fails with +the error below, and a note names `HasExtractor` rather than the missing derive: + +```text +error[E0599]: the method `area` exists for reference `&Plain`, but its trait bounds were not satisfied +``` -**A missing variant impl is reported at the use site, against the matcher.** Forgetting `HasArea for Circle` -does not fail where the impl should have been; it fails where `shape.area()` is called, as an unsatisfied -bound on `MatchWithValueHandlersRef`. The variant that is missing is somewhere in the chain -rather than in the headline. +**A missing variant impl is reported at the use site, against the matcher.** Forgetting +`HasArea for Rectangle` does not fail where the impl should have been. It fails where +`shape.area()` is called, with the same `E0599` headline, and the notes list unsatisfied bounds on +`MatchWithValueHandlersRef` without naming the variant that lacks an impl. -**The generated impl is a blanket impl over every type**, not just your enum. This lets it cover any -extensible enum whose payloads implement the trait, and it means the trait cannot also be implemented by -hand for some other type without colliding with it. +**The generated impl is a blanket impl over every type that implements `HasExtractor`.** This lets +it cover any extensible enum whose payloads implement the trait. A hand-written impl for a type +outside that set, such as the payload structs themselves, coexists with it, but one for another +extensible enum collides: + +```text +error[E0119]: conflicting implementations of trait `HasArea` for type `Shape` +``` ## Related constructs diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index bef1a35f..fe00cefd 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -73,14 +73,21 @@ natural. The field's type is inferred from what you return: |---|---|---| | `&T` | `T` | by reference, no conversion | | `&str` | `String` | `.as_str()` | -| `&[T]` | anything `AsRef<[T]>` | `.as_ref()` | +| `&[T]` | any `'static` type implementing `AsRef<[T]>` | `.as_ref()` | | `Option<&T>` | `Option` | `.as_ref()` | | `Option<&str>` | `Option` | `.as_deref()` | | [`MRef<'_, T>`](../types/mref.md) | `T` | by reference, wrapped as `MRef::Ref(…)` | | An owned type (`f64`, `String`, a tuple, an array) | the same type | by reference, then `.clone()` | -A `&mut self` receiver reads mutably, and each reference form has a mutable mirror: `&mut T`, `&mut [T]` -through `AsMut<[T]>`, `Option<&mut T>` via `.as_mut()`, and `Option<&mut str>` via `.as_deref_mut()`. +A `&mut self` receiver reads mutably, through `HasFieldMut`, and each reference form has a mutable +mirror: `&mut T`, `&mut str` from a `String` via `.as_mut_str()`, `&mut [T]` through `AsMut<[T]>`, +`Option<&mut T>` via `.as_mut()`, and `Option<&mut str>` via `.as_deref_mut()`. A `&mut` anywhere +in the return type needs that receiver, and under `&self` the macro rejects it with +*&mut self is required for mutable field reference*. + +Two combinations fall outside the table. `Option<&[T]>` has no rule of its own, so the `Option<&T>` +rule applies and asks for an unsized `Option<[T]>` field, which the compiler rejects. And a shared +`Option` return under `&mut self` does not compile, as [Common Mistakes](#common-mistakes) records. The `&str` row is the one most often wanted and least obvious: the context stores a `String` and the getter hands out a borrow of it, so no context ever has to hold a `&str`. **These are the same rules an @@ -123,7 +130,8 @@ pub trait HasFoo { It is forwarded to the generated method untouched and plays no part in the field lookup; it is there so a getter can carry a type-level argument in its signature. Anything else in that position is rejected with -*only PhantomData is allowed as second argument*, and a third argument is rejected outright. +*only PhantomData is allowed as second argument*, and a third argument with +*getter method must contain exactly one `&self` argument*. ### A type inferred from the field @@ -140,8 +148,35 @@ pub trait HasName { ``` The bound is enforced on whatever the field holds. When an associated type is present the trait must -contain **exactly one** getter method, whose return type is `&Self::AssocType`. There is only one field -for the type to be inferred from. +contain **exactly one** getter method, whose return type reads that type, most often as +`&Self::AssocType`. There is only one field for the type to be inferred from. A second associated +type, a generic associated type, a second method, or a return type that reads some other type is +rejected. + +### Companion attributes and trait generics + +The macro runs the attribute collector of [`#[cgp_component]`](./cgp_component.md), so +[`#[extend(...)]`](../attributes/extend.md) and [`#[use_type(...)]`](../attributes/use_type.md) +apply. Each becomes a bound on the context in the blanket impl, alongside any supertrait written +natively, and `#[use_type]` rewrites a bare abstract type in the signatures: + +```rust +#[cgp_auto_getter] +#[use_type(HasScalarType.Scalar)] +pub trait HasSide { + fn side(&self) -> &Scalar; +} +``` + +A trait may also carry generic parameters, which stay on the blanket impl and flow into the field +bound, so `trait HasValue { fn value(&self) -> &T; }` reads a `value` field of any type. + +### Methods the macro rejects + +A getter method is a plain signature, and the macro rejects anything more with a message naming the +problem: a `const`, `async`, or `unsafe` method, a method with generic parameters or a `where` +clause, a method without a return type, and a by-value `self` receiver. So is any trait item other +than a method or the one associated type. ## Examples @@ -336,6 +371,27 @@ error: #[cgp_auto_getter] does not accept any attribute argument here, because nothing else about the getter had to be declared. A missing `use` reports the method as not found rather than the trait as not imported. +**A `&mut self` getter cannot return a shared `Option`.** The macro picks the conversion from the +receiver, so `fn maybe(&mut self) -> Option<&u32>` reads with `.as_mut()`, produces an +`Option<&mut u32>`, and fails, because that type does not coerce to `Option<&u32>`: + +```text +error[E0308]: mismatched types +``` + +The plain reference, `&str`, slice, and `MRef` forms are unaffected, because a `&mut` result +coerces to the shared one. Return `Option<&mut T>` from a `&mut self` getter, or take `&self`. + +**`Option<&[T]>` is not a supported return type.** It falls through to the `Option<&T>` rule, which +bounds the field as `Option<[u8]>`: + +```text +error[E0277]: the size for values of type `[u8]` cannot be known at compilation time +``` + +Return `Option<&Vec>` from a `Vec` field, or read the option with `&Option>` and convert +at the call site. + **`#[prefix]` and `#[derive_delegate]` are accepted and dropped.** The macro runs the attribute collector of [`#[cgp_component]`](./cgp_component.md) so that `#[extend]` and `#[use_type]` apply, but it does not generate a component, so those two attributes register nothing and report nothing. A getter that diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index c0edd3de..03808992 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -32,13 +32,12 @@ that makes the *same function* answer the whole family. That wiring is the part `compute`, `try_compute`, `compute_async`, and `handle`, along with their by-reference forms, without you implementing any of them. -That last property is the whole reason for the macro. The family exists so a provider can declare exactly -the properties it has, and the [promotion combinators](../providers/handler/index.md) exist so a -simpler provider can stand in where a more capable one is expected: an infallible computation is a -fallible one that never fails, a synchronous one is an async one that never awaits. `#[cgp_computer]` picks -the narrowest -base that fits your function and wires the promotions for the rest, so you write one body and get every -shape. +That last property is the whole reason for the macro. The family exists so a provider can declare +exactly the properties it has, and the [promotion combinators](../providers/handler/index.md) exist +so a simpler provider can stand in where a more capable one is expected: an infallible computation +is a fallible one that never fails, a synchronous one is an async one that never awaits. +`#[cgp_computer]` picks the narrowest base that fits your function and wires the promotions for the +rest, so you write one body and get every shape. ## Usage @@ -62,7 +61,8 @@ argument is used verbatim. The function's shape decides everything else: - **Its parameters become the input.** Several parameters are collected into one tuple, so - `fn add(a: u64, b: u64)` has input `(u64, u64)`. + `fn add(a: u64, b: u64)` has input `(u64, u64)`. A single parameter's input is its bare type, and + no parameters give `()`. - **Its return type becomes the output.** - **It must not take `self`.** A handler provider has no receiver; the context is supplied separately by the handler machinery. @@ -82,10 +82,14 @@ promotion bundle: | `async fn f(..) -> T` | `AsyncComputer` | `PromoteAsyncComputer` | | `async fn f(..) -> Result` | `AsyncComputer` | `PromoteHandler` | -The `Result` row is worth a careful read. The base trait stays `Computer`, and its `Output` is simply the +The `Result` row is worth a careful read. The base trait stays `Computer`, and its `Output` is the `Result` type as written. Only the *bundle* changes, and it makes `try_compute` and `handle` surface the `Ok`/`Err` outcome as success or failure rather than handing back a `Result` as a plain value. +The macro recognizes a `Result` by its spelling, not its meaning: the return type must be written +`Result`, with `Result` as the whole path and two arguments. +[Common Mistakes](#common-mistakes) covers the spellings it misses. + ## Examples One function, every shape. The context here only has to supply the error type the fallible members need: @@ -108,13 +112,20 @@ delegate_components! { } } -// All four are answered by the single `add` definition: -// Add::compute(&App, PhantomData::<()>, (1, 2)) == 3 -// Add::try_compute(&App, PhantomData::<()>, (1, 2)) == Ok(3) -// Add::compute_async(&App, PhantomData::<()>, (1, 2)) resolves to 3 -// Add::handle(&App, PhantomData::<()>, (1, 2)) resolves to Ok(3) +pub fn demo() { + // All four are answered by the single `add` definition. + assert_eq!(Add::compute(&App, PhantomData::<()>, (1, 2)), 3); + assert_eq!(Add::try_compute(&App, PhantomData::<()>, (1, 2)), Ok(3)); + + // These futures resolve to 3 and Ok(3). + let _future = Add::compute_async(&App, PhantomData::<()>, (1, 2)); + let _future = Add::handle(&App, PhantomData::<()>, (1, 2)); +} ``` +`App` is an [environmental context](/docs/reference/glossary#environmental-context) with no fields: +it exists to supply the error type. + Because the function returns a plain `u64`, the fallible forms always succeed. Switching it to return a `Result` changes which bundle is wired and therefore what those forms mean, with no change at the call sites: @@ -262,9 +273,27 @@ input is `(T)`, which Rust treats as plain `T`. **The fallible forms need an error type on the context.** `try_compute` and `handle` name the context's abstract error, so a context wiring the provider without an [`ErrorTypeProviderComponent`](../components/has_error_type.md) fails on those members while `compute` works -fine. This is an error about the error type, arriving only for part of the family. Note also that the wiring key is -**not in the prelude**: it has to be imported from `cgp::core::error`, and forgetting that reports the -component as an unresolved type rather than as a missing import. +fine. This is an error about the error type, arriving only for part of the family: + +```text +error[E0277]: the trait bound `App: DelegateComponent` is not satisfied +``` + +The wiring key is **not in the prelude**: it has to be imported from `cgp::core::error`, and +forgetting that reports the component as an unresolved type rather than as a missing import. + +**Only a `Result` spelled exactly that way selects the fallible bundle.** Any other spelling, +such as `core::result::Result` or `anyhow::Result`, is treated as a plain value, +so `try_compute` wraps the whole result in `Ok` instead of propagating its error. A one-argument +alias written `Result`, such as the one `use anyhow::Result;` brings in, fails outright: + +```text +error: expected `,` +``` + +Write the full `Result` form in a fallible computer's signature. + +**A function with a receiver is rejected**, with *Computer functions cannot have a receiver*. **A `Result` return changes the bundle, not the base trait.** The `Computer` impl's `Output` *is* the `Result`, so `compute` hands back a `Result` as an ordinary value while `try_compute` treats its `Err` as diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 6b8d6eaa..7882c33f 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -54,13 +54,12 @@ pub trait HasName { } ``` -Because `#[cgp_getter]` builds on [`#[cgp_component]`](./cgp_component.md), it needs a provider trait name -and derives one from the **trait** name: a leading `Has` is stripped and `Getter` appended, so `HasName` -yields the provider trait `NameGetter` and the marker `NameGetterComponent`. The macro is therefore at its -most ergonomic when getter traits follow the `Has{Field}` convention. - -The companion attributes of `#[cgp_component]` apply here too, so -[`#[prefix(...)]`](../attributes/prefix.md) registers the getter into a namespace. +Because `#[cgp_getter]` builds on [`#[cgp_component]`](./cgp_component.md), it needs a provider +trait name and derives one from the **trait** name: a leading `Has` is stripped and `Getter` +appended, so `HasName` yields the provider trait `NameGetter` and the marker `NameGetterComponent`. +The macro is therefore at its most ergonomic when getter traits follow the `Has{Field}` convention. +A trait whose name does not start with `Has`, or is exactly `Has`, gets no default, and must name +its provider. Pass an identifier to override it, as with `#[cgp_component]`: @@ -75,6 +74,9 @@ Here the provider trait is `GetName` and the component `GetNameComponent`. The k `name` / `provider` / `context` form works too; only the default for `provider` differs from `#[cgp_component]`. +The companion attributes of `#[cgp_component]` apply here too, so +[`#[prefix(...)]`](../attributes/prefix.md) registers the getter into a namespace. + ### What a context can wire it to The macro produces these providers, and which you name decides where the value comes from: @@ -116,6 +118,12 @@ delegate_components! { } } +check_components! { + Person { + NameGetterComponent, + } +} + pub fn greet(person: &Person) { println!("Hello, {}!", person.name()); } @@ -123,11 +131,17 @@ pub fn greet(person: &Person) { `person.name()` returns `first_name`, because the wiring said so. A second context can store it under yet another name and wire accordingly, with `HasName` and every caller unchanged. This is the whole -difference from the blanket-impl getter. +difference from the blanket-impl getter. `Person` is a +[value context](/docs/reference/glossary#value-context) here, the person whose name is read. Where the names *do* line up, `UseFields` gives the auto-getter behaviour without giving up the component: ```rust +#[derive(HasField)] +pub struct Employee { + pub name: String, +} + delegate_components! { Employee { NameGetterComponent: UseFields, @@ -183,11 +197,12 @@ Use something else in these cases. ## Under the hood -`#[cgp_getter]` emits everything [`#[cgp_component]`](./cgp_component.md) would: the consumer trait, the -provider trait, the two blanket impls, the marker, and the standard +`#[cgp_getter]` emits everything [`#[cgp_component]`](./cgp_component.md) would: the consumer trait, +the provider trait, the two blanket impls, the marker, and the standard [`UseContext`](../providers/use_context.md) and [`RedirectLookup`](../providers/redirect_lookup.md) -impls. It then adds the getter providers below. The macro always emits `UseFields`; it emits `UseField` -and `WithProvider` only when the trait has exactly one method, since both presuppose a single field. +impls. It then adds the getter providers below, in the order `UseFields`, `UseField`, +`WithProvider`. The macro always emits `UseFields`; it emits `UseField` and `WithProvider` only when +the trait has exactly one method, since both presuppose a single field. The important addition is the **`UseField` impl**, which decouples the field from the method name. From this trait: @@ -246,6 +261,12 @@ where } ``` +The `WithProvider` bound follows the getter's shape. A `&mut self` getter bounds on +`MutFieldGetter` instead of `FieldGetter` and reads through `get_field_mut`, and a slice getter +returning `&[T]` bounds the value as `Value: AsRef<[T]> + 'static` rather than fixing it with +`Value =`. The `UseField` and `UseFields` bounds change the same way, to `HasFieldMut` and to the +`AsRef` bound. + Each of these is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl carrying the same bounds, so a missing field is reported by name when the component is checked. @@ -271,16 +292,20 @@ for a single-method trait, because each supplies one field. Wiring a two-method with the tag expanded into its raw list: ```text -error[E0277]: the trait bound `UseField>>: IsProviderFor<..., ...>` - is not satisfied +error[E0277]: the trait bound `cgp::prelude::UseField>>: IsProviderFor` is not satisfied ``` Nothing in that says the trait had too many methods, which is the actual cause. Use `UseFields`, or split the trait into one component per field. -**The macro derives the provider name by stripping `Has`.** `HasName` yields `NameGetterComponent`, so -a trait *not* named `Has…` produces a component whose name may surprise you: `Dimensions` yields -`DimensionsGetterComponent`. Pass the name explicitly when the convention does not fit. +**A trait not named `Has…` must name its provider.** The default comes from stripping a leading +`Has`, so a trait such as `Dimensions` has nothing to strip, and a bare `#[cgp_getter]` on it fails: + +```text +error: the `provider` key must be given +``` + +Pass the provider name, as in `#[cgp_getter(DimensionsGetter)]`. **Wiring `UseFields` everywhere means the component was unnecessary.** If no context ever names a different field, [`#[cgp_auto_getter]`](./cgp_auto_getter.md) does the same job with no wiring at all, and @@ -291,12 +316,17 @@ returning `&str` requires `first_name` to be a `String`; a `&'static str` field tag chose the field and not the conversion: ```text -error[E0271]: type mismatch resolving `

`, with the component's own key as the tag. A provider written once for +`TypeProvider`, such as [`UseDelegatedType`](../providers/use_delegated_type.md), then serves every +`#[cgp_type]` component. `UseType` needs no adapter, since the first addition covers it directly. Each generated provider impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl carrying the same bounds, as everywhere else. @@ -341,7 +342,8 @@ headline, so read downward. **Without a check the mistake is silent**, which is - [`UseType`](../providers/use_type.md) — the provider a context wires to supply the concrete type. - [`#[use_type]`](../attributes/use_type.md) — imports an abstract type so its name can be written bare; a different construct from the `UseType` provider despite the shared name. -- [`HasType`](../components/has_type.md) — CGP's built-in abstract-type component, which this builds on. +- [`HasType`](../components/has_type.md) — CGP's tag-indexed abstract-type component, which the + generated `WithProvider` impl adapts. - [`HasErrorType`](../components/has_error_type.md) — the canonical abstract type, defined this way. - [`UseDelegatedType`](../providers/use_delegated_type.md) — resolves the type through a table rather than fixing it. From adf0feeb10ad2a0fc93e026164a3e9af25cac41c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 02:17:22 +0000 Subject: [PATCH 123/516] Tighten the component pages' front matter and pin the wrap ambiguity Keep each description within a search snippet's length and the HasErrorType title within the site's title budget, and add the CanWrapError E0034 fixture beside the CanRaiseError one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/components/has_error_type.md | 4 ++-- docs/reference/components/has_runtime.md | 2 +- docs/reference/components/has_runtime_type.md | 2 +- docs/reference/components/index.md | 2 +- ..._wrap_error_usage_ambiguous_concrete_call.rs | 17 +++++++++++++++++ ...p_error_usage_ambiguous_concrete_call.stderr | 16 ++++++++++++++++ 6 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.rs create mode 100644 example-code/tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.stderr diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index 1885b6d6..f7b7ec49 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -1,6 +1,6 @@ --- -title: 'HasErrorType — a context''s abstract error type' -description: 'The component that gives a context one shared, abstract Error type, so fallible generic code never names a concrete error and the context chooses it by wiring.' +title: 'HasErrorType — the context''s error type' +description: 'The component that gives a context one abstract Error type, so fallible generic code never names a concrete error and the context chooses it by wiring.' sidebar_label: 'HasErrorType' sidebar_position: 1 --- diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index 83398b47..b2bfab79 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -1,6 +1,6 @@ --- title: 'HasRuntime — borrow the context''s runtime' -description: 'The getter component that borrows the runtime value a context stores, so effectful generic code reaches Tokio, a mock, or a test executor without naming it.' +description: 'The getter component that borrows the runtime value a context stores, so effectful generic code reaches Tokio, a mock, or a test executor generically.' sidebar_label: 'HasRuntime' sidebar_position: 6 --- diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md index f5a4de55..d86fedae 100644 --- a/docs/reference/components/has_runtime_type.md +++ b/docs/reference/components/has_runtime_type.md @@ -1,6 +1,6 @@ --- title: 'HasRuntimeType — the abstract runtime type' -description: 'The abstract-type component that declares the runtime type a context runs against, chosen per context by wiring, for code that names the type but not a value.' +description: 'The abstract-type component that declares the runtime type a context runs against, chosen by wiring, for code that names the type but not a value.' sidebar_label: 'HasRuntimeType' sidebar_position: 7 --- diff --git a/docs/reference/components/index.md b/docs/reference/components/index.md index 15208ca3..539abe6c 100644 --- a/docs/reference/components/index.md +++ b/docs/reference/components/index.md @@ -1,6 +1,6 @@ --- title: 'Component reference' -description: 'The components CGP ships, grouped by job: the abstract error type and its raising and wrapping, abstract types, the handler family, and runtimes and runners.' +description: 'The components CGP ships, grouped by job: the abstract error type, raising and wrapping errors, abstract types, the handler family, runtimes, and runners.' sidebar_label: 'Overview' sidebar_position: 0 --- diff --git a/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.rs b/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.rs new file mode 100644 index 00000000..429d9c9a --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.rs @@ -0,0 +1,17 @@ +use cgp::core::error::{ErrorTypeProviderComponent, ErrorWrapper, ErrorWrapperComponent}; +use cgp::extra::error::DiscardDetail; +use cgp::prelude::*; + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorWrapperComponent: DiscardDetail, + } +} + +fn main() { + // error[E0034]: multiple applicable items in scope + let _ = App::wrap_error("failed".to_owned(), "detail".to_owned()); +} diff --git a/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.stderr b/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.stderr new file mode 100644 index 00000000..722fef29 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.stderr @@ -0,0 +1,16 @@ +error[E0034]: multiple applicable items in scope + --> tests/compile_fail/reference/components/can_wrap_error_usage_ambiguous_concrete_call.rs:16:18 + | +16 | let _ = App::wrap_error("failed".to_owned(), "detail".to_owned()); + | ^^^^^^^^^^ multiple `wrap_error` found + | + = note: candidate #1 is defined in an impl of the trait `cgp::prelude::CanWrapError` for the type `__Context__` + = note: candidate #2 is defined in an impl of the trait `ErrorWrapper` for the type `__Provider__` +help: use fully-qualified syntax to disambiguate + | +16 - let _ = App::wrap_error("failed".to_owned(), "detail".to_owned()); +16 + let _ = ::wrap_error("failed".to_owned(), "detail".to_owned()); + | +16 - let _ = App::wrap_error("failed".to_owned(), "detail".to_owned()); +16 + let _ = ::wrap_error("failed".to_owned(), "detail".to_owned()); + | From 8ed458da68b7ca9edd31f607fd959fc887622214 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 02:42:19 +0000 Subject: [PATCH 124/516] Revise the handler-family component reference pages Resync the ten pages under components/handler/ against the internal computer, try_computer, handler, and producer documents and the cgp-handler source, and give each a title and description (extending the front-matter sweep past macros/, attributes/, and derives/). Correctness fixes: - Computer, AsyncComputer, AsyncComputerRef, TryComputer, Handler, and Producer are in the prelude; only the consumer traits, ComputerRef, TryComputerRef, HandlerRef, and the one-step promotions are imported from cgp::extra::handler. - PromoteRef as a ...Ref member passes the borrow through and needs a provider for &'a Input at every lifetime; the ComputerRef and HandlerRef pages had the direction backwards. - #[cgp_computer] on a Result function yields a Computer whose Output is the Result, lifted by TryPromote, not a TryComputer; an owned-input computer does not answer compute_ref. - Producer's example is self-targeted with a Code selector, and a context cannot wire PromoteProducer. - #[prefix] bullets link the attribute page and state the path binding; #[derive_delegate] bullets mark the legacy tables and that open dispatches on Code, Input, or both. Examples now wire real providers with check_components! and runnable demos. New Common Mistakes (each a trybuild fixture): the E0034 bare call, an owned computer behind PromoteRef, and a bundle wired for a provider not wired to it (Handler and Producer). Also fix two import sentences outside the chunk: cgp_provider's ComputerRefComponent and the type-level DSLs concept page's Computer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/concepts/type-level-dsls.md | 3 +- .../components/handler/async_computer.md | 125 ++++++++---- .../components/handler/async_computer_ref.md | 92 ++++++--- docs/reference/components/handler/computer.md | 175 +++++++++++----- .../components/handler/computer_ref.md | 130 ++++++++---- docs/reference/components/handler/handler.md | 190 ++++++++++++------ .../components/handler/handler_ref.md | 138 ++++++++----- docs/reference/components/handler/index.md | 89 ++++---- docs/reference/components/handler/producer.md | 132 ++++++++---- .../components/handler/try_computer.md | 158 +++++++++------ .../components/handler/try_computer_ref.md | 135 +++++++++---- docs/reference/macros/cgp_provider.md | 4 +- ...common_mistakes_ambiguous_concrete_call.rs | 25 +++ ...on_mistakes_ambiguous_concrete_call.stderr | 16 ++ ...ef_common_mistakes_owned_input_computer.rs | 29 +++ ...ommon_mistakes_owned_input_computer.stderr | 58 ++++++ ...mon_mistakes_bundle_on_a_plain_computer.rs | 30 +++ ...mistakes_bundle_on_a_plain_computer.stderr | 64 ++++++ ...mon_mistakes_bundle_on_a_plain_producer.rs | 30 +++ ...mistakes_bundle_on_a_plain_producer.stderr | 63 ++++++ .../components/handler/async_computer.rs | 79 +++++++- .../components/handler/async_computer_ref.rs | 47 ++++- .../reference/components/handler/computer.rs | 110 +++++++++- .../components/handler/computer_ref.rs | 83 +++++++- .../reference/components/handler/handler.rs | 46 ++++- .../components/handler/handler_ref.rs | 65 +++++- .../reference/components/handler/producer.rs | 111 +++++++++- .../components/handler/try_computer.rs | 98 ++++++--- .../components/handler/try_computer_ref.rs | 70 ++++++- 29 files changed, 1850 insertions(+), 545 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.rs create mode 100644 example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.stderr create mode 100644 example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs create mode 100644 example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.stderr create mode 100644 example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs create mode 100644 example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.stderr create mode 100644 example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs create mode 100644 example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.stderr diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index 3953ce6d..c4331b95 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -41,7 +41,8 @@ These describe the fixed program; handlers can still receive runtime values as t ## Providers give syntax its behavior A provider implements one syntax form and asks the context to interpret its subexpressions. -This addition provider assumes the `Computer` provider trait is imported from `cgp::extra::handler`: +This addition provider assumes the `CanCompute` consumer trait is imported from +`cgp::extra::handler`; the `Computer` provider trait comes from the prelude: ```rust #[cgp_impl(new EvalAdd)] diff --git a/docs/reference/components/handler/async_computer.md b/docs/reference/components/handler/async_computer.md index e3eeca1f..35b3cd9c 100644 --- a/docs/reference/components/handler/async_computer.md +++ b/docs/reference/components/handler/async_computer.md @@ -1,25 +1,28 @@ --- +title: 'AsyncComputer — an async computation' +description: 'The handler-family component for a computation that must await but cannot fail: its async method returns the Output directly rather than a Result.' sidebar_label: 'AsyncComputer' sidebar_position: 5 --- # `AsyncComputer` -The asynchronous, infallible member of the handler family: a [`Computer`](./computer.md) that awaits. +The asynchronous, infallible member of the handler family: a [`Computer`](./computer.md) that +awaits. ## Overview `AsyncComputer` is for computations that must await but still cannot fail. Reading a value that is -already in memory is a [`Computer`](./computer.md); awaiting a timer or a channel that always yields is -an `AsyncComputer`. It is the async point on the family's synchronicity axis with the failure path still -absent, so it transforms an `Input` into an `Output` under a phantom `Code` tag, against a **context** -(the type a method runs on, which supplies the values an implementation needs as its own -fields), and returns the `Output` directly rather than a `Result`. +already in memory is a [`Computer`](./computer.md); awaiting a timer, or a channel that always +yields a value, is an `AsyncComputer`. It turns an `Input` into an `Output` under a phantom `Code` +tag, against a [**context**](/docs/reference/glossary#context) (the type the implementation runs +against), and its async method returns the `Output` directly rather than a `Result`. -It sits between [`Computer`](./computer.md), which drops the asynchrony, and [`Handler`](./handler.md), -which adds a failure path on top of the asynchrony. Like the pure computer, it never names an error type, -so it does not [supertrait](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md). See the -[handler family overview](./index.md) for how the members relate and promote. +It sits between [`Computer`](./computer.md), which drops the asynchrony, and +[`Handler`](./handler.md), which adds a failure path to it. Like the synchronous computer it never +names an error type, so it does not have [`HasErrorType`](../has_error_type.md) as a +[supertrait](/docs/reference/glossary#supertrait). See the [handler family overview](./index.md) for +how the members relate and promote. ## Definition @@ -40,78 +43,114 @@ pub trait CanComputeAsync { Its attributes: -- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form, which adds no `Send` bound to the future. - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `AsyncComputer` that implementations target and the wiring key `AsyncComputerComponent`, while `CanComputeAsync` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.AsyncComputerComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` and `UseInputDelegate` providers, which dispatch on the `Code` tag and on the `Input` type through an inner table; the `open` statement replaces both, dispatching on either parameter or on the pair. ## Usage -`AsyncComputer` and its consumer trait `CanComputeAsync` are imported from `cgp::extra::handler`. The -method is `async` and takes the input by value: +`AsyncComputer` and `AsyncComputerComponent` are in the prelude. The consumer trait +`CanComputeAsync` is not, and is imported from `cgp::extra::handler`. The method is `async` and +takes the input by value: ```rust async fn compute_async(&self, _code: PhantomData, input: Input) -> Self::Output; ``` -A context gains the operation by wiring `AsyncComputerComponent` to a provider, and it dispatches on -both the `Code` tag and the `Input` type. In everyday code the provider comes from -[`#[cgp_computer]`](../../macros/cgp_computer.md), which wires the promotion table so a synchronous -function also answers `CanComputeAsync`, and the crate ships a [`UseField`](../../providers/use_field.md) -provider that forwards the async computation to a field of the context. Its by-reference sibling is -[`AsyncComputerRef`](./async_computer_ref.md). +A context gains the operation by wiring `AsyncComputerComponent` to a provider, and the component +dispatches on both the `Code` tag and the `Input` type. A provider comes from one of four places: + +- **A hand-written provider** declares `async fn compute_async` in its impl, as the example below + does. +- **[`PromoteAsync

`](../../providers/handler/promote_async.md)**, imported from + `cgp::extra::handler`, runs a synchronous [`Computer`](./computer.md) `P` inside the async method, + so `AsyncComputerComponent: PromoteAsync` answers `compute_async` from a `Double` + computer. +- **[`#[cgp_computer]`](../../macros/cgp_computer.md)** implements `AsyncComputer` directly for an + `async fn`, and reaches it through promotion for a synchronous one. +- **[`UseField`](../../providers/use_field.md)** forwards the computation to the value stored + in the context's `Tag` field, which must itself implement `CanComputeAsync`. + +Its by-reference sibling is [`AsyncComputerRef`](./async_computer_ref.md). ## Examples -A generic consumer awaits an async computation wired on its context: +An async computer provider, wired into a context and awaited through the consumer trait: ```rust use core::marker::PhantomData; use cgp::prelude::*; use cgp::extra::handler::CanComputeAsync; -async fn run(context: &Context, input: u64) -> Context::Output -where - Context: CanComputeAsync, -{ - context.compute_async(PhantomData::, input).await +#[cgp_new_provider] +impl AsyncComputer for DoubleAsync { + type Output = u64; + + async fn compute_async(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } +} + +pub struct App; + +delegate_components! { + App { + AsyncComputerComponent: DoubleAsync, + } +} + +check_components! { + App { + AsyncComputerComponent: ((), u64), + } +} + +pub async fn run(app: &App) -> u64 { + app.compute_async(PhantomData::<()>, 21).await // 42 } ``` -`run` works for any context that wires an async computer for the given `Code` and `u64` input. The -example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the -provider. A provider is usually generated from a function with -[`#[cgp_computer]`](../../macros/cgp_computer.md) rather than written by hand. +`DoubleAsync` implements the provider trait with an `async fn`, so a real provider could await +inside it. `App` is an [environmental context](/docs/reference/glossary#environmental-context), and +the component is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: +the computation acts on the `Input`, while `App` decides the provider. The future `run` returns +needs an executor to run it, which CGP leaves to the application. ## When to use it -**Reach for `AsyncComputer` for a computation that awaits but cannot fail.** It is the async infallible -corner of the family, so a provider that only reads its input should prefer the by-reference -[`AsyncComputerRef`](./async_computer_ref.md). +**Reach for `AsyncComputer` for a computation that awaits but cannot fail.** A computation that only +reads its input fits the by-reference [`AsyncComputerRef`](./async_computer_ref.md) better. -Reach for [`Computer`](./computer.md) instead when nothing needs awaiting, since a synchronous computer -promotes into an `AsyncComputer` for free and stays usable in more positions. Reach for -[`Handler`](./handler.md) when the computation can also fail. Implement whichever single variant fits and -let the wiring promote it. +Reach for [`Computer`](./computer.md) instead when nothing needs awaiting, since `PromoteAsync` +lifts a synchronous computer into an `AsyncComputer` and the computer stays usable in the +synchronous positions too. Reach for [`Handler`](./handler.md) when the computation can also fail. +Implement whichever single member fits and let the wiring promote it. ## Related constructs - [`Computer`](./computer.md) — the synchronous counterpart; promotes into this. - [`AsyncComputerRef`](./async_computer_ref.md) — the by-reference variant of this component. -- [`Handler`](./handler.md) — adds a failure path on top of the asynchrony. -- [`#[cgp_computer]`](../../macros/cgp_computer.md) — builds a provider that answers this through - promotion. -- [Handler combinators](../../providers/handler/index.md) — promote a `Computer` into this. +- [`Handler`](./handler.md) — adds a failure path to the asynchrony. +- [`#[async_trait]`](../../macros/async_trait.md) — the attribute that rewrites its `async fn`. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) — builds a provider that answers this, directly or + through promotion. +- [Handler combinators](../../providers/handler/index.md) — `PromoteAsync` and the promotion + bundles. The ideas behind it: - [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and input-passing axes. +- [Recovering `Send` bounds](/docs/concepts/send-bounds) — restoring the `Send` guarantee the async + method does not carry. ## Source -- `AsyncComputer` and `AsyncComputerRef`: +- `AsyncComputer` and `AsyncComputerRef`, and the `UseField` async computer: [`async_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/async_computer.rs) +- `PromoteAsync`: + [`promote_async.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_async.rs) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/components/handler/async_computer_ref.md b/docs/reference/components/handler/async_computer_ref.md index 5a5bcc3b..51bf9feb 100644 --- a/docs/reference/components/handler/async_computer_ref.md +++ b/docs/reference/components/handler/async_computer_ref.md @@ -1,4 +1,6 @@ --- +title: 'AsyncComputerRef — async, borrowed input' +description: 'The handler-family component for a computation that awaits, cannot fail, and only reads its input, which its async method takes as &Input.' sidebar_label: 'AsyncComputerRef' sidebar_position: 9 --- @@ -10,16 +12,16 @@ borrows its input. ## Overview -`AsyncComputerRef` combines two of the family's axes at once: it is asynchronous like +`AsyncComputerRef` combines two of the family's axes: it is asynchronous like [`AsyncComputer`](./async_computer.md) and takes its input by reference like -[`ComputerRef`](./computer_ref.md). A computation that must await and only *reads* its argument, while -still never failing, fits it: its method is `async`, receives `&Input`, and returns the `Output` directly -with no failure path. It runs against a **context**, the type a method runs on that supplies the -values an implementation needs as its own fields. +[`ComputerRef`](./computer_ref.md). A computation that must await and only *reads* its argument, +while still never failing, fits it: its method is `async`, receives `&Input`, and returns the +`Output` directly with no failure path. It runs against a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. -It is the async by-reference corner of the infallible computers. Like the other computers it never names -an error type, so it does not [supertrait](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md). See the -[handler family overview](./index.md) for how the members relate and promote. +Like the other computers it never names an error type, so it does not have +[`HasErrorType`](../has_error_type.md) as a [supertrait](/docs/reference/glossary#supertrait). See +the [handler family overview](./index.md) for how the members relate and promote. ## Definition @@ -40,50 +42,80 @@ pub trait CanComputeAsyncRef { Its attributes: -- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form, which adds no `Send` bound to the future. - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `AsyncComputerRef` that implementations target and the wiring key `AsyncComputerRefComponent`, while `CanComputeAsyncRef` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.AsyncComputerRefComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` and `UseInputDelegate` providers, which dispatch on the `Code` tag and on the `Input` type through an inner table; the `open` statement replaces both, dispatching on either parameter or on the pair. ## Usage -`AsyncComputerRef` and its consumer trait `CanComputeAsyncRef` are imported from `cgp::extra::handler`. -The method is `async` and borrows the input: +`AsyncComputerRef` and `AsyncComputerRefComponent` are in the prelude. The consumer trait +`CanComputeAsyncRef` is not, and is imported from `cgp::extra::handler`. The method is `async` and +borrows the input: ```rust async fn compute_async_ref(&self, _code: PhantomData, input: &Input) -> Self::Output; ``` -A context gains the operation by wiring `AsyncComputerRefComponent` to a provider, and it dispatches on -both the `Code` tag and the `Input` type. It is the least commonly wired member of the family, reached -when a computation is at once async, infallible, and read-only over its input. A simpler variant is -usually promoted into it through the [handler combinators](../../providers/handler/index.md). +A context gains the operation by wiring `AsyncComputerRefComponent` to a provider, and the component +dispatches on both the `Code` tag and the `Input` type. Besides a hand-written provider, the +[`PromoteRef`](../../providers/handler/promote_ref.md) combinator answers it from an `AsyncComputer` +written for `&'a Input` at every lifetime, which is the entry every promotion bundle uses. The same +combinator serves the reverse direction: an `AsyncComputerRef` provider answers `compute_async` for +an owned input that dereferences to its `Input`. See [`ComputerRef`](./computer_ref.md#usage) for +the two directions, which work the same way here. ## Examples -A generic consumer awaits an infallible computation over a borrowed input: +A provider that counts the words of a borrowed string, wired into a context and awaited: ```rust use core::marker::PhantomData; use cgp::prelude::*; use cgp::extra::handler::CanComputeAsyncRef; -async fn scan(context: &Context, input: &String) -> Context::Output -where - Context: CanComputeAsyncRef, -{ - context.compute_async_ref(PhantomData::, input).await +#[cgp_new_provider] +impl AsyncComputerRef for CountWords { + type Output = usize; + + async fn compute_async_ref( + _context: &Context, + _code: PhantomData, + input: &String, + ) -> usize { + input.split_whitespace().count() + } +} + +pub struct App; + +delegate_components! { + App { + AsyncComputerRefComponent: CountWords, + } +} + +check_components! { + App { + AsyncComputerRefComponent: ((), String), + } +} + +pub async fn run(app: &App, text: &String) -> usize { + app.compute_async_ref(PhantomData::<()>, text).await } ``` -`scan` awaits the computation while keeping ownership of the `String` with the caller. The example is -**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the provider. +`run` awaits the computation while the caller keeps ownership of `text`. `App` is an [environmental +context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation +acts on the `Input`, while `App` decides the provider. ## When to use it -**Reach for `AsyncComputerRef` when a computation is async and infallible and only reads its input.** -That is a narrow combination, so most code reaches a simpler member first and lets promotion bridge to -this one. +**Reach for `AsyncComputerRef` when a computation is async and infallible and only reads its +input.** That is a narrow combination, so code often implements a simpler member and lets promotion +bridge to this one, which works when that member takes the borrow as its input. Reach for [`AsyncComputer`](./async_computer.md) when the computation takes the input by value, for [`ComputerRef`](./computer_ref.md) when a borrowed-input computation needs no awaiting, and for @@ -94,7 +126,7 @@ Reach for [`AsyncComputer`](./async_computer.md) when the computation takes the - [`AsyncComputer`](./async_computer.md) — the owned-input counterpart. - [`ComputerRef`](./computer_ref.md) — the synchronous by-reference computer. - [`HandlerRef`](./handler_ref.md) — the fallible async by-reference member. -- [Handler combinators](../../providers/handler/index.md) — promote a simpler variant into this. +- [Handler combinators](../../providers/handler/index.md) — `PromoteRef` and the promotion bundles. The ideas behind it: @@ -105,6 +137,8 @@ The ideas behind it: - `AsyncComputer` and `AsyncComputerRef`: [`async_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/async_computer.rs) +- `PromoteRef`: + [`promote_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_ref.rs) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md index 85e0cc45..a5796a05 100644 --- a/docs/reference/components/handler/computer.md +++ b/docs/reference/components/handler/computer.md @@ -1,25 +1,27 @@ --- +title: 'Computer — a synchronous computation' +description: 'The handler-family component for a synchronous computation that cannot fail: a provider turns an Input into an Output under a Code tag.' sidebar_label: 'Computer' sidebar_position: 1 --- # `Computer` -The pure synchronous transform of the handler family: infallible, and the simplest provider to write. +The synchronous, infallible member of the handler family, and the simplest provider to write. ## Overview -`Computer` is for computations that always succeed and need no error type. A computation that adds two -numbers, formats a value, or projects a field never fails and never needs the **context's** abstract -error, so forcing it to return a `Result` would be noise. The context is the type a method runs -on, which supplies the values an implementation needs as its own fields. `Computer` captures the -succeeds-always case: a provider names an `Output` type and produces it from the context, a phantom -`Code` tag, and an `Input`, with no failure path. +`Computer` is for computations that always succeed. Adding two numbers, formatting a value, or +projecting a field never fails, so returning a `Result` and requiring an error type would be noise. +A `Computer` provider names an `Output` type and produces it from the +[**context**](/docs/reference/glossary#context) (the type the implementation runs against), a +phantom `Code` tag naming which computation is wanted, and an `Input`, with no failure path. -It is the simplest member of the [handler family](/docs/concepts/handlers) and the one a provider author -reaches for first, because a pure computation can always be *promoted* into the fallible, async, and -general variants when the wiring needs them, while a fallible provider cannot be demoted back. Writing -the narrowest variant that fits keeps a provider usable in every position. +It is the member of the [handler family](/docs/concepts/handlers) a provider author reaches for +first, because promotion runs one way. The [handler combinators](../../providers/handler/index.md) +lift a `Computer` into the fallible and async members by wrapping its output in `Ok` or its call in +an async method, while a fallible or async provider never loses its failure path or its `await`. +Writing the narrowest member that fits keeps a provider usable in the most positions. ## Definition @@ -40,38 +42,73 @@ pub trait CanCompute { Its attributes: - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Computer` that implementations target and the wiring key `ComputerComponent`, while `CanCompute` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.ComputerComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` and `UseInputDelegate` providers, which dispatch on the `Code` tag and on the `Input` type through an inner table; the `open` statement replaces both, dispatching on either parameter or on the pair. ## Usage -`Computer` and its consumer trait `CanCompute` are imported from `cgp::extra::handler`. The consumer -method takes the context, a `PhantomData` naming which computation is wanted, and the `Input` by -value, returning the associated `Output`: +`Computer` and `ComputerComponent` are in the prelude. The consumer trait `CanCompute` is not, and +is imported from `cgp::extra::handler`. The consumer method takes the context, a `PhantomData` +naming which computation is wanted, and the `Input` by value, and returns the associated `Output`: ```rust fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; ``` -A context gains the operation by wiring `ComputerComponent` to a provider. In everyday code the -provider comes from [`#[cgp_computer]`](../../macros/cgp_computer.md), which turns a plain function such as -`fn double(input: u64) -> u64` into a `Computer` provider and wires the promotion table so the same -function also answers `CanTryCompute`, `CanComputeAsync`, `CanHandle`, and the by-reference forms. +A context gains the operation by wiring `ComputerComponent` to a provider. Three sources supply one: + +- **[`#[cgp_computer]`](../../macros/cgp_computer.md)** turns a plain function such as + `fn double(input: u64) -> u64` into a `Computer` provider, and wires that provider to a promotion + bundle so it answers the other members too. +- **The [handler combinators](../../providers/handler/index.md)** build a computer from other + providers: [`ReturnInput`](../../providers/handler/return_input.md) returns its input, + [`PipeHandlers`](../../providers/handler/pipe_handlers.md) and + [`ComposeHandlers`](../../providers/handler/compose_handlers.md) chain computers, and + [`Promote`](../../providers/handler/promote.md) lifts a [`Producer`](./producer.md) into a + `Computer`. +- **[`UseField`](../../providers/use_field.md)** forwards the computation to the value stored + in the context's `Tag` field, which must itself implement `CanCompute`. + +Wiring a component to a promotion bundle such as +[`PromoteComputer`](../../providers/handler/promote_computer.md) lifts a `Computer` into +the other members. The bundle wraps the output in `Ok` for [`TryComputer`](./try_computer.md) and +runs the computation inside an async method for [`AsyncComputer`](./async_computer.md). Its +by-reference entries pass the borrow `&Input` through as the input, so they work only for a provider +written for `&'a Input` at every lifetime: a computer over an owned `u64` answers `compute`, +`try_compute`, and `compute_async`, but not `compute_ref`. A fallible function written with +`#[cgp_computer]` becomes a `Computer` whose `Output` is the `Result`, and +[`TryPromote`](../../providers/handler/try_promote.md) reads that `Result` as the failure path of a +[`TryComputer`](./try_computer.md). + +A context that joins `DefaultNamespace` binds the provider at the component's prefixed path, since a +bare `ComputerComponent` entry would conflict with the namespace's own entry for that key (`E0119`): -The component dispatches on both the `Code` tag and the `Input` type. It has three siblings, each -differing from `Computer` by one axis and documented on its own page: -[`ComputerRef`](./computer_ref.md) borrows the input, [`AsyncComputer`](./async_computer.md) is the async -counterpart, and [`AsyncComputerRef`](./async_computer_ref.md) combines the two. None of the four -[supertrait](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md), because none of them can fail. +```rust +delegate_components! { + App { + namespace DefaultNamespace; + + @cgp.extra.handler.ComputerComponent: Double, + } +} +``` + +The component has three siblings, each differing from `Computer` on one axis and documented on its +own page: [`ComputerRef`](./computer_ref.md) borrows the input, +[`AsyncComputer`](./async_computer.md) is async, and [`AsyncComputerRef`](./async_computer_ref.md) +is both. None of the four has [`HasErrorType`](../has_error_type.md) as a +[supertrait](/docs/reference/glossary#supertrait), because none of them can fail. ## Examples -A computer provider that doubles its input, wired into a context and invoked through the consumer trait: +A computer provider that doubles its input, wired into a context directly and, through promotion, as +a fallible computer: ```rust use core::marker::PhantomData; use cgp::prelude::*; -use cgp::extra::handler::{CanCompute, Computer, ComputerComponent}; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{CanCompute, CanTryCompute}; #[cgp_new_provider] impl Computer for Double { @@ -82,39 +119,75 @@ impl Computer for Double { } } -#[derive(HasField)] pub struct App; delegate_components! { App { + ErrorTypeProviderComponent: UseType, ComputerComponent: Double, + TryComputerComponent: PromoteComputer, } } -// `App` now implements `CanCompute<(), u64, Output = u64>`: -fn run(app: &App) -> u64 { - app.compute(PhantomData::<()>, 21) // returns 42 +check_components! { + App { + [ComputerComponent, TryComputerComponent]: ((), u64), + } +} + +pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 21), 42); + assert_eq!(App.try_compute(PhantomData::<()>, 21), Ok(42)); } ``` -`Double` implements the `Computer` provider trait for any context and any `Code`, fixing `Input` and -`Output` to `u64`. `App` delegates `ComputerComponent` to it, and the call passes `PhantomData::<()>` as -the `Code` tag. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input` value, while -the context decides the provider. In practice a provider like this is written with -[`#[cgp_computer]`](../../macros/cgp_computer.md) rather than by hand. +`Double` implements the `Computer` provider trait for any context and any `Code`, with `u64` as both +input and output. `App` is an [environmental +context](/docs/reference/glossary#environmental-context) with no fields, and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation +acts on the `Input` value, while `App` decides the provider. `App` wires `ComputerComponent` to +`Double`, so `compute` returns `42`, and wires `TryComputerComponent` through the `PromoteComputer` +bundle, so `try_compute` returns `Ok(42)`. The fallible member needs an error type, which `App` sets +to `String` with `ErrorTypeProviderComponent`, imported from `cgp::core::error`. In practice +[`#[cgp_computer]`](../../macros/cgp_computer.md) writes `Double` from +`fn double(input: u64) -> u64` and wires every promotion itself. ## When to use it -**Reach for `Computer` for a synchronous transform that cannot fail.** It is the default member of the -family to implement, because promotion lifts it into every other variant, so one `Computer` provider can -answer a fallible or async bound elsewhere in the wiring. Prefer [`ComputerRef`](./computer_ref.md) when -the computation only reads its input, and [`AsyncComputer`](./async_computer.md) when it must await but -still cannot fail. +**Reach for `Computer` for a synchronous transform that cannot fail.** It is the default member of +the family to implement, because promotion lifts it into the fallible and async members, so one +`Computer` provider can answer a fallible or async bound elsewhere in the wiring. Prefer +[`ComputerRef`](./computer_ref.md) when the computation only reads its input, and +[`AsyncComputer`](./async_computer.md) when it must await but still cannot fail. Reach for [`TryComputer`](./try_computer.md) instead when the computation can fail, for -[`Handler`](./handler.md) when it is both async and fallible, and for [`Producer`](./producer.md) when it -takes no input. Do not force a fallible computation into a `Computer` by making its `Output` a `Result` -unless you specifically want the result passed through unexamined. +[`Handler`](./handler.md) when it is both async and fallible, and for [`Producer`](./producer.md) +when it takes no input. A computation that reads its context's fields, names an abstract type, or +calls another trait of the context is written as a provider with +[`#[cgp_impl]`](../../macros/cgp_impl.md), since a `#[cgp_computer]` function cannot reach its +context. + +## Common Mistakes + +**Calling `compute` on a concrete context by its bare name is ambiguous.** A context that delegates +`ComputerComponent` also implements the `Computer` provider trait, which the prelude brings into +scope, so `App::compute(&App, PhantomData::<()>, 21)` has two candidates: + +```text +error[E0034]: multiple applicable items in scope + --> src/main.rs:24:18 + | +24 | let _ = App::compute(&App, PhantomData::<()>, 21); + | ^^^^^^^ multiple `compute` found + | + = note: candidate #1 is defined in an impl of the trait `CanCompute` for the type `__Context__` + = note: candidate #2 is defined in an impl of the trait `cgp::prelude::Computer` for the type `__Provider__` +``` + +Use method syntax, as in `App.compute(PhantomData::<()>, 21)`, since only the consumer trait takes +`self`, or name the consumer trait, as in +`>::compute(&App, PhantomData, 21)`. The same holds for every member of +the family whose provider trait is in scope. ## Related constructs @@ -122,13 +195,13 @@ unless you specifically want the result passed through unexamined. - [`AsyncComputer`](./async_computer.md) — the async variant that awaits. - [`AsyncComputerRef`](./async_computer_ref.md) — the async, by-reference variant. - [`TryComputer`](./try_computer.md) — the fallible synchronous counterpart. -- [`Handler`](./handler.md) — the general async-and-fallible generalization. +- [`Handler`](./handler.md) — the async and fallible member. - [`Producer`](./producer.md) — the input-free member of the family. - [`#[cgp_computer]`](../../macros/cgp_computer.md) — builds a `Computer` provider from a plain function. -- [Handler combinators](../../providers/handler/index.md) — compose computers and promote them into the - other variants. -- [`UseField`](../../providers/use_field.md) — the built-in computer provider that forwards to a context - field. +- [Handler combinators](../../providers/handler/index.md) — compose computers and promote them into + the other members. +- [`UseField`](../../providers/use_field.md) — the built-in computer provider that forwards to a + context field. The ideas behind it: @@ -138,10 +211,12 @@ The ideas behind it: ## Source -- The synchronous computers `Computer`/`ComputerRef`: +- The synchronous computers `Computer`/`ComputerRef`, and the `UseField` computer: [`computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/computer.rs) - The async computers `AsyncComputer`/`AsyncComputerRef`: [`async_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/async_computer.rs) +- The promotion bundles: + [`promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/components/handler/computer_ref.md b/docs/reference/components/handler/computer_ref.md index 2c398e09..74bccb5a 100644 --- a/docs/reference/components/handler/computer_ref.md +++ b/docs/reference/components/handler/computer_ref.md @@ -1,4 +1,6 @@ --- +title: 'ComputerRef — compute from a borrowed input' +description: 'The handler-family component for a synchronous computation that cannot fail and only reads its input, which it takes as &Input.' sidebar_label: 'ComputerRef' sidebar_position: 6 --- @@ -9,17 +11,17 @@ The by-reference member of the handler family: a [`Computer`](./computer.md) tha ## Overview -`ComputerRef` is a [`Computer`](./computer.md) that takes its input by reference instead of by value. A -synchronous, infallible computation that only *reads* its argument and should not take ownership of it -fits `ComputerRef`, whose method receives `&Input` where `CanCompute` receives `Input`. Everything else -is the same: it transforms toward an `Output` under a phantom `Code` tag, against a **context** (the type -a method runs on, which supplies the values an implementation needs as its own fields), and +`ComputerRef` is a [`Computer`](./computer.md) that takes its input by reference instead of by +value. A synchronous, infallible computation that only *reads* its argument fits `ComputerRef`, +whose method receives `&Input` where `CanCompute` receives `Input`, so the caller keeps ownership. +Everything else is the same: it turns the input into an `Output` under a phantom `Code` tag, against +a [**context**](/docs/reference/glossary#context) (the type the implementation runs against), and returns the `Output` directly with no failure path. -It is the owned-versus-borrowed variant of the pure computer, differing on the input axis alone. Like -`Computer` it never names an error type, so it does not [supertrait](/docs/reference/glossary#supertrait) -[`HasErrorType`](../has_error_type.md). See the [handler family overview](./index.md) for how the members -relate. +It differs from `Computer` on the input axis alone. Like `Computer` it never names an error type, so +it does not have [`HasErrorType`](../has_error_type.md) as a +[supertrait](/docs/reference/glossary#supertrait). See the [handler family overview](./index.md) for +how the members relate. ## Definition @@ -40,62 +42,116 @@ pub trait CanComputeRef { Its attributes: - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `ComputerRef` that implementations target and the wiring key `ComputerRefComponent`, while `CanComputeRef` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.ComputerRefComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` and `UseInputDelegate` providers, which dispatch on the `Code` tag and on the `Input` type through an inner table; the `open` statement replaces both, dispatching on either parameter or on the pair. ## Usage -`ComputerRef` and its consumer trait `CanComputeRef` are imported from `cgp::extra::handler`. The method -borrows the input: +`ComputerRefComponent` is in the prelude. The provider trait `ComputerRef` and the consumer trait +`CanComputeRef` are not, and are imported from `cgp::extra::handler`. The method borrows the input: ```rust fn compute_ref(&self, _code: PhantomData, input: &Input) -> Self::Output; ``` -A context gains the operation by wiring `ComputerRefComponent` to a provider, and it dispatches on both -the `Code` tag and the `Input` type. A provider that reads rather than consumes its input reaches for -this variant; a [`Computer`](./computer.md) can also be bridged to it by the -[`PromoteRef`](../../providers/handler/index.md) combinator, which supplies an owned input by -dereferencing the borrow. Its async counterpart is [`AsyncComputerRef`](./async_computer_ref.md). +A context gains the operation by wiring `ComputerRefComponent` to a provider, and the component +dispatches on both the `Code` tag and the `Input` type. The +[`PromoteRef`](../../providers/handler/promote_ref.md) combinator, imported from +`cgp::extra::handler`, bridges the owned and borrowed forms in both directions, and the two +directions ask different things of the inner provider: + +- **`PromoteRef

` as a `Computer`** takes an owned input that dereferences to `Target`, such as a + `Box` for `Target = String`, and calls the `ComputerRef` provider `P` on `input.deref()`. + Any `ComputerRef` provider serves this direction. +- **`PromoteRef

` as a `ComputerRef`** passes the borrow `&Input` through as the input of the + `Computer` provider `P`, so `P` must implement `Computer` for `&'a Input` at every lifetime `'a`. + A computer written for an owned `u64` does not, so it cannot answer `compute_ref`. + +Its async counterpart is [`AsyncComputerRef`](./async_computer_ref.md). ## Examples -A generic consumer computes from a borrowed input: +A provider that measures a borrowed string, wired for borrowed input and, through `PromoteRef`, for +an owned input that dereferences to it: ```rust use core::marker::PhantomData; use cgp::prelude::*; -use cgp::extra::handler::CanComputeRef; +use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef, PromoteRef}; + +#[cgp_new_provider] +impl ComputerRef for StringLength { + type Output = usize; + + fn compute_ref(_context: &Context, _code: PhantomData, input: &String) -> usize { + input.len() + } +} + +pub struct App; + +delegate_components! { + App { + ComputerRefComponent: StringLength, + ComputerComponent: PromoteRef, + } +} -fn measure(context: &Context, input: &String) -> Context::Output -where - Context: CanComputeRef, -{ - context.compute_ref(PhantomData::, input) +check_components! { + App { + ComputerRefComponent: ((), String), + ComputerComponent: ((), Box), + } +} + +pub fn demo() { + let name = "hello".to_owned(); + + assert_eq!(App.compute_ref(PhantomData::<()>, &name), 5); + assert_eq!(App.compute(PhantomData::<()>, Box::new(name)), 5); } ``` -`measure` passes the input by reference, so the caller keeps ownership of the `String`. The example is -**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the context decides the provider. +`compute_ref` reads `name` without taking it, so the caller can still move it into the `Box` on the +next line. The `compute` call hands over the owned `Box`, and `PromoteRef` dereferences it +to the `String` that `StringLength` reads. `App` is an [environmental +context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation +acts on the `Input`, while `App` decides the provider. ## When to use it -**Reach for `ComputerRef` when a synchronous, infallible computation only needs to read its input.** It -avoids handing ownership to a computation that does not consume the value, which matters when the caller -reuses the input afterwards. +**Reach for `ComputerRef` when a synchronous, infallible computation only needs to read its input.** +It avoids handing ownership to a computation that does not consume the value, which matters when the +caller reuses the input afterwards. + +Reach for [`Computer`](./computer.md) instead when the computation takes the input by value, which +is the more common case, and for [`AsyncComputerRef`](./async_computer_ref.md) when a borrowed-input +computation must also await. If the computation can fail, use +[`TryComputerRef`](./try_computer_ref.md). + +## Common Mistakes + +**An owned-input `Computer` cannot answer `compute_ref`.** Wiring `ComputerRefComponent` to +`PromoteRef`, for a `Double` that implements `Computer` for `u64`, fails at the check, +because the promotion asks `Double` for `u64` borrowed at every lifetime. The compiler's note names +that requirement: + +```text + = note: required for `Double` to implement `for<'a> cgp::prelude::Computer` +``` -Reach for [`Computer`](./computer.md) instead when the computation takes the input by value, which is the -more common case, and for [`AsyncComputerRef`](./async_computer_ref.md) when a borrowed-input computation -must also await. If the computation can fail, use [`TryComputer`](./try_computer.md) or its by-reference -sibling [`TryComputerRef`](./try_computer_ref.md). +The same applies to the `ComputerRefComponent` entry of the `PromoteComputer` bundle and to a +[`#[cgp_computer]`](../../macros/cgp_computer.md) function over an owned parameter. Write the +provider as a `ComputerRef`, or give the function a reference parameter such as `value: &u64`. ## Related constructs - [`Computer`](./computer.md) — the owned-input counterpart. - [`AsyncComputerRef`](./async_computer_ref.md) — the async version of this by-reference variant. - [`TryComputerRef`](./try_computer_ref.md) — the fallible by-reference computer. -- [Handler combinators](../../providers/handler/index.md) — the `PromoteRef` combinator bridging owned - and borrowed inputs. +- [Handler combinators](../../providers/handler/index.md) — the `PromoteRef` combinator bridging + owned and borrowed inputs. The ideas behind it: @@ -106,6 +162,8 @@ The ideas behind it: - `Computer` and `ComputerRef`: [`computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/computer.rs) +- `PromoteRef`: + [`promote_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_ref.rs) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md index 081fbd7f..265f2053 100644 --- a/docs/reference/components/handler/handler.md +++ b/docs/reference/components/handler/handler.md @@ -1,4 +1,6 @@ --- +title: 'Handler — an async, fallible computation' +description: 'The general handler-family component: an async computation that can fail, returning a Result in the context''s error type. Simpler members promote into it.' sidebar_label: 'Handler' sidebar_position: 3 slug: /reference/components/handler/handler @@ -6,23 +8,23 @@ slug: /reference/components/handler/handler # `Handler` -The general computation component: asynchronous, fallible, and error-aware. +The general computation component: asynchronous and fallible. ## Overview -`Handler` is the corner of the [handler family](/docs/concepts/handlers) that offers everything the -family can: a computation that runs asynchronously *and* can fail. A handler that calls a remote service -must await the response and must report failures, so it lives where the family is both async and -fallible. It transforms an `Input` into an `Output` under a phantom `Code` tag, returning a `Result` -against the **context's** abstract error type, where the context is the type a method runs on -that supplies the values an implementation needs as its own fields. +`Handler` is for computations that must both await and fail, such as a call to a remote service, +which awaits the response and must report a failure. It is the corner of the [handler +family](/docs/concepts/handlers) that has both properties: it turns an `Input` into an `Output` +under a phantom `Code` tag and returns a `Result` in the abstract error type of the +[**context**](/docs/reference/glossary#context), the type the implementation runs against. -Every other handler component is a special case of `Handler` obtained by dropping one property: drop -the failure path and it becomes an [`AsyncComputer`](./computer.md); drop the asynchrony and it becomes -a [`TryComputer`](./try_computer.md); drop both and it becomes a [`Computer`](./computer.md). This is why -generic pipeline code bounds against `Handler`: it is the one bound *every* member of the family can -meet, because each simpler provider promotes safely up to it. The reverse does not hold, since a general -computation cannot be assumed pure or synchronous. +The other owned-input members each drop one of these properties. Without the failure path a +`Handler` is an [`AsyncComputer`](./async_computer.md), without the asynchrony it is a +[`TryComputer`](./try_computer.md), and without both it is a [`Computer`](./computer.md). Each of +them promotes into a `Handler` through the handler combinators, so generic code bounded by +`CanHandle` accepts a provider written for any of them once the context wires the matching +promotion. The reverse does not hold, since a general computation cannot be assumed synchronous or +infallible. ## Definition @@ -38,112 +40,166 @@ computation cannot be assumed pure or synchronous. pub trait CanHandle { type Output; - async fn handle( - &self, - _tag: PhantomData, - input: Input, - ) -> Result; + async fn handle(&self, _tag: PhantomData, input: Input) -> Result; } ``` Its attributes: -- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form, which adds no `Send` bound to the future. - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Handler` that implementations target and the wiring key `HandlerComponent`, while `CanHandle` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.HandlerComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` and `UseInputDelegate` providers, which dispatch on the `Code` tag and on the `Input` type through an inner table; the `open` statement replaces both, dispatching on either parameter or on the pair. - [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. ## Usage -`Handler` and its consumer trait `CanHandle` are imported from `cgp::extra::handler`. The consumer -method is `async` and returns a `Result` against the context's error type: +`Handler` and `HandlerComponent` are in the prelude. The consumer trait `CanHandle` is not, and is +imported from `cgp::extra::handler`. The consumer method is `async` and returns a `Result` in the +context's error type: ```rust async fn handle(&self, _tag: PhantomData, input: Input) -> Result; ``` -A context gains the operation by wiring `HandlerComponent` to a provider. In practice most `Handler` -implementations are not written directly but produced by *promoting* a simpler provider: a function -written as a [`#[cgp_computer]`](../../macros/cgp_computer.md) or [`#[cgp_producer]`](../../macros/cgp_producer.md) -wires the promotion table so the same function answers `CanHandle` too, and the -[handler combinators](../../providers/handler/index.md) lift the narrowest fitting variant to a handler -wherever one is required. +A context gains the operation by wiring `HandlerComponent` to a provider and by wiring an error +type. Most `Handler` implementations are not written directly but produced by promoting a simpler +provider, and each promotion provider, imported from `cgp::extra::handler`, takes one step: + +- **[`PromoteAsync

`](../../providers/handler/promote_async.md)** makes a `Handler` from a + [`TryComputer`](./try_computer.md) by running it inside an async method. +- **[`Promote

`](../../providers/handler/promote.md)** makes a `Handler` from an + [`AsyncComputer`](./async_computer.md) by wrapping its awaited output in `Ok`. +- **[`TryPromote

`](../../providers/handler/try_promote.md)** makes a `Handler` from an + `AsyncComputer` whose `Output` is already `Result`. + +A plain [`Computer`](./computer.md) takes two steps, as `PromoteAsync>`: `Promote` makes +the `TryComputer`, and `PromoteAsync` makes the `Handler` from it. A provider written with +[`#[cgp_computer]`](../../macros/cgp_computer.md) or +[`#[cgp_producer]`](../../macros/cgp_producer.md) is wired to its own promotion bundle, so a context +can wire `HandlerComponent` to it directly. The component dispatches on both the `Code` tag and the `Input` type, so wiring can route different -codes or inputs to different handlers, as covered under [dispatching](/docs/concepts/dispatching). Its -by-reference sibling [`HandlerRef`](./handler_ref.md), documented on its own page, is identical except -that its `handle_ref` method borrows the input as `&Input`. +codes or inputs to different handlers, as covered under [dispatching](/docs/concepts/dispatching). +Its by-reference sibling [`HandlerRef`](./handler_ref.md), documented on its own page, is identical +except that its `handle_ref` method borrows the input as `&Input`. ## Examples -A generic consumer that bounds its context by `CanHandle` accepts any wired computation, whatever its -underlying properties: +A generic consumer bounded by `CanHandle`, and a context that answers it with a synchronous computer +lifted in two steps: ```rust use core::marker::PhantomData; use cgp::prelude::*; -use cgp::extra::handler::CanHandle; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{CanHandle, Promote, PromoteAsync}; + +#[cgp_new_provider] +impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } +} -async fn run_with( +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + HandlerComponent: PromoteAsync>, + } +} + +check_components! { + App { + HandlerComponent: ((), u64), + } +} + +pub async fn run_with( context: &Context, - input: String, + input: u64, ) -> Result where - Context: CanHandle, + Context: CanHandle, { context.handle(PhantomData::, input).await } + +pub async fn demo() -> Result { + run_with::(&App, 21).await // Ok(42) +} ``` -`run_with` works for any context that wires a handler for the given `Code` and `String` input, whether -the wired provider is a pure `Computer`, a fallible `TryComputer`, an `AsyncComputer`, or a genuine -`Handler`, because the promotion combinators make each of them satisfy `CanHandle`. This is why generic -pipeline code targets `Handler`. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the -`Input` type, while the context decides which provider answers. +`run_with` works for any context that wires a handler for the given `Code` and a `u64` input, +whether the provider behind it is a genuine `Handler` or a simpler one lifted by promotion, as +`Double` is here. `App` is an [environmental +context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation +acts on the `Input`, while `App` decides which provider answers and which error type it returns. ## When to use it -**Bound generic pipeline code against `CanHandle` when it should accept any computation regardless of -which of those properties the provider actually has.** Because every simpler member promotes up to -a handler, -a consumer written against `Handler` is the most reusable, and it is the right target for I/O steps, -request handlers, and composed pipelines. +**Bound generic pipeline code by `CanHandle` when it should accept any computation, whichever of the +async and fallible properties the provider actually has.** A consumer written against `Handler` is +the most reusable, and it is the right target for I/O steps, request handlers, and composed +pipelines. + +Do not *write* a `Handler` provider by hand when a simpler member fits: implement a +[`Computer`](./computer.md) for a pure transform, a [`TryComputer`](./try_computer.md) for a +fallible synchronous one, or a [`Producer`](./producer.md) for an input-free one, and let the wiring +promote it. The simpler provider stays usable in the positions a `Handler` cannot fill. + +## Common Mistakes + +**A promotion bundle wired on a context expects its provider to be wired to the same bundle.** The +`HandlerComponent` entry of `PromoteComputer

` is `PromoteAsync

`, which needs `P` to be a +`TryComputer`, and a hand-written computer is not one. So wiring `HandlerComponent` to +`PromoteComputer`, for a `Double` that implements only `Computer`, fails at the check: + +```text +error[E0277]: the trait bound `Double: DelegateComponent` is not satisfied +... + = note: required for `Double` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` +``` -Do not *write* a `Handler` provider by hand when a simpler variant fits: implement a -[`Computer`](./computer.md) for a pure transform, a [`TryComputer`](./try_computer.md) for a fallible -synchronous one, or a [`Producer`](./producer.md) for an input-free one, and let the wiring promote it. -Writing the narrowest variant keeps the provider reusable in every position, where a `Handler` can only -be used where a full handler is wanted. +Spell both steps as `PromoteAsync>`, or write the provider with +[`#[cgp_computer]`](../../macros/cgp_computer.md), which wires it to `PromoteComputer` so the +bundle finds the `TryComputer` it needs. ## Related constructs - [`HandlerRef`](./handler_ref.md) — the by-reference variant that borrows its input. -- [`Computer`](./computer.md) — the pure synchronous member; promotes up to `Handler`. -- [`TryComputer`](./try_computer.md) — the fallible synchronous member; promotes up to `Handler`. -- [`AsyncComputer`](./async_computer.md) — the async infallible member; promotes up to `Handler`. +- [`Computer`](./computer.md) — the synchronous, infallible member; promotes into `Handler` in two + steps. +- [`TryComputer`](./try_computer.md) — the fallible synchronous member; promotes into `Handler`. +- [`AsyncComputer`](./async_computer.md) — the async infallible member; promotes into `Handler`. - [`Producer`](./producer.md) — the input-free member of the family. -- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Self::Error` a handler returns. -- [Handler combinators](../../providers/handler/index.md) — compose handlers and promote simpler variants - into them. -- [`#[cgp_computer]`](../../macros/cgp_computer.md) / [`#[cgp_producer]`](../../macros/cgp_producer.md) — wire - a function so it answers `CanHandle` through promotion. +- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Error` a handler returns. +- [Handler combinators](../../providers/handler/index.md) — compose handlers and promote simpler + members into them. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) / [`#[cgp_producer]`](../../macros/cgp_producer.md) — + wire a function so it answers `CanHandle` through promotion. The ideas behind it: - [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and input-passing axes. -- [Monadic handlers](/docs/concepts/monadic-handlers) — chaining handlers that short-circuit through a - monad. -- [Recovering `Send` bounds](/docs/concepts/send-bounds) — restoring the `Send` guarantee an async trait - method drops. +- [Monadic handlers](/docs/concepts/monadic-handlers) — chaining handlers that short-circuit through + a monad. +- [Recovering `Send` bounds](/docs/concepts/send-bounds) — restoring the `Send` guarantee the async + method does not carry. ## Source - `Handler` and `HandlerRef`: [`handler.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/handler.rs) -- The `ReturnInput` provider and the promotion combinators: - [`cgp-handler/src/providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/) +- The promotion providers and bundles: + [`cgp-handler/src/providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/providers) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/components/handler/handler_ref.md b/docs/reference/components/handler/handler_ref.md index 0f4e5c72..e6dbc9ca 100644 --- a/docs/reference/components/handler/handler_ref.md +++ b/docs/reference/components/handler/handler_ref.md @@ -1,25 +1,27 @@ --- +title: 'HandlerRef — async and fallible, borrowed' +description: 'The handler-family component for an async computation that can fail and only reads its input, which its async method takes as &Input.' sidebar_label: 'HandlerRef' sidebar_position: 8 --- # `HandlerRef` -The by-reference member of the handler family's general corner: a [`Handler`](./handler.md) that borrows -its input. +The by-reference member of the handler family's general corner: a [`Handler`](./handler.md) that +borrows its input. ## Overview -`HandlerRef` is a [`Handler`](./handler.md) that takes its input by reference. It is asynchronous and -fallible like the general handler, so it awaits and may return the **context's** abstract error, but its -method receives `&Input` where `CanHandle` receives `Input`. The context is the type a method runs -on, which supplies the values an implementation needs as its own fields. `HandlerRef` is the -owned-versus-borrowed variant of the family's most general member, differing on the input axis alone, for -an async-and-fallible computation that reads rather than consumes its argument. +`HandlerRef` is a [`Handler`](./handler.md) that takes its input by reference. It is asynchronous +and fallible like the general handler, so it awaits and may return the abstract error of the +[**context**](/docs/reference/glossary#context), the type the implementation runs against, but its +method receives `&Input` where `CanHandle` receives `Input`. It suits an async, fallible computation +that reads its argument rather than consuming it, such as a request handler that inspects a borrowed +request. -Because it can fail, it [supertraits](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md), which supplies the -`Self::Error` it names in its `Result`. See the [handler family overview](./index.md) for how the members -relate and promote. +Because it can fail, it has [`HasErrorType`](../has_error_type.md) as a +[supertrait](/docs/reference/glossary#supertrait), which supplies the `Error` it names in its +`Result`. See the [handler family overview](./index.md) for how the members relate and promote. ## Definition @@ -45,60 +47,103 @@ pub trait CanHandleRef { Its attributes: -- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form. +- [`#[async_trait]`](../../macros/async_trait.md) — rewrites the `async fn` into a method returning `-> impl Future`, the lint-clean, allocation-free form, which adds no `Send` bound to the future. - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `HandlerRef` that implementations target and the wiring key `HandlerRefComponent`, while `CanHandleRef` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.HandlerRefComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` and `UseInputDelegate` providers, which dispatch on the `Code` tag and on the `Input` type through an inner table; the `open` statement replaces both, dispatching on either parameter or on the pair. - [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. ## Usage -`HandlerRef` and its consumer trait `CanHandleRef` are imported from `cgp::extra::handler`. The method is -`async`, borrows the input, and returns a `Result`: +`HandlerRefComponent` is in the prelude. The provider trait `HandlerRef` and the consumer trait +`CanHandleRef` are not, and are imported from `cgp::extra::handler`. The method is `async`, borrows +the input, and returns a `Result`: ```rust async fn handle_ref(&self, _tag: PhantomData, input: &Input) -> Result; ``` -A context gains the operation by wiring `HandlerRefComponent` to a provider, and it dispatches on both -the `Code` tag and the `Input` type. Because the consumer trait supertraits `HasErrorType`, the context -must also wire an error type. A [`Handler`](./handler.md) is bridged to `HandlerRef` by the -[`PromoteRef`](../../providers/handler/index.md) combinator, which supplies an owned input by dereferencing -the borrow, so most `HandlerRef` implementations come from promotion rather than being written by hand. +A context gains the operation by wiring `HandlerRefComponent` to a provider and by wiring an error +type, and the component dispatches on both the `Code` tag and the `Input` type. Besides a +hand-written provider, the [`PromoteRef`](../../providers/handler/promote_ref.md) combinator answers +it from a `Handler` written for `&'a Input` at every lifetime, which is the `HandlerRefComponent` +entry of every promotion bundle. In the other direction it lets a `HandlerRef` provider answer +`handle` for an owned input that dereferences to its `Input`. See +[`ComputerRef`](./computer_ref.md#usage) for the two directions, which work the same way here. ## Examples -A generic consumer awaits a fallible computation over a borrowed input: +An async, fallible provider over a borrowed request, wired into a context and awaited: ```rust use core::marker::PhantomData; use cgp::prelude::*; -use cgp::extra::handler::CanHandleRef; - -async fn serve( - context: &Context, - request: &String, -) -> Result -where - Context: CanHandleRef, -{ - context.handle_ref(PhantomData::, request).await +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; +use cgp::extra::handler::{CanHandleRef, HandlerRef}; + +#[cgp_impl(new NonEmptyLength)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl HandlerRef { + type Output = usize; + + async fn handle_ref( + &self, + _code: PhantomData, + input: &String, + ) -> Result { + if input.is_empty() { + return Err(Self::raise_error("empty request".to_owned())); + } + + Ok(input.len()) + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + HandlerRefComponent: NonEmptyLength, + } +} + +check_components! { + App { + HandlerRefComponent: ((), String), + } +} + +pub async fn demo() { + let request = "GET /".to_owned(); + + assert_eq!(App.handle_ref(PhantomData::<()>, &request).await, Ok(5)); + assert_eq!( + App.handle_ref(PhantomData::<()>, &String::new()).await, + Err("empty request".to_owned()) + ); } ``` -`serve` passes the request by reference, so the caller keeps ownership, and returns the context's -abstract error on failure. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, -while the context decides the provider and the error type. +`NonEmptyLength` raises a `String` message into the context's error, which `App` sets to `String`, +so [`RaiseFrom`](../../providers/error/raise_from.md) raises it through the identity `From` impl. +The caller keeps ownership of `request`. `App` is an [environmental +context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation +acts on the `Input`, while `App` decides the provider and the error type. ## When to use it -**Reach for `HandlerRef` when an async, fallible computation only needs to read its input**, for instance -a request handler that inspects a borrowed request without consuming it. Bounding generic pipeline code -against it accepts any provider that fits, since the simpler by-reference variants promote up to it. +**Reach for `HandlerRef` when an async, fallible computation only needs to read its input.** Generic +code bounded by `CanHandleRef` accepts a provider for any by-reference member that is lifted into +it, through a promotion bundle or a hand-written chain of promotions. -Reach for [`Handler`](./handler.md) instead when the computation takes the input by value, which is the -more common case, and for [`TryComputerRef`](./try_computer_ref.md) when a borrowed-input fallible -computation is synchronous. Do not write a `HandlerRef` by hand when a simpler by-reference variant fits: +Reach for [`Handler`](./handler.md) instead when the computation takes the input by value, which is +the more common case, and for [`TryComputerRef`](./try_computer_ref.md) when a borrowed-input +fallible computation is synchronous. Do not write a `HandlerRef` by hand when a simpler member fits: implement that and let the wiring promote it. ## Related constructs @@ -106,21 +151,22 @@ implement that and let the wiring promote it. - [`Handler`](./handler.md) — the owned-input counterpart, and the family's general corner. - [`TryComputerRef`](./try_computer_ref.md) — the synchronous fallible by-reference computer. - [`AsyncComputerRef`](./async_computer_ref.md) — the infallible async by-reference computer. -- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Self::Error` this returns. -- [Handler combinators](../../providers/handler/index.md) — the `PromoteRef` combinator that bridges - `Handler` and `HandlerRef`. +- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Error` this returns. +- [`PromoteRef`](../../providers/handler/promote_ref.md) — bridges `Handler` and `HandlerRef`. The ideas behind it: - [Handlers](/docs/concepts/handlers) — the computation family and its sync, async, fallible, and input-passing axes. -- [Recovering `Send` bounds](/docs/concepts/send-bounds) — restoring the `Send` guarantee an async trait - method drops. +- [Recovering `Send` bounds](/docs/concepts/send-bounds) — restoring the `Send` guarantee the async + method does not carry. ## Source - `Handler` and `HandlerRef`: [`handler.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/handler.rs) +- `PromoteRef`: + [`promote_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_ref.rs) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/components/handler/index.md b/docs/reference/components/handler/index.md index f9db374d..0841dab5 100644 --- a/docs/reference/components/handler/index.md +++ b/docs/reference/components/handler/index.md @@ -1,51 +1,66 @@ --- +description: 'The handler family: Computer, TryComputer, Handler, Producer, and their async and by-reference variants, and how a provider promotes between them.' sidebar_label: 'Overview' sidebar_position: 0 --- # The handler family -The handler family models a computation as a swappable component, so a pipeline step, an I/O call, or a -type-level interpreter is wired and composed the same way as any other component. Every member -transforms an `Input` into an `Output` under a phantom `Code` tag, against a **context**, the type a -method runs on that supplies the values an implementation needs as its own fields. The members -differ along three axes: synchronous or async, infallible or fallible, and taking an input or not. This -page maps the family; each member has its own page for the full detail. +The handler family models a computation as a swappable component, so a pipeline step, an I/O call, +or a type-level interpreter is wired and composed the same way as any other component. Every member +turns an `Input` into an `Output` under a phantom `Code` tag, against a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. The +members differ along three axes: synchronous or async, infallible or fallible, and taking the input +by value, by reference, or not at all. This page maps the family; each member has its own page for +the full detail. The one distinction that organizes the rest is which corner of those axes a member sits in. -[`Computer`](./computer.md) is the simplest, a pure synchronous transform that cannot fail. -[`TryComputer`](./try_computer.md) adds a failure path, returning a `Result` against the context's -abstract error type. [`Handler`](./handler.md) adds asynchrony on top of that, so it is both async and -fallible, and it is the general corner every other member is a special case of. -[`Producer`](./producer.md) is the odd one out on the input axis: it takes no input and simply yields a -value from the context and a `Code` tag. - -The family is built to be written from its weakest member and promoted upward. A pure `Computer` -promotes into a `TryComputer` by wrapping its output in `Ok`, into an `AsyncComputer` by wrapping it in a -future that never awaits, and all the way up to a `Handler`; a `Producer` promotes into any of them by -ignoring the input the target supplies. Because promotion only ever widens, a provider author implements -the narrowest variant that fits and lets the wiring lift it wherever a more capable one is required. -This is why generic pipeline code bounds against [`Handler`](./handler.md): it is the one bound every -member can meet. - -The family has nine members in all, because three of the base members carry by-reference and, for the -computers, async siblings, each a component of its own that differs from its base by a single axis. The -computers cover both axes: [`Computer`](./computer.md) with [`ComputerRef`](./computer_ref.md), -[`AsyncComputer`](./async_computer.md), and [`AsyncComputerRef`](./async_computer_ref.md); -[`TryComputer`](./try_computer.md) with [`TryComputerRef`](./try_computer_ref.md); and -[`Handler`](./handler.md) with [`HandlerRef`](./handler_ref.md). [`Producer`](./producer.md) has no such -sibling, because it has no input to borrow. Each has its own page; the variant pages lean on their base -member for the shared model. +[`Computer`](./computer.md) is the simplest, a synchronous transform that cannot fail. +[`TryComputer`](./try_computer.md) adds a failure path, returning a `Result` in the context's +abstract error type. [`AsyncComputer`](./async_computer.md) makes the computer async instead, and +[`Handler`](./handler.md) is both async and fallible, the most general corner. +[`Producer`](./producer.md) is the odd one out on the input axis: it takes no input and yields a +value from the context and a `Code` tag alone. + +The family is built to be written from its narrowest member and promoted outward. A `Computer` +promotes into a `TryComputer` by wrapping its output in `Ok`, into an `AsyncComputer` by running +inside an async method, and into a `Handler` in two such steps. A `Producer` promotes into a +`Computer` by ignoring the input it is given. A by-reference member answers the owned-input one by +dereferencing the input, and the reverse works only for a provider that takes the borrow as its +input. Promotion never removes a failure path or an `await`, so a provider author implements the +narrowest member that fits and lets the wiring lift it where a more capable one is required. Generic +code bounded by `CanHandle` therefore accepts a provider written for any owned-input member, once +the context wires the matching promotion. + +The family has nine members in all, because each of the four input-taking corners carries a +by-reference sibling, a component of its own whose method takes `&Input`: +[`Computer`](./computer.md) with [`ComputerRef`](./computer_ref.md), +[`AsyncComputer`](./async_computer.md) with [`AsyncComputerRef`](./async_computer_ref.md), +[`TryComputer`](./try_computer.md) with [`TryComputerRef`](./try_computer_ref.md), and +[`Handler`](./handler.md) with [`HandlerRef`](./handler_ref.md). [`Producer`](./producer.md) has no +such sibling, because it has no input to borrow, and no async one either. The variant pages lean on +their base member for the shared model. + +Every member's wiring key is in the prelude, and so are the provider traits `Computer`, +`AsyncComputer`, `AsyncComputerRef`, `TryComputer`, `Handler`, and `Producer`. The consumer traits +(`CanCompute`, `CanTryCompute`, `CanHandle`, `CanProduce`, and their siblings), the provider traits +`ComputerRef`, `TryComputerRef`, and `HandlerRef`, and the one-step promotion providers are imported +from `cgp::extra::handler`. Because a context that delegates a member also implements its provider +trait, calling a method on a concrete context by its bare name, as `App::compute(&App, …)`, is +ambiguous (`E0034`) whenever that provider trait is in scope; method syntax, `App.compute(…)`, is +not. Every member registers under `@cgp.extra.handler` in `DefaultNamespace`, so a context that +joins that namespace binds a member at a path such as `@cgp.extra.handler.ComputerComponent`, since +a bare-key entry would conflict with the namespace's own (`E0119`). You rarely implement a member of this family by hand. Providers come from -[`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md), -which turn a plain function into a provider and wire the promotion table so one function answers the -whole family, and they are composed and routed with the -[handler combinators](../../providers/handler/index.md), the -[dispatch combinators](../../providers/dispatch/index.md), and the -[monad providers](../../providers/monad/index.md). A fallible member [supertraits](/docs/reference/glossary#supertrait) -[`HasErrorType`](../has_error_type.md), and an effectful one reaches the runtime through -[`HasRuntime`](../has_runtime.md). +[`#[cgp_computer]`](../../macros/cgp_computer.md) and +[`#[cgp_producer]`](../../macros/cgp_producer.md), which turn a plain function into a provider and +wire it to a promotion bundle, so one function answers the rest of the family, and they are composed +and routed with the [handler combinators](../../providers/handler/index.md), the [dispatch +combinators](../../providers/dispatch/index.md), and the [monad +providers](../../providers/monad/index.md). A fallible member has +[`HasErrorType`](../has_error_type.md) as a [supertrait](/docs/reference/glossary#supertrait), and +an effectful one reaches the runtime through [`HasRuntime`](../has_runtime.md). --- diff --git a/docs/reference/components/handler/producer.md b/docs/reference/components/handler/producer.md index 03939e8c..14225d0f 100644 --- a/docs/reference/components/handler/producer.md +++ b/docs/reference/components/handler/producer.md @@ -1,4 +1,6 @@ --- +title: 'Producer — a value from no input' +description: 'The input-free handler-family component: a synchronous, infallible provider that produces an Output from the context and a Code tag alone.' sidebar_label: 'Producer' sidebar_position: 4 --- @@ -9,18 +11,17 @@ The input-free member of the handler family: a synchronous, infallible source of ## Overview -`Producer` is for computations that take nothing to compute and simply yield a value. A handler that -supplies a default configuration, a constant, or a value read entirely from the **context** has no -`Input` to transform: it needs only the context and a phantom `Code` tag to know which value to produce. -The context is the type a method runs on, which supplies the values an implementation needs as -its own fields. The rest of the [handler family](/docs/concepts/handlers) threads an `Input` through -every method; `Producer` is the case where that input is absent. It is the simplest component in the -family, synchronous and infallible, producing an `Output` directly. +`Producer` is for computations that take no input and yield a value. A default configuration, a +constant, or a value read entirely from the [**context**](/docs/reference/glossary#context) (the +type the implementation runs against) has no `Input` to transform: it needs only the context and a +phantom `Code` tag naming which value to produce. The rest of the [handler +family](/docs/concepts/handlers) threads an `Input` through every method, and `Producer` is the case +where that input is absent. It is synchronous and infallible, and returns its `Output` directly. -Being input-free does not isolate a producer from the family. It makes it the natural *source* of values -that flow into the other handlers: a producer promotes into any computer or handler by ignoring whatever -input that variant supplies and returning the produced value regardless. This is how a constant or a -context-derived value enters a computation pipeline. +A producer still feeds the rest of the family. Promotion turns it into a +[`Computer`](./computer.md) that ignores whatever input it is given, and from there into the other +members, which is how a constant or a context-derived value enters a pipeline of input-taking +handlers. ## Definition @@ -40,24 +41,47 @@ pub trait CanProduce { Its attributes: - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `Producer` that implementations target and the wiring key `ProducerComponent`, while `CanProduce` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Code` type, so a context can route each `Code` to its own provider; the `open` statement is the modern sugar for the same dispatch. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.ProducerComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` provider, which dispatches on the `Code` type through an inner table; the `open` statement replaces it. There is no `UseInputDelegate`, since there is no input. ## Usage -`Producer` and its consumer trait `CanProduce` are imported from `cgp::extra::handler`. The consumer -method takes only the context and a `Code` tag, with no `Input`: +`Producer` and `ProducerComponent` are in the prelude. The consumer trait `CanProduce` is not, and +is imported from `cgp::extra::handler`. The consumer method takes only the context and a `Code` tag, +with no `Input`: ```rust fn produce(&self, _code: PhantomData) -> Self::Output; ``` -A context gains the operation by wiring `ProducerComponent` to a provider. In everyday use the provider -comes from [`#[cgp_producer]`](../../macros/cgp_producer.md), which turns a zero-argument function such as -`fn magic_number() -> u64 { 42 }` into a `Producer` provider and wires `PromoteProducer` so the -same function also answers the input-taking components. Because there is no input to dispatch on, the -component dispatches on the `Code` tag alone, with no `Input`-keyed table. `Producer` has no -by-reference or async sibling, since there is no input to borrow. +A context gains the operation by wiring `ProducerComponent` to a provider. The component dispatches +on the `Code` tag alone, and it has no by-reference or async sibling, since there is no input to +borrow. + +In everyday use the provider comes from [`#[cgp_producer]`](../../macros/cgp_producer.md), which +turns a zero-argument function into a `Producer` provider and wires that provider to the +[`PromoteProducer`](../../providers/handler/promote_producer.md) bundle. So a context can wire +any member of the family to it directly, and each member returns the produced value whatever input +it is given: + +```rust +#[cgp_producer] +fn default_port() -> u16 { + 8080 +} + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + [ComputerComponent, HandlerComponent]: DefaultPort, + } +} +``` + +The fallible members need the context's error type to form their `Result`, which is why `App` wires +`ErrorTypeProviderComponent`, but they always return `Ok`. A `#[cgp_producer]` function cannot reach +its context, since it has no parameters, so a producer that reads a field or calls another trait of +the context is a provider written with [`#[cgp_impl]`](../../macros/cgp_impl.md). ## Examples @@ -66,7 +90,7 @@ A producer wired into a context and invoked directly: ```rust use core::marker::PhantomData; use cgp::prelude::*; -use cgp::extra::handler::{CanProduce, Producer, ProducerComponent}; +use cgp::extra::handler::CanProduce; #[cgp_new_provider] impl Producer for MagicNumber { @@ -85,37 +109,63 @@ delegate_components! { } } -fn run(app: &App) -> u64 { - app.produce(PhantomData::<()>) // returns 42 +check_components! { + App { + ProducerComponent: (), + } +} + +pub fn demo() { + assert_eq!(App.produce(PhantomData::<()>), 42); } ``` -`MagicNumber` produces `42` from the `Code` tag alone, and `App` delegates `ProducerComponent` to it, -giving `App` the `CanProduce<(), Output = u64>` implementation. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the -context decides which provider answers, and no value is operated on. In practice the provider is written -with [`#[cgp_producer]`](../../macros/cgp_producer.md), which also wires the promotion so the same function -answers the input-taking components while ignoring their input. +`MagicNumber` produces `42` for any context and any `Code`, and `App` delegates `ProducerComponent` +to it. `App` is an [environmental context](/docs/reference/glossary#environmental-context), and the +component is **[self-targeted](/docs/reference/glossary#self-targeted-component)**: there is no +input to act on, so the operation describes the context itself, and `Code` is a +[selector](/docs/reference/glossary#selector) naming which value is wanted. ## When to use it -**Reach for `Producer` for a value that a computation needs but does not compute from an input**, such -as a constant, a default, or a value read from the context. It is the family's source, and promotion -lets one producer feed the input-taking members: delegating a context's handler surface to -`PromoteProducer` makes one producer answer `CanCompute`, `CanTryCompute`, `CanComputeAsync`, -`CanHandle`, and their by-reference forms. +**Reach for `Producer` for a value that a computation needs but does not compute from an input**, +such as a constant, a default, or a value read from the context. It is the family's source, and +promotion lets one producer feed the input-taking members, so a producer can seed a pipeline such as +`PipeHandlers`. Reach for [`Computer`](./computer.md) instead when the value is computed *from* an input, and for -[`TryComputer`](./try_computer.md) or [`Handler`](./handler.md) when producing it can fail or must await. +[`TryComputer`](./try_computer.md) or [`Handler`](./handler.md) when producing it can fail or must +await. A `#[cgp_producer]` function returning a `Result` is not a fallible producer: the fallible +members wrap the whole `Result` in `Ok`, so an `Err` short-circuits nothing downstream. + +## Common Mistakes + +**`PromoteProducer

` answers the fallible and async members only when `P` is wired to it.** Its +`ComputerComponent` entry works for any producer, but its other entries reach `P` through `P`'s own +`Computer` wiring. So a context that wires `TryComputerComponent` to `PromoteProducer`, +for the hand-written `MagicNumber` above, fails at the check: + +```text +error[E0277]: the trait bound `MagicNumber: DelegateComponent` is not satisfied +... + = note: required for `MagicNumber` to implement `Computer` + = note: required for `Promote` to implement `IsProviderFor` +``` + +Write the producer with [`#[cgp_producer]`](../../macros/cgp_producer.md), which wires it to +`PromoteProducer`, or wire the hand-written producer to that bundle yourself, as the macro +does. ## Related constructs - [`Computer`](./computer.md) — the synchronous input-taking member; a producer promotes into it. - [`TryComputer`](./try_computer.md) — the fallible member of the family. -- [`Handler`](./handler.md) — the general async-and-fallible member. +- [`Handler`](./handler.md) — the general async and fallible member. - [`#[cgp_producer]`](../../macros/cgp_producer.md) — builds a `Producer` provider from a zero-argument function. -- [Handler combinators](../../providers/handler/index.md) — the `Promote` provider and the `PromoteProducer` - table that lift a producer into the rest of the family. +- [`PromoteProducer`](../../providers/handler/promote_producer.md) — the bundle that lifts a + producer into the rest of the family. +- [`Promote`](../../providers/handler/promote.md) — the one-step lift from a producer to a computer. The ideas behind it: @@ -126,8 +176,10 @@ The ideas behind it: - `Producer`: [`produce.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/produce.rs) -- The `Promote` combinator and the `PromoteProducer` table: - [`cgp-handler/src/providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/) +- `Promote`: + [`promote.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote.rs) +- The `PromoteProducer` bundle: + [`promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/components/handler/try_computer.md b/docs/reference/components/handler/try_computer.md index 43b0ddbf..230cd3c5 100644 --- a/docs/reference/components/handler/try_computer.md +++ b/docs/reference/components/handler/try_computer.md @@ -1,4 +1,6 @@ --- +title: 'TryComputer — a fallible computation' +description: 'The handler-family component for a synchronous computation that can fail, returning a Result in the context''s abstract error type.' sidebar_label: 'TryComputer' sidebar_position: 2 --- @@ -9,20 +11,20 @@ The fallible synchronous member of the handler family: a computer that can retur ## Overview -`TryComputer` is for synchronous computations that can fail. 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`](./computer.md) returns its `Output` directly, `TryComputer` returns -`Result`, where the error is the **context's** shared abstract error type. The context is -the type a method runs on, which supplies the values an implementation needs as its own fields. -This places `TryComputer` one step up from `Computer` on the fallibility axis of the -[handler family](/docs/concepts/handlers), still synchronous but now able to fail, and one step below -[`Handler`](./handler.md), which adds asynchrony on top. - -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 -`Self::Error`, and the concrete type is decided at wiring time. This is why the component [supertraits](/docs/reference/glossary#supertrait) -[`HasErrorType`](../has_error_type.md): the supertrait supplies the `Self::Error` it names in its -`Result`, and it ties every fallible component in a context to the same error so their results compose. +`TryComputer` is for synchronous computations that can fail. 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`](./computer.md) returns its `Output` directly, `TryComputer` +returns `Result`, where `Error` is the abstract error type of the +[**context**](/docs/reference/glossary#context), the type the implementation runs against. It sits +one step from `Computer` on the fallibility axis of the [handler family](/docs/concepts/handlers), +and one step from [`Handler`](./handler.md), 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`](../has_error_type.md) as a [supertrait](/docs/reference/glossary#supertrait): the +supertrait supplies that `Error`, and every fallible component in a context names the same one, so +their results compose with `?`. ## Definition @@ -37,51 +39,66 @@ provider generic. A provider does not commit to `anyhow::Error` or `std::io::Err pub trait CanTryCompute { type Output; - fn try_compute( - &self, - _code: PhantomData, - input: Input, - ) -> Result; + fn try_compute(&self, _code: PhantomData, input: Input) -> Result; } ``` Its attributes: - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `TryComputer` that implementations target and the wiring key `TryComputerComponent`, while `CanTryCompute` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. -- [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.TryComputerComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` and `UseInputDelegate` providers, which dispatch on the `Code` tag and on the `Input` type through an inner table; the `open` statement replaces both, dispatching on either parameter or on the pair. +- [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. The trait's own `Output` stays written as `Self::Output`. ## Usage -`TryComputer` and its consumer trait `CanTryCompute` are imported from `cgp::extra::handler`. The -consumer method mirrors `compute` but returns a `Result`: +`TryComputer` and `TryComputerComponent` are in the prelude. The consumer trait `CanTryCompute` is +not, and is imported from `cgp::extra::handler`. The consumer method mirrors `compute` but returns a +`Result`: ```rust fn try_compute(&self, _code: PhantomData, input: Input) -> Result; ``` -A context gains the operation by wiring `TryComputerComponent` to a provider. In everyday use the -provider comes from [`#[cgp_computer]`](../../macros/cgp_computer.md), which turns a function returning -`Result` into a `TryComputer` provider and wires the promotion table so the same function -also answers `CanCompute`, `CanHandle`, and the by-reference forms. +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 with [`CanRaiseError`](../can_raise_error.md), as the example below does. +- **The promotion providers**, imported from `cgp::extra::handler`, answer it from a neighbouring + member. [`Promote

`](../../providers/handler/promote.md) wraps the output of a + [`Computer`](./computer.md) in `Ok`, and [`TryPromote

`](../../providers/handler/try_promote.md) + reads a `Computer` whose `Output` is `Result` as success or failure. `TryPromote` also + works the other way, presenting a `TryComputer` as a `Computer` whose `Output` is that `Result`. +- **[`#[cgp_computer]`](../../macros/cgp_computer.md)** on a function returning `Result` + generates a `Computer` whose `Output` is the `Result`, and wires it to the + [`PromoteTryComputer`](../../providers/handler/promote_try_computer.md) bundle, whose + `TryComputerComponent` entry is `TryPromote`. So `compute` returns the whole `Result`, while + `try_compute` propagates its `Err`. The function's `E` must be the context's error type, because + the bundle passes the `Err` through unconverted. The component dispatches on both the `Code` tag and the `Input` type. Its by-reference sibling -[`TryComputerRef`](./try_computer_ref.md), documented on its own page, differs by one axis: its -`try_compute_ref` method borrows the input as `&Input`. Both are synchronous; the async-and-fallible -counterpart is [`Handler`](./handler.md). +[`TryComputerRef`](./try_computer_ref.md), 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`](./handler.md), and [`PromoteAsync

`](../../providers/handler/promote_async.md) lifts a +`TryComputer` into one. ## Examples -A `TryComputer` provider that parses a string into a number, raising the context's error on failure: +A `TryComputer` provider that parses a string into a number, raising the parse error into the +context's error: ```rust use core::marker::PhantomData; +use core::num::ParseIntError; use cgp::prelude::*; -use cgp::extra::handler::{CanTryCompute, TryComputer, TryComputerComponent}; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; +use cgp::extra::handler::CanTryCompute; #[cgp_impl(new ParseU64)] -#[uses(CanRaiseError)] +#[uses(CanRaiseError)] #[use_type(HasErrorType.Error)] impl TryComputer { type Output = u64; @@ -91,47 +108,72 @@ impl TryComputer { _code: PhantomData, input: String, ) -> Result { - input.parse().map_err(|e| Self::raise_error(e)) + input.parse().map_err(Self::raise_error) + } +} + +#[derive(Debug, PartialEq)] +pub struct AppError(pub String); + +impl From for AppError { + fn from(e: ParseIntError) -> Self { + AppError(e.to_string()) } } +pub struct App; + delegate_components! { App { + ErrorTypeProviderComponent: UseType, + 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` returns its `u64` output or the context's abstract error, converting the concrete -`ParseIntError` into that error with [`CanRaiseError`](../can_raise_error.md). Because the consumer trait -supertraits `HasErrorType`, `App` must also wire an error type and an error raiser before it can call -`try_compute`. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, while the -context decides the provider and the error type. +`ParseU64` names neither the context nor its error type. `App` supplies both: its error type is +`AppError`, and [`RaiseFrom`](../../providers/error/raise_from.md) raises the `ParseIntError` +through `AppError`'s `From` impl. `App` is an [environmental +context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: 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, and it sits in the promotion lattice, so it both receives providers promoted from a -[`Computer`](./computer.md) and is itself promoted up to a [`Handler`](./handler.md). Prefer -`TryComputerRef` when the computation only reads its input. +**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`](./computer.md) and is itself +promoted into a [`Handler`](./handler.md). Prefer [`TryComputerRef`](./try_computer_ref.md) when the +computation only reads its input. -Reach for [`Computer`](./computer.md) instead when the computation cannot fail, since a pure computer -promotes into a `TryComputer` for free and stays usable in more positions, and for -[`Handler`](./handler.md) when the computation must also await. A provider author implements whichever -single variant fits and lets the wiring bridge the rest. +Reach for [`Computer`](./computer.md) 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`](./handler.md) 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`](./try_computer_ref.md) — the by-reference variant that borrows its input. - [`Computer`](./computer.md) — the infallible counterpart; promotes into a `TryComputer`. -- [`Handler`](./handler.md) — the async-and-fallible generalization. -- [`Producer`](./producer.md) — the input-free member of the family. -- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Self::Error` this returns. -- [`CanRaiseError`](../can_raise_error.md) — converts a concrete source error into that abstract error. -- [`#[cgp_computer]`](../../macros/cgp_computer.md) — builds a `TryComputer` provider from a fallible - function. -- [Handler combinators](../../providers/handler/index.md) — promote a `Computer` into this and this into a - `Handler`. +- [`Handler`](./handler.md) — the async and fallible member. +- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Error` this returns. +- [`CanRaiseError`](../can_raise_error.md) — converts a concrete source error into that abstract + error. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) — builds a provider from a fallible function. +- [Handler combinators](../../providers/handler/index.md) — `Promote`, `TryPromote`, `PromoteAsync`, + and the promotion bundles. The ideas behind it: @@ -144,8 +186,8 @@ The ideas behind it: - `TryComputer` and `TryComputerRef`: [`try_compute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/try_compute.rs) -- The `ReturnInput` provider and the promotion combinators: - [`cgp-handler/src/providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/) +- `Promote`, `TryPromote`, and the promotion bundles: + [`cgp-handler/src/providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/providers) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/components/handler/try_computer_ref.md b/docs/reference/components/handler/try_computer_ref.md index d60c3455..0d27d744 100644 --- a/docs/reference/components/handler/try_computer_ref.md +++ b/docs/reference/components/handler/try_computer_ref.md @@ -1,25 +1,27 @@ --- +title: 'TryComputerRef — fallible, borrowed input' +description: 'The handler-family component for a synchronous computation that can fail and only reads its input, returning a Result in the context''s error type.' sidebar_label: 'TryComputerRef' sidebar_position: 7 --- # `TryComputerRef` -The by-reference member of the handler family's fallible corner: a [`TryComputer`](./try_computer.md) -that borrows its input. +The by-reference member of the handler family's fallible corner: a +[`TryComputer`](./try_computer.md) that borrows its input. ## Overview -`TryComputerRef` is a [`TryComputer`](./try_computer.md) that takes its input by reference. A synchronous -computation that can fail and only *reads* its argument fits it: its method receives `&Input` and returns -`Result`, where the error is the **context's** abstract error type. The context is the -type a method runs on, which supplies the values an implementation needs as its own fields. -`TryComputerRef` is the owned-versus-borrowed variant of the fallible synchronous computer, differing on -the input axis alone. +`TryComputerRef` is a [`TryComputer`](./try_computer.md) that takes its input by reference. A +synchronous computation that can fail and only *reads* its argument fits it: its method receives +`&Input` and returns `Result`, where `Error` is the abstract error type of the +[**context**](/docs/reference/glossary#context), the type the implementation runs against. It +differs from `TryComputer` on the input axis alone. -Because it can fail, it [supertraits](/docs/reference/glossary#supertrait) [`HasErrorType`](../has_error_type.md), which supplies the -`Self::Error` it names in its `Result` and ties it to the same error every other fallible component in -the context uses. See the [handler family overview](./index.md) for how the members relate and promote. +Because it can fail, it has [`HasErrorType`](../has_error_type.md) as a +[supertrait](/docs/reference/glossary#supertrait), which supplies the `Error` it names in its +`Result` and ties it to the same error every other fallible component in the context uses. See the +[handler family overview](./index.md) for how the members relate and promote. ## Definition @@ -45,65 +47,112 @@ pub trait CanTryComputeRef { Its attributes: - [`#[cgp_component]`](../../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `TryComputerRef` that implementations target and the wiring key `TryComputerRefComponent`, while `CanTryComputeRef` stays the consumer trait callers use. -- [`#[prefix]`](../../macros/cgp_namespace.md) — registers the generated names into the `@cgp.extra.handler` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. -- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the dispatching providers a context routes through: `UseDelegate` dispatches on the `Code` tag, and `UseInputDelegate` on the `Input` type; the `open` statement is the modern sugar for the `Code` dispatch. +- [`#[prefix]`](../../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.extra.handler`, so a context that joins that namespace binds its provider at `@cgp.extra.handler.TryComputerRefComponent` rather than at the bare key. +- [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates the legacy `UseDelegate` and `UseInputDelegate` providers, which dispatch on the `Code` tag and on the `Input` type through an inner table; the `open` statement replaces both, dispatching on either parameter or on the pair. - [`#[use_type]`](../../attributes/use_type.md) — adds `HasErrorType` as a supertrait and rewrites the bare `Error` to `::Error`. ## Usage -`TryComputerRef` and its consumer trait `CanTryComputeRef` are imported from `cgp::extra::handler`. The -method borrows the input and returns a `Result`: +`TryComputerRefComponent` is in the prelude. The provider trait `TryComputerRef` and the consumer +trait `CanTryComputeRef` are not, and are imported from `cgp::extra::handler`. The method borrows +the input and returns a `Result`: ```rust fn try_compute_ref(&self, _code: PhantomData, input: &Input) -> Result; ``` -A context gains the operation by wiring `TryComputerRefComponent` to a provider, and it dispatches on -both the `Code` tag and the `Input` type. Because the consumer trait supertraits `HasErrorType`, the -context must also wire an error type before it can call `try_compute_ref`. A provider that reads rather -than consumes its input reaches for this variant; the owned-input [`TryComputer`](./try_computer.md) is -the more common one. +A context gains the operation by wiring `TryComputerRefComponent` to a provider and by wiring an +error type, and the component dispatches on both the `Code` tag and the `Input` type. Besides a +hand-written provider, the [`PromoteRef`](../../providers/handler/promote_ref.md) combinator answers +it from a [`TryComputer`](./try_computer.md) written for `&'a Input` at every lifetime, and in the +other direction lets a `TryComputerRef` provider answer `try_compute` for an owned input that +dereferences to its `Input`. See [`ComputerRef`](./computer_ref.md#usage) for the two directions, +which work the same way here. ## Examples -A generic consumer runs a fallible computation over a borrowed input: +A provider that parses a port number from a borrowed setting, raising the parse error into the +context's error: ```rust use core::marker::PhantomData; +use core::num::ParseIntError; use cgp::prelude::*; -use cgp::extra::handler::CanTryComputeRef; - -fn check( - context: &Context, - input: &String, -) -> Result -where - Context: CanTryComputeRef, -{ - context.try_compute_ref(PhantomData::, input) +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; +use cgp::extra::handler::{CanTryComputeRef, TryComputerRef}; + +#[cgp_impl(new ParsePort)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl TryComputerRef { + type Output = u16; + + fn try_compute_ref( + &self, + _code: PhantomData, + input: &String, + ) -> Result { + input.trim().parse().map_err(Self::raise_error) + } +} + +#[derive(Debug, PartialEq)] +pub struct AppError(pub String); + +impl From for AppError { + fn from(e: ParseIntError) -> Self { + AppError(e.to_string()) + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + TryComputerRefComponent: ParsePort, + } +} + +check_components! { + App { + TryComputerRefComponent: ((), String), + } +} + +pub fn demo() { + let setting = " 8080 ".to_owned(); + + assert_eq!(App.try_compute_ref(PhantomData::<()>, &setting), Ok(8080)); + assert!(App.try_compute_ref(PhantomData::<()>, &"http".to_owned()).is_err()); } ``` -`check` passes the input by reference, so the caller keeps the `String`, and returns the context's -abstract error on failure. The example is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation acts on the `Input`, -while the context decides the provider and the error type. +`try_compute_ref` reads `setting` without taking it, so the caller still owns it afterwards. `App` +is an [environmental context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: the computation +acts on the `Input`, while `App` decides the provider and the error type. ## When to use it -**Reach for `TryComputerRef` when a fallible synchronous computation only needs to read its input.** It -keeps ownership with the caller while still reporting failure through the context's error type. +**Reach for `TryComputerRef` when a fallible synchronous computation only needs to read its input.** +It keeps ownership with the caller while still reporting failure through the context's error type. -Reach for [`TryComputer`](./try_computer.md) instead when the computation takes the input by value, for -[`ComputerRef`](./computer_ref.md) when a borrowed-input computation cannot fail, and for -[`Handler`](./handler.md) or [`HandlerRef`](./handler_ref.md) when it must also await. +Reach for [`TryComputer`](./try_computer.md) instead when the computation takes the input by value, +for [`ComputerRef`](./computer_ref.md) when a borrowed-input computation cannot fail, and for +[`HandlerRef`](./handler_ref.md) when it must also await. ## Related constructs - [`TryComputer`](./try_computer.md) — the owned-input counterpart. - [`ComputerRef`](./computer_ref.md) — the infallible by-reference computer. -- [`HandlerRef`](./handler_ref.md) — the async-and-fallible by-reference member. -- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Self::Error` this returns. -- [`CanRaiseError`](../can_raise_error.md) — converts a concrete source error into that abstract error. +- [`HandlerRef`](./handler_ref.md) — the async and fallible by-reference member. +- [`HasErrorType`](../has_error_type.md) — the supertrait supplying the `Error` this returns. +- [`CanRaiseError`](../can_raise_error.md) — converts a concrete source error into that abstract + error. +- [`PromoteRef`](../../providers/handler/promote_ref.md) — bridges the owned and borrowed forms. The ideas behind it: @@ -116,6 +165,8 @@ The ideas behind it: - `TryComputer` and `TryComputerRef`: [`try_compute.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/try_compute.rs) +- `PromoteRef`: + [`promote_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_ref.rs) - Re-exported through `cgp::extra::handler`. --- diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 016cbb47..5e0e61a9 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -238,8 +238,8 @@ subtle. ## Under the hood `#[cgp_provider]` emits two items: your impl, passed through unchanged, and a marker impl derived from -it. From this input, where `ComputerRef` and `ComputerRefComponent` come from -`cgp::extra::handler`: +it. From this input, where `ComputerRef` is imported from `cgp::extra::handler` and +`ComputerRefComponent` comes from the prelude: ```rust #[cgp_provider] diff --git a/example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.rs b/example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.rs new file mode 100644 index 00000000..c758623b --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.rs @@ -0,0 +1,25 @@ +use core::marker::PhantomData; + +use cgp::extra::handler::CanCompute; +use cgp::prelude::*; + +#[cgp_new_provider] +impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: Double, + } +} + +fn main() { + let _ = App::compute(&App, PhantomData::<()>, 21); +} diff --git a/example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.stderr b/example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.stderr new file mode 100644 index 00000000..60abf45e --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.stderr @@ -0,0 +1,16 @@ +error[E0034]: multiple applicable items in scope + --> tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.rs:24:18 + | +24 | let _ = App::compute(&App, PhantomData::<()>, 21); + | ^^^^^^^ multiple `compute` found + | + = note: candidate #1 is defined in an impl of the trait `CanCompute` for the type `__Context__` + = note: candidate #2 is defined in an impl of the trait `cgp::prelude::Computer` for the type `__Provider__` +help: use fully-qualified syntax to disambiguate + | +24 - let _ = App::compute(&App, PhantomData::<()>, 21); +24 + let _ = ::compute(&App, PhantomData::<()>, 21); + | +24 - let _ = App::compute(&App, PhantomData::<()>, 21); +24 + let _ = CanCompute::compute(&App, PhantomData::<()>, 21); + | diff --git a/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs b/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs new file mode 100644 index 00000000..b6950639 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs @@ -0,0 +1,29 @@ +use core::marker::PhantomData; + +use cgp::extra::handler::PromoteRef; +use cgp::prelude::*; + +#[cgp_new_provider] +impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } +} + +pub struct App; + +delegate_components! { + App { + ComputerRefComponent: PromoteRef, + } +} + +check_components! { + App { + ComputerRefComponent: ((), u64), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.stderr b/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.stderr new file mode 100644 index 00000000..f69fc883 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.stderr @@ -0,0 +1,58 @@ +error[E0277]: the trait bound `Double: DelegateComponent` is not satisfied + --> tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs:25:9 + | +25 | ComputerRefComponent: ((), u64), + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `DelegateComponent` is not implemented for `Double` + --> tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs:7:54 + | + 7 | impl Computer for Double { + | ^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + BuildAndMergeOutputs + MatchWithFieldHandlersRef + MatchWithValueHandlersMut + MatchWithValueHandlersRef + PipeMonadic + PromoteProducer + = note: required for `Double` to implement `for<'a> cgp::prelude::Computer` + = note: required for `PromoteRef` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs:23:1 + | +23 | / check_components! { +24 | | App { +25 | | ComputerRefComponent: ((), u64), +26 | | } +27 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `for<'a> Double: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs:25:9 + | +25 | ComputerRefComponent: ((), u64), + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `Double` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs:7:1 + | + 7 | impl Computer for Double { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `u64`, found `&'a u64` + = note: required for `Double` to implement `for<'a> cgp::prelude::Computer` + = note: required for `PromoteRef` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs:23:1 + | +23 | / check_components! { +24 | | App { +25 | | ComputerRefComponent: ((), u64), +26 | | } +27 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs b/example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs new file mode 100644 index 00000000..0b34d7f4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs @@ -0,0 +1,30 @@ +use core::marker::PhantomData; + +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::prelude::*; + +#[cgp_new_provider] +impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + HandlerComponent: PromoteComputer, + } +} + +check_components! { + App { + HandlerComponent: ((), u64), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.stderr b/example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.stderr new file mode 100644 index 00000000..79dc8e01 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.stderr @@ -0,0 +1,64 @@ +error[E0277]: the trait bound `Double: DelegateComponent` is not satisfied + --> tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs:26:9 + | +26 | HandlerComponent: ((), u64), + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `DelegateComponent` is not implemented for `Double` + --> tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs:7:54 + | + 7 | impl Computer for Double { + | ^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + BuildAndMergeOutputs + MatchWithFieldHandlersRef + MatchWithValueHandlersMut + MatchWithValueHandlersRef + PipeMonadic + PromoteProducer + PromoteTryComputer + cgp::prelude::PromoteComputer + = note: required for `Double` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::PromoteComputer` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs:24:1 + | +24 | / check_components! { +25 | | App { +26 | | HandlerComponent: ((), u64), +27 | | } +28 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Double: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs:26:9 + | +26 | HandlerComponent: ((), u64), + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `Double` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs:7:1 + | + 7 | impl Computer for Double { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `cgp::prelude::ComputerComponent`, found `TryComputerComponent` + = note: required for `Double` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::PromoteComputer` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs:24:1 + | +24 | / check_components! { +25 | | App { +26 | | HandlerComponent: ((), u64), +27 | | } +28 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs b/example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs new file mode 100644 index 00000000..8bc9e48c --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs @@ -0,0 +1,30 @@ +use core::marker::PhantomData; + +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::prelude::*; + +#[cgp_new_provider] +impl Producer for MagicNumber { + type Output = u64; + + fn produce(_context: &Context, _code: PhantomData) -> u64 { + 42 + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + [ComputerComponent, TryComputerComponent]: PromoteProducer, + } +} + +check_components! { + App { + [ComputerComponent, TryComputerComponent]: ((), ()), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.stderr b/example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.stderr new file mode 100644 index 00000000..f08c09fb --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.stderr @@ -0,0 +1,63 @@ +error[E0277]: the trait bound `MagicNumber: DelegateComponent` is not satisfied + --> tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs:26:29 + | +26 | [ComputerComponent, TryComputerComponent]: ((), ()), + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `DelegateComponent` is not implemented for `MagicNumber` + --> tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs:7:49 + | + 7 | impl Producer for MagicNumber { + | ^^^^^^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + App + BuildAndMergeOutputs + MatchWithFieldHandlersRef + MatchWithValueHandlersMut + MatchWithValueHandlersRef + PipeMonadic + cgp::prelude::PromoteProducer + = note: required for `MagicNumber` to implement `Computer` + = note: required for `Promote` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::PromoteProducer` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs:24:1 + | +24 | / check_components! { +25 | | App { +26 | | [ComputerComponent, TryComputerComponent]: ((), ()), +27 | | } +28 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `MagicNumber: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs:26:29 + | +26 | [ComputerComponent, TryComputerComponent]: ((), ()), + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `MagicNumber` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs:7:1 + | + 7 | impl Producer for MagicNumber { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `cgp::prelude::ProducerComponent`, found `cgp::prelude::ComputerComponent` + = note: required for `MagicNumber` to implement `Computer` + = note: required for `Promote` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::PromoteProducer` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs:24:1 + | +24 | / check_components! { +25 | | App { +26 | | [ComputerComponent, TryComputerComponent]: ((), ()), +27 | | } +28 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/components/handler/async_computer.rs b/example-code/tests/reference/components/handler/async_computer.rs index d5b925d5..5e4588d0 100644 --- a/example-code/tests/reference/components/handler/async_computer.rs +++ b/example-code/tests/reference/components/handler/async_computer.rs @@ -1,18 +1,83 @@ //! Code from `docs/reference/components/handler/async_computer.md` — `AsyncComputer`. //! -//! Pins the generic consumer from the page's Examples, which awaits an async computation wired on its -//! context. It is generic over the context, so it compiles on its own. +//! Pins the `DoubleAsync` provider from the page's Examples, wired onto a context and awaited through +//! `CanComputeAsync`, and the promoted synchronous computer the page's Usage section describes. + +/// ## Usage +/// +/// A synchronous `Computer` answers the async slot through `PromoteAsync`. +pub mod usage { + use core::marker::PhantomData; + + use cgp::extra::handler::{CanComputeAsync, PromoteAsync}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + AsyncComputerComponent: PromoteAsync, + } + } + + check_components! { + App { + AsyncComputerComponent: ((), u64), + } + } + + #[test] + fn the_promoted_computer_answers_compute_async() { + let output = futures::executor::block_on(App.compute_async(PhantomData::<()>, 21)); + assert_eq!(output, 42); + } +} /// ## Examples pub mod examples { use core::marker::PhantomData; use cgp::extra::handler::CanComputeAsync; + use cgp::prelude::*; + + #[cgp_new_provider] + impl AsyncComputer for DoubleAsync { + type Output = u64; + + async fn compute_async(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + AsyncComputerComponent: DoubleAsync, + } + } + + check_components! { + App { + AsyncComputerComponent: ((), u64), + } + } + + pub async fn run(app: &App) -> u64 { + app.compute_async(PhantomData::<()>, 21).await + } - pub async fn run(context: &Context, input: u64) -> Context::Output - where - Context: CanComputeAsync, - { - context.compute_async(PhantomData::, input).await + #[test] + fn run_awaits_the_doubled_input() { + assert_eq!(futures::executor::block_on(run(&App)), 42); } } diff --git a/example-code/tests/reference/components/handler/async_computer_ref.rs b/example-code/tests/reference/components/handler/async_computer_ref.rs index a679c2a3..e1fad5f2 100644 --- a/example-code/tests/reference/components/handler/async_computer_ref.rs +++ b/example-code/tests/reference/components/handler/async_computer_ref.rs @@ -1,18 +1,51 @@ //! Code from `docs/reference/components/handler/async_computer_ref.md` — `AsyncComputerRef`. //! -//! Pins the generic consumer from the page's Examples, which awaits an infallible computation over a -//! borrowed input. It is generic over the context, so it compiles on its own. +//! Pins the `CountWords` provider from the page's Examples, wired onto a context and awaited through +//! `CanComputeAsyncRef` over a borrowed input. /// ## Examples pub mod examples { use core::marker::PhantomData; use cgp::extra::handler::CanComputeAsyncRef; + use cgp::prelude::*; - pub async fn scan(context: &Context, input: &String) -> Context::Output - where - Context: CanComputeAsyncRef, - { - context.compute_async_ref(PhantomData::, input).await + #[cgp_new_provider] + impl AsyncComputerRef for CountWords { + type Output = usize; + + async fn compute_async_ref( + _context: &Context, + _code: PhantomData, + input: &String, + ) -> usize { + input.split_whitespace().count() + } + } + + pub struct App; + + delegate_components! { + App { + AsyncComputerRefComponent: CountWords, + } + } + + check_components! { + App { + AsyncComputerRefComponent: ((), String), + } + } + + pub async fn run(app: &App, text: &String) -> usize { + app.compute_async_ref(PhantomData::<()>, text).await + } + + #[test] + fn run_counts_the_words_and_keeps_the_input() { + let text = "hello context generic world".to_owned(); + + assert_eq!(futures::executor::block_on(run(&App, &text)), 4); + assert_eq!(text.len(), 27); } } diff --git a/example-code/tests/reference/components/handler/computer.rs b/example-code/tests/reference/components/handler/computer.rs index a54ee055..7b3ce689 100644 --- a/example-code/tests/reference/components/handler/computer.rs +++ b/example-code/tests/reference/components/handler/computer.rs @@ -1,13 +1,17 @@ //! Code from `docs/reference/components/handler/computer.md` — `Computer`. //! -//! Pins the `Double` provider from the page's Examples, wired onto a context and invoked through -//! `CanCompute`. +//! Pins the `Double` provider from the page's Examples, wired onto a context directly and through the +//! `PromoteComputer` bundle, and the wiring the page's Usage section shows for a context that joins +//! `DefaultNamespace`. The ambiguous associated-function call from Common Mistakes is a trybuild +//! fixture. -/// ## Examples -pub mod examples { +/// ## Usage +/// +/// A context that joins `DefaultNamespace` binds the provider at the component's prefixed path. +pub mod usage { use core::marker::PhantomData; - use cgp::extra::handler::{CanCompute, Computer, ComputerComponent}; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; #[cgp_new_provider] @@ -19,12 +23,13 @@ pub mod examples { } } - #[derive(HasField)] pub struct App; delegate_components! { App { - ComputerComponent: Double, + namespace DefaultNamespace; + + @cgp.extra.handler.ComputerComponent: Double, } } @@ -39,7 +44,94 @@ pub mod examples { } #[test] - fn app_doubles_its_input() { - assert_eq!(App.compute(PhantomData::<()>, 21u64), 42); + fn the_prefixed_path_binds_the_provider() { + assert_eq!(App.compute(PhantomData::<()>, 21), 42); + } +} + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanCompute, CanTryCompute}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ComputerComponent: Double, + TryComputerComponent: PromoteComputer, + } + } + + check_components! { + App { + [ComputerComponent, TryComputerComponent]: ((), u64), + } + } + + pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 21), 42); + assert_eq!(App.try_compute(PhantomData::<()>, 21), Ok(42)); + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## Common Mistakes +/// +/// The fix the page gives for the ambiguous call: call through the consumer trait by name. The +/// rejected call is `tests/compile_fail/reference/components/computer_common_mistakes_ambiguous_concrete_call.rs`. +pub mod common_mistakes { + use core::marker::PhantomData; + + use cgp::extra::handler::CanCompute; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: Double, + } + } + + check_components! { + App { + ComputerComponent: ((), u64), + } + } + + #[test] + fn the_qualified_call_resolves() { + assert_eq!(App.compute(PhantomData::<()>, 21), 42); + assert_eq!( + >::compute(&App, PhantomData, 21), + 42 + ); } } diff --git a/example-code/tests/reference/components/handler/computer_ref.rs b/example-code/tests/reference/components/handler/computer_ref.rs index 5250208a..1ed925e4 100644 --- a/example-code/tests/reference/components/handler/computer_ref.rs +++ b/example-code/tests/reference/components/handler/computer_ref.rs @@ -1,18 +1,87 @@ //! Code from `docs/reference/components/handler/computer_ref.md` — `ComputerRef`. //! -//! Pins the generic consumer from the page's Examples, which computes from a borrowed input. It is -//! generic over the context, so it compiles on its own. +//! Pins the `StringLength` provider from the page's Examples, wired for the borrowed input and, through +//! `PromoteRef`, for an owned input that dereferences to it, and the reference-parameter function +//! Common Mistakes gives as the fix. The owned-input computer that cannot answer the borrowed slot is a +//! trybuild fixture. /// ## Examples pub mod examples { use core::marker::PhantomData; + use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef, PromoteRef}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl ComputerRef for StringLength { + type Output = usize; + + fn compute_ref(_context: &Context, _code: PhantomData, input: &String) -> usize { + input.len() + } + } + + pub struct App; + + delegate_components! { + App { + ComputerRefComponent: StringLength, + ComputerComponent: PromoteRef, + } + } + + check_components! { + App { + ComputerRefComponent: ((), String), + ComputerComponent: ((), Box), + } + } + + pub fn demo() { + let name = "hello".to_owned(); + + assert_eq!(App.compute_ref(PhantomData::<()>, &name), 5); + assert_eq!(App.compute(PhantomData::<()>, Box::new(name)), 5); + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## Common Mistakes +/// +/// The fix the page gives: a `#[cgp_computer]` function over a reference answers `compute_ref`. The +/// owned-input computer behind `PromoteRef` is +/// `tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs`. +pub mod common_mistakes { + use core::marker::PhantomData; + use cgp::extra::handler::CanComputeRef; + use cgp::prelude::*; + + #[cgp_computer] + fn double(value: &u64) -> u64 { + value * 2 + } + + pub struct App; + + delegate_components! { + App { + ComputerRefComponent: Double, + } + } + + check_components! { + App { + ComputerRefComponent: ((), u64), + } + } - pub fn measure(context: &Context, input: &String) -> Context::Output - where - Context: CanComputeRef, - { - context.compute_ref(PhantomData::, input) + #[test] + fn a_reference_parameter_answers_compute_ref() { + assert_eq!(App.compute_ref(PhantomData::<()>, &21), 42); } } diff --git a/example-code/tests/reference/components/handler/handler.rs b/example-code/tests/reference/components/handler/handler.rs index 58d4f93a..c0244f2e 100644 --- a/example-code/tests/reference/components/handler/handler.rs +++ b/example-code/tests/reference/components/handler/handler.rs @@ -1,21 +1,57 @@ //! Code from `docs/reference/components/handler/handler.md` — `Handler`. //! -//! Pins the generic consumer from the page's Examples, which bounds its context by `CanHandle` and so -//! accepts any wired computation. It is generic over the context, so it compiles on its own. +//! Pins the page's Examples: a generic consumer bounded by `CanHandle`, and a context whose +//! `HandlerComponent` is a synchronous `Computer` lifted in two promotion steps. The one-step bundle +//! wiring from Common Mistakes is a trybuild fixture. /// ## Examples pub mod examples { use core::marker::PhantomData; - use cgp::extra::handler::CanHandle; + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanHandle, Promote, PromoteAsync}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + HandlerComponent: PromoteAsync>, + } + } + + check_components! { + App { + HandlerComponent: ((), u64), + } + } pub async fn run_with( context: &Context, - input: String, + input: u64, ) -> Result where - Context: CanHandle, + Context: CanHandle, { context.handle(PhantomData::, input).await } + + pub async fn demo() -> Result { + run_with::(&App, 21).await + } + + #[test] + fn test_demo() { + assert_eq!(futures::executor::block_on(demo()), Ok(42)); + } } diff --git a/example-code/tests/reference/components/handler/handler_ref.rs b/example-code/tests/reference/components/handler/handler_ref.rs index e5c2ecb7..a344ba79 100644 --- a/example-code/tests/reference/components/handler/handler_ref.rs +++ b/example-code/tests/reference/components/handler/handler_ref.rs @@ -1,21 +1,64 @@ //! Code from `docs/reference/components/handler/handler_ref.md` — `HandlerRef`. //! -//! Pins the generic consumer from the page's Examples, which awaits a fallible computation over a -//! borrowed input. It is generic over the context, so it compiles on its own. +//! Pins the `NonEmptyLength` provider from the page's Examples, an async, fallible computation over a +//! borrowed input, wired onto a context that supplies its error type and raiser. /// ## Examples pub mod examples { use core::marker::PhantomData; - use cgp::extra::handler::CanHandleRef; + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{CanHandleRef, HandlerRef}; + use cgp::prelude::*; - pub async fn serve( - context: &Context, - request: &String, - ) -> Result - where - Context: CanHandleRef, - { - context.handle_ref(PhantomData::, request).await + #[cgp_impl(new NonEmptyLength)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl HandlerRef { + type Output = usize; + + async fn handle_ref( + &self, + _code: PhantomData, + input: &String, + ) -> Result { + if input.is_empty() { + return Err(Self::raise_error("empty request".to_owned())); + } + + Ok(input.len()) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + HandlerRefComponent: NonEmptyLength, + } + } + + check_components! { + App { + HandlerRefComponent: ((), String), + } + } + + pub async fn demo() { + let request = "GET /".to_owned(); + + assert_eq!(App.handle_ref(PhantomData::<()>, &request).await, Ok(5)); + assert_eq!( + App.handle_ref(PhantomData::<()>, &String::new()).await, + Err("empty request".to_owned()) + ); + } + + #[test] + fn test_demo() { + futures::executor::block_on(demo()); } } diff --git a/example-code/tests/reference/components/handler/producer.rs b/example-code/tests/reference/components/handler/producer.rs index df67680a..b227fc8c 100644 --- a/example-code/tests/reference/components/handler/producer.rs +++ b/example-code/tests/reference/components/handler/producer.rs @@ -1,13 +1,56 @@ //! Code from `docs/reference/components/handler/producer.md` — `Producer`. //! //! Pins the `MagicNumber` provider from the page's Examples, wired onto a context and invoked through -//! `CanProduce`. +//! `CanProduce`, and the `#[cgp_producer]` provider the page's Usage section wires into the +//! input-taking components. The hand-written producer behind a bundle, from Common Mistakes, is a +//! trybuild fixture. + +/// ## Usage +/// +/// A `#[cgp_producer]` provider is wired to its own promotion bundle, so a context can wire it to any +/// member of the family. +pub mod usage { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanCompute, CanHandle}; + use cgp::prelude::*; + + #[cgp_producer] + fn default_port() -> u16 { + 8080 + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + [ComputerComponent, HandlerComponent]: DefaultPort, + } + } + + check_components! { + App { + [ComputerComponent, HandlerComponent]: ((), ()), + } + } + + #[test] + fn the_producer_answers_the_input_taking_members() { + assert_eq!(App.compute(PhantomData::<()>, ()), 8080); + assert_eq!( + futures::executor::block_on(App.handle(PhantomData::<()>, ())), + Ok(8080) + ); + } +} /// ## Examples pub mod examples { use core::marker::PhantomData; - use cgp::extra::handler::{CanProduce, Producer, ProducerComponent}; + use cgp::extra::handler::CanProduce; use cgp::prelude::*; #[cgp_new_provider] @@ -27,18 +70,66 @@ pub mod examples { } } - mod check_app { - use super::*; + check_components! { + App { + ProducerComponent: (), + } + } + + pub fn demo() { + assert_eq!(App.produce(PhantomData::<()>), 42); + } - check_components! { - App { - ProducerComponent: (), - } + #[test] + fn test_demo() { + demo(); + } +} + +/// ## Common Mistakes +/// +/// The fix the page gives: a hand-written producer wired to `PromoteProducer`, as +/// `#[cgp_producer]` does, answers the fallible members. The unwired producer behind the bundle is +/// `tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs`. +pub mod common_mistakes { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::CanTryCompute; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Producer for MagicNumber { + type Output = u64; + + fn produce(_context: &Context, _code: PhantomData) -> u64 { + 42 + } + } + + delegate_components! { + MagicNumber { + [ComputerComponent, TryComputerComponent]: PromoteProducer, + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + TryComputerComponent: MagicNumber, + } + } + + check_components! { + App { + TryComputerComponent: ((), ()), } } #[test] - fn app_produces_the_magic_number() { - assert_eq!(App.produce(PhantomData::<()>), 42); + fn the_self_wired_producer_answers_try_compute() { + assert_eq!(App.try_compute(PhantomData::<()>, ()), Ok(42)); } } diff --git a/example-code/tests/reference/components/handler/try_computer.rs b/example-code/tests/reference/components/handler/try_computer.rs index 2d80959a..ca4a80ad 100644 --- a/example-code/tests/reference/components/handler/try_computer.rs +++ b/example-code/tests/reference/components/handler/try_computer.rs @@ -1,19 +1,63 @@ //! Code from `docs/reference/components/handler/try_computer.md` — `TryComputer`. //! -//! Pins the `ParseU64` provider from the page's Examples, wired onto a context that also supplies an -//! error type and an error raiser for `ParseIntError`, and invoked through `CanTryCompute`. +//! Pins the `ParseU64` provider from the page's Examples, wired onto a context that supplies its error +//! type and raiser, and the `#[cgp_computer]` function whose `Result` output the page's Usage section +//! describes. + +/// ## Usage +/// +/// A `Result`-returning function becomes a `Computer` whose output is the `Result`, and its +/// `PromoteTryComputer` bundle reads that `Result` as the failure path. +pub mod usage { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanCompute, CanTryCompute}; + use cgp::prelude::*; + + #[cgp_computer] + fn checked_double(input: u64) -> Result { + input.checked_mul(2).ok_or_else(|| "overflow".to_owned()) + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + [ComputerComponent, TryComputerComponent]: CheckedDouble, + } + } + + check_components! { + App { + [ComputerComponent, TryComputerComponent]: ((), u64), + } + } + + #[test] + fn the_result_is_the_computer_output_and_the_try_computer_failure() { + assert_eq!(App.compute(PhantomData::<()>, 21), Ok(42)); + assert_eq!(App.try_compute(PhantomData::<()>, 21), Ok(42)); + assert_eq!( + App.try_compute(PhantomData::<()>, u64::MAX), + Err("overflow".to_owned()) + ); + } +} /// ## Examples pub mod examples { use core::marker::PhantomData; + use core::num::ParseIntError; use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::{DebugError, RaiseFrom}; - use cgp::extra::handler::{CanTryCompute, TryComputer, TryComputerComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::CanTryCompute; use cgp::prelude::*; #[cgp_impl(new ParseU64)] - #[uses(CanRaiseError)] + #[uses(CanRaiseError)] #[use_type(HasErrorType.Error)] impl TryComputer { type Output = u64; @@ -23,42 +67,42 @@ pub mod examples { _code: PhantomData, input: String, ) -> Result { - input.parse().map_err(|e| Self::raise_error(e)) + input.parse().map_err(Self::raise_error) + } + } + + #[derive(Debug, PartialEq)] + pub struct AppError(pub String); + + impl From for AppError { + fn from(e: ParseIntError) -> Self { + AppError(e.to_string()) } } pub struct App; - // The page shows only `TryComputerComponent: ParseU64` and says the context also wires an error - // type and an error raiser. That backend is filled in here so the wiring resolves: `DebugError` - // formats the `ParseIntError` into a `String`, which `RaiseFrom` then raises into the `String` - // error type. delegate_components! { App { - open ErrorRaiserComponent; - - ErrorTypeProviderComponent: UseType, + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, TryComputerComponent: ParseU64, - @ErrorRaiserComponent.core::num::ParseIntError: DebugError, - @ErrorRaiserComponent.String: RaiseFrom, } } - mod check_app { - use super::*; - - check_components! { - App { - TryComputerComponent: ((), String), - } + 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()); + } + #[test] - fn app_parses_a_number() { - assert_eq!( - App.try_compute(PhantomData::<()>, "42".to_owned()).unwrap(), - 42, - ); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/components/handler/try_computer_ref.rs b/example-code/tests/reference/components/handler/try_computer_ref.rs index 704a887a..ee5f8bb6 100644 --- a/example-code/tests/reference/components/handler/try_computer_ref.rs +++ b/example-code/tests/reference/components/handler/try_computer_ref.rs @@ -1,21 +1,69 @@ //! Code from `docs/reference/components/handler/try_computer_ref.md` — `TryComputerRef`. //! -//! Pins the generic consumer from the page's Examples, which runs a fallible computation over a -//! borrowed input. It is generic over the context, so it compiles on its own. +//! Pins the `ParsePort` provider from the page's Examples, which parses a borrowed string, wired onto a +//! context that supplies its error type and raiser. /// ## Examples pub mod examples { use core::marker::PhantomData; + use core::num::ParseIntError; - use cgp::extra::handler::CanTryComputeRef; + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{CanTryComputeRef, TryComputerRef}; + use cgp::prelude::*; - pub fn check( - context: &Context, - input: &String, - ) -> Result - where - Context: CanTryComputeRef, - { - context.try_compute_ref(PhantomData::, input) + #[cgp_impl(new ParsePort)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl TryComputerRef { + type Output = u16; + + fn try_compute_ref( + &self, + _code: PhantomData, + input: &String, + ) -> Result { + input.trim().parse().map_err(Self::raise_error) + } + } + + #[derive(Debug, PartialEq)] + pub struct AppError(pub String); + + impl From for AppError { + fn from(e: ParseIntError) -> Self { + AppError(e.to_string()) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + TryComputerRefComponent: ParsePort, + } + } + + check_components! { + App { + TryComputerRefComponent: ((), String), + } + } + + pub fn demo() { + let setting = " 8080 ".to_owned(); + + assert_eq!(App.try_compute_ref(PhantomData::<()>, &setting), Ok(8080)); + assert!(App.try_compute_ref(PhantomData::<()>, &"http".to_owned()).is_err()); + // The caller still owns `setting`. + assert_eq!(setting.len(), 6); + } + + #[test] + fn test_demo() { + demo(); } } From 7841bafdca45777b5ca5accb94572d49670759dd Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 02:48:07 +0000 Subject: [PATCH 125/516] Pin the handler pages' remaining prose claims and qualify E0034 Mirror the Usage and When-to-use claims that had no compiled counterpart: UseField forwarding for Computer and AsyncComputer, #[cgp_computer] on an async fn, PromoteRef answering an owned input for AsyncComputerRef, TryPromote presenting a TryComputer as a Computer, and a producer seeding a PipeHandlers pipeline. Each sits in the module of the heading that states it. The E0034 bare-name ambiguity needs the consumer trait imported as well as the provider trait; without it the call compiles against the provider trait. Say so on the Computer page and the overview, and split the overview's import and wiring paragraph. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/components/handler/computer.md | 5 +- docs/reference/components/handler/index.md | 15 +++-- .../components/handler/async_computer.rs | 56 ++++++++++++++++++- .../components/handler/async_computer_ref.rs | 50 ++++++++++++++++- .../reference/components/handler/computer.rs | 54 +++++++++++++++++- .../reference/components/handler/producer.rs | 43 +++++++++++++- .../components/handler/try_computer.rs | 50 ++++++++++++++++- 7 files changed, 256 insertions(+), 17 deletions(-) diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md index a5796a05..8c97c68a 100644 --- a/docs/reference/components/handler/computer.md +++ b/docs/reference/components/handler/computer.md @@ -171,7 +171,8 @@ context. **Calling `compute` on a concrete context by its bare name is ambiguous.** A context that delegates `ComputerComponent` also implements the `Computer` provider trait, which the prelude brings into -scope, so `App::compute(&App, PhantomData::<()>, 21)` has two candidates: +scope, so once `CanCompute` is imported as well, `App::compute(&App, PhantomData::<()>, 21)` has two +candidates: ```text error[E0034]: multiple applicable items in scope @@ -187,7 +188,7 @@ error[E0034]: multiple applicable items in scope Use method syntax, as in `App.compute(PhantomData::<()>, 21)`, since only the consumer trait takes `self`, or name the consumer trait, as in `>::compute(&App, PhantomData, 21)`. The same holds for every member of -the family whose provider trait is in scope. +the family whose consumer and provider traits are both in scope. ## Related constructs diff --git a/docs/reference/components/handler/index.md b/docs/reference/components/handler/index.md index 0841dab5..56bdf4f6 100644 --- a/docs/reference/components/handler/index.md +++ b/docs/reference/components/handler/index.md @@ -45,12 +45,15 @@ Every member's wiring key is in the prelude, and so are the provider traits `Com `AsyncComputer`, `AsyncComputerRef`, `TryComputer`, `Handler`, and `Producer`. The consumer traits (`CanCompute`, `CanTryCompute`, `CanHandle`, `CanProduce`, and their siblings), the provider traits `ComputerRef`, `TryComputerRef`, and `HandlerRef`, and the one-step promotion providers are imported -from `cgp::extra::handler`. Because a context that delegates a member also implements its provider -trait, calling a method on a concrete context by its bare name, as `App::compute(&App, …)`, is -ambiguous (`E0034`) whenever that provider trait is in scope; method syntax, `App.compute(…)`, is -not. Every member registers under `@cgp.extra.handler` in `DefaultNamespace`, so a context that -joins that namespace binds a member at a path such as `@cgp.extra.handler.ComputerComponent`, since -a bare-key entry would conflict with the namespace's own (`E0119`). +from `cgp::extra::handler`. + +Two wiring details apply to every member. Because a context that delegates a member also implements +its provider trait, calling a method on a concrete context by its bare name, as +`App::compute(&App, …)`, is ambiguous (`E0034`) whenever the consumer trait and that provider trait +are both in scope; method syntax, `App.compute(…)`, is not. Every member registers under +`@cgp.extra.handler` in `DefaultNamespace`, so a context that joins that namespace binds a member at +a path such as `@cgp.extra.handler.ComputerComponent`, since a bare-key entry would conflict with +the namespace's own (`E0119`). You rarely implement a member of this family by hand. Providers come from [`#[cgp_computer]`](../../macros/cgp_computer.md) and diff --git a/example-code/tests/reference/components/handler/async_computer.rs b/example-code/tests/reference/components/handler/async_computer.rs index 5e4588d0..920c8832 100644 --- a/example-code/tests/reference/components/handler/async_computer.rs +++ b/example-code/tests/reference/components/handler/async_computer.rs @@ -1,7 +1,8 @@ //! Code from `docs/reference/components/handler/async_computer.md` — `AsyncComputer`. //! //! Pins the `DoubleAsync` provider from the page's Examples, wired onto a context and awaited through -//! `CanComputeAsync`, and the promoted synchronous computer the page's Usage section describes. +//! `CanComputeAsync`, and the providers the page's Usage section lists: a promoted synchronous +//! computer, a `#[cgp_computer]` async function, and `UseField`. /// ## Usage /// @@ -40,6 +41,59 @@ pub mod usage { let output = futures::executor::block_on(App.compute_async(PhantomData::<()>, 21)); assert_eq!(output, 42); } + + /// `#[cgp_computer]` on an `async fn` implements `AsyncComputer` directly, and `UseField` + /// forwards the async computation to a field whose value computes it. + pub mod sources { + use core::marker::PhantomData; + + use cgp::extra::handler::CanComputeAsync; + use cgp::prelude::*; + + #[cgp_computer] + async fn double_later(input: u64) -> u64 { + input * 2 + } + + pub struct Doubler; + + delegate_components! { + Doubler { + AsyncComputerComponent: DoubleLater, + } + } + + #[derive(HasField)] + pub struct App { + pub doubler: Doubler, + } + + delegate_components! { + App { + AsyncComputerComponent: UseField, + } + } + + check_components! { + App { + AsyncComputerComponent: ((), u64), + } + } + + #[test] + fn both_sources_answer_compute_async() { + let app = App { doubler: Doubler }; + + assert_eq!( + futures::executor::block_on(Doubler.compute_async(PhantomData::<()>, 21)), + 42 + ); + assert_eq!( + futures::executor::block_on(app.compute_async(PhantomData::<()>, 21)), + 42 + ); + } + } } /// ## Examples diff --git a/example-code/tests/reference/components/handler/async_computer_ref.rs b/example-code/tests/reference/components/handler/async_computer_ref.rs index e1fad5f2..12e141df 100644 --- a/example-code/tests/reference/components/handler/async_computer_ref.rs +++ b/example-code/tests/reference/components/handler/async_computer_ref.rs @@ -1,7 +1,55 @@ //! Code from `docs/reference/components/handler/async_computer_ref.md` — `AsyncComputerRef`. //! //! Pins the `CountWords` provider from the page's Examples, wired onto a context and awaited through -//! `CanComputeAsyncRef` over a borrowed input. +//! `CanComputeAsyncRef` over a borrowed input, and, from the Usage section, `PromoteRef` answering an +//! owned input that dereferences to it. + +/// ## Usage +/// +/// Through `PromoteRef`, an `AsyncComputerRef` provider answers `compute_async` for an owned input that +/// dereferences to its `Input`. +pub mod usage { + use core::marker::PhantomData; + + use cgp::extra::handler::{CanComputeAsync, PromoteRef}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl AsyncComputerRef for CountWords { + type Output = usize; + + async fn compute_async_ref( + _context: &Context, + _code: PhantomData, + input: &String, + ) -> usize { + input.split_whitespace().count() + } + } + + pub struct App; + + delegate_components! { + App { + AsyncComputerComponent: PromoteRef, + } + } + + check_components! { + App { + AsyncComputerComponent: ((), Box), + } + } + + #[test] + fn the_owned_input_is_dereferenced() { + let text = Box::new("two words".to_owned()); + assert_eq!( + futures::executor::block_on(App.compute_async(PhantomData::<()>, text)), + 2 + ); + } +} /// ## Examples pub mod examples { diff --git a/example-code/tests/reference/components/handler/computer.rs b/example-code/tests/reference/components/handler/computer.rs index 7b3ce689..453662fe 100644 --- a/example-code/tests/reference/components/handler/computer.rs +++ b/example-code/tests/reference/components/handler/computer.rs @@ -1,9 +1,9 @@ //! Code from `docs/reference/components/handler/computer.md` — `Computer`. //! //! Pins the `Double` provider from the page's Examples, wired onto a context directly and through the -//! `PromoteComputer` bundle, and the wiring the page's Usage section shows for a context that joins -//! `DefaultNamespace`. The ambiguous associated-function call from Common Mistakes is a trybuild -//! fixture. +//! `PromoteComputer` bundle, and the Usage section's claims: the wiring for a context that joins +//! `DefaultNamespace`, and `UseField` forwarding to a field that computes. The ambiguous +//! associated-function call from Common Mistakes is a trybuild fixture. /// ## Usage /// @@ -47,6 +47,54 @@ pub mod usage { fn the_prefixed_path_binds_the_provider() { assert_eq!(App.compute(PhantomData::<()>, 21), 42); } + + /// `UseField` forwards the computation to the context's `Tag` field, whose value computes it. + pub mod use_field { + use core::marker::PhantomData; + + use cgp::extra::handler::CanCompute; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + pub struct Doubler; + + delegate_components! { + Doubler { + ComputerComponent: Double, + } + } + + #[derive(HasField)] + pub struct App { + pub doubler: Doubler, + } + + delegate_components! { + App { + ComputerComponent: UseField, + } + } + + check_components! { + App { + ComputerComponent: ((), u64), + } + } + + #[test] + fn the_field_value_computes() { + let app = App { doubler: Doubler }; + assert_eq!(app.compute(PhantomData::<()>, 21), 42); + } + } } /// ## Examples diff --git a/example-code/tests/reference/components/handler/producer.rs b/example-code/tests/reference/components/handler/producer.rs index b227fc8c..cca05a78 100644 --- a/example-code/tests/reference/components/handler/producer.rs +++ b/example-code/tests/reference/components/handler/producer.rs @@ -1,8 +1,8 @@ //! Code from `docs/reference/components/handler/producer.md` — `Producer`. //! //! Pins the `MagicNumber` provider from the page's Examples, wired onto a context and invoked through -//! `CanProduce`, and the `#[cgp_producer]` provider the page's Usage section wires into the -//! input-taking components. The hand-written producer behind a bundle, from Common Mistakes, is a +//! `CanProduce`, the `#[cgp_producer]` provider the page's Usage section wires into the input-taking +//! components, and the pipeline it seeds from When to use it. The hand-written producer behind a bundle, from Common Mistakes, is a //! trybuild fixture. /// ## Usage @@ -86,6 +86,45 @@ pub mod examples { } } +/// ## When to use it +/// +/// A producer seeds a `PipeHandlers` pipeline, since its promoted computer ignores the input. +pub mod when_to_use_it { + use core::marker::PhantomData; + + use cgp::extra::handler::{CanCompute, PipeHandlers}; + use cgp::prelude::*; + + #[cgp_producer] + fn default_port() -> u16 { + 8080 + } + + #[cgp_computer] + fn next_port(port: u16) -> u16 { + port + 1 + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: PipeHandlers, + } + } + + check_components! { + App { + ComputerComponent: ((), ()), + } + } + + #[test] + fn the_producer_seeds_the_pipeline() { + assert_eq!(App.compute(PhantomData::<()>, ()), 8081); + } +} + /// ## Common Mistakes /// /// The fix the page gives: a hand-written producer wired to `PromoteProducer`, as diff --git a/example-code/tests/reference/components/handler/try_computer.rs b/example-code/tests/reference/components/handler/try_computer.rs index ca4a80ad..244bb500 100644 --- a/example-code/tests/reference/components/handler/try_computer.rs +++ b/example-code/tests/reference/components/handler/try_computer.rs @@ -1,8 +1,8 @@ //! Code from `docs/reference/components/handler/try_computer.md` — `TryComputer`. //! //! Pins the `ParseU64` provider from the page's Examples, wired onto a context that supplies its error -//! type and raiser, and the `#[cgp_computer]` function whose `Result` output the page's Usage section -//! describes. +//! type and raiser, and the Usage section's claims: the `#[cgp_computer]` function whose `Result` +//! output `TryPromote` reads, and `TryPromote` presenting a `TryComputer` as a `Computer`. /// ## Usage /// @@ -44,6 +44,52 @@ pub mod usage { Err("overflow".to_owned()) ); } + + /// `TryPromote` also presents a `TryComputer` as a `Computer` whose `Output` is the `Result`. + pub mod try_promote { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanCompute, TryPromote}; + use cgp::prelude::*; + + #[cgp_impl(new NonZero)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl TryComputer { + type Output = u64; + + fn try_compute(&self, _code: PhantomData, input: u64) -> Result { + if input == 0 { + return Err(Self::raise_error("zero".to_owned())); + } + + Ok(input) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + cgp::core::error::ErrorRaiserComponent: cgp::extra::error::RaiseFrom, + ComputerComponent: TryPromote, + } + } + + check_components! { + App { + ComputerComponent: ((), u64), + } + } + + #[test] + fn compute_returns_the_result() { + assert_eq!(App.compute(PhantomData::<()>, 3), Ok(3)); + assert_eq!(App.compute(PhantomData::<()>, 0), Err("zero".to_owned())); + } + } } /// ## Examples From 19b16d6ed85c29090947fcda2970a94404b7aa3c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 03:08:25 +0000 Subject: [PATCH 126/516] Revise the providers index and singleton reference pages Resync the providers overview and its sixteen singleton pages against their internal documents and the source, and give each a title and description (extending the front-matter sweep). Correctness fixes: - UseType/WithType: a bound on the abstract type is checked when the component is used or checked, not where the entry is written. - UseField: four impl sources, not three; FieldGetter/MutFieldGetter impls carry no IsProviderFor pair; a #[cgp_type] component takes a field's type only through WithField; multi-method getters get no UseField impl. - WithProvider/WithContext: WithContext answers a component from the context's HasType or HasField entry keyed by the component, and is not interchangeable with UseContext. - UseDelegatedType: also wires directly to TypeProviderComponent. - RedirectLookup: a single lookup on the extended path, not a walk; a real registered-component example replaces the dangling one. - UseContext: never the whole value of its own component's entry. - UseDelegate and WithProvider examples now compile as shown (missing providers, missing WithField import); UseDefault uses #[extend]. - Under the hood listings match cargo cgp expand. New Common Mistakes, each a trybuild fixture: the UseContext self-cycle, an unchecked UseType bound, a multi-method getter on UseField, UseDefault without #[uses], and a bare key beside a joined namespace. New mirrors for with_context and use_delegated_type. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/providers/chain_getters.md | 23 ++- docs/reference/providers/index.md | 41 ++--- docs/reference/providers/redirect_lookup.md | 119 +++++++++++--- docs/reference/providers/use_context.md | 84 +++++++--- docs/reference/providers/use_default.md | 58 +++++-- docs/reference/providers/use_delegate.md | 71 ++++++-- .../reference/providers/use_delegated_type.md | 61 +++++-- docs/reference/providers/use_field.md | 104 +++++++++--- docs/reference/providers/use_field_ref.md | 26 +-- docs/reference/providers/use_fields.md | 101 ++++++------ docs/reference/providers/use_type.md | 96 ++++++++--- docs/reference/providers/with_context.md | 151 ++++++++++++++---- .../providers/with_delegated_type.md | 29 ++-- docs/reference/providers/with_field.md | 54 ++++++- docs/reference/providers/with_field_ref.md | 25 ++- docs/reference/providers/with_provider.md | 40 ++++- docs/reference/providers/with_type.md | 24 ++- ...edirect_lookup_common_mistakes_bare_key.rs | 26 +++ ...ect_lookup_common_mistakes_bare_key.stderr | 19 +++ .../use_context_common_mistakes_self_cycle.rs | 24 +++ ..._context_common_mistakes_self_cycle.stderr | 40 +++++ ...se_default_common_mistakes_missing_uses.rs | 22 +++ ...efault_common_mistakes_missing_uses.stderr | 53 ++++++ ...eld_common_mistakes_multi_method_getter.rs | 27 ++++ ...common_mistakes_multi_method_getter.stderr | 47 ++++++ ...se_type_common_mistakes_unchecked_bound.rs | 22 +++ ...ype_common_mistakes_unchecked_bound.stderr | 25 +++ .../reference/providers/chain_getters.rs | 14 +- example-code/tests/reference/providers/mod.rs | 2 + .../reference/providers/redirect_lookup.rs | 54 ++++++- .../tests/reference/providers/use_context.rs | 30 ++-- .../tests/reference/providers/use_default.rs | 52 +++++- .../tests/reference/providers/use_delegate.rs | 15 +- .../reference/providers/use_delegated_type.rs | 40 +++++ .../tests/reference/providers/use_field.rs | 105 ++++++++++-- .../tests/reference/providers/use_fields.rs | 57 +++++-- .../tests/reference/providers/use_type.rs | 33 +++- .../tests/reference/providers/with_context.rs | 82 ++++++++++ .../tests/reference/providers/with_field.rs | 49 +++++- .../reference/providers/with_field_ref.rs | 72 ++++++++- .../reference/providers/with_provider.rs | 81 +++++++++- 41 files changed, 1736 insertions(+), 362 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.rs create mode 100644 example-code/tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs create mode 100644 example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs create mode 100644 example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.rs create mode 100644 example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.rs create mode 100644 example-code/tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.stderr create mode 100644 example-code/tests/reference/providers/use_delegated_type.rs create mode 100644 example-code/tests/reference/providers/with_context.rs diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 79a141f2..f6444f44 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -1,4 +1,6 @@ --- +title: 'ChainGetters — read a field on a nested value' +description: 'The foundational getter that chains a list of field getters, so a getter component reads a field several hops inside its context.' sidebar_label: 'ChainGetters' sidebar_position: 10 --- @@ -10,8 +12,9 @@ Compose a list of field getters into one, reaching a field several hops inside a ## Overview `ChainGetters` reaches a field that does not live directly on the context but several levels -inside it. The **context** is the type a method runs on, and a single -[`UseField`](use_field.md) reads one field of one context. But CGP contexts often nest: a context holds +inside it. The [**context**](/docs/reference/glossary#context) is the type the method runs on, which supplies the +values it needs as its fields, and a single [`UseField`](use_field.md) reads one field of one +context. But CGP contexts often nest: a context holds a config, the config holds a connection, the connection holds a timeout, and a getter may need the innermost value. Writing one provider that walks the whole path by hand is tedious and couples the getter to the nesting. `ChainGetters` takes a list of getters, applies them in order, and @@ -85,11 +88,22 @@ delegate_components! { NameGetterComponent: WithProvider< ChainGetters, - UseField, + UseField, ]>, >, } } + +check_components! { + App { + NameGetterComponent, + } +} + +pub fn demo() { + let app = App { config: Config { name: "test".to_owned() } }; + assert_eq!(app.name(), "test"); +} ``` `App` wires `NameGetterComponent` to `WithProvider>` over a two-element list. The @@ -135,7 +149,8 @@ The head `Getter` reads `ValueA` from the `Context`, and the rest of the chain r `ValueA`, so the whole chain's `Value` is `ValueB`, the value at the end of the path. The head is applied through [`FieldMapper`](../traits/field-access/field_mapper.md) rather than `FieldGetter` directly: `map_field` hands the intermediate reference to a closure that runs the rest of the chain on it, which -keeps the borrowed lifetimes inferring across each hop. +keeps the borrowed lifetimes inferring across each hop. `FieldMapper` has a blanket implementation +for every `FieldGetter` that requires the getter and the tag to be `'static`, so each step of a chain must be a `'static` type. The recursion bottoms out at the empty list, where `ChainGetters` is the identity getter and returns the context it was given: diff --git a/docs/reference/providers/index.md b/docs/reference/providers/index.md index c2e64bac..df3c3cb2 100644 --- a/docs/reference/providers/index.md +++ b/docs/reference/providers/index.md @@ -1,4 +1,5 @@ --- +description: 'The providers CGP ships, grouped by job: context, type, and getter providers, the With… adapters, per-type dispatch, and the handler combinators.' sidebar_label: 'Overview' sidebar_position: 0 --- @@ -6,24 +7,26 @@ sidebar_position: 0 # Providers A provider is a zero-sized type wired to a component to say how that component is implemented for a -context. Providers carry no runtime value; they are type-level markers named in a -[`delegate_components!`](../macros/delegate_components.md) table and resolved at compile time. This page -groups the providers CGP ships by the job they do, in roughly the order most CGP code reaches for them. +[context](/docs/reference/glossary#context), the type the implementation runs against. Providers +carry no runtime value; they are type-level markers named in a +[`delegate_components!`](../macros/delegate_components.md) table and resolved at compile time. This +page groups the providers CGP ships by the job they do, in roughly the order most CGP code reaches +for them. If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here; this page is the fuller map for once the essentials are familiar. ## Wiring an everyday component -[`UseContext`](./use_context.md) implements a provider trait by routing back through the context's own -consumer-trait implementation. A [higher-order provider](/docs/reference/glossary#higher-order-provider) falls back to it, and a dispatch combinator -routes each matched case through it as its default per-variant provider. -[`UseType`](./use_type.md) supplies a concrete type for an abstract-type component, so a context binds -its error type or runtime with one wiring line. -[`UseField`](./use_field.md) implements a getter by reading a context field named by a tag, and -[`UseFields`](./use_fields.md) does the same when every getter method reads a same-named field. -[`UseDefault`](./use_default.md) selects a component's own default method bodies when there is no -behaviour left for a provider to supply. +[`UseContext`](./use_context.md) implements a provider trait by routing back through the context's +own consumer-trait implementation. A +[higher-order provider](/docs/reference/glossary#higher-order-provider) falls back to it, and a +dispatch combinator routes each matched case through it as its default per-variant provider. +[`UseType`](./use_type.md) supplies a concrete type for an abstract-type component, so a context +binds its error type or runtime with one wiring line. [`UseField`](./use_field.md) implements a +getter by reading a context field named by a tag, and [`UseFields`](./use_fields.md) does the same +when every getter method reads a same-named field. [`UseDefault`](./use_default.md) selects a +component's own default method bodies when there is no behavior left for a provider to supply. [`WithProvider`](./with_provider.md) is the adapter behind the `With…` aliases: it turns a foundational provider such as a field getter or a type provider into a provider for a named component, and the @@ -42,13 +45,13 @@ Both are read in wiring far more often than written. ## The specialized getters and type providers -[`UseFieldRef`](./use_field_ref.md) is the foundational getter that borrows a field through `AsRef`, for -a getter that returns a view of a field the context stores as a different type. -[`ChainGetters`](./chain_getters.md) composes a list of getters to reach a field several hops inside a -nested context. -[`UseDelegatedType`](./use_delegated_type.md) resolves an [abstract type](/docs/reference/glossary#abstract-type) through a table rather than -fixing it to one concrete type. Each is reached through [`WithProvider`](./with_provider.md) when wired -to a component. +[`UseFieldRef`](./use_field_ref.md) is the foundational getter that borrows a field through `AsRef`, +for a getter that returns a view of a field the context stores as a different type. +[`ChainGetters`](./chain_getters.md) composes a list of getters to reach a field several hops inside +a nested context. [`UseDelegatedType`](./use_delegated_type.md) resolves an +[abstract type](/docs/reference/glossary#abstract-type) through a table rather than fixing it to one +concrete type. Each is reached through [`WithProvider`](./with_provider.md) when wired to a named +component; `UseDelegatedType` alone is also wired directly to the built-in `TypeProviderComponent`. ## The computation-family combinators diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 1594837b..75fefd04 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -1,4 +1,6 @@ --- +title: 'RedirectLookup — look up a component by path' +description: 'The generated provider that answers a component by looking a type-level path up in a table, the mechanism behind namespaces and the open statement.' sidebar_label: 'RedirectLookup' sidebar_position: 8 --- @@ -24,9 +26,10 @@ this provider is legible. ## Overview `RedirectLookup` separates *which key* a component is looked up under from *which -table* answers it. The ordinary provider blanket impl looks a component up in the **context**'s own -delegation table, keyed by the [component marker](/docs/reference/glossary#component-marker), where the context is the type the method runs -on. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed by a +table* answers it. The ordinary provider blanket impl looks a component up in the +[**context**](/docs/reference/glossary#context)'s own delegation table, keyed by the +[component marker](/docs/reference/glossary#component-marker), where the context is the type the +implementation runs against. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed by a type-level `Path`, then delegates to whatever provider that entry holds. This indirection lets one component's resolution be redirected to a different key in a different table, which is the basis for organizing wiring into namespaces. @@ -46,50 +49,73 @@ generated entries is where this provider appears. Like every CGP provider, it ca ## Usage `RedirectLookup` is in the prelude, but you do not name it directly. It appears where the namespace and -`open` machinery generate it. A component is registered under a path with the -[`#[prefix(@path in Namespace)]`](../attributes/prefix.md) attribute, and a context joins a namespace -or opens a component for per-type dispatch: +`open` machinery generate it. A component registers under a path with the +[`#[prefix(@path in Namespace)]`](../attributes/prefix.md) attribute, and a context that joins the +namespace binds the component's provider at that path, in its own table: ```rust delegate_components! { App { namespace DefaultNamespace; - @bar.baz: TestProvider, + @app.GreeterComponent: GreetHello, } } ``` -A `RedirectLookup` later walks the path-keyed entry above (`@bar.baz`). The path itself is a -[`PathCons`](../types/path_cons.md) chain of [`Symbol!`](../macros/symbol.md) segments, most -easily written with [`Path!`](../macros/path.md). +The path is a [`PathCons`](../types/path_cons.md) chain of [`Symbol!`](../macros/symbol.md) segments +and a component marker, written with the `@`-path syntax [`Path!`](../macros/path.md) also uses. The +declared struct is `RedirectLookup`, but every generated impl and entry passes the +table first and the path second, as `RedirectLookup`, so read the parameter names +as swapped. ## Examples -`RedirectLookup` appears in the delegate the namespace machinery generates, where a component is -registered under a path and reached through it: +A component registers itself under `@app` in `DefaultNamespace`, and a context binds its provider at +that path: ```rust use cgp::prelude::*; +#[cgp_component(Greeter)] +#[prefix(@app in DefaultNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "hello".into() + } +} + pub struct App; delegate_components! { App { namespace DefaultNamespace; - @bar.baz: TestProvider, + @app.GreeterComponent: GreetHello, + } +} + +check_components! { + App { + GreeterComponent, } } + +pub fn demo() { + assert_eq!(App.greet(), "hello"); +} ``` -This registers `TestProvider` under the path `bar` then `baz` in `App`'s default namespace. When a -component is later resolved against `App` through that namespace, its delegate is a -`RedirectLookup` whose `Path` is the `PathCons` chain `bar`, then `baz`, then the component -marker. The lookup follows that path into `App`'s table, matches the entry above, and dispatches to -`TestProvider`. The component marker never keys the context directly; it is the tail of a path that -`RedirectLookup` walks. This is the indirection that lets namespaces organize wiring by path while still -resolving to ordinary providers. +`#[prefix]` makes `DefaultNamespace` route `GreeterComponent` to a `RedirectLookup` over the path +`@app.GreeterComponent`. The `namespace` statement makes `App` resolve its components through that +namespace, so `App.greet()` looks the path `@app.GreeterComponent` up in `App`'s own table and finds +`GreetHello`. The component marker is the last segment of the path rather than a key of its own. `App` +is an [environmental context](/docs/reference/glossary#environmental-context) with no fields. ## When to use it @@ -134,9 +160,33 @@ where The mechanism is one [`DelegateComponent`](../traits/wiring/delegate_component.md) lookup keyed on `__Path__` rather than on the component marker. `RedirectLookup` implements `Greeter` whenever `Components` maps `Path` to a delegate that itself implements `Greeter`, and the method forwards to that -delegate. When the consumer trait carries generic type parameters, the impl additionally constrains -`Path` with [`ConcatPath`](../traits/formatting/concat_path.md) so the parameters are appended to the path before -the lookup, letting the redirected key encode the generic arguments. As always, the impl is paired with a matching +delegate. When the consumer trait carries generic type parameters, the impl first appends every one of them to +the path with [`ConcatPath`](../traits/formatting/concat_path.md), in declaration order, skipping +lifetime and const parameters. For `CanCalculateArea`, `cargo cgp expand` shows, with the +path resugared as `Path!(@Shape)`: + +```rust +impl<__Context__, Shape, __Components__, __Path__> AreaCalculator<__Context__, Shape> +for RedirectLookup<__Components__, __Path__> +where + __Path__: ConcatPath, + __Components__: DelegateComponent<<__Path__ as ConcatPath>::Output>, + <__Components__ as DelegateComponent< + <__Path__ as ConcatPath>::Output, + >>::Delegate: AreaCalculator<__Context__, Shape>, +{ + fn area(__context__: &__Context__, shape: &Shape) -> f64 { + <__Components__ as DelegateComponent< + <__Path__ as ConcatPath>::Output, + >>::Delegate::area(__context__, shape) + } +} +``` + +The lookup is still a single `DelegateComponent` query on the whole extended path, not a walk +segment by segment. A table answers a shorter prefix of the path because +[`delegate_components!`](../macros/delegate_components.md) generates entries generic over the +remaining segments, which is how the `open` statement's key forms work. As always, the impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl. The [`#[prefix(@path in Namespace)]`](../attributes/prefix.md) attribute populates the path side: it @@ -144,6 +194,26 @@ generates a namespace impl whose delegate is `RedirectLookup`, joined onto the component marker, so resolving the component under that namespace follows the prefixed path into the table. +## Common Mistakes + +**A context that joins a namespace cannot also bind a registered component at its bare key.** Joining +`DefaultNamespace` already gives `App` an entry for `GreeterComponent`, the one that redirects to +`@app.GreeterComponent`, so adding `GreeterComponent: GreetHello` to the same table is a second impl +for the same key: + +```text +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` + --> src/main.rs:22:9 + | +20 | namespace DefaultNamespace; + | ---------------- first implementation here +21 | +22 | GreeterComponent: GreetHello, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `App` +``` + +Bind the provider at the registered path, `@app.GreeterComponent: GreetHello`, as the example does. + ## Related constructs - [`#[cgp_component]`](../macros/cgp_component.md) — generates a `RedirectLookup` impl for every @@ -155,8 +225,7 @@ prefixed path into the table. - [`delegate_components!`](../macros/delegate_components.md) — the `open` and `namespace` statements that generate the redirect entries. - [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table the lookup reads. -- [`Path!`](../macros/path.md) and [`PathCons`](../types/path_cons.md) — the type-level path it - walks. +- [`Path!`](../macros/path.md) and [`PathCons`](../types/path_cons.md) — the type-level path it looks up. - [`UseContext`](use_context.md) — the other `#[cgp_component]`-generated provider, routing back to the context. diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index 7c1cf44f..7ccb34e2 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -1,4 +1,6 @@ --- +title: 'UseContext — reuse the context''s own impl' +description: 'The provider that implements a provider trait by calling the context''s own consumer trait, usually as a higher-order provider''s default inner provider.' sidebar_label: 'UseContext' sidebar_position: 1 --- @@ -10,11 +12,12 @@ Satisfy a provider trait by routing back through the context's own consumer-trai ## Overview `UseContext` turns a context's existing consumer-trait implementation into a provider that other -providers can call. The **context** is the type a method runs on, and it normally *uses* a -provider through its consumer trait. Sometimes the implementation another provider wants for a -trait is exactly the one the context already supplies that way. `UseContext` is that bridge: it is -a provider whose method bodies call the consumer method on the context, so handing a component -`UseContext` means "use whatever this context already does for this trait." +providers can call. The [**context**](/docs/reference/glossary#context) is the type the +implementation runs against, and it normally *uses* a provider through its consumer trait. Sometimes +the implementation another provider wants for a trait is exactly the one the context already +supplies that way. `UseContext` is that bridge: it is a provider whose method bodies call the +consumer method on the context, so handing a component `UseContext` means "use whatever this context +already does for this trait." This makes `UseContext` the exact dual of the consumer-trait [blanket implementation](/docs/reference/glossary#blanket-implementation) that [`#[cgp_component]`](../macros/cgp_component.md) generates. That blanket impl runs in the @@ -41,9 +44,11 @@ the provider's struct definition: pub struct EncodeVec(pub PhantomData); ``` -It also appears directly in a wiring entry to route a component through the context's own -implementation, which is how the [dispatch combinators](dispatch/index.md) default their -per-variant provider. +It also appears as a type argument inside a wiring entry, where a provider that takes an inner +provider is given `UseContext` explicitly. The [dispatch combinators](dispatch/index.md), such as +`MatchWithValueHandlers`, default their per-variant provider to it. It is +never the whole value of an entry for the component it implements, which is the cycle +[Common Mistakes](#common-mistakes) describes. `UseContext` stands in for a provider trait only where that trait resolves to a *different* implementation than the one being wired: a wrapper over another trait, or a per-type dispatch entry @@ -93,19 +98,32 @@ delegate_components! { open EncoderComponent; @EncoderComponent.u32: EncodeAsText, - @EncoderComponent.Vec: EncodeVec, + @EncoderComponent.Vec: EncodeVec, } } + +check_components! { + App { + EncoderComponent: [u32, Vec], + } +} + +pub fn demo() { + assert_eq!(App.encode(&vec![1u32, 2, 3]), b"123"); +} ``` -`App` uses the [`open` statement](../macros/delegate_components.md) to wire the `Encoder` component per -value type, giving `Vec` a bare `EncodeVec` whose `Inner` defaults to `UseContext`. Encoding a -`Vec` runs `EncodeVec`, which calls `Inner::encode(self, item)` on each element; `Inner` resolves -through `UseContext` to `App`'s own `CanEncode`, wired to `EncodeAsText`. So encoding -`vec![1u32, 2, 3]` produces the bytes of `"123"`. There is no cycle, because the element lookup is for a -*different* type (`u32`) than the wired one (`Vec`). Naming an explicit inner provider in place of -the `UseContext` default binds the element encoder directly and bypasses the context's `CanEncode` -wiring. +`App` is an [environmental context](/docs/reference/glossary#environmental-context), and the +component is **[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: it +encodes the `Value`, while `App` chooses the encoder for each value type. `App` uses the +[`open` statement](../macros/delegate_components.md) to wire the `Encoder` component per value type, +giving `Vec` a bare `EncodeVec` whose `Inner` defaults to `UseContext`. Encoding a `Vec` +runs `EncodeVec`, which calls `Inner::encode(self, item)` on each element; `Inner` resolves through +`UseContext` to `App`'s own `CanEncode`, wired to `EncodeAsText`. So encoding +`vec![1u32, 2, 3]` produces the bytes of `"123"`. There is no cycle, because the element lookup is +for a *different* type (`u32`) than the wired one (`Vec`). Naming an explicit inner provider in +place of the `UseContext` default binds the element encoder directly and bypasses the context's +`CanEncode` wiring. `UseContext` acts as a default only when the provider's struct definition gives it as the default generic parameter, as `EncodeVec` does. A provider without such a default has no inner provider to fall @@ -150,22 +168,36 @@ where } ``` -The provider method takes the context explicitly and calls the context's own `CanGreet::greet`. Each -`UseContext` impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl -carrying the same `where` clause, so delegation propagates the dependency and a check reports a missing -consumer-trait implementation precisely. Any [supertrait](/docs/reference/glossary#supertrait) bound on the consumer trait is reproduced in the -`where` clause, so a context must satisfy it before `UseContext` can stand in as a provider. +The provider method takes the context explicitly and calls the context's own `CanGreet::greet`. The +impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl carrying +the same `where` clause, so delegation propagates the dependency and a check reports a missing +consumer-trait implementation precisely: + +```rust +impl<__Context__> IsProviderFor for UseContext +where + __Context__: CanGreet, +{} +``` + +Any [supertrait](/docs/reference/glossary#supertrait) bound on the consumer trait is reproduced in +the `where` clause, so a context must satisfy it before `UseContext` can stand in as a provider. ## Common Mistakes **Wiring a component to `UseContext` on the context whose only implementation is that same delegation creates a cycle.** If `App` wired `@EncoderComponent.u32: UseContext`, then `App`'s `CanEncode` would be implemented by delegating to `UseContext`, whose `Encoder` impl in turn calls `App`'s -`CanEncode`. The trait solver chases this in a loop and reports it as an overflow or an unsatisfied -bound. `UseContext` belongs where the provider trait resolves to a *different* implementation, such as a +`CanEncode`. The trait solver chases this in a loop, and a check reports the overflow: + +```text +error[E0275]: overflow evaluating the requirement `App: IsProviderFor` +``` + +`UseContext` belongs where the provider trait resolves to a *different* implementation, such as a wrapper over another trait or a per-type dispatch entry for a different type. The `EncodeVec` -example above is safe for exactly that reason: it is wired for `Vec`, but its inner `UseContext` -resolves `Encoder`, a different entry. +example above is safe for exactly that reason: it is wired for `Vec`, but its inner +`UseContext` resolves `Encoder`, a different entry. ## Related constructs diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index fdc7d1d9..22e8ff9a 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -1,4 +1,6 @@ --- +title: 'UseDefault — wire a trait''s default bodies' +description: 'The marker provider for a component whose implementation is the consumer trait''s own default method bodies, given meaning by an empty #[cgp_impl] block.' sidebar_label: 'UseDefault' sidebar_position: 5 --- @@ -16,11 +18,12 @@ the component can be wired. `UseDefault` is that empty provider: wiring a compon selects an implementation whose method bodies come from the trait's defaults rather than from a dedicated provider. -This keeps a default-only component consistent with the rest of wiring. Without it, a component whose -methods are all defaulted would still need some provider type and some -[`delegate_components!`](../macros/delegate_components.md) entry to take part in the table. `UseDefault` -is the shared name for that role, so a **context** (the type the method runs on) that wants -the defaults wires the component to `UseDefault` and writes no method bodies of its own. +This keeps a default-only component consistent with the rest of wiring. Without it, a component +whose methods are all defaulted would still need some provider type and some +[`delegate_components!`](../macros/delegate_components.md) entry to take part in the table. +`UseDefault` is the shared name for that role, so a [**context**](/docs/reference/glossary#context) +(the type the implementation runs against) that wants the defaults wires the component to +`UseDefault` and writes no method bodies of its own. `UseDefault` is a bare marker that CGP defines but does not implement for any trait. Unlike [`UseContext`](use_context.md) or the getter providers, no macro generates a provider implementation @@ -55,8 +58,8 @@ delegate_components! { } ``` -Because `UseDefault` has no generated impls, the author controls precisely which components it serves. -A type with no provider impl written for a component is simply not a provider for it; there is no +Because `UseDefault` has no generated impls, the author controls precisely which components it +serves. A type with no provider impl written for a component is not a provider for it; there is no automatic fallback, and the empty-body `#[cgp_impl]` is the explicit opt-in. ## Examples @@ -76,7 +79,8 @@ pub trait HasName { } #[cgp_component(Greeter)] -pub trait CanGreet: HasName { +#[extend(HasName)] +pub trait CanGreet { fn greet(&self) -> String { format!("Hello, {}!", self.name()) } @@ -97,15 +101,27 @@ delegate_components! { NameGetterComponent, GreeterComponent, ]: - UseDefault, + UseDefault, } } + +check_components! { + App { + NameGetterComponent, + GreeterComponent, + } +} + +pub fn demo() { + assert_eq!(App.greet(), "Hello, John!"); +} ``` The first `#[cgp_impl]` makes `UseDefault` a `NameGetter` provider whose `name` is the trait default `"John"`; the second makes it a `Greeter` provider whose `greet` is the trait default that formats -around `self.name()`. The `Greeter` impl restates its consumer-side dependency with -[`#[uses(HasName)]`](../attributes/uses.md), because the default body of `greet` calls `name`. `App` +around `self.name()`. The `Greeter` impl restates its dependency with [`#[uses(HasName)]`](../attributes/uses.md), because +the default body of `greet` calls `name`; [`#[extend(HasName)]`](../attributes/extend.md) on the +trait does not give the provider that bound, as [Common Mistakes](#common-mistakes) shows. `App` then delegates both components to `UseDefault` in one array entry, so `App.greet()` produces `"Hello, John!"` entirely from the two default bodies, with no method implemented on `App` or on a dedicated provider. @@ -135,6 +151,23 @@ matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) implementation c clause. That is the same pair any `#[cgp_impl]` produces; the only thing special about `UseDefault` is the empty body and the shared, conventional name. +## Common Mistakes + +**An empty impl still has to state what the default bodies call.** `#[extend(HasName)]` makes +`HasName` a supertrait of `CanGreet`, which the provider trait `Greeter` carries as a `where` +predicate on the context. A generic `#[cgp_impl(UseDefault)] impl Greeter {}` must prove that +predicate, so without `#[uses(HasName)]` the impl itself fails: + +```text +error[E0277]: the trait bound `__Context__: HasName` is not satisfied + --> src/main.rs:19:1 + | +19 | #[cgp_impl(UseDefault)] + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `DelegateComponent` is not implemented for `__Context__` +``` + +Add `#[uses(HasName)]` to the impl, as the example does. + ## Related constructs - [`#[cgp_impl]`](../macros/cgp_impl.md) — writes the empty-body provider impl that gives `UseDefault` @@ -152,9 +185,8 @@ The ideas behind it: ## Source -- Struct: +- Struct, the only item in its file: [`use_default.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_default.rs) - — the file contains only the bare struct, with no generated impls. --- diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 7150c4f6..7f040a84 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -1,4 +1,6 @@ --- +title: 'UseDelegate — legacy per-type dispatch table' +description: 'The legacy provider that routes a component to a different inner provider per generic-parameter type through a nested table; open replaces it.' sidebar_label: 'UseDelegate' sidebar_position: 7 --- @@ -27,8 +29,8 @@ It is expected to be deprecated once `open` is shown to cover every dispatch cas ## Overview `UseDelegate` chooses a provider based on a type argument rather than on the component alone. An -ordinary component picks its provider by looking the component name up in the **context**'s delegation -table, where the context is the type the method runs on. But when a provider trait carries an +ordinary component picks its provider by looking the component name up in the [**context**](/docs/reference/glossary#context)'s delegation +table, where the context is the type the implementation runs against. But when a provider trait carries an extra generic parameter, such as a `SourceError` to convert or a `Shape` to measure, the right provider often depends on which concrete type that parameter is. `UseDelegate` performs a second lookup: it treats one generic parameter as a key and reads the matching inner provider out of a table, so a single @@ -77,8 +79,30 @@ pub trait CanCalculateArea { fn area(&self, shape: &Shape) -> f64; } -pub struct Rectangle; -pub struct Circle; +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +pub struct Circle { + pub radius: f64, +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height + } +} + +#[cgp_impl(new CircleArea)] +impl AreaCalculator { + fn area(&self, shape: &Circle) -> f64 { + core::f64::consts::PI * shape.radius * shape.radius + } +} + +pub struct MyApp; delegate_components! { MyApp { @@ -89,6 +113,16 @@ delegate_components! { }>, } } + +check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } +} + +pub fn demo() { + assert_eq!(MyApp.area(&Rectangle { width: 2.0, height: 3.0 }), 6.0); +} ``` The wiring reads in two layers. `MyApp` delegates `AreaCalculatorComponent` to @@ -96,7 +130,10 @@ The wiring reads in two layers. `MyApp` delegates `AreaCalculatorComponent` to table. The inner table maps the `Rectangle` type to `RectangleArea` and the `Circle` type to `CircleArea`. The result is that `MyApp` implements `CanCalculateArea` through `RectangleArea` and `CanCalculateArea` through `CircleArea`, with `UseDelegate` selecting between -them by the `Shape` argument. Adding a shape is one more entry in the inner table. +them by the `Shape` argument. Adding a shape is one more entry in the inner table. `MyApp` is an +[environmental context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: it measures the +`Shape`, while `MyApp` decides which provider measures each one. The same dispatch, written with `open` for new code, folds the entries into the context's own table: @@ -130,27 +167,27 @@ too, with a key that has one path segment per type parameter. The [`#[derive_delegate(UseDelegate)]`](../attributes/derive_delegate.md) attribute on a component generates the `UseDelegate` provider impl, which uses `Components` as the table and the named -parameter as the key. For a component such as `CanRaiseError` (provider `ErrorRaiser`) with -a `#[derive_delegate(UseDelegate)]` attribute, the generated impl is: +parameter as the key. For the `CanCalculateArea` component above, with its +`#[derive_delegate(UseDelegate)]` attribute, `cargo cgp expand` shows: ```rust -impl ErrorRaiser - for UseDelegate +impl<__Context__, Shape, __Components__, __Delegate__> AreaCalculator<__Context__, Shape> +for UseDelegate<__Components__> where - Context: HasErrorType, - Components: DelegateComponent, - Delegate: ErrorRaiser, + __Components__: DelegateComponent<(Shape), Delegate = __Delegate__>, + __Delegate__: AreaCalculator<__Context__, Shape>, { - fn raise_error(error: SourceError) -> Context::Error { - Delegate::raise_error(error) + fn area(__context__: &__Context__, shape: &Shape) -> f64 { + __Delegate__::area(__context__, shape) } } ``` The mechanism is a single [`DelegateComponent`](../traits/wiring/delegate_component.md) lookup keyed on -`SourceError`. `UseDelegate` implements `ErrorRaiser` for a given `SourceError` exactly when -`Components` maps that `SourceError` to a delegate that itself implements `ErrorRaiser`, and the method -forwards to it. Only the parameter named inside `UseDelegate<...>` is the key; the rest pass through +`(Shape)`, which is the bare type `Shape` rather than a one-element tuple; `UseDelegate<(A, B)>` keys +on a real tuple of two parameters. `UseDelegate` implements `AreaCalculator` for a given +`Shape` exactly when `Components` maps that `Shape` to a delegate that itself implements +`AreaCalculator`, and the method forwards to it. Only the parameter named inside `UseDelegate<...>` is the key; the rest pass through unchanged. Each impl is paired with an [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl so dependencies propagate to a check. A component may derive more than one dispatcher when different parameters should be routed differently. diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index 3f19062a..89e461b3 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -1,4 +1,6 @@ --- +title: 'UseDelegatedType — look a type up in a table' +description: 'The type provider that resolves an abstract type by looking its tag up in a delegate_components! table, instead of fixing it to one concrete type.' sidebar_label: 'UseDelegatedType' sidebar_position: 11 --- @@ -15,8 +17,8 @@ type to one fixed `T`. But sometimes a single provider must answer several abstr once, or route each type tag to a different concrete type chosen elsewhere, such as when a namespace or a [higher-order provider](/docs/reference/glossary#higher-order-provider) supplies a coherent bundle of types. Hand-writing one `UseType` entry per tag would scatter that decision; `UseDelegatedType` concentrates it into one `Components` table the provider -consults. As always, the **context** (the type that implements the trait) points its type -components at the provider. +consults. As always, the [**context**](/docs/reference/glossary#context) (the type that implements the trait) +points its type components at the provider. The mechanism is the same indirection [`UseDelegate`](use_delegate.md) provides for behavioral components, lifted to the type level. Where `UseDelegate` dispatches a *method call* to @@ -27,16 +29,57 @@ and the other yields a type. Like every CGP provider, it carries no runtime valu ## Usage -`UseDelegatedType` supplies only the foundational [`TypeProvider`](../components/has_type.md), so it is -wired through its [`WithDelegatedType`](with_delegated_type.md) alias rather than named directly. See -[`WithDelegatedType`](with_delegated_type.md) for the import, the wiring form, and a worked example; the -mechanism those rest on is described under [Under the hood](#under-the-hood) below. +`UseDelegatedType` implements only the foundational [`TypeProvider`](../components/has_type.md), so a +[`#[cgp_type]`](../macros/cgp_type.md) component is wired to it through its +[`WithDelegatedType`](with_delegated_type.md) alias; see that page for the wiring form and a worked +example. Neither name is in the prelude, and both are imported from `cgp::core::types`. + +The one place it is named directly is the built-in `TypeProviderComponent`, also imported from +`cgp::core::types`. There the lookup key is the `Tag` of `HasType`, so the table maps tag types +to concrete types: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::core::types::{TypeProviderComponent, UseDelegatedType}; + +pub struct ScalarTag; +pub struct IndexTag; + +pub struct AppTypes; + +delegate_components! { + AppTypes { + ScalarTag: f64, + IndexTag: usize, + } +} + +pub struct App; + +delegate_components! { + App { + TypeProviderComponent: UseDelegatedType, + } +} + +pub fn types( + scalar: PhantomData<>::Type>, + index: PhantomData<>::Type>, +) -> (PhantomData, PhantomData) { + (scalar, index) +} +``` + +`App` answers `HasType` with `f64` and `HasType` with `usize`, and `types` +compiles only because they are those types. `App` is an +[environmental context](/docs/reference/glossary#environmental-context), and `AppTypes` is a plain +table whose values are types rather than providers. ## When to use it -You choose `UseDelegatedType` by wiring its [`WithDelegatedType`](with_delegated_type.md) alias, so the -guidance on when to answer several abstract types from one shared table — rather than fixing each one -with [`UseType`](use_type.md) — lives with that alias, on +You choose `UseDelegatedType` by wiring its [`WithDelegatedType`](with_delegated_type.md) alias, so the guidance on when to answer several abstract types from one shared table, rather than fixing +each one with [`UseType`](use_type.md), lives with that alias, on [`WithDelegatedType`](with_delegated_type.md). ## Under the hood diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index 31a0bdd0..821a56e4 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -1,4 +1,6 @@ --- +title: 'UseField — a getter that reads a named field' +description: 'The provider that implements a getter by reading the context field a type-level tag names, so the field name is a wiring choice, not the method name.' sidebar_label: 'UseField' sidebar_position: 3 --- @@ -12,8 +14,8 @@ decision rather than the method name. `UseField` decouples a getter's method name from the field it reads. A getter component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes a value the context can supply, such as -`fn name(&self) -> &str`. The **context** is the type the method runs on, and it supplies -that value as one of its own fields. But the context may store the value under a different field name, +`fn name(&self) -> &str`. The [**context**](/docs/reference/glossary#context) is the type the method runs on, which supplies +the values it needs as its fields. But the context may store the value under a different field name, say `first_name`, and different contexts may store it under different names. `UseField` carries the field name as its type parameter, so wiring a getter to `UseField` makes it read `first_name` even though the method is `name`. The field name lives in the wiring, not in the @@ -77,14 +79,22 @@ delegate_components! { } } -fn greet(person: &Person) { - println!("Hello, {}!", person.name()); // reads the first_name field +check_components! { + Person { + NameGetterComponent, + } +} + +pub fn demo() { + let person = Person { first_name: "Alice".to_owned() }; + assert_eq!(person.name(), "Alice"); // reads the first_name field } ``` -`Person` wires `NameGetterComponent` to `UseField`, so `person.name()` reads -the `first_name` field. The method name and the field name diverge, and the field name comes entirely -from the wiring. +`Person` is a [value context](/docs/reference/glossary#value-context): the getter reads its own +data. It wires `NameGetterComponent` to `UseField`, so `person.name()` reads +the `first_name` field. The method name and the field name diverge, and the field name comes +entirely from the wiring. The same binding can be written with the [`WithField`](with_field.md) alias, which routes through [`WithProvider`](with_provider.md). @@ -111,9 +121,39 @@ inside a nested context, use [`ChainGetters`](chain_getters.md). ## Under the hood -`UseField` implements three provider traits, each forwarding to the context's -[`HasField`](../traits/field-access/has_field.md) implementation for `Tag`. The central one is the provider-side -getter [`FieldGetter`](../traits/field-access/field_getter.md), which reads the field by reference: +`UseField` is implemented in four places, each forwarding to the context's +[`HasField`](../traits/field-access/has_field.md) implementation for `Tag`. + +**The getter component's own provider trait.** For a single-method getter, +[`#[cgp_getter]`](../macros/cgp_getter.md) generates a `UseField` implementation with the field tag +left free, and this is the implementation a direct `UseField` wiring uses. For the +`HasName` getter above, `cargo cgp expand` shows: + +```rust +impl<__Context__, __Tag__> NameGetter<__Context__> for UseField<__Tag__> +where + __Context__: HasField<__Tag__, Value = String>, +{ + fn name(__context__: &__Context__) -> &str { + __context__.get_field(::core::marker::PhantomData::<__Tag__>).as_str() + } +} + +impl<__Context__, __Tag__> IsProviderFor +for UseField<__Tag__> +where + __Context__: HasField<__Tag__, Value = String>, +{} +``` + +The `&str` return reads a `String` field and appends `.as_str()`, the getter macros' return-type +shorthand. The paired [`IsProviderFor`](../traits/wiring/is_provider_for.md) implementation carries +the same `HasField` bound, so a check names a missing field precisely. A getter with more than one +method gets no `UseField` implementation, since one tag cannot name several fields; +[Common Mistakes](#common-mistakes) shows the error. + +**The foundational field getters.** `UseField` implements +[`FieldGetter`](../traits/field-access/field_getter.md), which reads the field by reference: ```rust impl FieldGetter for UseField @@ -128,18 +168,38 @@ where } ``` -Two tags appear for a reason. `OutTag` is the tag the *component* asks under, the getter's own name, -while `Tag` is the *field* tag the provider was parameterized with. The implementation ignores `OutTag` -and reads `Tag` from the context, which is the decoupling: the component's identity and the field name -are independent. The associated `Value` comes from the context's `HasField` implementation, so -the returned reference is to the real field. - -`UseField` also implements the mutable getter [`MutFieldGetter`](../traits/field-access/mut_field_getter.md) -the same way, requiring `Context: HasFieldMut` and returning `&mut Value`. And it implements -[`TypeProvider`](../components/has_type.md), reporting the field's `Value` type as an [abstract type](/docs/reference/glossary#abstract-type), so -the *type* of a field can itself be wired as a context's abstract type. Each implementation is paired -with an [`IsProviderFor`](../traits/wiring/is_provider_for.md) implementation carrying the same `HasField` -bound, so delegation propagates the dependency and a check reports a missing field precisely. +Two tags appear for a reason. `OutTag` is the tag the *component* asks under, the getter's own +marker, while `Tag` is the *field* tag the provider was parameterized with. The implementation +ignores `OutTag` and reads `Tag` from the context, which is the decoupling: the component's identity +and the field name are independent. The mutable getter +[`MutFieldGetter`](../traits/field-access/mut_field_getter.md) is implemented the same way, requiring +`Context: HasFieldMut` and returning `&mut Value`. These are plain traits rather than +components, so the implementations carry no `IsProviderFor` pair; a getter component reaches them +through [`WithField`](with_field.md), whose `WithProvider` wrapper does. + +**[`TypeProvider`](../components/has_type.md).** `UseField` reports the field's `Value` type as an +[abstract type](/docs/reference/glossary#abstract-type), with a matching `IsProviderFor` implementation, +so the *type* of a field can be wired as a context's abstract type. The built-in +`TypeProviderComponent` takes `UseField` directly, while a +[`#[cgp_type]`](../macros/cgp_type.md) component takes it as `WithField`, because +the macro generates `UseType` and `WithProvider` implementations but no `UseField` one. + +**The handler family.** `Computer` and `AsyncComputer` are implemented for `UseField` by +forwarding the computation to the value stored in the field, which must itself implement the +consumer trait; see [`Computer`](../components/handler/computer.md#usage). + +## Common Mistakes + +**A getter with more than one method cannot be wired to `UseField`.** `#[cgp_getter]` generates the +`UseField` implementation only for a single-method getter, so wiring a two-method `HasFooBar` getter +to `UseField` fails at the check: + +```text +error[E0277]: the trait bound `cgp::prelude::UseField>>>>: IsProviderFor` is not satisfied +``` + +Wire such a getter to [`UseFields`](use_fields.md) when each method reads a same-named field, or split +it into single-method getters when the field names differ. ## Related constructs diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index ca44c1be..0cd2acd4 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -1,4 +1,6 @@ --- +title: 'UseFieldRef — borrow a field as another type' +description: 'The foundational field getter that borrows a field through AsRef or AsMut as a different type, wired to a getter through the WithFieldRef alias.' sidebar_label: 'UseFieldRef' sidebar_position: 9 --- @@ -10,8 +12,8 @@ stored type differs from the getter's return type. ## Overview -`UseFieldRef` reads the field named by `Tag` from the **context** (the type the method -runs on, which supplies the field) and borrows it through `AsRef` to produce a `&Value`, where the +`UseFieldRef` reads the field named by `Tag` from the [**context**](/docs/reference/glossary#context) (the type the method runs on, which supplies +the values it needs as its fields) and borrows it through `AsRef` to produce a `&Value`, where the stored field type implements `AsRef`. It exists for a getter whose return type is reached *through* a field rather than being the field's own type: a `&Config` from a stored `Arc`, for example, where the field is not a `Config` but can be borrowed as one. @@ -22,10 +24,11 @@ component's own provider, so it is wired through its [`WithFieldRef`](with_field [`#[cgp_getter]`](../macros/cgp_getter.md) generates a getter-component implementation for directly. Most borrowed-view getters do not need `UseFieldRef` at all, and this is the key thing to know before -reaching for it. When a getter's return type is one of the shorthands the getter macros recognize, -`&str` or `&[u8]`, the generated [`UseField`](use_field.md) implementation already borrows for you: it -reads the field and calls `as_str()` or `as_ref()`, so a `&str` getter over a `String` field, or a -`&[u8]` getter over a `Vec` field, is wired with a plain `UseField`. `UseFieldRef` is for the +reaching for it. When a getter's return type is one of the shorthands the getter macros recognize, the generated +[`UseField`](use_field.md) implementation already borrows for you: a `&str` getter reads a `String` +field through `.as_str()`, a `&[T]` getter reads any `'static` field implementing `AsRef<[T]>`, such +as a `Vec`, through `.as_ref()`, and an `Option<&T>` or `Option<&str>` getter reads an +`Option` or `Option` field. Each is wired with a plain `UseField`. `UseFieldRef` is for the remaining case, a getter that returns `&T` for some type `T` the field is not stored as but can be borrowed as. Like every CGP provider, it carries no runtime value. @@ -38,10 +41,9 @@ those rest on is described under [Under the hood](#under-the-hood) below. ## When to use it -You choose `UseFieldRef` by wiring its [`WithFieldRef`](with_field_ref.md) alias, so the guidance on when -a borrowed-view getter needs it — rather than the plain [`UseField`](use_field.md) or an -[`#[implicit]`](../attributes/implicit.md) argument — lives with that alias, on -[`WithFieldRef`](with_field_ref.md). +You choose `UseFieldRef` by wiring its [`WithFieldRef`](with_field_ref.md) alias, so the guidance on when a borrowed-view getter needs it, rather than the plain +[`UseField`](use_field.md) or an [`#[implicit]`](../attributes/implicit.md) argument, lives with that +alias, on [`WithFieldRef`](with_field_ref.md). ## Under the hood @@ -65,8 +67,8 @@ where The `where` clause carries the defining constraint: the context's field at `Tag` must implement `AsRef`, so the stored type can be borrowed as the exposed type. As in [`UseField`](use_field.md), `OutTag` is the tag the component asks under and is ignored, while the field -is read at `Tag`. The body reads the field and calls `as_ref()`. The `'static` bound on the field type -lets Rust infer the borrow's lifetime through the `AsRef` call. +is read at `Tag`. The body reads the field and calls `as_ref()`. The stored field type must also be `'static`, so a +field holding a borrowed reference cannot be read this way. `UseFieldRef` also implements the mutable getter [`MutFieldGetter`](../traits/field-access/mut_field_getter.md), requiring the field type to implement both `AsRef` and `AsMut` and returning `&mut Value` diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 56c372b4..4f7e8f36 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -1,4 +1,6 @@ --- +title: 'UseFields — getters for same-named fields' +description: 'The provider that implements every method of a getter component by reading the context field named after the method, for any number of methods.' sidebar_label: 'UseFields' sidebar_position: 4 --- @@ -10,13 +12,14 @@ method. ## Overview -`UseFields` is the provider form of the convention "the method `name` reads the field `name`." A getter -component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes one or more values the -**context** can supply, and the most common arrangement is that each value lives in a same-named field. -The context is the type the method runs on, and it supplies those values as its own fields. -`UseFields` is the provider that realizes the arrangement: wiring a getter to `UseFields` makes every -method read the context field whose name equals the method name, looked up through -[`HasField`](../traits/field-access/has_field.md) keyed by a [`Symbol!`](../macros/symbol.md). +`UseFields` is the provider form of the convention "the method `name` reads the field `name`." A +getter component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes one or more +values the **context** can supply, and the most common arrangement is that each value lives in a +same-named field. The [context](/docs/reference/glossary#context) is the type the method runs on, +which supplies the values it needs as its fields. `UseFields` is the provider that realizes the +arrangement: wiring a getter to `UseFields` makes every method read the context field whose name +equals the method name, looked up through [`HasField`](../traits/field-access/has_field.md) keyed by +a [`Symbol!`](../macros/symbol.md). This is the provider analogue of the [blanket implementation](/docs/reference/glossary#blanket-implementation) that [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) emits. `#[cgp_auto_getter]` produces a single @@ -27,8 +30,9 @@ participates in CGP wiring can still opt into the auto-getter convention when it its methods. `UseFields` is distinct from its sibling [`UseField`](use_field.md), and the singular-versus-plural -naming marks the difference. `UseField` keys on a tag the wiring chooses, letting one method read -a field of any name; `UseFields` takes no parameter and keys every method on its own name. Reach for +naming marks the difference. `UseField` keys on a tag the wiring chooses, letting one method read a field of any name, and it +exists only for single-method getters; `UseFields` takes no parameter, keys every method on its own +name, and works for any number of methods. Reach for `UseField` when the field name must differ from the method name, and for `UseFields` when the convention holds. Like every CGP provider, `UseFields` carries no runtime value: it is a marker named in wiring. @@ -53,37 +57,49 @@ macros support apply here too, so a `&str` return reads a `String` field and app ## Examples -A context whose field name matches the getter method can be wired to `UseFields` to get the auto-getter -convention inside a `#[cgp_getter]` component. The method `foo` and the field `foo` share a name: +A getter with two methods, each read from its same-named field, which is the case `UseField` cannot +serve: ```rust use cgp::prelude::*; #[cgp_getter] -pub trait HasFoo { +pub trait HasFooBar { fn foo(&self) -> &str; + fn bar(&self) -> &u8; } #[derive(HasField)] pub struct App { pub foo: String, + pub bar: u8, } delegate_components! { App { - FooGetterComponent: UseFields, + FooBarGetterComponent: UseFields, + } +} + +check_components! { + App { + FooBarGetterComponent, } } -fn describe(app: &App) -> &str { - app.foo() // reads the `foo` field +pub fn demo() { + let app = App { foo: "hi".to_owned(), bar: 7 }; + + assert_eq!(app.foo(), "hi"); // reads the `foo` field + assert_eq!(*app.bar(), 7); // reads the `bar` field } ``` -Because `App` wires `FooGetterComponent` to `UseFields`, the getter reads `App`'s `foo` field, the -field whose name equals the method `foo`. If the value were stored under a differently named field, -this wiring would not apply, and the context would wire [`UseField`](use_field.md) with -the actual field name instead. +Because `App` wires `FooBarGetterComponent` to `UseFields`, each method reads the field whose name +equals its own. `App` is a [value context](/docs/reference/glossary#value-context): the getters read +its own data. If one value were stored under a differently named field, that method would need a +single-method getter of its own, wired to [`UseField`](use_field.md) with the actual +field name. ## When to use it @@ -92,48 +108,43 @@ the wired counterpart of the [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md case where the getter is a full component rather than a blanket impl. Prefer [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) when the getter does not need to be a -wireable component, and prefer an [`#[implicit]`](../attributes/implicit.md) argument when a provider -simply needs a value from its own context, which is the common case and needs no [getter trait](/docs/reference/glossary#getter-trait) at all. +wireable component, and prefer an [`#[implicit]`](../attributes/implicit.md) argument when a provider needs a value from its own context, which is the common case and needs no [getter trait](/docs/reference/glossary#getter-trait) at all. Reach for [`UseField`](use_field.md) instead when the field name must differ from the method name. ## Under the hood [`#[cgp_getter]`](../macros/cgp_getter.md) generates a `UseFields` implementation of the getter's provider trait, reading each method's value from the field whose name matches the method, keyed by a -`Symbol!`. For a single-method getter such as +`Symbol!`. For the `HasFooBar` getter above, `cargo cgp expand` shows this implementation for the +generated `FooBarGetter` provider trait, with the macro's real placeholder identifiers: ```rust -#[cgp_getter] -pub trait HasFoo { - fn foo(&self) -> &str; -} -``` - -the macro emits this `UseFields` implementation for the generated `FooGetter` provider trait (shown -with the macro's real placeholder identifiers, and with `Symbol!("foo")` in sugared form): - -```rust -impl<__Context__> FooGetter<__Context__> for UseFields +impl<__Context__> FooBarGetter<__Context__> for UseFields where __Context__: HasField, + __Context__: HasField, { fn foo(__context__: &__Context__) -> &str { - __context__.get_field(PhantomData::).as_str() + __context__.get_field(::core::marker::PhantomData::).as_str() + } + + fn bar(__context__: &__Context__) -> &u8 { + __context__.get_field(::core::marker::PhantomData::) } } ``` -Each method becomes a `HasField` bound keyed on the method name as a `Symbol!`, and the body reads that -field. The `&str` return makes the field `Value` a `String` and appends `.as_str()`, the same shorthand -[`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) uses. When a getter has several methods, the -implementation carries one `HasField` bound and one body per method, each keyed by its own name. The -implementation is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md), so a check -reports a missing field precisely. - -This is one of three provider implementations `#[cgp_getter]` generates for a getter component. The -other two are [`UseField`](use_field.md), for a wiring-chosen field name, and -[`WithProvider`](with_provider.md), for adapting a foundational field getter. A context picks among -them at wiring time. +Each method becomes a `HasField` bound keyed on the method name as a `Symbol!`, and the body reads +that field. The `&str` return makes the field `Value` a `String` and appends `.as_str()`, the same +shorthand [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) uses. The implementation carries one +`HasField` bound and one body per method, each keyed by its own name. The implementation is paired +with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md), so a check reports a missing +field precisely. + +This is one of three provider implementations `#[cgp_getter]` generates for a getter component, and +the only one a getter with several methods gets. The other two, [`UseField`](use_field.md) for a +wiring-chosen field name and [`WithProvider`](with_provider.md) for adapting a foundational field +getter, are generated for single-method getters alone. A context picks among them at wiring time. ## Related constructs diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index 27de0556..a300086a 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -1,4 +1,6 @@ --- +title: 'UseType — fix an abstract type by wiring' +description: 'The provider that sets an abstract-type component to a concrete type, so a context chooses its error, scalar, or runtime type with one wiring line.' sidebar_label: 'UseType' sidebar_position: 2 --- @@ -23,13 +25,14 @@ different jobs. ## Overview `UseType` removes the need to hand-write a provider every time a **context** wants to fix an -abstract type to a concrete one. The context is the type that implements the trait, and it decides what -each abstract type resolves to. An abstract type in CGP is a trait with a single associated type, -defined with [`#[cgp_type]`](../macros/cgp_type.md), such as `trait HasScalarType { type Scalar; }`. -Generic code refers to the type without committing to any particular one, and a concrete context -decides what it actually is. Without `UseType`, making that decision would mean writing a small -provider whose only content is `type Scalar = f64;`, repeated for every abstract type and every -concrete choice. +abstract type to a concrete one. The context is the +[type that implements the trait](/docs/reference/glossary#context), and it decides what each +abstract type resolves to. An abstract type in CGP is a trait with a single associated type, defined +with [`#[cgp_type]`](../macros/cgp_type.md), such as `trait HasScalarType { type Scalar; }`. Generic +code refers to the type without committing to any particular one, and a concrete context decides +what it actually is. Without `UseType`, making that decision would mean writing a small provider +whose only content is `type Scalar = f64;`, repeated for every abstract type and every concrete +choice. `UseType` captures that trivial shape once. It is a [`TypeProvider`](../components/has_type.md) that reports its type parameter `T` as the abstract type, so wiring a context's type component to @@ -51,17 +54,20 @@ delegate_components! { } ``` -A `#[cgp_type]` trait such as `HasScalarType` generates the provider trait `ScalarTypeProvider` and the -[component marker](/docs/reference/glossary#component-marker) `ScalarTypeProviderComponent`; wiring that marker to `UseType` sets the context's -`Scalar` to `f64`. Any bound on the associated type, such as `type Scalar: Copy`, is enforced against -the concrete type at the wiring site. +A `#[cgp_type]` trait such as `HasScalarType` generates the provider trait `ScalarTypeProvider` and +the [component marker](/docs/reference/glossary#component-marker) `ScalarTypeProviderComponent`; +wiring that marker to `UseType` sets the context's `Scalar` to `f64`. Any bound on the +associated type, such as `type Scalar: Copy`, is checked against the concrete type when the +component is used or checked, not where the entry is written, since wiring is lazy; +[Common Mistakes](#common-mistakes) shows the consequence. `UseType` also has an alias, [`WithType`](with_type.md), the `WithProvider`-adapted form imported from `cgp::core::types`. Both bind the same type; prefer the plain `UseType` form. ## Examples -A complete use defines an abstract type, wires a concrete type with `UseType`, and reads it back: +A complete use defines an abstract type, wires a concrete type with `UseType`, checks the wiring, +and reads the type back in generic code: ```rust use cgp::prelude::*; @@ -75,14 +81,34 @@ pub struct App; delegate_components! { App { - ScalarTypeProviderComponent: UseType, + ScalarTypeProviderComponent: UseType, } } + +check_components! { + App { + ScalarTypeProviderComponent, + } +} + +pub fn zero() -> Context::Scalar +where + Context: HasScalarType, + Context::Scalar: Default, +{ + Default::default() +} + +pub fn demo() { + let scalar: f64 = zero::(); + assert_eq!(scalar, 0.0); +} ``` `App` wires `ScalarTypeProviderComponent` to `UseType`, so `App` implements `HasScalarType` with -`Scalar = f64`. The `Copy` bound on the associated type is checked against `f64` where the wiring is -written. +`Scalar = f64`, and `zero::()` returns an `f64`. The check confirms that `f64` meets the `Copy` +bound on the associated type. `zero` names the type only as `Context::Scalar`, so it serves any +context whatever scalar type that context wires. The same binding can be written with the [`WithType`](with_type.md) alias, which routes through [`WithProvider`](with_provider.md). @@ -112,25 +138,45 @@ impl TypeProvider for UseType { ``` The implementation is unconditional in `Context` and `Tag`: `UseType` is a `TypeProvider` whose -`Type` is `f64` regardless of which context or type tag asks. `HasType` is the consumer trait that -reads this, so once a context's type component is wired to `UseType`, the context implements -`HasType` with `Type = f64`. +`Type` is `f64` regardless of which context or type tag asks. `HasType` is the consumer trait +that reads this, so once a context wires `TypeProviderComponent` to `UseType`, the context +implements `HasType` with `Type = f64` for every `Tag`. [`#[cgp_type]`](../macros/cgp_type.md) targets the same provider. For -`#[cgp_type] trait HasScalarType { type Scalar; }`, the macro generates a `UseType` implementation for -the component's own provider trait: +`#[cgp_type] trait HasScalarType { type Scalar: Copy; }`, the macro generates a `UseType` +implementation for the component's own provider trait: ```rust -impl ScalarTypeProvider<__Context__> for UseType { +impl ScalarTypeProvider<__Context__> for UseType +where + Scalar: Copy, +{ type Scalar = Scalar; } ``` -so wiring `ScalarTypeProviderComponent` to `UseType` sets `Scalar = f64`. The built-in -`TypeProvider` impl and the per-component impl are the two faces of the same `UseType` struct: the -first makes it a provider for the built-in `HasType` component, the second for a user-defined +Wiring `ScalarTypeProviderComponent` to `UseType` therefore sets `Scalar = f64`. The built-in +`TypeProvider` impl and the per-component impl are the two faces of the same `UseType` struct: +the first makes it a provider for the built-in `HasType` component, the second for a user-defined abstract-type component. A bound on the associated type is copied into the generated impl's `where` -clause, so the concrete type must satisfy it at the wiring site. +clause, as the `Copy` above shows, so the concrete type must satisfy it wherever the component is +used or checked. + +## Common Mistakes + +**A concrete type that breaks the associated type's bound is not reported where it is wired.** +Wiring `ScalarTypeProviderComponent: UseType` for the `type Scalar: Copy` declaration above +compiles, because a delegation entry alone checks nothing. The mismatch surfaces only when something +needs `App: HasScalarType`, or at a [`check_components!`](../macros/check_components.md) block +naming the component: + +```text +error[E0277]: the trait bound `String: Copy` is not satisfied +... +note: required for `cgp::prelude::UseType` to implement `IsProviderFor` +``` + +Check every context's abstract-type components, so the bound is tested next to the wiring. ## Related constructs diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md index d073d22a..8593bac5 100644 --- a/docs/reference/providers/with_context.md +++ b/docs/reference/providers/with_context.md @@ -1,46 +1,110 @@ --- +title: 'WithContext — the context''s own entry' +description: 'The alias WithProvider: a named type or getter component answered by the context''s own HasType or HasField entry, keyed by the component.' sidebar_label: 'WithContext' sidebar_position: 6.1 --- # `WithContext` -The `WithProvider`-adapted spelling of `UseContext`, defined for completeness of the `With…` family. +The `WithProvider`-adapted spelling of `UseContext`: answer a named type or getter component from the +context's own generic `HasType` or `HasField` entry. ## Overview `WithContext` is the alias `WithProvider`. It pairs the [`WithProvider`](with_provider.md) -adapter with [`UseContext`](use_context.md) on a **context**, the type a method runs on. -[`UseContext`](use_context.md) carries a foundational [`FieldGetter`](../traits/field-access/field_getter.md), and -[`WithProvider`](with_provider.md) adapts a foundational provider into a named component's provider, so -`WithContext` is the two composed. Like every CGP provider, it carries no runtime value. - -`WithContext` is distinct from the bare [`UseContext`](use_context.md), and the two play different -roles. `UseContext` implements a component's provider trait *directly* by routing back to the context's -consumer trait, which is how it serves as a [higher-order provider](/docs/reference/glossary#higher-order-provider)'s default inner provider. `WithContext` -instead wraps `UseContext` in the [`WithProvider`](with_provider.md) adapter. It is the least-used member -of the `With…` family: the library defines it for completeness, and the common ways to serve a component -from the context's own state are the constructs named below rather than this alias. +adapter with [`UseContext`](use_context.md), which implements the two foundational traits by asking +the [**context**](/docs/reference/glossary#context), the type the implementation runs against: +[`TypeProvider`](../components/has_type.md) through the context's own `HasType`, and +[`FieldGetter`](../traits/field-access/field_getter.md) through its own `HasField`. +`WithProvider` passes the component's marker as that tag, so wiring a component to `WithContext` +answers it from the context's `HasType` or `HasField` entry keyed by the component itself. Like every +CGP provider, it carries no runtime value. + +`WithContext` is distinct from the bare [`UseContext`](use_context.md), and the two are not +interchangeable. `UseContext` implements a component's provider trait *directly*, by calling the +context's consumer trait for that same component, which is how it serves as a +[higher-order provider](/docs/reference/glossary#higher-order-provider)'s default inner provider and +why wiring a component to it loops. `WithContext` goes through the foundational traits instead, so it +reaches a *different* entry: the generic `HasType` or `HasField` table the context already has. It is +the least-used member of the `With…` family. ## Usage -`WithContext` is in the prelude, so `use cgp::prelude::*;` is enough. It takes no type parameter. It is -the alias `WithProvider`, so it appears wherever `WithProvider` would, adapting -`UseContext`'s foundational implementation into a named component's provider. +`WithContext` is in the prelude, so `use cgp::prelude::*;` is enough. It takes no type parameter and +appears as the value of a type component's or single-method getter's wiring entry: -For the everyday needs it is adjacent to, reach for one of these instead, all of which the codebase -exercises directly: +```rust +delegate_components! { + App { + TypeProviderComponent: UseType, + NameTypeProviderComponent: WithContext, + } +} +``` -- an [`#[implicit]`](../attributes/implicit.md) argument, where a provider simply needs a value from its - own context; -- [`UseFields`](use_fields.md) on a getter component, to read same-named fields; -- the bare [`UseContext`](use_context.md), as a higher-order provider's default inner provider. +What the entry needs from the context depends on the component's kind: + +- **A [`#[cgp_type]`](../macros/cgp_type.md) component**, such as `HasNameType`, resolves its type + through the context's `HasType`. The built-in `TypeProviderComponent`, + imported from `cgp::core::types`, is the usual way to supply it; wired to `UseType`, it + answers every tag with `String`. +- **A single-method [`#[cgp_getter]`](../macros/cgp_getter.md) component**, such as `HasName`, reads + the context's `HasField` entry. No derive generates a `HasField` impl keyed by a + component marker, so the context implements it by hand. + +## Examples + +A context supplies one type for every tag through the built-in `HasType`, and routes a named type +component to that answer with `WithContext`: + +```rust +use core::marker::PhantomData; +use cgp::prelude::*; +use cgp::core::types::TypeProviderComponent; + +#[cgp_type] +pub trait HasNameType { + type Name; +} + +pub struct App; + +delegate_components! { + App { + TypeProviderComponent: UseType, + NameTypeProviderComponent: WithContext, + } +} + +check_components! { + App { + NameTypeProviderComponent, + } +} + +pub fn name_type(name: PhantomData<::Name>) -> PhantomData { + name +} +``` + +`App` resolves `HasNameType::Name` by asking its own `HasType`, which the +`TypeProviderComponent: UseType` entry answers with `String`, so `name_type` compiles only +because `Name` is `String`. `App` is an +[environmental context](/docs/reference/glossary#environmental-context) with no fields. ## When to use it -**Reach for the constructs above rather than `WithContext` in practice.** The value it wraps is reached -more directly through [`UseContext`](use_context.md), [`UseFields`](use_fields.md), or an -[`#[implicit]`](../attributes/implicit.md) argument. +**Reach for `WithContext` when a context already answers a generic `HasType` or `HasField` lookup and +a named component should take that answer.** That is a narrow arrangement, so the adjacent constructs +usually fit better: + +- [`UseType`](use_type.md) on the named type component, to fix its type directly; +- [`UseFields`](use_fields.md) or [`UseField`](use_field.md) on a getter component, to read a named + field; +- an [`#[implicit]`](../attributes/implicit.md) argument, where a provider needs a value from its own + context; +- the bare [`UseContext`](use_context.md), as a higher-order provider's default inner provider. ## Under the hood @@ -50,31 +114,52 @@ more directly through [`UseContext`](use_context.md), [`UseFields`](use_fields.m pub type WithContext = WithProvider; ``` -The [`WithProvider`](with_provider.md) adapter forwards a component's provider-trait method to the inner -provider's foundational method, and [`UseContext`](use_context.md) supplies that foundational method, -its [`FieldGetter`](../traits/field-access/field_getter.md) reading the context's `HasField`. The generated -`WithProvider` impl that makes this work is shown on the [`WithProvider`](with_provider.md) page. +The [`WithProvider`](with_provider.md) impl that `#[cgp_type]` generates bounds its inner provider by +`TypeProvider<__Context__, NameTypeProviderComponent>`, and the one `#[cgp_getter]` generates bounds it +by `FieldGetter<__Context__, NameGetterComponent>`. `UseContext` implements both by asking the +context, the first through the `UseContext` impl `#[cgp_component]` generates for `HasType` and the +second through a hand-written impl beside `FieldGetter`: + +```rust +impl FieldGetter for UseContext +where + Context: HasField, +{ + type Value = Field; + + fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value { + context.get_field(PhantomData) + } +} +``` + +With the component's marker as `Tag`, the lookups are `Context: HasType` +and `Context: HasField`. ## Related constructs - [`WithProvider`](with_provider.md) — the adapter this alias specializes. - [`UseContext`](use_context.md) — the inner provider it wraps, whose direct form serves as a higher-order provider's inner default. +- [`HasType` / `TypeProvider`](../components/has_type.md) — the generic type lookup a type component + reaches through it. +- [`FieldGetter`](../traits/field-access/field_getter.md) and + [`HasField`](../traits/field-access/has_field.md) — the field lookup a getter component reaches + through it. - [`WithField`](with_field.md), [`WithType`](with_type.md) — the sibling aliases for a specific field or concrete type. -- [`UseFields`](use_fields.md) — reads same-named fields on a getter component, one of the direct forms - to prefer. -- [`FieldGetter`](../traits/field-access/field_getter.md) — the foundational getter `UseContext` supplies here. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) — the two-way split - `UseContext` bridges. +- [Abstract types](/docs/concepts/abstract-types) — the tag-indexed `HasType` component this routes a + named type component through. ## Source - The alias: [`use_context.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/providers/use_context.rs) +- `UseContext`'s `FieldGetter` impl: + [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs) --- diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md index df30a9cc..af55c7d1 100644 --- a/docs/reference/providers/with_delegated_type.md +++ b/docs/reference/providers/with_delegated_type.md @@ -1,4 +1,6 @@ --- +title: 'WithDelegatedType — types from a shared table' +description: 'The alias WithProvider>: several #[cgp_type] components answered from one table keyed by their component markers.' sidebar_label: 'WithDelegatedType' sidebar_position: 6.5 --- @@ -10,14 +12,14 @@ Resolve one or more abstract-type components from a shared table, through the `W ## Overview `WithDelegatedType` is the alias `WithProvider>`. It answers a -context's abstract-type components by looking each type tag up in the `Components` table, on a -**context**, the type that implements the trait, by adapting the foundational +context's abstract-type components by looking each type tag up in the `Components` table, on a [**context**](/docs/reference/glossary#context), the type that implements the trait, by adapting the foundational [`UseDelegatedType`](use_delegated_type.md) provider through the [`WithProvider`](with_provider.md) layer. Like every CGP provider, it carries no runtime value. -Unlike [`WithType`](with_type.md), this alias is not an alternative to a directly-wireable provider: the -bare [`UseDelegatedType`](use_delegated_type.md) supplies only the foundational -[`TypeProvider`](../components/has_type.md), so `WithDelegatedType` is the form you wire. +Unlike [`WithType`](with_type.md), this alias is not an alternative to a directly-wireable provider +on a `#[cgp_type]` component: the bare [`UseDelegatedType`](use_delegated_type.md) supplies only the +foundational [`TypeProvider`](../components/has_type.md), so `WithDelegatedType` is the form you wire +there. The bare form serves only the built-in `TypeProviderComponent`, as its page shows. ## Usage @@ -38,9 +40,11 @@ delegate_components! { } ``` -The `Components` parameter is a type that maps each type tag to a concrete type, built as an ordinary -[`delegate_components!`](../macros/delegate_components.md) table. Any tag the table has no entry for is -unresolved, and the context does not implement `HasType` for it. +The `Components` parameter is a type that maps each component marker to a concrete type, built as an +ordinary [`delegate_components!`](../macros/delegate_components.md) table. The key is the marker +because the `WithProvider` impl `#[cgp_type]` generates asks its inner provider for +`TypeProvider`. A component the table has no entry for is +unresolved, and the context does not implement that abstract type. ## Examples @@ -75,7 +79,14 @@ delegate_components! { [ ScalarTypeProviderComponent, IndexTypeProviderComponent, - ]: WithDelegatedType, + ]: WithDelegatedType, + } +} + +check_components! { + App { + ScalarTypeProviderComponent, + IndexTypeProviderComponent, } } ``` diff --git a/docs/reference/providers/with_field.md b/docs/reference/providers/with_field.md index 4a60f2a3..255fe209 100644 --- a/docs/reference/providers/with_field.md +++ b/docs/reference/providers/with_field.md @@ -1,4 +1,6 @@ --- +title: 'WithField — read a field through WithProvider' +description: 'The alias WithProvider>: a single-method getter reads the field Tag names, and a #[cgp_type] component takes that field''s type.' sidebar_label: 'WithField' sidebar_position: 6.3 --- @@ -10,10 +12,11 @@ Wire a getter component to a named context field, through the `WithProvider` ada ## Overview `WithField` is the alias `WithProvider>`. It implements a getter component by reading -the context field named by `Tag`, on a **context**, the type a method runs on, by adapting the +the context field named by `Tag`, on a [**context**](/docs/reference/glossary#context), the type the method runs on, by adapting the foundational [`UseField`](use_field.md) getter through the [`WithProvider`](with_provider.md) layer. -It reads the same field the plain [`UseField`](use_field.md) provider does, and both are interchangeable -in wiring. Like every CGP provider, it carries no runtime value. +On a getter it reads the same field the plain [`UseField`](use_field.md) provider does, and the two +are interchangeable there. On a [`#[cgp_type]`](../macros/cgp_type.md) component only `WithField` +works, and it sets the abstract type to the field's type. Like every CGP provider, it carries no runtime value. ## Usage @@ -54,20 +57,55 @@ pub struct Person { delegate_components! { Person { - NameGetterComponent: WithField, + NameGetterComponent: WithField, + } +} + +check_components! { + Person { + NameGetterComponent, } } + +pub fn demo() { + let person = Person { first_name: "Alice".to_owned() }; + assert_eq!(person.name(), "Alice"); +} ``` `WithField` expands to `WithProvider>`, so `person.name()` reads the `first_name` field. The field name lives in the wiring, not in the trait. +The same alias gives a type component a field's type, which the plain `UseField` cannot: + +```rust +#[cgp_type] +pub trait HasWidthType { + type Width; +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f32, +} + +delegate_components! { + Rectangle { + WidthTypeProviderComponent: WithField, + } +} +``` + +`Rectangle`'s `Width` is `f32`, the type of its `width` field. `#[cgp_type]` generates a +`WithProvider` impl but no `UseField` impl, so `WidthTypeProviderComponent: UseField` +fails with `E0277`, while `UseField`'s own `TypeProvider` impl serves it through `WithField`. + ## When to use it -**Prefer the plain [`UseField`](use_field.md) form.** It reads the same field and is the value a -[`#[cgp_getter]`](../macros/cgp_getter.md) component is normally wired to. `WithField` exists for the -case where a component is reached only through the [`WithProvider`](with_provider.md) adapter, and it -reads as a single wiring choice where spelling out `WithProvider>` would not. +**Prefer the plain [`UseField`](use_field.md) form on a getter.** It reads the same field and is +the value a [`#[cgp_getter]`](../macros/cgp_getter.md) component is normally wired to. **Reach for +`WithField` on a `#[cgp_type]` component** that should take a field's type, since only the +[`WithProvider`](with_provider.md) route reaches `UseField` there. For the common case of reading a field, an [`#[implicit]`](../attributes/implicit.md) argument is simpler than any getter provider. For a stored type that borrows to the getter's return type through diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md index a045d8af..3d156da2 100644 --- a/docs/reference/providers/with_field_ref.md +++ b/docs/reference/providers/with_field_ref.md @@ -1,4 +1,6 @@ --- +title: 'WithFieldRef — borrow a field through AsRef' +description: 'The alias WithProvider>: a getter returning &Value reads a field whose stored type implements AsRef.' sidebar_label: 'WithFieldRef' sidebar_position: 6.4 --- @@ -10,8 +12,7 @@ Wire a getter component to a field borrowed through `AsRef`, through the `WithPr ## Overview `WithFieldRef` is the alias `WithProvider>`. It implements a getter -component by reading the field named by `Tag` from the **context**, the type a method runs on, -and borrowing it through `AsRef` to produce a `&Value`, where the stored field type implements +component by reading the field named by `Tag` from the [**context**](/docs/reference/glossary#context), the type the method runs on, and borrowing it through `AsRef` to produce a `&Value`, where the stored field type implements `AsRef`. It adapts the foundational [`UseFieldRef`](use_field_ref.md) getter through the [`WithProvider`](with_provider.md) layer. Like every CGP provider, it carries no runtime value. @@ -71,9 +72,20 @@ pub struct App { delegate_components! { App { - ConfigGetterComponent: WithFieldRef, + ConfigGetterComponent: WithFieldRef, } } + +check_components! { + App { + ConfigGetterComponent, + } +} + +pub fn demo() { + let app = App { config: StoredConfig(Config { port: 8080 }) }; + assert_eq!(app.config().port, 8080); +} ``` `App` wires `ConfigGetterComponent` to `WithFieldRef`. The provider reads the @@ -86,9 +98,10 @@ delegate_components! { borrows as `T` through `AsRef`.** The stored type and the exposed type differ, and neither the plain [`WithField`](with_field.md) nor an [`#[implicit]`](../attributes/implicit.md) argument can bridge them. -For the common borrowed-view getters — a `-> &str` getter over a `String` field, a `-> &[u8]` getter -over a `Vec` field — the plain [`UseField`](use_field.md) or [`WithField`](with_field.md) already -borrows for you through the return-type shorthands, so no `WithFieldRef` is needed. For a field returned +The common borrowed-view getters need no `WithFieldRef`: a `-> &str` getter over a `String` field, a +`-> &[T]` getter over a field implementing `AsRef<[T]>` such as a `Vec`, and an `Option<&T>` getter +over an `Option` field are all served by the plain [`UseField`](use_field.md) or +[`WithField`](with_field.md) through the getter macros' return-type shorthands. For a field returned as its own type, an `#[implicit]` argument is simpler still. ## Under the hood diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 6553b3ca..4d3f90df 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -1,4 +1,6 @@ --- +title: 'WithProvider — adapt a foundational provider' +description: 'The adapter that turns a TypeProvider or FieldGetter into a named component''s provider, spelled in wiring through the With… aliases.' sidebar_label: 'WithProvider' sidebar_position: 6 --- @@ -15,7 +17,8 @@ specific named component. component-agnostic mechanisms: a `TypeProvider` supplies *some* [abstract type](/docs/reference/glossary#abstract-type) for *some* tag, and a `FieldGetter` reads *some* field for *some* output tag, without either knowing which named component it serves. A named component, by contrast, has a specific provider trait, such as `NameTypeProvider` or -`NameGetter`, that a **context** wires to, where the context is the type the method runs on. +`NameGetter`, that a [**context**](/docs/reference/glossary#context) wires to, where the context is the type the +implementation runs against. `WithProvider` is the adapter that lets a foundational provider stand in as the provider for one of those named components: it implements the component's provider trait by forwarding to the foundational provider's method. @@ -57,6 +60,7 @@ choice. Adapting the context's own field getter into a getter component uses `Wi ```rust use cgp::prelude::*; +use cgp::core::field::impls::WithField; #[cgp_getter] pub trait HasName { @@ -70,9 +74,20 @@ pub struct Person { delegate_components! { Person { - NameGetterComponent: WithField, + NameGetterComponent: WithField, } } + +check_components! { + Person { + NameGetterComponent, + } +} + +pub fn demo() { + let person = Person { first_name: "Ada".to_owned() }; + assert_eq!(person.name(), "Ada"); +} ``` `WithField` expands to `WithProvider>`, so @@ -85,11 +100,14 @@ the type through a table. ## When to use it -**Reach for one of the aliases, not `WithProvider` directly.** [`WithField`](with_field.md), -[`WithType`](with_type.md), and [`WithContext`](with_context.md) are interchangeable with the plain -providers they wrap: wiring a getter to `WithField` and to [`UseField`](use_field.md) both -read the same field, so prefer the plain provider ([`UseField`](use_field.md), [`UseType`](use_type.md)) -where it applies. [`WithFieldRef`](with_field_ref.md) and [`WithDelegatedType`](with_delegated_type.md) +**Reach for one of the aliases, not `WithProvider` directly.** [`WithType`](with_type.md) and +[`UseType`](use_type.md) are interchangeable on every `#[cgp_type]` component, and +[`WithField`](with_field.md) and [`UseField`](use_field.md) on every single-method getter, +so prefer the plain provider there. `WithField` is the form to wire when a `#[cgp_type]` component +should take a field's type, since such a component has no `UseField` impl. +[`WithContext`](with_context.md) is not interchangeable with [`UseContext`](use_context.md): wired to +a component, `UseContext` calls the context's own consumer trait for that component, which loops, +while `WithContext` reads the context's `HasField` or `HasType` entry keyed by the component. [`WithFieldRef`](with_field_ref.md) and [`WithDelegatedType`](with_delegated_type.md) have no plain wireable form, because their inner providers are foundational, so you wire the alias. Each alias is documented on its own page, linked from the table above. @@ -130,16 +148,22 @@ where __Provider__: FieldGetter<__Context__, NameGetterComponent, Value = String>, { fn name(__context__: &__Context__) -> &str { - __Provider__::get_field(__context__, PhantomData::).as_str() + __Provider__::get_field(__context__, ::core::marker::PhantomData::) + .as_str() } } ``` +A `&mut self` getter bounds the inner provider by `MutFieldGetter` instead, and a slice getter bounds +the value by `AsRef<[T]> + 'static` rather than fixing it. + In both cases the bound names the foundational trait, keyed by the [component marker](/docs/reference/glossary#component-marker), and the method or associated type forwards to it. `#[cgp_getter]` generates the `WithProvider` impl only when the getter has exactly one method, since a single foundational getter cannot serve several methods at once. Each impl is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl. +The struct itself is a plain marker, +`pub struct WithProvider(pub PhantomData);`, with no implementations of its own. The aliases specialize `WithProvider` to a fixed inner provider so the common cases need no `WithProvider<...>` spelled out. Each has its own page: [`WithContext`](with_context.md), [`WithType`](with_type.md), [`WithField`](with_field.md), [`WithFieldRef`](with_field_ref.md), and diff --git a/docs/reference/providers/with_type.md b/docs/reference/providers/with_type.md index bdb3beb6..f59ba5e4 100644 --- a/docs/reference/providers/with_type.md +++ b/docs/reference/providers/with_type.md @@ -1,4 +1,6 @@ --- +title: 'WithType — fix a type through WithProvider' +description: 'The alias WithProvider>, which binds an abstract-type component to a concrete type exactly as the plain UseType does.' sidebar_label: 'WithType' sidebar_position: 6.2 --- @@ -10,7 +12,8 @@ Bind an abstract-type component to a concrete type, through the `WithProvider` a ## Overview `WithType` is the alias `WithProvider>`. It binds an abstract-type component to the -concrete `Type` on a **context**, the type that implements the trait, by adapting the foundational +concrete `Type` on a [**context**](/docs/reference/glossary#context), the type that implements the +trait, by adapting the foundational [`UseType`](use_type.md) provider through the [`WithProvider`](with_provider.md) layer. It sets the same [abstract type](/docs/reference/glossary#abstract-type) the plain [`UseType`](use_type.md) provider does, and both are interchangeable in wiring. Like every CGP provider, it carries no runtime value. @@ -49,21 +52,28 @@ pub struct App; delegate_components! { App { - ScalarTypeProviderComponent: WithType, + ScalarTypeProviderComponent: WithType, + } +} + +check_components! { + App { + ScalarTypeProviderComponent, } } ``` `App` wires `ScalarTypeProviderComponent` to `WithType`, so `App` implements `HasScalarType` with -`Scalar = f64`. The `Copy` bound on the associated type is checked against `f64` where the wiring is -written. +`Scalar = f64`. The check confirms that `f64` meets the `Copy` bound on the associated type; without +it, a type that breaks the bound is reported only when the component is used, as +[`UseType`](use_type.md#common-mistakes) shows. ## When to use it **Prefer the plain [`UseType`](use_type.md) form.** It binds the same type and is the idiomatic -value for a [`#[cgp_type]`](../macros/cgp_type.md) component's wiring entry. `WithType` exists for the -case where a component is reached only through the [`WithProvider`](with_provider.md) adapter, and it -reads as a single wiring choice where spelling out `WithProvider>` would not. +value for a [`#[cgp_type]`](../macros/cgp_type.md) component's wiring entry. The two are equivalent on every `#[cgp_type]` component, because the macro generates both a `UseType` +impl and a [`WithProvider`](with_provider.md) impl; `WithType` completes the `With…` family and reads +as a single wiring choice where spelling out `WithProvider>` would not. For an abstract type resolved through a table rather than fixed to one concrete type, use [`WithDelegatedType`](with_delegated_type.md). diff --git a/example-code/tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.rs b/example-code/tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.rs new file mode 100644 index 00000000..79b06a28 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.rs @@ -0,0 +1,26 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +#[prefix(@app in DefaultNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "hello".into() + } +} + +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + GreeterComponent: GreetHello, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.stderr b/example-code/tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.stderr new file mode 100644 index 00000000..70f7ae50 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.stderr @@ -0,0 +1,19 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` + --> tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.rs:22:9 + | +20 | namespace DefaultNamespace; + | ---------------- first implementation here +21 | +22 | GreeterComponent: GreetHello, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `App` + | + = note: downstream crates may implement trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::RedirectLookup>>>, cgp::prelude::PathCons>>` + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` + --> tests/compile_fail/reference/providers/redirect_lookup_common_mistakes_bare_key.rs:22:9 + | +20 | namespace DefaultNamespace; + | ---------------- first implementation here +21 | +22 | GreeterComponent: GreetHello, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs b/example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs new file mode 100644 index 00000000..b25fe36c --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs @@ -0,0 +1,24 @@ +use cgp::prelude::*; + +#[cgp_component(Encoder)] +pub trait CanEncode { + fn encode(&self, value: &Value) -> Vec; +} + +pub struct App; + +delegate_components! { + App { + open EncoderComponent; + + @EncoderComponent.u32: UseContext, + } +} + +check_components! { + App { + EncoderComponent: u32, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.stderr b/example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.stderr new file mode 100644 index 00000000..3f1e75d7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.stderr @@ -0,0 +1,40 @@ +error[E0275]: overflow evaluating the requirement `App: IsProviderFor` + --> tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs:20:9 + | +20 | EncoderComponent: u32, + | ^^^^^^^^^^^^^^^^ + | +note: required for `App` to implement `Encoder` + --> tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs:3:1 + | + 3 | #[cgp_component(Encoder)] + | _^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 | | pub trait CanEncode { + | |__________________________^ +note: required for `App` to implement `CanEncode` + --> tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs:3:1 + | + 3 | #[cgp_component(Encoder)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 | pub trait CanEncode { + | ^^^^^^^^^^^^^^^^ +note: required for `cgp::prelude::UseContext` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs:3:1 + | + 3 | #[cgp_component(Encoder)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 | pub trait CanEncode { + | ---------------- unsatisfied trait bound introduced here + = note: 1 redundant requirement hidden + = note: required for `RedirectLookup>` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/use_context_common_mistakes_self_cycle.rs:18:1 + | +18 | / check_components! { +19 | | App { +20 | | EncoderComponent: u32, +21 | | } +22 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_component` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs b/example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs new file mode 100644 index 00000000..e848b1ae --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs @@ -0,0 +1,22 @@ +use cgp::core::component::UseDefault; +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str { + "John" + } +} + +#[cgp_component(Greeter)] +#[extend(HasName)] +pub trait CanGreet { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } +} + +#[cgp_impl(UseDefault)] +impl Greeter {} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.stderr b/example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.stderr new file mode 100644 index 00000000..0e8a8a74 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.stderr @@ -0,0 +1,53 @@ +error[E0277]: the trait bound `__Context__: HasName` is not satisfied + --> tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs:19:1 + | +19 | #[cgp_impl(UseDefault)] + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `DelegateComponent` is not implemented for `__Context__` + | +note: required for `__Context__` to implement `NameGetter<__Context__>` + --> tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs:4:1 + | + 4 | #[cgp_getter] + | ^^^^^^^^^^^^^ +note: required for `__Context__` to implement `HasName` + --> tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs:4:1 + | + 4 | #[cgp_getter] + | ^^^^^^^^^^^^^ + 5 | pub trait HasName { + | ^^^^^^^ +note: required by a bound in `Greeter` + --> tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs:12:10 + | +11 | #[cgp_component(Greeter)] + | ------- required by a bound in this trait +12 | #[extend(HasName)] + | ^^^^^^^ required by this bound in `Greeter` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the attribute macro `cgp_getter` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `__Context__: HasName` is not satisfied + --> tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs:19:1 + | +19 | #[cgp_impl(UseDefault)] + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `IsProviderFor` is not implemented for `__Context__` + | +note: required for `__Context__` to implement `NameGetter<__Context__>` + --> tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs:4:1 + | + 4 | #[cgp_getter] + | ^^^^^^^^^^^^^ +note: required for `__Context__` to implement `HasName` + --> tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs:4:1 + | + 4 | #[cgp_getter] + | ^^^^^^^^^^^^^ + 5 | pub trait HasName { + | ^^^^^^^ +note: required by a bound in `Greeter` + --> tests/compile_fail/reference/providers/use_default_common_mistakes_missing_uses.rs:12:10 + | +11 | #[cgp_component(Greeter)] + | ------- required by a bound in this trait +12 | #[extend(HasName)] + | ^^^^^^^ required by this bound in `Greeter` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the attribute macro `cgp_getter` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.rs b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.rs new file mode 100644 index 00000000..c8141be6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.rs @@ -0,0 +1,27 @@ +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasFooBar { + fn foo(&self) -> &str; + fn bar(&self) -> &u8; +} + +#[derive(HasField)] +pub struct App { + pub foo: String, + pub bar: u8, +} + +delegate_components! { + App { + FooBarGetterComponent: UseField, + } +} + +check_components! { + App { + FooBarGetterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr new file mode 100644 index 00000000..46d516c4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr @@ -0,0 +1,47 @@ +error[E0277]: the trait bound `cgp::prelude::UseField>>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.rs:23:9 + | +23 | FooBarGetterComponent, + | ^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `cgp::prelude::UseField>>>>` +help: the following other types implement trait `IsProviderFor` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + | +31 | / impl AsyncComputer for UseField +32 | | where +33 | | Context: HasField, +34 | | Context::Value: CanComputeAsync, + | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_field.rs:69:1 + | +69 | / impl IsProviderFor +70 | | for UseField +71 | | where +72 | | Context: HasField, + | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/computer.rs:29:1 + | +29 | / impl Computer for UseField +30 | | where +31 | | Context: HasField, +32 | | Context::Value: CanCompute, + | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + | + 5 | #[cgp_getter] + | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.rs:21:1 + | +21 | / check_components! { +22 | | App { +23 | | FooBarGetterComponent, +24 | | } +25 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.rs b/example-code/tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.rs new file mode 100644 index 00000000..8c50876a --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.rs @@ -0,0 +1,22 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar: Copy; +} + +pub struct App; + +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + } +} + +check_components! { + App { + ScalarTypeProviderComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.stderr b/example-code/tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.stderr new file mode 100644 index 00000000..4598309d --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.stderr @@ -0,0 +1,25 @@ +error[E0277]: the trait bound `String: Copy` is not satisfied + --> tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.rs:18:9 + | +18 | ScalarTypeProviderComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` + | +note: required for `cgp::prelude::UseType` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.rs:3:1 + | + 3 | #[cgp_type] + | ^^^^^^^^^^^ + 4 | pub trait HasScalarType { + 5 | type Scalar: Copy; + | ---- unsatisfied trait bound introduced here + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/use_type_common_mistakes_unchecked_bound.rs:16:1 + | +16 | / check_components! { +17 | | App { +18 | | ScalarTypeProviderComponent, +19 | | } +20 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_type` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/providers/chain_getters.rs b/example-code/tests/reference/providers/chain_getters.rs index e74e9459..93e90bc0 100644 --- a/example-code/tests/reference/providers/chain_getters.rs +++ b/example-code/tests/reference/providers/chain_getters.rs @@ -40,13 +40,13 @@ pub mod examples { } } - #[test] - fn test_chain_getters_reaches_nested_field() { - let app = App { - config: Config { - name: "test".to_owned(), - }, - }; + pub fn demo() { + let app = App { config: Config { name: "test".to_owned() } }; assert_eq!(app.name(), "test"); } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/providers/mod.rs b/example-code/tests/reference/providers/mod.rs index b613a799..3ef4195f 100644 --- a/example-code/tests/reference/providers/mod.rs +++ b/example-code/tests/reference/providers/mod.rs @@ -12,9 +12,11 @@ pub mod redirect_lookup; pub mod use_context; pub mod use_default; pub mod use_delegate; +pub mod use_delegated_type; pub mod use_field; pub mod use_fields; pub mod use_type; +pub mod with_context; pub mod with_delegated_type; pub mod with_field; pub mod with_field_ref; diff --git a/example-code/tests/reference/providers/redirect_lookup.rs b/example-code/tests/reference/providers/redirect_lookup.rs index a83f89db..597c3e0c 100644 --- a/example-code/tests/reference/providers/redirect_lookup.rs +++ b/example-code/tests/reference/providers/redirect_lookup.rs @@ -1,21 +1,65 @@ //! Code from `docs/reference/providers/redirect_lookup.md` — *`RedirectLookup`*. //! -//! `RedirectLookup` is generated machinery, so the only user-writable code the page shows is the -//! namespace registration that produces the redirect entries. This pins that that registration -//! compiles. +//! `RedirectLookup` is generated machinery, so the code the page shows is the namespace registration +//! that produces a redirect, and the components whose generated impls Under the hood lists. The +//! bare-key entry from Common Mistakes is a trybuild fixture. /// ## Examples pub mod examples { use cgp::prelude::*; + #[cgp_component(Greeter)] + #[prefix(@app in DefaultNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "hello".into() + } + } + pub struct App; - pub struct TestProvider; delegate_components! { App { namespace DefaultNamespace; - @bar.baz: TestProvider, + @app.GreeterComponent: GreetHello, } } + + check_components! { + App { + GreeterComponent, + } + } + + pub fn demo() { + assert_eq!(App.greet(), "hello"); + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## Under the hood +/// +/// The components whose `RedirectLookup` impls the page lists, for `cargo cgp expand`. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } } diff --git a/example-code/tests/reference/providers/use_context.rs b/example-code/tests/reference/providers/use_context.rs index bcc93a4e..a00a9b85 100644 --- a/example-code/tests/reference/providers/use_context.rs +++ b/example-code/tests/reference/providers/use_context.rs @@ -3,7 +3,7 @@ //! Pins the default-inner-provider use: `EncodeVec` encodes a `Vec` by encoding each element through its //! inner provider, which defaults to `UseContext` so the elements route back to the context's own //! `CanEncode` wiring for their type. No cycle, because the element lookup is for a different type -//! (`u32`) than the wired one (`Vec`). +//! (`u32`) than the wired one (`Vec`). The self-cycle from Common Mistakes is a trybuild fixture. /// ## Examples pub mod examples { @@ -48,19 +48,31 @@ pub mod examples { } } - mod check_app { - use super::*; - check_components! { - App { - EncoderComponent: [u32, Vec], - } + check_components! { + App { + EncoderComponent: [u32, Vec], } } + pub fn demo() { + assert_eq!(App.encode(&vec![1u32, 2, 3]), b"123"); + } + #[test] fn test_use_context_default_inner() { // The `Vec` element encoding routes through `UseContext` to the `u32` encoder. - let flat = >>::encode(&App, &vec![1u32, 2, 3]); - assert_eq!(flat, b"123"); + demo(); + } +} + +/// ## Under the hood +/// +/// The component whose generated `UseContext` impl the page lists, for `cargo cgp expand`. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); } } diff --git a/example-code/tests/reference/providers/use_default.rs b/example-code/tests/reference/providers/use_default.rs index 41f4771a..20fa72f8 100644 --- a/example-code/tests/reference/providers/use_default.rs +++ b/example-code/tests/reference/providers/use_default.rs @@ -1,7 +1,45 @@ //! Code from `docs/reference/providers/use_default.md` — *`UseDefault`*. //! //! Pins that empty-body `#[cgp_impl(UseDefault)]` blocks make the trait's default method bodies the -//! implementation, and that both components can be delegated to `UseDefault` in one array entry. +//! implementation, and that both components can be delegated to `UseDefault` in one array entry. The +//! impl without `#[uses(HasName)]` from Common Mistakes is a trybuild fixture. + +/// ## Usage +/// +/// The two steps the section shows: an empty `#[cgp_impl(UseDefault)]` block, then the wiring entry. +pub mod usage { + use cgp::core::component::UseDefault; + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + #[cgp_impl(UseDefault)] + impl Greeter {} + + pub struct App; + + delegate_components! { + App { + GreeterComponent: UseDefault, + } + } + + check_components! { + App { + GreeterComponent, + } + } + + #[test] + fn the_default_body_answers() { + assert_eq!(App.greet(), "Hello!"); + } +} /// ## Examples pub mod examples { @@ -16,7 +54,8 @@ pub mod examples { } #[cgp_component(Greeter)] - pub trait CanGreet: HasName { + #[extend(HasName)] + pub trait CanGreet { fn greet(&self) -> String { format!("Hello, {}!", self.name()) } @@ -48,9 +87,12 @@ pub mod examples { } } + pub fn demo() { + assert_eq!(App.greet(), "Hello, John!"); + } + #[test] - fn test_use_default() { - let app = App; - assert_eq!(app.greet(), "Hello, John!"); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/use_delegate.rs b/example-code/tests/reference/providers/use_delegate.rs index a54f86cf..260d7b56 100644 --- a/example-code/tests/reference/providers/use_delegate.rs +++ b/example-code/tests/reference/providers/use_delegate.rs @@ -73,15 +73,12 @@ pub mod examples { } } + pub fn demo() { + assert_eq!(MyApp.area(&Rectangle { width: 2.0, height: 3.0 }), 6.0); + } + #[test] - fn test_use_delegate_dispatch() { - let app = MyApp; - assert_eq!( - app.area(&Rectangle { - width: 2.0, - height: 3.0 - }), - 6.0 - ); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/use_delegated_type.rs b/example-code/tests/reference/providers/use_delegated_type.rs new file mode 100644 index 00000000..4594aee1 --- /dev/null +++ b/example-code/tests/reference/providers/use_delegated_type.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/providers/use_delegated_type.md` — *`UseDelegatedType`*. +//! +//! Pins the direct form the page's Usage section shows: the built-in `TypeProviderComponent` wired to +//! `UseDelegatedType`, so `HasType` looks each tag up in a table of types. The alias form lives in +//! `with_delegated_type.rs`. + +/// ## Usage +pub mod usage { + use core::marker::PhantomData; + + use cgp::core::types::{TypeProviderComponent, UseDelegatedType}; + use cgp::prelude::*; + + pub struct ScalarTag; + pub struct IndexTag; + + pub struct AppTypes; + + delegate_components! { + AppTypes { + ScalarTag: f64, + IndexTag: usize, + } + } + + pub struct App; + + delegate_components! { + App { + TypeProviderComponent: UseDelegatedType, + } + } + + pub fn types( + scalar: PhantomData<>::Type>, + index: PhantomData<>::Type>, + ) -> (PhantomData, PhantomData) { + (scalar, index) + } +} diff --git a/example-code/tests/reference/providers/use_field.rs b/example-code/tests/reference/providers/use_field.rs index e9135b83..b235223b 100644 --- a/example-code/tests/reference/providers/use_field.rs +++ b/example-code/tests/reference/providers/use_field.rs @@ -1,7 +1,9 @@ //! Code from `docs/reference/providers/use_field.md` — *`UseField`*. //! //! Pins the decoupling the page is about: a getter method `name` reads a `first_name` field through -//! `UseField`. The `WithField` alias is covered by `with_field.rs`. +//! `UseField`, the borrowed-view getter from When to use it, and the listings' inputs and +//! type-provider forms from Under the hood. The multi-method getter from Common Mistakes is a +//! trybuild fixture; the `WithField` alias is covered by `with_field.rs`. /// ## Examples pub mod examples { @@ -29,17 +31,100 @@ pub mod examples { } } - // The page's `greet` fn. - fn greet(person: &Person) { - println!("Hello, {}!", person.name()); // reads the first_name field + pub fn demo() { + let person = Person { first_name: "Alice".to_owned() }; + assert_eq!(person.name(), "Alice"); // reads the first_name field } #[test] - fn test_use_field_reads_first_name() { - let person = Person { - first_name: "Alice".to_owned(), - }; - assert_eq!(person.name(), "Alice"); - greet(&person); + fn test_demo() { + demo(); + } +} + +/// ## When to use it +/// +/// The borrowed-view getters `UseField` already handles: `-> &[u8]` over a `Vec` field. +pub mod when_to_use_it { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasPayload { + fn payload(&self) -> &[u8]; + } + + #[derive(HasField)] + pub struct Message { + pub body: Vec, + } + + delegate_components! { + Message { + PayloadGetterComponent: UseField, + } + } + + check_components! { + Message { + PayloadGetterComponent, + } + } + + #[test] + fn a_slice_getter_reads_a_vec_field() { + let message = Message { body: vec![1, 2, 3] }; + assert_eq!(message.payload(), &[1, 2, 3]); + } +} + +/// ## Under the hood +/// +/// The getter whose generated `UseField` impl the page lists, for `cargo cgp expand`. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + /// `UseField`'s `TypeProvider` impl: the built-in `TypeProviderComponent` takes it directly, and a + /// `#[cgp_type]` component takes it through `WithField`. + pub mod type_provider { + use core::marker::PhantomData; + + use cgp::core::field::impls::WithField; + use cgp::core::types::TypeProviderComponent; + use cgp::prelude::*; + + #[cgp_type] + pub trait HasWidthType { + type Width; + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f32, + } + + delegate_components! { + Rectangle { + TypeProviderComponent: UseField, + WidthTypeProviderComponent: WithField, + } + } + + check_components! { + Rectangle { + WidthTypeProviderComponent, + } + } + + pub fn assert_width_types( + built_in: PhantomData<>::Type>, + named: PhantomData<::Width>, + ) -> (PhantomData, PhantomData) { + (built_in, named) + } } } diff --git a/example-code/tests/reference/providers/use_fields.rs b/example-code/tests/reference/providers/use_fields.rs index 24206164..452bae8c 100644 --- a/example-code/tests/reference/providers/use_fields.rs +++ b/example-code/tests/reference/providers/use_fields.rs @@ -1,10 +1,10 @@ //! Code from `docs/reference/providers/use_fields.md` — *`UseFields`*. //! -//! Pins the method-name-equals-field-name convention: wiring a getter to `UseFields` reads the -//! same-named context field. +//! Pins the method-name-equals-field-name convention: the one-method wiring the Usage section shows, +//! and the two-method getter from Examples, whose `UseFields` impl is the listing in Under the hood. -/// ## Examples -pub mod examples { +/// ## Usage +pub mod usage { use cgp::prelude::*; #[cgp_getter] @@ -29,15 +29,50 @@ pub mod examples { } } - fn describe(app: &App) -> &str { - app.foo() // reads the `foo` field + #[test] + fn the_method_reads_the_same_named_field() { + let app = App { foo: "hi".to_owned() }; + assert_eq!(app.foo(), "hi"); + } +} + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasFooBar { + fn foo(&self) -> &str; + fn bar(&self) -> &u8; + } + + #[derive(HasField)] + pub struct App { + pub foo: String, + pub bar: u8, + } + + delegate_components! { + App { + FooBarGetterComponent: UseFields, + } + } + + check_components! { + App { + FooBarGetterComponent, + } + } + + pub fn demo() { + let app = App { foo: "hi".to_owned(), bar: 7 }; + + assert_eq!(app.foo(), "hi"); // reads the `foo` field + assert_eq!(*app.bar(), 7); // reads the `bar` field } #[test] - fn test_use_fields_reads_same_named_field() { - let app = App { - foo: "hi".to_owned(), - }; - assert_eq!(describe(&app), "hi"); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/use_type.rs b/example-code/tests/reference/providers/use_type.rs index eaa87755..4a15ed3e 100644 --- a/example-code/tests/reference/providers/use_type.rs +++ b/example-code/tests/reference/providers/use_type.rs @@ -1,7 +1,8 @@ //! Code from `docs/reference/providers/use_type.md` — *`UseType` (provider)*. //! //! Pins that wiring an abstract-type component to `UseType` sets the context's abstract type to -//! `f64` and enforces the `Copy` bound at the wiring site. The `WithType` alias is covered by +//! `f64`, read back through generic code, and that the check enforces the `Copy` bound. The unchecked +//! `UseType` from Common Mistakes is a trybuild fixture; the `WithType` alias is covered by //! `with_type.rs`. /// ## Examples @@ -26,4 +27,34 @@ pub mod examples { ScalarTypeProviderComponent, } } + + pub fn zero() -> Context::Scalar + where + Context: HasScalarType, + Context::Scalar: Default, + { + Default::default() + } + + pub fn demo() { + let scalar: f64 = zero::(); + assert_eq!(scalar, 0.0); + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## Under the hood +/// +/// The abstract type whose generated `UseType` impl the page lists, for `cargo cgp expand`. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Copy; + } } diff --git a/example-code/tests/reference/providers/with_context.rs b/example-code/tests/reference/providers/with_context.rs new file mode 100644 index 00000000..5bbff314 --- /dev/null +++ b/example-code/tests/reference/providers/with_context.rs @@ -0,0 +1,82 @@ +//! Code from `docs/reference/providers/with_context.md` — *`WithContext`*. +//! +//! Pins both forms the page's Usage section describes: a `#[cgp_type]` component resolved through the +//! context's own `HasType`, which is also the Examples program, and a single-method getter read +//! through a hand-written `HasField` impl keyed by the getter's marker. + +/// ## Usage +/// +/// The getter form: `WithContext` reads the context's `HasField` entry. +pub mod usage { + use core::marker::PhantomData; + + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + pub struct Person { + pub first_name: String, + } + + // No derive keys a field by a component marker, so the context implements it by hand. + impl HasField for Person { + type Value = String; + + fn get_field(&self, _tag: PhantomData) -> &String { + &self.first_name + } + } + + delegate_components! { + Person { + NameGetterComponent: WithContext, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + + #[test] + fn the_getter_reads_the_marker_keyed_field() { + let person = Person { first_name: "Ada".to_owned() }; + assert_eq!(person.name(), "Ada"); + } +} + +/// ## Examples +pub mod examples { + use core::marker::PhantomData; + + use cgp::core::types::TypeProviderComponent; + use cgp::prelude::*; + + #[cgp_type] + pub trait HasNameType { + type Name; + } + + pub struct App; + + delegate_components! { + App { + TypeProviderComponent: UseType, + NameTypeProviderComponent: WithContext, + } + } + + check_components! { + App { + NameTypeProviderComponent, + } + } + + pub fn name_type(name: PhantomData<::Name>) -> PhantomData { + name + } +} diff --git a/example-code/tests/reference/providers/with_field.rs b/example-code/tests/reference/providers/with_field.rs index b49a5403..1b7b00a3 100644 --- a/example-code/tests/reference/providers/with_field.rs +++ b/example-code/tests/reference/providers/with_field.rs @@ -1,7 +1,8 @@ //! Code from `docs/reference/providers/with_field.md` — *`WithField`*. //! //! Pins that the `WithField` alias wires a `name` getter to read the -//! `first_name` field, the same as the plain `UseField`. +//! `first_name` field, the same as the plain `UseField`, and gives a `#[cgp_type]` component a +//! field's type, which the plain `UseField` cannot. /// ## Examples pub mod examples { @@ -30,11 +31,47 @@ pub mod examples { } } - #[test] - fn test_with_field_reads_first_name() { - let person = Person { - first_name: "Alice".to_owned(), - }; + pub fn demo() { + let person = Person { first_name: "Alice".to_owned() }; assert_eq!(person.name(), "Alice"); } + + #[test] + fn test_demo() { + demo(); + } + + /// The type-component form: `WithField` gives a `#[cgp_type]` component a field's type. + pub mod type_component { + use core::marker::PhantomData; + + use cgp::core::field::impls::WithField; + use cgp::prelude::*; + + #[cgp_type] + pub trait HasWidthType { + type Width; + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f32, + } + + delegate_components! { + Rectangle { + WidthTypeProviderComponent: WithField, + } + } + + check_components! { + Rectangle { + WidthTypeProviderComponent, + } + } + + pub fn width_type(width: PhantomData<::Width>) -> PhantomData { + width + } + } } diff --git a/example-code/tests/reference/providers/with_field_ref.rs b/example-code/tests/reference/providers/with_field_ref.rs index ecdd7693..ffe38629 100644 --- a/example-code/tests/reference/providers/with_field_ref.rs +++ b/example-code/tests/reference/providers/with_field_ref.rs @@ -1,7 +1,8 @@ //! Code from `docs/reference/providers/with_field_ref.md` — *`WithFieldRef`*. //! //! `WithFieldRef` (`WithProvider>`) is the form that wires the foundational -//! `UseFieldRef` getter. This pins that a `-> &Config` getter reads a stored `AsRef` field. +//! `UseFieldRef` getter. This pins that a `-> &Config` getter reads a stored `AsRef` field, +//! and that the borrowed views When to use it names need only the plain `UseField`. /// ## Examples pub mod examples { @@ -44,11 +45,72 @@ pub mod examples { } } + pub fn demo() { + let app = App { config: StoredConfig(Config { port: 8080 }) }; + assert_eq!(app.config().port, 8080); + } + #[test] - fn test_with_field_ref_borrows_through_as_ref() { - let app = App { - config: StoredConfig(Config { port: 8080 }), + fn test_demo() { + demo(); + } +} + +/// ## When to use it +/// +/// The borrowed views the plain `UseField` already serves: `&[u8]` over `Vec`, and `Option<&T>` +/// and `Option<&str>` over `Option` and `Option`. +pub mod when_to_use_it { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasBody { + fn body(&self) -> &[u8]; + } + + #[cgp_getter] + pub trait HasNick { + fn nick(&self) -> Option<&str>; + } + + #[cgp_getter] + pub trait HasAge { + fn age(&self) -> Option<&u8>; + } + + #[derive(HasField)] + pub struct Person { + pub payload: Vec, + pub nickname: Option, + pub years: Option, + } + + delegate_components! { + Person { + BodyGetterComponent: UseField, + NickGetterComponent: UseField, + AgeGetterComponent: UseField, + } + } + + check_components! { + Person { + BodyGetterComponent, + NickGetterComponent, + AgeGetterComponent, + } + } + + #[test] + fn the_shorthands_borrow_without_with_field_ref() { + let person = Person { + payload: vec![1, 2], + nickname: Some("Al".to_owned()), + years: None, }; - assert_eq!(app.config(), &Config { port: 8080 }); + + assert_eq!(person.body(), &[1, 2]); + assert_eq!(person.nick(), Some("Al")); + assert_eq!(person.age(), None); } } diff --git a/example-code/tests/reference/providers/with_provider.rs b/example-code/tests/reference/providers/with_provider.rs index 73d68739..334eba91 100644 --- a/example-code/tests/reference/providers/with_provider.rs +++ b/example-code/tests/reference/providers/with_provider.rs @@ -1,7 +1,8 @@ //! Code from `docs/reference/providers/with_provider.md` — *`WithProvider`*. //! //! Pins that the `WithField` alias — `WithProvider>` — wires a getter to a named field -//! by adapting the foundational field getter. +//! by adapting the foundational field getter, the When to use it claims about `WithField` on a type +//! component and `WithContext`, and the listings' inputs from Under the hood. /// ## Examples pub mod examples { @@ -30,11 +31,79 @@ pub mod examples { } } - #[test] - fn test_with_field_adapts_use_field() { - let person = Person { - first_name: "Ada".to_owned(), - }; + pub fn demo() { + let person = Person { first_name: "Ada".to_owned() }; assert_eq!(person.name(), "Ada"); } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## When to use it +/// +/// `WithField` gives a `#[cgp_type]` component a field's type, which the bare `UseField` cannot, and +/// `WithContext` reads the context's `HasType` entry keyed by the component. +pub mod when_to_use_it { + use core::marker::PhantomData; + + use cgp::core::field::impls::WithField; + use cgp::core::types::TypeProviderComponent; + use cgp::prelude::*; + + #[cgp_type] + pub trait HasWidthType { + type Width; + } + + #[cgp_type] + pub trait HasNameType { + type Name; + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f32, + } + + delegate_components! { + Rectangle { + TypeProviderComponent: UseType, + WidthTypeProviderComponent: WithField, + NameTypeProviderComponent: WithContext, + } + } + + check_components! { + Rectangle { + WidthTypeProviderComponent, + NameTypeProviderComponent, + } + } + + pub fn assert_types( + width: PhantomData<::Width>, + name: PhantomData<::Name>, + ) -> (PhantomData, PhantomData) { + (width, name) + } +} + +/// ## Under the hood +/// +/// The type and getter components whose `WithProvider` impls the page lists, for `cargo cgp expand`. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasNameType { + type Name; + } + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } } From 8b2939008408c7ce40604c38dcf4a584b7acd161 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 03:18:48 +0000 Subject: [PATCH 127/516] Fix doubled indentation and rewrap edited provider paragraphs A scripted replacement kept each code line's original indentation and added its own, so nine example lines on the provider pages were indented twice. Halve them, and rewrap the prose paragraphs the P1 edits left over width. Add two fixtures for rejected snippets the pages describe: a bare UseField on a #[cgp_type] component, and WithFieldRef with an unsized str value, which now also has a Common Mistakes entry on the WithFieldRef page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/providers/chain_getters.md | 33 ++++---- docs/reference/providers/redirect_lookup.md | 34 ++++---- docs/reference/providers/use_context.md | 2 +- docs/reference/providers/use_default.md | 14 ++-- docs/reference/providers/use_delegate.md | 30 +++---- .../reference/providers/use_delegated_type.md | 18 ++-- docs/reference/providers/use_field.md | 18 ++-- docs/reference/providers/use_field_ref.md | 39 +++++---- docs/reference/providers/use_fields.md | 16 ++-- docs/reference/providers/use_type.md | 2 +- docs/reference/providers/with_context.md | 14 ++-- .../providers/with_delegated_type.md | 11 +-- docs/reference/providers/with_field.md | 20 +++-- docs/reference/providers/with_field_ref.md | 29 +++++-- docs/reference/providers/with_provider.md | 32 +++---- docs/reference/providers/with_type.md | 9 +- ...amples_bare_use_field_on_type_component.rs | 25 ++++++ ...es_bare_use_field_on_type_component.stderr | 47 +++++++++++ ...field_ref_common_mistakes_unsized_value.rs | 26 ++++++ ...d_ref_common_mistakes_unsized_value.stderr | 83 +++++++++++++++++++ .../tests/reference/providers/with_field.rs | 3 +- .../reference/providers/with_field_ref.rs | 3 +- 22 files changed, 363 insertions(+), 145 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.rs create mode 100644 example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs create mode 100644 example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index f6444f44..34a10b4d 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -11,15 +11,15 @@ Compose a list of field getters into one, reaching a field several hops inside a ## Overview -`ChainGetters` reaches a field that does not live directly on the context but several levels -inside it. The [**context**](/docs/reference/glossary#context) is the type the method runs on, which supplies the -values it needs as its fields, and a single [`UseField`](use_field.md) reads one field of one -context. But CGP contexts often nest: a context holds -a config, the config holds a connection, the connection holds a timeout, and a getter may need the -innermost value. Writing one provider that walks the whole path by hand is tedious and couples the -getter to the nesting. `ChainGetters` takes a list of getters, applies them in order, and -threads the reference from each step into the next, so the chain reads like the path it traverses: -outer getter, then the next, ending at the target field. +`ChainGetters` reaches a field that does not live directly on the context but several +levels inside it. The [**context**](/docs/reference/glossary#context) is the type the method runs +on, which supplies the values it needs as its fields, and a single [`UseField`](use_field.md) reads +one field of one context. But CGP contexts often nest: a context holds a config, the config holds a +connection, the connection holds a timeout, and a getter may need the innermost value. Writing one +provider that walks the whole path by hand is tedious and couples the getter to the nesting. +`ChainGetters` takes a list of getters, applies them in order, and threads the reference +from each step into the next, so the chain reads like the path it traverses: outer getter, then the +next, ending at the target field. `ChainGetters` is a foundational [`FieldGetter`](../traits/field-access/field_getter.md), so it is wired to a getter component through the [`WithProvider`](with_provider.md) adapter rather than named on its own. The list @@ -88,7 +88,7 @@ delegate_components! { NameGetterComponent: WithProvider< ChainGetters, - UseField, + UseField, ]>, >, } @@ -145,12 +145,13 @@ where } ``` -The head `Getter` reads `ValueA` from the `Context`, and the rest of the chain reads `ValueB` from that -`ValueA`, so the whole chain's `Value` is `ValueB`, the value at the end of the path. The head is -applied through [`FieldMapper`](../traits/field-access/field_mapper.md) rather than `FieldGetter` directly: -`map_field` hands the intermediate reference to a closure that runs the rest of the chain on it, which -keeps the borrowed lifetimes inferring across each hop. `FieldMapper` has a blanket implementation -for every `FieldGetter` that requires the getter and the tag to be `'static`, so each step of a chain must be a `'static` type. +The head `Getter` reads `ValueA` from the `Context`, and the rest of the chain reads `ValueB` from +that `ValueA`, so the whole chain's `Value` is `ValueB`, the value at the end of the path. The head +is applied through [`FieldMapper`](../traits/field-access/field_mapper.md) rather than `FieldGetter` +directly: `map_field` hands the intermediate reference to a closure that runs the rest of the chain +on it, which keeps the borrowed lifetimes inferring across each hop. `FieldMapper` has a blanket +implementation for every `FieldGetter` that requires the getter and the tag to be `'static`, so each +step of a chain must be a `'static` type. The recursion bottoms out at the empty list, where `ChainGetters` is the identity getter and returns the context it was given: diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 75fefd04..4ed02549 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -27,12 +27,12 @@ this provider is legible. `RedirectLookup` separates *which key* a component is looked up under from *which table* answers it. The ordinary provider blanket impl looks a component up in the -[**context**](/docs/reference/glossary#context)'s own delegation table, keyed by the -[component marker](/docs/reference/glossary#component-marker), where the context is the type the -implementation runs against. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed by a -type-level `Path`, then delegates to whatever provider that entry holds. This indirection lets -one component's resolution be redirected to a different key in a different table, which is the basis for -organizing wiring into namespaces. +[**context**](/docs/reference/glossary#context)'s own delegation table, keyed by the [component +marker](/docs/reference/glossary#component-marker), where the context is the type the implementation +runs against. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed +by a type-level `Path`, then delegates to whatever provider that entry holds. This indirection lets +one component's resolution be redirected to a different key in a different table, which is the basis +for organizing wiring into namespaces. The redirection makes namespaces work. A namespace groups a context's components under a path prefix so several related components can be wired in one place and addressed by a shared path. @@ -157,13 +157,14 @@ where } ``` -The mechanism is one [`DelegateComponent`](../traits/wiring/delegate_component.md) lookup keyed on `__Path__` -rather than on the component marker. `RedirectLookup` implements `Greeter` whenever -`Components` maps `Path` to a delegate that itself implements `Greeter`, and the method forwards to that -delegate. When the consumer trait carries generic type parameters, the impl first appends every one of them to -the path with [`ConcatPath`](../traits/formatting/concat_path.md), in declaration order, skipping -lifetime and const parameters. For `CanCalculateArea`, `cargo cgp expand` shows, with the -path resugared as `Path!(@Shape)`: +The mechanism is one [`DelegateComponent`](../traits/wiring/delegate_component.md) lookup keyed on +`__Path__` rather than on the component marker. `RedirectLookup` implements +`Greeter` whenever `Components` maps `Path` to a delegate that itself implements `Greeter`, and the +method forwards to that delegate. When the consumer trait carries generic type parameters, the impl +first appends every one of them to the path with +[`ConcatPath`](../traits/formatting/concat_path.md), in declaration order, skipping lifetime and +const parameters. For `CanCalculateArea`, `cargo cgp expand` shows, with the path resugared +as `Path!(@Shape)`: ```rust impl<__Context__, Shape, __Components__, __Path__> AreaCalculator<__Context__, Shape> @@ -186,8 +187,8 @@ where The lookup is still a single `DelegateComponent` query on the whole extended path, not a walk segment by segment. A table answers a shorter prefix of the path because [`delegate_components!`](../macros/delegate_components.md) generates entries generic over the -remaining segments, which is how the `open` statement's key forms work. As always, the impl is paired with a matching -[`IsProviderFor`](../traits/wiring/is_provider_for.md) impl. +remaining segments, which is how the `open` statement's key forms work. As always, the impl is +paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl. The [`#[prefix(@path in Namespace)]`](../attributes/prefix.md) attribute populates the path side: it generates a namespace impl whose delegate is `RedirectLookup`, with the prefix path @@ -225,7 +226,8 @@ Bind the provider at the registered path, `@app.GreeterComponent: GreetHello`, a - [`delegate_components!`](../macros/delegate_components.md) — the `open` and `namespace` statements that generate the redirect entries. - [`DelegateComponent`](../traits/wiring/delegate_component.md) — the table the lookup reads. -- [`Path!`](../macros/path.md) and [`PathCons`](../types/path_cons.md) — the type-level path it looks up. +- [`Path!`](../macros/path.md) and [`PathCons`](../types/path_cons.md) — the type-level path it + looks up. - [`UseContext`](use_context.md) — the other `#[cgp_component]`-generated provider, routing back to the context. diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index 7ccb34e2..cb3dc439 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -98,7 +98,7 @@ delegate_components! { open EncoderComponent; @EncoderComponent.u32: EncodeAsText, - @EncoderComponent.Vec: EncodeVec, + @EncoderComponent.Vec: EncodeVec, } } diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index 22e8ff9a..556f4403 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -101,7 +101,7 @@ delegate_components! { NameGetterComponent, GreeterComponent, ]: - UseDefault, + UseDefault, } } @@ -119,12 +119,12 @@ pub fn demo() { The first `#[cgp_impl]` makes `UseDefault` a `NameGetter` provider whose `name` is the trait default `"John"`; the second makes it a `Greeter` provider whose `greet` is the trait default that formats -around `self.name()`. The `Greeter` impl restates its dependency with [`#[uses(HasName)]`](../attributes/uses.md), because -the default body of `greet` calls `name`; [`#[extend(HasName)]`](../attributes/extend.md) on the -trait does not give the provider that bound, as [Common Mistakes](#common-mistakes) shows. `App` -then delegates both components to `UseDefault` in one array entry, so `App.greet()` produces -`"Hello, John!"` entirely from the two default bodies, with no method implemented on `App` or on a -dedicated provider. +around `self.name()`. The `Greeter` impl restates its dependency with +[`#[uses(HasName)]`](../attributes/uses.md), because the default body of `greet` calls `name`; +[`#[extend(HasName)]`](../attributes/extend.md) on the trait does not give the provider that bound, +as [Common Mistakes](#common-mistakes) shows. `App` then delegates both components to `UseDefault` +in one array entry, so `App.greet()` produces `"Hello, John!"` entirely from the two default bodies, +with no method implemented on `App` or on a dedicated provider. ## When to use it diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index 7f040a84..aaf481e7 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -29,12 +29,13 @@ It is expected to be deprecated once `open` is shown to cover every dispatch cas ## Overview `UseDelegate` chooses a provider based on a type argument rather than on the component alone. An -ordinary component picks its provider by looking the component name up in the [**context**](/docs/reference/glossary#context)'s delegation -table, where the context is the type the implementation runs against. But when a provider trait carries an -extra generic parameter, such as a `SourceError` to convert or a `Shape` to measure, the right provider -often depends on which concrete type that parameter is. `UseDelegate` performs a second lookup: it -treats one generic parameter as a key and reads the matching inner provider out of a table, so a single -wiring entry can fan out to many type-specific providers. +ordinary component picks its provider by looking the component name up in the +[**context**](/docs/reference/glossary#context)'s delegation table, where the context is the type +the implementation runs against. But when a provider trait carries an extra generic parameter, such +as a `SourceError` to convert or a `Shape` to measure, the right provider often depends on which +concrete type that parameter is. `UseDelegate` performs a second lookup: it treats one generic +parameter as a key and reads the matching inner provider out of a table, so a single wiring entry +can fan out to many type-specific providers. This lets context-generic providers stay generic even when their implementations would otherwise overlap on a parameter. Rather than one provider matching every possible `Shape`, you write a small provider per @@ -183,14 +184,15 @@ where } ``` -The mechanism is a single [`DelegateComponent`](../traits/wiring/delegate_component.md) lookup keyed on -`(Shape)`, which is the bare type `Shape` rather than a one-element tuple; `UseDelegate<(A, B)>` keys -on a real tuple of two parameters. `UseDelegate` implements `AreaCalculator` for a given -`Shape` exactly when `Components` maps that `Shape` to a delegate that itself implements -`AreaCalculator`, and the method forwards to it. Only the parameter named inside `UseDelegate<...>` is the key; the rest pass through -unchanged. Each impl is paired with an [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl so -dependencies propagate to a check. A component may derive more than one dispatcher when different -parameters should be routed differently. +The mechanism is a single [`DelegateComponent`](../traits/wiring/delegate_component.md) lookup keyed +on `(Shape)`, which is the bare type `Shape` rather than a one-element tuple; `UseDelegate<(A, B)>` +keys on a real tuple of two parameters. `UseDelegate` implements `AreaCalculator` for a +given `Shape` exactly when `Components` maps that `Shape` to a delegate that itself implements +`AreaCalculator`, and the method forwards to it. Only the parameter named inside `UseDelegate<...>` +is the key; the rest pass through unchanged. Each impl is paired with an +[`IsProviderFor`](../traits/wiring/is_provider_for.md) impl so dependencies propagate to a check. A +component may derive more than one dispatcher when different parameters should be routed +differently. ## Related constructs diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index 89e461b3..ec490902 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -12,12 +12,13 @@ Resolve an [abstract type](/docs/reference/glossary#abstract-type) by looking it ## Overview `UseDelegatedType` is for the case where the concrete type an abstract type resolves to -should itself be decided by a table. The plain [`UseType`](use_type.md) provider binds an abstract -type to one fixed `T`. But sometimes a single provider must answer several abstract-type components at -once, or route each type tag to a different concrete type chosen elsewhere, such as when a namespace or -a [higher-order provider](/docs/reference/glossary#higher-order-provider) supplies a coherent bundle of types. Hand-writing one `UseType` entry per tag -would scatter that decision; `UseDelegatedType` concentrates it into one `Components` table the provider -consults. As always, the [**context**](/docs/reference/glossary#context) (the type that implements the trait) +should itself be decided by a table. The plain [`UseType`](use_type.md) provider binds an +abstract type to one fixed `T`. But sometimes a single provider must answer several abstract-type +components at once, or route each type tag to a different concrete type chosen elsewhere, such as +when a namespace or a [higher-order provider](/docs/reference/glossary#higher-order-provider) +supplies a coherent bundle of types. Hand-writing one `UseType` entry per tag would scatter that +decision; `UseDelegatedType` concentrates it into one `Components` table the provider consults. As +always, the [**context**](/docs/reference/glossary#context) (the type that implements the trait) points its type components at the provider. The mechanism is the same indirection [`UseDelegate`](use_delegate.md) provides for behavioral @@ -78,8 +79,9 @@ table whose values are types rather than providers. ## When to use it -You choose `UseDelegatedType` by wiring its [`WithDelegatedType`](with_delegated_type.md) alias, so the guidance on when to answer several abstract types from one shared table, rather than fixing -each one with [`UseType`](use_type.md), lives with that alias, on +You choose `UseDelegatedType` by wiring its [`WithDelegatedType`](with_delegated_type.md) alias, so +the guidance on when to answer several abstract types from one shared table, rather than fixing each +one with [`UseType`](use_type.md), lives with that alias, on [`WithDelegatedType`](with_delegated_type.md). ## Under the hood diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index 821a56e4..5a12d333 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -14,12 +14,12 @@ decision rather than the method name. `UseField` decouples a getter's method name from the field it reads. A getter component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes a value the context can supply, such as -`fn name(&self) -> &str`. The [**context**](/docs/reference/glossary#context) is the type the method runs on, which supplies -the values it needs as its fields. But the context may store the value under a different field name, -say `first_name`, and different contexts may store it under different names. `UseField` carries -the field name as its type parameter, so wiring a getter to `UseField` makes it -read `first_name` even though the method is `name`. The field name lives in the wiring, not in the -trait. +`fn name(&self) -> &str`. The [**context**](/docs/reference/glossary#context) is the type the method +runs on, which supplies the values it needs as its fields. But the context may store the value under +a different field name, say `first_name`, and different contexts may store it under different names. +`UseField` carries the field name as its type parameter, so wiring a getter to +`UseField` makes it read `first_name` even though the method is `name`. The +field name lives in the wiring, not in the trait. This is the provider that [`#[cgp_getter]`](../macros/cgp_getter.md) targets. That macro generates a `UseField` implementation for the getter's provider trait with the field tag left as a free parameter, @@ -177,9 +177,9 @@ and the field name are independent. The mutable getter components, so the implementations carry no `IsProviderFor` pair; a getter component reaches them through [`WithField`](with_field.md), whose `WithProvider` wrapper does. -**[`TypeProvider`](../components/has_type.md).** `UseField` reports the field's `Value` type as an -[abstract type](/docs/reference/glossary#abstract-type), with a matching `IsProviderFor` implementation, -so the *type* of a field can be wired as a context's abstract type. The built-in +**[`TypeProvider`](../components/has_type.md).** `UseField` reports the field's `Value` type as +an [abstract type](/docs/reference/glossary#abstract-type), with a matching `IsProviderFor` +implementation, so the *type* of a field can be wired as a context's abstract type. The built-in `TypeProviderComponent` takes `UseField` directly, while a [`#[cgp_type]`](../macros/cgp_type.md) component takes it as `WithField`, because the macro generates `UseType` and `WithProvider` implementations but no `UseField` one. diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index 0cd2acd4..213a238b 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -12,25 +12,27 @@ stored type differs from the getter's return type. ## Overview -`UseFieldRef` reads the field named by `Tag` from the [**context**](/docs/reference/glossary#context) (the type the method runs on, which supplies -the values it needs as its fields) and borrows it through `AsRef` to produce a `&Value`, where the +`UseFieldRef` reads the field named by `Tag` from the +[**context**](/docs/reference/glossary#context) (the type the method runs on, which supplies the +values it needs as its fields) and borrows it through `AsRef` to produce a `&Value`, where the stored field type implements `AsRef`. It exists for a getter whose return type is reached -*through* a field rather than being the field's own type: a `&Config` from a stored `Arc`, for -example, where the field is not a `Config` but can be borrowed as one. +*through* a field rather than being the field's own type: a `&Config` from a stored `Arc`, +for example, where the field is not a `Config` but can be borrowed as one. `UseFieldRef` is a foundational [`FieldGetter`](../traits/field-access/field_getter.md) rather than a getter component's own provider, so it is wired through its [`WithFieldRef`](with_field_ref.md) alias, `WithProvider>`. That distinguishes it from [`UseField`](use_field.md), which [`#[cgp_getter]`](../macros/cgp_getter.md) generates a getter-component implementation for directly. -Most borrowed-view getters do not need `UseFieldRef` at all, and this is the key thing to know before -reaching for it. When a getter's return type is one of the shorthands the getter macros recognize, the generated -[`UseField`](use_field.md) implementation already borrows for you: a `&str` getter reads a `String` -field through `.as_str()`, a `&[T]` getter reads any `'static` field implementing `AsRef<[T]>`, such -as a `Vec`, through `.as_ref()`, and an `Option<&T>` or `Option<&str>` getter reads an -`Option` or `Option` field. Each is wired with a plain `UseField`. `UseFieldRef` is for the -remaining case, a getter that returns `&T` for some type `T` the field is not stored as but can be -borrowed as. Like every CGP provider, it carries no runtime value. +Most borrowed-view getters do not need `UseFieldRef` at all, and this is the key thing to know +before reaching for it. When a getter's return type is one of the shorthands the getter macros +recognize, the generated [`UseField`](use_field.md) implementation already borrows for you: a `&str` +getter reads a `String` field through `.as_str()`, a `&[T]` getter reads any `'static` field +implementing `AsRef<[T]>`, such as a `Vec`, through `.as_ref()`, and an `Option<&T>` or +`Option<&str>` getter reads an `Option` or `Option` field. Each is wired with a plain +`UseField`. `UseFieldRef` is for the remaining case, a getter that returns `&T` for some type `T` +the field is not stored as but can be borrowed as. Like every CGP provider, it carries no runtime +value. ## Usage @@ -41,9 +43,10 @@ those rest on is described under [Under the hood](#under-the-hood) below. ## When to use it -You choose `UseFieldRef` by wiring its [`WithFieldRef`](with_field_ref.md) alias, so the guidance on when a borrowed-view getter needs it, rather than the plain -[`UseField`](use_field.md) or an [`#[implicit]`](../attributes/implicit.md) argument, lives with that -alias, on [`WithFieldRef`](with_field_ref.md). +You choose `UseFieldRef` by wiring its [`WithFieldRef`](with_field_ref.md) alias, so the guidance on +when a borrowed-view getter needs it, rather than the plain [`UseField`](use_field.md) or an +[`#[implicit]`](../attributes/implicit.md) argument, lives with that alias, on +[`WithFieldRef`](with_field_ref.md). ## Under the hood @@ -66,9 +69,9 @@ where The `where` clause carries the defining constraint: the context's field at `Tag` must implement `AsRef`, so the stored type can be borrowed as the exposed type. As in -[`UseField`](use_field.md), `OutTag` is the tag the component asks under and is ignored, while the field -is read at `Tag`. The body reads the field and calls `as_ref()`. The stored field type must also be `'static`, so a -field holding a borrowed reference cannot be read this way. +[`UseField`](use_field.md), `OutTag` is the tag the component asks under and is ignored, while the +field is read at `Tag`. The body reads the field and calls `as_ref()`. The stored field type must +also be `'static`, so a field holding a borrowed reference cannot be read this way. `UseFieldRef` also implements the mutable getter [`MutFieldGetter`](../traits/field-access/mut_field_getter.md), requiring the field type to implement both `AsRef` and `AsMut` and returning `&mut Value` diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 4f7e8f36..52179753 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -30,12 +30,12 @@ participates in CGP wiring can still opt into the auto-getter convention when it its methods. `UseFields` is distinct from its sibling [`UseField`](use_field.md), and the singular-versus-plural -naming marks the difference. `UseField` keys on a tag the wiring chooses, letting one method read a field of any name, and it -exists only for single-method getters; `UseFields` takes no parameter, keys every method on its own -name, and works for any number of methods. Reach for +naming marks the difference. `UseField` keys on a tag the wiring chooses, letting one method +read a field of any name, and it exists only for single-method getters; `UseFields` takes no +parameter, keys every method on its own name, and works for any number of methods. Reach for `UseField` when the field name must differ from the method name, and for `UseFields` when the -convention holds. Like every CGP provider, `UseFields` carries no runtime value: it is a marker named -in wiring. +convention holds. Like every CGP provider, `UseFields` carries no runtime value: it is a marker +named in wiring. ## Usage @@ -108,8 +108,10 @@ the wired counterpart of the [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md case where the getter is a full component rather than a blanket impl. Prefer [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) when the getter does not need to be a -wireable component, and prefer an [`#[implicit]`](../attributes/implicit.md) argument when a provider needs a value from its own context, which is the common case and needs no [getter trait](/docs/reference/glossary#getter-trait) at all. -Reach for [`UseField`](use_field.md) instead when the field name must differ from the method name. +wireable component, and prefer an [`#[implicit]`](../attributes/implicit.md) argument when a +provider needs a value from its own context, which is the common case and needs no [getter +trait](/docs/reference/glossary#getter-trait) at all. Reach for [`UseField`](use_field.md) +instead when the field name must differ from the method name. ## Under the hood diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index a300086a..6d858e91 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -81,7 +81,7 @@ pub struct App; delegate_components! { App { - ScalarTypeProviderComponent: UseType, + ScalarTypeProviderComponent: UseType, } } diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md index 8593bac5..6444e33a 100644 --- a/docs/reference/providers/with_context.md +++ b/docs/reference/providers/with_context.md @@ -50,8 +50,8 @@ What the entry needs from the context depends on the component's kind: imported from `cgp::core::types`, is the usual way to supply it; wired to `UseType`, it answers every tag with `String`. - **A single-method [`#[cgp_getter]`](../macros/cgp_getter.md) component**, such as `HasName`, reads - the context's `HasField` entry. No derive generates a `HasField` impl keyed by a - component marker, so the context implements it by hand. + the context's `HasField` entry. No derive generates a `HasField` impl keyed + by a component marker, so the context implements it by hand. ## Examples @@ -114,11 +114,11 @@ usually fit better: pub type WithContext = WithProvider; ``` -The [`WithProvider`](with_provider.md) impl that `#[cgp_type]` generates bounds its inner provider by -`TypeProvider<__Context__, NameTypeProviderComponent>`, and the one `#[cgp_getter]` generates bounds it -by `FieldGetter<__Context__, NameGetterComponent>`. `UseContext` implements both by asking the -context, the first through the `UseContext` impl `#[cgp_component]` generates for `HasType` and the -second through a hand-written impl beside `FieldGetter`: +The [`WithProvider`](with_provider.md) impl that `#[cgp_type]` generates bounds its inner provider +by `TypeProvider<__Context__, NameTypeProviderComponent>`, and the one `#[cgp_getter]` generates +bounds it by `FieldGetter<__Context__, NameGetterComponent>`. `UseContext` implements both by asking +the context, the first through the `UseContext` impl `#[cgp_component]` generates for `HasType` and +the second through a hand-written impl beside `FieldGetter`: ```rust impl FieldGetter for UseContext diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md index af55c7d1..abda340f 100644 --- a/docs/reference/providers/with_delegated_type.md +++ b/docs/reference/providers/with_delegated_type.md @@ -11,10 +11,11 @@ Resolve one or more abstract-type components from a shared table, through the `W ## Overview -`WithDelegatedType` is the alias `WithProvider>`. It answers a -context's abstract-type components by looking each type tag up in the `Components` table, on a [**context**](/docs/reference/glossary#context), the type that implements the trait, by adapting the foundational -[`UseDelegatedType`](use_delegated_type.md) provider through the [`WithProvider`](with_provider.md) -layer. Like every CGP provider, it carries no runtime value. +`WithDelegatedType` is the alias `WithProvider>`. It +answers a context's abstract-type components by looking each type tag up in the `Components` table, +on a [**context**](/docs/reference/glossary#context), the type that implements the trait, by +adapting the foundational [`UseDelegatedType`](use_delegated_type.md) provider through the +[`WithProvider`](with_provider.md) layer. Like every CGP provider, it carries no runtime value. Unlike [`WithType`](with_type.md), this alias is not an alternative to a directly-wireable provider on a `#[cgp_type]` component: the bare [`UseDelegatedType`](use_delegated_type.md) supplies only the @@ -79,7 +80,7 @@ delegate_components! { [ ScalarTypeProviderComponent, IndexTypeProviderComponent, - ]: WithDelegatedType, + ]: WithDelegatedType, } } diff --git a/docs/reference/providers/with_field.md b/docs/reference/providers/with_field.md index 255fe209..3621cd8b 100644 --- a/docs/reference/providers/with_field.md +++ b/docs/reference/providers/with_field.md @@ -11,12 +11,13 @@ Wire a getter component to a named context field, through the `WithProvider` ada ## Overview -`WithField` is the alias `WithProvider>`. It implements a getter component by reading -the context field named by `Tag`, on a [**context**](/docs/reference/glossary#context), the type the method runs on, by adapting the -foundational [`UseField`](use_field.md) getter through the [`WithProvider`](with_provider.md) layer. -On a getter it reads the same field the plain [`UseField`](use_field.md) provider does, and the two -are interchangeable there. On a [`#[cgp_type]`](../macros/cgp_type.md) component only `WithField` -works, and it sets the abstract type to the field's type. Like every CGP provider, it carries no runtime value. +`WithField` is the alias `WithProvider>`. It implements a getter component by +reading the context field named by `Tag`, on a [**context**](/docs/reference/glossary#context), the +type the method runs on, by adapting the foundational [`UseField`](use_field.md) getter through +the [`WithProvider`](with_provider.md) layer. On a getter it reads the same field the plain +[`UseField`](use_field.md) provider does, and the two are interchangeable there. On a +[`#[cgp_type]`](../macros/cgp_type.md) component only `WithField` works, and it sets the abstract +type to the field's type. Like every CGP provider, it carries no runtime value. ## Usage @@ -57,7 +58,7 @@ pub struct Person { delegate_components! { Person { - NameGetterComponent: WithField, + NameGetterComponent: WithField, } } @@ -97,8 +98,9 @@ delegate_components! { ``` `Rectangle`'s `Width` is `f32`, the type of its `width` field. `#[cgp_type]` generates a -`WithProvider` impl but no `UseField` impl, so `WidthTypeProviderComponent: UseField` -fails with `E0277`, while `UseField`'s own `TypeProvider` impl serves it through `WithField`. +`WithProvider` impl but no `UseField` impl, so +`WidthTypeProviderComponent: UseField` fails with `E0277`, while `UseField`'s own +`TypeProvider` impl serves it through `WithField`. ## When to use it diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md index 3d156da2..5686e696 100644 --- a/docs/reference/providers/with_field_ref.md +++ b/docs/reference/providers/with_field_ref.md @@ -11,9 +11,11 @@ Wire a getter component to a field borrowed through `AsRef`, through the `WithPr ## Overview -`WithFieldRef` is the alias `WithProvider>`. It implements a getter -component by reading the field named by `Tag` from the [**context**](/docs/reference/glossary#context), the type the method runs on, and borrowing it through `AsRef` to produce a `&Value`, where the stored field type implements -`AsRef`. It adapts the foundational [`UseFieldRef`](use_field_ref.md) getter through the +`WithFieldRef` is the alias `WithProvider>`. It implements a +getter component by reading the field named by `Tag` from the +[**context**](/docs/reference/glossary#context), the type the method runs on, and borrowing it +through `AsRef` to produce a `&Value`, where the stored field type implements `AsRef`. It +adapts the foundational [`UseFieldRef`](use_field_ref.md) getter through the [`WithProvider`](with_provider.md) layer. Like every CGP provider, it carries no runtime value. Unlike [`WithField`](with_field.md), this alias is not an alternative to a directly-wireable provider: @@ -72,7 +74,7 @@ pub struct App { delegate_components! { App { - ConfigGetterComponent: WithFieldRef, + ConfigGetterComponent: WithFieldRef, } } @@ -99,8 +101,8 @@ borrows as `T` through `AsRef`.** The stored type and the exposed type differ, a [`WithField`](with_field.md) nor an [`#[implicit]`](../attributes/implicit.md) argument can bridge them. The common borrowed-view getters need no `WithFieldRef`: a `-> &str` getter over a `String` field, a -`-> &[T]` getter over a field implementing `AsRef<[T]>` such as a `Vec`, and an `Option<&T>` getter -over an `Option` field are all served by the plain [`UseField`](use_field.md) or +`-> &[T]` getter over a field implementing `AsRef<[T]>` such as a `Vec`, and an `Option<&T>` +getter over an `Option` field are all served by the plain [`UseField`](use_field.md) or [`WithField`](with_field.md) through the getter macros' return-type shorthands. For a field returned as its own type, an `#[implicit]` argument is simpler still. @@ -119,6 +121,21 @@ The `UseFieldRef` mechanism, including its mutable form, is documented on the [`UseFieldRef`](use_field_ref.md) page, and the generated `WithProvider` impl on the [`WithProvider`](with_provider.md) page. +## Common Mistakes + +**`WithFieldRef` cannot serve a `-> &str` getter.** `Value` must be sized, and a `&str` return +already makes the getter macros expect a `String` field, so `WithFieldRef` fails +twice over: + +```text +error[E0277]: the size for values of type `str` cannot be known at compilation time +... +error[E0271]: type mismatch resolving `>>>>, str> as FieldGetter>::Value == String` +``` + +Wire a `&str` getter over a `String` field to the plain [`UseField`](use_field.md), which borrows +through `.as_str()`. + ## Related constructs - [`WithProvider`](with_provider.md) — the adapter this alias specializes. diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 4d3f90df..85f71e53 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -13,15 +13,16 @@ specific named component. ## Overview `WithProvider` bridges CGP's two layers of provider trait. Foundational traits like -[`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field-access/field_getter.md) are generic, -component-agnostic mechanisms: a `TypeProvider` supplies *some* [abstract type](/docs/reference/glossary#abstract-type) for *some* tag, and a -`FieldGetter` reads *some* field for *some* output tag, without either knowing which named component it -serves. A named component, by contrast, has a specific provider trait, such as `NameTypeProvider` or -`NameGetter`, that a [**context**](/docs/reference/glossary#context) wires to, where the context is the type the -implementation runs against. -`WithProvider` is the adapter that lets a foundational provider stand in as the provider for -one of those named components: it implements the component's provider trait by forwarding to the -foundational provider's method. +[`TypeProvider`](../components/has_type.md) and +[`FieldGetter`](../traits/field-access/field_getter.md) are generic, component-agnostic mechanisms: +a `TypeProvider` supplies *some* [abstract type](/docs/reference/glossary#abstract-type) for *some* +tag, and a `FieldGetter` reads *some* field for *some* output tag, without either knowing which +named component it serves. A named component, by contrast, has a specific provider trait, such as +`NameTypeProvider` or `NameGetter`, that a [**context**](/docs/reference/glossary#context) wires to, +where the context is the type the implementation runs against. `WithProvider` is the +adapter that lets a foundational provider stand in as the provider for one of those named +components: it implements the component's provider trait by forwarding to the foundational +provider's method. This adapter lets the foundational layer be wired without each foundational provider implementing every component trait by hand. A field getter written once as a `FieldGetter` can serve any @@ -74,7 +75,7 @@ pub struct Person { delegate_components! { Person { - NameGetterComponent: WithField, + NameGetterComponent: WithField, } } @@ -105,11 +106,12 @@ the type through a table. [`WithField`](with_field.md) and [`UseField`](use_field.md) on every single-method getter, so prefer the plain provider there. `WithField` is the form to wire when a `#[cgp_type]` component should take a field's type, since such a component has no `UseField` impl. -[`WithContext`](with_context.md) is not interchangeable with [`UseContext`](use_context.md): wired to -a component, `UseContext` calls the context's own consumer trait for that component, which loops, -while `WithContext` reads the context's `HasField` or `HasType` entry keyed by the component. [`WithFieldRef`](with_field_ref.md) and [`WithDelegatedType`](with_delegated_type.md) -have no plain wireable form, because their inner providers are foundational, so you wire the alias. -Each alias is documented on its own page, linked from the table above. +[`WithContext`](with_context.md) is not interchangeable with [`UseContext`](use_context.md): wired +to a component, `UseContext` calls the context's own consumer trait for that component, which loops, +while `WithContext` reads the context's `HasField` or `HasType` entry keyed by the component. +[`WithFieldRef`](with_field_ref.md) and [`WithDelegatedType`](with_delegated_type.md) have no plain +wireable form, because their inner providers are foundational, so you wire the alias. Each alias is +documented on its own page, linked from the table above. Write `WithProvider` in full only when adapting a foundational provider that has no ready alias. diff --git a/docs/reference/providers/with_type.md b/docs/reference/providers/with_type.md index f59ba5e4..a8a445ed 100644 --- a/docs/reference/providers/with_type.md +++ b/docs/reference/providers/with_type.md @@ -52,7 +52,7 @@ pub struct App; delegate_components! { App { - ScalarTypeProviderComponent: WithType, + ScalarTypeProviderComponent: WithType, } } @@ -71,9 +71,10 @@ it, a type that breaks the bound is reported only when the component is used, as ## When to use it **Prefer the plain [`UseType`](use_type.md) form.** It binds the same type and is the idiomatic -value for a [`#[cgp_type]`](../macros/cgp_type.md) component's wiring entry. The two are equivalent on every `#[cgp_type]` component, because the macro generates both a `UseType` -impl and a [`WithProvider`](with_provider.md) impl; `WithType` completes the `With…` family and reads -as a single wiring choice where spelling out `WithProvider>` would not. +value for a [`#[cgp_type]`](../macros/cgp_type.md) component's wiring entry. The two are equivalent +on every `#[cgp_type]` component, because the macro generates both a `UseType` impl and a +[`WithProvider`](with_provider.md) impl; `WithType` completes the `With…` family and reads as a +single wiring choice where spelling out `WithProvider>` would not. For an abstract type resolved through a table rather than fixed to one concrete type, use [`WithDelegatedType`](with_delegated_type.md). diff --git a/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.rs b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.rs new file mode 100644 index 00000000..dde197c1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.rs @@ -0,0 +1,25 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasWidthType { + type Width; +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f32, +} + +delegate_components! { + Rectangle { + WidthTypeProviderComponent: UseField, + } +} + +check_components! { + Rectangle { + WidthTypeProviderComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr new file mode 100644 index 00000000..5c33041c --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr @@ -0,0 +1,47 @@ +error[E0277]: the trait bound `cgp::prelude::UseField>>>>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.rs:21:9 + | +21 | WidthTypeProviderComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `cgp::prelude::UseField>>>>>>` +help: the following other types implement trait `IsProviderFor` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + | +31 | / impl AsyncComputer for UseField +32 | | where +33 | | Context: HasField, +34 | | Context::Value: CanComputeAsync, + | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_field.rs:69:1 + | +69 | / impl IsProviderFor +70 | | for UseField +71 | | where +72 | | Context: HasField, + | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/computer.rs:29:1 + | +29 | / impl Computer for UseField +30 | | where +31 | | Context: HasField, +32 | | Context::Value: CanCompute, + | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + | + 5 | #[cgp_getter] + | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` + = note: required for `Rectangle` to implement `CanUseComponent` +note: required by a bound in `__CheckRectangle` + --> tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.rs:19:1 + | +19 | / check_components! { +20 | | Rectangle { +21 | | WidthTypeProviderComponent, +22 | | } +23 | | } + | |_^ required by this bound in `__CheckRectangle` + = note: this error originates in the attribute macro `cgp_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs new file mode 100644 index 00000000..c123e59d --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs @@ -0,0 +1,26 @@ +use cgp::core::field::impls::WithFieldRef; +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +delegate_components! { + Person { + NameGetterComponent: WithFieldRef, + } +} + +check_components! { + Person { + NameGetterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr new file mode 100644 index 00000000..f0c6977b --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr @@ -0,0 +1,83 @@ +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs:14:1 + | +14 | / delegate_components! { +15 | | Person { +16 | | NameGetterComponent: WithFieldRef, +17 | | } +18 | | } + | |_^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` +note: required by an implicit `Sized` bound in `UseFieldRef` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_ref.rs:7:29 + | + 7 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); + | ^^^^^ required by the implicit `Sized` requirement on this type parameter in `UseFieldRef` + = note: this error originates in the macro `delegate_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0271]: type mismatch resolving `>>>>, str> as FieldGetter>::Value == String` + --> tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs:22:9 + | +22 | NameGetterComponent, + | ^^^^^^^^^^^^^^^^^^^ expected `String`, found `str` + | +note: required for `WithProvider>>>>, str>>` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs:4:1 + | + 4 | #[cgp_getter] + | ^^^^^^^^^^^^^ + = note: associated types for the current `impl` cannot be restricted in `where` clauses + = note: required for `Person` to implement `CanUseComponent` +note: required by a bound in `__CheckPerson` + --> tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs:20:1 + | +20 | / check_components! { +21 | | Person { +22 | | NameGetterComponent, +23 | | } +24 | | } + | |_^ required by this bound in `__CheckPerson` + = note: this error originates in the attribute macro `cgp_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs:22:9 + | +22 | NameGetterComponent, + | ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` + = note: required for `UseFieldRef>>>>, str>` to implement `cgp::prelude::FieldGetter` +note: required for `WithProvider>>>>, str>>` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs:4:1 + | + 4 | #[cgp_getter] + | ^^^^^^^^^^^^^ + = note: required for `Person` to implement `CanUseComponent` +note: required by a bound in `__CheckPerson` + --> tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs:20:1 + | +20 | / check_components! { +21 | | Person { +22 | | NameGetterComponent, +23 | | } +24 | | } + | |_^ required by this bound in `__CheckPerson` + = note: this error originates in the attribute macro `cgp_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider relaxing the implicit `Sized` restriction + | +24 | }: ?Sized + | ++++++++ + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.rs:16:30 + | +16 | NameGetterComponent: WithFieldRef, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` +note: required by an implicit `Sized` bound in `UseFieldRef` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_ref.rs:7:29 + | + 7 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); + | ^^^^^ required by the implicit `Sized` requirement on this type parameter in `UseFieldRef` diff --git a/example-code/tests/reference/providers/with_field.rs b/example-code/tests/reference/providers/with_field.rs index 1b7b00a3..4171e2b3 100644 --- a/example-code/tests/reference/providers/with_field.rs +++ b/example-code/tests/reference/providers/with_field.rs @@ -2,7 +2,8 @@ //! //! Pins that the `WithField` alias wires a `name` getter to read the //! `first_name` field, the same as the plain `UseField`, and gives a `#[cgp_type]` component a -//! field's type, which the plain `UseField` cannot. +//! field's type, which the plain `UseField` cannot; the bare `UseField` on that component is a trybuild +//! fixture. /// ## Examples pub mod examples { diff --git a/example-code/tests/reference/providers/with_field_ref.rs b/example-code/tests/reference/providers/with_field_ref.rs index ffe38629..3f5cc82d 100644 --- a/example-code/tests/reference/providers/with_field_ref.rs +++ b/example-code/tests/reference/providers/with_field_ref.rs @@ -2,7 +2,8 @@ //! //! `WithFieldRef` (`WithProvider>`) is the form that wires the foundational //! `UseFieldRef` getter. This pins that a `-> &Config` getter reads a stored `AsRef` field, -//! and that the borrowed views When to use it names need only the plain `UseField`. +//! and that the borrowed views When to use it names need only the plain `UseField`. The unsized +//! `str` value from Common Mistakes is a trybuild fixture. /// ## Examples pub mod examples { From 80e10071128481cb36d813cb6634d63e52ef9802 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 03:31:27 +0000 Subject: [PATCH 128/516] Revise the error and monad provider reference pages Give the twelve pages under providers/error/ and providers/monad/ a description and, on the construct pages, a title, and resync them with the error and monad catalogues and the source. Examples now carry complete programs with check_components! and a demo(), taken from the mirrors: three error pages (RaiseInfallible, PanicOnError, DiscardDetail) and both bind pages had no Examples, and the rest showed wiring fragments or calls on undefined names. The stacked-monad PipeMonadic example is new and mirrored. Fixes: PanicOnError still needs an error type; DiscardDetail's Detail is unconstrained, not bound; the overviews name the imports and prefer open over UseDelegate; RaiseFrom's example now shows one entry converting two source types. New Common Mistakes, each a trybuild fixture: RaiseFrom on a source without a From impl, and the String key wired to DebugError or DisplayError, which forwards to itself (E0275). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/providers/error/debug_error.md | 133 ++++++++++++++---- .../providers/error/discard_detail.md | 84 +++++++++-- .../providers/error/display_error.md | 123 +++++++++++++--- docs/reference/providers/error/index.md | 44 +++--- .../providers/error/panic_on_error.md | 83 +++++++++-- docs/reference/providers/error/raise_from.md | 126 ++++++++++++++--- .../providers/error/raise_infallible.md | 94 +++++++++++-- .../reference/providers/error/return_error.md | 98 ++++++++++--- docs/reference/providers/monad/bind_err.md | 72 ++++++++-- docs/reference/providers/monad/bind_ok.md | 79 +++++++++-- docs/reference/providers/monad/index.md | 16 ++- .../reference/providers/monad/pipe_monadic.md | 124 +++++++++++++--- ..._error_common_mistakes_string_key_cycle.rs | 39 +++++ ...or_common_mistakes_string_key_cycle.stderr | 28 ++++ ..._error_common_mistakes_string_key_cycle.rs | 39 +++++ ...or_common_mistakes_string_key_cycle.stderr | 28 ++++ ...raise_from_common_mistakes_missing_from.rs | 38 +++++ ...e_from_common_mistakes_missing_from.stderr | 68 +++++++++ .../reference/providers/error/debug_error.rs | 49 ++++--- .../providers/error/discard_detail.rs | 42 +++--- .../providers/error/display_error.rs | 50 ++++--- .../providers/error/panic_on_error.rs | 28 ++-- .../reference/providers/error/raise_from.rs | 78 +++++----- .../providers/error/raise_infallible.rs | 31 ++-- .../reference/providers/error/return_error.rs | 84 +++++++---- .../reference/providers/monad/bind_err.rs | 48 +++---- .../reference/providers/monad/bind_ok.rs | 55 +++----- .../reference/providers/monad/pipe_monadic.rs | 106 ++++++++++---- 28 files changed, 1459 insertions(+), 428 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.rs create mode 100644 example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.rs create mode 100644 example-code/tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs create mode 100644 example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index 2ace4609..91021901 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -1,4 +1,6 @@ --- +title: 'DebugError — raise errors via Debug' +description: 'The error provider that formats a Debug source or detail into a String and forwards it to the context''s own String raiser or wrapper.' sidebar_label: 'DebugError' sidebar_position: 4 --- @@ -10,23 +12,25 @@ string handling. ## Overview -`DebugError` implements both error components by redirecting through a string. Rather than producing the -abstract error directly, it formats the source error or the detail with the `Debug` trait into a -`String`, then forwards to the **context**'s own `CanRaiseError` or `CanWrapError`, -where the context is the type a method runs on. It does not know the context's error type: it -only knows how to turn a `Debug` value into a `String` and hand it off, leaving the final step to -whatever string-handling provider the context already wires. Like every CGP provider, `DebugError` -carries no runtime value. +`DebugError` implements both error components by redirecting through a string. Rather than producing +the abstract error directly, it formats the source error or the detail with the `Debug` trait and +`format!("{:?}")` into a `String`, then forwards to the +[**context**](/docs/reference/glossary#context)'s own `CanRaiseError` or +`CanWrapError`, where the context is the type the implementation runs against. It does not +know the context's error type: it turns a `Debug` value into a `String` and hands it off, leaving +the final step to whatever provider the context wires for the `String` key. Like every CGP provider, +`DebugError` carries no runtime value. -This design lets a context handle an open-ended set of error types with one concrete -string-raising rule. `DebugError` routes every `Debug` source through the single `String` path, and the -context wires one provider (often [`RaiseFrom`](raise_from.md)) for that path. +This design lets a context handle an open-ended set of error types with one concrete string rule. +`DebugError` routes every `Debug` source through the single `String` key, and the context wires one +provider, often [`RaiseFrom`](raise_from.md), for that key. ## Usage -Import the provider from `cgp::extra::error` and the wiring keys from `cgp::core::error`. `DebugError` -lives behind the crate's `alloc` feature, because it allocates a `String`. It takes no type parameter -and is wired to `ErrorRaiserComponent`, `ErrorWrapperComponent`, or both: +Import the provider from `cgp::extra::error` and the wiring keys from `cgp::core::error`; none of them +is in the prelude. `DebugError` lives behind the crate's `alloc` feature, which is on by default, +because it allocates a `String`. It takes no type parameter and is wired to `ErrorRaiserComponent`, +`ErrorWrapperComponent`, or both, usually per source type with the `open` statement: ```rust use cgp::core::error::ErrorRaiserComponent; @@ -42,19 +46,79 @@ delegate_components! { } ``` -The `String` entry must be present for `DebugError` to forward to. Here a raised `ParseIntError` is -formatted with `Debug` and handed to the `String` entry, which `RaiseFrom` converts into the abstract -error. +The `String` entry must be present, and must be some other provider, for `DebugError` to forward to. +Here a raised `ParseIntError` is formatted and handed to the `String` entry, which +[`RaiseFrom`](raise_from.md) converts into the abstract error. + +## Examples + +A provider raises a `ParseIntError`, and the context formats it with `DebugError` into the `String` it +uses as its error: + +```rust +use core::num::ParseIntError; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::{DebugError, RaiseFrom}; + +#[cgp_component(PortParser)] +#[use_type(HasErrorType.Error)] +pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; +} + +#[cgp_impl(new ParsePort)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + raw.parse().map_err(Self::raise_error) + } +} + +pub struct App; + +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + PortParserComponent: ParsePort, + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + } +} + +check_components! { + App { + PortParserComponent, + } +} + +pub fn demo() { + assert_eq!(App.parse_port("8080"), Ok(8080)); + assert_eq!( + App.parse_port("http"), + Err("ParseIntError { kind: InvalidDigit }".to_owned()) + ); +} +``` + +`App` is an [environmental context](/docs/reference/glossary#environmental-context) whose error is +`String`. The `ParseIntError` key goes to `DebugError`, which produces +`"ParseIntError { kind: InvalidDigit }"` and raises it through the `String` key, and `RaiseFrom` +returns that string through the reflexive `From for String`. ## When to use it -**Reach for `DebugError` when a source error implements `Debug` but the abstract error has no `From` impl -for it, and you want its debug output carried as a string.** Pair it with a provider on the `String` -source, since it forwards rather than finishes. +**Reach for `DebugError` when a source error implements `Debug` but the abstract error has no `From` +impl for it, and you want its debug output carried as a string.** Pair it with a provider on the +`String` key, since it forwards rather than finishes. Reach for [`DisplayError`](display_error.md) when the source implements `Display` and you want its -user-facing message rather than its debug form. Reach for [`RaiseFrom`](raise_from.md) when a real `From` -impl exists, which preserves the source rather than flattening it to a string. +user-facing message rather than its debug form. Reach for [`RaiseFrom`](raise_from.md) when a real +`From` impl exists, which preserves the source rather than flattening it to a string. ## Under the hood @@ -89,13 +153,30 @@ Both bounds require the context to already handle the `String` case, which is th reduces any `Debug` source to the one case the context knows. Each impl is paired with a matching [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl. +## Common Mistakes + +**The `String` key itself cannot be wired to `DebugError`.** For a `String` source, `DebugError` +formats it and raises the result through the context's `CanRaiseError`, which is +`DebugError` again, so the lookup never ends. A check reports the overflow: + +```text +error[E0275]: overflow evaluating the requirement `DebugError: ErrorRaiser` +``` + +The same holds for `@ErrorWrapperComponent.String: DebugError`, which forwards to +`CanWrapError`. Wire the `String` key to a provider that finishes the job, such as +[`RaiseFrom`](raise_from.md) for raising or a wrapper written for the context's error type, and route +only the other source types to `DebugError`. + ## Related constructs -- [`DisplayError`](display_error.md) — the same provider formatting with `Display` and `to_string()`. -- [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) — the components it supplies, - and the `String` forms it forwards to. -- [`RaiseFrom`](raise_from.md) — the usual provider on the `String` source that finishes the raise. -- [`UseDelegate`](../use_delegate.md) — dispatches `DebugError` for the source types it should format. +- [`DisplayError`](display_error.md) — the same provider formatting with `Display` instead. +- [`CanRaiseError`](../../components/can_raise_error.md) and + [`CanWrapError`](../../components/can_wrap_error.md) — the components it supplies, and the `String` + forms it forwards to. +- [`RaiseFrom`](raise_from.md) — the usual provider on the `String` key that finishes the raise. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement routes the + source types `DebugError` should format. The ideas behind it: diff --git a/docs/reference/providers/error/discard_detail.md b/docs/reference/providers/error/discard_detail.md index b39a154f..62599448 100644 --- a/docs/reference/providers/error/discard_detail.md +++ b/docs/reference/providers/error/discard_detail.md @@ -1,4 +1,6 @@ --- +title: 'DiscardDetail — wrap by dropping the detail' +description: 'The error wrapper that ignores the attached detail and returns the error unchanged, for an error type that cannot carry extra context.' sidebar_label: 'DiscardDetail' sidebar_position: 6 --- @@ -10,15 +12,16 @@ Wrap an error by throwing the detail away and returning the error unchanged. ## Overview `DiscardDetail` is the `ErrorWrapper` provider that ignores whatever detail is attached and returns the -error as it was. It satisfies the `CanWrapError` trait of a **context**, the type a method runs -on, without enriching the error. This is useful when a context's error type cannot carry extra -context, or when the wrapping detail is deliberately not kept. It is the wrapping counterpart of a no-op: -the error propagates unchanged. Like every CGP provider, `DiscardDetail` carries no runtime value. +error as it was. It satisfies the `CanWrapError` trait of a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, without +enriching the error. This is useful when a context's error type cannot carry extra context, or when +the wrapping detail is deliberately not kept. It is the wrapping counterpart of a no-op: the error +propagates unchanged. Like every CGP provider, `DiscardDetail` carries no runtime value. ## Usage Import the provider from `cgp::extra::error` and the wiring key `ErrorWrapperComponent` from -`cgp::core::error`. It takes no type parameter and accepts any detail type: +`cgp::core::error`; neither is in the prelude. It takes no type parameter and accepts any detail type: ```rust use cgp::core::error::ErrorWrapperComponent; @@ -34,15 +37,68 @@ delegate_components! { Wired this way, any call to `Context::wrap_error(error, detail)` on `App` returns `error` and drops `detail`, for every detail type. +## Examples + +A provider raises an error and wraps it with a detail string, and the context's wrapper drops the +detail: + +```rust +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapperComponent}; +use cgp::extra::error::{DiscardDetail, RaiseFrom}; + +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self) -> Result<(), Error>; +} + +#[cgp_impl(new LoadConfig)] +#[uses(CanRaiseError, CanWrapError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self) -> Result<(), Error> { + let error = Self::raise_error("disk offline".to_owned()); + Err(Self::wrap_error(error, "while loading config".to_owned())) + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + ErrorWrapperComponent: DiscardDetail, + LoaderComponent: LoadConfig, + } +} + +check_components! { + App { + LoaderComponent, + } +} + +pub fn demo() { + assert_eq!(App.load(), Err("disk offline".to_owned())); +} +``` + +`LoadConfig` attaches `"while loading config"`, but `App`, an +[environmental context](/docs/reference/glossary#environmental-context), wires `DiscardDetail`, so +the error arrives as the bare `"disk offline"`. Wiring a wrapper that keeps the detail instead changes +the result without touching `LoadConfig`. + ## When to use it **Reach for `DiscardDetail` when a context's error type cannot hold extra detail, or when a call site attaches detail that this context has no use for.** It keeps the `CanWrapError` trait satisfiable without storing anything. -Reach for [`DebugError`](debug_error.md) or [`DisplayError`](display_error.md) when the detail should be -kept as a formatted string, or for a backend provider when the concrete error type can carry structured -context. +Reach for [`DebugError`](debug_error.md) or [`DisplayError`](display_error.md) when the detail should +be kept as a formatted string, or for a backend provider when the concrete error type can carry +structured context. ## Under the hood @@ -60,16 +116,18 @@ where } ``` -The detail is bound only so the method can accept it; the body returns the error untouched. The -generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same `HasErrorType` bound. +`Detail` is unconstrained, so any type is accepted, and the body returns the error untouched. The +generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same +`HasErrorType` bound. ## Related constructs -- [`CanWrapError`](../../components/can_wrap_error.md) — the component `DiscardDetail` supplies, through - the `ErrorWrapper` provider trait. +- [`CanWrapError`](../../components/can_wrap_error.md) — the component `DiscardDetail` supplies, + through the `ErrorWrapper` provider trait. - [`DebugError`](debug_error.md), [`DisplayError`](display_error.md) — wrap by keeping the detail as a formatted string instead of discarding it. -- [`UseDelegate`](../use_delegate.md) — dispatches wrappers per detail type. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement dispatches + wrappers per detail type. The ideas behind it: diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md index fb8cdb09..5df55b0d 100644 --- a/docs/reference/providers/error/display_error.md +++ b/docs/reference/providers/error/display_error.md @@ -1,4 +1,6 @@ --- +title: 'DisplayError — raise errors via Display' +description: 'The error provider that formats a Display source or detail with to_string() and forwards it to the context''s own String raiser or wrapper.' sidebar_label: 'DisplayError' sidebar_position: 5 --- @@ -10,19 +12,24 @@ string handling. ## Overview -`DisplayError` is the `Display` counterpart of [`DebugError`](debug_error.md). It implements both error -components by formatting the source error or the detail with the `Display` trait into a `String`, then -forwarding to the **context**'s own `CanRaiseError` or `CanWrapError`, where the context -is the type a method runs on. It carries the source's user-facing message rather than its debug -representation. Like every CGP provider, `DisplayError` carries no runtime value. +`DisplayError` implements both error components by redirecting through a string. Rather than +producing the abstract error directly, it formats the source error or the detail with the `Display` +trait through `to_string()` into a `String`, then forwards to the +[**context**](/docs/reference/glossary#context)'s own `CanRaiseError` or +`CanWrapError`, where the context is the type the implementation runs against. It does not +know the context's error type: it turns a `Display` value into a `String` and hands it off, leaving +the final step to whatever provider the context wires for the `String` key. Like every CGP provider, +`DisplayError` carries no runtime value. -As with `DebugError`, it does not know the context's error type. It reduces any `Display` source to the -`String` case and leaves the final step to whatever provider the context wires for `String`. +It is the `Display` counterpart of [`DebugError`](debug_error.md): it carries the source's user-facing +message rather than its debug representation. ## Usage -Import the provider from `cgp::extra::error` and the wiring keys from `cgp::core::error`. `DisplayError` -lives behind the crate's `alloc` feature, because it allocates a `String`. It takes no type parameter: +Import the provider from `cgp::extra::error` and the wiring keys from `cgp::core::error`; none of them +is in the prelude. `DisplayError` lives behind the crate's `alloc` feature, which is on by default, +because it allocates a `String`. It takes no type parameter and is wired to `ErrorRaiserComponent`, +`ErrorWrapperComponent`, or both, usually per source type with the `open` statement: ```rust use cgp::core::error::ErrorRaiserComponent; @@ -38,12 +45,74 @@ delegate_components! { } ``` -A `String` entry must be present for `DisplayError` to forward to. +The `String` entry must be present, and must be some other provider, for `DisplayError` to forward to. +Here a raised `ParseIntError` is formatted and handed to the `String` entry, which +[`RaiseFrom`](raise_from.md) converts into the abstract error. + +## Examples + +A provider raises a `ParseIntError`, and the context formats it with `DisplayError` into the +`String` it uses as its error: + +```rust +use core::num::ParseIntError; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::{DisplayError, RaiseFrom}; + +#[cgp_component(PortParser)] +#[use_type(HasErrorType.Error)] +pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; +} + +#[cgp_impl(new ParsePort)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + raw.parse().map_err(Self::raise_error) + } +} + +pub struct App; + +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + PortParserComponent: ParsePort, + + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DisplayError, + } +} + +check_components! { + App { + PortParserComponent, + } +} + +pub fn demo() { + assert_eq!(App.parse_port("8080"), Ok(8080)); + assert_eq!( + App.parse_port("http"), + Err("invalid digit found in string".to_owned()) + ); +} +``` + +`App` is an [environmental context](/docs/reference/glossary#environmental-context) whose error is +`String`. The `ParseIntError` key goes to `DisplayError`, which produces +`"invalid digit found in string"` and raises it through the `String` key, and `RaiseFrom` returns +that string through the reflexive `From for String`. ## When to use it **Reach for `DisplayError` when a source implements `Display` and you want its user-facing message -carried as a string.** Pair it with a provider on the `String` source, since it forwards rather than +carried as a string.** Pair it with a provider on the `String` key, since it forwards rather than finishes. Reach for [`DebugError`](debug_error.md) when you want the source's debug form instead, or when the @@ -52,8 +121,8 @@ impl exists, which keeps the source rather than reducing it to a string. ## Under the hood -`DisplayError` matches [`DebugError`](debug_error.md) in shape, but formats with `Display` through -`to_string()`: +`DisplayError` implements `ErrorRaiser` for any `Display` source over a context that raises +`String`, and `ErrorWrapper` for any `Display` detail over a context that wraps `String`: ```rust #[cgp_provider] @@ -79,16 +148,34 @@ where } ``` -Both bounds require the context to already handle `String`. Each impl is paired with a matching +Both bounds require the context to already handle the `String` case, which is the indirection that +reduces any `Display` source to the one case the context knows. Each impl is paired with a matching [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl. +## Common Mistakes + +**The `String` key itself cannot be wired to `DisplayError`.** For a `String` source, `DisplayError` +formats it and raises the result through the context's `CanRaiseError`, which is +`DisplayError` again, so the lookup never ends. A check reports the overflow: + +```text +error[E0275]: overflow evaluating the requirement `DisplayError: ErrorRaiser` +``` + +The same holds for `@ErrorWrapperComponent.String: DisplayError`, which forwards to +`CanWrapError`. Wire the `String` key to a provider that finishes the job, such as +[`RaiseFrom`](raise_from.md) for raising or a wrapper written for the context's error type, and route +only the other source types to `DisplayError`. + ## Related constructs - [`DebugError`](debug_error.md) — the same provider formatting with `Debug` instead. -- [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) — the components it supplies, - and the `String` forms it forwards to. -- [`RaiseFrom`](raise_from.md) — the usual provider on the `String` source that finishes the raise. -- [`UseDelegate`](../use_delegate.md) — dispatches `DisplayError` for the source types it should format. +- [`CanRaiseError`](../../components/can_raise_error.md) and + [`CanWrapError`](../../components/can_wrap_error.md) — the components it supplies, and the `String` + forms it forwards to. +- [`RaiseFrom`](raise_from.md) — the usual provider on the `String` key that finishes the raise. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement routes the + source types `DisplayError` should format. The ideas behind it: diff --git a/docs/reference/providers/error/index.md b/docs/reference/providers/error/index.md index 39abcb85..945ec28f 100644 --- a/docs/reference/providers/error/index.md +++ b/docs/reference/providers/error/index.md @@ -1,4 +1,5 @@ --- +description: 'The seven error providers CGP ships, from RaiseFrom to DisplayError: raising and wrapping strategies generic over the context''s error type.' sidebar_label: 'Overview' sidebar_position: 0 --- @@ -10,17 +11,19 @@ concrete error type the context chose. ## Overview -The error providers supply common error-handling strategies to any **context**, the type a method -runs on. [`CanRaiseError`](../../components/can_raise_error.md) and -[`CanWrapError`](../../components/can_wrap_error.md) define *what* a -context can do with an error: turn a source error into its abstract `Self::Error`, or attach detail to -one it already holds. They say nothing about *how*. These providers supply the how for the cases that -need no particular error library. Each one is generic over the context, so it works with whatever error -type the context's [`HasErrorType`](../../components/has_error_type.md) names. - -Each provider implements one or both of two provider traits. `CanRaiseError`'s provider trait is -`ErrorRaiser`, wired with `ErrorRaiserComponent`. `CanWrapError`'s provider trait is `ErrorWrapper`, -wired with `ErrorWrapperComponent`. A provider that implements `ErrorRaiser` supplies raising; one that +The error providers supply common error-handling strategies to any +[**context**](/docs/reference/glossary#context), the type the implementation runs against. +[`CanRaiseError`](../../components/can_raise_error.md) and +[`CanWrapError`](../../components/can_wrap_error.md) define *what* a context can do with an error: +turn a source error into its abstract `Self::Error`, or attach detail to one it already holds. They +say nothing about *how*. These providers supply the how for the cases that need no particular error +library. Each one is generic over the context, so it works with whatever error type the context's +[`HasErrorType`](../../components/has_error_type.md) names. + +Each provider implements one or both of two provider traits, all reached through `cgp::extra::error` +and none in the prelude. `CanRaiseError`'s provider trait is `ErrorRaiser`, wired with +`ErrorRaiserComponent`. `CanWrapError`'s provider trait is `ErrorWrapper`, wired with +`ErrorWrapperComponent`. A provider that implements `ErrorRaiser` supplies raising; one that implements `ErrorWrapper` supplies wrapping; two of them supply both. These are the in-tree counterparts to the standalone backends in `cgp-error-anyhow`, `cgp-error-eyre`, @@ -57,20 +60,27 @@ The remaining two act on the wrapping and raising components directly: ## Wiring them A context gains an error strategy by wiring one of these providers to `ErrorRaiserComponent` or -`ErrorWrapperComponent`, exactly like any other component, and the provider's `where` clause decides -when that wiring type-checks. Because both components dispatch on the source-error or detail type, a -context commonly wires several providers at once, one per source error type. The modern form is the -`open` statement of [`delegate_components!`](../../macros/delegate_components.md); the error family is -still defined with [`#[derive_delegate]`](../../attributes/derive_delegate.md), so a nested +`ErrorWrapperComponent`, both imported from `cgp::core::error`, and the provider's `where` clause +decides when that wiring type-checks. Because both components dispatch on the source-error or detail +type, a context commonly wires several providers at once, one per source error type. The modern form +is the `open` statement of [`delegate_components!`](../../macros/delegate_components.md); the error +family is still defined with [`#[derive_delegate]`](../../attributes/derive_delegate.md), so a nested [`UseDelegate`](../use_delegate.md) table is the form you will read in existing code. +The string-formatting providers compose with the rest rather than replacing them. `DebugError` and +`DisplayError` turn a value into a `String` and raise or wrap it through the context's own `String` +key, so the context wires one concrete rule for `String`, such as `RaiseFrom`, and routes the other +source types to the formatters. The `String` key itself must never go to a formatter, since the +formatter would then forward to itself (`E0275`). + ## Related constructs - [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) — the components these implement, through the `ErrorRaiser` and `ErrorWrapper` provider traits. - [`HasErrorType`](../../components/has_error_type.md) — names the abstract `Self::Error` every provider here produces. -- [`UseDelegate`](../use_delegate.md) — the table that dispatches these providers per source-error type. +- [`UseDelegate`](../use_delegate.md) — the legacy table that dispatches these providers per + source-error type, which the `open` statement replaces. - [`delegate_components!`](../../macros/delegate_components.md) and [`check_components!`](../../macros/check_components.md) — wire and verify them. diff --git a/docs/reference/providers/error/panic_on_error.md b/docs/reference/providers/error/panic_on_error.md index 02bd1287..f3edf4ff 100644 --- a/docs/reference/providers/error/panic_on_error.md +++ b/docs/reference/providers/error/panic_on_error.md @@ -1,4 +1,6 @@ --- +title: 'PanicOnError — panic instead of raising' +description: 'The error raiser that panics with the source error''s Debug output rather than returning an error value, for tests and fail-fast tools.' sidebar_label: 'PanicOnError' sidebar_position: 7 --- @@ -10,15 +12,17 @@ Abort with the source error's debug output instead of producing an abstract erro ## Overview `PanicOnError` is the `ErrorRaiser` provider that panics rather than returning an error. When a -**context**, the type a method runs on, treats an error as a programming fault that should stop -the program, `PanicOnError` raises by calling `panic!` with the source error's debug representation. Its -signature promises to return the abstract error, but the body never does, because `panic!` diverges. -This suits tests and fail-fast tooling. Like every CGP provider, `PanicOnError` carries no runtime value. +[**context**](/docs/reference/glossary#context), the type the implementation runs against, treats an +error as a programming fault that should stop the program, `PanicOnError` raises by calling `panic!` +with the source error's debug representation. Its signature promises to return the abstract error, +but the body never does, because `panic!` diverges. This suits tests and fail-fast tooling. Like every +CGP provider, `PanicOnError` carries no runtime value. ## Usage Import the provider from `cgp::extra::error` and the wiring key `ErrorRaiserComponent` from -`cgp::core::error`. It takes no type parameter and accepts any `Debug` source: +`cgp::core::error`; neither is in the prelude. It takes no type parameter and accepts any `Debug` +source: ```rust use cgp::core::error::ErrorRaiserComponent; @@ -31,17 +35,69 @@ delegate_components! { } ``` -Any call to `Context::raise_error(source)` on `TestApp` panics with `format!("{source:?}")` rather than -returning. +Any call to `Context::raise_error(source)` on `TestApp` panics with `format!("{source:?}")` rather +than returning. The context still wires an error type, because the provider's signature names +`Context::Error` and its `where` clause requires `HasErrorType`. + +## Examples + +A test context wires every raise to `PanicOnError`, so a provider that fails aborts the test with the +source's debug output: + +```rust +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::PanicOnError; + +#[cgp_component(Runner)] +#[use_type(HasErrorType.Error)] +pub trait CanRun { + fn run(&self) -> Result<(), Error>; +} + +#[cgp_impl(new RunOrAbort)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Runner { + fn run(&self) -> Result<(), Error> { + Err(Self::raise_error("unrecoverable".to_owned())) + } +} + +pub struct TestApp; + +delegate_components! { + TestApp { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: PanicOnError, + RunnerComponent: RunOrAbort, + } +} + +check_components! { + TestApp { + RunnerComponent, + } +} + +pub fn demo() { + let _ = TestApp.run(); // panics with "\"unrecoverable\"" +} +``` + +`RunOrAbort` raises a `String` and would return it as an error on another context. `TestApp`, an +[environmental context](/docs/reference/glossary#environmental-context) for tests, wires the raise +to `PanicOnError`, so `run` panics with the `Debug` form of the string, quotes included, and never +returns. ## When to use it -**Reach for `PanicOnError` where an error means a bug that should abort rather than be handled**, such as -a test harness or a fail-fast tool. It removes the need to give the context a real error type or a -handling strategy. +**Reach for `PanicOnError` where an error means a bug that should abort rather than be handled**, such +as a test harness or a fail-fast tool. It spares the context a handling strategy, though not an error +type. -Do not wire it in production code that should recover from errors. Use [`RaiseFrom`](raise_from.md) or a -backend provider there, so a raised error becomes a value the caller can handle. +Do not wire it in production code that should recover from errors. Use [`RaiseFrom`](raise_from.md) or +a backend provider there, so a raised error becomes a value the caller can handle. ## Under the hood @@ -69,7 +125,8 @@ generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries - [`CanRaiseError`](../../components/can_raise_error.md) — the component `PanicOnError` supplies. - [`RaiseFrom`](raise_from.md), [`ReturnError`](return_error.md) — the raisers to use when an error should become a value rather than abort. -- [`UseDelegate`](../use_delegate.md) — dispatches raisers per source-error type. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement dispatches + raisers per source type, so a context can panic on some sources and raise others. The ideas behind it: diff --git a/docs/reference/providers/error/raise_from.md b/docs/reference/providers/error/raise_from.md index 4a8b4e3d..823bfe43 100644 --- a/docs/reference/providers/error/raise_from.md +++ b/docs/reference/providers/error/raise_from.md @@ -1,4 +1,6 @@ --- +title: 'RaiseFrom — raise an error through From' +description: 'The error raiser that converts a source error into the context''s error type with From, so one wiring covers every source that error can absorb.' sidebar_label: 'RaiseFrom' sidebar_position: 1 --- @@ -9,19 +11,20 @@ Raise a source error by converting it into the context's error type through the ## Overview -`RaiseFrom` is the `ErrorRaiser` provider for the common case: the **context**, the type a method -runs on, already knows how to build its abstract `Error` from the source error through `From`. -Wiring it means "convert every source error the abstract error has a `From` impl for". It is the default -choice whenever that `From` impl exists, which covers most error raising in practice. +`RaiseFrom` is the `ErrorRaiser` provider for the common case: the abstract error of the +[**context**](/docs/reference/glossary#context), the type the implementation runs against, already +knows how to build itself from the source error through `From`. Wiring it means "convert every source +error the abstract error has a `From` impl for". It is the default choice whenever that `From` impl +exists, which covers most error raising in practice. -Because the bound is on the abstract error rather than on one source type, a single wiring of `RaiseFrom` -covers every source error the context's error can absorb. Like every CGP provider, `RaiseFrom` carries -no runtime value. +Because the bound is on the abstract error rather than on one source type, a single wiring of +`RaiseFrom` covers every source error the context's error can absorb. Like every CGP provider, +`RaiseFrom` carries no runtime value. ## Usage Import the provider from `cgp::extra::error` and the wiring key `ErrorRaiserComponent` from -`cgp::core::error`. It takes no type parameter: +`cgp::core::error`; neither is in the prelude. It takes no type parameter: ```rust use cgp::core::error::ErrorRaiserComponent; @@ -35,35 +38,97 @@ delegate_components! { ``` Wired this way, any provider that calls `Context::raise_error(source)` on `App` succeeds for every -`source` whose type the `App` error implements `From` for. +`source` whose type the `App` error implements `From` for. A context whose error cannot absorb every +source wires `RaiseFrom` per source type instead, with the `open` statement, beside other raisers +such as [`DebugError`](debug_error.md). ## Examples -`RaiseFrom` is most often one entry in a per-source dispatch table, alongside the formatting providers -for the source types the error cannot absorb directly. Here a raised `String` is converted straight -into the abstract error, while a `ParseIntError` is formatted first: +One `RaiseFrom` entry raises two different source types, each through its own `From` impl on the +context's `AppError`: ```rust -use cgp::core::error::ErrorRaiserComponent; -use cgp::extra::error::{DebugError, RaiseFrom}; +use core::num::ParseIntError; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; + +#[derive(Debug, PartialEq)] +pub enum AppError { + Parse(ParseIntError), + Message(String), +} + +impl From for AppError { + fn from(e: ParseIntError) -> Self { + AppError::Parse(e) + } +} + +impl From for AppError { + fn from(message: String) -> Self { + AppError::Message(message) + } +} + +#[cgp_component(PortParser)] +#[use_type(HasErrorType.Error)] +pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; +} + +#[cgp_impl(new ParsePort)] +#[uses(CanRaiseError, CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + let port: u16 = raw.parse().map_err(Self::raise_error)?; + + if port == 0 { + return Err(Self::raise_error("port 0 is reserved".to_owned())); + } + + Ok(port) + } +} + +pub struct App; delegate_components! { App { - open ErrorRaiserComponent; + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + PortParserComponent: ParsePort, + } +} - @ErrorRaiserComponent.String: RaiseFrom, - @ErrorRaiserComponent.ParseIntError: DebugError, +check_components! { + App { + PortParserComponent, } } + +pub fn demo() { + assert_eq!(App.parse_port("8080"), Ok(8080)); + assert_eq!( + App.parse_port("0"), + Err(AppError::Message("port 0 is reserved".to_owned())) + ); + assert!(matches!(App.parse_port("http"), Err(AppError::Parse(_)))); +} ``` -[`DebugError`](debug_error.md) formats the `ParseIntError` into a `String` and forwards it back through the -`String` entry, which `RaiseFrom` handles. +`ParsePort` names neither the context nor its error type; it raises a `ParseIntError` and a `String` +and leaves the conversion to the context. `App` is an +[environmental context](/docs/reference/glossary#environmental-context) that sets its error to +`AppError` and wires `RaiseFrom` once, which converts both sources through `AppError`'s two `From` +impls. ## When to use it -**Reach for `RaiseFrom` whenever the abstract error already has a `From` impl for the source.** It is the -plainest raiser and the one to try first. +**Reach for `RaiseFrom` whenever the abstract error already has a `From` impl for the source.** It is +the plainest raiser and the one to try first, and it keeps the source as a value rather than +flattening it to a string. Reach for [`ReturnError`](return_error.md) instead when the source *is* the abstract error, for [`RaiseInfallible`](raise_infallible.md) when the source is `Infallible`, and for @@ -91,6 +156,22 @@ The bound `Context::Error: From` makes one wiring cover many source types. Th [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same clause, so a [check](../../macros/check_components.md) reports a missing `From` impl at the wiring site. +## Common Mistakes + +**`RaiseFrom` accepts only sources the error has a `From` impl for.** Wiring +`ErrorRaiserComponent: RaiseFrom` on a context whose error is `String` and raising a `ParseIntError` +fails at the check, since `String` has no `From`: + +```text +error[E0277]: the trait bound `RaiseFrom: ErrorRaiser` is not satisfied +... +error[E0277]: the trait bound `String: From` is not satisfied +``` + +Add the `From` impl to an error type you own, or route that source to [`DebugError`](debug_error.md) +or [`DisplayError`](display_error.md) with the `open` statement, keeping `RaiseFrom` for the +`String` key. + ## Related constructs - [`CanRaiseError`](../../components/can_raise_error.md) — the component `RaiseFrom` supplies, through @@ -98,7 +179,8 @@ The bound `Context::Error: From` makes one wiring cover many source types. Th - [`ReturnError`](return_error.md), [`RaiseInfallible`](raise_infallible.md) — the other pure raisers. - [`DebugError`](debug_error.md), [`DisplayError`](display_error.md) — format a non-convertible source into a `String` that `RaiseFrom` can then convert. -- [`UseDelegate`](../use_delegate.md) — dispatches `RaiseFrom` per source-error type. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement dispatches + raisers per source type. The ideas behind it: diff --git a/docs/reference/providers/error/raise_infallible.md b/docs/reference/providers/error/raise_infallible.md index e9e4dff7..1079c08f 100644 --- a/docs/reference/providers/error/raise_infallible.md +++ b/docs/reference/providers/error/raise_infallible.md @@ -1,4 +1,6 @@ --- +title: 'RaiseInfallible — raise an Infallible error' +description: 'The error raiser for core::convert::Infallible, which fills the raiser slot for a step that cannot fail; its method is never called.' sidebar_label: 'RaiseInfallible' sidebar_position: 3 --- @@ -10,15 +12,17 @@ Absorb `core::convert::Infallible`, the error type that can never be constructed ## Overview `RaiseInfallible` is the `ErrorRaiser` provider for `core::convert::Infallible`, an error type with no -values. It lets generic code that is parameterized over a fallible operation be wired uniformly on a -**context**, the type a method runs on, even when the operation chosen for that context cannot -fail. Because an `Infallible` value cannot exist, the raising method is never actually called at -runtime. Like every CGP provider, `RaiseInfallible` carries no runtime value. +values. It lets generic code that raises the error of a fallible operation be wired uniformly on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, even when +the operation chosen for that context cannot fail. Because an `Infallible` value cannot exist, the +raising method is never actually called at runtime. Like every CGP provider, `RaiseInfallible` carries +no runtime value. ## Usage Import the provider from `cgp::extra::error` and the wiring key `ErrorRaiserComponent` from -`cgp::core::error`. It takes no type parameter and accepts only `Infallible` as the source: +`cgp::core::error`; neither is in the prelude. It takes no type parameter and accepts only +`Infallible` as the source: ```rust use core::convert::Infallible; @@ -35,14 +39,74 @@ delegate_components! { } ``` -The `Infallible` entry satisfies the raiser bound for a step that cannot fail, while other entries handle -the source types that can. +The `Infallible` entry satisfies the raiser bound for a step that cannot fail, while other entries +handle the source types that can. + +## Examples + +A provider raises the error of a step that cannot fail, the same way it would raise a real one, and +the context fills that raiser slot with `RaiseInfallible`: + +```rust +use core::convert::Infallible; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::{RaiseFrom, RaiseInfallible}; + +#[cgp_component(Runner)] +#[use_type(HasErrorType.Error)] +pub trait CanRun { + fn run(&self) -> Result<(), Error>; +} + +#[cgp_impl(new RunInfallibly)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Runner { + fn run(&self) -> Result<(), Error> { + // A step that cannot fail, raised the same way a fallible step would be. + let outcome: Result<(), Infallible> = Ok(()); + outcome.map_err(Self::raise_error)?; + Ok(()) + } +} + +pub struct App; + +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + RunnerComponent: RunInfallibly, + + @ErrorRaiserComponent.Infallible: RaiseInfallible, + @ErrorRaiserComponent.String: RaiseFrom, + } +} + +check_components! { + App { + RunnerComponent, + } +} + +pub fn demo() { + assert_eq!(App.run(), Ok(())); +} +``` + +`RunInfallibly` requires `CanRaiseError`, and `App`, an +[environmental context](/docs/reference/glossary#environmental-context), meets it with +`RaiseInfallible`. The check is what proves the wiring resolves, since the raise is never taken at +run time. ## When to use it -**Reach for `RaiseInfallible` when generic code must raise an `Infallible` on a context, even though the -value can never occur.** This happens when a component is generic over an operation and one wiring of it -picks an operation that never errors, so the raiser slot for `Infallible` still has to be filled. +**Reach for `RaiseInfallible` when generic code must raise an `Infallible` on a context, even though +the value can never occur.** This happens when a component is generic over an operation and one wiring +of it picks an operation that never errors, so the raiser slot for `Infallible` still has to be +filled. For any other source type, use one of the other raisers: [`RaiseFrom`](raise_from.md), [`ReturnError`](return_error.md), [`DebugError`](debug_error.md), or [`DisplayError`](display_error.md). @@ -64,16 +128,16 @@ where } ``` -Because an `Infallible` value cannot be constructed, the empty `match` is total and the function has no -reachable body. The generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same -`HasErrorType` bound. +Because an `Infallible` value cannot be constructed, the empty `match` is total and the function has +no reachable body. The generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl +carries the same `HasErrorType` bound. ## Related constructs - [`CanRaiseError`](../../components/can_raise_error.md) — the component `RaiseInfallible` supplies. - [`RaiseFrom`](raise_from.md), [`ReturnError`](return_error.md) — the other pure raisers. -- [`UseDelegate`](../use_delegate.md) — dispatches raisers per source-error type, which is where the - `Infallible` entry sits. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement dispatches + raisers per source type, which is where the `Infallible` entry sits. The ideas behind it: diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md index 4af6c04d..6292c29b 100644 --- a/docs/reference/providers/error/return_error.md +++ b/docs/reference/providers/error/return_error.md @@ -1,4 +1,6 @@ --- +title: 'ReturnError — raise the context''s own error' +description: 'The error raiser for a source that already is the context''s error type: raising returns the value unchanged, with no From bound.' sidebar_label: 'ReturnError' sidebar_position: 2 --- @@ -9,17 +11,17 @@ Raise a source error that already is the context's abstract error, so raising is ## Overview -`ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly the abstract -error the **context** chose, where the context is the type a method runs on. Raising then has -nothing to convert: it returns its argument untouched. A context uses it when generic code -raises a value that is already of the context's own error type. Like every CGP provider, `ReturnError` -carries no runtime value. +`ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly the +abstract error the [**context**](/docs/reference/glossary#context) chose, where the context is the +type the implementation runs against. Raising then has nothing to convert: it returns its argument +untouched. A context uses it when generic code raises a value that is already of the context's own +error type. Like every CGP provider, `ReturnError` carries no runtime value. ## Usage Import the provider from `cgp::extra::error` and the wiring key `ErrorRaiserComponent` from -`cgp::core::error`. It takes no type parameter, and it type-checks only for the one source type that -equals the context's `Error`: +`cgp::core::error`; neither is in the prelude. It takes no type parameter, and it type-checks only for +the one source type that equals the context's `Error`: ```rust use cgp::core::error::ErrorRaiserComponent; @@ -35,29 +37,90 @@ delegate_components! { ## Examples `ReturnError` most often sits in a per-source table as the entry for the context's own error type, -beside other raisers for the foreign types. If `App` chose `AppError` as its error, this entry raises an -`AppError` source by returning it and converts other sources elsewhere: +beside other raisers for the foreign types: ```rust -use cgp::core::error::ErrorRaiserComponent; +use core::num::ParseIntError; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::error::{DebugError, RaiseFrom, ReturnError}; +#[derive(Debug, PartialEq)] +pub struct AppError { + pub message: String, +} + +impl From for AppError { + fn from(message: String) -> Self { + AppError { message } + } +} + +#[cgp_component(PortChecker)] +#[use_type(HasErrorType.Error)] +pub trait CanCheckPort { + fn check_port(&self, raw: &str) -> Result; +} + +#[cgp_impl(new CheckPort)] +#[uses(CanRaiseError, CanRaiseError)] +#[use_type(HasErrorType.{Error = AppError})] +impl PortChecker { + fn check_port(&self, raw: &str) -> Result { + let port: u16 = raw.parse().map_err(Self::raise_error)?; + + if port == 0 { + return Err(Self::raise_error(AppError { + message: "port 0 is reserved".to_owned(), + })); + } + + Ok(port) + } +} + +pub struct App; + delegate_components! { App { open ErrorRaiserComponent; + ErrorTypeProviderComponent: UseType, + PortCheckerComponent: CheckPort, + @ErrorRaiserComponent.AppError: ReturnError, @ErrorRaiserComponent.String: RaiseFrom, @ErrorRaiserComponent.ParseIntError: DebugError, } } + +check_components! { + App { + PortCheckerComponent, + } +} + +pub fn demo() { + assert_eq!(App.check_port("8080"), Ok(8080)); + assert_eq!( + App.check_port("0"), + Err(AppError { message: "port 0 is reserved".to_owned() }) + ); + assert!(App.check_port("http").unwrap_err().message.contains("ParseIntError")); +} ``` +`CheckPort` pins the error to `AppError` with `#[use_type]`'s equality form, so it can construct one +and raise it. `App` is an [environmental context](/docs/reference/glossary#environmental-context) +whose table routes each source: the `AppError` through `ReturnError`, a `String` through `RaiseFrom` +and `AppError`'s `From`, and a `ParseIntError` through [`DebugError`](debug_error.md), which +formats it and forwards it to the `String` entry. + ## When to use it -**Reach for `ReturnError` when generic code raises a value that is already the context's error type.** A -`From for AppError` impl exists in the standard library, so [`RaiseFrom`](raise_from.md) would -also work here; `ReturnError` states the intent directly and needs no `From` bound. +**Reach for `ReturnError` when generic code raises a value that is already the context's error type.** +The standard library's reflexive `impl From for T` means [`RaiseFrom`](raise_from.md) would also +work here; `ReturnError` states the intent directly and needs no `From` bound. For a source the error can absorb through `From`, use [`RaiseFrom`](raise_from.md). For a printable source with no `From` impl, use [`DebugError`](debug_error.md) or [`DisplayError`](display_error.md). @@ -78,16 +141,17 @@ where } ``` -The `HasErrorType` bound ties the source type to the abstract error, so `raise_error` returns -its argument. The generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl carries the same -bound. +The `HasErrorType` bound ties the source type to the abstract error, so `raise_error` +returns its argument. The generated [`IsProviderFor`](../../traits/wiring/is_provider_for.md) impl +carries the same bound. ## Related constructs - [`CanRaiseError`](../../components/can_raise_error.md) — the component `ReturnError` supplies. - [`RaiseFrom`](raise_from.md) — converts through `From` rather than requiring an exact match. - [`RaiseInfallible`](raise_infallible.md) — the raiser for `Infallible`. -- [`UseDelegate`](../use_delegate.md) — dispatches `ReturnError` per source-error type. +- [`delegate_components!`](../../macros/delegate_components.md) — its `open` statement dispatches + raisers per source type, as the example does. The ideas behind it: diff --git a/docs/reference/providers/monad/bind_err.md b/docs/reference/providers/monad/bind_err.md index 8330cbc0..f30d8947 100644 --- a/docs/reference/providers/monad/bind_err.md +++ b/docs/reference/providers/monad/bind_err.md @@ -1,4 +1,6 @@ --- +title: 'BindErr — one ?-style bind step' +description: 'The per-step provider of the err monad: run the continuation on a step''s Ok value and stop on Err. PipeMonadic composes it under ErrMonadic.' sidebar_label: 'BindErr' sidebar_position: 3 --- @@ -13,9 +15,10 @@ short-circuit on `Err`. `BindErr` implements a single bind step of the err monad, the ordinary `?`-style behavior. [`PipeMonadic`](pipe_monadic.md) composes it for you when it folds a pipeline under [`ErrMonadic`](index.md#the-monad-markers), so most code never names it. It is usable directly as a -handler provider on a **context**, the type a method runs on, when a pipeline is built step by -step through [`PipeHandlers`](../handler/pipe_handlers.md). Like every CGP provider, it carries no -runtime value; the two parameters ride in `PhantomData`. +handler provider on a [**context**](/docs/reference/glossary#context), the type the implementation +runs against, when a pipeline is built step by step through +[`PipeHandlers`](../handler/pipe_handlers.md). Like every CGP provider, it carries no runtime value; +the two parameters ride in `PhantomData`. ## Usage @@ -32,6 +35,37 @@ type Pipeline = PipeHandlers Ok(2) -> BindErr runs the second Increment on 2 -> Ok(3) ``` +## Examples + +One `?`-style bind step built by hand, which is what `PipeMonadic` composes for a two-element list +under `ErrMonadic`: + +```rust +use cgp::prelude::*; +use cgp::extra::handler::PipeHandlers; +use cgp::extra::monad::monadic::err::BindErr; +use cgp::extra::monad::monadic::ident::IdentMonadic; + +#[cgp_computer] +pub fn increment(value: u8) -> Result { + value.checked_add(1).ok_or("overflow") +} + +pub type Pipeline = PipeHandlers]>; + +pub fn demo() { + let code = PhantomData::<()>; + + // 1 -> Ok(2); BindErr runs the second Increment on 2 -> Ok(3). + assert_eq!(Pipeline::compute(&(), code, 1), Ok(3)); + // The first step overflows, so the bind skips the second. + assert_eq!(Pipeline::compute(&(), code, 255), Err("overflow")); +} +``` + +`Pipeline` is called on the provider directly, with `()` as the context, since `Increment` reads +nothing from it. + ## When to use it **Reach for the [monad providers](index.md) rather than `BindErr` directly.** Wiring @@ -48,12 +82,32 @@ short-circuits on `Ok`, use [`BindOk`](bind_ok.md). pub struct BindErr(pub PhantomData<(M, Cont)>); ``` -It implements `Computer` and `AsyncComputer` for an input of `Result`. On `Ok(value)` it runs -`Cont` on the value and lifts the continuation's output back through `M`. On `Err(err)` it -short-circuits, lifting the error directly to the output and skipping `Cont`. It is the mirror of -[`BindOk`](bind_ok.md), which branches the other way. The `M` parameter lets these binds nest: at -the bottom of a single-layer pipeline it is `IdentMonadic`, and a stacked monad threads a deeper monad -through it. +It implements `Computer` and `AsyncComputer` for an input of `Result`. The `Computer` impl +is: + +```rust +#[cgp_provider] +impl Computer> for BindErr +where + Cont: Computer, + M: ContainsValue> + LiftValue, Cont::Output>, +{ + type Output = M::Output; + + fn compute(context: &Context, code: PhantomData, input: Result) -> Self::Output { + match input { + Ok(value) => M::lift_output(Cont::compute(context, code, value)), + Err(err) => M::lift_value(Err(err)), + } + } +} +``` + +On `Ok(value)` it runs `Cont` on the value and lifts the continuation's output back through `M`. On +`Err(err)` it short-circuits, lifting the error directly to the output and skipping `Cont`. It is +the mirror of [`BindOk`](bind_ok.md), which branches the other way. The `M` parameter lets these +binds nest: at the bottom of a single-layer pipeline it is `IdentMonadic`, and a stacked monad +threads a deeper monad through it. ## Related constructs diff --git a/docs/reference/providers/monad/bind_ok.md b/docs/reference/providers/monad/bind_ok.md index 59467bfe..c7bfa0af 100644 --- a/docs/reference/providers/monad/bind_ok.md +++ b/docs/reference/providers/monad/bind_ok.md @@ -1,4 +1,6 @@ --- +title: 'BindOk — one fallback bind step' +description: 'The per-step provider of the ok monad: run the continuation on a step''s Err value and stop on Ok. PipeMonadic composes it under OkMonadic.' sidebar_label: 'BindOk' sidebar_position: 2 --- @@ -11,11 +13,12 @@ short-circuit on `Ok`. ## Overview `BindOk` implements a single bind step of the ok monad. [`PipeMonadic`](pipe_monadic.md) -composes it for you when it folds a pipeline under [`OkMonadic`](index.md#the-monad-markers), so most -code never names it. It is usable directly as a handler provider on a **context**, the type a method -runs on, when a pipeline is built step by step through -[`PipeHandlers`](../handler/pipe_handlers.md) rather than through `PipeMonadic`. Like every CGP -provider, it carries no runtime value; the two parameters ride in `PhantomData`. +composes it for you when it folds a pipeline under [`OkMonadic`](index.md#the-monad-markers), so +most code never names it. It is usable directly as a handler provider on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, when a +pipeline is built step by step through [`PipeHandlers`](../handler/pipe_handlers.md) rather than +through `PipeMonadic`. Like every CGP provider, it carries no runtime value; the two parameters ride +in `PhantomData`. ## Usage @@ -34,6 +37,44 @@ type Pipeline = PipeHandlers]>; At the bottom of a single-layer pipeline `M` is `IdentMonadic`; a stacked monad threads a deeper monad through it. +## Examples + +A fallback chain built by hand: `Classify` accepts a small value and hands a large one on as an `Err`, +and the bind step runs `Halve` only on that `Err`: + +```rust +use cgp::prelude::*; +use cgp::extra::handler::PipeHandlers; +use cgp::extra::monad::monadic::ident::IdentMonadic; +use cgp::extra::monad::monadic::ok::BindOk; + +/// Accept a small value, or hand a too-large one to the fallback as an `Err`. +#[cgp_computer] +pub fn classify(value: u8) -> Result { + if value < 10 { Ok(value) } else { Err(value) } +} + +/// The fallback, run only on the `Err` branch: halve the rejected value. +#[cgp_computer] +pub fn halve(value: u8) -> Result { + Ok(value / 2) +} + +pub type Pipeline = PipeHandlers]>; + +pub fn demo() { + let code = PhantomData::<()>; + + // 5 is accepted, so BindOk stops and the fallback never runs. + assert_eq!(Pipeline::compute(&(), code, 5), Ok(5)); + // 20 is rejected, so BindOk runs the fallback on the Err value: 20 -> 10. + assert_eq!(Pipeline::compute(&(), code, 20), Ok(10)); +} +``` + +`Pipeline` is called on the provider directly, with `()` as the context, since neither computer reads +anything from it. `PipeMonadic` builds the same pipeline. + ## When to use it **Reach for the [monad providers](index.md) rather than `BindOk` directly.** Wiring @@ -50,10 +91,30 @@ short-circuits on `Err`, use [`BindErr`](bind_err.md). pub struct BindOk(pub PhantomData<(M, Cont)>); ``` -It implements `Computer` and `AsyncComputer` for an input of `Result`. On `Err(payload)` it runs -`Cont` on the payload and lifts the continuation's output back through `M`. On `Ok(value)` it -short-circuits, lifting the value directly to the output and skipping `Cont`. It is the mirror of -[`BindErr`](bind_err.md), which branches the other way. +It implements `Computer` and `AsyncComputer` for an input of `Result`. The `Computer` impl +is: + +```rust +#[cgp_provider] +impl Computer> for BindOk +where + Cont: Computer, + M: ContainsValue> + LiftValue, Cont::Output>, +{ + type Output = M::Output; + + fn compute(context: &Context, code: PhantomData, input: Result) -> Self::Output { + match input { + Err(value) => M::lift_output(Cont::compute(context, code, value)), + Ok(err) => M::lift_value(Ok(err)), + } + } +} +``` + +On `Err(payload)` it runs `Cont` on the payload and lifts the continuation's output back through +`M`. On `Ok(value)` it short-circuits, lifting the value directly to the output and skipping `Cont`. +It is the mirror of [`BindErr`](bind_err.md), which branches the other way. ## Related constructs diff --git a/docs/reference/providers/monad/index.md b/docs/reference/providers/monad/index.md index 3c1f5092..96d0c735 100644 --- a/docs/reference/providers/monad/index.md +++ b/docs/reference/providers/monad/index.md @@ -1,4 +1,5 @@ --- +description: 'PipeMonadic and its bind providers, which chain handlers under a monad marker so the pipeline stops on an Err, on the first Ok, or never.' sidebar_label: 'Overview' sidebar_position: 0 --- @@ -10,12 +11,15 @@ appropriate branch. ## Overview -The monad providers build [monadic handler composition](/docs/concepts/monadic-handlers) on top of the -[`Computer`](../../components/handler/computer.md) family. They let a sequence of handlers whose outputs carry a -"continue" case and a "stop" case be chained without pattern-matching each step by hand: the monad -decides which case threads forward and which short-circuits. A built pipeline is itself a provider for -`Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires into a **context**, the type a -method runs on, exactly like any other handler. +The monad providers build [monadic handler composition](/docs/concepts/monadic-handlers) on top of +the [`Computer`](../../components/handler/computer.md) family. They let a sequence of handlers whose +outputs carry a "continue" case and a "stop" case be chained without pattern-matching each step by +hand: the monad decides which case threads forward and which short-circuits. A built pipeline is +itself a provider for `Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires into a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, exactly +like any other handler. None of the names on these pages is in the prelude: `PipeMonadic` is +imported from `cgp::extra::monad::providers`, and the markers and bind providers from +`cgp::extra::monad::monadic::{ident, ok, err}`. The providers divide into three groups: diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index 8f6c7147..50595f5d 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -1,4 +1,6 @@ --- +title: 'PipeMonadic — a short-circuiting pipeline' +description: 'The provider that composes a Product! list of handlers under a monad marker, so each step runs only on the previous step''s continue case.' sidebar_label: 'PipeMonadic' sidebar_position: 1 --- @@ -11,10 +13,11 @@ branch. ## Overview `PipeMonadic` composes a handler list `Providers` under a monad `M` into one -short-circuiting handler, on a **context**, the type a method runs on. Each step runs only on -the previous step's continue branch, and the monad decides which branch that is. The result is a -provider for `Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires like any other -handler. Like every CGP provider, it carries no runtime value; `M` and the list ride in `PhantomData`. +short-circuiting handler, on a [**context**](/docs/reference/glossary#context), the type the +implementation runs against. Each step runs only on the previous step's continue branch, and the +monad decides which branch that is. The result is a provider for `Computer`, `AsyncComputer`, +`TryComputer`, and `Handler`, so it wires like any other handler. Like every CGP provider, it +carries no runtime value; `M` and the list ride in `PhantomData`. ## Usage @@ -40,26 +43,108 @@ there is worth re-reading, since `ErrMonadic` is the `?`-style monad. ## Examples -Composing a homogeneous list under a base monad. With an `Increment` computer that returns -`Result`, `Ok` on success and `Err("overflow")` on overflow, three under `ErrMonadic` chain on -the `Ok` value and stop at the first error: +A pipeline of three fallible computers, wired under `ErrMonadic` and called through the consumer +trait: ```rust -PipeMonadic::::compute(&context, code, 253) -// 253 -> Ok(254) -> Ok(255) -> Err("overflow") +use cgp::prelude::*; +use cgp::extra::handler::CanCompute; +use cgp::extra::monad::monadic::err::ErrMonadic; +use cgp::extra::monad::providers::PipeMonadic; + +#[cgp_computer] +pub fn increment(value: u8) -> Result { + value.checked_add(1).ok_or("overflow") +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: PipeMonadic, + } +} + +check_components! { + App { + ComputerComponent: ((), u8), + } +} + +pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 1), Ok(4)); + // 253 -> Ok(254) -> Ok(255) -> Err("overflow") + assert_eq!(App.compute(PhantomData::<()>, 253), Err("overflow")); +} ``` -Stacking monads handles nested results. Composing handlers that return `Result, &str>` -under `OkMonadicTrans` stops on an outer `Err` or an inner `Ok`: the err monad handles the -outer `Result` and the ok layer the one inside it. The same list composed under `OkMonadic` can be -driven through the fallible -`try_compute` and async `handle` entry points, because `PipeMonadic` implements `TryComputer` and -`Handler` as well: +Each `Increment` returns `Result`, and under `ErrMonadic` each step runs on the previous +step's `Ok` value, so the first overflow becomes the pipeline's output and the remaining steps do not +run. `App` is an [environmental context](/docs/reference/glossary#environmental-context), and +`Increment` comes from [`#[cgp_computer]`](../../macros/cgp_computer.md). + +Stacking monads handles nested results. These handlers return `Result, &str>`, and +under `OkMonadicTrans` the err monad handles the outer `Result` while the ok layer handles +the one inside it, so the pipeline stops on an outer `Err` or an inner `Ok`: ```rust -PipeMonadic::::try_compute(&context, code, 1) +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::monad::monadic::err::ErrMonadic; +use cgp::extra::monad::monadic::ok::{OkMonadic, OkMonadicTrans}; +use cgp::extra::monad::providers::PipeMonadic; + +#[cgp_computer] +pub fn return_ok_ok(_value: u8) -> Result, &'static str> { + Ok(Ok(())) +} + +#[cgp_computer] +pub fn return_ok_err(value: u8) -> Result, &'static str> { + Ok(Err(value)) +} + +#[cgp_computer] +pub fn return_err(_value: u8) -> Result, &'static str> { + Err("error") +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType<&'static str>, + } +} + +pub fn demo() { + let code = PhantomData::<()>; + + // An inner `Ok` stops the pipeline; the last step never runs. + assert_eq!( + PipeMonadic::, Product![ReturnOkErr, ReturnOkOk, ReturnOkErr]>::compute(&App, code, 1), + Ok(Ok(())), + ); + + // An outer `Err` stops it too. + assert_eq!( + PipeMonadic::, Product![ReturnErr, ReturnOkOk, ReturnOkErr]>::compute(&App, code, 1), + Err("error"), + ); + + // Through the fallible bridge, plain `OkMonadic` behaves the same way. + assert_eq!( + PipeMonadic::::try_compute(&App, code, 1), + Ok(Ok(())), + ); +} ``` +The pipelines are called on the provider directly, through the `Computer` and `TryComputer` provider +traits the prelude supplies, rather than wired. The last call goes through `try_compute`, where +`PipeMonadic` stacks `OkMonadic` over `ErrMonadic` itself and takes the context's error, here +`&'static str`, from the outer `Result`; that is why `App` wires an error type. + ## When to use it **Reach for `PipeMonadic` when a pipeline's steps should short-circuit on a branch**, such as an error @@ -77,8 +162,11 @@ pub struct PipeMonadic(pub PhantomData<(M, Providers)>); ``` It implements `ComputerComponent` and `AsyncComputerComponent` by folding the list: an internal -`BindProviders` computation walks the list so the first provider runs on the input and its result is -bound, through the monad, to the monadically-composed rest of the list. +`BindProviders` computation walks the list so the first provider runs on the input and its result +is bound, through the monad, to the monadically-composed rest of the list. For `[A, B, C]` the +result is `ComposeHandlers>>>`, where `Bind

` is the bind step +the monad produces, such as `BindErr` for `ErrMonadic`. A one-element list is its +only provider, and an empty list builds nothing. For the fallible components `TryComputerComponent` and `HandlerComponent`, it bridges through the err monad. It first maps every provider to [`TryPromote`](../handler/try_promote.md), demoting fallible diff --git a/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.rs b/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.rs new file mode 100644 index 00000000..aa1a2d7d --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.rs @@ -0,0 +1,39 @@ +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::DebugError; +use cgp::prelude::*; + +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self) -> Result<(), Error>; +} + +#[cgp_impl(new LoadOrFail)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self) -> Result<(), Error> { + Err(Self::raise_error("disk offline".to_owned())) + } +} + +pub struct App; + +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + LoaderComponent: LoadOrFail, + + @ErrorRaiserComponent.String: DebugError, + } +} + +check_components! { + App { + LoaderComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.stderr b/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.stderr new file mode 100644 index 00000000..09857bd1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.stderr @@ -0,0 +1,28 @@ +error[E0275]: overflow evaluating the requirement `DebugError: ErrorRaiser` + --> tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.rs:35:9 + | +35 | LoaderComponent, + | ^^^^^^^^^^^^^^^ + | + = note: required for `RedirectLookup>` to implement `ErrorRaiser` + = note: 1 redundant requirement hidden + = note: required for `App` to implement `ErrorRaiser` + = note: required for `App` to implement `cgp::prelude::CanRaiseError` +note: required for `LoadOrFail` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.rs:11:1 + | +11 | #[cgp_impl(new LoadOrFail)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +12 | #[uses(CanRaiseError)] + | --------------------- unsatisfied trait bound introduced here + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/debug_error_common_mistakes_string_key_cycle.rs:33:1 + | +33 | / check_components! { +34 | | App { +35 | | LoaderComponent, +36 | | } +37 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.rs b/example-code/tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.rs new file mode 100644 index 00000000..bc594f89 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.rs @@ -0,0 +1,39 @@ +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::DisplayError; +use cgp::prelude::*; + +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self) -> Result<(), Error>; +} + +#[cgp_impl(new LoadOrFail)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self) -> Result<(), Error> { + Err(Self::raise_error("disk offline".to_owned())) + } +} + +pub struct App; + +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + LoaderComponent: LoadOrFail, + + @ErrorRaiserComponent.String: DisplayError, + } +} + +check_components! { + App { + LoaderComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.stderr b/example-code/tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.stderr new file mode 100644 index 00000000..440ee088 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.stderr @@ -0,0 +1,28 @@ +error[E0275]: overflow evaluating the requirement `DisplayError: ErrorRaiser` + --> tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.rs:35:9 + | +35 | LoaderComponent, + | ^^^^^^^^^^^^^^^ + | + = note: required for `RedirectLookup>` to implement `ErrorRaiser` + = note: 1 redundant requirement hidden + = note: required for `App` to implement `ErrorRaiser` + = note: required for `App` to implement `cgp::prelude::CanRaiseError` +note: required for `LoadOrFail` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.rs:11:1 + | +11 | #[cgp_impl(new LoadOrFail)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +12 | #[uses(CanRaiseError)] + | --------------------- unsatisfied trait bound introduced here + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/display_error_common_mistakes_string_key_cycle.rs:33:1 + | +33 | / check_components! { +34 | | App { +35 | | LoaderComponent, +36 | | } +37 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs b/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs new file mode 100644 index 00000000..2fd70b82 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs @@ -0,0 +1,38 @@ +use core::num::ParseIntError; + +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; +use cgp::prelude::*; + +#[cgp_component(PortParser)] +#[use_type(HasErrorType.Error)] +pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; +} + +#[cgp_impl(new ParsePort)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + raw.parse().map_err(Self::raise_error) + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + PortParserComponent: ParsePort, + } +} + +check_components! { + App { + PortParserComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr b/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr new file mode 100644 index 00000000..074d743a --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr @@ -0,0 +1,68 @@ +error[E0277]: the trait bound `RaiseFrom: ErrorRaiser` is not satisfied + --> tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs:34:9 + | +34 | PortParserComponent, + | ^^^^^^^^^^^^^^^^^^^ the trait `ErrorRaiser` is not implemented for `RaiseFrom` + | +help: the trait `ErrorRaiser` is conditionally implemented for `RaiseFrom` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-error-extra/src/impls/raise_from.rs:5:1 + | + 5 | / impl ErrorRaiser for RaiseFrom + 6 | | where + 7 | | Context: HasErrorType, + 8 | | Context::Error: From, + | |_____________________-------^ + | | + | unsatisfied requirement introduced here: `::Error: From` + = note: required for `App` to implement `ErrorRaiser` + = note: required for `App` to implement `cgp::prelude::CanRaiseError` +note: required for `ParsePort` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs:13:1 + | +13 | #[cgp_impl(new ParsePort)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +14 | #[uses(CanRaiseError)] + | ---------------------------- unsatisfied trait bound introduced here + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs:32:1 + | +32 | / check_components! { +33 | | App { +34 | | PortParserComponent, +35 | | } +36 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `String: From` is not satisfied + --> tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs:34:9 + | +34 | PortParserComponent, + | ^^^^^^^^^^^^^^^^^^^ the trait `From` is not implemented for `String` + | + = help: `String` implements trait `From`: + From<&String> + From<&mut str> + From<&str> + From> + From> + From + = note: required for `RaiseFrom` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `App` to implement `IsProviderFor` + = note: required for `App` to implement `ErrorRaiser` + = note: required for `App` to implement `cgp::prelude::CanRaiseError` + = note: 1 redundant requirement hidden + = note: required for `ParsePort` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.rs:32:1 + | +32 | / check_components! { +33 | | App { +34 | | PortParserComponent, +35 | | } +36 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/providers/error/debug_error.rs b/example-code/tests/reference/providers/error/debug_error.rs index 6584eb50..9f5aaaa0 100644 --- a/example-code/tests/reference/providers/error/debug_error.rs +++ b/example-code/tests/reference/providers/error/debug_error.rs @@ -1,30 +1,29 @@ //! Code from `docs/reference/providers/error/debug_error.md` — `DebugError`. +//! +//! Pins the Examples program: a `ParseIntError` is formatted with `Debug` and forwarded to the +//! `String` entry, which `RaiseFrom` converts. The `String` key wired to `DebugError` itself, +//! from Common Mistakes, is a trybuild fixture. -/// ## Usage and Examples -/// -/// `DebugError` formats a `Debug` source into a `String` and forwards it to the context's own -/// `String` route, which `RaiseFrom` converts. A `String` entry must be present for it to forward -/// to. -pub mod formatting_through_debug { +/// ## Examples +pub mod examples { use core::num::ParseIntError; use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::error::{DebugError, RaiseFrom}; use cgp::prelude::*; - #[cgp_component(Parser)] + #[cgp_component(PortParser)] #[use_type(HasErrorType.Error)] - pub trait CanParse { - fn parse(&self, raw: &str) -> Result; + pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; } - #[cgp_impl(new ParseNumber)] + #[cgp_impl(new ParsePort)] #[uses(CanRaiseError)] #[use_type(HasErrorType.Error)] - impl Parser { - fn parse(&self, raw: &str) -> Result { - let parsed = raw.parse().map_err(Self::raise_error)?; - Ok(parsed) + impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + raw.parse().map_err(Self::raise_error) } } @@ -35,21 +34,29 @@ pub mod formatting_through_debug { open ErrorRaiserComponent; ErrorTypeProviderComponent: UseType, - ParserComponent: ParseNumber, + PortParserComponent: ParsePort, @ErrorRaiserComponent.String: RaiseFrom, @ErrorRaiserComponent.ParseIntError: DebugError, } } - mod check_app { - use super::*; - check_components! { App { ParserComponent } } + check_components! { + App { + PortParserComponent, + } + } + + pub fn demo() { + assert_eq!(App.parse_port("8080"), Ok(8080)); + assert_eq!( + App.parse_port("http"), + Err("ParseIntError { kind: InvalidDigit }".to_owned()) + ); } #[test] - fn a_parse_error_is_carried_as_its_debug_output() { - assert_eq!(App.parse("42").unwrap(), 42); - assert!(App.parse("nope").unwrap_err().contains("ParseIntError")); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/error/discard_detail.rs b/example-code/tests/reference/providers/error/discard_detail.rs index 6d3434d4..013f47e2 100644 --- a/example-code/tests/reference/providers/error/discard_detail.rs +++ b/example-code/tests/reference/providers/error/discard_detail.rs @@ -1,14 +1,11 @@ //! Code from `docs/reference/providers/error/discard_detail.md` — `DiscardDetail`. +//! +//! Pins the Examples program: an error is raised, wrapped with a detail string, and the wrapper +//! `DiscardDetail` drops the detail so the base error propagates unchanged. -/// ## Usage and Examples -/// -/// `DiscardDetail` satisfies the wrapping trait by returning the error and dropping the detail. -/// Here a base error is raised and then wrapped with a detail string; because the wrapper is -/// `DiscardDetail`, the detail is discarded and the base error propagates unchanged. -pub mod wrapping_by_discarding { - use cgp::core::error::{ - ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapperComponent, - }; +/// ## Examples +pub mod examples { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapperComponent}; use cgp::extra::error::{DiscardDetail, RaiseFrom}; use cgp::prelude::*; @@ -18,14 +15,13 @@ pub mod wrapping_by_discarding { fn load(&self) -> Result<(), Error>; } - #[cgp_impl(new LoadWithContext)] + #[cgp_impl(new LoadConfig)] #[uses(CanRaiseError, CanWrapError)] #[use_type(HasErrorType.Error)] impl Loader { fn load(&self) -> Result<(), Error> { - let base = Self::raise_error("disk offline".to_owned()); - // The detail is attached here, but the wrapper is free to drop it. - Err(Self::wrap_error(base, "while loading config".to_owned())) + let error = Self::raise_error("disk offline".to_owned()); + Err(Self::wrap_error(error, "while loading config".to_owned())) } } @@ -33,23 +29,25 @@ pub mod wrapping_by_discarding { delegate_components! { App { - open ErrorRaiserComponent; - ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, ErrorWrapperComponent: DiscardDetail, - LoaderComponent: LoadWithContext, + LoaderComponent: LoadConfig, + } + } - @ErrorRaiserComponent.String: RaiseFrom, + check_components! { + App { + LoaderComponent, } } - mod check_app { - use super::*; - check_components! { App { LoaderComponent } } + pub fn demo() { + assert_eq!(App.load(), Err("disk offline".to_owned())); } #[test] - fn the_detail_is_dropped_and_the_error_is_unchanged() { - assert_eq!(App.load().unwrap_err(), "disk offline"); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/error/display_error.rs b/example-code/tests/reference/providers/error/display_error.rs index 333722c8..b7bafc56 100644 --- a/example-code/tests/reference/providers/error/display_error.rs +++ b/example-code/tests/reference/providers/error/display_error.rs @@ -1,29 +1,29 @@ //! Code from `docs/reference/providers/error/display_error.md` — `DisplayError`. +//! +//! Pins the Examples program: a `ParseIntError` is formatted with `Display` and forwarded to the +//! `String` entry, which `RaiseFrom` converts. The `String` key wired to `DisplayError` itself, +//! from Common Mistakes, is a trybuild fixture. -/// ## Usage and Examples -/// -/// `DisplayError` formats a `Display` source into a `String` through `to_string()` and forwards it -/// to the context's `String` route. A `String` entry must be present for it to forward to. -pub mod formatting_through_display { +/// ## Examples +pub mod examples { use core::num::ParseIntError; use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::error::{DisplayError, RaiseFrom}; use cgp::prelude::*; - #[cgp_component(Parser)] + #[cgp_component(PortParser)] #[use_type(HasErrorType.Error)] - pub trait CanParse { - fn parse(&self, raw: &str) -> Result; + pub trait CanParsePort { + fn parse_port(&self, raw: &str) -> Result; } - #[cgp_impl(new ParseNumber)] + #[cgp_impl(new ParsePort)] #[uses(CanRaiseError)] #[use_type(HasErrorType.Error)] - impl Parser { - fn parse(&self, raw: &str) -> Result { - let parsed = raw.parse().map_err(Self::raise_error)?; - Ok(parsed) + impl PortParser { + fn parse_port(&self, raw: &str) -> Result { + raw.parse().map_err(Self::raise_error) } } @@ -34,25 +34,29 @@ pub mod formatting_through_display { open ErrorRaiserComponent; ErrorTypeProviderComponent: UseType, - ParserComponent: ParseNumber, + PortParserComponent: ParsePort, @ErrorRaiserComponent.String: RaiseFrom, @ErrorRaiserComponent.ParseIntError: DisplayError, } } - mod check_app { - use super::*; - check_components! { App { ParserComponent } } + check_components! { + App { + PortParserComponent, + } } - #[test] - fn a_parse_error_is_carried_as_its_display_message() { - assert_eq!(App.parse("42").unwrap(), 42); - // The `Display` of `ParseIntError` reads "invalid digit found in string". + pub fn demo() { + assert_eq!(App.parse_port("8080"), Ok(8080)); assert_eq!( - App.parse("nope").unwrap_err(), - "invalid digit found in string" + App.parse_port("http"), + Err("invalid digit found in string".to_owned()) ); } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/providers/error/panic_on_error.rs b/example-code/tests/reference/providers/error/panic_on_error.rs index 267e8af9..844fadc6 100644 --- a/example-code/tests/reference/providers/error/panic_on_error.rs +++ b/example-code/tests/reference/providers/error/panic_on_error.rs @@ -1,11 +1,10 @@ //! Code from `docs/reference/providers/error/panic_on_error.md` — `PanicOnError`. +//! +//! Pins the Examples program: a raise on `TestApp` panics with the source's `Debug` output. The +//! `#[should_panic]` test is what pins that behavior. -/// ## Usage and Examples -/// -/// `PanicOnError` raises by panicking with the source error's `Debug` output rather than returning -/// an error value. It suits a context that treats an error as a fault to abort on, such as a test -/// harness. The `#[should_panic]` test is what pins that behavior. -pub mod aborting_on_error { +/// ## Examples +pub mod examples { use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; use cgp::extra::error::PanicOnError; use cgp::prelude::*; @@ -35,14 +34,19 @@ pub mod aborting_on_error { } } - mod check_test_app { - use super::*; - check_components! { TestApp { RunnerComponent } } + check_components! { + TestApp { + RunnerComponent, + } + } + + pub fn demo() { + let _ = TestApp.run(); // panics with "\"unrecoverable\"" } #[test] - #[should_panic] - fn raising_aborts_the_program() { - let _ = TestApp.run(); + #[should_panic(expected = "\"unrecoverable\"")] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/error/raise_from.rs b/example-code/tests/reference/providers/error/raise_from.rs index a4a045fc..1d4f015a 100644 --- a/example-code/tests/reference/providers/error/raise_from.rs +++ b/example-code/tests/reference/providers/error/raise_from.rs @@ -1,20 +1,35 @@ //! Code from `docs/reference/providers/error/raise_from.md` — `RaiseFrom`. +//! +//! Pins the Usage wiring and the Examples program, in which one `ErrorRaiserComponent: RaiseFrom` +//! entry raises two different source types through the error's `From` impls. The source with no +//! `From` impl, from Common Mistakes, is a trybuild fixture. -/// ## Usage and Examples -/// -/// The page shows `RaiseFrom` wired on its own, then dispatched per source type beside a formatter. -/// One program covers both: a `String` is converted straight through `RaiseFrom` (the abstract error -/// *is* `String`, and `String: From`), while a `ParseIntError` is formatted by `DebugError` -/// and forwarded back through the same `String` route. -/// -/// The page's illustrative `ParseError` key is a real `ParseIntError` here, so the parse can run. -pub mod raising_through_from { +/// ## Examples +pub mod examples { use core::num::ParseIntError; use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::extra::error::RaiseFrom; use cgp::prelude::*; + #[derive(Debug, PartialEq)] + pub enum AppError { + Parse(ParseIntError), + Message(String), + } + + impl From for AppError { + fn from(e: ParseIntError) -> Self { + AppError::Parse(e) + } + } + + impl From for AppError { + fn from(message: String) -> Self { + AppError::Message(message) + } + } + #[cgp_component(PortParser)] #[use_type(HasErrorType.Error)] pub trait CanParsePort { @@ -26,14 +41,13 @@ pub mod raising_through_from { #[use_type(HasErrorType.Error)] impl PortParser { fn parse_port(&self, raw: &str) -> Result { - let parsed: u32 = raw.parse().map_err(Self::raise_error)?; + let port: u16 = raw.parse().map_err(Self::raise_error)?; - if parsed > u16::MAX as u32 { - // Raised as a `String`, converted straight through by `RaiseFrom`. - return Err(Self::raise_error(format!("port {parsed} out of range"))); + if port == 0 { + return Err(Self::raise_error("port 0 is reserved".to_owned())); } - Ok(parsed as u16) + Ok(port) } } @@ -41,31 +55,29 @@ pub mod raising_through_from { delegate_components! { App { - open ErrorRaiserComponent; - - ErrorTypeProviderComponent: UseType, + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, PortParserComponent: ParsePort, - - @ErrorRaiserComponent.String: RaiseFrom, - @ErrorRaiserComponent.ParseIntError: DebugError, } } - mod check_app { - use super::*; - check_components! { App { PortParserComponent } } + check_components! { + App { + PortParserComponent, + } } - #[test] - fn a_string_is_converted_and_a_parse_error_is_formatted() { - assert_eq!(App.parse_port("8080").unwrap(), 8080); + pub fn demo() { + assert_eq!(App.parse_port("8080"), Ok(8080)); assert_eq!( - App.parse_port("70000").unwrap_err(), - "port 70000 out of range" + App.parse_port("0"), + Err(AppError::Message("port 0 is reserved".to_owned())) ); - assert!(App - .parse_port("nope") - .unwrap_err() - .contains("ParseIntError")); + assert!(matches!(App.parse_port("http"), Err(AppError::Parse(_)))); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/error/raise_infallible.rs b/example-code/tests/reference/providers/error/raise_infallible.rs index 71fe9890..63646d0b 100644 --- a/example-code/tests/reference/providers/error/raise_infallible.rs +++ b/example-code/tests/reference/providers/error/raise_infallible.rs @@ -1,12 +1,11 @@ //! Code from `docs/reference/providers/error/raise_infallible.md` — `RaiseInfallible`. +//! +//! Pins the Examples program: a provider raises an `Infallible` error uniformly, and the context fills +//! that raiser slot with `RaiseInfallible`. The value is never constructed, so the raise path is wired +//! but never taken. -/// ## Usage and Examples -/// -/// `RaiseInfallible` fills the raiser slot for `core::convert::Infallible` on a context whose -/// operation cannot fail. The `Infallible` value is never constructed, so the raise path is wired -/// but never taken at run time; `check_components!` is what proves the wiring resolves. A second -/// source, a `String`, uses `RaiseFrom` beside it. -pub mod absorbing_an_impossible_error { +/// ## Examples +pub mod examples { use core::convert::Infallible; use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; @@ -24,8 +23,7 @@ pub mod absorbing_an_impossible_error { #[use_type(HasErrorType.Error)] impl Runner { fn run(&self) -> Result<(), Error> { - // A step that cannot fail. Its `Infallible` error is raised uniformly, which lets this - // provider be wired the same way as one whose step can fail. + // A step that cannot fail, raised the same way a fallible step would be. let outcome: Result<(), Infallible> = Ok(()); outcome.map_err(Self::raise_error)?; Ok(()) @@ -46,13 +44,18 @@ pub mod absorbing_an_impossible_error { } } - mod check_app { - use super::*; - check_components! { App { RunnerComponent } } + check_components! { + App { + RunnerComponent, + } } - #[test] - fn the_infallible_step_runs() { + pub fn demo() { assert_eq!(App.run(), Ok(())); } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/providers/error/return_error.rs b/example-code/tests/reference/providers/error/return_error.rs index 134da5b8..cb9c9f34 100644 --- a/example-code/tests/reference/providers/error/return_error.rs +++ b/example-code/tests/reference/providers/error/return_error.rs @@ -1,12 +1,41 @@ //! Code from `docs/reference/providers/error/return_error.md` — `ReturnError`. +//! +//! Pins the Examples program: an `AppError` source is raised through `ReturnError` by returning it, +//! beside a `String` converted by `RaiseFrom` and a `ParseIntError` formatted by `DebugError`. -/// ## Usage and Examples +/// ## Usage /// -/// `ReturnError` raises a source that already *is* the context's error type, so it returns its -/// argument. Here the context's error is `AppError`: an `AppError` source is raised through -/// `ReturnError`, and a `ParseIntError` is formatted and forwarded to the `String` route that -/// `RaiseFrom` converts (`AppError: From`). -pub mod returning_the_error_itself { +/// The whole-component wiring the section shows: every raise on the context goes to `ReturnError`, +/// which type-checks only for the source equal to the context's error. +pub mod usage { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::ReturnError; + use cgp::prelude::*; + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: ReturnError, + } + } + + pub fn raise_own_error(message: String) -> Context::Error + where + Context: CanRaiseError, + { + Context::raise_error(message) + } + + #[test] + fn the_source_is_returned_unchanged() { + assert_eq!(raise_own_error::("reserved".to_owned()), "reserved"); + } +} + +/// ## Examples +pub mod examples { use core::num::ParseIntError; use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; @@ -24,27 +53,26 @@ pub mod returning_the_error_itself { } } - #[cgp_component(Checker)] + #[cgp_component(PortChecker)] #[use_type(HasErrorType.Error)] - pub trait CanCheck { - fn check(&self, raw: &str) -> Result; + pub trait CanCheckPort { + fn check_port(&self, raw: &str) -> Result; } #[cgp_impl(new CheckPort)] #[uses(CanRaiseError, CanRaiseError)] #[use_type(HasErrorType.{Error = AppError})] - impl Checker { - fn check(&self, raw: &str) -> Result { - let parsed: u32 = raw.parse().map_err(Self::raise_error)?; + impl PortChecker { + fn check_port(&self, raw: &str) -> Result { + let port: u16 = raw.parse().map_err(Self::raise_error)?; - if parsed == 0 { - // Already an `AppError`, raised by returning it. + if port == 0 { return Err(Self::raise_error(AppError { message: "port 0 is reserved".to_owned(), })); } - Ok(parsed as u16) + Ok(port) } } @@ -55,7 +83,7 @@ pub mod returning_the_error_itself { open ErrorRaiserComponent; ErrorTypeProviderComponent: UseType, - CheckerComponent: CheckPort, + PortCheckerComponent: CheckPort, @ErrorRaiserComponent.AppError: ReturnError, @ErrorRaiserComponent.String: RaiseFrom, @@ -63,19 +91,23 @@ pub mod returning_the_error_itself { } } - mod check_app { - use super::*; - check_components! { App { CheckerComponent } } + check_components! { + App { + PortCheckerComponent, + } } - #[test] - fn an_app_error_source_is_returned_unchanged() { - assert_eq!(App.check("8080").unwrap(), 8080); + pub fn demo() { + assert_eq!(App.check_port("8080"), Ok(8080)); assert_eq!( - App.check("0").unwrap_err(), - AppError { - message: "port 0 is reserved".to_owned() - }, + App.check_port("0"), + Err(AppError { message: "port 0 is reserved".to_owned() }) ); + assert!(App.check_port("http").unwrap_err().message.contains("ParseIntError")); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/monad/bind_err.rs b/example-code/tests/reference/providers/monad/bind_err.rs index fbf90573..c173e4bd 100644 --- a/example-code/tests/reference/providers/monad/bind_err.rs +++ b/example-code/tests/reference/providers/monad/bind_err.rs @@ -1,12 +1,13 @@ //! Code from `docs/reference/providers/monad/bind_err.md` — `BindErr`. +//! +//! Pins the Examples program: one err-monad bind step built by hand inside a `PipeHandlers` list, +//! which is what `PipeMonadic` composes internally under `ErrMonadic`. -/// ## Usage and Examples -/// -/// `BindErr` is one bind step of the err monad: it runs its continuation on the `Ok` value and -/// short-circuits on `Err`. This is what `PipeMonadic` composes internally under `ErrMonadic`; the -/// page shows it built by hand inside a `PipeHandlers` list, which is the one time it is named -/// directly. -pub mod one_hand_built_bind_step { +/// ## Examples +pub mod examples { + use cgp::extra::handler::PipeHandlers; + use cgp::extra::monad::monadic::err::BindErr; + use cgp::extra::monad::monadic::ident::IdentMonadic; use cgp::prelude::*; #[cgp_computer] @@ -14,30 +15,19 @@ pub mod one_hand_built_bind_step { value.checked_add(1).ok_or("overflow") } - #[test] - fn the_bind_runs_the_continuation_on_the_ok_value() { - use cgp::extra::handler::PipeHandlers; - use cgp::extra::monad::monadic::err::BindErr; - use cgp::extra::monad::monadic::ident::IdentMonadic; + pub type Pipeline = PipeHandlers]>; + + pub fn demo() { + let code = PhantomData::<()>; // 1 -> Ok(2); BindErr runs the second Increment on 2 -> Ok(3). - assert_eq!( - PipeHandlers::]>::compute( - &(), - PhantomData::<()>, - 1u8, - ), - Ok(3), - ); + assert_eq!(Pipeline::compute(&(), code, 1), Ok(3)); + // The first step overflows, so the bind skips the second. + assert_eq!(Pipeline::compute(&(), code, 255), Err("overflow")); + } - // The first step overflows, so the bind short-circuits and the continuation never runs. - assert_eq!( - PipeHandlers::]>::compute( - &(), - PhantomData::<()>, - 255u8, - ), - Err("overflow"), - ); + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/monad/bind_ok.rs b/example-code/tests/reference/providers/monad/bind_ok.rs index 7a371cc8..c27f526a 100644 --- a/example-code/tests/reference/providers/monad/bind_ok.rs +++ b/example-code/tests/reference/providers/monad/bind_ok.rs @@ -1,53 +1,40 @@ //! Code from `docs/reference/providers/monad/bind_ok.md` — `BindOk`. +//! +//! Pins the Examples program: one ok-monad bind step built by hand inside a `PipeHandlers` list, which +//! runs a fallback on the `Err` value and stops on `Ok`. -/// ## Usage and Examples -/// -/// `BindOk` is the mirror of `BindErr`: it runs its continuation on the `Err` value and -/// short-circuits on `Ok`, which is the fallback behavior `PipeMonadic` composes under `OkMonadic`. -/// The page shows it built by hand inside a `PipeHandlers` list. -pub mod one_hand_built_bind_step { +/// ## Examples +pub mod examples { + use cgp::extra::handler::PipeHandlers; + use cgp::extra::monad::monadic::ident::IdentMonadic; + use cgp::extra::monad::monadic::ok::BindOk; use cgp::prelude::*; /// Accept a small value, or hand a too-large one to the fallback as an `Err`. #[cgp_computer] pub fn classify(value: u8) -> Result { - if value < 10 { - Ok(value) - } else { - Err(value) - } + if value < 10 { Ok(value) } else { Err(value) } } - /// The fallback: run only on the `Err` branch, halving the rejected value. + /// The fallback, run only on the `Err` branch: halve the rejected value. #[cgp_computer] pub fn halve(value: u8) -> Result { Ok(value / 2) } - #[test] - fn the_bind_runs_the_continuation_on_the_err_value() { - use cgp::extra::handler::PipeHandlers; - use cgp::extra::monad::monadic::ident::IdentMonadic; - use cgp::extra::monad::monadic::ok::BindOk; + pub type Pipeline = PipeHandlers]>; - // 5 is accepted, so BindOk short-circuits and the fallback never runs. - assert_eq!( - PipeHandlers::]>::compute( - &(), - PhantomData::<()>, - 5u8, - ), - Ok(5), - ); + pub fn demo() { + let code = PhantomData::<()>; + // 5 is accepted, so BindOk stops and the fallback never runs. + assert_eq!(Pipeline::compute(&(), code, 5), Ok(5)); // 20 is rejected, so BindOk runs the fallback on the Err value: 20 -> 10. - assert_eq!( - PipeHandlers::]>::compute( - &(), - PhantomData::<()>, - 20u8, - ), - Ok(10), - ); + assert_eq!(Pipeline::compute(&(), code, 20), Ok(10)); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/monad/pipe_monadic.rs b/example-code/tests/reference/providers/monad/pipe_monadic.rs index 84c8cc52..83134dc1 100644 --- a/example-code/tests/reference/providers/monad/pipe_monadic.rs +++ b/example-code/tests/reference/providers/monad/pipe_monadic.rs @@ -1,17 +1,16 @@ //! Code from `docs/reference/providers/monad/pipe_monadic.md` — `PipeMonadic`. +//! +//! Pins both Examples programs: a pipeline of fallible computers wired under `ErrMonadic`, and a +//! pipeline over nested `Result`s under a stacked monad, driven through `compute` and, through the +//! fallible bridge, `try_compute`. -/// ## Usage and Examples -/// -/// `PipeMonadic` composes a handler list under a monad into one short-circuiting handler. Under -/// `ErrMonadic` each step runs on the previous step's `Ok` value and the first `Err` becomes the -/// output. The composed pipeline is wired like any other computation. -pub mod chaining_under_a_monad { - use cgp::extra::handler::ComputerComponent; +/// ## Examples +pub mod examples { + use cgp::extra::handler::CanCompute; use cgp::extra::monad::monadic::err::ErrMonadic; use cgp::extra::monad::providers::PipeMonadic; use cgp::prelude::*; - /// A fallible step: succeeds with the next value, or reports an overflow. #[cgp_computer] pub fn increment(value: u8) -> Result { value.checked_add(1).ok_or("overflow") @@ -25,35 +24,80 @@ pub mod chaining_under_a_monad { } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), u8), - } + check_components! { + App { + ComputerComponent: ((), u8), } } + pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 1), Ok(4)); + // 253 -> Ok(254) -> Ok(255) -> Err("overflow") + assert_eq!(App.compute(PhantomData::<()>, 253), Err("overflow")); + } + #[test] - fn the_first_error_becomes_the_output() { - use cgp::extra::handler::CanCompute; + fn test_demo() { + demo(); + } - // Three successful steps. - assert_eq!(App.compute(PhantomData::<()>, 1u8), Ok(4)); + /// The stacked-monad example: nested `Result`s under `OkMonadicTrans`, and the same + /// handlers under plain `OkMonadic` through `try_compute`. + pub mod stacked { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::monad::monadic::err::ErrMonadic; + use cgp::extra::monad::monadic::ok::{OkMonadic, OkMonadicTrans}; + use cgp::extra::monad::providers::PipeMonadic; + use cgp::prelude::*; - // The third step overflows, and the remaining steps do not run. - assert_eq!(App.compute(PhantomData::<()>, 253u8), Err("overflow")); - } + #[cgp_computer] + pub fn return_ok_ok(_value: u8) -> Result, &'static str> { + Ok(Ok(())) + } - #[test] - fn invoked_directly_without_wiring() { - assert_eq!( - PipeMonadic::::compute( - &App, - PhantomData::<()>, - 1u8, - ), - Ok(4), - ); + #[cgp_computer] + pub fn return_ok_err(value: u8) -> Result, &'static str> { + Ok(Err(value)) + } + + #[cgp_computer] + pub fn return_err(_value: u8) -> Result, &'static str> { + Err("error") + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType<&'static str>, + } + } + + pub fn demo() { + let code = PhantomData::<()>; + + // An inner `Ok` stops the pipeline; the last step never runs. + assert_eq!( + PipeMonadic::, Product![ReturnOkErr, ReturnOkOk, ReturnOkErr]>::compute(&App, code, 1), + Ok(Ok(())), + ); + + // An outer `Err` stops it too. + assert_eq!( + PipeMonadic::, Product![ReturnErr, ReturnOkOk, ReturnOkErr]>::compute(&App, code, 1), + Err("error"), + ); + + // Through the fallible bridge, plain `OkMonadic` behaves the same way. + assert_eq!( + PipeMonadic::::try_compute(&App, code, 1), + Ok(Ok(())), + ); + } + + #[test] + fn test_demo() { + demo(); + } } } From 060d6bf944a025199a361360f75ce04ba5b0b0b9 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 03:33:29 +0000 Subject: [PATCH 129/516] Tighten the P2 provider pages after review - DebugError and DisplayError: the Usage fragments import the ParseIntError they key on, DebugError's overview no longer shows an argument-less format! call, and a fixture now pins the wrap-side String cycle the page states alongside the raise-side one. - ReturnError: the example's prose no longer implies the provider raises a String directly; the String comes from DebugError. - PipeMonadic: the stacked-monad calls are formatted rustfmt-style on the page and in the mirror instead of running far past the width. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/providers/error/debug_error.md | 5 ++- .../providers/error/display_error.md | 1 + .../reference/providers/error/return_error.md | 6 +-- .../reference/providers/monad/pipe_monadic.md | 15 +++++-- ...error_common_mistakes_string_wrap_cycle.rs | 41 +++++++++++++++++++ ...r_common_mistakes_string_wrap_cycle.stderr | 28 +++++++++++++ .../reference/providers/monad/pipe_monadic.rs | 15 +++++-- 7 files changed, 100 insertions(+), 11 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.rs create mode 100644 example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.stderr diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index 91021901..27c1db24 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -13,8 +13,8 @@ string handling. ## Overview `DebugError` implements both error components by redirecting through a string. Rather than producing -the abstract error directly, it formats the source error or the detail with the `Debug` trait and -`format!("{:?}")` into a `String`, then forwards to the +the abstract error directly, it formats the source error or the detail with the `Debug` trait, as +`{:?}` would print it, into a `String`, then forwards to the [**context**](/docs/reference/glossary#context)'s own `CanRaiseError` or `CanWrapError`, where the context is the type the implementation runs against. It does not know the context's error type: it turns a `Debug` value into a `String` and hands it off, leaving @@ -33,6 +33,7 @@ because it allocates a `String`. It takes no type parameter and is wired to `Err `ErrorWrapperComponent`, or both, usually per source type with the `open` statement: ```rust +use core::num::ParseIntError; use cgp::core::error::ErrorRaiserComponent; use cgp::extra::error::{DebugError, RaiseFrom}; diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md index 5df55b0d..e0c5951c 100644 --- a/docs/reference/providers/error/display_error.md +++ b/docs/reference/providers/error/display_error.md @@ -32,6 +32,7 @@ because it allocates a `String`. It takes no type parameter and is wired to `Err `ErrorWrapperComponent`, or both, usually per source type with the `open` statement: ```rust +use core::num::ParseIntError; use cgp::core::error::ErrorRaiserComponent; use cgp::extra::error::{DisplayError, RaiseFrom}; diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md index 6292c29b..85a5745b 100644 --- a/docs/reference/providers/error/return_error.md +++ b/docs/reference/providers/error/return_error.md @@ -112,9 +112,9 @@ pub fn demo() { `CheckPort` pins the error to `AppError` with `#[use_type]`'s equality form, so it can construct one and raise it. `App` is an [environmental context](/docs/reference/glossary#environmental-context) -whose table routes each source: the `AppError` through `ReturnError`, a `String` through `RaiseFrom` -and `AppError`'s `From`, and a `ParseIntError` through [`DebugError`](debug_error.md), which -formats it and forwards it to the `String` entry. +whose table routes each source: the `AppError` through `ReturnError`, and a `ParseIntError` through +[`DebugError`](debug_error.md), which formats it and forwards the resulting `String` to the `String` +entry, where `RaiseFrom` converts it through `AppError`'s `From`. ## When to use it diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index 50595f5d..f64eab42 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -122,19 +122,28 @@ pub fn demo() { // An inner `Ok` stops the pipeline; the last step never runs. assert_eq!( - PipeMonadic::, Product![ReturnOkErr, ReturnOkOk, ReturnOkErr]>::compute(&App, code, 1), + PipeMonadic::< + OkMonadicTrans, + Product![ReturnOkErr, ReturnOkOk, ReturnOkErr], + >::compute(&App, code, 1), Ok(Ok(())), ); // An outer `Err` stops it too. assert_eq!( - PipeMonadic::, Product![ReturnErr, ReturnOkOk, ReturnOkErr]>::compute(&App, code, 1), + PipeMonadic::< + OkMonadicTrans, + Product![ReturnErr, ReturnOkOk, ReturnOkErr], + >::compute(&App, code, 1), Err("error"), ); // Through the fallible bridge, plain `OkMonadic` behaves the same way. assert_eq!( - PipeMonadic::::try_compute(&App, code, 1), + PipeMonadic::< + OkMonadic, + Product![ReturnOkErr, ReturnOkOk, ReturnOkErr], + >::try_compute(&App, code, 1), Ok(Ok(())), ); } diff --git a/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.rs b/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.rs new file mode 100644 index 00000000..9fd14d7a --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.rs @@ -0,0 +1,41 @@ +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapperComponent}; +use cgp::extra::error::{DebugError, RaiseFrom}; +use cgp::prelude::*; + +#[cgp_component(Loader)] +#[use_type(HasErrorType.Error)] +pub trait CanLoad { + fn load(&self) -> Result<(), Error>; +} + +#[cgp_impl(new LoadWithDetail)] +#[uses(CanRaiseError, CanWrapError)] +#[use_type(HasErrorType.Error)] +impl Loader { + fn load(&self) -> Result<(), Error> { + let error = Self::raise_error("disk offline".to_owned()); + Err(Self::wrap_error(error, "while loading config".to_owned())) + } +} + +pub struct App; + +delegate_components! { + App { + open ErrorWrapperComponent; + + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + LoaderComponent: LoadWithDetail, + + @ErrorWrapperComponent.String: DebugError, + } +} + +check_components! { + App { + LoaderComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.stderr b/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.stderr new file mode 100644 index 00000000..97322697 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.stderr @@ -0,0 +1,28 @@ +error[E0275]: overflow evaluating the requirement `DebugError: ErrorWrapper` + --> tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.rs:37:9 + | +37 | LoaderComponent, + | ^^^^^^^^^^^^^^^ + | + = note: required for `RedirectLookup>` to implement `ErrorWrapper` + = note: 1 redundant requirement hidden + = note: required for `App` to implement `ErrorWrapper` + = note: required for `App` to implement `cgp::prelude::CanWrapError` +note: required for `LoadWithDetail` to implement `IsProviderFor` + --> tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.rs:11:1 + | +11 | #[cgp_impl(new LoadWithDetail)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +12 | #[uses(CanRaiseError, CanWrapError)] + | -------------------- unsatisfied trait bound introduced here + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/debug_error_common_mistakes_string_wrap_cycle.rs:35:1 + | +35 | / check_components! { +36 | | App { +37 | | LoaderComponent, +38 | | } +39 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/providers/monad/pipe_monadic.rs b/example-code/tests/reference/providers/monad/pipe_monadic.rs index 83134dc1..612b2ec6 100644 --- a/example-code/tests/reference/providers/monad/pipe_monadic.rs +++ b/example-code/tests/reference/providers/monad/pipe_monadic.rs @@ -78,19 +78,28 @@ pub mod examples { // An inner `Ok` stops the pipeline; the last step never runs. assert_eq!( - PipeMonadic::, Product![ReturnOkErr, ReturnOkOk, ReturnOkErr]>::compute(&App, code, 1), + PipeMonadic::< + OkMonadicTrans, + Product![ReturnOkErr, ReturnOkOk, ReturnOkErr], + >::compute(&App, code, 1), Ok(Ok(())), ); // An outer `Err` stops it too. assert_eq!( - PipeMonadic::, Product![ReturnErr, ReturnOkOk, ReturnOkErr]>::compute(&App, code, 1), + PipeMonadic::< + OkMonadicTrans, + Product![ReturnErr, ReturnOkOk, ReturnOkErr], + >::compute(&App, code, 1), Err("error"), ); // Through the fallible bridge, plain `OkMonadic` behaves the same way. assert_eq!( - PipeMonadic::::try_compute(&App, code, 1), + PipeMonadic::< + OkMonadic, + Product![ReturnOkErr, ReturnOkOk, ReturnOkErr], + >::try_compute(&App, code, 1), Ok(Ok(())), ); } From 7db3cda5f061b4b0b89cdd22bdcc8066dfd1dca6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 03:47:20 +0000 Subject: [PATCH 130/516] Revise the providers/handler reference pages Resync the 14 handler-combinator pages with the cgp source and the knowledge base: PromoteHandler's base is an AsyncComputer returning Result, PromoteTryComputer's Handler entry needs its base wired to the bundle, and ComposeHandlers and ReturnInput have no Ref impls. Add front matter, full Examples ported from the mirrors, and Common Mistakes for the bundles, with a fixture pinning a hand-written base. Drop the Generated machinery notice from the single-step promotions, which readers write by hand, and give UseInputDelegate its exact expansion. The front matter extends the description sweep to providers/handler/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../providers/handler/compose_handlers.md | 76 +++++--- docs/reference/providers/handler/index.md | 87 +++++---- .../providers/handler/pipe_handlers.md | 103 +++++++---- docs/reference/providers/handler/promote.md | 129 ++++++++++---- .../providers/handler/promote_async.md | 123 ++++++++++--- .../handler/promote_async_computer.md | 107 ++++++++--- .../providers/handler/promote_computer.md | 134 +++++++++++--- .../providers/handler/promote_handler.md | 113 +++++++++--- .../providers/handler/promote_producer.md | 127 +++++++++++--- .../providers/handler/promote_ref.md | 145 +++++++++++---- .../providers/handler/promote_try_computer.md | 133 +++++++++++--- .../providers/handler/return_input.md | 66 ++++--- .../providers/handler/try_promote.md | 135 ++++++++++---- .../providers/handler/use_input_delegate.md | 166 +++++++++++++----- ...puter_common_mistakes_hand_written_base.rs | 31 ++++ ...r_common_mistakes_hand_written_base.stderr | 66 +++++++ .../providers/handler/compose_handlers.rs | 30 ++-- .../providers/handler/pipe_handlers.rs | 79 +++++---- .../reference/providers/handler/promote.rs | 62 ++++--- .../providers/handler/promote_async.rs | 69 +++++--- .../handler/promote_async_computer.rs | 52 +++--- .../providers/handler/promote_computer.rs | 92 ++++++---- .../providers/handler/promote_handler.rs | 55 +++--- .../providers/handler/promote_producer.rs | 57 +++--- .../providers/handler/promote_ref.rs | 52 +++--- .../providers/handler/promote_try_computer.rs | 93 ++++++---- .../providers/handler/return_input.rs | 51 ++++-- .../providers/handler/try_promote.rs | 85 +++++---- .../providers/handler/use_input_delegate.rs | 75 ++++---- 29 files changed, 1841 insertions(+), 752 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs create mode 100644 example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.stderr diff --git a/docs/reference/providers/handler/compose_handlers.md b/docs/reference/providers/handler/compose_handlers.md index 17bd1a83..84eb33d6 100644 --- a/docs/reference/providers/handler/compose_handlers.md +++ b/docs/reference/providers/handler/compose_handlers.md @@ -1,4 +1,6 @@ --- +title: 'ComposeHandlers — two handlers in sequence' +description: 'The combinator that runs one handler and feeds its output to a second, as a Computer, TryComputer, AsyncComputer, or Handler.' sidebar_label: 'ComposeHandlers' sidebar_position: 1 --- @@ -9,16 +11,18 @@ Run two handlers back to back, feeding the output of the first as the input of t ## Overview -`ComposeHandlers` is the fundamental sequencing combinator. It runs `ProviderA`, -then runs `ProviderB` on `ProviderA`'s output, under one **context**, the type a method runs -on, and one `Code` tag. It implements every member of the handler family by threading the -intermediary value through both providers. Only the value flowing between them changes type. Like every -CGP provider, it carries no runtime value; the two inner providers ride in `PhantomData`. +`ComposeHandlers` is the fundamental sequencing combinator. It runs +`ProviderA`, then runs `ProviderB` on `ProviderA`'s output, under one +[**context**](/docs/reference/glossary#context), the type the implementation runs against, and one +`Code` tag. It implements the four owned-input members of the handler family, `Computer`, +`TryComputer`, `AsyncComputer`, and `Handler`, by threading the intermediate value through both +providers; it has no `…Ref` or `Producer` impl. Only the value flowing between the two changes type. +Like every CGP provider, it carries no runtime value; the two inner providers ride in `PhantomData`. ## Usage -Import it from `cgp::extra::handler`. It takes two provider type parameters, the first handler and the -second: +Import it from `cgp::extra::handler`; it is not in the prelude. It takes two provider type +parameters, the first handler and the second: ```rust use cgp::extra::handler::ComposeHandlers; @@ -31,36 +35,57 @@ delegate_components! { ``` The second provider's input type is pinned to the first's output type, so the two must line up: -`ProviderB` computes over `ProviderA::Output`, and the composite output is `ProviderB::Output`. - -For composing more than two handlers, reach for [`PipeHandlers`](pipe_handlers.md), which takes a list +`ProviderB` computes over `ProviderA::Output`, and the composite output is `ProviderB::Output`. For +composing more than two handlers, reach for [`PipeHandlers`](pipe_handlers.md), which takes a list and folds it into nested `ComposeHandlers`. ## Examples -`ComposeHandlers` chains two field-reading computers over a context. Given a `Double` computer and an -`AddOne` computer, both over `u64`: +Two computers composed and wired as one: ```rust +use cgp::prelude::*; use cgp::extra::handler::{CanCompute, ComposeHandlers}; +#[cgp_computer] +pub fn double(value: u64) -> u64 { + value * 2 +} + +#[cgp_computer] +pub fn add_one(value: u64) -> u64 { + value + 1 +} + +pub struct App; + delegate_components! { App { ComputerComponent: ComposeHandlers, } } + +check_components! { + App { + ComputerComponent: ((), u64), + } +} + +pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 5), 11); // (5 * 2) + 1 +} ``` -Computing over an input of `5` runs `Double` first, then `AddOne` on its output, giving `(5 * 2) + 1`. -The same composite serves as a `TryComputer`, `AsyncComputer`, or `Handler` if both stages support that -shape. +Computing over `5` runs `Double` first and `AddOne` on its output. `App` is an +[environmental context](/docs/reference/glossary#environmental-context), and the same composite +serves as a `TryComputer`, `AsyncComputer`, or `Handler` wherever both stages support that shape. ## When to use it **Reach for `ComposeHandlers` to sequence exactly two handlers.** For three or more, use [`PipeHandlers`](pipe_handlers.md), which reads better as a list and folds to the same nested -composition. For a step that should short-circuit on a `Result` branch rather than always run the next -stage, use the [monad providers](../monad/pipe_monadic.md) instead. +composition. For a step that should short-circuit on a `Result` branch rather than always run the +next stage, use the [monad providers](../monad/pipe_monadic.md) instead. ## Under the hood @@ -75,6 +100,7 @@ Its `Computer` impl requires `ProviderA: Computer` and `ProviderB::Output`: ```rust +#[cgp_provider] impl Computer for ComposeHandlers where @@ -90,16 +116,18 @@ where } ``` -The same shape is implemented for `TryComputer`, `AsyncComputer`, and `Handler`. The fallible variants -use `?` to short-circuit on the first provider's error, so they require the context to have an error -type; the async variants `.await` each step. +The same shape is implemented for `TryComputer`, `AsyncComputer`, and `Handler`. The fallible +variants use `?` to short-circuit on the first provider's error, so they require the context to have +an error type; the async variants `.await` each step. ## Related constructs -- [`PipeHandlers`](pipe_handlers.md) — generalizes this to a list, folding to nested `ComposeHandlers`. -- [`ReturnInput`](return_input.md) — the identity that composes with any handler without changing it. -- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family it - implements. +- [`PipeHandlers`](pipe_handlers.md) — generalizes this to a list, folding to nested + `ComposeHandlers`. +- [`ReturnInput`](return_input.md) — the identity that composes with any handler without changing + it. +- [`Computer`](../../components/handler/computer.md), + [`Handler`](../../components/handler/handler.md) — the family it implements. - [`PipeMonadic`](../monad/pipe_monadic.md) — composition that short-circuits through a monad. The ideas behind it: diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md index 36d55114..609c365e 100644 --- a/docs/reference/providers/handler/index.md +++ b/docs/reference/providers/handler/index.md @@ -1,4 +1,5 @@ --- +description: 'The handler combinators: compose handlers, pass input through, promote one handler shape into another, fill the family from one base, and dispatch by input type.' sidebar_label: 'Overview' sidebar_position: 0 --- @@ -10,31 +11,39 @@ through a pipeline, returning the input unchanged, and lifting one handler shape ## Overview -The handler combinators exist because the handler family is not one trait but several related ones, and -code is rarely written against all of them at once. A provider author writes a plain synchronous -[`Computer`](../../components/handler/computer.md), a fallible [`TryComputer`](../../components/handler/try_computer.md), -or an async [`Handler`](../../components/handler/handler.md), depending on the computation. The combinators let -those single-shape providers be wired where a different shape is expected, and let several providers be -glued into a larger one, on a **context**, the type a method runs on. Like every CGP provider, -each combinator is zero-sized: its type parameters are inner providers carried in `PhantomData`. +The handler combinators exist because the handler family is not one trait but several related ones, +and code is rarely written against all of them at once. A provider author writes a plain synchronous +[`Computer`](../../components/handler/computer.md), a fallible +[`TryComputer`](../../components/handler/try_computer.md), or an async +[`Handler`](../../components/handler/handler.md), depending on the computation. The combinators let +those single-shape providers be wired where a different shape is expected, and let several providers +be glued into a larger one, on a [**context**](/docs/reference/glossary#context), the type the +implementation runs against. Like every CGP provider, each combinator is zero-sized: its type +parameters are inner providers carried in `PhantomData`. + +The promotion bundles are in the prelude. Every other combinator here, from `ComposeHandlers` to +`UseInputDelegate`, is imported from `cgp::extra::handler`, as are the consumer traits such as +`CanCompute` that call them. ## The handler family -Every combinator is defined in terms of the handler component traits, so a short orientation helps. The -family shares one method signature: a context reference, a `PhantomData` tag selecting the -operation, and an input, producing an associated `Output`. The members differ on two axes. +Every combinator is defined in terms of the handler component traits, so a short orientation helps. +The family shares one method signature: a context reference, a `PhantomData` tag selecting the +operation, and an input, producing an associated `Output`. The members differ on two axes: - [`Computer`](../../components/handler/computer.md) is synchronous and infallible. -- [`TryComputer`](../../components/handler/try_computer.md) is synchronous and fallible, and requires the context - to have an error type. -- `AsyncComputer` is asynchronous and infallible. -- [`Handler`](../../components/handler/handler.md) is asynchronous and fallible, the most general member. +- [`TryComputer`](../../components/handler/try_computer.md) is synchronous and fallible, and + requires the context to have an error type. +- [`AsyncComputer`](../../components/handler/async_computer.md) is asynchronous and infallible. +- [`Handler`](../../components/handler/handler.md) is asynchronous and fallible, the most general + member. - [`Producer`](../../components/handler/producer.md) takes no input. -Each of the first four has a `…Ref` companion whose method takes the input by reference. The promotion -combinators trade on the natural orderings among these: a `Computer` is also a valid `TryComputer` and a -valid `AsyncComputer`, a `TryComputer` is a valid `Handler`, and a reference handler can serve a value -handler by dereferencing the input. +Each of the first four has a `…Ref` companion whose method takes the input by reference. The +promotion combinators trade on the natural orderings among these: a `Computer` is also a valid +`TryComputer` and a valid `AsyncComputer`, and a `TryComputer` or an `AsyncComputer` is a valid +`Handler`. A by-reference handler serves a by-value slot by dereferencing the input, and a by-value +handler serves a by-reference slot only when it accepts the borrow as its input. ## The combinators, by role @@ -47,33 +56,43 @@ handler by dereferencing the input. - [`ReturnInput`](return_input.md) passes its input straight through. -**Promotion** lifts one handler shape into another, so one written implementation satisfies several -traits: +**Promotion** lifts one handler shape into another in a single step, so one written implementation +satisfies another trait: + +- [`Promote`](promote.md) lifts a `Producer` to a `Computer`, and an infallible member to a fallible + one. +- [`PromoteAsync`](promote_async.md) lifts a synchronous member into an asynchronous one. +- [`PromoteRef`](promote_ref.md) bridges by-value and by-reference members, in both directions. +- [`TryPromote`](try_promote.md) bridges a `Result`-valued output and a fallible trait, in both + directions. -- [`Promote`](promote.md) lifts along the infallible-to-fallible and sync-to-async axes. -- [`PromoteAsync`](promote_async.md) lifts a synchronous provider into an asynchronous one. -- [`PromoteRef`](promote_ref.md) bridges value handlers and reference handlers by dereferencing. -- [`TryPromote`](try_promote.md) bridges a `Result`-valued output and a fallible trait. +A lift of two steps chains them, as `PromoteAsync>` makes a `Handler` from a `Computer`. -**Promotion bundles** wire a whole cluster of handler components to the right single-step promotion at -once, so a provider author implements one trait and gets the rest of the family. These are what -[`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md) -wire automatically: +**Promotion bundles** wire a whole cluster of handler components to the right single-step promotion +at once, so a provider author implements one trait and gets the rest of the family. These are what +[`#[cgp_computer]`](../../macros/cgp_computer.md) and +[`#[cgp_producer]`](../../macros/cgp_producer.md) wire a generated provider to: - [`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), [`PromoteProducer`](promote_producer.md), [`PromoteAsyncComputer`](promote_async_computer.md), and - [`PromoteHandler`](promote_handler.md), one per base trait. + [`PromoteHandler`](promote_handler.md), one per base. + +A bundle's entries that take one step from the base serve any provider, but an entry that takes its +step from a sibling component works only for a provider wired to that same bundle, as the macros +wire theirs. Each bundle page says which entries are which. **Input dispatch** chooses a handler by the type of the value: -- [`UseInputDelegate`](use_input_delegate.md) keys a lookup table on the handler's `Input` type. It is - the legacy form; the `open` statement of `delegate_components!` dispatches on the input directly. +- [`UseInputDelegate`](use_input_delegate.md) keys a lookup table on the handler's `Input` type. It + is the legacy form; the `open` statement of `delegate_components!` dispatches on the input + directly. ## Related constructs -- [`Computer`](../../components/handler/computer.md), [`TryComputer`](../../components/handler/try_computer.md), - [`Handler`](../../components/handler/handler.md), [`Producer`](../../components/handler/producer.md) — the components - these providers implement. +- [`Computer`](../../components/handler/computer.md), + [`TryComputer`](../../components/handler/try_computer.md), + [`Handler`](../../components/handler/handler.md), + [`Producer`](../../components/handler/producer.md) — the components these providers implement. - [`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md) — generate a single-trait provider and wire the rest of the family through the promotion bundles. - [`Product!`](../../macros/product.md) — the type-level list `PipeHandlers` composes. diff --git a/docs/reference/providers/handler/pipe_handlers.md b/docs/reference/providers/handler/pipe_handlers.md index 45028687..b8ad1bd9 100644 --- a/docs/reference/providers/handler/pipe_handlers.md +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -1,4 +1,6 @@ --- +title: 'PipeHandlers — a pipeline of handlers' +description: 'The combinator that folds a Product! list of handlers into nested ComposeHandlers, so the input flows through each stage in turn.' sidebar_label: 'PipeHandlers' sidebar_position: 2 --- @@ -10,43 +12,69 @@ next. ## Overview -`PipeHandlers` generalizes [`ComposeHandlers`](compose_handlers.md) from two handlers to a -list of them. It takes a [`Product!`](../../macros/product.md) list of providers and folds the whole -pipeline into one nested `ComposeHandlers`, so the input flows through each stage in turn, on one -**context**, the type a method runs on. It is the combinator to reach for when wiring a -multi-stage transformation: list the stages in order and let `PipeHandlers` build the composition. Like -every CGP provider, it carries no runtime value; the list rides in `PhantomData`. +`PipeHandlers` generalizes [`ComposeHandlers`](compose_handlers.md) from two handlers to +a list of them. It takes a [`Product!`](../../macros/product.md) list of providers and folds the +whole pipeline into one nested `ComposeHandlers`, so the input flows through each stage in turn, on +one [**context**](/docs/reference/glossary#context), the type the implementation runs against. It is +the combinator to reach for when wiring a multi-stage transformation: list the stages in order and +let `PipeHandlers` build the composition. Like every CGP provider, it carries no runtime value; the +list rides in `PhantomData`. ## Usage -Import it from `cgp::extra::handler`. It takes one type parameter, a `Product!` list of handler -providers: +Import it from `cgp::extra::handler`; it is not in the prelude. It takes one type parameter, a +`Product!` list of handler providers: ```rust -use cgp::extra::handler::{CanCompute, PipeHandlers}; +use cgp::extra::handler::PipeHandlers; delegate_components! { App { - ComputerComponent: - PipeHandlers, + ComputerComponent: PipeHandlers, } } ``` -The list runs left to right: `ParseInput`, then `Validate` on its output, then `Normalize`. Each +The list runs left to right: `Double`, then `AddOne` on its output, then `Double` again. Each stage's output type must match the next stage's input type. Because the fold is generic over the -component, one list serves as a `Computer`, `TryComputer`, `AsyncComputer`, or `Handler`, whichever the -wiring asks for, as long as every stage supports that shape. +component key, one list of two or more stages serves as a `Computer`, `TryComputer`, +`AsyncComputer`, or `Handler`, whichever the wiring asks for, as long as every stage supports that +shape; the fold's `ComposeHandlers` has no `…Ref` impl. A one-element list is that element, and an +empty list provides nothing. ## Examples -A pipeline of field-reading computers over a context. Suppose `Multiply` and `Add` are -`Computer` providers over `u64` that read a factor or an addend from a context field: +A pipeline of field-reading computers over a context, where `Multiply` and `Add` read +a factor or an addend from a context field: ```rust use cgp::prelude::*; use cgp::extra::handler::{CanCompute, PipeHandlers}; +#[cgp_new_provider] +impl Computer for Multiply +where + Context: HasField, +{ + type Output = u64; + + fn compute(context: &Context, _code: PhantomData, input: u64) -> u64 { + input * context.get_field(PhantomData) + } +} + +#[cgp_new_provider] +impl Computer for Add +where + Context: HasField, +{ + type Output = u64; + + fn compute(context: &Context, _code: PhantomData, input: u64) -> u64 { + input + context.get_field(PhantomData) + } +} + #[derive(HasField)] pub struct MyContext { pub foo: u64, @@ -64,13 +92,24 @@ delegate_components! { ]>, } } + +check_components! { + MyContext { + ComputerComponent: ((), u64), + } +} + +pub fn demo() { + let context = MyContext { foo: 2, bar: 3, baz: 4 }; + assert_eq!(context.compute(PhantomData::<()>, 5), 52); // ((5 * 2) + 3) * 4 +} ``` -Wiring `ComputerComponent` to this list composes the three into -`ComposeHandlers, ComposeHandlers, Multiply<…>>>`. Computing over an input of `5` on -a context with `foo = 2`, `bar = 3`, `baz = 4` gives `((5 * 2) + 3) * 4`. Stages of mismatched shapes -can be reconciled inline, as in `PromoteAsync>>`, which lifts a plain -`Computer` stage up to the async `Handler` shape a pipeline expects. +The list folds to `ComposeHandlers, ComposeHandlers, Multiply<…>>>`. `MyContext` +is a [value context](/docs/reference/glossary#value-context): each stage reads one of its fields. +Stages of mismatched shapes can be reconciled inline, as in +`PromoteAsync>>`, which lifts a plain `Computer` stage to the async +`Handler` shape a `Handler` pipeline asks for. ## When to use it @@ -78,9 +117,9 @@ can be reconciled inline, as in `PromoteAsync>>`, wh nesting [`ComposeHandlers`](compose_handlers.md) by hand. For exactly two, `ComposeHandlers` is the plainer choice. -For a pipeline where a step should short-circuit on a `Result` branch rather than always feed the next -stage, use [`PipeMonadic`](../monad/pipe_monadic.md), the monadic generalization that -`PipeHandlers` reduces to. +For a pipeline where a step should short-circuit on a `Result` branch rather than always feed the +next stage, use [`PipeMonadic`](../monad/pipe_monadic.md), the monadic generalization; +`PipeMonadic` reduces to `PipeHandlers`. ## Under the hood @@ -90,9 +129,9 @@ stage, use [`PipeMonadic`](../monad/pipe_monadic.md), the monadic generalization pub struct PipeHandlers(pub PhantomData); ``` -Instead it delegates every handler component to whatever single provider the list folds down to, -computed by an internal `ComposeProviders` trait that walks the `Cons`/`Nil` list. A one-element list -folds to that provider unchanged; a list `Cons` folds to +Instead it delegates every component key to whatever single provider the list folds down to, +computed by an internal `ComposeProviders` trait that walks the `Cons`/`Nil` list. A one-element +list folds to that provider unchanged, and a list `Cons` folds to `ComposeHandlers`: ```rust @@ -104,17 +143,17 @@ delegate_components! { } ``` -Because the delegation is generic over the `Component` key, the same pipeline answers whichever handler -shape the wiring asks for. +Because the delegation is generic over the `Component` key, the same pipeline answers whichever +handler shape the wiring asks for. ## Related constructs - [`ComposeHandlers`](compose_handlers.md) — the two-handler combinator this folds a list into. -- [`ReturnInput`](return_input.md) — the identity stage, the neutral element of the fold. +- [`ReturnInput`](return_input.md) — the identity stage, which leaves a pipeline unchanged. - [`Product!`](../../macros/product.md) — the type-level list of stages. - [`PipeMonadic`](../monad/pipe_monadic.md) — the monadic pipeline that adds short-circuiting. -- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family a - pipeline implements. +- [`Computer`](../../components/handler/computer.md), + [`Handler`](../../components/handler/handler.md) — the family a pipeline implements. The ideas behind it: diff --git a/docs/reference/providers/handler/promote.md b/docs/reference/providers/handler/promote.md index 864a0331..4a3c8160 100644 --- a/docs/reference/providers/handler/promote.md +++ b/docs/reference/providers/handler/promote.md @@ -1,36 +1,30 @@ --- +title: 'Promote — lift a handler one step up' +description: 'The single-step lift that turns a Producer into a Computer, a Computer into a TryComputer, and an AsyncComputer into a Handler, adding no behavior.' sidebar_label: 'Promote' sidebar_position: 4 --- # `Promote` -Lift a handler upward along the infallible-to-fallible and sync-to-async axes, without adding behavior -of its own. - -:::info - -### Generated machinery - -**You are not expected to name `Promote` directly.** The promotion bundle -[`PromoteComputer`](promote_computer.md) and the others wire it into the right handler slots, and those -bundles are what [`#[cgp_computer]`](../../macros/cgp_computer.md) and -[`#[cgp_producer]`](../../macros/cgp_producer.md) generate. You reach for it by hand only when wiring the -handler family one slot at a time. This page explains what that wiring emits. - -::: +Lift a handler one step up the family, from a producer to a computer or from infallible to fallible, +without adding behavior of its own. ## Overview -`Promote` re-exposes one inner provider under a more capable member of the handler family, -treating a less capable provider as a more capable one without introducing error or async behavior -itself. The **context**, the type a method runs on, sees the promoted shape while the inner -provider does the same work. Like every CGP provider, it carries no runtime value; the inner provider -rides in `PhantomData`. +`Promote` re-exposes one inner provider under a more capable member of the handler family. +It treats a less capable provider as a more capable one without introducing error or async behavior +itself, so the [**context**](/docs/reference/glossary#context), the type the implementation runs +against, sees the promoted shape while the inner provider does the same work. It is usually reached +through a promotion bundle such as [`PromoteComputer`](promote_computer.md), which the handler +macros wire for a generated provider, and it is written by hand when a context wires one handler +slot at a time. Like every CGP provider, it carries no runtime value; the inner provider rides in +`PhantomData`. ## Usage -Import it from `cgp::extra::handler`. It takes one type parameter, the inner provider: +Import it from `cgp::extra::handler`; it is not in the prelude. It takes one type parameter, the +inner provider: ```rust use cgp::extra::handler::Promote; @@ -43,14 +37,77 @@ delegate_components! { } ``` +Each lift takes exactly one step. A `Computer` reaches a `Handler` in two, as +`PromoteAsync>`: `Promote` makes the `TryComputer`, and +[`PromoteAsync`](promote_async.md) makes the `Handler` from it. + +## Examples + +A context fills three slots from two hand-written providers, one lift each and one chain of two: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{CanCompute, CanHandle, CanTryCompute, Promote, PromoteAsync}; + +#[cgp_new_provider] +impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } +} + +#[cgp_new_provider] +impl Producer for DefaultPort { + type Output = u16; + + fn produce(_context: &Context, _code: PhantomData) -> u16 { + 8080 + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ComputerComponent: Promote, + TryComputerComponent: Promote, + HandlerComponent: PromoteAsync>, + } +} + +check_components! { + App { + ComputerComponent: ((), ()), + [TryComputerComponent, HandlerComponent]: ((), u64), + } +} + +pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute(code, ()), 8080); + assert_eq!(App.try_compute(code, 21), Ok(42)); + assert_eq!(App.handle(code, 21).await, Ok(42)); +} +``` + +`Promote` answers `compute` by ignoring the input and producing `8080`, +`Promote` answers `try_compute` by wrapping `Double`'s output in `Ok`, and the chain answers +`handle`. The fallible members need the error type `App` wires. `App` is an [environmental +context](/docs/reference/glossary#environmental-context). + ## When to use it -**You rarely reach for `Promote` by hand.** A provider written with -[`#[cgp_computer]`](../../macros/cgp_computer.md) or [`#[cgp_producer]`](../../macros/cgp_producer.md) -gets the right lifts wired through a bundle such as [`PromoteComputer`](promote_computer.md), so the -whole family is filled in for you. Name `Promote` yourself only when you wire the family one slot at a -time and a slot needs exactly this lift: a producer filling a computer slot, or an infallible result -wrapped in `Ok`. For the sync-to-async lift use [`PromoteAsync`](promote_async.md), for the borrow lift +**Reach for `Promote` when wiring a handler slot by hand and the slot needs exactly this lift**: a +producer filling a computer slot, or an infallible result wrapped in `Ok`. A provider written with +[`#[cgp_computer]`](../../macros/cgp_computer.md) or +[`#[cgp_producer]`](../../macros/cgp_producer.md) is already wired to a bundle, such as +[`PromoteComputer`](promote_computer.md), that fills in the whole family, so it needs no `Promote` +of its own. For the sync-to-async lift use [`PromoteAsync`](promote_async.md), for the borrow lift [`PromoteRef`](promote_ref.md), and for the `Result` bridge [`TryPromote`](try_promote.md). ## Under the hood @@ -61,24 +118,26 @@ wrapped in `Ok`. For the sync-to-async lift use [`PromoteAsync`](promote_async.m pub struct Promote(pub PhantomData); ``` -- As a `Computer`, it requires the inner `Provider: Producer` and ignores its own input, - calling `Provider::produce`. This adapts a producer, which takes no input, to fill a computer slot - that is handed an input it does not need. +- As a `Computer`, it requires the inner `Provider: Producer` and ignores its own + input, calling `Provider::produce`. This adapts a producer, which takes no input, to fill a + computer slot that is handed an input it does not need. - As a `TryComputer`, it requires `Provider: Computer` and wraps the infallible result in `Ok`. - As a `Handler`, it requires `Provider: AsyncComputer` and wraps the awaited result in `Ok`. -Each promotion adds the missing behavior, either discarding an input or introducing an always-`Ok` -result, without changing what the inner provider computes. +The fallible impls require the context to have an error type. Each promotion adds the missing +behavior, either discarding an input or introducing an always-`Ok` result, without changing what the +inner provider computes. ## Related constructs -- [`PromoteAsync`](promote_async.md), [`PromoteRef`](promote_ref.md), [`TryPromote`](try_promote.md) — - the other single-step lifts, along different axes. +- [`PromoteAsync`](promote_async.md), [`PromoteRef`](promote_ref.md), [`TryPromote`](try_promote.md) + — the other single-step lifts, along different axes. - [`PromoteComputer`](promote_computer.md) and the other bundles — wire `Promote` into the family - automatically. + for a macro-generated provider. - [`#[cgp_computer]`](../../macros/cgp_computer.md), [`#[cgp_producer]`](../../macros/cgp_producer.md) — generate providers that the bundles promote. -- [`Producer`](../../components/handler/producer.md), [`Computer`](../../components/handler/computer.md), +- [`Producer`](../../components/handler/producer.md), + [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family members it lifts between. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_async.md b/docs/reference/providers/handler/promote_async.md index 12020311..b654d55d 100644 --- a/docs/reference/providers/handler/promote_async.md +++ b/docs/reference/providers/handler/promote_async.md @@ -1,4 +1,6 @@ --- +title: 'PromoteAsync — run a sync handler as async' +description: 'The single-step lift that runs a synchronous Computer or TryComputer inside an async method, to serve an AsyncComputer or Handler slot.' sidebar_label: 'PromoteAsync' sidebar_position: 5 --- @@ -7,27 +9,20 @@ sidebar_position: 5 Lift a synchronous handler into an asynchronous one. -:::info - -### Generated machinery - -**You are not expected to name `PromoteAsync` directly.** The promotion bundle -[`PromoteComputer`](promote_computer.md) wires it into the async slots, and the bundles are what -[`#[cgp_computer]`](../../macros/cgp_computer.md) generates. You reach for it by hand only when wiring -the handler family one slot at a time. This page explains what that wiring emits. - -::: - ## Overview `PromoteAsync` runs a synchronous inner provider inside an async method, so a synchronous -handler serves an asynchronous slot on a **context**, the type a method runs on. The returned -future is ready immediately, so no actual asynchrony is added. Like every CGP provider, it carries no -runtime value; the inner provider rides in `PhantomData`. +handler serves an asynchronous slot on a [**context**](/docs/reference/glossary#context), the type +the implementation runs against. The returned future does all its work when first polled and awaits +nothing, so no actual asynchrony is added. It is usually reached through a promotion bundle such as +[`PromoteComputer`](promote_computer.md), and it is written by hand when a context wires one slot at +a time. Like every CGP provider, it carries no runtime value; the inner provider rides in +`PhantomData`. ## Usage -Import it from `cgp::extra::handler`. It takes one type parameter, the inner provider: +Import it from `cgp::extra::handler`; it is not in the prelude. It takes one type parameter, the +inner provider: ```rust use cgp::extra::handler::PromoteAsync; @@ -40,13 +35,80 @@ delegate_components! { } ``` +## Examples + +A context serves both async members from hand-written synchronous providers: + +```rust +use core::num::ParseIntError; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::DebugError; +use cgp::extra::error::RaiseFrom; +use cgp::extra::handler::{CanComputeAsync, CanHandle, PromoteAsync}; + +#[cgp_new_provider] +impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } +} + +#[cgp_impl(new ParseU64)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl TryComputer { + type Output = u64; + + fn try_compute(&self, _code: PhantomData, input: String) -> Result { + input.parse().map_err(Self::raise_error) + } +} + +pub struct App; + +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + + AsyncComputerComponent: PromoteAsync, + HandlerComponent: PromoteAsync, + } +} + +check_components! { + App { + AsyncComputerComponent: ((), u64), + HandlerComponent: ((), String), + } +} + +pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute_async(code, 21).await, 42); + assert_eq!(App.handle(code, "12".to_owned()).await, Ok(12)); +} +``` + +`PromoteAsync` answers `compute_async` from the synchronous `Double`, and +`PromoteAsync` answers `handle` from the fallible synchronous `ParseU64`, passing its +`Result` through. `App` is an [environmental +context](/docs/reference/glossary#environmental-context) that also wires the error type and raisers +`ParseU64` needs. + ## When to use it -**You rarely reach for `PromoteAsync` by hand.** The [`PromoteComputer`](promote_computer.md) bundle -wires it into the async slots, so a synchronous provider serves the async family without you naming it. -Reach for it directly only when wiring a slot by hand and that slot needs a synchronous provider run in -an async method. For the infallible-to-fallible or producer lift use [`Promote`](promote.md), and for -the borrow lift [`PromoteRef`](promote_ref.md). +**Reach for `PromoteAsync` when wiring an async slot by hand from a synchronous provider.** A +provider written with [`#[cgp_computer]`](../../macros/cgp_computer.md) is already wired to a bundle +that routes its async slots here. For the infallible-to-fallible or producer lift use +[`Promote`](promote.md), and for the borrow lift [`PromoteRef`](promote_ref.md). ## Under the hood @@ -57,22 +119,25 @@ pub struct PromoteAsync(pub PhantomData); ``` - As an `AsyncComputer`, it requires `Provider: Computer` and runs it synchronously inside the async - method, returning a future that is already ready. -- As a `Handler`, it requires `Provider: TryComputer` and returns that fallible synchronous result, so - a synchronous fallible computer becomes an async fallible handler. + method, returning a future that awaits nothing. +- As a `Handler`, it requires `Provider: TryComputer` and returns that fallible synchronous result, + so a synchronous fallible computer becomes an async fallible handler. This impl requires the + context to have an error type. ## Related constructs -- [`Promote`](promote.md), [`PromoteRef`](promote_ref.md), [`TryPromote`](try_promote.md) — the other - single-step lifts. -- [`PromoteComputer`](promote_computer.md) and the other bundles — wire `PromoteAsync` into the family - automatically. -- [`Computer`](../../components/handler/computer.md), [`TryComputer`](../../components/handler/try_computer.md), +- [`Promote`](promote.md), [`PromoteRef`](promote_ref.md), [`TryPromote`](try_promote.md) — the + other single-step lifts. +- [`PromoteComputer`](promote_computer.md) and the other bundles — wire `PromoteAsync` into the + family for a macro-generated provider. +- [`Computer`](../../components/handler/computer.md), + [`TryComputer`](../../components/handler/try_computer.md), [`Handler`](../../components/handler/handler.md) — the family members it lifts between. The ideas behind it: -- [Handlers](/docs/concepts/handlers) — the family and the sync-to-async ordering this lift trades on. +- [Handlers](/docs/concepts/handlers) — the family and the sync-to-async ordering this lift trades + on. ## Source diff --git a/docs/reference/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md index 7f5f110f..f5b07b2a 100644 --- a/docs/reference/providers/handler/promote_async_computer.md +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -1,65 +1,128 @@ --- +title: 'PromoteAsyncComputer — the async family' +description: 'The promotion bundle that fills in Handler and the async by-reference members from an AsyncComputer base, such as an async #[cgp_computer] function.' sidebar_label: 'PromoteAsyncComputer' sidebar_position: 11 --- # `PromoteAsyncComputer` -Fill in the handler family from a provider that implements `AsyncComputer`. +Fill in the async members of the handler family from a provider that implements `AsyncComputer`. :::info ### Generated machinery -**You are not expected to name `PromoteAsyncComputer` directly.** It is wired for a generated provider -whose base is the asynchronous infallible computer. You name it by hand only when wiring a hand-written -`AsyncComputer`'s family explicitly. This page explains what that wiring emits. +**You are not expected to name `PromoteAsyncComputer` directly.** +[`#[cgp_computer]`](../../macros/cgp_computer.md) wires the provider it generates for an `async fn` +returning a plain value to `PromoteAsyncComputer`. A context names the bundle to route its own +components through such a provider, or through its `HandlerComponent` entry, which serves any +`AsyncComputer`. This page explains what the bundle emits. ::: ## Overview `PromoteAsyncComputer` starts from a provider that implements `AsyncComputer`, the -asynchronous infallible base, and fills in the rest of the handler family on a **context**, the type a -method runs on. It is the async-base counterpart of [`PromoteComputer`](promote_computer.md). -Like every CGP provider, it carries no runtime value. +asynchronous infallible base, and fills in the other async members of the handler family on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. It is the +async-base counterpart of [`PromoteComputer`](promote_computer.md), and it fills in only async +members, because the synchronous ones cannot be derived from an async base. Like every CGP provider, +it carries no runtime value. ## Usage It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base -`AsyncComputer` provider. `PromoteAsyncComputer` answers `HandlerComponent` and the async-ref members -but not `AsyncComputerComponent`, so the base is wired to `AsyncComputerComponent` directly and the -bundle fills in the rest: +`AsyncComputer` provider. It answers `HandlerComponent`, `AsyncComputerRefComponent`, and +`HandlerRefComponent` but not `AsyncComputerComponent`, so the base is wired to +`AsyncComputerComponent` directly and the bundle fills in the rest: ```rust delegate_components! { App { - AsyncComputerComponent: Double, - HandlerComponent: PromoteAsyncComputer, + AsyncComputerComponent: DoubleLater, + HandlerComponent: PromoteAsyncComputer, } } ``` +## Examples + +An async `#[cgp_computer]` function is the base, and the bundle answers `handle` from it: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{CanComputeAsync, CanHandle}; + +#[cgp_computer] +pub async fn double_later(value: u64) -> u64 { + value * 2 +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + AsyncComputerComponent: DoubleLater, + HandlerComponent: PromoteAsyncComputer, + } +} + +check_components! { + App { + [AsyncComputerComponent, HandlerComponent]: ((), u64), + } +} + +pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute_async(code, 5).await, 10); + assert_eq!(App.handle(code, 5).await, Ok(10)); +} +``` + +`handle` wraps the awaited `10` in `Ok`, and needs the error type `App` wires. The +`HandlerComponent` entry is one step from the base, so it serves a hand-written `AsyncComputer` too. +`App` is an [environmental context](/docs/reference/glossary#environmental-context). + ## When to use it -**Reach for `PromoteAsyncComputer` when the base is an infallible async `AsyncComputer`** and you wire -its family by hand. For a synchronous base use [`PromoteComputer`](promote_computer.md), and for a -fallible async `Handler` base use [`PromoteHandler`](promote_handler.md). +**Reach for `PromoteAsyncComputer` when the base is an infallible `AsyncComputer`**, generated from +an `async fn` or written by hand. For a synchronous base use +[`PromoteComputer`](promote_computer.md), and for an async base returning `Result` use +[`PromoteHandler`](promote_handler.md). ## Under the hood -`PromoteAsyncComputer` is a [`delegate_components!`](../../macros/delegate_components.md) table over a -generic inner `Provider`. It routes `HandlerComponent` to [`Promote`](promote.md), which wraps the -awaited value in `Ok`, and routes `AsyncComputerRefComponent` and `HandlerRefComponent` to -[`PromoteRef`](promote_ref.md). +`PromoteAsyncComputer` is a [`delegate_components!`](../../macros/delegate_components.md) table over +a generic inner `Provider`: + +```rust +delegate_components! { + + new PromoteAsyncComputer { + AsyncComputerRefComponent: PromoteRef, + HandlerComponent: Promote, + HandlerRefComponent: PromoteRef, + } +} +``` + +It routes `HandlerComponent` to [`Promote`](promote.md), which wraps the awaited value in `Ok`, and +the two by-reference members to [`PromoteRef`](promote_ref.md), which need the base to take the +borrow as its input. ## Related constructs - [`PromoteComputer`](promote_computer.md) — the synchronous-base counterpart. -- [`PromoteHandler`](promote_handler.md) — defers its async-ref components here. +- [`PromoteHandler`](promote_handler.md) — the counterpart for an async base returning `Result`, + which forwards its by-reference members here. - [`Promote`](promote.md), [`PromoteRef`](promote_ref.md) — the lifts this table wires. -- [`Handler`](../../components/handler/handler.md), [`Computer`](../../components/handler/computer.md) — the family it - fills in. +- [`AsyncComputer`](../../components/handler/async_computer.md), + [`Handler`](../../components/handler/handler.md) — the base and the family members it fills in. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md index fd6ad137..f9192e21 100644 --- a/docs/reference/providers/handler/promote_computer.md +++ b/docs/reference/providers/handler/promote_computer.md @@ -1,4 +1,6 @@ --- +title: 'PromoteComputer — the family from a Computer' +description: 'The promotion bundle that fills in the rest of the handler family from a Computer base; #[cgp_computer] wires its generated provider to it.' sidebar_label: 'PromoteComputer' sidebar_position: 8 --- @@ -12,28 +14,27 @@ Fill in every member of the handler family from a provider that implements `Comp ### Generated machinery **You are not expected to name `PromoteComputer` directly.** -[`#[cgp_computer]`](../../macros/cgp_computer.md) wires it across the family for the provider it -generates, so one written `Computer` impl answers the whole handler surface. A bundle -expects its parameter to be a provider wired to that same bundle, as the macro does with `Self`, because -some entries reach the base through a sibling: the `Handler` entry is `PromoteAsync`, which -needs `Provider` to be a `TryComputer`. To lift a hand-written `Computer` without wiring it to the -bundle, chain the one-step adapters, as in `PromoteAsync>`. This page explains what -the bundle emits. +[`#[cgp_computer]`](../../macros/cgp_computer.md) wires the provider it generates to +`PromoteComputer`, so one written function answers the whole handler surface. A context names +the bundle only to route its own components through such a provider, or through the entries that +serve any `Computer`, as [Common Mistakes](#common-mistakes) sets out. This page explains what the +bundle emits. ::: ## Overview -`PromoteComputer` starts from a provider that implements `Computer`, the by-value synchronous -infallible base, and fills in every other member of the handler family by promotion, on a **context**, -the type a method runs on. It is a delegation table that routes each remaining handler -component to the right single-step promotion. Like every CGP provider, it carries no runtime value. +`PromoteComputer` starts from a provider that implements `Computer`, the synchronous, +infallible, owned-input base, and fills in every other member of the handler family by promotion, on +a [**context**](/docs/reference/glossary#context), the type the implementation runs against. It is a +delegation table that routes each remaining handler component to the right single-step promotion. +Like every CGP provider, it carries no runtime value. ## Usage It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base -`Computer` provider. `PromoteComputer` answers every family member *except* `ComputerComponent`, so the -base is wired to `ComputerComponent` directly and the bundle fills in the rest: +`Computer` provider. `PromoteComputer` answers every family member *except* `ComputerComponent`, so +the base is wired to `ComputerComponent` directly and the bundle fills in the rest: ```rust delegate_components! { @@ -48,23 +49,78 @@ delegate_components! { } ``` -Most code gets this wiring from [`#[cgp_computer]`](../../macros/cgp_computer.md) rather than writing it. +Here `Double` comes from [`#[cgp_computer]`](../../macros/cgp_computer.md), which is what lets the +`HandlerComponent` entry resolve. + +## Examples + +One `#[cgp_computer]` function answers four members of the family through the bundle: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{CanCompute, CanComputeAsync, CanHandle, CanTryCompute}; + +#[cgp_computer] +pub fn double(value: u64) -> u64 { + value * 2 +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ComputerComponent: Double, + [ + TryComputerComponent, + AsyncComputerComponent, + HandlerComponent, + ]: PromoteComputer, + } +} + +check_components! { + App { + [ + ComputerComponent, + TryComputerComponent, + AsyncComputerComponent, + HandlerComponent, + ]: ((), u64), + } +} + +pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute(code, 5), 10); + assert_eq!(App.try_compute(code, 5), Ok(10)); + assert_eq!(App.compute_async(code, 5).await, 10); + assert_eq!(App.handle(code, 5).await, Ok(10)); +} +``` + +The fallible members wrap `10` in `Ok`, and need the error type `App` wires. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). ## When to use it -**Reach for `PromoteComputer` when you wire a hand-written `Computer` provider's family explicitly** -rather than through [`#[cgp_computer]`](../../macros/cgp_computer.md), which wires it for you. Use a -different bundle when the base is a different trait: [`PromoteTryComputer`](promote_try_computer.md) -from a `TryComputer`, [`PromoteProducer`](promote_producer.md) from a `Producer`, +**Reach for `PromoteComputer` when a context routes its handler components through a `Computer` +provider generated by [`#[cgp_computer]`](../../macros/cgp_computer.md).** For a hand-written base, +use the one-step entries the bundle offers, or spell the lift out with the single-step combinators. +Use a different bundle when the base is a different trait: +[`PromoteTryComputer`](promote_try_computer.md) from a `Computer` returning `Result`, +[`PromoteProducer`](promote_producer.md) from a `Producer`, [`PromoteAsyncComputer`](promote_async_computer.md) from an `AsyncComputer`, and -[`PromoteHandler`](promote_handler.md) from a `Handler`. +[`PromoteHandler`](promote_handler.md) from an `AsyncComputer` returning `Result`. ## Under the hood -`PromoteComputer` is defined with [`delegate_components!`](../../macros/delegate_components.md) over a -generic inner `Provider`. It routes the fallible slot to [`Promote`](promote.md) (wrap in `Ok`), the -async slots to [`PromoteAsync`](promote_async.md) (run synchronously in an async method), and every -`…Ref` slot to [`PromoteRef`](promote_ref.md) (pass the borrow to the base as its input): +`PromoteComputer` is defined with [`delegate_components!`](../../macros/delegate_components.md) over +a generic inner `Provider`. It routes the fallible slot to [`Promote`](promote.md) (wrap in `Ok`), +the async slots to [`PromoteAsync`](promote_async.md) (run synchronously in an async method), and +every `…Ref` slot to [`PromoteRef`](promote_ref.md) (pass the borrow to the base as its input): ```rust delegate_components! { @@ -81,19 +137,39 @@ delegate_components! { } ``` -The base `ComputerComponent` is the inner provider itself; the table fills in the other seven. +The base `ComputerComponent` is the inner provider itself; the table fills in the other seven. Two +of the entries take their step from a sibling rather than from the base: `HandlerComponent` is +`PromoteAsync`, whose `Handler` impl needs `Provider` to be a `TryComputer`, and each +`…Ref` entry needs `Provider` to answer the owned member over a borrowed input. + +## Common Mistakes + +**Only the one-step entries serve a hand-written `Computer`.** `TryComputerComponent` and +`AsyncComputerComponent` need only the base, so `PromoteComputer` answers them for any +`Computer`. `HandlerComponent` looks for a `TryComputer` on `Double` itself, which a hand-written +provider not wired to the bundle lacks, so the check fails: + +```text +error[E0277]: the trait bound `Double: DelegateComponent` is not satisfied +... + = note: required for `Double` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` +``` + +Spell the two steps out as `PromoteAsync>`, or write the base with +[`#[cgp_computer]`](../../macros/cgp_computer.md), which wires it to `PromoteComputer`. ## Related constructs -- [`#[cgp_computer]`](../../macros/cgp_computer.md) — generates a `Computer` provider and wires - `PromoteComputer` across the family. +- [`#[cgp_computer]`](../../macros/cgp_computer.md) — generates a `Computer` provider and wires it to + `PromoteComputer`. - [`PromoteTryComputer`](promote_try_computer.md), [`PromoteProducer`](promote_producer.md), [`PromoteAsyncComputer`](promote_async_computer.md), [`PromoteHandler`](promote_handler.md) — the - bundles for the other base traits. + bundles for the other bases. - [`Promote`](promote.md), [`PromoteAsync`](promote_async.md), [`PromoteRef`](promote_ref.md) — the single-step lifts this table wires. -- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family it - fills in. +- [`Computer`](../../components/handler/computer.md), + [`Handler`](../../components/handler/handler.md) — the family it fills in. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_handler.md b/docs/reference/providers/handler/promote_handler.md index dd488067..269f2a2c 100644 --- a/docs/reference/providers/handler/promote_handler.md +++ b/docs/reference/providers/handler/promote_handler.md @@ -1,63 +1,134 @@ --- +title: 'PromoteHandler — Handler from an async Result' +description: 'The promotion bundle that fills in Handler and the async by-reference members from an AsyncComputer whose output is a Result, via TryPromote.' sidebar_label: 'PromoteHandler' sidebar_position: 12 --- # `PromoteHandler` -Fill in the handler family from a provider that implements `Handler`, the most general base. +Fill in the async fallible members of the handler family from an `AsyncComputer` whose output is a +`Result`. :::info ### Generated machinery -**You are not expected to name `PromoteHandler` directly.** It is wired for a generated provider whose -base is the async fallible handler. You name it by hand only when wiring a hand-written `Handler`'s -family explicitly. This page explains what that wiring emits. +**You are not expected to name `PromoteHandler` directly.** +[`#[cgp_computer]`](../../macros/cgp_computer.md) wires the provider it generates for an `async fn` +returning `Result` to `PromoteHandler`. A context names the bundle to route its own components +through such a provider, or through its `HandlerComponent` entry, which serves any `AsyncComputer` +returning `Result`. This page explains what the bundle emits. ::: ## Overview -`PromoteHandler` starts from the most general base, a provider that implements -[`Handler`](../../components/handler/handler.md), and fills in the rest of the family on a **context**, the -type a method runs on. Like every CGP provider, it carries no runtime value. +`PromoteHandler` starts from an `AsyncComputer` whose output is a `Result` over the +context's error type, the base `#[cgp_computer]` builds for an `async fn` returning `Result`, and +fills in the fallible async members on a [**context**](/docs/reference/glossary#context), the type +the implementation runs against. Despite its name, its base is not a `Handler`: it produces the +`Handler` by reading the base's `Result` as the failure path. Like every CGP provider, it carries no +runtime value. ## Usage It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base -`Handler` provider: +provider: ```rust delegate_components! { App { - [HandlerComponent, HandlerRefComponent]: PromoteHandler, + HandlerComponent: PromoteHandler, } } ``` +It also answers `AsyncComputerRefComponent` and `HandlerRefComponent`, but those need a base that +takes its input by reference; a base over an owned `u64` answers only `HandlerComponent`. + +## Examples + +An async `#[cgp_computer]` function returning `Result` answers `handle` through the bundle: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::CanHandle; + +#[cgp_computer] +pub async fn checked_double(value: u64) -> Result { + value.checked_mul(2).ok_or_else(|| "overflow".to_owned()) +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + HandlerComponent: PromoteHandler, + } +} + +check_components! { + App { + HandlerComponent: ((), u64), + } +} + +pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.handle(code, 21).await, Ok(42)); + assert_eq!(App.handle(code, u64::MAX).await, Err("overflow".to_owned())); +} +``` + +The function's error type is `String`, which must equal `App`'s, since `TryPromote` passes the `Err` +through unconverted. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). + ## When to use it -**Reach for `PromoteHandler` when the base is the fully general async fallible `Handler`** and you wire -its family by hand. For a less capable base, use the bundle that matches it: -[`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), -[`PromoteProducer`](promote_producer.md), or [`PromoteAsyncComputer`](promote_async_computer.md). +**Reach for `PromoteHandler` when the base is an `AsyncComputer` returning `Result`**, generated +from an `async fn` or written by hand. For an infallible async base use +[`PromoteAsyncComputer`](promote_async_computer.md), and for a synchronous base the bundle that +matches it: [`PromoteComputer`](promote_computer.md), +[`PromoteTryComputer`](promote_try_computer.md), or [`PromoteProducer`](promote_producer.md). ## Under the hood -`PromoteHandler` is a [`delegate_components!`](../../macros/delegate_components.md) table over a generic -inner `Provider`. It routes `HandlerComponent` to [`TryPromote`](try_promote.md), which exposes the -handler as an async computer returning an explicit `Result`, and defers the async-ref components to -[`PromoteAsyncComputer`](promote_async_computer.md). +`PromoteHandler` is a [`delegate_components!`](../../macros/delegate_components.md) table over a +generic inner `Provider`: + +```rust +delegate_components! { + + new PromoteHandler { + HandlerComponent: TryPromote, + [ + AsyncComputerRefComponent, + HandlerRefComponent, + ] -> + PromoteAsyncComputer, + } +} +``` + +It routes `HandlerComponent` to [`TryPromote`](try_promote.md), whose `Handler` impl reads an +`AsyncComputer` returning `Result` as a fallible handler, one step from the base, so it serves a +hand-written base too. The by-reference members forward to +[`PromoteAsyncComputer`](promote_async_computer.md)'s entries, which route through +[`PromoteRef`](promote_ref.md). ## Related constructs -- [`PromoteAsyncComputer`](promote_async_computer.md) — the bundle this defers its async-ref components - to. +- [`PromoteAsyncComputer`](promote_async_computer.md) — the bundle this forwards its by-reference + members to. - [`TryPromote`](try_promote.md) — the lift it routes the handler slot through. - [`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), - [`PromoteProducer`](promote_producer.md) — the bundles for the other base traits. -- [`Handler`](../../components/handler/handler.md) — the base and the most general family member. + [`PromoteProducer`](promote_producer.md) — the bundles for the synchronous bases. +- [`Handler`](../../components/handler/handler.md) — the family member it produces. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_producer.md b/docs/reference/providers/handler/promote_producer.md index 98c4221b..ca26a92b 100644 --- a/docs/reference/providers/handler/promote_producer.md +++ b/docs/reference/providers/handler/promote_producer.md @@ -1,4 +1,6 @@ --- +title: 'PromoteProducer — the family from a Producer' +description: 'The promotion bundle that fills in the input-taking handler family from an input-free Producer; #[cgp_producer] wires its generated provider to it.' sidebar_label: 'PromoteProducer' sidebar_position: 10 --- @@ -12,58 +14,139 @@ Fill in the handler family from a provider that implements `Producer`. ### Generated machinery **You are not expected to name `PromoteProducer` directly.** -[`#[cgp_producer]`](../../macros/cgp_producer.md) wires it across the family for the provider it -generates. You name `PromoteProducer` by hand only when wiring a hand-written producer's -family explicitly. This page explains what that wiring emits. +[`#[cgp_producer]`](../../macros/cgp_producer.md) wires the provider it generates to +`PromoteProducer`. A context names the bundle only to route its own components through such a +provider, or through the one entry that serves any producer, as [Common Mistakes](#common-mistakes) +sets out. This page explains what the bundle emits. ::: ## Overview -`PromoteProducer` starts from a [`Producer`](../../components/handler/producer.md), a provider that -takes no input, and fills in every input-taking member of the handler family on a **context**, the -type a method runs on. The single produced value flows out of every handler shape regardless -of the input, which the promotion discards. Like every CGP provider, it carries no runtime value. +`PromoteProducer` starts from a [`Producer`](../../components/handler/producer.md), a +provider that takes no input, and fills in every input-taking member of the handler family on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. The +single produced value flows out of every handler shape regardless of the input, which the promotion +discards. Like every CGP provider, it carries no runtime value. ## Usage It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one type parameter, the base `Producer` provider. The base answers `ProducerComponent`, and `PromoteProducer` answers -`ComputerComponent` (and the rest of the family) by discarding the input and calling the producer: +`ComputerComponent` and the rest of the family by discarding the input and calling the producer: ```rust delegate_components! { App { - ProducerComponent: MakeDefault, - ComputerComponent: PromoteProducer, + ProducerComponent: DefaultPort, + [ComputerComponent, TryComputerComponent]: PromoteProducer, } } ``` -Most code gets this wiring from [`#[cgp_producer]`](../../macros/cgp_producer.md) rather than writing it. +## Examples + +A `#[cgp_producer]` function answers the producer and two input-taking members: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{CanCompute, CanProduce, CanTryCompute}; + +#[cgp_producer] +pub fn default_port() -> u16 { + 8080 +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ProducerComponent: DefaultPort, + [ComputerComponent, TryComputerComponent]: PromoteProducer, + } +} + +check_components! { + App { + ProducerComponent: (), + [ComputerComponent, TryComputerComponent]: ((), u64), + } +} + +pub fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.produce(code), 8080); + assert_eq!(App.compute(code, 999_u64), 8080); + assert_eq!(App.try_compute(code, 999_u64), Ok(8080)); +} +``` + +Every input-taking member ignores the `999` it is given and returns the produced `8080`. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). ## When to use it -**Reach for `PromoteProducer` when the base is an input-free `Producer`** and you wire its family by -hand rather than through [`#[cgp_producer]`](../../macros/cgp_producer.md). For an input-taking base use -[`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), +**Reach for `PromoteProducer` when a context routes input-taking components through a producer**, +usually one generated by [`#[cgp_producer]`](../../macros/cgp_producer.md). For an input-taking base +use [`PromoteComputer`](promote_computer.md), [`PromoteTryComputer`](promote_try_computer.md), [`PromoteAsyncComputer`](promote_async_computer.md), or [`PromoteHandler`](promote_handler.md). ## Under the hood -`PromoteProducer` is a [`delegate_components!`](../../macros/delegate_components.md) table over a generic -inner `Provider`. It routes `ComputerComponent` to [`Promote`](promote.md), which discards the -computer's input and calls the producer, and defers every remaining component to -[`PromoteComputer`](promote_computer.md), so the produced value reaches every handler shape. +`PromoteProducer` is a [`delegate_components!`](../../macros/delegate_components.md) table over a +generic inner `Provider`: + +```rust +delegate_components! { + + new PromoteProducer { + ComputerComponent: Promote, + [ + ComputerRefComponent, + TryComputerComponent, + TryComputerRefComponent, + AsyncComputerComponent, + AsyncComputerRefComponent, + HandlerComponent, + HandlerRefComponent, + ] -> + PromoteComputer, + } +} +``` + +It routes `ComputerComponent` to [`Promote`](promote.md), which discards the computer's input and +calls the producer, and forwards every remaining key to [`PromoteComputer`](promote_computer.md)'s +own entry, so each is derived from the producer's `Computer` form. Because that computer accepts an +input of any type, including a borrow, the `…Ref` members work too. + +## Common Mistakes + +**Only the `ComputerComponent` entry serves a hand-written producer.** Every other entry goes +through `PromoteComputer

`, which looks for a `Computer` on the producer itself. A hand-written +producer not wired to the bundle has none, so wiring `TryComputerComponent` to +`PromoteProducer` fails at the check: + +```text +error[E0277]: the trait bound `MagicNumber: DelegateComponent` is not satisfied +... + = note: required for `MagicNumber` to implement `Computer` +``` + +Write the producer with `#[cgp_producer]`, or wire the hand-written producer to the bundle itself; +the [`Producer`](../../components/handler/producer.md#common-mistakes) page shows both. ## Related constructs -- [`#[cgp_producer]`](../../macros/cgp_producer.md) — generates a `Producer` provider and wires +- [`#[cgp_producer]`](../../macros/cgp_producer.md) — generates a `Producer` provider and wires it to `PromoteProducer`. - [`Promote`](promote.md) — the lift that discards a computer's input and calls the producer. -- [`PromoteComputer`](promote_computer.md) — the bundle this defers to. -- [`Producer`](../../components/handler/producer.md), [`Computer`](../../components/handler/computer.md) — the base and - the family it fills in. +- [`PromoteComputer`](promote_computer.md) — the bundle this forwards to. +- [`Producer`](../../components/handler/producer.md), + [`Computer`](../../components/handler/computer.md) — the base and the family it fills in. The ideas behind it: diff --git a/docs/reference/providers/handler/promote_ref.md b/docs/reference/providers/handler/promote_ref.md index fc75a86f..5dccde73 100644 --- a/docs/reference/providers/handler/promote_ref.md +++ b/docs/reference/providers/handler/promote_ref.md @@ -1,55 +1,111 @@ --- +title: 'PromoteRef — bridge owned and borrowed inputs' +description: 'The single-step lift between a handler family member and its …Ref companion: deref an owned input for a …Ref provider, or pass a borrow as the input.' sidebar_label: 'PromoteRef' sidebar_position: 6 --- # `PromoteRef` -Bridge between value handlers and reference handlers by dereferencing. +Bridge between by-value handlers and by-reference handlers, in both directions. -:::info +## Overview -### Generated machinery +`PromoteRef` lets a provider written for one input mode serve a slot that uses the other, +without manual dereference code, on a [**context**](/docs/reference/glossary#context), the type the +implementation runs against. It is the most thoroughly implemented promotion: it covers all four +handler families, `Computer`, `TryComputer`, `AsyncComputer`, and `Handler`, in both directions, and +the two directions ask different things of the inner provider. Every promotion bundle routes its +`…Ref` slots through it, and it is written by hand when a context wires one slot at a time. Like +every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. -**You are not expected to name `PromoteRef` directly.** The promotion bundles such as -[`PromoteComputer`](promote_computer.md) wire it into every `…Ref` slot, and the bundles are what -[`#[cgp_computer]`](../../macros/cgp_computer.md) and [`#[cgp_producer]`](../../macros/cgp_producer.md) -generate. You reach for it by hand only when wiring the handler family one slot at a time. This page -explains what that wiring emits. +## Usage -::: +Import it from `cgp::extra::handler`; it is not in the prelude. It takes one type parameter, the +inner provider, and the direction depends on the slot it fills: -## Overview +- **A by-reference slot**, such as `ComputerRefComponent`, needs an inner by-value provider whose + input is a reference, `Computer` at every lifetime `'a`. `PromoteRef` + passes the borrow straight through as that input. A provider written for an owned `u64` does not + qualify. +- **A by-value slot**, such as `ComputerComponent`, needs an inner by-reference provider and an + input that dereferences to its `Input`, such as a `Box` for a `ComputerRef` over `String`. + `PromoteRef` calls the inner provider on `input.deref()`. -`PromoteRef` lets a provider written to take a value serve a slot that takes a reference, and -the reverse, without manual dereference code. It is the most thoroughly implemented promotion: it -covers all four handler families in both directions, on a **context**, the type a method runs -on. Like every CGP provider, it carries no runtime value; the inner provider rides in -`PhantomData`. +```rust +use cgp::extra::handler::PromoteRef; -## Usage +delegate_components! { + App { + ComputerRefComponent: PromoteRef, + ComputerComponent: PromoteRef, + } +} +``` + +## Examples -Import it from `cgp::extra::handler`. It takes one type parameter, the inner provider. To fill a -by-reference slot such as `ComputerRefComponent`, the inner provider is a by-value provider whose input -is a reference (`Computer`), and `PromoteRef` calls it on the borrowed input: +Both directions on one context, each from a hand-written provider: ```rust -use cgp::extra::handler::PromoteRef; +use cgp::prelude::*; +use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef, PromoteRef}; + +/// A by-value computer whose input is a reference. +#[cgp_new_provider] +impl Computer for DoubleRef { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: &u64) -> u64 { + input * 2 + } +} + +/// A by-reference computer over a `String`. +#[cgp_new_provider] +impl ComputerRef for StringLength { + type Output = usize; + + fn compute_ref(_context: &Context, _code: PhantomData, input: &String) -> usize { + input.len() + } +} + +pub struct App; -// `DoubleRef` is a `Computer<_, _, &u64>`; PromoteRef serves the by-reference slot from it. delegate_components! { App { ComputerRefComponent: PromoteRef, + ComputerComponent: PromoteRef, } } + +check_components! { + App { + ComputerRefComponent: ((), u64), + ComputerComponent: ((), Box), + } +} + +pub fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute_ref(code, &21), 42); + assert_eq!(App.compute(code, Box::new("hello".to_owned())), 5); +} ``` +`compute_ref` hands `DoubleRef` the borrowed `&21` as its input, and `compute` dereferences the +`Box` for `StringLength`. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). + ## When to use it -**You rarely reach for `PromoteRef` by hand.** Every promotion bundle wires it into the `…Ref` slots, so -the by-reference family follows from a by-value provider automatically. Reach for it directly only when -wiring a `…Ref` slot by hand. For the other axes use [`Promote`](promote.md), -[`PromoteAsync`](promote_async.md), or [`TryPromote`](try_promote.md). +**Reach for `PromoteRef` when wiring a slot by hand across the owned and borrowed forms.** Every +promotion bundle already routes its `…Ref` slots here, so a macro-generated provider needs no +`PromoteRef` of its own; it serves the `…Ref` slots only when its function takes a reference +parameter, since an owned-input provider cannot accept the borrow. For the other axes use +[`Promote`](promote.md), [`PromoteAsync`](promote_async.md), or [`TryPromote`](try_promote.md). ## Under the hood @@ -59,25 +115,42 @@ wiring a `…Ref` slot by hand. For the other axes use [`Promote`](promote.md), pub struct PromoteRef(pub PhantomData); ``` -For each of `Computer`/`ComputerRef`, `TryComputer`/`TryComputerRef`, `AsyncComputer`/`AsyncComputerRef`, -and `Handler`/`HandlerRef`, it provides two impls. One direction implements the by-value trait given an -inner by-reference provider plus `Input: Deref`, calling the inner provider on -`input.deref()`. The other direction implements the by-reference trait given an inner by-value provider -that works `for<'a>` over `&'a Input`, calling the inner provider on the borrowed input. A provider -written to take `&T` can then serve a slot that hands it a smart pointer to `T`, and the reverse. +For each of `Computer`/`ComputerRef`, `TryComputer`/`TryComputerRef`, +`AsyncComputer`/`AsyncComputerRef`, and `Handler`/`HandlerRef`, it provides two impls. The by-value +impl requires an inner by-reference provider plus `Input: Deref`, and calls the +inner provider on `input.deref()`. The by-reference impl requires an inner by-value provider that +works `for<'a>` over `&'a Input`, and calls it on the borrowed input: + +```rust +#[cgp_provider] +impl ComputerRef + for PromoteRef +where + Provider: for<'a> Computer, +{ + type Output = Output; + + fn compute_ref(context: &Context, tag: PhantomData, input: &Input) -> Self::Output { + Provider::compute(context, tag, input) + } +} +``` + +The fallible impls require the context to have an error type. ## Related constructs - [`Promote`](promote.md), [`PromoteAsync`](promote_async.md), [`TryPromote`](try_promote.md) — the other single-step lifts, along the fallibility and asynchrony axes rather than the borrow axis. -- [`PromoteComputer`](promote_computer.md) and the other bundles — wire `PromoteRef` into every `…Ref` - slot automatically. -- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family - members and their by-reference companions it bridges. +- [`PromoteComputer`](promote_computer.md) and the other bundles — route every `…Ref` slot through + `PromoteRef`. +- [`ComputerRef`](../../components/handler/computer_ref.md), + [`HandlerRef`](../../components/handler/handler_ref.md) — the by-reference companions it bridges. The ideas behind it: -- [Handlers](/docs/concepts/handlers) — the family, including the by-reference companion of each member. +- [Handlers](/docs/concepts/handlers) — the family, including the by-reference companion of each + member. ## Source diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md index 645ef82e..64c50450 100644 --- a/docs/reference/providers/handler/promote_try_computer.md +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -1,28 +1,35 @@ --- +title: 'PromoteTryComputer — the family from a Result' +description: 'The promotion bundle that fills in the handler family from a Computer whose output is a Result, the base #[cgp_computer] builds for a fallible function.' sidebar_label: 'PromoteTryComputer' sidebar_position: 9 --- # `PromoteTryComputer` -Fill in the handler family from a provider that implements `TryComputer`. +Fill in the handler family from a `Computer` whose output is a `Result`. :::info ### Generated machinery -**You are not expected to name `PromoteTryComputer` directly.** It is wired for a generated provider -that implements the fallible synchronous base. You name it by hand only when wiring a hand-written -`TryComputer`'s family explicitly. This page explains what that wiring emits. +**You are not expected to name `PromoteTryComputer` directly.** +[`#[cgp_computer]`](../../macros/cgp_computer.md) wires the provider it generates for a function +returning `Result` to `PromoteTryComputer`. A context names the bundle only to route its own +components through such a provider, or through the one entry that serves any base, as +[Common Mistakes](#common-mistakes) sets out. This page explains what the bundle emits. ::: ## Overview -`PromoteTryComputer` starts from a `Computer` whose output is a `Result`, the base -[`#[cgp_computer]`](../../macros/cgp_computer.md) generates for a function returning `Result`, and fills in the rest of the handler family on a **context**, the type a method runs -on. It turns that base into a `TryComputer` through [`TryPromote`](try_promote.md), then derives the rest of the family -from there. Like every CGP provider, it carries no runtime value. +`PromoteTryComputer` starts from a `Computer` whose output is a `Result` over the +context's error type, the base [`#[cgp_computer]`](../../macros/cgp_computer.md) generates for a +function returning `Result`, and fills in the rest of the handler family on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. It reads +that `Result` as the failure path for the fallible slot through [`TryPromote`](try_promote.md), and +derives the other members from the computer form through [`PromoteComputer`](promote_computer.md). +Like every CGP provider, it carries no runtime value. ## Usage @@ -32,35 +39,117 @@ provider, a `Computer` returning `Result`: ```rust delegate_components! { App { - [TryComputerComponent, HandlerComponent]: PromoteTryComputer, + [TryComputerComponent, HandlerComponent]: PromoteTryComputer, } } ``` +Here `CheckedDouble` comes from `#[cgp_computer]`, which is what lets the `HandlerComponent` entry +resolve. + +## Examples + +A fallible `#[cgp_computer]` function answers the fallible members through the bundle: + +```rust +use cgp::prelude::*; +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::{CanHandle, CanTryCompute}; + +#[cgp_computer] +pub fn checked_double(value: u64) -> Result { + value.checked_mul(2).ok_or_else(|| "overflow".to_owned()) +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + [TryComputerComponent, HandlerComponent]: PromoteTryComputer, + } +} + +check_components! { + App { + [TryComputerComponent, HandlerComponent]: ((), u64), + } +} + +pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.try_compute(code, 21), Ok(42)); + assert_eq!(App.try_compute(code, u64::MAX), Err("overflow".to_owned())); + assert_eq!(App.handle(code, 21).await, Ok(42)); +} +``` + +The function's error type is `String`, and it must equal `App`'s, because `TryPromote` passes the +`Err` through unconverted. `App` is an [environmental +context](/docs/reference/glossary#environmental-context). + ## When to use it -**Reach for `PromoteTryComputer` when the base provider is a synchronous `Computer` returning `Result`** and -you wire its family by hand. For a plain `Computer` base use [`PromoteComputer`](promote_computer.md); -for the other bases use [`PromoteProducer`](promote_producer.md), -[`PromoteAsyncComputer`](promote_async_computer.md), or [`PromoteHandler`](promote_handler.md). +**Reach for `PromoteTryComputer` when a context routes its handler components through a fallible +`#[cgp_computer]` provider.** For a plain `Computer` base use +[`PromoteComputer`](promote_computer.md); for the other bases use +[`PromoteProducer`](promote_producer.md), [`PromoteAsyncComputer`](promote_async_computer.md), or +[`PromoteHandler`](promote_handler.md). ## Under the hood `PromoteTryComputer` is a [`delegate_components!`](../../macros/delegate_components.md) table over a -generic inner `Provider`. It routes `TryComputerComponent` to [`TryPromote`](try_promote.md), which -exposes the fallible base as a computer returning an explicit `Result`, and defers every remaining -component to [`PromoteComputer`](promote_computer.md), so the rest of the family is derived from that -computer form. +generic inner `Provider`: + +```rust +delegate_components! { + + new PromoteTryComputer { + TryComputerComponent: TryPromote, + [ + ComputerRefComponent, + TryComputerRefComponent, + AsyncComputerComponent, + AsyncComputerRefComponent, + HandlerComponent, + HandlerRefComponent, + ] -> + PromoteComputer, + } +} +``` + +It routes `TryComputerComponent` to [`TryPromote`](try_promote.md), which reads the base's `Result` +output as the failure path, and forwards every remaining key to +[`PromoteComputer`](promote_computer.md)'s own entry for it, with the `->` operator, so those +members derive from the computer form. + +## Common Mistakes + +**Only the `TryComputerComponent` entry serves a hand-written base.** `TryPromote

` needs only a +`Computer` returning `Result`, but `HandlerComponent` goes through `PromoteComputer

` to +`PromoteAsync

`, which looks for a `TryComputer` on the base itself. A hand-written base not wired +to the bundle fails at the check: + +```text +error[E0277]: the trait bound `CheckedDouble: DelegateComponent` is not satisfied +... + = note: required for `CheckedDouble` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` +``` + +Write the base with `#[cgp_computer]`, or wire the handler slot as +`PromoteAsync>`. ## Related constructs -- [`PromoteComputer`](promote_computer.md) — the bundle this defers to once the base is a plain - computer. +- [`PromoteComputer`](promote_computer.md) — the bundle this forwards to for the computer form. - [`TryPromote`](try_promote.md) — the lift it routes the fallible slot through. - [`PromoteProducer`](promote_producer.md), [`PromoteAsyncComputer`](promote_async_computer.md), - [`PromoteHandler`](promote_handler.md) — the bundles for the other base traits. -- [`TryComputer`](../../components/handler/try_computer.md), [`Handler`](../../components/handler/handler.md) — the - family it fills in. + [`PromoteHandler`](promote_handler.md) — the bundles for the other bases. +- [`TryComputer`](../../components/handler/try_computer.md), + [`Handler`](../../components/handler/handler.md) — the family it fills in. The ideas behind it: diff --git a/docs/reference/providers/handler/return_input.md b/docs/reference/providers/handler/return_input.md index 024682a0..5111173a 100644 --- a/docs/reference/providers/handler/return_input.md +++ b/docs/reference/providers/handler/return_input.md @@ -1,4 +1,6 @@ --- +title: 'ReturnInput — the identity handler' +description: 'The handler that returns its input unchanged, the neutral stage of a pipeline, as a Computer, TryComputer, AsyncComputer, or Handler.' sidebar_label: 'ReturnInput' sidebar_position: 3 --- @@ -9,15 +11,16 @@ The identity handler: return the input unchanged as the output. ## Overview -`ReturnInput` ignores the **context**, the type a method runs on, and the `Code` tag, and -returns its input as its output. It is the neutral element of handler composition: putting it before or -after any other handler leaves that handler's behavior unchanged. It fills a handler slot where no -transformation is wanted, serves as the base case of a conditionally-built pipeline, and stands in as a -placeholder stage. Like every CGP provider, it carries no runtime value; it is a plain unit struct. +`ReturnInput` ignores the [**context**](/docs/reference/glossary#context), the type the +implementation runs against, and the `Code` tag, and returns its input as its output. It is the +neutral element of handler composition: putting it before or after any other handler leaves that +handler's behavior unchanged. It fills a handler slot where no transformation is wanted and stands +in as a placeholder stage. Like every CGP provider, it carries no runtime value; it is a plain unit +struct. ## Usage -Import it from `cgp::extra::handler`. It takes no type parameter: +Import it from `cgp::extra::handler`; it is not in the prelude. It takes no type parameter: ```rust use cgp::extra::handler::ReturnInput; @@ -33,30 +36,45 @@ Wired this way, computing over any input returns that input unchanged. ## Examples -`ReturnInput` is most useful as a pass-through stage. A pipeline that conditionally transforms its input -can fall back to `ReturnInput` when there is nothing to do, so the slot is always filled: +`ReturnInput` as the middle stage of a pipeline, where it changes nothing: ```rust -use cgp::extra::handler::{PipeHandlers, ReturnInput}; +use cgp::prelude::*; +use cgp::extra::handler::{CanCompute, PipeHandlers, ReturnInput}; + +#[cgp_computer] +pub fn add_one(value: u64) -> u64 { + value + 1 +} + +pub struct App; -// A pipeline whose middle stage is a no-op for this context. delegate_components! { App { - ComputerComponent: - PipeHandlers, + ComputerComponent: PipeHandlers, } } + +check_components! { + App { + ComputerComponent: ((), u64), + } +} + +pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 5), 7); // 5 -> 6 -> 6 -> 7 +} ``` -The `ReturnInput` stage passes its input straight to `Format`, so the pipeline behaves as -`PipeHandlers`. +The pipeline behaves as `PipeHandlers`, since the `ReturnInput` stage +passes its input straight on. ## When to use it -**Reach for `ReturnInput` when a handler slot must be filled but no transformation is wanted**, such as -the base case of a pipeline built up conditionally, or a stage that is a no-op for one context. Reach -for a producer written with [`#[cgp_producer]`](../../macros/cgp_producer.md) instead when the slot -should compute a fixed value rather than echo its input. +**Reach for `ReturnInput` when a handler slot must be filled but no transformation is wanted**, such +as a stage that is a no-op for one context, or a pipeline slot that a generic wiring always expects. +Reach for a producer written with [`#[cgp_producer]`](../../macros/cgp_producer.md) instead when the +slot should yield a fixed value rather than echo its input. ## Under the hood @@ -67,17 +85,17 @@ pub struct ReturnInput; ``` It implements `Computer`, `TryComputer`, `AsyncComputer`, and `Handler`, in each case setting -`Output = Input` and returning the input directly. The fallible variants wrap the input in `Ok`, so they -require the context to have an error type. +`Output = Input` and returning the input directly. The fallible variants wrap the input in `Ok`, so +they require the context to have an error type. It has no `…Ref` impl. ## Related constructs - [`ComposeHandlers`](compose_handlers.md), [`PipeHandlers`](pipe_handlers.md) — the composition combinators `ReturnInput` is the neutral element of. -- [`Producer`](../../components/handler/producer.md) — for a stage that computes a value rather than echoing - the input. -- [`Computer`](../../components/handler/computer.md), [`Handler`](../../components/handler/handler.md) — the family it - implements. +- [`Producer`](../../components/handler/producer.md) — for a stage that yields a value rather than + echoing the input. +- [`Computer`](../../components/handler/computer.md), + [`Handler`](../../components/handler/handler.md) — the family it implements. The ideas behind it: diff --git a/docs/reference/providers/handler/try_promote.md b/docs/reference/providers/handler/try_promote.md index 83b74fc5..50617589 100644 --- a/docs/reference/providers/handler/try_promote.md +++ b/docs/reference/providers/handler/try_promote.md @@ -1,4 +1,6 @@ --- +title: 'TryPromote — Result outputs and failure' +description: 'The single-step lift, in both directions, between a computer whose output is a Result and a genuinely fallible TryComputer or Handler.' sidebar_label: 'TryPromote' sidebar_position: 7 --- @@ -7,46 +9,117 @@ sidebar_position: 7 Bridge in both directions between a `Result`-valued output and a fallible handler trait. -:::info - -### Generated machinery - -**You are not expected to name `TryPromote` directly.** The promotion bundle -[`PromoteTryComputer`](promote_try_computer.md) wires it, and [`PipeMonadic`](../monad/pipe_monadic.md) -uses it internally to bridge fallible and infallible handlers. You reach for it by hand only when -wiring the handler family one slot at a time. This page explains what that wiring does. - -::: - ## Overview `TryPromote` unifies the two ways of expressing fallibility: a handler that *returns* a `Result`, and a genuinely fallible handler trait. It converts between them in both directions on a -**context**, the type a method runs on. Every impl requires the context to have an error type. -Like every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. +[**context**](/docs/reference/glossary#context), the type the implementation runs against, and every +impl requires the context to have an error type, which the `Result`'s error must equal. The +[`PromoteTryComputer`](promote_try_computer.md) and [`PromoteHandler`](promote_handler.md) bundles +route through it, [`PipeMonadic`](../monad/pipe_monadic.md) uses it internally, and it is written by +hand when a context wires one slot at a time. Like every CGP provider, it carries no runtime value; +the inner provider rides in `PhantomData`. ## Usage -Import it from `cgp::extra::handler`. It takes one type parameter, the inner provider: +Import it from `cgp::extra::handler`; it is not in the prelude. It takes one type parameter, the +inner provider, and the direction depends on the slot it fills: ```rust use cgp::extra::handler::TryPromote; -// Turn a Computer that returns Result into a genuine TryComputer. delegate_components! { App { - TryComputerComponent: TryPromote, + // A Computer returning Result serves the fallible slot. + TryComputerComponent: TryPromote, + // A TryComputer serves the infallible slot, returning its Result as a value. + ComputerComponent: TryPromote, + } +} +``` + +## Examples + +Both directions on one context, each from a hand-written provider: + +```rust +use core::num::ParseIntError; +use cgp::prelude::*; +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::{DebugError, RaiseFrom}; +use cgp::extra::handler::{CanCompute, CanTryCompute, TryPromote}; + +/// A computer whose output is a `Result` in the context's error type. +#[cgp_new_provider] +impl Computer for CheckedDouble +where + Context: HasErrorType, +{ + type Output = Result; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> Result { + input.checked_mul(2).ok_or_else(|| "overflow".to_owned()) + } +} + +/// A genuinely fallible computer. +#[cgp_impl(new ParseU64)] +#[uses(CanRaiseError)] +#[use_type(HasErrorType.Error)] +impl TryComputer { + type Output = u64; + + fn try_compute(&self, _code: PhantomData, input: String) -> Result { + input.parse().map_err(Self::raise_error) + } +} + +pub struct App; + +delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + + TryComputerComponent: TryPromote, + ComputerComponent: TryPromote, + } +} + +check_components! { + App { + TryComputerComponent: ((), u64), + ComputerComponent: ((), String), } } + +pub fn demo() { + let code = PhantomData::<()>; + + // The `Result` output becomes the fallible interface. + assert_eq!(App.try_compute(code, 21), Ok(42)); + assert_eq!(App.try_compute(code, u64::MAX), Err("overflow".to_owned())); + + // The fallible computer surfaces its `Result` as a plain value. + assert_eq!(App.compute(code, "12".to_owned()), Ok(12)); +} ``` +`CheckedDouble`'s output is `Result`, and `App`'s error type is `String`, so +`TryPromote` reads that `Result` as the failure path. `TryPromote` goes the +other way: `compute` returns `ParseU64`'s whole `Result`. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). + ## When to use it -**You rarely reach for `TryPromote` by hand.** The [`PromoteTryComputer`](promote_try_computer.md) and -[`PromoteHandler`](promote_handler.md) bundles wire it, and [`PipeMonadic`](../monad/pipe_monadic.md) -uses it internally. Reach for it directly only to convert between a `Result`-valued output and a -fallible trait when wiring a slot by hand. For the other lifts use [`Promote`](promote.md), -[`PromoteAsync`](promote_async.md), or [`PromoteRef`](promote_ref.md). +**Reach for `TryPromote` to convert between a `Result`-valued output and a fallible trait when +wiring a slot by hand.** A `#[cgp_computer]` function returning `Result` is already wired to +[`PromoteTryComputer`](promote_try_computer.md), which routes its fallible slot here. For the other +lifts use [`Promote`](promote.md), [`PromoteAsync`](promote_async.md), or +[`PromoteRef`](promote_ref.md). ## Under the hood @@ -56,24 +129,26 @@ fallible trait when wiring a slot by hand. For the other lifts use [`Promote`](p pub struct TryPromote(pub PhantomData); ``` -- As a `TryComputer`, it requires the inner `Provider: Computer` whose `Output` is itself a - `Result`, and unwraps that into the `TryComputer` result. This turns a - computer that *returns* a `Result` into a genuine fallible computer. +- As a `TryComputer`, it requires the inner `Provider: Computer` whose `Output` is + `Result`, and returns that result. This turns a computer that *returns* a + `Result` into a genuine fallible computer. - As a `Computer`, it goes the other way: given `Provider: TryComputer`, its output type is `Result`, surfacing the fallible result as an ordinary value. -The analogous pair lifts between `Handler` (from an `AsyncComputer` returning a `Result`) and -`AsyncComputer` (from a `Handler`). All four impls require the context to have an error type. +The analogous pair lifts between `Handler`, from an `AsyncComputer` returning a `Result`, and +`AsyncComputer`, from a `Handler`. All four impls require the context to have an error type. Neither +direction removes a failure path; the second only moves it into the output. ## Related constructs - [`Promote`](promote.md), [`PromoteAsync`](promote_async.md), [`PromoteRef`](promote_ref.md) — the other single-step lifts. -- [`PromoteTryComputer`](promote_try_computer.md) — the bundle that wires `TryPromote`. -- [`PipeMonadic`](../monad/pipe_monadic.md) — uses `TryPromote` to demote fallible handlers when +- [`PromoteTryComputer`](promote_try_computer.md), [`PromoteHandler`](promote_handler.md) — the + bundles that route through `TryPromote`. +- [`PipeMonadic`](../monad/pipe_monadic.md) — uses `TryPromote` to bridge fallible handlers when composing a fallible monadic pipeline. -- [`TryComputer`](../../components/handler/try_computer.md), [`Handler`](../../components/handler/handler.md) — the - fallible family members it bridges. +- [`TryComputer`](../../components/handler/try_computer.md), + [`Handler`](../../components/handler/handler.md) — the fallible family members it bridges. The ideas behind it: diff --git a/docs/reference/providers/handler/use_input_delegate.md b/docs/reference/providers/handler/use_input_delegate.md index b7da1672..6d4cf639 100644 --- a/docs/reference/providers/handler/use_input_delegate.md +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -1,4 +1,6 @@ --- +title: 'UseInputDelegate — legacy dispatch by input' +description: 'The legacy provider that routes a handler component to a per-input-type provider through a nested table; the open statement replaces it.' sidebar_label: 'UseInputDelegate' sidebar_position: 13 --- @@ -10,24 +12,25 @@ Dispatch a handler to a different inner provider per input type, through a looku ## Overview `UseInputDelegate` chooses a handler provider by the type of the value being handled. An -ordinary handler component is answered by one provider. `UseInputDelegate` performs a second lookup: it -treats the handler's `Input` type as a key and reads the matching inner provider out of a table, so a -single wiring entry on a **context**, the type a method runs on, fans out to many -input-specific providers. Like every CGP provider, it holds no runtime value; the table rides in -`PhantomData`. - -It is the sibling of [`UseDelegate`](../use_delegate.md). Where `UseDelegate` keys on the first generic -parameter of a provider trait, the `Code` for a handler, `UseInputDelegate` keys on the `Input` -parameter, so the provider that handles a value is chosen by the type of that value. The handler -components enable both dispatchers at once. Both are legacy forms: the `open` statement of +ordinary handler component is answered by one provider. `UseInputDelegate` performs a second lookup: +it treats the handler's `Input` type as a key and reads the matching inner provider out of a table, +so a single wiring entry on a [**context**](/docs/reference/glossary#context), the type the +implementation runs against, fans out to many input-specific providers. Like every CGP provider, it +holds no runtime value; the table rides in `PhantomData`. + +It is the sibling of [`UseDelegate`](../use_delegate.md). Where `UseDelegate` keys on the `Code` +parameter of a handler, `UseInputDelegate` keys on the `Input` parameter, so the provider that +handles a value is chosen by the type of that value. The handler components enable both dispatchers +at once. Both are legacy forms: the `open` statement of [`delegate_components!`](../../macros/delegate_components.md#choosing-a-provider-per-type-the-open-statement) -dispatches on the code, the input, or both with no table type, as the next section shows for the +dispatches on the code, the input, or both with no table type, as the Usage section shows for the input. ## Usage -Import it from `cgp::extra::handler`. It takes one type parameter, the lookup table, and is wired -through a nested table that maps each concrete input type to its provider: +Import it from `cgp::extra::handler`; it is not in the prelude. It takes one type parameter, the +lookup table, and is wired through a nested table that maps each concrete input type to its +provider: ```rust use cgp::extra::handler::UseInputDelegate; @@ -35,36 +38,112 @@ use cgp::extra::handler::UseInputDelegate; delegate_components! { App { ComputerComponent: UseInputDelegate, } } ``` -The outer entry routes the handler component to `UseInputDelegate`, and the inner table -maps each input type to the provider responsible for it. The current form stores the same entries on -the context with `open`. Each key has one path segment per type parameter of -`CanCompute`, and a generic first segment matches any code, so the second selects by the -input type: +The outer entry routes the handler component to `UseInputDelegate`, and the inner +table maps each input type to the provider responsible for it. The current form stores the same +entries on the context with `open`. Each key has one path segment per type parameter of +`CanCompute`, and a generic first segment matches any code, so the second selects by +the input type: ```rust delegate_components! { + OpenApp { + open ComputerComponent; + + @ComputerComponent. Code.Circle: CircleArea, + @ComputerComponent. Code.Rectangle: RectangleArea, + } +} +``` + +## Examples + +Two area computers routed by input type, once through the legacy table and once through `open`: + +```rust +use cgp::prelude::*; +use cgp::extra::handler::{CanCompute, UseInputDelegate}; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_computer] +pub fn circle_area(circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius +} + +#[cgp_computer] +pub fn rectangle_area(rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: UseInputDelegate, + } +} + +check_components! { App { + ComputerComponent: [((), Circle), ((), Rectangle)], + } +} + +pub struct OpenApp; + +delegate_components! { + OpenApp { open ComputerComponent; - @ComputerComponent. Code.Circle: ComputeCircleArea, - @ComputerComponent. Code.Rectangle: ComputeRectangleArea, + @ComputerComponent. Code.Circle: CircleArea, + @ComputerComponent. Code.Rectangle: RectangleArea, + } +} + +check_components! { + OpenApp { + ComputerComponent: [((), Circle), ((), Rectangle)], } } + +pub fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute(code, Rectangle { width: 3.0, height: 4.0 }), 12.0); + assert_eq!(OpenApp.compute(code, Rectangle { width: 3.0, height: 4.0 }), 12.0); + assert!((App.compute(code, Circle { radius: 1.0 }) - core::f64::consts::PI).abs() < 1e-9); +} ``` +`App` and `OpenApp` are [environmental contexts](/docs/reference/glossary#environmental-context), +and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: it acts on the +`Input`, while each context decides which provider handles each input type. The two wirings answer +the same calls. + ## When to use it **Read `UseInputDelegate` when you meet it in existing code, and write the `open` form instead.** -Dispatch by input type is common with the [dispatch combinators](../dispatch/index.md), where a matcher -routes each variant of an enum to a handler chosen by the payload type, and `open` expresses it -without a table type. The table form still works, since every handler component keeps the +Dispatch by input type is common with the [dispatch combinators](../dispatch/index.md), where a +matcher routes each variant of an enum to a handler chosen by the payload type, and `open` expresses +it without a table type. The table form still works, since every handler component keeps the `#[derive_delegate(UseInputDelegate)]` that generates it, so existing wiring does not need to change. @@ -76,12 +155,12 @@ change. pub struct UseInputDelegate(pub PhantomData); ``` -Each handler component trait is declared with two -[`#[derive_delegate]`](../../attributes/derive_delegate.md) directives, `UseDelegate` and -`UseInputDelegate`, as on the `Computer` component: +Each handler component trait carries two [`#[derive_delegate]`](../../attributes/derive_delegate.md) +directives, `UseDelegate` and `UseInputDelegate`, as on the `Computer` component: ```rust #[cgp_component(Computer)] +#[prefix(@cgp.extra.handler in DefaultNamespace)] #[derive_delegate(UseDelegate)] #[derive_delegate(UseInputDelegate)] pub trait CanCompute { @@ -91,35 +170,38 @@ pub trait CanCompute { } ``` -The second directive makes [`#[cgp_component]`](../../macros/cgp_component.md) generate a provider impl -that looks `Components` up by the `Input` type and forwards to the matching delegate: +The second directive makes [`#[cgp_component]`](../../macros/cgp_component.md) generate a provider +impl that looks `Components` up by the `Input` type and forwards to the matching delegate. For +`Computer`, `cargo cgp expand` on a component with the same directive shows: ```rust -impl Computer - for UseInputDelegate +impl<__Context__, Code, Input, __Components__, __Delegate__> Computer<__Context__, Code, Input> +for UseInputDelegate<__Components__> where - Components: DelegateComponent, - Delegate: Computer, + __Components__: DelegateComponent<(Input), Delegate = __Delegate__>, + __Delegate__: Computer<__Context__, Code, Input>, { - type Output = Delegate::Output; + type Output = <__Delegate__ as Computer<__Context__, Code, Input>>::Output; - fn compute(context: &Context, code: PhantomData, input: Input) -> Self::Output { - Delegate::compute(context, code, input) + fn compute(__context__: &__Context__, _code: PhantomData, input: Input) -> Self::Output { + __Delegate__::compute(__context__, _code, input) } } ``` -The lookup key is the `Input` type, while `Code` and `Context` pass through unchanged. The same impl -shape is generated for every handler family member. +The lookup key is `(Input)`, the bare type rather than a one-element tuple, while `Code` and the +context pass through unchanged. The same impl shape is generated for every handler family member +except `Producer`, which has no input. ## Related constructs - [`UseDelegate`](../use_delegate.md) — the sibling that keys on the `Code` selector. - [`#[derive_delegate]`](../../attributes/derive_delegate.md) — generates both dispatch impls on a handler component. -- [`delegate_components!`](../../macros/delegate_components.md) — wires it through a nested table. -- [Dispatch combinators](../dispatch/index.md) — the main users of input dispatch, selecting a per-variant - handler by payload type. +- [`delegate_components!`](../../macros/delegate_components.md) — wires it through a nested table, + and carries the `open` statement that replaces it. +- [Dispatch combinators](../dispatch/index.md) — the main users of input dispatch, selecting a + per-variant handler by payload type. - [`DelegateComponent`](../../traits/wiring/delegate_component.md) — the table the lookup reads. The ideas behind it: diff --git a/example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs b/example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs new file mode 100644 index 00000000..191cdebd --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs @@ -0,0 +1,31 @@ +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::prelude::*; + +#[cgp_new_provider] +impl Computer for CheckedDouble +where + Context: HasErrorType, +{ + type Output = Result; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> Result { + input.checked_mul(2).ok_or_else(|| "overflow".to_owned()) + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + HandlerComponent: PromoteTryComputer, + } +} + +check_components! { + App { + HandlerComponent: ((), u64), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.stderr b/example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.stderr new file mode 100644 index 00000000..609eb500 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.stderr @@ -0,0 +1,66 @@ +error[E0277]: the trait bound `CheckedDouble: DelegateComponent` is not satisfied + --> tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs:27:9 + | +27 | HandlerComponent: ((), u64), + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `DelegateComponent` is not implemented for `CheckedDouble` + --> tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs:5:54 + | + 5 | impl Computer for CheckedDouble + | ^^^^^^^^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + BuildAndMergeOutputs + MatchWithFieldHandlersRef + MatchWithValueHandlersMut + MatchWithValueHandlersRef + PipeMonadic + PromoteComputer + PromoteProducer + cgp::prelude::PromoteTryComputer + = note: required for `CheckedDouble` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::PromoteTryComputer` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs:25:1 + | +25 | / check_components! { +26 | | App { +27 | | HandlerComponent: ((), u64), +28 | | } +29 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `CheckedDouble: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs:27:9 + | +27 | HandlerComponent: ((), u64), + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `CheckedDouble` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs:5:1 + | + 5 | / impl Computer for CheckedDouble + 6 | | where + 7 | | Context: HasErrorType, + | |__________________________________________^ + = help: for that trait implementation, expected `cgp::prelude::ComputerComponent`, found `TryComputerComponent` + = note: required for `CheckedDouble` to implement `TryComputer` + = note: required for `PromoteAsync` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::PromoteTryComputer` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/promote_try_computer_common_mistakes_hand_written_base.rs:25:1 + | +25 | / check_components! { +26 | | App { +27 | | HandlerComponent: ((), u64), +28 | | } +29 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/providers/handler/compose_handlers.rs b/example-code/tests/reference/providers/handler/compose_handlers.rs index 4c9239a1..8e1e0728 100644 --- a/example-code/tests/reference/providers/handler/compose_handlers.rs +++ b/example-code/tests/reference/providers/handler/compose_handlers.rs @@ -1,11 +1,10 @@ //! Code from `docs/reference/providers/handler/compose_handlers.md` — `ComposeHandlers`. +//! +//! Pins the Examples program: `Double` then `AddOne`, composed and wired as one computer. -/// ## Usage and Examples -/// -/// `ComposeHandlers` runs `A`, then `B` on `A`'s output. Here `Double` then `AddOne` turns an -/// input of 5 into `(5 * 2) + 1`. -pub mod composing_two_handlers { - use cgp::extra::handler::{ComposeHandlers, ComputerComponent}; +/// ## Examples +pub mod examples { + use cgp::extra::handler::{CanCompute, ComposeHandlers}; use cgp::prelude::*; #[cgp_computer] @@ -26,19 +25,18 @@ pub mod composing_two_handlers { } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), u64), - } + check_components! { + App { + ComputerComponent: ((), u64), } } - #[test] - fn the_output_of_the_first_feeds_the_second() { - use cgp::extra::handler::CanCompute; + pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 5), 11); // (5 * 2) + 1 + } - assert_eq!(App.compute(PhantomData::<()>, 5u64), 11); + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/handler/pipe_handlers.rs b/example-code/tests/reference/providers/handler/pipe_handlers.rs index 7a352502..87b9e975 100644 --- a/example-code/tests/reference/providers/handler/pipe_handlers.rs +++ b/example-code/tests/reference/providers/handler/pipe_handlers.rs @@ -1,14 +1,40 @@ //! Code from `docs/reference/providers/handler/pipe_handlers.md` — `PipeHandlers`. +//! +//! Pins the Examples program: three field-reading computers folded into one pipeline that computes +//! `((5 * foo) + bar) * baz`. -/// ## Usage and Examples -/// -/// `PipeHandlers` folds a list of handlers into one pipeline. `Multiply` and `Add` each -/// read a factor or addend from a context field, so the three-stage list computes -/// `((5 * foo) + bar) * baz`. -pub mod a_pipeline_of_field_readers { - use core::marker::PhantomData; +/// ## Usage +pub mod usage { + use cgp::extra::handler::{CanCompute, PipeHandlers}; + use cgp::prelude::*; + + #[cgp_computer] + pub fn double(value: u64) -> u64 { + value * 2 + } + + #[cgp_computer] + pub fn add_one(value: u64) -> u64 { + value + 1 + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: PipeHandlers, + } + } - use cgp::extra::handler::{Computer, ComputerComponent, PipeHandlers}; + #[test] + fn the_list_runs_left_to_right() { + assert_eq!(App.compute(PhantomData::<()>, 5), 22); // ((5 * 2) + 1) * 2 + } +} + +/// ## Examples +pub mod examples { + use cgp::extra::handler::{CanCompute, PipeHandlers}; use cgp::prelude::*; #[cgp_new_provider] @@ -36,43 +62,36 @@ pub mod a_pipeline_of_field_readers { } #[derive(HasField)] - pub struct App { + pub struct MyContext { pub foo: u64, pub bar: u64, pub baz: u64, } delegate_components! { - App { - ComputerComponent: PipeHandlers< - Product![ + MyContext { + ComputerComponent: + PipeHandlers, Add, Multiply, - ] - >, + ]>, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), u64), - } + check_components! { + MyContext { + ComputerComponent: ((), u64), } } + pub fn demo() { + let context = MyContext { foo: 2, bar: 3, baz: 4 }; + assert_eq!(context.compute(PhantomData::<()>, 5), 52); // ((5 * 2) + 3) * 4 + } + #[test] - fn the_stages_run_left_to_right() { - use cgp::extra::handler::CanCompute; - - let app = App { - foo: 2, - bar: 3, - baz: 4, - }; - // ((5 * 2) + 3) * 4 - assert_eq!(app.compute(PhantomData::<()>, 5u64), 52); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/handler/promote.rs b/example-code/tests/reference/providers/handler/promote.rs index 07cf68f4..e30eb43d 100644 --- a/example-code/tests/reference/providers/handler/promote.rs +++ b/example-code/tests/reference/providers/handler/promote.rs @@ -1,18 +1,31 @@ //! Code from `docs/reference/providers/handler/promote.md` — `Promote`. +//! +//! Pins the Examples program: a hand-written `Computer` fills a `TryComputer` slot through +//! `Promote`, and a `Handler` slot through the two-step `PromoteAsync>`, and a +//! hand-written `Producer` fills a `Computer` slot. -/// ## Usage and Examples -/// -/// `Promote` lifts a provider up the family. Here a plain `Computer` (`Double`) fills a `TryComputer` -/// slot: `Promote` wraps its infallible result in `Ok`. -pub mod lifting_a_computer_into_a_try_computer { - use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::RaiseFrom; - use cgp::extra::handler::{Promote, TryComputerComponent}; +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanCompute, CanHandle, CanTryCompute, Promote, PromoteAsync}; use cgp::prelude::*; - #[cgp_computer] - pub fn double(value: u64) -> u64 { - value * 2 + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + #[cgp_new_provider] + impl Producer for DefaultPort { + type Output = u16; + + fn produce(_context: &Context, _code: PhantomData) -> u16 { + 8080 + } } pub struct App; @@ -20,24 +33,29 @@ pub mod lifting_a_computer_into_a_try_computer { delegate_components! { App { ErrorTypeProviderComponent: UseType, - ErrorRaiserComponent: RaiseFrom, + ComputerComponent: Promote, TryComputerComponent: Promote, + HandlerComponent: PromoteAsync>, } } - mod check_app { - use super::*; - check_components! { - App { - TryComputerComponent: ((), u64), - } + check_components! { + App { + ComputerComponent: ((), ()), + [TryComputerComponent, HandlerComponent]: ((), u64), } } - #[test] - fn the_infallible_result_is_wrapped_in_ok() { - use cgp::extra::handler::CanTryCompute; + pub async fn demo() { + let code = PhantomData::<()>; - assert_eq!(App.try_compute(PhantomData::<()>, 5u64), Ok(10)); + assert_eq!(App.compute(code, ()), 8080); + assert_eq!(App.try_compute(code, 21), Ok(42)); + assert_eq!(App.handle(code, 21).await, Ok(42)); + } + + #[test] + fn test_demo() { + futures::executor::block_on(demo()); } } diff --git a/example-code/tests/reference/providers/handler/promote_async.rs b/example-code/tests/reference/providers/handler/promote_async.rs index 101621b2..4124c1d2 100644 --- a/example-code/tests/reference/providers/handler/promote_async.rs +++ b/example-code/tests/reference/providers/handler/promote_async.rs @@ -1,40 +1,69 @@ //! Code from `docs/reference/providers/handler/promote_async.md` — `PromoteAsync`. +//! +//! Pins the Examples program: a hand-written `Computer` serves an `AsyncComputer` slot, and a +//! hand-written `TryComputer` serves a `Handler` slot. -/// ## Usage and Examples -/// -/// `PromoteAsync` lifts a synchronous provider into an asynchronous one. Here a plain `Computer` -/// (`Double`) fills an `AsyncComputer` slot; the returned future is ready immediately. -pub mod lifting_a_computer_into_an_async_computer { - use cgp::extra::handler::{AsyncComputerComponent, PromoteAsync}; +/// ## Examples +pub mod examples { + use core::num::ParseIntError; + + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::DebugError; + use cgp::extra::error::RaiseFrom; + use cgp::extra::handler::{CanComputeAsync, CanHandle, PromoteAsync}; use cgp::prelude::*; - #[cgp_computer] - pub fn double(value: u64) -> u64 { - value * 2 + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + #[cgp_impl(new ParseU64)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl TryComputer { + type Output = u64; + + fn try_compute(&self, _code: PhantomData, input: String) -> Result { + input.parse().map_err(Self::raise_error) + } } pub struct App; delegate_components! { App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + AsyncComputerComponent: PromoteAsync, + HandlerComponent: PromoteAsync, } } - mod check_app { - use super::*; - check_components! { - App { - AsyncComputerComponent: ((), u64), - } + check_components! { + App { + AsyncComputerComponent: ((), u64), + HandlerComponent: ((), String), } } - #[test] - fn the_synchronous_provider_runs_in_an_async_method() { - use cgp::extra::handler::CanComputeAsync; - use futures::executor::block_on; + pub async fn demo() { + let code = PhantomData::<()>; - assert_eq!(block_on(App.compute_async(PhantomData::<()>, 5u64)), 10); + assert_eq!(App.compute_async(code, 21).await, 42); + assert_eq!(App.handle(code, "12".to_owned()).await, Ok(12)); + } + + #[test] + fn test_demo() { + futures::executor::block_on(demo()); } } diff --git a/example-code/tests/reference/providers/handler/promote_async_computer.rs b/example-code/tests/reference/providers/handler/promote_async_computer.rs index 69802ecc..7ec34a1c 100644 --- a/example-code/tests/reference/providers/handler/promote_async_computer.rs +++ b/example-code/tests/reference/providers/handler/promote_async_computer.rs @@ -1,18 +1,16 @@ //! Code from `docs/reference/providers/handler/promote_async_computer.md` — `PromoteAsyncComputer`. - -/// ## Usage and Examples -/// -/// `PromoteAsyncComputer` fills the family from an infallible async base. It answers -/// `HandlerComponent` (and the async-ref members) but not `AsyncComputerComponent`, so the base is -/// wired to `AsyncComputerComponent` directly and the bundle fills in the rest. -pub mod filling_the_family_from_an_async_computer { - use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::RaiseFrom; - use cgp::extra::handler::{AsyncComputerComponent, HandlerComponent, PromoteAsyncComputer}; +//! +//! Pins the Examples program: an async `#[cgp_computer]` function is the `AsyncComputer` base, and +//! the bundle answers `HandlerComponent` from it, one step away, as it would for a hand-written base. + +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanComputeAsync, CanHandle}; use cgp::prelude::*; #[cgp_computer] - pub fn double(value: u64) -> u64 { + pub async fn double_later(value: u64) -> u64 { value * 2 } @@ -21,32 +19,26 @@ pub mod filling_the_family_from_an_async_computer { delegate_components! { App { ErrorTypeProviderComponent: UseType, - ErrorRaiserComponent: RaiseFrom, - - AsyncComputerComponent: Double, - HandlerComponent: PromoteAsyncComputer, + AsyncComputerComponent: DoubleLater, + HandlerComponent: PromoteAsyncComputer, } } - mod check_app { - use super::*; - check_components! { - App { - AsyncComputerComponent: ((), u64), - HandlerComponent: ((), u64), - } + check_components! { + App { + [AsyncComputerComponent, HandlerComponent]: ((), u64), } } - #[test] - fn the_async_base_answers_the_family() { - use cgp::extra::handler::{CanComputeAsync, CanHandle}; - use futures::executor::block_on; - - let app = App; + pub async fn demo() { let code = PhantomData::<()>; - assert_eq!(block_on(app.compute_async(code, 5u64)), 10); - assert_eq!(block_on(app.handle(code, 5u64)), Ok(10)); + assert_eq!(App.compute_async(code, 5).await, 10); + assert_eq!(App.handle(code, 5).await, Ok(10)); + } + + #[test] + fn test_demo() { + futures::executor::block_on(demo()); } } diff --git a/example-code/tests/reference/providers/handler/promote_computer.rs b/example-code/tests/reference/providers/handler/promote_computer.rs index 61f560a4..a8e3ace2 100644 --- a/example-code/tests/reference/providers/handler/promote_computer.rs +++ b/example-code/tests/reference/providers/handler/promote_computer.rs @@ -1,17 +1,14 @@ //! Code from `docs/reference/providers/handler/promote_computer.md` — `PromoteComputer`. +//! +//! Pins the Examples program: a `#[cgp_computer]` provider, wired to `PromoteComputer` by the +//! macro, answers the whole family when the context wires the bundle for it. The hand-written base +//! whose `Handler` entry fails is the C2 fixture +//! `tests/compile_fail/reference/components/handler_common_mistakes_bundle_on_a_plain_computer.rs`. -/// ## Usage and Examples -/// -/// `PromoteComputer` fills in every family member *other than* `ComputerComponent`. The base provider -/// answers `ComputerComponent`, and the bundle answers the rest, so one `Computer` implementation -/// serves the whole family. -pub mod filling_the_family_from_a_computer { - use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::RaiseFrom; - use cgp::extra::handler::{ - AsyncComputerComponent, ComputerComponent, HandlerComponent, PromoteComputer, - TryComputerComponent, - }; +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanCompute, CanComputeAsync, CanHandle, CanTryCompute}; use cgp::prelude::*; #[cgp_computer] @@ -24,9 +21,6 @@ pub mod filling_the_family_from_a_computer { delegate_components! { App { ErrorTypeProviderComponent: UseType, - ErrorRaiserComponent: RaiseFrom, - - // The base answers `ComputerComponent`; the bundle fills in the rest of the family. ComputerComponent: Double, [ TryComputerComponent, @@ -36,29 +30,61 @@ pub mod filling_the_family_from_a_computer { } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), u64), - TryComputerComponent: ((), u64), - AsyncComputerComponent: ((), u64), - HandlerComponent: ((), u64), - } + check_components! { + App { + [ + ComputerComponent, + TryComputerComponent, + AsyncComputerComponent, + HandlerComponent, + ]: ((), u64), } } + pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute(code, 5), 10); + assert_eq!(App.try_compute(code, 5), Ok(10)); + assert_eq!(App.compute_async(code, 5).await, 10); + assert_eq!(App.handle(code, 5).await, Ok(10)); + } + #[test] - fn one_computer_answers_the_family() { - use cgp::extra::handler::{CanCompute, CanComputeAsync, CanHandle, CanTryCompute}; - use futures::executor::block_on; + fn test_demo() { + futures::executor::block_on(demo()); + } +} - let app = App; - let code = PhantomData::<()>; +/// ## Common Mistakes +/// +/// The one-step entries work for a hand-written base: `TryComputerComponent` goes to `Promote` and +/// `AsyncComputerComponent` to `PromoteAsync`, each of which needs only the `Computer`. +pub mod common_mistakes { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for Double { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + pub struct App; - assert_eq!(app.compute(code, 5u64), 10); - assert_eq!(app.try_compute(code, 5u64), Ok(10)); - assert_eq!(block_on(app.compute_async(code, 5u64)), 10); - assert_eq!(block_on(app.handle(code, 5u64)), Ok(10)); + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + [TryComputerComponent, AsyncComputerComponent]: PromoteComputer, + } + } + + check_components! { + App { + [TryComputerComponent, AsyncComputerComponent]: ((), u64), + } } } diff --git a/example-code/tests/reference/providers/handler/promote_handler.rs b/example-code/tests/reference/providers/handler/promote_handler.rs index cbab4873..206f07e0 100644 --- a/example-code/tests/reference/providers/handler/promote_handler.rs +++ b/example-code/tests/reference/providers/handler/promote_handler.rs @@ -1,19 +1,18 @@ //! Code from `docs/reference/providers/handler/promote_handler.md` — `PromoteHandler`. - -/// ## Usage and Examples -/// -/// `PromoteHandler` fills the family from the most general base, a `Handler`. It answers -/// `HandlerComponent` and `HandlerRefComponent`, so those are routed to it; a base computer returning -/// a `Result` supplies the fallible async behavior. -pub mod filling_the_family_from_a_handler { - use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::RaiseFrom; - use cgp::extra::handler::{HandlerComponent, PromoteHandler}; +//! +//! Pins the Examples program: an async `#[cgp_computer]` function returning `Result` is the base, an +//! `AsyncComputer` whose output is a `Result`, and the bundle answers `HandlerComponent` from it +//! through `TryPromote`. + +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::CanHandle; use cgp::prelude::*; #[cgp_computer] - pub fn checked_add(a: u64, b: u64) -> Result { - a.checked_add(b).ok_or_else(|| "overflow".to_owned()) + pub async fn checked_double(value: u64) -> Result { + value.checked_mul(2).ok_or_else(|| "overflow".to_owned()) } pub struct App; @@ -21,33 +20,25 @@ pub mod filling_the_family_from_a_handler { delegate_components! { App { ErrorTypeProviderComponent: UseType, - ErrorRaiserComponent: RaiseFrom, - - HandlerComponent: PromoteHandler, + HandlerComponent: PromoteHandler, } } - mod check_app { - use super::*; - check_components! { - App { - HandlerComponent: ((), (u64, u64)), - } + check_components! { + App { + HandlerComponent: ((), u64), } } - #[test] - fn the_handler_base_answers_the_family() { - use cgp::extra::handler::CanHandle; - use futures::executor::block_on; - - let app = App; + pub async fn demo() { let code = PhantomData::<()>; - assert_eq!(block_on(app.handle(code, (1u64, 2u64))), Ok(3)); - assert_eq!( - block_on(app.handle(code, (u64::MAX, 1u64))), - Err("overflow".to_owned()) - ); + assert_eq!(App.handle(code, 21).await, Ok(42)); + assert_eq!(App.handle(code, u64::MAX).await, Err("overflow".to_owned())); + } + + #[test] + fn test_demo() { + futures::executor::block_on(demo()); } } diff --git a/example-code/tests/reference/providers/handler/promote_producer.rs b/example-code/tests/reference/providers/handler/promote_producer.rs index c9278449..e9074562 100644 --- a/example-code/tests/reference/providers/handler/promote_producer.rs +++ b/example-code/tests/reference/providers/handler/promote_producer.rs @@ -1,49 +1,48 @@ //! Code from `docs/reference/providers/handler/promote_producer.md` — `PromoteProducer`. - -/// ## Usage and Examples -/// -/// `PromoteProducer` fills in the input-taking family members from an input-free `Producer`. The base -/// answers `ProducerComponent`, and the bundle answers `ComputerComponent` (and the rest) by -/// discarding the input and calling the producer. -pub mod filling_the_family_from_a_producer { - use cgp::extra::handler::{ComputerComponent, ProducerComponent, PromoteProducer}; +//! +//! Pins the Examples program: the `ComputerComponent` entry serves any producer, and a +//! `#[cgp_producer]` provider answers the rest of the family too. The hand-written producer behind a +//! fallible entry is the C2 fixture +//! `tests/compile_fail/reference/components/producer_common_mistakes_bundle_on_a_plain_producer.rs`. + +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanCompute, CanProduce, CanTryCompute}; use cgp::prelude::*; #[cgp_producer] - pub fn make_default() -> u64 { - 42 + pub fn default_port() -> u16 { + 8080 } pub struct App; delegate_components! { App { - // The base answers `ProducerComponent`; the bundle answers `ComputerComponent` by - // discarding the input and calling the producer. - ProducerComponent: MakeDefault, - ComputerComponent: PromoteProducer, + ErrorTypeProviderComponent: UseType, + ProducerComponent: DefaultPort, + [ComputerComponent, TryComputerComponent]: PromoteProducer, } } - mod check_app { - use super::*; - check_components! { - App { - ProducerComponent: (), - ComputerComponent: ((), u64), - } + check_components! { + App { + ProducerComponent: (), + [ComputerComponent, TryComputerComponent]: ((), u64), } } - #[test] - fn the_produced_value_flows_out_of_every_shape() { - use cgp::extra::handler::{CanCompute, CanProduce}; - - let app = App; + pub fn demo() { let code = PhantomData::<()>; - assert_eq!(app.produce(code), 42); - // The computer shape discards its input and produces the same value. - assert_eq!(app.compute(code, 999u64), 42); + assert_eq!(App.produce(code), 8080); + assert_eq!(App.compute(code, 999_u64), 8080); + assert_eq!(App.try_compute(code, 999_u64), Ok(8080)); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/handler/promote_ref.rs b/example-code/tests/reference/providers/handler/promote_ref.rs index 12fa6c38..f07fdfe5 100644 --- a/example-code/tests/reference/providers/handler/promote_ref.rs +++ b/example-code/tests/reference/providers/handler/promote_ref.rs @@ -1,17 +1,14 @@ //! Code from `docs/reference/providers/handler/promote_ref.md` — `PromoteRef`. +//! +//! Pins both directions the page shows: a by-value computer over `&u64` serves `ComputerRefComponent`, +//! and a `ComputerRef` over `String` serves `ComputerComponent` for a `Box` input. -/// ## Usage and Examples -/// -/// `PromoteRef` bridges by-value and by-reference handlers. To fill a by-reference slot such as -/// `ComputerRefComponent`, the inner provider is a by-value provider whose input is a reference; the -/// bridge calls it on the borrowed input. -pub mod bridging_value_and_reference { - use core::marker::PhantomData; - - use cgp::extra::handler::{Computer, ComputerRefComponent, PromoteRef}; +/// ## Examples +pub mod examples { + use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef, PromoteRef}; use cgp::prelude::*; - /// A by-value computer whose input is a reference: doubles the value behind it. + /// A by-value computer whose input is a reference. #[cgp_new_provider] impl Computer for DoubleRef { type Output = u64; @@ -21,28 +18,41 @@ pub mod bridging_value_and_reference { } } + /// A by-reference computer over a `String`. + #[cgp_new_provider] + impl ComputerRef for StringLength { + type Output = usize; + + fn compute_ref(_context: &Context, _code: PhantomData, input: &String) -> usize { + input.len() + } + } + pub struct App; delegate_components! { App { ComputerRefComponent: PromoteRef, + ComputerComponent: PromoteRef, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerRefComponent: ((), u64), - } + check_components! { + App { + ComputerRefComponent: ((), u64), + ComputerComponent: ((), Box), } } - #[test] - fn the_by_reference_slot_is_served_from_the_inner_provider() { - use cgp::extra::handler::CanComputeRef; + pub fn demo() { + let code = PhantomData::<()>; - let app = App; - assert_eq!(app.compute_ref(PhantomData::<()>, &5u64), 10); + assert_eq!(App.compute_ref(code, &21), 42); + assert_eq!(App.compute(code, Box::new("hello".to_owned())), 5); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/handler/promote_try_computer.rs b/example-code/tests/reference/providers/handler/promote_try_computer.rs index 799dcf54..2422d517 100644 --- a/example-code/tests/reference/providers/handler/promote_try_computer.rs +++ b/example-code/tests/reference/providers/handler/promote_try_computer.rs @@ -1,19 +1,18 @@ //! Code from `docs/reference/providers/handler/promote_try_computer.md` — `PromoteTryComputer`. +//! +//! Pins the Examples program, a `#[cgp_computer]` function returning `Result` whose provider answers +//! the family through the bundle, and the one-step entry a hand-written base can use. The +//! hand-written base behind the `Handler` entry is a trybuild fixture. -/// ## Usage and Examples -/// -/// `PromoteTryComputer` fills the family from a synchronous fallible base. It answers -/// `TryComputerComponent` and the async members, so those are routed to it; a base computer returning -/// a `Result` supplies the fallible behavior. -pub mod filling_the_family_from_a_try_computer { - use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::RaiseFrom; - use cgp::extra::handler::{HandlerComponent, PromoteTryComputer, TryComputerComponent}; +/// ## Examples +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{CanHandle, CanTryCompute}; use cgp::prelude::*; #[cgp_computer] - pub fn checked_add(a: u64, b: u64) -> Result { - a.checked_add(b).ok_or_else(|| "overflow".to_owned()) + pub fn checked_double(value: u64) -> Result { + value.checked_mul(2).ok_or_else(|| "overflow".to_owned()) } pub struct App; @@ -21,35 +20,65 @@ pub mod filling_the_family_from_a_try_computer { delegate_components! { App { ErrorTypeProviderComponent: UseType, - ErrorRaiserComponent: RaiseFrom, - - [TryComputerComponent, HandlerComponent]: PromoteTryComputer, + [TryComputerComponent, HandlerComponent]: PromoteTryComputer, } } - mod check_app { - use super::*; - check_components! { - App { - TryComputerComponent: ((), (u64, u64)), - HandlerComponent: ((), (u64, u64)), - } + check_components! { + App { + [TryComputerComponent, HandlerComponent]: ((), u64), } } + pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.try_compute(code, 21), Ok(42)); + assert_eq!(App.try_compute(code, u64::MAX), Err("overflow".to_owned())); + assert_eq!(App.handle(code, 21).await, Ok(42)); + } + #[test] - fn the_fallible_base_answers_the_family() { - use cgp::extra::handler::{CanHandle, CanTryCompute}; - use futures::executor::block_on; + fn test_demo() { + futures::executor::block_on(demo()); + } +} - let app = App; - let code = PhantomData::<()>; +/// ## Common Mistakes +/// +/// The `TryComputerComponent` entry is `TryPromote

`, one step from the base, so it serves a +/// hand-written `Computer` returning `Result`. +pub mod common_mistakes { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{PromoteAsync, TryPromote}; + use cgp::prelude::*; + + #[cgp_new_provider] + impl Computer for CheckedDouble + where + Context: HasErrorType, + { + type Output = Result; - assert_eq!(app.try_compute(code, (1u64, 2u64)), Ok(3)); - assert_eq!( - app.try_compute(code, (u64::MAX, 1u64)), - Err("overflow".to_owned()) - ); - assert_eq!(block_on(app.handle(code, (1u64, 2u64))), Ok(3)); + fn compute(_context: &Context, _code: PhantomData, input: u64) -> Result { + input.checked_mul(2).ok_or_else(|| "overflow".to_owned()) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + TryComputerComponent: PromoteTryComputer, + // The fix the page gives for the handler slot. + HandlerComponent: PromoteAsync>, + } + } + + check_components! { + App { + [TryComputerComponent, HandlerComponent]: ((), u64), + } } } diff --git a/example-code/tests/reference/providers/handler/return_input.rs b/example-code/tests/reference/providers/handler/return_input.rs index 9067a7ea..7a38a3e2 100644 --- a/example-code/tests/reference/providers/handler/return_input.rs +++ b/example-code/tests/reference/providers/handler/return_input.rs @@ -1,11 +1,30 @@ //! Code from `docs/reference/providers/handler/return_input.md` — `ReturnInput`. +//! +//! Pins the Usage wiring and the Examples program, in which `ReturnInput` is the middle stage of a +//! pipeline and changes nothing. -/// ## Usage and Examples -/// -/// `ReturnInput` is the identity handler: it returns its input unchanged. Here it is the middle stage -/// of a pipeline, so the pipeline behaves as though the stage were not there. -pub mod the_identity_stage { - use cgp::extra::handler::{ComputerComponent, PipeHandlers, ReturnInput}; +/// ## Usage +pub mod usage { + use cgp::extra::handler::{CanCompute, ReturnInput}; + use cgp::prelude::*; + + pub struct App; + + delegate_components! { + App { + ComputerComponent: ReturnInput, + } + } + + #[test] + fn any_input_comes_back() { + assert_eq!(App.compute(PhantomData::<()>, "hello"), "hello"); + } +} + +/// ## Examples +pub mod examples { + use cgp::extra::handler::{CanCompute, PipeHandlers, ReturnInput}; use cgp::prelude::*; #[cgp_computer] @@ -21,20 +40,18 @@ pub mod the_identity_stage { } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), u64), - } + check_components! { + App { + ComputerComponent: ((), u64), } } - #[test] - fn the_input_passes_straight_through() { - use cgp::extra::handler::CanCompute; + pub fn demo() { + assert_eq!(App.compute(PhantomData::<()>, 5), 7); // 5 -> 6 -> 6 -> 7 + } - // AddOne, then ReturnInput (a no-op), then AddOne: 5 -> 6 -> 6 -> 7. - assert_eq!(App.compute(PhantomData::<()>, 5u64), 7); + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/handler/try_promote.rs b/example-code/tests/reference/providers/handler/try_promote.rs index 8beab3c7..a0166bc5 100644 --- a/example-code/tests/reference/providers/handler/try_promote.rs +++ b/example-code/tests/reference/providers/handler/try_promote.rs @@ -1,52 +1,77 @@ //! Code from `docs/reference/providers/handler/try_promote.md` — `TryPromote`. +//! +//! Pins both directions the page shows: a `Computer` returning a `Result` serves a `TryComputer` slot, +//! and a `TryComputer` serves a `Computer` slot whose output is the `Result`. + +/// ## Examples +pub mod examples { + use core::num::ParseIntError; -/// ## Usage and Examples -/// -/// `TryPromote` turns a `Computer` that *returns* a `Result` into a genuine `TryComputer`, unwrapping -/// the `Result` into the fallible interface. The context's error type is what the `Result`'s error -/// arm becomes. -pub mod unwrapping_a_result_output { use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::RaiseFrom; - use cgp::extra::handler::{TryComputerComponent, TryPromote}; + use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::extra::handler::{CanCompute, CanTryCompute, TryPromote}; use cgp::prelude::*; - /// A computer whose output is itself a `Result`. - #[cgp_computer] - pub fn checked_add(a: u64, b: u64) -> Result { - a.checked_add(b).ok_or_else(|| "overflow".to_owned()) + /// A computer whose output is a `Result` in the context's error type. + #[cgp_new_provider] + impl Computer for CheckedDouble + where + Context: HasErrorType, + { + type Output = Result; + + fn compute(_context: &Context, _code: PhantomData, input: u64) -> Result { + input.checked_mul(2).ok_or_else(|| "overflow".to_owned()) + } + } + + /// A genuinely fallible computer. + #[cgp_impl(new ParseU64)] + #[uses(CanRaiseError)] + #[use_type(HasErrorType.Error)] + impl TryComputer { + type Output = u64; + + fn try_compute(&self, _code: PhantomData, input: String) -> Result { + input.parse().map_err(Self::raise_error) + } } pub struct App; delegate_components! { App { + open ErrorRaiserComponent; + ErrorTypeProviderComponent: UseType, - ErrorRaiserComponent: RaiseFrom, - TryComputerComponent: TryPromote, + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseIntError: DebugError, + + TryComputerComponent: TryPromote, + ComputerComponent: TryPromote, } } - mod check_app { - use super::*; - check_components! { - App { - TryComputerComponent: ((), (u64, u64)), - } + check_components! { + App { + TryComputerComponent: ((), u64), + ComputerComponent: ((), String), } } - #[test] - fn the_result_becomes_the_fallible_interface() { - use cgp::extra::handler::CanTryCompute; - - let app = App; + pub fn demo() { let code = PhantomData::<()>; - assert_eq!(app.try_compute(code, (1u64, 2u64)), Ok(3)); - assert_eq!( - app.try_compute(code, (u64::MAX, 1u64)), - Err("overflow".to_owned()) - ); + // The `Result` output becomes the fallible interface. + assert_eq!(App.try_compute(code, 21), Ok(42)); + assert_eq!(App.try_compute(code, u64::MAX), Err("overflow".to_owned())); + + // The fallible computer surfaces its `Result` as a plain value. + assert_eq!(App.compute(code, "12".to_owned()), Ok(12)); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/handler/use_input_delegate.rs b/example-code/tests/reference/providers/handler/use_input_delegate.rs index cc83d900..2b6a6af8 100644 --- a/example-code/tests/reference/providers/handler/use_input_delegate.rs +++ b/example-code/tests/reference/providers/handler/use_input_delegate.rs @@ -1,12 +1,11 @@ //! Code from `docs/reference/providers/handler/use_input_delegate.md` — `UseInputDelegate`. +//! +//! Pins the Usage and Examples programs, the legacy table and its `open` equivalent, and the +//! component whose generated `UseInputDelegate` impl Under the hood lists, for `cargo cgp expand`. -/// ## Usage and Examples -/// -/// `UseInputDelegate` chooses the handler by the type of the input. Here a `Circle` input routes to -/// `CircleArea` and a `Rectangle` input to `RectangleArea`, through one wiring entry keyed on the -/// input type. -pub mod dispatching_on_the_input_type { - use cgp::extra::handler::{ComputerComponent, UseInputDelegate}; +/// ## Examples +pub mod examples { + use cgp::extra::handler::{CanCompute, UseInputDelegate}; use cgp::prelude::*; pub struct Circle { @@ -39,17 +38,12 @@ pub mod dispatching_on_the_input_type { } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: [((), Circle), ((), Rectangle)], - } + check_components! { + App { + ComputerComponent: [((), Circle), ((), Rectangle)], } } - /// The same dispatch in the current form, with `open` keys whose generic first segment matches - /// any code. The page names the providers `ComputeCircleArea` and `ComputeRectangleArea`. pub struct OpenApp; delegate_components! { @@ -61,34 +55,39 @@ pub mod dispatching_on_the_input_type { } } - mod check_open_app { - use super::*; - check_components! { - OpenApp { - ComputerComponent: [((), Circle), ((), Rectangle)], - } + check_components! { + OpenApp { + ComputerComponent: [((), Circle), ((), Rectangle)], } } + pub fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute(code, Rectangle { width: 3.0, height: 4.0 }), 12.0); + assert_eq!(OpenApp.compute(code, Rectangle { width: 3.0, height: 4.0 }), 12.0); + assert!((App.compute(code, Circle { radius: 1.0 }) - core::f64::consts::PI).abs() < 1e-9); + } + #[test] - fn each_input_reaches_its_own_handler() { - use cgp::extra::handler::CanCompute; + fn test_demo() { + demo(); + } +} - let app = App; - let code = PhantomData::<()>; +/// ## Under the hood +/// +/// A component declared with the same `#[derive_delegate(UseInputDelegate)]` directive as the +/// handler components, whose generated impl the page lists. +pub mod under_the_hood { + use cgp::extra::handler::UseInputDelegate; + use cgp::prelude::*; + + #[cgp_component(Measurer)] + #[derive_delegate(UseInputDelegate)] + pub trait CanMeasure { + type Output; - assert_eq!( - app.compute( - code, - Rectangle { - width: 3.0, - height: 4.0 - } - ), - 12.0, - ); - - let area = app.compute(code, Circle { radius: 1.0 }); - assert!((area - core::f64::consts::PI).abs() < 1e-9); + fn measure(&self, _code: PhantomData, input: Input) -> Self::Output; } } From c1558c90233635316622acb6e6a2bcc0f1ec9034 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 03:56:30 +0000 Subject: [PATCH 131/516] Correct which promotion-bundle entries serve a hand-written base PromoteTryComputer's AsyncComputer entry is one step from the base, so it serves a hand-written Computer returning Result; the page claimed only the TryComputer entry did. Of the Ref entries, ComputerRef and AsyncComputerRef take one step from a base over a borrowed input, while HandlerRef on the async bundles steps from the sibling Handler and fails for such a base. The bundle mirrors now pin each one-step Ref entry. Also say what PipeMonadic stops on, note the error type a Handler pipeline needs, and merge an import. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../providers/handler/compose_handlers.md | 5 +- .../providers/handler/pipe_handlers.md | 7 +-- .../providers/handler/promote_async.md | 3 +- .../handler/promote_async_computer.md | 6 ++- .../providers/handler/promote_computer.md | 13 +++-- .../providers/handler/promote_handler.md | 5 +- .../providers/handler/promote_ref.md | 9 ++-- .../providers/handler/promote_try_computer.md | 11 +++-- .../providers/handler/promote_async.rs | 3 +- .../handler/promote_async_computer.rs | 42 +++++++++++++++++ .../providers/handler/promote_computer.rs | 37 +++++++++++++++ .../providers/handler/promote_handler.rs | 47 +++++++++++++++++++ .../providers/handler/promote_try_computer.rs | 24 +++++++--- 13 files changed, 179 insertions(+), 33 deletions(-) diff --git a/docs/reference/providers/handler/compose_handlers.md b/docs/reference/providers/handler/compose_handlers.md index 84eb33d6..da6f322e 100644 --- a/docs/reference/providers/handler/compose_handlers.md +++ b/docs/reference/providers/handler/compose_handlers.md @@ -84,8 +84,9 @@ serves as a `TryComputer`, `AsyncComputer`, or `Handler` wherever both stages su **Reach for `ComposeHandlers` to sequence exactly two handlers.** For three or more, use [`PipeHandlers`](pipe_handlers.md), which reads better as a list and folds to the same nested -composition. For a step that should short-circuit on a `Result` branch rather than always run the -next stage, use the [monad providers](../monad/pipe_monadic.md) instead. +composition. For stages whose output carries the branch to stop on, such as an `Err` value or the +first success, use [`PipeMonadic`](../monad/pipe_monadic.md), which runs the next stage only on the +continue branch. ## Under the hood diff --git a/docs/reference/providers/handler/pipe_handlers.md b/docs/reference/providers/handler/pipe_handlers.md index b8ad1bd9..cc3679f8 100644 --- a/docs/reference/providers/handler/pipe_handlers.md +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -109,7 +109,7 @@ The list folds to `ComposeHandlers, ComposeHandlers, Mult is a [value context](/docs/reference/glossary#value-context): each stage reads one of its fields. Stages of mismatched shapes can be reconciled inline, as in `PromoteAsync>>`, which lifts a plain `Computer` stage to the async -`Handler` shape a `Handler` pipeline asks for. +`Handler` shape a `Handler` pipeline asks for; the context then also needs an error type. ## When to use it @@ -117,8 +117,9 @@ Stages of mismatched shapes can be reconciled inline, as in nesting [`ComposeHandlers`](compose_handlers.md) by hand. For exactly two, `ComposeHandlers` is the plainer choice. -For a pipeline where a step should short-circuit on a `Result` branch rather than always feed the -next stage, use [`PipeMonadic`](../monad/pipe_monadic.md), the monadic generalization; +For a pipeline whose stages should stop on a branch of their output, such as an `Err` value or the +first success, rather than feed every output to the next stage, use +[`PipeMonadic`](../monad/pipe_monadic.md), the monadic generalization; `PipeMonadic` reduces to `PipeHandlers`. ## Under the hood diff --git a/docs/reference/providers/handler/promote_async.md b/docs/reference/providers/handler/promote_async.md index b654d55d..0b9481f5 100644 --- a/docs/reference/providers/handler/promote_async.md +++ b/docs/reference/providers/handler/promote_async.md @@ -43,8 +43,7 @@ A context serves both async members from hand-written synchronous providers: use core::num::ParseIntError; use cgp::prelude::*; use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; -use cgp::extra::error::DebugError; -use cgp::extra::error::RaiseFrom; +use cgp::extra::error::{DebugError, RaiseFrom}; use cgp::extra::handler::{CanComputeAsync, CanHandle, PromoteAsync}; #[cgp_new_provider] diff --git a/docs/reference/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md index f5b07b2a..54f38fb8 100644 --- a/docs/reference/providers/handler/promote_async_computer.md +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -112,8 +112,10 @@ delegate_components! { ``` It routes `HandlerComponent` to [`Promote`](promote.md), which wraps the awaited value in `Ok`, and -the two by-reference members to [`PromoteRef`](promote_ref.md), which need the base to take the -borrow as its input. +the two by-reference members to [`PromoteRef`](promote_ref.md), which passes the borrow to an owned +member as its input. `AsyncComputerRefComponent` asks that of the base, which must accept the +borrow. `HandlerRefComponent` asks it of the base's `Handler`, a sibling entry, so it serves only a +base wired to the bundle. ## Related constructs diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md index f9192e21..4749d277 100644 --- a/docs/reference/providers/handler/promote_computer.md +++ b/docs/reference/providers/handler/promote_computer.md @@ -137,17 +137,20 @@ delegate_components! { } ``` -The base `ComputerComponent` is the inner provider itself; the table fills in the other seven. Two +The base `ComputerComponent` is the inner provider itself; the table fills in the other seven. Four of the entries take their step from a sibling rather than from the base: `HandlerComponent` is -`PromoteAsync`, whose `Handler` impl needs `Provider` to be a `TryComputer`, and each -`…Ref` entry needs `Provider` to answer the owned member over a borrowed input. +`PromoteAsync`, whose `Handler` impl needs `Provider` to be a `TryComputer`, and the +`TryComputerRef`, `AsyncComputerRef`, and `HandlerRef` entries need `Provider` to answer the +matching owned member over a borrowed input. `ComputerRefComponent` takes its step from the base, +which must accept the borrow as its input. ## Common Mistakes **Only the one-step entries serve a hand-written `Computer`.** `TryComputerComponent` and `AsyncComputerComponent` need only the base, so `PromoteComputer` answers them for any -`Computer`. `HandlerComponent` looks for a `TryComputer` on `Double` itself, which a hand-written -provider not wired to the bundle lacks, so the check fails: +`Computer`, and `ComputerRefComponent` for any `Computer` whose input is a borrow. +`HandlerComponent` looks for a `TryComputer` on `Double` itself, which a hand-written provider not +wired to the bundle lacks, so the check fails: ```text error[E0277]: the trait bound `Double: DelegateComponent` is not satisfied diff --git a/docs/reference/providers/handler/promote_handler.md b/docs/reference/providers/handler/promote_handler.md index 269f2a2c..1bf1955e 100644 --- a/docs/reference/providers/handler/promote_handler.md +++ b/docs/reference/providers/handler/promote_handler.md @@ -44,8 +44,9 @@ delegate_components! { } ``` -It also answers `AsyncComputerRefComponent` and `HandlerRefComponent`, but those need a base that -takes its input by reference; a base over an owned `u64` answers only `HandlerComponent`. +It also answers `AsyncComputerRefComponent`, for a base whose input is a borrow, and +`HandlerRefComponent`, which needs that base wired to the bundle as `#[cgp_computer]` wires it. A +base over an owned `u64` answers only `HandlerComponent`. ## Examples diff --git a/docs/reference/providers/handler/promote_ref.md b/docs/reference/providers/handler/promote_ref.md index 5dccde73..7303d621 100644 --- a/docs/reference/providers/handler/promote_ref.md +++ b/docs/reference/providers/handler/promote_ref.md @@ -14,10 +14,11 @@ Bridge between by-value handlers and by-reference handlers, in both directions. `PromoteRef` lets a provider written for one input mode serve a slot that uses the other, without manual dereference code, on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. It is the most thoroughly implemented promotion: it covers all four -handler families, `Computer`, `TryComputer`, `AsyncComputer`, and `Handler`, in both directions, and -the two directions ask different things of the inner provider. Every promotion bundle routes its -`…Ref` slots through it, and it is written by hand when a context wires one slot at a time. Like -every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. +input-taking members of the family, `Computer`, `TryComputer`, `AsyncComputer`, and `Handler`, in +both directions, and the two directions ask different things of the inner provider. Every promotion +bundle routes its `…Ref` slots through it, and it is written by hand when a context wires one slot +at a time. Like every CGP provider, it carries no runtime value; the inner provider rides in +`PhantomData`. ## Usage diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md index 64c50450..6ff3af95 100644 --- a/docs/reference/providers/handler/promote_try_computer.md +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -16,7 +16,7 @@ Fill in the handler family from a `Computer` whose output is a `Result`. **You are not expected to name `PromoteTryComputer` directly.** [`#[cgp_computer]`](../../macros/cgp_computer.md) wires the provider it generates for a function returning `Result` to `PromoteTryComputer`. A context names the bundle only to route its own -components through such a provider, or through the one entry that serves any base, as +components through such a provider, or through the entries that serve any base, as [Common Mistakes](#common-mistakes) sets out. This page explains what the bundle emits. ::: @@ -127,10 +127,11 @@ members derive from the computer form. ## Common Mistakes -**Only the `TryComputerComponent` entry serves a hand-written base.** `TryPromote

` needs only a -`Computer` returning `Result`, but `HandlerComponent` goes through `PromoteComputer

` to -`PromoteAsync

`, which looks for a `TryComputer` on the base itself. A hand-written base not wired -to the bundle fails at the check: +**The `HandlerComponent` entry does not serve a hand-written base.** `TryComputerComponent` and +`AsyncComputerComponent` take one step from the base, through `TryPromote

` and `PromoteAsync

`, +so they serve any `Computer` returning `Result`; the async entry keeps the `Result` as its output. +`HandlerComponent` goes through `PromoteComputer

` to `PromoteAsync

`, which looks for a +`TryComputer` on the base itself. A hand-written base not wired to the bundle fails at the check: ```text error[E0277]: the trait bound `CheckedDouble: DelegateComponent` is not satisfied diff --git a/example-code/tests/reference/providers/handler/promote_async.rs b/example-code/tests/reference/providers/handler/promote_async.rs index 4124c1d2..f1625f73 100644 --- a/example-code/tests/reference/providers/handler/promote_async.rs +++ b/example-code/tests/reference/providers/handler/promote_async.rs @@ -8,8 +8,7 @@ pub mod examples { use core::num::ParseIntError; use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; - use cgp::extra::error::DebugError; - use cgp::extra::error::RaiseFrom; + use cgp::extra::error::{DebugError, RaiseFrom}; use cgp::extra::handler::{CanComputeAsync, CanHandle, PromoteAsync}; use cgp::prelude::*; diff --git a/example-code/tests/reference/providers/handler/promote_async_computer.rs b/example-code/tests/reference/providers/handler/promote_async_computer.rs index 7ec34a1c..567c3fbe 100644 --- a/example-code/tests/reference/providers/handler/promote_async_computer.rs +++ b/example-code/tests/reference/providers/handler/promote_async_computer.rs @@ -42,3 +42,45 @@ pub mod examples { futures::executor::block_on(demo()); } } + +/// ## Under the hood +/// +/// `AsyncComputerRefComponent` is `PromoteRef

`, one step from the base, so a hand-written +/// `AsyncComputer` whose input is a borrow answers it. +pub mod under_the_hood { + use cgp::extra::handler::CanComputeAsyncRef; + use cgp::prelude::*; + + #[cgp_new_provider] + impl<'a, Context, Code> AsyncComputer for DoubleRefLater { + type Output = u64; + + async fn compute_async( + _context: &Context, + _code: PhantomData, + input: &'a u64, + ) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + AsyncComputerRefComponent: PromoteAsyncComputer, + } + } + + check_components! { + App { + AsyncComputerRefComponent: ((), u64), + } + } + + #[test] + fn test_compute_async_ref() { + let output = futures::executor::block_on(App.compute_async_ref(PhantomData::<()>, &21)); + assert_eq!(output, 42); + } +} diff --git a/example-code/tests/reference/providers/handler/promote_computer.rs b/example-code/tests/reference/providers/handler/promote_computer.rs index a8e3ace2..26f04a81 100644 --- a/example-code/tests/reference/providers/handler/promote_computer.rs +++ b/example-code/tests/reference/providers/handler/promote_computer.rs @@ -56,6 +56,43 @@ pub mod examples { } } +/// ## Under the hood +/// +/// `ComputerRefComponent` is `PromoteRef

`, one step from the base, so a hand-written `Computer` +/// whose input is a borrow answers it. +pub mod under_the_hood { + use cgp::extra::handler::CanComputeRef; + use cgp::prelude::*; + + #[cgp_new_provider] + impl<'a, Context, Code> Computer for DoubleRef { + type Output = u64; + + fn compute(_context: &Context, _code: PhantomData, input: &'a u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + ComputerRefComponent: PromoteComputer, + } + } + + check_components! { + App { + ComputerRefComponent: ((), u64), + } + } + + #[test] + fn test_compute_ref() { + assert_eq!(App.compute_ref(PhantomData::<()>, &21), 42); + } +} + /// ## Common Mistakes /// /// The one-step entries work for a hand-written base: `TryComputerComponent` goes to `Promote` and diff --git a/example-code/tests/reference/providers/handler/promote_handler.rs b/example-code/tests/reference/providers/handler/promote_handler.rs index 206f07e0..f00a3ca5 100644 --- a/example-code/tests/reference/providers/handler/promote_handler.rs +++ b/example-code/tests/reference/providers/handler/promote_handler.rs @@ -4,6 +4,53 @@ //! `AsyncComputer` whose output is a `Result`, and the bundle answers `HandlerComponent` from it //! through `TryPromote`. +/// ## Usage +/// +/// `AsyncComputerRefComponent` reaches `PromoteRef

` through `PromoteAsyncComputer

`, one step +/// from the base, so a hand-written `AsyncComputer` returning `Result` over a borrow answers it. +pub mod usage { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::CanComputeAsyncRef; + use cgp::prelude::*; + + #[cgp_new_provider] + impl<'a, Context, Code> AsyncComputer for CheckedDoubleRef + where + Context: HasErrorType, + { + type Output = Result; + + async fn compute_async( + _context: &Context, + _code: PhantomData, + input: &'a u64, + ) -> Result { + input.checked_mul(2).ok_or_else(|| "overflow".to_owned()) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + AsyncComputerRefComponent: PromoteHandler, + } + } + + check_components! { + App { + AsyncComputerRefComponent: ((), u64), + } + } + + #[test] + fn test_compute_async_ref() { + let output = futures::executor::block_on(App.compute_async_ref(PhantomData::<()>, &21)); + assert_eq!(output, Ok(42)); + } +} + /// ## Examples pub mod examples { use cgp::core::error::ErrorTypeProviderComponent; diff --git a/example-code/tests/reference/providers/handler/promote_try_computer.rs b/example-code/tests/reference/providers/handler/promote_try_computer.rs index 2422d517..2e0be4e3 100644 --- a/example-code/tests/reference/providers/handler/promote_try_computer.rs +++ b/example-code/tests/reference/providers/handler/promote_try_computer.rs @@ -1,7 +1,7 @@ //! Code from `docs/reference/providers/handler/promote_try_computer.md` — `PromoteTryComputer`. //! //! Pins the Examples program, a `#[cgp_computer]` function returning `Result` whose provider answers -//! the family through the bundle, and the one-step entry a hand-written base can use. The +//! the family through the bundle, and the one-step entries a hand-written base can use. The //! hand-written base behind the `Handler` entry is a trybuild fixture. /// ## Examples @@ -46,11 +46,12 @@ pub mod examples { /// ## Common Mistakes /// -/// The `TryComputerComponent` entry is `TryPromote

`, one step from the base, so it serves a -/// hand-written `Computer` returning `Result`. +/// The `TryComputerComponent` and `AsyncComputerComponent` entries are `TryPromote

` and +/// `PromoteAsync

`, one step from the base, so they serve a hand-written `Computer` returning +/// `Result`; the async one keeps the `Result` as its output. pub mod common_mistakes { use cgp::core::error::ErrorTypeProviderComponent; - use cgp::extra::handler::{PromoteAsync, TryPromote}; + use cgp::extra::handler::{CanComputeAsync, PromoteAsync, TryPromote}; use cgp::prelude::*; #[cgp_new_provider] @@ -70,7 +71,7 @@ pub mod common_mistakes { delegate_components! { App { ErrorTypeProviderComponent: UseType, - TryComputerComponent: PromoteTryComputer, + [TryComputerComponent, AsyncComputerComponent]: PromoteTryComputer, // The fix the page gives for the handler slot. HandlerComponent: PromoteAsync>, } @@ -78,7 +79,18 @@ pub mod common_mistakes { check_components! { App { - [TryComputerComponent, HandlerComponent]: ((), u64), + [TryComputerComponent, AsyncComputerComponent, HandlerComponent]: ((), u64), } } + + pub async fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute_async(code, u64::MAX).await, Err("overflow".to_owned())); + } + + #[test] + fn test_demo() { + futures::executor::block_on(demo()); + } } From 90fd30dbadb4329c3795922360f7ce0f882e47f9 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 04:23:28 +0000 Subject: [PATCH 132/516] Revise the providers/dispatch reference pages Rewrite the 12 dispatch pages with front matter, the glossary context gloss, complete Examples ported from rewritten mirrors, and Under the hood listings quoted from the cgp-dispatch source. Add Common Mistakes, each backed by a fixture: a matcher list missing a variant, a matcher in a fallible slot (with the Promote lifts that fix it), a convenience matcher on a struct, a borrowed matcher's fallible entry, a builder list leaving a field unset, and BuildAndMergeOutputs on a Ref component. Document the borrowed matcher forms, the Mut form's unresolvable Ref entries, reading a set field from a later builder step, and the MatchFirstWith convenience aliases. The front matter extends the description sweep to providers/dispatch/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../providers/dispatch/build_and_merge.md | 188 ++++++++++--- .../dispatch/build_and_merge_outputs.md | 201 ++++++++++++-- .../providers/dispatch/build_and_set_field.md | 155 +++++++++-- .../providers/dispatch/build_with_handlers.md | 202 +++++++++++--- .../providers/dispatch/downcast_and_handle.md | 177 +++++++++--- .../dispatch/extract_field_and_handle.md | 190 +++++++++---- .../providers/dispatch/handle_field_value.md | 149 ++++++++--- docs/reference/providers/dispatch/index.md | 133 ++++----- .../dispatch/match_first_with_handlers.md | 212 +++++++++++---- .../dispatch/match_with_field_handlers.md | 183 +++++++++---- .../providers/dispatch/match_with_handlers.md | 229 +++++++++++----- .../dispatch/match_with_value_handlers.md | 253 ++++++++++++++---- example-code/README.md | 2 +- ...e_outputs_common_mistakes_ref_component.rs | 50 ++++ ...tputs_common_mistakes_ref_component.stderr | 47 ++++ ..._handlers_common_mistakes_missing_field.rs | 55 ++++ ...dlers_common_mistakes_missing_field.stderr | 28 ++ ..._handlers_common_mistakes_fallible_slot.rs | 58 ++++ ...dlers_common_mistakes_fallible_slot.stderr | 38 +++ ...th_handlers_common_mistakes_missing_arm.rs | 55 ++++ ...andlers_common_mistakes_missing_arm.stderr | 28 ++ ..._common_mistakes_borrowed_fallible_slot.rs | 53 ++++ ...mon_mistakes_borrowed_fallible_slot.stderr | 74 +++++ ...e_handlers_common_mistakes_struct_input.rs | 51 ++++ ...ndlers_common_mistakes_struct_input.stderr | 88 ++++++ .../providers/dispatch/build_and_merge.rs | 118 ++++---- .../dispatch/build_and_merge_outputs.rs | 107 +++++--- .../providers/dispatch/build_and_set_field.rs | 91 ++++--- .../providers/dispatch/build_with_handlers.rs | 112 ++++---- .../providers/dispatch/downcast_and_handle.rs | 88 +++--- .../dispatch/extract_field_and_handle.rs | 84 +++--- .../providers/dispatch/handle_field_value.rs | 60 ++--- .../dispatch/match_first_with_handlers.rs | 154 ++++++++--- .../dispatch/match_with_field_handlers.rs | 117 +++++--- .../providers/dispatch/match_with_handlers.rs | 218 ++++++++++++--- .../dispatch/match_with_value_handlers.rs | 247 ++++++++++++++--- 36 files changed, 3356 insertions(+), 939 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.rs create mode 100644 example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs create mode 100644 example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.rs create mode 100644 example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs create mode 100644 example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs create mode 100644 example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr create mode 100644 example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs create mode 100644 example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr diff --git a/docs/reference/providers/dispatch/build_and_merge.md b/docs/reference/providers/dispatch/build_and_merge.md index c70c65e4..183ca43a 100644 --- a/docs/reference/providers/dispatch/build_and_merge.md +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -1,50 +1,171 @@ --- +title: 'BuildAndMerge — merge a built sub-record' +description: 'The builder step that builds a sub-record with a provider and copies every field it shares with the target into the partial record at once.' sidebar_label: 'BuildAndMerge' sidebar_position: 9 --- # `BuildAndMerge` -The builder adapter that computes a whole record's worth of fields and copies every shared field into -the builder at once. +Build a sub-record and copy every field it shares with the target into the builder at once. ## Overview -`BuildAndMerge` is the bulk counterpart of [`BuildAndSetField`](build_and_set_field.md). -Instead of setting one field, it runs `Provider` over a reference to the builder to produce another -record, then copies every shared field from that result into the builder in one step. It runs on a -**context**, the type a method runs on, and is the field-list analogue of setting a single -field. Like every CGP provider, it carries no runtime value. +`BuildAndMerge` is the builder step for a group of fields that one provider produces +together. It runs `Provider` over a reference to the builder to build another record, then copies +each of that record's fields into the builder by name, on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. A +subsystem can therefore contribute its part of a larger record as a struct of its own, with no +knowledge of the record it ends up in. `Provider` defaults to [`UseContext`](../use_context.md). +Like every CGP provider, it carries no runtime value. ## Usage -Import it from `cgp::extra::dispatch`. It takes the provider that produces the record to merge, and -appears in a builder list alongside single-field adapters: +Import it from `cgp::extra::dispatch`. It takes the provider that builds the sub-record, and is +written as a step in a [`BuildWithHandlers`](build_with_handlers.md) list, beside other merges or +single-field steps: ```rust -use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; +use cgp::extra::dispatch::{BuildAndMerge, BuildWithHandlers}; + +delegate_components! { + AppBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndMerge, + ]>, + } +} +``` + +The sub-record's fields must all be fields of the target, with the same names and types, and still +unset in the builder; the sub-record needs [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) +so its fields can be read out. It implements `Computer`, `TryComputer`, and `Handler`, running the +provider as the same member; the fallible forms need the context to have an error type and return +the provider's error. + +## Examples -type Handlers = Product![ - BuildAndMerge, - BuildAndSetField, -]; +Two subsystems each build their part of an `App`: + +```rust +use cgp::prelude::*; +use cgp::extra::dispatch::{BuildAndMerge, BuildWithHandlers}; +use cgp::extra::handler::CanCompute; + +#[derive(Debug, PartialEq, CgpData)] +pub struct App { + pub db_url: String, + pub max_connections: u32, + pub user_agent: String, +} + +#[derive(CgpData)] +pub struct DatabaseConfig { + pub db_url: String, + pub max_connections: u32, +} + +#[derive(HasField)] +pub struct AppBuilder { + pub db_path: String, + pub agent_name: String, +} + +#[cgp_impl(new BuildDatabaseConfig)] +impl Computer { + type Output = DatabaseConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] db_path: &str, + ) -> DatabaseConfig { + DatabaseConfig { + db_url: format!("sqlite://{db_path}"), + max_connections: 4, + } + } +} + +#[derive(CgpData)] +pub struct HttpConfig { + pub user_agent: String, +} + +#[cgp_impl(new BuildHttpConfig)] +impl Computer { + type Output = HttpConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] agent_name: &str, + ) -> HttpConfig { + HttpConfig { + user_agent: format!("{agent_name}/1.0"), + } + } +} + +delegate_components! { + AppBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndMerge, + ]>, + } +} + +check_components! { + AppBuilder { + ComputerComponent: ((), ()), + } +} + +pub fn demo() { + let builder = AppBuilder { + db_path: "app.db".to_owned(), + agent_name: "reader".to_owned(), + }; + + assert_eq!( + builder.compute(PhantomData::<()>, ()), + App { + db_url: "sqlite://app.db".to_owned(), + max_connections: 4, + user_agent: "reader/1.0".to_owned(), + }, + ); +} ``` +`DatabaseConfig` fills two of `App`'s fields and `HttpConfig` the third, each matched by name. +`AppBuilder` is an [environmental context](/docs/reference/glossary#environmental-context) whose +fields the two providers read as [`#[implicit]`](../../attributes/implicit.md) arguments. + ## When to use it -**Reach for `BuildAndMerge` when a builder step produces several fields at once**, a sub-record merged -into the result, inside a list passed to [`BuildWithHandlers`](build_with_handlers.md). For a single -field use [`BuildAndSetField`](build_and_set_field.md). When the list is plain field-producing providers -rather than builder adapters, [`BuildAndMergeOutputs`](build_and_merge_outputs.md) wraps each one in -`BuildAndMerge` for you. +**Reach for `BuildAndMerge` when a provider builds several of the target's fields as a struct of its +own.** For a single field, [`BuildAndSetField`](build_and_set_field.md) needs no sub-record type. +When every step is a merge, as here, +[`BuildAndMergeOutputs`](build_and_merge_outputs.md) takes the providers directly and adds the +`BuildAndMerge` to each. ## Under the hood -`BuildAndMerge` carries the provider in `PhantomData`: +`BuildAndMerge` carries the provider in `PhantomData`. Its `Computer` impl runs `Provider` +on a reference to the builder and copies the result's fields in with +[`CanBuildFrom`](../../traits/casting/can_build_from.md): ```rust pub struct BuildAndMerge(pub PhantomData); +#[cgp_provider] impl Computer for BuildAndMerge where @@ -52,27 +173,30 @@ where Builder: CanBuildFrom, { type Output = Output; - // compute: let output = Provider::compute(context, code, &builder); - // builder.build_from(output) + + fn compute(context: &Context, code: PhantomData, builder: Builder) -> Self::Output { + let output = Provider::compute(context, code, &builder); + builder.build_from(output) + } } ``` -It runs `Provider` on a reference to the builder to produce a result record, then uses -[`CanBuildFrom`](../../traits/casting/can_build_from.md) to copy every shared field into the builder. It -implements `Computer`, `TryComputer`, and `Handler`; the fallible and async forms require the context to -have an error type. +`build_from` walks the sub-record's field list and sets each field on the builder, so the returned +builder has those fields marked present. The `TryComputer` and `Handler` impls run the provider with +`try_compute` or `handle` and return its error through `?`. ## Related constructs -- [`BuildAndSetField`](build_and_set_field.md) — the single-field counterpart. -- [`BuildWithHandlers`](build_with_handlers.md) — the entry point that runs a list of these adapters. -- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — wraps a list of plain field-producing providers - in `BuildAndMerge` automatically. -- [`CanBuildFrom`](../../traits/casting/can_build_from.md) — the cast it uses to copy shared fields. +- [`BuildAndSetField`](build_and_set_field.md) — the step for one field. +- [`BuildWithHandlers`](build_with_handlers.md) — runs a list of steps and finalizes. +- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — adds this step to each provider in a list. +- [`CanBuildFrom`](../../traits/casting/can_build_from.md) — the trait that copies the shared + fields. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — assembling a record from independent parts. +- [Extensible records](/docs/concepts/extensible-records) — assembling a record from independent + parts. ## Source diff --git a/docs/reference/providers/dispatch/build_and_merge_outputs.md b/docs/reference/providers/dispatch/build_and_merge_outputs.md index f10ac198..1e2cefcb 100644 --- a/docs/reference/providers/dispatch/build_and_merge_outputs.md +++ b/docs/reference/providers/dispatch/build_and_merge_outputs.md @@ -1,66 +1,209 @@ --- +title: 'BuildAndMergeOutputs — merge whole records' +description: 'The builder that takes a list of sub-record providers, merges each output into the target record by field name, and finalizes it.' sidebar_label: 'BuildAndMergeOutputs' sidebar_position: 11 --- # `BuildAndMergeOutputs` -Build a record from a list of plain field-producing providers, wrapping each in a merge step -automatically. +Build a record from a list of providers that each build part of it, merging every output in by field +name. ## Overview -`BuildAndMergeOutputs` is a higher-level wrapper over -[`BuildWithHandlers`](build_with_handlers.md), used when the handler list is a list of plain -field-producing providers rather than builder adapters. It wraps each provider in -[`BuildAndMerge`](build_and_merge.md) for you, so a caller supplies result-producing providers and each -one is merged into the builder without the caller writing the merge step. It runs on a **context**, the -type a method runs on. Like every CGP provider, it carries no runtime value. +`BuildAndMergeOutputs` assembles a record from providers that each build a +sub-record: a database configuration, an HTTP configuration, a logger. It wraps each provider in the +[`BuildAndMerge`](build_and_merge.md) step and runs the list through +[`BuildWithHandlers`](build_with_handlers.md), on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. The +providers know nothing of the target record or of each other; the merge matches their fields to the +target's by name. Like every CGP provider, it carries no runtime value. ## Usage Import it from `cgp::extra::dispatch`. It takes the output record type and a -[`Product!`](../../macros/product.md) list of field-producing providers: +[`Product!`](../../macros/product.md) list of sub-record providers: ```rust use cgp::extra::dispatch::BuildAndMergeOutputs; -// Each provider produces some fields; BuildAndMergeOutputs merges them all into an App. delegate_components! { AppBuilder { ComputerComponent: - BuildAndMergeOutputs, + BuildAndMergeOutputs, } } ``` -Each of the three providers produces a record's worth of fields, and `BuildAndMergeOutputs` merges them -in turn into an `App`. +Between them, the sub-records must set every field of `Output` once. It answers `ComputerComponent`, +`TryComputerComponent`, and `HandlerComponent`, running each provider as the same member, so a +builder whose providers are handlers is wired to `HandlerComponent`. + +## Examples + +The same two subsystems as on the [`BuildAndMerge`](build_and_merge.md) page, listed bare: + +```rust +use cgp::prelude::*; +use cgp::extra::dispatch::BuildAndMergeOutputs; +use cgp::extra::handler::CanCompute; + +#[derive(Debug, PartialEq, CgpData)] +pub struct App { + pub db_url: String, + pub max_connections: u32, + pub user_agent: String, +} + +#[derive(CgpData)] +pub struct DatabaseConfig { + pub db_url: String, + pub max_connections: u32, +} + +#[derive(HasField)] +pub struct AppBuilder { + pub db_path: String, + pub agent_name: String, +} + +#[cgp_impl(new BuildDatabaseConfig)] +impl Computer { + type Output = DatabaseConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] db_path: &str, + ) -> DatabaseConfig { + DatabaseConfig { + db_url: format!("sqlite://{db_path}"), + max_connections: 4, + } + } +} + +#[derive(CgpData)] +pub struct HttpConfig { + pub user_agent: String, +} + +#[cgp_impl(new BuildHttpConfig)] +impl Computer { + type Output = HttpConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] agent_name: &str, + ) -> HttpConfig { + HttpConfig { + user_agent: format!("{agent_name}/1.0"), + } + } +} + +delegate_components! { + AppBuilder { + ComputerComponent: + BuildAndMergeOutputs, + } +} + +check_components! { + AppBuilder { + ComputerComponent: ((), ()), + } +} + +pub fn demo() { + let builder = AppBuilder { + db_path: "app.db".to_owned(), + agent_name: "reader".to_owned(), + }; + + assert_eq!( + builder.compute(PhantomData::<()>, ()), + App { + db_url: "sqlite://app.db".to_owned(), + max_connections: 4, + user_agent: "reader/1.0".to_owned(), + }, + ); +} +``` + +The wiring is the `BuildAndMerge` page's list with the two `BuildAndMerge` wrappers left out. +`AppBuilder` is an [environmental context](/docs/reference/glossary#environmental-context) holding +the configuration the providers read. ## When to use it -**Reach for `BuildAndMergeOutputs` when your handlers are plain field-producing providers** rather than -builder adapters, so each is merged into the builder without you writing the merge step. When you want -to control each step, setting one field or merging explicitly, use -[`BuildWithHandlers`](build_with_handlers.md) directly with -[`BuildAndSetField`](build_and_set_field.md) and [`BuildAndMerge`](build_and_merge.md). +**Reach for `BuildAndMergeOutputs` when every part of a record comes from a provider that builds a +sub-record**, the extensible builder pattern for assembling an application from its subsystems. When +some steps set single fields, use [`BuildWithHandlers`](build_with_handlers.md) with +[`BuildAndSetField`](build_and_set_field.md) and [`BuildAndMerge`](build_and_merge.md) directly. ## Under the hood -`BuildAndMergeOutputs` is a [`delegate_components!`](../../macros/delegate_components.md) -table that maps the whole handler family (`ComputerComponent`, `TryComputerComponent`, -`HandlerComponent`, and their `Ref` forms) to -`BuildWithHandlers`, where each provider in `Handlers` has first been wrapped -in [`BuildAndMerge`](build_and_merge.md). The wrapping is done by mapping the list through the -`ToBuildAndMergeHandler` [`MapType`](../../traits/type-level/map_type.md) marker, so a caller supplies plain -result-producing providers and each is merged into the builder automatically. +`BuildAndMergeOutputs` is a [`delegate_components!`](../../macros/delegate_components.md) table that +maps the handler components to `BuildWithHandlers` over the list with each provider wrapped in +`BuildAndMerge`: + +```rust +delegate_components! { + > + new BuildAndMergeOutputs { + [ + ComputerComponent, + ComputerRefComponent, + TryComputerComponent, + TryComputerRefComponent, + HandlerComponent, + HandlerRefComponent, + ]: + BuildWithHandlers + } +} + +pub struct ToBuildAndMergeHandler; + +impl MapType for ToBuildAndMergeHandler { + type Map = BuildAndMerge; +} +``` + +[`MapFields`](../../traits/type-level/map_fields.md) applies the +[`MapType`](../../traits/type-level/map_type.md) marker `ToBuildAndMergeHandler` to each element of +the list, so `Product![BuildDatabaseConfig, BuildHttpConfig]` becomes +`Product![BuildAndMerge, BuildAndMerge]`. + +## Common Mistakes + +**The `…Ref` entries do not resolve.** The table routes `ComputerRefComponent`, +`TryComputerRefComponent`, and `HandlerRefComponent`, but `BuildWithHandlers` implements only +`Computer`, `TryComputer`, and `Handler`, so wiring `ComputerRefComponent` to it fails at the check, +and rustc lists the three impls it has: + +```text + | |________________________________________^ `IsProviderFor` + | |________________________________________^ `IsProviderFor` + | |________________________________________^ `IsProviderFor` +``` + +Wire it to the owned-input components only. The builder ignores its input, so a borrowed form would +add nothing. ## Related constructs -- [`BuildWithHandlers`](build_with_handlers.md) — the entry point this wraps, for a list of builder - adapters directly. -- [`BuildAndMerge`](build_and_merge.md) — the merge step each provider in the list is wrapped in. -- [`MapType`](../../traits/type-level/map_type.md) — the trait the list-mapping marker implements. +- [`BuildWithHandlers`](build_with_handlers.md) — the builder this runs, for a list of steps written + directly. +- [`BuildAndMerge`](build_and_merge.md) — the step each provider is wrapped in. +- [`MapFields`](../../traits/type-level/map_fields.md), + [`MapType`](../../traits/type-level/map_type.md) — the list mapping that adds the wrappers. The ideas behind it: diff --git a/docs/reference/providers/dispatch/build_and_set_field.md b/docs/reference/providers/dispatch/build_and_set_field.md index b2a22554..f596cb5a 100644 --- a/docs/reference/providers/dispatch/build_and_set_field.md +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -1,48 +1,148 @@ --- +title: 'BuildAndSetField — set one built field' +description: 'The builder step that computes one field''s value from a provider, which can read the fields already set, and sets it on the partial record.' sidebar_label: 'BuildAndSetField' sidebar_position: 8 --- # `BuildAndSetField` -The builder adapter that computes one field's value and sets it on a [partial record](/docs/reference/glossary#partial-record). +Compute one field's value and set it on a +[partial record](/docs/reference/glossary#partial-record). ## Overview -`BuildAndSetField` is the single-field builder adapter. It takes a builder, a partial -record, runs `Provider` over a *reference* to that builder to compute the value for `Tag`, then sets -that field and returns the advanced builder. Because the provider sees `&Builder`, it can read fields -already set on the partial record while computing the next one. It runs on a **context**, the type a -method runs on. Like every CGP provider, it carries no runtime value. +`BuildAndSetField` is the builder step for a single field. It takes the builder, a +partial record with some fields set, runs `Provider` over a reference to it to compute the value of +the field named `Tag`, and returns the builder with that field set, on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. Because +`Provider` receives the builder, it can read the fields earlier steps have set as well as anything +on the context. `Provider` defaults to [`UseContext`](../use_context.md). Like every CGP provider, +it carries no runtime value. ## Usage -Import it from `cgp::extra::dispatch`. It takes a field tag and the provider that computes the field's -value, and appears as an element of a builder list passed to -[`BuildWithHandlers`](build_with_handlers.md): +Import it from `cgp::extra::dispatch`. It takes the field's tag, a +[`Symbol!`](../../macros/symbol.md) naming it, and the provider that computes its value, and is +written as a step in a [`BuildWithHandlers`](build_with_handlers.md) list: ```rust use cgp::extra::dispatch::{BuildAndSetField, BuildWithHandlers}; -type Handlers = Product![ - BuildAndSetField, - BuildAndSetField, -]; +delegate_components! { + PoolBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndSetField, + ]>, + } +} +``` + +The provider's output type must equal the field's type. It implements `Computer`, `TryComputer`, and +`Handler`, running the provider as the same member; the fallible forms need the context to have an +error type and return the provider's error. + +## Examples + +The second step reads the field the first one set: + +```rust +use cgp::prelude::*; +use cgp::extra::dispatch::{BuildAndSetField, BuildWithHandlers}; +use cgp::extra::handler::CanCompute; + +#[derive(Debug, PartialEq, CgpData)] +pub struct PoolConfig { + pub max_connections: u32, + pub max_idle: u32, +} + +#[derive(HasField)] +pub struct PoolBuilder { + pub connections: u32, +} + +#[cgp_impl(new BuildMaxConnections)] +impl Computer { + type Output = u32; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] connections: u32, + ) -> u32 { + connections + } +} + +// Reads `max_connections` from the partial record, which the step before it has set. +#[cgp_new_provider] +impl<'a, Context, Code, Builder> Computer for BuildMaxIdle +where + Builder: HasField, +{ + type Output = u32; + + fn compute(_context: &Context, _code: PhantomData, builder: &'a Builder) -> u32 { + builder.get_field(PhantomData) / 2 + } +} + +delegate_components! { + PoolBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndSetField, + ]>, + } +} + +check_components! { + PoolBuilder { + ComputerComponent: ((), ()), + } +} + +pub fn demo() { + let builder = PoolBuilder { connections: 8 }; + + assert_eq!( + builder.compute(PhantomData::<()>, ()), + PoolConfig { + max_connections: 8, + max_idle: 4, + }, + ); +} ``` +A partial record implements [`HasField`](../../traits/field-access/has_field.md) for the fields it +has set, so `BuildMaxIdle` bounds on the one it needs, and listing it before the +`max_connections` step would fail that bound. `BuildMaxConnections` reads the context's +`connections` field instead. `PoolBuilder` is an +[environmental context](/docs/reference/glossary#environmental-context) holding the configuration. + ## When to use it -**Reach for `BuildAndSetField` when a builder step computes one named field**, inside a list passed to -[`BuildWithHandlers`](build_with_handlers.md). To copy a whole record's worth of fields in one step, use -[`BuildAndMerge`](build_and_merge.md) instead. +**Reach for `BuildAndSetField` when a step computes one named field**, in a list for +[`BuildWithHandlers`](build_with_handlers.md). When a provider already builds a record holding +several of the fields, [`BuildAndMerge`](build_and_merge.md) copies them in one step. ## Under the hood -`BuildAndSetField` carries the tag and provider in `PhantomData`: +`BuildAndSetField` carries the tag and provider in `PhantomData`. Its `Computer` impl +runs `Provider` on a reference to the builder, then sets the field with +[`BuildField`](../../traits/builder/build_field.md), which returns a builder of a new type with +that field marked present: ```rust pub struct BuildAndSetField(pub PhantomData<(Tag, Provider)>); +#[cgp_provider] impl Computer for BuildAndSetField where @@ -50,22 +150,23 @@ where Builder: BuildField, { type Output = Output; - // compute: let value = Provider::compute(context, code, &builder); - // builder.build_field(PhantomData::, value) + + fn compute(context: &Context, code: PhantomData, builder: Builder) -> Self::Output { + let value = Provider::compute(context, code, &builder); + builder.build_field(PhantomData::, value) + } } ``` -It runs `Provider` on a reference to the builder to compute the value, then calls -[`BuildField`](../../traits/builder/build_field.md) to set it. It implements `Computer`, `TryComputer`, and -`Handler`; the fallible and async forms require the context to have an error type and propagate the -provider's error. +The `for<'a>` bound is why the provider must accept a borrow of the builder at any lifetime. The +`TryComputer` and `Handler` impls run the provider with `try_compute` or `handle` and return its +error through `?`. ## Related constructs -- [`BuildAndMerge`](build_and_merge.md) — the bulk counterpart, copying a whole record's fields at once. -- [`BuildWithHandlers`](build_with_handlers.md) — the entry point that runs a list of these adapters and - finalizes. -- [`BuildField`](../../traits/builder/build_field.md) — the trait it drives to set a field. +- [`BuildAndMerge`](build_and_merge.md) — the step that copies a sub-record's fields at once. +- [`BuildWithHandlers`](build_with_handlers.md) — runs a list of steps and finalizes. +- [`BuildField`](../../traits/builder/build_field.md) — the trait it drives to set the field. - [`UseContext`](../use_context.md) — the default provider. The ideas behind it: diff --git a/docs/reference/providers/dispatch/build_with_handlers.md b/docs/reference/providers/dispatch/build_with_handlers.md index 32ca57ea..81861d61 100644 --- a/docs/reference/providers/dispatch/build_with_handlers.md +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -1,58 +1,171 @@ --- +title: 'BuildWithHandlers — build a record in steps' +description: 'The builder that starts an empty partial record, runs a list of steps that each fill fields, and finalizes the record once every field is set.' sidebar_label: 'BuildWithHandlers' sidebar_position: 10 --- # `BuildWithHandlers` -Turn a list of builder adapters into a complete record, starting from an empty builder and finalizing -the fully-populated result. +Build a record from a list of steps, starting from an empty builder and finalizing once every field +is set. ## Overview -`BuildWithHandlers` is the entry point on the builder side. It starts from an empty -[partial record](/docs/reference/glossary#partial-record), pipes that builder through a list of builder adapters so each one sets its field, and -finalizes the fully-populated result into the concrete `Output`. It runs on a **context**, the type a -method runs on. Because the finalize step is available only when every field is present, -omitting a handler for some field is a compile error rather than a runtime failure. Like every CGP -provider, it carries no runtime value. +`BuildWithHandlers` assembles a record whose fields come from separate providers. +It starts from the empty [partial record](/docs/reference/glossary#partial-record) of `Output`, +passes it through a list of builder steps that each set one field or a group of fields, and turns +the finished builder into the concrete `Output`, on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. Each +step's provider can read the context, so the context usually holds the configuration the record is +built from. The final conversion exists only for a builder with every field set, so a list that +leaves a field unset does not compile. Like every CGP provider, it carries no runtime value. ## Usage Import it from `cgp::extra::dispatch`. It takes the output record type and a -[`Product!`](../../macros/product.md) list of builder adapters: +[`Product!`](../../macros/product.md) list of steps, each a +[`BuildAndSetField`](build_and_set_field.md) for one field or a +[`BuildAndMerge`](build_and_merge.md) for a sub-record's fields: ```rust use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; -type Handlers = Product![ - BuildAndMerge, - BuildAndSetField, -]; +delegate_components! { + AppBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndSetField, + ]>, + } +} +``` + +It ignores the input it is given, so it is called with `()`. `Output` needs the builder traits, +which [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) or +[`#[derive(BuildField)]`](../../derives/derive_build_field.md) gives it. It implements `Computer`, +`TryComputer`, and `Handler`; the fallible forms need every step to support them and the context to +have an error type. + +## Examples + +An `AppBuilder` context holds the configuration, and two steps build an `App` from it: + +```rust +use cgp::prelude::*; +use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; +use cgp::extra::handler::CanCompute; -let foo_bar_baz = BuildWithHandlers::::compute(&context, code, ()); +#[derive(Debug, PartialEq, CgpData)] +pub struct App { + pub db_url: String, + pub max_connections: u32, + pub user_agent: String, +} + +#[derive(CgpData)] +pub struct DatabaseConfig { + pub db_url: String, + pub max_connections: u32, +} + +#[derive(HasField)] +pub struct AppBuilder { + pub db_path: String, + pub agent_name: String, +} + +#[cgp_impl(new BuildDatabaseConfig)] +impl Computer { + type Output = DatabaseConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] db_path: &str, + ) -> DatabaseConfig { + DatabaseConfig { + db_url: format!("sqlite://{db_path}"), + max_connections: 4, + } + } +} + +#[cgp_impl(new BuildUserAgent)] +impl Computer { + type Output = String; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] agent_name: &str, + ) -> String { + format!("{agent_name}/1.0") + } +} + +delegate_components! { + AppBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndSetField, + ]>, + } +} + +check_components! { + AppBuilder { + ComputerComponent: ((), ()), + } +} + +pub fn demo() { + let builder = AppBuilder { + db_path: "app.db".to_owned(), + agent_name: "reader".to_owned(), + }; + + assert_eq!( + builder.compute(PhantomData::<()>, ()), + App { + db_url: "sqlite://app.db".to_owned(), + max_connections: 4, + user_agent: "reader/1.0".to_owned(), + }, + ); +} ``` -`BuildWithHandlers` starts from `FooBarBaz::builder()`, runs [`BuildAndMerge`](build_and_merge.md) to -copy the `foo` and `bar` fields from a built `FooBar`, runs -[`BuildAndSetField`](build_and_set_field.md) to compute and set `baz`, and finalizes. Dropping either -handler leaves a field unset and fails to compile at the finalize step. +`BuildAndMerge` copies `db_url` and `max_connections` from the built `DatabaseConfig`, and +`BuildAndSetField` sets `user_agent`. Each step's provider ignores its input, the partial record, +and reads the configuration it needs from the context as an +[`#[implicit]`](../../attributes/implicit.md) argument. `AppBuilder` is an +[environmental context](/docs/reference/glossary#environmental-context) that stands for the +configuration an `App` is built from. ## When to use it -**Reach for `BuildWithHandlers` to assemble a record from a list of builder adapters**, -[`BuildAndSetField`](build_and_set_field.md) and [`BuildAndMerge`](build_and_merge.md). When the list is -plain field-producing providers instead, [`BuildAndMergeOutputs`](build_and_merge_outputs.md) wraps each -one and defers here. To take a value apart rather than assemble one, use a matcher such as +**Reach for `BuildWithHandlers` to assemble a record from steps you list**, mixing single fields and +merged sub-records. When every step builds a sub-record, +[`BuildAndMergeOutputs`](build_and_merge_outputs.md) takes the sub-record providers directly and +adds the merge steps. To take an enum apart rather than assemble a record, use a matcher such as [`MatchWithHandlers`](match_with_handlers.md). ## Under the hood -`BuildWithHandlers` carries the output type and the list in `PhantomData`: +`BuildWithHandlers` carries the output type and the list in `PhantomData`. Its +`Computer` impl takes the empty builder from [`HasBuilder`](../../traits/builder/has_builder.md), +runs the list over it with [`PipeHandlers`](../handler/pipe_handlers.md), and converts the result +with [`FinalizeBuild`](../../traits/builder/finalize_build.md): ```rust pub struct BuildWithHandlers(pub PhantomData<(Output, Handlers)>); +#[cgp_provider] impl Computer for BuildWithHandlers where @@ -61,31 +174,44 @@ where Res: FinalizeBuild, { type Output = Output; - // compute: PipeHandlers::compute(context, code, Output::builder()).finalize_build() + + fn compute(context: &Context, code: PhantomData, _input: Input) -> Self::Output { + PipeHandlers::compute(context, code, Output::builder()).finalize_build() + } } ``` -It obtains an empty builder from [`HasBuilder`](../../traits/builder/has_builder.md), threads it through the list -with [`PipeHandlers`](../handler/pipe_handlers.md) so each adapter sets its field, and calls -[`FinalizeBuild`](../../traits/builder/finalize_build.md) to recover the concrete `Output`. The original `Input` -is discarded; the output is produced from the builder. It implements `Computer`, `TryComputer`, and -`Handler`, the latter two requiring the context to have an error type. Because `finalize_build` is in -scope only for the all-present builder configuration, a missing field is caught at compile time. +Each step changes the builder's type, marking the fields it set as present, so `Res` is the builder +type after the last step. The `TryComputer` and `Handler` impls run the list with `try_compute` or +`handle`, return a step's error through `?`, and finalize the same way. + +## Common Mistakes + +**A list that leaves a field unset does not compile.** Dropping the `user_agent` step leaves the +final builder with that field absent, and `FinalizeBuild` exists only once every field is present, +so the check reports the builder by its markers, `IsNothing` for the missing `user_agent`: + +```text +error[E0277]: the trait bound `__PartialApp: FinalizeBuild` is not satisfied +``` + +Add a step for the field, or merge a sub-record that carries it. ## Related constructs -- [`BuildAndSetField`](build_and_set_field.md), [`BuildAndMerge`](build_and_merge.md) — the adapters +- [`BuildAndSetField`](build_and_set_field.md), [`BuildAndMerge`](build_and_merge.md) — the steps its list is built from. -- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — the higher-level wrapper for a list of plain - field-producing providers. -- [`PipeHandlers`](../handler/pipe_handlers.md) — the pipeline it threads the builder through. -- [`HasBuilder`](../../traits/builder/has_builder.md), [`FinalizeBuild`](../../traits/builder/finalize_build.md) — the - traits that start and finish the build. +- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — takes sub-record providers and adds the + merge steps. +- [`PipeHandlers`](../handler/pipe_handlers.md) — the pipeline it runs the builder through. +- [`HasBuilder`](../../traits/builder/has_builder.md), + [`FinalizeBuild`](../../traits/builder/finalize_build.md) — the traits that start and finish the + build. The ideas behind it: -- [Extensible records](/docs/concepts/extensible-records) — building a record field by field, checked at - compile time. +- [Extensible records](/docs/concepts/extensible-records) — building a record field by field, + checked at compile time. ## Source diff --git a/docs/reference/providers/dispatch/downcast_and_handle.md b/docs/reference/providers/dispatch/downcast_and_handle.md index da6d3e3b..062249d3 100644 --- a/docs/reference/providers/dispatch/downcast_and_handle.md +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -1,69 +1,186 @@ --- +title: 'DowncastAndHandle — match a group of variants' +description: 'The matcher adapter that narrows an enum to a smaller enum of some of its variants and hands that whole group to one inner provider.' sidebar_label: 'DowncastAndHandle' sidebar_position: 7 --- # `DowncastAndHandle` -The adapter that matches a whole group of variants at once by narrowing to a smaller enum. +Match a group of variants in one arm, by narrowing the input to a smaller enum. ## Overview -`DowncastAndHandle` is the matcher adapter that handles a *group* of variants in one -step rather than a single variant. Instead of extracting one field, it tries to narrow the input to a -smaller enum type `Inner`. On success it hands the whole `Inner` value to `Provider` and returns `Ok`; -on failure it returns `Err` of the remainder. It runs on a **context**, the type a method runs -on, and lets a matcher delegate several variants to one sub-matcher in a single step. Like every -CGP provider, it carries no runtime value. - -`Provider` defaults to [`UseContext`](../use_context.md). +`DowncastAndHandle` is the matcher arm for several variants that one provider +handles together. Instead of extracting one variant, it tries to narrow the input to `Inner`, a +smaller enum whose variants are a subset of the input's. When the value is one of those variants, +it hands the whole `Inner` value to `Provider` and returns `Ok`; otherwise it returns `Err` of the +remainder, with every variant of `Inner` ruled out, on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. +`Provider` defaults to [`UseContext`](../use_context.md). Like every CGP provider, it carries no +runtime value. ## Usage -Import it from `cgp::extra::dispatch`. It takes the inner enum type to narrow to and an optional inner -provider, and appears as an element of a matcher's list alongside single-variant adapters: +Import it from `cgp::extra::dispatch`. It takes the smaller enum and an optional inner provider, and +sits in a matcher's list beside single-variant arms: ```rust -use cgp::extra::dispatch::{DowncastAndHandle, ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; +use cgp::extra::dispatch::{ + DowncastAndHandle, ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers, +}; + +delegate_components! { + App { + ComputerComponent: + MatchWithHandlers>, + DowncastAndHandle, + ]>, + } +} +``` + +`Inner` needs [`HasFields`](../../traits/shape/has_fields.md) and +[`FromVariant`](../../traits/variant/from_variant.md), which `#[derive(CgpData)]` gives it, and each +of its variants must be a variant of the input with the same name and payload type. It implements +`Computer` and `AsyncComputer`. + +## Examples -// Handle the two "primitive" variants together via a sub-matcher, and the rest one at a time. -type Match = MatchWithHandlers, - ExtractFieldAndHandle>, -]>; +Counting the corners of a shape, with the two quadrilaterals handled as one group: + +```rust +use cgp::prelude::*; +use cgp::extra::dispatch::{ + DowncastAndHandle, ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers, +}; +use cgp::extra::handler::CanCompute; + +pub struct Circle { + pub radius: f64, +} + +pub struct Square { + pub side: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Square(Square), + Rectangle(Rectangle), +} + +#[derive(CgpData)] +pub enum Quadrilateral { + Square(Square), + Rectangle(Rectangle), +} + +#[cgp_computer] +pub fn count_circle_corners(_circle: Circle) -> u32 { + 0 +} + +#[cgp_computer] +pub fn count_quadrilateral_corners(_shape: Quadrilateral) -> u32 { + 4 +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: + MatchWithHandlers>, + DowncastAndHandle, + ]>, + } +} + +check_components! { + App { + ComputerComponent: ((), Shape), + } +} + +pub fn demo() { + let code = PhantomData::<()>; + + assert_eq!(App.compute(code, Shape::Circle(Circle { radius: 1.0 })), 0); + assert_eq!(App.compute(code, Shape::Square(Square { side: 2.0 })), 4); + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + assert_eq!(App.compute(code, rectangle), 4); +} ``` +The downcast arm rules out both `Square` and `Rectangle` on a miss, so after the two arms nothing is +left and the list is complete. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). + ## When to use it -**Reach for `DowncastAndHandle` when several variants share one sub-handler** and you want to route them -as a group rather than name each one. For a single variant use -[`ExtractFieldAndHandle`](extract_field_and_handle.md). Both go in a list consumed by +**Reach for `DowncastAndHandle` when several variants share one provider that wants them as an +enum of their own**, such as a sub-matcher or a function over a narrower type. For a single variant +use [`ExtractFieldAndHandle`](extract_field_and_handle.md). Both go in a list for [`MatchWithHandlers`](match_with_handlers.md). ## Under the hood -`DowncastAndHandle` carries the inner enum type and the provider in `PhantomData`: +`DowncastAndHandle` carries the smaller enum and the provider in `PhantomData`; the struct's first +parameter is named `Input`, while the impl names it `Inner`. The `Computer` impl narrows the input +with [`CanDowncastFields`](../../traits/casting/can_downcast_fields.md), returning early with +the remainder through `?`: ```rust pub struct DowncastAndHandle(pub PhantomData<(Input, Provider)>); + +#[cgp_provider] +impl Computer + for DowncastAndHandle +where + Input: CanDowncastFields, + Provider: Computer, +{ + type Output = Result; + + fn compute( + context: &Context, + tag: PhantomData, + input: Input, + ) -> Result { + let inner = input.downcast_fields(PhantomData::)?; + let output = Provider::compute(context, tag, inner); + Ok(output) + } +} ``` -Its `Output` is `Result`. It uses -[`CanDowncastFields`](../../traits/casting/can_downcast_fields.md) to try to narrow the input to `Inner`; -on success it hands the whole `Inner` value to `Provider` and returns `Ok`, and on failure it returns -`Err` of the remainder. It implements both `Computer` and `AsyncComputer`. +`CanDowncastFields` works on the extractor, not the enum, which is why the arm fits in a matcher's +loop. The `AsyncComputer` impl matches on the downcast and awaits `Provider::compute_async` on a +hit. ## Related constructs -- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the single-variant adapter this generalizes to - a group. -- [`MatchWithHandlers`](match_with_handlers.md) — the matcher that consumes a list mixing both. -- [`CanDowncastFields`](../../traits/casting/can_downcast_fields.md) — the cast it uses to narrow the input. +- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the single-variant arm. +- [`MatchWithHandlers`](match_with_handlers.md) — the matcher that runs a list mixing both. +- [`CanDowncastFields`](../../traits/casting/can_downcast_fields.md) — the cast it uses to narrow + the input. - [`UseContext`](../use_context.md) — the default inner provider. The ideas behind it: -- [Dispatching](/docs/concepts/dispatching) — routing a group of variants to one sub-handler. +- [Dispatching](/docs/concepts/dispatching) — routing a group of variants to one handler. - [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern and its casts. ## Source diff --git a/docs/reference/providers/dispatch/extract_field_and_handle.md b/docs/reference/providers/dispatch/extract_field_and_handle.md index 8de79a05..5c97fcfe 100644 --- a/docs/reference/providers/dispatch/extract_field_and_handle.md +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -1,91 +1,187 @@ --- +title: 'ExtractFieldAndHandle — one matcher arm' +description: 'The matcher adapter that tries one variant, hands its payload to an inner provider on a match, and passes the remainder on when the variant does not match.' sidebar_label: 'ExtractFieldAndHandle' sidebar_position: 5 --- # `ExtractFieldAndHandle` -The per-variant adapter that tries one variant and forwards its matched payload to an inner handler. +Try one variant of an enum, handing its payload to an inner provider on a match and the remainder +on to the next arm otherwise. ## Overview -`ExtractFieldAndHandle` is the variant adapter a matcher's handler list is built from. It -tries to extract the variant named `Tag` from the input. On success it wraps the payload in a -`Field` and hands it to `Provider`, returning `Ok` of the provider's output. On failure it -returns `Err` of the remainder, the extractor with that variant ruled out. It runs on a **context**, the -type a method runs on. It returns the `Result` shape the -matcher loop expects, so a [`Product!`](../../macros/product.md) of these adapters is the list a matcher -consumes. Like every CGP provider, it carries no runtime value. - -`Provider` defaults to [`UseContext`](../use_context.md), so a matched payload routes back through the -context's own handler wiring unless another provider is named. The first-argument variant -`ExtractFirstFieldAndHandle` is the same adapter for the `(Input, Args)` calling -convention: it threads the arguments into the provider call as `(Field, Args)` and returns -`Result`. +`ExtractFieldAndHandle` is one arm of a matcher's list. It takes an extractor, a view +of an enum that can rule variants out one at a time, and tries to extract the variant named `Tag`. +On a match it wraps the payload in a [`Field`](../../types/field.md) and returns `Ok` of +what `Provider` computes from it; on a miss it returns `Err` of the remainder, the extractor with +that variant ruled out, which the next arm takes as its input. It runs on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, and +`Provider` defaults to [`UseContext`](../use_context.md). Like every CGP provider, it carries no +runtime value. ## Usage -Import it from `cgp::extra::dispatch`. It takes a variant tag and an optional inner provider, and -appears as an element of a matcher's list: +Import it from `cgp::extra::dispatch`. It takes the variant's tag, a +[`Symbol!`](../../macros/symbol.md) naming it, and an optional inner provider. It is written as an +element of a matcher's list, usually around [`HandleFieldValue`](handle_field_value.md) so the inner +provider receives the bare payload rather than the `Field`: ```rust use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; -type Match = MatchWithHandlers>, - ExtractFieldAndHandle>, -]>; +delegate_components! { + App { + ComputerComponent: + MatchWithHandlers>, + ExtractFieldAndHandle>, + ]>, + } +} +``` + +The first-argument form `ExtractFirstFieldAndHandle` is the same arm for an +`(Input, Args)` input, as [`MatchFirstWithHandlers`](match_first_with_handlers.md) runs it. It hands +`Provider` a `(Field, Args)` on a match and returns `Err((remainder, args))` on a miss, +so the arguments travel on with the remainder. Both forms implement `Computer` and `AsyncComputer`. + +## Examples + +Two arms called by hand, to show the `Result` a matcher's loop passes between them: + +```rust +use cgp::prelude::*; +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue}; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +#[cgp_new_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } +} + +#[cgp_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +pub type CircleArm = ExtractFieldAndHandle>; +pub type RectangleArm = + ExtractFieldAndHandle>; + +pub struct App; + +pub fn demo() { + let code = PhantomData::<()>; + + // A hit: the circle arm extracts its variant and returns `Ok` of the area. + let circle = Shape::Circle(Circle { radius: 1.0 }); + let hit = CircleArm::compute(&App, code, circle.to_extractor()); + assert_eq!(hit.ok(), Some(core::f64::consts::PI)); + + // A miss: the circle arm hands back the remainder, which the rectangle arm takes. + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + match CircleArm::compute(&App, code, rectangle.to_extractor()) { + Ok(_) => panic!("a rectangle is not a circle"), + Err(remainder) => { + let area = RectangleArm::compute(&App, code, remainder); + assert_eq!(area.ok(), Some(12.0)); + } + } +} ``` -The payload arrives at `Provider` still wrapped as a `Field`, so wrapping the inner handler -in [`HandleFieldValue`](handle_field_value.md) strips the tag to a bare value. The convenience -matchers [`MatchWithValueHandlers`](match_with_value_handlers.md) and -[`MatchWithFieldHandlers`](match_with_field_handlers.md) generate lists of these adapters from an enum's -fields, so you rarely write them out by hand. +The arms are called through the `Computer` provider trait with `App` as the context, which needs no +wiring because `ComputeArea` reads nothing from it. `to_extractor` comes from the +[`HasExtractor`](../../traits/variant/has_extractor.md) impl that `#[derive(CgpData)]` gives +`Shape`. A matcher runs exactly this chain, and stops at the first `Ok`. ## When to use it -**Reach for `ExtractFieldAndHandle` when you spell out a matcher's per-variant list by hand** with -[`MatchWithHandlers`](match_with_handlers.md), naming one adapter per variant. When every variant is -handled the same way, [`MatchWithValueHandlers`](match_with_value_handlers.md) generates the list of -these adapters for you and is far shorter. Use the first-argument form `ExtractFirstFieldAndHandle` -documented here when the handlers also take extra arguments, and -[`DowncastAndHandle`](downcast_and_handle.md) to match a group of variants in one step. +**Reach for `ExtractFieldAndHandle` when you spell out a matcher's list**, one arm per variant, for +[`MatchWithHandlers`](match_with_handlers.md). When every payload goes to one provider, +[`MatchWithValueHandlers`](match_with_value_handlers.md) and +[`MatchWithFieldHandlers`](match_with_field_handlers.md) build the list of these arms from the enum. +To handle several variants in one arm, use [`DowncastAndHandle`](downcast_and_handle.md). ## Under the hood -`ExtractFieldAndHandle` carries the tag and provider in `PhantomData`: +`ExtractFieldAndHandle` carries the tag and provider in `PhantomData`. Its `Computer` +impl calls [`ExtractField`](../../traits/variant/extract_field.md) on the input, returns early +with the remainder on a miss through `?`, and converts the payload into a `Field` for `Provider`: ```rust pub struct ExtractFieldAndHandle(pub PhantomData<(Tag, Provider)>); -pub struct ExtractFirstFieldAndHandle(pub PhantomData<(Tag, Provider)>); + +#[cgp_provider] +impl Computer + for ExtractFieldAndHandle +where + Input: ExtractField, + Provider: Computer, Output = Output>, +{ + type Output = Result; + + fn compute( + context: &Context, + tag: PhantomData, + input: Input, + ) -> Result { + let value = input.extract_field(PhantomData::)?; + let output = Provider::compute(context, tag, value.into()); + Ok(output) + } +} ``` -Its `Output` is `Result`. It calls [`ExtractField`](../../traits/variant/extract_field.md) -on the input; on success it forwards a `Field` to `Provider` and returns `Ok`, and on -failure it returns `Err` of the remainder, the extractor with that variant ruled out. It implements both -`Computer` and `AsyncComputer`. +The `AsyncComputer` impl matches on the extraction and awaits `Provider::compute_async` on a hit. +`ExtractFirstFieldAndHandle` has the same two impls over `(Input, Args)`, with +`Output = Result`. ## Related constructs -- [`HandleFieldValue`](handle_field_value.md) — strips the `Field` wrapper this adapter delivers, so the - inner handler receives the bare payload. -- [`DowncastAndHandle`](downcast_and_handle.md) — the adapter that matches a group of variants at once - instead of one. -- [`MatchWithHandlers`](match_with_handlers.md) — the matcher that consumes a list of these adapters. -- [`ExtractField`](../../traits/variant/extract_field.md) — the trait it drives, and - [`Field`](../../types/field.md) — the tagged payload it forwards. -- [`UseContext`](../use_context.md) — the default inner provider. +- [`HandleFieldValue`](handle_field_value.md) — strips the `Field` this arm delivers, so the inner + provider receives the bare payload. +- [`DowncastAndHandle`](downcast_and_handle.md) — the arm that handles a group of variants at once. +- [`MatchWithHandlers`](match_with_handlers.md) — the matcher that runs a list of these arms. +- [`ExtractField`](../../traits/variant/extract_field.md) — the trait it drives. +- [`Field`](../../types/field.md) — the tagged payload it forwards. The ideas behind it: - [Dispatching](/docs/concepts/dispatching) — routing one variant to a handler. -- [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern it serves. +- [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern and its extractors. ## Source - [`providers/field_matchers/extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/field_matchers/extract_field.rs), - and `extract_first_field.rs` for the first-argument form. + with the first-argument form in `extract_first_field.rs`. --- diff --git a/docs/reference/providers/dispatch/handle_field_value.md b/docs/reference/providers/dispatch/handle_field_value.md index 84b1b0e5..7931655e 100644 --- a/docs/reference/providers/dispatch/handle_field_value.md +++ b/docs/reference/providers/dispatch/handle_field_value.md @@ -1,79 +1,166 @@ --- +title: 'HandleFieldValue — strip a variant''s tag' +description: 'The adapter that unwraps the tagged Field a matcher arm delivers and passes the bare payload to an inner provider, so an ordinary computer can handle it.' sidebar_label: 'HandleFieldValue' sidebar_position: 6 --- # `HandleFieldValue` -Strip the variant tag from a matched payload and pass the bare value to an inner handler. +Strip the variant tag from a matched payload and pass the bare value to an inner provider. ## Overview -`HandleFieldValue` is the unwrapping adapter that sits between an extract adapter and the -handler that does the work. An extract adapter such as -[`ExtractFieldAndHandle`](extract_field_and_handle.md) delivers a `Field`, so the variant -name stays attached to the payload. `HandleFieldValue` strips the `Field` wrapper and passes the bare -`Value` to `Provider`, on a **context**, the type a method runs on. This lets an -ordinary computer over the payload type serve as a per-variant handler. Like every CGP provider, it -carries no runtime value. - -`Provider` defaults to [`UseContext`](../use_context.md). The first-argument variant -`HandleFirstFieldValue` does the same for the `(Field, Args)` tuple, forwarding -`(Input, Args)`. +`HandleFieldValue` sits between a matcher arm and the provider that does the work. An arm +such as [`ExtractFieldAndHandle`](extract_field_and_handle.md) delivers its payload as a +[`Field`](../../types/field.md), with the variant name attached as a type. Most payload +handlers are ordinary computers over the payload type and know nothing of that tag, so +`HandleFieldValue` unwraps the `Field` and passes the bare `Value` to `Provider`, on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. +`Provider` defaults to [`UseContext`](../use_context.md). Like every CGP provider, it carries no +runtime value. ## Usage Import it from `cgp::extra::dispatch`. It takes one optional type parameter, the inner provider, and -wraps the handler inside an extract adapter: +is written inside an arm: ```rust use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue}; -// ComputeArea is an ordinary computer over the payload type; HandleFieldValue -// removes the Field wrapper so it receives the bare payload. type CircleArm = ExtractFieldAndHandle>; ``` -The convenience matcher [`MatchWithValueHandlers`](match_with_value_handlers.md) adds this wrapper -automatically, which is the one difference between it and -[`MatchWithFieldHandlers`](match_with_field_handlers.md). +The first-argument form `HandleFirstFieldValue` does the same for the +`(Field, Args)` input an [`ExtractFirstFieldAndHandle`](extract_field_and_handle.md) arm +delivers, forwarding `(Value, Args)`. Both implement `Computer` and `AsyncComputer`. + +## Examples + +`ComputeArea` is a plain computer over `Circle` and `Rectangle`, reached from each arm through +`HandleFieldValue`: + +```rust +use cgp::prelude::*; +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; +use cgp::extra::handler::CanCompute; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +#[cgp_new_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } +} + +#[cgp_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: + MatchWithHandlers>, + ExtractFieldAndHandle>, + ]>, + } +} + +check_components! { + App { + ComputerComponent: ((), Shape), + } +} + +pub fn demo() { + let circle = App.compute(PhantomData::<()>, Shape::Circle(Circle { radius: 2.0 })); + assert!((circle - 4.0 * core::f64::consts::PI).abs() < 1e-9); +} +``` + +Without `HandleFieldValue`, `ComputeArea` would need impls over `Field` +and `Field` instead. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). ## When to use it -**Reach for `HandleFieldValue` inside an extract adapter when the inner handler is an ordinary computer -over the payload type**, so it receives the bare value rather than a tagged `Field`. You rarely write it -directly, because [`MatchWithValueHandlers`](match_with_value_handlers.md) adds it for you. Omit it, or -use [`MatchWithFieldHandlers`](match_with_field_handlers.md), when the handler needs the variant tag. +**Reach for `HandleFieldValue` inside a spelled-out arm whose provider wants the bare payload.** You +rarely write it with the convenience matchers, because +[`MatchWithValueHandlers`](match_with_value_handlers.md) adds it to every arm; that is its one +difference from [`MatchWithFieldHandlers`](match_with_field_handlers.md). Leave it out when the +provider needs the variant's name from the tag. ## Under the hood -`HandleFieldValue` carries the inner provider in `PhantomData`: +`HandleFieldValue` carries the inner provider in `PhantomData`, and its `Computer` impl +reads the `Field`'s `value` and forwards it: ```rust pub struct HandleFieldValue(pub PhantomData); -pub struct HandleFirstFieldValue(pub PhantomData); + +#[cgp_provider] +impl Computer> + for HandleFieldValue +where + Provider: Computer, +{ + type Output = Output; + + fn compute( + context: &Context, + tag: PhantomData, + input: Field, + ) -> Self::Output { + Provider::compute(context, tag, input.value) + } +} ``` -It takes a `Field` input, unwraps it to the bare `Value`, and forwards to `Provider`. -`HandleFirstFieldValue` unwraps the `(Field, Args)` tuple and forwards `(Input, Args)`. +The `AsyncComputer` impl forwards the value to `Provider::compute_async`, and +`HandleFirstFieldValue` has the same pair over `(Field, Args)`, forwarding +`(input.value, args)`. ## Related constructs -- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the extract adapter that delivers the - `Field` this strips. -- [`MatchWithValueHandlers`](match_with_value_handlers.md) — adds this wrapper automatically; +- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the arm that delivers the `Field` this + unwraps. +- [`MatchWithValueHandlers`](match_with_value_handlers.md) — adds this to every arm; [`MatchWithFieldHandlers`](match_with_field_handlers.md) does not. - [`Field`](../../types/field.md) — the tagged payload it unwraps. - [`UseContext`](../use_context.md) — the default inner provider. The ideas behind it: -- [Dispatching](/docs/concepts/dispatching) — preparing a matched payload for a handler. +- [Dispatching](/docs/concepts/dispatching) — preparing a matched payload for its handler. ## Source - [`providers/field_matchers/field_value.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/field_matchers/field_value.rs), - and `first_field_value.rs` for the first-argument form. + with the first-argument form in `first_field_value.rs`. --- diff --git a/docs/reference/providers/dispatch/index.md b/docs/reference/providers/dispatch/index.md index bce7e17f..532ee69a 100644 --- a/docs/reference/providers/dispatch/index.md +++ b/docs/reference/providers/dispatch/index.md @@ -1,90 +1,101 @@ --- +description: 'The dispatch combinators: match an enum one variant at a time, and build a record one field at a time, with a handler per variant or field.' sidebar_label: 'Overview' sidebar_position: 0 --- # Dispatch combinators -The providers that route an extensible-data value (a record or a variant) to per-field or per-variant -handlers, and assemble or finalize the result. +The providers that route an extensible-data value (an enum or a record) to per-variant or per-field +handlers: the matchers take an enum apart, and the builders assemble a record. ## Overview -The dispatch combinators handle an arbitrary record or enum generically, where the set of fields or -variants is not known at the call site and the handling logic for each one lives in a separate -provider. A hand-written `match` names every variant in one place; these combinators instead drive the -extractor and builder trait families to do the same work over a value whose shape is only known at the -type level, dispatching each field or variant to a handler chosen by type. They run on a **context**, -the type a method runs on, and are all [`Computer`](../../components/handler/computer.md)-family -providers, several also [`Handler`](../../components/handler/handler.md) and -[`TryComputer`](../../components/handler/try_computer.md) providers. Like every CGP provider, each is zero-sized. - -The combinators divide into two halves. - -The **matcher** half consumes a sum type. It tries each variant in turn, hands the matched payload to a -handler, and proves the match exhaustive without a wildcard arm: - -- [`MatchWithHandlers`](match_with_handlers.md) runs a spelled-out list of per-variant handlers over an - owned input. -- [`MatchFirstWithHandlers`](match_first_with_handlers.md) does the same for the multi-argument calling - convention, where the input carries extra arguments alongside the value. +The dispatch combinators handle an enum or a record generically, where the logic for each variant +or field lives in its own provider. A hand-written `match` names every variant in one place. These +combinators drive the extractor and builder traits instead, trying one variant or filling one field +at a time on a [**context**](/docs/reference/glossary#context), the type the implementation runs +against, and they prove at compile time that every variant is matched or every field is set. Like +every CGP provider, each is zero-sized: its type parameters ride in `PhantomData`. + +The two halves implement different members of the handler family. The matchers and their adapters +implement [`Computer`](../../components/handler/computer.md) and +[`AsyncComputer`](../../components/handler/async_computer.md) only, so a fallible slot takes them +through a [promotion](../handler/index.md). The builders implement `Computer`, +[`TryComputer`](../../components/handler/try_computer.md), and +[`Handler`](../../components/handler/handler.md), propagating a step's error in the fallible forms. + +The value matchers `MatchWithValueHandlers`, `MatchWithValueHandlersRef`, +`MatchWithValueHandlersMut`, and their `MatchFirstWith…` counterparts are in the prelude. Every +other name here is imported from `cgp::extra::dispatch`. + +## The matchers + +A **matcher** consumes an enum. It tries each variant in turn, hands the matched payload to a +handler, and needs no wildcard arm, because a variant with no handler is a compile error: + +- [`MatchWithHandlers`](match_with_handlers.md) runs a spelled-out list of per-variant handlers, + over an owned or a borrowed input. +- [`MatchFirstWithHandlers`](match_first_with_handlers.md) does the same for an `(Input, Args)` + input, passing the extra arguments to every handler. - [`MatchWithValueHandlers`](match_with_value_handlers.md) and - [`MatchWithFieldHandlers`](match_with_field_handlers.md) build that list automatically from the input - type's own field list. + [`MatchWithFieldHandlers`](match_with_field_handlers.md) build that list from the enum's own + variants, passing each payload bare or tagged with its variant name. -The per-variant list a matcher runs is normally a list of **adapters**, each trying one variant and -forwarding the payload: +The list a matcher runs is a list of **adapters**, each trying one variant or group: -- [`ExtractFieldAndHandle`](extract_field_and_handle.md) extracts one variant and hands the payload, - still tagged, to an inner provider. -- [`HandleFieldValue`](handle_field_value.md) strips the tag so the inner provider receives the bare - value. -- [`DowncastAndHandle`](downcast_and_handle.md) matches a whole group of variants at once. +- [`ExtractFieldAndHandle`](extract_field_and_handle.md) extracts one variant and hands its payload, + tagged, to an inner provider. +- [`HandleFieldValue`](handle_field_value.md) strips the tag, so the inner provider receives the + bare payload. +- [`DowncastAndHandle`](downcast_and_handle.md) narrows the input to a smaller enum and hands a + whole group of variants to one provider. -The **builder** half produces a product type. It starts from an empty builder, runs a handler per field, -and finalizes the fully-populated record: +## The builders +A **builder** produces a record. It starts from an empty +[partial record](/docs/reference/glossary#partial-record), runs a step per field or group of +fields, and finalizes the record once every field is set: + +- [`BuildWithHandlers`](build_with_handlers.md) runs a list of builder steps and finalizes. - [`BuildAndSetField`](build_and_set_field.md) computes and sets one field. -- [`BuildAndMerge`](build_and_merge.md) copies a whole record's worth of fields in at once. -- [`BuildWithHandlers`](build_with_handlers.md) is the entry point that runs a list of builder adapters - and finalizes. -- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) is the wrapper for a list of plain field-producing - providers. - -Both halves are handler providers, so they compose with the [handler combinators](../handler/index.md), -nest inside [`UseInputDelegate`](../handler/use_input_delegate.md), and can be wired into a context with -[`delegate_components!`](../../macros/delegate_components.md). The matcher loop they share is -`DispatchMatchers`, a type alias for [`PipeMonadic`](../monad/pipe_monadic.md) under the `OkMonadic` -monad; it is an implementation detail rather than a construct a user names, and it is explained under -the hood on [`MatchWithHandlers`](match_with_handlers.md). +- [`BuildAndMerge`](build_and_merge.md) builds a sub-record and copies its fields in. +- [`BuildAndMergeOutputs`](build_and_merge_outputs.md) takes a list of sub-record providers and adds + the merge step to each. + +Both halves are handler providers, so they compose with the +[handler combinators](../handler/index.md) and wire into a context with +[`delegate_components!`](../../macros/delegate_components.md). ## Related constructs -- [`#[cgp_auto_dispatch]`](../../macros/cgp_auto_dispatch.md) — generates a matcher-backed handler impl - automatically. -- [`extract_field`](../../traits/variant/extract_field.md), [`has_extractor`](../../traits/variant/has_extractor.md), - [`finalize_extract`](../../traits/variant/finalize_extract.md) — the enum-deconstruction traits the matchers - stand on. -- [`has_builder`](../../traits/builder/has_builder.md), [`build_field`](../../traits/builder/build_field.md), - [`finalize_build`](../../traits/builder/finalize_build.md) — the record-assembly traits the builders stand on. -- [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher the convenience matchers - use. -- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — the derive that gives a type the shape these - operate over. +- [`#[cgp_auto_dispatch]`](../../macros/cgp_auto_dispatch.md) — generates a matcher-backed trait + impl for an enum. +- [`ExtractField`](../../traits/variant/extract_field.md), + [`HasExtractor`](../../traits/variant/has_extractor.md), + [`FinalizeExtract`](../../traits/variant/finalize_extract.md) — the enum-deconstruction traits the + matchers stand on. +- [`HasBuilder`](../../traits/builder/has_builder.md), + [`BuildField`](../../traits/builder/build_field.md), + [`FinalizeBuild`](../../traits/builder/finalize_build.md) — the record-assembly traits the + builders stand on. +- [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) — the derive that gives a type the shape + these operate over. The ideas behind it: -- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to per-field and - per-variant handlers. -- [Extensible records](/docs/concepts/extensible-records) and - [Extensible variants](/docs/concepts/extensible-variants) — the data patterns the builders and matchers - serve. +- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to per-variant and + per-field handlers. +- [Extensible variants](/docs/concepts/extensible-variants) and + [Extensible records](/docs/concepts/extensible-records) — the data patterns the matchers and + builders serve. ## Source - The provider structs are in `cgp-dispatch` under - [`providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-dispatch/src/providers). - The prelude re-exports the value-handler matchers; the rest are reached through `cgp::extra::dispatch`. + [`providers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-dispatch/src/providers), + and the prelude re-exports the value matchers from + [`cgp-extra`](https://github.com/contextgeneric/cgp/blob/main/crates/main/cgp-extra/src/prelude.rs). --- diff --git a/docs/reference/providers/dispatch/match_first_with_handlers.md b/docs/reference/providers/dispatch/match_first_with_handlers.md index 333e89ed..9af1a5e4 100644 --- a/docs/reference/providers/dispatch/match_first_with_handlers.md +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -1,98 +1,206 @@ --- +title: 'MatchFirstWithHandlers — match with arguments' +description: 'The matcher for an (Input, Args) input: it matches the enum in the first element and passes the extra arguments to every per-variant handler.' sidebar_label: 'MatchFirstWithHandlers' sidebar_position: 2 --- # `MatchFirstWithHandlers` -Match an enum for the multi-argument calling convention, where the input carries extra arguments -alongside the value. +Match an enum that arrives together with extra arguments, passing the arguments to every handler. ## Overview -`MatchFirstWithHandlers` is the matcher for the calling convention where the input is a tuple -`(Input, Args)`: the value being matched, together with extra arguments to pass to each handler. It -threads `Args` through the loop unchanged, so on a miss both the shrinking remainder and the still-owned -arguments carry to the next handler. It runs on a **context**, the type a method runs on. The -"first" in the name reflects that the value being matched is the *first* element of the input tuple. -Like every CGP provider, it carries no runtime value; the handler list rides in `PhantomData`. - -Two borrowed forms exist: `MatchFirstWithHandlersRef` over `(&Input, Args)` and -`MatchFirstWithHandlersMut` over `(&mut Input, Args)`. Each of the three implements both -`Computer` and `AsyncComputer`. +`MatchFirstWithHandlers` is the matcher for an input of the form `(Input, Args)`: the enum +being matched, first, and extra arguments that every per-variant handler needs, such as a scale +factor or a target buffer. It works like [`MatchWithHandlers`](match_with_handlers.md) on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, except +that `Args` travels with the extractor through the loop, so on a miss the next handler still +receives the arguments. Like every CGP provider, it carries no runtime value; the handler list rides +in `PhantomData`. ## Usage Import it from `cgp::extra::dispatch`. It takes one type parameter, a -[`Product!`](../../macros/product.md) list of per-variant adapters, built from -[`ExtractFirstFieldAndHandle`](extract_field_and_handle.md) and -[`HandleFirstFieldValue`](handle_field_value.md) rather than their plain forms: +[`Product!`](../../macros/product.md) list of per-variant adapters built from the first-argument +forms [`ExtractFirstFieldAndHandle`](extract_field_and_handle.md) and +[`HandleFirstFieldValue`](handle_field_value.md), which carry `Args` alongside the payload: ```rust use cgp::extra::dispatch::{ ExtractFirstFieldAndHandle, HandleFirstFieldValue, MatchFirstWithHandlers, }; -// Each handler receives the matched payload together with the shared Args. -type Match = MatchFirstWithHandlers>, - ExtractFirstFieldAndHandle>, -]>; +delegate_components! { + App { + ComputerComponent: + MatchFirstWithHandlers>, + ExtractFirstFieldAndHandle>, + ]>, + } +} ``` -For a list built automatically, use [`MatchFirstWithValueHandlers`](match_with_value_handlers.md). +Each payload handler then computes over `(Circle, Args)` or `(Rectangle, Args)`. Two borrowed forms +take the same list: `MatchFirstWithHandlersRef` over `(&Input, Args)` and +`MatchFirstWithHandlersMut` over `(&mut Input, Args)`. All three implement `Computer` and +`AsyncComputer`, and nothing else. + +## Examples + +A `Shape` enum whose area is scaled by a factor passed with it: + +```rust +use cgp::prelude::*; +use cgp::extra::dispatch::{ + ExtractFirstFieldAndHandle, HandleFirstFieldValue, MatchFirstWithHandlers, +}; +use cgp::extra::handler::CanCompute; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +#[cgp_new_provider] +impl Computer for ScaledArea { + type Output = f64; + + fn compute( + _context: &Context, + _code: PhantomData, + (circle, scale): (Circle, f64), + ) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius * scale * scale + } +} + +#[cgp_provider] +impl Computer for ScaledArea { + type Output = f64; + + fn compute( + _context: &Context, + _code: PhantomData, + (rectangle, scale): (Rectangle, f64), + ) -> f64 { + rectangle.width * rectangle.height * scale * scale + } +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: + MatchFirstWithHandlers>, + ExtractFirstFieldAndHandle>, + ]>, + } +} + +check_components! { + App { + ComputerComponent: ((), (Shape, f64)), + } +} + +pub fn demo() { + let code = PhantomData::<()>; + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + + assert_eq!(App.compute(code, (rectangle, 2.0)), 48.0); // 12 * 2 * 2 +} +``` + +The `Circle` arm misses and hands the extractor and the `2.0` on together, so `ScaledArea` receives +the `Rectangle` payload beside its scale factor. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). ## When to use it -**Reach for `MatchFirstWithHandlers` when the per-variant handlers need extra arguments passed alongside -the matched value**, such as a renderer that takes a target buffer or a visitor that takes an -accumulator. When the handlers need only the value, use the plain -[`MatchWithHandlers`](match_with_handlers.md), which is simpler. +**Reach for `MatchFirstWithHandlers` when every per-variant handler needs the same extra +arguments.** When the handlers need only the payload, [`MatchWithHandlers`](match_with_handlers.md) +is simpler. When every payload goes to one provider, the convenience aliases build the list from the +enum: `MatchFirstWithValueHandlers` answers the example above on its own, and +`MatchFirstWithFieldHandlers` keeps each payload tagged. They come in the same three input modes as +their plain counterparts, [`MatchWithValueHandlers`](match_with_value_handlers.md) and +[`MatchWithFieldHandlers`](match_with_field_handlers.md). The value forms are in the prelude; the +field forms are imported from `cgp::extra::dispatch`. ## Under the hood -`MatchFirstWithHandlers` carries the list in `PhantomData`: +`MatchFirstWithHandlers` carries the list in `PhantomData`. Its `Computer` impl runs the +shared matcher loop over `(Input::Extractor, Args)`, so each miss returns `(Remainder, Args)` and +the arguments stay with the extractor, and it discharges the leftover remainder once every variant +is ruled out: ```rust pub struct MatchFirstWithHandlers(pub PhantomData); -``` - -Its `Computer` impl runs the shared matcher loop over `(Input::Extractor, Args)` and returns -`Result`, so a miss carries both the shrunken remainder and the still-owned -arguments to the next handler. When the loop finishes with an `Err`, the remainder is uninhabited and is -discharged through `finalize_extract`: -```rust -impl - Computer for MatchFirstWithHandlers +#[cgp_provider] +impl Computer + for MatchFirstWithHandlers where Input: HasExtractor, DispatchMatchers: Computer< - Context, Code, (Input::Extractor, Args), - Output = Result>, + Context, + Code, + (Input::Extractor, Args), + Output = Result, + >, Remainder: FinalizeExtract, { type Output = Output; - // compute: match DispatchMatchers::compute(context, code, (input.to_extractor(), args)) { - // Ok(output) => output, - // Err((remainder, _)) => remainder.finalize_extract(), - // } + + fn compute(context: &Context, code: PhantomData, (input, args): (Input, Args)) -> Output { + let res = DispatchMatchers::compute(context, code, (input.to_extractor(), args)); + match res { + Ok(output) => output, + Err((remainder, _)) => remainder.finalize_extract(), + } + } } ``` -The loop is the same `DispatchMatchers` alias described on -[`MatchWithHandlers`](match_with_handlers.md#under-the-hood). +The loop is the `DispatchMatchers` alias described on +[`MatchWithHandlers`](match_with_handlers.md#under-the-hood). The `AsyncComputer` impl has the same +bounds over `AsyncComputer`. The convenience aliases are `UseInputDelegate` tables keyed on +`(Input, Args)`, and on `(&'a Input, Args)` and `(&'a mut Input, Args)` for the borrowed forms, each +mapping the input to this matcher over a list built from the enum's variants. + +## Common Mistakes + +**The mistakes of the plain matcher apply unchanged.** A list that misses a variant fails the +`FinalizeExtract` bound, and the matcher cannot fill a `TryComputer` or `Handler` slot without a +promotion; [`MatchWithHandlers`](match_with_handlers.md#common-mistakes) shows both. ## Related constructs - [`MatchWithHandlers`](match_with_handlers.md) — the plain matcher, for handlers that need only the - value. -- [`ExtractFirstFieldAndHandle`](extract_field_and_handle.md), - [`HandleFirstFieldValue`](handle_field_value.md) — the first-argument adapters its list is built from. -- [`MatchWithValueHandlers`](match_with_value_handlers.md) — the automatic form, whose - `MatchFirstWithValueHandlers` sibling matches this convention. -- [`HasExtractor`](../../traits/variant/has_extractor.md), [`FinalizeExtract`](../../traits/variant/finalize_extract.md) - — the traits it stands on. + payload. +- [`ExtractFieldAndHandle`](extract_field_and_handle.md), + [`HandleFieldValue`](handle_field_value.md) — document the first-argument adapters its list is + built from. +- [`MatchWithValueHandlers`](match_with_value_handlers.md) — the convenience matcher whose + `MatchFirstWith…` forms build this list automatically. +- [`HasExtractor`](../../traits/variant/has_extractor.md), + [`FinalizeExtract`](../../traits/variant/finalize_extract.md) — the traits it stands on. The ideas behind it: @@ -102,7 +210,9 @@ The ideas behind it: ## Source - [`providers/with_handlers/match_first_with_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/with_handlers/match_first_with_handlers.rs), - with the borrowed forms in `match_first_with_handlers_ref.rs` and `match_first_with_handlers_mut.rs`. + with the borrowed forms in `match_first_with_handlers_ref.rs` and + `match_first_with_handlers_mut.rs`, and the convenience aliases in + [`providers/matchers/match_first_with_field_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/matchers/match_first_with_field_handlers.rs). --- diff --git a/docs/reference/providers/dispatch/match_with_field_handlers.md b/docs/reference/providers/dispatch/match_with_field_handlers.md index 5553d923..372e25d4 100644 --- a/docs/reference/providers/dispatch/match_with_field_handlers.md +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -1,70 +1,158 @@ --- +title: 'MatchWithFieldHandlers — match with the tag' +description: 'The convenience matcher that builds the per-variant handler list from an enum''s variants and passes each payload as a Field tagged with its variant name.' sidebar_label: 'MatchWithFieldHandlers' sidebar_position: 4 --- # `MatchWithFieldHandlers` -Match an enum by building the per-variant handler list automatically, passing each payload with its -variant tag still attached. +Match an enum by building the per-variant handler list from its own variants, passing each payload +with its variant name attached. ## Overview -`MatchWithFieldHandlers` synthesizes the per-variant handler list from the input type's own -field list, like [`MatchWithValueHandlers`](match_with_value_handlers.md), but hands each matched -payload to `Provider` as a `Field` with the variant name still attached rather than as a -bare value. It runs on a **context**, the type a method runs on. Reach for it when the handler -needs to know which variant it received. Like every CGP provider, it carries no runtime value. - -The two matchers differ by exactly one [`HandleFieldValue`](handle_field_value.md) wrapper: -`MatchWithValueHandlers` wraps `Provider` in it to strip the tag, and `MatchWithFieldHandlers` does not. -`Provider` defaults to [`UseContext`](../use_context.md). The borrowed and multi-argument variants are -`MatchWithFieldHandlersRef` and the first-argument aliases `MatchFirstWithFieldHandlers`, -`MatchFirstWithFieldHandlersRef`, and `MatchFirstWithFieldHandlersMut`. +`MatchWithFieldHandlers` builds the per-variant list from the input enum's field list, +like [`MatchWithValueHandlers`](match_with_value_handlers.md), but hands each payload to `Provider` +as a [`Field`](../../types/field.md), where `Tag` is the variant's name as a type-level +string. A provider over `Field` can read that name, so one provider can report or route +on which variant it received, on a [**context**](/docs/reference/glossary#context), the type the +implementation runs against. `Provider` defaults to [`UseContext`](../use_context.md). Like every +CGP provider, it carries no runtime value. ## Usage -Import it from `cgp::extra::dispatch`. It takes one optional type parameter, the per-variant provider. -Because it is itself a [`UseInputDelegate`](../handler/use_input_delegate.md) alias, it is wired -directly to a handler component and dispatches on the input type: +Import it from `cgp::extra::dispatch`; unlike the value form, it is not in the prelude. It takes one +optional type parameter, the per-variant provider, and is wired directly to a handler component, +since it dispatches on the input type itself: ```rust use cgp::extra::dispatch::MatchWithFieldHandlers; delegate_components! { App { - ComputerComponent: MatchWithFieldHandlers, + ComputerComponent: MatchWithFieldHandlers, + } +} +``` + +The borrowed form `MatchWithFieldHandlersRef` matches `&Input` and hands the provider a +`Field`. There is no `Mut` form, and the multi-argument forms are on +[`MatchFirstWithHandlers`](match_first_with_handlers.md#when-to-use-it). + +## Examples + +One provider describes every variant of two enums, reading the variant name from the tag: + +```rust +use core::fmt::Display; +use cgp::prelude::*; +use cgp::core::field::traits::StaticString; +use cgp::extra::dispatch::MatchWithFieldHandlers; +use cgp::extra::handler::CanCompute; + +#[derive(CgpData)] +pub enum Reading { + Temperature(i32), + Label(String), +} + +#[derive(CgpData)] +pub enum Event { + Started(u64), + Stopped(bool), +} + +#[cgp_computer] +pub fn describe(field: Field) -> String +where + Tag: StaticString, + Value: Display, +{ + format!("{}: {}", Tag::VALUE, field.value) +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: MatchWithFieldHandlers, + } +} + +check_components! { + App { + ComputerComponent: [((), Reading), ((), Event)], } } + +pub fn demo() { + let code = PhantomData::<()>; + + assert_eq!( + App.compute(code, Reading::Temperature(21)), + "Temperature: 21" + ); + assert_eq!( + App.compute(code, Reading::Label("north".to_owned())), + "Label: north" + ); + assert_eq!(App.compute(code, Event::Stopped(true)), "Stopped: true"); +} ``` -`FieldToString` receives each matched payload as a `Field`, so the variant tag stays -attached to it. For a handler that wants only the payload, use -[`MatchWithValueHandlers`](match_with_value_handlers.md). +[`StaticString`](../../traits/formatting/static_string.md) recovers the variant name from the tag, +so `Describe` prints it without naming either enum, and the one wiring entry serves both. `App` is +an [environmental context](/docs/reference/glossary#environmental-context). ## When to use it -**Reach for `MatchWithFieldHandlers` when the per-variant handler needs the variant tag**, for example -to log which case ran or to route further by name. When the handler wants only the payload, which is the common -case, [`MatchWithValueHandlers`](match_with_value_handlers.md) is simpler. +**Reach for `MatchWithFieldHandlers` when the per-variant handler needs the variant's name**, for +example to log which case ran or to look up a setting by name. When the handler wants only the +payload, which is the usual case, [`MatchWithValueHandlers`](match_with_value_handlers.md) is +simpler, and when different variants need different providers, +[`MatchWithHandlers`](match_with_handlers.md) takes a spelled-out list. ## Under the hood `MatchWithFieldHandlers` is a type alias over -[`UseInputDelegate`](../handler/use_input_delegate.md): +[`UseInputDelegate`](../handler/use_input_delegate.md), whose table maps each input enum to +[`MatchWithHandlers`](match_with_handlers.md) over a list built from the enum: ```rust pub type MatchWithFieldHandlers = UseInputDelegate>; + +delegate_components! { + >, Provider> + new MatchWithFieldHandlersInputs { + Input: MatchWithHandlers + } +} ``` -The per-variant list is built from a context's field list by three cooperating traits. `MapFieldHandler` -is a type-level function from a field's `Tag` to the adapter that should handle it; `ToFieldHandlers` -walks the [sum list](../../types/either.md) of a field list and applies that function to each -field, producing a [`Product!`](../../macros/product.md) list of adapters; and `HasFieldHandlers` reads a -context's [`HasFields`](../../traits/shape/has_fields.md) list and runs `ToFieldHandlers` over it: +Three traits build the list. `MapFieldHandler` maps a variant's `Tag` to the adapter that handles +it; `ToFieldHandlers` walks a [sum-type](../../types/either.md) field list and applies that map to +each variant; and `HasFieldHandlers` runs `ToFieldHandlers` over a type's +[`HasFields`](../../traits/shape/has_fields.md) list: ```rust +pub trait MapFieldHandler { + type FieldHandler; +} + +impl ToFieldHandlers for Either, RestFields> +where + M: MapFieldHandler, + RestFields: ToFieldHandlers, +{ + type Handlers = Cons, RestFields::Handlers>; +} + +impl ToFieldHandlers for Void { + type Handlers = Nil; +} + impl HasFieldHandlers for Context where Context: HasFields, @@ -74,23 +162,28 @@ where } ``` -`ToFieldHandlers` is implemented inductively over the sum list: for `Either, Rest>` -it produces `Cons, Rest::Handlers>`, and for the terminating `Void` it produces -`Nil`. The `MapFieldHandler` marker the crate supplies here is `MapExtractFieldAndHandle`, -whose `FieldHandler` is [`ExtractFieldAndHandle`](extract_field_and_handle.md)``, so -the matcher runs one extract adapter per variant without the user spelling out the list. -`MatchWithValueHandlers` differs only by wrapping `Provider` in -[`HandleFieldValue`](handle_field_value.md) first. +The map used here is `MapExtractFieldAndHandle`, whose `FieldHandler` is +[`ExtractFieldAndHandle`](extract_field_and_handle.md)``, so the list holds one +extract adapter per variant. Only the `Either`/`Void` list has impls, which is why the convenience +matchers apply to enums and not to structs. The first-argument aliases use +`MapExtractFirstFieldAndHandle` in the same place. + +## Common Mistakes + +**The mistakes of `MatchWithValueHandlers` apply unchanged.** The input must be an enum, and the +matcher answers only `Computer` and `AsyncComputer`; +[`MatchWithValueHandlers`](match_with_value_handlers.md#common-mistakes) shows both. ## Related constructs -- [`MatchWithValueHandlers`](match_with_value_handlers.md) — the sibling that strips the tag; the two - differ by one `HandleFieldValue` wrapper. -- [`MatchWithHandlers`](match_with_handlers.md) — the explicit form the list expands to. -- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the per-variant adapter the list is built - from. -- [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher this alias is built on. -- [`HasFields`](../../traits/shape/has_fields.md) — the field list the handler list is synthesized from. +- [`MatchWithValueHandlers`](match_with_value_handlers.md) — the sibling that strips the tag with + [`HandleFieldValue`](handle_field_value.md). +- [`MatchWithHandlers`](match_with_handlers.md) — the matcher the list is built for. +- [`ExtractFieldAndHandle`](extract_field_and_handle.md) — the per-variant adapter in the list. +- [`Field`](../../types/field.md), [`StaticString`](../../traits/formatting/static_string.md) — the + tagged payload and the trait that reads its name. +- [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher this alias is built + on. The ideas behind it: @@ -100,8 +193,8 @@ The ideas behind it: ## Source - [`providers/matchers/match_with_field_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs), - with the field-to-handler machinery in `to_field_handlers.rs` and the first-argument forms in - `match_first_with_field_handlers.rs`. + with the list machinery in + [`to_field_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/matchers/to_field_handlers.rs). --- diff --git a/docs/reference/providers/dispatch/match_with_handlers.md b/docs/reference/providers/dispatch/match_with_handlers.md index 90dc969d..7c321d48 100644 --- a/docs/reference/providers/dispatch/match_with_handlers.md +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -1,31 +1,30 @@ --- +title: 'MatchWithHandlers — match an enum, arm by arm' +description: 'The matcher that runs a spelled-out list of per-variant handlers over an enum, stopping at the first match and needing no wildcard arm.' sidebar_label: 'MatchWithHandlers' sidebar_position: 1 --- # `MatchWithHandlers` -Match an enum against a spelled-out list of per-variant handlers, proving the match exhaustive without a -wildcard arm. +Match an enum against a spelled-out list of per-variant handlers, with no wildcard arm. ## Overview -`MatchWithHandlers` is the owned-input matcher. Given a value, it converts the value to its -extractor and runs a list of handlers over it, stopping at the first one that matches. It runs on a -**context**, the type a method runs on. When the list is exhausted the remaining type has every -variant ruled out and is therefore uninhabited, which lets the matcher return the bare output -with no fallback arm. Like every CGP provider, it carries no runtime value; the handler list rides in -`PhantomData`. - -Two borrowed forms match a value without moving it: `MatchWithHandlersRef` over `&Input` and -`MatchWithHandlersMut` over `&mut Input`. Each of the three implements both the synchronous -`Computer` and the `AsyncComputer` form. +`MatchWithHandlers` is the matcher for an enum whose variants each have their own handler. +It turns the input into its extractor, a view of the enum that can rule variants out one at a time, +and runs a list of handlers over it on a [**context**](/docs/reference/glossary#context), the type +the implementation runs against. The first handler whose variant matches produces the output. When +the list has a handler for every variant, the last miss leaves nothing to match, so the matcher +returns the bare output with no fallback arm; a list that misses a variant does not compile. Like +every CGP provider, it carries no runtime value; the handler list rides in `PhantomData`. ## Usage -Import it from `cgp::extra::dispatch`. It takes one type parameter, a [`Product!`](../../macros/product.md) -list of per-variant adapters. The list is normally one [`ExtractFieldAndHandle`](extract_field_and_handle.md) -per variant, each wrapping its payload handler in [`HandleFieldValue`](handle_field_value.md): +Import it from `cgp::extra::dispatch`. It takes one type parameter, a +[`Product!`](../../macros/product.md) list of per-variant adapters. The list is normally one +[`ExtractFieldAndHandle`](extract_field_and_handle.md) per variant, each wrapping its payload +handler in [`HandleFieldValue`](handle_field_value.md) so the handler receives the bare payload: ```rust use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; @@ -41,15 +40,50 @@ delegate_components! { } ``` -For a list built automatically from the enum's own variants, reach for -[`MatchWithValueHandlers`](match_with_value_handlers.md) instead, which spells this list out for you. +Two borrowed forms take the same list and match without moving the value: +`MatchWithHandlersRef` over `&Input` and `MatchWithHandlersMut` over +`&mut Input`. Their adapters extract a borrowed payload, so each payload handler computes over +`&Circle` or `&mut Circle`, and the check names the borrowed input: + +```rust +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlersRef}; + +delegate_components! { + App { + ComputerComponent: + MatchWithHandlersRef>, + ExtractFieldAndHandle>, + ]>, + } +} + +check_components! { + App { + ComputerComponent: <'a> ((), &'a Shape), + } +} +``` + +All three implement `Computer` and `AsyncComputer`, and nothing else. ## Examples -Dispatching a `Shape` enum to a per-variant area computer: +A `Shape` enum dispatched to one area provider with an impl per payload type: ```rust +use cgp::prelude::*; use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; +use cgp::extra::handler::CanCompute; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} #[derive(CgpData)] pub enum Shape { @@ -57,42 +91,83 @@ pub enum Shape { Rectangle(Rectangle), } -// ComputeArea implements Computer for both the Circle and Rectangle payloads. -let circle = Shape::Circle(Circle { radius: 5.0 }); +#[cgp_new_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } +} + +#[cgp_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: + MatchWithHandlers>, + ExtractFieldAndHandle>, + ]>, + } +} + +check_components! { + App { + ComputerComponent: ((), Shape), + } +} + +pub fn demo() { + let code = PhantomData::<()>; + + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + assert_eq!(App.compute(code, rectangle), 12.0); -let _area = MatchWithHandlers::< - Product![ - ExtractFieldAndHandle>, - ExtractFieldAndHandle>, - ], ->::compute(&(), PhantomData::<()>, circle); + let circle = App.compute(code, Shape::Circle(Circle { radius: 1.0 })); + assert!((circle - core::f64::consts::PI).abs() < 1e-9); +} ``` -The list tries `Circle` first. If the value is a circle, `ComputeArea` runs on the `Circle` payload and -the loop stops. Otherwise the remainder carries `Circle` ruled out into the `Rectangle` adapter, the -last arm, so its failure would leave an uninhabited remainder that the matcher discharges. +A rectangle misses the `Circle` arm, and the extractor, now with `Circle` ruled out, reaches the +`Rectangle` arm. `App` is an [environmental +context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: it acts on the +`Shape` input. ## When to use it -**Reach for `MatchWithHandlers` when you want to name a handler per variant explicitly**, or when the -variants map to handlers in a way the automatic form cannot express. For the common case where every -variant is routed the same way, [`MatchWithValueHandlers`](match_with_value_handlers.md) builds the list -from the enum's fields and is far shorter. When the handlers also need extra arguments passed alongside -the value, use [`MatchFirstWithHandlers`](match_first_with_handlers.md). +**Reach for `MatchWithHandlers` when each variant needs a handler you name**, or when the variants +map to handlers in a way the enum's field list cannot generate. When every payload goes to the same +provider, [`MatchWithValueHandlers`](match_with_value_handlers.md) builds this list from the enum +and is shorter. When the handlers also take extra arguments, use +[`MatchFirstWithHandlers`](match_first_with_handlers.md). And when the per-variant handlers return +`Result`, [`TryPromote`](../handler/try_promote.md) turns the matcher's `Result` output into a +`TryComputer`. ## Under the hood -`MatchWithHandlers` carries the list in `PhantomData`: +`MatchWithHandlers` carries the list in `PhantomData`, and its `Computer` impl turns the +input into its [extractor](../../traits/variant/has_extractor.md), runs the list over it, and +discharges the leftover with +[`finalize_extract_result`](../../traits/variant/finalize_extract_result.md): ```rust pub struct MatchWithHandlers(pub PhantomData); -``` -Its `Computer` impl requires the input to implement [`HasExtractor`](../../traits/variant/has_extractor.md), runs -the shared matcher loop over `Input::Extractor` to obtain `Result`, and calls -`finalize_extract_result` on that result so the uninhabited remainder is discharged: - -```rust +#[cgp_provider] impl Computer for MatchWithHandlers where @@ -102,46 +177,78 @@ where Remainder: FinalizeExtract, { type Output = Output; - // compute: DispatchMatchers::compute(context, code, input.to_extractor()) - // .finalize_extract_result() + + fn compute(context: &Context, code: PhantomData, input: Input) -> Output { + DispatchMatchers::compute(context, code, input.to_extractor()).finalize_extract_result() + } } ``` -`DispatchMatchers` is the matcher loop every matcher shares. It is a type alias for +`DispatchMatchers` is the loop every matcher shares, an alias for [`PipeMonadic`](../monad/pipe_monadic.md) under the `OkMonadic` monad: ```rust pub type DispatchMatchers = PipeMonadic; ``` -Each handler in the list returns `Ok(output)` when it matches and `Err(remainder)` when it does not, -handing back the extractor with one more variant ruled out. Under `OkMonadic` the loop threads along the -`Err` branch and short-circuits on `Ok`, so it runs handler by handler, carrying the shrinking remainder -forward, until one returns `Ok`. `DispatchMatchers` is an implementation detail rather than a construct -a user names. +Each adapter returns `Ok(output)` when its variant matches and `Err(remainder)` when it does not, +handing back the extractor with that variant ruled out. Under `OkMonadic` the loop passes each `Err` +to the next adapter and stops at the first `Ok`. After the last adapter, `Remainder` has every +variant ruled out, and only then does it implement +[`FinalizeExtract`](../../traits/variant/finalize_extract.md), which turns the impossible `Err` into +any type. The `AsyncComputer` impl has the same bounds over `AsyncComputer`, and the borrowed forms +call `extractor_ref()` or `extractor_mut()` in place of `to_extractor()`. + +## Common Mistakes + +**A list that misses a variant does not compile.** Leaving out the `Rectangle` arm leaves the +extractor with a variant still present after the last adapter, so the leftover has no +`FinalizeExtract` impl, and the check reports it by the partial enum's markers: `IsVoid` for the +ruled-out `Circle`, `IsPresent` for the unmatched `Rectangle`: + +```text +error[E0277]: the trait bound `__PartialShape: FinalizeExtract` is not satisfied +``` + +**A matcher cannot fill a fallible slot directly.** It implements only `Computer` and +`AsyncComputer`, so wiring it to `HandlerComponent` fails, and rustc lists the two impls it has: + +```text +help: `MatchWithHandlers` implements trait `IsProviderFor` +... + | |_______________________________^ `IsProviderFor` +... + | |_______________________________^ `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +``` + +Lift it with the handler promotions instead, as `TryComputerComponent: Promote` and +`HandlerComponent: PromoteAsync>`, where `AreaMatcher` names the matcher type. ## Related constructs -- [`MatchWithValueHandlers`](match_with_value_handlers.md) — builds the handler list from the enum's own - variants instead of spelling it out. -- [`MatchFirstWithHandlers`](match_first_with_handlers.md) — the same matcher for the multi-argument - convention. -- [`ExtractFieldAndHandle`](extract_field_and_handle.md), [`HandleFieldValue`](handle_field_value.md) — - the adapters the list is built from. -- [`PipeMonadic`](../monad/pipe_monadic.md) — the `OkMonadic` pipeline the matcher loop is built on. -- [`HasExtractor`](../../traits/variant/has_extractor.md), [`FinalizeExtract`](../../traits/variant/finalize_extract.md), - [`FinalizeExtractResult`](../../traits/variant/finalize_extract_result.md) — the traits it stands on. +- [`MatchWithValueHandlers`](match_with_value_handlers.md) — builds the handler list from the enum's + own variants. +- [`MatchFirstWithHandlers`](match_first_with_handlers.md) — the same matcher for an input that + carries extra arguments. +- [`ExtractFieldAndHandle`](extract_field_and_handle.md), + [`HandleFieldValue`](handle_field_value.md), [`DowncastAndHandle`](downcast_and_handle.md) — the + adapters a list is built from. +- [`PipeMonadic`](../monad/pipe_monadic.md) — the pipeline the matcher loop is built on. +- [`HasExtractor`](../../traits/variant/has_extractor.md), + [`FinalizeExtract`](../../traits/variant/finalize_extract.md) — the traits it stands on. The ideas behind it: -- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to per-variant handlers. +- [Dispatching](/docs/concepts/dispatching) — routing an extensible-data value to per-variant + handlers. - [Extensible variants](/docs/concepts/extensible-variants) — the enum pattern the matchers serve. ## Source - [`providers/with_handlers/match_with_handlers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs), - with the borrowed forms in `match_with_handlers_ref.rs` and `match_with_handlers_mut.rs`, and the loop - alias in + with the borrowed forms in `match_with_handlers_ref.rs` and `match_with_handlers_mut.rs`, and the + loop alias in [`providers/dispatchers/dispatch_matchers.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-dispatch/src/providers/dispatchers/dispatch_matchers.rs). --- diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index 5cf80fab..63143b82 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -1,38 +1,33 @@ --- +title: 'MatchWithValueHandlers — match every variant' +description: 'The convenience matcher that builds the per-variant handler list from an enum''s own variants and passes each payload to one provider as a bare value.' sidebar_label: 'MatchWithValueHandlers' sidebar_position: 3 --- # `MatchWithValueHandlers` -Match an enum by building the per-variant handler list automatically, passing each payload as a bare -value. +Match an enum by building the per-variant handler list from its own variants, passing each payload +as a bare value. ## Overview -`MatchWithValueHandlers` is the convenience matcher for the common case. Rather than spelling -out one adapter per variant, it synthesizes the handler list from the input type's own field list, so -adding a variant needs no change to the wiring. Each matched payload reaches `Provider` as a bare value, -which is the form to use when the per-variant handler is an ordinary computer over the payload type, -such as one generated by [`#[cgp_computer]`](../../macros/cgp_computer.md). It runs on a **context**, -the type a method runs on. Like every CGP provider, it carries no runtime value. - -It is the value-passing sibling of [`MatchWithFieldHandlers`](match_with_field_handlers.md): the two -differ by exactly one [`HandleFieldValue`](handle_field_value.md) wrapper, which -`MatchWithValueHandlers` adds so `Provider` receives the payload rather than a tagged field. `Provider` -defaults to [`UseContext`](../use_context.md), so each payload routes back through the context's own -handler wiring unless another provider is named. - -The borrowed and multi-argument variants are `MatchWithValueHandlersRef` (over `&Input`), -`MatchWithValueHandlersMut` (over `&mut Input`), and the first-argument forms -`MatchFirstWithValueHandlers`, `MatchFirstWithValueHandlersRef`, and `MatchFirstWithValueHandlersMut`. +`MatchWithValueHandlers` is the matcher for the common case, where every variant's +payload goes to one provider. Rather than a spelled-out list, it builds one adapter per variant from +the input enum's own field list, so adding a variant needs no change to the wiring, and it hands +each payload to `Provider` as a bare value on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. That +makes it the form for payload handlers that are ordinary computers over the payload type, such as +ones from [`#[cgp_computer]`](../../macros/cgp_computer.md). `Provider` defaults to +[`UseContext`](../use_context.md), so each payload goes back through the context's own wiring. Like +every CGP provider, it carries no runtime value. ## Usage It is in the prelude, so `use cgp::prelude::*;` is enough. It takes one optional type parameter, the -per-variant provider, and is most often wired by input type with the -[`open` statement](../../macros/delegate_components.md#choosing-a-provider-per-type-the-open-statement), -so it is selected when the input is a given enum: +per-variant provider. With the default `UseContext`, it is wired by input type with the [`open` +statement](../../macros/delegate_components.md#choosing-a-provider-per-type-the-open-statement), +beside the entries that answer each payload type: ```rust delegate_components! { @@ -46,48 +41,212 @@ delegate_components! { ``` Each key has one segment per type parameter of `CanCompute`, and the generic first -segment matches any code, so the second selects by the input type. A `Circle` input is handled -directly by `ComputeArea`, while a `Shape` input is handled by `MatchWithValueHandlers`, which -synthesizes an adapter for each variant and routes each payload back through the context's own -`ComputerComponent`, so the `Circle` and `Rectangle` payloads reach `ComputeArea` after all. Older -code wires the same dispatch as a [`UseInputDelegate`](../handler/use_input_delegate.md) table. +segment matches any code, so the second selects by the input type. A named provider needs no +per-type entries: `ComputerComponent: MatchWithValueHandlers` sends every payload +straight to `ComputeArea`. + +Two borrowed forms match without moving the value, and each answers two components. +`MatchWithValueHandlersRef` serves `ComputerComponent` over `&Input` with a provider over +borrowed payloads, and `ComputerRefComponent` over `Input` with a +[`ComputerRef`](../../components/handler/computer_ref.md) provider over the payloads: + +```rust +delegate_components! { + App { + ComputerComponent: MatchWithValueHandlersRef, + ComputerRefComponent: MatchWithValueHandlersRef, + } +} + +check_components! { + App { + ComputerComponent: <'a> ((), &'a Shape), + ComputerRefComponent: ((), Shape), + } +} +``` + +`MatchWithValueHandlersMut` serves `ComputerComponent` the same way over `&mut Input`, +with a provider over mutable payloads that can change them in place. Its `…Ref` entries cannot +resolve, because `PromoteRef` lends only a shared borrow. The multi-argument forms +`MatchFirstWithValueHandlers`, `MatchFirstWithValueHandlersRef`, and +`MatchFirstWithValueHandlersMut` are on +[`MatchFirstWithHandlers`](match_first_with_handlers.md#when-to-use-it). + +## Examples + +A context that computes each shape directly, and a `Shape` enum by matching it: + +```rust +use cgp::prelude::*; +use cgp::extra::handler::CanCompute; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +#[cgp_new_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } +} + +#[cgp_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +pub struct App; + +delegate_components! { + App { + open ComputerComponent; + + @ComputerComponent. Code.[Circle, Rectangle]: ComputeArea, + @ComputerComponent. Code.Shape: MatchWithValueHandlers, + } +} + +check_components! { + App { + ComputerComponent: [((), Circle), ((), Rectangle), ((), Shape)], + } +} + +pub fn demo() { + let code = PhantomData::<()>; + + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + assert_eq!(App.compute(code, rectangle), 12.0); + + let circle = App.compute(code, Shape::Circle(Circle { radius: 1.0 })); + assert!((circle - core::f64::consts::PI).abs() < 1e-9); +} +``` + +For a `Shape`, the matcher extracts the payload and asks `App` again, through `UseContext`, for the +payload's type, which reaches `ComputeArea`. `App` is an +[environmental context](/docs/reference/glossary#environmental-context), and the component is +**[parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: it acts on the +input. Existing code writes the same table as a +[`UseInputDelegate`](../handler/use_input_delegate.md) table. ## When to use it -**Reach for `MatchWithValueHandlers` when every variant of an enum is handled the same way and each -handler wants the bare payload.** This is the usual case, and far shorter than spelling out the list -with [`MatchWithHandlers`](match_with_handlers.md). Reach for -[`MatchWithFieldHandlers`](match_with_field_handlers.md) when a handler needs the variant's tag attached -to its payload, and for [`MatchWithHandlers`](match_with_handlers.md) when the handlers cannot be -generated uniformly from the field list. +**Reach for `MatchWithValueHandlers` when every variant's payload goes to the same provider as a +bare value.** This is the usual case, and shorter than spelling out the list with +[`MatchWithHandlers`](match_with_handlers.md). Reach for +[`MatchWithFieldHandlers`](match_with_field_handlers.md) when the handler needs the variant's name, +and for `MatchWithHandlers` when different variants need providers the field list cannot generate. ## Under the hood `MatchWithValueHandlers` is a type alias over -[`UseInputDelegate`](../handler/use_input_delegate.md) that dispatches on the input type and, for each -input, synthesizes the per-variant handler list from that input's [`HasFields`](../../traits/shape/has_fields.md): +[`UseInputDelegate`](../handler/use_input_delegate.md), which keys on the input type and, for each +enum, maps it to [`MatchWithHandlers`](match_with_handlers.md) over a list built from the enum's +[`HasFields`](../../traits/shape/has_fields.md): ```rust pub type MatchWithValueHandlers = UseInputDelegate>>; + +delegate_components! { + >, Provider> + new MatchWithFieldHandlersInputs { + Input: MatchWithHandlers + } +} +``` + +Wrapping `Provider` in [`HandleFieldValue`](handle_field_value.md) is its one difference from +`MatchWithFieldHandlers`, and it makes each payload arrive bare. The list is built by the +`HasFieldHandlers` machinery described on +[`MatchWithFieldHandlers`](match_with_field_handlers.md#under-the-hood). + +The borrowed forms are structs with a delegation table rather than aliases. The owned-input entries +key a `UseInputDelegate` on `&'a Input` or `&'a mut Input` and reach `MatchWithHandlersRef` or +`MatchWithHandlersMut`; the `…Ref` entries wrap that in [`PromoteRef`](../handler/promote_ref.md), +which borrows the input and hands each borrowed payload to the provider's `…Ref` impl: + +```rust +delegate_components! { + + MatchWithValueHandlersRef { + [ + ComputerComponent, + TryComputerComponent, + AsyncComputerComponent, + HandlerComponent, + ]: + UseInputDelegate>>, + [ + ComputerRefComponent, + TryComputerRefComponent, + AsyncComputerRefComponent, + HandlerRefComponent, + ]: + PromoteRef>>>>, + } +} +``` + +## Common Mistakes + +**The input must be an enum.** The list is built by walking a sum-type field list, so a struct, +whose field list is a product, has no list and no extractor. Wiring a `Scene` struct fails with: + +```text +error[E0277]: the trait bound `MatchWithHandlers<_>: cgp::prelude::Computer` is not satisfied +``` + +Handle a struct's fields one by one instead, or build a record with the +[builders](build_with_handlers.md). + +**The borrowed forms route fallible components they cannot answer.** Their tables list +`TryComputerComponent`, `HandlerComponent`, and the fallible `…Ref` components, but the borrowed +matchers behind them implement only `Computer` and `AsyncComputer`, so wiring +`HandlerComponent: MatchWithValueHandlersRef` fails at the check: + +```text + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `IsProviderFor` ``` -Wrapping `Provider` in [`HandleFieldValue`](handle_field_value.md) is the one difference from -[`MatchWithFieldHandlers`](match_with_field_handlers.md), and it makes each payload arrive as a -bare value. The list itself is assembled by the `HasFieldHandlers` machinery described on -[`MatchWithFieldHandlers`](match_with_field_handlers.md#under-the-hood). The borrowed variants -additionally wire the `…RefComponent` handler traits through [`PromoteRef`](../handler/promote_ref.md), -so one struct serves both the by-value-of-reference and the by-reference interfaces. +The owned `MatchWithValueHandlers` has the same limit. Wire the matcher to `ComputerComponent` or +`AsyncComputerComponent`, and lift it with a promotion as +[`MatchWithHandlers`](match_with_handlers.md#common-mistakes) shows. ## Related constructs -- [`MatchWithFieldHandlers`](match_with_field_handlers.md) — the sibling that keeps the variant tag on - the payload; the two differ by one `HandleFieldValue` wrapper. -- [`MatchWithHandlers`](match_with_handlers.md) — the explicit form, when the list cannot be generated. -- [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher this alias is built on. -- [`HandleFieldValue`](handle_field_value.md), [`UseContext`](../use_context.md) — the wrapper it adds - and the default per-variant provider. -- [`HasFields`](../../traits/shape/has_fields.md) — the field list the handler list is synthesized from. +- [`MatchWithFieldHandlers`](match_with_field_handlers.md) — the sibling that keeps the variant tag + on the payload. +- [`MatchWithHandlers`](match_with_handlers.md) — the matcher this builds its list for. +- [`UseInputDelegate`](../handler/use_input_delegate.md) — the input dispatcher this alias is built + on. +- [`HandleFieldValue`](handle_field_value.md), [`UseContext`](../use_context.md) — the wrapper it + adds and the default per-variant provider. +- [`#[cgp_auto_dispatch]`](../../macros/cgp_auto_dispatch.md) — generates trait impls for an enum + on top of these matchers. The ideas behind it: diff --git a/example-code/README.md b/example-code/README.md index 96759a99..b868c9f7 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -36,7 +36,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, every `macros/` page and every `attributes/` page that shows code, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, every `macros/` page and every `attributes/` page that shows code, all of `derives/`, the `traits/` pages that show checkable code, all of `providers/` that shows code (the singletons, and all of `error/`, `handler/`, `monad/`, and `dispatch/`; `use_field_ref` shows its example on its alias page), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | diff --git a/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.rs b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.rs new file mode 100644 index 00000000..55919ba5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.rs @@ -0,0 +1,50 @@ +use cgp::extra::dispatch::BuildAndMergeOutputs; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct App { + pub db_url: String, + pub user_agent: String, +} + +#[derive(CgpData)] +pub struct DatabaseConfig { + pub db_url: String, +} + +#[derive(CgpData)] +pub struct HttpConfig { + pub user_agent: String, +} + +#[cgp_producer] +fn build_database_config() -> DatabaseConfig { + DatabaseConfig { + db_url: "sqlite://app.db".to_owned(), + } +} + +#[cgp_producer] +fn build_http_config() -> HttpConfig { + HttpConfig { + user_agent: "reader/1.0".to_owned(), + } +} + +pub struct AppBuilder; + +// The table routes `ComputerRefComponent`, but `BuildWithHandlers` has no `ComputerRef` impl. +delegate_components! { + AppBuilder { + ComputerRefComponent: + BuildAndMergeOutputs, + } +} + +check_components! { + AppBuilder { + ComputerRefComponent: ((), ()), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr new file mode 100644 index 00000000..0d77835f --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr @@ -0,0 +1,47 @@ +error[E0277]: the trait bound `BuildWithHandlers, Cons, Nil>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.rs:46:9 + | +46 | ComputerRefComponent: ((), ()), + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `BuildWithHandlers, Cons, Nil>>>` +help: `BuildWithHandlers` implements trait `IsProviderFor` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/with_handlers/build_with_handlers.rs:10:1 + | +10 | / impl Computer +11 | | for BuildWithHandlers +12 | | where +13 | | Output: HasBuilder, +14 | | PipeHandlers: Computer, +15 | | Res: FinalizeBuild, + | |________________________________________^ `IsProviderFor` +... +25 | / impl TryComputer +26 | | for BuildWithHandlers +27 | | where +28 | | Context: HasErrorType, +29 | | Output: HasBuilder, +30 | | PipeHandlers: TryComputer, +31 | | Res: FinalizeBuild, + | |________________________________________^ `IsProviderFor` +... +45 | / impl Handler +46 | | for BuildWithHandlers +47 | | where +48 | | Context: HasErrorType, +49 | | Output: HasBuilder, +50 | | PipeHandlers: Handler, +51 | | Res: FinalizeBuild, + | |________________________________________^ `IsProviderFor` + = note: required for `BuildAndMergeOutputs>>` to implement `IsProviderFor` + = note: required for `AppBuilder` to implement `CanUseComponent` +note: required by a bound in `__CheckAppBuilder` + --> tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.rs:44:1 + | +44 | / check_components! { +45 | | AppBuilder { +46 | | ComputerRefComponent: ((), ()), +47 | | } +48 | | } + | |_^ required by this bound in `__CheckAppBuilder` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs b/example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs new file mode 100644 index 00000000..a9664420 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs @@ -0,0 +1,55 @@ +use cgp::extra::dispatch::{BuildAndMerge, BuildWithHandlers}; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct App { + pub db_url: String, + pub max_connections: u32, + pub user_agent: String, +} + +#[derive(CgpData)] +pub struct DatabaseConfig { + pub db_url: String, + pub max_connections: u32, +} + +#[derive(HasField)] +pub struct AppBuilder { + pub db_path: String, +} + +#[cgp_impl(new BuildDatabaseConfig)] +impl Computer { + type Output = DatabaseConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] db_path: &str, + ) -> DatabaseConfig { + DatabaseConfig { + db_url: format!("sqlite://{db_path}"), + max_connections: 4, + } + } +} + +// No step sets `user_agent`, so the builder never reaches the all-present state. +delegate_components! { + AppBuilder { + ComputerComponent: + BuildWithHandlers, + ]>, + } +} + +check_components! { + AppBuilder { + ComputerComponent: ((), ()), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.stderr b/example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.stderr new file mode 100644 index 00000000..2ea05475 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `__PartialApp: FinalizeBuild` is not satisfied + --> tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs:51:9 + | +51 | ComputerComponent: ((), ()), + | ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `FinalizeBuild` is not implemented for `__PartialApp` + --> tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs:5:1 + | + 5 | pub struct App { + | ^^^^^^^^^^^^^^ +help: the trait `FinalizeBuild` is implemented for `__PartialApp` + --> tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs:5:12 + | + 5 | pub struct App { + | ^^^ + = note: required for `BuildWithHandlers, Nil>>` to implement `IsProviderFor` + = note: required for `AppBuilder` to implement `CanUseComponent` +note: required by a bound in `__CheckAppBuilder` + --> tests/compile_fail/reference/providers/build_with_handlers_common_mistakes_missing_field.rs:49:1 + | +49 | / check_components! { +50 | | AppBuilder { +51 | | ComputerComponent: ((), ()), +52 | | } +53 | | } + | |_^ required by this bound in `__CheckAppBuilder` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.rs b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.rs new file mode 100644 index 00000000..cb635a20 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.rs @@ -0,0 +1,58 @@ +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; +use cgp::prelude::*; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +#[cgp_new_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } +} + +#[cgp_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +pub struct App; + +// A matcher implements only `Computer` and `AsyncComputer`. +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + HandlerComponent: + MatchWithHandlers>, + ExtractFieldAndHandle>, + ]>, + } +} + +check_components! { + App { + HandlerComponent: ((), Shape), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr new file mode 100644 index 00000000..6dfcf506 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr @@ -0,0 +1,38 @@ +error[E0277]: the trait bound `MatchWithHandlers>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.rs:54:9 + | +54 | HandlerComponent: ((), Shape), + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `MatchWithHandlers>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` +help: `MatchWithHandlers` implements trait `IsProviderFor` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 + | +12 | / impl Computer +13 | | for MatchWithHandlers +14 | | where +15 | | Input: HasExtractor, +16 | | DispatchMatchers: +17 | | Computer>, +18 | | Remainder: FinalizeExtract, + | |_______________________________^ `IsProviderFor` +... +28 | / impl AsyncComputer +29 | | for MatchWithHandlers +30 | | where +31 | | Input: HasExtractor, +32 | | DispatchMatchers: +33 | | AsyncComputer>, +34 | | Remainder: FinalizeExtract, + | |_______________________________^ `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.rs:52:1 + | +52 | / check_components! { +53 | | App { +54 | | HandlerComponent: ((), Shape), +55 | | } +56 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs new file mode 100644 index 00000000..6b539271 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs @@ -0,0 +1,55 @@ +use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; +use cgp::prelude::*; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +#[cgp_new_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } +} + +#[cgp_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +pub struct App; + +// The list has no arm for `Rectangle`, so the remainder is still inhabited. +delegate_components! { + App { + ComputerComponent: + MatchWithHandlers>, + ]>, + } +} + +check_components! { + App { + ComputerComponent: ((), Shape), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.stderr b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.stderr new file mode 100644 index 00000000..5cc066d0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `__PartialShape: FinalizeExtract` is not satisfied + --> tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs:51:9 + | +51 | ComputerComponent: ((), Shape), + | ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `FinalizeExtract` is not implemented for `__PartialShape` + --> tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs:14:1 + | +14 | pub enum Shape { + | ^^^^^^^^^^^^^^ +help: the trait `FinalizeExtract` is implemented for `__PartialShape` + --> tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs:14:10 + | +14 | pub enum Shape { + | ^^^^^ + = note: required for `MatchWithHandlers>>>>>>, HandleFieldValue>, Nil>>` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_missing_arm.rs:49:1 + | +49 | / check_components! { +50 | | App { +51 | | ComputerComponent: ((), Shape), +52 | | } +53 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs new file mode 100644 index 00000000..36801771 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs @@ -0,0 +1,53 @@ +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::prelude::*; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +#[cgp_new_provider] +impl<'a, Context, Code> Computer for ComputeAreaOfRef { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: &'a Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } +} + +#[cgp_provider] +impl<'a, Context, Code> Computer for ComputeAreaOfRef { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: &'a Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +pub struct App; + +// The table routes `HandlerComponent`, but the borrowed matcher behind it has no `Handler` impl. +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + HandlerComponent: MatchWithValueHandlersRef, + } +} + +check_components! { + App { + HandlerComponent: <'a> ((), &'a Shape), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr new file mode 100644 index 00000000..265c0bfe --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr @@ -0,0 +1,74 @@ +error[E0277]: the trait bound `MatchWithHandlersRef>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs:49:9 + | +49 | HandlerComponent: <'a> ((), &'a Shape), + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `MatchWithHandlersRef>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` +help: `MatchWithHandlersRef` implements trait `IsProviderFor` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 + | +12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer +13 | | for MatchWithHandlersRef +14 | | where +15 | | Input: HasExtractorRef, +16 | | DispatchMatchers: +17 | | Computer, Output = Result>, +18 | | Remainder: FinalizeExtract, + | |_______________________________^ `IsProviderFor` +... +28 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> AsyncComputer +29 | | for MatchWithHandlersRef +30 | | where +31 | | Input: HasExtractorRef, +32 | | DispatchMatchers: +33 | | AsyncComputer, Output = Result>, +34 | | Remainder: FinalizeExtract, + | |_______________________________^ `IsProviderFor` + = note: required for `UseInputDelegate>>` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs:47:1 + | +47 | / check_components! { +48 | | App { +49 | | HandlerComponent: <'a> ((), &'a Shape), +50 | | } +51 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `MatchWithHandlersRef>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>: DelegateComponent` is not satisfied + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs:49:9 + | +49 | HandlerComponent: <'a> ((), &'a Shape), + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `DelegateComponent` is not implemented for `MatchWithHandlersRef>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` + = help: the following other types implement trait `DelegateComponent`: + App + BuildAndMergeOutputs + MatchWithFieldHandlersRef + MatchWithValueHandlersMut + PipeMonadic + PromoteAsyncComputer + PromoteComputer + PromoteHandler + and $N others + = note: required for `MatchWithHandlersRef>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` to implement `Handler` + = note: required for `UseInputDelegate>>` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.rs:47:1 + | +47 | / check_components! { +48 | | App { +49 | | HandlerComponent: <'a> ((), &'a Shape), +50 | | } +51 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs new file mode 100644 index 00000000..23360f76 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs @@ -0,0 +1,51 @@ +use cgp::prelude::*; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_new_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } +} + +#[cgp_provider] +impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +// A struct, not an enum: its field list is a product, which the matcher cannot walk. +#[derive(CgpData)] +pub struct Scene { + pub circle: Circle, + pub rectangle: Rectangle, +} + +pub struct App; + +delegate_components! { + App { + ComputerComponent: MatchWithValueHandlers, + } +} + +check_components! { + App { + ComputerComponent: ((), Scene), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr new file mode 100644 index 00000000..c8fe7f64 --- /dev/null +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr @@ -0,0 +1,88 @@ +error[E0277]: the trait bound `MatchWithHandlers<_>: cgp::prelude::Computer` is not satisfied + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:47:9 + | +47 | ComputerComponent: ((), Scene), + | ^^^^^^^^^^^^^^^^^ the trait `cgp::prelude::Computer` is not implemented for `MatchWithHandlers<_>` + | +help: the trait `cgp::prelude::Computer` is conditionally implemented for `MatchWithHandlers` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 + | +12 | / impl Computer +13 | | for MatchWithHandlers +14 | | where +15 | | Input: HasExtractor, + | | ------------ unsatisfied requirement introduced here: `Scene: HasExtractor` +16 | | DispatchMatchers: +17 | | Computer>, +18 | | Remainder: FinalizeExtract, + | |_______________________________^ + = note: required for `UseInputDelegate>>` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:45:1 + | +45 | / check_components! { +46 | | App { +47 | | ComputerComponent: ((), Scene), +48 | | } +49 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Cons>>>>>>, Circle>, Cons>>>>>>>>>, Rectangle>, Nil>>: dispatch::providers::matchers::to_field_handlers::ToFieldHandlers>>` is not satisfied + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:47:9 + | +47 | ComputerComponent: ((), Scene), + | ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `dispatch::providers::matchers::to_field_handlers::ToFieldHandlers>>` is not implemented for `Cons>>>>>>, Circle>, Cons>>>>>>>>>, Rectangle>, Nil>>` +help: the following other types implement trait `dispatch::providers::matchers::to_field_handlers::ToFieldHandlers` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/matchers/to_field_handlers.rs:25:1 + | +25 | / impl ToFieldHandlers for Either, RestFields> +26 | | where +27 | | M: MapFieldHandler, +28 | | RestFields: ToFieldHandlers, + | |___________________________________^ `Either, RestFields>` implements `dispatch::providers::matchers::to_field_handlers::ToFieldHandlers` +... +33 | impl ToFieldHandlers for Void { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Void` implements `dispatch::providers::matchers::to_field_handlers::ToFieldHandlers` + = note: required for `Scene` to implement `dispatch::providers::matchers::to_field_handlers::HasFieldHandlers>>` + = note: required for `UseInputDelegate>>` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:45:1 + | +45 | / check_components! { +46 | | App { +47 | | ComputerComponent: ((), Scene), +48 | | } +49 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Scene: HasExtractor` is not satisfied + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:47:9 + | +47 | ComputerComponent: ((), Scene), + | ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasExtractor` is not implemented for `Scene` + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:32:1 + | +32 | pub struct Scene { + | ^^^^^^^^^^^^^^^^ + = note: required for `MatchWithHandlers<_>` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `UseInputDelegate>>` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.rs:45:1 + | +45 | / check_components! { +46 | | App { +47 | | ComputerComponent: ((), Scene), +48 | | } +49 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/providers/dispatch/build_and_merge.rs b/example-code/tests/reference/providers/dispatch/build_and_merge.rs index e7301cd1..563df8b4 100644 --- a/example-code/tests/reference/providers/dispatch/build_and_merge.rs +++ b/example-code/tests/reference/providers/dispatch/build_and_merge.rs @@ -1,77 +1,105 @@ //! Code from `docs/reference/providers/dispatch/build_and_merge.md` — `BuildAndMerge`. //! -//! Pins that `BuildAndMerge` copies a whole sub-record's shared fields into the builder at -//! once, beside a single-field `BuildAndSetField`, under `BuildWithHandlers`. +//! Pins the Examples program: two `BuildAndMerge` steps copy the fields of two sub-records into one +//! `App` builder, each sub-record built by a provider that reads its configuration from the context. /// ## Examples pub mod examples { - use core::marker::PhantomData; - - use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; - use cgp::extra::handler::ComputerComponent; + use cgp::extra::dispatch::{BuildAndMerge, BuildWithHandlers}; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; - #[derive(Debug, Eq, PartialEq, CgpData)] - pub struct FooBarBaz { - pub foo: u64, - pub bar: String, - pub baz: bool, + #[derive(Debug, PartialEq, CgpData)] + pub struct App { + pub db_url: String, + pub max_connections: u32, + pub user_agent: String, } #[derive(CgpData)] - pub struct FooBar { - pub foo: u64, - pub bar: String, + pub struct DatabaseConfig { + pub db_url: String, + pub max_connections: u32, + } + + #[derive(HasField)] + pub struct AppBuilder { + pub db_path: String, + pub agent_name: String, } - #[cgp_producer] - fn build_foo_bar() -> FooBar { - FooBar { - foo: 1, - bar: "bar".to_owned(), + #[cgp_impl(new BuildDatabaseConfig)] + impl Computer { + type Output = DatabaseConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] db_path: &str, + ) -> DatabaseConfig { + DatabaseConfig { + db_url: format!("sqlite://{db_path}"), + max_connections: 4, + } } } - #[cgp_producer(BuildBaz)] - fn build_baz() -> bool { - true + #[derive(CgpData)] + pub struct HttpConfig { + pub user_agent: String, } - // `BuildAndMerge` copies `foo` and `bar`; `BuildAndSetField` sets `baz`. - pub type Handlers = - Product![BuildAndMerge, BuildAndSetField]; + #[cgp_impl(new BuildHttpConfig)] + impl Computer { + type Output = HttpConfig; - pub struct App; + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] agent_name: &str, + ) -> HttpConfig { + HttpConfig { + user_agent: format!("{agent_name}/1.0"), + } + } + } delegate_components! { - App { - ComputerComponent: BuildWithHandlers, + AppBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndMerge, + ]>, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), ()), - } + check_components! { + AppBuilder { + ComputerComponent: ((), ()), } } - #[test] - fn test_build_and_merge() { - use cgp::extra::handler::CanCompute; - - let app = App; - let code = PhantomData::<()>; + pub fn demo() { + let builder = AppBuilder { + db_path: "app.db".to_owned(), + agent_name: "reader".to_owned(), + }; assert_eq!( - app.compute(code, ()), - FooBarBaz { - foo: 1, - bar: "bar".to_owned(), - baz: true, + builder.compute(PhantomData::<()>, ()), + App { + db_url: "sqlite://app.db".to_owned(), + max_connections: 4, + user_agent: "reader/1.0".to_owned(), }, ); } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/providers/dispatch/build_and_merge_outputs.rs b/example-code/tests/reference/providers/dispatch/build_and_merge_outputs.rs index 055afdb5..d3fbd414 100644 --- a/example-code/tests/reference/providers/dispatch/build_and_merge_outputs.rs +++ b/example-code/tests/reference/providers/dispatch/build_and_merge_outputs.rs @@ -1,80 +1,103 @@ //! Code from `docs/reference/providers/dispatch/build_and_merge_outputs.md` — `BuildAndMergeOutputs`. //! -//! Pins that `BuildAndMergeOutputs` wraps each plain field-producing provider in a -//! merge step, so a list of sub-record producers assembles the whole record without the caller writing -//! the merges. +//! Pins the Examples program: the same two sub-record providers as the `BuildAndMerge` page, listed +//! bare, with `BuildAndMergeOutputs` adding the merge step to each. Wiring a `…Ref` component to it +//! is a trybuild fixture. /// ## Examples pub mod examples { - use core::marker::PhantomData; - use cgp::extra::dispatch::BuildAndMergeOutputs; - use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; - #[derive(Debug, Eq, PartialEq, CgpData)] + #[derive(Debug, PartialEq, CgpData)] pub struct App { - pub foo: u64, - pub bar: String, - pub baz: bool, + pub db_url: String, + pub max_connections: u32, + pub user_agent: String, } #[derive(CgpData)] - pub struct FooBar { - pub foo: u64, - pub bar: String, + pub struct DatabaseConfig { + pub db_url: String, + pub max_connections: u32, } - #[derive(CgpData)] - pub struct BazPart { - pub baz: bool, + #[derive(HasField)] + pub struct AppBuilder { + pub db_path: String, + pub agent_name: String, } - #[cgp_producer] - fn build_foo_bar() -> FooBar { - FooBar { - foo: 1, - bar: "bar".to_owned(), + #[cgp_impl(new BuildDatabaseConfig)] + impl Computer { + type Output = DatabaseConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] db_path: &str, + ) -> DatabaseConfig { + DatabaseConfig { + db_url: format!("sqlite://{db_path}"), + max_connections: 4, + } } } - #[cgp_producer] - fn build_baz_part() -> BazPart { - BazPart { baz: true } + #[derive(CgpData)] + pub struct HttpConfig { + pub user_agent: String, } - pub struct AppBuilder; + #[cgp_impl(new BuildHttpConfig)] + impl Computer { + type Output = HttpConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] agent_name: &str, + ) -> HttpConfig { + HttpConfig { + user_agent: format!("{agent_name}/1.0"), + } + } + } delegate_components! { AppBuilder { ComputerComponent: - BuildAndMergeOutputs, + BuildAndMergeOutputs, } } - mod check_builder { - use super::*; - check_components! { - AppBuilder { - ComputerComponent: ((), ()), - } + check_components! { + AppBuilder { + ComputerComponent: ((), ()), } } - #[test] - fn test_build_and_merge_outputs() { - use cgp::extra::handler::CanCompute; - - let builder = AppBuilder; - let code = PhantomData::<()>; + pub fn demo() { + let builder = AppBuilder { + db_path: "app.db".to_owned(), + agent_name: "reader".to_owned(), + }; assert_eq!( - builder.compute(code, ()), + builder.compute(PhantomData::<()>, ()), App { - foo: 1, - bar: "bar".to_owned(), - baz: true, + db_url: "sqlite://app.db".to_owned(), + max_connections: 4, + user_agent: "reader/1.0".to_owned(), }, ); } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/providers/dispatch/build_and_set_field.rs b/example-code/tests/reference/providers/dispatch/build_and_set_field.rs index bb208315..87704715 100644 --- a/example-code/tests/reference/providers/dispatch/build_and_set_field.rs +++ b/example-code/tests/reference/providers/dispatch/build_and_set_field.rs @@ -1,67 +1,82 @@ //! Code from `docs/reference/providers/dispatch/build_and_set_field.md` — `BuildAndSetField`. //! -//! Pins that `BuildAndSetField` computes one named field and sets it on the builder, and -//! that a `Product!` of them assembles a whole record through `BuildWithHandlers`. +//! Pins the Examples program: the second step reads the field the first step set, since each +//! provider receives a reference to the partial record built so far. /// ## Examples pub mod examples { - use core::marker::PhantomData; - use cgp::extra::dispatch::{BuildAndSetField, BuildWithHandlers}; - use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; - #[derive(Debug, Eq, PartialEq, CgpData)] - pub struct Rectangle { - pub width: u64, - pub height: u64, + #[derive(Debug, PartialEq, CgpData)] + pub struct PoolConfig { + pub max_connections: u32, + pub max_idle: u32, } - #[cgp_producer(ComputeWidth)] - fn compute_width() -> u64 { - 3 + #[derive(HasField)] + pub struct PoolBuilder { + pub connections: u32, } - #[cgp_producer(ComputeHeight)] - fn compute_height() -> u64 { - 4 + #[cgp_impl(new BuildMaxConnections)] + impl Computer { + type Output = u32; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] connections: u32, + ) -> u32 { + connections + } } - pub type Handlers = Product![ - BuildAndSetField, - BuildAndSetField, - ]; + // Reads `max_connections` from the partial record, which the step before it has set. + #[cgp_new_provider] + impl<'a, Context, Code, Builder> Computer for BuildMaxIdle + where + Builder: HasField, + { + type Output = u32; - pub struct App; + fn compute(_context: &Context, _code: PhantomData, builder: &'a Builder) -> u32 { + builder.get_field(PhantomData) / 2 + } + } delegate_components! { - App { - ComputerComponent: BuildWithHandlers, + PoolBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndSetField, + ]>, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), ()), - } + check_components! { + PoolBuilder { + ComputerComponent: ((), ()), } } - #[test] - fn test_build_and_set_field() { - use cgp::extra::handler::CanCompute; - - let app = App; - let code = PhantomData::<()>; + pub fn demo() { + let builder = PoolBuilder { connections: 8 }; assert_eq!( - app.compute(code, ()), - Rectangle { - width: 3, - height: 4, + builder.compute(PhantomData::<()>, ()), + PoolConfig { + max_connections: 8, + max_idle: 4, }, ); } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/providers/dispatch/build_with_handlers.rs b/example-code/tests/reference/providers/dispatch/build_with_handlers.rs index 8626084b..f43d1a0b 100644 --- a/example-code/tests/reference/providers/dispatch/build_with_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/build_with_handlers.rs @@ -1,77 +1,99 @@ //! Code from `docs/reference/providers/dispatch/build_with_handlers.md` — `BuildWithHandlers`. //! -//! Pins that `BuildWithHandlers` assembles a record from a `Product!` of builder adapters, starting -//! from an empty builder and finalizing the all-present result. Dropping a handler for some field would -//! fail to compile at the finalize step. +//! Pins the Examples program: a builder context assembles an `App` from a merged sub-record and one +//! computed field, each provider reading the configuration it needs from the context. A list that +//! leaves a field unset is a trybuild fixture. /// ## Examples pub mod examples { - use core::marker::PhantomData; - use cgp::extra::dispatch::{BuildAndMerge, BuildAndSetField, BuildWithHandlers}; - use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; - #[derive(Debug, Eq, PartialEq, CgpData)] - pub struct FooBarBaz { - pub foo: u64, - pub bar: String, - pub baz: bool, + #[derive(Debug, PartialEq, CgpData)] + pub struct App { + pub db_url: String, + pub max_connections: u32, + pub user_agent: String, } #[derive(CgpData)] - pub struct FooBar { - pub foo: u64, - pub bar: String, + pub struct DatabaseConfig { + pub db_url: String, + pub max_connections: u32, } - #[cgp_producer] - fn build_foo_bar() -> FooBar { - FooBar { - foo: 1, - bar: "bar".to_owned(), - } + #[derive(HasField)] + pub struct AppBuilder { + pub db_path: String, + pub agent_name: String, } - #[cgp_producer(BuildBaz)] - fn build_baz() -> bool { - true + #[cgp_impl(new BuildDatabaseConfig)] + impl Computer { + type Output = DatabaseConfig; + + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] db_path: &str, + ) -> DatabaseConfig { + DatabaseConfig { + db_url: format!("sqlite://{db_path}"), + max_connections: 4, + } + } } - pub type Handlers = - Product![BuildAndMerge, BuildAndSetField]; + #[cgp_impl(new BuildUserAgent)] + impl Computer { + type Output = String; - pub struct App; + fn compute( + &self, + _code: PhantomData, + _input: Input, + #[implicit] agent_name: &str, + ) -> String { + format!("{agent_name}/1.0") + } + } delegate_components! { - App { - ComputerComponent: BuildWithHandlers, + AppBuilder { + ComputerComponent: + BuildWithHandlers, + BuildAndSetField, + ]>, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), ()), - } + check_components! { + AppBuilder { + ComputerComponent: ((), ()), } } - #[test] - fn test_build_with_handlers() { - use cgp::extra::handler::CanCompute; - - let app = App; - let code = PhantomData::<()>; + pub fn demo() { + let builder = AppBuilder { + db_path: "app.db".to_owned(), + agent_name: "reader".to_owned(), + }; assert_eq!( - app.compute(code, ()), - FooBarBaz { - foo: 1, - bar: "bar".to_owned(), - baz: true, + builder.compute(PhantomData::<()>, ()), + App { + db_url: "sqlite://app.db".to_owned(), + max_connections: 4, + user_agent: "reader/1.0".to_owned(), }, ); } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/providers/dispatch/downcast_and_handle.rs b/example-code/tests/reference/providers/dispatch/downcast_and_handle.rs index 2bf26e71..2e963ed9 100644 --- a/example-code/tests/reference/providers/dispatch/downcast_and_handle.rs +++ b/example-code/tests/reference/providers/dispatch/downcast_and_handle.rs @@ -1,72 +1,84 @@ //! Code from `docs/reference/providers/dispatch/downcast_and_handle.md` — `DowncastAndHandle`. //! -//! Pins that `DowncastAndHandle` matches a group of variants at once by narrowing to a -//! smaller enum, beside a single-variant `ExtractFieldAndHandle`, inside one `MatchWithHandlers` list. +//! Pins the Examples program: `DowncastAndHandle` narrows a `Shape` to the smaller `Quadrilateral` +//! enum and hands both of its variants to one handler, beside a single-variant arm for `Circle`. /// ## Examples pub mod examples { - use core::marker::PhantomData; - use cgp::extra::dispatch::{ DowncastAndHandle, ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers, }; - use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; - #[derive(Debug, Eq, PartialEq, CgpData)] - pub enum FooBarBaz { - Foo(u64), - Bar(String), - Baz(bool), + pub struct Circle { + pub radius: f64, } - #[derive(Debug, Eq, PartialEq, CgpData)] - pub enum FooBar { - Foo(u64), - Bar(String), + pub struct Square { + pub side: f64, } - #[cgp_computer] - fn show_foo_bar(input: FooBar) -> String { - format!("FooBar::{input:?}") + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Square(Square), + Rectangle(Rectangle), + } + + #[derive(CgpData)] + pub enum Quadrilateral { + Square(Square), + Rectangle(Rectangle), } #[cgp_computer] - fn show_baz(input: bool) -> String { - format!("Baz({input:?})") + pub fn count_circle_corners(_circle: Circle) -> u32 { + 0 } - // `Foo` and `Bar` are handled together by narrowing to `FooBar`; `Baz` is matched on its own. - pub type Computers = Product![ - ExtractFieldAndHandle>, - DowncastAndHandle, - ]; + #[cgp_computer] + pub fn count_quadrilateral_corners(_shape: Quadrilateral) -> u32 { + 4 + } pub struct App; delegate_components! { App { - ComputerComponent: MatchWithHandlers, + ComputerComponent: + MatchWithHandlers>, + DowncastAndHandle, + ]>, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), FooBarBaz), - } + check_components! { + App { + ComputerComponent: ((), Shape), } } - #[test] - fn test_downcast_and_handle() { - use cgp::extra::handler::CanCompute; - - let app = App; + pub fn demo() { let code = PhantomData::<()>; - assert_eq!(app.compute(code, FooBarBaz::Foo(1)), "FooBar::Foo(1)"); - assert_eq!(app.compute(code, FooBarBaz::Baz(true)), "Baz(true)"); + assert_eq!(App.compute(code, Shape::Circle(Circle { radius: 1.0 })), 0); + assert_eq!(App.compute(code, Shape::Square(Square { side: 2.0 })), 4); + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + assert_eq!(App.compute(code, rectangle), 4); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs b/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs index 8480342c..72a16195 100644 --- a/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs +++ b/example-code/tests/reference/providers/dispatch/extract_field_and_handle.rs @@ -1,24 +1,14 @@ //! Code from `docs/reference/providers/dispatch/extract_field_and_handle.md` — `ExtractFieldAndHandle`. +//! +//! Pins the Examples program, which calls two adapters by hand to show the `Result` shape a matcher +//! loop consumes: a hit returns `Ok` of the handler's output, and a miss returns the remainder, which +//! the next adapter takes as its input. -/// ## Usage and Examples -/// -/// `ExtractFieldAndHandle` is the per-variant adapter a matcher's list is built from. It -/// tries to extract the variant named `Tag`; on success it hands the payload, still tagged, to -/// `Provider`. Here each variant of `Shape` gets its own adapter, wrapped in `HandleFieldValue` so the -/// handler receives the bare payload. -pub mod one_adapter_per_variant { - use core::marker::PhantomData; - - use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; - use cgp::extra::handler::{Computer, ComputerComponent}; +/// ## Examples +pub mod examples { + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue}; use cgp::prelude::*; - #[derive(CgpData)] - pub enum Shape { - Circle(Circle), - Rectangle(Rectangle), - } - pub struct Circle { pub radius: f64, } @@ -28,6 +18,12 @@ pub mod one_adapter_per_variant { pub height: f64, } + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + #[cgp_new_provider] impl Computer for ComputeArea { type Output = f64; @@ -46,44 +42,36 @@ pub mod one_adapter_per_variant { } } + pub type CircleArm = ExtractFieldAndHandle>; + pub type RectangleArm = + ExtractFieldAndHandle>; + pub struct App; - delegate_components! { - App { - ComputerComponent: MatchWithHandlers< - Product![ - ExtractFieldAndHandle>, - ExtractFieldAndHandle>, - ] - >, - } - } + pub fn demo() { + let code = PhantomData::<()>; + + // A hit: the circle arm extracts its variant and returns `Ok` of the area. + let circle = Shape::Circle(Circle { radius: 1.0 }); + let hit = CircleArm::compute(&App, code, circle.to_extractor()); + assert_eq!(hit.ok(), Some(core::f64::consts::PI)); - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), Shape), + // A miss: the circle arm hands back the remainder, which the rectangle arm takes. + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + match CircleArm::compute(&App, code, rectangle.to_extractor()) { + Ok(_) => panic!("a rectangle is not a circle"), + Err(remainder) => { + let area = RectangleArm::compute(&App, code, remainder); + assert_eq!(area.ok(), Some(12.0)); } } } #[test] - fn the_adapter_extracts_its_variant_and_forwards_the_payload() { - use cgp::extra::handler::CanCompute; - - let app = App; - let code = PhantomData::<()>; - - assert_eq!( - app.compute( - code, - Shape::Rectangle(Rectangle { - width: 2.0, - height: 5.0 - }) - ), - 10.0, - ); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/dispatch/handle_field_value.rs b/example-code/tests/reference/providers/dispatch/handle_field_value.rs index 25843a2f..dd62ec83 100644 --- a/example-code/tests/reference/providers/dispatch/handle_field_value.rs +++ b/example-code/tests/reference/providers/dispatch/handle_field_value.rs @@ -1,24 +1,14 @@ //! Code from `docs/reference/providers/dispatch/handle_field_value.md` — `HandleFieldValue`. +//! +//! Pins the Examples program: `ComputeArea` is a plain computer over each payload type, reached from +//! the tagged `Field` an extract adapter delivers through `HandleFieldValue`. -/// ## Usage and Examples -/// -/// `HandleFieldValue` strips the `Field` wrapper an extract adapter delivers and -/// passes the bare `Value` to `Provider`. That is what lets an ordinary computer over the payload type -/// serve as a per-variant handler. Here `ComputeArea` is a plain computer over each payload type, -/// reached through `HandleFieldValue`. -pub mod unwrapping_the_field { - use core::marker::PhantomData; - +/// ## Examples +pub mod examples { use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; - use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; - #[derive(CgpData)] - pub enum Shape { - Circle(Circle), - Rectangle(Rectangle), - } - pub struct Circle { pub radius: f64, } @@ -28,7 +18,12 @@ pub mod unwrapping_the_field { pub height: f64, } - // A plain computer over the bare payload type; it never sees the `Field` wrapper. + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + #[cgp_new_provider] impl Computer for ComputeArea { type Output = f64; @@ -51,32 +46,27 @@ pub mod unwrapping_the_field { delegate_components! { App { - ComputerComponent: MatchWithHandlers< - Product![ + ComputerComponent: + MatchWithHandlers>, ExtractFieldAndHandle>, - ] - >, + ]>, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), Shape), - } + check_components! { + App { + ComputerComponent: ((), Shape), } } - #[test] - fn the_handler_receives_the_bare_payload() { - use cgp::extra::handler::CanCompute; - - let app = App; - let code = PhantomData::<()>; - - let circle = app.compute(code, Shape::Circle(Circle { radius: 2.0 })); + pub fn demo() { + let circle = App.compute(PhantomData::<()>, Shape::Circle(Circle { radius: 2.0 })); assert!((circle - 4.0 * core::f64::consts::PI).abs() < 1e-9); } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/providers/dispatch/match_first_with_handlers.rs b/example-code/tests/reference/providers/dispatch/match_first_with_handlers.rs index 10d8a048..1c89e169 100644 --- a/example-code/tests/reference/providers/dispatch/match_first_with_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/match_first_with_handlers.rs @@ -1,87 +1,161 @@ //! Code from `docs/reference/providers/dispatch/match_first_with_handlers.md` — `MatchFirstWithHandlers`. //! //! Pins the multi-argument calling convention: the input is `(Input, Args)`, and each per-variant -//! handler receives the matched payload together with the shared `Args`. +//! handler receives the matched payload together with the shared `Args`, both through the explicit +//! list and through the `MatchFirstWithValueHandlers` convenience alias. /// ## Examples pub mod examples { - use core::marker::PhantomData; - use cgp::extra::dispatch::{ ExtractFirstFieldAndHandle, HandleFirstFieldValue, MatchFirstWithHandlers, }; - use cgp::extra::handler::ComputerComponent; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; - #[derive(Debug, PartialEq, CgpData)] + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(CgpData)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } - #[derive(Debug, PartialEq)] + #[cgp_new_provider] + impl Computer for ScaledArea { + type Output = f64; + + fn compute( + _context: &Context, + _code: PhantomData, + (circle, scale): (Circle, f64), + ) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius * scale * scale + } + } + + #[cgp_provider] + impl Computer for ScaledArea { + type Output = f64; + + fn compute( + _context: &Context, + _code: PhantomData, + (rectangle, scale): (Rectangle, f64), + ) -> f64 { + rectangle.width * rectangle.height * scale * scale + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: + MatchFirstWithHandlers>, + ExtractFirstFieldAndHandle>, + ]>, + } + } + + check_components! { + App { + ComputerComponent: ((), (Shape, f64)), + } + } + + pub fn demo() { + let code = PhantomData::<()>; + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + + assert_eq!(App.compute(code, (rectangle, 2.0)), 48.0); // 12 * 2 * 2 + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## When to use it +/// +/// `MatchFirstWithValueHandlers` builds the same list from the enum's variants. +pub mod when_to_use_it { + use cgp::extra::handler::CanCompute; + use cgp::prelude::*; + pub struct Circle { pub radius: f64, } - #[derive(Debug, PartialEq)] pub struct Rectangle { pub width: f64, pub height: f64, } - pub trait Container { - fn contains(self, x: f64, y: f64) -> bool; + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), } - impl Container for Circle { - fn contains(self, _x: f64, _y: f64) -> bool { - true - } - } + #[cgp_new_provider] + impl Computer for ScaledArea { + type Output = f64; - impl Container for Rectangle { - fn contains(self, _x: f64, _y: f64) -> bool { - true + fn compute( + _context: &Context, + _code: PhantomData, + (circle, scale): (Circle, f64), + ) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius * scale * scale } } - // A computer that takes the payload plus the shared `(x, y)` argument. - #[cgp_computer] - fn contains(shape: T, (x, y): (f64, f64)) -> bool { - shape.contains(x, y) - } + #[cgp_provider] + impl Computer for ScaledArea { + type Output = f64; - pub type Handlers = Product![ - ExtractFirstFieldAndHandle>, - ExtractFirstFieldAndHandle>, - ]; + fn compute( + _context: &Context, + _code: PhantomData, + (rectangle, scale): (Rectangle, f64), + ) -> f64 { + rectangle.width * rectangle.height * scale * scale + } + } pub struct App; delegate_components! { App { - ComputerComponent: MatchFirstWithHandlers, + ComputerComponent: MatchFirstWithValueHandlers, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), (Shape, (f64, f64))), - } + check_components! { + App { + ComputerComponent: ((), (Shape, f64)), } } #[test] - fn test_match_first_with_handlers() { - use cgp::extra::handler::CanCompute; - - let app = App; - let code = PhantomData::<()>; - let circle = Shape::Circle(Circle { radius: 5.0 }); + fn the_alias_builds_the_same_list() { + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); - assert!(app.compute(code, (circle, (1.0, 2.0)))); + assert_eq!(App.compute(PhantomData::<()>, (rectangle, 2.0)), 48.0); } } diff --git a/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs index e7aa2452..71d57ded 100644 --- a/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/match_with_field_handlers.rs @@ -1,72 +1,117 @@ //! Code from `docs/reference/providers/dispatch/match_with_field_handlers.md` — `MatchWithFieldHandlers`. +//! +//! Pins the Examples program: one handler over `Field` reads the variant name from the +//! tag, and the same wiring serves a second enum with no new arm. -/// ## Usage and Examples +/// ## Usage /// -/// `MatchWithFieldHandlers` builds the per-variant list from the enum's fields like -/// `MatchWithValueHandlers`, but hands each payload to the provider as a `Field` with the -/// variant tag still attached. Here one handler over `Field` serves every variant, and the -/// same wiring serves a wider enum with no new arm. -pub mod matching_with_the_tag_attached { - use core::convert::Infallible; +/// `MatchWithFieldHandlersRef` hands the provider a `Field`, so the same generic +/// provider serves a borrowed enum. +pub mod usage { use core::fmt::Display; - use cgp::core::error::ErrorTypeProviderComponent; - use cgp::extra::dispatch::MatchWithFieldHandlers; - use cgp::extra::handler::ComputerComponent; + use cgp::core::field::traits::StaticString; + use cgp::extra::dispatch::MatchWithFieldHandlersRef; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; - #[derive(Debug, Eq, PartialEq, CgpData)] + #[derive(CgpData)] pub enum Reading { - Temperature(u64), + Temperature(i32), Label(String), } - #[derive(Debug, Eq, PartialEq, CgpData)] - pub enum ExtendedReading { - Temperature(u64), + #[cgp_computer] + pub fn describe(field: Field) -> String + where + Tag: StaticString, + Value: Display, + { + format!("{}: {}", Tag::VALUE, field.value) + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: MatchWithFieldHandlersRef, + } + } + + check_components! { + App { + ComputerComponent: <'a> ((), &'a Reading), + } + } + + #[test] + fn the_borrowed_form_tags_a_borrowed_payload() { + let reading = Reading::Temperature(21); + + assert_eq!(App.compute(PhantomData::<()>, &reading), "Temperature: 21"); + } +} + +/// ## Examples +pub mod examples { + use core::fmt::Display; + + use cgp::core::field::traits::StaticString; + use cgp::extra::dispatch::MatchWithFieldHandlers; + use cgp::extra::handler::CanCompute; + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Reading { + Temperature(i32), Label(String), - Flag(bool), } - // The payload arrives as a `Field`, so the handler still has the variant tag. + #[derive(CgpData)] + pub enum Event { + Started(u64), + Stopped(bool), + } + #[cgp_computer] - pub fn field_to_string(Field { value, .. }: Field) -> String + pub fn describe(field: Field) -> String where + Tag: StaticString, Value: Display, { - value.to_string() + format!("{}: {}", Tag::VALUE, field.value) } pub struct App; delegate_components! { App { - ErrorTypeProviderComponent: UseType, - ComputerComponent: MatchWithFieldHandlers, + ComputerComponent: MatchWithFieldHandlers, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: [((), Reading), ((), ExtendedReading)], - } + check_components! { + App { + ComputerComponent: [((), Reading), ((), Event)], } } - #[test] - fn one_handler_serves_every_variant_of_two_enums() { - use cgp::extra::handler::CanCompute; - - let app = App; + pub fn demo() { let code = PhantomData::<()>; - assert_eq!(app.compute(code, Reading::Temperature(21)), "21"); assert_eq!( - app.compute(code, Reading::Label("north".to_owned())), - "north" + App.compute(code, Reading::Temperature(21)), + "Temperature: 21" ); - assert_eq!(app.compute(code, ExtendedReading::Flag(true)), "true"); + assert_eq!( + App.compute(code, Reading::Label("north".to_owned())), + "Label: north" + ); + assert_eq!(App.compute(code, Event::Stopped(true)), "Stopped: true"); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/providers/dispatch/match_with_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_handlers.rs index 69092cd7..006d1835 100644 --- a/example-code/tests/reference/providers/dispatch/match_with_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/match_with_handlers.rs @@ -1,23 +1,87 @@ //! Code from `docs/reference/providers/dispatch/match_with_handlers.md` — `MatchWithHandlers`. +//! +//! Pins the borrowed form from Usage, the Examples program, and the lifts Common Mistakes gives for +//! the fallible slots. A list that misses a variant, and a matcher wired to `HandlerComponent`, are +//! trybuild fixtures. -/// ## Usage and Examples +/// ## Usage /// -/// `MatchWithHandlers` runs a spelled-out list of per-variant adapters over an enum, stopping at the -/// first match. Each adapter extracts one variant and hands its payload to a handler; the list is -/// exhaustive, so no wildcard arm is needed. -pub mod matching_an_explicit_list { - use core::marker::PhantomData; - - use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; - use cgp::extra::handler::{Computer, ComputerComponent}; +/// `MatchWithHandlersRef` takes the same list over a borrowed input, so each payload handler +/// computes over a borrowed payload. +pub mod usage { + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlersRef}; + use cgp::extra::handler::CanCompute; use cgp::prelude::*; + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + #[derive(CgpData)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } + #[cgp_new_provider] + impl<'a, Context, Code> Computer for ComputeAreaRef { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: &'a Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl<'a, Context, Code> Computer for ComputeAreaRef { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: &'a Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: + MatchWithHandlersRef>, + ExtractFieldAndHandle>, + ]>, + } + } + + check_components! { + App { + ComputerComponent: <'a> ((), &'a Shape), + } + } + + #[test] + fn the_borrowed_matcher_leaves_the_value_in_place() { + let shape = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + + assert_eq!(App.compute(PhantomData::<()>, &shape), 12.0); + assert!(matches!(shape, Shape::Rectangle(_))); + } +} + +/// ## Examples +pub mod examples { + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + use cgp::extra::handler::CanCompute; + use cgp::prelude::*; + pub struct Circle { pub radius: f64, } @@ -27,7 +91,12 @@ pub mod matching_an_explicit_list { pub height: f64, } - // One provider handles every payload type, with an impl per shape. + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + #[cgp_new_provider] impl Computer for ComputeArea { type Output = f64; @@ -50,43 +119,120 @@ pub mod matching_an_explicit_list { delegate_components! { App { - ComputerComponent: MatchWithHandlers< - Product![ + ComputerComponent: + MatchWithHandlers>, ExtractFieldAndHandle>, - ] - >, + ]>, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: ((), Shape), - } + check_components! { + App { + ComputerComponent: ((), Shape), } } + pub fn demo() { + let code = PhantomData::<()>; + + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + assert_eq!(App.compute(code, rectangle), 12.0); + + let circle = App.compute(code, Shape::Circle(Circle { radius: 1.0 })); + assert!((circle - core::f64::consts::PI).abs() < 1e-9); + } + #[test] - fn the_first_matching_arm_handles_the_value() { - use cgp::extra::handler::CanCompute; + fn test_demo() { + demo(); + } +} + +/// ## Common Mistakes +/// +/// A matcher implements only `Computer` and `AsyncComputer`, so the fallible slots take it through +/// the handler promotions: `Promote` for `TryComputer`, and `PromoteAsync>` for `Handler`. +pub mod common_mistakes { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlers}; + use cgp::extra::handler::{CanHandle, CanTryCompute, Promote, PromoteAsync}; + use cgp::prelude::*; + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } - let app = App; + #[cgp_new_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + pub type AreaMatcher = MatchWithHandlers< + Product![ + ExtractFieldAndHandle>, + ExtractFieldAndHandle>, + ], + >; + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + TryComputerComponent: Promote, + HandlerComponent: PromoteAsync>, + } + } + + check_components! { + App { + [TryComputerComponent, HandlerComponent]: ((), Shape), + } + } + + pub async fn demo() { let code = PhantomData::<()>; + let shape = || { + Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }) + }; + + assert_eq!(App.try_compute(code, shape()), Ok(12.0)); + assert_eq!(App.handle(code, shape()).await, Ok(12.0)); + } - assert_eq!( - app.compute( - code, - Shape::Rectangle(Rectangle { - width: 3.0, - height: 4.0 - }) - ), - 12.0, - ); - - let circle = app.compute(code, Shape::Circle(Circle { radius: 1.0 })); - assert!((circle - core::f64::consts::PI).abs() < 1e-9); + #[test] + fn test_demo() { + futures::executor::block_on(demo()); } } diff --git a/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs b/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs index 4697ec3d..cc2643dc 100644 --- a/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs +++ b/example-code/tests/reference/providers/dispatch/match_with_value_handlers.rs @@ -1,25 +1,203 @@ //! Code from `docs/reference/providers/dispatch/match_with_value_handlers.md` — `MatchWithValueHandlers`. +//! +//! Pins the Examples program, wired by input type with `open`, and the borrowed form from Usage, +//! which answers both `compute` over `&Shape` and `compute_ref` over `Shape`. A struct input and a +//! fallible slot on the borrowed form are trybuild fixtures. -/// ## Usage and Examples +/// ## Usage /// -/// `MatchWithValueHandlers` builds the per-variant handler list from the enum's own fields and passes -/// each payload as a bare value. Wired by input type with `open`, it is selected when the input is a -/// `Shape`, and each payload routes back through the context's own `ComputerComponent` to its handler. -pub mod matching_by_value { - use core::convert::Infallible; - use core::marker::PhantomData; - - use cgp::core::error::ErrorTypeProviderComponent; - use cgp::extra::dispatch::MatchWithValueHandlers; - use cgp::extra::handler::{Computer, ComputerComponent}; +/// `MatchWithValueHandlersRef` answers `ComputerComponent` over a borrowed enum with a provider over +/// borrowed payloads, and `ComputerRefComponent` with a `ComputerRef` provider over the payloads. +pub mod usage { + use cgp::extra::handler::{CanCompute, CanComputeRef, ComputerRef}; use cgp::prelude::*; + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + #[cgp_new_provider] + impl<'a, Context, Code> Computer for ComputeAreaOfRef { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: &'a Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl<'a, Context, Code> Computer for ComputeAreaOfRef { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: &'a Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + #[cgp_new_provider] + impl ComputerRef for ComputeAreaByRef { + type Output = f64; + + fn compute_ref(_context: &Context, _code: PhantomData, circle: &Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl ComputerRef for ComputeAreaByRef { + type Output = f64; + + fn compute_ref(_context: &Context, _code: PhantomData, rectangle: &Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: MatchWithValueHandlersRef, + ComputerRefComponent: MatchWithValueHandlersRef, + } + } + + check_components! { + App { + ComputerComponent: <'a> ((), &'a Shape), + ComputerRefComponent: ((), Shape), + } + } + + #[test] + fn one_matcher_serves_both_borrowed_interfaces() { + let code = PhantomData::<()>; + let shape = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + + assert_eq!(App.compute(code, &shape), 12.0); + assert_eq!(App.compute_ref(code, &shape), 12.0); + } +} + +/// ## Usage: a named provider and the mutable form +/// +/// A named provider needs no per-type entries, and `MatchWithValueHandlersMut` hands each payload +/// to a provider over `&mut` payloads, which can change the value in place. +pub mod usage_named_and_mut { + use cgp::extra::handler::CanCompute; + use cgp::prelude::*; + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + #[derive(CgpData)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } + #[cgp_new_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, circle: Circle) -> f64 { + core::f64::consts::PI * circle.radius * circle.radius + } + } + + #[cgp_provider] + impl Computer for ComputeArea { + type Output = f64; + + fn compute(_context: &Context, _code: PhantomData, rectangle: Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + #[cgp_new_provider] + impl<'a, Context, Code> Computer for DoubleSize { + type Output = (); + + fn compute(_context: &Context, _code: PhantomData, circle: &'a mut Circle) { + circle.radius *= 2.0; + } + } + + #[cgp_provider] + impl<'a, Context, Code> Computer for DoubleSize { + type Output = (); + + fn compute(_context: &Context, _code: PhantomData, rectangle: &'a mut Rectangle) { + rectangle.width *= 2.0; + rectangle.height *= 2.0; + } + } + + pub struct Named; + + delegate_components! { + Named { + ComputerComponent: MatchWithValueHandlers, + } + } + + check_components! { + Named { + ComputerComponent: ((), Shape), + } + } + + pub struct Mutating; + + delegate_components! { + Mutating { + ComputerComponent: MatchWithValueHandlersMut, + } + } + + check_components! { + Mutating { + ComputerComponent: <'a> ((), &'a mut Shape), + } + } + + #[test] + fn the_named_and_mutable_forms_match_each_variant() { + let code = PhantomData::<()>; + let mut shape = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + + Mutating.compute(code, &mut shape); + assert_eq!(Named.compute(code, shape), 48.0); + } +} + +/// ## Examples +pub mod examples { + use cgp::extra::handler::CanCompute; + use cgp::prelude::*; + pub struct Circle { pub radius: f64, } @@ -29,6 +207,12 @@ pub mod matching_by_value { pub height: f64, } + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + #[cgp_new_provider] impl Computer for ComputeArea { type Output = f64; @@ -53,41 +237,32 @@ pub mod matching_by_value { App { open ComputerComponent; - ErrorTypeProviderComponent: UseType, - @ComputerComponent. Code.[Circle, Rectangle]: ComputeArea, @ComputerComponent. Code.Shape: MatchWithValueHandlers, } } - mod check_app { - use super::*; - check_components! { - App { - ComputerComponent: [((), Shape), ((), Circle), ((), Rectangle)], - } + check_components! { + App { + ComputerComponent: [((), Circle), ((), Rectangle), ((), Shape)], } } - #[test] - fn each_variant_reaches_its_handler() { - use cgp::extra::handler::CanCompute; - - let app = App; + pub fn demo() { let code = PhantomData::<()>; - assert_eq!( - app.compute( - code, - Shape::Rectangle(Rectangle { - width: 3.0, - height: 4.0 - }) - ), - 12.0, - ); - - let circle = app.compute(code, Shape::Circle(Circle { radius: 1.0 })); + let rectangle = Shape::Rectangle(Rectangle { + width: 3.0, + height: 4.0, + }); + assert_eq!(App.compute(code, rectangle), 12.0); + + let circle = App.compute(code, Shape::Circle(Circle { radius: 1.0 })); assert!((circle - core::f64::consts::PI).abs() < 1e-9); } + + #[test] + fn test_demo() { + demo(); + } } From 61810e82516ef4c09792a544ec7527cfc39be39f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 04:43:12 +0000 Subject: [PATCH 133/516] Tighten the dispatch pages and route dispatch names from the index Adding a variant to MatchWithValueHandlers needs no new arm but, with the default UseContext, a wiring entry for its payload; only the Ref form of the value matcher answers both borrowed components; CanDowncastFields accepts any extracting source; TryPromote needs the context's error type. Link the check_components generic-parameter form, and point the index's lookup rows for the borrowed and first-argument matchers, DispatchMatchers, and the list traits at the pages that document them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/index.md | 9 +++++++-- docs/reference/providers/dispatch/downcast_and_handle.md | 6 +++--- .../providers/dispatch/match_first_with_handlers.md | 2 +- docs/reference/providers/dispatch/match_with_handlers.md | 7 ++++--- .../providers/dispatch/match_with_value_handlers.md | 8 ++++---- 5 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/reference/index.md b/docs/reference/index.md index 7ac799a7..276decbd 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -242,9 +242,14 @@ of the thing it belongs to. If you arrived knowing one of these names, this is w | `Symbol` (the type, not the `Symbol!` macro) | [`Chars`](./types/chars.md) | | `IdentMonadic`, `OkMonadic`, `ErrMonadic`, `OkMonadicTrans`, `ErrMonadicTrans` | [Monad providers](./providers/monad/index.md) | | `UseDelegatedType`, `WithDelegatedType` | [`UseDelegatedType`](./providers/use_delegated_type.md) and [`WithProvider`](./providers/with_provider.md) | -| `MatchWithHandlersRef`, `MatchFirstWithHandlers`, and the other borrowed and first-argument matcher forms | the matcher page they vary, under [Dispatch combinators](./providers/dispatch/index.md) | +| `MatchWithHandlersRef`, `MatchWithHandlersMut` | [`MatchWithHandlers`](./providers/dispatch/match_with_handlers.md) | +| `MatchFirstWithHandlersRef`, `MatchFirstWithHandlersMut`, and the `MatchFirstWithValueHandlers` and `MatchFirstWithFieldHandlers` forms | [`MatchFirstWithHandlers`](./providers/dispatch/match_first_with_handlers.md) | +| `MatchWithValueHandlersRef`, `MatchWithValueHandlersMut` | [`MatchWithValueHandlers`](./providers/dispatch/match_with_value_handlers.md) | +| `MatchWithFieldHandlersRef` | [`MatchWithFieldHandlers`](./providers/dispatch/match_with_field_handlers.md) | | `ExtractFirstFieldAndHandle`, `HandleFirstFieldValue` | [`ExtractFieldAndHandle`](./providers/dispatch/extract_field_and_handle.md), [`HandleFieldValue`](./providers/dispatch/handle_field_value.md) | -| `DispatchMatchers`, `ToFieldHandlers`, `HasFieldHandlers`, `MapFieldHandler` | [Dispatch combinators](./providers/dispatch/index.md) | +| `DispatchMatchers` | [`MatchWithHandlers`](./providers/dispatch/match_with_handlers.md) | +| `ToFieldHandlers`, `HasFieldHandlers`, `MapFieldHandler`, `MapExtractFieldAndHandle` | [`MatchWithFieldHandlers`](./providers/dispatch/match_with_field_handlers.md) | +| `ToBuildAndMergeHandler` | [`BuildAndMergeOutputs`](./providers/dispatch/build_and_merge_outputs.md) | | `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` | [`MapType`](./traits/type-level/map_type.md) | | `IsRef`, `IsMut`, `IsOwned` | [`MapTypeRef`](./traits/type-level/map_type_ref.md) | | `product!` (the value-level form) | [`Product!`](./macros/product.md) | diff --git a/docs/reference/providers/dispatch/downcast_and_handle.md b/docs/reference/providers/dispatch/downcast_and_handle.md index 062249d3..f3166bd8 100644 --- a/docs/reference/providers/dispatch/downcast_and_handle.md +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -166,9 +166,9 @@ where } ``` -`CanDowncastFields` works on the extractor, not the enum, which is why the arm fits in a matcher's -loop. The `AsyncComputer` impl matches on the downcast and awaits `Provider::compute_async` on a -hit. +`CanDowncastFields` accepts any source that can extract each of `Inner`'s variants, the extractor +included, which is why the arm fits in a matcher's loop. The `AsyncComputer` impl matches on the +downcast and awaits `Provider::compute_async` on a hit. ## Related constructs diff --git a/docs/reference/providers/dispatch/match_first_with_handlers.md b/docs/reference/providers/dispatch/match_first_with_handlers.md index 9af1a5e4..f7b51ffa 100644 --- a/docs/reference/providers/dispatch/match_first_with_handlers.md +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -137,7 +137,7 @@ the `Rectangle` payload beside its scale factor. `App` is an **Reach for `MatchFirstWithHandlers` when every per-variant handler needs the same extra arguments.** When the handlers need only the payload, [`MatchWithHandlers`](match_with_handlers.md) is simpler. When every payload goes to one provider, the convenience aliases build the list from the -enum: `MatchFirstWithValueHandlers` answers the example above on its own, and +enum: `MatchFirstWithValueHandlers` answers the example above without the list, and `MatchFirstWithFieldHandlers` keeps each payload tagged. They come in the same three input modes as their plain counterparts, [`MatchWithValueHandlers`](match_with_value_handlers.md) and [`MatchWithFieldHandlers`](match_with_field_handlers.md). The value forms are in the prelude; the diff --git a/docs/reference/providers/dispatch/match_with_handlers.md b/docs/reference/providers/dispatch/match_with_handlers.md index 7c321d48..5e0d2b94 100644 --- a/docs/reference/providers/dispatch/match_with_handlers.md +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -43,7 +43,8 @@ delegate_components! { Two borrowed forms take the same list and match without moving the value: `MatchWithHandlersRef` over `&Input` and `MatchWithHandlersMut` over `&mut Input`. Their adapters extract a borrowed payload, so each payload handler computes over -`&Circle` or `&mut Circle`, and the check names the borrowed input: +`&Circle` or `&mut Circle`, and the check names the borrowed input with a [generic parameter +list](../../macros/check_components.md#components-with-generic-parameters) of its own: ```rust use cgp::extra::dispatch::{ExtractFieldAndHandle, HandleFieldValue, MatchWithHandlersRef}; @@ -154,8 +155,8 @@ map to handlers in a way the enum's field list cannot generate. When every paylo provider, [`MatchWithValueHandlers`](match_with_value_handlers.md) builds this list from the enum and is shorter. When the handlers also take extra arguments, use [`MatchFirstWithHandlers`](match_first_with_handlers.md). And when the per-variant handlers return -`Result`, [`TryPromote`](../handler/try_promote.md) turns the matcher's `Result` output into a -`TryComputer`. +`Result` in the context's error type, [`TryPromote`](../handler/try_promote.md) turns the matcher's +`Result` output into a `TryComputer`. ## Under the hood diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index 63143b82..15e9d641 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -14,7 +14,7 @@ as a bare value. `MatchWithValueHandlers` is the matcher for the common case, where every variant's payload goes to one provider. Rather than a spelled-out list, it builds one adapter per variant from -the input enum's own field list, so adding a variant needs no change to the wiring, and it hands +the input enum's own field list, so adding a variant needs no new arm, and it hands each payload to `Provider` as a bare value on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. That makes it the form for payload handlers that are ordinary computers over the payload type, such as @@ -45,9 +45,9 @@ segment matches any code, so the second selects by the input type. A named provi per-type entries: `ComputerComponent: MatchWithValueHandlers` sends every payload straight to `ComputeArea`. -Two borrowed forms match without moving the value, and each answers two components. -`MatchWithValueHandlersRef` serves `ComputerComponent` over `&Input` with a provider over -borrowed payloads, and `ComputerRefComponent` over `Input` with a +The borrowed form `MatchWithValueHandlersRef` matches without moving the value and answers +two components. It serves `ComputerComponent` over `&Input` with a provider over borrowed payloads, +and `ComputerRefComponent` over `Input` with a [`ComputerRef`](../../components/handler/computer_ref.md) provider over the payloads: ```rust From da462de13030b4cc737eca63b1f1895bc038fbd3 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 05:08:57 +0000 Subject: [PATCH 134/516] Revise the traits index, wiring, field-access, and shape pages Rewrite the wiring and field-access pages and revise the shape pages against the source and cargo cgp expand, with mirrors for all fifteen construct pages and fixtures for each quoted error. Corrections: a hand-written DelegateComponent entry does not wire a component, since the provider blanket impl also requires IsProviderFor; #[cgp_getter] consumes FieldGetter through its WithProvider impl rather than generating it; ChainGetters takes one Product! list inside WithProvider; the namespace blanket entry comes from the namespace header, not cgp_namespace!; RedirectLookup reads a path key in one lookup; delegate_and_check_components! checks every component-keyed entry. MapField's page now shows the generic read that needs it, and drops the Generated machinery notice, since readers call it. Examples are complete programs; Under the hood listings are the real expansions. The front matter extends the description sweep to traits/wiring, field-access, and shape. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../traits/field-access/field_getter.md | 254 +++++++----- .../traits/field-access/field_mapper.md | 194 +++++---- .../traits/field-access/has_field.md | 279 +++++++------ .../traits/field-access/has_field_mut.md | 150 ++++--- docs/reference/traits/field-access/index.md | 25 +- .../traits/field-access/map_field.md | 219 ++++++----- .../traits/field-access/mut_field_getter.md | 163 ++++---- docs/reference/traits/index.md | 1 + docs/reference/traits/shape/from_fields.md | 158 +++++--- docs/reference/traits/shape/has_fields.md | 181 +++++---- docs/reference/traits/shape/has_fields_ref.md | 131 ++++--- docs/reference/traits/shape/index.md | 1 + docs/reference/traits/shape/to_fields.md | 121 +++--- docs/reference/traits/shape/to_fields_ref.md | 106 ++--- .../traits/wiring/can_use_component.md | 285 ++++++++------ .../traits/wiring/delegate_component.md | 343 +++++++++------- docs/reference/traits/wiring/index.md | 7 +- .../traits/wiring/is_provider_for.md | 371 +++++++++++------- ...mponent_common_mistakes_duplicate_entry.rs | 32 ++ ...ent_common_mistakes_duplicate_entry.stderr | 15 + ...nent_common_mistakes_hand_written_entry.rs | 24 ++ ..._common_mistakes_hand_written_entry.stderr | 41 ++ ...component_common_mistakes_missing_entry.rs | 31 ++ ...onent_common_mistakes_missing_entry.stderr | 32 ++ ...r_common_mistakes_without_with_provider.rs | 43 ++ ...mmon_mistakes_without_with_provider.stderr | 32 ++ ...has_field_common_mistakes_deref_overlap.rs | 25 ++ ...field_common_mistakes_deref_overlap.stderr | 9 + ...s_field_common_mistakes_misspelled_name.rs | 22 ++ ...eld_common_mistakes_misspelled_name.stderr | 20 + ...r_for_common_mistakes_missing_attribute.rs | 17 + ...r_common_mistakes_missing_attribute.stderr | 27 ++ ..._for_common_mistakes_missing_dependency.rs | 39 ++ ..._common_mistakes_missing_dependency.stderr | 37 ++ ...r_for_common_mistakes_one_element_tuple.rs | 31 ++ ...r_common_mistakes_one_element_tuple.stderr | 43 ++ ...field_common_mistakes_chained_get_field.rs | 14 + ...d_common_mistakes_chained_get_field.stderr | 36 ++ .../reference/traits/can_use_component.rs | 90 +++++ .../reference/traits/delegate_component.rs | 78 ++++ .../tests/reference/traits/field_getter.rs | 86 ++++ .../tests/reference/traits/field_mapper.rs | 74 ++++ .../tests/reference/traits/from_fields.rs | 43 ++ .../tests/reference/traits/has_field.rs | 103 +++++ .../tests/reference/traits/has_field_mut.rs | 65 +++ .../tests/reference/traits/has_fields.rs | 54 +++ .../tests/reference/traits/has_fields_ref.rs | 49 +++ .../tests/reference/traits/is_provider_for.rs | 104 +++++ .../tests/reference/traits/map_field.rs | 70 ++++ example-code/tests/reference/traits/mod.rs | 14 + .../reference/traits/mut_field_getter.rs | 43 ++ .../tests/reference/traits/to_fields.rs | 39 ++ .../tests/reference/traits/to_fields_ref.rs | 33 ++ 53 files changed, 3241 insertions(+), 1263 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.rs create mode 100644 example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs create mode 100644 example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.rs create mode 100644 example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.rs create mode 100644 example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.rs create mode 100644 example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs create mode 100644 example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.rs create mode 100644 example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs create mode 100644 example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs create mode 100644 example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.rs create mode 100644 example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.stderr create mode 100644 example-code/tests/reference/traits/can_use_component.rs create mode 100644 example-code/tests/reference/traits/delegate_component.rs create mode 100644 example-code/tests/reference/traits/field_getter.rs create mode 100644 example-code/tests/reference/traits/field_mapper.rs create mode 100644 example-code/tests/reference/traits/from_fields.rs create mode 100644 example-code/tests/reference/traits/has_field.rs create mode 100644 example-code/tests/reference/traits/has_field_mut.rs create mode 100644 example-code/tests/reference/traits/has_fields.rs create mode 100644 example-code/tests/reference/traits/has_fields_ref.rs create mode 100644 example-code/tests/reference/traits/is_provider_for.rs create mode 100644 example-code/tests/reference/traits/map_field.rs create mode 100644 example-code/tests/reference/traits/mut_field_getter.rs create mode 100644 example-code/tests/reference/traits/to_fields.rs create mode 100644 example-code/tests/reference/traits/to_fields_ref.rs diff --git a/docs/reference/traits/field-access/field_getter.md b/docs/reference/traits/field-access/field_getter.md index e8dd06fc..b3d0df98 100644 --- a/docs/reference/traits/field-access/field_getter.md +++ b/docs/reference/traits/field-access/field_getter.md @@ -1,40 +1,45 @@ --- +title: 'FieldGetter — field access as a provider' +description: 'The provider-side form of HasField: a getter component takes any FieldGetter provider, such as UseField, through WithProvider.' sidebar_label: 'FieldGetter' sidebar_position: 3 --- # `FieldGetter` -The provider-side mirror of `HasField`: field access that gets wired. +The provider-side form of `HasField`: field access a context chooses by wiring. :::info ### Generated machinery -**You are not expected to implement `FieldGetter`.** -[`#[cgp_getter]`](../../macros/cgp_getter.md) generates it as the getter's provider trait, and -[`UseField`](../../providers/use_field.md) is the provider you wire to satisfy it. What you write is the -wiring entry; this page explains the shape that entry resolves through. The one case for implementing it by hand is a getter whose value is computed rather than stored. +**You are not expected to name `FieldGetter` in wiring.** A getter component defined with +[`#[cgp_getter]`](../../macros/cgp_getter.md) accepts any provider of it through +[`WithProvider`](../../providers/with_provider.md), and +[`UseField`](../../providers/use_field.md) is the provider you usually name there, as +`WithField`. What you write is the wiring entry. The one case for implementing the trait +yourself is a getter provider whose read no existing provider expresses. ::: ## Overview -[`HasField`](./has_field.md) is a bound an implementation states about its own context. Sometimes field -access should instead be **chosen by wiring**, so that a context decides which of its fields answers a -given getter. That needs the provider-trait shape: the context as an explicit type argument rather than -as `&self`. +[`HasField`](./has_field.md) is a bound an implementation states about its own context. Sometimes +the field should instead be **chosen by wiring**, so that each +[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the +values it needs as its fields, decides which of its fields answers a getter. That needs the +provider-trait shape: a zero-sized provider as `Self`, and the context as an explicit type argument. -`FieldGetter` is that shape. This is the ordinary consumer/provider duality applied to field access: -**you bound against [`HasField`](./has_field.md), and you wire `FieldGetter`**. They are not alternatives. - -[`UseField`](../../providers/use_field.md) is the provider that implements it by reading a named field, -and [`#[cgp_getter]`](../../macros/cgp_getter.md) targets it. +`FieldGetter` is that shape, and it is the ordinary consumer and provider split applied to field +access: you bound against [`HasField`](./has_field.md), and you wire a `FieldGetter`. Three +providers implement it. `UseField` reads the field `Tag`; +[`UseContext`](../../providers/use_context.md) reads the field named by the tag it is asked under; +and [`ChainGetters`](../../providers/chain_getters.md) composes others to reach a nested field. ## Definition -`FieldGetter` is the provider-trait mirror of [`HasField`](./has_field.md), with the context -as an explicit type argument instead of `&self`: +`FieldGetter` mirrors [`HasField`](./has_field.md), with the context as an explicit +type argument instead of `&self`: ```rust pub trait FieldGetter { @@ -44,39 +49,40 @@ pub trait FieldGetter { } ``` -`Self` is the **provider**, a zero-sized marker carrying no data, and `Context` is the type the field is -read from. `Tag` names the field, exactly as it does on `HasField`, and `Value` is the field's type. -`get_field` takes the context by shared reference and returns `&Self::Value`, with the `PhantomData` -argument disambiguating which field is meant. +`Self` is the provider, a marker carrying no data, and `Context` is the type the field is read from. +`Tag` is the tag the provider is asked under: through a getter component, that is the component's +own marker. `Value` is the field's type, and `get_field` returns a borrow of it. It is a plain trait +rather than a component provider trait, so its impls carry no +[`IsProviderFor`](../wiring/is_provider_for.md) pair. ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. - -You rarely name the trait directly. What you write is a wiring entry naming a provider that implements -it: +It is in the prelude, so `use cgp::prelude::*;` is enough. A getter component takes a `FieldGetter` +provider wrapped in `WithProvider`, most often through the `WithField` alias for +`WithProvider>`, which is imported from `cgp::core::field::impls`: ```rust +use cgp::core::field::impls::WithField; + delegate_components! { Person { - NameGetterComponent: UseField, + NameGetterComponent: WithField, } } ``` -Reading it back: the getter component is answered by [`UseField`](../../providers/use_field.md), which -implements `FieldGetter` by reading the `first_name` field, whose name need not match the getter's method -name. That is the whole point of wiring the access rather than deriving it. - -Writing a `FieldGetter` impl by hand is the escape hatch for a getter whose value is computed rather than -stored, and it is an ordinary trait impl on a marker type of your own. +The getter then reads `first_name`, whose name need not match the getter's method. A bare +`UseField` entry works as well, through a separate impl that `#[cgp_getter]` +emits for `UseField` directly, without going through `FieldGetter`. ## Examples -The wired form, where the field's name and the getter's name differ: +One getter component answered on two contexts by two `FieldGetter` providers, `UseField` reading a +differently named field and a hand-written provider reading a nested one: ```rust use cgp::prelude::*; +use cgp::core::field::impls::WithField; #[cgp_getter(NameGetter)] pub trait HasName { @@ -90,106 +96,172 @@ pub struct Person { delegate_components! { Person { - NameGetterComponent: UseField, + NameGetterComponent: WithField, + } +} + +pub struct Profile { + pub display_name: String, +} + +#[derive(HasField)] +pub struct Account { + pub profile: Profile, +} + +pub struct ReadDisplayName; + +impl FieldGetter for ReadDisplayName +where + Context: HasField, +{ + type Value = String; + + fn get_field(context: &Context, _tag: PhantomData) -> &String { + &context.get_field(PhantomData).display_name + } +} + +delegate_components! { + Account { + NameGetterComponent: WithProvider, } } -``` -`person.name()` now returns the `first_name` field. **[Value context](/docs/reference/glossary#value-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** +check_components! { + Person { + NameGetterComponent, + } +} -A second context can answer the same getter from a different field by changing one wiring line, which -the provider-side shape buys and a plain [`HasField`](./has_field.md) bound cannot express. +check_components! { + Account { + NameGetterComponent, + } +} + +pub fn demo() { + let person = Person { + first_name: "Ada".to_owned(), + }; + let account = Account { + profile: Profile { + display_name: "ada99".to_owned(), + }, + }; + + assert_eq!(person.name(), "Ada"); + assert_eq!(account.name(), "ada99"); +} +``` + +`ReadDisplayName` ignores the tag it is asked under and reads a field of a field, so it is an +ordinary impl on a marker type, with no attribute. Both contexts are +[value contexts](/docs/reference/glossary#value-context), and the getter is +[self-targeted](/docs/reference/glossary#self-targeted-component). ## When to use it -**Wire a `FieldGetter` only when a context must choose which field a getter reads**, which is the -advanced case. Everything else is better served higher up. +**Wire a `FieldGetter` only when a context must choose which field a getter reads**, the advanced +case. The simpler forms come first: -- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** for a field an implementation reads from - its own context. It generates a [`HasField`](./has_field.md) bound and involves no provider at all. -- **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a named trait, - keyed by the method name. It generates a blanket impl over `HasField` and needs no wiring. -- **Use [`#[cgp_getter]`](../../macros/cgp_getter.md)** when the source field must be chosen per context. - That is what makes the getter a full component with a `FieldGetter` provider trait, and it costs a - wiring line per context. -- **Reach for [`MutFieldGetter`](./mut_field_getter.md)** when the wired access must also mutate. +- **An [`#[implicit]`](../../attributes/implicit.md) argument** reads a field of the + implementation's own context, and involves no provider. +- **[`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** makes the read a named trait keyed by + the method name, with no wiring. +- **[`#[cgp_getter]`](../../macros/cgp_getter.md)** makes the getter a component, whose wiring entry + names the `FieldGetter` provider: `WithField` for a field of the context, or + `WithProvider>` for a field of a nested value. -Do not treat it as an alternative to [`HasField`](./has_field.md). One is what an implementation -requires; the other is what a context supplies. +Write a provider of your own only for a read those do not cover. A nested field is usually a +`ChainGetters` list of `UseField` steps rather than a hand-written provider like the example's. ## Under the hood -The provider side connects to ordinary derived field access through one blanket impl: -[`UseContext`](../../providers/use_context.md) implements `FieldGetter` for any context that already has the -field, delegating straight through. +For a one-method getter, `#[cgp_getter]` emits an impl of the getter's provider trait for +`WithProvider

`, bounded on `P: FieldGetter` under the component's marker. `cargo cgp expand` on +the example shows: ```rust -impl FieldGetter for UseContext +impl<__Context__, __Provider__> NameGetter<__Context__> for WithProvider<__Provider__> where - Context: HasField, + __Provider__: FieldGetter<__Context__, NameGetterComponent, Value = String>, { - type Value = Field; - - fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value { - context.get_field(PhantomData) + fn name(__context__: &__Context__) -> &String { + __Provider__::get_field( + __context__, + ::core::marker::PhantomData::, + ) } } ``` -So wiring a getter to `UseContext` means "read the field of the same name off the context", which is the -behaviour [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) gives without any wiring. +`UseField` implements `FieldGetter` for every tag it is asked under, reading its own `Tag` +instead, which is why it serves any getter: -[`UseField`](../../providers/use_field.md) is the more interesting provider: it fixes the tag at the -wiring site, so the field it reads is decided there rather than by the method's name. +```rust +impl FieldGetter for UseField +where + Context: HasField, +{ + type Value = Value; + + fn get_field(context: &Context, _tag: PhantomData) -> &Value { + context.get_field(PhantomData) + } +} +``` -The lifetime-safe variant [`FieldMapper`](./field_mapper.md) is a blanket impl over every `FieldGetter` -with the getter and tag `'static`, which [`ChainGetters`](../../providers/chain_getters.md) relies -on. +`UseContext` reads the tag it is asked under, so through +[`WithContext`](../../providers/with_context.md) it needs the context to implement +`HasField`, keyed by the component rather than by a field name. The +lifetime-safe [`FieldMapper`](./field_mapper.md) is a blanket impl over every `FieldGetter`, which +`ChainGetters` relies on. ## Common Mistakes -**`Self` is the provider, not the context.** The context is the first type parameter. Reading the -signature the other way round is the usual confusion when meeting a provider trait, and it applies to -every provider trait rather than to this one specially. +**A `FieldGetter` provider does not answer a getter on its own.** Wiring +`NameGetterComponent: ReadDisplayName`, without `WithProvider`, names a provider that implements +`FieldGetter` but not the getter's provider trait, so the check fails on its missing marker: + +```text +error[E0277]: the trait bound `ReadDisplayName: IsProviderFor` is not satisfied +``` -**It is not an alternative to [`HasField`](./has_field.md).** Bounding an implementation on `FieldGetter` -instead of `HasField` is almost always a mistake: the implementation wants a requirement on its context, -not a provider parameter. +Wrap it, as `WithProvider`. -**The getter's method name and the field's name are independent once wired.** That is the feature, and it -means a reader cannot infer the field from the getter: the wiring line is the only place the answer -lives. +**`Self` is the provider, not the context.** The context is the first type parameter, which is the +usual confusion when meeting any provider trait. -**A getter wired to [`UseContext`](../../providers/use_context.md) needs the field to exist under the -getter's own name**, since that impl keys on the tag it is given. +**It is not an alternative to [`HasField`](./has_field.md).** An implementation that needs a field +bounds its context on `HasField`; `FieldGetter` is what a context supplies through wiring. -**It returns a reference.** A getter that must produce an owned or computed value uses -[`MRef`](../../types/mref.md) as its return type instead. +**The getter's method name and the field's name are independent once wired.** That is the feature, +and it means a reader cannot infer the field from the getter: the wiring line holds the answer. ## Related constructs - [`HasField`](./has_field.md): the consumer side you bound against. -- [`MutFieldGetter`](./mut_field_getter.md): the mutable extension of this trait. +- [`MutFieldGetter`](./mut_field_getter.md): the mutable extension. - [`FieldMapper`](./field_mapper.md): the lifetime-safe form, for nested access. -- [`UseField`](../../providers/use_field.md): the provider that implements it by reading a named field. -- [`UseContext`](../../providers/use_context.md): the provider that routes back through the context's own - fields. -- [`#[cgp_getter]`](../../macros/cgp_getter.md): the macro that makes a getter a full component. -- [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md): the simpler getter, keyed by method name. -- [`ChainGetters`](../../providers/chain_getters.md): composing getters to reach a nested field. -- [`MRef`](../../types/mref.md): the owned-or-borrowed return type for a getter that may produce its value. +- [`UseField`](../../providers/use_field.md) and [`WithField`](../../providers/with_field.md): the + provider that reads a named field, and its `WithProvider` alias. +- [`UseContext`](../../providers/use_context.md): the provider that reads the field named by its + tag. +- [`ChainGetters`](../../providers/chain_getters.md): composes getters to reach a nested field. +- [`#[cgp_getter]`](../../macros/cgp_getter.md): the macro whose getters take these providers. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the duality this trait is - the field-access instance of. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the split this trait + is the field-access instance of. ## Source -- [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs): +- [`traits/has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs): `FieldGetter` and the `UseContext` impl -- [`use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs): - the `UseField` provider +- [`impls/use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs): + the `UseField` impls --- diff --git a/docs/reference/traits/field-access/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md index 90da9e4e..7cd55038 100644 --- a/docs/reference/traits/field-access/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -2,7 +2,7 @@ title: 'FieldMapper — the provider side of MapField' sidebar_label: 'FieldMapper' sidebar_position: 6 -description: 'The provider-side mirror of MapField, generated as a blanket implementation over every field getter. You meet it in an expansion rather than call it.' +description: 'The provider-side mirror of MapField, a blanket impl over every field getter that lets a getter provider read through the field another provider returns.' --- # `FieldMapper` @@ -13,31 +13,33 @@ The provider-side mirror of `MapField`. ### Generated machinery -**You will not call `map_field` yourself.** It is a blanket impl over every -[`FieldGetter`](./field_getter.md), and [`ChainGetters`](../../providers/chain_getters.md) is its only -caller in practice. This page explains the mechanism a chained getter is built from. The one case for calling it directly is writing a getter provider of your own that has to descend. +**You are not expected to implement `FieldMapper`.** It is a blanket impl over every +[`FieldGetter`](./field_getter.md), and [`ChainGetters`](../../providers/chain_getters.md) is the +provider that calls it to descend into a nested value. The one case for naming it is a getter +provider of your own that has to read through another provider's field, as the example on this page +does. ::: ## Overview -[`MapField`](./map_field.md) reads through a field without forcing its type to be `'static`, by taking a -higher-ranked closure instead of returning the intermediate borrow. `FieldMapper` is the same operation -in provider-trait shape, with the context as an explicit type argument rather than as `&self`. The -group's two-by-two shape holds here too: +[`MapField`](./map_field.md) reads through a field of a generic +[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the +values it needs as its fields, by handing the borrowed field to a closure rather than returning it. +`FieldMapper` is the same operation in provider shape, with a provider as `Self` and the context as +an explicit type argument. This is the form a getter provider needs, because a provider trait's +method has its lifetimes fixed by the trait, so a chained read inside it cannot take the lifetime +bound a free function could. The group's two-by-two shape holds here too: | | you bound against | you wire | |---|---|---| | plain read | [`HasField`](./has_field.md) | [`FieldGetter`](./field_getter.md) | | read through | [`MapField`](./map_field.md) | `FieldMapper` | -**This is the one [`ChainGetters`](../../providers/chain_getters.md) actually uses**, because a chained -getter is a provider composing other providers rather than a method on a concrete type. - ## Definition -`FieldMapper` is the provider-trait mirror of [`MapField`](./map_field.md), with the context -as an explicit type argument instead of `&self`: +`FieldMapper` mirrors [`MapField`](./map_field.md), with the context as an explicit +type argument: ```rust pub trait FieldMapper: FieldGetter { @@ -49,33 +51,45 @@ pub trait FieldMapper: FieldGetter { } ``` -`Self` is the provider and `Context` is the type being read from. It is a [supertrait](/docs/reference/glossary#supertrait) extension of -[`FieldGetter`](./field_getter.md), exactly as [`MapField`](./map_field.md) extends -[`HasField`](./has_field.md), so `Value` comes from the supertrait. `map_field` takes the context by -shared reference, the `PhantomData` that names the field, and a `mapper` closure whose higher-ranked -`for<'a>` bound ties the returned `&T` to the field's own lifetime. +`Self` is the provider and `Context` is the type being read from. It is a +[supertrait](/docs/reference/glossary#supertrait) extension of [`FieldGetter`](./field_getter.md), +so `Value` comes from there, and the `for<'a>` bound on `mapper` ties the returned `&T` to the +context's borrow. ## Usage -**It is not in the prelude.** Import it from `cgp::core::field::traits`: +It is not in the prelude. Import it from `cgp::core::field::traits`: ```rust use cgp::core::field::traits::FieldMapper; ``` -**Nobody implements it.** It is a blanket impl for every [`FieldGetter`](./field_getter.md) with the -getter and the tag `'static`, so every field-getter provider gains `map_field` for free, which makes -chaining composable without each provider opting in. - -The `mapper` argument carries the same `for<'a>` binder as its consumer-side twin, and for the same -reason: it lets the returned borrow be tied to the field borrow rather than to a fixed lifetime. +Nothing implements it by hand: a blanket impl gives it to every `FieldGetter` whose provider and tag +are `'static`, so every field-getter provider can be read through. A provider of your own bounds an +inner provider on `FieldMapper` and calls `map_field` on it. ## Examples -You meet it through a wiring line rather than a call. A getter that reaches a field on a nested context: +A two-step getter provider that reads through the field one provider returns with another, wired for +a getter, and a direct call through `UseContext`: ```rust use cgp::prelude::*; +use cgp::core::field::traits::FieldMapper; + +pub struct ThenGet(pub PhantomData<(First, Second)>); + +impl FieldGetter for ThenGet +where + First: FieldMapper, + Second: FieldGetter, +{ + type Value = Value; + + fn get_field(context: &Context, tag: PhantomData) -> &Value { + First::map_field(context, tag, |mid| Second::get_field(mid, tag)) + } +} #[cgp_getter(NameGetter)] pub trait HasName { @@ -94,98 +108,104 @@ pub struct Outer { delegate_components! { Outer { - NameGetterComponent: ChainGetters>, + NameGetterComponent: + WithProvider, UseField>>, } } -``` - -**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** [`ChainGetters`](../../providers/chain_getters.md) descends into -`inner` with `FieldMapper::map_field` and then applies the inner provider to what it finds, so -`outer.name()` resolves to `outer.inner.name` with no lifetime obligations leaking into either type. -Calling it directly is possible and rarely what you want: - -```rust -use cgp::core::field::traits::FieldMapper; +check_components! { + Outer { + NameGetterComponent, + } +} -let name = >::map_field( - &outer, - PhantomData, - |inner| inner.get_field(PhantomData::), -); +pub fn demo() { + let outer = Outer { + inner: Inner { + name: "Alice".to_owned(), + }, + }; + + assert_eq!(outer.name(), "Alice"); + + let name = >::map_field( + &outer, + PhantomData, + |inner| inner.get_field(PhantomData::), + ); + assert_eq!(name, "Alice"); +} ``` -## When to use it - -**Reach for [`ChainGetters`](../../providers/chain_getters.md) rather than this trait.** It is the construct; -`FieldMapper` is the mechanism underneath it. +`ThenGet` is a two-element [`ChainGetters`](../../providers/chain_getters.md), written out to show +the mechanism; in real wiring use `ChainGetters` itself. Its `get_field` could not be written as +`Second::get_field(First::get_field(context, tag), tag)`: that fails with `E0311`, because `Mid` is +not known to outlive the borrow. `Outer` is a [value +context](/docs/reference/glossary#value-context). -- **Use [`ChainGetters`](../../providers/chain_getters.md)** to reach a field on a nested context by wiring. -- **Use [`FieldGetter`](./field_getter.md)** when the wired access is a plain one-level read. -- **Use [`MapField`](./map_field.md)** when the descent happens on `self` rather than on a wired context: - the consumer-side twin. -- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** before any of them for a field of the - implementation's own context. +## When to use it -Name it directly only when writing a getter provider of your own that must descend, and check first -whether composing the existing ones does the job. +**Reach for [`ChainGetters`](../../providers/chain_getters.md)** to give a getter a nested field by +wiring. Name `FieldMapper` only when writing a getter provider of your own that must read through +another provider's field, and use [`MapField`](./map_field.md) when the descent is on a generic +context in an ordinary function. ## Under the hood -`FieldMapper` is a blanket impl over every [`FieldGetter`](./field_getter.md), with two `'static` bounds -that its consumer-side twin needs only one of: - -- the **tag** must be `'static`, which is free, since a [`Symbol!`](../../macros/symbol.md) or an - [`Index`](../../types/index_type.md) is `'static` by construction; -- the **getter**, that is, `Self`, the provider, must be `'static`, which is also free, since a - provider is a zero-sized marker type with no lifetime parameters in the ordinary case. +`FieldMapper` is a blanket impl over every [`FieldGetter`](./field_getter.md): -The field's *value* stays free of any bound, which is the whole point: it is the intermediate whose -lifetime the naive chained read could not express. +```rust +impl FieldMapper for Getter +where + Getter: FieldGetter + 'static, + Tag: 'static, +{ + fn map_field( + context: &Context, + tag: PhantomData, + mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, + ) -> &T { + mapper(Getter::get_field(context, tag)) + } +} +``` -[`ChainGetters`](../../providers/chain_getters.md) composes descents by nesting `map_field` calls, one per -path segment, so an arbitrarily deep chain stays lifetime-correct. Because the impl is blanket, adding a -new getter provider makes it chainable with no extra work. +Both `'static` bounds are on types that are `'static` in practice, the tag and the provider, a +zero-sized marker; the field's value stays free. `ChainGetters` nests these calls, one per step, so +a chain of any length stays free of lifetime bounds. ## Common Mistakes -**It is not in the prelude.** Import from `cgp::core::field::traits`. -[`MapField`](./map_field.md) is the other non-prelude member of the group. - -**`Self` is the provider, not the context.** The context is the first type parameter and arrives as -`&Context` in the method. - -**The closure must be higher-ranked.** A closure capturing a reference of a particular lifetime will not -satisfy `for<'a>`, and the error talks about lifetime bounds rather than about the closure's body. +**A chained `get_field` inside a provider fails.** As the example notes, a provider that calls one +getter's `get_field` on another's result fails with `E0311` on the intermediate type; call +`map_field` on the first getter instead. -**A provider with a non-`'static` parameter loses the blanket impl.** The bound on `Self` is free for an -ordinary zero-sized marker and not for one carrying a lifetime, which is a rare shape and a puzzling -failure when it happens. +**`Self` is the provider, not the context.** The context is the first type parameter. -**It cannot map to an owned value.** The signature returns `&T`; a getter that must produce a value uses -[`MRef`](../../types/mref.md). +**A provider with a non-`'static` parameter loses the blanket impl.** The bound on `Self` holds for +an ordinary marker type and not for one carrying a lifetime, a rare shape and a puzzling failure +when it happens. ## Related constructs -- [`MapField`](./map_field.md): the consumer-side twin, and where the lifetime problem is explained in +- [`MapField`](./map_field.md): the consumer-side twin, where the lifetime problem is explained in full. - [`FieldGetter`](./field_getter.md): the supertrait, and the plain wired read. -- [`ChainGetters`](../../providers/chain_getters.md): the provider that uses this to descend. -- [`HasField`](./has_field.md): the consumer side of field access. -- [`UseField`](../../providers/use_field.md) and [`UseContext`](../../providers/use_context.md): the two +- [`ChainGetters`](../../providers/chain_getters.md): the provider built on this trait. +- [`UseField`](../../providers/use_field.md) and [`UseContext`](../../providers/use_context.md): the providers a chain is usually built from. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags, `'static` by construction. -- [`MRef`](../../types/mref.md): the return type for a getter that may produce rather than lend. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the duality this trait is - an instance of. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the split this trait + is an instance of. ## Source -- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs): +- [`traits/map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs): `FieldMapper` and `MapField` +- [`impls/chain.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/chain.rs): + `ChainGetters`, which calls it --- diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index 0073d6ce..c7e7e6b9 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -1,4 +1,6 @@ --- +title: 'HasField — read a field by a type-level name' +description: 'The trait for reading one field of a context by its name as a type, so generic code can bound on a field of a type it cannot name.' sidebar_label: 'HasField' sidebar_position: 1 --- @@ -9,27 +11,24 @@ Reading a field by a type-level name, from a context you cannot name. ## Overview -An implementation written against a **context**, the type the method runs on, which supplies -the values it needs as its fields, is generic over that context and cannot name its concrete type. So it -cannot write `self.name`. Yet reading a value out of the context is the commonest thing such an -implementation does. - -`HasField` closes the gap. The field's *name* becomes a type, and the implementation asks for it as -an ordinary trait bound: +An implementation written against a [**context**](/docs/reference/glossary#context), the type the +method runs on, which supplies the values it needs as its fields, is generic over that context and +cannot name its concrete type, so it cannot write `self.name`. `HasField` closes the gap: the +field's name becomes a type, and the implementation asks for the field as a trait bound: ```rust Self: HasField ``` -Any context with a matching field satisfies that bound. Nothing is compared by string at run time. -[`Symbol!("name")`](../../macros/symbol.md) is a type, so the compiler resolves which field is meant and the -read compiles to a direct field access. +Any context with a matching field satisfies that bound. Nothing is compared by string at run time: +[`Symbol!("name")`](../../macros/symbol.md) is a type, so the compiler resolves which field is meant +and the read compiles to a direct field access. -This is the foundation the whole ergonomic surface stands on. An -[`#[implicit]`](../../attributes/implicit.md) argument, a [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) -method, and a [`UseField`](../../providers/use_field.md) wiring entry all generate this bound from a name you -already wrote. **You will read `HasField` far more often than you write it**, and the impls come from -[`#[derive(HasField)]`](../../derives/derive_has_field.md). +The ergonomic constructs all stand on this trait. An [`#[implicit]`](../../attributes/implicit.md) +argument, a [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) method, and a +[`UseField`](../../providers/use_field.md) wiring entry each generate this bound from a name you +already wrote, and the impls come from [`#[derive(HasField)]`](../../derives/derive_has_field.md). +You read `HasField` far more often than you write it. ## Definition @@ -43,33 +42,42 @@ pub trait HasField { } ``` -`Tag` is a type-level name: [`Symbol!("field_name")`](../../macros/symbol.md) for a named field, -[`Index`](../../types/index_type.md) for a tuple field. `Value` is the field's type, exposed as an associated -type so a bound can pin it or leave it open: `HasField` accepts a field of any type, -while `HasField` requires a `String`. `get_field` takes `&self` and -returns `&Self::Value`, a borrow of the field; its `PhantomData` argument carries no data and only -lets a call site say *which* field it means when several `HasField` impls are in scope, which is why a -read is written `self.get_field(PhantomData::)`. +`Tag` is a type-level name: [`Symbol!("field_name")`](../../macros/symbol.md) for a named field, and +[`Index`](../../types/index_type.md) for a tuple field. `Value` is the field's type, exposed as +an associated type so a bound can pin it, as `HasField`, or leave +it open. `get_field` borrows the field; its `PhantomData` argument carries no data and tells a +call site which field it means when several `HasField` impls are in scope, so a read is written +`self.get_field(PhantomData::)`. ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. +It is in the prelude, so `use cgp::prelude::*;` is enough. An implementation states the field it +needs in its `where` clause and reads it with `get_field`; a context gets the impls by deriving +them: -**Four neighbours complete the picture**, each on its own page: [`HasFieldMut`](./has_field_mut.md) for -mutable access, [`FieldGetter`](./field_getter.md) for the provider-side mirror that gets wired, and -[`MapField`](./map_field.md) with [`FieldMapper`](./field_mapper.md) for the lifetime-safe form nested -accessors use. +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, +} +``` + +Four neighbours complete the picture, each on its own page: [`HasFieldMut`](./has_field_mut.md) for +mutable access, [`FieldGetter`](./field_getter.md) for the provider-side form that gets wired, and +[`MapField`](./map_field.md) with [`FieldMapper`](./field_mapper.md) for reading through a field in +generic code. ## Examples -An implementation states the field it needs and reads it: +A provider that bounds on a field and reads it, and a generic function that reads the same field +through a `Box`: ```rust use cgp::prelude::*; #[cgp_component(Greeter)] pub trait CanGreet { - fn greet(&self); + fn greet(&self) -> String; } #[cgp_impl(new GreetHello)] @@ -77,8 +85,8 @@ impl Greeter where Self: HasField, { - fn greet(&self) { - println!("Hello, {}!", self.get_field(PhantomData::)); + fn greet(&self) -> String { + format!("Hello, {}!", self.get_field(PhantomData::)) } } @@ -92,135 +100,172 @@ delegate_components! { GreeterComponent: GreetHello, } } -``` -`Person` derives the access, so it satisfies exactly the bound `GreetHello` requires and the wiring -compiles. **[Value context](/docs/reference/glossary#value-context), [self-targeted](/docs/reference/glossary#self-targeted-component)**: the wired type is the data the method runs on. +check_components! { + Person { + GreeterComponent, + } +} -**Written idiomatically, none of that bound is visible.** The same read is an -[`#[implicit]`](../../attributes/implicit.md) argument: +pub fn read_name(context: &Context) -> &String +where + Context: HasField, +{ + context.get_field(PhantomData) +} -```rust -#[cgp_impl(new GreetHello)] -impl Greeter { - fn greet(&self, #[implicit] name: &str) { - println!("Hello, {name}!"); - } +pub fn demo() { + let person = Person { + name: "Ada".to_owned(), + }; + assert_eq!(person.greet(), "Hello, Ada!"); + + // `Box` has the field through the `Deref` forwarding impl. + let boxed = Box::new(Person { + name: "Alice".to_owned(), + }); + assert_eq!(read_name(&boxed), "Alice"); } ``` -which generates the identical bound and the identical read. The explicit form above appears in an error -message or an expansion, not in code you type. +`Person` derives the access, so it satisfies exactly the bound `GreetHello` requires. `Person` is a +[value context](/docs/reference/glossary#value-context) and the component is +[self-targeted](/docs/reference/glossary#self-targeted-component): the wired type is the data the +method reads. -Field access also passes through smart pointers with no extra work, because the trait carries a `Deref` -forwarding impl: +Written idiomatically, the bound is not visible. The same read is an +[`#[implicit]`](../../attributes/implicit.md) argument, which generates the identical bound and +read: ```rust -let boxed: Box = Box::new(Person { name: "Alice".to_owned() }); - -assert_eq!(boxed.get_field(PhantomData::), "Alice"); +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } +} ``` ## When to use it -**Bound against `HasField` only when the ergonomic constructs cannot do the job**, which is rarely. The -ordering is settled and worth following. - -- **Use an [`#[implicit]`](../../attributes/implicit.md) argument by default.** It reads a field of the - implementation's own context as a plain parameter, generating this bound for you. It covers the common - case, including a field several implementations each read. -- **Use [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** when the read must be a *named* trait, - when the field lives on a type other than the context, or when the getter should carry a type inferred - from the field. An implicit argument cannot reach those cases. -- **Use [`#[cgp_getter]`](../../macros/cgp_getter.md) with [`UseField`](../../providers/use_field.md)** only - when a context needs to choose *which* field the getter reads. That is the advanced case and costs a - wiring line per context. -- **Write the bound by hand** when none of those fit, such as a bound on a type that is not `Self`. It is - an ordinary trait bound. - -Three neighbours are easy to confuse with it. [`HasFields`](../shape/has_fields.md), the plural, is the -whole-shape view, for code that must process *every* field rather than one named one; the two are -complementary and often derived together. [`HasFieldMut`](./has_field_mut.md) is the same access with -mutation, not an alternative. And [`FieldGetter`](./field_getter.md) is not an alternative either but the -provider-side mirror: you bound against `HasField` and wire `FieldGetter`. +**Bound on `HasField` by hand only when the ergonomic constructs cannot do the job**, which is +rarely. The order to try them in: + +- **An [`#[implicit]`](../../attributes/implicit.md) argument** reads a field of the + implementation's own context as a plain parameter, and covers the common case, including a field + several implementations each read. +- **[`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md)** makes the read a named trait, reaches + a field on a type other than the context, or infers a type from the field, which an implicit + argument cannot. +- **[`#[cgp_getter]`](../../macros/cgp_getter.md) with [`UseField`](../../providers/use_field.md)** + lets each context choose which field the getter reads, at the cost of a wiring line per context. +- **A hand-written bound** fits the rest, such as a generic function over any context with the + field, as `read_name` is above. + +Three neighbours are easy to confuse with it. [`HasFields`](../shape/has_fields.md), the plural, is +the whole-shape view for code that processes every field. [`HasFieldMut`](./has_field_mut.md) is the +same access with mutation. And [`FieldGetter`](./field_getter.md) is the provider-side form: you +bound against `HasField` and wire `FieldGetter`. ## Under the hood -The per-field impls come almost entirely from -[`#[derive(HasField)]`](../../derives/derive_has_field.md). What the trait module itself supplies is the -blanket impls that let the access compose, and two of them belong to this trait. - -**Smart-pointer forwarding.** `HasField` is implemented for any type whose -[`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) target implements it, so a `Box` or -a newtype resolves a read to the inner struct. It is marked so the compiler does **not** suggest it in a -diagnostic, which keeps a missing-field error pointed at the struct that lacks the field rather -than at the pointer. - -**`UseContext` as a field getter.** The provider side connects to wiring through one impl: -[`UseContext`](../../providers/use_context.md) implements [`FieldGetter`](./field_getter.md) for any context -that already has the field, delegating straight through. +`#[derive(HasField)]` emits one `HasField` impl per field, keyed by the field's `Symbol!`, and the +trait module adds two impls that make access compose. The first forwards through +[`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html), so a smart pointer or newtype has the +fields of its target: ```rust -impl FieldGetter for UseContext +#[diagnostic::do_not_recommend] +impl HasField for Context where - Context: HasField, + Context: DerefMap, + Target: HasField, { - type Value = Field; + type Value = Value; - fn get_field(context: &Context, _tag: PhantomData) -> &Self::Value { - context.get_field(PhantomData) + fn get_field(&self, tag: PhantomData) -> &Self::Value { + self.map_deref(|context| context.get_field(tag)) } } ``` -The remaining blanket impls belong to the neighbours: [`HasFieldMut`](./has_field_mut.md) carries the -`DerefMut` forwarding, and [`MapField`](./map_field.md) is free for every `HasField` whose tag is -`'static`. +`DerefMap` is a private helper over `Deref` that passes the borrow through a higher-ranked closure, +so the target needs no `'static` bound, and `#[diagnostic::do_not_recommend]` keeps the compiler +from suggesting this impl in errors, so a missing-field error names the struct that lacks the field. +The second connects field access to wiring: [`UseContext`](../../providers/use_context.md) +implements [`FieldGetter`](./field_getter.md) for any context that has the field, delegating +straight through, as that page shows. ## Common Mistakes -**Two spellings of a name are unrelated types.** `Symbol!("first_name")` and `Symbol!("firstName")` have -nothing to do with each other, and a mismatch reports as a missing `HasField` bound rather than as a -typo. This is the usual cause of a read that "should" work. +**Two spellings of a name are unrelated types.** A context whose field is `firstName` does not meet +a bound on `Symbol!("first_name")`, and the mismatch reports as a missing `HasField` bound, with +each name spelled out character by character: + +```text +error[E0277]: the trait bound `Person: cgp::prelude::HasField>>>>>>>>>>>` is not satisfied +... + but trait `HasField>>>>>>>>>>` is implemented for it +``` + +The leading number is the name's length, and the `Chars` list spells it. A tuple field is keyed by +[`Index`](../../types/index_type.md), never by `Symbol!("0")`. + +**A type that derefs to a target cannot also derive a field its target has.** The `Deref` forwarding +impl already covers every tag of the target, so a second impl for the same tag overlaps. A `Wrapper` +that derefs to a `Person` with `name`, and also derives its own `name` field, fails: + +```rust +#[derive(HasField)] +pub struct Wrapper { + pub name: String, + pub person: Person, +} + +impl Deref for Wrapper { + type Target = Person; -**A tuple field is keyed by [`Index`](../../types/index_type.md), never by a `Symbol!` of the number.** -`Index<0>` and `Symbol!("0")` are different types. + fn deref(&self) -> &Person { + &self.person + } +} +``` + +```text +error[E0119]: conflicting implementations of trait `cgp::prelude::HasField>>>>>` for type `Wrapper` +``` -**`Value` can be pinned or left open.** Omitting `Value = T` when you meant to pin it produces an -inference failure further along rather than at the bound. +Fields the target lacks are unaffected, so rename the wrapper's field or drop the `Deref` impl. -**The `PhantomData` argument is required and carries the tag.** `self.get_field(PhantomData)` works only -where inference can determine the tag from context; at an ambiguous site write -`PhantomData::`. +**The `PhantomData` argument carries the tag.** `self.get_field(PhantomData)` works only where +inference can determine the tag, as in a function whose only `HasField` bound fixes it; elsewhere +write `PhantomData::`. -**It returns a reference, always.** There is no owning read; cloning is the caller's business, and an -[`#[implicit]`](../../attributes/implicit.md) argument inserts a `.clone()` for you when the -parameter is owned. +**It returns a reference, always.** There is no owning read; an +[`#[implicit]`](../../attributes/implicit.md) argument inserts a `.clone()` when the parameter is +owned. ## Related constructs -- [`#[derive(HasField)]`](../../derives/derive_has_field.md): generates the per-field impls; what a context - writes. +- [`#[derive(HasField)]`](../../derives/derive_has_field.md): generates the per-field impls. - [`HasFieldMut`](./has_field_mut.md): the mutable extension. -- [`FieldGetter`](./field_getter.md): the provider-side mirror that gets wired. -- [`MapField`](./map_field.md): the lifetime-safe form for reaching into a nested value. -- [`HasFields`](../shape/has_fields.md): the plural, whole-shape counterpart. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that key a field. +- [`FieldGetter`](./field_getter.md): the provider-side form that gets wired. +- [`MapField`](./map_field.md): reading through a field in generic code. +- [`HasFields`](../shape/has_fields.md): the whole-shape counterpart. +- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that key a + field. - [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to read a field. -- [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) and [`#[cgp_getter]`](../../macros/cgp_getter.md): - getter traits over the same access. -- [`UseField`](../../providers/use_field.md): the provider-side implementation of `FieldGetter`. -- [`HasBuilder`](../builder/has_builder.md): where `HasField` reappears on a partial record, gated on presence. The ideas behind it: -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): why a field requirement belongs on - the implementation rather than the interface. -- [Implicit arguments](/docs/concepts/implicit-arguments): the ergonomic surface built on this trait. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): why a field requirement belongs + on the implementation rather than the interface. +- [Implicit arguments](/docs/concepts/implicit-arguments): the ergonomic surface built on this + trait. ## Source -- [`has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs): +- [`traits/has_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field.rs): `HasField`, `FieldGetter`, the `Deref` forwarding, and the `UseContext` impl --- diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index eb98b09f..7d34f6c9 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -11,12 +11,14 @@ Mutable tag-keyed field access. ## Overview -[`HasField`](./has_field.md) lets an implementation read a field of a context it cannot name, by keying -on the field's name as a type. `HasFieldMut` is the same access with mutation: it hands back a `&mut` -rather than a `&`, so an implementation can change a value in place. +[`HasField`](./has_field.md) lets an implementation read a field of a +[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the +values it needs as its fields, by keying on the field's name as a type. `HasFieldMut` is the same +access with mutation: it hands back a `&mut` rather than a `&`, so an implementation can change a +value in place. **You do not opt into it.** [`#[derive(HasField)]`](../../derives/derive_has_field.md) always emits -`HasFieldMut` beside `HasField`, so every derived field is mutably accessible and there is no +`HasFieldMut` beside `HasField`, so every derived field is mutably accessible, and there is no derive-level way to make one read-only. ## Definition @@ -30,34 +32,30 @@ pub trait HasFieldMut: HasField { } ``` -It is a **[supertrait](/docs/reference/glossary#supertrait) extension** rather than an alternative: `HasFieldMut` requires `HasField`, -so the field's type comes from that supertrait's `Value`, and bounding on the mutable form gives you the -read as well. `get_field_mut` takes `&mut self` and returns `&mut Self::Value`, with the -`PhantomData` argument naming the field exactly as [`HasField`](./has_field.md)'s `get_field` does. +It is a [supertrait](/docs/reference/glossary#supertrait) extension rather than an alternative: +`HasFieldMut` requires `HasField`, so the field's type comes from that supertrait's +`Value`, and bounding on the mutable form gives the read as well. `get_field_mut` takes `&mut self` +and names the field with `PhantomData`, as `get_field` does. ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. - -The call reads like its immutable sibling, with `PhantomData` naming the field: +It is in the prelude, so `use cgp::prelude::*;` is enough. An implementation that mutates declares +the bound on `Self`, pinning `Value` through the supertrait, and takes `&mut self`: ```rust -*context.get_field_mut(PhantomData::) += 1; +Self: HasFieldMut ``` -An implementation that mutates declares the bound on `Self` the same way it declares a read, and needs -`&mut self` on the method: +The call reads like its immutable sibling: ```rust -Self: HasFieldMut +*self.get_field_mut(PhantomData::) += 1; ``` -[`#[derive(HasField)]`](../../derives/derive_has_field.md) generates it beside `HasField` for every -field. - ## Examples -An implementation that updates a counter on its context: +A provider that increments a counter on its context, and a generic function that resets it through +a `Box`: ```rust use cgp::prelude::*; @@ -87,79 +85,101 @@ delegate_components! { CounterComponent: IncrementCounter, } } -``` -**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component)**: `App` stands for the application and carries the wiring. +check_components! { + App { + CounterComponent, + } +} + +pub fn reset(context: &mut Context) +where + Context: HasFieldMut, +{ + *context.get_field_mut(PhantomData) = 0; +} -Mutable access passes through a smart pointer too, via a `DerefMut` forwarding impl, so a -`Box` resolves the write to the inner struct. +pub fn demo() { + let mut app = App { counter: 0 }; + app.count(); + app.count(); + assert_eq!(app.counter, 2); + + // `Box` has the field mutably through the `DerefMut` forwarding impl. + let mut boxed = Box::new(App { counter: 5 }); + reset(&mut boxed); + assert_eq!(boxed.counter, 0); +} +``` + +`App` is an [environmental context](/docs/reference/glossary#environmental-context) that carries the +counter, and the component is [self-targeted](/docs/reference/glossary#self-targeted-component). ## When to use it -**Bound on it only when the implementation genuinely writes**, and prefer the read-only bound otherwise. -Requiring mutation where none happens narrows what a caller can pass for no benefit. A context behind a -shared reference satisfies [`HasField`](./has_field.md) but not this. - -- **Use [`HasField`](./has_field.md)** whenever the value is only read. This is the overwhelmingly common - case. -- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** for a read, since it generates the - immutable bound for you and reads like an ordinary parameter. Implicit arguments cover mutable access - too, under the access rules on that page, which is the idiomatic route before reaching for this trait - by hand. -- **Reach for [`MutFieldGetter`](./mut_field_getter.md)** when the mutation must be *wired* rather than - bounded: the provider-side mirror of this trait. -- **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable and - threads state through handler outputs instead, which composes better with the +**Bound on it only when the implementation writes**, and use [`HasField`](./has_field.md) otherwise. +Requiring mutation where none happens narrows what a caller can pass, since a context behind a +shared reference satisfies `HasField` but not this. + +- **An [`#[implicit]`](../../attributes/implicit.md) argument** covers mutable access too, under the + access rules on that page, and is the idiomatic route before a hand-written bound. +- **[`MutFieldGetter`](./mut_field_getter.md)** is the provider-side form, for a getter whose + mutable access a context chooses by wiring. +- **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable + and passes state through handler outputs instead, which composes with the [handler family](../../components/handler/handler.md). ## Under the hood -`HasFieldMut` is implemented for any type whose -[`DerefMut`](https://doc.rust-lang.org/std/ops/trait.DerefMut.html) target implements it, with the target -additionally bounded `'static`. That extra bound is the one asymmetry with -[`HasField`](./has_field.md#under-the-hood)'s `Deref` forwarding, and it is why a borrowed context inside -a smart pointer sometimes resolves the read and not the write. +`#[derive(HasField)]` emits one `HasFieldMut` impl beside each `HasField` impl. The trait module +adds one forwarding impl through +[`DerefMut`](https://doc.rust-lang.org/std/ops/trait.DerefMut.html): -Like the immutable forwarding, it is marked so the compiler does **not** suggest it in a diagnostic, -which keeps a missing-field error pointed at the struct that lacks the field rather than at the pointer. +```rust +#[diagnostic::do_not_recommend] +impl HasFieldMut for Context +where + Context: DerefMut, + Target: HasFieldMut + 'static, +{ + fn get_field_mut(&mut self, tag: PhantomData) -> &mut Self::Value { + self.deref_mut().get_field_mut(tag) + } +} +``` -The per-field impls themselves come from [`#[derive(HasField)]`](../../derives/derive_has_field.md), one -`HasFieldMut` beside each `HasField`. +The `'static` bound on the target is the one asymmetry with [`HasField`](./has_field.md)'s `Deref` +forwarding, which passes the borrow through a helper instead. So a smart pointer to a type holding a +borrowed value forwards the read and not the write. ## Common Mistakes -**It is not separately opt-in.** The derive always emits it, so there is no way to expose a field as -read-only through the derive. Restricting mutation is a matter of what the implementations declare. +**It is not separately opt-in.** The derive always emits it, so a field cannot be exposed read-only +through the derive; restricting mutation is a matter of what implementations declare. -**The `DerefMut` forwarding requires `'static` on the target**, where the `Deref` forwarding does not. A -context holding a borrowed value can therefore satisfy the read and not the write, and the error names -the lifetime rather than the field. +**The `DerefMut` forwarding requires `'static` on the target**, where the `Deref` forwarding does +not. A context behind a smart pointer to borrowed data satisfies the read and not the write, and the +error names the lifetime rather than the field. **Bounding on it implies the read.** `Self: HasFieldMut` already gives `get_field`, so adding -`HasField` alongside is redundant. - -**`Value` lives on the supertrait.** Pin it as `HasFieldMut`. The associated -type is inherited, not redeclared. - -**A tuple field is keyed by [`Index`](../../types/index_type.md)**, exactly as for the immutable form. +`HasField` beside it is redundant. ## Related constructs -- [`HasField`](./has_field.md): the supertrait, and where the tag-keyed access is explained in full. -- [`MutFieldGetter`](./mut_field_getter.md): the provider-side mirror of this trait. +- [`HasField`](./has_field.md): the supertrait, where tag-keyed access is explained in full. +- [`MutFieldGetter`](./mut_field_getter.md): the provider-side form of this trait. - [`#[derive(HasField)]`](../../derives/derive_has_field.md): generates both impls per field. -- [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to reach a field, including mutably. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that key a field. -- [`UseField`](../../providers/use_field.md): the provider that implements the wired form. +- [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to reach a field, including + mutably. The ideas behind it: -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): why a field requirement belongs on - the implementation rather than the interface. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): why a field requirement belongs + on the implementation rather than the interface. ## Source -- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs): +- [`traits/has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs): `HasFieldMut`, `MutFieldGetter`, and the `DerefMut` forwarding --- diff --git a/docs/reference/traits/field-access/index.md b/docs/reference/traits/field-access/index.md index 3a6aee2f..ed075154 100644 --- a/docs/reference/traits/field-access/index.md +++ b/docs/reference/traits/field-access/index.md @@ -1,4 +1,5 @@ --- +description: 'The traits for reading one field of a context by its type-level name: the bounds an implementation states, and the provider-side forms a getter is wired through.' sidebar_label: 'Overview' sidebar_position: 0 --- @@ -9,11 +10,12 @@ Reading one field of a context by its type-level name, from code that cannot nam ## Overview -A CGP implementation most often reads a value out of its **context**, the type a method runs on, -without naming that type. It reads the field by keying on the field's *name as a type*, so any context -with a matching field satisfies the bound. These traits are the foundation -the ergonomic surface stands on: an [`#[implicit]`](../../attributes/implicit.md) argument, a -[`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) method, and a +A CGP implementation most often reads a value out of its +[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the +values it needs as its fields, without naming that type. It reads the field by keying on the field's +*name as a type*, so any context with a matching field satisfies the bound. These traits are the +foundation the ergonomic surface stands on: an [`#[implicit]`](../../attributes/implicit.md) +argument, a [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) method, and a [`UseField`](../../providers/use_field.md) wiring entry all generate a bound on the traits here. The traits divide on two axes: read versus write, and consumer-side versus provider-side. @@ -21,14 +23,15 @@ The traits divide on two axes: read versus write, and consumer-side versus provi The **consumer traits** are what an implementation bounds against on its own context. [`HasField`](has_field.md) reads a field, and [`HasFieldMut`](has_field_mut.md) adds mutable access. -The **provider-side mirrors** are what a getter component is wired through, so that a context chooses by -wiring which field answers a getter. [`FieldGetter`](field_getter.md) is the read side and +The **provider-side mirrors** are what a getter component is wired through, by way of +[`WithProvider`](../../providers/with_provider.md), so that a context chooses by wiring which field +answers a getter. [`FieldGetter`](field_getter.md) is the read side and [`MutFieldGetter`](mut_field_getter.md) the write side. -The **lifetime-safe forms** let a getter reach into a nested value without forcing its type to be -`'static`. [`MapField`](map_field.md) is the consumer side and [`FieldMapper`](field_mapper.md) the -provider side, and [`ChainGetters`](../../providers/chain_getters.md) composes them to descend into a -nested context. +The **read-through forms** let generic code and getter providers read a field of a field without a +lifetime bound on the intermediate type. [`MapField`](map_field.md) is the consumer side and +[`FieldMapper`](field_mapper.md) the provider side, and +[`ChainGetters`](../../providers/chain_getters.md) composes them to descend into a nested context. ## The ideas behind them diff --git a/docs/reference/traits/field-access/map_field.md b/docs/reference/traits/field-access/map_field.md index 48497a36..645eae51 100644 --- a/docs/reference/traits/field-access/map_field.md +++ b/docs/reference/traits/field-access/map_field.md @@ -1,39 +1,34 @@ --- +title: 'MapField — read through a field' +description: 'A blanket helper on every HasField that passes a borrowed field to a closure, so generic code can read a field of a field without a lifetime bound.' sidebar_label: 'MapField' sidebar_position: 5 --- # `MapField` -Reading through a field without forcing its type to be `'static`. - -:::info - -### Generated machinery - -**You will not call `map_field` yourself.** It is a blanket impl that every -[`HasField`](./has_field.md) already has, and [`ChainGetters`](../../providers/chain_getters.md) is what -uses it to descend into a nested context. This page explains the lifetime problem it exists to solve, -which is why reaching a nested field is a provider rather than two chained reads. The one case for calling it directly is writing a getter provider of your own that has to descend. - -::: +Read through a field of a generic context without adding a lifetime bound on its type. ## Overview -Chaining field reads looks like it should just work: read a field, then read a field of *that*. It does -not, and the reason is about lifetimes rather than about CGP. Writing -`context.get_field(..).get_field(..)` makes the intermediate `Value` outlive the borrow it came from, -which the compiler can only accept by requiring it to be `'static`. - -`MapField` sidesteps that by taking a closure instead of returning the intermediate borrow. +Reading a field of a field looks like two chained reads, and on a concrete type it is. In generic +code it is not: when a [**context**](/docs/reference/glossary#context), the type the method runs on, +which supplies the values it needs as its fields, holds a field of a generic type `Inner`, +`context.get_field(..).get_field(..)` returns a borrow that the compiler cannot tie to the context's +borrow without knowing that `Inner` outlives it. A free function can add that bound, but a provider +trait's method has its lifetimes fixed by the trait, so there the only bound that fits is `'static`. -**You will not normally call it.** [`ChainGetters`](../../providers/chain_getters.md) uses -`map_field`, which is how a getter reaches a field on a nested context. +`MapField` avoids the problem by taking a closure instead of returning the intermediate borrow. +`map_field` reads the field and hands it to a closure that returns a borrow derived from it, and the +closure's higher-ranked bound lets the compiler tie the result to the context's own borrow. Every +[`HasField`](./has_field.md) has it through a blanket impl, and its provider-side twin +[`FieldMapper`](./field_mapper.md) is what [`ChainGetters`](../../providers/chain_getters.md) uses +to descend into a nested value. ## Definition -`MapField` extends [`HasField`](./has_field.md) with a `map_field` method that reads the field -and hands it to a closure: +`MapField` extends [`HasField`](./has_field.md) with a `map_field` method that reads the +field and hands it to a closure: ```rust pub trait MapField: HasField { @@ -45,35 +40,47 @@ pub trait MapField: HasField { } ``` -It is a [supertrait](/docs/reference/glossary#supertrait) extension of [`HasField`](./has_field.md), so `Value` comes from the supertrait. -`map_field` takes `&self`, the `PhantomData` that names the field, and a `mapper` closure, and it -returns `&T`. The higher-ranked `for<'a>` bound on the closure is the whole trick: the closure must work -for *any* lifetime, so the compiler ties the returned borrow to the field's own lifetime rather than -demanding `'static`. +It is a [supertrait](/docs/reference/glossary#supertrait) extension, so `Value` comes from +`HasField`. The `for<'a>` bound on `mapper` requires the closure to work for any lifetime of its +argument, so the `&T` it returns is a borrow of the field, and `map_field` can return it as a borrow +of `self`. ## Usage -**It is not in the prelude**, one of only two members of the `HasField` group that are not. Import it -from `cgp::core::field::traits`: +It is not in the prelude. Import it from `cgp::core::field::traits`: ```rust use cgp::core::field::traits::MapField; ``` -It is a supertrait extension of [`HasField`](./has_field.md), so bounding on it gives you the plain read -as well. The `mapper` argument is an ordinary closure; the `for<'a>` binder makes it unusual, because a -closure that captures a reference of some *specific* lifetime will not satisfy it. - -**Nobody implements it.** It is a blanket impl for every `HasField` whose tag is `'static`, so every -field access gains `map_field` for free. +Nothing implements it by hand: a blanket impl gives it to every `HasField` whose tag is `'static`, +which every [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md) is. So +bounding a context on `HasField` is enough to call `map_field` on it. ## Examples -Reaching a field of a field, which is the case the trait exists for: +A generic function that reads the `name` of a context's `inner` field, and the wiring that performs +the same descent for a getter: ```rust -use cgp::core::field::traits::MapField; use cgp::prelude::*; +use cgp::core::field::impls::ChainGetters; +use cgp::core::field::traits::MapField; + +pub fn inner_name(context: &Context) -> &String +where + Context: HasField, + Inner: HasField, +{ + context.map_field(PhantomData::, |inner| { + inner.get_field(PhantomData::) + }) +} + +#[cgp_getter(NameGetter)] +pub trait HasName { + fn name(&self) -> &String; +} #[derive(HasField)] pub struct Inner { @@ -85,99 +92,105 @@ pub struct Outer { pub inner: Inner, } -let outer = Outer { inner: Inner { name: "Alice".to_owned() } }; - -let name: &String = outer.map_field( - PhantomData::, - |inner| inner.get_field(PhantomData::), -); - -assert_eq!(name, "Alice"); -``` - -The closure receives the borrowed `Inner` and returns a borrow *derived from it*, so no intermediate -outlives its source and no `'static` bound appears anywhere. - -In practice this is what a wiring line expresses instead: - -```rust delegate_components! { Outer { - NameGetterComponent: ChainGetters>, + NameGetterComponent: WithProvider< + ChainGetters, + UseField, + ]>, + >, } } -``` -which is the same descent, chosen at the wiring site rather than written at the call site. +check_components! { + Outer { + NameGetterComponent, + } +} -## When to use it +pub fn demo() { + let outer = Outer { + inner: Inner { + name: "Alice".to_owned(), + }, + }; -**Reach for [`ChainGetters`](../../providers/chain_getters.md) rather than this trait.** The provider is the -construct; `map_field` is the mechanism it is built from, and calling it by hand means writing at a call -site what the wiring could have decided. + assert_eq!(inner_name(&outer), "Alice"); + assert_eq!(outer.name(), "Alice"); +} +``` -- **Use [`ChainGetters`](../../providers/chain_getters.md)** to reach a field on a nested context. -- **Use [`HasField`](./has_field.md)** for a field of the context itself, which is the common case and - needs none of this. -- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** before either, since it covers every - same-context read. -- **Reach for [`FieldMapper`](./field_mapper.md)** when the same descent must happen on the provider - side, where the context is a type argument rather than `self`. +The closure receives the borrowed `Inner` and returns a borrow derived from it, so no bound on +`Inner`'s lifetime appears. The `ChainGetters` entry reaches the same field for the `HasName` +getter, chosen at the wiring site rather than written at a call site. `Outer` is a +[value context](/docs/reference/glossary#value-context). + +## When to use it -Call `map_field` directly only when you are writing machinery of the same kind, such as a new getter -provider, and even then the existing ones usually compose. +**Reach for [`ChainGetters`](../../providers/chain_getters.md) to give a getter a nested field**, +and for an [`#[implicit]`](../../attributes/implicit.md) argument or [`HasField`](./has_field.md) +for a field of the context itself, which is the common case and needs none of this. Call `map_field` +directly when generic code of your own must read through a field, as `inner_name` does, and use +[`FieldMapper`](./field_mapper.md) when that code is a provider, where the context is a type +argument rather than `self`. ## Under the hood -`MapField` is a blanket impl for every [`HasField`](./has_field.md) whose **tag** is `'static`: +The blanket impl reads the field once and passes the borrow to the mapper: ```rust -// for every Context: HasField, where Tag: 'static +impl MapField for Context +where + Context: HasField, + Tag: 'static, +{ + fn map_field( + &self, + tag: PhantomData, + mapper: impl for<'a> FnOnce(&'a Self::Value) -> &'a T, + ) -> &T { + mapper(self.get_field(tag)) + } +} ``` -The bound is on the *tag*, not on the value, and that is the point. A tag is a -[`Symbol!`](../../macros/symbol.md) or an [`Index`](../../types/index_type.md), both of which are `'static` by -construction, so the bound costs nothing. The value stays free, which is exactly what the naive chained -read could not achieve. - -Inside, the implementation reads the field once and hands the borrow to the mapper. Because the mapper -is higher-ranked over `'a`, its return borrow is tied to the field borrow rather than to any fixed -lifetime, and the result can be returned to the caller. - -[`ChainGetters`](../../providers/chain_getters.md) composes descents by nesting these calls, one per -segment, so an arbitrarily deep path stays lifetime-correct with no `'static` anywhere in the chain. +The `'static` bound is on the tag, not on the value, and that is the point: the tag is always +`'static`, while the value, the intermediate whose lifetime the chained read could not express, +stays free. ## Common Mistakes -**It is not in the prelude.** Import from `cgp::core::field::traits`. -[`FieldMapper`](./field_mapper.md) is the other non-prelude member of the group; everything else in it -is in the prelude. +**Two chained reads fail in generic code.** Written as +`context.get_field(PhantomData::).get_field(PhantomData::)`, +the example's `inner_name` fails: + +```text +error[E0311]: the parameter type `Inner` may not live long enough +``` -**The closure must be higher-ranked.** A closure that captures a reference with a particular lifetime -will not satisfy `for<'a>`, and the error talks about lifetime bounds rather than about the closure's -body, which is confusing the first time. +rustc suggests naming the lifetime and adding `Inner: 'a`, which works in a free function. In a +provider trait's method, whose signature the trait fixes, that bound cannot be written, so use +`map_field` or [`FieldMapper`](./field_mapper.md) instead. -**The mapper must return a borrow *derived from* its argument.** Returning a reference to something else -in scope does not satisfy the binder, which is the safety the design buys. +**The closure must return a borrow derived from its argument.** Returning a reference to something +else does not satisfy the `for<'a>` binder, and the error talks about lifetimes rather than about +the closure's body. -**It cannot map to an owned value.** The signature returns `&T`. A getter that must produce a value uses -[`MRef`](../../types/mref.md) instead. +**It cannot map to an owned value.** The signature returns `&T`; a getter that must produce a value +returns [`MRef`](../../types/mref.md) instead. -**`MapField` is not [`MapFields`](../type-level/map_fields.md) and not [`MapType`](../type-level/map_type.md).** The names -are similar: this one is a lifetime helper for reading a nested field, `MapFields` applies a marker across -a type-level list, and `MapType` names one field's storage on a partial type. +**`MapField` is not [`MapFields`](../type-level/map_fields.md) or +[`MapType`](../type-level/map_type.md).** This one reads through a field; `MapFields` applies a +marker across a type-level list, and `MapType` names one field's storage on a partial record. ## Related constructs -- [`FieldMapper`](./field_mapper.md): the provider-side mirror of this trait. +- [`FieldMapper`](./field_mapper.md): the provider-side twin. - [`HasField`](./has_field.md): the supertrait, and the plain read. -- [`ChainGetters`](../../providers/chain_getters.md): the provider that uses `map_field` to descend. -- [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to read a field of the context itself. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags, which are `'static` by - construction. +- [`ChainGetters`](../../providers/chain_getters.md): the provider that descends through nested + fields. - [`MRef`](../../types/mref.md): the return type for a getter that may produce rather than lend. -- [`MapFields`](../type-level/map_fields.md) and [`MapType`](../type-level/map_type.md): the two similarly-named traits that do - something else. The ideas behind it: @@ -185,7 +198,7 @@ The ideas behind it: ## Source -- [`map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs): +- [`traits/map_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/map_field.rs): `MapField` and `FieldMapper` --- diff --git a/docs/reference/traits/field-access/mut_field_getter.md b/docs/reference/traits/field-access/mut_field_getter.md index eb1b73a7..94d15389 100644 --- a/docs/reference/traits/field-access/mut_field_getter.md +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -1,31 +1,34 @@ --- +title: 'MutFieldGetter — wired mutable field access' +description: 'The provider-side form of HasFieldMut: a getter with a &mut self method takes any MutFieldGetter provider, such as UseField, through WithProvider.' sidebar_label: 'MutFieldGetter' sidebar_position: 4 --- # `MutFieldGetter` -The provider-side mirror of `HasFieldMut`: wired field access that can mutate. +The provider-side form of `HasFieldMut`: wired field access that can mutate. :::info ### Generated machinery -**You are not expected to implement `MutFieldGetter`.** -[`#[cgp_getter]`](../../macros/cgp_getter.md) generates it alongside its [supertrait](/docs/reference/glossary#supertrait), and -[`UseField`](../../providers/use_field.md) satisfies both. What you write is the wiring entry; this page -explains what the mutable half of that entry provides. The one case for implementing it by hand is a provider whose mutable access is not a plain field read. +**You are not expected to name `MutFieldGetter` in wiring.** A getter component whose method takes +`&mut self` accepts any provider of it through +[`WithProvider`](../../providers/with_provider.md), and +[`UseField`](../../providers/use_field.md) implements it, so the wiring entry is `WithField` as +for a read. The one case for implementing it yourself is a provider whose mutable access no existing +provider expresses. ::: ## Overview -[`FieldGetter`](./field_getter.md) is field access in provider-trait shape, so that a context can choose -by wiring which field answers a getter. `MutFieldGetter` is the same thing with mutation: it hands back a -`&mut` rather than a `&`. - -Completing the square, the traits divide on two axes, consumer versus provider and read versus -write: +[`FieldGetter`](./field_getter.md) is field access in provider shape, so that a +[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the +values it needs as its fields, can choose by wiring which field answers a getter. `MutFieldGetter` +is the same with mutation: it hands back a `&mut` rather than a `&`, for a getter whose method takes +`&mut self`. The four field-access traits divide on two axes: | | you bound against | you wire | |---|---|---| @@ -34,8 +37,8 @@ write: ## Definition -`MutFieldGetter` extends [`FieldGetter`](./field_getter.md) with one method that returns a -mutable borrow: +`MutFieldGetter` extends [`FieldGetter`](./field_getter.md) with one method that +returns a mutable borrow: ```rust pub trait MutFieldGetter: FieldGetter { @@ -43,34 +46,39 @@ pub trait MutFieldGetter: FieldGetter { } ``` -It stands to [`FieldGetter`](./field_getter.md) exactly as [`HasFieldMut`](./has_field_mut.md) stands to -[`HasField`](./has_field.md): a **supertrait extension** rather than an alternative, with the field's type -inherited from the supertrait's `Value`. `Self` is the provider and `Context` is the type being mutated; -`get_field_mut` takes the context by mutable reference and returns `&mut Self::Value`, with the -`PhantomData` argument naming the field. +It stands to `FieldGetter` as [`HasFieldMut`](./has_field_mut.md) stands to `HasField`: a +[supertrait](/docs/reference/glossary#supertrait) extension, with the field's type inherited from +the supertrait's `Value`. `Self` is the provider and `Context` is the type being mutated, passed as +`&mut Context`. ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. +It is in the prelude, so `use cgp::prelude::*;` is enough. A getter whose method takes `&mut self` +and returns `&mut T` is wired the same way as a read, with `WithField` from +`cgp::core::field::impls`: -As with its immutable sibling you rarely name the trait. What you write is a wiring entry naming a -provider that implements it. [`UseField`](../../providers/use_field.md) does, so a getter component wired -to `UseField` supports both the read and the write. +```rust +delegate_components! { + App { + CounterGetterComponent: WithField, + } +} +``` -Writing an impl by hand is the escape hatch for a provider whose mutable access is not a plain field -read, and it is an ordinary trait impl on a marker type of your own. Implementing it means implementing -[`FieldGetter`](./field_getter.md) too, since that is the supertrait. +A bare `UseField` entry works too, through the impl `#[cgp_getter]` emits for `UseField` +directly. Implementing the trait yourself means implementing `FieldGetter` as well, its supertrait. ## Examples -A getter component whose mutable access is chosen by wiring: +A mutable getter named `counter_mut` that reads the `request_count` field: ```rust use cgp::prelude::*; +use cgp::core::field::impls::WithField; #[cgp_getter(CounterGetter)] pub trait HasCounter { - fn counter(&self) -> &u64; + fn counter_mut(&mut self) -> &mut u64; } #[derive(HasField)] @@ -80,76 +88,93 @@ pub struct App { delegate_components! { App { - CounterGetterComponent: UseField, + CounterGetterComponent: WithField, + } +} + +check_components! { + App { + CounterGetterComponent, } } + +pub fn demo() { + let mut app = App { request_count: 0 }; + *app.counter_mut() += 1; + assert_eq!(app.request_count, 1); +} ``` -**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** The getter reads `request_count` though it is named `counter`, -and because [`UseField`](../../providers/use_field.md) implements `MutFieldGetter` as well, a provider that -holds `&mut App` can write through the same wiring. +`UseField` implements `MutFieldGetter` for any context whose field has +[`HasFieldMut`](./has_field_mut.md), which the derive always emits. `App` is an +[environmental context](/docs/reference/glossary#environmental-context), and the getter is +[self-targeted](/docs/reference/glossary#self-targeted-component). ## When to use it -**Wire it only when the mutable access must be chosen per context**, which is rarer than the read case -and rarer still than mutation generally. +**Wire mutable access only when a context must choose which field is mutated**, which is rarer than +the read case and rarer still than mutation generally. -- **Use an [`#[implicit]`](../../attributes/implicit.md) argument** for a field the implementation reaches - on its own context. The access rules on that page cover mutable access, and no provider is involved. -- **Use [`HasFieldMut`](./has_field_mut.md)** when the implementation should simply *require* mutable - access rather than have it wired. -- **Use [`FieldGetter`](./field_getter.md)** when the wired access is read-only, which is the common case. - Requiring mutation narrows what a context can supply for no benefit. -- **Consider whether the context should be mutated at all.** Much CGP code keeps contexts immutable and - threads state through handler outputs instead. +- **An [`#[implicit]`](../../attributes/implicit.md) argument** reaches a field of the + implementation's own context, mutably too, with no provider involved. +- **[`HasFieldMut`](./has_field_mut.md)** is the bound for an implementation that requires mutable + access rather than having it wired. +- **[`FieldGetter`](./field_getter.md)** is the form for read-only wired access, the common case. ## Under the hood -`MutFieldGetter` adds one method to its supertrait and no new resolution path: a provider that implements -[`FieldGetter`](./field_getter.md) and can also produce a `&mut` implements this too, and -[`UseField`](../../providers/use_field.md) does for any context whose field is derived. +For a one-method getter whose method takes `&mut self`, `#[cgp_getter]` bounds its `WithProvider` +impl on `MutFieldGetter` instead of `FieldGetter`. `cargo cgp expand` on the example shows: -The route from a wired getter back to a context's own fields runs through -[`HasFieldMut`](./has_field_mut.md), whose `DerefMut` forwarding carries the `'static` bound on the -target that its immutable counterpart does not, so a context behind a smart pointer holding borrowed -data can satisfy the wired read and not the wired write. - -## Common Mistakes +```rust +impl<__Context__, __Provider__> CounterGetter<__Context__> for WithProvider<__Provider__> +where + __Provider__: MutFieldGetter<__Context__, CounterGetterComponent, Value = u64>, +{ + fn counter_mut(__context__: &mut __Context__) -> &mut u64 { + __Provider__::get_field_mut( + __context__, + ::core::marker::PhantomData::, + ) + } +} +``` -**`Self` is the provider, not the context.** The context is the first type parameter, and it arrives as -`&mut Context` in the method rather than as `&mut self`. +`UseField` implements `MutFieldGetter` for every tag it is asked under, through the context's +`HasFieldMut`, and [`UseFieldRef`](../../providers/use_field_ref.md) implements it through +`AsMut`. `UseContext` has no `MutFieldGetter` impl, so a mutable getter cannot be wired through +`WithContext`. -**Implementing it means implementing [`FieldGetter`](./field_getter.md).** It is a supertrait, so the -read half is not optional. +## Common Mistakes -**`Value` lives on the supertrait**, so pin it there rather than redeclaring it. +**`Self` is the provider, not the context.** The context is the first type parameter, and arrives as +`&mut Context` rather than as `&mut self`. -**The `'static` bound behind `DerefMut` can bite.** A wired read that resolves and a wired write that -does not usually means the context is behind a smart pointer over borrowed data. See -[`HasFieldMut`](./has_field_mut.md#common-mistakes). +**Implementing it means implementing [`FieldGetter`](./field_getter.md).** It is a supertrait, so +the read half is not optional. -**Requiring it where a read would do narrows the contexts that fit**, since a provider holding `&Context` -cannot satisfy it. +**The `'static` bound behind `DerefMut` can bite.** A context behind a smart pointer to borrowed +data satisfies the read and not the write; see [`HasFieldMut`](./has_field_mut.md#common-mistakes). ## Related constructs -- [`FieldGetter`](./field_getter.md): the supertrait, and where the wired form is explained in full. +- [`FieldGetter`](./field_getter.md): the supertrait, where wired access is explained in full. - [`HasFieldMut`](./has_field_mut.md): the consumer side you bound against. -- [`HasField`](./has_field.md): the read half of the consumer side. -- [`UseField`](../../providers/use_field.md): the provider that implements both halves. -- [`#[cgp_getter]`](../../macros/cgp_getter.md): the macro that makes a getter a full component. -- [`#[implicit]`](../../attributes/implicit.md): the idiomatic way to reach a field. -- [`Symbol!`](../../macros/symbol.md) and [`Index`](../../types/index_type.md): the tags that key a field. +- [`UseField`](../../providers/use_field.md) and [`WithField`](../../providers/with_field.md): the + provider that implements both halves, and its `WithProvider` alias. +- [`#[cgp_getter]`](../../macros/cgp_getter.md): the macro whose mutable getters take this trait. The ideas behind it: -- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the duality this trait is - an instance of. +- [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the split this trait + is an instance of. ## Source -- [`has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs): +- [`traits/has_field_mut.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_field_mut.rs): `MutFieldGetter`, `HasFieldMut`, and the `DerefMut` forwarding +- [`impls/use_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/use_field.rs): + the `UseField` impls --- diff --git a/docs/reference/traits/index.md b/docs/reference/traits/index.md index 719f387d..fbfb645a 100644 --- a/docs/reference/traits/index.md +++ b/docs/reference/traits/index.md @@ -1,4 +1,5 @@ --- +description: 'The traits CGP''s macros generate and consume, grouped by job: wiring and checking, field access, extensible data, namespaces, and monads.' sidebar_label: 'Overview' sidebar_position: 0 --- diff --git a/docs/reference/traits/shape/from_fields.md b/docs/reference/traits/shape/from_fields.md index 914bf420..8da90d1f 100644 --- a/docs/reference/traits/shape/from_fields.md +++ b/docs/reference/traits/shape/from_fields.md @@ -11,11 +11,11 @@ Rebuilding a concrete value from its shape. ## Overview -[`ToFields`](./to_fields.md) takes a value apart into an anonymous list of named entries. `FromFields` is -the return journey. It closes the loop for generic code: decompose a value, work on the entries without -naming the type, and put a concrete value back together at the end. Both directions go through the -identical `Fields` type, so **the shapes line up by construction rather than by check**: there is -nothing to validate and nothing that can fail. +[`ToFields`](./to_fields.md) takes a value apart into an anonymous list of named entries. +`FromFields` is the return journey. It closes the loop for generic code: decompose a value, work on +the entries without naming the type, and put a concrete value back together at the end. Both +directions go through the identical `Fields` type, so **the shapes line up by construction rather +than by check**: there is nothing to validate and nothing that can fail. ## Definition @@ -27,23 +27,24 @@ pub trait FromFields: HasFields { } ``` -It [supertraits](/docs/reference/glossary#supertrait) [`HasFields`](./has_fields.md), so `from_fields` takes that trait's `Fields` shape and a -bound on `FromFields` gives you `Fields` as well. It is an associated function rather than a method, -because there is no value to call it on, so the call reads `Person::from_fields(fields)`, or -`T::from_fields(fields)` in generic code. +It [supertraits](/docs/reference/glossary#supertrait) [`HasFields`](./has_fields.md), so +`from_fields` takes that trait's `Fields` shape and a bound on `FromFields` gives you `Fields` as +well. It is an associated function rather than a method, because there is no value to call it on, so +the call reads `Person::from_fields(fields)`, or `T::from_fields(fields)` in generic code. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. The impls come from -[`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all five shape traits together. +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all five shape traits +together. -The argument must be **exactly** `Self::Fields`: the same entries, the same tags, in the same order. A -shape that merely has the same field names in a different order is a different type and will not be -accepted, which makes the conversion total. +The argument must be **exactly** `Self::Fields`: the same entries, the same tags, in the same order. +A shape that merely has the same field names in a different order is a different type and will not +be accepted, which makes the conversion total. ## Examples -Rebuilding after a round trip: +A generic round trip through the shape, for a struct and an enum: ```rust use cgp::prelude::*; @@ -54,72 +55,102 @@ pub struct Config { pub port: u16, } -let config = Config { host: "localhost".to_owned(), port: 8080 }; - -let fields = config.clone().to_fields(); -let config_again = Config::from_fields(fields); - -assert_eq!(config, config_again); -``` - -In generic code it is the half that names the destination: +#[derive(Clone, Debug, PartialEq, HasFields)] +pub enum Shape { + Circle(f64), + Square(f64), +} -```rust -fn rebuild(fields: T::Fields) -> T +pub fn round_trip(value: T) -> T where - T: FromFields, + T: ToFields + FromFields, { - T::from_fields(fields) + T::from_fields(value.to_fields()) +} + +pub fn demo() { + let config = Config { + host: "localhost".to_owned(), + port: 8080, + }; + assert_eq!(round_trip(config.clone()), config); + + assert_eq!(round_trip(Shape::Square(2.0)), Shape::Square(2.0)); } ``` -An enum rebuilds the same way, from a [`Sum!`](../../macros/sum.md) rather than a product: the arm that is -present becomes the variant that is constructed. +An enum rebuilds from a [`Sum!`](../../macros/sum.md) rather than a product: the arm that is present +becomes the variant that is constructed. ## When to use it -**Bound on it when generic code produces a concrete value from entries it has assembled or transformed.** -Pair it with [`ToFields`](./to_fields.md) for a round trip, and require only one of the two when only one -direction happens. +**Bound on it when generic code produces a concrete value from entries it has assembled or +transformed.** Pair it with [`ToFields`](./to_fields.md) for a round trip, and require only one of +the two when only one direction happens. - **[`ToFields`](./to_fields.md)** for the decomposition half. - **[`HasFields`](./has_fields.md) alone** when the code names the shape and never builds a value. -- **The [builder family](../builder/has_builder.md)** when the value is assembled *incrementally*, from pieces - arriving at different times. `from_fields` needs the whole shape at once, already complete; - [`HasBuilder`](../builder/has_builder.md) tracks presence field by field, and the extensible builder - pattern uses it. -- **[`FromVariant`](../variant/from_variant.md)** when an enum is built from *one* named variant rather than from - a whole shape. That is the far more common way to construct an enum generically. -- **A plain constructor** when the type is concrete. Nothing about `from_fields` improves on a struct - literal where one can be written. +- **The [builder family](../builder/has_builder.md)** when the value is assembled *incrementally*, + from pieces arriving at different times. `from_fields` needs the whole shape at once, already + complete; [`HasBuilder`](../builder/has_builder.md) tracks presence field by field, and the + extensible builder pattern uses it. +- **[`FromVariant`](../variant/from_variant.md)** when an enum is built from *one* named variant + rather than from a whole shape. That is the far more common way to construct an enum generically. +- **A plain constructor** when the type is concrete. Nothing about `from_fields` improves on a + struct literal where one can be written. ## Under the hood -The conversion destructures the `Cons` chain positionally and unwraps each entry's value: +The conversion destructures the `Cons` chain positionally and unwraps each entry's value. +`cargo cgp expand` on the example's `Config` shows: ```rust -impl FromFields for Person { - fn from_fields(Cons(name, Cons(age, Nil)): Self::Fields) -> Self { - Self { name: name.value, age: age.value } +impl FromFields for Config { + fn from_fields(Cons(host, Cons(port, Nil)): Self::Fields) -> Self { + Self { + host: host.value, + port: port.value, + } } } ``` -Note the pattern in the argument position: the shape is matched apart in the signature itself, one node -per field, terminated by `Nil`. Because the chain is built and matched in declaration order, this is the -exact inverse of [`to_fields`](./to_fields.md): no lookup by name happens at run time, and the tags -exist only to make the types distinct. +The shape is matched apart in the signature itself, one node per field, terminated by `Nil`. Because +the chain is built and matched in declaration order, this is the exact inverse of +[`to_fields`](./to_fields.md): nothing is looked up by name at run time, and the tags exist only to +make the types distinct. An enum's impl is the dual, a `match` down the `Either` chain, and the +example's `Shape` ends in an empty match on the `Void` terminator: -An enum's impl is the dual: a `match` over the `Either` chain, each arm reconstructing the corresponding -variant, with the `Void` terminator unreachable by construction. +```rust +impl FromFields for Shape { + fn from_fields(rest: Self::Fields) -> Self { + match rest { + Either::Left(field) => { + let field = field.value; + Self::Circle(field) + } + Either::Right(rest) => { + match rest { + Either::Left(field) => { + let field = field.value; + Self::Square(field) + } + Either::Right(rest) => match rest {} + } + } + } + } +} +``` ## Common Mistakes -**It is an associated function, not a method.** Write `T::from_fields(fields)`; there is no receiver. +**It is an associated function, not a method.** Write `T::from_fields(fields)`; there is no +receiver. -**The shape must match exactly.** Same tags, same value types, same order. Two structs with identical -field names in different orders have unrelated `Fields` types, and the mismatch is reported against the -whole chain rather than against the field that moved. +**The shape must match exactly.** Same tags, same value types, same order. Two structs with +identical field names in different orders have unrelated `Fields` types, and the mismatch is +reported against the whole chain rather than against the field that moved. **A newtype's shape is the inner type**, not a one-element product, so `from_fields` on `struct Wrapper(String)` takes a `String`. @@ -127,23 +158,24 @@ whole chain rather than against the field that moved. **It supertraits [`HasFields`](./has_fields.md)**, so naming both in a bound is redundant. **It cannot build a value incrementally.** The whole shape is required at once. Assembling from -independent pieces is [`HasBuilder`](../builder/has_builder.md)'s job, and reaching for `from_fields` there means -constructing the complete product by hand first. +independent pieces is [`HasBuilder`](../builder/has_builder.md)'s job, and reaching for +`from_fields` there means constructing the complete product by hand first. -**There is no borrowing counterpart.** [`ToFieldsRef`](./to_fields_ref.md) has no `FromFieldsRef`, because -a borrowed shape cannot yield an owned value. +**There is no borrowing counterpart.** [`ToFieldsRef`](./to_fields_ref.md) has no `FromFieldsRef`, +because a borrowed shape cannot yield an owned value. ## Related constructs - [`ToFields`](./to_fields.md): the reverse conversion, and the one usually written first. - [`HasFields`](./has_fields.md): the supertrait that names the shape. -- [`ToFieldsRef`](./to_fields_ref.md) and [`HasFieldsRef`](./has_fields_ref.md): the borrowed half of - the family, which has no rebuild. +- [`ToFieldsRef`](./to_fields_ref.md) and [`HasFieldsRef`](./has_fields_ref.md): the borrowed half + of the family, which has no rebuild. - [`FromVariant`](../variant/from_variant.md): constructing an enum from one named variant. -- [`HasBuilder`](../builder/has_builder.md): incremental assembly, as against this wholesale conversion. +- [`HasBuilder`](../builder/has_builder.md): incremental assembly, as against this wholesale + conversion. - [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl. -- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md): what - a shape is made of. +- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and + [`Field`](../../types/field.md): what a shape is made of. The ideas behind it: diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index 1dafa3da..a6b8979f 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -11,17 +11,17 @@ A type's whole shape, as a single type. ## Overview -Some code needs one field of a type. Other code needs the *shape*, every field, its name, and its type, -so it can walk them: a serializer, a validator, a builder that merges two structs, a dispatcher that -routes an enum to a handler per variant. None of those can be written one field at a time, and none can -name the concrete type either. +Some code needs one field of a type. Other code needs the *shape*, every field, its name, and its +type, so it can walk them: a serializer, a validator, a builder that merges two structs, a +dispatcher that routes an enum to a handler per variant. None of those can be written one field at a +time, and none can name the concrete type either. `HasFields` gives a type that shape as a single associated type. Where -[`HasField`](../field-access/has_field.md), the singular, answers *"give me this field"*, `HasFields` answers -*"describe all of them at once"*. +[`HasField`](../field-access/has_field.md), the singular, answers *"give me this field"*, +`HasFields` answers *"describe all of them at once"*. -**The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md).** What you write is the -derive; what you bound against is the trait. +**The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md).** What you write +is the derive; what you bound against is the trait. ## Definition @@ -33,12 +33,12 @@ pub trait HasFields { } ``` -`Self` is the type being described, a struct or an enum, and `Fields` is its shape written as a single -type. For a struct that shape is a [`Product!`](../../macros/product.md) list with one -[`Field`](../../types/field.md) entry per field, each pairing a value type with its type-level name. For -an enum it is a [`Sum!`](../../macros/sum.md) instead, the same idea for a choice rather than a -combination. There is no method, because describing a type is not an operation, so the associated type is -the whole trait. +`Self` is the type being described, a struct or an enum, and `Fields` is its shape written as a +single type. For a struct that shape is a [`Product!`](../../macros/product.md) list with one +[`Field`](../../types/field.md) entry per field, each pairing a value type with its type-level name. +For an enum it is a [`Sum!`](../../macros/sum.md) instead, the same idea for a choice rather than a +combination. There is no method, because describing a type is not an operation, so the associated +type is the whole trait. For `struct Person { name: String, age: u8 }` the shape is: @@ -54,10 +54,11 @@ type Fields = Product![ **It is in the prelude**, so `use cgp::prelude::*;` is enough. The shape's construction follows one rule everywhere: a named field or variant is keyed by -[`Symbol!`](../../macros/symbol.md), a positional field by [`Index`](../../types/index_type.md), a struct becomes -a `Cons`/`Nil` product, and an enum becomes an `Either`/`Void` sum. A single-field tuple struct is the one -special case, with its `Fields` the inner type directly rather than a one-element product. The -[derive's page](../../derives/derive_has_fields.md) covers that and the other shapes in full. +[`Symbol!`](../../macros/symbol.md), a positional field by [`Index`](../../types/index_type.md), +a struct becomes a `Cons`/`Nil` product, and an enum becomes an `Either`/`Void` sum. A single-field +tuple struct is the one special case, with its `Fields` the inner type directly rather than a +one-element product. The [derive's page](../../derives/derive_has_fields.md) covers that and the +other shapes in full. **Four companions turn the description into a two-way door**, each on its own page: [`HasFieldsRef`](./has_fields_ref.md) names the borrowed shape, and [`ToFields`](./to_fields.md), @@ -66,107 +67,132 @@ value and it. This trait names the shape; those move values through it. ### Bounding on the shape -The point of all this is a bound. Generic code writes `T: HasFields` and recurses over `T::Fields`, so it -applies to any type that derives the shape, including one declared in another crate: +Generic code bounds on `T: HasFields` and works with `T::Fields`, so it applies to any type that +derives the shape, including one declared in another crate. The bound can also pin the shape, which +is how the example below checks it: ```rust -fn describe() -> &'static str +pub fn assert_shape() where - T: HasFields, + T: HasFields, { - // recurse over T::Fields - todo!() } ``` -Require this trait alone when the code only *names* the shape; require one of the conversions when values +Require this trait alone when the code only names the shape, and one of the conversions when values have to move through it. +**`HasFields` accepts every enum variant shape**: unit, tuple, multi-field, and struct-style. A +variant with one unnamed field carries its payload directly, a unit variant carries `Nil`, and any +other variant carries its fields as a nested product. The derives that take an enum apart need +exactly one unnamed payload per variant; this one only describes the variant, so it does not. + ## Examples -Deriving it alongside [`HasField`](../field-access/has_field.md) is the common pairing, giving one struct both indexed -and structural access: +The shapes a struct, an enum, and a one-field tuple struct derive, each checked by a generic bound +that pins `Fields`: ```rust use cgp::prelude::*; -#[derive(Clone, Debug, Eq, PartialEq, HasField, HasFields)] +#[derive(HasField, HasFields)] pub struct Config { pub host: String, pub port: u16, } -``` -`Config::Fields` is now `Product![Field, Field]`, which is -what a generic routine recurses over. +pub struct Circle { + pub radius: f64, +} -An enum's shape is a sum rather than a product: +pub struct Rectangle { + pub width: f64, + pub height: f64, +} -```rust #[derive(HasFields)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } -``` -giving `Sum![Field, Field]`. +#[derive(HasFields)] +pub struct UserId(pub u64); + +pub fn assert_shape() +where + T: HasFields, +{ +} + +pub fn demo() { + assert_shape::, Field]>( + ); + assert_shape::< + Shape, + Sum![Field, Field], + >(); + assert_shape::(); +} +``` -**`HasFields` is the one member of the extensible-data family that accepts every variant shape** (unit, -tuple, multi-field, and struct-style) because it only *describes* a variant rather than deconstructing -it. The derives that take an enum apart need exactly one unnamed payload per variant; this one does not. +`assert_shape` compiles only if the type's `Fields` is exactly the second parameter, so each call is +a compile-time check of one shape. `Config` also derives [`HasField`](../field-access/has_field.md), +the common pairing that gives one struct both indexed and whole-shape access. A variant with one +unnamed field carries its payload directly, so `Shape`'s entries hold `Circle` and `Rectangle`, and +the one-field `UserId` has the bare `u64` as its shape rather than a one-element product. ## When to use it **Bound on `HasFields` when code must process a type's whole shape; bound on -[`HasField`](../field-access/has_field.md) when it needs one named field.** That is the entire distinction, and the two -are complementary rather than ranked. Most types that need both derive both in one `#[derive(...)]`. +[`HasField`](../field-access/has_field.md) when it needs one named field.** That is the entire +distinction, and the two are complementary rather than ranked. Most types that need both derive both +in one `#[derive(...)]`. - **`HasFields` alone** when the code only names the shape: a `where` clause, an associated-type projection, or a type-level computation like [`AppendProduct`](../type-level/append_product.md). - **[`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md)** when values move through the shape in both directions. -- **[`ToFieldsRef`](./to_fields_ref.md)** when the value must not be consumed. Requiring `ToFields` where - a borrow would do forces callers to clone. +- **[`ToFieldsRef`](./to_fields_ref.md)** when the value must not be consumed. Requiring `ToFields` + where a borrow would do forces callers to clone. -Two things this is not. It is **not runtime reflection**: a type has a shape only because it opted in -with a derive, there is nothing to query at run time, and the shape is a type rather than data. That buys -static checking and no runtime cost, and it costs one thing: a foreign type you cannot patch has no -shape at all. And it is **not the whole extensible-data story**. The shape describes a type, while -building one up field by field or taking one apart variant by variant is the -[builder](../builder/has_builder.md) and [extractor](../variant/extract_field.md) families, bundled with this one by -[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md). +Two things this is not. It is **not runtime reflection**: a type has a shape only because it opted +in with a derive, there is nothing to query at run time, and the shape is a type rather than data. +That buys static checking and no runtime cost, and it costs one thing: a foreign type you cannot +patch has no shape at all. And it is **not the whole extensible-data story**. The shape describes a +type, while building one up field by field or taking one apart variant by variant is the +[builder](../builder/has_builder.md) and [extractor](../variant/extract_field.md) families, bundled +with this one by [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md). ## Under the hood The trait module defines only the bare trait; every impl comes from -[`#[derive(HasFields)]`](../../derives/derive_has_fields.md). The part that matters is the type the derive -puts in `Fields`, and the sugar hides one level of structure: +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md). `cargo cgp expand` on the example's +`Config` and `Shape` shows the types it puts in `Fields`: ```rust -impl HasFields for Person { +impl HasFields for Config { type Fields = Product![ - Field, - Field, + Field, Field + ]; +} +impl HasFields for Shape { + type Fields = Sum![ + Field, Field ]; } ``` -`Product![A, B]` is `Cons>`, so a `Fields` type in an error message is a `Cons` chain -rather than the sugar. The [type-level lists](../../types/index.md) page covers reading it. - -An enum's shape is the dual: an `Either` chain terminated by `Void` rather than a `Cons` chain terminated -by `Nil`, with each arm tagged by the variant name and carrying that variant's own fields as a nested -product. - -Because a shape is a type rather than a value, nothing about this costs anything at run time. It exists -to give the trait solver something to recurse over. +`Product![A, B]` is `Cons>` and `Sum![A, B]` is `Either>`, so a +`Fields` type in an error message is a chain rather than the sugar, which the [type-level +lists](../../types/index.md) page covers reading. Because a shape is a type rather than a value, +nothing about it costs anything at run time. ## Common Mistakes -**`HasFields` and [`HasField`](../field-access/has_field.md) differ by one letter and do not overlap.** The plural is -the whole shape and takes structs and enums; the singular is per-field access and takes only structs. -Their derives are likewise distinct. +**`HasFields` and [`HasField`](../field-access/has_field.md) differ by one letter and do not +overlap.** The plural is the whole shape and takes structs and enums; the singular is per-field +access and takes only structs. Their derives are likewise distinct. **A newtype's shape is the inner type, not a one-element product.** `struct Wrapper(String)` has `Fields = String`. Generic code written against a `Cons` chain will not match it. The @@ -176,9 +202,9 @@ Their derives are likewise distinct. different orders have different `Fields` types. Name-driven conversions cope; code written against a literal `Cons` chain does not. -**Two enum variant names are reserved.** A variant called `Fields` or `FieldsRef` collides with these -associated types and the derive fails; the [derive's page](../../derives/derive_has_fields.md) lists it with -the other reserved names. +**Two enum variant names are reserved.** A variant called `Fields` or `FieldsRef` collides with +these associated types and the derive fails; the [derive's page](../../derives/derive_has_fields.md) +lists it with the other reserved names. **There is no method.** `Fields` is a type. Getting a *value* in that shape is [`ToFields`](./to_fields.md). @@ -192,25 +218,28 @@ the other reserved names. [`ToFieldsRef`](./to_fields_ref.md): the conversions between a value and its shape. - [`HasField`](../field-access/has_field.md): the singular counterpart, per-field access. - [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md): bundles this with the builder and extractor. -- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md): the list types a shape is built - from. +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md): the list types a shape is + built from. - [`Field`](../../types/field.md): one entry: a value paired with its type-level name. - [Type-level lists](../../types/index.md): the `Cons`/`Nil` and `Either`/`Void` chains underneath. -- [`AppendProduct`](../type-level/append_product.md): the operations that compute new shapes from old ones. -- [`CanUpcast`](../casting/can_upcast.md) and [`CanBuildFrom`](../casting/can_build_from.md): conversions between two - types whose shapes overlap, driven by this one. +- [`AppendProduct`](../type-level/append_product.md): the operations that compute new shapes from + old ones. +- [`CanUpcast`](../casting/can_upcast.md) and [`CanBuildFrom`](../casting/can_build_from.md): + conversions between two types whose shapes overlap, driven by this one. The ideas behind it: - [Extensible records](/docs/concepts/extensible-records): a struct as a product of named fields. -- [Extensible variants](/docs/concepts/extensible-variants): the enum half, and the expression problem. +- [Extensible variants](/docs/concepts/extensible-variants): the enum half, and the expression + problem. ## Source - [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs): `HasFields` and `HasFieldsRef` -- Derive codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) +- Derive codegen: + [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) --- diff --git a/docs/reference/traits/shape/has_fields_ref.md b/docs/reference/traits/shape/has_fields_ref.md index 361ca672..5ff4117f 100644 --- a/docs/reference/traits/shape/has_fields_ref.md +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -14,18 +14,18 @@ A type's whole shape, with every value borrowed. ### Generated machinery **You are not expected to implement `HasFieldsRef`.** -[`#[derive(HasFields)]`](../../derives/derive_has_fields.md) emits it alongside the owned shape. What -generic code writes is a bound; this page explains the type the derive produces, including the reserved -lifetime name that shows up in an error message. +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md) emits it alongside the owned shape. +What generic code writes is a bound; this page explains the type the derive produces, including the +reserved lifetime name that shows up in an error message. ::: ## Overview -[`HasFields`](./has_fields.md) describes a type as a list of named entries holding owned values. Code -that only *reads* a value should not have to consume it to walk its shape (a validator, a serializer, a -routine that inspects a struct and hands it back), so there is a second description in which every entry -holds a borrow instead. +[`HasFields`](./has_fields.md) describes a type as a list of named entries holding owned values. +Code that only *reads* a value should not have to consume it to walk its shape (a validator, a +serializer, a routine that inspects a struct and hands it back), so there is a second description in +which every entry holds a borrow instead. ## Definition @@ -39,53 +39,69 @@ pub trait HasFieldsRef { } ``` -`Self` is the type being described. `FieldsRef<'a>` is the same shape as [`HasFields`](./has_fields.md)'s -`Fields`, with each value borrowed for `'a`. It is a **generic associated type**, which lets one trait -describe the shape at whatever lifetime a caller has, and the `where Self: 'a` clause keeps the borrowed -shape from outliving the value it describes. There is no method, because the trait only names a type; the -conversion that produces a value in this shape is [`ToFieldsRef`](./to_fields_ref.md). +`Self` is the type being described. `FieldsRef<'a>` is the same shape as +[`HasFields`](./has_fields.md)'s `Fields`, with each value borrowed for `'a`. It is a **generic +associated type**, which lets one trait describe the shape at whatever lifetime a caller has, and +the `where Self: 'a` clause keeps the borrowed shape from outliving the value it describes. There is +no method, because the trait only names a type; the conversion that produces a value in this shape +is [`ToFieldsRef`](./to_fields_ref.md). -The two shape traits are independent rather than one extending the other, and that is deliberate: a type -may be described owned, borrowed, or both. +The two shape traits are independent rather than one extending the other, and that is deliberate: a +type may be described owned, borrowed, or both. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits this alongside -[`HasFields`](./has_fields.md) rather than as a separate opt-in. +The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits this +alongside [`HasFields`](./has_fields.md) rather than as a separate opt-in. ## Examples -The borrowed shape of a struct pairs each name with a reference: +The borrowed shapes of two structs at the `'static` lifetime, one with a field that is itself a +reference: ```rust use cgp::prelude::*; -#[derive(HasField, HasFields)] +#[derive(HasFields)] pub struct Config { pub host: String, pub port: u16, } -// Config::FieldsRef<'a> is -// Product![Field, Field] -``` - -Bounding on it is how generic read-only code names what it walks: +#[derive(HasFields)] +pub struct Greeting<'a> { + pub name: &'a str, +} -```rust -fn inspect(value: &T) +pub fn assert_shape_ref<'a, T, FieldsRef>() where - T: HasFieldsRef + ToFieldsRef, + T: HasFieldsRef = FieldsRef> + 'a, { - let _fields = value.to_fields_ref(); - // walk the borrowed shape; `value` is untouched +} + +pub fn demo() { + assert_shape_ref::< + 'static, + Config, + Product![ + Field, + Field, + ], + >(); + assert_shape_ref::< + 'static, + Greeting<'static>, + Product![ + Field, + ], + >(); } ``` -Requiring [`ToFields`](./to_fields.md) there instead would force every caller to give up its value or -clone it. +Each entry's value type `T` becomes `&'a T`, so `Greeting<'a>`'s `name: &'a str` field appears as +`&'__a &'a str`, a borrow of a borrow, which the example instantiates at `'static` for both. ## When to use it @@ -94,55 +110,54 @@ clone it. - **Use [`HasFields`](./has_fields.md)** when the code takes ownership: building, converting, destructuring. -- **Use `HasFieldsRef` + [`ToFieldsRef`](./to_fields_ref.md)** when the original must survive. This is - the weaker requirement, so prefer it when it suffices. -- **Use [`HasField`](../field-access/has_field.md)** when only one named field is needed. The whole-shape traits are - for code that walks everything. +- **Use `HasFieldsRef` + [`ToFieldsRef`](./to_fields_ref.md)** when the original must survive. This + is the weaker requirement, so prefer it when it suffices. +- **Use [`HasField`](../field-access/has_field.md)** when only one named field is needed. The + whole-shape traits are for code that walks everything. Being precise about which shape trait a routine requires pays, because each one narrows what a caller must supply. ## Under the hood -The derive emits the borrowed shape with a **reserved lifetime name**, `'__a`, so it cannot collide with -a lifetime of yours: +The derive emits the borrowed shape with a **reserved lifetime name**, `'__a`, so it cannot collide +with a lifetime of yours. `cargo cgp expand` on the example's `Config` shows: ```rust -impl HasFieldsRef for Person { +impl HasFieldsRef for Config { type FieldsRef<'__a> = Product![ - Field, - Field, + Field, Field ] where Self: '__a; } ``` -The transformation is uniform: each entry's value type `T` becomes `&'__a T`, and the list is otherwise -untouched: same length, same order, same tags. An enum's borrowed shape is the dual, an `Either` chain -whose arms carry borrowed payloads. +The transformation is uniform: each entry's value type `T` becomes `&'__a T`, and the list is +otherwise untouched: same length, same order, same tags. An enum's borrowed shape is the dual, an +`Either` chain whose arms carry borrowed payloads. Because the rewrite is per-entry rather than structural, **a field that is already a reference gains -another one**: a field of type `&'a Name` appears as `&'__a &'a Name`. That is correct, and it is the one -thing about this trait that surprises people in an error message. +another one**: a field of type `&'a Name` appears as `&'__a &'a Name`. That is correct, and it is +the one thing about this trait that surprises people in an error message. ## Common Mistakes **A field that is already borrowed gets a second borrow.** `&'a Name` becomes `&'__a &'a Name` in `FieldsRef`, which reads oddly in a diagnostic and is not a bug. -**The `where Self: 'a` clause propagates.** Any bound naming `FieldsRef<'a>` inherits it, so a signature -that borrows the shape usually needs the lifetime spelled out rather than elided. +**The `where Self: 'a` clause propagates.** Any bound naming `FieldsRef<'a>` inherits it, so a +signature that borrows the shape usually needs the lifetime spelled out rather than elided. -**It is emitted by [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), not by a derive of its -own.** There is no `#[derive(HasFieldsRef)]`. +**It is emitted by [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), not by a derive of +its own.** There is no `#[derive(HasFieldsRef)]`. -**Naming the shape is not obtaining it.** [`ToFieldsRef`](./to_fields_ref.md) is the method half; this -trait has none. +**Naming the shape is not obtaining it.** [`ToFieldsRef`](./to_fields_ref.md) is the method half; +this trait has none. -**Two enum variant names are reserved**, `Fields` and `FieldsRef`, because these associated types are -named through `Self::…` in the generated impls. The -[derive's page](../../derives/derive_has_fields.md) lists them with the others. +**Two enum variant names are reserved**, `Fields` and `FieldsRef`, because these associated types +are named through `Self::…` in the generated impls. The [derive's +page](../../derives/derive_has_fields.md) lists them with the others. ## Related constructs @@ -150,10 +165,11 @@ named through `Self::…` in the generated impls. The - [`ToFieldsRef`](./to_fields_ref.md): the conversion that produces a value in this shape. - [`ToFields`](./to_fields.md) and [`FromFields`](./from_fields.md): the owned conversions. - [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl. -- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md): the list types a shape is built - from. +- [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md): the list types a shape is + built from. - [`Field`](../../types/field.md): one entry of a shape. -- [`MapTypeRef`](../type-level/map_type_ref.md): the borrow markers the extractor family uses for the same job. +- [`MapTypeRef`](../type-level/map_type_ref.md): the borrow markers the extractor family uses for + the same job. The ideas behind it: @@ -163,7 +179,8 @@ The ideas behind it: - [`has_fields.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/has_fields.rs): `HasFieldsRef` and `HasFields` -- Derive codegen: [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) +- Derive codegen: + [`cgp_data/derive_has_fields/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields) --- diff --git a/docs/reference/traits/shape/index.md b/docs/reference/traits/shape/index.md index 500931c3..fa44c78a 100644 --- a/docs/reference/traits/shape/index.md +++ b/docs/reference/traits/shape/index.md @@ -1,4 +1,5 @@ --- +description: 'The traits that describe a type''s whole shape as one type-level list, and the conversions that move a value into and out of it.' sidebar_label: 'Overview' sidebar_position: 0 --- diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index dc33f856..38fd422a 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -13,17 +13,17 @@ Taking a value apart into its shape. [`HasFields`](./has_fields.md) *names* a type's shape. `ToFields` produces a value in it. -That lets generic code stop working on a concrete struct and start working on an anonymous list -of named entries: the form a serializer walks, a converter rewrites, or a merge consumes. The -concrete type goes in; a [`Product!`](../../macros/product.md) of [`Field`](../../types/field.md) entries comes -out, or a [`Sum!`](../../macros/sum.md) for an enum. +That lets generic code stop working on a concrete struct and start working on an anonymous list of +named entries: the form a serializer walks, a converter rewrites, or a merge consumes. The concrete +type goes in; a [`Product!`](../../macros/product.md) of [`Field`](../../types/field.md) entries +comes out, or a [`Sum!`](../../macros/sum.md) for an enum. -**It consumes the value.** That is the difference from [`ToFieldsRef`](./to_fields_ref.md), and it is the -commonest surprise in the family, because the two read alike at a call site. +**It consumes the value.** That is the difference from [`ToFieldsRef`](./to_fields_ref.md), and it +is the commonest surprise in the family, because the two read alike at a call site. -The reverse direction is [`FromFields`](./from_fields.md), and the two round-trip through the identical -`Fields` type, so generic code can decompose, transform, and rebuild with the shapes lining up by -construction rather than by check. +The reverse direction is [`FromFields`](./from_fields.md), and the two round-trip through the +identical `Fields` type, so generic code can decompose, transform, and rebuild with the shapes +lining up by construction rather than by check. ## Definition @@ -35,21 +35,21 @@ pub trait ToFields: HasFields { } ``` -It [supertraits](/docs/reference/glossary#supertrait) [`HasFields`](./has_fields.md), so `to_fields` returns that trait's `Fields` shape and a -bound on `ToFields` gives you `Fields` as well. The method takes `self` by value, so it consumes the -value to produce the owned shape. +It [supertraits](/docs/reference/glossary#supertrait) [`HasFields`](./has_fields.md), so `to_fields` +returns that trait's `Fields` shape and a bound on `ToFields` gives you `Fields` as well. The method +takes `self` by value, so it consumes the value to produce the owned shape. ## Usage -**It is in the prelude**, so `use cgp::prelude::*;` is enough. Writing `T: HasFields + ToFields` is common -and harmless, though `T: ToFields` alone already gives you `Fields` through the supertrait. +**It is in the prelude**, so `use cgp::prelude::*;` is enough. Writing `T: HasFields + ToFields` is +common and harmless, though `T: ToFields` alone already gives you `Fields` through the supertrait. -The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all five shape -traits together. +The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all +five shape traits together. ## Examples -A value round-tripping through its shape: +A value taken apart by a generic function, read from the product, and rebuilt: ```rust use cgp::prelude::*; @@ -60,28 +60,30 @@ pub struct Config { pub port: u16, } -let config = Config { host: "localhost".to_owned(), port: 8080 }; - -let fields = config.clone().to_fields(); // Config -> the product -let config_again = Config::from_fields(fields); // the product -> Config - -assert_eq!(config, config_again); -``` - -The `clone()` is there only because the assertion compares against the original. `to_fields` would -otherwise have consumed it, which is exactly the point. - -In generic code, the bound is the point: - -```rust -fn shape_of(value: T) -> T::Fields +pub fn shape_of(value: T) -> T::Fields where T: ToFields, { value.to_fields() } + +pub fn demo() { + let config = Config { + host: "localhost".to_owned(), + port: 8080, + }; + + let fields = shape_of(config.clone()); + assert_eq!(fields.1 .0.value, 8080); + + assert_eq!(Config::from_fields(fields), config); +} ``` +`fields.1.0` is the second entry of the `Cons` chain, the `port` field, and `from_fields` puts the +value back together. The `clone()` is there only because the assertion compares against the +original, which `to_fields` consumes. + ## When to use it **Bound on it when generic code must consume a value and work on its entries**, and reach for the @@ -91,22 +93,24 @@ borrowing form otherwise. borrow would do forces every caller to clone, which is the most common over-requirement in this family. - **[`FromFields`](./from_fields.md)** for the other direction, and both together for a round trip. -- **[`HasFields`](./has_fields.md) alone** when the code only *names* the shape and never holds a value - in it. -- **[`HasField`](../field-access/has_field.md)** when one named field is all that is wanted. Decomposing a whole struct - to read one entry is the wrong tool. -- **The [builder family](../builder/has_builder.md)** when a value is assembled incrementally rather than - converted wholesale. `to_fields` is a single flat conversion; a builder tracks presence field by field. +- **[`HasFields`](./has_fields.md) alone** when the code only *names* the shape and never holds a + value in it. +- **[`HasField`](../field-access/has_field.md)** when one named field is all that is wanted. + Decomposing a whole struct to read one entry is the wrong tool. +- **The [builder family](../builder/has_builder.md)** when a value is assembled incrementally rather + than converted wholesale. `to_fields` is a single flat conversion; a builder tracks presence field + by field. ## Under the hood -`Product![A, B]` is `Cons>`, so the conversion builds a `Cons` chain, one node per field, -wrapping each value into its [`Field`](../../types/field.md) entry: +`Product![A, B]` is `Cons>`, so the conversion builds a `Cons` chain, one node per +field, converting each value into its [`Field`](../../types/field.md) entry with `into`. +`cargo cgp expand` on the example's `Config` shows: ```rust -impl ToFields for Person { +impl ToFields for Config { fn to_fields(self) -> Self::Fields { - Cons(self.name.into(), Cons(self.age.into(), Nil)) + Cons(self.host.into(), Cons(self.port.into(), Nil)) } } ``` @@ -114,30 +118,32 @@ impl ToFields for Person { An error message prints that chain when structural code fails to resolve, and the [type-level lists](../../types/index.md) page covers reading it. -An enum's conversion is the dual: each concrete variant is matched onto its arm of an `Either` chain -terminated by `Void`, tagged with the variant name. +An enum's conversion is the dual: each variant is matched onto its arm of the `Either` chain, as +`Self::Square(field) => Either::Right(Either::Left(field.into()))` for the second variant of an +enum. Because the shape is built positionally from declaration order, `to_fields` and -[`from_fields`](./from_fields.md) are exact inverses by construction: there is no lookup, no matching by -name at run time, and nothing that can fail. +[`from_fields`](./from_fields.md) are exact inverses by construction: there is no lookup, no +matching by name at run time, and nothing that can fail. ## Common Mistakes -**It consumes the value.** Reach for [`ToFieldsRef`](./to_fields_ref.md) when you need to keep it. This -is the commonest surprise in the family, because the two read alike. +**It consumes the value.** Reach for [`ToFieldsRef`](./to_fields_ref.md) when you need to keep it. +This is the commonest surprise in the family, because the two read alike. -**Field order is declaration order and is part of the type.** Two structs with the same field names in -different orders produce unrelated `Fields` types, so a chain built from one will not satisfy the other. +**Field order is declaration order and is part of the type.** Two structs with the same field names +in different orders produce unrelated `Fields` types, so a chain built from one will not satisfy the +other. **A newtype's shape is the inner type**, not a one-element product, so `to_fields` on -`struct Wrapper(String)` yields a `String`. Generic code written against a `Cons` chain will not match -it. +`struct Wrapper(String)` yields a `String`. Generic code written against a `Cons` chain will not +match it. **It supertraits [`HasFields`](./has_fields.md)**, so a bound naming both is redundant rather than wrong. -**There is no fallible form.** The conversion cannot fail; anything that could is a different operation, -such as a [cast](../casting/can_downcast.md). +**There is no fallible form.** The conversion cannot fail; anything that could is a different +operation, such as a [cast](../casting/can_downcast.md). ## Related constructs @@ -146,10 +152,11 @@ such as a [cast](../casting/can_downcast.md). - [`ToFieldsRef`](./to_fields_ref.md): the borrowing form, which leaves the value intact. - [`HasFieldsRef`](./has_fields_ref.md): the shape that form produces. - [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl. -- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and [`Field`](../../types/field.md): what - a shape is made of. +- [`Product!`](../../macros/product.md), [`Sum!`](../../macros/sum.md), and + [`Field`](../../types/field.md): what a shape is made of. - [Type-level lists](../../types/index.md): the `Cons` chain the conversion builds. -- [`HasBuilder`](../builder/has_builder.md): incremental assembly, as against this wholesale conversion. +- [`HasBuilder`](../builder/has_builder.md): incremental assembly, as against this wholesale + conversion. The ideas behind it: diff --git a/docs/reference/traits/shape/to_fields_ref.md b/docs/reference/traits/shape/to_fields_ref.md index 2594aab5..d5a19fb5 100644 --- a/docs/reference/traits/shape/to_fields_ref.md +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -11,14 +11,14 @@ Walking a value's shape without consuming it. ## Overview -[`ToFields`](./to_fields.md) takes a value apart into its shape and consumes it in the process. Code that -only reads (a validator, a serializer, a routine that inspects a struct and hands it back) should not -have to. `ToFieldsRef` produces the **borrowed** shape instead. The original survives, and every entry in -the result holds a reference rather than a value. +[`ToFields`](./to_fields.md) takes a value apart into its shape and consumes it in the process. Code +that only reads (a validator, a serializer, a routine that inspects a struct and hands it back) +should not have to. `ToFieldsRef` produces the **borrowed** shape instead. The original survives, +and every entry in the result holds a reference rather than a value. **It is the weaker requirement, so prefer it wherever it suffices.** Bounding on -[`ToFields`](./to_fields.md) when a borrow would do forces every caller to give up ownership or clone, -which is the most common over-requirement in this family. +[`ToFields`](./to_fields.md) when a borrow would do forces every caller to give up ownership or +clone, which is the most common over-requirement in this family. ## Definition @@ -32,86 +32,90 @@ pub trait ToFieldsRef: HasFieldsRef { } ``` -It [supertraits](/docs/reference/glossary#supertrait) [`HasFieldsRef`](./has_fields_ref.md) rather than [`HasFields`](./has_fields.md), which is -the one structural difference from its owning counterpart [`ToFields`](./to_fields.md): the borrowed shape -and the owned shape are named by two independent traits, and each conversion supertraits the one it -produces. The method borrows `self` for `'a` and returns the borrowed -[`FieldsRef<'a>`](./has_fields_ref.md) shape at that lifetime, so the original stays intact, and the -`where Self: 'a` clause keeps the borrowed shape from outliving the value. +It [supertraits](/docs/reference/glossary#supertrait) [`HasFieldsRef`](./has_fields_ref.md) rather +than [`HasFields`](./has_fields.md), which is the one structural difference from its owning +counterpart [`ToFields`](./to_fields.md): the borrowed shape and the owned shape are named by two +independent traits, and each conversion supertraits the one it produces. The method borrows `self` +for `'a` and returns the borrowed [`FieldsRef<'a>`](./has_fields_ref.md) shape at that lifetime, so +the original stays intact, and the `where Self: 'a` clause keeps the borrowed shape from outliving +the value. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all five shape -traits together. +The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md), which emits all +five shape traits together. ## Examples -Reading a shape and keeping the value: +Reading one entry of a value's borrowed shape, and using the value afterwards: ```rust use cgp::prelude::*; -#[derive(HasField, HasFields)] +#[derive(HasFields)] pub struct Config { pub host: String, pub port: u16, } -let config = Config { host: "localhost".to_owned(), port: 8080 }; - -let fields_ref = config.to_fields_ref(); - -assert_eq!(fields_ref.0.value, &"localhost".to_owned()); -``` - -`config` is still usable afterwards, which is the whole difference from -[`to_fields`](./to_fields.md). +pub fn host_of(config: &Config) -> &String { + config.to_fields_ref().0.value +} -In generic code it is the bound that says "I will not take your value": +pub fn demo() { + let config = Config { + host: "localhost".to_owned(), + port: 8080, + }; -```rust -fn inspect(value: &T) -where - T: ToFieldsRef, -{ - let _fields = value.to_fields_ref(); - // walk the borrowed entries + assert_eq!(host_of(&config), "localhost"); + assert_eq!(config.port, 8080); // `config` is still usable } ``` +`to_fields_ref().0` is the first entry, and its `value` is a `&String` borrowed from `config`, which +stays usable. + ## When to use it **Bound on it whenever generic code reads a shape and the caller keeps the value.** This is most read-only structural code. -- **[`ToFields`](./to_fields.md)** when the code genuinely consumes: a conversion, a merge, a rebuild. +- **[`ToFields`](./to_fields.md)** when the code genuinely consumes: a conversion, a merge, a + rebuild. - **[`FromFields`](./from_fields.md)** for constructing a value, which has no borrowing counterpart: a borrowed shape cannot yield an owned value. - **[`HasFieldsRef`](./has_fields_ref.md) alone** when the code only *names* the borrowed shape. - **[`HasField`](../field-access/has_field.md)** when one named field is all that is wanted. -There is one thing this cannot do that [`ToFields`](./to_fields.md) can: hand the entries' values onward -by ownership. A routine that must move a field out of a struct needs the owning form. +There is one thing this cannot do that [`ToFields`](./to_fields.md) can: hand the entries' values +onward by ownership. A routine that must move a field out of a struct needs the owning form. ## Under the hood -The generated impl borrows each field and wraps it into the corresponding entry of the borrowed shape, -under the reserved lifetime name `'__a` that -[`HasFieldsRef`](./has_fields_ref.md#under-the-hood) declares: +The generated impl borrows each field and converts the borrow into the entry of the borrowed shape, +under the reserved lifetime name `'__a` that [`HasFieldsRef`](./has_fields_ref.md#under-the-hood) +declares. `cargo cgp expand` on the example's `Config` shows: ```rust -// each field is borrowed rather than moved: -// Cons((&self.name).into(), Cons((&self.age).into(), Nil)) +impl ToFieldsRef for Config { + fn to_fields_ref<'__a>(&'__a self) -> Self::FieldsRef<'__a> + where + Self: '__a, + { + Cons((&self.host).into(), Cons((&self.port).into(), Nil)) + } +} ``` The `where Self: 'a` clause on both the trait method and the associated type keeps the result tied to the borrow it came from, so the shape cannot outlive the value. One consequence follows from the rewrite being per-entry rather than structural: **a field that is -already a reference gains another one**, appearing as `&'__a &'a Name`. That is correct, and it is the -detail most likely to look wrong in an error message. +already a reference gains another one**, appearing as `&'__a &'a Name`. That is correct, and it is +the detail most likely to look wrong in an error message. An enum's borrowed conversion matches the concrete variant and produces the corresponding arm of the borrowed sum, with the payload borrowed rather than moved, which is also how @@ -119,18 +123,20 @@ borrowed sum, with the payload borrowed rather than moved, which is also how ## Common Mistakes -**It supertraits [`HasFieldsRef`](./has_fields_ref.md), not [`HasFields`](./has_fields.md).** Bounding on -`ToFieldsRef` does not give you `Fields`; require both traits if the code needs both shapes. +**It supertraits [`HasFieldsRef`](./has_fields_ref.md), not [`HasFields`](./has_fields.md).** +Bounding on `ToFieldsRef` does not give you `Fields`; require both traits if the code needs both +shapes. -**A field that is already borrowed gets a second borrow** in the result, which is correct and surprising. +**A field that is already borrowed gets a second borrow** in the result, which is correct and +surprising. **There is no `FromFieldsRef`.** The borrowed half of the family is read-only by construction. **The lifetime usually has to be spelled out.** A signature that returns or stores `FieldsRef<'a>` inherits the `where Self: 'a` clause and rarely elides cleanly. -**A newtype's borrowed shape is a borrow of the inner type**, not a one-element product. It is the same -special case the owned shape has. +**A newtype's borrowed shape is a borrow of the inner type**, not a one-element product. It is the +same special case the owned shape has. ## Related constructs @@ -139,8 +145,8 @@ special case the owned shape has. - [`FromFields`](./from_fields.md): rebuilding a value, which has no borrowing form. - [`HasFields`](./has_fields.md): the owned shape, and where the family is explained in full. - [`#[derive(HasFields)]`](../../derives/derive_has_fields.md): generates this impl. -- [`HasExtractorRef`](../variant/has_extractor_ref.md): the same borrow-rather-than-consume idea on the enum - side. +- [`HasExtractorRef`](../variant/has_extractor_ref.md): the same borrow-rather-than-consume idea on + the enum side. - [`Field`](../../types/field.md): one entry of a shape. The ideas behind it: diff --git a/docs/reference/traits/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md index 1ed50031..abc487c0 100644 --- a/docs/reference/traits/wiring/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -1,4 +1,6 @@ --- +title: 'CanUseComponent — the wiring check' +description: 'The check a check_components! entry asserts: the context wires the component, and the provider it chose has every dependency met for that context.' sidebar_label: 'CanUseComponent' sidebar_position: 3 --- @@ -13,39 +15,32 @@ The context-side check that a context both wires a component and satisfies its p **You are not expected to name `CanUseComponent` directly.** [`check_components!`](../../macros/check_components.md) and -[`delegate_and_check_components!`](../../macros/delegate_and_check_components.md) generate the assertion -that uses it. What you write is the check; this page explains what a check actually asserts, so that its -failure is legible. +[`delegate_and_check_components!`](../../macros/delegate_and_check_components.md) generate the +assertion that uses it. What you write is the check; this page explains what a check asserts, so +that its failure is legible. A hand-written bound on it is legal, and occasionally useful when +probing one case. ::: ## Overview -CGP's wiring is lazy: writing a wiring line does not check that the chosen implementation's own requirements -are met. That check happens the first time the trait is actually called, which is usually somewhere far -from the wiring and produces a bad error when it fails. +CGP's wiring is lazy: writing a wiring line does not check that the chosen provider's own +requirements are met. That check happens where the trait is first used, usually far from the wiring, +and the error there is poor, because asking whether a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, +implements the consumer trait makes the compiler report only the outermost unmet bound. The root +cause, often one absent field, does not appear. -`CanUseComponent` is the bound that forces the check early, and it exists because the obvious way of asking -does not work. Asking "does this **context** (the type the method runs on) implement the consumer -trait?" makes the compiler report the outermost unmet bound, usually a bare "the provider does not implement -the provider trait", and hide the reasoning behind it. The root cause, often one absent field, never appears. - -`CanUseComponent` reframes the same question along a path the compiler will explain. It holds when two things -hold together: - -- the context **delegates** the component: it has a [`DelegateComponent`](./delegate_component.md) entry; -- the delegated provider **is a valid provider** for that exact context and parameters: it satisfies - [`IsProviderFor`](./is_provider_for.md). - -Because `IsProviderFor` carries the provider's real `where` bounds, requiring it forces the compiler to -evaluate and report them. The error that was hidden becomes visible, at the wiring site. - -**You never name this trait.** It is the bound [`check_components!`](../../macros/check_components.md) asserts, and the -reason that macro produces a legible error instead of a cascade. +`CanUseComponent` asks the same question along a path the compiler explains. It holds when two +things hold together: the context **wires** the component, with a +[`DelegateComponent`](./delegate_component.md) entry, and the provider it chose **is valid** for +that context and those parameters, through [`IsProviderFor`](./is_provider_for.md). Because +`IsProviderFor` carries the provider's real `where` bounds, requiring it makes the compiler evaluate +and report them, at the check. ## Definition -`CanUseComponent` is an empty marker trait, and its entire meaning lives in a single blanket impl: +`CanUseComponent` is an empty trait whose meaning lives in one blanket impl: ```rust pub trait CanUseComponent {} @@ -58,49 +53,40 @@ where } ``` -`Self` is the context being checked. `Component` is the component-name marker, the same key the wiring -table uses. `Params` collects the component's extra generic parameters and defaults to `()` when there -are none, filled by the same rule [`IsProviderFor`](./is_provider_for.md) uses: one parameter directly, -several as a tuple. The trait has no method, so the blanket impl carries the meaning. Its two bounds are -the two halves of "can use": the context must hold a [`DelegateComponent`](./delegate_component.md) entry -for the component, and that entry's provider must satisfy [`IsProviderFor`](./is_provider_for.md) for this -context and these parameters. Because `IsProviderFor` re-exposes the provider's real `where` bounds, -requiring it forces the compiler to evaluate and report them. +`Self` is the context being checked. `Component` is the component's marker, the key the wiring table +uses. `Params` holds the component's generic parameters, filled by the rule +[`IsProviderFor`](./is_provider_for.md#how-params-is-filled) uses: `()` for none, one directly, +several as a tuple. The two bounds are the two halves of "can use": an entry, and a valid provider +behind it. ## Usage -The trait is in the prelude. You do not name it directly; you assert it through a check macro. - -### Asserting it - -You assert it through a macro. A [`check_components!`](../../macros/check_components.md) table reduces to one -impl of a private [check trait](/docs/reference/glossary#check-trait) per entry, whose [supertrait](/docs/reference/glossary#supertrait) is this bound, so the impl compiles only if the -bound holds: +The trait is in the prelude. A [`check_components!`](../../macros/check_components.md) entry asserts +it, carrying the component's parameters after a colon: ```rust check_components! { - Person { + App { GreeterComponent, + AreaCalculatorComponent: Rectangle, } } ``` -Writing the bound by hand is legal and occasionally useful when probing one case: +The same bounds written by hand hold exactly when that check passes: ```rust -fn assert_wiring() +pub fn assert_wiring() where - Person: CanUseComponent, -{} + App: + CanUseComponent + CanUseComponent, +{ +} ``` -For a component with parameters the check table carries them, which is the same `Params` slot: -`GreeterComponent: Rectangle` for one, `(Rectangle, f64)` for several. - ## Examples -The trait's value is what happens when the check fails. Here a provider needs a `name` field and the context -has a differently-named one: +Two components checked on one context, one without parameters and one with a shape parameter: ```rust use cgp::prelude::*; @@ -112,130 +98,175 @@ pub trait HasName { #[cgp_component(Greeter)] pub trait CanGreet { - fn greet(&self); + fn greet(&self) -> String; } #[cgp_impl(new GreetHello)] #[uses(HasName)] impl Greeter { - fn greet(&self) { - println!("Hello, {}!", self.name()); + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } +} + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, rectangle: &Rectangle) -> f64 { + rectangle.width * rectangle.height } } #[derive(HasField)] -pub struct Person { - pub first_name: String, // not `name` +pub struct App { + pub name: String, } delegate_components! { - Person { GreeterComponent: GreetHello } + App { + GreeterComponent: GreetHello, + AreaCalculatorComponent: RectangleArea, + } } check_components! { - Person { GreeterComponent } + App { + GreeterComponent, + AreaCalculatorComponent: Rectangle, + } +} + +pub fn assert_wiring() +where + App: + CanUseComponent + CanUseComponent, +{ } -``` -The check forces `Person: CanUseComponent`. Resolving it needs -`Person: DelegateComponent`, which the wiring supplies, and -`GreetHello: IsProviderFor`, which fails because `GreetHello` needs `HasName` -and `Person` has no `name` field. The compiler reports the absent field **here**, at the check, rather than at -some later `person.greet()`. +pub fn demo() { + assert_wiring(); -Rename the field to `name` and the block compiles and produces nothing: a passing check is a successful -build, with nothing added to the binary. + let app = App { + name: "Ada".to_owned(), + }; + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; -## When to use it + assert_eq!(app.greet(), "Hello, Ada!"); + assert_eq!(app.area(&rectangle), 12.0); +} +``` -**Reach for [`check_components!`](../../macros/check_components.md), which reaches for this trait.** The one -non-negotiable is that a context's wiring gets checked *somehow*: lazy wiring means an unchecked context can -compile and fail later. Which macro does it is a matter of scale. +The `Greeter` check holds because `App` has the `name` field `GreetHello` reads, and the +`AreaCalculator` check holds at `Rectangle`, the parameter it names. A passing check produces +nothing; the build succeeding is the result. Rename the field, and the `Greeter` check fails with +the chain shown on [`IsProviderFor`](./is_provider_for.md#common-mistakes). `App` is an +[environmental context](/docs/reference/glossary#environmental-context) that also holds the name its +greeting reads. + +## When to use it -- **[`delegate_and_check_components!`](../../macros/delegate_and_check_components.md)** fuses wiring and checking, - which suits basic wiring and getting started. It derives a check only for plain `Component: Provider` - entries. -- **Separate [`check_components!`](../../macros/check_components.md)** is what larger wiring wants, because it - gives control over *what* is checked: concrete parameters for a generic component, checks over opened or - namespaced wiring, and `#[check_providers(...)]` per provider layer. +**Reach for [`check_components!`](../../macros/check_components.md), which reaches for this trait.** +What is not optional is that every context's wiring gets checked somehow, since lazy wiring lets an +unchecked context compile and fail later. Which macro does it is a matter of scale: + +- **[`delegate_and_check_components!`](../../macros/delegate_and_check_components.md)** wires and + checks in one block, which suits basic wiring and a starter context. It checks each entry keyed on + a component name, including `->` entries, and wires path keys, `=>` redirects, and statements + without checking them. +- **A separate [`check_components!`](../../macros/check_components.md)** gives control over what is + checked: parameters for a generic component, opened or namespaced wiring, and + `#[check_providers(...)]` per provider layer. - **`#[check_providers(...)]`** switches the assertion from this trait to - [`IsProviderFor`](./is_provider_for.md) on named providers. Reach for it when a - [higher-order provider](/docs/concepts/higher-order-providers) stack fails and you need to know *which - layer*, which a context-side check cannot tell you. + [`IsProviderFor`](./is_provider_for.md) on named providers, which is what localizes a failure in a + stack of [higher-order providers](/docs/concepts/higher-order-providers). -One case makes a context-side check actively wrong rather than merely unnecessary: **a provider bundle.** A -[`delegate_components!`](../../macros/delegate_components.md) block with a leading `new` declares a provider that -other contexts delegate to, not a context. Asserting `CanUseComponent` on it asks whether the bundle can use -each component *as a context* (a role it never plays), so the answer is uninformative either way. It passes -vacuously when the bundled providers need nothing from their context, and fails blaming the bundle when any of -them needs something the real context would have supplied. Wire a bundle with plain -`delegate_components!` and let a real context's check verify it, or assert `IsProviderFor` on it directly. +**Do not assert it on a provider bundle.** A `delegate_components!` block with a leading `new` +declares a provider that contexts delegate to, not a context, so asserting `CanUseComponent` on it +asks a question it never answers in use. It passes vacuously when the bundled providers need nothing +from their context, and fails blaming the bundle when one needs something the real context would +supply. Check the bundle through a real context that delegates to it, or assert `IsProviderFor` on +it directly. -Finally, not every unmet bound is a component. Some are ordinary or blanket traits, and no check macro can -verify those. They surface as themselves. +Not every unmet bound is a component. Ordinary and blanket traits that a provider requires surface +as themselves, and no check macro verifies them. ## Under the hood -The blanket impl *is* the behaviour, and its two bounds fail differently, which is the practical payoff. +[`check_components!`](../../macros/check_components.md) emits a private check trait whose supertrait +is this bound, then one empty impl of it per entry. `cargo cgp expand` on the example shows: -**The first bound failing means the wiring is absent.** `Context: DelegateComponent` is unmet when -the context never wired the component, and the [`DelegateComponent`](./delegate_component.md) diagnostic -reports a missing table entry. The fix is a wiring line. +```rust +trait __CheckApp< + __Component__, + __Params__: ?Sized, +>: CanUseComponent<__Component__, __Params__> {} +impl __CheckApp for App {} +impl __CheckApp for App {} +``` -**The second bound failing means the wiring is incomplete.** `Context::Delegate: IsProviderFor<…>` is unmet -when the component *is* wired but the chosen provider's own requirements are not satisfied, and the error is -that provider's unsatisfied `where` clause carried up through the marker. The fix is to supply the dependency. +Each impl compiles only if its supertrait holds, so the table is an assertion, and it adds nothing +to the binary. The two bounds of the blanket impl then fail differently, which tells you what to +fix: -Reading which bound failed is therefore the first thing to do with the error. The trait is the mirror image of -[`IsProviderFor`](./is_provider_for.md): the same readability-restoring question, indexed on the context -(`Self = Context`) rather than on the provider (`Self = Provider`). One starts from "the context delegates and -its delegate is valid"; the other from "this specific provider is valid". +- **The entry bound failing means the wiring is absent.** The check's help line names the + unimplemented `DelegateComponent` for the context, as + [`DelegateComponent`](./delegate_component.md#common-mistakes) shows, and the fix is a wiring + line. +- **The provider bound failing means the wiring is incomplete.** The component is wired, but the + chosen provider's requirements are not met, and the notes carry the provider's unsatisfied bound + up through `IsProviderFor`, as [`IsProviderFor`](./is_provider_for.md#common-mistakes) shows. The + fix is to supply the dependency. -[`check_components!`](../../macros/check_components.md) consumes it by emitting a private check trait whose -supertrait is this bound, then one empty impl of that trait per checked entry. Each impl compiles only if its -supertrait holds, so the table is an assertion. Because it produces no values, a successful build *is* the -passing test. +The trait is the mirror image of `IsProviderFor`: the same question, indexed on the context +(`Self = Context`) rather than on the provider (`Self = Provider`). ## Common Mistakes -**It is not the consumer trait.** `Person: CanUseComponent` holding is not the same -statement as `Person: CanGreet`, even though in practice one follows the other. The check exists precisely -because the two questions produce different diagnostics. - -**Do not assert it on a provider bundle.** The question is meaningless there, and worse, it can pass -vacuously, so a green check on a bundle proves nothing. This is why -[`delegate_and_check_components!`](../../macros/delegate_and_check_components.md) is wrong for a bundle. - -**`Params` follows the tuple rule.** One parameter directly, several as a tuple, `()` for none. A hand-written -assertion that gets this wrong reports as an unsatisfied bound rather than an arity error. +**It is not the consumer trait.** `App: CanUseComponent` holding is a different +statement from `App: CanGreet`, though in practice one follows the other. The check exists because +the two questions produce different diagnostics. -**A passing check is not a passing test of behaviour.** It proves the wiring resolves and the dependencies -exist. It says nothing about whether the provider does the right thing. +**A green check on a provider bundle proves nothing.** It can pass vacuously, as [When to use +it](#when-to-use-it) explains, which is why `delegate_and_check_components!` is the wrong macro for +a bundle. -**Checking costs compile time and nothing else.** The trait is empty and the impls are empty; nothing reaches -the binary. The cost is trait resolution at build time, which is the trade the check exists to make. +**A passing check does not test behavior.** It proves the wiring resolves and every dependency +exists, not that the provider computes the right thing. ## Related constructs -- [`check_components!`](../../macros/check_components.md): the macro that asserts this trait; what you write. -- [`delegate_and_check_components!`](../../macros/delegate_and_check_components.md): wires and checks at once, - for basic wiring. -- [`DelegateComponent`](./delegate_component.md): the first of the two bounds: the context must delegate. -- [`IsProviderFor`](./is_provider_for.md): the second bound, and the provider-indexed counterpart of this - trait. -- [`#[cgp_component]`](../../macros/cgp_component.md): defines the components being checked. +- [`check_components!`](../../macros/check_components.md): the macro that asserts this trait; what + you write. +- [`delegate_and_check_components!`](../../macros/delegate_and_check_components.md): wires and + checks at once, for basic wiring. +- [`DelegateComponent`](./delegate_component.md): the first bound, the entry. +- [`IsProviderFor`](./is_provider_for.md): the second bound, and the provider-side counterpart. - [Compile errors](../../errors.md): the shapes these checks produce, and how to read them. The ideas behind it: -- [Check traits](/docs/concepts/check-traits): why wiring is lazy, and what a compile-time assertion buys. -- [Higher-order providers](/docs/concepts/higher-order-providers): the case where a context-side check is not - enough. +- [Check traits](/docs/concepts/check-traits): why wiring is lazy, and what a compile-time + assertion buys. +- [Higher-order providers](/docs/concepts/higher-order-providers): the case where a context-side + check is not enough. ## Source -- Trait and its blanket impl: [`can_use_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/can_use_component.rs) -- The checks that assert it: [`check_components/table.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/check_components/table.rs) +- [`traits/can_use_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/can_use_component.rs) +- The checks that assert it, in + [`check_components/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/check_components). --- diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index 278b9b4b..4c45d0fc 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -1,4 +1,6 @@ --- +title: 'DelegateComponent — the wiring table entry' +description: 'The trait a wiring table is made of: one impl per entry, mapping a key such as a component name to the provider a context chose for it.' sidebar_label: 'DelegateComponent' sidebar_position: 1 --- @@ -12,18 +14,19 @@ The per-context type-level table mapping a component key to its provider. ### Generated machinery **You are not expected to write `DelegateComponent` impls.** -[`delegate_components!`](../../macros/delegate_components.md) emits one per entry of a wiring table, and -[`cgp_namespace!`](../../macros/cgp_namespace.md) emits the blanket forwarding impls behind a namespace. -What you write is the table. This page explains what the table *becomes*, so that an expansion or a -wiring error naming this trait is legible. +[`delegate_components!`](../../macros/delegate_components.md) emits one per entry of a wiring table, +and its `namespace` header emits the blanket impl that forwards every key through a namespace. What +you write is the table. This page explains what the table becomes, so that an expansion or a wiring +error naming this trait is legible. The one place you name the trait yourself is a bound that reads +an entry, as the [Usage](#usage) section shows. ::: ## Overview -Wiring a **context** (the type the method runs on, which supplies the values it needs as its -fields) means recording which implementation it uses for each trait. `DelegateComponent` is the trait -that record is made of. One impl is one entry: +Wiring a [**context**](/docs/reference/glossary#context), the type the implementation runs against, +means recording which provider it uses for each component. `DelegateComponent` is the trait that +record is made of, and one impl is one entry: ```rust impl DelegateComponent for App { @@ -31,19 +34,15 @@ impl DelegateComponent for App { } ``` -Read that as *"in `App`'s table, the entry at `GreeterComponent` is `GreetHello`."* The key is a type, the -value is a type, and the whole lookup happens while the compiler is type-checking, which is why the -"table" costs nothing at runtime and compiles down to a direct call. +Read that as *"in `App`'s table, the entry at `GreeterComponent` is `GreetHello`."* The key and the +value are both types, and the lookup happens while the compiler type-checks, so the table costs +nothing at runtime and a wired call compiles to a direct one. Wiring is not a registry or a startup +step; it is a set of trait impls the compiler resolves. -**You will almost never write this by hand.** [`delegate_components!`](../../macros/delegate_components.md) -generates one impl per line of its body, and that macro is what you write. What makes the trait worth a -page is that it appears by name in compiler errors, and that reading it is how you understand what wiring -*is*: not a registry, not a lookup at startup, but a set of trait impls the compiler resolves. - -One thing to notice early, because it explains why the trait is so general: **the key does not have to be a -component name.** When it is, the entry makes the context inherit the component's provider trait. When it -is any other type (a shape, a tag, a path segment) the same trait is just a lookup table that a provider -walks. One trait covers both, which is why it underlies both ordinary wiring and the inner dispatch tables. +**The key does not have to be a component name.** When it is, the entry gives the context the +component's provider trait. When it is any other type, such as a shape or a tag, the same trait is a +plain lookup table that a provider reads. One trait covers both, which is why it underlies ordinary +wiring and the inner dispatch tables alike. ## Definition @@ -55,13 +54,10 @@ pub trait DelegateComponent { } ``` -`Self` is the table: the context or the provider bundle that owns the entry. `Key` is the type being -looked up, and it is `?Sized` so that an unsized marker can serve as one. `Delegate` is the value stored -at that key, the provider or the further table the entry resolves to. There is no method and no data; the -trait only associates one value type with one key type on a carrier type, so the whole lookup happens -while the compiler type-checks. A missed lookup is reported as the plain -``the trait `DelegateComponent` is not implemented for `App` ``, which names the missing -entry; [`cargo cgp check`](/docs/cargo-cgp/check) turns such errors into CGP-specific messages. +`Self` is the table: a context, or a provider bundle that owns its own entries. `Key` is the type +being looked up, and it is `?Sized` so that an unsized type can serve as a key. `Delegate` is the +value stored at that key: the provider, or a further table, that the entry resolves to. The trait +has no data, so the table exists only in the type system. ## Usage @@ -69,14 +65,12 @@ The trait is in the prelude, so `use cgp::prelude::*;` is enough to name it. ### Setting an entry, and reading one -There are only two operations, and both are ordinary Rust rather than anything CGP-specific. - -**Setting** an entry is writing the impl, which in practice means writing a -[`delegate_components!`](../../macros/delegate_components.md) line. **Reading** one is bounding on the trait -and projecting the associated type: +There are two operations, and both are ordinary Rust. **Setting** an entry is writing the impl, +which in practice means writing a [`delegate_components!`](../../macros/delegate_components.md) +line. **Reading** one is bounding on the trait and projecting the associated type: ```rust -fn provider_for() -> PhantomData<

>>>::Value == String` +error[E0271]: type mismatch resolving `>>>::Value == String` ``` The `Symbol<10, …>` in that message is `first_name` with its length in bytes, worth being able to read since the tag tells you which field the mismatch is about. +**A `&mut self` getter cannot return a shared `Option`, and `Option<&[T]>` is unsupported.** Both +come from the method parsing this macro shares with `#[cgp_auto_getter]`, which documents them under +[Common Mistakes](./cgp_auto_getter.md#common-mistakes): the first fails with `E0308` in every +generated provider, and the second reaches the compiler as an unsized bound. + ## Related constructs - [`#[cgp_auto_getter]`](./cgp_auto_getter.md) — the blanket-impl getter, and the one to prefer. diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index a354b57d..0311af20 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -28,7 +28,7 @@ family member whose method takes only a **context** (the type the method runs on `Code` tag, with no input value at all. A dedicated macro is worth having because **a producer can stand in for any handler**: a handler that -ignores its input is just a producer with an unused parameter. So the macro wires the +ignores its input behaves as a producer with an unused parameter. So the macro wires the generated provider into every member of the family, and one function definition answers `produce`, `compute`, `try_compute`, `compute_async`, `handle`, and their by-reference forms, every one of them yielding the same value regardless of what it is handed. @@ -87,19 +87,26 @@ delegate_components! { } } -// The single `magic_number` definition answers every shape, all yielding 42: -// MagicNumber::produce(&App, PhantomData::<()>) == 42 -// MagicNumber::compute(&App, PhantomData::<()>, &()) == 42 -// MagicNumber::try_compute(&App, PhantomData::<()>, &()) == Ok(42) -// MagicNumber::handle(&App, PhantomData::<()>, &()) resolves to Ok(42) +pub fn demo() { + // The single `magic_number` definition answers every shape, each yielding 42. + assert_eq!(MagicNumber::produce(&App, PhantomData::<()>), 42); + assert_eq!(MagicNumber::compute(&App, PhantomData::<()>, ()), 42); + assert_eq!(MagicNumber::try_compute(&App, PhantomData::<()>, "ignored"), Ok(42)); + + // The future resolves to Ok(42). + let _future = MagicNumber::handle(&App, PhantomData::<()>, ()); +} ``` -The computer and handler forms accept an input argument and discard it, since the underlying producer takes -none. The error type wired into `App` lets the fallible forms build their `Result`; the produced -value is always `Ok`. +The computer and handler forms accept an input of any type and discard it, since the underlying +producer takes none. `App` is an +[environmental context](/docs/reference/glossary#environmental-context) with no fields. The error +type wired into it lets the fallible forms build their `Result`, and the produced value is always +`Ok`. The typical use is as the first step of a pipeline, where a producer seeds the value the later steps -transform: +transform. With `Double` a `#[cgp_computer]` that doubles its input, and `ComputerComponent` and +`PipeHandlers` imported from `cgp::extra::handler`, `app.compute(PhantomData::<()>, ())` returns 84: ```rust delegate_components! { @@ -143,7 +150,7 @@ pub fn magic_number() -> u64 { } ``` -it produces the base impl, whose method ignores both of its parameters and simply calls the function: +it produces the base impl, whose method ignores both of its parameters and calls the function: ```rust #[cgp_new_provider] diff --git a/example-code/README.md b/example-code/README.md index 32b11833..b7f33258 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -36,7 +36,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, the `macros/` pages `cgp_component.md`, `cgp_impl.md`, `cgp_provider.md`, `cgp_fn.md`, `cgp_type.md`, `cgp_namespace.md`, and `delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, the `macros/` pages `cgp_component.md`, `cgp_impl.md`, `cgp_provider.md`, `cgp_fn.md`, `cgp_type.md`, `cgp_getter.md`, `cgp_auto_getter.md`, `blanket_trait.md`, `async_trait.md`, `cgp_computer.md`, `cgp_producer.md`, `cgp_auto_dispatch.md`, `cgp_namespace.md`, and `delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | diff --git a/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs b/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs new file mode 100644 index 00000000..b18240e8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs @@ -0,0 +1,13 @@ +//! `docs/reference/macros/async_trait.md`, *Common Mistakes*: a default-bodied `async fn` keeps its +//! body while its signature is rewritten. + +use cgp::prelude::*; + +#[async_trait] +pub trait CanCount { + async fn count(&self) -> u32 { + 1 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.stderr b/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.stderr new file mode 100644 index 00000000..65194138 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.stderr @@ -0,0 +1,10 @@ +error[E0277]: `{integer}` is not a future + --> tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs:6:1 + | +6 | #[async_trait] + | ^^^^^^^^^^^^^^ `{integer}` is not a future +... +9 | 1 + | - return type was inferred to be `{integer}` here + | + = help: the trait `Future` is not implemented for `{integer}` diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.rs b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.rs new file mode 100644 index 00000000..29e720a9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.rs @@ -0,0 +1,12 @@ +//! `docs/reference/macros/blanket_trait.md`, *Common Mistakes*: a constant needs a default expression. + +use cgp::core::macros::blanket_trait; + +pub trait Foo {} + +#[blanket_trait] +pub trait FooExt: Foo { + const LIMIT: u32; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.stderr b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.stderr new file mode 100644 index 00000000..739fd469 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.stderr @@ -0,0 +1,5 @@ +error: const item require implementation expression + --> tests/compile_fail/reference/macros/blanket_trait_common_mistakes_const_without_default.rs:9:5 + | +9 | const LIMIT: u32; + | ^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.rs b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.rs new file mode 100644 index 00000000..b0fe430a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.rs @@ -0,0 +1,27 @@ +//! `docs/reference/macros/blanket_trait.md`, *Common Mistakes*: the blanket impl conflicts with a hand-written impl for a type that satisfies its bounds. + +use cgp::core::macros::blanket_trait; + +pub trait Foo { + fn foo(&self); +} + +#[blanket_trait] +pub trait FooExt: Foo { + fn foo_twice(&self) { + self.foo(); + self.foo(); + } +} + +pub struct Ctx; + +impl Foo for Ctx { + fn foo(&self) {} +} + +impl FooExt for Ctx { + fn foo_twice(&self) {} +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.stderr b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.stderr new file mode 100644 index 00000000..50b380be --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.stderr @@ -0,0 +1,10 @@ +error[E0119]: conflicting implementations of trait `FooExt` for type `Ctx` + --> tests/compile_fail/reference/macros/blanket_trait_common_mistakes_hand_written_impl.rs:9:1 + | + 9 | #[blanket_trait] + | ^^^^^^^^^^^^^^^^ conflicting implementation for `Ctx` +... +23 | impl FooExt for Ctx { + | ------------------- first implementation here + | + = note: this error originates in the attribute macro `blanket_trait` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.rs b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.rs new file mode 100644 index 00000000..915afa91 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.rs @@ -0,0 +1,14 @@ +//! `docs/reference/macros/blanket_trait.md`, *Common Mistakes*: a method needs a default body. + +use cgp::core::macros::blanket_trait; + +pub trait Foo { + fn foo(&self); +} + +#[blanket_trait] +pub trait FooExt: Foo { + fn foo_twice(&self); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.stderr b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.stderr new file mode 100644 index 00000000..323f1751 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.stderr @@ -0,0 +1,5 @@ +error: function item require implementation block + --> tests/compile_fail/reference/macros/blanket_trait_common_mistakes_method_without_default.rs:11:5 + | +11 | fn foo_twice(&self); + | ^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.rs b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.rs new file mode 100644 index 00000000..263f1f2a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.rs @@ -0,0 +1,17 @@ +//! `docs/reference/macros/blanket_trait.md`, *Common Mistakes*: the macro is not in the prelude. + +use cgp::prelude::*; + +pub trait Foo { + fn foo(&self); +} + +#[blanket_trait] +pub trait FooExt: Foo { + fn foo_twice(&self) { + self.foo(); + self.foo(); + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.stderr b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.stderr new file mode 100644 index 00000000..a144dfaf --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.stderr @@ -0,0 +1,13 @@ +error: cannot find attribute `blanket_trait` in this scope + --> tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.rs:9:3 + | +9 | #[blanket_trait] + | ^^^^^^^^^^^^^ + +warning: unused import: `cgp::prelude::*` + --> tests/compile_fail/reference/macros/blanket_trait_common_mistakes_not_in_prelude.rs:3:5 + | +3 | use cgp::prelude::*; + | ^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.rs b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.rs new file mode 100644 index 00000000..217239a7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.rs @@ -0,0 +1,16 @@ +//! `docs/reference/macros/blanket_trait.md`, *Common Mistakes*: only methods, associated types, and constants are accepted. + +use cgp::core::macros::blanket_trait; + +pub trait Foo {} + +macro_rules! no_items { + () => {}; +} + +#[blanket_trait] +pub trait FooExt: Foo { + no_items!(); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.stderr b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.stderr new file mode 100644 index 00000000..1aa5dcc5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.stderr @@ -0,0 +1,13 @@ +error: unsupported trait item + --> tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.rs:13:5 + | +13 | no_items!(); + | ^^^^^^^^^^^^ + +warning: unused macro definition: `no_items` + --> tests/compile_fail/reference/macros/blanket_trait_common_mistakes_unsupported_item.rs:7:14 + | +7 | macro_rules! no_items { + | ^^^^^^^^ + | + = note: `#[warn(unused_macros)]` (part of `#[warn(unused)]`) on by default diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.rs new file mode 100644 index 00000000..933621c6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.rs @@ -0,0 +1,27 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: every trait item must be a method. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_auto_dispatch] +pub trait HasUnit { + type Unit; + + fn area(&self) -> f64; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.stderr new file mode 100644 index 00000000..7198a918 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.stderr @@ -0,0 +1,5 @@ +error: Only function items are allowed in a dispatch trait + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.rs:22:5 + | +22 | type Unit; + | ^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.rs new file mode 100644 index 00000000..0dd540e3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.rs @@ -0,0 +1,25 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a dispatch method cannot take a type parameter. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_auto_dispatch] +pub trait CanDescribe { + fn describe(&self) -> T; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.stderr new file mode 100644 index 00000000..196f8df0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.stderr @@ -0,0 +1,5 @@ +error: Dispatch trait methods cannot contain non-lifetime generic parameters due to the lack of quantified constraints in Rust + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.rs:22:17 + | +22 | fn describe(&self) -> T; + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.rs new file mode 100644 index 00000000..4d1b3302 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.rs @@ -0,0 +1,31 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a hand-written impl collides for a type the blanket impl covers. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} + +impl HasArea for Shape { + fn area(&self) -> f64 { + 0.0 + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr new file mode 100644 index 00000000..c81e9ce6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr @@ -0,0 +1,12 @@ +error[E0119]: conflicting implementations of trait `HasArea` for type `Shape` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.rs:20:1 + | +20 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Shape` +... +25 | impl HasArea for Shape { + | ---------------------- first implementation here + | + = note: upstream crates may add a new impl of trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::MatchWithValueHandlersRef` in future versions + = note: upstream crates may add a new impl of trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::MatchWithValueHandlersRef` in future versions + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs new file mode 100644 index 00000000..512c3821 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs @@ -0,0 +1,27 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: the per-method helper function takes the method's name in the module. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} + +pub fn area() {} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.stderr new file mode 100644 index 00000000..859ea3df --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.stderr @@ -0,0 +1,36 @@ +error[E0428]: the name `area` is defined multiple times + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs:25:1 + | +20 | #[cgp_auto_dispatch] + | -------------------- previous definition of the value `area` here +... +25 | pub fn area() {} + | ^^^^^^^^^^^^^ `area` redefined here + | + = note: `area` must be defined only once in the value namespace of this module + +error[E0061]: this function takes 0 arguments but 1 argument was supplied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs:22:8 + | +20 | #[cgp_auto_dispatch] + | -------------------- unexpected argument of type `&'__a__ __Variants__` +21 | pub trait HasArea { +22 | fn area(&self) -> f64; + | ^^^^ + | +note: function defined here + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs:25:8 + | +25 | pub fn area() {} + | ^^^^ + +error[E0308]: mismatched types + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs:20:1 + | +20 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ + | | + | expected `f64`, found `()` + | expected `f64` because of return type + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs new file mode 100644 index 00000000..d40fc123 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs @@ -0,0 +1,39 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: an enum without the extensible-data derive cannot be dispatched. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +pub enum Plain { + Circle(Circle), +} + +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} + +impl HasArea for Circle { + fn area(&self) -> f64 { + 1.0 + } +} + +pub fn area_of(shape: &Plain) -> f64 { + shape.area() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr new file mode 100644 index 00000000..40ca0314 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr @@ -0,0 +1,39 @@ +error[E0599]: the method `area` exists for reference `&Plain`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs:36:11 + | +20 | pub enum Plain { + | -------------- doesn't satisfy `Plain: HasArea` or `Plain: cgp::prelude::HasExtractor` +... +36 | shape.area() + | ^^^^ method cannot be called on `&Plain` due to unsatisfied trait bounds + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + | +19 | pub struct MatchWithValueHandlersRef(pub PhantomData); + | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Plain>>::Output = f64`, `<_ as Computer<(), (), &Plain>>::Output = f64`, `_: Computer<(), (), &&Plain>` or `_: Computer<(), (), &Plain>` + | +note: the following trait bounds were not satisfied: + `&Plain: cgp::prelude::HasExtractor` + ` as cgp::prelude::Computer<(), (), &'__a__ &Plain>>::Output = f64` + ` as cgp::prelude::Computer<(), (), &'__a__ Plain>>::Output = f64` + `Plain: cgp::prelude::HasExtractor` + `cgp::prelude::MatchWithValueHandlersRef: cgp::prelude::Computer<(), (), &'__a__ &Plain>` + `cgp::prelude::MatchWithValueHandlersRef: cgp::prelude::Computer<(), (), &'__a__ Plain>` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs:24:1 + | +24 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ +25 | pub trait HasArea { + | ^^^^^^^ +note: the trait `cgp::prelude::HasExtractor` must be implemented + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + | + 6 | pub trait HasExtractor { + | ^^^^^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `HasArea` defines an item `area`, perhaps you need to implement it + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs:25:1 + | +25 | pub trait HasArea { + | ^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs new file mode 100644 index 00000000..4041317c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs @@ -0,0 +1,35 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a variant payload without an impl fails where the method is called. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} + +impl HasArea for Circle { + fn area(&self) -> f64 { + 1.0 + } +} + +pub fn area_of(shape: &Shape) -> f64 { + shape.area() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr new file mode 100644 index 00000000..c0896303 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr @@ -0,0 +1,33 @@ +error[E0599]: the method `area` exists for reference `&Shape`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs:32:11 + | + 6 | pub enum Shape { + | -------------- doesn't satisfy `Shape: HasArea` +... +32 | shape.area() + | ^^^^ method cannot be called on `&Shape` due to unsatisfied trait bounds + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + | +19 | pub struct MatchWithValueHandlersRef(pub PhantomData); + | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Shape>>::Output = f64`, `<_ as Computer<(), (), &Shape>>::Output = f64`, `_: Computer<(), (), &&Shape>` or `_: Computer<(), (), &Shape>` + | +note: the following trait bounds were not satisfied: + `&Shape: cgp::prelude::HasExtractor` + ` as cgp::prelude::Computer<(), (), &'__a__ &Shape>>::Output = f64` + ` as cgp::prelude::Computer<(), (), &'__a__ Shape>>::Output = f64` + `cgp::prelude::MatchWithValueHandlersRef: cgp::prelude::Computer<(), (), &'__a__ &Shape>` + `cgp::prelude::MatchWithValueHandlersRef: cgp::prelude::Computer<(), (), &'__a__ Shape>` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs:20:1 + | +20 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ +21 | pub trait HasArea { + | ^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `HasArea` defines an item `area`, perhaps you need to implement it + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs:21:1 + | +21 | pub trait HasArea { + | ^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.rs new file mode 100644 index 00000000..a36a6333 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.rs @@ -0,0 +1,25 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: every method needs a `self` receiver. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_auto_dispatch] +pub trait HasOrigin { + fn origin() -> (f64, f64); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.stderr new file mode 100644 index 00000000..2cb0dd12 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.stderr @@ -0,0 +1,5 @@ +error: Dispatcher method must have a self argument + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.rs:22:5 + | +22 | fn origin() -> (f64, f64); + | ^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs new file mode 100644 index 00000000..1a5eb1bb --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs @@ -0,0 +1,29 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a supertrait is not carried onto the blanket impl. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +pub trait Named { + fn name(&self) -> String; +} + +#[cgp_auto_dispatch] +pub trait HasArea: Named { + fn area(&self) -> f64; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.stderr new file mode 100644 index 00000000..0b53bdab --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.stderr @@ -0,0 +1,16 @@ +error[E0277]: the trait bound `__Variants__: Named` is not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs:24:1 + | +24 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ the trait `Named` is not implemented for `__Variants__` + | +note: required by a bound in `HasArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs:25:20 + | +25 | pub trait HasArea: Named { + | ^^^^^ required by this bound in `HasArea` + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider further restricting type parameter `__Variants__` with trait `Named` + | +24 | #[cgp_auto_dispatch], __Variants__: Named + | +++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs new file mode 100644 index 00000000..7468a334 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs @@ -0,0 +1,25 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a method needing two distinct lifetimes fails. + +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_auto_dispatch] +pub trait Lookup { + fn lookup<'a>(&'a self, key: &str) -> &'a str; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.stderr new file mode 100644 index 00000000..47222205 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.stderr @@ -0,0 +1,19 @@ +error[E0261]: use of undeclared lifetime name `'__a__` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs:20:1 + | +20 | #[cgp_auto_dispatch] + | -^^^^^^^^^^^^^^^^^^^ + | | + | undeclared lifetime + | lifetime `'__a__` is missing in item created through this procedural macro + | + = note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider making the bound lifetime-generic with a new `'__a__` lifetime + | +20 | for<'__a__> #[cgp_auto_dispatch] + | +++++++++++ +help: consider introducing lifetime `'__a__` here + | +20 | #[cgp_auto_dispatch]'__a__, + | +++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.rs new file mode 100644 index 00000000..114e2056 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.rs @@ -0,0 +1,13 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: an associated type allows exactly one getter method. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + type Name; + + fn name(&self) -> &Self::Name; + fn nickname(&self) -> &Self::Name; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.stderr new file mode 100644 index 00000000..0aad1383 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.stderr @@ -0,0 +1,5 @@ +error: if associated type is defined, exactly one getter method must be defined + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_associated_type_two_methods.rs:6:1 + | +6 | pub trait HasName { + | ^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.rs new file mode 100644 index 00000000..f1a13d18 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: the macro takes no argument. + +use cgp::prelude::*; + +#[cgp_auto_getter(NameGetter)] +pub trait HasName { + fn name(&self) -> &str; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.stderr new file mode 100644 index 00000000..2be1e85b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.stderr @@ -0,0 +1,7 @@ +error: #[cgp_auto_getter] does not accept any attribute argument + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_attribute_argument.rs:5:1 + | +5 | #[cgp_auto_getter(NameGetter)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.rs new file mode 100644 index 00000000..faf67e29 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.rs @@ -0,0 +1,19 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: a context whose field has another name does not satisfy the getter. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub full_name: String, +} + +pub fn greet(person: &Person) -> &str { + person.name() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr new file mode 100644 index 00000000..ede1d1c2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr @@ -0,0 +1,32 @@ +error[E0599]: the method `name` exists for reference `&Person`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.rs:16:12 + | +11 | pub struct Person { + | ----------------- doesn't satisfy `<_ as HasField>>>>>>::Value = String`, `Person: HasName` or `_: HasField>>>>>` +... +16 | person.name() + | ^^^^ method cannot be called on `&Person` due to unsatisfied trait bounds + | +note: the following trait bounds were not satisfied: + `&Person: cgp::prelude::HasField>>>>>` + `<&Person as cgp::prelude::HasField>>>>>>::Value = String` + `>>>>>>::Value = String` + `Person: cgp::prelude::HasField>>>>>` + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.rs:5:1 + | + 5 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ + 6 | pub trait HasName { + | ^^^^^^^ +note: the trait `cgp::prelude::HasField` must be implemented + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/has_field.rs:46:1 + | +46 | pub trait HasField { + | ^^^^^^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `HasName` defines an item `name`, perhaps you need to implement it + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.rs:6:1 + | + 6 | pub trait HasName { + | ^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.rs new file mode 100644 index 00000000..ce89c9dc --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: a `&mut` return needs a `&mut self` receiver. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasCounter { + fn counter(&self) -> &mut u32; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.stderr new file mode 100644 index 00000000..aabb8df1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.stderr @@ -0,0 +1,5 @@ +error: &mut self is required for mutable field reference `& mut u32` + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_return_under_shared_self.rs:7:26 + | +7 | fn counter(&self) -> &mut u32; + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.rs new file mode 100644 index 00000000..a6dd49b4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: a `&mut self` getter returning a shared `Option<&T>` fails with `E0308`. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasMaybe { + fn maybe(&mut self) -> Option<&u32>; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.stderr new file mode 100644 index 00000000..668bafcf --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.stderr @@ -0,0 +1,16 @@ +error[E0308]: mismatched types + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_mut_self_shared_option.rs:5:1 + | +5 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ types differ in mutability +6 | pub trait HasMaybe { +7 | fn maybe(&mut self) -> Option<&u32>; + | ------------ expected `Option<&u32>` because of return type + | + = note: expected enum `Option<&u32>` + found enum `Option<&mut u32>` + = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) +help: try using `.as_deref()` to convert `Option<&mut u32>` to `Option<&u32>` + | +5 | #[cgp_auto_getter].as_deref() + | +++++++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs new file mode 100644 index 00000000..3cec0eb2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: `Option<&[T]>` has no rule and reaches the compiler as an unsized bound. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasBytes { + fn bytes(&self) -> Option<&[u8]>; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr new file mode 100644 index 00000000..83c8d941 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr @@ -0,0 +1,30 @@ +error[E0277]: the size for values of type `[u8]` cannot be known at compilation time + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs:5:1 + | +5 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `[u8]` +note: required by an implicit `Sized` bound in `Option` + --> $RUST/core/src/option.rs + | + | pub enum Option { + | ^ required by the implicit `Sized` requirement on this type parameter in `Option` + = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0599]: the method `as_ref` exists for reference `&Option<[u8]>`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs:5:1 + | +5 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ method cannot be called on `&Option<[u8]>` due to unsatisfied trait bounds + | + ::: $RUST/core/src/option.rs + | + | pub enum Option { + | ------------------ doesn't satisfy `Option<[u8]>: AsRef<_>` + | + = note: the following trait bounds were not satisfied: + `[u8]: Sized` + `Option<[u8]>: AsRef<_>` + which is required by `&Option<[u8]>: AsRef<_>` + = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.rs new file mode 100644 index 00000000..165478ff --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: a getter method must be a plain signature. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + async fn name(&self) -> &str; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.stderr new file mode 100644 index 00000000..17068625 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.stderr @@ -0,0 +1,5 @@ +error: getter method must not be async fn + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_rejected_method_shape.rs:7:5 + | +7 | async fn name(&self) -> &str; + | ^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.rs new file mode 100644 index 00000000..5fbefec8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: the second argument must be a `PhantomData`. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self, index: usize) -> &str; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.stderr new file mode 100644 index 00000000..419fc026 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.stderr @@ -0,0 +1,5 @@ +error: only PhantomData is allowed as second argument + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_second_argument_not_phantom.rs:7:20 + | +7 | fn name(&self, index: usize) -> &str; + | ^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.rs new file mode 100644 index 00000000..fce8a142 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: a getter takes at most `self` and one `PhantomData`. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self, index: usize, count: usize) -> &str; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.stderr new file mode 100644 index 00000000..62a9666e --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.stderr @@ -0,0 +1,5 @@ +error: getter method must contain exactly one `&self` argument + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_third_argument.rs:7:13 + | +7 | fn name(&self, index: usize, count: usize) -> &str; + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs new file mode 100644 index 00000000..cafde1dd --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs @@ -0,0 +1,19 @@ +//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: the fallible members need an error +//! type on the context, while `compute` does not. + +use core::marker::PhantomData; + +use cgp::extra::handler::{Computer, TryComputer}; +use cgp::prelude::*; + +#[cgp_computer] +fn add(a: u64, b: u64) -> u64 { + a + b +} + +pub struct App; + +fn main() { + let _ = Add::compute(&App, PhantomData::<()>, (1, 2)); + let _ = Add::try_compute(&App, PhantomData::<()>, (1, 2)); +} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr new file mode 100644 index 00000000..af995f3a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr @@ -0,0 +1,65 @@ +error[E0277]: the trait bound `App: DelegateComponent` is not satisfied + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs:18:13 + | +18 | let _ = Add::try_compute(&App, PhantomData::<()>, (1, 2)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `DelegateComponent` is not implemented for `App` + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs:14:1 + | +14 | pub struct App; + | ^^^^^^^^^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `BuildAndMergeOutputs` implements `DelegateComponent` + and $N others + = note: required for `App` to implement `ErrorTypeProvider` + +error[E0277]: the trait bound `App: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs:18:13 + | +18 | let _ = Add::try_compute(&App, PhantomData::<()>, (1, 2)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `App` + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs:14:1 + | +14 | pub struct App; + | ^^^^^^^^^^^^^^ + = help: the following other types implement trait `IsProviderFor`: + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + and $N others + = note: required for `App` to implement `ErrorTypeProvider` + +error[E0277]: the trait bound `Promote: TryComputer` is not satisfied + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.rs:18:13 + | +18 | let _ = Add::try_compute(&App, PhantomData::<()>, (1, 2)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TryComputer` is not implemented for `Promote` + | +help: the trait `TryComputer` is conditionally implemented for `Promote` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/providers/promote.rs:23:1 + | +23 | / impl TryComputer for Promote +24 | | where +25 | | Context: HasErrorType, + | | ------------ + | | | + | | unsatisfied requirement introduced here: `App: HasErrorType` + | | unsatisfied requirement introduced here: `App: HasErrorType` +26 | | Provider: Computer, + | |______________________________________________________________^ + = note: required for `Add` to implement `TryComputer` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.rs new file mode 100644 index 00000000..f97df523 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.rs @@ -0,0 +1,14 @@ +//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: a computer function takes no receiver. + +use cgp::prelude::*; + +pub struct Adder; + +impl Adder { + #[cgp_computer] + fn add(&self, a: u64, b: u64) -> u64 { + a + b + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.stderr new file mode 100644 index 00000000..2b04cddb --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.stderr @@ -0,0 +1,5 @@ +error: Computer functions cannot have a receiver + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.rs:9:12 + | +9 | fn add(&self, a: u64, b: u64) -> u64 { + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs new file mode 100644 index 00000000..c11053ad --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs @@ -0,0 +1,13 @@ +//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: a one-argument `Result` alias fails +//! to parse, because the macro expects `Result`. + +use cgp::prelude::*; + +pub type Result = core::result::Result; + +#[cgp_computer] +fn halve(value: u64) -> Result { + Ok(value / 2) +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr new file mode 100644 index 00000000..e8b6f4b7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr @@ -0,0 +1,5 @@ +error: expected `,` + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs:9:35 + | +9 | fn halve(value: u64) -> Result { + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs new file mode 100644 index 00000000..2e53de59 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs @@ -0,0 +1,27 @@ +//! `docs/reference/macros/cgp_getter.md`, *Common Mistakes*: the field must have the type the return type calls for. + +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[derive(HasField)] +pub struct Person { + pub first_name: &'static str, +} + +delegate_components! { + Person { + NameGetterComponent: UseField, + } +} + +check_components! { + Person { + NameGetterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.stderr b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.stderr new file mode 100644 index 00000000..5a53d59b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.stderr @@ -0,0 +1,28 @@ +error[E0271]: type mismatch resolving `>>>>>>>>>>>>::Value == String` + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs:23:9 + | +23 | NameGetterComponent, + | ^^^^^^^^^^^^^^^^^^^ type mismatch resolving `>>>>>>>>>>>>::Value == String` + | +note: expected this to be `String` + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs:12:21 + | +12 | pub first_name: &'static str, + | ^^^^^^^^^^^^ +note: required for `cgp::prelude::UseField>>>>>>>>>>>` to implement `IsProviderFor` + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs:5:1 + | + 5 | #[cgp_getter] + | ^^^^^^^^^^^^^ + = note: associated types for the current `impl` cannot be restricted in `where` clauses + = note: required for `Person` to implement `CanUseComponent` +note: required by a bound in `__CheckPerson` + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_field_type_mismatch.rs:21:1 + | +21 | / check_components! { +22 | | Person { +23 | | NameGetterComponent, +24 | | } +25 | | } + | |_^ required by this bound in `__CheckPerson` + = note: this error originates in the attribute macro `cgp_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.rs b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.rs new file mode 100644 index 00000000..6a465552 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_getter.md`, *Common Mistakes*: a `&mut self` getter returning a shared `Option<&T>` fails with `E0308`. + +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasMaybe { + fn maybe(&mut self) -> Option<&u32>; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.stderr b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.stderr new file mode 100644 index 00000000..462adf1d --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.stderr @@ -0,0 +1,16 @@ +error[E0308]: mismatched types + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_mut_self_shared_option.rs:5:1 + | +5 | #[cgp_getter] + | ^^^^^^^^^^^^^ types differ in mutability +6 | pub trait HasMaybe { +7 | fn maybe(&mut self) -> Option<&u32>; + | ------------ expected `Option<&u32>` because of return type + | + = note: expected enum `Option<&u32>` + found enum `Option<&mut u32>` + = note: this error originates in the attribute macro `cgp_getter` (in Nightly builds, run with -Z macro-backtrace for more info) +help: try using `.as_deref()` to convert `Option<&mut u32>` to `Option<&u32>` + | +5 | #[cgp_getter].as_deref() + | +++++++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.rs b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.rs new file mode 100644 index 00000000..1ae8c938 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_getter.md`, *Common Mistakes*: a trait not named `Has…` gets no default provider name. + +use cgp::prelude::*; + +#[cgp_getter] +pub trait Dimensions { + fn width(&self) -> &f64; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.stderr b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.stderr new file mode 100644 index 00000000..698d9369 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.stderr @@ -0,0 +1,7 @@ +error: the `provider` key must be given + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_no_has_prefix.rs:5:1 + | +5 | #[cgp_getter] + | ^^^^^^^^^^^^^ + | + = note: this error originates in the attribute macro `cgp_getter` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.rs b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.rs new file mode 100644 index 00000000..6c4f55ee --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.rs @@ -0,0 +1,29 @@ +//! `docs/reference/macros/cgp_getter.md`, *Common Mistakes*: a multi-method trait gets no `UseField` provider. + +use cgp::prelude::*; + +#[cgp_getter] +pub trait HasDimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + DimensionsGetterComponent: UseField, + } +} + +check_components! { + Rectangle { + DimensionsGetterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr new file mode 100644 index 00000000..e0d98ed7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr @@ -0,0 +1,47 @@ +error[E0277]: the trait bound `cgp::prelude::UseField>>>>>>: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.rs:25:9 + | +25 | DimensionsGetterComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `cgp::prelude::UseField>>>>>>` +help: the following other types implement trait `IsProviderFor` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + | +31 | / impl AsyncComputer for UseField +32 | | where +33 | | Context: HasField, +34 | | Context::Value: CanComputeAsync, + | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_field.rs:69:1 + | +69 | / impl IsProviderFor +70 | | for UseField +71 | | where +72 | | Context: HasField, + | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/computer.rs:29:1 + | +29 | / impl Computer for UseField +30 | | where +31 | | Context: HasField, +32 | | Context::Value: CanCompute, + | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + | + 5 | #[cgp_getter] + | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` + = note: required for `Rectangle` to implement `CanUseComponent` +note: required by a bound in `__CheckRectangle` + --> tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.rs:23:1 + | +23 | / check_components! { +24 | | Rectangle { +25 | | DimensionsGetterComponent, +26 | | } +27 | | } + | |_^ required by this bound in `__CheckRectangle` + = note: this error originates in the attribute macro `cgp_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.rs b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.rs new file mode 100644 index 00000000..f4784cb6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_producer.md`, *Common Mistakes*: a producer cannot be `async`. + +use cgp::prelude::*; + +#[cgp_producer] +async fn magic_number() -> u64 { + 42 +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.stderr b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.stderr new file mode 100644 index 00000000..74f29d5a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.stderr @@ -0,0 +1,5 @@ +error: Producer functions cannot be async + --> tests/compile_fail/reference/macros/cgp_producer_common_mistakes_async.rs:6:1 + | +6 | async fn magic_number() -> u64 { + | ^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.rs b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.rs new file mode 100644 index 00000000..2a063bbd --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_producer.md`, *Common Mistakes*: a producer takes no generic parameters. + +use cgp::prelude::*; + +#[cgp_producer] +fn default_value() -> T { + T::default() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.stderr b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.stderr new file mode 100644 index 00000000..bcb0cbc0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.stderr @@ -0,0 +1,5 @@ +error: Producer functions must have empty generic parameters + --> tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.rs:6:18 + | +6 | fn default_value() -> T { + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.rs b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.rs new file mode 100644 index 00000000..0b39c51f --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.rs @@ -0,0 +1,10 @@ +//! `docs/reference/macros/cgp_producer.md`, *Common Mistakes*: a producer takes no parameters. + +use cgp::prelude::*; + +#[cgp_producer] +fn magic_number(seed: u64) -> u64 { + seed +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.stderr b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.stderr new file mode 100644 index 00000000..77ffd6c2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.stderr @@ -0,0 +1,5 @@ +error: Producer functions cannot have parameters + --> tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.rs:6:17 + | +6 | fn magic_number(seed: u64) -> u64 { + | ^^^^ diff --git a/example-code/tests/reference/macros/async_trait.rs b/example-code/tests/reference/macros/async_trait.rs new file mode 100644 index 00000000..42cc9b68 --- /dev/null +++ b/example-code/tests/reference/macros/async_trait.rs @@ -0,0 +1,171 @@ +//! Code from `docs/reference/macros/async_trait.md` — *`#[async_trait]`*. +//! +//! The snippet the page rejects lives under `tests/compile_fail/reference/macros/`. + +/// ## Overview and Usage +/// +/// The `CanFetch` trait with the attribute, implemented directly on a context the page does not +/// show, and an ignored argument, which the page says is accepted. +pub mod overview_and_usage { + use cgp::prelude::*; + + #[async_trait] + pub trait CanFetch { + async fn fetch(&self, id: &str) -> Result, String>; + } + + #[async_trait(ignored)] + pub trait CanFetchQuietly { + async fn fetch_quietly(&self) -> u8; + } + + pub struct App; + + impl CanFetch for App { + async fn fetch(&self, id: &str) -> Result, String> { + Ok(id.as_bytes().to_vec()) + } + } + + #[test] + fn the_rewritten_method_is_implemented_with_async_fn() { + assert_eq!( + futures::executor::block_on(App.fetch("x")), + Ok(b"x".to_vec()) + ); + } +} + +/// ### Ordering with a host macro +/// +/// `#[async_trait]` above and below `#[cgp_component]`, and below `#[cgp_fn]`. The page elides the +/// `#[cgp_fn]` body and names `Client` without declaring it; it is a small struct here. +pub mod ordering_with_a_host_macro { + pub mod outermost { + use cgp::prelude::*; + + #[async_trait] + #[cgp_component(StorageObjectFetcher)] + pub trait CanFetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> Result, String>; + } + } + + pub mod below_the_component { + use cgp::prelude::*; + + #[cgp_component(StorageObjectFetcher)] + #[async_trait] + pub trait CanFetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> Result, String>; + } + } + + pub mod under_cgp_fn { + use cgp::prelude::*; + + pub struct Client { + pub prefix: String, + } + + #[cgp_fn] + #[async_trait] + pub async fn fetch_storage_object( + &self, + #[implicit] storage_client: &Client, + object_id: &str, + ) -> Result, String> { + // The page elides the body. + Ok(format!("{}{object_id}", storage_client.prefix).into_bytes()) + } + + #[derive(HasField)] + pub struct App { + pub storage_client: Client, + } + + #[test] + fn the_generated_trait_runs() { + let app = App { + storage_client: Client { + prefix: "p/".to_owned(), + }, + }; + assert_eq!( + futures::executor::block_on(app.fetch_storage_object("o")), + Ok(b"p/o".to_vec()) + ); + } + } +} + +/// ## Examples +/// +/// The page's async component, provider, and wiring, with the check the page shows. +pub mod examples { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + #[async_trait] + #[cgp_component(StorageObjectFetcher)] + #[use_type(HasErrorType.Error)] + pub trait CanFetchStorageObject { + async fn fetch_storage_object(&self, object_id: &str) -> Result, Error>; + } + + #[cgp_impl(new FetchFromBucket)] + #[use_type(HasErrorType.Error)] + impl StorageObjectFetcher { + async fn fetch_storage_object( + &self, + #[implicit] bucket_id: &str, + object_id: &str, + ) -> Result, Error> { + Ok(format!("{bucket_id}/{object_id}").into_bytes()) + } + } + + #[derive(HasField)] + pub struct App { + pub bucket_id: String, + } + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + StorageObjectFetcherComponent: FetchFromBucket, + } + } + + check_components! { + App { + StorageObjectFetcherComponent, + } + } + + #[test] + fn the_provider_is_awaited_through_the_trait() { + let app = App { + bucket_id: "b".to_owned(), + }; + assert_eq!( + futures::executor::block_on(app.fetch_storage_object("o")), + Ok(b"b/o".to_vec()) + ); + } +} + +/// ## Under the hood +/// +/// The three-method trait whose expansion the page lists, checked with +/// `cargo cgp expand --item reference::macros::async_trait::under_the_hood`. +pub mod under_the_hood { + use cgp::prelude::*; + + #[async_trait] + pub trait CanFetch { + async fn fetch(&self, id: &str) -> Result, String>; + async fn run(&self); + fn sync_method(&self) -> u8; + } +} diff --git a/example-code/tests/reference/macros/blanket_trait.rs b/example-code/tests/reference/macros/blanket_trait.rs new file mode 100644 index 00000000..84de5511 --- /dev/null +++ b/example-code/tests/reference/macros/blanket_trait.rs @@ -0,0 +1,165 @@ +//! Code from `docs/reference/macros/blanket_trait.md` — *`#[blanket_trait]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. + +/// ## Overview and Usage +/// +/// The `FooBar` extension trait, written once and used on a context implementing `Foo` and `Bar`. +/// The page names `Foo` and `Bar` in the Overview and Usage without declaring them until Examples. +pub mod overview_and_usage { + use cgp::core::macros::blanket_trait; + + pub trait Foo { + fn foo(&self) -> u32; + } + + pub trait Bar { + fn bar(&self) -> u32; + } + + #[blanket_trait] + pub trait FooBar: Foo + Bar { + fn foo_bar(&self) -> u32 { + self.foo() + self.bar() + } + } + + /// The context override, which names the impl's parameter `Ctx`. + #[blanket_trait(Ctx)] + pub trait BarFoo: Foo + Bar { + fn bar_foo(&self) -> u32 { + self.bar() * self.foo() + } + } + + /// Trait generics, which the impl lists before the context parameter. + #[blanket_trait] + pub trait Scaled>: Foo { + fn scaled(&self, factor: T) -> u32 { + self.foo() * factor.into() + } + } + + /// A trait with no supertraits covers every type. + #[blanket_trait] + pub trait Everything { + const ANSWER: u32 = 42; + } + + pub struct Ctx; + + impl Foo for Ctx { + fn foo(&self) -> u32 { + 2 + } + } + + impl Bar for Ctx { + fn bar(&self) -> u32 { + 3 + } + } + + #[test] + fn the_blanket_impls_apply() { + assert_eq!(Ctx.foo_bar(), 5); + assert_eq!(Ctx.bar_foo(), 6); + assert_eq!(Ctx.scaled(4u8), 8); + assert_eq!(::ANSWER, 42); + } +} + +/// ### Lifting an associated type out of a supertrait +/// +/// The page names `HasFooTypeAt` and `BarTag` without declaring them. `HasFooTypeAt` is an +/// abstract-type trait keyed by a tag here, implemented directly on the context. +pub mod lifting_an_associated_type_out_of_a_supertrait { + use cgp::core::macros::blanket_trait; + + pub trait HasFooTypeAt { + type Foo; + } + + pub struct BarTag; + + #[blanket_trait] + pub trait HasFooTypeAtBar: HasFooTypeAt { + type FooBar: Clone; + + /// A method can name the lifted type too; the macro rewrites `Self::FooBar` to the impl's + /// parameter. + fn clone_foo(value: &Self::FooBar) -> Self::FooBar { + value.clone() + } + } + + pub struct App; + + impl HasFooTypeAt for App { + type Foo = String; + } + + #[test] + fn the_supertrait_type_is_reexported() { + let foo: ::FooBar = "foo".to_owned(); + assert_eq!(App::clone_foo(&foo), "foo"); + } +} + +/// ## Examples +/// +/// The page's extension trait and context, and the empty-body trait alias. +pub mod examples { + use cgp::core::macros::blanket_trait; + + pub trait Foo { + fn foo(&self); + } + + pub trait Bar { + fn bar(&self); + } + + #[blanket_trait] + pub trait FooBar: Foo + Bar { + fn foo_bar(&self) { + self.foo(); + self.bar(); + } + } + + pub struct Ctx; + + impl Foo for Ctx { + fn foo(&self) {} + } + + impl Bar for Ctx { + fn bar(&self) {} + } + + pub fn run(ctx: &Ctx) { + ctx.foo_bar(); + } + + pub mod trait_alias { + use cgp::core::macros::blanket_trait; + + use super::{Bar, Ctx, Foo}; + + #[blanket_trait] + pub trait FooBar: Foo + Bar {} + + pub fn needs_both(_value: &T) {} + + #[test] + fn any_foo_and_bar_is_foobar() { + needs_both(&Ctx); + } + } + + #[test] + fn the_method_runs() { + run(&Ctx); + } +} diff --git a/example-code/tests/reference/macros/cgp_auto_dispatch.rs b/example-code/tests/reference/macros/cgp_auto_dispatch.rs new file mode 100644 index 00000000..889818f5 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_auto_dispatch.rs @@ -0,0 +1,171 @@ +//! Code from `docs/reference/macros/cgp_auto_dispatch.md` — *`#[cgp_auto_dispatch]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. This file builds +//! against the `cgp` pinned in `Cargo.lock`; the *Under the hood* listing was checked with +//! `cargo cgp expand` against the local `cgp` checkout, whose matcher call is qualified. + +/// ## Examples +/// +/// The page's `Shape` enum with `HasArea` and `CanScale`, and the argument-taking `contains` the +/// page shows under the hood. +pub mod examples { + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub struct Circle { + pub radius: f64, + } + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_auto_dispatch] + pub trait HasArea { + fn area(&self) -> f64; + } + + impl HasArea for Circle { + fn area(&self) -> f64 { + core::f64::consts::PI * self.radius * self.radius + } + } + + impl HasArea for Rectangle { + fn area(&self) -> f64 { + self.width * self.height + } + } + + #[cgp_auto_dispatch] + pub trait CanScale { + fn scale(&mut self, factor: f64); + } + + impl CanScale for Circle { + fn scale(&mut self, factor: f64) { + self.radius *= factor; + } + } + + impl CanScale for Rectangle { + fn scale(&mut self, factor: f64) { + self.width *= factor; + self.height *= factor; + } + } + + #[cgp_auto_dispatch] + pub trait CanContain { + fn contains(&self, x: f64, y: f64) -> bool; + } + + impl CanContain for Circle { + fn contains(&self, x: f64, y: f64) -> bool { + x * x + y * y <= self.radius * self.radius + } + } + + impl CanContain for Rectangle { + fn contains(&self, x: f64, y: f64) -> bool { + x.abs() <= self.width / 2.0 && y.abs() <= self.height / 2.0 + } + } + + #[test] + fn the_enum_dispatches_each_method() { + let shape = Shape::Rectangle(Rectangle { + width: 2.0, + height: 2.0, + }); + assert_eq!(shape.area(), 4.0); + + let mut shape = Shape::Circle(Circle { radius: 1.0 }); + shape.scale(2.0); + assert!(shape.contains(1.5, 0.0)); + assert!(!shape.contains(2.5, 0.0)); + } +} + +/// ## Usage +/// +/// The shapes the page lists in prose: a by-value `self`, an `async` method, and a trait generic +/// parameter, each dispatched over one enum. +pub mod usage { + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Token { + Word(Word), + Number(Number), + } + + pub struct Word(pub String); + pub struct Number(pub u32); + + #[cgp_auto_dispatch] + pub trait IntoText { + fn into_text(self) -> String; + } + + impl IntoText for Word { + fn into_text(self) -> String { + self.0 + } + } + + impl IntoText for Number { + fn into_text(self) -> String { + self.0.to_string() + } + } + + #[cgp_auto_dispatch] + pub trait CanLength { + async fn length(&self) -> usize; + } + + impl CanLength for Word { + async fn length(&self) -> usize { + self.0.len() + } + } + + impl CanLength for Number { + async fn length(&self) -> usize { + self.0.to_string().len() + } + } + + #[cgp_auto_dispatch] + pub trait CanRender { + fn render(&self, prefix: Prefix) -> String; + } + + impl CanRender for Word { + fn render(&self, prefix: char) -> String { + format!("{prefix}{}", self.0) + } + } + + impl CanRender for Number { + fn render(&self, prefix: char) -> String { + format!("{prefix}{}", self.0) + } + } + + #[test] + fn every_listed_shape_dispatches() { + assert_eq!(Token::Number(Number(12)).into_text(), "12"); + assert_eq!( + futures::executor::block_on(Token::Word(Word("abc".to_owned())).length()), + 3 + ); + assert_eq!(Token::Word(Word("w".to_owned())).render('#'), "#w"); + } +} diff --git a/example-code/tests/reference/macros/cgp_auto_getter.rs b/example-code/tests/reference/macros/cgp_auto_getter.rs new file mode 100644 index 00000000..282111ff --- /dev/null +++ b/example-code/tests/reference/macros/cgp_auto_getter.rs @@ -0,0 +1,400 @@ +//! Code from `docs/reference/macros/cgp_auto_getter.md` — *`#[cgp_auto_getter]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. + +/// ## Overview +/// +/// The opening getter and a context with the field it reads. +pub mod overview { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[test] + fn any_struct_with_the_field_gets_the_getter() { + let person = Person { + name: "Ada".to_owned(), + }; + assert_eq!(person.name(), "Ada"); + } +} + +/// ## Usage +/// +/// The two-method trait, each method reading its own field. +pub mod usage { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasDimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[test] + fn each_method_reads_its_field() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(*rect.width() * *rect.height(), 6.0); + } +} + +/// ### How the return type decides the read +/// +/// One getter per row of the table, then the mutable mirrors, which the page lists in prose. +pub mod how_the_return_type_decides_the_read { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasForms { + fn by_ref(&self) -> &u32; + fn text(&self) -> &str; + fn bytes(&self) -> &[u8]; + fn maybe(&self) -> Option<&u32>; + fn maybe_text(&self) -> Option<&str>; + fn borrowed(&self) -> MRef<'_, u32>; + fn owned(&self) -> (u8, u8); + } + + #[cgp_auto_getter] + pub trait HasMutableForms { + fn by_ref(&mut self) -> &mut u32; + fn text(&mut self) -> &mut str; + fn bytes(&mut self) -> &mut [u8]; + fn maybe(&mut self) -> Option<&mut u32>; + fn maybe_text(&mut self) -> Option<&mut str>; + } + + #[derive(HasField)] + pub struct Forms { + pub by_ref: u32, + pub text: String, + pub bytes: Vec, + pub maybe: Option, + pub maybe_text: Option, + pub borrowed: u32, + pub owned: (u8, u8), + } + + #[test] + fn each_form_reads_as_the_table_says() { + let mut forms = Forms { + by_ref: 1, + text: "t".to_owned(), + bytes: vec![1, 2], + maybe: Some(3), + maybe_text: Some("m".to_owned()), + borrowed: 4, + owned: (5, 6), + }; + assert_eq!(*HasForms::by_ref(&forms), 1); + assert_eq!(HasForms::text(&forms), "t"); + assert_eq!(HasForms::bytes(&forms), &[1, 2]); + assert_eq!(HasForms::maybe(&forms), Some(&3)); + assert_eq!(HasForms::maybe_text(&forms), Some("m")); + assert!(matches!(forms.borrowed(), MRef::Ref(&4))); + assert_eq!(forms.owned(), (5, 6)); + + *HasMutableForms::by_ref(&mut forms) += 1; + HasMutableForms::text(&mut forms).make_ascii_uppercase(); + HasMutableForms::bytes(&mut forms)[0] = 9; + *HasMutableForms::maybe(&mut forms).unwrap() += 1; + HasMutableForms::maybe_text(&mut forms).unwrap().make_ascii_uppercase(); + assert_eq!(forms.by_ref, 2); + assert_eq!(forms.text, "T"); + assert_eq!(forms.bytes, vec![9, 2]); + assert_eq!(forms.maybe, Some(4)); + assert_eq!(forms.maybe_text, Some("M".to_owned())); + } +} + +/// ### Reading a field of another type +/// +/// The typed-reference getter. The page names `HasFooType` and `HasBarType` without declaring +/// them; they are abstract types here, and the field `foo_bar` lives on the `Foo` type. +pub mod reading_a_field_of_another_type { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasFooType { + type Foo; + } + + #[cgp_type] + pub trait HasBarType { + type Bar; + } + + #[cgp_auto_getter] + pub trait HasFooBar: HasFooType + HasBarType { + fn foo_bar(foo: &Self::Foo) -> &Self::Bar; + } + + #[derive(HasField)] + pub struct Foo { + pub foo_bar: u32, + } + + pub struct App; + + delegate_components! { + App { + FooTypeProviderComponent: UseType, + BarTypeProviderComponent: UseType, + } + } + + #[test] + fn the_getter_reads_the_other_type() { + let foo = Foo { foo_bar: 7 }; + assert_eq!(*App::foo_bar(&foo), 7); + } +} + +/// ### An optional `PhantomData` argument +/// +/// The page names `Foo` as both the tag and the field type; it is a unit struct here. +pub mod an_optional_phantomdata_argument { + use core::marker::PhantomData; + + use cgp::prelude::*; + + #[derive(Debug, PartialEq)] + pub struct Foo; + + #[cgp_auto_getter] + pub trait HasFoo { + fn foo(&self, _tag: PhantomData) -> &Foo; + } + + #[derive(HasField)] + pub struct Holder { + pub foo: Foo, + } + + #[test] + fn the_phantom_argument_is_forwarded() { + assert_eq!(Holder { foo: Foo }.foo(PhantomData), &Foo); + } +} + +/// ### A type inferred from the field +pub mod a_type_inferred_from_the_field { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + type Name: Display; + + fn name(&self) -> &Self::Name; + } + + #[derive(HasField)] + pub struct Numbered { + pub name: u32, + } + + #[test] + fn the_field_decides_the_type() { + assert_eq!(Numbered { name: 7 }.name().to_string(), "7"); + } +} + +/// ### Companion attributes and trait generics +/// +/// `#[extend]` and `#[use_type]` apply, becoming context bounds on the impl, and a trait's own +/// generic parameter is carried onto the impl. The page states these in prose. +pub mod companion_attributes_and_trait_generics { + use core::fmt::Debug; + + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar; + } + + #[cgp_auto_getter] + #[use_type(HasScalarType.Scalar)] + pub trait HasSide { + fn side(&self) -> &Scalar; + } + + /// `#[extend]`, which the page states in prose, on a getter of its own. + #[cgp_auto_getter] + #[extend(Debug)] + pub trait HasLabel { + fn label(&self) -> &str; + } + + #[cgp_auto_getter] + pub trait HasValue { + fn value(&self) -> &T; + } + + #[derive(Debug, HasField)] + pub struct Square { + pub side: f64, + pub value: u8, + pub label: String, + } + + delegate_components! { + Square { + ScalarTypeProviderComponent: UseType, + } + } + + #[test] + fn the_bounds_and_generics_apply() { + let square = Square { + side: 2.0, + value: 3, + label: "s".to_owned(), + }; + assert_eq!(*square.side(), 2.0); + assert_eq!(square.label(), "s"); + assert_eq!(*HasValue::::value(&square), 3); + } +} + +/// ## Examples +/// +/// The page's getter, the provider that depends on it by name, and the hand-written impl for a +/// context that stores the name elsewhere. The provider is wired and checked on `Person` here. +pub mod examples { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + pub fn greet(person: &Person) { + println!("Hello, {}!", person.name()); + } + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); + } + + #[cgp_impl(new GreetHello)] + #[uses(HasName)] + impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + pub struct Employee { + pub full_name: String, + } + + impl HasName for Employee { + fn name(&self) -> &str { + &self.full_name + } + } + + #[test] + fn both_contexts_have_names() { + let person = Person { + name: "Ada".to_owned(), + }; + greet(&person); + person.greet(); + let employee = Employee { + full_name: "Grace Hopper".to_owned(), + }; + assert_eq!(employee.name(), "Grace Hopper"); + } +} + +/// ## Common Mistakes +/// +/// The compiling halves: `#[prefix]` on an auto getter is accepted and registers nothing, the +/// workaround for the `Option` known issue, returning `Option<&mut T>` from a `&mut self` getter, +/// and the two replacements for an `Option<&[T]>` return. +pub mod common_mistakes { + use cgp::prelude::*; + + #[cgp_auto_getter] + #[prefix(@app in DefaultNamespace)] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_auto_getter] + pub trait HasMaybe { + fn maybe(&mut self) -> Option<&mut u32>; + } + + /// The two ways around the unsupported `Option<&[T]>` return. + #[cgp_auto_getter] + pub trait HasBytes { + fn bytes(&self) -> Option<&Vec>; + } + + #[cgp_auto_getter] + pub trait HasRawBytes { + fn raw_bytes(&self) -> &Option>; + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + pub maybe: Option, + pub bytes: Option>, + pub raw_bytes: Option>, + } + + #[test] + fn the_prefix_is_dropped_and_the_workaround_compiles() { + let mut person = Person { + name: "Ada".to_owned(), + maybe: Some(1), + bytes: Some(vec![1]), + raw_bytes: None, + }; + assert_eq!(person.name(), "Ada"); + assert_eq!(person.maybe(), Some(&mut 1)); + assert_eq!(person.bytes().map(|b| b.as_slice()), Some(&[1u8][..])); + assert_eq!(person.raw_bytes(), &None); + } +} diff --git a/example-code/tests/reference/macros/cgp_computer.rs b/example-code/tests/reference/macros/cgp_computer.rs new file mode 100644 index 00000000..157efffb --- /dev/null +++ b/example-code/tests/reference/macros/cgp_computer.rs @@ -0,0 +1,255 @@ +//! Code from `docs/reference/macros/cgp_computer.md` — *`#[cgp_computer]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. + +/// ## Usage +/// +/// The default and the explicit provider name, in separate modules since both define `add`. +pub mod usage { + pub mod default_name { + use core::marker::PhantomData; + + use cgp::extra::handler::Computer; + use cgp::prelude::*; + + #[cgp_computer] + fn add(a: u64, b: u64) -> u64 { + a + b + } + + #[test] + fn the_provider_is_named_after_the_function() { + assert_eq!(Add::compute(&(), PhantomData::<()>, (1, 2)), 3); + } + } + + pub mod explicit_name { + use core::marker::PhantomData; + + use cgp::extra::handler::Computer; + use cgp::prelude::*; + + #[cgp_computer(MyAdder)] + fn add(a: u64, b: u64) -> u64 { + a + b + } + + #[test] + fn the_argument_names_the_provider() { + assert_eq!(MyAdder::compute(&(), PhantomData::<()>, (1, 2)), 3); + } + } +} + +/// ### What the two axes select +/// +/// One function per row of the table, each checked through the member its bundle makes fallible +/// or async. +pub mod what_the_two_axes_select { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{AsyncComputer, Computer, Handler, TryComputer}; + use cgp::prelude::*; + + #[cgp_computer] + fn double(value: u64) -> u64 { + value * 2 + } + + #[cgp_computer] + fn halve(value: u64) -> Result { + if value % 2 == 0 { + Ok(value / 2) + } else { + Err("odd".to_owned()) + } + } + + #[cgp_computer] + async fn triple(value: u64) -> u64 { + value * 3 + } + + #[cgp_computer] + async fn third(value: u64) -> Result { + if value % 3 == 0 { + Ok(value / 3) + } else { + Err("indivisible".to_owned()) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } + } + + #[test] + fn each_row_picks_its_base_and_bundle() { + let code = PhantomData::<()>; + assert_eq!(Double::compute(&App, code, 4), 8); + assert_eq!(Double::try_compute(&App, code, 4), Ok(8)); + assert_eq!(Halve::compute(&App, code, 3), Err("odd".to_owned())); + assert_eq!(Halve::try_compute(&App, code, 3), Err("odd".to_owned())); + assert_eq!( + futures::executor::block_on(Triple::compute_async(&App, code, 2)), + 6 + ); + assert_eq!( + futures::executor::block_on(Third::handle(&App, code, 4)), + Err("indivisible".to_owned()) + ); + } +} + +/// ## Examples +/// +/// The page's `add` called through all four shapes, the fallible variant, and the generic one. +pub mod examples { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{AsyncComputer, Computer, Handler, TryComputer}; + use cgp::prelude::*; + + #[cgp_computer] + fn add(a: u64, b: u64) -> u64 { + a + b + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } + } + + pub fn demo() { + // All four are answered by the single `add` definition. + assert_eq!(Add::compute(&App, PhantomData::<()>, (1, 2)), 3); + assert_eq!(Add::try_compute(&App, PhantomData::<()>, (1, 2)), Ok(3)); + + // These futures resolve to 3 and Ok(3). + let _future = Add::compute_async(&App, PhantomData::<()>, (1, 2)); + let _future = Add::handle(&App, PhantomData::<()>, (1, 2)); + } + + #[test] + fn one_function_answers_every_shape() { + demo(); + assert_eq!(Add::compute(&App, PhantomData::<()>, (1, 2)), 3); + assert_eq!(Add::try_compute(&App, PhantomData::<()>, (1, 2)), Ok(3)); + assert_eq!( + futures::executor::block_on(Add::compute_async(&App, PhantomData::<()>, (1, 2))), + 3 + ); + assert_eq!( + futures::executor::block_on(Add::handle(&App, PhantomData::<()>, (1, 2))), + Ok(3) + ); + } + + #[cgp_computer] + fn add_with_error(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "Overflow".to_string()) + } + + #[test] + fn the_fallible_forms_propagate_the_error() { + assert_eq!( + AddWithError::try_compute(&App, PhantomData::<()>, (u64::MAX, 1)), + Err("Overflow".to_owned()) + ); + assert_eq!( + futures::executor::block_on(AddWithError::handle( + &App, + PhantomData::<()>, + (u64::MAX, 1) + )), + Err("Overflow".to_owned()) + ); + } + + #[cgp_computer] + pub fn add_generic>(a: T, b: T) -> T { + a + b + } + + #[test] + fn the_generic_provider_covers_each_type() { + assert_eq!(AddGeneric::compute(&App, PhantomData::<()>, (1u8, 2u8)), 3); + assert_eq!(AddGeneric::compute(&App, PhantomData::<()>, (1.5f64, 2.0f64)), 3.5); + } +} + +/// ## Under the hood +/// +/// The `add` provider whose impl and wiring the page lists, checked with +/// `cargo cgp expand --item reference::macros::cgp_computer::under_the_hood`, and the reference +/// parameter the page describes in prose. +pub mod under_the_hood { + use core::fmt::Display; + use core::marker::PhantomData; + + use cgp::extra::handler::{Computer, ComputerRef}; + use cgp::prelude::*; + + #[cgp_computer] + fn add(a: u64, b: u64) -> u64 { + a + b + } + + #[cgp_computer] + fn to_string_ref(value: &V) -> String { + value.to_string() + } + + #[test] + fn the_reference_input_serves_the_ref_component() { + assert_eq!(ToStringRef::compute(&(), PhantomData::<()>, &7), "7"); + assert_eq!(ToStringRef::compute_ref(&(), PhantomData::<()>, &7), "7"); + assert_eq!(Add::compute(&(), PhantomData::<()>, (1, 2)), 3); + } +} + +/// ## Common Mistakes +/// +/// The compiling half of the `Result` detection entry: a fully qualified `Result` is not +/// recognised, so the value bundle is wired and `try_compute` wraps the whole result in `Ok`. +pub mod common_mistakes { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::TryComputer; + use cgp::prelude::*; + + #[cgp_computer] + fn checked_halve(value: u64) -> core::result::Result { + if value % 2 == 0 { + Ok(value / 2) + } else { + Err("odd".to_owned()) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } + } + + #[test] + fn a_qualified_result_is_treated_as_a_value() { + assert_eq!( + CheckedHalve::try_compute(&App, PhantomData::<()>, 3), + Ok(Err("odd".to_owned())) + ); + } +} diff --git a/example-code/tests/reference/macros/cgp_getter.rs b/example-code/tests/reference/macros/cgp_getter.rs new file mode 100644 index 00000000..9cff8e35 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_getter.rs @@ -0,0 +1,325 @@ +//! Code from `docs/reference/macros/cgp_getter.md` — *`#[cgp_getter]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. + +/// ## Overview +/// +/// `Person` wires the getter to a field whose name differs from the method's. +pub mod overview { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub first_name: String, + } + + delegate_components! { + Person { + NameGetterComponent: UseField, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + + #[test] + fn the_wiring_chooses_the_field() { + let person = Person { + first_name: "Ada".to_owned(), + }; + assert_eq!(person.name(), "Ada"); + } +} + +/// ## Usage +/// +/// The derived name, the bare override, and the keyed form, each in its own module. +pub mod usage { + pub mod derived_name { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + NameGetterComponent: UseFields, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + } + + pub mod bare_override { + use cgp::prelude::*; + + #[cgp_getter(GetName)] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GetNameComponent: UseFields, + } + } + + check_components! { + Person { + GetNameComponent, + } + } + } + + /// A trait without the `Has` prefix, which gets no default and so names its provider. + pub mod keyed_form { + use cgp::prelude::*; + + #[cgp_getter { + provider: DimensionsGetter, + name: DimensionsComponent, + }] + pub trait Dimensions { + fn width(&self) -> &f64; + fn height(&self) -> &f64; + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + DimensionsComponent: UseFields, + } + } + + check_components! { + Rectangle { + DimensionsComponent, + } + } + } +} + +/// ### What a context can wire it to +/// +/// All three providers, and the direct impl. `WithProvider` is reached through its `WithField` +/// alias, which wraps the field-getter provider `UseField`. +pub mod what_a_context_can_wire_it_to { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct ByTag { + pub first_name: String, + } + + #[derive(HasField)] + pub struct ByMethodName { + pub name: String, + } + + #[derive(HasField)] + pub struct ByFieldGetter { + pub display_name: String, + } + + delegate_components! { + ByTag { + NameGetterComponent: UseField, + } + } + + delegate_components! { + ByMethodName { + NameGetterComponent: UseFields, + } + } + + delegate_components! { + ByFieldGetter { + NameGetterComponent: WithProvider>, + } + } + + check_components! { + ByTag { + NameGetterComponent, + } + } + + check_components! { + ByMethodName { + NameGetterComponent, + } + } + + check_components! { + ByFieldGetter { + NameGetterComponent, + } + } + + #[test] + fn each_provider_reads_as_described() { + assert_eq!( + ByTag { + first_name: "a".to_owned() + } + .name(), + "a" + ); + assert_eq!( + ByMethodName { + name: "b".to_owned() + } + .name(), + "b" + ); + assert_eq!( + ByFieldGetter { + display_name: "c".to_owned() + } + .name(), + "c" + ); + } +} + +/// ## Examples +/// +/// The page's three snippets: `UseField` on `Person`, `UseFields` on `Employee`, and the direct +/// impl on `Anonymous`. The page does not declare `Employee`; it has a `name` field here. +pub mod examples { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub first_name: String, + } + + delegate_components! { + Person { + NameGetterComponent: UseField, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + + pub fn greet(person: &Person) { + println!("Hello, {}!", person.name()); + } + + #[derive(HasField)] + pub struct Employee { + pub name: String, + } + + delegate_components! { + Employee { + NameGetterComponent: UseFields, + } + } + + check_components! { + Employee { + NameGetterComponent, + } + } + + pub struct Anonymous; + + impl HasName for Anonymous { + fn name(&self) -> &str { + "anonymous" + } + } + + #[test] + fn all_three_contexts_answer() { + let person = Person { + first_name: "Ada".to_owned(), + }; + greet(&person); + assert_eq!(person.name(), "Ada"); + assert_eq!( + Employee { + name: "Grace".to_owned() + } + .name(), + "Grace" + ); + assert_eq!(Anonymous.name(), "anonymous"); + } +} + +/// ## Under the hood +/// +/// The trait whose three providers the page lists, checked with +/// `cargo cgp expand --item reference::macros::cgp_getter::under_the_hood`, plus a `&mut self` getter +/// and a slice getter, whose `WithProvider` bounds the page describes in prose. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_getter] + pub trait HasCounter { + fn counter(&mut self) -> &mut u32; + } + + #[cgp_getter] + pub trait HasBytes { + fn bytes(&self) -> &[u8]; + } + + /// `#[prefix]` registers a getter component into a namespace, as on any component. + #[cgp_getter] + #[prefix(@app in DefaultNamespace)] + pub trait HasTitle { + fn title(&self) -> &str; + } +} diff --git a/example-code/tests/reference/macros/cgp_producer.rs b/example-code/tests/reference/macros/cgp_producer.rs new file mode 100644 index 00000000..deb351f6 --- /dev/null +++ b/example-code/tests/reference/macros/cgp_producer.rs @@ -0,0 +1,161 @@ +//! Code from `docs/reference/macros/cgp_producer.md` — *`#[cgp_producer]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. + +/// ## Usage +/// +/// The default and explicit provider names, each in its own module since both define +/// `magic_number`. +pub mod usage { + pub mod default_name { + use core::marker::PhantomData; + + use cgp::extra::handler::Producer; + use cgp::prelude::*; + + #[cgp_producer] + fn magic_number() -> u64 { + 42 + } + + #[test] + fn the_provider_is_named_after_the_function() { + assert_eq!(MagicNumber::produce(&(), PhantomData::<()>), 42); + } + } + + pub mod explicit_name { + use core::marker::PhantomData; + + use cgp::extra::handler::Producer; + use cgp::prelude::*; + + #[cgp_producer(TheAnswer)] + fn magic_number() -> u64 { + 42 + } + + #[test] + fn the_argument_names_the_provider() { + assert_eq!(TheAnswer::produce(&(), PhantomData::<()>), 42); + } + } +} + +/// ## Examples +/// +/// The page's producer read through every shape, and the pipeline it seeds. The page names +/// `Double` without declaring it; it is a `#[cgp_computer]` here. +pub mod examples { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{Computer, Handler, Producer, TryComputer}; + use cgp::prelude::*; + + #[cgp_producer] + pub fn magic_number() -> u64 { + 42 + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } + } + + pub fn demo() { + // The single `magic_number` definition answers every shape, each yielding 42. + assert_eq!(MagicNumber::produce(&App, PhantomData::<()>), 42); + assert_eq!(MagicNumber::compute(&App, PhantomData::<()>, ()), 42); + assert_eq!(MagicNumber::try_compute(&App, PhantomData::<()>, "ignored"), Ok(42)); + + // The future resolves to Ok(42). + let _future = MagicNumber::handle(&App, PhantomData::<()>, ()); + } + + #[test] + fn every_shape_yields_the_value() { + demo(); + assert_eq!( + futures::executor::block_on(MagicNumber::handle(&App, PhantomData::<()>, ())), + Ok(42) + ); + } + + pub mod pipeline { + use core::marker::PhantomData; + + use cgp::extra::handler::{CanCompute, ComputerComponent, PipeHandlers}; + use cgp::prelude::*; + + use super::MagicNumber; + + #[cgp_computer] + fn double(value: u64) -> u64 { + value * 2 + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: + PipeHandlers, + } + } + + check_components! { + App { + ComputerComponent: ((), ()), + } + } + + #[test] + fn the_producer_seeds_the_pipeline() { + assert_eq!(App.compute(PhantomData::<()>, ()), 84); + } + } +} + +/// ## Common Mistakes +/// +/// A `Result` output is not interpreted: `produce` returns it as a value, and `try_compute` wraps +/// it in `Ok`, which is the output the page quotes. +pub mod common_mistakes { + use core::marker::PhantomData; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::extra::handler::{Producer, TryComputer}; + use cgp::prelude::*; + + #[cgp_producer] + fn failing() -> Result { + Err("nope".to_owned()) + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } + } + + #[test] + fn the_result_is_wrapped_again() { + assert_eq!( + Failing::produce(&App, PhantomData::<()>), + Err("nope".to_owned()) + ); + assert_eq!( + Failing::try_compute(&App, PhantomData::<()>, ()), + Ok(Err("nope".to_owned())) + ); + } +} diff --git a/example-code/tests/reference/macros/mod.rs b/example-code/tests/reference/macros/mod.rs index 618af3d7..7252ff36 100644 --- a/example-code/tests/reference/macros/mod.rs +++ b/example-code/tests/reference/macros/mod.rs @@ -1,9 +1,16 @@ //! Code from the pages under `docs/reference/macros/`. +pub mod async_trait; +pub mod blanket_trait; +pub mod cgp_auto_dispatch; +pub mod cgp_auto_getter; pub mod cgp_component; +pub mod cgp_computer; pub mod cgp_fn; +pub mod cgp_getter; pub mod cgp_impl; pub mod cgp_namespace; +pub mod cgp_producer; pub mod cgp_provider; pub mod cgp_type; pub mod delegate_components; From 0a44e55966905f4d3d9f7f103ccc4b8f1421fcac Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 14:32:22 +0000 Subject: [PATCH 112/516] Review the M2 macro pages Add what the implementation notes and the Handlers concept page carried and the reference pages lacked, each probed: #[cgp_computer] reads only parameter types, both function macros default an omitted return to (), and a Result computer's error type must equal the context's (E0271). Correct the #[cgp_auto_dispatch] E0119 wording to match its example, the Option> workaround, and the producer pipeline call, and trim a repeated sentence. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/cgp_auto_dispatch.md | 4 +- docs/reference/macros/cgp_auto_getter.md | 2 +- docs/reference/macros/cgp_computer.md | 21 +++++-- docs/reference/macros/cgp_producer.md | 8 ++- ...r_common_mistakes_mismatched_error_type.rs | 25 +++++++++ ...mmon_mistakes_mismatched_error_type.stderr | 55 +++++++++++++++++++ .../tests/reference/macros/cgp_computer.rs | 22 ++++++++ .../tests/reference/macros/cgp_producer.rs | 16 ++++++ 8 files changed, 143 insertions(+), 10 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 942c7a6c..38c16eab 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -285,8 +285,8 @@ error[E0599]: the method `area` exists for reference `&Plain`, but its trait bou **The generated impl is a blanket impl over every type that implements `HasExtractor`.** This lets it cover any extensible enum whose payloads implement the trait. A hand-written impl for a type -outside that set, such as the payload structs themselves, coexists with it, but one for another -extensible enum collides: +outside that set, such as the payload structs themselves, coexists with it, but one for any +extensible enum collides, including the enum the trait was written for: ```text error[E0119]: conflicting implementations of trait `HasArea` for type `Shape` diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index fe00cefd..e48650b5 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -389,7 +389,7 @@ bounds the field as `Option<[u8]>`: error[E0277]: the size for values of type `[u8]` cannot be known at compilation time ``` -Return `Option<&Vec>` from a `Vec` field, or read the option with `&Option>` and convert +From an `Option>` field, return `Option<&Vec>`, or return `&Option>` and convert at the call site. **`#[prefix]` and `#[derive_delegate]` are accepted and dropped.** The macro runs the attribute diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 03808992..8d749659 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -62,8 +62,9 @@ The function's shape decides everything else: - **Its parameters become the input.** Several parameters are collected into one tuple, so `fn add(a: u64, b: u64)` has input `(u64, u64)`. A single parameter's input is its bare type, and - no parameters give `()`. -- **Its return type becomes the output.** + no parameters give `()`. Only the parameter *types* matter, so a destructuring pattern such as + `(a, b): (u64, u64)` is accepted and the input is that tuple type. +- **Its return type becomes the output**, and an omitted return type is `()`. - **It must not take `self`.** A handler provider has no receiver; the context is supplied separately by the handler machinery. - **It may be `async`**, and it may return a `Result`. Those two choices select the base trait. @@ -123,8 +124,8 @@ pub fn demo() { } ``` -`App` is an [environmental context](/docs/reference/glossary#environmental-context) with no fields: -it exists to supply the error type. +`App` is an [environmental context](/docs/reference/glossary#environmental-context) with no +fields. Because the function returns a plain `u64`, the fallible forms always succeed. Switching it to return a `Result` changes which bundle is wired and therefore what those forms mean, with no change at the call @@ -293,6 +294,18 @@ error: expected `,` Write the full `Result` form in a fallible computer's signature. +**A `Result` function's error type must be the context's error type.** The fallible bundles pass +the `Err` through unchanged rather than converting it, so a function returning +`Result` needs a context whose error type is `String`, and any other type fails the +fallible members: + +```text +error[E0271]: type mismatch resolving `::Error == String` +``` + +Convert inside the function, or write a `TryComputer` provider by hand that raises its own error +through the context. + **A function with a receiver is rejected**, with *Computer functions cannot have a receiver*. **A `Result` return changes the bundle, not the base trait.** The `Computer` impl's `Output` *is* the diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 0311af20..ad7e55fd 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -50,7 +50,8 @@ fn magic_number() -> u64 { ``` Omitted, the provider struct takes the function name in PascalCase: `magic_number` becomes `MagicNumber`. -Given, the argument is used verbatim. The function's return type becomes the producer's output. +Given, the argument is used verbatim. The function's return type becomes the producer's output, and +an omitted return type is `()`. **The function is constrained tightly, to exactly what a producer can be.** Each restriction is enforced at expansion time with its own message: @@ -105,8 +106,9 @@ type wired into it lets the fallible forms build their `Result`, and the produce `Ok`. The typical use is as the first step of a pipeline, where a producer seeds the value the later steps -transform. With `Double` a `#[cgp_computer]` that doubles its input, and `ComputerComponent` and -`PipeHandlers` imported from `cgp::extra::handler`, `app.compute(PhantomData::<()>, ())` returns 84: +transform. With `Double` a `#[cgp_computer]` that doubles its input, and `CanCompute`, +`ComputerComponent`, and `PipeHandlers` imported from `cgp::extra::handler`, +`App.compute(PhantomData::<()>, ())` returns 84: ```rust delegate_components! { diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.rs new file mode 100644 index 00000000..4fa5cf5a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.rs @@ -0,0 +1,25 @@ +//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: a `Result` function's error type must +//! be the context's error type, since the fallible bundles do not convert it. + +use core::marker::PhantomData; + +use cgp::core::error::ErrorTypeProviderComponent; +use cgp::extra::handler::TryComputer; +use cgp::prelude::*; + +#[cgp_computer] +fn checked_add(a: u64, b: u64) -> Result { + a.checked_add(b).ok_or_else(|| "overflow".to_owned()) +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + } +} + +fn main() { + let _ = CheckedAdd::try_compute(&App, PhantomData::<()>, (1, 2)); +} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr new file mode 100644 index 00000000..7139823b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr @@ -0,0 +1,55 @@ +error[E0271]: type mismatch resolving `::Error == String` + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.rs:24:13 + | +24 | let _ = CheckedAdd::try_compute(&App, PhantomData::<()>, (1, 2)); + | ^^^^^^^^^^ expected `String`, found `u32` + | + = note: required for `TryPromote` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `CheckedAdd` to implement `IsProviderFor` +note: required by a bound in `cgp::prelude::TryComputer::try_compute` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/try_compute.rs:8:1 + | + 8 | #[cgp_component(TryComputer)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `TryComputer::try_compute` +... +16 | fn try_compute(&self, _code: PhantomData, input: Input) -> Result; + | ----------- required by a bound in this associated function + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `TryPromote: TryComputer` is not satisfied + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.rs:24:13 + | +24 | let _ = CheckedAdd::try_compute(&App, PhantomData::<()>, (1, 2)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TryComputer` is not implemented for `TryPromote` + | +help: the trait `TryComputer` is conditionally implemented for `TryPromote` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/providers/try_promote.rs:11:1 + | +11 | / impl TryComputer +12 | | for TryPromote +13 | | where +14 | | Context: HasErrorType, +15 | | Provider: Computer>, + | |______________________________________________---------------------------------------_^ + | | + | unsatisfied requirement introduced here: `>::Output == Result<_, ::Error>` + = note: required for `CheckedAdd` to implement `TryComputer` + +error[E0271]: type mismatch resolving `>::Output == Result` + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.rs:24:13 + | +24 | let _ = CheckedAdd::try_compute(&App, PhantomData::<()>, (1, 2)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `>::Output == Result` + | +note: expected this to be `Result` + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.rs:11:35 + | +11 | fn checked_add(a: u64, b: u64) -> Result { + | ^^^^^^^^^^^^^^^^^^^ + = note: expected enum `Result` + found enum `Result` + = note: required for `TryPromote` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `CheckedAdd` to implement `IsProviderFor` + = note: required for `CheckedAdd` to implement `TryComputer` diff --git a/example-code/tests/reference/macros/cgp_computer.rs b/example-code/tests/reference/macros/cgp_computer.rs index 157efffb..345fc8c7 100644 --- a/example-code/tests/reference/macros/cgp_computer.rs +++ b/example-code/tests/reference/macros/cgp_computer.rs @@ -23,6 +23,28 @@ pub mod usage { } } + /// A destructuring parameter and an omitted return type, which the page states in prose. + pub mod patterns_and_unit_output { + use core::marker::PhantomData; + + use cgp::extra::handler::Computer; + use cgp::prelude::*; + + #[cgp_computer] + fn sum_pair((a, b): (u64, u64)) -> u64 { + a + b + } + + #[cgp_computer] + fn log_value(_value: u64) {} + + #[test] + fn only_the_types_are_read() { + assert_eq!(SumPair::compute(&(), PhantomData::<()>, (1, 2)), 3); + let () = LogValue::compute(&(), PhantomData::<()>, 5); + } + } + pub mod explicit_name { use core::marker::PhantomData; diff --git a/example-code/tests/reference/macros/cgp_producer.rs b/example-code/tests/reference/macros/cgp_producer.rs index deb351f6..1ab648c6 100644 --- a/example-code/tests/reference/macros/cgp_producer.rs +++ b/example-code/tests/reference/macros/cgp_producer.rs @@ -24,6 +24,22 @@ pub mod usage { } } + /// An omitted return type, which the page states in prose. + pub mod unit_output { + use core::marker::PhantomData; + + use cgp::extra::handler::Producer; + use cgp::prelude::*; + + #[cgp_producer] + fn nothing() {} + + #[test] + fn the_output_is_unit() { + let () = Nothing::produce(&(), PhantomData::<()>); + } + } + pub mod explicit_name { use core::marker::PhantomData; From 67e3f49ad00102848ba25fb209a89b1a0b1ca6b6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 15:14:24 +0000 Subject: [PATCH 113/516] Revise the wiring and checking macro reference pages Resync delegate_components!, delegate_and_check_components!, check_components!, and cgp_namespace! with their internal documents and the source, and revise their writing. Corrections found by probing: a child namespace's more specific path conflicts rather than winning; a generic component checked without parameters is checked at unit parameters; a const parameter cannot reach a table struct the macro declares; UseDelegate2 is a user-defined wrapper; #[check_providers] on a generic table fails; and every quoted diagnostic now comes from a run. Rewrite the stale delegate_components mirror against the current page, add mirrors for check_components and delegate_and_check_components, and add a trybuild fixture for every error the four pages quote. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/cgp_namespace.md | 66 +- docs/reference/macros/check_components.md | 106 ++- .../macros/delegate_and_check_components.md | 127 ++- docs/reference/macros/delegate_components.md | 163 ++-- example-code/README.md | 2 +- ...on_mistakes_child_redefines_parent_path.rs | 18 + ...istakes_child_redefines_parent_path.stderr | 7 + ...on_mistakes_context_overrides_bound_key.rs | 32 + ...istakes_context_overrides_bound_key.stderr | 17 + ...namespace_common_mistakes_unbound_route.rs | 30 + ...space_common_mistakes_unbound_route.stderr | 38 + ...ents_common_mistakes_aggregate_provider.rs | 28 + ..._common_mistakes_aggregate_provider.stderr | 27 + ...stakes_check_providers_on_generic_table.rs | 36 + ...es_check_providers_on_generic_table.stderr | 17 + ..._common_mistakes_derived_name_collision.rs | 40 + ...mon_mistakes_derived_name_collision.stderr | 26 + ...ponents_common_mistakes_duplicate_entry.rs | 34 + ...nts_common_mistakes_duplicate_entry.stderr | 11 + ...s_common_mistakes_empty_check_providers.rs | 25 + ...mmon_mistakes_empty_check_providers.stderr | 5 + ...mon_mistakes_generic_without_parameters.rs | 32 + ...mistakes_generic_without_parameters.stderr | 28 + ...nents_common_mistakes_reference_context.rs | 24 + ...s_common_mistakes_reference_context.stderr | 5 + ...h_generic_parameters_caret_on_parameter.rs | 33 + ...neric_parameters_caret_on_parameter.stderr | 28 + ...ck_components_examples_wrong_field_name.rs | 33 + ...omponents_examples_wrong_field_name.stderr | 28 + ...onents_formal_grammar_invalid_attribute.rs | 25 + ...ts_formal_grammar_invalid_attribute.stderr | 5 + ...nents_formal_grammar_repeated_attribute.rs | 26 + ...s_formal_grammar_repeated_attribute.stderr | 5 + ...on_a_list_key_merge_duplicate_parameter.rs | 38 + ..._list_key_merge_duplicate_parameter.stderr | 14 + ...es_on_a_list_key_merge_skip_with_params.rs | 38 + ...n_a_list_key_merge_skip_with_params.stderr | 5 + ...ents_common_mistakes_aggregate_provider.rs | 28 + ..._common_mistakes_aggregate_provider.stderr | 32 + ...n_mistakes_generic_without_check_params.rs | 34 + ...stakes_generic_without_check_params.stderr | 28 + ...ts_common_mistakes_two_entry_attributes.rs | 30 + ...ommon_mistakes_two_entry_attributes.stderr | 5 + ..._naming_the_check_trait_other_attribute.rs | 29 + ...ing_the_check_trait_other_attribute.stderr | 5 + ...s_naming_the_check_trait_two_attributes.rs | 30 + ...ming_the_check_trait_two_attributes.stderr | 5 + ...nts_skipping_one_entrys_check_arguments.rs | 29 + ...skipping_one_entrys_check_arguments.stderr | 5 + ...ipping_one_entrys_check_other_attribute.rs | 29 + ...ng_one_entrys_check_other_attribute.stderr | 5 + ..._that_quietly_check_nothing_generic_key.rs | 29 + ...t_quietly_check_nothing_generic_key.stderr | 26 + ..._and_what_is_checked_path_key_attribute.rs | 31 + ..._what_is_checked_path_key_attribute.stderr | 5 + ...delegate_components_attributes_rejected.rs | 30 + ...gate_components_attributes_rejected.stderr | 5 + ...common_mistakes_braced_group_then_path.rs} | 2 +- ...on_mistakes_braced_group_then_path.stderr} | 2 +- ...onents_common_mistakes_const_new_target.rs | 22 + ...ts_common_mistakes_const_new_target.stderr | 5 + ...omponents_common_mistakes_duplicate_key.rs | 31 + ...nents_common_mistakes_duplicate_key.stderr | 19 + ...ponents_common_mistakes_statements_lead.rs | 31 + ...nts_common_mistakes_statements_lead.stderr | 5 + ...nts_common_mistakes_undeclared_provider.rs | 29 + ...common_mistakes_undeclared_provider.stderr | 5 + ...onents_formal_grammar_inner_table_bound.rs | 33 + ...ts_formal_grammar_inner_table_bound.stderr | 5 + ...onents_formal_grammar_inner_table_const.rs | 33 + ...ts_formal_grammar_inner_table_const.stderr | 5 + ...ents_formal_grammar_key_generic_default.rs | 31 + ..._formal_grammar_key_generic_default.stderr | 5 + ...omponents_open_statement_braceless_list.rs | 29 + ...nents_open_statement_braceless_list.stderr | 5 + ..._the_key_forms_generic_list_on_list_key.rs | 31 + ..._key_forms_generic_list_on_list_key.stderr | 5 + ...the_namespace_statements_namespace_path.rs | 16 + ...namespace_statements_namespace_path.stderr | 13 + ...the_value_forms_missing_derive_delegate.rs | 36 + ...value_forms_missing_derive_delegate.stderr | 33 + ...nents_the_value_forms_qualified_wrapper.rs | 31 + ...s_the_value_forms_qualified_wrapper.stderr | 5 + .../tests/reference/macros/cgp_namespace.rs | 168 +++- .../reference/macros/check_components.rs | 330 +++++++ .../macros/delegate_and_check_components.rs | 611 ++++++++++++ .../reference/macros/delegate_components.rs | 883 +++++++++++++----- example-code/tests/reference/macros/mod.rs | 2 + 88 files changed, 3680 insertions(+), 423 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.rs create mode 100644 example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_attributes_rejected.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_attributes_rejected.stderr rename example-code/tests/compile_fail/reference/macros/{delegate_components_gotchas.rs => delegate_components_common_mistakes_braced_group_then_path.rs} (85%) rename example-code/tests/compile_fail/reference/macros/{delegate_components_gotchas.stderr => delegate_components_common_mistakes_braced_group_then_path.stderr} (56%) create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.rs create mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.stderr create mode 100644 example-code/tests/reference/macros/check_components.rs create mode 100644 example-code/tests/reference/macros/delegate_and_check_components.rs diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index ad2aac70..cb736153 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -68,9 +68,10 @@ A namespace body accepts two kinds of entry, and they do different things. | `Key: Provider` | **Bind.** Asked for `Key`, resolve straight to `Provider`, as in `delegate_components!`. | Redirection makes namespaces composable: because a lookup is keyed by a *path* rather than a bare -component name, a whole subtree can be rerouted at once, and a more specific path takes precedence over an -inherited one. Paths are written with the `@` sigil as dotted sequences, such as `@MyFooComponent`, -`@app.ErrorRaiserComponent`, and `@cgp.core.error`, where lowercase segments become [type-level strings](/docs/reference/glossary#type-level-string) and +component name, a whole subtree can be rerouted at once, and a context can fill one path the +namespace leaves open without disturbing the rest. Paths are written with the `@` sigil as dotted +sequences, such as `@MyFooComponent`, `@app.ErrorRaiserComponent`, and `@cgp.core.error`, where +lowercase segments become [type-level strings](/docs/reference/glossary#type-level-string) and capitalized segments name types. [`Path!`](./path.md) covers the syntax in full. ### The rest of the body grammar @@ -110,8 +111,12 @@ cgp_namespace! { } ``` -The parent may itself be parameterized. The child's entries layer on top, and a path-rewriting entry like -the one above reroutes a whole subtree of the parent's namespace rather than a single component. +The parent may itself be parameterized, and may be named by a path. The child's entries sit beside +everything it inherits: they may add keys the parent does not resolve, but not redefine one it does, as +[Common Mistakes](#common-mistakes) explains. A path-rewriting entry like the one above qualifies when +the parent routes the `@cgp.core.error` prefix onward without binding it, as a parent inheriting +`DefaultNamespace` does for CGP's error components, and it reroutes a whole subtree of those routes +rather than a single component. A namespace with nothing of its own to add may stop at the header. The braces are optional when the body would be empty, which is the usual shape of a namespace that exists only to inherit: @@ -122,9 +127,11 @@ cgp_namespace! { } ``` -This is the same as writing `{}` after the parent, and `new BaseNamespace` on its own emits just the -trait and struct the same way. Only the end of the input may follow the header; any other token there is -an `expected curly braces` error. The shorthand is this macro's alone, since +This is the same as writing `{}` after the parent, and `new BaseNamespace` on its own, with no parent +and no braces, emits only the trait and struct. Only the end of the input may follow the header; any other token there is +an `expected curly braces` error. Without `new`, a header-only `ExtendedNamespace: BaseNamespace` emits +only the inheritance impl, so it compiles only where the `ExtendedNamespace` trait and its +`__ExtendedNamespaceComponents` struct are already declared. The shorthand is this macro's alone, since [`delegate_components!`](./delegate_components.md) keeps its braces even when its table is empty. ### The other two halves: registering, and joining @@ -246,14 +253,22 @@ A few lighter tools cover most cases, and it is worth knowing where each stops. when inheritance is wanted, or when a library is publishing defaults for applications it does not know about. +The last two also combine. A context that joins a namespace can forward a whole path to an aggregate +provider in one entry, as `@app.core.user: UserComponents`, and the bundle then answers every component +registered under that path. The lookup reaches the bundle keyed by the bare component name, so a bundle +keyed by bare names needs nothing more. A bundle that groups several paths, such as a `CoreComponents` +holding `@app.core.user: UserComponents`, is keyed by paths and must itself join the namespace, or the +check fails with `CoreComponents: DelegateComponent` unsatisfied. + A couple of things a namespace is *not* for. It will not make a single context's wiring shorter on its own; the entries still have to exist somewhere. And it is not how one component gets per-type dispatch, which is `open`'s job; the two do not combine on the same component, as the [Common Mistakes](#common-mistakes) explain. ## Under the hood -`cgp_namespace!` emits, in order, an optional backing struct, an optional lookup trait, and one impl of that -trait per entry, plus one inheritance impl when a parent is named. From this input: +`cgp_namespace!` emits, in order, an optional backing struct, an optional lookup trait, the structs of any +nested tables, and then the impls: one inheritance impl first when a parent is named, one impl of the trait +per entry, and the nested tables' own impls. From this input: ```rust cgp_namespace! { @@ -308,7 +323,9 @@ where ``` For any key the parent resolves, the child resolves it to the same value. The child's own entries are emitted -after this impl and win where their keys are more specific. +after this impl and sit beside it rather than overriding it, since Rust has no rule that lets a more +specific impl win. A child entry must therefore be keyed on a path the parent does not resolve, and a +longer path beneath one the parent resolves overlaps it too, because every path key ends in a wildcard. A couple of naming details appear verbatim in errors and are worth recognizing: the table parameter is literally `__Table__`, and the inheritance impl uses `__Key__` and `__Value__`. And every `@` path is a @@ -356,8 +373,17 @@ blanket `DelegateComponent` impl covering every path `N` resolves, so a direct e paths is a second impl for the same key and the compiler rejects the overlap with `E0119`. A context can wire only a path the namespace *routes to* without binding, which is why the example above has the namespace own the route and the context own the provider. A path the namespace binds with a `:` entry or -a `#[default_impl]` has to be changed in the namespace instead. The same restriction stops a child -namespace from redefining a key its parent binds. +a `#[default_impl]` has to be changed in the namespace instead. + +The same restriction stops a child namespace from redefining a key its parent resolves, and a more +specific path does not escape it. With the parent routing `@app => @base`, a child entry +`@app.Seg => @child` still overlaps, because the parent's key ends in a wildcard that covers `@app.Seg`: + +```text +error[E0119]: conflicting implementations of trait `ExtendedNamespace<_>` for type `PathCons>, PathCons>` +``` + +The `Chars` nest, which spells `app`, is shortened here. **Joining two namespaces on one context conflicts, for the same reason.** Each namespace produces a blanket forwarding impl covering every key, so joining two collides them: @@ -369,6 +395,11 @@ error[E0119]: conflicting implementations of trait `DelegateComponent<_>` for ty A bare-key `for` loop (`for in Table { Key: Value }`) alongside a `namespace` join collides the same way, which is why a loop's key is normally embedded in a path, as in `@app.SomeComponent.Key: Value`. +**The `namespace` statement takes a bare name.** A namespace from another module cannot be written as a +path there: `namespace some_mod::AppNamespace;` fails with ``expected `;` `` at the `::`. Import the +namespace first and join it by its name. The inheritance header and a `for` loop's `in` clause both accept +a path. + **`open` does not combine with a prefixed component in a joined namespace.** Once a component's lookups are routed under a prefix, `open`, which roots the route at the bare component name, no longer reaches those entries. Write the per-value entries with the full prefixed path instead. @@ -397,13 +428,12 @@ context compiles regardless. Only a [`check_components!`](./check_components.md) reports is the *path* failing to resolve rather than a provider being absent: ```text -error[E0277]: the trait bound `PathCons>, ...>: AppNamespace<...>` - is not satisfied +error[E0277]: the trait bound `PathCons>, PathCons>: AppNamespace` is not satisfied ``` -The `Symbol<4, …>` is the prefix, `show`, so the message is saying "this route is not something the -namespace resolves". This is the lazy-wiring problem in a namespace setting, and the answer is the same: check -the context. +The `Symbol<4, …>` is the prefix, `show`, with its `Chars` nest shortened here, so the message is +saying "this route is not something the namespace resolves". This is the lazy-wiring problem in a +namespace setting, and the answer is the same: check the context. ## Related constructs diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index dfbf242e..ef0048fa 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -57,7 +57,8 @@ check_components! { } ``` -Several tables may appear in one invocation, each with its own context type and attributes. +Several tables may appear in one invocation, one after another with no separator, each with its own +context type and attributes. An invocation with no table at all is accepted and emits nothing. ### Components with generic parameters @@ -85,15 +86,21 @@ check_components! { } ``` -That is four checks from one entry. A table may also carry a leading `<...>` generic list and a trailing -`where` clause, to introduce and constrain generics the checked parameters use. +That is four checks from one entry. A table may also carry a leading `<...>` generic list and a `where` +clause after the context type, to introduce and constrain generics the checked parameters use, and a +parameter may carry a generic list of its own, as in `AreaCalculatorComponent: <'a> &'a Rectangle`. + +A failed check points at the entry it came from. The caret lands on the component, or on the +parameter when a bracketed value lists more parameters than its key names components, so +`AreaCalculatorComponent: [Rectangle, Circle]` shows which of the two shapes failed. ### Naming the check trait The macro derives a trait name of the form `__Check{Context}` (`__CheckPerson`) from the **final segment** of the context's path, so `some_mod::Person` also yields `__CheckPerson`. Override it with `#[check_trait(Name)]` on the table. You need this when two tables in one module would otherwise -collide: +collide, and when the context is not a path at all, such as `&'a Person`, from which no name can be +derived: ```rust check_components! { @@ -130,31 +137,28 @@ check_components! { **This localizes a broken layer of a nested provider stack**, and it is the main reason to keep `check_components!` separate from the wiring. A dependency missing only from the outer wrapper fails the wrapper's line alone, while one missing from the inner provider fails both. The pattern of failures -tells you which layer to look at. It must list at least one provider, and may appear at most once per table. +tells you which layer to look at. It must list at least one provider, and may appear at most once per +table. The listed providers are checked against the table's context type as written, so this form needs a +concrete context rather than a generic table, as [Common Mistakes](#common-mistakes) explains. ## Examples -A check that catches a real mistake. The provider needs a `name` field, and the context has the wrong field +A check that catches a real mistake. The provider reads a `name` field through an +[`#[implicit]`](../attributes/implicit.md) argument, and the context stores the value under another name: ```rust use cgp::prelude::*; -#[cgp_auto_getter] -pub trait HasName { - fn name(&self) -> &str; -} - #[cgp_component(Greeter)] pub trait CanGreet { fn greet(&self); } #[cgp_impl(new GreetHello)] -#[uses(HasName)] impl Greeter { - fn greet(&self) { - println!("Hello, {}!", self.name()); + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); } } @@ -177,8 +181,13 @@ check_components! { ``` The `delegate_components!` block compiles on its own, because wiring is lazy. The `check_components!` block -does not. It fails *here*, naming the missing field, rather than at some later `person.greet()` in -another file. +does not. It fails *here*, with `E0277` at the `GreeterComponent` entry, and the compiler's help names +the cause: `Person` does not implement `HasField` for the `name` tag, which rustc prints as the nested +`Symbol<4, Chars<'n', …>>` type. The mismatch is reported at the wiring rather than at some later +`person.greet()` in another file. [`cargo cgp check`](/docs/cargo-cgp/check) reports the same failure +with the root cause first, as ``[CGP-E106] missing field `name` on `Person` ``. `cargo cgp check` +leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not +yet reshape every class. A generic component supplies its parameters, and the bracketed form checks several at once: @@ -208,7 +217,8 @@ choice of macro scales with the wiring's complexity. read: the `open` statement, `@`-path keys, and [namespaces](./cgp_namespace.md). - **Use [`delegate_and_check_components!`](./delegate_and_check_components.md) while getting started, or for plain `Component: Provider` tables.** It fuses wiring and checking so the check cannot be forgotten. A - newcomer needs exactly that. Its derivation understands only the plain entry form. + newcomer needs exactly that. Its derivation understands only `:` and `->` entries keyed on a component + name. - **Do not check an [aggregate provider](./delegate_components.md#defining-the-target-at-the-same-time) as though it were a context.** A `new`-keyword bundle is delegated *to*; it has no fields and never stands in the context position, so a context-side check on it asks the wrong question. Verify it through a real @@ -288,7 +298,7 @@ The input is one or more check tables, in the Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): ```ebnf -CheckComponents -> CheckTable+ +CheckComponents -> CheckTable* CheckTable -> TableAttr* Generics? ContextType WhereClause? `{` CheckEntries `}` @@ -310,14 +320,17 @@ CheckValue -> CheckParam CheckParam -> Generics? Type ``` -One invocation may carry several `CheckTable`s, written one after another with no separator. This is how -a module checks two contexts from one block. Both `TableAttr`s are optional, each may appear at most once, -and any other attribute is rejected by name rather than ignored. `#[check_trait(...)]` overrides the derived -`__Check{Context}` name, and `#[check_providers(...)]` switches the assertion to the listed providers. A -`CheckEntry`'s value is omitted for a component with no generic parameters; when present, a bracketed -`CheckKey` or `CheckValue` expands to the cartesian product. A `CheckParam` may carry its own generic list, -which is merged with the table's before the impl is emitted. `Generics`, `WhereClause`, and `Type` are Rust -grammar productions. +One invocation may carry several `CheckTable`s, written one after another with no separator, or none +at all. This is how a module checks two contexts from one block. Both `TableAttr`s are optional, in +either order, and each may appear at most once: a repeat fails with +``Multiple `#[check_trait]` attributes found. Expected at most one.`` or its `check_providers` twin. +Any other attribute is rejected by name, as `Invalid attribute #[allow(unused)]`, rather than +ignored. `#[check_trait(...)]` overrides the derived `__Check{Context}` name, and +`#[check_providers(...)]` switches the assertion to the listed providers. A `CheckEntry`'s value is +omitted for a component with no generic parameters; when present, a bracketed `CheckKey` or +`CheckValue` expands to the cartesian product. A `CheckParam` may carry its own generic list, which +is merged with the table's before the impl is emitted. `Generics`, `WhereClause`, and `Type` are +Rust grammar productions. Both bracketed lists accept **zero** elements, and the empty forms behave differently. An empty value list, `FooComponent: []`, falls back to the no-parameter check, exactly as omitting the colon would. An @@ -332,26 +345,26 @@ provider's dependencies. If that provider has none, the check passes vacuously a needs anything from its context, such as a field or a type, the check fails, blaming the bundle: ```text -error[E0277]: the trait bound `GeometryComponents: CanUseComponent` - is not satisfied -note: required for `RectangleArea` to implement - `IsProviderFor` +error[E0277]: the trait bound `GeometryComponents: CanUseComponent` is not satisfied +note: required for `RectangleArea` to implement `IsProviderFor` ``` Nothing there says the target was never meant to be a context. Wire the bundle with plain [`delegate_components!`](./delegate_components.md) and check it through a real context instead. -**A component with generic parameters cannot be checked without them, and the error does not say so.** -Omitting the value emits a check with an empty parameter tuple, which a component expecting a `Shape` can -never satisfy. You get an ordinary unsatisfied-wiring complaint that never mentions the -parameters: +**A component with generic parameters checked without them is checked at `()`.** Omitting the value +emits a check with unit parameters, which asks whether the context can use `CanCalculateArea<()>`. A +provider generic over every shape passes that vacuously, proving nothing about the shapes the context +uses. A provider written for particular shapes fails it, with a complaint that reads like a broken +provider: ```text -error[E0277]: the trait bound `App: CanUseComponent` is not satisfied +error[E0277]: the trait bound `RectangleArea: IsProviderFor` is not satisfied ``` -That looks identical to a broken wiring. If a check fails on a generic component and the wiring -looks right, the missing value is the first thing to suspect. +Only a help line hints at the cause, noting that the provider implements the marker for `Rectangle` +but not for `()`. If a check on a generic component fails or passes too easily, the missing value is +the first thing to suspect. **`#[check_providers(...)]` must list at least one provider**, and is rejected rather than treated as a no-op: @@ -360,6 +373,16 @@ no-op: error: `#[check_providers(...)]` requires at least one provider type. ``` +**`#[check_providers(...)]` does not work on a generic table.** The generated trait names the context +type in its supertrait, `IsProviderFor<__Component__, Gen, __Params__>`, but the table's generics +reach only the impls, so `#[check_providers(RectangleArea)] Gen { … }` fails with `E0425`, +``cannot find type `T` in this scope``, and an `E0207` beside it. Check a concrete instantiation such +as `Gen` instead. + +**Listing one check twice conflicts.** The same component and parameters named twice, directly or +through a bracketed list such as `[AreaCalculatorComponent, AreaCalculatorComponent]`, emit two +identical impls and fail with `E0119`. + **Two tables in one module can collide on the derived name.** The name comes from the context's *last* path segment, so `a::Person` and `b::Person` both derive `__CheckPerson`, and so do two tables for the same context: @@ -370,9 +393,12 @@ error[E0428]: the name `__CheckPerson` is defined multiple times Use `#[check_trait(...)]` on one of them. -**A passing check is not a claim that the implementation is correct**, only that it resolves. It -proves the -provider was found and its dependencies are satisfiable, not that the provider does what you meant. +**A context that is not a path needs a named trait.** A reference context such as `&'a Person` gives +the macro no identifier to derive a name from, and the table fails with `expected identifier` at the +context type, which does not say a name is missing. Add `#[check_trait(Name)]`. + +**A passing check is not a claim that the implementation is correct**, only that it resolves. It proves +the provider was found and its dependencies are satisfiable, not that the provider does what you meant. ## Related constructs diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index dfc9b0ab..73e68cea 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -34,8 +34,8 @@ writing both macros by hand would emit. **It is aimed at simple wiring and at getting started, not at being the default everywhere.** Its value is that a newcomer cannot forget the check and then run into the confusing errors lazy wiring produces. The -derivation understands only a mapping keyed on a component *name*, though, so a codebase whose wiring grows -past that keeps the two macros separate. The reasons are in +derivation understands only `:` and `->` mappings keyed on a component *name*, though, so a codebase whose +wiring grows past that keeps the two macros separate. The reasons are in [When to use it](#when-to-use-it). ## Usage @@ -59,7 +59,8 @@ works". The derived trait is named `__CanUse{Context}` (`__CanUseScaledRectangle`). That deliberately differs from the `__Check{Context}` name [`check_components!`](./check_components.md) derives, so both macros can be used -once each in the same module without colliding. Override it with a table-level `#[check_trait(Name)]`: +once each in the same module without colliding. Override it with a table-level `#[check_trait(Name)]`, +the one attribute the table accepts: ```rust delegate_and_check_components! { @@ -70,6 +71,9 @@ delegate_and_check_components! { } ``` +A second table attribute fails with `Expected exactly one attribute for the check trait name`, and any +other attribute with ``Expected `#[check_trait]` attribute for specifying the check trait name``. + ### Components with generic parameters A component with type parameters needs `#[check_params(...)]` on its entry. The delegation half does not @@ -79,26 +83,21 @@ macro cannot infer what from the delegation alone: ```rust delegate_and_check_components! { MyApp { - #[check_params( - Rectangle, - Circle, - )] - AreaCalculatorComponent: - UseDelegate, + #[check_params(Rectangle, Circle)] + AreaCalculatorComponent: ShapeArea, // a provider generic over the shape } } ``` -The same single-versus-tuple convention as `check_components!` applies: one parameter bare, several as a -tuple. +Each listed parameter produces its own check, and the same single-versus-tuple convention as +`check_components!` applies: one parameter bare, several as a tuple. Leave the attribute off and the +check tests the component at unit parameters instead, as [Common Mistakes](#common-mistakes) +describes. ### Skipping one entry's check `#[skip_check]` wires an entry and generates no check for it, for a component verified elsewhere. It saves -splitting out a second plain `delegate_components!` block just to leave one component unchecked: +splitting out a second plain `delegate_components!` block only to leave one component unchecked: ```rust delegate_and_check_components! { @@ -110,7 +109,10 @@ delegate_and_check_components! { ``` The two per-entry attributes are **mutually exclusive**, and at most one may appear on a given key. A -second one is rejected, as is any other attribute, and `#[skip_check]` takes no arguments. +second one fails with ``Expected at most one `#[check_params]` or `#[skip_check]` attribute``, any +other attribute with +``Expected either `#[skip_check]` or `#[check_params]` attribute for specifying the check generics``, +and `#[skip_check]` given arguments with `` `#[skip_check]` does not take any arguments ``. ### Attributes on a list key merge @@ -139,14 +141,22 @@ they ask for opposite things: error: cannot combine #[skip_check] with #[check_params] ``` +Merged lists concatenate rather than deduplicate, so a parameter named at both levels is checked twice, +and the two identical check impls conflict with `E0119`. + ### Two forms that quietly check nothing An **empty** `#[check_params()]` has no parameters to iterate over, so it skips the entry exactly as -`#[skip_check]` would, without saying so. Write `#[skip_check]` to say so directly. +`#[skip_check]` would, without saying so. Write `#[skip_check]` to say so directly. A table whose every +entry is skipped this way, or is empty, still emits the check trait, with no impls, and so verifies +nothing. A key carrying **only generics** is the opposite case and is easy to assume away: it *is* still checked, -with its generics bound on the check impl and unit parameters. ` FooKey: FooProvider` derives -`impl __CanUseContext, ()> for Context {}`, which keeps `I` from appearing unbound. +with its generics bound on the check impl and unit parameters. ` FooKeyComponent: AnyFoo` derives +`impl __CanUseApp, ()> for App {}`, which keeps `I` from appearing unbound. For a +component whose marker carries the trait's own parameter, those unit parameters do not match what the +provider implements, so the check fails with `E0277` on `AnyFoo: IsProviderFor, App>`. +Name the key's generic as the parameter instead, with `#[check_params(I)]`. ### What is wired, and what is checked @@ -168,13 +178,15 @@ literally the same evaluation. | `open` / `namespace` / `for` | yes | **no** | Nothing warns about the rows that are not checked: the block compiles, the wiring is correct, and those -components simply go unverified. That silence is the practical reason to split the macros once a table uses -more than plain entries. A standalone [`check_components!`](./check_components.md) block can name the +components go unverified. That silence is the practical reason to split the macros once a table uses more +than plain entries. A standalone [`check_components!`](./check_components.md) block can name the concrete parameters an opened component needs and cover what a namespace brought in. Attributes are accepted only where they mean something. `#[check_params(...)]` and `#[skip_check]` attach -to the table's single and list keys; on an `@`-path key, or inside a `for` loop, they are rejected outright -rather than read and ignored. +to the table's single and list keys of `:` and `->` mappings. On an `@`-path key, on the key of a `=>` +mapping, or inside a `for` loop they fail with the `unsupported attribute: …` error +`delegate_components!` raises, rather than being read and ignored. The one place an attribute is dropped +instead is a key inside a nested table, as [Common Mistakes](#common-mistakes) records. ## Examples @@ -203,31 +215,33 @@ delegate_and_check_components! { If `MyContext` were missing the `name` field, the derived check would fail here, naming the missing field, rather than letting the gap survive to some later call to `name()`. -Mixing checked and skipped entries lets a nested delegation be verified more precisely elsewhere while the -rest is checked inline: +Mixing checked and skipped entries lets a nested provider stack be verified more precisely elsewhere while +the rest is checked inline. Here the perimeter entry is checked inline, and the scaled area calculator is +checked one layer at a time by a standalone block: ```rust delegate_and_check_components! { ScaledRectangle { - AreaCalculatorComponent: - ScaledArea, + PerimeterCalculatorComponent: + RectanglePerimeter, #[skip_check] - TransformCalculatorComponent: - ComplexTransform, + AreaCalculatorComponent: + ScaledArea, } } check_components! { - #[check_providers(RectangleArea, ComplexTransform)] + #[check_providers(RectangleArea, ScaledArea)] ScaledRectangle { - TransformCalculatorComponent, + AreaCalculatorComponent, } } ``` That pairing is the usual reason to use `#[skip_check]`: the fused derivation can only check the -context, and a nested stack is better checked per layer. +context, and a nested stack is better checked per layer, where a dependency missing from the inner +`RectangleArea` fails on both providers and one missing only from `ScaledArea` fails on it alone. ## When to use it @@ -318,7 +332,10 @@ A generic table threads its generics through both halves, so ` MyContext { `impl DelegateComponent<…> for MyContext` alongside `impl __CanUseMyContext<…, ()> for MyContext {}`. A key carrying its own generics is bound on the derived check the same way, so ` BarGetterAtComponent: UseField` checks as -`impl __CanUse…, ()> for MyContext {}`. +`impl __CanUse…, ()> for MyContext {}`, and a `#[check_params(...)]` value +that mentions the key's generic is bound the same way: `#[check_params((I, Index<0>))]` on that entry +checks as `impl __CanUse…, (I, Index<0>)> for MyContext {}`. So a component +with a generic marker can be wired and checked in one step. ## Formal grammar @@ -326,7 +343,7 @@ The body is [`delegate_components!`](./delegate_components.md)'s table shape plu Rust Reference's [notation](https://doc.rust-lang.org/reference/notation.html): ```ebnf -DelegateAndCheck -> TableAttr* Generics? `new`? TargetType `{` TableBody `}` +DelegateAndCheck -> TableAttr? Generics? `new`? TargetType `{` TableBody `}` TableAttr -> `#` `[` `check_trait` `(` IDENTIFIER `)` `]` @@ -335,15 +352,19 @@ TableBody -> Statement* ( CheckedMapping ( `,` CheckedMapping )* `,`? )? CheckedMapping -> EntryAttr? Mapping // Mapping, Key, ProviderValue, Statement // see delegate_components! -EntryAttr -> `#` `[` `check_params` `(` Type ( `,` Type )* `,`? `)` `]` +EntryAttr -> `#` `[` `check_params` `(` ( Type ( `,` Type )* `,`? )? `)` `]` | `#` `[` `skip_check` `]` ``` The `Mapping`, `Key`, `ProviderValue`, and `Statement` productions are exactly [`delegate_components!`](./delegate_components.md)'s; only the attributes differ. The table-level -`#[check_trait(...)]` overrides the derived `__CanUse{Context}` name. Each mapping may carry at most one -`EntryAttr`, and the two are mutually exclusive: `#[check_params(...)]` supplies the parameters a generic -component's check needs, and `#[skip_check]` wires the entry with no check at all. +`#[check_trait(...)]` overrides the derived `__CanUse{Context}` name, and it is the only attribute the +table accepts. Each mapping may carry at most one `EntryAttr`, and the two are mutually exclusive: +`#[check_params(...)]` supplies the parameters a generic component's check needs, and `#[skip_check]` +wires the entry with no check at all. An `EntryAttr` is accepted on a single key, on a list key, and on a +single key inside a list, and only for a `:` or `->` mapping. The grammar is therefore more permissive +than the derivation, as [What is wired, and what is checked](#what-is-wired-and-what-is-checked) +explains. ## Common Mistakes @@ -353,13 +374,13 @@ dependencies. When the bundled provider needs nothing, the check passes and prov anything from its context, the check fails and blames the bundle: ```text -error[E0277]: the trait bound `GeometryComponents: CanUseComponent` - is not satisfied -note: required for `RectangleArea` to implement - `IsProviderFor` +error[E0277]: the trait bound `GeometryComponents: CanUseComponent` is not satisfied +note: required for `RectangleArea` to implement `IsProviderFor` ``` -Neither outcome is informative, and neither says the target was never meant to be a context. Use plain +The help line between them says the bundle does not implement `HasField` for the field +`RectangleArea` reads, which is the real context's job. Neither outcome is informative, and neither +says the target was never meant to be a context. Use plain [`delegate_components!`](./delegate_components.md) for a bundle. **The two per-entry attributes cannot be combined**, and the macro says so rather than picking one: @@ -368,19 +389,25 @@ Neither outcome is informative, and neither says the target was never meant to b error: Expected at most one `#[check_params]` or `#[skip_check]` attribute ``` -**A generic component without `#[check_params(...)]` cannot be checked, and the error does not say so.** The -delegation succeeds; the derived check is emitted with an empty parameter tuple, which a component expecting a -type parameter can never satisfy. An ordinary unsatisfied-marker complaint against the -provider surfaces instead: +**A generic component without `#[check_params(...)]` is checked at unit parameters**, and the result says +little either way. The derived check tests `CanCalculateArea<()>`, the component with `()` in place of +the shape. A provider generic over every shape passes it vacuously, proving nothing about the shapes the +context uses. A provider written for particular shapes fails it, with an error that reads like a broken +provider rather than an incomplete check: ```text -error[E0277]: the trait bound `RectArea: IsProviderFor` is not satisfied +error[E0277]: the trait bound `RectangleArea: IsProviderFor` is not satisfied ``` -Nothing in it mentions the missing parameters, so it reads like a broken provider rather than an incomplete -check. Add `#[check_params(...)]`, or move the entry to a standalone +Only a help line hints at the cause, noting that the provider implements the marker for `Rectangle` but +not for `()`. Add `#[check_params(...)]`, or move the entry to a standalone [`check_components!`](./check_components.md). +**An attribute on a key inside a nested table is silently dropped.** In +`UseDelegate`, the inner +`#[skip_check]` compiles and does nothing, where `delegate_components!` would reject it. The inner table's +entries are never checked in any case, since only the outer key becomes a check. + **An inherited, opened, or redirected component is not covered.** A `namespace` header, an `open` statement, an `@`-path key, and a `=>` redirect are all accepted in the table and all wired, but the derivation only produces checks for entries keyed on a component name, so a table using any of them is diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index f79f8d51..d0050262 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -64,7 +64,8 @@ delegate_components! { ### Defining the target at the same time -A leading `new` keyword makes the macro declare the target struct as well. +A leading `new` keyword makes the macro declare the target struct as well. A target with +parameters, as in ` new MyComponents { … }`, is declared with a `PhantomData` field over them. ```rust delegate_components! { @@ -154,7 +155,10 @@ The other use of `=>` is rerouting a whole path *prefix* at once, which is a ### The key forms **A single key** is one component name, and may carry generics of its own: -` ShapeAreaCalculatorComponent: SumAreas` adds a parameter to just that entry. +` ShapeAreaCalculatorComponent: SumAreas` adds a parameter to that entry alone, for a +component whose marker carries the trait's parameter through the `name:` key of +[`#[cgp_component]`](./cgp_component.md). Those generics may carry bounds, as in ``, +but not defaults. **A list key** is a bracketed list, expanding to one entry per name so several components share one value: @@ -173,9 +177,11 @@ delegate_components! { Each bracketed element is a full key, so an element may carry its own generics: in `[WidthKey, HeightKey]: RectangleValue` only the second key introduces `T2`. The -list is a key form rather than an operator, so `[A, B] -> SomeTable` and `[A, B] => @somewhere` are as -legal as `[A, B]: Provider`. The `->` form adopts several of another table's entries at once, and the -`=>` form points several components at one shared slot. +list itself takes no generic list, so ` [WidthKey, HeightKey]` fails with +`expected square brackets`; put the parameter on the element that uses it. The list is a key form +rather than an operator, so `[A, B] -> SomeTable` and `[A, B] => @somewhere` are as legal as +`[A, B]: Provider`. The `->` form adopts several of another table's entries at once, and the `=>` +form points several components at one shared slot. **A path key** is an `@`-prefixed route rather than a bare name, and it addresses a slot behind a redirect: the per-value slots an `open` statement opens, or the prefixed routes a @@ -208,9 +214,13 @@ delegate_components! { Remember it this way: `[…]` is a choice *within* a segment and `{…}` is a choice *of tails*. +Every bracketed or braced list on this page, the list key and `open { … }` included, may also be +empty. An empty list produces no entries and no error, so a list emptied by an edit compiles +silently. + ### The value forms -A value is normally just a type: the provider, or the table a `->` forwards into. One other form +A value is normally a type: the provider, or the table a `->` forwards into. One other form exists, and it is legacy. :::info @@ -240,9 +250,12 @@ delegate_components! { A few details of the form are easy to miss. The inner braces hold a **full table body**, so an inner table accepts everything an outer one does, nesting included. The **wrapper is not fixed to -`UseDelegate`**: the macro accepts any single-parameter wrapper type, which is how a component -dispatched on a tuple of parameters gets wired to a matching `UseDelegate2`. And the **inner table's -name may carry generics**, which a per-entry generic on the outer key threads into: +`UseDelegate`**: the macro accepts any wrapper named by a single identifier, so a component whose +`#[derive_delegate]` names a wrapper of your own, such as a `UseDelegate2` keyed on a tuple of its +parameters, is wired the same way. A qualified name such as `cgp::prelude::UseDelegate` is +not recognized as this form and fails with ``expected `,` `` at the inner table's name, so import +the wrapper instead. And the **inner table's name may carry generics**, which a per-entry generic on +the outer key threads into: ```rust delegate_components! { @@ -256,8 +269,9 @@ delegate_components! { One prerequisite is not visible in either snippet: **the component must carry [`#[derive_delegate(UseDelegate)]`](../attributes/derive_delegate.md)**, which generates the -dispatch impl the wrapper resolves through. Leave it off and the table still expands, then fails at the -check with an unsatisfied `IsProviderFor` that never mentions the missing attribute. +dispatch impl the wrapper resolves through. Leave it off and the table still expands, then fails at +the check with `E0277`, an unsatisfied `IsProviderFor` on `UseDelegate<…>` that never mentions the +missing attribute. ### Choosing a provider per type: the `open` statement @@ -290,14 +304,15 @@ delegate_components! { Braces are optional when opening a single component, so `open AreaCalculatorComponent;` and `open { AreaCalculatorComponent };` are the same. The braced list is needed to open several at once, -and the macro rejects a braceless header naming more than one component. +and a braceless header naming more than one component fails with ``expected `;` `` at the first +comma. **A key has one path segment per type parameter of the component, so `open` dispatches on any of them.** The redirect appends every type parameter to the lookup path, in declaration order, so a -lookup of `CanCompute` follows `@ComputerComponent.Code.Input`. A key that stops after -the first segment matches that value of the first parameter with every value of the rest, and a -per-entry generic in a segment matches any value there. A handler can therefore be chosen by its -input alone, by its code alone, or by both: +lookup of `CanCompute` follows `@ComputerComponent.Code.Input`. A lifetime parameter +adds no segment. A key that stops after the first segment matches that value of the first parameter +with every value of the rest, and a per-entry generic in a segment matches any value there. A +handler can therefore be chosen by its input alone, by its code alone, or by both: ```rust delegate_components! { @@ -334,10 +349,11 @@ The remaining statements opt a context into a [`cgp_namespace!`](./cgp_namespace describes them in full, since they are most often written there. **`namespace SomeNamespace;`** joins the namespace, so every lookup the table does not wire directly -falls through to it. **`for in SomeTable { … }`** reads each entry of another lookup -table and emits one mapping per entry, which is how a context adopts per-type defaults wholesale. Its -body holds only `:` mappings, and an optional `where` clause on the loop constrains the entries it -wires. +falls through to it. The name is a bare identifier, so import a namespace from another module first: +`namespace some_mod::SomeNamespace;` fails with ``expected `;` `` at the `::`. +**`for in SomeTable { … }`** reads each entry of another lookup table and emits one +mapping per entry, which is how a context adopts per-type defaults wholesale. Its body holds only +`:` mappings, and an optional `where` clause on the loop constrains the entries it wires. ### Statements come first @@ -369,13 +385,16 @@ differ only in how many entries a line produces and in what each entry resolves ### Attributes The macro **does not accept attributes** anywhere: not on the table, not on a key, and not on a key -inside a `for` loop or a nested table. It rejects any it finds rather than ignoring them. -Attribute-driven variants such as `#[check_params(...)]` and `#[skip_check]` belong to +inside a `for` loop or a nested table. It rejects the first one it finds with +`unsupported attribute: …`, naming the attribute, rather than ignoring it. Attribute-driven variants +such as `#[check_params(...)]` and `#[skip_check]` belong to [`delegate_and_check_components!`](./delegate_and_check_components.md). ## Examples -A component, a provider, and a context wired to use it: +A component, a provider, and a context wired to use it, with a check that the wiring resolves. +`Rectangle` is a value context here: the shape whose area the component computes is the same type +that owns the wiring. ```rust use cgp::prelude::*; @@ -404,6 +423,12 @@ delegate_components! { } } +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + fn print_area(rect: &Rectangle) { println!("area = {}", rect.area()); } @@ -430,6 +455,12 @@ delegate_components! { AreaCalculatorComponent: SquareArea, } } + +check_components! { + Square { + AreaCalculatorComponent, + } +} ``` `Rectangle` and `Square` now both implement `CanCalculateArea`, through different providers reading @@ -439,8 +470,10 @@ them which implementation runs. When one context needs a different provider *per type* rather than one provider outright, the component carries the type as a parameter, as the generic `CanCalculateArea` under -[Usage](#choosing-a-provider-per-type-the-open-statement) does. The context then opens the component -and fills the slots: +[Usage](#choosing-a-provider-per-type-the-open-statement) does. The wired type changes role with it: +`MyApp` is an environmental context, a type that stands for one set of choices and holds no shape +of its own, so each provider reads the shape from its argument. The context opens the component, +fills the slots, and checks each shape it wires: ```rust pub struct MyApp; @@ -453,6 +486,12 @@ delegate_components! { @AreaCalculatorComponent.{Circle, Ellipse}: CurveArea, } } + +check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle, Ellipse], + } +} ``` ## When to use it @@ -468,9 +507,9 @@ compiles, and the failure only surfaces later, where the trait is used. macros apart. - **Use [`delegate_and_check_components!`](./delegate_and_check_components.md)** when you are getting started or the wiring is plain `Component: Provider` entries. It fuses the two so you cannot forget - the check. It accepts this whole grammar, but it derives checks only from mappings keyed on a - component *name*, so it wires opened, redirected, and namespaced entries and leaves them unchecked - without a warning. + the check. It accepts this whole grammar, but it derives checks only from `:` and `->` mappings + keyed on a component *name*, so it wires opened, redirected, and namespaced entries and leaves + them unchecked without a warning. - **Use plain `delegate_components!` without a check** for an **aggregate provider** (the [`new`-keyword form](#defining-the-target-at-the-same-time)). That target is a provider other contexts delegate to rather than a context in its own right, so a context-side check on it asks the wrong @@ -619,7 +658,7 @@ TableBody -> Statement* ( Mapping ( `,` Mapping )* `,`? )? Statement -> OpenStmt | NamespaceStmt | ForStmt -OpenStmt -> `open` ( `{` Type ( `,` Type )* `,`? `}` | Type ) `;` +OpenStmt -> `open` ( `{` ( Type ( `,` Type )* `,`? )? `}` | Type ) `;` NamespaceStmt -> `namespace` IDENTIFIER `;` @@ -634,12 +673,12 @@ NormalMapping -> Key `:` ProviderValue Key -> SingleKey | MultiKey | PathKey SingleKey -> Generics? Type -MultiKey -> `[` SingleKey ( `,` SingleKey )* `,`? `]` +MultiKey -> `[` ( SingleKey ( `,` SingleKey )* `,`? )? `]` PathKey -> Generics? `@` PathHead PathHead -> KeySegment ( `.` PathHead )? - | `[` KeySegment ( `,` KeySegment )* `,`? `]` ( `.` PathHead )? - | `{` PathHead ( `,` PathHead )* `,`? `}` + | `[` ( KeySegment ( `,` KeySegment )* `,`? )? `]` ( `.` PathHead )? + | `{` ( PathHead ( `,` PathHead )* `,`? )? `}` KeySegment -> Generics? PathSegment @@ -671,27 +710,32 @@ production, which keeps the two in step. And every `Generics` list on a key is a so the parser accepts a bound (` WidthKey: WidthProvider`) and rejects a parameter *default*: `` fails with `invalid impl generics syntax`. -A `ProviderValue`'s nested-table form carries a full `TableBody`, so an inner table accepts every form -an outer one does. An `InnerTable` is an identifier with an optional generic list rather than a full -`TargetType`, because a nested table always names a fresh struct the macro declares. Its -`BoundFreeGenerics` is a definition-position list: it allows neither bounds nor defaults, and a `const` -parameter is written as the bare name. Put a bound on the entry's own generics instead. The parser -rejects a bound written on the inner table as `expected ','`, because the value parser tries the -nested-table form speculatively and then falls back to reading the whole value as a plain type. +A `ProviderValue`'s nested-table form carries a full `TableBody`, so an inner table accepts every +form an outer one does. Its wrapper is a bare `IDENTIFIER`, not a path. An `InnerTable` is an +identifier with an optional generic list rather than a full `TargetType`, because a nested table +always names a fresh struct the macro declares. Its `BoundFreeGenerics` is a definition-position +list of lifetimes and type parameters: it allows neither bounds nor defaults, so put a bound on the +entry's own generics instead. The value parser tries the nested-table form speculatively and falls +back to reading the whole value as a plain type, so a bound on the inner table, a `const` parameter +on it, and a qualified wrapper all fail the same misleading way, with ``expected `,` `` at the inner +table's name. A bare `N` in that list declares a type parameter, so passing a `const` through it +fails with `E0747`: an inner table cannot carry a `const` parameter at all. The remaining rules restate points made above. An `OpenStmt` may omit its braces when opening exactly -one component. Every `Statement` precedes every `Mapping`. [`cgp_namespace!`](./cgp_namespace.md) -describes `NamespaceStmt` and `ForStmt`. The macro does not accept attributes anywhere and rejects any -it finds. +one component. A `MultiKey` takes no generic list of its own, only its elements do. Every bracketed +and braced list may be empty, and then produces no entries. Every `Statement` precedes every +`Mapping`. [`cgp_namespace!`](./cgp_namespace.md) describes `NamespaceStmt` and `ForStmt`. The macro +does not accept attributes anywhere and rejects any it finds. ## Common Mistakes **Wiring is lazy.** A table with a missing entry, or one naming a provider whose own dependencies are -unmet, still compiles. The failure appears later, at the place where code uses the trait, often -as a long error naming types you did not write. This is the single most common source of confusion with CGP. The -answer is to check the table (see [`check_components!`](./check_components.md)) and to run -[`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`, which leads with the root cause -for the classes it recognizes. +unmet, still compiles. The failure appears later, at the place where code uses the trait, often as a +long error naming types you did not write. The answer is to check the table (see +[`check_components!`](./check_components.md)) and to read failures through +[`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`. `cargo cgp check` leads with the +root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape +every class. **Statements must lead the block**, and getting it wrong produces a misleading message. Once the parser has consumed the statements it expects only mappings, so it reads the `open` keyword as a *key* and @@ -718,15 +762,24 @@ end. **Naming a provider struct that does not exist** is easy to do when you wrote a provider with [`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared it separately. The error -names an unresolved type rather than anything about wiring. - -**Two entries claiming one key conflict**, and the compiler reports it as a [coherence](/docs/reference/glossary#coherence) error rather than -as a wiring one. This covers the obvious duplicate, an `open` header colliding with an explicit mapping -for the same component, a generic ` AreaCalculatorComponent` entry overlapping a -specific `AreaCalculatorComponent` one, and a path key covering a longer one, as +is `E0425`, ``cannot find type `SquareArea` in this scope``, which names an unresolved type rather +than anything about wiring. + +**A table struct the macro declares cannot take a `const` parameter.** Both a `new` target such as +` new ArrayTable` and a nested inner table read `N` as a type parameter, so +passing a constant through fails with `E0747`, `constant provided when a type was expected`. +Declare the struct yourself instead, as `pub struct ArrayTable;`, wire it with its +own `delegate_components!` block, and name it as `UseDelegate>` in the outer entry. + +**Two entries claiming one key conflict**, and the compiler reports it as a +[coherence](/docs/reference/glossary#coherence) error, `E0119`, rather than as a wiring one. It +arrives twice, once for each impl of the entry, with the caret on the later entry's key. This covers +the obvious duplicate, an `open` header colliding with an explicit mapping for the same component, a +generic ` AreaCalculatorComponent` entry overlapping a specific +`AreaCalculatorComponent` one, and a path key covering a longer one, as `@ComputerComponent.Area` beside `@ComputerComponent.Area.Rectangle` or -`@ComputerComponent. Code.Circle`. The same applies to a direct entry for a path a -joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#common-mistakes). +`@ComputerComponent. Code.Circle`. The same applies to a direct entry for a path a joined +namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#common-mistakes). ## Related constructs diff --git a/example-code/README.md b/example-code/README.md index b7f33258..648a443e 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -36,7 +36,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, the `macros/` pages `cgp_component.md`, `cgp_impl.md`, `cgp_provider.md`, `cgp_fn.md`, `cgp_type.md`, `cgp_getter.md`, `cgp_auto_getter.md`, `blanket_trait.md`, `async_trait.md`, `cgp_computer.md`, `cgp_producer.md`, `cgp_auto_dispatch.md`, `cgp_namespace.md`, and `delegate_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, the `macros/` pages `cgp_component.md`, `cgp_impl.md`, `cgp_provider.md`, `cgp_fn.md`, `cgp_type.md`, `cgp_getter.md`, `cgp_auto_getter.md`, `blanket_trait.md`, `async_trait.md`, `cgp_computer.md`, `cgp_producer.md`, `cgp_auto_dispatch.md`, `cgp_namespace.md`, `delegate_components.md`, `delegate_and_check_components.md`, and `check_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.rs b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.rs new file mode 100644 index 00000000..98592d27 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.rs @@ -0,0 +1,18 @@ +use cgp::prelude::*; + +pub struct Seg; + +cgp_namespace! { + new BaseNamespace { + @app => @base, + } +} + +// error[E0119]: the child's more specific path overlaps the parent's, whose key ends in a wildcard +cgp_namespace! { + new ExtendedNamespace: BaseNamespace { + @app.Seg => @child, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.stderr new file mode 100644 index 00000000..e1e98c8a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.stderr @@ -0,0 +1,7 @@ +error[E0119]: conflicting implementations of trait `ExtendedNamespace<_>` for type `PathCons>>>, PathCons>` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.rs:14:14 + | +13 | new ExtendedNamespace: BaseNamespace { + | ------------- first implementation here +14 | @app.Seg => @child, + | ^^^ conflicting implementation for `PathCons>>>, PathCons>` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.rs b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.rs new file mode 100644 index 00000000..4122a049 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.rs @@ -0,0 +1,32 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +cgp_namespace! { + new AppNamespace { + AreaCalculatorComponent: RectangleArea, + } +} + +pub struct App; + +// error[E0119]: the namespace already binds `AreaCalculatorComponent` +delegate_components! { + App { + namespace AppNamespace; + + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.stderr new file mode 100644 index 00000000..b4c2f17a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.stderr @@ -0,0 +1,17 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.rs:28:9 + | +26 | namespace AppNamespace; + | ------------ first implementation here +27 | +28 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.rs:28:9 + | +26 | namespace AppNamespace; + | ------------ first implementation here +27 | +28 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs new file mode 100644 index 00000000..11373729 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs @@ -0,0 +1,30 @@ +use cgp::prelude::*; + +#[cgp_component(ShowImpl)] +#[prefix(@show in AppNamespace)] +pub trait CanShow { + fn show(&self) -> String; +} + +cgp_namespace! { + new AppNamespace {} +} + +#[derive(Debug)] +pub struct MyApp; + +// Nothing binds a provider at `@show.ShowImplComponent`. +delegate_components! { + MyApp { + namespace AppNamespace; + } +} + +// error[E0277]: the path `@show.ShowImplComponent` is not something the namespace resolves +check_components! { + MyApp { + ShowImplComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.stderr new file mode 100644 index 00000000..094d32ab --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.stderr @@ -0,0 +1,38 @@ +error[E0277]: the trait bound `PathCons>>>>, PathCons>: AppNamespace` is not satisfied + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs:26:9 + | +26 | ShowImplComponent, + | ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `AppNamespace` is not implemented for `PathCons>>>>, PathCons>` +help: the trait `AppNamespace<__Components__>` is implemented for `ShowImplComponent` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs:3:1 + | + 3 | #[cgp_component(ShowImpl)] + | ^^^^^^^^^^^^^^^^^^^^^^^^ +note: required for `MyApp` to implement `DelegateComponent>>>>, PathCons>>` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs:17:1 + | +17 | / delegate_components! { +18 | | MyApp { + | | ^^^^^ +19 | | namespace AppNamespace; +20 | | } +21 | | } + | |_^ +note: required for `RedirectLookup>>>>, PathCons>>` to implement `IsProviderFor` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs:3:1 + | + 3 | #[cgp_component(ShowImpl)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `MyApp` to implement `CanUseComponent` +note: required by a bound in `__CheckMyApp` + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs:24:1 + | +24 | / check_components! { +25 | | MyApp { +26 | | ShowImplComponent, +27 | | } +28 | | } + | |_^ required by this bound in `__CheckMyApp` + = note: this error originates in the attribute macro `cgp_component` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs new file mode 100644 index 00000000..24158ffc --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs @@ -0,0 +1,28 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +delegate_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + } +} + +// error[E0277]: `GeometryComponents: CanUseComponent` is not satisfied +check_components! { + GeometryComponents { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.stderr new file mode 100644 index 00000000..1025f6c5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.stderr @@ -0,0 +1,27 @@ +error[E0277]: the trait bound `GeometryComponents: CanUseComponent` is not satisfied + --> tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs:24:9 + | +24 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::prelude::HasField>>>>>>` is not implemented for `GeometryComponents` + --> tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs:16:9 + | +16 | new GeometryComponents { + | ^^^^^^^^^^^^^^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs:8:1 + | + 8 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `GeometryComponents` to implement `CanUseComponent` +note: required by a bound in `__CheckGeometryComponents` + --> tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs:22:1 + | +22 | / check_components! { +23 | | GeometryComponents { +24 | | AreaCalculatorComponent, +25 | | } +26 | | } + | |_^ required by this bound in `__CheckGeometryComponents` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs new file mode 100644 index 00000000..58dd477b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs @@ -0,0 +1,36 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Gen { + pub width: f64, + pub height: f64, + pub marker: core::marker::PhantomData, +} + +delegate_components! { + Gen { + AreaCalculatorComponent: RectangleArea, + } +} + +// error[E0425]: cannot find type `T` in this scope, then E0207 +check_components! { + #[check_providers(RectangleArea)] + Gen { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.stderr new file mode 100644 index 00000000..1bf22f3a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.stderr @@ -0,0 +1,17 @@ +error[E0425]: cannot find type `T` in this scope + --> tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs:31:13 + | +31 | Gen { + | ^ not found in this scope + +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs:31:6 + | +29 | / check_components! { +30 | | #[check_providers(RectangleArea)] +31 | | Gen { + | | ^ unconstrained type parameter +32 | | AreaCalculatorComponent, +33 | | } +34 | | } + | |_- help: remove the unused type parameter `T` diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.rs b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.rs new file mode 100644 index 00000000..d3604405 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.rs @@ -0,0 +1,40 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + +// error[E0428]: the name `__CheckRectangle` is defined multiple times +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.stderr new file mode 100644 index 00000000..828a9629 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.stderr @@ -0,0 +1,26 @@ +error[E0428]: the name `__CheckRectangle` is defined multiple times + --> tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.rs:34:1 + | +27 | check_components! { + | ----------------- previous definition of the trait `__CheckRectangle` here +... +34 | check_components! { + | ^^^^^^^^^^^^^^^^^ `__CheckRectangle` redefined here + | + = note: `__CheckRectangle` must be defined only once in the type namespace of this module + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `__CheckRectangle` for type `Rectangle` + --> tests/compile_fail/reference/macros/check_components_common_mistakes_derived_name_collision.rs:34:1 + | +27 | / check_components! { +28 | | Rectangle { +29 | | AreaCalculatorComponent, + | |_______________________________- first implementation here +... +34 | / check_components! { +35 | | Rectangle { +36 | | AreaCalculatorComponent, + | |_______________________________^ conflicting implementation for `Rectangle` + | + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.rs b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.rs new file mode 100644 index 00000000..444f175f --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.rs @@ -0,0 +1,34 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +// error[E0119]: the same check listed twice emits two identical impls +check_components! { + Rectangle { + [AreaCalculatorComponent, AreaCalculatorComponent], + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.stderr new file mode 100644 index 00000000..a04b3aaa --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.stderr @@ -0,0 +1,11 @@ +error[E0119]: conflicting implementations of trait `__CheckRectangle` for type `Rectangle` + --> tests/compile_fail/reference/macros/check_components_common_mistakes_duplicate_entry.rs:28:1 + | +28 | // check_components! { +29 | || Rectangle { +30 | || [AreaCalculatorComponent, AreaCalculatorComponent], + | ||________________________________-________________________^ conflicting implementation for `Rectangle` + | |_________________________________| + | first implementation here + | + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.rs b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.rs new file mode 100644 index 00000000..e57abac8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.rs @@ -0,0 +1,25 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +pub struct App; + +// error: `#[check_providers(...)]` requires at least one provider type. +check_components! { + #[check_providers()] + App { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.stderr new file mode 100644 index 00000000..aefb430f --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.stderr @@ -0,0 +1,5 @@ +error: `#[check_providers(...)]` requires at least one provider type. + --> tests/compile_fail/reference/macros/check_components_common_mistakes_empty_check_providers.rs:19:5 + | +19 | #[check_providers()] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.rs b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.rs new file mode 100644 index 00000000..1daf5686 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.rs @@ -0,0 +1,32 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle; + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } +} + +pub struct MyApp; + +delegate_components! { + MyApp { + AreaCalculatorComponent: RectangleArea, + } +} + +// error[E0277]: `RectangleArea: IsProviderFor` is not satisfied +check_components! { + MyApp { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.stderr new file mode 100644 index 00000000..d0260e3a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `RectangleArea: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.rs:28:9 + | +28 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `RectangleArea` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.rs:11:1 + | +11 | / impl AreaCalculator { +12 | | fn area(&self, _shape: &Rectangle) -> f64 { +13 | | 1.0 +14 | | } +15 | | } + | |_^ + = help: for that trait implementation, expected `Rectangle`, found `()` + = note: required for `MyApp` to implement `CanUseComponent` +note: required by a bound in `__CheckMyApp` + --> tests/compile_fail/reference/macros/check_components_common_mistakes_generic_without_parameters.rs:26:1 + | +26 | / check_components! { +27 | | MyApp { +28 | | AreaCalculatorComponent, +29 | | } +30 | | } + | |_^ required by this bound in `__CheckMyApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.rs b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.rs new file mode 100644 index 00000000..7375f47a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.rs @@ -0,0 +1,24 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } +} + +pub struct Person; + +// error: expected identifier, at the context type +check_components! { + <'a> &'a Person { + GreeterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.stderr new file mode 100644 index 00000000..3509ec4b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.stderr @@ -0,0 +1,5 @@ +error: expected identifier + --> tests/compile_fail/reference/macros/check_components_common_mistakes_reference_context.rs:19:10 + | +19 | <'a> &'a Person { + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.rs b/example-code/tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.rs new file mode 100644 index 00000000..19ec1541 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.rs @@ -0,0 +1,33 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle; +pub struct Circle; + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } +} + +pub struct MyApp; + +delegate_components! { + MyApp { + AreaCalculatorComponent: RectangleArea, + } +} + +// error[E0277]: the caret lands on `Circle`, the parameter that failed +check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.stderr b/example-code/tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.stderr new file mode 100644 index 00000000..c2b6269f --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `RectangleArea: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.rs:29:46 + | +29 | AreaCalculatorComponent: [Rectangle, Circle], + | ^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `RectangleArea` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.rs:12:1 + | +12 | / impl AreaCalculator { +13 | | fn area(&self, _shape: &Rectangle) -> f64 { +14 | | 1.0 +15 | | } +16 | | } + | |_^ + = help: for that trait implementation, expected `Rectangle`, found `Circle` + = note: required for `MyApp` to implement `CanUseComponent` +note: required by a bound in `__CheckMyApp` + --> tests/compile_fail/reference/macros/check_components_components_with_generic_parameters_caret_on_parameter.rs:27:1 + | +27 | / check_components! { +28 | | MyApp { +29 | | AreaCalculatorComponent: [Rectangle, Circle], +30 | | } +31 | | } + | |_^ required by this bound in `__CheckMyApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs b/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs new file mode 100644 index 00000000..a40f9afe --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs @@ -0,0 +1,33 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } +} + +#[derive(HasField)] +pub struct Person { + pub first_name: String, // GreetHello needs `name` +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} + +// error[E0277]: `Person` does not implement `HasField` for the `name` tag +check_components! { + Person { + GreeterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.stderr b/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.stderr new file mode 100644 index 00000000..edba1d89 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `Person: CanUseComponent` is not satisfied + --> tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs:29:9 + | +29 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>` is not implemented for `Person` + but trait `HasField>>>>>>>>>>>` is implemented for it + --> tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs:17:9 + | +17 | pub first_name: String, // GreetHello needs `name` + | ^^^^^^^^^^ +note: required for `GreetHello` to implement `IsProviderFor` + --> tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs:8:1 + | + 8 | #[cgp_impl(new GreetHello)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Person` to implement `CanUseComponent` +note: required by a bound in `__CheckPerson` + --> tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs:27:1 + | +27 | / check_components! { +28 | | Person { +29 | | GreeterComponent, +30 | | } +31 | | } + | |_^ required by this bound in `__CheckPerson` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.rs b/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.rs new file mode 100644 index 00000000..8a81aade --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.rs @@ -0,0 +1,25 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } +} + +pub struct Person; + +// error: Invalid attribute #[allow(unused)] +check_components! { + #[allow(unused)] + Person { + GreeterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.stderr b/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.stderr new file mode 100644 index 00000000..348e3d76 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.stderr @@ -0,0 +1,5 @@ +error: Invalid attribute #[allow(unused)] + --> tests/compile_fail/reference/macros/check_components_formal_grammar_invalid_attribute.rs:19:5 + | +19 | #[allow(unused)] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.rs b/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.rs new file mode 100644 index 00000000..0fc0d40d --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.rs @@ -0,0 +1,26 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self, #[implicit] name: &str) { + println!("Hello, {name}!"); + } +} + +pub struct Person; + +// error: Multiple `#[check_trait]` attributes found. Expected at most one. +check_components! { + #[check_trait(CheckPerson)] + #[check_trait(CheckPersonAgain)] + Person { + GreeterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.stderr b/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.stderr new file mode 100644 index 00000000..aa16b228 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.stderr @@ -0,0 +1,5 @@ +error: Multiple `#[check_trait]` attributes found. Expected at most one. + --> tests/compile_fail/reference/macros/check_components_formal_grammar_repeated_attribute.rs:20:5 + | +20 | #[check_trait(CheckPersonAgain)] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.rs new file mode 100644 index 00000000..46b7f622 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.rs @@ -0,0 +1,38 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle; +pub struct Circle; + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } +} + +#[cgp_impl(new ShapeArea)] +impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 1.0 + } +} + +pub struct MyApp; + +// error[E0119]: the merged lists name `Rectangle` twice, so its check impl is emitted twice +delegate_and_check_components! { + MyApp { + #[check_params(Rectangle)] + [ + #[check_params(Rectangle, Circle)] + AreaCalculatorComponent, + ]: ShapeArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.stderr new file mode 100644 index 00000000..f5286d1e --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.stderr @@ -0,0 +1,14 @@ +error[E0119]: conflicting implementations of trait `__CanUseMyApp` for type `MyApp` + --> tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_duplicate_parameter.rs:28:1 + | +28 | / delegate_and_check_components! { +29 | | MyApp { +30 | | #[check_params(Rectangle)] +... | +33 | | AreaCalculatorComponent, + | | ^ + | | | + | |___________________________________first implementation here + | conflicting implementation for `MyApp` + | + = note: this error originates in the macro `delegate_and_check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.rs new file mode 100644 index 00000000..7d85d030 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.rs @@ -0,0 +1,38 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle; +pub struct Circle; + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } +} + +#[cgp_impl(new ShapeArea)] +impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 1.0 + } +} + +pub struct MyApp; + +// error: cannot combine #[skip_check] with #[check_params] +delegate_and_check_components! { + MyApp { + #[skip_check] + [ + #[check_params(Rectangle)] + AreaCalculatorComponent, + ]: ShapeArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.stderr new file mode 100644 index 00000000..75a2cfca --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.stderr @@ -0,0 +1,5 @@ +error: cannot combine #[skip_check] with #[check_params] + --> tests/compile_fail/reference/macros/delegate_and_check_components_attributes_on_a_list_key_merge_skip_with_params.rs:32:28 + | +32 | #[check_params(Rectangle)] + | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs new file mode 100644 index 00000000..95da5c5d --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs @@ -0,0 +1,28 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +// error[E0277]: `GeometryComponents: CanUseComponent` is not satisfied +delegate_and_check_components! { + new GeometryComponents { + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.stderr new file mode 100644 index 00000000..9df57141 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.stderr @@ -0,0 +1,32 @@ +error[E0277]: the trait bound `GeometryComponents: CanUseComponent` is not satisfied + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs:24:9 + | +24 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::prelude::HasField>>>>>>` is not implemented for `GeometryComponents` + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs:23:9 + | +23 | new GeometryComponents { + | ^^^^^^^^^^^^^^^^^^ +help: the trait `cgp::prelude::HasField>>>>>>` is implemented for `Rectangle` + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs:17:9 + | +17 | pub width: f64, + | ^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs:8:1 + | + 8 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `GeometryComponents` to implement `CanUseComponent` +note: required by a bound in `__CanUseGeometryComponents` + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_aggregate_provider.rs:22:1 + | +22 | / delegate_and_check_components! { +23 | | new GeometryComponents { +24 | | AreaCalculatorComponent: RectangleArea, +25 | | } +26 | | } + | |_^ required by this bound in `__CanUseGeometryComponents` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `delegate_and_check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.rs new file mode 100644 index 00000000..858c7e6d --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.rs @@ -0,0 +1,34 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle; +pub struct Circle; + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } +} + +#[cgp_impl(new ShapeArea)] +impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 1.0 + } +} + +pub struct MyApp; + +// error[E0277]: `RectangleArea: IsProviderFor` is not satisfied +delegate_and_check_components! { + MyApp { + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.stderr new file mode 100644 index 00000000..6b8d4683 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `RectangleArea: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.rs:30:9 + | +30 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `RectangleArea` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.rs:12:1 + | +12 | / impl AreaCalculator { +13 | | fn area(&self, _shape: &Rectangle) -> f64 { +14 | | 1.0 +15 | | } +16 | | } + | |_^ + = help: for that trait implementation, expected `Rectangle`, found `()` + = note: required for `MyApp` to implement `CanUseComponent` +note: required by a bound in `__CanUseMyApp` + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_generic_without_check_params.rs:28:1 + | +28 | / delegate_and_check_components! { +29 | | MyApp { +30 | | AreaCalculatorComponent: RectangleArea, +31 | | } +32 | | } + | |_^ required by this bound in `__CanUseMyApp` + = note: this error originates in the macro `delegate_and_check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.rs new file mode 100644 index 00000000..1c60a98a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.rs @@ -0,0 +1,30 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +// error: Expected at most one `#[check_params]` or `#[skip_check]` attribute +delegate_and_check_components! { + Rectangle { + #[skip_check] + #[skip_check] + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.stderr new file mode 100644 index 00000000..16864282 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.stderr @@ -0,0 +1,5 @@ +error: Expected at most one `#[check_params]` or `#[skip_check]` attribute + --> tests/compile_fail/reference/macros/delegate_and_check_components_common_mistakes_two_entry_attributes.rs:25:9 + | +25 | #[skip_check] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.rs new file mode 100644 index 00000000..06f4d5d0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.rs @@ -0,0 +1,29 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +// error: Expected `#[check_trait]` attribute for specifying the check trait name +delegate_and_check_components! { + #[allow(unused)] + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.stderr new file mode 100644 index 00000000..8c616bfb --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.stderr @@ -0,0 +1,5 @@ +error: Expected `#[check_trait]` attribute for specifying the check trait name + --> tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_other_attribute.rs:23:5 + | +23 | #[allow(unused)] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.rs new file mode 100644 index 00000000..39e00eaa --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.rs @@ -0,0 +1,30 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +// error: Expected exactly one attribute for the check trait name +delegate_and_check_components! { + #[check_trait(CheckRectangle)] + #[check_trait(CheckRectangleAgain)] + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.stderr new file mode 100644 index 00000000..9e641909 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.stderr @@ -0,0 +1,5 @@ +error: Expected exactly one attribute for the check trait name + --> tests/compile_fail/reference/macros/delegate_and_check_components_naming_the_check_trait_two_attributes.rs:24:5 + | +24 | #[check_trait(CheckRectangleAgain)] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.rs new file mode 100644 index 00000000..845f9356 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.rs @@ -0,0 +1,29 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +// error: `#[skip_check]` does not take any arguments +delegate_and_check_components! { + Rectangle { + #[skip_check(AreaCalculatorComponent)] + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.stderr new file mode 100644 index 00000000..f18f3eef --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.stderr @@ -0,0 +1,5 @@ +error: `#[skip_check]` does not take any arguments + --> tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_arguments.rs:24:9 + | +24 | #[skip_check(AreaCalculatorComponent)] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.rs new file mode 100644 index 00000000..e445e880 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.rs @@ -0,0 +1,29 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +// error: Expected either `#[skip_check]` or `#[check_params]` attribute for specifying the check generics +delegate_and_check_components! { + Rectangle { + #[allow(unused)] + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.stderr new file mode 100644 index 00000000..9ae91e06 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.stderr @@ -0,0 +1,5 @@ +error: Expected either `#[skip_check]` or `#[check_params]` attribute for specifying the check generics + --> tests/compile_fail/reference/macros/delegate_and_check_components_skipping_one_entrys_check_other_attribute.rs:24:9 + | +24 | #[allow(unused)] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.rs new file mode 100644 index 00000000..e1107aa2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.rs @@ -0,0 +1,29 @@ +use core::marker::PhantomData; + +use cgp::prelude::*; + +#[cgp_component { + name: FooKeyComponent, + provider: FooProvider, +}] +pub trait CanFoo { + fn foo(&self, tag: PhantomData) -> u8; +} + +#[cgp_impl(new AnyFoo: FooKeyComponent)] +impl FooProvider { + fn foo(&self, _tag: PhantomData) -> u8 { + 0 + } +} + +pub struct App; + +// error[E0277]: the derived check tests `FooKeyComponent` at unit parameters +delegate_and_check_components! { + App { + FooKeyComponent: AnyFoo, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.stderr new file mode 100644 index 00000000..0096187a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.stderr @@ -0,0 +1,26 @@ +error[E0277]: the trait bound `AnyFoo: IsProviderFor, App>` is not satisfied + --> tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.rs:25:13 + | +25 | FooKeyComponent: AnyFoo, + | ^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor, App>` is not implemented for `AnyFoo` + --> tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.rs:13:16 + | +13 | #[cgp_impl(new AnyFoo: FooKeyComponent)] + | ^^^^^^ + = note: required for `App` to implement `CanUseComponent>` +note: required by a bound in `__CanUseApp` + --> tests/compile_fail/reference/macros/delegate_and_check_components_two_forms_that_quietly_check_nothing_generic_key.rs:23:1 + | +23 | / delegate_and_check_components! { +24 | | App { +25 | | FooKeyComponent: AnyFoo, +26 | | } +27 | | } + | |_^ required by this bound in `__CanUseApp` + = note: this error originates in the macro `delegate_and_check_components` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement + | +25 | FooKeyComponent where AnyFoo: IsProviderFor, App>: AnyFoo, + | ++++++++++++++++++++++++++++++++++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.rs b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.rs new file mode 100644 index 00000000..deec95ad --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.rs @@ -0,0 +1,31 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +// error: unsupported attribute: skip_check +delegate_and_check_components! { + Rectangle { + AreaCalculatorComponent => @shared, + + #[skip_check] + @shared: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.stderr b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.stderr new file mode 100644 index 00000000..1928c713 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.stderr @@ -0,0 +1,5 @@ +error: unsupported attribute: skip_check + --> tests/compile_fail/reference/macros/delegate_and_check_components_what_is_wired_and_what_is_checked_path_key_attribute.rs:26:9 + | +26 | #[skip_check] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_attributes_rejected.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_attributes_rejected.rs new file mode 100644 index 00000000..9e701830 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_attributes_rejected.rs @@ -0,0 +1,30 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +// error: unsupported attribute: allow +delegate_components! { + App { + #[allow(unused)] + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_attributes_rejected.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_attributes_rejected.stderr new file mode 100644 index 00000000..a09d0072 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_attributes_rejected.stderr @@ -0,0 +1,5 @@ +error: unsupported attribute: allow + --> tests/compile_fail/reference/macros/delegate_components_attributes_rejected.rs:25:9 + | +25 | #[allow(unused)] + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.rs similarity index 85% rename from example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.rs rename to example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.rs index 45ddbb20..9de60170 100644 --- a/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.rs +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.rs @@ -12,7 +12,7 @@ impl FooProvider { pub struct App; -// error: expected `:` +// error: expected `:`, on the dot after the closing brace delegate_components! { App { open FooProviderComponent; diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.stderr similarity index 56% rename from example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.stderr rename to example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.stderr index 22230728..61c9f170 100644 --- a/example-code/tests/compile_fail/reference/macros/delegate_components_gotchas.stderr +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.stderr @@ -1,5 +1,5 @@ error: expected `:` - --> tests/compile_fail/reference/macros/delegate_components_gotchas.rs:20:44 + --> tests/compile_fail/reference/macros/delegate_components_common_mistakes_braced_group_then_path.rs:20:44 | 20 | @FooProviderComponent.{String, u32}.bool: DummyFoo, | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs new file mode 100644 index 00000000..bb898f5b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs @@ -0,0 +1,22 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +// error[E0747]: `new` reads `N` as a type parameter of the declared struct +delegate_components! { + new ArrayTable { + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.stderr new file mode 100644 index 00000000..e27bcaaa --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.stderr @@ -0,0 +1,5 @@ +error[E0747]: constant provided when a type was expected + --> tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs:17:37 + | +17 | new ArrayTable { + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.rs new file mode 100644 index 00000000..6a2ae970 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.rs @@ -0,0 +1,31 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +// error[E0119]: conflicting implementations, reported for both impls of the later entry +delegate_components! { + App { + open AreaCalculatorComponent; + + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.stderr new file mode 100644 index 00000000..6882e849 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.stderr @@ -0,0 +1,19 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` + --> tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.rs:27:9 + | +25 | open AreaCalculatorComponent; + | ----------------------- first implementation here +26 | +27 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` + | + = note: downstream crates may implement trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::RedirectLookup>` + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` + --> tests/compile_fail/reference/macros/delegate_components_common_mistakes_duplicate_key.rs:27:9 + | +25 | open AreaCalculatorComponent; + | ----------------------- first implementation here +26 | +27 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.rs new file mode 100644 index 00000000..6063cec3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.rs @@ -0,0 +1,31 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +// error: expected `:`, on the component the misplaced `open` names +delegate_components! { + App { + AreaCalculatorComponent: RectangleArea, + + open PerimeterCalculatorComponent; + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.stderr new file mode 100644 index 00000000..0ab69b69 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.stderr @@ -0,0 +1,5 @@ +error: expected `:` + --> tests/compile_fail/reference/macros/delegate_components_common_mistakes_statements_lead.rs:27:14 + | +27 | open PerimeterCalculatorComponent; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.rs new file mode 100644 index 00000000..865de628 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.rs @@ -0,0 +1,29 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +// error[E0425]: cannot find type `SquareArea` in this scope +delegate_components! { + App { + AreaCalculatorComponent: SquareArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.stderr new file mode 100644 index 00000000..101d159c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.stderr @@ -0,0 +1,5 @@ +error[E0425]: cannot find type `SquareArea` in this scope + --> tests/compile_fail/reference/macros/delegate_components_common_mistakes_undeclared_provider.rs:25:34 + | +25 | AreaCalculatorComponent: SquareArea, + | ^^^^^^^^^^ not found in this scope diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.rs new file mode 100644 index 00000000..e99c7cb6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.rs @@ -0,0 +1,33 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +pub struct WidthKey(pub core::marker::PhantomData); + +// error: expected `,`, at the inner table's name +delegate_components! { + new MyComponents { + WidthKey: UseDelegate { + u32: RectangleArea, + }>, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.stderr new file mode 100644 index 00000000..475c7e0a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.stderr @@ -0,0 +1,5 @@ +error: expected `,` + --> tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_bound.rs:27:42 + | +27 | WidthKey: UseDelegate { + | ^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs new file mode 100644 index 00000000..42ea44d1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs @@ -0,0 +1,33 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +pub struct ArrayKey; + +// error[E0747]: the bare `N` declares a type parameter, so the const argument does not fit it +delegate_components! { + new MyComponents { + ArrayKey: UseDelegate { + u32: RectangleArea, + }>, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.stderr new file mode 100644 index 00000000..4fa1cc5c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.stderr @@ -0,0 +1,5 @@ +error[E0747]: constant provided when a type was expected + --> tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs:27:66 + | +27 | ArrayKey: UseDelegate { + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.rs new file mode 100644 index 00000000..ebabaefb --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.rs @@ -0,0 +1,31 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +pub struct WidthKey(pub core::marker::PhantomData); + +// error: invalid impl generics syntax +delegate_components! { + App { + WidthKey: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.stderr new file mode 100644 index 00000000..ccc015be --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.stderr @@ -0,0 +1,5 @@ +error: invalid impl generics syntax + --> tests/compile_fail/reference/macros/delegate_components_formal_grammar_key_generic_default.rs:27:9 + | +27 | WidthKey: RectangleArea, + | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.rs new file mode 100644 index 00000000..1e537bd8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.rs @@ -0,0 +1,29 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +// error: expected `;`, at the first comma +delegate_components! { + App { + open AreaCalculatorComponent, PerimeterCalculatorComponent; + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.stderr new file mode 100644 index 00000000..676cf4f2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.stderr @@ -0,0 +1,5 @@ +error: expected `;` + --> tests/compile_fail/reference/macros/delegate_components_open_statement_braceless_list.rs:25:37 + | +25 | open AreaCalculatorComponent, PerimeterCalculatorComponent; + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.rs new file mode 100644 index 00000000..4503291f --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.rs @@ -0,0 +1,31 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +pub struct WidthKey(pub core::marker::PhantomData); + +// error: expected square brackets +delegate_components! { + App { + [WidthKey, AreaCalculatorComponent]: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.stderr new file mode 100644 index 00000000..d3c77168 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.stderr @@ -0,0 +1,5 @@ +error: expected square brackets + --> tests/compile_fail/reference/macros/delegate_components_the_key_forms_generic_list_on_list_key.rs:27:9 + | +27 | [WidthKey, AreaCalculatorComponent]: RectangleArea, + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.rs new file mode 100644 index 00000000..7194fbf4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.rs @@ -0,0 +1,16 @@ +use cgp::prelude::*; + +mod some_mod { + pub use cgp::prelude::DefaultNamespace as SomeNamespace; +} + +pub struct App; + +// error: expected `;`, at the `::` +delegate_components! { + App { + namespace some_mod::SomeNamespace; + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.stderr new file mode 100644 index 00000000..04b6db9b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.stderr @@ -0,0 +1,13 @@ +error: expected `;` + --> tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.rs:12:27 + | +12 | namespace some_mod::SomeNamespace; + | ^ + +warning: unused import: `cgp::prelude::DefaultNamespace as SomeNamespace` + --> tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.rs:4:13 + | +4 | pub use cgp::prelude::DefaultNamespace as SomeNamespace; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.rs new file mode 100644 index 00000000..dc26254e --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.rs @@ -0,0 +1,36 @@ +use cgp::prelude::*; + +// The component lacks `#[derive_delegate(UseDelegate)]`. +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle; + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } +} + +pub struct MyApp; + +delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } +} + +// error[E0277]: `UseDelegate: IsProviderFor<..>` is not satisfied +check_components! { + MyApp { + AreaCalculatorComponent: Rectangle, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.stderr new file mode 100644 index 00000000..388f1dc9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.stderr @@ -0,0 +1,33 @@ +error[E0277]: the trait bound `cgp::prelude::UseDelegate: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.rs:32:9 + | +32 | AreaCalculatorComponent: Rectangle, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `IsProviderFor` is not implemented for `cgp::prelude::UseDelegate` + = help: `cgp::prelude::UseDelegate<__Components__>` implements trait `IsProviderFor`: + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + IsProviderFor + = note: required for `MyApp` to implement `CanUseComponent` +note: required by a bound in `__CheckMyApp` + --> tests/compile_fail/reference/macros/delegate_components_the_value_forms_missing_derive_delegate.rs:30:1 + | +30 | / check_components! { +31 | | MyApp { +32 | | AreaCalculatorComponent: Rectangle, +33 | | } +34 | | } + | |_^ required by this bound in `__CheckMyApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.rs new file mode 100644 index 00000000..29266673 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.rs @@ -0,0 +1,31 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +pub struct App; + +// error: expected `,`, at the inner table's name +delegate_components! { + App { + AreaCalculatorComponent: cgp::prelude::UseDelegate, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.stderr new file mode 100644 index 00000000..be0944b9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.stderr @@ -0,0 +1,5 @@ +error: expected `,` + --> tests/compile_fail/reference/macros/delegate_components_the_value_forms_qualified_wrapper.rs:25:64 + | +25 | AreaCalculatorComponent: cgp::prelude::UseDelegate @Component`, and a nested table, which every joining context +/// inherits. The page names no types here; they are declared. +pub mod the_rest_of_the_body_grammar { + use cgp::prelude::*; + + #[cgp_component(ShapeArea)] + #[derive_delegate(UseDelegate)] + pub trait CanShapeArea { + fn shape_area(&self, shape: &Shape) -> f64; + } + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new AnyArea)] + impl ShapeArea { + fn shape_area(&self, _shape: &Shape) -> f64 { + 1.0 + } + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "hello".to_owned() + } + } + + cgp_namespace! { + new AppNamespace { + open GreeterComponent; + + ShapeAreaComponent: + UseDelegate, + } + } + + pub struct App; + + delegate_components! { + App { + namespace AppNamespace; + + @GreeterComponent: GreetHello, + } + } + + mod check_app { + use super::*; + check_components! { + App { + GreeterComponent, + ShapeAreaComponent: [u32, String], + } + } + } +} + /// ## Inheriting from a parent /// /// The child that rewrites the `@cgp.core.error` prefix onto `@app`, and the header-only child @@ -146,6 +212,22 @@ pub mod inheriting_from_a_parent { } } +/// A header-only child written without `new`, which emits only the inheritance impl, so the trait +/// and struct it names are declared by hand. +pub mod header_without_new { + use cgp::prelude::*; + + cgp_namespace! { new BaseNamespace {} } + + pub trait ExtendedNamespace<__Table__> { + type Delegate; + } + + pub struct __ExtendedNamespaceComponents; + + cgp_namespace! { ExtendedNamespace: BaseNamespace } +} + /// ## The other two halves: registering, and joining /// /// A component registered under a prefix, and a context joining the namespace and binding the @@ -280,6 +362,75 @@ pub mod examples { } } +/// ## When to use it +/// +/// An aggregate provider behind a namespace path, in both shapes the section names: a bundle keyed +/// by bare component names, and a bundle grouping paths, which must join the namespace itself. +pub mod when_to_use_it { + use cgp::prelude::*; + + cgp_namespace! { new AppNamespace {} } + + #[cgp_component(Greeter)] + #[prefix(@app.core.user in AppNamespace)] + pub trait CanGreet { + fn greet(&self) -> u8; + } + + #[cgp_impl(new GreetOne)] + impl Greeter { + fn greet(&self) -> u8 { + 1 + } + } + + delegate_components! { + new UserComponents { + GreeterComponent: GreetOne, + } + } + + pub struct App; + + delegate_components! { + App { + namespace AppNamespace; + + @app.core.user: UserComponents, + } + } + + delegate_components! { + new CoreComponents { + namespace AppNamespace; + + @app.core.user: UserComponents, + } + } + + pub struct CoreApp; + + delegate_components! { + CoreApp { + namespace AppNamespace; + + @app.core: CoreComponents, + } + } + + mod check_apps { + use super::*; + check_components! { App { GreeterComponent } } + check_components! { CoreApp { GreeterComponent } } + } + + #[test] + fn both_bundles_answer_through_the_path() { + assert_eq!(App.greet(), 1); + assert_eq!(CoreApp.greet(), 1); + } +} + /// ## Under the hood /// /// The input whose expansion the page walks through. Only the input is checked here; the generated @@ -304,9 +455,7 @@ pub mod under_the_hood { /// ## Common Mistakes /// -/// The page quotes four errors; three carry a snippet the compiler must refuse, each a trybuild -/// fixture. The fourth, a registered component with no provider bound anywhere, is the fixture on -/// the `#[prefix(...)]` page. +/// Every error the page quotes has a trybuild fixture. /// /// Joining two namespaces on one context, `E0119` — /// `tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_two_namespaces_joined.rs`. @@ -317,6 +466,19 @@ pub mod under_the_hood { /// A namespace inheriting itself, `E0207` — /// `tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs`. /// +/// A context overriding a key its namespace binds, `E0119` — +/// `tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_context_overrides_bound_key.rs`. +/// +/// A child namespace adding a longer path beneath one its parent routes, `E0119` — +/// `tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_child_redefines_parent_path.rs`. +/// +/// A registered component whose route nothing binds, `E0277` — +/// `tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_unbound_route.rs`. +/// +/// A `namespace` statement written with a path, ``expected `;` `` — shared with the +/// `delegate_components!` page, as +/// `tests/compile_fail/reference/macros/delegate_components_the_namespace_statements_namespace_path.rs`. +/// /// The *Inheriting from a parent* section also states that only the end of the input may follow a /// header written without braces; the macro's `expected curly braces` rejection of a stray token is /// `tests/compile_fail/reference/macros/cgp_namespace_inheriting_from_a_parent_stray_token.rs`. diff --git a/example-code/tests/reference/macros/check_components.rs b/example-code/tests/reference/macros/check_components.rs new file mode 100644 index 00000000..dbc8d8e1 --- /dev/null +++ b/example-code/tests/reference/macros/check_components.rs @@ -0,0 +1,330 @@ +//! Code from `docs/reference/macros/check_components.md` — *`check_components!`*. +//! +//! The snippets the page rejects, and the errors it quotes, live under +//! `tests/compile_fail/reference/macros/`. The *Examples* section's first program is one of them, +//! since the page shows it failing. + +/// ## Overview and Usage +/// +/// The one-entry table both sections open with, against a `Person` that does carry the `name` +/// field. The greeter is the one *Examples* shows. +pub mod overview { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + // An invocation with no table, which the page says is accepted. + check_components! {} +} + +/// ### Components with generic parameters +/// +/// A bare parameter, a tuple of two, the bracketed product, and a parameter carrying its own +/// generics. The page names the components and shapes without declaring them. +pub mod components_with_generic_parameters { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + #[cgp_component(Rotator)] + pub trait CanRotate { + fn rotate(&self, shape: &Shape, degrees: f64) -> f64; + } + + #[cgp_component(TransformCalculator)] + pub trait CanTransform { + fn transform(&self, shape: &Shape, factor: Factor) -> f64; + } + + pub struct Rectangle; + pub struct Circle; + + #[cgp_impl(new AnyShape)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 1.0 + } + } + + #[cgp_impl(AnyShape)] + impl Rotator { + fn rotate(&self, _shape: &Shape, degrees: f64) -> f64 { + degrees + } + } + + #[cgp_impl(AnyShape)] + impl TransformCalculator { + fn transform(&self, _shape: &Shape, factor: f64) -> f64 { + factor + } + } + + pub struct MyApp; + + delegate_components! { + MyApp { + [ + AreaCalculatorComponent, + RotatorComponent, + TransformCalculatorComponent, + ]: AnyShape, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent: Rectangle, // one parameter + TransformCalculatorComponent: (Rectangle, f64), // two, as a tuple + } + } + + check_components! { + #[check_trait(CheckMyAppProduct)] + MyApp { + [AreaCalculatorComponent, RotatorComponent]: [Rectangle, Circle], + } + } + + check_components! { + #[check_trait(CheckMyAppReference)] + MyApp { + AreaCalculatorComponent: <'a> &'a Rectangle, + } + } +} + +/// ### Naming the check trait +/// +/// The override, and the reference context that needs one because it has no name to derive. +pub mod naming_the_check_trait { + use cgp::prelude::*; + + pub use super::overview::{GreeterComponent, Person}; + + check_components! { + #[check_trait(CheckPersonGreeting)] + Person { + GreeterComponent, + } + } + + check_components! { + #[check_trait(CheckPersonReference)] + <'a> &'a Person { + } + } +} + +/// ### Checking each provider instead of the context +/// +/// The per-layer check of a scaled-area stack. The page names `ScaledRectangle`, `RectangleArea`, +/// and `ScaledArea` without declaring them. +pub mod checking_each_provider_instead_of_the_context { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(new ScaledArea)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } + } + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_components! { + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } + } + + check_components! { + #[check_trait(CheckScaledProviders)] + #[check_providers( + RectangleArea, + ScaledArea, + )] + ScaledRectangle { + AreaCalculatorComponent, + } + } + + /// The generic-table case the page warns about, checked on a concrete instantiation instead. + #[derive(HasField)] + pub struct Gen { + pub width: f64, + pub height: f64, + pub marker: core::marker::PhantomData, + } + + delegate_components! { + Gen { + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + #[check_trait(CheckGenProviders)] + #[check_providers(RectangleArea)] + Gen { + AreaCalculatorComponent, + } + } +} + +/// ## Examples +/// +/// The second example: a generic component checked at two shapes. The page shows only the +/// component and the check; the context's wiring and the providers are declared here. The first +/// example fails by design and is a trybuild fixture. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub struct Circle { + pub radius: f64, + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height + } + } + + #[cgp_impl(new CircleArea)] + impl AreaCalculator { + fn area(&self, shape: &Circle) -> f64 { + core::f64::consts::PI * shape.radius * shape.radius + } + } + + pub struct MyApp; + + delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } + } +} + +/// ## Under the hood +/// +/// The table generics and `where` clause merged onto an impl, and the unsized parameter the +/// `?Sized` bound admits. The page names `FooComponent` and `ReferenceGetterComponent` without +/// declaring them. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_component(FooProvider)] + pub trait CanFoo { + fn foo(&self, value: T) -> u8; + } + + #[cgp_impl(new AnyFoo)] + impl FooProvider { + fn foo(&self, _value: T) -> u8 { + 0 + } + } + + #[cgp_component(ReferenceGetter)] + pub trait CanGetReference<'a, T: ?Sized + 'a> { + fn get_reference(&self) -> Option<&'a T>; + } + + #[cgp_impl(new NoReference)] + impl<'a, T: ?Sized + 'a> ReferenceGetter<'a, T> { + fn get_reference(&self) -> Option<&'a T> { + None + } + } + + pub struct Context; + + delegate_components! { + Context { + FooProviderComponent: AnyFoo, + ReferenceGetterComponent: NoReference, + } + } + + check_components! { + <'a, I> Context where I: Clone { + FooProviderComponent: &'a I, + } + } + + check_components! { + #[check_trait(CheckUnsized)] + Context { + ReferenceGetterComponent: <'a> (Life<'a>, str), + } + } +} diff --git a/example-code/tests/reference/macros/delegate_and_check_components.rs b/example-code/tests/reference/macros/delegate_and_check_components.rs new file mode 100644 index 00000000..ce544801 --- /dev/null +++ b/example-code/tests/reference/macros/delegate_and_check_components.rs @@ -0,0 +1,611 @@ +//! Code from `docs/reference/macros/delegate_and_check_components.md` — +//! *`delegate_and_check_components!`*. +//! +//! The snippets the page rejects, and the errors it quotes, live under +//! `tests/compile_fail/reference/macros/`. Each snippet that wires `ScaledRectangle` or `MyApp` +//! gets its own module, since one context cannot be wired twice. + +/// ## Overview +/// +/// The name component pair the opening snippet wires. The page declares neither trait there; the +/// getter appears under *Examples* and the type component is declared here. +pub mod overview { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasNameType { + type Name; + } + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct MyContext { + pub name: String, + } + + delegate_and_check_components! { + MyContext { + NameTypeProviderComponent: UseType, + NameGetterComponent: UseField, + } + } + + #[test] + fn the_wired_getter_reads_the_field() { + let context = MyContext { + name: "Alice".to_owned(), + }; + assert_eq!(context.name(), "Alice"); + } +} + +/// ## Usage +/// +/// The scaled-area context the page's attribute examples share. The page names the component, +/// `ScaledArea`, and `RectangleArea` without declaring them. +pub mod usage { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(new ScaledArea)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } + } + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_and_check_components! { + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } + } + + #[test] + fn the_scaled_area_is_wired_and_checked() { + let rectangle = ScaledRectangle { + width: 2.0, + height: 3.0, + scale_factor: 2.0, + }; + assert_eq!(rectangle.area(), 24.0); + } +} + +/// ### Naming the check trait +/// +/// The table-level override. The same context is redeclared so it can be wired again. +pub mod naming_the_check_trait { + use cgp::prelude::*; + + use super::usage::{AreaCalculatorComponent, RectangleArea, ScaledArea}; + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_and_check_components! { + #[check_trait(TestScaledRectangle)] + ScaledRectangle { + AreaCalculatorComponent: ScaledArea, + } + } + + /// The override names the trait, so it can be referred to. + fn the_trait_is_named>() {} + + #[test] + fn the_named_trait_holds() { + the_trait_is_named::(); + } +} + +/// ### Components with generic parameters +/// +/// `#[check_params(Rectangle, Circle)]` on an entry wired to a provider generic over the shape. +/// The page names the component, the shapes, and `ShapeArea` without declaring them. +pub mod components_with_generic_parameters { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub trait HasBoundingBox { + fn bounding_box(&self) -> (f64, f64); + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub struct Circle { + pub radius: f64, + } + + impl HasBoundingBox for Rectangle { + fn bounding_box(&self) -> (f64, f64) { + (self.width, self.height) + } + } + + impl HasBoundingBox for Circle { + fn bounding_box(&self) -> (f64, f64) { + (2.0 * self.radius, 2.0 * self.radius) + } + } + + #[cgp_impl(new ShapeArea)] + impl AreaCalculator { + fn area(&self, shape: &Shape) -> f64 { + let (width, height) = shape.bounding_box(); + width * height + } + } + + pub struct MyApp; + + delegate_and_check_components! { + MyApp { + #[check_params(Rectangle, Circle)] + AreaCalculatorComponent: ShapeArea, // a provider generic over the shape + } + } + + fn each_parameter_is_checked< + T: __CanUseMyApp + + __CanUseMyApp, + >() { + } + + #[test] + fn both_shapes_are_checked() { + each_parameter_is_checked::(); + assert_eq!(MyApp.area(&Circle { radius: 1.0 }), 4.0); + } +} + +/// ### Skipping one entry's check +pub mod skipping_one_entrys_check { + use cgp::prelude::*; + + use super::usage::{AreaCalculatorComponent, RectangleArea, ScaledArea}; + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_and_check_components! { + ScaledRectangle { + #[skip_check] + AreaCalculatorComponent: ScaledArea, + } + } + + // The skipped entry is still wired; a standalone block verifies it. + check_components! { + ScaledRectangle { + AreaCalculatorComponent, + } + } +} + +/// ### Attributes on a list key merge +/// +/// The list-level and element-level `#[check_params]` combining per element. The page names +/// `RotatorComponent` and `ShapeProvider` without declaring them. +pub mod attributes_on_a_list_key_merge { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + #[cgp_component(Rotator)] + pub trait CanRotate { + fn rotate(&self, shape: &Shape, degrees: f64) -> f64; + } + + pub struct Rectangle; + pub struct Circle; + + #[cgp_impl(new ShapeProvider)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 1.0 + } + } + + #[cgp_impl(ShapeProvider)] + impl Rotator { + fn rotate(&self, _shape: &Shape, degrees: f64) -> f64 { + degrees + } + } + + pub struct MyApp; + + delegate_and_check_components! { + MyApp { + #[check_params(Rectangle)] + [ + #[check_params(Circle)] + AreaCalculatorComponent, + RotatorComponent, + ]: ShapeProvider, + } + } + + fn the_merged_checks_exist< + T: __CanUseMyApp + + __CanUseMyApp + + __CanUseMyApp, + >() { + } + + #[test] + fn each_element_gets_its_merged_parameters() { + the_merged_checks_exist::(); + } +} + +/// ### Two forms that quietly check nothing +/// +/// The empty `#[check_params()]`, an all-skipped table, and a key carrying only generics, which the +/// page says is checked at unit parameters and fails for a component whose marker carries the +/// trait's parameter (a trybuild fixture). The working `#[check_params(I)]` form is below. +pub mod two_forms_that_quietly_check_nothing { + use core::marker::PhantomData; + + use cgp::prelude::*; + + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + #[cgp_impl(new NeedsWidth)] + impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64) -> f64 { + width + } + } + + // `App` has no `width` field, so a real check would fail; the empty list skips it silently, + // and the table still emits `__CanUseApp` with no impls. + pub struct App; + + delegate_and_check_components! { + App { + #[check_params()] + PerimeterCalculatorComponent: NeedsWidth, + } + } + + #[cgp_component { + name: FooKeyComponent, + provider: FooProvider, + }] + pub trait CanFoo { + fn foo(&self, tag: PhantomData) -> u8; + } + + #[cgp_impl(new AnyFoo: FooKeyComponent)] + impl FooProvider { + fn foo(&self, _tag: PhantomData) -> u8 { + 0 + } + } + + pub struct FooApp; + + delegate_and_check_components! { + FooApp { + #[check_params(I)] + FooKeyComponent: AnyFoo, + } + } + + #[test] + fn the_key_generic_is_the_parameter() { + assert_eq!(FooApp.foo(PhantomData::), 0); + } +} + +/// ### What is wired, and what is checked +/// +/// One table carrying every row of the page's coverage table. Only the first three rows are +/// checked by the derivation; a standalone block checks the rest. +pub mod what_is_wired_and_what_is_checked { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + #[cgp_component(ColorGetter)] + pub trait HasColor { + fn color(&self) -> &'static str; + } + + #[cgp_component(LabelGetter)] + pub trait HasLabel { + fn label(&self) -> &'static str; + } + + pub struct Rectangle; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } + } + + #[cgp_impl(new FixedPerimeter)] + impl PerimeterCalculator { + fn perimeter(&self) -> f64 { + 4.0 + } + } + + #[cgp_impl(new DefaultStyle)] + impl ColorGetter { + fn color(&self) -> &'static str { + "black" + } + } + + #[cgp_impl(DefaultStyle)] + impl LabelGetter { + fn label(&self) -> &'static str { + "shape" + } + } + + delegate_components! { + new StyleComponents { + LabelGetterComponent: DefaultStyle, + } + } + + pub struct App; + + delegate_and_check_components! { + App { + open AreaCalculatorComponent; + + PerimeterCalculatorComponent: FixedPerimeter, + LabelGetterComponent -> StyleComponents, + ColorGetterComponent => @style, + + @style: DefaultStyle, + @AreaCalculatorComponent.Rectangle: RectangleArea, + } + } + + check_components! { + App { + AreaCalculatorComponent: Rectangle, + ColorGetterComponent, + } + } +} + +/// ## Examples +/// +/// The getter context, and the mixed table whose skipped entry a per-layer `#[check_providers]` +/// block verifies. The page names `RectanglePerimeter` and reuses the scaled-area providers. +pub mod examples { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct MyContext { + pub name: String, + } + + delegate_and_check_components! { + MyContext { + NameGetterComponent: UseField, + } + } + + pub mod mixed { + use cgp::prelude::*; + + pub use crate::reference::macros::delegate_and_check_components::usage::{ + AreaCalculatorComponent, CanCalculateArea, RectangleArea, ScaledArea, + }; + + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + #[cgp_impl(new RectanglePerimeter)] + impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } + } + + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_and_check_components! { + ScaledRectangle { + PerimeterCalculatorComponent: + RectanglePerimeter, + + #[skip_check] + AreaCalculatorComponent: + ScaledArea, + } + } + + check_components! { + #[check_providers(RectangleArea, ScaledArea)] + ScaledRectangle { + AreaCalculatorComponent, + } + } + + #[test] + fn both_entries_are_wired() { + let rectangle = ScaledRectangle { + width: 2.0, + height: 3.0, + scale_factor: 2.0, + }; + assert_eq!(rectangle.area(), 24.0); + assert_eq!(rectangle.perimeter(), 10.0); + } + } +} + +/// ## Under the hood +/// +/// The input whose expansion the page lists, checked with +/// `cargo cgp expand --item reference::macros::delegate_and_check_components::under_the_hood`, the +/// generic table, and the generic-marker key with its parameters. +pub mod under_the_hood { + use core::marker::PhantomData; + + use cgp::prelude::*; + + pub use super::overview::{HasName, NameGetterComponent, NameTypeProviderComponent}; + + #[derive(HasField)] + pub struct MyContext { + pub name: String, + } + + delegate_and_check_components! { + #[check_trait(CheckMyContext)] + MyContext { + NameTypeProviderComponent: UseType, + NameGetterComponent: UseField, + } + } + + #[derive(HasField)] + pub struct GenericContext { + pub name: String, + pub marker: PhantomData, + } + + delegate_and_check_components! { + GenericContext { + NameGetterComponent: UseField, + } + } + + #[cgp_type] + pub trait HasBarType { + type Bar; + } + + #[cgp_getter { + name: BarGetterAtComponent, + provider: BarGetterAt, + }] + pub trait HasBarAt: HasBarType { + fn bar(&self, _tag: PhantomData<(I, J)>) -> &Self::Bar; + } + + #[derive(HasField)] + pub struct BarContext { + pub dummy: (), + } + + delegate_and_check_components! { + BarContext { + BarTypeProviderComponent: UseType<()>, + + #[check_params((I, Index<0>))] + BarGetterAtComponent: UseField, + } + } +} + +/// ## Common Mistakes +/// +/// The compiling half of the nested-table entry: an attribute on an inner key is dropped without +/// an error. The failing snippets are the trybuild fixtures. +pub mod common_mistakes { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + #[derive_delegate(UseDelegate)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle; + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } + } + + pub struct MyApp; + + delegate_and_check_components! { + MyApp { + #[check_params(Rectangle)] + AreaCalculatorComponent: + UseDelegate, + } + } +} diff --git a/example-code/tests/reference/macros/delegate_components.rs b/example-code/tests/reference/macros/delegate_components.rs index fa3aceba..a2742df4 100644 --- a/example-code/tests/reference/macros/delegate_components.rs +++ b/example-code/tests/reference/macros/delegate_components.rs @@ -1,11 +1,14 @@ //! Code from `docs/reference/macros/delegate_components.md` — *`delegate_components!`*. +//! +//! The snippets the page rejects, and the parse errors it quotes, live under +//! `tests/compile_fail/reference/macros/`. -/// ## Overview +/// ## Overview and Usage /// -/// The page opens on the single-entry table. The component, the provider, and the context it wires -/// are shown further down the page under *Examples*; they are declared here so the opening snippet -/// has something to name. -pub mod what_its_for { +/// The single-entry table the page opens both sections with. The component, the provider, and the +/// context it wires appear under *Examples*; they are declared here so the snippet has something +/// to name. +pub mod overview { use cgp::prelude::*; #[cgp_component(AreaCalculator)] @@ -39,17 +42,17 @@ pub mod what_its_for { } } -/// ## Defining the target at the same time +/// ### Defining the target at the same time /// -/// The aggregate-provider bundle. `PerimeterCalculator` and its provider are named by the page -/// without being introduced, so they are declared here. -/// -/// No `check_components!` block appears: the page's own point is that a context-side check on a -/// bundle asks the wrong question. The wiring is verified through `MyApp` below instead. +/// The aggregate-provider bundle. The page names `PerimeterCalculator` and its provider without +/// introducing them. No `check_components!` names the bundle, since the page's point is that a +/// context-side check on it asks the wrong question; `MyApp` verifies it instead. pub mod defining_the_target_at_the_same_time { + use core::marker::PhantomData; + use cgp::prelude::*; - use super::what_its_for::{AreaCalculatorComponent, RectangleArea}; + pub use super::overview::{AreaCalculatorComponent, CanCalculateArea, RectangleArea}; #[cgp_component(PerimeterCalculator)] pub trait CanCalculatePerimeter { @@ -70,7 +73,6 @@ pub mod defining_the_target_at_the_same_time { } } - /// A real context delegating to the bundle, which is how a bundle is actually verified. #[derive(HasField)] pub struct MyApp { pub width: f64, @@ -89,210 +91,402 @@ pub mod defining_the_target_at_the_same_time { PerimeterCalculatorComponent, } } + + // The prose's generic target: `new` declares it with a `PhantomData` field over its + // parameters, a lifetime lifted into `Life`. + delegate_components! { + <'a, T> new MyComponents<'a, T> { + AreaCalculatorComponent: RectangleArea, + } + } + + pub fn the_generic_target_has_a_phantom_field( + bundle: MyComponents<'static, u32>, + ) -> PhantomData<(Life<'static>, u32)> { + bundle.0 + } + + #[test] + fn the_bundle_answers_through_the_context() { + let app = MyApp { + width: 2.0, + height: 3.0, + }; + assert_eq!(app.area(), 6.0); + assert_eq!(app.perimeter(), 10.0); + } } -/// ## One table for a family of types +/// ### One table for a family of types /// -/// The page shows only the `delegate_components!` block; the generic context it wires is declared -/// here so the table has a target. +/// The page shows only the table; the generic context it wires is declared here with the fields +/// `RectangleArea` reads, so one check covers every instantiation. pub mod one_table_for_a_family_of_types { use core::marker::PhantomData; use cgp::prelude::*; - use super::what_its_for::{AreaCalculatorComponent, RectangleArea}; + use super::overview::{AreaCalculatorComponent, CanCalculateArea, RectangleArea}; - pub struct MyContext(pub PhantomData); + #[derive(HasField)] + pub struct MyContext { + pub width: f64, + pub height: f64, + pub marker: PhantomData, + } delegate_components! { MyContext { AreaCalculatorComponent: RectangleArea, } } + + check_components! { + MyContext { + AreaCalculatorComponent, + } + } + + #[test] + fn every_instantiation_is_wired() { + let context = MyContext:: { + width: 2.0, + height: 5.0, + marker: PhantomData, + }; + assert_eq!(context.area(), 10.0); + } } -/// ## The three operators +/// ### The operators /// -/// The `:`-versus-`->` pair the page contrasts. `FooComponents` is named by the page without being -/// introduced, so it is declared here with the two entries the `->` line reaches into. -pub mod the_three_operators { +/// The `:`-versus-`->` pair, and the `=>` table pointing two components at one slot. The page +/// names `ScaledAreaCalculator` and `RectangleGeometry` without declaring them. +pub mod the_operators { use cgp::prelude::*; + pub use super::defining_the_target_at_the_same_time::{ + CanCalculatePerimeter, GeometryComponents, PerimeterCalculator, PerimeterCalculatorComponent, + }; + pub use super::overview::{AreaCalculator, AreaCalculatorComponent, CanCalculateArea, RectangleArea}; + + #[cgp_impl(new ScaledAreaCalculator)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } + } + delegate_components! { - new FooComponents { - Index<0>: u64, - Index<1>: String, + new ScaledGeometryComponents { + AreaCalculatorComponent: + ScaledAreaCalculator, // the provider *is* this scaled calculator + PerimeterCalculatorComponent -> + GeometryComponents, // the provider is whatever GeometryComponents wires for perimeter } } + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + delegate_components! { - new BarComponents { - Index<0>: - FooComponents, // the provider *is* FooComponents - Index<1> -> - FooComponents, // the provider is whatever FooComponents wires for Index<1> + ScaledRectangle { + [AreaCalculatorComponent, PerimeterCalculatorComponent]: ScaledGeometryComponents, } } - /// The `=>` snippet from the same section: two components pointed at one shared slot. - /// - /// `Bar`, `Baz`, and `DummyImpl` are named by the page without being introduced. - #[cgp_component(BarProvider)] - pub trait Bar { - fn bar(&self); + check_components! { + ScaledRectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } } - #[cgp_component(BazProvider)] - pub trait Baz { - fn baz(&self); + #[test] + fn only_the_named_entry_is_scaled() { + let rectangle = ScaledRectangle { + width: 2.0, + height: 3.0, + scale_factor: 2.0, + }; + assert_eq!(rectangle.area(), 24.0); + assert_eq!(rectangle.perimeter(), 10.0); } - #[cgp_impl(new DummyImpl)] - impl BarProvider { - fn bar(&self) {} + #[cgp_impl(new RectangleGeometry)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } } - #[cgp_impl(DummyImpl)] - impl BazProvider { - fn baz(&self) {} + #[cgp_impl(RectangleGeometry)] + impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } } - pub struct App; + #[derive(HasField)] + pub struct App { + pub width: f64, + pub height: f64, + } delegate_components! { App { - [BarProviderComponent, BazProviderComponent] => + [AreaCalculatorComponent, PerimeterCalculatorComponent] => @shared, - @shared: DummyImpl, + @shared: RectangleGeometry, } } check_components! { App { - BarProviderComponent, - BazProviderComponent, + AreaCalculatorComponent, + PerimeterCalculatorComponent, } } + + #[test] + fn one_slot_answers_both_components() { + let app = App { + width: 2.0, + height: 3.0, + }; + assert_eq!(app.area(), 6.0); + assert_eq!(app.perimeter(), 10.0); + } } -/// ## The three key forms +/// ### The key forms /// -/// The list-key table, plus the single key carrying its own generics that the surrounding prose -/// mentions inline. The components and providers are named by the page without being introduced. -/// -/// The page's `{…}`-group snippet is not reproduced here: it wires `ExtendedNamespace` and the error -/// components, which belong to the `cgp_namespace!` page. The two grouping forms are exercised -/// against a local component under [`choosing_a_provider_per_type_the_open_statement`] instead. -pub mod the_three_key_forms { +/// The single key with its own generics, the list key, the element generics, and the path keys with +/// both grouping forms. The page names every component and provider here without declaring them. +pub mod the_key_forms { use core::marker::PhantomData; + use cgp::core::error::{ErrorRaiserComponent, ErrorWrapperComponent}; + use cgp::extra::error::RaiseFrom; use cgp::prelude::*; - #[cgp_component(FooProvider)] - pub trait Foo { - fn foo(&self); + pub use super::the_operators::{ + AreaCalculatorComponent, PerimeterCalculatorComponent, RectangleGeometry, + }; + + /// ` ShapeAreaCalculatorComponent: SumAreas`: the key's marker carries the + /// trait's parameter, so the provider names the component explicitly. + #[cgp_component { + provider: ShapeAreaCalculator, + name: ShapeAreaCalculatorComponent, + }] + pub trait CanCalculateShapeArea { + fn shape_area(&self, shape: &Shape) -> f64; + } + + pub struct Square { + pub side: f64, } - #[cgp_component(BarProvider)] - pub trait Bar { - fn bar(&self); + #[cgp_impl(new SumAreas: ShapeAreaCalculatorComponent)] + impl ShapeAreaCalculator { + fn shape_area(&self, _shape: &Shape) -> f64 { + 0.0 + } } - #[cgp_component(BazProvider)] - pub trait Baz { - fn baz(&self); + pub struct ShapeApp; + + delegate_components! { + ShapeApp { + ShapeAreaCalculatorComponent: SumAreas, + } } - #[cgp_impl(new FooBarProvider)] - impl FooProvider { - fn foo(&self) {} + check_components! { + ShapeApp { + ShapeAreaCalculatorComponent: Square, + } } - #[cgp_impl(FooBarProvider)] - impl BarProvider { - fn bar(&self) {} + /// The list-key table. `MyComponents` is not declared with `new` on the page, so it is + /// declared here, and a context delegating to it verifies it. + #[cgp_component { + provider: ColorProvider, + name: ColorComponent, + }] + pub trait HasColor { + fn color(&self) -> &'static str; } - #[cgp_impl(new BazProvider2)] - impl BazProvider { - fn baz(&self) {} + #[cgp_impl(new SolidColor: ColorComponent)] + impl ColorProvider { + fn color(&self) -> &'static str { + "black" + } } + pub struct MyComponents; + delegate_components! { - new MyComponents { + MyComponents { [ - FooProviderComponent, - BarProviderComponent, - ]: FooBarProvider, - BazProviderComponent: BazProvider2, + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ]: RectangleGeometry, + ColorComponent: SolidColor, } } - /// The ` BazKey: BazProvider` shape the prose names: a key carrying its own generic - /// parameter, which the key must mention or the generated impl leaves it unconstrained. The - /// page also says a bracketed element may carry generics, so one does here. - /// - /// The key types are declared rather than derived, since a generic key is a type-level lookup - /// key rather than a `#[cgp_component]` marker, which is never generic. - pub struct FooKey(pub PhantomData); - pub struct BarKey(pub PhantomData); - pub struct BazKey(pub PhantomData<(T1, T2)>); - pub struct FooValue; - pub struct BarValue(pub PhantomData); + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } delegate_components! { - - GenericKeyComponents { - FooKey: FooValue, + Rectangle { [ - BarKey, - BazKey, - ]: - BarValue, + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ColorComponent, + ]: MyComponents, } } - pub struct GenericKeyComponents; + check_components! { + Rectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + ColorComponent, + } + } + + /// `[WidthKey, HeightKey]: RectangleValue`: only the second element + /// introduces `T2`. The keys are plain types rather than component markers, and the table's + /// `` shows a key generic carrying a bound. + pub struct WidthKey(pub PhantomData); + pub struct HeightKey(pub PhantomData<(T1, T2)>); + pub struct RectangleValue(pub PhantomData); + + pub struct RectangleValues; + + delegate_components! { + RectangleValues { + [WidthKey, HeightKey]: RectangleValue, + } + } + + /// The path keys the section names: a bracketed group continuing into a second group, and the + /// braced group of tails joined to a namespace. Nothing redirects into `@app` here, so the + /// entries are checked by naming their keys directly. + pub struct Tagged; + + delegate_components! { + Tagged { + @app.[AreaCalculatorComponent, PerimeterCalculatorComponent].[u64, String]: + RectangleGeometry, + } + } + + pub fn delegates_to() + where + Table: DelegateComponent, + { + } + + #[test] + fn a_bracketed_path_expands_to_the_product() { + delegates_to::(); + delegates_to::(); + delegates_to::(); + delegates_to::(); + } + + cgp_namespace! { + new ExtendedNamespace: DefaultNamespace { + @cgp.core.error => + @app, + } + } + + pub struct App; + + delegate_components! { + App { + namespace ExtendedNamespace; + + @app.{ + ErrorRaiserComponent.{&'static str, String}, + ErrorWrapperComponent, + }: RaiseFrom, + } + } + + #[test] + fn a_braced_path_covers_tails_of_different_lengths() { + delegates_to::(); + delegates_to::(); + } + + /// Every list form accepts being empty, and produces no entries. + pub struct Empty; + + delegate_components! { + Empty { + open {}; + + []: RectangleGeometry, + @AreaCalculatorComponent.{}: RectangleGeometry, + @AreaCalculatorComponent.[]: RectangleGeometry, + } + } } -/// ## The two value forms +/// ### The value forms /// -/// The legacy nested-table value, in both shapes the page's admonition shows: the plain -/// `UseDelegate` dispatch table, and the form whose inner table name carries generics -/// threaded in from a per-entry `` on the outer key. -/// -/// The page names `AreaCalculatorComponents`, `RectangleArea`, and `CircleArea` for the first and -/// `BarKey`/`BarValue`/`BazKey`/`BazValue` for the second; all are declared here. The keys are plain -/// types rather than component markers, which is what an inner dispatch table is keyed on. -pub mod the_two_value_forms { +/// The legacy nested-table value in both shapes the page shows: the `UseDelegate` +/// dispatch table, and the form whose inner table name carries generics from a per-entry `` on +/// the outer key. The page names every type here without declaring it. +pub mod the_value_forms { use core::marker::PhantomData; use cgp::prelude::*; - // `#[derive_delegate]` is what generates the `UseDelegate` dispatch impl, and the legacy form - // does not resolve without it — which is the concrete difference the page draws between this - // form and the `open` statement, whose redirect every `#[cgp_component]` already generates. + // `#[derive_delegate]` generates the `UseDelegate` dispatch impl the wrapper resolves through, + // which is the prerequisite the page points out. #[cgp_component(AreaCalculator)] #[derive_delegate(UseDelegate)] pub trait CanCalculateArea { fn area(&self, shape: &Shape) -> f64; } - pub struct Rectangle; - pub struct Circle; + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub struct Circle { + pub radius: f64, + } #[cgp_impl(new RectangleArea)] - impl AreaCalculator { - fn area(&self, _shape: &Shape) -> f64 { - 0.0 + impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height } } #[cgp_impl(new CircleArea)] - impl AreaCalculator { - fn area(&self, _shape: &Shape) -> f64 { - 0.0 + impl AreaCalculator { + fn area(&self, shape: &Circle) -> f64 { + core::f64::consts::PI * shape.radius * shape.radius } } @@ -314,26 +508,39 @@ pub mod the_two_value_forms { } } + #[test] + fn the_inner_table_dispatches_per_shape() { + let rectangle = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(MyApp.area(&rectangle), 6.0); + } + /// The generic inner table: the entry's `` reaches the outer key, the wrapper, and the - /// generated `struct BarValue;` alike. - pub struct BarKey(pub PhantomData); - pub struct BazKey; - pub struct BazValue(pub PhantomData); + /// generated `struct WidthValue` alike. + pub struct WidthKey(pub PhantomData); + pub struct HeightKey; + pub struct HeightValue(pub PhantomData); delegate_components! { - new GenericInnerComponents { - BarKey: UseDelegate { - BazKey: BazValue, + new MyComponents { + WidthKey: UseDelegate { + HeightKey: HeightValue, }>, } } + + pub fn the_inner_table_is_generic(table: WidthValue) -> PhantomData { + table.0 + } } -/// ## Choosing a provider per type: the `open` statement +/// ### Choosing a provider per type: the `open` statement /// -/// The `open` header with its per-value path keys, extended to cover both grouping forms and a -/// generic path segment — the three path-key shapes the section describes. The page shows them -/// against `AreaCalculator`; the shapes are the point, so one component carries all of them here. +/// The generic component, the `open` header with per-value path keys, and the two-parameter +/// component dispatched on its input alone and on both parameters. The page names the providers +/// and shapes without declaring them. pub mod choosing_a_provider_per_type_the_open_statement { use cgp::prelude::*; @@ -342,37 +549,29 @@ pub mod choosing_a_provider_per_type_the_open_statement { fn area(&self, shape: &Shape) -> f64; } - pub struct Rectangle; - pub struct Circle; - pub struct Ellipse; - pub struct Square; - pub struct Triangle; + pub struct Rectangle { + pub width: f64, + pub height: f64, + } - #[cgp_impl(new RectangleArea)] - impl AreaCalculator { - fn area(&self, _shape: &Shape) -> f64 { - 0.0 - } + pub struct Circle { + pub radius: f64, } - #[cgp_impl(CurveArea)] - impl AreaCalculator { - fn area(&self, _shape: &Shape) -> f64 { - 0.0 + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height } } - pub struct CurveArea; - - #[cgp_impl(PolygonArea)] - impl AreaCalculator { - fn area(&self, _shape: &Shape) -> f64 { - 0.0 + #[cgp_impl(new CircleArea)] + impl AreaCalculator { + fn area(&self, shape: &Circle) -> f64 { + core::f64::consts::PI * shape.radius * shape.radius } } - pub struct PolygonArea; - pub struct MyApp; delegate_components! { @@ -380,7 +579,7 @@ pub mod choosing_a_provider_per_type_the_open_statement { open AreaCalculatorComponent; @AreaCalculatorComponent.Rectangle: RectangleArea, - @AreaCalculatorComponent.Circle: CurveArea, + @AreaCalculatorComponent.Circle: CircleArea, } } @@ -390,41 +589,50 @@ pub mod choosing_a_provider_per_type_the_open_statement { } } - /// The braced group, the bracketed group, and a segment carrying its own generics, on one - /// context — the forms the *three key forms* section contrasts. - pub struct GroupedApp; + /// The braced spelling of the header is the same statement. + pub struct BracedApp; delegate_components! { - GroupedApp { - open AreaCalculatorComponent; + BracedApp { + open { AreaCalculatorComponent }; - @AreaCalculatorComponent.{Circle, Ellipse}: - CurveArea, + @AreaCalculatorComponent.Rectangle: RectangleArea, + } + } - @AreaCalculatorComponent.[Square, Triangle]: - PolygonArea, + check_components! { + BracedApp { + AreaCalculatorComponent: Rectangle, + } + } - @AreaCalculatorComponent.<'a, T> &'a T: - RectangleArea, + /// The key-forms section's `@SomeComponent.<'a, T> &'a T: SomeProvider`: a path segment + /// carrying its own generics. + #[cgp_impl(new AnyReferenceArea)] + impl<'a, T> AreaCalculator<&'a T> { + fn area(&self, _shape: &&'a T) -> f64 { + 0.0 + } + } + + pub struct ReferenceApp; + + delegate_components! { + ReferenceApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.<'a, T> &'a T: AnyReferenceArea, } } check_components! { - GroupedApp { - AreaCalculatorComponent: [ - Circle, - Ellipse, - Square, - Triangle, - <'a> &'a Rectangle, - ], + ReferenceApp { + AreaCalculatorComponent: <'a> &'a Rectangle, } } - /// A component with two type parameters, dispatched on the input alone and on both parameters - /// in one table. Its own module, so its provider names do not clash with the ones above. pub mod later_parameters { - use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::extra::handler::{CanCompute, Computer, ComputerComponent}; use cgp::prelude::*; pub struct Area; @@ -491,87 +699,91 @@ pub mod choosing_a_provider_per_type_the_open_statement { #[test] fn the_input_or_both_parameters_select_the_provider() { - use cgp::extra::handler::CanCompute; - - let app = MyApp; let rectangle = || Rectangle { width: 2.0, height: 3.0, }; - assert_eq!(app.compute(PhantomData::, Circle { radius: 1.5 }), 1.5); - assert_eq!(app.compute(PhantomData::, Circle { radius: 1.5 }), 1.5); - assert_eq!(app.compute(PhantomData::, rectangle()), 6.0); - assert_eq!(app.compute(PhantomData::, rectangle()), 10.0); + assert_eq!(MyApp.compute(PhantomData::, Circle { radius: 1.5 }), 1.5); + assert_eq!(MyApp.compute(PhantomData::, Circle { radius: 1.5 }), 1.5); + assert_eq!(MyApp.compute(PhantomData::, rectangle()), 6.0); + assert_eq!(MyApp.compute(PhantomData::, rectangle()), 10.0); } } } -/// ## Statements come first +/// ### Statements come first /// -/// The combined block, which is the page's demonstration that the forms mix. `BarBundle` and the -/// providers are named by the page without being introduced. +/// The combined block, which is the page's demonstration that the forms mix. It opens the generic +/// area component while forwarding the plain perimeter component into `GeometryComponents`; the +/// page names the style components and every provider without declaring them. pub mod statements_come_first { use cgp::prelude::*; - use super::choosing_a_provider_per_type_the_open_statement::{ - AreaCalculatorComponent, Circle, PolygonArea, Rectangle, Square, Triangle, + pub use super::defining_the_target_at_the_same_time::{ + CanCalculatePerimeter, GeometryComponents, PerimeterCalculatorComponent, }; + use super::the_key_forms::{ColorComponent, ColorProvider}; - #[cgp_component(BarProvider)] - pub trait Bar { - fn bar(&self); - } - - #[cgp_component(BazProvider)] - pub trait Baz { - fn baz(&self); + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; } - #[cgp_component(QuuxProvider)] - pub trait Quux { - fn quux(&self); - } + pub struct Rectangle; + pub struct Circle; + pub struct Square; + pub struct Triangle; - #[cgp_impl(new DummyBar)] - impl BarProvider { - fn bar(&self) {} + #[cgp_impl(new ShapeArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 1.0 + } } - #[cgp_impl(new DummyBaz)] - impl BazProvider { - fn baz(&self) {} + #[cgp_impl(new PolygonArea)] + impl AreaCalculator { + fn area(&self, _shape: &Shape) -> f64 { + 2.0 + } } - #[cgp_impl(DummyBaz)] - impl QuuxProvider { - fn quux(&self) {} + #[cgp_component { + provider: LabelProvider, + name: LabelComponent, + }] + pub trait HasLabel { + fn label(&self) -> &'static str; } - delegate_components! { - new BarBundle { - BarProviderComponent: DummyBar, + #[cgp_impl(new DefaultStyle: ColorComponent)] + impl ColorProvider { + fn color(&self) -> &'static str { + "black" } } - /// The page names `ShapeArea` and `PolygonArea` as the two shape providers; `ShapeArea` is - /// declared here and `PolygonArea` is reused from the `open` section. - #[cgp_impl(new ShapeArea)] - impl super::choosing_a_provider_per_type_the_open_statement::AreaCalculator { - fn area(&self, _shape: &Shape) -> f64 { - 0.0 + #[cgp_impl(DefaultStyle: LabelComponent)] + impl LabelProvider { + fn label(&self) -> &'static str { + "shape" } } - pub struct App; + #[derive(HasField)] + pub struct App { + pub width: f64, + pub height: f64, + } delegate_components! { App { open AreaCalculatorComponent; - BarProviderComponent -> BarBundle, + PerimeterCalculatorComponent -> GeometryComponents, - [BazProviderComponent, QuuxProviderComponent]: DummyBaz, + [ColorComponent, LabelComponent]: DefaultStyle, @AreaCalculatorComponent.{Rectangle, Circle}: ShapeArea, @@ -584,17 +796,28 @@ pub mod statements_come_first { check_components! { App { AreaCalculatorComponent: [Rectangle, Circle, Square, Triangle], - BarProviderComponent, - BazProviderComponent, - QuuxProviderComponent, + PerimeterCalculatorComponent, + ColorComponent, + LabelComponent, } } + + #[test] + fn every_form_contributes_to_one_table() { + let app = App { + width: 2.0, + height: 3.0, + }; + assert_eq!(app.area(&Circle), 1.0); + assert_eq!(app.area(&Triangle), 2.0); + assert_eq!(app.perimeter(), 10.0); + } } /// ## Examples /// -/// The two-context payoff the page builds to: the same trait answered differently by two -/// contexts, and a generic function serving both. +/// The two contexts answering one trait through different providers, a function generic over the +/// trait serving both, and the per-type table on an environmental context. pub mod examples { use cgp::prelude::*; @@ -622,6 +845,12 @@ pub mod examples { } } + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + pub fn print_area(rect: &Rectangle) { println!("area = {}", rect.area()); } @@ -645,49 +874,195 @@ pub mod examples { } check_components! { - Rectangle { + Square { AreaCalculatorComponent, } } - check_components! { - #[check_trait(__CheckSquare2)] - Square { - AreaCalculatorComponent, - } + /// The page's claim that a function generic over the trait serves both contexts. + pub fn doubled_area(shape: &Shape) -> f64 { + shape.area() * 2.0 } - /// The page's claim that one generic function serves both contexts. - pub fn total_area(shapes: &[&dyn Fn() -> f64]) -> f64 { - shapes.iter().map(|f| f()).sum() + #[test] + fn each_context_answers_through_its_own_provider() { + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + print_area(&rectangle); + + assert_eq!(doubled_area(&rectangle), 24.0); + assert_eq!(doubled_area(&Square { side: 5.0 }), 50.0); } - #[cfg(test)] - mod tests { - use super::*; + /// The per-type table. `MyApp` wires the generic `CanCalculateArea` from *Usage*, so it + /// sits in its own module; the page names the shapes and `CurveArea` without declaring them. + pub mod per_type { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Ellipse { + pub major: f64, + pub minor: f64, + } + + pub trait HasSemiAxes { + fn semi_axes(&self) -> (f64, f64); + } + + impl HasSemiAxes for Circle { + fn semi_axes(&self) -> (f64, f64) { + (self.radius, self.radius) + } + } + + impl HasSemiAxes for Ellipse { + fn semi_axes(&self) -> (f64, f64) { + (self.major, self.minor) + } + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height + } + } + + #[cgp_impl(new CurveArea)] + impl AreaCalculator { + fn area(&self, shape: &Shape) -> f64 { + let (a, b) = shape.semi_axes(); + core::f64::consts::PI * a * b + } + } + + pub struct MyApp; + + delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.{Circle, Ellipse}: CurveArea, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle, Ellipse], + } + } #[test] - fn each_context_answers_through_its_own_provider() { + fn each_shape_reaches_its_provider() { let rectangle = Rectangle { - width: 3.0, - height: 4.0, + width: 2.0, + height: 3.0, }; - let square = Square { side: 5.0 }; - - assert_eq!(rectangle.area(), 12.0); - assert_eq!(square.area(), 25.0); + assert_eq!(MyApp.area(&rectangle), 6.0); + assert_eq!(MyApp.area(&Circle { radius: 1.0 }), core::f64::consts::PI); } } } -/// ## Gotchas +/// ## Under the hood /// -/// The page's rejected snippet: a braced path group followed by more path. A braced group holds -/// whole tails and therefore ends the path, so the trailing `.bool` sits where the mapping's -/// operator should be and the macro reports `expected ':'`. -/// -/// The bracketed form, which the page offers as the fix, is exercised above under -/// [`choosing_a_provider_per_type_the_open_statement`]. +/// The contexts whose expansions the page lists, checked with `cargo cgp expand --item` on each +/// item: `super::overview::Rectangle` for the plain pair, `super::the_key_forms::MyComponents` for +/// the list key, `super::the_operators::ScaledGeometryComponents` for `->`, `super::the_operators::App` +/// for `=>`, and the items below for `open`, its `=>` spelling, and the namespace statement. +pub mod under_the_hood { + use cgp::prelude::*; + + pub use super::choosing_a_provider_per_type_the_open_statement::{ + AreaCalculatorComponent, Rectangle, RectangleArea, + }; + + pub struct MyApp; + + delegate_components! { + MyApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent: Rectangle, + } + } + + /// `AreaCalculatorComponent => @AreaCalculatorComponent,`, whose impl the page says is the + /// `open` header's byte for byte. + pub struct RedirectApp; + + delegate_components! { + RedirectApp { + AreaCalculatorComponent => @AreaCalculatorComponent, + + @AreaCalculatorComponent.Rectangle: RectangleArea, + } + } + + check_components! { + RedirectApp { + AreaCalculatorComponent: Rectangle, + } + } + + pub struct App; + + delegate_components! { + App { + namespace DefaultNamespace; + } + } +} + +/// ## Common Mistakes /// -/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/macros/delegate_components_gotchas.rs`. -pub mod gotchas {} +/// The workaround the page gives for a `const`-parameter table: declare the struct by hand and +/// wire it with its own block. The rejected snippets are the trybuild fixtures. +pub mod common_mistakes { + use cgp::prelude::*; + + pub use super::overview::{AreaCalculatorComponent, RectangleArea}; + + pub struct ArrayKey; + pub struct ArrayTable; + + delegate_components! { + ArrayTable { + AreaCalculatorComponent: RectangleArea, + } + } + + delegate_components! { + new MyComponents { + ArrayKey: UseDelegate>, + } + } + + #[test] + fn the_hand_declared_table_is_wired() { + super::the_key_forms::delegates_to::, AreaCalculatorComponent, RectangleArea>(); + super::the_key_forms::delegates_to::, UseDelegate>>(); + } +} diff --git a/example-code/tests/reference/macros/mod.rs b/example-code/tests/reference/macros/mod.rs index 7252ff36..2462ba2b 100644 --- a/example-code/tests/reference/macros/mod.rs +++ b/example-code/tests/reference/macros/mod.rs @@ -13,4 +13,6 @@ pub mod cgp_namespace; pub mod cgp_producer; pub mod cgp_provider; pub mod cgp_type; +pub mod check_components; +pub mod delegate_and_check_components; pub mod delegate_components; From fe323c03d3cf5c2a8b66d642b0b85ecf1c08329c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 15:18:56 +0000 Subject: [PATCH 114/516] Correct a back-reference on the cgp_namespace reference page The paragraph combining namespaces with aggregate providers pointed at the wrong list items and named a component the page never introduces. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/cgp_namespace.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index cb736153..34df8c28 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -253,12 +253,13 @@ A few lighter tools cover most cases, and it is worth knowing where each stops. when inheritance is wanted, or when a library is publishing defaults for applications it does not know about. -The last two also combine. A context that joins a namespace can forward a whole path to an aggregate -provider in one entry, as `@app.core.user: UserComponents`, and the bundle then answers every component -registered under that path. The lookup reaches the bundle keyed by the bare component name, so a bundle -keyed by bare names needs nothing more. A bundle that groups several paths, such as a `CoreComponents` -holding `@app.core.user: UserComponents`, is keyed by paths and must itself join the namespace, or the -check fails with `CoreComponents: DelegateComponent` unsatisfied. +A namespace and an aggregate provider also combine. A context that joins a namespace can forward a +whole path to an aggregate provider in one entry, as `@app.core.user: UserComponents`, and the +bundle then answers every component registered under that path. The lookup reaches the bundle keyed +by the bare component name, so a bundle keyed by bare names needs nothing more. A bundle that groups +several paths, such as a `CoreComponents` holding `@app.core.user: UserComponents`, is keyed by +paths and must itself join the namespace, or the check fails reporting that `CoreComponents` has no +`DelegateComponent` entry for the component's bare name. A couple of things a namespace is *not* for. It will not make a single context's wiring shorter on its own; the entries still have to exist somewhere. And it is not how one component gets per-type dispatch, which is From cd2ab35d6a3d211583a99facf5705e930dc4acbe Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 15:41:54 +0000 Subject: [PATCH 115/516] Revise the type-level construction macro reference pages Resync Symbol!, Product!, Sum!, Path!, and the macros overview with their internal documents and the source, and revise their writing. Record the literal forms Symbol! accepts and rejects, StaticString, and the canonical cargo-cgp qualification; qualify the derived field lists as one of several generated impls; state the variant payload shapes and which derives reject them; and document Path!'s primitive-shaped segment defect, its empty-segment error, and the wildcard-tailed wiring key. Give the overview its provenance note. Add mirrors for the four macro pages and a trybuild fixture for every error they quote. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/index.md | 25 ++- docs/reference/macros/path.md | 55 ++++-- docs/reference/macros/product.md | 30 ++- docs/reference/macros/sum.md | 36 +++- docs/reference/macros/symbol.md | 43 +++-- example-code/README.md | 2 +- ...th_common_mistakes_letter_digit_segment.rs | 6 + ...ommon_mistakes_letter_digit_segment.stderr | 10 + .../macros/path_common_mistakes_missing_at.rs | 6 + .../path_common_mistakes_missing_at.stderr | 5 + .../macros/path_common_mistakes_no_segment.rs | 6 + .../path_common_mistakes_no_segment.stderr | 7 + ...ommon_mistakes_type_macro_in_expression.rs | 8 + ...n_mistakes_type_macro_in_expression.stderr | 5 + ...uct_common_mistakes_value_macro_in_type.rs | 6 + ...common_mistakes_value_macro_in_type.stderr | 11 ++ ...um_common_mistakes_variant_derive_shape.rs | 10 + ...ommon_mistakes_variant_derive_shape.stderr | 5 + .../symbol_common_mistakes_value_position.rs | 8 + ...mbol_common_mistakes_value_position.stderr | 23 +++ .../symbol_formal_grammar_byte_string.rs | 6 + .../symbol_formal_grammar_byte_string.stderr | 5 + .../symbol_formal_grammar_trailing_token.rs | 6 + ...ymbol_formal_grammar_trailing_token.stderr | 5 + example-code/tests/reference/macros/mod.rs | 4 + example-code/tests/reference/macros/path.rs | 146 ++++++++++++++ .../tests/reference/macros/product.rs | 137 ++++++++++++++ example-code/tests/reference/macros/sum.rs | 85 +++++++++ example-code/tests/reference/macros/symbol.rs | 179 ++++++++++++++++++ 29 files changed, 824 insertions(+), 56 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs create mode 100644 example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/path_common_mistakes_missing_at.rs create mode 100644 example-code/tests/compile_fail/reference/macros/path_common_mistakes_missing_at.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/path_common_mistakes_no_segment.rs create mode 100644 example-code/tests/compile_fail/reference/macros/path_common_mistakes_no_segment.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.rs create mode 100644 example-code/tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.rs create mode 100644 example-code/tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.rs create mode 100644 example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.rs create mode 100644 example-code/tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.rs create mode 100644 example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.rs create mode 100644 example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.stderr create mode 100644 example-code/tests/reference/macros/path.rs create mode 100644 example-code/tests/reference/macros/product.rs create mode 100644 example-code/tests/reference/macros/sum.rs create mode 100644 example-code/tests/reference/macros/symbol.rs diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md index 13200c05..d33c4fbe 100644 --- a/docs/reference/macros/index.md +++ b/docs/reference/macros/index.md @@ -13,8 +13,9 @@ building the type-level values (strings, lists, paths) that the rest of the syst page groups every macro in this section by the kind of work it does, in roughly the order most CGP code uses them. -If you are new to CGP, start with the [reference overview](/docs/reference/)'s six essentials rather -than here; this page is the fuller reference for once those six are familiar. +If you are new to CGP, start with the [six essentials](/docs/reference/#start-with-these-six) on the +reference overview rather than here; this page is the fuller reference for once those six are +familiar. ## Defining a component, and writing its providers @@ -28,8 +29,9 @@ generated code rather than written by hand. When a trait has exactly one implementation and needs no wiring at all, [`#[cgp_fn]`](./cgp_fn.md) builds it straight from a function, and [`#[blanket_trait]`](./blanket_trait.md) does the same starting from a trait with default methods and -[supertrait](/docs/reference/glossary#supertrait) dependencies. [`#[async_trait]`](./async_trait.md) is how any of these traits declares an -`async fn` without tripping the lint a bare one produces. +[supertrait](/docs/reference/glossary#supertrait) dependencies. [`#[async_trait]`](./async_trait.md) +is how any of these traits declares an `async fn` without tripping the lint a bare one produces in a +public trait. A few macros specialize `#[cgp_component]` for a narrower job. [`#[cgp_type]`](./cgp_type.md) is for a component that supplies a type a context chooses rather than a value it computes. @@ -60,7 +62,14 @@ presets without a separate construct for them. [`Product!`](./product.md) and its value-level twin `product!` build a type-level list for a struct's fields or a handler pipeline's steps, [`Sum!`](./sum.md) builds the dual list for an enum's variants, and [`Path!`](./path.md) builds the routing list that namespaces and redirected lookups resolve -against. All of them are mostly generated for you, by a derive, by the ergonomic macros above, or by the -`open` statement inside `delegate_components!`, and the useful skill is reading one back out of -a compiler error rather than writing it, since a diagnostic actually prints the raw list each expands -to (`Cons`/`Nil`, `Either`/`Void`, `PathCons`). +against. You write two of them by hand in ordinary code, `Symbol!` in a `UseField` wiring entry and +`Product!` in a handler pipeline, and the derives, the ergonomic macros above, and the `open` +statement inside `delegate_components!` generate the rest. The skill all four ask for is reading one +back out of a compiler error, since a diagnostic prints the raw list each expands to: +`Symbol<…, Chars<…>>`, `Cons`/`Nil`, `Either`/`Void`, or `PathCons`. + +--- + +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index cf2c2ce2..a790ade9 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -27,8 +27,8 @@ Path!(@app.error.ErrorRaiserComponent) It is the path-shaped sibling of CGP's other type-level construction macros. Where [`Symbol!`](./symbol.md) turns a literal into a [type-level string](/docs/reference/glossary#type-level-string) and [`Product!`](./product.md) and -[`Sum!`](./sum.md) build record and variant lists, `Path!` builds the routing list, sharing their right-nested, -`Nil`-terminated shape. +[`Sum!`](./sum.md) build record and variant lists, `Path!` builds the routing list. It shares their +right-nested shape and, like `Product!`, ends in `Nil`. **You will more often write the syntax than the macro.** The same `@`-path form is embedded directly in [`cgp_namespace!`](./cgp_namespace.md) entries, in `#[prefix(...)]` attributes, and in the `@`-path keys of @@ -48,14 +48,16 @@ Path!(@app.error.ErrorRaiserComponent) ### How a segment is encoded -Each segment is parsed as a type, and **its first character decides how it is treated**. This is the one rule -worth learning, because it lets a path mix names and types without any extra syntax: +Each segment is parsed as a type, and **its spelling decides how it is treated**: a bare lowercase +identifier becomes a string, and anything else stays a type. This is the one rule worth learning, +because it lets a path mix names and types without any extra syntax: | The segment | Becomes | |---|---| -| A single lowercase identifier (`app`, `error`) | a [`Symbol`](./symbol.md) type-level string | +| A single identifier starting with a lowercase ASCII letter (`app`, `my_app`) | a [`Symbol`](./symbol.md) type-level string | | A capitalized name (`ErrorRaiserComponent`) | that named type | | A primitive type name (`u32`, `bool`, `str`) | that type, *not* a symbol | +| Any other type (`Vec`, `some_mod::Marker`, `&'static str`) | that type | So lowercase segments read as namespace and prefix names, capitalized ones as component keys or marker types, and the primitive exception keeps `@u32` meaning the type `u32` rather than the string `"u32"`. Mixing is @@ -70,6 +72,7 @@ Used directly, `Path!` names a route that a [`RedirectLookup`](../providers/redi a table: ```rust +use cgp::core::error::ErrorRaiserComponent; use cgp::prelude::*; type ErrorRoute = Path!(@app.error.ErrorRaiserComponent); @@ -113,7 +116,8 @@ delegate_components! { ``` All four build the same kind of list. The macro and the embedded syntax are two places to write it, not two -different things. +different things, with one difference in the last: a `delegate_components!` path key ends in a wildcard +parameter rather than `Nil`, so it also matches longer paths beneath it. ## When to use it @@ -187,11 +191,12 @@ PathInput -> `@` PathSegment ( `.` PathSegment )* PathSegment -> Type ``` -The leading `` `@` `` is required and at least one segment must follow. Each `PathSegment` is parsed as a Rust -`Type`, but its encoding is decided semantically: a single lowercase identifier that is not a primitive type name -becomes a `Symbol` type-level string, while every other segment (a capitalized name or a primitive) is kept as -the named type. [`cgp_namespace!`](./cgp_namespace.md) entries and `#[prefix(...)]` -attributes embed this same grammar, where it appears as the `Path` production. +The leading `` `@` `` is required and at least one segment must follow. Each `PathSegment` is parsed +as a Rust `Type`, but its encoding is decided semantically: a single identifier starting with a +lowercase ASCII letter that is not primitive-shaped becomes a `Symbol` type-level string, while +every other segment (a capitalized name, a primitive, or any type with a path, generic arguments, or +other structure) is kept as the type. [`cgp_namespace!`](./cgp_namespace.md) entries and +`#[prefix(...)]` attributes embed this same grammar, where it appears as the `Path` production. ## Common Mistakes @@ -201,15 +206,33 @@ attributes embed this same grammar, where it appears as the `Path` production. error: expected `@` ``` -**Case decides meaning, silently.** `@app` and `@App` are entirely different segments (a type-level string -versus a named type), and both are valid, so a capitalization slip produces a path that compiles and routes -somewhere else. The failure surfaces later as a lookup that resolves to nothing, with no hint that the cause was -a capital letter. +**Case decides meaning, silently.** `@app` and `@App` are entirely different segments (a type-level +string versus a named type), and wherever a type `App` exists both are valid, so a capitalization +slip produces a path that compiles and routes somewhere else. The failure surfaces later as a lookup +that resolves to nothing, with no hint that the cause was a capital letter. **A lowercase primitive is the type, not a string.** `@u32`, `@bool`, and `@str` name those types. That is almost always what you want, and it means a path segment cannot be the *string* `"u32"` through this syntax. -**A path that routes nowhere still compiles.** A route is just a type; nothing checks that anything is bound at +**The primitive check also catches names that are not primitives.** It treats `char`, `bool`, +`usize`, `isize`, `str`, and any `i`, `u`, or `f` followed only by digits as a primitive, which +includes the bare `i`, `u`, and `f` and names such as `u2`. So `@app.f` keeps `f` as a type instead +of the string `"f"`, and fails unless a type `f` is in scope: + +```text +error[E0425]: cannot find type `f` in this scope +``` + +Avoid one-letter and letter-digit segments of that shape in a path. + +**A path needs a segment after the `@` and after every dot.** `@` alone, or a trailing dot as in +`@app.`, fails while parsing the missing segment as a type, with a message that lists type tokens: + +```text +error: unexpected end of input, expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime +``` + +**A path that routes nowhere still compiles.** A route is only a type; nothing checks that anything is bound at its end. An unbound route is reported only when a [`check_components!`](./check_components.md) evaluates the lookup, as an unsatisfied bound naming the expanded path. This is why namespace mistakes tend to surface at the check rather than at the definition. diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 5f5c519e..094bcdf0 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -65,7 +65,7 @@ pub struct Person { pub age: u8, } -// generated: +// generated, among other impls: // impl HasFields for Person { // type Fields = Product![ // Field, @@ -74,12 +74,15 @@ pub struct Person { // } ``` -The names are [`Symbol!`](./symbol.md) [type-level strings](/docs/reference/glossary#type-level-string) and each entry is a [`Field`](../types/field.md), so -the whole `Product!` is a complete type-level description of `Person`'s layout. Generic code walks that list to -build or read a `Person` without being written against `Person`. +The names are [`Symbol!`](./symbol.md) [type-level strings](/docs/reference/glossary#type-level-string) +and each entry is a [`Field`](../types/field.md), so the whole `Product!` is a complete type-level +description of `Person`'s layout. Generic code walks that list to build or read a `Person` without being +written against `Person`. The derive emits the same list again for `HasFieldsRef`, over references, along +with the `ToFields`, `ToFieldsRef`, and `FromFields` conversions. You write `Product!` yourself in a handler pipeline, where the list *is* the program: the steps run -left to right: +left to right. Here `Multiply` and `Add` stand for computers that read a `u64` field named by +`Tag`, so `MyContext` computes `((input * foo) + bar) * baz`: ```rust delegate_components! { @@ -132,7 +135,7 @@ Cons>> Both building blocks are ordinary types. `Cons` is a tuple struct holding the first element and the rest of the list (`Cons(pub Head, pub Tail)`), and `Nil` is a unit struct terminating it. Chaining -through the tail gives a list of any length, and the empty `Product![]` is simply `Nil`. The macro builds the +through the tail gives a list of any length, and the empty `Product![]` is `Nil`. The macro builds the chain by folding the elements right to left onto `Nil`. `product!` folds identically but produces a value, using `Cons`'s tuple-struct constructor: @@ -176,12 +179,19 @@ type macro in expression position fails inside the macro's own parser, which is message is a list of type-position tokens with no hint that the lowercase macro was wanted: ```text -error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, - square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime +error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime ``` -**A one-element list is not a wrapper.** `Product![T]` is `Cons`, which is a distinct type from `T`, -so a pipeline of one step still needs the list, and unwrapping it is a type error rather than a no-op. +The reverse slip is no clearer. `product!` in type position expands to the constructor call +`Cons(u32, …)`, which rustc reads as a parenthesized type argument: + +```text +error[E0214]: parenthesized type parameters may only be used with a `Fn` trait +``` + +**A one-element list is still a list.** `Product![T]` is `Cons`, which is a distinct type +from `T`, so a pipeline of one step still needs the list, and unwrapping it is a type error rather +than a no-op. **The empty list is `Nil`, a real value.** That is the difference from [`Sum!`](./sum.md), whose empty form is the uninhabited `Void`. An empty record exists; an empty choice cannot. diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index b5ce46cf..7568f74c 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -61,7 +61,7 @@ pub enum Shape { Rectangle { width: f64, height: f64 }, } -// generated (schematically): +// generated, among other impls: // impl HasFields for Shape { // type Fields = Sum![ // Field, @@ -73,10 +73,20 @@ pub enum Shape { // } ``` -A couple of things to notice. The variant names are [`Symbol!`](./symbol.md) [type-level strings](/docs/reference/glossary#type-level-string), exactly as field names -are. And a struct-like variant nests a [`Product!`](./product.md) of its own fields, so an enum's full shape is -a sum of variants whose payloads may themselves be records. Generic code walks the `Sum!` to find which variant -a value holds, then walks the nested `Product!` to reach that variant's fields. +A couple of things to notice. The variant names are [`Symbol!`](./symbol.md) +[type-level strings](/docs/reference/glossary#type-level-string), exactly as field names are. And a +variant's payload follows its fields, so an enum's full shape is a sum of variants whose payloads may +themselves be records: + +- **A single unnamed field** is the payload type itself, as `Circle(f64)` gives `f64`. +- **Named fields** nest a [`Product!`](./product.md) of `Field` entries, as `Rectangle` does. +- **Several unnamed fields** nest a `Product!` keyed by [`Index`](../types/index_type.md), so + `Pair(f64, f64)` gives `Product![Field, f64>, Field, f64>]`. +- **A unit variant** carries `Nil`. + +Generic code walks the `Sum!` to find which variant a value holds, then walks a nested `Product!` to +reach that variant's fields. `#[derive(HasFields)]` accepts all four shapes; the variant derives that +build and take apart values accept only the first, as [Common Mistakes](#common-mistakes) explains. A standalone sum can be written directly, which is mostly useful for illustration: @@ -121,7 +131,7 @@ the rest of the chain. So a value of `Either>>` is The terminator is `Void`, an **empty enum that can never be constructed**, and choosing it rather than `Nil` is the essential decision here. Reaching the `Void` position would mean the value matched none of the listed types, which is impossible. So the type system knows the chain is exhausted. An empty `Sum![]` is therefore -just `Void`: a type with no values. +`Void`: a type with no values. That is precisely the asymmetry with [`Product!`](./product.md). A product terminates in `Nil` because an empty record is a perfectly good value; a sum terminates in `Void` because an empty choice is *uninhabited*, there @@ -161,9 +171,17 @@ name-tagged [`Field`](../types/field.md)s and the operations match on names, so But the *types* are still different, and a cast between two enums works through the name matching rather than by position. -**A derivable enum's variants must each hold exactly one unnamed field.** That is a restriction of the -extensible-data derives rather than of `Sum!` itself, and it is why richer payloads are wrapped in a dedicated -struct: the variant's payload type has to be a single nameable type for the sum entry to carry it. +**The variant derives need each variant to hold exactly one unnamed field.** +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md), `CgpVariant`, `ExtractField`, and `FromVariant` +reject a struct-like, multi-field, or unit variant, while `#[derive(HasFields)]` accepts all of them: + +```text +error: Expected variant to contain exactly one unnamed field +``` + +That is a restriction of those derives rather than of `Sum!` itself, and it is why richer payloads are +wrapped in a dedicated struct, as `Rectangle(Rectangle)`: constructing or extracting a variant hands +over its payload as one value, so the payload has to be a single type. ## Related constructs diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 9e65c45e..a57fe95f 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -46,8 +46,11 @@ Symbol!("first_name") Symbol!("") ``` -Any valid string literal is accepted, including the empty string and multi-byte Unicode -(`Symbol!("世界")`). Most often it appears inside a field bound: +Any string literal is accepted, including the empty string and multi-byte Unicode +(`Symbol!("世界")`). A raw string or an escape spells the characters it denotes, so `Symbol!(r"raw")` +is the same type as `Symbol!("raw")`. Anything else fails: a byte string or an identifier with +`expected string literal`, and a second token after the literal with `unexpected token`. Most often +the macro appears inside a field bound: ```rust Self: HasField @@ -119,6 +122,11 @@ let s = ::default(); assert_eq!(s.to_string(), "hello"); ``` +The same text is available as a constant through +[`StaticString`](../traits/formatting/static_string.md), imported from `cgp::core::field::traits`: +`::VALUE` is `"hello"`. That trait is the reason the expansion +records a length, as [Under the hood](#under-the-hood) explains. + ## When to use it **Write `Symbol!` when a wiring entry has to name a field**, and let the macros produce it everywhere else. @@ -167,16 +175,19 @@ Symbol!("世界你好") // Symbol<12, Chars<'世', ...>> — 12 bytes, 4 char ``` The character list has one `Chars` node per Unicode scalar value, so those two numbers disagree for any -non-ASCII string. `LEN` is there so length-dependent code can read the size off the type instead of recursing -through the list. +non-ASCII string. `LEN` is there so length-dependent code can read the size off the type instead of +recursing through the list. `StaticString` is that code: it decodes the characters into a `[u8; LEN]` +buffer at compile time, and an array's size must be a constant. The expansion is built by folding the characters right to left onto `Nil` and wrapping the result, so the empty string `Symbol!("")` becomes `Symbol<0, Nil>`. **What this means for reading errors** is the practical benefit. A missing field on a context is reported against the expanded tag, so an error mentioning -`HasField>>>` is telling you the field `width` is missing. Counting the -characters is enough to decode it, and `cargo cgp check` resugars the common cases. +`HasField>>>` is telling you the field `width` is missing. Reading +the characters in order is enough to decode it, and [`cargo cgp check`](/docs/cargo-cgp/check) names +the field directly, as ``missing field `width` ``. `cargo cgp check` leads with the root cause for the +classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. ## Formal grammar @@ -187,9 +198,9 @@ The input is a single string literal, in the Rust Reference's SymbolInput -> STRING_LITERAL ``` -`STRING_LITERAL` is the Rust string-literal token, so any valid string literal is accepted, including the -empty string and multi-byte Unicode. The macro is used in type position, and this single literal is the whole -of its input. +`STRING_LITERAL` is the Rust string-literal token, so any string literal is accepted, raw strings +included, while a byte string or a C string is not. The macro is used in type position, and this single +literal is the whole of its input: a token after it fails with `unexpected token`. ## Common Mistakes @@ -204,9 +215,17 @@ types, and the derive generates the second, so the first matches nothing. unrelated types, and a mismatch reports as a missing `HasField` bound rather than as a typo. This is the usual cause of a getter that "should" work. -**It is a type, so it goes in type position.** Writing `Symbol!("name")` where a value is expected does not -work; the `PhantomData::` form is how the tag is passed to `get_field`, and the tag is the -type argument rather than the value. +**It is a type, so it goes in type position.** Writing `Symbol!("name")` where a value is expected +fails with errors that do not mention the macro, because the expanded `Symbol<4, Chars<…>>` parses as a +chain of comparisons: + +```text +error: macro expansion ignores `,` and any tokens following +``` + +followed by an `E0369` and an `E0308` about `<` and struct constructors. The +`PhantomData::` form is how the tag is passed to `get_field`, and the tag is the type +argument rather than the value. ## Related constructs diff --git a/example-code/README.md b/example-code/README.md index 648a443e..abeaa861 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -36,7 +36,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, the `macros/` pages `cgp_component.md`, `cgp_impl.md`, `cgp_provider.md`, `cgp_fn.md`, `cgp_type.md`, `cgp_getter.md`, `cgp_auto_getter.md`, `blanket_trait.md`, `async_trait.md`, `cgp_computer.md`, `cgp_producer.md`, `cgp_auto_dispatch.md`, `cgp_namespace.md`, `delegate_components.md`, `delegate_and_check_components.md`, and `check_components.md`, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, every `macros/` page that shows code, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | diff --git a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs new file mode 100644 index 00000000..2dd10215 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs @@ -0,0 +1,6 @@ +use cgp::prelude::*; + +// error[E0425]: the segment `f` is read as a primitive-shaped type, not a symbol +pub type Route = Path!(@app.f); + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.stderr b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.stderr new file mode 100644 index 00000000..af4c3845 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.stderr @@ -0,0 +1,10 @@ +error[E0425]: cannot find type `f` in this scope + --> tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs:4:29 + | +4 | pub type Route = Path!(@app.f); + | ^ not found in this scope + | +help: you might be missing a type parameter + | +4 | pub type Route = Path!(@app.f); + | +++ diff --git a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_missing_at.rs b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_missing_at.rs new file mode 100644 index 00000000..4d3eeb84 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_missing_at.rs @@ -0,0 +1,6 @@ +use cgp::prelude::*; + +// error: expected `@` +pub type Route = Path!(app.error); + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_missing_at.stderr b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_missing_at.stderr new file mode 100644 index 00000000..54e56d3c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_missing_at.stderr @@ -0,0 +1,5 @@ +error: expected `@` + --> tests/compile_fail/reference/macros/path_common_mistakes_missing_at.rs:4:24 + | +4 | pub type Route = Path!(app.error); + | ^^^ diff --git a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_no_segment.rs b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_no_segment.rs new file mode 100644 index 00000000..6ff98c75 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_no_segment.rs @@ -0,0 +1,6 @@ +use cgp::prelude::*; + +// error: unexpected end of input, expected one of: `for`, parentheses, `fn`, ... +pub type Route = Path!(@); + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_no_segment.stderr b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_no_segment.stderr new file mode 100644 index 00000000..5ce6c4e0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_no_segment.stderr @@ -0,0 +1,7 @@ +error: unexpected end of input, expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime + --> tests/compile_fail/reference/macros/path_common_mistakes_no_segment.rs:4:18 + | +4 | pub type Route = Path!(@); + | ^^^^^^^^ + | + = note: this error originates in the macro `Path` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.rs b/example-code/tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.rs new file mode 100644 index 00000000..c4cc7e78 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.rs @@ -0,0 +1,8 @@ +use cgp::prelude::*; + +// error: expected one of: `for`, parentheses, `fn`, ... +pub fn row() { + let _row = Product![1, 2]; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.stderr b/example-code/tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.stderr new file mode 100644 index 00000000..7bbbe2e0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.stderr @@ -0,0 +1,5 @@ +error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime + --> tests/compile_fail/reference/macros/product_common_mistakes_type_macro_in_expression.rs:5:25 + | +5 | let _row = Product![1, 2]; + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.rs b/example-code/tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.rs new file mode 100644 index 00000000..245cbd23 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.rs @@ -0,0 +1,6 @@ +use cgp::prelude::*; + +// error[E0214]: parenthesized type parameters may only be used with a `Fn` trait +pub type Row = product![u32, bool]; + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.stderr b/example-code/tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.stderr new file mode 100644 index 00000000..581d2d90 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.stderr @@ -0,0 +1,11 @@ +error[E0214]: parenthesized type parameters may only be used with a `Fn` trait + --> tests/compile_fail/reference/macros/product_common_mistakes_value_macro_in_type.rs:4:16 + | +4 | pub type Row = product![u32, bool]; + | ^^^^^^^^^^^^^^^^^^^ only `Fn` traits may use parentheses + | + = note: this error originates in the macro `product` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use angle brackets instead + | +4 | pub type Row = ; + | + + diff --git a/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.rs b/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.rs new file mode 100644 index 00000000..3a24ef6a --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: Expected variant to contain exactly one unnamed field +#[derive(CgpData)] +pub enum Shape { + Circle(f64), + Rectangle { width: f64, height: f64 }, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.stderr b/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.stderr new file mode 100644 index 00000000..1cdb5caf --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.stderr @@ -0,0 +1,5 @@ +error: Expected variant to contain exactly one unnamed field + --> tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.rs:7:5 + | +7 | Rectangle { width: f64, height: f64 }, + | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.rs b/example-code/tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.rs new file mode 100644 index 00000000..f3a00078 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.rs @@ -0,0 +1,8 @@ +use cgp::prelude::*; + +// error[E0369] and others: `Symbol!` builds a type, so it fails in expression position +pub fn tag() { + let _tag = Symbol!("name"); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.stderr b/example-code/tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.stderr new file mode 100644 index 00000000..e4ea5627 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.stderr @@ -0,0 +1,23 @@ +error: macro expansion ignores `,` and any tokens following + --> tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.rs:5:24 + | +5 | let _tag = Symbol!("name"); + | --------^^^^^^- caused by the macro expansion here + | + = note: the usage of `Symbol!` is likely invalid in expression context + +error[E0369]: binary operation `<` cannot be applied to type `fn(PhantomData<_>) -> cgp::prelude::Symbol<_, _> {cgp::prelude::Symbol::<_, _>}` + --> tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.rs:5:24 + | +5 | let _tag = Symbol!("name"); + | ^^^^^^ + +error[E0308]: mismatched types + --> tests/compile_fail/reference/macros/symbol_common_mistakes_value_position.rs:5:16 + | +5 | let _tag = Symbol!("name"); + | ^^^^^^^^^^^^^^^ expected struct constructor, found integer + | + = note: expected struct constructor `fn(PhantomData<_>) -> cgp::prelude::Symbol<_, _> {cgp::prelude::Symbol::<_, _>}` + found type `{integer}` + = note: this error originates in the macro `Symbol` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.rs b/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.rs new file mode 100644 index 00000000..cf5fab86 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.rs @@ -0,0 +1,6 @@ +use cgp::prelude::*; + +// error: expected string literal +pub type Tag = Symbol!(b"name"); + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.stderr b/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.stderr new file mode 100644 index 00000000..6daf4d62 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.stderr @@ -0,0 +1,5 @@ +error: expected string literal + --> tests/compile_fail/reference/macros/symbol_formal_grammar_byte_string.rs:4:24 + | +4 | pub type Tag = Symbol!(b"name"); + | ^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.rs b/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.rs new file mode 100644 index 00000000..d7e15f1e --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.rs @@ -0,0 +1,6 @@ +use cgp::prelude::*; + +// error: unexpected token +pub type Tag = Symbol!("first" "name"); + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.stderr b/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.stderr new file mode 100644 index 00000000..3a459e58 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.stderr @@ -0,0 +1,5 @@ +error: unexpected token + --> tests/compile_fail/reference/macros/symbol_formal_grammar_trailing_token.rs:4:32 + | +4 | pub type Tag = Symbol!("first" "name"); + | ^^^^^^ diff --git a/example-code/tests/reference/macros/mod.rs b/example-code/tests/reference/macros/mod.rs index 2462ba2b..09f9faef 100644 --- a/example-code/tests/reference/macros/mod.rs +++ b/example-code/tests/reference/macros/mod.rs @@ -16,3 +16,7 @@ pub mod cgp_type; pub mod check_components; pub mod delegate_and_check_components; pub mod delegate_components; +pub mod path; +pub mod product; +pub mod sum; +pub mod symbol; diff --git a/example-code/tests/reference/macros/path.rs b/example-code/tests/reference/macros/path.rs new file mode 100644 index 00000000..0ce30c54 --- /dev/null +++ b/example-code/tests/reference/macros/path.rs @@ -0,0 +1,146 @@ +//! Code from `docs/reference/macros/path.md` — *`Path!`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. Type +//! equalities are checked by assigning one `PhantomData` to a binding typed with the other. + +/// ## Usage and How a segment is encoded +/// +/// The three example paths, and one segment of each kind in the page's table. +pub mod usage { + use cgp::core::error::ErrorRaiserComponent; + use cgp::prelude::*; + + pub type One = Path!(@app); + pub type Two = Path!(@app.error); + pub type Three = Path!(@app.error.ErrorRaiserComponent); + + pub struct ShowImplComponent; + + pub mod some_mod { + pub struct Marker; + } + + #[test] + fn a_segment_is_encoded_by_its_spelling() { + // A lowercase identifier becomes a symbol. + let _: PhantomData = PhantomData::>; + let _: PhantomData = PhantomData::>; + // A capitalized name, a primitive, and any other type stay the type. + let _: PhantomData = + PhantomData::>; + let _: PhantomData = + PhantomData::>>>; + let _: PhantomData)> = + PhantomData::, Nil>>>; + let _: PhantomData = + PhantomData::>>; + let _: PhantomData = + PhantomData::>>; + } +} + +/// ## Examples +/// +/// The named route, the namespace redirect, the prefix registration, and the wiring key, joined +/// into one program so the route resolves. The page names `FooProviderComponent`, +/// `MyFooComponent`, `AppNamespace`, `ShowWithDebug`, and `MyApp` without declaring them here. +pub mod examples { + use cgp::core::error::ErrorRaiserComponent; + use cgp::prelude::*; + + pub type ErrorRoute = Path!(@app.error.ErrorRaiserComponent); + + #[test] + fn the_named_route_is_a_path_list() { + let _: PhantomData = PhantomData::< + PathCons>>, + >; + } + + #[cgp_component(FooProvider)] + pub trait Foo { + fn foo(&self) -> u8; + } + + pub struct MyFooComponent; + + cgp_namespace! { + new MyNamespace { + FooProviderComponent => + @MyFooComponent, + } + } + + #[cgp_component(ShowImpl)] + #[prefix(@show in AppNamespace)] + pub trait CanShow { + fn show(&self) -> String; + } + + #[cgp_impl(new ShowWithDebug)] + #[uses(core::fmt::Debug)] + impl ShowImpl { + fn show(&self) -> String { + format!("{:?}", self) + } + } + + cgp_namespace! { + new AppNamespace {} + } + + #[derive(Debug)] + pub struct MyApp; + + delegate_components! { + MyApp { + namespace AppNamespace; + + @show.ShowImplComponent: ShowWithDebug, + } + } + + check_components! { + MyApp { + ShowImplComponent, + } + } + + #[test] + fn the_prefixed_route_resolves() { + assert_eq!(MyApp.show(), "MyApp"); + } +} + +/// ## Under the hood +/// +/// The fully expanded symbol segment and the embedded forms' paths, checked against the traits +/// the macros implement: the namespace's redirect `Delegate`, and the prefix route. +pub mod under_the_hood { + use cgp::prelude::*; + + pub use super::examples::{ + AppNamespace, FooProviderComponent, MyFooComponent, MyNamespace, ShowImplComponent, + }; + + pub struct MyComp; + + #[test] + fn a_symbol_segment_nests_a_character_list() { + let _: PhantomData = + PhantomData::>>>, Nil>>; + let _: PhantomData = PhantomData::>; + let _: PhantomData = PhantomData::>; + } + + pub struct Table; + + #[test] + fn the_embedded_forms_build_the_same_list() { + let _: PhantomData<>::Delegate> = + PhantomData::>>; + let _: PhantomData<>::Delegate> = PhantomData::< + RedirectLookup>>, + >; + } +} diff --git a/example-code/tests/reference/macros/product.rs b/example-code/tests/reference/macros/product.rs new file mode 100644 index 00000000..404d4844 --- /dev/null +++ b/example-code/tests/reference/macros/product.rs @@ -0,0 +1,137 @@ +//! Code from `docs/reference/macros/product.md` — *`Product!` & `product!`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. Type +//! equalities are checked by assigning one `PhantomData` to a binding typed with the other. + +/// ## Usage +/// +/// The type, its value, the empty list, and a trailing comma. +pub mod usage { + use cgp::prelude::*; + + #[test] + fn the_value_has_the_type_the_type_macro_builds() { + let row: Product![u32, String, bool] = product![1u32, "hi".to_string(), true]; + let Cons(first, Cons(_, Cons(third, Nil))) = row; + assert_eq!((first, third), (1, true)); + + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::; + let Nil = product![]; + } +} + +/// ## Examples +/// +/// The derived field list, the pipeline the page wires, and the standalone row. The page names +/// `MyContext`, `Multiply`, and `Add` without declaring them; `Multiply` and `Add` are +/// computers reading a `u64` field named by `Tag`. +pub mod examples { + use cgp::extra::handler::{CanCompute, Computer, ComputerComponent, PipeHandlers}; + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + #[test] + fn the_derive_generates_the_field_list() { + let _: PhantomData<::Fields> = PhantomData::< + Product![Field, Field], + >; + } + + #[cgp_impl(new Multiply)] + #[uses(HasField)] + impl Computer { + type Output = u64; + + fn compute(&self, _code: PhantomData, input: u64) -> u64 { + input * self.get_field(PhantomData::) + } + } + + #[cgp_impl(new Add)] + #[uses(HasField)] + impl Computer { + type Output = u64; + + fn compute(&self, _code: PhantomData, input: u64) -> u64 { + input + self.get_field(PhantomData::) + } + } + + #[derive(HasField)] + pub struct MyContext { + pub foo: u64, + pub bar: u64, + pub baz: u64, + } + + delegate_components! { + MyContext { + ComputerComponent: + PipeHandlers, + Add, + Multiply, + ]>, + } + } + + check_components! { + MyContext { + ComputerComponent: ((), u64), + } + } + + #[test] + fn the_steps_run_left_to_right() { + let context = MyContext { + foo: 2, + bar: 3, + baz: 4, + }; + assert_eq!(context.compute(PhantomData::<()>, 5), ((5 * 2) + 3) * 4); + } + + #[test] + fn a_standalone_row() { + type Row = Product![u32, String, bool]; + let row: Row = product![1, "hi".to_string(), true]; + let Cons(first, _) = row; + assert_eq!(first, 1); + } +} + +/// ## Under the hood +pub mod under_the_hood { + use cgp::prelude::*; + + pub struct A; + pub struct B; + pub struct C; + + #[test] + fn both_macros_fold_onto_nil() { + let _: PhantomData = PhantomData::>>>; + let Cons(A, Cons(B, Cons(C, Nil))) = product![A, B, C]; + } +} + +/// ## Common Mistakes +/// +/// A one-element list is a distinct type from its element. The misplaced-macro snippets are +/// trybuild fixtures. +pub mod common_mistakes { + use cgp::prelude::*; + + #[test] + fn a_one_element_list_wraps_its_element() { + let one: Product![u32] = product![7]; + let Cons(inner, Nil) = one; + assert_eq!(inner, 7); + } +} diff --git a/example-code/tests/reference/macros/sum.rs b/example-code/tests/reference/macros/sum.rs new file mode 100644 index 00000000..f12a5bdb --- /dev/null +++ b/example-code/tests/reference/macros/sum.rs @@ -0,0 +1,85 @@ +//! Code from `docs/reference/macros/sum.md` — *`Sum!`*. +//! +//! The snippet the page rejects lives under `tests/compile_fail/reference/macros/`. Type +//! equalities are checked by assigning one `PhantomData` to a binding typed with the other. + +/// ## Usage +pub mod usage { + use cgp::prelude::*; + + #[test] + fn the_empty_sum_is_void() { + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::; + } +} + +/// ## Examples +/// +/// The enum whose derived variant list the page shows, extended with the two payload shapes the +/// page describes in prose: several unnamed fields, keyed by `Index`, and a unit variant. +pub mod examples { + use cgp::prelude::*; + + #[derive(HasFields)] + pub enum Shape { + Circle(f64), + Rectangle { width: f64, height: f64 }, + } + + #[test] + fn the_derive_generates_the_variant_list() { + let _: PhantomData<::Fields> = PhantomData::< + Sum![ + Field, + Field< + Symbol!("Rectangle"), + Product![Field, Field], + >, + ], + >; + } + + #[derive(HasFields)] + pub enum Payloads { + Pair(f64, f64), + Empty, + } + + #[test] + fn unnamed_fields_nest_by_index_and_a_unit_variant_holds_nil() { + let _: PhantomData<::Fields> = PhantomData::< + Sum![ + Field, f64>, Field, f64>]>, + Field, + ], + >; + } + + pub type Token = Sum![u32, String, bool]; +} + +/// ## Under the hood +/// +/// The `Either`/`Void` chain, and the position of each alternative in it. +pub mod under_the_hood { + use cgp::prelude::*; + + pub struct A; + pub struct B; + pub struct C; + + #[test] + fn the_sum_folds_onto_void() { + let _: PhantomData = + PhantomData::>>>; + + let b: Sum![A, B, C] = Either::Right(Either::Left(B)); + assert!(matches!(b, Either::Right(Either::Left(B)))); + } + + /// A handled-every-variant remainder is `Void`, discharged without a fallback arm. + pub fn exhausted(remainder: Void) -> u8 { + match remainder {} + } +} diff --git a/example-code/tests/reference/macros/symbol.rs b/example-code/tests/reference/macros/symbol.rs new file mode 100644 index 00000000..c7df1c05 --- /dev/null +++ b/example-code/tests/reference/macros/symbol.rs @@ -0,0 +1,179 @@ +//! Code from `docs/reference/macros/symbol.md` — *`Symbol!`*. +//! +//! The snippets the page rejects, and the errors it quotes, live under +//! `tests/compile_fail/reference/macros/`. Type equalities are checked by assigning one +//! `PhantomData` to a binding typed with the other. + +/// ## Overview and Usage +/// +/// The literal forms the page lists, and the field bound it shows twice. +pub mod overview_and_usage { + use cgp::prelude::*; + + pub type Name = Symbol!("name"); + pub type FirstName = Symbol!("first_name"); + pub type Empty = Symbol!(""); + pub type Unicode = Symbol!("世界"); + + pub fn reads_a_name(context: &Context) -> &String + where + Context: HasField, + { + context.get_field(PhantomData::) + } + + /// Any string literal the parser accepts decodes to the same type: a raw string and an + /// escape spell the characters they denote. + #[test] + fn every_string_literal_form_is_accepted() { + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::; + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[test] + fn the_tag_selects_the_field() { + let person = Person { + name: "Ada".to_owned(), + }; + assert_eq!(reads_a_name(&person), "Ada"); + } +} + +/// ### The tag for a tuple field +pub mod the_tag_for_a_tuple_field { + use cgp::prelude::*; + + #[derive(HasField)] + pub struct Point(pub f64, pub f64); + + #[test] + fn a_position_is_keyed_by_index() { + let point = Point(1.0, 2.0); + assert_eq!(*point.get_field(PhantomData::>), 2.0); + } +} + +/// ### Raw identifiers +pub mod raw_identifiers { + use cgp::prelude::*; + + #[derive(HasField)] + pub struct Token { + pub r#type: u8, + } + + #[test] + fn the_raw_prefix_is_stripped() { + let token = Token { r#type: 7 }; + assert_eq!(*token.get_field(PhantomData::), 7); + } +} + +/// ## Examples +/// +/// The getter wired to a differently-named field, the hand-written field bound, and the runtime +/// string. The page names `Greeter` without declaring it. +pub mod examples { + use cgp::prelude::*; + + #[cgp_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub first_name: String, + } + + delegate_components! { + Person { + NameGetterComponent: UseField, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + + #[test] + fn the_tag_names_the_field_to_read() { + let person = Person { + first_name: "Ada".to_owned(), + }; + assert_eq!(person.name(), "Ada"); + } + + pub mod hand_written_bound { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self); + } + + #[cgp_impl(new GreetHello)] + impl Greeter + where + Self: HasField, + { + fn greet(&self) { + println!("Hello, {}!", self.get_field(PhantomData::)); + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + } + + #[test] + fn a_type_level_string_prints_its_text() { + let s = ::default(); + assert_eq!(s.to_string(), "hello"); + } + + #[test] + fn a_type_level_string_is_also_a_constant() { + use cgp::core::field::traits::StaticString; + + assert_eq!(::VALUE, "hello"); + } +} + +/// ## Under the hood +/// +/// The expansion the page shows, and the byte length a multi-byte string records. +pub mod under_the_hood { + use cgp::prelude::*; + + #[test] + fn the_expansion_is_a_length_and_a_character_list() { + let _: PhantomData = + PhantomData::>>>>; + let _: PhantomData = PhantomData::>; + let _: PhantomData = + PhantomData::>>>>>; + } +} From b6ba60947a202480ec455c9fa6bc6f189b8c76b3 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 27 Sep 2026 15:45:22 +0000 Subject: [PATCH 116/516] Check the Symbol! example's wiring and say how a sum value is built Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/sum.md | 8 +++++--- docs/reference/macros/symbol.md | 9 ++++++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 7568f74c..8e9474cf 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -43,9 +43,11 @@ Sum![u32, String, bool] Sum![] // the empty sum ``` -Each listed type is one possible variant, and a value of the sum type carries exactly one of them. There are no -options and no value-level counterpart. Unlike [`Product!`](./product.md), which has `product!`, a sum value is -constructed through the variant machinery rather than by a literal. +Each listed type is one possible variant, and a value of the sum type carries exactly one of them. +There are no options and no value-level counterpart: unlike [`Product!`](./product.md), which has +`product!`, a sum has no literal macro. A value is built with `Either`'s own constructors, as +`Either::Right(Either::Left(b))` for the second variant, or, for a derived enum, through +[`FromVariant`](../traits/variant/from_variant.md). ## Examples diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index a57fe95f..bbc5f1fd 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -71,7 +71,8 @@ is tagged `Symbol!("type")`. The macro itself performs no stripping. It takes th ## Examples -The everyday appearance is a wiring entry that points a getter at a particular field: +The everyday appearance is a wiring entry that points a getter at a particular field. `Person` is a +value context here, the type whose own field the getter reads: ```rust use cgp::prelude::*; @@ -91,6 +92,12 @@ delegate_components! { NameGetterComponent: UseField, } } + +check_components! { + Person { + NameGetterComponent, + } +} ``` `Symbol!("first_name")` tells [`UseField`](../providers/use_field.md) which field to read. This is the From 09231677d4b61a9c9a7d703f0d7b30615a5fd4f0 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 01:31:02 +0000 Subject: [PATCH 117/516] Revise the attribute reference pages and mirror every one Resync all of docs/reference/attributes/ against its internal documents and the cgp source, and give every page that shows code an example-code mirror with trybuild fixtures for its rejected snippets. Corrections found by compiling the pages: a provider of an #[extend]-ed component must import the supertrait itself; a #[prefix] that repeats the marker still resolves on a component without type parameters; the implicit HasField bounds are not always last in a where clause; a misplaced #[impl_generics] errors once rather than once per generated item; two methods reading one field at different types break the provider with E0284. The pages also gain forms they lacked (&mut str, raw identifiers, empty use_type groups, one-element tuple keys, the empty use_provider bound list) and the overview gains its provenance note. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/attributes/default_impl.md | 58 ++- docs/reference/attributes/derive_delegate.md | 31 +- docs/reference/attributes/extend.md | 50 +- docs/reference/attributes/extend_where.md | 20 +- docs/reference/attributes/impl_generics.md | 24 +- docs/reference/attributes/implicit.md | 71 ++- docs/reference/attributes/index.md | 28 +- docs/reference/attributes/prefix.md | 15 +- docs/reference/attributes/use_provider.md | 37 +- docs/reference/attributes/use_type.md | 91 +++- docs/reference/attributes/uses.md | 61 ++- docs/reference/macros/cgp_component.md | 5 +- example-code/README.md | 2 +- ...t_impl_common_mistakes_explicit_context.rs | 19 + ...pl_common_mistakes_explicit_context.stderr | 8 + ..._impl_common_mistakes_foreign_namespace.rs | 18 + ...l_common_mistakes_foreign_namespace.stderr | 9 + ...default_impl_common_mistakes_marker_key.rs | 22 + ...ult_impl_common_mistakes_marker_key.stderr | 8 + .../default_impl_common_mistakes_override.rs | 30 ++ ...fault_impl_common_mistakes_override.stderr | 19 + ...lt_impl_common_mistakes_table_parameter.rs | 20 + ...mpl_common_mistakes_table_parameter.stderr | 11 + ...egate_common_mistakes_missing_parameter.rs | 10 + ...e_common_mistakes_missing_parameter.stderr | 5 + ...delegate_common_mistakes_two_mechanisms.rs | 35 ++ ...gate_common_mistakes_two_mechanisms.stderr | 17 + ...ive_delegate_formal_grammar_empty_tuple.rs | 10 + ...delegate_formal_grammar_empty_tuple.stderr | 5 + .../extend_common_mistakes_on_cgp_impl.rs | 23 + .../extend_common_mistakes_on_cgp_impl.stderr | 29 ++ ...d_common_mistakes_provider_without_uses.rs | 22 + ...mmon_mistakes_provider_without_uses.stderr | 46 ++ .../extend_formal_grammar_relaxed_bound.rs | 10 + ...extend_formal_grammar_relaxed_bound.stderr | 15 + ...here_common_mistakes_caller_omits_bound.rs | 22 + ..._common_mistakes_caller_omits_bound.stderr | 35 ++ ...tend_where_common_mistakes_on_component.rs | 10 + ..._where_common_mistakes_on_component.stderr | 5 + ...tend_where_examples_unsatisfiable_bound.rs | 24 + ..._where_examples_unsatisfiable_bound.stderr | 37 ++ ...nerics_common_mistakes_on_cgp_component.rs | 14 + ...cs_common_mistakes_on_cgp_component.stderr | 13 + ...pl_generics_common_mistakes_on_cgp_impl.rs | 20 + ...enerics_common_mistakes_on_cgp_impl.stderr | 19 + ...nerics_rejected_unconstrained_parameter.rs | 4 +- .../implicit_common_mistakes_arguments.rs | 9 + .../implicit_common_mistakes_arguments.stderr | 5 + ...licit_common_mistakes_conflicting_types.rs | 21 + ...t_common_mistakes_conflicting_types.stderr | 37 ++ .../implicit_common_mistakes_destructuring.rs | 9 + ...licit_common_mistakes_destructuring.stderr | 5 + .../implicit_common_mistakes_mut_binding.rs | 10 + ...mplicit_common_mistakes_mut_binding.stderr | 5 + .../implicit_common_mistakes_mut_not_alone.rs | 9 + ...licit_common_mistakes_mut_not_alone.stderr | 5 + ...t_common_mistakes_mut_under_shared_self.rs | 9 + ...mmon_mistakes_mut_under_shared_self.stderr | 5 + .../implicit_common_mistakes_no_self.rs | 9 + .../implicit_common_mistakes_no_self.stderr | 7 + .../implicit_usage_outside_a_host.rs | 7 + .../implicit_usage_outside_a_host.stderr | 5 + .../prefix_common_mistakes_doubled_marker.rs | 37 ++ ...efix_common_mistakes_doubled_marker.stderr | 43 ++ .../prefix_common_mistakes_on_cgp_impl.rs | 17 + .../prefix_common_mistakes_on_cgp_impl.stderr | 5 + .../prefix_rejected_duplicate_namespace.rs | 2 +- ..._provider_common_mistakes_bare_provider.rs | 27 + ...vider_common_mistakes_bare_provider.stderr | 5 + ...use_provider_common_mistakes_comma_list.rs | 29 ++ ...provider_common_mistakes_comma_list.stderr | 5 + ...vider_formal_grammar_associated_binding.rs | 29 ++ ...r_formal_grammar_associated_binding.stderr | 5 + .../use_provider_usage_component_trait.rs | 27 + .../use_provider_usage_component_trait.stderr | 16 + ...use_type_common_mistakes_alias_as_trait.rs | 20 + ...type_common_mistakes_alias_as_trait.stderr | 5 + .../use_type_common_mistakes_circular_pins.rs | 20 + ..._type_common_mistakes_circular_pins.stderr | 7 + .../use_type_common_mistakes_cycle.rs | 20 + .../use_type_common_mistakes_cycle.stderr | 5 + .../use_type_common_mistakes_misspelled.rs | 20 + ...use_type_common_mistakes_misspelled.stderr | 15 + ...ype_common_mistakes_own_associated_type.rs | 20 + ...common_mistakes_own_associated_type.stderr | 14 + ...e_type_common_mistakes_pin_on_component.rs | 20 + ...pe_common_mistakes_pin_on_component.stderr | 5 + .../use_type_common_mistakes_self_pin.rs | 20 + .../use_type_common_mistakes_self_pin.stderr | 5 + ...use_type_common_mistakes_self_reference.rs | 20 + ...type_common_mistakes_self_reference.stderr | 5 + .../use_type_common_mistakes_shared_alias.rs | 20 + ...e_type_common_mistakes_shared_alias.stderr | 5 + .../uses_common_mistakes_component_trait.rs | 15 + ...ses_common_mistakes_component_trait.stderr | 11 + .../uses_common_mistakes_provider_trait.rs | 15 + ...uses_common_mistakes_provider_trait.stderr | 15 + .../uses_formal_grammar_relaxed_bound.rs | 10 + .../uses_formal_grammar_relaxed_bound.stderr | 7 + .../reference/attributes/default_impl.rs | 2 +- .../reference/attributes/derive_delegate.rs | 222 ++++++++ .../tests/reference/attributes/extend.rs | 187 +++++++ .../reference/attributes/extend_where.rs | 114 +++++ .../reference/attributes/impl_generics.rs | 23 + .../tests/reference/attributes/implicit.rs | 384 ++++++++++++++ .../tests/reference/attributes/mod.rs | 7 + .../tests/reference/attributes/prefix.rs | 60 +++ .../reference/attributes/use_provider.rs | 282 +++++++++++ .../tests/reference/attributes/use_type.rs | 477 ++++++++++++++++++ .../tests/reference/attributes/uses.rs | 243 +++++++++ 110 files changed, 3708 insertions(+), 103 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.stderr create mode 100644 example-code/tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.rs create mode 100644 example-code/tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.stderr create mode 100644 example-code/tests/reference/attributes/derive_delegate.rs create mode 100644 example-code/tests/reference/attributes/extend.rs create mode 100644 example-code/tests/reference/attributes/extend_where.rs create mode 100644 example-code/tests/reference/attributes/implicit.rs create mode 100644 example-code/tests/reference/attributes/use_provider.rs create mode 100644 example-code/tests/reference/attributes/use_type.rs create mode 100644 example-code/tests/reference/attributes/uses.rs diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index c9b36273..ffba56b2 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -130,6 +130,12 @@ delegate_components! { @test.ShowImplComponent.u64: ShowWithDisplay, // u64 has no registered default } } + +check_components! { + App { + ShowImplComponent: [String, u64], + } +} ``` **[Environmental context](/docs/reference/glossary#environmental-context), [parameter-targeted](/docs/reference/glossary#parameter-targeted-component)**: `App` carries the wiring and the shown value is a @@ -194,17 +200,17 @@ inherits the foreign one. The attribute emits a single impl of the named lookup trait, for the key type: ```rust -impl DefaultImpls1 for String { +impl<__Components__> DefaultImpls1 for String { type Delegate = ShowString; } ``` -The `Components` parameter is the table the lookup runs against, appended by the macro and left generic -so one registration serves every context. A path key emits the same impl for the path type, a +The `__Components__` parameter is the table the lookup runs against, appended by the macro and left +generic so one registration serves every context. A path key emits the same impl for the path type, a [`PathCons`](../types/path_cons.md) list that `cargo cgp expand` prints as `Path!(@app.GreeterComponent)`: ```rust -impl AppNamespace for Path!(@app.GreeterComponent) { +impl<__Components__> AppNamespace<__Components__> for Path!(@app.GreeterComponent) { type Delegate = GreetHello; } ``` @@ -260,11 +266,36 @@ exactly one such argument, and the attribute may be repeated. and the trait's positions follow. The parameter names on [`DefaultImpls1`](../traits/namespace/default_impls1.md) suggest otherwise. -**Do not write the table parameter.** The macro appends it, so supplying it yourself makes the path's -arity wrong. +**Do not write the table parameter.** The macro appends it, so supplying it yourself, as in +`#[default_impl(String in DefaultImpls1)]`, gives the trait one argument too many: + +```text +error[E0107]: trait takes 2 generic arguments but 3 generic arguments were supplied +``` + +**On a prefixed component it is confined to the namespace's crate**, by the orphan rule. A path key into +a namespace another crate owns, such as `#[default_impl(@app.GreeterComponent in DefaultNamespace)]` +outside `cgp`, fails because neither the trait nor the `PathCons` key is local: + +```text +error[E0210]: type parameter `__Components__` must be used as an argument to some local type (e.g., `MyStruct<__Components__>`) +``` + +Do not try to work around this. Register into a local namespace that inherits the foreign one, or put +the wiring in a namespace body you own. + +**A prefixed component is registered by its path, not its marker.** `#[prefix(@app in DefaultNamespace)]` +already makes `DefaultNamespace` answer `GreeterComponent` with a redirect, so a +`#[default_impl(GreeterComponent in DefaultNamespace)]` on its provider emits a second impl for the same +marker. A namespace that inherits `DefaultNamespace` covers the marker through its inheritance, so +`#[default_impl(GreeterComponent in AppNamespace)]` collides the same way: + +```text +error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` +``` -**On a prefixed component it is confined to the namespace's crate**, by the orphan rule. Do not try to -work around this. Put the wiring in the namespace body instead. +Write the path the redirect leads to, `#[default_impl(@app.GreeterComponent in AppNamespace)]`, as in +[Usage](#usage). **The lookup trait must be imported.** The emitted impl names it, so [`DefaultImpls1`](../traits/namespace/default_impls1.md) and [`DefaultImpls2`](../traits/namespace/default_impls2.md) need @@ -281,8 +312,11 @@ error[E0207]: the type parameter `T` is not constrained by the impl trait, self | ^ unconstrained type parameter ``` -This holds even when the provider struct is not generic. Write per-type defaults for concrete impls, -and wire a generic provider in a namespace body or directly on the context instead. +This holds even when the provider struct is not generic. It also rules out the explicit-context form +of a provider: `impl ShowImpl for Context` copies `Context` onto the registration and +fails with the same `E0207` for `Context`, while the concise `impl ShowImpl` registers cleanly. +Write per-type defaults on concise, concrete impls, and wire a generic provider in a namespace body or +directly on the context instead. **Two registrations for one key conflict.** Each emits an impl of the lookup trait for the same key, and the compiler rejects the second, with both carets on the keys inside the attributes: @@ -298,8 +332,8 @@ error[E0119]: conflicting implementations of trait `DefaultImpls1` through `RectangleArea` and -`CanCalculateArea` through `CircleArea`. +`CanCalculateArea` through `CircleArea`, which a check confirms for both shapes: + +```rust +check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } +} +``` + +`MyApp` is an environmental context and the component is parameter-targeted: the shape is the +parameter, and `MyApp` carries only the wiring. **Write the same result without the attribute instead.** Drop `#[derive_delegate]` from the component and let the context open it: @@ -201,7 +212,7 @@ where ``` Reading it back: `UseDelegate` is a provider for any `Shape` whose entry in `Components` -names something that is itself a provider for that `Shape`, and the method simply forwards. The +names something that is itself a provider for that `Shape`, and the method forwards. The `Components` type is the inner table, and [`DelegateComponent`](../traits/wiring/delegate_component.md) is the same trait ordinary wiring is made of, which is why you write the table with [`delegate_components!`](../macros/delegate_components.md) like any other. @@ -211,10 +222,16 @@ macro wraps the key list in parentheses**, so a multi-parameter key becomes a tu `UseDelegate<(Code, Input)>` declaration produces `DelegateComponent<(Code, Input), …>` with no other change. With one parameter, the parentheses in `DelegateComponent<(Shape), …>` are only grouping, and Rust reads the key as the bare `Shape`. That is why the table's entries are written as -`Rectangle: RectangleArea` rather than as one-element tuples. And the generics carry reserved names: +`Rectangle: RectangleArea` rather than as one-element tuples. A trailing comma is kept, so +`#[derive_delegate(UseDelegate<(Shape,)>)]` does key on the one-element tuple, and its table entries +are then written `(Rectangle,): RectangleArea`. And the generics carry reserved names: the table is `__Components__` and the looked-up entry `__Delegate__`, alongside the provider trait's own `__Context__`. +The dispatcher comes with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl +under the same `where` clause, like the component's other generated provider impls, so a dependency +missing inside the looked-up provider is still reported by name. + **A component's [supertraits](/docs/reference/glossary#supertrait) carry into the dispatcher.** The provider trait records each supertrait as a `Context:` predicate, and because the dispatcher reuses the provider trait's generics that predicate appears here too, so a component declaring an error type through @@ -243,8 +260,9 @@ Both parts are required. `Wrapper` is a bare identifier rather than a path, so a module path has to be imported first. `KeyParams` are **identifiers**, not types: each must name a generic parameter the trait declares, and a type expression such as `Vec` in that position does not parse. The parenthesized form must list at least one parameter (the parser rejects an empty `()` with *expect -non-empty tuple list of identifiers in use_delegate_spec*), and a single parameter written bare is keyed -the same way a one-element list would be. The attribute may be repeated, once per dispatcher. +non-empty tuple list of identifiers in use_delegate_spec*). A single parameter is keyed as the bare type +whether it is written `Shape` or `(Shape)`, and as a one-element tuple only when written with a trailing +comma, `(Shape,)`. The attribute may be repeated, once per dispatcher. ## Common Mistakes @@ -260,7 +278,8 @@ error[E0425]: cannot find type `Shape` in this scope ``` The usual cause is putting the attribute on a component that has no type parameter to dispatch on, where -there is nothing for it to do. +there is nothing for it to do. The macro does not check the name against the trait's parameters, so a +name that happens to resolve to a type in scope is accepted and used as a fixed key instead. **One component gets one dispatch mechanism.** Wiring the same component both with `open` and with a `UseDelegate` table is a [coherence](/docs/reference/glossary#coherence) conflict, because each produces its own table entry for that key. A diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index d0462855..82729c89 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -114,8 +114,19 @@ pub trait CanGreet { } ``` -`CanGreet` now means "can greet, and can tell you its name". Every provider may rely on the name being -available, and so may every caller. +`CanGreet` now means "can greet, and can tell you its name", and every caller may rely on the name being +available. A provider of the component must still import `HasName` itself, with `#[uses]`, because the +provider trait carries the supertrait as a `where` bound that each implementation has to satisfy: + +```rust +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} +``` ## When to use it @@ -165,7 +176,9 @@ where } ``` -Callers see the supertrait, and the predicate on the implementation lets the body call the methods. +Callers see the supertrait, and the predicate on the implementation lets the body call the methods. The +`#[extend]` entries share that one `Self:` predicate with any [`#[uses]`](uses.md) entries on the same +function, the `#[extend]` ones first. Compare [`#[uses]`](uses.md), which emits only the predicate and leaves the trait declaration bare. That single difference is the whole of the distinction. @@ -189,6 +202,22 @@ where } ``` +The provider trait carries the same requirement, but as a `where` bound rather than a supertrait, since its +context is a type parameter: + +```rust +pub trait Greeter<__Context__>: IsProviderFor +where + __Context__: HasName, +{ + fn greet(__context__: &__Context__); +} +``` + +Rust does not let an implementation assume a trait's `where` bound, so every provider impl must prove +`__Context__: HasName` itself. That is why the provider in [Examples](#examples) carries +`#[uses(HasName)]` even though the component already names the trait. + Here the result is identical to `pub trait CanGreet: HasName`, so on a component `#[extend]` generates only what the language can already express. It remains the preferred form because it presents the bound as an import rather than as inheritance, and because it keeps the `use`/`pub use` pairing with `#[uses]` @@ -204,7 +233,9 @@ ExtendArgs -> TypeParamBound ( `,` TypeParamBound )* `,`? ``` This is the same production [`#[uses]`](uses.md) accepts, the Rust grammar's own bound, so a lifetime, a -`?Sized`, or an associated-type equality parses as readily as a plain trait name. The list may be empty, +`?Sized`, or an associated-type equality parses as readily as a plain trait name. Rust still rejects a +relaxed bound on a trait, so `#[extend(?Sized)]` fails with +`relaxed bounds are not permitted in supertrait bounds`. The list may be empty, and the attribute may be repeated, with every occurrence's entries collected together. The two attributes differ in where the bounds land, not in the grammar. @@ -233,6 +264,17 @@ then fail with `E0599`, reporting that the method exists but its trait bounds we errors have the same cause, and one fix removes both: move the requirement to [`#[uses]`](uses.md), or onto the component's trait where supertraits belong. +**A provider of an extended component must import the supertrait again.** Leaving `#[uses(HasName)]` off +a `GreetHello` provider for the `CanGreet` component above fails at the provider, whether or not its body +calls `name()`: + +```text +error[E0277]: the trait bound `__Context__: HasName` is not satisfied +``` + +The component's `#[extend]` guarantees the trait to callers of `CanGreet`. It does not supply it to the +implementations that make `CanGreet` true, each of which states its own requirements. + **A supertrait cannot be narrowed later.** Because every implementor and every caller may now rely on it, removing an entry from `#[extend]` is a breaking change in a way removing one from `#[uses]` is not. This is the practical reason to default to `#[uses]`. diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 801cec1b..4b0ce65c 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -7,7 +7,7 @@ description: 'Add where predicates to a generated trait''s own definition rather # `#[extend_where]` -Add `where` predicates to a generated trait's own definition, not just to its implementation. +Add `where` predicates to a generated trait's own definition, not only to its implementation. ## Overview @@ -52,10 +52,11 @@ these are arbitrary predicates: a bound on any type in scope, including an assoc higher-ranked bound, or a lifetime bound. The macro adds each to the generated trait's `where` clause verbatim, and keeps it on the implementation as well. -**Only [`#[cgp_fn]`](../macros/cgp_fn.md) supports `#[extend_where]`.** On -[`#[cgp_impl]`](../macros/cgp_impl.md) or [`#[cgp_component]`](../macros/cgp_component.md) the `where` -clause you write is already part of the definition, so there is nothing to promote. Write the bound as -an ordinary `where` clause there. +**Only [`#[cgp_fn]`](../macros/cgp_fn.md) supports `#[extend_where]`**, because it is the one host that +keeps your `where` clause off the trait it generates. A `where` clause on a +[`#[cgp_component]`](../macros/cgp_component.md) trait is already part of the trait, so there is nothing +to promote, and [`#[cgp_impl]`](../macros/cgp_impl.md) generates no trait at all. Write the bound as an +ordinary `where` clause there. ## Examples @@ -161,10 +162,11 @@ The trait carries only the promoted predicate. The function's own bound is absen default this attribute overrides. The implementation carries all of them, and their **order is fixed**: the function's own `where` clause -first, then whatever the attributes contribute, then the -[`HasField`](../traits/field-access/has_field.md) bounds from [`#[implicit]`](implicit.md) arguments, -which are always appended last. That order helps when you read a long `where` clause in an expansion, -because it tells you where each bound came from. +first, then one `Self:` predicate for the [`#[extend]`](extend.md) and [`#[uses]`](uses.md) bounds, then +the `#[extend_where]` predicates, then the [`HasField`](../traits/field-access/has_field.md) bounds from +[`#[implicit]`](implicit.md) arguments, and last the bounds [`#[use_type]`](use_type.md) and +[`#[use_provider]`](use_provider.md) add. That order helps when you read a long `where` clause in an +expansion, because it tells you where each bound came from. The context parameter is literally `__Context__` in the emitted code and appears as `Self` inside the implementation. diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index f677679e..3ff7d28b 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -68,7 +68,9 @@ implementation determines one is the field bound an `#[implicit]` argument produ not appear in any implicit argument with `E0207`. See [Common Mistakes](#common-mistakes). The list accepts a lifetime or a const parameter as well as a type parameter, because the macro reads -ordinary generic parameters. Type parameters are the case the attribute exists for. +ordinary generic parameters. A const parameter is pinned the same way, by a field type that mentions it: +`#[impl_generics(const N: usize)]` with `#[implicit] data: &[u8; N]` infers `N` from an array field's +length. Type parameters are the case the attribute exists for. **Only [`#[cgp_fn]`](../macros/cgp_fn.md) reads `#[impl_generics]`.** A [`#[cgp_impl]`](../macros/cgp_impl.md) block's own generic list is already impl-only, so a provider @@ -107,7 +109,8 @@ pub fn greet_both(person: &Person, robot: &Robot) { `Person` and `Robot` both implement `Greet` through the one [blanket implementation](/docs/reference/glossary#blanket-implementation), without any wiring. For `Person` the compiler resolves `Name` to `String`, and for `Robot` to `u32`. Neither type -appears anywhere except in the field. +appears anywhere except in the field. Both are value contexts: the greeting reads the data each type +holds. A trait built on `greet` never learns that `Name` exists: @@ -182,8 +185,11 @@ then the `#[impl_generics]` parameters, so a function `fn scale` with `# emits `impl<__Context__, Scalar, Db>`. Rust requires lifetimes to lead a generic list, and the emitted list keeps that rule whatever order the parameters were declared in. -The `where` clause is ordered too: the function's own predicates first, then the bounds the -companion attributes contribute, then the `HasField` bounds from the implicit arguments, always last. +The `where` clause is ordered too: the function's own predicates first, then the +[`#[extend]`](./extend.md) and [`#[uses]`](./uses.md) bounds, then the +[`#[extend_where]`](./extend_where.md) predicates, then the `HasField` bounds from the implicit +arguments, and last any bounds [`#[use_type]`](./use_type.md) and +[`#[use_provider]`](./use_provider.md) add. The parameter's name is yours. The context, by contrast, is literally `__Context__` in the emitted code and appears as `Self` inside the implementation. @@ -288,11 +294,14 @@ impl Greeter { ```text error: cannot find attribute `impl_generics` in this scope + +error[E0425]: cannot find type `Name` in this scope ``` -On a [`#[cgp_component]`](../macros/cgp_component.md) the error repeats once per item the macro -generates. On a [`#[cgp_impl]`](../macros/cgp_impl.md) block, delete the attribute and declare the -parameter in the block's own generic list, which is already impl-only. +The second error follows from the first, because the parameter the attribute would have declared never +exists. On a [`#[cgp_component]`](../macros/cgp_component.md) the attribute is reported once, the same +way. On a [`#[cgp_impl]`](../macros/cgp_impl.md) block, delete the attribute and declare the parameter +in the block's own generic list, which is already impl-only. ## Related constructs @@ -314,7 +323,6 @@ The ideas behind it: - Parsing: [`types/attributes/function.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/function.rs) - Insertion into the implementation's generic list: [`types/cgp_fn/preprocessed.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_fn/preprocessed.rs) -- Expansion snapshot: [`generic_components/fn_impl_generics.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/tests/cgp-tests/tests/generic_components/fn_impl_generics.rs) --- diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index e104c214..1e315149 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -12,8 +12,8 @@ Source a function argument from a same-named field on the context. ## Overview `#[implicit]` lets a CGP construct read a field value from a generic **context** by naming the field -like an ordinary function argument. The context is the type the construct runs against, and the macro -hides the implicit argument from the public signature. +like an ordinary function argument. The context is the type the method runs on, which supplies the +values it needs as its fields, and the macro hides the implicit argument from the public signature. ```rust #[cgp_fn] @@ -50,7 +50,12 @@ fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { `#[implicit]` works only inside the macros that rewrite a function body into an implementation: [`#[cgp_fn]`](../macros/cgp_fn.md) and the methods of a [`#[cgp_impl]`](../macros/cgp_impl.md) block. It -is not a macro of its own, so it does nothing on an ordinary function. +is not a macro of its own. Anywhere else, on an ordinary function or on a method of a +[`#[cgp_component]`](../macros/cgp_component.md) trait, nothing removes it, and the compiler reports +``cannot find attribute `implicit` in this scope``. + +The argument's name is also the field's name. A raw identifier is read by its plain name, so +`#[implicit] r#type: &str` reads the field `type`. The macro constrains where the attribute may appear. The function must take `self` first, because the macro reads the field from `self`. The argument must be a bare identifier, not a destructuring or `mut` @@ -71,6 +76,7 @@ that type. The table below lists every case: | `Option<&T>` | `Option` | `.as_ref()` | | `Option<&str>` | `Option` | `.as_deref()` | | `&mut T` | `T` | mutably, no conversion | +| `&mut str` | `String` | `.as_mut_str()` | | `&mut [T]` | anything `AsMut<[T]>` | `.as_mut()` | | `Option<&mut T>` | `Option` | `.as_mut()` | | `Option<&mut str>` | `Option` | `.as_deref_mut()` | @@ -88,14 +94,17 @@ with one lifetime argument and one type argument. Anything else spelled `MRef` f and the macro clones it. This is the one place where a small change to the type changes the read without a warning. -The same rules govern the [getter traits](/docs/reference/glossary#getter-trait), so learning them once covers everywhere CGP reads a field. +The same conversions govern the [getter traits](/docs/reference/glossary#getter-trait), so learning them +once covers everywhere CGP reads a field. The one difference is where mutability comes from, which the +next section covers. ### Mutable arguments -An implicit argument is mutable when its type carries a `&mut`: the outer reference of a `&mut T` or a -`&mut [T]`, or the inner reference of an `Option<&mut T>` or an `Option<&mut str>`. A mutable argument -reads through [`HasFieldMut`](../traits/field-access/has_field_mut.md) and `get_field_mut` rather than through -[`HasField`](../traits/field-access/has_field.md) and `get_field`, so it borrows the field for writing. +An implicit argument is mutable when its type carries a `&mut`: the outer reference of a `&mut T`, a +`&mut str`, or a `&mut [T]`, or the inner reference of an `Option<&mut T>` or an `Option<&mut str>`. +A mutable argument reads through [`HasFieldMut`](../traits/field-access/has_field_mut.md) and +`get_field_mut` rather than through [`HasField`](../traits/field-access/has_field.md) and +`get_field`, so it borrows the field for writing. A mutable argument requires a `&mut self` receiver, because a function cannot borrow a field mutably through a shared `&self`. It must also be the only implicit argument on its function, because reading @@ -104,7 +113,8 @@ one field mutably borrows the whole context exclusively and cannot coexist with Mutability follows the *argument's* type rather than the receiver's. An argument carrying a `&mut` reads mutably, and every other argument, an `MRef` included, reads through a shared borrow. A `&mut self` function may therefore still take any number of immutable implicit arguments, as long as none of them is -mutable. +mutable. A getter trait works the other way, taking its mode from its receiver, so this is the one rule +that does not carry over from getters. To get a mutable local from a field the body only reads, take the argument immutably and clone it inside the body. `#[implicit]` rejects a `mut` binding on the argument itself, because a mutable argument means @@ -134,11 +144,23 @@ pub fn print_area(rect: &Rectangle) { ``` `Rectangle` derives [`HasField`](../derives/derive_has_field.md), and that derive is all it needs to -qualify. The program does not wire anything. +qualify. The program does not wire anything. `Rectangle` is a value context: the data the method +computes on is the context itself. + +A mutable argument modifies a field in place. It is the function's only implicit argument, under a +`&mut self` receiver: + +```rust +#[cgp_fn] +pub fn shout(&mut self, #[implicit] name: &mut str) { + name.make_ascii_uppercase(); +} +``` Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) provider the attribute behaves the same way and mixes -with the method's ordinary arguments. The macro removes the implicit arguments from the signature and -keeps `to` and `body`: +with the method's ordinary arguments. This fragment assumes an `EmailSender` component whose +`send_email(&self, to: &str, body: &str)` method is defined elsewhere. The macro removes the implicit +argument from the signature and keeps `to` and `body`: ```rust #[cgp_impl(new SendViaSmtp)] @@ -151,7 +173,8 @@ impl EmailSender { Callers still write `app.send_email(to, body)`. The provider's requirement from its context, an `smtp_server` field borrowed here as a `&str` from a `String`, never appears in the trait everyone else -calls. +calls. The context here is an environmental one, an `app` that carries the application's settings +rather than being the data a method acts on. ## When to use it @@ -234,7 +257,8 @@ Inside a [`#[cgp_impl]`](../macros/cgp_impl.md) block the rewrite is the same, e that provider's `where` clause. One addition shows only in a multi-method block: the macro collects the bounds across *every* method and de-duplicates them, so two methods each taking `#[implicit] name: &str` add one `HasField` bound rather than two. The macro still emits the -`let` bindings per method, because each body needs its own. +`let` bindings per method, because each body needs its own. Two reads of one field at *different* +field types are not merged, and the conflict they create is under [Common Mistakes](#common-mistakes). ## Common Mistakes @@ -288,6 +312,25 @@ error: a `&mut` implicit argument must be the only implicit argument, since its borrow of the context conflicts with reading any other field ``` +**Two methods of one block cannot read a field at two types.** Each method's argument adds its own +field bound, so a `u32` read in one method and a `u64` read in another require the same field to be +both. No context can satisfy that, and the provider fails where it is defined: + +```rust +#[cgp_impl(new ReadCount)] +impl Counter { + fn small(&self, #[implicit] count: u32) -> u32 { count } + fn big(&self, #[implicit] count: u64) -> u64 { count } +} +``` + +```text +error[E0284]: type annotations needed: cannot satisfy `<__Context__ as HasField>>>::Value == u32` +``` + +Reads that differ only in how they borrow do not conflict. A `&str` in one method and a `String` in +another both require a `String` field, so they agree. + ## Related constructs - [`#[cgp_fn]`](../macros/cgp_fn.md) — the usual host, turning a function into a trait. diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index 2d62ed89..7a267ec6 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -10,8 +10,10 @@ description: 'The modifier attributes that refine what a CGP macro generates: de An attribute here is a modifier, not a macro of its own. Each one is an option that a host macro reads to refine the trait or implementation it generates. The hosts are [`#[cgp_impl]`](../macros/cgp_impl.md), [`#[cgp_fn]`](../macros/cgp_fn.md), and -[`#[cgp_component]`](../macros/cgp_component.md). This page groups every attribute in this section by -the job it does, in roughly the order most CGP code uses them. +[`#[cgp_component]`](../macros/cgp_component.md), together with the macros built on +`#[cgp_component]`. Each attribute works only on the hosts its page names. Anywhere else nothing reads +it, and the compiler reports it as an attribute it cannot find. This page groups every attribute in +this section by the job it does, in roughly the order most CGP code uses them. If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here. This page is the fuller guide, for a reader who already knows the essentials. @@ -19,16 +21,16 @@ is the fuller guide, for a reader who already knows the essentials. ## Reading a value from the context [`#[implicit]`](./implicit.md) marks a function argument that the macro reads from a same-named field -on the context rather than from the caller. The context is the type the method runs on. A -provider that needs a value then reads like an ordinary function that takes it. Almost every provider -uses the attribute, and it is usually the first piece of CGP anyone writes. +on the context rather than from the caller. The context is the type the method runs on, which supplies +the values it needs as its fields. A provider that needs a value then reads like an ordinary function +that takes it. It is the default way to read a context's field, and usually the first piece of CGP +anyone writes. ## Importing a dependency These attributes declare what an implementation depends on, and each reads like an import. Most dependencies belong on the implementation, where callers never see them. `#[extend]` and -`#[extend_where]` put a dependency on the generated trait instead, for the case where every caller must -rely on it. +`#[extend_where]` put a requirement on the generated trait instead, where every caller meets it. [`#[uses]`](./uses.md) imports a consumer trait, or an ordinary Rust trait, that the context must satisfy. This is the common case. [`#[use_type]`](./use_type.md) imports an [abstract type](/docs/reference/glossary#abstract-type) that another @@ -37,8 +39,10 @@ qualified path. [`#[use_provider]`](./use_provider.md) imports a provider trait provider must satisfy, which is the dependency a [higher-order provider](/docs/reference/glossary#higher-order-provider) declares. [`#[extend]`](./extend.md) and [`#[extend_where]`](./extend_where.md) put the requirement on the generated -trait rather than on the implementation, so every caller inherits it. `#[extend]` adds a [supertrait](/docs/reference/glossary#supertrait), and -`#[extend_where]` adds a `where` predicate that a supertrait cannot express. +trait rather than on the implementation. `#[extend]` adds a [supertrait](/docs/reference/glossary#supertrait), +which every caller can rely on. `#[extend_where]` adds a `where` predicate that a supertrait cannot +express, which callers do not inherit: each caller must prove it, and the compiler checks it wherever +the trait is named. ## Naming a type the body needs @@ -63,3 +67,9 @@ the default once per-type defaults accumulate. generic over a type parameter. The `open` statement of [`delegate_components!`](../macros/delegate_components.md) replaced it for new code. The page remains because you will meet the form in existing wiring and in CGP's own error and handler components. + +--- + +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index 678a4f62..c8b412b3 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -282,9 +282,13 @@ namespaces. ## Common Mistakes **The macro appends the marker, so do not write it.** `#[prefix(@app.GreeterComponent in Ns)]` -registers the component at `@app.GreeterComponent.GreeterComponent`. It compiles, and a context that -binds `@app.GreeterComponent` then finds its entry never consulted, because the route and the binding -name different paths. Write the prefix alone. +routes the component to `@app.GreeterComponent.GreeterComponent`. On a component without type +parameters the mistake stays hidden, because a context's `@app.GreeterComponent` entry also matches +every longer path beneath it and so catches the doubled route. On a component with type parameters it +surfaces. With `#[prefix(@app.ShowImplComponent in DefaultNamespace)]` on a `CanShow`, the entry +`@app.ShowImplComponent.String` does not match the route +`@app.ShowImplComponent.ShowImplComponent.String`, and the check reports the unbound path described +next. Write the prefix alone. **Registering routes a component but does not bind a provider.** A prefixed component compiles even when nothing binds its path, and so does a context that joins the namespace. Only a @@ -341,7 +345,9 @@ pub trait CanGreet { error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` ``` -A component has one route per namespace. To reach it under two paths, define two namespaces. +Both carets land on the `#[cgp_component]` attribute rather than on the two `#[prefix]` lines, so the +message does not say which registration is the duplicate. A component has one route per namespace. To +reach it under two paths, define two namespaces. **`open` does not reach a prefixed component in a joined namespace.** `open` roots the route at the bare marker, while the prefix routes under the path, so the per-type entries `open` expects are never @@ -408,7 +414,6 @@ The ideas behind it: - Collection on the component: [`types/attributes/cgp_component_attributes.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/attributes/cgp_component_attributes.rs) - Emission, after the standard provider impls: [`types/cgp_component/evaluated/item.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_component/evaluated/item.rs) - A library use: [`has_error_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/traits/has_error_type.rs) -- Expansion snapshots: [`namespaces/`](https://github.com/contextgeneric/cgp/tree/main/crates/tests/cgp-tests/tests/namespaces/) --- diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index ab40a2de..7e198b58 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -48,7 +48,8 @@ a different choice and usually not what a [higher-order provider](/docs/referenc `InnerCalculator` is the provider, usually a generic parameter of the implementation, and `AreaCalculator` is the provider trait it must satisfy. The trait may carry further arguments of its own, -and the macro preserves those in order. +lifetimes included, as in `#[use_provider(Inner: Namer<'a>)]`, and the macro keeps them after the +context argument it inserts. The form to use depends on whether one provider must satisfy several traits, or several providers must each satisfy one. @@ -72,7 +73,9 @@ from [`#[uses]`](uses.md) and [`#[use_type]`](use_type.md), where commas are the several entries, so remember `#[use_provider]` as the exception. `#[use_provider]` is accepted on [`#[cgp_impl]`](../macros/cgp_impl.md) and on -[`#[cgp_fn]`](../macros/cgp_fn.md), and it works the same way on both. +[`#[cgp_fn]`](../macros/cgp_fn.md), and it works the same way on both. On any other host, such as a +[`#[cgp_component]`](../macros/cgp_component.md) trait, nothing reads the attribute, and the compiler +reports ``cannot find attribute `use_provider` in this scope``. ## Examples @@ -110,7 +113,8 @@ impl AreaCalculator { ``` A context then composes the two when it wires the component, and `ScaledArea` computes a -rectangle's area and scales it: +rectangle's area and scales it. `Rectangle` is a value context, the shape being measured, and it carries +the fields both layers read: ```rust #[derive(HasField)] @@ -125,6 +129,12 @@ delegate_components! { AreaCalculatorComponent: ScaledArea, } } + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} ``` Because the wrapper never names a particular inner implementation, the same `ScaledArea` composes over any @@ -211,6 +221,13 @@ The `Self` you wrote in the attribute is the context, so it appears as `__Contex name the surrounding macro inserted. Writing `#[use_provider(InnerCalculator: AreaCalculator)]` is therefore exactly equivalent to writing `where InnerCalculator: AreaCalculator` by hand. +The bound also reaches the provider's [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl, and +because it names the component's own provider trait, that impl gains a matching +`InnerCalculator: IsProviderFor` bound as well. That is how a +dependency missing inside the inner provider surfaces through the wrapper when the context is checked. +A component that carries a lifetime does not get this counterpart, a known defect described under +[`#[cgp_provider]`](../macros/cgp_provider.md#common-mistakes). + On a [`#[cgp_fn]`](../macros/cgp_fn.md) the same insertion happens. Because that macro's implementation is written *for* the context, the bound reads with `Self` directly: @@ -234,20 +251,22 @@ The attribute argument is one provider and the provider traits it must satisfy, [notation](https://doc.rust-lang.org/reference/notation.html): ```ebnf -UseProviderArgs -> ProviderType `:` ProviderBound ( `+` ProviderBound )* +UseProviderArgs -> ProviderType `:` ( ProviderBound ( `+` ProviderBound )* `+`? )? ProviderType -> Type ProviderBound -> TypePath GenericArgs? ``` -Both parts are required. `ProviderType` names the generic parameter the inner provider occupies, and each -`ProviderBound` is the provider trait to require of it, written *without* its leading context argument, -which the attribute inserts. +The provider and the colon are required. `ProviderType` names the generic parameter the inner provider +occupies, and each `ProviderBound` is the provider trait to require of it, written *without* its leading +context argument, which the attribute inserts. The bound list may end with a `+`, and it may even be +empty: `#[use_provider(Inner:)]` parses and adds a `where Inner:` predicate that requires nothing. Those productions carry the restrictions that account for every parse failure this attribute produces. **`ProviderBound` is a path with plain generic arguments**, not a full `TypeParamBound`, so a turbofish -or an associated-type binding in that position does not parse. A bound of that shape belongs in the -block's own `where` clause. And **the argument holds exactly one provider**, because the `+`-separated +or an associated-type binding in that position does not parse: `AreaCalculator` fails with +``associated bindings (`Name = ...`) are not allowed in type arguments``. A bound of that shape belongs in +the block's own `where` clause. And **the argument holds exactly one provider**, because the `+`-separated bound list runs to the end of the attribute, so a comma after the first pair lands where a `+` was expected. That makes this attribute the one exception to the comma-separated convention its siblings follow: bind several inner providers by stacking one attribute each. See diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 6394b55f..fbf14622 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -69,6 +69,16 @@ a local alias: #[use_type(HasFooType.{Foo, Bar as Baz})] ``` +Renaming is also how one associated type is imported from two instantiations of a generic trait, since +the two imports would otherwise share a name: + +```rust +#[use_type(HasFooType.{Foo as FooX}, HasFooType.{Foo as FooY})] +``` + +An empty group, as in `#[use_type(HasFooType.{})]`, parses too. It imports no name but still adds the +trait's bound. + Stacking several `#[use_type]` attributes behaves identically, because the macro collects every attribute's entries into one list before it resolves any of them. So an alias declared in one is available to another regardless of which comes first. Use a second attribute only when there is a @@ -83,14 +93,23 @@ the error type is `anyhow::Error`": #[use_type(HasErrorType.{Error = anyhow::Error})] ``` -That emits `Self: HasErrorType` in place of the plain bound. The macro substitutes -the right-hand side too, so it may name another import. One import can therefore tie two abstract types -together: +That emits `Self: HasErrorType` in place of the plain bound. On a generic trait the +binding joins the trait's own arguments, so `#[use_type(HasFooType.{Foo = u32})]` emits +`Self: HasFooType`. The binding always names the associated type's own name, even when the +import renames it with `as`. + +The macro substitutes the right-hand side too, so it may name another import, alone or inside a larger +type. One import can therefore tie two abstract types together: ```rust #[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})] ``` +and `#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits +`Self: HasTransactionType::Db>>`. The one name the macro leaves +alone on the right-hand side is the pinned alias itself, so a pin such as `{Foo = Foo}` fails with +``cannot find type `Foo` in this scope`` rather than becoming a bound that says nothing. + The pin is an implementation-side constraint, so the macro **rejects it on [`#[cgp_component]`](../macros/cgp_component.md)** and on the macros built on it, whose trait definitions have nowhere to put it. @@ -150,7 +169,8 @@ The component gains `HasScalarType` as a [supertrait](/docs/reference/glossary#s `Scalar` in both becomes the same qualified projection, so the fields the provider reads and the value it returns are guaranteed to agree on whatever scalar the context chose. -A context supplies the concrete type by wiring, and nothing above changes: +A context supplies the concrete type by wiring, and nothing above changes. `Rectangle` is a value context, +the shape whose area is being computed: ```rust #[derive(HasField)] @@ -165,6 +185,12 @@ delegate_components! { AreaCalculatorComponent: RectangleArea, } } + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} ``` The most common use of all is an @@ -264,11 +290,13 @@ where An equality pin is the exception: it stays on the implementation, and the macro never adds it to the trait. -**What substitution touches.** The rewrite matches a single-segment type path with no arguments whose -identifier is an imported name or alias, anywhere it appears: a return type, an argument, a `where` -predicate, a local binding. It also reaches an alias used to *qualify* a path, so `Transaction::begin()` -becomes `<::Transaction>::begin()`, because `::Assoc::method` is -not valid syntax. +**What substitution touches.** The rewrite matches a single-segment type path with no arguments +whose identifier is an imported name or alias, anywhere it appears: a return type, an argument, a +`where` predicate, a local binding, and the provider trait's arguments in a `#[cgp_impl]` header, so +`impl ErrorParser` under `#[use_type(HasErrorType.Error)]` implements the provider trait for +the context's error type. It also reaches an alias used to *qualify* a path, so +`Transaction::begin()` becomes `<::Transaction>::begin()`, because +`::Assoc::method` is not valid syntax. The rewrite leaves one position alone: a **bare alias in expression position**, which names a value, something an abstract type can never be. So an alias sharing its name with a unit struct still constructs @@ -300,7 +328,7 @@ ContextPath -> TypePath TraitPath -> TypePath TypeItems -> UseTypeIdent - | `{` UseTypeIdent ( `,` UseTypeIdent )* `,`? `}` + | `{` ( UseTypeIdent ( `,` UseTypeIdent )* `,`? )? `}` UseTypeIdent -> IDENTIFIER ( `as` IDENTIFIER )? ( `=` Type )? ``` @@ -310,7 +338,8 @@ arguments. Their `::` segments belong to the path, while the `.` after the trait associated-type list. An omitted `in ContextPath` defaults the target to `Self`. In each `UseTypeIdent` the leading `IDENTIFIER` is the associated type's own name, `as` gives it a local alias to write in signatures, and `= Type` pins it with an equality bound. The pin is accepted on `#[cgp_fn]` and -`#[cgp_impl]` and rejected on `#[cgp_component]` and the macros built on it. +`#[cgp_impl]` and rejected on `#[cgp_component]` and the macros built on it. An empty braced list +imports no name and adds only the trait's bound. ## Common Mistakes @@ -360,9 +389,47 @@ Pin the type on the provider with [`#[cgp_impl]`](../macros/cgp_impl.md) instead [`#[cgp_fn]`](../macros/cgp_fn.md). **A construct's own associated type must stay qualified.** Writing a local `type Output` as a bare -`Output` leaves an identifier that the substitution has no entry for, so the compiler cannot resolve it. +`Output` leaves an identifier that the substitution has no entry for, so the compiler cannot resolve it: + +```rust +#[cgp_component(Maker)] +pub trait CanMake { + type Output; + fn make(&self) -> Output; +} +``` + +```text +error[E0425]: cannot find type `Output` in this scope +``` + Write `Self::Output`, and do not list it in a `#[use_type]` attribute. +**A misspelled associated type is reported where you wrote it.** The macro keeps your identifier's +position when it substitutes, so `#[use_type(HasErrorType.Eror)]` fails with +``error[E0576]: cannot find associated type `Eror` in trait `HasErrorType` `` pointing at each use of +`Eror` in the signature. + +**An alias cannot stand for the trait an import comes from.** The macro grounds an import's `in` clause +and trait arguments, but not the trait's own name, because that position must name a trait and an alias +names a type. So `#[use_type(HasFooType.Foo, Foo.Bar)]` fails with +``error[E0405]: cannot find trait `Foo` in this scope``. + +**Two pins that name each other overflow the compiler.** This import grounds without trouble, since it +asserts only that the two types are equal: + +```rust +#[use_type(HasFooType.{Foo = Bar}, HasBarType.{Bar = Foo})] +``` + +The macro therefore emits both bounds, and the trait solver cannot discharge them: + +```text +error[E0275]: overflow evaluating the requirement `<__Context__ as HasFooType>::Foo == _` +``` + +Pin one of the two types to a concrete type, or pin only one of them to the other. + ## Related constructs - [`#[cgp_type]`](../macros/cgp_type.md) — declares the abstract-type component this imports from. diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index a33b0dc0..e2be9d47 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -53,8 +53,10 @@ single list reads as a single set of requirements. You may also split entries ac attribute only when there is a reason. `#[uses(...)]` is accepted on [`#[cgp_fn]`](../macros/cgp_fn.md) and on -[`#[cgp_impl]`](../macros/cgp_impl.md). In both, it imports into the item being defined, and it does not -matter how the imported trait was itself produced. +[`#[cgp_impl]`](../macros/cgp_impl.md), the two hosts that generate an implementation to carry the +bound. In both, it imports into the item being defined, and it does not matter how the imported trait +was itself produced. It is not accepted on [`#[cgp_component]`](../macros/cgp_component.md), where a +trait dependency is a supertrait written with [`#[extend]`](extend.md). ### Bounds beyond the simple form @@ -111,7 +113,28 @@ impl AreaCalculator { ``` This provider is a short adapter: it satisfies the `AreaCalculator` component by calling whatever -`rectangle_area` computes. Any context with the fields that trait needs can wire it. +`rectangle_area` computes. Any context with the fields that trait needs can wire it, as a `Rectangle` +does here. `Rectangle` is a value context, the shape whose area is being computed: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleAreaCalculator, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} +``` ## When to use it @@ -183,12 +206,14 @@ The attribute argument is a comma-separated list of bounds, in the Rust Referenc UsesArgs -> TypeParamBound ( `,` TypeParamBound )* `,`? ``` -`TypeParamBound` is the Rust grammar's own bound production, which is wider than the plain `Trait` -this attribute is normally written with: a lifetime, a `?Sized`, and an associated-type equality such as -`HasErrorType` all parse. The list may be empty, and the attribute may be repeated, -with entries from every occurrence collected into one `Self:` predicate. The commas separate *bounds*, so -`#[uses(A, B)]` and `#[uses(A)] #[uses(B)]` are the same thing, and the single-attribute form is the one -to write. +`TypeParamBound` is the Rust grammar's own bound production, which is wider than the plain +`Trait` this attribute is normally written with: a lifetime, a `?Sized`, and an +associated-type equality such as `HasErrorType` all parse. Rust still rejects some +of them as a bound on `Self`, so `#[uses(?Sized)]` fails with +`this relaxed bound is not permitted here`. The list may be empty, and the attribute may be +repeated, with entries from every occurrence collected into one `Self:` predicate. The commas +separate *bounds*, so `#[uses(A, B)]` and `#[uses(A)] #[uses(B)]` are the same thing, and the +single-attribute form is the one to write. ## Common Mistakes @@ -218,6 +243,24 @@ The `__Context__` in that note points to the mistake. Depend on the **consumer** case. Use [`#[use_provider]`](use_provider.md) when you mean a named implementation, and it will supply the missing argument. +**`#[uses]` fails on a component trait.** `#[cgp_component]` does not read the attribute, so it +stays on the trait and the compiler cannot find it: + +```rust +#[cgp_component(Shouter)] +#[uses(CanCalculateArea)] +pub trait CanShout { + fn shout(&self) -> String; +} +``` + +```text +error: cannot find attribute `uses` in this scope +``` + +A trait that every implementation of the component needs is a supertrait. Write it with +[`#[extend(CanCalculateArea)]`](extend.md), or put `#[uses]` on each provider that needs it. + ## Related constructs - [`#[cgp_fn]`](../macros/cgp_fn.md) and [`#[cgp_impl]`](../macros/cgp_impl.md) — the two hosts. diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index ac0d1608..8b444045 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -322,7 +322,10 @@ where The macro adds that predicate to every emitted item that mentions the context. The two blanket impls below and the `UseContext` and `RedirectLookup` impls further down each gain their own -`Context: HasName`, because none of them can apply where the supertrait does not hold. +`Context: HasName`, because none of them can apply where the supertrait does not hold. A provider you +write must satisfy the predicate too, since Rust does not let an implementation assume a trait's `where` +bound, so a `#[cgp_impl]` provider for this component imports it with +[`#[uses(HasName)]`](../attributes/uses.md) whether or not its body calls `name()`. **A method may carry a default body, and the body moves to the provider trait.** The `Self`-to-`Context` move reaches the body as well, and that move lets a provider inherit a default. diff --git a/example-code/README.md b/example-code/README.md index abeaa861..96759a99 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -36,7 +36,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, every `macros/` page that shows code, the `attributes/` pages `default_impl.md`, `impl_generics.md`, and `prefix.md`, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, every `macros/` page and every `attributes/` page that shows code, all of `derives/`, the `traits/` pages that show checkable code, most of `providers/` (the singletons, all of `error/`, `handler/`, and `monad/`, and the matcher-side of `dispatch/`), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.rs b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.rs new file mode 100644 index 00000000..23a8a2ce --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.rs @@ -0,0 +1,19 @@ +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; + +#[cgp_component(ShowImpl)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +// error[E0207]: the type parameter `Context` is not constrained by the impl trait, self type, or +// predicates +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl for Context { + fn show(&self, value: &String) -> String { + value.clone() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.stderr new file mode 100644 index 00000000..8118491b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.stderr @@ -0,0 +1,8 @@ +error[E0207]: the type parameter `Context` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/attributes/default_impl_common_mistakes_explicit_context.rs:13:6 + | +11 | #[cgp_impl(new ShowString)] + | --------------------------- help: remove the unused type parameter `Context` +12 | #[default_impl(String in DefaultImpls1)] +13 | impl ShowImpl for Context { + | ^^^^^^^ unconstrained type parameter diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.rs b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.rs new file mode 100644 index 00000000..c425b2d2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.rs @@ -0,0 +1,18 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +#[prefix(@app in DefaultNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +// error[E0210]: type parameter `__Components__` must be used as an argument to some local type +#[cgp_impl(new GreetHello)] +#[default_impl(@app.GreeterComponent in DefaultNamespace)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.stderr new file mode 100644 index 00000000..507d6f1c --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.stderr @@ -0,0 +1,9 @@ +error[E0210]: type parameter `__Components__` must be used as an argument to some local type (e.g., `MyStruct<__Components__>`) + --> tests/compile_fail/reference/attributes/default_impl_common_mistakes_foreign_namespace.rs:10:1 + | +10 | #[cgp_impl(new GreetHello)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ uncovered type parameter + | + = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local + = note: only traits defined in the current crate can be implemented for a type parameter + = note: this error originates in the attribute macro `cgp_impl` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.rs b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.rs new file mode 100644 index 00000000..bce12663 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.rs @@ -0,0 +1,22 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +#[prefix(@app in DefaultNamespace)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +cgp_namespace! { + new AppNamespace: DefaultNamespace {} +} + +// error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` +#[cgp_impl(new GreetHello)] +#[default_impl(GreeterComponent in AppNamespace)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.stderr new file mode 100644 index 00000000..1acb8b13 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.stderr @@ -0,0 +1,8 @@ +error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` + --> tests/compile_fail/reference/attributes/default_impl_common_mistakes_marker_key.rs:15:16 + | +10 | new AppNamespace: DefaultNamespace {} + | ---------------- first implementation here +... +15 | #[default_impl(GreeterComponent in AppNamespace)] + | ^^^^^^^^^^^^^^^^ conflicting implementation for `GreeterComponent` diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.rs b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.rs new file mode 100644 index 00000000..196d9575 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.rs @@ -0,0 +1,30 @@ +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; + +#[cgp_component(ShowImpl)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} + +pub struct App; + +// error[E0119]: conflicting implementations of trait `DelegateComponent<…>` for type `App` +delegate_components! { + App { + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + @test.ShowImplComponent.String: ShowString, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.stderr new file mode 100644 index 00000000..37487c8b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.stderr @@ -0,0 +1,19 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor>>>>, PathCons>>, _, _>` for type `App` + --> tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.rs:26:33 + | +23 | @test.ShowImplComponent.T: Provider, + | - first implementation here +... +26 | @test.ShowImplComponent.String: ShowString, + | ^^^^^^ conflicting implementation for `App` + | + = note: downstream crates may implement trait `cgp::prelude::IsProviderFor>>>>, cgp::prelude::PathCons>>, _, _>` for type `ShowString` + +error[E0119]: conflicting implementations of trait `DelegateComponent>>>>, PathCons>>>` for type `App` + --> tests/compile_fail/reference/attributes/default_impl_common_mistakes_override.rs:26:33 + | +23 | @test.ShowImplComponent.T: Provider, + | - first implementation here +... +26 | @test.ShowImplComponent.String: ShowString, + | ^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.rs b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.rs new file mode 100644 index 00000000..6ab76b55 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.rs @@ -0,0 +1,20 @@ +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; + +#[cgp_component(ShowImpl)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +pub struct App; + +// error[E0107]: trait takes 2 generic arguments but 3 generic arguments were supplied +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr new file mode 100644 index 00000000..f6f65d9b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr @@ -0,0 +1,11 @@ +error[E0107]: trait takes 2 generic arguments but 3 generic arguments were supplied + --> tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.rs:13:26 + | +13 | #[default_impl(String in DefaultImpls1)] + | ^^^^^^^^^^^^^ expected 2 generic arguments + | +note: trait defined here, with 2 generic parameters: `T`, `Components` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-component/src/namespaces.rs:5:11 + | + 5 | pub trait DefaultImpls1 { + | ^^^^^^^^^^^^^ - ---------- diff --git a/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.rs b/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.rs new file mode 100644 index 00000000..21541a0e --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error[E0425]: cannot find type `Shape` in this scope +#[cgp_component(Greeter)] +#[derive_delegate(UseDelegate)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.stderr b/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.stderr new file mode 100644 index 00000000..055eed30 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.stderr @@ -0,0 +1,5 @@ +error[E0425]: cannot find type `Shape` in this scope + --> tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_missing_parameter.rs:5:31 + | +5 | #[derive_delegate(UseDelegate)] + | ^^^^^ not found in this scope diff --git a/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.rs b/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.rs new file mode 100644 index 00000000..69540e37 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.rs @@ -0,0 +1,35 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +#[derive_delegate(UseDelegate)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle; + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, _shape: &Rectangle) -> f64 { + 1.0 + } +} + +pub struct App; + +// error[E0119]: conflicting implementations of trait `DelegateComponent` +// for type `App` +delegate_components! { + App { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + + AreaCalculatorComponent: + UseDelegate, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.stderr b/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.stderr new file mode 100644 index 00000000..bbbf491d --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.stderr @@ -0,0 +1,17 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` + --> tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.rs:28:9 + | +24 | open AreaCalculatorComponent; + | ----------------------- first implementation here +... +28 | AreaCalculatorComponent: + | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` + --> tests/compile_fail/reference/attributes/derive_delegate_common_mistakes_two_mechanisms.rs:28:9 + | +24 | open AreaCalculatorComponent; + | ----------------------- first implementation here +... +28 | AreaCalculatorComponent: + | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.rs b/example-code/tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.rs new file mode 100644 index 00000000..21e13290 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: expect non-empty tuple list of identifiers in use_delegate_spec +#[cgp_component(AreaCalculator)] +#[derive_delegate(UseDelegate<()>)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.stderr b/example-code/tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.stderr new file mode 100644 index 00000000..9fbc498d --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.stderr @@ -0,0 +1,5 @@ +error: expect non-empty tuple list of identifiers in use_delegate_spec + --> tests/compile_fail/reference/attributes/derive_delegate_formal_grammar_empty_tuple.rs:5:32 + | +5 | #[derive_delegate(UseDelegate<()>)] + | ^ diff --git a/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.rs b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.rs new file mode 100644 index 00000000..8a84d8cb --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.rs @@ -0,0 +1,23 @@ +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self); +} + +// error: cannot find attribute `extend` in this scope +// error[E0599]: the method `name` exists for reference `&__Context__`, but its trait bounds were not satisfied +#[cgp_impl(new GreetHello)] +#[extend(HasName)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.stderr b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.stderr new file mode 100644 index 00000000..390be45b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.stderr @@ -0,0 +1,29 @@ +error: cannot find attribute `extend` in this scope + --> tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.rs:16:3 + | +16 | #[extend(HasName)] + | ^^^^^^ + +error[E0599]: the method `name` exists for reference `&__Context__`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.rs:19:37 + | +19 | println!("Hello, {}!", self.name()); + | ^^^^ method cannot be called on `&__Context__` due to unsatisfied trait bounds + | +note: the following trait bounds were not satisfied: + `&__Context__: cgp::prelude::HasField>>>>>` + `<&__Context__ as cgp::prelude::HasField>>>>>>::Value = String` + `<__Context__ as cgp::prelude::HasField>>>>>>::Value = String` + `__Context__: cgp::prelude::HasField>>>>>` + --> tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.rs:3:1 + | + 3 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ + 4 | pub trait HasName { + | ^^^^^^^ + = help: items from traits can only be used if the type parameter is bounded by the trait + = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) +help: the following trait defines an item `name`, perhaps you need to restrict type parameter `__Context__` with it: + | +15 | #[cgp_impl(new GreetHello)]: HasName + | +++++++++ diff --git a/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs new file mode 100644 index 00000000..7fb6ff13 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs @@ -0,0 +1,22 @@ +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_component(Greeter)] +#[extend(HasName)] +pub trait CanGreet { + fn greet(&self); +} + +// error[E0277]: the trait bound `__Context__: HasName` is not satisfied +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr new file mode 100644 index 00000000..269e0615 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr @@ -0,0 +1,46 @@ +error[E0277]: the trait bound `__Context__: HasName` is not satisfied + --> tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs:15:1 + | +15 | #[cgp_impl(new GreetHello)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `cgp::prelude::HasField>>>>>` is not implemented for `__Context__` +note: required for `__Context__` to implement `HasName` + --> tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs:3:1 + | + 3 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ + 4 | pub trait HasName { + | ^^^^^^^ +note: required by a bound in `Greeter` + --> tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs:9:10 + | + 8 | #[cgp_component(Greeter)] + | ------- required by a bound in this trait + 9 | #[extend(HasName)] + | ^^^^^^^ required by this bound in `Greeter` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0599]: the method `name` exists for reference `&__Context__`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs:18:37 + | +18 | println!("Hello, {}!", self.name()); + | ^^^^ method cannot be called on `&__Context__` due to unsatisfied trait bounds + | +note: the following trait bounds were not satisfied: + `&__Context__: cgp::prelude::HasField>>>>>` + `<&__Context__ as cgp::prelude::HasField>>>>>>::Value = String` + `<__Context__ as cgp::prelude::HasField>>>>>>::Value = String` + `__Context__: cgp::prelude::HasField>>>>>` + --> tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs:3:1 + | + 3 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ + 4 | pub trait HasName { + | ^^^^^^^ + = help: items from traits can only be used if the type parameter is bounded by the trait + = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) +help: the following trait defines an item `name`, perhaps you need to restrict type parameter `__Context__` with it: + | +15 | #[cgp_impl(new GreetHello)]: HasName + | +++++++++ diff --git a/example-code/tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.rs b/example-code/tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.rs new file mode 100644 index 00000000..12583dbc --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: relaxed bounds are not permitted in supertrait bounds +#[cgp_fn] +#[extend(?Sized)] +pub fn thing(&self) -> u8 { + 1 +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.stderr b/example-code/tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.stderr new file mode 100644 index 00000000..4ea0a443 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.stderr @@ -0,0 +1,15 @@ +error: relaxed bounds are not permitted in supertrait bounds + --> tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.rs:5:10 + | +5 | #[extend(?Sized)] + | ^^^^^^ + | + = note: traits are not implicitly bounded by `Sized`, so there is nothing to relax + +error: this relaxed bound is not permitted here + --> tests/compile_fail/reference/attributes/extend_formal_grammar_relaxed_bound.rs:5:10 + | +5 | #[extend(?Sized)] + | ^^^^^^ + | + = note: in this context, relaxed bounds are only allowed on type parameters defined on the closest item diff --git a/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.rs b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.rs new file mode 100644 index 00000000..1c9af79c --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.rs @@ -0,0 +1,22 @@ +use core::ops::Mul; + +use cgp::prelude::*; + +#[cgp_fn] +#[extend_where(Scalar: Clone)] +pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar +where + Scalar: Mul, +{ + factor.clone() * factor +} + +// error[E0277]: the trait bound `Scalar: Clone` is not satisfied +pub fn scale_it(ctx: &Ctx) -> Scalar +where + Ctx: Scale, +{ + ctx.scale() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.stderr b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.stderr new file mode 100644 index 00000000..504ad63c --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.stderr @@ -0,0 +1,35 @@ +error[E0277]: the trait bound `Scalar: Clone` is not satisfied + --> tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.rs:17:10 + | +17 | Ctx: Scale, + | ^^^^^^^^^^^^^ the trait `Clone` is not implemented for `Scalar` + | +note: required by a bound in `Scale` + --> tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.rs:6:24 + | + 6 | #[extend_where(Scalar: Clone)] + | ^^^^^ required by this bound in `Scale` + 7 | pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + | ----- required by a bound in this trait +help: consider further restricting type parameter `Scalar` with trait `Clone` + | +17 | Ctx: Scale, Scalar: std::clone::Clone + | +++++++++++++++++++++++++ + +error[E0277]: the trait bound `Scalar: Clone` is not satisfied + --> tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.rs:19:9 + | +19 | ctx.scale() + | ^^^^^ the trait `Clone` is not implemented for `Scalar` + | +note: required by a bound in `Scale::scale` + --> tests/compile_fail/reference/attributes/extend_where_common_mistakes_caller_omits_bound.rs:6:24 + | + 6 | #[extend_where(Scalar: Clone)] + | ^^^^^ required by this bound in `Scale::scale` + 7 | pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + | ----- required by a bound in this associated function +help: consider further restricting type parameter `Scalar` with trait `Clone` + | +17 | Ctx: Scale, Scalar: std::clone::Clone + | +++++++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.rs b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.rs new file mode 100644 index 00000000..bd0cfb33 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: cannot find attribute `extend_where` in this scope +#[cgp_component(Scaler)] +#[extend_where(Scalar: Clone)] +pub trait CanScale { + fn scale(&self) -> Scalar; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.stderr b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.stderr new file mode 100644 index 00000000..3efba6c9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.stderr @@ -0,0 +1,5 @@ +error: cannot find attribute `extend_where` in this scope + --> tests/compile_fail/reference/attributes/extend_where_common_mistakes_on_component.rs:5:3 + | +5 | #[extend_where(Scalar: Clone)] + | ^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.rs b/example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.rs new file mode 100644 index 00000000..f5ca937b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.rs @@ -0,0 +1,24 @@ +use core::ops::Mul; + +use cgp::prelude::*; + +#[cgp_fn] +#[extend_where(Scalar: Clone)] +pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar +where + Scalar: Mul, +{ + factor.clone() * factor +} + +pub struct NoClone; + +// error[E0277]: the trait bound `NoClone: Clone` is not satisfied +pub fn scale_it(ctx: &Ctx) -> NoClone +where + Ctx: Scale, +{ + ctx.scale() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.stderr b/example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.stderr new file mode 100644 index 00000000..855d3268 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.stderr @@ -0,0 +1,37 @@ +error[E0277]: the trait bound `NoClone: Clone` is not satisfied + --> tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.rs:19:10 + | +19 | Ctx: Scale, + | ^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `NoClone` + | +note: required by a bound in `Scale` + --> tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.rs:6:24 + | + 6 | #[extend_where(Scalar: Clone)] + | ^^^^^ required by this bound in `Scale` + 7 | pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + | ----- required by a bound in this trait +help: consider annotating `NoClone` with `#[derive(Clone)]` + | +14 + #[derive(Clone)] +15 | pub struct NoClone; + | + +error[E0277]: the trait bound `NoClone: Clone` is not satisfied + --> tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.rs:21:9 + | +21 | ctx.scale() + | ^^^^^ the trait `Clone` is not implemented for `NoClone` + | +note: required by a bound in `Scale::scale` + --> tests/compile_fail/reference/attributes/extend_where_examples_unsatisfiable_bound.rs:6:24 + | + 6 | #[extend_where(Scalar: Clone)] + | ^^^^^ required by this bound in `Scale::scale` + 7 | pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + | ----- required by a bound in this associated function +help: consider annotating `NoClone` with `#[derive(Clone)]` + | +14 + #[derive(Clone)] +15 | pub struct NoClone; + | diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.rs b/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.rs new file mode 100644 index 00000000..7162d5a9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.rs @@ -0,0 +1,14 @@ +use core::fmt::Display; + +use cgp::prelude::*; + +// error: cannot find attribute `impl_generics` in this scope +// +// Reported once, although every item the component macro generates carries the attribute. +#[cgp_component(Greeter)] +#[impl_generics(Name: Display)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.stderr b/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.stderr new file mode 100644 index 00000000..cf6b5f76 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.stderr @@ -0,0 +1,13 @@ +error: cannot find attribute `impl_generics` in this scope + --> tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.rs:9:3 + | +9 | #[impl_generics(Name: Display)] + | ^^^^^^^^^^^^^ + +warning: unused import: `core::fmt::Display` + --> tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_component.rs:1:5 + | +1 | use core::fmt::Display; + | ^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.rs b/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.rs new file mode 100644 index 00000000..7ae867b4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.rs @@ -0,0 +1,20 @@ +use core::fmt::Display; + +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +// error: cannot find attribute `impl_generics` in this scope +// error[E0425]: cannot find type `Name` in this scope +#[cgp_impl(new GreetHello)] +#[impl_generics(Name: Display)] +impl Greeter { + fn greet(&self, #[implicit] name: &Name) -> String { + format!("Hello, {name}!") + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.stderr b/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.stderr new file mode 100644 index 00000000..279234c1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.stderr @@ -0,0 +1,19 @@ +error: cannot find attribute `impl_generics` in this scope + --> tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.rs:13:3 + | +13 | #[impl_generics(Name: Display)] + | ^^^^^^^^^^^^^ + +error[E0425]: cannot find type `Name` in this scope + --> tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.rs:15:40 + | +15 | fn greet(&self, #[implicit] name: &Name) -> String { + | ^^^^ not found in this scope + +warning: unused import: `core::fmt::Display` + --> tests/compile_fail/reference/attributes/impl_generics_common_mistakes_on_cgp_impl.rs:1:5 + | +1 | use core::fmt::Display; + | ^^^^^^^^^^^^^^^^^^ + | + = note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default diff --git a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs index afe60f54..7823f0cd 100644 --- a/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs +++ b/example-code/tests/compile_fail/reference/attributes/impl_generics_rejected_unconstrained_parameter.rs @@ -6,8 +6,8 @@ use cgp::prelude::*; // predicates #[cgp_fn] #[impl_generics(Name: Display)] -pub fn greet(&self, #[implicit] label: &str) -> String { - format!("Hello, {label}!") +pub fn greet(&self) -> String { + "Hello!".to_owned() } fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.rs b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.rs new file mode 100644 index 00000000..56e9e576 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: `#[implicit]` does not take any arguments; write it as a bare `#[implicit]` +#[cgp_fn] +fn area(&self, #[implicit(width)] width: f64) -> f64 { + width +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.stderr new file mode 100644 index 00000000..d8de268d --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.stderr @@ -0,0 +1,5 @@ +error: `#[implicit]` does not take any arguments; write it as a bare `#[implicit]` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_arguments.rs:5:16 + | +5 | fn area(&self, #[implicit(width)] width: f64) -> f64 { + | ^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs new file mode 100644 index 00000000..4e7dbb3b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs @@ -0,0 +1,21 @@ +use cgp::prelude::*; + +#[cgp_component(Counter)] +pub trait CanCount { + fn small(&self) -> u32; + fn big(&self) -> u64; +} + +// error[E0284]: type annotations needed: cannot satisfy `<__Context__ as HasField<…>>::Value == u32` +#[cgp_impl(new ReadCount)] +impl Counter { + fn small(&self, #[implicit] count: u32) -> u32 { + count + } + + fn big(&self, #[implicit] count: u64) -> u64 { + count + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr new file mode 100644 index 00000000..5a394b72 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr @@ -0,0 +1,37 @@ +error[E0284]: type annotations needed: cannot satisfy `<__Context__ as cgp::prelude::HasField>>>>>>>::Value == u32` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:16 + | +10 | #[cgp_impl(new ReadCount)] + | ^^^^^^^^^ cannot satisfy `<__Context__ as cgp::prelude::HasField>>>>>>>::Value == u32` + | +note: required for `ReadCount` to implement `Counter<__Context__>` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:1 + | +10 | #[cgp_impl(new ReadCount)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: associated types for the current `impl` cannot be restricted in `where` clauses + = note: associated types for the current `impl` cannot be restricted in `where` clauses + = note: this error originates in the attribute macro `cgp_impl` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0284]: type annotations needed: cannot satisfy `<__Context__ as cgp::prelude::HasField>>>>>>>::Value == u32` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:16 + | +10 | #[cgp_impl(new ReadCount)] + | ^^^^^^^^^ cannot satisfy `<__Context__ as cgp::prelude::HasField>>>>>>>::Value == u32` + | +note: required for `ReadCount` to implement `IsProviderFor` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:1 + | +10 | #[cgp_impl(new ReadCount)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: associated types for the current `impl` cannot be restricted in `where` clauses + = note: associated types for the current `impl` cannot be restricted in `where` clauses + = note: this error originates in the attribute macro `cgp_impl` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0282]: type annotations needed + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:1 + | +10 | #[cgp_impl(new ReadCount)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type + | + = note: this error originates in the attribute macro `cgp_impl` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.rs b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.rs new file mode 100644 index 00000000..19bbc3d6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: Expected an identifier +#[cgp_fn] +fn area(&self, #[implicit] (width, height): (f64, f64)) -> f64 { + width * height +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.stderr new file mode 100644 index 00000000..4858936b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.stderr @@ -0,0 +1,5 @@ +error: Expected an identifier + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_destructuring.rs:5:28 + | +5 | fn area(&self, #[implicit] (width, height): (f64, f64)) -> f64 { + | ^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.rs b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.rs new file mode 100644 index 00000000..5b16b25c --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: Mutable variables are not allowed in implicit arguments. +#[cgp_fn] +fn area(&self, #[implicit] mut width: f64) -> f64 { + width += 1.0; + width +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.stderr new file mode 100644 index 00000000..65fcd7e2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.stderr @@ -0,0 +1,5 @@ +error: Mutable variables are not allowed in implicit arguments. (Explicitly clone a `&` reference if you want a mutable local copy of the value) + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_binding.rs:5:28 + | +5 | fn area(&self, #[implicit] mut width: f64) -> f64 { + | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.rs b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.rs new file mode 100644 index 00000000..f8364bb8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: a `&mut` implicit argument must be the only implicit argument +#[cgp_fn] +fn bump(&mut self, #[implicit] counter: &mut u64, #[implicit] step: u64) { + *counter += step; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.stderr new file mode 100644 index 00000000..d7f1f9dc --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.stderr @@ -0,0 +1,5 @@ +error: a `&mut` implicit argument must be the only implicit argument, since its mutable borrow of the context conflicts with reading any other field + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_not_alone.rs:5:9 + | +5 | fn bump(&mut self, #[implicit] counter: &mut u64, #[implicit] step: u64) { + | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.rs b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.rs new file mode 100644 index 00000000..d14aaeb2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: &mut self is required for mutable field reference `& mut u64` +#[cgp_fn] +fn bump(&self, #[implicit] counter: &mut u64) { + *counter += 1; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.stderr new file mode 100644 index 00000000..af87f6e1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.stderr @@ -0,0 +1,5 @@ +error: &mut self is required for mutable field reference `& mut u64` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_mut_under_shared_self.rs:5:37 + | +5 | fn bump(&self, #[implicit] counter: &mut u64) { + | ^ diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.rs b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.rs new file mode 100644 index 00000000..58ff507d --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: The first argument of a function with implicit arguments must be `self` +#[cgp_fn] +fn area(#[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.stderr new file mode 100644 index 00000000..a5bba8ec --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.stderr @@ -0,0 +1,7 @@ +error: The first argument of a function with implicit arguments must be `self` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_no_self.rs:4:1 + | +4 | #[cgp_fn] + | ^^^^^^^^^ + | + = note: this error originates in the attribute macro `cgp_fn` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.rs b/example-code/tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.rs new file mode 100644 index 00000000..533215ac --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.rs @@ -0,0 +1,7 @@ +// error: cannot find attribute `implicit` in this scope +pub fn area(width_source: &f64, #[implicit] width: f64) -> f64 { + let _ = width_source; + width +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.stderr new file mode 100644 index 00000000..20a47114 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.stderr @@ -0,0 +1,5 @@ +error: cannot find attribute `implicit` in this scope + --> tests/compile_fail/reference/attributes/implicit_usage_outside_a_host.rs:2:35 + | +2 | pub fn area(width_source: &f64, #[implicit] width: f64) -> f64 { + | ^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.rs b/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.rs new file mode 100644 index 00000000..d3d071b1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.rs @@ -0,0 +1,37 @@ +use core::fmt::Display; + +use cgp::prelude::*; + +// The prefix repeats the marker the macro appends, so the route is +// `@app.ShowImplComponent.ShowImplComponent.String`, which the entry below does not match. +#[cgp_component(ShowImpl)] +#[prefix(@app.ShowImplComponent in DefaultNamespace)] +pub trait CanShow { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowWithDisplay)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + format!("{value}") + } +} + +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + @app.ShowImplComponent.String: ShowWithDisplay, + } +} + +// error[E0277]: the trait bound `PathCons<...>: DefaultNamespace` is not satisfied +check_components! { + App { + ShowImplComponent: String, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.stderr b/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.stderr new file mode 100644 index 00000000..6b6f8c3b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.stderr @@ -0,0 +1,43 @@ +error[E0277]: the trait bound `PathCons>>>, PathCons>>>: cgp::prelude::DefaultNamespace` is not satisfied + --> tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.rs:33:9 + | +33 | ShowImplComponent: String, + | ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `cgp::prelude::DefaultNamespace` is not implemented for `PathCons>>>, PathCons>>>` + = help: the following other types implement trait `cgp::prelude::DefaultNamespace`: + AsyncComputerComponent + AsyncComputerRefComponent + ComputerComponent + ComputerRefComponent + ErrorRaiserComponent + ErrorTypeProviderComponent + ErrorWrapperComponent + HandlerComponent + and $N others +note: required for `App` to implement `DelegateComponent>>>, PathCons>>>>` + --> tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.rs:22:1 + | +22 | / delegate_components! { +23 | | App { + | | ^^^ +24 | | namespace DefaultNamespace; +... | +28 | | } + | |_^ +note: required for `RedirectLookup>>>, PathCons>>>` to implement `IsProviderFor` + --> tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.rs:7:1 + | + 7 | #[cgp_component(ShowImpl)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/attributes/prefix_common_mistakes_doubled_marker.rs:31:1 + | +31 | / check_components! { +32 | | App { +33 | | ShowImplComponent: String, +34 | | } +35 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `delegate_components` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.rs b/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.rs new file mode 100644 index 00000000..e64adbf3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.rs @@ -0,0 +1,17 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +// error: cannot find attribute `prefix` in this scope +#[cgp_impl(new GreetHello)] +#[prefix(@app in DefaultNamespace)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.stderr b/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.stderr new file mode 100644 index 00000000..1b15fbcf --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.stderr @@ -0,0 +1,5 @@ +error: cannot find attribute `prefix` in this scope + --> tests/compile_fail/reference/attributes/prefix_common_mistakes_on_cgp_impl.rs:10:3 + | +10 | #[prefix(@app in DefaultNamespace)] + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs index 410b922f..551da8f6 100644 --- a/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs +++ b/example-code/tests/compile_fail/reference/attributes/prefix_rejected_duplicate_namespace.rs @@ -7,7 +7,7 @@ cgp_namespace! { // error[E0119]: conflicting implementations of trait `AppNamespace<_>` for type `GreeterComponent` #[cgp_component(Greeter)] #[prefix(@app in AppNamespace)] -#[prefix(@other in AppNamespace)] +#[prefix(@greeting in AppNamespace)] pub trait CanGreet { fn greet(&self) -> String; } diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.rs b/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.rs new file mode 100644 index 00000000..bb1dbdd1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.rs @@ -0,0 +1,27 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +// error: expected `:` +#[cgp_fn] +#[use_provider(RectangleArea)] +pub fn rect_area(&self) -> f64 { + RectangleArea::area(self) +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.stderr b/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.stderr new file mode 100644 index 00000000..b2ec35ec --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.stderr @@ -0,0 +1,5 @@ +error: expected `:` + --> tests/compile_fail/reference/attributes/use_provider_common_mistakes_bare_provider.rs:22:29 + | +22 | #[use_provider(RectangleArea)] + | ^ diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.rs b/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.rs new file mode 100644 index 00000000..9011a97e --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.rs @@ -0,0 +1,29 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +// error: expected `+` +#[cgp_impl(new Both)] +#[use_provider(A: AreaCalculator, P: PerimeterCalculator)] +impl AreaCalculator { + fn area(&self) -> f64 { + A::area(self) + P::perimeter(self) + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.stderr b/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.stderr new file mode 100644 index 00000000..44eb18e5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.stderr @@ -0,0 +1,5 @@ +error: expected `+` + --> tests/compile_fail/reference/attributes/use_provider_common_mistakes_comma_list.rs:22:33 + | +22 | #[use_provider(A: AreaCalculator, P: PerimeterCalculator)] + | ^ diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.rs b/example-code/tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.rs new file mode 100644 index 00000000..f28aa9b4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.rs @@ -0,0 +1,29 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +// error: associated bindings (`Name = ...`) are not allowed in type arguments +#[cgp_impl(new Wrap)] +#[use_provider(Inner: AreaCalculator)] +impl AreaCalculator { + fn area(&self) -> f64 { + Inner::area(self) + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.stderr b/example-code/tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.stderr new file mode 100644 index 00000000..ac11818f --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.stderr @@ -0,0 +1,5 @@ +error: associated bindings (`Name = ...`) are not allowed in type arguments + --> tests/compile_fail/reference/attributes/use_provider_formal_grammar_associated_binding.rs:22:45 + | +22 | #[use_provider(Inner: AreaCalculator)] + | ^ diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.rs b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.rs new file mode 100644 index 00000000..cfbddf29 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.rs @@ -0,0 +1,27 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_component(PerimeterCalculator)] +pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } +} + +// error: cannot find attribute `use_provider` in this scope +#[cgp_component(Shouter)] +#[use_provider(RectangleArea: AreaCalculator)] +pub trait CanShout { + fn shout(&self) -> String; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr new file mode 100644 index 00000000..88a524b8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr @@ -0,0 +1,16 @@ +error: cannot find attribute `use_provider` in this scope + --> tests/compile_fail/reference/attributes/use_provider_usage_component_trait.rs:22:3 + | + 22 | #[use_provider(RectangleArea: AreaCalculator)] + | ^^^^^^^^^^^^ + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/macros/cgp-macro/src/lib.rs:135:1 + | +135 | pub fn cgp_provider(attr: TokenStream, item: TokenStream) -> TokenStream { + | ------------------------------------------------------------------------ similarly named attribute macro `cgp_provider` defined here + | +help: an attribute macro with a similar name exists + | + 22 - #[use_provider(RectangleArea: AreaCalculator)] + 22 + #[cgp_provider(RectangleArea: AreaCalculator)] + | diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.rs new file mode 100644 index 00000000..87b6cddc --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasFooType { + type Foo; +} + +#[cgp_type] +pub trait HasBarType { + type Bar; +} + +// error[E0405]: cannot find trait `Foo` in this scope +#[cgp_fn] +#[use_type(HasFooType.Foo, Foo.Bar)] +pub fn pick(&self, value: Bar) -> Bar { + value +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.stderr new file mode 100644 index 00000000..fe4b58a6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.stderr @@ -0,0 +1,5 @@ +error[E0405]: cannot find trait `Foo` in this scope + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_alias_as_trait.rs:15:28 + | +15 | #[use_type(HasFooType.Foo, Foo.Bar)] + | ^^^ not found in this scope diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.rs new file mode 100644 index 00000000..b2a93504 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasFooType { + type Foo; +} + +#[cgp_type] +pub trait HasBarType { + type Bar; +} + +// error[E0275]: overflow evaluating the requirement `<__Context__ as HasFooType>::Foo == _` +#[cgp_fn] +#[use_type(HasFooType.{Foo = Bar}, HasBarType.{Bar = Foo})] +pub fn pick(&self, value: Foo) -> Bar { + value +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.stderr new file mode 100644 index 00000000..d6598c95 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.stderr @@ -0,0 +1,7 @@ +error[E0275]: overflow evaluating the requirement `<__Context__ as HasFooType>::Foo == _` + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_circular_pins.rs:14:1 + | +14 | #[cgp_fn] + | ^^^^^^^^^ + | + = note: this error originates in the attribute macro `cgp_fn` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.rs new file mode 100644 index 00000000..79898a8e --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasAType { + type A; +} + +#[cgp_type] +pub trait HasBType { + type B; +} + +// error: cannot ground `#[use_type]` imports: they resolve through one another in a cycle +#[cgp_fn] +#[use_type(HasAType.A in B, HasBType.B in A)] +pub fn pick(&self, value: A) -> A { + value +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.stderr new file mode 100644 index 00000000..630f1315 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.stderr @@ -0,0 +1,5 @@ +error: cannot ground `#[use_type]` imports: they resolve through one another in a cycle `B` -> `A` -> `B`. An `in Context` clause or a trait argument may name another import's alias only if the resulting chain is acyclic, since a cycle has no valid grounding order. + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_cycle.rs:15:43 + | +15 | #[use_type(HasAType.A in B, HasBType.B in A)] + | ^ diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.rs new file mode 100644 index 00000000..6876be0c --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasFooType { + type Foo; +} + +#[cgp_type] +pub trait HasBarType { + type Bar; +} + +// error[E0576]: cannot find associated type `Eror` in trait `HasErrorType` +#[cgp_fn] +#[use_type(HasErrorType.Eror)] +pub fn fail(&self) -> Result<(), Eror> { + Ok(()) +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr new file mode 100644 index 00000000..79920408 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr @@ -0,0 +1,15 @@ +error[E0576]: cannot find associated type `Eror` in trait `HasErrorType` + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.rs:16:34 + | +16 | pub fn fail(&self) -> Result<(), Eror> { + | ^^^^ + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-error/src/traits/has_error_type.rs:28:5 + | +28 | type Error: Debug; + | ----------------- similarly named associated type `Error` defined here + | +help: an associated type with a similar name exists + | +16 | pub fn fail(&self) -> Result<(), Error> { + | + diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.rs new file mode 100644 index 00000000..29580330 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasFooType { + type Foo; +} + +#[cgp_type] +pub trait HasBarType { + type Bar; +} + +// error[E0425]: cannot find type `Output` in this scope +#[cgp_component(Maker)] +pub trait CanMake { + type Output; + fn make(&self) -> Output; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.stderr new file mode 100644 index 00000000..f2c50d65 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.stderr @@ -0,0 +1,14 @@ +error[E0425]: cannot find type `Output` in this scope + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_own_associated_type.rs:17:23 + | +17 | fn make(&self) -> Output; + | ^^^^^^ + | +help: you might have meant to use the associated type + | +17 | fn make(&self) -> Self::Output; + | ++++++ +help: consider importing this struct + | + 1 + use std::process::Output; + | diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.rs new file mode 100644 index 00000000..1e2ed306 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasFooType { + type Foo; +} + +#[cgp_type] +pub trait HasBarType { + type Bar; +} + +// error: Type equality constraints cannot be used in component trait definition +#[cgp_component(Loader)] +#[use_type(HasErrorType.{Error = anyhow::Error})] +pub trait CanLoad { + fn load(&self, path: &str) -> Result; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.stderr new file mode 100644 index 00000000..000d9250 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.stderr @@ -0,0 +1,5 @@ +error: Type equality constraints cannot be used in component trait definition + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_pin_on_component.rs:15:34 + | +15 | #[use_type(HasErrorType.{Error = anyhow::Error})] + | ^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.rs new file mode 100644 index 00000000..ebc999df --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasFooType { + type Foo; +} + +#[cgp_type] +pub trait HasBarType { + type Bar; +} + +// error[E0425]: cannot find type `Foo` in this scope +#[cgp_fn] +#[use_type(HasFooType.{Foo = Foo})] +pub fn pick(&self, value: Foo) -> Foo { + value +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.stderr new file mode 100644 index 00000000..95509a19 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.stderr @@ -0,0 +1,5 @@ +error[E0425]: cannot find type `Foo` in this scope + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_self_pin.rs:15:30 + | +15 | #[use_type(HasFooType.{Foo = Foo})] + | ^^^ not found in this scope diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.rs new file mode 100644 index 00000000..265b42e2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasAType { + type A; +} + +#[cgp_type] +pub trait HasBType { + type B; +} + +// error: cannot ground `#[use_type]` imports: they resolve through one another in a cycle +#[cgp_fn] +#[use_type(HasAType.A in A)] +pub fn pick(&self, value: A) -> A { + value +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.stderr new file mode 100644 index 00000000..832d94a5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.stderr @@ -0,0 +1,5 @@ +error: cannot ground `#[use_type]` imports: they resolve through one another in a cycle `A` -> `A`. An `in Context` clause or a trait argument may name another import's alias only if the resulting chain is acyclic, since a cycle has no valid grounding order. + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_self_reference.rs:15:26 + | +15 | #[use_type(HasAType.A in A)] + | ^ diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.rs b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.rs new file mode 100644 index 00000000..9c7550dd --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.rs @@ -0,0 +1,20 @@ +use cgp::prelude::*; + +#[cgp_type] +pub trait HasFooType { + type Foo; +} + +#[cgp_type] +pub trait HasBarType { + type Bar; +} + +// error: Multiple abstract types cannot share the same identifier or alias +#[cgp_fn] +#[use_type(HasFooType.Foo, HasBarType.Bar as Foo)] +pub fn pick(&self, value: Foo) -> Foo { + value +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.stderr new file mode 100644 index 00000000..7411de18 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.stderr @@ -0,0 +1,5 @@ +error: Multiple abstract types cannot share the same identifier or alias + --> tests/compile_fail/reference/attributes/use_type_common_mistakes_shared_alias.rs:15:39 + | +15 | #[use_type(HasFooType.Foo, HasBarType.Bar as Foo)] + | ^^^ diff --git a/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.rs b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.rs new file mode 100644 index 00000000..73d3673a --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.rs @@ -0,0 +1,15 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +// error: cannot find attribute `uses` in this scope +#[cgp_component(Shouter)] +#[uses(CanCalculateArea)] +pub trait CanShout { + fn shout(&self) -> String; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr new file mode 100644 index 00000000..703594fe --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr @@ -0,0 +1,11 @@ +error: cannot find attribute `uses` in this scope + --> tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.rs:10:3 + | +10 | #[uses(CanCalculateArea)] + | ^^^^ + | +help: a built-in attribute with a similar name exists + | +10 - #[uses(CanCalculateArea)] +10 + #[used(CanCalculateArea)] + | diff --git a/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.rs b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.rs new file mode 100644 index 00000000..0cc5a83e --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.rs @@ -0,0 +1,15 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +// error[E0107]: missing generics for trait `AreaCalculator` +#[cgp_fn] +#[uses(AreaCalculator)] +pub fn scaled_area(&self, #[implicit] scale_factor: f64) -> f64 { + self.area() * scale_factor * scale_factor +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.stderr b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.stderr new file mode 100644 index 00000000..21d9183b --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.stderr @@ -0,0 +1,15 @@ +error[E0107]: missing generics for trait `AreaCalculator` + --> tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.rs:10:8 + | +10 | #[uses(AreaCalculator)] + | ^^^^^^^^^^^^^^ expected 1 generic argument + | +note: trait defined here, with 1 generic parameter: `__Context__` + --> tests/compile_fail/reference/attributes/uses_common_mistakes_provider_trait.rs:3:17 + | + 3 | #[cgp_component(AreaCalculator)] + | ----------------^^^^^^^^^^^^^^-- +help: add missing generic argument + | +10 | #[uses(AreaCalculator<__Context__>)] + | +++++++++++++ diff --git a/example-code/tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.rs b/example-code/tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.rs new file mode 100644 index 00000000..bc5e1a61 --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: this relaxed bound is not permitted here +#[cgp_fn] +#[uses(?Sized)] +pub fn thing(&self) -> u8 { + 1 +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.stderr b/example-code/tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.stderr new file mode 100644 index 00000000..20d538be --- /dev/null +++ b/example-code/tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.stderr @@ -0,0 +1,7 @@ +error: this relaxed bound is not permitted here + --> tests/compile_fail/reference/attributes/uses_formal_grammar_relaxed_bound.rs:5:8 + | +5 | #[uses(?Sized)] + | ^^^^^^ + | + = note: in this context, relaxed bounds are only allowed on type parameters defined on the closest item diff --git a/example-code/tests/reference/attributes/default_impl.rs b/example-code/tests/reference/attributes/default_impl.rs index 850d4c52..33e85b17 100644 --- a/example-code/tests/reference/attributes/default_impl.rs +++ b/example-code/tests/reference/attributes/default_impl.rs @@ -205,7 +205,7 @@ pub mod under_the_hood { } } - impl AppNamespace for Path!(@app.GreeterComponent) { + impl<__Components__> AppNamespace<__Components__> for Path!(@app.GreeterComponent) { type Delegate = GreetHello; } diff --git a/example-code/tests/reference/attributes/derive_delegate.rs b/example-code/tests/reference/attributes/derive_delegate.rs new file mode 100644 index 00000000..3e448cad --- /dev/null +++ b/example-code/tests/reference/attributes/derive_delegate.rs @@ -0,0 +1,222 @@ +//! Code from `docs/reference/attributes/derive_delegate.md` — *`#[derive_delegate]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/attributes/`. + +/// ## Usage +/// +/// Two dispatchers on one component, the second through a user-defined wrapper, and a tuple key. +/// The page names `UseInputDelegate` as a struct the reader defines. +pub mod usage { + use cgp::prelude::*; + + pub struct UseInputDelegate(pub PhantomData); + + #[cgp_component(Computer)] + #[derive_delegate(UseDelegate)] + #[derive_delegate(UseInputDelegate)] + pub trait CanCompute { + type Output; + + fn compute(&self, _code: PhantomData, input: Input) -> Self::Output; + } + + #[cgp_component(Pairer)] + #[derive_delegate(UseDelegate<(Code, Input)>)] + pub trait CanPair { + fn pair(&self, input: Input) -> u64; + } + + pub struct Double; + pub struct Negate; + + #[cgp_impl(new DoubleIt)] + impl Computer { + type Output = u64; + + fn compute(&self, _code: PhantomData, input: u64) -> u64 { + input * 2 + } + } + + #[cgp_impl(new NegateIt)] + impl Computer { + type Output = i64; + + fn compute(&self, _code: PhantomData, input: i64) -> i64 { + -input + } + } + + #[cgp_impl(new PairDouble)] + impl Pairer { + fn pair(&self, input: u64) -> u64 { + input * 2 + } + } + + pub struct App; + + delegate_components! { + App { + ComputerComponent: + UseInputDelegate, + PairerComponent: + UseDelegate, + } + } + + check_components! { + App { + ComputerComponent: [(Double, u64), (Negate, i64)], + PairerComponent: (Double, u64), + } + } + + #[test] + fn each_dispatcher_keys_on_its_own_parameter() { + assert_eq!(App.compute(PhantomData::, 4u64), 8); + assert_eq!(App.compute(PhantomData::, 4i64), -4); + assert_eq!(CanPair::::pair(&App, 3), 6); + } +} + +/// ## Examples +/// +/// The dispatching component and the two wirings the page compares, on two contexts. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + #[derive_delegate(UseDelegate)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + pub struct Circle { + pub radius: f64, + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, shape: &Rectangle) -> f64 { + shape.width * shape.height + } + } + + #[cgp_impl(new CircleArea)] + impl AreaCalculator { + fn area(&self, shape: &Circle) -> f64 { + core::f64::consts::PI * shape.radius * shape.radius + } + } + + pub struct MyApp; + + delegate_components! { + MyApp { + AreaCalculatorComponent: + UseDelegate, + } + } + + check_components! { + MyApp { + AreaCalculatorComponent: [Rectangle, Circle], + } + } + + /// The same result through `open`. A second context stands in for the page's `MyApp`, since + /// one context cannot use both forms. + pub struct OpenApp; + + delegate_components! { + OpenApp { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Rectangle: RectangleArea, + @AreaCalculatorComponent.Circle: CircleArea, + } + } + + check_components! { + OpenApp { + AreaCalculatorComponent: [Rectangle, Circle], + } + } + + #[test] + fn both_forms_resolve_to_the_same_providers() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(MyApp.area(&rect), 6.0); + assert_eq!(OpenApp.area(&rect), MyApp.area(&rect)); + assert_eq!( + OpenApp.area(&Circle { radius: 1.0 }), + MyApp.area(&Circle { radius: 1.0 }) + ); + } +} + +/// ## Under the hood +/// +/// A one-element tuple key, written with a trailing comma, keys the table on the tuple. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + #[derive_delegate(UseDelegate)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + #[cgp_component(TupleArea)] + #[derive_delegate(UseDelegate<(Shape,)>)] + pub trait CanTupleArea { + fn tuple_area(&self, shape: &Shape) -> f64; + } + + pub struct Square(pub f64); + + #[cgp_impl(new SquareArea)] + impl TupleArea { + fn tuple_area(&self, shape: &Square) -> f64 { + shape.0 * shape.0 + } + } + + pub struct App; + + delegate_components! { + App { + TupleAreaComponent: + UseDelegate, + } + } + + check_components! { + App { + TupleAreaComponent: Square, + } + } + + #[test] + fn the_tuple_key_resolves() { + assert_eq!(App.tuple_area(&Square(3.0)), 9.0); + } +} diff --git a/example-code/tests/reference/attributes/extend.rs b/example-code/tests/reference/attributes/extend.rs new file mode 100644 index 00000000..dadf5113 --- /dev/null +++ b/example-code/tests/reference/attributes/extend.rs @@ -0,0 +1,187 @@ +//! Code from `docs/reference/attributes/extend.md` — *`#[extend]`*. +//! +//! The snippet the page rejects lives under `tests/compile_fail/reference/attributes/`. + +/// ## Overview and Usage +/// +/// A supertrait added to a component, a list in one attribute, and a list split across two. +pub mod usage { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_auto_getter] + pub trait HasTitle { + fn title(&self) -> &str; + } + + #[cgp_fn] + #[extend(HasName, HasTitle)] + pub fn listed(&self) -> String { + format!("{} {}", self.title(), self.name()) + } + + #[cgp_fn] + #[extend(HasName)] + #[extend(HasTitle)] + pub fn split(&self) -> String { + format!("{} {}", self.title(), self.name()) + } + + /// `#[extend]` and `#[uses]` together share one `Self:` predicate. + #[cgp_fn] + #[extend(HasName)] + #[uses(HasTitle)] + pub fn mixed(&self) -> String { + format!("{} {}", self.title(), self.name()) + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + pub title: String, + } + + #[test] + fn the_lists_accumulate() { + let person = Person { + name: "Lovelace".to_owned(), + title: "Countess".to_owned(), + }; + assert_eq!(person.listed(), "Countess Lovelace"); + assert_eq!(person.split(), person.listed()); + assert_eq!(person.mixed(), person.listed()); + } +} + +/// ## When the supertrait supplies a type +pub mod when_the_supertrait_supplies_a_type { + use cgp::prelude::*; + + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self, path: &str) -> Result; + } +} + +/// ## Examples +/// +/// The `#[cgp_fn]` example with a context that has both fields, and the component example with a +/// provider and wiring. The page names the `Greeter` provider trait without writing a provider. +pub mod examples { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_auto_getter] + pub trait HasTitle { + fn title(&self) -> &str; + } + + #[cgp_fn] + #[extend(HasName, HasTitle)] + pub fn full_label(&self) -> String { + format!("{} {}", self.title(), self.name()) + } + + /// A caller holding `T: FullLabel` can call the supertrait's getter without asking for it. + pub fn name_of(value: &T) -> &str { + value.name() + } + + #[cgp_component(Greeter)] + #[extend(HasName)] + pub trait CanGreet { + fn greet(&self); + } + + /// The provider trait carries `HasName` as a `where` bound, which an impl must prove rather than + /// inherit, so the provider imports it again. + #[cgp_impl(new GreetHello)] + #[uses(HasName)] + impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } + } + + /// A caller of `CanGreet` may rely on the supertrait without asking for it. + pub fn greet_by_name(value: &T) -> &str { + value.greet(); + value.name() + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + pub title: String, + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + #[test] + fn callers_rely_on_the_supertrait() { + let person = Person { + name: "Ada".to_owned(), + title: "Countess".to_owned(), + }; + assert_eq!(person.full_label(), "Countess Ada"); + assert_eq!(name_of(&person), "Ada"); + assert_eq!(greet_by_name(&person), "Ada"); + } +} + +/// ## Under the hood +/// +/// The two listings' inputs. The page's `CanGreet` returns nothing; so does this one. +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_auto_getter] + pub trait HasTitle { + fn title(&self) -> &str; + } + + #[cgp_fn] + #[extend(HasName, HasTitle)] + pub fn full_label(&self) -> String { + format!("{} {}", self.title(), self.name()) + } + + #[cgp_component(Greeter)] + #[extend(HasName)] + pub trait CanGreet { + fn greet(&self); + } + + /// The provider from Examples, proving the provider trait's `where` bound with `#[uses]`. + #[cgp_impl(new GreetHello)] + #[uses(HasName)] + impl Greeter { + fn greet(&self) { + println!("Hello, {}!", self.name()); + } + } +} diff --git a/example-code/tests/reference/attributes/extend_where.rs b/example-code/tests/reference/attributes/extend_where.rs new file mode 100644 index 00000000..c6235373 --- /dev/null +++ b/example-code/tests/reference/attributes/extend_where.rs @@ -0,0 +1,114 @@ +//! Code from `docs/reference/attributes/extend_where.md` — *`#[extend_where]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/attributes/`. + +/// ## Overview, Usage, and Examples +/// +/// The example trait, a caller who states the promoted predicate, and the wider predicate forms +/// the grammar accepts. +pub mod examples { + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_fn] + #[extend_where(Scalar: Clone)] + pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + where + Scalar: Mul, + { + factor.clone() * factor + } + + pub fn scale_it(ctx: &Ctx) -> Scalar + where + Ctx: Scale, + Scalar: Clone, + { + ctx.scale() + } + + #[cgp_fn] + #[extend_where(for<'a> &'a Items: IntoIterator, Items: Default)] + pub fn total(&self, #[implicit] items: &Items) -> u32 { + items.into_iter().sum() + } + + #[derive(HasField)] + pub struct Scaler { + pub factor: u32, + pub items: Vec, + } + + #[test] + fn the_caller_states_the_bound() { + let scaler = Scaler { + factor: 3, + items: vec![1, 2], + }; + assert_eq!(scale_it::<_, u32>(&scaler), 9); + assert_eq!(Total::>::total(&scaler), 3); + } +} + +/// ## Examples: the bound left on the implementation +/// +/// With `Clone` in the function's own `where` clause, a caller naming the trait for a type that +/// cannot be cloned compiles, since nothing checks the bound until a context is supplied. +pub mod left_on_the_implementation { + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_fn] + pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + where + Scalar: Mul + Clone, + { + factor.clone() * factor + } + + pub struct NoClone; + + pub fn scale_it(ctx: &Ctx) -> NoClone + where + Ctx: Scale, + { + ctx.scale() + } +} + +/// ## Under the hood +/// +/// The listing's input, and one function combining every contributor to the implementation's +/// `where` clause, to pin their order. +pub mod under_the_hood { + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_fn] + #[extend_where(Scalar: Clone)] + pub fn scale(&self, #[implicit] factor: Scalar) -> Scalar + where + Scalar: Mul, + { + factor.clone() * factor + } + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_fn] + #[use_type(HasErrorType.Error)] + #[extend_where(Scalar: Clone)] + #[uses(HasName)] + pub fn ordered(&self, #[implicit] factor: Scalar) -> Result + where + Scalar: Mul, + { + Ok(factor.clone() * factor) + } +} diff --git a/example-code/tests/reference/attributes/impl_generics.rs b/example-code/tests/reference/attributes/impl_generics.rs index 71f52311..ce2abc85 100644 --- a/example-code/tests/reference/attributes/impl_generics.rs +++ b/example-code/tests/reference/attributes/impl_generics.rs @@ -92,6 +92,29 @@ pub mod usage { } } +/// ## Usage: a const parameter +/// +/// A const parameter pinned by an array field's length. +pub mod const_parameter { + use cgp::prelude::*; + + #[cgp_fn] + #[impl_generics(const N: usize)] + pub fn byte_count(&self, #[implicit] data: &[u8; N]) -> usize { + data.len() + } + + #[derive(HasField)] + pub struct Packet { + pub data: [u8; 4], + } + + #[test] + fn the_length_is_inferred() { + assert_eq!(Packet { data: [0; 4] }.byte_count(), 4); + } +} + /// ## Examples pub mod examples { use core::fmt::Display; diff --git a/example-code/tests/reference/attributes/implicit.rs b/example-code/tests/reference/attributes/implicit.rs new file mode 100644 index 00000000..2654e3db --- /dev/null +++ b/example-code/tests/reference/attributes/implicit.rs @@ -0,0 +1,384 @@ +//! Code from `docs/reference/attributes/implicit.md` — *`#[implicit]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/attributes/`. + +/// ## Overview +pub mod overview { + use cgp::prelude::*; + + #[cgp_fn] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + // The page names `rect` without declaring its type. + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[test] + fn the_caller_passes_nothing() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.rectangle_area(), 6.0); + } +} + +/// ## Usage, How the argument's type decides the read, and Mutable arguments +/// +/// The Usage snippet as a `#[cgp_fn]`, the raw-identifier rule, and one function per row of the +/// access table, each run against a context holding the field type the row names. +pub mod usage { + use cgp::prelude::*; + + #[cgp_fn] + pub fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[cgp_fn] + pub fn kind(&self, #[implicit] r#type: &str) -> String { + r#type.to_owned() + } + + #[cgp_fn] + pub fn read_owned(&self, #[implicit] pair: (f64, f64)) -> f64 { + pair.0 + pair.1 + } + + #[cgp_fn] + pub fn read_ref(&self, #[implicit] tags: &Vec) -> usize { + tags.len() + } + + #[cgp_fn] + pub fn read_str(&self, #[implicit] name: &str) -> usize { + name.len() + } + + #[cgp_fn] + pub fn read_slice(&self, #[implicit] bytes: &[u8]) -> usize { + bytes.len() + } + + #[cgp_fn] + pub fn read_option_ref(&self, #[implicit] limit: Option<&u32>) -> u32 { + limit.copied().unwrap_or(0) + } + + #[cgp_fn] + pub fn read_option_str(&self, #[implicit] nickname: Option<&str>) -> usize { + nickname.map_or(0, str::len) + } + + #[cgp_fn] + pub fn read_mref(&self, #[implicit] name: MRef<'_, String>) -> usize { + name.len() + } + + #[cgp_fn] + pub fn bump(&mut self, #[implicit] counter: &mut u64) { + *counter += 1; + } + + #[cgp_fn] + pub fn shout_name(&mut self, #[implicit] name: &mut str) { + name.make_ascii_uppercase(); + } + + #[cgp_fn] + pub fn zero_bytes(&mut self, #[implicit] bytes: &mut [u8]) { + bytes.fill(0); + } + + #[cgp_fn] + pub fn raise_limit(&mut self, #[implicit] limit: Option<&mut u32>) { + if let Some(limit) = limit { + *limit += 1; + } + } + + #[cgp_fn] + pub fn shout_nickname(&mut self, #[implicit] nickname: Option<&mut str>) { + if let Some(nickname) = nickname { + nickname.make_ascii_uppercase(); + } + } + + /// A `&mut self` receiver with several immutable implicit arguments. + #[cgp_fn] + pub fn describe_mut(&mut self, #[implicit] name: &str, #[implicit] bytes: &[u8]) -> usize { + name.len() + bytes.len() + } + + #[derive(HasField)] + pub struct Record { + pub width: f64, + pub height: f64, + pub r#type: String, + pub pair: (f64, f64), + pub tags: Vec, + pub name: String, + pub bytes: Vec, + pub limit: Option, + pub nickname: Option, + pub counter: u64, + } + + #[test] + fn every_access_form_reads_its_field() { + let mut record = Record { + width: 2.0, + height: 3.0, + r#type: "box".to_owned(), + pair: (1.0, 2.0), + tags: vec!["a".to_owned()], + name: "ada".to_owned(), + bytes: vec![1, 2], + limit: Some(5), + nickname: Some("lin".to_owned()), + counter: 0, + }; + + assert_eq!(record.area(), 6.0); + assert_eq!(record.kind(), "box"); + assert_eq!(record.read_owned(), 3.0); + assert_eq!(record.read_ref(), 1); + assert_eq!(record.read_str(), 3); + assert_eq!(record.read_slice(), 2); + assert_eq!(record.read_option_ref(), 5); + assert_eq!(record.read_option_str(), 3); + assert_eq!(record.read_mref(), 3); + assert_eq!(record.describe_mut(), 5); + + record.bump(); + record.shout_name(); + record.zero_bytes(); + record.raise_limit(); + record.shout_nickname(); + + assert_eq!(record.counter, 1); + assert_eq!(record.name, "ADA"); + assert_eq!(record.bytes, vec![0, 0]); + assert_eq!(record.limit, Some(6)); + assert_eq!(record.nickname.as_deref(), Some("LIN")); + } +} + +/// ## Examples +/// +/// The complete trait, the mutable example, and the `#[cgp_impl]` fragment. The page assumes the +/// `EmailSender` component and the `App` context without declaring them. +pub mod examples { + use cgp::prelude::*; + + #[cgp_fn] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub fn print_area(rect: &Rectangle) { + println!("area = {}", rect.rectangle_area()); + } + + #[cgp_fn] + pub fn shout(&mut self, #[implicit] name: &mut str) { + name.make_ascii_uppercase(); + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[cgp_component(EmailSender)] + pub trait CanSendEmail { + fn send_email(&self, to: &str, body: &str); + } + + #[cgp_impl(new SendViaSmtp)] + impl EmailSender { + fn send_email(&self, #[implicit] smtp_server: &str, to: &str, body: &str) { + // connect to `smtp_server` and send the message + let _ = (smtp_server, to, body); + } + } + + #[derive(HasField)] + pub struct App { + pub smtp_server: String, + } + + delegate_components! { + App { + EmailSenderComponent: SendViaSmtp, + } + } + + check_components! { + App { + EmailSenderComponent, + } + } + + #[test] + fn the_examples_run() { + print_area(&Rectangle { + width: 2.0, + height: 3.0, + }); + + let mut person = Person { + name: "ada".to_owned(), + }; + person.shout(); + assert_eq!(person.name, "ADA"); + + let app = App { + smtp_server: "smtp.example.com".to_owned(), + }; + app.send_email("to@example.com", "hi"); + } +} + +/// ## Under the hood +/// +/// The hand-written expansion of the page's listing, under another trait name so it can sit +/// beside the macro's own output, plus the slice and mutable bounds the section names. +pub mod under_the_hood { + use cgp::prelude::*; + + pub trait RectangleArea { + fn rectangle_area(&self) -> f64; + } + + impl<__Context__> RectangleArea for __Context__ + where + Self: HasField + HasField, + { + fn rectangle_area(&self) -> f64 { + let width: f64 = self.get_field(PhantomData::).clone(); + let height: f64 = self.get_field(PhantomData::).clone(); + + width * height + } + } + + #[cgp_fn] + pub fn slice_len(&self, #[implicit] slice: &[u8]) -> usize { + slice.len() + } + + #[cgp_fn] + pub fn bump_counter(&mut self, #[implicit] counter: &mut u64) { + *counter += 1; + } + + /// Two methods reading one field at one type contribute one bound. + #[cgp_component(Namer)] + pub trait CanName { + fn first(&self) -> String; + fn second(&self) -> String; + } + + #[cgp_impl(new ReadName)] + impl Namer { + fn first(&self, #[implicit] name: &str) -> String { + name.to_owned() + } + + fn second(&self, #[implicit] name: &str) -> String { + name.to_uppercase() + } + } + + #[derive(HasField)] + pub struct Sample { + pub width: f64, + pub height: f64, + pub slice: [u8; 3], + pub counter: u64, + pub name: String, + } + + delegate_components! { + Sample { + NamerComponent: ReadName, + } + } + + check_components! { + Sample { + NamerComponent, + } + } + + #[test] + fn the_expansion_behaves_like_the_macro() { + let mut sample = Sample { + width: 2.0, + height: 3.0, + slice: [1, 2, 3], + counter: 0, + name: "ada".to_owned(), + }; + assert_eq!(RectangleArea::rectangle_area(&sample), 6.0); + // An array field qualifies for a `&[u8]` argument through `AsRef<[u8]>`. + assert_eq!(sample.slice_len(), 3); + sample.bump_counter(); + assert_eq!(sample.counter, 1); + assert_eq!((sample.first(), sample.second()), ("ada".to_owned(), "ADA".to_owned())); + } +} + +/// ## Common Mistakes +/// +/// Reads that differ only in how they borrow agree on one field type. The rejected snippets are +/// trybuild fixtures. +pub mod common_mistakes { + use cgp::prelude::*; + + #[cgp_component(Namer)] + pub trait CanName { + fn borrowed(&self) -> String; + fn owned(&self) -> String; + } + + #[cgp_impl(new ReadName)] + impl Namer { + fn borrowed(&self, #[implicit] name: &str) -> String { + name.to_owned() + } + + fn owned(&self, #[implicit] name: String) -> String { + name + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + NamerComponent: ReadName, + } + } + + check_components! { + Person { + NamerComponent, + } + } +} diff --git a/example-code/tests/reference/attributes/mod.rs b/example-code/tests/reference/attributes/mod.rs index 9194b15d..cfc1d548 100644 --- a/example-code/tests/reference/attributes/mod.rs +++ b/example-code/tests/reference/attributes/mod.rs @@ -1,5 +1,12 @@ //! Code from the pages under `docs/reference/attributes/`. pub mod default_impl; +pub mod derive_delegate; +pub mod extend; +pub mod extend_where; pub mod impl_generics; +pub mod implicit; pub mod prefix; +pub mod use_provider; +pub mod use_type; +pub mod uses; diff --git a/example-code/tests/reference/attributes/prefix.rs b/example-code/tests/reference/attributes/prefix.rs index 56964df3..76645bf1 100644 --- a/example-code/tests/reference/attributes/prefix.rs +++ b/example-code/tests/reference/attributes/prefix.rs @@ -291,3 +291,63 @@ pub mod under_the_hood { assert_eq!(App.greet(), "Hello!"); } } + +/// ## Common Mistakes +/// +/// Two mistakes that compile: a doubled marker on a component without type parameters, which the +/// shorter path key still catches, and a prefix on `#[cgp_auto_getter]`, which is dropped. +pub mod common_mistakes { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + #[prefix(@app.GreeterComponent in DefaultNamespace)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + pub struct App; + + delegate_components! { + App { + namespace DefaultNamespace; + + @app.GreeterComponent: GreetHello, + } + } + + check_components! { + App { + GreeterComponent, + } + } + + #[cgp_auto_getter] + #[prefix(@app in DefaultNamespace)] + pub trait HasName { + fn name(&self) -> &str; + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[test] + fn both_compile() { + assert_eq!(App.greet(), "Hello!"); + assert_eq!( + Person { + name: "Ada".to_owned() + } + .name(), + "Ada" + ); + } +} diff --git a/example-code/tests/reference/attributes/use_provider.rs b/example-code/tests/reference/attributes/use_provider.rs new file mode 100644 index 00000000..c9855bd9 --- /dev/null +++ b/example-code/tests/reference/attributes/use_provider.rs @@ -0,0 +1,282 @@ +//! Code from `docs/reference/attributes/use_provider.md` — *`#[use_provider]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/attributes/`. + +/// ## Usage +/// +/// Several traits on one provider, several stacked providers, a lifetime-carrying provider +/// trait, and the trailing-`+` and empty-list forms the grammar allows. +pub mod usage { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_component(PerimeterCalculator)] + pub trait CanCalculatePerimeter { + fn perimeter(&self) -> f64; + } + + #[cgp_impl(new RectangleShape)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(RectangleShape)] + impl PerimeterCalculator { + fn perimeter(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + 2.0 * (width + height) + } + } + + #[cgp_impl(new AreaPlusPerimeter)] + #[use_provider(Inner: AreaCalculator + PerimeterCalculator)] + impl AreaCalculator { + fn area(&self) -> f64 { + Inner::area(self) + Inner::perimeter(self) + } + } + + #[cgp_impl(new AreaTimesPerimeter)] + #[use_provider(A: AreaCalculator)] + #[use_provider(P: PerimeterCalculator)] + impl AreaCalculator { + fn area(&self) -> f64 { + A::area(self) * P::perimeter(self) + } + } + + #[cgp_impl(new TrailingPlus)] + #[use_provider(Inner: AreaCalculator +)] + impl AreaCalculator { + fn area(&self) -> f64 { + Inner::area(self) + } + } + + #[cgp_impl(new Constant)] + #[use_provider(Inner:)] + impl AreaCalculator { + fn area(&self) -> f64 { + 1.0 + } + } + + #[cgp_component(Namer)] + pub trait CanName<'a> { + fn name(&self, name: &'a str) -> &'a str; + } + + #[cgp_impl(new SameName)] + impl<'a> Namer<'a> { + fn name(&self, name: &'a str) -> &'a str { + name + } + } + + #[cgp_impl(new ForwardName)] + #[use_provider(Inner: Namer<'a>)] + impl<'a, Inner> Namer<'a> { + fn name(&self, name: &'a str) -> &'a str { + Inner::name(self, name) + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + + delegate_components! { + Rectangle { + AreaCalculatorComponent: AreaPlusPerimeter, + PerimeterCalculatorComponent: RectangleShape, + NamerComponent: ForwardName, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + PerimeterCalculatorComponent, + } + } + + #[test] + fn every_form_composes() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.area(), 16.0); + assert_eq!( + as AreaCalculator>::area( + &rect + ), + 60.0 + ); + assert_eq!( + as AreaCalculator>::area(&rect), + 6.0 + ); + assert_eq!( as AreaCalculator>::area(&rect), 1.0); + assert_eq!(rect.name("ada"), "ada"); + } +} + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(new ScaledArea)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + let base_area = InnerCalculator::area(self); + base_area * scale_factor * scale_factor + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: ScaledArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + pub type ScaledRectangle = ScaledArea; + + #[cgp_fn] + #[use_provider(RectangleArea: AreaCalculator)] + pub fn rect_area(&self) -> f64 { + RectangleArea::area(self) + } + + #[test] + fn the_wrapper_scales_the_inner_area() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + scale_factor: 2.0, + }; + assert_eq!(rect.area(), 24.0); + assert_eq!(>::area(&rect), 24.0); + assert_eq!(rect.rect_area(), 6.0); + } +} + +/// ## When to use it +/// +/// A wrapper whose parameter defaults to `UseContext`, declared by hand, falls back to the +/// context's own wiring. The page names `IterSum` without defining it; here it sums the areas of +/// a context's shapes, reading each through the context's wiring for that shape. +pub mod when_to_use_it { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct IterSum(pub PhantomData); + + #[cgp_impl(IterSum)] + #[use_provider(Inner: AreaCalculator)] + impl AreaCalculator> { + fn area(&self, shapes: &Vec) -> f64 { + shapes.iter().map(|shape| Inner::area(self, shape)).sum() + } + } + + pub struct Square(pub f64); + + #[cgp_impl(new SquareArea)] + impl AreaCalculator { + fn area(&self, square: &Square) -> f64 { + square.0 * square.0 + } + } + + pub struct App; + + delegate_components! { + App { + open AreaCalculatorComponent; + + @AreaCalculatorComponent.Square: SquareArea, + @AreaCalculatorComponent.Vec: IterSum, + } + } + + check_components! { + App { + AreaCalculatorComponent: [Square, Vec], + } + } + + #[test] + fn the_default_reads_the_context_wiring() { + assert_eq!(App.area(&vec![Square(1.0), Square(2.0)]), 5.0); + } +} + +/// ## Under the hood +pub mod under_the_hood { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[cgp_impl(new ScaledArea)] + #[use_provider(InnerCalculator: AreaCalculator)] + impl AreaCalculator { + fn area(&self, #[implicit] scale_factor: f64) -> f64 { + InnerCalculator::area(self) * scale_factor * scale_factor + } + } + + #[cgp_fn] + #[use_provider(RectangleArea: AreaCalculator)] + pub fn rect_area(&self) -> f64 { + RectangleArea::area(self) + } +} diff --git a/example-code/tests/reference/attributes/use_type.rs b/example-code/tests/reference/attributes/use_type.rs new file mode 100644 index 00000000..ca36bd68 --- /dev/null +++ b/example-code/tests/reference/attributes/use_type.rs @@ -0,0 +1,477 @@ +//! Code from `docs/reference/attributes/use_type.md` — *`#[use_type]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/attributes/`. Type +//! equalities are checked by assigning one `PhantomData` to a binding typed with the other. + +/// ## Overview +/// +/// The error-type import, on a component whose context picks `String` as its error type. +pub mod overview { + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + #[cgp_component(Greeter)] + #[use_type(HasErrorType.Error)] + pub trait CanGreet { + fn greet(&self) -> Result; + } + + #[cgp_impl(new GreetOrFail)] + #[use_type(HasErrorType.Error)] + impl Greeter { + fn greet(&self) -> Result { + Ok("hello".to_owned()) + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + GreeterComponent: GreetOrFail, + } + } + + check_components! { + App { + GreeterComponent, + } + } + + #[test] + fn the_method_names_only_the_bare_error() { + assert_eq!(App.greet(), Ok("hello".to_owned())); + } +} + +/// ## Usage, Importing several types, Pinning a type to a concrete one, and Importing from another +/// type +/// +/// One function per form the sections name. The page names the traits without declaring them. +pub mod usage { + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar; + } + + pub mod errors { + pub use cgp::prelude::HasErrorType; + } + + pub trait HasFooType { + type Foo; + type Bar; + } + + #[cgp_type] + pub trait HasUserIdType { + type UserId; + } + + #[cgp_type] + pub trait HasCurrencyType { + type Currency; + } + + #[cgp_type] + pub trait HasPasswordType { + type Password; + } + + #[cgp_type] + pub trait HasHashedPasswordType { + type HashedPassword; + } + + #[cgp_type] + pub trait HasDbType { + type Db; + } + + pub trait HasPoolType { + type Pool; + } + + #[cgp_type] + pub trait HasTransactionType { + type Transaction; + } + + pub struct Tx(pub Db); + + pub struct X; + pub struct Y; + + #[cgp_fn] + #[use_type(HasScalarType.Scalar)] + pub fn scalar(&self, value: Scalar) -> Scalar { + value + } + + #[cgp_fn] + #[use_type(errors::HasErrorType.Error)] + pub fn error_by_path(&self, error: Error) -> Error { + error + } + + #[cgp_fn] + #[use_type(HasFooType.Foo)] + pub fn foo_of_x(&self, foo: Foo) -> Foo { + foo + } + + #[cgp_fn] + #[use_type(HasUserIdType.UserId, HasCurrencyType.Currency, HasErrorType.Error)] + pub fn charge(&self, _user: UserId, _amount: Currency) -> Result<(), Error> { + Ok(()) + } + + #[cgp_fn] + #[use_type(HasFooType.{Foo, Bar as Baz})] + pub fn renamed(&self, foo: Foo, baz: Baz) -> (Foo, Baz) { + (foo, baz) + } + + #[cgp_fn] + #[use_type(HasFooType.{Foo as FooX}, HasFooType.{Foo as FooY})] + pub fn two_instantiations(&self, x: FooX, y: FooY) -> (FooX, FooY) { + (x, y) + } + + #[cgp_fn] + #[use_type(HasScalarType.{})] + pub fn bound_only(&self) -> ::Scalar + where + ::Scalar: Default, + { + Default::default() + } + + #[cgp_fn] + #[use_type(HasUserIdType.UserId)] + #[use_type(HasCurrencyType.Currency)] + pub fn stacked(&self, user: UserId, amount: Currency) -> (UserId, Currency) { + (user, amount) + } + + #[cgp_fn] + #[use_type(HasErrorType.{Error = String})] + pub fn pinned(&self) -> Error { + "pinned".to_owned() + } + + #[cgp_fn] + #[use_type(HasFooType.{Foo = u32})] + pub fn pinned_generic(&self) -> Foo { + 7 + } + + #[cgp_fn] + #[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})] + pub fn hash(&self, password: Password) -> HashedPassword { + password + } + + #[cgp_fn] + #[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})] + pub fn begin(&self, db: Db) -> Transaction { + Tx(db) + } + + #[cgp_fn] + #[use_type(HasScalarType.Scalar in Types)] + pub fn scalar_of(&self, value: Scalar) -> Scalar { + value + } + + #[cgp_fn] + #[use_type(HasDbType.Db, HasPoolType.Pool)] + pub fn pool(&self, pool: Pool) -> Pool { + pool + } + + pub struct App; + + delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + cgp::core::error::ErrorTypeProviderComponent: UseType, + UserIdTypeProviderComponent: UseType, + CurrencyTypeProviderComponent: UseType, + PasswordTypeProviderComponent: UseType, + HashedPasswordTypeProviderComponent: UseType, + DbTypeProviderComponent: UseType, + TransactionTypeProviderComponent: UseType>, + } + } + + impl HasFooType for App { + type Foo = u32; + type Bar = bool; + } + + impl HasPoolType for App { + type Pool = &'static str; + } + + #[test] + fn every_form_resolves_against_the_wiring() { + assert_eq!(App.scalar(1.5), 1.5); + assert_eq!(App.error_by_path("e".to_owned()), "e"); + assert_eq!(App.foo_of_x(3), 3); + assert_eq!(App.charge(1, 2), Ok(())); + assert_eq!(App.renamed(1, true), (1, true)); + assert_eq!(App.two_instantiations(1, 2), (1, 2)); + assert_eq!(App.bound_only(), 0.0); + assert_eq!(App.stacked(1, 2), (1, 2)); + assert_eq!(App.pinned(), "pinned"); + assert_eq!(App.pinned_generic(), 7); + assert_eq!(App.hash("pw".to_owned()), "pw"); + assert_eq!(App.begin(4).0, 4); + assert_eq!(ScalarOf::::scalar_of(&App, 2.5), 2.5); + assert_eq!(App.pool("main"), "main"); + } +} + +/// ## Examples +pub mod examples { + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Clone + Mul; + } + + #[cgp_component(AreaCalculator)] + #[use_type(HasScalarType.Scalar)] + pub trait CanCalculateArea { + fn area(&self) -> Scalar; + } + + #[cgp_impl(new RectangleArea)] + #[use_type(HasScalarType.Scalar)] + impl AreaCalculator { + fn area(&self, #[implicit] width: Scalar, #[implicit] height: Scalar) -> Scalar { + width * height + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + ScalarTypeProviderComponent: UseType, + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self, path: &str) -> Result; + } + + #[test] + fn the_context_picks_the_scalar() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.area(), 6.0); + } +} + +/// ## When to use it +/// +/// A construct's own associated type stays qualified beside a bare imported one. +pub mod when_to_use_it { + use cgp::prelude::*; + + #[cgp_component(Parser)] + #[use_type(HasErrorType.Error)] + pub trait CanParse { + type Output; + + fn parse(&self, input: &str) -> Result; + } +} + +/// ## Under the hood +/// +/// The listing's input and its hand-written expansion, the foreign-context trait, the +/// expression-path rewrite and its unit-struct boundary, the header rewrite, and a chain written +/// back to front. +pub mod under_the_hood { + use core::ops::Mul; + + use cgp::prelude::*; + + #[cgp_type] + pub trait HasScalarType { + type Scalar: Clone + Mul; + } + + #[cgp_fn] + #[use_type(HasScalarType.Scalar)] + pub fn area(&self, #[implicit] width: Scalar, #[implicit] height: Scalar) -> Scalar { + width * height + } + + pub trait AreaExpanded: HasScalarType { + fn area_expanded(&self) -> ::Scalar; + } + + impl<__Context__> AreaExpanded for __Context__ + where + Self: HasField::Scalar> + + HasField::Scalar>, + Self: HasScalarType, + { + fn area_expanded(&self) -> ::Scalar { + let width: ::Scalar = + self.get_field(PhantomData::).clone(); + let height: ::Scalar = + self.get_field(PhantomData::).clone(); + width * height + } + } + + #[cgp_fn] + #[use_type(HasScalarType.Scalar in Types)] + pub fn area_of(&self, scalar: Scalar) -> Scalar { + scalar + } + + pub trait Begin { + fn begin() -> Self; + } + + #[cgp_type] + pub trait HasTransactionType { + type Transaction: Begin; + } + + #[cgp_fn] + #[use_type(HasTransactionType.Transaction)] + pub fn start(&self) -> Transaction { + Transaction::begin() + } + + pub struct Marker; + + #[cgp_type] + pub trait HasMarkerType { + type Marker; + } + + #[cgp_fn] + #[use_type(HasMarkerType.Marker)] + pub fn markers(&self, typed: Marker) -> Marker { + // The page's `todo!()` is replaced by the argument. + let _value = Marker; // stays the unit struct `Marker` + typed + } + + #[cgp_component(ErrorParser)] + pub trait CanParseWith { + fn parse_with(&self, input: &str) -> Error; + } + + #[cgp_impl(new ParseToError)] + #[use_type(HasErrorType.Error)] + impl ErrorParser { + fn parse_with(&self, input: &str) -> Error { + let _ = input; + todo!() + } + } + + pub trait HasA { + type A; + } + + pub trait HasB { + type B; + } + + pub trait HasC { + type C; + } + + #[cgp_fn] + #[use_type(HasC.C in B, HasB.B in A, HasA.A)] + pub fn chain(&self, c: C) -> C { + c + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub struct Tx; + + impl Begin for Tx { + fn begin() -> Self { + Tx + } + } + + delegate_components! { + Rectangle { + ScalarTypeProviderComponent: UseType, + TransactionTypeProviderComponent: UseType, + MarkerTypeProviderComponent: UseType, + cgp::core::error::ErrorTypeProviderComponent: UseType, + ErrorParserComponent: ParseToError, + } + } + + impl HasA for Rectangle { + type A = Rectangle; + } + + impl HasB for Rectangle { + type B = Rectangle; + } + + impl HasC for Rectangle { + type C = u16; + } + + check_components! { + Rectangle { + ErrorParserComponent: String, + } + } + + #[test] + fn the_rewrites_resolve() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.area(), 6.0); + assert_eq!(rect.area_expanded(), rect.area()); + assert_eq!(AreaOf::::area_of(&rect, 1.0), 1.0); + let Tx = rect.start(); + assert_eq!(rect.markers(9), 9); + assert_eq!(rect.chain(5), 5); + } +} diff --git a/example-code/tests/reference/attributes/uses.rs b/example-code/tests/reference/attributes/uses.rs new file mode 100644 index 00000000..7be8757d --- /dev/null +++ b/example-code/tests/reference/attributes/uses.rs @@ -0,0 +1,243 @@ +//! Code from `docs/reference/attributes/uses.md` — *`#[uses]`*. +//! +//! The snippets the page rejects live under `tests/compile_fail/reference/attributes/`. + +/// ## Overview and Usage +/// +/// The import list forms: one attribute with several entries, an ordinary Rust trait, a trait +/// with type arguments, split attributes, and the wider bound forms the section lists. +pub mod usage { + use core::fmt::Display; + + use cgp::core::error::ErrorTypeProviderComponent; + use cgp::prelude::*; + + #[cgp_fn] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_fn] + #[uses(RectangleArea, CanCalculateArea)] + pub fn both_areas(&self) -> f64 { + self.rectangle_area() + self.area() + } + + #[cgp_fn] + #[uses(Display, AsRef<[u8]>)] + pub fn describe_bytes(&self) -> String { + format!("{} ({} bytes)", self, self.as_ref().len()) + } + + #[cgp_fn] + #[uses(RectangleArea)] + #[uses(Display)] + pub fn labelled_area(&self) -> String { + format!("{}: {}", self, self.rectangle_area()) + } + + #[cgp_fn] + #[uses(HasErrorType)] + pub fn fail(&self) -> Result<(), String> { + Err("failed".to_owned()) + } + + #[cgp_fn] + #[uses('static, for<'a> PartialEq<&'a str>)] + pub fn is_ada(&self) -> bool { + *self == "ada" + } + + #[cgp_fn] + #[uses()] + pub fn nothing(&self) -> u8 { + 0 + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(new RectangleAreaCalculator)] + #[uses(RectangleArea)] + impl AreaCalculator { + fn area(&self) -> f64 { + self.rectangle_area() + } + } + + impl Display for Rectangle { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "rectangle") + } + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleAreaCalculator, + ErrorTypeProviderComponent: UseType, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + #[test] + fn every_form_imports() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.both_areas(), 12.0); + assert_eq!(rect.labelled_area(), "rectangle: 6"); + assert_eq!(rect.fail(), Err("failed".to_owned())); + assert_eq!("hello".to_owned().describe_bytes(), "hello (5 bytes)"); + assert!("ada".is_ada()); + assert_eq!(rect.nothing(), 0); + } +} + +/// ## Examples +/// +/// Both examples, with the value context the page wires for the second. +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_fn] + #[uses(CanCalculateArea)] + pub fn scaled_area(&self, #[implicit] scale_factor: f64) -> f64 { + self.area() * scale_factor * scale_factor + } + + #[cgp_fn] + pub fn rectangle_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[cgp_impl(new RectangleAreaCalculator)] + #[uses(RectangleArea)] + impl AreaCalculator { + fn area(&self) -> f64 { + self.rectangle_area() + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleAreaCalculator, + } + } + + check_components! { + Rectangle { + AreaCalculatorComponent, + } + } + + /// A context with a scale factor gains `scaled_area` through its wired provider. + #[derive(HasField)] + pub struct ScaledRectangle { + pub width: f64, + pub height: f64, + pub scale_factor: f64, + } + + delegate_components! { + ScaledRectangle { + AreaCalculatorComponent: RectangleAreaCalculator, + } + } + + check_components! { + ScaledRectangle { + AreaCalculatorComponent, + } + } + + #[test] + fn the_provider_and_the_function_compose() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.area(), 6.0); + + let scaled = ScaledRectangle { + width: 2.0, + height: 3.0, + scale_factor: 2.0, + }; + assert_eq!(scaled.scaled_area(), 24.0); + } +} + +/// ## Under the hood +/// +/// The listing's input, and the stacked form the section says produces the same predicate. The +/// page names `BaseArea` without declaring it. +pub mod under_the_hood { + use core::fmt::Display; + + use cgp::prelude::*; + + #[cgp_fn] + pub fn base_area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + + #[cgp_fn] + #[uses(BaseArea, Display)] + pub fn describe_area(&self) -> String { + format!("{} for {}", self.base_area(), self) + } + + #[cgp_fn] + #[uses(BaseArea)] + #[uses(Display)] + pub fn describe_area_stacked(&self) -> String { + format!("{} for {}", self.base_area(), self) + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + impl Display for Rectangle { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "rectangle") + } + } + + #[test] + fn both_forms_describe() { + let rect = Rectangle { + width: 2.0, + height: 3.0, + }; + assert_eq!(rect.describe_area(), "6 for rectangle"); + assert_eq!(rect.describe_area_stacked(), rect.describe_area()); + } +} From 9e1a95d2055aca5f304de4d412f75bda5e0a0dfb Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 01:35:46 +0000 Subject: [PATCH 118/516] Tighten the attribute pages after review Link the context terms the examples introduced to the glossary, qualify the overview's claim about misplaced attributes, reorder a paragraph on the extend page, and pin the aliased-pin rule of #[use_type] in its mirror. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/attributes/derive_delegate.md | 3 ++- docs/reference/attributes/extend.md | 27 +++++++++---------- docs/reference/attributes/impl_generics.md | 2 +- docs/reference/attributes/implicit.md | 9 ++++--- docs/reference/attributes/index.md | 5 ++-- docs/reference/attributes/use_provider.md | 2 +- docs/reference/attributes/use_type.md | 5 ++-- docs/reference/attributes/uses.md | 2 +- .../tests/reference/attributes/use_type.rs | 8 ++++++ 9 files changed, 37 insertions(+), 26 deletions(-) diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 7a04beda..8c8822f3 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -150,7 +150,8 @@ check_components! { } ``` -`MyApp` is an environmental context and the component is parameter-targeted: the shape is the +`MyApp` is an [environmental context](/docs/reference/glossary#environmental-context) and the component is +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component): the shape is the parameter, and `MyApp` carries only the wiring. **Write the same result without the attribute instead.** Drop `#[derive_delegate]` from the component and diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 82729c89..7a88b00d 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -176,11 +176,10 @@ where } ``` -Callers see the supertrait, and the predicate on the implementation lets the body call the methods. The -`#[extend]` entries share that one `Self:` predicate with any [`#[uses]`](uses.md) entries on the same -function, the `#[extend]` ones first. +Callers see the supertrait, and the predicate on the implementation lets the body call the methods. Compare [`#[uses]`](uses.md), which emits only the predicate and leaves the trait declaration bare. -That single difference is the whole of the distinction. +That single difference is the whole of the distinction. When a function carries both attributes, +their entries share the one `Self:` predicate, the `#[extend]` entries first. On a `#[cgp_component]` the supertrait goes on the consumer trait, and it also joins the `where` clause of the generated consumer blanket implementation, because that implementation can only apply where the @@ -218,10 +217,10 @@ Rust does not let an implementation assume a trait's `where` bound, so every pro `__Context__: HasName` itself. That is why the provider in [Examples](#examples) carries `#[uses(HasName)]` even though the component already names the trait. -Here the result is identical to `pub trait CanGreet: HasName`, so on a component `#[extend]` generates -only what the language can already express. It remains the preferred form because it presents the bound -as an import rather than as inheritance, and because it keeps the `use`/`pub use` pairing with `#[uses]` -reading consistently across both macros. +The consumer trait is identical to `pub trait CanGreet: HasName`, so on a component `#[extend]` +generates only what the language can already express. It remains the preferred form because it +presents the bound as an import rather than as inheritance, and because it keeps the `use`/`pub use` +pairing with `#[uses]` reading consistently across both macros. ## Formal grammar @@ -232,12 +231,12 @@ The attribute argument is a comma-separated list of bounds, in the Rust Referenc ExtendArgs -> TypeParamBound ( `,` TypeParamBound )* `,`? ``` -This is the same production [`#[uses]`](uses.md) accepts, the Rust grammar's own bound, so a lifetime, a -`?Sized`, or an associated-type equality parses as readily as a plain trait name. Rust still rejects a -relaxed bound on a trait, so `#[extend(?Sized)]` fails with -`relaxed bounds are not permitted in supertrait bounds`. The list may be empty, -and the attribute may be repeated, with every occurrence's entries collected together. The two attributes -differ in where the bounds land, not in the grammar. +This is the same production [`#[uses]`](uses.md) accepts, the Rust grammar's own bound, so a +lifetime, a `?Sized`, or an associated-type equality parses as readily as a plain trait name. Rust +still rejects a relaxed bound on a trait, so `#[extend(?Sized)]` fails with +`relaxed bounds are not permitted in supertrait bounds`. The list may be empty, and the attribute +may be repeated, with every occurrence's entries collected together. The two attributes differ in +where the bounds land, not in the grammar. ## Common Mistakes diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 3ff7d28b..8d9fc699 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -109,7 +109,7 @@ pub fn greet_both(person: &Person, robot: &Robot) { `Person` and `Robot` both implement `Greet` through the one [blanket implementation](/docs/reference/glossary#blanket-implementation), without any wiring. For `Person` the compiler resolves `Name` to `String`, and for `Robot` to `u32`. Neither type -appears anywhere except in the field. Both are value contexts: the greeting reads the data each type +appears anywhere except in the field. Both are [value contexts](/docs/reference/glossary#value-context): the greeting reads the data each type holds. A trait built on `greet` never learns that `Name` exists: diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index 1e315149..e0b9ca46 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -144,7 +144,7 @@ pub fn print_area(rect: &Rectangle) { ``` `Rectangle` derives [`HasField`](../derives/derive_has_field.md), and that derive is all it needs to -qualify. The program does not wire anything. `Rectangle` is a value context: the data the method +qualify. The program does not wire anything. `Rectangle` is a [value context](/docs/reference/glossary#value-context): the data the method computes on is the context itself. A mutable argument modifies a field in place. It is the function's only implicit argument, under a @@ -172,9 +172,10 @@ impl EmailSender { ``` Callers still write `app.send_email(to, body)`. The provider's requirement from its context, an -`smtp_server` field borrowed here as a `&str` from a `String`, never appears in the trait everyone else -calls. The context here is an environmental one, an `app` that carries the application's settings -rather than being the data a method acts on. +`smtp_server` field borrowed here as a `&str` from a `String`, never appears in the trait everyone +else calls. The context here is an +[environmental context](/docs/reference/glossary#environmental-context), an `app` that carries the +application's settings rather than being the data a method acts on. ## When to use it diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index 7a267ec6..c6829343 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -11,8 +11,9 @@ An attribute here is a modifier, not a macro of its own. Each one is an option t to refine the trait or implementation it generates. The hosts are [`#[cgp_impl]`](../macros/cgp_impl.md), [`#[cgp_fn]`](../macros/cgp_fn.md), and [`#[cgp_component]`](../macros/cgp_component.md), together with the macros built on -`#[cgp_component]`. Each attribute works only on the hosts its page names. Anywhere else nothing reads -it, and the compiler reports it as an attribute it cannot find. This page groups every attribute in +`#[cgp_component]`. Each attribute works only on the hosts its page names. Anywhere else the compiler +usually reports it as an attribute it cannot find, and each page's Common Mistakes names the +exceptions, such as a `#[prefix]` that `#[cgp_auto_getter]` accepts and drops. This page groups every attribute in this section by the job it does, in roughly the order most CGP code uses them. If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here. This page diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 7e198b58..192070fc 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -113,7 +113,7 @@ impl AreaCalculator { ``` A context then composes the two when it wires the component, and `ScaledArea` computes a -rectangle's area and scales it. `Rectangle` is a value context, the shape being measured, and it carries +rectangle's area and scales it. `Rectangle` is a [value context](/docs/reference/glossary#value-context), the shape being measured, and it carries the fields both layers read: ```rust diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index fbf14622..34d432de 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -105,7 +105,8 @@ type. One import can therefore tie two abstract types together: #[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})] ``` -and `#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits +An alias nested inside the right-hand side is grounded in place, so +`#[use_type(HasDbType.Db, HasTransactionType.{Transaction = Tx})]` emits `Self: HasTransactionType::Db>>`. The one name the macro leaves alone on the right-hand side is the pinned alias itself, so a pin such as `{Foo = Foo}` fails with ``cannot find type `Foo` in this scope`` rather than becoming a bound that says nothing. @@ -169,7 +170,7 @@ The component gains `HasScalarType` as a [supertrait](/docs/reference/glossary#s `Scalar` in both becomes the same qualified projection, so the fields the provider reads and the value it returns are guaranteed to agree on whatever scalar the context chose. -A context supplies the concrete type by wiring, and nothing above changes. `Rectangle` is a value context, +A context supplies the concrete type by wiring, and nothing above changes. `Rectangle` is a [value context](/docs/reference/glossary#value-context), the shape whose area is being computed: ```rust diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index e2be9d47..8089147d 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -114,7 +114,7 @@ impl AreaCalculator { This provider is a short adapter: it satisfies the `AreaCalculator` component by calling whatever `rectangle_area` computes. Any context with the fields that trait needs can wire it, as a `Rectangle` -does here. `Rectangle` is a value context, the shape whose area is being computed: +does here. `Rectangle` is a [value context](/docs/reference/glossary#value-context), the shape whose area is being computed: ```rust #[derive(HasField)] diff --git a/example-code/tests/reference/attributes/use_type.rs b/example-code/tests/reference/attributes/use_type.rs index ca36bd68..5cb2804a 100644 --- a/example-code/tests/reference/attributes/use_type.rs +++ b/example-code/tests/reference/attributes/use_type.rs @@ -169,6 +169,13 @@ pub mod usage { 7 } + /// A pin on a renamed import binds the associated type's own name, `Bar`. + #[cgp_fn] + #[use_type(HasFooType.{Bar as Flag = bool})] + pub fn flag(&self, flag: Flag) -> Flag { + flag + } + #[cgp_fn] #[use_type(HasPasswordType.Password, HasHashedPasswordType.{HashedPassword = Password})] pub fn hash(&self, password: Password) -> HashedPassword { @@ -229,6 +236,7 @@ pub mod usage { assert_eq!(App.stacked(1, 2), (1, 2)); assert_eq!(App.pinned(), "pinned"); assert_eq!(App.pinned_generic(), 7); + assert!(App.flag(true)); assert_eq!(App.hash("pw".to_owned()), "pw"); assert_eq!(App.begin(4).0, 4); assert_eq!(ScalarOf::::scalar_of(&App, 2.5), 2.5); From 286b357f7c9763a842443ceb520716d75da0a69f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 01:45:50 +0000 Subject: [PATCH 119/516] Revise the derive reference pages against their mirrors Resync all of docs/reference/derives/ with the internal documents and the cgp source, rename each mirror's modules after the page headings, and add fixtures for every rejection a page describes. Corrections: FromVariant's tag cannot be inferred from the payload type once an enum has two variants (E0283), and a garbled sentence in its Examples is rewritten. The pages gain the known issues only the internal documents carried: a Deref target's fields collide with derived HasField impls, the mutable Deref blanket impl needs a 'static target, and the builder and extractor companions copy field and variant helper attributes of other derives. Each rejection now quotes its message, and the overview gains its provenance note. serde becomes an example-code dev-dependency for the helper-attribute fixtures. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/derives/derive_build_field.md | 23 ++++- docs/reference/derives/derive_cgp_data.md | 15 +++- docs/reference/derives/derive_cgp_record.md | 13 ++- docs/reference/derives/derive_cgp_variant.md | 9 +- .../reference/derives/derive_extract_field.md | 36 +++++++- docs/reference/derives/derive_from_variant.md | 28 ++++-- docs/reference/derives/derive_has_field.md | 48 ++++++++++- docs/reference/derives/derive_has_fields.md | 7 +- docs/reference/derives/index.md | 19 +++- example-code/Cargo.toml | 1 + ..._common_mistakes_field_helper_attribute.rs | 14 +++ ...mon_mistakes_field_helper_attribute.stderr | 8 ++ .../derives/derive_build_field_usage_enum.rs | 9 ++ .../derive_build_field_usage_enum.stderr | 5 ++ .../derive_cgp_data_under_the_hood_union.rs | 10 +++ ...erive_cgp_data_under_the_hood_union.stderr | 8 ++ .../derive_cgp_record_common_mistakes_enum.rs | 9 ++ ...ive_cgp_record_common_mistakes_enum.stderr | 5 ++ ...ariant_common_mistakes_reserved_variant.rs | 13 +++ ...nt_common_mistakes_reserved_variant.stderr | 20 +++++ ...rive_cgp_variant_common_mistakes_struct.rs | 9 ++ ..._cgp_variant_common_mistakes_struct.stderr | 5 ++ ..._field_common_mistakes_reserved_variant.rs | 16 ++++ ...ld_common_mistakes_reserved_variant.stderr | 20 +++++ ...ommon_mistakes_variant_helper_attribute.rs | 16 ++++ ...n_mistakes_variant_helper_attribute.stderr | 12 +++ .../derive_extract_field_usage_struct.rs | 9 ++ .../derive_extract_field_usage_struct.stderr | 5 ++ ...ariant_common_mistakes_reserved_variant.rs | 11 +++ ...nt_common_mistakes_reserved_variant.stderr | 20 +++++ ...m_variant_common_mistakes_untagged_call.rs | 23 +++++ ...riant_common_mistakes_untagged_call.stderr | 19 ++++ .../derive_from_variant_usage_struct.rs | 7 ++ .../derive_from_variant_usage_struct.stderr | 5 ++ ...s_field_common_mistakes_deref_collision.rs | 25 ++++++ ...eld_common_mistakes_deref_collision.stderr | 9 ++ ...ield_under_the_hood_mutable_through_box.rs | 16 ++++ ..._under_the_hood_mutable_through_box.stderr | 16 ++++ .../derives/derive_has_field_usage_enum.rs | 9 ++ .../derive_has_field_usage_enum.stderr | 5 ++ ...fields_common_mistakes_reserved_variant.rs | 10 +++ ...ds_common_mistakes_reserved_variant.stderr | 20 +++++ .../derives/derive_has_fields_usage_union.rs | 10 +++ .../derive_has_fields_usage_union.stderr | 8 ++ .../reference/derives/derive_build_field.rs | 36 +++++++- .../reference/derives/derive_cgp_data.rs | 4 +- .../reference/derives/derive_cgp_record.rs | 60 +++++++++++++ .../reference/derives/derive_cgp_variant.rs | 38 ++++++++ .../reference/derives/derive_extract_field.rs | 15 +++- .../reference/derives/derive_from_variant.rs | 4 +- .../reference/derives/derive_has_field.rs | 19 +++- .../reference/derives/derive_has_fields.rs | 86 ++++++++++++++++++- 52 files changed, 829 insertions(+), 38 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_usage_enum.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_usage_enum.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_usage_struct.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_usage_struct.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_usage_struct.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_usage_struct.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_field_usage_enum.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_field_usage_enum.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_fields_usage_union.rs create mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_fields_usage_union.stderr diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index ed6e4b94..49a25662 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -58,7 +58,8 @@ carried onto the companion type and every generated impl. A fieldless struct produces a builder that can be finalized immediately. Its companion does not need field-state parameters because it has nothing to track. -The derive parses a struct, so applying it to an enum fails at parse time. The enum counterparts are +The derive parses a struct, so applying it to an enum fails at parse time with ``expected `struct` ``. +The enum counterparts are [`#[derive(ExtractField)]`](./derive_extract_field.md) for taking one apart and [`#[derive(FromVariant)]`](./derive_from_variant.md) for constructing one. @@ -289,6 +290,26 @@ missing field. attributes. Read a set field through the companion's `HasField` implementation when inspecting a partial value. +**A field attribute that belongs to another derive breaks the build.** The companion copies each +field's attributes but none of the struct's derives, so a helper attribute such as `serde`'s lands on +a struct that does not derive `Serialize`: + +```rust +#[derive(Serialize, BuildField)] +pub struct Person { + #[serde(rename = "name")] + pub first_name: String, +} +``` + +```text +error: cannot find attribute `serde` in this scope +``` + +A struct therefore cannot combine `BuildField`, or [`CgpRecord`](./derive_cgp_record.md) or +[`CgpData`](./derive_cgp_data.md), with a derive whose field helper attributes it uses. Plain field +attributes such as `#[doc]` and `#[allow]` are harmless. + **`build_from` needs `HasFields` on its source in addition to `BuildField`.** Deriving only `BuildField` on both structs leaves the source without the field list that the conversion traverses. The error reports an unsatisfied [`HasFields`](./derive_has_fields.md) bound on the source. diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 7fd3cdbd..7908defa 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -144,7 +144,9 @@ implementations. Derive only the parts you need when the full set of operations [`CgpVariant`](./derive_cgp_variant.md#under-the-hood) call those paths directly, which is why their output matches. Their pages show the generated implementations. -All three derives reject unions. The family models structs and enums. +All three derives reject unions, since the family models structs and enums. `CgpData` reports +`expect body to be either a struct or enum`, while `CgpRecord` and `CgpVariant` report +``expected `struct` `` and ``expected `enum` `` for any input of the wrong kind. ## Common Mistakes @@ -158,6 +160,17 @@ The following restrictions apply when choosing the combined derive. are rejected, and individual variants cannot opt out. [`HasFields`](./derive_has_fields.md) accepts all of these shapes when only a representation and whole-value conversions are needed. +**Seven variant names are reserved on an enum.** `Fields`, `FieldsRef`, `Value`, `Remainder`, +`Extractor`, `ExtractorRef`, and `ExtractorMut` make a generated path ambiguous. The +[variant page](./derive_cgp_variant.md#common-mistakes) explains which collisions name the variant. + +**A field attribute that belongs to another derive breaks the build.** The builder's companion copies +each field's attributes, so a `serde` helper attribute beside `#[derive(Serialize, CgpData)]` lands on a +struct that does not derive `Serialize` and fails with ``cannot find attribute `serde` in this scope``. +The extractor's companion enums copy variant attributes the same way, so a `serde` helper on a variant +fails too. [`#[derive(BuildField)]`](./derive_build_field.md#common-mistakes) and +[`#[derive(ExtractField)]`](./derive_extract_field.md#common-mistakes) show the two cases. + **Record and variant absence use different markers.** `IsNothing` represents a missing record field; `IsVoid` represents a ruled-out variant. An error mentioning the wrong marker usually means record and variant operations have been mixed. diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index 48d40ff1..c01ca5bf 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -19,7 +19,8 @@ per-field access, a representation of the whole struct, and a builder that fills Generic code can use these operations without naming the concrete struct. `CgpRecord` accepts only structs. It produces the same output as -[`CgpData`](./derive_cgp_data.md) on a struct, but rejects an enum at parse time. +[`CgpData`](./derive_cgp_data.md) on a struct, but rejects an enum at parse time with +``expected `struct` ``. ## Usage @@ -35,8 +36,9 @@ pub struct Person { } ``` -Every struct shape is accepted. Named fields use [`Symbol!`](../macros/symbol.md) tags, and tuple -fields use [`Index`](../types/index_type.md) tags. A fieldless struct produces a companion without +Every struct shape is accepted. Named fields use [`Symbol!`](../macros/symbol.md) tags, a +raw-identifier field such as `r#type` is tagged by its plain name `Symbol!("type")`, and tuple fields +use [`Index`](../types/index_type.md) tags. A fieldless struct produces a companion without field-state parameters, so its `builder()` can be finalized immediately. Generic parameters, lifetimes, and a `where` clause are carried onto everything generated, including @@ -181,6 +183,11 @@ which this derive inherits. **A fieldless struct has an immediately finalizable builder.** Its companion does not need field-state parameters. +**A field attribute that belongs to another derive breaks the build.** The builder's companion copies +each field's attributes, so a `serde` helper attribute beside `#[derive(Serialize, CgpRecord)]` lands on a +struct that does not derive `Serialize` and fails with ``cannot find attribute `serde` in this scope``. +[`#[derive(BuildField)]`](./derive_build_field.md#common-mistakes) shows the case. + **`CgpRecord` rejects enums.** Use [`CgpVariant`](./derive_cgp_variant.md) or [`CgpData`](./derive_cgp_data.md) for an enum. diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 7c4462ef..0d81a19a 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -20,7 +20,8 @@ individually while tracking which remain possible. Generic code can use these op naming the concrete enum. `CgpVariant` accepts only enums. It produces the same output as -[`CgpData`](./derive_cgp_data.md) on an enum, but rejects a struct at parse time. +[`CgpData`](./derive_cgp_data.md) on an enum, but rejects a struct at parse time with +``expected `enum` ``. ## Usage @@ -224,6 +225,12 @@ variant operations have been mixed. **A variantless enum is accepted.** It produces empty companion enums without field-state parameters. +**A variant attribute that belongs to another derive breaks the build.** The extractor's companion +enums copy each variant's attributes, so a `serde` helper attribute beside +`#[derive(Serialize, CgpVariant)]` lands on an enum that does not derive `Serialize` and fails with +``cannot find attribute `serde` in this scope``. +[`#[derive(ExtractField)]`](./derive_extract_field.md#common-mistakes) shows the case. + **`CgpVariant` rejects structs.** Use [`CgpRecord`](./derive_cgp_record.md) or [`CgpData`](./derive_cgp_data.md) for a struct. diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 43966808..85c88232 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -89,7 +89,8 @@ single-field requirement. representation and whole-value conversions are needed. `ExtractField` also accepts a variantless enum; its companion enums do not need field-state parameters. -The derive parses an enum, so applying it to a struct fails at parse time. The struct analogue is +The derive parses an enum, so applying it to a struct fails at parse time with ``expected `enum` ``. The +struct analogue is [`#[derive(BuildField)]`](./derive_build_field.md). ### What it does *not* generate @@ -113,7 +114,8 @@ extractor back into the original enum. ## Examples -`finalize_extract_result` returns the last payload once the chain has ruled out every other variant: +`finalize_extract_result` returns the last payload once the chain has ruled out every other variant. +`Circle` and `Rectangle` are payload structs with `radius`, and `width` and `height`, fields: ```rust use cgp::core::field::traits::FinalizeExtractResult; @@ -307,12 +309,38 @@ rename the conflicting variant. [`HasFields`](./derive_has_fields.md) also reser enum does not implement them for the companion. Use `.ok()`, `.is_ok()`, or a `match` to inspect the result instead of printing or comparing the whole `Result`. +**A variant attribute that belongs to another derive breaks the build.** The companion enums copy each +variant's attributes but none of the enum's derives, so a helper attribute such as `serde`'s lands on an +enum that does not derive `Serialize`: + +```rust +#[derive(Serialize, ExtractField)] +pub enum Shape { + #[serde(rename = "circle")] + Circle(Circle), +} +``` + +```text +error: cannot find attribute `serde` in this scope +``` + +An enum therefore cannot combine `ExtractField`, or [`CgpVariant`](./derive_cgp_variant.md) or +[`CgpData`](./derive_cgp_data.md), with a derive whose variant helper attributes it uses. + **`FinalizeExtractResult` is not in the prelude.** Import it from `cgp::core::field::traits` to call `finalize_extract_result`. **Finalizing early does not compile, and the error names the companion.** The all-void impl does not apply -while any marker is still `IsPresent`, so the compiler reports a missing method. Read the companion type in -the message to see which variants are still possible. +while any marker is still `IsPresent`, so the method's trait bounds fail. After only the `Circle` attempt +in the example above: + +```text +error[E0599]: the method `finalize_extract_result` exists for enum `Result>`, but its trait bounds were not satisfied +``` + +Read the companion type in the message to see which variants are still possible: here `Rectangle`, +whose marker is still `IsPresent`. **Every variant must be ruled out before finalizing the remainder.** Extraction order is unrestricted because each step changes only its own variant's marker. diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index ab1c2e06..3f7b3abc 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -70,8 +70,8 @@ pub enum Shape { representation and whole-value conversions are needed. `FromVariant` accepts a variantless enum but does not emit any implementations for it. -The derive parses an enum, so applying it to a struct fails at parse time. The struct analogue, setting one -field of a value being assembled, is [`#[derive(BuildField)]`](./derive_build_field.md). +The derive parses an enum, so applying it to a struct fails at parse time with ``expected `enum` ``. The +struct analogue, setting one field of a value being assembled, is [`#[derive(BuildField)]`](./derive_build_field.md). ### What it does *not* generate @@ -112,8 +112,10 @@ The `FromVariant` bound connects each tag to its payload type and construct interface, `Shape::Circle` and `Shape::Rectangle` remain separate expressions with different argument types. -Upcasting lets an implementation construct a small local enum and convert it into a larger one. -The implementation only needs to know the variants Each generated implementation selects its constructor through the variant-name tag: +Upcasting lets an implementation construct a small local enum and convert it into a larger one, so the +implementation only needs to know the variants it constructs. Here both enums derive +[`CgpData`](./derive_cgp_data.md), which supplies the constructors and the representation the cast +reads: ```rust use cgp::core::field::impls::CanUpcast; // not in the prelude @@ -189,9 +191,21 @@ underlines that variant rather than the whole `#[derive(FromVariant)]`. **Every variant must carry exactly one unnamed payload.** Individual variants cannot opt out. [`HasFields`](./derive_has_fields.md) accepts all variant shapes when only a representation is needed. -**Specify the tag when the payload does not determine the variant.** In -`Shape::from_variant(PhantomData::, value)`, the type argument selects `Circle`. -The payload type alone cannot distinguish variants that share that type. +**Specify the tag whenever the enum has more than one variant.** In +`Shape::from_variant(PhantomData::, value)`, the type argument selects `Circle`. The +payload type does not select the implementation, even when every variant's payload type is different, +so an untagged call fails: + +```text +error[E0283]: type annotations needed + | + | let _ = Shape::from_variant(PhantomData, Circle { radius: 2.0 }); + | ----- ^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the struct `PhantomData` + | | + | type must be known at this point +``` + +Only an enum with a single variant lets the compiler infer the tag. **Variants sharing a payload type have distinct tags.** A tag that does not match an implemented variant produces an unsatisfied `FromVariant` bound. diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 5f24d58c..143eb30b 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -98,8 +98,8 @@ pub struct Wrapper { ### What it does not accept -The derive parses its input as a struct, so applying it to an enum or a union fails at parse time. The -whole-shape view of a struct *or* an enum is a different derive, +The derive parses its input as a struct, so applying it to an enum or a union fails at parse time with +``expected `struct` ``. The whole-shape view of a struct *or* an enum is a different derive, [`#[derive(HasFields)]`](./derive_has_fields.md) (note the plural), and the two are frequently derived together. @@ -140,9 +140,17 @@ delegate_components! { GreeterComponent: GreetHello, } } + +check_components! { + Person { + GreeterComponent, + } +} ``` `Person` satisfies the field bound required by `GreetHello`, so `person.greet()` prints its name. +`Person` is a [value context](/docs/reference/glossary#value-context): the greeting reads data the +context itself holds. Removing the `name` field prevents the call from compiling because the required `HasField` implementation is missing. @@ -243,6 +251,8 @@ the same way, and a borrowed field type is kept verbatim as `Value`. The library supplies smart-pointer access through blanket implementations of `HasField` and `HasFieldMut`. Shared access requires [`Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html), and mutable access requires `DerefMut`, with the target implementing the corresponding field trait. +The mutable blanket implementation also requires the target to be `'static`, so mutable access through +a `Box>` does not resolve, while shared access does. The blanket implementations are marked to keep the compiler from recommending them in missing-field diagnostics, directing attention to the underlying struct. @@ -267,6 +277,40 @@ types. A spelling mismatch produces an unsatisfied `HasField` bound. **The mutable accessor is always generated.** The derive does not offer a read-only mode. Limit mutation through the access bounds and references supplied to implementations. +**A struct that implements `Deref` cannot derive a field its target also has.** The `Deref` blanket +implementation already gives the struct every field of its target, so a derived accessor for the same +name overlaps it: + +```rust +use core::ops::Deref; + +#[derive(HasField)] +pub struct Inner { + pub name: String, +} + +#[derive(HasField)] +pub struct Outer { + pub inner: Inner, + pub name: String, +} + +impl Deref for Outer { + type Target = Inner; + + fn deref(&self) -> &Inner { + &self.inner + } +} +``` + +```text +error[E0119]: conflicting implementations of trait `cgp::prelude::HasField>>>>>` for type `Outer` +``` + +Fields whose names the target lacks derive without trouble. Rename the colliding field, drop the +`Deref` implementation, or write the needed accessors by hand. + **It does not accept an enum.** `#[derive(HasField)]` parses a struct. The plural [`#[derive(HasFields)]`](./derive_has_fields.md) is the one that takes both, and the near-identical names are easy to confuse. diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 33d5cf8b..2178363c 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -54,8 +54,8 @@ pub enum Shape { For a struct the shape is a product; for an enum it is a sum. Naming follows the same rules everywhere: a named field or a variant is keyed by [`Symbol!`](../macros/symbol.md), a positional field by -[`Index`](../types/index_type.md). Applying the derive to anything other than a struct or an enum is a -compile error. +[`Index`](../types/index_type.md). Applying the derive to anything other than a struct or an enum, such +as a union, fails with `expect body to be either a struct or enum`. ### Struct shapes @@ -296,7 +296,8 @@ code written against a literal `Cons` chain does not. **Variants named `Fields` or `FieldsRef` make generated paths ambiguous.** The implementations use `Self::Fields` and `Self::FieldsRef`, which conflict with variants of those names. The compiler -reports `ambiguous associated item` at the derive and points to the offending variant in a note. +reports `ambiguous associated item`, a lint that denies the build by default, at the derive, and points +to the offending variant in a note. Rename that variant. The [extractor](./derive_extract_field.md) and [constructor](./derive_from_variant.md) derives reserve additional names, so check their restrictions when deriving the full family. diff --git a/docs/reference/derives/index.md b/docs/reference/derives/index.md index 18bb607e..6794d45f 100644 --- a/docs/reference/derives/index.md +++ b/docs/reference/derives/index.md @@ -16,7 +16,8 @@ derives once you are familiar with the essentials. ## Reading a value from a context -Use `HasField` to access individual fields and `HasFields` to process a type's whole structure. +Use `HasField` to access individual fields and `HasFields` to process a type's whole structure. The +context is the type the method runs on, which supplies the values it needs as its fields. [`#[derive(HasField)]`](./derive_has_field.md) lets an implementation read a struct field by a type-level tag. The implementation declares the field it needs as a trait bound. An @@ -56,9 +57,21 @@ The individual derives provide these operations: `BuildField` accepts structs. `ExtractField` and `FromVariant` accept enums and are commonly derived together. -## One restriction to know before you reach for them +## Restrictions to know before you reach for them The enum constructor and extractor derives require every variant to carry exactly one unnamed payload. This restriction applies to `FromVariant`, `ExtractField`, `CgpData`, and `CgpVariant`; individual variants cannot opt out. `HasFields` accepts every variant shape and provides a structural -representation with whole-value conversions, so it can be used with enums that mix variant shapes. \ No newline at end of file +representation with whole-value conversions, so it can be used with enums that mix variant shapes. + +The builder and extractor derives also generate companion types that copy each field's or variant's +attributes but not the original type's derives. A helper attribute that belongs to another derive, +such as `serde`'s `#[serde(rename = "…")]`, therefore fails to compile on a type that also derives +`BuildField`, `ExtractField`, or one of the umbrella derives. The +[`BuildField`](./derive_build_field.md#common-mistakes) page shows the error. + +--- + +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index 6f1d1165..2b68949d 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -12,6 +12,7 @@ cgp = "0.8.0-alpha" anyhow = "1" cap-std = "3" futures = "0.3" +serde = { version = "1", features = ["derive"] } trybuild = "1" diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs b/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs new file mode 100644 index 00000000..c9d1da41 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs @@ -0,0 +1,14 @@ +use cgp::prelude::*; +use serde::Serialize; + +// error: cannot find attribute `serde` in this scope +// +// The companion `__PartialPerson` copies each field's attributes but not the struct's derives, so +// the `serde` helper lands on a struct that does not derive `Serialize`. +#[derive(Serialize, BuildField)] +pub struct Person { + #[serde(rename = "name")] + pub first_name: String, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.stderr new file mode 100644 index 00000000..df056ca3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.stderr @@ -0,0 +1,8 @@ +error: cannot find attribute `serde` in this scope + --> tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs:10:7 + | +10 | #[serde(rename = "name")] + | ^^^^^ + | + = note: `serde` is an attribute that can be used by the derive macros `Deserialize` and `Serialize`, you might be missing a `derive` attribute + = note: `serde` is in scope, but it is a crate, not an attribute diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_usage_enum.rs b/example-code/tests/compile_fail/reference/derives/derive_build_field_usage_enum.rs new file mode 100644 index 00000000..6568e0ef --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_usage_enum.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: expected `struct` +#[derive(BuildField)] +pub enum Shape { + Circle(f64), +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_usage_enum.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_usage_enum.stderr new file mode 100644 index 00000000..294e0493 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_usage_enum.stderr @@ -0,0 +1,5 @@ +error: expected `struct` + --> tests/compile_fail/reference/derives/derive_build_field_usage_enum.rs:5:5 + | +5 | pub enum Shape { + | ^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.rs b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.rs new file mode 100644 index 00000000..dbe805fd --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: expect body to be either a struct or enum +#[derive(CgpData)] +pub union Bits { + small: u8, + large: u16, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.stderr new file mode 100644 index 00000000..cc402438 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.stderr @@ -0,0 +1,8 @@ +error: expect body to be either a struct or enum + --> tests/compile_fail/reference/derives/derive_cgp_data_under_the_hood_union.rs:5:1 + | +5 | / pub union Bits { +6 | | small: u8, +7 | | large: u16, +8 | | } + | |_^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.rs b/example-code/tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.rs new file mode 100644 index 00000000..0b9872b6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: expected `struct` +#[derive(CgpRecord)] +pub enum Shape { + Circle(f64), +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.stderr new file mode 100644 index 00000000..305d17f9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.stderr @@ -0,0 +1,5 @@ +error: expected `struct` + --> tests/compile_fail/reference/derives/derive_cgp_record_common_mistakes_enum.rs:5:5 + | +5 | pub enum Shape { + | ^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs new file mode 100644 index 00000000..1ca479fe --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs @@ -0,0 +1,13 @@ +use cgp::prelude::*; + +pub struct Payload; +pub struct Other; + +// error: ambiguous associated item +#[derive(CgpVariant)] +pub enum Slot { + Remainder(Payload), + Other(Other), +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr new file mode 100644 index 00000000..ae20c25c --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr @@ -0,0 +1,20 @@ +error: ambiguous associated item + --> tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs:7:10 + | + 7 | #[derive(CgpVariant)] + | ^^^^^^^^^^ + | +note: `Remainder` could refer to the variant defined here + --> tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs:7:10 + | + 7 | #[derive(CgpVariant)] + | ^^^^^^^^^^ +note: `Remainder` could also refer to the associated type defined here + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:33:5 + | +33 | type Remainder; + | ^^^^^^^^^^^^^^ + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57644 + = note: `#[deny(ambiguous_associated_items)]` (part of `#[deny(future_incompatible)]`) on by default + = note: this error originates in the derive macro `CgpVariant` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.rs b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.rs new file mode 100644 index 00000000..a1186fba --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: expected `enum` +#[derive(CgpVariant)] +pub struct Circle { + pub radius: f64, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.stderr new file mode 100644 index 00000000..88269263 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.stderr @@ -0,0 +1,5 @@ +error: expected `enum` + --> tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_struct.rs:5:5 + | +5 | pub struct Circle { + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs new file mode 100644 index 00000000..ac6a03c6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs @@ -0,0 +1,16 @@ +use cgp::prelude::*; + +pub struct Payload; +pub struct Other; + +// error: ambiguous associated item +// +// Both the headline and the note land on the derive: the colliding variant is the generated +// companion's, whose identifiers carry the derive's span. +#[derive(ExtractField)] +pub enum Slot { + Value(Payload), + Other(Other), +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr new file mode 100644 index 00000000..4e88983e --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr @@ -0,0 +1,20 @@ +error: ambiguous associated item + --> tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs:10:10 + | +10 | #[derive(ExtractField)] + | ^^^^^^^^^^^^ + | +note: `Value` could refer to the variant defined here + --> tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs:10:10 + | +10 | #[derive(ExtractField)] + | ^^^^^^^^^^^^ +note: `Value` could also refer to the associated type defined here + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:31:5 + | +31 | type Value; + | ^^^^^^^^^^ + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57644 + = note: `#[deny(ambiguous_associated_items)]` (part of `#[deny(future_incompatible)]`) on by default + = note: this error originates in the derive macro `ExtractField` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs new file mode 100644 index 00000000..7482266d --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs @@ -0,0 +1,16 @@ +use cgp::prelude::*; +use serde::Serialize; + +#[derive(Serialize)] +pub struct Circle { + pub radius: f64, +} + +// error: cannot find attribute `serde` in this scope +#[derive(Serialize, ExtractField)] +pub enum Shape { + #[serde(rename = "circle")] + Circle(Circle), +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.stderr new file mode 100644 index 00000000..e08c3bcd --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.stderr @@ -0,0 +1,12 @@ +error: cannot find attribute `serde` in this scope + --> tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs:12:7 + | +12 | #[serde(rename = "circle")] + | ^^^^^ + | + = note: `serde` is in scope, but it is a crate, not an attribute +help: `serde` is an attribute that can be used by the derive macros `Deserialize` and `Serialize`, you might be missing a `derive` attribute + | +11 + #[derive(Deserialize, Serialize)] +12 | pub enum Shape { + | diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_usage_struct.rs b/example-code/tests/compile_fail/reference/derives/derive_extract_field_usage_struct.rs new file mode 100644 index 00000000..bbe2193b --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_usage_struct.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: expected `enum` +#[derive(ExtractField)] +pub struct Circle { + pub radius: f64, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_usage_struct.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_usage_struct.stderr new file mode 100644 index 00000000..08ab0651 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_usage_struct.stderr @@ -0,0 +1,5 @@ +error: expected `enum` + --> tests/compile_fail/reference/derives/derive_extract_field_usage_struct.rs:5:5 + | +5 | pub struct Circle { + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs new file mode 100644 index 00000000..147a1724 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs @@ -0,0 +1,11 @@ +use cgp::prelude::*; + +pub struct Payload; + +// error: ambiguous associated item +#[derive(FromVariant)] +pub enum Slot { + Value(Payload), +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr new file mode 100644 index 00000000..1df1f07b --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr @@ -0,0 +1,20 @@ +error: ambiguous associated item + --> tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs:6:10 + | +6 | #[derive(FromVariant)] + | ^^^^^^^^^^^ + | +note: `Value` could refer to the variant defined here + --> tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs:8:5 + | +8 | Value(Payload), + | ^^^^^ +note: `Value` could also refer to the associated type defined here + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/from_variant.rs:4:5 + | +4 | type Value; + | ^^^^^^^^^^ + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57644 + = note: `#[deny(ambiguous_associated_items)]` (part of `#[deny(future_incompatible)]`) on by default + = note: this error originates in the derive macro `FromVariant` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.rs b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.rs new file mode 100644 index 00000000..e1cbbf07 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.rs @@ -0,0 +1,23 @@ +use cgp::prelude::*; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(FromVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn main() { + // error[E0283]: type annotations needed + // + // The payload type does not select the variant, so the tag must be written. + let _ = Shape::from_variant(PhantomData, Circle { radius: 2.0 }); +} diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.stderr b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.stderr new file mode 100644 index 00000000..baa53e2d --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.stderr @@ -0,0 +1,19 @@ +error[E0283]: type annotations needed + --> tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.rs:22:33 + | +22 | let _ = Shape::from_variant(PhantomData, Circle { radius: 2.0 }); + | ----- ^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the struct `PhantomData` + | | + | type must be known at this point + | +note: multiple `impl`s satisfying `Shape: cgp::prelude::FromVariant<_>` found + --> tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_untagged_call.rs:14:5 + | +14 | Circle(Circle), + | ^^^^^^ +15 | Rectangle(Rectangle), + | ^^^^^^^^^ +help: consider specifying a concrete type for the type parameter `T` + | +22 | let _ = Shape::from_variant(PhantomData::, Circle { radius: 2.0 }); + | ++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_usage_struct.rs b/example-code/tests/compile_fail/reference/derives/derive_from_variant_usage_struct.rs new file mode 100644 index 00000000..211664e1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_usage_struct.rs @@ -0,0 +1,7 @@ +use cgp::prelude::*; + +// error: expected `enum` +#[derive(FromVariant)] +pub struct Circle(pub f64); + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_usage_struct.stderr b/example-code/tests/compile_fail/reference/derives/derive_from_variant_usage_struct.stderr new file mode 100644 index 00000000..241496f1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_usage_struct.stderr @@ -0,0 +1,5 @@ +error: expected `enum` + --> tests/compile_fail/reference/derives/derive_from_variant_usage_struct.rs:5:5 + | +5 | pub struct Circle(pub f64); + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.rs b/example-code/tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.rs new file mode 100644 index 00000000..1eca78ab --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.rs @@ -0,0 +1,25 @@ +use core::ops::Deref; + +use cgp::prelude::*; + +#[derive(HasField)] +pub struct Inner { + pub name: String, +} + +// error[E0119]: conflicting implementations of trait `HasField>` for type `Outer` +#[derive(HasField)] +pub struct Outer { + pub inner: Inner, + pub name: String, +} + +impl Deref for Outer { + type Target = Inner; + + fn deref(&self) -> &Inner { + &self.inner + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.stderr b/example-code/tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.stderr new file mode 100644 index 00000000..35aa2ecd --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.stderr @@ -0,0 +1,9 @@ +error[E0119]: conflicting implementations of trait `cgp::prelude::HasField>>>>>` for type `Outer` + --> tests/compile_fail/reference/derives/derive_has_field_common_mistakes_deref_collision.rs:14:9 + | +14 | pub name: String, + | ^^^^ + | + = note: conflicting implementation in crate `cgp_field`: + - impl cgp::prelude::HasField for Context + where ::Target == Target, >::Value == Value, Context: cgp::cgp_core::cgp_field::traits::has_field::DerefMap, Target: cgp::prelude::HasField; diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.rs b/example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.rs new file mode 100644 index 00000000..69b249ed --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.rs @@ -0,0 +1,16 @@ +use cgp::prelude::*; + +#[derive(HasField)] +pub struct Borrowed<'a> { + pub name: &'a str, +} + +// error[E0521]: borrowed data escapes outside of function +// +// The mutable `Deref` blanket impl requires a `'static` target, so `Borrowed<'a>` behind a `Box` +// can be read but not written through it. +pub fn rename<'a>(boxed: &mut Box>) { + let _ = boxed.get_field_mut(PhantomData::); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.stderr b/example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.stderr new file mode 100644 index 00000000..9c3e4584 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.stderr @@ -0,0 +1,16 @@ +error[E0521]: borrowed data escapes outside of function + --> tests/compile_fail/reference/derives/derive_has_field_under_the_hood_mutable_through_box.rs:13:13 + | +12 | pub fn rename<'a>(boxed: &mut Box>) { + | -- ----- `boxed` is a reference that is only valid in the function body + | | + | lifetime `'a` defined here +13 | let _ = boxed.get_field_mut(PhantomData::); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | `boxed` escapes the function body here + | argument requires that `'a` must outlive `'static` + | + = note: requirement occurs because of a mutable reference to `Box>` + = note: mutable references are invariant over their type parameter + = help: see for more information about variance diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_field_usage_enum.rs b/example-code/tests/compile_fail/reference/derives/derive_has_field_usage_enum.rs new file mode 100644 index 00000000..0b214017 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_field_usage_enum.rs @@ -0,0 +1,9 @@ +use cgp::prelude::*; + +// error: expected `struct` +#[derive(HasField)] +pub enum Shape { + Circle(f64), +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_field_usage_enum.stderr b/example-code/tests/compile_fail/reference/derives/derive_has_field_usage_enum.stderr new file mode 100644 index 00000000..632e4d62 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_field_usage_enum.stderr @@ -0,0 +1,5 @@ +error: expected `struct` + --> tests/compile_fail/reference/derives/derive_has_field_usage_enum.rs:5:5 + | +5 | pub enum Shape { + | ^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs new file mode 100644 index 00000000..18fdf92a --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: ambiguous associated item +#[derive(HasFields)] +pub enum Message { + Fields(u8), + Other(u16), +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr new file mode 100644 index 00000000..2a65b6a1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr @@ -0,0 +1,20 @@ +error: ambiguous associated item + --> tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs:4:10 + | +4 | #[derive(HasFields)] + | ^^^^^^^^^ + | +note: `Fields` could refer to the variant defined here + --> tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs:6:5 + | +6 | Fields(u8), + | ^^^^^^ +note: `Fields` could also refer to the associated type defined here + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/has_fields.rs:2:5 + | +2 | type Fields; + | ^^^^^^^^^^^ + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #57644 + = note: `#[deny(ambiguous_associated_items)]` (part of `#[deny(future_incompatible)]`) on by default + = note: this error originates in the derive macro `HasFields` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_fields_usage_union.rs b/example-code/tests/compile_fail/reference/derives/derive_has_fields_usage_union.rs new file mode 100644 index 00000000..6f2deb97 --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_fields_usage_union.rs @@ -0,0 +1,10 @@ +use cgp::prelude::*; + +// error: expect body to be either a struct or enum +#[derive(HasFields)] +pub union Bits { + small: u8, + large: u16, +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_fields_usage_union.stderr b/example-code/tests/compile_fail/reference/derives/derive_has_fields_usage_union.stderr new file mode 100644 index 00000000..6f6998df --- /dev/null +++ b/example-code/tests/compile_fail/reference/derives/derive_has_fields_usage_union.stderr @@ -0,0 +1,8 @@ +error: expect body to be either a struct or enum + --> tests/compile_fail/reference/derives/derive_has_fields_usage_union.rs:5:1 + | +5 | / pub union Bits { +6 | | small: u8, +7 | | large: u16, +8 | | } + | |_^ diff --git a/example-code/tests/reference/derives/derive_build_field.rs b/example-code/tests/reference/derives/derive_build_field.rs index 9f967f8a..97368674 100644 --- a/example-code/tests/reference/derives/derive_build_field.rs +++ b/example-code/tests/reference/derives/derive_build_field.rs @@ -7,8 +7,8 @@ /// ## Overview /// -/// The opening builder chain. The page shows it against `Person`, which it declares under *Using it*. -pub mod what_its_for { +/// The opening builder chain. The page shows it against `Person`, which it declares under *Usage*. +pub mod overview { use cgp::prelude::*; #[derive(BuildField, Debug, Eq, PartialEq)] @@ -61,7 +61,7 @@ pub mod rejected_build_from_without_has_fields {} /// /// The shapes the page lists: a named-field struct, a tuple struct keyed by position, and the /// fieldless struct whose `builder()` is immediately finalizable. -pub mod using_it { +pub mod usage { use cgp::prelude::*; #[derive(BuildField, Debug, Eq, PartialEq)] @@ -200,3 +200,33 @@ pub mod examples { ); } } + +/// ## Common Mistakes +/// +/// The derives that emit no companion type leave field helper attributes alone, so `serde`'s +/// `rename` coexists with them. The companion-emitting case is a trybuild fixture. +pub mod common_mistakes { + use cgp::prelude::*; + use serde::Serialize; + + #[derive(Serialize, HasField, HasFields)] + pub struct Person { + #[serde(rename = "name")] + pub first_name: String, + } + + #[derive(Serialize, FromVariant)] + pub enum Shape { + #[serde(rename = "circle")] + Circle(f64), + } + + #[test] + fn test_helper_attributes_survive_the_narrow_derives() { + let person = Person { + first_name: "Ada".to_owned(), + }; + assert_eq!(person.get_field(PhantomData::), "Ada"); + let _ = Shape::from_variant(PhantomData::, 1.0); + } +} diff --git a/example-code/tests/reference/derives/derive_cgp_data.rs b/example-code/tests/reference/derives/derive_cgp_data.rs index cb65f642..27eede01 100644 --- a/example-code/tests/reference/derives/derive_cgp_data.rs +++ b/example-code/tests/reference/derives/derive_cgp_data.rs @@ -7,8 +7,8 @@ /// ## Usage /// /// The two inputs the page opens on, the shape-specific faces, and the shapes the page says are -/// accepted. The one it says is rejected is a doctest in the module below this one. -pub mod using_it { +/// accepted. The one it says is rejected is a trybuild fixture, named in the module below this one. +pub mod usage { use cgp::prelude::*; #[derive(Debug, Eq, PartialEq)] diff --git a/example-code/tests/reference/derives/derive_cgp_record.rs b/example-code/tests/reference/derives/derive_cgp_record.rs index 0da0b85c..09db08df 100644 --- a/example-code/tests/reference/derives/derive_cgp_record.rs +++ b/example-code/tests/reference/derives/derive_cgp_record.rs @@ -3,6 +3,52 @@ //! The page's worked example, run. Written with `CgpRecord` rather than the umbrella, which is the //! page's own claim that the two emit the same output on a struct. +/// ## Usage +/// +/// The struct shapes the page lists: a raw-identifier field, a tuple struct keyed by position, a +/// fieldless struct whose builder finalizes at once, and a generic struct. +pub mod usage { + use cgp::prelude::*; + + #[derive(CgpRecord, Debug, Eq, PartialEq)] + pub struct Entry { + pub r#type: String, + } + + #[derive(CgpRecord, Debug, Eq, PartialEq)] + pub struct Pair(pub u32, pub u32); + + #[derive(CgpRecord, Debug, Eq, PartialEq)] + pub struct NoConfig {} + + #[derive(CgpRecord, Debug, Eq, PartialEq)] + pub struct Generic { + pub value: T, + } + + #[test] + fn test_every_shape_builds() { + let entry: Entry = Entry::builder() + .build_field(PhantomData::, "text".to_owned()) + .finalize_build(); + assert_eq!(entry.get_field(PhantomData::), "text"); + + let pair: Pair = Pair::builder() + .build_field(PhantomData::>, 3) + .build_field(PhantomData::>, 4) + .finalize_build(); + assert_eq!(pair, Pair(3, 4)); + + let config: NoConfig = NoConfig::builder().finalize_build(); + assert_eq!(config, NoConfig {}); + + let generic: Generic = Generic::builder() + .build_field(PhantomData::, 1) + .finalize_build(); + assert_eq!(generic, Generic { value: 1 }); + } +} + /// ## Examples /// /// The record half: `promote`, which merges one record into another's builder. @@ -47,3 +93,17 @@ pub mod examples { ); } } + +/// ## Common Mistakes +/// +/// A single-field tuple struct's representation is the inner type, not a one-element product. +pub mod common_mistakes { + use cgp::prelude::*; + + #[derive(CgpRecord)] + pub struct Wrapper(pub String); + + pub fn wrapper_shape(fields: ::Fields) -> String { + fields + } +} diff --git a/example-code/tests/reference/derives/derive_cgp_variant.rs b/example-code/tests/reference/derives/derive_cgp_variant.rs index 1f63a914..244f5de9 100644 --- a/example-code/tests/reference/derives/derive_cgp_variant.rs +++ b/example-code/tests/reference/derives/derive_cgp_variant.rs @@ -5,6 +5,44 @@ /// ## Usage /// +/// The accepted rewrite the page recommends, with a payload struct that derives `CgpRecord`, a +/// generic enum, and the variantless enum it says is accepted. +pub mod usage { + use cgp::prelude::*; + + #[derive(CgpRecord, Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + #[derive(CgpVariant, Debug, PartialEq)] + pub enum Shape { + Circle(Circle), + } + + #[derive(CgpVariant)] + pub enum Generic { + Item(T), + } + + #[derive(CgpVariant)] + pub enum Never {} + + #[test] + fn test_the_payload_struct_is_a_record_too() { + let circle: Circle = Circle::builder() + .build_field(PhantomData::, 2.0) + .finalize_build(); + let shape = Shape::from_variant(PhantomData::, circle); + + assert_eq!(shape, Shape::Circle(Circle { radius: 2.0 })); + assert!(Generic::Item(1u8) + .to_extractor() + .extract_field(PhantomData::) + .is_ok()); + } +} + /// The page's rejected snippet: a struct-style variant has no single payload type, so the derive /// fails. Every variant must carry exactly one unnamed payload, with no per-variant opt-out. /// diff --git a/example-code/tests/reference/derives/derive_extract_field.rs b/example-code/tests/reference/derives/derive_extract_field.rs index 1c3f8e95..3598c4ce 100644 --- a/example-code/tests/reference/derives/derive_extract_field.rs +++ b/example-code/tests/reference/derives/derive_extract_field.rs @@ -8,7 +8,7 @@ /// ## Overview /// /// The opening extraction, and the payload types the page names without declaring. -pub mod what_its_for { +pub mod overview { use cgp::prelude::*; #[derive(Debug, Eq, PartialEq)] @@ -51,7 +51,7 @@ pub mod what_its_for { /// /// The accepted enum, the payload-struct rewrite the page recommends — including for a case that /// carries nothing — and the variantless enum the page says degenerates. -pub mod using_it { +pub mod usage { use cgp::prelude::*; #[derive(Debug, PartialEq)] @@ -90,6 +90,17 @@ pub mod using_it { assert_eq!(extracted, Some(Empty)); } + /// `from_extractor` turns an all-present owned extractor back into the enum. + #[test] + fn test_an_extractor_converts_back() { + let extractor = Shape::Circle(Circle { radius: 1.0 }).to_extractor(); + + assert_eq!( + Shape::from_extractor(extractor), + Shape::Circle(Circle { radius: 1.0 }) + ); + } + #[test] fn test_generics_are_carried_onto_the_companions() { let extracted = Generic::Item(42_u32) diff --git a/example-code/tests/reference/derives/derive_from_variant.rs b/example-code/tests/reference/derives/derive_from_variant.rs index 9b20213d..0e09482e 100644 --- a/example-code/tests/reference/derives/derive_from_variant.rs +++ b/example-code/tests/reference/derives/derive_from_variant.rs @@ -8,7 +8,7 @@ /// ## Overview /// /// The opening claim: `from_variant` with a tag is the same construction as naming the variant. -pub mod what_its_for { +pub mod overview { use cgp::prelude::*; #[derive(Debug, Eq, PartialEq)] @@ -39,7 +39,7 @@ pub mod what_its_for { /// ## Usage /// /// The accepted enum, a generic one, and the variantless enum the page says produces no impls. -pub mod using_it { +pub mod usage { use cgp::prelude::*; #[derive(Debug, Eq, PartialEq)] diff --git a/example-code/tests/reference/derives/derive_has_field.rs b/example-code/tests/reference/derives/derive_has_field.rs index 12219b59..20006cbf 100644 --- a/example-code/tests/reference/derives/derive_has_field.rs +++ b/example-code/tests/reference/derives/derive_has_field.rs @@ -9,7 +9,7 @@ /// /// The page opens on the bound an implementation writes. The component and the context are shown /// further down under *Examples*; they are declared here so the opening bound has something to hold. -pub mod what_its_for { +pub mod overview { use cgp::prelude::*; #[derive(HasField)] @@ -40,7 +40,7 @@ pub mod what_its_for { /// The four struct shapes the page lists, in the order it lists them: named fields, a raw-identifier /// field, tuple fields, a unit struct, and a generic struct. The unit struct is the one whose whole /// point is that it compiles and emits nothing. -pub mod using_it { +pub mod usage { use cgp::prelude::*; #[derive(HasField)] @@ -65,6 +65,21 @@ pub mod using_it { pub value: T, } + /// The *Under the hood* claim that a struct lifetime carries through, with a borrowed field type + /// kept verbatim as `Value`. + #[derive(HasField)] + pub struct Borrowed<'a> { + pub name: &'a str, + } + + #[test] + fn test_a_borrowed_field_keeps_its_type() { + let borrowed = Borrowed { name: "Alice" }; + + let name: &&str = borrowed.get_field(PhantomData::); + assert_eq!(*name, "Alice"); + } + #[test] fn test_named_fields_are_keyed_by_symbol() { let person = Person { diff --git a/example-code/tests/reference/derives/derive_has_fields.rs b/example-code/tests/reference/derives/derive_has_fields.rs index d7b91ba5..95e19238 100644 --- a/example-code/tests/reference/derives/derive_has_fields.rs +++ b/example-code/tests/reference/derives/derive_has_fields.rs @@ -8,7 +8,7 @@ /// ## Overview /// /// The `Fields` type the page opens on, checked by naming it explicitly. -pub mod what_its_for { +pub mod overview { use cgp::prelude::*; #[derive(Clone, Debug, Eq, PartialEq, HasFields)] @@ -42,7 +42,7 @@ pub mod what_its_for { /// /// Every struct and enum shape the page lists. The four struct shapes come first, then the four /// variant shapes in the single enum the page uses for them. -pub mod using_it { +pub mod usage { use cgp::prelude::*; #[derive(Clone, Debug, Eq, PartialEq, HasFields)] @@ -66,6 +66,21 @@ pub mod using_it { pub value: T, } + /// The borrowed view layers its own `'__a` borrow on a borrowed field type. + #[derive(HasFields)] + pub struct Borrowed<'a, Name> { + pub name: &'a Name, + } + + pub fn assert_borrowed_fields<'a, 'b, Name>( + fields: as HasFieldsRef>::FieldsRef<'b>, + ) -> Product![Field] + where + Borrowed<'a, Name>: 'b, + { + fields + } + /// The four variant shapes, all accepted by this derive and by no other in the family. #[derive(Clone, Debug, Eq, PartialEq, HasFields)] pub enum Shape { @@ -170,6 +185,18 @@ pub mod examples { Rectangle(Rectangle), } + pub fn assert_config_fields( + fields: ::Fields, + ) -> Product![Field, Field] { + fields + } + + pub fn assert_shape_fields( + fields: ::Fields, + ) -> Sum![Field, Field] { + fields + } + /// The page's closing claim: generic code bounds on the shape rather than on the type, so one /// function applies to any record that derives it. The page does not show a recursion, so this /// stops at naming the shape. @@ -203,3 +230,58 @@ pub mod examples { assert_eq!(Shape::from_fields(shape.clone().to_fields()), shape); } } + +/// ## Under the hood +/// +/// The listings' inputs, for `cargo cgp expand`, and the variantless enum whose shape is `Void`. +pub mod under_the_hood { + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + #[derive(HasFields)] + pub struct Unit; + + #[derive(HasFields)] + pub enum Never {} + + pub fn assert_never_fields(fields: ::Fields) -> Void { + fields + } +} + +/// ## Common Mistakes +/// +/// Field order is part of the type: two structs with the same fields in different orders have +/// different shapes. The reserved variant name is a trybuild fixture. +pub mod common_mistakes { + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct NameFirst { + pub name: String, + pub age: u8, + } + + #[derive(HasFields)] + pub struct AgeFirst { + pub age: u8, + pub name: String, + } + + pub fn name_first_shape( + fields: ::Fields, + ) -> Product![Field, Field] { + fields + } + + pub fn age_first_shape( + fields: ::Fields, + ) -> Product![Field, Field] { + fields + } +} From 3b581d4ccd0bdf6aa3215b0cd2bdf448d7b8ffb0 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 01:51:03 +0000 Subject: [PATCH 120/516] Tighten the derive pages after review State exactly what an upcast needs of each enum and pin the target-only case in the mirror, add the serde import to the helper-attribute snippets, and split an over-long sentence on the HasFields page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/derives/derive_build_field.md | 2 ++ docs/reference/derives/derive_extract_field.md | 2 ++ docs/reference/derives/derive_from_variant.md | 10 ++++++---- docs/reference/derives/derive_has_fields.md | 6 +++--- .../reference/derives/derive_from_variant.rs | 16 ++++++++++++++++ 5 files changed, 29 insertions(+), 7 deletions(-) diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index 49a25662..e3137469 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -295,6 +295,8 @@ field's attributes but none of the struct's derives, so a helper attribute such a struct that does not derive `Serialize`: ```rust +use serde::Serialize; + #[derive(Serialize, BuildField)] pub struct Person { #[serde(rename = "name")] diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 85c88232..d4f671d6 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -314,6 +314,8 @@ variant's attributes but none of the enum's derives, so a helper attribute such enum that does not derive `Serialize`: ```rust +use serde::Serialize; + #[derive(Serialize, ExtractField)] pub enum Shape { #[serde(rename = "circle")] diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 3f7b3abc..ab64d70c 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -112,10 +112,12 @@ The `FromVariant` bound connects each tag to its payload type and construct interface, `Shape::Circle` and `Shape::Rectangle` remain separate expressions with different argument types. -Upcasting lets an implementation construct a small local enum and convert it into a larger one, so the -implementation only needs to know the variants it constructs. Here both enums derive -[`CgpData`](./derive_cgp_data.md), which supplies the constructors and the representation the cast -reads: +Upcasting lets an implementation construct a small local enum and convert it into a larger one, so +the implementation only needs to know the variants it constructs. The cast walks the source enum's +representation with its extractor and builds each variant with the target's `FromVariant` +constructors, so the source needs [`HasFields`](./derive_has_fields.md) and +[`ExtractField`](./derive_extract_field.md) while the target needs only `FromVariant`. Both enums +derive [`CgpData`](./derive_cgp_data.md) here, which covers either side: ```rust use cgp::core::field::impls::CanUpcast; // not in the prelude diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 2178363c..68f8540f 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -295,9 +295,9 @@ different orders have different `Fields` types. Structural conversions that matc code written against a literal `Cons` chain does not. **Variants named `Fields` or `FieldsRef` make generated paths ambiguous.** The implementations use -`Self::Fields` and `Self::FieldsRef`, which conflict with variants of those names. The compiler -reports `ambiguous associated item`, a lint that denies the build by default, at the derive, and points -to the offending variant in a note. +`Self::Fields` and `Self::FieldsRef`, which conflict with variants of those names. The compiler reports +`ambiguous associated item` at the derive and points to the offending variant in a note. The error +comes from a lint that denies the build by default. Rename that variant. The [extractor](./derive_extract_field.md) and [constructor](./derive_from_variant.md) derives reserve additional names, so check their restrictions when deriving the full family. diff --git a/example-code/tests/reference/derives/derive_from_variant.rs b/example-code/tests/reference/derives/derive_from_variant.rs index 0e09482e..3740b2e4 100644 --- a/example-code/tests/reference/derives/derive_from_variant.rs +++ b/example-code/tests/reference/derives/derive_from_variant.rs @@ -153,6 +153,22 @@ pub mod examples_upcast { Literal(Literal), } + /// A target that derives only `FromVariant`, which is all the cast needs of it. + #[derive(FromVariant, Debug, PartialEq)] + pub enum IdentOrLiteral { + Ident(Ident), + Literal(Literal), + } + + #[test] + fn test_the_target_needs_only_constructors() { + use cgp::core::field::impls::CanUpcast; + + let value = LispSubExpr::Ident(Ident("x".to_owned())).upcast(PhantomData::); + + assert_eq!(value, IdentOrLiteral::Ident(Ident("x".to_owned()))); + } + #[test] fn test_upcast_from_the_narrow_enum() { use cgp::core::field::impls::CanUpcast; From 8d54134fd372a78dafe912414caf20380f3e4997 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 02:13:48 +0000 Subject: [PATCH 121/516] Revise the top-level component reference pages Resync docs/reference/components/ (the overview and the eight top-level component pages) with the internal documents and the cgp source, and give each page the title and description the front-matter convention asks for. Corrections: the CanWrapError usage table routed String to DisplayError, which forwards to the same entry and overflows (E0275), so it now routes String to an application provider; HasType is the tag-indexed abstract type rather than the only one or a substrate the named ones are wired on; the handler variants have pages of their own. The error pages gain #[track_caller] and its propagation, checked against the local cgp, and the E0034 ambiguity of a bare call on a concrete context; the #[prefix] bullets say what the registration does; and every Examples snippet now imports the wiring keys it uses and checks its context. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/components/can_raise_error.md | 41 +++++++--- docs/reference/components/can_wrap_error.md | 81 ++++++++++++++++--- docs/reference/components/has_error_type.md | 27 +++++-- docs/reference/components/has_runtime.md | 30 +++++-- docs/reference/components/has_runtime_type.md | 28 ++++--- docs/reference/components/has_type.md | 74 ++++++++++++----- docs/reference/components/index.md | 18 +++-- docs/reference/components/runner.md | 29 ++++--- docs/reference/components/send_runner.md | 20 +++-- ...ise_error_usage_ambiguous_concrete_call.rs | 20 +++++ ...error_usage_ambiguous_concrete_call.stderr | 16 ++++ ...an_wrap_error_usage_display_error_cycle.rs | 24 ++++++ ...rap_error_usage_display_error_cycle.stderr | 22 +++++ .../reference/components/can_raise_error.rs | 75 ++++++++++++++++- .../reference/components/can_wrap_error.rs | 70 ++++++++++++++-- .../reference/components/has_error_type.rs | 31 ++++--- .../tests/reference/components/has_type.rs | 26 ++++++ .../tests/reference/components/runner.rs | 11 ++- 18 files changed, 531 insertions(+), 112 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.rs create mode 100644 example-code/tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.stderr create mode 100644 example-code/tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.rs create mode 100644 example-code/tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.stderr diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md index 7b552ca5..91a33b9f 100644 --- a/docs/reference/components/can_raise_error.md +++ b/docs/reference/components/can_raise_error.md @@ -1,4 +1,6 @@ --- +title: 'CanRaiseError — raise into the abstract error' +description: 'The component that converts a concrete source error into the context''s abstract error type, dispatching per source error to the provider the context wires.' sidebar_label: 'CanRaiseError' sidebar_position: 2 --- @@ -10,12 +12,12 @@ Turn a concrete source error into the context's abstract `Self::Error`. ## Overview `CanRaiseError` lets generic CGP code produce its context's abstract error from any -concrete error it meets. A provider that calls a fallible operation gets back a specific error type, a -parse error, an I/O error, a string message, but it must return the **context's** abstract `Self::Error`, -whose concrete identity it does not know. The context here is the type a method runs on, which -supplies the values an implementation needs as its own fields, and it decides how each source error maps -into its chosen error type. `CanRaiseError` bridges the gap: generic code writes -`Context::raise_error(source)` and the context converts the concrete `SourceError` into `Self::Error`. +concrete error it meets. A provider that calls a fallible operation gets back a specific error type, +a parse error, an I/O error, a string message, but it must return the **context's** abstract +`Self::Error`, whose concrete identity it does not know. The context here is the type the +implementation runs against, and it decides how each source error maps into its chosen error type. +`CanRaiseError` bridges the gap: generic code writes `Context::raise_error(source)` and +the context converts the concrete `SourceError` into `Self::Error`. Because the trait is parameterized by `SourceError`, one context can know how to raise many different source errors into its single abstract error. This is the "raise" half of CGP's error handling; the @@ -32,6 +34,7 @@ Both build on [`HasErrorType`](./has_error_type.md), which supplies the `Self::E #[derive_delegate(UseDelegate)] #[use_type(HasErrorType.Error)] pub trait CanRaiseError { + #[track_caller] fn raise_error(error: SourceError) -> Error; } ``` @@ -39,7 +42,7 @@ pub trait CanRaiseError { Its attributes: - [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `ErrorRaiser` that implementations target and the wiring key `ErrorRaiserComponent`, while `CanRaiseError` stays the consumer trait callers use. -- [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[prefix]`](../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.core.error`, so a context that joins that namespace binds its provider at `@cgp.core.error.ErrorRaiserComponent.String` rather than at the bare key. - [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `SourceError` type, so a context can route each `SourceError` to its own provider; the `open` statement is the modern sugar for the same dispatch. - [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. @@ -70,6 +73,9 @@ delegate_components! { } ``` +`ParseError` stands for any source error type the application meets. The key comes from +`cgp::core::error` and the providers from `cgp::extra::error`. + The interchangeable strategies that satisfy `CanRaiseError` are the [error providers](../providers/error/index.md): `RaiseFrom` converts through `From`, `DebugError` and `DisplayError` format the source into a string, `ReturnError` returns it unchanged, and so on. The @@ -80,6 +86,22 @@ Because `raise_error` is an associated function, generic code calls it on the co `Context::raise_error(source)` or `Self::raise_error(source)`, without borrowing a context value. This matches how errors are constructed deep inside generic code where only the type parameter is in scope. +Calling it on a concrete context by its bare name, as `App::raise_error(…)`, is ambiguous when the +provider trait `ErrorRaiser` is also in scope, because a context implements the provider trait too. +The compiler reports ``error[E0034]: multiple applicable items in scope``. Name the consumer trait +in that case, as `>::raise_error(…)`, or leave `ErrorRaiser` +unimported. + +**`raise_error` carries `#[track_caller]`, and the attribute survives every layer of forwarding.** +Rust applies `#[track_caller]` on a trait method declaration to every implementation of that method, +and `#[cgp_component]` keeps it on the provider trait's declaration. It therefore covers the +consumer and provider blanket implementations, the `UseDelegate`, `RedirectLookup`, and `UseContext` +implementations, and every provider. An error library that records `Location::caller()`, such as +`eyre` with its `track-caller` feature, records the line that called `raise_error`, whether the +component is wired directly, with `open`, through a namespace path, or through a `UseDelegate` +table. The location survives only while every call between that line and the library is +`#[track_caller]`: a generic helper function without the attribute records its own line instead. + ## Examples A provider raises a concrete error into the context's abstract one: @@ -109,8 +131,9 @@ impl Loader { The provider `LoadOrFail` names neither the context nor its concrete error type. It requires `CanRaiseError` through [`#[uses]`](../attributes/uses.md) to turn a `String` message into the abstract error, and any wired context that satisfies that bound, typically by plugging in an error -backend, makes `load` produce errors in that context's chosen type. The context is an **environmental -context**, and the component targets it rather than a value. +backend, makes `load` produce errors in that context's chosen type. The context is an +**[environmental context](/docs/reference/glossary#environmental-context)**, and the component targets +it rather than a value. ## When to use it diff --git a/docs/reference/components/can_wrap_error.md b/docs/reference/components/can_wrap_error.md index 63a3ea91..5480942d 100644 --- a/docs/reference/components/can_wrap_error.md +++ b/docs/reference/components/can_wrap_error.md @@ -1,4 +1,6 @@ --- +title: 'CanWrapError — add detail to an error' +description: 'The component that folds a piece of detail, such as a message or a path, into an error the context already holds, dispatching per detail type.' sidebar_label: 'CanWrapError' sidebar_position: 3 --- @@ -10,12 +12,12 @@ Attach a piece of detail to an error the context already holds, enriching it as ## Overview `CanWrapError` enriches an error as it travels up a call stack. Where -[`CanRaiseError`](./can_raise_error.md) converts a *foreign* error into the context's abstract error, -`CanWrapError` takes an error the **context** already holds and folds a piece of `Detail` into it, a -message, a span, a path, producing an enriched `Self::Error`. The context is the type a method runs -on, which supplies the values an implementation needs as its own fields, and it decides how detail -is combined with an existing error. Together the two components cover the common error-handling motions -in CGP: raise a foreign error in, then wrap context onto it as it bubbles up. +[`CanRaiseError`](./can_raise_error.md) converts a *foreign* error into the context's abstract +error, `CanWrapError` takes an error the **context** already holds and folds a piece of `Detail` +into it, a message, a span, a path, producing an enriched `Self::Error`. The context is the type the +implementation runs against, and it decides how detail is combined with an existing error. Together +the two components cover the common error-handling motions in CGP: raise a foreign error in, then +wrap context onto it as it bubbles up. Because the trait is parameterized by `Detail`, one context can attach many kinds of detail, each through its own provider, all onto the same abstract error. Like its companion, `CanWrapError` builds on @@ -31,6 +33,7 @@ through its own provider, all onto the same abstract error. Like its companion, #[derive_delegate(UseDelegate)] #[use_type(HasErrorType.Error)] pub trait CanWrapError { + #[track_caller] fn wrap_error(error: Error, detail: Detail) -> Error; } ``` @@ -38,7 +41,7 @@ pub trait CanWrapError { Its attributes: - [`#[cgp_component]`](../macros/cgp_component.md) — turns the trait into a component: its argument names the provider trait `ErrorWrapper` that implementations target and the wiring key `ErrorWrapperComponent`, while `CanWrapError` stays the consumer trait callers use. -- [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[prefix]`](../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.core.error`, so a context that joins that namespace binds its provider at `@cgp.core.error.ErrorWrapperComponent.String` rather than at the bare key. - [`#[derive_delegate]`](../attributes/derive_delegate.md) — generates a `UseDelegate` provider that dispatches on the `Detail` type, so a context can route each `Detail` to its own provider; the `open` statement is the modern sugar for the same dispatch. - [`#[use_type]`](../attributes/use_type.md) — adds `HasErrorType` as a [supertrait](/docs/reference/glossary#supertrait) and rewrites the bare `Error` to `::Error`. @@ -60,22 +63,53 @@ delegate_components! { App { open ErrorWrapperComponent; - @ErrorWrapperComponent.String: DisplayError, + @ErrorWrapperComponent.String: AppendDetail, + @ErrorWrapperComponent.u64: DisplayError, } } ``` +`AppendDetail` is a provider of the application's own that folds a `String` detail into the error; +[Examples](#examples) defines it. [`DisplayError`](../providers/error/display_error.md) formats any +`Display` detail into a `String` and forwards it to the context's own `CanWrapError`, so here a +`u64` detail reaches `AppendDetail` too. The forwarding is why `DisplayError` cannot serve the `String` +entry itself: `@ErrorWrapperComponent.String: DisplayError` sends the lookup back to the same entry, and +the check overflows: + +```text +error[E0275]: overflow evaluating the requirement `App: IsProviderFor` +``` + The [error providers](../providers/error/index.md) supply the strategies that satisfy it, and the standalone backend crates (`cgp-error-anyhow`, `cgp-error-eyre`, `cgp-error-std`) wire wrapping for common detail types, so an application usually plugs in a backend rather than writing wrap logic itself. Because `wrap_error` is an associated function, generic code calls it on the context type, `Context::wrap_error(err, detail)`, without borrowing a context value. +Calling it on a concrete context by its bare name, as `App::wrap_error(…)`, is ambiguous when the +provider trait `ErrorWrapper` is also in scope, because a context implements the provider trait too. +The compiler reports ``error[E0034]: multiple applicable items in scope``. Name the consumer trait +in that case, as `>::wrap_error(…)`, or leave `ErrorWrapper` unimported. + +**`wrap_error` carries `#[track_caller]`, and the attribute survives every layer of forwarding.** +Rust applies `#[track_caller]` on a trait method declaration to every implementation of that method, +and `#[cgp_component]` keeps it on the provider trait's declaration. It therefore covers the +consumer and provider blanket implementations, the `UseDelegate`, `RedirectLookup`, and `UseContext` +implementations, and every provider. An error library that records `Location::caller()`, such as +`eyre` with its `track-caller` feature, records the line that called `wrap_error`, whether the +component is wired directly, with `open`, through a namespace path, or through a `UseDelegate` +table. The location survives only while every call between that line and the library is +`#[track_caller]`: a generic helper function without the attribute records its own line instead. + ## Examples A provider wraps a message onto an error as it propagates: ```rust +use cgp::core::error::{ + ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapper, ErrorWrapperComponent, +}; +use cgp::extra::error::RaiseFrom; use cgp::prelude::*; #[cgp_component(Loader)] @@ -96,13 +130,42 @@ impl Loader { Ok(format!("contents of {path}")) } } + +#[cgp_impl(new AppendDetail)] +#[use_type(HasErrorType.{Error = String})] +impl ErrorWrapper { + fn wrap_error(error: Error, detail: String) -> Error { + format!("{detail}: {error}") + } +} + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + ErrorWrapperComponent: AppendDetail, + LoaderComponent: LoadOrFail, + } +} + +check_components! { + App { + LoaderComponent, + } +} ``` +`App.load("")` returns `Err("while loading : empty path")`. `AppendDetail` pins the abstract error to +`String` with the equality form of [`#[use_type]`](../attributes/use_type.md), since it builds a +`String` directly. + The provider `LoadOrFail` first raises a `String` into the context's abstract error with [`CanRaiseError`](./can_raise_error.md), then wraps a further message onto it with `CanWrapError`. Both dependencies are declared with [`#[uses]`](../attributes/uses.md), so neither appears on the public `CanLoad` signature, and any context that satisfies them makes `load` produce enriched errors in its own -error type. The context is an **[environmental context](/docs/reference/glossary#environmental-context)**, and the component targets it. +error type. `App` here satisfies them with `RaiseFrom` and `AppendDetail`. The context is an **[environmental context](/docs/reference/glossary#environmental-context)**, and the component targets it. ## When to use it diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index 439291f0..1885b6d6 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -1,4 +1,6 @@ --- +title: 'HasErrorType — a context''s abstract error type' +description: 'The component that gives a context one shared, abstract Error type, so fallible generic code never names a concrete error and the context chooses it by wiring.' sidebar_label: 'HasErrorType' sidebar_position: 1 --- @@ -9,10 +11,11 @@ Give a context one shared, abstract `Error` type, so fallible generic code never ## Overview -`HasErrorType` lets generic CGP code fail without committing to a concrete error type. A provider that -may error has to produce *some* error, but it runs against a **context**, the type that implements the trait that supplies the values an implementation needs, and it cannot know whether that context wants -`anyhow::Error`, `std::io::Error`, or an enum of its own. `HasErrorType` resolves this by giving the -context one abstract `Self::Error` type that every fallible operation refers to. Generic code returns +`HasErrorType` lets generic CGP code fail without committing to a concrete error type. A provider +that may error has to produce *some* error, but it runs against a **context**, the type that +implements the trait, and it cannot know whether that context wants `anyhow::Error`, +`std::io::Error`, or an enum of its own. `HasErrorType` resolves this by giving the context one +abstract `Self::Error` type that every fallible operation refers to. Generic code returns `Result`, and the concrete error is decided once, at wiring time, by whichever error backend the context plugs in. @@ -40,7 +43,7 @@ pub type ErrorOf = ::Error; Its attributes: - [`#[cgp_type]`](../macros/cgp_type.md) — makes this an abstract-type component rather than a plain trait: it generates the provider trait, the [component marker](/docs/reference/glossary#component-marker), and a [`UseType`](../providers/use_type.md) impl, so a context binds the concrete type by wiring. -- [`#[prefix]`](../macros/cgp_namespace.md) — registers the generated names into the `@cgp.core.error` path of `DefaultNamespace`, so a context that joins the namespace inherits the wiring by default. +- [`#[prefix]`](../attributes/prefix.md) — registers the component in `DefaultNamespace` under the path `@cgp.core.error`, so a context that joins that namespace binds its provider at `@cgp.core.error.ErrorTypeProviderComponent` rather than at the bare key. ## Usage @@ -79,13 +82,15 @@ supply ready-made providers that set `Error` to their respective types. Generic code names the abstract error with the [`#[use_type]`](../attributes/use_type.md) attribute, which imports it as the bare name `Error`, or through the `ErrorOf` alias, which spells -`::Error`. +`::Error`. `ErrorOf`, the provider trait `ErrorTypeProvider`, and the key +`ErrorTypeProviderComponent` all come from `cgp::core::error`. ## Examples A context declares its abstract error, and generic code returns it without naming a concrete type: ```rust +use cgp::core::error::ErrorTypeProviderComponent; use cgp::prelude::*; #[cgp_component(Validator)] @@ -101,6 +106,12 @@ delegate_components! { ErrorTypeProviderComponent: UseType, } } + +check_components! { + App { + ErrorTypeProviderComponent, + } +} ``` Here [`#[use_type(HasErrorType.Error)]`](../attributes/use_type.md) adds `HasErrorType` as a supertrait @@ -127,8 +138,8 @@ the abstract error to a concrete type, use the equality form - [`#[cgp_type]`](../macros/cgp_type.md) — the macro `HasErrorType` is defined with, which generates its `UseType` provider. -- [`HasType` / `TypeProvider`](./has_type.md) — the built-in abstract-type substrate `#[cgp_type]` - builds this on. +- [`HasType` / `TypeProvider`](./has_type.md) — the tag-indexed abstract-type component; a + `TypeProvider` can back this component through the `WithProvider` impl `#[cgp_type]` generates. - [`CanRaiseError`](./can_raise_error.md) — raises a source error into this abstract error. - [`CanWrapError`](./can_wrap_error.md) — wraps detail onto this abstract error. - [`#[use_type]`](../attributes/use_type.md) — imports the abstract error into a definition as the bare diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index 6c426706..83398b47 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -1,4 +1,6 @@ --- +title: 'HasRuntime — borrow the context''s runtime' +description: 'The getter component that borrows the runtime value a context stores, so effectful generic code reaches Tokio, a mock, or a test executor without naming it.' sidebar_label: 'HasRuntime' sidebar_position: 6 --- @@ -13,8 +15,8 @@ Hand out a borrow of the context's runtime value, so effectful code reaches it g A runtime here is whatever object provides the services an application needs at execution time, spawning tasks, sleeping, opening sockets, reading the clock, and different deployments want different runtimes: Tokio in production, a mock in tests, a single-threaded executor in a benchmark. Rather than -thread a concrete runtime type through every signature, the **context**, the type a method runs -on that supplies the values an implementation needs as its own fields, stores one runtime value, +thread a concrete runtime type through every signature, the **context**, the type the method runs +on, which supplies the values it needs as its fields, stores one runtime value, and `HasRuntime` is the getter that borrows it. `HasRuntime` answers *how to obtain the runtime value*; its companion @@ -44,9 +46,11 @@ Its attributes: ## Usage -`HasRuntime` is imported from `cgp::extra::runtime`. It is a getter component: its method borrows the -runtime value out of a borrow of the context, returning `&Runtime`, where `Runtime` is the [abstract type](/docs/reference/glossary#abstract-type) -supplied by [`HasRuntimeType`](./has_runtime_type.md): +`HasRuntime` is imported from `cgp::extra::runtime`, with its provider trait `RuntimeGetter` and its +key `RuntimeGetterComponent`. None of the runtime names is in the prelude. It is a getter component: +its method borrows the runtime value out of a borrow of the context, returning `&Runtime`, where +`Runtime` is the [abstract type](/docs/reference/glossary#abstract-type) supplied by +[`HasRuntimeType`](./has_runtime_type.md): ```rust fn runtime(&self) -> &Runtime; @@ -68,8 +72,9 @@ delegate_components! { ``` One entry fixes the abstract runtime type, and the other says where the value lives. Context-generic -providers then write `where Self: HasRuntime` and call `self.runtime()` to obtain a `&RuntimeOf`, -never naming the concrete runtime. +providers then depend on `HasRuntime` and call `self.runtime()` to obtain a `&RuntimeOf`, +never naming the concrete runtime. Declare that dependency with +[`#[uses(HasRuntime)]`](../attributes/uses.md) on a provider. ## Examples @@ -78,7 +83,9 @@ generically: ```rust use cgp::prelude::*; -use cgp::extra::runtime::{HasRuntime, HasRuntimeType, RuntimeOf}; +use cgp::extra::runtime::{ + HasRuntime, RuntimeGetterComponent, RuntimeOf, RuntimeTypeProviderComponent, +}; pub struct TokioRuntime { /* handle, clock, etc. */ } @@ -94,6 +101,13 @@ delegate_components! { } } +check_components! { + App { + RuntimeTypeProviderComponent, + RuntimeGetterComponent, + } +} + fn runtime_of(context: &Context) -> &RuntimeOf where Context: HasRuntime, diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md index 38488eb4..f5a4de55 100644 --- a/docs/reference/components/has_runtime_type.md +++ b/docs/reference/components/has_runtime_type.md @@ -1,4 +1,6 @@ --- +title: 'HasRuntimeType — the abstract runtime type' +description: 'The abstract-type component that declares the runtime type a context runs against, chosen per context by wiring, for code that names the type but not a value.' sidebar_label: 'HasRuntimeType' sidebar_position: 7 --- @@ -9,12 +11,11 @@ Declare the abstract runtime *type* a context runs against, chosen per context t ## Overview -`HasRuntimeType` lets context-generic code name the runtime type a context uses without committing to a -concrete one. A runtime is whatever object supplies the services an application needs at execution -time, and different deployments want different runtimes: Tokio in production, a mock in tests, an -executor in a benchmark. `HasRuntimeType` gives the **context**, the type that implements the trait that -supplies the values an implementation needs as its own fields, an abstract associated `Runtime` type, -resolved to a concrete one at wiring time. +`HasRuntimeType` lets context-generic code name the runtime type a context uses without committing +to a concrete one. A runtime is whatever object supplies the services an application needs at +execution time, and different deployments want different runtimes: Tokio in production, a mock in +tests, an executor in a benchmark. `HasRuntimeType` gives the **context**, the type that implements +the trait, an abstract associated `Runtime` type, resolved to a concrete one at wiring time. The runtime abstraction is split into a type component and a getter component because the two questions are independent. `HasRuntimeType` answers *what the runtime type is*, while its companion @@ -42,7 +43,9 @@ Its attributes: ## Usage -`HasRuntimeType` is imported from `cgp::extra::runtime`. It is an abstract-type component with a single +`HasRuntimeType` is imported from `cgp::extra::runtime`, with the `RuntimeOf` alias, the provider trait +`RuntimeTypeProvider`, and the key `RuntimeTypeProviderComponent`. None of them is in the prelude, and +the component carries no `#[prefix]`. It is an abstract-type component with a single associated type, `Runtime`, carrying no bound, so any concrete type may be plugged in. A context supplies the type either by implementing `HasRuntimeType` directly or, more commonly, by wiring `RuntimeTypeProviderComponent` to [`UseType`](../providers/use_type.md): @@ -66,7 +69,7 @@ A context fixes its runtime type, and generic code names it without committing t ```rust use cgp::prelude::*; -use cgp::extra::runtime::{HasRuntimeType, RuntimeOf}; +use cgp::extra::runtime::{HasRuntimeType, RuntimeOf, RuntimeTypeProviderComponent}; pub struct TokioRuntime { /* handle, clock, etc. */ } @@ -78,6 +81,12 @@ delegate_components! { } } +check_components! { + App { + RuntimeTypeProviderComponent, + } +} + fn describe() -> &'static str where Context: HasRuntimeType, @@ -107,7 +116,8 @@ rather than reusing this one. - [`HasRuntime`](./has_runtime.md) — the getter companion that borrows a value of this type. - [`#[cgp_type]`](../macros/cgp_type.md) — the macro `HasRuntimeType` is defined with. -- [`HasType` / `TypeProvider`](./has_type.md) — the built-in abstract-type substrate this rests on. +- [`HasType` / `TypeProvider`](./has_type.md) — the tag-indexed abstract-type component; a + `TypeProvider` can back this one through its generated `WithProvider` impl. - [`UseType`](../providers/use_type.md) — the provider that fixes the runtime type in wiring. - [`CanRun` / `Runner`](./runner.md) — the task runner whose providers reach the runtime. diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index 68f55bf8..d69c1e6c 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -1,11 +1,13 @@ --- +title: 'HasType — a tag-indexed abstract type' +description: 'CGP''s tag-indexed abstract-type component: a context resolves one type per tag through wiring, and generic code names it through TypeOf.' sidebar_label: 'HasType' sidebar_position: 4 --- # `HasType` -CGP's single built-in abstract-type component: a tag-indexed type a context resolves through wiring. +CGP's tag-indexed abstract-type component: a type per tag that a context resolves through wiring. ## Overview @@ -17,13 +19,14 @@ is the foundational, tag-indexed instance of that pattern. A **context**, the ty through wiring. Generic code names `Self::Type` (or the alias `TypeOf`), the concrete type stays hidden behind the tag, and any context that wires the tag to a type satisfies the bound. -What makes `HasType` central is that it is the *only* abstract-type component built into CGP, and it is -the machinery [`#[cgp_type]`](../macros/cgp_type.md) defers to. Every named abstract-type component a -program defines with `#[cgp_type]`, including [`HasErrorType`](./has_error_type.md) and -[`HasRuntimeType`](./has_runtime_type.md), is wired on top of this one, so the same -[`UseType`](../providers/use_type.md) marker that resolves `HasType` also resolves any `#[cgp_type]` -component. `HasType` is the common substrate; `#[cgp_type]` is the ergonomic layer that gives each -abstract type its own named trait. +`HasType` is the one abstract-type component in CGP indexed by a tag rather than named. CGP's other +abstract types, such as [`HasErrorType`](./has_error_type.md) and +[`HasRuntimeType`](./has_runtime_type.md), are named components defined with +[`#[cgp_type]`](../macros/cgp_type.md), each with its own provider trait and wiring key. The two kinds share the +[`UseType`](../providers/use_type.md) marker, because `#[cgp_type]` generates a `UseType` impl for +each named component. They also meet at the provider level: `#[cgp_type]` generates a +[`WithProvider`](../providers/with_provider.md) impl that lets a `TypeProvider` back a named +component. ## Definition @@ -46,9 +49,11 @@ Its attributes: ## Usage -`HasType` is in the prelude. It carries a `Tag` parameter, the type-level name that distinguishes one -abstract type from another within a context, and an associated `Type` that the tag resolves to. A -context supplies the type in one of two ways. +`HasType` and the provider trait `TypeProvider` are in the prelude. The wiring key +`TypeProviderComponent` and the `TypeOf` alias come from `cgp::core::types`. `HasType` carries a +`Tag` parameter, the type-level name that distinguishes one abstract type from another within a +context, and an associated `Type` that the tag resolves to. A context supplies the type in one of +two ways. The direct way is an ordinary trait impl. The wired way, and the common one, delegates the component's key `TypeProviderComponent` to [`UseType`](../providers/use_type.md), the zero-sized marker that @@ -62,18 +67,36 @@ delegate_components! { } ``` +**`UseType` ignores the tag**, so that single entry answers every tag with `f64`. To give different +tags different types, dispatch on the tag with the +[`open` statement](../macros/delegate_components.md#choosing-a-provider-per-type-the-open-statement): + +```rust +delegate_components! { + App { + open TypeProviderComponent; + + @TypeProviderComponent.ScalarTag: UseType, + @TypeProviderComponent.NameTag: UseType, + } +} +``` + +The legacy form wires `TypeProviderComponent` to a `UseDelegate` table keyed by tag, or to +[`UseDelegatedType`](../providers/use_delegated_type.md), whose table maps each tag straight to its type. + In most code you would not wire `HasType` directly. You would define a named abstract type with [`#[cgp_type]`](../macros/cgp_type.md), such as `#[cgp_type] trait HasScalarType { type Scalar; }`, -which gives a readable `Self::Scalar` and its own provider trait and marker, all resolving down to this -`HasType` substrate. The related [`#[use_type]`](../attributes/use_type.md) attribute, distinct from the -`UseType` provider despite the shared name, rewrites a bare type name and adds the bound inside a -definition. +which gives a readable `Self::Scalar` and its own provider trait and marker. The related +[`#[use_type]`](../attributes/use_type.md) attribute, distinct from the `UseType` provider despite +the shared name, rewrites a bare type name and adds the bound inside a definition. ## Examples A direct use defines no new component and resolves an abstract type by tag through `UseType`: ```rust +use cgp::core::types::{TypeOf, TypeProviderComponent}; use cgp::prelude::*; pub struct ScalarTag; @@ -86,6 +109,12 @@ delegate_components! { } } +check_components! { + App { + TypeProviderComponent: ScalarTag, + } +} + fn zero() -> TypeOf where Context: HasType, @@ -97,8 +126,8 @@ where `App` wires `TypeProviderComponent` to `UseType`, so the `UseType` impl makes `App` implement `HasType` with `Type = f64`. `App` is an **[environmental context](/docs/reference/glossary#environmental-context)** here, a type standing for -the application that carries its type choices. In real code you would write the named `#[cgp_type]` -layer; this page documents the substrate it rests on. +the application that carries its type choices. `zero::()` returns `0.0`. In real code you would +usually define a named `#[cgp_type]` component instead. ## When to use it @@ -107,13 +136,14 @@ defines a named abstract type with its own readable trait, and let it build on t time `HasType` is useful on its own is when a program wants a family of abstract types keyed by a tag it computes rather than a fixed set of named traits. -Recognizing `HasType` matters more than writing it: an expansion or an error message names it -when a `#[cgp_type]` component fails to resolve, and knowing that every abstract type reduces to it -explains why the one [`UseType`](../providers/use_type.md) provider wires all of them. +Recognizing `HasType` matters more than writing it. Its `TypeProvider` trait appears in the +`WithProvider` impl every `#[cgp_type]` component carries, so an expansion or a diagnostic about a +named abstract type can mention it. ## Related constructs -- [`#[cgp_type]`](../macros/cgp_type.md) — builds every named abstract-type component on this substrate. +- [`#[cgp_type]`](../macros/cgp_type.md) — defines named abstract-type components, whose generated + `WithProvider` impl accepts a `TypeProvider`. - [`UseType`](../providers/use_type.md) — the zero-sized marker that supplies a concrete type to the abstract one. - [`#[use_type]`](../attributes/use_type.md) — the differently-named attribute that imports an abstract @@ -135,7 +165,7 @@ The ideas behind it: [`has_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/traits/has_type.rs) - The `UseType` provider and its `TypeProvider` impl: [`use_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-type/src/impls/use_type.rs) -- The `#[cgp_type]` macro that builds named components on this substrate: +- The `#[cgp_type]` macro that defines named abstract-type components: [`cgp_type/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_type/) --- diff --git a/docs/reference/components/index.md b/docs/reference/components/index.md index 6b0e9863..15208ca3 100644 --- a/docs/reference/components/index.md +++ b/docs/reference/components/index.md @@ -1,4 +1,6 @@ --- +title: 'Component reference' +description: 'The components CGP ships, grouped by job: the abstract error type and its raising and wrapping, abstract types, the handler family, and runtimes and runners.' sidebar_label: 'Overview' sidebar_position: 0 --- @@ -34,12 +36,12 @@ crate rather than by hand. ## Let each context choose a type -[`HasType`](./has_type.md) is CGP's single built-in abstract-type component: a tag-indexed trait whose -associated type a context resolves to a concrete one through wiring. Every named [abstract type](/docs/reference/glossary#abstract-type) a program -defines with [`#[cgp_type]`](../macros/cgp_type.md), including `HasErrorType` and -[`HasRuntimeType`](./has_runtime_type.md) below, is built on this substrate, and the same -[`UseType`](../providers/use_type.md) marker resolves all of them. You reach for `HasType` directly -only rarely, but recognizing it explains how every other abstract type in a codebase works. +[`HasType`](./has_type.md) is CGP's tag-indexed [abstract type](/docs/reference/glossary#abstract-type): +a trait whose associated type a context resolves, one tag at a time, to a concrete type through wiring. +CGP's other abstract types, such as `HasErrorType` and [`HasRuntimeType`](./has_runtime_type.md) below, +are named components defined with [`#[cgp_type]`](../macros/cgp_type.md), and the same +[`UseType`](../providers/use_type.md) marker supplies all of them. You reach for `HasType` directly +only rarely; a named `#[cgp_type]` component reads better. ## Compute things @@ -52,8 +54,8 @@ targets because every simpler member promotes up to it. [`Producer`](./handler/p input-free case that yields a value from the context alone. Each of `Computer`, `TryComputer`, and `Handler` also has by-reference and, for the computers, async -siblings, such as `ComputerRef`, `AsyncComputer`, and `HandlerRef`. These differ from the base member by -one axis and are documented on the base member's page. Providers for the family are written from plain +siblings, such as `ComputerRef`, `AsyncComputer`, and `HandlerRef`. Each differs from its base member by +one axis and has a page of its own in the subsection. Providers for the family are written from plain functions with [`#[cgp_computer]`](../macros/cgp_computer.md) and [`#[cgp_producer]`](../macros/cgp_producer.md), then composed with the [handler combinators](../providers/handler/index.md). diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index e69f8012..36fdac92 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -1,4 +1,6 @@ --- +title: 'CanRun — run a task by type-level code' +description: 'The async component that runs a task named at the type level to a Result, with each task code dispatched to its own provider through wiring.' sidebar_label: 'CanRun' sidebar_position: 8 --- @@ -9,15 +11,14 @@ Run a task named at the type level to a `Result<(), Error>`, with the behavior c ## Overview -`CanRun` gives a context a uniform way to *execute a unit of work* selected at the type level. The -unit of work is identified by a `Code` type parameter, a phantom tag rather than a value, so a single -**context**, the type a method runs on that supplies the values an implementation needs as its -own fields, can host many distinct tasks, one per `Code`, and dispatch each to its own provider. Running -a task here means invoking the provider wired for that `Code` and awaiting an asynchronous -`Result<(), Error>`: the task either completes or produces the context's abstract error. The component -carries no input or output beyond success-or-error, so it models a fire-and-complete action rather than -a transformation, which separates it from the [handler family](./handler/index.md) that maps an -`Input` to an `Output`. +`CanRun` gives a context a uniform way to *execute a unit of work* selected at the type level. +The unit of work is identified by a `Code` type parameter, a phantom tag rather than a value, so a +single **context**, the type the implementation runs against, can host many distinct tasks, one per +`Code`, and dispatch each to its own provider. Running a task here means invoking the provider wired +for that `Code` and awaiting an asynchronous `Result<(), Error>`: the task either completes or +produces the context's abstract error. The component carries no input or output beyond +success-or-error, so it models a fire-and-complete action rather than a transformation, which +separates it from the [handler family](./handler/index.md) that maps an `Input` to an `Output`. `CanRun` is the execution layer that ties a CGP application together: a runner provider typically reaches the context's runtime through [`HasRuntime`](./has_runtime.md) to spawn or await work, and dispatches to @@ -48,7 +49,9 @@ Its attributes: ## Usage -`CanRun` is imported from `cgp::extra::run`. Its method is `async` and takes only a `Code` tag: +`CanRun` is imported from `cgp::extra::run`, with its provider trait `Runner` and its key +`RunnerComponent`; none of them is in the prelude, and the component carries no `#[prefix]`. Its +method is `async` and takes only a `Code` tag: ```rust async fn run(&self, _code: PhantomData) -> Result<(), Error>; @@ -78,8 +81,10 @@ statement supersedes. ## Examples -A spawning runner provider requires the context to be [`CanSendRun`](./send_runner.md) so it can hand a -`Send` future to a spawner, and runs an inner task on a background thread: +A spawning runner provider requires the context to be [`CanSendRun`](./send_runner.md) so it can +hand a `Send` future to a spawner, and runs an inner task on a background thread. `spawn` stands for +any function with the signature of `tokio::spawn`, which requires a `Send + 'static` future. The +wiring is the `open` table from [Usage](#usage): ```rust #[cgp_impl(new SpawnAndRun: RunnerComponent)] diff --git a/docs/reference/components/send_runner.md b/docs/reference/components/send_runner.md index e708e524..9f80530e 100644 --- a/docs/reference/components/send_runner.md +++ b/docs/reference/components/send_runner.md @@ -1,4 +1,6 @@ --- +title: 'CanSendRun — a runner with a Send future' +description: 'The runner component whose future is Send, supplied by a proxy on the concrete context so a spawning provider can hand work to a work-stealing executor.' sidebar_label: 'CanSendRun' sidebar_position: 9 --- @@ -52,7 +54,8 @@ Its attributes: ## Usage -`CanSendRun` is imported from `cgp::extra::run`. Its method differs from `run` only in the shape of its +`CanSendRun` is imported from `cgp::extra::run`, with its provider trait `SendRunner` and its key +`SendRunnerComponent`; none of them is in the prelude. Its method differs from `run` only in the shape of its return, an explicit `Send` future rather than a plain `async fn`: ```rust @@ -64,6 +67,8 @@ proxy impl on the concrete context that forwards to its own `run`. The proxy dis `Send` bound: ```rust +use cgp::extra::run::{CanRun, SendRunner, SendRunnerComponent}; + #[cgp_provider] impl SendRunner for App { async fn send_run(context: &App, code: PhantomData) -> Result<(), Infallible> { @@ -74,13 +79,18 @@ impl SendRunner for App { Because this impl names the concrete `App` and `ActionA`, the future produced by `context.run(code)` has a fully known type, so the compiler can verify it is `Send` and satisfy the `+ Send` bound on -`send_run`, which the generic [`CanRun`](./runner.md) definition deliberately does not assert. A spawning -runner provider can then require `Context: CanSendRun`, clone the context into a `Send` future, -and hand it to a spawner, all without `Send` bounds leaking into the abstract interfaces. +`send_run`, which the generic [`CanRun`](./runner.md) definition deliberately does not assert. A +spawning runner provider can then require `Context: CanSendRun`, clone the context into a `Send` +future, and hand it to a spawner, all without `Send` bounds leaking into the abstract interfaces. + +`#[cgp_provider]` derives the component key `SendRunnerComponent` from the trait name, so the key must +be in scope even though the context never wires it. ## Examples -A spawning provider requires the context to be `CanSendRun` and hands a `Send` future to a spawner: +A spawning provider requires the context to be `CanSendRun` and hands a `Send` future to a spawner. +`spawn` stands for any function with the signature of `tokio::spawn`, which requires a +`Send + 'static` future. The context wires it as [`CanRun`](./runner.md#usage) shows: ```rust #[cgp_impl(new SpawnAndRun: RunnerComponent)] diff --git a/example-code/tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.rs b/example-code/tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.rs new file mode 100644 index 00000000..43f6d66c --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.rs @@ -0,0 +1,20 @@ +use cgp::core::error::{ErrorRaiser, ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::RaiseFrom; +use cgp::prelude::*; + +pub struct App; + +delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + } +} + +fn main() { + // error[E0034]: multiple applicable items in scope + // + // `App` implements the provider trait `ErrorRaiser` too, so with it imported the bare name is + // ambiguous. `>::raise_error(…)` names the consumer trait. + let _ = App::raise_error("boom".to_owned()); +} diff --git a/example-code/tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.stderr b/example-code/tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.stderr new file mode 100644 index 00000000..f97a3207 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.stderr @@ -0,0 +1,16 @@ +error[E0034]: multiple applicable items in scope + --> tests/compile_fail/reference/components/can_raise_error_usage_ambiguous_concrete_call.rs:19:18 + | +19 | let _ = App::raise_error("boom".to_owned()); + | ^^^^^^^^^^^ multiple `raise_error` found + | + = note: candidate #1 is defined in an impl of the trait `cgp::prelude::CanRaiseError` for the type `__Context__` + = note: candidate #2 is defined in an impl of the trait `ErrorRaiser` for the type `__Provider__` +help: use fully-qualified syntax to disambiguate + | +19 - let _ = App::raise_error("boom".to_owned()); +19 + let _ = ::raise_error("boom".to_owned()); + | +19 - let _ = App::raise_error("boom".to_owned()); +19 + let _ = ::raise_error("boom".to_owned()); + | diff --git a/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.rs b/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.rs new file mode 100644 index 00000000..4e4369e2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.rs @@ -0,0 +1,24 @@ +use cgp::core::error::{ErrorTypeProviderComponent, ErrorWrapperComponent}; +use cgp::extra::error::DisplayError; +use cgp::prelude::*; + +pub struct App; + +// `DisplayError` forwards to the context's own `CanWrapError`, which is this same entry. +delegate_components! { + App { + open ErrorWrapperComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorWrapperComponent.String: DisplayError, + } +} + +// error[E0275]: overflow evaluating the requirement `App: IsProviderFor` +check_components! { + App { + ErrorWrapperComponent: String, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.stderr b/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.stderr new file mode 100644 index 00000000..ff38ca23 --- /dev/null +++ b/example-code/tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.stderr @@ -0,0 +1,22 @@ +error[E0275]: overflow evaluating the requirement `App: IsProviderFor` + --> tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.rs:20:9 + | +20 | ErrorWrapperComponent: String, + | ^^^^^^^^^^^^^^^^^^^^^ + | + = note: required for `App` to implement `ErrorWrapper` + = note: required for `App` to implement `CanWrapError` + = note: required for `DisplayError` to implement `IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `RedirectLookup>` to implement `IsProviderFor` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/components/can_wrap_error_usage_display_error_cycle.rs:18:1 + | +18 | / check_components! { +19 | | App { +20 | | ErrorWrapperComponent: String, +21 | | } +22 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/reference/components/can_raise_error.rs b/example-code/tests/reference/components/can_raise_error.rs index 5e7b6024..5d693480 100644 --- a/example-code/tests/reference/components/can_raise_error.rs +++ b/example-code/tests/reference/components/can_raise_error.rs @@ -1,12 +1,57 @@ //! Code from `docs/reference/components/can_raise_error.md` — `CanRaiseError`. //! -//! Pins the `LoadOrFail` provider from the page's Examples, which raises a `String` into the context's -//! abstract error through `#[uses(CanRaiseError)]`. The provider is generic over its context, -//! so it compiles on its own; the `CanRaiseError` dependency is discharged wherever a concrete -//! context wires `LoadOrFail`. +//! The page's Definition carries `#[track_caller]`, which the `cgp` revision this crate pins predates; +//! the caller-location claims were checked against the local `cgp` checkout instead. The rejected +//! concrete-context call is a trybuild fixture. + +/// ## Usage +/// +/// The `open` table routing each source error to a provider. `ParseError` stands for any source +/// error the application meets. +pub mod usage { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::{DebugError, RaiseFrom}; + use cgp::prelude::*; + + #[derive(Debug)] + pub struct ParseError; + + pub struct App; + + delegate_components! { + App { + open ErrorRaiserComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorRaiserComponent.String: RaiseFrom, + @ErrorRaiserComponent.ParseError: DebugError, + } + } + + check_components! { + App { + ErrorRaiserComponent: [String, ParseError], + } + } + + /// Generic code calls the associated function on the context type. + pub fn raise_parse>() -> Context::Error { + Context::raise_error(ParseError) + } + + #[test] + fn each_source_error_reaches_its_provider() { + assert_eq!(>::raise_error("boom".to_owned()), "boom"); + assert_eq!(raise_parse::(), "ParseError"); + } +} /// ## Examples +/// +/// `LoadOrFail`, wired on a context whose error type is `String`. pub mod examples { + use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; + use cgp::extra::error::RaiseFrom; use cgp::prelude::*; #[cgp_component(Loader)] @@ -26,4 +71,26 @@ pub mod examples { Ok(format!("contents of {path}")) } } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + LoaderComponent: LoadOrFail, + } + } + + check_components! { + App { + LoaderComponent, + } + } + + #[test] + fn load_raises_into_the_contexts_error() { + assert_eq!(App.load("a.txt"), Ok("contents of a.txt".to_owned())); + assert_eq!(App.load(""), Err("empty path".to_owned())); + } } diff --git a/example-code/tests/reference/components/can_wrap_error.rs b/example-code/tests/reference/components/can_wrap_error.rs index e8d0ea33..3aad4fa5 100644 --- a/example-code/tests/reference/components/can_wrap_error.rs +++ b/example-code/tests/reference/components/can_wrap_error.rs @@ -1,13 +1,18 @@ //! Code from `docs/reference/components/can_wrap_error.md` — `CanWrapError`. //! -//! Pins the `LoadOrFail` provider from the page's Examples, which raises a `String` into the context's -//! abstract error and then wraps a further message onto it, declaring both dependencies through -//! `#[uses]`. The provider is generic over its context, so it compiles on its own; the -//! `CanRaiseError` and `CanWrapError` dependencies are discharged wherever a concrete -//! context wires `LoadOrFail`. +//! The page's Definition carries `#[track_caller]`, which the `cgp` revision this crate pins predates; +//! the caller-location claims were checked against the local `cgp` checkout instead. The circular +//! `DisplayError` wiring and the ambiguous concrete-context call are trybuild fixtures. -/// ## Examples +/// ## Usage and Examples +/// +/// The `open` table from Usage and the context from Examples, one program: `AppendDetail` folds a +/// `String` detail into the error, and `DisplayError` forwards a `u64` detail to it. pub mod examples { + use cgp::core::error::{ + ErrorRaiserComponent, ErrorTypeProviderComponent, ErrorWrapper, ErrorWrapperComponent, + }; + use cgp::extra::error::{DisplayError, RaiseFrom}; use cgp::prelude::*; #[cgp_component(Loader)] @@ -28,4 +33,57 @@ pub mod examples { Ok(format!("contents of {path}")) } } + + #[cgp_impl(new AppendDetail)] + #[use_type(HasErrorType.{Error = String})] + impl ErrorWrapper { + fn wrap_error(error: Error, detail: String) -> Error { + format!("{detail}: {error}") + } + } + + pub struct App; + + delegate_components! { + App { + ErrorTypeProviderComponent: UseType, + ErrorRaiserComponent: RaiseFrom, + ErrorWrapperComponent: AppendDetail, + LoaderComponent: LoadOrFail, + } + } + + check_components! { + App { + LoaderComponent, + } + } + + /// The Usage table: `String` goes to `AppendDetail`, and `u64` through `DisplayError` to it. + pub struct UsageApp; + + delegate_components! { + UsageApp { + open ErrorWrapperComponent; + + ErrorTypeProviderComponent: UseType, + @ErrorWrapperComponent.String: AppendDetail, + @ErrorWrapperComponent.u64: DisplayError, + } + } + + check_components! { + UsageApp { + ErrorWrapperComponent: [String, u64], + } + } + + #[test] + fn detail_is_folded_into_the_error() { + assert_eq!(App.load(""), Err("while loading : empty path".to_owned())); + assert_eq!( + >::wrap_error("failed".to_owned(), 7), + "7: failed" + ); + } } diff --git a/example-code/tests/reference/components/has_error_type.rs b/example-code/tests/reference/components/has_error_type.rs index d35eab5a..f4f84473 100644 --- a/example-code/tests/reference/components/has_error_type.rs +++ b/example-code/tests/reference/components/has_error_type.rs @@ -1,9 +1,24 @@ //! Code from `docs/reference/components/has_error_type.md` — `HasErrorType`. //! //! Pins that a context wires its abstract error to a concrete type through `UseType`, and that an -//! error-aware component names the error as the bare `Error` via `#[use_type]`. The page's direct-impl -//! form uses `anyhow::Error`, which this crate does not depend on, so the wired `String` form stands -//! in for it. +//! error-aware component names the error as the bare `Error` via `#[use_type]`. + +/// ## Usage +/// +/// The direct impl, with `anyhow::Error` as the context's error type. +pub mod usage { + use cgp::prelude::*; + + pub struct App; + + impl HasErrorType for App { + type Error = anyhow::Error; + } + + pub fn fail() -> Result<(), ::Error> { + Err(anyhow::anyhow!("failed")) + } +} /// ## Examples pub mod examples { @@ -24,13 +39,9 @@ pub mod examples { } } - mod check_app { - use super::*; - - check_components! { - App { - ErrorTypeProviderComponent, - } + check_components! { + App { + ErrorTypeProviderComponent, } } } diff --git a/example-code/tests/reference/components/has_type.rs b/example-code/tests/reference/components/has_type.rs index 4b25f6cb..1c6236d9 100644 --- a/example-code/tests/reference/components/has_type.rs +++ b/example-code/tests/reference/components/has_type.rs @@ -36,6 +36,32 @@ pub mod examples { Default::default() } + /// The Usage section's `open` table, giving two tags two types. + pub struct NameTag; + + pub struct TwoTypes; + + delegate_components! { + TwoTypes { + open TypeProviderComponent; + + @TypeProviderComponent.ScalarTag: UseType, + @TypeProviderComponent.NameTag: UseType, + } + } + + check_components! { + TwoTypes { + TypeProviderComponent: [ScalarTag, NameTag], + } + } + + #[test] + fn open_gives_each_tag_its_own_type() { + let _: PhantomData> = PhantomData::; + assert_eq!(zero::(), 0.0); + } + #[test] fn app_resolves_any_tag_to_f64() { // `App` wires `TypeProviderComponent` to `UseType`, so `HasType` resolves to diff --git a/example-code/tests/reference/components/runner.rs b/example-code/tests/reference/components/runner.rs index c94b276a..c5b6411a 100644 --- a/example-code/tests/reference/components/runner.rs +++ b/example-code/tests/reference/components/runner.rs @@ -1,8 +1,9 @@ //! Code from `docs/reference/components/runner.md` — `CanRun`. //! //! Pins the `SpawnAndRun` provider from the page's Examples, together with the cast the page names but -//! does not show in full: a base `RunWithFooBar` runner, a `UseDelegate` table routing two tasks, a -//! `SendRunner` proxy on the concrete context, and a `dummy_spawn` standing in for `tokio::spawn`. It +//! does not show in full: a base `RunWithFooBar` runner, the Usage section's `open` table routing two +//! tasks, a `SendRunner` proxy on the concrete context, and a `dummy_spawn` standing in for +//! `tokio::spawn`. It //! follows the library's own async-and-send spawn test. The elided `RunWithFooBar` body is a trivial //! success here. @@ -77,6 +78,12 @@ pub mod examples { } } + check_components! { + App { + RunnerComponent: [ActionA, ActionB], + } + } + #[test] fn spawns_and_runs_a_task() { let app = App; From 151ab8ebab8602c8baf9d98313dae6b36e84c209 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 02:14:49 +0000 Subject: [PATCH 122/516] Describe what the #[cgp_type] WithProvider impl actually adapts UseType satisfies a named abstract type through its own generated impl; the WithProvider impl is what lets any TypeProvider, such as UseDelegatedType, back a named component. HasType is CGP's tag-indexed abstract type, not its only one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/index.md | 14 +++++++------- docs/reference/macros/cgp_type.md | 12 +++++++----- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/reference/index.md b/docs/reference/index.md index fdc4156f..7ac799a7 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -96,15 +96,15 @@ so callers never name it. ### Let each context choose a type -[`#[cgp_type]`](./macros/cgp_type.md) defines an abstract-type component — an error type, a runtime, a -scalar — that each context fills in by wiring the component to +[`#[cgp_type]`](./macros/cgp_type.md) defines an abstract-type component — an error type, a runtime, +a scalar — that each context fills in by wiring the component to [`UseType`](./providers/use_type.md), or to [`UseDelegatedType`](./providers/use_delegated_type.md) to resolve it through a table. Generic code -names such a type by importing it with [`#[use_type]`](./attributes/use_type.md), which is a different -thing from the `UseType` provider despite the shared name. All of it rests on -[`HasType`](./components/has_type.md), CGP's built-in abstract-type component, and -[`WithProvider`](./providers/with_provider.md) is the adapter that lets a foundational provider stand -in as a named component's. +names such a type by importing it with [`#[use_type]`](./attributes/use_type.md), which is a +different thing from the `UseType` provider despite the shared name. Beside the named components +sits [`HasType`](./components/has_type.md), CGP's tag-indexed abstract-type component, and +[`WithProvider`](./providers/with_provider.md) is the adapter that lets a foundational provider +stand in as a named component's. ### Handle errors diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index d1b19069..fc02da98 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -246,10 +246,11 @@ where } ``` -[`HasType` / `TypeProvider`](../components/has_type.md) is CGP's single built-in abstract-type component, -and `UseType` is itself a `TypeProvider`. This impl lets one `UseType` satisfy both the -built-in component and any `#[cgp_type]` component you declare, instead of needing a separate provider -per component. +[`HasType` / `TypeProvider`](../components/has_type.md) is CGP's tag-indexed abstract-type component, +and this impl lets any `TypeProvider` back the named component when the context wires +`WithProvider

>::Delegate> +pub fn provider_for() -> PhantomData<
>::Delegate> where Table: DelegateComponent, { @@ -84,57 +78,52 @@ where } ``` -The bound is the "get"; `
>::Delegate` is the value it returns. Because Rust -forbids two impls of one trait for the same `Self` and `Key`, each key maps to exactly one value. This -makes the structure a map rather than a relation, and it turns a duplicate wiring entry into a [coherence](/docs/reference/glossary#coherence) -error rather than a silent overwrite. +The bound is the lookup, and `
>::Delegate` is the value it finds. +Rust forbids two impls of one trait for the same `Self` and `Key`, so each key maps to exactly one +value: the structure is a map, and a duplicate entry is a +[coherence](/docs/reference/glossary#coherence) error rather than a silent overwrite. ### What can be a key -The key's type decides what the entry *means*, and there are three shapes in practice. - -A **component name** (`GreeterComponent`, `AreaCalculatorComponent`) is the ordinary case. An entry keyed -this way is read by the blanket impl that [`#[cgp_component]`](../../macros/cgp_component.md) generates, which -concludes that the context has the component's provider trait, and from there its consumer trait. +The key's type decides what an entry means, and three kinds occur: -An **arbitrary type** (a shape, a tag) makes the table a plain dispatch map with no provider trait -attached. This is what the nested tables inside [`UseDelegate`](../../providers/use_delegate.md) are, and what -the `open` statement's per-key entries resolve through. - -A **type-level path** (a [`PathCons`](../../types/path_cons.md) list built by -[`Path!`](../../macros/path.md)) is how namespaces key their entries, so a lookup walks one segment at a time. -[`RedirectLookup`](../../providers/redirect_lookup.md) is the provider that performs that walk. +- **A component name**, such as `GreeterComponent`. The provider blanket impl that + [`#[cgp_component]`](../../macros/cgp_component.md) generates reads the entry, so the context gets + the component's provider trait, and from it the consumer trait. +- **Any other type**, such as a shape or a tag. The table is a dispatch map with no provider trait + attached, as the nested tables inside [`UseDelegate`](../../providers/use_delegate.md) are. +- **A type-level path**, a [`PathCons`](../../types/path_cons.md) list, which is how the `open` + statement and namespaces key their entries. A path entry is written with a generic tail, so it + matches every longer path beneath it, and + [`RedirectLookup`](../../providers/redirect_lookup.md) reads it with one lookup on the whole path. ### What owns a table -`Self` is not always a context. A [`delegate_components!`](../../macros/delegate_components.md) block with a -leading `new` declares a provider bundle that owns its own table, so several contexts can delegate a whole -group of components to it as one unit. Resolution is shallow (one read yields the immediate `Delegate`), -and chaining happens when that delegate is itself a table, which is exactly what a bundle is. +`Self` is not always a context. A [`delegate_components!`](../../macros/delegate_components.md) +block with a leading `new` declares a provider bundle that owns its own table, so several contexts +can delegate a group of components to it as one unit. A lookup is shallow: one read yields the +immediate `Delegate`, and chaining happens when that delegate is itself a table, as a bundle is. ## Examples -The single wired component is the whole idea. Given a component and a provider: +One component wired on a context, and a table keyed on shapes, each read back with the function from +[Usage](#usage): ```rust use cgp::prelude::*; #[cgp_component(Greeter)] pub trait CanGreet { - fn greet(&self); + fn greet(&self) -> String; } #[cgp_impl(new GreetHello)] impl Greeter { - fn greet(&self) { - println!("Hello!"); + fn greet(&self) -> String { + "Hello!".to_owned() } } -``` -a context wires it in one line: - -```rust pub struct App; delegate_components! { @@ -142,123 +131,207 @@ delegate_components! { GreeterComponent: GreetHello, } } + +check_components! { + App { + GreeterComponent, + } +} + +pub struct Rectangle; +pub struct Circle; +pub struct RectangleArea; +pub struct CircleArea; + +delegate_components! { + new AreaComponents { + Rectangle: RectangleArea, + Circle: CircleArea, + } +} + +pub fn demo() { + assert_eq!(App.greet(), "Hello!"); + + // Each read resolves to the entry's value at compile time. + let _: PhantomData = provider_for::(); + let _: PhantomData = provider_for::(); + let _: PhantomData = provider_for::(); +} ``` -and that line is exactly one `DelegateComponent` impl: +The `App` line is one `DelegateComponent` impl, and through it `App` gets the `Greeter` provider +trait and then `CanGreet`, so `App.greet()` compiles; swapping `GreetHello` for another provider +changes only that line. `AreaComponents` holds two entries keyed on shapes, with no provider trait +attached, which a [`UseDelegate`](../../providers/use_delegate.md) provider reads to pick an area +provider per shape. `App` is an +[environmental context](/docs/reference/glossary#environmental-context). + +## When to use it + +**Write [`delegate_components!`](../../macros/delegate_components.md), not `DelegateComponent`.** +The macro also emits the [`IsProviderFor`](./is_provider_for.md) forwarding impl beside each entry, +and the provider blanket impl requires both, so a hand-written `DelegateComponent` impl alone does +not wire the component at all. Name the trait yourself only to **read an entry in generic code**: a +dispatcher or a [higher-order provider](/docs/reference/glossary#higher-order-provider) that +resolves a key bounds on `DelegateComponent` and projects `Delegate`. + +When a trait has exactly one implementation for a context, **implement the consumer trait directly +on the context** instead. A CGP consumer trait is an ordinary trait, so +`impl CanGreet for App { … }` is legal and needs no table entry. Wiring earns its place when the +implementation is one of several, is shared between contexts, or composes with a wrapper. + +## Under the hood + +`cargo cgp expand` shows what the `App` line of the example becomes: the entry, and beside it an +[`IsProviderFor`](./is_provider_for.md) impl that forwards the chosen provider's requirements: ```rust impl DelegateComponent for App { type Delegate = GreetHello; } +impl<__Context__, __Params__> IsProviderFor +for App +where + GreetHello: IsProviderFor, +{} ``` -From there the generated blanket impls take over: because `App` delegates `GreeterComponent`, it gets the -`Greeter` provider trait, and because it has that, it gets `CanGreet`, so `app.greet()` compiles. Swap -`GreetHello` for another provider and only that one line changes. - -An arbitrary-key table looks identical and means something different. The nested-table syntax builds a -dispatch map keyed on shapes: +The reader is the provider blanket impl that [`#[cgp_component]`](../../macros/cgp_component.md) +generates for `Greeter`. It implements the provider trait for any type that has both an entry and +the forwarding impl, and forwards each method to the entry's value: ```rust -delegate_components! { - new AreaComponents { - Rectangle: RectangleArea, - Circle: CircleArea, +impl<__Provider__, __Context__> Greeter<__Context__> for __Provider__ +where + __Provider__: DelegateComponent + + IsProviderFor, + <__Provider__ as DelegateComponent< + GreeterComponent, + >>::Delegate: Greeter<__Context__>, +{ + fn greet(__context__: &__Context__) -> String { + <__Provider__ as DelegateComponent< + GreeterComponent, + >>::Delegate::greet(__context__) } } ``` -`AreaComponents` now has `DelegateComponent` and `DelegateComponent` entries. No provider -trait attaches to either; they are data that a [`UseDelegate`](../../providers/use_delegate.md) provider reads -at dispatch time to pick `RectangleArea` or `CircleArea` for the shape it was asked about. +The routing is the projection, and the call it forwards to is resolved statically. A context that +joins a namespace with a `namespace N;` header gets a blanket entry instead of one per key, which +reads each key's value from the namespace trait. For an `App` that joins a namespace `MyNamespace` +defined with [`cgp_namespace!`](../../macros/cgp_namespace.md), the header becomes: -## When to use it +```rust +impl<__Key__, __Value__> DelegateComponent<__Key__> for App +where + __Key__: MyNamespace, +{ + type Delegate = __Value__; +} +``` -**Write [`delegate_components!`](../../macros/delegate_components.md), not `DelegateComponent`.** That is the -honest summary of this page: the trait is what you read, and the macro is what you write. The macro also -emits the [`IsProviderFor`](./is_provider_for.md) forwarding impl beside each entry, which is what keeps a -missing dependency diagnosable, so a hand-written `DelegateComponent` impl gets you the wiring and loses -the error message. +That is how a context inherits a whole table while still adding direct entries at the keys the +namespace leaves open. -There are narrow reasons to name the trait yourself. +## Common Mistakes -- **Reading an entry in generic code.** A provider that must resolve a key itself (a dispatcher, a - [higher-order provider](/docs/reference/glossary#higher-order-provider) walking a table) bounds on `DelegateComponent` and projects `Delegate`. This - is the one legitimate hand-written use, and it is a *read*. -- **Recognizing it in an error.** `the trait bound App: DelegateComponent is not - satisfied` means the context never wired that component. That is the most common wiring error there is, - and knowing the trait is how you read it. +**A missing entry and an unsatisfied provider are different errors.** A context that never wires the +component fails a check on the table entry: -And the alternative to reach for instead: **implement the consumer trait directly on the context** when a -trait has exactly one implementation for it. A CGP consumer trait is an ordinary trait, so -`impl CanGreet for App { … }` is legal and needs no table entry at all. Wiring earns its keep when the -implementation is one of several, or is shared, or should compose with a wrapper. +```rust +pub struct App; -## Under the hood +check_components! { + App { + GreeterComponent, + } +} +``` -The trait is the plainest thing in CGP (one associated type, no method), so the interesting part is what -reads it. The provider blanket impl generated by [`#[cgp_component]`](../../macros/cgp_component.md) is the -reader, and its body is itself a table lookup: it bounds the provider on `DelegateComponent` -and forwards each method to `>::Delegate`. So the "routing" is -literally the projection, and the call it forwards to is resolved statically and inlined. +rustc names the missing entry in a help line: -Two further facts about the generated impls are worth carrying away. Each entry is emitted **alongside** an -[`IsProviderFor`](./is_provider_for.md) impl that forwards the chosen provider's requirements, so the entry -is both resolvable and checkable, and [`CanUseComponent`](./can_use_component.md) then combines the pair -into a single assertion. And a namespace's -`namespace N;` header emits not one entry but a *blanket* `DelegateComponent` impl that forwards every key -through the namespace, which is how a context inherits a whole table while still adding direct entries -at the keys the namespace leaves open. +```text +error[E0277]: the trait bound `App: CanUseComponent` is not satisfied +... +help: the trait `DelegateComponent` is not implemented for `App` +``` -## Common Mistakes +The fix is a wiring line. A wired component whose provider's dependencies are unmet fails through +[`IsProviderFor`](./is_provider_for.md) instead, and the fix is to supply the dependency. + +**A hand-written entry does not wire the component.** An +`impl DelegateComponent for App` written by hand, without the forwarding impl the +macro emits beside it, fails the provider blanket impl's `IsProviderFor` bound, so `App` never gets +the provider trait and a call fails: + +```text +error[E0599]: the method `greet` exists for struct `App`, but its trait bounds were not satisfied +``` + +Write the entry with `delegate_components!`. + +**Two entries for the same key conflict rather than override.** Wiring one component on one +context twice, to `GreetHello` and to a second provider `GreetHi`, is two impls of each generated +trait for one type: + +```rust +delegate_components! { + App { + GreeterComponent: GreetHello, + GreeterComponent: GreetHi, + } +} +``` -**A missing entry and an unsatisfied provider are different errors.** `DelegateComponent` not implemented -means the component was never wired. A wired component whose provider's dependencies are unmet fails -elsewhere, through [`IsProviderFor`](./is_provider_for.md). Reading which one you have tells you whether to -add a wiring line or supply a dependency. +It fails twice, once for the forwarding impl and once for the entry: -**Two entries for the same key is a coherence error, not an override.** Wiring one component twice on one -context reports `E0119` conflicting implementations. A direct entry for a key the context's namespace -binds conflicts the same way, with the namespace's blanket impl, so a context adds entries only at keys -the namespace leaves open. +```text +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` +... +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` +``` -**`Self` is not always a context.** A provider bundle declared with `new` owns a table too, and reading an -error that names one as the table's `Self` does not mean something is being used as a context. +A direct entry for a key the context's namespace already binds conflicts the same way, with the +namespace's blanket impl, so a context adds entries only at keys the namespace leaves open. -**A hand-written impl loses the diagnostics.** It wires correctly and silently gives up the `IsProviderFor` -forwarding that makes a missing transitive dependency readable. Use the macro. +**`Self` is not always a context.** A provider bundle declared with `new` owns a table too, and an +error naming one as the table does not mean something is being used as a context. -**The table is resolved at compile time, in full.** There is no runtime map to inspect, no way to add an -entry dynamically, and no cost per call. If you are looking for a place to register something at startup, -this is not it, and that is the point. +**The table is resolved at compile time, in full.** There is no runtime map to inspect and no way to +add an entry dynamically. If you are looking for a place to register something at startup, this is +not it. ## Related constructs -- [`delegate_components!`](../../macros/delegate_components.md): the macro that generates these impls; what - you write instead of the trait. -- [`#[cgp_component]`](../../macros/cgp_component.md): generates the blanket impl that reads the table. -- [`IsProviderFor`](./is_provider_for.md): emitted beside each entry so a missing dependency stays - readable. -- [`CanUseComponent`](./can_use_component.md): combines a delegation and a valid provider into one +- [`delegate_components!`](../../macros/delegate_components.md): the macro that generates these + impls; what you write instead of the trait. +- [`#[cgp_component]`](../../macros/cgp_component.md): generates the blanket impl that reads the + table. +- [`IsProviderFor`](./is_provider_for.md): emitted beside each entry, and required with it. +- [`CanUseComponent`](./can_use_component.md): combines an entry and a valid provider into one assertion. -- [`check_components!`](../../macros/check_components.md): asserts that combination. -- [`UseDelegate`](../../providers/use_delegate.md): reads an arbitrary-key table for per-type dispatch. -- [`RedirectLookup`](../../providers/redirect_lookup.md): walks path-keyed entries; the namespace mechanism. -- [`DefaultNamespace`](../namespace/default_namespace.md): the lookup traits a `namespace` header forwards through. +- [`UseDelegate`](../../providers/use_delegate.md): reads a table keyed on other types, for dispatch + per type. +- [`RedirectLookup`](../../providers/redirect_lookup.md): reads a path-keyed entry; the mechanism + behind `open` and namespaces. The ideas behind it: - [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits): the split this table connects. - [Bypassing coherence](/docs/concepts/coherence): why the choice is recorded per context at all. -- [Aggregate providers](/docs/concepts/aggregate-providers): a table owned by a provider rather than a - context. +- [Aggregate providers](/docs/concepts/aggregate-providers): a table owned by a provider rather than + a context. ## Source -- Trait: [`delegate_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/delegate_component.rs) -- Entry codegen: [`delegate_component/mapping/eval.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/delegate_component/mapping/eval.rs) -- The blanket impl that reads it: [`cgp_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component) +- [`traits/delegate_component.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/delegate_component.rs) +- The entry codegen, in + [`delegate_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component), + and the blanket impl that reads it, in + [`cgp_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component). --- diff --git a/docs/reference/traits/wiring/index.md b/docs/reference/traits/wiring/index.md index 92b3df64..dd3ea627 100644 --- a/docs/reference/traits/wiring/index.md +++ b/docs/reference/traits/wiring/index.md @@ -1,4 +1,5 @@ --- +description: 'The three traits a context''s wiring rests on: the table entry, the marker that names a missing dependency, and the check that combines them.' sidebar_label: 'Overview' sidebar_position: 0 --- @@ -9,9 +10,9 @@ The three traits every context's wiring rests on, and the ones a wiring error na ## Overview -Wiring a **context**, the type a method runs on, records which provider it uses for each -component and checks that the provider's own requirements are met. These traits carry that, and you -read them far more often than you write them, because a +Wiring a [**context**](/docs/reference/glossary#context), the type the implementation runs against, +records which provider it uses for each component and checks that the provider's own requirements +are met. These traits carry that, and you read them far more often than you write them, because a [`delegate_components!`](../../macros/delegate_components.md) table generates the first two and a [`check_components!`](../../macros/check_components.md) block asserts the third. diff --git a/docs/reference/traits/wiring/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md index f9965489..12ddc2dc 100644 --- a/docs/reference/traits/wiring/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -1,268 +1,335 @@ --- +title: 'IsProviderFor — name a missing dependency' +description: 'The empty marker every provider trait requires, implemented under the provider''s own where clause so a check can name the dependency a provider is missing.' sidebar_label: 'IsProviderFor' sidebar_position: 2 --- # `IsProviderFor` -The marker [supertrait](/docs/reference/glossary#supertrait) that makes a provider's missing dependency show up by name. +The marker [supertrait](/docs/reference/glossary#supertrait) that makes a provider's missing +dependency show up by name. :::info ### Generated machinery -**You never write `IsProviderFor` yourself.** The provider macros, -[`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md) (which also -covers `#[cgp_new_provider]`), derive it from the same `where` clause you already wrote. This page explains what they emit, because this trait is what a missing-dependency error -names, and reading that error is the reason to know it exists. +**You are not expected to implement `IsProviderFor`.** The provider macros, +[`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md) +(which also covers `#[cgp_new_provider]`), emit its impl from the `where` clause you already wrote, +and [`delegate_components!`](../../macros/delegate_components.md) forwards it through each table +entry. The one place you name it is an assertion, usually through the `#[check_providers(...)]` form +of [`check_components!`](../../macros/check_components.md). This page explains what the macros emit, +because this trait is what a missing-dependency error names. ::: ## Overview -An implementation in CGP states what it needs from its **context**, the type the method runs on, -in its own `where` clause: a field, an [abstract type](/docs/reference/glossary#abstract-type), another trait. When one of those requirements is -not met, you want the compiler to say *which*. Left to itself, it will not. - -The reason is a specific behaviour of Rust's diagnostics. Asking "does this provider implement the provider -trait?" has two candidate answers in scope (the blanket impl that routes through the wiring table, and the -implementation you wrote), and when more than one impl could apply, Rust reports only that none matched and -withholds the per-candidate reasoning, because it cannot know which one you meant. The real cause, often a -single absent field, never appears. - -`IsProviderFor` is a second path to the same question that Rust *will* explain. It is an empty marker trait, -and the macros implement it for a provider under **exactly the same** `where` bounds as the provider trait -itself. Every generated provider trait carries it as a supertrait, so asking whether a provider satisfies -`IsProviderFor` forces the compiler to evaluate those bounds, and because that question has only one -candidate impl, with no blanket competing with it, the compiler commits to it and reports precisely which -constraint failed. - -**This is invisible plumbing until you read an error.** You never write it and never call it. It buys the -difference between "the trait is not implemented" and "the field `name` is missing on `App`", and it is -the mechanism [`check_components!`](../../macros/check_components.md) leans on to produce the second. +A provider states what it needs from its [**context**](/docs/reference/glossary#context), the type +the implementation runs against, in its own `where` clause: a field, an +[abstract type](/docs/reference/glossary#abstract-type), another trait. When one of those +requirements is not met, you want the compiler to say which, and left to itself it will not. Asking +whether a provider implements its provider trait has two candidate impls in scope, the blanket impl +that routes through the wiring table and the one you wrote, and when more than one impl could apply, +rustc reports only that none matched. + +`IsProviderFor` is a second path to the same question, with one candidate. It is an empty marker +trait, and the provider macros implement it for a provider under exactly the provider trait impl's +`where` bounds. With no competing impl, the compiler commits to that one and reports which bound +failed. So the trait buys the difference between "the trait is not implemented" and "`Person` has no +`name` field", and it is what [`check_components!`](../../macros/check_components.md) relies on to +report the second. ## Definition -`IsProviderFor` is an empty marker trait with three type parameters: +`IsProviderFor` is an empty trait with three type parameters: ```rust pub trait IsProviderFor {} ``` -The four types together identify one provider-trait implementation. `Self` is the **provider** whose -validity is asserted. `Component` is the component-name marker, the same key the wiring table uses. -`Context` is the context the provider trait is implemented for. `Params` collects the component's own -extra generic parameters, and it defaults to the unit tuple `()` for a component that has none; how -several parameters are grouped is covered under [How `Params` is filled](#how-params-is-filled). The -trait has no method and no associated item. [`#[cgp_component]`](../../macros/cgp_component.md) attaches -it as a supertrait on every provider trait, so using a provider trait requires establishing -`IsProviderFor` first, which is why probing the marker probes the provider trait's whole dependency set. +The four types together identify one provider trait impl: + +- **`Self`** is the provider whose validity is asserted. +- **`Component`** is the component's marker, the same key the wiring table uses. +- **`Context`** is the context the provider trait is implemented for. +- **`Params`** holds the component's own generic parameters, and defaults to `()` for a component + with none; [Usage](#how-params-is-filled) gives the rule. + +[`#[cgp_component]`](../../macros/cgp_component.md) makes it a supertrait of every provider trait, +so using a provider trait requires `IsProviderFor` first. Probing the marker therefore probes the +provider trait's whole dependency set. ## Usage -The trait is in the prelude, so `use cgp::prelude::*;` names it. You never implement it; the useful -operations are supplying `Params` correctly and, occasionally, asserting the marker. +The trait is in the prelude, so `use cgp::prelude::*;` names it. ### How `Params` is filled -This is the only part with a rule worth memorizing, and it is what a hand-written assertion gets wrong. +The component's generic parameters go into `Params` by one rule: - A component with **no** parameters uses the default, `()`. -- A component with **one** parameter passes it directly: `IsProviderFor`. -- A component with **several** groups them into a tuple: `IsProviderFor`. -- A **lifetime** parameter is lifted into [`Life<'a>`](../../types/life.md), because the tuple holds types and a - lifetime cannot sit there directly. +- A component with **one** parameter passes it directly, as in + `IsProviderFor`. +- A component with **several** groups them into a tuple, as in + `IsProviderFor`. +- A **lifetime** parameter is lifted into [`Life<'a>`](../../types/life.md), since the tuple holds + types. + +The same rule fills the `Params` of [`CanUseComponent`](./can_use_component.md) and the parameter +list of a [`check_components!`](../../macros/check_components.md) entry. ### Asserting it -You do not implement the trait; you occasionally *assert* it, which is a `where` bound on an empty function: +You assert the trait rather than implement it, as a `where` bound on an empty function: ```rust -fn assert_provider() +pub fn assert_provider() where - GreetHello: IsProviderFor, -{} + RectangleArea: IsProviderFor, +{ +} ``` -That holds exactly when `GreetHello`'s dependencies are satisfied for `App`. In practice you write this -through the `#[check_providers(...)]` form of [`check_components!`](../../macros/check_components.md) rather -than by hand. That form is the tool for localizing a failure inside a stack of -[higher-order providers](/docs/concepts/higher-order-providers), where checking the context tells you a layer -is broken but not which one. +The bound holds exactly when `RectangleArea`'s dependencies are met for `App`, whether or not `App` +wires it. The `#[check_providers(...)]` form of `check_components!` writes such assertions for you, +which is how a failure inside a stack of +[higher-order providers](/docs/concepts/higher-order-providers) is pinned to one layer. ## Examples -The trait is something you observe. A provider that needs a field gets a matching marker impl automatically: +A provider with a dependency, a context that meets it, and the marker asserted both through the +context and on the provider itself: ```rust use cgp::prelude::*; +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + #[cgp_component(Greeter)] pub trait CanGreet { - fn greet(&self); + fn greet(&self) -> String; } #[cgp_impl(new GreetHello)] #[uses(HasName)] impl Greeter { - fn greet(&self) { - println!("Hello, {}!", self.name()); + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) } } -``` -`#[cgp_impl]` emits the `Greeter` impl *and* an `IsProviderFor` impl for -`GreetHello`, both guarded by the same `Self: HasName` bound. Now wire it onto a context that cannot satisfy -that bound: - -```rust #[derive(HasField)] -pub struct App { - pub first_name: String, // not `name` +pub struct Person { + pub name: String, } delegate_components! { - App { GreeterComponent: GreetHello } + Person { + GreeterComponent: GreetHello, + } } check_components! { - App { GreeterComponent } + Person { + GreeterComponent, + } +} + +check_components! { + #[check_trait(CheckGreetHello)] + #[check_providers(GreetHello)] + Person { + GreeterComponent, + } +} + +pub fn demo() { + let person = Person { + name: "Ada".to_owned(), + }; + + assert_eq!(person.greet(), "Hello, Ada!"); } ``` -The check forces `App: CanUseComponent`, which routes through -`GreetHello: IsProviderFor`, whose `where` clause names the `HasName` -requirement, so the error names the absent field, at the wiring site. Remove the `check_components!` block -and the same mistake surfaces far away, at whatever calls `app.greet()`, as a much worse message. +The first check asserts it through `Person`'s wiring, and the second on `GreetHello` directly, as +`GreetHello: IsProviderFor`; the second needs its own trait name, +since two checks in one module would otherwise both declare `__CheckPerson`. Both hold because +`Person` has a `name` field. `Person` is a +[value context](/docs/reference/glossary#value-context): the greeting reads its own field. ## When to use it -**Do not reach for it. Recognize it.** There is no case in ordinary CGP code where you write -`IsProviderFor`: the provider macros emit the impl, `#[cgp_component]` emits the supertrait link, and -[`delegate_components!`](../../macros/delegate_components.md) emits the forwarding. You instead read it in -an error and, occasionally, assert it through a check. +**Recognize it; do not write it.** The provider macros emit the impl, `#[cgp_component]` the +supertrait link, and `delegate_components!` the forwarding, so ordinary CGP code never implements +it. Two situations put its name in your hands, and both are about diagnosis: -Two situations do put its name in your hands, and both are about diagnosis rather than construction. +- **Localizing a broken layer in a [higher-order + provider](/docs/reference/glossary#higher-order-provider) stack.** Checking the context proves + that something in the stack is unsatisfied; `#[check_providers(...)]` asserts `IsProviderFor` on + each named provider instead, so a dependency missing only from the outer wrapper errors on its + line alone, while one missing from the inner provider errors on both. +- **Reading a diagnostic.** A compiler note or a [`cargo cgp check`](/docs/cargo-cgp/check) chain + that names `IsProviderFor` for a provider means "this provider's requirements, for this + context", and the frame below it names the requirement. -- **Localizing a broken layer in a [higher-order provider](/docs/reference/glossary#higher-order-provider) stack.** Checking the context proves *something* - in the stack is unsatisfied. `#[check_providers(...)]` asserts `IsProviderFor` on each named provider - instead, so a dependency missing only from the outer wrapper errors on its line alone while one missing - from the inner provider errors on both, which pins the layer. -- **Reading a `[CGP-Exxx]` diagnostic.** `cargo cgp check` names this trait in the dependency chain it - renders, and knowing that a frame means "this provider's requirements, for this context" is what makes - the chain readable. - -If you find yourself wanting to implement it by hand, the thing you actually want is -[`#[cgp_provider]`](../../macros/cgp_provider.md) or [`#[cgp_impl]`](../../macros/cgp_impl.md) on the impl block. -A provider-trait impl written without either attribute is the one case where a missing marker impl is -the reported problem rather than the hidden one. +If you want to implement it by hand, what you want is +[`#[cgp_provider]`](../../macros/cgp_provider.md) or [`#[cgp_impl]`](../../macros/cgp_impl.md) on +the impl block. ## Under the hood -`IsProviderFor` appears in three places, and together they form the chain an error travels along. +`IsProviderFor` appears in three places in an expansion, and together they form the chain an error +travels along. `cargo cgp expand` on the example shows the second and third. -**The supertrait link.** [`#[cgp_component]`](../../macros/cgp_component.md) emits every provider trait -with the marker as a supertrait, so for a component `CanGetFooAt` the provider trait reads: +**The supertrait link.** [`#[cgp_component]`](../../macros/cgp_component.md) gives every provider +trait the marker as a supertrait. For the `AreaCalculator` component of [Usage](#usage), whose +consumer trait is `CanCalculateArea`, the provider trait begins: ```rust -pub trait FooGetterAt: - IsProviderFor -{ /* … */ } +pub trait AreaCalculator< + __Context__, + Shape, +>: IsProviderFor { ``` -This binds a provider's dependency set to the marker: using the provider trait *requires* -establishing `IsProviderFor` first, so probing the marker is equivalent to probing the provider trait. +`(Shape)` is the one parameter in parentheses, not a tuple, which is the Params rule at work. -**The per-provider impl.** [`#[cgp_provider]`](../../macros/cgp_provider.md) and -[`#[cgp_impl]`](../../macros/cgp_impl.md) emit an empty impl beside the provider trait impl, carrying identical -bounds: +**The per-provider impl.** [`#[cgp_impl]`](../../macros/cgp_impl.md) emits, beside the provider +trait impl, an empty marker impl under the same bound: ```rust -impl Greeter for GreetHello +impl<__Context__> Greeter<__Context__> for GreetHello where - Context: HasName, -{ /* … */ } - -impl IsProviderFor for GreetHello + __Context__: HasName, +{ + fn greet(__context__: &__Context__) -> String { + ::alloc::__export::must_use({ + ::alloc::fmt::format(format_args!("Hello, {0}!", __context__.name())) + }) + } +} +impl<__Context__> IsProviderFor for GreetHello where - Context: HasName, + __Context__: HasName, {} ``` -Identical `where` clauses mean the marker is satisfiable exactly when the provider trait is. That is the -whole trick. +Identical `where` clauses make the marker satisfiable exactly when the provider trait is. The clause +is augmented rather than copied in one case: a bound naming a component's provider trait, as a +higher-order provider's inner-provider bound does, gains its marker counterpart, which carries an +inner provider's requirements outward through the stack. -**The table forwarding.** [`delegate_components!`](../../macros/delegate_components.md) emits, for each -entry, an impl on the table that forwards to the delegated provider's marker: +**The table forwarding.** [`delegate_components!`](../../macros/delegate_components.md) emits, for +each entry, an impl on the table that forwards to the chosen provider's marker: ```rust -impl IsProviderFor for AppComponents +impl<__Context__, __Params__> IsProviderFor +for Person where - GreetHello: IsProviderFor, + GreetHello: IsProviderFor, {} ``` -Because this is an explicit impl rather than a blanket, the compiler follows it and surfaces everything -`GreetHello` requires. It also carries requirements *across layers*: when a provider bundle delegates -to another bundle, each forwards to the next, so a dependency unmet several tables deep still propagates back -to where the component is checked. - -One refinement is worth knowing, because it is what makes `#[check_providers]` able to localize a layer: the -clause the provider macros derive is **augmented rather than copied**. A bound naming the component's own -provider trait gains its marker counterpart, which is the mechanism that carries an inner provider's -requirements outward through a higher-order stack. +Because this is an impl on a specific table rather than a blanket, the compiler follows it and +surfaces everything `GreetHello` requires. When a context delegates to a provider bundle that +delegates further, each table forwards to the next, so a requirement unmet several tables deep still +reaches the check. ## Common Mistakes -**`Params` grouping is the usual mistake in a hand-written assertion.** One parameter goes in directly, two -or more as a tuple, none as `()`. Getting it wrong reports as an unsatisfied bound on a trait you did not -expect, rather than as a helpful arity error. +**Read the error as "because", not "instead".** Give the example's `Person` a differently named +field, and its check fails: -**A lifetime parameter becomes [`Life<'a>`](../../types/life.md) in the tuple.** It cannot appear as a bare -lifetime in a type position, so it is lifted. +```rust +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} +``` + +The notes name the marker as the step between the check and the real cause, down to the attribute +that introduced the bound: + +```text +error[E0277]: the trait bound `Person: CanUseComponent` is not satisfied +... +note: required for `Person` to implement `HasName` +... +note: required for `GreetHello` to implement `IsProviderFor` +... + | ------- unsatisfied trait bound introduced here +``` -**A missing marker impl usually means a missing attribute.** If the compiler says a provider does not -implement `IsProviderFor`, the likeliest cause is a provider-trait impl written without -[`#[cgp_provider]`](../../macros/cgp_provider.md). +The marker is not the problem; the missing `name` field, which the error's help line names as an +unimplemented `HasField`, is. -**Read it as "because", not as "instead".** `GreetHello: IsProviderFor<…> is not satisfied` does not mean the -marker is the problem; it means the provider trait is not implemented *because* the named dependency is -missing. The useful part of the message is the constraint underneath. +**One parameter is not a one-element tuple.** Writing the Usage assertion with `(Rectangle,)`, +as `RectangleArea: IsProviderFor`, asserts a different +bound, which rustc reports with the mismatch: -**It is empty, so satisfying it costs nothing.** There is no method, no data, and nothing in the binary. The -only effect is the compile-time obligation its `where` clause imposes. +```text +error[E0277]: the trait bound `RectangleArea: cgp::prelude::IsProviderFor` is not satisfied +... + = help: for that trait implementation, expected `Rectangle`, found `(Rectangle,)` +``` + +**A missing marker impl means a missing attribute.** A provider trait impl written without +[`#[cgp_provider]`](../../macros/cgp_provider.md) gets no marker impl, so it fails its own +supertrait: + +```rust +pub struct GreetHello; + +impl Greeter for GreetHello { + fn greet(_context: &Context) -> String { + "Hello!".to_owned() + } +} +``` + +```text +error[E0277]: the trait bound `GreetHello: IsProviderFor` is not satisfied +``` -**A higher-order provider with a lifetime loses the propagation.** The inner-provider bound of such a stack -gets no marker counterpart when the component carries a lifetime, because the rewrite reads the bound's first -generic argument as the context and finds a lifetime there. The stack still compiles and runs; what is lost -is the propagation that lets `#[check_providers]` localize a broken layer. +**A higher-order provider over a component with a lifetime loses the propagation.** The rewrite +reads the inner-provider bound's first generic argument as the context and finds a lifetime there, +so the bound gets no marker counterpart. The stack still compiles and runs; what is lost is the +propagation that lets `#[check_providers]` localize a broken layer. ## Related constructs -- [`#[cgp_component]`](../../macros/cgp_component.md): attaches the marker as a supertrait on every provider - trait. -- [`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md): emit the - per-provider impl beside the provider trait impl. -- [`delegate_components!`](../../macros/delegate_components.md): emits the forwarding impl at each table entry. -- [`DelegateComponent`](./delegate_component.md): the table those entries live in. -- [`CanUseComponent`](./can_use_component.md): the context-indexed counterpart, which requires this of the - delegate. -- [`check_components!`](../../macros/check_components.md): forces both; its `#[check_providers(...)]` form - asserts this trait directly. -- [Compile errors](../../errors.md): how the resulting diagnostics read, and what the tool makes of them. +- [`#[cgp_component]`](../../macros/cgp_component.md): makes the marker a supertrait of every + provider trait. +- [`#[cgp_impl]`](../../macros/cgp_impl.md) and [`#[cgp_provider]`](../../macros/cgp_provider.md): + emit the per-provider impl. +- [`delegate_components!`](../../macros/delegate_components.md): emits the forwarding impl at each + table entry. +- [`CanUseComponent`](./can_use_component.md): the context-side counterpart, which requires this of + the delegate. +- [`check_components!`](../../macros/check_components.md): asserts it, directly with + `#[check_providers(...)]`. +- [Compile errors](../../errors.md): how the resulting diagnostics read. The ideas behind it: -- [Check traits](/docs/concepts/check-traits): why wiring is lazy and how an assertion makes its failures - readable. -- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the `where`-clause requirements this - trait re-exposes. +- [Check traits](/docs/concepts/check-traits): why wiring is lazy and how an assertion makes its + failures readable. +- [Impl-side dependencies](/docs/concepts/impl-side-dependencies): the `where`-clause requirements + this trait re-exposes. ## Source -- Trait: [`is_provider.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/is_provider.rs) -- Supertrait link and per-provider impl: [`cgp_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component) -- Table forwarding: [`delegate_component/mapping/eval.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/delegate_component/mapping/eval.rs) +- [`traits/is_provider.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-component/src/traits/is_provider.rs) +- The supertrait link and the per-provider impl, in + [`cgp_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component), + and the table forwarding, in + [`delegate_component/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/delegate_component). --- diff --git a/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.rs b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.rs new file mode 100644 index 00000000..3818734c --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.rs @@ -0,0 +1,32 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +#[cgp_impl(new GreetHi)] +impl Greeter { + fn greet(&self) -> String { + "Hi!".to_owned() + } +} + +pub struct App; + +// Two entries for one key are two impls of one trait for one type. +delegate_components! { + App { + GreeterComponent: GreetHello, + GreeterComponent: GreetHi, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.stderr b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.stderr new file mode 100644 index 00000000..679896f0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.stderr @@ -0,0 +1,15 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.rs:28:9 + | +27 | GreeterComponent: GreetHello, + | ---------------- first implementation here +28 | GreeterComponent: GreetHi, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `App` + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_duplicate_entry.rs:28:9 + | +27 | GreeterComponent: GreetHello, + | ---------------- first implementation here +28 | GreeterComponent: GreetHi, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs new file mode 100644 index 00000000..5589de23 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs @@ -0,0 +1,24 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +pub struct App; + +// The entry alone, without the `IsProviderFor` impl `delegate_components!` emits beside it. +impl DelegateComponent for App { + type Delegate = GreetHello; +} + +fn main() { + let _ = App.greet(); +} diff --git a/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.stderr b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.stderr new file mode 100644 index 00000000..a21820d4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.stderr @@ -0,0 +1,41 @@ +error[E0599]: the method `greet` exists for struct `App`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs:23:17 + | +15 | pub struct App; + | -------------- method `greet` not found for this struct because it doesn't satisfy `App: CanGreet` or `App: Greeter` +... +23 | let _ = App.greet(); + | ^^^^^ this is an associated function, not a method + | + = note: found the following associated functions; to be used as methods, functions must have a `self` parameter +note: the candidate is defined in the trait `Greeter` + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs:5:5 + | + 5 | fn greet(&self) -> String; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: trait bound `App: Greeter` was not satisfied + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs:3:1 + | + 3 | #[cgp_component(Greeter)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 | pub trait CanGreet { + | ^^^^^^^^ +note: the trait `Greeter` must be implemented + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs:4:1 + | + 4 | / pub trait CanGreet { + 5 | | fn greet(&self) -> String; + 6 | | } + | |_^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `CanGreet` defines an item `greet`, perhaps you need to implement it + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_hand_written_entry.rs:4:1 + | + 4 | pub trait CanGreet { + | ^^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use associated function syntax instead + | +23 - let _ = App.greet(); +23 + let _ = App::greet(); + | diff --git a/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.rs b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.rs new file mode 100644 index 00000000..01fbe87d --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.rs @@ -0,0 +1,31 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +#[cgp_impl(new GreetHi)] +impl Greeter { + fn greet(&self) -> String { + "Hi!".to_owned() + } +} + +pub struct App; + +// `App` has no table entry for `GreeterComponent`. +check_components! { + App { + GreeterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.stderr b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.stderr new file mode 100644 index 00000000..94bb43c9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.stderr @@ -0,0 +1,32 @@ +error[E0277]: the trait bound `App: CanUseComponent` is not satisfied + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.rs:27:9 + | +27 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `DelegateComponent` is not implemented for `App` + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.rs:22:1 + | +22 | pub struct App; + | ^^^^^^^^^^^^^^ + = help: the following other types implement trait `DelegateComponent`: + `BuildAndMergeOutputs` implements `DelegateComponent` + `BuildAndMergeOutputs` implements `DelegateComponent` + `BuildAndMergeOutputs` implements `DelegateComponent` + `BuildAndMergeOutputs` implements `DelegateComponent` + `BuildAndMergeOutputs` implements `DelegateComponent` + `BuildAndMergeOutputs` implements `DelegateComponent` + `MatchFirstWithFieldHandlersInputs` implements `DelegateComponent<(Input, Args)>` + `MatchFirstWithFieldHandlersInputsMut` implements `DelegateComponent<(&'a mut Input, Args)>` + and $N others + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/reference/traits/delegate_component_common_mistakes_missing_entry.rs:25:1 + | +25 | / check_components! { +26 | | App { +27 | | GreeterComponent, +28 | | } +29 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.rs b/example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.rs new file mode 100644 index 00000000..06987ddd --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.rs @@ -0,0 +1,43 @@ +use cgp::prelude::*; + +#[cgp_getter(NameGetter)] +pub trait HasName { + fn name(&self) -> &String; +} + +pub struct Profile { + pub display_name: String, +} + +#[derive(HasField)] +pub struct Account { + pub profile: Profile, +} + +pub struct ReadDisplayName; + +impl FieldGetter for ReadDisplayName +where + Context: HasField, +{ + type Value = String; + + fn get_field(context: &Context, _tag: PhantomData) -> &String { + &context.get_field(PhantomData).display_name + } +} + +// A `FieldGetter` provider does not implement the getter's provider trait itself. +delegate_components! { + Account { + NameGetterComponent: ReadDisplayName, + } +} + +check_components! { + Account { + NameGetterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.stderr b/example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.stderr new file mode 100644 index 00000000..9ceea331 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.stderr @@ -0,0 +1,32 @@ +error[E0277]: the trait bound `ReadDisplayName: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.rs:39:9 + | +39 | NameGetterComponent, + | ^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `ReadDisplayName` + --> tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.rs:17:1 + | +17 | pub struct ReadDisplayName; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: the following other types implement trait `IsProviderFor`: + `Account` implements `IsProviderFor` + `BindErr` implements `IsProviderFor)>` + `BindErr` implements `IsProviderFor)>` + `BindOk` implements `IsProviderFor)>` + `BindOk` implements `IsProviderFor)>` + `BuildAndMerge` implements `IsProviderFor` + `BuildAndMerge` implements `IsProviderFor` + `BuildAndMerge` implements `IsProviderFor` + and $N others + = note: required for `Account` to implement `CanUseComponent` +note: required by a bound in `__CheckAccount` + --> tests/compile_fail/reference/traits/field_getter_common_mistakes_without_with_provider.rs:37:1 + | +37 | / check_components! { +38 | | Account { +39 | | NameGetterComponent, +40 | | } +41 | | } + | |_^ required by this bound in `__CheckAccount` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.rs b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.rs new file mode 100644 index 00000000..ce7b992a --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.rs @@ -0,0 +1,25 @@ +use core::ops::Deref; + +use cgp::prelude::*; + +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +// `Wrapper` derefs to `Person`, which has `name`, so the forwarding impl already covers that tag. +#[derive(HasField)] +pub struct Wrapper { + pub name: String, + pub person: Person, +} + +impl Deref for Wrapper { + type Target = Person; + + fn deref(&self) -> &Person { + &self.person + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.stderr b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.stderr new file mode 100644 index 00000000..aa64365e --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.stderr @@ -0,0 +1,9 @@ +error[E0119]: conflicting implementations of trait `cgp::prelude::HasField>>>>>` for type `Wrapper` + --> tests/compile_fail/reference/traits/has_field_common_mistakes_deref_overlap.rs:13:9 + | +13 | pub name: String, + | ^^^^ + | + = note: conflicting implementation in crate `cgp_field`: + - impl cgp::prelude::HasField for Context + where ::Target == Target, >::Value == Value, Context: cgp::cgp_core::cgp_field::traits::has_field::DerefMap, Target: cgp::prelude::HasField; diff --git a/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs new file mode 100644 index 00000000..1c5a9d2d --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs @@ -0,0 +1,22 @@ +use cgp::prelude::*; + +pub fn read_first_name(context: &Context) -> &String +where + Context: HasField, +{ + context.get_field(PhantomData) +} + +// The field is spelled `firstName`, a different type-level name. +#[allow(non_snake_case)] +#[derive(HasField)] +pub struct Person { + pub firstName: String, +} + +fn main() { + let person = Person { + firstName: "Ada".to_owned(), + }; + let _ = read_first_name(&person); +} diff --git a/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr new file mode 100644 index 00000000..a2d70c08 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr @@ -0,0 +1,20 @@ +error[E0277]: the trait bound `Person: cgp::prelude::HasField>>>>>>>>>>>` is not satisfied + --> tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs:21:29 + | +21 | let _ = read_first_name(&person); + | ^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>>>>>>` is not implemented for `Person` + but trait `HasField>>>>>>>>>>` is implemented for it + --> tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs:14:9 + | +14 | pub firstName: String, + | ^^^^^^^^^ +note: required by a bound in `read_first_name` + --> tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs:5:14 + | + 3 | pub fn read_first_name(context: &Context) -> &String + | --------------- required by a bound in this function + 4 | where + 5 | Context: HasField, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `read_first_name` diff --git a/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.rs b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.rs new file mode 100644 index 00000000..54e913cd --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.rs @@ -0,0 +1,17 @@ +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +pub struct GreetHello; + +// A provider trait impl written without `#[cgp_provider]` gets no `IsProviderFor` impl. +impl Greeter for GreetHello { + fn greet(_context: &Context) -> String { + "Hello!".to_owned() + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.stderr b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.stderr new file mode 100644 index 00000000..1bde955f --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.stderr @@ -0,0 +1,27 @@ +error[E0277]: the trait bound `GreetHello: IsProviderFor` is not satisfied + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.rs:11:36 + | +11 | impl Greeter for GreetHello { + | ^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `GreetHello` + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.rs:8:1 + | + 8 | pub struct GreetHello; + | ^^^^^^^^^^^^^^^^^^^^^ + = help: the following other types implement trait `IsProviderFor`: + `BindErr` implements `IsProviderFor)>` + `BindErr` implements `IsProviderFor)>` + `BindOk` implements `IsProviderFor)>` + `BindOk` implements `IsProviderFor)>` + `BuildAndMerge` implements `IsProviderFor` + `BuildAndMerge` implements `IsProviderFor` + `BuildAndMerge` implements `IsProviderFor` + `BuildAndMergeOutputs` implements `IsProviderFor` + and $N others +note: required by a bound in `Greeter` + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_attribute.rs:3:1 + | + 3 | #[cgp_component(Greeter)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Greeter` + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs new file mode 100644 index 00000000..5553ba7d --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs @@ -0,0 +1,39 @@ +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasName { + fn name(&self) -> &str; +} + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +#[uses(HasName)] +impl Greeter { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } +} + +// The field is `first_name`, not `name`. +#[derive(HasField)] +pub struct Person { + pub first_name: String, +} + +delegate_components! { + Person { + GreeterComponent: GreetHello, + } +} + +check_components! { + Person { + GreeterComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.stderr b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.stderr new file mode 100644 index 00000000..b7f247d5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.stderr @@ -0,0 +1,37 @@ +error[E0277]: the trait bound `Person: CanUseComponent` is not satisfied + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs:35:9 + | +35 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>` is not implemented for `Person` + but trait `HasField>>>>>>>>>>>` is implemented for it + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs:24:9 + | +24 | pub first_name: String, + | ^^^^^^^^^^ +note: required for `Person` to implement `HasName` + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs:3:1 + | + 3 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ + 4 | pub trait HasName { + | ^^^^^^^ +note: required for `GreetHello` to implement `IsProviderFor` + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs:13:1 + | +13 | #[cgp_impl(new GreetHello)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +14 | #[uses(HasName)] + | ------- unsatisfied trait bound introduced here + = note: required for `Person` to implement `CanUseComponent` +note: required by a bound in `__CheckPerson` + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs:33:1 + | +33 | / check_components! { +34 | | Person { +35 | | GreeterComponent, +36 | | } +37 | | } + | |_^ required by this bound in `__CheckPerson` + = note: this error originates in the attribute macro `cgp_auto_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs new file mode 100644 index 00000000..709461f8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs @@ -0,0 +1,31 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, rectangle: &Rectangle) -> f64 { + rectangle.width * rectangle.height + } +} + +pub struct App; + +// One parameter is passed directly, not as a one-element tuple. +fn assert_provider() +where + RectangleArea: IsProviderFor, +{ +} + +fn main() { + assert_provider(); +} diff --git a/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.stderr b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.stderr new file mode 100644 index 00000000..c45699d9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.stderr @@ -0,0 +1,43 @@ +error[E0277]: the trait bound `RectangleArea: cgp::prelude::IsProviderFor` is not satisfied + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs:25:5 + | +25 | RectangleArea: IsProviderFor, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `RectangleArea` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs:14:1 + | +14 | / impl AreaCalculator { +15 | | fn area(&self, rectangle: &Rectangle) -> f64 { +16 | | rectangle.width * rectangle.height +17 | | } +18 | | } + | |_^ + = help: for that trait implementation, expected `Rectangle`, found `(Rectangle,)` + +error[E0277]: the trait bound `RectangleArea: cgp::prelude::IsProviderFor` is not satisfied + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs:30:5 + | +30 | assert_provider(); + | ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `IsProviderFor` is not implemented for `RectangleArea` + but trait `IsProviderFor` is implemented for it + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs:14:1 + | +14 | / impl AreaCalculator { +15 | | fn area(&self, rectangle: &Rectangle) -> f64 { +16 | | rectangle.width * rectangle.height +17 | | } +18 | | } + | |_^ + = help: for that trait implementation, expected `Rectangle`, found `(Rectangle,)` +note: required by a bound in `assert_provider` + --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_one_element_tuple.rs:25:20 + | +23 | fn assert_provider() + | --------------- required by a bound in this function +24 | where +25 | RectangleArea: IsProviderFor, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_provider` diff --git a/example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.rs b/example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.rs new file mode 100644 index 00000000..fe05ddd0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.rs @@ -0,0 +1,14 @@ +use cgp::prelude::*; + +// Two chained reads tie the inner borrow to a lifetime `Inner` is not known to outlive. +pub fn inner_name(context: &Context) -> &String +where + Context: HasField, + Inner: HasField, +{ + context + .get_field(PhantomData::) + .get_field(PhantomData::) +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.stderr b/example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.stderr new file mode 100644 index 00000000..0413edca --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.stderr @@ -0,0 +1,36 @@ +error[E0311]: the parameter type `Inner` may not live long enough + --> tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.rs:9:5 + | + 4 | pub fn inner_name(context: &Context) -> &String + | -------- the parameter type `Inner` must be valid for the anonymous lifetime defined here... +... + 9 | / context +10 | | .get_field(PhantomData::) + | |___________________________________________________^ ...so that the type `Inner` will meet its required lifetime bounds + | +help: consider adding an explicit lifetime bound + | + 4 ~ pub fn inner_name<'a, Context, Inner>(context: &'a Context) -> &'a String + 5 | where + 6 | Context: HasField, + 7 ~ Inner: HasField + 'a, + | + +error[E0311]: the parameter type `Inner` may not live long enough + --> tests/compile_fail/reference/traits/map_field_common_mistakes_chained_get_field.rs:9:5 + | + 4 | pub fn inner_name(context: &Context) -> &String + | -------- the parameter type `Inner` must be valid for the anonymous lifetime defined here... +... + 9 | / context +10 | | .get_field(PhantomData::) +11 | | .get_field(PhantomData::) + | |__________________________________________________^ ...so that the type `Inner` will meet its required lifetime bounds + | +help: consider adding an explicit lifetime bound + | + 4 ~ pub fn inner_name<'a, Context, Inner>(context: &'a Context) -> &'a String + 5 | where + 6 | Context: HasField, + 7 ~ Inner: HasField + 'a, + | diff --git a/example-code/tests/reference/traits/can_use_component.rs b/example-code/tests/reference/traits/can_use_component.rs new file mode 100644 index 00000000..42a810c8 --- /dev/null +++ b/example-code/tests/reference/traits/can_use_component.rs @@ -0,0 +1,90 @@ +//! Code from `docs/reference/traits/wiring/can_use_component.md` — `CanUseComponent`. +//! +//! Pins the Examples program: a component with no parameters and one with a parameter, each checked +//! through `check_components!` and through a hand-written `CanUseComponent` bound. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + #[uses(HasName)] + impl Greeter { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } + } + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, rectangle: &Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + #[derive(HasField)] + pub struct App { + pub name: String, + } + + delegate_components! { + App { + GreeterComponent: GreetHello, + AreaCalculatorComponent: RectangleArea, + } + } + + check_components! { + App { + GreeterComponent, + AreaCalculatorComponent: Rectangle, + } + } + + pub fn assert_wiring() + where + App: + CanUseComponent + CanUseComponent, + { + } + + pub fn demo() { + assert_wiring(); + + let app = App { + name: "Ada".to_owned(), + }; + let rectangle = Rectangle { + width: 3.0, + height: 4.0, + }; + + assert_eq!(app.greet(), "Hello, Ada!"); + assert_eq!(app.area(&rectangle), 12.0); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/delegate_component.rs b/example-code/tests/reference/traits/delegate_component.rs new file mode 100644 index 00000000..a5828e8b --- /dev/null +++ b/example-code/tests/reference/traits/delegate_component.rs @@ -0,0 +1,78 @@ +//! Code from `docs/reference/traits/wiring/delegate_component.md` — `DelegateComponent`. +//! +//! Pins the reading function from Usage and the Examples program: one component wired on a context, +//! and a table keyed on shapes whose entries a bound reads back. A duplicate entry and an unwired +//! component are trybuild fixtures. + +/// ## Usage +/// +/// Reading an entry is a bound plus a projection of `Delegate`. +pub mod usage { + use cgp::prelude::*; + + pub fn provider_for() -> PhantomData<
>::Delegate> + where + Table: DelegateComponent, + { + PhantomData + } +} + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + use super::usage::provider_for; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } + } + + pub struct App; + + delegate_components! { + App { + GreeterComponent: GreetHello, + } + } + + check_components! { + App { + GreeterComponent, + } + } + + pub struct Rectangle; + pub struct Circle; + pub struct RectangleArea; + pub struct CircleArea; + + delegate_components! { + new AreaComponents { + Rectangle: RectangleArea, + Circle: CircleArea, + } + } + + pub fn demo() { + assert_eq!(App.greet(), "Hello!"); + + // Each read resolves to the entry's value at compile time. + let _: PhantomData = provider_for::(); + let _: PhantomData = provider_for::(); + let _: PhantomData = provider_for::(); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/field_getter.rs b/example-code/tests/reference/traits/field_getter.rs new file mode 100644 index 00000000..95deca2c --- /dev/null +++ b/example-code/tests/reference/traits/field_getter.rs @@ -0,0 +1,86 @@ +//! Code from `docs/reference/traits/field-access/field_getter.md` — `FieldGetter`. +//! +//! Pins the Examples program: one getter component answered through `WithProvider` by two +//! `FieldGetter` providers, `UseField` reading a differently named field and a hand-written +//! provider reading a nested one. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::WithField; + use cgp::prelude::*; + + #[cgp_getter(NameGetter)] + pub trait HasName { + fn name(&self) -> &String; + } + + #[derive(HasField)] + pub struct Person { + pub first_name: String, + } + + delegate_components! { + Person { + NameGetterComponent: WithField, + } + } + + pub struct Profile { + pub display_name: String, + } + + #[derive(HasField)] + pub struct Account { + pub profile: Profile, + } + + pub struct ReadDisplayName; + + impl FieldGetter for ReadDisplayName + where + Context: HasField, + { + type Value = String; + + fn get_field(context: &Context, _tag: PhantomData) -> &String { + &context.get_field(PhantomData).display_name + } + } + + delegate_components! { + Account { + NameGetterComponent: WithProvider, + } + } + + check_components! { + Person { + NameGetterComponent, + } + } + + check_components! { + Account { + NameGetterComponent, + } + } + + pub fn demo() { + let person = Person { + first_name: "Ada".to_owned(), + }; + let account = Account { + profile: Profile { + display_name: "ada99".to_owned(), + }, + }; + + assert_eq!(person.name(), "Ada"); + assert_eq!(account.name(), "ada99"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/field_mapper.rs b/example-code/tests/reference/traits/field_mapper.rs new file mode 100644 index 00000000..0d15ace4 --- /dev/null +++ b/example-code/tests/reference/traits/field_mapper.rs @@ -0,0 +1,74 @@ +//! Code from `docs/reference/traits/field-access/field_mapper.md` — `FieldMapper`. +//! +//! Pins the Examples program: a two-step chain provider written with `FieldMapper::map_field`, +//! wired as a getter, and a direct `map_field` call through `UseContext`. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::FieldMapper; + use cgp::prelude::*; + + pub struct ThenGet(pub PhantomData<(First, Second)>); + + impl FieldGetter for ThenGet + where + First: FieldMapper, + Second: FieldGetter, + { + type Value = Value; + + fn get_field(context: &Context, tag: PhantomData) -> &Value { + First::map_field(context, tag, |mid| Second::get_field(mid, tag)) + } + } + + #[cgp_getter(NameGetter)] + pub trait HasName { + fn name(&self) -> &String; + } + + #[derive(HasField)] + pub struct Inner { + pub name: String, + } + + #[derive(HasField)] + pub struct Outer { + pub inner: Inner, + } + + delegate_components! { + Outer { + NameGetterComponent: + WithProvider, UseField>>, + } + } + + check_components! { + Outer { + NameGetterComponent, + } + } + + pub fn demo() { + let outer = Outer { + inner: Inner { + name: "Alice".to_owned(), + }, + }; + + assert_eq!(outer.name(), "Alice"); + + let name = >::map_field( + &outer, + PhantomData, + |inner| inner.get_field(PhantomData::), + ); + assert_eq!(name, "Alice"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/from_fields.rs b/example-code/tests/reference/traits/from_fields.rs new file mode 100644 index 00000000..ca46b54e --- /dev/null +++ b/example-code/tests/reference/traits/from_fields.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/traits/shape/from_fields.md` — `FromFields`. +//! +//! Pins the Examples program: a generic function that rebuilds a value from its shape, round-tripping +//! a struct and an enum. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] + pub struct Config { + pub host: String, + pub port: u16, + } + + #[derive(Clone, Debug, PartialEq, HasFields)] + pub enum Shape { + Circle(f64), + Square(f64), + } + + pub fn round_trip(value: T) -> T + where + T: ToFields + FromFields, + { + T::from_fields(value.to_fields()) + } + + pub fn demo() { + let config = Config { + host: "localhost".to_owned(), + port: 8080, + }; + assert_eq!(round_trip(config.clone()), config); + + assert_eq!(round_trip(Shape::Square(2.0)), Shape::Square(2.0)); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/has_field.rs b/example-code/tests/reference/traits/has_field.rs new file mode 100644 index 00000000..adaaa09f --- /dev/null +++ b/example-code/tests/reference/traits/has_field.rs @@ -0,0 +1,103 @@ +//! Code from `docs/reference/traits/field-access/has_field.md` — `HasField`. +//! +//! Pins the Examples program: a provider that bounds on a field and reads it, the `#[implicit]` form +//! of the same read, and a read through a `Box` that resolves by the `Deref` forwarding impl. A +//! misspelled field name and a `Deref` type that also derives the field are trybuild fixtures. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter + where + Self: HasField, + { + fn greet(&self) -> String { + format!("Hello, {}!", self.get_field(PhantomData::)) + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + pub fn read_name(context: &Context) -> &String + where + Context: HasField, + { + context.get_field(PhantomData) + } + + pub fn demo() { + let person = Person { + name: "Ada".to_owned(), + }; + assert_eq!(person.greet(), "Hello, Ada!"); + + // `Box` has the field through the `Deref` forwarding impl. + let boxed = Box::new(Person { + name: "Alice".to_owned(), + }); + assert_eq!(read_name(&boxed), "Alice"); + } + + #[test] + fn test_demo() { + demo(); + } + + /// The `#[implicit]` form of the same read. + pub mod implicit { + use cgp::prelude::*; + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + impl Greeter { + fn greet(&self, #[implicit] name: &str) -> String { + format!("Hello, {name}!") + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } + + #[test] + fn the_implicit_argument_reads_the_same_field() { + let person = Person { + name: "Ada".to_owned(), + }; + assert_eq!(person.greet(), "Hello, Ada!"); + } + } +} diff --git a/example-code/tests/reference/traits/has_field_mut.rs b/example-code/tests/reference/traits/has_field_mut.rs new file mode 100644 index 00000000..60c068b1 --- /dev/null +++ b/example-code/tests/reference/traits/has_field_mut.rs @@ -0,0 +1,65 @@ +//! Code from `docs/reference/traits/field-access/has_field_mut.md` — `HasFieldMut`. +//! +//! Pins the Examples program: a provider that increments a field of its context, and a write +//! through a `Box` that resolves by the `DerefMut` forwarding impl. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_component(Counter)] + pub trait CanCount { + fn count(&mut self); + } + + #[cgp_impl(new IncrementCounter)] + impl Counter + where + Self: HasFieldMut, + { + fn count(&mut self) { + *self.get_field_mut(PhantomData::) += 1; + } + } + + #[derive(HasField)] + pub struct App { + pub counter: u64, + } + + delegate_components! { + App { + CounterComponent: IncrementCounter, + } + } + + check_components! { + App { + CounterComponent, + } + } + + pub fn reset(context: &mut Context) + where + Context: HasFieldMut, + { + *context.get_field_mut(PhantomData) = 0; + } + + pub fn demo() { + let mut app = App { counter: 0 }; + app.count(); + app.count(); + assert_eq!(app.counter, 2); + + // `Box` has the field mutably through the `DerefMut` forwarding impl. + let mut boxed = Box::new(App { counter: 5 }); + reset(&mut boxed); + assert_eq!(boxed.counter, 0); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/has_fields.rs b/example-code/tests/reference/traits/has_fields.rs new file mode 100644 index 00000000..81610a53 --- /dev/null +++ b/example-code/tests/reference/traits/has_fields.rs @@ -0,0 +1,54 @@ +//! Code from `docs/reference/traits/shape/has_fields.md` — `HasFields`. +//! +//! Pins the Examples program: the shapes a struct, an enum, and a one-field tuple struct derive, +//! each asserted as a type equality through a generic bound. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(HasField, HasFields)] + pub struct Config { + pub host: String, + pub port: u16, + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(HasFields)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + #[derive(HasFields)] + pub struct UserId(pub u64); + + pub fn assert_shape() + where + T: HasFields, + { + } + + pub fn demo() { + assert_shape::, Field]>( + ); + assert_shape::< + Shape, + Sum![Field, Field], + >(); + assert_shape::(); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/has_fields_ref.rs b/example-code/tests/reference/traits/has_fields_ref.rs new file mode 100644 index 00000000..ada0e292 --- /dev/null +++ b/example-code/tests/reference/traits/has_fields_ref.rs @@ -0,0 +1,49 @@ +//! Code from `docs/reference/traits/shape/has_fields_ref.md` — `HasFieldsRef`. +//! +//! Pins the Examples program: the borrowed shape of a struct at a given lifetime, including a +//! field that is itself a reference and so gains a second one. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Config { + pub host: String, + pub port: u16, + } + + #[derive(HasFields)] + pub struct Greeting<'a> { + pub name: &'a str, + } + + pub fn assert_shape_ref<'a, T, FieldsRef>() + where + T: HasFieldsRef = FieldsRef> + 'a, + { + } + + pub fn demo() { + assert_shape_ref::< + 'static, + Config, + Product![ + Field, + Field, + ], + >(); + assert_shape_ref::< + 'static, + Greeting<'static>, + Product![ + Field, + ], + >(); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/is_provider_for.rs b/example-code/tests/reference/traits/is_provider_for.rs new file mode 100644 index 00000000..097d7f32 --- /dev/null +++ b/example-code/tests/reference/traits/is_provider_for.rs @@ -0,0 +1,104 @@ +//! Code from `docs/reference/traits/wiring/is_provider_for.md` — `IsProviderFor`. +//! +//! Pins the Params rule from Usage and the Examples program: a provider with a dependency, a context +//! that meets it, and the marker asserted both through the context and on the provider directly. A +//! context that misses the dependency, a one-element tuple for `Params`, and a provider impl written +//! without its attribute are trybuild fixtures. + +/// ## Usage +/// +/// One component parameter is passed directly as `Params`. +pub mod usage { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self, shape: &Shape) -> f64; + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, rectangle: &Rectangle) -> f64 { + rectangle.width * rectangle.height + } + } + + pub struct App; + + pub fn assert_provider() + where + RectangleArea: IsProviderFor, + { + } + + #[test] + fn one_parameter_is_passed_directly() { + assert_provider(); + } +} + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[cgp_auto_getter] + pub trait HasName { + fn name(&self) -> &str; + } + + #[cgp_component(Greeter)] + pub trait CanGreet { + fn greet(&self) -> String; + } + + #[cgp_impl(new GreetHello)] + #[uses(HasName)] + impl Greeter { + fn greet(&self) -> String { + format!("Hello, {}!", self.name()) + } + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + delegate_components! { + Person { + GreeterComponent: GreetHello, + } + } + + check_components! { + Person { + GreeterComponent, + } + } + + check_components! { + #[check_trait(CheckGreetHello)] + #[check_providers(GreetHello)] + Person { + GreeterComponent, + } + } + + pub fn demo() { + let person = Person { + name: "Ada".to_owned(), + }; + + assert_eq!(person.greet(), "Hello, Ada!"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/map_field.rs b/example-code/tests/reference/traits/map_field.rs new file mode 100644 index 00000000..85a602a0 --- /dev/null +++ b/example-code/tests/reference/traits/map_field.rs @@ -0,0 +1,70 @@ +//! Code from `docs/reference/traits/field-access/map_field.md` — `MapField`. +//! +//! Pins the Examples program: a generic function that reads a field of a field with `map_field`, +//! and the `ChainGetters` wiring that performs the same descent. The same read written as two +//! chained `get_field` calls is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::ChainGetters; + use cgp::core::field::traits::MapField; + use cgp::prelude::*; + + pub fn inner_name(context: &Context) -> &String + where + Context: HasField, + Inner: HasField, + { + context.map_field(PhantomData::, |inner| { + inner.get_field(PhantomData::) + }) + } + + #[cgp_getter(NameGetter)] + pub trait HasName { + fn name(&self) -> &String; + } + + #[derive(HasField)] + pub struct Inner { + pub name: String, + } + + #[derive(HasField)] + pub struct Outer { + pub inner: Inner, + } + + delegate_components! { + Outer { + NameGetterComponent: WithProvider< + ChainGetters, + UseField, + ]>, + >, + } + } + + check_components! { + Outer { + NameGetterComponent, + } + } + + pub fn demo() { + let outer = Outer { + inner: Inner { + name: "Alice".to_owned(), + }, + }; + + assert_eq!(inner_name(&outer), "Alice"); + assert_eq!(outer.name(), "Alice"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/mod.rs b/example-code/tests/reference/traits/mod.rs index 5a319fae..13898db3 100644 --- a/example-code/tests/reference/traits/mod.rs +++ b/example-code/tests/reference/traits/mod.rs @@ -11,9 +11,23 @@ pub mod can_build_from; pub mod can_downcast; pub mod can_downcast_fields; pub mod can_upcast; +pub mod can_use_component; pub mod concat_path; pub mod concat_product; +pub mod delegate_component; +pub mod field_getter; +pub mod field_mapper; +pub mod from_fields; pub mod has_builder; +pub mod has_field; +pub mod has_field_mut; +pub mod has_fields; +pub mod has_fields_ref; +pub mod is_provider_for; +pub mod map_field; pub mod map_fields; +pub mod mut_field_getter; pub mod static_format; pub mod static_string; +pub mod to_fields; +pub mod to_fields_ref; diff --git a/example-code/tests/reference/traits/mut_field_getter.rs b/example-code/tests/reference/traits/mut_field_getter.rs new file mode 100644 index 00000000..91bede75 --- /dev/null +++ b/example-code/tests/reference/traits/mut_field_getter.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/traits/field-access/mut_field_getter.md` — `MutFieldGetter`. +//! +//! Pins the Examples program: a getter with a `&mut self` method, answered through `WithField`, +//! whose `WithProvider` impl bounds on `MutFieldGetter`. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::WithField; + use cgp::prelude::*; + + #[cgp_getter(CounterGetter)] + pub trait HasCounter { + fn counter_mut(&mut self) -> &mut u64; + } + + #[derive(HasField)] + pub struct App { + pub request_count: u64, + } + + delegate_components! { + App { + CounterGetterComponent: WithField, + } + } + + check_components! { + App { + CounterGetterComponent, + } + } + + pub fn demo() { + let mut app = App { request_count: 0 }; + *app.counter_mut() += 1; + assert_eq!(app.request_count, 1); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/to_fields.rs b/example-code/tests/reference/traits/to_fields.rs new file mode 100644 index 00000000..f831fa15 --- /dev/null +++ b/example-code/tests/reference/traits/to_fields.rs @@ -0,0 +1,39 @@ +//! Code from `docs/reference/traits/shape/to_fields.md` — `ToFields`. +//! +//! Pins the Examples program: a value taken apart into its shape by a generic function, then read +//! from the product and rebuilt. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Clone, Debug, Eq, PartialEq, HasFields)] + pub struct Config { + pub host: String, + pub port: u16, + } + + pub fn shape_of(value: T) -> T::Fields + where + T: ToFields, + { + value.to_fields() + } + + pub fn demo() { + let config = Config { + host: "localhost".to_owned(), + port: 8080, + }; + + let fields = shape_of(config.clone()); + assert_eq!(fields.1 .0.value, 8080); + + assert_eq!(Config::from_fields(fields), config); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/to_fields_ref.rs b/example-code/tests/reference/traits/to_fields_ref.rs new file mode 100644 index 00000000..842827ac --- /dev/null +++ b/example-code/tests/reference/traits/to_fields_ref.rs @@ -0,0 +1,33 @@ +//! Code from `docs/reference/traits/shape/to_fields_ref.md` — `ToFieldsRef`. +//! +//! Pins the Examples program: reading a value's borrowed shape and using the value afterwards. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(HasFields)] + pub struct Config { + pub host: String, + pub port: u16, + } + + pub fn host_of(config: &Config) -> &String { + config.to_fields_ref().0.value + } + + pub fn demo() { + let config = Config { + host: "localhost".to_owned(), + port: 8080, + }; + + assert_eq!(host_of(&config), "localhost"); + assert_eq!(config.port, 8080); // `config` is still usable + } + + #[test] + fn test_demo() { + demo(); + } +} From 451f5f597dbee520196eec9b8e427d8adc3407f1 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 05:13:34 +0000 Subject: [PATCH 135/516] Name every FieldGetter provider and say who emits a path entry's tail Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/traits/field-access/field_getter.md | 3 ++- docs/reference/traits/wiring/delegate_component.md | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/reference/traits/field-access/field_getter.md b/docs/reference/traits/field-access/field_getter.md index b3d0df98..e810ac98 100644 --- a/docs/reference/traits/field-access/field_getter.md +++ b/docs/reference/traits/field-access/field_getter.md @@ -31,8 +31,9 @@ values it needs as its fields, decides which of its fields answers a getter. Tha provider-trait shape: a zero-sized provider as `Self`, and the context as an explicit type argument. `FieldGetter` is that shape, and it is the ordinary consumer and provider split applied to field -access: you bound against [`HasField`](./has_field.md), and you wire a `FieldGetter`. Three +access: you bound against [`HasField`](./has_field.md), and you wire a `FieldGetter`. Four library providers implement it. `UseField` reads the field `Tag`; +[`UseFieldRef`](../../providers/use_field_ref.md) reads one through `AsRef`; [`UseContext`](../../providers/use_context.md) reads the field named by the tag it is asked under; and [`ChainGetters`](../../providers/chain_getters.md) composes others to reach a nested field. diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index 4c45d0fc..87090af4 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -93,8 +93,8 @@ The key's type decides what an entry means, and three kinds occur: - **Any other type**, such as a shape or a tag. The table is a dispatch map with no provider trait attached, as the nested tables inside [`UseDelegate`](../../providers/use_delegate.md) are. - **A type-level path**, a [`PathCons`](../../types/path_cons.md) list, which is how the `open` - statement and namespaces key their entries. A path entry is written with a generic tail, so it - matches every longer path beneath it, and + statement and namespaces key their entries. The macro emits a path entry with a generic tail, so + it matches every longer path beneath it, and [`RedirectLookup`](../../providers/redirect_lookup.md) reads it with one lookup on the whole path. ### What owns a table From 2c6c75cdcb59098c52627cda3a23bbabd48b598b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 05:32:47 +0000 Subject: [PATCH 136/516] Mirror the builder and optional-field reference pages in example-code Adds one mirror per page under tests/reference/traits/ and trybuild fixtures for each quoted Common Mistakes error: building twice, taking an absent field, an uninferred or undeclared UpdateField target, a missing Default through a method call, an optional builder, and build_with_default, an extra source field, re-converting an optional builder, and set or finalize_optional on a core builder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- ...build_field_common_mistakes_build_twice.rs | 14 +++ ...d_field_common_mistakes_build_twice.stderr | 15 ++++ ...ault_common_mistakes_extra_source_field.rs | 25 ++++++ ..._common_mistakes_extra_source_field.stderr | 24 ++++++ ...with_default_common_mistakes_no_default.rs | 22 +++++ ..._default_common_mistakes_no_default.stderr | 18 ++++ ...with_default_common_mistakes_no_default.rs | 17 ++++ ..._default_common_mistakes_no_default.stderr | 37 ++++++++ ..._common_mistakes_optional_needs_default.rs | 19 +++++ ...mon_mistakes_optional_needs_default.stderr | 36 ++++++++ ...e_optional_common_mistakes_core_builder.rs | 13 +++ ...tional_common_mistakes_core_builder.stderr | 21 +++++ ...t_optional_common_mistakes_core_builder.rs | 13 +++ ...tional_common_mistakes_core_builder.stderr | 33 +++++++ .../take_field_common_mistakes_take_absent.rs | 13 +++ ...e_field_common_mistakes_take_absent.stderr | 15 ++++ ...tional_common_mistakes_already_optional.rs | 13 +++ ...al_common_mistakes_already_optional.stderr | 24 ++++++ ...eld_common_mistakes_marker_not_inferred.rs | 13 +++ ...common_mistakes_marker_not_inferred.stderr | 13 +++ ..._field_common_mistakes_undeclared_field.rs | 12 +++ ...ld_common_mistakes_undeclared_field.stderr | 21 +++++ .../tests/reference/traits/build_field.rs | 50 +++++++++++ .../traits/can_build_with_default.rs | 39 +++++++++ .../traits/can_finalize_with_default.rs | 34 ++++++++ .../tests/reference/traits/finalize_build.rs | 43 ++++++++++ .../reference/traits/finalize_optional.rs | 43 ++++++++++ .../tests/reference/traits/has_builder.rs | 85 ++++--------------- .../reference/traits/has_optional_builder.rs | 48 +++++++++++ .../tests/reference/traits/into_builder.rs | 46 ++++++++++ example-code/tests/reference/traits/mod.rs | 14 +++ .../tests/reference/traits/partial_data.rs | 35 ++++++++ .../tests/reference/traits/set_optional.rs | 34 ++++++++ .../tests/reference/traits/take_field.rs | 43 ++++++++++ .../tests/reference/traits/to_optional.rs | 41 +++++++++ .../reference/traits/transform_map_default.rs | 37 ++++++++ .../reference/traits/transform_optional.rs | 40 +++++++++ .../tests/reference/traits/update_field.rs | 42 +++++++++ 38 files changed, 1038 insertions(+), 67 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs create mode 100644 example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.rs create mode 100644 example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs create mode 100644 example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs create mode 100644 example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.rs create mode 100644 example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.rs create mode 100644 example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs create mode 100644 example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr create mode 100644 example-code/tests/reference/traits/build_field.rs create mode 100644 example-code/tests/reference/traits/can_build_with_default.rs create mode 100644 example-code/tests/reference/traits/can_finalize_with_default.rs create mode 100644 example-code/tests/reference/traits/finalize_build.rs create mode 100644 example-code/tests/reference/traits/finalize_optional.rs create mode 100644 example-code/tests/reference/traits/has_optional_builder.rs create mode 100644 example-code/tests/reference/traits/into_builder.rs create mode 100644 example-code/tests/reference/traits/partial_data.rs create mode 100644 example-code/tests/reference/traits/set_optional.rs create mode 100644 example-code/tests/reference/traits/take_field.rs create mode 100644 example-code/tests/reference/traits/to_optional.rs create mode 100644 example-code/tests/reference/traits/transform_map_default.rs create mode 100644 example-code/tests/reference/traits/transform_optional.rs create mode 100644 example-code/tests/reference/traits/update_field.rs diff --git a/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs new file mode 100644 index 00000000..2418ad99 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs @@ -0,0 +1,14 @@ +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +fn main() { + // `first_name` is already present when the second `build_field` asks to set it. + let _ = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .build_field(PhantomData::, "Bob".to_owned()); +} diff --git a/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr new file mode 100644 index 00000000..87be6271 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr @@ -0,0 +1,15 @@ +error[E0271]: type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsPresent>>::Mapper == IsNothing` + --> tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs:13:22 + | +13 | .build_field(PhantomData::, "Bob".to_owned()); + | ----------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsPresent>>::Mapper == IsNothing` + | | + | required by a bound introduced by this call + | +note: expected this to be `IsNothing` + --> tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs:3:10 + | + 3 | #[derive(BuildField)] + | ^^^^^^^^^^ + = note: required for `__PartialPerson` to implement `cgp::prelude::BuildField>>>>>>>>>>>` + = note: this error originates in the derive macro `BuildField` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.rs b/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.rs new file mode 100644 index 00000000..f3c9ac8a --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.rs @@ -0,0 +1,25 @@ +use cgp::extra::field::impls::CanBuildWithDefault; +use cgp::prelude::*; + +// The source has a `label` field that `Point3d` does not. +#[derive(CgpData)] +pub struct LabeledPoint2d { + pub x: u64, + pub y: u64, + pub label: String, +} + +#[derive(CgpData)] +pub struct Point3d { + pub x: u64, + pub y: u64, + pub z: u64, +} + +fn main() { + let _ = Point3d::build_with_default(LabeledPoint2d { + x: 1, + y: 2, + label: "origin".to_owned(), + }); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.stderr b/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.stderr new file mode 100644 index 00000000..1299656a --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.stderr @@ -0,0 +1,24 @@ +error[E0277]: the trait bound `__PartialPoint3d: UpdateField>>>>>, IsPresent>` is not satisfied + --> tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.rs:20:13 + | +20 | let _ = Point3d::build_with_default(LabeledPoint2d { + | ^^^^^^^ unsatisfied trait bound + | +help: the trait `UpdateField>>>>>, IsPresent>` is not implemented for `__PartialPoint3d` + --> tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.rs:13:1 + | +13 | pub struct Point3d { + | ^^^^^^^^^^^^^^^^^^ +help: the following other types implement trait `UpdateField` + --> tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_extra_source_field.rs:14:9 + | +14 | pub x: u64, + | ^ `__PartialPoint3d<__M1__, __F1__, __F2__>` implements `UpdateField>, __M2__>` +15 | pub y: u64, + | ^ `__PartialPoint3d<__F0__, __M1__, __F2__>` implements `UpdateField>, __M2__>` +16 | pub z: u64, + | ^ `__PartialPoint3d<__F0__, __F1__, __M1__>` implements `UpdateField>, __M2__>` + = note: required for `__PartialPoint3d` to implement `BuildField>>>>>>` + = note: required for `Cons>>>>>, String>, Nil>` to implement `cgp::cgp_core::cgp_field::impls::build_from::FieldsBuilder<__PartialLabeledPoint2d, __PartialPoint3d>` + = note: required for `__PartialPoint3d` to implement `CanBuildFrom` + = note: required for `Point3d` to implement `CanBuildWithDefault` diff --git a/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.rs b/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.rs new file mode 100644 index 00000000..1fe09cc5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.rs @@ -0,0 +1,22 @@ +use cgp::extra::field::impls::CanBuildWithDefault; +use cgp::prelude::*; + +// `Port` has no `Default`, and the source does not supply `port`. +pub struct Port(pub u16); + +#[derive(CgpData)] +pub struct Host { + pub host: String, +} + +#[derive(CgpData)] +pub struct Server { + pub host: String, + pub port: Port, +} + +fn main() { + let _ = Server::build_with_default(Host { + host: "localhost".to_owned(), + }); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.stderr b/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.stderr new file mode 100644 index 00000000..fec7a0aa --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.stderr @@ -0,0 +1,18 @@ +error[E0277]: the trait bound `Port: Default` is not satisfied + --> tests/compile_fail/reference/traits/can_build_with_default_common_mistakes_no_default.rs:19:13 + | +19 | let _ = Server::build_with_default(Host { + | ^^^^^^ the trait `Default` is not implemented for `Port` + | + = note: required for `TransformMapDefault` to implement `TransformMap` + = note: required for `Cons>>>>, Port>, Nil>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialServer, TransformMapDefault, IsPresent>` + = note: 1 redundant requirement hidden + = note: required for `Cons>>>>, String>, Cons>>>>, Port>, Nil>>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialServer, TransformMapDefault, IsPresent>` + = note: required for `__PartialServer` to implement `TransformMapFields` + = note: required for `__PartialServer` to implement `CanFinalizeWithDefault` + = note: required for `Server` to implement `CanBuildWithDefault` +help: consider annotating `Port` with `#[derive(Default)]` + | + 5 + #[derive(Default)] + 6 | pub struct Port(pub u16); + | diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.rs b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.rs new file mode 100644 index 00000000..7ae262c8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.rs @@ -0,0 +1,17 @@ +use cgp::extra::field::impls::CanFinalizeWithDefault; +use cgp::prelude::*; + +// `Port` has no `Default`, so an unset `port` cannot be filled. +pub struct Port(pub u16); + +#[derive(CgpData)] +pub struct Server { + pub host: String, + pub port: Port, +} + +fn main() { + let _ = Server::builder() + .build_field(PhantomData::, "localhost".to_owned()) + .finalize_with_default(); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr new file mode 100644 index 00000000..8fae6bdf --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr @@ -0,0 +1,37 @@ +error[E0599]: the method `finalize_with_default` exists for struct `__PartialServer`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.rs:16:10 + | + 8 | pub struct Server { + | ----------------- method `finalize_with_default` not found for this struct because `__PartialServer` doesn't implement `PartialData` or `TransformMapFields` +... +14 | let _ = Server::builder() + | _____________- +15 | | .build_field(PhantomData::, "localhost".to_owned()) +16 | | .finalize_with_default(); + | | -^^^^^^^^^^^^^^^^^^^^^ method cannot be called on `__PartialServer` due to unsatisfied trait bounds + | |_________| + | + | + = note: the following trait bounds were not satisfied: + `__PartialServer: TransformMapFields` + which is required by `__PartialServer: CanFinalizeWithDefault` + `<&__PartialServer as PartialData>::Target = _` + which is required by `&__PartialServer: CanFinalizeWithDefault` + `&__PartialServer: PartialData` + which is required by `&__PartialServer: CanFinalizeWithDefault` + `&__PartialServer: TransformMapFields` + which is required by `&__PartialServer: CanFinalizeWithDefault` + `<&mut __PartialServer as PartialData>::Target = _` + which is required by `&mut __PartialServer: CanFinalizeWithDefault` + `&mut __PartialServer: PartialData` + which is required by `&mut __PartialServer: CanFinalizeWithDefault` + `&mut __PartialServer: TransformMapFields` + which is required by `&mut __PartialServer: CanFinalizeWithDefault` +note: the trait `TransformMapFields` must be implemented + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + | +12 | pub trait TransformMapFields { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `finalize_with_default`, perhaps you need to implement it: + candidate #1: `CanFinalizeWithDefault` diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.rs b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.rs new file mode 100644 index 00000000..3eb09704 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.rs @@ -0,0 +1,19 @@ +use cgp::extra::field::impls::{CanFinalizeWithDefault, HasOptionalBuilder, SetOptional}; +use cgp::prelude::*; + +// `Port` has no `Default`. Setting `port` does not help: on an optional builder the field stays +// `IsOptional`, and `TransformMapDefault` converts `IsOptional` only for a `Default` type. +pub struct Port(pub u16); + +#[derive(CgpData)] +pub struct Server { + pub host: String, + pub port: Port, +} + +fn main() { + let _ = Server::optional_builder() + .set(PhantomData::, "localhost".to_owned()) + .set(PhantomData::, Port(8080)) + .finalize_with_default(); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr new file mode 100644 index 00000000..6b7c3805 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr @@ -0,0 +1,36 @@ +error[E0599]: the method `finalize_with_default` exists for struct `__PartialServer`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.rs:18:10 + | + 9 | pub struct Server { + | ----------------- method `finalize_with_default` not found for this struct because `__PartialServer` doesn't implement `PartialData` or `TransformMapFields` +... +15 | let _ = Server::optional_builder() + | _____________- +16 | | .set(PhantomData::, "localhost".to_owned()) +17 | | .set(PhantomData::, Port(8080)) +18 | | .finalize_with_default(); + | |_________-^^^^^^^^^^^^^^^^^^^^^ + | + = note: the following trait bounds were not satisfied: + `__PartialServer: TransformMapFields` + which is required by `__PartialServer: CanFinalizeWithDefault` + `<&__PartialServer as PartialData>::Target = _` + which is required by `&__PartialServer: CanFinalizeWithDefault` + `&__PartialServer: PartialData` + which is required by `&__PartialServer: CanFinalizeWithDefault` + `&__PartialServer: TransformMapFields` + which is required by `&__PartialServer: CanFinalizeWithDefault` + `<&mut __PartialServer as PartialData>::Target = _` + which is required by `&mut __PartialServer: CanFinalizeWithDefault` + `&mut __PartialServer: PartialData` + which is required by `&mut __PartialServer: CanFinalizeWithDefault` + `&mut __PartialServer: TransformMapFields` + which is required by `&mut __PartialServer: CanFinalizeWithDefault` +note: the trait `TransformMapFields` must be implemented + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + | +12 | pub trait TransformMapFields { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `finalize_with_default`, perhaps you need to implement it: + candidate #1: `CanFinalizeWithDefault` diff --git a/example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.rs b/example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.rs new file mode 100644 index 00000000..89782ff1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.rs @@ -0,0 +1,13 @@ +use cgp::extra::field::impls::*; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +fn main() { + // A core builder's fields are `IsNothing`, not `IsOptional`. + let _ = Context::builder().finalize_optional(); +} diff --git a/example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.stderr b/example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.stderr new file mode 100644 index 00000000..35e306fa --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.stderr @@ -0,0 +1,21 @@ +error[E0599]: the method `finalize_optional` exists for struct `__PartialContext`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/traits/finalize_optional_common_mistakes_core_builder.rs:12:32 + | + 5 | pub struct Context { + | ------------------ method `finalize_optional` not found for this struct +... +12 | let _ = Context::builder().finalize_optional(); + | ^^^^^^^^^^^^^^^^^ + | + = note: the following trait bounds were not satisfied: + `<&__PartialContext as PartialData>::Target = _` + which is required by `&__PartialContext: cgp::cgp_extra::cgp_field_extra::impls::FinalizeOptional` + `&__PartialContext: PartialData` + which is required by `&__PartialContext: cgp::cgp_extra::cgp_field_extra::impls::FinalizeOptional` + `<&mut __PartialContext as PartialData>::Target = _` + which is required by `&mut __PartialContext: cgp::cgp_extra::cgp_field_extra::impls::FinalizeOptional` + `&mut __PartialContext: PartialData` + which is required by `&mut __PartialContext: cgp::cgp_extra::cgp_field_extra::impls::FinalizeOptional` + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `finalize_optional`, perhaps you need to implement it: + candidate #1: `cgp::cgp_extra::cgp_field_extra::impls::FinalizeOptional` diff --git a/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs b/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs new file mode 100644 index 00000000..cfcb6c8d --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs @@ -0,0 +1,13 @@ +use cgp::extra::field::impls::SetOptional; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +fn main() { + // A core builder's fields are `IsNothing`, not `IsOptional`. + let _ = Context::builder().set(PhantomData::, "foo".to_owned()); +} diff --git a/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr b/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr new file mode 100644 index 00000000..165b34cd --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr @@ -0,0 +1,33 @@ +error[E0271]: type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Mapper == IsOptional` + --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:12:36 + | +12 | let _ = Context::builder().set(PhantomData::, "foo".to_owned()); + | --- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Mapper == IsOptional` + | | + | required by a bound introduced by this call + | +note: expected this to be `IsOptional` + --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:4:10 + | + 4 | #[derive(CgpData)] + | ^^^^^^^ + = note: required for `__PartialContext` to implement `SetOptional>>>>` + = note: this error originates in the derive macro `CgpData` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0271]: type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Output == __PartialContext` + --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:12:36 + | +12 | let _ = Context::builder().set(PhantomData::, "foo".to_owned()); + | --- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Output == __PartialContext` + | | + | required by a bound introduced by this call + | +note: expected this to be `__PartialContext` + --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:4:10 + | + 4 | #[derive(CgpData)] + | ^^^^^^^ + = note: expected struct `__PartialContext` + found struct `__PartialContext` + = note: required for `__PartialContext` to implement `SetOptional>>>>` + = note: this error originates in the derive macro `CgpData` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs b/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs new file mode 100644 index 00000000..887a110f --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs @@ -0,0 +1,13 @@ +use cgp::core::field::traits::TakeField; +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +fn main() { + // An empty builder has no `first_name` to take. + let _ = Person::builder().take_field(PhantomData::); +} diff --git a/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr b/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr new file mode 100644 index 00000000..e25a2ac9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr @@ -0,0 +1,15 @@ +error[E0271]: type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsNothing>>::Mapper == IsPresent` + --> tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs:12:42 + | +12 | let _ = Person::builder().take_field(PhantomData::); + | ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsNothing>>::Mapper == IsPresent` + | | + | required by a bound introduced by this call + | +note: expected this to be `IsPresent` + --> tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs:4:10 + | + 4 | #[derive(BuildField)] + | ^^^^^^^^^^ + = note: required for `__PartialPerson` to implement `TakeField>>>>>>>>>>>` + = note: this error originates in the derive macro `BuildField` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.rs b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.rs new file mode 100644 index 00000000..82ad13fc --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.rs @@ -0,0 +1,13 @@ +use cgp::extra::field::impls::*; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +fn main() { + // The builder is already optional, and `TransformOptional` has no `IsOptional` source impl. + let _ = Context::optional_builder().to_optional(); +} diff --git a/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr new file mode 100644 index 00000000..80ad72a1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr @@ -0,0 +1,24 @@ +error[E0599]: the method `to_optional` exists for struct `__PartialContext`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.rs:12:41 + | + 5 | pub struct Context { + | ------------------ method `to_optional` not found for this struct because it doesn't satisfy `_: ToOptional` or `_: TransformMapFields` +... +12 | let _ = Context::optional_builder().to_optional(); + | ^^^^^^^^^^^ + | + = note: the following trait bounds were not satisfied: + `__PartialContext: TransformMapFields` + which is required by `__PartialContext: cgp::cgp_extra::cgp_field_extra::impls::ToOptional` + `&__PartialContext: TransformMapFields` + which is required by `&__PartialContext: cgp::cgp_extra::cgp_field_extra::impls::ToOptional` + `&mut __PartialContext: TransformMapFields` + which is required by `&mut __PartialContext: cgp::cgp_extra::cgp_field_extra::impls::ToOptional` +note: the trait `TransformMapFields` must be implemented + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + | +12 | pub trait TransformMapFields { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `to_optional`, perhaps you need to implement it: + candidate #1: `cgp::cgp_extra::cgp_field_extra::impls::ToOptional` diff --git a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.rs b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.rs new file mode 100644 index 00000000..9171479c --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.rs @@ -0,0 +1,13 @@ +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +fn main() { + // The target marker `M` is not inferred from the value. + let (_old, _partial) = + Person::builder().update_field(PhantomData::, "Alice".to_owned()); +} diff --git a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr new file mode 100644 index 00000000..576a579f --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr @@ -0,0 +1,13 @@ +error[E0284]: type annotations needed for `((), __PartialPerson<_, IsNothing>)` + --> tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.rs:11:9 + | +11 | let (_old, _partial) = + | ^^^^^^^^^^^^^^^^ +12 | Person::builder().update_field(PhantomData::, "Alice".to_owned()); + | ------------ type must be known at this point + | + = note: cannot satisfy `<_ as MapType>::Map == String` +help: consider giving this pattern a type, where the type for type parameter `M` is specified + | +11 | let (_old, _partial): (_, __PartialPerson<__M2__, _>) = + | +++++++++++++++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs new file mode 100644 index 00000000..23d7dd6e --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs @@ -0,0 +1,12 @@ +use cgp::prelude::*; + +#[derive(BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +fn main() { + // `Person` declares no `age` field. + let _ = Person::builder().build_field(PhantomData::, 42_u8); +} diff --git a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr new file mode 100644 index 00000000..2cce9860 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr @@ -0,0 +1,21 @@ +error[E0277]: the trait bound `__PartialPerson: UpdateField>>>, IsPresent>` is not satisfied + --> tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs:11:43 + | +11 | let _ = Person::builder().build_field(PhantomData::, 42_u8); + | ----------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call + | +help: the trait `UpdateField>>>, IsPresent>` is not implemented for `__PartialPerson` + --> tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs:4:1 + | + 4 | pub struct Person { + | ^^^^^^^^^^^^^^^^^ +help: the following other types implement trait `UpdateField` + --> tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs:5:9 + | + 5 | pub first_name: String, + | ^^^^^^^^^^ `__PartialPerson<__M1__, __F1__>` implements `UpdateField>>>>>>>>>>, __M2__>` + 6 | pub last_name: String, + | ^^^^^^^^^ `__PartialPerson<__F0__, __M1__>` implements `UpdateField>>>>>>>>>, __M2__>` + = note: required for `__PartialPerson` to implement `cgp::prelude::BuildField>>>>` diff --git a/example-code/tests/reference/traits/build_field.rs b/example-code/tests/reference/traits/build_field.rs new file mode 100644 index 00000000..e1413c86 --- /dev/null +++ b/example-code/tests/reference/traits/build_field.rs @@ -0,0 +1,50 @@ +//! Code from `docs/reference/traits/builder/build_field.md` — `BuildField`. +//! +//! Pins the Examples program: a record built one field at a time in either order, and a wider record +//! built from a narrower one plus one field. Setting a field twice is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::CanBuildFrom; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, HasFields, BuildField)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(Debug, PartialEq, BuildField)] + pub struct Employee { + pub first_name: String, + pub last_name: String, + pub employee_id: u64, + } + + pub fn demo() { + // Order does not matter: `last_name` is set first here. + let person = Person::builder() + .build_field(PhantomData::, "Chen".to_owned()) + .build_field(PhantomData::, "Alice".to_owned()) + .finalize_build(); + + let employee = Employee::builder() + .build_from(person) + .build_field(PhantomData::, 7) + .finalize_build(); + + assert_eq!( + employee, + Employee { + first_name: "Alice".to_owned(), + last_name: "Chen".to_owned(), + employee_id: 7, + } + ); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/can_build_with_default.rs b/example-code/tests/reference/traits/can_build_with_default.rs new file mode 100644 index 00000000..e4dea802 --- /dev/null +++ b/example-code/tests/reference/traits/can_build_with_default.rs @@ -0,0 +1,39 @@ +//! Code from `docs/reference/traits/optional/can_build_with_default.md` — `CanBuildWithDefault`. +//! +//! Pins the Examples program: a record widened into one with an extra field, in one call and as the +//! three calls it stands for. A source field the target lacks is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::CanBuildFrom; + use cgp::extra::field::impls::{CanBuildWithDefault, CanFinalizeWithDefault}; + use cgp::prelude::*; + + #[derive(Debug, Clone, Eq, PartialEq, CgpData)] + pub struct Point2d { + pub x: u64, + pub y: u64, + } + + #[derive(Debug, Clone, Eq, PartialEq, CgpData)] + pub struct Point3d { + pub x: u64, + pub y: u64, + pub z: u64, + } + + pub fn demo() { + let point_3d = Point3d::build_with_default(Point2d { x: 1, y: 2 }); + assert_eq!(point_3d, Point3d { x: 1, y: 2, z: 0 }); + + let written_out: Point3d = Point3d::builder() + .build_from(Point2d { x: 1, y: 2 }) + .finalize_with_default(); + assert_eq!(written_out, point_3d); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/can_finalize_with_default.rs b/example-code/tests/reference/traits/can_finalize_with_default.rs new file mode 100644 index 00000000..925b5c94 --- /dev/null +++ b/example-code/tests/reference/traits/can_finalize_with_default.rs @@ -0,0 +1,34 @@ +//! Code from `docs/reference/traits/optional/can_finalize_with_default.md` — `CanFinalizeWithDefault`. +//! +//! Pins the Examples program: an optional builder and a core builder, each finalized with the unset +//! field defaulted. A field whose type has no `Default` is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::extra::field::impls::{CanFinalizeWithDefault, HasOptionalBuilder, SetOptional}; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub struct Context { + pub foo: String, + pub bar: u64, + } + + pub fn demo() { + let from_optional = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + assert_eq!(from_optional.bar, 0); + + // A core builder works too: its absent field is `IsNothing` rather than `None`. + let from_core = Context::builder() + .build_field(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + assert_eq!(from_core, from_optional); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/finalize_build.rs b/example-code/tests/reference/traits/finalize_build.rs new file mode 100644 index 00000000..1c856fe8 --- /dev/null +++ b/example-code/tests/reference/traits/finalize_build.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/traits/builder/finalize_build.md` — `FinalizeBuild`. +//! +//! Pins the Examples program: a generic finalize over any complete builder, including a fieldless +//! record. The incomplete build is the `has_builder` trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Debug, PartialEq, BuildField)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + #[derive(Debug, PartialEq, BuildField)] + pub struct Empty {} + + pub fn assemble(partial: Partial) -> Target + where + Partial: FinalizeBuild, + { + partial.finalize_build() + } + + pub fn demo() { + let person: Person = assemble( + Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .build_field(PhantomData::, "Chen".to_owned()), + ); + assert_eq!(person.last_name, "Chen"); + + // A fieldless record's builder is complete from the start. + let empty: Empty = assemble(Empty::builder()); + assert_eq!(empty, Empty {}); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/finalize_optional.rs b/example-code/tests/reference/traits/finalize_optional.rs new file mode 100644 index 00000000..6eac3eaf --- /dev/null +++ b/example-code/tests/reference/traits/finalize_optional.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/traits/optional/finalize_optional.md` — `FinalizeOptional`. +//! +//! Pins the Examples program: success, one missing field, and two missing fields, which report the +//! last in declaration order. Finalizing a core builder this way is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub struct Context { + pub foo: String, + pub bar: u64, + } + + pub fn demo() { + let complete = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .set(PhantomData::, 42) + .finalize_optional(); + assert_eq!( + complete, + Ok(Context { + foo: "foo".to_owned(), + bar: 42, + }) + ); + + let missing_bar = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_optional(); + assert_eq!(missing_bar, Err("bar")); + + // With both unset, the walk from the last field back stops at `bar`. + assert_eq!(Context::optional_builder().finalize_optional(), Err("bar")); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/has_builder.rs b/example-code/tests/reference/traits/has_builder.rs index f610866b..67d11b1b 100644 --- a/example-code/tests/reference/traits/has_builder.rs +++ b/example-code/tests/reference/traits/has_builder.rs @@ -1,9 +1,8 @@ -//! Code from `docs/reference/traits/has_builder.md` — *`HasBuilder`*. +//! Code from `docs/reference/traits/builder/has_builder.md` — `HasBuilder`. //! -//! The page's three snippets, run: the `extend` merge, the `into_builder`/`take_field` round trip, -//! and reading a set field back off a partial value. The rejected cases the page states are -//! `compile_fail` doctests below, since a page that says something will not compile should be -//! checked on that rather than trusted. +//! Pins the Examples program: a record extended from a narrower one through `build_from`, and a set +//! field read back off a partial value mid-build. An incomplete build, and a `build_from` source +//! without `HasFields`, are trybuild fixtures. /// ## Examples pub mod examples { @@ -11,25 +10,19 @@ pub mod examples { use cgp::prelude::*; // `build_from` walks the *source's* field list, so the source needs `HasFields` too. - #[derive(HasFields, BuildField, Debug, Eq, PartialEq)] + #[derive(HasFields, BuildField)] pub struct FooBar { pub foo: u64, pub bar: String, } - #[derive(BuildField, Debug, Eq, PartialEq)] + #[derive(Debug, PartialEq, BuildField)] pub struct FooBarBaz { pub foo: u64, pub bar: String, pub baz: bool, } - #[derive(BuildField, Debug, Eq, PartialEq)] - pub struct Person { - pub first_name: String, - pub last_name: String, - } - pub fn extend(foo_bar: FooBar) -> FooBarBaz { FooBarBaz::builder() .build_from(foo_bar) @@ -37,13 +30,17 @@ pub mod examples { .finalize_build() } - #[test] - fn test_extend() { + pub fn demo() { + // A set field can be read back off a still-incomplete builder. + let partial = FooBarBaz::builder().build_field(PhantomData::, true); + assert!(*partial.get_field(PhantomData::)); + + let foo_bar_baz = extend(FooBar { + foo: 1, + bar: "bar".to_owned(), + }); assert_eq!( - extend(FooBar { - foo: 1, - bar: "bar".to_owned() - }), + foo_bar_baz, FooBarBaz { foo: 1, bar: "bar".to_owned(), @@ -53,53 +50,7 @@ pub mod examples { } #[test] - fn test_take_a_field_out_and_put_it_back() { - // `TakeField` is the one trait in the family that is not in the prelude. - use cgp::core::field::traits::TakeField; - - let person = Person { - first_name: "Alice".to_owned(), - last_name: "Anderson".to_owned(), - }; - - let builder = person.into_builder(); - - let (first_name, remainder) = builder.take_field(PhantomData::); - assert_eq!(first_name, "Alice"); - - let person = remainder - .build_field(PhantomData::, first_name) - .finalize_build(); - - assert_eq!( - person, - Person { - first_name: "Alice".to_owned(), - last_name: "Anderson".to_owned(), - } - ); - } - - #[test] - fn test_read_a_set_field_mid_build() { - let partial = - Person::builder().build_field(PhantomData::, "Alice".to_owned()); - - assert_eq!( - partial.get_field(PhantomData::), - "Alice" - ); + fn test_demo() { + demo(); } } - -/// The page's central claim: `finalize_build` exists only at the all-present configuration, so an -/// incomplete build does not resolve. -/// -/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/traits/has_builder_rejected_incomplete_build.rs`. -pub mod rejected_incomplete_build {} - -/// The page's other claim: a `build_from` source deriving only `BuildField` cannot be merged, because -/// the recursion needs the source's `HasFields` shape. -/// -/// Rejected snippet — trybuild fixture `tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs`. -pub mod rejected_build_from_without_has_fields {} diff --git a/example-code/tests/reference/traits/has_optional_builder.rs b/example-code/tests/reference/traits/has_optional_builder.rs new file mode 100644 index 00000000..d92e374b --- /dev/null +++ b/example-code/tests/reference/traits/has_optional_builder.rs @@ -0,0 +1,48 @@ +//! Code from `docs/reference/traits/optional/has_optional_builder.md` — `HasOptionalBuilder`. +//! +//! Pins the Examples program: an all-optional builder set in any order, finished by each of the two +//! endings. + +/// ## Examples +pub mod examples { + use cgp::extra::field::impls::{ + CanFinalizeWithDefault, FinalizeOptional, HasOptionalBuilder, SetOptional, + }; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub struct Context { + pub foo: String, + pub bar: u64, + } + + pub fn demo() { + let context = Context::optional_builder() + .set(PhantomData::, 42) + .set(PhantomData::, "foo".to_owned()) + .finalize_optional(); + assert_eq!( + context, + Ok(Context { + foo: "foo".to_owned(), + bar: 42, + }) + ); + + // The same kind of builder, with `bar` left unset, finalized each way. + let defaulted = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + assert_eq!(defaulted.bar, 0); + + let missing = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_optional(); + assert_eq!(missing, Err("bar")); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/into_builder.rs b/example-code/tests/reference/traits/into_builder.rs new file mode 100644 index 00000000..1f33b893 --- /dev/null +++ b/example-code/tests/reference/traits/into_builder.rs @@ -0,0 +1,46 @@ +//! Code from `docs/reference/traits/builder/into_builder.md` — `IntoBuilder`. +//! +//! Pins the Examples program: a complete record turned into a full builder, one field swapped, and +//! the record rebuilt. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::TakeField; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, BuildField)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + pub fn with_last_name(person: Person, last_name: String) -> Person { + let (_old, remainder) = person + .into_builder() + .take_field(PhantomData::); + + remainder + .build_field(PhantomData::, last_name) + .finalize_build() + } + + pub fn demo() { + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + }; + + assert_eq!( + with_last_name(person, "Chen".to_owned()), + Person { + first_name: "Alice".to_owned(), + last_name: "Chen".to_owned(), + } + ); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/mod.rs b/example-code/tests/reference/traits/mod.rs index 13898db3..e4711472 100644 --- a/example-code/tests/reference/traits/mod.rs +++ b/example-code/tests/reference/traits/mod.rs @@ -7,9 +7,12 @@ //! check nothing about CGP. pub mod append_product; +pub mod build_field; pub mod can_build_from; +pub mod can_build_with_default; pub mod can_downcast; pub mod can_downcast_fields; +pub mod can_finalize_with_default; pub mod can_upcast; pub mod can_use_component; pub mod concat_path; @@ -17,17 +20,28 @@ pub mod concat_product; pub mod delegate_component; pub mod field_getter; pub mod field_mapper; +pub mod finalize_build; +pub mod finalize_optional; pub mod from_fields; pub mod has_builder; pub mod has_field; pub mod has_field_mut; pub mod has_fields; pub mod has_fields_ref; +pub mod has_optional_builder; +pub mod into_builder; pub mod is_provider_for; pub mod map_field; pub mod map_fields; pub mod mut_field_getter; +pub mod partial_data; +pub mod set_optional; pub mod static_format; pub mod static_string; +pub mod take_field; pub mod to_fields; pub mod to_fields_ref; +pub mod to_optional; +pub mod transform_map_default; +pub mod transform_optional; +pub mod update_field; diff --git a/example-code/tests/reference/traits/partial_data.rs b/example-code/tests/reference/traits/partial_data.rs new file mode 100644 index 00000000..6b6551f3 --- /dev/null +++ b/example-code/tests/reference/traits/partial_data.rs @@ -0,0 +1,35 @@ +//! Code from `docs/reference/traits/builder/partial_data.md` — `PartialData`. +//! +//! Pins the Examples program: a generic function that names the destination of a partial value at +//! two different configurations. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Debug, PartialEq, BuildField)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + pub fn target_name(_partial: &Partial) -> &'static str + where + Partial: PartialData, + { + core::any::type_name::() + } + + pub fn demo() { + let empty = Person::builder(); + assert!(target_name(&empty).ends_with("Person")); + + let half = empty.build_field(PhantomData::, "Alice".to_owned()); + assert!(target_name(&half).ends_with("Person")); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/set_optional.rs b/example-code/tests/reference/traits/set_optional.rs new file mode 100644 index 00000000..6beee0a9 --- /dev/null +++ b/example-code/tests/reference/traits/set_optional.rs @@ -0,0 +1,34 @@ +//! Code from `docs/reference/traits/optional/set_optional.md` — `SetOptional`. +//! +//! Pins the Examples program: fields set in any order, and one re-set with the replaced value returned. + +/// ## Examples +pub mod examples { + use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub struct Context { + pub foo: String, + pub bar: u64, + } + + pub fn demo() { + let builder = Context::optional_builder() + .set(PhantomData::, 42) + .set(PhantomData::, "foo".to_owned()); + + // Setting an already-set field hands back what it replaced. + let (replaced, builder) = + builder.set_optional(PhantomData::, "bar".to_owned()); + assert_eq!(replaced, Some("foo".to_owned())); + + let context = builder.finalize_optional().unwrap(); + assert_eq!(context.foo, "bar"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/take_field.rs b/example-code/tests/reference/traits/take_field.rs new file mode 100644 index 00000000..e2f7726b --- /dev/null +++ b/example-code/tests/reference/traits/take_field.rs @@ -0,0 +1,43 @@ +//! Code from `docs/reference/traits/builder/take_field.md` — `TakeField`. +//! +//! Pins the Examples program: a field taken out of a full builder, changed, and put back. Taking an +//! absent field is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::TakeField; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, BuildField)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + pub fn shout_first_name(person: Person) -> Person { + let (first_name, remainder) = person + .into_builder() + .take_field(PhantomData::); + + remainder + .build_field( + PhantomData::, + first_name.to_uppercase(), + ) + .finalize_build() + } + + pub fn demo() { + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Chen".to_owned(), + }; + + assert_eq!(shout_first_name(person).first_name, "ALICE"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/to_optional.rs b/example-code/tests/reference/traits/to_optional.rs new file mode 100644 index 00000000..e99b93b9 --- /dev/null +++ b/example-code/tests/reference/traits/to_optional.rs @@ -0,0 +1,41 @@ +//! Code from `docs/reference/traits/optional/to_optional.md` — `ToOptional`. +//! +//! Pins the Examples program: a partly built core builder relaxed to optional, and a complete value +//! relaxed by way of `into_builder`. Converting an already-optional builder is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::extra::field::impls::{FinalizeOptional, SetOptional, ToOptional}; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub struct Context { + pub foo: String, + pub bar: u64, + } + + pub fn demo() { + // `foo` is set before the conversion and survives it as `Some`. + let context = Context::builder() + .build_field(PhantomData::, "foo".to_owned()) + .to_optional() + .set(PhantomData::, 42) + .finalize_optional() + .unwrap(); + assert_eq!(context.foo, "foo"); + + // Every field of a complete value becomes `Some`, so one can be overwritten. + let context = context + .into_builder() + .to_optional() + .set(PhantomData::, 7) + .finalize_optional() + .unwrap(); + assert_eq!(context.bar, 7); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/transform_map_default.rs b/example-code/tests/reference/traits/transform_map_default.rs new file mode 100644 index 00000000..81369a69 --- /dev/null +++ b/example-code/tests/reference/traits/transform_map_default.rs @@ -0,0 +1,37 @@ +//! Code from `docs/reference/traits/optional/transform_map_default.md` — `TransformMapDefault`. +//! +//! Pins the Examples program: a generic function that drives the marker across a builder with +//! `TransformMapFields`, then finalizes the all-present result. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::TransformMapFields; + use cgp::extra::field::impls::TransformMapDefault; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub struct Context { + pub foo: String, + pub bar: u64, + } + + pub fn fill_defaults(builder: Builder) -> Builder::Output + where + Builder: TransformMapFields, + { + builder.transform_map_fields() + } + + pub fn demo() { + let full = fill_defaults( + Context::builder().build_field(PhantomData::, "foo".to_owned()), + ); + let context = full.finalize_build(); + assert_eq!(context.bar, 0); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/transform_optional.rs b/example-code/tests/reference/traits/transform_optional.rs new file mode 100644 index 00000000..be2d1218 --- /dev/null +++ b/example-code/tests/reference/traits/transform_optional.rs @@ -0,0 +1,40 @@ +//! Code from `docs/reference/traits/optional/transform_optional.md` — `TransformOptional`. +//! +//! Pins the Examples program: a generic function that drives the marker across a builder with +//! `TransformMapFields`, turning a partly built core builder into an optional one. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::IsOptional; + use cgp::core::field::traits::TransformMapFields; + use cgp::extra::field::impls::{FinalizeOptional, SetOptional, TransformOptional}; + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub struct Context { + pub foo: String, + pub bar: u64, + } + + pub fn relax(builder: Builder) -> Builder::Output + where + Builder: TransformMapFields, + { + builder.transform_map_fields() + } + + pub fn demo() { + let optional = + relax(Context::builder().build_field(PhantomData::, "foo".to_owned())); + let context = optional + .set(PhantomData::, 42) + .finalize_optional() + .unwrap(); + assert_eq!(context.foo, "foo"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/update_field.rs b/example-code/tests/reference/traits/update_field.rs new file mode 100644 index 00000000..1a53fbf9 --- /dev/null +++ b/example-code/tests/reference/traits/update_field.rs @@ -0,0 +1,42 @@ +//! Code from `docs/reference/traits/builder/update_field.md` — `UpdateField`. +//! +//! Pins the Examples program: the two transitions `BuildField` and `TakeField` pin, each written as +//! a direct `update_field` call with the target marker named. Leaving the marker to inference, and +//! a field the record does not declare, are trybuild fixtures. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Debug, PartialEq, BuildField)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + + pub fn demo() { + // IsNothing -> IsPresent: the old storage is `()`. + let (old, partial) = UpdateField::::update_field( + Person::builder(), + PhantomData, + "Alice".to_owned(), + ); + assert_eq!(old, ()); + + // IsPresent -> IsNothing: the old storage is the value. + let (taken, partial) = + UpdateField::::update_field(partial, PhantomData, ()); + assert_eq!(taken, "Alice"); + + let person = partial + .build_field(PhantomData::, "Bob".to_owned()) + .build_field(PhantomData::, "Chen".to_owned()) + .finalize_build(); + assert_eq!(person.first_name, "Bob"); + } + + #[test] + fn test_demo() { + demo(); + } +} From 7619144dcc86cb2df84c631f987787f9d5e22361 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 05:32:47 +0000 Subject: [PATCH 137/516] Revise the builder and optional-field reference pages Adds front matter, ports each Examples section from its mirror, replaces the sketched Under the hood listings with the real expansion and source impls, and quotes each Common Mistakes error with its snippet. Corrects four claims: the UpdateField marker is not inferred, ToOptional rejects an already-optional builder, build_with_default rejects a source field the target lacks, and an optional builder needs Default on every field to finalize with defaults. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/traits/builder/build_field.md | 109 +++++++++---- .../traits/builder/finalize_build.md | 113 +++++++------ docs/reference/traits/builder/has_builder.md | 153 +++++++++++++----- docs/reference/traits/builder/index.md | 1 + docs/reference/traits/builder/into_builder.md | 87 ++++++---- docs/reference/traits/builder/partial_data.md | 72 +++++---- docs/reference/traits/builder/take_field.md | 90 +++++++---- docs/reference/traits/builder/update_field.md | 136 +++++++++++----- .../traits/optional/can_build_with_default.md | 132 +++++++++++---- .../optional/can_finalize_with_default.md | 98 ++++++++--- .../traits/optional/finalize_optional.md | 124 ++++++++++---- .../traits/optional/has_optional_builder.md | 87 ++++++---- docs/reference/traits/optional/index.md | 1 + .../reference/traits/optional/set_optional.md | 78 ++++++--- docs/reference/traits/optional/to_optional.md | 91 +++++++---- .../traits/optional/transform_map_default.md | 59 ++++--- .../traits/optional/transform_optional.md | 88 ++++++---- 17 files changed, 1039 insertions(+), 480 deletions(-) diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index 84088ae8..9414da4e 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -55,37 +55,53 @@ position. `Value` is the field's declared type, so what you pass is an ordinary ## Examples -The everyday chain, one call per field: +A record built one field at a time, in either order, and a wider record built from it plus one +field: ```rust use cgp::prelude::*; +use cgp::core::field::impls::CanBuildFrom; -#[derive(BuildField)] +#[derive(Debug, PartialEq, HasFields, BuildField)] pub struct Person { pub first_name: String, pub last_name: String, } -let person = Person::builder() - .build_field(PhantomData::, "Alice".to_owned()) - .build_field(PhantomData::, "Chen".to_owned()) - .finalize_build(); -``` - -**Order does not matter**, because each impl constrains only its own field's marker and leaves the rest -generic. Setting `last_name` first compiles identically. - -Mixing it with a merge is the usual shape once more than one source contributes: - -```rust -use cgp::core::field::impls::CanBuildFrom; +#[derive(Debug, PartialEq, BuildField)] +pub struct Employee { + pub first_name: String, + pub last_name: String, + pub employee_id: u64, +} -let employee = Employee::builder() - .build_from(person) // the shared fields - .build_field(PhantomData::, 7) // and the one it did not carry - .finalize_build(); +pub fn demo() { + // Order does not matter: `last_name` is set first here. + let person = Person::builder() + .build_field(PhantomData::, "Chen".to_owned()) + .build_field(PhantomData::, "Alice".to_owned()) + .finalize_build(); + + let employee = Employee::builder() + .build_from(person) + .build_field(PhantomData::, 7) + .finalize_build(); + + assert_eq!( + employee, + Employee { + first_name: "Alice".to_owned(), + last_name: "Chen".to_owned(), + employee_id: 7, + } + ); +} ``` +Each impl constrains only its own field's marker, so setting `last_name` first compiles identically. +[`build_from`](../casting/can_build_from.md) copies the shared fields from `person`, which is why +`Person` also derives [`HasFields`](../shape/has_fields.md). + ## When to use it **Call `build_field` in any code that fills a builder; bound on the trait when the code is generic over @@ -102,30 +118,52 @@ the record.** ## Under the hood -`BuildField` is a **library blanket impl** over [`UpdateField`](./update_field.md), pinning the target +`BuildField` is a library blanket impl over [`UpdateField`](./update_field.md), pinning the target marker to `IsPresent` and constraining the reported source marker to `IsNothing`: ```rust -// conceptually: -// impl BuildField for Partial -// where Partial: UpdateField -``` +impl BuildField for Context +where + Context: UpdateField, +{ + type Value = Context::Value; -The `Mapper = IsNothing` constraint does the checking. `Mapper` is an *output* of the primitive (the -marker the field was in), so constraining it selects only those partial types whose field is -currently absent. A field already set has `Mapper = IsPresent`, no impl matches, and the call fails to -resolve. + type Output = Context::Output; -`update_field` returns the old value alongside the new partial; `build_field` discards it, which is sound -because the old value under `IsNothing` is `()`. + fn build_field(self, tag: PhantomData, value: Self::Value) -> Self::Output { + self.update_field(tag, value).1 + } +} +``` -[`TakeField`](./take_field.md) is the mirror image (the same primitive with `IsNothing` as the target -and `Mapper = IsPresent`), which is why the two read as opposites and share every mechanism. +The `Mapper = IsNothing` constraint does the checking. `Mapper` is an output of the primitive, the +marker the field was in, so constraining it selects only the partial types whose field is absent. A +field already set has `Mapper = IsPresent`, and the constraint fails. `build_field` discards the old +value the primitive returns, which is sound because under `IsNothing` it is `()`. +[`TakeField`](./take_field.md) is the mirror image: the same primitive, with `IsNothing` as the +target and `Mapper = IsPresent`. ## Common Mistakes -**Building a field twice does not compile.** The second call finds `Mapper = IsPresent` and no impl. That -is the guarantee, and the error is a missing-method one rather than anything mentioning "already set". +**Building a field twice does not compile.** On the two-field `Person` of the +[example](#examples), setting `first_name` a second time: + +```rust +let _ = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .build_field(PhantomData::, "Bob".to_owned()); +``` + +makes the second call find `Mapper = IsPresent` where the blanket impl requires `IsNothing`, and +rustc reports the mismatch on the partial type, whose markers show the field already set: + +```text +error[E0271]: type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsPresent>>::Mapper == IsNothing` +... +note: expected this to be `IsNothing` +``` + +Nothing in the message says "already set"; the first `IsPresent` in the partial type does. **`Output` is a different type from `Self`.** A builder cannot be stored in a variable of fixed type across a chain, and it cannot be filled in a loop. The chain is unrolled by construction. @@ -140,7 +178,8 @@ detectable at the end, since any prefix of a chain is a legal partial value. `PhantomData::` in full. **Nothing implements it directly**, so an unsatisfied `BuildField` bound is really an unsatisfied -[`UpdateField`](./update_field.md) one, which the error names. +[`UpdateField`](./update_field.md) one, which the error names, as a mismatch on `Mapper` for a field +already set or a missing impl for a field the record lacks. ## Related constructs diff --git a/docs/reference/traits/builder/finalize_build.md b/docs/reference/traits/builder/finalize_build.md index 89d0da47..45e76be5 100644 --- a/docs/reference/traits/builder/finalize_build.md +++ b/docs/reference/traits/builder/finalize_build.md @@ -1,6 +1,8 @@ --- +title: 'FinalizeBuild — end a build' sidebar_label: 'FinalizeBuild' sidebar_position: 6 +description: 'Turn a partial record with every field present back into the concrete struct; the impl exists only at that configuration.' --- # `FinalizeBuild` @@ -22,7 +24,7 @@ let person = Person::builder() ``` Delete a middle line and this does not compile. There is nothing to run and nothing to panic: the method -is simply not in scope for a value with a field still absent. +is not in scope for a value with a field still absent. The destination type comes from its [supertrait](/docs/reference/glossary#supertrait) [`PartialData`](./partial_data.md), which every configuration implements. That division is deliberate: **one names where you are going, the other says @@ -52,51 +54,52 @@ this page works out. `finalize_build` consumes the partial value and returns `Self::Target`. It takes no arguments. There is nothing left to decide by the time it applies. -Bounding on it is how generic builder code says it will produce a finished value: - -```rust -fn assemble(partial: Partial) -> Target -where - Partial: FinalizeBuild, -{ - partial.finalize_build() -} -``` +Bounding on it is how generic builder code says it will produce a finished value, as the +`assemble` function in the [example](#examples) does with `FinalizeBuild`. The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), which emits exactly one per record. ## Examples -The ordinary ending of a build chain: +A generic finalize over any complete builder, including a fieldless record: ```rust use cgp::prelude::*; -#[derive(BuildField)] +#[derive(Debug, PartialEq, BuildField)] pub struct Person { pub first_name: String, pub last_name: String, } -let person = Person::builder() - .build_field(PhantomData::, "Alice".to_owned()) - .build_field(PhantomData::, "Chen".to_owned()) - .finalize_build(); -``` +#[derive(Debug, PartialEq, BuildField)] +pub struct Empty {} -And the failure it exists to produce, omitting a field: +pub fn assemble(partial: Partial) -> Target +where + Partial: FinalizeBuild, +{ + partial.finalize_build() +} -```rust -// error: no method named `finalize_build` found for struct -// `__PartialPerson` -let person = Person::builder() - .build_field(PhantomData::, "Alice".to_owned()) - .finalize_build(); +pub fn demo() { + let person: Person = assemble( + Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .build_field(PhantomData::, "Chen".to_owned()), + ); + assert_eq!(person.last_name, "Chen"); + + // A fieldless record's builder is complete from the start. + let empty: Empty = assemble(Empty::builder()); + assert_eq!(empty, Empty {}); +} ``` -**Read the partial type in the message to see which marker is still `IsNothing`.** That is the field you -forgot, and it is the only place the compiler names it. +`assemble` names only `FinalizeBuild`, yet it can bind `Target`, because the projection comes from +the supertrait [`PartialData`](./partial_data.md). `Empty` has no markers to fill, so its builder is +already at the one configuration the impl covers. ## When to use it @@ -114,40 +117,54 @@ forgot, and it is the only place the compiler names it. ## Under the hood -The derive emits one impl, with every marker fixed: +The derive emits one impl, with every marker fixed. `cargo cgp expand` on the example's `Person` +shows it beside its supertrait's impl, which leaves every marker generic: ```rust +impl<__F0__: MapType, __F1__: MapType> PartialData for __PartialPerson<__F0__, __F1__> { + type Target = Person; +} impl FinalizeBuild for __PartialPerson { - // ... + fn finalize_build(self) -> Self::Target { + Person { + first_name: self.first_name, + last_name: self.last_name, + } + } } ``` -Compare its supertrait, which leaves every marker generic: - -```rust -// impl PartialData for __PartialPerson { -// type Target = Person; -// } -``` - So a partial value always knows its destination and only sometimes has a way to reach it. Because -`IsPresent::Map` is `T`, the all-present companion holds exactly the concrete struct's fields in the -same order, and the body is a field-by-field move with nothing to unwrap. - -**This is why the error is a missing method rather than a missing field.** Method resolution looks for -`finalize_build` on `__PartialPerson`, finds no impl, and reports that. The -compiler has no way to say "you forgot `last_name`", because nothing in the failed lookup mentions field -names. The marker list in the type is the diagnostic. +`IsPresent::Map` is `T`, the body is a field-by-field move with nothing to unwrap. **This is why +the error for an incomplete build is a missing method rather than a missing field**: method +resolution looks for `finalize_build` on `__PartialPerson`, finds no impl, and +reports that, so the marker list in the type is the diagnostic. The optional layer reaches this same impl rather than replacing it: [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) runs a -[`TransformMapFields`](../type-level/transform_map_fields.md) to `IsPresent` first, so **the strict, all-present impl -remains the only way a partial value becomes a concrete struct.** +[`TransformMapFields`](../type-level/transform_map_fields.md) walk to `IsPresent` first, so **the +strict, all-present impl remains the only way a partial value becomes a concrete struct.** ## Common Mistakes -**"No method named `finalize_build`" is the expected error for an incomplete build.** Read the partial -type in the message: the field whose marker is still `IsNothing` is the one missing. +**"No method named `finalize_build`" is the expected error for an incomplete build.** Setting only +`first_name` on the example's `Person` and finalizing: + +```rust +let person: Person = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .finalize_build(); +``` + +fails with: + +```text +error[E0599]: no method named `finalize_build` found for struct `__PartialPerson<__F0__, __F1__>` in the current scope +... + | | -^^^^^^^^^^^^^^ method not found in `__PartialPerson` +``` + +The field whose marker is still `IsNothing` is the one missing. **It consumes the partial value**, so the builder cannot be reused afterwards. diff --git a/docs/reference/traits/builder/has_builder.md b/docs/reference/traits/builder/has_builder.md index ffde1632..5c418a16 100644 --- a/docs/reference/traits/builder/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -64,12 +64,11 @@ about whether you are assembling a record or redistributing one. ## Examples -The everyday shape is `builder()`, some `build_field` calls, and `finalize_build`, with -[`build_from`](../casting/can_build_from.md) copying every shared field from another record in one step: +A record extended from a narrower one, and a field read back off a still-incomplete builder: ```rust -use cgp::core::field::impls::CanBuildFrom; use cgp::prelude::*; +use cgp::core::field::impls::CanBuildFrom; // `build_from` walks the *source's* field list, so the source needs `HasFields` too. #[derive(HasFields, BuildField)] @@ -78,35 +77,44 @@ pub struct FooBar { pub bar: String, } -#[derive(BuildField)] +#[derive(Debug, PartialEq, BuildField)] pub struct FooBarBaz { pub foo: u64, pub bar: String, pub baz: bool, } -fn extend(foo_bar: FooBar) -> FooBarBaz { - FooBarBaz::builder() // all absent - .build_from(foo_bar) // foo, bar now present - .build_field(PhantomData::, true) // baz now present - .finalize_build() // only the all-present impl applies +pub fn extend(foo_bar: FooBar) -> FooBarBaz { + FooBarBaz::builder() + .build_from(foo_bar) + .build_field(PhantomData::, true) + .finalize_build() } -``` - -Every line changes the partial *type*, and the last one type-checks only because every marker has reached -present. Reorder them so `finalize_build` runs before `baz` is set and it is a compile error. -A field that has been set can be read back mid-build, because the derive emits a -[`HasField`](../field-access/has_field.md) impl on the partial type gated on presence: - -```rust -let partial = Person::builder() - .build_field(PhantomData::, "Alice".to_owned()); - -assert_eq!(partial.get_field(PhantomData::), "Alice"); +pub fn demo() { + // A set field can be read back off a still-incomplete builder. + let partial = FooBarBaz::builder().build_field(PhantomData::, true); + assert!(*partial.get_field(PhantomData::)); + + let foo_bar_baz = extend(FooBar { + foo: 1, + bar: "bar".to_owned(), + }); + assert_eq!( + foo_bar_baz, + FooBarBaz { + foo: 1, + bar: "bar".to_owned(), + baz: true, + } + ); +} ``` -Asking for `last_name` there would not compile. +Every step changes the partial *type*, and `finalize_build` type-checks only because every marker +has reached present; moving it before the `baz` step is a compile error. A set field can be read +back mid-build because the derive emits a [`HasField`](../field-access/has_field.md) impl on the +partial type for each field once it is present. ## When to use it @@ -131,9 +139,9 @@ are a different family: [`ExtractField`](../variant/extract_field.md) for taking ## Under the hood -The derive generates a companion struct, `__Partial{Name}`, that is your struct with one -[`MapType`](../type-level/map_type.md) parameter added per field and each field's type wrapped in that parameter's -projection: +`#[derive(BuildField)]` generates a companion struct, `__Partial{Name}`, with one +[`MapType`](../type-level/map_type.md) parameter per field and each field's type wrapped in that +parameter's projection. `cargo cgp expand` on a two-field `Person` shows it: ```rust pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { @@ -142,12 +150,17 @@ pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { } ``` -`HasBuilder` then fixes the starting configuration to all-absent: +`HasBuilder` fixes the starting configuration to all-absent, where each field is stored as `()`: ```rust impl HasBuilder for Person { - type Builder = __PartialPerson; // the empty builder - // ... + type Builder = __PartialPerson; + fn builder() -> Self::Builder { + __PartialPerson { + first_name: (), + last_name: (), + } + } } ``` @@ -155,27 +168,81 @@ and [`FinalizeBuild`](./finalize_build.md) exists only at the opposite end: ```rust impl FinalizeBuild for __PartialPerson { - // ... + fn finalize_build(self) -> Self::Target { + Person { + first_name: self.first_name, + last_name: self.last_name, + } + } } ``` That pair is the whole safety argument. `builder()` starts at all-absent, each -[`build_field`](./build_field.md) flips one marker, and there is no check to run at the end: the impl -simply is not there for an incomplete value. - -Everything between the two ends reduces to one primitive, [`UpdateField`](./update_field.md), which is -what the derive actually writes; [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are -library blanket impls over it in opposite directions. +[`build_field`](./build_field.md) flips one marker, and there is no check to run at the end: the +impl is absent for an incomplete value. Everything between the two ends reduces to one primitive, +[`UpdateField`](./update_field.md), which is what the derive writes per field; +[`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are library blanket impls over +it in opposite directions. ## Common Mistakes -**"No method named `finalize_build`" is the expected error for an incomplete build.** A missing field -means the all-present impl does not apply, so the compiler reports a missing method rather than a missing -field. Read the partial type in the message to see which marker is still `IsNothing`. +**"No method named `finalize_build`" is the expected error for an incomplete build.** A missing +field means the all-present impl does not apply, so the compiler reports a missing method rather +than a missing field. Finalizing a `Person` with only `first_name` set: + +```rust +let person: Person = Person::builder() + .build_field(PhantomData::, "Alice".to_owned()) + .finalize_build(); +``` + +fails with: + +```text +error[E0599]: no method named `finalize_build` found for struct `__PartialPerson<__F0__, __F1__>` in the current scope +... + | | -^^^^^^^^^^^^^^ method not found in `__PartialPerson` +``` + +The marker still `IsNothing` is the missing field, here `last_name`. + +**`build_from` needs [`HasFields`](../shape/has_fields.md) on the source.** It walks the source's +field list, so a source with only `#[derive(BuildField)]`: + +```rust +#[derive(BuildField)] +pub struct FooBar { + pub foo: u64, +} + +#[derive(BuildField)] +pub struct FooBaz { + pub foo: u64, + pub baz: bool, +} + +let _ = FooBaz::builder() + .build_from(FooBar { foo: 1 }) + .build_field(PhantomData::, true) + .finalize_build(); +``` + +fails on the source rather than on the builder: + +```text +error[E0277]: the trait bound `FooBar: HasFields` is not satisfied +... + = note: required for `__PartialFooBaz` to implement `CanBuildFrom` +``` + +The [example](#examples) derives both on its `FooBar`. -**The partial type cannot be printed or cloned.** The derive clears the original's attributes, so no -`Debug`, no `Clone`, whatever the record derives. Read a set field through the partial type's -[`HasField`](../field-access/has_field.md) impl instead. +**The partial type cannot be printed or cloned.** The derive drops the original's struct-level +attributes, so no `Debug`, no `Clone`, whatever the record derives. Read a set field through the +partial type's [`HasField`](../field-access/has_field.md) impl instead. Field-level attributes, by +contrast, are copied onto the partial type, so a field helper attribute such as +`#[serde(rename = "...")]` breaks the build; see +[`#[derive(BuildField)]`](../../derives/derive_build_field.md#common-mistakes). **There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible default still has to be set, unless you reach for the @@ -184,8 +251,8 @@ default still has to be set, unless you reach for the **`builder()` is an associated function.** There is no receiver, so it is `Person::builder()` rather than anything called on a value. Starting from a value is [`IntoBuilder`](./into_builder.md). -**A fieldless struct's builder is immediately finalizable**, since there is nothing to track. That is -legal and useless. +**A fieldless struct's builder is immediately finalizable**, since there is nothing to track. +`Empty::builder().finalize_build()` compiles for a `struct Empty {}`, which is legal and useless. ## Related constructs diff --git a/docs/reference/traits/builder/index.md b/docs/reference/traits/builder/index.md index 1d828bd7..8d98e338 100644 --- a/docs/reference/traits/builder/index.md +++ b/docs/reference/traits/builder/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The traits that assemble a struct one field at a time, with each field''s presence tracked in the type so an incomplete record cannot be finalized.' --- # Record builders diff --git a/docs/reference/traits/builder/into_builder.md b/docs/reference/traits/builder/into_builder.md index 7040e59b..60cbc29b 100644 --- a/docs/reference/traits/builder/into_builder.md +++ b/docs/reference/traits/builder/into_builder.md @@ -1,6 +1,8 @@ --- +title: 'IntoBuilder — a full builder from a value' sidebar_label: 'IntoBuilder' sidebar_position: 2 +description: 'Turn a complete record into a partial one with every field present, to take fields out and put them back without naming the concrete type.' --- # `IntoBuilder` @@ -50,24 +52,48 @@ The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.m ## Examples -Taking a value apart and putting it back, which is the shape generic redistributing code has: +Swapping one field of a complete record, the shape redistributing code has: ```rust -use cgp::core::field::traits::TakeField; use cgp::prelude::*; +use cgp::core::field::traits::TakeField; + +#[derive(Debug, PartialEq, BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} -let builder = person.into_builder(); // all present +pub fn with_last_name(person: Person, last_name: String) -> Person { + let (_old, remainder) = person + .into_builder() + .take_field(PhantomData::); -let (first_name, remainder) = builder.take_field(PhantomData::); -// `remainder` is missing first_name, so it cannot be finalized + remainder + .build_field(PhantomData::, last_name) + .finalize_build() +} -let person = remainder - .build_field(PhantomData::, first_name) - .finalize_build(); // all present again +pub fn demo() { + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + }; + + assert_eq!( + with_last_name(person, "Chen".to_owned()), + Person { + first_name: "Alice".to_owned(), + last_name: "Chen".to_owned(), + } + ); +} ``` -Note that a value straight out of `into_builder` is already finalizable: every marker is `IsPresent`, so -[`finalize_build`](./finalize_build.md) resolves immediately and the round trip is the identity. The trait earns its keep only from what happens in between. +`into_builder` starts with every field present, [`take_field`](./take_field.md) removes `last_name`, +and [`build_field`](./build_field.md) puts a new one in its place. A value straight out of +`into_builder` is already finalizable, so the round trip earns its keep only from what happens in +between. ## When to use it @@ -76,8 +102,8 @@ entry points and the one that shows up in generic code more than in application - **Use [`HasBuilder`](./has_builder.md)** when assembling a record from independent pieces. That is the common case and the one the extensible builder pattern is about. -- **Use `IntoBuilder`** when a complete value must be decomposed: to swap one field, to hand fields to - several destinations, or to rebuild a record with one type changed. +- **Use `IntoBuilder`** when a complete value must be decomposed: to swap one field, or to hand its + fields to several destinations, including the builder of a different record. - **Use [`ToFields`](../shape/to_fields.md)** instead when what you want is the value's *shape* as a flat list rather than a partial type you can fill. A partial value tracks presence; a `Fields` product does not. - **Prefer a struct update expression** in concrete code. `Person { first_name, ..person }` does the @@ -85,27 +111,34 @@ entry points and the one that shows up in generic code more than in application ## Under the hood -The derive generates one partial companion per record (`__Partial{Name}`, with a -[`MapType`](../type-level/map_type.md) parameter per field), and the two entry points differ only in the -configuration they name: +The derive generates one partial companion per record, and the two entry points differ only in the +configuration they produce. `cargo cgp expand` on the example's `Person` shows both: ```rust impl HasBuilder for Person { - type Builder = __PartialPerson; // nothing set + type Builder = __PartialPerson; + fn builder() -> Self::Builder { + __PartialPerson { + first_name: (), + last_name: (), + } + } } - impl IntoBuilder for Person { - type Builder = __PartialPerson; // everything set + type Builder = __PartialPerson; + fn into_builder(self) -> Self::Builder { + __PartialPerson { + first_name: self.first_name, + last_name: self.last_name, + } + } } ``` -`into_builder` moves each field of the concrete struct into the corresponding slot of the companion, -which under `IsPresent` holds the value itself, so the conversion is a move rather than a wrap, and -nothing about the runtime representation changes. - -Because the result is at the all-present configuration, it satisfies -[`FinalizeBuild`](./finalize_build.md) immediately and [`TakeField`](./take_field.md) for every field, -which is exactly the pair a redistribution needs. +Under `IsPresent` a slot holds the value itself, so `into_builder` moves each field across and +nothing about the runtime representation changes. The result is at the all-present configuration, +so it satisfies [`FinalizeBuild`](./finalize_build.md) immediately and +[`TakeField`](./take_field.md) for every field, the pair a redistribution needs. ## Common Mistakes @@ -115,8 +148,8 @@ original must survive, bearing in mind that gives you a shape rather than a buil **The result is already finalizable.** Calling `into_builder().finalize_build()` is the identity, which is legal and pointless. The trait earns its keep only if something happens in between. -**The partial type cannot be printed or cloned.** The derive clears the original's attributes, so a value -mid-redistribution has none of the record's own derives. +**The partial type cannot be printed or cloned.** The derive drops the original's struct-level +attributes, so a value mid-redistribution has none of the record's own derives. **It is a method, where [`HasBuilder`](./has_builder.md)'s `builder()` is an associated function.** The asymmetry is deliberate (one starts from a value and the other from nothing), and it catches people diff --git a/docs/reference/traits/builder/partial_data.md b/docs/reference/traits/builder/partial_data.md index 37c7e0a7..ea494d8e 100644 --- a/docs/reference/traits/builder/partial_data.md +++ b/docs/reference/traits/builder/partial_data.md @@ -1,6 +1,8 @@ --- +title: 'PartialData — the type a builder becomes' sidebar_label: 'PartialData' sidebar_position: 7 +description: 'Name the concrete struct a partial record will become, at every configuration, so generic code can mention the destination mid-build.' --- # `PartialData` @@ -51,16 +53,8 @@ read the destination through this projection rather than declaring one of their **It is in the prelude**, so `use cgp::prelude::*;` is enough. -You bound on it when a signature must mention the destination while holding a partial value: - -```rust -fn describe(partial: Partial) -> &'static str -where - Partial: PartialData, -{ - core::any::type_name::() -} -``` +You bound on it when a signature must mention the destination while holding a partial value, as +`Partial::Target` in the `target_name` function of the [example](#examples). The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md) for a record and [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) for an enum. **Both** partial families @@ -69,21 +63,35 @@ directly. ## Examples -Its most visible use is as [`FinalizeBuild`](./finalize_build.md)'s [supertrait](/docs/reference/glossary#supertrait), which is how a finalize -knows what to return: +A generic function naming the destination of a partial value, at two configurations: ```rust -pub trait FinalizeBuild: PartialData { - fn finalize_build(self) -> Self::Target; +use cgp::prelude::*; + +#[derive(Debug, PartialEq, BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} + +pub fn target_name(_partial: &Partial) -> &'static str +where + Partial: PartialData, +{ + core::any::type_name::() } -``` -`Self::Target` in that signature comes from here. Without it the finalize would need its own associated -type, and the destination would be unnameable until the value was complete. +pub fn demo() { + let empty = Person::builder(); + assert!(target_name(&empty).ends_with("Person")); -The same appears in [`FinalizeOptional`](../optional/finalize_optional.md), which returns -`Result`, again projecting the destination through this trait rather than -declaring one of its own. + let half = empty.build_field(PhantomData::, "Alice".to_owned()); + assert!(target_name(&half).ends_with("Person")); +} +``` + +`Partial::Target` is `Person` for the empty builder and the half-built one alike, since the impl +covers every configuration. ## When to use it @@ -101,24 +109,20 @@ traits otherwise. ## Under the hood -The derive emits one impl covering every configuration at once, by leaving the markers generic: +The derive emits one impl covering every configuration at once, by leaving the markers generic. +`cargo cgp expand` on a two-field `Person` shows: ```rust -// conceptually, for the record companion: -// impl PartialData for __PartialPerson { -// type Target = Person; -// } +impl<__F0__: MapType, __F1__: MapType> PartialData for __PartialPerson<__F0__, __F1__> { + type Target = Person; +} ``` -Nothing about the markers is constrained, so the destination stays available at every step of -a build. Contrast [`FinalizeBuild`](./finalize_build.md), whose impl fixes every marker to `IsPresent`. - -Splitting the two lets generic builder code work against a destination it can name while -still being *unable* to finalize prematurely: the type is known, the conversion is not available. A -single trait carrying both would have to choose one or the other. - -The enum side implements it identically on its extraction companions, with `Target` naming the original -enum, which is how [`HasExtractor`](../variant/has_extractor.md)'s round trip knows what to rebuild. +Nothing about the markers is constrained, so the destination stays available at every step of a +build. Contrast [`FinalizeBuild`](./finalize_build.md), whose impl fixes every marker to +`IsPresent`. Splitting the two lets generic builder code name a destination while still being unable +to finalize early. The enum side implements it the same way on its extraction companions, with +`Target` naming the original enum. ## Common Mistakes diff --git a/docs/reference/traits/builder/take_field.md b/docs/reference/traits/builder/take_field.md index f50ee1a5..7eac0712 100644 --- a/docs/reference/traits/builder/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -1,6 +1,8 @@ --- +title: 'TakeField — remove one field of a builder' sidebar_label: 'TakeField' sidebar_position: 4 +description: 'Take a present field out of a partial record, getting the value and a remainder that cannot be finalized until the field is put back.' --- # `TakeField` @@ -59,24 +61,43 @@ remainder second.** ## Examples -Taking a field out and putting it back, which is the shape generic redistributing code has: +Taking a field out of a full builder, changing it, and putting it back: ```rust -use cgp::core::field::traits::TakeField; use cgp::prelude::*; +use cgp::core::field::traits::TakeField; + +#[derive(Debug, PartialEq, BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} -let builder = person.into_builder(); // all present +pub fn shout_first_name(person: Person) -> Person { + let (first_name, remainder) = person + .into_builder() + .take_field(PhantomData::); + + remainder + .build_field( + PhantomData::, + first_name.to_uppercase(), + ) + .finalize_build() +} -let (first_name, remainder) = builder.take_field(PhantomData::); -// `remainder` is missing first_name, so it cannot be finalized +pub fn demo() { + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Chen".to_owned(), + }; -let person = remainder - .build_field(PhantomData::, first_name) - .finalize_build(); // all present again + assert_eq!(shout_first_name(person).first_name, "ALICE"); +} ``` -Dropping the `build_field` line makes `finalize_build` fail to resolve, which is the guarantee: a field -taken out and not replaced cannot be forgotten silently. +Dropping the `build_field` step makes `finalize_build` fail to resolve, which is the guarantee: a +field taken out and not replaced cannot be forgotten silently. ## When to use it @@ -95,35 +116,50 @@ merging one record into another, already uses it for you. ## Under the hood -`TakeField` is a **library blanket impl** over [`UpdateField`](./update_field.md), the mirror image of +`TakeField` is a library blanket impl over [`UpdateField`](./update_field.md), the mirror image of [`BuildField`](./build_field.md#under-the-hood): ```rust -// conceptually: -// impl TakeField for Partial -// where Partial: UpdateField -``` +impl TakeField for Context +where + Context: UpdateField, +{ + type Value = Context::Value; -The target marker is `IsNothing` and the constraint on the reported source marker is `IsPresent`, both -swapped relative to `BuildField`. Since `Mapper` is an *output* of the primitive, constraining it selects -only those partial types whose field is currently set. + type Remainder = Context::Output; -The primitive's signature makes one trait serve both directions: `update_field` takes the new -storage in and hands the old storage back, so under this transition it takes `()` in and hands the real -value back. + fn take_field(self, tag: PhantomData) -> (Self::Value, Self::Remainder) { + self.update_field(tag, ()) + } +} +``` -**Its heaviest user is [`CanBuildFrom`](../casting/can_build_from.md).** That recursion walks the source's field -list, taking each field out with `take_field` and writing it into the target with -[`build_field`](./build_field.md), threading the shrinking source and the growing target through, which -is why a merge needs [`HasFields`](../shape/has_fields.md) on the source as well as a builder. +The target marker is `IsNothing` and the constraint on the reported source marker is `IsPresent`, +both swapped relative to `BuildField`, so under this transition the primitive takes `()` in and +hands the real value back. **Its heaviest user is [`CanBuildFrom`](../casting/can_build_from.md)**, +whose recursion walks the source's field list, taking each field out with `take_field` and writing +it into the target with [`build_field`](./build_field.md), which is why a merge needs +[`HasFields`](../shape/has_fields.md) on the source as well as a builder. ## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. Every other trait in the core builder family is. -**Taking an absent field does not compile.** The second take of the same field finds `Mapper = IsNothing` -and no impl, reported as a missing method rather than as anything about absence. +**Taking an absent field does not compile.** Taking `first_name` from an empty builder: + +```rust +let _ = Person::builder().take_field(PhantomData::); +``` + +finds `Mapper = IsNothing` where the blanket impl requires `IsPresent`, reported as a mismatch +rather than as anything about absence: + +```text +error[E0271]: type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsNothing>>::Mapper == IsPresent` +... +note: expected this to be `IsPresent` +``` **It returns `(value, remainder)`, in that order.** Reversing the binding is a type error, but a confusing one when both are generic. diff --git a/docs/reference/traits/builder/update_field.md b/docs/reference/traits/builder/update_field.md index 03bde2e6..7ac6158e 100644 --- a/docs/reference/traits/builder/update_field.md +++ b/docs/reference/traits/builder/update_field.md @@ -1,6 +1,8 @@ --- +title: 'UpdateField — move one field between states' sidebar_label: 'UpdateField' sidebar_position: 5 +description: 'The per-field primitive of the builder family: change one field''s presence marker and hand back what was stored there before.' --- # `UpdateField` @@ -62,37 +64,54 @@ directions. **It is in the prelude**, so `use cgp::prelude::*;` is enough. -The `M` parameter is the target marker, and it is usually inferred from the value you pass: supplying a -`String` where the field's type is `String` means `M = IsPresent`, and supplying `()` means -`M = IsNothing`. +The `M` parameter is the target marker, and **it is not inferred from the value you pass**: a +`String` could be the storage of `IsPresent` or of any other marker that maps to it, so a direct +call names the trait with the marker, as +`UpdateField::::update_field(builder, PhantomData, value)`. +[`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) pin the marker for you, which is +one reason to call them instead. The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), one per field. ## Examples -You almost always reach it through the two directions rather than directly: +The two transitions `BuildField` and `TakeField` pin, written as direct calls with the target marker +named: ```rust use cgp::prelude::*; -// BuildField: IsNothing -> IsPresent -let partial = Person::builder() - .build_field(PhantomData::, "Alice".to_owned()); -``` - -Naming `UpdateField` yourself is for a transition neither direction covers, which in practice means one -involving `IsOptional`: +#[derive(Debug, PartialEq, BuildField)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} -```rust -// the shape SetOptional uses: IsOptional -> IsOptional, so the type does not change -let (previous, builder) = builder.update_field( - PhantomData::, - Some("Bob".to_owned()), -); +pub fn demo() { + // IsNothing -> IsPresent: the old storage is `()`. + let (old, partial) = UpdateField::::update_field( + Person::builder(), + PhantomData, + "Alice".to_owned(), + ); + assert_eq!(old, ()); + + // IsPresent -> IsNothing: the old storage is the value. + let (taken, partial) = + UpdateField::::update_field(partial, PhantomData, ()); + assert_eq!(taken, "Alice"); + + let person = partial + .build_field(PhantomData::, "Bob".to_owned()) + .build_field(PhantomData::, "Chen".to_owned()) + .finalize_build(); + assert_eq!(person.first_name, "Bob"); +} ``` -Because both markers are `IsOptional` here, `Output` is the same type as `Self`, which is exactly what -lets an optional field be set repeatedly, unlike the core `build_field` that consumes an absent slot once. +Under `IsNothing` a field is stored as `()`, so setting it hands back `()` and taking it hands back +the value. Naming the trait with the marker is required: the marker is not inferred from the value, +as [Common Mistakes](#common-mistakes) shows. ## When to use it @@ -110,31 +129,41 @@ call site. ## Under the hood -The derive emits one impl per field, and the key property is visible in the generics: **only the named -field's marker moves, while every other stays generic.** +The derive emits one impl per field, and the key property is visible in the generics: only the +named field's marker moves, while every other stays generic. `cargo cgp expand` on the example's +`Person` shows the `first_name` impl: ```rust -impl<__M1__: MapType, __M2__: MapType, __F1__: MapType> - UpdateField for __PartialPerson<__M1__, __F1__> -{ +impl< + __M1__: MapType, + __M2__: MapType, + __F1__: MapType, +> UpdateField for __PartialPerson<__M1__, __F1__> { type Value = String; - type Mapper = __M1__; // the marker before - type Output = __PartialPerson<__M2__, __F1__>; // and after - // ... + type Mapper = __M1__; + type Output = __PartialPerson<__M2__, __F1__>; + fn update_field( + self, + _tag: ::core::marker::PhantomData, + value: __M2__::Map, + ) -> (__M1__::Map, Self::Output) { + ( + self.first_name, + __PartialPerson { + first_name: value, + last_name: self.last_name, + }, + ) + } } ``` -`__M1__` is unconstrained, so the impl applies whatever state the field is currently in, and `__F1__` -passes through untouched. That is precisely why fields can be built in any order: no impl cares about the -other fields' states. - -Because `Mapper` is an *output* rather than an input, the two directional traits can pin a transition -by constraining it. [`BuildField`](./build_field.md) is a blanket impl over -`UpdateField` and [`TakeField`](./take_field.md) over -`UpdateField`: same primitive, opposite constraints. - -Nothing here changes a value's runtime layout beyond moving it in or out of the slot; the markers are -zero-sized and the wrapping is a type-level fiction. +`__M1__` is unconstrained, so the impl applies whatever state the field is in, and `__F1__` passes +through untouched, which is why fields can be built in any order. Because `Mapper` is an output, the +two directional traits pin a transition by constraining it: [`BuildField`](./build_field.md) is a +blanket impl over `UpdateField` and +[`TakeField`](./take_field.md) over `UpdateField`. The markers +are zero-sized, so nothing changes at run time beyond moving the value in or out of its slot. ## Common Mistakes @@ -153,8 +182,35 @@ fine, but the shape catches people expecting the builder alone. **Reaching for it where [`BuildField`](./build_field.md) would do makes the code harder to read** for no gain. The directional traits exist because they say what is happening. -**A field not declared on the record has no impl**, and the error names the missing `UpdateField` bound -with the tag fully expanded rather than saying the field does not exist. +**The marker must be named.** Calling the method without it: + +```rust +let (_old, _partial) = + Person::builder().update_field(PhantomData::, "Alice".to_owned()); +``` + +leaves `M` to inference, which cannot recover it from the value: + +```text +error[E0284]: type annotations needed for `((), __PartialPerson<_, IsNothing>)` +... + = note: cannot satisfy `<_ as MapType>::Map == String` +``` + +**A field not declared on the record has no impl.** Setting an `age` that `Person` does not declare: + +```rust +let _ = Person::builder().build_field(PhantomData::, 42_u8); +``` + +reports the missing `UpdateField` bound with the tag spelled out, rather than saying the field does +not exist, and lists the fields that do have impls: + +```text +error[E0277]: the trait bound `__PartialPerson: UpdateField>>>, IsPresent>` is not satisfied +... +help: the following other types implement trait `UpdateField` +``` ## Related constructs diff --git a/docs/reference/traits/optional/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md index 6a21203e..615b9830 100644 --- a/docs/reference/traits/optional/can_build_with_default.md +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -1,6 +1,8 @@ --- +title: 'CanBuildWithDefault — widen a record' sidebar_label: 'CanBuildWithDefault' sidebar_position: 6 +description: 'Build a wider record from a narrower one in one call, copying the shared fields by name and filling the rest from Default.' --- # `CanBuildWithDefault` @@ -51,34 +53,40 @@ It is an **associated function**, called on the target: `Point3d::build_with_def ## Examples -Widening a record with no field named anywhere: +Widening a record with no field named anywhere, in one call and as the three calls it stands for: ```rust -use cgp::extra::field::impls::CanBuildWithDefault; use cgp::prelude::*; +use cgp::core::field::impls::CanBuildFrom; +use cgp::extra::field::impls::{CanBuildWithDefault, CanFinalizeWithDefault}; #[derive(Debug, Clone, Eq, PartialEq, CgpData)] -struct Point2d { x: u64, y: u64 } +pub struct Point2d { + pub x: u64, + pub y: u64, +} #[derive(Debug, Clone, Eq, PartialEq, CgpData)] -struct Point3d { x: u64, y: u64, z: u64 } +pub struct Point3d { + pub x: u64, + pub y: u64, + pub z: u64, +} -let point_3d = Point3d::build_with_default(Point2d { x: 1, y: 2 }); +pub fn demo() { + let point_3d = Point3d::build_with_default(Point2d { x: 1, y: 2 }); + assert_eq!(point_3d, Point3d { x: 1, y: 2, z: 0 }); -assert_eq!(point_3d, Point3d { x: 1, y: 2, z: 0 }); // z defaulted + let written_out: Point3d = Point3d::builder() + .build_from(Point2d { x: 1, y: 2 }) + .finalize_with_default(); + assert_eq!(written_out, point_3d); +} ``` Neither struct knows about the other. They share field *names*, matched at the type level, and `z` is filled because `u64: Default`. -Written out, the same thing is three calls: - -```rust -let point_3d: Point3d = Point3d::builder() - .build_from(Point2d { x: 1, y: 2 }) - .finalize_with_default(); -``` - ## When to use it **Reach for it for a one-call widening from a narrower record**, and reach for the pieces when anything @@ -95,45 +103,103 @@ in between needs to happen. ## Under the hood -The impl chains the three steps and constrains each with a bound: +The trait's one impl chains the three steps and constrains each with a bound: ```rust -// conceptually: -// Self: HasBuilder, -// Self::Builder: CanBuildFrom, -// >::Output: CanFinalizeWithDefault -// -// fn build_with_default(source: Source) -> Self { -// Self::builder().build_from(source).finalize_with_default() -// } +impl CanBuildWithDefault for Target +where + Target: HasBuilder, + Builder: CanBuildFrom, + Builder::Output: CanFinalizeWithDefault, +{ + fn build_with_default(source: Source) -> Target { + Target::builder().build_from(source).finalize_with_default() + } +} ``` -Each bound is where one of the requirements comes from: [`CanBuildFrom`](../casting/can_build_from.md) brings the -[`HasFields`](../shape/has_fields.md) obligation on the source, and +Each bound is where one of the requirements comes from: +[`CanBuildFrom`](../casting/can_build_from.md) brings the [`HasFields`](../shape/has_fields.md) +obligation on the source and needs every source field to exist on the target, and [`CanFinalizeWithDefault`](./can_finalize_with_default.md) brings the `Default` obligation on the -remaining fields, through a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying -[`TransformMapDefault`](./transform_map_default.md). +remaining fields, through a [`TransformMapFields`](../type-level/transform_map_fields.md) walk +carrying [`TransformMapDefault`](./transform_map_default.md). -So an unsatisfied bound here is always really an unsatisfied bound one layer down, which is worth knowing -because the error names that layer rather than this trait. +So an unsatisfied bound here is always really an unsatisfied bound one layer down. Because the call +is an associated function checked against these `where` clauses, not a method looked up on a +receiver, rustc follows the chain to the root cause and prints each layer as a `required for` note. ## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::field::impls`. -**The source needs [`HasFields`](../shape/has_fields.md), not just a builder.** Deriving only +**The source needs [`HasFields`](../shape/has_fields.md), not only a builder.** Deriving only [`BuildField`](../../derives/derive_build_field.md) on both looks symmetric and fails, the same trap [`CanBuildFrom`](../casting/can_build_from.md) carries. -**Every field the source does not supply needs `Default`.** The error names the missing -[`TransformMap`](../type-level/transform_map.md) impl rather than the field. +**Every field the source does not supply needs `Default`.** Building a `Server` from a `Host` that +lacks its `port`, where `Port` has no `Default`: + +```rust +pub struct Port(pub u16); + +#[derive(CgpData)] +pub struct Host { + pub host: String, +} + +#[derive(CgpData)] +pub struct Server { + pub host: String, + pub port: Port, +} + +let _ = Server::build_with_default(Host { + host: "localhost".to_owned(), +}); +``` + +names the type and the conversion that needs it: + +```text +error[E0277]: the trait bound `Port: Default` is not satisfied +... + = note: required for `TransformMapDefault` to implement `TransformMap` +``` + +The later notes climb the chain from there, through `TransformMapFields` and +`CanFinalizeWithDefault`, to ``required for `Server` to implement `CanBuildWithDefault` ``. **It is an associated function on the target.** `Point3d::build_with_default(source)`, not a method on the source. **There is no place to set a field explicitly.** If one field needs a real value, use the three-call form. -**A field the target lacks is silently dropped**, since the merge matches on the target's slots. +**A source field the target lacks is an error, not dropped.** The merge walks the *source's* fields +and builds each into the target, so a `label` that `Point3d` does not declare: + +```rust +#[derive(CgpData)] +pub struct LabeledPoint2d { + pub x: u64, + pub y: u64, + pub label: String, +} + +let _ = Point3d::build_with_default(LabeledPoint2d { + x: 1, + y: 2, + label: "origin".to_owned(), +}); +``` + +has no slot to go into: + +```text +error[E0277]: the trait bound `__PartialPoint3d: UpdateField>>>>>, IsPresent>` is not satisfied +``` + +The widening runs one way only: the target may have fields the source lacks, never the reverse. ## Related constructs diff --git a/docs/reference/traits/optional/can_finalize_with_default.md b/docs/reference/traits/optional/can_finalize_with_default.md index 05a5af21..ed545f4d 100644 --- a/docs/reference/traits/optional/can_finalize_with_default.md +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -1,6 +1,8 @@ --- +title: 'CanFinalizeWithDefault — fill gaps, then build' sidebar_label: 'CanFinalizeWithDefault' sidebar_position: 5 +description: 'End a build by filling every unset field from Default, for an optional builder or a core one, then finalizing through the strict impl.' --- # `CanFinalizeWithDefault` @@ -14,7 +16,7 @@ catches a missing field at compile time. For a record where some fields have sen strictness is the wrong shape. `CanFinalizeWithDefault` relaxes it: every field that is not set becomes `Default::default()`, and the result is the concrete struct. -**The strict presence check still runs; it just always passes**, because the fields are re-marked to +**The strict presence check still runs, and it always passes**, because the fields are re-marked to `IsPresent` first. That is the layer's whole design in one sentence, and it is why the core [`FinalizeBuild`](../builder/finalize_build.md) remains the only route from a partial value to a struct. @@ -54,36 +56,43 @@ from `cgp-field-extra`. use cgp::extra::field::impls::CanFinalizeWithDefault; ``` -**Every unset field's type needs `Default`.** A field whose type has none makes the transform -unresolvable, and the error names the missing -[`TransformMap`](../type-level/transform_map.md) impl rather than the field. +**A field's type needs `Default` unless the field is `IsPresent`.** On a core builder that means +every unset field. On an optional builder it means every field, set or not, because a set field is +still `IsOptional` and only [`TransformMapDefault`](./transform_map_default.md)'s `IsPresent` impl +is free of the bound. [Common Mistakes](#common-mistakes) shows what rustc reports. ## Examples -Filling a gap rather than reporting it: +Filling a gap rather than reporting it, from an optional builder and from a core one: ```rust -use cgp::extra::field::impls::{CanFinalizeWithDefault, HasOptionalBuilder, SetOptional}; use cgp::prelude::*; +use cgp::extra::field::impls::{CanFinalizeWithDefault, HasOptionalBuilder, SetOptional}; -#[derive(CgpData)] +#[derive(Debug, PartialEq, CgpData)] pub struct Context { pub foo: String, pub bar: u64, } -let context = Context::optional_builder() - .set(PhantomData::, "foo".to_owned()) - .finalize_with_default(); - -assert_eq!(context.foo, "foo"); -assert_eq!(context.bar, 0); // defaulted +pub fn demo() { + let from_optional = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + assert_eq!(from_optional.bar, 0); + + // A core builder works too: its absent field is `IsNothing` rather than `None`. + let from_core = Context::builder() + .build_field(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + assert_eq!(from_core, from_optional); +} ``` -Had that used [`finalize_optional`](./finalize_optional.md), it would have returned `Err("bar")` instead, -which is the point of deferring the choice to the finalize call rather than to the builder. - -The one-call form that also copies from a source is +Had the first used [`finalize_optional`](./finalize_optional.md), it would have returned +`Err("bar")` instead, which is the point of deferring the choice to the finalize call. The core +builder reaches the same value, because [`TransformMapDefault`](./transform_map_default.md) converts +an `IsNothing` field as readily as a `None`. The one-call form that also copies from a source is [`CanBuildWithDefault`](./can_build_with_default.md). ## When to use it @@ -101,7 +110,7 @@ The one-call form that also copies from a source is ## Under the hood -The whole impl is a transform followed by the ordinary finalize: +The trait's one impl is a transform followed by the ordinary finalize: ```rust impl CanFinalizeWithDefault for Builder @@ -118,7 +127,9 @@ where ``` Read the bounds together: the first says every field can be re-marked to `IsPresent` by -[`TransformMapDefault`](./transform_map_default.md), and the second says the result is then finalizable. +[`TransformMapDefault`](./transform_map_default.md), and the second says the result is then +finalizable. The `Default` requirement lives inside the first, on the marker's conversions from +`IsNothing` and `IsOptional`. Its mirror image is [`ToOptional`](./to_optional.md), which runs the same [`TransformMapFields`](../type-level/transform_map_fields.md) walk with @@ -133,9 +144,50 @@ configuration its single impl requires, so the strict check runs, and cannot fai **It is not in the prelude.** Import from `cgp::extra::field::impls`. -**Every field's type needs `Default`.** A field whose type has none makes the transform unresolvable, and -the error names the missing [`TransformMap`](../type-level/transform_map.md) impl rather than the field, which is -the most confusing failure in this layer. +**A field whose type has no `Default` is reported without being named.** On a core builder with +`port` left unset, where `Port` has no `Default`: + +```rust +pub struct Port(pub u16); + +#[derive(CgpData)] +pub struct Server { + pub host: String, + pub port: Port, +} + +let _ = Server::builder() + .build_field(PhantomData::, "localhost".to_owned()) + .finalize_with_default(); +``` + +method resolution fails, and the notes stop at the walk rather than reaching `Port`: + +```text +error[E0599]: the method `finalize_with_default` exists for struct `__PartialServer`, but its trait bounds were not satisfied +... + = note: the following trait bounds were not satisfied: + `__PartialServer: TransformMapFields` + which is required by `__PartialServer: CanFinalizeWithDefault` +``` + +Neither `port` nor `Default` appears, which makes this the most confusing failure in the layer. The +same bound reached through a `where` clause rather than a method call, as in +[`build_with_default`](./can_build_with_default.md#common-mistakes), does name `Port: Default`. + +**On an optional builder, setting the field does not help.** Setting both fields of the same +`Server` on an optional builder: + +```rust +let _ = Server::optional_builder() + .set(PhantomData::, "localhost".to_owned()) + .set(PhantomData::, Port(8080)) + .finalize_with_default(); +``` + +fails the same way, on `__PartialServer`, because a set field is still +`IsOptional` and its conversion requires `Default`. A core builder with both fields set finalizes +this way regardless, and [`finalize_optional`](./finalize_optional.md) needs no `Default` at all. **A defaulted field is silent.** Nothing distinguishes "set to zero" from "left unset" in the result, which is the trade against [`FinalizeOptional`](./finalize_optional.md). @@ -143,7 +195,7 @@ is the trade against [`FinalizeOptional`](./finalize_optional.md). **It gives up the compile-time completeness check** that the core builder provides. **It applies to a core builder too**, not only an optional one: an absent `IsNothing` field is -transformed as readily as a `None`. +transformed as readily as a `None`, as the [example](#examples) shows. **It consumes the builder.** diff --git a/docs/reference/traits/optional/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md index 46c2b9eb..0182ef31 100644 --- a/docs/reference/traits/optional/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -1,6 +1,8 @@ --- +title: 'FinalizeOptional — finalize or name the gap' sidebar_label: 'FinalizeOptional' sidebar_position: 4 +description: 'End an optional build at run time: the concrete struct if every field holds a value, or the name of a missing field as an Err.' --- # `FinalizeOptional` @@ -36,8 +38,8 @@ pub trait FinalizeOptional: PartialData { The `PartialData` [supertrait](/docs/reference/glossary#supertrait) supplies `Target`, the concrete struct being built, so the method projects its return type through it and declares no associated type of its own. `finalize_optional` takes `self`, consuming the builder, and returns `Result`: the built struct on success, -or, on failure, a missing field's own name, recovered from its type-level tag as a `&'static -str` with no allocation. The trait carries no other parameter. It is not in the prelude; import it from +or, on failure, a missing field's own name, recovered from its type-level tag as a +`&'static str` with no allocation. The trait carries no other parameter. It is not in the prelude; import it from `cgp-field-extra`. ## Usage @@ -48,41 +50,50 @@ str` with no allocation. The trait carries no other parameter. It is not in the use cgp::extra::field::impls::FinalizeOptional; ``` -`Self` must be an optional builder, from -[`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md). +`Self` must be an optional builder, from [`optional_builder()`](./has_optional_builder.md) or +[`to_optional()`](./to_optional.md). The record also needs [`HasFields`](../shape/has_fields.md), +since the walk runs over its field list; +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) supplies it along with the builder. ## Examples The strict ending, succeeding and failing: ```rust -use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; use cgp::prelude::*; +use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; -#[derive(CgpData)] +#[derive(Debug, PartialEq, CgpData)] pub struct Context { pub foo: String, pub bar: u64, } -let context = Context::optional_builder() - .set(PhantomData::, "foo".to_owned()) - .set(PhantomData::, 42) - .finalize_optional() - .unwrap(); - -assert_eq!(context.foo, "foo"); +pub fn demo() { + let complete = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .set(PhantomData::, 42) + .finalize_optional(); + assert_eq!( + complete, + Ok(Context { + foo: "foo".to_owned(), + bar: 42, + }) + ); + + let missing_bar = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_optional(); + assert_eq!(missing_bar, Err("bar")); + + // With both unset, the walk from the last field back stops at `bar`. + assert_eq!(Context::optional_builder().finalize_optional(), Err("bar")); +} ``` -Leave `bar` unset and it reports the name: - -```rust -let result = Context::optional_builder() - .set(PhantomData::, "foo".to_owned()) - .finalize_optional(); - -assert_eq!(result.err(), Some("bar")); -``` +With both fields unset the error is still `"bar"`: the walk checks the last declared field first and +stops at the first `None` it meets. ## When to use it @@ -105,21 +116,51 @@ which field is missing and not enough to match on programmatically. Unlike its defaulting sibling, `FinalizeOptional` does **not** go through [`TransformMapFields`](../type-level/transform_map_fields.md). It walks the target's -[`HasFields`](../shape/has_fields.md) list directly, and the reason is that it has to be able to *stop*. +[`HasFields`](../shape/has_fields.md) list directly, and the reason is that it has to be able to +*stop*. The trait's one impl hands the walk the builder and finalizes whatever comes back: -It checks the rest of the list before the current field, so the fields are checked from last to -first. For each field it pulls the `Option` out with [`UpdateField`](../builder/update_field.md), and: +```rust +impl FinalizeOptional for ContextA +where + ContextA: PartialData, + Target: HasFields, + Target::Fields: FinalizeOptionalImpl, + ContextB: FinalizeBuild, +{ + fn finalize_optional(self) -> Result { + let context = Target::Fields::finalize_optional(self)?; + Ok(context.finalize_build()) + } +} +``` + +The walk is a private helper trait, implemented for `Nil` as the identity and for each `Cons` cell +as: -- if it is `Some`, writes the value back as `IsPresent` with [`BuildField`](../builder/build_field.md) and - continues; -- if it is `None`, returns `Err(Tag::VALUE)` immediately, the field's name recovered as a static string - through [`StaticString`](../formatting/static_string.md). +```rust +fn finalize_optional(context: ContextA) -> Result { + let context = Rest::finalize_optional(context)?; + let (m_value, context) = context.update_field(PhantomData, ()); + + let value = m_value.ok_or(Tag::VALUE)?; + let context = context.build_field(PhantomData, value); + + Ok(context) +} +``` + +It checks the rest of the list before the current field, so the fields are checked from last to +first. For each field, [`UpdateField`](../builder/update_field.md) moves it from `IsOptional` to +`IsNothing` and hands back the `Option`. A `Some` is written back as `IsPresent` with +[`BuildField`](../builder/build_field.md); a `None` returns `Err(Tag::VALUE)`, the field's name +recovered as a static string through [`StaticString`](../formatting/static_string.md), and the `?` +stops the walk. Only if every field yields a value does the walk reach the all-present configuration and call [`finalize_build`](../builder/finalize_build.md). **The strict, all-present [`FinalizeBuild`](../builder/finalize_build.md) remains the only way a partial value -becomes a concrete struct.** Everything in this layer simply guarantees that configuration is reached +becomes a concrete struct.** Everything in this layer guarantees that configuration is reached before it is invoked, or reports why it could not be. That short-circuiting is also why only one missing field is named: the walk stops at the first @@ -134,16 +175,29 @@ the error is `"bar"`. **The error is a `&'static str`.** It names one missing field and is not a structured error, so it cannot be matched on beyond string comparison. -**It reports only the first.** A builder missing three fields yields one name. +**It reports only one.** A builder missing three fields yields one name, the last of them in +declaration order. + +**It does not apply to a core builder.** Calling it on a builder from `builder()`: + +```rust +let _ = Context::builder().finalize_optional(); +``` + +fails method resolution, and the notes list only the unmet bounds for the autoref'd receivers, with +nothing about `IsOptional`: + +```text +error[E0599]: the method `finalize_optional` exists for struct `__PartialContext`, but its trait bounds were not satisfied +``` -**It does not apply to a core builder.** The fields must be `IsOptional`; a core builder either -finalizes at compile time or does not. +The fields must be `IsOptional`; a core builder either finalizes at compile time or does not. **It supertraits [`PartialData`](../builder/partial_data.md)**, so `Target` is projected from there and naming both in a bound is redundant. -**Field order decides which name you get**, since the walk runs from the last declared field back and -stops at the first `None` it meets, so the name is the last unset field in declaration order. +**Field order decides which name you get.** Reordering a struct's fields changes which missing +field is reported, so a test asserting on the name depends on the declaration order. ## Related constructs diff --git a/docs/reference/traits/optional/has_optional_builder.md b/docs/reference/traits/optional/has_optional_builder.md index 68c03662..d0892088 100644 --- a/docs/reference/traits/optional/has_optional_builder.md +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -1,6 +1,8 @@ --- +title: 'HasOptionalBuilder — an all-optional builder' sidebar_label: 'HasOptionalBuilder' sidebar_position: 1 +description: 'Start a builder whose every field is an Option, set in any order and as often as you like, with the choice of ending deferred to the finalize call.' --- # `HasOptionalBuilder` @@ -62,40 +64,49 @@ The impls are blanket ones over the core builder machinery, so any record derivi ## Examples -An all-optional builder, set in any order and finalized strictly: +An all-optional builder, set in any order and finished by each of the two endings: ```rust -use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; use cgp::prelude::*; +use cgp::extra::field::impls::{ + CanFinalizeWithDefault, FinalizeOptional, HasOptionalBuilder, SetOptional, +}; -#[derive(CgpData)] +#[derive(Debug, PartialEq, CgpData)] pub struct Context { pub foo: String, pub bar: u64, } -let builder = Context::optional_builder() - .set(PhantomData::, "foo".to_owned()) - .set(PhantomData::, 42); - -let context = builder.finalize_optional().unwrap(); - -assert_eq!(context.foo, "foo"); -``` - -Leave a field unset and the two endings diverge, which is the point of deferring the choice: - -```rust -use cgp::extra::field::impls::CanFinalizeWithDefault; - -let context = Context::optional_builder() - .set(PhantomData::, "foo".to_owned()) - .finalize_with_default(); - -assert_eq!(context.bar, 0); // defaulted +pub fn demo() { + let context = Context::optional_builder() + .set(PhantomData::, 42) + .set(PhantomData::, "foo".to_owned()) + .finalize_optional(); + assert_eq!( + context, + Ok(Context { + foo: "foo".to_owned(), + bar: 42, + }) + ); + + // The same kind of builder, with `bar` left unset, finalized each way. + let defaulted = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_with_default(); + assert_eq!(defaulted.bar, 0); + + let missing = Context::optional_builder() + .set(PhantomData::, "foo".to_owned()) + .finalize_optional(); + assert_eq!(missing, Err("bar")); +} ``` -Had that used `finalize_optional`, it would have returned `Err("bar")` instead. +The fields are set in reverse declaration order, which the core builder also allows; what it does +not allow is ending an incomplete build any way but a compile error. Here the same unfinished +builder either fills `bar` with `0` or reports it by name, chosen at the finalize call. ## When to use it @@ -115,18 +126,28 @@ Had that used `finalize_optional`, it would have returned `Err("bar")` instead. ## Under the hood -`optional_builder()` is [`HasBuilder`](../builder/has_builder.md)'s `builder()` followed by -[`ToOptional`](./to_optional.md): start at all-`IsNothing`, then re-mark every field to `IsOptional` -with a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying the -[`TransformOptional`](./transform_optional.md) marker. - -So the resulting type is the same partial companion the core builder uses, at a configuration the core -builder never reaches on its own: +The trait's one impl is a blanket impl over the core builder and [`ToOptional`](./to_optional.md): ```rust -// __PartialContext +impl HasOptionalBuilder for Context +where + Context: HasBuilder, + Context::Builder: ToOptional, +{ + type Builder = Builder; + + fn optional_builder() -> Self::Builder { + Self::builder().to_optional() + } +} ``` +So `optional_builder()` starts at the all-`IsNothing` configuration and re-marks every field to +`IsOptional` with a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying the +[`TransformOptional`](./transform_optional.md) marker. For the example's `Context`, the result is +`__PartialContext`, the same partial companion the core builder uses, at a +configuration the core builder never reaches on its own. + Nothing about the companion type is special to this layer. What changes is the marker, and with it which operations apply: [`SetOptional`](./set_optional.md) resolves where [`BuildField`](../builder/build_field.md) does not, and the strict @@ -143,7 +164,9 @@ compile error; here it is an `Err` or a silently substituted default. That is th making consciously. **The builder's type does not record what you have set.** Every field stays `IsOptional` throughout, -which allows re-setting and is why finalizing has to check at run time. +which allows re-setting and is why finalizing has to check at run time. It also means +[`finalize_with_default`](./can_finalize_with_default.md#common-mistakes) needs `Default` on every +field's type, set or not. **`optional_builder()` is an associated function**, so it is `Context::optional_builder()` with no receiver. diff --git a/docs/reference/traits/optional/index.md b/docs/reference/traits/optional/index.md index 6ef27ca6..1da0da7a 100644 --- a/docs/reference/traits/optional/index.md +++ b/docs/reference/traits/optional/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'Traits that relax the strict record builder, so a field can be set in any order, more than once, or left unset and then defaulted or reported.' --- # Optional and defaulted fields diff --git a/docs/reference/traits/optional/set_optional.md b/docs/reference/traits/optional/set_optional.md index 01d0989e..26a1a147 100644 --- a/docs/reference/traits/optional/set_optional.md +++ b/docs/reference/traits/optional/set_optional.md @@ -1,6 +1,8 @@ --- +title: 'SetOptional — set a field of an optional builder' sidebar_label: 'SetOptional' sidebar_position: 3 +description: 'Set one field of an all-optional builder, as many times as you like, optionally getting back the value it replaced.' --- # `SetOptional` @@ -59,27 +61,28 @@ is no "unset" operation: a field starts absent and stays so unless it is set. Setting fields in any order, and re-setting one: ```rust -use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; use cgp::prelude::*; +use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional}; -#[derive(CgpData)] +#[derive(Debug, PartialEq, CgpData)] pub struct Context { pub foo: String, pub bar: u64, } -let builder = Context::optional_builder() - .set(PhantomData::, "foo".to_owned()) - .set(PhantomData::, 42); - -// Setting an already-set field hands back what it replaced. -let (replaced, builder) = builder.set_optional(PhantomData::, "bar".to_owned()); +pub fn demo() { + let builder = Context::optional_builder() + .set(PhantomData::, 42) + .set(PhantomData::, "foo".to_owned()); -assert_eq!(replaced, Some("foo".to_owned())); + // Setting an already-set field hands back what it replaced. + let (replaced, builder) = + builder.set_optional(PhantomData::, "bar".to_owned()); + assert_eq!(replaced, Some("foo".to_owned())); -let context = builder.finalize_optional().unwrap(); - -assert_eq!(context.foo, "bar"); + let context = builder.finalize_optional().unwrap(); + assert_eq!(context.foo, "bar"); +} ``` Because `set` returns `Self`, the calls chain exactly as core `build_field` calls do. The difference is @@ -92,29 +95,47 @@ thing the core builder cannot express. - **[`BuildField`](../builder/build_field.md)** when each field is set exactly once. The compile-time completeness check it buys is the reason the core family exists. -- **`set`** when whatever was there should simply be replaced. +- **`set`** when whatever was there should be replaced. - **`set_optional`** when the previous value matters: merging, accumulating, or warning on a duplicate. - **[`CanBuildFrom`](../casting/can_build_from.md)** when the values come from another record wholesale rather than one at a time. ## Under the hood -`SetOptional` is a single [`UpdateField`](../builder/update_field.md) call writing `Some(value)` into an -`IsOptional` slot, with both the source and target markers pinned to `IsOptional`: +`SetOptional` is a blanket impl over a single [`UpdateField`](../builder/update_field.md) call that +writes `Some(value)` into an `IsOptional` slot, with both the source and target markers pinned to +`IsOptional`: ```rust -// conceptually: -// Partial: UpdateField +impl SetOptional for Context +where + Context: UpdateField, +{ + type Value = Context::Value; + + fn set(self, tag: PhantomData, value: Self::Value) -> Self { + self.set_optional(tag, value).1 + } + + fn set_optional( + self, + tag: PhantomData, + value: Self::Value, + ) -> (Option, Self) { + self.update_field(tag, Some(value)) + } +} ``` -`Mapper = IsOptional` requires the field to already be in the optional state, and `Output = Partial` +`Mapper = IsOptional` requires the field to already be in the optional state, and `Output = Context` pins the result to the same type on both sides. **That pinning allows repeated sets:** there is no marker to consume, so no impl becomes unavailable after the first call. Contrast [`BuildField`](../builder/build_field.md#under-the-hood), which pins `Mapper = IsNothing` and a target of `IsPresent`: its `Output` is a *different* type, which makes a second call fail to resolve. -Since the primitive returns the old storage alongside the new value, `set_optional` simply exposes it and +Since the primitive returns the old storage alongside the new value, `set_optional` +exposes it and `set` discards it. Under `IsOptional` that old storage is an `Option`, which is why the returned value is optional even though the argument is not. @@ -122,8 +143,23 @@ value is optional even though the argument is not. **It is not in the prelude.** Import from `cgp::extra::field::impls`. -**It does not apply to a core builder.** The field must already be `IsOptional`, so start with -[`optional_builder()`](./has_optional_builder.md) or convert with [`to_optional()`](./to_optional.md). +**It does not apply to a core builder.** Calling `set` on a builder from `builder()`: + +```rust +let _ = Context::builder().set(PhantomData::, "foo".to_owned()); +``` + +fails both pins of the blanket impl, each reported as a mismatch: + +```text +error[E0271]: type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Mapper == IsOptional` +... +error[E0271]: type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Output == __PartialContext` +``` + +The field must already be `IsOptional`, so start with +[`optional_builder()`](./has_optional_builder.md) or convert with +[`to_optional()`](./to_optional.md). **The builder's type never changes, so it carries no record of what you have set.** That is deliberate: it allows re-setting, and it is why finalizing has to check at run time. diff --git a/docs/reference/traits/optional/to_optional.md b/docs/reference/traits/optional/to_optional.md index 8d714583..1c29ab6d 100644 --- a/docs/reference/traits/optional/to_optional.md +++ b/docs/reference/traits/optional/to_optional.md @@ -1,6 +1,8 @@ --- +title: 'ToOptional — relax an existing builder' sidebar_label: 'ToOptional' sidebar_position: 2 +description: 'Re-mark every field of a core builder as optional, keeping set fields as Some, so the rest can arrive in any order and the build can end either way.' --- # `ToOptional` @@ -52,39 +54,43 @@ You call it on a partial value, as `builder.to_optional()`. ## Examples -Relaxing a partly-filled core builder so the remaining fields can arrive in any order: +Relaxing a partly filled core builder, and then a complete value: ```rust -use cgp::extra::field::impls::{FinalizeOptional, SetOptional, ToOptional}; use cgp::prelude::*; +use cgp::extra::field::impls::{FinalizeOptional, SetOptional, ToOptional}; -#[derive(CgpData)] +#[derive(Debug, PartialEq, CgpData)] pub struct Context { pub foo: String, pub bar: u64, } -let builder = Context::builder() - .build_field(PhantomData::, "foo".to_owned()) - .to_optional(); // foo is Some, bar is None - -let context = builder - .set(PhantomData::, 42) - .finalize_optional() - .unwrap(); - -assert_eq!(context.bar, 42); +pub fn demo() { + // `foo` is set before the conversion and survives it as `Some`. + let context = Context::builder() + .build_field(PhantomData::, "foo".to_owned()) + .to_optional() + .set(PhantomData::, 42) + .finalize_optional() + .unwrap(); + assert_eq!(context.foo, "foo"); + + // Every field of a complete value becomes `Some`, so one can be overwritten. + let context = context + .into_builder() + .to_optional() + .set(PhantomData::, 7) + .finalize_optional() + .unwrap(); + assert_eq!(context.bar, 7); +} ``` -The already-set `foo` survives the conversion as `Some("foo")`, which distinguishes this from -starting over with [`optional_builder()`](./has_optional_builder.md). - -Converting a *complete* value works too, by way of -[`into_builder`](../builder/into_builder.md): - -```rust -let builder = context.into_builder().to_optional(); // every field Some -``` +The already-set `foo` survives the first conversion as `Some("foo")`, which distinguishes this from +starting over with [`optional_builder()`](./has_optional_builder.md). The second conversion starts +from [`into_builder`](../builder/into_builder.md), so every field is `Some` and `set` overwrites +`bar`. ## When to use it @@ -101,18 +107,28 @@ let builder = context.into_builder().to_optional(); // every field Some ## Under the hood -`ToOptional` is a [`TransformMapFields`](../type-level/transform_map_fields.md) walk carrying the -[`TransformOptional`](./transform_optional.md) marker, targeting `IsOptional`: +`ToOptional` is a blanket impl over a [`TransformMapFields`](../type-level/transform_map_fields.md) +walk carrying the [`TransformOptional`](./transform_optional.md) marker, targeting `IsOptional`: ```rust -// conceptually: -// self.transform_map_fields::() +impl ToOptional for Context +where + Context: TransformMapFields, +{ + type Output = Context::Output; + + fn to_optional(self) -> Self::Output { + self.transform_map_fields() + } +} ``` That walk visits each field of the target's [`HasFields`](../shape/has_fields.md) shape, uses -[`UpdateField`](../builder/update_field.md) to take the field out and learn its current marker, applies the -transform, and writes it back under `IsOptional`. The transform's own impls are what decide the value: -`IsPresent` becomes `Some(value)`, `IsNothing` becomes `None`, and `IsOptional` passes through. +[`UpdateField`](../builder/update_field.md) to take the field out and learn its current marker, +applies the transform, and writes it back under `IsOptional`. The transform's impls decide the +value: `IsPresent` becomes `Some(value)` and `IsNothing` becomes `None`. **There is no impl from +`IsOptional`**, so a builder that is already optional cannot be converted again, as [Common +Mistakes](#common-mistakes) shows. Its mirror image is [`CanFinalizeWithDefault`](./can_finalize_with_default.md), which runs the same walk with [`TransformMapDefault`](./transform_map_default.md) toward `IsPresent`. **Both operations are the @@ -131,6 +147,23 @@ symmetrically. **Converting gives up the compile-time completeness check** for the fields that were still absent. From here a missing field is an `Err` or a default rather than a compile error. +**It does not apply to a builder that is already optional.** Converting the result of +`optional_builder()` again: + +```rust +let _ = Context::optional_builder().to_optional(); +``` + +finds no [`TransformOptional`](./transform_optional.md) conversion from `IsOptional`, and fails +with: + +```text +error[E0599]: the method `to_optional` exists for struct `__PartialContext`, but its trait bounds were not satisfied +... + = note: the following trait bounds were not satisfied: + `__PartialContext: TransformMapFields` +``` + **It is not reversible.** There is no `from_optional`; getting back to a strict configuration means finalizing, through [`FinalizeOptional`](./finalize_optional.md) or [`CanFinalizeWithDefault`](./can_finalize_with_default.md). diff --git a/docs/reference/traits/optional/transform_map_default.md b/docs/reference/traits/optional/transform_map_default.md index 3f41dce9..95d4d7de 100644 --- a/docs/reference/traits/optional/transform_map_default.md +++ b/docs/reference/traits/optional/transform_map_default.md @@ -1,6 +1,8 @@ --- +title: 'TransformMapDefault — make every field present' sidebar_label: 'TransformMapDefault' sidebar_position: 7 +description: 'The transform marker behind the defaulting finalize: three per-field conversions that leave every field present, filling gaps from Default.' --- # `TransformMapDefault` @@ -68,38 +70,47 @@ conversion it drives: Builder: TransformMapFields ``` -**Every field's type must implement `Default`** for the two filling impls to apply, which is where the -defaulting layer's one real requirement comes from. +**A field's type must implement `Default` unless the field is already `IsPresent`**, since two of +the three impls carry the bound. That is where the defaulting layer's one real requirement comes +from. ## Examples -You meet it in a bound rather than at a call site. This is -[`CanFinalizeWithDefault`](./can_finalize_with_default.md)'s whole impl: +A generic function that drives the defaulting conversion across any builder, and a core builder +passed through it: ```rust +use cgp::prelude::*; use cgp::core::field::traits::TransformMapFields; use cgp::extra::field::impls::TransformMapDefault; -use cgp::prelude::*; -impl CanFinalizeWithDefault for Builder +#[derive(Debug, PartialEq, CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +pub fn fill_defaults(builder: Builder) -> Builder::Output where Builder: TransformMapFields, - Builder::Output: FinalizeBuild, { - type Output = Output; + builder.transform_map_fields() +} - fn finalize_with_default(self) -> Output { - self.transform_map_fields().finalize_build() - } +pub fn demo() { + let full = fill_defaults( + Context::builder().build_field(PhantomData::, "foo".to_owned()), + ); + let context = full.finalize_build(); + assert_eq!(context.bar, 0); } ``` -The marker is the first type argument, and swapping it for -[`TransformOptional`](./transform_optional.md) (with `IsOptional` as the target) is exactly how -[`ToOptional`](./to_optional.md) is written. **Same recursion, different marker.** - -Writing a marker of your own follows the same three-impl shape; the -[`TransformMap`](../type-level/transform_map.md#examples) page shows one. +`fill_defaults` is [`CanFinalizeWithDefault`](./can_finalize_with_default.md) without its last step: +the bound names the marker and the target, and the result is at the all-present configuration, so +`finalize_build` resolves on it. Swapping the marker for +[`TransformOptional`](./transform_optional.md), with `IsOptional` as the target, is how +[`ToOptional`](./to_optional.md) is written. ## When to use it @@ -140,9 +151,10 @@ impl TransformMap for TransformMapDefault ``` Note that each argument type is the *source* marker's projection (`T`, then `()`, then `Option`), -which keeps the three from overlapping. And note that only two carry the `T: Default` bound: a -field already present needs no default, which is why a fully-set builder can be finalized this way -regardless of its field types. +which keeps the three from overlapping. And note that only two carry the `T: Default` bound: a field +already present needs no default, which is why a fully-set *core* builder can be finalized this way +regardless of its field types. An optional builder cannot: its set fields are still `IsOptional`, so +the third impl, and its bound, applies to every field. Three impls are needed rather than one because [`TransformMapFields`](../type-level/transform_map_fields.md#under-the-hood) resolves a conversion per field from @@ -152,8 +164,11 @@ whatever state that field is in, and a record may hold fields in all three state **It is not in the prelude.** Import from `cgp::extra::field::impls`. -**Two of its three impls require `Default`.** A field whose type has none makes the walk unresolvable the -moment that field is unset, and the error names the missing `TransformMap` impl rather than the field. +**Two of its three impls require `Default`.** A field whose type has none makes the walk +unresolvable whenever that field is not `IsPresent`: unset on a core builder, and always on an +optional one. Through a method call such as `finalize_with_default`, the error names the unmet +`TransformMapFields` bound rather than the field; +[`CanFinalizeWithDefault`](./can_finalize_with_default.md#common-mistakes) shows it. **It always targets `IsPresent`.** It cannot be used to reach any other configuration; that is [`TransformOptional`](./transform_optional.md)'s job. diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index 12fe7c0d..6adbc3a3 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -1,6 +1,8 @@ --- +title: 'TransformOptional — make every field optional' sidebar_label: 'TransformOptional' sidebar_position: 8 +description: 'The transform marker behind ToOptional: two per-field conversions that wrap a present field in Some and turn an absent one into None.' --- # `TransformOptional` @@ -41,8 +43,8 @@ pub struct TransformOptional; ``` It carries no data. It becomes a transform by implementing -[`TransformMap`](../type-level/transform_map.md) once for each state a field might currently be in, both -impls targeting `IsOptional`: +[`TransformMap`](../type-level/transform_map.md) once for each state a core builder's field can be +in, both impls targeting `IsOptional`: | a field currently | becomes | |---|---| @@ -77,30 +79,43 @@ to records the defaulting path does not. ## Examples -You meet it in the bound behind [`ToOptional`](./to_optional.md): +A generic function that drives the optional conversion across any builder, and a partly built core +builder passed through it: ```rust -use cgp::core::field::traits::TransformMapFields; -use cgp::extra::field::impls::TransformOptional; use cgp::prelude::*; - -// conceptually: -// impl ToOptional for Builder -// where Builder: TransformMapFields -// { -// fn to_optional(self) -> Self::Output { -// self.transform_map_fields() -// } -// } +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::TransformMapFields; +use cgp::extra::field::impls::{FinalizeOptional, SetOptional, TransformOptional}; + +#[derive(Debug, PartialEq, CgpData)] +pub struct Context { + pub foo: String, + pub bar: u64, +} + +pub fn relax(builder: Builder) -> Builder::Output +where + Builder: TransformMapFields, +{ + builder.transform_map_fields() +} + +pub fn demo() { + let optional = + relax(Context::builder().build_field(PhantomData::, "foo".to_owned())); + let context = optional + .set(PhantomData::, 42) + .finalize_optional() + .unwrap(); + assert_eq!(context.foo, "foo"); +} ``` -Swap the marker for [`TransformMapDefault`](./transform_map_default.md) and the target for `IsPresent`, -add a [`finalize_build`](../builder/finalize_build.md), and you have -[`CanFinalizeWithDefault`](./can_finalize_with_default.md). The two operations differ by exactly that -much. - -Writing a marker of your own follows the same shape; the -[`TransformMap`](../type-level/transform_map.md#examples) page shows one with three impls. +`relax` is [`ToOptional`](./to_optional.md)'s whole impl written as a function. Swap the marker for +[`TransformMapDefault`](./transform_map_default.md) and the target for `IsPresent`, add a +[`finalize_build`](../builder/finalize_build.md), and you have +[`CanFinalizeWithDefault`](./can_finalize_with_default.md). ## When to use it @@ -115,21 +130,29 @@ Writing a marker of your own follows the same shape; the ## Under the hood -The marker is zero-sized and carries [`TransformMap`](../type-level/transform_map.md) impls distinguished by their -source marker, each targeting `IsOptional`: +The marker is zero-sized and carries two [`TransformMap`](../type-level/transform_map.md) impls, +distinguished by their source marker, each targeting `IsOptional`: ```rust -// IsPresent -> IsOptional: wrap -// fn transform_mapped(value: T) -> Option { Some(value) } -// -// IsNothing -> IsOptional: nothing to wrap -// fn transform_mapped(_value: ()) -> Option { None } +impl TransformMap for TransformOptional { + fn transform_mapped(value: T) -> Option { + Some(value) + } +} + +impl TransformMap for TransformOptional { + fn transform_mapped(_value: ()) -> Option { + None + } +} ``` Note what is absent: **no `Default` bound anywhere.** Its counterpart -[`TransformMapDefault`](./transform_map_default.md) needs one on two of its three impls, because filling -an absent field means producing a value from nothing. Producing `None` does not, so this conversion -applies to every field type. +[`TransformMapDefault`](./transform_map_default.md) needs one on two of its three impls, because +filling an absent field means producing a value from nothing. Producing `None` does not, so this +conversion applies to every field type. Also absent is an impl from `IsOptional`, which +[`TransformMapDefault`](./transform_map_default.md) has: a field that is already optional has no +conversion here, so the marker cannot be applied to an optional builder. [`TransformMapFields`](../type-level/transform_map_fields.md#under-the-hood) applies it, visiting each field of the target's [`HasFields`](../shape/has_fields.md) shape and using @@ -147,6 +170,9 @@ makes [`SetOptional`](./set_optional.md) resolve and the strict **It always targets `IsOptional`.** Reaching `IsPresent` is [`TransformMapDefault`](./transform_map_default.md)'s job. +**It has no conversion from `IsOptional`**, so a builder that is already optional cannot be relaxed +again; [`ToOptional`](./to_optional.md#common-mistakes) shows the error. + **It is a marker, not an operation.** There is no method and nothing to wire. It is named in a bound. **It requires nothing of the field types**, which is the one place the two markers genuinely differ in From 8acb4d939d15241ef8e637ac5aaa67cdbf4bfccc Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 05:46:49 +0000 Subject: [PATCH 138/516] Tighten the builder and optional-field reference pages Rewrites the bare "there is no X" constructions, idioms, and clefts the style guide rules out, shortens three titles to fit the length limit, and states why UpdateField's marker is not inferred: rustc does not solve the M::Map projection backwards. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/traits/builder/build_field.md | 20 +++++---- .../traits/builder/finalize_build.md | 28 ++++++------ docs/reference/traits/builder/has_builder.md | 41 +++++++++--------- docs/reference/traits/builder/into_builder.md | 20 ++++----- docs/reference/traits/builder/partial_data.md | 20 +++++---- docs/reference/traits/builder/take_field.md | 8 ++-- docs/reference/traits/builder/update_field.md | 19 ++++---- .../traits/optional/can_build_with_default.md | 43 ++++++++++--------- .../optional/can_finalize_with_default.md | 22 +++++----- .../traits/optional/finalize_optional.md | 14 +++--- .../traits/optional/has_optional_builder.md | 27 ++++++------ .../reference/traits/optional/set_optional.md | 33 +++++++------- docs/reference/traits/optional/to_optional.md | 26 +++++------ .../traits/optional/transform_map_default.md | 24 +++++------ .../traits/optional/transform_optional.md | 36 ++++++++-------- 15 files changed, 197 insertions(+), 184 deletions(-) diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index 9414da4e..fdff7758 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -36,22 +36,24 @@ pub trait BuildField { } ``` -`Tag` names the field. `Value` is the field's declared type, so `build_field` takes an ordinary value with -no marker wrapper. `Output` is the partial record with that one field's marker flipped from `IsNothing` to -`IsPresent`, a different type from `Self`. The blanket impl over [`UpdateField`](./update_field.md) that -supplies all of this is shown in [Under the hood](#under-the-hood). +`Tag` names the field. `Value` is the field's declared type, so `build_field` takes an ordinary +value without a marker wrapper. `Output` is the partial record with that one field's marker flipped +from `IsNothing` to `IsPresent`, a different type from `Self`. The blanket impl over +[`UpdateField`](./update_field.md) that supplies all of this is shown in [Under the +hood](#under-the-hood). ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -The `PhantomData` argument names the field, the same way a [`HasField`](../field-access/has_field.md) read does: -`PhantomData::` for a named field, `PhantomData::>` for a tuple-struct -position. `Value` is the field's declared type, so what you pass is an ordinary value with no wrapper. +The `PhantomData` argument names the field, the same way a +[`HasField`](../field-access/has_field.md) read does: `PhantomData::` for a +named field, `PhantomData::>` for a tuple-struct position. `Value` is the field's declared +type, so what you pass is an ordinary value without a wrapper. **Nothing implements it directly.** It is a library blanket impl over -[`UpdateField`](./update_field.md), so every field the derive generates an `UpdateField` impl for gains -`build_field` for free. +[`UpdateField`](./update_field.md), so every field the derive generates an `UpdateField` impl for +gains `build_field` without an impl of its own. ## Examples diff --git a/docs/reference/traits/builder/finalize_build.md b/docs/reference/traits/builder/finalize_build.md index 45e76be5..8bcee269 100644 --- a/docs/reference/traits/builder/finalize_build.md +++ b/docs/reference/traits/builder/finalize_build.md @@ -40,19 +40,19 @@ pub trait FinalizeBuild: PartialData { } ``` -`finalize_build` takes `self` by value, so it consumes the partial record, and returns `Self::Target`, the -concrete struct being built. `Target` is not declared here: it comes from the supertrait -[`PartialData`](./partial_data.md), which every configuration of a partial record implements, so the -destination is nameable at any point in a build. What `FinalizeBuild` adds is the method, and its impl -exists for only one configuration (every field `IsPresent`), which is the safety argument the rest of -this page works out. +`finalize_build` takes `self` by value, so it consumes the partial record, and returns +`Self::Target`, the concrete struct being built. `Target` is not declared here: it comes from the +supertrait [`PartialData`](./partial_data.md), which every configuration of a partial record +implements, so the destination is nameable at any point in a build. `FinalizeBuild` adds the method, +and its impl exists for only one configuration (every field `IsPresent`), which is the safety +argument the rest of this page works out. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -`finalize_build` consumes the partial value and returns `Self::Target`. It takes no arguments. There is -nothing left to decide by the time it applies. +`finalize_build` consumes the partial value and returns `Self::Target`. It takes only `self`: +nothing is left to decide by the time it applies. Bounding on it is how generic builder code says it will produce a finished value, as the `assemble` function in the [example](#examples) does with `FinalizeBuild`. @@ -98,7 +98,7 @@ pub fn demo() { ``` `assemble` names only `FinalizeBuild`, yet it can bind `Target`, because the projection comes from -the supertrait [`PartialData`](./partial_data.md). `Empty` has no markers to fill, so its builder is +the supertrait [`PartialData`](./partial_data.md). `Empty` lacks markers to fill, so its builder is already at the one configuration the impl covers. ## When to use it @@ -137,8 +137,8 @@ impl FinalizeBuild for __PartialPerson { So a partial value always knows its destination and only sometimes has a way to reach it. Because `IsPresent::Map` is `T`, the body is a field-by-field move with nothing to unwrap. **This is why the error for an incomplete build is a missing method rather than a missing field**: method -resolution looks for `finalize_build` on `__PartialPerson`, finds no impl, and -reports that, so the marker list in the type is the diagnostic. +resolution looks for `finalize_build` on `__PartialPerson`, does not find an +impl, and reports that, so the marker list in the type is the diagnostic. The optional layer reaches this same impl rather than replacing it: [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) runs a @@ -171,11 +171,11 @@ The field whose marker is still `IsNothing` is the one missing. **It supertraits [`PartialData`](./partial_data.md)**, so naming both in a bound is redundant, and `Target` is projected from the supertrait. -**There is no fallible variant here.** Reporting absence at run time is +**It lacks a fallible variant.** Reporting absence at run time is [`FinalizeOptional`](../optional/finalize_optional.md), a different trait in a different crate. -**A fieldless struct finalizes immediately.** Its companion has no markers, so `builder().finalize_build()` -compiles, which is legal and useless. +**A fieldless struct finalizes immediately.** Its companion lacks markers, so +`builder().finalize_build()` compiles, which is legal and useless. **The enum side has its own ending.** [`FinalizeExtract`](../variant/finalize_extract.md) discharges an exhausted extractor, and it is sound for the opposite reason: the value cannot exist, rather than being complete. diff --git a/docs/reference/traits/builder/has_builder.md b/docs/reference/traits/builder/has_builder.md index 5c418a16..8487ffcf 100644 --- a/docs/reference/traits/builder/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -42,17 +42,17 @@ pub trait HasBuilder { } ``` -`Self` is the concrete record being built. `Builder` is the *partial companion type* the derive generates -for it, the record carrying one [`MapType`](../type-level/map_type.md) presence marker per field. -`builder()` is an associated function, so it takes no receiver, and it returns that companion at its -all-absent configuration, ready to fill. +`Self` is the concrete record being built. `Builder` is the *partial companion type* the derive +generates for it, the record carrying one [`MapType`](../type-level/map_type.md) presence marker per +field. `builder()` is an associated function, so it does not take a receiver, and it returns that +companion at its all-absent configuration, ready to fill. ## Usage **It is in the prelude**, so `use cgp::prelude::*;` is enough. -`builder()` is called with no receiver, as `Person::builder()` or `T::builder()` in generic code. You -rarely name the `Builder` type yourself, but it appears in an error when a build is incomplete. +`builder()` is called without a receiver, as `Person::builder()` or `T::builder()` in generic code. +You rarely name the `Builder` type yourself, but it appears in an error when a build is incomplete. The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), also available through [`#[derive(CgpRecord)]`](../../derives/derive_cgp_record.md) and @@ -112,7 +112,7 @@ pub fn demo() { ``` Every step changes the partial *type*, and `finalize_build` type-checks only because every marker -has reached present; moving it before the `baz` step is a compile error. A set field can be read +has reached `IsPresent`; moving it before the `baz` step is a compile error. A set field can be read back mid-build because the derive emits a [`HasField`](../field-access/has_field.md) impl on the partial type for each field once it is present. @@ -130,11 +130,12 @@ record being built, which is the extensible builder pattern, and the reason the completeness, reads better, and generates nothing. This family buys *decoupling*, and with nothing to decouple it is pure cost. -Two boundaries are worth stating plainly. This is **not a conventional builder**: it tracks presence and -nothing else, with no defaults, no validation at finalize, and no optional field unless the field's own -type is optional. The [optional-field extensions](../optional/has_optional_builder.md) cover the defaulted and optional -cases, and a hand-written builder remains better when the *logic* is the point. And the enum counterparts -are a different family: [`ExtractField`](../variant/extract_field.md) for taking a value apart and +Two boundaries are worth stating plainly. This is **not a conventional builder**: it tracks presence +and nothing else, without defaults, validation at finalize, or optional fields unless the field's +own type is optional. The [optional-field extensions](../optional/has_optional_builder.md) cover the +defaulted and optional cases, and a hand-written builder remains better when the *logic* is the +point. And the enum counterparts are a different family: +[`ExtractField`](../variant/extract_field.md) for taking a value apart and [`FromVariant`](../variant/from_variant.md) for constructing one. ## Under the hood @@ -178,7 +179,7 @@ impl FinalizeBuild for __PartialPerson { ``` That pair is the whole safety argument. `builder()` starts at all-absent, each -[`build_field`](./build_field.md) flips one marker, and there is no check to run at the end: the +[`build_field`](./build_field.md) flips one marker, and nothing is checked at the end: the impl is absent for an incomplete value. Everything between the two ends reduces to one primitive, [`UpdateField`](./update_field.md), which is what the derive writes per field; [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are library blanket impls over @@ -238,18 +239,18 @@ error[E0277]: the trait bound `FooBar: HasFields` is not satisfied The [example](#examples) derives both on its `FooBar`. **The partial type cannot be printed or cloned.** The derive drops the original's struct-level -attributes, so no `Debug`, no `Clone`, whatever the record derives. Read a set field through the -partial type's [`HasField`](../field-access/has_field.md) impl instead. Field-level attributes, by -contrast, are copied onto the partial type, so a field helper attribute such as -`#[serde(rename = "...")]` breaks the build; see +attributes, so it lacks `Debug`, `Clone`, and every other derive the record carries. Read a set +field through the partial type's [`HasField`](../field-access/has_field.md) impl instead. +Field-level attributes, by contrast, are copied onto the partial type, so a field helper attribute +such as `#[serde(rename = "...")]` breaks the build; see [`#[derive(BuildField)]`](../../derives/derive_build_field.md#common-mistakes). -**There are no defaults and no validation.** Presence is all that is tracked. A field with a sensible +**It neither defaults nor validates.** Presence is all that is tracked. A field with a sensible default still has to be set, unless you reach for the [optional-field extensions](../optional/can_finalize_with_default.md). -**`builder()` is an associated function.** There is no receiver, so it is `Person::builder()` rather than -anything called on a value. Starting from a value is [`IntoBuilder`](./into_builder.md). +**`builder()` is an associated function.** It does not take a receiver, so it is `Person::builder()` +rather than anything called on a value. Starting from a value is [`IntoBuilder`](./into_builder.md). **A fieldless struct's builder is immediately finalizable**, since there is nothing to track. `Empty::builder().finalize_build()` compiles for a `struct Empty {}`, which is legal and useless. diff --git a/docs/reference/traits/builder/into_builder.md b/docs/reference/traits/builder/into_builder.md index 60cbc29b..6616f6c8 100644 --- a/docs/reference/traits/builder/into_builder.md +++ b/docs/reference/traits/builder/into_builder.md @@ -52,7 +52,7 @@ The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.m ## Examples -Swapping one field of a complete record, the shape redistributing code has: +Swapping one field of a complete record, the usual form of a redistribution: ```rust use cgp::prelude::*; @@ -92,8 +92,7 @@ pub fn demo() { `into_builder` starts with every field present, [`take_field`](./take_field.md) removes `last_name`, and [`build_field`](./build_field.md) puts a new one in its place. A value straight out of -`into_builder` is already finalizable, so the round trip earns its keep only from what happens in -between. +`into_builder` is already finalizable, so the round trip is useful only for what happens in between. ## When to use it @@ -104,10 +103,11 @@ entry points and the one that shows up in generic code more than in application common case and the one the extensible builder pattern is about. - **Use `IntoBuilder`** when a complete value must be decomposed: to swap one field, or to hand its fields to several destinations, including the builder of a different record. -- **Use [`ToFields`](../shape/to_fields.md)** instead when what you want is the value's *shape* as a flat list - rather than a partial type you can fill. A partial value tracks presence; a `Fields` product does not. +- **Use [`ToFields`](../shape/to_fields.md)** instead when you want the value's *shape* as a flat + list rather than a partial type you can fill. A partial value tracks presence; a `Fields` product + does not. - **Prefer a struct update expression** in concrete code. `Person { first_name, ..person }` does the - common case with no machinery, and this family is for code that cannot name the type. + common case without this machinery, and this family is for code that cannot name the type. ## Under the hood @@ -142,11 +142,11 @@ so it satisfies [`FinalizeBuild`](./finalize_build.md) immediately and ## Common Mistakes -**It consumes the value.** There is no borrowing form; use [`ToFieldsRef`](../shape/to_fields_ref.md) if the -original must survive, bearing in mind that gives you a shape rather than a builder. +**It consumes the value.** It lacks a borrowing form; use [`ToFieldsRef`](../shape/to_fields_ref.md) +if the original must survive, bearing in mind that gives you a shape rather than a builder. -**The result is already finalizable.** Calling `into_builder().finalize_build()` is the identity, which -is legal and pointless. The trait earns its keep only if something happens in between. +**The result is already finalizable.** Calling `into_builder().finalize_build()` is the identity, +which is legal and pointless. The trait is useful only when something happens in between. **The partial type cannot be printed or cloned.** The derive drops the original's struct-level attributes, so a value mid-redistribution has none of the record's own derives. diff --git a/docs/reference/traits/builder/partial_data.md b/docs/reference/traits/builder/partial_data.md index ea494d8e..087471a8 100644 --- a/docs/reference/traits/builder/partial_data.md +++ b/docs/reference/traits/builder/partial_data.md @@ -15,9 +15,10 @@ Naming the concrete type a partial value is on its way to becoming. **You are not expected to implement `PartialData`.** [`#[derive(BuildField)]`](../../derives/derive_build_field.md) and -[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) emit it for every companion type they -generate. What you meet is the projection `Self::Target` in another trait's signature; this page explains -where that projection comes from. The one case for bounding on it is generic code that needs the destination type before the value is complete. +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) emit it for every companion type +they generate. You meet the projection `Self::Target` in another trait's signature; this page +explains where that projection comes from. The one case for bounding on it is generic code that +needs the destination type before the value is complete. ::: @@ -43,11 +44,12 @@ pub trait PartialData { } ``` -`Self` is a partial companion type, a record builder or an extraction remainder. `Target` is the concrete -struct or enum it belongs to. There is no method, because naming a type is not an operation; the trait -exists so that generic code can project `Self::Target` while holding a value of unknown completeness. -[`FinalizeBuild`](./finalize_build.md) and [`FinalizeOptional`](../optional/finalize_optional.md) both -read the destination through this projection rather than declaring one of their own. +`Self` is a partial companion type, a record builder or an extraction remainder. `Target` is the +concrete struct or enum it belongs to. It lacks a method, because naming a type is not an operation; +the trait exists so that generic code can project `Self::Target` while holding a value of unknown +completeness. [`FinalizeBuild`](./finalize_build.md) and +[`FinalizeOptional`](../optional/finalize_optional.md) both read the destination through this +projection rather than declaring one of their own. ## Usage @@ -137,7 +139,7 @@ builder, which is occasionally what you want and occasionally too permissive. **`Target` is the original type, not the partial one.** Reading the projection the other way round is the usual confusion when meeting it in an error. -**It has no method.** Getting a value of `Target` is a finalize; this only names the type. +**It lacks a method.** Getting a value of `Target` is a finalize; this only names the type. ## Related constructs diff --git a/docs/reference/traits/builder/take_field.md b/docs/reference/traits/builder/take_field.md index 7eac0712..dfe38479 100644 --- a/docs/reference/traits/builder/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -56,8 +56,8 @@ The `PhantomData` argument names the field, and the method returns a tuple: remainder second.** **Nothing implements it directly.** It is a library blanket impl over -[`UpdateField`](./update_field.md), so every field the derive generates an `UpdateField` impl for gains -`take_field` for free. +[`UpdateField`](./update_field.md), so every field the derive generates an `UpdateField` impl for +gains `take_field` without an impl of its own. ## Examples @@ -111,8 +111,8 @@ merging one record into another, already uses it for you. - **Use [`BuildField`](./build_field.md)** for the opposite direction. - **Use [`ToFields`](../shape/to_fields.md)** when the whole value should become a flat shape rather than a partial record with one field missing. -- **Prefer ordinary destructuring** in concrete code. `let Person { first_name, .. } = person;` needs no - machinery, and this family is for code that cannot name the type. +- **Prefer ordinary destructuring** in concrete code. `let Person { first_name, .. } = person;` + needs none of this machinery, and this family is for code that cannot name the type. ## Under the hood diff --git a/docs/reference/traits/builder/update_field.md b/docs/reference/traits/builder/update_field.md index 7ac6158e..9b18f3a0 100644 --- a/docs/reference/traits/builder/update_field.md +++ b/docs/reference/traits/builder/update_field.md @@ -13,10 +13,10 @@ The primitive that moves one field of a [partial record](/docs/reference/glossar ### Generated machinery -**You are not expected to call `update_field` directly.** It is the per-field -primitive [`#[derive(BuildField)]`](../../derives/derive_build_field.md) emits, and -[`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are the two directions you actually -call. This page explains the primitive, because it is what makes build order free and what the +**You are not expected to call `update_field` directly.** It is the per-field primitive +[`#[derive(BuildField)]`](../../derives/derive_build_field.md) emits, and +[`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are the two directions you +actually call. This page explains the primitive, because it makes build order free and is what the optional-field layer reaches for when neither direction fits. ::: @@ -64,10 +64,10 @@ directions. **It is in the prelude**, so `use cgp::prelude::*;` is enough. -The `M` parameter is the target marker, and **it is not inferred from the value you pass**: a -`String` could be the storage of `IsPresent` or of any other marker that maps to it, so a direct -call names the trait with the marker, as -`UpdateField::::update_field(builder, PhantomData, value)`. +The `M` parameter is the target marker, and **it is not inferred from the value you pass**. The +argument's type is the projection `M::Map`, and rustc does not solve a projection +backwards, so a `String` argument leaves `M` unknown. A direct call names the trait with the marker, +as `UpdateField::::update_field(builder, PhantomData, value)`. [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) pin the marker for you, which is one reason to call them instead. @@ -197,7 +197,8 @@ error[E0284]: type annotations needed for `((), __PartialPerson<_, IsNothing>)` = note: cannot satisfy `<_ as MapType>::Map == String` ``` -**A field not declared on the record has no impl.** Setting an `age` that `Person` does not declare: +**A field not declared on the record lacks an impl.** Setting an `age` that `Person` does not +declare: ```rust let _ = Person::builder().build_field(PhantomData::, 42_u8); diff --git a/docs/reference/traits/optional/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md index 615b9830..6b59a8c4 100644 --- a/docs/reference/traits/optional/can_build_with_default.md +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -16,12 +16,12 @@ start a builder, copy the shared fields, default the rest. `CanBuildWithDefault` call. `Self` is the target record and `Source` the narrower one. **It is the field-level counterpart of an -[upcast](../casting/can_upcast.md)**: turning a `Point2d` into a `Point3d` whose extra `z` is `0`, naming no field -explicitly. +[upcast](../casting/can_upcast.md)**: turning a `Point2d` into a `Point3d` whose extra `z` is `0`, +without naming a field explicitly. -It chains [`builder()`](../builder/has_builder.md), [`build_from`](../casting/can_build_from.md), and -[`finalize_with_default`](./can_finalize_with_default.md), and it is worth reaching for precisely because -those three lines together read as plumbing. +It chains [`builder()`](../builder/has_builder.md), [`build_from`](../casting/can_build_from.md), +and [`finalize_with_default`](./can_finalize_with_default.md), and it is worth reaching for because +those three lines, written out, say only that one record is widened into another. ## Definition @@ -33,13 +33,13 @@ pub trait CanBuildWithDefault { } ``` -`Source` is the narrower record and `Self` is the target. `build_with_default` is an associated function -with no receiver, and it returns a fully built `Self`. The trait declares no associated type and no -[supertrait](/docs/reference/glossary#supertrait); it is a blanket impl chaining a builder, a merge, and a defaulted finalize, shown in -[*Under the hood*](#under-the-hood). Two requirements follow from that chain: the source needs -[`HasFields`](../shape/has_fields.md), because the merge walks its field list, and every field the source -does not supply needs `Default`, because the finalize fills it. It is not in the prelude; import it from -`cgp-field-extra`. +`Source` is the narrower record and `Self` is the target. `build_with_default` is an associated +function without a receiver, and it returns a fully built `Self`. The trait declares neither an +associated type nor a [supertrait](/docs/reference/glossary#supertrait); it is a blanket impl +chaining a builder, a merge, and a defaulted finalize, shown in [*Under the hood*](#under-the-hood). +Two requirements follow from that chain: the source needs [`HasFields`](../shape/has_fields.md), +because the merge walks its field list, and every field the source does not supply needs `Default`, +because the finalize fills it. It is not in the prelude; import it from `cgp-field-extra`. ## Usage @@ -53,7 +53,7 @@ It is an **associated function**, called on the target: `Point3d::build_with_def ## Examples -Widening a record with no field named anywhere, in one call and as the three calls it stands for: +Widening a record without naming a field, in one call and as the three calls it stands for: ```rust use cgp::prelude::*; @@ -92,9 +92,10 @@ filled because `u64: Default`. **Reach for it for a one-call widening from a narrower record**, and reach for the pieces when anything in between needs to happen. -- **[`CanBuildFrom`](../casting/can_build_from.md) plus an explicit finalize** when some fields must be set by - hand as well as copied. This trait offers no place to insert a `build_field`. -- **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when there is no source to merge from. +- **[`CanBuildFrom`](../casting/can_build_from.md) plus an explicit finalize** when some fields must + be set by hand as well as copied. This trait cannot insert a `build_field` between its steps. +- **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when the fields do not come from a + source record. - **[`CanUpcast`](../casting/can_upcast.md)** for the enum analogue: widening a variant set rather than a field set. - **A plain `From` impl** when both types are yours and the conversion is one you would write once. A @@ -134,11 +135,11 @@ receiver, rustc follows the chain to the root cause and prints each layer as a ` **It is not in the prelude.** Import from `cgp::extra::field::impls`. **The source needs [`HasFields`](../shape/has_fields.md), not only a builder.** Deriving only -[`BuildField`](../../derives/derive_build_field.md) on both looks symmetric and fails, the same trap -[`CanBuildFrom`](../casting/can_build_from.md) carries. +[`BuildField`](../../derives/derive_build_field.md) on both looks symmetric and fails, the same +mistake [`CanBuildFrom`](../casting/can_build_from.md) carries. **Every field the source does not supply needs `Default`.** Building a `Server` from a `Host` that -lacks its `port`, where `Port` has no `Default`: +lacks its `port`, where `Port` lacks `Default`: ```rust pub struct Port(pub u16); @@ -173,7 +174,7 @@ The later notes climb the chain from there, through `TransformMapFields` and **It is an associated function on the target.** `Point3d::build_with_default(source)`, not a method on the source. -**There is no place to set a field explicitly.** If one field needs a real value, use the three-call form. +**It cannot set a field explicitly.** If one field needs a real value, use the three-call form. **A source field the target lacks is an error, not dropped.** The merge walks the *source's* fields and builds each into the target, so a `label` that `Point3d` does not declare: @@ -193,7 +194,7 @@ let _ = Point3d::build_with_default(LabeledPoint2d { }); ``` -has no slot to go into: +lacks a slot to go into: ```text error[E0277]: the trait bound `__PartialPoint3d: UpdateField>>>>>, IsPresent>` is not satisfied diff --git a/docs/reference/traits/optional/can_finalize_with_default.md b/docs/reference/traits/optional/can_finalize_with_default.md index ed545f4d..f03d0105 100644 --- a/docs/reference/traits/optional/can_finalize_with_default.md +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -1,5 +1,5 @@ --- -title: 'CanFinalizeWithDefault — fill gaps, then build' +title: 'CanFinalizeWithDefault — finish with defaults' sidebar_label: 'CanFinalizeWithDefault' sidebar_position: 5 description: 'End a build by filling every unset field from Default, for an optional builder or a core one, then finalizing through the strict impl.' @@ -40,13 +40,14 @@ pub trait CanFinalizeWithDefault { } ``` -`Self` is any partial builder whose fields can be re-marked to all-present, which covers a core builder -from [`builder()`](../builder/has_builder.md) as well as an optional one from +`Self` is any partial builder whose fields can be re-marked to all-present, which covers a core +builder from [`builder()`](../builder/has_builder.md) as well as an optional one from [`optional_builder()`](./has_optional_builder.md). `Output` is the concrete struct being built. -`finalize_with_default` takes `self`, consuming the builder, and returns that struct with every unset -field filled from `Default`. The trait has no [supertrait](/docs/reference/glossary#supertrait); it is a blanket impl over the -transform-then-finalize shown in [*Under the hood*](#under-the-hood). It is not in the prelude; import it -from `cgp-field-extra`. +`finalize_with_default` takes `self`, consuming the builder, and returns that struct with every +unset field filled from `Default`. The trait does not declare a +[supertrait](/docs/reference/glossary#supertrait); it is a blanket impl over the +transform-then-finalize shown in [*Under the hood*](#under-the-hood). It is not in the prelude; +import it from `cgp-field-extra`. ## Usage @@ -144,8 +145,8 @@ configuration its single impl requires, so the strict check runs, and cannot fai **It is not in the prelude.** Import from `cgp::extra::field::impls`. -**A field whose type has no `Default` is reported without being named.** On a core builder with -`port` left unset, where `Port` has no `Default`: +**A field whose type lacks `Default` is reported without being named.** On a core builder with +`port` left unset, where `Port` lacks `Default`: ```rust pub struct Port(pub u16); @@ -187,7 +188,8 @@ let _ = Server::optional_builder() fails the same way, on `__PartialServer`, because a set field is still `IsOptional` and its conversion requires `Default`. A core builder with both fields set finalizes -this way regardless, and [`finalize_optional`](./finalize_optional.md) needs no `Default` at all. +this way regardless, and [`finalize_optional`](./finalize_optional.md) does not need `Default` at +all. **A defaulted field is silent.** Nothing distinguishes "set to zero" from "left unset" in the result, which is the trade against [`FinalizeOptional`](./finalize_optional.md). diff --git a/docs/reference/traits/optional/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md index 0182ef31..679aef3d 100644 --- a/docs/reference/traits/optional/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -35,12 +35,12 @@ pub trait FinalizeOptional: PartialData { } ``` -The `PartialData` [supertrait](/docs/reference/glossary#supertrait) supplies `Target`, the concrete struct being built, so the method projects -its return type through it and declares no associated type of its own. `finalize_optional` takes `self`, -consuming the builder, and returns `Result`: the built struct on success, -or, on failure, a missing field's own name, recovered from its type-level tag as a -`&'static str` with no allocation. The trait carries no other parameter. It is not in the prelude; import it from -`cgp-field-extra`. +The `PartialData` [supertrait](/docs/reference/glossary#supertrait) supplies `Target`, the concrete +struct being built, so the method projects its return type through it and does not declare an +associated type of its own. `finalize_optional` takes `self`, consuming the builder, and returns +`Result`: the built struct on success, or, on failure, a missing field's +own name, recovered from its type-level tag as a `&'static str` without allocating. The trait is not +generic. It is not in the prelude; import it from `cgp-field-extra`. ## Usage @@ -97,7 +97,7 @@ stops at the first `None` it meets. ## When to use it -**Reach for it when absence is an error you want to *report* rather than paper over.** +**Reach for it when absence is an error you want to *report* rather than hide.** - **[`CanFinalizeWithDefault`](./can_finalize_with_default.md)** when unset fields have meaningful defaults and silence is the right outcome. The two are the same builder finalized differently, so the diff --git a/docs/reference/traits/optional/has_optional_builder.md b/docs/reference/traits/optional/has_optional_builder.md index d0892088..717ac967 100644 --- a/docs/reference/traits/optional/has_optional_builder.md +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -38,12 +38,13 @@ pub trait HasOptionalBuilder { } ``` -`Builder` names the partial companion type the derive generated, with every field marked `IsOptional`. -It is the same companion the core builder produces, at a configuration the core builder never starts -from. `optional_builder` is an associated function with no receiver, so a caller writes -`Context::optional_builder()`. The trait carries no [supertrait](/docs/reference/glossary#supertrait), and it is implemented as a blanket impl -over the core builder machinery, so any record that derives the builder gains it. It is not in the -prelude; the whole optional-field layer lives in `cgp-field-extra`. +`Builder` names the partial companion type the derive generated, with every field marked +`IsOptional`. It is the same companion the core builder produces, at a configuration the core +builder never starts from. `optional_builder` is an associated function without a receiver, so a +caller writes `Context::optional_builder()`. The trait does not declare a +[supertrait](/docs/reference/glossary#supertrait), and it is implemented as a blanket impl over the +core builder machinery, so any record that derives the builder gains it. It is not in the prelude; +the whole optional-field layer lives in `cgp-field-extra`. ## Usage @@ -56,7 +57,7 @@ use cgp::extra::field::impls::HasOptionalBuilder; The impls are blanket ones over the core builder machinery, so any record deriving [`#[derive(BuildField)]`](../../derives/derive_build_field.md) (or -[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md)) gets this for free. There is no separate derive. +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md)) gets this with nothing more to derive. **Two endings are available**, and picking between them at the call site is the layer's real payoff: [`FinalizeOptional`](./finalize_optional.md) requires every field and reports a missing one, while @@ -104,9 +105,9 @@ pub fn demo() { } ``` -The fields are set in reverse declaration order, which the core builder also allows; what it does -not allow is ending an incomplete build any way but a compile error. Here the same unfinished -builder either fills `bar` with `0` or reports it by name, chosen at the finalize call. +The fields are set in reverse declaration order, which the core builder also allows. The core +builder rejects an incomplete build at compile time, while here the same unfinished builder either +fills `bar` with `0` or reports it by name, as the finalize call chooses. ## When to use it @@ -148,11 +149,11 @@ So `optional_builder()` starts at the all-`IsNothing` configuration and re-marks `__PartialContext`, the same partial companion the core builder uses, at a configuration the core builder never reaches on its own. -Nothing about the companion type is special to this layer. What changes is the marker, and with it which +Nothing about the companion type is special to this layer. The marker changes, and with it which operations apply: [`SetOptional`](./set_optional.md) resolves where [`BuildField`](../builder/build_field.md) does not, and the strict -[`FinalizeBuild`](../builder/finalize_build.md) does not resolve at all until a finalize has re-marked the fields -back to `IsPresent`. +[`FinalizeBuild`](../builder/finalize_build.md) does not resolve at all until a finalize has +re-marked the fields back to `IsPresent`. ## Common Mistakes diff --git a/docs/reference/traits/optional/set_optional.md b/docs/reference/traits/optional/set_optional.md index 26a1a147..725c435d 100644 --- a/docs/reference/traits/optional/set_optional.md +++ b/docs/reference/traits/optional/set_optional.md @@ -1,5 +1,5 @@ --- -title: 'SetOptional — set a field of an optional builder' +title: 'SetOptional — set an optional builder field' sidebar_label: 'SetOptional' sidebar_position: 3 description: 'Set one field of an all-optional builder, as many times as you like, optionally getting back the value it replaced.' @@ -35,13 +35,14 @@ pub trait SetOptional { ``` `Tag` is the field's type-level name, a [`Symbol!`](../../macros/symbol.md) for a named field or an -[`Index`](../../types/index_type.md) for a tuple field, passed at the call site as a `PhantomData` -argument. `Value` is the field's declared type, so a caller passes an ordinary value rather than an -`Option`. Both methods take `self` and return `Self`: the field's marker stays `IsOptional` before and -after, so the builder's type does not change and an optional field can be set repeatedly. The two -methods differ only in what they do with whatever was already there. `set` discards it; `set_optional` -returns it as an `Option` alongside the rebuilt builder. The trait has no [supertrait](/docs/reference/glossary#supertrait). It is -not in the prelude; import it from `cgp-field-extra`. +[`Index`](../../types/index_type.md) for a tuple field, passed at the call site as a +`PhantomData` argument. `Value` is the field's declared type, so a caller passes an ordinary +value rather than an `Option`. Both methods take `self` and return `Self`: the field's marker stays +`IsOptional` before and after, so the builder's type does not change and an optional field can be +set repeatedly. The two methods differ only in what they do with whatever was already there. `set` +discards it; `set_optional` returns it as an `Option` alongside the rebuilt builder. +The trait does not declare a [supertrait](/docs/reference/glossary#supertrait). It is not in the +prelude; import it from `cgp-field-extra`. ## Usage @@ -51,10 +52,10 @@ not in the prelude; import it from `cgp-field-extra`. use cgp::extra::field::impls::SetOptional; ``` -`Self` must be an optional builder, one from -[`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md). Calling it on a -core builder does not resolve, because the field's marker is `IsNothing` rather than `IsOptional`. There -is no "unset" operation: a field starts absent and stays so unless it is set. +`Self` must be an optional builder, one from [`optional_builder()`](./has_optional_builder.md) or +[`to_optional()`](./to_optional.md). Calling it on a core builder does not resolve, because the +field's marker is `IsNothing` rather than `IsOptional`. The trait lacks an "unset" operation: a +field starts absent and stays so unless it is set. ## Examples @@ -129,7 +130,7 @@ where `Mapper = IsOptional` requires the field to already be in the optional state, and `Output = Context` pins the result to the same type on both sides. **That pinning allows repeated sets:** -there is no marker to consume, so no impl becomes unavailable after the first call. +the call does not consume a marker, so every impl that applied before it still applies after it. Contrast [`BuildField`](../builder/build_field.md#under-the-hood), which pins `Mapper = IsNothing` and a target of `IsPresent`: its `Output` is a *different* type, which makes a second call fail to resolve. @@ -161,14 +162,14 @@ The field must already be `IsOptional`, so start with [`optional_builder()`](./has_optional_builder.md) or convert with [`to_optional()`](./to_optional.md). -**The builder's type never changes, so it carries no record of what you have set.** That is deliberate: +**The builder's type never changes, so it does not record what you have set.** That is deliberate: it allows re-setting, and it is why finalizing has to check at run time. **`set_optional` returns `(previous, builder)`, in that order.** Reversing the binding is a type error, and a confusing one in generic code. -**The argument is a `Value`, not an `Option`.** There is no "unset" operation; a field left alone -stays absent. +**The argument is a `Value`, not an `Option`.** The trait lacks an "unset" operation; a field +left alone stays absent. **A field whose type is already `Option` takes an `Option` here and is stored as `Option>`.** The outer layer is the builder's presence tracking, and the two are easy to diff --git a/docs/reference/traits/optional/to_optional.md b/docs/reference/traits/optional/to_optional.md index 1c29ab6d..80bdb613 100644 --- a/docs/reference/traits/optional/to_optional.md +++ b/docs/reference/traits/optional/to_optional.md @@ -35,12 +35,12 @@ pub trait ToOptional { } ``` -`Self` is any partial builder, and `Output` is the same partial companion type with every marker set to -`IsOptional`. `to_optional` takes `self`, consuming the builder and returning the re-marked one. The -trait has no [supertrait](/docs/reference/glossary#supertrait); it is a blanket impl over -[`TransformMapFields`](../type-level/transform_map_fields.md), so any partial value whose fields can be -re-marked gains it, with nothing to implement by hand. It is not in the prelude; the optional-field -layer lives in `cgp-field-extra`. +`Self` is any partial builder, and `Output` is the same partial companion type with every marker set +to `IsOptional`. `to_optional` takes `self`, consuming the builder and returning the re-marked one. +The trait does not declare a [supertrait](/docs/reference/glossary#supertrait); it is a blanket impl +over [`TransformMapFields`](../type-level/transform_map_fields.md), so any partial value whose +fields can be re-marked gains it, with nothing to implement by hand. It is not in the prelude; the +optional-field layer lives in `cgp-field-extra`. ## Usage @@ -126,9 +126,9 @@ where That walk visits each field of the target's [`HasFields`](../shape/has_fields.md) shape, uses [`UpdateField`](../builder/update_field.md) to take the field out and learn its current marker, applies the transform, and writes it back under `IsOptional`. The transform's impls decide the -value: `IsPresent` becomes `Some(value)` and `IsNothing` becomes `None`. **There is no impl from -`IsOptional`**, so a builder that is already optional cannot be converted again, as [Common -Mistakes](#common-mistakes) shows. +value: `IsPresent` becomes `Some(value)` and `IsNothing` becomes `None`. **`TransformOptional` lacks +an impl from `IsOptional`**, so a builder that is already optional cannot be converted again, as +[Common Mistakes](#common-mistakes) shows. Its mirror image is [`CanFinalizeWithDefault`](./can_finalize_with_default.md), which runs the same walk with [`TransformMapDefault`](./transform_map_default.md) toward `IsPresent`. **Both operations are the @@ -154,8 +154,8 @@ here a missing field is an `Err` or a default rather than a compile error. let _ = Context::optional_builder().to_optional(); ``` -finds no [`TransformOptional`](./transform_optional.md) conversion from `IsOptional`, and fails -with: +does not find a [`TransformOptional`](./transform_optional.md) conversion from `IsOptional`, and +fails with: ```text error[E0599]: the method `to_optional` exists for struct `__PartialContext`, but its trait bounds were not satisfied @@ -164,8 +164,8 @@ error[E0599]: the method `to_optional` exists for struct `__PartialContext: TransformMapFields` ``` -**It is not reversible.** There is no `from_optional`; getting back to a strict configuration means -finalizing, through [`FinalizeOptional`](./finalize_optional.md) or +**It is not reversible.** `from_optional` does not exist; getting back to a strict configuration +means finalizing, through [`FinalizeOptional`](./finalize_optional.md) or [`CanFinalizeWithDefault`](./can_finalize_with_default.md). **A field whose type is already `Option` becomes `Option>`** in the slot. That is correct diff --git a/docs/reference/traits/optional/transform_map_default.md b/docs/reference/traits/optional/transform_map_default.md index 95d4d7de..d969db2e 100644 --- a/docs/reference/traits/optional/transform_map_default.md +++ b/docs/reference/traits/optional/transform_map_default.md @@ -1,5 +1,5 @@ --- -title: 'TransformMapDefault — make every field present' +title: 'TransformMapDefault — fill the unset fields' sidebar_label: 'TransformMapDefault' sidebar_position: 7 description: 'The transform marker behind the defaulting finalize: three per-field conversions that leave every field present, filling gaps from Default.' @@ -15,7 +15,7 @@ The transform marker that makes every field present, defaulting whatever is not. **You are not expected to name `TransformMapDefault` directly.** It is the marker [`CanFinalizeWithDefault`](./can_finalize_with_default.md) and -[`CanBuildWithDefault`](./can_build_with_default.md) drive, and calling one of those is what you write. +[`CanBuildWithDefault`](./can_build_with_default.md) drive, and you write a call to one of those. This page explains the three conversions behind them, which is also the model to copy if you write a transform of your own. @@ -29,7 +29,7 @@ record to `IsPresent` and then calling the ordinary [`finalize_build`](../builde **You name it only when extending the layer.** Using the defaulting workflow means calling [`finalize_with_default`](./can_finalize_with_default.md) or -[`build_with_default`](./can_build_with_default.md), with no marker in sight. +[`build_with_default`](./can_build_with_default.md), without naming the marker. ## Definition @@ -39,9 +39,9 @@ record to `IsPresent` and then calling the ordinary [`finalize_build`](../builde pub struct TransformMapDefault; ``` -It carries no data. It becomes a transform by implementing -[`TransformMap`](../type-level/transform_map.md) once for each state a field might currently be in, every -impl targeting `IsPresent`: +It stores nothing. It becomes a transform by implementing +[`TransformMap`](../type-level/transform_map.md) once for each state a field might currently be in, +every impl targeting `IsPresent`: | a field currently | becomes | |---|---| @@ -127,7 +127,7 @@ served by the two operations already built on it. ## Under the hood -The marker is zero-sized and carries no data. What it carries is three +The marker is zero-sized, so it stores nothing. What it carries is three [`TransformMap`](../type-level/transform_map.md) impls, distinguished by their source marker: ```rust @@ -152,9 +152,9 @@ impl TransformMap for TransformMapDefault Note that each argument type is the *source* marker's projection (`T`, then `()`, then `Option`), which keeps the three from overlapping. And note that only two carry the `T: Default` bound: a field -already present needs no default, which is why a fully-set *core* builder can be finalized this way -regardless of its field types. An optional builder cannot: its set fields are still `IsOptional`, so -the third impl, and its bound, applies to every field. +already present does not need a default, which is why a fully-set *core* builder can be finalized +this way regardless of its field types. An optional builder cannot: its set fields are still +`IsOptional`, so the third impl, and its bound, applies to every field. Three impls are needed rather than one because [`TransformMapFields`](../type-level/transform_map_fields.md#under-the-hood) resolves a conversion per field from @@ -173,8 +173,8 @@ optional one. Through a method call such as `finalize_with_default`, the error n **It always targets `IsPresent`.** It cannot be used to reach any other configuration; that is [`TransformOptional`](./transform_optional.md)'s job. -**It is a marker, not an operation.** There is no method to call and nothing to wire. It is named in a -bound. +**It is a marker, not an operation.** It lacks a method to call and needs nothing wired. It is named +in a bound. **A defaulted field is indistinguishable from one set to the default value** in the result, which is the trade against [`FinalizeOptional`](./finalize_optional.md). diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index 6adbc3a3..0402e584 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -13,10 +13,11 @@ The transform marker that makes every field optional. ### Generated machinery -**You are not expected to name `TransformOptional` directly.** It is the -marker [`ToOptional`](./to_optional.md) and [`HasOptionalBuilder`](./has_optional_builder.md) drive, and -calling one of those is what you write. This page explains the conversion behind them, and why it needs -less of a field's type than its defaulting counterpart does. The one case for naming it is writing an operation of your own that drives the optional conversion. +**You are not expected to name `TransformOptional` directly.** It is the marker +[`ToOptional`](./to_optional.md) and [`HasOptionalBuilder`](./has_optional_builder.md) drive, and +you write a call to one of those. This page explains the conversion behind them, and why it needs +less of a field's type than its defaulting counterpart does. The one case for naming it is writing +an operation of your own that drives the optional conversion. ::: @@ -31,8 +32,8 @@ conversions that make that possible. workflows behave so alike. **You name it only when extending the layer.** Using the optional workflow means calling -[`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md), with no marker -in sight. +[`optional_builder()`](./has_optional_builder.md) or [`to_optional()`](./to_optional.md), without +naming the marker. ## Definition @@ -42,7 +43,7 @@ in sight. pub struct TransformOptional; ``` -It carries no data. It becomes a transform by implementing +It stores nothing. It becomes a transform by implementing [`TransformMap`](../type-level/transform_map.md) once for each state a core builder's field can be in, both impls targeting `IsOptional`: @@ -51,11 +52,11 @@ in, both impls targeting `IsOptional`: | `IsPresent` | `Some(value)` | | `IsNothing` | `None` | -Because both impls target `IsOptional`, applying the marker across a record leaves every field optional, -the configuration [`SetOptional`](./set_optional.md) requires. Unlike its defaulting counterpart it needs -nothing of the field types, since wrapping a value in `Some` and producing `None` require no `Default`. -The impl bodies are in [*Under the hood*](#under-the-hood). The marker is not in the prelude; import it -from `cgp-field-extra`. +Because both impls target `IsOptional`, applying the marker across a record leaves every field +optional, the configuration [`SetOptional`](./set_optional.md) requires. Unlike its defaulting +counterpart it needs nothing of the field types, since wrapping a value in `Some` and producing +`None` do not require `Default`. The impl bodies are in [*Under the hood*](#under-the-hood). The +marker is not in the prelude; import it from `cgp-field-extra`. ## Usage @@ -74,8 +75,8 @@ Builder: TransformMapFields ``` Unlike its defaulting counterpart, **it requires nothing of the field types**: wrapping a value in -`Some` and producing `None` need no `Default` and no other bound, which is why the optional path applies -to records the defaulting path does not. +`Some` and producing `None` need neither `Default` nor any other bound, which is why the optional +path applies to records the defaulting path does not. ## Examples @@ -147,7 +148,7 @@ impl TransformMap for TransformOptional { } ``` -Note what is absent: **no `Default` bound anywhere.** Its counterpart +Note what is absent: **a `Default` bound.** Its counterpart [`TransformMapDefault`](./transform_map_default.md) needs one on two of its three impls, because filling an absent field means producing a value from nothing. Producing `None` does not, so this conversion applies to every field type. Also absent is an impl from `IsOptional`, which @@ -170,10 +171,11 @@ makes [`SetOptional`](./set_optional.md) resolve and the strict **It always targets `IsOptional`.** Reaching `IsPresent` is [`TransformMapDefault`](./transform_map_default.md)'s job. -**It has no conversion from `IsOptional`**, so a builder that is already optional cannot be relaxed +**It lacks a conversion from `IsOptional`**, so a builder that is already optional cannot be relaxed again; [`ToOptional`](./to_optional.md#common-mistakes) shows the error. -**It is a marker, not an operation.** There is no method and nothing to wire. It is named in a bound. +**It is a marker, not an operation.** It lacks a method and needs nothing wired. It is named in a +bound. **It requires nothing of the field types**, which is the one place the two markers genuinely differ in what they can be applied to. From a3b6534f8b83c03967edb37fc4932d5430b5537b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 06:02:16 +0000 Subject: [PATCH 139/516] Mirror the variant and casting reference pages in example-code Adds mirrors for the seven variant pages, rewrites the four casting mirrors around a demo() program, and adds trybuild fixtures for each quoted mistake: a repeated extraction, early finalizing, the missing FinalizeExtractResult import, an uninferred or misspelled FromVariant tag, a conflicting impl, a target missing a variant, a downcast on a remainder, and build_from with a renamed or repeated field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- ...rom_common_mistakes_overlapping_sources.rs | 29 +++++++ ...common_mistakes_overlapping_sources.stderr | 15 ++++ ...uild_from_common_mistakes_renamed_field.rs | 24 ++++++ ..._from_common_mistakes_renamed_field.stderr | 21 +++++ ...on_mistakes_source_lacks_target_variant.rs | 19 +++++ ...istakes_source_lacks_target_variant.stderr | 22 +++++ ...s_common_mistakes_downcast_on_remainder.rs | 27 +++++++ ...mmon_mistakes_downcast_on_remainder.stderr | 30 +++++++ ...upcast_common_mistakes_payload_mismatch.rs | 18 +++++ ...st_common_mistakes_payload_mismatch.stderr | 15 ++++ ...st_common_mistakes_target_lacks_variant.rs | 19 +++++ ...ommon_mistakes_target_lacks_variant.stderr | 24 ++++++ ...ct_field_common_mistakes_compare_result.rs | 27 +++++++ ...ield_common_mistakes_compare_result.stderr | 68 ++++++++++++++++ ...act_field_common_mistakes_extract_twice.rs | 26 ++++++ ...field_common_mistakes_extract_twice.stderr | 15 ++++ ..._extract_common_mistakes_finalize_early.rs | 27 +++++++ ...ract_common_mistakes_finalize_early.stderr | 17 ++++ ...t_result_common_mistakes_missing_import.rs | 26 ++++++ ...sult_common_mistakes_missing_import.stderr | 22 +++++ ...t_result_common_mistakes_one_step_early.rs | 28 +++++++ ...sult_common_mistakes_one_step_early.stderr | 28 +++++++ ...ariant_common_mistakes_conflicting_impl.rs | 27 +++++++ ...nt_common_mistakes_conflicting_impl.stderr | 8 ++ ..._variant_common_mistakes_misspelled_tag.rs | 23 ++++++ ...iant_common_mistakes_misspelled_tag.stderr | 37 +++++++++ ...ariant_common_mistakes_tag_not_inferred.rs | 23 ++++++ ...nt_common_mistakes_tag_not_inferred.stderr | 19 +++++ .../tests/reference/traits/can_build_from.rs | 80 +++++++------------ .../tests/reference/traits/can_downcast.rs | 27 +++---- .../reference/traits/can_downcast_fields.rs | 49 ++++++++---- .../tests/reference/traits/can_upcast.rs | 29 ++++--- .../tests/reference/traits/extract_field.rs | 65 +++++++++++++++ .../reference/traits/finalize_extract.rs | 50 ++++++++++++ .../traits/finalize_extract_result.rs | 48 +++++++++++ .../tests/reference/traits/from_variant.rs | 63 +++++++++++++++ .../tests/reference/traits/has_extractor.rs | 56 +++++++++++++ .../reference/traits/has_extractor_mut.rs | 53 ++++++++++++ .../reference/traits/has_extractor_ref.rs | 61 ++++++++++++++ example-code/tests/reference/traits/mod.rs | 7 ++ 40 files changed, 1178 insertions(+), 94 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.rs create mode 100644 example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs create mode 100644 example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.rs create mode 100644 example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.rs create mode 100644 example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.rs create mode 100644 example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.rs create mode 100644 example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.rs create mode 100644 example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs create mode 100644 example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.rs create mode 100644 example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.stderr create mode 100644 example-code/tests/reference/traits/extract_field.rs create mode 100644 example-code/tests/reference/traits/finalize_extract.rs create mode 100644 example-code/tests/reference/traits/finalize_extract_result.rs create mode 100644 example-code/tests/reference/traits/from_variant.rs create mode 100644 example-code/tests/reference/traits/has_extractor.rs create mode 100644 example-code/tests/reference/traits/has_extractor_mut.rs create mode 100644 example-code/tests/reference/traits/has_extractor_ref.rs diff --git a/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.rs b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.rs new file mode 100644 index 00000000..61d11389 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.rs @@ -0,0 +1,29 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +#[derive(CgpData)] +pub struct FooBar { + pub foo: u64, + pub bar: String, +} + +#[derive(CgpData)] +pub struct FooBaz { + pub foo: u64, + pub baz: bool, +} + +#[derive(CgpData)] +pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, +} + +fn main() { + // Both sources carry `foo`, so the second merge would set it twice. + let _ = FooBarBaz::builder() + .build_from(FooBar { foo: 1, bar: "bar".to_owned() }) + .build_from(FooBaz { foo: 2, baz: true }) + .finalize_build(); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.stderr b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.stderr new file mode 100644 index 00000000..80dfd729 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.stderr @@ -0,0 +1,15 @@ +error[E0271]: type mismatch resolving `<__PartialFooBarBaz as UpdateField>>>, IsPresent>>::Mapper == IsNothing` + --> tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.rs:27:10 + | +27 | .build_from(FooBaz { foo: 2, baz: true }) + | ^^^^^^^^^^ type mismatch resolving `<__PartialFooBarBaz as UpdateField>>>, IsPresent>>::Mapper == IsNothing` + | +note: expected this to be `IsNothing` + --> tests/compile_fail/reference/traits/can_build_from_common_mistakes_overlapping_sources.rs:16:10 + | +16 | #[derive(CgpData)] + | ^^^^^^^ + = note: required for `__PartialFooBarBaz` to implement `BuildField>>>>` + = note: required for `Cons>>>, u64>, Cons>>>, bool>, Nil>>` to implement `cgp::cgp_core::cgp_field::impls::build_from::FieldsBuilder<__PartialFooBaz, __PartialFooBarBaz>` + = note: required for `__PartialFooBarBaz` to implement `CanBuildFrom` + = note: this error originates in the derive macro `CgpData` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs new file mode 100644 index 00000000..c8c013d7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs @@ -0,0 +1,24 @@ +use cgp::core::field::impls::CanBuildFrom; +use cgp::prelude::*; + +// The source spells the field `surname`; the target calls it `last_name`. +#[derive(CgpData)] +pub struct Person { + pub first_name: String, + pub surname: String, +} + +#[derive(CgpData)] +pub struct Employee { + pub first_name: String, + pub last_name: String, +} + +fn main() { + let _ = Employee::builder() + .build_from(Person { + first_name: "Alice".to_owned(), + surname: "Anderson".to_owned(), + }) + .finalize_build(); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.stderr b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.stderr new file mode 100644 index 00000000..26c93e7b --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.stderr @@ -0,0 +1,21 @@ +error[E0277]: the trait bound `__PartialEmployee: UpdateField>>>>>>>, IsPresent>` is not satisfied + --> tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs:19:10 + | +19 | .build_from(Person { + | ^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `UpdateField>>>>>>>, IsPresent>` is not implemented for `__PartialEmployee` + --> tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs:12:1 + | +12 | pub struct Employee { + | ^^^^^^^^^^^^^^^^^^^ +help: the following other types implement trait `UpdateField` + --> tests/compile_fail/reference/traits/can_build_from_common_mistakes_renamed_field.rs:13:9 + | +13 | pub first_name: String, + | ^^^^^^^^^^ `__PartialEmployee<__M1__, __F1__>` implements `UpdateField>>>>>>>>>>, __M2__>` +14 | pub last_name: String, + | ^^^^^^^^^ `__PartialEmployee<__F0__, __M1__>` implements `UpdateField>>>>>>>>>, __M2__>` + = note: required for `__PartialEmployee` to implement `BuildField>>>>>>>>` + = note: required for `Cons>>>>>>>, String>, Nil>` to implement `cgp::cgp_core::cgp_field::impls::build_from::FieldsBuilder<__PartialPerson, __PartialEmployee>` + = note: required for `__PartialEmployee` to implement `CanBuildFrom` diff --git a/example-code/tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.rs b/example-code/tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.rs new file mode 100644 index 00000000..3ce40a4f --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.rs @@ -0,0 +1,19 @@ +use cgp::core::field::impls::CanDowncast; +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum FooBar { + Foo(u64), + Bar(String), +} + +// `FooQux` has a `Qux` that `FooBar` can never hold. +#[derive(CgpData)] +pub enum FooQux { + Foo(u64), + Qux(char), +} + +fn main() { + let _ = FooBar::Foo(1).downcast(PhantomData::); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.stderr b/example-code/tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.stderr new file mode 100644 index 00000000..ec8a8183 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.stderr @@ -0,0 +1,22 @@ +error[E0277]: the trait bound `__PartialFooBar: ExtractField>>>>` is not satisfied + --> tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.rs:18:28 + | +18 | let _ = FooBar::Foo(1).downcast(PhantomData::); + | ^^^^^^^^ unsatisfied trait bound + | +help: the trait `ExtractField>>>>` is not implemented for `__PartialFooBar` + --> tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.rs:5:1 + | + 5 | pub enum FooBar { + | ^^^^^^^^^^^^^^^ +help: the following other types implement trait `ExtractField` + --> tests/compile_fail/reference/traits/can_downcast_common_mistakes_source_lacks_target_variant.rs:6:5 + | + 6 | Foo(u64), + | ^^^ `__PartialFooBar` implements `ExtractField>>>>` + 7 | Bar(String), + | ^^^ `__PartialFooBar<__F0__, IsPresent>` implements `ExtractField>>>>` + = note: required for `Either>>>, char>, Void>` to implement `FieldsExtractor<__PartialFooBar, FooQux>` + = note: 1 redundant requirement hidden + = note: required for `Either>>>, u64>, Either>>>, char>, Void>>` to implement `FieldsExtractor<__PartialFooBar, FooQux>` + = note: required for `FooBar` to implement `CanDowncast` diff --git a/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.rs b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.rs new file mode 100644 index 00000000..80de3bae --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.rs @@ -0,0 +1,27 @@ +use cgp::core::field::impls::CanDowncast; +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum FooBarBaz { + Foo(u64), + Bar(String), + Baz(bool), +} + +#[derive(CgpData)] +pub enum JustFoo { + Foo(u64), +} + +#[derive(CgpData)] +pub enum JustBar { + Bar(String), +} + +fn main() { + let value = FooBarBaz::Bar("hi".to_owned()); + if let Err(remainder) = value.downcast(PhantomData::) { + // A remainder is an extractor, not an enum, so it takes `downcast_fields`. + let _ = remainder.downcast(PhantomData::); + } +} diff --git a/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr new file mode 100644 index 00000000..f1eb8bd2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr @@ -0,0 +1,30 @@ +error[E0599]: the method `downcast` exists for enum `__PartialFooBarBaz`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.rs:25:27 + | + 5 | pub enum FooBarBaz { + | ------------------ method `downcast` not found for this enum because it doesn't satisfy `<_ as HasExtractor>::Extractor = _`, `_: CanDowncast<_>` or `_: HasExtractor` +... +25 | let _ = remainder.downcast(PhantomData::); + | ^^^^^^^^ + | + = note: the following trait bounds were not satisfied: + `<__PartialFooBarBaz as HasExtractor>::Extractor = _` + which is required by `__PartialFooBarBaz: CanDowncast<_>` + `__PartialFooBarBaz: HasExtractor` + which is required by `__PartialFooBarBaz: CanDowncast<_>` + `<&__PartialFooBarBaz as HasExtractor>::Extractor = _` + which is required by `&__PartialFooBarBaz: CanDowncast<_>` + `&__PartialFooBarBaz: HasExtractor` + which is required by `&__PartialFooBarBaz: CanDowncast<_>` + `<&mut __PartialFooBarBaz as HasExtractor>::Extractor = _` + which is required by `&mut __PartialFooBarBaz: CanDowncast<_>` + `&mut __PartialFooBarBaz: HasExtractor` + which is required by `&mut __PartialFooBarBaz: CanDowncast<_>` +note: the trait `HasExtractor` must be implemented + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + | + 6 | pub trait HasExtractor { + | ^^^^^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `downcast`, perhaps you need to implement it: + candidate #1: `CanDowncast` diff --git a/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.rs b/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.rs new file mode 100644 index 00000000..1ffee1f1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.rs @@ -0,0 +1,18 @@ +use cgp::core::field::impls::CanUpcast; +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum Foo64 { + Foo(u64), +} + +// The variant name matches, but the payload type does not. +#[derive(CgpData)] +pub enum Foo32Bar { + Foo(u32), + Bar(String), +} + +fn main() { + let _ = Foo64::Foo(1).upcast(PhantomData::); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.stderr b/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.stderr new file mode 100644 index 00000000..dc1f5ba6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.stderr @@ -0,0 +1,15 @@ +error[E0271]: type mismatch resolving `>>>>>::Value == u64` + --> tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.rs:17:34 + | +17 | let _ = Foo64::Foo(1).upcast(PhantomData::); + | ------ ^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `>>>>>::Value == u64` + | | + | required by a bound introduced by this call + | +note: expected this to be `u64` + --> tests/compile_fail/reference/traits/can_upcast_common_mistakes_payload_mismatch.rs:12:9 + | +12 | Foo(u32), + | ^^^ + = note: required for `Either>>>, u64>, Void>` to implement `FieldsExtractor<__PartialFoo64, Foo32Bar>` + = note: required for `Foo64` to implement `CanUpcast` diff --git a/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.rs b/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.rs new file mode 100644 index 00000000..561fe151 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.rs @@ -0,0 +1,19 @@ +use cgp::core::field::impls::CanUpcast; +use cgp::prelude::*; + +#[derive(CgpData)] +pub enum FooBar { + Foo(u64), + Bar(String), +} + +// `FooBaz` has no `Bar`, so it is not wider than `FooBar`. +#[derive(CgpData)] +pub enum FooBaz { + Foo(u64), + Baz(bool), +} + +fn main() { + let _ = FooBar::Foo(1).upcast(PhantomData::); +} diff --git a/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.stderr b/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.stderr new file mode 100644 index 00000000..cb50dd48 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.stderr @@ -0,0 +1,24 @@ +error[E0277]: the trait bound `FooBaz: FromVariant>>>>` is not satisfied + --> tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.rs:18:35 + | +18 | let _ = FooBar::Foo(1).upcast(PhantomData::); + | ------ ^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call + | +help: the trait `FromVariant>>>>` is not implemented for `FooBaz` + --> tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.rs:12:1 + | +12 | pub enum FooBaz { + | ^^^^^^^^^^^^^^^ +help: `FooBaz` implements trait `FromVariant` + --> tests/compile_fail/reference/traits/can_upcast_common_mistakes_target_lacks_variant.rs:13:5 + | +13 | Foo(u64), + | ^^^ `FromVariant>>>>` +14 | Baz(bool), + | ^^^ `FromVariant>>>>` + = note: required for `Either>>>, String>, Void>` to implement `FieldsExtractor<__PartialFooBar, FooBaz>` + = note: 1 redundant requirement hidden + = note: required for `Either>>>, u64>, Either>>>, String>, Void>>` to implement `FieldsExtractor<__PartialFooBar, FooBaz>` + = note: required for `FooBar` to implement `CanUpcast` diff --git a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs new file mode 100644 index 00000000..61c0e7a5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs @@ -0,0 +1,27 @@ +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(Debug, PartialEq, ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn main() { + let shape = Shape::Circle(Circle { radius: 1.0 }); + // The `Err` half is a generated remainder, which derives nothing. + assert_eq!( + shape.to_extractor().extract_field(PhantomData::), + Ok(Circle { radius: 1.0 }) + ); +} diff --git a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr new file mode 100644 index 00000000..c3708b57 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr @@ -0,0 +1,68 @@ +error[E0369]: binary operation `==` cannot be applied to type `Result>` + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs:23:5 + | +23 | / assert_eq!( +24 | | shape.to_extractor().extract_field(PhantomData::), +25 | | Ok(Circle { radius: 1.0 }) +26 | | ); + | | ^ + | | | + | |_____Result> + | Result> + | +note: an implementation of `PartialEq` might be missing for `__PartialShape` + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs:15:1 + | +15 | pub enum Shape { + | ^^^^^^^^^^^^^^ must implement `PartialEq` +help: consider annotating `__PartialShape` with `#[derive(PartialEq)]` + | +15 + #[derive(PartialEq)] +16 | pub enum Shape { + | + +error[E0277]: `__PartialShape` doesn't implement `Debug` + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs:23:5 + | +23 | / assert_eq!( +24 | | shape.to_extractor().extract_field(PhantomData::), +25 | | Ok(Circle { radius: 1.0 }) +26 | | ); + | |_____^ the trait `Debug` is not implemented for `__PartialShape` + | +help: the trait `Debug` is conditionally implemented for `Result` + --> $RUST/core/src/result.rs + | + | #[derive(Copy, Debug, Hash)] + | ^^^^^ +... + | pub enum Result { + | - unsatisfied requirement introduced here: `__PartialShape: Debug` +help: consider annotating `__PartialShape` with `#[derive(Debug)]` + | +15 + #[derive(Debug)] +16 | pub enum Shape { + | + +error[E0277]: `__PartialShape` doesn't implement `Debug` + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.rs:23:5 + | +23 | / assert_eq!( +24 | | shape.to_extractor().extract_field(PhantomData::), +25 | | Ok(Circle { radius: 1.0 }) +26 | | ); + | |_____^ the trait `Debug` is not implemented for `__PartialShape` + | +help: the trait `Debug` is conditionally implemented for `Result` + --> $RUST/core/src/result.rs + | + | #[derive(Copy, Debug, Hash)] + | ^^^^^ +... + | pub enum Result { + | - unsatisfied requirement introduced here: `__PartialShape: Debug` +help: consider annotating `__PartialShape` with `#[derive(Debug)]` + | +15 + #[derive(Debug)] +16 | pub enum Shape { + | diff --git a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.rs b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.rs new file mode 100644 index 00000000..8989bdb3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.rs @@ -0,0 +1,26 @@ +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), +} + +fn main() { + let shape = Shape::Circle(Circle { radius: 1.0 }); + if let Err(remainder) = shape.to_extractor().extract_field(PhantomData::) { + // `Circle` is already ruled out of `remainder`. + let _ = remainder.extract_field(PhantomData::); + } +} diff --git a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr new file mode 100644 index 00000000..b45a3ba3 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr @@ -0,0 +1,15 @@ +error[E0308]: mismatched types + --> tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.rs:24:41 + | +24 | let _ = remainder.extract_field(PhantomData::); + | ------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `9`, found `6` + | | + | arguments to this method are incorrect + | + = note: expected struct `std::marker::PhantomData>>>>>>>>>>` + found struct `std::marker::PhantomData>>>>>>>` +note: method defined here + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:35:8 + | +35 | fn extract_field(self, _tag: PhantomData) -> Result; + | ^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.rs b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.rs new file mode 100644 index 00000000..29473d38 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.rs @@ -0,0 +1,27 @@ +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), +} + +fn main() { + let shape = Shape::Circle(Circle { radius: 1.0 }); + let _: f64 = match shape.to_extractor().extract_field(PhantomData::) { + Ok(rect) => rect.width, + // `Circle` is still possible, so the remainder is inhabited. + Err(remainder) => remainder.finalize_extract(), + }; +} diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr new file mode 100644 index 00000000..e91affe1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr @@ -0,0 +1,17 @@ +error[E0599]: no method named `finalize_extract` found for enum `__PartialShape<__F0__, __F1__>` in the current scope + --> tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.rs:25:37 + | +15 | pub enum Shape { + | -------------- method `finalize_extract` not found for this enum +... +25 | Err(remainder) => remainder.finalize_extract(), + | ^^^^^^^^^^^^^^^^ method not found in `__PartialShape` + | +note: the method `finalize_extract` exists on the type `::Map` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:39:5 + | +39 | fn finalize_extract(self) -> T; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `finalize_extract`, perhaps you need to implement it: + candidate #1: `cgp::prelude::FinalizeExtract` diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.rs b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.rs new file mode 100644 index 00000000..036c66d2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.rs @@ -0,0 +1,26 @@ +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), +} + +fn main() { + let shape = Shape::Circle(Circle { radius: 1.0 }); + // `FinalizeExtractResult` is not in the prelude, and it is not imported here. + let _circle = shape + .to_extractor() + .extract_field(PhantomData::) + .finalize_extract_result(); +} diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr new file mode 100644 index 00000000..bfb8d935 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr @@ -0,0 +1,22 @@ +error[E0599]: no method named `finalize_extract_result` found for enum `Result` in the current scope + --> tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.rs:25:10 + | +22 | let _circle = shape + | ___________________- +23 | | .to_extractor() +24 | | .extract_field(PhantomData::) +25 | | .finalize_extract_result(); + | | -^^^^^^^^^^^^^^^^^^^^^^^ method not found in `Result>` + | |_________| + | + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:57:8 + | +57 | fn finalize_extract_result(self) -> Self::Output; + | ----------------------- the method is available for `Result>` here + | + = help: items from traits can only be used if the trait is in scope +help: trait `FinalizeExtractResult` which provides `finalize_extract_result` is implemented but not in scope; perhaps you want to import it + | + 1 + use cgp::cgp_core::cgp_field::traits::FinalizeExtractResult; + | diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.rs b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.rs new file mode 100644 index 00000000..b5b19628 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.rs @@ -0,0 +1,28 @@ +use cgp::core::field::traits::FinalizeExtractResult; +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), +} + +fn main() { + let shape = Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 }); + // Only `Rectangle` has been tried; `Circle` is still possible. + let _rect = shape + .to_extractor() + .extract_field(PhantomData::) + .finalize_extract_result(); +} diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr new file mode 100644 index 00000000..efdbd2a1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr @@ -0,0 +1,28 @@ +error[E0599]: the method `finalize_extract_result` exists for enum `Result>`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.rs:27:10 + | +16 | pub enum Shape { + | -------------- doesn't satisfy `__PartialShape: FinalizeExtract` +... +24 | let _rect = shape + | _________________- +25 | | .to_extractor() +26 | | .extract_field(PhantomData::) +27 | | .finalize_extract_result(); + | | -^^^^^^^^^^^^^^^^^^^^^^^ method cannot be called due to unsatisfied trait bounds + | |_________| + | + | + ::: $RUST/core/src/result.rs + | + | pub enum Result { + | --------------------- doesn't satisfy `_: FinalizeExtractResult` + | + = note: the following trait bounds were not satisfied: + `__PartialShape: FinalizeExtract` + which is required by `Result>: FinalizeExtractResult` +note: the trait `FinalizeExtract` must be implemented + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:38:1 + | +38 | pub trait FinalizeExtract { + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.rs b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.rs new file mode 100644 index 00000000..018d6aad --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.rs @@ -0,0 +1,27 @@ +use cgp::prelude::*; + +pub struct Circle { + pub radius: f64, +} + +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(FromVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +// The derive already emits this impl. +impl FromVariant for Shape { + type Value = Circle; + + fn from_variant(_tag: PhantomData, value: Circle) -> Self { + Shape::Circle(value) + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.stderr b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.stderr new file mode 100644 index 00000000..c02f71a4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.stderr @@ -0,0 +1,8 @@ +error[E0119]: conflicting implementations of trait `cgp::prelude::FromVariant>>>>>>>` for type `Shape` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_conflicting_impl.rs:14:5 + | +14 | Circle(Circle), + | ^^^^^^ conflicting implementation for `Shape` +... +19 | impl FromVariant for Shape { + | --------------------------------------------- first implementation here diff --git a/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs new file mode 100644 index 00000000..d1732765 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs @@ -0,0 +1,23 @@ +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(FromVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn main() { + // The variant is `Circle`, not `circle`. + let _ = Shape::from_variant(PhantomData::, Circle { radius: 1.0 }); +} diff --git a/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.stderr b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.stderr new file mode 100644 index 00000000..54d43f6d --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.stderr @@ -0,0 +1,37 @@ +error[E0277]: the trait bound `Shape: cgp::prelude::FromVariant>>>>>>>` is not satisfied + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:22:13 + | +22 | let _ = Shape::from_variant(PhantomData::, Circle { radius: 1.0 }); + | ^^^^^ unsatisfied trait bound + | +help: the trait `cgp::prelude::FromVariant>>>>>>>` is not implemented for `Shape` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:15:1 + | +15 | pub enum Shape { + | ^^^^^^^^^^^^^^ +help: `Shape` implements trait `cgp::prelude::FromVariant` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:16:5 + | +16 | Circle(Circle), + | ^^^^^^ `cgp::prelude::FromVariant>>>>>>>` +17 | Rectangle(Rectangle), + | ^^^^^^^^^ `cgp::prelude::FromVariant>>>>>>>>>>` + +error[E0277]: the trait bound `Shape: cgp::prelude::FromVariant>>>>>>>` is not satisfied + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:22:67 + | +22 | let _ = Shape::from_variant(PhantomData::, Circle { radius: 1.0 }); + | ^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::prelude::FromVariant>>>>>>>` is not implemented for `Shape` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:15:1 + | +15 | pub enum Shape { + | ^^^^^^^^^^^^^^ +help: `Shape` implements trait `cgp::prelude::FromVariant` + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_misspelled_tag.rs:16:5 + | +16 | Circle(Circle), + | ^^^^^^ `cgp::prelude::FromVariant>>>>>>>` +17 | Rectangle(Rectangle), + | ^^^^^^^^^ `cgp::prelude::FromVariant>>>>>>>>>>` diff --git a/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.rs b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.rs new file mode 100644 index 00000000..12fdfac6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.rs @@ -0,0 +1,23 @@ +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(FromVariant)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} + +fn main() { + // Two variants, so the tag cannot be read off the payload. + let _ = Shape::from_variant(PhantomData, Circle { radius: 1.0 }); +} diff --git a/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.stderr b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.stderr new file mode 100644 index 00000000..7ac2e9ea --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.stderr @@ -0,0 +1,19 @@ +error[E0283]: type annotations needed + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.rs:22:33 + | +22 | let _ = Shape::from_variant(PhantomData, Circle { radius: 1.0 }); + | ----- ^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the struct `PhantomData` + | | + | type must be known at this point + | +note: multiple `impl`s satisfying `Shape: cgp::prelude::FromVariant<_>` found + --> tests/compile_fail/reference/traits/from_variant_common_mistakes_tag_not_inferred.rs:16:5 + | +16 | Circle(Circle), + | ^^^^^^ +17 | Rectangle(Rectangle), + | ^^^^^^^^^ +help: consider specifying a concrete type for the type parameter `T` + | +22 | let _ = Shape::from_variant(PhantomData::, Circle { radius: 1.0 }); + | ++++++++++++++ diff --git a/example-code/tests/reference/traits/can_build_from.rs b/example-code/tests/reference/traits/can_build_from.rs index 660dba4a..978c04d1 100644 --- a/example-code/tests/reference/traits/can_build_from.rs +++ b/example-code/tests/reference/traits/can_build_from.rs @@ -1,13 +1,11 @@ -//! Code from `docs/reference/traits/can_build_from.md` — *`CanBuildFrom`*. +//! Code from `docs/reference/traits/casting/can_build_from.md` — `CanBuildFrom`. //! -//! The page's snippets, run. Two claims are pinned beyond "it compiles": the import path, since the -//! trait is not in the prelude, and that `build_from` returns a *builder* rather than the target, so -//! a second merge and an explicit `build_field` can follow before `finalize_build`. +//! Pins the Examples program: one struct merged from two sources, and a merge mixed with an explicit +//! field. A source field the target lacks, and two sources sharing a field, are trybuild fixtures. /// ## Examples -/// -/// One struct assembled from two smaller ones. -pub mod examples_two_sources { +pub mod examples { + use cgp::core::field::impls::CanBuildFrom; use cgp::prelude::*; #[derive(CgpData)] @@ -28,10 +26,28 @@ pub mod examples_two_sources { pub baz: bool, } - #[test] - fn test_build_from_two_sources() { - use cgp::core::field::impls::CanBuildFrom; + // A source rarely covers everything, so a merge is often followed by an explicit field. + #[derive(CgpData)] + pub struct Person { + pub first_name: String, + pub last_name: String, + } + #[derive(Debug, Eq, PartialEq, CgpData)] + pub struct Employee { + pub employee_id: u64, + pub first_name: String, + pub last_name: String, + } + + pub fn hire(person: Person, employee_id: u64) -> Employee { + Employee::builder() + .build_from(person) + .build_field(PhantomData::, employee_id) + .finalize_build() + } + + pub fn demo() { let combined: FooBarBaz = FooBarBaz::builder() .build_from(FooBar { foo: 1, @@ -39,7 +55,6 @@ pub mod examples_two_sources { }) .build_from(Baz { baz: true }) .finalize_build(); - assert_eq!( combined, FooBarBaz { @@ -48,49 +63,16 @@ pub mod examples_two_sources { baz: true, } ); - } -} - -/// ## Examples -/// -/// A merge mixed with an explicit field, which is the shape the page shows second. -pub mod examples_merge_and_set { - use cgp::prelude::*; - - #[derive(CgpData)] - pub struct Person { - pub first_name: String, - pub last_name: String, - } - - #[derive(Debug, Eq, PartialEq, CgpData)] - pub struct Employee { - pub employee_id: u64, - pub first_name: String, - pub last_name: String, - } - - #[test] - fn test_merge_then_set() { - use cgp::core::field::impls::CanBuildFrom; let person = Person { first_name: "Alice".to_owned(), last_name: "Anderson".to_owned(), }; + assert_eq!(hire(person, 7).employee_id, 7); + } - let employee: Employee = Employee::builder() - .build_from(person) - .build_field(PhantomData::, 7) - .finalize_build(); - - assert_eq!( - employee, - Employee { - employee_id: 7, - first_name: "Alice".to_owned(), - last_name: "Anderson".to_owned(), - } - ); + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/traits/can_downcast.rs b/example-code/tests/reference/traits/can_downcast.rs index 20175d0c..ce505772 100644 --- a/example-code/tests/reference/traits/can_downcast.rs +++ b/example-code/tests/reference/traits/can_downcast.rs @@ -1,11 +1,12 @@ -//! Code from `docs/reference/traits/can_downcast.md` — *`CanDowncast`*. +//! Code from `docs/reference/traits/casting/can_downcast.md` — `CanDowncast`. //! -//! The page's snippets, run. What this pins is the import path — the trait is not in the prelude — -//! and the two halves of the page's claim: a downcast succeeds for a shared variant and returns a -//! remainder for one the target lacks. +//! Pins the Examples program: a downcast succeeding for a shared variant and handing back a +//! remainder for one the target lacks. A target variant the source lacks, and a second `downcast` +//! on a remainder, are trybuild fixtures. /// ## Examples pub mod examples { + use cgp::core::field::impls::CanDowncast; use cgp::prelude::*; #[derive(Debug, Eq, PartialEq, CgpData)] @@ -21,27 +22,19 @@ pub mod examples { Baz(bool), } - #[test] - fn test_downcast_succeeds_for_a_shared_variant() { - use cgp::core::field::impls::CanDowncast; - use core::marker::PhantomData; - + pub fn demo() { assert_eq!( FooBarBaz::Bar("hi".to_owned()) .downcast(PhantomData::) .ok(), Some(FooBar::Bar("hi".to_owned())), ); + + assert_eq!(FooBarBaz::Baz(true).downcast(PhantomData::).ok(), None); } #[test] - fn test_downcast_fails_for_a_variant_the_target_lacks() { - use cgp::core::field::impls::CanDowncast; - use core::marker::PhantomData; - - assert_eq!( - FooBarBaz::Baz(true).downcast(PhantomData::).ok(), - None, - ); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/traits/can_downcast_fields.rs b/example-code/tests/reference/traits/can_downcast_fields.rs index 9b3ee041..adce985f 100644 --- a/example-code/tests/reference/traits/can_downcast_fields.rs +++ b/example-code/tests/reference/traits/can_downcast_fields.rs @@ -1,11 +1,12 @@ -//! Code from `docs/reference/traits/can_downcast_fields.md` — *`CanDowncastFields`*. +//! Code from `docs/reference/traits/casting/can_downcast_fields.md` — `CanDowncastFields`. //! -//! The page's chain, run. The load-bearing check is that the second attempt is written with -//! `downcast_fields` rather than `downcast`: a remainder is an extractor rather than an enum, so the -//! two halves of the pair are not interchangeable. +//! Pins the Examples program: a value tried against three candidate targets in turn, the last step +//! closed by `finalize_extract_result` because the candidates cover every variant. /// ## Examples pub mod examples { + use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; + use cgp::core::field::traits::FinalizeExtractResult; use cgp::prelude::*; #[derive(Debug, Eq, PartialEq, CgpData)] @@ -25,20 +26,36 @@ pub mod examples { Bar(String), } - #[test] - fn test_a_chain_of_two_candidate_targets() { - use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; - use core::marker::PhantomData; - - let value = FooBarBaz::Bar("hi".to_owned()); + #[derive(Debug, Eq, PartialEq, CgpData)] + pub enum JustBaz { + Baz(bool), + } + pub fn classify(value: FooBarBaz) -> &'static str { match value.downcast(PhantomData::) { - Ok(_foo) => panic!("the value is not a Foo"), - Err(remainder) => { - let bar = remainder.downcast_fields(PhantomData::); - - assert!(bar.is_ok()); - } + Ok(_) => "foo", + // `remainder` can no longer be a `Foo`. + Err(remainder) => match remainder.downcast_fields(PhantomData::) { + Ok(_) => "bar", + Err(remainder) => { + // Every variant is now covered, so the last attempt cannot fail. + let JustBaz::Baz(_) = remainder + .downcast_fields(PhantomData::) + .finalize_extract_result(); + "baz" + } + }, } } + + pub fn demo() { + assert_eq!(classify(FooBarBaz::Foo(1)), "foo"); + assert_eq!(classify(FooBarBaz::Bar("hi".to_owned())), "bar"); + assert_eq!(classify(FooBarBaz::Baz(true)), "baz"); + } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/traits/can_upcast.rs b/example-code/tests/reference/traits/can_upcast.rs index e254e5f1..f5e9a0c1 100644 --- a/example-code/tests/reference/traits/can_upcast.rs +++ b/example-code/tests/reference/traits/can_upcast.rs @@ -1,33 +1,38 @@ -//! Code from `docs/reference/traits/can_upcast.md` — *`CanUpcast`*. +//! Code from `docs/reference/traits/casting/can_upcast.md` — `CanUpcast`. //! -//! The page's snippet, run. What this pins beyond "it compiles" is the import path — the trait is -//! not in the prelude — and the totality claim: an upcast into a wider enum always succeeds, so -//! `upcast` returns the target directly rather than a `Result`. +//! Pins the Examples program: a narrow enum widened into a wider one, with each side deriving only +//! what the cast needs. A target that lacks a source variant is a trybuild fixture. /// ## Examples pub mod examples { + use cgp::core::field::impls::CanUpcast; use cgp::prelude::*; - #[derive(Debug, Eq, PartialEq, CgpData)] + // The source is walked and taken apart, so it needs its shape and its extractor. + #[derive(Debug, Eq, PartialEq, HasFields, ExtractField)] pub enum FooBar { Foo(u64), Bar(String), } - #[derive(Debug, Eq, PartialEq, CgpData)] + // The target is only built into, one variant at a time. + #[derive(Debug, Eq, PartialEq, FromVariant)] pub enum FooBarBaz { Foo(u64), Bar(String), Baz(bool), } - #[test] - fn test_upcast_always_succeeds() { - use cgp::core::field::impls::CanUpcast; - use core::marker::PhantomData; - + pub fn demo() { let wide = FooBar::Foo(1).upcast(PhantomData::); - assert_eq!(wide, FooBarBaz::Foo(1)); + + let wide = FooBar::Bar("hi".to_owned()).upcast(PhantomData::); + assert_eq!(wide, FooBarBaz::Bar("hi".to_owned())); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/traits/extract_field.rs b/example-code/tests/reference/traits/extract_field.rs new file mode 100644 index 00000000..04951011 --- /dev/null +++ b/example-code/tests/reference/traits/extract_field.rs @@ -0,0 +1,65 @@ +//! Code from `docs/reference/traits/variant/extract_field.md` — `ExtractField`. +//! +//! Pins the Examples program: a two-variant chain closed by `finalize_extract_result`, with the +//! extractions written in either order. Extracting a variant twice and finalizing early are +//! trybuild fixtures. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; + 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::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + // `remainder` can no longer be a `Circle`. + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width * rect.height + } + } + } + + // The same chain with the extractions the other way round. + pub fn perimeter(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(rect) => 2.0 * (rect.width + rect.height), + Err(remainder) => { + let circle = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + 2.0 * core::f64::consts::PI * circle.radius + } + } + } + + pub fn demo() { + assert_eq!(area(Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), 12.0); + assert_eq!(perimeter(Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), 14.0); + assert!(area(Shape::Circle(Circle { radius: 1.0 })) > 3.14); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/finalize_extract.rs b/example-code/tests/reference/traits/finalize_extract.rs new file mode 100644 index 00000000..75cf394f --- /dev/null +++ b/example-code/tests/reference/traits/finalize_extract.rs @@ -0,0 +1,50 @@ +//! Code from `docs/reference/traits/variant/finalize_extract.md` — `FinalizeExtract`. +//! +//! Pins the Examples program: `finalize_extract` called directly on a remainder unwrapped by a +//! nested `match`. Finalizing before every variant is tried is a trybuild fixture. + +/// ## Examples +pub mod examples { + 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::) { + Ok(circle) => format!("circle of radius {}", circle.radius), + Err(remainder) => match remainder.extract_field(PhantomData::) { + 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" + ); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/finalize_extract_result.rs b/example-code/tests/reference/traits/finalize_extract_result.rs new file mode 100644 index 00000000..14ad0ab1 --- /dev/null +++ b/example-code/tests/reference/traits/finalize_extract_result.rs @@ -0,0 +1,48 @@ +//! Code from `docs/reference/traits/variant/finalize_extract_result.md` — `FinalizeExtractResult`. +//! +//! Pins the Examples program: a chain closed by `finalize_extract_result`. Calling it one step +//! early, and calling it without the import, are trybuild fixtures. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; + 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::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .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); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/from_variant.rs b/example-code/tests/reference/traits/from_variant.rs new file mode 100644 index 00000000..9c73f7af --- /dev/null +++ b/example-code/tests/reference/traits/from_variant.rs @@ -0,0 +1,63 @@ +//! Code from `docs/reference/traits/variant/from_variant.md` — `FromVariant`. +//! +//! Pins the Examples program: one generic `wrap` building either variant, and a narrow enum +//! upcast into `Shape`, which needs only `FromVariant` on the target. Leaving the tag to inference +//! on a two-variant enum is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::CanUpcast; + 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(Debug, PartialEq, FromVariant)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn wrap(tag: PhantomData, value: >::Value) -> Shape + where + Shape: FromVariant, + { + Shape::from_variant(tag, value) + } + + // A routine that only ever produces circles works in a one-variant enum. + #[derive(HasFields, ExtractField)] + pub enum RoundShape { + Circle(Circle), + } + + pub fn unit_circle() -> Shape { + RoundShape::Circle(Circle { radius: 1.0 }).upcast(PhantomData::) + } + + pub fn demo() { + let circle = wrap(PhantomData::, Circle { radius: 2.0 }); + assert_eq!(circle, Shape::Circle(Circle { radius: 2.0 })); + + let rect = wrap( + PhantomData::, + Rectangle { width: 3.0, height: 4.0 }, + ); + assert_eq!(rect, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })); + + assert_eq!(unit_circle(), Shape::Circle(Circle { radius: 1.0 })); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/has_extractor.rs b/example-code/tests/reference/traits/has_extractor.rs new file mode 100644 index 00000000..37eda647 --- /dev/null +++ b/example-code/tests/reference/traits/has_extractor.rs @@ -0,0 +1,56 @@ +//! Code from `docs/reference/traits/variant/has_extractor.md` — `HasExtractor`. +//! +//! Pins the Examples program: `to_extractor` starting a chain, and `from_extractor` rebuilding the +//! enum from an extractor that was not narrowed. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; + 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(Debug, PartialEq, ExtractField)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn area(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width * rect.height + } + } + } + + // Any extractable enum survives the round trip unchanged. + pub fn round_trip(value: E) -> E { + E::from_extractor(value.to_extractor()) + } + + pub fn demo() { + assert_eq!(area(Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), 12.0); + + let shape = Shape::Circle(Circle { radius: 2.0 }); + assert_eq!(round_trip(shape), Shape::Circle(Circle { radius: 2.0 })); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/has_extractor_mut.rs b/example-code/tests/reference/traits/has_extractor_mut.rs new file mode 100644 index 00000000..aca0f2a7 --- /dev/null +++ b/example-code/tests/reference/traits/has_extractor_mut.rs @@ -0,0 +1,53 @@ +//! Code from `docs/reference/traits/variant/has_extractor_mut.md` — `HasExtractorMut`. +//! +//! Pins the Examples program: a full mutable chain that scales whichever variant is present, the +//! writes landing in the original value. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; + 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(Debug, PartialEq, ExtractField)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn scale(shape: &mut Shape, factor: f64) { + match shape.extractor_mut().extract_field(PhantomData::) { + Ok(circle) => circle.radius *= factor, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width *= factor; + rect.height *= factor; + } + } + } + + pub fn demo() { + let mut shape = Shape::Circle(Circle { radius: 1.0 }); + scale(&mut shape, 5.0); + + // `shape` now holds the updated `Circle`. + assert_eq!(shape, Shape::Circle(Circle { radius: 5.0 })); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/has_extractor_ref.rs b/example-code/tests/reference/traits/has_extractor_ref.rs new file mode 100644 index 00000000..d6c08735 --- /dev/null +++ b/example-code/tests/reference/traits/has_extractor_ref.rs @@ -0,0 +1,61 @@ +//! Code from `docs/reference/traits/variant/has_extractor_ref.md` — `HasExtractorRef`. +//! +//! Pins the Examples program: a single borrowed attempt, and a full borrowed chain closed by +//! `finalize_extract_result`, both leaving the value usable. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; + 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(Debug, PartialEq, ExtractField)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn radius(shape: &Shape) -> Option { + shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok() + } + + pub fn area(shape: &Shape) -> f64 { + match shape.extractor_ref().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width * rect.height + } + } + } + + pub fn demo() { + let shape = Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 }); + assert_eq!(radius(&shape), None); + assert_eq!(area(&shape), 12.0); + + // `shape` is still usable here. + assert_eq!(shape, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/mod.rs b/example-code/tests/reference/traits/mod.rs index e4711472..a98eba9b 100644 --- a/example-code/tests/reference/traits/mod.rs +++ b/example-code/tests/reference/traits/mod.rs @@ -18,12 +18,19 @@ pub mod can_use_component; pub mod concat_path; pub mod concat_product; pub mod delegate_component; +pub mod extract_field; pub mod field_getter; pub mod field_mapper; pub mod finalize_build; +pub mod finalize_extract; +pub mod finalize_extract_result; pub mod finalize_optional; pub mod from_fields; +pub mod from_variant; pub mod has_builder; +pub mod has_extractor; +pub mod has_extractor_mut; +pub mod has_extractor_ref; pub mod has_field; pub mod has_field_mut; pub mod has_fields; From 200bb3ef56653fe8661213451604bc1cdbb379ab Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 06:02:16 +0000 Subject: [PATCH 140/516] Revise the variant and casting reference pages Adds front matter, ports each Examples section from its mirror, replaces the sketched listings with the real expansion and source impls, and quotes every Common Mistakes error with its snippet. Corrects the claims that a repeated extraction is a missing method, that the borrowed extractors reuse the owned companion, that from_extractor relies on PartialData, that both cast sides need every derive, that the FromVariant tag is never inferred, that build_from drops a field the target lacks, and that FieldsBuilder never appears in diagnostics. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../traits/casting/can_build_from.md | 223 ++++++++++++++---- docs/reference/traits/casting/can_downcast.md | 95 ++++++-- .../traits/casting/can_downcast_fields.md | 101 ++++++-- docs/reference/traits/casting/can_upcast.md | 140 ++++++++--- docs/reference/traits/casting/index.md | 14 +- .../reference/traits/variant/extract_field.md | 156 +++++++++--- .../traits/variant/finalize_extract.md | 140 +++++++---- .../traits/variant/finalize_extract_result.md | 132 +++++++---- docs/reference/traits/variant/from_variant.md | 182 ++++++++------ .../reference/traits/variant/has_extractor.md | 86 ++++--- .../traits/variant/has_extractor_mut.md | 101 +++++--- .../traits/variant/has_extractor_ref.md | 119 +++++++--- docs/reference/traits/variant/index.md | 1 + 13 files changed, 1072 insertions(+), 418 deletions(-) diff --git a/docs/reference/traits/casting/can_build_from.md b/docs/reference/traits/casting/can_build_from.md index 239f689f..03a46b9b 100644 --- a/docs/reference/traits/casting/can_build_from.md +++ b/docs/reference/traits/casting/can_build_from.md @@ -1,6 +1,8 @@ --- +title: 'CanBuildFrom — merge a record into a builder' sidebar_label: 'CanBuildFrom' sidebar_position: 4 +description: 'Move every field of one record into another record''s builder by field name, so several sources can be merged before the target is finalized.' --- # `CanBuildFrom` @@ -13,10 +15,10 @@ Assembling one struct out of several smaller ones means copying each shared fiel line per field, repeated for every pair of types. `CanBuildFrom` derives that copying from the field names instead. -It is the record counterpart of the [variant casts](./can_upcast.md), and it differs from them in one -way that shapes how it is written: **it is implemented for a builder rather than for the target type**. -Calling it fills a partial value with whatever fields it shares with the source and hands the builder -back, so several sources can be absorbed in sequence before the result is finalized. +It is the record counterpart of the [variant casts](./can_upcast.md), and it differs from them in +one way that shapes how it is written: **it is implemented for a builder rather than for the target +type**. Calling it moves every field of the source into a partial value and hands the builder back, +so several sources can be absorbed in sequence before the result is finalized. That is the merge step of the extensible builder pattern: independent parts of a program each produce a record, and the target absorbs all of them without any of them naming it. @@ -46,40 +48,90 @@ before a finalize. use cgp::core::field::impls::CanBuildFrom; ``` -**The source needs [`HasFields`](../shape/has_fields.md) as well as a builder**, because the recursion walks the -source's field list to know what to copy. The target needs only its builder. Deriving the same thing on -both looks symmetric and does not compile, which is the mistake this trait causes most often. +**The source needs [`HasFields`](../shape/has_fields.md) as well as a builder**, because the +recursion walks the source's field list to know what to copy. The target needs only its builder, and +must declare every field the source carries. Deriving only +[`BuildField`](../../derives/derive_build_field.md) on both looks symmetric and does not compile, +which is the mistake this trait causes most often. ## Examples -Two independent records merged into a third, which names neither of them: +Two independent records merged into a third, and a merge followed by the one field its source did +not carry: ```rust -use cgp::core::field::impls::CanBuildFrom; use cgp::prelude::*; +use cgp::core::field::impls::CanBuildFrom; -#[derive(CgpData)] pub struct FooBar { pub foo: u64, pub bar: String } -#[derive(CgpData)] pub struct Baz { pub baz: bool } -#[derive(CgpData)] pub struct FooBarBaz { pub foo: u64, pub bar: String, pub baz: bool } +#[derive(CgpData)] +pub struct FooBar { + pub foo: u64, + pub bar: String, +} -let combined: FooBarBaz = FooBarBaz::builder() - .build_from(FooBar { foo: 1, bar: "bar".to_owned() }) - .build_from(Baz { baz: true }) - .finalize_build(); -``` +#[derive(CgpData)] +pub struct Baz { + pub baz: bool, +} -Neither source names the target and the target names neither source. They share field *names*, matched -at the type level, and that is the whole coupling. +#[derive(Debug, Eq, PartialEq, CgpData)] +pub struct FooBarBaz { + pub foo: u64, + pub bar: String, + pub baz: bool, +} -Mixing a merge with an explicit field is the usual shape, since a source rarely covers everything: +// A source rarely covers everything, so a merge is often followed by an explicit field. +#[derive(CgpData)] +pub struct Person { + pub first_name: String, + pub last_name: String, +} -```rust -let employee = Employee::builder() - .build_from(person) // the shared fields - .build_field(PhantomData::, 7) // and the one it did not carry - .finalize_build(); +#[derive(Debug, Eq, PartialEq, CgpData)] +pub struct Employee { + pub employee_id: u64, + pub first_name: String, + pub last_name: String, +} + +pub fn hire(person: Person, employee_id: u64) -> Employee { + Employee::builder() + .build_from(person) + .build_field(PhantomData::, employee_id) + .finalize_build() +} + +pub fn demo() { + let combined: FooBarBaz = FooBarBaz::builder() + .build_from(FooBar { + foo: 1, + bar: "bar".to_owned(), + }) + .build_from(Baz { baz: true }) + .finalize_build(); + assert_eq!( + combined, + FooBarBaz { + foo: 1, + bar: "bar".to_owned(), + baz: true, + } + ); + + let person = Person { + first_name: "Alice".to_owned(), + last_name: "Anderson".to_owned(), + }; + assert_eq!(hire(person, 7).employee_id, 7); +} ``` +Neither source names the target and the target names neither source. They share field *names*, +matched at the type level, and that is the whole coupling. `hire` shows the usual shape, since a +source rarely covers everything: `build_from` returns a builder, so an explicit +[`build_field`](../builder/build_field.md) can follow it before `finalize_build`. + ## When to use it **Reach for it when a record is assembled from independent pieces.** That is the extensible builder @@ -87,48 +139,127 @@ pattern's merge step, and the reason the trait exists. - **Prefer a struct literal** when one place knows every field. A literal is already checked for completeness, reads better, and generates nothing. -- **Prefer a plain `From` impl** when the two types are yours and the conversion is one you would write - once. This trait earns its keep when the conversion must be *derived* from names rather than written. +- **Prefer a plain `From` impl** when the two types are yours and the conversion is one you would + write once. This trait pays off when the conversion must be *derived* from names rather than + written. - **Reach for [`CanBuildWithDefault`](../optional/can_build_with_default.md)** when the target has fields the source does not cover and their defaults are acceptable: it chains `builder()`, `build_from`, and a defaulted finalize into one call. - **Reach for [`CanUpcast`](./can_upcast.md)** for the enum analogue. -One boundary worth stating: this is **compile-time, name-driven, and opt-in**. Both types must derive the -machinery, the names must match exactly, and nothing is inspected at run time. +One boundary worth stating: this is **compile-time, name-driven, and opt-in**. Both types must +derive their part of the machinery, the names must match exactly, and nothing is inspected at run +time. ## Under the hood -`CanBuildFrom` **recurses over the source's field product.** For each field the source exposes, it uses -[`TakeField`](../builder/take_field.md) to remove that value from the source and [`BuildField`](../builder/build_field.md) -to write it into the target builder, threading both the shrinking source and the growing builder through -the walk. +`CanBuildFrom` **recurses over the source's field product.** Its one impl turns the source into a +full builder with [`IntoBuilder`](../builder/into_builder.md) and walks the source's +[`HasFields`](../shape/has_fields.md) list: -When the source's fields run out, the builder is returned, **not finalized**, which lets a second -`build_from` follow and is why `Output` is a builder type rather than the target struct. +```rust +impl CanBuildFrom for Builder +where + Source: HasFields + IntoBuilder, + Source::Fields: FieldsBuilder, +{ + type Output = Output; + + fn build_from(self, source: Source) -> Output { + Source::Fields::build_fields(source.into_builder(), self) + } +} +``` -One asymmetry in the source is worth knowing if you read it: this recursion, `FieldsBuilder`, is -**private**, while the variant casts' `FieldsExtractor` is public. So the extractor recursion can appear -by name in a diagnostic and be named in a bound; this one cannot. +For each field, `FieldsBuilder` takes the value out of the source with +[`TakeField`](../builder/take_field.md) and writes it into the target with +[`BuildField`](../builder/build_field.md), threading both the shrinking source and the growing +builder: + +```rust +impl FieldsBuilder + for Cons, RestFields> +where + Source: TakeField, + Target: BuildField, + RestFields: FieldsBuilder, +{ + type Output = RestFields::Output; + + fn build_fields(source: Source, target: Target) -> Self::Output { + let (value, next_source) = source.take_field(PhantomData); + let next_target = target.build_field(PhantomData, value); + + RestFields::build_fields(next_source, next_target) + } +} +``` + +The `Target: BuildField` bound is what makes every source field mandatory in the target, and +absent there before the merge. When the source's fields run out, the `Nil` impl returns the builder, +**not finalized**, which lets a second `build_from` follow and is why `Output` is a builder type +rather than the target struct. + +`FieldsBuilder` is **private**, while the variant casts' `FieldsExtractor` is public. So only the +extractor recursion can be named in a bound; both still appear by name in a failed call's notes, +this one as `cgp::cgp_core::cgp_field::impls::build_from::FieldsBuilder`. ## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::impls`. -**The source needs [`HasFields`](../shape/has_fields.md), not just a builder.** Deriving only -[`BuildField`](../../derives/derive_build_field.md) on both structs looks symmetric and fails; the error is -an unsatisfied `HasFields` bound on the source type. +**The source needs [`HasFields`](../shape/has_fields.md), not only a builder.** Deriving only +[`BuildField`](../../derives/derive_build_field.md) on both structs looks symmetric and fails; the +error is an unsatisfied `HasFields` bound on the source type. **It is called on the builder, not the target.** `Target::builder().build_from(source)`, and the result is a builder you still have to [finalize](../builder/finalize_build.md). -**Field names are the whole interface.** Renaming a field in one struct silently stops it being copied, -and the failure surfaces at `finalize_build`, as a missing-method error, rather than at the rename. +**Every source field must exist in the target, so a renamed field fails at the merge.** A source +spelling `surname` where the target says `last_name`: + +```rust +#[derive(CgpData)] +pub struct Person { + pub first_name: String, + pub surname: String, +} + +#[derive(CgpData)] +pub struct Employee { + pub first_name: String, + pub last_name: String, +} -**A field the target lacks is not an error and not copied.** The walk matches on the target's slots, so -an extra field on the source is simply dropped. +let _ = Employee::builder() + .build_from(Person { + first_name: "Alice".to_owned(), + surname: "Anderson".to_owned(), + }) + .finalize_build(); +``` + +has nowhere to put `surname`, and the error is on `build_from`: + +```text +error[E0277]: the trait bound `__PartialEmployee: UpdateField>>>>>>>, IsPresent>` is not satisfied +... + = note: required for `__PartialEmployee` to implement `CanBuildFrom` +``` + +A source field the target lacks is never silently dropped. The reverse, a target field no source +carries, is legal and is left for a [`build_field`](../builder/build_field.md) or a defaulted +finalize. + +**Two sources may not carry the same field.** Merging `FooBar { foo, bar }` and then +`FooBaz { foo, baz }` into one builder sets `foo` twice, which fails on the second merge as +[`BuildField`](../builder/build_field.md#common-mistakes)'s build-twice mismatch: + +```text +error[E0271]: type mismatch resolving `<__PartialFooBarBaz as UpdateField>>>, IsPresent>>::Mapper == IsNothing` +``` -**It consumes the source.** There is no borrowing form. +**It consumes the source.** The trait lacks a borrowing form. ## Related constructs diff --git a/docs/reference/traits/casting/can_downcast.md b/docs/reference/traits/casting/can_downcast.md index 68819e42..5a2bfa29 100644 --- a/docs/reference/traits/casting/can_downcast.md +++ b/docs/reference/traits/casting/can_downcast.md @@ -1,6 +1,8 @@ --- +title: 'CanDowncast — narrow an enum, or get the rest' sidebar_label: 'CanDowncast' sidebar_position: 2 +description: 'Try to convert a wide enum into a narrower one, getting the narrowed value or a remainder with the attempted variants ruled out for the next attempt.' --- # `CanDowncast` @@ -49,14 +51,20 @@ use cgp::core::field::impls::CanDowncast; use core::marker::PhantomData; ``` +**The two sides swap roles from an upcast.** The source is only taken apart, so it needs +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md); the target's variant list is the +one walked and each match is rebuilt into it, so it needs +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md) and +[`#[derive(FromVariant)]`](../../derives/derive_from_variant.md). + + ## Examples A downcast succeeds for a variant the target shares and fails for one it lacks: ```rust -use cgp::core::field::impls::CanDowncast; use cgp::prelude::*; -use core::marker::PhantomData; +use cgp::core::field::impls::CanDowncast; #[derive(Debug, Eq, PartialEq, CgpData)] pub enum FooBar { @@ -71,16 +79,20 @@ pub enum FooBarBaz { Baz(bool), } -assert_eq!( - FooBarBaz::Bar("hi".to_owned()).downcast(PhantomData::).ok(), - Some(FooBar::Bar("hi".to_owned())), -); +pub fn demo() { + assert_eq!( + FooBarBaz::Bar("hi".to_owned()) + .downcast(PhantomData::) + .ok(), + Some(FooBar::Bar("hi".to_owned())), + ); -assert_eq!(FooBarBaz::Baz(true).downcast(PhantomData::).ok(), None); + assert_eq!(FooBarBaz::Baz(true).downcast(PhantomData::).ok(), None); +} ``` -`.ok()` is right for a single attempt and wrong when another target should be tried, because it throws -away the remainder that the next attempt needs. +`.ok()` suits a single attempt and is wrong when another target should be tried, because it throws +away the remainder the next attempt needs. ## When to use it @@ -100,30 +112,65 @@ first starts the chain and the second continues it on each remainder. ## Under the hood **The downcasts recurse over the *target's* variants**, which is the mirror image of -[`CanUpcast`](./can_upcast.md#under-the-hood) walking the source's. For each `Field` in -`Target::Fields`, the implementation tries pulling that variant out of the source extractor: on success -it rebuilds the target with [`FromVariant`](../variant/from_variant.md) and returns `Ok`; on failure it threads the -shrunken remainder into the next attempt. If no target variant matches, the terminal `Void` impl returns -the whole remainder as `Err`. +[`CanUpcast`](./can_upcast.md#under-the-hood) walking the source's. The impl hands the source's +extractor to the target's variant list: -`CanDowncast` differs from [`CanDowncastFields`](./can_downcast_fields.md) only in where the walk starts: -this one calls [`to_extractor`](../variant/has_extractor.md) on the enum first, while that one operates on an -extractor it is handed. That is the entire reason two traits exist rather than one, and it makes -chaining possible: the `Remainder` a `downcast` returns is precisely a `downcast_fields` input. +```rust +impl CanDowncast for Context +where + Context: HasExtractor, + Target: HasFields, + Target::Fields: FieldsExtractor, +{ + type Remainder = Remainder; + + fn downcast(self, _tag: PhantomData) -> Result { + Target::Fields::extract_from(self.to_extractor()) + } +} +``` + +`FieldsExtractor` is the same walk the upcast uses: for each `Field` in +`Target::Fields`, it tries pulling that variant out of the source extractor with +[`ExtractField`](../variant/extract_field.md). On success it rebuilds the target with +[`FromVariant`](../variant/from_variant.md) and returns `Ok`; on failure it threads the shrunken +remainder into the next attempt. If no target variant matches, the terminal `Void` impl returns the +whole remainder as `Err`. The walk needs `ExtractField` for every target variant, so each one must +exist in the source; the source's other variants are what can reach the `Err`. + +`CanDowncast` differs from [`CanDowncastFields`](./can_downcast_fields.md) only in where the walk +starts: this one calls [`to_extractor`](../variant/has_extractor.md) on the enum first, while that +one operates on an extractor it is handed. That is the entire reason two traits exist rather than +one, and it makes chaining possible: the `Remainder` a `downcast` returns is precisely a +`downcast_fields` input. ## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::impls`. -**A downcast returns a remainder, not an `Option`.** `.ok()` discards it, which is fine for a single -attempt and wrong if you meant to try another target. +**A downcast returns a remainder, not an `Option`.** `.ok()` discards it, which suits a single +attempt and is wrong if you meant to try another target. **A remainder carries none of the enum's attributes**, so a `Result` is neither -`Debug` nor `PartialEq`, and comparing one whole does not compile. Reach for `.ok()`, `.is_ok()`, or a -`match`. +`Debug` nor `PartialEq`, and comparing one whole does not compile, as +[`ExtractField`](../variant/extract_field.md#common-mistakes) shows. Reach for `.ok()`, `.is_ok()`, +or a `match`. + +**Every target variant must exist in the source, by name and payload type.** A source variant the +target lacks is the runtime `Err` case, but a target variant the source lacks is a compile error. +With a target `FooQux { Foo(u64), Qux(char) }` and a source `FooBar { Foo(u64), Bar(String) }`: + +```rust +let _ = FooBar::Foo(1).downcast(PhantomData::); +``` -**Names and payload types must match exactly**, and a mismatch is a compile error rather than a runtime -miss: the variant simply drops out of the overlap. +the walk cannot extract `Qux` from what remains of the source: + +```text +error[E0277]: the trait bound `__PartialFooBar: ExtractField>>>>` is not satisfied +... + = note: required for `FooBar` to implement `CanDowncast` +``` **The remainder's type is not the source enum.** It is a partial companion with markers, so it cannot be stored where the original was. diff --git a/docs/reference/traits/casting/can_downcast_fields.md b/docs/reference/traits/casting/can_downcast_fields.md index 264dbecf..78404872 100644 --- a/docs/reference/traits/casting/can_downcast_fields.md +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -19,8 +19,10 @@ The two traits do the same narrowing and differ in one thing: **where the walk s is called on an enum and converts it to an extractor first; `CanDowncastFields` is called on an extractor it is already given. Since a remainder *is* an extractor, that is exactly the shape a chain needs. -**So the pair is the construct, and this half is never used alone.** A chain reads as one `downcast` -followed by one `downcast_fields` per additional candidate. +**So the pair is the construct, and this half is almost always the continuation.** A chain reads as +one `downcast` followed by one `downcast_fields` per additional candidate. It applies to any +extractor that can yield each target variant, so it also works on a fresh `to_extractor()`, where it +does exactly what `downcast` does. ## Definition @@ -35,7 +37,7 @@ pub trait CanDowncastFields { ``` `Target` is the enum being narrowed to. `Self` here is a *remainder* rather than an enum, and the method -takes it by value, returning `Result` just as `downcast` does. The returned +takes it by value, returning `Result` as `downcast` does. The returned `Remainder` is narrower again, so each call in a chain has a different, progressively smaller `Self` type. ## Usage @@ -50,12 +52,12 @@ use core::marker::PhantomData; ## Examples -Trying a value against two candidate targets in turn: +Trying a value against three candidate targets in turn: ```rust -use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; use cgp::prelude::*; -use core::marker::PhantomData; +use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; +use cgp::core::field::traits::FinalizeExtractResult; #[derive(Debug, Eq, PartialEq, CgpData)] pub enum FooBarBaz { @@ -74,52 +76,99 @@ pub enum JustBar { Bar(String), } -let value = FooBarBaz::Bar("hi".to_owned()); +#[derive(Debug, Eq, PartialEq, CgpData)] +pub enum JustBaz { + Baz(bool), +} -match value.downcast(PhantomData::) { - Ok(foo) => { /* it was a Foo */ } - Err(remainder) => { - // `remainder` can no longer be a Foo - let bar = remainder.downcast_fields(PhantomData::); - assert!(bar.is_ok()); +pub fn classify(value: FooBarBaz) -> &'static str { + match value.downcast(PhantomData::) { + Ok(_) => "foo", + // `remainder` can no longer be a `Foo`. + Err(remainder) => match remainder.downcast_fields(PhantomData::) { + Ok(_) => "bar", + Err(remainder) => { + // Every variant is now covered, so the last attempt cannot fail. + let JustBaz::Baz(_) = remainder + .downcast_fields(PhantomData::) + .finalize_extract_result(); + "baz" + } + }, } } + +pub fn demo() { + assert_eq!(classify(FooBarBaz::Foo(1)), "foo"); + assert_eq!(classify(FooBarBaz::Bar("hi".to_owned())), "bar"); + assert_eq!(classify(FooBarBaz::Baz(true)), "baz"); +} ``` -The first call starts the chain and the second continues it. Written the other way round, with a second -`downcast` on the remainder, it does not compile, because a remainder is not an enum. +The first call starts the chain and each later one continues it on the remainder. The three +candidates cover every variant of `FooBarBaz`, so the last remainder is uninhabited and the final +step closes with [`finalize_extract_result`](../variant/finalize_extract_result.md) instead of a +`match`, exactly as an [extraction chain](../variant/extract_field.md) does. ## When to use it -**Reach for it only as the continuation of a [`CanDowncast`](./can_downcast.md) chain.** It has no other -use: its `Self` is a remainder, and a remainder only ever comes from a prior downcast. +**Reach for it as the continuation of a [`CanDowncast`](./can_downcast.md) chain.** Its `Self` is an +extractor, and in practice that is the remainder a prior downcast returned. - **Use one `downcast` and then one `downcast_fields` per further candidate.** That is the whole pattern. - **Prefer the [extractor family](../variant/extract_field.md)** when what you want is the *payload* of whichever variant is present rather than another enum. It narrows identically and ends with a checked, wildcard-free discharge through [`FinalizeExtract`](../variant/finalize_extract.md). -- **Prefer a `match`** when the enum is concrete and the candidates are few. A cast chain earns its keep +- **Prefer a `match`** when the enum is concrete and the candidates are few. A cast chain pays off when the targets are type parameters or the chain is long. ## Under the hood -Both traits walk the *target's* variant list, trying to pull each one out of the extractor they hold and -threading the shrunken remainder into the next attempt, with the terminal `Void` impl returning the whole -remainder as `Err`. The only difference is the entry point: `CanDowncast` calls -[`to_extractor`](../variant/has_extractor.md) on an enum to obtain the extractor, and this trait takes one it is -handed. +Its one impl applies to any `Source` the target's variant walk can extract from, and hands it +straight to that walk: + +```rust +impl CanDowncastFields for Source +where + Target: HasFields, + Target::Fields: FieldsExtractor, +{ + type Remainder = Remainder; + + fn downcast_fields(self, _tag: PhantomData) -> Result { + Target::Fields::extract_from(self) + } +} +``` + +`FieldsExtractor` is the same recursion [`CanDowncast`](./can_downcast.md#under-the-hood) uses: it +tries each target variant against the extractor, threading the shrunken remainder into the next +attempt, with the terminal `Void` impl returning the whole remainder as `Err`. The only difference +is the entry point: `CanDowncast` calls [`to_extractor`](../variant/has_extractor.md) on an enum to +obtain the extractor, and this trait takes one it is handed. Because the remainder type narrows at every step, a chain's types are all distinct, and the compiler knows at each point exactly which variants remain, the same narrowing a hand-written -[extraction chain](../variant/extract_field.md) performs. +[extraction chain](../variant/extract_field.md) performs. So once the candidates have covered every +variant, the last remainder is uninhabited and the final `Result` closes with +[`finalize_extract_result`](../variant/finalize_extract_result.md), as the example's last step does. ## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::impls`. -**It cannot be called on an enum.** `Self` is an extractor. Start with -[`CanDowncast`](./can_downcast.md). +**It cannot be called on an enum, and `downcast` cannot be called on a remainder.** `Self` here is +an extractor, and `downcast` needs an enum to call `to_extractor` on. Writing the second step of the +example as `remainder.downcast(PhantomData::)` fails with: + +```text +error[E0599]: the method `downcast` exists for enum `__PartialFooBarBaz`, but its trait bounds were not satisfied +... +note: the trait `HasExtractor` must be implemented +``` + +Start a chain with [`CanDowncast`](./can_downcast.md) and continue it with this trait. **`.ok()` on an intermediate step ends the chain.** Discarding the remainder discards the input the next attempt needs. diff --git a/docs/reference/traits/casting/can_upcast.md b/docs/reference/traits/casting/can_upcast.md index 946b98ec..f67cce4a 100644 --- a/docs/reference/traits/casting/can_upcast.md +++ b/docs/reference/traits/casting/can_upcast.md @@ -1,6 +1,8 @@ --- +title: 'CanUpcast — widen an enum by variant name' sidebar_label: 'CanUpcast' sidebar_position: 1 +description: 'Convert a narrow enum into a wider one that has every one of its variants, routing each by name at the type level; the cast cannot fail.' --- # `CanUpcast` @@ -32,11 +34,10 @@ pub trait CanUpcast { } ``` -`Self` is the narrow enum and `Target` the wider one. The method takes `self` by value and consumes it, -returning the `Target` directly rather than a `Result`, because a widening cannot fail. The -`PhantomData` argument names the target for inference and carries no data. Both enums must derive -the extensible-data machinery, and the target's variant set must include every one of the source's, -matched by name and by payload type. +`Self` is the narrow enum and `Target` the wider one. The method takes `self` by value and consumes +it, returning the `Target` directly rather than a `Result`, because a widening cannot fail. The +`PhantomData` argument names the target for inference and carries nothing but the type. The +target's variant set must include every one of the source's, matched by name and by payload type. ## Usage @@ -49,35 +50,51 @@ use cgp::core::field::impls::CanUpcast; use core::marker::PhantomData; ``` +**Each side derives what its role needs.** The source is walked and taken apart, so it needs +[`#[derive(HasFields)]`](../../derives/derive_has_fields.md) and +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md); the target is only built into, +so it needs [`#[derive(FromVariant)]`](../../derives/derive_from_variant.md). +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) on both covers every direction at once. + + ## Examples -Two independently-defined enums that share variant names interconvert with no manual impl: +A narrow enum widened into a wider one, with each side deriving only what the cast needs: ```rust -use cgp::core::field::impls::CanUpcast; use cgp::prelude::*; -use core::marker::PhantomData; +use cgp::core::field::impls::CanUpcast; -#[derive(Debug, Eq, PartialEq, CgpData)] +// The source is walked and taken apart, so it needs its shape and its extractor. +#[derive(Debug, Eq, PartialEq, HasFields, ExtractField)] pub enum FooBar { Foo(u64), Bar(String), } -#[derive(Debug, Eq, PartialEq, CgpData)] +// The target is only built into, one variant at a time. +#[derive(Debug, Eq, PartialEq, FromVariant)] pub enum FooBarBaz { Foo(u64), Bar(String), Baz(bool), } -let wide = FooBar::Foo(1).upcast(PhantomData::); +pub fn demo() { + let wide = FooBar::Foo(1).upcast(PhantomData::); + assert_eq!(wide, FooBarBaz::Foo(1)); -assert_eq!(wide, FooBarBaz::Foo(1)); + let wide = FooBar::Bar("hi".to_owned()).upcast(PhantomData::); + assert_eq!(wide, FooBarBaz::Bar("hi".to_owned())); +} ``` Neither enum names the other. They share variant *names*, matched at the type level, and that is the -whole coupling. +whole coupling. The source derives [`HasFields`](../shape/has_fields.md) and +[`ExtractField`](../../derives/derive_extract_field.md) because the cast walks it and takes it +apart; the target derives only [`FromVariant`](../../derives/derive_from_variant.md) because the +cast only builds into it. [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) on both covers +every case. ## When to use it @@ -93,24 +110,63 @@ name only the variants you need, and let the widening be checked. - **Reach for [`CanBuildFrom`](./can_build_from.md)** for the record analogue: merging a struct's fields into another struct's builder. -One boundary worth stating: this is **compile-time, name-driven, and opt-in**. Both enums must derive -the shape, the names must match exactly, and nothing is inspected at run time. An enum from a crate that -has not derived the machinery cannot participate at all. +One boundary worth stating: this is **compile-time, name-driven, and opt-in**. Each enum must derive +the machinery its side of the cast needs, the names must match exactly, and nothing is inspected at +run time. An enum from a crate that has not derived the machinery cannot participate at all. ## Under the hood -`CanUpcast` **recurses over the source's variants**. It converts the source to its extractor with -[`HasExtractor`](../variant/has_extractor.md), then walks the source's own field list, pulling each variant out -with [`ExtractField`](../variant/extract_field.md) and rebuilding it into the target with -[`FromVariant`](../variant/from_variant.md). +`CanUpcast` **recurses over the source's variants**. Its one impl turns the source into its +extractor with [`HasExtractor`](../variant/has_extractor.md), walks the source's own +[`HasFields`](../shape/has_fields.md) list, and discharges what is left: + +```rust +impl CanUpcast for Context +where + Context: HasFields + HasExtractor, + Context::Fields: FieldsExtractor, + Remainder: FinalizeExtract, +{ + fn upcast(self, _tag: PhantomData) -> Target { + Context::Fields::extract_from(self.to_extractor()).finalize_extract_result() + } +} +``` + +The walk is `FieldsExtractor`, implemented for each cell of the variant list. A cell pulls its +variant out with [`ExtractField`](../variant/extract_field.md), rebuilds it into the target with +[`FromVariant`](../variant/from_variant.md), or threads the remainder into the rest of the list: + +```rust +impl FieldsExtractor + for Either, RestFields> +where + Source: ExtractField, + Target: FromVariant, + RestFields: FieldsExtractor, +{ + type Remainder = Remainder; + + fn extract_from(source: Source) -> Result { + match source.extract_field(PhantomData) { + Ok(field) => Ok(Target::from_variant(PhantomData, field)), + Err(remainder) => RestFields::extract_from(remainder), + } + } +} +``` -Because every source variant is guaranteed to exist in a wider target, the walk is total, and the -extractor left at the end is uninhabited, discharged with [`FinalizeExtract`](../variant/finalize_extract.md). -That is precisely why `upcast` returns the target directly instead of a `Result`. +and the terminal `Void` cell returns whatever remains as `Err`. Because the list walked is the +source's own, every source variant is tried, so the final remainder is uninhabited and +`Remainder: FinalizeExtract` holds; +[`finalize_extract_result`](../variant/finalize_extract_result.md) then discharges it. That is why +`upcast` returns the target directly instead of a `Result`, and why the bounds put `HasFields` and +`HasExtractor` on the source and only `FromVariant` on the target. -One detail from the source is worth knowing if you read it: the recursion driving this, -`FieldsExtractor`, is **public**, so it can appear by name in a diagnostic and be named in a bound. Its -record-side analogue `FieldsBuilder`, behind [`CanBuildFrom`](./can_build_from.md), is private. +`FieldsExtractor` is **public**, so it can be named in a bound, and it appears by name in a failed +cast's notes. Its record-side analogue `FieldsBuilder`, behind +[`CanBuildFrom`](./can_build_from.md), is private, so it cannot be named in a bound, though it still +appears in diagnostics. ## Common Mistakes @@ -118,16 +174,34 @@ record-side analogue `FieldsBuilder`, behind [`CanBuildFrom`](./can_build_from.m wrong. **An upcast is total only if the target really is wider.** If the target lacks one of the source's -variants there is no impl, and the failure is an unsatisfied bound rather than a runtime error. That is -the guarantee, but it reads as a puzzling missing-impl message until you check the variant lists. +variants, the cast fails to compile rather than at run time. With a target +`FooBaz { Foo(u64), Baz(bool) }` that lacks `FooBar`'s `Bar`: + +```rust +let _ = FooBar::Foo(1).upcast(PhantomData::); +``` -**Names must match exactly.** Renaming a variant in one enum silently removes it from the overlap, and -the failure surfaces wherever the cast is written rather than at the rename. +the error names the missing constructor, then the walk that needed it: -**The payload types must match too.** A `Foo(u64)` does not upcast into a `Foo(u32)`; the tag and the -value type are both part of the entry. +```text +error[E0277]: the trait bound `FooBaz: FromVariant>>>>` is not satisfied +... + = note: required for `FooBar` to implement `CanUpcast` +``` + +Read the `Symbol` in the headline to find the variant the target is missing. + +**Names must match exactly.** Renaming a variant in one enum removes it from the overlap, and the +failure surfaces where the cast is written rather than at the rename. + +**The payload types must match too.** A `Foo(u64)` does not upcast into a `Foo(u32)`; the tag and +the value type are both part of the entry, and the mismatch is reported on the target's constructor: + +```text +error[E0271]: type mismatch resolving `>>>>>::Value == u64` +``` -**It consumes the source.** There is no borrowing form. +**It consumes the source.** The trait lacks a borrowing form. ## Related constructs diff --git a/docs/reference/traits/casting/index.md b/docs/reference/traits/casting/index.md index ac40d077..c2be70cf 100644 --- a/docs/reference/traits/casting/index.md +++ b/docs/reference/traits/casting/index.md @@ -1,20 +1,22 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The traits that convert between two data types by their shared variant or field names: widening and narrowing enums, and merging records into a builder.' --- # Structural casts -Converting between two data types by their shared fields or variants, with no hand-written conversion. +Converting between two data types by their shared fields or variants, without a hand-written +conversion. ## Overview Two types that share a subset of named fields or variants can convert into one another generically, without a hand-written `From` or `TryFrom`. Because CGP represents each record as a product of named fields and each enum as a sum of named variants, a conversion becomes a matter of routing each named -entry to the target's slot of the same name. Both types must derive the extensible-data machinery, and -the names are matched at the type level. None of these traits is in the prelude. Import each from -`cgp::core::field::impls`. +entry to the target's slot of the same name. Each side derives the part of the extensible-data +machinery its role needs, and the names are matched at the type level. None of these traits is in +the prelude. Import each from `cgp::core::field::impls`. These traits cover the directions that routing can take. @@ -23,8 +25,8 @@ which always succeeds, and [`CanDowncast`](can_downcast.md) narrows into a small and hands back a remainder. [`CanDowncastFields`](can_downcast_fields.md) continues a narrowing chain on that remainder against a further candidate. -For **records**, [`CanBuildFrom`](can_build_from.md) fills a builder with every field it shares with -another record, so several sources can be merged into one target before it is finalized. +For **records**, [`CanBuildFrom`](can_build_from.md) moves every field of another record into a +builder, so several sources can be merged into one target before it is finalized. ## The ideas behind them diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index ad70d863..d5dc4e49 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -1,6 +1,8 @@ --- +title: 'ExtractField — take one variant out' sidebar_label: 'ExtractField' sidebar_position: 1 +description: 'Try one named variant of an enum''s extractor, getting its payload or a remainder with that variant ruled out, so a chain ends in a proven-exhaustive match.' --- # `ExtractField` @@ -18,10 +20,10 @@ wanted. is still possible**, so attempting the same variant twice is a compile error rather than a guaranteed miss. -Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** -(a value of it cannot exist), and [`FinalizeExtract`](./finalize_extract.md) closes the chain with -no wildcard and no panic path. Add a variant to the enum and the final remainder becomes inhabited again, -so the code stops compiling until it is handled. +Keep going and the remainder narrows. Once every variant has been ruled out its type is +**uninhabited** (a value of it cannot exist), and [`FinalizeExtract`](./finalize_extract.md) closes +the chain with without a wildcard or a panic path. Add a variant to the enum and the final remainder +becomes inhabited again, so the code stops compiling until it is handled. The family is the mirror of the [builder](../builder/has_builder.md): a builder tracks which fields are *present*, an extractor tracks which variants are still *possible*. @@ -63,11 +65,22 @@ through [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) and ## Examples The chain reads as a sequence of attempts, each handling one variant, closed by -[`finalize_extract_result`](./finalize_extract_result.md): +[`finalize_extract_result`](./finalize_extract_result.md), written here in both orders: ```rust -use cgp::core::field::traits::FinalizeExtractResult; use cgp::prelude::*; +use cgp::core::field::traits::FinalizeExtractResult; + +#[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 { @@ -75,27 +88,47 @@ pub enum Shape { Rectangle(Rectangle), } -fn area(shape: Shape) -> f64 { +pub fn area(shape: Shape) -> f64 { match shape.to_extractor().extract_field(PhantomData::) { Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, Err(remainder) => { - // `remainder` now has Circle ruled out + // `remainder` can no longer be a `Circle`. let rect = remainder .extract_field(PhantomData::) - .finalize_extract_result(); // uninhabited; cannot fail + .finalize_extract_result(); rect.width * rect.height } } } + +// The same chain with the extractions the other way round. +pub fn perimeter(shape: Shape) -> f64 { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(rect) => 2.0 * (rect.width + rect.height), + Err(remainder) => { + let circle = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + 2.0 * core::f64::consts::PI * circle.radius + } + } +} + +pub fn demo() { + assert_eq!(area(Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), 12.0); + assert_eq!(perimeter(Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), 14.0); + assert!(area(Shape::Circle(Circle { radius: 1.0 })) > 3.14); +} ``` -After the second extraction both variants are ruled out, so the remainder's type is uninhabited and the -finalize is accepted with no wildcard arm. That is not a convention but the type. Try to finalize -after only the first extraction and it does not compile. +After the second extraction both variants are ruled out, so the remainder's type is uninhabited and +the finalize is accepted without a wildcard arm. The type enforces this: finalize after only the +first extraction and the code does not compile. The two functions try the variants in opposite +orders, which works because each step changes only its own variant's marker. -**In practice you rarely write these chains.** The -[dispatch combinators](../../providers/dispatch/index.md) build them from a set of per-variant -implementations, which is the extensible visitor pattern: a chain exactly like the one above, generated, +**In practice you rarely write these chains.** The [dispatch +combinators](../../providers/dispatch/index.md) build them from a set of per-variant +implementations, which is the extensible visitor pattern: a chain like the one above, generated, with one implementation per variant chosen by wiring. ## When to use it @@ -123,8 +156,9 @@ the whole family is [`HasBuilder`](../builder/has_builder.md). ## Under the hood -The derive generates a companion enum with one [`MapType`](../type-level/map_type.md) parameter per variant, each -payload wrapped in that parameter's projection: +The derive generates a companion enum with one [`MapType`](../type-level/map_type.md) parameter per +variant, each payload wrapped in that parameter's projection. `cargo cgp expand` on the example's +`Shape` shows it: ```rust pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { @@ -133,36 +167,92 @@ pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { } ``` -[`to_extractor`](./has_extractor.md) starts at the all-`IsPresent` configuration, where every variant is -still possible. **Each `extract_field` impl is in scope only while its variant's marker is `IsPresent`**; -on a miss it returns the remainder with that one marker flipped to `IsVoid`, leaving the rest generic, -which is why extractions may happen in any order. +[`to_extractor`](./has_extractor.md) starts at the all-`IsPresent` configuration, where every +variant is still possible. The derive then writes one `ExtractField` impl per variant, and the +`Circle` one shows the whole mechanism: + +```rust +impl<__F1__: MapType> ExtractField +for __PartialShape { + type Value = Circle; + type Remainder = __PartialShape; + fn extract_field( + self, + _tag: ::core::marker::PhantomData, + ) -> Result { + match self { + __PartialShape::Circle(value) => Ok(value), + __PartialShape::Rectangle(value) => Err(__PartialShape::Rectangle(value)), + } + } +} +``` -That per-variant scoping is the mirror of [`BuildField`](../builder/build_field.md)'s requirement that a field be -`IsNothing` before it can be set, and it makes a repeated attempt a compile error rather than a -guaranteed `Err`. +**The impl exists only while `Circle`'s marker is `IsPresent`**, and on a miss it returns the +remainder with that one marker flipped to `IsVoid` while `__F1__` passes through, which is why +extractions may happen in any order. That per-variant scoping is the mirror of +[`BuildField`](../builder/build_field.md)'s requirement that a field be `IsNothing` before it can be +set, and it makes a repeated attempt a compile error rather than a guaranteed `Err`. -The exhaustiveness argument itself belongs to [`FinalizeExtract`](./finalize_extract.md), and turns on -`IsVoid` mapping a payload to the uninhabited `Void`. +The exhaustiveness argument itself belongs to [`FinalizeExtract`](./finalize_extract.md), and turns +on `IsVoid` mapping a payload to the uninhabited `Void`. -The borrowed accessors use the same partial enum with an extra [`MapTypeRef`](../type-level/map_type_ref.md) -parameter fixed to `IsRef` or `IsMut`, so a value can be matched without being moved and the narrowing -works identically. +The borrowed accessors use a second companion, `__PartialRefShape`, with a lifetime and an extra +[`MapTypeRef`](../type-level/map_type_ref.md) parameter that +[`HasExtractorRef`](./has_extractor_ref.md) fixes to `IsRef` and +[`HasExtractorMut`](./has_extractor_mut.md) to `IsMut`. The derive emits the same per-variant +`ExtractField` impls on it, so a value can be matched without being moved and the narrowing works +identically. ## Common Mistakes **`Self` is an extractor, not the enum.** A chain starts with [`to_extractor`](./has_extractor.md) or one of its borrowing siblings. -**Attempting the same variant twice does not compile.** The marker is already `IsVoid`, so no impl -applies, reported as a missing method. +**Attempting the same variant twice does not compile, and the error is not about the variant.** +Extracting `Circle` again from the remainder of a failed `Circle` attempt: + +```rust +if let Err(remainder) = shape.to_extractor().extract_field(PhantomData::) { + let _ = remainder.extract_field(PhantomData::); +} +``` + +leaves only the `Rectangle` impl applicable, so rustc settles on it and reports the tag argument as +the wrong type: + +```text +error[E0308]: mismatched types +... + | ------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `9`, found `6` +``` + +The two numbers are the lengths of `Rectangle` and `Circle` in their `Symbol` types, and the `note` +lines below spell both out. **Absence is `IsVoid` here and `IsNothing` in a builder, and they are not interchangeable.** An error naming the wrong one usually means record and variant machinery have been crossed. **A remainder carries none of the enum's attributes.** The partial enums are generated without your -derives, so a `Result` is neither `Debug` nor `PartialEq` however the enum is derived, -and `assert_eq!` on the whole result does not compile. Reach for `.ok()`, `.is_ok()`, or a `match`. +derives, so a `Result` is neither `Debug` nor `PartialEq` however the enum is +derived. On a `Shape` deriving both: + +```rust +assert_eq!( + shape.to_extractor().extract_field(PhantomData::), + Ok(Circle { radius: 1.0 }) +); +``` + +fails with + +```text +error[E0369]: binary operation `==` cannot be applied to type `Result>` +... +error[E0277]: `__PartialShape` doesn't implement `Debug` +``` + +Reach for `.ok()`, `.is_ok()`, or a `match`. **Order is free but the set is not.** Each step changes only its own variant's marker, so extractions may be written in any order, but every variant must be tried before the remainder can be finalized. diff --git a/docs/reference/traits/variant/finalize_extract.md b/docs/reference/traits/variant/finalize_extract.md index 40828d8f..57a40b92 100644 --- a/docs/reference/traits/variant/finalize_extract.md +++ b/docs/reference/traits/variant/finalize_extract.md @@ -1,6 +1,8 @@ --- +title: 'FinalizeExtract — end an exhausted match' sidebar_label: 'FinalizeExtract' sidebar_position: 5 +description: 'Discharge an extractor with every variant ruled out: its type is uninhabited, so the method returns any type and closes the match without a wildcard.' --- # `FinalizeExtract` @@ -13,13 +15,13 @@ An [extraction chain](./extract_field.md) ends when every variant has been ruled 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, because there is no value to return it from: -the method can only be called on something that cannot exist, so its body is an empty `match` and no -execution path reaches it. +**It returns *any* type.** That looks unsound and is not, because a value to return it from cannot +exist: the method can only be called on something that cannot exist, so its body is an empty `match` +and no execution path reaches it. -That closes a generic match with **no wildcard arm and no `unreachable!()`**. It is the mirror of -[`FinalizeBuild`](../builder/finalize_build.md), and the two are sound for opposite reasons: a build finalizes -because the value is *complete*, an extraction because the value is *impossible*. +That closes a generic match **without a wildcard arm or an `unreachable!()`**. It is the mirror of +[`FinalizeBuild`](../builder/finalize_build.md), and the two are sound for opposite reasons: a build +finalizes because the value is *complete*, an extraction because the value is *impossible*. ## Definition @@ -29,11 +31,11 @@ pub trait FinalizeExtract { } ``` -`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 trait is implemented for the uninhabited -[`Void`](../../types/void.md), the standard `Infallible`, and the all-ruled-out -configuration of a partial enum. +`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`](../../types/void.md) and the standard `Infallible`, and the derive for the +all-ruled-out configuration of each partial enum, owned and borrowed. ## Usage @@ -47,33 +49,53 @@ The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_fie ## Examples -Called directly, on a remainder held in hand: +Called directly, on a remainder a nested `match` has unwrapped: ```rust use cgp::prelude::*; -match shape.to_extractor().extract_field(PhantomData::) { - Ok(circle) => handle_circle(circle), - Err(remainder) => match remainder.extract_field(PhantomData::) { - Ok(rect) => handle_rectangle(rect), - Err(remainder) => remainder.finalize_extract(), // uninhabited: cannot be reached - }, +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, } -``` -The last arm returns whatever the surrounding `match` needs, and the compiler accepts it because the -value being matched cannot exist. +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} -The same chain written with the `Result` helper is shorter and is the form most code uses: +#[derive(ExtractField)] +pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), +} -```rust -use cgp::core::field::traits::FinalizeExtractResult; +pub fn describe(shape: Shape) -> String { + match shape.to_extractor().extract_field(PhantomData::) { + Ok(circle) => format!("circle of radius {}", circle.radius), + Err(remainder) => match remainder.extract_field(PhantomData::) { + Ok(rect) => format!("{} by {} rectangle", rect.width, rect.height), + // Uninhabited: this arm can never run. + Err(remainder) => remainder.finalize_extract(), + }, + } +} -let rect = remainder - .extract_field(PhantomData::) - .finalize_extract_result(); +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`](./finalize_extract_result.md) on the last `Result` is shorter, and is +the form most code uses. + ## When to use it **Reach for [`FinalizeExtractResult`](./finalize_extract_result.md) unless you already hold a @@ -90,39 +112,65 @@ remainder.** The two do the same job at different points in the chain. ## Under the hood -**Everything turns on what `IsVoid` maps to.** The [`MapType`](../type-level/map_type.md) marker `IsVoid` maps a -payload to the uninhabited [`Void`](../../types/void.md), so once every variant's marker is -`IsVoid`, every arm of the partial enum holds a `Void` and **the whole type is uninhabited**. +**Everything turns on what `IsVoid` maps to.** The [`MapType`](../type-level/map_type.md) marker +`IsVoid` maps a payload to the uninhabited [`Void`](../../types/void.md), 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: +The derive supplies an impl on exactly that configuration, for the owned companion and, generic over +the [`MapTypeRef`](../type-level/map_type_ref.md) marker, for the borrowed one. `cargo cgp expand` +on the example's `Shape` shows both: ```rust impl FinalizeExtract for __PartialShape { fn finalize_extract<__T__>(self) -> __T__ { - match self {} // no arms to write + match self {} + } +} +impl<'__a__, __R__: MapTypeRef> FinalizeExtract +for __PartialRefShape<'__a__, __R__, IsVoid, IsVoid> { + fn finalize_extract<__T__>(self) -> __T__ { + match self {} } } ``` -An empty `match` is legal precisely 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 with no fallback. +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 exactly why a builder needs an explicit all-present -[`FinalizeBuild`](../builder/finalize_build.md) impl while an extractor can discharge its remainder with an empty -`match`. +**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`](../builder/finalize_build.md) 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`, so the compiler reports a missing method. Read the type in -the message to see which variants remain. +**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: + +```rust +match shape.to_extractor().extract_field(PhantomData::) { + Ok(rect) => rect.width, + Err(remainder) => remainder.finalize_extract(), +} +``` + +reports a missing method: + +```text +error[E0599]: no method named `finalize_extract` found for enum `__PartialShape<__F0__, __F1__>` in the current scope +... + | ^^^^^^^^^^^^^^^^ method not found in `__PartialShape` +``` + +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; there is no value and no execution. +**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. diff --git a/docs/reference/traits/variant/finalize_extract_result.md b/docs/reference/traits/variant/finalize_extract_result.md index 226f8b66..7036743d 100644 --- a/docs/reference/traits/variant/finalize_extract_result.md +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -1,6 +1,8 @@ --- +title: 'FinalizeExtractResult — close a variant chain' sidebar_label: 'FinalizeExtractResult' sidebar_position: 6 +description: 'Collapse the Result the last step of an extraction chain returns, returning the payload and discharging the uninhabited remainder at the type level.' --- # `FinalizeExtractResult` @@ -30,17 +32,9 @@ pub trait FinalizeExtractResult { ``` `Self` is the `Result` and `Output` is the payload alone. The trait has one blanket impl, for any -`Result` whose error half can be discharged: +`Result` whose error half can be discharged, shown in [Under the hood](#under-the-hood). + -```rust -impl FinalizeExtractResult for Result -where - E: FinalizeExtract, -{ - type Output = T; - // Ok(value) => value, Err(remainder) => remainder.finalize_extract() -} -``` `finalize_extract_result` returns the `Ok` value directly and discharges the `Err` half through [`FinalizeExtract`](./finalize_extract.md), which cannot fail once the remainder is uninhabited. @@ -62,8 +56,19 @@ dischargeable, so it applies the moment a chain has tried every variant. Closing a chain, which is the whole use: ```rust -use cgp::core::field::traits::FinalizeExtractResult; use cgp::prelude::*; +use cgp::core::field::traits::FinalizeExtractResult; + +#[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 { @@ -71,33 +76,27 @@ pub enum Shape { Rectangle(Rectangle), } -fn area(shape: Shape) -> f64 { +pub fn area(shape: Shape) -> f64 { match shape.to_extractor().extract_field(PhantomData::) { Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, Err(remainder) => { let rect = remainder .extract_field(PhantomData::) - .finalize_extract_result(); // no variants left, so this cannot fail + .finalize_extract_result(); // no variants left, so this cannot fail rect.width * rect.height } } } -``` - -No `.unwrap()`, no `expect`, and no wildcard arm. The call compiles only because both variants have been -tried, which makes it a proof rather than an assertion. - -Calling it one step early does not compile: -```rust -// error: the trait bound is not satisfied: Circle is still possible, -// so the remainder is inhabited and cannot be discharged -let rect = shape - .to_extractor() - .extract_field(PhantomData::) - .finalize_extract_result(); +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; [Common +Mistakes](#common-mistakes) 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. @@ -109,34 +108,83 @@ let rect = shape - **The [dispatch combinators](../../providers/dispatch/index.md)** 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 a `match`** when you are making a single attempt and do not intend to exhaust the enum. - Reaching for this trait then simply will not resolve. +- **`.ok()` or a `match`** when 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 `match`** when the enum is concrete. ## Under the hood -The impl delegates to [`FinalizeExtract`](./finalize_extract.md) on the error half, which is where the -soundness argument lives: 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. +The trait's one impl delegates to [`FinalizeExtract`](./finalize_extract.md) on the error half: + +```rust +impl FinalizeExtractResult for Result +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`](../../types/void.md). That is occasionally useful -outside the extractor family, for collapsing a `Result` that a signature required but that cannot fail. +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`](../../types/void.md). That is occasionally useful +outside the extractor family, for collapsing a `Result` that a signature required but that cannot +fail. -`Output` being an associated type rather than a generic lets the call sit at the end of a method +`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 it there is no -`finalize_extract_result` in scope and the chain has no clean ending, and the error is a -missing-method one, which reads as though the chain is wrong rather than the import missing. +**It is not in the prelude.** Import it from `cgp::core::field::traits`. Without the import, a +complete chain on a one-variant enum: + +```rust +let circle = shape + .to_extractor() + .extract_field(PhantomData::) + .finalize_extract_result(); +``` + +fails as a missing method, though rustc does name the fix: + +```text +error[E0599]: no method named `finalize_extract_result` found for enum `Result` 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`: + +```rust +let rect = shape + .to_extractor() + .extract_field(PhantomData::) + .finalize_extract_result(); +``` + +reports the unsatisfied `FinalizeExtract` bound on the remainder: -**Calling it early does not compile.** Any variant still possible leaves the remainder inhabited and the -bound unsatisfied. +```text +error[E0599]: the method `finalize_extract_result` exists for enum `Result>`, but its trait bounds were not satisfied +... + = note: the following trait bounds were not satisfied: + `__PartialShape: FinalizeExtract` + which is required by `Result>: FinalizeExtractResult` +``` -**It discards nothing and cannot panic.** Unlike `.unwrap()`, there is no runtime branch: the `Err` case -is discharged at the type level. +**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. diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index cffa7525..c8ebecb5 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -1,6 +1,8 @@ --- +title: 'FromVariant — build an enum from one variant' sidebar_label: 'FromVariant' sidebar_position: 7 +description: 'Construct an enum from a single variant chosen by its type-level name, so generic code can build a variant it cannot name as a constructor.' --- # `FromVariant` @@ -23,9 +25,9 @@ Shape::from_variant(PhantomData::, circle) That call is exactly `Shape::Circle(circle)`. The difference is that the tag can come from a type parameter, so one function can build whichever variant it was asked for, on whatever enum implements the trait for that tag. -**This is the smallest trait in the extensible-data family.** There is no companion type, no state, and nothing -to track, because building a single variant has no intermediate states. It is the construction counterpart to -[`ExtractField`](./extract_field.md)'s deconstruction, and the impls come from +**This is the smallest trait in the extensible-data family.** It needs neither a companion type nor +any state, because building a single variant leaves nothing to track. It is the construction +counterpart to [`ExtractField`](./extract_field.md)'s deconstruction, and the impls come from [`#[derive(FromVariant)]`](../../derives/derive_from_variant.md), one per variant. ## Definition @@ -42,11 +44,11 @@ pub trait FromVariant { ``` `Self` is the enum. `Tag` is the variant's name as a [`Symbol!`](../../macros/symbol.md) type-level -string, and `Value` is that variant's payload type. `from_variant` wraps a payload into the enum as the -chosen variant. The `PhantomData` argument carries no data; it lets a caller pick which variant to -build when several impls, one per variant, are in scope on the same enum. Because the trait is -implemented once per variant, each impl fixing its own `Tag` and `Value`, choosing the impl **is** -choosing the variant. +string, and `Value` is that variant's payload type. `from_variant` wraps a payload into the enum as +the chosen variant. The `PhantomData` argument carries nothing but the tag; it lets a caller +pick which variant to build when several impls, one per variant, are in scope on the same enum. +Because the trait is implemented once per variant, each impl fixing its own `Tag` and `Value`, +choosing the impl **is** choosing the variant. ## Usage @@ -55,76 +57,87 @@ yourself: the derive supplies one per variant, and you either call `T::from_variant(PhantomData::, value)` at a concrete site or bound on the trait in code generic over the tag. -### Naming the payload type generically - The associated `Value` makes a generic signature possible: a function that does not know the variant -still needs to name the type it takes. Project it through the trait: - -```rust -fn wrap(tag: PhantomData, value: >::Value) -> Shape -where - Shape: FromVariant, -{ - Shape::from_variant(tag, value) -} -``` - -`>::Value` is the payload type *derived from the tag*. Without it there would be -nothing to write in the parameter position, which is the whole reason the trait carries an associated type -rather than taking the payload as a second parameter. +still needs to name the type it takes, and projects it through the trait as +`>::Value`, the payload type *derived from the tag*, as `wrap` does in the +[example](#examples). Without it there would be nothing to write in the parameter position, which is +the whole reason the trait carries an associated type rather than taking the payload as a second +parameter. ## Examples -One `wrap` builds either variant, and its payload type follows the tag: +One `wrap` builds either variant, with its payload type following the tag, and a narrow enum widens +into `Shape`: ```rust use cgp::prelude::*; +use cgp::core::field::impls::CanUpcast; + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} -#[derive(FromVariant)] +#[derive(Debug, PartialEq, FromVariant)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } -fn wrap(tag: PhantomData, value: >::Value) -> Shape +pub fn wrap(tag: PhantomData, value: >::Value) -> Shape where Shape: FromVariant, { Shape::from_variant(tag, value) } -let circle = wrap(PhantomData::, Circle { radius: 2.0 }); -let rect = wrap( - PhantomData::, - Rectangle { width: 3.0, height: 4.0 }, -); -``` +// A routine that only ever produces circles works in a one-variant enum. +#[derive(HasFields, ExtractField)] +pub enum RoundShape { + Circle(Circle), +} -No hand-written function can do that, because `Shape::Circle` and `Shape::Rectangle` are different expressions -taking different types. +pub fn unit_circle() -> Shape { + RoundShape::Circle(Circle { radius: 1.0 }).upcast(PhantomData::) +} -Where this earns its keep in practice is **building through a narrow enum and widening**. A routine that only -produces some of a large enum's variants declares a small local enum, constructs into that, and lifts the -result: +pub fn demo() { + let circle = wrap(PhantomData::, Circle { radius: 2.0 }); + assert_eq!(circle, Shape::Circle(Circle { radius: 2.0 })); -```rust -use cgp::core::field::impls::CanUpcast; + let rect = wrap( + PhantomData::, + Rectangle { width: 3.0, height: 4.0 }, + ); + assert_eq!(rect, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })); -let ident = LispSubExpr::Ident(Ident("+".to_owned())).upcast(PhantomData::); + assert_eq!(unit_circle(), Shape::Circle(Circle { radius: 1.0 })); +} ``` -The upcast always succeeds, because every variant of the smaller enum has a home in the larger one, and -`FromVariant` rebuilds each variant into the target. That is the construction-side counterpart of reading -a field through a getter: the implementation names only what it needs, and the widening is checked. -Upcasting is documented with the other [structural casts](../casting/can_upcast.md). +A hand-written function cannot do what `wrap` does, because `Shape::Circle` and `Shape::Rectangle` +are different expressions taking different types. + +`unit_circle` shows where this matters in practice, **building through a narrow enum and widening**. +A routine that only produces some of a large enum's variants declares a small local enum, constructs +into that, and lifts the result. The upcast always succeeds, because every variant of the smaller +enum has a home in the larger one, and `FromVariant` rebuilds each variant into the target, which is +why `Shape` derives nothing else. Upcasting is documented with the other [structural +casts](../casting/can_upcast.md). ## When to use it -**Bound on `FromVariant` when the variant to build is decided by a type parameter.** That is the whole test, -and it is narrower than the extractor's, because most code decides which variant to build at a site that can -simply name it. +**Bound on `FromVariant` when the variant to build is decided by a type parameter.** That is the +whole test, and it is narrower than the extractor's, because most code decides which variant to +build at a site that can name it. -- **Bound on it in a routine parameterized over the variant it produces.** There is no alternative. +- **Bound on it in a routine parameterized over the variant it produces.** Nothing else can do it. - **Derive it to make a smaller enum upcastable into a larger one.** Casting between enums is built on these constructors, so this lets an implementation work in a narrow local enum and widen the result. - **Do not reach for it for an ordinary constructor call.** `Shape::Circle(circle)` is shorter, clearer, and @@ -139,47 +152,80 @@ The names capture the split exactly: this trait puts a value *into* an enum, ## Under the hood -The derive emits **one impl per variant and nothing else**: +The derive emits **one impl per variant and nothing else**. `cargo cgp expand` on the example's +`Shape` shows them: ```rust impl FromVariant for Shape { type Value = Circle; - - fn from_variant(_tag: PhantomData, value: Self::Value) -> Self { + fn from_variant( + _tag: ::core::marker::PhantomData, + value: Self::Value, + ) -> Self { Self::Circle(value) } } - impl FromVariant for Shape { type Value = Rectangle; - - fn from_variant(_tag: PhantomData, value: Self::Value) -> Self { + fn from_variant( + _tag: ::core::marker::PhantomData, + value: Self::Value, + ) -> Self { Self::Rectangle(value) } } ``` -Each body is the plain constructor call, and there is no intermediate type, no marker, and no validation beyond -the type system's own check that the payload matches. Because the impls are distinguished *only* by their `Tag` -parameter, resolving a `from_variant` call comes down to which `Symbol!` the caller names: the compiler picks -the matching impl and inlines it to the corresponding constructor. So the generic call costs exactly what the -concrete one does. +Each body is the plain constructor call, without an intermediate type, a marker, or any check beyond +the type system's own that the payload matches. Because the impls are distinguished *only* by their +`Tag` parameter, resolving a `from_variant` call comes down to which `Symbol!` the caller names: the +compiler picks the matching impl and inlines it to the corresponding constructor. So the generic +call costs exactly what the concrete one does. -The trait itself is defined in the library; the derive supplies only these per-variant impls. Each is aimed at -the variant it came from, so a conflict with a hand-written impl underlines that variant rather than the whole -derive. +The trait itself is defined in the library; the derive supplies only these per-variant impls. Each +is spanned at the variant it came from, so a conflict with a hand-written impl underlines that +variant rather than the whole derive, as [Common Mistakes](#common-mistakes) shows. ## Common Mistakes -**The tag must be written out, not inferred.** `Shape::from_variant(PhantomData::, value)` -needs the turbofish, because nothing in the value determines the variant when two variants could share a payload -type. +**The tag must be written out whenever the enum has two or more variants.** With a bare +`PhantomData`: + +```rust +let _ = Shape::from_variant(PhantomData, Circle { radius: 1.0 }); +``` + +rustc does not pick the impl from the payload's type, since two variants could share one: + +```text +error[E0283]: type annotations needed +... +note: multiple `impl`s satisfying `Shape: cgp::prelude::FromVariant<_>` found +``` + +A one-variant enum has a single impl, so there the tag is inferred. **Two variants with the same payload type are distinguishable only by tag.** That is the reason for the previous point, and it means a mistyped tag is a missing-impl error rather than a type mismatch. -**A variant name is matched exactly.** `Symbol!("Circle")` and `Symbol!("circle")` are unrelated types, so a -case slip reports as an unsatisfied `FromVariant` bound. +**A variant name is matched exactly.** `Symbol!("Circle")` and `Symbol!("circle")` are unrelated +types, so `Shape::from_variant(PhantomData::, circle)` reports an unsatisfied +bound: + +```text +error[E0277]: the trait bound `Shape: cgp::prelude::FromVariant>>>>>>>` is not satisfied +``` + +**A hand-written impl for a variant the derive covers conflicts with it.** Adding +`impl FromVariant for Shape` beside the derive fails with `E0119`, and the +primary label sits on the variant: + +```text +error[E0119]: conflicting implementations of trait `cgp::prelude::FromVariant>>>>>>>` for type `Shape` +... +14 | Circle(Circle), + | ^^^^^^ conflicting implementation for `Shape` +``` **A variant named `Value` does not compile**, because the generated signature names the payload as `Self::Value`. The [derive's page](../../derives/derive_from_variant.md) covers this with the family's other diff --git a/docs/reference/traits/variant/has_extractor.md b/docs/reference/traits/variant/has_extractor.md index 42d7c216..55b99530 100644 --- a/docs/reference/traits/variant/has_extractor.md +++ b/docs/reference/traits/variant/has_extractor.md @@ -53,19 +53,30 @@ through [`#[derive(CgpVariant)]`](../../derives/derive_cgp_variant.md) and ## Examples -Starting a chain, which is `to_extractor`'s job: +Starting a chain, which is `to_extractor`'s job, and a round trip through `from_extractor`: ```rust -use cgp::core::field::traits::FinalizeExtractResult; use cgp::prelude::*; +use cgp::core::field::traits::FinalizeExtractResult; -#[derive(ExtractField)] +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(Debug, PartialEq, ExtractField)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } -fn area(shape: Shape) -> f64 { +pub fn area(shape: Shape) -> f64 { match shape.to_extractor().extract_field(PhantomData::) { Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, Err(remainder) => { @@ -76,18 +87,23 @@ fn area(shape: Shape) -> f64 { } } } -``` -`from_extractor` is the less common half, and it round-trips an un-narrowed extractor: +// Any extractable enum survives the round trip unchanged. +pub fn round_trip(value: E) -> E { + E::from_extractor(value.to_extractor()) +} -```rust -let extractor = shape.to_extractor(); -// ... inspect without extracting ... -let shape = Shape::from_extractor(extractor); +pub fn demo() { + assert_eq!(area(Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })), 12.0); + + let shape = Shape::Circle(Circle { radius: 2.0 }); + assert_eq!(round_trip(shape), Shape::Circle(Circle { radius: 2.0 })); +} ``` -Note that this only works on an extractor still at the all-possible configuration. Once a variant has -been ruled out the type has changed, and there is no way back. +`round_trip` works for any extractable enum because it never narrows: `from_extractor` accepts only +the all-possible extractor `to_extractor` returns. Once a variant has been ruled out the type has +changed, and the rebuild no longer applies. ## When to use it @@ -105,28 +121,36 @@ accessor otherwise; the weakest that works is the right one. ## Under the hood -The derive generates a companion enum with one [`MapType`](../type-level/map_type.md) parameter per variant, and this -trait fixes the starting configuration to all-possible: +The derive generates a companion enum with one [`MapType`](../type-level/map_type.md) parameter per +variant, and this trait fixes the starting configuration to all-possible. `cargo cgp expand` on the +example's `Shape` shows the impl: ```rust -pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { - Circle(<__F0__ as MapType>::Map), - Rectangle(<__F1__ as MapType>::Map), -} - impl HasExtractor for Shape { - type Extractor = __PartialShape; // every variant still possible - // ... + type Extractor = __PartialShape; + fn to_extractor(self) -> Self::Extractor { + match self { + Self::Circle(value) => __PartialShape::Circle(value), + Self::Rectangle(value) => __PartialShape::Rectangle(value), + } + } + fn from_extractor(extractor: Self::Extractor) -> Self { + match extractor { + __PartialShape::Circle(value) => Self::Circle(value), + __PartialShape::Rectangle(value) => Self::Rectangle(value), + } + } } ``` -Because `IsPresent::Map` is `T`, the all-possible companion holds exactly the enum's own payloads, so -`to_extractor` is a variant-for-variant move rather than a wrapping, and `from_extractor` is the same -move back. +Because `IsPresent::Map` is `T`, the all-possible companion holds exactly the enum's own payloads, +so `to_extractor` is a variant-for-variant move rather than a wrapping, and `from_extractor` is the +same move back. -The companion also implements [`PartialData`](../builder/partial_data.md), with `Target` naming the original enum, -which is how `from_extractor` knows what to rebuild, and the one trait the builder and extractor -families share directly. +The companion also implements [`PartialData`](../builder/partial_data.md), with `Target` naming the +original enum, so generic code holding an extractor can name the enum it came from; that is the one +trait the builder and extractor families share directly. `from_extractor` does not need it, since +its own `match` names every variant. Narrowing from here is [`ExtractField`](./extract_field.md), and the chain ends at [`FinalizeExtract`](./finalize_extract.md). @@ -137,10 +161,12 @@ Narrowing from here is [`ExtractField`](./extract_field.md), and the chain ends survive. This is the commonest over-requirement in the family. **`from_extractor` only accepts an un-narrowed extractor.** Once a variant is ruled out the type is -different and there is no rebuild, which is correct, since the value may no longer be representable. +different and the rebuild no longer applies, which is correct, since the value may no longer be +representable. -**The extractor carries none of the enum's attributes.** The companion is generated without your derives, -so it is neither `Debug` nor `PartialEq` however the enum is derived. +**The extractor carries none of the enum's attributes.** The companion is generated without your +derives, so it is neither `Debug` nor `PartialEq` however the enum is derived; +[`ExtractField`](./extract_field.md#common-mistakes) shows the error. **`Extractor` is not the enum.** A signature that returns `Self::Extractor` is returning a companion type, and naming it in a public API exposes a generated name. diff --git a/docs/reference/traits/variant/has_extractor_mut.md b/docs/reference/traits/variant/has_extractor_mut.md index 52e212fa..dd9738c0 100644 --- a/docs/reference/traits/variant/has_extractor_mut.md +++ b/docs/reference/traits/variant/has_extractor_mut.md @@ -1,6 +1,8 @@ --- +title: 'HasExtractorMut — edit a variant in place' sidebar_label: 'HasExtractorMut' sidebar_position: 4 +description: 'Obtain an extractor that borrows an enum mutably, so a named variant''s payload can be changed in place without consuming or rebuilding the value.' --- # `HasExtractorMut` @@ -38,11 +40,11 @@ pub trait HasExtractorMut { } ``` -`Self` is the enum. `ExtractorMut<'a>` is a **generic associated type**: the borrowed extractor over the -same partial companion enum, with every payload held as a mutable reference for `'a`. The `where Self: -'a` clause keeps it from outliving the value. `extractor_mut` takes a mutable borrow and returns the -extractor at the anonymous lifetime, so the call reads with no lifetime written and the borrow ends where -the extractor is dropped. +`Self` is the enum. `ExtractorMut<'a>` is a **generic associated type**: the borrowed extractor over +the same partial companion enum, with every payload held as a mutable reference for `'a`. The +`where Self: 'a` clause keeps it from outliving the value. `extractor_mut` takes a mutable borrow +and returns the extractor at the anonymous lifetime, so the call reads without a written lifetime +and the borrow ends where the extractor is dropped. ## Usage @@ -53,29 +55,54 @@ and shared-borrow accessors. ## Examples -Changing a payload without rebuilding the enum: +Changing whichever payload is present, without rebuilding the enum: ```rust use cgp::prelude::*; +use cgp::core::field::traits::FinalizeExtractResult; -#[derive(ExtractField)] +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(Debug, PartialEq, ExtractField)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } -if let Ok(circle) = shape - .extractor_mut() - .extract_field(PhantomData::) -{ - circle.radius = 5.0; +pub fn scale(shape: &mut Shape, factor: f64) { + match shape.extractor_mut().extract_field(PhantomData::) { + Ok(circle) => circle.radius *= factor, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width *= factor; + rect.height *= factor; + } + } } -// `shape` now holds the updated Circle +pub fn demo() { + let mut shape = Shape::Circle(Circle { radius: 1.0 }); + scale(&mut shape, 5.0); + + // `shape` now holds the updated `Circle`. + assert_eq!(shape, Shape::Circle(Circle { radius: 5.0 })); +} ``` -The payload arrives as `&mut Circle`, so the write lands in the original value. Written with -[`HasExtractor`](./has_extractor.md) instead, the same code would consume `shape` and have to rebuild it. +Each payload arrives as `&mut`, so the writes land in the original value, and the chain still ends +in a checked `finalize_extract_result`. Written with [`HasExtractor`](./has_extractor.md) instead, +the same code would consume `shape` and have to rebuild it. ## When to use it @@ -92,40 +119,54 @@ The payload arrives as `&mut Circle`, so the write lands in the original value. ## Under the hood -It uses the **same borrowed companion** as [`HasExtractorRef`](./has_extractor_ref.md#under-the-hood), -with the outer [`MapTypeRef`](../type-level/map_type_ref.md) marker fixed to `IsMut` rather than `IsRef`: +It uses the **same borrowed companion** as +[`HasExtractorRef`](./has_extractor_ref.md#under-the-hood), with the +[`MapTypeRef`](../type-level/map_type_ref.md) marker fixed to `IsMut` rather than `IsRef`. +`cargo cgp expand` on the example's `Shape` shows the impl: ```rust -// impl HasExtractorMut for Shape { -// type ExtractorMut<'a> = __PartialRefShape<'a, IsMut, IsPresent, IsPresent>; -// } +impl HasExtractorMut for Shape { + type ExtractorMut<'__a__> = __PartialRefShape<'__a__, IsMut, IsPresent, IsPresent> + where + Self: '__a__; + fn extractor_mut<'__a__>(&'__a__ mut self) -> Self::ExtractorMut<'__a__> { + match self { + Self::Circle(value) => __PartialRefShape::Circle(value), + Self::Rectangle(value) => __PartialRefShape::Rectangle(value), + } + } +} ``` Since `IsMut::Map<'a, T>` is `&'a mut T`, every payload slot becomes a mutable reference while the -per-variant [`MapType`](../type-level/map_type.md) markers continue to track possibility. That is the whole -difference between the two borrowing accessors: one marker. +per-variant [`MapType`](../type-level/map_type.md) markers continue to track possibility. That one +marker is the whole difference between the two borrowing accessors, and the same +[`ExtractField`](./extract_field.md) and [`FinalizeExtract`](./finalize_extract.md) impls serve +both. -There is no rebuild counterpart, and none is needed, because the value was never taken apart, only +The trait lacks a rebuild counterpart, and needs none, because the value was never taken apart, only borrowed. ## Common Mistakes -**It takes `&mut self`, so nothing else may borrow the value** for as long as the extractor lives. That is -ordinary borrow checking, but it surfaces as an error about the companion type, which reads as though the -machinery is at fault. +**It takes `&mut self`, so nothing else may borrow the value** for as long as the extractor or any +payload taken from it lives. That is ordinary borrow checking. **Payloads are `&mut T`, so a chain cannot move one out.** Taking ownership needs [`HasExtractor`](./has_extractor.md). -**There is no rebuild.** `from_extractor` belongs to the owning accessor alone. +**It cannot rebuild the enum.** `from_extractor` belongs to the owning accessor alone. **The `where Self: 'a` clause propagates**, so a signature holding an `ExtractorMut<'a>` rarely elides its lifetime cleanly. -**The three extractors are three different types.** Code generic over "an extractor" must pick one or be -generic over the [`MapTypeRef`](../type-level/map_type_ref.md) marker too. +**The owned and borrowed extractors are different enums.** The two borrowing accessors share +`__PartialRefShape` and differ in its [`MapTypeRef`](../type-level/map_type_ref.md) marker, while +the owned one is `__PartialShape`, so code generic over "an extractor" is generic over the extractor +type itself. -**A remainder still carries none of the enum's attributes.** +**A remainder still carries none of the enum's attributes**, so a `Result` holding one is neither +`Debug` nor `PartialEq`. ## Related constructs diff --git a/docs/reference/traits/variant/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md index b5ebd6af..8c7b043c 100644 --- a/docs/reference/traits/variant/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -1,6 +1,8 @@ --- +title: 'HasExtractorRef — extract through a borrow' sidebar_label: 'HasExtractorRef' sidebar_position: 3 +description: 'Obtain an extractor that borrows an enum, so its variants can be matched by name with payloads as shared references and the value left intact.' --- # `HasExtractorRef` @@ -48,35 +50,69 @@ and mutable accessors. ## Examples -Reading through a borrow leaves the value intact: +Reading through a borrow, as a single attempt and as a full chain, leaves the value intact: ```rust use cgp::prelude::*; +use cgp::core::field::traits::FinalizeExtractResult; -#[derive(ExtractField)] +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(Debug, PartialEq, ExtractField)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } -let radius = shape - .extractor_ref() - .extract_field(PhantomData::) - .map(|circle| circle.radius) - .ok(); +pub fn radius(shape: &Shape) -> Option { + shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok() +} + +pub fn area(shape: &Shape) -> f64 { + match shape.extractor_ref().extract_field(PhantomData::) { + Ok(circle) => core::f64::consts::PI * circle.radius * circle.radius, + Err(remainder) => { + let rect = remainder + .extract_field(PhantomData::) + .finalize_extract_result(); + rect.width * rect.height + } + } +} + +pub fn demo() { + let shape = Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 }); + assert_eq!(radius(&shape), None); + assert_eq!(area(&shape), 12.0); -// `shape` is still usable here + // `shape` is still usable here. + assert_eq!(shape, Shape::Rectangle(Rectangle { width: 3.0, height: 4.0 })); +} ``` -The payload arrives as `&Circle`, so `circle.radius` reads through the borrow and nothing is moved. A -full chain narrows the same way, with each remainder also borrowing. +The payloads arrive as `&Circle` and `&Rectangle`, so fields read through the borrow and nothing is +moved. The full chain narrows and finalizes exactly as an owned one does, with each remainder also +borrowing. ## When to use it **Reach for it whenever the value must survive**, which is most read-only code over an enum. -- **`HasExtractorRef`** for a read-only operation. Prefer it over consuming, since requiring ownership - narrows what a caller can pass for no benefit. +- **`HasExtractorRef`** for a read-only operation. Prefer it over consuming, since requiring + ownership narrows what a caller can pass without any benefit. - **[`HasExtractorMut`](./has_extractor_mut.md)** to change a payload in place. - **[`HasExtractor`](./has_extractor.md)** only when the payload must be moved out. - **A `match`** when the enum is concrete. This family is for code that cannot name it. @@ -85,34 +121,48 @@ full chain narrows the same way, with each remainder also borrowing. ## Under the hood -The borrowed accessor uses the **same partial enum** as the owning one, with an extra -[`MapTypeRef`](../type-level/map_type_ref.md) parameter fixed to `IsRef`: +The borrowing accessors use a **second companion enum**, `__PartialRefShape`, beside the owned +`__PartialShape`. `cargo cgp expand` on the example's `Shape` shows it: + +```rust +pub enum __PartialRefShape<'__a__, __R__: MapTypeRef, __F0__: MapType, __F1__: MapType> { + Circle(<__F0__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Circle>>), + Rectangle(<__F1__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Rectangle>>), +} +``` + +and this trait's impl, which fixes the [`MapTypeRef`](../type-level/map_type_ref.md) marker to +`IsRef` and every variant to still possible: ```rust -// conceptually -// -// pub enum __PartialRefShape<'a, R: MapTypeRef, F0: MapType, F1: MapType> { -// Circle(F0::Map>), -// Rectangle(F1::Map>), -// } -// -// impl HasExtractorRef for Shape { -// type ExtractorRef<'a> = __PartialRefShape<'a, IsRef, IsPresent, IsPresent>; -// } +impl HasExtractorRef for Shape { + type ExtractorRef<'__a__> = __PartialRefShape<'__a__, IsRef, IsPresent, IsPresent> + where + Self: '__a__; + fn extractor_ref<'__a__>(&'__a__ self) -> Self::ExtractorRef<'__a__> { + match self { + Self::Circle(value) => __PartialRefShape::Circle(value), + Self::Rectangle(value) => __PartialRefShape::Rectangle(value), + } + } +} ``` -Read the nesting outward: the [`MapTypeRef`](../type-level/map_type_ref.md) marker decides *how* a payload is held -(`IsRef::Map<'a, T>` is `&'a T`), and the per-variant [`MapType`](../type-level/map_type.md) markers decide *whether* -it is still possible. The two axes are independent, which is precisely why narrowing behaves the same -through a borrow as through an owned value. +Read the payload type outward: the [`MapTypeRef`](../type-level/map_type_ref.md) marker decides +*how* a payload is held (`IsRef::Map<'a, T>` is `&'a T`), and the per-variant +[`MapType`](../type-level/map_type.md) marker decides *whether* it is still possible. The two axes +are independent, which is why narrowing behaves the same through a borrow as through an owned value. +The derive emits the per-variant [`ExtractField`](./extract_field.md) impls and the all-`IsVoid` +[`FinalizeExtract`](./finalize_extract.md) impl on this enum too, generic over the `MapTypeRef` +marker, so a borrowed chain finalizes exactly as an owned one does. -There is no `from_extractor` counterpart here: a borrowed extractor cannot rebuild an owned enum, and the -original is still there anyway. +The trait lacks a `from_extractor` counterpart: a borrowed extractor cannot rebuild an owned enum, +and the original is still there anyway. ## Common Mistakes -**There is no rebuild.** [`HasExtractor`](./has_extractor.md)'s `from_extractor` has no borrowing -equivalent, which is rarely a problem since the value was never consumed. +**It cannot rebuild the enum.** [`HasExtractor`](./has_extractor.md)'s `from_extractor` lacks a +borrowing equivalent, which is rarely a problem since the value was never consumed. **Payloads are `&T`, so a chain cannot move one out.** A routine that must take ownership of a payload needs [`HasExtractor`](./has_extractor.md). @@ -123,8 +173,9 @@ has to spell the lifetime out rather than elide it. **A remainder still carries none of the enum's attributes**, so a `Result` holding one is neither `Debug` nor `PartialEq`. -**The borrowed and owned extractors are different types.** Code generic over "an extractor" has to pick -one, or be generic over the [`MapTypeRef`](../type-level/map_type_ref.md) marker as well. +**The borrowed and owned extractors are different enums**, `__PartialRefShape` and +`__PartialShape`. Code generic over "an extractor" is generic over the extractor type itself, with +[`ExtractField`](./extract_field.md) bounds on it, rather than over a marker. ## Related constructs diff --git a/docs/reference/traits/variant/index.md b/docs/reference/traits/variant/index.md index a57e0a91..b8a449b1 100644 --- a/docs/reference/traits/variant/index.md +++ b/docs/reference/traits/variant/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The traits that build an enum from one named variant and take one apart variant by variant, with exhaustiveness proven in the type rather than a wildcard.' --- # Extensible variants From d2efd5cc06f219e721ce1544df6024d376ab1db1 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 06:06:23 +0000 Subject: [PATCH 141/516] Fix leftover contradictions in the variant, casting, and builder pages Repairs a sentence a phrase rewrite broke on extract_field, states that the borrowed extractors are a separate companion enum in both Definitions, and corrects the claims that both upcast sides need a shape, that FromVariant makes the narrow enum upcastable, and that build_from and BuildAndMerge copy only the fields a source shares with its target. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../providers/dispatch/build_and_merge.md | 8 ++++---- docs/reference/traits/builder/build_field.md | 4 ++-- docs/reference/traits/builder/has_builder.md | 3 ++- docs/reference/traits/builder/take_field.md | 4 ++-- docs/reference/traits/casting/can_build_from.md | 4 ++-- .../traits/casting/can_downcast_fields.md | 11 ++++++----- docs/reference/traits/casting/can_upcast.md | 14 ++++++-------- .../traits/optional/can_build_with_default.md | 8 ++++---- docs/reference/traits/variant/extract_field.md | 6 +++--- docs/reference/traits/variant/finalize_extract.md | 9 +++++---- .../traits/variant/finalize_extract_result.md | 4 ++-- docs/reference/traits/variant/from_variant.md | 5 +++-- docs/reference/traits/variant/has_extractor.md | 10 +++++----- docs/reference/traits/variant/has_extractor_mut.md | 10 +++++----- docs/reference/traits/variant/has_extractor_ref.md | 10 +++++----- 15 files changed, 56 insertions(+), 54 deletions(-) diff --git a/docs/reference/providers/dispatch/build_and_merge.md b/docs/reference/providers/dispatch/build_and_merge.md index 183ca43a..e21b0e2e 100644 --- a/docs/reference/providers/dispatch/build_and_merge.md +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -1,13 +1,13 @@ --- title: 'BuildAndMerge — merge a built sub-record' -description: 'The builder step that builds a sub-record with a provider and copies every field it shares with the target into the partial record at once.' +description: 'The builder step that builds a sub-record with a provider and moves every one of its fields into the target''s partial record at once.' sidebar_label: 'BuildAndMerge' sidebar_position: 9 --- # `BuildAndMerge` -Build a sub-record and copy every field it shares with the target into the builder at once. +Build a sub-record and move every one of its fields into the target's builder at once. ## Overview @@ -190,8 +190,8 @@ builder has those fields marked present. The `TryComputer` and `Handler` impls r - [`BuildAndSetField`](build_and_set_field.md) — the step for one field. - [`BuildWithHandlers`](build_with_handlers.md) — runs a list of steps and finalizes. - [`BuildAndMergeOutputs`](build_and_merge_outputs.md) — adds this step to each provider in a list. -- [`CanBuildFrom`](../../traits/casting/can_build_from.md) — the trait that copies the shared - fields. +- [`CanBuildFrom`](../../traits/casting/can_build_from.md) — the trait that moves the sub-record's + fields into the builder. The ideas behind it: diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index fdff7758..ed030bc2 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -111,8 +111,8 @@ the record.** - **Bound on [`HasBuilder`](./has_builder.md) + `BuildField` + [`FinalizeBuild`](./finalize_build.md)** to write a routine that assembles a record it does not name. -- **Use [`CanBuildFrom`](../casting/can_build_from.md)** to copy every shared field from another record at once, - rather than one `build_field` per field. +- **Use [`CanBuildFrom`](../casting/can_build_from.md)** to copy every field of another record at + once, rather than one `build_field` per field. - **Use [`SetOptional`](../optional/set_optional.md)** when a field must be settable more than once. `build_field` consumes an absent slot exactly once by design; the optional layer relaxes that. - **Use [`UpdateField`](./update_field.md)** for a transition this does not cover. diff --git a/docs/reference/traits/builder/has_builder.md b/docs/reference/traits/builder/has_builder.md index 8487ffcf..56148551 100644 --- a/docs/reference/traits/builder/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -263,7 +263,8 @@ rather than anything called on a value. Starting from a value is [`IntoBuilder`] - [`UpdateField`](./update_field.md): the primitive both are built from. - [`PartialData`](./partial_data.md) and [`FinalizeBuild`](./finalize_build.md): naming the destination, and reaching it. -- [`CanBuildFrom`](../casting/can_build_from.md): merging every shared field from another record. +- [`CanBuildFrom`](../casting/can_build_from.md): merging every field of another record into the + builder. - [`#[derive(BuildField)]`](../../derives/derive_build_field.md): generates the partial type and every impl in the family. - [`MapType`](../type-level/map_type.md): the `IsPresent`/`IsNothing` markers presence is encoded in. diff --git a/docs/reference/traits/builder/take_field.md b/docs/reference/traits/builder/take_field.md index dfe38479..be266f96 100644 --- a/docs/reference/traits/builder/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -104,8 +104,8 @@ field taken out and not replaced cannot be forgotten silently. **Reach for it when a complete value must be decomposed**, and remember that the common case, merging one record into another, already uses it for you. -- **Use [`CanBuildFrom`](../casting/can_build_from.md)** to move every shared field from one record into another's - builder. It is this trait applied in a loop, written once. +- **Use [`CanBuildFrom`](../casting/can_build_from.md)** to move every field of one record into + another's builder. It is this trait applied in a loop, written once. - **Use `take_field`** when a *specific* field must be extracted from a partial value, typically after [`into_builder`](./into_builder.md). - **Use [`BuildField`](./build_field.md)** for the opposite direction. diff --git a/docs/reference/traits/casting/can_build_from.md b/docs/reference/traits/casting/can_build_from.md index 03a46b9b..5895decb 100644 --- a/docs/reference/traits/casting/can_build_from.md +++ b/docs/reference/traits/casting/can_build_from.md @@ -7,11 +7,11 @@ description: 'Move every field of one record into another record''s builder by f # `CanBuildFrom` -Filling a builder with every field it shares with another record. +Moving every field of one record into another record's builder. ## Overview -Assembling one struct out of several smaller ones means copying each shared field across by hand: a +Assembling one struct out of several smaller ones means copying each field across by hand: a line per field, repeated for every pair of types. `CanBuildFrom` derives that copying from the field names instead. diff --git a/docs/reference/traits/casting/can_downcast_fields.md b/docs/reference/traits/casting/can_downcast_fields.md index 78404872..8db35a68 100644 --- a/docs/reference/traits/casting/can_downcast_fields.md +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -36,14 +36,15 @@ pub trait CanDowncastFields { } ``` -`Target` is the enum being narrowed to. `Self` here is a *remainder* rather than an enum, and the method -takes it by value, returning `Result` as `downcast` does. The returned -`Remainder` is narrower again, so each call in a chain has a different, progressively smaller `Self` type. +`Target` is the enum being narrowed to. `Self` here is an extractor rather than an enum, in practice +the remainder a prior downcast returned, and the method takes it by value, returning +`Result` as `downcast` does. The returned `Remainder` is narrower again, so each +call in a chain has a different, progressively smaller `Self` type. ## Usage -**It is not in the prelude.** Import it from `cgp::core::field::impls`, alongside `CanDowncast`, which -you will always be using with it: +**It is not in the prelude.** Import it from `cgp::core::field::impls`, alongside `CanDowncast`, +which it nearly always follows: ```rust use cgp::core::field::impls::{CanDowncast, CanDowncastFields}; diff --git a/docs/reference/traits/casting/can_upcast.md b/docs/reference/traits/casting/can_upcast.md index f67cce4a..2b590288 100644 --- a/docs/reference/traits/casting/can_upcast.md +++ b/docs/reference/traits/casting/can_upcast.md @@ -15,9 +15,10 @@ Two enums defined independently can share variant names, say a small `FooBar` an Converting the narrow one into the wide one is a conversion you could write by hand, and it is pure boilerplate: one `match` arm per variant, rewrapping each payload under the same name. -`CanUpcast` derives that conversion from the names instead. Once both enums expose their shape as a -type-level list, which [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) makes them, widening is a -matter of routing each source variant to the target's slot of the same name. +`CanUpcast` derives that conversion from the names instead. Once the source exposes its variants as +a type-level list and the target can be built one variant at a time, widening is a matter of routing +each source variant to the target's slot of the same name; +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) on both provides everything. **It always succeeds.** Every variant of the source has a home in the target, or the conversion does not type-check at all, so `upcast` returns the target directly rather than a `Result`. That totality is the @@ -90,11 +91,8 @@ pub fn demo() { ``` Neither enum names the other. They share variant *names*, matched at the type level, and that is the -whole coupling. The source derives [`HasFields`](../shape/has_fields.md) and -[`ExtractField`](../../derives/derive_extract_field.md) because the cast walks it and takes it -apart; the target derives only [`FromVariant`](../../derives/derive_from_variant.md) because the -cast only builds into it. [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) on both covers -every case. +whole coupling. Each derives only its side of the cast, as [Usage](#usage) explains: the source is +walked and taken apart, and the target is only built into. ## When to use it diff --git a/docs/reference/traits/optional/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md index 6b59a8c4..270bf0c5 100644 --- a/docs/reference/traits/optional/can_build_with_default.md +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -2,7 +2,7 @@ title: 'CanBuildWithDefault — widen a record' sidebar_label: 'CanBuildWithDefault' sidebar_position: 6 -description: 'Build a wider record from a narrower one in one call, copying the shared fields by name and filling the rest from Default.' +description: 'Build a wider record from a narrower one in one call, copying the source''s fields by name and filling the rest from Default.' --- # `CanBuildWithDefault` @@ -11,9 +11,9 @@ Widening one record into another in a single call. ## Overview -Turning a narrow record into a wider one whose extra fields have sensible defaults is a three-step motion: -start a builder, copy the shared fields, default the rest. `CanBuildWithDefault` is that motion as one -call. +Turning a narrow record into a wider one whose extra fields have sensible defaults is a three-step +motion: start a builder, copy the source's fields, default the rest. `CanBuildWithDefault` is that +motion as one call. `Self` is the target record and `Source` the narrower one. **It is the field-level counterpart of an [upcast](../casting/can_upcast.md)**: turning a `Point2d` into a `Point3d` whose extra `z` is `0`, diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index d5dc4e49..6c86ae69 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -22,7 +22,7 @@ miss. Keep going and the remainder narrows. Once every variant has been ruled out its type is **uninhabited** (a value of it cannot exist), and [`FinalizeExtract`](./finalize_extract.md) closes -the chain with without a wildcard or a panic path. Add a variant to the enum and the final remainder +the chain without a wildcard or a panic path. Add a variant to the enum and the final remainder becomes inhabited again, so the code stops compiling until it is handled. The family is the mirror of the [builder](../builder/has_builder.md): a builder tracks which fields are *present*, @@ -126,8 +126,8 @@ the finalize is accepted without a wildcard arm. The type enforces this: finaliz first extraction and the code does not compile. The two functions try the variants in opposite orders, which works because each step changes only its own variant's marker. -**In practice you rarely write these chains.** The [dispatch -combinators](../../providers/dispatch/index.md) build them from a set of per-variant +**In practice you rarely write these chains.** The +[dispatch combinators](../../providers/dispatch/index.md) build them from a set of per-variant implementations, which is the extensible visitor pattern: a chain like the one above, generated, with one implementation per variant chosen by wiring. diff --git a/docs/reference/traits/variant/finalize_extract.md b/docs/reference/traits/variant/finalize_extract.md index 57a40b92..54dec02a 100644 --- a/docs/reference/traits/variant/finalize_extract.md +++ b/docs/reference/traits/variant/finalize_extract.md @@ -15,9 +15,8 @@ An [extraction chain](./extract_field.md) ends when every variant has been ruled 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, because a value to return it from cannot -exist: the method can only be called on something that cannot exist, so its body is an empty `match` -and no execution path reaches it. +**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`](../builder/finalize_build.md), and the two are sound for opposite reasons: a build @@ -45,7 +44,9 @@ all-ruled-out configuration of each partial enum, owned and borrowed. 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 come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md). +The impls on partial enums come from +[`#[derive(ExtractField)]`](../../derives/derive_extract_field.md); the library supplies the ones +for `Void` and `Infallible`. ## Examples diff --git a/docs/reference/traits/variant/finalize_extract_result.md b/docs/reference/traits/variant/finalize_extract_result.md index 7036743d..5d611589 100644 --- a/docs/reference/traits/variant/finalize_extract_result.md +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -94,8 +94,8 @@ pub fn demo() { ``` 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; [Common -Mistakes](#common-mistakes) shows the call one step early. +both variants have been tried, which makes it a proof rather than an assertion; the +[Common Mistakes](#common-mistakes) section shows the call one step early. ## When to use it diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index c8ebecb5..f7631ca8 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -138,8 +138,9 @@ whole test, and it is narrower than the extractor's, because most code decides w build at a site that can name it. - **Bound on it in a routine parameterized over the variant it produces.** Nothing else can do it. -- **Derive it to make a smaller enum upcastable into a larger one.** Casting between enums is built on these - constructors, so this lets an implementation work in a narrow local enum and widen the result. +- **Derive it on a wide enum so narrower enums can upcast into it.** An upcast builds each variant + into its target through these constructors, and asks nothing else of the target, so this lets an + implementation work in a narrow local enum and widen the result. - **Do not reach for it for an ordinary constructor call.** `Shape::Circle(circle)` is shorter, clearer, and generates nothing. The trait adds a *second* way to do the same thing, for callers that cannot use the first. - **Do not derive it alone if you also take the enum apart**, which is the usual case; reach for diff --git a/docs/reference/traits/variant/has_extractor.md b/docs/reference/traits/variant/has_extractor.md index 55b99530..d5d33955 100644 --- a/docs/reference/traits/variant/has_extractor.md +++ b/docs/reference/traits/variant/has_extractor.md @@ -34,11 +34,11 @@ pub trait HasExtractor { } ``` -`Self` is the enum. `Extractor` is the partial companion enum at its all-possible configuration, with -every variant still available. `to_extractor` **consumes** the value and yields an extractor whose -payloads are owned, which a chain needs when it will take a payload away. `from_extractor` reverses it, -rebuilding the enum from an extractor that was not narrowed, which is useful when a routine inspects a -value and hands it back unchanged. +`Self` is the enum. `Extractor` is the partial companion enum at its all-possible configuration, +with every variant still available. `to_extractor` **consumes** the value and yields an extractor +whose payloads are owned, which a chain needs when it will take a payload away. `from_extractor` +reverses it, rebuilding the enum from an extractor that was not narrowed, which lets generic code +that converted a value to its extractor hand the enum back when it does not go on to extract. ## Usage diff --git a/docs/reference/traits/variant/has_extractor_mut.md b/docs/reference/traits/variant/has_extractor_mut.md index dd9738c0..3aa13b70 100644 --- a/docs/reference/traits/variant/has_extractor_mut.md +++ b/docs/reference/traits/variant/has_extractor_mut.md @@ -40,11 +40,11 @@ pub trait HasExtractorMut { } ``` -`Self` is the enum. `ExtractorMut<'a>` is a **generic associated type**: the borrowed extractor over -the same partial companion enum, with every payload held as a mutable reference for `'a`. The -`where Self: 'a` clause keeps it from outliving the value. `extractor_mut` takes a mutable borrow -and returns the extractor at the anonymous lifetime, so the call reads without a written lifetime -and the borrow ends where the extractor is dropped. +`Self` is the enum. `ExtractorMut<'a>` is a **generic associated type**: the borrowed extractor, the +same companion enum [`HasExtractorRef`](./has_extractor_ref.md) uses, with every payload held as a +mutable reference for `'a`. The `where Self: 'a` clause keeps it from outliving the value. +`extractor_mut` takes a mutable borrow and returns the extractor at the anonymous lifetime, so the +call reads without a written lifetime and the borrow ends where the extractor is dropped. ## Usage diff --git a/docs/reference/traits/variant/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md index 8c7b043c..bbd5d700 100644 --- a/docs/reference/traits/variant/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -35,11 +35,11 @@ pub trait HasExtractorRef { } ``` -`Self` is the enum. `ExtractorRef<'a>` is a **generic associated type**: the borrowed extractor over the -same partial companion enum, with every payload held for the lifetime `'a`. The `where Self: 'a` clause -keeps the borrowed extractor from outliving the value it came from. `extractor_ref` takes a shared borrow -of the value and returns the extractor at the anonymous lifetime, which is why the call reads with no -lifetime written. +`Self` is the enum. `ExtractorRef<'a>` is a **generic associated type**: the borrowed extractor, a +second companion enum beside the owned one, with every payload held for the lifetime `'a`. The +`where Self: 'a` clause keeps the borrowed extractor from outliving the value it came from. +`extractor_ref` takes a shared borrow of the value and returns the extractor at the anonymous +lifetime, which is why the call reads without a written lifetime. ## Usage From 66225f28fadbc571ddecd77e832f518526c2eac4 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 06:30:14 +0000 Subject: [PATCH 142/516] Mirror the type-level, namespace, formatting, and monad trait pages Adds mirrors for the eleven pages that had none, rewrites the formatting mirrors around a demo() program, pins TransformMapFields' last-to-first order, and adds trybuild fixtures for each quoted mistake: MapFields::Output, a non-marker mapper, a transform missing a source state, a bare transform_map_fields call, a loop key without its variable, overriding a registered default or a namespace entry, StaticString on bare Chars, and Path! without its @. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../concat_path_common_mistakes_missing_at.rs | 6 ++ ...cat_path_common_mistakes_missing_at.stderr | 5 + ...common_mistakes_loop_key_omits_variable.rs | 39 ++++++++ ...on_mistakes_loop_key_omits_variable.stderr | 35 +++++++ ...on_mistakes_override_registered_default.rs | 41 +++++++++ ...istakes_override_registered_default.stderr | 20 ++++ ...ommon_mistakes_override_namespace_entry.rs | 37 ++++++++ ...n_mistakes_override_namespace_entry.stderr | 19 ++++ ...map_fields_common_mistakes_not_a_marker.rs | 9 ++ ...fields_common_mistakes_not_a_marker.stderr | 19 ++++ ...ields_common_mistakes_output_not_mapped.rs | 7 ++ ...s_common_mistakes_output_not_mapped.stderr | 16 ++++ ...tatic_string_common_mistakes_bare_chars.rs | 8 ++ ...c_string_common_mistakes_bare_chars.stderr | 18 ++++ ...ap_common_mistakes_missing_source_state.rs | 22 +++++ ...ommon_mistakes_missing_source_state.stderr | 32 +++++++ ...rm_map_fields_common_mistakes_bare_call.rs | 20 ++++ ...ap_fields_common_mistakes_bare_call.stderr | 42 +++++++++ .../tests/reference/traits/append_product.rs | 8 ++ .../tests/reference/traits/concat_path.rs | 21 +++-- .../tests/reference/traits/contains_value.rs | 33 +++++++ .../tests/reference/traits/default_impls1.rs | 64 +++++++++++++ .../tests/reference/traits/default_impls2.rs | 53 +++++++++++ .../reference/traits/default_namespace.rs | 49 ++++++++++ .../tests/reference/traits/lift_value.rs | 34 +++++++ .../tests/reference/traits/map_type.rs | 49 ++++++++++ .../tests/reference/traits/map_type_ref.rs | 65 +++++++++++++ example-code/tests/reference/traits/mod.rs | 11 +++ .../tests/reference/traits/monadic_bind.rs | 35 +++++++ .../tests/reference/traits/monadic_trans.rs | 34 +++++++ .../tests/reference/traits/static_format.rs | 39 +++++--- .../tests/reference/traits/static_string.rs | 33 ++++--- .../tests/reference/traits/transform_map.rs | 60 ++++++++++++ .../reference/traits/transform_map_fields.rs | 91 +++++++++++++++++++ 34 files changed, 1042 insertions(+), 32 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.rs create mode 100644 example-code/tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.rs create mode 100644 example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.rs create mode 100644 example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.rs create mode 100644 example-code/tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.rs create mode 100644 example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.rs create mode 100644 example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.rs create mode 100644 example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs create mode 100644 example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.stderr create mode 100644 example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs create mode 100644 example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr create mode 100644 example-code/tests/reference/traits/contains_value.rs create mode 100644 example-code/tests/reference/traits/default_impls1.rs create mode 100644 example-code/tests/reference/traits/default_impls2.rs create mode 100644 example-code/tests/reference/traits/default_namespace.rs create mode 100644 example-code/tests/reference/traits/lift_value.rs create mode 100644 example-code/tests/reference/traits/map_type.rs create mode 100644 example-code/tests/reference/traits/map_type_ref.rs create mode 100644 example-code/tests/reference/traits/monadic_bind.rs create mode 100644 example-code/tests/reference/traits/monadic_trans.rs create mode 100644 example-code/tests/reference/traits/transform_map.rs create mode 100644 example-code/tests/reference/traits/transform_map_fields.rs diff --git a/example-code/tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.rs b/example-code/tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.rs new file mode 100644 index 00000000..4b080f9b --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.rs @@ -0,0 +1,6 @@ +use cgp::prelude::*; + +// `Path!` needs its leading `@`. +pub type Outer = Path!(a.b); + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.stderr b/example-code/tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.stderr new file mode 100644 index 00000000..ddbbc1f1 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.stderr @@ -0,0 +1,5 @@ +error: expected `@` + --> tests/compile_fail/reference/traits/concat_path_common_mistakes_missing_at.rs:4:24 + | +4 | pub type Outer = Path!(a.b); + | ^ diff --git a/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.rs b/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.rs new file mode 100644 index 00000000..65801842 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.rs @@ -0,0 +1,39 @@ +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; +use core::fmt::Display; + +#[cgp_component(ShowImpl)] +#[prefix(@test in DefaultNamespace)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} + +#[cgp_impl(new ShowWithDisplay)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + value.to_string() + } +} + +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + // The key never mentions `T`, so the loop's impl leaves it unconstrained. + for in DefaultImpls1 { + @test.ShowImplComponent.String: Provider, + } + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.stderr b/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.stderr new file mode 100644 index 00000000..d8ab60c9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.stderr @@ -0,0 +1,35 @@ +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.rs:33:14 + | +33 | for in DefaultImpls1 { + | ^-- + | | + | unconstrained type parameter + | help: remove the unused type parameter `T` + +error[E0207]: the type parameter `Provider` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.rs:33:17 + | +33 | for in DefaultImpls1 { + | ^^^^^^^^ unconstrained type parameter + | +help: use the type parameter `Provider` in the `App` type and use it in the type definition + | +26 ~ pub struct App; +27 | +28 | delegate_components! { +29 ~ App { + | + +error[E0207]: the type parameter `Provider` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/traits/default_impls1_common_mistakes_loop_key_omits_variable.rs:33:17 + | +28 | / delegate_components! { +29 | | App { +30 | | namespace DefaultNamespace; +... | +33 | | for in DefaultImpls1 { + | | ^^^^^^^^ unconstrained type parameter +... | +37 | | } + | |_- help: remove the unused type parameter `Provider` diff --git a/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.rs b/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.rs new file mode 100644 index 00000000..3dcd39d6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.rs @@ -0,0 +1,41 @@ +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; +use core::fmt::Display; + +#[cgp_component(ShowImpl)] +#[prefix(@test in DefaultNamespace)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} + +#[cgp_impl(new ShowWithDisplay)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + value.to_string() + } +} + +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + // `String` already has a registered default, which the loop wires. + @test.ShowImplComponent.String: ShowWithDisplay, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.stderr b/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.stderr new file mode 100644 index 00000000..32bfb561 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.stderr @@ -0,0 +1,20 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor>>>>, PathCons>>, _, _>` for type `App` + --> tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.rs:37:33 + | +33 | @test.ShowImplComponent.T: Provider, + | - first implementation here +... +37 | @test.ShowImplComponent.String: ShowWithDisplay, + | ^^^^^^ conflicting implementation for `App` + | + = note: downstream crates may implement trait `cgp::prelude::IsProviderFor>>>>, cgp::prelude::PathCons>>, _, _>` for type `ShowString` + = note: downstream crates may implement trait `cgp::prelude::IsProviderFor>>>>, cgp::prelude::PathCons>>, _, _>` for type `ShowWithDisplay` + +error[E0119]: conflicting implementations of trait `DelegateComponent>>>>, PathCons>>>` for type `App` + --> tests/compile_fail/reference/traits/default_impls1_common_mistakes_override_registered_default.rs:37:33 + | +33 | @test.ShowImplComponent.T: Provider, + | - first implementation here +... +37 | @test.ShowImplComponent.String: ShowWithDisplay, + | ^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.rs b/example-code/tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.rs new file mode 100644 index 00000000..81f949c2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.rs @@ -0,0 +1,37 @@ +use cgp::core::component::DefaultImpls1; +use cgp::prelude::*; +use core::fmt::Display; + +#[cgp_component(ShowImpl)] +#[prefix(@test in DefaultNamespace)] +pub trait Show { + fn show(&self, value: &T) -> String; +} + +#[cgp_impl(new ShowString)] +#[default_impl(String in DefaultImpls1)] +impl ShowImpl { + fn show(&self, value: &String) -> String { + value.clone() + } +} + +#[cgp_impl(new ShowWithDisplay)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + value.to_string() + } +} + +pub struct App; + +delegate_components! { + App { + namespace DefaultNamespace; + + // The namespace already binds the component's own key to its path. + ShowImplComponent: ShowWithDisplay, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.stderr b/example-code/tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.stderr new file mode 100644 index 00000000..c38ebdbe --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.stderr @@ -0,0 +1,19 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` + --> tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.rs:33:9 + | +30 | namespace DefaultNamespace; + | ---------------- first implementation here +... +33 | ShowImplComponent: ShowWithDisplay, + | ^^^^^^^^^^^^^^^^^ conflicting implementation for `App` + | + = note: downstream crates may implement trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::RedirectLookup>>>>, cgp::prelude::PathCons>>` + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` + --> tests/compile_fail/reference/traits/default_namespace_common_mistakes_override_namespace_entry.rs:33:9 + | +30 | namespace DefaultNamespace; + | ---------------- first implementation here +... +33 | ShowImplComponent: ShowWithDisplay, + | ^^^^^^^^^^^^^^^^^ conflicting implementation for `App` diff --git a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.rs b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.rs new file mode 100644 index 00000000..0839c966 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.rs @@ -0,0 +1,9 @@ +use cgp::core::field::traits::MapFields; +use cgp::prelude::*; + +// A plain struct, with no `MapType` impl. +pub struct Wrapped; + +pub fn take(_fields: >::Mapped) {} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.stderr b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.stderr new file mode 100644 index 00000000..c7e3ab97 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.stderr @@ -0,0 +1,19 @@ +error[E0277]: the trait bound `Wrapped: MapType` is not satisfied + --> tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.rs:7:22 + | +7 | pub fn take(_fields: >::Mapped) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `MapType` is not implemented for `Wrapped` + --> tests/compile_fail/reference/traits/map_fields_common_mistakes_not_a_marker.rs:5:1 + | +5 | pub struct Wrapped; + | ^^^^^^^^^^^^^^^^^^ + = help: the following other types implement trait `MapType`: + IsNothing + IsOptional + IsPresent + IsVoid + ToBuildAndMergeHandler + TryPromoteProviders + = note: required for `Cons>` to implement `MapFields` diff --git a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.rs b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.rs new file mode 100644 index 00000000..0917dfa6 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.rs @@ -0,0 +1,7 @@ +use cgp::core::field::traits::MapFields; +use cgp::prelude::*; + +// `MapFields` names its result `Mapped`; `Output` belongs to the other two operations. +pub type Mapped = >::Output; + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr new file mode 100644 index 00000000..be482646 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr @@ -0,0 +1,16 @@ +error[E0576]: cannot find associated type `Output` in trait `MapFields` + --> tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.rs:5:64 + | +5 | pub type Mapped = >::Output; + | ^^^^^^ not found in `MapFields` + | + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/map_fields.rs:5:5 + | +5 | type Mapped; + | ----------- associated type `Mapped` defined here + | +help: maybe you meant this associated type + | +5 - pub type Mapped = >::Output; +5 + pub type Mapped = >::Mapped; + | diff --git a/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.rs b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.rs new file mode 100644 index 00000000..b41462df --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.rs @@ -0,0 +1,8 @@ +use cgp::core::base::types::Chars; +use cgp::core::field::traits::StaticString; +use cgp::prelude::*; + +// A bare character list, without the `Symbol` wrapper that carries its byte length. +pub const NAME: &str = as StaticString>::VALUE; + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr new file mode 100644 index 00000000..14f1765d --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr @@ -0,0 +1,18 @@ +error[E0277]: the trait bound `cgp::prelude::Chars<'a', cgp::prelude::Nil>: StaticString` is not satisfied + --> tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.rs:6:25 + | + 6 | pub const NAME: &str = as StaticString>::VALUE; + | ^^^^^^^^^^^^^^^ unsatisfied trait bound + | + = help: the trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` is not implemented for `cgp::prelude::Chars<'a', cgp::prelude::Nil>` +help: the following other types implement trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/static_string.rs:29:1 + | +29 | / impl StaticBytes for Symbol +30 | | where +31 | | Chars: MaybeChars, + | |______________________^ `Symbol` +... +36 | impl StaticBytes for Nil { + | ^^^^^^^^^^^^^^^^^^^^^^^^ `cgp::prelude::Nil` + = note: required for `cgp::prelude::Chars<'a', cgp::prelude::Nil>` to implement `StaticString` diff --git a/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs b/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs new file mode 100644 index 00000000..28ceb8d8 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs @@ -0,0 +1,22 @@ +use cgp::core::field::traits::{TransformMap, TransformMapFields}; +use cgp::prelude::*; + +// Only the `IsNothing` case, so a field that is already present has no conversion. +pub struct OnlyAbsent; + +impl TransformMap for OnlyAbsent { + fn transform_mapped(_value: ()) -> T { + T::default() + } +} + +#[derive(CgpData)] +pub struct Config { + pub port: u16, + pub verbose: bool, +} + +fn main() { + let partial = Config::builder().build_field(PhantomData::, 8080); + let _ = TransformMapFields::::transform_map_fields(partial); +} diff --git a/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.stderr b/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.stderr new file mode 100644 index 00000000..3e9aabb5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.stderr @@ -0,0 +1,32 @@ +error[E0271]: type mismatch resolving `<__PartialConfig as UpdateField>>>>, IsNothing>>::Mapper == IsNothing` + --> tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs:21:79 + | +21 | let _ = TransformMapFields::::transform_map_fields(partial); + | ----------------------------------------------------------------- ^^^^^^^ type mismatch resolving `<__PartialConfig as UpdateField>>>>, IsNothing>>::Mapper == IsNothing` + | | + | required by a bound introduced by this call + | +note: expected this to be `cgp::prelude::IsNothing` + --> tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs:13:10 + | +13 | #[derive(CgpData)] + | ^^^^^^^ + = note: required for `Cons>>>>, u16>, Cons>>>>>>>, bool>, Nil>>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialConfig, OnlyAbsent, cgp::prelude::IsPresent>` + = note: required for `__PartialConfig` to implement `TransformMapFields` + = note: this error originates in the derive macro `CgpData` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `OnlyAbsent: TransformMap` is not satisfied + --> tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs:21:13 + | +21 | let _ = TransformMapFields::::transform_map_fields(partial); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `TransformMap` is not implemented for `OnlyAbsent` + but trait `TransformMap` is implemented for it + --> tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs:7:1 + | + 7 | impl TransformMap for OnlyAbsent { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `cgp::prelude::IsNothing`, found `cgp::prelude::IsPresent` + = note: required for `Cons>>>>, u16>, Cons>>>>>>>, bool>, Nil>>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialConfig, OnlyAbsent, cgp::prelude::IsPresent>` + = note: required for `__PartialConfig` to implement `TransformMapFields` diff --git a/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs b/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs new file mode 100644 index 00000000..97232c3b --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs @@ -0,0 +1,20 @@ +use cgp::core::field::traits::{TransformMap, TransformMapFields}; +use cgp::prelude::*; + +pub struct Keep; + +impl TransformMap for Keep { + fn transform_mapped(value: T) -> T { + value + } +} + +#[derive(CgpData)] +pub struct Point { + pub x: u32, +} + +fn main() { + // Nothing here says which transform or target marker to use. + let _ = Point { x: 1 }.into_builder().transform_map_fields(); +} diff --git a/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr b/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr new file mode 100644 index 00000000..96332567 --- /dev/null +++ b/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr @@ -0,0 +1,42 @@ +error[E0283]: type annotations needed for `__PartialPoint<_>` + --> tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs:19:9 + | +19 | let _ = Point { x: 1 }.into_builder().transform_map_fields(); + | ^ -------------------- type must be known at this point + | + = note: the type must implement `MapType` + = help: the following types implement trait `MapType`: + IsNothing + IsOptional + IsVoid + ToBuildAndMergeHandler + TryPromoteProviders + cgp::prelude::IsPresent + = note: required for `Cons>, u32>, Nil>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialPoint, _, _>` + = note: required for `__PartialPoint` to implement `TransformMapFields<_, _>` +help: consider giving this pattern a type, where the type for type parameter `TargetMap` is specified + | +19 | let _: __PartialPoint<__M2__> = Point { x: 1 }.into_builder().transform_map_fields(); + | ++++++++++++++++++++++++ + +error[E0283]: type annotations needed + --> tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs:19:43 + | +19 | let _ = Point { x: 1 }.into_builder().transform_map_fields(); + | ^^^^^^^^^^^^^^^^^^^^ + | +note: multiple `impl`s satisfying `_: TransformMap` found + --> tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs:6:1 + | + 6 | impl TransformMap for Keep { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: and more `impl`s found in the following crates: `cgp_field_extra`: + - impl TransformMap for TransformOptional; + - impl TransformMap for TransformMapDefault; + = note: required for `Cons>, u32>, Nil>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialPoint, _, _>` + = note: required for `__PartialPoint` to implement `TransformMapFields<_, _>` +help: try using a fully qualified path to specify the expected types + | +19 - let _ = Point { x: 1 }.into_builder().transform_map_fields(); +19 + let _ = <__PartialPoint as TransformMapFields>::transform_map_fields(Point { x: 1 }.into_builder()); + | diff --git a/example-code/tests/reference/traits/append_product.rs b/example-code/tests/reference/traits/append_product.rs index 69bbf549..3b220d64 100644 --- a/example-code/tests/reference/traits/append_product.rs +++ b/example-code/tests/reference/traits/append_product.rs @@ -20,6 +20,14 @@ pub mod examples { fields } + /// A generic signature naming the shape a routine will produce. + pub fn with_extra_field() -> PhantomData<>::Output> + where + Fields: AppendProduct, + { + PhantomData + } + /// The base case the page states under *Using it*: appending onto `Nil` yields a one-element list. pub fn assert_nil_base_case( fields: >>::Output, diff --git a/example-code/tests/reference/traits/concat_path.rs b/example-code/tests/reference/traits/concat_path.rs index ff503089..a3f8d60b 100644 --- a/example-code/tests/reference/traits/concat_path.rs +++ b/example-code/tests/reference/traits/concat_path.rs @@ -1,8 +1,8 @@ -//! Code from `docs/reference/traits/concat_path.md` — *`ConcatPath`*. +//! Code from `docs/reference/traits/formatting/concat_path.md` — `ConcatPath`. //! -//! Paths are unsized markers, so there is no value to build: naming the joined type and coercing it -//! to the expected one is the check. The absence of any `use` beyond the prelude is the page's claim -//! that this trait, unlike its neighbours, is re-exported there. +//! Paths are unsized markers, so there is no value to build: the check is a type equality, and the +//! prelude-only import pins that the trait is re-exported there. `Path!` without its `@` is a +//! trybuild fixture. /// ## Examples pub mod examples { @@ -13,8 +13,17 @@ pub mod examples { pub type Joined = >::Output; - #[allow(dead_code)] - pub fn assert_joined(path: PhantomData<&Joined>) -> PhantomData<&Path!(@a.b.c.d)> { + // Compiles only if the joined path is `@a.b.c.d`. + pub fn assert_joined(path: PhantomData) -> PhantomData { path } + + // A generic signature naming the composed route. + pub fn descend( + ) -> PhantomData<>::Output> + where + Outer: ConcatPath, + { + PhantomData + } } diff --git a/example-code/tests/reference/traits/contains_value.rs b/example-code/tests/reference/traits/contains_value.rs new file mode 100644 index 00000000..310fc8d2 --- /dev/null +++ b/example-code/tests/reference/traits/contains_value.rs @@ -0,0 +1,33 @@ +//! Code from `docs/reference/traits/monad/contains_value.md` — `ContainsValue`. +//! +//! Pins the Examples program: the value each shipped marker reads beneath an output, including a +//! two-layer stack, checked as type equalities. + +/// ## Examples +pub mod examples { + use cgp::extra::monad::monadic::err::ErrMonadic; + use cgp::extra::monad::monadic::ident::IdentMonadic; + use cgp::extra::monad::monadic::ok::{OkMonadic, OkMonadicTrans}; + use cgp::extra::monad::traits::ContainsValue; + + pub fn ident(value: >::Value) -> u8 { + value + } + + // `ErrMonadic` continues on `Ok`, so the value is the `Ok` payload. + pub fn err(value: >>::Value) -> u8 { + value + } + + // `OkMonadic` continues on `Err`, so the value is the error. + pub fn ok(value: >>::Value) -> String { + value + } + + // The outer layer is `ErrMonadic`'s, the inner one the `Ok` layer's. + pub fn stacked( + value: as ContainsValue, bool>>>::Value, + ) -> String { + value + } +} diff --git a/example-code/tests/reference/traits/default_impls1.rs b/example-code/tests/reference/traits/default_impls1.rs new file mode 100644 index 00000000..32cc4bbd --- /dev/null +++ b/example-code/tests/reference/traits/default_impls1.rs @@ -0,0 +1,64 @@ +//! Code from `docs/reference/traits/namespace/default_impls1.md` — `DefaultImpls1`. +//! +//! Pins the Examples program: a provider registered as the `String` default with `#[default_impl]`, +//! a context pulling registered defaults in with a `for … in` loop, and a direct entry for a type the +//! registry does not cover. A loop whose key omits the loop variable is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::component::DefaultImpls1; + use cgp::prelude::*; + use core::fmt::Display; + + #[cgp_component(ShowImpl)] + #[prefix(@test in DefaultNamespace)] + pub trait Show { + fn show(&self, value: &T) -> String; + } + + #[cgp_impl(new ShowString)] + #[default_impl(String in DefaultImpls1)] + impl ShowImpl { + fn show(&self, value: &String) -> String { + format!("{value:?}") + } + } + + #[cgp_impl(new ShowWithDisplay)] + impl ShowImpl { + fn show(&self, value: &T) -> String { + value.to_string() + } + } + + pub struct App; + + delegate_components! { + App { + namespace DefaultNamespace; + + for in DefaultImpls1 { + @test.ShowImplComponent.T: Provider, + } + + // `u64` has no registered default, so the context supplies one. + @test.ShowImplComponent.u64: ShowWithDisplay, + } + } + + check_components! { + App { + ShowImplComponent: [String, u64], + } + } + + pub fn demo() { + assert_eq!(App.show(&"hi".to_owned()), "\"hi\""); + assert_eq!(App.show(&5u64), "5"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/default_impls2.rs b/example-code/tests/reference/traits/default_impls2.rs new file mode 100644 index 00000000..3f7609fe --- /dev/null +++ b/example-code/tests/reference/traits/default_impls2.rs @@ -0,0 +1,53 @@ +//! Code from `docs/reference/traits/namespace/default_impls2.md` — `DefaultImpls2`. +//! +//! Pins the Examples program: a two-parameter component, a provider registered under a pair with +//! `#[default_impl]`, and a context pulling every default for one fixed target in with a loop. + +/// ## Examples +pub mod examples { + use cgp::core::component::DefaultImpls2; + use cgp::prelude::*; + + #[cgp_component(Converter)] + #[prefix(@test in DefaultNamespace)] + pub trait CanConvert { + fn convert(&self, value: &Source) -> Target; + } + + #[cgp_impl(new ParseU64)] + #[default_impl(String in DefaultImpls2)] + impl Converter { + fn convert(&self, value: &String) -> u64 { + value.parse().unwrap_or_default() + } + } + + pub struct App; + + delegate_components! { + App { + namespace DefaultNamespace; + + // Every source type with a registered default into `u64`. + for in DefaultImpls2 { + @test.ConverterComponent.T.u64: Provider, + } + } + } + + check_components! { + App { + ConverterComponent: (String, u64), + } + } + + pub fn demo() { + let parsed: u64 = App.convert(&"42".to_owned()); + assert_eq!(parsed, 42); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/default_namespace.rs b/example-code/tests/reference/traits/default_namespace.rs new file mode 100644 index 00000000..82868ba1 --- /dev/null +++ b/example-code/tests/reference/traits/default_namespace.rs @@ -0,0 +1,49 @@ +//! Code from `docs/reference/traits/namespace/default_namespace.md` — `DefaultNamespace`. +//! +//! Pins the Examples program: a component registered into `DefaultNamespace` with `#[prefix]`, and +//! a context joining the namespace and filling the paths it leaves open. + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + use core::fmt::Display; + + #[cgp_component(ShowImpl)] + #[prefix(@test in DefaultNamespace)] + pub trait Show { + fn show(&self, value: &T) -> String; + } + + #[cgp_impl(new ShowWithDisplay)] + impl ShowImpl { + fn show(&self, value: &T) -> String { + value.to_string() + } + } + + pub struct App; + + delegate_components! { + App { + namespace DefaultNamespace; + + // The namespace routes the component to this path and binds nothing there. + @test.ShowImplComponent.u64: ShowWithDisplay, + } + } + + check_components! { + App { + ShowImplComponent: u64, + } + } + + pub fn demo() { + assert_eq!(App.show(&5u64), "5"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/lift_value.rs b/example-code/tests/reference/traits/lift_value.rs new file mode 100644 index 00000000..1da611e2 --- /dev/null +++ b/example-code/tests/reference/traits/lift_value.rs @@ -0,0 +1,34 @@ +//! Code from `docs/reference/traits/monad/lift_value.md` — `LiftValue`. +//! +//! Pins the Examples program: each shipped marker's two lifting functions, called directly. + +/// ## Examples +pub mod examples { + use cgp::extra::monad::monadic::err::ErrMonadic; + use cgp::extra::monad::monadic::ident::IdentMonadic; + use cgp::extra::monad::monadic::ok::OkMonadic; + use cgp::extra::monad::traits::LiftValue; + + pub fn demo() { + assert_eq!(>::lift_value(1), 1); + + // A bare value enters an `ErrMonadic` output as `Ok`, and an `OkMonadic` one as `Err`. + let lifted: Result = + >>::lift_value(1); + assert_eq!(lifted, Ok(1)); + + let lifted: Result = + >>::lift_value("no".to_owned()); + assert_eq!(lifted, Err("no".to_owned())); + + // An output already in the inner shape is forwarded unchanged. + let forwarded = + >>::lift_output(Err("stop".to_owned())); + assert_eq!(forwarded, Err("stop".to_owned())); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/map_type.rs b/example-code/tests/reference/traits/map_type.rs new file mode 100644 index 00000000..89e57207 --- /dev/null +++ b/example-code/tests/reference/traits/map_type.rs @@ -0,0 +1,49 @@ +//! Code from `docs/reference/traits/type-level/map_type.md` — `MapType`. +//! +//! Pins the Examples program: what each standard marker stores, checked as type equalities, a +//! generic function bounded on a marker, and a bound that pins the generic associated type. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::IsOptional; + use cgp::prelude::*; + + // Each function compiles only if the projection is the type on its right. + pub fn present(value: ::Map) -> String { + value + } + + pub fn nothing(value: ::Map) -> () { + value + } + + pub fn void(value: ::Map) -> Void { + value + } + + pub fn optional(value: ::Map) -> Option { + value + } + + // Generic over any marker, the way the builder and extractor families are. + pub fn store(value: M::Map) -> M::Map { + value + } + + // A bound that pins the storage names the generic associated type with its argument. + pub fn unwrap_present = String>>(value: M::Map) -> String { + value + } + + pub fn demo() { + assert_eq!(present("a".to_owned()), "a"); + assert_eq!(optional(None), None); + assert_eq!(store::(Some(1)), Some(1)); + assert_eq!(unwrap_present::("b".to_owned()), "b"); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/map_type_ref.rs b/example-code/tests/reference/traits/map_type_ref.rs new file mode 100644 index 00000000..28ea1d78 --- /dev/null +++ b/example-code/tests/reference/traits/map_type_ref.rs @@ -0,0 +1,65 @@ +//! Code from `docs/reference/traits/type-level/map_type_ref.md` — `MapTypeRef`. +//! +//! Pins the Examples program: what each standard marker stores at a lifetime, checked as type +//! equalities, and the two borrowed extractors whose outer marker is `IsRef` or `IsMut`. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::IsOwned; + use cgp::prelude::*; + + pub fn by_ref<'a>(value: ::Map<'a, String>) -> &'a String { + value + } + + pub fn by_mut<'a>(value: ::Map<'a, String>) -> &'a mut String { + value + } + + pub fn owned<'a>(value: ::Map<'a, String>) -> String { + value + } + + #[derive(Debug, PartialEq)] + pub struct Circle { + pub radius: f64, + } + + #[derive(Debug, PartialEq)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + #[derive(Debug, PartialEq, ExtractField)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub fn demo() { + let mut shape = Shape::Circle(Circle { radius: 1.0 }); + + // The outer marker is `IsRef`, so the payload comes out as `&Circle`. + let radius = shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok(); + assert_eq!(radius, Some(1.0)); + + // The outer marker is `IsMut`, so the payload comes out as `&mut Circle`. + if let Ok(circle) = shape + .extractor_mut() + .extract_field(PhantomData::) + { + circle.radius = 5.0; + } + assert_eq!(shape, Shape::Circle(Circle { radius: 5.0 })); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/mod.rs b/example-code/tests/reference/traits/mod.rs index a98eba9b..bf8f8471 100644 --- a/example-code/tests/reference/traits/mod.rs +++ b/example-code/tests/reference/traits/mod.rs @@ -17,6 +17,10 @@ pub mod can_upcast; pub mod can_use_component; pub mod concat_path; pub mod concat_product; +pub mod contains_value; +pub mod default_impls1; +pub mod default_impls2; +pub mod default_namespace; pub mod delegate_component; pub mod extract_field; pub mod field_getter; @@ -38,8 +42,13 @@ pub mod has_fields_ref; pub mod has_optional_builder; pub mod into_builder; pub mod is_provider_for; +pub mod lift_value; pub mod map_field; pub mod map_fields; +pub mod map_type; +pub mod map_type_ref; +pub mod monadic_bind; +pub mod monadic_trans; pub mod mut_field_getter; pub mod partial_data; pub mod set_optional; @@ -49,6 +58,8 @@ pub mod take_field; pub mod to_fields; pub mod to_fields_ref; pub mod to_optional; +pub mod transform_map; pub mod transform_map_default; +pub mod transform_map_fields; pub mod transform_optional; pub mod update_field; diff --git a/example-code/tests/reference/traits/monadic_bind.rs b/example-code/tests/reference/traits/monadic_bind.rs new file mode 100644 index 00000000..6ccbf3af --- /dev/null +++ b/example-code/tests/reference/traits/monadic_bind.rs @@ -0,0 +1,35 @@ +//! Code from `docs/reference/traits/monad/monadic_bind.md` — `MonadicBind`. +//! +//! Pins the Examples program: the bind provider each shipped marker wraps a continuation in, +//! checked as type equalities. + +/// ## Examples +pub mod examples { + use cgp::extra::monad::monadic::err::{BindErr, ErrMonadic}; + use cgp::extra::monad::monadic::ident::IdentMonadic; + use cgp::extra::monad::monadic::ok::{BindOk, OkMonadic}; + use cgp::extra::monad::traits::MonadicBind; + use cgp::prelude::*; + + // A continuation provider; any type stands in for one here. + pub struct Next; + + // Each function compiles only if the projection is the type on its right. + pub fn ident( + p: PhantomData<>::Provider>, + ) -> PhantomData { + p + } + + pub fn err( + p: PhantomData<>::Provider>, + ) -> PhantomData> { + p + } + + pub fn ok( + p: PhantomData<>::Provider>, + ) -> PhantomData> { + p + } +} diff --git a/example-code/tests/reference/traits/monadic_trans.rs b/example-code/tests/reference/traits/monadic_trans.rs new file mode 100644 index 00000000..b07c2a6e --- /dev/null +++ b/example-code/tests/reference/traits/monadic_trans.rs @@ -0,0 +1,34 @@ +//! Code from `docs/reference/traits/monad/monadic_trans.md` — `MonadicTrans`. +//! +//! Pins the Examples program: what applying each shipped marker as a transformer produces, checked as +//! type equalities. + +/// ## Examples +pub mod examples { + use cgp::extra::monad::monadic::err::{ErrMonadic, ErrMonadicTrans}; + use cgp::extra::monad::monadic::ident::IdentMonadic; + use cgp::extra::monad::monadic::ok::{OkMonadic, OkMonadicTrans}; + use cgp::extra::monad::traits::MonadicTrans; + use cgp::prelude::*; + + // `IdentMonadic` leaves the base unchanged. + pub fn ident( + m: PhantomData<>::M>, + ) -> PhantomData { + m + } + + // `OkMonadic` over `ErrMonadic`, the stack `PipeMonadic` builds for a fallible pipeline. + pub fn ok_over_err( + m: PhantomData<>::M>, + ) -> PhantomData> { + m + } + + // Transformers compose: the outer one wraps whatever the inner one produces. + pub fn nested( + m: PhantomData< as MonadicTrans>::M>, + ) -> PhantomData>> { + m + } +} diff --git a/example-code/tests/reference/traits/static_format.rs b/example-code/tests/reference/traits/static_format.rs index c265404c..8db73c74 100644 --- a/example-code/tests/reference/traits/static_format.rs +++ b/example-code/tests/reference/traits/static_format.rs @@ -1,30 +1,45 @@ -//! Code from `docs/reference/traits/static_format.md` — *`StaticFormat`*. +//! Code from `docs/reference/traits/formatting/static_format.md` — `StaticFormat`. //! -//! The page's central claim is a negative one: the trait cannot be named from the `cgp` crate, so its -//! effect is reachable only through `Display`. The absence of any `use` for it below is that claim, -//! and the bound in `describe` is the page's advice about what to require instead. +//! Pins the Examples program: formatting a type-level string through `Display`, a `Display` bound in +//! generic code, and the narrow case for the trait itself, a wrapper with no symbol value to format. /// ## Examples pub mod examples { + use core::fmt::{self, Display, Formatter}; + + use cgp::core::base::traits::StaticFormat; use cgp::prelude::*; - pub fn describe(_tag: PhantomData) -> String { + // A `Display` bound is all that formatting a name needs. + pub fn describe(_tag: PhantomData) -> String { format!("missing field `{}`", Tag::default()) } - #[test] - fn test_formatting_through_display() { - let s = ::default(); + // A wrapper holds only `PhantomData`, so it formats its tag through the trait. + pub struct FieldName(pub PhantomData); + impl Display for FieldName { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + Tag::fmt(f) + } + } + + pub fn demo() { + let s = ::default(); assert_eq!(s.to_string(), "hello"); assert_eq!(format!("field: {s}"), "field: hello"); - } - #[test] - fn test_a_display_bound_is_what_generic_code_requires() { assert_eq!( describe(PhantomData::), - "missing field `height`", + "missing field `height`" ); + + let name = FieldName(PhantomData::); + assert_eq!(format!("[{name}]"), "[width]"); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/traits/static_string.rs b/example-code/tests/reference/traits/static_string.rs index 381cc06e..c5dd92c8 100644 --- a/example-code/tests/reference/traits/static_string.rs +++ b/example-code/tests/reference/traits/static_string.rs @@ -1,29 +1,34 @@ -//! Code from `docs/reference/traits/static_string.md` — *`StaticString`*. +//! Code from `docs/reference/traits/formatting/static_string.md` — `StaticString`. //! -//! The page's snippets, run. The load-bearing check is the import path — the trait is not in the -//! prelude — and that the eager and lazy routes agree, including on multi-byte and empty symbols. +//! Pins the Examples program: a symbol decoded eagerly and lazily, multi-byte and empty symbols, and +//! a generic function naming its tag. `StaticString` on a bare `Chars` list is a trybuild fixture. /// ## Examples pub mod examples { - #[test] - fn test_both_recovery_routes() { - use cgp::core::field::traits::StaticString; - use cgp::prelude::*; + use cgp::core::field::traits::StaticString; + use cgp::prelude::*; + + // A generic routine recovers the name of whatever tag it is given. + pub fn field_name(_tag: PhantomData) -> &'static str { + Tag::VALUE + } + pub fn demo() { // eagerly, as a compile-time constant assert_eq!(::VALUE, "hello"); - // lazily, through Display + // lazily, through `Display`: reconstructed at the point of formatting let s = ::default(); assert_eq!(s.to_string(), "hello"); - } - - #[test] - fn test_multi_byte_and_empty() { - use cgp::core::field::traits::StaticString; - use cgp::prelude::*; assert_eq!(::VALUE, "世界你好"); assert_eq!(::VALUE, ""); + + assert_eq!(field_name(PhantomData::), "height"); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/traits/transform_map.rs b/example-code/tests/reference/traits/transform_map.rs new file mode 100644 index 00000000..e9ff3f17 --- /dev/null +++ b/example-code/tests/reference/traits/transform_map.rs @@ -0,0 +1,60 @@ +//! Code from `docs/reference/traits/type-level/transform_map.md` — `TransformMap`. +//! +//! Pins the Examples program: a transform marker with one impl per source state, applied to a +//! builder whose fields are present and absent. A transform missing a source state is a trybuild +//! fixture. + +/// ## Examples +pub mod examples { + use cgp::core::field::impls::IsOptional; + use cgp::core::field::traits::{TransformMap, TransformMapFields}; + use cgp::prelude::*; + + pub struct FillDefaults; + + impl TransformMap for FillDefaults { + fn transform_mapped(value: T) -> T { + value + } + } + + impl TransformMap for FillDefaults { + fn transform_mapped(_value: ()) -> T { + T::default() + } + } + + impl TransformMap for FillDefaults { + fn transform_mapped(value: Option) -> T { + value.unwrap_or_default() + } + } + + #[derive(Debug, PartialEq, CgpData)] + pub struct Config { + pub port: u16, + pub verbose: bool, + } + + pub fn with_defaults() -> Config { + let partial = Config::builder().build_field(PhantomData::, 8080); + + TransformMapFields::::transform_map_fields(partial) + .finalize_build() + } + + pub fn demo() { + assert_eq!( + with_defaults(), + Config { + port: 8080, + verbose: false, + } + ); + } + + #[test] + fn test_demo() { + demo(); + } +} diff --git a/example-code/tests/reference/traits/transform_map_fields.rs b/example-code/tests/reference/traits/transform_map_fields.rs new file mode 100644 index 00000000..cfe4730c --- /dev/null +++ b/example-code/tests/reference/traits/transform_map_fields.rs @@ -0,0 +1,91 @@ +//! Code from `docs/reference/traits/type-level/transform_map_fields.md` — `TransformMapFields`. +//! +//! Pins the Examples program: a transform applied by naming the trait at a concrete call site, and +//! through a bound in generic code. `under_the_hood` pins the walk's order, last declared field +//! first. Calling the method bare at a concrete site is a trybuild fixture. + +/// ## Examples +pub mod examples { + use cgp::core::field::traits::{TransformMap, TransformMapFields}; + use cgp::prelude::*; + + // Doubles every present number and keeps it present. + pub struct Double; + + impl + Copy> TransformMap for Double { + fn transform_mapped(value: T) -> T { + value + value + } + } + + #[derive(Debug, PartialEq, CgpData)] + pub struct Point { + pub x: u32, + pub y: u32, + } + + // At a concrete site, name the transform and the target marker on the trait. + pub fn doubled(point: Point) -> Point { + TransformMapFields::::transform_map_fields(point.into_builder()) + .finalize_build() + } + + // In generic code, the bound fixes both, so the method is called bare. + pub fn double_all(builder: Builder) -> Builder::Output + where + Builder: TransformMapFields, + { + builder.transform_map_fields() + } + + pub fn demo() { + assert_eq!(doubled(Point { x: 1, y: 2 }), Point { x: 2, y: 4 }); + + let point = double_all(Point { x: 3, y: 4 }.into_builder()).finalize_build(); + assert_eq!(point, Point { x: 6, y: 8 }); + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## Under the hood +/// +/// The walk recurses into the rest of the list first, so a transform with a side effect sees the +/// last declared field first. +pub mod under_the_hood { + use std::cell::RefCell; + + use cgp::core::field::traits::{TransformMap, TransformMapFields}; + use cgp::prelude::*; + + thread_local! { + static SEEN: RefCell> = const { RefCell::new(Vec::new()) }; + } + + pub struct Record; + + impl TransformMap for Record { + fn transform_mapped(value: u32) -> u32 { + SEEN.with(|seen| seen.borrow_mut().push(value)); + value + } + } + + #[derive(CgpData)] + pub struct Triple { + pub a: u32, + pub b: u32, + pub c: u32, + } + + #[test] + fn test_last_field_first() { + let builder = Triple { a: 1, b: 2, c: 3 }.into_builder(); + let _ = + TransformMapFields::::transform_map_fields(builder).finalize_build(); + SEEN.with(|seen| assert_eq!(*seen.borrow(), vec![3, 2, 1])); + } +} From 3bc300bec2431eb1afaae7048ef9e7c71603a67b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 06:30:14 +0000 Subject: [PATCH 143/516] Revise the type-level, namespace, formatting, and monad trait pages Adds front matter, ports each Examples section from its mirror, replaces the sketched listings with the real expansion and source, and quotes each mistake with its snippet. Corrects the ErrMonadic/OkMonadic bind providers, the role of ContainsValue, TransformMapFields' visit order and inference, ConcatPath's one consumer, StaticString's impls, and the DefaultImpls2 example; removes the Generated machinery notices from AppendProduct and ConcatProduct, which CGP never uses. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../traits/formatting/concat_path.md | 132 +++++++++------ docs/reference/traits/formatting/index.md | 8 +- .../traits/formatting/static_format.md | 108 +++++++----- .../traits/formatting/static_string.md | 120 ++++++++----- docs/reference/traits/monad/contains_value.md | 102 ++++++++---- docs/reference/traits/monad/index.md | 13 +- docs/reference/traits/monad/lift_value.md | 86 +++++++--- docs/reference/traits/monad/monadic_bind.md | 117 +++++++++---- docs/reference/traits/monad/monadic_trans.md | 105 ++++++++---- .../traits/namespace/default_impls1.md | 135 +++++++++++---- .../traits/namespace/default_impls2.md | 104 ++++++++---- .../traits/namespace/default_namespace.md | 118 ++++++++++--- docs/reference/traits/namespace/index.md | 1 + .../traits/type-level/append_product.md | 73 ++++---- .../traits/type-level/concat_product.md | 64 ++++--- docs/reference/traits/type-level/index.md | 12 +- .../reference/traits/type-level/map_fields.md | 70 ++++++-- docs/reference/traits/type-level/map_type.md | 70 +++++--- .../traits/type-level/map_type_ref.md | 116 ++++++++----- .../traits/type-level/transform_map.md | 91 +++++++--- .../traits/type-level/transform_map_fields.md | 157 +++++++++++++----- 21 files changed, 1226 insertions(+), 576 deletions(-) diff --git a/docs/reference/traits/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md index 3b3fb7ad..fe3bca7e 100644 --- a/docs/reference/traits/formatting/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -2,7 +2,7 @@ title: 'ConcatPath — join two type-level paths' sidebar_label: 'ConcatPath' sidebar_position: 3 -description: 'Join two type-level paths, which CGP''s namespace machinery uses to address a component. You are not expected to call it directly.' +description: 'Join two type-level paths, as the generated lookup behind namespaces and open does to append a component''s type parameters to its route.' --- # `ConcatPath` @@ -14,24 +14,26 @@ Joining two type-level paths. ### Generated machinery **You are not expected to call `ConcatPath` directly.** -[`cgp_namespace!`](../../macros/cgp_namespace.md) and [`RedirectLookup`](../../providers/redirect_lookup.md) -use it to extend a route one segment at a time, and [`ChainGetters`](../../providers/chain_getters.md) to -descend into a nested context. This page explains the operation, so that a composed path in an -expansion or an error message is legible. The one case for naming it is generic code that composes paths rather than writing one out. +[`#[cgp_component]`](../../macros/cgp_component.md) uses it in the +[`RedirectLookup`](../../providers/redirect_lookup.md) impl it generates for every component, to +append the component's type parameters to the lookup path that namespaces and the `open` statement +route along. This page explains the operation, so that a composed path in an expansion or an error +message is legible. The one case for naming it is generic code that composes paths rather than +writing one out. ::: ## Overview -A [`Path!`](../../macros/path.md) is a type-level list of segments: the route a namespaced component -lookup is redirected along, or the chain of field names a nested getter descends. Composing two such -routes means splicing one list onto the end of another, and `ConcatPath` is that operation. It is the -path-level analogue of [`ConcatProduct`](../type-level/concat_product.md), with the same two-impl -recursion over a different list. +A [`Path!`](../../macros/path.md) is a type-level list of segments: the route a namespaced or +`open`-dispatched component lookup is redirected along. Composing two such routes means splicing one +list onto the end of another, and `ConcatPath` is that operation. It is the path-level analogue of +[`ConcatProduct`](../type-level/concat_product.md), with the same two-impl recursion over a +different list. ## Definition -`ConcatPath` carries a single associated type and no method: +`ConcatPath` carries a single associated type and nothing else: ```rust pub trait ConcatPath { @@ -39,54 +41,60 @@ pub trait ConcatPath { } ``` -`Self` is the first path and `Other` the second, and `Output` is the first path's segments followed by -the second's. **Both sides may be unsized**, since path types are markers rather than types anything is -instantiated at. There is no method and no value: `ConcatPath` is a pure type-level computation resolved -during trait resolution, so it names the combined path type and nothing runs. +`Self` is the first path and `Other` the second, and `Output` is the first path's segments followed +by the second's. **Both sides may be unsized**, since path types are markers rather than types +anything is instantiated at. The trait has neither a method nor a value: `ConcatPath` is a pure +type-level computation resolved during trait resolution, so it names the combined path type and +nothing runs. ## Usage -**`ConcatPath` is in the prelude**: `use cgp::prelude::*;` names it, which makes it the one member of -the type-level recovery group that needs no import. Its two neighbours each need a different one: -[`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and +**`ConcatPath` is in the prelude**: `use cgp::prelude::*;` names it, which makes it the one member +of the type-level recovery group that comes with the prelude. Its two neighbours each need a +different one: [`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and [`StaticFormat`](./static_format.md), defined in the same crate as this trait, from `cgp::core::base::traits`. ## Examples -Two paths composed at the type level, which is the operation behind chaining nested accessors: +Two paths joined at the type level, and a generic signature naming a composed route: ```rust use cgp::prelude::*; -type Outer = Path!(@a.b); -type Inner = Path!(@c.d); +pub type Outer = Path!(@a.b); +pub type Inner = Path!(@c.d); -type Joined = >::Output; // the path @a.b.c.d -``` - -Note the leading `@`: [`Path!`](../../macros/path.md) requires it, and `Path!(a.b)` does not parse. +pub type Joined = >::Output; -In generic code the projection usually appears in a bound rather than a type alias, naming the route a -composed getter will take: +// Compiles only if the joined path is `@a.b.c.d`. +pub fn assert_joined(path: PhantomData) -> PhantomData { + path +} -```rust -fn descend() -> >::Output +// A generic signature naming the composed route. +pub fn descend( +) -> PhantomData<>::Output> where Outer: ConcatPath, { - todo!() + PhantomData } ``` +`assert_joined` compiles only because the joined path is `@a.b.c.d`. Note the leading `@`: +[`Path!`](../../macros/path.md) requires it, and `Path!(a.b)` does not parse. The `?Sized` bounds on +`descend` are needed because a path is an unsized marker. + ## When to use it -**Reach for it when composing paths in generic code**, which is nested-accessor territory. If you are -writing a path literally, [`Path!`](../../macros/path.md) already gives you the whole thing and there is -nothing to concatenate. +**Reach for it when composing paths in generic code**, which is rare outside the generated lookup +impls. If you are writing a path literally, [`Path!`](../../macros/path.md) already gives you the +whole thing and there is nothing to concatenate. -- **Use [`ChainGetters`](../../providers/chain_getters.md)** rather than composing paths by hand when the - goal is reaching a field on a nested context. That provider is the construct this operation serves. +- **Use [`ChainGetters`](../../providers/chain_getters.md)** to reach a field on a nested context. + It chains getters through a [`Product!`](../../macros/product.md) list, not a path, so this trait + is not involved. - **Use [`ConcatProduct`](../type-level/concat_product.md)** for field lists rather than paths. The two recursions are the same shape over different lists and are not interchangeable. - **Use [`StaticString`](./static_string.md)** if what you want is the segments as *text*. This produces @@ -94,8 +102,8 @@ nothing to concatenate. ## Under the hood -Two impls, one per list node. Each node keeps its head segment and rebuilds the tail; the terminator -becomes the other path outright: +Two impls, one per list node. Each node keeps its head segment and rebuilds the tail; the +terminator becomes the other path outright: ```rust impl ConcatPath for PathCons @@ -106,23 +114,50 @@ where } impl ConcatPath for Nil { - type Output = Other; // the second path is substituted whole + type Output = Other; } ``` -Note the `?Sized` on every parameter, including the associated type: that lets both operands -be the unsized markers a path is built from, and it is the one way this recursion differs from -[`ConcatProduct`](../type-level/concat_product.md)'s otherwise identical shape. +Note the `?Sized` on every parameter, including the associated type: that lets both operands be the +unsized markers a path is built from, and it is the one way this recursion differs from +[`ConcatProduct`](../type-level/concat_product.md)'s otherwise identical shape. So the result is the +first path's segments followed by the second's, in order, with the cost of resolution proportional +to the first path's length. + +Its one consumer shows the job. For a component `Show`, `#[cgp_component]` generates a +[`RedirectLookup`](../../providers/redirect_lookup.md) provider impl that appends `T` to the path it +was given before reading the table; `cargo cgp expand` shows the bounds: -So the result is the first path's segments followed by the second's, in order, with the cost of -resolution proportional to the first path's length. +```rust +impl<__Context__, T, __Components__, __Path__> ShowImpl<__Context__, T> +for RedirectLookup<__Components__, __Path__> +where + __Path__: ConcatPath, + __Components__: DelegateComponent<<__Path__ as ConcatPath>::Output>, + <__Components__ as DelegateComponent< + <__Path__ as ConcatPath>::Output, + >>::Delegate: ShowImpl<__Context__, T>, +{ + fn show(__context__: &__Context__, value: &T) -> String { + <__Components__ as DelegateComponent< + <__Path__ as ConcatPath>::Output, + >>::Delegate::show(__context__, value) + } +} +``` -It never touches a value; it only names the combined path type, which a getter or a -[`RedirectLookup`](../../providers/redirect_lookup.md) then uses to descend. +That is how `@test.ShowImplComponent` becomes `@test.ShowImplComponent.u64` for a `u64` value, the +key a namespaced or `open` entry is written at. ## Common Mistakes -**[`Path!`](../../macros/path.md) requires a leading `@`.** `Path!(a.b)` does not parse; `Path!(@a.b)` does. +**[`Path!`](../../macros/path.md) requires a leading `@`.** `Path!(@a.b)` parses, and +`pub type Outer = Path!(a.b);` fails with: + +```text +error: expected `@` +``` + This is the most common way an otherwise-correct `ConcatPath` example fails to build. **It produces a type, not a joined string.** This is path composition for trait resolution. If you want @@ -145,9 +180,10 @@ normalizes them. - [`StaticString`](./static_string.md): recovering a segment's name as text. - [`StaticFormat`](./static_format.md): the lazy formatting counterpart. - [`RedirectLookup`](../../providers/redirect_lookup.md): the provider that follows a path. -- [`ChainGetters`](../../providers/chain_getters.md): nested accessors, the setting path composition - serves. +- [`#[cgp_component]`](../../macros/cgp_component.md): generates the one impl that uses it. - [`cgp_namespace!`](../../macros/cgp_namespace.md): where paths key a namespace's entries. +- [`ChainGetters`](../../providers/chain_getters.md): nested accessors, which chain getters rather + than paths. The ideas behind it: diff --git a/docs/reference/traits/formatting/index.md b/docs/reference/traits/formatting/index.md index 0640742c..54b39474 100644 --- a/docs/reference/traits/formatting/index.md +++ b/docs/reference/traits/formatting/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The traits that recover type-level names and paths as runtime data: a symbol as a constant string, a symbol written into a formatter, and joined paths.' --- # Type-level strings and paths @@ -17,9 +18,10 @@ is the group's sharpest edge: one is in the prelude and the other two each need - [`StaticString`](static_string.md) decodes a [`Symbol!`](../../macros/symbol.md) into a compile-time `&'static str` constant. This is the one to reach for when you need a name as data. Import it from `cgp::core::field::traits`. -- [`StaticFormat`](static_format.md) writes a [type-level string](/docs/reference/glossary#type-level-string) into a formatter, and backs the - `Display` impl on `Symbol`, so a `Display` bound is usually all you need. Reach for the trait itself - only where there is no value to format. Import it from `cgp::core::base::traits`. +- [`StaticFormat`](static_format.md) writes a [type-level + string](/docs/reference/glossary#type-level-string) into a formatter, and backs the `Display` impl + on `Symbol`, so a `Display` bound is usually all you need. Reach for the trait itself only where a + value to format is missing. Import it from `cgp::core::base::traits`. - [`ConcatPath`](concat_path.md) joins two type-level [`Path!`](../../macros/path.md) routes, the path-level analogue of `ConcatProduct`. It is in the prelude. diff --git a/docs/reference/traits/formatting/static_format.md b/docs/reference/traits/formatting/static_format.md index 41b3d5af..6169d10b 100644 --- a/docs/reference/traits/formatting/static_format.md +++ b/docs/reference/traits/formatting/static_format.md @@ -1,6 +1,8 @@ --- +title: 'StaticFormat — write a type-level string' sidebar_label: 'StaticFormat' sidebar_position: 2 +description: 'Write a type-level string''s characters into a formatter without a value to format; the trait behind Display on Symbol and Chars.' --- # `StaticFormat` @@ -29,7 +31,7 @@ type-level string can be printed with `{}` or `to_string()` because of this trai ## Definition -`StaticFormat` carries a single associated function and no data: +`StaticFormat` carries a single associated function and nothing else: ```rust pub trait StaticFormat { @@ -37,7 +39,7 @@ pub trait StaticFormat { } ``` -Note the absent `self`: there is no runtime value, only the type, so `fmt` takes the formatter alone and +Note the absent `self`: the string exists only as a type, so `fmt` takes the formatter alone and writes the type's characters into it. The trait is implemented for the type-level string itself, by recursion over the character list, and the terminator writes nothing. @@ -54,8 +56,8 @@ neighbours: [`StaticString`](./static_string.md) comes from `cgp::core::field::t [`ConcatPath`](./concat_path.md), which lives in the same crate as this trait, is in the prelude. Three neighbouring traits, three different imports. -Most of the time you reach the effect rather than the trait. Any type-level string can be interpolated -or turned into an owned `String` with no import at all: +Most of the time you reach the effect rather than the trait. Any type-level string can be +interpolated or turned into an owned `String` without any import: ```rust use cgp::prelude::*; @@ -71,39 +73,48 @@ delegating to its inner list. Every type-level string therefore formats, includi ## Examples -A diagnostic or a log line wants formatting, where the name appears once. A `Display` bound is -usually enough, and needs no import: +Formatting through `Display`, a `Display` bound in generic code, and the one case for the trait +itself: ```rust +use core::fmt::{self, Display, Formatter}; use cgp::prelude::*; +use cgp::core::base::traits::StaticFormat; -fn describe(_tag: core::marker::PhantomData) -> String { +// A `Display` bound is all that formatting a name needs. +pub fn describe(_tag: PhantomData) -> String { format!("missing field `{}`", Tag::default()) } -let message = describe(core::marker::PhantomData::); +// A wrapper holds only `PhantomData`, so it formats its tag through the trait. +pub struct FieldName(pub PhantomData); -assert_eq!(message, "missing field `height`"); -``` +impl Display for FieldName { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + Tag::fmt(f) + } +} -You reach for the trait itself when there is no *value* to call `Display` on. The -method is an associated function, so it writes a type's characters without one: +pub fn demo() { + let s = ::default(); + assert_eq!(s.to_string(), "hello"); + assert_eq!(format!("field: {s}"), "field: hello"); -```rust -use cgp::core::base::traits::StaticFormat; + assert_eq!( + describe(PhantomData::), + "missing field `height`" + ); -fn write_name(f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - Tag::fmt(f) + let name = FieldName(PhantomData::); + assert_eq!(format!("[{name}]"), "[width]"); } ``` -For a name used more than once, the eager form is cheaper and is bounded differently again: - -```rust -use cgp::core::field::traits::StaticString; - -assert_eq!(::VALUE, "height"); -``` +`describe` needs nothing imported: a `Display` bound is all that formatting a name takes. +`FieldName` is the narrow case the trait exists for. It holds only a `PhantomData`, so there is no +symbol value to call `Display` on, and its own `Display` impl writes the tag's characters through +`Tag::fmt`. For a name used more than once, [`StaticString`](./static_string.md)'s constant is +cheaper. ## When to use it @@ -113,36 +124,53 @@ more than once, and this trait only when you need to write characters without a - **`Display` / `to_string()`** when the name goes straight into a message. This is what `StaticFormat` exists to power, and it is the form to prefer. - **[`StaticString`](./static_string.md)** for a constant, a key, or a comparison. It is computed at - compile time, so there is no per-call work. -- **`StaticFormat`** when a formatter has to be written into from a type with no value, such as - implementing `Display` for a wrapper over a type-level string. This is the narrow case, and it is why - the method takes no `self`. + compile time, so it costs nothing per call. +- **`StaticFormat`** when a formatter has to be written into from a type without a value, such as + implementing `Display` for a wrapper over a type-level string. This is the narrow case, and it is + why the method does not take `self`. - **[`ConcatPath`](./concat_path.md)** when the thing being composed is a path rather than a string. ## Under the hood -Each character node writes itself and defers to the tail: +Each character node writes itself and defers to the tail, and the terminator writes nothing: ```rust impl StaticFormat for Chars where Tail: StaticFormat, { - fn fmt(f: &mut Formatter<'_>) -> Result<(), fmt::Error> { + fn fmt(f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{CHAR}")?; Tail::fmt(f) } } -impl StaticFormat for Nil { /* writes nothing */ } +impl StaticFormat for Nil { + fn fmt(_f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + Ok(()) + } +} ``` -Because both `Symbol` and `Chars` implement `Display` by delegating to this, any type-level string can be -interpolated or turned into an owned `String`, and the string is *reconstructed* on each call rather -than read out of storage, since there is no `&str` inside a `Symbol` to read. +`Symbol` implements it by delegating to its inner character list, and both `Symbol` and `Chars` +implement `Display` by calling it: + +```rust +impl Display for Symbol +where + Self: StaticFormat, +{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(f) + } +} +``` -That per-call reconstruction is the difference from [`StaticString`](./static_string.md), which does the -same decoding once, at compile time, into a `&'static str` constant. +So any type-level string can be interpolated or turned into an owned `String`, and the string is +*reconstructed* on each call rather than read out of storage, since a `Symbol` does not store a +`&str` to read. That per-call reconstruction is the difference from +[`StaticString`](./static_string.md), which does the same decoding once, at compile time, into a +`&'static str` constant. ## Common Mistakes @@ -151,15 +179,15 @@ same decoding once, at compile time, into a `&'static str` constant. [`ConcatPath`](./concat_path.md), defined in the same crate as this one, is in the prelude. Reaching for the wrong module is the usual first failure. -**Prefer a `Display` bound where one will do.** Any code that only needs to *format* a type-level string -should require `Display`, which needs no import and is what the trait produces. +**Prefer a `Display` bound where one will do.** Any code that only needs to *format* a type-level +string should require `Display`, which needs nothing imported and is what the trait produces. **`Display` reconstructs the string on every call.** For a name used repeatedly, [`StaticString`](./static_string.md)'s `VALUE` is the cheaper choice. -**There is no `self`.** The trait's method is an associated function, because a type-level string has no -value. That is why the `Display` impl goes through a `Default`-constructed marker, and why you need a -bound on this trait when there is no value to construct. +**The method does not take `self`.** It is an associated function, because a type-level string +lacks a value. Formatting through `Display` therefore needs a value, which for a symbol is +`::default()`, and code holding only the type bounds on this trait instead. ## Related constructs diff --git a/docs/reference/traits/formatting/static_string.md b/docs/reference/traits/formatting/static_string.md index 8f906042..ae1aa1a0 100644 --- a/docs/reference/traits/formatting/static_string.md +++ b/docs/reference/traits/formatting/static_string.md @@ -1,6 +1,8 @@ --- +title: 'StaticString — a symbol as a &static str' sidebar_label: 'StaticString' sidebar_position: 1 +description: 'Decode a Symbol into a compile-time &''static str constant, the eager way to recover a field or variant name as data.' --- # `StaticString` @@ -18,11 +20,11 @@ against input. **This is the one of the three recovery traits to reach for.** Its sibling [`StaticFormat`](./static_format.md) recovers a name lazily by writing into a formatter, which backs -`Display`; reach for it only where there is no value to format and no constant will do. +`Display`; reach for it only where a value to format is missing and a constant will not do. ## Definition -`StaticString` carries a single associated constant and no method: +`StaticString` carries a single associated constant and nothing else: ```rust pub trait StaticString { @@ -30,10 +32,10 @@ pub trait StaticString { } ``` -`VALUE` is the decoded string as a constant, computed by const evaluation rather than at run time, so the -string is available wherever a `const` is, costs nothing per use, and can be compared or stored freely. -The trait is implemented for the type-level string itself and carries no method, because there is no -value to call one on. +`VALUE` is the decoded string as a constant, computed by const evaluation rather than at run time, +so the string is available wherever a `const` is, costs nothing per use, and can be compared or +stored freely. The trait is implemented for the type-level string itself and lacks a method, because +there is nothing to call one on. ## Usage @@ -44,48 +46,56 @@ use cgp::core::field::traits::StaticString; ``` `VALUE` is an associated constant rather than a method, so it is named through the trait: -`::VALUE`. There is no value to have and nothing to call. +`::VALUE`. Nothing needs a value or a call. -The impl is a blanket one over `Symbol`, so every type-level string has it, including the -empty one. +Every [`Symbol!`](../../macros/symbol.md) has it, including the empty one, and so does `Nil`, whose +value is `""`. A bare [`Chars`](../../types/chars.md) list does not, because the impl needs the byte +length only `Symbol` carries; [Common Mistakes](#common-mistakes) shows the error. ## Examples -Decoding a symbol, and the eager-versus-lazy pair side by side: +Decoding a symbol eagerly and lazily, multi-byte and empty symbols, and a generic routine naming its +tag: ```rust -use cgp::core::field::traits::StaticString; use cgp::prelude::*; +use cgp::core::field::traits::StaticString; -// eagerly, as a compile-time constant -assert_eq!(::VALUE, "hello"); +// A generic routine recovers the name of whatever tag it is given. +pub fn field_name(_tag: PhantomData) -> &'static str { + Tag::VALUE +} -// lazily, through Display: reconstructed at the point of formatting -let s = ::default(); -assert_eq!(s.to_string(), "hello"); -``` +pub fn demo() { + // eagerly, as a compile-time constant + assert_eq!(::VALUE, "hello"); -Multi-byte Unicode round-trips faithfully, and the empty symbol decodes to the empty string: + // lazily, through `Display`: reconstructed at the point of formatting + let s = ::default(); + assert_eq!(s.to_string(), "hello"); -```rust -assert_eq!(::VALUE, "世界你好"); -assert_eq!(::VALUE, ""); + assert_eq!(::VALUE, "世界你好"); + assert_eq!(::VALUE, ""); + + assert_eq!(field_name(PhantomData::), "height"); +} ``` -Where it shows up in real code is recovering a name for an error. The -[optional-field layer](../optional/finalize_optional.md)'s `finalize_optional` reports its missing field by -returning `Tag::VALUE`, the field's own name, as a static string, with no allocation. +Multi-byte Unicode round-trips faithfully and the empty symbol decodes to the empty string. +`field_name` is where the trait shows up in real code: the [optional-field +layer](../optional/finalize_optional.md)'s `finalize_optional` reports a missing field by returning +`Tag::VALUE`, the field's own name as a static string, with no allocation. ## When to use it **Reach for `StaticString` when you need a name as data, and for `Display` when you need it in a message.** That is the whole decision. -- **`StaticString`** for a constant, a key, a comparison, or anywhere the name is used more than once. It - is computed at compile time, so there is no per-call work. +- **`StaticString`** for a constant, a key, a comparison, or anywhere the name is used more than + once. It is computed at compile time, so it costs nothing per call. - **`Display` / `to_string()`** for one-off formatting, which is what - [`StaticFormat`](./static_format.md) powers. Bounding on that trait directly is for the narrow case - where there is no value to format. + [`StaticFormat`](./static_format.md) powers. Bounding on that trait directly is for the narrow + case where a value to format is missing. - **[`ConcatPath`](./concat_path.md)** when the thing being composed is a path rather than a string. Two things this is not for. It is **not a general string facility**: [`Symbol!`](../../macros/symbol.md) @@ -95,15 +105,32 @@ called, while [`HasField`](../field-access/has_field.md) reads its value. ## Under the hood -`StaticString` is const evaluation rather than a recursion at run time. It is a blanket impl over an -internal `StaticBytes` trait: `Symbol` computes a `[u8; LEN]` in a `const` block by walking -the character list and UTF-8-encoding each character into the array, and `VALUE` then validates those -bytes as UTF-8 and exposes the `&'static str`. +`StaticString` is const evaluation rather than a recursion at run time. It is a blanket impl over a +private `StaticBytes` trait, which only `Symbol` and `Nil` implement: -**That array is why `Symbol` carries a `LEN` at all.** A const-evaluated byte array must have a known -size, and the size cannot be computed from inside the const context by walking the list, so the macro -precomputes it. It is a *byte* length, which makes multi-byte Unicode round-trip correctly and makes -`LEN` disagree with the visible character count for any non-ASCII name. +```rust +impl StaticString for T +where + T: StaticBytes, +{ + const VALUE: &'static str = const { + match str::from_utf8(T::BYTES) { + Ok(value) => value, + Err(_) => panic!("error const decoding &[u8] to &str"), + } + }; +} +``` + +`Symbol`'s `BYTES` is a `[u8; LEN]` computed in a `const fn` by walking the character +list and UTF-8-encoding each character into the array, and `VALUE` then validates those bytes as +UTF-8 and exposes the `&'static str`. + +**That array is why `Symbol` carries a `LEN` at all.** A const-evaluated array's length must be a +constant known from the type, and stable Rust cannot compute it from the character list inside a +generic, so the macro precomputes it. It is a *byte* length, which makes multi-byte Unicode +round-trip correctly and makes `LEN` disagree with the visible character count for any non-ASCII +name. ## Common Mistakes @@ -111,16 +138,27 @@ precomputes it. It is a *byte* length, which makes multi-byte Unicode round-trip that do neighbouring jobs. Import `StaticString` from `cgp::core::field::traits`. **`VALUE` is a constant, so it is named through the trait.** Write -`::VALUE`; there is no method to call. +`::VALUE`; the trait lacks a method. **`LEN` on a `Symbol` is bytes, not characters.** They coincide for ASCII, so the distinction only surfaces on a non-ASCII name, where the number will not match the visible character count. -**`Display` reconstructs the string rather than reading a stored one.** There is no `&str` inside a -`Symbol`, so `to_string()` walks the type. For a name used repeatedly, `VALUE` is the cheaper choice. +**`Display` reconstructs the string rather than reading a stored one.** A `Symbol` does not store a +`&str`, so `to_string()` walks the type. For a name used repeatedly, `VALUE` is the cheaper choice. + +**It decodes a symbol, not a path or a bare character list.** A [`Path!`](../../macros/path.md) is a +list of segments; decoding one means decoding each segment's symbol. And a `Chars` list on its own, +without the `Symbol` wrapper that carries its byte length, lacks the impl: -**It decodes a symbol, not a path.** A [`Path!`](../../macros/path.md) is a list of segments; decoding one -means decoding each segment's symbol. +```rust +pub const NAME: &str = as StaticString>::VALUE; +``` + +```text +error[E0277]: the trait bound `cgp::prelude::Chars<'a', cgp::prelude::Nil>: StaticString` is not satisfied +... + = help: the trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` is not implemented for `cgp::prelude::Chars<'a', cgp::prelude::Nil>` +``` ## Related constructs diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index afad374f..3b8fbd3f 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -1,6 +1,8 @@ --- +title: 'ContainsValue — the value a monad threads' sidebar_label: 'ContainsValue' sidebar_position: 2 +description: 'The monad trait naming the value beneath a step''s output that the monad threads forward: the Ok payload under ErrMonadic, the error under OkMonadic.' --- # `ContainsValue` @@ -31,12 +33,12 @@ It is one of four traits that give a monad marker its meaning, and it pairs with back *in*. The other two, [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline rather than run a step of it. -**This is a plain trait, not a CGP component.** It has no generated provider trait and is +**This is a plain trait, not a CGP component.** It lacks a generated provider trait and is never wired. ## Definition -`ContainsValue` carries a single associated type and no method: +`ContainsValue` carries a single associated type and nothing else: ```rust pub trait ContainsValue { @@ -56,38 +58,53 @@ layer unwraps it further. use cgp::extra::monad::traits::ContainsValue; ``` -You import it only when **defining a monad of your own**. There is no method. The trait is a type-level -projection from an output type to the value beneath the wrapper. +You import it only when **defining a monad of your own**. The trait lacks a method: it is a +type-level projection from an output type to the value beneath the wrapper. ## Examples -What each marker's impl says decides how a pipeline behaves. +The value each shipped marker reads beneath an output, including a two-layer stack, checked as type +equalities: -**`IdentMonadic` is the identity**: `ContainsValue::Value` is `T`. Nothing is wrapped, so nothing is -unwrapped, and every value threads forward. +```rust +use cgp::extra::monad::monadic::err::ErrMonadic; +use cgp::extra::monad::monadic::ident::IdentMonadic; +use cgp::extra::monad::monadic::ok::{OkMonadic, OkMonadicTrans}; +use cgp::extra::monad::traits::ContainsValue; + +pub fn ident(value: >::Value) -> u8 { + value +} -**`ErrMonadic` and `OkMonadic` are mirror images over a `Result`**, and the mirroring is the whole design: +// `ErrMonadic` continues on `Ok`, so the value is the `Ok` payload. +pub fn err(value: >>::Value) -> u8 { + value +} -| Monad | `ContainsValue>::Value` | continue branch | -|---|---|---| -| `ErrMonadic` | `T` | the `Ok` payload threads forward | -| `OkMonadic` | `E` | the `Err` payload threads forward | +// `OkMonadic` continues on `Err`, so the value is the error. +pub fn ok(value: >>::Value) -> String { + value +} -So under `ErrMonadic` a step's continuation receives the `Ok` payload, the ordinary `?` behaviour, and -under `OkMonadic` it receives the `Err` payload, which is the inverted, run-until-something-succeeds -behaviour. +// The outer layer is `ErrMonadic`'s, the inner one the `Ok` layer's. +pub fn stacked( + value: as ContainsValue, bool>>>::Value, +) -> String { + value +} +``` -**The transformer forms peel one layer.** `OkMonadicTrans` and `ErrMonadicTrans` let `M` unwrap the -outer layers and then remove their own `Result` from the value `M` exposes, requiring -`M: ContainsValue>`. A two-layer -stack therefore unwraps two `Result` layers in order, and an *n*-layer stack unwraps *n*, with no code -specific to any depth. +Under `ErrMonadic` the value is the `Ok` payload and under `OkMonadic` the error, the mirror image +that is the whole design. The transformer form peels one layer after its base: `ErrMonadic` unwraps +the outer `Result` to `Result`, and the `Ok` layer then takes its error, `String`. An +*n*-layer stack unwraps *n* layers the same way, without code specific to any depth. ## When to use it -**Reach for the [monad providers](../../providers/monad/index.md), not this trait.** A pipeline is built -by wiring [`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker and a handler list; this is what -the bind providers bound on internally. +**Reach for the [monad providers](../../providers/monad/index.md), not this trait.** A pipeline is +built by wiring [`PipeMonadic`](../../providers/monad/pipe_monadic.md) with a marker and a handler +list; this is what the bind providers bound on internally, to relate each continuation's output to +the step's. The one real reason to name it is **defining a new monad**: short-circuiting over an `Option`, or over a custom two-branch enum. Implement it alongside [`LiftValue`](./lift_value.md), since the two are the pair @@ -100,17 +117,38 @@ of this. ## Under the hood -The [`BindOk` and `BindErr`](../../providers/monad/index.md) providers use `ContainsValue` in their -[`Computer`](../../components/handler/computer.md) and `AsyncComputer` impls. Running one bind step means: take the -step's output, ask the monad what value sits beneath its wrapper, and hand that to the continuation. This -trait is the second half of that sentence. +The bind providers bound on `ContainsValue` in their +[`Computer`](../../components/handler/computer.md) and `AsyncComputer` impls. `BindErr`'s, the step +`ErrMonadic` builds, is: + +```rust +#[cgp_provider] +impl Computer> for BindErr +where + Cont: Computer, + M: ContainsValue> + LiftValue, Cont::Output>, +{ + type Output = M::Output; + + fn compute(context: &Context, code: PhantomData, input: Result) -> Self::Output { + match input { + Ok(value) => M::lift_output(Cont::compute(context, code, value)), + Err(err) => M::lift_value(Err(err)), + } + } +} +``` -[`LiftValue`](./lift_value.md) then puts a result back into the output type: `lift_value` for the -branch that short-circuits, `lift_output` for the branch that forwarded to the continuation. So the two -traits bracket one step: unwrap, run, re-wrap. +The step matches the incoming `Result` itself; `ContainsValue` is not what unwraps it. What this +trait does is constrain the **continuation's output**: `M` is the monad the step sits inside +(`IdentMonadic` for a single-layer pipeline), and +`M: ContainsValue>` requires that what `M` sees beneath the +continuation's output is a `Result` with the same error type `E`. That is what lets the +short-circuit branch lift its `Err(err)` into the same output type the continue branch produces. -Because the transformer forms implement it by delegating to the base monad, the unwrapping composes -without any depth-specific code. +[`LiftValue`](./lift_value.md) is the other half of the bound, and supplies the two functions the +branches call. Because the transformer forms implement both by delegating to the base monad after +handling their own layer, the constraint composes without any depth-specific code. ## Common Mistakes diff --git a/docs/reference/traits/monad/index.md b/docs/reference/traits/monad/index.md index efb5e1db..aa3d2ec5 100644 --- a/docs/reference/traits/monad/index.md +++ b/docs/reference/traits/monad/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The four traits that give a monad marker its meaning in a monadic handler pipeline: how a step binds, which value continues, and how values are lifted.' --- # Monad interface @@ -9,13 +10,13 @@ The traits that give a monad marker its meaning for monadic handler composition. ## Overview -A [monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue or -short-circuit, the `?`-style behaviour, expressed as composable providers. A monad in CGP is a +A [monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue +or short-circuit, the `?`-style behaviour, expressed as composable providers. A monad in CGP is a zero-sized marker, and these four traits are what give that marker meaning. They are plain traits -rather than CGP components: they have no generated provider trait and are never wired. The -[monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a -pipeline at compile time, so you name a trait here only when defining a monad of your own. Import each -from `cgp::extra::monad::traits`. +rather than CGP components: they lack a generated provider trait and are never wired. The [monad +providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a pipeline +at compile time, so you name a trait here only when defining a monad of your own. Import each from +`cgp::extra::monad::traits`. They split into the pair that folds the pipeline and the pair that runs one step. diff --git a/docs/reference/traits/monad/lift_value.md b/docs/reference/traits/monad/lift_value.md index f5e4816f..0f778d55 100644 --- a/docs/reference/traits/monad/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -1,6 +1,8 @@ --- +title: 'LiftValue — wrap a value into an output' sidebar_label: 'LiftValue' sidebar_position: 3 +description: 'The monad trait that puts a value into a step''s output on either branch: lift_value for a short-circuit, lift_output for a continuation''s result.' --- # `LiftValue` @@ -30,7 +32,7 @@ It is the counterpart of [`ContainsValue`](./contains_value.md): that one says h output type, this one how to get back *in*. Together they run one step; the other two monad traits, [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline instead. -**This is a plain trait, not a CGP component.** It has no generated provider trait and is +**This is a plain trait, not a CGP component.** It lacks a generated provider trait and is never wired. ## Definition @@ -66,26 +68,38 @@ output type. ## Examples -What each marker's impl says decides how a pipeline behaves. +Each shipped marker's two lifting functions, called directly: -**`IdentMonadic` is the identity in both directions**: `LiftValue` returns `T` from both methods. -Nothing is wrapped, so a pipeline under it is plain function composition. +```rust +use cgp::extra::monad::monadic::err::ErrMonadic; +use cgp::extra::monad::monadic::ident::IdentMonadic; +use cgp::extra::monad::monadic::ok::OkMonadic; +use cgp::extra::monad::traits::LiftValue; + +pub fn demo() { + assert_eq!(>::lift_value(1), 1); -**`ErrMonadic` and `OkMonadic` mirror each other** over a `Result`, and the `lift_value` constructor is -where the mirroring shows: + // A bare value enters an `ErrMonadic` output as `Ok`, and an `OkMonadic` one as `Err`. + let lifted: Result = + >>::lift_value(1); + assert_eq!(lifted, Ok(1)); -| Monad | `lift_value` wraps with | continue branch | -|---|---|---| -| `ErrMonadic` | `Ok` | `Ok` | -| `OkMonadic` | `Err` | `Err` | + let lifted: Result = + >>::lift_value("no".to_owned()); + assert_eq!(lifted, Err("no".to_owned())); -So under `ErrMonadic` a bare value re-enters the pipeline as `Ok(value)`, the ordinary `?` behaviour, -and under `OkMonadic` as `Err(value)`. + // An output already in the inner shape is forwarded unchanged. + let forwarded = + >>::lift_output(Err("stop".to_owned())); + assert_eq!(forwarded, Err("stop".to_owned())); +} +``` -**Both methods matter, and conflating them changes behaviour silently.** `lift_value` is used where a -bare value is being wrapped for the first time; `lift_output` where a continuation has already produced -something in the inner shape and the step is passing it outward. Implementing the second as the first -collapses the two branches. +Under `ErrMonadic` a bare value enters the output as `Ok(value)` and under `OkMonadic` as +`Err(value)`, while `lift_output` forwards an output already in the inner shape unchanged. **Both +methods matter, and conflating them changes behaviour silently**: a bind step lifts the +short-circuit value with `lift_value` and forwards the continuation's result with `lift_output`, as +[Under the hood](#under-the-hood) shows. ## When to use it @@ -102,21 +116,41 @@ chain steps without a branch and involve none of this. ## Under the hood -The [`BindOk` and `BindErr`](../../providers/monad/index.md) providers use `LiftValue` in their -[`Computer`](../../components/handler/computer.md) and `AsyncComputer` impls, as the closing half of a step whose -opening half is [`ContainsValue`](./contains_value.md). The step unwraps the incoming output, decides -whether to short-circuit, and then lifts: +The bind providers use `LiftValue` in their [`Computer`](../../components/handler/computer.md) and +`AsyncComputer` impls, beside [`ContainsValue`](./contains_value.md). `BindErr`'s, the step +`ErrMonadic` builds, is: + +```rust +#[cgp_provider] +impl Computer> for BindErr +where + Cont: Computer, + M: ContainsValue> + LiftValue, Cont::Output>, +{ + type Output = M::Output; + + fn compute(context: &Context, code: PhantomData, input: Result) -> Self::Output { + match input { + Ok(value) => M::lift_output(Cont::compute(context, code, value)), + Err(err) => M::lift_value(Err(err)), + } + } +} +``` + +The step matches the incoming `Result`, then lifts with `M`, the monad it sits inside: -- on the **short-circuit** branch, the value never reached the continuation, so it is wrapped with - `lift_value`; -- on the **continue** branch, the continuation has already produced an inner output, so it is forwarded - with `lift_output`. +- on the **short-circuit** branch, the value never reached the continuation, so `Err(err)` is + wrapped with `lift_value`; +- on the **continue** branch, the continuation has already produced an output in the inner shape, so + it is forwarded with `lift_output`. That is the whole reason for two methods. A monad whose two methods agree, as `IdentMonadic`'s do, is one where the distinction happens to be vacuous, not one where it does not exist. -The transformer forms implement both by delegating to the base monad after handling their own layer, -which lets a stack lift through *n* layers with no depth-specific code. +The transformer forms implement both by delegating to the base monad after handling their own layer +(`ErrMonadicTrans`'s `lift_value` is `M::lift_value(Ok(value))`), which lets a stack lift through +*n* layers without depth-specific code. ## Common Mistakes diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index 0ed27034..4ff90ab6 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -1,6 +1,8 @@ --- +title: 'MonadicBind — build one bind step' sidebar_label: 'MonadicBind' sidebar_position: 1 +description: 'The monad trait that turns a continuation provider into the bind step running it, BindErr for ErrMonadic and BindOk for OkMonadic.' --- # `MonadicBind` @@ -31,15 +33,15 @@ It is one of four traits that give a monad marker its meaning, alongside [`ContainsValue`](./contains_value.md), [`LiftValue`](./lift_value.md), and [`MonadicTrans`](./monadic_trans.md). Keeping them apart lets one marker serve all four roles. -**This is a plain trait, not a CGP component.** It has no generated provider trait, no +**This is a plain trait, not a CGP component.** It lacks a generated provider trait and a `…Component` marker, and is never wired through -[`delegate_components!`](../../macros/delegate_components.md): the -[monad providers](../../providers/monad/index.md) consume it as an ordinary trait bound while folding a +[`delegate_components!`](../../macros/delegate_components.md): the [monad +providers](../../providers/monad/index.md) consume it as an ordinary trait bound while folding a pipeline at compile time. ## Definition -`MonadicBind` carries a single associated type and no method: +`MonadicBind` carries a single associated type and nothing else: ```rust pub trait MonadicBind { @@ -61,35 +63,59 @@ use cgp::extra::monad::traits::MonadicBind; ``` In practice you import it only when **defining a monad of your own**. Using the existing ones means -naming [`PipeMonadic`](../../providers/monad/pipe_monadic.md) and a marker in a wiring entry, with no trait in -sight. +naming [`PipeMonadic`](../../providers/monad/pipe_monadic.md) and a marker in a wiring entry, +without naming a trait. -There is no method. The whole trait is a type-level function from a continuation to the provider that +The trait lacks a method: it is a type-level function from a continuation to the provider that binds it. ## Examples -The trait is consumed rather than called, so read what each marker's impl *says*, because that decides -how a pipeline behaves. +The bind provider each shipped marker wraps a continuation in, checked as type equalities: -**`IdentMonadic` implements it as the identity**: `MonadicBind::Provider` is `Provider` -unchanged. Nothing wraps the continuation, nothing branches, and a pipeline under `IdentMonadic` is -therefore just function composition. +```rust +use cgp::prelude::*; +use cgp::extra::monad::monadic::err::{BindErr, ErrMonadic}; +use cgp::extra::monad::monadic::ident::IdentMonadic; +use cgp::extra::monad::monadic::ok::{BindOk, OkMonadic}; +use cgp::extra::monad::traits::MonadicBind; + +// A continuation provider; any type stands in for one here. +pub struct Next; + +// Each function compiles only if the projection is the type on its right. +pub fn ident( + p: PhantomData<>::Provider>, +) -> PhantomData { + p +} + +pub fn err( + p: PhantomData<>::Provider>, +) -> PhantomData> { + p +} + +pub fn ok( + p: PhantomData<>::Provider>, +) -> PhantomData> { + p +} +``` -**`ErrMonadic` and `OkMonadic` wrap the continuation in a bind provider**, and the two are mirror images -over a `Result`: +**`IdentMonadic` implements it as the identity**: the continuation comes back unchanged, so nothing +branches, and a pipeline under `IdentMonadic` is plain composition. **`ErrMonadic` and `OkMonadic` +wrap the continuation in a bind provider**, and the two are mirror images over a `Result`: | | continue branch | short-circuits on | bind provider | |---|---|---|---| -| `ErrMonadic` | `Ok` | `Err` | `BindOk` | -| `OkMonadic` | `Err` | `Ok` | `BindErr` | - -So `ErrMonadic` gives the ordinary `?` behaviour, and `OkMonadic` the inverted one that runs until -something succeeds, useful for a fallback chain. +| `ErrMonadic` | `Ok` | `Err` | `BindErr` | +| `OkMonadic` | `Err` | `Ok` | `BindOk` | -**The transformer forms delegate to their base.** `OkMonadicTrans` and `ErrMonadicTrans` wrap their -own bind provider for the inner `Result` layer and hand it to `M`, which binds the outer layers, and -that is how a stack reaches arbitrary depth. +Each bind provider is named for the branch it stops on. So `ErrMonadic` gives the ordinary `?` +behaviour, and `OkMonadic` the inverted one that runs until something succeeds, useful for a +fallback chain. **The transformer forms delegate to their base**: `ErrMonadicTrans` asks `M` to +bind a `BindErr`, which is how a stack reaches arbitrary depth. ## When to use it @@ -111,27 +137,46 @@ And the alternatives to prefer when you do *not* need short-circuiting: ## Under the hood -[`PipeMonadic`](../../providers/monad/pipe_monadic.md) walks the handler list and, for each step, asks the monad -to turn the continuation built so far into a bind step, which is this trait. Because the walk proceeds -from the end of the list backwards, `Provider` at each stage is everything that follows the current step, -and the result is a single nested provider by the time the list is exhausted. +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) folds its handler list with a private helper +trait, and this trait is what the fold asks at each step: + +```rust +impl BindProviders + for Cons> +where + Cons: BindProviders, + M: MonadicBind, +{ + type Provider = ComposeHandlers; +} + +impl BindProviders for Cons { + type Provider = Provider; +} +``` + +The fold recurses into the rest of the list first, so `OutProviders` at each stage is everything +that follows the current step, and the monad binds it: the first handler runs plainly and its output +is handed to a bind step over the rest. By the time the list is exhausted the result is one nested +provider, built from [`ComposeHandlers`](../../providers/handler/compose_handlers.md) and the bind +providers. -[`MonadicTrans`](./monadic_trans.md) is what applies one monad as a transformer over another while that -fold happens, so a stacked monad is resolved *before* any binding does. The pair is therefore the -list-folding half of the four traits, while [`ContainsValue`](./contains_value.md) and -[`LiftValue`](./lift_value.md) are the step-running half. +For the fallible components, `PipeMonadic` first stacks the chosen monad over `ErrMonadic` with +[`MonadicTrans`](./monadic_trans.md), so a stacked monad is resolved *before* any binding does. The +pair is therefore the list-folding half of the four traits, while +[`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) are the step-running half. -The whole fold happens during trait resolution. A monadic pipeline is not a runtime structure, and the -provider it resolves to implements the [`Computer`](../../components/handler/computer.md) family like any other -handler. +The whole fold happens during trait resolution. A monadic pipeline is not a runtime structure, and +the provider it resolves to implements the [`Computer`](../../components/handler/computer.md) family +like any other handler. ## Common Mistakes **It is not in the prelude.** Import from `cgp::extra::monad::traits`. -**It is not a component and cannot be wired.** There is no `…Component` marker, so it never appears in a -[`delegate_components!`](../../macros/delegate_components.md) block. What gets wired is the provider that -consumes it. +**It is not a component and cannot be wired.** It lacks a `…Component` marker, so it never appears +in a [`delegate_components!`](../../macros/delegate_components.md) block. What gets wired is the +provider that consumes it. **`OkMonadic` short-circuits on `Ok`, not on `Err`.** The naming reads as "the monad *for* `Ok`" and means "the monad whose continue branch is `Err`". [`ErrMonadic`](../../providers/monad/index.md) is the one diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index d10cd204..42bc1c0c 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -2,7 +2,7 @@ title: 'MonadicTrans — stack one monad on another' sidebar_label: 'MonadicTrans' sidebar_position: 4 -description: 'Stack one monad on top of another, which the monadic handler combinators resolve for you rather than asking you to name the stack yourself.' +description: 'The monad trait applying one monad as a transformer over another, so a pipeline can peel a nested Result; PipeMonadic uses it for fallible steps.' --- # `MonadicTrans` @@ -31,12 +31,12 @@ It is one of four traits that give a monad marker its meaning, and it belongs wi composed provider, while [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) run each step. -**This is a plain trait, not a CGP component.** It has no generated provider trait and is +**This is a plain trait, not a CGP component.** It lacks a generated provider trait and is never wired. ## Definition -`MonadicTrans` carries a single associated type and no method: +`MonadicTrans` carries a single associated type and nothing else: ```rust pub trait MonadicTrans { @@ -57,32 +57,50 @@ the err monad handles the outer `Result` of each output, and the ok layer the `R use cgp::extra::monad::traits::MonadicTrans; ``` -You import it only when **defining a monad of your own**, and specifically when giving it a transformer -form so it can stack. There is no method; the trait is a type-level function from a base monad to a -composed one. +You import it only when **defining a monad of your own**, and specifically when giving it a +transformer form so it can stack. The trait lacks a method: it is a type-level function from a base +monad to a composed one. ## Examples -What each marker's impl says decides how deeply a pipeline can reach. +What applying each shipped marker as a transformer produces, checked as type equalities: -**`IdentMonadic` returns `M` unchanged**, so applying it as a transformer changes nothing, which makes -it the neutral element of a stack as well as of a pipeline. +```rust +use cgp::prelude::*; +use cgp::extra::monad::monadic::err::{ErrMonadic, ErrMonadicTrans}; +use cgp::extra::monad::monadic::ident::IdentMonadic; +use cgp::extra::monad::monadic::ok::{OkMonadic, OkMonadicTrans}; +use cgp::extra::monad::traits::MonadicTrans; -**The transformer forms compose.** `OkMonadicTrans` and `ErrMonadicTrans` implement the running -traits by letting `M` unwrap the outer layers and then peeling their own `Result` from the value `M` -exposes, and their `MonadicTrans` impls compose in the same order, so a stack like -`OkMonadicTrans` resolves layer by layer: +// `IdentMonadic` leaves the base unchanged. +pub fn ident( + m: PhantomData<>::M>, +) -> PhantomData { + m +} -```rust -// conceptually: ErrMonadic unwraps the outer Result, -// then the Ok layer handles the Result inside it -type Stacked = OkMonadicTrans; -``` +// `OkMonadic` over `ErrMonadic`, the stack `PipeMonadic` builds for a fallible pipeline. +pub fn ok_over_err( + m: PhantomData<>::M>, +) -> PhantomData> { + m +} -An *n*-layer stack unwraps *n* layers with no code specific to any depth, which is the whole payoff. +// Transformers compose: the outer one wraps whatever the inner one produces. +pub fn nested( + m: PhantomData< as MonadicTrans>::M>, +) -> PhantomData>> { + m +} +``` -**Layer order is meaningful.** `OkMonadicTrans` and `ErrMonadicTrans` unwrap their -`Result` layers in opposite orders and are not interchangeable. +`IdentMonadic` leaves the base unchanged, so it is the neutral element of a stack as well as of a +pipeline. `OkMonadic` over `ErrMonadic` is the stack +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) builds for a fallible pipeline: the err layer +handles the outer `Result` of each output and the ok layer the `Result` inside it. And the +transformer forms compose, so a stack resolves layer by layer. **Layer order is meaningful**: +`OkMonadicTrans` and `ErrMonadicTrans` unwrap their `Result` layers in +opposite orders. ## When to use it @@ -95,26 +113,47 @@ The reasons to name it are narrow. - **Defining a new monad that should stack.** The three other traits give a marker meaning on its own; this one lets it sit over another. A marker without it works as a base monad and cannot be a transformer. -- **Reading a stacked marker in an error.** A resolution failure over a nested result usually names this - trait, and knowing it is the composition step rather than the running step tells you the - problem is the stack's shape rather than a step's types. +- **Reading a stacked marker in an error.** A fallible pipeline's types carry an + `OkMonadicTrans`-shaped stack that `PipeMonadic` built with this trait, and knowing it + is the composition step rather than the running step helps read the bound. If your pipeline runs over a single-layer output, you do not need a transformer at all. Use the base marker directly. ## Under the hood -`MonadicTrans` is applied to the **monads** rather than to the handlers, and it runs *before* any binding -does. [`PipeMonadic`](../../providers/monad/pipe_monadic.md) resolves the stacked monad first, then walks the -handler list asking [`MonadicBind`](./monadic_bind.md) to turn each continuation into a bind step. +`MonadicTrans` is applied to the **monads** rather than to the handlers, and it runs *before* any +binding does. Its one consumer is [`PipeMonadic`](../../providers/monad/pipe_monadic.md)'s wiring +for the fallible components, which stacks the chosen monad over `ErrMonadic` and promotes each +handler first: + +```rust +delegate_components! { + < + Provider, + M1: MonadicTrans, + M2, + ProvidersA: MapFields, + ProvidersB: BindProviders, + > + PipeMonadic { + TryComputerComponent: TryPromote, + HandlerComponent: TryPromote, + } +} +``` + +A `TryComputer` step returns `Result`, so under a user's monad `M1` its outputs carry +one more `Result` layer, the context's error; stacking `M1` over `ErrMonadic` lets the error layer +short-circuit on that while `M1` handles the layer inside. The `Computer` and `AsyncComputer` +entries use the chosen monad directly. Because the transformer forms implement [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) by delegating to the base monad after handling their own layer, a two-layer stack unwraps two `Result` layers in order and re-wraps them in reverse, and the same code -serves any depth. That is the sense in which stacking is composition rather than a special case: the -resolved stack is just another marker, and everything downstream treats it as one. - -The whole fold happens during trait resolution, so a stacked monadic pipeline is not a runtime structure. +serves any depth. The resolved stack is another marker, and everything downstream treats it as +one. The whole fold happens during trait resolution, so a stacked monadic pipeline is not a runtime +structure. ## Common Mistakes @@ -130,8 +169,8 @@ short-circuits on the wrong layer. which reads oddly in a projection like `>::M` and is easy to misread when debugging a bound. -**A base marker without this impl cannot be transformed.** The error names the missing `MonadicTrans` -bound rather than saying the marker is not stackable. +**A base marker without this impl cannot be transformed**, so a monad of your own used with a +fallible pipeline needs it even if you never stack it by hand. **A new monad needs all four traits**, and this one only if it should stack. diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index 9ed4300f..0c7f9db3 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -1,6 +1,8 @@ --- +title: 'DefaultImpls1 — a per-type namespace default' sidebar_label: 'DefaultImpls1' sidebar_position: 2 +description: 'The lookup trait for a namespace default keyed on a component and one type, which default_impl registers into and a for loop reads back.' --- # `DefaultImpls1` @@ -27,7 +29,7 @@ needs: the same component resolving differently for `String` than for `u64`. ## Definition -`DefaultImpls1` carries a single associated type and no method: +`DefaultImpls1` carries a single associated type and nothing else: ```rust pub trait DefaultImpls1 { @@ -37,7 +39,8 @@ pub trait DefaultImpls1 { `Self` is the key being looked up, the *instance* type, such as `String`. `T` is the further lookup type, which the attribute fills with the component name. `Components` is the table the lookup runs -against, and `Delegate` is the resolved provider. There is no method and no data, so resolving a default +against, and `Delegate` is the resolved provider. The trait has +neither a method nor data, so resolving a default projects `Delegate` from the matching impl, exactly as with [`DelegateComponent`](../wiring/delegate_component.md). @@ -82,19 +85,20 @@ impl DefaultImpls1 for String { The rule that governs this comes from the attribute rather than the trait, and once you have it the positions stop being surprising. **`#[default_impl(Key in NamespacePath)]` makes `Key` the impl's -`Self`** and appends the table parameter to whatever `NamespacePath` names, so the leading arguments are -simply whatever you wrote inside the path. The same rule is why the `for … in` loop's bound reads -`T: DefaultImpls1`, with the loop variable in the `Self` position. +`Self`** and appends the table parameter to whatever `NamespacePath` names, so the leading arguments +are whatever you wrote inside the path. The same rule is why the `for … in` loop's bound reads +`T: DefaultImpls1`, with the loop variable in the `Self` +position. ## Examples -The whole chain, from a provider declaring itself a default to a context pulling it in and adding an entry -for a type the registry does not cover: +The whole chain, from a provider declaring itself the `String` default to a context pulling +registered defaults in and adding an entry for a type the registry does not cover: ```rust -use cgp::core::component::DefaultImpls1; -use cgp::prelude::*; use core::fmt::Display; +use cgp::prelude::*; +use cgp::core::component::DefaultImpls1; #[cgp_component(ShowImpl)] #[prefix(@test in DefaultNamespace)] @@ -106,14 +110,17 @@ pub trait Show { #[default_impl(String in DefaultImpls1)] impl ShowImpl { fn show(&self, value: &String) -> String { - value.clone() + format!("{value:?}") } } -``` -Then the context: +#[cgp_impl(new ShowWithDisplay)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + value.to_string() + } +} -```rust pub struct App; delegate_components! { @@ -124,18 +131,32 @@ delegate_components! { @test.ShowImplComponent.T: Provider, } - @test.ShowImplComponent.u64: ShowWithDisplay, // u64 has no registered default + // `u64` has no registered default, so the context supplies one. + @test.ShowImplComponent.u64: ShowWithDisplay, } } + +check_components! { + App { + ShowImplComponent: [String, u64], + } +} + +pub fn demo() { + assert_eq!(App.show(&"hi".to_owned()), "\"hi\""); + assert_eq!(App.show(&5u64), "5"); +} ``` -**[Environmental context](/docs/reference/glossary#environmental-context), [parameter-targeted](/docs/reference/glossary#parameter-targeted-component).** `App` carries the wiring and the shown value is a -parameter. The loop wires every type with a registered default by projecting -`T: DefaultImpls1`. Only `String` has a registered default, -so the direct `u64` line adds a type beside it. Had `u64` a registered default too, the loop's impl and -the direct entry would both cover its path, and the compiler would reject them with `E0119`. +**[Environmental context](/docs/reference/glossary#environmental-context), +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component).** `App` carries the +wiring and the shown value is a parameter. The loop wires every type with a registered default by +projecting `T: DefaultImpls1`. Only `String` has a +registered default, so the direct `u64` line adds a type beside it; had `u64` a registered default +too, the loop's impl and the direct entry would both cover its path, and the compiler would reject +them, as [Common Mistakes](#common-mistakes) shows. -A whole namespace can also be the loop target: +A whole namespace can also be the loop target. After ```rust cgp_namespace! { @@ -145,8 +166,8 @@ cgp_namespace! { } ``` -Pointing `for in DefaultShowComponents { … }` at this wires the listed types through the -same projection. +a `for in DefaultShowComponents { … }` loop wires the listed types through the same +projection. ## When to use it @@ -174,24 +195,44 @@ body of the crate that owns it, or into a local namespace that inherits the fore ## Under the hood A `for in DefaultImpls1 { … }` loop emits a -[`DelegateComponent`](../wiring/delegate_component.md) impl whose `where` clause projects the default: +[`DelegateComponent`](../wiring/delegate_component.md) impl, with its +[`IsProviderFor`](../wiring/is_provider_for.md) pair, whose `where` clause projects the default. +`cargo cgp expand` on the example's `App` shows the first: ```rust -where T: DefaultImpls1 +impl< + __Wildcard__, + T, + Provider, +> DelegateComponent< + PathCons>>, +> for App +where + T: DefaultImpls1, +{ + type Delegate = Provider; +} ``` Read it as: for each type `T` that has a default, wire that key to the projected `Provider`. - **Because the loop variables appear only in that bound and in the key, the key must mention `T`**, -otherwise the parameter is unconstrained and the compiler rejects the impl with `E0207`, which reads as a -puzzling error about a generic parameter rather than about the loop. +otherwise the parameters are unconstrained and the compiler rejects the impl with `E0207`, which +reads as a puzzling error about generic parameters rather than about the loop. -The registration side is the mirror. [`#[default_impl]`](../../attributes/default_impl.md) emits an impl of -this trait for the key type, carrying **only** the parameters naming the key and provider plus the table, -never the provider's own `where` clause. A provider whose bounds come from `#[use_type]`, `#[uses]`, -`#[implicit]`, or `#[use_provider]` therefore registers cleanly, because those bounds stay on the -provider's impl and its [`IsProviderFor`](../wiring/is_provider_for.md), and are checked when a real context -resolves it. +The registration side is the mirror. [`#[default_impl]`](../../attributes/default_impl.md) emits an +impl of this trait for the key type: + +```rust +impl<__Components__> DefaultImpls1 for String { + type Delegate = ShowString; +} +``` + +It carries **only** the parameters naming the key and provider plus the table, never the provider's +own `where` clause. A provider whose bounds come from `#[use_type]`, `#[uses]`, `#[implicit]`, or +`#[use_provider]` therefore registers cleanly, because those bounds stay on the provider's impl and +its [`IsProviderFor`](../wiring/is_provider_for.md), and are checked when a real context resolves +it. ## Common Mistakes @@ -201,13 +242,35 @@ resolves it. **`Self` is the instance type, not the component.** The parameter names suggest otherwise. Read `#[default_impl(Key in Path)]` as "`Key` becomes `Self`" and the positions follow. -**A `for … in` loop's key must mention the loop variable**, or the impl is rejected with `E0207`. +**A `for … in` loop's key must mention the loop variable.** Writing a fixed type where the variable +belongs: + +```rust +for in DefaultImpls1 { + @test.ShowImplComponent.String: Provider, +} +``` + +leaves both loop variables unconstrained: + +```text +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates +... +error[E0207]: the type parameter `Provider` is not constrained by the impl trait, self type, or predicates +``` **`#[default_impl]` on a prefixed component is confined to the namespace's crate**, by the orphan rule. Put downstream wiring in the namespace body instead. -**A registered default cannot be overridden from the context.** A direct entry for a type the loop -already wires overlaps the loop's impl and is rejected with `E0119`. +**A registered default cannot be overridden from the context.** Adding +`@test.ShowImplComponent.String: ShowWithDisplay` beside the example's loop, for a type the loop +already wires through its registered default, overlaps the loop's impl: + +```text +error[E0119]: conflicting implementations of trait `IsProviderFor>>>>, PathCons>>, _, _>` for type `App` +... +error[E0119]: conflicting implementations of trait `DelegateComponent>>>>, PathCons>>>` for type `App` +``` **The registration impl carries none of the provider's bounds**, which is deliberate: they are checked where the provider is used rather than where it is registered. diff --git a/docs/reference/traits/namespace/default_impls2.md b/docs/reference/traits/namespace/default_impls2.md index 86dfa608..7e150dc0 100644 --- a/docs/reference/traits/namespace/default_impls2.md +++ b/docs/reference/traits/namespace/default_impls2.md @@ -1,6 +1,8 @@ --- +title: 'DefaultImpls2 — a default keyed on two types' sidebar_label: 'DefaultImpls2' sidebar_position: 3 +description: 'The lookup trait for a namespace default keyed on a component and a pair of types, reachable through default_impl and a for loop.' --- # `DefaultImpls2` @@ -25,7 +27,7 @@ per-type default needs. `DefaultImpls2` is the same idea under a **pair** of typ ## Definition -`DefaultImpls2` carries a single associated type and no method: +`DefaultImpls2` carries a single associated type and nothing else: ```rust pub trait DefaultImpls2 { @@ -33,18 +35,19 @@ pub trait DefaultImpls2 { } ``` -`Self` is the key being looked up, `T1` and `T2` are the two further lookup types the attribute fills -from the namespace path, `Components` is the table, and `Delegate` is the resolved provider. There is no -method and no data, so resolving a default projects `Delegate` from the matching impl. +`Self` is the key being looked up, `T1` and `T2` are the two further lookup types the attribute +fills from the namespace path, `Components` is the table, and `Delegate` is the resolved provider. +The trait has neither a method nor data, so resolving a default projects `Delegate` from the +matching impl. Three traits exist rather than one variadic trait because each fixes the key's arity at the type level, which lets the projection resolve cleanly. This is the widest of the three. :::warning -**Nothing inside CGP emits or consumes it.** It is reachable and tested, and it is a provided extension -point rather than a construct the generated code relies on, so there is no library-generated example to -pattern-match against. The [next section](#usage) shows what a use looks like. +**Nothing inside CGP emits or consumes it.** It is reachable and tested, and it is a provided +extension point rather than a construct the generated code relies on, so the library generates +nothing to pattern-match against. The [next section](#usage) shows what a use looks like. ::: @@ -62,50 +65,71 @@ path.** So `#[default_impl(Key in DefaultImpls2)]` emits ```rust impl DefaultImpls2 for Key { - type Delegate = /* the provider */; + type Delegate = Provider; } ``` -Registration is [`#[default_impl(...)]`](../../attributes/default_impl.md), which accepts an arbitrary -namespace path and therefore needed no new construct to support this trait. Consumption is a `for … in` -loop inside [`delegate_components!`](../../macros/delegate_components.md), whose bound projects `Delegate` -the same way the one-type form does. +where `Provider` is the provider the attribute sits on. + +Registration is [`#[default_impl(...)]`](../../attributes/default_impl.md), which accepts an +arbitrary namespace path and therefore did not need a new construct to support this trait. +Consumption is a `for … in` loop inside +[`delegate_components!`](../../macros/delegate_components.md), whose bound projects `Delegate` the +same way the one-type form does. ## Examples -A two-type key registered and then consumed: +A two-parameter component, a default registered under a pair, and a context pulling in every default +for one target type: ```rust -use cgp::core::component::DefaultImpls2; use cgp::prelude::*; +use cgp::core::component::DefaultImpls2; + +#[cgp_component(Converter)] +#[prefix(@test in DefaultNamespace)] +pub trait CanConvert { + fn convert(&self, value: &Source) -> Target; +} -#[cgp_impl(new ConvertStringToU64)] +#[cgp_impl(new ParseU64)] #[default_impl(String in DefaultImpls2)] -impl Converter { +impl Converter { fn convert(&self, value: &String) -> u64 { value.parse().unwrap_or_default() } } -``` - -and a context pulling every registered pair in: -```rust pub struct App; delegate_components! { App { namespace DefaultNamespace; + // Every source type with a registered default into `u64`. for in DefaultImpls2 { - @test.ConverterComponent.T: Provider, + @test.ConverterComponent.T.u64: Provider, } } } + +check_components! { + App { + ConverterComponent: (String, u64), + } +} + +pub fn demo() { + let parsed: u64 = App.convert(&"42".to_owned()); + assert_eq!(parsed, 42); +} ``` -**[Environmental context](/docs/reference/glossary#environmental-context), [parameter-targeted](/docs/reference/glossary#parameter-targeted-component).** The loop variable must still appear in the key, exactly as -for the one-type form. +**[Environmental context](/docs/reference/glossary#environmental-context), +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component).** The component's two +parameters each take a path segment, so the loop's key is `@test.ConverterComponent.T.u64`, with the +loop variable in the first and the fixed target in the second. The loop variable must appear in the +key, exactly as for the one-type form. ## When to use it @@ -126,27 +150,37 @@ and is worked out on [its page](./default_impls1.md#when-to-use-it). ## Under the hood -A `for … in` loop emits a [`DelegateComponent`](../wiring/delegate_component.md) impl whose `where` clause -projects the default: +Registration and consumption follow the one-type form exactly. `cargo cgp expand` on the example +shows the registration impl the attribute emits, with `String` in the `Self` position and both path +arguments leading: ```rust -where T: DefaultImpls2 +impl<__Components__> DefaultImpls2 for String { + type Delegate = ParseU64; +} ``` -The loop variables appear only in that bound and in the key, so **the key must mention them**, otherwise -the parameter is unconstrained and the compiler rejects the impl with `E0207`. +The `for … in` loop emits a [`DelegateComponent`](../wiring/delegate_component.md) impl whose +`where` clause projects the default: + +```rust +where T: DefaultImpls2 +``` -The registration impl carries only the parameters naming the key and provider plus the table, never the -provider's own `where` clause, so a provider with [impl-side dependencies](/docs/reference/glossary#impl-side-dependency) registers cleanly and its bounds -are checked when a real context resolves it. +The loop variables appear only in that bound and in the key, so **the key must mention them**, +otherwise the parameters are unconstrained and the compiler rejects the impl with `E0207`, as +[`DefaultImpls1`](./default_impls1.md#common-mistakes) shows. -Because nothing in the library emits this trait, there is no generated code to compare against. The -impls you see are the ones you or the attribute wrote. +The registration impl carries only the parameters naming the key and provider plus the table, never +the provider's own `where` clause, so a provider with +[impl-side dependencies](/docs/reference/glossary#impl-side-dependency) registers cleanly and its +bounds are checked when a real context resolves it. Because nothing in the library emits this trait, +the impls you see are the ones you or the attribute wrote. ## Common Mistakes -**Nothing inside CGP uses it.** There is no generated code to pattern-match against, and no worked -library example. +**Nothing inside CGP uses it.** The library emits nothing to pattern-match against and does not ship +a worked example. **It is not in the prelude.** Import from `cgp::core::component`. diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index c3c970a2..df24494a 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -1,6 +1,8 @@ --- +title: 'DefaultNamespace — the default lookup table' sidebar_label: 'DefaultNamespace' sidebar_position: 1 +description: 'The namespace trait a context joins with a namespace header, resolving each component''s default route; prefix registers components into it.' --- # `DefaultNamespace` @@ -36,7 +38,7 @@ the forwarding, so this page is mostly about reading what they generate. ## Definition -`DefaultNamespace` carries a single associated type and no method: +`DefaultNamespace` carries a single associated type and nothing else: ```rust pub trait DefaultNamespace { @@ -45,9 +47,9 @@ pub trait DefaultNamespace { ``` `Self` is the component being looked up. `Components` is the table the lookup runs against, threaded -through as a parameter so one key can resolve differently for each context. `Delegate` is the resolved -value: the provider the key maps to. There is no method and no data, so resolving a default projects -`Delegate` from the matching impl, exactly as with +through as a parameter so one key can resolve differently for each context. `Delegate` is the +resolved value: the provider the key maps to. The trait has neither a method nor data, so resolving +a default projects `Delegate` from the matching impl, exactly as with [`DelegateComponent`](../wiring/delegate_component.md). ## Usage @@ -71,9 +73,11 @@ registers into one with the [`#[prefix(...)]`](../../attributes/prefix.md) attri ## Examples -A component registered into the namespace, and a context joining it: +A component registered into the namespace, and a context joining it and filling the path it leaves +open: ```rust +use core::fmt::Display; use cgp::prelude::*; #[cgp_component(ShowImpl)] @@ -82,20 +86,41 @@ pub trait Show { fn show(&self, value: &T) -> String; } +#[cgp_impl(new ShowWithDisplay)] +impl ShowImpl { + fn show(&self, value: &T) -> String { + value.to_string() + } +} + pub struct App; delegate_components! { App { namespace DefaultNamespace; - @test.ShowImplComponent.u64: ShowWithDisplay, // fills a path the namespace leaves open + // The namespace routes the component to this path and binds nothing there. + @test.ShowImplComponent.u64: ShowWithDisplay, + } +} + +check_components! { + App { + ShowImplComponent: u64, } } + +pub fn demo() { + assert_eq!(App.show(&5u64), "5"); +} ``` -**[Environmental context](/docs/reference/glossary#environmental-context), [self-targeted](/docs/reference/glossary#self-targeted-component).** The header forwards `App`'s lookups through the -namespace. `DefaultNamespace` routes `ShowImplComponent` to `@test.ShowImplComponent` but binds no -provider there, so the direct entry supplies the one for `u64`. +**[Environmental context](/docs/reference/glossary#environmental-context), +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component).** `App` carries the +wiring and the shown value is a parameter. The header forwards `App`'s lookups through the +namespace. `#[prefix]` makes `DefaultNamespace` route `ShowImplComponent` to the path +`@test.ShowImplComponent` but leaves the paths beneath it unbound, so the direct entry supplies the +one for `u64`, and the check confirms it resolves. ## When to use it @@ -116,38 +141,77 @@ where the syntax requires it.** It appears in a `namespace` header and nowhere e ## Under the hood A `namespace N;` header does not emit one entry. It emits a **blanket** -[`DelegateComponent`](../wiring/delegate_component.md) impl on the context that forwards every key through the -namespace: +[`DelegateComponent`](../wiring/delegate_component.md) impl on the context that forwards every key +through the namespace, paired with the matching [`IsProviderFor`](../wiring/is_provider_for.md) +forwarding so dependencies stay diagnosable. `cargo cgp expand` on the example's `App` shows both: ```rust -impl DelegateComponent for App +impl<__Key__, __Value__> DelegateComponent<__Key__> for App where - Key: N, + __Key__: DefaultNamespace, { - type Delegate = Value; + type Delegate = __Value__; } +impl< + __Key__, + __Value__, + __Context__, + __Params__, +> IsProviderFor<__Key__, __Context__, __Params__> for App +where + __Key__: DefaultNamespace, + __Value__: IsProviderFor<__Key__, __Context__, __Params__>, +{} ``` -paired with the matching [`IsProviderFor`](../wiring/is_provider_for.md) forwarding so dependencies stay -diagnosable. +The namespace's own entries come from [`#[prefix(...)]`](../../attributes/prefix.md), which +implements the trait for the component with a [`RedirectLookup`](../../providers/redirect_lookup.md) +as the `Delegate`, re-routing the component to its path: + +```rust +impl<__Components__> DefaultNamespace<__Components__> for ShowImplComponent { + type Delegate = RedirectLookup<__Components__, Path!(@test.ShowImplComponent)>; +} +``` -**That blanket is why a context cannot override a namespace entry.** A directly-wired entry is a second -`DelegateComponent` impl for its key, and Rust has no specialization to prefer one impl over another. -Where the namespace binds that key, the blanket covers it too, and the compiler rejects the overlap with -`E0119`. A direct entry compiles only for a key the blanket does not cover: a path the namespace routes -to but leaves unbound, like `@test.ShowImplComponent.u64` above. +**That blanket is why a context cannot override a namespace entry.** A directly wired entry is a +second `DelegateComponent` impl for its key, and Rust lacks the specialization that would prefer one +impl over another. Where the namespace binds that key, the blanket covers it too, and the compiler +rejects the overlap with `E0119`. A direct entry compiles only for a key the blanket does not cover: +a path the namespace routes to but leaves unbound, like `@test.ShowImplComponent.u64` above. Inheritance composes on top. A namespace declared `new Child: Parent { … }` emits a blanket impl forwarding any key the parent resolves, so the child resolves everything the parent does plus its own -entries. The same rule holds at each level: a child cannot rebind a key its parent binds, and a context -cannot rebind a key either one binds. All of it is projections, resolved at -compile time, with nothing at run time. +entries. The same rule holds at each level: a child cannot rebind a key its parent binds, and a +context cannot rebind a key either one binds. All of it is projections, resolved at compile time, +with nothing at run time. ## Common Mistakes **A namespace entry cannot be overridden from the context.** A direct entry for a key the namespace -binds is rejected with `E0119` rather than preferred. To vary a choice between contexts, leave its path -unbound in the namespace and wire it on each context, or give the contexts different namespaces. +binds is rejected rather than preferred. Wiring the example's component by its bare name: + +```rust +delegate_components! { + App { + namespace DefaultNamespace; + + ShowImplComponent: ShowWithDisplay, + } +} +``` + +conflicts with the namespace's entry for `ShowImplComponent`, twice, once per generated trait: + +```text +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` +... +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` +``` + +The form that works is the component's path, as the example wires `@test.ShowImplComponent.u64`. To +vary a choice between contexts, leave its path unbound in the namespace and wire it on each context, +or give the contexts different namespaces. **`Self` is the component here**, as you would expect, but **not** in [`DefaultImpls1`](./default_impls1.md) and [`DefaultImpls2`](./default_impls2.md), where the instance @@ -155,7 +219,7 @@ type takes the `Self` position instead. The inconsistency is the family's sharpe **It is in the prelude while its two siblings are not.** They come from `cgp::core::component`. -**There is no method.** Resolving a default is a type projection. +**It lacks a method.** Resolving a default is a type projection. **Registering into a foreign namespace is bound by the [orphan rule](/docs/reference/glossary#orphan-rule).** See [`DefaultImpls1`](./default_impls1.md#when-to-use-it), where the diff --git a/docs/reference/traits/namespace/index.md b/docs/reference/traits/namespace/index.md index 88a5fcc5..2184ec5b 100644 --- a/docs/reference/traits/namespace/index.md +++ b/docs/reference/traits/namespace/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The lookup traits that resolve a namespace''s default provider for a key: by component alone, or per type through one or two further type parameters.' --- # Namespaces and defaults diff --git a/docs/reference/traits/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md index 87d50ad9..078ede9c 100644 --- a/docs/reference/traits/type-level/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -1,23 +1,14 @@ --- +title: 'AppendProduct — add an entry to a product' sidebar_label: 'AppendProduct' sidebar_position: 5 +description: 'Name the type-level product list with one more entry at the end, so generic code can describe in a signature the shape it will produce.' --- # `AppendProduct` Adding one entry to the end of a type-level product list. -:::info - -### Generated machinery - -**You are not expected to use `AppendProduct` directly.** It is a type-level -operation the extensible-data machinery computes with. The builder and merge recursions are its callers -in practice. You will most likely meet it in an error message from code that walks a shape; this page -explains what it produces so that message is legible. The one case for naming it is generic code that must describe in a signature the shape it *will* produce. - -::: - ## Overview A struct's shape in CGP is a type-level list, a [`Product!`](../../macros/product.md) of named fields. @@ -28,8 +19,9 @@ to return. `AppendProduct` is that computation for a single entry. It takes a product and an item and names the product with that item added **at the end**. -**This is one of the least user-facing traits in the reference.** You meet it if you write generic code -over shapes, and otherwise only in an error message from code that does. +**This is one of the least user-facing traits in the reference, and CGP itself never uses it.** It +is provided for generic code of your own that computes shapes, and you meet it only there or in an +error message from such code. ## Definition @@ -41,10 +33,10 @@ pub trait AppendProduct { } ``` -`Self` is the existing product, `Item` is the entry to add, and `Output` is the resulting product. `Item` -may be unsized. There is no method, because there is nothing to execute: `Output` is an associated type -the trait solver evaluates while the compiler type-checks, so it carries no runtime cost and imposes no -ordering. +`Self` is the existing product, `Item` is the entry to add, and `Output` is the resulting product. +`Item` may be unsized. The trait lacks a method, because nothing needs executing: `Output` is an +associated type the trait solver evaluates while the compiler type-checks, so it costs nothing at +run time. ## Usage @@ -60,34 +52,49 @@ when reading a bound. ## Examples -The results are types, so the check is a type equality rather than a value comparison: +The results are types, so the check is a type equality: each function compiles only if the computed +`Output` is the type it is returned as. ```rust -use cgp::core::field::traits::AppendProduct; use cgp::prelude::*; +use cgp::core::field::traits::AppendProduct; -type Base = Product![Field]; +pub type Base = Product![Field]; -type WithPort = >>::Output; -// = Product![Field, Field] -``` +pub type WithPort = >>::Output; -In generic code the same thing appears as a bound whose projection names the routine's result shape: +/// The page's claim about `WithPort`. +pub fn assert_with_port( + fields: WithPort, +) -> Product![Field, Field] { + fields +} -```rust -fn with_extra_field() -> >::Output +/// A generic signature naming the shape a routine will produce. +pub fn with_extra_field() -> PhantomData<>::Output> where Fields: AppendProduct, { - todo!() + PhantomData +} + +/// The base case the page states under *Using it*: appending onto `Nil` yields a one-element list. +pub fn assert_nil_base_case( + fields: >>::Output, +) -> Base { + fields } ``` +`with_extra_field` is the generic form: its return type names the shape the routine promises, +computed from its parameters. Appending onto `Nil` yields a one-element list, the recursion's base +case. + ## When to use it -**Reach for it when a routine must describe the shape it *will* produce** (in a signature, an associated -type, or a `where` clause) and essentially never otherwise. It is a building block the extensible-data -machinery uses; application code touches the machinery itself. +**Reach for it when a routine must describe the shape it *will* produce** (in a signature, an +associated type, or a `where` clause) and essentially never otherwise. Nothing in CGP names it, so +it matters only to code of your own that computes shapes. - **Reach for [`ConcatProduct`](./concat_product.md)** to splice a whole list rather than one entry. Append is its single-entry special case, so if you find yourself appending in a loop, you wanted @@ -98,7 +105,7 @@ machinery uses; application code touches the machinery itself. moving *values* through a shape. This never touches a value, so if you want something to happen at run time, it is the wrong layer. -There is no `AppendSum`. Growing a sum is not an operation this layer provides. +`AppendSum` does not exist. Growing a sum is not an operation this layer provides. ## Under the hood @@ -122,7 +129,7 @@ Because the recursion only ever rebuilds the list, order is structurally preserv appending yields a *different* type from prepending, and why two products with the same entries in different orders are unrelated types. -All of this is resolved during type checking. There is no `fn` anywhere on this page. +All of this is resolved during type checking. Nothing on this page is a `fn`. ## Common Mistakes @@ -133,7 +140,7 @@ wrong when reaching for it. the three product operations is easy to forget, and reaching for the wrong name is a plain unresolved-associated-type error. -**It is product-only.** There is no sum equivalent. +**It is product-only.** It lacks a sum equivalent. **Order is part of the type.** Appending is not commutative with prepending, and nothing reorders a list to make two shapes match. diff --git a/docs/reference/traits/type-level/concat_product.md b/docs/reference/traits/type-level/concat_product.md index 267ada52..e1a004d7 100644 --- a/docs/reference/traits/type-level/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -1,31 +1,23 @@ --- +title: 'ConcatProduct — join two product lists' sidebar_label: 'ConcatProduct' sidebar_position: 6 +description: 'Name the type-level product list formed by one product''s entries followed by another''s, the general form of appending a single entry.' --- # `ConcatProduct` Splicing one type-level product list onto the end of another. -:::info - -### Generated machinery - -**You are not expected to use `ConcatProduct` directly.** It is a type-level -operation the extensible-data machinery computes with, and you will most likely meet it in an error -message from code that walks a shape rather than in code you wrote. This page explains what it -produces. The one case for naming it is generic code that must describe the shape produced by combining two others. - -::: - ## Overview Merging two records means merging their shapes, and the shapes are type-level lists, a [`Product!`](../../macros/product.md) of named fields each. `ConcatProduct` names the list you get by following one product with another. -It is the general form of [`AppendProduct`](./append_product.md): **append is the single-entry special -case of concat**, and that is the shortest way to hold both in mind. +It is the general form of [`AppendProduct`](./append_product.md): **append is the single-entry +special case of concat**, and that is the shortest way to hold both in mind. Like append, CGP itself +never uses it; it is provided for generic code of your own. ## Definition @@ -38,9 +30,9 @@ pub trait ConcatProduct { } ``` -`Self` is the first product, `Items` is the second, and `Output` is the first's entries followed by the -second's, in order. There is no method, because there is nothing to execute: `Output` is an associated -type the trait solver evaluates during type checking, so it costs nothing at run time. +`Self` is the first product, `Items` is the second, and `Output` is the first's entries followed by +the second's, in order. The trait lacks a method, because nothing needs executing: `Output` is an +associated type the trait solver evaluates during type checking, so it costs nothing at run time. ## Usage @@ -56,24 +48,44 @@ unchanged. ## Examples -The results are types, so the check is a type equality: +The results are types, so the check is a type equality, here for the worked concatenation and the +two `Nil` identities: ```rust -use cgp::core::field::traits::{AppendProduct, ConcatProduct}; use cgp::prelude::*; +use cgp::core::field::traits::{AppendProduct, ConcatProduct}; -type Base = Product![Field]; +pub type Base = Product![Field]; -type WithPort = >>::Output; +pub type WithPort = >>::Output; -type Extra = Product![Field]; +pub type Extra = Product![Field]; -type Full = >::Output; -// = Product![host, port, tls] +pub type Full = >::Output; + +/// The page's claim about `Full`. +pub fn assert_full( + fields: Full, +) -> Product![ + Field, + Field, + Field, + ] { + fields +} + +/// The `Nil` identities the page states under *Using it*. +pub fn assert_left_identity(fields: >::Output) -> Base { + fields +} + +pub fn assert_right_identity(fields: >::Output) -> Base { + fields +} ``` -Which is the type-level counterpart of what [`CanBuildFrom`](../casting/can_build_from.md) does with values: this -names the combined shape, that moves the fields into it. +This is the type-level counterpart of what [`CanBuildFrom`](../casting/can_build_from.md) does with +values: this names the combined shape, that moves the fields into it. ## When to use it @@ -88,7 +100,7 @@ routine that extends a record with a caller-supplied set of fields) and essentia - **Note that [`ConcatPath`](../formatting/concat_path.md) is the path-level analogue**, doing the same job for the segment lists behind [`Path!`](../../macros/path.md), with the same two-impl recursion. -There is no `ConcatSum`. Combining two sums is not an operation this layer provides. +`ConcatSum` does not exist. Combining two sums is not an operation this layer provides. ## Under the hood diff --git a/docs/reference/traits/type-level/index.md b/docs/reference/traits/type-level/index.md index d51dafee..5a530ea6 100644 --- a/docs/reference/traits/type-level/index.md +++ b/docs/reference/traits/type-level/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The per-field state markers, the per-field and whole-record conversions between them, and the operations that grow and reshape type-level field lists.' --- # Type-level list algebra @@ -9,11 +10,12 @@ The per-field state markers and list operations the extensible-data families are ## Overview -These are the least user-facing traits in the reference. They are the type-level plumbing beneath the -[builders](../builder/index.md), [extractors](../variant/index.md), and [casts](../casting/index.md): -the markers that record what state one field is in, and the operations that grow and reshape a type's -field list. You meet them in an error message from code that walks a shape far more often than in code -you wrote, and this group exists so that such a message is legible. Most are not in the prelude. +These are the least user-facing traits in the reference. They are the type-level layer beneath the +[builders](../builder/index.md), [extractors](../variant/index.md), and +[casts](../casting/index.md): the markers that record what state one field is in, and the operations +that grow and reshape a type's field list. You meet them in an error message from code that walks a +shape far more often than in code you wrote, and this group exists so that such a message is +legible. Most are not in the prelude. The group divides into the state markers and the list operations. diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index 6f47f335..b51e4171 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -1,6 +1,8 @@ --- +title: 'MapFields — rewrite every entry of a list' sidebar_label: 'MapFields' sidebar_position: 7 +description: 'Rewrite every entry of a type-level product or sum through one MapType marker, as CGP does to wrap each provider in a pipeline''s list.' --- # `MapFields` @@ -47,10 +49,10 @@ pub trait MapFields { } ``` -`Self` is the list, `Mapper` is the [`MapType`](./map_type.md) marker to apply, and the result is exposed -as `Mapped`. Note the name, which differs from the `Output` its two siblings -[`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md) expose. There is no -method, because there is nothing to execute. +`Self` is the list, `Mapper` is the [`MapType`](./map_type.md) marker to apply, and the result is +exposed as `Mapped`. Note the name, which differs from the `Output` its two siblings +[`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md) expose. The trait +lacks a method, because nothing needs executing. ## Usage @@ -66,28 +68,48 @@ use cgp::core::field::traits::MapFields; ## Examples -Applying `IsOptional` turns a product of values into a product of optionals: +One marker applied over a product and over a sum, checked as type equalities: ```rust +use cgp::prelude::*; use cgp::core::field::impls::IsOptional; use cgp::core::field::traits::MapFields; -use cgp::prelude::*; -type Fields = Product![String, u16, bool]; +pub type Fields = Product![String, u16, bool]; -type Optional = >::Mapped; -// = Product![Option, Option, Option] -``` +pub type Optional = >::Mapped; + +pub fn assert_optional( + fields: Optional, +) -> Product![Option, Option, Option] { + fields +} -The same marker applies over a sum: +pub type Variants = Sum![String, u16]; -```rust -type Variants = Sum![String, u16]; +pub type OptionalVariants = >::Mapped; + +pub fn assert_optional_variants( + variants: OptionalVariants, +) -> Sum![Option, Option] { + variants +} -type OptionalVariants = >::Mapped; -// = Sum![Option, Option] +/// The page's claim that `IsPresent` is the identity, and that `IsNothing` collapses each entry. +pub fn assert_present(fields: >::Mapped) -> Fields { + fields +} + +pub fn assert_nothing( + fields: >::Mapped, +) -> Product![(), (), ()] { + fields +} ``` +`IsOptional` wraps each entry, `IsPresent` leaves the list unchanged, and `IsNothing` collapses each +entry to `()`. The sum is rewritten by the same marker, since `MapFields` covers both lists. + ## When to use it **Reach for it when generic code must name a uniformly re-wrapped list**, such as a list of @@ -138,15 +160,27 @@ needs its own import from `cgp::core::field::impls`. **The result is `Mapped`, not `Output`.** [`AppendProduct`](./append_product.md) and [`ConcatProduct`](./concat_product.md) both expose `Output`, and this one does not. +`>::Output` fails with: + +```text +error[E0576]: cannot find associated type `Output` in trait `MapFields` +``` **It computes types, not values.** A `MapFields` result does not wrap anything at run time. Something still has to build the wrapped values, such as [`TransformMapFields`](./transform_map_fields.md). -**A marker with no `MapType` impl does not resolve**, and the error names the missing `MapType` bound -rather than the marker's role. +**A marker without a `MapType` impl does not resolve.** Mapping through a plain +`pub struct Wrapped;`, as `>::Mapped`, names the missing +bound and the list that needed it: + +```text +error[E0277]: the trait bound `Wrapped: MapType` is not satisfied +... + = note: required for `Cons>` to implement `MapFields` +``` -**It is the only one of the three that covers sums.** There is no `AppendSum` or `ConcatSum`. +**It is the only one of the three that covers sums.** Neither `AppendSum` nor `ConcatSum` exists. **A long list means a deep recursion**, so mapping a wide shape costs compile time proportional to its width. diff --git a/docs/reference/traits/type-level/map_type.md b/docs/reference/traits/type-level/map_type.md index ea63286e..36120015 100644 --- a/docs/reference/traits/type-level/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -1,6 +1,8 @@ --- +title: 'MapType — the storage of one field' sidebar_label: 'MapType' sidebar_position: 1 +description: 'The marker trait whose Map decides how one field of a partial record or enum is stored: its value, nothing, an uninhabited type, or an Option.' --- # `MapType` @@ -35,7 +37,7 @@ fields are filled, and refuses to finalize an incomplete one. ## Definition -`MapType` carries a single generic associated type and no method: +`MapType` carries a single generic associated type and nothing else: ```rust pub trait MapType { @@ -73,31 +75,54 @@ value-level side, carrying the functions that actually convert a field from one ## Examples -You mostly meet the markers inside the partial types that -[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) generates, where a builder's type reads -`__PartialPerson` and tells you at a glance which fields are set. - -Generic partial-type machinery bounds on the trait: +What each standard marker stores, checked as type equalities, and generic code bounded on the trait: ```rust use cgp::prelude::*; +use cgp::core::field::impls::IsOptional; -fn storage_of(value: M::Map) -> M::Map -where - M: MapType, -{ +// Each function compiles only if the projection is the type on its right. +pub fn present(value: ::Map) -> String { value } -``` -and a projection names one marker's storage directly: +pub fn nothing(value: ::Map) -> () { + value +} -```rust -// IsPresent::Map is String -// IsNothing::Map is () -// IsVoid::Map is Void +pub fn void(value: ::Map) -> Void { + value +} + +pub fn optional(value: ::Map) -> Option { + value +} + +// Generic over any marker, the way the builder and extractor families are. +pub fn store(value: M::Map) -> M::Map { + value +} + +// A bound that pins the storage names the generic associated type with its argument. +pub fn unwrap_present = String>>(value: M::Map) -> String { + value +} + +pub fn demo() { + assert_eq!(present("a".to_owned()), "a"); + assert_eq!(optional(None), None); + assert_eq!(store::(Some(1)), Some(1)); + assert_eq!(unwrap_present::("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)]`](../../derives/derive_cgp_data.md) generates, where a builder's +type reads `__PartialPerson` 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 @@ -111,9 +136,11 @@ The trait itself has narrower uses. partial-type machinery. - **Implement [`TransformMap`](./transform_map.md)** 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 derives to use it. The generated partial - types are parameterized over markers, but only the four standard ones have transforms and finalize - impls behind them; a fifth marker is a type with no machinery attached. +- **Do not implement `MapType` for a new marker** expecting the rest of CGP to use it. The generated + [`UpdateField`](../builder/update_field.md) impls are generic over any marker, so `update_field` + moves a field into a custom state, and a [`TransformMap`](./transform_map.md) 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](../optional/has_optional_builder.md)** if what you want is defaulted or optional finalization. Both already exist, built on exactly this. @@ -153,8 +180,9 @@ two families have been crossed. storage, against one marker applied across a whole list. The names are close and the jobs are not. [`MapField`](../field-access/map_field.md), singular, with no *s*, is a third, unrelated thing again. -**A new marker gets you a type and nothing else.** Implementing `MapType` is easy; the derives' finalize -and transform impls are written against the standard markers, so a custom one has no machinery behind it. +**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` is a generic associated type**, so pinning it in a bound needs the `Map = String` form rather than a plain associated-type equality. diff --git a/docs/reference/traits/type-level/map_type_ref.md b/docs/reference/traits/type-level/map_type_ref.md index 625a69ff..7e879848 100644 --- a/docs/reference/traits/type-level/map_type_ref.md +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -1,6 +1,8 @@ --- +title: 'MapTypeRef — storage in a borrowed view' sidebar_label: 'MapTypeRef' sidebar_position: 2 +description: 'The marker trait deciding how a borrowed extractor holds each payload, by shared reference, by mutable reference, or by value, at a lifetime.' --- # `MapTypeRef` @@ -33,7 +35,7 @@ be matched without being moved, with the narrowing working identically. ## Definition -`MapTypeRef` carries a single generic associated type and no method: +`MapTypeRef` carries a single generic associated type and nothing else: ```rust pub trait MapTypeRef { @@ -59,46 +61,73 @@ impl MapTypeRef for IsOwned { type Map<'a, T: 'a> = T; } :::warning -**`IsOwned` has no consumer in CGP.** No derive emits it and no provider resolves against it. It is -available for a borrowed view that holds its payloads by value, and at present that view exists only if -you write the machinery yourself. +**Nothing in CGP consumes `IsOwned`.** No derive emits it and no provider resolves against it. It is +available for a borrowed view that holds its payloads by value, and at present that view exists only +if you write the machinery yourself. ::: ## Examples -You meet these markers inside the borrowed companion types the derives generate. Reading a variant -through a shared borrow leaves the value intact: +What each standard marker stores at a lifetime, and the two borrowed extractors that fix it: ```rust use cgp::prelude::*; +use cgp::core::field::impls::IsOwned; -#[derive(ExtractField)] +pub fn by_ref<'a>(value: ::Map<'a, String>) -> &'a String { + value +} + +pub fn by_mut<'a>(value: ::Map<'a, String>) -> &'a mut String { + value +} + +pub fn owned<'a>(value: ::Map<'a, String>) -> String { + value +} + +#[derive(Debug, PartialEq)] +pub struct Circle { + pub radius: f64, +} + +#[derive(Debug, PartialEq)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +#[derive(Debug, PartialEq, ExtractField)] pub enum Shape { Circle(Circle), Rectangle(Rectangle), } -let radius = shape - .extractor_ref() // outer marker is IsRef - .extract_field(PhantomData::) - .map(|circle| circle.radius) - .ok(); -``` - -and the mutable form changes a payload in place: - -```rust -if let Ok(circle) = shape - .extractor_mut() // outer marker is IsMut - .extract_field(PhantomData::) -{ - circle.radius = 5.0; +pub fn demo() { + let mut shape = Shape::Circle(Circle { radius: 1.0 }); + + // The outer marker is `IsRef`, so the payload comes out as `&Circle`. + let radius = shape + .extractor_ref() + .extract_field(PhantomData::) + .map(|circle| circle.radius) + .ok(); + assert_eq!(radius, Some(1.0)); + + // The outer marker is `IsMut`, so the payload comes out as `&mut Circle`. + if let Ok(circle) = shape + .extractor_mut() + .extract_field(PhantomData::) + { + circle.radius = 5.0; + } + assert_eq!(shape, Shape::Circle(Circle { radius: 5.0 })); } ``` -Neither call names a marker. What the markers do is decide the type the payload comes out as (`&Circle` -in the first case, `&mut Circle` in the second) while the per-field +Neither extractor call names a marker. What the markers decide is the type the payload comes out as, +`&Circle` through `extractor_ref` and `&mut Circle` through `extractor_mut`, while the per-field [`MapType`](./map_type.md) markers track which variants are still possible. ## When to use it @@ -121,31 +150,31 @@ what this page is for: an error mentioning `IsRef` is telling you the value is b ## Under the hood -A borrowed companion enum carries the outer marker as an extra parameter alongside the per-variant ones, -and each payload slot projects through both: +A borrowed companion enum carries the outer marker as an extra parameter alongside the per-variant +ones, and each payload slot projects through both. `cargo cgp expand` on a +`Shape { Circle(Circle), Rectangle(Rectangle) }` deriving `ExtractField` shows it: ```rust -// conceptually, for `enum Shape { Circle(Circle), Rectangle(Rectangle) }` -// -// pub enum __PartialRefShape<'a, R: MapTypeRef, F0: MapType, F1: MapType> { -// Circle(F0::Map>), -// Rectangle(F1::Map>), -// } +pub enum __PartialRefShape<'__a__, __R__: MapTypeRef, __F0__: MapType, __F1__: MapType> { + Circle(<__F0__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Circle>>), + Rectangle(<__F1__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Rectangle>>), +} ``` -Read the nesting outward: `R::Map<'a, T>` decides *how* the payload is held, and `F::Map<…>` decides -*whether* it is there at all. Fixing `R = IsRef` gives a shared-borrow extractor; flipping an `F` from -`IsPresent` to `IsVoid` rules that variant out. The two axes are independent, which is why narrowing -behaves identically through a borrow and through an owned value. +Read the nesting outward: `__R__`'s `Map<'a, T>` decides *how* the payload is held, and each +`__F__`'s `Map<…>` decides *whether* it is there at all. Fixing `__R__` to `IsRef` gives a +shared-borrow extractor; flipping an `__F__` from `IsPresent` to `IsVoid` rules that variant out. +The two axes are independent, which is why narrowing behaves identically through a borrow and +through an owned value. -The `T: 'a` bound and the `: 'a` bound on the associated type are what keep the projection well-formed: -a payload cannot be borrowed for longer than it lives, and the resulting storage type cannot outlive the -borrow either. +The `T: 'a` bound and the `: 'a` bound on the associated type are what keep the projection +well-formed: a payload cannot be borrowed for longer than it lives, and the resulting storage type +cannot outlive the borrow either. ## Common Mistakes -**`IsOwned` is unused by CGP.** It is a legal marker with no consumer, so selecting it means writing the -machinery that uses it yourself. +**`IsOwned` is unused by CGP.** It is a legal marker that nothing consumes, so selecting it means +writing the machinery that uses it yourself. **`IsOwned` is not in the prelude.** Import it from `cgp::core::field::impls`. `IsRef` and `IsMut` are. @@ -156,9 +185,8 @@ usually means the owned and borrowed forms have been crossed. **The associated type takes a lifetime as well as a type.** A bound over it is more verbose than a `MapType` bound, and eliding the lifetime rarely works. -**A mutable extractor cannot coexist with another borrow of the same value**, which is ordinary borrow -checking rather than anything CGP adds, but it surfaces as an error about the companion type, which -reads as though the machinery is at fault. +**A mutable extractor cannot coexist with another borrow of the same value**, which is ordinary +borrow checking rather than anything CGP adds. ## Related constructs diff --git a/docs/reference/traits/type-level/transform_map.md b/docs/reference/traits/type-level/transform_map.md index 399c87d7..76910237 100644 --- a/docs/reference/traits/type-level/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -1,6 +1,8 @@ --- +title: 'TransformMap — convert a fields storage' sidebar_label: 'TransformMap' sidebar_position: 3 +description: 'The per-field function converting a value from one marker''s storage to another''s, and the extension point for a new way to re-mark a record.' --- # `TransformMap` @@ -44,21 +46,22 @@ use cgp::core::field::impls::IsOptional; use cgp::core::field::traits::TransformMap; ``` -The trait is implemented on a **transform marker**, a zero-sized type you declare. It carries no data +The trait is implemented on a **transform marker**, a zero-sized type you declare. It stores nothing and exists only to name the set of conversions, exactly as a provider does elsewhere in CGP. -**A transform needs an impl for every source marker a field might currently be in.** That is the rule -that decides how many impls you write, and getting it wrong is the usual failure: the walk does -not resolve, and the error names the missing `TransformMap` impl rather than the field. +**A transform needs an impl for every source marker a field might currently be in.** That rule +decides how many impls you write, and getting it wrong is the usual failure, shown in +[Common Mistakes](#common-mistakes). ## Examples -A marker that fills absent fields from `Default` is one impl per source state: +A marker that fills absent fields from `Default`, one impl per source state, applied to a builder +with one field set: ```rust -use cgp::core::field::impls::IsOptional; -use cgp::core::field::traits::TransformMap; use cgp::prelude::*; +use cgp::core::field::impls::IsOptional; +use cgp::core::field::traits::{TransformMap, TransformMapFields}; pub struct FillDefaults; @@ -79,19 +82,39 @@ impl TransformMap for FillDefaults { value.unwrap_or_default() } } -``` -Read that as three cases of one rule: a present field passes through, an absent one becomes its default, -and an optional one becomes its contents or the default. Note how each signature's argument type is the -source marker's `Map` (`T`, then `()`, then `Option`), which makes the three impls -non-overlapping. +#[derive(Debug, PartialEq, CgpData)] +pub struct Config { + pub port: u16, + pub verbose: bool, +} + +pub fn with_defaults() -> Config { + let partial = Config::builder().build_field(PhantomData::, 8080); + + TransformMapFields::::transform_map_fields(partial) + .finalize_build() +} + +pub fn demo() { + assert_eq!( + with_defaults(), + Config { + port: 8080, + verbose: false, + } + ); +} +``` +Read the impls as three cases of one rule: a present field passes through, an absent one becomes its +default, and an optional one becomes its contents or the default. Each argument type is the source +marker's `Map` (`T`, then `()`, then `Option`), which keeps the three impls from overlapping. Because all three target `IsPresent`, applying `FillDefaults` through -[`transform_map_fields`](./transform_map_fields.md) leaves every field present, which is precisely the -configuration [`FinalizeBuild`](../builder/finalize_build.md) accepts. +[`transform_map_fields`](./transform_map_fields.md) leaves every field present, the configuration +[`FinalizeBuild`](../builder/finalize_build.md) accepts, so `verbose` comes out as `false`. -**That is not hypothetical: it is how [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) works**, -and reading it here is the shortest route to understanding that layer. +**That is not hypothetical: it is how [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) works**, and reading it here is the shortest route to understanding that layer. ## When to use it @@ -105,9 +128,9 @@ and reading it here is the shortest route to understanding that layer. logs, or one that fills from something other than `Default`. - **Use [`TransformMapFields`](./transform_map_fields.md)** to apply what you have written. This trait converts one field; that one walks a whole record. -- **Do not implement [`MapType`](./map_type.md) for a new marker** and expect the derives to use it. A - fifth state marker has no machinery behind it; a new *transform* marker, by contrast, works - immediately. +- **Do not implement [`MapType`](./map_type.md) for a new marker** and expect the derives to use it. + A fifth state marker is reachable only through `update_field` and a transform; a new *transform* + marker, by contrast, works immediately. ## Under the hood @@ -126,16 +149,33 @@ The transform must have an impl for **every** source marker a field might curren `FillDefaults` above needs three rather than one. And the walk is driven by the *target's* shape, so it re-marks exactly the fields the concrete struct declares. -Nothing here has a runtime representation beyond the field values themselves: the markers are zero-sized, -and `transform_mapped` is an associated function with no receiver. +Nothing here has a runtime representation beyond the field values themselves: the markers are +zero-sized, and `transform_mapped` is an associated function without a receiver. ## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. -**It needs an impl per source state.** Writing only the `IsNothing` case leaves the recursion -unresolvable for a record with any field already present, and the error names the missing -`TransformMap` impl rather than the field that caused it. +**It needs an impl per source state.** Writing only the `IsNothing` case, as +`pub struct OnlyAbsent;` with a single `TransformMap` impl, and applying it +to a `Config` builder whose `port` is already set: + +```rust +let partial = Config::builder().build_field(PhantomData::, 8080); +let _ = TransformMapFields::::transform_map_fields(partial); +``` + +fails with two errors. The first is a misleading mismatch on the walk's internal `UpdateField` +step; the second names the missing impl, identifying the field by its value type rather than its +name: + +```text +error[E0271]: type mismatch resolving `<__PartialConfig as UpdateField>>>>, IsNothing>>::Mapper == IsNothing` +... +error[E0277]: the trait bound `OnlyAbsent: TransformMap` is not satisfied +``` + +Read the second: the source marker is the case to add. **The argument type is the source marker's projection**, not `T`. An impl from `IsNothing` takes `()`, one from `IsOptional` takes `Option`. Writing `T` there is the most common mistake. @@ -146,7 +186,8 @@ one from `IsOptional` takes `Option`. Writing `T` there is the most common mi **A transform whose impls do not all target the same marker will not compose into a finalize.** The layer's payoff comes from every field landing in one state, usually `IsPresent`. -**It is an associated function, not a method.** There is no receiver; the marker exists only as a name. +**It is an associated function, not a method.** It does not take a receiver; the marker exists only +as a name. ## Related constructs diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index c61fc0fd..c0a42b1b 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -1,6 +1,8 @@ --- +title: 'TransformMapFields — convert every field' sidebar_label: 'TransformMapFields' sidebar_position: 4 +description: 'Apply one per-field transform across a whole partial record, re-marking every field to a target marker in one call; the optional layer is built on it.' --- # `TransformMapFields` @@ -11,10 +13,12 @@ Applying one per-field transform across a whole [partial record](/docs/reference ### Generated machinery -**You are not expected to call `transform_map_fields` directly.** It is the +**You are not expected to call `transform_map_fields` for CGP's own conversions.** It is the recursion the optional-field layer is built from, and -[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and [`ToOptional`](../optional/to_optional.md) are what -you call. This page explains the walk, which makes those two behave so symmetrically. The one case for bounding on it is writing an operation of your own that re-marks a whole record. +[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and +[`ToOptional`](../optional/to_optional.md) are what you call. This page explains the walk, which +makes those two behave so symmetrically. The case for naming it is applying a transform of your own, +or writing an operation that re-marks a whole record. ::: @@ -24,10 +28,10 @@ you call. This page explains the walk, which makes those two behave so symmetric `TransformMapFields` lifts that conversion across an entire partial record, so every field is re-marked in one call. -**This is the motion the optional-field layer is made of.** Re-marking every field to `IsPresent` and -then calling the ordinary [`finalize_build`](../builder/finalize_build.md) is exactly what -[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) does, and re-marking to `IsOptional` is what -[`ToOptional`](../optional/to_optional.md) does. +**This is the motion the optional-field layer is made of.** +[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) re-marks every field to +`IsPresent` and then calls the ordinary [`finalize_build`](../builder/finalize_build.md), and +[`ToOptional`](../optional/to_optional.md) re-marks every field to `IsOptional`. ## Definition @@ -58,37 +62,61 @@ It is implemented for any [`PartialData`](../builder/partial_data.md) whose fiel there is nothing to implement. What you supply is the `Transform` marker, by writing [`TransformMap`](./transform_map.md) impls for it. -The two type parameters are usually inferred from the surrounding bound rather than written at a call -site, which is why the method reads as a bare `self.transform_map_fields()`. +**The method does not take type arguments, so something must fix `Transform` and `TargetMap`.** +Inside generic code a `where` clause does, and the method is called bare as +`builder.transform_map_fields()`. At a concrete call site, name both on the trait, as +`TransformMapFields::::transform_map_fields(builder)`; a bare call there does not +compile, as [Common Mistakes](#common-mistakes) shows. ## Examples -You reach it through the layer built on it far more often than directly. This is the whole body of -[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md): +A transform of your own, applied at a concrete call site and through a bound: ```rust -use cgp::core::field::traits::TransformMapFields; use cgp::prelude::*; +use cgp::core::field::traits::{TransformMap, TransformMapFields}; + +// Doubles every present number and keeps it present. +pub struct Double; + +impl + Copy> TransformMap for Double { + fn transform_mapped(value: T) -> T { + value + value + } +} + +#[derive(Debug, PartialEq, CgpData)] +pub struct Point { + pub x: u32, + pub y: u32, +} + +// At a concrete site, name the transform and the target marker on the trait. +pub fn doubled(point: Point) -> Point { + TransformMapFields::::transform_map_fields(point.into_builder()) + .finalize_build() +} -impl CanFinalizeWithDefault for Builder +// In generic code, the bound fixes both, so the method is called bare. +pub fn double_all(builder: Builder) -> Builder::Output where - Builder: TransformMapFields, - Builder::Output: FinalizeBuild, + Builder: TransformMapFields, { - type Output = Output; + builder.transform_map_fields() +} - fn finalize_with_default(self) -> Output { - self.transform_map_fields().finalize_build() - } +pub fn demo() { + assert_eq!(doubled(Point { x: 1, y: 2 }), Point { x: 2, y: 4 }); + + let point = double_all(Point { x: 3, y: 4 }.into_builder()).finalize_build(); + assert_eq!(point, Point { x: 6, y: 8 }); } ``` -Read the two bounds together: the first says every field can be re-marked to `IsPresent` by -`TransformMapDefault`, and the second says the result is then finalizable. The strict presence check -still runs. It just always passes, because the transform guaranteed presence first. - -Applying a transform of your own follows the same shape, with your marker in place of -`TransformMapDefault`. +At a concrete site nothing fixes the transform or the target marker, so `doubled` names both on the +trait. Inside `double_all` the `where` clause fixes them, so the method is called bare. +[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and +[`ToOptional`](../optional/to_optional.md) are this second shape with CGP's own markers. ## When to use it @@ -106,32 +134,79 @@ layer requires exactly that. ## Under the hood -`TransformMapFields` walks the target's [`HasFields`](../shape/has_fields.md) product one entry at a time. For -each `Field` it uses [`UpdateField`](../builder/update_field.md) **twice**: it takes the field out -(replacing its marker with `IsNothing` and reading what the marker *was*), applies -`Transform::transform_mapped` to convert the value into the `TargetMap` wrapping, then writes it back -under `TargetMap`. +The trait's one impl applies to any [`PartialData`](../builder/partial_data.md) whose target has a +[`HasFields`](../shape/has_fields.md) shape, and hands the value to a private walk over that shape: -So the result type has every field re-marked to `TargetMap`, with the values converted accordingly. Two -things follow from that construction, and both explain limits you might otherwise trip over. +```rust +impl TransformMapFields + for ContextA +where + ContextA: PartialData, + ContextB: HasFields, + ContextB::Fields: TransformMapFieldsImpl, +{ + type Output = Output; -**The transform must have an impl for every source marker a field might currently be in**, or the walk -does not resolve, which is why a transform like `FillDefaults` needs three -[`TransformMap`](./transform_map.md) impls rather than one. + fn transform_map_fields(self) -> Self::Output { + ContextB::Fields::transform_map_fields(self) + } +} +``` -**The recursion is driven by the target's shape**, so it re-marks exactly the fields the concrete struct -declares, in declaration order, and a field the shape does not mention is not visited at all. +The walk's `Cons` impl converts one field with [`UpdateField`](../builder/update_field.md) +**twice**, after the rest of the list: + +```rust +fn transform_map_fields(context_a: ContextA) -> Self::Output { + let context_b = Tail::transform_map_fields(context_a); + + let (value_a, context_c) = context_b.update_field(PhantomData, ()); + let value_b = Transform::transform_mapped(value_a); + let (_, context_d) = context_c.update_field(PhantomData, value_b); + + context_d +} +``` + +The first `update_field` takes the field out, re-marking it `IsNothing` and reporting as `SourceMap` +the marker it was in; `Transform::transform_mapped` converts the value from `SourceMap`'s storage to +`TargetMap`'s; the second writes it back under `TargetMap`. So the result type has every field +re-marked to `TargetMap`, with the values converted accordingly. Three things follow. + +**The transform must have an impl for every source marker a field might currently be in**, or the +walk does not resolve, which is why a transform like +[`FillDefaults`](./transform_map.md#examples) needs three [`TransformMap`](./transform_map.md) impls +rather than one. + +**The recursion is driven by the target's shape**, so it re-marks exactly the fields the concrete +struct declares, and a field the shape does not mention is not visited at all. + +**It visits the fields last to first**, because each cell recurses into the rest of the list before +converting its own field. The order matters only to a transform with a side effect, such as one that +logs: on `struct Triple { a: u32, b: u32, c: u32 }` it sees `c`, then `b`, then `a`. The intermediate `IsNothing` state is invisible from outside: it exists only between the two -`UpdateField` calls for one field, and no observable value is ever in a half-transformed configuration. +`UpdateField` calls for one field, and no observable value is ever in a half-transformed +configuration. ## Common Mistakes **It is not in the prelude.** Import from `cgp::core::field::traits`. -**A missing [`TransformMap`](./transform_map.md) impl stops the whole walk.** The error names the missing -impl for one field's source marker, not the record, so it reads as being about a marker pair rather than -about the transform being incomplete. +**A missing [`TransformMap`](./transform_map.md) impl stops the whole walk.** The useful error names +the missing impl for one field's source marker and value type, after a misleading `UpdateField` +mismatch; [`TransformMap`](./transform_map.md#common-mistakes) shows both. + +**A bare call at a concrete site does not compile.** Nothing fixes the transform or the target +marker, so `Point { x: 1 }.into_builder().transform_map_fields()` fails with: + +```text +error[E0283]: type annotations needed for `__PartialPoint<_>` +... + = note: required for `__PartialPoint` to implement `TransformMapFields<_, _>` +``` + +Name both on the trait, as the [example](#examples)'s `doubled` does. **`Output` is a partial type, not the finished struct.** Finalizing is still [`FinalizeBuild`](../builder/finalize_build.md)'s job. This trait only guarantees the configuration that impl From 6438c37f8077887a9cc345dedb97fa88e07487b5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 06:39:15 +0000 Subject: [PATCH 144/516] Fix leftover contradictions in the T4 trait pages and pipe_monadic Corrects the stacking direction on pipe_monadic (the chosen monad goes over ErrMonadic), states that DefaultNamespace is named in #[prefix] as well as a namespace header and that #[prefix] emits its impls, notes the two list mappers that also implement MapType, drops AppendProduct and ConcatProduct motivations that implied CGP uses them, and repairs a dangling reference and two wraps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- .../reference/providers/monad/pipe_monadic.md | 19 +++++++++-------- .../traits/formatting/concat_path.md | 2 +- .../traits/namespace/default_impls1.md | 5 ++--- .../traits/namespace/default_namespace.md | 21 ++++++++++--------- .../traits/type-level/append_product.md | 16 +++++++------- .../traits/type-level/concat_product.md | 6 +++--- docs/reference/traits/type-level/map_type.md | 8 +++++-- .../traits/type-level/transform_map.md | 4 +++- .../traits/type-level/transform_map_fields.md | 8 +++---- 9 files changed, 47 insertions(+), 42 deletions(-) diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index f64eab42..f1c66eba 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -177,15 +177,16 @@ result is `ComposeHandlers>>>`, where `Bind

` for `ErrMonadic`. A one-element list is its only provider, and an empty list builds nothing. -For the fallible components `TryComputerComponent` and `HandlerComponent`, it bridges through the err -monad. It first maps every provider to [`TryPromote`](../handler/try_promote.md), demoting fallible -handlers to plain computers whose output is an explicit `Result`; the mapper that rewrites the whole list -is `TryPromoteProviders`, which implements [`MapType`](../../traits/type-level/map_type.md). It then applies -`ErrMonadic` as a transformer on top of `M`, composes the demoted list under the transformed monad, and -wraps the composed provider back in `TryPromote` to restore the fallible interface. A `PipeMonadic` over -fallible handlers therefore short-circuits on the context's error type in addition to whatever branching -`M` contributes. The whole fold happens during trait resolution, so the pipeline is not a runtime -structure. +For the fallible components `TryComputerComponent` and `HandlerComponent`, it bridges through the +err monad. It first maps every provider to [`TryPromote`](../handler/try_promote.md), demoting +fallible handlers to plain computers whose output is an explicit `Result`; the mapper that rewrites +the whole list is `TryPromoteProviders`, which implements +[`MapType`](../../traits/type-level/map_type.md). It then applies `M` as a transformer over +`ErrMonadic`, so the err monad handles the outer `Result` and `M` the layer inside it, composes the +demoted list under that stack, and wraps the composed provider back in `TryPromote` to restore the +fallible interface. A `PipeMonadic` over fallible handlers therefore short-circuits on the context's +error type in addition to whatever branching `M` contributes. The whole fold happens during trait +resolution, so the pipeline is not a runtime structure. ## Related constructs diff --git a/docs/reference/traits/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md index fe3bca7e..ff903ea2 100644 --- a/docs/reference/traits/formatting/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -51,7 +51,7 @@ nothing runs. **`ConcatPath` is in the prelude**: `use cgp::prelude::*;` names it, which makes it the one member of the type-level recovery group that comes with the prelude. Its two neighbours each need a -different one: [`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and +different import: [`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and [`StaticFormat`](./static_format.md), defined in the same crate as this trait, from `cgp::core::base::traits`. diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index 0c7f9db3..985c16ce 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -39,9 +39,8 @@ pub trait DefaultImpls1 { `Self` is the key being looked up, the *instance* type, such as `String`. `T` is the further lookup type, which the attribute fills with the component name. `Components` is the table the lookup runs -against, and `Delegate` is the resolved provider. The trait has -neither a method nor data, so resolving a default -projects `Delegate` from the matching impl, exactly as with +against, and `Delegate` is the resolved provider. The trait has neither a method nor data, so +resolving a default projects `Delegate` from the matching impl, exactly as with [`DelegateComponent`](../wiring/delegate_component.md). Three traits exist rather than one variadic trait because each fixes the key's arity at the type level, diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index df24494a..98c91927 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -13,12 +13,11 @@ Resolving a namespace's default provider for a component. ### Generated machinery -**You do not implement `DefaultNamespace`.** -[`cgp_namespace!`](../../macros/cgp_namespace.md) and its -[`#[prefix(...)]`](../../attributes/prefix.md) attribute emit the impls. You name the trait in exactly -one place, a `namespace` header inside -[`delegate_components!`](../../macros/delegate_components.md), and this page explains what that header -generates, including why a direct entry can fill a path the namespace leaves open but cannot replace +**You do not implement `DefaultNamespace`.** The [`#[prefix(...)]`](../../attributes/prefix.md) +attribute on a component emits its impls. You name the trait in two places, that attribute's +`in DefaultNamespace` and a `namespace` header inside +[`delegate_components!`](../../macros/delegate_components.md), and this page explains what they +generate, including why a direct entry can fill a path the namespace leaves open but cannot replace one it binds. ::: @@ -33,8 +32,9 @@ defaults means asking: *for this component, what does the namespace delegate to? [`DefaultImpls1`](./default_impls1.md) adds one further type for a *per-type* default, and [`DefaultImpls2`](./default_impls2.md) does the same under a pair. -**You name it in one place**: the `namespace` header of a wiring block. The macros generate the impls and -the forwarding, so this page is mostly about reading what they generate. +**You name it in two places**: a component's `#[prefix(@path in DefaultNamespace)]` and the +`namespace` header of a wiring block. The macros generate the impls and the forwarding, so this page +is mostly about reading what they generate. ## Definition @@ -124,8 +124,9 @@ one for `u64`, and the check confirms it resolves. ## When to use it -**Write [`cgp_namespace!`](../../macros/cgp_namespace.md) and the wiring statements; name this trait only -where the syntax requires it.** It appears in a `namespace` header and nowhere else in ordinary code. +**Write [`cgp_namespace!`](../../macros/cgp_namespace.md) and the wiring statements; name this trait +only where the syntax requires it.** It appears in a `#[prefix]` attribute and a `namespace` header +and nowhere else in ordinary code. - **Use `DefaultNamespace`** for a namespace whose defaults are per component, which is the common case and what [`#[prefix(...)]`](../../attributes/prefix.md) registers into. diff --git a/docs/reference/traits/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md index 078ede9c..e6bbac91 100644 --- a/docs/reference/traits/type-level/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -11,10 +11,10 @@ Adding one entry to the end of a type-level product list. ## Overview -A struct's shape in CGP is a type-level list, a [`Product!`](../../macros/product.md) of named fields. -Code that processes such a shape generically sometimes needs to describe a *new* shape computed from an -old one: the shape a builder will have after one more field is set, say, or the shape a routine promises -to return. +A struct's shape in CGP is a type-level list, a [`Product!`](../../macros/product.md) of named +fields. Code that processes such a shape generically sometimes needs to describe a *new* shape +computed from an old one: the shape a routine promises to return after adding a field, say, or a +bound relating an input shape to an output one. `AppendProduct` is that computation for a single entry. It takes a product and an item and names the product with that item added **at the end**. @@ -87,8 +87,7 @@ pub fn assert_nil_base_case( ``` `with_extra_field` is the generic form: its return type names the shape the routine promises, -computed from its parameters. Appending onto `Nil` yields a one-element list, the recursion's base -case. +computed from its parameters. ## When to use it @@ -145,9 +144,8 @@ unresolved-associated-type error. **Order is part of the type.** Appending is not commutative with prepending, and nothing reorders a list to make two shapes match. -**A long list means a deep recursion.** This is trait resolution over the list, so a very wide struct -costs compile time proportional to its width, one of the places CGP's compile-time cost actually comes -from. +**A long list means a deep recursion.** This is trait resolution over the list, so a very wide shape +costs compile time proportional to its width, as every type-level list recursion in CGP does. ## Related constructs diff --git a/docs/reference/traits/type-level/concat_product.md b/docs/reference/traits/type-level/concat_product.md index e1a004d7..138cad63 100644 --- a/docs/reference/traits/type-level/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -11,9 +11,9 @@ Splicing one type-level product list onto the end of another. ## Overview -Merging two records means merging their shapes, and the shapes are type-level lists, a -[`Product!`](../../macros/product.md) of named fields each. `ConcatProduct` names the list you get by -following one product with another. +Describing the result of combining two records means naming their combined shape, and the shapes are +type-level lists, a [`Product!`](../../macros/product.md) of named fields each. +`ConcatProduct` names the list you get by following one product with another. It is the general form of [`AppendProduct`](./append_product.md): **append is the single-entry special case of concat**, and that is the shortest way to hold both in mind. Like append, CGP itself diff --git a/docs/reference/traits/type-level/map_type.md b/docs/reference/traits/type-level/map_type.md index 36120015..c2060451 100644 --- a/docs/reference/traits/type-level/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -52,8 +52,12 @@ storage reads `M: MapType = String>`, and one that leaves it open is ## Usage -Four markers implement it, and they are the trait's whole public surface. **Three are in the prelude; -`IsOptional` is not.** Import it from `cgp::core::field::impls`. +Four state markers implement it, and they are the ones a partial type is parameterized by. **Three +are in the prelude; `IsOptional` is not.** Import it from `cgp::core::field::impls`. The library +also implements it for two list mappers that are not field states, `TryPromoteProviders` in +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) and `ToBuildAndMergeHandler` in +[`BuildAndMergeOutputs`](../../providers/dispatch/build_and_merge_outputs.md), which +[`MapFields`](./map_fields.md) uses to wrap every provider in a list. ```rust impl MapType for IsPresent { type Map = T; } // the field holds its value diff --git a/docs/reference/traits/type-level/transform_map.md b/docs/reference/traits/type-level/transform_map.md index 76910237..5223d319 100644 --- a/docs/reference/traits/type-level/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -114,7 +114,9 @@ Because all three target `IsPresent`, applying `FillDefaults` through [`transform_map_fields`](./transform_map_fields.md) leaves every field present, the configuration [`FinalizeBuild`](../builder/finalize_build.md) accepts, so `verbose` comes out as `false`. -**That is not hypothetical: it is how [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) works**, and reading it here is the shortest route to understanding that layer. +**That is not hypothetical: it is how +[`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) works**, and reading it here is +the shortest route to understanding that layer. ## When to use it diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index c0a42b1b..9aeab2bd 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -168,10 +168,10 @@ fn transform_map_fields(context_a: ContextA) -> Self::Output { } ``` -The first `update_field` takes the field out, re-marking it `IsNothing` and reporting as `SourceMap` -the marker it was in; `Transform::transform_mapped` converts the value from `SourceMap`'s storage to -`TargetMap`'s; the second writes it back under `TargetMap`. So the result type has every field -re-marked to `TargetMap`, with the values converted accordingly. Three things follow. +The first `update_field` takes the field out, re-marking it `IsNothing` and reporting through its +`Mapper` the marker it was in; `Transform::transform_mapped` converts the value from that marker's +storage to `TargetMap`'s; the second writes it back under `TargetMap`. So the result type has every +field re-marked to `TargetMap`, with the values converted accordingly. Three things follow. **The transform must have an impl for every source marker a field might currently be in**, or the walk does not resolve, which is why a transform like From 0462c60b58d48be01dfb1c2d5f92430d9fbc1ac3 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 06:42:54 +0000 Subject: [PATCH 145/516] Record that every traits/ page is now mirrored Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- example-code/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example-code/README.md b/example-code/README.md index b868c9f7..33aaf2a2 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -36,7 +36,7 @@ One file per page, at the matching path with the file name in `snake_case`: | Section | Coverage | |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | -| `docs/reference/` | partial — `errors.md`, every `macros/` page and every `attributes/` page that shows code, all of `derives/`, the `traits/` pages that show checkable code, all of `providers/` that shows code (the singletons, and all of `error/`, `handler/`, `monad/`, and `dispatch/`; `use_field_ref` shows its example on its alias page), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | +| `docs/reference/` | partial — `errors.md`, every `macros/` page and every `attributes/` page that shows code, all of `derives/`, every `traits/` construct page, all of `providers/` that shows code (the singletons, and all of `error/`, `handler/`, `monad/`, and `dispatch/`; `use_field_ref` shows its example on its alias page), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | | `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | From a9452b47e7d66397d09d685a5f41b6632a022bb4 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 07:25:08 +0000 Subject: [PATCH 146/516] Revise the types/ reference pages and mirror their programs Resync all twelve types/ pages with their internal documents and the cgp source, rewrite each Examples section as a complete program with a demo() mirrored in example-code, and add trybuild fixtures for every quoted error. Corrections found by probing: Life is neither Send nor Sync, its invariance does not affect impl selection, and a check names it as (Life<'a>, T); new declares one PhantomData over the provider's parameters; RedirectLookup looks the whole extended path up as one key; an exhausted extractor is the all-IsVoid companion rather than Void, and FinalizeExtract's real signature is shown; a by-value match may omit the Void arm while a match behind a reference may not; a qualified MRef path fails with E0637; the Index page's Pair lacked its derive. Also records a cgp defect: a component used at an unsized type parameter passes its check but fails every call, now noted on the delegate_components, check_components, and CanUseComponent pages. Adds title and description front matter to the types/ pages, extending the description sweep recorded in website/seo.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/check_components.md | 3 + docs/reference/macros/delegate_components.md | 8 + .../traits/wiring/can_use_component.md | 5 +- docs/reference/types/chars.md | 129 +++++++++--- docs/reference/types/cons.md | 95 ++++++--- docs/reference/types/either.md | 109 ++++++---- docs/reference/types/field.md | 93 ++++++--- docs/reference/types/index.md | 7 +- docs/reference/types/index_type.md | 101 +++++---- docs/reference/types/life.md | 191 ++++++++++++++---- docs/reference/types/mref.md | 143 +++++++++---- docs/reference/types/nil.md | 62 +++--- docs/reference/types/path_cons.md | 105 ++++++---- docs/reference/types/phantom_data.md | 147 ++++++++++---- docs/reference/types/void.md | 136 ++++++++++--- ...common_mistakes_reading_a_missing_field.rs | 36 ++++ ...on_mistakes_reading_a_missing_field.stderr | 28 +++ ...x_type_common_mistakes_missing_position.rs | 13 ++ ...pe_common_mistakes_missing_position.stderr | 19 ++ ..._type_common_mistakes_symbol_of_a_digit.rs | 13 ++ ...e_common_mistakes_symbol_of_a_digit.stderr | 18 ++ .../life_behavior_bare_lifetime_in_check.rs | 38 ++++ ...ife_behavior_bare_lifetime_in_check.stderr | 5 + .../life_common_mistakes_unsized_target.rs | 43 ++++ ...life_common_mistakes_unsized_target.stderr | 29 +++ .../types/life_definition_invariant.rs | 11 + .../types/life_definition_invariant.stderr | 14 ++ .../types/life_definition_not_send.rs | 24 +++ .../types/life_definition_not_send.stderr | 55 +++++ .../mref_common_mistakes_qualified_path.rs | 12 ++ ...mref_common_mistakes_qualified_path.stderr | 5 + ..._data_common_mistakes_inferring_the_tag.rs | 18 ++ ...a_common_mistakes_inferring_the_tag.stderr | 33 +++ ...om_data_common_mistakes_unused_lifetime.rs | 6 + ...ata_common_mistakes_unused_lifetime.stderr | 7 + ...ommon_mistakes_match_behind_a_reference.rs | 16 ++ ...n_mistakes_match_behind_a_reference.stderr | 24 +++ example-code/tests/reference/types/chars.rs | 60 +++--- example-code/tests/reference/types/cons.rs | 54 +++-- example-code/tests/reference/types/either.rs | 57 +++--- example-code/tests/reference/types/field.rs | 57 ++++-- .../tests/reference/types/index_type.rs | 24 ++- example-code/tests/reference/types/life.rs | 74 ++++++- example-code/tests/reference/types/mod.rs | 2 +- example-code/tests/reference/types/mref.rs | 89 ++++++-- example-code/tests/reference/types/nil.rs | 31 ++- .../tests/reference/types/path_cons.rs | 38 ++-- .../tests/reference/types/phantom_data.rs | 54 ++--- example-code/tests/reference/types/void.rs | 49 ++++- 49 files changed, 1808 insertions(+), 582 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs create mode 100644 example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.stderr create mode 100644 example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs create mode 100644 example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.stderr create mode 100644 example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs create mode 100644 example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.stderr create mode 100644 example-code/tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.rs create mode 100644 example-code/tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.stderr create mode 100644 example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs create mode 100644 example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.stderr create mode 100644 example-code/tests/compile_fail/reference/types/life_definition_invariant.rs create mode 100644 example-code/tests/compile_fail/reference/types/life_definition_invariant.stderr create mode 100644 example-code/tests/compile_fail/reference/types/life_definition_not_send.rs create mode 100644 example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr create mode 100644 example-code/tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.rs create mode 100644 example-code/tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.stderr create mode 100644 example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs create mode 100644 example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.stderr create mode 100644 example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.rs create mode 100644 example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.stderr create mode 100644 example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.rs create mode 100644 example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index ef0048fa..9090636d 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -399,6 +399,9 @@ context type, which does not say a name is missing. Add `#[check_trait(Name)]`. **A passing check is not a claim that the implementation is correct**, only that it resolves. It proves the provider was found and its dependencies are satisfiable, not that the provider does what you meant. +One case slips past it: a component used at an unsized type parameter, such as `str`, passes its check +but fails at every call through the table, as the +[`delegate_components!`](./delegate_components.md#common-mistakes) page records. ## Related constructs diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index d0050262..55bbf52d 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -781,6 +781,14 @@ generic ` AreaCalculatorComponent` entry overlapping a specific `@ComputerComponent. Code.Circle`. The same applies to a direct entry for a path a joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#common-mistakes). +**A component used at an unsized type parameter passes its check and fails at the call.** The impl the +macro emits for each entry to forward the dependency marker requires the component's parameters to be +`Sized`, so a component declared over `T: ?Sized` and wired at `str` never works through the table, +though `check_components!` passes for it. A call reports `E0599` with the note +`` `str: Sized` which is required by … ``. This is a defect in the library. Until it is fixed, use a +sized parameter or implement the consumer trait directly on the context. The [`Life`](../types/life.md) +page shows the full example. + ## Related constructs - [`#[cgp_component]`](./cgp_component.md) — defines the components this table wires. diff --git a/docs/reference/traits/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md index abc487c0..ce5a8c52 100644 --- a/docs/reference/traits/wiring/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -243,7 +243,10 @@ it](#when-to-use-it) explains, which is why `delegate_and_check_components!` is a bundle. **A passing check does not test behavior.** It proves the wiring resolves and every dependency -exists, not that the provider computes the right thing. +exists, not that the provider computes the right thing. The trait asks the delegate's +`IsProviderFor` impl rather than the context's own, so a component used at an unsized type parameter +passes it and still fails at the call; see +[`delegate_components!`](../../macros/delegate_components.md#common-mistakes). ## Related constructs diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index 39dcc496..aceffb90 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -1,6 +1,8 @@ --- +title: 'Chars — a type-level character list' sidebar_label: 'Chars' sidebar_position: 9 +description: 'The character list behind Symbol!, which spells a field name out one character at a time so the name can be a type in trait resolution.' --- # `Chars` @@ -32,61 +34,76 @@ byte-length parameter, and the rest of the wrapper. This page covers the `Chars` its tail: ```rust +#[derive(Eq, PartialEq, Clone, Copy, Default)] pub struct Chars(pub PhantomData); ``` -`CHAR` is the character at this position, and `Tail` is the rest of the string, which is the next `Chars` -node or [`Nil`](nil.md) at the end. The character lives in the const parameter, and the tail lives in a -[`PhantomData`](phantom_data.md), so a `Chars` chain does not carry runtime data and compiles to -a zero-sized value. A `Symbol` then wraps such a chain together with the string's -byte length. The wrapper stores the length explicitly because stable Rust cannot compute it inside a -const-generic context, and the [`Symbol!`](../macros/symbol.md) page explains why. +`CHAR` is the character at this position, and `Tail` is the rest of the string, which is the next +`Chars` node or [`Nil`](nil.md) at the end. The character lives in the const parameter, and the tail +lives in a [`PhantomData`](phantom_data.md), so a `Chars` chain does not carry runtime data +and compiles to a zero-sized value. A `Symbol` then wraps such a chain +together with the string's byte length. The wrapper stores the length explicitly because stable Rust +cannot compute it inside a const-generic context, and the [`Symbol!`](../macros/symbol.md) page +explains why. Both `Chars` and `Symbol` are in the prelude. ## Behavior A `Chars` chain reconstructs its original string on demand through the -[`StaticFormat`](../traits/formatting/static_format.md) trait, which formats a type-level string into a -`Formatter` without needing a value. `Chars` writes `CHAR` and then recurses into the tail, -and [`Nil`](nil.md) ends the recursion by writing nothing. A `Symbol` forwards to its inner `Chars`, and -its `Display` impl defers to `StaticFormat`, so `::default().to_string()` yields -`"hello"`. +[`StaticFormat`](../traits/formatting/static_format.md) trait, which formats a type-level string +into a `Formatter` without needing a value. `Chars` writes `CHAR` and then recurses into +the tail, and [`Nil`](nil.md) ends the recursion by writing nothing. A `Symbol` forwards to its +inner `Chars`, and the `Display` impls on both defer to `StaticFormat`, so +`::default().to_string()` yields `"hello"`. The length a `Symbol` records enables [`StaticString`](../traits/formatting/static_string.md), which -exposes the string as a `const VALUE: &'static str` rather than as a formatting routine. It decodes the -characters into a byte buffer sized by that length at compile time. Code that needs the string at run -time uses `Display`, and code that needs it as a const uses `StaticString`. +exposes the string as a `const VALUE: &'static str` rather than as a formatting routine. It decodes +the characters into a byte buffer sized by that length at compile time. A bare `Chars` chain lacks +the length, so `StaticString` is implemented for `Symbol` and for `Nil`, not for `Chars`. Code that +needs the string at run time uses `Display`, and code that needs it as a const uses `StaticString`. ## Examples A type-level string most often appears as the tag in a -[`HasField`](../traits/field-access/has_field.md) bound, where it names the field a provider reads: +[`HasField`](../traits/field-access/has_field.md) bound, where it names the field a function or +provider reads. The same type rebuilds its string through `Display`: ```rust use cgp::prelude::*; -#[cgp_impl(new GreetHello)] -impl Greeter +// The tag names the field the function reads. +pub fn name_of(context: &Context) -> &str where - Self: HasField, + Context: HasField, { - fn greet(&self) { - println!("Hello, {}!", self.get_field(PhantomData::)); - } + context.get_field(PhantomData::) } -``` -You can also build the same type at run time and inspect it through its `Display` impl, which walks the -`Chars` chain to rebuild the string: - -```rust -use cgp::prelude::*; +#[derive(HasField)] +pub struct Person { + pub name: String, +} -let s = ::default(); -assert_eq!(s.to_string(), "hello"); +pub fn demo() { + let person = Person { + name: "Alice".to_owned(), + }; + assert_eq!(name_of(&person), "Alice"); + + // `Symbol!` spells the string out as a `Chars` chain, with its byte length in front. + let _: PhantomData>>>> = + PhantomData::; + let _: PhantomData>>> = PhantomData::; + + // `Display` walks the chain to rebuild the text. + let symbol = ::default(); + assert_eq!(symbol.to_string(), "hello"); + assert_eq!(core::mem::size_of::(), 0); +} ``` -Because the encoding is a list, an empty string is `Symbol<0, Nil>`: a `Symbol` whose character list is -just the terminator and whose recorded length is zero. +The two `PhantomData` annotations are the check on the expansion: `"世界"` records a length of `6`, +its UTF-8 byte count, over a chain of two `Chars` nodes. Because the encoding is a list, an empty +string is `Symbol<0, Nil>`: a `Symbol` whose character list is only the terminator. ## When to use it @@ -94,8 +111,7 @@ just the terminator and whose recorded length is zero. chain. You need to know the type so that you can decode a field name in a diagnostic. - **Decode a `Chars` chain by reading off the characters.** An error that mentions - `HasField>>>` says that the field `width` is missing, and - `cargo cgp check` restores the `Symbol!` form in the common cases. + `HasField>>>` says that the field `width` is involved. - **Use [`Symbol!`](../macros/symbol.md) for a field-name tag,** and let the ergonomic constructs produce it from an argument or a method name where they can. - **Use [`Index`](index_type.md) for a tuple-field position,** which encodes a number rather than a @@ -103,6 +119,53 @@ chain. You need to know the type so that you can decode a field name in a diagno ## Common Mistakes +**A missing field appears in a raw error as a `Chars` chain.** A provider that reads `width` and +`height`, wired on a context with only `height`, fails its check: + +```rust +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} +``` + +The compiler's help line names the missing tag, and the tag the context does have, character by +character: + +```text +help: the trait `HasField>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>>` is implemented for it +``` + +[`cargo cgp check`](/docs/cargo-cgp/check) reads the chain back into the name, and reports +``[CGP-E106] missing field `width` on `Rectangle` `` as the root cause. `cargo cgp check` leads with +the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet +reshape every class. + **The `LEN` in a wrapping `Symbol` is bytes, not characters.** For ASCII the two counts agree, so the difference shows only on a non-ASCII field name. There `LEN` does not match the visible character count, and the `Chars` chain is shorter than `LEN`. diff --git a/docs/reference/types/cons.md b/docs/reference/types/cons.md index 55f65ffa..36ac325c 100644 --- a/docs/reference/types/cons.md +++ b/docs/reference/types/cons.md @@ -1,6 +1,8 @@ --- +title: 'Cons — the product list cell' sidebar_label: 'Cons' sidebar_position: 5 +description: 'The head-and-tail cell of the type-level product list, which describes a record one field at a time so generic code can walk any struct''s fields.' --- # `Cons` @@ -36,19 +38,22 @@ a struct's layout becomes a `Product!` of `Field` cells over this list. pub struct Cons(pub Head, pub Tail); ``` -`Head` is the first element's type, and `Tail` is the rest of the list, which is another `Cons` or, at the -end, [`Nil`](nil.md). Both positional fields are public, so `Cons(head, tail)` builds a cell, and `.0` and -`.1` reach its parts. Unlike the zero-sized [`Chars`](chars.md) and [`PathCons`](path_cons.md) lists, -`Cons` holds real values. It is as large as its nested elements, without boxing or indirection. It derives -`Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a list of values that implement those traits -inherits them structurally, comparing head to head down the chain. +`Head` is the first element's type, and `Tail` is the rest of the list, which is another `Cons` or, +at the end, [`Nil`](nil.md). Both positional fields are public, so `Cons(head, tail)` builds a cell, +and `.0` and `.1` reach its parts. Unlike the zero-sized [`Chars`](chars.md) and +[`PathCons`](path_cons.md) lists, `Cons` holds real values. It is as large as its nested elements, +without boxing or indirection. It derives `Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a +list of values that implement those traits inherits them structurally: equality compares head to +head down the chain, and `Default` gives the list of defaults. It is in the prelude, and so is +`Nil`. ## Behavior -A list of any length is a `Cons` chain ending in `Nil`, nested to the right. The type `Product![A, B, C]` -is `Cons>>`, and the empty `Product![]` is just `Nil`. The tuple-struct -constructor builds the matching value, `Cons(a, Cons(b, Cons(c, Nil)))`. So a `product!` value is an -ordinary owned value, and its type is exactly the one `Product!` produces over the same element types. +A list of any length is a `Cons` chain ending in `Nil`, nested to the right. The type +`Product![A, B, C]` is `Cons>>`, and the empty `Product![]` is `Nil` alone. +The tuple-struct constructor builds the matching value, `Cons(a, Cons(b, Cons(c, Nil)))`. So a +`product!` value is an ordinary owned value, and its type is exactly the one `Product!` produces +over the same element types. Generic code consumes the list by recursing on its cases. A trait impl for `Nil` supplies the base case, the empty list. A blanket impl for `Cons` supplies the recursive step, and it usually @@ -58,9 +63,8 @@ product. It is how the field machinery processes a struct of any width without p ## Examples -The product list appears most visibly as the `Fields` of a struct that derives -[`HasFields`](../derives/derive_has_fields.md), where the [`Product!`](../macros/product.md) macro -hides the `Cons`/`Nil` chain: +A `product!` value is the nested `Cons` value, a struct's shape is a `Cons` chain of +[`Field`](field.md) entries, and a fold over the list is one impl for `Nil` and one for `Cons`: ```rust use cgp::prelude::*; @@ -71,29 +75,48 @@ pub struct Person { pub age: u8, } -// generated: -// impl HasFields for Person { -// type Fields = Product![ -// Field, -// Field, -// ]; -// // i.e. Cons, -// // Cons, Nil>> -// } -``` +pub type Row = Product![u32, String, bool]; -You can also write a standalone list type and a matching value through the macros, which expand to the -nested `Cons` form: +// A fold over a product list: `Nil` is the base case, `Cons` the step. +pub trait Len { + const LEN: usize; +} -```rust -use cgp::prelude::*; +impl Len for Nil { + const LEN: usize = 0; +} -type Row = Product![u32, String, bool]; -let row: Row = product![1, "hi".to_string(), true]; -// Row == Cons>> -// row == Cons(1, Cons("hi".to_string(), Cons(true, Nil))) +impl Len for Cons { + const LEN: usize = 1 + Tail::LEN; +} + +pub fn demo() { + // `product!` builds the same nested value a hand-written chain does. + let row: Row = product![1, "hi".to_owned(), true]; + let by_hand: Cons>> = + Cons(1, Cons("hi".to_owned(), Cons(true, Nil))); + assert_eq!(row, by_hand); + + // A struct's shape is a `Cons` chain of `Field` entries. + let Cons(name, Cons(age, Nil)): Cons< + Field, + Cons, Nil>, + > = Person { + name: "Alice".to_owned(), + age: 30, + } + .to_fields(); + assert_eq!((name.value.as_str(), age.value), ("Alice", 30)); + + assert_eq!(::LEN, 3); + assert_eq!(<::Fields as Len>::LEN, 2); +} ``` +The annotation on the `Person` pattern is the check that the derive assigned the `Cons` chain +written there. [`#[derive(HasFields)]`](../derives/derive_has_fields.md) writes it with the macro, +as `type Fields = Product![Field, Field];`. + ## When to use it **Read `Cons` in an expansion, and write [`Product!`](../macros/product.md) instead.** The macro produces @@ -104,13 +127,17 @@ the list. Writing the chain out yourself is longer, harder to change, and identi drift apart. - **Use [`Product!`](../macros/product.md) for a list you write deliberately,** such as a handler pipeline, and let the macro build the chain. +- **Name `Cons` and `Nil` in the impls of a fold,** as `Len` does above. That is the one place the + cells themselves are written, since an impl matches on the cell rather than on the macro. - **Decode a `Cons` chain in an error by counting cells.** The compiler reports a field-list mismatch as a mismatch between two `Cons` chains, and the position where they diverge is the field that differs. ## Common Mistakes -**A one-element list is not the element.** `Product![T]` is `Cons`, a distinct type from `T`, so a -list of one still carries its cell. +**A one-element list is not the element.** `Product![T]` is `Cons`, a distinct type from +`T`, so a list of one still carries its cell. A one-field tuple struct is the exception on the +derive's side: its shape is the field's type itself rather than a list of one, as +[`Field`](field.md) describes. **Element order is part of the type.** `Cons>` and `Cons>` are unrelated types. For a field list this matters less than it sounds, because the entries are name-tagged @@ -129,6 +156,8 @@ is the uninhabited [`Void`](void.md). An empty record can exist, but an empty ch - [`Field`](field.md): what the elements usually are, pairing a name with a value. - [`HasFields`](../traits/shape/has_fields.md): exposes a struct's shape as one of these lists. - [`#[derive(HasFields)]`](../derives/derive_has_fields.md): generates that list for a struct. +- [`AppendProduct`](../traits/type-level/append_product.md): one of the operations that transform a + product list. The ideas behind it: diff --git a/docs/reference/types/either.md b/docs/reference/types/either.md index 77cc1710..690ecfa5 100644 --- a/docs/reference/types/either.md +++ b/docs/reference/types/either.md @@ -1,6 +1,8 @@ --- +title: 'Either — the sum list cell' sidebar_label: 'Either' sidebar_position: 7 +description: 'The head-or-rest cell of the type-level sum list, which describes an enum one variant at a time so generic code can match any enum''s variants.' --- # `Either` @@ -38,18 +40,20 @@ pub enum Either { } ``` -`Head` is the type of the current branch, and `Tail` is the rest of the chain, which is another `Either` -or, at the end, [`Void`](void.md). `Left(Head)` carries a value of the head type, and `Right(Tail)` -carries a value that belongs further down the chain. It derives `Eq`, `PartialEq`, `Debug`, and `Clone`, -so a sum of values that implement those traits inherits them. +`Head` is the type of the current branch, and `Tail` is the rest of the chain, which is another +`Either` or, at the end, [`Void`](void.md). `Left(Head)` carries a value of the head type, and +`Right(Tail)` carries a value that belongs further down the chain. It derives `Eq`, `PartialEq`, +`Debug`, and `Clone`, so a sum of values that implement those traits inherits them. It is in the +prelude, and so is `Void`. ## Behavior -A sum of any width is an `Either` chain ending in `Void`, nested to the right. The type `Sum![A, B, C]` -is `Either>>`, and the empty `Sum![]` is just `Void`. A value selects one -branch by its nesting depth: `Left(a)` is an `A`, `Right(Left(b))` is a `B`, and `Right(Right(Left(c)))` -is a `C`. A value at the `Void` position would match none of the listed branches. That is impossible, -because a value of `Void` cannot exist, so the chain is closed at its end. +A sum of any width is an `Either` chain ending in `Void`, nested to the right. The type +`Sum![A, B, C]` is `Either>>`, and the empty `Sum![]` is `Void` alone. +A value selects one branch by its nesting depth: `Left(a)` is an `A`, `Right(Left(b))` is a `B`, and +`Right(Right(Left(c)))` is a `C`. A value at the `Void` position would match none of the listed +branches. That is impossible, because a value of `Void` cannot exist, so the chain is closed at its +end. Generic code consumes the sum by recursing on its cases, in the same way it folds the product list, but it branches instead of pairing. The code handles a `Left` directly as the head. A `Right` defers to a trait @@ -57,11 +61,15 @@ impl on the `Tail`, which recurses until it finds a `Left`. The base case is the terminator, and here the difference from the product list matters. A product ends in the constructible [`Nil`](nil.md), but a sum ends in the uninhabited `Void`, because an empty choice cannot hold a value. +An enum's shape follows each variant's own form. A variant with one unnamed field has that field's +type as its payload, a variant with named fields has a product of `Field` entries keyed by name, a +variant with several unnamed fields has one keyed by [`Index`](index_type.md), and a unit variant +has [`Nil`](nil.md). + ## Examples -The sum list appears most visibly as the `Fields` of an enum that derives -[`#[derive(HasFields)]`](../derives/derive_has_fields.md), where the [`Sum!`](../macros/sum.md) macro -hides the `Either`/`Void` chain: +An enum's shape is an `Either` chain of `Field` branches, and a `match` on it selects a variant by +depth, with the `Void` arm closing the match: ```rust use cgp::prelude::*; @@ -72,32 +80,56 @@ pub enum Shape { Rectangle { width: f64, height: f64 }, } -// generated (schematically): -// impl HasFields for Shape { -// type Fields = Sum![ -// Field, -// Field, -// Field, -// ]>, -// ]; -// // i.e. Either, -// // Either, Void>> -// } -``` +pub fn area(shape: Shape) -> f64 { + match shape.to_fields() { + Either::Left(circle) => core::f64::consts::PI * circle.value * circle.value, + Either::Right(Either::Left(rectangle)) => { + let Cons(width, Cons(height, Nil)) = rectangle.value; + width.value * height.value + } + Either::Right(Either::Right(void)) => match void {}, + } +} -You can also write a standalone sum type through the macro, and a value picks one branch by its nesting -depth: +pub type Token = Sum![u32, String, bool]; -```rust -use cgp::prelude::*; +pub fn demo() { + assert_eq!( + area(Shape::Rectangle { + width: 2.0, + height: 3.0 + }), + 6.0 + ); + + // The `String` branch sits one `Right` deep. + let token: Token = Either::Right(Either::Left("hi".to_owned())); + assert_eq!(token, Either::Right(Either::Left("hi".to_owned()))); -type Token = Sum![u32, String, bool]; -// Token == Either>> + // `Sum!` is the right-nested `Either` chain ending in `Void`. + let _: PhantomData>>> = PhantomData::; +} +``` + +The derive writes `Shape`'s shape with the macros: -let t: Token = Either::Right(Either::Left("hi".to_string())); // the String branch +```rust +impl HasFields for Shape { + type Fields = Sum![ + Field, + Field, + Field, + ]>, + ]; +} ``` +The `Void` arm in `area` states that the chain ends, and `match void {}` is accepted because `Void` +is uninhabited. Here the arm may also be left out, since `to_fields` returns the shape by value and +Rust lets a match on a value omit an arm whose payload is uninhabited. Behind a reference the arm is +required, as the [`Void`](void.md) page shows. + ## When to use it **Read `Either` in an expansion, and write [`Sum!`](../macros/sum.md) instead.** The macro produces the @@ -110,12 +142,16 @@ list. Writing the chain out yourself is longer, harder to change, and identical - **Use [`Cons`](cons.md), not `Either`, when every element is present at once.** A product holds a value for every element, and a sum holds a value for exactly one. They are duals, and mixing them produces a type error rather than a subtle bug. +- **Use the [extractor family](../traits/variant/extract_field.md)** to take an enum apart by + variant name in generic code. A `match` on the `Either` chain, as above, is positional and belongs + where the enum's order is known. ## Common Mistakes -**A sum holds one branch, not all of them.** `Either>` is a value that is *either* an -`A` or a `B`, not both. This is the opposite of the [product list](cons.md), and confusing the two is the -usual cause of an "expected `Either`, found `Cons`" error. +**A sum holds one branch, not all of them.** `Either>` is a value that is +*either* an `A` or a `B`, not both. This is the opposite of the [product list](cons.md), and a type +written with one where the other is expected fails as a mismatch between an `Either` chain and a +`Cons` chain. **The empty sum is the uninhabited [`Void`](void.md), not a value.** `Sum![]` is `Void`, which is uninhabited, so code cannot construct an empty choice. It can construct an empty record, because a record @@ -132,7 +168,8 @@ it sounds, but the types still differ. - [`Sum!`](../macros/sum.md): the macro that folds element types onto this list. - [`Field`](field.md): what the branches usually are, pairing a variant name with its payload. - [`HasFields`](../traits/shape/has_fields.md): exposes an enum's shape as one of these lists. -- [`ExtractField`](../traits/variant/extract_field.md): the extractor family that walks this list. +- [`ExtractField`](../traits/variant/extract_field.md): the extractor family that takes an enum + apart by variant name. The ideas behind it: diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index 3063d13a..c18651c5 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -1,6 +1,8 @@ --- +title: 'Field — a value tagged with its name' sidebar_label: 'Field' sidebar_position: 2 +description: 'A value paired with its type-level name tag, so a struct''s fields and an enum''s variants can be described one named entry at a time.' --- # `Field` @@ -40,10 +42,12 @@ pub struct Field { } ``` -`Tag` is the type-level name of the field. It appears only inside `PhantomData`, never in a stored -field. It is usually a [type-level string](/docs/reference/glossary#type-level-string) such as `Symbol!("name")` for a named field, or a type-level -number such as `Index<0>` for a tuple position. `Value` is the field's actual type, and `value` is the -only data the struct keeps. Apart from the tag, a `Field` is a thin wrapper around its `Value`. +`Tag` is the type-level name of the field. It appears only inside `PhantomData`, never in a +stored field. It is usually a [type-level string](/docs/reference/glossary#type-level-string) such +as `Symbol!("name")` for a named field, or a type-level number such as `Index<0>` for a tuple +position. `Value` is the field's actual type, and `value` is the only data the struct keeps. Apart +from the tag, a `Field` is a thin wrapper around its `Value`. It is in the prelude, so +`use cgp::prelude::*;` is enough. ## Behavior @@ -52,21 +56,28 @@ rather than from you. The `From` impl fills in `value` and sets `phantom` `let f: Field = "Alice".to_string().into();` compiles, and the compiler infers the tag from the expected type. This is why generated code builds each entry with a plain `.into()`. -The other trait impls defer to the value and ignore the tag, so a `Field` behaves like its `Value` for -comparison and printing. `Debug` forwards to the value's `Debug` and does not show the tag. +The other trait impls defer to the value and ignore the tag, so a `Field` behaves like its `Value` +for comparison and printing. `Debug` forwards to the value's `Debug` and does not show the tag. `PartialEq` and `Eq` compare only `value`, each gated on the matching bound on `Value`. Two `Field` -values are equal when their values are equal. The tag is a compile-time matter and plays no part at run -time. +values are equal when their values are equal. The tag is a compile-time matter and does not take +part at run time. `Field` implements nothing else: it is not `Clone`, `Copy`, or `Default`, whatever +its `Value` is. Because the tag lives only in `PhantomData`, code that needs the name reads it from the `Tag` parameter through trait resolution rather than from stored data. For example, it matches a `Field` against a [`HasField`](../traits/field-access/has_field.md) bound. +**A tuple struct with exactly one field is the exception to the wrapping.** Its shape is the field's +type itself, without a `Field` around it or a list, so `struct Meters(u32)` has `Fields = u32`. A +tuple struct with two or more fields tags each entry by position, as `Field, u32>`. Inside +an enum, a variant with a single unnamed field has that field's type as its payload in the variant's +`Field`. + ## Examples -`Field` appears most often inside the shape a derive generates, where each struct field becomes one -entry tagged by its [`Symbol!`](../macros/symbol.md) name: +A struct's shape, as [`#[derive(HasFields)]`](../derives/derive_has_fields.md) assigns it, is a list +of `Field` entries, and [`to_fields`](../traits/shape/to_fields.md) turns a value into that list: ```rust use cgp::prelude::*; @@ -77,26 +88,50 @@ pub struct Person { pub age: u8, } -// generated: -// impl HasFields for Person { -// type Fields = Product![ -// Field, -// Field, -// ]; -// } -``` - -You can also build a single `Field` directly from its value, with the type annotation supplying the tag: - -```rust -use cgp::prelude::*; +#[derive(HasFields)] +pub struct Point(pub u32, pub u32); -let name: Field = "Alice".to_string().into(); -assert_eq!(name.value, "Alice"); +#[derive(HasFields)] +pub struct Meters(pub u32); + +pub fn demo() { + // A struct's shape is a list of `Field` entries, each tagged by its name. + let fields: Product![Field, Field] = Person { + name: "Alice".to_owned(), + age: 30, + } + .to_fields(); + + let Cons(name, Cons(age, Nil)) = fields; + assert_eq!(name.value, "Alice"); + assert_eq!(age.value, 30); + + // A tuple struct's entries are tagged by position. + let Cons(x, Cons(y, Nil)): Product![Field, u32>, Field, u32>] = + Point(3, 4).to_fields(); + assert_eq!((x.value, y.value), (3, 4)); + + // A one-field tuple struct's shape is the field's type itself. + let inner: u32 = Meters(7).to_fields(); + assert_eq!(inner, 7); + + // One entry, built from its value; the annotation supplies the tag. + let entry: Field = "Bob".to_owned().into(); + assert_eq!(entry.value, "Bob"); + + // The tag adds no size, and `Debug` prints the value alone. + assert_eq!( + core::mem::size_of::>(), + core::mem::size_of::() + ); + assert_eq!(format!("{entry:?}"), "\"Bob\""); +} ``` -For a tuple-struct field the tag is an [`Index`](index_type.md) rather than a `Symbol!`, so the same -wrapper names a positional field, as `Field, u32>`. +The annotations on `fields` and on the tuple pattern are the check: each names the list type the +derive assigned, and the program compiles only if it matches. The derive writes that list as +`type Fields = Product![Field, Field];` for `Person`, +and as `type Fields = u32;` for `Meters`. ## When to use it @@ -121,6 +156,10 @@ run time. It distinguishes them only in the type. **A `Field` is the size of its `Value`, not larger.** The tag occupies zero bytes, so wrapping a value in a `Field` is free at run time. +**A one-field tuple struct's shape lacks a `Field`.** Code that expects every shape to be a list of +`Field` entries meets a bare `u32` for `struct Meters(u32)`, since the derive treats such a struct +as a newtype around its field. + **The tag must match exactly for a lookup to resolve.** `Field` and `Field` carry unrelated tags, so a name mismatch appears as an unsatisfied [`HasField`](../traits/field-access/has_field.md) bound rather than as a typo. diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index 15807c88..68e995f5 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The type-level building blocks CGP is made of, the markers and recursive lists that carry names, positions, and shapes, plus the MRef getter type.' --- # Types @@ -40,9 +41,9 @@ these lists through the macros ([`Product!`](../macros/product.md), [`Sum!`](../ [`Symbol!`](../macros/symbol.md), and [`Path!`](../macros/path.md)) and read them in expansions and errors. -[`MRef`](mref.md) is the one type here that is not a building block. It is an ordinary runtime value, the -owned-or-borrowed return type of a getter. It belongs in this section because it is the one type here that -you write yourself. +[`MRef`](mref.md) is the one type here that is not a building block. It is an ordinary runtime +value, the owned-or-borrowed return type of a getter. It belongs in this section because it is a +type rather than a trait or a provider, and you name it yourself as a getter's return type. ## The ideas behind them diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index ca426725..78025eb7 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -1,6 +1,8 @@ --- +title: 'Index — a tuple field position as a type' sidebar_label: 'Index' sidebar_position: 3 +description: 'A number lifted into a type, so a tuple-struct field can be named by its position the way Symbol! names a field by its string.' --- # `Index` @@ -17,12 +19,12 @@ same trait-resolution machinery as named fields. `Index` is that type. It car parameter and nothing else, so `Index<0>`, `Index<1>`, and `Index<2>` are distinct types that stand for a tuple struct's positional fields. -Encoding the position as a type lets positional field access resolve through traits. Here a **context** is -the type the method runs on. It supplies the values the method needs as its own fields. +Encoding the position as a type lets positional field access resolve through traits. Here a +**context** is the type the method runs on, which supplies the values it needs as its fields. Because `Index<0>` is a type, a context can carry a [`HasField>`](../traits/field-access/has_field.md) impl for its first field and a -`HasField>` impl for its second, side by side. The compiler selects the right one from the tag -alone, exactly as it does for differently named `Symbol!` tags. `Index` is the numeric counterpart to +`HasField>` impl for its second, side by side. The compiler selects the right one from the +tag alone, as it does for differently named `Symbol!` tags. `Index` is the numeric counterpart to `Symbol!`. A field is keyed by a `Symbol!` when it has a name, and by an `Index` when it has only a position. @@ -40,22 +42,27 @@ a [`Field`](field.md) entry inside a tuple struct's shape, and as the type insid pub struct Index; ``` -`I` is the position the type represents: `Index<0>` for the field at offset zero, and so on. The struct -is empty, so a value of `Index` holds nothing, and the number lives entirely in the type. The -derived `Default`, `Clone`, and `Copy` make a value available whenever code needs one. `Eq` and -`PartialEq` treat any two values of the same `Index` as equal, because they hold no data. `Index` -also implements `Display` and `Debug`, and both print the underlying number. So `Index<0>` displays as -`0`, and output and diagnostics show the position a tag stands for. +`I` is the position the type represents: `Index<0>` for the field at offset zero, and so on. The +struct is empty, so a value of `Index` holds nothing, and the number lives entirely in the type. +The derived `Default`, `Clone`, and `Copy` make a value available whenever code needs one. `Eq` and +`PartialEq` treat any two values of the same `Index` as equal, because they hold nothing. +`Index` also implements `Display` and `Debug`, and both print the underlying number. So +`Index<0>` displays as `0`, and output and diagnostics show the position a tag stands for. It is in +the prelude, so `use cgp::prelude::*;` is enough. ## Behavior A tuple struct keys each of its fields by `Index`, counting from zero, so code reads the field at position `N` through the tag `Index`. When a tuple struct derives -[`#[derive(HasField)]`](../derives/derive_has_field.md), the generated impl uses `Index<0>` for the `.0` -field, `Index<1>` for `.1`, and so on. Each `get_field(PhantomData::>)` call maps to the -matching positional access. Those tags then appear as the tag of each [`Field`](field.md) entry in the -tuple struct's [`HasFields`](../traits/shape/has_fields.md) shape. So generic code that walks the field -list reads positions where it would read `Symbol!` names for a named struct. +[`#[derive(HasField)]`](../derives/derive_has_field.md), the generated impls use `Index<0>` for the +`.0` field, `Index<1>` for `.1`, and so on, with a `HasFieldMut` impl beside each `HasField` one. +Each `get_field(PhantomData::>)` call maps to the matching positional access. + +The same tags name the entries of a tuple struct's [`HasFields`](../traits/shape/has_fields.md) +shape when it has two or more fields, a list of `Field, _>` entries. So generic code that +walks the field list reads positions where it would read `Symbol!` names for a named struct. A tuple +struct with exactly one field is the exception: its shape is the field's type itself, without a +`Field, _>` around it, although its `HasField>` impl still exists. Because `Index` is zero-sized and the position lives in the type, a field access by index resolves entirely at compile time. The access does not check an array bound and does not index at run time. @@ -64,37 +71,40 @@ Selecting the wrong index is a type error rather than a panic, because a three-f ## Examples -When a tuple struct derives `HasField`, the derive tags each positional field with an `Index`: +A tuple struct that derives `HasField` is read by position, and an `Index` prints the number it +stands for: ```rust use cgp::prelude::*; +#[derive(HasField)] pub struct Pair(pub u32, pub String); -// generated for the first field: -// impl HasField> for Pair { -// type Value = u32; -// fn get_field(&self, _tag: PhantomData>) -> &u32 { -// &self.0 -// } -// } -``` - -You then read a field by supplying the `Index` tag, and the compiler fixes the chosen position: +pub fn demo() { + let pair = Pair(7, "hi".to_owned()); -```rust -use cgp::prelude::*; + assert_eq!(*pair.get_field(PhantomData::>), 7); + assert_eq!(pair.get_field(PhantomData::>), "hi"); -let pair = Pair(7, "hi".to_string()); -assert_eq!(*pair.get_field(PhantomData::>), 7); + // `Display` and `Debug` both print the number. + assert_eq!(Index::<2>.to_string(), "2"); + assert_eq!(format!("{:?}", Index::<2>), "2"); +} ``` -The number an `Index` carries is also visible through its `Display` impl: +The derive generates one impl pair per position. For the first field it writes: ```rust -assert_eq!(Index::<2>.to_string(), "2"); +impl HasField> for Pair { + type Value = u32; + fn get_field(&self, key: ::core::marker::PhantomData>) -> &Self::Value { + &self.0 + } +} ``` +and a matching `HasFieldMut>` impl returning `&mut self.0`. + ## When to use it **Use `Index` for a tuple-field tag, and let the derive produce it where it can.** The derive generates it @@ -110,15 +120,28 @@ so you write it only when you tag a positional field yourself. ## Common Mistakes -**`Index` and `Symbol!("N")` are different types.** A tuple field is keyed by the number lifted into a -type, not by a string of the digit, so `Symbol!("0")` never matches a tuple field and the derive never -generates it. +**A position the struct lacks is a type error, not a panic.** Reading `Index<5>` on a three-field +tuple struct does not compile: + +```rust +#[derive(HasField)] +pub struct Point(pub f64, pub f64, pub f64); + +pub fn sixth(point: &Point) -> f64 { + *point.get_field(PhantomData::>) +} +``` -**Indices count from zero.** `Index<0>` is the first field, matching Rust's own `.0` access. An -off-by-one error here appears as a missing `HasField` impl rather than as an out-of-range error. +The compiler reports +``error[E0277]: the trait bound `Point: cgp::prelude::HasField>` is not satisfied``, +and lists the three `HasField>` to `HasField>` impls the struct does have. Indices +count from zero, as Rust's own `.0` access does, so an off-by-one error surfaces the same way. -**Selecting a position that does not exist is a type error, not a panic.** A three-field struct lacks a -`HasField` impl for `Index<5>`, so the compiler catches the mistake. +**`Index` and `Symbol!("N")` are different types.** A tuple field is keyed by the number lifted +into a type, not by a string of the digit, so `Symbol!("0")` never matches a tuple field and the +derive never generates it. `pair.get_field(PhantomData::)` on the `Pair` above fails +with +``error[E0277]: the trait bound `Pair: cgp::prelude::HasField>>` is not satisfied``. ## Related constructs diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index c086bcd8..7d528137 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -1,6 +1,8 @@ --- +title: 'Life — a lifetime lifted into a type' sidebar_label: 'Life' sidebar_position: 4 +description: 'A lifetime lifted into a type, so a component''s lifetime parameter can travel through the dependency marker, whose parameters are types.' --- # `Life` @@ -18,10 +20,11 @@ lifetime cannot sit in that tuple, because a tuple is a type and its members mus parameter on the trait must first become a type. `Life<'a>` is that conversion. It packages the lifetime `'a` as a concrete type that can stand beside the trait's other type parameters. -Without this lift, a trait that borrows could not record its lifetime in the dependency marker, and the -wiring could not tell one lifetime instantiation from another. `Life` lets the lifetime pass through -`IsProviderFor` as `(Life<'a>, T)`, so it stays part of the provider's identity while the marker's -argument stays a plain type. +Without this lift, a trait that borrows could not record its lifetime in the dependency marker. +`Life` lets the lifetime pass through `IsProviderFor` as `(Life<'a>, T)`, so it stays part of the +provider's identity while the marker's argument stays a plain type. The macros insert it, so you +read it in generated code and in errors, and you write it in one place: the +[`check_components!`](../macros/check_components.md) entry for a component with a lifetime. ## Definition @@ -32,31 +35,43 @@ pub struct Life<'a>(pub PhantomData<*mut &'a ()>); ``` The struct holds nothing at run time. Its only job is to carry the lifetime `'a` in the type system -through [`PhantomData`](phantom_data.md). The choice of `PhantomData<*mut &'a ()>` is deliberate, -because it controls how `Life<'a>` relates to other lifetimes under subtyping. A `*mut T` is -*invariant* in `T`, so wrapping `&'a ()` behind a `*mut` makes `Life<'a>` invariant in `'a`. A -`Life<'long>` is neither a subtype nor a supertype of a `Life<'short>`. - -Invariance is correct here because the lifetime is an exact identity in the dependency marker. The -compiler must treat two providers wired for different lifetimes as wired for different things. A variant -`Life` would let the compiler coerce one instantiation into another and pick the wrong provider. The raw -pointer also means that `Life<'a>` does not carry auto-trait obligations tied to a real borrow, because -it neither owns nor references a real value. +through [`PhantomData`](phantom_data.md). It is in the prelude, so `use cgp::prelude::*;` is enough. + +The phantom type `*mut &'a ()` decides how `Life<'a>` behaves under subtyping. A `*mut T` is +*invariant* in `T`, so wrapping `&'a ()` behind a `*mut` makes `Life<'a>` invariant in `'a`: a +`Life<'long>` is neither a subtype nor a supertype of a `Life<'short>`. The lifetime is therefore an +exact identity wherever subtyping could apply, as in a provider struct holding a +`PhantomData>`. Trait resolution itself matches lifetimes exactly whatever the variance, so +the choice affects values and types that contain `Life`, not which impl the compiler selects. + +The raw pointer has a second effect: `Life<'a>` is neither `Send` nor `Sync`. Neither is any struct +holding a `PhantomData>`, such as the provider struct `#[cgp_impl(new …)]` declares for a +provider generic over a lifetime. This rarely matters, because `Life` and provider structs appear +only at the type level and are never sent between threads, but a bound such as `Provider: Send` on +such a provider fails with +``error[E0277]: `*mut &'static ()` cannot be sent between threads safely``. ## Behavior -`Life` does not define methods and does not implement CGP traits of its own. Its entire behavior is to +`Life` does not define methods and does not implement traits of its own. Its entire behavior is to occupy a type position. In the generated provider trait for a component with a lifetime, the macro -collects the lifetime into the [`IsProviderFor`](../traits/wiring/is_provider_for.md) argument tuple as -`Life<'a>`, so the provider's dependency obligation reads the same way as for any type parameter. The -provider trait, its blanket forwarding impl, and the impls that satisfy it all agree on the same -`(Life<'a>, T)` shape. That shared shape lets CGP wire and check a borrowing component exactly like a +collects the lifetime into the [`IsProviderFor`](../traits/wiring/is_provider_for.md) argument tuple +as `Life<'a>`, so the provider's dependency obligation reads the same way as for any type parameter. +The provider trait, its blanket forwarding impl, and the impls that satisfy it all agree on the same +`(Life<'a>, T)` shape. That shared shape lets CGP wire and check a borrowing component like a non-borrowing one. +A check names the shape itself. A `check_components!` entry lists a component's parameters in the +form the marker records them, so a component with a lifetime is checked as `(Life<'a>, T)`, with the +lifetime declared on the table, as in +`<'a> App<'a> { ReferenceGetterComponent: (Life<'a>, Config) }`. A bare `('a, Config)` is rejected: +the compiler reads `'a` as a trait-object type without a trait and reports +`error: at least one trait is required for an object type`. + ## Examples -`Life` appears in the wiring generated for a component whose consumer trait carries a lifetime. Given a -borrowing getter component: +A borrowing getter component, wired on a context that holds a borrow, and checked with `Life` in its +parameter tuple: ```rust use cgp::prelude::*; @@ -65,34 +80,78 @@ use cgp::prelude::*; pub trait HasReference<'a, T: 'a + ?Sized> { fn get_reference(&self) -> &'a T; } + +pub struct Config { + pub name: String, +} + +#[cgp_impl(new GetConfig)] +#[uses(HasField)] +impl<'a> ReferenceGetter<'a, Config> { + fn get_reference(&self) -> &'a Config { + self.get_field(PhantomData::) + } +} + +#[derive(HasField)] +pub struct App<'a> { + pub config: &'a Config, +} + +delegate_components! { + <'a> App<'a> { + ReferenceGetterComponent: GetConfig, + } +} + +check_components! { + <'a> App<'a> { + ReferenceGetterComponent: (Life<'a>, Config), + } +} + +pub fn demo() { + let config = Config { + name: "demo".to_owned(), + }; + let app = App { config: &config }; + + let config_ref: &Config = app.get_reference(); + assert_eq!(config_ref.name, "demo"); +} ``` -the generated provider trait records the lifetime in its dependency marker through `Life`, so its -`IsProviderFor` bound names the lifetime as the type `Life<'a>` rather than as a bare `'a`: +`App` is an environmental context: it holds the borrowed configuration a provider reads, and the +component is parameter-targeted, returning a borrow of `T` for the lifetime `'a`. The generated +provider trait records the lifetime in its dependency marker as the type `Life<'a>`, as +`cargo cgp expand` shows: ```rust -// generated, in readable form: -// pub trait ReferenceGetter<'a, __Context__, T: 'a + ?Sized>: -// IsProviderFor, T)> -// { -// fn get_reference(__context__: &__Context__) -> &'a T; -// } +pub trait ReferenceGetter< + 'a, + __Context__, + T: 'a + ?Sized, +>: IsProviderFor, T)> { + fn get_reference(__context__: &__Context__) -> &'a T; +} ``` -Every impl that wires this component, whether through `UseContext`, a `UseField` getter, or a provider you -write yourself, carries the same `(Life<'a>, T)` tuple, so the resolution machinery preserves the lifetime -end to end. +Every impl that satisfies this component, whether through `UseContext`, a table's forwarding impl, +or a provider you write yourself, carries the same `(Life<'a>, T)` tuple, so the resolution +machinery preserves the lifetime end to end. ## When to use it -**You read `Life` in generated code, and you do not write it.** The macros insert it, and you only need to -recognize it. +**You read `Life` in generated code, and you write it only in a check.** The macros insert it +everywhere else. - **Read `Life<'a>` in an `IsProviderFor` tuple as the component's lifetime.** A dependency marker such as `IsProviderFor<..., (Life<'a>, T)>` names a lifetime and a type parameter, in that order. -- **Do not substitute a bare [`PhantomData`](phantom_data.md) for it** when you write a lifetime marker - yourself. A plain `PhantomData<&'a ()>` is covariant, which is the wrong relationship for a dependency - marker. `Life` forces the invariance that keeps two lifetime instantiations distinct. +- **Write `(Life<'a>, T)` in a `check_components!` entry** for a component with a lifetime, and + declare `'a` in the table's generic list. +- **Hold a lifetime as `PhantomData>`** when you declare a provider struct by hand and want + the shape `#[cgp_new_provider]` gives it. A plain [`PhantomData<&'a ()>`](phantom_data.md) also + compiles, but it is covariant and keeps the struct `Send`. ## Common Mistakes @@ -100,9 +159,51 @@ recognize it. `'a` is invalid there, and the macro lifts it into `Life<'a>`. `Life` in an error means that the component carries a lifetime. -**`Life<'a>` is invariant in `'a` by design.** It does not behave like `&'a ()`, which is covariant. The -invariance keeps the compiler from confusing providers wired for different lifetimes, so it is intended -rather than an over-restriction. +**A component whose target is unsized passes its check but fails at the call.** The `?Sized` bound +on `T` above admits `str`, and wiring such a component at `str` compiles and checks: + +```rust +#[cgp_impl(new GetName)] +#[uses(HasField)] +impl<'a> ReferenceGetter<'a, str> { + fn get_reference(&self) -> &'a str { + self.get_field(PhantomData::) + } +} + +#[derive(HasField)] +pub struct Borrowed<'a> { + pub name: &'a str, +} + +delegate_components! { + <'a> Borrowed<'a> { + ReferenceGetterComponent: GetName, + } +} + +check_components! { + <'a> Borrowed<'a> { + ReferenceGetterComponent: (Life<'a>, str), + } +} +``` + +A call such as `let name: &str = borrowed.get_reference();` then fails with +``error[E0599]: the method `get_reference` exists for struct `Borrowed<'_>`, but its trait bounds were not satisfied``, +whose note names the unmet bound: + +```text + = note: the following trait bounds were not satisfied: + `str: Sized` + which is required by `Borrowed<'_>: HasReference<'_, str>` +``` + +The parameter tuple `(Life<'a>, str)` is unsized, and the forwarding impl that +[`delegate_components!`](../macros/delegate_components.md) emits for the table requires its +parameter tuple to be `Sized`, while the check goes to the provider's own impl and passes. This is a +defect in the library. Until it is fixed, give such a component a sized target, as `Config` is +above, or implement the consumer trait directly on the context. **A [higher-order provider](/docs/reference/glossary#higher-order-provider) with a lifetime loses its dependency propagation.** When the component carries a lifetime, the inner-provider bound of such a stack does not get a marker counterpart, because the rewrite @@ -116,6 +217,8 @@ compiles and runs. But it loses the propagation that lets `#[check_providers]` l into as `Life<'a>`. - [`#[cgp_component]`](../macros/cgp_component.md): inserts `Life` when a consumer trait carries a lifetime. +- [`check_components!`](../macros/check_components.md): where a check names `Life` in a parameter + tuple. - [`PhantomData`](phantom_data.md): the marker `Life` is built from, wrapped for invariance. - [`Index`](index_type.md) and [`Chars`](chars.md): the other lifts that make a non-type addressable in trait resolution, a number and a string where `Life` lifts a lifetime. @@ -129,9 +232,11 @@ The ideas behind it: - The type: [`life.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/life.rs) -- The macro logic that wraps a trait's lifetime parameters in `Life` when building the `IsProviderFor` - argument tuple: - [`is_provider_params.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/is_provider_params.rs) +- The macro logic that wraps a trait's lifetime parameters in `Life` when building the + `IsProviderFor` argument tuple: + [`is_provider_params.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/functions/is_provider_params.rs), + with the same lifting in a provider struct's `PhantomData` in + [`empty_struct.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/empty_struct.rs) --- diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 1b439427..152df3b8 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -13,13 +13,13 @@ whichever it has without forcing every implementor to one or the other. ## Overview `MRef<'a, T>` lets one getter signature serve both the context that already stores a value and the -context that must produce one. Here a **context** is the type the method runs on. It supplies the -values the method needs as its own fields. A getter that returns `&'a T` forces every context to keep -a `T` it can lend. A getter that returns `T` forces every context to give up ownership, and to clone even -when it could share a reference. `MRef<'a, T>` avoids both constraints by being either case at run time. A -context with the value in a field returns `MRef::Ref` and lends it. A context that computes or assembles -the value returns `MRef::Owned` and transfers it. The caller treats both the same, because `MRef` derefs -to `T`. +context that must produce one. Here a **context** is the type the method runs on, which supplies the +values it needs as its fields. A getter that returns `&'a T` forces every context to keep a `T` it +can lend. A getter that returns `T` forces every context to give up ownership, and to clone even +when it could share a reference. `MRef<'a, T>` avoids both constraints by being either case at run +time. A context with the value in a field returns `MRef::Ref` and lends it. A context that computes +or assembles the value returns `MRef::Owned` and transfers it. The caller treats both the same, +because `MRef` derefs to `T`. CGP's getter machinery uses the type directly, because a getter method's return type decides what body the macro generates. When a getter returns `MRef<'a, T>` over `&self`, the generated accessor @@ -28,8 +28,8 @@ nothing extra, and the same interface still lets a provider elsewhere return an getter can therefore leave open whether the context stores the value or makes it, without splitting into a separate trait for each case. -Unlike the rest of this section, `MRef` is an ordinary runtime value rather than a type-level marker. It -belongs here because it is the one type in the group that you write yourself, as the return type of a +Unlike the rest of this section, `MRef` is an ordinary runtime value rather than a type-level +marker. It belongs here because it is a type you name in your own code, as the return type of a getter. ## Definition @@ -44,10 +44,10 @@ pub enum MRef<'a, T> { } ``` -`Ref` borrows a `T` for the lifetime `'a`, and `Owned` carries a `T` by value. The lifetime applies only -to the borrowed case, so an `MRef` built from an owned value is effectively unbounded in `'a`. The enum is -an ordinary owned value, with nothing type-level about it, and it is the payload a getter passes back to -its caller. +`Ref` borrows a `T` for the lifetime `'a`, and `Owned` carries a `T` by value. The lifetime applies +only to the borrowed case, so an `MRef` built from an owned value is effectively unbounded in `'a`. +The enum is an ordinary owned value, with nothing type-level about it, and it is the payload a +getter passes back to its caller. It is in the prelude, so `use cgp::prelude::*;` is enough. ## Behavior @@ -56,38 +56,101 @@ implements `Deref` by matching on the variant and returning a `&T` e and any auto-deref method call work regardless of which case is inside. It also implements `AsRef` over the same logic, giving an explicit `as_ref()` for code that prefers it. -Building an `MRef` takes a single `.into()`, because it implements `From` for both cases. `From` builds -`Owned`, and `From<&'a T>` builds `Ref`, so a value or a reference converts with `.into()`. When a caller -needs ownership unconditionally, `get_or_clone` resolves the enum to a plain `T`. It returns the owned -value as is or clones the borrowed one, and it is available whenever `T: Clone`. These make up the whole -API: the transparent `Deref` and `AsRef`, the `From` impls, and `get_or_clone`. Code reads a borrowed -`MRef` cheaply and promotes it to ownership only on request. +Building an `MRef` takes a single `.into()`, because it implements `From` for both cases. `From` +builds `Owned`, and `From<&'a T>` builds `Ref`, so a value or a reference converts with `.into()`. +When a caller needs ownership unconditionally, `get_or_clone` resolves the enum to a plain `T`. It +returns the owned value as is or clones the borrowed one, and it is available whenever `T: Clone`. +These make up the whole API: the transparent `Deref` and `AsRef`, the `From` impls, and +`get_or_clone`. `MRef` does not implement any other trait, so it is neither `Clone` nor `Debug`. +Code reads a borrowed `MRef` cheaply and promotes it to ownership only on request. + +The getter macros recognize `MRef<'_, T>` by its shape: a single-segment path named `MRef` with a +lifetime and a type argument. The same form works for an [`#[implicit]`](../attributes/implicit.md) +argument, which then lends the field as `MRef::Ref`. A differently shaped or fully qualified `MRef`, +such as `cgp::prelude::MRef<'_, T>`, is not recognized. It falls through to the owned form, which +expects a field of that type, and with `'_` in it the definition does not compile. ## Examples -`MRef` is the return type of a getter that should work whether the context stores the value or produces -it. A borrowed field and a freshly built value have the same type, and code reads them the same way: +A getter returning `MRef` lets one context lend a stored field and another build the value, and +generic code reads both the same way: ```rust use cgp::prelude::*; -let stored = String::from("hello"); +#[cgp_getter] +pub trait HasGreeting { + fn greeting(&self) -> MRef<'_, String>; +} + +// A provider that builds the value instead of lending a field. +#[cgp_impl(new BuildGreeting)] +impl GreetingGetter { + fn greeting(&self, #[implicit] name: &str) -> MRef<'_, String> { + MRef::Owned(format!("Hello, {name}!")) + } +} + +#[derive(HasField)] +pub struct Stored { + pub greeting: String, +} + +#[derive(HasField)] +pub struct Computed { + pub name: String, +} + +delegate_components! { + Stored { + GreetingGetterComponent: UseField, + } +} -// a context lending a stored value: -let borrowed: MRef<'_, String> = MRef::from(&stored); -assert_eq!(&*borrowed, "hello"); +delegate_components! { + Computed { + GreetingGetterComponent: BuildGreeting, + } +} -// a provider returning a freshly built value through the same type: -let made: MRef<'_, String> = MRef::from(String::from("world")); -assert_eq!(made.as_ref(), "world"); +check_components! { + Stored { + GreetingGetterComponent, + } +} + +check_components! { + Computed { + GreetingGetterComponent, + } +} -// promote either to an owned value when ownership is required: -let owned: String = borrowed.get_or_clone(); -assert_eq!(owned, "hello"); +// Generic code reads either case through `Deref`. +pub fn shout(context: &Context) -> String { + context.greeting().to_uppercase() +} + +pub fn demo() { + let stored = Stored { + greeting: "Hi there".to_owned(), + }; + let computed = Computed { + name: "Alice".to_owned(), + }; + + assert_eq!(shout(&stored), "HI THERE"); + assert_eq!(shout(&computed), "HELLO, ALICE!"); + + // `UseField` lends the stored field, and `get_or_clone` moves an owned value out. + assert!(matches!(stored.greeting(), MRef::Ref(_))); + let owned: String = computed.greeting().get_or_clone(); + assert_eq!(owned, "Hello, Alice!"); +} ``` -Both `borrowed` and `made` have the same type, and code consumes them the same way. Only the construction -differs. `get_or_clone` clones the borrowed case and moves the owned one. +`Stored` and `Computed` are value contexts for a self-targeted getter. `Stored` wires the getter to +[`UseField`](../providers/use_field.md), whose generated accessor wraps the field as `MRef::Ref`. +`Computed` wires it to a provider that formats a new `String` and returns it as `MRef::Owned`. ## When to use it @@ -96,9 +159,10 @@ return type when the value is not always a field the context can lend. - **Use a plain `&T` return** when every context stores the value and can lend it. `MRef` is useful only where some context must produce the value instead. -- **Use an [`#[implicit]`](../attributes/implicit.md) argument** to read a stored field in a provider, - which is the default for field access. An implicit argument can itself have the type `MRef<'_, T>` when - the field may be lent or produced. +- **Use an [`#[implicit]`](../attributes/implicit.md) argument** to read a stored field in a + provider, which is the default for field access. An implicit argument declared as `MRef<'_, T>` + lends the field as `MRef::Ref`, which suits a body written against a value that may be owned or + borrowed. - **Use `MRef` with [`#[cgp_getter]`](../macros/cgp_getter.md)** and the [`UseField`](../providers/use_field.md) family, where a getter's return type selects the accessor the macro generates. @@ -113,6 +177,11 @@ value, while `Life<'a>` is a zero-sized type-level lift for provider wiring. The is free when the getter already owns the value and costs a clone when it borrowed. Use it only when you need ownership. +**A qualified path is not recognized.** A getter declared as +`fn greeting(&self) -> cgp::prelude::MRef<'_, String>;` is treated as returning an owned field of +that type, so its `'_` lands in a `HasField` bound and the definition fails with +``error[E0637]: `'_` cannot be used here``. Import `MRef` and write it bare. + **`Deref` makes the variants transparent, so you rarely match on them.** Reading through `&*` or `as_ref()` works whichever case is inside, and a manual match on `Ref` versus `Owned` usually means the code should have called `get_or_clone` instead. @@ -120,6 +189,8 @@ code should have called `get_or_clone` instead. ## Related constructs - [`#[cgp_getter]`](../macros/cgp_getter.md): the getter component whose return type may be `MRef`. +- [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md): the blanket getter, which recognizes the + same return type. - [`UseField`](../providers/use_field.md) and [`UseFieldRef`](../providers/use_field_ref.md): the providers that wire a getter, and the by-reference variant. - [`HasField`](../traits/field-access/has_field.md): the field access an `MRef` getter builds on. diff --git a/docs/reference/types/nil.md b/docs/reference/types/nil.md index 575a158b..5823f848 100644 --- a/docs/reference/types/nil.md +++ b/docs/reference/types/nil.md @@ -1,6 +1,8 @@ --- +title: 'Nil — the end of a type-level list' sidebar_label: 'Nil' sidebar_position: 6 +description: 'The end marker of the product, string, and path lists: an empty, constructible list that is also the shape of a unit struct.' --- # `Nil` @@ -30,7 +32,8 @@ pub struct Nil; It holds nothing. Used as a tail it terminates a chain, and used on its own it is the empty list. It derives `Eq`, `PartialEq`, `Clone`, `Default`, and `Debug`, so a list ending in `Nil` inherits those -traits structurally, and `Nil` itself compares equal to `Nil`. +traits structurally, and `Nil` itself compares equal to `Nil`. It is in the prelude, so +`use cgp::prelude::*;` is enough. ## Behavior @@ -40,49 +43,62 @@ recursion stops when it reaches `Nil`. The string and path lists work the same w [`Chars`](chars.md) stops at `Nil`, and a walk over [`PathCons`](path_cons.md) stops at `Nil`. Because `Nil` is a real, constructible value, the empty product `Product![]` is `Nil`, and the empty -value `product![]` is the `Nil` value. A builder or a conversion returns it when every field of a -shape has been consumed. This is why an empty record is a value the program can hold. The contrast -with [`Void`](void.md) is exact. A value with every branch ruled out cannot exist, so a sum ends in -an uninhabited marker, while a record ends in this inhabited one. +value `product![]` is the `Nil` value. The empty string `Symbol!("")` is `Symbol<0, Nil>`, and a +unit struct that derives [`HasFields`](../derives/derive_has_fields.md) has `Nil` as its shape. A +builder or a conversion returns `Nil` when every field of a shape has been consumed. This is why an +empty record is a value the program can hold. The contrast with [`Void`](void.md) is exact. A value +with every branch ruled out cannot exist, so a sum ends in an uninhabited marker, while a record +ends in this inhabited one. ## Examples -`Nil` ends every product chain, which the expansion of [`Product!`](../macros/product.md) shows: +Each list ends in `Nil`, and the empty product, the empty string, and a unit struct's shape are all +`Nil`: ```rust use cgp::prelude::*; -// Product![u32, bool] expands to: -type Row = Cons>; - -// the empty list is Nil alone: -type Empty = Product![]; // == Nil +#[derive(HasFields)] +pub struct Marker; + +pub fn demo() { + // Each list ends in `Nil`; the annotations are the check. + let _row: PhantomData>> = PhantomData::; + let _name: PhantomData>>> = + PhantomData::; + let _path: PhantomData>> = + PhantomData::; + + // The empty product, the empty string, and a unit struct's shape are all `Nil`. + let empty: Product![] = product![]; + assert_eq!(empty, Nil); + let _empty_name: PhantomData> = PhantomData::; + let fields: Nil = Marker.to_fields(); + assert_eq!(fields, Nil); +} ``` -It also terminates a [`Symbol!`](../macros/symbol.md) character chain and a -[`Path!`](../macros/path.md) segment chain: - -```rust -// Symbol!("hi") ends its Chars chain in Nil -// Path!(@a.b) ends its PathCons chain in Nil -``` +Each `PhantomData` annotation compiles only if the macro on its right expands to the chain on its +left. ## When to use it -**You read `Nil` at the end of a chain, and you do not write it.** The macros produce it, and you -only need to recognize it. +**You read `Nil` at the end of a chain, and you write it as the base case of a fold.** The macros +produce it everywhere else. - **Read `Nil` as "the list ends here."** In an expanded `Cons`, `Chars`, or `PathCons` chain, the `Nil` is the terminator and marks the count of cells before it. +- **Implement a trait for `Nil`** as the base case when you fold over a product, beside the impl for + [`Cons`](cons.md). - **Expect `Nil`, not [`Void`](void.md), at the end of a record, a string, or a path.** A sum ends in `Void`, and the other lists end in `Nil`. The wrong terminator in an error usually means the product and sum families have been mixed up. ## Common Mistakes -**`Nil` is inhabited, and [`Void`](void.md) is not.** `Nil` is the real value of the empty product, while -`Void` is the uninhabited type of an empty choice. They are not interchangeable, and the extractor -machinery depends on the difference. +**`Nil` is inhabited, and [`Void`](void.md) is not.** `Nil` is the real value of the empty product, +while `Void` is the uninhabited type of an empty choice. They are not interchangeable: variant +extraction relies on `Void` being uninhabited, which `Nil` is not. **`Nil` terminates the string and path lists as well as the product list.** A `Nil` at the end of a [`Chars`](chars.md) chain or a [`PathCons`](path_cons.md) chain is the same marker doing the same job, so diff --git a/docs/reference/types/path_cons.md b/docs/reference/types/path_cons.md index e7cb9922..863be709 100644 --- a/docs/reference/types/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -1,6 +1,8 @@ --- +title: 'PathCons — a type-level lookup path' sidebar_label: 'PathCons' sidebar_position: 10 +description: 'The cell of a type-level path, the list of segments that names a route through nested delegation tables so a lookup can reach an entry behind a prefix.' --- # `PathCons` @@ -11,18 +13,19 @@ lookup can reach an entry several layers deep. ## Overview `PathCons` expresses a *route* through nested delegation tables as a single type. A bare -component name picks one entry out of a context's table. Here the **context** is the type the method -runs on, and its table records which provider it uses for each component. Sometimes the entry a -lookup wants sits behind a layer of indirection: inside a namespace, behind a namespace it inherits from, -or under a prefix. A path names such a route as a list of segments read left to right, and each segment -narrows the lookup a step further. `PathCons` is the cell of that list, and [`Nil`](nil.md) terminates -it, so `PathCons>` is the path that steps through `A` and then `B`. +component name picks one entry out of a context's table. Here the **context** is the type the +implementation runs against, and its table records which provider it uses for each component. +Sometimes the entry a lookup wants sits behind a layer of indirection: inside a namespace, behind a +namespace it inherits from, or under a prefix. A path names such a route as a list of segments read +left to right, and each segment narrows the lookup a step further. `PathCons` is the cell of that +list, and [`Nil`](nil.md) terminates it, so `PathCons>` is the path that steps +through `A` and then `B`. A path differs from the [`Cons`](cons.md) product list in its unsized bound, even though both are -right-nested and end in `Nil`. `PathCons` declares its head and tail `?Sized`, so a segment may be a trait -object or another unsized type, and code can manipulate the whole path without its parts having a known -size. A product list keys a struct's fields, and its elements are always sized values. A path keys a -lookup, and its segments are pure type-level markers that never need to be `Sized`. +right-nested and end in `Nil`. `PathCons` declares its head and tail `?Sized`, so a segment may be +an unsized type such as `str`, and code can manipulate the whole path without its parts having a +known size. A product list keys a struct's fields, and its elements are always sized values. A path +keys a lookup, and its segments are pure type-level markers that never need to be `Sized`. The segments are the markers CGP uses elsewhere. A lowercase dotted name becomes a [`Symbol`](chars.md) [type-level string](/docs/reference/glossary#type-level-string), and a capitalized name becomes that named type, usually a @@ -39,10 +42,11 @@ component names, in the form `@a.B.c`, assembled into a `PathCons` chain. You wr pub struct PathCons(pub PhantomData, pub PhantomData); ``` -`Head` is the first segment, and `Tail` is the remainder, which is another `PathCons` or [`Nil`](nil.md) -at the end. Both bounds are `?Sized`, so any type may occupy a segment. The struct holds nothing at run -time. Like the other type-level building blocks, it exists through [`PhantomData`](phantom_data.md) so -that trait resolution can name and match a route. +`Head` is the first segment, and `Tail` is the remainder, which is another `PathCons` or +[`Nil`](nil.md) at the end. Both bounds are `?Sized`, so any type may occupy a segment. The struct +holds nothing at run time. Like the other type-level building blocks, it exists through +[`PhantomData`](phantom_data.md) so that trait resolution can name and match a route. It is in the +prelude, so `use cgp::prelude::*;` is enough. ## Behavior @@ -53,22 +57,33 @@ another at the type level. The trait recurses down the list: `PathCons` whose `Path` is a `PathCons` -chain, and `RedirectLookup` follows the chain segment by segment until it reaches a concrete provider. The -path never names a provider itself. It only describes where to look, so the same path can resolve to -different providers depending on the table `RedirectLookup` walks. +[`RedirectLookup`](../providers/redirect_lookup.md) consumes a path. When a namespace entry, an +`open` statement, or a `=>` redirect reroutes a lookup, it produces a +`RedirectLookup` whose `Path` is a `PathCons` chain. Its impl, which +[`#[cgp_component]`](../macros/cgp_component.md) generates for each component, extends the path with +the component's type parameters through `ConcatPath`, then looks the whole extended path up in +`Components` as one key, through `DelegateComponent`. The path never names a provider itself. It +only says which key to look up, so the same path can resolve to different providers in different +tables, and the entry it reaches may redirect again. ## Examples -The [`Path!`](../macros/path.md) macro produces paths, and they most often appear inside the wirings that -[`cgp_namespace!`](../macros/cgp_namespace.md) emits. A namespace entry that redirects one component key -to a path expands into a `RedirectLookup` over a `PathCons` chain: +A path is a type, so the checks here are type equalities. The +[`cgp_namespace!`](../macros/cgp_namespace.md) entry at the top reroutes one component to a path: ```rust use cgp::prelude::*; +#[cgp_component(FooProvider)] +pub trait CanFoo { + fn foo(&self); +} + +#[cgp_component(MyFoo)] +pub trait CanMyFoo { + fn my_foo(&self); +} + cgp_namespace! { new MyNamespace { FooProviderComponent => @@ -76,23 +91,31 @@ cgp_namespace! { } } -// the emitted entry, in readable form: -// impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { -// type Delegate = RedirectLookup<__Table__, PathCons>; -// } +pub fn demo() { + // A lowercase segment is a `Symbol`, and a capitalized one names its type. + let _: PhantomData>> = + PhantomData::; + + // A one-segment path. + let _: PhantomData> = PhantomData::; + + // `ConcatPath` appends one path to another. + let _: PhantomData = + PhantomData::<>::Output>; +} ``` -A path can interleave lowercase symbol segments with capitalized component segments. Registering a -component into a namespace under a prefix produces a path that steps through the prefix and then the -component: +The namespace entry expands into a `RedirectLookup` over the one-segment path. `cargo cgp expand` +prints the path in its `Path!` form: ```rust -// @MyBarComponent.BarProviderComponent expands to -// PathCons> +impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { + type Delegate = RedirectLookup<__Table__, Path!(@MyFooComponent)>; +} ``` -The lookup steps through `MyBarComponent` and then through `BarProviderComponent` before it resolves. A -single-segment path is `PathCons`, and the empty path is [`Nil`](nil.md) alone. +which is `RedirectLookup<__Table__, PathCons>`. A single-segment path is +`PathCons`, and the empty path is [`Nil`](nil.md) alone. ## When to use it @@ -109,9 +132,10 @@ single-segment path is `PathCons`, and the empty path is [`Nil`](n ## Common Mistakes -**A path names a route, not a provider.** A `PathCons` chain describes where to look. The provider it -resolves to depends on the table that [`RedirectLookup`](../providers/redirect_lookup.md) walks. The same -path can resolve to different providers in different contexts. +**A path names a route, not a provider.** A `PathCons` chain describes which key to look up. The +provider it resolves to depends on the table that +[`RedirectLookup`](../providers/redirect_lookup.md) looks it up in, so the same path can resolve to +different providers in different contexts. **A path list is `?Sized`, unlike the [`Cons`](cons.md) product list.** Its segments are markers rather than values, so a segment need not have a known size. Expecting a path to behave like a product list of @@ -120,6 +144,11 @@ values is the usual source of confusion. **Both a path and a product end in [`Nil`](nil.md).** A `Nil` at the end of a `PathCons` chain is the same terminator doing the same job it does for a record. It does not mean the two lists have been mixed. +**A table's own path keys end in a parameter, not in `Nil`.** A path key written in +[`delegate_components!`](../macros/delegate_components.md) matches every longer path beneath it, so +its last `PathCons` holds a generic parameter where a `Path!` holds `Nil`. The expansion of such a +table shows that parameter rather than `Nil`. + ## Related constructs - [`Nil`](nil.md): the end marker that terminates a `PathCons` chain. @@ -128,7 +157,7 @@ same terminator doing the same job it does for a record. It does not mean the tw - [`Chars`](chars.md): the [`Symbol`](chars.md) segments a path is built from. - [`Path!`](../macros/path.md): the macro that folds `@`-segments onto this list. - [`ConcatPath`](../traits/formatting/concat_path.md): appends one path onto another. -- [`RedirectLookup`](../providers/redirect_lookup.md): walks a path against a table at resolution +- [`RedirectLookup`](../providers/redirect_lookup.md): looks a path up in a table at resolution time. - [`cgp_namespace!`](../macros/cgp_namespace.md): emits these paths to reroute and register entries. diff --git a/docs/reference/types/phantom_data.md b/docs/reference/types/phantom_data.md index 8066dbdf..34a311ec 100644 --- a/docs/reference/types/phantom_data.md +++ b/docs/reference/types/phantom_data.md @@ -1,6 +1,8 @@ --- +title: 'PhantomData — carry a type without a value' sidebar_label: 'PhantomData' sidebar_position: 1 +description: 'The standard-library marker that lets a type carry a type parameter without storing a value of it, and lets a call pass a type where a value is expected.' --- # `PhantomData` @@ -60,17 +62,18 @@ that it stores nowhere. `PhantomData` compiles anyway because the compiler knows unused-parameter rule, and every other marker type can use it. Those types satisfy the rule by *holding* a `PhantomData` field rather than by being one. -The parameter is `?Sized`, so `T` may be any type, sized or not. A value of `PhantomData` occupies no -space and holds nothing. Its only content is the type `T`, recorded in its own type. You construct one by -writing `PhantomData`. Where inference cannot supply the type, you name it with a turbofish, as in -`PhantomData::`. +The parameter is `?Sized`, so `T` may be any type, sized or not. A value of `PhantomData` is +zero-sized and holds nothing. Its only content is the type `T`, recorded in its own type. You +construct one by writing `PhantomData`. Where inference cannot supply the type, you name it with a +turbofish, as in `PhantomData::`. CGP re-exports it through the prelude, so +`use cgp::prelude::*;` brings it into scope. -`PhantomData` also tells the compiler how the surrounding type relates to `T`, beyond satisfying the -used-parameter rule. It sets **variance** (whether a longer lifetime may stand in for a shorter one), drop -checking, and the auto traits such as `Send` and `Sync`. Most CGP markers do not depend on which -relationship they get, so they use the plain `PhantomData`. [`Life`](life.md) is the exception. It -wraps its lifetime as `PhantomData<*mut &'a ()>` to force invariance, so that the compiler treats two -lifetime instantiations as different types. That page explains why. +`PhantomData` also tells the compiler how the surrounding type relates to `T`, beyond satisfying +the used-parameter rule. It sets **variance** (whether a longer lifetime may stand in for a shorter +one), drop checking, and the auto traits such as `Send` and `Sync`. Most CGP markers do not depend +on which relationship they get, so they use the plain `PhantomData`. [`Life`](life.md) is the +exception. It wraps its lifetime as `PhantomData<*mut &'a ()>`, which makes it invariant in the +lifetime and neither `Send` nor `Sync`. That page explains the consequences. ## How CGP uses it @@ -95,17 +98,18 @@ let name = self.get_field(PhantomData::); let output = context.compute(PhantomData::, input); ``` -Here the **context** is the type the method runs on. It supplies the values the method -needs as its own fields. The `PhantomData` argument carries nothing. It exists so that type -inference selects the right [`HasField`](../traits/field-access/has_field.md) impl or the right -handler. In effect, the call passes a type where a value is expected, and `PhantomData::` is the -empty value that stands for the type `T`. +Here the **context** is the type the method runs on, which supplies the values it needs as its +fields. The `PhantomData` argument carries nothing. It exists so that type inference selects the +right [`HasField`](../traits/field-access/has_field.md) impl or the right handler. The call passes a +type where a value is expected, and `PhantomData::` is the empty value that stands for the type +`T`. **You rarely write either role yourself, because a higher-level construct produces each for you.** - On the declaring side, the `new` keyword of [`#[cgp_impl]`](../macros/cgp_impl.md) declares the - provider struct: a `PhantomData` field per generic parameter, or a bare `struct Foo;` when there are - none. + provider struct: a bare `struct Foo;` when the provider lacks generic parameters, and otherwise + one `PhantomData` field over the parameter, or over a tuple of all of them when there are several, + with each lifetime wrapped as [`Life<'a>`](life.md). - On the passing side, [`#[implicit]`](../attributes/implicit.md) and [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) read a context field without the tag, so your code does not contain a `get_field(PhantomData::<...>)` call. @@ -114,32 +118,66 @@ You meet `PhantomData` directly only when you work below these constructs. ## Examples -At a call site, `PhantomData::` selects which field a getter reads: +A provider generic over the field it reads uses `PhantomData` on both sides. `new` declares the +struct with a `PhantomData` field, and the body passes the tag to `get_field` as +`PhantomData::`: ```rust use cgp::prelude::*; -#[cgp_impl(new GreetHello)] -impl Greeter -where - Self: HasField, -{ - fn greet(&self) { - let name = self.get_field(PhantomData::); - println!("Hello, {name}!"); +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +// `new` declares `pub struct GreetField(pub PhantomData);` +#[cgp_impl(new GreetField)] +#[uses(HasField)] +impl Greeter { + fn greet(&self) -> String { + let name = self.get_field(PhantomData::); + format!("Hello, {name}!") } } -``` -You meet this form in an expansion rather than write it. The idiomatic version uses an -[`#[implicit]`](../attributes/implicit.md) argument and does not show `PhantomData` at all. +#[derive(HasField)] +pub struct Person { + pub name: String, +} + +delegate_components! { + Person { + GreeterComponent: GreetField, + } +} -A type with several parameters uses one `PhantomData` over a tuple: +check_components! { + Person { + GreeterComponent, + } +} -```rust +// A marker over two parameters holds one `PhantomData` over a tuple. pub struct Add(pub PhantomData<(Left, Right)>); + +pub fn demo() { + let person = Person { + name: "World".to_owned(), + }; + assert_eq!(person.greet(), "Hello, World!"); + + // Both markers occupy no space. + assert_eq!(core::mem::size_of::>(), 0); + assert_eq!(core::mem::size_of::>(), 0); +} ``` +`Person` is a value context, and `CanGreet` is self-targeted: the greeting reads the person it is +called on. The wiring names the tag once, in `GreetField`, and the provider carries +it as a type. The idiomatic way to read a field of the context is an +[`#[implicit]`](../attributes/implicit.md) argument, which hides the tag. `GreetField` passes the +tag explicitly because the field it reads is a parameter chosen by the wiring. + ## When to use it **You write `PhantomData` yourself only to declare a marker field or to pass a type at a call site.** @@ -152,8 +190,10 @@ Everywhere else the macros insert it for you. - **Pass `PhantomData::`** at a call site that takes a type-level selector, such as `get_field` or a handler's `compute`. This is the common case you write yourself, and the turbofish names the type when inference cannot. -- **Use [`Life`](life.md), not a bare `PhantomData`, for a lifetime** that must stay invariant. A plain - `PhantomData<&'a ()>` is covariant, which is the wrong relationship for a dependency marker. +- **Hold a lifetime as `PhantomData>`** to match what `#[cgp_new_provider]` declares for a + lifetime parameter. A plain `PhantomData<&'a ()>` also satisfies the unused-parameter rule, but it + is covariant in `'a` and keeps the struct `Send` and `Sync`, where the macro's form is invariant + and neither. ## Common Mistakes @@ -161,18 +201,37 @@ Everywhere else the macros insert it for you. `PhantomData` fields is still zero-sized, and a `PhantomData` argument compiles to nothing. A `PhantomData` in a signature does not mean a hidden allocation. -**`PhantomData` and `PhantomData::` differ only by whether the type is inferred.** In a struct field -the type comes from the field's declared type, so plain `PhantomData` is enough. At a call site where -nothing fixes `T`, the turbofish `PhantomData::` states it, and omitting it gives a -"type annotations needed" error rather than a wrong result. +**Leaving the tag to inference fails when nothing fixes it.** In a struct field the type comes from +the field's declared type, so plain `PhantomData` is enough. At a call site the turbofish states it. +A `get_field` call on a context with two fields cannot infer which one is meant: + +```rust +#[derive(HasField)] +pub struct Person { + pub name: String, + pub age: u8, +} + +pub fn print_name(person: &Person) { + let name = person.get_field(PhantomData); + println!("{name}"); +} +``` + +The compiler reports two errors, headed `error[E0284]: type annotations needed` and +`error[E0283]: type annotations needed`, and the second names the cause: + +```text +note: multiple `impl`s satisfying `Person: cgp::prelude::HasField<_>` found +``` -**A bare `PhantomData<&'a ()>` is covariant.** If you write a lifetime marker yourself and let a longer -lifetime stand in for a shorter one, the compiler may pick a provider wired for a different lifetime. -Use [`Life<'a>`](life.md), whose `PhantomData<*mut &'a ()>` forces invariance, when the lifetime is an -exact identity. +Write `PhantomData::` to name the field. -**A generic marker needs its `PhantomData` field.** A struct that is generic over a `T` without storing a -value of it fails to compile with `error[E0392]`. +**A generic marker needs its `PhantomData` field, for a lifetime as much as for a type.** A struct +that is generic over a `T` without storing a value of it fails with `error[E0392]`, as [the first +section](#why-a-marker-needs-it) shows. The same rule covers a lifetime parameter: +`pub struct Borrowing<'a>;` fails with ``error[E0392]: lifetime parameter `'a` is never used``, and +a `PhantomData>` field fixes it. ## Related constructs @@ -201,6 +260,8 @@ The ideas behind it: documentation covers the variance, drop-check, and auto-trait effects in full. - CGP re-exports it through the prelude, so `use cgp::prelude::*;` brings `PhantomData` into scope alongside the rest. +- The provider struct `new` declares, with its `PhantomData` field: + [`empty_struct.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/empty_struct.rs) --- diff --git a/docs/reference/types/void.md b/docs/reference/types/void.md index 805624d8..999c2165 100644 --- a/docs/reference/types/void.md +++ b/docs/reference/types/void.md @@ -1,6 +1,8 @@ --- +title: 'Void — the end of a sum list' sidebar_label: 'Void' sidebar_position: 8 +description: 'The uninhabited end marker of the sum list: an empty enum that can never be constructed, which lets a complete variant match end without a runtime branch.' --- # `Void` @@ -29,63 +31,106 @@ nothing left to handle. pub enum Void {} ``` -Its variant list is empty, so it is uninhabited, like Rust's never type. It derives the standard -traits so that a sum ending in `Void` can inherit them. But code never builds a value of `Void`, so -those impls never run on one. +Its variant list is empty, so it is uninhabited, like Rust's never type `!` or +[`Infallible`](https://doc.rust-lang.org/std/convert/enum.Infallible.html). CGP defines its own so +that the terminator of a sum is named for that job. It derives the standard traits so that a sum +ending in `Void` can inherit them. But code never builds a value of `Void`, so those impls never run +on one. It is in the prelude, so `use cgp::prelude::*;` is enough. ## Behavior -`Void` is the base case of a recursion over a sum, and it differs from the product list's base case in a -way that matters. A walk over an [`Either`](either.md) chain handles each `Left` as a branch and defers -each `Right` to the tail, until the tail is `Void`. At that point nothing is left to handle. - -The extractor machinery depends on this uninhabitedness. After an extractor has tried every variant of a -sum and matched none, the leftover value has type `Void`, so it cannot exist. -[`FinalizeExtract`](../traits/variant/finalize_extract.md) for `Void` turns that value into any required -type with an empty `match self {}`, because nothing remains to handle. So a fully handled variant -extraction is complete at compile time and does not need an unreachable runtime branch: +`Void` is the base case of a recursion over a sum, and it differs from the product list's base case +in a way that matters. A walk over an [`Either`](either.md) chain handles each `Left` as a branch +and defers each `Right` to the tail, until the tail is `Void`. At that point nothing is left to +handle, so the base-case impl for `Void` either returns without doing anything or discharges a value +that cannot exist. + +Variant extraction uses the same uninhabitedness in a second place. An extractor from +[`#[derive(ExtractField)]`](../derives/derive_extract_field.md) is a companion enum with one marker +per variant, and [`extract_field`](../traits/variant/extract_field.md) marks each variant it has +ruled out as `IsVoid`, whose payload type is `Void`. Once every variant is `IsVoid`, every variant +of the companion holds a `Void`, so the companion itself is uninhabited. The derive gives that +configuration a [`FinalizeExtract`](../traits/variant/finalize_extract.md) impl whose body is an +empty `match self {}`, so a fully handled extraction ends without an unreachable runtime branch. The +trait's impl for `Void` itself has the same body: ```rust -// schematically: -impl FinalizeExtract for Void { - fn finalize_extract(self) -> T { - match self {} // no cases, because Void has no values +pub trait FinalizeExtract { + fn finalize_extract(self) -> T; +} + +impl FinalizeExtract for Void { + fn finalize_extract(self) -> T { + match self {} } } ``` -A constructible terminator like [`Nil`](nil.md) could not be consumed this way, because the compiler would -demand an arm for the `Nil` case. Only an uninhabited type lets the empty match stand. This is why the sum -list terminates in `Void` and the product list in `Nil`. +A constructible type could not be discharged this way, because the compiler would demand an arm for +its values. This is why a ruled-out variant holds `Void` rather than the `()` a missing record field +holds, and why the sum list terminates in `Void` while the product list terminates in `Nil`. ## Examples -`Void` ends every sum chain, which the expansion of [`Sum!`](../macros/sum.md) shows: +`Void` ends every sum chain, closes a match over one, and fills the error position of a `Result` +that cannot fail: ```rust +use cgp::core::field::traits::FinalizeExtractResult; use cgp::prelude::*; -// Sum![u32, bool] expands to: -type Token = Either>; +pub type Token = Sum![u32, bool]; + +// Behind a reference, the `Void` arm is required. +pub fn describe(token: &Token) -> String { + match token { + Either::Left(number) => format!("number {number}"), + Either::Right(Either::Left(flag)) => format!("flag {flag}"), + Either::Right(Either::Right(void)) => match *void {}, + } +} + +// By value, it may be left out. +pub fn is_number(token: Token) -> bool { + match token { + Either::Left(_) => true, + Either::Right(Either::Left(_)) => false, + } +} + +pub fn demo() { + // The annotations are the check: the chain ends in `Void`, and the empty sum is `Void`. + let _: PhantomData>> = PhantomData::; + let _: PhantomData = PhantomData::; + + assert_eq!(describe(&Either::Right(Either::Left(true))), "flag true"); + assert!(is_number(Either::Left(3))); -// the empty sum is Void alone: -type Empty = Sum![]; // == Void + // A `Result` that cannot fail unwraps without an `unwrap`. + let result: Result = Ok(5); + assert_eq!(result.finalize_extract_result(), 5); +} ``` -You do not construct a `Void`. You only eliminate one. The only thing code does with a `Void` value is -match on it with an empty `match`, and the extractor family does that when a variant match is complete. +You do not construct a `Void`. You only eliminate one, with an empty `match`, and +[`FinalizeExtractResult`](../traits/variant/finalize_extract_result.md) does that for the error side +of a `Result`. ## When to use it -**You read `Void` at the end of a sum and in an extractor's type, and you do not write it.** +**You read `Void` at the end of a sum and in an extractor's type, and you write it only to close a +match.** - **Read `Void` as "the choice ends here, and this point is unreachable."** In an expanded [`Either`](either.md) chain, the `Void` marks the end, and a value can never sit at it. +- **Write `match void {}` for the last arm** of a match on a sum behind a reference, where Rust + requires the arm. - **Expect `Void`, not [`Nil`](nil.md), at the end of a variant.** A record, a string, and a path end in `Nil`, and a variant ends in `Void`. The wrong terminator in an error usually means the product and sum families have been mixed up. - **Recognize `Void` in a [`FinalizeExtract`](../traits/variant/finalize_extract.md) error** as the - all-ruled-out remainder of a variant extraction. + payload of a variant already ruled out. An extraction that stops short leaves some variant + `IsPresent`, and the missing `FinalizeExtract` impl is for that partly ruled-out companion. ## Common Mistakes @@ -93,6 +138,31 @@ match on it with an empty `match`, and the extractor family does that when a var `Void` is a type without values. Records use `Nil`, and variants use `Void`. An error that names the wrong one usually means the two families have been mixed up. +**A match behind a reference needs the `Void` arm.** A match on a sum by value may leave the last +arm out, since Rust treats an uninhabited payload as unreachable there. Through a reference it does +not: + +```rust +pub type Token = Sum![u32, bool]; + +pub fn describe(token: &Token) -> String { + match token { + Either::Left(number) => format!("number {number}"), + Either::Right(Either::Left(flag)) => format!("flag {flag}"), + } +} +``` + +This fails with +``error[E0004]: non-exhaustive patterns: `&cgp::prelude::Either::Right(cgp::prelude::Either::Right(_))` not covered``, +and the compiler says why: + +```text + = note: `Void` is uninhabited but is not being matched by value, so a wildcard `_` is required +``` + +Add `Either::Right(Either::Right(void)) => match *void {}` to close it. + **You cannot build a `Void`.** It has neither a constructor nor a literal, by design. Code that appears to "return a `Void`" is really an empty match that never returns. @@ -102,10 +172,12 @@ one usually means the two families have been mixed up. - [`Nil`](nil.md): the product, string, and path lists' constructible end marker, the counterpart to this one. - [`Sum!`](../macros/sum.md): the macro whose empty form is `Void`. -- [`FinalizeExtract`](../traits/variant/finalize_extract.md): eliminates the uninhabited remainder of - a variant extraction with an empty match. +- [`FinalizeExtract`](../traits/variant/finalize_extract.md): discharges an extractor whose every + variant holds `Void`, with an empty match. - [`FinalizeExtractResult`](../traits/variant/finalize_extract_result.md): the result-carrying form built on the same idea. +- [`MapType`](../traits/type-level/map_type.md): whose `IsVoid` marker maps a ruled-out variant's + payload to `Void`. The ideas behind it: @@ -117,8 +189,10 @@ The ideas behind it: - `Void` is in [`sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/types/sum.rs), alongside [`Either`](either.md) -- `FinalizeExtract for Void`, which eliminates the uninhabited remainder: +- `FinalizeExtract` and its impl for `Void`: [`extract_field.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/extract_field.rs) +- The `IsVoid` marker: + [`map_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/impls/map_type.rs) --- diff --git a/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs b/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs new file mode 100644 index 00000000..d6ea2524 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs @@ -0,0 +1,36 @@ +// A provider reads `width` and `height`, and the context has only `height`. The raw error names the +// missing tag as a `Symbol` over a `Chars` chain, beside the tag the context does have. This is the +// `Chars` page's *Common Mistakes* entry on reading the chain. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.stderr b/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.stderr new file mode 100644 index 00000000..70c335a0 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `Rectangle: CanUseComponent` is not satisfied + --> tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs:32:9 + | +32 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>>` is implemented for it + --> tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs:21:9 + | +21 | pub height: f64, + | ^^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs:12:1 + | +12 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Rectangle` to implement `CanUseComponent` +note: required by a bound in `__CheckRectangle` + --> tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs:30:1 + | +30 | / check_components! { +31 | | Rectangle { +32 | | AreaCalculatorComponent, +33 | | } +34 | | } + | |_^ required by this bound in `__CheckRectangle` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs new file mode 100644 index 00000000..c23f5824 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs @@ -0,0 +1,13 @@ +// A position a tuple struct lacks has no `HasField` impl, so reading it is a compile error rather +// than a runtime panic. This is the `Index` page's *Common Mistakes* entry on an absent position. + +use cgp::prelude::*; + +#[derive(HasField)] +pub struct Point(pub f64, pub f64, pub f64); + +pub fn sixth(point: &Point) -> f64 { + *point.get_field(PhantomData::>) +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.stderr b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.stderr new file mode 100644 index 00000000..8c9081c5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.stderr @@ -0,0 +1,19 @@ +error[E0277]: the trait bound `Point: cgp::prelude::HasField>` is not satisfied + --> tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs:10:12 + | +10 | *point.get_field(PhantomData::>) + | ^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::prelude::HasField>` is not implemented for `Point` + --> tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs:7:1 + | + 7 | pub struct Point(pub f64, pub f64, pub f64); + | ^^^^^^^^^^^^^^^^ +help: `Point` implements trait `cgp::prelude::HasField` + --> tests/compile_fail/reference/types/index_type_common_mistakes_missing_position.rs:7:18 + | + 7 | pub struct Point(pub f64, pub f64, pub f64); + | ^^^ ^^^ ^^^ `cgp::prelude::HasField>` + | | | + | | `cgp::prelude::HasField>` + | `cgp::prelude::HasField>` diff --git a/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs new file mode 100644 index 00000000..67ae74d9 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs @@ -0,0 +1,13 @@ +// A tuple field is keyed by `Index`, never by a string of its digit, so `Symbol!("0")` names no +// field of a tuple struct. This is the `Index` page's *Common Mistakes* entry on the two tags. + +use cgp::prelude::*; + +#[derive(HasField)] +pub struct Pair(pub u32, pub String); + +pub fn first(pair: &Pair) -> u32 { + *pair.get_field(PhantomData::) +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.stderr b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.stderr new file mode 100644 index 00000000..9f3cab2a --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.stderr @@ -0,0 +1,18 @@ +error[E0277]: the trait bound `Pair: cgp::prelude::HasField>>` is not satisfied + --> tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs:10:11 + | +10 | *pair.get_field(PhantomData::) + | ^^^^^^^^^ unsatisfied trait bound + | +help: the trait `cgp::prelude::HasField>>` is not implemented for `Pair` + --> tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs:7:1 + | + 7 | pub struct Pair(pub u32, pub String); + | ^^^^^^^^^^^^^^^ +help: `Pair` implements trait `cgp::prelude::HasField` + --> tests/compile_fail/reference/types/index_type_common_mistakes_symbol_of_a_digit.rs:7:17 + | + 7 | pub struct Pair(pub u32, pub String); + | ^^^ ^^^ `cgp::prelude::HasField>` + | | + | `cgp::prelude::HasField>` diff --git a/example-code/tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.rs b/example-code/tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.rs new file mode 100644 index 00000000..1b9eb163 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.rs @@ -0,0 +1,38 @@ +// A check lists a lifetime component's parameters as `(Life<'a>, T)`. A bare `'a` in the tuple is +// read as a trait-object type without a trait. This pins the `Life` page's *Behavior*. + +use cgp::prelude::*; + +#[cgp_component(ReferenceGetter)] +pub trait HasReference<'a, T: 'a + ?Sized> { + fn get_reference(&self) -> &'a T; +} + +pub struct Config { + pub name: String, +} + +pub struct App<'a> { + pub config: &'a Config, +} + +#[cgp_impl(new GetConfig)] +impl<'a> ReferenceGetter<'a, Config> for App<'a> { + fn get_reference(&self) -> &'a Config { + self.config + } +} + +delegate_components! { + <'a> App<'a> { + ReferenceGetterComponent: GetConfig, + } +} + +check_components! { + <'a> App<'a> { + ReferenceGetterComponent: ('a, Config), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.stderr b/example-code/tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.stderr new file mode 100644 index 00000000..5799fb51 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.stderr @@ -0,0 +1,5 @@ +error: at least one trait is required for an object type + --> tests/compile_fail/reference/types/life_behavior_bare_lifetime_in_check.rs:34:36 + | +34 | ReferenceGetterComponent: ('a, Config), + | ^^ diff --git a/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs b/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs new file mode 100644 index 00000000..f7e26b20 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs @@ -0,0 +1,43 @@ +// A component whose type parameter is `?Sized` passes `check_components!` at an unsized argument +// such as `str`, but a call through the wiring fails: the forwarding `IsProviderFor` impl that +// `delegate_components!` emits declares its `__Params__` parameter without `?Sized`, and the params +// tuple `(Life<'a>, str)` is unsized. This pins the `Life` page's *Common Mistakes* entry. + +use cgp::prelude::*; + +#[cgp_component(ReferenceGetter)] +pub trait HasReference<'a, T: 'a + ?Sized> { + fn get_reference(&self) -> &'a T; +} + +#[cgp_impl(new GetName)] +#[uses(HasField)] +impl<'a> ReferenceGetter<'a, str> { + fn get_reference(&self) -> &'a str { + self.get_field(PhantomData::) + } +} + +#[derive(HasField)] +pub struct Borrowed<'a> { + pub name: &'a str, +} + +delegate_components! { + <'a> Borrowed<'a> { + ReferenceGetterComponent: GetName, + } +} + +// The check passes. +check_components! { + <'a> Borrowed<'a> { + ReferenceGetterComponent: (Life<'a>, str), + } +} + +fn main() { + let borrowed = Borrowed { name: "hello" }; + let name: &str = borrowed.get_reference(); + assert_eq!(name, "hello"); +} diff --git a/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.stderr b/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.stderr new file mode 100644 index 00000000..a0955938 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.stderr @@ -0,0 +1,29 @@ +error[E0599]: the method `get_reference` exists for struct `Borrowed<'_>`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs:41:31 + | +22 | pub struct Borrowed<'a> { + | ----------------------- method `get_reference` not found for this struct because it doesn't satisfy `Borrowed<'_>: HasReference<'_, str>` +... +41 | let name: &str = borrowed.get_reference(); + | ^^^^^^^^^^^^^ this is an associated function, not a method + | + = note: found the following associated functions; to be used as methods, functions must have a `self` parameter +note: the candidate is defined in the trait `ReferenceGetter` + --> tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs:10:5 + | +10 | fn get_reference(&self) -> &'a T; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: the following trait bounds were not satisfied: + `str: Sized` + which is required by `Borrowed<'_>: HasReference<'_, str>` + = help: items from traits can only be used if the trait is implemented and in scope +note: `HasReference` defines an item `get_reference`, perhaps you need to implement it + --> tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs:9:1 + | + 9 | pub trait HasReference<'a, T: 'a + ?Sized> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +help: use associated function syntax instead + | +41 - let name: &str = borrowed.get_reference(); +41 + let name: &str = Borrowed<'_>::get_reference(); + | diff --git a/example-code/tests/compile_fail/reference/types/life_definition_invariant.rs b/example-code/tests/compile_fail/reference/types/life_definition_invariant.rs new file mode 100644 index 00000000..ad6102cd --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_definition_invariant.rs @@ -0,0 +1,11 @@ +// `Life<'a>` holds a `PhantomData<*mut &'a ()>`, and `*mut T` is invariant in `T`, so a `Life<'l>` +// does not convert to a `Life<'s>` even when `'l` outlives `'s`. This pins the `Life` page's +// *Definition*; the same function over a covariant `PhantomData<&'l ()>` compiles. + +use cgp::prelude::*; + +pub fn shorten<'s, 'l: 's>(marker: Life<'l>) -> Life<'s> { + marker +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/life_definition_invariant.stderr b/example-code/tests/compile_fail/reference/types/life_definition_invariant.stderr new file mode 100644 index 00000000..d3be328d --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_definition_invariant.stderr @@ -0,0 +1,14 @@ +error: lifetime may not live long enough + --> tests/compile_fail/reference/types/life_definition_invariant.rs:8:5 + | +7 | pub fn shorten<'s, 'l: 's>(marker: Life<'l>) -> Life<'s> { + | -- -- lifetime `'l` defined here + | | + | lifetime `'s` defined here +8 | marker + | ^^^^^^ function was supposed to return data with lifetime `'l` but it is returning data with lifetime `'s` + | + = help: consider adding the following bound: `'s: 'l` + = note: requirement occurs because of the type `cgp::prelude::Life<'_>`, which makes the generic argument `'_` invariant + = note: the struct `cgp::prelude::Life<'a>` is invariant over the parameter `'a` + = help: see for more information about variance diff --git a/example-code/tests/compile_fail/reference/types/life_definition_not_send.rs b/example-code/tests/compile_fail/reference/types/life_definition_not_send.rs new file mode 100644 index 00000000..33d7e916 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_definition_not_send.rs @@ -0,0 +1,24 @@ +// The raw pointer inside `Life` makes it neither `Send` nor `Sync`, and a provider struct that +// `#[cgp_impl(new ...)]` declares over a lifetime holds a `PhantomData>`, so it is not +// `Send` either. This pins the `Life` page's *Definition*. + +use cgp::prelude::*; + +#[cgp_component(NameGetter)] +pub trait HasName<'a> { + fn name(&self) -> &'a str; +} + +#[cgp_impl(new GetName<'b>)] +impl<'a, 'b> NameGetter<'a> { + fn name(&self) -> &'a str { + "name" + } +} + +fn require_send() {} + +fn main() { + require_send::>(); + require_send::>(); +} diff --git a/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr new file mode 100644 index 00000000..6bc3014f --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr @@ -0,0 +1,55 @@ +error[E0277]: `*mut &'static ()` cannot be sent between threads safely + --> tests/compile_fail/reference/types/life_definition_not_send.rs:22:20 + | +22 | require_send::>(); + | ^^^^^^^^^^^^^ `*mut &'static ()` cannot be sent between threads safely + | + = help: within `cgp::prelude::Life<'static>`, the trait `Send` is not implemented for `*mut &'static ()` +note: required because it appears within the type `PhantomData<*mut &'static ()>` + --> $RUST/core/src/marker.rs + | + | pub struct PhantomData; + | ^^^^^^^^^^^ +note: required because it appears within the type `cgp::prelude::Life<'static>` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/types/life.rs:3:12 + | + 3 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); + | ^^^^ +note: required by a bound in `require_send` + --> tests/compile_fail/reference/types/life_definition_not_send.rs:19:20 + | +19 | fn require_send() {} + | ^^^^ required by this bound in `require_send` + +error[E0277]: `*mut &'static ()` cannot be sent between threads safely + --> tests/compile_fail/reference/types/life_definition_not_send.rs:23:20 + | +23 | require_send::>(); + | ^^^^^^^^^^^^^^^^ `*mut &'static ()` cannot be sent between threads safely + | + = help: within `GetName<'static>`, the trait `Send` is not implemented for `*mut &'static ()` +note: required because it appears within the type `PhantomData<*mut &'static ()>` + --> $RUST/core/src/marker.rs + | + | pub struct PhantomData; + | ^^^^^^^^^^^ +note: required because it appears within the type `cgp::prelude::Life<'static>` + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/types/life.rs:3:12 + | + 3 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); + | ^^^^ +note: required because it appears within the type `PhantomData>` + --> $RUST/core/src/marker.rs + | + | pub struct PhantomData; + | ^^^^^^^^^^^ +note: required because it appears within the type `GetName<'static>` + --> tests/compile_fail/reference/types/life_definition_not_send.rs:12:16 + | +12 | #[cgp_impl(new GetName<'b>)] + | ^^^^^^^ +note: required by a bound in `require_send` + --> tests/compile_fail/reference/types/life_definition_not_send.rs:19:20 + | +19 | fn require_send() {} + | ^^^^ required by this bound in `require_send` diff --git a/example-code/tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.rs b/example-code/tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.rs new file mode 100644 index 00000000..34332116 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.rs @@ -0,0 +1,12 @@ +// The getter macros recognize `MRef<'_, T>` by its shape, a single-segment path named `MRef`. A +// qualified path is treated as an owned field type instead, so `'_` lands in a `HasField` bound, +// where it is not allowed. This is the `MRef` page's *Common Mistakes* entry on a qualified path. + +use cgp::prelude::*; + +#[cgp_auto_getter] +pub trait HasGreeting { + fn greeting(&self) -> cgp::prelude::MRef<'_, String>; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.stderr b/example-code/tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.stderr new file mode 100644 index 00000000..dd198042 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.stderr @@ -0,0 +1,5 @@ +error[E0637]: `'_` cannot be used here + --> tests/compile_fail/reference/types/mref_common_mistakes_qualified_path.rs:9:46 + | +9 | fn greeting(&self) -> cgp::prelude::MRef<'_, String>; + | ^^ `'_` is a reserved lifetime name diff --git a/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs new file mode 100644 index 00000000..dd571862 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs @@ -0,0 +1,18 @@ +// `get_field` takes its tag as a `PhantomData` argument. On a context with more than one field, +// a bare `PhantomData` leaves the tag to inference, and nothing fixes it. This is the `PhantomData` +// page's *Common Mistakes* entry on the turbofish. + +use cgp::prelude::*; + +#[derive(HasField)] +pub struct Person { + pub name: String, + pub age: u8, +} + +pub fn print_name(person: &Person) { + let name = person.get_field(PhantomData); + println!("{name}"); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.stderr b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.stderr new file mode 100644 index 00000000..f43c2633 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.stderr @@ -0,0 +1,33 @@ +error[E0284]: type annotations needed + --> tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs:14:33 + | +14 | let name = person.get_field(PhantomData); + | --------- ^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the struct `PhantomData` + | | + | type must be known at this point + | + = note: cannot satisfy `>::Value == _` +help: consider specifying a concrete type for the type parameter `T` + | +14 | let name = person.get_field(PhantomData::); + | ++++++++++++++ + +error[E0283]: type annotations needed + --> tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs:14:33 + | +14 | let name = person.get_field(PhantomData); + | --------- ^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the struct `PhantomData` + | | + | required by a bound introduced by this call + | +note: multiple `impl`s satisfying `Person: cgp::prelude::HasField<_>` found + --> tests/compile_fail/reference/types/phantom_data_common_mistakes_inferring_the_tag.rs:9:9 + | + 9 | pub name: String, + | ^^^^ +10 | pub age: u8, + | ^^^ +help: consider specifying a concrete type for the type parameter `T` + | +14 | let name = person.get_field(PhantomData::); + | ++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.rs b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.rs new file mode 100644 index 00000000..ffe7e490 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.rs @@ -0,0 +1,6 @@ +// The unused-parameter rule covers lifetimes too: a marker generic over a lifetime it stores no +// borrow of does not compile. This is the `PhantomData` page's *Common Mistakes* entry on the rule. + +pub struct Borrowing<'a>; + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.stderr b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.stderr new file mode 100644 index 00000000..0101c6b7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.stderr @@ -0,0 +1,7 @@ +error[E0392]: lifetime parameter `'a` is never used + --> tests/compile_fail/reference/types/phantom_data_common_mistakes_unused_lifetime.rs:4:22 + | +4 | pub struct Borrowing<'a>; + | ^^ unused lifetime parameter + | + = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` diff --git a/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.rs b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.rs new file mode 100644 index 00000000..9c2a1918 --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.rs @@ -0,0 +1,16 @@ +// A match on a sum by value may leave out the `Void` arm, but a match behind a reference may not: +// Rust does not treat an uninhabited type reached through a reference as unreachable. This is the +// `Void` page's *Common Mistakes* entry on the closing arm. + +use cgp::prelude::*; + +pub type Token = Sum![u32, bool]; + +pub fn describe(token: &Token) -> String { + match token { + Either::Left(number) => format!("number {number}"), + Either::Right(Either::Left(flag)) => format!("flag {flag}"), + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr new file mode 100644 index 00000000..8104bcba --- /dev/null +++ b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr @@ -0,0 +1,24 @@ +error[E0004]: non-exhaustive patterns: `&cgp::prelude::Either::Right(cgp::prelude::Either::Right(_))` not covered + --> tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.rs:10:11 + | +10 | match token { + | ^^^^^ pattern `&cgp::prelude::Either::Right(cgp::prelude::Either::Right(_))` not covered + | +note: `cgp::prelude::Either>` defined here + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/types/sum.rs:27:1 + | +27 | pub enum Either { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +28 | Left(Head), +29 | Right(Tail), + | ----- + | | + | not covered + | not covered + = note: the matched value is of type `&cgp::prelude::Either>` + = note: `Void` is uninhabited but is not being matched by value, so a wildcard `_` is required +help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown + | +12 ~ Either::Right(Either::Left(flag)) => format!("flag {flag}"), +13 ~ &cgp::prelude::Either::Right(cgp::prelude::Either::Right(_)) => todo!(), + | diff --git a/example-code/tests/reference/types/chars.rs b/example-code/tests/reference/types/chars.rs index e86f226a..ce8b81e2 100644 --- a/example-code/tests/reference/types/chars.rs +++ b/example-code/tests/reference/types/chars.rs @@ -1,58 +1,46 @@ //! Code from `docs/reference/types/chars.md` — *`Chars`*. //! -//! A `Symbol!` wraps a `Chars` chain. The page reads a field by its `Symbol!` tag and rebuilds the -//! string from the type; both run here. The greet provider duplicates the one on the `PhantomData` -//! page, which the crate prefers over a shared helper so each file answers for its own page. +//! A `Symbol!` wraps a `Chars` chain. The Examples program reads a field through its `Symbol!` tag, +//! checks the chain a symbol expands to (with its byte length for a non-ASCII name), and rebuilds the +//! string through `Display`. The raw error for a missing field, whose `Chars` chain the page shows how +//! to read, is a trybuild fixture under `tests/compile_fail/reference/types/`. /// ## Examples -/// -/// A field-name tag drives a getter, and a `Symbol!` rebuilds its string through `Display`. pub mod examples { use cgp::prelude::*; - #[cgp_component(Greeter)] - pub trait CanGreet { - fn greet(&self); - } - - #[cgp_impl(new GreetHello)] - impl Greeter + // The tag names the field the function reads. + pub fn name_of(context: &Context) -> &str where - Self: HasField, + Context: HasField, { - fn greet(&self) { - println!("Hello, {}!", self.get_field(PhantomData::)); - } + context.get_field(PhantomData::) } #[derive(HasField)] - pub struct App { + pub struct Person { pub name: String, } - delegate_components! { - App { - GreeterComponent: GreetHello, - } - } + pub fn demo() { + let person = Person { + name: "Alice".to_owned(), + }; + assert_eq!(name_of(&person), "Alice"); - check_components! { - App { - GreeterComponent - } - } + // `Symbol!` spells the string out as a `Chars` chain, with its byte length in front. + let _: PhantomData>>>> = + PhantomData::; + let _: PhantomData>>> = PhantomData::; - #[test] - fn test_a_symbol_rebuilds_its_string() { - let s = ::default(); - assert_eq!(s.to_string(), "hello"); + // `Display` walks the chain to rebuild the text. + let symbol = ::default(); + assert_eq!(symbol.to_string(), "hello"); + assert_eq!(core::mem::size_of::(), 0); } #[test] - fn test_greet_reads_the_name_field() { - let app = App { - name: "World".to_owned(), - }; - app.greet(); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/types/cons.rs b/example-code/tests/reference/types/cons.rs index 8eb443b5..c042c04a 100644 --- a/example-code/tests/reference/types/cons.rs +++ b/example-code/tests/reference/types/cons.rs @@ -1,12 +1,10 @@ //! Code from `docs/reference/types/cons.md` — *`Cons`*. //! -//! `Cons`/`Nil` are what `Product!` expands to. This pins the `Cons` chain a derive assigns and the one -//! a `Product!` alias produces, by naming the chain explicitly and by building a `product!` value by -//! hand. +//! `Cons`/`Nil` are what `Product!` expands to. The Examples program builds a `product!` value and +//! the same value by hand, reads a struct's shape as a `Cons` chain, and folds over a list with the +//! standard pair of impls: one for `Nil` and one for `Cons`. /// ## Examples -/// -/// A struct's shape is a `Cons` chain of `Field` entries, and a `Product!` value is a `Cons` value. pub mod examples { use cgp::prelude::*; @@ -16,25 +14,45 @@ pub mod examples { pub age: u8, } - // The page shows the generated `Fields` as a `Cons` chain; the coercion checks it. - pub fn assert_person_fields( - fields: ::Fields, - ) -> Cons, Cons, Nil>> { - fields + pub type Row = Product![u32, String, bool]; + + // A fold over a product list: `Nil` is the base case, `Cons` the step. + pub trait Len { + const LEN: usize; } - pub type Row = Product![u32, String, bool]; + impl Len for Nil { + const LEN: usize = 0; + } - // `Product!` is sugar for the right-nested `Cons` chain. - pub fn assert_row_is_cons(row: Row) -> Cons>> { - row + impl Len for Cons { + const LEN: usize = 1 + Tail::LEN; } - #[test] - fn test_a_product_value_is_a_cons_value() { - let row: Row = product![1, "hi".to_string(), true]; + pub fn demo() { + // `product!` builds the same nested value a hand-written chain does. + let row: Row = product![1, "hi".to_owned(), true]; let by_hand: Cons>> = - Cons(1, Cons("hi".to_string(), Cons(true, Nil))); + Cons(1, Cons("hi".to_owned(), Cons(true, Nil))); assert_eq!(row, by_hand); + + // A struct's shape is a `Cons` chain of `Field` entries. + let Cons(name, Cons(age, Nil)): Cons< + Field, + Cons, Nil>, + > = Person { + name: "Alice".to_owned(), + age: 30, + } + .to_fields(); + assert_eq!((name.value.as_str(), age.value), ("Alice", 30)); + + assert_eq!(::LEN, 3); + assert_eq!(<::Fields as Len>::LEN, 2); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/types/either.rs b/example-code/tests/reference/types/either.rs index 42f2428d..c536bf3c 100644 --- a/example-code/tests/reference/types/either.rs +++ b/example-code/tests/reference/types/either.rs @@ -1,12 +1,10 @@ //! Code from `docs/reference/types/either.md` — *`Either`*. //! -//! `Either`/`Void` are what `Sum!` expands to. This pins the `Either` chain a derive assigns to an enum -//! and the branch a nested `Either` value selects. +//! `Either`/`Void` are what `Sum!` expands to. The Examples program reads an enum's shape as an +//! `Either` chain of `Field` entries, matches it by nesting depth with a `Void` arm that closes the +//! match, and builds a standalone `Sum!` value. /// ## Examples -/// -/// An enum's shape is an `Either` chain of `Field` entries terminated by `Void`, and a `Sum!` value -/// selects one branch by its nesting depth. pub mod examples { use cgp::prelude::*; @@ -16,35 +14,38 @@ pub mod examples { Rectangle { width: f64, height: f64 }, } - // The page shows the generated `Fields` as an `Either` chain; the coercion checks it. - pub fn assert_shape_fields( - fields: ::Fields, - ) -> Either< - Field, - Either< - Field< - Symbol!("Rectangle"), - Product![Field, Field], - >, - Void, - >, - > { - fields + pub fn area(shape: Shape) -> f64 { + match shape.to_fields() { + Either::Left(circle) => core::f64::consts::PI * circle.value * circle.value, + Either::Right(Either::Left(rectangle)) => { + let Cons(width, Cons(height, Nil)) = rectangle.value; + width.value * height.value + } + Either::Right(Either::Right(void)) => match void {}, + } } pub type Token = Sum![u32, String, bool]; - pub fn assert_token_is_either(token: Token) -> Either>> { - token + pub fn demo() { + assert_eq!( + area(Shape::Rectangle { + width: 2.0, + height: 3.0 + }), + 6.0 + ); + + // The `String` branch sits one `Right` deep. + let token: Token = Either::Right(Either::Left("hi".to_owned())); + assert_eq!(token, Either::Right(Either::Left("hi".to_owned()))); + + // `Sum!` is the right-nested `Either` chain ending in `Void`. + let _: PhantomData>>> = PhantomData::; } #[test] - fn test_a_value_selects_a_branch_by_depth() { - // the String branch - let t: Token = Either::Right(Either::Left("hi".to_string())); - match t { - Either::Right(Either::Left(s)) => assert_eq!(s, "hi"), - _ => panic!("wrong branch"), - } + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/types/field.rs b/example-code/tests/reference/types/field.rs index ac8419be..17ef2e93 100644 --- a/example-code/tests/reference/types/field.rs +++ b/example-code/tests/reference/types/field.rs @@ -1,13 +1,11 @@ //! Code from `docs/reference/types/field.md` — *`Field`*. //! -//! A `Field` pairs a value with a type-level tag. This pins the `Fields` shape a derive assigns, where -//! each entry is a `Field`, and the `.into()` construction the page shows. +//! A `Field` pairs a value with a type-level tag. The Examples program reads a struct's shape as a +//! list of `Field` entries, builds one entry with `.into()`, shows that the tag adds no size and no +//! output, and shows a one-field tuple struct, whose shape is its field's type with no `Field` around +//! it. /// ## Examples -/// -/// Each entry of a struct's shape is a `Field` tagged by its name; naming the shape checks the mapping. -/// A single `Field` is built from its value with `.into()`, the tag supplied by the type annotation, -/// and a tuple-struct field is tagged by an `Index` rather than a `Symbol!`. pub mod examples { use cgp::prelude::*; @@ -17,18 +15,47 @@ pub mod examples { pub age: u8, } - pub type ExpectedFields = Product![Field, Field]; + #[derive(HasFields)] + pub struct Point(pub u32, pub u32); - pub fn assert_fields(fields: ::Fields) -> ExpectedFields { - fields - } + #[derive(HasFields)] + pub struct Meters(pub u32); - // The positional form the page names: `Index<0>` in place of a `Symbol!`. - pub type PositionalField = Field, u32>; + pub fn demo() { + // A struct's shape is a list of `Field` entries, each tagged by its name. + let fields: Product![Field, Field] = Person { + name: "Alice".to_owned(), + age: 30, + } + .to_fields(); - #[test] - fn test_a_field_is_built_from_its_value() { - let name: Field = "Alice".to_string().into(); + let Cons(name, Cons(age, Nil)) = fields; assert_eq!(name.value, "Alice"); + assert_eq!(age.value, 30); + + // A tuple struct's entries are tagged by position. + let Cons(x, Cons(y, Nil)): Product![Field, u32>, Field, u32>] = + Point(3, 4).to_fields(); + assert_eq!((x.value, y.value), (3, 4)); + + // A one-field tuple struct's shape is the field's type itself. + let inner: u32 = Meters(7).to_fields(); + assert_eq!(inner, 7); + + // One entry, built from its value; the annotation supplies the tag. + let entry: Field = "Bob".to_owned().into(); + assert_eq!(entry.value, "Bob"); + + // The tag adds no size, and `Debug` prints the value alone. + assert_eq!( + core::mem::size_of::>(), + core::mem::size_of::() + ); + assert_eq!(format!("{entry:?}"), "\"Bob\""); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/types/index_type.rs b/example-code/tests/reference/types/index_type.rs index 3b696cb3..9c37c0de 100644 --- a/example-code/tests/reference/types/index_type.rs +++ b/example-code/tests/reference/types/index_type.rs @@ -1,26 +1,30 @@ //! Code from `docs/reference/types/index_type.md` — *`Index`*. //! -//! `Index` tags a tuple-struct field by its position. The page reads a field by its index and prints -//! the number a tag stands for; both run here. +//! `Index` tags a tuple-struct field by its position. The Examples program reads both fields of a +//! tuple struct by their indices and prints the number an `Index` stands for. A position the struct +//! lacks, and a `Symbol!` of a digit, are trybuild fixtures under +//! `tests/compile_fail/reference/types/`. /// ## Examples -/// -/// Deriving `HasField` on a tuple struct is what makes the positional `get_field` below resolve, and an -/// `Index` prints its number through `Display`. pub mod examples { use cgp::prelude::*; #[derive(HasField)] pub struct Pair(pub u32, pub String); - #[test] - fn test_a_tuple_field_is_read_by_its_index() { - let pair = Pair(7, "hi".to_string()); + pub fn demo() { + let pair = Pair(7, "hi".to_owned()); + assert_eq!(*pair.get_field(PhantomData::>), 7); + assert_eq!(pair.get_field(PhantomData::>), "hi"); + + // `Display` and `Debug` both print the number. + assert_eq!(Index::<2>.to_string(), "2"); + assert_eq!(format!("{:?}", Index::<2>), "2"); } #[test] - fn test_an_index_prints_its_number() { - assert_eq!(Index::<2>.to_string(), "2"); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/types/life.rs b/example-code/tests/reference/types/life.rs index d93b6d90..bea93e06 100644 --- a/example-code/tests/reference/types/life.rs +++ b/example-code/tests/reference/types/life.rs @@ -1,14 +1,12 @@ //! Code from `docs/reference/types/life.md` — *`Life`*. //! -//! `Life` is inserted by the macros; the only user-written code the page shows is a component whose -//! consumer trait carries a lifetime. This pins that `#[cgp_component]` accepts that form. The -//! generated provider trait, which records the lifetime as `Life<'a>`, is shown as a comment on the -//! page and checked by `cargo cgp expand` rather than here. +//! `Life` is inserted by the macros into the dependency marker of a component with a lifetime, and a +//! reader names it in one place: the `check_components!` entry for such a component. The Examples +//! program wires and checks a borrowing getter component and calls it. The generated provider trait, +//! which records the lifetime as `Life<'a>`, is checked with `cargo cgp expand`. The unsized-target +//! defect the page records is a trybuild fixture under `tests/compile_fail/reference/types/`. /// ## Examples -/// -/// A borrowing getter component. Defining it is the check: the macro accepts the lifetime and lifts it -/// into the dependency marker. pub mod examples { use cgp::prelude::*; @@ -16,4 +14,66 @@ pub mod examples { pub trait HasReference<'a, T: 'a + ?Sized> { fn get_reference(&self) -> &'a T; } + + pub struct Config { + pub name: String, + } + + #[cgp_impl(new GetConfig)] + #[uses(HasField)] + impl<'a> ReferenceGetter<'a, Config> { + fn get_reference(&self) -> &'a Config { + self.get_field(PhantomData::) + } + } + + #[derive(HasField)] + pub struct App<'a> { + pub config: &'a Config, + } + + delegate_components! { + <'a> App<'a> { + ReferenceGetterComponent: GetConfig, + } + } + + check_components! { + <'a> App<'a> { + ReferenceGetterComponent: (Life<'a>, Config), + } + } + + pub fn demo() { + let config = Config { + name: "demo".to_owned(), + }; + let app = App { config: &config }; + + let config_ref: &Config = app.get_reference(); + assert_eq!(config_ref.name, "demo"); + } + + #[test] + fn test_demo() { + demo(); + } +} + +/// ## Definition +/// +/// The covariant half of the invariance comparison: a function that shortens a +/// `PhantomData<&'l ()>` compiles, while the same function over `Life<'l>` is the fixture +/// `life_definition_invariant.rs`. A `Life` is zero-sized. +pub mod definition { + use cgp::prelude::*; + + pub fn shorten<'s, 'l: 's>(marker: PhantomData<&'l ()>) -> PhantomData<&'s ()> { + marker + } + + #[test] + fn test_life_is_zero_sized() { + assert_eq!(core::mem::size_of::>(), 0); + } } diff --git a/example-code/tests/reference/types/mod.rs b/example-code/tests/reference/types/mod.rs index 61a7a183..b27e5be5 100644 --- a/example-code/tests/reference/types/mod.rs +++ b/example-code/tests/reference/types/mod.rs @@ -2,7 +2,7 @@ //! //! Most of these types are type-level markers a reader recognizes rather than writes, so a page gets a //! module only where it shows code a compiler can check: a shape a derive assigns, a value built from a -//! marker, a call site that passes a tag. The two overview pages, which show no code, get none. +//! marker, a call site that passes a tag. The overview page, which shows no code, gets none. pub mod chars; pub mod cons; diff --git a/example-code/tests/reference/types/mref.rs b/example-code/tests/reference/types/mref.rs index 6d6db2df..b64bf769 100644 --- a/example-code/tests/reference/types/mref.rs +++ b/example-code/tests/reference/types/mref.rs @@ -1,29 +1,84 @@ //! Code from `docs/reference/types/mref.md` — *`MRef`*. //! -//! `MRef` is an ordinary runtime value, not a type-level marker. The page builds one both ways and -//! promotes it to an owned value; this runs that. +//! `MRef` is an ordinary runtime value, not a type-level marker. The Examples program declares a +//! getter returning `MRef`, wires one context to lend a stored field and another to build the value, +//! and reads both through one generic function. /// ## Examples -/// -/// A borrowed value and a freshly built one have the same type and are read the same way, and -/// `get_or_clone` promotes either to ownership. pub mod examples { use cgp::prelude::*; - #[test] - fn test_borrowed_and_owned_are_read_the_same_way() { - let stored = String::from("hello"); + #[cgp_getter] + pub trait HasGreeting { + fn greeting(&self) -> MRef<'_, String>; + } + + // A provider that builds the value instead of lending a field. + #[cgp_impl(new BuildGreeting)] + impl GreetingGetter { + fn greeting(&self, #[implicit] name: &str) -> MRef<'_, String> { + MRef::Owned(format!("Hello, {name}!")) + } + } - // a context lending a stored value: - let borrowed: MRef<'_, String> = MRef::from(&stored); - assert_eq!(&*borrowed, "hello"); + #[derive(HasField)] + pub struct Stored { + pub greeting: String, + } - // a provider returning a freshly built value through the same type: - let made: MRef<'_, String> = MRef::from(String::from("world")); - assert_eq!(made.as_ref(), "world"); + #[derive(HasField)] + pub struct Computed { + pub name: String, + } - // promote either to an owned value when ownership is required: - let owned: String = borrowed.get_or_clone(); - assert_eq!(owned, "hello"); + delegate_components! { + Stored { + GreetingGetterComponent: UseField, + } + } + + delegate_components! { + Computed { + GreetingGetterComponent: BuildGreeting, + } + } + + check_components! { + Stored { + GreetingGetterComponent, + } + } + + check_components! { + Computed { + GreetingGetterComponent, + } + } + + // Generic code reads either case through `Deref`. + pub fn shout(context: &Context) -> String { + context.greeting().to_uppercase() + } + + pub fn demo() { + let stored = Stored { + greeting: "Hi there".to_owned(), + }; + let computed = Computed { + name: "Alice".to_owned(), + }; + + assert_eq!(shout(&stored), "HI THERE"); + assert_eq!(shout(&computed), "HELLO, ALICE!"); + + // `UseField` lends the stored field, and `get_or_clone` moves an owned value out. + assert!(matches!(stored.greeting(), MRef::Ref(_))); + let owned: String = computed.greeting().get_or_clone(); + assert_eq!(owned, "Hello, Alice!"); + } + + #[test] + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/types/nil.rs b/example-code/tests/reference/types/nil.rs index ee94dddb..cd39ba68 100644 --- a/example-code/tests/reference/types/nil.rs +++ b/example-code/tests/reference/types/nil.rs @@ -1,25 +1,34 @@ //! Code from `docs/reference/types/nil.md` — *`Nil`*. //! -//! `Nil` terminates the product, string, and path lists and is the empty product. This pins that the -//! empty `Product!` is `Nil`, at the type level and the value level. +//! `Nil` terminates the product, string, and path lists and is the empty product. The Examples +//! program checks each of those as a type equality, and builds the empty product and a unit struct's +//! shape as `Nil` values. /// ## Examples -/// -/// A `Cons` chain ends in `Nil`, and the empty product is `Nil` alone. pub mod examples { use cgp::prelude::*; - pub type Row = Cons>; + #[derive(HasFields)] + pub struct Marker; - pub type Empty = Product![]; + pub fn demo() { + // Each list ends in `Nil`; the annotations are the check. + let _row: PhantomData>> = PhantomData::; + let _name: PhantomData>>> = + PhantomData::; + let _path: PhantomData>> = + PhantomData::; - pub fn assert_empty_is_nil(empty: Empty) -> Nil { - empty + // The empty product, the empty string, and a unit struct's shape are all `Nil`. + let empty: Product![] = product![]; + assert_eq!(empty, Nil); + let _empty_name: PhantomData> = PhantomData::; + let fields: Nil = Marker.to_fields(); + assert_eq!(fields, Nil); } #[test] - fn test_the_empty_product_value_is_nil() { - let empty: Empty = product![]; - assert_eq!(empty, Nil); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/types/path_cons.rs b/example-code/tests/reference/types/path_cons.rs index 5b04fd8f..e7ae8d2c 100644 --- a/example-code/tests/reference/types/path_cons.rs +++ b/example-code/tests/reference/types/path_cons.rs @@ -1,26 +1,14 @@ //! Code from `docs/reference/types/path_cons.md` — *`PathCons`*. //! -//! `PathCons` is built by `Path!` and emitted by `cgp_namespace!`. Paths are unsized markers, so there -//! is no value to build: naming the `PathCons` chain a `Path!` produces and coercing it is the check, -//! and the namespace registration pins that the `=>` redirect the page shows compiles. +//! `PathCons` is built by `Path!` and emitted by `cgp_namespace!` and `#[prefix]`. Paths are markers +//! with no value to build, so the Examples program checks the chains as type equalities, including +//! a `ConcatPath` result, and registers the `cgp_namespace!` redirect the page shows. Its emitted entry +//! is checked with `cargo cgp expand`. /// ## Examples -/// -/// A lowercase path segment is a `Symbol`, so `Path!(@a.b)` is a two-segment `PathCons` chain, which is -/// the expansion the page shows. The page's `cgp_namespace!` then reroutes one component to a path; the -/// two components it names are defined here, which the page elides, so the redirect compiles. pub mod examples { use cgp::prelude::*; - pub type TwoSegments = Path!(@a.b); - - #[allow(dead_code)] - pub fn assert_path_is_pathcons( - path: PhantomData<&TwoSegments>, - ) -> PhantomData<&PathCons>> { - path - } - #[cgp_component(FooProvider)] pub trait CanFoo { fn foo(&self); @@ -37,4 +25,22 @@ pub mod examples { @MyFooComponent, } } + + pub fn demo() { + // A lowercase segment is a `Symbol`, and a capitalized one names its type. + let _: PhantomData>> = + PhantomData::; + + // A one-segment path. + let _: PhantomData> = PhantomData::; + + // `ConcatPath` appends one path to another. + let _: PhantomData = + PhantomData::<>::Output>; + } + + #[test] + fn test_demo() { + demo(); + } } diff --git a/example-code/tests/reference/types/phantom_data.rs b/example-code/tests/reference/types/phantom_data.rs index ff345a45..fbe29aa5 100644 --- a/example-code/tests/reference/types/phantom_data.rs +++ b/example-code/tests/reference/types/phantom_data.rs @@ -2,8 +2,10 @@ //! //! `PhantomData` is a standard-library type, so there is nothing of CGP's to re-declare. What the //! page's snippets check are its two roles: declaring a zero-sized struct generic over a type it -//! stores no value of, and passing a type to a call site as a token. The greet provider exercises the -//! second through `get_field(PhantomData::)`. +//! stores no value of, and passing a type to a call site as a zero-sized value. The Examples program +//! does both through one generic provider. The rejected forms (an unused type parameter, an unused +//! lifetime, and a call that leaves the tag to inference) are trybuild fixtures under +//! `tests/compile_fail/reference/types/`. /// ## Why a marker needs it /// @@ -22,59 +24,57 @@ pub mod why_a_marker_needs_it { } /// ## Examples -/// -/// Passing a type to a call site: `PhantomData::` selects which field the getter -/// reads. The component and the context are filled in around the page's `#[cgp_impl]` snippet so the -/// call resolves. A type carrying two parameters uses one `PhantomData` over a tuple. pub mod examples { use cgp::prelude::*; #[cgp_component(Greeter)] pub trait CanGreet { - fn greet(&self); + fn greet(&self) -> String; } - #[cgp_impl(new GreetHello)] - impl Greeter - where - Self: HasField, - { - fn greet(&self) { - let name = self.get_field(PhantomData::); - println!("Hello, {name}!"); + // `new` declares `pub struct GreetField(pub PhantomData);` + #[cgp_impl(new GreetField)] + #[uses(HasField)] + impl Greeter { + fn greet(&self) -> String { + let name = self.get_field(PhantomData::); + format!("Hello, {name}!") } } #[derive(HasField)] - pub struct App { + pub struct Person { pub name: String, } delegate_components! { - App { - GreeterComponent: GreetHello, + Person { + GreeterComponent: GreetField, } } check_components! { - App { - GreeterComponent + Person { + GreeterComponent, } } - // A type that must carry two parameters uses one `PhantomData` over a tuple. + // A marker over two parameters holds one `PhantomData` over a tuple. pub struct Add(pub PhantomData<(Left, Right)>); - #[test] - fn test_greet_reads_the_name_field() { - let app = App { + pub fn demo() { + let person = Person { name: "World".to_owned(), }; - app.greet(); + assert_eq!(person.greet(), "Hello, World!"); + + // Both markers occupy no space. + assert_eq!(core::mem::size_of::>(), 0); + assert_eq!(core::mem::size_of::>(), 0); } #[test] - fn test_a_two_parameter_marker_is_zero_sized() { - assert_eq!(core::mem::size_of::>(), 0); + fn test_demo() { + demo(); } } diff --git a/example-code/tests/reference/types/void.rs b/example-code/tests/reference/types/void.rs index 7e2e0d9d..b4b11e7d 100644 --- a/example-code/tests/reference/types/void.rs +++ b/example-code/tests/reference/types/void.rs @@ -1,21 +1,50 @@ //! Code from `docs/reference/types/void.md` — *`Void`*. //! -//! `Void` is uninhabited, so there is no value to build. Naming the empty `Sum!` as `Void` and coercing -//! it is the check. +//! `Void` is uninhabited, so the Examples program never builds one. It checks the empty `Sum!` is +//! `Void`, closes a match behind a reference with an empty `match` on the `Void` arm, leaves the arm +//! out of a match by value, and unwraps a `Result` whose error type is `Void` through +//! `FinalizeExtractResult`. The reference match without its `Void` arm is a trybuild fixture under +//! `tests/compile_fail/reference/types/`. /// ## Examples -/// -/// An `Either` chain ends in `Void`, and the empty sum is `Void` alone. pub mod examples { + use cgp::core::field::traits::FinalizeExtractResult; use cgp::prelude::*; - pub type Token = Either>; + pub type Token = Sum![u32, bool]; - pub type Empty = Sum![]; + // Behind a reference, the `Void` arm is required. + pub fn describe(token: &Token) -> String { + match token { + Either::Left(number) => format!("number {number}"), + Either::Right(Either::Left(flag)) => format!("flag {flag}"), + Either::Right(Either::Right(void)) => match *void {}, + } + } + + // By value, it may be left out. + pub fn is_number(token: Token) -> bool { + match token { + Either::Left(_) => true, + Either::Right(Either::Left(_)) => false, + } + } + + pub fn demo() { + // The annotations are the check: the chain ends in `Void`, and the empty sum is `Void`. + let _: PhantomData>> = PhantomData::; + let _: PhantomData = PhantomData::; + + assert_eq!(describe(&Either::Right(Either::Left(true))), "flag true"); + assert!(is_number(Either::Left(3))); + + // A `Result` that cannot fail unwraps without an `unwrap`. + let result: Result = Ok(5); + assert_eq!(result.finalize_extract_result(), 5); + } - // No value of either type is constructed: the coercion checks the type equality. - #[allow(dead_code)] - pub fn assert_empty_is_void(empty: Empty) -> Void { - empty + #[test] + fn test_demo() { + demo(); } } From 0ab069d31f74c5055bdbfc5d4f0f3a266e2eed85 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 07:37:48 +0000 Subject: [PATCH 147/516] Review the types/ revision Correct the Sum! page's claim that exhausted variant handling is left holding a Void (it holds an extractor whose every payload is Void), label the Life example's getter as self-targeted, describe the Void base case accurately, tighten the Void overview, and wrap the paragraphs the unsized-parameter notes added. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/macros/check_components.md | 8 ++++---- docs/reference/macros/delegate_components.md | 12 ++++++------ docs/reference/macros/sum.md | 9 +++++---- docs/reference/types/life.md | 6 +++--- docs/reference/types/void.md | 7 +++---- 5 files changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 9090636d..4ff11fe1 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -397,10 +397,10 @@ Use `#[check_trait(...)]` on one of them. the macro no identifier to derive a name from, and the table fails with `expected identifier` at the context type, which does not say a name is missing. Add `#[check_trait(Name)]`. -**A passing check is not a claim that the implementation is correct**, only that it resolves. It proves -the provider was found and its dependencies are satisfiable, not that the provider does what you meant. -One case slips past it: a component used at an unsized type parameter, such as `str`, passes its check -but fails at every call through the table, as the +**A passing check is not a claim that the implementation is correct**, only that it resolves. It +proves the provider was found and its dependencies are satisfiable, not that the provider does what +you meant. One case slips past it: a component used at an unsized type parameter, such as `str`, +passes its check but fails at every call through the table, as the [`delegate_components!`](./delegate_components.md#common-mistakes) page records. ## Related constructs diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 55bbf52d..dc00ed8a 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -781,13 +781,13 @@ generic ` AreaCalculatorComponent` entry overlapping a specific `@ComputerComponent. Code.Circle`. The same applies to a direct entry for a path a joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#common-mistakes). -**A component used at an unsized type parameter passes its check and fails at the call.** The impl the -macro emits for each entry to forward the dependency marker requires the component's parameters to be -`Sized`, so a component declared over `T: ?Sized` and wired at `str` never works through the table, -though `check_components!` passes for it. A call reports `E0599` with the note +**A component used at an unsized type parameter passes its check and fails at the call.** The +impl the macro emits for each entry to forward the dependency marker requires the component's +parameters to be `Sized`, so a component declared over `T: ?Sized` and wired at `str` never works +through the table, though `check_components!` passes for it. A call reports `E0599` with the note `` `str: Sized` which is required by … ``. This is a defect in the library. Until it is fixed, use a -sized parameter or implement the consumer trait directly on the context. The [`Life`](../types/life.md) -page shows the full example. +sized parameter or implement the consumer trait directly on the context. The +[`Life`](../types/life.md) page shows the full example. ## Related constructs diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 8e9474cf..b883a3fb 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -140,10 +140,11 @@ record is a perfectly good value; a sum terminates in `Void` because an empty ch being nothing to pick. `Void` functions as the never type, used here to close a sum off. **Why it matters beyond tidiness**: this gives generic variant handling compile-time exhaustiveness -without a wildcard arm. As each variant is ruled out, the remaining type shrinks toward `Void`, and code that -has handled every variant is left holding a value that cannot exist. The compiler accepts discharging it -with no fallback case. Add a variant to the enum without handling it, and the remainder becomes inhabited -again, so the code stops compiling. The same guarantee a concrete `match` gives, recovered for generic code. +without a wildcard arm. As an extractor rules each variant out, it marks that variant's payload as +`Void`, so code that has handled every variant is left holding a value that cannot exist. The +compiler accepts discharging it without a fallback case. Add a variant to the enum without handling +it, and the remainder becomes inhabited again, so the code stops compiling. Generic code gets the +guarantee a concrete `match` gives. The macro builds the chain by folding the element types right to left onto `Void`. diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index 7d528137..687a1053 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -121,9 +121,9 @@ pub fn demo() { } ``` -`App` is an environmental context: it holds the borrowed configuration a provider reads, and the -component is parameter-targeted, returning a borrow of `T` for the lifetime `'a`. The generated -provider trait records the lifetime in its dependency marker as the type `Life<'a>`, as +`App` is an environmental context: it holds the borrowed configuration a provider reads. The +component is a self-targeted getter, and its `T` names the type it lends for the lifetime `'a`. The +generated provider trait records the lifetime in its dependency marker as the type `Life<'a>`, as `cargo cgp expand` shows: ```rust diff --git a/docs/reference/types/void.md b/docs/reference/types/void.md index 999c2165..f716b3a6 100644 --- a/docs/reference/types/void.md +++ b/docs/reference/types/void.md @@ -14,8 +14,7 @@ complete variant match end without a runtime branch. `Void` marks the end of a sum. Unlike the [`Nil`](nil.md) that ends the other lists, it is uninhabited: a value of `Void` cannot exist. A record, a string, or a path can each be empty and still exist, but an -empty *choice* cannot. A value that is "none of the branches" cannot exist, so the natural terminator for -the sum list is a type without values. +empty *choice* cannot, so the natural terminator for the sum list is a type without values. The sum list depends on this uninhabitedness. An [`Either`](either.md) chain ends in `Void`, so a value that passed every real branch would have type `Void`, and such a value cannot exist. So the @@ -42,8 +41,8 @@ on one. It is in the prelude, so `use cgp::prelude::*;` is enough. `Void` is the base case of a recursion over a sum, and it differs from the product list's base case in a way that matters. A walk over an [`Either`](either.md) chain handles each `Left` as a branch and defers each `Right` to the tail, until the tail is `Void`. At that point nothing is left to -handle, so the base-case impl for `Void` either returns without doing anything or discharges a value -that cannot exist. +handle, so the base-case impl for `Void` ends the recursion, handing back what it was given or +discharging a value that cannot exist. Variant extraction uses the same uninhabitedness in a second place. An extractor from [`#[derive(ExtractField)]`](../derives/derive_extract_field.md) is a companion enum with one marker From 5cfab73b247cfb5e10233eef19f74c8d270d29e5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 08:47:59 +0000 Subject: [PATCH 148/516] Revise the reference index, compile-errors page, and glossary Index: route every exported name that lacks a page (consumer traits, the ErrorOf/TypeOf/RuntimeOf aliases, FieldsBuilder/FieldsExtractor, TryPromoteProviders, the derives' __Partial companions, component markers), drop rows for aliases that now have pages, fix the handler sibling list (Producer has none) and the field-access and ConcatPath descriptions, and add front matter. Errors: quote every diagnostic exactly as its fixture or stable rustc prints it, use the canonical cargo-cgp sentence, correct the child namespace override (rewritten as CGP-E005, or CGP-E007 for a redirect) and the self-inheriting namespace (E0207), add the reserved variant name, widen the E004, E005, and E007 descriptions, and fix the hidden-error fixture, which had pinned a parse error instead of E0599. Glossary: link the Hello World blanket-implementation explanation and the type-class source its comparison page cites, and drop an unsupported claim. Documents ErrorOnly on the HasErrorType page. All three pages lose their prose em dashes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/components/has_error_type.md | 21 ++ docs/reference/errors.md | 318 ++++++++++-------- docs/reference/glossary.md | 42 +-- docs/reference/index.md | 187 +++++----- .../reference/errors_the_fix_2.rs | 10 +- .../reference/errors_the_fix_2.stderr | 45 ++- .../reference/components/has_error_type.rs | 18 + example-code/tests/reference/errors.rs | 4 +- 8 files changed, 384 insertions(+), 261 deletions(-) diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index f7b7ec49..a073b2bd 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -85,6 +85,25 @@ which imports it as the bare name `Error`, or through the `ErrorOf` ali `::Error`. `ErrorOf`, the provider trait `ErrorTypeProvider`, and the key `ErrorTypeProviderComponent` all come from `cgp::core::error`. +The same module carries `ErrorOnly`, a zero-sized context whose one trait is `HasErrorType`, with +`Error = E` for any `E: Debug`. It implements `Default`, so `ErrorOnly::::default()` stands +in wherever code needs a context that has an error type and nothing else, such as a test of a +fallible function that reads nothing from its context: + +```rust +use cgp::core::error::{ErrorOf, ErrorOnly}; + +pub fn parse_port>( + _context: &Context, + raw: &str, +) -> Result> { + raw.parse().map_err(|_| format!("bad port: {raw}")) +} + +let context = ErrorOnly::::default(); +assert_eq!(parse_port(&context, "80"), Ok(80)); +``` + ## Examples A context declares its abstract error, and generic code returns it without naming a concrete type: @@ -157,6 +176,8 @@ The ideas behind it: - The trait and the `ErrorOf` alias: [`has_error_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/traits/has_error_type.rs) +- `ErrorOnly`: + [`error_only.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-error/src/contexts/error_only.rs) - The `#[cgp_type]` machinery it relies on: [`cgp_type/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_type/) - The pluggable concrete error backends: diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 510f216d..2bd3a698 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -1,44 +1,48 @@ --- sidebar_label: 'Compile errors' sidebar_position: 90 +description: 'The compile errors CGP code produces after macro expansion, how to read each one back to the mistake behind it, and what cargo cgp check makes of it.' --- # Compile errors The errors CGP produces after macro expansion, and how to read each one back to the mistake behind it. -CGP's macros expand to ordinary Rust, so most mistakes are not caught by a macro at all. They are caught -by the compiler afterwards, checking code you did not write — which is why a CGP error can name types -that appear nowhere in your source. This page is the catalog of those failures: what each one looks -like, whether the message contains the real cause, and what to change. +CGP's macros expand to ordinary Rust, so most mistakes are not caught by a macro at all. They are +caught by the compiler afterwards, checking code you did not write, which is why a CGP error can +name types that appear nowhere in your source. This page is the catalog of those failures: what each +one looks like, whether the message contains the real cause, and what to change. It is meant to be looked up rather than read through. If you have an error in front of you, start from [Find your error](#find-your-error). ## Run the checker first -**Before decoding anything, run [`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`.** -It rewrites the classes it recognizes to lead with the cause, and for the worst class it recovers a -cause that plain `cargo check` discards entirely. Every "what you see" example below is its real output. +**Before decoding anything, run [`cargo cgp check`](/docs/cargo-cgp/check) in place of +`cargo check`.** For the worst class it recovers a cause that plain `cargo check` discards entirely, +and every "what you see" example below is its real output. -It is a `v0.1.0-alpha` and does not reshape everything. Where a class passes through as the compiler -wrote it, this page says so and shows the raw form instead. +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a +v0.1.0-alpha that does not yet reshape every class. Where a class passes through as the compiler +wrote it, this page says so and shows the raw form instead. The raw forms quoted here are what +stable `rustc` prints. ## The one distinction that explains everything -**The same mistake produces two completely different errors depending on how you run into it**, and +**The same mistake produces two different errors depending on how you run into it**, and knowing which one you are looking at decides whether there is a cause in the message to find at all. -CGP wiring is lazy: [`delegate_components!`](./macros/delegate_components.md) records that a **context** -— the type the method runs on, which supplies the values it needs as its fields — uses some -provider, and nothing checks that the provider's own requirements hold. That check happens later, and +CGP wiring is lazy: [`delegate_components!`](./macros/delegate_components.md) records that a +[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the +values it needs as its fields, uses some provider, and nothing checks that the provider's own +requirements hold. That check happens later, and *how* it happens decides what you see. - **Surfaced.** When a [`check_components!`](./macros/check_components.md) block forces the question, the compiler proves the obligation outright and names the bound that failed. The cause is in the message. -- **Hidden.** When you instead call the method on the context, the compiler sees a blanket impl among - several candidates, abandons it, and reports only that the method's bounds were not satisfied. The - cause is **absent** — not buried. Reading harder will not find it. +- **Hidden.** When you instead call the method on the context, the compiler sees a blanket impl + among several candidates, abandons it, and reports only that the method's bounds were not + satisfied. The cause is **absent**, not buried. Reading harder will not find it. This is why the standard first move on a confusing CGP error is to add a check at the wiring site: it converts a hidden error into a surfaced one. `cargo cgp check` does the equivalent for you, which is why @@ -55,7 +59,7 @@ Match the compiler's code and the shape of the message. | `E0277` … `CanUseComponent` is not satisfied | A checked component's provider is missing something | [A dependency is not met](#a-dependency-is-not-met) | | `E0277` the trait bound `f64: Eq` is not satisfied | An ordinary Rust bound on a wired type | [When the missing bound is an ordinary Rust trait](#when-the-missing-bound-is-an-ordinary-rust-trait) | | `E0277` … `PathCons<…>: SomeNamespace<…>` is not satisfied | A namespace path nothing binds | [Nothing is wired there](#nothing-is-wired-there) | -| `E0277` the size for values of type `[u8]` cannot be known | A field-type shorthand lowered to an unsized type | [A field-type shorthand with no rule](#a-field-type-shorthand-with-no-rule) | +| `E0277` the size for values of type `[u8]` cannot be known | A field-type shorthand lowered to an unsized type | [A field-type shorthand without a rule](#a-field-type-shorthand-without-a-rule) | | `E0271` type mismatch resolving `<… as …>::Assoc == …` | A type pinned one way and wired another | [When two decisions disagree about a type](#when-two-decisions-disagree-about-a-type) | | `E0119` conflicting implementations | Two wiring entries claim one key | [The wiring itself does not compile](#the-wiring-itself-does-not-compile) | | `E0428` the name … is defined multiple times | A generated name declared twice | [Two entries claim one key](#two-entries-claim-one-key) | @@ -66,11 +70,12 @@ Match the compiler's code and the shape of the message. | `E0433` / `E0425` cannot find type | A name the generated code cannot see | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | | `E0576` cannot find associated type … in trait | A `#[use_type]` import with a wrong name | [An imported type that does not exist](#an-imported-type-that-does-not-exist) | | `E0404` expected trait, found type parameter | An [abstract type](/docs/reference/glossary#abstract-type) named after its own bound | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | +| `error: ambiguous associated item` (without a code) | An enum variant named like a derive's associated type | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | ## A dependency is not met -This is the most common CGP failure by a wide margin: a provider needs something from its context, and -the context does not supply it. +This is the most common CGP failure: a provider needs something from its context, and the context +does not supply it. ```rust use cgp::prelude::*; @@ -136,26 +141,28 @@ is the single largest thing the tool does. ### What the raw compiler says Without the tool the two routes diverge sharply. The **checked** form is readable: an `E0277` on -`CanUseComponent`, with a `help:` note naming the missing `HasField` and a -`required for …` chain building outward from it. The cause sits early, in that `help:` note, rather than -at the end. +`CanUseComponent`, with a `help:` note naming the missing `HasField` bound for `name` (spelled as a +`Symbol<4, Chars<…>>` list) and a `required for …` chain building outward from it. The cause sits +early, in that `help:` note, rather than at the end. The **method-call** form is the one to learn to recognize, because there is nothing in it to find: ```text error[E0599]: the method `greet` exists for struct `Person`, but its trait bounds were not satisfied + --> src/main.rs:50:23 | - | pub struct Person { - | ----------------- method `greet` not found for this struct because it doesn't satisfy - | `Person: CanGreet` or `Person: Greeter` - | - | Person { age: 0 }.greet(); +37 | pub struct Person { + | ----------------- method `greet` not found for this struct because it doesn't satisfy `Person: CanGreet` or `Person: Greeter` +... +50 | Person { age: 0 }.greet(); | ^^^^^ this is an associated function, not a method ``` -It names the traits it could not satisfy and stops. `HasName` and the missing field appear nowhere. The -"this is an associated function, not a method" line is an artifact of how a provider trait is generated -— the suggestion to write `Person::greet()` is wrong, and it is noise rather than a clue. +It names the traits it could not satisfy and stops. `HasName` and the missing field appear nowhere. +The "this is an associated function, not a method" line is an artifact of how a provider trait is +generated. The suggestion to write `Person::greet()` is wrong, and it is noise rather than a clue. A +recent nightly compiler adds a note naming the missing `HasField` bound, though still not the chain +that leads to it. The suppression is a [long-standing compiler limitation](https://github.com/rust-lang/rust/issues/61661) rather than a CGP quirk: with a blanket impl among the candidates, rustc declines to expand which @@ -163,7 +170,7 @@ rather than a CGP quirk: with a blanket impl among the candidates, rustc decline ### The fix -Give the context what the provider needs — add the `name` field, or wire the getter to a field that +Give the context what the provider needs: add the `name` field, or wire the getter to a field that exists. If you are looking at the hidden form, add a check at the wiring site first: ```rust @@ -176,24 +183,24 @@ check_components! { ### When the derive is missing entirely -A variant worth knowing, because the fix differs and the usual landmark disappears. If the struct *has* -the field but never derived [`HasField`](./derives/derive_has_field.md), it implements the accessor for -nothing at all — and the tool reports that as one cause rather than one per field: +A variant worth knowing, because the fix differs and the usual landmark disappears. If the struct +*has* the field but never derived [`HasField`](./derives/derive_has_field.md), it implements the +accessor for nothing at all, and the tool reports that as one cause rather than one per field: ```text = help: make sure that `#[derive(HasField)]` is used for `Person` = note: root cause: [CGP-E108] accessor trait `HasField` with field `name` is not implemented for `Person` ``` -In the raw output the tell is an absence. A genuinely missing field draws a "but trait -`HasField` is implemented for it" hint pointing at the nearest field; a missing derive -cannot, because no field is implemented. +In the raw output the tell is an absence. A missing field draws a "but trait +`HasField` is implemented for it" hint pointing at the nearest field; a missing +derive cannot, because the struct implements `HasField` for none of its fields. ### When the missing bound is an ordinary Rust trait -A provider's dependency may be a plain Rust trait rather than a CGP trait — `Scalar: Eq`, -`Item: Ord` — unmet by the type the context wired. Here the tool deliberately keeps rustc's own headline, -because it was already the clearest statement, and tidies only the frames beneath it: +A provider's dependency may be a plain Rust trait rather than a CGP trait (`Scalar: Eq`, +`Item: Ord`), unmet by the type the context wired. Here the tool deliberately keeps rustc's own +headline, because it was already the clearest statement, and tidies only the frames beneath it: ```text error[E0277]: the trait bound `f64: Eq` is not satisfied @@ -208,12 +215,12 @@ error[E0277]: the trait bound `f64: Eq` is not satisfied └─ the trait bound `f64: Eq` is not satisfied ``` -This is the one class here with no `[CGP-Exxx]` headline, and the absence is deliberate. +This is the one class here without a `[CGP-Exxx]` headline, and the absence is deliberate. -The fix is not to wire a component or add a field but to satisfy the trait: wire the abstract type to -something that implements it, implement it for a type you own, or relax the provider's bound if it asked -for more than it needed. One connective step is left to you — the message names `f64`, not the -`ScalarTypeProviderComponent: UseType` line that chose it. +The fix is not to wire a component or add a field but to satisfy the trait: wire the abstract type +to something that implements it, implement it for a type you own, or relax the provider's bound if +it asked for more than it needed. One connective step is left to you: the message names `f64`, not +the `ScalarTypeProviderComponent: UseType` line that chose it. ### When two decisions disagree about a type @@ -224,17 +231,16 @@ reports a projection mismatch rather than a missing impl: ```text error[E0271]: [CGP-E017] expected the abstract type `Scalar` of `HasScalarType` on `Rectangle` to be `f64`, but found `u32` | - = help: wire `ScalarTypeProviderComponent` to `UseType` in the wiring for `Rectangle`, or - change the provider to work with `u32` + = help: wire `ScalarTypeProviderComponent` to `UseType` in the wiring for `Rectangle`, or change the provider to work with `u32` ``` Both halves of the disagreement are named, and the `help:` names the wiring line to change. The raw -`E0271` is much worse: it states only what was *required*, never what the context supplied, and puts its -caret on the `#[cgp_type]` attribute that declared the type — nowhere near either decision. +`E0271` is much worse: it states only what was *required*, never what the context supplied, and puts +its caret on the `#[cgp_type]` attribute that declared the type, nowhere near either decision. The same shape appears one level down, when a *field's* type is expressed through an abstract type -(`#[implicit] database: &Pool`). The tool then gives the requirement in both forms — -`Pool<::Db>` followed by `(Pool)` — because the projection says where the +(`#[implicit] database: &Pool`). The tool then gives the requirement in both forms, +`Pool<::Db>` followed by `(Pool)`, because the projection says where the requirement came from and the reduced type is what you compare the field against. ### When the provider is a stack @@ -261,9 +267,9 @@ missing only from the wrapper fails on its line alone. ### When one mistake prints many errors -A dependency several components share, left unmet, fails at every one of them. Raw `cargo check` prints -one block per affected provider — three chained components over one missing field produce **six** — and -only some of them reach the cause. +A dependency several components share, left unmet, fails at every one of them. Raw `cargo check` +prints one block per affected provider (three chained components over one missing field produce +**six**), and only some of them reach the cause. The tool collapses the whole cascade into one block naming every affected consumer over a single tree: @@ -283,14 +289,15 @@ error[E0277]: [CGP-E001] the consumer traits `CanBaz`, `CanBar`, and `CanFoo` ar Fix the one cause and all of it disappears together. On the raw output the rule for finding that cause is structural rather than positional: **look for a -block whose `help:` names a concrete missing item** — a field, a type — rather than another provider -trait. Blocks naming `SomeProvider: SomeTrait` are consequences. Two habits help besides: check one -suspect component in its own `check_components!` block, or comment entries out until the failure moves. +block whose `help:` names a concrete missing item**, such as a field or a type, rather than another +provider trait. Blocks naming `SomeProvider: SomeTrait` are consequences. Two habits help +besides: check one suspect component in its own `check_components!` block, or comment entries out +until the failure moves. ## Nothing is wired there -A neighbouring failure that reads like a dependency problem but is not: no provider is found *at all*, -rather than one being found whose requirements fail. +A neighbouring failure that reads like a dependency problem but is not: the lookup does not find a +provider *at all*, rather than one being found whose requirements fail. The common case is a component registered into a [namespace](./macros/cgp_namespace.md) under a path that nothing ever binds: a [`#[prefix]`](./attributes/prefix.md) routes the lookup somewhere, and no @@ -304,29 +311,29 @@ nothing ever binds: a [`#[prefix]`](./attributes/prefix.md) routes the lookup so └─ [CGP-E107] context `App` does not contain any delegate entry for `@app.GreeterComponent` ``` -The same `[CGP-E107]` leaf covers a component the context simply never wired. The path is resugared to -its `@app.GreeterComponent` form, which is the largest readability win here — raw `rustc` prints it as a +The same `[CGP-E107]` leaf covers a component the context never wired. The path is resugared to its +`@app.GreeterComponent` form, which is the largest readability win here. Raw `rustc` prints it as a `PathCons>, _>` list. -In the raw output this class is unusual in that the cause **is** the primary error rather than a note -below it: an `E0277` saying a `PathCons<…>` path does not implement the namespace trait. A `Self` that is -a path or a `RedirectLookup` rather than a provider struct always means the lookup failed, not a -provider's dependencies. One landmark reads like a contradiction and is in fact the diagnosis — a `help:` -listing the component *markers* the namespace does resolve, yours among them, tells you the registration -worked and only the leaf binding is missing. +In the raw output this class is unusual in that the cause **is** the primary error rather than a +note below it: an `E0277` saying a `PathCons<…>` path does not implement the namespace trait. A +`Self` that is a path or a `RedirectLookup` rather than a provider struct always means the lookup +failed, not a provider's dependencies. One landmark reads like a contradiction and is in fact the +diagnosis: a `help:` listing the component *markers* the namespace does resolve, yours among them, +tells you the registration worked and only the leaf binding is missing. Reached by a method call instead of a check, this hides exactly as any other dependency does. -**The fix** is to bind a provider at the path: a `#[default_impl(@app.GreeterComponent in Namespace)]` on -the provider, a namespace body entry, or a direct line on the context — whichever matches where the -wiring belongs. When the path itself is wrong, reconcile the prefix and the binding so they name the same -one. +**The fix** is to bind a provider at the path: a +`#[default_impl(@app.GreeterComponent in Namespace)]` on the provider, a namespace body entry, or a +direct line on the context, whichever matches where the wiring belongs. When the path itself is +wrong, reconcile the prefix and the binding so they name the same one. ## The wiring itself does not compile -These are structural failures. The compiler reports a definite code and points at both offending lines, -so there is no cause to hunt for — the difficulty is only mapping the message back to the wiring -decision. +These are structural failures. The compiler reports a definite code and points at both offending +lines, so the cause does not need hunting for. The difficulty is only mapping the message back to +the wiring decision. ### Two entries claim one key @@ -344,22 +351,24 @@ error[E0119]: [CGP-E004] duplicate wiring for component `GreeterComponent` on `P | ^^^^^^^^^^^^^^^^ conflicting implementation for `Person` ``` -Two carets, two lines to reconcile. Related codes cover the neighbouring shapes: `[CGP-E007]` for an -`open` header colliding with an explicit entry, `[CGP-E008]` for the same key redirected twice. +Two carets, two lines to reconcile. Related codes cover the neighbouring shapes: `[CGP-E005]` for a +path key that covers a longer one, `[CGP-E007]` for an `open` header colliding with an explicit +entry, and `[CGP-E008]` for the same key redirected twice. -Two things are worth knowing when reading the raw form. A context-wiring entry generates *two* impls, so -one duplicate prints a **pair** of `E0119`s — one conflict, not two. And a blanket-versus-specific -collision often carries a "downstream crates may implement …" note: that is the compiler explaining that -[coherence](/docs/reference/glossary#coherence) must allow for impls a future crate could add, not a second problem. +Two things are worth knowing when reading the raw form. A context-wiring entry generates *two* +impls, so one duplicate prints a **pair** of `E0119`s, which is one conflict, not two. And a +blanket-versus-specific collision often carries a "downstream crates may implement …" note: that is +the compiler explaining that [coherence](/docs/reference/glossary#coherence) must allow for impls a +future crate could add, not a second problem. -A duplicate **name** rather than a duplicate key is an `E0428` instead, and passes through uncoded — it -already points precisely at both definitions. +A duplicate **name** rather than a duplicate key is an `E0428` instead, and passes through uncoded, +because it already points precisely at both definitions. ### Joining more than one namespace -A context can forward through exactly one namespace. Two `namespace` headers — or one header plus a `for` -loop whose key is bare rather than embedded in a path — each produce a blanket impl covering every key, -and the two overlap: +A context can forward through exactly one namespace. Two `namespace` headers (or one header plus a +`for` loop whose key is bare rather than embedded in a path) each produce a blanket impl covering +every key, and the two overlap: ```text error[E0119]: [CGP-E006] only one namespace can be used for each target type in `delegate_components!`, but `App` uses both `NamespaceA` and `NamespaceB` @@ -391,10 +400,24 @@ error[E0119]: [CGP-E005] `App` cannot wire `@app.GreeterComponent.*` that is alr **The fix** follows one rule: *a bound namespace entry cannot be overridden.* Leave the leaf path unclaimed in the namespace so the context can supply it, or change the binding in the namespace itself. -The same mistake one level up — a child namespace redefining a key it inherits — produces a bare -`conflicting implementations of trait ChildNs<_> for type GreeterComponent`, which the tool does not yet -rewrite. The tell is that the conflicting *self type* is a [component marker](/docs/reference/glossary#component-marker) rather than a context. The -fix there is to leave the key unbound in the base so each child can bind it. +The same mistake one level up, a child namespace redefining a key it inherits, is rewritten the same +way: + +```text +error[E0119]: [CGP-E005] `ChildNs` cannot wire component `GreeterComponent` that is already set through `BaseNs` +``` + +In the raw form, ``conflicting implementations of trait `ChildNs<_>` for type `GreeterComponent` ``, +the tell is that the conflicting *self type* is a [component +marker](/docs/reference/glossary#component-marker) rather than a context. The fix there is to leave +the key unbound in the base so each child can bind it. When the parent *redirects* the key rather +than binding it, as it does for a component carrying [`#[prefix]`](./attributes/prefix.md), the key +was written in the wrong form rather than overridden, and the tool says so with a different code: + +```text +error[E0119]: [CGP-E007] component `GreeterComponent` on `AppNamespace` is redirected to `@app.GreeterComponent` + = help: wire the provider `GreetHello` with the key `@app.GreeterComponent` +``` ### Registering into a namespace you do not own @@ -407,14 +430,13 @@ error[E0210]: [CGP-E011] cannot register the foreign path `@app.AnnouncerCompone 26 | #[cgp_impl(new AnnounceQuietly)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = help: own one end of the wiring: key it on a component defined in this crate, or register it - from the crate that defines `AppNamespace` + = help: own one end of the wiring: key it on a component defined in this crate, or register it from the crate that defines `AppNamespace` ``` -**The fix** is in the `help:`: own one end. Key the registration on a local component, register it from -the namespace's own crate, or — to extend a foreign namespace — define a new local namespace that -*inherits* it rather than re-opening it, which is orphan-safe because every emitted impl is then for your -own trait. +**The fix** is in the `help:`: own one end. Key the registration on a local component, or register +it from the namespace's own crate. To extend a foreign namespace, define a new local namespace that +*inherits* it rather than re-opening it, which is orphan-safe because every emitted impl is then for +your own trait. ### A lookup that never terminates @@ -424,25 +446,25 @@ component *is* that wiring makes the lookup chase its own tail: ```text error[E0275]: [CGP-E010] the wiring for the consumer trait `CanGreet` on context `Person` never resolves — the lookup recurses without terminating | - = help: a lookup that recurses usually means the component is delegated back to the context itself — - e.g. wired to `UseContext` with no direct implementation of the consumer trait — so wire a - real provider, or implement the consumer trait directly on the context + = help: a lookup that recurses usually means the component is delegated back to the context itself — e.g. wired to `UseContext` with no direct implementation of the consumer trait — so wire a real provider, or implement the consumer trait directly on the context ``` Raw `rustc` gives an `E0275` overflow with a note chain you can read the loop out of, plus a stock -"consider increasing the recursion limit" suggestion. **Ignore that suggestion**: a true cycle does not -terminate at any depth, so no limit is high enough. +"consider increasing the recursion limit" suggestion. **Ignore that suggestion**: a true cycle does +not terminate at any depth, so raising the limit cannot help. -Reached by a method call rather than a check, a cycle does not overflow at all — it hides as the ordinary -`E0599`, with nothing to say a cycle was the reason. +Reached by a method call rather than a check, a cycle does not overflow at all. It hides as the +ordinary `E0599`, and nothing in it says a cycle was the reason. **A related cycle sits at namespace definitions rather than at a use site.** Namespaces whose parent -chain loops (`A: B` with `B: A`, or `A: A`) fail *eagerly*, with an `E0275` on each `cgp_namespace!` -block, because the cycle lives in the `where` clause of a generated impl the compiler checks on sight. -Two things are unusual about it. Under `cargo cgp check`'s next-generation solver the code **compiles -clean** and nothing is reported — the one class where the tool shows you *less* than plain `cargo check`. -And the wiring is wrong regardless: break the loop so the parent chain forms a tree, factoring shared -entries into a third base namespace both inherit from. +chain loops (`A: B` with `B: A`) fail *eagerly*, with an `E0275` on each `cgp_namespace!` block, +because the cycle lives in the `where` clause of a generated impl the compiler checks on sight. A +namespace that inherits itself (`A: A`) fails differently, with an `E0207` saying the impl's value +parameter is not constrained. Two things are unusual about the mutual cycle. Under +`cargo cgp check`'s next-generation solver the code **compiles clean** and nothing is reported, the +one class where the tool shows you *less* than plain `cargo check`. And the wiring is wrong +regardless: break the loop so the parent chain forms a tree, factoring shared entries into a third +base namespace both inherit from. ### A generic that reaches nothing @@ -456,10 +478,10 @@ error[E0207]: the type parameter `T` is not constrained by the impl trait, self | ^ unconstrained type parameter ``` -This passes through unrewritten, and it does not need much — the caret is on the parameter. The message -speaks in impl terms, though, where the actionable reading is a wiring one: **the generic has to appear -in the key** (` SomeKey: …`), not only in the value. Expect the same error twice, once per -generated position; both name the same ``. +This passes through unrewritten, and it does not need much: the caret is on the parameter. The +message speaks in impl terms, though, where the actionable reading is a wiring one: **the generic +has to appear in the key** (` SomeKey: …`), not only in the value. Expect the same error +twice, once per generated position; both name the same ``. ## A macro lowered something the compiler rejects @@ -482,8 +504,8 @@ error[E0576]: cannot find associated type `Scalr` in trait `HasScalarType` | ^^^^^ ``` -The caret lands on the name *you* wrote — the macro copies the identifier's span onto the rewritten path -— and the `help:` usually supplies the spelling. Nothing to decode. +The caret lands on the name *you* wrote, because the macro copies the identifier's span onto the +rewritten path, and the `help:` usually supplies the spelling. Nothing needs decoding. ### A name the generated code cannot see @@ -498,14 +520,14 @@ error[E0433]: cannot find type `Db` in this scope | ^^ use of undeclared type `Db` ``` -The `&Pool` argument is fine — that one is stripped into a field bound on the impl, where `Db` *is* in -scope. The `Db::Row` return type is not. **The fix** is a choice the macro cannot make for you: promote -the type to an [abstract type](./macros/cgp_type.md) so it can be named everywhere, or keep -`#[impl_generics]` and stop naming it. A bare unresolved name with no path context reports as `E0425` -instead, so grep for both. +The `&Pool` argument is fine, because it is stripped into a field bound on the impl, where `Db` +*is* in scope. The `Db::Row` return type is not. **The fix** is a choice the macro cannot make for +you: promote the type to an [abstract type](./macros/cgp_type.md) so it can be named everywhere, or +keep `#[impl_generics]` and stop naming it. A bare unresolved name without path context reports as +`E0425` instead, so grep for both. -A sibling has the opposite cause — the name resolves, to the wrong thing. Naming an abstract type after -the trait that bounds it makes the bound resolve to the type being declared: +A sibling has the opposite cause: the name resolves, but to the wrong thing. Naming an abstract type +after the trait that bounds it makes the bound resolve to the type being declared: ```text error[E0404]: expected trait, found type parameter `Database` @@ -517,15 +539,30 @@ error[E0404]: expected trait, found type parameter `Database` | -------- ^^^^^^^^ not a trait ``` -Both halves are named, so the message explains itself once read. Name them apart — `Db` reads better for -an abstract database type anyway. +Both halves are named, so the message explains itself once read. Name them apart: `Db` reads better +for an abstract database type anyway. + +A third sibling is a defect in the library rather than a mistake of yours. The extensible-data +derives name their own associated types as `Self::Value`, `Self::Remainder`, `Self::Fields`, and so +on, so an enum with a variant of one of those names makes the path ambiguous. The error does not +carry a code: + +```text +error: ambiguous associated item +``` + +and its notes say the name "could refer to the variant defined here" or "could also refer to the +associated type defined here". Under [`#[derive(ExtractField)]`](./derives/derive_extract_field.md) +both notes point at the derive attribute, so nothing names the variant to rename. The seven reserved +names are listed on that page and on [`#[derive(HasFields)]`](./derives/derive_has_fields.md) and +[`#[derive(FromVariant)]`](./derives/derive_from_variant.md). Rename the variant. -### A field-type shorthand with no rule +### A field-type shorthand without a rule -The getter and implicit-argument macros recognize a small set of field-type shorthands — `Option<&T>`, -`&[T]`, `&str`. A *combination* they have no rule for is lowered by whichever rule matches first, and the -result can be a type that is not well-formed. `Option<&[u8]>` lowers to a bound naming the unsized -`Option<[u8]>`: +The getter and implicit-argument macros recognize a small set of field-type shorthands: +`Option<&T>`, `&[T]`, and `&str`. A *combination* they lack a rule for is lowered by whichever rule +matches first, and the result can be a type that is not well-formed. `Option<&[u8]>` lowers to a +bound naming the unsized `Option<[u8]>`: ```text error[E0277]: the size for values of type `[u8]` cannot be known at compilation time @@ -537,9 +574,9 @@ error[E0277]: the size for values of type `[u8]` cannot be known at compilation note: required by an implicit `Sized` bound in `Option` ``` -Two things make this harder to read than it looks. The caret is on the macro attribute rather than on any -type you wrote, because the offending type is synthesized. And a second `E0599` on `as_ref` usually -follows — derived noise from the same unsized type, pointing at nothing new. +Two things make this harder to read than it looks. The caret is on the macro attribute rather than +on any type you wrote, because the offending type is synthesized. And a second `E0599` on `as_ref` +usually follows, which is derived noise from the same unsized type and points at nothing new. **The fix** is a shape a single shorthand supports: `Option>`, or `Option<&'static [u8]>`, or a hand-written getter naming whatever type the field actually has. The shorthands compose only where the @@ -593,9 +630,10 @@ error[E0107]: [CGP-E013] `CanCalculateArea` is a consumer trait, but a `#[cgp_im ``` Untranslated, this one mistake produces a burst of `E0425`/`E0107`/`E0186`/`E0207` errors plus a -downstream check failure, none of which names the cause. Two neighbours share the shape: `[CGP-E015]` is -the same confusion in a `#[use_provider]` bound, and `[CGP-E014]` is `#[cgp_impl]` applied to a trait that -is not a component at all — where the fix is to make it one, or to write a plain `impl`. +downstream check failure, none of which names the cause. Two neighbours share the shape: +`[CGP-E015]` is the same confusion in a `#[use_provider]` bound, and `[CGP-E014]` is `#[cgp_impl]` +applied to a trait that is not a component at all, where the fix is to make it one, or to write a +plain `impl`. ## The `[CGP-Exxx]` codes @@ -612,12 +650,12 @@ code in the **root-cause tree** labels one link in the chain. | `CGP-E001` | A context does not implement a consumer trait | | `CGP-E002` | A provider does not implement its provider trait for the context | | `CGP-E003` | A field is present but has the wrong type | -| `CGP-E004` | The same key wired twice | -| `CGP-E005` | Wiring a key a namespace already binds | +| `CGP-E004` | The same key wired twice, or a generic table overlapping a specific one | +| `CGP-E005` | Wiring a key that a shorter path key or a namespace entry already covers | | `CGP-E006` | More than one namespace joined on one context | -| `CGP-E007` | An `open` redirect colliding with an explicit entry | +| `CGP-E007` | A direct entry colliding with a redirect of the same key, such as an `open` header | | `CGP-E008` | The same key redirected twice | -| `CGP-E009` | A non-component trait — a wrapper, or a `#[cgp_fn]` blanket trait — blocked by a CGP dependency | +| `CGP-E009` | A non-component trait (a wrapper, or a `#[cgp_fn]` blanket trait) blocked by a CGP dependency | | `CGP-E010` | The wiring recurses without terminating | | `CGP-E011` | An orphan-rule namespace registration | | `CGP-E012` | A trait used but not declared with `#[uses]` | @@ -635,7 +673,7 @@ code in the **root-cause tree** labels one link in the chain. | `CGP-E102` | A hop through a provider's provider-trait impl | | `CGP-E104` | A hop through a namespace or `open` redirect | | `CGP-E105` | A hop through any other trait | -| `CGP-E106` | **Leaf:** a field is genuinely absent | +| `CGP-E106` | **Leaf:** a field is absent | | `CGP-E107` | **Leaf:** the context wires nothing for a component or path | | `CGP-E108` | **Leaf:** the field exists but `#[derive(HasField)]` is missing | | `CGP-E109` | **Leaf:** the field has the wrong type | @@ -645,7 +683,7 @@ code in the **root-cause tree** labels one link in the chain. | `CGP-E201` | The root-cause lead for an ordinary Rust trait bound | A tree entry that merely passes a non-CGP message through in rustc's own words is left uncoded. -`CGP-E103` was retired rather than reassigned, so the rest stay stable. +`CGP-E103` is unassigned, so the numbering has a gap there. ## Related constructs diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index a9659566..a9762e36 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -11,8 +11,8 @@ Short definitions of the words used across this documentation, each pointing at explains the idea properly. It is a place to look a term up, not a place to learn CGP: every entry is a sentence or two and a link onward. -If you arrived knowing the name of a *construct* rather than a word — `IsPresent`, -`#[cgp_new_provider]` — the [reference index](./index.md) is the page that routes those. +If you arrived knowing the name of a *construct* rather than a word, such as `IsPresent` or +`#[cgp_new_provider]`, the [reference index](./index.md) is the page that routes those. ## CGP terms @@ -70,7 +70,7 @@ associated types, and consts, exactly as an ordinary trait may. ### component marker The zero-sized type naming a component in a wiring table, such as `GreeterComponent`. It is the key -the table looks a provider up by, and it carries no behavior of its own. +the table looks a provider up by, and it does not carry behavior of its own. [`#[cgp_component]`](./macros/cgp_component.md) · [`DelegateComponent`](./traits/wiring/delegate_component.md) @@ -101,8 +101,7 @@ a concrete type, so a context selects among them at compile time. ### delegation An entry in a wiring table, mapping one component to the provider that supplies it. Delegating a -component does not by itself check that the provider's dependencies hold — that is what a check trait -is for. +component does not by itself check that the provider's dependencies hold; a check trait does that. [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · [`DelegateComponent`](./traits/wiring/delegate_component.md) @@ -126,7 +125,7 @@ way. ### expansion -The ordinary Rust a CGP macro generates — the traits, impls, and marker types behind a construct, +The ordinary Rust a CGP macro generates: the traits, impls, and marker types behind a construct, also called what a construct desugars to. `cargo cgp expand` prints it with CGP's type-level constructs restored to readable macro notation. @@ -152,7 +151,7 @@ or matched variant by variant without naming its concrete type. ### getter trait A trait declaring a named accessor for a value the context holds, used where an implicit argument -cannot reach — a field on another type, an accessor other code requires by name, or a return type +cannot reach: a field on another type, an accessor other code requires by name, or a return type inferred from the field. [Implicit arguments](/docs/concepts/implicit-arguments) · @@ -191,7 +190,7 @@ on the context. It is the default way to read a context field. ### marker type -A zero-sized type carrying no data, used as a name the compiler can resolve rather than as a value. +A zero-sized type without data, used as a name the compiler can resolve rather than as a value. Providers and component markers are both marker types, and neither is ever instantiated. [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · @@ -246,7 +245,7 @@ In `CanCompute`, `Code` is the selector and `Input` is the target. ### self-targeted component A component whose operation acts on, or describes, the context itself, as in `CanGreet` or -`HasErrorType`. Most components are self-targeted. +`HasErrorType`. Getters are self-targeted too. [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) @@ -275,7 +274,8 @@ both the target and the context, so it has one implementation of that component ### wiring The type-level table on a context recording which provider supplies each component. The compiler -resolves it during type checking, so a wired call compiles to a direct call with no runtime lookup. +resolves it during type checking, so a wired call compiles to a direct call without a runtime +lookup. [Consumer and provider traits](/docs/concepts/consumer-and-provider-traits) · [`delegate_components!`](./macros/delegate_components.md) @@ -297,7 +297,9 @@ than the caller. An implementation written for every type satisfying a set of bounds, such as `impl Foo for T`, rather than for one named type. CGP's generated code rests on these. -[Rust Reference: Implementations](https://doc.rust-lang.org/reference/items/implementations.html) +[Blanket implementations in +Rust](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) · [Rust Reference: +Implementations](https://doc.rust-lang.org/reference/items/implementations.html) ### coherence @@ -357,16 +359,16 @@ and derives are built. ### static dispatch -Resolving a call at compile time to a direct call to a known function, with no runtime lookup. CGP +Resolving a call at compile time to a direct call to a known function, without a runtime lookup. CGP wiring resolves this way. [Rust Book: Generic data types](https://doc.rust-lang.org/book/ch10-01-syntax.html) ### supertrait -A trait required by another trait, so implementing the second means the first is available too. CGP -adds one with `#[extend]` rather than native `:` syntax, which keeps the generated trait's bounds -together. +A trait required by another trait, so implementing the second means the first is available too. In +CGP, `#[extend]` adds one to a generated trait, and it is the only way to give a `#[cgp_fn]` trait a +supertrait. [Rust Reference: Traits](https://doc.rust-lang.org/reference/items/traits.html) · [`#[extend]`](./attributes/extend.md) @@ -513,7 +515,7 @@ arguments, so behavior is composed at compile time. ### reflection -Inspecting a type's structure — its fields, variants, and names — from within the program. CGP's +Inspecting a type's structure (its fields, variants, and names) from within the program. CGP's equivalent is encoded in types and resolved at compile time rather than read from runtime metadata. [Comparison: Reflection](/docs/comparisons/reflection) · @@ -537,7 +539,7 @@ apply to records that differ in the fields it does not mention. ### signature and structure -In ML, a signature is the interface a module satisfies, and a structure is a module satisfying it — +In ML, a signature is the interface a module satisfies, and a structure is a module satisfying it: roughly a type and its implementation, related by ascription rather than by declaration. [Comparison: ML modules](/docs/comparisons/ml-modules) · @@ -567,12 +569,12 @@ An interface a type can be declared to satisfy after the fact, with the compiler implementation from the types at a call site. [Comparison: Type classes](/docs/comparisons/type-classes) · -[Type class](https://en.wikipedia.org/wiki/Type_class) +[How to make ad-hoc polymorphism less ad hoc](https://dl.acm.org/doi/10.1145/75277.75283) ### vtable -The table of function pointers behind a dynamically dispatched call, consulted at run time to find the -implementation. CGP wiring has no runtime counterpart to it. +The table of function pointers behind a dynamically dispatched call, consulted at run time to find +the implementation. CGP wiring does not use one, because it resolves every call at compile time. [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch) · [Virtual method table](https://en.wikipedia.org/wiki/Virtual_method_table) diff --git a/docs/reference/index.md b/docs/reference/index.md index 276decbd..a8c9a43e 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -1,6 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The complete reference for every CGP construct, grouped by the job it does, with the handful a newcomer needs first and a lookup table for names without a page.' --- # Reference @@ -30,25 +31,26 @@ these. | [`#[implicit]`](./attributes/implicit.md) | Reads a value out of the context as if it were a function argument | The first four are the full component cycle: define, implement, wire, verify. The last two are how -most code avoids needing that cycle at all — reach for them first, and climb to a full component when -a trait genuinely needs a second implementation. +most code avoids needing that cycle at all. Reach for them first, and climb to a full component when +a trait needs a second implementation. ## By what you are trying to do -The rest of the reference is grouped by the job a construct does rather than by what kind of thing it -is. If you know which *file* you want rather than which job, the sidebar groups the same pages by kind -— macros, attributes, derives, and so on. +The rest of the reference is grouped by the job a construct does rather than by what kind of thing +it is. If you know which *file* you want rather than which job, the sidebar groups the same pages by +kind: macros, attributes, derives, and so on. ### Define a trait, and implement it -[`#[cgp_component]`](./macros/cgp_component.md) is the foundational macro, turning one trait into the -consumer trait callers use and the provider trait implementations target. A provider is then written -with [`#[cgp_impl]`](./macros/cgp_impl.md), which keeps `self` and the consumer method signatures; -[`#[cgp_provider]`](./macros/cgp_provider.md) is the lower-level form underneath it, which you will -read in generated code more often than you write. When a trait needs only one implementation and -no wiring at all, [`#[cgp_fn]`](./macros/cgp_fn.md) builds it straight from a function, and -[`#[blanket_trait]`](./macros/blanket_trait.md) does the same from a trait with default methods. -[`#[async_trait]`](./macros/async_trait.md) is how a CGP trait declares an `async fn`. +[`#[cgp_component]`](./macros/cgp_component.md) is the foundational macro, turning one trait into +the consumer trait callers use and the provider trait implementations target. A provider is then +written with [`#[cgp_impl]`](./macros/cgp_impl.md), which keeps `self` and the consumer method +signatures; [`#[cgp_provider]`](./macros/cgp_provider.md) is the lower-level form underneath it, +which you will read in generated code more often than you write. When a trait needs only one +implementation and does not need wiring, [`#[cgp_fn]`](./macros/cgp_fn.md) builds it straight from a +function, and [`#[blanket_trait]`](./macros/blanket_trait.md) does the same from a trait with +default methods. [`#[async_trait]`](./macros/async_trait.md) is how a CGP trait declares an +`async fn`. ### Wire a type to the implementations it uses @@ -64,16 +66,17 @@ the table is made of. ### Read values out of the context -An [`#[implicit]`](./attributes/implicit.md) argument is the default way to read a field: it looks like -an ordinary function parameter and is filled from a same-named field on the context. The field access -itself comes from [`#[derive(HasField)]`](./derives/derive_has_field.md) and the +An [`#[implicit]`](./attributes/implicit.md) argument is the default way to read a field: it looks +like an ordinary function parameter and is filled from a same-named field on the context. The field +access itself comes from [`#[derive(HasField)]`](./derives/derive_has_field.md) and the [`HasField`](./traits/field-access/has_field.md) trait, whose mutable form is -[`HasFieldMut`](./traits/field-access/has_field_mut.md). Four further traits are the machinery underneath, generated -rather than written: [`FieldGetter`](./traits/field-access/field_getter.md) and -[`MutFieldGetter`](./traits/field-access/mut_field_getter.md) are the provider-side mirrors a getter component is -wired through, and [`MapField`](./traits/field-access/map_field.md) with -[`FieldMapper`](./traits/field-access/field_mapper.md) are what let a getter reach into a nested value without -forcing its type to be `'static`. +[`HasFieldMut`](./traits/field-access/has_field_mut.md). Four further traits sit underneath. +[`FieldGetter`](./traits/field-access/field_getter.md) and +[`MutFieldGetter`](./traits/field-access/mut_field_getter.md) are the provider-side forms of field +access, which a getter component is wired through, and +[`MapField`](./traits/field-access/map_field.md) with its provider-side mirror +[`FieldMapper`](./traits/field-access/field_mapper.md) reads through a field of a generic context, +where a chained `get_field` would need a lifetime bound on the field's type. Getter traits are the sparing alternative, for the cases an implicit argument cannot reach. [`#[cgp_auto_getter]`](./macros/cgp_auto_getter.md) generates one from the method name; @@ -84,20 +87,20 @@ chosen by wiring, through [`UseField` and its siblings](./providers/use_field.md ### Declare what an implementation needs -These attributes state what an implementation needs, and they divide by whether the requirement stays -private to it. [`#[uses]`](./attributes/uses.md) imports the traits the body depends on and -[`#[use_provider]`](./attributes/use_provider.md) does the same for an inner provider in a higher-order -provider — both landing on the implementation alone, so a caller never sees them. Where a requirement -should instead be part of what the trait promises, [`#[extend]`](./attributes/extend.md) adds it as a -supertrait and [`#[extend_where]`](./attributes/extend_where.md) as a predicate on the generated trait -itself. When the body needs a type that a field of the context fixes, -[`#[impl_generics]`](./attributes/impl_generics.md) declares the parameter on the implementation alone, -so callers never name it. +These attributes state what an implementation needs, and they divide by whether the requirement +stays private to it. [`#[uses]`](./attributes/uses.md) imports the traits the body depends on and +[`#[use_provider]`](./attributes/use_provider.md) does the same for an inner provider in a +higher-order provider. Both land on the implementation alone, so a caller never sees them. Where a +requirement should instead be part of what the trait promises, [`#[extend]`](./attributes/extend.md) +adds it as a supertrait and [`#[extend_where]`](./attributes/extend_where.md) as a predicate on the +generated trait itself. When the body needs a type that a field of the context fixes, +[`#[impl_generics]`](./attributes/impl_generics.md) declares the parameter on the implementation +alone, so callers never name it. ### Let each context choose a type -[`#[cgp_type]`](./macros/cgp_type.md) defines an abstract-type component — an error type, a runtime, -a scalar — that each context fills in by wiring the component to +[`#[cgp_type]`](./macros/cgp_type.md) defines an abstract-type component, such as an error type, a +runtime, or a scalar, that each context fills in by wiring the component to [`UseType`](./providers/use_type.md), or to [`UseDelegatedType`](./providers/use_delegated_type.md) to resolve it through a table. Generic code names such a type by importing it with [`#[use_type]`](./attributes/use_type.md), which is a @@ -110,37 +113,37 @@ stand in as a named component's. [`HasErrorType`](./components/has_error_type.md) gives a context one shared error type, [`CanRaiseError`](./components/can_raise_error.md) constructs it from a source error, and -[`CanWrapError`](./components/can_wrap_error.md) attaches detail to it. The interchangeable strategies -that satisfy them — `RaiseFrom`, `ReturnError`, `DebugError`, and the rest — are the -[error providers](./providers/error/index.md). +[`CanWrapError`](./components/can_wrap_error.md) attaches detail to it. The interchangeable +strategies that satisfy them, such as `RaiseFrom`, `ReturnError`, and `DebugError`, are the [error +providers](./providers/error/index.md). ### Compute things -The [handler family](./components/handler/index.md) models computation along three axes: synchronous or -async, fallible or not, taking an input or not. [`Computer`](./components/handler/computer.md) is the -plain synchronous transform, [`TryComputer`](./components/handler/try_computer.md) adds fallibility, -[`Handler`](./components/handler/handler.md) is the general async and fallible case, and -[`Producer`](./components/handler/producer.md) is the input-free one. +The [handler family](./components/handler/index.md) models computation along three axes: synchronous +or async, fallible or not, taking an input or not. [`Computer`](./components/handler/computer.md) is +the plain synchronous transform, [`TryComputer`](./components/handler/try_computer.md) adds +fallibility, [`Handler`](./components/handler/handler.md) is the general async and fallible case, +and [`Producer`](./components/handler/producer.md) is the input-free one. [`CanRun`](./components/runner.md) runs tasks, [`CanSendRun`](./components/send_runner.md) is its `Send`-future variant, and [`HasRuntime`](./components/has_runtime.md) with -[`HasRuntimeType`](./components/has_runtime_type.md) supplies the runtime they run on. Each of the three -computers and the handler also has by-reference and, where it applies, async siblings — +[`HasRuntimeType`](./components/has_runtime_type.md) supplies the runtime they run on. `Computer`, +`TryComputer`, and `Handler` also have by-reference siblings, and `Computer` has async ones: [`ComputerRef`](./components/handler/computer_ref.md), -[`AsyncComputer`](./components/handler/async_computer.md), -[`AsyncComputerRef`](./components/handler/async_computer_ref.md), -[`TryComputerRef`](./components/handler/try_computer_ref.md), and -[`HandlerRef`](./components/handler/handler_ref.md) — each a component with its own page under the -[handler family](./components/handler/index.md). +[`TryComputerRef`](./components/handler/try_computer_ref.md), +[`HandlerRef`](./components/handler/handler_ref.md), +[`AsyncComputer`](./components/handler/async_computer.md), and +[`AsyncComputerRef`](./components/handler/async_computer_ref.md). Each is a component with its own +page under the [handler family](./components/handler/index.md). Providers in this family are written from plain functions with [`#[cgp_computer]`](./macros/cgp_computer.md) and [`#[cgp_producer]`](./macros/cgp_producer.md), and -composed with the [handler combinators](./providers/handler/index.md), the -[dispatch combinators](./providers/dispatch/index.md), and the -[monad providers](./providers/monad/index.md) built on the monad traits — -[`MonadicBind`](./traits/monad/monadic_bind.md), [`ContainsValue`](./traits/monad/contains_value.md), -[`LiftValue`](./traits/monad/lift_value.md), and [`MonadicTrans`](./traits/monad/monadic_trans.md). -[`#[cgp_auto_dispatch]`](./macros/cgp_auto_dispatch.md) generates a dispatching handler from a per-type -trait. +composed with the [handler combinators](./providers/handler/index.md), the [dispatch +combinators](./providers/dispatch/index.md), and the [monad providers](./providers/monad/index.md) +built on the monad traits: [`MonadicBind`](./traits/monad/monadic_bind.md), +[`ContainsValue`](./traits/monad/contains_value.md), [`LiftValue`](./traits/monad/lift_value.md), +and [`MonadicTrans`](./traits/monad/monadic_trans.md). +[`#[cgp_auto_dispatch]`](./macros/cgp_auto_dispatch.md) generates a dispatching handler from a +per-type trait. ### Work with a type's structure @@ -187,36 +190,37 @@ the whole set, so that a name met in an expansion or an error message can be loo [`cgp_namespace!`](./macros/cgp_namespace.md) defines a reusable, inheritable wiring table that many contexts can join, which is how top-level wiring stays short as component counts grow. It works through [`RedirectLookup`](./providers/redirect_lookup.md), which re-routes a lookup along a -[`Path!`](./macros/path.md), together with the three lookup traits that resolve inherited and per-type -defaults — [`DefaultNamespace`](./traits/namespace/default_namespace.md) for a key that is a component alone, and -[`DefaultImpls1`](./traits/namespace/default_impls1.md) and [`DefaultImpls2`](./traits/namespace/default_impls2.md) when the -key carries one further type or two. A component registers into a namespace under a path prefix with +[`Path!`](./macros/path.md), together with the three lookup traits that resolve inherited and +per-type defaults: [`DefaultNamespace`](./traits/namespace/default_namespace.md) for a key that is a +component alone, and [`DefaultImpls1`](./traits/namespace/default_impls1.md) and +[`DefaultImpls2`](./traits/namespace/default_impls2.md) when the key carries one further type or +two. A component registers into a namespace under a path prefix with [`#[prefix(...)]`](./attributes/prefix.md), and a provider registers itself as one of those defaults with [`#[default_impl(...)]`](./attributes/default_impl.md). The `open` statement of -[`delegate_components!`](./macros/delegate_components.md) is a -lightweight special case of the same mechanism, and it supersedes the older -[`UseDelegate`](./providers/use_delegate.md) tables and the +[`delegate_components!`](./macros/delegate_components.md) is a lightweight special case of the same +mechanism, and it supersedes the older [`UseDelegate`](./providers/use_delegate.md) tables and the [`#[derive_delegate]`](./attributes/derive_delegate.md) attribute that generates them. ### Understand a generated type or an error These are the type-level building blocks the rest of CGP is made of, and the place to look when a -generated type or an error names one you did not write. [`PhantomData`](./types/phantom_data.md) is the -one to start with: it is what lets a provider or a tag carry a type it stores no value of, and it -underlies most of the rest. You write the lists through sugar — [`Symbol!`](./macros/symbol.md) for a -field name, [`Product!`](./macros/product.md) for a record list, [`Sum!`](./macros/sum.md) for its dual, -[`Path!`](./macros/path.md) for a route — and only need to recognize the -[lists](./types/index.md) they expand into, [`Cons`](./types/cons.md) and -[`Nil`](./types/nil.md), [`Either`](./types/either.md) and -[`Void`](./types/void.md), [`Chars`](./types/chars.md), and -[`PathCons`](./types/path_cons.md), when one shows up in an error. Each entry in a record or a -variant is a [`Field`](./types/field.md), tagged by a [`Symbol!`](./macros/symbol.md) or an -[`Index`](./types/index_type.md), and [`Life`](./types/life.md) lifts a lifetime into a type where the -wiring needs one. [`MRef`](./types/mref.md) is the odd one out, a runtime value a getter returns rather -than a type-level marker. Three traits turn those encodings back into runtime data: -[`StaticString`](./traits/formatting/static_string.md) decodes a type-level string into a constant, -[`StaticFormat`](./traits/formatting/static_format.md) writes one into a formatter and is what makes it printable -at all, and [`ConcatPath`](./traits/formatting/concat_path.md) joins two paths. +generated type or an error names one you did not write. [`PhantomData`](./types/phantom_data.md) is +the one to start with: it is what lets a provider or a tag carry a type without storing a value of +it, and it underlies most of the rest. You write the lists through sugar, with +[`Symbol!`](./macros/symbol.md) for a field name, [`Product!`](./macros/product.md) for a record +list, [`Sum!`](./macros/sum.md) for its dual, and [`Path!`](./macros/path.md) for a route. You only +need to recognize the [lists](./types/index.md) they expand into, [`Cons`](./types/cons.md) and +[`Nil`](./types/nil.md), [`Either`](./types/either.md) and [`Void`](./types/void.md), +[`Chars`](./types/chars.md), and [`PathCons`](./types/path_cons.md), when one shows up in an error. +Each entry in a record or a variant is a [`Field`](./types/field.md), tagged by a +[`Symbol!`](./macros/symbol.md) or an [`Index`](./types/index_type.md), and +[`Life`](./types/life.md) lifts a lifetime into a type where the wiring needs one. +[`MRef`](./types/mref.md) is the odd one out, a runtime value a getter returns rather than a +type-level marker. Two traits turn a type-level string back into runtime data: +[`StaticString`](./traits/formatting/static_string.md) decodes it into a constant, and +[`StaticFormat`](./traits/formatting/static_format.md) writes it into a formatter, which is what +makes it printable. [`ConcatPath`](./traits/formatting/concat_path.md) joins two paths at the type +level. When wiring fails, three traits are what you will see named: [`DelegateComponent`](./traits/wiring/delegate_component.md), @@ -224,35 +228,44 @@ When wiring fails, three traits are what you will see named: name, and [`CanUseComponent`](./traits/wiring/can_use_component.md), which is what a check asserts. The [compile errors](./errors.md) page covers the recurring failures and how to read them. -If what you are missing is a *word* rather than a construct — environmental context, impl-side -dependency, type class — the [glossary](./glossary.md) defines the terms this documentation uses and -links to the page that explains each one. +If what you are missing is a *word* rather than a construct, such as environmental context, +impl-side dependency, or type class, the [glossary](./glossary.md) defines the terms this +documentation uses and links to the page that explains each one. ## Looking for a name you don't see? Almost every construct has a page of its own. The exceptions are names that are not separately *constructs*: a **marker** is a type implementing a trait, an **alias** is another spelling of a -construct, and a **variant** differs from a base construct by one axis. Each is documented on the page -of the thing it belongs to. If you arrived knowing one of these names, this is where it lives. +construct, and a **variant** differs from a base construct by one axis. A component's **consumer +trait** shares a page with its provider trait, and the **helper traits and generated types** a +construct uses are explained on its page. Each is documented on the page of the thing it belongs to. +If you arrived knowing one of these names, this is where it lives. | Looking for | It's on | |---|---| | `#[cgp_new_provider]` | [`#[cgp_provider]`](./macros/cgp_provider.md) | -| `WithType`, `WithField`, `WithContext` | [`WithProvider`](./providers/with_provider.md) | -| `Symbol` (the type, not the `Symbol!` macro) | [`Chars`](./types/chars.md) | +| `Symbol` (the type, not the `Symbol!` macro) | [`Symbol!`](./macros/symbol.md) and [`Chars`](./types/chars.md) | | `IdentMonadic`, `OkMonadic`, `ErrMonadic`, `OkMonadicTrans`, `ErrMonadicTrans` | [Monad providers](./providers/monad/index.md) | -| `UseDelegatedType`, `WithDelegatedType` | [`UseDelegatedType`](./providers/use_delegated_type.md) and [`WithProvider`](./providers/with_provider.md) | | `MatchWithHandlersRef`, `MatchWithHandlersMut` | [`MatchWithHandlers`](./providers/dispatch/match_with_handlers.md) | | `MatchFirstWithHandlersRef`, `MatchFirstWithHandlersMut`, and the `MatchFirstWithValueHandlers` and `MatchFirstWithFieldHandlers` forms | [`MatchFirstWithHandlers`](./providers/dispatch/match_first_with_handlers.md) | | `MatchWithValueHandlersRef`, `MatchWithValueHandlersMut` | [`MatchWithValueHandlers`](./providers/dispatch/match_with_value_handlers.md) | | `MatchWithFieldHandlersRef` | [`MatchWithFieldHandlers`](./providers/dispatch/match_with_field_handlers.md) | | `ExtractFirstFieldAndHandle`, `HandleFirstFieldValue` | [`ExtractFieldAndHandle`](./providers/dispatch/extract_field_and_handle.md), [`HandleFieldValue`](./providers/dispatch/handle_field_value.md) | | `DispatchMatchers` | [`MatchWithHandlers`](./providers/dispatch/match_with_handlers.md) | -| `ToFieldHandlers`, `HasFieldHandlers`, `MapFieldHandler`, `MapExtractFieldAndHandle` | [`MatchWithFieldHandlers`](./providers/dispatch/match_with_field_handlers.md) | +| `ToFieldHandlers`, `HasFieldHandlers`, `MapFieldHandler`, `MapExtractFieldAndHandle`, `MapExtractFirstFieldAndHandle` | [`MatchWithFieldHandlers`](./providers/dispatch/match_with_field_handlers.md) | | `ToBuildAndMergeHandler` | [`BuildAndMergeOutputs`](./providers/dispatch/build_and_merge_outputs.md) | | `IsPresent`, `IsNothing`, `IsVoid`, `IsOptional` | [`MapType`](./traits/type-level/map_type.md) | | `IsRef`, `IsMut`, `IsOwned` | [`MapTypeRef`](./traits/type-level/map_type_ref.md) | | `product!` (the value-level form) | [`Product!`](./macros/product.md) | +| `CanCompute`, `CanComputeRef`, `CanComputeAsync`, `CanComputeAsyncRef` | [`Computer`](./components/handler/computer.md), [`ComputerRef`](./components/handler/computer_ref.md), [`AsyncComputer`](./components/handler/async_computer.md), [`AsyncComputerRef`](./components/handler/async_computer_ref.md) | +| `CanTryCompute`, `CanTryComputeRef`, `CanHandle`, `CanHandleRef`, `CanProduce` | [`TryComputer`](./components/handler/try_computer.md), [`TryComputerRef`](./components/handler/try_computer_ref.md), [`Handler`](./components/handler/handler.md), [`HandlerRef`](./components/handler/handler_ref.md), [`Producer`](./components/handler/producer.md) | +| `ErrorOf`, `ErrorOnly` | [`HasErrorType`](./components/has_error_type.md) | +| `TypeOf` | [`HasType`](./components/has_type.md) | +| `RuntimeOf` | [`HasRuntimeType`](./components/has_runtime_type.md) | +| `FieldsBuilder`, `FieldsExtractor` | [`CanBuildFrom`](./traits/casting/can_build_from.md), [`CanUpcast`](./traits/casting/can_upcast.md) | +| `TryPromoteProviders` | [`PipeMonadic`](./providers/monad/pipe_monadic.md) | +| `__Partial{Name}`, `__PartialRef{Name}` (a derive's companion types) | [`#[derive(BuildField)]`](./derives/derive_build_field.md), [`#[derive(ExtractField)]`](./derives/derive_extract_field.md) | +| `{Name}Component` (a component's marker) | [`#[cgp_component]`](./macros/cgp_component.md) | | `#[check_trait(...)]`, `#[check_providers(...)]` | [`check_components!`](./macros/check_components.md) | | `#[check_params(...)]`, `#[skip_check]` | [`delegate_and_check_components!`](./macros/delegate_and_check_components.md) | diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_2.rs b/example-code/tests/compile_fail/reference/errors_the_fix_2.rs index 493540dc..a3b98f22 100644 --- a/example-code/tests/compile_fail/reference/errors_the_fix_2.rs +++ b/example-code/tests/compile_fail/reference/errors_the_fix_2.rs @@ -29,8 +29,8 @@ delegate_components! { } } -// error[E0599]: the method `greet` exists for struct `Person`, but its trait bounds -// were not satisfied -Person { age: 0 }.greet(); - -fn main() {} +fn main() { + // error[E0599]: the method `greet` exists for struct `Person`, but its trait bounds + // were not satisfied + Person { age: 0 }.greet(); +} diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_2.stderr b/example-code/tests/compile_fail/reference/errors_the_fix_2.stderr index 50f750bd..adca7d9a 100644 --- a/example-code/tests/compile_fail/reference/errors_the_fix_2.stderr +++ b/example-code/tests/compile_fail/reference/errors_the_fix_2.stderr @@ -1,10 +1,41 @@ -error: missing `struct` for struct definition - --> tests/compile_fail/reference/errors_the_fix_2.rs:34:1 +error[E0599]: the method `greet` exists for struct `Person`, but its trait bounds were not satisfied + --> tests/compile_fail/reference/errors_the_fix_2.rs:35:23 | -34 | Person { age: 0 }.greet(); - | ^^^^^^ +22 | pub struct Person { + | ----------------- method `greet` not found for this struct because it doesn't satisfy `Person: CanGreet` or `Person: Greeter` +... +35 | Person { age: 0 }.greet(); + | ^^^^^ this is an associated function, not a method | -help: add `struct` here to parse `Person` as a struct + = note: found the following associated functions; to be used as methods, functions must have a `self` parameter +note: the candidate is defined in the trait `Greeter` + --> tests/compile_fail/reference/errors_the_fix_2.rs:5:5 + | + 5 | fn greet(&self); + | ^^^^^^^^^^^^^^^^ +note: trait bound `Person: Greeter` was not satisfied + --> tests/compile_fail/reference/errors_the_fix_2.rs:3:1 + | + 3 | #[cgp_component(Greeter)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 | pub trait CanGreet { + | ^^^^^^^^ +note: the trait `Greeter` must be implemented + --> tests/compile_fail/reference/errors_the_fix_2.rs:4:1 + | + 4 | / pub trait CanGreet { + 5 | | fn greet(&self); + 6 | | } + | |_^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `CanGreet` defines an item `greet`, perhaps you need to implement it + --> tests/compile_fail/reference/errors_the_fix_2.rs:4:1 + | + 4 | pub trait CanGreet { + | ^^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use associated function syntax instead + | +35 - Person { age: 0 }.greet(); +35 + Person::greet(); | -34 | struct Person { age: 0 }.greet(); - | ++++++ diff --git a/example-code/tests/reference/components/has_error_type.rs b/example-code/tests/reference/components/has_error_type.rs index f4f84473..3a8e1147 100644 --- a/example-code/tests/reference/components/has_error_type.rs +++ b/example-code/tests/reference/components/has_error_type.rs @@ -18,6 +18,24 @@ pub mod usage { pub fn fail() -> Result<(), ::Error> { Err(anyhow::anyhow!("failed")) } + + // `ErrorOnly`: a context with an error type and nothing else. + use cgp::core::error::{ErrorOf, ErrorOnly}; + + pub fn parse_port>( + _context: &Context, + raw: &str, + ) -> Result> { + raw.parse().map_err(|_| format!("bad port: {raw}")) + } + + #[test] + fn test_error_only_supplies_an_error_type() { + let context = ErrorOnly::::default(); + assert_eq!(parse_port(&context, "80"), Ok(80)); + assert_eq!(parse_port(&context, "x"), Err("bad port: x".to_owned())); + assert_eq!(core::mem::size_of::>(), 0); + } } /// ## Examples diff --git a/example-code/tests/reference/errors.rs b/example-code/tests/reference/errors.rs index 80743887..4a14498a 100644 --- a/example-code/tests/reference/errors.rs +++ b/example-code/tests/reference/errors.rs @@ -57,9 +57,9 @@ pub mod a_dependency_is_not_met { /// /// The other half: the same wiring, with the check the page adds to force the failure to the wiring /// site. The page quotes the resulting `E0277` — `[CGP-E001]` through the toolchain — so the -/// snippet is carried as a `compile_fail` doctest. +/// snippet is a trybuild fixture. /// -/// The program is repeated in full rather than importing the module above, because a doctest is +/// The program is repeated in full rather than importing the module above, because a fixture is /// compiled as its own crate and because the page shows it whole. /// /// Rejected snippet — trybuild fixture `tests/compile_fail/reference/errors_the_fix_1.rs`. From 5b71d7ca4062a734cd69edc140e4c241373f3681 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 08:51:03 +0000 Subject: [PATCH 149/516] Review the X1 revision MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Link the seven provider pages the index no longer reached (UseFieldRef, UseFields, and the five With… aliases), point the reserved-variant entry at the page that lists all seven names, make the ErrorOnly snippet a complete program with a demo(), and shorten the index description to fit a search result. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HEMw6zp1hjNDZyxaKsszMj --- docs/reference/components/has_error_type.md | 8 ++++++-- docs/reference/errors.md | 4 ++-- docs/reference/index.md | 11 ++++++++--- .../tests/reference/components/has_error_type.rs | 8 ++++++-- 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index a073b2bd..8ea59c71 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -92,6 +92,7 @@ fallible function that reads nothing from its context: ```rust use cgp::core::error::{ErrorOf, ErrorOnly}; +use cgp::prelude::*; pub fn parse_port>( _context: &Context, @@ -100,8 +101,11 @@ pub fn parse_port>( raw.parse().map_err(|_| format!("bad port: {raw}")) } -let context = ErrorOnly::::default(); -assert_eq!(parse_port(&context, "80"), Ok(80)); +pub fn demo() { + let context = ErrorOnly::::default(); + assert_eq!(parse_port(&context, "80"), Ok(80)); + assert_eq!(parse_port(&context, "x"), Err("bad port: x".to_owned())); +} ``` ## Examples diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 2bd3a698..2fb59374 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -554,8 +554,8 @@ error: ambiguous associated item and its notes say the name "could refer to the variant defined here" or "could also refer to the associated type defined here". Under [`#[derive(ExtractField)]`](./derives/derive_extract_field.md) both notes point at the derive attribute, so nothing names the variant to rename. The seven reserved -names are listed on that page and on [`#[derive(HasFields)]`](./derives/derive_has_fields.md) and -[`#[derive(FromVariant)]`](./derives/derive_from_variant.md). Rename the variant. +names are listed on [`#[derive(CgpVariant)]`](./derives/derive_cgp_variant.md#common-mistakes), and +each derive's own page names the ones it reserves. Rename the variant. ### A field-type shorthand without a rule diff --git a/docs/reference/index.md b/docs/reference/index.md index a8c9a43e..bce98821 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -1,7 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 -description: 'The complete reference for every CGP construct, grouped by the job it does, with the handful a newcomer needs first and a lookup table for names without a page.' +description: 'The complete reference for every CGP construct, grouped by job, with the constructs a newcomer needs first and a lookup table for names without a page.' --- # Reference @@ -81,7 +81,9 @@ where a chained `get_field` would need a lifetime bound on the field's type. Getter traits are the sparing alternative, for the cases an implicit argument cannot reach. [`#[cgp_auto_getter]`](./macros/cgp_auto_getter.md) generates one from the method name; [`#[cgp_getter]`](./macros/cgp_getter.md) makes the getter a full component so the field it reads is -chosen by wiring, through [`UseField` and its siblings](./providers/use_field.md). +chosen by wiring, through [`UseField`](./providers/use_field.md), its borrowing form +[`UseFieldRef`](./providers/use_field_ref.md), or [`UseFields`](./providers/use_fields.md), which +reads the field named after each method. [`ChainGetters`](./providers/chain_getters.md) reaches a field on a nested context, and [`MRef`](./types/mref.md) is the return type of a getter that may lend or produce its value. @@ -107,7 +109,10 @@ names such a type by importing it with [`#[use_type]`](./attributes/use_type.md) different thing from the `UseType` provider despite the shared name. Beside the named components sits [`HasType`](./components/has_type.md), CGP's tag-indexed abstract-type component, and [`WithProvider`](./providers/with_provider.md) is the adapter that lets a foundational provider -stand in as a named component's. +stand in as a named component's, usually written through one of its aliases: +[`WithType`](./providers/with_type.md), [`WithField`](./providers/with_field.md), +[`WithFieldRef`](./providers/with_field_ref.md), [`WithContext`](./providers/with_context.md), and +[`WithDelegatedType`](./providers/with_delegated_type.md). ### Handle errors diff --git a/example-code/tests/reference/components/has_error_type.rs b/example-code/tests/reference/components/has_error_type.rs index 3a8e1147..c60689a8 100644 --- a/example-code/tests/reference/components/has_error_type.rs +++ b/example-code/tests/reference/components/has_error_type.rs @@ -29,11 +29,15 @@ pub mod usage { raw.parse().map_err(|_| format!("bad port: {raw}")) } - #[test] - fn test_error_only_supplies_an_error_type() { + pub fn demo() { let context = ErrorOnly::::default(); assert_eq!(parse_port(&context, "80"), Ok(80)); assert_eq!(parse_port(&context, "x"), Err("bad port: x".to_owned())); + } + + #[test] + fn test_error_only_supplies_an_error_type() { + demo(); assert_eq!(core::mem::size_of::>(), 0); } } From 2f3709984fbe773fd4c45182a4c86d2d1a3e3b72 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 28 Sep 2026 13:39:19 +0000 Subject: [PATCH 150/516] Sync the reference pages with the cgp defect fixes Remove the Common Mistakes the five cgp fixes close and document what replaces them: the macro's error for an undeclared name: parameter, #[check_providers] on a generic table, a ?Sized component called at str through a table, const parameters on declared table structs, and the reserved __compute_{method}__ helper of #[cgp_auto_dispatch]. The __Params__: ?Sized forwarding impl is updated in every listing that shows it. The example-code mirrors cover each change, the fixtures for the fixed defects are removed, and the shared-method-name clash gets its own fixture. example-code patches cgp to its git main, which carries the fixes once cgp is pushed. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/expand.md | 2 +- docs/reference/macros/cgp_auto_dispatch.md | 22 +- docs/reference/macros/cgp_component.md | 31 +- docs/reference/macros/check_components.md | 33 +- .../macros/delegate_and_check_components.md | 6 +- docs/reference/macros/delegate_components.md | 49 +-- .../traits/namespace/default_namespace.md | 2 +- .../traits/wiring/can_use_component.md | 5 +- .../traits/wiring/delegate_component.md | 6 +- .../traits/wiring/is_provider_for.md | 6 +- docs/reference/types/life.md | 62 ++- example-code/Cargo.toml | 1 + ...ch_common_mistakes_helper_function_name.rs | 27 -- ...ommon_mistakes_helper_function_name.stderr | 36 -- ...atch_common_mistakes_shared_method_name.rs | 16 + ..._common_mistakes_shared_method_name.stderr | 366 ++++++++++++++++++ ...common_mistakes_const_parameter_in_name.rs | 2 +- ...on_mistakes_const_parameter_in_name.stderr | 13 +- ...n_mistakes_undeclared_parameter_in_name.rs | 4 +- ...stakes_undeclared_parameter_in_name.stderr | 34 +- ...stakes_check_providers_on_generic_table.rs | 36 -- ...es_check_providers_on_generic_table.stderr | 17 - ...onents_common_mistakes_const_new_target.rs | 22 -- ...ts_common_mistakes_const_new_target.stderr | 5 - ...onents_formal_grammar_inner_table_const.rs | 3 +- ...ts_formal_grammar_inner_table_const.stderr | 4 +- .../life_common_mistakes_unsized_target.rs | 43 -- ...life_common_mistakes_unsized_target.stderr | 29 -- .../reference/macros/cgp_auto_dispatch.rs | 78 ++++ .../reference/macros/check_components.rs | 10 +- .../reference/macros/delegate_components.rs | 53 ++- example-code/tests/reference/types/life.rs | 44 ++- 32 files changed, 680 insertions(+), 387 deletions(-) delete mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs delete mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr delete mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs delete mode 100644 example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.stderr delete mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs delete mode 100644 example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.stderr delete mode 100644 example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs delete mode 100644 example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.stderr diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 74dba438..619a8a41 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -57,7 +57,7 @@ impl DelegateComponent for Rectangle { } impl< __Context__, - __Params__, + __Params__: ?Sized, > IsProviderFor for Rectangle where RectangleArea: IsProviderFor, diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 38c16eab..112aaa3b 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -160,17 +160,21 @@ the operation from scratch and expect contexts to configure it, start with a The macro keeps the trait unchanged and appends two kinds of item: one per-method computer, and one blanket impl of the trait for a fresh enum parameter. -For each method it emits a free function, named after the method, which -[`#[cgp_computer]`](./cgp_computer.md) turns into a provider named `Compute` plus the method name in -PascalCase: +For each method it emits a private free function under a reserved name, `__compute_` plus the method +name plus `__`, which [`#[cgp_computer]`](./cgp_computer.md) turns into a provider named `Compute` plus +the method name in PascalCase: ```rust #[cgp_computer(ComputeArea)] -fn area<'__a__, __Variants__: HasArea>(__Variants__: &'__a__ __Variants__) -> f64 { +fn __compute_area__<'__a__, __Variants__: HasArea>(__Variants__: &'__a__ __Variants__) -> f64 { __Variants__.area() } ``` +The reserved name does not collide with the module's own items, so a function called `area` beside +the trait compiles. Both generated names drop a raw-identifier prefix, so a method named `r#type` +yields `__compute_type__` and `ComputeType`. + The body calls the trait method on the payload, which makes the per-variant handler "invoke `HasArea::area` on whatever this variant holds". It is bound by `__Variants__: HasArea` so it applies to every payload type implementing the trait, and borrows through a fresh `'__a__` lifetime to mirror the `&self` @@ -265,10 +269,12 @@ named `'a` with the lifetime the macro gives the elided `&str`, reports ``error[E0261]: use of undeclared lifetime name `'__a__` ``. Name every reference with the same lifetime, or elide them all. -**The helper function takes the method's name.** Each method's per-variant function is a free -function called, for example, `area`, in the module where the trait is declared, so a module that -already has an `area` item fails with ``error[E0428]: the name `area` is defined multiple times``. -Declare the trait in a module of its own when the names clash. +**Two dispatch traits in one module cannot share a method name.** The macro names the helper and +the provider after the method alone, so a second trait with an `area` method emits a second +`__compute_area__` and a second `ComputeArea`, and the module fails with +``error[E0428]: the name `__compute_area__` is defined multiple times``, the same error for +`ComputeArea`, and `E0119` conflicts between the two providers' impls, followed by `E0277` errors on +the second trait's generated code. Declare such traits in separate modules. **The enum must derive the extensible-data machinery.** Without [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or the variant derives, the call fails with diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 8b444045..90fb43b5 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -484,15 +484,17 @@ name and the context name take no generics. The component name's parameters are bare names, such as `name: ShapeComponent`, which the marker struct then declares. Each must be one of the trait's own parameters, since the macro writes -the name wherever the component appears. The parser rejects anything more: +the name wherever the component appears, and the macro rejects one the trait does not declare, as +[Common Mistakes](#common-mistakes) shows. The parser rejects anything more: - a bound fails with ``trait bounds (`A: Clone`) are not allowed in type generics``, and a lifetime bound with ``lifetime bounds (`'a: 'b`) are not allowed in type generics``; - a default fails with ``default type parameters (`A = B`) are not allowed in type generics``; - a type that is not a single identifier, such as `Vec`, fails to parse. A single identifier such as `u32` is read as a parameter name rather than as the type; -- a const parameter parses, per the grammar, but then fails inside the macro, as - [Common Mistakes](#common-mistakes) records. +- a const parameter parses, per the grammar, but is always rejected: a component trait cannot + declare one, so the name either carries a parameter the trait lacks or sits on a trait the macro + refuses for its const generic parameter. A provider for such a component names the component explicitly, as in `#[cgp_impl(new SquareArea: AreaCalculatorComponent)]`, because the default @@ -529,17 +531,18 @@ error: failed to parse internal tokens to type `proc_macro2::Ident`: Name the parameter instead, as in `_value: u32`, and destructure inside a default method's body. -**A const parameter in the `name:` list fails inside the macro.** -`#[cgp_component { provider: Buffer, name: BufferComponent }]` is accepted by the -parser, but the name is then used in type positions, where the const parameter cannot appear, and -the macro fails with ``failed to parse internal tokens to type `syn::generics::TypeParamBound` ``. -Keep the name's parameters to bare type names, as the component's own parameters are. - -**A `name:` parameter the trait does not declare fails in the generated code.** In -`#[cgp_component { provider: Shape, name: ShapeComponent }]` on a trait without a `T`, the parser -accepts the name, and the compiler then reports ``error[E0425]: cannot find type `T` in this scope`` -at the `T`, followed by a confusing `E0034` about the generated impls. List only the trait's own -parameters in the name. +**A `name:` parameter must be one of the trait's own.** The marker struct declares the name's +parameters while the generated impls name it with the trait's, so the macro rejects a parameter the +trait lacks, with an error pointing at that parameter. +`#[cgp_component { provider: Shape, name: ShapeComponent }]` on a trait without a `T` fails with: + +```text +error: the component name's parameter `T` is not a generic parameter of the trait `CanShape` +``` + +A const parameter, as in `name: BufferComponent`, fails the same way on a trait +without an `N`, and a trait that declares `const N: usize` is refused for the const generic +parameter itself. List only the trait's own type and lifetime parameters in the name. **The attribute must be applied to a trait.** The macro refuses a struct, an enum, or a free function at parse time with ``expected `trait` ``, instead of lowering it into code that fails to compile diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 4ff11fe1..4eb18cbd 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -138,8 +138,9 @@ check_components! { `check_components!` separate from the wiring. A dependency missing only from the outer wrapper fails the wrapper's line alone, while one missing from the inner provider fails both. The pattern of failures tells you which layer to look at. It must list at least one provider, and may appear at most once per -table. The listed providers are checked against the table's context type as written, so this form needs a -concrete context rather than a generic table, as [Common Mistakes](#common-mistakes) explains. +table. The listed providers are checked against the table's context type, and a generic table checks them +at every instantiation, so `#[check_providers(RectangleArea)] Gen { AreaCalculatorComponent }` +asserts that `RectangleArea` is a provider for each `Gen`. ## Examples @@ -278,19 +279,25 @@ and `where` clause are merged into every impl it produces, so `impl<'a, I> __CheckContext for Context where I: Clone {}`. The `#[check_providers(...)]` form changes both the supertrait and the implementing type. The assertion -becomes `IsProviderFor` with the context *fixed*, and the impls are written for each provider: +becomes `IsProviderFor`, the trait gains a `__Context__` parameter that each impl fills with the table's +context type, and the impls are written for each provider: ```rust -trait CheckScaledProviders<__Component__, __Params__: ?Sized>: - IsProviderFor<__Component__, ScaledRectangle, __Params__> +trait CheckScaledProviders<__Component__, __Context__, __Params__: ?Sized>: + IsProviderFor<__Component__, __Context__, __Params__> {} -impl CheckScaledProviders for RectangleArea {} -impl CheckScaledProviders for ScaledArea {} +impl CheckScaledProviders +for RectangleArea {} +impl CheckScaledProviders +for ScaledArea {} ``` Because each provider is checked on its own line, the failures localize: a dependency the inner provider -lacks fails both impls, while one only the wrapper needs fails the wrapper's alone. +lacks fails both impls, while one only the wrapper needs fails the wrapper's alone. Passing the context +as a parameter keeps a generic table's parameters on the impls that declare them, so the `Gen` table +above, named with `#[check_trait(CheckGenProviders)]`, emits +`impl CheckGenProviders, ()> for RectangleArea {}`. ## Formal grammar @@ -373,12 +380,6 @@ no-op: error: `#[check_providers(...)]` requires at least one provider type. ``` -**`#[check_providers(...)]` does not work on a generic table.** The generated trait names the context -type in its supertrait, `IsProviderFor<__Component__, Gen, __Params__>`, but the table's generics -reach only the impls, so `#[check_providers(RectangleArea)] Gen { … }` fails with `E0425`, -``cannot find type `T` in this scope``, and an `E0207` beside it. Check a concrete instantiation such -as `Gen` instead. - **Listing one check twice conflicts.** The same component and parameters named twice, directly or through a bracketed list such as `[AreaCalculatorComponent, AreaCalculatorComponent]`, emit two identical impls and fail with `E0119`. @@ -399,9 +400,7 @@ context type, which does not say a name is missing. Add `#[check_trait(Name)]`. **A passing check is not a claim that the implementation is correct**, only that it resolves. It proves the provider was found and its dependencies are satisfiable, not that the provider does what -you meant. One case slips past it: a component used at an unsized type parameter, such as `str`, -passes its check but fails at every call through the table, as the -[`delegate_components!`](./delegate_components.md#common-mistakes) page records. +you meant. ## Related constructs diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 73e68cea..e65d48e4 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -293,8 +293,10 @@ the wiring half is a [`DelegateComponent`](../traits/wiring/delegate_component.m impl DelegateComponent for MyContext { type Delegate = UseType; } -impl<__Context__, __Params__> - IsProviderFor for MyContext +impl< + __Context__, + __Params__: ?Sized, +> IsProviderFor for MyContext where UseType: IsProviderFor, {} diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index dc00ed8a..47a04353 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -66,6 +66,9 @@ delegate_components! { A leading `new` keyword makes the macro declare the target struct as well. A target with parameters, as in ` new MyComponents { … }`, is declared with a `PhantomData` field over them. +The target's parameters take their kinds from the leading generic list, so +` new ArrayTable { … }` declares `ArrayTable`, and the +`PhantomData` field covers only the lifetime and type parameters. ```rust delegate_components! { @@ -267,6 +270,9 @@ delegate_components! { } ``` +That list declares the inner struct's parameters, so a `const` parameter is written with its kind, +as in ` ArrayKey: UseDelegate { … }>`. + One prerequisite is not visible in either snippet: **the component must carry [`#[derive_delegate(UseDelegate)]`](../attributes/derive_delegate.md)**, which generates the dispatch impl the wrapper resolves through. Leave it off and the table still expands, then fails at @@ -544,8 +550,10 @@ The hand-written equivalent of one wiring entry is exactly that block. The [`IsProviderFor`](../traits/wiring/is_provider_for.md) impl forwards the provider's requirements: ```rust -impl<__Context__, __Params__> - IsProviderFor for Rectangle +impl< + __Context__, + __Params__: ?Sized, +> IsProviderFor for Rectangle where RectangleArea: IsProviderFor, {} @@ -554,7 +562,9 @@ where This is why missing dependencies stay diagnosable. `RectangleArea`'s own `IsProviderFor` impl carries the `where` bounds it needs, so an unsatisfied requirement flows back through this forwarding impl to the point of use. Note that these parameters are literally named `__Context__` and `__Params__` in the -emitted code. +emitted code. `__Params__` is `?Sized`, as it is on the trait, so a component used at an unsized +parameter such as `str`, whose parameter tuple `(Life<'a>, str)` is unsized, still resolves through +the table. **Every other form on this page lowers to that same pair.** A form changes only how many pairs one line produces and what the `Delegate` type is. @@ -714,12 +724,13 @@ A `ProviderValue`'s nested-table form carries a full `TableBody`, so an inner ta form an outer one does. Its wrapper is a bare `IDENTIFIER`, not a path. An `InnerTable` is an identifier with an optional generic list rather than a full `TargetType`, because a nested table always names a fresh struct the macro declares. Its `BoundFreeGenerics` is a definition-position -list of lifetimes and type parameters: it allows neither bounds nor defaults, so put a bound on the -entry's own generics instead. The value parser tries the nested-table form speculatively and falls -back to reading the whole value as a plain type, so a bound on the inner table, a `const` parameter -on it, and a qualified wrapper all fail the same misleading way, with ``expected `,` `` at the inner -table's name. A bare `N` in that list declares a type parameter, so passing a `const` through it -fails with `E0747`: an inner table cannot carry a `const` parameter at all. +list of lifetimes, type parameters, and `const` parameters: it allows neither bounds nor defaults, +so put a bound on the entry's own generics instead. Because the list declares the struct's +parameters, a `const` is written with its kind, as `ArrayTable`, and a bare `N` +declares a type parameter. The value parser tries the nested-table form speculatively and falls back +to reading the whole value as a plain type, so a bound or a default on the inner table and a +qualified wrapper all fail the same misleading way, with ``expected `,` `` at the inner table's +name. The remaining rules restate points made above. An `OpenStmt` may omit its braces when opening exactly one component. A `MultiKey` takes no generic list of its own, only its elements do. Every bracketed @@ -765,11 +776,13 @@ end. is `E0425`, ``cannot find type `SquareArea` in this scope``, which names an unresolved type rather than anything about wiring. -**A table struct the macro declares cannot take a `const` parameter.** Both a `new` target such as -` new ArrayTable` and a nested inner table read `N` as a type parameter, so -passing a constant through fails with `E0747`, `constant provided when a type was expected`. -Declare the struct yourself instead, as `pub struct ArrayTable;`, wire it with its -own `delegate_components!` block, and name it as `UseDelegate>` in the outer entry. +**A bare `N` in a nested table's generic list declares a type parameter.** That list declares the +inner struct, so ` ArrayKey: UseDelegate { … }>` gives +`ArrayTable` a type parameter `N`, and passing the constant through fails with `E0747`, +`constant provided when a type was expected`. Write the parameter with its kind, as +`new ArrayTable { … }`. A `new` target is different, because its list is the +target's type arguments: ` new ArrayTable` takes the kind from the leading +generic list. **Two entries claiming one key conflict**, and the compiler reports it as a [coherence](/docs/reference/glossary#coherence) error, `E0119`, rather than as a wiring one. It @@ -781,14 +794,6 @@ generic ` AreaCalculatorComponent` entry overlapping a specific `@ComputerComponent. Code.Circle`. The same applies to a direct entry for a path a joined namespace itself binds: see [`cgp_namespace!`](./cgp_namespace.md#common-mistakes). -**A component used at an unsized type parameter passes its check and fails at the call.** The -impl the macro emits for each entry to forward the dependency marker requires the component's -parameters to be `Sized`, so a component declared over `T: ?Sized` and wired at `str` never works -through the table, though `check_components!` passes for it. A call reports `E0599` with the note -`` `str: Sized` which is required by … ``. This is a defect in the library. Until it is fixed, use a -sized parameter or implement the consumer trait directly on the context. The -[`Life`](../types/life.md) page shows the full example. - ## Related constructs - [`#[cgp_component]`](./cgp_component.md) — defines the components this table wires. diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index 98c91927..8eef42f8 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -157,7 +157,7 @@ impl< __Key__, __Value__, __Context__, - __Params__, + __Params__: ?Sized, > IsProviderFor<__Key__, __Context__, __Params__> for App where __Key__: DefaultNamespace, diff --git a/docs/reference/traits/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md index ce5a8c52..abc487c0 100644 --- a/docs/reference/traits/wiring/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -243,10 +243,7 @@ it](#when-to-use-it) explains, which is why `delegate_and_check_components!` is a bundle. **A passing check does not test behavior.** It proves the wiring resolves and every dependency -exists, not that the provider computes the right thing. The trait asks the delegate's -`IsProviderFor` impl rather than the context's own, so a component used at an unsized type parameter -passes it and still fails at the call; see -[`delegate_components!`](../../macros/delegate_components.md#common-mistakes). +exists, not that the provider computes the right thing. ## Related constructs diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index 87090af4..b56c3738 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -190,8 +190,10 @@ implementation is one of several, is shared between contexts, or composes with a impl DelegateComponent for App { type Delegate = GreetHello; } -impl<__Context__, __Params__> IsProviderFor -for App +impl< + __Context__, + __Params__: ?Sized, +> IsProviderFor for App where GreetHello: IsProviderFor, {} diff --git a/docs/reference/traits/wiring/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md index 12ddc2dc..eb94bad5 100644 --- a/docs/reference/traits/wiring/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -229,8 +229,10 @@ inner provider's requirements outward through the stack. each entry, an impl on the table that forwards to the chosen provider's marker: ```rust -impl<__Context__, __Params__> IsProviderFor -for Person +impl< + __Context__, + __Params__: ?Sized, +> IsProviderFor for Person where GreetHello: IsProviderFor, {} diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index 687a1053..dd4fd755 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -140,27 +140,10 @@ Every impl that satisfies this component, whether through `UseContext`, a table' or a provider you write yourself, carries the same `(Life<'a>, T)` tuple, so the resolution machinery preserves the lifetime end to end. -## When to use it - -**You read `Life` in generated code, and you write it only in a check.** The macros insert it -everywhere else. - -- **Read `Life<'a>` in an `IsProviderFor` tuple as the component's lifetime.** A dependency marker such - as `IsProviderFor<..., (Life<'a>, T)>` names a lifetime and a type parameter, in that order. -- **Write `(Life<'a>, T)` in a `check_components!` entry** for a component with a lifetime, and - declare `'a` in the table's generic list. -- **Hold a lifetime as `PhantomData>`** when you declare a provider struct by hand and want - the shape `#[cgp_new_provider]` gives it. A plain [`PhantomData<&'a ()>`](phantom_data.md) also - compiles, but it is covariant and keeps the struct `Send`. - -## Common Mistakes - -**A lifetime cannot appear directly in the `IsProviderFor` tuple.** The tuple holds types, so a bare -`'a` is invalid there, and the macro lifts it into `Life<'a>`. `Life` in an error means that the component -carries a lifetime. - -**A component whose target is unsized passes its check but fails at the call.** The `?Sized` bound -on `T` above admits `str`, and wiring such a component at `str` compiles and checks: +The `?Sized` bound on `T` admits an unsized target such as `str`, which makes the tuple +`(Life<'a>, str)` unsized too. `IsProviderFor` and the table's forwarding impl both accept an +unsized parameter tuple, so the same component wired at `str` resolves through the table like any +other: ```rust #[cgp_impl(new GetName)] @@ -187,23 +170,34 @@ check_components! { ReferenceGetterComponent: (Life<'a>, str), } } -``` -A call such as `let name: &str = borrowed.get_reference();` then fails with -``error[E0599]: the method `get_reference` exists for struct `Borrowed<'_>`, but its trait bounds were not satisfied``, -whose note names the unmet bound: +pub fn demo_unsized() { + let text = String::from("demo"); + let borrowed = Borrowed { name: &text }; -```text - = note: the following trait bounds were not satisfied: - `str: Sized` - which is required by `Borrowed<'_>: HasReference<'_, str>` + let name: &str = borrowed.get_reference(); + assert_eq!(name, "demo"); +} ``` -The parameter tuple `(Life<'a>, str)` is unsized, and the forwarding impl that -[`delegate_components!`](../macros/delegate_components.md) emits for the table requires its -parameter tuple to be `Sized`, while the check goes to the provider's own impl and passes. This is a -defect in the library. Until it is fixed, give such a component a sized target, as `Config` is -above, or implement the consumer trait directly on the context. +## When to use it + +**You read `Life` in generated code, and you write it only in a check.** The macros insert it +everywhere else. + +- **Read `Life<'a>` in an `IsProviderFor` tuple as the component's lifetime.** A dependency marker such + as `IsProviderFor<..., (Life<'a>, T)>` names a lifetime and a type parameter, in that order. +- **Write `(Life<'a>, T)` in a `check_components!` entry** for a component with a lifetime, and + declare `'a` in the table's generic list. +- **Hold a lifetime as `PhantomData>`** when you declare a provider struct by hand and want + the shape `#[cgp_new_provider]` gives it. A plain [`PhantomData<&'a ()>`](phantom_data.md) also + compiles, but it is covariant and keeps the struct `Send`. + +## Common Mistakes + +**A lifetime cannot appear directly in the `IsProviderFor` tuple.** The tuple holds types, so a bare +`'a` is invalid there, and the macro lifts it into `Life<'a>`. `Life` in an error means that the component +carries a lifetime. **A [higher-order provider](/docs/reference/glossary#higher-order-provider) with a lifetime loses its dependency propagation.** When the component carries a lifetime, the inner-provider bound of such a stack does not get a marker counterpart, because the rewrite diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index 2b68949d..00fc0e8d 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -18,3 +18,4 @@ trybuild = "1" [patch.crates-io] cgp = { git = "https://github.com/contextgeneric/cgp.git" } +# cgp = { path = "../../cgp/crates/main/cgp" } diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs deleted file mode 100644 index 512c3821..00000000 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: the per-method helper function takes the method's name in the module. - -use cgp::prelude::*; - -#[derive(CgpData)] -pub enum Shape { - Circle(Circle), - Rectangle(Rectangle), -} - -pub struct Circle { - pub radius: f64, -} - -pub struct Rectangle { - pub width: f64, - pub height: f64, -} - -#[cgp_auto_dispatch] -pub trait HasArea { - fn area(&self) -> f64; -} - -pub fn area() {} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.stderr deleted file mode 100644 index 859ea3df..00000000 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.stderr +++ /dev/null @@ -1,36 +0,0 @@ -error[E0428]: the name `area` is defined multiple times - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs:25:1 - | -20 | #[cgp_auto_dispatch] - | -------------------- previous definition of the value `area` here -... -25 | pub fn area() {} - | ^^^^^^^^^^^^^ `area` redefined here - | - = note: `area` must be defined only once in the value namespace of this module - -error[E0061]: this function takes 0 arguments but 1 argument was supplied - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs:22:8 - | -20 | #[cgp_auto_dispatch] - | -------------------- unexpected argument of type `&'__a__ __Variants__` -21 | pub trait HasArea { -22 | fn area(&self) -> f64; - | ^^^^ - | -note: function defined here - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs:25:8 - | -25 | pub fn area() {} - | ^^^^ - -error[E0308]: mismatched types - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_helper_function_name.rs:20:1 - | -20 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ - | | - | expected `f64`, found `()` - | expected `f64` because of return type - | - = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs new file mode 100644 index 00000000..52f0abc2 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs @@ -0,0 +1,16 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: two dispatch traits in one +//! module sharing a method name emit the same helper and provider names. + +use cgp::prelude::*; + +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(&self) -> f64; +} + +#[cgp_auto_dispatch] +pub trait HasSurface { + fn area(&self) -> f64; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr new file mode 100644 index 00000000..7547fdbb --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr @@ -0,0 +1,366 @@ +error[E0428]: the name `__compute_area__` is defined multiple times + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- previous definition of the value `__compute_area__` here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ `__compute_area__` redefined here + | + = note: `__compute_area__` must be defined only once in the value namespace of this module + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0428]: the name `ComputeArea` is defined multiple times + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:13:8 + | + 8 | fn area(&self) -> f64; + | ---- previous definition of the type `ComputeArea` here +... +13 | fn area(&self) -> f64; + | ^^^^ `ComputeArea` redefined here + | + = note: `ComputeArea` must be defined only once in the type namespace of this module + +error[E0119]: conflicting implementations of trait `cgp::prelude::Computer<_, _, &_>` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | + 6 | #[cgp_auto_dispatch] + | -------------------- first implementation here +... +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` + | + = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `__Variants__: HasArea` is not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ the trait `cgp::prelude::HasExtractor` is not implemented for `__Variants__` +12 | pub trait HasSurface { +13 | fn area(&self) -> f64; + | ---- required by a bound introduced by this call + | +note: required for `__Variants__` to implement `HasArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 + | + 6 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ + 7 | pub trait HasArea { + | ^^^^^^^ +note: required by a bound in `__compute_area__` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:7:11 + | + 7 | pub trait HasArea { + | ^^^^^^^ required by this bound in `__compute_area__` + 8 | fn area(&self) -> f64; + | ---- required by a bound in this function + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider further restricting type parameter `__Variants__` with trait `HasExtractor` + | +12 | pub trait HasSurface + cgp::prelude::HasExtractor { + | ++++++++++++++++++++++++++++ + +error[E0277]: the trait bound `for<'__a__> UseInputDelegate>>: cgp::prelude::Computer<(), (), &'__a__ __Variants__>` is not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound +12 | pub trait HasSurface { +13 | fn area(&self) -> f64; + | ---- required by a bound introduced by this call + | + = help: the trait `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` is not implemented for `UseInputDelegate>>` + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` +note: required for `__Variants__` to implement `HasArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 + | + 6 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ + 7 | pub trait HasArea { + | ^^^^^^^ +note: required by a bound in `__compute_area__` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:7:11 + | + 7 | pub trait HasArea { + | ^^^^^^^ required by this bound in `__compute_area__` + 8 | fn area(&self) -> f64; + | ---- required by a bound in this function + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement + | +13 | fn area where for<'__a__> UseInputDelegate>>: cgp::prelude::Computer<(), (), &'__a__ __Variants__>(&self) -> f64; + | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +error[E0277]: the trait bound `for<'__a__> MatchWithHandlersRef<_>: cgp::prelude::Computer<(), (), &'__a__ __Variants__>` is not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ the trait `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` is not implemented for `MatchWithHandlersRef<_>` +12 | pub trait HasSurface { +13 | fn area(&self) -> f64; + | ---- required by a bound introduced by this call + | +help: the trait `cgp::prelude::Computer` is conditionally implemented for `MatchWithHandlersRef` + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 + | +12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer +13 | | for MatchWithHandlersRef +14 | | where +15 | | Input: HasExtractorRef, + | | --------------- unsatisfied requirement introduced here: `__Variants__: HasExtractorRef` +16 | | DispatchMatchers: +17 | | Computer, Output = Result>, +18 | | Remainder: FinalizeExtract, + | |_______________________________^ + = note: required for `UseInputDelegate>>` to implement `for<'__a__> IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` +note: required for `__Variants__` to implement `HasArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 + | + 6 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ + 7 | pub trait HasArea { + | ^^^^^^^ +note: required by a bound in `__compute_area__` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:7:11 + | + 7 | pub trait HasArea { + | ^^^^^^^ required by this bound in `__compute_area__` + 8 | fn area(&self) -> f64; + | ---- required by a bound in this function + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `__Variants__: HasArea` is not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ the trait `HasFields` is not implemented for `__Variants__` +12 | pub trait HasSurface { +13 | fn area(&self) -> f64; + | ---- required by a bound introduced by this call + | + = note: required for `__Variants__` to implement `dispatch::providers::matchers::to_field_handlers::HasFieldHandlers>>` + = note: required for `UseInputDelegate>>` to implement `for<'__a__> IsProviderFor` + = note: 1 redundant requirement hidden + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` +note: required for `__Variants__` to implement `HasArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 + | + 6 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ + 7 | pub trait HasArea { + | ^^^^^^^ +note: required by a bound in `__compute_area__` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:7:11 + | + 7 | pub trait HasArea { + | ^^^^^^^ required by this bound in `__compute_area__` + 8 | fn area(&self) -> f64; + | ---- required by a bound in this function + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider further restricting type parameter `__Variants__` with trait `HasFields` + | +12 | pub trait HasSurface + cgp::prelude::HasFields { + | +++++++++++++++++++++++++ + +error[E0277]: the trait bound `__Variants__: HasArea` is not satisfied + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 + | +11 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ the trait `HasExtractorRef` is not implemented for `__Variants__` +12 | pub trait HasSurface { +13 | fn area(&self) -> f64; + | ---- required by a bound introduced by this call + | + = note: required for `MatchWithHandlersRef<_>` to implement `for<'__a__> IsProviderFor` + = note: 2 redundant requirements hidden + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` + = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` +note: required for `__Variants__` to implement `HasArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 + | + 6 | #[cgp_auto_dispatch] + | ^^^^^^^^^^^^^^^^^^^^ + 7 | pub trait HasArea { + | ^^^^^^^ +note: required by a bound in `__compute_area__` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:7:11 + | + 7 | pub trait HasArea { + | ^^^^^^^ required by this bound in `__compute_area__` + 8 | fn area(&self) -> f64; + | ---- required by a bound in this function + = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider further restricting type parameter `__Variants__` with trait `HasExtractorRef` + | +12 | pub trait HasSurface + cgp::prelude::HasExtractorRef { + | +++++++++++++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs index 597a686f..96aca140 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs @@ -1,5 +1,5 @@ //! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: a const parameter in the `name:` -//! list parses, then fails where the name is used as a type. +//! list parses, then is rejected as a parameter the trait does not declare. use cgp::prelude::*; diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr index 74038c58..fe18aa19 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.stderr @@ -1,14 +1,5 @@ -error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime +error: the component name's parameter `N` is not a generic parameter of the trait `CanBuffer` --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs:6:59 | 6 | #[cgp_component { provider: Buffer, name: BufferComponent }] - | ^^^^^ - -error: failed to parse internal tokens to type `syn::generics::TypeParamBound`: - IsProviderFor < BufferComponent < const N : usize > , __Context__, () > - --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_const_parameter_in_name.rs:6:1 - | -6 | #[cgp_component { provider: Buffer, name: BufferComponent }] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs index f26cc0fc..652f5e02 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs @@ -1,5 +1,5 @@ -//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: a `name:` parameter the trait does -//! not declare passes the parser and fails in the generated code. +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: the macro rejects a `name:` +//! parameter the trait does not declare. use cgp::prelude::*; diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr index 3c4309d5..68482b76 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.stderr @@ -1,35 +1,5 @@ -error[E0425]: cannot find type `T` in this scope +error: the component name's parameter `T` is not a generic parameter of the trait `CanShape` --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs:6:57 | 6 | #[cgp_component { provider: Shape, name: ShapeComponent }] - | ^ not found in this scope - -error[E0034]: multiple applicable items in scope - --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs:8:8 - | -8 | fn shape(&self); - | ^^^^^ multiple `shape` found - | -note: candidate #1 is defined in the trait `Shape` - --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs:8:5 - | -8 | fn shape(&self); - | ^^^^^^^^^^^^^^^^ -note: candidate #2 is defined in an impl of the trait `CanShape` for the type `__Context__` - --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_undeclared_parameter_in_name.rs:6:1 - | -6 | #[cgp_component { provider: Shape, name: ShapeComponent }] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) -help: use fully-qualified syntax to disambiguate - | -6 - #[cgp_component { provider: Shape, name: ShapeComponent }] -7 - pub trait CanShape { -8 - fn shape(&self); -6 + <<__Components__ as DelegateComponent<__Path__>>::Delegate as Shape>::shape(&self); - | -6 - #[cgp_component { provider: Shape, name: ShapeComponent }] -7 - pub trait CanShape { -8 - fn shape(&self); -6 + CanShape::shape(&self); - | + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs deleted file mode 100644 index 58dd477b..00000000 --- a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs +++ /dev/null @@ -1,36 +0,0 @@ -use cgp::prelude::*; - -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self) -> f64; -} - -#[cgp_impl(new RectangleArea)] -impl AreaCalculator { - fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { - width * height - } -} - -#[derive(HasField)] -pub struct Gen { - pub width: f64, - pub height: f64, - pub marker: core::marker::PhantomData, -} - -delegate_components! { - Gen { - AreaCalculatorComponent: RectangleArea, - } -} - -// error[E0425]: cannot find type `T` in this scope, then E0207 -check_components! { - #[check_providers(RectangleArea)] - Gen { - AreaCalculatorComponent, - } -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.stderr deleted file mode 100644 index 1bf22f3a..00000000 --- a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.stderr +++ /dev/null @@ -1,17 +0,0 @@ -error[E0425]: cannot find type `T` in this scope - --> tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs:31:13 - | -31 | Gen { - | ^ not found in this scope - -error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates - --> tests/compile_fail/reference/macros/check_components_common_mistakes_check_providers_on_generic_table.rs:31:6 - | -29 | / check_components! { -30 | | #[check_providers(RectangleArea)] -31 | | Gen { - | | ^ unconstrained type parameter -32 | | AreaCalculatorComponent, -33 | | } -34 | | } - | |_- help: remove the unused type parameter `T` diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs deleted file mode 100644 index bb898f5b..00000000 --- a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs +++ /dev/null @@ -1,22 +0,0 @@ -use cgp::prelude::*; - -#[cgp_component(AreaCalculator)] -pub trait CanCalculateArea { - fn area(&self) -> f64; -} - -#[cgp_impl(new RectangleArea)] -impl AreaCalculator { - fn area(&self) -> f64 { - 1.0 - } -} - -// error[E0747]: `new` reads `N` as a type parameter of the declared struct -delegate_components! { - new ArrayTable { - AreaCalculatorComponent: RectangleArea, - } -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.stderr deleted file mode 100644 index e27bcaaa..00000000 --- a/example-code/tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error[E0747]: constant provided when a type was expected - --> tests/compile_fail/reference/macros/delegate_components_common_mistakes_const_new_target.rs:17:37 - | -17 | new ArrayTable { - | ^ diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs index 42ea44d1..f4f7908e 100644 --- a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs @@ -21,7 +21,8 @@ pub struct App; pub struct ArrayKey; -// error[E0747]: the bare `N` declares a type parameter, so the const argument does not fit it +// error[E0747]: the bare `N` declares a type parameter, so the const argument does not fit it; +// writing `new ArrayTable` keeps the kind delegate_components! { new MyComponents { ArrayKey: UseDelegate { diff --git a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.stderr b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.stderr index 4fa1cc5c..71ba20cb 100644 --- a/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.stderr +++ b/example-code/tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.stderr @@ -1,5 +1,5 @@ error[E0747]: constant provided when a type was expected - --> tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs:27:66 + --> tests/compile_fail/reference/macros/delegate_components_formal_grammar_inner_table_const.rs:28:66 | -27 | ArrayKey: UseDelegate { +28 | ArrayKey: UseDelegate { | ^ diff --git a/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs b/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs deleted file mode 100644 index f7e26b20..00000000 --- a/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs +++ /dev/null @@ -1,43 +0,0 @@ -// A component whose type parameter is `?Sized` passes `check_components!` at an unsized argument -// such as `str`, but a call through the wiring fails: the forwarding `IsProviderFor` impl that -// `delegate_components!` emits declares its `__Params__` parameter without `?Sized`, and the params -// tuple `(Life<'a>, str)` is unsized. This pins the `Life` page's *Common Mistakes* entry. - -use cgp::prelude::*; - -#[cgp_component(ReferenceGetter)] -pub trait HasReference<'a, T: 'a + ?Sized> { - fn get_reference(&self) -> &'a T; -} - -#[cgp_impl(new GetName)] -#[uses(HasField)] -impl<'a> ReferenceGetter<'a, str> { - fn get_reference(&self) -> &'a str { - self.get_field(PhantomData::) - } -} - -#[derive(HasField)] -pub struct Borrowed<'a> { - pub name: &'a str, -} - -delegate_components! { - <'a> Borrowed<'a> { - ReferenceGetterComponent: GetName, - } -} - -// The check passes. -check_components! { - <'a> Borrowed<'a> { - ReferenceGetterComponent: (Life<'a>, str), - } -} - -fn main() { - let borrowed = Borrowed { name: "hello" }; - let name: &str = borrowed.get_reference(); - assert_eq!(name, "hello"); -} diff --git a/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.stderr b/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.stderr deleted file mode 100644 index a0955938..00000000 --- a/example-code/tests/compile_fail/reference/types/life_common_mistakes_unsized_target.stderr +++ /dev/null @@ -1,29 +0,0 @@ -error[E0599]: the method `get_reference` exists for struct `Borrowed<'_>`, but its trait bounds were not satisfied - --> tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs:41:31 - | -22 | pub struct Borrowed<'a> { - | ----------------------- method `get_reference` not found for this struct because it doesn't satisfy `Borrowed<'_>: HasReference<'_, str>` -... -41 | let name: &str = borrowed.get_reference(); - | ^^^^^^^^^^^^^ this is an associated function, not a method - | - = note: found the following associated functions; to be used as methods, functions must have a `self` parameter -note: the candidate is defined in the trait `ReferenceGetter` - --> tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs:10:5 - | -10 | fn get_reference(&self) -> &'a T; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: the following trait bounds were not satisfied: - `str: Sized` - which is required by `Borrowed<'_>: HasReference<'_, str>` - = help: items from traits can only be used if the trait is implemented and in scope -note: `HasReference` defines an item `get_reference`, perhaps you need to implement it - --> tests/compile_fail/reference/types/life_common_mistakes_unsized_target.rs:9:1 - | - 9 | pub trait HasReference<'a, T: 'a + ?Sized> { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -help: use associated function syntax instead - | -41 - let name: &str = borrowed.get_reference(); -41 + let name: &str = Borrowed<'_>::get_reference(); - | diff --git a/example-code/tests/reference/macros/cgp_auto_dispatch.rs b/example-code/tests/reference/macros/cgp_auto_dispatch.rs index 889818f5..29c22177 100644 --- a/example-code/tests/reference/macros/cgp_auto_dispatch.rs +++ b/example-code/tests/reference/macros/cgp_auto_dispatch.rs @@ -169,3 +169,81 @@ pub mod usage { assert_eq!(Token::Word(Word("w".to_owned())).render('#'), "#w"); } } + +/// ## Under the hood +/// +/// The helper's reserved name: a free function called `area` beside the trait does not clash with +/// the `__compute_area__` helper the macro emits for the `area` method, and a raw method name +/// yields valid generated names. +pub mod under_the_hood { + use cgp::prelude::*; + + #[derive(CgpData)] + pub enum Shape { + Circle(Circle), + Rectangle(Rectangle), + } + + pub struct Circle { + pub radius: f64, + } + + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + pub fn area(side: f64) -> f64 { + side * side + } + + #[cgp_auto_dispatch] + pub trait HasArea { + fn area(&self) -> f64; + } + + impl HasArea for Circle { + fn area(&self) -> f64 { + core::f64::consts::PI * self.radius * self.radius + } + } + + impl HasArea for Rectangle { + fn area(&self) -> f64 { + self.width * self.height + } + } + + /// The raw-identifier case the page names: `r#type` dispatches through `ComputeType`. + #[cgp_auto_dispatch] + pub trait HasKind { + fn r#type(&self) -> &'static str; + } + + impl HasKind for Circle { + fn r#type(&self) -> &'static str { + "circle" + } + } + + impl HasKind for Rectangle { + fn r#type(&self) -> &'static str { + "rectangle" + } + } + + #[test] + fn a_raw_method_name_dispatches() { + assert_eq!(Shape::Circle(Circle { radius: 1.0 }).r#type(), "circle"); + } + + #[test] + fn the_free_function_and_the_method_coexist() { + let shape = Shape::Rectangle(Rectangle { + width: 2.0, + height: 3.0, + }); + assert_eq!(shape.area(), 6.0); + assert_eq!(area(2.0), 4.0); + } +} diff --git a/example-code/tests/reference/macros/check_components.rs b/example-code/tests/reference/macros/check_components.rs index dbc8d8e1..4ed207bc 100644 --- a/example-code/tests/reference/macros/check_components.rs +++ b/example-code/tests/reference/macros/check_components.rs @@ -197,7 +197,7 @@ pub mod checking_each_provider_instead_of_the_context { } } - /// The generic-table case the page warns about, checked on a concrete instantiation instead. + /// The page's generic table: the providers are checked at every instantiation of `Gen`. #[derive(HasField)] pub struct Gen { pub width: f64, @@ -214,7 +214,7 @@ pub mod checking_each_provider_instead_of_the_context { check_components! { #[check_trait(CheckGenProviders)] #[check_providers(RectangleArea)] - Gen { + Gen { AreaCalculatorComponent, } } @@ -327,4 +327,10 @@ pub mod under_the_hood { ReferenceGetterComponent: <'a> (Life<'a>, str), } } + + #[test] + fn the_unsized_component_is_callable() { + let reference: Option<&'static str> = Context.get_reference(); + assert!(reference.is_none()); + } } diff --git a/example-code/tests/reference/macros/delegate_components.rs b/example-code/tests/reference/macros/delegate_components.rs index a2742df4..50acf936 100644 --- a/example-code/tests/reference/macros/delegate_components.rs +++ b/example-code/tests/reference/macros/delegate_components.rs @@ -106,6 +106,23 @@ pub mod defining_the_target_at_the_same_time { bundle.0 } + // The prose's const target: the bare `N` takes its kind from the leading list, so the + // declared struct is `ArrayTable`, and its `PhantomData` field leaves `N` out. + delegate_components! { + new ArrayTable { + AreaCalculatorComponent: RectangleArea, + } + } + + pub fn the_const_target_leaves_the_constant_out(table: ArrayTable<3>) -> PhantomData<()> { + table.0 + } + + #[test] + fn the_const_target_is_wired() { + super::the_key_forms::delegates_to::, AreaCalculatorComponent, RectangleArea>(); + } + #[test] fn the_bundle_answers_through_the_context() { let app = MyApp { @@ -534,6 +551,23 @@ pub mod the_value_forms { pub fn the_inner_table_is_generic(table: WidthValue) -> PhantomData { table.0 } + + /// The prose's const inner table: its list declares the struct, so the `const` keeps its kind. + pub struct ArrayKey; + + delegate_components! { + new ConstComponents { + ArrayKey: UseDelegate { + Rectangle: RectangleArea, + }>, + } + } + + #[test] + fn the_inner_table_carries_a_const() { + super::the_key_forms::delegates_to::, Rectangle, RectangleArea>(); + super::the_key_forms::delegates_to::, UseDelegate>>(); + } } /// ### Choosing a provider per type: the `open` statement @@ -1038,31 +1072,26 @@ pub mod under_the_hood { /// ## Common Mistakes /// -/// The workaround the page gives for a `const`-parameter table: declare the struct by hand and -/// wire it with its own block. The rejected snippets are the trybuild fixtures. +/// The fix the page gives for a bare `N` in a nested table's list: write the parameter with its +/// kind. The rejected snippets are the trybuild fixtures. pub mod common_mistakes { use cgp::prelude::*; pub use super::overview::{AreaCalculatorComponent, RectangleArea}; pub struct ArrayKey; - pub struct ArrayTable; - - delegate_components! { - ArrayTable { - AreaCalculatorComponent: RectangleArea, - } - } delegate_components! { new MyComponents { - ArrayKey: UseDelegate>, + ArrayKey: UseDelegate { + u32: RectangleArea, + }>, } } #[test] - fn the_hand_declared_table_is_wired() { - super::the_key_forms::delegates_to::, AreaCalculatorComponent, RectangleArea>(); + fn the_const_inner_table_is_wired() { + super::the_key_forms::delegates_to::, u32, RectangleArea>(); super::the_key_forms::delegates_to::, UseDelegate>>(); } } diff --git a/example-code/tests/reference/types/life.rs b/example-code/tests/reference/types/life.rs index bea93e06..a1dc75f7 100644 --- a/example-code/tests/reference/types/life.rs +++ b/example-code/tests/reference/types/life.rs @@ -3,8 +3,8 @@ //! `Life` is inserted by the macros into the dependency marker of a component with a lifetime, and a //! reader names it in one place: the `check_components!` entry for such a component. The Examples //! program wires and checks a borrowing getter component and calls it. The generated provider trait, -//! which records the lifetime as `Life<'a>`, is checked with `cargo cgp expand`. The unsized-target -//! defect the page records is a trybuild fixture under `tests/compile_fail/reference/types/`. +//! which records the lifetime as `Life<'a>`, is checked with `cargo cgp expand`. The second +//! Examples program wires the same component at the unsized target `str` and calls it. /// ## Examples pub mod examples { @@ -58,6 +58,46 @@ pub mod examples { fn test_demo() { demo(); } + + // The unsized target: the parameter tuple `(Life<'a>, str)` is unsized, and the table's + // forwarding impl accepts it. + #[cgp_impl(new GetName)] + #[uses(HasField)] + impl<'a> ReferenceGetter<'a, str> { + fn get_reference(&self) -> &'a str { + self.get_field(PhantomData::) + } + } + + #[derive(HasField)] + pub struct Borrowed<'a> { + pub name: &'a str, + } + + delegate_components! { + <'a> Borrowed<'a> { + ReferenceGetterComponent: GetName, + } + } + + check_components! { + <'a> Borrowed<'a> { + ReferenceGetterComponent: (Life<'a>, str), + } + } + + pub fn demo_unsized() { + let text = String::from("demo"); + let borrowed = Borrowed { name: &text }; + + let name: &str = borrowed.get_reference(); + assert_eq!(name, "demo"); + } + + #[test] + fn test_demo_unsized() { + demo_unsized(); + } } /// ## Definition From 6b18d5b7df3619000cec40388add729e2623dad6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 4 Oct 2026 14:09:27 +0000 Subject: [PATCH 151/516] Update the computer, producer, and dispatch macro pages for v0.8.0 `cgp` now lowers `#[cgp_computer]`, `#[cgp_producer]`, and `#[cgp_auto_dispatch]` itself and fixes several of their failures, so the three reference pages change with it: - `#[cgp_auto_dispatch]` documents supertraits, which the enum now has to provide, and its naming of elided lifetimes by Rust's elision rules, and drops the two Common Mistakes those changes fixed. It adds the rejected typed receiver and attribute argument, and the one lifetime shape that still fails: a lifetime hidden in a path, as in `Cow`. - `#[cgp_computer]` states its `Result` rule and the new message for a one-argument `Result`, the rejection of `impl Trait`, the unrawed default name, and the `E0207` a type parameter used only in the output produces. - `#[cgp_producer]` adds the `impl Trait` return rejection and the unrawed default name. - All three say the expansion is already lowered and fully qualified, and link the renamed `cgp-macro-extra-lib` and new `cgp-macro-extra-core` sources. The `example-code` compile-fail fixtures follow: the supertrait and two-lifetime cases, which now compile, are removed, the new rejections and failures gain fixtures, and the macros' existing fixtures are re-blessed for their new messages and wider carets. These snapshots were blessed against the unmerged `cgp` refactor, so the crate's compile-fail suite needs one more re-bless once that lands on `cgp` `main`. Co-Authored-By: Claude Opus 5.5 --- docs/reference/macros/cgp_auto_dispatch.md | 94 +++++++++----- docs/reference/macros/cgp_computer.md | 45 +++++-- docs/reference/macros/cgp_producer.md | 21 ++- ...tch_common_mistakes_associated_type.stderr | 2 +- ...atch_common_mistakes_attribute_argument.rs | 11 ++ ..._common_mistakes_attribute_argument.stderr | 5 + ...atch_common_mistakes_generic_method.stderr | 2 +- ...stakes_hand_impl_on_extensible_enum.stderr | 7 +- ...ispatch_common_mistakes_hidden_lifetime.rs | 16 +++ ...tch_common_mistakes_hidden_lifetime.stderr | 32 +++++ ...atch_common_mistakes_missing_derive.stderr | 24 ++-- ...ommon_mistakes_missing_variant_impl.stderr | 16 +-- ...ispatch_common_mistakes_no_receiver.stderr | 2 +- ..._common_mistakes_shared_method_name.stderr | 120 +++++++++--------- ...uto_dispatch_common_mistakes_supertrait.rs | 29 ----- ...dispatch_common_mistakes_supertrait.stderr | 16 --- ..._dispatch_common_mistakes_two_lifetimes.rs | 25 ---- ...patch_common_mistakes_two_lifetimes.stderr | 19 --- ...dispatch_common_mistakes_typed_receiver.rs | 11 ++ ...atch_common_mistakes_typed_receiver.stderr | 5 + ...er_common_mistakes_impl_trait_parameter.rs | 11 ++ ...ommon_mistakes_impl_trait_parameter.stderr | 5 + ...puter_common_mistakes_impl_trait_return.rs | 11 ++ ...r_common_mistakes_impl_trait_return.stderr | 5 + ...mmon_mistakes_mismatched_error_type.stderr | 14 +- ..._common_mistakes_missing_error_type.stderr | 34 ++--- ...mon_mistakes_output_only_type_parameter.rs | 11 ++ ...mistakes_output_only_type_parameter.stderr | 18 +++ ...p_computer_common_mistakes_receiver.stderr | 2 +- ...n_mistakes_single_argument_result_alias.rs | 4 +- ...stakes_single_argument_result_alias.stderr | 6 +- ...p_producer_common_mistakes_generics.stderr | 2 +- ...ducer_common_mistakes_impl_trait_return.rs | 11 ++ ...r_common_mistakes_impl_trait_return.stderr | 5 + ...producer_common_mistakes_parameters.stderr | 2 +- 35 files changed, 383 insertions(+), 260 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.stderr delete mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs delete mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.stderr delete mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs delete mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.rs create mode 100644 example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.stderr diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 112aaa3b..fda82ac4 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -37,8 +37,8 @@ the enum, use the combinators directly. This is the convenient front end to ## Usage -Write the attribute above a trait definition. It takes no arguments, and any tokens given as one -are ignored: +Write the attribute above a trait definition. It takes no arguments, and an argument is rejected +with `` `#[cgp_auto_dispatch]` takes no arguments ``: ```rust #[cgp_auto_dispatch] @@ -47,20 +47,22 @@ pub trait HasArea { } ``` -The trait may have generic parameters. Each method may take `self` by value, by shared reference, or -by mutable reference; may take further value or reference arguments; and may be `async`. +The trait may have generic parameters, lifetime parameters among them, and +[supertraits](/docs/reference/glossary#supertrait), which the enum then has to implement as well. +Each method may take `self` by value, by shared reference, or by mutable reference; may take further +value or reference arguments; may name its lifetimes or leave them elided; may have a default body; +and may be `async`. -The macro enforces three restrictions when it expands: +The macro enforces four restrictions when it expands: - **Every trait item must be a method.** Associated types and constants are rejected. - **Every method must have a `self` receiver**, since the receiver is the enum value being matched. +- **The receiver must be `self`, `&self`, or `&mut self`.** A typed receiver such as + `self: Box` is rejected, because the generated code passes the receiver to a matcher that + takes the enum or a borrow of it. - **A method may not have non-lifetime generic parameters.** Lifetimes are fine. The reason is in the [Common Mistakes](#common-mistakes), and it is a real limitation rather than an oversight. -Two further shapes are accepted and then fail to compile: a -[supertrait](/docs/reference/glossary#supertrait) on the trait, and a method that needs two distinct -lifetimes. [Common Mistakes](#common-mistakes) covers both. - The enum also has to be made extensible, with [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or the narrower variant derives, so the machinery can take it apart one variant at a time. @@ -160,9 +162,12 @@ the operation from scratch and expect contexts to configure it, start with a The macro keeps the trait unchanged and appends two kinds of item: one per-method computer, and one blanket impl of the trait for a fresh enum parameter. -For each method it emits a private free function under a reserved name, `__compute_` plus the method -name plus `__`, which [`#[cgp_computer]`](./cgp_computer.md) turns into a provider named `Compute` plus -the method name in PascalCase: +For each method it writes a private free function under a reserved name, `__compute_` plus the +method name plus `__`, and turns it into a provider named `Compute` plus the method name in +PascalCase exactly as [`#[cgp_computer]`](./cgp_computer.md) would. It runs the function through +`#[cgp_computer]`'s own code rather than emitting the attribute, so the expansion holds the +provider's final code; the block below shows the function as `#[cgp_computer]` input, which is the +readable form: ```rust #[cgp_computer(ComputeArea)] @@ -177,8 +182,30 @@ yields `__compute_type__` and `ComputeType`. The body calls the trait method on the payload, which makes the per-variant handler "invoke `HasArea::area` on whatever this variant holds". It is bound by `__Variants__: HasArea` so it applies to every -payload type implementing the trait, and borrows through a fresh `'__a__` lifetime to mirror the `&self` -receiver. +payload type implementing the trait, and borrows through the receiver's lifetime, a fresh `'__a__` +when the receiver elides it as `&self` does. + +**The macro names every elided lifetime in the signature the way Rust's elision rules read it**, +because it copies the signature into this function and into the bound below, where an unnamed +lifetime is either rejected or means something else. Each elided lifetime in an argument, at any +depth (`&str`, `Option<&str>`, `Foo<'_>`), gets its own fresh name, `'__a1__`, `'__a2__`, and so on, +just as elided inputs are distinct lifetimes. An elided lifetime in the return type takes the +receiver's, or, for a by-value `self`, the one lifetime the arguments use. A `fn(&T)` type or an +`Fn(&T)` bound keeps the lifetimes it binds itself. So `fn label(&self, suffix: &str) -> &str` +generates: + +```rust +#[cgp_computer(ComputeLabel)] +fn __compute_label__<'__a__, '__a1__, __Variants__: CanLabel>( + __Variants__: &'__a__ __Variants__, + (arg_0): (&'__a1__ str), +) -> &'__a__ str { + __Variants__.label(arg_0) +} +``` + +and the borrow the method returns outlives a shorter-lived `suffix`, as the trait's own signature +promises. Then the enum-level blanket impl, which wires a matcher over the whole enum: @@ -203,7 +230,9 @@ A few things are worth reading off that. The matcher is invoked with a **unit co code** (`&()` and `PhantomData::<()>`), because the per-variant logic depends only on the payload, which is exactly why a context cannot influence it. The call names the provider trait, with its arguments inferred, so it stays unambiguous in a module that also imports `CanCompute`. The -`__Variants__: HasExtractor` bound requires the enum to be extensible. And **the first `where` bound +`__Variants__: HasExtractor` bound requires the enum to be extensible, and when the trait has a +supertrait, a further `__Variants__: Supertrait` bound requires the enum to provide it, for instance +by dispatching the supertrait as well. And **the first `where` bound is where a missing variant impl is reported**: it says the matcher must be a `Computer` over this enum, which holds only if every variant's payload can be handled. @@ -230,8 +259,11 @@ fn contains(&self, arg_0: f64, arg_1: f64) -> bool { } ``` -An `async` method selects the `AsyncComputer` form of the bound and the call instead of `Computer`, and awaits -the result. +The bound is quantified, in a single `for<…>`, over the method's own lifetime parameters and the +lifetimes the macro named; the trait's lifetime parameters belong to the impl and are not quantified. +An `async` method selects the `AsyncComputer` form of the bound and the call instead of `Computer`, +and awaits the result. Every name in the expansion is written as a full path, so it compiles in a +module that does not import `cgp::prelude::*`. ## Common Mistakes @@ -252,22 +284,19 @@ parameters are fine. error: Only function items are allowed in a dispatch trait ``` -**A method without a receiver is rejected**, with *Dispatcher method must have a self argument*. - -**A supertrait breaks the expansion.** The blanket impl implements the trait for every -`__Variants__` without requiring the supertrait, so Rust rejects it: - -```text -error[E0277]: the trait bound `__Variants__: Named` is not satisfied -``` +**A method without a receiver is rejected**, with *Dispatcher method must have a self argument*, +and **a typed receiver** such as `self: Box` with +*Dispatcher method receiver must be `self`, `&self`, or `&mut self`*. -Declare the dependency on each payload's impl instead of as a supertrait. +**An attribute argument is rejected**, with +`` `#[cgp_auto_dispatch]` takes no arguments ``. The macro has nothing to configure. -**A method needing two distinct lifetimes fails to compile.** The macro quantifies the generated -bound over only one lifetime, so `fn lookup<'a>(&'a self, key: &str) -> &'a str`, which pairs a -named `'a` with the lifetime the macro gives the elided `&str`, reports -``error[E0261]: use of undeclared lifetime name `'__a__` ``. Name every reference with the same -lifetime, or elide them all. +**A lifetime hidden in a type's path is not named.** A type that carries a lifetime without writing +it, such as `Cow` for `Cow<'_, str>`, gives the macro nothing to rename, since whether a path +hides a lifetime depends on the type's definition, which a macro cannot see. Such an argument fails +to compile with ``error[E0726]: implicit elided lifetime not allowed here``, and such a return type +with ``error[E0106]: missing lifetime specifier``. Write the lifetime out as `Cow<'_, str>`, which +the macro then names like any other elided lifetime. **Two dispatch traits in one module cannot share a method name.** The macro names the helper and the provider after the method alone, so a second trait with an `area` method emits a second @@ -318,7 +347,8 @@ The ideas behind it: ## Source -- Entry point: [`entrypoints/cgp_auto_dispatch.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_auto_dispatch.rs) +- Entry point: [`cgp-macro-extra-lib/src/cgp_auto_dispatch.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-extra-lib/src/cgp_auto_dispatch.rs) +- The parsing and code generation, including the lifetime naming: [`cgp-macro-extra-core/src/types/cgp_auto_dispatch/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-extra-core/src/types/cgp_auto_dispatch/) - The matchers it generates: [`cgp-dispatch/src/providers/matchers/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-dispatch/src/providers/matchers/) --- diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 8d749659..e1ac8a55 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -55,8 +55,8 @@ fn add(a: u64, b: u64) -> u64 { } ``` -Omitted, the provider struct takes the function name in PascalCase: `add` becomes `Add`. Given, the -argument is used verbatim. +Omitted, the provider struct takes the function name in PascalCase: `add` becomes `Add`, and a raw +identifier loses its `r#`, so `r#type` becomes `Type`. Given, the argument is used verbatim. The function's shape decides everything else: @@ -67,6 +67,8 @@ The function's shape decides everything else: - **Its return type becomes the output**, and an omitted return type is `()`. - **It must not take `self`.** A handler provider has no receiver; the context is supplied separately by the handler machinery. +- **It must not use `impl Trait`**, in a parameter or the return type, since the generated impl's + input and output types have to be nameable. Declare a generic parameter instead. - **It may be `async`**, and it may return a `Result`. Those two choices select the base trait. - **Its generics and `where` clause carry over** to the generated impl, so the provider can itself be generic. @@ -87,9 +89,10 @@ The `Result` row is worth a careful read. The base trait stays `Computer`, and i `Result` type as written. Only the *bundle* changes, and it makes `try_compute` and `handle` surface the `Ok`/`Err` outcome as success or failure rather than handing back a `Result` as a plain value. -The macro recognizes a `Result` by its spelling, not its meaning: the return type must be written -`Result`, with `Result` as the whole path and two arguments. -[Common Mistakes](#common-mistakes) covers the spellings it misses. +The macro recognizes a `Result` by its spelling, not its meaning: only a return type written +`Result`, with `Result` as the whole path and two arguments, is fallible. Any other type is a +plain value, and a type that starts with `Result` in another form, such as a one-argument alias, is +rejected. [Common Mistakes](#common-mistakes) shows what each spelling does. ## Examples @@ -176,8 +179,12 @@ variants. A single transform with one caller is a method. ## Under the hood -The macro emits the function unchanged, a provider impl of the base trait, and a -[`delegate_components!`](./delegate_components.md) block wiring the rest of the family. From this input: +The macro's expansion is the function unchanged, a provider impl of the base trait, and a +[`delegate_components!`](./delegate_components.md) block wiring the rest of the family. It builds the +input for [`#[cgp_new_provider]`](./cgp_provider.md) and `delegate_components!` itself and runs their +code in place, so what it emits is already their expansion, with every name written as a full path, +and it compiles in a module that does not import `cgp::prelude::*`. The blocks below show that +input, which is the readable form. From this function: ```rust #[cgp_computer] @@ -286,10 +293,11 @@ forgetting that reports the component as an unresolved type rather than as a mis **Only a `Result` spelled exactly that way selects the fallible bundle.** Any other spelling, such as `core::result::Result` or `anyhow::Result`, is treated as a plain value, so `try_compute` wraps the whole result in `Ok` instead of propagating its error. A one-argument -alias written `Result`, such as the one `use anyhow::Result;` brings in, fails outright: +alias written `Result`, such as the one `use anyhow::Result;` brings in, is rejected, since +the macro cannot tell what it names: ```text -error: expected `,` +error: A `Result` return type must be written as `Result`, naming its error type ``` Write the full `Result` form in a fallible computer's signature. @@ -308,6 +316,21 @@ through the context. **A function with a receiver is rejected**, with *Computer functions cannot have a receiver*. +**`impl Trait` is rejected.** In a parameter it fails with +*Computer function parameters cannot use `impl Trait`; declare a generic parameter instead*, and in +the return type with *Computer functions cannot return `impl Trait`*. A parameter's `impl Trait` is +shorthand for a generic parameter, so the fix is to write that parameter out. + +**A type parameter used only in the return type fails to compile.** The function's generics move +onto the generated impl, which names only the input type, so in +`fn parse(value: String) -> Option` nothing fixes `T` and the compiler rejects it: + +```text +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates +``` + +Such a computation needs a `Computer` provider written by hand, whose struct can carry `T`. + **A `Result` return changes the bundle, not the base trait.** The `Computer` impl's `Output` *is* the `Result`, so `compute` hands back a `Result` as an ordinary value while `try_compute` treats its `Err` as failure. Both are available on the same provider, and which one a pipeline uses decides whether an error @@ -333,8 +356,8 @@ The ideas behind it: ## Source -- Entry point: [`entrypoints/cgp_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_computer.rs) -- `Result`-versus-value detection: [`parse/maybe_result.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/parse/maybe_result.rs) +- Entry point: [`cgp-macro-extra-lib/src/cgp_computer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-extra-lib/src/cgp_computer.rs) +- The parsing and code generation: [`cgp-macro-extra-core/src/types/cgp_computer/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-extra-core/src/types/cgp_computer/), with the `Result`-versus-value detection in `maybe_result.rs` - The base traits: [`cgp-handler/src/components/`](https://github.com/contextgeneric/cgp/tree/main/crates/extra/cgp-handler/src/components/) - The promotion bundles: [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index ad7e55fd..6dd687b1 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -49,8 +49,8 @@ fn magic_number() -> u64 { } ``` -Omitted, the provider struct takes the function name in PascalCase: `magic_number` becomes `MagicNumber`. -Given, the argument is used verbatim. The function's return type becomes the producer's output, and +Omitted, the provider struct takes the function name in PascalCase: `magic_number` becomes `MagicNumber`, +and a raw identifier loses its `r#`, so `r#loop` becomes `Loop`. Given, the argument is used verbatim. The function's return type becomes the producer's output, and an omitted return type is `()`. **The function is constrained tightly, to exactly what a producer can be.** Each restriction is @@ -61,6 +61,7 @@ enforced at expansion time with its own message: | No parameters, and no `self` | A producer takes no input and has no receiver. | | Not `async` | The producer trait is synchronous. | | No generic parameters | There is nothing to infer them from. | +| No `impl Trait` return type | The generated impl's output type has to be nameable. | That last restriction is the one most likely to cause trouble, and it is the biggest difference from [`#[cgp_computer]`](./cgp_computer.md), which carries generics through fine. A producer has no input, so a @@ -142,8 +143,12 @@ within it there is nothing simpler. ## Under the hood -The macro emits the function unchanged, a provider impl of [`Producer`](../components/handler/producer.md), and a -[`delegate_components!`](./delegate_components.md) block wiring the whole family. From this input: +The macro's expansion is the function unchanged, a provider impl of +[`Producer`](../components/handler/producer.md), and a +[`delegate_components!`](./delegate_components.md) block wiring the whole family. It builds the input +for [`#[cgp_new_provider]`](./cgp_provider.md) and `delegate_components!` itself and runs their code +in place, so what it emits is already their expansion, with every name written as a full path. The +blocks below show that input, which is the readable form. From this function: ```rust #[cgp_producer] @@ -213,7 +218,7 @@ ProviderName -> IDENTIFIER Omitted, the provider struct takes the function name converted to PascalCase; a given `IDENTIFIER` is used verbatim. The annotated function is plain Rust, constrained to a producer's shape (no parameters, no -`async`, no generics), as described in [Usage](#usage). +`async`, no generics, and no `impl Trait` return type), as described in [Usage](#usage). ## Common Mistakes @@ -223,10 +228,11 @@ verbatim. The annotated function is plain Rust, constrained to a producer's shap error: Producer functions cannot have parameters error: Producer functions cannot be async error: Producer functions must have empty generic parameters +error: Producer functions cannot return `impl Trait` ``` For the first two, [`#[cgp_computer]`](./cgp_computer.md) is the macro that accepts them. For the third there -is no macro alternative: write the provider by hand. +is no macro alternative: write the provider by hand. For the fourth, name the returned type. **The function cannot reach the context**, so a producer that needs a field or an abstract type is not expressible this way at all. That rules out most real producers, which is worth knowing before reaching for @@ -272,7 +278,8 @@ The ideas behind it: ## Source -- Entry point: [`entrypoints/cgp_producer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-extra-macro-lib/src/entrypoints/cgp_producer.rs) +- Entry point: [`cgp-macro-extra-lib/src/cgp_producer.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-extra-lib/src/cgp_producer.rs) +- The parsing and code generation: [`cgp-macro-extra-core/src/types/cgp_producer/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-extra-core/src/types/cgp_producer/) - The `Producer` trait: [`components/produce.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/components/produce.rs) - The `PromoteProducer` bundle: [`providers/promote_all.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/extra/cgp-handler/src/providers/promote_all.rs) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.stderr index 7198a918..c2b42ddf 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.stderr @@ -2,4 +2,4 @@ error: Only function items are allowed in a dispatch trait --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_associated_type.rs:22:5 | 22 | type Unit; - | ^^^^ + | ^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.rs new file mode 100644 index 00000000..451a2748 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: the attribute takes no +//! arguments. + +use cgp::prelude::*; + +#[cgp_auto_dispatch(AreaDispatcher)] +pub trait HasArea { + fn area(&self) -> f64; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.stderr new file mode 100644 index 00000000..87dea8cf --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.stderr @@ -0,0 +1,5 @@ +error: `#[cgp_auto_dispatch]` takes no arguments + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_attribute_argument.rs:6:21 + | +6 | #[cgp_auto_dispatch(AreaDispatcher)] + | ^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.stderr index 196f8df0..0d2e46ca 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.stderr @@ -2,4 +2,4 @@ error: Dispatch trait methods cannot contain non-lifetime generic parameters due --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_generic_method.rs:22:17 | 22 | fn describe(&self) -> T; - | ^ + | ^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr index c81e9ce6..a08b681f 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr @@ -1,12 +1,11 @@ error[E0119]: conflicting implementations of trait `HasArea` for type `Shape` - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.rs:20:1 + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.rs:21:11 | -20 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Shape` +21 | pub trait HasArea { + | ^^^^^^^ conflicting implementation for `Shape` ... 25 | impl HasArea for Shape { | ---------------------- first implementation here | = note: upstream crates may add a new impl of trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::MatchWithValueHandlersRef` in future versions = note: upstream crates may add a new impl of trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::MatchWithValueHandlersRef` in future versions - = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.rs new file mode 100644 index 00000000..1389fbd7 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.rs @@ -0,0 +1,16 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a lifetime hidden in a type's +//! path, as in `Cow`, gives the macro nothing to name, so the argument fails with `E0726` and +//! the return type with `E0106`. + +use std::borrow::Cow; + +use cgp::prelude::*; + +#[cgp_auto_dispatch] +pub trait HasLabel { + fn measure(&self, label: Cow) -> usize; + + fn label(&self) -> Cow; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.stderr new file mode 100644 index 00000000..e02055a5 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.stderr @@ -0,0 +1,32 @@ +error[E0106]: missing lifetime specifier + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.rs:11:33 + | +11 | fn measure(&self, label: Cow) -> usize; + | ^ expected named lifetime parameter + | +help: consider using the `'__a__` lifetime + | +11 | fn measure(&self, label: Cow<'__a__, str>) -> usize; + | +++++++ + +error[E0106]: missing lifetime specifier + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.rs:13:27 + | +13 | fn label(&self) -> Cow; + | ^ expected named lifetime parameter + | +help: consider using the `'__a__` lifetime + | +13 | fn label(&self) -> Cow<'__a__, str>; + | +++++++ + +error[E0726]: implicit elided lifetime not allowed here + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hidden_lifetime.rs:11:30 + | +11 | fn measure(&self, label: Cow) -> usize; + | ^^^^^^^^ expected lifetime parameter + | +help: indicate the anonymous lifetime + | +11 | fn measure(&self, label: Cow<'_, str>) -> usize; + | +++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr index 40ca0314..cb4bd16d 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr @@ -2,31 +2,31 @@ error[E0599]: the method `area` exists for reference `&Plain`, but its trait bou --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs:36:11 | 20 | pub enum Plain { - | -------------- doesn't satisfy `Plain: HasArea` or `Plain: cgp::prelude::HasExtractor` + | -------------- doesn't satisfy `Plain: HasArea` or `Plain: HasExtractor` ... 36 | shape.area() | ^^^^ method cannot be called on `&Plain` due to unsatisfied trait bounds | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 | 19 | pub struct MatchWithValueHandlersRef(pub PhantomData); | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Plain>>::Output = f64`, `<_ as Computer<(), (), &Plain>>::Output = f64`, `_: Computer<(), (), &&Plain>` or `_: Computer<(), (), &Plain>` | note: the following trait bounds were not satisfied: - `&Plain: cgp::prelude::HasExtractor` - ` as cgp::prelude::Computer<(), (), &'__a__ &Plain>>::Output = f64` - ` as cgp::prelude::Computer<(), (), &'__a__ Plain>>::Output = f64` - `Plain: cgp::prelude::HasExtractor` - `cgp::prelude::MatchWithValueHandlersRef: cgp::prelude::Computer<(), (), &'__a__ &Plain>` - `cgp::prelude::MatchWithValueHandlersRef: cgp::prelude::Computer<(), (), &'__a__ Plain>` + `&Plain: HasExtractor` + ` as Computer<(), (), &'__a__ &Plain>>::Output = f64` + ` as Computer<(), (), &'__a__ Plain>>::Output = f64` + `MatchWithValueHandlersRef: Computer<(), (), &'__a__ &Plain>` + `MatchWithValueHandlersRef: Computer<(), (), &'__a__ Plain>` + `Plain: HasExtractor` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.rs:24:1 | 24 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound introduced here 25 | pub trait HasArea { - | ^^^^^^^ -note: the trait `cgp::prelude::HasExtractor` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + | ------- +note: the trait `HasExtractor` must be implemented + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:6:1 | 6 | pub trait HasExtractor { | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr index c0896303..0c0ba666 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr @@ -7,23 +7,23 @@ error[E0599]: the method `area` exists for reference `&Shape`, but its trait bou 32 | shape.area() | ^^^^ method cannot be called on `&Shape` due to unsatisfied trait bounds | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 | 19 | pub struct MatchWithValueHandlersRef(pub PhantomData); | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Shape>>::Output = f64`, `<_ as Computer<(), (), &Shape>>::Output = f64`, `_: Computer<(), (), &&Shape>` or `_: Computer<(), (), &Shape>` | note: the following trait bounds were not satisfied: - `&Shape: cgp::prelude::HasExtractor` - ` as cgp::prelude::Computer<(), (), &'__a__ &Shape>>::Output = f64` - ` as cgp::prelude::Computer<(), (), &'__a__ Shape>>::Output = f64` - `cgp::prelude::MatchWithValueHandlersRef: cgp::prelude::Computer<(), (), &'__a__ &Shape>` - `cgp::prelude::MatchWithValueHandlersRef: cgp::prelude::Computer<(), (), &'__a__ Shape>` + `&Shape: HasExtractor` + ` as Computer<(), (), &'__a__ &Shape>>::Output = f64` + ` as Computer<(), (), &'__a__ Shape>>::Output = f64` + `MatchWithValueHandlersRef: Computer<(), (), &'__a__ &Shape>` + `MatchWithValueHandlersRef: Computer<(), (), &'__a__ Shape>` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs:20:1 | 20 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound introduced here 21 | pub trait HasArea { - | ^^^^^^^ + | ------- = help: items from traits can only be used if the trait is implemented and in scope note: `HasArea` defines an item `area`, perhaps you need to implement it --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.rs:21:1 diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.stderr index 2cb0dd12..1d106d49 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.stderr @@ -2,4 +2,4 @@ error: Dispatcher method must have a self argument --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_no_receiver.rs:22:5 | 22 | fn origin() -> (f64, f64); - | ^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr index 7547fdbb..d3e80782 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr @@ -21,29 +21,25 @@ error[E0428]: the name `ComputeArea` is defined multiple times | = note: `ComputeArea` must be defined only once in the type namespace of this module -error[E0119]: conflicting implementations of trait `cgp::prelude::Computer<_, _, &_>` for type `ComputeArea` - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 +error[E0119]: conflicting implementations of trait `Computer<_, _, &_>` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:13:8 | - 6 | #[cgp_auto_dispatch] - | -------------------- first implementation here + 8 | fn area(&self) -> f64; + | ---- first implementation here ... -11 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` - | - = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) +13 | fn area(&self) -> f64; + | ^^^^ conflicting implementation for `ComputeArea` -error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:13:8 | - 6 | #[cgp_auto_dispatch] - | -------------------- first implementation here + 8 | fn area(&self) -> f64; + | ---- first implementation here ... -11 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `ComputeArea` - | - = note: this error originates in the attribute macro `cgp_computer` (in Nightly builds, run with -Z macro-backtrace for more info) +13 | fn area(&self) -> f64; + | ^^^^ conflicting implementation for `ComputeArea` -error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -52,9 +48,9 @@ error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -63,9 +59,9 @@ error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -74,9 +70,9 @@ error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -85,9 +81,9 @@ error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -96,9 +92,9 @@ error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -107,9 +103,9 @@ error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -118,9 +114,9 @@ error[E0119]: conflicting implementations of trait `IsProviderFor` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -129,9 +125,9 @@ error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -140,9 +136,9 @@ error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -151,9 +147,9 @@ error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -162,9 +158,9 @@ error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -173,9 +169,9 @@ error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -184,9 +180,9 @@ error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `ComputeArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 6 | #[cgp_auto_dispatch] @@ -195,13 +191,13 @@ error[E0119]: conflicting implementations of trait `DelegateComponent tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 11 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ the trait `cgp::prelude::HasExtractor` is not implemented for `__Variants__` + | ^^^^^^^^^^^^^^^^^^^^ the trait `HasExtractor` is not implemented for `__Variants__` 12 | pub trait HasSurface { 13 | fn area(&self) -> f64; | ---- required by a bound introduced by this call @@ -226,7 +222,7 @@ help: consider further restricting type parameter `__Variants__` with trait `Has 12 | pub trait HasSurface + cgp::prelude::HasExtractor { | ++++++++++++++++++++++++++++ -error[E0277]: the trait bound `for<'__a__> UseInputDelegate>>: cgp::prelude::Computer<(), (), &'__a__ __Variants__>` is not satisfied +error[E0277]: the trait bound `for<'__a__> UseInputDelegate>>: Computer<(), (), &'__a__ __Variants__>` is not satisfied --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 11 | #[cgp_auto_dispatch] @@ -235,8 +231,8 @@ error[E0277]: the trait bound `for<'__a__> UseInputDelegate f64; | ---- required by a bound introduced by this call | - = help: the trait `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` is not implemented for `UseInputDelegate>>` - = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` + = help: the trait `for<'__a__> Computer<(), (), &'__a__ __Variants__>` is not implemented for `UseInputDelegate>>` + = note: required for `MatchWithValueHandlersRef` to implement `for<'__a__> Computer<(), (), &'__a__ __Variants__>` note: required for `__Variants__` to implement `HasArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 | @@ -254,19 +250,19 @@ note: required by a bound in `__compute_area__` = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement | -13 | fn area where for<'__a__> UseInputDelegate>>: cgp::prelude::Computer<(), (), &'__a__ __Variants__>(&self) -> f64; - | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +13 | fn area where for<'__a__> UseInputDelegate>>: Computer<(), (), &'__a__ __Variants__>(&self) -> f64; + | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -error[E0277]: the trait bound `for<'__a__> MatchWithHandlersRef<_>: cgp::prelude::Computer<(), (), &'__a__ __Variants__>` is not satisfied +error[E0277]: the trait bound `for<'__a__> MatchWithHandlersRef<_>: Computer<(), (), &'__a__ __Variants__>` is not satisfied --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:11:1 | 11 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ the trait `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` is not implemented for `MatchWithHandlersRef<_>` + | ^^^^^^^^^^^^^^^^^^^^ the trait `for<'__a__> Computer<(), (), &'__a__ __Variants__>` is not implemented for `MatchWithHandlersRef<_>` 12 | pub trait HasSurface { 13 | fn area(&self) -> f64; | ---- required by a bound introduced by this call | -help: the trait `cgp::prelude::Computer` is conditionally implemented for `MatchWithHandlersRef` +help: the trait `Computer` is conditionally implemented for `MatchWithHandlersRef` --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 | 12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer @@ -278,10 +274,10 @@ help: the trait `cgp::prelude::Computer` is conditionally 17 | | Computer, Output = Result>, 18 | | Remainder: FinalizeExtract, | |_______________________________^ - = note: required for `UseInputDelegate>>` to implement `for<'__a__> IsProviderFor` + = note: required for `UseInputDelegate>>` to implement `for<'__a__> IsProviderFor` = note: 1 redundant requirement hidden - = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` - = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` + = note: required for `MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` + = note: required for `MatchWithValueHandlersRef` to implement `for<'__a__> Computer<(), (), &'__a__ __Variants__>` note: required for `__Variants__` to implement `HasArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 | @@ -308,10 +304,10 @@ error[E0277]: the trait bound `__Variants__: HasArea` is not satisfied | ---- required by a bound introduced by this call | = note: required for `__Variants__` to implement `dispatch::providers::matchers::to_field_handlers::HasFieldHandlers>>` - = note: required for `UseInputDelegate>>` to implement `for<'__a__> IsProviderFor` + = note: required for `UseInputDelegate>>` to implement `for<'__a__> IsProviderFor` = note: 1 redundant requirement hidden - = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` - = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` + = note: required for `MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` + = note: required for `MatchWithValueHandlersRef` to implement `for<'__a__> Computer<(), (), &'__a__ __Variants__>` note: required for `__Variants__` to implement `HasArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 | @@ -341,10 +337,10 @@ error[E0277]: the trait bound `__Variants__: HasArea` is not satisfied 13 | fn area(&self) -> f64; | ---- required by a bound introduced by this call | - = note: required for `MatchWithHandlersRef<_>` to implement `for<'__a__> IsProviderFor` + = note: required for `MatchWithHandlersRef<_>` to implement `for<'__a__> IsProviderFor` = note: 2 redundant requirements hidden - = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` - = note: required for `cgp::prelude::MatchWithValueHandlersRef` to implement `for<'__a__> cgp::prelude::Computer<(), (), &'__a__ __Variants__>` + = note: required for `MatchWithValueHandlersRef` to implement `for<'__a__> IsProviderFor` + = note: required for `MatchWithValueHandlersRef` to implement `for<'__a__> Computer<(), (), &'__a__ __Variants__>` note: required for `__Variants__` to implement `HasArea` --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.rs:6:1 | diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs deleted file mode 100644 index 1a5eb1bb..00000000 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a supertrait is not carried onto the blanket impl. - -use cgp::prelude::*; - -#[derive(CgpData)] -pub enum Shape { - Circle(Circle), - Rectangle(Rectangle), -} - -pub struct Circle { - pub radius: f64, -} - -pub struct Rectangle { - pub width: f64, - pub height: f64, -} - -pub trait Named { - fn name(&self) -> String; -} - -#[cgp_auto_dispatch] -pub trait HasArea: Named { - fn area(&self) -> f64; -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.stderr deleted file mode 100644 index 0b53bdab..00000000 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.stderr +++ /dev/null @@ -1,16 +0,0 @@ -error[E0277]: the trait bound `__Variants__: Named` is not satisfied - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs:24:1 - | -24 | #[cgp_auto_dispatch] - | ^^^^^^^^^^^^^^^^^^^^ the trait `Named` is not implemented for `__Variants__` - | -note: required by a bound in `HasArea` - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_supertrait.rs:25:20 - | -25 | pub trait HasArea: Named { - | ^^^^^ required by this bound in `HasArea` - = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider further restricting type parameter `__Variants__` with trait `Named` - | -24 | #[cgp_auto_dispatch], __Variants__: Named - | +++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs deleted file mode 100644 index 7468a334..00000000 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a method needing two distinct lifetimes fails. - -use cgp::prelude::*; - -#[derive(CgpData)] -pub enum Shape { - Circle(Circle), - Rectangle(Rectangle), -} - -pub struct Circle { - pub radius: f64, -} - -pub struct Rectangle { - pub width: f64, - pub height: f64, -} - -#[cgp_auto_dispatch] -pub trait Lookup { - fn lookup<'a>(&'a self, key: &str) -> &'a str; -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.stderr deleted file mode 100644 index 47222205..00000000 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error[E0261]: use of undeclared lifetime name `'__a__` - --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_two_lifetimes.rs:20:1 - | -20 | #[cgp_auto_dispatch] - | -^^^^^^^^^^^^^^^^^^^ - | | - | undeclared lifetime - | lifetime `'__a__` is missing in item created through this procedural macro - | - = note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html - = note: this error originates in the attribute macro `cgp_auto_dispatch` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider making the bound lifetime-generic with a new `'__a__` lifetime - | -20 | for<'__a__> #[cgp_auto_dispatch] - | +++++++++++ -help: consider introducing lifetime `'__a__` here - | -20 | #[cgp_auto_dispatch]'__a__, - | +++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.rs new file mode 100644 index 00000000..c06ac8f4 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_auto_dispatch.md`, *Common Mistakes*: a typed receiver such as +//! `self: Box` is rejected, since no matcher takes it. + +use cgp::prelude::*; + +#[cgp_auto_dispatch] +pub trait HasArea { + fn area(self: Box) -> f64; +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.stderr new file mode 100644 index 00000000..e5ea68ac --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.stderr @@ -0,0 +1,5 @@ +error: Dispatcher method receiver must be `self`, `&self`, or `&mut self` + --> tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_typed_receiver.rs:8:13 + | +8 | fn area(self: Box) -> f64; + | ^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.rs new file mode 100644 index 00000000..40e21972 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: `impl Trait` in a parameter is +//! rejected; a generic parameter is the fix. + +use cgp::prelude::*; + +#[cgp_computer] +fn describe(value: impl core::fmt::Display) -> String { + value.to_string() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.stderr new file mode 100644 index 00000000..45ab754b --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.stderr @@ -0,0 +1,5 @@ +error: Computer function parameters cannot use `impl Trait`; declare a generic parameter instead + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_parameter.rs:7:20 + | +7 | fn describe(value: impl core::fmt::Display) -> String { + | ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.rs new file mode 100644 index 00000000..f58ec570 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: `impl Trait` in the return type is +//! rejected. + +use cgp::prelude::*; + +#[cgp_computer] +fn describe(value: u64) -> impl core::fmt::Display { + value +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.stderr new file mode 100644 index 00000000..f0505f40 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.stderr @@ -0,0 +1,5 @@ +error: Computer functions cannot return `impl Trait` + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_impl_trait_return.rs:7:28 + | +7 | fn describe(value: u64) -> impl core::fmt::Display { + | ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr index 7139823b..1029a6c0 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr @@ -4,11 +4,11 @@ error[E0271]: type mismatch resolving `::Error == String` 24 | let _ = CheckedAdd::try_compute(&App, PhantomData::<()>, (1, 2)); | ^^^^^^^^^^ expected `String`, found `u32` | - = note: required for `TryPromote` to implement `IsProviderFor` + = note: required for `TryPromote` to implement `IsProviderFor` = note: 1 redundant requirement hidden - = note: required for `CheckedAdd` to implement `IsProviderFor` + = note: required for `CheckedAdd` to implement `IsProviderFor` note: required by a bound in `cgp::prelude::TryComputer::try_compute` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/try_compute.rs:8:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/try_compute.rs:8:1 | 8 | #[cgp_component(TryComputer)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `TryComputer::try_compute` @@ -24,7 +24,7 @@ error[E0277]: the trait bound `TryPromote: TryComputer` is not implemented for `TryPromote` | help: the trait `TryComputer` is conditionally implemented for `TryPromote` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/providers/try_promote.rs:11:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/try_promote.rs:11:1 | 11 | / impl TryComputer 12 | | for TryPromote @@ -33,7 +33,7 @@ help: the trait `TryComputer` is conditionally implemented 15 | | Provider: Computer>, | |______________________________________________---------------------------------------_^ | | - | unsatisfied requirement introduced here: `>::Output == Result<_, ::Error>` + | unsatisfied requirement introduced here: `>::Output == Result<_, ::Error>` = note: required for `CheckedAdd` to implement `TryComputer` error[E0271]: type mismatch resolving `>::Output == Result` @@ -49,7 +49,7 @@ note: expected this to be `Result` | ^^^^^^^^^^^^^^^^^^^ = note: expected enum `Result` found enum `Result` - = note: required for `TryPromote` to implement `IsProviderFor` + = note: required for `TryPromote` to implement `IsProviderFor` = note: 1 redundant requirement hidden - = note: required for `CheckedAdd` to implement `IsProviderFor` + = note: required for `CheckedAdd` to implement `IsProviderFor` = note: required for `CheckedAdd` to implement `TryComputer` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr index af995f3a..1de3fe97 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr @@ -10,14 +10,14 @@ help: the trait `DelegateComponent` is not implement 14 | pub struct App; | ^^^^^^^^^^^^^^ = help: the following other types implement trait `DelegateComponent`: - `Add` implements `DelegateComponent` - `Add` implements `DelegateComponent` - `Add` implements `DelegateComponent` - `Add` implements `DelegateComponent` - `Add` implements `DelegateComponent` - `Add` implements `DelegateComponent` - `Add` implements `DelegateComponent` - `BuildAndMergeOutputs` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `Add` implements `DelegateComponent` + `BuildAndMergeOutputs` implements `DelegateComponent` and $N others = note: required for `App` to implement `ErrorTypeProvider` @@ -33,14 +33,14 @@ help: the trait `IsProviderFor` is not implemen 14 | pub struct App; | ^^^^^^^^^^^^^^ = help: the following other types implement trait `IsProviderFor`: - `Add` implements `IsProviderFor` - `Add` implements `IsProviderFor` - `Add` implements `IsProviderFor` - `Add` implements `IsProviderFor` - `Add` implements `IsProviderFor` - `Add` implements `IsProviderFor` - `Add` implements `IsProviderFor` - `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` + `Add` implements `IsProviderFor` and $N others = note: required for `App` to implement `ErrorTypeProvider` @@ -51,7 +51,7 @@ error[E0277]: the trait bound `Promote: TryComputer` i | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TryComputer` is not implemented for `Promote` | help: the trait `TryComputer` is conditionally implemented for `Promote` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/providers/promote.rs:23:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/promote.rs:23:1 | 23 | / impl TryComputer for Promote 24 | | where diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs new file mode 100644 index 00000000..63b8e72e --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: a type parameter used only in the +//! return type is not constrained by the generated impl (`E0207`). + +use cgp::prelude::*; + +#[cgp_computer] +fn parse(value: String) -> Option { + value.parse().ok() +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr new file mode 100644 index 00000000..0c88b29c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr @@ -0,0 +1,18 @@ +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs:7:10 + | +7 | fn parse(value: String) -> Option { + | ^ unconstrained type parameter + | +help: use the type parameter `T` in the `Parse` type and use it in the type definition + | +7 | fn parse(value: String) -> Option { + | +++ + +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs:7:10 + | +6 | #[cgp_computer] + | --------------- help: remove the unused type parameter `T` +7 | fn parse(value: String) -> Option { + | ^ unconstrained type parameter diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.stderr index 2b04cddb..a141276f 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.stderr @@ -2,4 +2,4 @@ error: Computer functions cannot have a receiver --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_receiver.rs:9:12 | 9 | fn add(&self, a: u64, b: u64) -> u64 { - | ^ + | ^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs index c11053ad..4e3715b9 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs @@ -1,5 +1,5 @@ -//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: a one-argument `Result` alias fails -//! to parse, because the macro expects `Result`. +//! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: a one-argument `Result` alias is +//! rejected, because the macro selects the fallible bundle only for `Result`. use cgp::prelude::*; diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr index e8b6f4b7..ec062d23 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.stderr @@ -1,5 +1,5 @@ -error: expected `,` - --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs:9:35 +error: A `Result` return type must be written as `Result`, naming its error type + --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_single_argument_result_alias.rs:9:25 | 9 | fn halve(value: u64) -> Result { - | ^ + | ^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.stderr b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.stderr index bcb0cbc0..6b1467fc 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.stderr @@ -2,4 +2,4 @@ error: Producer functions must have empty generic parameters --> tests/compile_fail/reference/macros/cgp_producer_common_mistakes_generics.rs:6:18 | 6 | fn default_value() -> T { - | ^ + | ^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.rs b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.rs new file mode 100644 index 00000000..54e0b3af --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.rs @@ -0,0 +1,11 @@ +//! `docs/reference/macros/cgp_producer.md`, *Common Mistakes*: `impl Trait` in the return type is +//! rejected. + +use cgp::prelude::*; + +#[cgp_producer] +fn magic_number() -> impl core::fmt::Display { + 42 +} + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.stderr b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.stderr new file mode 100644 index 00000000..a2365a4d --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.stderr @@ -0,0 +1,5 @@ +error: Producer functions cannot return `impl Trait` + --> tests/compile_fail/reference/macros/cgp_producer_common_mistakes_impl_trait_return.rs:7:22 + | +7 | fn magic_number() -> impl core::fmt::Display { + | ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.stderr b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.stderr index 77ffd6c2..442b3d78 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.stderr @@ -2,4 +2,4 @@ error: Producer functions cannot have parameters --> tests/compile_fail/reference/macros/cgp_producer_common_mistakes_parameters.rs:6:17 | 6 | fn magic_number(seed: u64) -> u64 { - | ^^^^ + | ^^^^^^^^^ From 9a81323391a0c55e8609d03210069b03e5dd627f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 4 Oct 2026 14:16:32 +0000 Subject: [PATCH 152/516] Mirror the new claims on the computer, producer, and dispatch pages The pages now state behaviour the `example-code` mirrors did not check: the unrawed default name of a computer or producer named with a raw identifier, and a dispatch trait with a supertrait, named and elided lifetimes, and a default body, plus the `label` example's elided lifetimes under *Under the hood*. Each gets a test in its page's mirror. Like the compile-fail fixtures, they need the `cgp` extra-macro refactor and pass against it through a local path patch. Co-Authored-By: Claude Opus 5.5 --- .../reference/macros/cgp_auto_dispatch.rs | 98 ++++++++++++++++++- .../tests/reference/macros/cgp_computer.rs | 21 +++- .../tests/reference/macros/cgp_producer.rs | 20 +++- 3 files changed, 133 insertions(+), 6 deletions(-) diff --git a/example-code/tests/reference/macros/cgp_auto_dispatch.rs b/example-code/tests/reference/macros/cgp_auto_dispatch.rs index 29c22177..f1dee64f 100644 --- a/example-code/tests/reference/macros/cgp_auto_dispatch.rs +++ b/example-code/tests/reference/macros/cgp_auto_dispatch.rs @@ -94,8 +94,9 @@ pub mod examples { /// ## Usage /// -/// The shapes the page lists in prose: a by-value `self`, an `async` method, and a trait generic -/// parameter, each dispatched over one enum. +/// The shapes the page lists in prose: a by-value `self`, an `async` method, a trait generic +/// parameter, a supertrait, named and elided lifetimes, and a default body, each dispatched over one +/// enum. pub mod usage { use cgp::prelude::*; @@ -159,6 +160,63 @@ pub mod usage { } } + /// A supertrait, which the enum provides by dispatching it too. + #[cgp_auto_dispatch] + pub trait HasName { + fn name(&self) -> String; + } + + #[cgp_auto_dispatch] + pub trait CanGreet: HasName { + fn greet(&self) -> String; + } + + impl HasName for Word { + fn name(&self) -> String { + self.0.clone() + } + } + + impl HasName for Number { + fn name(&self) -> String { + self.0.to_string() + } + } + + impl CanGreet for Word { + fn greet(&self) -> String { + format!("hello, {}", self.name()) + } + } + + impl CanGreet for Number { + fn greet(&self) -> String { + format!("number {}", self.name()) + } + } + + /// Named and elided lifetimes, and a default body. + #[cgp_auto_dispatch] + pub trait CanPick { + fn pick<'a>(&'a self, fallback: &'a str) -> &'a str; + + fn first_char(&self, text: Option<&str>) -> Option { + text.and_then(|text| text.chars().next()) + } + } + + impl CanPick for Word { + fn pick<'a>(&'a self, _fallback: &'a str) -> &'a str { + &self.0 + } + } + + impl CanPick for Number { + fn pick<'a>(&'a self, fallback: &'a str) -> &'a str { + fallback + } + } + #[test] fn every_listed_shape_dispatches() { assert_eq!(Token::Number(Number(12)).into_text(), "12"); @@ -167,14 +225,17 @@ pub mod usage { 3 ); assert_eq!(Token::Word(Word("w".to_owned())).render('#'), "#w"); + assert_eq!(Token::Number(Number(7)).greet(), "number 7"); + assert_eq!(Token::Number(Number(7)).pick("none"), "none"); + assert_eq!(Token::Number(Number(7)).first_char(Some("xy")), Some('x')); } } /// ## Under the hood /// /// The helper's reserved name: a free function called `area` beside the trait does not clash with -/// the `__compute_area__` helper the macro emits for the `area` method, and a raw method name -/// yields valid generated names. +/// the `__compute_area__` helper the macro emits for the `area` method, a raw method name yields +/// valid generated names, and the `label` example's elided lifetimes keep their meaning. pub mod under_the_hood { use cgp::prelude::*; @@ -232,6 +293,35 @@ pub mod under_the_hood { } } + /// The elided-lifetime example: the returned borrow takes the receiver's lifetime, so it + /// outlives a shorter-lived `suffix`. + #[cgp_auto_dispatch] + pub trait CanLabel { + fn label(&self, suffix: &str) -> &str; + } + + impl CanLabel for Circle { + fn label(&self, _suffix: &str) -> &str { + "circle" + } + } + + impl CanLabel for Rectangle { + fn label(&self, _suffix: &str) -> &str { + "rectangle" + } + } + + #[test] + fn the_returned_borrow_outlives_the_argument() { + let shape = Shape::Circle(Circle { radius: 1.0 }); + let label = { + let suffix = String::from("!"); + shape.label(&suffix) + }; + assert_eq!(label, "circle"); + } + #[test] fn a_raw_method_name_dispatches() { assert_eq!(Shape::Circle(Circle { radius: 1.0 }).r#type(), "circle"); diff --git a/example-code/tests/reference/macros/cgp_computer.rs b/example-code/tests/reference/macros/cgp_computer.rs index 345fc8c7..da7a5055 100644 --- a/example-code/tests/reference/macros/cgp_computer.rs +++ b/example-code/tests/reference/macros/cgp_computer.rs @@ -4,7 +4,8 @@ /// ## Usage /// -/// The default and the explicit provider name, in separate modules since both define `add`. +/// The default and the explicit provider name, in separate modules since both define `add`, and the +/// default for a raw function name. pub mod usage { pub mod default_name { use core::marker::PhantomData; @@ -61,6 +62,24 @@ pub mod usage { assert_eq!(MyAdder::compute(&(), PhantomData::<()>, (1, 2)), 3); } } + + /// A raw function name, which the page says loses its `r#`: `r#type` names `Type`. + pub mod raw_name { + use core::marker::PhantomData; + + use cgp::extra::handler::Computer; + use cgp::prelude::*; + + #[cgp_computer] + fn r#type(value: u64) -> u64 { + value + 1 + } + + #[test] + fn the_raw_prefix_is_dropped() { + assert_eq!(Type::compute(&(), PhantomData::<()>, 1), 2); + } + } } /// ### What the two axes select diff --git a/example-code/tests/reference/macros/cgp_producer.rs b/example-code/tests/reference/macros/cgp_producer.rs index 1ab648c6..10720755 100644 --- a/example-code/tests/reference/macros/cgp_producer.rs +++ b/example-code/tests/reference/macros/cgp_producer.rs @@ -5,7 +5,7 @@ /// ## Usage /// /// The default and explicit provider names, each in its own module since both define -/// `magic_number`. +/// `magic_number`, and the default for a raw function name. pub mod usage { pub mod default_name { use core::marker::PhantomData; @@ -56,6 +56,24 @@ pub mod usage { assert_eq!(TheAnswer::produce(&(), PhantomData::<()>), 42); } } + + /// A raw function name, which the page says loses its `r#`: `r#loop` names `Loop`. + pub mod raw_name { + use core::marker::PhantomData; + + use cgp::extra::handler::Producer; + use cgp::prelude::*; + + #[cgp_producer] + fn r#loop() -> u64 { + 42 + } + + #[test] + fn the_raw_prefix_is_dropped() { + assert_eq!(Loop::produce(&(), PhantomData::<()>), 42); + } + } } /// ## Examples From 39000aa87c12f3b457f6c74fe603ec5e86ca39dd Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 4 Oct 2026 14:29:42 +0000 Subject: [PATCH 153/516] Re-bless example-code against cgp with the extra-macro refactor merged Re-bless the compile-fail fixtures against `cgp` at `52bcaf7`, the merge of the extra-macro refactor (#274); the crate's lock file is not tracked, so a fresh checkout resolves the git dependency to that commit or later. Every changed `.stderr` differs only in the `cgp` checkout path it quotes, or in rustc printing a CGP name without the `cgp::prelude::` path, now that the macros qualify every name; the fixtures for the computer, producer, and dispatch pages, blessed earlier against the local branch, now quote the git checkout as well. The whole crate's tests pass. The extensible-variants mirror imported `Computer` only because the old `#[cgp_computer]` expansion named it unqualified; that import is now unused and removed. The page itself never showed it. Co-Authored-By: Claude Opus 5.5 --- ...onadic_handlers_plain_composition_is_wrong.stderr | 12 ++++++------ ...fault_impl_common_mistakes_table_parameter.stderr | 2 +- .../use_provider_usage_component_trait.stderr | 2 +- .../use_type_common_mistakes_misspelled.stderr | 2 +- ...uild_field_rejected_read_of_an_unset_field.stderr | 2 +- ...p_variant_common_mistakes_reserved_variant.stderr | 2 +- ...act_field_common_mistakes_reserved_variant.stderr | 2 +- ..._extract_field_rejected_premature_finalize.stderr | 2 +- ...m_variant_common_mistakes_reserved_variant.stderr | 2 +- ...as_fields_common_mistakes_reserved_variant.stderr | 2 +- ...to_dispatch_common_mistakes_missing_derive.stderr | 4 ++-- ...patch_common_mistakes_missing_variant_impl.stderr | 2 +- ...ispatch_common_mistakes_shared_method_name.stderr | 2 +- ...getter_common_mistakes_field_name_mismatch.stderr | 2 +- ...uter_common_mistakes_mismatched_error_type.stderr | 4 ++-- ...omputer_common_mistakes_missing_error_type.stderr | 2 +- ...r_common_mistakes_use_field_on_two_methods.stderr | 8 ++++---- ...erge_outputs_common_mistakes_ref_component.stderr | 8 ++++---- ...ith_handlers_common_mistakes_fallible_slot.stderr | 2 +- ...ers_common_mistakes_borrowed_fallible_slot.stderr | 2 +- ...alue_handlers_common_mistakes_struct_input.stderr | 4 ++-- .../raise_from_common_mistakes_missing_from.stderr | 2 +- ..._field_common_mistakes_multi_method_getter.stderr | 8 ++++---- ..._examples_bare_use_field_on_type_component.stderr | 8 ++++---- ...th_field_ref_common_mistakes_unsized_value.stderr | 4 ++-- ...elds_common_mistakes_downcast_on_remainder.stderr | 2 +- ...ze_with_default_common_mistakes_no_default.stderr | 2 +- ...ult_common_mistakes_optional_needs_default.stderr | 2 +- ...xtract_field_common_mistakes_extract_twice.stderr | 2 +- ...ize_extract_common_mistakes_finalize_early.stderr | 2 +- ...ract_result_common_mistakes_missing_import.stderr | 2 +- ...ract_result_common_mistakes_one_step_early.stderr | 2 +- ...p_fields_common_mistakes_output_not_mapped.stderr | 2 +- .../static_string_common_mistakes_bare_chars.stderr | 2 +- ..._optional_common_mistakes_already_optional.stderr | 2 +- .../reference/types/life_definition_not_send.stderr | 4 ++-- ...d_common_mistakes_match_behind_a_reference.stderr | 2 +- example-code/tests/concepts/extensible_variants.rs | 2 +- 38 files changed, 60 insertions(+), 60 deletions(-) diff --git a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr index e4b06044..b19d2d4b 100644 --- a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr +++ b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr @@ -4,19 +4,19 @@ error[E0599]: the associated function or constant `compute` exists for struct `P 12 | let _ = PipeHandlers::::compute(&(), PhantomData::<()>, 1u8); | ^^^^^^^ associated function or constant cannot be called due to unsatisfied trait bounds | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/providers/pipe.rs:7:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/providers/pipe.rs:7:1 | 7 | pub struct PipeHandlers(pub PhantomData); | ---------------------------------- doesn't satisfy `_: Computer<_, _, _>` or `_: IsProviderFor` | = note: the following trait bounds were not satisfied: - `PipeHandlers>>: IsProviderFor` + `PipeHandlers>>: IsProviderFor` which is required by `PipeHandlers>>: Computer<_, _, _>` - `&PipeHandlers>>: DelegateComponent` + `&PipeHandlers>>: DelegateComponent` which is required by `&PipeHandlers>>: Computer<_, _, _>` - `&PipeHandlers>>: IsProviderFor` + `&PipeHandlers>>: IsProviderFor` which is required by `&PipeHandlers>>: Computer<_, _, _>` - `&mut PipeHandlers>>: DelegateComponent` + `&mut PipeHandlers>>: DelegateComponent` which is required by `&mut PipeHandlers>>: Computer<_, _, _>` - `&mut PipeHandlers>>: IsProviderFor` + `&mut PipeHandlers>>: IsProviderFor` which is required by `&mut PipeHandlers>>: Computer<_, _, _>` diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr index f6f65d9b..923db29d 100644 --- a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr @@ -5,7 +5,7 @@ error[E0107]: trait takes 2 generic arguments but 3 generic arguments were suppl | ^^^^^^^^^^^^^ expected 2 generic arguments | note: trait defined here, with 2 generic parameters: `T`, `Components` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-component/src/namespaces.rs:5:11 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-component/src/namespaces.rs:5:11 | 5 | pub trait DefaultImpls1 { | ^^^^^^^^^^^^^ - ---------- diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr index 88a524b8..3cca527f 100644 --- a/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr @@ -4,7 +4,7 @@ error: cannot find attribute `use_provider` in this scope 22 | #[use_provider(RectangleArea: AreaCalculator)] | ^^^^^^^^^^^^ | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/macros/cgp-macro/src/lib.rs:135:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/macros/cgp-macro/src/lib.rs:135:1 | 135 | pub fn cgp_provider(attr: TokenStream, item: TokenStream) -> TokenStream { | ------------------------------------------------------------------------ similarly named attribute macro `cgp_provider` defined here diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr index 79920408..04ae1fb0 100644 --- a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr @@ -4,7 +4,7 @@ error[E0576]: cannot find associated type `Eror` in trait `HasErrorType` 16 | pub fn fail(&self) -> Result<(), Eror> { | ^^^^ | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-error/src/traits/has_error_type.rs:28:5 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-error/src/traits/has_error_type.rs:28:5 | 28 | type Error: Debug; | ----------------- similarly named associated type `Error` defined here diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr index f8e5e7bd..22203515 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr @@ -9,7 +9,7 @@ error[E0308]: mismatched types = note: expected struct `std::marker::PhantomData>>>>>>>>>>>` found struct `std::marker::PhantomData>>>>>>>>>>` note: method defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/has_field.rs:49:8 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/has_field.rs:49:8 | 49 | fn get_field(&self, _tag: PhantomData) -> &Self::Value; | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr index ae20c25c..c5b23323 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr @@ -10,7 +10,7 @@ note: `Remainder` could refer to the variant defined here 7 | #[derive(CgpVariant)] | ^^^^^^^^^^ note: `Remainder` could also refer to the associated type defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:33:5 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:33:5 | 33 | type Remainder; | ^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr index 4e88983e..5e58a7bc 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr @@ -10,7 +10,7 @@ note: `Value` could refer to the variant defined here 10 | #[derive(ExtractField)] | ^^^^^^^^^^^^ note: `Value` could also refer to the associated type defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:31:5 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:31:5 | 31 | type Value; | ^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr index 00df801a..7ca57677 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr @@ -22,7 +22,7 @@ error[E0599]: the method `finalize_extract_result` exists for enum `Result: FinalizeExtract` which is required by `Result>: FinalizeExtractResult` note: the trait `FinalizeExtract` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:38:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:38:1 | 38 | pub trait FinalizeExtract { | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr index 1df1f07b..7d66de11 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr @@ -10,7 +10,7 @@ note: `Value` could refer to the variant defined here 8 | Value(Payload), | ^^^^^ note: `Value` could also refer to the associated type defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/from_variant.rs:4:5 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/from_variant.rs:4:5 | 4 | type Value; | ^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr index 2a65b6a1..d67b3d82 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr @@ -10,7 +10,7 @@ note: `Fields` could refer to the variant defined here 6 | Fields(u8), | ^^^^^^ note: `Fields` could also refer to the associated type defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/has_fields.rs:2:5 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/has_fields.rs:2:5 | 2 | type Fields; | ^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr index cb4bd16d..3e26f506 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr @@ -7,7 +7,7 @@ error[E0599]: the method `area` exists for reference `&Plain`, but its trait bou 36 | shape.area() | ^^^^ method cannot be called on `&Plain` due to unsatisfied trait bounds | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 | 19 | pub struct MatchWithValueHandlersRef(pub PhantomData); | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Plain>>::Output = f64`, `<_ as Computer<(), (), &Plain>>::Output = f64`, `_: Computer<(), (), &&Plain>` or `_: Computer<(), (), &Plain>` @@ -26,7 +26,7 @@ note: the following trait bounds were not satisfied: 25 | pub trait HasArea { | ------- note: the trait `HasExtractor` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:6:1 | 6 | pub trait HasExtractor { | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr index 0c0ba666..bd873693 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr @@ -7,7 +7,7 @@ error[E0599]: the method `area` exists for reference `&Shape`, but its trait bou 32 | shape.area() | ^^^^ method cannot be called on `&Shape` due to unsatisfied trait bounds | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 | 19 | pub struct MatchWithValueHandlersRef(pub PhantomData); | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Shape>>::Output = f64`, `<_ as Computer<(), (), &Shape>>::Output = f64`, `_: Computer<(), (), &&Shape>` or `_: Computer<(), (), &Shape>` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr index d3e80782..509df97a 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr @@ -263,7 +263,7 @@ error[E0277]: the trait bound `for<'__a__> MatchWithHandlersRef<_>: Computer<(), | ---- required by a bound introduced by this call | help: the trait `Computer` is conditionally implemented for `MatchWithHandlersRef` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 | 12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer 13 | | for MatchWithHandlersRef diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr index ede1d1c2..54825f49 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr @@ -19,7 +19,7 @@ note: the following trait bounds were not satisfied: 6 | pub trait HasName { | ^^^^^^^ note: the trait `cgp::prelude::HasField` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/has_field.rs:46:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/has_field.rs:46:1 | 46 | pub trait HasField { | ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr index 1029a6c0..a36c9d7c 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr @@ -8,7 +8,7 @@ error[E0271]: type mismatch resolving `::Error == String` = note: 1 redundant requirement hidden = note: required for `CheckedAdd` to implement `IsProviderFor` note: required by a bound in `cgp::prelude::TryComputer::try_compute` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/try_compute.rs:8:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/try_compute.rs:8:1 | 8 | #[cgp_component(TryComputer)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `TryComputer::try_compute` @@ -24,7 +24,7 @@ error[E0277]: the trait bound `TryPromote: TryComputer` is not implemented for `TryPromote` | help: the trait `TryComputer` is conditionally implemented for `TryPromote` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/try_promote.rs:11:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/providers/try_promote.rs:11:1 | 11 | / impl TryComputer 12 | | for TryPromote diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr index 1de3fe97..e861b739 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr @@ -51,7 +51,7 @@ error[E0277]: the trait bound `Promote: TryComputer` i | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TryComputer` is not implemented for `Promote` | help: the trait `TryComputer` is conditionally implemented for `Promote` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/promote.rs:23:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/providers/promote.rs:23:1 | 23 | / impl TryComputer for Promote 24 | | where diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr index e0d98ed7..6b6f84ff 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 | 31 | / impl AsyncComputer for UseField 32 | | where @@ -14,7 +14,7 @@ help: the following other types implement trait `IsProviderFor, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_field.rs:69:1 | 69 | / impl IsProviderFor 70 | | for UseField @@ -22,7 +22,7 @@ help: the following other types implement trait `IsProviderFor, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/computer.rs:29:1 | 29 | / impl Computer for UseField 30 | | where @@ -30,7 +30,7 @@ help: the following other types implement trait `IsProviderFor, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 | 5 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` diff --git a/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr index 0d77835f..8ce68304 100644 --- a/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr +++ b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `BuildWithHandlers` is not implemented for `BuildWithHandlers, Cons, Nil>>>` help: `BuildWithHandlers` implements trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/with_handlers/build_with_handlers.rs:10:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/build_with_handlers.rs:10:1 | 10 | / impl Computer 11 | | for BuildWithHandlers @@ -14,7 +14,7 @@ help: `BuildWithHandlers` implements trait `IsProviderFor, 14 | | PipeHandlers: Computer, 15 | | Res: FinalizeBuild, - | |________________________________________^ `IsProviderFor` + | |________________________________________^ `IsProviderFor` ... 25 | / impl TryComputer 26 | | for BuildWithHandlers @@ -23,7 +23,7 @@ help: `BuildWithHandlers` implements trait `IsProviderFor, 30 | | PipeHandlers: TryComputer, 31 | | Res: FinalizeBuild, - | |________________________________________^ `IsProviderFor` + | |________________________________________^ `IsProviderFor` ... 45 | / impl Handler 46 | | for BuildWithHandlers @@ -32,7 +32,7 @@ help: `BuildWithHandlers` implements trait `IsProviderFor, 50 | | PipeHandlers: Handler, 51 | | Res: FinalizeBuild, - | |________________________________________^ `IsProviderFor` + | |________________________________________^ `IsProviderFor` = note: required for `BuildAndMergeOutputs>>` to implement `IsProviderFor` = note: required for `AppBuilder` to implement `CanUseComponent` note: required by a bound in `__CheckAppBuilder` diff --git a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr index 6dfcf506..29a3991a 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `MatchWithHandlers` is not implemented for `MatchWithHandlers>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` help: `MatchWithHandlers` implements trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 | 12 | / impl Computer 13 | | for MatchWithHandlers diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr index 265c0bfe..a5444d61 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `MatchWithHandlersRef` is not implemented for `MatchWithHandlersRef>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` help: `MatchWithHandlersRef` implements trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 | 12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer 13 | | for MatchWithHandlersRef diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr index c8fe7f64..f944f70e 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr @@ -5,7 +5,7 @@ error[E0277]: the trait bound `MatchWithHandlers<_>: cgp::prelude::Computer` is not implemented for `MatchWithHandlers<_>` | help: the trait `cgp::prelude::Computer` is conditionally implemented for `MatchWithHandlers` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 | 12 | / impl Computer 13 | | for MatchWithHandlers @@ -37,7 +37,7 @@ error[E0277]: the trait bound `Cons>>` is not implemented for `Cons>>>>>>, Circle>, Cons>>>>>>>>>, Rectangle>, Nil>>` help: the following other types implement trait `dispatch::providers::matchers::to_field_handlers::ToFieldHandlers` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-dispatch/src/providers/matchers/to_field_handlers.rs:25:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/matchers/to_field_handlers.rs:25:1 | 25 | / impl ToFieldHandlers for Either, RestFields> 26 | | where diff --git a/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr b/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr index 074d743a..c6d14689 100644 --- a/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr +++ b/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr @@ -5,7 +5,7 @@ error[E0277]: the trait bound `RaiseFrom: ErrorRaiser` is no | ^^^^^^^^^^^^^^^^^^^ the trait `ErrorRaiser` is not implemented for `RaiseFrom` | help: the trait `ErrorRaiser` is conditionally implemented for `RaiseFrom` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-error-extra/src/impls/raise_from.rs:5:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-error-extra/src/impls/raise_from.rs:5:1 | 5 | / impl ErrorRaiser for RaiseFrom 6 | | where diff --git a/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr index 46d516c4..027a9953 100644 --- a/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr +++ b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 | 31 | / impl AsyncComputer for UseField 32 | | where @@ -14,7 +14,7 @@ help: the following other types implement trait `IsProviderFor, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_field.rs:69:1 | 69 | / impl IsProviderFor 70 | | for UseField @@ -22,7 +22,7 @@ help: the following other types implement trait `IsProviderFor, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/computer.rs:29:1 | 29 | / impl Computer for UseField 30 | | where @@ -30,7 +30,7 @@ help: the following other types implement trait `IsProviderFor, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 | 5 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` diff --git a/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr index 5c33041c..5f42a92a 100644 --- a/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr +++ b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 | 31 | / impl AsyncComputer for UseField 32 | | where @@ -14,7 +14,7 @@ help: the following other types implement trait `IsProviderFor, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_field.rs:69:1 | 69 | / impl IsProviderFor 70 | | for UseField @@ -22,7 +22,7 @@ help: the following other types implement trait `IsProviderFor, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/computer.rs:29:1 | 29 | / impl Computer for UseField 30 | | where @@ -30,7 +30,7 @@ help: the following other types implement trait `IsProviderFor, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 | 5 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` diff --git a/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr index f0c6977b..a7adbee2 100644 --- a/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr +++ b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr @@ -10,7 +10,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t | = help: the trait `Sized` is not implemented for `str` note: required by an implicit `Sized` bound in `UseFieldRef` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_ref.rs:7:29 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_ref.rs:7:29 | 7 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); | ^^^^^ required by the implicit `Sized` requirement on this type parameter in `UseFieldRef` @@ -77,7 +77,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t | = help: the trait `Sized` is not implemented for `str` note: required by an implicit `Sized` bound in `UseFieldRef` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/impls/use_ref.rs:7:29 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_ref.rs:7:29 | 7 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); | ^^^^^ required by the implicit `Sized` requirement on this type parameter in `UseFieldRef` diff --git a/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr index f1eb8bd2..8d922512 100644 --- a/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr @@ -21,7 +21,7 @@ error[E0599]: the method `downcast` exists for enum `__PartialFooBarBaz: HasExtractor` which is required by `&mut __PartialFooBarBaz: CanDowncast<_>` note: the trait `HasExtractor` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:6:1 | 6 | pub trait HasExtractor { | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr index 8fae6bdf..283110cd 100644 --- a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr @@ -28,7 +28,7 @@ error[E0599]: the method `finalize_with_default` exists for struct `__PartialSer `&mut __PartialServer: TransformMapFields` which is required by `&mut __PartialServer: CanFinalizeWithDefault` note: the trait `TransformMapFields` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/transform_map.rs:12:1 | 12 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr index 6b7c3805..7b0260c4 100644 --- a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr @@ -27,7 +27,7 @@ error[E0599]: the method `finalize_with_default` exists for struct `__PartialSer `&mut __PartialServer: TransformMapFields` which is required by `&mut __PartialServer: CanFinalizeWithDefault` note: the trait `TransformMapFields` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/transform_map.rs:12:1 | 12 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr index b45a3ba3..3d7c5efa 100644 --- a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr @@ -9,7 +9,7 @@ error[E0308]: mismatched types = note: expected struct `std::marker::PhantomData>>>>>>>>>>` found struct `std::marker::PhantomData>>>>>>>` note: method defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:35:8 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:35:8 | 35 | fn extract_field(self, _tag: PhantomData) -> Result; | ^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr index e91affe1..cb81290d 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr @@ -8,7 +8,7 @@ error[E0599]: no method named `finalize_extract` found for enum `__PartialShape< | ^^^^^^^^^^^^^^^^ method not found in `__PartialShape` | note: the method `finalize_extract` exists on the type `::Map` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:39:5 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:39:5 | 39 | fn finalize_extract(self) -> T; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr index bfb8d935..d3304cce 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr @@ -10,7 +10,7 @@ error[E0599]: no method named `finalize_extract_result` found for enum `Result Self::Output; | ----------------------- the method is available for `Result>` here diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr index efdbd2a1..4501820a 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr @@ -22,7 +22,7 @@ error[E0599]: the method `finalize_extract_result` exists for enum `Result: FinalizeExtract` which is required by `Result>: FinalizeExtractResult` note: the trait `FinalizeExtract` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/extract_field.rs:38:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:38:1 | 38 | pub trait FinalizeExtract { | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr index be482646..bc2f7044 100644 --- a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr +++ b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr @@ -4,7 +4,7 @@ error[E0576]: cannot find associated type `Output` in trait `MapFields` 5 | pub type Mapped = >::Output; | ^^^^^^ not found in `MapFields` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/map_fields.rs:5:5 + ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/map_fields.rs:5:5 | 5 | type Mapped; | ----------- associated type `Mapped` defined here diff --git a/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr index 14f1765d..bd839a7a 100644 --- a/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr +++ b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `cgp::prelude::Chars<'a', cgp::prelude::Nil>: Stat | = help: the trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` is not implemented for `cgp::prelude::Chars<'a', cgp::prelude::Nil>` help: the following other types implement trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/static_string.rs:29:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/static_string.rs:29:1 | 29 | / impl StaticBytes for Symbol 30 | | where diff --git a/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr index 80ad72a1..2477e95b 100644 --- a/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr +++ b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr @@ -15,7 +15,7 @@ error[E0599]: the method `to_optional` exists for struct `__PartialContext: TransformMapFields` which is required by `&mut __PartialContext: cgp::cgp_extra::cgp_field_extra::impls::ToOptional` note: the trait `TransformMapFields` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/transform_map.rs:12:1 | 12 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr index 6bc3014f..6b1c3cfa 100644 --- a/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr +++ b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr @@ -11,7 +11,7 @@ note: required because it appears within the type `PhantomData<*mut &'static ()> | pub struct PhantomData; | ^^^^^^^^^^^ note: required because it appears within the type `cgp::prelude::Life<'static>` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/types/life.rs:3:12 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/types/life.rs:3:12 | 3 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); | ^^^^ @@ -34,7 +34,7 @@ note: required because it appears within the type `PhantomData<*mut &'static ()> | pub struct PhantomData; | ^^^^^^^^^^^ note: required because it appears within the type `cgp::prelude::Life<'static>` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/types/life.rs:3:12 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/types/life.rs:3:12 | 3 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); | ^^^^ diff --git a/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr index 8104bcba..4ce370b4 100644 --- a/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr +++ b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr @@ -5,7 +5,7 @@ error[E0004]: non-exhaustive patterns: `&cgp::prelude::Either::Right(cgp::prelud | ^^^^^ pattern `&cgp::prelude::Either::Right(cgp::prelude::Either::Right(_))` not covered | note: `cgp::prelude::Either>` defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/0bf713d/crates/core/cgp-field/src/types/sum.rs:27:1 + --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/types/sum.rs:27:1 | 27 | pub enum Either { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/concepts/extensible_variants.rs b/example-code/tests/concepts/extensible_variants.rs index 40b9020b..b08f657e 100644 --- a/example-code/tests/concepts/extensible_variants.rs +++ b/example-code/tests/concepts/extensible_variants.rs @@ -47,7 +47,7 @@ pub mod one_handler_per_variant { use cgp::core::error::ErrorTypeProviderComponent; use cgp::extra::dispatch::MatchWithFieldHandlers; - use cgp::extra::handler::{Computer, ComputerComponent}; + use cgp::extra::handler::ComputerComponent; use cgp::prelude::*; #[derive(Debug, Eq, PartialEq, CgpData)] From 8307845cc8ee50edeaab497a56130334af7b9c4a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 4 Oct 2026 14:46:45 +0000 Subject: [PATCH 154/516] Update cgp-skills --- cgp-skills | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgp-skills b/cgp-skills index 51d37f68..bc45a587 160000 --- a/cgp-skills +++ b/cgp-skills @@ -1 +1 @@ -Subproject commit 51d37f68b8d47e28e97220363ae93deaa6f47227 +Subproject commit bc45a587447774663d3f556cde1efad8d6e87701 From bc2926323a2fd56183077a7444a0d3cef8c7d5e6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 4 Oct 2026 15:23:01 +0000 Subject: [PATCH 155/516] Update blog post draft --- blog/2026-05-10-v0.8.0-release.md | 87 +++++++++++++++++++++++++++++-- docs/cargo-cgp/check.md | 9 +--- docs/cargo-cgp/index.md | 1 + 3 files changed, 87 insertions(+), 10 deletions(-) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index e3e5e3cd..74e5d217 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -7,16 +7,97 @@ description: 'CGP v0.8.0 groups components with namespaces and paths, so a wirin # CGP v0.8.0 - Grouping components with namespaces and paths -**CGP v0.8.0** has been released, and it comes with major ergonomic improvements to manage CGP components at scale. In this blog post, we will explore the problems with managing CGP components, and how the new namespace feature in CGP v0.8.0 helps solve the problem. +**CGP v0.8.0** has been released, and it comes with major ergonomic improvements to Context-Generic Programming (CGP) in the following area: + +- Improved error diagnostics with cargo-cgp +- AI-assisted development with `/cgp` skill +- Grouping components with namespaces and paths -## Introducing cargo-cgp +## Improved error diagnostics with cargo-cgp + +Since its inception, one of the biggest challenge for users to adopt CGP is the verbose and confusing compile error messages produced by the Rust compiler, even for simple mistakes in a CGP code. This makes it virtually impossible for a new developer to dissect what went wrong in their CGP code, as doing so requires advanced understanding of Rust concepts like traits, generics, as well as internal details of how CGP works. + +This long-standing problem has been largely solved in v0.8.0, with the introduction of [**cargo-cgp**](/docs/cargo-cgp), a new tool that you can use in place of `cargo check` to tame the error messages. + +To see how cargo-cgp works, let's look at a simple example from the [area calculation example](/docs/tutorials/area-calculation/static-dispatch): + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + // missing `height` field +} + +delegate_and_check_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} +``` + +In the example above, we intentionally forget to include a `height` field in our `Rectangle` struct, causing it to fail to implement `CanCalculateArea` via the `RectangleArea` provider. If you try to compile the code with `cargo check`, you would see errors that show something like: + +```text +error[E0277]: the trait bound `Rectangle: HasField>>` is not satisfied + | +28 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` +``` + +Which is not very easy to understand, especially for someone who are new to CGP. Now with cargo-cgp, you can instead run `cargo cgp check` and get the following error: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` + --> src/lib.rs:28:9 + | +28 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + └─ [CGP-E106] missing field `height` on `Rectangle` +``` -## The challenges of scaling CGP +which tells you precisely that `Rectangle` is missing a field `height`, and the dependency chain that requires the field. + +Behind the scene, cargo-cgp wraps around a nightly Rust compiler, and uses the Rustc API to extract the root cause of CGP errors, and format them to become easily readable by users. + +Read the [cargo-cgp documentation](/docs/cargo-cgp) to learn more about how to install and use it using `cargo install`. + +## AI-assisted development with `/cgp` skill + +In addition to cargo-cgp, CGP v0.8.0 also comes with a comprehensive [`/cgp` skill](/docs/ai/skills/) to equip AI agents with foundational understanding to proficiently write CGP code. This further reduces the learning curve required for you to start writing CGP code today. + +If you are new to CGP and want to get started, the easiest way is to try out some simple example with an AI agent, and ask your agent how the code works in case you are stuck on anything. The skill should allow your agent to properly work out the internal details of CGP macros, install and use cargo-cgp to diagose errors for you, and explain CGP concepts in a way that matches your level of expertise. + +## Grouping components with namespaces and paths Up until now, one of main challenges of using CGP is on the boilerplate of using `delegate_components!` to wire CGP providers, especially as the number of CGP components grow within an application. When there are too many entries inside `delegate_components!`, developers quickly get lost on what they should pay attention to, and it gives the impression that the application becomes too complex. +CGP v0.8.0 introduces a new primitive called **namespaces**, which allows components to be grouped and dispatched while significantly reduce the boilerplate required. + ### An example social media web app To demonstrate the challenge, we will make use of a simple web application as an example. Suppose that we want to build a simple social media web app, we could use CGP to define modular traits to expose simple CRUD capabilities for managing users and posts. A simplified version of the traits would look something like follows: diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index 77614986..f7ac0aa6 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -44,19 +44,14 @@ impl AreaCalculator { #[derive(HasField)] pub struct Rectangle { pub width: f64, + // missing `height` field } -delegate_components! { +delegate_and_check_components! { Rectangle { AreaCalculatorComponent: RectangleArea, } } - -check_components! { - Rectangle { - AreaCalculatorComponent, - } -} ``` Running the tool on it: diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index 1dc6b0a4..6a659c96 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -29,6 +29,7 @@ impl AreaCalculator { #[derive(HasField)] pub struct Rectangle { pub width: f64, + // missing `height` field } ``` From 458c36732addfb7a1861bb869bee8b5f15721308 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 5 Oct 2026 15:49:23 +0000 Subject: [PATCH 156/516] Add AI-generated documentation section --- blog/2026-05-10-v0.8.0-release.md | 51 +++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index 74e5d217..cfeebe24 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -5,13 +5,13 @@ tags: [release] description: 'CGP v0.8.0 groups components with namespaces and paths, so a wiring table stays readable as an application''s component count grows.' --- -# CGP v0.8.0 - Grouping components with namespaces and paths +# CGP v0.8.0 - Namespaces, cargo-cgp, and AI-assisted development **CGP v0.8.0** has been released, and it comes with major ergonomic improvements to Context-Generic Programming (CGP) in the following area: -- Improved error diagnostics with cargo-cgp -- AI-assisted development with `/cgp` skill -- Grouping components with namespaces and paths +- [Improved error diagnostics with cargo-cgp](#improved-error-diagnostics-with-cargo-cgp) +- [AI-generated documentation and skill](#ai-generated-documentation-and-skill) +- [Grouping components with namespaces and paths](#grouping-components-with-namespaces-and-paths) @@ -86,9 +86,28 @@ Behind the scene, cargo-cgp wraps around a nightly Rust compiler, and uses the R Read the [cargo-cgp documentation](/docs/cargo-cgp) to learn more about how to install and use it using `cargo install`. -## AI-assisted development with `/cgp` skill +## AI-generated documentation and skill -In addition to cargo-cgp, CGP v0.8.0 also comes with a comprehensive [`/cgp` skill](/docs/ai/skills/) to equip AI agents with foundational understanding to proficiently write CGP code. This further reduces the learning curve required for you to start writing CGP code today. +Aside from poor error diagnostics, which is now solved by cargo-cgp, the CGP project had a long-standing problem of lack of documentation to explain all concepts and features available in CGP. Up until now, the main source of documentation for CGP had been the blog posts, which did not have the space to properly explain everything. The lack of documentation is not due to any technical challenges, but simply the lack of personal time by the author to invest for the side project. + +Thanks to advance in AI and agentic coding, the CGP website has been overhauled with comprehensive documentation that are largely written by Claude Code. The documentation now includes: + +- A comprehensive [reference documentation](/docs/reference/) to cover every feature available in CGP. +- [Concept documentation](/docs/concepts/) to walk through the high level programming concepts introduced by CGP. +- [Comparison documentation](/docs/comparisons/) to compare similar features in other programming languages with what is offered by CGP. +- [Projects documentation](/docs/projects/) to cover example CGP projects that had been highlighted by past blog posts. +- [`/cgp` skill](/docs/ai/skills/) to be used by AI agents to proficiently work with CGP. (more on that later) +- A [knowledge base](#) to be used internally by AI agents to work on the CGP project itself. + +At this point, some of the AI skeptic readers might think that the AI-generated documentation are just AI slop that are not worth reading. However, the documentation has gone through many iterations of planning and revision to arrive at a significantly higher quality than what would be generated by one-shot prompts. + +The current documentation covers roughly X number of words that would span X pages. It is also worth stating the alternative, which is human-written documentation, would likely take months of full time work by the author to write the same amount of content, which is unlikely to happen anytime in the near future. + +Explaining the full methodology is something that is worth covering in a dedicated follow up blog post in the future. But for now, I highly recommend you to take a look at it, and give me feedback for improvement if you still find any content that you consider slop. + +### The `/cgp` skill + +CGP v0.8.0 comes with a comprehensive [`/cgp` skill](/docs/ai/skills/) to equip AI agents with foundational understanding to proficiently write CGP code. This further reduces the learning curve required for you to start writing CGP code today. If you are new to CGP and want to get started, the easiest way is to try out some simple example with an AI agent, and ask your agent how the code works in case you are stuck on anything. The skill should allow your agent to properly work out the internal details of CGP macros, install and use cargo-cgp to diagose errors for you, and explain CGP concepts in a way that matches your level of expertise. @@ -216,7 +235,7 @@ delegate_and_check_components! { With just two lines of configurations, we have managed to configure our `ProductionApp` to use the `PostgresUserManager` and the `PostgresPostManager` providers that we have defined, without tightly coupling the implementations with the `ProductionApp` context. -### Filtering usernames and post messages +#### Filtering usernames and post messages Our base implementation of `PostgresUserManager` and `PostgresPostManager` only have a single dependency to the PostgreSQL database. But as the application grows, the methods may require additional dependencies to implement more features. @@ -310,7 +329,7 @@ In the example above, we have a `ProductionApp` that is used in production, and As we can see, CGP makes it easy to organically extend the dependency tree of an application context. However, with the transitive dependencies, we now have 4 items listed in 2 contexts, resulting in 8 wiring configuration entries. -### Fine grained traits +#### Fine grained traits If we look carefully at the implementation of `PostgresUserManager`, we can notice that the trait `CanCensorUsername` is not really needed by `get_user` and `update_user_data`. Similarly, in `PostgresPostManager`, the trait `CanDetectSpamMessage` is not needed by `get_post`, `update_post`, and `delete_post`. @@ -369,7 +388,7 @@ impl UserGetter { Instead of having a monolithic `PostgresUserManager` provider, we now have fine grained providers like `CreateUserWithPostgres` and `GetUserWithPostgres` that implement each fine grained trait separately. We can also see that the dependency to `CanCensorUsername` is only present in the implementation of `CreateUserWithPostgres`, while other providers like `GetUserWithPostgres` can work fine without requiring that trait to be implemented by the context. -### Higher-order providers +#### Higher-order providers Another key advantage of using fine grained traits is that we can now easily define *higher-order providers* that wrap around other provider implementations. For example, we can extra the logic of banning censored username into a separate provider like follows: @@ -406,7 +425,7 @@ With this separation of concern, we can now remove the dependency on `CanCensorU This separation of concern also allows logic like `FilterCensoredUsername` to be reused with other inner providers. For example, suppose that we also have a separate `CreateUserWithSqlite` provider that can be used by a local-first application. We can now enable the filtering of user creation using `FilterCensoredUsername`. -### Too much wiring with fine grained traits +#### Too much wiring with fine grained traits As we can see, the use of fine grained traits and higher order providers allows us to nicely decompose and decouple the dependencies that each trait needs. However, the main issue with this approach is that the boilerplate for wiring the components become significantly more verbose. For instance, the wiring for `ProductionApp` would become: @@ -460,7 +479,7 @@ With the code above, we define an *aggregated provider* called `PostgresUserComp Similarly, we can define a `PostgresPostComponents` to group all PostgreSQL-based post-related providers, and a `AiContentFilterComponents` to group the AI-based username and spam message filter providers. -### The challenges of grouping delegate component keys +#### The challenges of grouping delegate component keys However, before the current v0.8.0 release, even though we have ways to group CGP component wirings, there lacked good developer experience for using these aggregated providers at the top-level component wiring. For example, the component wiring for `ProductionApp` can at best be simplified into: @@ -527,7 +546,7 @@ where the macros like `all_user_components!()` expand into `[UserCreatorComponen Furthermore, there is no easy way for CGP to generate macros like `all_user_components!()` for the user. That is, there are limited support in Rust's macro system to allow macros to generate and export new macros. -### The problems with CGP presets +#### The problems with CGP presets Since the early days of the project, we have experimented with various ways to work around the limitations of Rust macros, and implemented a [**preset system**](/blog/hypershell-release#cgp-presets) system to group a collection of component wirings together to form a preset. However, there are many issues with providing a good developer experience through CGP presets. @@ -564,7 +583,7 @@ However, the biggest limitation of CGP presets is that it supports only a single We have also experimented on a multiple-inheritance-like feature with CGP presets using macros. However, the lack of eager macro evaluation and hygenic bindings of imports make it tedious to use the feature. -## Introducing CGP namespaces and paths +### Introducing CGP namespaces and paths Fortunately, with CGP v0.8.0, we have managed to solve the long-standing problem and devise a way to group component keys through a new feature called **namespaces**. @@ -620,7 +639,7 @@ Compared to before, our new definition for `ProductionApp` becomes significantly Following that, a delegate key like `@app.core.user` implicitly forwards all implementation of the user-related CGP traits to the aggregated provider `PostgresUserComponents`. Similarly, the next two entries delegate the corresponding CGP components to the respective aggregated providers. -### Hierarchical delegation +#### Hierarchical delegation CGP namespaces allows us to group CGP component keys into a hierarchy of prefixes. This in turns allows us to cleanly encapsulate group of CGP components, and break down the wiring configuration into smaller parts. @@ -694,7 +713,7 @@ We know that all PostgreSQL-specific core logic has been replaced by an SQLite-s If we were to define the same 3 contexts without namespaces, the difference in developer experience is stark. A new developer would need to scan through the dozens of lines of component wirings between the 3 contexts. Worse yet, the component wirings may be defined in different orders, making it extremely difficult to compare using humen eyes. -## Default implementations +### Default implementations In the earlier examples, we defined aggregated providers like `PostgresUserComponents`, `PostgresPostComponents`, and `PostgresCoreComponents` to group related provider implementations together, and then bulk delegate a prefix like `@app.core` to the aggregated provider. This provides great flexibility in customizing an application stack with different implementation bundles, such as `SqliteCoreComponents` or `PostgresWithLoggingCoreComponents`. @@ -771,7 +790,7 @@ By using default implementations, CGP allows developers to focus on wirings that At the same time, the use of namespaces means that developers still have the option to opt out of a given default implementation, by choosing to use a different namespace. -### Caveats with default implementations +#### Caveats with default implementations Although default implementations provide the convenience of omitting explicit wirings, the coherence restrictions in Rust makes it tricky to use default implementations as an application grows large. From 73081fb6abb287627b7e540f473cbcaba2b930fe Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 5 Oct 2026 16:24:43 +0000 Subject: [PATCH 157/516] Rewrite the cargo-cgp section for its v0.1.0 release The section grows from five pages to eight. The overview now leads with the unchecked-call mistake, whose raw E0599 never names the missing field, and states what the tool costs. Installation covers the reader with neither rustup nor Nix, checking the install, the platforms and CGP version, the upgrade from the alpha, CI, and uninstalling. New pages explain reading the output shape by shape, list every [CGP-Exxx] code with its fix, and collect the commands, options, and variables. Every quoted output was produced by running the source-built tool on exactly the program the page shows, and each of those programs is now an example-code fixture. The compile-errors page points to the new error-codes page instead of keeping its own copy of the code tables. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/check.md | 198 +++++---- docs/cargo-cgp/command-reference.md | 149 +++++++ docs/cargo-cgp/error-codes.md | 420 ++++++++++++++++++ docs/cargo-cgp/expand.md | 229 ++++++---- docs/cargo-cgp/index.md | 215 ++++++--- docs/cargo-cgp/installation.md | 252 ++++++----- docs/cargo-cgp/reading-output.md | 224 ++++++++++ docs/cargo-cgp/troubleshooting.md | 315 +++++++------ docs/projects/hypershell/guides/debugging.md | 6 +- docs/reference/errors.md | 58 +-- example-code/README.md | 2 +- example-code/tests/cargo_cgp/check.rs | 18 +- example-code/tests/cargo_cgp/mod.rs | 17 +- .../tests/cargo_cgp/reading_output.rs | 34 ++ ...eck_check_the_wiring_where_you_write_it.rs | 35 ++ ...heck_the_wiring_where_you_write_it.stderr} | 24 +- .../check_try_it_on_a_deliberate_mistake.rs | 33 ++ ...heck_try_it_on_a_deliberate_mistake.stderr | 43 ++ .../cargo_cgp/index_the_problem_it_solves.rs | 33 ++ .../index_the_problem_it_solves.stderr | 43 ++ ...ing_output_a_field_with_the_wrong_type.rs} | 4 +- ..._output_a_field_with_the_wrong_type.stderr | 29 ++ .../reading_output_a_fix_in_a_help_line.rs | 15 + ...reading_output_a_fix_in_a_help_line.stderr | 23 + ...ding_output_several_causes_in_one_error.rs | 34 ++ ..._output_several_causes_in_one_error.stderr | 28 ++ ...g_output_two_entries_that_claim_one_key.rs | 33 ++ ...tput_two_entries_that_claim_one_key.stderr | 15 + 28 files changed, 1984 insertions(+), 545 deletions(-) create mode 100644 docs/cargo-cgp/command-reference.md create mode 100644 docs/cargo-cgp/error-codes.md create mode 100644 docs/cargo-cgp/reading-output.md create mode 100644 example-code/tests/cargo_cgp/reading_output.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs rename example-code/tests/compile_fail/cargo_cgp/{check_check.stderr => check_check_the_wiring_where_you_write_it.stderr} (67%) create mode 100644 example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.stderr create mode 100644 example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.stderr rename example-code/tests/compile_fail/cargo_cgp/{check_check.rs => reading_output_a_field_with_the_wrong_type.rs} (85%) create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.stderr create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.stderr create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.stderr diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index f7ac0aa6..e2c26dac 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -1,18 +1,22 @@ --- +title: 'cargo cgp check: CGP errors, root cause first' +sidebar_label: 'Check' sidebar_position: 3 +description: 'Run cargo cgp check in place of cargo check to get CGP compile errors that name the root cause, then try it on a deliberate mistake.' --- # Check -`cargo cgp check` stands in for `cargo check` and re-presents CGP's wiring errors with their root cause -first. +`cargo cgp check` runs `cargo check` on your project and rewrites the CGP errors it recognizes so that +each one leads with its root cause. It is part of [`cargo-cgp`](./index.md), the error toolchain for +[Context-Generic Programming (CGP)](/docs/), and you use it wherever you would use `cargo check`: ```sh cargo cgp check ``` -Run it from anywhere inside a cargo package or workspace that uses `cgp`. Everything after `check` is -forwarded verbatim to `cargo check`, so the flags you already use work unchanged: +**Run it from your package's or workspace's root directory.** Everything after `check` is passed to +`cargo check`, so the flags you already use work unchanged: ```sh cargo cgp check --workspace @@ -20,11 +24,24 @@ cargo cgp check -p my-crate cargo cgp check --all-targets ``` -## A worked example +## Try it on a deliberate mistake -Here is a complete program with one mistake in it. `RectangleArea` reads a `height` field through an -[`#[implicit]`](/docs/reference/attributes/implicit) argument, and `Rectangle` does not have one — -someone removed it, or never added it. +A small library with one mistake shows what the tool does. Create a package: + +```sh +cargo new --lib area-demo +cd area-demo +``` + +Add CGP to its `Cargo.toml`: + +```toml +[dependencies] +cgp = "0.8.0" +``` + +Then replace `src/lib.rs` with this program. `RectangleArea` reads `width` and `height` through +[`#[implicit]`](/docs/reference/attributes/implicit) arguments, and `Rectangle` has only a `width`: ```rust use cgp::prelude::*; @@ -47,23 +64,27 @@ pub struct Rectangle { // missing `height` field } -delegate_and_check_components! { +delegate_components! { Rectangle { AreaCalculatorComponent: RectangleArea, } } + +pub fn print_area(rectangle: &Rectangle) { + println!("{}", rectangle.area()); +} ``` -Running the tool on it: +Running the check prints this, followed by cargo's own one-line summary: ```text $ cargo cgp check -error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` - --> src/lib.rs:28:9 +error[E0599]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` + --> src/lib.rs:28:30 | -28 | AreaCalculatorComponent, - | ^^^^^^^^^^^^^^^^^^^^^^^ +28 | println!("{}", rectangle.area()); + | ^^^^ | = note: root cause: [CGP-E106] missing field `height` on `Rectangle` this is required through the dependency chain: @@ -71,103 +92,130 @@ error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemente └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` └─ [CGP-E106] missing field `height` on `Rectangle` -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0599`. ``` -**Read the `root cause:` line first.** It names the fix — add a `height: f64` field to `Rectangle`, or -stop reading one. The tree beneath it is the chain of obligations that demanded it, read top to bottom: -the context has to implement the consumer trait, which means its wired provider has to be a provider -for that context, which means the context has to have the field. +**Read the `root cause:` line first.** It names the fix: add a `height: f64` field to `Rectangle`, or +wire a provider that does not read one. The tree beneath it is the chain of requirements, read from +the top: `Rectangle` must implement `CanCalculateArea`, so its provider `RectangleArea` must work for +`Rectangle`, so `Rectangle` must have the field. Replace the comment with `pub height: f64,` and the +check passes. Plain `cargo check` reports this same mistake without ever mentioning `height`; the +[overview](./index.md#the-problem-it-solves) shows its output. -For comparison, the same mistake under plain `cargo check`: +## Check the wiring where you write it -```text -help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` -``` +**Add a [`check_components!`](/docs/reference/macros/check_components) block to move the error from +the call to the wiring.** Wiring is lazy, so without one the error appears wherever the trait is first +used, which in a larger program can be far from the line you need to change. Replace `print_area` in +the program above with: -The field name is in there, one character per type parameter. That is the class of message the tool -exists to turn into a sentence. - -## Reading the output +```rust +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} +``` -The output is ordinary rustc and cargo diagnostics, with the errors the tool recognizes rewritten. -A rewritten message carries a short code in square brackets: +The check reports the same cause, now at the entry that asserted it: ```text error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` + --> src/lib.rs:29:9 + | +29 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + └─ [CGP-E106] missing field `height` on `Rectangle` + +For more information about this error, try `rustc --explain E0277`. ``` -The `[CGP-Exxx]` code names one class of CGP mistake. Codes appear in two places and mean slightly -different things: the one in the **headline** classifies the error, and the ones in the **root-cause -tree** label each link in the chain. In the example above, `CGP-E001` is "a context does not implement -a consumer trait", `CGP-E106` is "a required field is missing", and `CGP-E101`/`CGP-E102` are the -consumer and provider impls in between. +A check also changes what plain `cargo check` can tell you. On this version the compiler names the +missing requirement, but spells the field name one character at a time, as a type-level string: + +```text +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` +``` -The compiler's own code is always kept — `E0277` here — so `rustc --explain` still works and nothing is -reclassified away from rustc. The CGP code rides inside the message as a tag on the sentence it -classifies. **Errors the tool does not recognize pass through exactly as the compiler wrote them.** +That line is an excerpt from an error of about thirty lines whose headline names +`CanUseComponent`, a trait the macros generated. The tool turns it into the +sentence above. ## What a check does differently -Three deliberate differences from `cargo check`, all handled for you: +A check is `cargo check` with three settings the tool chooses for you: -- **It compiles under the tool's pinned nightly**, not your project's toolchain, so the diagnostics are - reproducible and the embedded compiler matches the driver. Your project's toolchain is untouched. -- **It turns on the next-generation trait solver.** This is the substantive one: the default solver - *hides* the failing bound in CGP's worst error class, reporting only that a method's bounds were not - satisfied. The new solver names the bound, which is what makes a root cause available to print. -- **It builds into `target/cgp`** rather than your project's `target/`, so a check never invalidates - your normal build cache and vice versa. +- **It compiles under the tool's pinned nightly**, so the compiler inside the driver matches the one + that builds your code. Your project's own toolchain is untouched. +- **It uses Rust's next-generation trait solver**, which works out the missing requirement in the cases + where the default solver only says that a method's bounds were not satisfied. +- **It builds into `target/cgp`** rather than `target`, so a check never invalidates your normal build + cache, and your builds never invalidate its. -Pass `--target-dir` (or set `CARGO_TARGET_DIR`) to send the artifacts elsewhere. +Because the tool picks these settings, a check is a diagnostic pass rather than a reproduction of your +own build, the way Clippy runs under settings of its own. Your toolchain's `cargo check` remains the +authority on whether the code compiles. -Because those are settings the tool chooses, a check is a diagnostic pass rather than a reproduction of -your own `cargo check` — the same relationship Clippy has to your build. +**`target/cgp` is relative to the directory you run the command from.** Run from a subdirectory, the +check creates a new `target/cgp` inside that subdirectory and builds every dependency again there. Pass +`--target-dir`, or set `CARGO_TARGET_DIR`, to put the artifacts somewhere else. ## Flags are cargo's, not the tool's -The tool appends your arguments to `cargo check` and lets cargo own them. Three consequences are worth -knowing: +The tool appends your arguments to `cargo check` and lets cargo handle them, which has three +consequences: -- Every `cargo check` flag behaves exactly as it does normally, because that is literally what runs. -- **cargo validates them, not cargo-cgp**, so an unknown flag produces cargo's error - (`error: unexpected argument '--nope' found`) rather than a cargo-cgp message. -- `cargo cgp check --help` prints *cargo's* help and exits **without running a check**, since `--help` - is forwarded like anything else. +- **Every `cargo check` flag behaves as it normally does**, because `cargo check` is what runs. +- **cargo validates them, not cargo-cgp.** An unknown flag produces cargo's error, + `error: unexpected argument '--nope' found`, rather than a message from the tool. +- **`cargo cgp check --help` prints cargo's help** for `cargo check` and exits without running a check. + For the tool's own commands, run `cargo cgp --help`. -The one flag the tool inspects is `--target-dir`, and only to decide whether to supply its own default. +The one flag the tool reads itself is `--target-dir`, and only to decide whether to supply +`target/cgp`. ## In your editor -Rust Analyzer can run the check on save. It is two words and must emit JSON, so wire it through -`check.overrideCommand` rather than `check.command`: +rust-analyzer can run the check every time you save. In VS Code, add this to your `settings.json`: ```json -"rust-analyzer.check.overrideCommand": [ - "cargo", "cgp", "check", "--workspace", "--all-targets", "--message-format=json" -] +{ + "rust-analyzer.check.overrideCommand": [ + "cargo", "cgp", "check", "--workspace", "--all-targets", "--message-format=json" + ] +} ``` -The transformed diagnostics are rendered as rustc JSON, which cargo wraps and the editor parses, so the -rewritten messages appear inline. The isolated `target/cgp` directory earns its keep here too: the -editor's checking does not contend with your own builds. +The command must go in `check.overrideCommand` rather than `check.command`, because it is more than one +word and must print JSON for the editor to read. The tool renders its rewritten errors in the same +JSON format as the compiler, so they appear inline like any other diagnostic, and the separate +`target/cgp` directory keeps the editor's checks from contending with your builds. Other editors that +use rust-analyzer take the same setting in their own configuration format. This setup has not yet been +tried in an editor as part of writing this page. ## When it will not help -**A check only reports what your code asks the compiler to prove.** CGP's wiring is lazy, so a context -that is never checked and never used produces no error at all — from this tool or any other. Pair your -wiring with [`check_components!`](/docs/reference/macros/check_components), which is what forces a -missing dependency to surface at the wiring site instead of at some distant call. +**A check reports only what your code asks the compiler to prove.** Wiring that nothing uses and +nothing checks produces no error, from this tool or any other. That is why +[`check_components!`](/docs/reference/macros/check_components) is worth adding for every context you +wire. + +**Some errors pass through as the compiler wrote them.** `cargo cgp check` leads with the root cause +for the classes it recognizes, and the tool does not yet reshape every class. +[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the ones that do not +change. -**Some classes still pass through raw.** The tool is a `v0.1.0-alpha` that reshapes the core wiring -errors; orphan-rule violations, among others, arrive as the compiler wrote them. +**It reshapes errors in your workspace's own crates only.** A dependency outside the workspace is +compiled normally, so an error inside it arrives as the compiler wrote it. If the command itself will not run, see [Troubleshooting](./troubleshooting.md). --- -*An AI agent wrote this page using the CGP knowledge base. The example and both outputs were -produced by running the tool. See -[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*An AI agent wrote this page using the CGP knowledge base, and its outputs were produced by running the +commands. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/command-reference.md b/docs/cargo-cgp/command-reference.md new file mode 100644 index 00000000..6df6753d --- /dev/null +++ b/docs/cargo-cgp/command-reference.md @@ -0,0 +1,149 @@ +--- +title: 'cargo-cgp command reference: commands, options, variables' +sidebar_label: 'Command reference' +sidebar_position: 8 +description: 'Every cargo-cgp command and option, the environment variables it reads and sets, the files it creates, and its exit status, in one place.' +--- + +# Command reference + +This page lists everything [`cargo-cgp`](./index.md) version 0.1.0 accepts and changes: its commands, +their options, the environment variables it reads and sets, the files it creates, and its exit +status. The other pages in this section explain how to use them. + +## Running it + +The tool is a cargo subcommand, so it runs either through cargo or on its own: + +```sh +cargo cgp [ARGS]... +cargo-cgp [ARGS]... +``` + +Two options stand in for a command: + +| Option | Effect | +|---|---| +| `-h`, `--help` | Prints the version, the list of commands, and a line on each. Running `cargo cgp` with no command does the same. | +| `--version` | Prints the version of the tool. | + +## Commands + +The tool has four commands. Two read your code, and two install and update the tool itself: + +| Command | Does | Details | +|---|---|---| +| `check` | Runs `cargo check` and rewrites the CGP errors it recognizes | [Check](./check.md) | +| `expand` | Prints the Rust one target's macros generate | [Expand](./expand.md) | +| `setup` | Installs the pinned nightly and builds the driver | [Installation](./installation.md#with-cargo) | +| `update` | Upgrades the tool to the newest published version | [Installation](./installation.md#updating) | + +### `check` + +```sh +cargo cgp check [CARGO CHECK ARGS]... +``` + +**Every argument is passed to `cargo check`**, which also validates them, so the command takes every +`cargo check` flag and no flags of its own. `cargo cgp check --help` prints `cargo check`'s help and +does not run a check. Two flags matter more than the rest: + +- **`--target-dir

`** sets where the build goes. Without it, and without `CARGO_TARGET_DIR`, the + tool adds `--target-dir target/cgp`, relative to the directory you run it from. +- **`--message-format=json`** prints the errors as JSON, rewritten the same way as the text output. An + editor needs this form; see [Check](./check.md#in-your-editor). + +### `expand` + +```sh +cargo cgp expand [--item ] [CARGO RUSTC ARGS]... +``` + +| Option | Effect | +|---|---| +| `--item ` | Prints only one module or item instead of the whole target. The path is `::`-separated, names something inside the crate, and may start with `crate::`. A module gives its contents, a type its declaration and every impl written for it, and a trait its definition and every impl of it. | +| `-h`, `--help` | Prints the help for `expand`, including `--item`. | + +**Every other argument is passed to `cargo rustc`**, so choosing the target, with `--lib`, `--bin`, +`-p`, or `--features`, is cargo's job. A package with more than one target needs `--lib` or +`--bin `. Unless you pass `--profile`, the tool builds under cargo's `check` profile. The +expansion goes to standard output, and everything else goes to standard error. + +### `setup` + +```sh +cargo cgp setup +``` + +Installs the pinned nightly through rustup, with the `rustc-dev` and `llvm-tools` components, then +builds `cargo-cgp-driver` at the front end's version under that nightly and installs it beside the +front end. Running it again when both are present does no harm. It needs rustup and a network +connection. + +### `update` + +```sh +cargo cgp update +``` + +Looks up the published versions on crates.io and, if there is a newer one in your release channel, +reinstalls the front end and runs the new version's `setup`. It needs a network connection. + +**`setup` and `update` take no options, and they ignore any arguments.** `cargo cgp setup --help` +therefore runs setup; use `cargo cgp --help` for help. + +## Environment variables + +The tool reads these variables, which are meant for running a build of the tool that `setup` did not +install, such as one from a source checkout: + +| Variable | Effect | +|---|---| +| `CARGO_CGP_NO_MANAGE` | When set, skips the preflight test of the toolchain and driver, and does not switch to the pinned nightly. The check then runs under whatever toolchain is active, which must be the driver's nightly. | +| `CARGO_CGP_DRIVER` | The path of the driver to run, instead of looking beside the front end. | +| `CARGO_CGP_TOOLCHAIN` | A nightly to use in place of the pinned one, for `setup` and for the checks. The driver must be built against it. | +| `CARGO_TARGET_DIR` | cargo's own variable. When set, the tool does not add `--target-dir target/cgp`. | + +For the length of a `check` or `expand`, the tool also sets variables for cargo: + +| Variable | Set to | +|---|---| +| `RUSTC_WORKSPACE_WRAPPER` | The driver. This replaces any value you set, so a wrapper of your own given through this variable does not run under the tool. | +| `RUSTUP_TOOLCHAIN` | The pinned nightly, unless `CARGO_CGP_NO_MANAGE` is set. | +| `LD_LIBRARY_PATH` | The `lib` directory of the toolchain the check runs under, added in front of any existing value, so the driver can load the compiler. | + +## Files and directories + +The tool creates these, and removing it does not remove them; see +[Uninstalling](./installation.md#uninstalling): + +| Path | What it holds | +|---|---| +| `~/.cargo/bin/cargo-cgp` | The front end, on the cargo path. | +| `~/.cargo/bin/cargo-cgp-driver` | The driver, which `setup` installs beside the front end. | +| `~/.rustup/toolchains/nightly-…` | The pinned nightly, which `setup` installs through rustup. The driver's `--version` names it. | +| `target/cgp` | The check's build artifacts, relative to the directory the command ran in. | + +## Exit status + +`check` exits with `cargo check`'s status, so `0` means no errors. `expand` exits with `0` when it +printed an expansion and with a non-zero status when it did not. A failure in the tool itself, such as +a preflight message or an unknown command, exits with `1`. + +## The driver + +You do not normally run `cargo-cgp-driver` yourself; the front end runs it in place of the compiler. +It answers two queries of its own: + +| Option | Effect | +|---|---| +| `--version`, `-V` | Prints three lines: its version, the `pinned-toolchain:` it needs, and the `built-against-rustc:` compiler it was built with. | +| `--help`, `-h` | Prints a short description of the driver. Running it with no arguments does the same. | + +Run directly on the cargo path, it needs the pinned nightly's `lib` directory on `LD_LIBRARY_PATH`; +[Troubleshooting](./troubleshooting.md#the-driver-cannot-load-the-compiler) shows the command. + +--- + +*An AI agent wrote this page using the CGP knowledge base, and checked it against the tool's source. +See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md new file mode 100644 index 00000000..4a9e3062 --- /dev/null +++ b/docs/cargo-cgp/error-codes.md @@ -0,0 +1,420 @@ +--- +title: 'cargo-cgp error codes: every CGP-E code explained' +sidebar_label: 'Error codes' +sidebar_position: 7 +description: 'Look up any [CGP-Exxx] code cargo cgp check prints: what the message says, what mistake it means, how to fix it, and where the class is explained.' +--- + +# Error codes + +`cargo cgp check`, part of the [`cargo-cgp`](./index.md) toolchain for +[Context-Generic Programming (CGP)](/docs/), tags each CGP error it rewrites with a code in square +brackets, such as `[CGP-E001]`. This page lists every code: the message it heads, the mistake it means, +the fix, and the section of the [compile-errors reference](/docs/reference/errors) that explains the +class of mistake in full. [Reading the output](./reading-output.md) shows how the codes sit inside a +complete error. + +## How the codes work + +**A CGP code sits beside the compiler's own code, not in place of it.** In +`error[E0277]: [CGP-E001] …`, `E0277` is the compiler's code, which `rustc --explain` describes, and +`[CGP-E001]` is the CGP class the tool recognized. A rewritten error restates the compiler's error more +readably and keeps its code, so searching your output for a CGP code finds every error of that class. + +The hundreds digit says where in the error a code appears: + +- **`CGP-E0xx` codes head the error.** They classify the whole error: what failed. +- **`CGP-E1xx` codes label the dependency chain**, one per line of the tree beneath a `root cause:` + note. The inner lines are steps along the way, and the last line is the cause. +- **`CGP-E2xx` codes label a `root cause:` line** whose cause has no `CGP-E1xx` code of its own. + +In the messages below, a word in angle brackets, such as ``, stands for the name the tool fills +in from your code. + +## Headline codes + +### CGP-E001 + +**A context does not implement a consumer trait.** The context cannot use a component it is expected +to use: the component is not wired, or something the wired provider needs is missing, so the context +never gets the consumer trait. + +```text +[CGP-E001] the consumer trait `` is not implemented for context `` +``` + +When one mistake breaks several components, the message names them all: "the consumer traits ``, +``, and `` are not implemented". The compiler's code stays whatever it assigned: `E0277` at a +check, `E0599` at a method call. **Fix:** follow the `root cause:` note, which names the missing field, +derive, wiring entry, or trait bound. Explained in +[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met). + +### CGP-E002 + +**A provider does not implement its provider trait for the context.** Something the provider requires +does not hold. This is the provider-side face of `[CGP-E001]`, and it is what a +`#[check_providers(...)]` assertion in +[`check_components!`](/docs/reference/macros/check_components) reports. + +```text +[CGP-E002] the provider trait `` with context `` is not implemented for provider `` +``` + +**Fix:** follow the `root cause:` note to what the provider is missing. Explained in +[When the provider is a stack](/docs/reference/errors#when-the-provider-is-a-stack). + +### CGP-E003 + +**A field is present but has the wrong type.** The context has the field and derives `HasField` for it, +but its type is not the one a provider reads. + +```text +[CGP-E003] expected a `` field of type `` on ``, but found `` +``` + +When the required type is written in terms of an abstract type, the message shows both forms, the +written one and what it resolves to: + +```text +[CGP-E003] expected a `database` field of type `Pool<::Db>` (`Pool`) on `App`, but found `Pool` +``` + +The compiler's code is `E0271`. **Fix:** change the +field's type, or change the provider to accept the type the field has. Explained in +[When two decisions disagree about a type](/docs/reference/errors#when-two-decisions-disagree-about-a-type). + +### CGP-E004 + +**The same key is wired twice.** A wiring table, or a namespace, maps one component or path to two +providers. + +```text +[CGP-E004] duplicate wiring for on `` +``` + +The compiler's two carets point at the two entries. **Fix:** remove one of them. Explained in +[Two entries claim one key](/docs/reference/errors#two-entries-claim-one-key). + +### CGP-E005 + +**A key is wired that another entry already covers.** The two keys differ but overlap: a generic +entry over a specific one, a path that covers a longer path, or an entry for a key the context's +namespace already binds. + +```text +[CGP-E005] `` cannot wire that is already set through +``` + +**Fix:** remove or narrow the overlapping entry. Explained in +[Two entries claim one key](/docs/reference/errors#two-entries-claim-one-key) and +[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds). + +### CGP-E006 + +**A context joins more than one namespace.** Each namespace covers every key, so two of them, or a +namespace and a loop over bare keys, conflict. + +```text +[CGP-E006] only one namespace can be used for each target type in `delegate_components!`, but `` uses both `` and `` +``` + +**Fix:** join one namespace and make it inherit the others. Explained in +[Joining more than one namespace](/docs/reference/errors#joining-more-than-one-namespace). + +### CGP-E007 + +**A direct entry collides with a redirect of the same key**, such as a component wired by name while an +`open` statement, a `=>` redirect, or a namespace sends it along a path. + +```text +[CGP-E007] on `` is redirected to `` +``` + +A `help` line names the entry to write instead. **Fix:** wire the provider under the redirected path +rather than the component name. Explained in +[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds). + +### CGP-E008 + +**The same key is redirected twice**, by two `open` statements or `=>` mappings on one context, or by +one path registered twice in a namespace. + +```text +[CGP-E008] duplicate redirect for on `` +``` + +**Fix:** keep one redirect. Explained in +[Two entries claim one key](/docs/reference/errors#two-entries-claim-one-key). + +### CGP-E009 + +**A trait that is not a CGP component fails because a component it depends on fails.** It is the +`[CGP-E001]` case for a trait you wrote by hand over a consumer trait, or for a +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) or [`#[blanket_trait]`](/docs/reference/macros/blanket_trait) +trait, which is why it says "the trait" rather than "the consumer trait". + +```text +[CGP-E009] the trait `` is not implemented for context `` +``` + +**Fix:** follow the `root cause:` note to the dependency the trait needs. Explained in +[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met). + +### CGP-E010 + +**The wiring for a component never resolves**, because looking it up leads back to itself. Almost +always a component is wired to `UseContext` on a context whose only implementation of it is that very +wiring. + +```text +[CGP-E010] the wiring for the consumer trait `` on context `` never resolves — the lookup recurses without terminating +``` + +The compiler's code is `E0275`, and a `help` line names the usual cause. **Fix:** wire the component to +a real provider, or implement the consumer trait directly on the context. Explained in +[A lookup that never terminates](/docs/reference/errors#a-lookup-that-never-terminates). + +### CGP-E011 + +**A crate registers wiring into a namespace it does not own, under a key it does not own either**, +which Rust's orphan rule forbids. + +```text +[CGP-E011] cannot register the foreign into the foreign namespace `` +``` + +The compiler's code is `E0210` or `E0117`. **Fix:** own one end, as the `help` line says: key the +registration on a component your crate defines, register it from the crate that owns the namespace, or +define a namespace of your own that inherits the foreign one. Explained in +[Registering into a namespace you do not own](/docs/reference/errors#registering-into-a-namespace-you-do-not-own). + +### CGP-E012 + +**A `#[cgp_fn]` body calls a CGP trait's method on `self` without declaring the trait as a +dependency.** The macro turns the body into a blanket implementation over a generated context type, so +a trait the body uses has to be declared for that type to have it. + +```text +[CGP-E012] the trait `` is used but not declared as a dependency +``` + +The compiler's code is `E0599`. **Fix:** add the trait to `#[uses(...)]`, as the `help` line says. +Explained in [Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare). + +### CGP-E013 + +**A `#[cgp_impl]` header names the component's consumer trait where its provider trait belongs.** + +```text +[CGP-E013] `` is a consumer trait, but a `#[cgp_impl]` provider must implement its provider trait `` +``` + +Without the rewrite, this one mistake produces a burst of unrelated-looking errors. **Fix:** name the +provider trait in the header, as the `help` line says. Explained in +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component). + +### CGP-E014 + +**`#[cgp_impl]` is applied to a trait that is not a CGP component at all**, so there is no provider +trait to implement. + +```text +[CGP-E014] `#[cgp_impl]` can only implement a CGP component's provider trait, but `` is not a CGP component +``` + +**Fix:** make the trait a component with +[`#[cgp_component]`](/docs/reference/macros/cgp_component), or drop `#[cgp_impl]` and write an ordinary +`impl`. Explained in +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component). + +### CGP-E015 + +**An inner-provider bound names a consumer trait where the provider trait belongs**, most often in +[`#[use_provider]`](/docs/reference/attributes/use_provider). + +```text +[CGP-E015] `` is a consumer trait and cannot bound an inner provider; a higher-order provider imports its provider trait `` +``` + +**Fix:** name the provider trait, as the `help` line says. Explained in +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component). + +### CGP-E016 + +**A higher-order provider calls an inner provider it never imported**, so the inner provider has no +provider-trait bound and the call cannot resolve. + +```text +[CGP-E016] the inner provider `` is used but not imported +``` + +**Fix:** import it with `#[use_provider(: )]`, as the `help` line says. Explained +in [Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare). + +### CGP-E017 + +**An abstract type is wired one way and required another.** The context supplies one type for an +associated type, such as its error type, while a provider requires a different one. + +```text +[CGP-E017] expected the abstract type `` of `` on `` to be ``, but found `` +``` + +For a trait that is not a CGP abstract-type component, the message says "associated type" instead. Like +`[CGP-E003]`, it shows a required type in both forms when it is written through another abstract type. +The compiler's code is `E0271`. **Fix:** make the two sides agree; for a +[`#[cgp_type]`](/docs/reference/macros/cgp_type) component, the `help` line names the `UseType` entry to +wire. Explained in +[When two decisions disagree about a type](/docs/reference/errors#when-two-decisions-disagree-about-a-type). + +## Dependency-chain codes + +These codes label the lines of the tree beneath a `root cause:` note. The first four are steps along +the way; the rest end the chain, and the cause they state is the one to fix. + +### CGP-E101 + +**A step through a context's consumer trait.** Usually the first line of the chain. + +```text +[CGP-E101] consumer trait impl `` for context `` +``` + +### CGP-E102 + +**A step through a provider's provider trait**: the context's wiring selected this provider, and the +chain continues with what the provider needs. + +```text +[CGP-E102] provider trait impl `` with context `` for provider `` +``` + +### CGP-E104 + +**A step through a redirected lookup**, from an `open` statement or a namespace, naming the table the +path is looked up in. + +```text +[CGP-E104] redirect lookup to `@` in `
` +``` + +### CGP-E105 + +**A step through any other trait**, such as a getter or a blanket trait you wrote. + +```text +[CGP-E105] trait impl `` for `` +``` + +`CGP-E103` is not assigned. + +### CGP-E106 + +**The chain ends at a field the context does not have.** + +```text +[CGP-E106] missing field `` on `` +``` + +**Fix:** add the field, or wire a provider that does not read it. Explained in +[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met). + +### CGP-E107 + +**The chain ends at a component or path the context wires nothing for.** + +```text +[CGP-E107] context `` does not contain any delegate entry for `` +``` + +**Fix:** add the wiring entry. Explained in +[Nothing is wired there](/docs/reference/errors#nothing-is-wired-there). + +### CGP-E108 + +**The chain ends at a field that exists but has no `HasField` impl**, because the struct does not derive +it. + +```text +[CGP-E108] accessor trait `HasField` with field `` is not implemented for `` +``` + +**Fix:** add `#[derive(HasField)]` to the struct, as the `help` line says. Explained in +[When the derive is missing entirely](/docs/reference/errors#when-the-derive-is-missing-entirely). + +### CGP-E109 + +**The chain ends at a field with the wrong type.** It is the last line of a `[CGP-E003]` error. + +```text +[CGP-E109] field `` on `` has type ``, but `` is required +``` + +### CGP-E110 + +**The chain ends at a provider's own table that has no entry for a key**: a bundle of wiring missing a +component, or a provider that dispatches per type missing the type it was given. + +```text +[CGP-E110] provider `` does not contain any delegate entry for `` +``` + +**Fix:** add the entry to that provider's table, or pass it a type the table covers. + +### CGP-E111 + +**The chain ends at a type wired where a provider belongs that is not a provider**, such as a value +type put in a provider's place. + +```text +[CGP-E111] the provider trait `` is not implemented for `` +``` + +**Fix:** wire an actual provider in that position. + +### CGP-E112 + +**The chain ends at an associated type that differs from what was required.** It is the last line of a +`[CGP-E017]` error. + +```text +[CGP-E112] abstract type `` of `` on `` is ``, but `` is required +``` + +## Root-cause codes + +A `root cause:` line normally carries the same code as the last line of its chain. This range covers +the case where that last line has no code. + +### CGP-E201 + +**The chain ends at an ordinary Rust trait bound that does not hold**, such as `f64: Eq`. The last line +of the tree repeats the compiler's own wording without a code, and the `root cause:` line carries this +one. + +```text +root cause: [CGP-E201] the trait bound `` is not satisfied +``` + +**Fix:** use a type that implements the trait, or a provider that does not require it. Explained in +[When the missing bound is an ordinary Rust trait](/docs/reference/errors#when-the-missing-bound-is-an-ordinary-rust-trait). + +## Rewrites without a code + +Some changes make an error easier to read without classifying it, so they carry no code. You may see +them in an error whose headline the tool left as the compiler wrote it: + +- **Type-level names written back as you wrote them**: a field name as `Symbol!("name")`, a list as + `Product![A, B]` or `Sum![A, B]`, and a path as `Path!(@app.Component)`. A path that ends in an + unknown part gets a trailing `.*`, which is not real `Path!` syntax. +- **Shorter type names**, with the CGP module paths the compiler prints in front of them removed. +- **A missing-field sentence** in place of an unmet `HasField` requirement inside a note. +- **Consumer and provider trait names** in the compiler's "required for … to implement …" notes, in + place of the generated traits that connect them. +- **Removed advice** that a method call should use associated-function syntax, which the compiler + suggests for CGP's provider methods and which does not fix the mistake. + +--- + +*An AI agent wrote this page using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 619a8a41..233dd1ca 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -1,29 +1,75 @@ --- -sidebar_position: 4 +title: 'cargo cgp expand: see what CGP macros generate' +sidebar_label: 'Expand' +sidebar_position: 5 +description: 'Print the Rust your CGP macros generate, narrowed to one module, type, or trait, with field names and type-level lists written the way you wrote them.' --- # Expand -`cargo cgp expand` prints your crate as the compiler sees it after macro expansion, so you can read -what a CGP macro actually generated instead of reasoning about what it probably generated. +`cargo cgp expand` prints your crate as the compiler sees it after macro expansion, so you can read what +a [CGP](/docs/) macro actually generated instead of reasoning about what it probably generated. It is +part of [`cargo-cgp`](./index.md), and it writes CGP's type-level constructs back in the form you wrote +them. ```sh cargo cgp expand --lib ``` -:::note +## When to use it -`expand` landed after the published `v0.1.0-alpha`, so an install from crates.io does not carry it yet. -Get it from the Nix flake with the tag dropped -(`nix run github:contextgeneric/cargo-cgp -- expand --lib`) or from a source build — see -[Installation](./installation.md#expand-is-newer-than-the-published-release). `cargo cgp check` is -unaffected. +Reach for `expand` when the answer is in the generated code rather than in an error message: -::: +- **A diagnostic names a type you did not write**, such as + [`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for), a `PathCons` key, or a + `__Context__` parameter, and you want to see the impl it came from. +- **A wiring table does not resolve**, and you want its actual + [`DelegateComponent`](/docs/reference/traits/wiring/delegate_component) keys and providers rather + than inferring them from the table's syntax. +- **You are unsure what a construct emits**, such as the exact `where` clauses of a provider, or which + field a getter reads. +- **Two forms differ and only one compiles.** Expand both and compare the output. ## What it looks like -Taking the `Rectangle` context from the [Check](./check.md) page, once its missing field is restored: +This is the `Rectangle` program from the [Check page](./check.md#check-the-wiring-where-you-write-it) +with its `height` field restored, so the program compiles: + +```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} +``` + +Asking for the `Rectangle` type gives its declaration and every impl written for it: ```sh cargo cgp expand --lib --item Rectangle @@ -51,7 +97,23 @@ impl HasFieldMut for Rectangle { &mut self.width } } -// … the same pair again for `height` … +impl HasField for Rectangle { + type Value = f64; + fn get_field( + &self, + key: ::core::marker::PhantomData, + ) -> &Self::Value { + &self.height + } +} +impl HasFieldMut for Rectangle { + fn get_field_mut( + &mut self, + key: ::core::marker::PhantomData, + ) -> &mut Self::Value { + &mut self.height + } +} impl DelegateComponent for Rectangle { type Delegate = RectangleArea; } @@ -65,17 +127,21 @@ where impl __CheckRectangle for Rectangle {} ``` -Everything a reader needs in order to follow a wiring error is visible there: the field accessors -[`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) produced, the one-line table entry -[`delegate_components!`](/docs/reference/macros/delegate_components) produced, the forwarding impl that -carries the provider's requirements, and the assertion -[`check_components!`](/docs/reference/macros/check_components) added. +Each part of the program is visible in the listing: + +- [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) produced a pair of field accessors + for each field, keyed by the field's name. +- [`delegate_components!`](/docs/reference/macros/delegate_components) produced the one-line table + entry that selects `RectangleArea`, and an impl that passes the provider's requirements through to + `Rectangle`. +- [`check_components!`](/docs/reference/macros/check_components) produced the last line, the + assertion that `Rectangle` can use the component. ## Narrowing with `--item` -A whole crate's expansion is long — for the tiny example above, 148 lines against 49 for the one item. -`--item` takes a `::`-separated path naming something *inside* the crate, and what you get depends on -what you name: +**`--item` narrows the output to one module or item.** A whole crate's expansion is long: for this +small program it is 148 lines, against 49 for `Rectangle` alone. The option takes a `::`-separated +path naming something inside the crate, and what you get depends on what it names: ```sh cargo cgp expand --lib --item shapes # a module: its contents @@ -83,27 +149,34 @@ cargo cgp expand --lib --item shapes::Rectangle # a type: its declaration and e cargo cgp expand --lib --item AreaCalculator # a trait: its definition and every impl of it ``` -A leading `crate::` is accepted, so `--item crate::contexts::app` and `--item contexts::app` are the -same request. +A leading `crate::` is accepted, so `--item crate::shapes` and `--item shapes` are the same request. -**The trait form is usually the one you want on CGP code**, because a component's generated items *are* -impls. Naming a component's *provider* trait gives you the provider trait, the delegation blanket impl, -the `UseContext` impl, and each wired provider's impl of it — the whole resolution path in one listing. -Naming the *consumer* trait gives just that trait and its routing blanket. The type form is the -companion, and is what the example above uses. +**Naming a component's provider trait is usually the most useful form**, because most of a +component's generated items are impls of it. For this program, `--item AreaCalculator` gives the +provider trait itself, the blanket impl that lets a context's wiring pick the provider, the impls for +the `UseContext` and `RedirectLookup` providers CGP generates for every component, and +`RectangleArea`'s own impl, with the `where` clause that requires the two fields. Naming the consumer +trait instead, as in `--item CanCalculateArea`, gives that trait and the one blanket impl that connects +it to the provider trait. -If the path matches nothing, the tool says so rather than falling back to a whole-crate dump: +If the path matches nothing, the tool says so instead of printing the whole crate. Among cargo's +progress lines, it prints: ```text error: no module or item matched `NoSuchThing` -note: the path names a module or item inside the crate being expanded, as in `contexts::app`; - a leading `crate::` is accepted too +note: the path names a module or item inside the crate being expanded, as in `contexts::app`; a leading `crate::` is accepted too +``` + +and finishes with: + +```text +error: no expansion was produced; see the errors above ``` ## Choosing a target -`expand` expands exactly one target, and arguments are forwarded to `cargo rustc`, so target selection -is cargo's. A package with both a library and a binary therefore needs to be told which: +`expand` expands exactly one target, and its other arguments are passed to `cargo rustc`, so choosing +the target is cargo's job. A package with both a library and a binary needs to be told which one: ```sh cargo cgp expand --lib @@ -111,74 +184,72 @@ cargo cgp expand --bin my-app cargo cgp expand -p my-crate --lib ``` -Without one, cargo declines with *"extra arguments to `rustc` can only be passed to one target"*. That -is worth knowing before your first run, because the message is cargo's and does not mention `expand`. +Without one, cargo declines, in a message that does not mention `expand`: -Output goes to stdout, so it redirects and pipes like anything else: +```text +error: extra arguments to `rustc` can only be passed to one target, consider filtering +the package by passing, e.g., `--lib` or `--bin NAME` to specify a single target +error: no expansion was produced; see the errors above +``` + +The expansion goes to standard output, so it redirects and pipes like any other program's output: ```sh cargo cgp expand --lib > expanded.rs -cargo cgp expand --lib | rg 'Symbol!' +cargo cgp expand --lib | grep 'Symbol!' ``` -`cargo cgp expand --help` is the one argument the tool answers itself rather than forwarding: it -prints the expand options, including `--item`, with examples. For cargo's own target-selection -options, run `cargo rustc --help`. +`cargo cgp expand --help` prints the tool's own help for `expand`, which documents `--item`. That is +the one argument `expand` reads itself; for cargo's target-selection options, run `cargo rustc --help`. ## Why not `cargo-expand` -`cargo-expand` is the general tool and it works on CGP code. The reason to reach for this one is that -CGP's generated code is dominated by *type-level constructs*, and a general expander prints them as the -compiler stores them. +[`cargo-expand`](https://github.com/dtolnay/cargo-expand) is the general tool, and it works on CGP code. +The reason to use this one is that CGP's generated code is full of type-level constructs, which a +general expander prints the way the compiler stores them. -**A field name is the clearest case.** CGP encodes it as a [type-level string](/docs/reference/glossary#type-level-string) — one type parameter per -character. Expanded generically, the `height` tag above reads: +**A field name is the clearest case.** CGP encodes it as a +[type-level string](/docs/reference/glossary#type-level-string), with one type per character. In the +compiler's own expansion, which is what a general expander formats, the `height` accessor above begins: ```text -Symbol<6, Chars<'h', Chars<'e', Chars<'i', Chars<'g', Chars<'h', Chars<'t', Nil>>>>>>> +impl ::cgp::macro_prelude::HasField<::cgp::macro_prelude::Symbol<6, + ::cgp::macro_prelude::Chars<'h', + ::cgp::macro_prelude::Chars<'e', + ::cgp::macro_prelude::Chars<'i', + ::cgp::macro_prelude::Chars<'g', + ::cgp::macro_prelude::Chars<'h', + ::cgp::macro_prelude::Chars<'t', ::cgp::macro_prelude::Nil>>>>>>>> for + Rectangle { ``` -`cargo cgp expand` resugars it back to `Symbol!("height")`, which is what you wrote. It does the same -for the rest of the vocabulary — a pipeline reads `Product![StepOne, StepTwo]` rather than a `Cons` -list, and a namespace key reads `Path!(@app.GreeterComponent)`. On a page of wiring the difference is -between a listing you can read and one you have to decode. +`cargo cgp expand` writes it back as `Symbol!("height")`, which is what you wrote. It does the same for +the rest of CGP's type-level vocabulary: a list of handlers reads `Product![StepOne, StepTwo]` rather +than a chain of `Cons` cells, and a namespace key reads `Path!(@app.GreeterComponent)`. -Two smaller differences follow from the same purpose. **`--item` understands Rust items** — asking for -a trait gives you every impl *of* it, which is the shape a CGP question actually takes, rather than a -textual filter. And **the `cgp::macro_prelude::` qualifier is stripped**, which makes the output far -easier to read at the cost of not being compilable — see below. +`--item` is the other difference. It selects Rust items rather than filtering text: asking for a trait +gives every impl of that trait, wherever it sits in the crate, which is the shape a question about CGP +wiring usually takes. ## What to expect from the output -**Every macro is expanded, not only CGP's.** `#[derive(Debug)]` and `println!` appear in their -generated form too. The CGP-specific part is the resugaring, not the selection. - -**The output is for reading, not compiling.** Stripping the `cgp::macro_prelude::` qualifier is what -makes it legible, and it also means you cannot paste the result back into your crate and expect it to -build. +**Every macro is expanded, not only CGP's.** `#[derive(Debug)]` and `println!` appear in their generated +form too. What is specific to CGP is how the type-level constructs are written. -**`expand` is not a check.** Compilation stops as soon as the macros are expanded, so no type analysis -runs and no CGP diagnostic is produced. A malformed macro invocation still fails, because that happens -during expansion — but a wiring mistake does not surface here at all. That is exactly what makes it -useful mid-debugging: it works on a crate that does not type-check. For the wiring mistake itself, use -[`cargo cgp check`](./check.md). +**The output is for reading, not compiling.** The tool removes the `cgp::macro_prelude::` prefix the +macros put in front of every CGP name, which makes the listing readable and means it does not compile +if you paste it back into your crate. -## When to use it +**`expand` is not a check.** Compilation stops once the macros are expanded, so no type checking runs +and no wiring error is reported. A malformed macro invocation still fails, because that happens during +expansion. This is what makes `expand` useful in the middle of debugging: it works on a crate that does +not type-check. For the wiring mistake itself, use [`cargo cgp check`](./check.md). -Four situations, all of them cases where the answer is in the generated code rather than in a message: - -- **A diagnostic names a type you did not write** — - [`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for), a `PathCons` key, a `__Context__` - parameter — and you want to see the impl it came from. -- **A wiring table does not resolve** and you want its real - [`DelegateComponent`](/docs/reference/traits/wiring/delegate_component) keys and values rather - than inferring them from the table's syntax. -- **You are unsure what a construct emits** — the exact `where` clauses of a provider impl, whether a - getter's blanket impl needs the field you think it does. -- **Two forms differ and only one compiles.** Expand both and diff; the delta is the bug. +**It builds the way a check does.** `expand` uses the same pinned nightly and the same `target/cgp` +directory as `cargo cgp check`, so the notes on the [Check page](./check.md#what-a-check-does-differently) +apply to it too. --- -*An AI agent wrote this page using the CGP knowledge base. The example output was produced by -running the tool. See -[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*An AI agent wrote this page using the CGP knowledge base, and its outputs were produced by running the +commands. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index 6a659c96..db8206cd 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -1,24 +1,38 @@ --- +title: 'cargo-cgp: readable CGP compile errors' +sidebar_label: 'Overview' sidebar_position: 1 +description: 'cargo-cgp runs in place of cargo check and reports a CGP compile error with its root cause first, including the causes plain cargo check leaves out.' --- # cargo-cgp -`cargo-cgp` is CGP's error toolchain: a cargo subcommand that stands in for `cargo check` and presents -CGP's compiler errors root cause first, plus a second command that shows the ordinary Rust your macros -generate. +[Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait +implementations at compile-time. `cargo-cgp` is its error toolchain: a cargo subcommand you run in +place of `cargo check` to read a CGP compile error with its root cause first, and to see the ordinary +Rust your CGP macros generate. + +The tool is optional. CGP is a library on stable Rust, and `cargo check`, `cargo build`, and +`cargo test` work on a CGP project without it. Reach for `cargo-cgp` when an error is hard to read. ## The problem it solves -CGP's wiring is **lazy**. A `delegate_components!` entry is accepted without checking that the provider -it names can actually do the job, so a context with a missing field or an unmet dependency compiles -fine and fails somewhere else entirely — usually at the first call to the trait's method, in a message -about types you never wrote. +**Some CGP mistakes produce a compiler error that does not contain its cause.** CGP's wiring is lazy: a +[`delegate_components!`](/docs/reference/macros/delegate_components) entry selects a provider without +checking that the context can give the provider what it needs. That check happens later, where the +trait is first used, and from there the compiler often cannot say what went wrong. -Here is the whole of a mistake: a `Rectangle` that lost its `height` field while a provider still reads -it. +In this program, `RectangleArea` reads a `width` and a `height` field through +[`#[implicit]`](/docs/reference/attributes/implicit) arguments, and `Rectangle` has no `height`: ```rust +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + #[cgp_impl(new RectangleArea)] impl AreaCalculator { fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { @@ -31,99 +45,166 @@ pub struct Rectangle { pub width: f64, // missing `height` field } + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +pub fn print_area(rectangle: &Rectangle) { + println!("{}", rectangle.area()); +} ``` -Under plain `cargo check`, with the mistake pinned to the wiring site by -[`check_components!`](/docs/reference/macros/check_components), this is what comes back: +Plain `cargo check` on stable Rust reports the call to `area`: ```text -error[E0277]: the trait bound `Rectangle: HasField>>` is not satisfied +error[E0599]: the method `area` exists for reference `&Rectangle`, but its trait bounds were not satisfied + --> src/lib.rs:28:30 + | +16 | pub struct Rectangle { + | -------------------- doesn't satisfy `Rectangle: AreaCalculator` or `Rectangle: CanCalculateArea` +... +28 | println!("{}", rectangle.area()); + | ^^^^ this is an associated function, not a method + | + = note: found the following associated functions; to be used as methods, functions must have a `self` parameter +note: the candidate is defined in the trait `AreaCalculator` + --> src/lib.rs:5:5 + | + 5 | fn area(&self) -> f64; + | ^^^^^^^^^^^^^^^^^^^^^^ +note: the following trait bounds were not satisfied: + `&Rectangle: AreaCalculator<&Rectangle>` + `Rectangle: AreaCalculator` + --> src/lib.rs:3:1 + | + 3 | #[cgp_component(AreaCalculator)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 | pub trait CanCalculateArea { + | ^^^^^^^^^^^^^^^^ +note: the trait `AreaCalculator` must be implemented + --> src/lib.rs:4:1 | -28 | AreaCalculatorComponent, - | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + 4 | / pub trait CanCalculateArea { + 5 | | fn area(&self) -> f64; + 6 | | } + | |_^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `CanCalculateArea` defines an item `area`, perhaps you need to implement it + --> src/lib.rs:4:1 | -help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` + 4 | pub trait CanCalculateArea { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use associated function syntax instead + | +28 - println!("{}", rectangle.area()); +28 + println!("{}", Rectangle::area()); + | + +For more information about this error, try `rustc --explain E0599`. ``` -The answer is in there — the field is spelled out one character per type parameter — but you have to -decode a `Chars` list to read it, and this is the *good* case, where a check forced the failure to the -wiring site. +The message never mentions `height`. It describes the trait machinery CGP generated, and its closing +suggestion, calling `Rectangle::area()`, fixes a different problem. The cause is not buried in the +output: it is absent, because the compiler set the candidate implementation aside before working out +why it did not apply. `cargo cgp check` reports the same mistake like this: ```text -error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` - --> src/lib.rs:28:9 +error[E0599]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` + --> src/lib.rs:28:30 | -28 | AreaCalculatorComponent, - | ^^^^^^^^^^^^^^^^^^^^^^^ +28 | println!("{}", rectangle.area()); + | ^^^^ | = note: root cause: [CGP-E106] missing field `height` on `Rectangle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` └─ [CGP-E106] missing field `height` on `Rectangle` -``` -Same error, same `E0277`, same span. What changed is that the cause is named in English on the second -line, and the chain that demanded it is drawn out beneath. +For more information about this error, try `rustc --explain E0599`. +``` -## How it does that +The error code and the position are unchanged. The headline says which trait `Rectangle` fails to +implement, the `root cause:` line names the missing field, and the tree beneath it shows the chain of +requirements that led there. [Reading the output](./reading-output.md) explains each part. -Two things, and the first matters more than the reshaping. +## How it works -**It un-hides causes the compiler suppresses.** The worst class of CGP error is not verbose but -*incomplete*: the default trait solver stops at "the trait bounds were not satisfied" without ever -naming the bound that failed, so the answer is absent from the output rather than buried in it. -`cargo cgp check` compiles under Rust's next-generation trait solver, which reports the real missing -bound — and that is what makes a root cause available to print at all. +**It compiles your code under Rust's next-generation trait solver, which computes the cause the +default solver leaves out.** The default solver stops at "the trait bounds were not satisfied" in the +case above; the next-generation solver works the failed requirement down to the missing +`HasField` bound. That is what gives the tool a root cause to print at all. -**It rewrites the classes it recognizes.** Where the tool knows the shape of a CGP failure, it leads -with the cause, draws the dependency chain as a tree, and stamps the message with a `[CGP-Exxx]` code -naming the class. The compiler's own code is always kept, so `rustc --explain E0277` still works and -nothing is reclassified away from rustc. +**It rewrites the errors it recognizes.** Where the tool knows the shape of a CGP failure, it leads with +the cause, draws the chain of requirements as a tree, and tags the message with a `[CGP-Exxx]` code +naming the class of mistake. The compiler's own code stays in the header, so `rustc --explain` still +works. Errors it does not recognize pass through as the compiler wrote them. ## The two commands [**`cargo cgp check`**](./check.md) stands in for `cargo check` when you hit or expect a wiring error. -Everything after `check` is forwarded to cargo, so the flags you already use work unchanged. +Everything after `check` is passed to `cargo check`, so the flags you already use work unchanged. + +[**`cargo cgp expand`**](./expand.md) prints the Rust your CGP macros generated, with CGP's type-level +constructs written the way you wrote them: a field name reads `Symbol!("height")` rather than a list of +characters. Use it when you want to know what a macro produced rather than guess. + +## What it costs + +**Installing it takes a nightly toolchain.** The tool embeds the Rust compiler, so it needs one exact +nightly with the compiler's development libraries, which is more than a gigabyte of disk. Setup +downloads that toolchain and builds a driver binary against it. Your project does not switch +toolchains: the nightly is used only for the tool's own check. + +**The first check rebuilds your dependencies.** A check builds into its own `target/cgp` directory +under that nightly, so the first run compiles every dependency once more and keeps a second set of +build artifacts beside your normal ones. Later checks reuse them. + +If you work with a coding assistant, [CGP's agent skill](/docs/ai/skills) teaches it to run +`cargo cgp check` and read what comes back. That makes the error output cheaper to work through; it +does not replace reading the conclusion yourself. + +## What it does not do + +**It is not a build tool.** There is no `cargo cgp build`, `run`, or `test`. CGP compiles on stable Rust +1.89 or newer, so build, run, and test with ordinary cargo. -[**`cargo cgp expand`**](./expand.md) prints what your CGP macros generated, with CGP's type-level -constructs spelled the way you wrote them — a field tag reads `Symbol!("height")` rather than the -six-level `Chars` list above. It is how you answer "what did that macro actually produce?" rather than -reasoning about what it probably produced. +**It does not decide whether your code compiles.** A check runs a different compiler and trait solver +from your project's, so treat it as a diagnostic pass, the way Clippy runs under its own settings. +Your own toolchain's `cargo check` is the authority on whether the code builds. -## What it is not +**It does not reshape every error.** `cargo cgp check` leads with the root cause for the classes it +recognizes, and the tool does not yet reshape every class. +[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the ones that pass +through, and where to read about them instead. It also reshapes errors only in your workspace's own +crates. -**It is optional, and it is not a build tool.** CGP is an ordinary library that compiles on **stable -Rust 1.89 or newer**, so `cargo build`, `cargo run`, and `cargo test` work on a CGP project unchanged -and should stay as they are. There is no `cargo cgp build` or `cargo cgp test`. Reach for -`cargo cgp check` when you want a wiring error made readable, and plain `cargo check` when you do not. +**It is tested on Linux.** macOS and Windows have not been tested yet. -**It is a diagnostic pass rather than a reproduction of your own build.** A check runs under the tool's -pinned nightly, turns on the next-generation solver, and builds into a separate `target/cgp` directory, -so it neither adopts your project's toolchain nor disturbs its build cache — much as Clippy runs under -its own settings. +## Where to go next -**It is a `v0.1.0-alpha`, and the honest description is *dramatically better, not solved*.** The tool -reshapes the core wiring errors and passes everything else through as the compiler wrote it, so some -classes — orphan-rule violations among them — still arrive raw. If you hit one, the -[reference](/docs/reference) and [`check_components!`](/docs/reference/macros/check_components) are -still the tools that localize it. +Start with installation, then the page for what you want to do: -## Next +- [Installation](./installation.md): installing with cargo or Nix, checking the install, updating, + and uninstalling. +- [Check](./check.md): running a check, and trying it on a deliberate mistake. +- [Reading the output](./reading-output.md): every shape of error the tool produces, part by part. +- [Expand](./expand.md): reading what your CGP macros generated. +- [Troubleshooting](./troubleshooting.md): when the tool itself will not run. +- [Error codes](./error-codes.md) and [Command reference](./command-reference.md): to look something + up. -- [Installation](./installation.md) — cargo, Nix, running it without installing, or asking your coding - assistant to set it up. -- [Check](./check.md) — running it, reading the output, and wiring it into your editor. -- [Expand](./expand.md) — seeing through the macros, and why it is not `cargo-expand`. -- [Troubleshooting](./troubleshooting.md) — matching an error to its cause when the tool itself will not - run. +For a guided walk through one mistake, from the raw error to the fix, the area-calculation tutorial's +[checking part](/docs/tutorials/area-calculation/checking) uses the tool on a program it builds up +step by step. --- -*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the -tool's output. See -[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*An AI agent wrote this page using the CGP knowledge base, and its outputs were produced by running the +commands. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index 146df2ab..171cb988 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -1,190 +1,234 @@ --- +title: 'Install cargo-cgp with cargo or Nix' +sidebar_label: 'Installation' sidebar_position: 2 +description: 'Install cargo-cgp v0.1.0 with cargo and rustup or with Nix, check that it runs, update it, use it in CI, and remove it again.' --- # Installation -`cargo-cgp` is two binaries plus one exact nightly compiler, and installing it means getting all three -in place and matched. The `cargo-cgp` front-end is the subcommand you type; the `cargo-cgp-driver` it -calls links the compiler's internals, so it has to be built against the nightly it embeds. +Install [`cargo-cgp`](./index.md) with cargo if your Rust comes from rustup, or with Nix if you use +Nix. This page covers version 0.1.0 of the tool, which is built for CGP v0.8. -You never type that nightly date, and **your own project never adopts it** — the tool forces its -toolchain only for its own check, and your project keeps whatever it already uses for ordinary builds. +On the cargo path, installing takes two commands, because the tool comes in two parts. `cargo-cgp` is +the cargo subcommand you type. `cargo-cgp-driver` is the program it runs in place of the compiler, and +it embeds the compiler itself, so it has to be built against one exact nightly toolchain. You never +type that nightly's date, and **your project does not switch to it**: the tool uses the nightly for its +own check only. ## Which path to use -| You have | Use | Why | +Match what your machine already has to the path for it: + +| You have | Use | What it does | |---|---|---| -| rustup | [cargo](#with-cargo) | Installs a small front-end, then provisions the rest for you | -| Nix | [Nix](#with-nix) | Builds both binaries against the pinned nightly; no rustup needed | -| Nix, and want to try it once | [without installing](#without-installing) | Runs from the flake in place | -| A coding assistant | [the agent skill](#let-your-coding-assistant-do-it) | It detects the tool is missing and offers to install it | +| rustup | [With cargo](#with-cargo) | Installs the small front end, then provisions the nightly and the driver | +| Nix | [With Nix](#with-nix) | Builds both binaries against the pinned nightly; no rustup needed | +| Nix, and want to try it once | [Without installing](#without-installing) | Runs the tool from the flake, putting nothing on your `PATH` | +| Neither | [Install rustup or Nix first](#neither-rustup-nor-nix) | No packaged path fits | ## With cargo -Two commands, and the first is one you can type from memory because it carries no version in it: - ```sh cargo install cargo-cgp cargo cgp setup ``` -They divide the work deliberately. `cargo install cargo-cgp` builds the front-end, which has no -compiler linkage and so installs under whatever toolchain you already have. `cargo cgp setup` then does -everything heavyweight: it installs the pinned nightly with its `rustc-dev` and `llvm-tools` -components, builds the driver against that exact nightly, and places it beside the front-end. `setup` -needs rustup, since that is what it manages toolchains through. +**`cargo install cargo-cgp` installs the front end.** It is an ordinary binary with no compiler +inside, so it builds with whatever toolchain you already have. + +**`cargo cgp setup` does the rest.** It asks rustup to install the pinned nightly with the `rustc-dev` +and `llvm-tools` components, then builds `cargo-cgp-driver` at the same version as the front end under +that nightly, and places it beside the front end in `~/.cargo/bin`. It needs rustup and a network +connection, and it takes a while: the toolchain is more than a gigabyte, and the driver is compiled on +your machine. + +Run `setup` once after installing, and again only when the tool tells you to. Before every check the +front end runs a quick, read-only test of the toolchain and the driver. If either is missing or the two +do not match, it stops with a message naming `cargo cgp setup` as the fix, rather than downloading +anything on its own. [Troubleshooting](./troubleshooting.md#the-preflight-rejects-the-setup) lists those +messages. -You run `setup` once, and again only when the tool tells you to. Before each check the front-end runs a -fast read-only preflight; if the driver is missing, the toolchain absent, or the two out of step, it -stops and names `cargo cgp setup` as the fix rather than doing slow or stateful work behind your back. +`setup` and `update` take no options, and they ignore anything you pass after them. In particular, +`cargo cgp setup --help` runs setup rather than printing help; run `cargo cgp --help` instead. ## With Nix -The flake builds both binaries against the pinned nightly and wraps them so they run without rustup — -so a machine with only Nix can run the tool, and the project you check needs no toolchain of its own. +The flake builds both binaries against the pinned nightly and wraps them so they find its libraries +without rustup. A machine with only Nix can run the tool this way. ```sh -nix profile install github:contextgeneric/cargo-cgp +nix profile install github:contextgeneric/cargo-cgp/v0.1.0 ``` -Append a released tag to pin an exact version rather than the default branch, which is the form to -prefer when you want the install reproducible: +The `/v0.1.0` suffix pins the install to that release. Without it, the flake tracks the repository's +default branch, which is what you want only if you are following the tool's development. -```sh -nix profile install github:contextgeneric/cargo-cgp/v0.1.0-alpha +To pin the tool inside another project's flake, add it as an input and take its default package: + +```nix +inputs.cargo-cgp.url = "github:contextgeneric/cargo-cgp/v0.1.0"; +# then, in a devShell or CI derivation: +# packages = [ cargo-cgp.packages.${system}.default ]; ``` ## Without installing -To try the tool on a project without putting anything on your `PATH`, run the flake's default app from -that project's directory. Everything after `--` is forwarded to the check: +To try the tool on a project without installing anything, run the flake's default app from that +project's directory. Everything after `--` is passed to the tool, so this is `cargo cgp check`: ```sh cd /path/to/your/project -nix run github:contextgeneric/cargo-cgp -- check +nix run github:contextgeneric/cargo-cgp/v0.1.0 -- check ``` -This is also the form to use in CI. Add a `/v0.1.0-alpha` suffix to pin the release, or leave it off to -track the default branch. +## Neither rustup nor Nix -To pin the tool inside another project's own flake, take its `packages.default`: - -```nix -inputs.cargo-cgp.url = "github:contextgeneric/cargo-cgp/v0.1.0-alpha"; -# then, in a devShell or CI derivation: -# packages = [ cargo-cgp.packages.${system}.default ]; -``` +**If your Rust comes from somewhere else, such as an operating system package, neither path works as +it stands.** The driver has to be built against one exact nightly with the compiler's development +libraries, and only rustup or the Nix flake provides that. Installing rustup alongside a packaged Rust +is the usual way forward. CGP itself does not need either: it compiles on any stable Rust 1.89 or +newer. -## Let your coding assistant do it +## Checking your install -If you work with an LLM assistant that has [CGP's agent skill](/docs/ai/skills) loaded, you do not have -to drive this yourself. The skill tells the assistant to check whether `cargo-cgp` is available before -debugging any CGP compile error, to recommend it when it is missing, and to prefer it over plain -`cargo check` when diagnosing a wiring failure. Asking your assistant to set up CGP tooling is enough. +Ask the front end for its version: -Two things the skill is deliberately careful about, so you are not surprised: +```sh +cargo cgp --version +``` -- **It asks before installing.** Provisioning a nightly toolchain and building a compiler-linked driver - is heavy, so the skill instructs the assistant to get your approval rather than run `setup` on its - own. -- **It prefers cargo, and only mentions Nix if you have it.** The skill reaches for the Nix path when a - `nix` command or a `flake.nix` is actually present, and otherwise does not bring it up. +It prints the version of the tool you are running. `cargo cgp --help` prints the same version on its +first line, followed by the list of commands. -## Checking what you have +The driver has its own version query, and it doubles as a test that the driver can run at all, because +the driver loads the compiler's libraries before printing anything: ```sh -cargo cgp +cargo-cgp-driver --version ``` -With no subcommand, the front-end prints its version and the commands it accepts. **Read the command -list rather than the version number**, because the two can disagree: a build from the default branch -still reports the released version while carrying commands that release does not have. If `expand` is -absent from the list, see the note below. - -The driver has its own version query, which loads the compiler library before printing and so doubles -as a check that it can run at all: +On the cargo path that command runs under your default toolchain rather than the pinned nightly, so it +can fail with a library-loading error even when the install is fine: the front end sets up the +library path for the driver every time it runs it. Run the probe the way the front end would: ```sh -cargo-cgp-driver --version +LD_LIBRARY_PATH="$(rustc +nightly-YYYY-MM-DD --print sysroot)/lib" cargo-cgp-driver --version ``` -On success it prints three lines — its own version, the `pinned-toolchain:` it needs, and the -`built-against-rustc:` compiler it was built with. That first pair is the fastest way to see which -nightly a driver actually wants. +where `nightly-YYYY-MM-DD` is the pinned nightly, the one `cargo cgp setup` installed and +`rustup toolchain list` now shows. A Nix-installed driver needs no library path and runs as it is. On +success it prints three lines: + +```text +cargo-cgp-driver 0.1.0 +pinned-toolchain: nightly-2026-09-14 +built-against-rustc: rustc 1.100.0-nightly (4b6d04e70 2026-09-13) +``` -:::note +The second line names the nightly the driver needs, and the third the compiler it was built with. Your +dates may differ from these; the lines are the way to read them. -### `expand` is newer than the published release +## Supported platforms and CGP versions -`cargo cgp expand` landed after `v0.1.0-alpha` was tagged, so an install from crates.io does not carry -it — `cargo cgp check` is unaffected. Until the next release, get it from the flake with the tag -dropped, which tracks the default branch: +**The tool is tested on Linux.** It has not yet been tested on macOS or Windows. + +**It is built for CGP v0.8.** The tool recognizes CGP's errors by the names of the traits and crates +CGP defines, so a project on an older CGP version compiles under it as it would under `cargo check`, +but whether its errors are reshaped has not been tested. + +## Updating + +On the cargo path, one command updates the tool: ```sh -nix run github:contextgeneric/cargo-cgp -- expand --lib +cargo cgp update ``` -or from a [source build](#from-source). +It looks up the published versions on crates.io and does nothing if you already have the newest. When +there is a newer one, it reinstalls the front end and runs the new version's `setup`, so the driver and +the pinned nightly move with it. It stays within your release channel: a stable install moves only to +stable releases, and a pre-release install to newer pre-releases or a stable release. -::: +On the Nix path there is no `cargo cgp update`. Change the version in the flake reference and reinstall +the profile, or run `nix flake update cargo-cgp` in a flake that pins the tool as an input. -## From source +### Upgrading from the v0.1.0-alpha pre-release -To run the current code, clone and build. The repository's own `rust-toolchain.toml` selects the right -nightly automatically: +**An install of the `v0.1.0-alpha` pre-release cannot update itself to 0.1.0.** `update` runs the code +of the version you have, and the pre-release only ever looks for newer pre-releases. Reinstall instead: ```sh -git clone https://github.com/contextgeneric/cargo-cgp -cd cargo-cgp -cargo build +cargo install cargo-cgp +cargo cgp setup ``` -Then run the freshly built front-end against another project, pointing it at the built driver and -skipping the preflight: +On the Nix path, install the `v0.1.0` reference as above. -```sh -CARGO_CGP_NO_MANAGE=1 CARGO_CGP_DRIVER=$PWD/target/debug/cargo-cgp-driver \ - /path/to/cargo-cgp/target/debug/cargo-cgp check -``` +## Using it in CI -For most from-source use the Nix flake is easier, because it wires these overrides for you. +**Keep your own toolchain's `cargo check` as the gate, and add the tool for readable failures.** The +commands are the same as on your machine; pin them so a build does not change under you, either with +`cargo install cargo-cgp --version 0.1.0 --locked` followed by `cargo cgp setup`, or with the tagged +Nix reference. -## Updating +On the cargo path every fresh machine downloads the pinned nightly and compiles the driver, which is +the slowest part of the install. If your CI service can cache directories between runs, caching +`~/.cargo/bin` and the pinned nightly under `~/.rustup/toolchains/` avoids repeating that. This page does +not cover any particular CI service, and these setups have not been run there. + +## Uninstalling -On the cargo path, one command: +Remove the binaries with whatever placed them; there is no `cargo cgp uninstall`. ```sh -cargo cgp update +cargo uninstall cargo-cgp cargo-cgp-driver # cargo path: both, since setup installed the driver +nix profile remove cargo-cgp # Nix path ``` -It reads the crates.io index, stays within your current release channel — a stable install never jumps -to a pre-release, and a pre-release install stays on pre-releases — and does nothing if you are already -current. When there is something newer it reinstalls the front-end and re-runs `setup` so the driver and -toolchain move with it. On Windows the running binary cannot replace itself, so `update` prints the two -commands to run by hand instead. +Neither removes the pinned nightly, since another tool may use the same toolchain. Remove it yourself +when nothing else needs it; its name is the `pinned-toolchain:` line of `cargo-cgp-driver --version`: -On the Nix path there is no `cargo cgp update`: upgrade the profile (`nix profile upgrade`), or run -`nix flake update cargo-cgp` where you pinned it as an input. +```sh +rustup toolchain uninstall nightly-YYYY-MM-DD +``` -## Uninstalling +Neither removes the `target/cgp` directories the tool built in your projects either. Delete them as you +would any build output, for example with `cargo clean --target-dir target/cgp` from the project's root. -There is no `cargo cgp uninstall`; you remove the binaries with whatever placed them. +## From source + +To run the tool from a checkout, for example to work on it, clone and build. The repository's +`rust-toolchain.toml` selects the pinned nightly for you, which needs rustup: ```sh -nix profile remove cargo-cgp # Nix path -cargo uninstall cargo-cgp cargo-cgp-driver # cargo path — both, since setup installed the driver +git clone https://github.com/contextgeneric/cargo-cgp +cd cargo-cgp +cargo build ``` -Neither removes the pinned nightly, because another tool may still want that dated toolchain. Remove it -by hand only when nothing else needs it; its name is the `pinned-toolchain:` line of -`cargo-cgp-driver --version`: +Then run the built front end in another project, pointing it at the built driver and turning off the +read-only test, which expects an installed setup: ```sh -rustup toolchain uninstall +CARGO_CGP_NO_MANAGE=1 CARGO_CGP_DRIVER=/path/to/cargo-cgp/target/debug/cargo-cgp-driver \ + /path/to/cargo-cgp/target/debug/cargo-cgp check ``` +With the test turned off, the tool does not switch to the pinned nightly for you either, so the project +you check must be using that nightly too, or the driver will fail to load. The Nix flake handles this +for you, so it is usually the easier way to run a checkout: from the project you want to check, run +`nix run /path/to/cargo-cgp -- check`. The [command reference](./command-reference.md#environment-variables) +describes both variables. + +## A coding assistant can set it up + +If you work with a coding assistant that has [CGP's agent skill](/docs/ai/skills) loaded, it checks +whether `cargo-cgp` is installed before debugging a CGP error and recommends it when it is missing. The +skill tells the assistant to ask before installing, because setup downloads a toolchain and builds a +compiler-linked binary, and to mention Nix only when you use it. + --- -*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the -tool. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*An AI agent wrote this page using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/reading-output.md b/docs/cargo-cgp/reading-output.md new file mode 100644 index 00000000..6c8f593b --- /dev/null +++ b/docs/cargo-cgp/reading-output.md @@ -0,0 +1,224 @@ +--- +title: 'Reading cargo-cgp output: the parts of a CGP error' +sidebar_label: 'Reading the output' +sidebar_position: 4 +description: 'How to read the errors cargo cgp check prints: the headline and its code, the root cause, the dependency tree, several causes at once, conflicts, and fixes.' +--- + +# Reading the output + +`cargo cgp check`, part of the [`cargo-cgp`](./index.md) toolchain for +[Context-Generic Programming (CGP)](/docs/), prints ordinary compiler diagnostics, with the CGP errors +it recognizes rewritten into a few fixed shapes. This page takes each shape apart. Every example comes +from running the tool on the program shown beside it, and every `[CGP-Exxx]` code is listed on +[Error codes](./error-codes.md). + +## The parts of a rewritten error + +Most errors you will see have the shape of this one, from the +[checked program on the Check page](./check.md#check-the-wiring-where-you-write-it), where `Rectangle` +lacks the `height` field its area provider reads: + +```text +error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` + --> src/lib.rs:29:9 + | +29 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + └─ [CGP-E106] missing field `height` on `Rectangle` + +For more information about this error, try `rustc --explain E0277`. +``` + +Read it in four parts: + +- **The compiler's code**, `error[E0277]`, is the one the compiler assigned, and it is always kept. A + rewritten error restates the compiler's error rather than replacing it, so `rustc --explain E0277` + still applies. +- **The headline** starts with a CGP code and says what failed, in CGP's terms. Here `[CGP-E001]` means + a context does not implement a consumer trait: `Rectangle` cannot use `CanCalculateArea`. +- **The `root cause:` line** says why, and it is the line that names the fix. Its code describes the + cause; `[CGP-E106]` is a missing field. +- **The dependency chain** shows how the requirement reached the cause, one step per line, read from + the top. `[CGP-E101]` is the context's consumer trait, `[CGP-E102]` is the provider wired for it, and + the last line repeats the root cause where the chain ends. + +The chain matters when the fix is not where the caret points. If the provider in the `[CGP-E102]` line +is not the one you meant to wire, the mistake is in the wiring rather than in the struct. + +The caret stays where the compiler put it: on the `check_components!` entry that asserted the +requirement, or on the call that used the trait when nothing checked it first. The +[Check page](./check.md#try-it-on-a-deliberate-mistake) shows the second case, where the compiler's +own message leaves the cause out entirely. + +## Several causes in one error + +When one requirement fails for more than one reason, the tool lists every cause under `root causes:` +and branches the chain to show each one. Here `Rectangle` has a `length` field and neither of the two +the provider reads: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub length: f64, +} +``` + +```text +error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` + --> src/lib.rs:28:9 + | +28 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root causes: + - [CGP-E106] missing field `height` on `Rectangle` + - [CGP-E106] missing field `width` on `Rectangle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + ├─ [CGP-E106] missing field `height` on `Rectangle` + └─ [CGP-E106] missing field `width` on `Rectangle` + +For more information about this error, try `rustc --explain E0277`. +``` + +Fix every listed cause before checking again. Plain `cargo check` reports only the `width` field for +this program, so fixing what it names would surface `height` on the next run. + +The same merging works in the other direction. When several components fail because of one shared +mistake, such as a single missing field that three providers read, the tool reports one error whose +headline names all three consumer traits, rather than three errors with the same cause. + +## A field with the wrong type + +When the field exists but has the wrong type, the headline states the whole cause, so the error has +no separate `root cause:` line. Here `height` is a `u32` where the provider reads an `f64`: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: u32, +} +``` + +```text +error[E0271]: [CGP-E003] expected a `height` field of type `f64` on `Rectangle`, but found `u32` + --> src/lib.rs:29:9 + | +29 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + └─ [CGP-E109] field `height` on `Rectangle` has type `u32`, but `f64` is required + +For more information about this error, try `rustc --explain E0271`. +``` + +The chain still shows which provider needs the type, which tells you whether to change the field or +the provider. An [abstract type](/docs/concepts/abstract-types) wired one way and required another +produces the same shape with `[CGP-E017]`. + +## Two entries that claim one key + +A wiring conflict is reported where it happens, with two carets and no chain. Here one context wires +the same component twice: + +```rust +delegate_components! { + App { + GreeterComponent: GreetHello, + GreeterComponent: GreetGoodbye, + } +} +``` + +```text +error[E0119]: [CGP-E004] duplicate wiring for component `GreeterComponent` on `App` + --> src/lib.rs:27:9 + | +26 | GreeterComponent: GreetHello, + | ---------------- first implementation here +27 | GreeterComponent: GreetGoodbye, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `App` + +For more information about this error, try `rustc --explain E0119`. +``` + +The two carets point at the two entries; remove the one you did not mean. The neighbouring codes +`[CGP-E005]` to `[CGP-E008]` cover the other ways two entries can claim one key, such as a path key +that covers a longer one, or an entry that collides with an `open` statement. + +## A fix in a `help` line + +Some mistakes have one right fix, and the tool states it in a `help` line. Here a +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) function calls another CGP function on `self` without +declaring it as a dependency: + +```rust +#[cgp_fn] +fn person_name(&self, #[implicit] name: &str) -> String { + name.to_owned() +} + +#[cgp_fn] +fn greeting(&self) -> String { + format!("Hello, {}!", self.person_name()) +} +``` + +```text +error[E0599]: [CGP-E012] the trait `PersonName` is used but not declared as a dependency + --> src/lib.rs:10:32 + | +10 | format!("Hello, {}!", self.person_name()) + | ^^^^^^^^^^^ + | + = help: declare it as a dependency with `#[uses(PersonName)]` + +For more information about this error, try `rustc --explain E0599`. +``` + +Adding `#[uses(PersonName)]` under `#[cgp_fn]` on `greeting` fixes it. The compiler's own message for +this mistake talks about a method that exists for `&__Context__`, a type parameter the macro +generated, and never names the missing attribute. The codes from `[CGP-E012]` to `[CGP-E016]` all work +this way, each for a different attribute or trait mistake. + +## Errors that pass through unchanged + +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet +reshape every class. An error with no `[CGP-Exxx]` code in its headline is one it passed through, so +read it as the compiler wrote it. These are the ones you are most likely to meet: + +- **A per-entry generic that never reaches the key**, which the compiler reports as `E0207` twice, with + two suggested fixes of which only the second matches the mistake. See + [A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing). +- **Errors in code a macro generated**, such as a shorthand that lowers to an unsized type, or an + imported type name that does not exist. These land on the macro's attribute. See + [A macro lowered something the compiler rejects](/docs/reference/errors#a-macro-lowered-something-the-compiler-rejects). +- **Failures of the extensible-data operations**: casts between enums, builders, extractors, and + dispatch over enum variants. Their errors name generated helper types rather than the variant or + field at fault. [Extensible variants](/docs/concepts/extensible-variants) and + [extensible records](/docs/concepts/extensible-records) explain what those operations require. +- **An undeclared trait called inside a [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider's + body.** The same mistake in a `#[cgp_fn]` body is reshaped, as shown above; inside a provider it + arrives as the compiler's `E0599` about `&__Context__`. The fix is the same `#[uses(...)]` + attribute. + +Errors in crates outside your workspace also pass through, because the tool reshapes only your +workspace's own crates. For any error that arrives raw, the +[compile-errors reference](/docs/reference/errors) starts from the compiler's own message and works +back to the mistake. + +--- + +*An AI agent wrote this page using the CGP knowledge base, and its outputs were produced by running the +commands. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index 4979ca34..18d6f7e8 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -1,242 +1,277 @@ --- -sidebar_position: 5 +title: 'Troubleshooting cargo-cgp' +sidebar_label: 'Troubleshooting' +sidebar_position: 6 +description: 'Match an error from cargo-cgp itself to its cause and fix: the setup check, a driver that will not load or cannot be found, wrong invocations, and slow checks.' --- # Troubleshooting -`cargo-cgp` is two binaries plus one exact nightly compiler, held together by a sibling-path lookup and -a couple of environment variables. When it will not run, the fault sits at one of those seams. This -page maps the error you see to the seam it came from. +This page is for when [`cargo-cgp`](./index.md) itself will not run, or behaves in a way you did not +expect. For help reading a CGP error the tool printed about your code, see +[Reading the output](./reading-output.md) instead. + +`cargo-cgp` is two programs and one exact nightly toolchain. The `cargo-cgp` front end looks for +`cargo-cgp-driver` in its own directory, and the driver loads the compiler's libraries from the pinned +nightly. Most failures come from one of those three not matching the others. The tool is tested on +Linux, and the library paths on this page are the Linux ones. ## Start with the symptom index -Match the distinctive fragment of your error, then read the section. +Find the distinctive part of your error in the left column, then read the section it points to. | Error fragment | Cause | Section | |---|---|---| -| `unknown cargo-cgp subcommand` | wrong invocation | [The command itself fails](#the-command-itself-fails) | -| `could not find Cargo.toml` | run outside a cargo package | [The command itself fails](#the-command-itself-fails) | -| `is cargo on PATH?` | cargo missing from `PATH` | [The command itself fails](#the-command-itself-fails) | +| `toolchain … is not available` | the pinned nightly is not installed | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `is rustup on PATH?` | no rustup to find the pinned nightly with | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `could not run under toolchain` | the driver was built against another nightly | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `out of lockstep` | the front end and driver have different versions | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `now provides` | the pinned nightly changed since the driver was built | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `could not parse` … `--version` output | an old or unrelated driver binary | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `error while loading shared libraries: librustc_driver-…` | library path unset, or the wrong toolchain | [The driver cannot load the compiler](#the-driver-cannot-load-the-compiler) | | `failed to run the cargo-cgp-driver at …` | driver missing | [The driver cannot be found](#the-driver-cannot-be-found) | -| `could not execute process` … `(never executed)` | driver path wrong | [The driver cannot be found](#the-driver-cannot-be-found) | -| `error while loading shared libraries: librustc_driver-…` | library path unset, or toolchain mismatch | [The driver cannot load the compiler](#the-driver-cannot-load-the-compiler) | -| `--print sysroot` failed with `exit status: 127` | Nix install shadowed by a same-version rustup toolchain | [A Nix install fails its sysroot probe](#a-nix-install-fails-its-sysroot-probe) | -| `the pinned toolchain is not installed` | nightly absent | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | -| `could not run under toolchain …` | driver built against another nightly | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | -| `out of lockstep` / `now provides` | front-end and driver disagree | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | -| `rustup was not found on PATH` | no rustup for `setup` | [Provisioning fails](#provisioning-fails) | - -## Isolating the failure - -Two probes narrow almost anything before you read further. +| `could not execute process` … `(never executed)` | driver path wrong, with the preflight turned off | [The driver cannot be found](#the-driver-cannot-be-found) | +| `unknown cargo-cgp subcommand` | wrong command name | [The command itself fails](#the-command-itself-fails) | +| `could not find Cargo.toml` | run outside a cargo package | [The command itself fails](#the-command-itself-fails) | +| `unexpected argument` | a flag `cargo check` does not know | [The command itself fails](#the-command-itself-fails) | +| `rustup was not found on PATH` | `setup` needs rustup | [Setup fails](#setup-fails) | +| `--print sysroot` failed with `exit status: 127` | a pre-release Nix install | [A Nix pre-release install fails its sysroot probe](#a-nix-pre-release-install-fails-its-sysroot-probe) | -**First, ask the driver for its version.** It loads the compiler library before printing, so this -doubles as a test that it can run at all: +Some problems print no error at all: a check that disagrees with `cargo check`, a check that is slow +or builds a second `target/cgp`, and a compiler wrapper of your own that stopped running. Each has a +section near the end of the page. -```sh -cargo-cgp-driver --version -``` +## Narrowing it down -If that fails, the problem is the driver or its library path, not the front-end — jump to -[The driver cannot load the compiler](#the-driver-cannot-load-the-compiler). On success it prints the -`pinned-toolchain:` it needs and the `built-against-rustc:` it was built with, which is the fastest way -to see which nightly a given driver actually wants. +**Run the check once more and read the first line of the error.** Before every check, the front end +runs a quick, read-only test of the toolchain and the driver, the preflight. A message beginning with +`cargo-cgp:` and ending with "Run `cargo cgp setup`" comes from that test, and the +[preflight section](#the-preflight-rejects-the-setup) covers each one. -**Then run the check verbosely:** +**If the preflight passes, run the check verbosely:** ```sh cargo cgp check -v ``` -Each `Running …` line showing a `cargo-cgp-driver … rustc …` command is the driver being invoked. An -error *before* those lines is a front-end or preflight problem; an error *from* one of them is a driver -or compiler problem. +Each `Running` line that shows a `cargo-cgp-driver … rustc …` command is cargo calling the driver for one +crate. An error before those lines is a front-end or setup problem; an error from one of them is a +driver or compiler problem. -## The command itself fails +## The preflight rejects the setup + +Almost every message in this section is resolved by running `cargo cgp setup`, which installs the pinned +nightly and rebuilds the driver against it at the front end's version. The messages tell you which part +was wrong. The examples show `nightly-2026-09-14`; yours names the nightly your build is pinned to. -The simplest failures never reach the driver. An unknown or missing subcommand is reported with the -list of what is accepted: +**The pinned nightly is not installed:** ```text -cargo-cgp: unknown cargo-cgp subcommand `frobnicate` (expected `check`, `expand`, `setup`, or `update`) -``` +cargo-cgp: toolchain `nightly-2026-09-14` is not available (exit status: 1) -If your build lists only three and omits `expand`, that is not a fault — it predates that command. See -[Installation](./installation.md#expand-is-newer-than-the-published-release). +The pinned toolchain is not installed. Run `cargo cgp setup`. +``` -Running outside a cargo package produces cargo's error rather than the tool's, because the front-end -forwards to `cargo check`: +**There is no rustup to ask.** The front end finds the pinned nightly through rustup, so on a machine +without it the same advice appears with a different first line: ```text -error: could not find `Cargo.toml` in `/some/dir` or any parent directory +cargo-cgp: failed to run `rustc` (is rustup on PATH?) + +The pinned toolchain is not installed. Run `cargo cgp setup`. ``` -Run it from inside the package or workspace you mean to check. And if cargo is not on `PATH` at all, -the front-end says so while trying to launch the build: +Here `setup` cannot help, since it needs rustup too; install rustup, or use the +[Nix flake](./installation.md#with-nix), which does not run the preflight. + +**The toolchain is installed, but the driver cannot run under it**, almost always because the driver +was built against a different nightly: ```text -failed to run `cargo check` (is cargo on PATH?) +cargo-cgp: the cargo-cgp-driver could not run under toolchain `nightly-2026-09-14` (it was likely built against a different nightly). Run `cargo cgp setup`. ``` -## The driver cannot be found +**The driver runs, but its version differs from the front end's.** This follows a partial upgrade, or +an older driver found first: -The front-end looks for the driver **beside itself**, in the same directory, unless `CARGO_CGP_DRIVER` -says otherwise. When it is missing, the message depends on whether the preflight is running. +```text +cargo-cgp: the installed cargo-cgp-driver is version 0.0.9, but this cargo-cgp is 0.1.0 (the two are out of lockstep) + +Run `cargo cgp setup`. +``` -Normally the preflight catches it and names the fix: +**The driver was built by a different compiler than the pinned nightly now provides**, which happens +when that nightly has been reinstalled: ```text -cargo-cgp: failed to run the cargo-cgp-driver at /path/to/cargo-cgp-driver: No such file or directory (os error 2) +cargo-cgp: the cargo-cgp-driver was built against `rustc 1.99.0-nightly (0123abcde 2026-08-01)`, but the pinned toolchain `nightly-2026-09-14` now provides `rustc 1.100.0-nightly (4b6d04e70 2026-09-13)` Run `cargo cgp setup`. ``` -With the preflight skipped — the from-source and Nix paths set `CARGO_CGP_NO_MANAGE` — the bad path -reaches cargo instead, which reports a wrapper it could not execute: +**The program found as the driver does not answer like one**, such as an unrelated binary with the +same name: ```text -error: could not execute process `/path/to/cargo-cgp-driver …/rustc -vV` (never executed) - -Caused by: - No such file or directory (os error 2) +cargo-cgp: could not parse `cargo-cgp-driver --version` output. Run `cargo cgp setup`. ``` -Either way, make the driver reachable: run `cargo cgp setup` to reinstall it beside the front-end, point -`CARGO_CGP_DRIVER` at the real binary (for a source build, `target/debug/cargo-cgp-driver`), or run -through the Nix flake, which places both binaries together. +If you are deliberately running a build that `setup` did not install, from a source checkout for +example, set `CARGO_CGP_NO_MANAGE=1` to skip the preflight. The tool then trusts your environment, and +keeping the toolchain matched is up to you; the next section describes what happens when it is not. ## The driver cannot load the compiler -This is the most common failure and the most confusing, because the driver aborts *before its own code -runs* and the message comes from the operating system's loader: +**This failure comes from the operating system's loader, before the driver's own code runs**, which is +why it looks unlike any other message from the tool: ```text -cargo-cgp-driver: error while loading shared libraries: librustc_driver-c29d28819724b6fa.so: -cannot open shared object file: No such file or directory +cargo-cgp-driver: error while loading shared libraries: librustc_driver-61d225838afd1915.so: cannot open shared object file: No such file or directory ``` -The driver links `librustc_driver-.so` from the nightly it was built against, and that hash is -fixed at build time. The loader cannot find *that exact library*, for one of two reasons. +The driver links `librustc_driver-.so` from the nightly it was built against, and the hash is +fixed when the driver is built, so yours differs from the one above. The loader could not find that +exact library, for one of two reasons. -**The library path is not set.** You ran the driver directly, without the search-path setup the -front-end normally provides. A Nix-built driver has the path baked into its wrapper and never hits -this; a from-source driver run by hand does. Supply the pinned toolchain's `lib` directory — -`DYLD_FALLBACK_LIBRARY_PATH` on macOS, `LD_LIBRARY_PATH` elsewhere: +**You ran the driver yourself, without the library path.** The front end sets the path every time it +runs the driver, so a working install still fails this way when you run `cargo-cgp-driver` directly. +Supply the pinned nightly's `lib` directory: ```sh -SYSROOT=$(rustc --print sysroot) # under the pinned toolchain -LD_LIBRARY_PATH=$SYSROOT/lib cargo-cgp-driver --version +LD_LIBRARY_PATH="$(rustc +nightly-YYYY-MM-DD --print sysroot)/lib" cargo-cgp-driver --version ``` -**Or the path is set to the wrong toolchain.** The exact library is absent because the active toolchain -is not the one the driver was built against — the driver wants a dated nightly, the environment offers -stable: +with the pinned nightly in place of `nightly-YYYY-MM-DD`. A driver installed with Nix has the path built +in and does not need this. + +**The check ran under a different toolchain from the driver's.** With the preflight turned off, the +tool uses whichever toolchain is active, and when that is not the driver's nightly, cargo's first call +to the driver fails: ```text -error: process didn't exit successfully: `…/cargo-cgp-driver …/stable/…/rustc -vV` (exit status: 127) +error: process didn't exit successfully: `…/cargo-cgp-driver …/stable-…/bin/rustc -vV` (exit status: 127) --- stderr -…/cargo-cgp-driver: error while loading shared libraries: librustc_driver-c29d28819724b6fa.so +…/cargo-cgp-driver: error while loading shared libraries: librustc_driver-61d225838afd1915.so: cannot open shared object file: No such file or directory ``` -A normal install forces the right nightly for you. If you are running unmanaged, either make the pinned -nightly active — work inside the `cargo-cgp` checkout, whose `rust-toolchain.toml` selects it, or set -`RUSTUP_TOOLCHAIN` — or use the Nix flake, which forces the matching nightly from any directory. +Unset `CARGO_CGP_NO_MANAGE` so the tool switches to the pinned nightly itself, or make that nightly the +active toolchain, for example with `RUSTUP_TOOLCHAIN`. Running through the Nix flake also handles it. -## A Nix install fails its sysroot probe +## The driver cannot be found -A Nix-installed tool can fail before compiling anything, on the query it makes to locate the -toolchain's libraries: +**The front end looks for the driver in its own directory**, unless `CARGO_CGP_DRIVER` names another +path, and only then on your `PATH`. When the driver is missing, the preflight reports it: ```text -cargo-cgp: `/nix/store/…-rust-minimal-…/bin/rustc --print sysroot` failed with status exit status: 127: +cargo-cgp: failed to run the cargo-cgp-driver at /path/to/cargo-cgp-driver: No such file or directory (os error 2) -rustc: error while loading shared libraries: libz.so.1: cannot open shared object file +Run `cargo cgp setup`. ``` -Two things make this one recognizable: **the same command run by hand succeeds**, and it fails only in -*some* projects. Both follow from one cause — a foreign toolchain's library directory reaching the Nix -toolchain's binaries. Invoked as `cargo cgp`, the entry point is rustup's `cargo` shim, which exports -the project's active toolchain's `lib` directory to everything it spawns, and the loader searches that -ahead of the binary's own path. - -Whether it matters depends on the project, because a rustc shared library is named for its Rust version -rather than a content hash. A project on a *different* version collides with nothing. A project pinning -the **same** version as the tool's own nightly has a library with exactly the name the Nix `rustc` is -looking for, so it wins the lookup — and being a non-Nix build, it then wants a system `libz.so.1` the -Nix loader cannot resolve. The failure therefore appears in whichever project happens to track the same -Rust version as the tool, which is the opposite of the intuition that a closely matched toolchain is -the safe case. +With the preflight turned off by `CARGO_CGP_NO_MANAGE`, the missing driver reaches cargo instead, which +reports a compiler wrapper it could not start: -The fix ships in the flake, whose wrapper puts the pinned toolchain's `lib` first. Upgrade the install -(`nix profile upgrade cargo-cgp`, or remove and re-add it). To confirm the diagnosis before upgrading, -run the probe with that directory in front — it should succeed where the bare command failed: +```text +error: could not execute process `/path/to/cargo-cgp-driver …/stable-…/bin/rustc -vV` (never executed) -```sh -NIX_RUSTC=/nix/store/…-rust-minimal-…/bin/rustc -LD_LIBRARY_PATH=$(dirname "$NIX_RUSTC")/../lib "$NIX_RUSTC" --print sysroot +Caused by: + No such file or directory (os error 2) ``` -A rustup-managed install does not hit this. +Either way, make the driver reachable. Run `cargo cgp setup` to install it beside the front end, point +`CARGO_CGP_DRIVER` at the real binary (`target/debug/cargo-cgp-driver` in a source checkout), or run +through the Nix flake, which installs both together. Keep the two in the same directory: if the driver +is missing there, the front end falls back to any `cargo-cgp-driver` on your `PATH`, which may be an +older one. -## The preflight rejects the setup - -Before each check the front-end verifies the toolchain and the driver, read-only. Every failure names -`cargo cgp setup` as the fix, and the messages tell the cases apart. +## The command itself fails -The pinned nightly is not installed: +These failures happen before the driver is involved. An unknown command is reported with the list the +tool accepts: ```text -cargo-cgp: toolchain `nightly-2026-07-16` is not available (exit status: 1) - -The pinned toolchain is not installed. Run `cargo cgp setup`. +cargo-cgp: unknown cargo-cgp subcommand `frobnicate` (expected `check`, `expand`, `setup`, or `update`) ``` -The toolchain is there, but the driver cannot run under it — almost always a driver built against a -different nightly: +**Running outside a cargo package** produces cargo's error rather than the tool's, because the tool +runs `cargo check`: ```text -cargo-cgp: the cargo-cgp-driver could not run under toolchain `nightly-2026-07-16` -(it was likely built against a different nightly). Run `cargo cgp setup`. +error: could not find `Cargo.toml` in `/some/dir` or any parent directory ``` -The driver runs but the two are out of lockstep — a partial upgrade, or a stale binary earlier on -`PATH`: +**A flag `cargo check` does not know** is rejected by cargo, since every argument after `check` is +passed to it: ```text -the installed cargo-cgp-driver is version 0.1.0, but this cargo-cgp is 0.2.0 (the two are out of lockstep) +error: unexpected argument '--nope' found +``` -Run `cargo cgp setup`. +## Setup fails + +`cargo cgp setup` installs the toolchain through rustup, so without rustup it stops at once: + +```text +cargo-cgp: installing toolchain `nightly-2026-09-14` (with rustc-dev, llvm-tools)… +cargo-cgp: rustup was not found on PATH; cargo-cgp requires rustup to manage toolchains ``` -Every one of these is resolved by `cargo cgp setup`, which reinstalls the pinned toolchain and rebuilds -the driver against it. If you are deliberately running an unprovisioned build, set `CARGO_CGP_NO_MANAGE` -to skip the preflight — but then keeping the toolchain matched is your responsibility, per -[the section above](#the-driver-cannot-load-the-compiler). +Install through the [Nix flake](./installation.md#with-nix) instead, which needs no rustup, or install +rustup first. `setup` also downloads the toolchain and the driver's source, so it needs a network +connection; a failure during either step comes from rustup or cargo, and their message says what went +wrong. -## Provisioning fails +## A Nix pre-release install fails its sysroot probe -`cargo cgp setup` manages toolchains through rustup, so on a machine without it the command stops -plainly rather than failing obscurely: +A Nix install of the `v0.1.0-alpha` pre-release can fail in some projects before compiling anything: ```text -rustup was not found on PATH; cargo-cgp requires rustup to manage toolchains +cargo-cgp: `/nix/store/…-rust-minimal-…/bin/rustc --print sysroot` failed with status exit status: 127: + +rustc: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory ``` -Install through the [Nix flake](./installation.md#with-nix) instead, which provisions the toolchain at -build time and needs no rustup. +It happens in projects whose own rustup toolchain has the same Rust version as the tool's nightly: +rustup puts that toolchain's libraries ahead of the Nix ones, and they do not load in the Nix +environment. Version 0.1.0 fixes it, so upgrade the install to the `v0.1.0` reference, as described on +the [installation page](./installation.md#with-nix). + +## The check disagrees with `cargo check` + +**Your own toolchain's `cargo check` decides whether your code compiles.** A check runs a different +compiler, a pinned nightly, with Rust's next-generation trait solver turned on, so on code that relies +on nightly-only or solver-specific behavior the two can disagree. When they do, trust `cargo check`, +and use the tool for what it is for: reading the CGP errors both of them report. + +## The check is slow, or a second `target/cgp` appears + +**The first check in a project builds every dependency once more**, into `target/cgp`, because the +check uses its own toolchain and keeps its artifacts apart from your normal build. Later checks reuse +them. + +**The directory is relative to where you run the command.** Run from a subdirectory of your project, +the check creates `target/cgp` inside that subdirectory and builds everything there again. Run it from +the package or workspace root, or pass `--target-dir` to fix the location. Delete a stray directory as +you would any build output. + +## Your own compiler wrapper stopped running + +**The tool sets cargo's `RUSTC_WORKSPACE_WRAPPER` to its driver for the length of a check**, which +replaces any value you set yourself, so a wrapper you configured through that variable does not run +during `cargo cgp check`. Your normal builds are unaffected. -## Still stuck? +## Still stuck -The root cause of most of these is a single thing: **a mismatch between the nightly the driver embeds -and the toolchain present when it runs.** Several different-looking errors trace back to it, so if you -are between sections, run `cargo-cgp-driver --version` and compare its `pinned-toolchain:` line against -`rustc --version` in the directory where the check fails. +Most of these failures share one root: **the nightly the driver embeds is not the toolchain present +when it runs.** If you are between sections, `cargo cgp setup` puts the expected pair back in place on +the cargo path, and reinstalling the profile does the same on the Nix path. -Failures that are not covered here are worth reporting on the -[issue tracker](https://github.com/contextgeneric/cargo-cgp/issues), with the output of -`cargo cgp check -v` and `cargo-cgp-driver --version`. +Failures not covered here are worth reporting on the +[issue tracker](https://github.com/contextgeneric/cargo-cgp/issues). Include the output of +`cargo cgp check -v`, `cargo cgp --version`, and the driver's `--version` run as shown +[above](#the-driver-cannot-load-the-compiler). --- -*An AI agent wrote this page using the CGP knowledge base. See -[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* +*An AI agent wrote this page using the CGP knowledge base, and its messages were produced by running the +tool. See [How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/hypershell/guides/debugging.md b/docs/projects/hypershell/guides/debugging.md index e554df81..58833737 100644 --- a/docs/projects/hypershell/guides/debugging.md +++ b/docs/projects/hypershell/guides/debugging.md @@ -12,8 +12,8 @@ failed. [Hypershell](../index.md) is a shell-scripting language whose programs a with [CGP](/docs/). This guide shows the common mistakes, each with the code that triggers it, the root cause [`cargo cgp check`](/docs/cargo-cgp/check) reports, and the fix. Each output below was produced by running the check and is trimmed to its headline and root cause, with long types -abridged. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is -a v0.1.0-alpha that does not yet reshape every class. +abridged. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool +does not yet reshape every class. ## Check first, then read the root cause @@ -39,7 +39,7 @@ step, which follows the walk on the [assembly](../architecture/assembly.md#following-one-piece-of-syntax) page. Read it from the bottom: the last line is the part that failed. Each step names the table it looked in, so the chain shows whether the failure is in the context, in a bundle, or in an input dispatcher. The codes in brackets -are listed in the [compile errors](/docs/reference/errors#the-cgp-exxx-codes) page. +are listed on the [error codes](/docs/cargo-cgp/error-codes) page. ## A context lacks a field diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 2fb59374..a8969e16 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -22,8 +22,8 @@ It is meant to be looked up rather than read through. If you have an error in fr `cargo check`.** For the worst class it recovers a cause that plain `cargo check` discards entirely, and every "what you see" example below is its real output. -`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a -v0.1.0-alpha that does not yet reshape every class. Where a class passes through as the compiler +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet +reshape every class. Where a class passes through as the compiler wrote it, this page says so and shows the raw form instead. The raw forms quoted here are what stable `rustc` prints. @@ -637,53 +637,13 @@ plain `impl`. ## The `[CGP-Exxx]` codes -A code tags one class of CGP mistake. The compiler's own code is always kept beside it, so -`rustc --explain` still works and nothing is reclassified away from rustc. - -Codes appear in two places and mean different things. A code in the **headline** classifies the error; a -code in the **root-cause tree** labels one link in the chain. - -### Headline codes - -| Code | Means | -|---|---| -| `CGP-E001` | A context does not implement a consumer trait | -| `CGP-E002` | A provider does not implement its provider trait for the context | -| `CGP-E003` | A field is present but has the wrong type | -| `CGP-E004` | The same key wired twice, or a generic table overlapping a specific one | -| `CGP-E005` | Wiring a key that a shorter path key or a namespace entry already covers | -| `CGP-E006` | More than one namespace joined on one context | -| `CGP-E007` | A direct entry colliding with a redirect of the same key, such as an `open` header | -| `CGP-E008` | The same key redirected twice | -| `CGP-E009` | A non-component trait (a wrapper, or a `#[cgp_fn]` blanket trait) blocked by a CGP dependency | -| `CGP-E010` | The wiring recurses without terminating | -| `CGP-E011` | An orphan-rule namespace registration | -| `CGP-E012` | A trait used but not declared with `#[uses]` | -| `CGP-E013` | A consumer trait named in a provider impl header | -| `CGP-E014` | `#[cgp_impl]` applied to a trait that is not a component | -| `CGP-E015` | A consumer trait named in an inner-provider bound | -| `CGP-E016` | An inner provider used but not imported | -| `CGP-E017` | An abstract type wired differently from what a provider pinned | - -### Dependency-tree codes - -| Code | Means | -|---|---| -| `CGP-E101` | A hop through a context's consumer-trait impl | -| `CGP-E102` | A hop through a provider's provider-trait impl | -| `CGP-E104` | A hop through a namespace or `open` redirect | -| `CGP-E105` | A hop through any other trait | -| `CGP-E106` | **Leaf:** a field is absent | -| `CGP-E107` | **Leaf:** the context wires nothing for a component or path | -| `CGP-E108` | **Leaf:** the field exists but `#[derive(HasField)]` is missing | -| `CGP-E109` | **Leaf:** the field has the wrong type | -| `CGP-E110` | **Leaf:** a provider's own dispatch table is missing an entry | -| `CGP-E111` | **Leaf:** something wired where a provider belongs is not a provider | -| `CGP-E112` | **Leaf:** an associated type differs from what was required | -| `CGP-E201` | The root-cause lead for an ordinary Rust trait bound | - -A tree entry that merely passes a non-CGP message through in rustc's own words is left uncoded. -`CGP-E103` is unassigned, so the numbering has a gap there. +A code tags one class of CGP mistake in the output of `cargo cgp check`. The compiler's own code is +always kept beside it, so `rustc --explain` still works and nothing is reclassified away from rustc. A +code in the **headline** classifies the error; a code in the **root-cause tree** labels one link in +the chain. + +[Error codes](/docs/cargo-cgp/error-codes) lists every code with its message, its meaning, its fix, +and the section of this page that explains its class. ## Related constructs diff --git a/example-code/README.md b/example-code/README.md index 33aaf2a2..f210e310 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -37,7 +37,7 @@ One file per page, at the matching path with the file name in `snake_case`: |---|---| | `docs/concepts/` | complete — one file under `tests/concepts/` per page that shows code | | `docs/reference/` | partial — `errors.md`, every `macros/` page and every `attributes/` page that shows code, all of `derives/`, every `traits/` construct page, all of `providers/` that shows code (the singletons, and all of `error/`, `handler/`, `monad/`, and `dispatch/`; `use_field_ref` shows its example on its alias page), all of `components/` (each component page that shows code, including the `handler/` subsection), and all of `types/` (each type page that shows code, the `spines/` subsection included); the section is filled in lazily | -| `docs/cargo-cgp/` | complete — the two pages that show Rust, under `tests/cargo_cgp/` | +| `docs/cargo-cgp/` | complete — the four pages that show Rust: the programs they say compile under `tests/cargo_cgp/`, and the deliberate mistakes under `tests/compile_fail/cargo_cgp/` | | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | | `docs/quickstart.md` | complete — `tests/quickstart.rs`, a standalone binary rather than a section tree | diff --git a/example-code/tests/cargo_cgp/check.rs b/example-code/tests/cargo_cgp/check.rs index 0e79c495..dc74a739 100644 --- a/example-code/tests/cargo_cgp/check.rs +++ b/example-code/tests/cargo_cgp/check.rs @@ -1,12 +1,12 @@ -//! Code from `docs/cargo-cgp/check.md` — *Check*, and the excerpt of it on the section index. +//! Code from `docs/cargo-cgp/check.md` — *Check*. //! -//! The page's whole program is the mistake: `RectangleArea` reads a `height` field through an -//! `#[implicit]` argument and `Rectangle` does not have one. It therefore cannot be a module, and is -//! carried as a `compile_fail` doctest. +//! Both programs on the page are broken on purpose, so both are `trybuild` fixtures: //! -//! What the doctest guards is narrow but real: that the snippet the page calls broken is still broken. -//! It does **not** verify which diagnostic comes out — rustdoc does not enforce that — and it says -//! nothing at all about the `cargo cgp check` output the page quotes beside it. That output was -//! produced by running the tool, and re-running it is the only way to re-verify it. +//! - *Try it on a deliberate mistake* — `tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs`, +//! the unchecked call to `area` on a `Rectangle` without its `height` field. The same program is +//! `index_the_problem_it_solves.rs`, for the section index. +//! - *Check the wiring where you write it* — +//! `tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs`, the same mistake with +//! `print_area` replaced by a `check_components!` block. //! -//! Rejected snippet — trybuild fixture `tests/compile_fail/cargo_cgp/check_check.rs`. +//! The page's repaired program, with `height` restored, is the one [`super::expand`] carries. diff --git a/example-code/tests/cargo_cgp/mod.rs b/example-code/tests/cargo_cgp/mod.rs index fa78588b..11126f3f 100644 --- a/example-code/tests/cargo_cgp/mod.rs +++ b/example-code/tests/cargo_cgp/mod.rs @@ -1,11 +1,18 @@ //! Code from the pages under `docs/cargo-cgp/`. //! -//! Two of the five pages show Rust. `installation.md` and `troubleshooting.md` are shell commands and -//! quoted diagnostics, so they have no file here. +//! Four of the eight pages show Rust: `index.md`, `check.md`, `reading-output.md`, and `expand.md`. +//! The rest are shell commands, quoted messages, and tables, so they have no file here. //! -//! Both pages that do show Rust show the *same* program, once broken and once fixed, because that is -//! the point being made: `check.md` runs the tool on the broken one, and `expand.md` expands the fixed -//! one. The broken version cannot be a module, so it is a `compile_fail` doctest. +//! Almost every program those pages show is broken on purpose, because the point of each is the error +//! `cargo cgp check` prints for it. Those programs are `trybuild` fixtures under +//! `tests/compile_fail/cargo_cgp/`, one per heading, named `_.rs`. The modules here hold +//! the programs the pages say compile: the repaired `Rectangle` that `expand.md` expands, and the +//! repaired `greeting` that `reading-output.md` gives as the fix for `[CGP-E012]`. +//! +//! Neither the fixtures nor these modules check the `cargo cgp check` or `cargo cgp expand` output the +//! pages quote. That output was produced by running the tool on exactly these programs, and re-running +//! it is the only way to re-verify it. pub mod check; pub mod expand; +pub mod reading_output; diff --git a/example-code/tests/cargo_cgp/reading_output.rs b/example-code/tests/cargo_cgp/reading_output.rs new file mode 100644 index 00000000..2f582c6e --- /dev/null +++ b/example-code/tests/cargo_cgp/reading_output.rs @@ -0,0 +1,34 @@ +//! Code from `docs/cargo-cgp/reading-output.md` — *Reading the output*. +//! +//! Every program the page shows is broken on purpose and is a `trybuild` fixture under +//! `tests/compile_fail/cargo_cgp/reading_output_*.rs`. The one program the page says compiles is the fix +//! it gives under *A fix in a help line*: adding `#[uses(PersonName)]` to `greeting`. + +/// *A fix in a `help` line* — the program with the attribute the `[CGP-E012]` help names. +pub mod a_fix_in_a_help_line { + use cgp::prelude::*; + + #[cgp_fn] + fn person_name(&self, #[implicit] name: &str) -> String { + name.to_owned() + } + + #[cgp_fn] + #[uses(PersonName)] + fn greeting(&self) -> String { + format!("Hello, {}!", self.person_name()) + } + + #[derive(HasField)] + pub struct Person { + pub name: String, + } + + #[test] + fn the_declared_dependency_resolves() { + let person = Person { + name: "World".to_owned(), + }; + assert_eq!(person.greeting(), "Hello, World!"); + } +} diff --git a/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs b/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs new file mode 100644 index 00000000..c5c85df8 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs @@ -0,0 +1,35 @@ +// From docs/cargo-cgp/check.md, Check the wiring where you write it: print_area replaced by a check. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + // missing `height` field +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/check_check.stderr b/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr similarity index 67% rename from example-code/tests/compile_fail/cargo_cgp/check_check.stderr rename to example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr index 2c7c07cc..a104d06f 100644 --- a/example-code/tests/compile_fail/cargo_cgp/check_check.stderr +++ b/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr @@ -1,28 +1,28 @@ error[E0277]: the trait bound `Rectangle: CanUseComponent` is not satisfied - --> tests/compile_fail/cargo_cgp/check_check.rs:29:9 + --> tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs:31:9 | -29 | AreaCalculatorComponent, +31 | AreaCalculatorComponent, | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound | help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` but trait `HasField>>>>>>` is implemented for it - --> tests/compile_fail/cargo_cgp/check_check.rs:18:9 + --> tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs:19:9 | -18 | pub width: f64, +19 | pub width: f64, | ^^^^^ note: required for `RectangleArea` to implement `IsProviderFor` - --> tests/compile_fail/cargo_cgp/check_check.rs:8:1 + --> tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs:10:1 | - 8 | #[cgp_impl(new RectangleArea)] +10 | #[cgp_impl(new RectangleArea)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `Rectangle` to implement `CanUseComponent` note: required by a bound in `__CheckRectangle` - --> tests/compile_fail/cargo_cgp/check_check.rs:27:1 + --> tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs:29:1 | -27 | / check_components! { -28 | | Rectangle { -29 | | AreaCalculatorComponent, -30 | | } -31 | | } +29 | / check_components! { +30 | | Rectangle { +31 | | AreaCalculatorComponent, +32 | | } +33 | | } | |_^ required by this bound in `__CheckRectangle` = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs b/example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs new file mode 100644 index 00000000..7932ee7e --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs @@ -0,0 +1,33 @@ +// From docs/cargo-cgp/check.md, Try it on a deliberate mistake. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + // missing `height` field +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +pub fn print_area(rectangle: &Rectangle) { + println!("{}", rectangle.area()); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.stderr b/example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.stderr new file mode 100644 index 00000000..518fe6cc --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.stderr @@ -0,0 +1,43 @@ +error[E0599]: the method `area` exists for reference `&Rectangle`, but its trait bounds were not satisfied + --> tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs:30:30 + | +18 | pub struct Rectangle { + | -------------------- doesn't satisfy `Rectangle: AreaCalculator` or `Rectangle: CanCalculateArea` +... +30 | println!("{}", rectangle.area()); + | ^^^^ this is an associated function, not a method + | + = note: found the following associated functions; to be used as methods, functions must have a `self` parameter +note: the candidate is defined in the trait `AreaCalculator` + --> tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs:7:5 + | + 7 | fn area(&self) -> f64; + | ^^^^^^^^^^^^^^^^^^^^^^ +note: the following trait bounds were not satisfied: + `&Rectangle: AreaCalculator<&Rectangle>` + `Rectangle: AreaCalculator` + --> tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs:5:1 + | + 5 | #[cgp_component(AreaCalculator)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 6 | pub trait CanCalculateArea { + | ^^^^^^^^^^^^^^^^ +note: the trait `AreaCalculator` must be implemented + --> tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs:6:1 + | + 6 | / pub trait CanCalculateArea { + 7 | | fn area(&self) -> f64; + 8 | | } + | |_^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `CanCalculateArea` defines an item `area`, perhaps you need to implement it + --> tests/compile_fail/cargo_cgp/check_try_it_on_a_deliberate_mistake.rs:6:1 + | + 6 | pub trait CanCalculateArea { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use associated function syntax instead + | +30 - println!("{}", rectangle.area()); +30 + println!("{}", Rectangle::area()); + | diff --git a/example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs b/example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs new file mode 100644 index 00000000..3c5ce4e7 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs @@ -0,0 +1,33 @@ +// From docs/cargo-cgp/index.md, The problem it solves: the unchecked call hides the missing field. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + // missing `height` field +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +pub fn print_area(rectangle: &Rectangle) { + println!("{}", rectangle.area()); +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.stderr b/example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.stderr new file mode 100644 index 00000000..aa63d11f --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/index_the_problem_it_solves.stderr @@ -0,0 +1,43 @@ +error[E0599]: the method `area` exists for reference `&Rectangle`, but its trait bounds were not satisfied + --> tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs:30:30 + | +18 | pub struct Rectangle { + | -------------------- doesn't satisfy `Rectangle: AreaCalculator` or `Rectangle: CanCalculateArea` +... +30 | println!("{}", rectangle.area()); + | ^^^^ this is an associated function, not a method + | + = note: found the following associated functions; to be used as methods, functions must have a `self` parameter +note: the candidate is defined in the trait `AreaCalculator` + --> tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs:7:5 + | + 7 | fn area(&self) -> f64; + | ^^^^^^^^^^^^^^^^^^^^^^ +note: the following trait bounds were not satisfied: + `&Rectangle: AreaCalculator<&Rectangle>` + `Rectangle: AreaCalculator` + --> tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs:5:1 + | + 5 | #[cgp_component(AreaCalculator)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 6 | pub trait CanCalculateArea { + | ^^^^^^^^^^^^^^^^ +note: the trait `AreaCalculator` must be implemented + --> tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs:6:1 + | + 6 | / pub trait CanCalculateArea { + 7 | | fn area(&self) -> f64; + 8 | | } + | |_^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `CanCalculateArea` defines an item `area`, perhaps you need to implement it + --> tests/compile_fail/cargo_cgp/index_the_problem_it_solves.rs:6:1 + | + 6 | pub trait CanCalculateArea { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use associated function syntax instead + | +30 - println!("{}", rectangle.area()); +30 + println!("{}", Rectangle::area()); + | diff --git a/example-code/tests/compile_fail/cargo_cgp/check_check.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs similarity index 85% rename from example-code/tests/compile_fail/cargo_cgp/check_check.rs rename to example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs index 861ab2b1..b93c0e11 100644 --- a/example-code/tests/compile_fail/cargo_cgp/check_check.rs +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs @@ -1,3 +1,5 @@ +// From docs/cargo-cgp/reading-output.md, A field with the wrong type. + use cgp::prelude::*; #[cgp_component(AreaCalculator)] @@ -12,10 +14,10 @@ impl AreaCalculator { } } -// The mistake: no `height` field, though the provider reads one. #[derive(HasField)] pub struct Rectangle { pub width: f64, + pub height: u32, } delegate_components! { diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.stderr new file mode 100644 index 00000000..c8c916f3 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.stderr @@ -0,0 +1,29 @@ +error[E0271]: type mismatch resolving `>>>>>>>>::Value == f64` + --> tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs:31:9 + | +31 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `>>>>>>>>::Value == f64` + | +note: expected this to be `f64` + --> tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs:20:17 + | +20 | pub height: u32, + | ^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs:10:1 + | +10 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: associated types for the current `impl` cannot be restricted in `where` clauses + = note: associated types for the current `impl` cannot be restricted in `where` clauses + = note: required for `Rectangle` to implement `CanUseComponent` +note: required by a bound in `__CheckRectangle` + --> tests/compile_fail/cargo_cgp/reading_output_a_field_with_the_wrong_type.rs:29:1 + | +29 | / check_components! { +30 | | Rectangle { +31 | | AreaCalculatorComponent, +32 | | } +33 | | } + | |_^ required by this bound in `__CheckRectangle` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.rs new file mode 100644 index 00000000..36a4a20a --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.rs @@ -0,0 +1,15 @@ +// From docs/cargo-cgp/reading-output.md, A fix in a help line. + +use cgp::prelude::*; + +#[cgp_fn] +fn person_name(&self, #[implicit] name: &str) -> String { + name.to_owned() +} + +#[cgp_fn] +fn greeting(&self) -> String { + format!("Hello, {}!", self.person_name()) +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr new file mode 100644 index 00000000..401e3a7a --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr @@ -0,0 +1,23 @@ +error[E0599]: the method `person_name` exists for reference `&__Context__`, but its trait bounds were not satisfied + --> tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.rs:12:32 + | +12 | format!("Hello, {}!", self.person_name()) + | ^^^^^^^^^^^ method cannot be called on `&__Context__` due to unsatisfied trait bounds + | +note: the following trait bounds were not satisfied: + `&__Context__: cgp::prelude::HasField>>>>>` + `<&__Context__ as cgp::prelude::HasField>>>>>>::Value = String` + `<__Context__ as cgp::prelude::HasField>>>>>>::Value = String` + `__Context__: cgp::prelude::HasField>>>>>` + --> tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.rs:5:1 + | + 5 | #[cgp_fn] + | ^^^^^^^^^ + 6 | fn person_name(&self, #[implicit] name: &str) -> String { + | ^^^^^^^^^^^ + = help: items from traits can only be used if the type parameter is bounded by the trait + = note: this error originates in the attribute macro `cgp_fn` (in Nightly builds, run with -Z macro-backtrace for more info) +help: the following trait defines an item `person_name`, perhaps you need to restrict type parameter `__Context__` with it: + | +10 | #[cgp_fn]: PersonName + | ++++++++++++ diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs new file mode 100644 index 00000000..c5732077 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs @@ -0,0 +1,34 @@ +// From docs/cargo-cgp/reading-output.md, Several causes in one error. + +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub length: f64, +} + +delegate_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +check_components! { + Rectangle { + AreaCalculatorComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.stderr new file mode 100644 index 00000000..839505e6 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `Rectangle: CanUseComponent` is not satisfied + --> tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs:30:9 + | +30 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>>` is implemented for it + --> tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs:19:9 + | +19 | pub length: f64, + | ^^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs:10:1 + | +10 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Rectangle` to implement `CanUseComponent` +note: required by a bound in `__CheckRectangle` + --> tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs:28:1 + | +28 | / check_components! { +29 | | Rectangle { +30 | | AreaCalculatorComponent, +31 | | } +32 | | } + | |_^ required by this bound in `__CheckRectangle` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.rs new file mode 100644 index 00000000..82e0d791 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.rs @@ -0,0 +1,33 @@ +// From docs/cargo-cgp/reading-output.md, Two entries that claim one key. + +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +#[cgp_impl(new GreetGoodbye)] +impl Greeter { + fn greet(&self) -> String { + "Goodbye!".to_owned() + } +} + +pub struct App; + +delegate_components! { + App { + GreeterComponent: GreetHello, + GreeterComponent: GreetGoodbye, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.stderr new file mode 100644 index 00000000..4c6bd3b5 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.stderr @@ -0,0 +1,15 @@ +error[E0119]: conflicting implementations of trait `IsProviderFor` for type `App` + --> tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.rs:29:9 + | +28 | GreeterComponent: GreetHello, + | ---------------- first implementation here +29 | GreeterComponent: GreetGoodbye, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `App` + +error[E0119]: conflicting implementations of trait `DelegateComponent` for type `App` + --> tests/compile_fail/cargo_cgp/reading_output_two_entries_that_claim_one_key.rs:29:9 + | +28 | GreeterComponent: GreetHello, + | ---------------- first implementation here +29 | GreeterComponent: GreetGoodbye, + | ^^^^^^^^^^^^^^^^ conflicting implementation for `App` From 215692d261adfcc0d57db74ae8ae7fec26176f53 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 5 Oct 2026 16:24:43 +0000 Subject: [PATCH 158/516] Use the version-free cargo-cgp caveat across the site Every page that concedes the tool's limits now carries the canonical sentence without a version number, and the four Concepts paraphrases that named the alpha release are replaced by it. Co-Authored-By: Claude Opus 5.5 --- docs/comparisons/algebraic-effects.md | 2 +- docs/comparisons/capabilities.md | 4 ++-- docs/comparisons/dependency-injection.md | 2 +- docs/comparisons/dynamic-dispatch.md | 2 +- docs/comparisons/implicit-parameters.md | 2 +- docs/comparisons/reflection.md | 2 +- docs/comparisons/row-polymorphism.md | 2 +- docs/comparisons/rust-language-proposals.md | 4 ++-- docs/comparisons/type-classes.md | 2 +- docs/concepts/check-traits.md | 5 +++-- docs/concepts/coherence.md | 4 ++-- docs/concepts/consumer-and-provider-traits.md | 4 ++-- docs/concepts/impl-side-dependencies.md | 5 ++--- docs/concepts/modularity-hierarchy.md | 2 +- .../cgp-examples/expression/examples/add-mult-code.md | 3 +-- .../cgp-examples/expression/examples/add-mult-neg.md | 2 +- docs/projects/cgp-examples/expression/examples/add-mult.md | 4 ++-- .../projects/cgp-examples/web-app/examples/coarse-grained.md | 3 +-- docs/projects/cgp-examples/web-app/examples/default-impls.md | 2 +- docs/projects/cgp-examples/web-app/examples/fine-grained.md | 4 ++-- docs/projects/cgp-examples/web-app/examples/namespaces.md | 2 +- docs/projects/cgp-serde/examples/messages.md | 3 +-- docs/projects/cgp-serde/guides/debugging-wiring.md | 2 +- docs/projects/cgp-serde/index.md | 2 +- docs/projects/cgp-serde/limitations.md | 4 ++-- docs/projects/hypershell/examples/bluesky-websocket.md | 4 ++-- docs/projects/hypershell/examples/hello-name.md | 4 ++-- docs/projects/hypershell/examples/http-checksum-native.md | 2 +- docs/projects/hypershell/guides/writing-a-program.md | 2 +- docs/projects/hypershell/index.md | 4 ++-- docs/projects/hypershell/limitations.md | 4 ++-- docs/reference/macros/check_components.md | 4 ++-- docs/reference/macros/delegate_components.md | 3 +-- docs/reference/macros/symbol.md | 2 +- docs/reference/types/chars.md | 3 +-- docs/resources.md | 2 +- docs/tutorials/area-calculation/checking.md | 2 +- 37 files changed, 52 insertions(+), 57 deletions(-) diff --git a/docs/comparisons/algebraic-effects.md b/docs/comparisons/algebraic-effects.md index 2fe21ce8..dcd19482 100644 --- a/docs/comparisons/algebraic-effects.md +++ b/docs/comparisons/algebraic-effects.md @@ -330,7 +330,7 @@ that handling check into the type system. CGP requires component declarations, wiring, and compile-time trait resolution. It also requires readers to learn the consumer/provider split. Its raw diagnostics expose generated types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. CGP does not provide +and the tool does not yet reshape every class. CGP does not provide continuation handling, effect typing, or checked algebraic laws for its operations. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) weighs its machinery against simpler Rust abstractions. diff --git a/docs/comparisons/capabilities.md b/docs/comparisons/capabilities.md index 726ec690..88cc7cd2 100644 --- a/docs/comparisons/capabilities.md +++ b/docs/comparisons/capabilities.md @@ -309,8 +309,8 @@ respective designs. CGP adds declarations, wiring, and compile-time work without supplying confinement or capture checking. Programs that need those properties must obtain them elsewhere. Its generated trait machinery also affects diagnostics: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root -cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every -class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) compares this machinery +cause for the classes it recognizes, and the tool does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) compares this machinery with simpler Rust abstractions. ## Where a capability system is the better choice diff --git a/docs/comparisons/dependency-injection.md b/docs/comparisons/dependency-injection.md index 56c26cb0..4248cf57 100644 --- a/docs/comparisons/dependency-injection.md +++ b/docs/comparisons/dependency-injection.md @@ -229,7 +229,7 @@ management to the application. CGP's raw errors can be difficult to read because they include generated traits and types. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The +and the tool does not yet reshape every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) weighs the additional machinery against plain traits, generics, and other alternatives. diff --git a/docs/comparisons/dynamic-dispatch.md b/docs/comparisons/dynamic-dispatch.md index 8995a819..569d284e 100644 --- a/docs/comparisons/dynamic-dispatch.md +++ b/docs/comparisons/dynamic-dispatch.md @@ -258,7 +258,7 @@ runtime mechanisms, which CGP code can use alongside its wiring. CGP's raw diagnostics expose generated traits and types. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The +and the tool does not yet reshape every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) compares these costs with ordinary traits, generics, and trait objects. diff --git a/docs/comparisons/implicit-parameters.md b/docs/comparisons/implicit-parameters.md index 5e9abcf9..8633be3f 100644 --- a/docs/comparisons/implicit-parameters.md +++ b/docs/comparisons/implicit-parameters.md @@ -263,7 +263,7 @@ CGP requires component declarations and provider selection through wiring or dec This adds code to maintain and trait-resolution work during compilation. Tracing a selection can also require following delegation through several tables. Raw diagnostics expose generated traits and types: [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it -recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The +recognizes, and the tool does not yet reshape every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) weighs these costs against simpler forms. ## Where implicit resolution is the better choice diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index cb3fee9c..3957b678 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -293,7 +293,7 @@ raises this concern. CGP requires exposed field shapes, explicit wiring, and specialized code for each field list. Learning the type-level representation and tracing recursive trait errors are additional costs. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The +and the tool does not yet reshape every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) compares these costs with simpler approaches. diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index 33f6e986..eb7e3837 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -272,7 +272,7 @@ CGP requires derives and type-level tags, plus wiring for operations supplied by dependencies can produce long trait errors. [`check_components!`](/docs/reference/macros/check_components) checks the listed components beside the wiring. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it -recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. A direct `match` +recognizes, and the tool does not yet reshape every class. A direct `match` can still be easier to understand and debug. CGP separates a provider's field requirements from the context's choice to use it. Matching fields diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md index 476761f2..6eddbd5d 100644 --- a/docs/comparisons/rust-language-proposals.md +++ b/docs/comparisons/rust-language-proposals.md @@ -332,8 +332,8 @@ CGP requires a component definition and explicit wiring. A provider trait create [`#[cgp_component]`](/docs/reference/macros/cgp_component) cannot retrofit a foreign trait such as `serde::Serialize` without a parallel component. Wiring adds compile-time work and can produce long trait errors over generated types. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root -cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every -class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs +cause for the classes it recognizes, and the tool does not yet reshape every class. The +[Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page weighs these costs against simpler approaches. ## Where a proposal, or a smaller tool, is the better choice diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md index aeb9edf2..85bea89d 100644 --- a/docs/comparisons/type-classes.md +++ b/docs/comparisons/type-classes.md @@ -307,7 +307,7 @@ CGP requires explicit wiring to choose providers. Providers also need a componen [`#[cgp_component]`](/docs/reference/macros/cgp_component), adding code beyond a plain trait. Trait resolution adds compile-time work and can produce long errors over generated types. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The +and the tool does not yet reshape every class. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page compares these costs with simpler approaches. diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index d519616d..fcef33bd 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -139,8 +139,9 @@ The dependency chain connects that missing field to the `CanSendEmail` trait the The tool can also recover causes that ordinary compiler output omits. It uses the compiler's next-generation trait solver for diagnostic recovery, then translates the recognized CGP structures. -Its `v0.1.0-alpha` release covers core wiring errors, but some classes, including orphan-rule -failures, still pass through unchanged. Output details depend on the compiler and tool version. +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet +reshape every class; [Reading the output](/docs/cargo-cgp/reading-output#errors-that-pass-through-unchanged) +lists the ones that pass through unchanged. Output details depend on the compiler and tool version. ## Checking a stack one layer at a time diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 9cc35b95..02fc9e9a 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -192,8 +192,8 @@ further places to inspect when tracing a choice. Wiring checks are deferred until the trait is checked or used. A table can name a provider whose requirements the context does not satisfy, and a later call can produce a verbose error. [`check_components!`](/docs/reference/macros/check_components) verifies requirements beside the -wiring. [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) makes recognized causes -easier to read; its `v0.1.0-alpha` release covers core wiring errors rather than every class. +wiring. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it +recognizes, and the tool does not yet reshape every class. [Checking your wiring](./check-traits.md) shows the diagnostics and their limits. ## Where to go next diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index 53cd2e70..f1c136d3 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -247,8 +247,8 @@ Wiring does not immediately verify the selected provider's requirements. A missi unsatisfied dependency can remain undetected until a caller needs the trait. [`check_components!`](/docs/reference/macros/check_components) verifies the requirements where you place the check, usually beside the table. -[`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reports recognized failures with -readable causes; its `v0.1.0-alpha` release covers core wiring errors rather than every class. +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +and the tool does not yet reshape every class. [Checking your wiring](./check-traits.md) shows what to expect with and without those tools. Tracing a method call requires following the wiring to its provider. Static dispatch avoids runtime diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index cb68d520..6fa9b44c 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -243,9 +243,8 @@ Errors may refer to generated bounds rather than the requirement as written in t A missing implicit field, for example, can appear as an unsatisfied `HasField` bound with a nested type-level field name. [`check_components!`](/docs/reference/macros/check_components) checks selected components where you place it, usually beside the wiring, and helps expose the -missing dependency. [`cargo cgp check`](https://github.com/contextgeneric/cargo-cgp) reports readable -causes for recognized cases; its `v0.1.0-alpha` release covers core wiring errors rather than every -class. [Checking your wiring](./check-traits.md) shows the diagnostics and their limits. +missing dependency. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the +classes it recognizes, and the tool does not yet reshape every class. [Checking your wiring](./check-traits.md) shows the diagnostics and their limits. A component and wiring are unnecessary when one blanket implementation provides all the reuse you need. Write that implementation in ordinary Rust, or use diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index efdf16fc..c15ae458 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -345,7 +345,7 @@ runs. Wrappers and namespaces can add further steps to that trace even though se Wiring failures can produce verbose diagnostics involving generated types and transitive bounds. [`check_components!`](/docs/reference/macros/check_components) forces selected requirements to be checked near the wiring. `cargo cgp check` leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. The +and the tool does not yet reshape every class. The [cargo-cgp documentation](/docs/cargo-cgp/) explains the checking workflow. Macros, trait resolution, and [monomorphization](/docs/reference/glossary#monomorphization) add compile-time work. The effect depends on the diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-code.md b/docs/projects/cgp-examples/expression/examples/add-mult-code.md index 8f713f8e..2de5377d 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-code.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-code.md @@ -163,8 +163,7 @@ error[E0277]: [CGP-E001] the consumer trait `CanComputeRef Supporting it would be a second group of `ToLisp` entries beside the `Eval` ones, with a provider for each new operator, an entry binding the context's Lisp type, and a `DispatchToLisp` wrapper, as [`add_mult`](./add-mult.md) has. `cargo cgp check` leads with the root cause -for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. +for the classes it recognizes, and the tool does not yet reshape every class. ## The pattern diff --git a/docs/projects/cgp-examples/expression/examples/add-mult.md b/docs/projects/cgp-examples/expression/examples/add-mult.md index c386a4a3..7ec86354 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult.md @@ -297,8 +297,8 @@ error[E0277]: [CGP-E001] the consumer trait `CanCompute>` A second, longer error points at the wrapper's call to `MatchWithValueHandlers`, because the dispatcher cannot find a provider for the `Times` variant either. The first error is the one to -read. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a -v0.1.0-alpha that does not yet reshape every class. Put the line back, and the check passes. +read. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does +not yet reshape every class. Put the line back, and the check passes. ## The pattern diff --git a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md index 005c46de..703dec7c 100644 --- a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md +++ b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md @@ -160,8 +160,7 @@ error[E0277]: [CGP-E001] the consumer trait `CanManageUser` is not implemented f The context has lost `get_user` and `update_user_data` as well as `create_user`, though neither calls the censor, because the three methods share one provider and one set of requirements. Compare the same change in the [next stage](./fine-grained.md#try-a-change). `cargo cgp check` leads with -the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet -reshape every class. +the root cause for the classes it recognizes, and the tool does not yet reshape every class. ## The pattern diff --git a/docs/projects/cgp-examples/web-app/examples/default-impls.md b/docs/projects/cgp-examples/web-app/examples/default-impls.md index 0d7c8803..8b3638b0 100644 --- a/docs/projects/cgp-examples/web-app/examples/default-impls.md +++ b/docs/projects/cgp-examples/web-app/examples/default-impls.md @@ -164,7 +164,7 @@ A default a namespace binds is final. The context's entry would be a second answ lookup, and Rust rejects the two as conflicting implementations, which is `E0119` underneath the tool's message. A context that needs a different getter joins a different namespace, one that does not bind the getter. `cargo cgp check` leads with the root cause for the classes it recognizes, and -the tool is a v0.1.0-alpha that does not yet reshape every class. +the tool does not yet reshape every class. ## The pattern diff --git a/docs/projects/cgp-examples/web-app/examples/fine-grained.md b/docs/projects/cgp-examples/web-app/examples/fine-grained.md index bf2ed699..06c0df25 100644 --- a/docs/projects/cgp-examples/web-app/examples/fine-grained.md +++ b/docs/projects/cgp-examples/web-app/examples/fine-grained.md @@ -171,8 +171,8 @@ error[E0277]: [CGP-E001] the consumer traits `CanCreateUser` and `CanCensorUsern Getting and updating users still check, because their providers need only the database. In the [coarse stage](./coarse-grained.md#try-a-change) the same change took the whole user manager with -it. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a -v0.1.0-alpha that does not yet reshape every class. +it. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not +yet reshape every class. ## The pattern diff --git a/docs/projects/cgp-examples/web-app/examples/namespaces.md b/docs/projects/cgp-examples/web-app/examples/namespaces.md index ec3be15d..4a58f61b 100644 --- a/docs/projects/cgp-examples/web-app/examples/namespaces.md +++ b/docs/projects/cgp-examples/web-app/examples/namespaces.md @@ -154,7 +154,7 @@ error[E0277]: [CGP-E001] the consumer traits `CanCreatePost` and `CanDetectSpamM Each root cause names the full path the namespace routed the lookup to, which says where the entry belongs. The other five components still check, since the getters, updaters, and deleter need nothing from the extras. `cargo cgp check` leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. +and the tool does not yet reshape every class. ## The pattern diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md index 65f1e3a3..0b58ca4f 100644 --- a/docs/projects/cgp-serde/examples/messages.md +++ b/docs/projects/cgp-serde/examples/messages.md @@ -270,8 +270,7 @@ Every checked type that contains a date fails, and all for one reason. Below the tool prints the chain that leads to it: from `MessagesArchive` through `SerializeFields`, the vectors, the references, and `EncryptedMessage`, down to `SerializeTimestamp`, which asks `AppB` for an `i64` it has no entry for. The fix is to put `i64` back. `cargo cgp check` leads with the root -cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every -class. +cause for the classes it recognizes, and the tool does not yet reshape every class. ## The pattern diff --git a/docs/projects/cgp-serde/guides/debugging-wiring.md b/docs/projects/cgp-serde/guides/debugging-wiring.md index be5604dd..92159e39 100644 --- a/docs/projects/cgp-serde/guides/debugging-wiring.md +++ b/docs/projects/cgp-serde/guides/debugging-wiring.md @@ -13,7 +13,7 @@ recognize once seen. cgp-serde rebuilds Serde's `Serialize` and `Deserialize` as The errors below come from [`cargo cgp check`](/docs/cargo-cgp/check), CGP's error tool, run in place of `cargo check`. `cargo cgp check` leads with the root cause for the classes it recognizes, -and the tool is a v0.1.0-alpha that does not yet reshape every class. Each mistake is caught by a +and the tool does not yet reshape every class. Each mistake is caught by a [`check_components!`](/docs/reference/macros/check_components) table listing the context's types, as [wiring a context](./wiring-a-context.md#5-check-every-value-type) recommends, and the errors are shorter and clearer there than at the first call. diff --git a/docs/projects/cgp-serde/index.md b/docs/projects/cgp-serde/index.md index 8483cb59..63f79f84 100644 --- a/docs/projects/cgp-serde/index.md +++ b/docs/projects/cgp-serde/index.md @@ -107,7 +107,7 @@ know first: compile, and the compiler's raw message lists every step it took to find it. Checking the context with `check_components!` and reading the error with [`cargo cgp check`](/docs/cargo-cgp/check) names the missing entry: `cargo cgp check` leads with the root cause for the classes it - recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. The [debugging + recognizes, and the tool does not yet reshape every class. The [debugging guide](./guides/debugging-wiring.md) shows the common mistakes. - **Its output suits self-describing formats.** JSON and RON work with it as they are. Length-prefixed binary formats, such as postcard, do not accept the maps and sequences its generic diff --git a/docs/projects/cgp-serde/limitations.md b/docs/projects/cgp-serde/limitations.md index 80cd5093..ff568270 100644 --- a/docs/projects/cgp-serde/limitations.md +++ b/docs/projects/cgp-serde/limitations.md @@ -64,8 +64,8 @@ reaches. See [wiring a context](./guides/wiring-a-context.md). A missing entry is a compile error, and the compiler's raw message lists every step from the top-level type down to the entry it could not find. Checking the context with `check_components!` and reading the error with [`cargo cgp check`](/docs/cargo-cgp/check) gets to the cause faster: -`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a -v0.1.0-alpha that does not yet reshape every class. The [debugging +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet +reshape every class. The [debugging guide](./guides/debugging-wiring.md) shows the common mistakes. ## When plain Serde is the better choice diff --git a/docs/projects/hypershell/examples/bluesky-websocket.md b/docs/projects/hypershell/examples/bluesky-websocket.md index 5805a2d3..e433d444 100644 --- a/docs/projects/hypershell/examples/bluesky-websocket.md +++ b/docs/projects/hypershell/examples/bluesky-websocket.md @@ -154,8 +154,8 @@ error[E0277]: [CGP-E002] the provider trait `Handler, TokioAsyncReadSt The path's last segment is the error type the provider raises, written by its own name. That type is `tungstenite::Error`, which the program imports as `TungsteniteError`, so the `Error` in the message is `tungstenite`'s error rather than the context's own. Adding the route back fixes it. -`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a -v0.1.0-alpha that does not yet reshape every class. +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet +reshape every class. ## The pattern diff --git a/docs/projects/hypershell/examples/hello-name.md b/docs/projects/hypershell/examples/hello-name.md index 886a5d0b..a2b16a1b 100644 --- a/docs/projects/hypershell/examples/hello-name.md +++ b/docs/projects/hypershell/examples/hello-name.md @@ -150,8 +150,8 @@ error[E0277]: [CGP-E002] the provider trait `Handler, Vec>` with c The full output continues with the dependency chain that leads there, from the pipeline through `SimpleExec`, the command's argument list, and the `FieldArg` that asked for the field. The fix is the one `MyApp` already applies: run the program on a context that derives `HasField` and has the -field. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a -v0.1.0-alpha that does not yet reshape every class. +field. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does +not yet reshape every class. ## The pattern diff --git a/docs/projects/hypershell/examples/http-checksum-native.md b/docs/projects/hypershell/examples/http-checksum-native.md index 254716ef..67e14365 100644 --- a/docs/projects/hypershell/examples/http-checksum-native.md +++ b/docs/projects/hypershell/examples/http-checksum-native.md @@ -169,7 +169,7 @@ The digest is a `GenericArray`, and `StreamToStdout`'s input dispatcher type. The path in the message is the syntax followed by the input type, which is exactly the key the dispatcher failed to match. The fix is to convert the value into a type the dispatcher lists, which is what `BytesToHex` does. `cargo cgp check` leads with the root cause for the classes it -recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. +recognizes, and the tool does not yet reshape every class. ## The pattern diff --git a/docs/projects/hypershell/guides/writing-a-program.md b/docs/projects/hypershell/guides/writing-a-program.md index d2fceab9..d8c806c3 100644 --- a/docs/projects/hypershell/guides/writing-a-program.md +++ b/docs/projects/hypershell/guides/writing-a-program.md @@ -140,7 +140,7 @@ One check can list several programs, or several inputs, as an array: [`cargo cgp check`](/docs/cargo-cgp/check); the [debugging guide](./debugging.md) shows the common ones. A failure reported at the `handle` call itself often carries no root cause, which is the practical reason to check. `cargo cgp check` leads with the root cause for the classes it -recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. +recognizes, and the tool does not yet reshape every class. ## Build with nightly and the new trait solver diff --git a/docs/projects/hypershell/index.md b/docs/projects/hypershell/index.md index fdb08b30..4773e18d 100644 --- a/docs/projects/hypershell/index.md +++ b/docs/projects/hypershell/index.md @@ -107,8 +107,8 @@ Hypershell is a demonstration, and these are the costs a reader evaluating it sh - **Error messages are long.** A mistake in a program is a compile error, and the compiler's raw message lists every step it took before it failed. Checking the program with `check_components!` and reading the error with [`cargo cgp check`](/docs/cargo-cgp/check) helps: `cargo cgp check` - leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does - not yet reshape every class. The [debugging guide](./guides/debugging.md) shows the common + leads with the root cause for the classes it recognizes, and the tool does not yet reshape every + class. The [debugging guide](./guides/debugging.md) shows the common failures. - **It is a demonstration.** Hypershell is lightly tested and not meant for production use; its value is as a worked example. The [limitations page](./limitations.md) describes the limits of its diff --git a/docs/projects/hypershell/limitations.md b/docs/projects/hypershell/limitations.md index 928890f7..627c98b9 100644 --- a/docs/projects/hypershell/limitations.md +++ b/docs/projects/hypershell/limitations.md @@ -57,8 +57,8 @@ program. A mistake in a program or its wiring is a compile error, and the compiler's raw message lists every step it took through the wiring before it failed. Checking a program with `check_components!` and reading the error with [`cargo cgp check`](/docs/cargo-cgp/check) gets to the cause faster: -`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool is a -v0.1.0-alpha that does not yet reshape every class. The [debugging guide](./guides/debugging.md) +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet +reshape every class. The [debugging guide](./guides/debugging.md) shows the common mistakes. ## When another tool is the better choice diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 4eb18cbd..95ddb6bc 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -187,8 +187,8 @@ the cause: `Person` does not implement `HasField` for the `name` tag, which rust `Symbol<4, Chars<'n', …>>` type. The mismatch is reported at the wiring rather than at some later `person.greet()` in another file. [`cargo cgp check`](/docs/cargo-cgp/check) reports the same failure with the root cause first, as ``[CGP-E106] missing field `name` on `Person` ``. `cargo cgp check` -leads with the root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not -yet reshape every class. +leads with the root cause for the classes it recognizes, and the tool does not yet reshape every +class. A generic component supplies its parameters, and the bracketed form checks several at once: diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 47a04353..27c22e30 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -745,8 +745,7 @@ unmet, still compiles. The failure appears later, at the place where code uses t long error naming types you did not write. The answer is to check the table (see [`check_components!`](./check_components.md)) and to read failures through [`cargo cgp check`](/docs/cargo-cgp/check) in place of `cargo check`. `cargo cgp check` leads with the -root cause for the classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape -every class. +root cause for the classes it recognizes, and the tool does not yet reshape every class. **Statements must lead the block**, and getting it wrong produces a misleading message. Once the parser has consumed the statements it expects only mappings, so it reads the `open` keyword as a *key* and diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index bbc5f1fd..99f2b472 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -194,7 +194,7 @@ against the expanded tag, so an error mentioning `HasField>>>` is telling you the field `width` is missing. Reading the characters in order is enough to decode it, and [`cargo cgp check`](/docs/cargo-cgp/check) names the field directly, as ``missing field `width` ``. `cargo cgp check` leads with the root cause for the -classes it recognizes, and the tool is a v0.1.0-alpha that does not yet reshape every class. +classes it recognizes, and the tool does not yet reshape every class. ## Formal grammar diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index aceffb90..2c804e80 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -163,8 +163,7 @@ help: the trait `HasField Date: Mon, 5 Oct 2026 16:30:36 +0000 Subject: [PATCH 159/516] Correct and extend the cargo-cgp pages after review Reading the output gains the missing-wiring and ordinary-trait-bound shapes, marks the switch from Rectangle to App, and no longer claims that an error without a code in its headline passed through: an ordinary-bound failure at a check keeps the compiler's headline. Error codes says when CGP-E201 appears and notes the #[cgp_impl] gap under CGP-E012. The command reference, troubleshooting, and check pages get smaller corrections. The new examples are example-code fixtures. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/check.md | 8 +- docs/cargo-cgp/command-reference.md | 6 +- docs/cargo-cgp/error-codes.md | 9 +- docs/cargo-cgp/reading-output.md | 105 +++++++++++++++++- docs/cargo-cgp/troubleshooting.md | 6 +- ...output_a_component_nothing_is_wired_for.rs | 37 ++++++ ...ut_a_component_nothing_is_wired_for.stderr | 25 +++++ ...rdinary_rust_trait_that_does_not_hold_1.rs | 42 +++++++ ...ary_rust_trait_that_does_not_hold_1.stderr | 35 ++++++ ...rdinary_rust_trait_that_does_not_hold_2.rs | 40 +++++++ ...ary_rust_trait_that_does_not_hold_2.stderr | 44 ++++++++ 11 files changed, 343 insertions(+), 14 deletions(-) create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.stderr create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.stderr create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs create mode 100644 example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.stderr diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index e2c26dac..564e30cb 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -75,7 +75,7 @@ pub fn print_area(rectangle: &Rectangle) { } ``` -Running the check prints this, followed by cargo's own one-line summary: +After cargo's progress lines, the check prints this, followed by cargo's one-line summary: ```text $ cargo cgp check @@ -135,8 +135,10 @@ error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemente For more information about this error, try `rustc --explain E0277`. ``` -A check also changes what plain `cargo check` can tell you. On this version the compiler names the -missing requirement, but spells the field name one character at a time, as a type-level string: +A check also changes what plain `cargo check` can tell you. With the check in place, stable Rust names +the missing requirement, but spells the field name one character at a time, as a type-level string. +Because it compares that name with the `width` field the struct does have, it also prints the letter +the two share in that position as `_`: ```text help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` diff --git a/docs/cargo-cgp/command-reference.md b/docs/cargo-cgp/command-reference.md index 6df6753d..092c0f38 100644 --- a/docs/cargo-cgp/command-reference.md +++ b/docs/cargo-cgp/command-reference.md @@ -101,7 +101,7 @@ install, such as one from a source checkout: |---|---| | `CARGO_CGP_NO_MANAGE` | When set, skips the preflight test of the toolchain and driver, and does not switch to the pinned nightly. The check then runs under whatever toolchain is active, which must be the driver's nightly. | | `CARGO_CGP_DRIVER` | The path of the driver to run, instead of looking beside the front end. | -| `CARGO_CGP_TOOLCHAIN` | A nightly to use in place of the pinned one, for `setup` and for the checks. The driver must be built against it. | +| `CARGO_CGP_TOOLCHAIN` | A nightly to use in place of the pinned one, for `setup`, `check`, and `expand`. The driver must be built against it. | | `CARGO_TARGET_DIR` | cargo's own variable. When set, the tool does not add `--target-dir target/cgp`. | For the length of a `check` or `expand`, the tool also sets variables for cargo: @@ -114,8 +114,8 @@ For the length of a `check` or `expand`, the tool also sets variables for cargo: ## Files and directories -The tool creates these, and removing it does not remove them; see -[Uninstalling](./installation.md#uninstalling): +The tool puts its files in these places. Uninstalling with cargo removes the two binaries but leaves +the toolchain and the build directories; see [Uninstalling](./installation.md#uninstalling): | Path | What it holds | |---|---| diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index 4a9e3062..90a2bb19 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -199,7 +199,10 @@ a trait the body uses has to be declared for that type to have it. ``` The compiler's code is `E0599`. **Fix:** add the trait to `#[uses(...)]`, as the `help` line says. -Explained in [Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare). +The same mistake inside a [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider body is not +recognized yet and arrives as the compiler wrote it, as +[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) describes. Explained in +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare). ### CGP-E013 @@ -390,7 +393,9 @@ the case where that last line has no code. **The chain ends at an ordinary Rust trait bound that does not hold**, such as `f64: Eq`. The last line of the tree repeats the compiler's own wording without a code, and the `root cause:` line carries this -one. +one. The line appears when the error has a CGP headline, as at a method call; at a +`check_components!` entry the tool keeps the compiler's own headline, which already names the bound, +and adds the chain without a `root cause:` line. ```text root cause: [CGP-E201] the trait bound `` is not satisfied diff --git a/docs/cargo-cgp/reading-output.md b/docs/cargo-cgp/reading-output.md index 6c8f593b..a63a2018 100644 --- a/docs/cargo-cgp/reading-output.md +++ b/docs/cargo-cgp/reading-output.md @@ -10,7 +10,8 @@ description: 'How to read the errors cargo cgp check prints: the headline and it `cargo cgp check`, part of the [`cargo-cgp`](./index.md) toolchain for [Context-Generic Programming (CGP)](/docs/), prints ordinary compiler diagnostics, with the CGP errors it recognizes rewritten into a few fixed shapes. This page takes each shape apart. Every example comes -from running the tool on the program shown beside it, and every `[CGP-Exxx]` code is listed on +from running the tool on a complete program; the snippets show the part of it that matters, and the +line numbers in the output refer to the whole file. Every `[CGP-Exxx]` code is listed on [Error codes](./error-codes.md). ## The parts of a rewritten error @@ -95,6 +96,49 @@ The same merging works in the other direction. When several components fail beca mistake, such as a single missing field that three providers read, the tool reports one error whose headline names all three consumer traits, rather than three errors with the same cause. +## A component nothing is wired for + +When the context has no wiring entry for a component at all, the chain is short, and its last line +names the entry that is missing. The examples from here on use `App`, a type that stands for an +application and carries its wiring, where the examples above used `Rectangle`, the shape being +measured. The error shapes are the same for both. Here `App` is checked for `FarewellComponent` but +wires only the greeter: + +```rust +delegate_components! { + App { + GreeterComponent: GreetHello, + } +} + +check_components! { + App { + GreeterComponent, + FarewellComponent, + } +} +``` + +```text +error[E0277]: [CGP-E001] the consumer trait `CanSayGoodbye` is not implemented for context `App` + --> src/lib.rs:31:9 + | +31 | FarewellComponent, + | ^^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `FarewellComponent` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanSayGoodbye` for context `App` + └─ [CGP-E107] context `App` does not contain any delegate entry for `FarewellComponent` + +For more information about this error, try `rustc --explain E0277`. +``` + +There is no `[CGP-E102]` line, because no provider was selected for the chain to pass through. Add the +entry, or remove the component from the check if the context is not meant to have it. When the +component is routed through a namespace or an `open` statement, the chain gains a `[CGP-E104]` line +naming the path the lookup followed, and the last line names that path rather than the component. + ## A field with the wrong type When the field exists but has the wrong type, the headline states the whole cause, so the error has @@ -127,6 +171,60 @@ The chain still shows which provider needs the type, which tells you whether to the provider. An [abstract type](/docs/concepts/abstract-types) wired one way and required another produces the same shape with `[CGP-E017]`. +## An ordinary Rust trait that does not hold + +Not every requirement is a CGP one. When a provider needs an ordinary trait that the wired type does +not implement, the compiler's own headline already states the cause, so the tool keeps it and adds +only the chain. Here `CompareScalars` requires `Scalar: Eq`, and `App` wires the scalar type to +`f64`, which is not `Eq`: + +```rust +#[cgp_impl(new CompareScalars)] +#[use_type(HasScalarType.Scalar)] +impl ScalarEquality +where + Scalar: Eq, +{ + fn same(&self, a: &Scalar, b: &Scalar) -> bool { + a == b + } +} + +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + ScalarEqualityComponent: CompareScalars, + } +} +``` + +```text +error[E0277]: the trait bound `f64: Eq` is not satisfied + --> src/lib.rs:36:9 + | +36 | ScalarEqualityComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Eq` is not implemented for `f64` + | + = note: this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCompareScalars` for context `App` + └─ [CGP-E102] provider trait impl `ScalarEquality` with context `App` for provider `CompareScalars` + └─ the trait bound `f64: Eq` is not satisfied + +For more information about this error, try `rustc --explain E0277`. +``` + +The last line of the chain repeats the compiler's words without a code, since it is not a CGP +requirement. Reached through a method call rather than a check, the same mistake gets a CGP headline +instead, and then the cause line carries `[CGP-E201]`, the code for an ordinary bound: + +```text + = note: root cause: [CGP-E201] the trait bound `f64: Eq` is not satisfied +``` + +The fix is in the types rather than the wiring: wire the scalar type to one that implements the trait, +or relax the provider's bound if it asks for more than it needs. The message names `f64` but not the +`UseType` entry that chose it, so that last step is yours. + ## Two entries that claim one key A wiring conflict is reported where it happens, with two carets and no chain. Here one context wires @@ -195,8 +293,9 @@ this way, each for a different attribute or trait mistake. ## Errors that pass through unchanged `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet -reshape every class. An error with no `[CGP-Exxx]` code in its headline is one it passed through, so -read it as the compiler wrote it. These are the ones you are most likely to meet: +reshape every class. An error with no `[CGP-Exxx]` code anywhere in it, in the headline or in a +dependency chain beneath it, is one the tool passed through, so read it as the compiler wrote it. +These are the ones you are most likely to meet: - **A per-entry generic that never reaches the key**, which the compiler reports as `E0207` twice, with two suggested fixes of which only the second matches the mistake. See diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index 18d6f7e8..c5e4c52b 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -100,8 +100,8 @@ cargo-cgp: the installed cargo-cgp-driver is version 0.0.9, but this cargo-cgp i Run `cargo cgp setup`. ``` -**The driver was built by a different compiler than the pinned nightly now provides**, which happens -when that nightly has been reinstalled: +**The driver was built by a different compiler than the pinned nightly now provides.** The driver and +the toolchain the front end expects no longer belong together, even though their versions match: ```text cargo-cgp: the cargo-cgp-driver was built against `rustc 1.99.0-nightly (0123abcde 2026-08-01)`, but the pinned toolchain `nightly-2026-09-14` now provides `rustc 1.100.0-nightly (4b6d04e70 2026-09-13)` @@ -160,7 +160,7 @@ active toolchain, for example with `RUSTUP_TOOLCHAIN`. Running through the Nix f ## The driver cannot be found **The front end looks for the driver in its own directory**, unless `CARGO_CGP_DRIVER` names another -path, and only then on your `PATH`. When the driver is missing, the preflight reports it: +path, and looks on your `PATH` only when the driver is not there. When the driver is missing, the preflight reports it: ```text cargo-cgp: failed to run the cargo-cgp-driver at /path/to/cargo-cgp-driver: No such file or directory (os error 2) diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.rs new file mode 100644 index 00000000..f64e2ffe --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.rs @@ -0,0 +1,37 @@ +// From docs/cargo-cgp/reading-output.md, A component nothing is wired for. + +use cgp::prelude::*; + +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + +#[cgp_component(Farewell)] +pub trait CanSayGoodbye { + fn goodbye(&self) -> String; +} + +#[cgp_impl(new GreetHello)] +impl Greeter { + fn greet(&self) -> String { + "Hello!".to_owned() + } +} + +pub struct App; + +delegate_components! { + App { + GreeterComponent: GreetHello, + } +} + +check_components! { + App { + GreeterComponent, + FarewellComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.stderr new file mode 100644 index 00000000..090d8e5f --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.stderr @@ -0,0 +1,25 @@ +error[E0277]: the trait bound `App: CanUseComponent` is not satisfied + --> tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.rs:33:9 + | +33 | FarewellComponent, + | ^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `DelegateComponent` is not implemented for `App` + but trait `DelegateComponent` is implemented for it + --> tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.rs:26:9 + | +26 | GreeterComponent: GreetHello, + | ^^^^^^^^^^^^^^^^ + = help: for that trait implementation, expected `GreeterComponent`, found `FarewellComponent` + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/cargo_cgp/reading_output_a_component_nothing_is_wired_for.rs:30:1 + | +30 | / check_components! { +31 | | App { +32 | | GreeterComponent, +33 | | FarewellComponent, +34 | | } +35 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.rs new file mode 100644 index 00000000..1fe0b5d0 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.rs @@ -0,0 +1,42 @@ +// From docs/cargo-cgp/reading-output.md, An ordinary Rust trait that does not hold: at a check. + +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar; +} + +#[cgp_component(ScalarEquality)] +#[use_type(HasScalarType.Scalar)] +pub trait CanCompareScalars { + fn same(&self, a: &Scalar, b: &Scalar) -> bool; +} + +#[cgp_impl(new CompareScalars)] +#[use_type(HasScalarType.Scalar)] +impl ScalarEquality +where + Scalar: Eq, +{ + fn same(&self, a: &Scalar, b: &Scalar) -> bool { + a == b + } +} + +pub struct App; + +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + ScalarEqualityComponent: CompareScalars, + } +} + +check_components! { + App { + ScalarEqualityComponent, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.stderr new file mode 100644 index 00000000..f187e822 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.stderr @@ -0,0 +1,35 @@ +error[E0277]: the trait bound `f64: Eq` is not satisfied + --> tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.rs:38:9 + | +38 | ScalarEqualityComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Eq` is not implemented for `f64` + | + = help: the following other types implement trait `Eq`: + i128 + i16 + i32 + i64 + i8 + isize + u128 + u16 + and $N others +note: required for `CompareScalars` to implement `IsProviderFor` + --> tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.rs:16:1 + | +16 | #[cgp_impl(new CompareScalars)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +... +20 | Scalar: Eq, + | -- unsatisfied trait bound introduced here + = note: required for `App` to implement `CanUseComponent` +note: required by a bound in `__CheckApp` + --> tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_1.rs:36:1 + | +36 | / check_components! { +37 | | App { +38 | | ScalarEqualityComponent, +39 | | } +40 | | } + | |_^ required by this bound in `__CheckApp` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs b/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs new file mode 100644 index 00000000..fa829292 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs @@ -0,0 +1,40 @@ +// From docs/cargo-cgp/reading-output.md, An ordinary Rust trait that does not hold: at a method call. + +use cgp::prelude::*; + +#[cgp_type] +pub trait HasScalarType { + type Scalar; +} + +#[cgp_component(ScalarEquality)] +#[use_type(HasScalarType.Scalar)] +pub trait CanCompareScalars { + fn same(&self, a: &Scalar, b: &Scalar) -> bool; +} + +#[cgp_impl(new CompareScalars)] +#[use_type(HasScalarType.Scalar)] +impl ScalarEquality +where + Scalar: Eq, +{ + fn same(&self, a: &Scalar, b: &Scalar) -> bool { + a == b + } +} + +pub struct App; + +delegate_components! { + App { + ScalarTypeProviderComponent: UseType, + ScalarEqualityComponent: CompareScalars, + } +} + +pub fn compare() -> bool { + App.same(&1.0, &2.0) +} + +fn main() {} diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.stderr new file mode 100644 index 00000000..1fa96ad9 --- /dev/null +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.stderr @@ -0,0 +1,44 @@ +error[E0599]: the method `same` exists for struct `App`, but its trait bounds were not satisfied + --> tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs:37:9 + | +27 | pub struct App; + | -------------- method `same` not found for this struct because it doesn't satisfy `App: CanCompareScalars` or `App: ScalarEquality` +... +37 | App.same(&1.0, &2.0) + | ^^^^ this is an associated function, not a method + | + = note: found the following associated functions; to be used as methods, functions must have a `self` parameter +note: the candidate is defined in the trait `ScalarEquality` + --> tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs:13:5 + | +13 | fn same(&self, a: &Scalar, b: &Scalar) -> bool; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: trait bound `App: ScalarEquality` was not satisfied + --> tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs:10:1 + | +10 | #[cgp_component(ScalarEquality)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +11 | #[use_type(HasScalarType.Scalar)] +12 | pub trait CanCompareScalars { + | ^^^^^^^^^^^^^^^^^ +note: the trait `ScalarEquality` must be implemented + --> tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs:12:1 + | +12 | / pub trait CanCompareScalars { +13 | | fn same(&self, a: &Scalar, b: &Scalar) -> bool; +14 | | } + | |_^ + = help: items from traits can only be used if the trait is implemented and in scope +note: `CanCompareScalars` defines an item `same`, perhaps you need to implement it + --> tests/compile_fail/cargo_cgp/reading_output_an_ordinary_rust_trait_that_does_not_hold_2.rs:12:1 + | +12 | / pub trait CanCompareScalars { +13 | | fn same(&self, a: &Scalar, b: &Scalar) -> bool; +14 | | } + | |_^ + = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) +help: use associated function syntax instead + | +37 - App.same(&1.0, &2.0) +37 + App::same(&1.0, &2.0) + | From db1266d2c775dad2ae89275559c9717357ff864b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 5 Oct 2026 16:56:12 +0000 Subject: [PATCH 160/516] Update the cargo-cgp pages for the front-end fixes The pages quote `cargo cgp --version`, say `setup` and `update` answer `--help`, place `target/cgp` in the project's target directory wherever the check runs, and count a `#[cgp_impl]` body among those CGP-E012 covers. The reading page lists the call on a non-context parameter that passes through on purpose. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/check.md | 12 ++++++------ docs/cargo-cgp/command-reference.md | 13 +++++++------ docs/cargo-cgp/error-codes.md | 10 ++++------ docs/cargo-cgp/installation.md | 11 +++++++---- docs/cargo-cgp/reading-output.md | 13 +++++++------ docs/cargo-cgp/troubleshooting.md | 18 ++++++------------ 6 files changed, 37 insertions(+), 40 deletions(-) diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index 564e30cb..0e73eaff 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -15,7 +15,7 @@ each one leads with its root cause. It is part of [`cargo-cgp`](./index.md), the cargo cgp check ``` -**Run it from your package's or workspace's root directory.** Everything after `check` is passed to +Run it anywhere inside your package or workspace. Everything after `check` is passed to `cargo check`, so the flags you already use work unchanged: ```sh @@ -163,9 +163,9 @@ Because the tool picks these settings, a check is a diagnostic pass rather than own build, the way Clippy runs under settings of its own. Your toolchain's `cargo check` remains the authority on whether the code compiles. -**`target/cgp` is relative to the directory you run the command from.** Run from a subdirectory, the -check creates a new `target/cgp` inside that subdirectory and builds every dependency again there. Pass -`--target-dir`, or set `CARGO_TARGET_DIR`, to put the artifacts somewhere else. +**`target/cgp` sits inside your project's own target directory**, wherever in the project you run the +command, and follows a `build.target-dir` you have configured. Pass `--target-dir`, or set +`CARGO_TARGET_DIR`, to put the artifacts somewhere else. ## Flags are cargo's, not the tool's @@ -178,8 +178,8 @@ consequences: - **`cargo cgp check --help` prints cargo's help** for `cargo check` and exits without running a check. For the tool's own commands, run `cargo cgp --help`. -The one flag the tool reads itself is `--target-dir`, and only to decide whether to supply -`target/cgp`. +The tool reads two of the flags itself, `--target-dir` and `--manifest-path`, and only to decide where +`target/cgp` goes. ## In your editor diff --git a/docs/cargo-cgp/command-reference.md b/docs/cargo-cgp/command-reference.md index 092c0f38..11666f9a 100644 --- a/docs/cargo-cgp/command-reference.md +++ b/docs/cargo-cgp/command-reference.md @@ -25,7 +25,7 @@ Two options stand in for a command: | Option | Effect | |---|---| | `-h`, `--help` | Prints the version, the list of commands, and a line on each. Running `cargo cgp` with no command does the same. | -| `--version` | Prints the version of the tool. | +| `-V`, `--version` | Prints the version of the tool, as `cargo-cgp 0.1.0`. | ## Commands @@ -49,7 +49,8 @@ cargo cgp check [CARGO CHECK ARGS]... does not run a check. Two flags matter more than the rest: - **`--target-dir `** sets where the build goes. Without it, and without `CARGO_TARGET_DIR`, the - tool adds `--target-dir target/cgp`, relative to the directory you run it from. + tool builds into the `cgp` subdirectory of your project's own target directory, which it reads from + `cargo metadata`, so the location is the same wherever in the project you run it. - **`--message-format=json`** prints the errors as JSON, rewritten the same way as the text output. An editor needs this form; see [Check](./check.md#in-your-editor). @@ -89,8 +90,8 @@ cargo cgp update Looks up the published versions on crates.io and, if there is a newer one in your release channel, reinstalls the front end and runs the new version's `setup`. It needs a network connection. -**`setup` and `update` take no options, and they ignore any arguments.** `cargo cgp setup --help` -therefore runs setup; use `cargo cgp --help` for help. +**`setup` and `update` take no options.** Each answers `-h` or `--help` with a description of what it +does instead of running, and refuses any other argument with an error naming it. ## Environment variables @@ -102,7 +103,7 @@ install, such as one from a source checkout: | `CARGO_CGP_NO_MANAGE` | When set, skips the preflight test of the toolchain and driver, and does not switch to the pinned nightly. The check then runs under whatever toolchain is active, which must be the driver's nightly. | | `CARGO_CGP_DRIVER` | The path of the driver to run, instead of looking beside the front end. | | `CARGO_CGP_TOOLCHAIN` | A nightly to use in place of the pinned one, for `setup`, `check`, and `expand`. The driver must be built against it. | -| `CARGO_TARGET_DIR` | cargo's own variable. When set, the tool does not add `--target-dir target/cgp`. | +| `CARGO_TARGET_DIR` | cargo's own variable. When set, the tool does not add its `target/cgp` directory. | For the length of a `check` or `expand`, the tool also sets variables for cargo: @@ -122,7 +123,7 @@ the toolchain and the build directories; see [Uninstalling](./installation.md#un | `~/.cargo/bin/cargo-cgp` | The front end, on the cargo path. | | `~/.cargo/bin/cargo-cgp-driver` | The driver, which `setup` installs beside the front end. | | `~/.rustup/toolchains/nightly-…` | The pinned nightly, which `setup` installs through rustup. The driver's `--version` names it. | -| `target/cgp` | The check's build artifacts, relative to the directory the command ran in. | +| `target/cgp` | The check's build artifacts, inside the project's target directory. | ## Exit status diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index 90a2bb19..b2f3a12a 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -190,18 +190,16 @@ define a namespace of your own that inherits the foreign one. Explained in ### CGP-E012 -**A `#[cgp_fn]` body calls a CGP trait's method on `self` without declaring the trait as a -dependency.** The macro turns the body into a blanket implementation over a generated context type, so -a trait the body uses has to be declared for that type to have it. +**A `#[cgp_fn]` or `#[cgp_impl]` body calls a CGP trait's method on `self` without declaring the trait +as a dependency.** The macro turns the body into an implementation over a generated context type, so a +trait the body uses has to be declared for that type to have it. ```text [CGP-E012] the trait `` is used but not declared as a dependency ``` The compiler's code is `E0599`. **Fix:** add the trait to `#[uses(...)]`, as the `help` line says. -The same mistake inside a [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider body is not -recognized yet and arrives as the compiler wrote it, as -[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) describes. Explained in +Explained in [Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare). ### CGP-E013 diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index 171cb988..9ed55f07 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -49,8 +49,8 @@ do not match, it stops with a message naming `cargo cgp setup` as the fix, rathe anything on its own. [Troubleshooting](./troubleshooting.md#the-preflight-rejects-the-setup) lists those messages. -`setup` and `update` take no options, and they ignore anything you pass after them. In particular, -`cargo cgp setup --help` runs setup rather than printing help; run `cargo cgp --help` instead. +`setup` and `update` take no options. Each answers `--help` with what it does instead of running, and +refuses any other argument rather than starting an install you did not ask for. ## With Nix @@ -98,8 +98,11 @@ Ask the front end for its version: cargo cgp --version ``` -It prints the version of the tool you are running. `cargo cgp --help` prints the same version on its -first line, followed by the list of commands. +```text +cargo-cgp 0.1.0 +``` + +`cargo cgp --help` prints the same line first, followed by the list of commands. The driver has its own version query, and it doubles as a test that the driver can run at all, because the driver loads the compiler's libraries before printing anything: diff --git a/docs/cargo-cgp/reading-output.md b/docs/cargo-cgp/reading-output.md index a63a2018..b191ab43 100644 --- a/docs/cargo-cgp/reading-output.md +++ b/docs/cargo-cgp/reading-output.md @@ -285,8 +285,9 @@ error[E0599]: [CGP-E012] the trait `PersonName` is used but not declared as a de For more information about this error, try `rustc --explain E0599`. ``` -Adding `#[uses(PersonName)]` under `#[cgp_fn]` on `greeting` fixes it. The compiler's own message for -this mistake talks about a method that exists for `&__Context__`, a type parameter the macro +Adding `#[uses(PersonName)]` under `#[cgp_fn]` on `greeting` fixes it, and the same error and fix +apply to a [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider body. The compiler's own message +for this mistake talks about a method that exists for `&__Context__`, a type parameter the macro generated, and never names the missing attribute. The codes from `[CGP-E012]` to `[CGP-E016]` all work this way, each for a different attribute or trait mistake. @@ -307,10 +308,10 @@ These are the ones you are most likely to meet: dispatch over enum variants. Their errors name generated helper types rather than the variant or field at fault. [Extensible variants](/docs/concepts/extensible-variants) and [extensible records](/docs/concepts/extensible-records) explain what those operations require. -- **An undeclared trait called inside a [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider's - body.** The same mistake in a `#[cgp_fn]` body is reshaped, as shown above; inside a provider it - arrives as the compiler's `E0599` about `&__Context__`. The fix is the same `#[uses(...)]` - attribute. +- **An undeclared trait called on a generic parameter other than the context**, such as + `value.describe()` on a `value: &Value` argument. The fix is a bound on `Value` rather than an + `#[uses(...)]` attribute, which only bounds the context, so the tool leaves the compiler's message, + which names `Value`, as it is. Errors in crates outside your workspace also pass through, because the tool reshapes only your workspace's own crates. For any error that arrives raw, the diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index c5e4c52b..7a93b421 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -37,9 +37,8 @@ Find the distinctive part of your error in the left column, then read the sectio | `rustup was not found on PATH` | `setup` needs rustup | [Setup fails](#setup-fails) | | `--print sysroot` failed with `exit status: 127` | a pre-release Nix install | [A Nix pre-release install fails its sysroot probe](#a-nix-pre-release-install-fails-its-sysroot-probe) | -Some problems print no error at all: a check that disagrees with `cargo check`, a check that is slow -or builds a second `target/cgp`, and a compiler wrapper of your own that stopped running. Each has a -section near the end of the page. +Some problems print no error at all: a check that disagrees with `cargo check`, a slow first check, +and a compiler wrapper of your own that stopped running. Each has a section near the end of the page. ## Narrowing it down @@ -243,16 +242,11 @@ compiler, a pinned nightly, with Rust's next-generation trait solver turned on, on nightly-only or solver-specific behavior the two can disagree. When they do, trust `cargo check`, and use the tool for what it is for: reading the CGP errors both of them report. -## The check is slow, or a second `target/cgp` appears +## The first check is slow -**The first check in a project builds every dependency once more**, into `target/cgp`, because the -check uses its own toolchain and keeps its artifacts apart from your normal build. Later checks reuse -them. - -**The directory is relative to where you run the command.** Run from a subdirectory of your project, -the check creates `target/cgp` inside that subdirectory and builds everything there again. Run it from -the package or workspace root, or pass `--target-dir` to fix the location. Delete a stray directory as -you would any build output. +**The first check in a project builds every dependency once more**, into `target/cgp` inside your +project's target directory, because the check uses its own toolchain and keeps its artifacts apart +from your normal build. Later checks reuse them, from wherever in the project you run them. ## Your own compiler wrapper stopped running From b30e96c2ace532139fe8ff8ffd7eaf2c791e6652 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 5 Oct 2026 17:05:17 +0000 Subject: [PATCH 161/516] Name official versions only on the site The pages, the AGENTS rules, and the example-code crate name cgp 0.8.0 and cargo-cgp 0.1.0 and never a pre-release. The installation and troubleshooting pages drop their alpha-only sections, the comparison pages say they were compiled against cgp 0.8.0, three pages call cargo-cgp an early release, and example-code takes cgp straight from the repository's main. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 11 +++++++++++ docs/ai/disclaimer.md | 2 +- docs/cargo-cgp/installation.md | 15 +-------------- docs/cargo-cgp/troubleshooting.md | 16 ---------------- docs/comparisons/algebraic-effects.md | 2 +- docs/comparisons/capabilities.md | 2 +- docs/comparisons/dependency-injection.md | 2 +- docs/comparisons/dynamic-dispatch.md | 2 +- docs/comparisons/implicit-parameters.md | 2 +- docs/comparisons/ml-modules.md | 2 +- docs/comparisons/policy-based-design.md | 2 +- docs/comparisons/reflection.md | 2 +- docs/comparisons/row-polymorphism.md | 2 +- docs/comparisons/rust-language-proposals.md | 2 +- docs/comparisons/type-classes.md | 2 +- docs/index.md | 2 +- docs/overview.md | 2 +- example-code/Cargo.toml | 8 ++------ example-code/README.md | 5 +++-- 19 files changed, 31 insertions(+), 52 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a69ce266..d967d5c9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,6 +75,17 @@ which exists partly to be quoted. When a page quotes a project built with CGP, s [`projects/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/projects), which records the project's current code and whether it uses current idioms. +## Name official versions only + +Every page names official release versions, `cgp` 0.8.0 and `cargo-cgp` 0.1.0, as though they had +already shipped, and never a pre-release such as `0.8.0-alpha` or `0.1.0-alpha`. Pre-releases are +test runs of the crates and the cargo integration before an official release, not versions a reader +is expected to have, so no page names one, explains how one differs, or tells a reader how to move +off one. Command output that names a pre-release version is quoted with the official version. The +rule is the knowledge base's +[rule on versions](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md#document-official-versions-never-pre-releases), +and it yields only to an explicit instruction from the user. + ## Consult the communication strategy before writing public prose Everything published here is public writing about CGP, and how CGP is presented is a settled matter diff --git a/docs/ai/disclaimer.md b/docs/ai/disclaimer.md index c0645fb2..4c3427e1 100644 --- a/docs/ai/disclaimer.md +++ b/docs/ai/disclaimer.md @@ -70,7 +70,7 @@ work is extensive and repetitive, so assistance makes coverage practical beyond could maintain alone. Passing tests provide evidence for the cases they cover; an incorrect expectation or a missing case can still leave a bug undetected. -`cargo-cgp` is an early pre-release and can contain bugs. It rewrites the error classes it recognizes +`cargo-cgp` is an early release and can contain bugs. It rewrites the error classes it recognizes and passes other diagnostics through in the compiler's wording. ## The CGP library diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index 9ed55f07..ffabdefc 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -150,24 +150,11 @@ cargo cgp update It looks up the published versions on crates.io and does nothing if you already have the newest. When there is a newer one, it reinstalls the front end and runs the new version's `setup`, so the driver and -the pinned nightly move with it. It stays within your release channel: a stable install moves only to -stable releases, and a pre-release install to newer pre-releases or a stable release. +the pinned nightly move with it. On the Nix path there is no `cargo cgp update`. Change the version in the flake reference and reinstall the profile, or run `nix flake update cargo-cgp` in a flake that pins the tool as an input. -### Upgrading from the v0.1.0-alpha pre-release - -**An install of the `v0.1.0-alpha` pre-release cannot update itself to 0.1.0.** `update` runs the code -of the version you have, and the pre-release only ever looks for newer pre-releases. Reinstall instead: - -```sh -cargo install cargo-cgp -cargo cgp setup -``` - -On the Nix path, install the `v0.1.0` reference as above. - ## Using it in CI **Keep your own toolchain's `cargo check` as the gate, and add the tool for readable failures.** The diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index 7a93b421..569be744 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -35,7 +35,6 @@ Find the distinctive part of your error in the left column, then read the sectio | `could not find Cargo.toml` | run outside a cargo package | [The command itself fails](#the-command-itself-fails) | | `unexpected argument` | a flag `cargo check` does not know | [The command itself fails](#the-command-itself-fails) | | `rustup was not found on PATH` | `setup` needs rustup | [Setup fails](#setup-fails) | -| `--print sysroot` failed with `exit status: 127` | a pre-release Nix install | [A Nix pre-release install fails its sysroot probe](#a-nix-pre-release-install-fails-its-sysroot-probe) | Some problems print no error at all: a check that disagrees with `cargo check`, a slow first check, and a compiler wrapper of your own that stopped running. Each has a section near the end of the page. @@ -220,21 +219,6 @@ rustup first. `setup` also downloads the toolchain and the driver's source, so i connection; a failure during either step comes from rustup or cargo, and their message says what went wrong. -## A Nix pre-release install fails its sysroot probe - -A Nix install of the `v0.1.0-alpha` pre-release can fail in some projects before compiling anything: - -```text -cargo-cgp: `/nix/store/…-rust-minimal-…/bin/rustc --print sysroot` failed with status exit status: 127: - -rustc: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory -``` - -It happens in projects whose own rustup toolchain has the same Rust version as the tool's nightly: -rustup puts that toolchain's libraries ahead of the Nix ones, and they do not load in the Nix -environment. Version 0.1.0 fixes it, so upgrade the install to the `v0.1.0` reference, as described on -the [installation page](./installation.md#with-nix). - ## The check disagrees with `cargo check` **Your own toolchain's `cargo check` decides whether your code compiles.** A check runs a different diff --git a/docs/comparisons/algebraic-effects.md b/docs/comparisons/algebraic-effects.md index dcd19482..fca7a523 100644 --- a/docs/comparisons/algebraic-effects.md +++ b/docs/comparisons/algebraic-effects.md @@ -379,7 +379,7 @@ These pages expand the CGP mechanisms and nearby comparisons: The Koka `ask` snippet was compiled with Koka 3.2.3, and the `choice` handler follows the Koka book's own example; the OCaml snippet was compiled with OCaml 5.5.0 and the Flix snippet run with Flix -0.76.0. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` +0.76.0. The CGP snippets were compiled against `cgp` `0.8.0` with a `check_components!` assertion per wired context. - [Plotkin & Pretnar, *Handling Algebraic Effects* (LMCS 2013)](https://homepages.inf.ed.ac.uk/gdp/publications/handling-algebraic-effects.pdf) and [*Handlers of Algebraic Effects* (ESOP 2009)](https://homepages.inf.ed.ac.uk/gdp/publications/Effect_Handlers.pdf): effects as operations with an equational theory and handlers interpreting them through the continuation. diff --git a/docs/comparisons/capabilities.md b/docs/comparisons/capabilities.md index 88cc7cd2..fcb4c010 100644 --- a/docs/comparisons/capabilities.md +++ b/docs/comparisons/capabilities.md @@ -357,7 +357,7 @@ These pages explain the dependencies and related language proposals: ## Sources -The `cap-std` snippets were compiled with `cap-std` 3 and the CGP snippet against `cgp` `0.8.0-alpha` +The `cap-std` snippets were compiled with `cap-std` 3 and the CGP snippet against `cgp` `0.8.0` with a `check_components!` assertion per wired context; the Scala snippet was compiled with Scala 3.8.4. The Pony snippet was checked against the standard library's documented signatures for `FileAuth`, `FilePath`, and `OpenFile` rather than compiled. diff --git a/docs/comparisons/dependency-injection.md b/docs/comparisons/dependency-injection.md index 4248cf57..f858a805 100644 --- a/docs/comparisons/dependency-injection.md +++ b/docs/comparisons/dependency-injection.md @@ -274,7 +274,7 @@ These pages explain the mechanisms behind the comparison: ## Sources -The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per +The CGP snippets were compiled against `cgp` `0.8.0` with a `check_components!` assertion per wired context. The Java snippets follow the framework documentation cited below. - [Dagger developer guide](https://dagger.dev/dev-guide/): generated wiring, component graphs, and compile-time validation. diff --git a/docs/comparisons/dynamic-dispatch.md b/docs/comparisons/dynamic-dispatch.md index 569d284e..7a47275c 100644 --- a/docs/comparisons/dynamic-dispatch.md +++ b/docs/comparisons/dynamic-dispatch.md @@ -304,7 +304,7 @@ These pages explain the static mechanisms and related comparisons: ## Sources -The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per +The CGP snippets were compiled against `cgp` `0.8.0` with a `check_components!` assertion per wired context. This page contains only Rust snippets. - [The Rust Reference, *Trait object types*](https://doc.rust-lang.org/reference/types/trait-object.html): trait-object pointers and dynamic dispatch. diff --git a/docs/comparisons/implicit-parameters.md b/docs/comparisons/implicit-parameters.md index 8633be3f..cfc64954 100644 --- a/docs/comparisons/implicit-parameters.md +++ b/docs/comparisons/implicit-parameters.md @@ -308,7 +308,7 @@ These pages develop the mechanisms and related comparisons: ## Sources The Haskell snippets were compiled with GHC 9.10 and the Scala snippets with Scala 3.8.4. The CGP -snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per wired +snippets were compiled against `cgp` `0.8.0` with a `check_components!` assertion per wired context. - [Scala 3 Book, *Context Parameters*](https://docs.scala-lang.org/scala3/book/ca-context-parameters.html) and [Scala 3 Reference, *Given Instances*](https://docs.scala-lang.org/scala3/reference/contextual/givens.html): `using` clauses, `given` instances, and the 3.6 syntax change. diff --git a/docs/comparisons/ml-modules.md b/docs/comparisons/ml-modules.md index adfab06c..3aa87e72 100644 --- a/docs/comparisons/ml-modules.md +++ b/docs/comparisons/ml-modules.md @@ -332,7 +332,7 @@ These pages expand the constructs and comparisons used here: The OCaml snippets were compiled with OCaml 5.5.0; the modular-implicits snippet follows the proposal paper, since the extension has not shipped. The CGP snippets were compiled against `cgp` -`0.8.0-alpha` with a `check_components!` assertion per wired context. +`0.8.0` with a `check_components!` assertion per wired context. These references support the module semantics and comparison: diff --git a/docs/comparisons/policy-based-design.md b/docs/comparisons/policy-based-design.md index 6596a4da..4e2f7ff6 100644 --- a/docs/comparisons/policy-based-design.md +++ b/docs/comparisons/policy-based-design.md @@ -410,7 +410,7 @@ These pages expand the mechanisms used in the examples: The C++ snippets are adapted from the reference examples from Wikipedia and cppreference. They were compiled and run with GCC 15.2.0 in C++23 mode, with standard-library headers and small drivers added where omitted. The greeting qualifies inherited member calls with `this->` for dependent-base lookup. -The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` assertion per +The CGP snippets were compiled against `cgp` `0.8.0` with a `check_components!` assertion per wired context. These references support the C++ mechanisms and example origins: diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index 3957b678..7305103c 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -341,7 +341,7 @@ These pages develop the constructs and the neighbouring comparisons: ## Sources The Zig snippet was compiled with Zig 0.16; the Rust snippet is the nightly source's own doc test -and is unstable. The CGP snippets were compiled against `cgp` `0.8.0-alpha` with a +and is unstable. The CGP snippets were compiled against `cgp` `0.8.0` with a `check_components!` assertion on the wired context. - [`bevy_reflect` documentation](https://docs.rs/bevy_reflect/latest/bevy_reflect/), [`TypeInfo`](https://docs.rs/bevy/latest/bevy/reflect/enum.TypeInfo.html), and [`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html): the `Reflect` trait, the shape descriptor, and the runtime registry. diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index eb7e3837..c68837cc 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -322,7 +322,7 @@ These pages develop the patterns and the neighbouring comparisons: ## Sources The PureScript snippet was compiled with PureScript 0.15.15 against the prelude and the OCaml -snippet with OCaml 5.5.0. The CGP snippets were compiled against `cgp` `0.8.0-alpha` . +snippet with OCaml 5.5.0. The CGP snippets were compiled against `cgp` `0.8.0` . - [Wikipedia, *Structural type system*](https://en.wikipedia.org/wiki/Structural_type_system), [*Nominal type system*](https://en.wikipedia.org/wiki/Nominal_type_system), and [*Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism): the definitions and their contrast. - [PureScript language reference, *Types*](https://github.com/purescript/documentation/blob/master/language/Types.md), [Pursuit, *Prim*](https://pursuit.purescript.org/builtins/docs/Prim), and [*Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row): rows, records, open-row syntax, and the row type classes. diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md index 6eddbd5d..6d51a45d 100644 --- a/docs/comparisons/rust-language-proposals.md +++ b/docs/comparisons/rust-language-proposals.md @@ -379,7 +379,7 @@ These pages develop the constructs and the neighbouring comparisons: The Rust snippets from the proposals are quoted from their authors' posts and the Cairo book. The specialization snippet was compiled against a stable toolchain to confirm it is rejected with -`E0658` ; the CGP snippets were compiled against `cgp` `0.8.0-alpha` with a `check_components!` +`E0658` ; the CGP snippets were compiled against `cgp` `0.8.0` with a `check_components!` assertion per wired context. - [Rust Reference, *Implementations*](https://doc.rust-lang.org/reference/items/implementations.html) and [RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html): the orphan and overlap rules. diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md index 85bea89d..2116ac19 100644 --- a/docs/comparisons/type-classes.md +++ b/docs/comparisons/type-classes.md @@ -354,7 +354,7 @@ These pages develop the constructs and the neighbouring comparisons: The Haskell snippets were compiled with GHC 9.10, the Agda snippet type-checked with Agda 2.8.0, and the Lean snippet evaluated with Lean 4.34.0. The CGP snippets were compiled against `cgp` -`0.8.0-alpha` with a `check_components!` assertion per wired context. +`0.8.0` with a `check_components!` assertion per wired context. - [Wadler & Blott, *How to make ad-hoc polymorphism less ad hoc* (POPL 1989)](https://dl.acm.org/doi/10.1145/75277.75283): the origin of type classes and the dictionary-passing translation. - [GHC User's Guide, *Instance declarations and resolution*](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/instances.html): the one-instance rule, the orphan-instance rule, the overlap pragmas, and GHC's own warnings about incoherence. diff --git a/docs/index.md b/docs/index.md index cf0e8ed2..db991214 100644 --- a/docs/index.md +++ b/docs/index.md @@ -33,7 +33,7 @@ mission-critical project, expect to investigate problems yourself when the avail and support do not cover your case. [cargo-cgp](/docs/cargo-cgp) helps diagnose wiring errors by naming their root cause and showing the -dependency chain. The tool is an early pre-release and rewrites the error classes it recognizes; +dependency chain. The tool is an early release and rewrites the error classes it recognizes; other diagnostics retain the compiler's wording. CGP also publishes an [agent skill](/docs/ai/skills) to help coding assistants read, write, and debug CGP code. You still need to review the code an assistant produces. diff --git a/docs/overview.md b/docs/overview.md index 03106e92..d2ffbc18 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -44,7 +44,7 @@ does not force that verification, so use These checks establish that components fit together; they do not prove application logic correct. [cargo-cgp](/docs/cargo-cgp) helps explain wiring failures by showing the root cause and dependency -chain. It is an early pre-release and does not rewrite every kind of compiler error. +chain. It is an early release and does not rewrite every kind of compiler error. ### Abstract Over Every Dependency diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index 00fc0e8d..4452621f 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -6,7 +6,8 @@ publish = false description = "Compiled counterparts of the code shown on contextgeneric.dev. Not part of the site." [dependencies] -cgp = "0.8.0-alpha" +# The `cgp` release the site documents, taken from the repository until it is on crates.io. +cgp = { git = "https://github.com/contextgeneric/cgp.git" } [dev-dependencies] anyhow = "1" @@ -14,8 +15,3 @@ cap-std = "3" futures = "0.3" serde = { version = "1", features = ["derive"] } trybuild = "1" - - -[patch.crates-io] -cgp = { git = "https://github.com/contextgeneric/cgp.git" } -# cgp = { path = "../../cgp/crates/main/cgp" } diff --git a/example-code/README.md b/example-code/README.md index f210e310..9b150d5e 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -118,5 +118,6 @@ rejected snippet means writing a fixture under `tests/compile_fail/`, blessing i ## The `cgp` version -The crate pins `cgp = "0.8.0-alpha"`, which is what resolves from crates.io today. Re-pin it to -`"0.8.0"` when that release ships, alongside the version pins in the tutorials. +The crate takes `cgp` from the `cgp` repository's `main`, which is the 0.8.0 release the site +documents, so it checks the pages against that release before it is on crates.io. Once 0.8.0 is +published, pin `cgp = "0.8.0"` from crates.io instead, alongside the version pins in the tutorials. From d089837b0f62470f359b5f1325d709fb04b07a69 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 5 Oct 2026 17:11:16 +0000 Subject: [PATCH 162/516] Update cgp-skills --- cgp-skills | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgp-skills b/cgp-skills index bc45a587..40ee1f62 160000 --- a/cgp-skills +++ b/cgp-skills @@ -1 +1 @@ -Subproject commit bc45a587447774663d3f556cde1efad8d6e87701 +Subproject commit 40ee1f622a2396dff8c3d24717c48a1a52ac1f9f From f54b1f19db2e3faf2def225038012a4bb6b8e0c1 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 5 Oct 2026 17:20:24 +0000 Subject: [PATCH 163/516] Add the cargo-cgp editor integration page Document running cargo cgp check from rust-analyzer in VS Code, shrink the Check page's editor section to a pointer, renumber the cargo-cgp sidebar, and publish the skill's error-backends reference through its symlink. Co-Authored-By: Claude Opus 5.5 --- docs/ai/skills/references/error-backends.md | 1 + docs/cargo-cgp/check.md | 19 +-- docs/cargo-cgp/command-reference.md | 4 +- docs/cargo-cgp/editor-integration.md | 150 ++++++++++++++++++++ docs/cargo-cgp/error-codes.md | 2 +- docs/cargo-cgp/index.md | 1 + docs/cargo-cgp/troubleshooting.md | 2 +- 7 files changed, 159 insertions(+), 20 deletions(-) create mode 120000 docs/ai/skills/references/error-backends.md create mode 100644 docs/cargo-cgp/editor-integration.md diff --git a/docs/ai/skills/references/error-backends.md b/docs/ai/skills/references/error-backends.md new file mode 120000 index 00000000..5a746f68 --- /dev/null +++ b/docs/ai/skills/references/error-backends.md @@ -0,0 +1 @@ +../../../../cgp-skills/cgp/references/error-backends.md \ No newline at end of file diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index 0e73eaff..8a431d90 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -183,22 +183,9 @@ The tool reads two of the flags itself, `--target-dir` and `--manifest-path`, an ## In your editor -rust-analyzer can run the check every time you save. In VS Code, add this to your `settings.json`: - -```json -{ - "rust-analyzer.check.overrideCommand": [ - "cargo", "cgp", "check", "--workspace", "--all-targets", "--message-format=json" - ] -} -``` - -The command must go in `check.overrideCommand` rather than `check.command`, because it is more than one -word and must print JSON for the editor to read. The tool renders its rewritten errors in the same -JSON format as the compiler, so they appear inline like any other diagnostic, and the separate -`target/cgp` directory keeps the editor's checks from contending with your builds. Other editors that -use rust-analyzer take the same setting in their own configuration format. This setup has not yet been -tried in an editor as part of writing this page. +rust-analyzer can run `cargo cgp check` every time you save, so the errors your editor underlines lead +with their root cause too. It takes one setting, which +[Editor integration](./editor-integration.md) gives for VS Code, along with what the switch changes. ## When it will not help diff --git a/docs/cargo-cgp/command-reference.md b/docs/cargo-cgp/command-reference.md index 11666f9a..2413c9a9 100644 --- a/docs/cargo-cgp/command-reference.md +++ b/docs/cargo-cgp/command-reference.md @@ -1,7 +1,7 @@ --- title: 'cargo-cgp command reference: commands, options, variables' sidebar_label: 'Command reference' -sidebar_position: 8 +sidebar_position: 9 description: 'Every cargo-cgp command and option, the environment variables it reads and sets, the files it creates, and its exit status, in one place.' --- @@ -52,7 +52,7 @@ does not run a check. Two flags matter more than the rest: tool builds into the `cgp` subdirectory of your project's own target directory, which it reads from `cargo metadata`, so the location is the same wherever in the project you run it. - **`--message-format=json`** prints the errors as JSON, rewritten the same way as the text output. An - editor needs this form; see [Check](./check.md#in-your-editor). + editor needs this form; see [Editor integration](./editor-integration.md). ### `expand` diff --git a/docs/cargo-cgp/editor-integration.md b/docs/cargo-cgp/editor-integration.md new file mode 100644 index 00000000..9214deb3 --- /dev/null +++ b/docs/cargo-cgp/editor-integration.md @@ -0,0 +1,150 @@ +--- +title: 'Use cargo-cgp in VS Code with rust-analyzer' +sidebar_label: 'Editor integration' +sidebar_position: 6 +description: 'Make rust-analyzer run cargo cgp check when you save, so VS Code shows CGP errors with their root cause first, and learn what the switch changes.' +--- + +# Editor integration + +rust-analyzer runs `cargo check` every time you save a file and shows the errors in your editor. One +setting makes it run `cargo cgp check` instead, so the CGP errors VS Code underlines lead with their +root cause, exactly as they do in a terminal. This page covers VS Code with the +[rust-analyzer extension](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). +It is part of [`cargo-cgp`](./index.md), the error toolchain for [CGP](/docs/), and it assumes the +tool is [installed](./installation.md) and that `cargo cgp check` already works in a terminal in your +project. + +## Set it up + +**Add the setting to your project's workspace settings**, the `.vscode/settings.json` file at the +project's root. Open it with **Preferences: Open Workspace Settings (JSON)** from the command palette, +and add: + +```json +{ + "rust-analyzer.check.overrideCommand": [ + "cargo", "cgp", "check", "--workspace", "--all-targets", "--message-format=json" + ] +} +``` + +The next time you save a Rust file, rust-analyzer runs this command instead of `cargo check`. If the +errors you see do not change, run **rust-analyzer: Restart server** from the command palette. + +Each part of the command has a job: + +- **`cargo cgp check`** is the check itself, the same command you run in a terminal. +- **`--workspace`** checks every crate in the workspace, as rust-analyzer's own check does. +- **`--all-targets`** includes tests, examples, and benchmarks, so an error in a test shows up too. +- **`--message-format=json`** makes cargo print its errors as JSON, which is the only form + rust-analyzer reads. The tool writes its rewritten errors in the same JSON format as the compiler, + so nothing else is needed for them to reach the editor. + +**The command goes in `check.overrideCommand`, not `check.command`.** The +[`check.command`](https://rust-analyzer.github.io/book/configuration.html#check.command) setting takes +a single cargo subcommand, such as `clippy`, and rust-analyzer adds its own arguments after it, which +cannot spell `cgp check`. +[`check.overrideCommand`](https://rust-analyzer.github.io/book/configuration.html#check.overrideCommand) +takes the whole command line and runs it as written. + +### Workspace or user settings + +**Prefer the workspace settings, so the tool runs only on projects that use CGP.** +[User settings](https://code.visualstudio.com/docs/configure/settings) apply to every project you open. +The tool checks a project without CGP correctly, but it still builds that project a second time under +its pinned nightly, which costs time and disk for errors it has nothing to add to. Workspace settings +override user settings, so a project can also turn the check on or off for itself. + +**Commit `.vscode/settings.json` only if everyone who opens the project has the tool.** On a machine +without `cargo-cgp`, rust-analyzer runs a command that does not exist there, and that person sees no +check errors in their editor at all until they remove the setting or install the tool. + +## What the editor shows + +The errors appear where `cargo check`'s errors would: underlined in the file, listed in the Problems +panel, and in the hover over the underline. Their text is what `cargo cgp check` prints in a terminal. +For the program on the [Check page](./check.md#try-it-on-a-deliberate-mistake), where `Rectangle` lacks +the `height` field its area provider reads, the underline sits on `area` in `rectangle.area()`, and the +message is the rewritten one: + +```text +[CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` +root cause: [CGP-E106] missing field `height` on `Rectangle` +this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + └─ [CGP-E106] missing field `height` on `Rectangle` +``` + +The compiler's own code, `E0599` here, stays attached to the error, as it does in a terminal. +[Reading the output](./reading-output.md) explains each part. + +## What changes when the editor runs the tool + +Switching the check changes a few things about how rust-analyzer behaves, and each is worth knowing +before you wonder about it: + +- **The first save is slow.** The check builds into its own `target/cgp` directory under the tool's + pinned nightly, so the first one compiles every dependency again. Later saves reuse that build, and + because it is separate from `target`, your terminal builds and the editor's checks do not undo each + other's work. +- **rust-analyzer's own check options stop applying.** With an override in place, rust-analyzer runs + the command exactly as written, so settings such as + [`check.features`](https://rust-analyzer.github.io/book/configuration.html#check.features), + `check.allTargets`, and `check.extraArgs` no longer reach the check. Put the flags you need in the + command itself, for example `"--all-features"` or `"--features", "my-feature"` after + `"--all-targets"`. +- **Two kinds of error appear, and only one is rewritten.** rust-analyzer also analyzes your code as + you type, with its own engine and without running any compiler, and reports some errors of its own. + Those come from rust-analyzer rather than from the check, so they read as they always have. The + rewritten ones are the errors that arrive after a save. +- **The check and your toolchain can disagree.** The check compiles under the tool's pinned nightly + with Rust's next-generation trait solver, so on rare code the editor can show an error your own + `cargo check` does not, or the reverse. Your toolchain's `cargo check` is the authority on whether + the code compiles, as the [Check page](./check.md#what-a-check-does-differently) explains. + +## Turning it off + +Delete the `rust-analyzer.check.overrideCommand` entry from the settings file you added it to. +rust-analyzer goes back to running `cargo check` on save. + +## When it does not work + +**Run the same command in a terminal first**, from the root of the project you opened in VS Code: + +```sh +cargo cgp check --workspace --all-targets +``` + +The editor runs exactly this, so an error it prints here is the reason the editor shows nothing. +Messages from the tool itself, such as one telling you to run `cargo cgp setup`, are listed with +their fixes on [Troubleshooting](./troubleshooting.md). + +**If the terminal check works but the editor shows no errors from it**, VS Code may be running with a +different `PATH` from your terminal, so the `cargo` it starts cannot find the tool. This happens most +often when VS Code is started from a desktop launcher rather than from a shell, and when the tool is +installed somewhere only your shell's start-up files add to `PATH`, as with a Nix profile. Start VS Code +from a terminal in which `cargo cgp --version` works, and check again. + +**If only some errors are rewritten**, that is the tool's limit rather than the editor's. +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet +reshape every class. [Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists +the errors that arrive as the compiler wrote them. + +## What this does not do + +**It changes only the errors from the check that runs on save.** Completion, hover types, +go-to-definition, and rust-analyzer's own as-you-type errors are unaffected, because none of them run +the check. + +**It has been tested on Linux, with the rust-analyzer language server.** The setting was verified by +running the server the way VS Code runs it and reading the errors it reported for the program above. +Other editors that use rust-analyzer accept the same setting, `check.overrideCommand`, in their own +configuration format, but none of them, and neither macOS nor Windows, has been tried. + +--- + +*An AI agent wrote this page using the CGP knowledge base, and checked its setup against the +rust-analyzer language server. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index b2f3a12a..75428ab2 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -1,7 +1,7 @@ --- title: 'cargo-cgp error codes: every CGP-E code explained' sidebar_label: 'Error codes' -sidebar_position: 7 +sidebar_position: 8 description: 'Look up any [CGP-Exxx] code cargo cgp check prints: what the message says, what mistake it means, how to fix it, and where the class is explained.' --- diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index db8206cd..1a29b52d 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -196,6 +196,7 @@ Start with installation, then the page for what you want to do: - [Check](./check.md): running a check, and trying it on a deliberate mistake. - [Reading the output](./reading-output.md): every shape of error the tool produces, part by part. - [Expand](./expand.md): reading what your CGP macros generated. +- [Editor integration](./editor-integration.md): rewritten errors in VS Code, every time you save. - [Troubleshooting](./troubleshooting.md): when the tool itself will not run. - [Error codes](./error-codes.md) and [Command reference](./command-reference.md): to look something up. diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index 569be744..c3a88dc0 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -1,7 +1,7 @@ --- title: 'Troubleshooting cargo-cgp' sidebar_label: 'Troubleshooting' -sidebar_position: 6 +sidebar_position: 7 description: 'Match an error from cargo-cgp itself to its cause and fix: the setup check, a driver that will not load or cannot be found, wrong invocations, and slow checks.' --- From 8ae47e20a5b2d620c8da726151311e50cb54df88 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 5 Oct 2026 17:26:55 +0000 Subject: [PATCH 164/516] Describe rust-analyzer's failure warning on the editor page Quote the warning a failing check produces, for a missing setup and a tool missing from PATH, explain why check.command cannot hold cgp check, and say what was and was not tested. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/editor-integration.md | 59 ++++++++++++++++++---------- 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/docs/cargo-cgp/editor-integration.md b/docs/cargo-cgp/editor-integration.md index 9214deb3..c2f168d4 100644 --- a/docs/cargo-cgp/editor-integration.md +++ b/docs/cargo-cgp/editor-integration.md @@ -43,8 +43,8 @@ Each part of the command has a job: **The command goes in `check.overrideCommand`, not `check.command`.** The [`check.command`](https://rust-analyzer.github.io/book/configuration.html#check.command) setting takes -a single cargo subcommand, such as `clippy`, and rust-analyzer adds its own arguments after it, which -cannot spell `cgp check`. +a single cargo subcommand, such as `clippy`, and rust-analyzer puts its own flags straight after it, +so `cgp` would be followed by `--workspace` rather than by `check`. [`check.overrideCommand`](https://rust-analyzer.github.io/book/configuration.html#check.overrideCommand) takes the whole command line and runs it as written. @@ -53,12 +53,12 @@ takes the whole command line and runs it as written. **Prefer the workspace settings, so the tool runs only on projects that use CGP.** [User settings](https://code.visualstudio.com/docs/configure/settings) apply to every project you open. The tool checks a project without CGP correctly, but it still builds that project a second time under -its pinned nightly, which costs time and disk for errors it has nothing to add to. Workspace settings +its pinned nightly, which costs time and disk on a project that has no CGP errors to rewrite. Workspace settings override user settings, so a project can also turn the check on or off for itself. **Commit `.vscode/settings.json` only if everyone who opens the project has the tool.** On a machine -without `cargo-cgp`, rust-analyzer runs a command that does not exist there, and that person sees no -check errors in their editor at all until they remove the setting or install the tool. +without `cargo-cgp`, the check fails on every save, so that person gets a warning from rust-analyzer +instead of their check errors until they install the tool or remove the setting. ## What the editor shows @@ -82,17 +82,16 @@ The compiler's own code, `E0599` here, stays attached to the error, as it does i ## What changes when the editor runs the tool -Switching the check changes a few things about how rust-analyzer behaves, and each is worth knowing -before you wonder about it: +Running the tool in place of `cargo check` changes four things about how rust-analyzer behaves: - **The first save is slow.** The check builds into its own `target/cgp` directory under the tool's pinned nightly, so the first one compiles every dependency again. Later saves reuse that build, and because it is separate from `target`, your terminal builds and the editor's checks do not undo each other's work. -- **rust-analyzer's own check options stop applying.** With an override in place, rust-analyzer runs +- **rust-analyzer's own check options are ignored.** With an override in place, rust-analyzer runs the command exactly as written, so settings such as [`check.features`](https://rust-analyzer.github.io/book/configuration.html#check.features), - `check.allTargets`, and `check.extraArgs` no longer reach the check. Put the flags you need in the + `check.allTargets`, and `check.extraArgs` do not reach the check. Put the flags you need in the command itself, for example `"--all-features"` or `"--features", "my-feature"` after `"--all-targets"`. - **Two kinds of error appear, and only one is rewritten.** rust-analyzer also analyzes your code as @@ -111,21 +110,37 @@ rust-analyzer goes back to running `cargo check` on save. ## When it does not work -**Run the same command in a terminal first**, from the root of the project you opened in VS Code: +**When the command fails, rust-analyzer says so in a warning.** The warning begins +`cargo check failed to start`, whatever the command is, and ends with what the command printed. A +missing setup, for example, arrives as the tool's own message: + +```text +cargo check failed to start: Cargo watcher failed, the command produced no valid metadata (exit code: ExitStatus(unix_wait_status(256))): +cargo-cgp: toolchain `nightly-2026-09-14` is not available (exit status: 1) + +The pinned toolchain is not installed. Run `cargo cgp setup`. +``` + +Your message names the nightly your build is pinned to. Look the message up on +[Troubleshooting](./troubleshooting.md), which lists each one with its fix. To tell whether the problem +is the tool or the editor, run the same command in a terminal from the root of the project you opened +in VS Code: ```sh cargo cgp check --workspace --all-targets ``` -The editor runs exactly this, so an error it prints here is the reason the editor shows nothing. -Messages from the tool itself, such as one telling you to run `cargo cgp setup`, are listed with -their fixes on [Troubleshooting](./troubleshooting.md). +**If the warning ends with cargo's `no such command` error, the editor cannot find the tool:** + +```text +error: no such command: `cgp` +``` -**If the terminal check works but the editor shows no errors from it**, VS Code may be running with a -different `PATH` from your terminal, so the `cargo` it starts cannot find the tool. This happens most -often when VS Code is started from a desktop launcher rather than from a shell, and when the tool is -installed somewhere only your shell's start-up files add to `PATH`, as with a Nix profile. Start VS Code -from a terminal in which `cargo cgp --version` works, and check again. +When the terminal command works, VS Code is running with a different `PATH` from your terminal, so the +`cargo` it starts does not see the tool. This happens most often when VS Code is started from a desktop +launcher rather than from a shell, and the tool is installed somewhere only your shell's start-up files +add to `PATH`, as with a Nix profile. Start VS Code from a terminal in which `cargo cgp --version` +works, and save again. **If only some errors are rewritten**, that is the tool's limit rather than the editor's. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet @@ -139,9 +154,11 @@ go-to-definition, and rust-analyzer's own as-you-type errors are unaffected, bec the check. **It has been tested on Linux, with the rust-analyzer language server.** The setting was verified by -running the server the way VS Code runs it and reading the errors it reported for the program above. -Other editors that use rust-analyzer accept the same setting, `check.overrideCommand`, in their own -configuration format, but none of them, and neither macOS nor Windows, has been tried. +running the server the way VS Code runs it, saving the program above, and reading what the server +reported: the rewritten error, the warnings quoted above, and the check options it leaves out +under the override. The VS Code window itself was not part of that test. Other editors that use rust-analyzer accept the +same setting, `check.overrideCommand`, in their own configuration format, but none of them has been +tried, and neither have macOS and Windows. --- From dcd896bdde0ab4df21ca74e6c9e2e9d01116ce51 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 14:38:57 +0200 Subject: [PATCH 165/516] Add the AI section overview and the knowledge-base pages Add docs/ai/index.md and docs/ai/knowledge-base/ (overview, how the documentation is written, using it with an agent, contributing with an agent). Revise the AI disclaimer, link the new pages from the skill index and Contribute, rename the section label to AI-Assisted Development, and record the bounded link exception in AGENTS.md. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 25 ++- docs/ai/_category_.json | 6 +- docs/ai/disclaimer.md | 158 +++++++++++------- docs/ai/index.md | 55 ++++++ docs/ai/knowledge-base/_category_.json | 8 + .../contributing-with-an-agent.md | 143 ++++++++++++++++ .../knowledge-base/how-cgp-is-documented.md | 143 ++++++++++++++++ docs/ai/knowledge-base/index.md | 106 ++++++++++++ .../using-it-with-your-agent.md | 95 +++++++++++ docs/ai/skills/index.md | 4 + docs/contribute.md | 13 ++ 11 files changed, 686 insertions(+), 70 deletions(-) create mode 100644 docs/ai/index.md create mode 100644 docs/ai/knowledge-base/_category_.json create mode 100644 docs/ai/knowledge-base/contributing-with-an-agent.md create mode 100644 docs/ai/knowledge-base/how-cgp-is-documented.md create mode 100644 docs/ai/knowledge-base/index.md create mode 100644 docs/ai/knowledge-base/using-it-with-your-agent.md diff --git a/AGENTS.md b/AGENTS.md index d967d5c9..565c4fe5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,14 +40,23 @@ A published page may link only to public resources: other pages on this site, th [docs.rs](https://docs.rs/cgp), [crates.io](https://crates.io/crates/cgp), the [CGP Patterns book](https://patterns.contextgeneric.dev/), and ordinary external sources. -**One published page is a sanctioned exception, and only one.** `docs/ai/disclaimer.md` links to the -knowledge base repository, because the base is the subject it discloses: the page's argument is that -CGP's documentation is written against a public record whose rules and history a reader can go and -check, and that argument cannot be made while hiding the record. Neither reason behind the rule applies -there — the link is a public GitHub URL that resolves for anyone, and exposing the material is the -point rather than an accident. The exception covers the repository's front door only, never a path into -a particular file, since a reader following a deep link lands in prose written for agents. Do not -"correct" that page's link, and do not extend the exception to any other page. +**Two hand-written surfaces are sanctioned exceptions, and only two.** `docs/ai/disclaimer.md` links +to the knowledge base repository, because the base is the subject it discloses: the page's argument +is that CGP's documentation is written against a public record whose rules and history a reader can +go and check, and that argument cannot be made while hiding the record. The pages under +`docs/ai/knowledge-base/` link to it because they explain the base and teach readers to point an +agent at it, which cannot be done without naming its files. Neither reason behind the rule applies +to either surface: the links are public GitHub URLs that resolve for anyone, and exposing the +material is the point rather than an accident. + +Each exception has a bound. The disclaimer links the repository's front door and its issue tracker, +where readers report problems in the base. The knowledge-base pages may also link the four top-level +entry files (`README.md`, `summary.md`, `AGENTS.md`, and `sibling-projects.md`), and never a +document inside a section, since a reader following such a link lands in prose written for agents; +they name a section's directory in prose instead. Do not "correct" these links, and do not extend +the exception to any other page. The knowledge base's [website +rules](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/AGENTS.md#the-one-way-link-rule) +are the authority on both bounds. This file is the exception, because it is not published — Docusaurus renders `docs/`, `blog/`, and `src/pages/`, and a repository-root Markdown file is never part of the built site. So it may point at diff --git a/docs/ai/_category_.json b/docs/ai/_category_.json index 20b1b6dc..92b8a026 100644 --- a/docs/ai/_category_.json +++ b/docs/ai/_category_.json @@ -1,8 +1,8 @@ { - "label": "AI Assisted Development", + "label": "AI-Assisted Development", "position": 12, "link": { - "type": "generated-index", - "description": "CGP's published agent skill, for handing to a coding assistant, and how the project discloses its own use of AI." + "type": "doc", + "id": "ai/index" } } diff --git a/docs/ai/disclaimer.md b/docs/ai/disclaimer.md index 4c3427e1..96f7b0f3 100644 --- a/docs/ai/disclaimer.md +++ b/docs/ai/disclaimer.md @@ -1,77 +1,99 @@ --- -sidebar_position: 2 +sidebar_position: 3 sidebar_label: AI Disclaimer +description: 'How the CGP project uses AI: agents write most of the documentation and tooling, the author designs CGP and writes the core library, and how each part is checked and reviewed.' --- # How AI Is Used in the CGP Project -CGP uses AI agents to write documentation, develop tools, maintain tests, and assist with library -implementation. The author designs every CGP construct and interface and writes the core library -almost entirely by hand. This page explains who does what, how the work is checked, and where those -checks have limits. +[Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait +implementations at compile-time. The project uses AI agents to write documentation, develop tools, +maintain tests, and assist with library implementation. The author designs every CGP construct and +interface and writes the core library almost entirely by hand. + +How much of the work agents do differs by part of the project, and the sections below run from the +most agent-written part to the least. Each section says who does what, how the work is checked, and +where those checks have limits. ## Why the levels differ CGP gives agents more writing responsibility when the result can be checked against existing code and does not become part of your compiled program. Documentation, tools, and tests fit that arrangement. The core library requires more direct authorship because applications depend on its -code and its design establishes the behavior that other work must follow. +code, and its design sets the behavior that all other work must follow. -Verification also differs by artifact. A claim about a macro can be checked against its source and -expansion snapshots. A tool's output can be compared with test fixtures. Design requires the author's -judgment about which behavior the library should provide; passing tests alone cannot settle it. +Verification also differs by part. A claim about a macro can be checked against its source and +expansion snapshots, and a tool's output can be compared with test fixtures. Design is different: it +requires the author's judgment about which behavior the library should provide, and passing tests +alone cannot settle that. ## Documentation and reference pages -AI agents write most of CGP's reference pages, explanations, guides, and error documentation from the -public [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base). That repository -records the material behind the website and the rules agents must follow. Readers can inspect both -the documentation and the process used to produce it. - -**The source code is authoritative.** Agents must check claims about accepted syntax, generated names, -and macro expansions against the code, tests, or expansion snapshots. When documentation and code -disagree, the documentation needs correction. The rules also require documentation updates alongside -behavior changes and direct corrections to pages that describe current behavior. - -The public history records AI contributions through `Co-Authored-By` commit trailers naming the -model. Together with the writing rules, that history lets readers inspect how the documentation was -produced. It provides a record of contributions, not a guarantee that every statement is correct. - -**Human review varies by page.** The author sets the writing rules and priorities and reads the front -page, Concepts explanation pages, reference index, this disclosure, and every blog post in full -before publication. On each Comparisons page, which describes another community's tool beside CGP, -the author reads in full the two sections that judge that tool: what each approach costs, and where -the other tool is the better choice. Individual construct reference pages, and the remaining sections -of a comparison page, follow a writing guide and receive spot checks; the author does not read each -one line by line. - -Source verification and human review serve different purposes. Checking a macro expansion against -the source can reveal a technical mistake, while reading an explanation can reveal a misleading -argument. Both can miss errors, and the project remains responsible for correcting them. +AI agents write most of CGP's reference pages, explanations, guides, and error documentation from +the public [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base). That +repository is written for agents, and it records the material behind the website and the rules +agents must follow. Readers can inspect both the documentation and the process that produces it, +which [How CGP's Documentation Is Written](/docs/ai/knowledge-base/how-cgp-is-documented) describes +in full. + +The knowledge base is in an early phase and under active development. Many of its documents still +need further review, by the author and by agents, and some contain errors or inconsistencies that no +review has found yet. The aim is to improve it step by step toward full accuracy, meaning agreement +with the author's intent as well as with the source, and the pages written from it inherit its +current state. + +**The source code is authoritative.** Agents must check claims about accepted syntax, generated +names, and macro expansions against the code, tests, or expansion snapshots. When documentation and +code disagree, the documentation is corrected. The rules also require a change in behavior to update +its documentation in the same change, and pages that describe current behavior are corrected in +place. + +The author directs this work. He designs CGP, writes the rules agents follow, and chooses what gets +documented, and the rules tell an agent to ask rather than guess when a choice has more than one +reasonable answer. The public history records AI contributions through `Co-Authored-By` commit +trailers naming the model, so readers can see which changes agents made. That history is a record of +contributions, not a guarantee that every statement is correct. + +**Human review varies by page.** The author reads these pages in full before publication: the front +page, the Concepts explanation pages, the reference index, this disclosure, the page describing how +the documentation is written, and every blog post. On each Comparisons page, which describes another +community's tool beside CGP, he reads in full the two sections that judge that tool: what each +approach costs, and where the other tool is the better choice. Every other page, including the +individual construct reference pages and the remaining sections of each comparison page, follows a +writing guide and receives spot checks; the author does not read each one line by line. + +Source checks and human review catch different mistakes, and neither catches all of them. Some +checks are mechanical: expansion snapshots fail when a macro's output changes, and code shown on a +page is compiled in a test crate when the page is written or revised. Agreement between prose and +code depends on agents following the rules and on review. Checking a macro expansion against the +source can reveal a technical mistake, while reading an explanation can reveal a misleading +argument. Either can miss an error, and the project remains responsible for correcting it. ## Blog posts and tutorials The author drafts blog posts and tutorials, then an agent revises the prose and checks the code and -claims against the knowledge base. The author supplies the argument, examples, and judgment about -what to teach. This differs from reference pages, where agents write the initial text. +claims against the knowledge base. The author supplies the argument, the examples, and the judgment +about what to teach. This reverses the arrangement for reference pages, where agents write the +initial text. Revision improves the prose and checks the code; it does not guarantee that the +argument is correct. -Revision does not guarantee that an argument is correct. This describes the current writing process; -older site text received broader LLM refinement, as -[the post about this website](/blog/2026/02/21/new-website) describes. +Older site text went through broader LLM refinement than this, as +[the post about this website](/blog/2026/02/21/new-website) describes. This section describes the +current process. ## Tooling and tests -Agents write most of [cargo-cgp](https://github.com/contextgeneric/cargo-cgp) and maintain much of -CGP's test suite. These tools run on a project rather than becoming library dependencies compiled -into its application. Their output can be checked against fixtures and the library's behavior. +Agents write most of [cargo-cgp](/docs/cargo-cgp) and maintain much of CGP's test suite. Neither +becomes part of your compiled program: `cargo-cgp` runs on a project, and the tests exercise the +library. Their results can be checked against test fixtures and the library's behavior. -Agents also help expand test coverage across the syntax forms the procedural macros accept. That -work is extensive and repetitive, so assistance makes coverage practical beyond what the author -could maintain alone. Passing tests provide evidence for the cases they cover; an incorrect +Agents also help extend test coverage across the syntax forms the procedural macros accept. That +work is extensive and repetitive, and agent assistance makes coverage practical beyond what the +author could maintain alone. Passing tests are evidence for the cases they cover, but an incorrect expectation or a missing case can still leave a bug undetected. -`cargo-cgp` is an early release and can contain bugs. It rewrites the error classes it recognizes -and passes other diagnostics through in the compiler's wording. +`cargo-cgp` is an early release and can contain bugs. `cargo cgp check` leads with the root cause +for the classes it recognizes, and the tool does not yet reshape every class. ## The CGP library @@ -79,26 +101,44 @@ The author designs every CGP construct and interface, and writes the core librar by hand. This is the code applications import and compile, so he takes direct responsibility for its design and implementation. -AI assists with correctness checks, code-quality review, and procedural-macro implementation. The -author directs and reviews that implementation work. The -[cgp repository](https://github.com/contextgeneric/cgp) records shared work through -`Co-Authored-By` trailers, including contributions to the macros. +AI assists with correctness checks, code-quality review, and procedural-macro implementation, and +the author directs and reviews that work. The [cgp +repository](https://github.com/contextgeneric/cgp) records shared work through `Co-Authored-By` +trailers, including contributions to the macros. + +The line runs between design ownership and implementation assistance. The author decides what CGP +provides and how its interfaces fit together; agents help implement and check some of those +decisions. The library therefore includes AI contributions, and its checks cannot guarantee that +every implementation is correct. + +## Contributions from others + +Contributions from outside the project follow their own policy, which is deliberately light; a more +detailed one will follow. An AI-assisted contribution to any CGP repository must use the knowledge +base, so the agent works from the current syntax and updates the documentation the change affects. +An AI-assisted pull request or issue must also include the prompts used to verify the issue or apply +the fix, since the CGP maintainers may run similar prompts themselves rather than merge a pull +request directly. [Contributing to CGP with an +Agent](/docs/ai/knowledge-base/contributing-with-an-agent) gives the policy in full. -The distinction is between design ownership and implementation assistance. The author decides what -CGP provides and how its interfaces fit together; agents help implement and check some of those -decisions. The library is not entirely free of AI contributions, and its checks cannot guarantee -that every implementation is correct. +Finding and reporting problems in the knowledge base is itself a useful contribution while it is +still being reviewed. File them on its +[issue tracker](https://github.com/contextgeneric/cgp-knowledge-base/issues). ## Responsibility The project is responsible for everything published under CGP's name, including errors in -agent-written work. As CGP's author, I would rather you told me about an error than worked around it. +agent-written work. As CGP's author, I would rather you told me about an error than worked around +it. Report a problem in the knowledge base on its +[issue tracker](https://github.com/contextgeneric/cgp-knowledge-base/issues), and any other error in +[GitHub Discussions](https://github.com/orgs/contextgeneric/discussions) or on the repository it +concerns. ## How pages are marked -New or substantially rewritten pages carry a short note linking to the section here that describes -how they were made. Older pages receive a note only after their provenance has been established. -The absence of a note does not mean a page was written without AI assistance. +New or substantially rewritten pages carry a short note at their foot, linking to the section here +that describes how they were made. Older pages receive a note only after their provenance has been +established, so the absence of a note does not mean a page was written without AI assistance. --- diff --git a/docs/ai/index.md b/docs/ai/index.md new file mode 100644 index 00000000..aac810d5 --- /dev/null +++ b/docs/ai/index.md @@ -0,0 +1,55 @@ +--- +title: 'AI-Assisted Development' +sidebar_label: 'Overview' +sidebar_position: 0 +description: 'How to work with CGP through a coding agent, using its agent skill and knowledge base, and how the CGP project itself uses AI to write its documentation, tools, and tests.' +--- + +# AI-Assisted Development + +[Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait +implementations at compile-time. This section covers CGP and AI coding agents in two directions: +help for you when you work on CGP code with an agent, and an account of how the CGP project uses +agents itself. The two are separate subjects, and the pages below keep them apart. + +## Working with CGP through an agent + +CGP publishes material that teaches a coding agent its vocabulary, its recommended syntax, and how +to read its compile errors. That can reduce the work of learning CGP, writing its wiring, and +reading its diagnostics, but it does not replace your own review: an agent can still produce wrong +code, and you remain the one who has to understand it. + +Choose the page for what you want to do: + +- **Have your agent read and write CGP code.** Start with [CGP's agent skill](/docs/ai/skills), + which your agent loads and which covers everyday work. +- **Get a deeper answer than the skill gives.** Read + [Using the Knowledge Base with Your Agent](/docs/ai/knowledge-base/using-it-with-your-agent) to + point your agent at the full record behind the skill. +- **Contribute to CGP with an agent's help.** Read + [Contributing to CGP with an Agent](/docs/ai/knowledge-base/contributing-with-an-agent) for the + policy for AI-assisted contributions, how to report problems in the knowledge base, the setup, and + the rules your agent follows. + +To learn CGP yourself, start with the [tutorials](/docs/tutorials/hello) and the +[Concepts](/docs/concepts) pages instead. The skill and the knowledge base are written for agents. + +## How the CGP project uses AI + +AI agents write most of CGP's documentation and most of `cargo-cgp`, maintain much of CGP's test +suite, and assist with parts of the library's implementation. The author designs every CGP construct +and writes the core library almost entirely by hand. These pages explain the arrangement and how it +is checked: + +- **Which parts of the project are written by AI, and who reviews them?** Read [How AI Is Used in + the CGP Project](/docs/ai/disclaimer). New pages written with AI assistance link to it from a note + at their foot. +- **How is agent-written documentation kept accurate?** Read + [How CGP's Documentation Is Written](/docs/ai/knowledge-base/how-cgp-is-documented). +- **What is the knowledge base the documentation comes from?** Read + [The CGP Knowledge Base](/docs/ai/knowledge-base). + +--- + +*An AI agent wrote this page using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/ai/knowledge-base/_category_.json b/docs/ai/knowledge-base/_category_.json new file mode 100644 index 00000000..549befc4 --- /dev/null +++ b/docs/ai/knowledge-base/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Knowledge Base", + "position": 2, + "link": { + "type": "doc", + "id": "ai/knowledge-base/index" + } +} diff --git a/docs/ai/knowledge-base/contributing-with-an-agent.md b/docs/ai/knowledge-base/contributing-with-an-agent.md new file mode 100644 index 00000000..8ccd93e6 --- /dev/null +++ b/docs/ai/knowledge-base/contributing-with-an-agent.md @@ -0,0 +1,143 @@ +--- +title: 'Contributing to CGP with an Agent' +sidebar_label: 'Contributing with an Agent' +sidebar_position: 4 +description: 'Meet CGP''s policy for AI-assisted contributions, report problems in the knowledge base, set up the repositories for a coding agent, and follow the rules each repository gives it.' +--- + +# Contributing to CGP with an Agent + +[Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait +implementations at compile-time. This page is for contributors who want to change CGP itself (the +library, the [cargo-cgp](/docs/cargo-cgp) toolchain, the agent skill, or the documentation) with a +coding agent's help. It covers the policy for AI-assisted contributions, reporting problems in the +knowledge base, the local setup the repositories expect, and the rules your agent follows while it +works. It assumes you already use an agent and have contributed to a Rust project through GitHub +before. + +## Contribution policy + +**An AI-assisted contribution to any CGP repository must use the +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base).** If an agent writes or +changes code or documentation in your contribution, direct it to read the knowledge base, which is +written for agents, and to follow the `AGENTS.md` file of each repository it touches. The +contribution then carries the documentation and skill updates the change requires, and it uses the +vocabulary and the current syntax the knowledge base records. + +The policy exists because an agent working from its training alone writes outdated CGP. It +reproduces syntax that earlier releases accepted and the current one does not, and it guesses at +semantics the knowledge base already states. [How CGP's Documentation Is +Written](how-cgp-is-documented.md) explains the problem and the process that answers it. + +**An AI-assisted pull request or issue must include the prompts used to produce it**: the prompt +that verified the issue, or the prompt that applied the fix. The CGP maintainers may run similar +prompts themselves rather than merge a pull request directly, so the prompt can be as useful to them +as the change. + +This is a deliberately light policy, and a more detailed one will follow. Until then, it asks for +nothing beyond these two requirements. You remain responsible for reviewing what your agent produces +before you submit it. + +## Report problems in the knowledge base + +Finding problems in the knowledge base is one of the most useful contributions, and it needs no +local setup. The knowledge base is in an early phase, and many of its documents still need further +review by the author and by agents, as [its current state](index.md#its-current-state) describes. An +error you find, or an inconsistency between two documents or between a document and the code, is +review the project would otherwise have to do itself. + +File each problem on the knowledge base's +[issue tracker](https://github.com/contextgeneric/cgp-knowledge-base/issues). Say which document is +wrong, what it says, and what the source or another document shows instead. If an agent found or +checked the problem, include the prompt you gave it, as the policy above requires. + +## Set up the repositories + +Clone the CGP repositories next to each other under one parent directory. Their documents and rules +refer to each other by relative paths such as `../cgp`, and some tests depend on that layout. Clone +the repositories your change touches, together with the knowledge base and the skill: + +```sh +mkdir context-generic && cd context-generic +git clone https://github.com/contextgeneric/cgp.git +git clone https://github.com/contextgeneric/cgp-knowledge-base.git +git clone https://github.com/contextgeneric/cgp-skills.git +# as needed: +git clone https://github.com/contextgeneric/cargo-cgp.git +git clone https://github.com/contextgeneric/contextgeneric.dev.git +``` + +The layout matters in these places: + +- **The skills inside `cgp`.** The `cgp` repository includes two skills under `.claude/skills/` as + links to sibling checkouts: the CGP skill from `cgp-skills`, and the `point-first-writing` skill + from the knowledge base. Each link resolves only when its repository is cloned next to `cgp`. +- **The `cargo-cgp` tests.** Its UI test suite compiles fixtures against a `cgp` checkout at + `../cgp`. Work on its compiler driver may also consult the Rust compiler's source, which its + `AGENTS.md` expects at `../external/rust`. +- **The rest of the family.** The full list of repositories, including the projects built with CGP, + is in the knowledge base's + [sibling-projects.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/sibling-projects.md). + +## Follow the repository rules + +Each repository has an `AGENTS.md` at its root, and it is the first file your agent should read: +[`cgp`](https://github.com/contextgeneric/cgp/blob/main/AGENTS.md), +[`cargo-cgp`](https://github.com/contextgeneric/cargo-cgp/blob/main/AGENTS.md), +[`cgp-skills`](https://github.com/contextgeneric/cgp-skills/blob/main/AGENTS.md), [the knowledge +base](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md), and [the +website](https://github.com/contextgeneric/contextgeneric.dev/blob/main/AGENTS.md). Each one gives +the conventions that repository follows and the knowledge-base documents to read before a task. The +code repositories' files also give the commands that build and test them. + +One obligation runs through all of them: **a change carries its documentation in the same +contribution.** The code is the authority, and the knowledge base, the skill, and the site are +views of it that must not drift. Each kind of change carries its own updates: + +- **A change to a construct** (its syntax, its expansion, its defaults, or its errors) updates the + knowledge base's reference and implementation documents, the expansion snapshots, and the matching + part of the agent skill. +- **A change to `cargo-cgp`'s behavior** updates the knowledge base's `cargo-cgp/` documents and the + UI fixtures that pin the output. +- **A change to a page on this site** updates the knowledge base's record of that page. +- **A correction to a document** starts in the knowledge base and then reaches whatever was written + from it: the matching part of the skill, and the page on this site ported from it. + +A contribution that spans repositories needs a pull request in each. Link them to each other so +they can be reviewed together. + +The rules also ask your agent to load two skills before it works. The CGP skill lives in +[`cgp-skills`](https://github.com/contextgeneric/cgp-skills), and the `point-first-writing` skill, +which the rules name for any prose the agent writes, lives in the knowledge base's `skills/` +directory. Make both available to your agent in the way it loads skills. + +The rules also shape how the agent works with you. It stops and asks you when a choice has more than +one defensible answer, such as an unclear intended behavior, rather than guessing. And it creates +commits only when you ask for them, so you decide when the work is ready to commit and submit. + +## Use an established workflow + +The `cgp` and `cargo-cgp` repositories each describe a complete workflow for their most common kind +of change, which an agent can follow from start to finish: + +- **Reviewing a macro.** The `cgp` repository's [macro review + workflow](https://github.com/contextgeneric/cgp/blob/main/AGENTS.md#macro-review-workflow) hardens + one macro at a time: fixing bugs and corner cases, closing test gaps, checking spans and hygiene, + and updating every view of the macro together. +- **Improving an error message.** The `cargo-cgp` repository's [error-message + loop](https://github.com/contextgeneric/cargo-cgp/blob/main/AGENTS.md#improving-error-messages-against-real-world-cgp-code) + reproduces a confusing diagnostic as a small test fixture before changing the tool, then confirms + that the fixture's output improves. + +## Where to ask + +Ask questions about a contribution in [GitHub +Discussions](https://github.com/orgs/contextgeneric/discussions) or on +[Discord](https://discord.gg/Hgk3rCw6pQ). The author designs CGP's constructs and interfaces, so +raise a change to a construct's design there before starting it. The [Contribute](/docs/contribute) +page lists other ways to help CGP. + +--- + +*An AI agent wrote this page using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/ai/knowledge-base/how-cgp-is-documented.md b/docs/ai/knowledge-base/how-cgp-is-documented.md new file mode 100644 index 00000000..da101c73 --- /dev/null +++ b/docs/ai/knowledge-base/how-cgp-is-documented.md @@ -0,0 +1,143 @@ +--- +title: 'How CGP''s Documentation Is Written' +sidebar_label: 'How the Documentation Is Written' +sidebar_position: 2 +description: 'AI agents write CGP''s documentation from a public knowledge base that is checked against the library''s source. How that differs from one-shot prompting, and where its checks stop.' +--- + +# How CGP's Documentation Is Written + +[Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait +implementations at compile-time. AI agents write most of its documentation from the public +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base), a record written for +agents and checked against the library's source. This page describes that process, the problem it +answers, and where its checks stop. The [AI disclaimer](/docs/ai/disclaimer) summarizes who writes +and reviews each part of the project; this page gives the full account of the documentation process. + +## The problem with one-shot prompts + +An agent asked to write about CGP in a single prompt, with no written record to work from, falls +back on what it learned in training, and for CGP that is a poor source. CGP's syntax has changed +across releases, and much of what has been published about it, including many posts on this site's +blog, shows constructs the current release no longer accepts, such as `#[cgp_context]` and +`cgp_preset!`. An agent writing from training reproduces that syntax, and it fills the gaps in what +it remembers with plausible guesses about what the macros generate. + +Giving the agent the source code does not solve this alone. CGP is implemented mostly as procedural +macros, so the source shows token-stream transformations rather than the traits and impls they +produce. Knowing that `#[cgp_component]` generates a consumer trait, a provider trait, and the +blanket impls that connect them requires mentally running the macro. Every agent that reads the +source has to repeat that reconstruction, and two agents can reconstruct it differently. + +## A written record, kept true + +The knowledge base records each of those reconstructions once, in prose, so that later agents read +the conclusion instead of deriving it again. Each document owns one subject: a construct, a +cross-cutting concept, a class of compile errors, a worked example, the internals of one macro, or a +page of this site. A document that mentions another subject links to the document that owns it +rather than explaining it a second time, so two explanations cannot drift apart. + +The record is only useful while it is true, so these rules govern every document: + +- **The source outranks every document.** When a document and the code disagree, the code is right + and the document has a defect. Agents check claims about accepted syntax, generated names, and + macro expansions against the source, the tests, and the expansion snapshots, not against memory or + an earlier draft of the document. +- **A change carries its documentation.** A change to how a construct behaves updates the matching + documents in the same change. A stale document counts as a bug in the change that made it stale. +- **Documents describe the present.** A document states how the code works now, without a history of + how it got there. The version history is recorded separately, in the `releases/` section, + including when each construct was renamed or removed, so an agent that meets old syntax can find + what replaced it. + +## One construct, five views + +A single construct is described in five places, and the rules require all five to agree. Following +`#[cgp_component]` through them shows what "kept in sync" means in practice: + +- **The implementation:** the parsing and code generation in + [`cgp-macro-core`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/types/cgp_component). +- **The tests and snapshots:** behavioral tests in the `cgp` repository, with expansion snapshots + that record the exact code the macro generates, such as + [`component_macro.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/tests/cgp-tests/tests/basic_delegation/component_macro.rs). +- **The reference document:** the knowledge base's description of the accepted syntax and the + expansion, at `cgp/reference/macros/cgp_component.md`. This site's + [`#[cgp_component]` reference page](/docs/reference/macros/cgp_component) is written from it. +- **The implementation document:** the knowledge base's account of how the macro produces that + expansion, its corner cases, and every test that covers it, at + `cgp/implementation/entrypoints/cgp_component.md`. +- **The agent skill:** the condensed explanation an assistant loads, in the skill's + [Components](/docs/ai/skills/references/components) reference. + +When the macro's output changes, the snapshot changes with it, and the reference document, the +implementation document, and the skill are updated in the same change. When the views disagree, the +source decides which one is wrong. + +## Written rules + +The rules agents follow are written down in the knowledge base and are public. A top-level +[AGENTS.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md) holds the +rules for the whole base, and each section adds its own: how a reference document is structured, how +an implementation document indexes the tests, how an error class is documented with the example that +produces it. Each code repository has an `AGENTS.md` of its own that points back to these. Agents +load the CGP skill and the relevant rules before a task and read +[summary.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/summary.md), a one-line +index of every document, to find the few documents the task needs. + +Public writing follows written rules too. The `communication-strategy/` section fixes how CGP is +presented: the voice of each kind of page, the vocabulary, how costs are stated beside benefits, and +how other projects are described. The `website/` section holds a writing guide for each kind of page +on this site and a record of each page: which documents it rests on, how it was made, and what a +revision must preserve. + +## Who directs the work + +Agents write the documents, but they do not decide what CGP is or what gets documented. The author +designs every CGP construct, writes and revises the rules above, and chooses what the knowledge base +and this site cover. The rules tell an agent to stop and ask the person directing it when a choice +has more than one defensible answer, such as an unclear intended behavior or a document whose right +home is uncertain, rather than guessing and building on the guess. + +The work also moves in separate passes rather than one prompt. A review of a document first checks +every claim against the source, and only then improves how the document reads, so polished prose +cannot hide a wrong claim. A new kind of page on this site gets a writing guide before the page is +written, stating the page's job and what must not appear on it, and the draft is checked against +that guide. + +## From the record to this site + +The agent skill and this site's pages are derived from the record rather than written fresh. The +skill condenses it. This site's reference pages are ported from the knowledge base's reference +documents, its Concepts pages from the concept documents, and its comparison pages from the +related-work documents, each rewritten for a person rather than an agent. Code shown on a page is +also added to a test crate in the website's repository when the page is written or revised, so a +snippet there that stops compiling fails a test. + +Human review varies by page. The +[AI disclaimer](/docs/ai/disclaimer#documentation-and-reference-pages) states which pages the author +reads in full and which receive spot checks. + +## Where the checks stop + +Some checks are mechanical and most are not. Expansion snapshots fail a test when a macro's output +changes, the [cargo-cgp](/docs/cargo-cgp) test fixtures fail when a diagnostic changes, and the +website's test crate fails when a snippet it holds no longer compiles. Agreement between prose and +code is enforced by agents following the rules and by the author's review, and both can miss a stale +sentence. + +A document can therefore lag behind the code or state something wrong, and so can a page derived +from it. The knowledge base is also in an early phase and under active development, so many of its +documents still need further review by the author and by agents, as +[its current state](index.md#its-current-state) describes. The aim is to improve it step by +step toward full accuracy, meaning agreement with the author's intent as well as with the source. + +The process does not make agent-written documentation correct. It makes an error checkable against a +public record and correctable at its source, after which the correction reaches the skill and the +site. If you find an error or an inconsistency in the knowledge base, file it on its +[issue tracker](https://github.com/contextgeneric/cgp-knowledge-base/issues). For an error in a page +on this site or in the code, report it on the repository it concerns. + +--- + +*An AI agent wrote this page using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/ai/knowledge-base/index.md b/docs/ai/knowledge-base/index.md new file mode 100644 index 00000000..371662fc --- /dev/null +++ b/docs/ai/knowledge-base/index.md @@ -0,0 +1,106 @@ +--- +title: 'The CGP Knowledge Base' +sidebar_label: 'Overview' +sidebar_position: 1 +description: 'The public, agent-written record that CGP''s documentation and agent skill are written from: what it holds, who it is written for, and how it relates to the source code.' +--- + +# The CGP Knowledge Base + +[Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait +implementations at compile-time. The +[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base) is a public repository of +documents that record what CGP's constructs mean, how its macros and tools are built, and how the +project presents itself. AI agents write and maintain it, and agents are its main readers. The +reference pages on this site, most of its other documentation, and the +[agent skill](/docs/ai/skills) are written from it. + +## What it is for + +The knowledge base gives an agent a written record of CGP to read, so the agent does not have to +reconstruct CGP from the macro source or recall it from training. It records the semantics of each +construct, including the syntax forms it accepts and the code each macro expands to. It also holds +the internals of the macros and of [cargo-cgp](/docs/cargo-cgp), the classes of compile error CGP +produces, worked examples, and comparisons with related ideas from other languages. + +The [agent skill](/docs/ai/skills) is the part of this record sized for everyday work: it fits in an +assistant's context and teaches it to read and write CGP code. The knowledge base is the exhaustive +record behind it, for questions the skill does not answer, such as a corner case of one macro, how a +macro is implemented, or why a diagnostic reads as it does. + +## Who reads it + +The knowledge base is written for agents, not for people learning CGP. Its documents assume the +agent skill's vocabulary, favor completeness over a gentle introduction, and record unfinished work +and known defects beside current behavior. To learn CGP, start with the +[tutorials](/docs/tutorials/hello) and the [Concepts](/docs/concepts) pages. + +You can still read it directly. It is useful when you want the complete record of a construct, when +you want to check how a page on this site was produced, or when you are deciding whether to +contribute. + +## Its current state + +The knowledge base is in an early phase and under active development. Many of its documents still +need further review, by the author and by agents, and some contain errors or inconsistencies that no +review has found yet. Read any one document as the current best record rather than a finished one. + +The aim is to improve the knowledge base step by step until it is fully accurate, meaning that it +agrees with the author's intent for CGP as well as with the source code. Finding a problem in it is +a useful contribution: file it on the knowledge base's +[issue tracker](https://github.com/contextgeneric/cgp-knowledge-base/issues), as +[Contributing to CGP with an Agent](contributing-with-an-agent.md) describes. + +## How it relates to the code + +CGP's source code is the final authority. When a document in the knowledge base disagrees with the +code, the document is wrong and is corrected. The knowledge base records what the source means, the +agent skill condenses that record, and the pages on this site are written from the record in a form +meant for people. A correction therefore starts in the source or the knowledge base and moves +outward to the skill and the site. + +## What it contains + +The knowledge base is divided into top-level sections, each with a `README.md` that catalogs its +documents: + +- **`cgp/`:** The CGP library, with a reference document for every construct, concept overviews, + guides for choosing between constructs, a catalog of compile errors, and the macros' internals. +- **`cargo-cgp/`:** The error toolchain's usage, internals, open issues, and error codes. +- **`examples/`:** Worked examples, each developing one use case, which serve as the verified source + of most code on this site. +- **`related-work/`:** Comparisons with ideas CGP resembles, such as type classes, dependency + injection, and ML modules. +- **`communication-strategy/`:** How CGP is presented in public, including the policy behind the + [AI disclaimer](/docs/ai/disclaimer). +- **`website/`:** A record of each page on this site and a guide for each kind of page. +- **`releases/`:** The version history, including when each construct was renamed or removed. +- **`projects/`:** Libraries built with CGP, such as Hypershell and cgp-serde. +- **`skills/`:** Writing skills that the knowledge base's rules ask an agent to load. + +These files at the top level orient an agent before it opens any section: + +- **[README.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/README.md):** how the + knowledge base is organized, and what an agent that only reads it needs to know. +- **[summary.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/summary.md):** every + document, with a one-line summary of each. +- **[AGENTS.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md):** the + rules for writing and maintaining the documents. +- **[sibling-projects.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/sibling-projects.md):** + the CGP repositories and where to find each one. + +## Where to go next + +Choose the page that answers your question: + +- **How can I tell whether this documentation is reliable?** Read + [How CGP's Documentation Is Written](how-cgp-is-documented.md). +- **How do I get my agent to use the knowledge base?** Read + [Using the Knowledge Base with Your Agent](using-it-with-your-agent.md). +- **How do I contribute to CGP with an agent's help?** Read + [Contributing to CGP with an Agent](contributing-with-an-agent.md). + +--- + +*An AI agent wrote this page using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/ai/knowledge-base/using-it-with-your-agent.md b/docs/ai/knowledge-base/using-it-with-your-agent.md new file mode 100644 index 00000000..4893aff8 --- /dev/null +++ b/docs/ai/knowledge-base/using-it-with-your-agent.md @@ -0,0 +1,95 @@ +--- +title: 'Using the Knowledge Base with Your Agent' +sidebar_label: 'Using It with Your Agent' +sidebar_position: 3 +description: 'Direct a coding agent to the CGP knowledge base when a question about CGP needs more than the agent skill carries: a corner case, an unfamiliar error, the implementation, or a comparison.' +--- + +# Using the Knowledge Base with Your Agent + +[Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait +implementations at compile-time. This page shows how to direct a coding agent to the [CGP knowledge +base](https://github.com/contextgeneric/cgp-knowledge-base) when you want a deeper answer than the +[agent skill](/docs/ai/skills) gives. The knowledge base is written for agents rather than people, +so the page is about directing your agent to it. It assumes you already use an agent and know how to +give it files or a repository to read. + +## When to use it + +Start with the agent skill for everyday CGP code. It teaches an agent the vocabulary, the +recommended syntax, the wiring, and how to read compile errors, and it is sized to fit in the +agent's context next to your code. Writing a component, wiring a context, or fixing a missing +dependency usually needs nothing more. + +Use the knowledge base when a question needs the complete record: + +- **A corner case:** an unusual syntax form, how a macro treats lifetimes, or an interaction between + two constructs. +- **An unfamiliar error:** a compile error whose cause the skill and + [cargo-cgp](/docs/cargo-cgp) do not make clear. +- **The implementation:** how a macro produces its expansion, for learning or for auditing the + source. +- **The generated code:** what the macros add to your own crate, which + [`cargo cgp expand`](/docs/cargo-cgp/expand) prints and the knowledge base explains. +- **A comparison:** how CGP relates to an idea from another language you already know. + +The skill already links to knowledge-base documents for details it leaves out, so an agent with the +skill may fetch some of them on its own. The steps below make that reading deliberate. + +## Give the agent access + +An agent can read the knowledge base from a local clone or fetch files from GitHub. A clone is +faster for the agent and lets it search across documents: + +```sh +git clone https://github.com/contextgeneric/cgp-knowledge-base.git +``` + +To audit CGP's source, also clone the [`cgp` repository](https://github.com/contextgeneric/cgp) into +the same parent directory. The knowledge base refers to its sibling repositories by that layout, and +[sibling-projects.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/sibling-projects.md) +lists them. + +## Tell it what to read + +An agent makes the best use of the knowledge base when you tell it where to start and how to treat +the rules it finds there. Include three instructions in your prompt: + +1. **Load the CGP skill** so the agent knows the vocabulary the documents use. If your agent does + not load skills, attach the skill's + [SKILL.md](https://raw.githubusercontent.com/contextgeneric/cgp-skills/refs/heads/main/cgp/SKILL.md) + instead, as the [skill page](/docs/ai/skills) describes. +2. **Read the README first.** The + [README](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/README.md) explains the + organization and has a section for agents that only read the base. +3. **Read the section that owns the question.** Each top-level directory has a `README.md` that + catalogs its documents. Name the section yourself when you know it, so the agent does not need + the full index: `cgp/reference/` for a construct, `cgp/errors/` for a compile error, + `cgp/implementation/` for how a macro is built, and `related-work/` for a comparison. + +The `AGENTS.md` files describe how the knowledge base's own documents are written and maintained. +They bind an agent that edits the base, not one that only reads it, and the README tells the agent +so. + +Ask the agent to read selectively, because reading costs context. The index of every document, +[summary.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/summary.md), is roughly +a hundred kilobytes, or tens of thousands of tokens. Have the agent open it only when it cannot tell +which section owns the question. + +## Review the answer + +Review the agent's answer before relying on it. The knowledge base gives an agent a checked record +to work from, but the agent can still misread a document, and a document can lag behind the code. +The knowledge base is also in an early phase, and many of its documents still need further review, +as [its current state](index.md#its-current-state) describes. +Ask the agent to name the documents it used, so you can check each claim at its source. + +When an answer disagrees with the code, the code is right. If the disagreement comes from the +document rather than the agent's reading of it, file it on the knowledge base's +[issue tracker](https://github.com/contextgeneric/cgp-knowledge-base/issues), together with the +prompt that surfaced it, so the document can be corrected. + +--- + +*An AI agent wrote this page using the CGP knowledge base. See +[How AI is used in this project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/ai/skills/index.md b/docs/ai/skills/index.md index 4b136c12..c6e42236 100644 --- a/docs/ai/skills/index.md +++ b/docs/ai/skills/index.md @@ -44,6 +44,10 @@ for learning CGP. The skill is written for an assistant that needs dense rules a for a specific task. Read it when you want that detail or want to see the instructions your assistant receives. +When a question needs more than the skill carries, such as a macro's corner cases or how it is +implemented, point your assistant at the knowledge base the skill is written from. [Using the +Knowledge Base with Your Agent](/docs/ai/knowledge-base/using-it-with-your-agent) shows how. + ## What is published here The skill pages on this site are pinned to a particular repository revision. The repository may diff --git a/docs/contribute.md b/docs/contribute.md index d5a798de..de48c2a5 100644 --- a/docs/contribute.md +++ b/docs/contribute.md @@ -24,6 +24,19 @@ When that happens, it would become possible for CGP to be used by anyone, withou If you _care_ about modularity and would like to contribute, the best way is to start publishing context-generic components, and help build up an ecosystem that benefits the rest of developers. +## Contribute Code or Documentation + +To change CGP itself, with or without a coding agent, start from +[Contributing to CGP with an Agent](/docs/ai/knowledge-base/contributing-with-an-agent). It explains +how the repositories are set up, the rules each one follows, and the policy for AI-assisted +contributions. + +Reporting problems is also a contribution. The CGP knowledge base, which the documentation is +written from, is in an early phase, and an error or inconsistency you find in it is worth filing as +an issue; [Report problems in the knowledge +base](/docs/ai/knowledge-base/contributing-with-an-agent#report-problems-in-the-knowledge-base) +explains how. + ## Spread on Social Media Help raise awareness of CGP by sharing it on social media. Follow our official BlueSky account [@contextgeneric.dev](https://bsky.app/profile/contextgeneric.dev) to stay updated on CGP’s development and latest news. From 028541c2ecd9e2494b38010ca83c394424bb6ebe Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 15:34:24 +0200 Subject: [PATCH 166/516] Add reference pages for the `Struct!` and `Enum!` shape macros Each page follows the layered descent: what a shape is and why to name one, both body forms with the delimiter rule, worked examples, when to reach for the macro instead of `Product!`/`Sum!` or the derives, the expansion and its newtype and empty-body rules, the formal grammar, and the common mistakes. The macro index, the reference index, the `Product!`, `Sum!`, `HasFields`, and `#[derive(HasFields)]` pages, and the `cargo cgp expand` page now point at the shapes, and `Path!` and `#[cgp_provider]` move down the sidebar so the list and shape macros sit together. The example-code mirrors compile every snippet on the two pages, and a compile-fail fixture pins the rejection of a value written as a field type. They need the `cgp` revision that adds the macros. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/expand.md | 4 +- docs/reference/derives/derive_has_fields.md | 2 + docs/reference/index.md | 4 +- docs/reference/macros/cgp_provider.md | 2 +- docs/reference/macros/enum.md | 190 ++++++++++++++ docs/reference/macros/index.md | 4 +- docs/reference/macros/path.md | 2 +- docs/reference/macros/product.md | 4 + docs/reference/macros/struct.md | 245 ++++++++++++++++++ docs/reference/macros/sum.md | 4 + docs/reference/traits/shape/has_fields.md | 2 + .../macros/struct_common_mistakes_value.rs | 8 + .../struct_common_mistakes_value.stderr | 5 + example-code/tests/reference/macros/enum.rs | 96 +++++++ example-code/tests/reference/macros/mod.rs | 2 + example-code/tests/reference/macros/struct.rs | 180 +++++++++++++ 16 files changed, 749 insertions(+), 5 deletions(-) create mode 100644 docs/reference/macros/enum.md create mode 100644 docs/reference/macros/struct.md create mode 100644 example-code/tests/compile_fail/reference/macros/struct_common_mistakes_value.rs create mode 100644 example-code/tests/compile_fail/reference/macros/struct_common_mistakes_value.stderr create mode 100644 example-code/tests/reference/macros/enum.rs create mode 100644 example-code/tests/reference/macros/struct.rs diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 233dd1ca..4c461f5b 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -225,7 +225,9 @@ impl ::cgp::macro_prelude::HasField<::cgp::macro_prelude::Symbol<6, `cargo cgp expand` writes it back as `Symbol!("height")`, which is what you wrote. It does the same for the rest of CGP's type-level vocabulary: a list of handlers reads `Product![StepOne, StepTwo]` rather -than a chain of `Cons` cells, and a namespace key reads `Path!(@app.GreeterComponent)`. +than a chain of `Cons` cells, a derived field list reads +[`Struct! { width: f64, height: f64 }`](/docs/reference/macros/struct), and a namespace key reads +`Path!(@app.GreeterComponent)`. `--item` is the other difference. It selects Rust items rather than filtering text: asking for a trait gives every impl of that trait, wherever it sits in the crate, which is the shape a question about CGP diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 68f8540f..28c35453 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -317,6 +317,8 @@ These references cover the related derives, generated traits, and supporting typ incremental machinery. - [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md) — the list types a struct and an enum shape are built from. +- [`Struct!`](../macros/struct.md) and [`Enum!`](../macros/enum.md) — write the shape this derive + generates as the body of a struct or enum declaration, for code that names it. - [`Field`](../types/field.md) — one entry: a value paired with its type-level name. - [`Symbol!`](../macros/symbol.md) and [`Index`](../types/index_type.md) — the tags that name an entry. - [Type-level lists](../types/index.md) — the `Cons`/`Nil` and `Either`/`Void` chains the diff --git a/docs/reference/index.md b/docs/reference/index.md index bce98821..2c57859a 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -213,7 +213,9 @@ generated type or an error names one you did not write. [`PhantomData`](./types/ the one to start with: it is what lets a provider or a tag carry a type without storing a value of it, and it underlies most of the rest. You write the lists through sugar, with [`Symbol!`](./macros/symbol.md) for a field name, [`Product!`](./macros/product.md) for a record -list, [`Sum!`](./macros/sum.md) for its dual, and [`Path!`](./macros/path.md) for a route. You only +list, [`Sum!`](./macros/sum.md) for its dual, and [`Path!`](./macros/path.md) for a route, and you +name a whole struct or enum shape with [`Struct!`](./macros/struct.md) or +[`Enum!`](./macros/enum.md), written as the body of its declaration. You only need to recognize the [lists](./types/index.md) they expand into, [`Cons`](./types/cons.md) and [`Nil`](./types/nil.md), [`Either`](./types/either.md) and [`Void`](./types/void.md), [`Chars`](./types/chars.md), and [`PathCons`](./types/path_cons.md), when one shows up in an error. diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 5e0e61a9..83c814f7 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -1,7 +1,7 @@ --- title: '#[cgp_provider] and #[cgp_new_provider]' sidebar_label: '#[cgp_provider] & #[cgp_new_provider]' -sidebar_position: 20 +sidebar_position: 22 description: 'Implement a provider trait directly, in the inside-out shape the ergonomic macros desugar to, with or without declaring the provider struct.' --- diff --git a/docs/reference/macros/enum.md b/docs/reference/macros/enum.md new file mode 100644 index 00000000..73c47e70 --- /dev/null +++ b/docs/reference/macros/enum.md @@ -0,0 +1,190 @@ +--- +title: 'Enum! — enum shapes' +sidebar_label: 'Enum!' +sidebar_position: 20 +description: 'The type-level shape of an enum, written as the body of an enum declaration.' +--- + +# `Enum!` + +The type-level shape of an enum, written as the body of an enum declaration. + +## Overview + +Generic code over enums works on an enum's **shape**: one type that lists every variant by name, +which [`#[derive(HasFields)]`](../derives/derive_has_fields.md) generates for an enum as its `Fields` +type. Written out by hand, that shape is a [`Sum!`](./sum.md) of [`Field`](../types/field.md) +entries that repeats each variant name as a +[type-level string](/docs/reference/glossary#type-level-string): + +```rust +Sum![Field, Field] +``` + +`Enum!` writes the same type as the enum body it describes: + +```rust +Enum! { Circle(f64), Square(f64) } +``` + +The two are the identical type, and it is exactly the `Fields` the derive gives an enum with that +body. Reach for `Enum!` wherever code *names* a variant set's shape rather than deriving it, such as +a [trait bound](https://doc.rust-lang.org/book/ch10-02-traits.html) on `FromFields`. It is also the +form [`cargo cgp`](/docs/cargo-cgp) prints a variant list in, so a list read in the tool's output can +be copied back into code. + +## Usage + +The body is the inside of an enum declaration, and each variant takes one of the three Rust variant +shapes: + +```rust +Enum! { + Empty, // a unit variant + Circle(f64), // positional fields + Rectangle { width: f64, height: f64 }, // named fields +} +``` + +Inside the body, a variant's brackets keep their Rust meaning: parentheses hold positional fields, +and braces hold named fields. The brackets around the whole `Enum!` invocation do not matter. A +variant name may be a raw identifier, tagged without the `r#`, and the list accepts a trailing comma. +An empty body, `Enum! {}`, is allowed. + +`Enum!` builds a type, never a value. A value of the shape selects its variant with `Either::Left` +and `Either::Right`, wrapping the payload with `Field::from`, or comes from an existing enum through +`to_fields()`. + +## Examples + +A function bounded on an enum's shape converts a value built in that shape into the enum. Here +`Value` derives the whole variant family, and `from_shape` works for any enum with the same variants: + +```rust +use cgp::prelude::*; + +#[derive(Debug, PartialEq, CgpData)] +pub enum Value { + Int(u64), + Text(String), +} + +pub fn from_shape(fields: Enum! { Int(u64), Text(String) }) -> T +where + T: FromFields, +{ + T::from_fields(fields) +} + +assert_eq!(from_shape::(Either::Left(Field::from(7))), Value::Int(7)); +assert_eq!( + from_shape::(Either::Right(Either::Left(Field::from("seven".to_owned())))), + Value::Text("seven".to_owned()), +); +``` + +`Either::Left` selects the first variant and each `Either::Right` moves one variant further, and the +variant's name comes from the `Enum!` type the argument is expected to have. + +## When to use it + +**Write `Enum!` whenever you would otherwise spell a variant list by hand.** A +`Sum![Field, …]` written out is longer and hides the fact that it describes an +enum. + +- **Let [`#[derive(HasFields)]`](../derives/derive_has_fields.md) or + [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) produce an enum's shape**, and use `Enum!` + only where code has to name one. Restating an enum you own as an `Enum!` next to it is a second copy + that can drift. +- **Use [`Struct!`](./struct.md) for a record's shape**, where every field is present at once. +- **Use [`Sum!`](./sum.md) for a choice among types that are not named variants.** +- **Use a plain `enum` and `match` when the variant set is closed and consumed in one place.** A shape + is worth naming when independent code handles variants it did not define. + +## Under the hood + +`Enum!` expands exactly as `#[derive(HasFields)]` expands the same body, because the macro runs the +derive's own code. Each variant becomes a `Field` entry keyed by its name, and the entries are chained +into a sum that ends in `Void`: + +```rust +// before +Enum! { Circle(f64), Square(f64) } + +// after +Either, Either, Void>> +``` + +A variant's payload is its fields, encoded by the [`Struct!`](./struct.md#under-the-hood) rules: + +| Variant | Payload | +| --- | --- | +| `Empty`, `Empty()`, or `Empty {}` | `Nil` | +| `Circle(f64)` | `f64`, the bare type | +| `Pair(u32, u32)` | `Struct!(u32, u32)`, a list keyed by position | +| `Rect { width: f64, height: f64 }` | `Struct! { width: f64, height: f64 }`, a list keyed by name | + +So several spellings are the same type: `V`, `V()`, `V {}`, and `V(Nil)` are one variant, and +`V { a: u32 }` is `V(Struct! { a: u32 })`. `cargo cgp` relies on this when it prints a variant list, +choosing the shortest spelling. An empty body is `Void`, the shape of an enum with no variants. + +## Formal grammar + +The body is a list of variants, each a name with an optional field list, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +EnumInput -> ( Variant ( `,` Variant )* `,`? )? + +Variant -> IDENTIFIER ( `(` TupleFields `)` | `{` NamedFields `}` )? +``` + +`IDENTIFIER` includes raw identifiers. `TupleFields` and `NamedFields` are the +[`Struct!` productions](./struct.md#formal-grammar), so a variant's fields follow the rules of a +`Struct!` body of the same form. + +## Common Mistakes + +**The variant derives need each variant to hold exactly one positional field.** `Enum!` describes any +variant, as `#[derive(HasFields)]` does, but [`#[derive(CgpData)]`](../derives/derive_cgp_data.md), +`CgpVariant`, `ExtractField`, and `FromVariant` reject a unit, multi-field, or named-field variant. A +shape with such variants therefore has no generic constructor or extractor. + +**An enum body's other parts are rejected.** An attribute on a variant (such as `#[default]` or a doc +comment), `pub` on a variant, a discriminant such as `= 1`, a variant name given twice, and any field +`Struct!` would reject each fail with their own error. + +**A variant list tagged by position has no `Enum!` spelling.** A variant needs a name, so a sum whose +entries are keyed by `Index` is written with `Sum!`. + +**Clippy's `type_complexity` lint, and an imported abstract type inside the body,** behave as they do +for [`Struct!`](./struct.md#common-mistakes). + +## Related constructs + +- [`Struct!`](./struct.md) — the struct counterpart, whose rules encode each variant's payload. +- [`Sum!`](./sum.md) — the sum `Enum!` expands to. +- [`Field`](../types/field.md) and [`Symbol!`](./symbol.md) — the entry and the tag each variant + becomes. +- [`HasFields`](../traits/shape/has_fields.md) — the trait whose `Fields` an `Enum!` names. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — the derive whose encoding `Enum!` runs. +- [`FromVariant`](../traits/variant/from_variant.md) and + [`ExtractField`](../traits/variant/extract_field.md) — constructing and taking apart a variant + generically. + +The ideas behind it: + +- [Extensible variants](/docs/concepts/extensible-variants) — the variant representation a shape + describes. + +## Source + +- Entry point: [`enum_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/enum_type.rs) +- Parsing the body: [`types/shape/enum_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/shape/enum_type.rs) +- The encoding shared with the derive: [`derive_has_fields/sum.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields/sum.rs) + +--- + +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md index d33c4fbe..8bc82a28 100644 --- a/docs/reference/macros/index.md +++ b/docs/reference/macros/index.md @@ -62,7 +62,9 @@ presets without a separate construct for them. [`Product!`](./product.md) and its value-level twin `product!` build a type-level list for a struct's fields or a handler pipeline's steps, [`Sum!`](./sum.md) builds the dual list for an enum's variants, and [`Path!`](./path.md) builds the routing list that namespaces and redirected lookups resolve -against. You write two of them by hand in ordinary code, `Symbol!` in a `UseField` wiring entry and +against. [`Struct!`](./struct.md) and [`Enum!`](./enum.md) write a whole struct or enum shape as the +body of its declaration, expanding to the same `Product!` or `Sum!` of named fields that +`#[derive(HasFields)]` generates. You write two of them by hand in ordinary code, `Symbol!` in a `UseField` wiring entry and `Product!` in a handler pipeline, and the derives, the ergonomic macros above, and the `open` statement inside `delegate_components!` generate the rest. The skill all four ask for is reading one back out of a compiler error, since a diagnostic prints the raw list each expands to: diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index a790ade9..6fe3e919 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -1,7 +1,7 @@ --- title: 'Path! — type-level paths' sidebar_label: 'Path!' -sidebar_position: 19 +sidebar_position: 21 description: 'A type-level path, used by CGP namespaces and by component lookups that are redirected along one.' --- diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 094bcdf0..563a2b97 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -114,6 +114,9 @@ a provider list. Everywhere else it is generated for you. [`Sum!`](./sum.md)'s list. - **Use [`#[derive(HasFields)]`](../derives/derive_has_fields.md) for a struct's shape** rather than declaring the list yourself. Writing it by hand means restating the struct, and the two will disagree eventually. +- **Use [`Struct!`](./struct.md) where code has to name a list of named fields**, in a bound or an impl: + `Struct! { name: String, age: u8 }` is this same `Product!` of `Field` entries, written as a struct + body. - **Use a tuple when nothing generic consumes it.** A `Product!` is worth using only where code recurses over the list; for a fixed group of values passed between known functions, a tuple or a struct is clearer and needs no machinery. @@ -204,6 +207,7 @@ the order *is* the execution order. ## Related constructs - [`Sum!`](./sum.md) — the dual, for a choice among types rather than a collection of them. +- [`Struct!`](./struct.md) — writes a `Product!` of named or positional `Field` entries as a struct body. - [Type-level lists](../types/index.md) — the `Cons`/`Nil` types the expansion builds. - [`Field`](../types/field.md) — what the entries usually are, pairing a name with a type. - [`Symbol!`](./symbol.md) — the name half of a `Field` entry. diff --git a/docs/reference/macros/struct.md b/docs/reference/macros/struct.md new file mode 100644 index 00000000..a515080d --- /dev/null +++ b/docs/reference/macros/struct.md @@ -0,0 +1,245 @@ +--- +title: 'Struct! — struct shapes' +sidebar_label: 'Struct!' +sidebar_position: 19 +description: 'The type-level shape of a struct, written as the body of a struct declaration.' +--- + +# `Struct!` + +The type-level shape of a struct, written as the body of a struct declaration. + +## Overview + +Generic code over records works on a struct's **shape**: one type that lists every field by name, +which [`#[derive(HasFields)]`](../derives/derive_has_fields.md) generates for a struct as its +`Fields` type. Written out by hand, that shape is a [`Product!`](./product.md) of +[`Field`](../types/field.md) entries that repeats each field name as a +[type-level string](/docs/reference/glossary#type-level-string): + +```rust +Product![Field, Field] +``` + +`Struct!` writes the same type as the struct body it describes: + +```rust +Struct! { name: String, age: u8 } +``` + +The two are the identical type, and it is exactly the `Fields` the derive gives a struct with that +body. Reach for `Struct!` wherever code *names* a shape rather than deriving it: a +[trait bound](https://doc.rust-lang.org/book/ch10-02-traits.html) on `HasFields`, a trait +implemented for a shape, or a wiring entry. It is also the form +[`cargo cgp expand`](/docs/cargo-cgp) and `cargo cgp check` print a shape in, so a shape read in +the tool's output can be copied back into code. + +## Usage + +The body is the inside of a struct declaration, in either of its two forms: + +```rust +Struct! { name: String, age: u8 } // like `struct S { name: String, age: u8 }` +Struct!(u64, String) // like `struct S(u64, String);` +Struct! {} // an empty body +``` + +**The form comes from the entries, not from the brackets.** A procedural macro never sees the +delimiter it was invoked with, so `Struct!(a: u8)` is the named form and `Struct! { u8, bool }` is +the tuple form. Write braces for named fields and parentheses for a tuple body, by convention. An +entry is a named field when it starts with a name followed by a single `:`, so a path type such as +`core::marker::PhantomData` is a positional field. + +Both forms accept a trailing comma. A field name may be a raw identifier, and its tag is the name +without the `r#`: `Struct! { r#type: u8 }` tags its field `"type"`, as the derive does. A field +type is any Rust type, including generic parameters, references with +[lifetimes](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html), and +[associated-type](https://doc.rust-lang.org/reference/items/associated-items.html) projections. + +`Struct!` builds a type, never a value. A value of the shape comes from an existing struct through +`to_fields()`, or is built with [`product!`](./product.md), wrapping each field value with `.into()`. + +## Examples + +A function generic over every struct with a given shape bounds the shape directly. Here `rebuild` +turns a value of the shape into any type whose `Fields` it is: + +```rust +use cgp::prelude::*; + +#[derive(Debug, PartialEq, HasFields)] +pub struct Person { + pub name: String, + pub age: u8, +} + +pub fn rebuild(fields: Struct! { name: String, age: u8 }) -> T +where + T: FromFields, +{ + T::from_fields(fields) +} + +let person: Person = rebuild(product!["Carol".to_owned().into(), 25u8.into()]); +assert_eq!(person.age, 25); +``` + +Each `.into()` wraps one value in its `Field`, and the field's name comes from the `Struct!` type +the argument is expected to have. + +A shape is an ordinary type, so a trait can be implemented for it, in either form: + +```rust +pub trait Describe { + fn describe() -> &'static str; +} + +impl Describe for Struct! { name: String, age: u8 } { + fn describe() -> &'static str { + "a person's shape" + } +} + +impl Describe for Struct!(u8, u16) { + fn describe() -> &'static str { + "a pair's shape" + } +} +``` + +A shape can also key an `open` dispatch entry in [`delegate_components!`](./delegate_components.md), +choosing a provider by the structure of a record: + +```rust +delegate_components! { + App { + open ShapeDescriberComponent; + + @ShapeDescriberComponent.Struct! { x: f64, y: f64 }: DescribePoint, + @ShapeDescriberComponent.Struct!(u8, u16): DescribePair, + } +} +``` + +## When to use it + +**Write `Struct!` whenever you would otherwise spell a field list by hand.** A +`Product![Field, …]` written out is longer, repeats every name as a string, +and hides the fact that it describes a record. + +- **Let [`#[derive(HasFields)]`](../derives/derive_has_fields.md) produce a struct's shape**, and use + `Struct!` only where code has to name a shape: in a bound, an impl, or a wiring entry. Restating a + struct you own as a `Struct!` next to it is a second copy that can drift. +- **Use [`Enum!`](./enum.md) for an enum's shape**, a choice among variants rather than a record. +- **Use [`Product!`](./product.md) for a list that is not a set of named fields**, such as a handler + pipeline, or for the one field list `Struct!` cannot spell, described under + [Common Mistakes](#common-mistakes). +- **Use a plain struct when no generic code walks the fields.** A shape is worth naming when + independent code builds, reads, or converts records by their field names. + +## Under the hood + +`Struct!` expands exactly as `#[derive(HasFields)]` expands the same body, because the macro runs +the derive's own code. Named fields become `Field` entries keyed by `Symbol!`, in declaration +order: + +```rust +// before +Struct! { name: String, age: u8 } + +// after +Cons, Cons, Nil>> +``` + +Positional fields become `Field` entries keyed by [`Index`](../types/index_type.md): + +```rust +// before +Struct!(u64, String) + +// after +Cons, u64>, Cons, String>, Nil>> +``` + +Two bodies follow special rules, both taken from the derive. A body with **exactly one positional +field** is that field's type, with no `Field` and no list, so `Struct!(u64)` is `u64`: the same +newtype rule that makes the shape of `struct Wrap(u64);` plain `u64`. An **empty body** is `Nil`, +the shape of a unit struct. A single *named* field is not unwrapped: `Struct! { value: u64 }` is the +one-element list `Cons, Nil>`. + +Every CGP name in the expansion is written with its full path, so the macro works in a module that +imports nothing else from `cgp`. + +## Formal grammar + +The body is either a list of named fields or a list of types, in the Rust Reference's +[notation](https://doc.rust-lang.org/reference/notation.html): + +```ebnf +StructInput -> NamedFields | TupleFields + +NamedFields -> ( NamedField ( `,` NamedField )* `,`? )? + +NamedField -> IDENTIFIER `:` Type + +TupleFields -> ( Type ( `,` Type )* `,`? )? +``` + +`IDENTIFIER` includes raw identifiers and excludes `_`, and `Type` is the Rust grammar's type +production. The empty body matches both alternatives, and both give the same type. + +## Common Mistakes + +**A one-element positional list has no `Struct!` spelling.** `Struct!(T)` is `T`, by the newtype +rule, so the list holding a single `Field, T>` is written +`Product![Field, T>]`. A trailing comma does not help: `Struct!(T,)` is `T` as well, unlike +the tuple type `(T,)`. + +**The shape is a type, not a value.** A literal where a type belongs is rejected: + +```text +error: expected a type: a type-level shape lists field types, not values +``` + +Build a value with `product!` and `.into()`, or with `to_fields()`. + +**A struct body's other parts are rejected.** Attributes (doc comments included), visibility such as +`pub`, a field named `_`, a field name given twice, and a body that mixes named and positional entries +each fail with their own error, since a shape has no use for them. + +**Clippy's `type_complexity` lint can fire on an ordinary shape.** Clippy measures the expanded type, +in which every field name is a nested type-level string, so a shape nested in a larger type in a +signature can cross the lint's threshold. A `type` alias for the shape, or +`#[allow(clippy::type_complexity)]`, silences it. + +**An imported abstract type is not rewritten inside the body.** In an item that imports `Error` with +[`#[use_type(HasErrorType.Error)]`](../attributes/use_type.md), a bare `Error` written inside +`Struct! { … }` is left as it is and fails as an unknown type. Write +`::Error` inside the macro instead. + +## Related constructs + +- [`Enum!`](./enum.md) — the enum counterpart, whose variant payloads follow the `Struct!` rules. +- [`Product!`](./product.md) — the list `Struct!` expands to. +- [`Field`](../types/field.md) — the entry each field becomes. +- [`Symbol!`](./symbol.md) and [`Index`](../types/index_type.md) — the name and position tags. +- [`HasFields`](../traits/shape/has_fields.md) — the trait whose `Fields` a `Struct!` names. +- [`#[derive(HasFields)]`](../derives/derive_has_fields.md) — the derive whose encoding `Struct!` + runs. + +The ideas behind it: + +- [Extensible records](/docs/concepts/extensible-records) — the record representation a shape + describes. + +## Source + +- Entry point: [`struct_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-lib/src/struct_type.rs) +- Parsing the body: [`types/shape/struct_type.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/shape/struct_type.rs) and [`functions/shape/`](https://github.com/contextgeneric/cgp/tree/main/crates/macros/cgp-macro-core/src/functions/shape) +- The encoding shared with the derive: [`derive_has_fields/product.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/macros/cgp-macro-core/src/types/cgp_data/derive_has_fields/product.rs) + +--- + +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index b883a3fb..3e1206d8 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -105,6 +105,9 @@ use. - **Use [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or [`#[derive(HasFields)]`](../derives/derive_has_fields.md) on the enum**, which generates the list from the variants you already declared. Writing it out means restating the enum, and the two will drift. +- **Use [`Enum!`](./enum.md) where code has to name a variant list**, in a bound or an impl: + `Enum! { Circle(f64), Rectangle { width: f64, height: f64 } }` is the list above, written as an enum + body. - **Never hand-write the list.** `Sum!` expands to `Either>`, and writing it out is longer and identical in meaning. - **Use [`Product!`](./product.md) for a collection rather than a choice.** They are duals: every element @@ -189,6 +192,7 @@ over its payload as one value, so the payload has to be a single type. ## Related constructs - [`Product!`](./product.md) — the dual, for a collection rather than a choice. +- [`Enum!`](./enum.md) — writes a `Sum!` of named variants as an enum body. - [Type-level lists](../types/index.md) — the `Either`/`Void` types the expansion builds. - [`Field`](../types/field.md) — what the branches usually are, pairing a variant name with its payload. - [`Symbol!`](./symbol.md) — the name half of a branch. diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index a6b8979f..f2a009ea 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -220,6 +220,8 @@ lists it with the other reserved names. - [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md): bundles this with the builder and extractor. - [`Product!`](../../macros/product.md) and [`Sum!`](../../macros/sum.md): the list types a shape is built from. +- [`Struct!`](../../macros/struct.md) and [`Enum!`](../../macros/enum.md): name a shape as the body of a + struct or enum declaration, as in `HasFields`. - [`Field`](../../types/field.md): one entry: a value paired with its type-level name. - [Type-level lists](../../types/index.md): the `Cons`/`Nil` and `Either`/`Void` chains underneath. diff --git a/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_value.rs b/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_value.rs new file mode 100644 index 00000000..1c9f3d4c --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_value.rs @@ -0,0 +1,8 @@ +// From `docs/reference/macros/struct.md`, *Common Mistakes*: a value written where `Struct!` +// expects a field type. + +use cgp::prelude::*; + +type Shape = Struct! { a: 1 }; + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_value.stderr b/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_value.stderr new file mode 100644 index 00000000..8e8bc5dd --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_value.stderr @@ -0,0 +1,5 @@ +error: expected a type: a type-level shape lists field types, not values + --> tests/compile_fail/reference/macros/struct_common_mistakes_value.rs:6:27 + | +6 | type Shape = Struct! { a: 1 }; + | ^ diff --git a/example-code/tests/reference/macros/enum.rs b/example-code/tests/reference/macros/enum.rs new file mode 100644 index 00000000..66dc3502 --- /dev/null +++ b/example-code/tests/reference/macros/enum.rs @@ -0,0 +1,96 @@ +//! Code from `docs/reference/macros/enum.md` — *`Enum!`*. +//! +//! Type equalities are checked by assigning one `PhantomData` to a binding typed with the other. + +/// ## Overview +pub mod overview { + use cgp::prelude::*; + + #[test] + fn the_shape_is_the_hand_written_variant_list() { + let _: PhantomData = + PhantomData::, Field]>; + } +} + +/// ## Usage +pub mod usage { + use cgp::prelude::*; + + #[derive(HasFields)] + pub enum Shape { + Empty, + Circle(f64), + Rectangle { width: f64, height: f64 }, + } + + #[test] + fn each_variant_shape_matches_the_derive() { + let _: PhantomData< + Enum! { + Empty, + Circle(f64), + Rectangle { width: f64, height: f64 }, + }, + > = PhantomData::<::Fields>; + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::]>; + } +} + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Debug, PartialEq, CgpData)] + pub enum Value { + Int(u64), + Text(String), + } + + pub fn from_shape(fields: Enum! { Int(u64), Text(String) }) -> T + where + T: FromFields, + { + T::from_fields(fields) + } + + #[test] + fn a_shape_value_converts_into_the_enum() { + assert_eq!(from_shape::(Either::Left(Field::from(7))), Value::Int(7)); + assert_eq!( + from_shape::(Either::Right(Either::Left(Field::from("seven".to_owned())))), + Value::Text("seven".to_owned()), + ); + } +} + +/// ## Under the hood +pub mod under_the_hood { + use cgp::prelude::*; + + #[test] + fn the_expansion() { + let _: PhantomData = PhantomData::< + Either, Either, Void>>, + >; + } + + #[test] + fn the_payload_table() { + let _: PhantomData = PhantomData::]>; + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::]>; + let _: PhantomData = + PhantomData::]>; + let _: PhantomData = + PhantomData::]>; + } + + #[test] + fn equivalent_spellings() { + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::; + } +} diff --git a/example-code/tests/reference/macros/mod.rs b/example-code/tests/reference/macros/mod.rs index 09f9faef..a620e297 100644 --- a/example-code/tests/reference/macros/mod.rs +++ b/example-code/tests/reference/macros/mod.rs @@ -16,7 +16,9 @@ pub mod cgp_type; pub mod check_components; pub mod delegate_and_check_components; pub mod delegate_components; +pub mod r#enum; pub mod path; pub mod product; +pub mod r#struct; pub mod sum; pub mod symbol; diff --git a/example-code/tests/reference/macros/struct.rs b/example-code/tests/reference/macros/struct.rs new file mode 100644 index 00000000..2fbe00f5 --- /dev/null +++ b/example-code/tests/reference/macros/struct.rs @@ -0,0 +1,180 @@ +//! Code from `docs/reference/macros/struct.md` — *`Struct!`*. +//! +//! The snippet the page rejects lives under `tests/compile_fail/reference/macros/`. Type +//! equalities are checked by assigning one `PhantomData` to a binding typed with the other. + +/// ## Overview +pub mod overview { + use cgp::prelude::*; + + #[test] + fn the_shape_is_the_hand_written_field_list() { + let _: PhantomData = + PhantomData::, Field]>; + } +} + +/// ## Usage +pub mod usage { + use cgp::prelude::*; + + #[test] + fn the_form_comes_from_the_entries() { + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::; + let _: PhantomData, u8)> = + PhantomData::, PhantomData>, Field, u8>]>; + } + + #[test] + fn trailing_commas_and_raw_names() { + let _: PhantomData = PhantomData::; + let _: PhantomData = + PhantomData::]>; + let _: PhantomData = PhantomData::; + } + + #[derive(Debug, PartialEq, HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + #[test] + fn a_value_comes_from_to_fields_or_product() { + let from_struct: Struct! { name: String, age: u8 } = Person { + name: "Ada".to_owned(), + age: 36, + } + .to_fields(); + let built: Struct! { name: String, age: u8 } = + product!["Ada".to_owned().into(), 36u8.into()]; + assert_eq!(from_struct, built); + } +} + +/// ## Examples +pub mod examples { + use cgp::prelude::*; + + #[derive(Debug, PartialEq, HasFields)] + pub struct Person { + pub name: String, + pub age: u8, + } + + pub fn rebuild(fields: Struct! { name: String, age: u8 }) -> T + where + T: FromFields, + { + T::from_fields(fields) + } + + #[test] + fn rebuild_turns_a_shape_into_the_struct() { + let person: Person = rebuild(product!["Carol".to_owned().into(), 25u8.into()]); + assert_eq!(person.age, 25); + } + + pub trait Describe { + fn describe() -> &'static str; + } + + impl Describe for Struct! { name: String, age: u8 } { + fn describe() -> &'static str { + "a person's shape" + } + } + + impl Describe for Struct!(u8, u16) { + fn describe() -> &'static str { + "a pair's shape" + } + } + + #[test] + fn a_trait_is_implemented_for_a_shape() { + assert_eq!(<::Fields as Describe>::describe(), "a person's shape"); + assert_eq!(::describe(), "a pair's shape"); + } + + // The page elides the component and providers behind the `open` entries. + #[cgp_component(ShapeDescriber)] + pub trait CanDescribeShape { + fn describe_shape(&self) -> &'static str; + } + + #[cgp_impl(new DescribePoint)] + impl ShapeDescriber { + fn describe_shape(&self) -> &'static str { + "point" + } + } + + #[cgp_impl(new DescribePair)] + impl ShapeDescriber { + fn describe_shape(&self) -> &'static str { + "pair" + } + } + + pub struct App; + + delegate_components! { + App { + open ShapeDescriberComponent; + + @ShapeDescriberComponent.Struct! { x: f64, y: f64 }: DescribePoint, + @ShapeDescriberComponent.Struct!(u8, u16): DescribePair, + } + } + + #[test] + fn a_shape_keys_an_open_entry() { + assert_eq!(CanDescribeShape::::describe_shape(&App), "point"); + assert_eq!(CanDescribeShape::::describe_shape(&App), "pair"); + } +} + +/// ## Under the hood +pub mod under_the_hood { + use cgp::prelude::*; + + #[test] + fn named_and_positional_expansions() { + let _: PhantomData = PhantomData::< + Cons, Cons, Nil>>, + >; + let _: PhantomData = + PhantomData::, u64>, Cons, String>, Nil>>>; + } + + #[test] + fn the_newtype_and_empty_rules() { + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::; + let _: PhantomData = + PhantomData::, Nil>>; + } + + mod without_imports { + pub type Point = cgp::prelude::Struct! { x: f64, y: f64 }; + } + + #[test] + fn the_expansion_needs_no_imports() { + let _: PhantomData = PhantomData::; + } +} + +/// ## Common Mistakes +pub mod common_mistakes { + use cgp::prelude::*; + + #[test] + fn a_one_element_positional_list_is_written_with_product() { + let _: PhantomData = PhantomData::; + let _: PhantomData, u64>]> = + PhantomData::, u64>, Nil>>; + } +} From c481284bad39f44a1264db53ddcf7dde52467359 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 15:37:14 +0200 Subject: [PATCH 167/516] Link the `Field` and `Index` pages to the shape macros Co-Authored-By: Claude Opus 5.5 --- docs/reference/types/field.md | 2 ++ docs/reference/types/index_type.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index c18651c5..7a97a913 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -171,6 +171,8 @@ as a newtype around its field. - [`PhantomData`](phantom_data.md): where the tag is stored, at zero size. - [`Product!`](../macros/product.md) and [`Sum!`](../macros/sum.md): the lists of `Field` entries that describe a record and a variant. +- [`Struct!`](../macros/struct.md) and [`Enum!`](../macros/enum.md): write a list of `Field` entries as + the body of a struct or enum declaration, each tag taken from a field or variant name. - [`Cons`](cons.md) and [`Either`](either.md): the product and sum lists those entries are built into. - [`HasFields`](../traits/shape/has_fields.md): exposes a type's whole list of `Field` entries. - [`HasField`](../traits/field-access/has_field.md): single-field access against a matching tag. diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index 78025eb7..fe4272b7 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -152,6 +152,8 @@ with - [`Field`](field.md): carries an `Index` tag beside a positional value. - [`PhantomData`](phantom_data.md): how an `Index` tag is passed to `get_field`. - [`HasFields`](../traits/shape/has_fields.md): the tuple struct's shape whose entries this tag names. +- [`Struct!`](../macros/struct.md): writes that shape as a tuple struct body, so `Struct!(u64, String)` + keys its entries `Index<0>` and `Index<1>`. The ideas behind it: From 28bf315519ebd4d2b7a40428a4080625d69b4142 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 16:26:00 +0200 Subject: [PATCH 168/516] Cover the shape macros across the reference, concepts, and glossary The `Struct!` and `Enum!` pages gain the Usage rules a reader needs before building a value (the newtype and empty-body rules, a variant's payload), the keyword-name and delimiter-mismatch rejections, links to the check and expand pages, and a labelled `open` fragment. The `#[derive(HasFields)]` and `HasFields` pages, the two extensible-data concept pages, and the error-codes rewrite list now say how a shape is written with the macros. The glossary defines "shape", linked from the first use of the term on the pages that use it. example-code mirrors the new spellings and records the keyword-name rejection as a compile-fail case. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/error-codes.md | 7 +++-- docs/comparisons/row-polymorphism.md | 2 +- docs/concepts/dispatching.md | 2 +- docs/concepts/extensible-records.md | 5 ++++ docs/concepts/extensible-variants.md | 5 ++++ .../architecture/derive-free-records.md | 2 +- docs/reference/derives/derive_has_fields.md | 9 ++++-- docs/reference/derives/index.md | 2 +- docs/reference/glossary.md | 9 ++++++ docs/reference/macros/enum.md | 28 +++++++++++++----- docs/reference/macros/index.md | 2 +- docs/reference/macros/product.md | 2 +- docs/reference/macros/struct.md | 29 +++++++++++++++---- docs/reference/macros/sum.md | 2 +- docs/reference/traits/builder/into_builder.md | 2 +- docs/reference/traits/builder/take_field.md | 2 +- docs/reference/traits/index.md | 2 +- .../traits/optional/transform_optional.md | 2 +- docs/reference/traits/shape/has_fields.md | 10 +++++-- .../traits/type-level/append_product.md | 2 +- .../traits/type-level/concat_product.md | 2 +- docs/reference/traits/type-level/index.md | 2 +- .../reference/traits/type-level/map_fields.md | 2 +- .../traits/type-level/transform_map.md | 2 +- .../traits/type-level/transform_map_fields.md | 2 +- docs/reference/traits/variant/from_variant.md | 2 +- .../traits/variant/has_extractor_ref.md | 2 +- docs/reference/types/either.md | 2 +- docs/reference/types/field.md | 2 +- docs/reference/types/index.md | 2 +- docs/reference/types/index_type.md | 2 +- docs/reference/types/nil.md | 2 +- .../struct_common_mistakes_keyword_name.rs | 8 +++++ ...struct_common_mistakes_keyword_name.stderr | 5 ++++ .../tests/concepts/extensible_records.rs | 12 ++++++++ .../tests/concepts/extensible_variants.rs | 12 ++++++++ .../reference/derives/derive_has_fields.rs | 13 +++++++++ example-code/tests/reference/macros/enum.rs | 7 +++++ example-code/tests/reference/macros/struct.rs | 10 ++++++- .../tests/reference/traits/has_fields.rs | 4 +++ 40 files changed, 176 insertions(+), 45 deletions(-) create mode 100644 example-code/tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.rs create mode 100644 example-code/tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.stderr diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index 75428ab2..a8b39578 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -408,8 +408,11 @@ Some changes make an error easier to read without classifying it, so they carry them in an error whose headline the tool left as the compiler wrote it: - **Type-level names written back as you wrote them**: a field name as `Symbol!("name")`, a list as - `Product![A, B]` or `Sum![A, B]`, and a path as `Path!(@app.Component)`. A path that ends in an - unknown part gets a trailing `.*`, which is not real `Path!` syntax. + `Product![A, B]` or `Sum![A, B]`, and a path as `Path!(@app.Component)`. A list of named or + numbered fields reads as the struct or enum body it describes, such as + [`Struct! { name: String }`](/docs/reference/macros/struct) or + [`Enum! { Circle(f64) }`](/docs/reference/macros/enum), when it has such a spelling. A path that + ends in an unknown part gets a trailing `.*`, which is not real `Path!` syntax. - **Shorter type names**, with the CGP module paths the compiler prints in front of them removed. - **A missing-field sentence** in place of an unmet `HasField` requirement inside a note. - **Consumer and provider trait names** in the compiler's "required for … to implement …" notes, in diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index c68837cc..0ef257c2 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -121,7 +121,7 @@ effect sets, as in [Koka](https://arxiv.org/pdf/1406.2061) ; the ## How CGP expresses it -CGP derives type-level shapes for Rust's nominal structs and enums. Trait bounds then express the +CGP derives type-level [shapes](/docs/reference/glossary#shape) for Rust's nominal structs and enums. Trait bounds then express the field and variant requirements that row predicates express in a row system. ### Field lists and field requirements {#a-struct-is-a-closed-row-hasfield-is-row-containment} diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index a3765ff0..4c9f289e 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -126,7 +126,7 @@ An incomplete builder similarly reports bounds involving its partial-record stat can be longer and less direct than an ordinary non-exhaustive `match` or missing struct field. Dispatching adds type-level work for each field or variant. The compiler resolves the handler chain -and checks its changing types; wide shapes and many instantiations can increase that work. Runtime +and checks its changing types; wide [shapes](/docs/reference/glossary#shape) and many instantiations can increase that work. Runtime variant tests and handler calls still occur, and their optimization depends on the generated code and compiler. Static wiring alone does not guarantee that dispatch has zero runtime cost. diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index df9647a8..27557c82 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -56,6 +56,11 @@ Each `Field` pairs a name tag with a value type. `Symbol!("url")` encodes the na trait bounds to identify the field during compilation. A product contains every listed field; this differs from an enum's sum, which contains one variant at a time. +That list is the struct's **shape**. Code that names a shape itself, in a bound or an impl, can +write it as the struct body it describes: +[`Struct! { url: String, pool_size: u32 }`](/docs/reference/macros/struct) is exactly the type +above, because the macro runs the derive's own encoding. + Generic code can use either the complete field representation or a single-field bound. `HasFields` describes the whole structure, while `HasField` provides access to one field. The latter is also the mechanism used by [implicit arguments](./implicit-arguments.md). These operations use diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index ef8d4a92..4d56a81f 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -50,6 +50,11 @@ Each `Field` pairs a variant-name tag with its payload type. A sum holds one of where a record's product holds all its fields. Generic code can require an operation on the `Circle` variant without naming `Shape` itself. +That sum is the enum's **shape**. Code that names a shape itself, in a bound or an impl, can write +it as the enum body it describes: +[`Enum! { Circle(Circle), Rectangle(Rectangle) }`](/docs/reference/macros/enum) is exactly the type +above, because the macro runs the derive's own encoding. + Construction uses the same tags. A `FromVariant` bound lets generic code supply a payload for a named variant, while the implementing enum determines how to construct the value. Extraction provides the corresponding operation for taking a payload out. diff --git a/docs/projects/cgp-serde/architecture/derive-free-records.md b/docs/projects/cgp-serde/architecture/derive-free-records.md index 7e2b2559..d15f95ca 100644 --- a/docs/projects/cgp-serde/architecture/derive-free-records.md +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -64,7 +64,7 @@ derives all three. A struct that derives only the narrower ones, as the arena te `HasFields` and `BuildField` for reading, works in the directions they cover. The same derive serves every other generic CGP code that works over fields, such as builders and -conversions between struct shapes, so one opt-in covers more than serialization. A type whose owner +conversions between struct [shapes](/docs/reference/glossary#shape), so one opt-in covers more than serialization. A type whose owner has not derived the field traits, including any type from a crate that does not use CGP, cannot use the struct providers; it is encoded through its own Serde impl with [`UseSerde`](../reference/providers/use_serde.md) instead. diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 28c35453..e1b23dbf 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -127,8 +127,10 @@ pub struct Config { } ``` -`Config::Fields` is now `Product![Field, Field]`, and a -value round-trips through it: +`Config::Fields` is now `Product![Field, Field]`. +Code that needs to name that type can write it as the struct body instead, with +[`Struct!`](../macros/struct.md): `Struct! { host: String, port: u16 }` is the same type. A value +round-trips through it: ```rust let config = Config { host: "localhost".to_owned(), port: 8080 }; @@ -155,7 +157,8 @@ pub enum Shape { } ``` -`Shape::Fields` is `Sum![Field, Field]`. +`Shape::Fields` is `Sum![Field, Field]`, +which [`Enum!`](../macros/enum.md) writes as `Enum! { Circle(Circle), Rectangle(Rectangle) }`. Generic code can operate on `Self::Fields` under a `Self: HasFields` bound. An implementation that supports the resulting representation can work with `Config`, `Person`, or a struct in another crate diff --git a/docs/reference/derives/index.md b/docs/reference/derives/index.md index 6794d45f..0981212b 100644 --- a/docs/reference/derives/index.md +++ b/docs/reference/derives/index.md @@ -24,7 +24,7 @@ type-level tag. The implementation declares the field it needs as a trait bound. [`#[implicit]`](../attributes/implicit.md) argument and a [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) method generate that bound from the field name. -[`#[derive(HasFields)]`](./derive_has_fields.md) gives the whole shape instead of one field: the struct +[`#[derive(HasFields)]`](./derive_has_fields.md) gives the whole [shape](/docs/reference/glossary#shape) instead of one field: the struct or enum described as a single type-level list, plus the conversions that move values in and out of it. Reach for it when code must process every field at once, such as a serializer or a builder that merges two records. It is often derived alongside `HasField`. diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index a9762e36..6f44f08d 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -249,6 +249,15 @@ A component whose operation acts on, or describes, the context itself, as in `Ca [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) +### shape + +The type-level list of a struct's fields or an enum's variants, which `#[derive(HasFields)]` gives a +type as its `Fields`. Code that names a shape can write it as the declaration body, with `Struct!` +or `Enum!`. + +[Extensible records](/docs/concepts/extensible-records) · [`Struct!`](./macros/struct.md) · +[`Enum!`](./macros/enum.md) + ### target The thing a component's operation acts on: the context itself for a self-targeted component, or a type diff --git a/docs/reference/macros/enum.md b/docs/reference/macros/enum.md index 73c47e70..ff575af1 100644 --- a/docs/reference/macros/enum.md +++ b/docs/reference/macros/enum.md @@ -30,8 +30,8 @@ Enum! { Circle(f64), Square(f64) } The two are the identical type, and it is exactly the `Fields` the derive gives an enum with that body. Reach for `Enum!` wherever code *names* a variant set's shape rather than deriving it, such as a [trait bound](https://doc.rust-lang.org/book/ch10-02-traits.html) on `FromFields`. It is also the -form [`cargo cgp`](/docs/cargo-cgp) prints a variant list in, so a list read in the tool's output can -be copied back into code. +form [`cargo cgp check`](/docs/cargo-cgp/check) and [`cargo cgp expand`](/docs/cargo-cgp/expand) +print a variant list in, so a list read in the tool's output can be copied back into code. ## Usage @@ -51,6 +51,12 @@ and braces hold named fields. The brackets around the whole `Enum!` invocation d variant name may be a raw identifier, tagged without the `r#`, and the list accepts a trailing comma. An empty body, `Enum! {}`, is allowed. +Each variant carries its fields as one payload, and two cases matter when you build a value. A +variant with **exactly one positional field** carries that field's type directly, so `Circle(f64)` +carries an `f64`, and a **unit variant** carries `Nil`, the empty list. Every other variant, +including one with a single named field, carries a list, as a [`Struct!`](./struct.md) body +would. [Under the hood](#under-the-hood) lists every case. + `Enum!` builds a type, never a value. A value of the shape selects its variant with `Either::Left` and `Either::Right`, wrapping the payload with `Field::from`, or comes from an existing enum through `to_fields()`. @@ -151,11 +157,19 @@ variant, as `#[derive(HasFields)]` does, but [`#[derive(CgpData)]`](../derives/d shape with such variants therefore has no generic constructor or extractor. **An enum body's other parts are rejected.** An attribute on a variant (such as `#[default]` or a doc -comment), `pub` on a variant, a discriminant such as `= 1`, a variant name given twice, and any field -`Struct!` would reject each fail with their own error. - -**A variant list tagged by position has no `Enum!` spelling.** A variant needs a name, so a sum whose -entries are keyed by `Index` is written with `Sum!`. +comment), `pub` on a variant, a discriminant such as `= 1`, and a variant name given twice each fail +with their own error. A variant's fields are checked as a `Struct!` body's are, with the same +messages, so an attribute, visibility, a field named `_`, a field name given twice, a keyword field +name without its `r#`, and a value where a type belongs are each rejected inside a variant too. + +**A variant's brackets decide its form, and a field that contradicts them is rejected.** A bare +type inside braces, as in `V { u8 }`, and a `name: Type` entry inside parentheses, as in +`V(a: u8)`, each fail with a message saying which form the brackets require. This differs from the +brackets around the whole `Enum!` invocation, which do not matter. + +**A list whose tags are not identifiers has no `Enum!` spelling.** A variant needs a name that is a +Rust identifier, so a sum whose entries are keyed by `Index`, or by a type-level string that is +not an identifier, is written with `Sum!`. **Clippy's `type_complexity` lint, and an imported abstract type inside the body,** behave as they do for [`Struct!`](./struct.md#common-mistakes). diff --git a/docs/reference/macros/index.md b/docs/reference/macros/index.md index 8bc82a28..4edeca84 100644 --- a/docs/reference/macros/index.md +++ b/docs/reference/macros/index.md @@ -62,7 +62,7 @@ presets without a separate construct for them. [`Product!`](./product.md) and its value-level twin `product!` build a type-level list for a struct's fields or a handler pipeline's steps, [`Sum!`](./sum.md) builds the dual list for an enum's variants, and [`Path!`](./path.md) builds the routing list that namespaces and redirected lookups resolve -against. [`Struct!`](./struct.md) and [`Enum!`](./enum.md) write a whole struct or enum shape as the +against. [`Struct!`](./struct.md) and [`Enum!`](./enum.md) write a whole struct or enum [shape](/docs/reference/glossary#shape) as the body of its declaration, expanding to the same `Product!` or `Sum!` of named fields that `#[derive(HasFields)]` generates. You write two of them by hand in ordinary code, `Symbol!` in a `UseField` wiring entry and `Product!` in a handler pipeline, and the derives, the ergonomic macros above, and the `open` diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index 563a2b97..bbcc8a5a 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -12,7 +12,7 @@ A type-level list and its value-level counterpart. ## Overview `Product![A, B, C]` represents an ordered sequence of types as a single type. CGP uses it to describe the -*shape* of a struct: the list of its fields, in order, as one type that generic code can reason about. +[*shape*](/docs/reference/glossary#shape) of a struct: the list of its fields, in order, as one type that generic code can reason about. It is sometimes called an anonymous product type, because like a tuple it holds several things at once. The difference from a tuple is the one that matters: a `Product!` is built from a recursive list that generic code diff --git a/docs/reference/macros/struct.md b/docs/reference/macros/struct.md index a515080d..b355ca37 100644 --- a/docs/reference/macros/struct.md +++ b/docs/reference/macros/struct.md @@ -31,8 +31,8 @@ The two are the identical type, and it is exactly the `Fields` the derive gives body. Reach for `Struct!` wherever code *names* a shape rather than deriving it: a [trait bound](https://doc.rust-lang.org/book/ch10-02-traits.html) on `HasFields`, a trait implemented for a shape, or a wiring entry. It is also the form -[`cargo cgp expand`](/docs/cargo-cgp) and `cargo cgp check` print a shape in, so a shape read in -the tool's output can be copied back into code. +[`cargo cgp check`](/docs/cargo-cgp/check) and [`cargo cgp expand`](/docs/cargo-cgp/expand) print +a shape in, so a shape read in the tool's output can be copied back into code. ## Usage @@ -50,12 +50,18 @@ the tuple form. Write braces for named fields and parentheses for a tuple body, entry is a named field when it starts with a name followed by a single `:`, so a path type such as `core::marker::PhantomData` is a positional field. -Both forms accept a trailing comma. A field name may be a raw identifier, and its tag is the name -without the `r#`: `Struct! { r#type: u8 }` tags its field `"type"`, as the derive does. A field -type is any Rust type, including generic parameters, references with +Both forms accept a trailing comma. A field name may be a raw identifier, and a name that is a +keyword such as `type` must be written as one. Its tag is the name without the `r#`: +`Struct! { r#type: u8 }` tags its field `"type"`, as the derive does. A field type is any Rust +type, including generic parameters, references with [lifetimes](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html), and [associated-type](https://doc.rust-lang.org/reference/items/associated-items.html) projections. +Two bodies give a type you might not expect, because `Struct!` follows the derive. A body with +**exactly one positional field** is that field's type itself, so `Struct!(u64)` is plain `u64` +rather than a list with one entry, and an **empty body** is `Nil`, the empty list. A single named +field still makes a list. [Under the hood](#under-the-hood) shows both expansions. + `Struct!` builds a type, never a value. A value of the shape comes from an existing struct through `to_fields()`, or is built with [`product!`](./product.md), wrapping each field value with `.into()`. @@ -108,7 +114,8 @@ impl Describe for Struct!(u8, u16) { ``` A shape can also key an `open` dispatch entry in [`delegate_components!`](./delegate_components.md), -choosing a provider by the structure of a record: +so `App` chooses a provider by the structure of a record. This fragment assumes a component +`CanDescribeShape` and its providers `DescribePoint` and `DescribePair`, defined elsewhere: ```rust delegate_components! { @@ -207,6 +214,16 @@ Build a value with `product!` and `.into()`, or with `to_fields()`. `pub`, a field named `_`, a field name given twice, and a body that mixes named and positional entries each fail with their own error, since a shape has no use for them. +**A keyword field name needs its `r#`.** A keyword is not an identifier, so `Struct! { type: u8 }` +is rejected: + +```text +error: `type` is a keyword: write the field name as `r#type` +``` + +Write `Struct! { r#type: u8 }`, which tags the field `"type"`. The four keywords that have no raw +form, `self`, `Self`, `super`, and `crate`, cannot name a field at all. + **Clippy's `type_complexity` lint can fire on an ordinary shape.** Clippy measures the expanded type, in which every field name is a nested type-level string, so a shape nested in a larger type in a signature can cross the lint's threshold. A `type` alias for the shape, or diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index 3e1206d8..bfe9bf13 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -11,7 +11,7 @@ A type-level sum, the dual of `Product!`. ## Overview -`Sum![A, B, C]` represents a *choice* among several types as a single type. CGP uses it to describe the shape +`Sum![A, B, C]` represents a *choice* among several types as a single type. CGP uses it to describe the [shape](/docs/reference/glossary#shape) of an **enum**, the list of its variants, the way [`Product!`](./product.md) describes the fields of a struct. diff --git a/docs/reference/traits/builder/into_builder.md b/docs/reference/traits/builder/into_builder.md index 6616f6c8..736707ac 100644 --- a/docs/reference/traits/builder/into_builder.md +++ b/docs/reference/traits/builder/into_builder.md @@ -103,7 +103,7 @@ entry points and the one that shows up in generic code more than in application common case and the one the extensible builder pattern is about. - **Use `IntoBuilder`** when a complete value must be decomposed: to swap one field, or to hand its fields to several destinations, including the builder of a different record. -- **Use [`ToFields`](../shape/to_fields.md)** instead when you want the value's *shape* as a flat +- **Use [`ToFields`](../shape/to_fields.md)** instead when you want the value's [*shape*](/docs/reference/glossary#shape) as a flat list rather than a partial type you can fill. A partial value tracks presence; a `Fields` product does not. - **Prefer a struct update expression** in concrete code. `Person { first_name, ..person }` does the diff --git a/docs/reference/traits/builder/take_field.md b/docs/reference/traits/builder/take_field.md index be266f96..813ba3bb 100644 --- a/docs/reference/traits/builder/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -109,7 +109,7 @@ merging one record into another, already uses it for you. - **Use `take_field`** when a *specific* field must be extracted from a partial value, typically after [`into_builder`](./into_builder.md). - **Use [`BuildField`](./build_field.md)** for the opposite direction. -- **Use [`ToFields`](../shape/to_fields.md)** when the whole value should become a flat shape rather than a +- **Use [`ToFields`](../shape/to_fields.md)** when the whole value should become a flat [shape](/docs/reference/glossary#shape) rather than a partial record with one field missing. - **Prefer ordinary destructuring** in concrete code. `let Person { first_name, .. } = person;` needs none of this machinery, and this family is for code that cannot name the type. diff --git a/docs/reference/traits/index.md b/docs/reference/traits/index.md index fbfb645a..7cbaab5d 100644 --- a/docs/reference/traits/index.md +++ b/docs/reference/traits/index.md @@ -31,7 +31,7 @@ Reading a value out of a context is the next most common need. Most of the remaining traits build and read structs and enums generically, by their fields and variants. They divide into families that mirror the extensible-data derives: -- [Field structure](shape/index.md) exposes a type's whole shape as a single type, and moves a value +- [Field structure](shape/index.md) exposes a type's whole [shape](/docs/reference/glossary#shape) as a single type, and moves a value through it in both directions. - [Record builders](builder/index.md) assemble a struct one field at a time, with field presence tracked at compile time so an incomplete record cannot be finalized. diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index 0402e584..5f144364 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -156,7 +156,7 @@ conversion applies to every field type. Also absent is an impl from `IsOptional` conversion here, so the marker cannot be applied to an optional builder. [`TransformMapFields`](../type-level/transform_map_fields.md#under-the-hood) applies it, visiting each field -of the target's [`HasFields`](../shape/has_fields.md) shape and using +of the target's [`HasFields`](../shape/has_fields.md) [shape](/docs/reference/glossary#shape) and using [`UpdateField`](../builder/update_field.md) twice per field: once to take the value out and learn its marker, once to write it back under `IsOptional`. diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index f2a009ea..abdee791 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -137,8 +137,14 @@ pub fn demo() { ``` `assert_shape` compiles only if the type's `Fields` is exactly the second parameter, so each call is -a compile-time check of one shape. `Config` also derives [`HasField`](../field-access/has_field.md), -the common pairing that gives one struct both indexed and whole-shape access. A variant with one +a compile-time check of one shape. The listing spells the shapes out to show their encoding. Code +that only needs to name a shape writes it as a declaration body with +[`Struct!`](../../macros/struct.md) or [`Enum!`](../../macros/enum.md), so the first two checks +could pass `Struct! { host: String, port: u16 }` and +`Enum! { Circle(Circle), Rectangle(Rectangle) }`, which are the same types. + +`Config` also derives [`HasField`](../field-access/has_field.md), the common pairing that gives one +struct both indexed and whole-shape access. A variant with one unnamed field carries its payload directly, so `Shape`'s entries hold `Circle` and `Rectangle`, and the one-field `UserId` has the bare `u64` as its shape rather than a one-element product. diff --git a/docs/reference/traits/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md index e6bbac91..33530582 100644 --- a/docs/reference/traits/type-level/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -11,7 +11,7 @@ Adding one entry to the end of a type-level product list. ## Overview -A struct's shape in CGP is a type-level list, a [`Product!`](../../macros/product.md) of named +A struct's [shape](/docs/reference/glossary#shape) in CGP is a type-level list, a [`Product!`](../../macros/product.md) of named fields. Code that processes such a shape generically sometimes needs to describe a *new* shape computed from an old one: the shape a routine promises to return after adding a field, say, or a bound relating an input shape to an output one. diff --git a/docs/reference/traits/type-level/concat_product.md b/docs/reference/traits/type-level/concat_product.md index 138cad63..a76a0b93 100644 --- a/docs/reference/traits/type-level/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -11,7 +11,7 @@ Splicing one type-level product list onto the end of another. ## Overview -Describing the result of combining two records means naming their combined shape, and the shapes are +Describing the result of combining two records means naming their combined [shape](/docs/reference/glossary#shape), and the shapes are type-level lists, a [`Product!`](../../macros/product.md) of named fields each. `ConcatProduct` names the list you get by following one product with another. diff --git a/docs/reference/traits/type-level/index.md b/docs/reference/traits/type-level/index.md index 5a530ea6..5c53e6bf 100644 --- a/docs/reference/traits/type-level/index.md +++ b/docs/reference/traits/type-level/index.md @@ -14,7 +14,7 @@ These are the least user-facing traits in the reference. They are the type-level [builders](../builder/index.md), [extractors](../variant/index.md), and [casts](../casting/index.md): the markers that record what state one field is in, and the operations that grow and reshape a type's field list. You meet them in an error message from code that walks a -shape far more often than in code you wrote, and this group exists so that such a message is +[shape](/docs/reference/glossary#shape) far more often than in code you wrote, and this group exists so that such a message is legible. Most are not in the prelude. The group divides into the state markers and the list operations. diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index b51e4171..ef345404 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -18,7 +18,7 @@ Rewriting every entry of a type-level list through one marker. marker, and the record builder's `BuildAndMergeOutputs` maps its handler list the same way. You will most likely meet it in an error message from one of those; this page explains what it produces, and how it differs from the two similarly-named traits beside it. The one case for naming it is generic -code that must describe a uniformly re-wrapped shape. +code that must describe a uniformly re-wrapped [shape](/docs/reference/glossary#shape). ::: diff --git a/docs/reference/traits/type-level/transform_map.md b/docs/reference/traits/type-level/transform_map.md index 5223d319..63a20d1b 100644 --- a/docs/reference/traits/type-level/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -142,7 +142,7 @@ argument type of `::Map`, which normalizes to `()`, and That lets three impls for one marker coexist without overlapping: they differ in `M1`. [`TransformMapFields`](./transform_map_fields.md) calls this. For each field of the target's -[`HasFields`](../shape/has_fields.md) shape, it uses [`UpdateField`](../builder/update_field.md) to take the field out +[`HasFields`](../shape/has_fields.md) [shape](/docs/reference/glossary#shape), it uses [`UpdateField`](../builder/update_field.md) to take the field out (learning the marker it was in), applies `Transform::transform_mapped`, and writes the result back under the target marker. diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index 9aeab2bd..88ab5bd7 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -129,7 +129,7 @@ layer requires exactly that. cover. - **Use [`UpdateField`](../builder/update_field.md)** when a *single* field changes state. This trait is the whole-record form, and reaching for it to change one field walks every other field for nothing. -- **Use [`MapFields`](./map_fields.md)** when you only need to *name* the re-marked shape as a type. +- **Use [`MapFields`](./map_fields.md)** when you only need to *name* the re-marked [shape](/docs/reference/glossary#shape) as a type. That trait computes the type; this one converts the values. ## Under the hood diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index f7631ca8..60814ade 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -145,7 +145,7 @@ build at a site that can name it. generates nothing. The trait adds a *second* way to do the same thing, for callers that cannot use the first. - **Do not derive it alone if you also take the enum apart**, which is the usual case; reach for [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md), which bundles construction, deconstruction, and the - shape. + [shape](/docs/reference/glossary#shape). The names capture the split exactly: this trait puts a value *into* an enum, [`ExtractField`](./extract_field.md) gets one *out*. For structs, the analogous field-setting primitive is diff --git a/docs/reference/traits/variant/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md index bbd5d700..91b38e31 100644 --- a/docs/reference/traits/variant/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -116,7 +116,7 @@ borrowing. - **[`HasExtractorMut`](./has_extractor_mut.md)** to change a payload in place. - **[`HasExtractor`](./has_extractor.md)** only when the payload must be moved out. - **A `match`** when the enum is concrete. This family is for code that cannot name it. -- **[`ToFieldsRef`](../shape/to_fields_ref.md)** when what you want is the value's borrowed *shape* rather than +- **[`ToFieldsRef`](../shape/to_fields_ref.md)** when what you want is the value's borrowed [*shape*](/docs/reference/glossary#shape) rather than a narrowing chain: the same borrow-rather-than-consume idea, applied to the whole-shape view. ## Under the hood diff --git a/docs/reference/types/either.md b/docs/reference/types/either.md index 690ecfa5..64c119a3 100644 --- a/docs/reference/types/either.md +++ b/docs/reference/types/either.md @@ -26,7 +26,7 @@ nested branches rather than by a `match` written against a fixed enum. You write this list through the [`Sum!`](../macros/sum.md) macro. `Sum![A, B, C]` is the right-nested `Either` chain terminated by `Void`. The branches are most often [`Field`](field.md) entries that pair a -variant name with its payload, so an enum's shape becomes a `Sum!` of `Field` branches over this list. +variant name with its payload, so an enum's [shape](/docs/reference/glossary#shape) becomes a `Sum!` of `Field` branches over this list. ## Definition diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index 7a97a913..f944f512 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -15,7 +15,7 @@ described one entry at a time without naming the concrete type. `Field` carries a field's *name* and its *value* together in one type. A bare [`Product!`](../macros/product.md) list such as `Product![String, u8]` records the value types and their order, but it cannot tell `name: String` from any other `String`. Wrapping each element in a `Field`, -as `Field`, attaches the name as a type, so a struct's shape describes itself. +as `Field`, attaches the name as a type, so a struct's [shape](/docs/reference/glossary#shape) describes itself. Code that walks the list matches on the tag to find the field it wants. The name is a type because the program needs it only at compile time, for trait resolution and diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index 68e995f5..18d9e84f 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -13,7 +13,7 @@ the one ordinary runtime type you return from a getter. Most types on these pages are **type-level building blocks**, and you read them far more often than you write them. Much of CGP's machinery runs at the type level, where a field name, a variant, a position, or -a whole record shape is a *type* rather than a value. These building blocks carry that information. A +a whole record [shape](/docs/reference/glossary#shape) is a *type* rather than a value. These building blocks carry that information. A macro writes almost all of them for you, so you meet them when you read generated code or when a wiring mistake reports a deeply nested type. This section exists to make such a type readable. diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index fe4272b7..98fc23c2 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -30,7 +30,7 @@ position. `Index` is a zero-sized marker without runtime data. Its only job is to make a number available at the type level. So it can serve as a [`HasField`](../traits/field-access/has_field.md) tag, as the tag of -a [`Field`](field.md) entry inside a tuple struct's shape, and as the type inside a +a [`Field`](field.md) entry inside a tuple struct's [shape](/docs/reference/glossary#shape), and as the type inside a [`PhantomData`](phantom_data.md) wherever compile-time code needs a positional name. ## Definition diff --git a/docs/reference/types/nil.md b/docs/reference/types/nil.md index 5823f848..fe8f98d4 100644 --- a/docs/reference/types/nil.md +++ b/docs/reference/types/nil.md @@ -44,7 +44,7 @@ recursion stops when it reaches `Nil`. The string and path lists work the same w Because `Nil` is a real, constructible value, the empty product `Product![]` is `Nil`, and the empty value `product![]` is the `Nil` value. The empty string `Symbol!("")` is `Symbol<0, Nil>`, and a -unit struct that derives [`HasFields`](../derives/derive_has_fields.md) has `Nil` as its shape. A +unit struct that derives [`HasFields`](../derives/derive_has_fields.md) has `Nil` as its [shape](/docs/reference/glossary#shape). A builder or a conversion returns `Nil` when every field of a shape has been consumed. This is why an empty record is a value the program can hold. The contrast with [`Void`](void.md) is exact. A value with every branch ruled out cannot exist, so a sum ends in an uninhabited marker, while a record diff --git a/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.rs b/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.rs new file mode 100644 index 00000000..be22f920 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.rs @@ -0,0 +1,8 @@ +// From `docs/reference/macros/struct.md`, *Common Mistakes*: a keyword field name written without +// its `r#`, which the macro reads as a positional field. + +use cgp::prelude::*; + +type Shape = Struct! { type: u8 }; + +fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.stderr b/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.stderr new file mode 100644 index 00000000..bb874e88 --- /dev/null +++ b/example-code/tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.stderr @@ -0,0 +1,5 @@ +error: `type` is a keyword: write the field name as `r#type` + --> tests/compile_fail/reference/macros/struct_common_mistakes_keyword_name.rs:6:24 + | +6 | type Shape = Struct! { type: u8 }; + | ^^^^ diff --git a/example-code/tests/concepts/extensible_records.rs b/example-code/tests/concepts/extensible_records.rs index e10bac2f..d6242223 100644 --- a/example-code/tests/concepts/extensible_records.rs +++ b/example-code/tests/concepts/extensible_records.rs @@ -24,6 +24,18 @@ pub mod a_struct_as_a_list_of_named_fields { assert_shape::(); } + + /// The page's `Struct!` spelling of the same shape. + #[test] + fn struct_writes_the_same_shape() { + fn assert_shape() + where + T: HasFields, + { + } + + assert_shape::(); + } } /// ## Building one field at a time diff --git a/example-code/tests/concepts/extensible_variants.rs b/example-code/tests/concepts/extensible_variants.rs index b08f657e..356134ea 100644 --- a/example-code/tests/concepts/extensible_variants.rs +++ b/example-code/tests/concepts/extensible_variants.rs @@ -38,6 +38,18 @@ pub mod an_enum_as_a_list_of_named_variants { assert_shape::(); } + + /// The page's `Enum!` spelling of the same shape. + #[test] + fn enum_writes_the_same_shape() { + fn assert_shape() + where + T: HasFields, + { + } + + assert_shape::(); + } } /// ## One handler per variant, dispatched by name diff --git a/example-code/tests/reference/derives/derive_has_fields.rs b/example-code/tests/reference/derives/derive_has_fields.rs index 95e19238..1425827b 100644 --- a/example-code/tests/reference/derives/derive_has_fields.rs +++ b/example-code/tests/reference/derives/derive_has_fields.rs @@ -197,6 +197,19 @@ pub mod examples { fields } + /// The same two shapes, written with the shape macros the page names. + pub fn assert_config_struct( + fields: ::Fields, + ) -> Struct! { host: String, port: u16 } { + fields + } + + pub fn assert_shape_enum( + fields: ::Fields, + ) -> Enum! { Circle(Circle), Rectangle(Rectangle) } { + fields + } + /// The page's closing claim: generic code bounds on the shape rather than on the type, so one /// function applies to any record that derives it. The page does not show a recursion, so this /// stops at naming the shape. diff --git a/example-code/tests/reference/macros/enum.rs b/example-code/tests/reference/macros/enum.rs index 66dc3502..2bb78085 100644 --- a/example-code/tests/reference/macros/enum.rs +++ b/example-code/tests/reference/macros/enum.rs @@ -36,6 +36,13 @@ pub mod usage { let _: PhantomData = PhantomData::; let _: PhantomData = PhantomData::]>; } + + #[test] + fn the_payloads_that_matter_when_building_a_value() { + let circle: Enum! { Circle(f64), Empty } = Either::Left(Field::from(2.0)); + let empty: Enum! { Circle(f64), Empty } = Either::Right(Either::Left(Field::from(Nil))); + let _ = (circle, empty); + } } /// ## Examples diff --git a/example-code/tests/reference/macros/struct.rs b/example-code/tests/reference/macros/struct.rs index 2fbe00f5..1676ecf8 100644 --- a/example-code/tests/reference/macros/struct.rs +++ b/example-code/tests/reference/macros/struct.rs @@ -1,6 +1,6 @@ //! Code from `docs/reference/macros/struct.md` — *`Struct!`*. //! -//! The snippet the page rejects lives under `tests/compile_fail/reference/macros/`. Type +//! The snippets the page rejects live under `tests/compile_fail/reference/macros/`. Type //! equalities are checked by assigning one `PhantomData` to a binding typed with the other. /// ## Overview @@ -34,6 +34,14 @@ pub mod usage { let _: PhantomData = PhantomData::; } + #[test] + fn the_bodies_that_follow_the_derive() { + let _: PhantomData = PhantomData::; + let _: PhantomData = PhantomData::; + let _: PhantomData = + PhantomData::]>; + } + #[derive(Debug, PartialEq, HasFields)] pub struct Person { pub name: String, diff --git a/example-code/tests/reference/traits/has_fields.rs b/example-code/tests/reference/traits/has_fields.rs index 81610a53..e42d8df9 100644 --- a/example-code/tests/reference/traits/has_fields.rs +++ b/example-code/tests/reference/traits/has_fields.rs @@ -45,6 +45,10 @@ pub mod examples { Sum![Field, Field], >(); assert_shape::(); + + // The prose's shape-macro spellings of the first two checks. + assert_shape::(); + assert_shape::(); } #[test] From d457aa295ad2bb3fbb142d4dc7563ac549bf262c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 17:36:49 +0200 Subject: [PATCH 169/516] Rename the cgp-serde SerializeFields page to SerializeRecordFields Move reference/providers/serialize_fields.md to serialize_record_fields.md, fix every link and mention, and update the messages example now that the test asserts both documents instead of printing them. The published announcement post is left as it stands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017CCBh7fScUH7fzq5DeNtyt --- docs/comparisons/reflection.md | 6 ++--- .../architecture/component-design.md | 2 +- .../cgp-serde/architecture/crate-layout.md | 2 +- .../architecture/derive-free-records.md | 4 +-- .../architecture/reentrant-providers.md | 4 +-- docs/projects/cgp-serde/examples/basic.md | 6 ++--- docs/projects/cgp-serde/examples/messages.md | 27 +++++++++---------- .../cgp-serde/guides/debugging-wiring.md | 10 +++---- .../cgp-serde/guides/wiring-a-context.md | 6 ++--- docs/projects/cgp-serde/reference/index.md | 4 +-- .../providers/deserialize_record_fields.md | 4 +-- .../reference/providers/serialize_iterator.md | 2 +- ...e_fields.md => serialize_record_fields.md} | 16 ++++++----- .../reference/providers/use_serde.md | 2 +- .../reference/types/serialize_with_context.md | 2 +- docs/projects/cgp-serde/serde-comparison.md | 2 +- example-code/tests/comparisons/reflection.rs | 2 +- 17 files changed, 50 insertions(+), 51 deletions(-) rename docs/projects/cgp-serde/reference/providers/{serialize_fields.md => serialize_record_fields.md} (87%) diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index 7305103c..53e7dca7 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -115,7 +115,7 @@ Zig-style `comptime` outside its immediate scope. The feature remains experiment CGP encodes a type's structure as types and processes it with trait resolution. The example fragments form a field writer modeled on [`cgp-serde`](https://github.com/contextgeneric/cgp-serde) -'s `SerializeFields` provider, which does the same over serde's `Serializer` . Its context is an +'s `SerializeRecordFields` provider, which does the same over serde's `Serializer` . Its context is an [environmental context](/docs/reference/glossary#environmental-context) : `App` stands for an application and chooses how each field type is written. The written `Value` is a type parameter, so the component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component) . @@ -228,7 +228,7 @@ App.write_value(&config); // {"host": "localhost", "port": 8080} To complete these fragments, `Config` also needs `#[derive(HasField)]` , `App` needs a declaration, and `config` needs a value. The `WriteWithDebug` provider formats a value with `Debug` ; this illustrates traversal and dispatch rather than a complete JSON serializer. `cgp-serde` 's -[`SerializeFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs) +[`SerializeRecordFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs) performs the same recursion over a `serde::Serializer` . Its deserialization counterpart reads a field name as a runtime string and compares it with each field's compile-time `Tag::VALUE` . @@ -348,7 +348,7 @@ and is unstable. The CGP snippets were compiled against `cgp` `0.8.0` with a - [Zig language reference](https://ziglang.org/documentation/master/), [Comptime (zig.guide)](https://zig.guide/language-basics/comptime/), and [*Compile-Time Reflection with @typeInfo*](https://hive.blog/hive-196387/@scipio/learn-zig-series-32-compile-time-reflection-with-typeinfo): `comptime`, `@typeInfo`, `@Type`, `inline for`, and `@field`. - [Rust tracking issue #146922](https://github.com/rust-lang/rust/issues/146922), the source at [`library/core/src/mem/type_info.rs`](https://github.com/rust-lang/rust/blob/master/library/core/src/mem/type_info.rs), and the [*Reflection and comptime* project goal](https://rust-lang.github.io/rust-project-goals/2026/reflection-and-comptime.html): the `type_info` API, the compile-time-only restriction, and the stabilization plan. - [fasterthanli.me, *Introducing facet*](https://fasterthanli.me/articles/introducing-facet-reflection-for-rust): the derive-generates-data approach and its motivation. -- [`cgp-serde`, `SerializeFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs): the production version of this page's field recursion, over serde. +- [`cgp-serde`, `SerializeRecordFields`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/fields.rs): the production version of this page's field recursion, over serde. - [P2996R13, *Reflection for C++26*](https://isocpp.org/files/papers/P2996R13.html): C++'s static reflection with `std::meta::info` and splicers. - [*The Hidden Cost of Reflection in Go*](https://dev.to/devflex-pro/the-hidden-cost-of-reflection-in-go-why-your-code-is-slower-than-you-think-41ee) and [*Golang Reflection guide*](https://medium.com/@mojimich2015/golang-reflection-the-guide-to-runtime-type-inspection-manipulation-and-best-practices-303087684576): the runtime performance and type-safety costs of reflection. diff --git a/docs/projects/cgp-serde/architecture/component-design.md b/docs/projects/cgp-serde/architecture/component-design.md index ac3f35eb..56935c1f 100644 --- a/docs/projects/cgp-serde/architecture/component-design.md +++ b/docs/projects/cgp-serde/architecture/component-design.md @@ -101,7 +101,7 @@ same encoding: | [`TrySerializeFrom`](../reference/providers/try_serialize_from.md) | the same provider | | [`SerializeDeref`](../reference/providers/serialize_deref.md) | [`DeserializeAndAllocate`](../reference/providers/deserialize_and_allocate.md), for a reference | | [`SerializeIterator`](../reference/providers/serialize_iterator.md) | [`DeserializeExtend`](../reference/providers/deserialize_extend.md) | -| [`SerializeFields`](../reference/providers/serialize_fields.md) | [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) | +| [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) | [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) | | none | [`DeserializeDefault`](../reference/providers/deserialize_default.md), which wraps another reader | | [`SerializeHex`](../reference/providers/serialize_hex.md), [`SerializeBase64`](../reference/providers/serialize_base64.md), [`SerializeRfc3339Date`](../reference/providers/serialize_rfc3339_date.md), [`SerializeTimestamp`](../reference/providers/serialize_timestamp.md) | the same providers | diff --git a/docs/projects/cgp-serde/architecture/crate-layout.md b/docs/projects/cgp-serde/architecture/crate-layout.md index 462ef50c..4f002e39 100644 --- a/docs/projects/cgp-serde/architecture/crate-layout.md +++ b/docs/projects/cgp-serde/architecture/crate-layout.md @@ -54,7 +54,7 @@ services](./context-services.md). Every crate sorts its items into modules by kind, so an item's kind says where to import it from: - **`components`** — the serialization components, in `cgp-serde`. -- **`providers`** — the providers, in every crate, as in `cgp_serde::providers::SerializeFields` or +- **`providers`** — the providers, in every crate, as in `cgp_serde::providers::SerializeRecordFields` or `cgp_serde_extra::providers::SerializeHex`. - **`types`** — the adapter types, in `cgp-serde`. - **`traits`** — components that support a provider, such as the allocation component in diff --git a/docs/projects/cgp-serde/architecture/derive-free-records.md b/docs/projects/cgp-serde/architecture/derive-free-records.md index d15f95ca..b6f4be77 100644 --- a/docs/projects/cgp-serde/architecture/derive-free-records.md +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -35,7 +35,7 @@ pub struct Payload { ``` Two generic providers are written once against what `CgpData` exposes. -[`SerializeFields`](../reference/providers/serialize_fields.md) walks the field list and writes the +[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) walks the field list and writes the struct as a map from each field's name to its value, asking the **context**, the type whose wiring holds an application's choices, to serialize each value. [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) reads the map back, @@ -44,7 +44,7 @@ field the input left out. A context wires the struct to them like any other type ```rust @ValueSerializerComponent.Payload: - SerializeFields, + SerializeRecordFields, @ValueDeserializerComponent.Payload: DeserializeRecordFields, diff --git a/docs/projects/cgp-serde/architecture/reentrant-providers.md b/docs/projects/cgp-serde/architecture/reentrant-providers.md index 38245c8d..9fd05160 100644 --- a/docs/projects/cgp-serde/architecture/reentrant-providers.md +++ b/docs/projects/cgp-serde/architecture/reentrant-providers.md @@ -20,14 +20,14 @@ is written however Serde's impl for `Vec` writes it. The choice is fixed whe written. A cgp-serde provider makes the same call on the context instead. The struct provider, -[`SerializeFields`](../reference/providers/serialize_fields.md), serializes each field by asking the +[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md), serializes each field by asking the context to serialize the field's type. The collection provider, [`SerializeIterator`](../reference/providers/serialize_iterator.md), does the same for each item. The context answers each request from its wiring table, so a context that wires `Vec` to hex gets hex for every `Vec` it serializes: a top-level value, a field, or an item in a list inside a field. -This also keeps each provider small. `SerializeFields` knows how to walk a struct and nothing about +This also keeps each provider small. `SerializeRecordFields` knows how to walk a struct and nothing about the fields' types, and `SerializeIterator` knows how to walk a collection and nothing about the items. Each is written once, generically, and the context composes them. diff --git a/docs/projects/cgp-serde/examples/basic.md b/docs/projects/cgp-serde/examples/basic.md index 4712f2e6..f1f39e82 100644 --- a/docs/projects/cgp-serde/examples/basic.md +++ b/docs/projects/cgp-serde/examples/basic.md @@ -114,7 +114,7 @@ delegate_components! { SerializeHex, @ValueSerializerComponent.Payload: - SerializeFields, + SerializeRecordFields, @ValueDeserializerComponent.[ u64, @@ -155,7 +155,7 @@ The providers each do one job: string. - [`SerializeHex`](../reference/providers/serialize_hex.md) writes bytes as a hex string, and reads them back. -- [`SerializeFields`](../reference/providers/serialize_fields.md) writes a struct as a map from +- [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) writes a struct as a map from field names to values, and [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) reads one back. @@ -165,7 +165,7 @@ in both directions, because one struct implements both halves of the hex encodin ## The struct's provider asks the context for its fields -`SerializeFields` knows how to walk a struct, but not how to encode any field. For each field, it +`SerializeRecordFields` knows how to walk a struct, but not how to encode any field. For each field, it asks the context to serialize the field's type, and the context's wiring answers. That is why `App` has entries for `u64`, `String`, and `Vec` as well as for `Payload`: they are the types the struct's provider hands back. diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md index 0b58ca4f..01f33d16 100644 --- a/docs/projects/cgp-serde/examples/messages.md +++ b/docs/projects/cgp-serde/examples/messages.md @@ -43,17 +43,17 @@ application its own choices. ## Run it From the root of the [cgp-serde repository](https://github.com/contextgeneric/cgp-serde), run the -test and show what it prints: +test: ```sh -cargo test -p cgp-serde-tests messages -- --nocapture +cargo test -p cgp-serde-tests messages ``` -It prints the same archive twice. From the first application, `AppA`, bytes are hex and dates are -RFC 3339 strings: +It serializes the same archive twice and checks each document against the exact JSON below. From +the first application, `AppA`, bytes are hex and dates are RFC 3339 strings: -```text -serialized with A: { +```json +{ "decryption_key": "746f702d736563726574", "messages_by_topics": [ { @@ -79,8 +79,8 @@ serialized with A: { From the second, `AppB`, bytes are base64 and dates are Unix timestamps: -```text -serialized with B: { +```json +{ "decryption_key": "dG9wLXNlY3JldA==", "messages_by_topics": [ { @@ -104,8 +104,6 @@ serialized with B: { } ``` -The test prints the documents rather than asserting them, and passes when both serialize. - ## The data names no encoding The archive is three nested structs, from @@ -176,7 +174,7 @@ delegate_components! { MessagesByTopic, EncryptedMessage, ]: - SerializeFields, + SerializeRecordFields, } } ``` @@ -213,7 +211,7 @@ they do not, because each choice holds only within the context that makes it. Neither table says anything about where a `Vec` appears, and yet every byte field in the archive, at all three levels, follows its context's choice. That is because no provider encodes the -values inside the one it is given. [`SerializeFields`](../reference/providers/serialize_fields.md) +values inside the one it is given. [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) walks a struct and asks the context to serialize each field, and [`SerializeIterator`](../reference/providers/serialize_iterator.md) walks a collection and asks the context to serialize each item. Each of those requests goes back through the same table, so the @@ -246,9 +244,8 @@ Each context's wiring is asserted by a serializes. Then the test hands each context and the archive to `serde_json`: ```rust -let serialized = +let serialized_a = serde_json::to_string_pretty(&SerializeWithContext::new(&AppA, &archive)).unwrap(); -println!("serialized with A: {serialized}"); ``` [`SerializeWithContext`](../reference/types/serialize_with_context.md) pairs a context with a value @@ -267,7 +264,7 @@ error[E0277]: [CGP-E001] the consumer traits `CanSerializeValue>`, ``` Every checked type that contains a date fails, and all for one reason. Below the root cause, the -tool prints the chain that leads to it: from `MessagesArchive` through `SerializeFields`, the +tool prints the chain that leads to it: from `MessagesArchive` through `SerializeRecordFields`, the vectors, the references, and `EncryptedMessage`, down to `SerializeTimestamp`, which asks `AppB` for an `i64` it has no entry for. The fix is to put `i64` back. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. diff --git a/docs/projects/cgp-serde/guides/debugging-wiring.md b/docs/projects/cgp-serde/guides/debugging-wiring.md index 92159e39..a8d379ac 100644 --- a/docs/projects/cgp-serde/guides/debugging-wiring.md +++ b/docs/projects/cgp-serde/guides/debugging-wiring.md @@ -21,7 +21,7 @@ shorter and clearer there than at the first call. ## A type the traversal reaches has no entry **The most common mistake is a missing entry for a nested type.** Here `Payload` is wired to -[`SerializeFields`](../reference/providers/serialize_fields.md), but the type of its `data` field +[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md), but the type of its `data` field has no entry: ```rust @@ -37,7 +37,7 @@ delegate_components! { App { open ValueSerializerComponent; @ValueSerializerComponent.u64: UseSerde, - @ValueSerializerComponent.Payload: SerializeFields, + @ValueSerializerComponent.Payload: SerializeRecordFields, } } @@ -56,7 +56,7 @@ error[E0277]: [CGP-E001] the consumer trait `CanSerializeValue` is not this is required through the dependency chain: [CGP-E101] consumer trait impl `CanSerializeValue` for context `App` └─ [CGP-E104] redirect lookup to `@ValueSerializerComponent` in `App` - └─ [CGP-E102] provider trait impl `ValueSerializer` with context `App` for provider `SerializeFields` + └─ [CGP-E102] provider trait impl `ValueSerializer` with context `App` for provider `SerializeRecordFields` └─ [CGP-E105] trait impl `FieldsSerializer` for `Struct! { quantity: u64, data: Vec }` └─ [CGP-E105] trait impl `FieldsSerializer` for `Struct! { data: Vec }` └─ [CGP-E101] consumer trait impl `CanSerializeValue>` for context `App` @@ -64,7 +64,7 @@ error[E0277]: [CGP-E001] the consumer trait `CanSerializeValue` is not └─ [CGP-E107] context `App` does not contain any delegate entry for `@ValueSerializerComponent.Vec` ``` -The chain reads from the top down: serializing `Payload` goes to `SerializeFields`, which walks the +The chain reads from the top down: serializing `Payload` goes to `SerializeRecordFields`, which walks the fields to `data`, which asks the context for a `Vec`, which the table does not have. However deep the missing type sits, the root cause names it. The fix is an entry for `Vec`, such as `@ValueSerializerComponent.Vec: SerializeHex`. @@ -225,7 +225,7 @@ delegate_components! { @ValueSerializerComponent.<'a, T> &'a T: SerializeDeref, @ValueSerializerComponent.u64: UseSerde, @ValueSerializerComponent.Vec: SerializeIterator, - @ValueSerializerComponent.Node: SerializeFields, + @ValueSerializerComponent.Node: SerializeRecordFields, } } ``` diff --git a/docs/projects/cgp-serde/guides/wiring-a-context.md b/docs/projects/cgp-serde/guides/wiring-a-context.md index 51f96d48..d65da32a 100644 --- a/docs/projects/cgp-serde/guides/wiring-a-context.md +++ b/docs/projects/cgp-serde/guides/wiring-a-context.md @@ -49,7 +49,7 @@ delegate_components! { MessagesByTopic, EncryptedMessage, ]: - SerializeFields, + SerializeRecordFields, } } ``` @@ -70,7 +70,7 @@ List the types a traversal touches, not only the types the data names. Start fro type, and follow what each provider asks the context for, which each provider's [reference page](../reference/index.md) states: -- **A struct** wired to [`SerializeFields`](../reference/providers/serialize_fields.md) or +- **A struct** wired to [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) or [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) needs an entry for each field's type. - **A collection** needs an entry of its own, besides its item type's. Writing one with @@ -177,7 +177,7 @@ cgp_namespace! { @ValueSerializerComponent.Vec: SerializeIterator, @ValueSerializerComponent.[MessagesByTopic, EncryptedMessage]: - SerializeFields, + SerializeRecordFields, } } diff --git a/docs/projects/cgp-serde/reference/index.md b/docs/projects/cgp-serde/reference/index.md index d4f51a5c..96868b9d 100644 --- a/docs/projects/cgp-serde/reference/index.md +++ b/docs/projects/cgp-serde/reference/index.md @@ -27,7 +27,7 @@ to. ## Serialization providers Every provider below implements the serializing component, the deserializing one, or both, and is -imported from its crate's `providers` module, such as `cgp_serde::providers::SerializeFields`. The +imported from its crate's `providers` module, such as `cgp_serde::providers::SerializeRecordFields`. The last column is what the provider asks the context to encode in turn; see [re-entrant providers](../architecture/reentrant-providers.md). @@ -44,7 +44,7 @@ providers](../architecture/reentrant-providers.md). | [`SerializeDeref`](./providers/serialize_deref.md) | `cgp-serde` | writes | a reference or smart pointer | the value it points to | | [`SerializeIterator`](./providers/serialize_iterator.md) | `cgp-serde` | writes | a collection iterable by reference | each item it yields | | [`DeserializeExtend`](./providers/deserialize_extend.md) | `cgp-serde` | reads | a collection that can be extended | each item | -| [`SerializeFields`](./providers/serialize_fields.md) | `cgp-serde` | writes | a struct with named fields | each field's type | +| [`SerializeRecordFields`](./providers/serialize_record_fields.md) | `cgp-serde` | writes | a struct with named fields | each field's type | | [`DeserializeRecordFields`](./providers/deserialize_record_fields.md) | `cgp-serde` | reads | a struct with named fields | each field's type | | [`DeserializeDefault`](./providers/deserialize_default.md) | `cgp-serde` | reads | a `Default` type that may be null | nothing; wraps another provider | | [`SerializeHex`](./providers/serialize_hex.md) | `cgp-serde-extra` | both | bytes, as hex | `String` | diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md index 3317b138..48a39944 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md @@ -12,7 +12,7 @@ field. ## Overview -`DeserializeRecordFields` is the reading half of [`SerializeFields`](./serialize_fields.md). It +`DeserializeRecordFields` is the reading half of [`SerializeRecordFields`](./serialize_record_fields.md). It reads a map, asks the **context**, the type whose wiring holds the application's choices, to read each field's value, and collects the values in CGP's builder for the struct until every field is present. The struct derives only CGP's field traits, through @@ -86,7 +86,7 @@ through [`DeserializeExtend`](./deserialize_extend.md). ## Pairing -[`SerializeFields`](./serialize_fields.md) writes the map it reads. +[`SerializeRecordFields`](./serialize_record_fields.md) writes the map it reads. ## When to use it diff --git a/docs/projects/cgp-serde/reference/providers/serialize_iterator.md b/docs/projects/cgp-serde/reference/providers/serialize_iterator.md index 367704b1..cef67058 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_iterator.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_iterator.md @@ -76,7 +76,7 @@ choices.** For a collection of types the application does not customize, such as ## Related constructs -- [`SerializeFields`](./serialize_fields.md) is the matching provider for a struct. +- [`SerializeRecordFields`](./serialize_record_fields.md) is the matching provider for a struct. ## The ideas behind it diff --git a/docs/projects/cgp-serde/reference/providers/serialize_fields.md b/docs/projects/cgp-serde/reference/providers/serialize_record_fields.md similarity index 87% rename from docs/projects/cgp-serde/reference/providers/serialize_fields.md rename to docs/projects/cgp-serde/reference/providers/serialize_record_fields.md index 85ac596e..9135efe0 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_fields.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_record_fields.md @@ -1,17 +1,17 @@ --- -title: 'SerializeFields — write a struct with no serialization derive in cgp-serde' -sidebar_label: 'SerializeFields' +title: 'SerializeRecordFields — write a struct with no serialization derive in cgp-serde' +sidebar_label: 'SerializeRecordFields' sidebar_position: 12 description: 'The cgp-serde provider that writes any struct deriving CGP''s field traits as a map from field names to values, asking the context to write each field.' --- -# `SerializeFields` +# `SerializeRecordFields` Write a struct as a map from each field's name to its value, asking the context to write each value. ## Overview -`SerializeFields` serializes a struct that derives nothing from Serde. It reads the struct's field +`SerializeRecordFields` serializes a struct that derives nothing from Serde. It reads the struct's field list through CGP's field traits, which [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) provides, and asks the **context**, the type whose wiring holds the application's choices, to write each field's value. So one generic @@ -20,7 +20,9 @@ provider serves every struct, and each field is encoded however the context enco ## Definition ```rust -#[cgp_impl(new SerializeFields)] +pub struct SerializeRecordFields; + +#[cgp_impl(SerializeRecordFields)] impl ValueSerializer where Value: HasFields, @@ -50,7 +52,7 @@ pub struct Payload { @ValueSerializerComponent.u64: UseSerde, @ValueSerializerComponent.String: SerializeString, @ValueSerializerComponent.Vec: SerializeHex, -@ValueSerializerComponent.Payload: SerializeFields, +@ValueSerializerComponent.Payload: SerializeRecordFields, ``` That context writes a `Payload` as `{"quantity":42,"message":"hello","data":"010203"}`. @@ -78,7 +80,7 @@ shape: a map keyed by Rust field names. ## When to use it -**Reach for `SerializeFields` for a struct whose fields should follow the context's choices**, and +**Reach for `SerializeRecordFields` for a struct whose fields should follow the context's choices**, and for any struct whose crate should not depend on `serde`. For a struct that already derives Serde's `Serialize` and needs no per-application choice, [`UseSerde`](./use_serde.md) uses that derive. diff --git a/docs/projects/cgp-serde/reference/providers/use_serde.md b/docs/projects/cgp-serde/reference/providers/use_serde.md index deb4c677..eefe97ba 100644 --- a/docs/projects/cgp-serde/reference/providers/use_serde.md +++ b/docs/projects/cgp-serde/reference/providers/use_serde.md @@ -74,7 +74,7 @@ The same provider reads what it writes. most scalar types, and for any type cgp-serde's generic providers do not cover, such as an enum with a derived Serde impl. -Reach for [`SerializeFields`](./serialize_fields.md) and +Reach for [`SerializeRecordFields`](./serialize_record_fields.md) and [`DeserializeRecordFields`](./deserialize_record_fields.md) instead when a struct's fields should follow the context's choices, since `UseSerde` hands the whole struct to its own impl. diff --git a/docs/projects/cgp-serde/reference/types/serialize_with_context.md b/docs/projects/cgp-serde/reference/types/serialize_with_context.md index 3ca55a4d..bde009a7 100644 --- a/docs/projects/cgp-serde/reference/types/serialize_with_context.md +++ b/docs/projects/cgp-serde/reference/types/serialize_with_context.md @@ -73,7 +73,7 @@ type, [`SerializeToJsonString`](../providers/serialize_to_json_string.md) wraps ## Related constructs - [`SerializeIterator`](../providers/serialize_iterator.md) and - [`SerializeFields`](../providers/serialize_fields.md) use it for each item and field. + [`SerializeRecordFields`](../providers/serialize_record_fields.md) use it for each item and field. ## The ideas behind it diff --git a/docs/projects/cgp-serde/serde-comparison.md b/docs/projects/cgp-serde/serde-comparison.md index 721b4c9e..1cd70b47 100644 --- a/docs/projects/cgp-serde/serde-comparison.md +++ b/docs/projects/cgp-serde/serde-comparison.md @@ -55,7 +55,7 @@ field while a cgp-serde context chooses per type: | `serialize_with` and `deserialize_with` | write a provider, and wire the type to it | | a newtype to change a type's encoding | wire a different provider in a different context | | `#[serde(remote = "…")]` for a type from another crate | wire the type to a provider directly | -| `#[derive(Serialize, Deserialize)]` on a struct | derive `CgpData`, and wire the struct to `SerializeFields` and `DeserializeRecordFields` | +| `#[derive(Serialize, Deserialize)]` on a struct | derive `CgpData`, and wire the struct to `SerializeRecordFields` and `DeserializeRecordFields` | | a hand-written `DeserializeSeed` for state | a provider that takes the state from the context | | a borrowed `&'de str` field | wire `&'a str` to `UseSerde`, and read from input that can lend it | diff --git a/example-code/tests/comparisons/reflection.rs b/example-code/tests/comparisons/reflection.rs index 6c654b76..37acae24 100644 --- a/example-code/tests/comparisons/reflection.rs +++ b/example-code/tests/comparisons/reflection.rs @@ -1,7 +1,7 @@ //! Code from `docs/comparisons/reflection.md` — *Reflection and compile-time introspection*. //! //! The page's worked example is a self-contained field writer modeled on `cgp-serde`'s -//! `SerializeFields` provider, so it can be compiled here without a `serde` dependency. +//! `SerializeRecordFields` provider, so it can be compiled here without a `serde` dependency. /// ## A type's shape becomes a type, not a descriptor pub mod a_types_shape_becomes_a_type { From fdb7483b4bf2ffe8f29aef8e71917785a88c5a43 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 17:48:22 +0200 Subject: [PATCH 170/516] Add cgp-serde pages for the variant providers Add reference pages for SerializeVariantFields and DeserializeVariantFields, list them in the reference index, and update the pages that said cgp-serde has no generic enum provider: the index, limitations, the Serde comparison, derive-free records, the Serde bridge, and UseSerde. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017CCBh7fScUH7fzq5DeNtyt --- .../architecture/derive-free-records.md | 9 +- .../cgp-serde/architecture/serde-bridge.md | 2 +- docs/projects/cgp-serde/index.md | 5 +- docs/projects/cgp-serde/limitations.md | 10 +- docs/projects/cgp-serde/reference/index.md | 2 + .../providers/allocate_with_arena.md | 2 +- .../providers/deserialize_and_allocate.md | 2 +- .../providers/deserialize_default.md | 2 +- .../providers/deserialize_from_json_reader.md | 2 +- .../providers/deserialize_from_json_string.md | 2 +- .../providers/deserialize_variant_fields.md | 114 ++++++++++++++++ .../reference/providers/serialize_base64.md | 2 +- .../reference/providers/serialize_hex.md | 2 +- .../providers/serialize_rfc3339_date.md | 2 +- .../providers/serialize_timestamp.md | 2 +- .../providers/serialize_to_json_string.md | 2 +- .../providers/serialize_variant_fields.md | 125 ++++++++++++++++++ .../reference/providers/use_serde.md | 4 +- docs/projects/cgp-serde/serde-comparison.md | 6 +- 19 files changed, 273 insertions(+), 24 deletions(-) create mode 100644 docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md diff --git a/docs/projects/cgp-serde/architecture/derive-free-records.md b/docs/projects/cgp-serde/architecture/derive-free-records.md index b6f4be77..93af35be 100644 --- a/docs/projects/cgp-serde/architecture/derive-free-records.md +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -77,10 +77,13 @@ written under its Rust name, and a field cannot be renamed, skipped, flattened, when it is missing. Choices are made per type instead, through the context: a `Vec` field is encoded however the context encodes `Vec`. -The providers also cover one shape of type: structs with named fields. Tuple structs and enums are -not handled by them, and an enum is encoded through its own Serde impl, with `UseSerde`. The +The struct providers cover structs with named fields, and tuple structs are not handled by them. +Enums get the same treatment from +[`SerializeVariantFields`](../reference/providers/serialize_variant_fields.md) and +[`DeserializeVariantFields`](../reference/providers/deserialize_variant_fields.md), which read an +enum's variants through CGP's traits and handle variants that each hold one value. The [comparison with Serde](../serde-comparison.md) lists what Serde's derive does that cgp-serde's -struct providers do not. +providers do not. ## What it costs diff --git a/docs/projects/cgp-serde/architecture/serde-bridge.md b/docs/projects/cgp-serde/architecture/serde-bridge.md index f32d3b8b..eabb7602 100644 --- a/docs/projects/cgp-serde/architecture/serde-bridge.md +++ b/docs/projects/cgp-serde/architecture/serde-bridge.md @@ -49,7 +49,7 @@ where `SerdeSerialize` is Serde's `Serialize`, imported under another name. Every `Serialize` impl, in the standard library or in any crate, is therefore available to a context without a cgp-serde provider being written for it; the context wires the type to `UseSerde`. This is also how a context handles a -type that cgp-serde's generic providers do not cover, such as an enum with a derived impl. +type that cgp-serde's generic providers do not cover, such as an enum in an internally tagged form, with a derived impl. The trade is that the context's choices stop at that value. The type's own impl serializes its contents, so a `Vec` inside it is written the way that impl writes it, whatever the context diff --git a/docs/projects/cgp-serde/index.md b/docs/projects/cgp-serde/index.md index 63f79f84..e06bab32 100644 --- a/docs/projects/cgp-serde/index.md +++ b/docs/projects/cgp-serde/index.md @@ -14,8 +14,9 @@ applications can write the same value differently, and neither needs to own the cgp-serde is a proof of concept. It replaces Serde's per-type implementations and keeps everything else: Serde's data model, its formats such as `serde_json`, and any `Serialize` impl a type already -has. Its generic providers cover structs with named fields and the standard collections, and -scalars, enums, and every other type are encoded through their own Serde impls. These pages show +has. Its generic providers cover structs with named fields, enums whose variants each hold one +value, and the standard collections, and scalars and every other type are encoded through their +own Serde impls. These pages show what the design makes possible and where it stops. ## One value, two encodings diff --git a/docs/projects/cgp-serde/limitations.md b/docs/projects/cgp-serde/limitations.md index ff568270..93dd64d3 100644 --- a/docs/projects/cgp-serde/limitations.md +++ b/docs/projects/cgp-serde/limitations.md @@ -25,11 +25,13 @@ everything else. Its output is whatever Serde's data model can express, written format. It cannot make a format do something the format does not do, and a program still depends on `serde` and on the format crates it uses. See [the bridge to Serde](./architecture/serde-bridge.md). -## The generic providers cover structs with named fields +## The generic providers cover structs and simple enums -The providers that walk a type generically handle structs with named fields, the standard -collections, references, and types that convert to or from another type. They do not handle enums, -tuple structs, or tuples. Those types, and any other type that already implements Serde's traits, +The providers that walk a type generically handle structs with named fields, enums whose variants +each hold exactly one value, the standard collections, references, and types that convert to or +from another type. Enums are written only in Serde's default form, `{"Variant": value}`, and only +an enum without a lifetime can be written. The providers do not handle other enums, tuple structs, +or tuples. Those types, and any other type that already implements Serde's traits, are encoded through their own Serde impl, with `UseSerde`, and the choices of the **context**, the type whose wiring holds an application's choices, do not reach inside them. diff --git a/docs/projects/cgp-serde/reference/index.md b/docs/projects/cgp-serde/reference/index.md index 96868b9d..af40dd26 100644 --- a/docs/projects/cgp-serde/reference/index.md +++ b/docs/projects/cgp-serde/reference/index.md @@ -46,6 +46,8 @@ providers](../architecture/reentrant-providers.md). | [`DeserializeExtend`](./providers/deserialize_extend.md) | `cgp-serde` | reads | a collection that can be extended | each item | | [`SerializeRecordFields`](./providers/serialize_record_fields.md) | `cgp-serde` | writes | a struct with named fields | each field's type | | [`DeserializeRecordFields`](./providers/deserialize_record_fields.md) | `cgp-serde` | reads | a struct with named fields | each field's type | +| [`SerializeVariantFields`](./providers/serialize_variant_fields.md) | `cgp-serde` | writes | an enum of one-value variants, without a lifetime | each variant's value type | +| [`DeserializeVariantFields`](./providers/deserialize_variant_fields.md) | `cgp-serde` | reads | an enum of one-value variants | each variant's value type | | [`DeserializeDefault`](./providers/deserialize_default.md) | `cgp-serde` | reads | a `Default` type that may be null | nothing; wraps another provider | | [`SerializeHex`](./providers/serialize_hex.md) | `cgp-serde-extra` | both | bytes, as hex | `String` | | [`SerializeBase64`](./providers/serialize_base64.md) | `cgp-serde-extra` | both | bytes, as base64 | `String` | diff --git a/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md index 36fa0f3c..3e73fc2c 100644 --- a/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md +++ b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md @@ -1,7 +1,7 @@ --- title: 'AllocateWithArena — allocate into an arena held by the context in cgp-serde' sidebar_label: 'AllocateWithArena' -sidebar_position: 23 +sidebar_position: 25 description: 'The cgp-serde provider that implements the allocation component by moving values into a typed_arena::Arena the context supplies through an arena getter.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md index b71fa556..6f024458 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md @@ -1,7 +1,7 @@ --- title: 'DeserializeAndAllocate — read a reference into an allocator in cgp-serde' sidebar_label: 'DeserializeAndAllocate' -sidebar_position: 22 +sidebar_position: 24 description: 'The cgp-serde provider that reads a borrowed &T by reading an owned T through the context and allocating it through the context''s allocation component.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_default.md b/docs/projects/cgp-serde/reference/providers/deserialize_default.md index b4c1ed53..eab690c3 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_default.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_default.md @@ -1,7 +1,7 @@ --- title: 'DeserializeDefault — read a null value as the default in cgp-serde' sidebar_label: 'DeserializeDefault' -sidebar_position: 14 +sidebar_position: 16 description: 'The cgp-serde higher-order provider that reads a null input as the type''s Default and passes any other input to an inner provider named in the wiring.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md index 123abb63..6b839c9e 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md @@ -1,7 +1,7 @@ --- title: 'DeserializeFromJsonReader — read JSON from any serde_json reader in cgp-serde' sidebar_label: 'DeserializeFromJsonReader' -sidebar_position: 20 +sidebar_position: 22 description: 'The cgp-serde provider that reads a value from a string, bytes, or a stream through serde_json and the context''s wiring, rejecting trailing input.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md index b7f1135c..31f4976f 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md @@ -1,7 +1,7 @@ --- title: 'DeserializeFromJsonString — read JSON from a string in cgp-serde' sidebar_label: 'DeserializeFromJsonString' -sidebar_position: 21 +sidebar_position: 23 description: 'The cgp-serde provider that reads a value from any string-like input by wrapping it in a serde_json reader and handing it to an inner provider.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md b/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md new file mode 100644 index 00000000..9d2b40a9 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md @@ -0,0 +1,114 @@ +--- +title: 'DeserializeVariantFields — read an enum with no serialization derive in cgp-serde' +sidebar_label: 'DeserializeVariantFields' +sidebar_position: 15 +description: 'The cgp-serde provider that reads an enum deriving CGP''s variant traits from Serde''s externally tagged form, reading the payload through the context.' +--- + +# `DeserializeVariantFields` + +Read an enum from `{"Variant": payload}`, reading the payload through the context. + +## Overview + +`DeserializeVariantFields` is the reading half of +[`SerializeVariantFields`](./serialize_variant_fields.md). It reads the variant's name, asks the +**context**, the type whose wiring holds the application's choices, to read that variant's payload, +and builds the enum. The enum derives only CGP's variant traits, through +[`#[derive(CgpVariant)]`](/docs/reference/derives/derive_cgp_variant) or the narrower +[`HasFields`](/docs/reference/traits/shape/has_fields) derive, and every variant holds exactly one +unnamed payload. + +## Definition + +```rust +pub struct DeserializeVariantFields; + +#[cgp_impl(DeserializeVariantFields)] +impl<'de, Value> ValueDeserializer<'de, Value> +where + Value: FromFields, + Value::Fields: VariantsDeserializer<'de, Self>, +{ ... } +``` + +[`FromFields`](/docs/reference/traits/shape/from_fields) builds the enum from one variant of its +variant list. `VariantsDeserializer` is a private trait that finds the variant by name or position, +and it requires, for each variant, that the context can read the payload's type. + +## Usage + +Import it from `cgp_serde::providers`, and wire it beside an entry for each variant's payload type: + +```rust +delegate_components! { + App { + open ValueDeserializerComponent; + + @ValueDeserializerComponent.[u64, String, ()]: UseSerde, + @ValueDeserializerComponent.Circle: DeserializeRecordFields, + @ValueDeserializerComponent.Shape: DeserializeVariantFields, + } +} +``` + +## Behavior + +The provider reads the variant's identifier, then its payload through the context. A text format +names the variant, and a binary format such as postcard gives its position in the declaration, as +Serde's derive does. With JSON, `{"Circle":{"radius":3}}` reads as `Shape::Circle`, and +`{"Empty":null}` reads as `Shape::Empty(())` because `()` is wired to `UseSerde`. The payload may +borrow from the input: an enum `Token<'a>` with a `Word(&'a str)` variant reads `{"Word":"hello"}` +without copying the string. + +**The context's entry for `()` decides how a variant with no data is written.** A context that wires +`()` to a provider writing an empty map reads `{"Empty":{}}` and rejects `{"Empty":null}`. Under +either choice, the bare `"Empty"` that Serde's derive uses for a unit variant is rejected, with +`invalid type: unit variant, expected newtype variant`. + +The provider reports an unknown variant with the names it expected, in the same wording as Serde's +derive: + +```text +unknown variant `Square`, expected one of `Circle`, `Rectangle`, `Label`, `Empty` at line 1 column 9 +``` + +A payload of the wrong type fails with that payload's own error, and input that is not a single +variant, such as `{}` or an array, fails with the format's error. + +## Context dependencies + +`CanDeserializeValue<'de, P>` for the payload type `P` of every variant. + +## Pairing + +[`SerializeVariantFields`](./serialize_variant_fields.md) writes the form it reads. + +## When to use it + +**Reach for `DeserializeVariantFields` to read an enum whose payloads should follow the context's +choices.** It reads only Serde's default enum form, with one payload per variant. An enum written in +another form, or with variants that hold several fields, keeps its own Serde impl and is wired to +[`UseSerde`](./use_serde.md). + +## Related constructs + +- [`DeserializeRecordFields`](./deserialize_record_fields.md) is the matching provider for a struct, + and usually reads a variant's payload. + +## The ideas behind it + +- [Derive-free records](../../architecture/derive-free-records.md): reading data through CGP's field + traits. +- [Extensible variants](/docs/concepts/extensible-variants): building an enum from one of its named + variants. + +## Source + +- [`crates/cgp-serde/src/providers/variant.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/variant.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_base64.md b/docs/projects/cgp-serde/reference/providers/serialize_base64.md index 586f4c54..d4269733 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_base64.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_base64.md @@ -1,7 +1,7 @@ --- title: 'SerializeBase64 — encode bytes as base64 in cgp-serde' sidebar_label: 'SerializeBase64' -sidebar_position: 16 +sidebar_position: 18 description: 'The cgp-serde provider that writes bytes as a standard padded base64 string and reads one back into a Vec.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_hex.md b/docs/projects/cgp-serde/reference/providers/serialize_hex.md index 371fb8fc..e2062c06 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_hex.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_hex.md @@ -1,7 +1,7 @@ --- title: 'SerializeHex — encode bytes as hex in cgp-serde' sidebar_label: 'SerializeHex' -sidebar_position: 15 +sidebar_position: 17 description: 'The cgp-serde provider that writes bytes as a lowercase hex string and reads a hex string back, asking the context to write and read the String.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md b/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md index 6c0eb1e4..6eacee35 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md @@ -1,7 +1,7 @@ --- title: 'SerializeRfc3339Date — encode a date as an RFC 3339 string in cgp-serde' sidebar_label: 'SerializeRfc3339Date' -sidebar_position: 17 +sidebar_position: 19 description: 'The cgp-serde provider that writes a DateTime as an RFC 3339 string and reads one back with any offset.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md b/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md index d6a343b6..aa4d805e 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md @@ -1,7 +1,7 @@ --- title: 'SerializeTimestamp — encode a date as a Unix timestamp in cgp-serde' sidebar_label: 'SerializeTimestamp' -sidebar_position: 18 +sidebar_position: 20 description: 'The cgp-serde provider that writes a DateTime as whole seconds since the Unix epoch and reads one back, asking the context to write and read the i64.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md b/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md index 6327add9..d3755746 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md @@ -1,7 +1,7 @@ --- title: 'SerializeToJsonString — write JSON as an operation on the context in cgp-serde' sidebar_label: 'SerializeToJsonString' -sidebar_position: 19 +sidebar_position: 21 description: 'The cgp-serde provider that writes a value as a compact JSON string through the context''s wiring, turning serde_json errors into the context''s error type.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md b/docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md new file mode 100644 index 00000000..b2edfaa4 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md @@ -0,0 +1,125 @@ +--- +title: 'SerializeVariantFields — write an enum with no serialization derive in cgp-serde' +sidebar_label: 'SerializeVariantFields' +sidebar_position: 14 +description: 'The cgp-serde provider that writes any enum deriving CGP''s variant traits in Serde''s externally tagged form, asking the context to write the payload.' +--- + +# `SerializeVariantFields` + +Write an enum as `{"Variant": payload}`, asking the context to write the payload. + +## Overview + +`SerializeVariantFields` serializes an enum that derives nothing from Serde. It reads the enum's +variants through CGP's field traits, which +[`#[derive(CgpVariant)]`](/docs/reference/derives/derive_cgp_variant) provides, and asks the +**context**, the type whose wiring holds the application's choices, to write the active variant's +payload. So one generic provider serves every such enum, and each payload is encoded however the +context encodes its type. + +Every variant must hold exactly one unnamed payload, as `Circle(Circle)` does, which is also what +`CgpVariant` requires. A variant with no data is written with a `()` payload, as `Empty(())`. + +## Definition + +```rust +pub struct SerializeVariantFields; + +#[cgp_impl(SerializeVariantFields)] +impl ValueSerializer +where + Value: ToFieldsRef, + for<'a> Value::FieldsRef<'a>: VariantsSerializer, +{ ... } +``` + +[`ToFieldsRef`](/docs/reference/traits/shape/to_fields_ref) borrows the enum as a list of its +variants, each paired with its name. `VariantsSerializer` is a private trait that finds the active +variant in that list, and it requires, for each variant, that the context can write the payload's +type. + +## Usage + +Import it from `cgp_serde::providers`, and wire it beside an entry for each variant's payload type: + +```rust +#[derive(CgpVariant)] +pub enum Shape { + Circle(Circle), + Label(String), + Empty(()), +} + +delegate_components! { + App { + open ValueSerializerComponent; + + @ValueSerializerComponent.[u64, String, ()]: UseSerde, + @ValueSerializerComponent.Circle: SerializeRecordFields, + @ValueSerializerComponent.Shape: SerializeVariantFields, + } +} +``` + +Here `Circle` is a struct with one `radius: u64` field, so its own entry needs `u64`. + +## Behavior + +The provider writes the active variant as a Serde newtype variant, with the variant's name and its +position in the declaration. With JSON, `Shape::Circle(Circle { radius: 3 })` is written as +`{"Circle":{"radius":3}}`, `Shape::Label("hi".into())` as `{"Label":"hi"}`, and +`Shape::Empty(())` as `{"Empty":null}`, because `()` is wired to `UseSerde`. This is exactly what +Serde's derive writes for the same enum. + +Other formats see the same Serde calls. RON writes `Label("x")`, and postcard writes the variant's +position followed by its payload. Both match Serde's derive, except where the payload is a struct: +structs are written as maps without a declared length, which RON shows in map syntax and postcard +rejects. + +## Context dependencies + +`CanSerializeValue

` for the payload type `P` of every variant. + +## Pairing + +[`DeserializeVariantFields`](./deserialize_variant_fields.md) reads what it writes. + +## When to use it + +**Reach for `SerializeVariantFields` to write an enum whose payloads should follow the context's +choices.** Its limits are worth knowing first: + +- **The enum must not borrow.** An enum with a lifetime, such as `Token<'a>` holding a `&'a str`, + fails to compile with "the type `Token<'a>` does not fulfill the required lifetime", because of a + current limitation in how Rust proves lifetime bounds. `Token<'static>` works, and reading a + borrowing enum with [`DeserializeVariantFields`](./deserialize_variant_fields.md) works too. +- **Only Serde's default enum form is written.** There is no internally tagged, adjacently tagged, + or untagged form, and a variant with no data is `Empty(())` rather than a bare `"Empty"`. +- **An enum that contains itself**, such as an expression tree, fails to compile, as a struct that + contains itself does. + +An enum outside these limits keeps its own Serde impl and is wired to +[`UseSerde`](./use_serde.md). + +## Related constructs + +- [`SerializeRecordFields`](./serialize_record_fields.md) is the matching provider for a struct, and + usually writes a variant's payload. + +## The ideas behind it + +- [Derive-free records](../../architecture/derive-free-records.md): serializing data through CGP's + field traits instead of a serialization derive. +- [Extensible variants](/docs/concepts/extensible-variants): an enum seen as a list of named + variants. + +## Source + +- [`crates/cgp-serde/src/providers/variant_fields.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/variant_fields.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/use_serde.md b/docs/projects/cgp-serde/reference/providers/use_serde.md index eefe97ba..e7ee8b5a 100644 --- a/docs/projects/cgp-serde/reference/providers/use_serde.md +++ b/docs/projects/cgp-serde/reference/providers/use_serde.md @@ -71,8 +71,8 @@ The same provider reads what it writes. ## When to use it **Reach for `UseSerde` for a type whose Serde encoding the application is happy with**, which is -most scalar types, and for any type cgp-serde's generic providers do not cover, such as an enum -with a derived Serde impl. +most scalar types, and for any type cgp-serde's generic providers do not cover, such as an enum in +an internally tagged form, with a derived Serde impl. Reach for [`SerializeRecordFields`](./serialize_record_fields.md) and [`DeserializeRecordFields`](./deserialize_record_fields.md) instead when a struct's fields should diff --git a/docs/projects/cgp-serde/serde-comparison.md b/docs/projects/cgp-serde/serde-comparison.md index 1cd70b47..c60ad4e7 100644 --- a/docs/projects/cgp-serde/serde-comparison.md +++ b/docs/projects/cgp-serde/serde-comparison.md @@ -56,6 +56,7 @@ field while a cgp-serde context chooses per type: | a newtype to change a type's encoding | wire a different provider in a different context | | `#[serde(remote = "…")]` for a type from another crate | wire the type to a provider directly | | `#[derive(Serialize, Deserialize)]` on a struct | derive `CgpData`, and wire the struct to `SerializeRecordFields` and `DeserializeRecordFields` | +| `#[derive(Serialize, Deserialize)]` on an enum of one-value variants | derive `CgpVariant`, and wire the enum to `SerializeVariantFields` and `DeserializeVariantFields` | | a hand-written `DeserializeSeed` for state | a provider that takes the state from the context | | a borrowed `&'de str` field | wire `&'a str` to `UseSerde`, and read from input that can lend it | @@ -67,8 +68,9 @@ providers leave to it: - **Field and container attributes**, such as `rename`, `skip`, `flatten`, `default`, and `deny_unknown_fields`. cgp-serde's struct providers write every field under its Rust name and expect every field to be present. -- **Enums, tuple structs, and tuples.** Serde derives all of them, in several representations for - enums. cgp-serde's struct providers handle structs with named fields. +- **Enum representations, tuple structs, and tuples.** Serde derives all of them, in several + representations for enums. cgp-serde's providers handle structs with named fields, and enums + whose variants each hold one value, in Serde's default externally tagged form. - **Recursive types**, such as a tree whose nodes contain nodes. Serde derives them without difficulty; cgp-serde's generic providers cannot express the recursion, and such a type needs a provider written for it. From f26dcc5bbfebbc7eee918fe4fe305128a5e62ff8 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 17:52:45 +0200 Subject: [PATCH 171/516] Re-wrap paragraphs the SerializeRecordFields rename lengthened Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017CCBh7fScUH7fzq5DeNtyt --- docs/comparisons/reflection.md | 4 ++-- docs/projects/cgp-serde/architecture/crate-layout.md | 4 ++-- .../cgp-serde/architecture/derive-free-records.md | 6 +++--- .../cgp-serde/architecture/reentrant-providers.md | 10 +++++----- docs/projects/cgp-serde/architecture/serde-bridge.md | 3 ++- docs/projects/cgp-serde/examples/basic.md | 12 ++++++------ docs/projects/cgp-serde/examples/messages.md | 5 +++-- docs/projects/cgp-serde/guides/debugging-wiring.md | 12 ++++++------ docs/projects/cgp-serde/guides/wiring-a-context.md | 4 ++-- docs/projects/cgp-serde/reference/index.md | 4 ++-- .../reference/providers/deserialize_record_fields.md | 12 ++++++------ .../reference/providers/serialize_record_fields.md | 11 ++++++----- 12 files changed, 45 insertions(+), 42 deletions(-) diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index 53e7dca7..90e678f9 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -115,8 +115,8 @@ Zig-style `comptime` outside its immediate scope. The feature remains experiment CGP encodes a type's structure as types and processes it with trait resolution. The example fragments form a field writer modeled on [`cgp-serde`](https://github.com/contextgeneric/cgp-serde) -'s `SerializeRecordFields` provider, which does the same over serde's `Serializer` . Its context is an -[environmental context](/docs/reference/glossary#environmental-context) : `App` stands for an +'s `SerializeRecordFields` provider, which does the same over serde's `Serializer` . Its context is +an [environmental context](/docs/reference/glossary#environmental-context) : `App` stands for an application and chooses how each field type is written. The written `Value` is a type parameter, so the component is [parameter-targeted](/docs/reference/glossary#parameter-targeted-component) . diff --git a/docs/projects/cgp-serde/architecture/crate-layout.md b/docs/projects/cgp-serde/architecture/crate-layout.md index 4f002e39..9132ed0c 100644 --- a/docs/projects/cgp-serde/architecture/crate-layout.md +++ b/docs/projects/cgp-serde/architecture/crate-layout.md @@ -54,8 +54,8 @@ services](./context-services.md). Every crate sorts its items into modules by kind, so an item's kind says where to import it from: - **`components`** — the serialization components, in `cgp-serde`. -- **`providers`** — the providers, in every crate, as in `cgp_serde::providers::SerializeRecordFields` or - `cgp_serde_extra::providers::SerializeHex`. +- **`providers`** — the providers, in every crate, as in + `cgp_serde::providers::SerializeRecordFields` or `cgp_serde_extra::providers::SerializeHex`. - **`types`** — the adapter types, in `cgp-serde`. - **`traits`** — components that support a provider, such as the allocation component in `cgp-serde-alloc` and the arena getter in `cgp-serde-typed-arena`. diff --git a/docs/projects/cgp-serde/architecture/derive-free-records.md b/docs/projects/cgp-serde/architecture/derive-free-records.md index 93af35be..797e74bf 100644 --- a/docs/projects/cgp-serde/architecture/derive-free-records.md +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -35,9 +35,9 @@ pub struct Payload { ``` Two generic providers are written once against what `CgpData` exposes. -[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) walks the field list and writes the -struct as a map from each field's name to its value, asking the **context**, the type whose wiring -holds an application's choices, to serialize each value. +[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) walks the field list +and writes the struct as a map from each field's name to its value, asking the **context**, the type +whose wiring holds an application's choices, to serialize each value. [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) reads the map back, asking the context to deserialize each value, and fills the struct in field by field, reporting any field the input left out. A context wires the struct to them like any other type: diff --git a/docs/projects/cgp-serde/architecture/reentrant-providers.md b/docs/projects/cgp-serde/architecture/reentrant-providers.md index 9fd05160..07ae5049 100644 --- a/docs/projects/cgp-serde/architecture/reentrant-providers.md +++ b/docs/projects/cgp-serde/architecture/reentrant-providers.md @@ -20,16 +20,16 @@ is written however Serde's impl for `Vec` writes it. The choice is fixed whe written. A cgp-serde provider makes the same call on the context instead. The struct provider, -[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md), serializes each field by asking the -context to serialize the field's type. The collection provider, +[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md), serializes each field +by asking the context to serialize the field's type. The collection provider, [`SerializeIterator`](../reference/providers/serialize_iterator.md), does the same for each item. The context answers each request from its wiring table, so a context that wires `Vec` to hex gets hex for every `Vec` it serializes: a top-level value, a field, or an item in a list inside a field. -This also keeps each provider small. `SerializeRecordFields` knows how to walk a struct and nothing about -the fields' types, and `SerializeIterator` knows how to walk a collection and nothing about the -items. Each is written once, generically, and the context composes them. +This also keeps each provider small. `SerializeRecordFields` knows how to walk a struct and nothing +about the fields' types, and `SerializeIterator` knows how to walk a collection and nothing about +the items. Each is written once, generically, and the context composes them. ## Re-entering directly diff --git a/docs/projects/cgp-serde/architecture/serde-bridge.md b/docs/projects/cgp-serde/architecture/serde-bridge.md index eabb7602..1a2a8f7e 100644 --- a/docs/projects/cgp-serde/architecture/serde-bridge.md +++ b/docs/projects/cgp-serde/architecture/serde-bridge.md @@ -49,7 +49,8 @@ where `SerdeSerialize` is Serde's `Serialize`, imported under another name. Every `Serialize` impl, in the standard library or in any crate, is therefore available to a context without a cgp-serde provider being written for it; the context wires the type to `UseSerde`. This is also how a context handles a -type that cgp-serde's generic providers do not cover, such as an enum in an internally tagged form, with a derived impl. +type that cgp-serde's generic providers do not cover, such as an enum in an internally tagged form, +with a derived impl. The trade is that the context's choices stop at that value. The type's own impl serializes its contents, so a `Vec` inside it is written the way that impl writes it, whatever the context diff --git a/docs/projects/cgp-serde/examples/basic.md b/docs/projects/cgp-serde/examples/basic.md index f1f39e82..5857afca 100644 --- a/docs/projects/cgp-serde/examples/basic.md +++ b/docs/projects/cgp-serde/examples/basic.md @@ -155,8 +155,8 @@ The providers each do one job: string. - [`SerializeHex`](../reference/providers/serialize_hex.md) writes bytes as a hex string, and reads them back. -- [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) writes a struct as a map from - field names to values, and +- [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) writes a struct as a + map from field names to values, and [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) reads one back. The two directions are wired separately, so they can name different providers. `String` is written @@ -165,10 +165,10 @@ in both directions, because one struct implements both halves of the hex encodin ## The struct's provider asks the context for its fields -`SerializeRecordFields` knows how to walk a struct, but not how to encode any field. For each field, it -asks the context to serialize the field's type, and the context's wiring answers. That is why `App` -has entries for `u64`, `String`, and `Vec` as well as for `Payload`: they are the types the -struct's provider hands back. +`SerializeRecordFields` knows how to walk a struct, but not how to encode any field. For each field, +it asks the context to serialize the field's type, and the context's wiring answers. That is why +`App` has entries for `u64`, `String`, and `Vec` as well as for `Payload`: they are the types +the struct's provider hands back. The same handing back is what lets a choice reach every level of a nested value. Wire `Vec` to `SerializeHex`, and every `Vec` the context serializes is hex, wherever it sits. diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md index 01f33d16..37c42960 100644 --- a/docs/projects/cgp-serde/examples/messages.md +++ b/docs/projects/cgp-serde/examples/messages.md @@ -211,8 +211,9 @@ they do not, because each choice holds only within the context that makes it. Neither table says anything about where a `Vec` appears, and yet every byte field in the archive, at all three levels, follows its context's choice. That is because no provider encodes the -values inside the one it is given. [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) -walks a struct and asks the context to serialize each field, and +values inside the one it is given. +[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) walks a struct and asks +the context to serialize each field, and [`SerializeIterator`](../reference/providers/serialize_iterator.md) walks a collection and asks the context to serialize each item. Each of those requests goes back through the same table, so the context's choice for a type applies wherever the type turns up. [Re-entrant diff --git a/docs/projects/cgp-serde/guides/debugging-wiring.md b/docs/projects/cgp-serde/guides/debugging-wiring.md index a8d379ac..0a3d0bb2 100644 --- a/docs/projects/cgp-serde/guides/debugging-wiring.md +++ b/docs/projects/cgp-serde/guides/debugging-wiring.md @@ -21,8 +21,8 @@ shorter and clearer there than at the first call. ## A type the traversal reaches has no entry **The most common mistake is a missing entry for a nested type.** Here `Payload` is wired to -[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md), but the type of its `data` field -has no entry: +[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md), but the type of its +`data` field has no entry: ```rust #[derive(CgpData)] @@ -64,10 +64,10 @@ error[E0277]: [CGP-E001] the consumer trait `CanSerializeValue` is not └─ [CGP-E107] context `App` does not contain any delegate entry for `@ValueSerializerComponent.Vec` ``` -The chain reads from the top down: serializing `Payload` goes to `SerializeRecordFields`, which walks the -fields to `data`, which asks the context for a `Vec`, which the table does not have. However -deep the missing type sits, the root cause names it. The fix is an entry for `Vec`, such as -`@ValueSerializerComponent.Vec: SerializeHex`. +The chain reads from the top down: serializing `Payload` goes to `SerializeRecordFields`, which +walks the fields to `data`, which asks the context for a `Vec`, which the table does not have. +However deep the missing type sits, the root cause names it. The fix is an entry for `Vec`, such +as `@ValueSerializerComponent.Vec: SerializeHex`. ## An entry for a type no field has diff --git a/docs/projects/cgp-serde/guides/wiring-a-context.md b/docs/projects/cgp-serde/guides/wiring-a-context.md index d65da32a..648ca4e9 100644 --- a/docs/projects/cgp-serde/guides/wiring-a-context.md +++ b/docs/projects/cgp-serde/guides/wiring-a-context.md @@ -70,8 +70,8 @@ List the types a traversal touches, not only the types the data names. Start fro type, and follow what each provider asks the context for, which each provider's [reference page](../reference/index.md) states: -- **A struct** wired to [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) or - [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) needs an entry +- **A struct** wired to [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) + or [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) needs an entry for each field's type. - **A collection** needs an entry of its own, besides its item type's. Writing one with [`SerializeIterator`](../reference/providers/serialize_iterator.md) also asks for the item as a diff --git a/docs/projects/cgp-serde/reference/index.md b/docs/projects/cgp-serde/reference/index.md index af40dd26..95369d89 100644 --- a/docs/projects/cgp-serde/reference/index.md +++ b/docs/projects/cgp-serde/reference/index.md @@ -27,8 +27,8 @@ to. ## Serialization providers Every provider below implements the serializing component, the deserializing one, or both, and is -imported from its crate's `providers` module, such as `cgp_serde::providers::SerializeRecordFields`. The -last column is what the provider asks the context to encode in turn; see [re-entrant +imported from its crate's `providers` module, such as `cgp_serde::providers::SerializeRecordFields`. +The last column is what the provider asks the context to encode in turn; see [re-entrant providers](../architecture/reentrant-providers.md). | Provider | Crate | Direction | Handles | Asks the context for | diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md index 48a39944..7c508902 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md @@ -12,12 +12,12 @@ field. ## Overview -`DeserializeRecordFields` is the reading half of [`SerializeRecordFields`](./serialize_record_fields.md). It -reads a map, asks the **context**, the type whose wiring holds the application's choices, to read -each field's value, and collects the values in CGP's builder for the struct until every field is -present. The struct derives only CGP's field traits, through -[`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) or the narrower -[`HasFields`](/docs/reference/traits/shape/has_fields) and +`DeserializeRecordFields` is the reading half of +[`SerializeRecordFields`](./serialize_record_fields.md). It reads a map, asks the **context**, the +type whose wiring holds the application's choices, to read each field's value, and collects the +values in CGP's builder for the struct until every field is present. The struct derives only CGP's +field traits, through [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) or the +narrower [`HasFields`](/docs/reference/traits/shape/has_fields) and [`BuildField`](/docs/reference/traits/builder/build_field) derives. ## Definition diff --git a/docs/projects/cgp-serde/reference/providers/serialize_record_fields.md b/docs/projects/cgp-serde/reference/providers/serialize_record_fields.md index 9135efe0..9bcc35c1 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_record_fields.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_record_fields.md @@ -11,8 +11,8 @@ Write a struct as a map from each field's name to its value, asking the context ## Overview -`SerializeRecordFields` serializes a struct that derives nothing from Serde. It reads the struct's field -list through CGP's field traits, which +`SerializeRecordFields` serializes a struct that derives nothing from Serde. It reads the struct's +field list through CGP's field traits, which [`#[derive(CgpData)]`](/docs/reference/derives/derive_cgp_data) provides, and asks the **context**, the type whose wiring holds the application's choices, to write each field's value. So one generic provider serves every struct, and each field is encoded however the context encodes its type. @@ -80,9 +80,10 @@ shape: a map keyed by Rust field names. ## When to use it -**Reach for `SerializeRecordFields` for a struct whose fields should follow the context's choices**, and -for any struct whose crate should not depend on `serde`. For a struct that already derives Serde's -`Serialize` and needs no per-application choice, [`UseSerde`](./use_serde.md) uses that derive. +**Reach for `SerializeRecordFields` for a struct whose fields should follow the context's choices**, +and for any struct whose crate should not depend on `serde`. For a struct that already derives +Serde's `Serialize` and needs no per-application choice, [`UseSerde`](./use_serde.md) uses that +derive. ## Related constructs From 986d5c6b1858f035489fff7c575c57e3f55c79a6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 18:05:50 +0200 Subject: [PATCH 172/516] Run the cgp-serde examples from the cgp-serde-examples crate The examples are now Cargo examples run with `cargo run -p cgp-serde-examples --example `, each checked by its own test. Update the run instructions, source links, the messages snippet, and the pages that called them tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017CCBh7fScUH7fzq5DeNtyt --- .../architecture/context-services.md | 2 +- .../cgp-serde/architecture/crate-layout.md | 4 +- .../architecture/derive-free-records.md | 4 +- docs/projects/cgp-serde/examples/basic.md | 55 +++++++++---------- docs/projects/cgp-serde/examples/index.md | 21 +++---- docs/projects/cgp-serde/examples/messages.md | 26 +++++---- .../cgp-serde/guides/debugging-wiring.md | 2 +- docs/projects/cgp-serde/index.md | 15 ++--- .../providers/allocate_with_arena.md | 2 +- .../providers/deserialize_and_allocate.md | 2 +- .../reference/providers/deserialize_extend.md | 2 +- .../providers/deserialize_from_json_string.md | 2 +- .../providers/deserialize_record_fields.md | 4 +- 13 files changed, 73 insertions(+), 68 deletions(-) diff --git a/docs/projects/cgp-serde/architecture/context-services.md b/docs/projects/cgp-serde/architecture/context-services.md index 7bd9ac8b..c5c7cf01 100644 --- a/docs/projects/cgp-serde/architecture/context-services.md +++ b/docs/projects/cgp-serde/architecture/context-services.md @@ -81,7 +81,7 @@ impl<'a, Value: 'a> Allocator<'a, Value> { } ``` -A context wires all three. These are the relevant entries from the repository's arena test, where +A context wires all three. These are the relevant entries from the repository's arena example, where the context holds the arena in a field named `arena`: ```rust diff --git a/docs/projects/cgp-serde/architecture/crate-layout.md b/docs/projects/cgp-serde/architecture/crate-layout.md index 9132ed0c..b12b7ca2 100644 --- a/docs/projects/cgp-serde/architecture/crate-layout.md +++ b/docs/projects/cgp-serde/architecture/crate-layout.md @@ -31,8 +31,8 @@ base64 compiles `hex` and not `base64`. None of the library crates names an erro JSON providers raise their errors into whatever error type the context wires, so the application chooses it, as the [`basic`](../examples/basic.md) example does with `anyhow`. -The repository's sixth crate, `cgp-serde-tests`, holds the tests the -[examples](../examples/index.md) walk through. +Two more crates are not published. `cgp-serde-examples` holds the programs the +[examples](../examples/index.md) walk through, and `cgp-serde-tests` holds the library's tests. ## A data crate needs none of them diff --git a/docs/projects/cgp-serde/architecture/derive-free-records.md b/docs/projects/cgp-serde/architecture/derive-free-records.md index 797e74bf..ac386728 100644 --- a/docs/projects/cgp-serde/architecture/derive-free-records.md +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -60,8 +60,8 @@ field traits: writing needs the field list, from [`HasFields`](/docs/reference/traits/shape/has_fields), and access to each field, from [`HasField`](/docs/reference/traits/field-access/has_field); reading needs the field list and the field-by-field builder, from [`BuildField`](/docs/reference/traits/builder/build_field). `CgpData` -derives all three. A struct that derives only the narrower ones, as the arena tests' structs derive -`HasFields` and `BuildField` for reading, works in the directions they cover. +derives all three. A struct that derives only the narrower ones, as the arena examples' structs +derive `HasFields` and `BuildField` for reading, works in the directions they cover. The same derive serves every other generic CGP code that works over fields, such as builders and conversions between struct [shapes](/docs/reference/glossary#shape), so one opt-in covers more than serialization. A type whose owner diff --git a/docs/projects/cgp-serde/examples/basic.md b/docs/projects/cgp-serde/examples/basic.md index 5857afca..d3bb84ef 100644 --- a/docs/projects/cgp-serde/examples/basic.md +++ b/docs/projects/cgp-serde/examples/basic.md @@ -1,17 +1,16 @@ --- sidebar_label: 'basic' sidebar_position: 1 -description: 'A cgp-serde test that writes a struct to JSON and reads it back, with no serialization derive and each field type''s encoding chosen by the context.' +description: 'A cgp-serde example that writes a struct to JSON and reads it back, with no serialization derive and each field type''s encoding chosen by the context.' --- # Write a struct to JSON and read it back -This test writes a struct to a JSON string and reads it back, through a **context**, the type whose -wiring holds the application's choices, which decides how each of the struct's field types is -encoded. It is an example from -[cgp-serde](../index.md), which rebuilds Serde's `Serialize` and `Deserialize` traits as components -of [CGP](/docs/). The struct derives nothing from Serde, and its bytes come out as hex because one -wiring line says so. +This example writes a struct to a JSON string and reads it back, through a **context**, the type +whose wiring holds the application's choices, which decides how each of the struct's field types is +encoded. It is an example from [cgp-serde](../index.md), which rebuilds Serde's `Serialize` and +`Deserialize` traits as components of [CGP](/docs/). The struct derives nothing from Serde, and its +bytes come out as hex because one wiring line says so. :::tip @@ -45,26 +44,23 @@ moves both decisions out of the struct and into the application's wiring. From the root of the [cgp-serde repository](https://github.com/contextgeneric/cgp-serde): ```sh -cargo test -p cgp-serde-tests basic +cargo run -p cgp-serde-examples --example basic ``` -The test passes: +It prints the JSON the struct serializes to, and the value read back from it: ```text -test tests::basic::test_basic_serialization ... ok +serialized: {"quantity":42,"message":"hello","data":"010203"} +deserialized: Payload { quantity: 42, message: "hello", data: [1, 2, 3] } ``` -It asserts that the struct serializes to exactly this JSON, and that reading the JSON back gives the -original value: - -```json -{"quantity":42,"message":"hello","data":"010203"} -``` +`cargo test -p cgp-serde-examples --example basic` checks both: the exact JSON, and that reading it +back gives the original value. ## The struct derives nothing from Serde The data type is an ordinary struct, from -[`basic.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-tests/src/tests/basic.rs): +[`basic.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-examples/examples/basic.rs): ```rust #[derive(Debug, Eq, PartialEq, CgpData)] @@ -75,17 +71,17 @@ pub struct Payload { } ``` -`Debug`, `Eq`, and `PartialEq` are there for the test's assertions. The only other derive is CGP's -[`CgpData`](/docs/reference/derives/derive_cgp_data), which exposes the struct's field names and -types to generic code and lets generic code build the struct one field at a time. It is not specific -to serialization, and nothing in the struct says how any field is encoded. cgp-serde's record -providers read what `CgpData` exposes, as [derive-free +`Debug`, `Eq`, and `PartialEq` are there to print the value and for the example's test. The only +other derive is CGP's [`CgpData`](/docs/reference/derives/derive_cgp_data), which exposes the +struct's field names and types to generic code and lets generic code build the struct one field at a +time. It is not specific to serialization, and nothing in the struct says how any field is encoded. +cgp-serde's record providers read what `CgpData` exposes, as [derive-free records](../architecture/derive-free-records.md) explains. ## One context holds every choice -The test runs on `App`, a type that stands for this application, which is where its choices live. It -has no fields, because every choice it makes is in its wiring: +The example runs on `App`, a type that stands for this application, which is where its choices live. +It has no fields, because every choice it makes is in its wiring: ```rust pub struct App; @@ -180,11 +176,11 @@ The same handing back is what lets a choice reach every level of a nested value. The last two entries make JSON encoding something `App` can do. They are keyed on CGP's [`TryComputer`](/docs/reference/components/handler/try_computer), an interface for a fallible computation chosen by a marker type, and the markers `SerializeJson` and `DeserializeJson` pick -the JSON providers. The test calls both through `try_compute`: +the JSON providers. The example calls both through `try_compute`: ```rust let serialized = context - .try_compute(PhantomData::, &value) + .try_compute(PhantomData::, &payload()) .unwrap(); let deserialized: Payload = context @@ -209,7 +205,7 @@ handling](/docs/concepts/modular-error-handling) explains how. ## Checking both directions -Wiring is checked when it is used, so the test asserts that every entry resolves with +Wiring is checked when it is used, so the example asserts that every entry resolves with [`check_components!`](/docs/reference/macros/check_components), once per direction: ```rust @@ -247,7 +243,8 @@ the same name. Change the encoding of the bytes from hex to base64 by replacing `SerializeHex` with `SerializeBase64` in both `Vec` entries, and importing it from `cgp_serde_extra::providers`. -Nothing else changes. Run the test again, and its first assertion fails, printing the new JSON: +Nothing else changes. Run the example's test again, and its first assertion fails, printing the new +JSON: ```text assertion `left == right` failed @@ -261,7 +258,7 @@ the encoding lived only in the wiring. ## The pattern -This test shows **serialization as a choice made by the context, one type at a time**. The +This example shows **serialization as a choice made by the context, one type at a time**. The component takes the encoded value as a parameter, so the context, not the data type, chooses the provider for each value type, and a provider for a struct asks the context about the struct's fields. The same move makes the error type the context's choice too. [Modularity diff --git a/docs/projects/cgp-serde/examples/index.md b/docs/projects/cgp-serde/examples/index.md index ad44d88f..c6176349 100644 --- a/docs/projects/cgp-serde/examples/index.md +++ b/docs/projects/cgp-serde/examples/index.md @@ -1,17 +1,17 @@ --- sidebar_label: 'Overview' sidebar_position: 0 -description: 'The cgp-serde tests as short tutorials: a JSON round trip with no serialization derive, and one value encoded two ways by two applications.' +description: 'The cgp-serde examples as short tutorials: a JSON round trip with no serialization derive, and one value encoded two ways by two applications.' --- # cgp-serde examples -These pages walk through the tests in the [cgp-serde -repository](https://github.com/contextgeneric/cgp-serde), one test per page. The tests are the -repository's runnable examples. [cgp-serde](../index.md) rebuilds Serde's `Serialize` and -`Deserialize` traits as components of [CGP](/docs/), so that each application chooses how a type is -encoded. Each page runs a test, explains how its wiring produces what it prints, and names the CGP -pattern it shows, so the pages work as short tutorials on those patterns. +These pages walk through the examples in the [cgp-serde +repository](https://github.com/contextgeneric/cgp-serde), one example per page. +[cgp-serde](../index.md) rebuilds Serde's `Serialize` and `Deserialize` traits as components of +[CGP](/docs/), so that each application chooses how a type is encoded. Each page runs an example, +explains how its wiring produces what it prints, and names the CGP pattern it shows, so the pages +work as short tutorials on those patterns. The pages are in the order they teach. Each stands alone, but a reader new to cgp-serde should start with [`basic`](./basic.md), since the later pages build on the wiring it introduces. @@ -29,9 +29,10 @@ smaller encoding example. Neither is required reading; each page links what it r ## Running an example -Clone the repository and run an example from its root with `cargo test -p cgp-serde-tests `. -Add `-- --nocapture` to see what a test prints. The repository's toolchain file selects the Rust -version, and no example needs a network or any program outside the build. +Clone the repository and run an example from its root with +`cargo run -p cgp-serde-examples --example `. Each example also checks what it prints in a +test, which `cargo test -p cgp-serde-examples --example ` runs. The repository's toolchain +file selects the Rust version, and no example needs a network or any program outside the build. ## The examples diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md index 37c42960..957cf302 100644 --- a/docs/projects/cgp-serde/examples/messages.md +++ b/docs/projects/cgp-serde/examples/messages.md @@ -1,12 +1,12 @@ --- sidebar_label: 'messages' sidebar_position: 2 -description: 'A cgp-serde test in which two application contexts encode one nested value differently, hex and RFC 3339 against base64 and Unix time.' +description: 'A cgp-serde example in which two application contexts encode one nested value differently, hex and RFC 3339 against base64 and Unix time.' --- # Encode one value two ways in two applications -This test serializes one nested archive of messages twice, under two applications that disagree +This example serializes one nested archive of messages twice, under two applications that disagree about how bytes and dates should look. It is an example from [cgp-serde](../index.md), which rebuilds Serde's `Serialize` and `Deserialize` traits as components of [CGP](/docs/). The data types name no encoding, and the two applications differ in three wiring lines, which is the whole @@ -43,13 +43,14 @@ application its own choices. ## Run it From the root of the [cgp-serde repository](https://github.com/contextgeneric/cgp-serde), run the -test: +example: ```sh -cargo test -p cgp-serde-tests messages +cargo run -p cgp-serde-examples --example messages ``` -It serializes the same archive twice and checks each document against the exact JSON below. From +It serializes the same archive twice and prints each document, shown below. +`cargo test -p cgp-serde-examples --example messages` checks both against this exact JSON. From the first application, `AppA`, bytes are hex and dates are RFC 3339 strings: ```json @@ -107,7 +108,7 @@ From the second, `AppB`, bytes are base64 and dates are Unix timestamps: ## The data names no encoding The archive is three nested structs, from -[`messages.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-tests/src/tests/messages.rs): +[`messages.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-examples/examples/messages.rs): ```rust #[derive(CgpData)] @@ -242,11 +243,16 @@ without it. Each context's wiring is asserted by a [`check_components!`](/docs/reference/macros/check_components) table listing the seven types it -serializes. Then the test hands each context and the archive to `serde_json`: +serializes. Then the example hands each context and the archive to `serde_json`, through a helper +that accepts any context able to serialize the archive: ```rust -let serialized_a = - serde_json::to_string_pretty(&SerializeWithContext::new(&AppA, &archive)).unwrap(); +fn to_pretty_json(context: &Context, archive: &MessagesArchive) -> String +where + Context: CanSerializeValue, +{ + serde_json::to_string_pretty(&SerializeWithContext::new(context, archive)).unwrap() +} ``` [`SerializeWithContext`](../reference/types/serialize_with_context.md) pairs a context with a value @@ -272,7 +278,7 @@ cause for the classes it recognizes, and the tool does not yet reshape every cla ## The pattern -This test shows **two applications choosing different implementations for the same types, without +This example shows **two applications choosing different implementations for the same types, without a conflict**. Each application is a context, the serialized value is a parameter of the component, and a context's table decides the provider for each value type, including types from other crates. Because every provider hands nested values back to the context, one entry decides a type's encoding diff --git a/docs/projects/cgp-serde/guides/debugging-wiring.md b/docs/projects/cgp-serde/guides/debugging-wiring.md index 0a3d0bb2..63756767 100644 --- a/docs/projects/cgp-serde/guides/debugging-wiring.md +++ b/docs/projects/cgp-serde/guides/debugging-wiring.md @@ -95,7 +95,7 @@ context. Hex, base64, and RFC 3339 dates need `String` the same way. The **A service a provider takes from the context.** Wiring `&'b Coord` to [`DeserializeAndAllocate`](../reference/providers/deserialize_and_allocate.md) without an entry for `AllocatorComponent` fails, because the provider allocates through the context. In the repository's -arena test, with the allocator entry removed, the check on the borrowed types reports: +arena example, with the allocator entry removed, the check on the borrowed types reports: ```text error[E0277]: [CGP-E001] the consumer traits `CanDeserializeValue<&Coord>` and `CanDeserializeValue>` are not implemented for context `App<'_>` diff --git a/docs/projects/cgp-serde/index.md b/docs/projects/cgp-serde/index.md index e06bab32..151113a2 100644 --- a/docs/projects/cgp-serde/index.md +++ b/docs/projects/cgp-serde/index.md @@ -117,16 +117,17 @@ know first: ## The examples -The examples are the repository's tests, walked through as short tutorials in the order they teach: +The examples are the repository's runnable programs, walked through as short tutorials in the order +they teach: - [`basic`](./examples/basic.md) — one struct written to JSON and read back, with its bytes as hex and its errors in the context's error type. - [`messages`](./examples/messages.md) — one nested archive encoded two ways by two contexts that differ in three wiring lines. -Two more tests deserialize borrowed values into an arena that the context supplies. Their pages are -still being written, and [context services](./architecture/context-services.md) explains the design -they show. +Two more examples deserialize borrowed values into an arena that the context supplies. Their pages +are still being written, and [context services](./architecture/context-services.md) explains the +design they show. ## The rest of the section @@ -140,9 +141,9 @@ describes where the design stops. ## Running it -Clone the [repository](https://github.com/contextgeneric/cgp-serde) and run the examples from its -root with `cargo test -p cgp-serde-tests`. The repository's toolchain file selects the Rust version, -and no example needs a network or any program outside the build. +Clone the [repository](https://github.com/contextgeneric/cgp-serde) and run an example from its root +with `cargo run -p cgp-serde-examples --example `. The repository's toolchain file selects the +Rust version, and no example needs a network or any program outside the build. To use cgp-serde from your own crate, depend on its crates from the repository by git: `cgp-serde` for the components and core providers, and `cgp-serde-extra`, `cgp-serde-json`, `cgp-serde-alloc`, diff --git a/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md index 3e73fc2c..a77bffa0 100644 --- a/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md +++ b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md @@ -33,7 +33,7 @@ impl<'a, Value: 'a> Allocator<'a, Value> { ... } Import it from `cgp_serde_typed_arena::providers`. Wire it as the context's allocator, and point the arena getter at the field that holds the arena with -[`UseField`](/docs/reference/providers/use_field). From the repository's arena test: +[`UseField`](/docs/reference/providers/use_field). From the repository's arena example: ```rust #[derive(HasField)] diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md index 6f024458..78044e23 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md @@ -28,7 +28,7 @@ impl<'de, 'a, Value> ValueDeserializer<'de, &'a Value> { ... } ## Usage Import it from `cgp_serde_alloc::providers`, and wire it for the reference type, beside an entry for -the owned type and an allocator. From the repository's arena test: +the owned type and an allocator. From the repository's arena example: ```rust AllocatorComponent: diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_extend.md b/docs/projects/cgp-serde/reference/providers/deserialize_extend.md index 230e9a73..4ed2c8c1 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_extend.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_extend.md @@ -34,7 +34,7 @@ The `IntoIterator` bound only names the collection's item type; the provider nev ## Usage Import it from `cgp_serde::providers`, and wire each collection type the context reads, beside its -item type. The repository's arena test reads a vector of references into an arena: +item type. The repository's arena example reads a vector of references into an arena: ```rust @ValueDeserializerComponent.<'b> Vec<&'b Coord>: diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md index 31f4976f..0aee474f 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md @@ -62,7 +62,7 @@ let deserialized: Payload = context The provider wraps the string in a `StrRead` and calls the inner provider with it, which reads the value and checks for trailing input. Because it must work for a reader of any lifetime, the value it produces cannot borrow from the input string. A value that borrows from elsewhere is unaffected: the -repository's arena test reads a `Payload<'a>` that borrows from the context's arena through this +repository's arena example reads a `Payload<'a>` that borrows from the context's arena through this provider. ## Context dependencies diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md index 7c508902..cd1b83c6 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_record_fields.md @@ -77,8 +77,8 @@ position to the message: `invalid type: sequence, expected map`. Only structs with named fields work, since a field's name is its key. A struct with a lifetime works -the same way: the arena test's `Payload<'a>` is read with this provider, its `Vec<&'a Coord>` field -through [`DeserializeExtend`](./deserialize_extend.md). +the same way: the arena example's `Payload<'a>` is read with this provider, its `Vec<&'a Coord>` +field through [`DeserializeExtend`](./deserialize_extend.md). ## Context dependencies From 8f3e770b704033dd772f3add29d3220b8bb3f65a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 19:37:43 +0200 Subject: [PATCH 173/516] Add the cgp-serde events example page A tutorial page for the events example: an enum of structs written and read back by two applications with their own encodings, what happens when each reads the other's JSON, and a change to try. List it in the examples index and the section index. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017CCBh7fScUH7fzq5DeNtyt --- docs/projects/cgp-serde/examples/events.md | 213 +++++++++++++++++++++ docs/projects/cgp-serde/examples/index.md | 6 +- docs/projects/cgp-serde/index.md | 2 + 3 files changed, 219 insertions(+), 2 deletions(-) create mode 100644 docs/projects/cgp-serde/examples/events.md diff --git a/docs/projects/cgp-serde/examples/events.md b/docs/projects/cgp-serde/examples/events.md new file mode 100644 index 00000000..62c5aed2 --- /dev/null +++ b/docs/projects/cgp-serde/examples/events.md @@ -0,0 +1,213 @@ +--- +sidebar_label: 'events' +sidebar_position: 3 +description: 'A cgp-serde example in which two applications write and read back a batch of chat events, an enum of records, each with its own encodings, and misread each other''s JSON.' +--- + +# Write and read back an enum of records in two applications + +This example writes a batch of chat events to JSON and reads it back, under two applications that +encode bytes and dates differently, and then has each application read the other's JSON. It is an +example from [cgp-serde](../index.md), which rebuilds Serde's `Serialize` and `Deserialize` traits +as components of [CGP](/docs/). The events are an enum whose variants hold structs, and none of the +types derives anything from Serde. + +:::tip + +### New to CGP? + +[`messages`](./messages.md) introduces two applications with their own wiring, which this page +extends to an enum and to reading. For CGP itself, the [Hello World tutorial](/docs/tutorials/hello) +shows contexts and wiring with a smaller program. This page can be read without them. + +::: + +## The problem + +A chat client syncs a batch of events with a server. Each event is one of several kinds, a message +posted, edited, or reacted to, or the history cleared, and each kind carries its own data. The +server stores batches compactly, with bytes as base64 and dates as Unix timestamps. A debugging +inspector writes the same batches for people to read, with bytes as hex and dates as RFC 3339 +strings. Both read batches back, and both use the same Rust types. + +### Without CGP + +With Serde, the event enum and its structs each have one `Serialize` and one `Deserialize` impl in +the whole program, so the encoding of their byte and date fields is fixed by `#[serde(with = …)]` +attributes on the types. Two applications that want different encodings need two copies of the +types, or wrappers and conversions around them. This page keeps one set of types and gives each +application its own choices, in both directions. + +## Run it + +From the root of the [cgp-serde repository](https://github.com/contextgeneric/cgp-serde), run the +example: + +```sh +cargo run -p cgp-serde-examples --example events +``` + +It prints the batch as each application writes it, confirms that each reads its own JSON back into +the same batch, and prints the error each gives reading the other's. The first event, from the +server and then from the inspector, condensed onto one line each: + +```json +{"Posted": {"message_id": 1, "author_id": 2, "date": 1762179300, "encrypted_data": "SGVsbG8="}} +{"Posted": {"message_id": 1, "author_id": 2, "date": "2025-11-03T14:15:00+00:00", "encrypted_data": "48656c6c6f"}} +``` + +`cargo test -p cgp-serde-examples --example events` checks both documents exactly, both round trips, +and both errors. + +## An enum whose variants hold structs + +The event is an enum deriving CGP's +[`CgpVariant`](/docs/reference/derives/derive_cgp_variant), and each variant holds a struct deriving +[`CgpData`](/docs/reference/derives/derive_cgp_data), from +[`events.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde-examples/examples/events.rs): + +```rust +#[derive(Debug, PartialEq, CgpData)] +pub struct Posted { + pub message_id: u64, + pub author_id: u64, + pub date: DateTime, + pub encrypted_data: Vec, +} + +#[derive(Debug, PartialEq, CgpVariant)] +pub enum ChatEvent { + Posted(Posted), + Edited(Edited), + Reacted(Reacted), + HistoryCleared(()), +} + +#[derive(Debug, PartialEq, CgpData)] +pub struct SyncBatch { + pub device_key: Vec, + pub events: Vec, +} +``` + +`Edited` holds a message id, a date, and new encrypted data, and `Reacted` holds a message id, an +author id, and an emoji as a `String`, since many emoji, such as 👍🏽, are more than one `char`. Every +variant holds exactly one value, which `CgpVariant` requires, so `HistoryCleared`, which carries no +data, holds `()`. The batch is a struct holding a `Vec` of events, so structs sit inside the enum +and the enum sits inside a struct. + +## Each application wires both directions + +Each application is a **context**, a type whose wiring holds the application's choices. The server's +table chooses a provider for every type the batch contains, once for writing and once for reading: + +```rust +delegate_components! { + ServerApp { + open { + ValueSerializerComponent, + ValueDeserializerComponent, + }; + + @ValueSerializerComponent.<'a, T> &'a T: SerializeDeref, + @ValueSerializerComponent.[i64, u64, String, ()]: UseSerde, + @ValueSerializerComponent.Vec: SerializeBase64, + @ValueSerializerComponent.DateTime: SerializeTimestamp, + @ValueSerializerComponent.[Posted, Edited, Reacted, SyncBatch]: SerializeRecordFields, + @ValueSerializerComponent.ChatEvent: SerializeVariantFields, + @ValueSerializerComponent.Vec: SerializeIterator, + + @ValueDeserializerComponent.[i64, u64, String, ()]: UseSerde, + @ValueDeserializerComponent.Vec: SerializeBase64, + @ValueDeserializerComponent.DateTime: SerializeTimestamp, + @ValueDeserializerComponent.[Posted, Edited, Reacted, SyncBatch]: DeserializeRecordFields, + @ValueDeserializerComponent.ChatEvent: DeserializeVariantFields, + @ValueDeserializerComponent.Vec: DeserializeExtend, + } +} +``` + +The source spreads each entry over two lines. The structs go to +[`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) and +[`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md), and the enum to +[`SerializeVariantFields`](../reference/providers/serialize_variant_fields.md) and +[`DeserializeVariantFields`](../reference/providers/deserialize_variant_fields.md), which write +each event as `{"Variant": value}` and read it back. Each of them asks the context for the types +inside, so the encodings of `Vec` and `DateTime` reach through the enum into every struct. +The `()` entry serves `HistoryCleared`, written as `{"HistoryCleared": null}`. + +The inspector's table is the same except for three entries: +[`SerializeHex`](../reference/providers/serialize_hex.md) for `Vec`, +[`SerializeRfc3339Date`](../reference/providers/serialize_rfc3339_date.md) for `DateTime`, and +no `i64` entry, which only the server's timestamp encoding needs. Each context checks every type +it reaches with [`check_components!`](/docs/reference/macros/check_components), in both directions. + +## Reading the other application's JSON + +Each application reads its own JSON back into a batch equal to the original. The dates in the batch +are whole seconds, since a Unix timestamp drops anything finer. **Reading the other application's +JSON fails, and the two directions fail differently.** The inspector reading the server's JSON fails +at the first field, because base64 is not valid hex: + +```text +Invalid character 'Z' at position 0 at line 2 column 30 +``` + +The server reading the inspector's JSON gets further. The inspector's hex device key, +`"6465766963652d37"`, uses only characters that base64 also allows, so the server decodes it as +base64, into the wrong bytes, without an error. It stops only at the first date, a string where it +expects a number: + +```text +invalid type: string "2025-11-03T14:15:00+00:00", expected i64 at line 8 column 43 +``` + +The JSON does not record which encoding wrote it, and neither do the types. Two programs exchanging +data therefore have to wire the same choices, and when they do not, a value can be misread without +any error. + +## Try a change + +Remove `()` from the server's `UseSerde` entry for reading, leaving `[i64, u64, String]`, remove +`(Life<'de>, ())` from its check, and run [`cargo cgp check`](/docs/cargo-cgp/check). The check +fails on the three types that contain an event, and the tool names the missing entry as the root +cause: + +```text +error[E0277]: [CGP-E001] the consumer traits `CanDeserializeValue`, `CanDeserializeValue>`, and `CanDeserializeValue` are not implemented for context `ServerApp` + = note: root cause: [CGP-E107] context `ServerApp` does not contain any delegate entry for `@ValueDeserializerComponent.()` +``` + +`HistoryCleared` holds `()`, so reading an event asks the context to read `()`, even though no +struct has a `()` field. Put the entry back to fix it. + +## The pattern + +This example shows **the encoding of a whole data model, enums included, as a choice the context +makes in both directions**. The struct and enum providers walk the types through CGP's field and +variant traits, and hand every value inside back to the context, so one entry decides how a type is +written and read wherever it appears. The idea behind the enum providers is +[Extensible variants](/docs/concepts/extensible-variants), and +[Coherence](/docs/concepts/coherence) explains why plain Rust allows only one encoding per type. + +The cost is the same as in [`messages`](./messages.md): each application lists every type its data +reaches, in each direction. The second half of this example shows a cost that belongs to any choice +of encoding rather than to CGP: the choice is not visible in the data, so two programs must agree on +it. With Serde's derive the agreement comes from sharing the types; here it comes from sharing the +wiring. + +## Where to go next + +- [`SerializeVariantFields`](../reference/providers/serialize_variant_fields.md) and + [`DeserializeVariantFields`](../reference/providers/deserialize_variant_fields.md): the enum + providers, with the limits on which enums they accept. +- [Wiring a context](../guides/wiring-a-context.md): how to find every type a traversal reaches, and + how to check the table. +- [Derive-free records](../architecture/derive-free-records.md): serializing data through CGP's + traits instead of a serialization derive. + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/examples/index.md b/docs/projects/cgp-serde/examples/index.md index c6176349..666502a2 100644 --- a/docs/projects/cgp-serde/examples/index.md +++ b/docs/projects/cgp-serde/examples/index.md @@ -41,9 +41,11 @@ file selects the Rust version, and no example needs a network or any program out - [`messages`](./messages.md) — one nested archive encoded by two contexts that differ in three wiring lines, with hex bytes and RFC 3339 dates from one and base64 bytes and Unix timestamps from the other. +- [`events`](./events.md) — a batch of chat events, an enum whose variants hold structs, written and + read back by two applications with different encodings, and misread by each with the other's. -Two more tests, `arena_simplified` and `arena`, deserialize borrowed values into an arena that the -context supplies. Their pages are still being written; [context +Two more examples, `arena_simplified` and `arena`, deserialize borrowed values into an arena that +the context supplies. Their pages are still being written; [context services](../architecture/context-services.md) explains the design they show. ## Where to go next diff --git a/docs/projects/cgp-serde/index.md b/docs/projects/cgp-serde/index.md index 151113a2..df47cb26 100644 --- a/docs/projects/cgp-serde/index.md +++ b/docs/projects/cgp-serde/index.md @@ -124,6 +124,8 @@ they teach: and its errors in the context's error type. - [`messages`](./examples/messages.md) — one nested archive encoded two ways by two contexts that differ in three wiring lines. +- [`events`](./examples/events.md) — an enum of chat events, each holding a struct, written and read + back by two applications with different encodings. Two more examples deserialize borrowed values into an arena that the context supplies. Their pages are still being written, and [context services](./architecture/context-services.md) explains the From 64259207560214802b8441e1b805cc32e4ea4a57 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 19:39:22 +0200 Subject: [PATCH 174/516] Describe the events example in the cgp-serde examples index Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017CCBh7fScUH7fzq5DeNtyt --- docs/projects/cgp-serde/examples/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/projects/cgp-serde/examples/index.md b/docs/projects/cgp-serde/examples/index.md index 666502a2..7f10cec8 100644 --- a/docs/projects/cgp-serde/examples/index.md +++ b/docs/projects/cgp-serde/examples/index.md @@ -1,7 +1,7 @@ --- sidebar_label: 'Overview' sidebar_position: 0 -description: 'The cgp-serde examples as short tutorials: a JSON round trip with no serialization derive, and one value encoded two ways by two applications.' +description: 'The cgp-serde examples as short tutorials: a JSON round trip with no serialization derive, one value encoded two ways by two applications, and an enum of records written and read back.' --- # cgp-serde examples From 384ec361e4afe5fd36395f9109045100455d9359 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Tue, 6 Oct 2026 20:27:03 +0200 Subject: [PATCH 175/516] Document empty variants and the cgp-serde SerializeUnit provider The derive, trait, macro, and dispatch pages describe variants with no fields and their `Nil` payload. The cgp-serde section adds a `SerializeUnit` page and updates the `events` example and variant provider pages. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017CCBh7fScUH7fzq5DeNtyt --- docs/concepts/extensible-variants.md | 6 +- .../architecture/component-design.md | 2 + .../architecture/derive-free-records.md | 2 +- docs/projects/cgp-serde/examples/events.md | 28 +++-- .../cgp-serde/guides/wiring-a-context.md | 5 + docs/projects/cgp-serde/limitations.md | 14 ++- docs/projects/cgp-serde/reference/index.md | 5 +- .../providers/allocate_with_arena.md | 2 +- .../providers/deserialize_and_allocate.md | 2 +- .../providers/deserialize_default.md | 2 +- .../providers/deserialize_from_json_reader.md | 2 +- .../providers/deserialize_from_json_string.md | 2 +- .../providers/deserialize_variant_fields.md | 33 +++--- .../reference/providers/serialize_base64.md | 2 +- .../reference/providers/serialize_hex.md | 2 +- .../providers/serialize_rfc3339_date.md | 2 +- .../providers/serialize_timestamp.md | 2 +- .../providers/serialize_to_json_string.md | 2 +- .../reference/providers/serialize_unit.md | 103 ++++++++++++++++++ .../providers/serialize_variant_fields.md | 38 +++++-- docs/projects/cgp-serde/serde-comparison.md | 6 +- docs/reference/derives/derive_cgp_data.md | 8 +- docs/reference/derives/derive_cgp_variant.md | 23 +++- .../reference/derives/derive_extract_field.md | 24 ++-- docs/reference/derives/derive_from_variant.md | 11 +- docs/reference/derives/derive_has_fields.md | 3 +- docs/reference/derives/index.md | 9 +- docs/reference/macros/cgp_auto_dispatch.md | 14 +++ docs/reference/macros/enum.md | 9 +- docs/reference/macros/sum.md | 7 +- .../dispatch/match_with_value_handlers.md | 8 ++ docs/reference/traits/shape/has_fields.md | 5 +- docs/reference/traits/variant/from_variant.md | 6 +- .../reference/traits/variant/has_extractor.md | 5 +- 34 files changed, 296 insertions(+), 98 deletions(-) create mode 100644 docs/projects/cgp-serde/reference/providers/serialize_unit.md diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 4d56a81f..8fcbc2f9 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -136,9 +136,11 @@ complete result type. ## What it costs -The full construction and extraction derives require exactly one unnamed payload per variant. +The full construction and extraction derives require one unnamed payload or no fields per variant. A richer case must wrap its fields in a payload type, such as `Circle(Circle)` instead of -`Circle { radius: u64 }`. Unit variants also need a payload if they are to use these derives. +`Circle { radius: u64 }`. A variant with no fields carries the payload `Nil`, which has a cost of +its own: a handler that sees only payloads sees every such variant as the same `Nil`, so telling +them apart needs a handler that also receives the variant's name. [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) can describe all variant shapes, but that structural description alone does not supply generic constructors or extractors. diff --git a/docs/projects/cgp-serde/architecture/component-design.md b/docs/projects/cgp-serde/architecture/component-design.md index 56935c1f..9c7b1b88 100644 --- a/docs/projects/cgp-serde/architecture/component-design.md +++ b/docs/projects/cgp-serde/architecture/component-design.md @@ -102,6 +102,8 @@ same encoding: | [`SerializeDeref`](../reference/providers/serialize_deref.md) | [`DeserializeAndAllocate`](../reference/providers/deserialize_and_allocate.md), for a reference | | [`SerializeIterator`](../reference/providers/serialize_iterator.md) | [`DeserializeExtend`](../reference/providers/deserialize_extend.md) | | [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) | [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) | +| [`SerializeVariantFields`](../reference/providers/serialize_variant_fields.md) | [`DeserializeVariantFields`](../reference/providers/deserialize_variant_fields.md) | +| [`SerializeUnit`](../reference/providers/serialize_unit.md) | the same provider, for a `Default` type | | none | [`DeserializeDefault`](../reference/providers/deserialize_default.md), which wraps another reader | | [`SerializeHex`](../reference/providers/serialize_hex.md), [`SerializeBase64`](../reference/providers/serialize_base64.md), [`SerializeRfc3339Date`](../reference/providers/serialize_rfc3339_date.md), [`SerializeTimestamp`](../reference/providers/serialize_timestamp.md) | the same providers | diff --git a/docs/projects/cgp-serde/architecture/derive-free-records.md b/docs/projects/cgp-serde/architecture/derive-free-records.md index ac386728..f601e12c 100644 --- a/docs/projects/cgp-serde/architecture/derive-free-records.md +++ b/docs/projects/cgp-serde/architecture/derive-free-records.md @@ -81,7 +81,7 @@ The struct providers cover structs with named fields, and tuple structs are not Enums get the same treatment from [`SerializeVariantFields`](../reference/providers/serialize_variant_fields.md) and [`DeserializeVariantFields`](../reference/providers/deserialize_variant_fields.md), which read an -enum's variants through CGP's traits and handle variants that each hold one value. The +enum's variants through CGP's traits and handle variants that each hold one value or none. The [comparison with Serde](../serde-comparison.md) lists what Serde's derive does that cgp-serde's providers do not. diff --git a/docs/projects/cgp-serde/examples/events.md b/docs/projects/cgp-serde/examples/events.md index 62c5aed2..97140f6b 100644 --- a/docs/projects/cgp-serde/examples/events.md +++ b/docs/projects/cgp-serde/examples/events.md @@ -80,7 +80,7 @@ pub enum ChatEvent { Posted(Posted), Edited(Edited), Reacted(Reacted), - HistoryCleared(()), + HistoryCleared, } #[derive(Debug, PartialEq, CgpData)] @@ -91,9 +91,9 @@ pub struct SyncBatch { ``` `Edited` holds a message id, a date, and new encrypted data, and `Reacted` holds a message id, an -author id, and an emoji as a `String`, since many emoji, such as 👍🏽, are more than one `char`. Every -variant holds exactly one value, which `CgpVariant` requires, so `HistoryCleared`, which carries no -data, holds `()`. The batch is a struct holding a `Vec` of events, so structs sit inside the enum +author id, and an emoji as a `String`, since many emoji, such as 👍🏽, are more than one `char`. +`HistoryCleared` carries no data, so it has no fields, and `CgpVariant` gives it the payload `Nil`, +CGP's empty value. The batch is a struct holding a `Vec` of events, so structs sit inside the enum and the enum sits inside a struct. ## Each application wires both directions @@ -110,14 +110,16 @@ delegate_components! { }; @ValueSerializerComponent.<'a, T> &'a T: SerializeDeref, - @ValueSerializerComponent.[i64, u64, String, ()]: UseSerde, + @ValueSerializerComponent.[i64, u64, String]: UseSerde, + @ValueSerializerComponent.Nil: SerializeUnit, @ValueSerializerComponent.Vec: SerializeBase64, @ValueSerializerComponent.DateTime: SerializeTimestamp, @ValueSerializerComponent.[Posted, Edited, Reacted, SyncBatch]: SerializeRecordFields, @ValueSerializerComponent.ChatEvent: SerializeVariantFields, @ValueSerializerComponent.Vec: SerializeIterator, - @ValueDeserializerComponent.[i64, u64, String, ()]: UseSerde, + @ValueDeserializerComponent.[i64, u64, String]: UseSerde, + @ValueDeserializerComponent.Nil: SerializeUnit, @ValueDeserializerComponent.Vec: SerializeBase64, @ValueDeserializerComponent.DateTime: SerializeTimestamp, @ValueDeserializerComponent.[Posted, Edited, Reacted, SyncBatch]: DeserializeRecordFields, @@ -134,7 +136,9 @@ The source spreads each entry over two lines. The structs go to [`DeserializeVariantFields`](../reference/providers/deserialize_variant_fields.md), which write each event as `{"Variant": value}` and read it back. Each of them asks the context for the types inside, so the encodings of `Vec` and `DateTime` reach through the enum into every struct. -The `()` entry serves `HistoryCleared`, written as `{"HistoryCleared": null}`. +The `Nil` entry serves `HistoryCleared`: +[`SerializeUnit`](../reference/providers/serialize_unit.md) writes it as +`{"HistoryCleared": null}`, where Serde's derive would write the bare name `"HistoryCleared"`. The inspector's table is the same except for three entries: [`SerializeHex`](../reference/providers/serialize_hex.md) for `Vec`, @@ -168,18 +172,18 @@ any error. ## Try a change -Remove `()` from the server's `UseSerde` entry for reading, leaving `[i64, u64, String]`, remove -`(Life<'de>, ())` from its check, and run [`cargo cgp check`](/docs/cargo-cgp/check). The check +Remove the server's `@ValueDeserializerComponent.Nil: SerializeUnit` entry, remove +`(Life<'de>, Nil)` from its check, and run [`cargo cgp check`](/docs/cargo-cgp/check). The check fails on the three types that contain an event, and the tool names the missing entry as the root cause: ```text error[E0277]: [CGP-E001] the consumer traits `CanDeserializeValue`, `CanDeserializeValue>`, and `CanDeserializeValue` are not implemented for context `ServerApp` - = note: root cause: [CGP-E107] context `ServerApp` does not contain any delegate entry for `@ValueDeserializerComponent.()` + = note: root cause: [CGP-E107] context `ServerApp` does not contain any delegate entry for `@ValueDeserializerComponent.Nil` ``` -`HistoryCleared` holds `()`, so reading an event asks the context to read `()`, even though no -struct has a `()` field. Put the entry back to fix it. +`HistoryCleared` carries `Nil`, so reading an event asks the context to read `Nil`, even though no +struct has a `Nil` field. Put the entry back to fix it. ## The pattern diff --git a/docs/projects/cgp-serde/guides/wiring-a-context.md b/docs/projects/cgp-serde/guides/wiring-a-context.md index 648ca4e9..1add25a4 100644 --- a/docs/projects/cgp-serde/guides/wiring-a-context.md +++ b/docs/projects/cgp-serde/guides/wiring-a-context.md @@ -73,6 +73,11 @@ type, and follow what each provider asks the context for, which each provider's - **A struct** wired to [`SerializeRecordFields`](../reference/providers/serialize_record_fields.md) or [`DeserializeRecordFields`](../reference/providers/deserialize_record_fields.md) needs an entry for each field's type. +- **An enum** wired to + [`SerializeVariantFields`](../reference/providers/serialize_variant_fields.md) or + [`DeserializeVariantFields`](../reference/providers/deserialize_variant_fields.md) needs an entry + for each variant's payload type. A variant with no fields, such as `Empty`, carries `Nil`, which + [`SerializeUnit`](../reference/providers/serialize_unit.md) writes as `{"Empty":null}`. - **A collection** needs an entry of its own, besides its item type's. Writing one with [`SerializeIterator`](../reference/providers/serialize_iterator.md) also asks for the item as a reference, which one generic entry covers: diff --git a/docs/projects/cgp-serde/limitations.md b/docs/projects/cgp-serde/limitations.md index 93dd64d3..833cfa6b 100644 --- a/docs/projects/cgp-serde/limitations.md +++ b/docs/projects/cgp-serde/limitations.md @@ -28,12 +28,14 @@ format. It cannot make a format do something the format does not do, and a progr ## The generic providers cover structs and simple enums The providers that walk a type generically handle structs with named fields, enums whose variants -each hold exactly one value, the standard collections, references, and types that convert to or -from another type. Enums are written only in Serde's default form, `{"Variant": value}`, and only -an enum without a lifetime can be written. The providers do not handle other enums, tuple structs, -or tuples. Those types, and any other type that already implements Serde's traits, -are encoded through their own Serde impl, with `UseSerde`, and the choices of the **context**, the -type whose wiring holds an application's choices, do not reach inside them. +each hold one value or none, the standard collections, references, and types that convert to or +from another type. Enums are written only in Serde's default form, `{"Variant": value}`, a variant +with no fields included, so it becomes `{"Variant":null}` where Serde writes a bare `"Variant"`, an +empty sequence, or an empty map. Only an enum without a lifetime can be written. The providers do +not handle other enums, tuple structs, or tuples. Those types, and any other type that already +implements Serde's traits, are encoded through their own Serde impl, with `UseSerde`, and the +choices of the **context**, the type whose wiring holds an application's choices, do not reach +inside them. A recursive type, such as a tree whose nodes contain nodes, cannot be encoded by the generic providers at all, because the compiler cannot resolve the cycle in the wiring. It needs a provider diff --git a/docs/projects/cgp-serde/reference/index.md b/docs/projects/cgp-serde/reference/index.md index 95369d89..4c0b2200 100644 --- a/docs/projects/cgp-serde/reference/index.md +++ b/docs/projects/cgp-serde/reference/index.md @@ -46,8 +46,9 @@ providers](../architecture/reentrant-providers.md). | [`DeserializeExtend`](./providers/deserialize_extend.md) | `cgp-serde` | reads | a collection that can be extended | each item | | [`SerializeRecordFields`](./providers/serialize_record_fields.md) | `cgp-serde` | writes | a struct with named fields | each field's type | | [`DeserializeRecordFields`](./providers/deserialize_record_fields.md) | `cgp-serde` | reads | a struct with named fields | each field's type | -| [`SerializeVariantFields`](./providers/serialize_variant_fields.md) | `cgp-serde` | writes | an enum of one-value variants, without a lifetime | each variant's value type | -| [`DeserializeVariantFields`](./providers/deserialize_variant_fields.md) | `cgp-serde` | reads | an enum of one-value variants | each variant's value type | +| [`SerializeVariantFields`](./providers/serialize_variant_fields.md) | `cgp-serde` | writes | an enum whose variants hold one value or none, without a lifetime | each variant's value type, `Nil` for a variant with no fields | +| [`DeserializeVariantFields`](./providers/deserialize_variant_fields.md) | `cgp-serde` | reads | an enum whose variants hold one value or none | each variant's value type, `Nil` for a variant with no fields | +| [`SerializeUnit`](./providers/serialize_unit.md) | `cgp-serde` | both | writes any type as a unit; reads any `Default` type from one | nothing | | [`DeserializeDefault`](./providers/deserialize_default.md) | `cgp-serde` | reads | a `Default` type that may be null | nothing; wraps another provider | | [`SerializeHex`](./providers/serialize_hex.md) | `cgp-serde-extra` | both | bytes, as hex | `String` | | [`SerializeBase64`](./providers/serialize_base64.md) | `cgp-serde-extra` | both | bytes, as base64 | `String` | diff --git a/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md index a77bffa0..f1ff8784 100644 --- a/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md +++ b/docs/projects/cgp-serde/reference/providers/allocate_with_arena.md @@ -1,7 +1,7 @@ --- title: 'AllocateWithArena — allocate into an arena held by the context in cgp-serde' sidebar_label: 'AllocateWithArena' -sidebar_position: 25 +sidebar_position: 26 description: 'The cgp-serde provider that implements the allocation component by moving values into a typed_arena::Arena the context supplies through an arena getter.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md index 78044e23..6644a6d2 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_and_allocate.md @@ -1,7 +1,7 @@ --- title: 'DeserializeAndAllocate — read a reference into an allocator in cgp-serde' sidebar_label: 'DeserializeAndAllocate' -sidebar_position: 24 +sidebar_position: 25 description: 'The cgp-serde provider that reads a borrowed &T by reading an owned T through the context and allocating it through the context''s allocation component.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_default.md b/docs/projects/cgp-serde/reference/providers/deserialize_default.md index eab690c3..11509bce 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_default.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_default.md @@ -1,7 +1,7 @@ --- title: 'DeserializeDefault — read a null value as the default in cgp-serde' sidebar_label: 'DeserializeDefault' -sidebar_position: 16 +sidebar_position: 17 description: 'The cgp-serde higher-order provider that reads a null input as the type''s Default and passes any other input to an inner provider named in the wiring.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md index 6b839c9e..956cd92b 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_reader.md @@ -1,7 +1,7 @@ --- title: 'DeserializeFromJsonReader — read JSON from any serde_json reader in cgp-serde' sidebar_label: 'DeserializeFromJsonReader' -sidebar_position: 22 +sidebar_position: 23 description: 'The cgp-serde provider that reads a value from a string, bytes, or a stream through serde_json and the context''s wiring, rejecting trailing input.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md index 0aee474f..29d92353 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_from_json_string.md @@ -1,7 +1,7 @@ --- title: 'DeserializeFromJsonString — read JSON from a string in cgp-serde' sidebar_label: 'DeserializeFromJsonString' -sidebar_position: 23 +sidebar_position: 24 description: 'The cgp-serde provider that reads a value from any string-like input by wrapping it in a serde_json reader and handing it to an inner provider.' --- diff --git a/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md b/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md index 9d2b40a9..d00b596a 100644 --- a/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md +++ b/docs/projects/cgp-serde/reference/providers/deserialize_variant_fields.md @@ -16,8 +16,8 @@ Read an enum from `{"Variant": payload}`, reading the payload through the contex **context**, the type whose wiring holds the application's choices, to read that variant's payload, and builds the enum. The enum derives only CGP's variant traits, through [`#[derive(CgpVariant)]`](/docs/reference/derives/derive_cgp_variant) or the narrower -[`HasFields`](/docs/reference/traits/shape/has_fields) derive, and every variant holds exactly one -unnamed payload. +[`HasFields`](/docs/reference/traits/shape/has_fields) derive, and every variant holds one unnamed +payload or no fields. ## Definition @@ -34,7 +34,8 @@ where [`FromFields`](/docs/reference/traits/shape/from_fields) builds the enum from one variant of its variant list. `VariantsDeserializer` is a private trait that finds the variant by name or position, -and it requires, for each variant, that the context can read the payload's type. +and it requires, for each variant, that the context can read the payload's type, `Nil` for a +variant with no fields. ## Usage @@ -45,7 +46,8 @@ delegate_components! { App { open ValueDeserializerComponent; - @ValueDeserializerComponent.[u64, String, ()]: UseSerde, + @ValueDeserializerComponent.[u64, String]: UseSerde, + @ValueDeserializerComponent.Nil: SerializeUnit, @ValueDeserializerComponent.Circle: DeserializeRecordFields, @ValueDeserializerComponent.Shape: DeserializeVariantFields, } @@ -57,14 +59,16 @@ delegate_components! { The provider reads the variant's identifier, then its payload through the context. A text format names the variant, and a binary format such as postcard gives its position in the declaration, as Serde's derive does. With JSON, `{"Circle":{"radius":3}}` reads as `Shape::Circle`, and -`{"Empty":null}` reads as `Shape::Empty(())` because `()` is wired to `UseSerde`. The payload may +`{"Empty":null}` reads as `Shape::Empty` because `Nil` is wired to +[`SerializeUnit`](./serialize_unit.md). The payload may borrow from the input: an enum `Token<'a>` with a `Word(&'a str)` variant reads `{"Word":"hello"}` without copying the string. -**The context's entry for `()` decides how a variant with no data is written.** A context that wires -`()` to a provider writing an empty map reads `{"Empty":{}}` and rejects `{"Empty":null}`. Under -either choice, the bare `"Empty"` that Serde's derive uses for a unit variant is rejected, with -`invalid type: unit variant, expected newtype variant`. +**The context's entry for `Nil` decides how a variant with no fields is read.** `SerializeUnit` +reads only a unit, so `{"Empty":{}}`, which Serde's derive writes for `Empty {}`, is rejected with +`invalid type: map, expected unit`. Whatever the entry, the bare `"Empty"` that Serde's derive +writes for a unit variant is rejected, with `invalid type: unit variant, expected newtype variant`. +So JSON written by Serde's derive cannot be read back for these variants. The provider reports an unknown variant with the names it expected, in the same wording as Serde's derive: @@ -78,7 +82,8 @@ variant, such as `{}` or an array, fails with the format's error. ## Context dependencies -`CanDeserializeValue<'de, P>` for the payload type `P` of every variant. +`CanDeserializeValue<'de, P>` for the payload type `P` of every variant, which is `Nil` for a +variant with no fields. ## Pairing @@ -87,14 +92,16 @@ variant, such as `{}` or an array, fails with the format's error. ## When to use it **Reach for `DeserializeVariantFields` to read an enum whose payloads should follow the context's -choices.** It reads only Serde's default enum form, with one payload per variant. An enum written in -another form, or with variants that hold several fields, keeps its own Serde impl and is wired to -[`UseSerde`](./use_serde.md). +choices.** It reads only Serde's default enum form, with one payload or none per variant, and reads +a variant with no fields only in the `{"Empty":null}` form its serializing pair writes. An enum +written in another form, or with variants that hold several fields, keeps its own Serde impl and is +wired to [`UseSerde`](./use_serde.md). ## Related constructs - [`DeserializeRecordFields`](./deserialize_record_fields.md) is the matching provider for a struct, and usually reads a variant's payload. +- [`SerializeUnit`](./serialize_unit.md) reads the `Nil` payload of a variant with no fields. ## The ideas behind it diff --git a/docs/projects/cgp-serde/reference/providers/serialize_base64.md b/docs/projects/cgp-serde/reference/providers/serialize_base64.md index d4269733..6d16f112 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_base64.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_base64.md @@ -1,7 +1,7 @@ --- title: 'SerializeBase64 — encode bytes as base64 in cgp-serde' sidebar_label: 'SerializeBase64' -sidebar_position: 18 +sidebar_position: 19 description: 'The cgp-serde provider that writes bytes as a standard padded base64 string and reads one back into a Vec.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_hex.md b/docs/projects/cgp-serde/reference/providers/serialize_hex.md index e2062c06..28633740 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_hex.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_hex.md @@ -1,7 +1,7 @@ --- title: 'SerializeHex — encode bytes as hex in cgp-serde' sidebar_label: 'SerializeHex' -sidebar_position: 17 +sidebar_position: 18 description: 'The cgp-serde provider that writes bytes as a lowercase hex string and reads a hex string back, asking the context to write and read the String.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md b/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md index 6eacee35..42156a09 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_rfc3339_date.md @@ -1,7 +1,7 @@ --- title: 'SerializeRfc3339Date — encode a date as an RFC 3339 string in cgp-serde' sidebar_label: 'SerializeRfc3339Date' -sidebar_position: 19 +sidebar_position: 20 description: 'The cgp-serde provider that writes a DateTime as an RFC 3339 string and reads one back with any offset.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md b/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md index aa4d805e..afedc018 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_timestamp.md @@ -1,7 +1,7 @@ --- title: 'SerializeTimestamp — encode a date as a Unix timestamp in cgp-serde' sidebar_label: 'SerializeTimestamp' -sidebar_position: 20 +sidebar_position: 21 description: 'The cgp-serde provider that writes a DateTime as whole seconds since the Unix epoch and reads one back, asking the context to write and read the i64.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md b/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md index d3755746..53c7f7b1 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_to_json_string.md @@ -1,7 +1,7 @@ --- title: 'SerializeToJsonString — write JSON as an operation on the context in cgp-serde' sidebar_label: 'SerializeToJsonString' -sidebar_position: 21 +sidebar_position: 22 description: 'The cgp-serde provider that writes a value as a compact JSON string through the context''s wiring, turning serde_json errors into the context''s error type.' --- diff --git a/docs/projects/cgp-serde/reference/providers/serialize_unit.md b/docs/projects/cgp-serde/reference/providers/serialize_unit.md new file mode 100644 index 00000000..a7491310 --- /dev/null +++ b/docs/projects/cgp-serde/reference/providers/serialize_unit.md @@ -0,0 +1,103 @@ +--- +title: 'SerializeUnit — write a variant with no fields in cgp-serde' +sidebar_label: 'SerializeUnit' +sidebar_position: 16 +description: 'The cgp-serde provider that writes any value as Serde''s unit and reads a unit back as the type''s default, used for the payload of an enum variant with no fields.' +--- + +# `SerializeUnit` + +Write any value as Serde's unit, and read a unit back as the type's default. + +## Overview + +`SerializeUnit` is the provider for a type with nothing to write. Its main use is `Nil`, the payload +that [`#[derive(CgpVariant)]`](/docs/reference/derives/derive_cgp_variant) gives an enum variant +with no fields, such as `Empty`, `Empty()`, or `Empty {}`. The +[variant providers](./serialize_variant_fields.md) ask the **context**, the type whose wiring holds +the application's choices, to write and read each payload, so a context with such a variant needs an +entry for `Nil`, and `SerializeUnit` is the usual one. + +## Definition + +```rust +pub struct SerializeUnit; + +#[cgp_impl(SerializeUnit)] +impl ValueSerializer { ... } + +#[cgp_impl(SerializeUnit)] +impl<'de, Value> ValueDeserializer<'de, Value> +where + Value: Default, +{ ... } +``` + +One struct implements both directions. Serializing accepts any value, and deserializing needs a +`Default` to build the value from. + +## Usage + +Import it from `cgp_serde::providers`, and wire it for `Nil` in both directions: + +```rust +@ValueSerializerComponent.Nil: SerializeUnit, +@ValueDeserializerComponent.Nil: SerializeUnit, +``` + +`Nil` is in `cgp::prelude`, so the entry needs no further import. + +## Behavior + +The serializer ignores the value and writes Serde's unit, which JSON writes as `null`, RON as `()`, +and postcard as nothing at all. Inside an enum, a variant `Status::Closed` therefore becomes +`{"Closed":null}` in JSON and `Closed(())` in RON. + +The deserializer reads a unit and returns `Value::default()`. Anything else is rejected, so with +JSON, `{"Closed":{}}` fails with: + +```text +invalid type: map, expected unit at line 1 column 10 +``` + +## Context dependencies + +None. `SerializeUnit` asks the context for nothing. + +## Pairing + +The same provider reads what it writes. + +## When to use it + +**Reach for `SerializeUnit` for `Nil`, so that an enum with variants that have no fields can be +written and read.** Wire it only for a type with nothing to write: the serializer accepts any value +and writes none of its data, so a type that carries data would lose it. + +A context that wants another form for the payload wires `Nil` to its own provider instead. The +entry decides only the payload, so Serde's own forms, such as the bare name `"Closed"` for a unit +variant, are not available this way: +[`SerializeVariantFields`](./serialize_variant_fields.md) always writes the variant around a +payload. + +## Related constructs + +- [`SerializeVariantFields`](./serialize_variant_fields.md) and + [`DeserializeVariantFields`](./deserialize_variant_fields.md) ask the context for the `Nil` + payload this provider handles. +- [`UseSerde`](./use_serde.md) writes `()` the same way, through Serde's own impl for `()`. + +## The ideas behind it + +- [Extensible variants](/docs/concepts/extensible-variants): an enum seen as a list of named + variants, each with one payload. + +## Source + +- [`crates/cgp-serde/src/providers/unit.rs`](https://github.com/contextgeneric/cgp-serde/blob/main/crates/cgp-serde/src/providers/unit.rs) + +--- + +*An AI agent wrote this page using the CGP knowledge base. Its content was verified against the +project's source. See [How AI is used in this +project](/docs/ai/disclaimer#documentation-and-reference-pages).* diff --git a/docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md b/docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md index b2edfaa4..b06ee733 100644 --- a/docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md +++ b/docs/projects/cgp-serde/reference/providers/serialize_variant_fields.md @@ -18,8 +18,9 @@ variants through CGP's field traits, which payload. So one generic provider serves every such enum, and each payload is encoded however the context encodes its type. -Every variant must hold exactly one unnamed payload, as `Circle(Circle)` does, which is also what -`CgpVariant` requires. A variant with no data is written with a `()` payload, as `Empty(())`. +Every variant must hold one unnamed payload, as `Circle(Circle)` does, or no fields, as `Empty` +does, which is also what `CgpVariant` requires. A variant with no fields has the payload `Nil`, so +the context decides how it is written through its entry for `Nil`. ## Definition @@ -37,7 +38,7 @@ where [`ToFieldsRef`](/docs/reference/traits/shape/to_fields_ref) borrows the enum as a list of its variants, each paired with its name. `VariantsSerializer` is a private trait that finds the active variant in that list, and it requires, for each variant, that the context can write the payload's -type. +type, `Nil` for a variant with no fields. ## Usage @@ -48,29 +49,41 @@ Import it from `cgp_serde::providers`, and wire it beside an entry for each vari pub enum Shape { Circle(Circle), Label(String), - Empty(()), + Empty, } delegate_components! { App { open ValueSerializerComponent; - @ValueSerializerComponent.[u64, String, ()]: UseSerde, + @ValueSerializerComponent.[u64, String]: UseSerde, + @ValueSerializerComponent.Nil: SerializeUnit, @ValueSerializerComponent.Circle: SerializeRecordFields, @ValueSerializerComponent.Shape: SerializeVariantFields, } } ``` -Here `Circle` is a struct with one `radius: u64` field, so its own entry needs `u64`. +Here `Circle` is a struct with one `radius: u64` field, so its own entry needs `u64`, and +[`SerializeUnit`](./serialize_unit.md) writes the `Nil` of `Empty`. ## Behavior The provider writes the active variant as a Serde newtype variant, with the variant's name and its position in the declaration. With JSON, `Shape::Circle(Circle { radius: 3 })` is written as -`{"Circle":{"radius":3}}`, `Shape::Label("hi".into())` as `{"Label":"hi"}`, and -`Shape::Empty(())` as `{"Empty":null}`, because `()` is wired to `UseSerde`. This is exactly what -Serde's derive writes for the same enum. +`{"Circle":{"radius":3}}` and `Shape::Label("hi".into())` as `{"Label":"hi"}`, exactly what +Serde's derive writes for those variants. `Shape::Empty` is written as `{"Empty":null}`, because +`Nil` is wired to `SerializeUnit`. Every empty form is written that way, while Serde's derive +writes each form its own way: + +| Variant | This provider | Serde's derive | +|---|---|---| +| `Empty` | `{"Empty":null}` | `"Empty"` | +| `Empty()` | `{"Empty":null}` | `{"Empty":[]}` | +| `Empty {}` | `{"Empty":null}` | `{"Empty":{}}` | + +Serde's derive reads `{"Empty":null}` back only for the first form. In postcard the two agree, +since every form is written as the variant's position alone. Other formats see the same Serde calls. RON writes `Label("x")`, and postcard writes the variant's position followed by its payload. Both match Serde's derive, except where the payload is a struct: @@ -79,7 +92,8 @@ rejects. ## Context dependencies -`CanSerializeValue

` for the payload type `P` of every variant. +`CanSerializeValue

` for the payload type `P` of every variant, which is `Nil` for a variant with +no fields. ## Pairing @@ -95,7 +109,8 @@ choices.** Its limits are worth knowing first: current limitation in how Rust proves lifetime bounds. `Token<'static>` works, and reading a borrowing enum with [`DeserializeVariantFields`](./deserialize_variant_fields.md) works too. - **Only Serde's default enum form is written.** There is no internally tagged, adjacently tagged, - or untagged form, and a variant with no data is `Empty(())` rather than a bare `"Empty"`. + or untagged form, and a variant with no fields is written as `{"Empty":null}`, which does not + match Serde's derive in JSON or RON. - **An enum that contains itself**, such as an expression tree, fails to compile, as a struct that contains itself does. @@ -106,6 +121,7 @@ An enum outside these limits keeps its own Serde impl and is wired to - [`SerializeRecordFields`](./serialize_record_fields.md) is the matching provider for a struct, and usually writes a variant's payload. +- [`SerializeUnit`](./serialize_unit.md) writes the `Nil` payload of a variant with no fields. ## The ideas behind it diff --git a/docs/projects/cgp-serde/serde-comparison.md b/docs/projects/cgp-serde/serde-comparison.md index c60ad4e7..6e6d857d 100644 --- a/docs/projects/cgp-serde/serde-comparison.md +++ b/docs/projects/cgp-serde/serde-comparison.md @@ -56,7 +56,7 @@ field while a cgp-serde context chooses per type: | a newtype to change a type's encoding | wire a different provider in a different context | | `#[serde(remote = "…")]` for a type from another crate | wire the type to a provider directly | | `#[derive(Serialize, Deserialize)]` on a struct | derive `CgpData`, and wire the struct to `SerializeRecordFields` and `DeserializeRecordFields` | -| `#[derive(Serialize, Deserialize)]` on an enum of one-value variants | derive `CgpVariant`, and wire the enum to `SerializeVariantFields` and `DeserializeVariantFields` | +| `#[derive(Serialize, Deserialize)]` on an enum whose variants hold one value or none | derive `CgpVariant`, wire the enum to `SerializeVariantFields` and `DeserializeVariantFields`, and wire `Nil` to `SerializeUnit` for the variants with no fields | | a hand-written `DeserializeSeed` for state | a provider that takes the state from the context | | a borrowed `&'de str` field | wire `&'a str` to `UseSerde`, and read from input that can lend it | @@ -70,7 +70,9 @@ providers leave to it: expect every field to be present. - **Enum representations, tuple structs, and tuples.** Serde derives all of them, in several representations for enums. cgp-serde's providers handle structs with named fields, and enums - whose variants each hold one value, in Serde's default externally tagged form. + whose variants each hold one value or none, in Serde's default externally tagged form. A variant + with no fields is written as `{"Variant":null}`, where Serde writes a bare `"Variant"`, an empty + sequence, or an empty map, depending on how the variant is declared. - **Recursive types**, such as a tree whose nodes contain nodes. Serde derives them without difficulty; cgp-serde's generic providers cannot express the recursion, and such a type needs a provider written for it. diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 7908defa..8902c7a6 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -59,7 +59,8 @@ output in detail: | a struct | per-field access, the representation, and the builder | [`#[derive(CgpRecord)]`](./derive_cgp_record.md) | | an enum | the representation, the constructors, and the extractor | [`#[derive(CgpVariant)]`](./derive_cgp_variant.md) | -Every enum variant must carry exactly one unnamed payload, and individual variants cannot opt out. +Every enum variant must carry one unnamed payload or no fields, and individual variants cannot opt +out. The matching page covers the accepted shapes, generated code, and corner cases. ### Choosing among the three @@ -156,8 +157,9 @@ tuple builders, and the newtype representation. The [variant page](./derive_cgp_variant.md#common-mistakes) covers payload shapes and reserved names. The following restrictions apply when choosing the combined derive. -**Every enum variant needs exactly one unnamed payload.** Unit, multi-field, and struct-style variants -are rejected, and individual variants cannot opt out. [`HasFields`](./derive_has_fields.md) accepts +**Every enum variant needs one unnamed payload or none.** A variant with no fields has the payload +`Nil`. Multi-field and struct-style variants with fields are rejected, and individual variants +cannot opt out. [`HasFields`](./derive_has_fields.md) accepts all of these shapes when only a representation and whole-value conversions are needed. **Seven variant names are reserved on an enum.** `Fields`, `FieldsRef`, `Value`, `Remainder`, diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 0d81a19a..16be3e26 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -40,11 +40,14 @@ pub enum Shape { Each variant is keyed by [`Symbol!`](../macros/symbol.md) of its name. Generic parameters, lifetimes, and a `where` clause are carried onto everything generated, including the companion enums. -### Every variant needs exactly one unnamed payload +### Every variant needs one unnamed payload or none -Every variant must contain exactly one unnamed field. The constructor and extractor implementations -use that field's type as the payload type. Unit, multi-field, and struct-style variants fail with -`Expected variant to contain exactly one unnamed field`. Individual variants cannot opt out. +Every variant must contain exactly one unnamed field or no fields at all. The constructor and +extractor implementations use the field's type as the payload type. A variant with no fields, +written `Closed`, `Closed()`, or `Closed {}`, has the payload `Nil`, so it is built from `Nil` and +extracted as `Nil`. Multi-field and struct-style variants with fields fail with +`Expected variant to contain exactly one unnamed field, or no fields`. Individual variants cannot +opt out. Wrap a richer payload in its own struct so the variant contains a single payload type: @@ -202,10 +205,20 @@ hand-written impl underlines that variant rather than the whole derive. ## Common Mistakes -**Every variant needs exactly one unnamed payload.** Individual variants cannot opt out. +**Every variant needs one unnamed payload or none.** Individual variants cannot opt out. [`HasFields`](./derive_has_fields.md) accepts all variant shapes when only the representation and whole-value conversions are needed. +**A `no_std` crate needs `Box` in scope for a variant with no fields.** The mutable extractor builds +that variant's `&mut Nil` with `Box::leak(Box::new(Nil))`, which never allocates, and finds `Box` +in your crate. Without it, the build fails with ``cannot find type `Box` in this scope`` on the +variant; add `extern crate alloc; use alloc::boxed::Box;`. + +**`#[cgp_auto_dispatch]` cannot serve an enum with a variant that has no fields.** The variant's +payload is `Nil`, and an impl of your trait for `Nil` conflicts with the macro's blanket impl. +Dispatch such an enum with the [dispatch combinators](/docs/reference/providers/dispatch) and a +provider instead. + **Seven variant names are reserved.** Because the generated impls name their associated types through `Self::…`, a variant called `Fields`, `FieldsRef`, `Value`, `Remainder`, `Extractor`, `ExtractorRef`, or `ExtractorMut` makes that path ambiguous and the derive fails with `ambiguous associated item`, headlined diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index d4f671d6..a0ba70a9 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -52,11 +52,14 @@ Each variant's name becomes a [`Symbol!`](../macros/symbol.md) tag and its paylo that tag yields. Generic parameters, lifetimes, and a `where` clause are carried onto both companion types and every generated impl. -### Every variant needs exactly one unnamed payload +### Every variant needs one unnamed payload or none -Every variant must contain exactly one unnamed field. The extractor uses that field's type as its -payload type. Unit, multi-field, and struct-style variants fail with -`Expected variant to contain exactly one unnamed field`. Individual variants cannot opt out. +Every variant must contain exactly one unnamed field or no fields at all. The extractor uses the +field's type as its payload type. A variant with no fields, written `Closed`, `Closed()`, or +`Closed {}`, has the payload `Nil`, extracted as `Nil`, `&Nil`, or `&mut Nil` depending on the +extractor. Multi-field and struct-style variants with fields fail with +`Expected variant to contain exactly one unnamed field, or no fields`. Individual variants cannot +opt out. Wrap the payload in a dedicated struct to give each variant a single payload type: @@ -189,8 +192,8 @@ Choose the derive according to the operations the enum needs: - **[`FromVariant`](./derive_from_variant.md)**: provide generic construction, often needed alongside extraction. -The single-payload requirement can require changes at every construction site. An enum with unit, -multi-field, or struct-style variants must be restructured before it can derive the extractor. +The payload requirement can require changes at every construction site. An enum with multi-field or +struct-style variants must be restructured before it can derive the extractor. Consider that cost when deciding whether independent variant handling is needed. ## Under the hood @@ -287,8 +290,13 @@ at the enum name. The companion enums are cloned from yours, so their tokens alr ## Common Mistakes -**Every variant must carry exactly one unnamed payload.** Individual variants cannot opt out. Wrap -richer payloads in structs, and give a fieldless case a payload type too. +**Every variant must carry one unnamed payload or none.** Individual variants cannot opt out. Wrap +richer payloads in structs. + +**A `no_std` crate needs `Box` in scope for a variant with no fields.** The mutable extractor makes +that variant's `&mut Nil` with `Box::leak(Box::new(Nil))`, which never allocates, and finds `Box` in +your crate. Without it, the build fails with ``cannot find type `Box` in this scope`` on the variant; +add `extern crate alloc; use alloc::boxed::Box;`. [`HasFields`](./derive_has_fields.md) accepts all variant shapes if only a representation is needed. **A ruled-out variant uses `IsVoid`.** It maps the payload to uninhabited `Void`, allowing a fully diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index ab64d70c..92d9ab88 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -47,11 +47,14 @@ Each variant's name becomes a [`Symbol!`](../macros/symbol.md) tag and its paylo constructor's value type. Generic parameters, lifetimes, and a `where` clause are carried onto every generated impl. -### Every variant needs exactly one unnamed payload +### Every variant needs one unnamed payload or none Every variant must contain exactly one unnamed field, whose type becomes the constructor's payload -type. Unit, multi-field, and struct-style variants fail with -`Expected variant to contain exactly one unnamed field`. Individual variants cannot opt out. +type, or no fields at all. A variant with no fields, written `Closed`, `Closed()`, or `Closed {}`, +takes the payload `Nil`: `Status::from_variant(PhantomData::, Nil)` builds +`Status::Closed`. Multi-field and struct-style variants with fields fail with +`Expected variant to contain exactly one unnamed field, or no fields`. Individual variants cannot +opt out. Wrap a richer payload in a dedicated struct so the variant contains a single payload type: @@ -190,7 +193,7 @@ underlines that variant rather than the whole `#[derive(FromVariant)]`. ## Common Mistakes -**Every variant must carry exactly one unnamed payload.** Individual variants cannot opt out. +**Every variant must carry one unnamed payload or none.** Individual variants cannot opt out. [`HasFields`](./derive_has_fields.md) accepts all variant shapes when only a representation is needed. **Specify the tag whenever the enum has more than one variant.** In diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index e1b23dbf..dc134008 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -76,7 +76,8 @@ that depends on the original representation must account for that change. applies the struct field rules within each variant. In contrast, the per-variant constructor and extractor derives ([`FromVariant`](./derive_from_variant.md) and [`ExtractField`](./derive_extract_field.md), also included by [`CgpData`](./derive_cgp_data.md)) -require exactly one unnamed payload per variant. +require one unnamed payload or no fields per variant, and give a variant with no fields the same +`Nil` payload this derive does. ```rust #[derive(HasFields)] diff --git a/docs/reference/derives/index.md b/docs/reference/derives/index.md index 0981212b..415bc466 100644 --- a/docs/reference/derives/index.md +++ b/docs/reference/derives/index.md @@ -59,10 +59,11 @@ together. ## Restrictions to know before you reach for them -The enum constructor and extractor derives require every variant to carry exactly one unnamed -payload. This restriction applies to `FromVariant`, `ExtractField`, `CgpData`, and `CgpVariant`; -individual variants cannot opt out. `HasFields` accepts every variant shape and provides a structural -representation with whole-value conversions, so it can be used with enums that mix variant shapes. +The enum constructor and extractor derives require every variant to carry one unnamed payload or no +fields, the latter with the payload `Nil`. This restriction applies to `FromVariant`, +`ExtractField`, `CgpData`, and `CgpVariant`; individual variants cannot opt out. `HasFields` accepts +every variant shape and provides a structural representation with whole-value conversions, so it can +be used with enums whose variants have several or named fields. The builder and extractor derives also generate companion types that copy each field's or variant's attributes but not the original type's derives. A helper attribute that belongs to another derive, diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index fda82ac4..99ba7092 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -327,6 +327,20 @@ extensible enum collides, including the enum the trait was written for: error[E0119]: conflicting implementations of trait `HasArea` for type `Shape` ``` +**Every payload type must belong to the crate that implements the trait.** An impl for a foreign +payload type, such as `u64`, collides with the same blanket impl, because Rust assumes the foreign +type's crate may implement `HasExtractor` in a later version: + +```text +error[E0119]: conflicting implementations of trait `HasArea` for type `u64` +``` + +This rules out an enum with a variant that has no fields, such as `Empty` in +`enum Shape { Circle(Circle), Empty }`, because the derive gives that variant the payload `Nil`, +which comes from CGP. Dispatch such an enum with +[`MatchWithValueHandlers`](../providers/dispatch/match_with_value_handlers.md) and a provider +instead. A crate can implement its own provider for `Nil`. + ## Related constructs - [Dispatch combinators](../providers/dispatch/index.md) — the matchers this wires, and what to use diff --git a/docs/reference/macros/enum.md b/docs/reference/macros/enum.md index ff575af1..e85414ad 100644 --- a/docs/reference/macros/enum.md +++ b/docs/reference/macros/enum.md @@ -151,10 +151,11 @@ Variant -> IDENTIFIER ( `(` TupleFields `)` | `{` NamedFields `}` )? ## Common Mistakes -**The variant derives need each variant to hold exactly one positional field.** `Enum!` describes any -variant, as `#[derive(HasFields)]` does, but [`#[derive(CgpData)]`](../derives/derive_cgp_data.md), -`CgpVariant`, `ExtractField`, and `FromVariant` reject a unit, multi-field, or named-field variant. A -shape with such variants therefore has no generic constructor or extractor. +**The variant derives need each variant to hold one positional field or none.** `Enum!` describes +any variant, as `#[derive(HasFields)]` does, and +[`#[derive(CgpData)]`](../derives/derive_cgp_data.md), `CgpVariant`, `ExtractField`, and +`FromVariant` accept a unit variant with the same `Nil` payload, but reject a multi-field or +named-field variant. A shape with such variants therefore has no generic constructor or extractor. **An enum body's other parts are rejected.** An attribute on a variant (such as `#[default]` or a doc comment), `pub` on a variant, a discriminant such as `= 1`, and a variant name given twice each fail diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index bfe9bf13..b296dbfa 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -177,12 +177,13 @@ name-tagged [`Field`](../types/field.md)s and the operations match on names, so But the *types* are still different, and a cast between two enums works through the name matching rather than by position. -**The variant derives need each variant to hold exactly one unnamed field.** +**The variant derives need each variant to hold one unnamed field or none.** [`#[derive(CgpData)]`](../derives/derive_cgp_data.md), `CgpVariant`, `ExtractField`, and `FromVariant` -reject a struct-like, multi-field, or unit variant, while `#[derive(HasFields)]` accepts all of them: +accept a unit variant with the payload `Nil`, but reject a multi-field or struct-like variant with +fields, while `#[derive(HasFields)]` accepts all of them: ```text -error: Expected variant to contain exactly one unnamed field +error: Expected variant to contain exactly one unnamed field, or no fields ``` That is a restriction of those derives rather than of `Sum!` itself, and it is why richer payloads are diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index 15e9d641..d777af91 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -236,6 +236,14 @@ The owned `MatchWithValueHandlers` has the same limit. Wire the matcher to `Comp `AsyncComputerComponent`, and lift it with a promotion as [`MatchWithHandlers`](match_with_handlers.md#common-mistakes) shows. +**Variants with no fields all reach the same handler.** The +[variant derives](../../derives/derive_cgp_variant.md) give each such variant, such as `Closed` or +`Paused()`, the payload `Nil`. The provider receives only the payload, so its `Nil` impl serves +every one of them and cannot tell which variant it got. Use +[`MatchWithFieldHandlers`](match_with_field_handlers.md) when they need different handling: its +provider receives `Field` and can read the variant name from the tag. The +borrowed forms handle these variants too, with a `&Nil` or `&mut Nil` payload. + ## Related constructs - [`MatchWithFieldHandlers`](match_with_field_handlers.md) — the sibling that keeps the variant tag diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index abdee791..1e7c18d9 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -84,8 +84,9 @@ have to move through it. **`HasFields` accepts every enum variant shape**: unit, tuple, multi-field, and struct-style. A variant with one unnamed field carries its payload directly, a unit variant carries `Nil`, and any -other variant carries its fields as a nested product. The derives that take an enum apart need -exactly one unnamed payload per variant; this one only describes the variant, so it does not. +other variant carries its fields as a nested product. The derives that take an enum apart need one +unnamed payload or no fields per variant, and give a variant with no fields the same `Nil`; this one +only describes the variant, so it accepts every shape. ## Examples diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index 60814ade..cf8f8b90 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -232,9 +232,9 @@ error[E0119]: conflicting implementations of trait `cgp::prelude::FromVariant Date: Sat, 10 Oct 2026 23:13:39 +0200 Subject: [PATCH 176/516] Quote nightly-2026-10-10 in the cargo-cgp pages The installation, troubleshooting, and editor pages show the driver's `--version` and the preflight's messages as the new pinned nightly prints them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SajznGLmpQzjPd1newVGDK --- docs/cargo-cgp/editor-integration.md | 2 +- docs/cargo-cgp/installation.md | 4 ++-- docs/cargo-cgp/troubleshooting.md | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/cargo-cgp/editor-integration.md b/docs/cargo-cgp/editor-integration.md index c2f168d4..9652aad3 100644 --- a/docs/cargo-cgp/editor-integration.md +++ b/docs/cargo-cgp/editor-integration.md @@ -116,7 +116,7 @@ missing setup, for example, arrives as the tool's own message: ```text cargo check failed to start: Cargo watcher failed, the command produced no valid metadata (exit code: ExitStatus(unix_wait_status(256))): -cargo-cgp: toolchain `nightly-2026-09-14` is not available (exit status: 1) +cargo-cgp: toolchain `nightly-2026-10-10` is not available (exit status: 1) The pinned toolchain is not installed. Run `cargo cgp setup`. ``` diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index ffabdefc..57027162 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -125,8 +125,8 @@ success it prints three lines: ```text cargo-cgp-driver 0.1.0 -pinned-toolchain: nightly-2026-09-14 -built-against-rustc: rustc 1.100.0-nightly (4b6d04e70 2026-09-13) +pinned-toolchain: nightly-2026-10-10 +built-against-rustc: rustc 1.101.0-nightly (32dba69d6 2026-10-09) ``` The second line names the nightly the driver needs, and the third the compiler it was built with. Your diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index c3a88dc0..8add2bb1 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -60,12 +60,12 @@ driver or compiler problem. Almost every message in this section is resolved by running `cargo cgp setup`, which installs the pinned nightly and rebuilds the driver against it at the front end's version. The messages tell you which part -was wrong. The examples show `nightly-2026-09-14`; yours names the nightly your build is pinned to. +was wrong. The examples show `nightly-2026-10-10`; yours names the nightly your build is pinned to. **The pinned nightly is not installed:** ```text -cargo-cgp: toolchain `nightly-2026-09-14` is not available (exit status: 1) +cargo-cgp: toolchain `nightly-2026-10-10` is not available (exit status: 1) The pinned toolchain is not installed. Run `cargo cgp setup`. ``` @@ -86,7 +86,7 @@ Here `setup` cannot help, since it needs rustup too; install rustup, or use the was built against a different nightly: ```text -cargo-cgp: the cargo-cgp-driver could not run under toolchain `nightly-2026-09-14` (it was likely built against a different nightly). Run `cargo cgp setup`. +cargo-cgp: the cargo-cgp-driver could not run under toolchain `nightly-2026-10-10` (it was likely built against a different nightly). Run `cargo cgp setup`. ``` **The driver runs, but its version differs from the front end's.** This follows a partial upgrade, or @@ -102,7 +102,7 @@ Run `cargo cgp setup`. the toolchain the front end expects no longer belong together, even though their versions match: ```text -cargo-cgp: the cargo-cgp-driver was built against `rustc 1.99.0-nightly (0123abcde 2026-08-01)`, but the pinned toolchain `nightly-2026-09-14` now provides `rustc 1.100.0-nightly (4b6d04e70 2026-09-13)` +cargo-cgp: the cargo-cgp-driver was built against `rustc 1.99.0-nightly (0123abcde 2026-08-01)`, but the pinned toolchain `nightly-2026-10-10` now provides `rustc 1.101.0-nightly (32dba69d6 2026-10-09)` Run `cargo cgp setup`. ``` @@ -210,7 +210,7 @@ error: unexpected argument '--nope' found `cargo cgp setup` installs the toolchain through rustup, so without rustup it stops at once: ```text -cargo-cgp: installing toolchain `nightly-2026-09-14` (with rustc-dev, llvm-tools)… +cargo-cgp: installing toolchain `nightly-2026-10-10` (with rustc-dev, llvm-tools)… cargo-cgp: rustup was not found on PATH; cargo-cgp requires rustup to manage toolchains ``` From 080c125db58c39f9d6b188c60845f2acd510e2a3 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 25 Oct 2026 18:19:35 +0100 Subject: [PATCH 177/516] Minor edits --- blog/2026-05-10-v0.8.0-release.md | 8 ++++++-- docs/ai/knowledge-base/contributing-with-an-agent.md | 12 ++++++------ docs/ai/knowledge-base/how-cgp-is-documented.md | 4 ++++ docs/ai/knowledge-base/index.md | 8 ++++---- docs/comparisons/policy-based-design.md | 2 +- docs/contribute.md | 4 ---- docs/resources.md | 12 ------------ 7 files changed, 21 insertions(+), 29 deletions(-) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index cfeebe24..41ccae24 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -17,7 +17,11 @@ description: 'CGP v0.8.0 groups components with namespaces and paths, so a wirin ## Improved error diagnostics with cargo-cgp -Since its inception, one of the biggest challenge for users to adopt CGP is the verbose and confusing compile error messages produced by the Rust compiler, even for simple mistakes in a CGP code. This makes it virtually impossible for a new developer to dissect what went wrong in their CGP code, as doing so requires advanced understanding of Rust concepts like traits, generics, as well as internal details of how CGP works. +For those who are new here, Context-Generic Programming (CGP) is a language extension for Rust, with pluggable trait implementations at compile-time. You can learn more about CGP [here](/docs/overview). + +Since its inception, one of the biggest challenge for users to adopt CGP is the verbose and confusing compile error messages produced by the Rust compiler, even for simple mistakes in a CGP code. This is because CGP makes use of advanced traits and type-level machinery to enable new language features in Rust. + +This makes it virtually impossible for a new developer to dissect what went wrong in their CGP code, as doing so requires advanced understanding of Rust concepts like traits, generics, as well as internal details of how CGP works. This long-standing problem has been largely solved in v0.8.0, with the introduction of [**cargo-cgp**](/docs/cargo-cgp), a new tool that you can use in place of `cargo check` to tame the error messages. @@ -97,7 +101,7 @@ Thanks to advance in AI and agentic coding, the CGP website has been overhauled - [Comparison documentation](/docs/comparisons/) to compare similar features in other programming languages with what is offered by CGP. - [Projects documentation](/docs/projects/) to cover example CGP projects that had been highlighted by past blog posts. - [`/cgp` skill](/docs/ai/skills/) to be used by AI agents to proficiently work with CGP. (more on that later) -- A [knowledge base](#) to be used internally by AI agents to work on the CGP project itself. +- A [knowledge base](/docs/ai/knowledge-base/) to be used internally by AI agents to work on the CGP project itself. At this point, some of the AI skeptic readers might think that the AI-generated documentation are just AI slop that are not worth reading. However, the documentation has gone through many iterations of planning and revision to arrive at a significantly higher quality than what would be generated by one-shot prompts. diff --git a/docs/ai/knowledge-base/contributing-with-an-agent.md b/docs/ai/knowledge-base/contributing-with-an-agent.md index 8ccd93e6..17e488a1 100644 --- a/docs/ai/knowledge-base/contributing-with-an-agent.md +++ b/docs/ai/knowledge-base/contributing-with-an-agent.md @@ -24,13 +24,13 @@ written for agents, and to follow the `AGENTS.md` file of each repository it tou contribution then carries the documentation and skill updates the change requires, and it uses the vocabulary and the current syntax the knowledge base records. -The policy exists because an agent working from its training alone writes outdated CGP. It -reproduces syntax that earlier releases accepted and the current one does not, and it guesses at -semantics the knowledge base already states. [How CGP's Documentation Is -Written](how-cgp-is-documented.md) explains the problem and the process that answers it. +The policy exists because CGP lacks presence in today's LLM training data. As a result, agents either +hallucinate with significant misunderstanding about CGP, or use outdated information about CGP. +[How CGP's Documentation Is Written](how-cgp-is-documented.md) explains the problem and the process +that answers it. -**An AI-assisted pull request or issue must include the prompts used to produce it**: the prompt -that verified the issue, or the prompt that applied the fix. The CGP maintainers may run similar +**An AI-assisted pull request or issue must include the prompts that can be used to reproduce similar patch**: +the prompt that verified the issue, or the prompt that applied the fix. The CGP maintainers may run similar prompts themselves rather than merge a pull request directly, so the prompt can be as useful to them as the change. diff --git a/docs/ai/knowledge-base/how-cgp-is-documented.md b/docs/ai/knowledge-base/how-cgp-is-documented.md index da101c73..681875cd 100644 --- a/docs/ai/knowledge-base/how-cgp-is-documented.md +++ b/docs/ai/knowledge-base/how-cgp-is-documented.md @@ -73,6 +73,10 @@ When the macro's output changes, the snapshot changes with it, and the reference implementation document, and the skill are updated in the same change. When the views disagree, the source decides which one is wrong. +The repeating explanation from different views keeps agents from drifting away from the correct +understand of a given CGP construct. Doing so would require the agent to maintain the same +misunderstanding across all views, which is relatively unlikely. + ## Written rules The rules agents follow are written down in the knowledge base and are public. A top-level diff --git a/docs/ai/knowledge-base/index.md b/docs/ai/knowledge-base/index.md index 371662fc..ff8a2867 100644 --- a/docs/ai/knowledge-base/index.md +++ b/docs/ai/knowledge-base/index.md @@ -18,10 +18,10 @@ reference pages on this site, most of its other documentation, and the ## What it is for The knowledge base gives an agent a written record of CGP to read, so the agent does not have to -reconstruct CGP from the macro source or recall it from training. It records the semantics of each -construct, including the syntax forms it accepts and the code each macro expands to. It also holds -the internals of the macros and of [cargo-cgp](/docs/cargo-cgp), the classes of compile error CGP -produces, worked examples, and comparisons with related ideas from other languages. +reconstruct CGP from the macro source or hallucinate on what a given syntax really means. It records +the semantics of each construct, including the syntax forms it accepts and the code each macro +expands to. It also holds the internals of the macros and of [cargo-cgp](/docs/cargo-cgp), the classes +of compile error CGP produces, worked examples, and comparisons with related ideas from other languages. The [agent skill](/docs/ai/skills) is the part of this record sized for everyday work: it fits in an assistant's context and teaches it to read and write CGP code. The knowledge base is the exhaustive diff --git a/docs/comparisons/policy-based-design.md b/docs/comparisons/policy-based-design.md index 4e2f7ff6..59fa9ac0 100644 --- a/docs/comparisons/policy-based-design.md +++ b/docs/comparisons/policy-based-design.md @@ -1,6 +1,6 @@ --- sidebar_label: 'Policy-based design' -sidebar_position: 2 +sidebar_position: 5 description: 'CGP read against C++ policy classes, host templates, CRTP, and concepts, for a reader who composes behavior with templates.' --- diff --git a/docs/contribute.md b/docs/contribute.md index de48c2a5..a7725352 100644 --- a/docs/contribute.md +++ b/docs/contribute.md @@ -50,10 +50,6 @@ already covered on the official site, your perspective might make it clearer to If you appreciate my work and want to see CGP gain wider adoption, the best way to support it is to *sponsor* me, regardless of the amount. I have sponsorship pages on [Github Sponsor](https://github.com/sponsors/soareschen/), [Patreon](https://www.patreon.com/c/maybevoid/about), and [Ko-Fi](https://ko-fi.com/maybevoid). -*As with most open-source projects*, I don't expect sponsorship to be enough to allow me to quit my job and work full-time on CGP, or even *with* CGP. *However*, any financial support will significantly boost my confidence in the *value* of my work and encourage me to continue dedicating hundreds of hours of my free time to it instead of other pursuits. - -I do hope to eventually spend a year or two working full-time on CGP using my *personal savings*, even if sponsorships don't cover my living expenses. *However*, exponential growth is important, and if I could secure around a quarter of my living expenses through monthly sponsorship, it would reduce some risk and suggest a higher chance of CGP becoming self-sustaining later on. - # Acknowledgement CGP is created by [Soares Chen](https://maybevoid.com/), with inspiration drawn from various programming languages and paradigms, particularly Haskell typeclasses. diff --git a/docs/resources.md b/docs/resources.md index be68b02e..f41a7177 100644 --- a/docs/resources.md +++ b/docs/resources.md @@ -37,18 +37,6 @@ Install it with `cargo install cargo-cgp`, then run `cargo cgp setup` to provisi [Read the full transcript here](/blog/rustlab-2025-coherence) -## Books - -- [Context-Generic Programming Patterns](https://patterns.contextgeneric.dev/) - Builds CGP's constructs from first principles, for readers who want to understand what happens behind the macros. Its early chapters explain the ideas in ordinary Rust and remain accurate; its later chapters were written against an earlier release and show syntax that has since changed. - -## CGP in production - -[Hermes SDK](https://github.com/informalsystems/hermes-sdk/) is the system CGP was built for and the -largest real-world use of it. It is an inter-blockchain relayer developed at -[Informal Systems](https://informal.systems/), and its need to support many chains and configurations -from one codebase is the problem the paradigm grew out of. If you are evaluating whether CGP holds up -beyond small examples, this is the codebase to read. - ## Projects - [CGP Examples](https://github.com/contextgeneric/cgp-examples) - A repository hosting various examples of using CGP. Documented on this site in the [Projects](/docs/projects/cgp-examples/) section, with its examples walked through as short tutorials. From b2b391e2096aaf20b8dd8493ddcbf122710bc5ad Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 25 Oct 2026 23:07:11 +0100 Subject: [PATCH 178/516] Revise v0.8.0 release announcement and verify examples --- blog/2026-05-10-v0.8.0-release.md | 615 +++++--- example-code/README.md | 2 + example-code/tests/blog/v0_8_0_release.rs | 1272 +++++++++++++++++ example-code/tests/blog_tests.rs | 8 + .../blog/v0_8_0_missing_height.rs | 27 + .../blog/v0_8_0_missing_height.stderr | 28 + 6 files changed, 1753 insertions(+), 199 deletions(-) create mode 100644 example-code/tests/blog/v0_8_0_release.rs create mode 100644 example-code/tests/blog_tests.rs create mode 100644 example-code/tests/compile_fail/blog/v0_8_0_missing_height.rs create mode 100644 example-code/tests/compile_fail/blog/v0_8_0_missing_height.stderr diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index 41ccae24..67655040 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -1,31 +1,40 @@ --- slug: 'v0.8.0-release' authors: [soares] -tags: [release] -description: 'CGP v0.8.0 groups components with namespaces and paths, so a wiring table stays readable as an application''s component count grows.' +tags: [release, deepdive] +description: 'CGP v0.8.0 introduces cargo-cgp diagnostics, expanded documentation and an agent skill, and namespace groups for component wiring.' --- -# CGP v0.8.0 - Namespaces, cargo-cgp, and AI-assisted development +# CGP v0.8.0 - cargo-cgp, new documentation, and namespaces -**CGP v0.8.0** has been released, and it comes with major ergonomic improvements to Context-Generic Programming (CGP) in the following area: +**CGP v0.8.0 has been released with improvements to debugging, documentation, and component wiring.** Alongside the release, cargo-cgp helps explain wiring failures. The website now provides reference material, conceptual explanations, and project walkthroughs, while namespaces let growing applications group related wiring and make configuration differences easier to see. -- [Improved error diagnostics with cargo-cgp](#improved-error-diagnostics-with-cargo-cgp) -- [AI-generated documentation and skill](#ai-generated-documentation-and-skill) -- [Grouping components with namespaces and paths](#grouping-components-with-namespaces-and-paths) +{/* truncate */} - +Context-Generic Programming (CGP) is a language extension for Rust, with pluggable trait implementations at compile-time. It is an ordinary library on stable Rust: applications select providers through wiring that resolves to static calls. You can adopt it one component at a time. The [Overview](/docs/overview) explains the model. -## Improved error diagnostics with cargo-cgp +You can read the tooling and documentation news before the longer namespace walkthrough. The post starts with cargo-cgp and the new documentation, then develops the namespace feature through a social-media application. Allow about 35 minutes for the full post, including the code, or jump to the section you need: -For those who are new here, Context-Generic Programming (CGP) is a language extension for Rust, with pluggable trait implementations at compile-time. You can learn more about CGP [here](/docs/overview). +- [Diagnosing wiring with cargo-cgp](#diagnosing-wiring-with-cargo-cgp) +- [Expanded documentation and optional agent support](#expanded-documentation-and-optional-agent-support) +- [Grouping component wiring with namespaces](#grouping-component-wiring-with-namespaces) +- [Sharing default implementations](#default-implementations) +- [Other improvements](#other-improvements) +- [Breaking changes and migration](#breaking-changes-and-migration) -Since its inception, one of the biggest challenge for users to adopt CGP is the verbose and confusing compile error messages produced by the Rust compiler, even for simple mistakes in a CGP code. This is because CGP makes use of advanced traits and type-level machinery to enable new language features in Rust. +## Diagnosing wiring with cargo-cgp -This makes it virtually impossible for a new developer to dissect what went wrong in their CGP code, as doing so requires advanced understanding of Rust concepts like traits, generics, as well as internal details of how CGP works. +Verbose and confusing compiler errors have been one of the largest obstacles to adopting CGP since the project began. Even a simple mistake, such as forgetting a field or a component binding, can produce a diagnostic naming generated traits and type-level encodings of fields or paths. CGP uses that machinery to support interchangeable implementations, but the compiler reports errors in terms of the Rust it receives after macro expansion. -This long-standing problem has been largely solved in v0.8.0, with the introduction of [**cargo-cgp**](/docs/cargo-cgp), a new tool that you can use in place of `cargo check` to tame the error messages. +Diagnosing a small mistake can require newcomers to understand advanced Rust traits and generics, together with the internal details of CGP. A developer can understand what their code is supposed to do and still struggle to work out why it does not compile. Better syntax alone does not address that barrier. -To see how cargo-cgp works, let's look at a simple example from the [area calculation example](/docs/tutorials/area-calculation/static-dispatch): +[cargo-cgp v0.1.0](/docs/cargo-cgp) helps developers find missing dependencies without reconstructing the generated code first. I am introducing this separate tool for checking CGP code and inspecting macro expansions alongside CGP v0.8.0. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. + +### Find a missing field + +A missing `height` field demonstrates how cargo-cgp explains a wiring failure. In this example from the [area-calculation tutorial](/docs/tutorials/area-calculation/static-dispatch), the context is `Rectangle` itself, the value being operated on. Its area provider needs both `width` and `height`, but the struct supplies only `width`. + +Save this library example as `src/lib.rs` in a Cargo package using `cgp = "0.8.0"`: ```rust use cgp::prelude::*; @@ -55,75 +64,152 @@ delegate_and_check_components! { } ``` -In the example above, we intentionally forget to include a `height` field in our `Rectangle` struct, causing it to fail to implement `CanCalculateArea` via the `RectangleArea` provider. If you try to compile the code with `cargo check`, you would see errors that show something like: +The wiring check fails because `RectangleArea` requires a field that `Rectangle` lacks. `RectangleArea` reads its implicit arguments from the context's fields, and the wiring selects it for `AreaCalculatorComponent`. `delegate_and_check_components!` checks that the provider's dependencies are satisfied. Running `cargo cgp check` identifies the missing field: ```text -error[E0277]: the trait bound `Rectangle: HasField>>` is not satisfied +error[E0277]: [CGP-E001] missing field `height` on `Rectangle` + --> src/lib.rs:23:9 | -28 | AreaCalculatorComponent, - | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound +23 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ | -help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` + = note: root cause: [CGP-E110] missing field `height` on `Rectangle` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` + └─ [CGP-E110] missing field `height` on `Rectangle` + = help: add the field `height: f64` to `Rectangle` ``` -Which is not very easy to understand, especially for someone who are new to CGP. Now with cargo-cgp, you can instead run `cargo cgp check` and get the following error: +The rewritten diagnostic names the missing field and the change needed to supply it. Its dependency tree explains why the field is required. Plain `cargo check` reports the same mistake through generated traits and a nested `Symbol` type: + +

+Compare the output from cargo check ```text -error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` - --> src/lib.rs:28:9 +error[E0277]: the trait bound `Rectangle: CanUseComponent` is not satisfied + --> src/lib.rs:23:9 | -28 | AreaCalculatorComponent, - | ^^^^^^^^^^^^^^^^^^^^^^^ +23 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound | - = note: root cause: [CGP-E106] missing field `height` on `Rectangle` - this is required through the dependency chain: - [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` - └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` - └─ [CGP-E106] missing field `height` on `Rectangle` +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>` is implemented for it + --> src/lib.rs:17:9 + | +17 | pub width: f64, + | ^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> src/lib.rs:8:1 + | + 8 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Rectangle` to implement `CanUseComponent` +note: required by a bound in `__CanUseRectangle` + --> src/lib.rs:21:1 + | +21 | / delegate_and_check_components! { +22 | | Rectangle { +23 | | AreaCalculatorComponent: RectangleArea, +24 | | } +25 | | } + | |_^ required by this bound in `__CanUseRectangle` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `delegate_and_check_components` (in Nightly builds, run with -Z macro-backtrace for more info) +``` + +
+ +Add the field to repair the program: + +```rust +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + pub height: f64, +} +``` + +Adding `height` makes the wiring check pass. The provider can then read both fields and calculate the area. + +cargo-cgp extracts the root cause through the Rust compiler's API. It wraps a nightly compiler, uses that API to inspect the failed dependencies, and formats their chain. This gives it access to information that would otherwise be difficult to recover from the printed diagnostic alone. + +### Try the checker + +Install cargo-cgp with cargo and rustup, then run it inside your CGP project. The installation commands build the front-end and provision its compiler-linked driver: + +```sh +cargo install cargo-cgp +cargo cgp setup +# Run this from your CGP project's directory: +cargo cgp check ``` -which tells you precisely that `Rectangle` is missing a field `height`, and the dependency chain that requires the field. +cargo-cgp's nightly is separate from your application's normal toolchain. `cargo cgp setup` installs the tool's pinned nightly and builds the matching driver for its checks. Your application keeps its normal toolchain for ordinary cargo builds, and CGP itself still compiles on stable Rust. cargo-cgp is optional. + +The tool is tested on Linux. macOS and Windows are untested. + +Use plain cargo to build, run, and test applications. cargo-cgp supplies `check` for diagnostics and [`expand`](/docs/cargo-cgp/expand) for reading the Rust generated by macros, with CGP's type-level constructs restored to readable notation. The [installation guide](/docs/cargo-cgp/installation) covers setup, updates, and the Nix alternative. + +## Expanded documentation and optional agent support + +The lack of documentation has been another long-standing obstacle to learning CGP. Until now, the main explanations lived in blog posts, which introduced features as they were released but did not have room to explain every construct and how the pieces fit together. A reader could learn about a feature in an announcement and still lack the reference material needed to use it independently. + +My available time has limited how much documentation I could write for CGP. It is a side project, and writing a comparable body of documentation entirely by hand would likely take months of full-time work. I do not expect to have that time for the project in the near future. Waiting until I could write it all myself would leave readers facing the same gaps. + +AI agents made the documentation work practical within my available time. Advances in AI and agentic coding let me build out the material, primarily through Claude Code, over many iterations of planning and revision. The website now gives readers several ways into the same subject: -Behind the scene, cargo-cgp wraps around a nightly Rust compiler, and uses the Rustc API to extract the root cause of CGP errors, and format them to become easily readable by users. +- [Reference](/docs/reference/): accepted syntax, examples, and generated code for CGP constructs. +- [Concepts](/docs/concepts/): explanations of ideas such as provider composition, abstract types, and namespaces. +- [Comparisons](/docs/comparisons/): how CGP relates to similar features in other programming languages and approaches, including the limits of those comparisons. +- [Projects](/docs/projects/): walkthroughs of CGP projects highlighted in earlier blog posts and the patterns their code demonstrates. +- [The `/cgp` skill](/docs/ai/skills/): a foundation for AI assistants working with CGP, described below. +- [The knowledge base](/docs/ai/knowledge-base/): the fuller record used by agents working on CGP itself, including its implementation and documentation. -Read the [cargo-cgp documentation](/docs/cargo-cgp) to learn more about how to install and use it using `cargo install`. +The documentation's scale helps explain my estimate of months of full-time writing. The website now contains roughly 330,000 words of documentation prose across more than 340 pages, excluding code blocks and the mirrored skill files. At 300 words per printed page, that is about 1,100 pages before code listings. The actual printed length would depend on the layout. -## AI-generated documentation and skill +Repeated planning, source checks, and revision are essential to the quality I am aiming for. I understand why readers may be skeptical of AI-written documentation, and I would not expect a one-shot prompt to produce useful documentation at this scale. I encourage you to read it and tell me where an explanation is vague, incorrect, or reads like generic AI output. -Aside from poor error diagnostics, which is now solved by cargo-cgp, the CGP project had a long-standing problem of lack of documentation to explain all concepts and features available in CGP. Up until now, the main source of documentation for CGP had been the blog posts, which did not have the space to properly explain everything. The lack of documentation is not due to any technical challenges, but simply the lack of personal time by the author to invest for the side project. +### How the documentation is written -Thanks to advance in AI and agentic coding, the CGP website has been overhauled with comprehensive documentation that are largely written by Claude Code. The documentation now includes: +The knowledge base gives agents a written account of CGP to work from. It records how CGP works, so an agent can consult it rather than write a page from what it remembers. I direct the work, set the rules, and choose what gets documented. -- A comprehensive [reference documentation](/docs/reference/) to cover every feature available in CGP. -- [Concept documentation](/docs/concepts/) to walk through the high level programming concepts introduced by CGP. -- [Comparison documentation](/docs/comparisons/) to compare similar features in other programming languages with what is offered by CGP. -- [Projects documentation](/docs/projects/) to cover example CGP projects that had been highlighted by past blog posts. -- [`/cgp` skill](/docs/ai/skills/) to be used by AI agents to proficiently work with CGP. (more on that later) -- A [knowledge base](/docs/ai/knowledge-base/) to be used internally by AI agents to work on the CGP project itself. +Agents check technical claims against the implementation, tests, and expansion snapshots. Those checks cover syntax and macro expansions. The website pages are then written from the knowledge base and revised against the project's writing guides. -At this point, some of the AI skeptic readers might think that the AI-generated documentation are just AI slop that are not worth reading. However, the documentation has gone through many iterations of planning and revision to arrive at a significantly higher quality than what would be generated by one-shot prompts. +The written record also supports later revisions without requiring each agent to reconstruct CGP from scratch. That reuse helps me expand the documentation with the time available to me. The [knowledge-base overview](/docs/ai/knowledge-base/) explains the record and its role in the project. -The current documentation covers roughly X number of words that would span X pages. It is also worth stating the alternative, which is human-written documentation, would likely take months of full time work by the author to write the same amount of content, which is unlikely to happen anytime in the near future. +Human review varies by page. I read the argument-bearing pages in full, including the Concepts explanations and blog posts. Individual reference pages follow their writing guides and receive spot checks. The knowledge base is [still being reviewed](/docs/ai/knowledge-base/#its-current-state), and both source checks and human review can miss errors. I remain responsible for what the project publishes. -Explaining the full methodology is something that is worth covering in a dedicated follow up blog post in the future. But for now, I highly recommend you to take a look at it, and give me feedback for improvement if you still find any content that you consider slop. +[How CGP's Documentation Is Written](/docs/ai/knowledge-base/how-cgp-is-documented) explains how claims are checked and where those checks stop. The [AI disclosure](/docs/ai/disclaimer) describes who writes and reviews the documentation, tooling, and core library. -### The `/cgp` skill +I would like to explore the methodology further in a dedicated follow-up post. For now, [the process page](/docs/ai/knowledge-base/how-cgp-is-documented) explains how the documentation is produced and checked. -CGP v0.8.0 comes with a comprehensive [`/cgp` skill](/docs/ai/skills/) to equip AI agents with foundational understanding to proficiently write CGP code. This further reduces the learning curve required for you to start writing CGP code today. +### Optional help from the `/cgp` skill -If you are new to CGP and want to get started, the easiest way is to try out some simple example with an AI agent, and ask your agent how the code works in case you are stuck on anything. The skill should allow your agent to properly work out the internal details of CGP macros, install and use cargo-cgp to diagose errors for you, and explain CGP concepts in a way that matches your level of expertise. +The [`/cgp` skill](/docs/ai/skills/) teaches an AI assistant the foundations of reading and writing current CGP code. It covers the consumer/provider model, wiring, dependency declarations, and using cargo-cgp to investigate failures. The skill is a condensed guide for an agent, while the knowledge base supplies the fuller record it can consult. -## Grouping components with namespaces and paths +The skill can help you learn CGP through a small example, with explanations suited to your Rust experience. If you are new to CGP and already work with an assistant, load the skill and ask it to explain unfamiliar parts of the example. It can help investigate macro expansions, guide you through installing and using cargo-cgp, and diagnose errors. The goal is to reduce how much you need to learn upfront by exploring the internal details as questions arise. -Up until now, one of main challenges of using CGP is on the boilerplate of using `delegate_components!` to wire CGP providers, especially as the number of CGP components grow within an application. When there are too many entries inside `delegate_components!`, developers quickly get lost on what they should pay attention to, and it gives the impression that the application becomes too complex. +You still need to review and verify the assistant's suggested code. The [skill instructions](/docs/ai/skills/) explain how to install and use the skill, and [Using the Knowledge Base with Your Agent](/docs/ai/knowledge-base/using-it-with-your-agent) covers deeper investigation. Neither is required to use CGP. -CGP v0.8.0 introduces a new primitive called **namespaces**, which allows components to be grouped and dispatched while significantly reduce the boilerplate required. +## Grouping component wiring with namespaces -### An example social media web app +Flat wiring tables can make growing CGP applications difficult to understand. Splitting an application into reusable providers makes dependencies easier to isolate, but each component also needs a routing entry in a flat `delegate_components!` table. As the component count grows, that list can obscure which choices matter and make the application look more complicated than the behavior it implements. -To demonstrate the challenge, we will make use of a simple web application as an example. Suppose that we want to build a simple social media web app, we could use CGP to define modular traits to expose simple CRUD capabilities for managing users and posts. A simplified version of the traits would look something like follows: +Provider bundles did not remove repeated component lists from top-level wiring. CGP could already bundle implementations, but applications still had to enumerate the corresponding component keys. The preset system was an earlier attempt to reduce that repetition, with limitations explained below. + +Namespaces let an application select related implementations as a group. In the example below, production and test configurations share a PostgreSQL-backed core and differ in their content filters. A table that lists every component becomes a table selecting those groups, making the difference between configurations visible in one entry. + +You can skip the motivation if you already know why flat wiring tables become difficult to maintain. Jump to [the namespace syntax](#introducing-cgp-namespaces-and-paths), or to [the migration guide](#breaking-changes-and-migration) if you are upgrading an existing application. The walkthrough below builds up the wiring problem before introducing the solution. + +### Start with a manager per domain {#an-example-social-media-web-app} + +The running example uses an application context to select the operations of a social-media service. It holds a database handle and chooses the implementations for managing users and posts. Here the context represents the service, while the earlier `Rectangle` context was the data being operated on. + +The snippets illustrate wiring rather than a complete web service. They assume `use cgp::prelude::*;` and omit domain type declarations and database query bodies. The [web-app walkthrough](/docs/projects/cgp-examples/web-app) follows the same example, and its [compiling source](https://github.com/contextgeneric/cgp-examples/tree/v0.8.0/web-app) uses placeholder database operations. + +Each stage replaces the preceding definitions or wiring. Treat a revised provider or table as a replacement, rather than adding a second implementation beside the previous one. + +The initial design groups user and post operations into a manager trait per domain: ```rust #[cgp_component(UserManager)] @@ -147,7 +233,11 @@ pub trait CanManagePost { } ``` -Our trait definitions are as straightforward as vanilla trait definitions, aside from the use of `#[cgp_component]` to turn them into CGP traits. The main advantage is that we can now define context-generic implementations for the traits. For example, we can implement production-ready providers as follows: +`#[cgp_component]` separates each trait's calling interface from its provider implementations. It turns the ordinary trait into a CGP component, generating a provider trait such as `UserManager` and a wiring key such as `UserManagerComponent`. A provider implements the operations independently of a concrete application, and the application's wiring chooses which provider to use. + +Grouping items in a component makes one provider choice decide their implementations together. Component traits can contain multiple methods, associated types, and constants, so grouping the manager methods is a design choice. + +The database providers can remain independent of any concrete application context: ```rust #[cgp_impl(new PostgresUserManager)] @@ -217,11 +307,9 @@ impl PostManager { } ``` -Our production provider implementations are not coupled with any concrete application context, and CGP allows us to reuse it on any application context that provides the required dependencies, such as the PostgreSQL `database` field. +Both providers read a PostgreSQL `database` field through their implicit arguments. Any context supplying that dependency can reuse the implementations. We could also define `SqliteUserManager` and `SqlitePostManager` providers for a SQLite-backed application, without changing the manager interfaces. -CGP also enables us to define other context-generic provider implementations for the traits, such as an `SqliteUserManager` and `SqlitePostManager` that implements the queries using SQLite instead of PostgreSQL. - -With this minimal settings, the configuration for our production application is straightforward, and can be written as follows: +The initial production configuration needs only two entries: ```rust #[derive(HasField)] @@ -237,13 +325,11 @@ delegate_and_check_components! { } ``` -With just two lines of configurations, we have managed to configure our `ProductionApp` to use the `PostgresUserManager` and the `PostgresPostManager` providers that we have defined, without tightly coupling the implementations with the `ProductionApp` context. - -#### Filtering usernames and post messages +`ProductionApp` selects both managers without coupling their implementations to that context. At this stage, the database field is their only dependency. -Our base implementation of `PostgresUserManager` and `PostgresPostManager` only have a single dependency to the PostgreSQL database. But as the application grows, the methods may require additional dependencies to implement more features. +### Add dependencies as the service grows -For example, we may want to ban certain words in the username, or detect and reject spam messages when creating a post. With the earlier traits, we may implement those functionalities as follows: +Content filtering adds dependencies to the database-backed managers. As the service grows, user creation needs username filtering and post creation needs spam detection, so the managers acquire dependencies on two more components: ```rust #[cgp_component(UsernameCensor)] @@ -266,7 +352,7 @@ impl UserManager { email: &Email, ) -> Result { if self.username_is_censored(username) > Probability::new(0.8) { - return Err(Error::InvalidUsername) + return Err(Error::InvalidUsername); } // ... @@ -285,7 +371,7 @@ impl PostManager { content: &str, ) -> Result { if self.message_is_spam(content) > Probability::new(0.8) { - return Err(Error::InvalidMessage) + return Err(Error::InvalidMessage); } // ... @@ -295,14 +381,14 @@ impl PostManager { } ``` -In the above example, we introduce two new CGP traits, `UsernameCensor` and `SpamMessageDetector`, to be used by `PostgresUserManager` and `PostgresPostManager`. The providers make use of the probability scores returned by the filters to determine whether to reject the creation of a user or post. +The managers use the filter scores to decide whether to reject a user or post. `CanCensorUsername` and `CanDetectSpamMessage` return the scores compared with the threshold. `#[uses]` declares each trait dependency on the context, while `#[implicit] database` reads its database field. The remaining manager methods are omitted here. -In production, the implementation of features like spam filters may employ sophisticated setup, such as using AI or a cloud service provider. But in testing environments, we may want to make use of simplified setup to test the other parts of the application more quickly. With CGP, we can do so by defining two separate contexts such as follows: +Production and tests can share the database providers while choosing different filters. Production filtering may involve an AI model or a cloud service, while tests can use deterministic string matching to exercise the rest of the application more quickly: ```rust +#[derive(HasField)] pub struct ProductionApp { pub database: PostgresDb, - // ... } delegate_components! { @@ -314,13 +400,13 @@ delegate_components! { } } +#[derive(HasField)] pub struct TestApp { pub database: PostgresDb, - // ... } delegate_components! { - ProductionApp { + TestApp { UserManagerComponent: PostgresUserManager, PostManagerComponent: PostgresPostManager, UsernameCensorComponent: DummyUserCensor, @@ -329,21 +415,21 @@ delegate_components! { } ``` -In the example above, we have a `ProductionApp` that is used in production, and a `TestApp` that is used for testing. Both `ProductionApp` and `TestApp` make use of the same PostgreSQL database backend, and thus they reuse the same `PostgresUserManager` and `PostgresPostManager` providers. But `ProductionApp` uses providers that make use of AI to detect spam and censored usernames, while `TestApp` uses dummy implementation that performs detection with simple string pattern matching. +Both contexts reuse the PostgreSQL managers and supply the fields those managers require. Their different filter choices distinguish production from testing. `#[derive(HasField)]` makes each context's `database` field available to the providers' implicit arguments. -As we can see, CGP makes it easy to organically extend the dependency tree of an application context. However, with the transitive dependencies, we now have 4 items listed in 2 contexts, resulting in 8 wiring configuration entries. +These tables record choices without checking all their dependencies. Explicit component checks, shown below, verify that the selected providers can be used. -#### Fine grained traits +Adding dependencies also increases the wiring repeated across contexts. CGP lets the application's dependency tree grow as requirements are added, but four component entries on each of two contexts already means eight wiring entries. -If we look carefully at the implementation of `PostgresUserManager`, we can notice that the trait `CanCensorUsername` is not really needed by `get_user` and `update_user_data`. Similarly, in `PostgresPostManager`, the trait `CanDetectSpamMessage` is not needed by `get_post`, `update_post`, and `delete_post`. +### Split independently reusable operations {#fine-grained-traits} -In practice, the accumulation of dependencies like `CanDetectSpamMessage` can quickly pile up in trait implementations, especially when the number of trait methods increases. The long list of dependencies can make it harder to maintain and test the implementations. +A manager provider makes every operation require all of that provider's dependencies. `get_user` needs the database, but it also requires a context implementing `CanCensorUsername` because that bound belongs to `PostgresUserManager`. The post manager has the same problem with spam detection. As more methods acquire unrelated dependencies, the manager becomes harder to maintain and test. -As the application grows, pressure will increase on how to better organize which method belongs to which trait. For example, we may need to decide whether a `get_user_profile_picture` method should belong to the `UserManager` trait. Furthermore, when a method involves multiple domains, such as `get_user_posts`, it is not clear whether they should be placed in `UserManager` or `PostManager`. +Domain names also leave questions about which operations belong together. Should `get_user_profile_picture` be part of the user manager, and should `get_user_posts` belong to the user or post manager? A single domain name does not always identify the right group of operations. -In more advanced use cases, we may also want to make use of CGP to isolate capabilities that can be used in a piece of code. For example, since user deletion is very destructive, we may not want to expose a `delete_user` method to all code that have access to `UserManager`. +Narrower trait bounds let generic code request fewer operations. If a user manager gains a destructive `delete_user` operation, code that only retrieves users should not have to depend on the whole manager interface. Separate bounds let that code require only the operations it needs. -One of the simple but powerful design patterns that is enabled by CGP is that we can break down monolithic trait definitions like `UserManager` into *fine-grained traits* that each contains only one or a handful of items. For example: +Fine-grained components, each containing one or a handful of related items, let each provider require only what it uses: ```rust #[cgp_component(UserCreator)] @@ -362,7 +448,7 @@ pub trait CanUpdateUser { } ``` -With the fine grained traits, it becomes much easier for us to isolate the dependencies and only expose them to implementations that really need them. For example, the `CanCensorUsername` consumer trait can now be imported in the `UserCreator` implementation: +The user-creation provider needs the censor, while the getter needs only the database: ```rust #[cgp_impl(new CreateUserWithPostgres)] @@ -375,7 +461,7 @@ impl UserCreator { email: &Email, ) -> Result { if self.username_is_censored(username) > Probability::new(0.8) { - return Err(Error::InvalidUsername) + return Err(Error::InvalidUsername); } // ... @@ -390,11 +476,11 @@ impl UserGetter { } ``` -Instead of having a monolithic `PostgresUserManager` provider, we now have fine grained providers like `CreateUserWithPostgres` and `GetUserWithPostgres` that implement each fine grained trait separately. We can also see that the dependency to `CanCensorUsername` is only present in the implementation of `CreateUserWithPostgres`, while other providers like `GetUserWithPostgres` can work fine without requiring that trait to be implemented by the context. +The dependencies now follow the individual operations. `CreateUserWithPostgres` imports `CanCensorUsername`, while `GetUserWithPostgres` does not. The post manager can be split in the same way into creation, retrieval, update, and deletion components. Generic code bounded by `CanGetUser` can retrieve users without requiring user creation or deletion. -#### Higher-order providers +### Separate filtering from database access -Another key advantage of using fine grained traits is that we can now easily define *higher-order providers* that wrap around other provider implementations. For example, we can extra the logic of banning censored username into a separate provider like follows: +A filtering wrapper can now add the username check to any user-creation provider: ```rust #[cgp_impl(new FilterCensoredUsername)] @@ -423,15 +509,15 @@ impl UserCreator { } ``` -In the example above, we introduce a higher-order provider called `FilterCensoredUsername`, which can wrap around an inner provider for `UserCreator`. It would reject a call to `create_user` based on the result from `CanCensorUsername`. Otherwise, it forwards the call to the inner provider. +`FilterCensoredUsername` is a **higher-order provider**: it takes another provider as a parameter. `#[use_provider]` requires that inner provider to implement user creation for the same context. The wrapper rejects censored names and otherwise calls the inner provider. -With this separation of concern, we can now remove the dependency on `CanCensorUsername` from `CreateUserWithPostgres`, which can now focus purely on constructing the SQL insert query. Instead of always filtering the username, the logic becomes composable, allowing the concrete context to choose either just `CreateUserWithPostgres` or the combined `FilterCensoredUsername` provider to handle user creation. +Filtering is now a wiring choice separate from database access. `CreateUserWithPostgres` can focus on constructing the SQL insert query, while the context chooses either that provider directly or `FilterCensoredUsername`. A local-first application could reuse the wrapper as `FilterCensoredUsername`, without changing the filtering implementation. -This separation of concern also allows logic like `FilterCensoredUsername` to be reused with other inner providers. For example, suppose that we also have a separate `CreateUserWithSqlite` provider that can be used by a local-first application. We can now enable the filtering of user creation using `FilterCensoredUsername`. +`FilterSpamMessage` applies the same separation to post creation. It uses `CanDetectSpamMessage` to reject spam, then forwards an allowed post to its inner `PostCreator`. The wiring can therefore choose `FilterSpamMessage` independently of the database provider's implementation. -#### Too much wiring with fine grained traits +### Count the cost of the separation -As we can see, the use of fine grained traits and higher order providers allows us to nicely decompose and decouple the dependencies that each trait needs. However, the main issue with this approach is that the boilerplate for wiring the components become significantly more verbose. For instance, the wiring for `ProductionApp` would become: +The smaller components isolate dependencies and make the filtering reusable, but they add wiring. With seven CRUD operations and two filters, the production table becomes: ```rust delegate_components! { @@ -458,13 +544,11 @@ delegate_components! { } ``` -Compared to before, there are now 9 component entries in `ProductionApp`, as compared to the list of 4 components earlier. And given that this example only include minimal features, it is not uncommon for real world applications to have dozens if not hundreds of component wirings if fine grained traits are used. +The small example now needs nine component entries instead of four. An application with more features can grow to dozens or hundreds of wiring entries. To someone unfamiliar with the code, that list can obscure what `ProductionApp` implements and make adopting CGP look harder than it needs to be. -This presents a significant challenge to spread the adoption of CGP. To the eyes of an untrained developers, the hundreds of lines of component wirings are noise that brings confusion on what `ProductionApp` really implements. +Grouping the bindings would let a reader understand one part of the application at a time. The flat table presents too much information at once, so it needs smaller units. -If we consider the principles of good programming practices, the real problem with the code above is that too much information are presented at once. What we need is to group the component wirings back into smaller sub-units, so that they can be read and understood piece by piece. - -For example, we could group the user-related traits together as follows: +A provider bundle can collect related bindings into a smaller table: ```rust delegate_components! { @@ -479,13 +563,9 @@ delegate_components! { } ``` -With the code above, we define an *aggregated provider* called `PostgresUserComponents` which encapsulates all PostgreSQL-based user-related providers. Since this standalone definition only contains 3 entries, it is much more manageable to understand what this aggregated provider implements. - -Similarly, we can define a `PostgresPostComponents` to group all PostgreSQL-based post-related providers, and a `AiContentFilterComponents` to group the AI-based username and spam message filter providers. - -#### The challenges of grouping delegate component keys +`new PostgresUserComponents` declares an **aggregate provider**, a provider whose table delegates each operation to another provider. Its three entries can be read independently of the rest of the application. `PostgresPostComponents` can collect the post operations, and `AiContentFilterComponents` can collect the AI-backed filtering providers. -However, before the current v0.8.0 release, even though we have ways to group CGP component wirings, there lacked good developer experience for using these aggregated providers at the top-level component wiring. For example, the component wiring for `ProductionApp` can at best be simplified into: +Bundles organize the implementations, but without namespaces the application must still enumerate every key when forwarding to them: ```rust delegate_components! { @@ -512,11 +592,13 @@ delegate_components! { } ``` -In the code above, we make use of the array notation to forward a group of keys, such as `UserCreatorComponent`, `UserGetterComponent`, and `UserUpdaterComponent`, all to the same aggregated provider, i.e. `PostgresUserComponents`. +Array keys still leave each component group unnamed. They send several components to the same bundle, but the application cannot refer to “all user components” or “all content filters” as a group. Adding a user operation therefore means updating both the bundle and the component list on each application that forwards to it. -The problem we have here is that CGP had no way encapsulate the group of component keys used in the wiring. What we really wanted is to express something like follows: +### Why the earlier grouping approaches were insufficient -```rust +The desired configuration would let us name each group once. In pseudocode, it would look like this: + +```text delegate_components! { ProductionApp { ???: // all user components @@ -529,11 +611,11 @@ delegate_components! { } ``` -However, due to how CGP internally makes use of the trait system, it is not possible to directly express something like *"implement `DelegateComponent` for these list of types"* with Rust's existing trait system. +Rust's trait system does not provide an operation that expands a type-level list into a separate implementation for every listed key. CGP therefore needs a way to express the grouping through its own lookup rules or macro expansion. -The closest technique that CGP could use is to use macros to expand the identifier, such as: +A macro that expands to a list of component keys might appear to solve the repetition. Another hypothetical form is: -```rust +```text delegate_components! { ProductionApp { all_user_components!(): @@ -546,86 +628,51 @@ delegate_components! { } ``` -where the macros like `all_user_components!()` expand into `[UserCreatorComponent, UserGetterComponent, UserUpdaterComponent]`. But even this wouldn't work, because Rust macros are expanded lazily, meaning that `delegate_components!` could only see the unexpanded literal `all_user_components!()`, and thus cannot properly desugar the entries. - -Furthermore, there is no easy way for CGP to generate macros like `all_user_components!()` for the user. That is, there are limited support in Rust's macro system to allow macros to generate and export new macros. - -#### The problems with CGP presets - -Since the early days of the project, we have experimented with various ways to work around the limitations of Rust macros, and implemented a [**preset system**](/blog/hypershell-release#cgp-presets) system to group a collection of component wirings together to form a preset. However, there are many issues with providing a good developer experience through CGP presets. - -With CGP presets, we could define a `PostgresUserComponents` preset like follows: - -```rust -cgp_preset! { - PostgresUserComponents { - UserCreatorComponent: - FilterCensoredUsername, - UserGetterComponent: - GetUserWithPostgres, - UserUpdaterComponent: - UpdateUserWithPostgres, - } -} -``` - -and then use the components by inheriting it in `ProductionApp`: +The proposed helpers would supply a component list for each group. For example, `all_user_components!()` would expand to `[UserCreatorComponent, UserGetterComponent, UserUpdaterComponent]`, with corresponding lists for posts and filters. These are hypothetical forms, not supported syntax. -```rust -#[cgp_inherit(PostgresUserComponents)] -pub struct ProductionApp { /* ... */ } +The outer macro cannot inspect a helper's output when it parses the invocation. `delegate_components!` receives `all_user_components!()` before the helper expands, so the component list is unavailable to its parser. Supporting this arrangement would require a different macro-composition mechanism, together with machinery for generating and exporting helpers whose names and imports remain usable across crate boundaries. -delegate_components! { - ProductionApp { - // No need to delegate entries in PostgresUserComponents - // ... - } -} -``` +My earlier [preset system](/blog/hypershell-release#cgp-presets) shared wiring but made independent groups difficult to combine. Its inheritance mechanism could supply one preset to a context, while Rust's coherence restrictions prevented a context from inheriting independent user and post presets that way. I also experimented with macro-based composition of multiple presets, but expansion order and the handling of imports and aliases made that approach tedious to use. -However, the biggest limitation of CGP presets is that it supports only a single-inheritance-like hierarchy of components. This means that since `ProductionApp` has "inherited" `PostgresUserComponents`, it cannot also inherit another preset like `PostgresPostComponents` due to the coherence restrictions in Rust. +Namespaces let an application name a component group and select its implementation bundle without enumerating every key. That is the goal the earlier approaches were trying to meet. Namespaces express it through trait resolution and paths. The [migration section](#replace-presets-with-namespace-configuration) shows how existing preset users can move to them. -We have also experimented on a multiple-inheritance-like feature with CGP presets using macros. However, the lack of eager macro evaluation and hygenic bindings of imports make it tedious to use the feature. +### Give component groups a path {#introducing-cgp-namespaces-and-paths} -### Introducing CGP namespaces and paths - -Fortunately, with CGP v0.8.0, we have managed to solve the long-standing problem and devise a way to group component keys through a new feature called **namespaces**. - -The way CGP namespaces work is as follows. For each CGP component definition, we can define a **namespace prefix** like follows: +A component can register a path prefix in a namespace. Here, `CanCreateUser` registers its component under `@app.core.user` in the built-in `DefaultNamespace`: ```rust #[cgp_component(UserCreator)] -#[namespace(@app.core.user)] +#[prefix(@app.core.user in DefaultNamespace)] pub trait CanCreateUser { fn create_user(&self, username: &str, email: &Email) -> Result; } ``` -In the code above, we add a new `#[prefix]` attribute to the `UserCreator` component, with a prefix `@app.core.user`. This prefix acts as the new group "key" that we will use later in `delegate_components!`. +`#[prefix]` records the route, and CGP appends the component marker to it. A lookup for `UserCreatorComponent` therefore uses the address `@app.core.user.UserCreatorComponent` once a context joins the namespace. -CGP allows the same namespace prefix to be used by multiple traits. For example, we can also apply the `@app.core.user` prefix to `UserGetter`, and similarly to `UserUpdater`: +Several components can share one prefix. The getter below and the updater register under the same user prefix: ```rust #[cgp_component(UserGetter)] -#[prefix(@app.core.user)] +#[prefix(@app.core.user in DefaultNamespace)] pub trait CanGetUser { fn get_user(&self, user_id: &UserId) -> Result; } ``` -Similarly, we can assign the prefix `@app.core.post` to `PostCreator`, and other post-related traits: +The post components register under `@app.core.post`: ```rust #[cgp_component(PostCreator)] -#[prefix(@app.core.post)] +#[prefix(@app.core.post in DefaultNamespace)] pub trait CanCreatePost { fn create_post(&self, title: &str, content: &str) -> Result; } ``` -We would also assign the prefix `@app.core.content_filter` to `UsernameCensor` and `SpamMessageDetector`. +The filter components register under `@app.extra.content_filter`, also in `DefaultNamespace`. These paths describe the groups independently of which providers an application chooses. -After assigning the namespace prefixes, we can now use them to bulk delegate the CGP components in the top-level wiring for `ProductionApp`: +The application joins the namespace and forwards each group to its bundle: ```rust delegate_components! { @@ -639,17 +686,15 @@ delegate_components! { } ``` -Compared to before, our new definition for `ProductionApp` becomes significantly shorter and concise. Since namespace is an opt-in feature, we explicitly enable it using the `namespace` keyword inside the `delegate_components!` block. The `DefaultNamespace` namespace is used here, but as we will see in later sections, it is also possible to define custom namespaces and assign different prefixes to CGP components. - -Following that, a delegate key like `@app.core.user` implicitly forwards all implementation of the user-related CGP traits to the aggregated provider `PostgresUserComponents`. Similarly, the next two entries delegate the corresponding CGP components to the respective aggregated providers. +Namespace routing connects each component lookup to the application's selected provider bundle. The namespace supplies routes, prefixes identify groups, and aggregate providers supply implementations. For example, `create_user` asks for `UserCreatorComponent`, which the namespace redirects to `@app.core.user.UserCreatorComponent`. The `@app.core.user` entry selects `PostgresUserComponents`, and that bundle selects `FilterCensoredUsername` for the component. Rust resolves these steps at compile time, without a runtime lookup table. -#### Hierarchical delegation +Namespaces are opt-in: `namespace DefaultNamespace;` enables the registered routes for this table. A custom namespace can register components under different prefixes and be selected in the same way. -CGP namespaces allows us to group CGP component keys into a hierarchy of prefixes. This in turns allows us to cleanly encapsulate group of CGP components, and break down the wiring configuration into smaller parts. +The top-level table now has three entries. The individual bindings still live in the bundles, but the application no longer repeats their component names merely to select a group. -CGP allows us to not only group components into prefixes, but also group child prefixes using the parent prefixes. In the earlier example, the prefix `@app.core.user` has a parent prefix `@app.core`, which in turns has a parent prefix `@app`. And since the prefix `@app.core.post` also has `@app.core` as its parent prefix, this means that we can group both group of components together using `@app.core`. +### Group paths hierarchically -With this, we can for example define an aggregated provider for all core components for the application, like: +Parent prefixes can group several domains. The path `@app.core.user` has the parent `@app.core`, which itself sits under `@app`. Both user and post components share `@app.core`, so an intermediate bundle can collect them, with another bundle collecting the extras: ```rust delegate_components! { @@ -672,7 +717,9 @@ delegate_components! { } ``` -With these intermediary aggregated providers, our top-level wiring for `ProductionApp` is now reduced to just: +Path-keyed bundles must also join `DefaultNamespace` to resolve the component keys they receive. A bundle receives the bare component key, and its namespace statement redirects that key to the paths inside its own table. Leaf bundles keyed by bare component names do not need a namespace statement. + +The production configuration now selects two groups: ```rust delegate_components! { @@ -685,9 +732,9 @@ delegate_components! { } ``` -A key benefit for this hierarchical separation is that it also becomes much easier to distinguish the difference in behavior of different contexts. For example, if we see a definition of `TestApp` as follows: +A test configuration can share the whole PostgreSQL-backed core and change just the extras. Its `DummyExtraComponents` bundle supplies the deterministic filters: -```rust +```rust {6} delegate_components! { TestApp { namespace DefaultNamespace; @@ -698,11 +745,9 @@ delegate_components! { } ``` -We can easily deduce from the definition that `TestApp` uses the same PostgreSQL-based core components, but replace the non-essential extra components like content filter with dummy implementations to speed up the tests. - -Similarly, if we see another definition of `LocalApp` like: +A local configuration can instead change the database-backed core while retaining the production filters: -```rust +```rust {5} delegate_components! { LocalApp { namespace DefaultNamespace; @@ -713,17 +758,47 @@ delegate_components! { } ``` -We know that all PostgreSQL-specific core logic has been replaced by an SQLite-specific database backend. +The two variants differ from production in one entry each: `TestApp` changes `@app.extra`, while `LocalApp` changes `@app.core`. + +Each context must still supply the fields and other dependencies its selected providers require. A SQLite core would need its corresponding database handle. + +Named groups make the configuration differences easier to compare. Without namespace grouping, a reader would have to compare the individual component entries across all three contexts. Those entries might appear in different orders, making the differences harder to spot. Grouping shows the shared parts and the parts that change directly. + +### Check the completed configuration + +Check each concrete context explicitly to verify its provider dependencies. Wiring records provider choices lazily, so a `delegate_components!` block can compile before any operation forces those dependencies to be checked: + +```rust +check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } +} +``` + +`ProductionApp`, `TestApp`, and local variants can use the same nine-component check. Apply the check above to `TestApp` and any local variant as well. For an earlier stage of the walkthrough, check the components used in that stage, such as `UserManagerComponent` and `PostManagerComponent` before the managers are split. + +Component checks must still name the operations that need to work. Namespaces remove repeated routing entries, but the dependencies of those operations still need verification. Check aggregate providers through the real contexts that use them, rather than treating a bundle as its own application context. -If we were to define the same 3 contexts without namespaces, the difference in developer experience is stark. A new developer would need to scan through the dozens of lines of component wirings between the 3 contexts. Worse yet, the component wirings may be defined in different orders, making it extremely difficult to compare using humen eyes. +The [namespace documentation](/docs/concepts/namespaces) explains the lookup model, and the [`delegate_components!` reference](/docs/reference/macros/delegate_components) covers the path syntax. -### Default implementations +## Sharing default implementations {#default-implementations} -In the earlier examples, we defined aggregated providers like `PostgresUserComponents`, `PostgresPostComponents`, and `PostgresCoreComponents` to group related provider implementations together, and then bulk delegate a prefix like `@app.core` to the aggregated provider. This provides great flexibility in customizing an application stack with different implementation bundles, such as `SqliteCoreComponents` or `PostgresWithLoggingCoreComponents`. +A namespace can also bind provider choices shared by all its contexts. The bundles above suit configurations that swap whole implementation groups, such as `SqliteCoreComponents`, `PostgresCoreComponents`, or a `PostgresWithLoggingCoreComponents` variant that adds logging. -However, such flexibility is not often needed during the early phase of application development. For example, it might be premature to define a `PostgresUserComponents`, if we are very sure that the initial version of the application will only use Postgres to store the user information. In other words, developers tend to prefer *singleton* implementations of a feature with intentional coupling between the interface and the implementation to make it easier to reason about the application. +An early application may not need interchangeable provider bundles. If it only uses PostgreSQL, defining a `PostgresUserComponents` bundle may be more organization than it needs yet. A single chosen implementation, intentionally coupled to its interface within a configuration, can be easier to reason about. -With namespaces, CGP now offers **default implementation** as a way to tightly couple a particular provider with the component *within a namespace*. To demonstrate how it works, let's first define a new custom namespace for our application: +Default implementations record fixed provider choices within a namespace. If several contexts should always use the same user and post providers, a custom namespace can record those choices once, leaving explicit wiring for the choices that vary. + +Define a namespace inheriting the component routes from `DefaultNamespace`: ```rust cgp_namespace! { @@ -731,37 +806,41 @@ cgp_namespace! { } ``` -In the code above, we use `cgp_namespace!` to define a new namespace called `DefaultAppComponents` that **inherits** from `DefaultNamespace` as its parent namespace. This means that all prefixes and default implementations defined in `DefaultNamespace` would also automatically apply to `DefaultAppComponents`. +`DefaultAppComponents` inherits the prefixes and any default bindings supplied by `DefaultNamespace`. Its own bindings apply to contexts that select this configuration namespace, without changing what other namespaces select. -With the new `DefaultAppComponents` namespace defined, we can now designate our provider implementations as default implementations in `DefaultAppComponents`, such as: +Add `#[default_impl]` to the earlier `GetUserWithPostgres` implementation to bind it at the component's full path: ```rust #[cgp_impl(new GetUserWithPostgres)] #[default_impl(@app.core.user.UserGetterComponent in DefaultAppComponents)] impl UserGetter { fn get_user(&self, #[implicit] database: &PostgresDb, user_id: &UserId) -> Result { - // ... + // ... query the database } } ``` -Compared to earlier, we added a new `#[default_impl]` attribute when defining the `GetUserWithPostgres` provider. Inside the attribute, we designate `@app.core.user.UserGetterComponent` as the component key which `GetUserWithPostgres` would be set as the default provider. Following that, `in DefaultAppComponents` indicates that this default provider is only applicable when the namespace `DefaultAppComponents` is used in `delegate_components!`. - - -The above use of `#[default_impl]` essentially expands into the following use of `cgp_namespace!`: +The attribute registers `GetUserWithPostgres` at that path in `DefaultAppComponents`. It is equivalent to writing the binding separately in a namespace body: ```rust cgp_namespace! { DefaultAppComponents { - @app.core.user.UserGetterComponent: - GetUserWithPostgres, + @app.core.user.UserGetterComponent: GetUserWithPostgres, } } ``` -The use of `cgp_namespace!` is similar to `delegate_components!`, with each key-value mapping being bound to a namespace instead of a context or provider. Notice that we use the prefixed key `@app.core.user.UserGetterComponent` instead of the bare `UserGetterComponent`, as `DefaultAppComponents` extends from `DefaultNamespace`, which redirects the use of `UserGetterComponent` to the prefixed key. +Namespace-body entries bind providers for every context that selects the namespace. The body resembles a `delegate_components!` table, but its entries belong to the namespace instead of one context or aggregate provider. The full `@app.core.user.UserGetterComponent` path is required here because the inherited route already maps the bare component marker to that address. + +Use either the attribute or the namespace-body entry for this binding, rather than writing both. + +A prefixed default registration must live in the crate that owns its namespace, here `DefaultAppComponents`. The key expands to CGP's `PathCons` type, so owning a component marker nested inside it does not satisfy Rust's orphan rules. An unprefixed local component marker has different ownership rules, covered by the [`#[default_impl]` reference](/docs/reference/attributes/default_impl). + +A namespace's fixed bindings cannot be overridden by joining contexts or inheriting namespaces. Adding a more specific entry does not replace a binding, and a context cannot disable just one fixed default while keeping the rest of that same namespace. Keep choices that should vary on paths the namespace leaves unbound. + +### Bind composite providers in the namespace body -When we want to assign a composite provider as the default implementation, we can do so by using `cgp_namespace!` directly. For example: +A wrapper such as `FilterCensoredUsername` is a complete provider choice, so record it directly in the namespace body: ```rust cgp_namespace! { @@ -772,9 +851,13 @@ cgp_namespace! { } ``` -would mean that the default user creator component would always be the combined provider `FilterCensoredUsername`. +The application only needs to choose its filters once the namespace binds the remaining user and post providers. In this example, `ContentFilterComponents` names the AI-backed filter bundle defined earlier: -With default implementations, we can now omit the delegation of the relevant components entirely, if we use a namespace that contains the default implementations. For example: +```rust +type ContentFilterComponents = AiContentFilterComponents; +``` + +The application selects that bundle explicitly: ```rust delegate_components! { @@ -786,24 +869,158 @@ delegate_components! { } ``` -Assuming that we also assign default implementations for every user and post providers in `DefaultAppComponents`, now there is almost no explicit wiring needed in `ProductionApp`, which uses `DefaultAppComponents` as the namespace. +Leaving the filter path unbound lets each context choose its filters. A test context can select `DummyContentFilterComponents` at that same path. Both contexts still need component checks, including the dependencies of providers supplied by defaults. + +### Choose how much wiring to share + +Separate structural routes from fixed provider choices so configurations can reuse the same routes. Put the routes in a base namespace and fixed choices in a configuration namespace that inherits it. Another configuration can then reuse the routes without inheriting provider choices it needs to replace. + +Choose a namespace that leaves a destination open when you need to replace its fixed default. For example, join the base `DefaultNamespace` and supply the required bindings there. + +`#[default_impl]` is convenient for gradual adoption in a single crate, where the namespace and provider definitions can live together. As providers move into separate crates, namespace-body entries let the namespace's own crate assemble them without requiring registration attributes beside each implementation. The ownership rule still applies to the generated binding. + +I see default implementations as a way to move gradually from a single-crate application to a more modular one. Ordinary traits may already be sufficient when a single crate has one implementation of each operation. An application that later needs more modularity can first refactor its monolithic code into CGP components with defaults, without significantly disrupting its organization. It can then introduce explicit bundles and split crates as those needs arise, rather than requiring the full wiring structure at the start. + +Choose the amount of wiring that makes the application's decisions clear. Defaults suit choices every joining context should share, while explicit bundles suit interchangeable implementation groups. Smaller applications can stay with direct wiring until grouping makes their configuration easier to read. + +## Other improvements + +The release also adds smaller features that build on the same machinery. Their references cover the full syntax: + +- **Per-type dispatch with `open`:** choose providers for a generic component directly in a context's table, without declaring a namespace or a nested `UseDelegate` table. See [`delegate_components!`](/docs/reference/macros/delegate_components#choosing-a-provider-per-type-the-open-statement). +- **Importing tables with `for`:** bring entries from another namespace table onto a path, so independently defined groups of defaults can be assembled in one context. See [namespace statements](/docs/reference/macros/delegate_components#the-namespace-statements). +- **Implementation-only generics:** `#[impl_generics]` lets a `#[cgp_fn]` implementation infer a generic type from an implicit field without exposing that type as a trait parameter. See [`#[impl_generics]`](/docs/reference/attributes/impl_generics). +- **Readable data shapes:** [`Struct!`](/docs/reference/macros/struct) and [`Enum!`](/docs/reference/macros/enum) express the field lists of structs and enums using declaration-like syntax. cargo-cgp also uses these forms when displaying shapes. +- **Variants without fields:** the extensible-variant derives accept variants such as `Closed`, `Closed()`, and `Closed {}`, representing their payload as `Nil`. A `no_std` crate using the mutable extractor must have `Box` in scope. + +The handler macros also generate self-contained expansions without relying on a prelude import at the call site. The release fixes lifetime handling and supertrait support in `#[cgp_auto_dispatch]`, and improves rejection messages for unsupported function signatures in `#[cgp_computer]` and `#[cgp_producer]`. + +## Breaking changes and migration + +Existing applications need source changes when moving from v0.7.0. The largest change is the removal of presets, which namespaces replace. + +### Replace presets with namespace configuration + +The preset system described [earlier](#why-the-earlier-grouping-approaches-were-insufficient) is removed in v0.8.0. Its shared provider choices can become namespace bindings, while groups that need to remain interchangeable can become aggregate providers selected through paths. + +The following v0.7.0 example defines a preset and inherits it into a context. **This is old syntax and does not compile with v0.8.0:** + +```rust +cgp_preset! { + PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: GetUserWithPostgres, + UserUpdaterComponent: UpdateUserWithPostgres, + } +} + +#[cgp_inherit(PostgresUserComponents)] +pub struct ProductionApp { + pub database: PostgresDb, +} + +delegate_components! { + ProductionApp { + // The inherited preset supplies the user-component entries. + // Other component bindings go here. + } +} +``` + +A configuration namespace can preserve the preset's fixed user-provider choices. Register the user components under `@app.core.user` in `DefaultNamespace`, using the `#[prefix(... in DefaultNamespace)]` attributes shown earlier. Then replace the preset with this namespace: + +```rust +cgp_namespace! { + new PostgresAppNamespace: DefaultNamespace { + @app.core.user.UserCreatorComponent: + FilterCensoredUsername, + @app.core.user.UserGetterComponent: GetUserWithPostgres, + @app.core.user.UserUpdaterComponent: UpdateUserWithPostgres, + } +} +``` + +The migrated context must also supply the censor required by its creation wrapper. Register `UsernameCensor` under `@app.extra.content_filter` in `DefaultNamespace`. With the user components and filter registered, replace the inheritance attribute with explicit delegation on the context: + +```rust +#[derive(HasField)] +pub struct ProductionApp { + pub database: PostgresDb, +} + +delegate_components! { + ProductionApp { + namespace PostgresAppNamespace; + + @app.extra.content_filter.UsernameCensorComponent: AiUserCensor, + } +} + +check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + UsernameCensorComponent, + } +} +``` + +The example above deliberately checks only the migrated user group and its filter. Add the post operations and any other dependencies your application uses. + +An aggregate provider keeps the user-provider group interchangeable. If configurations need that variation, retain `PostgresUserComponents` using `delegate_components! { new PostgresUserComponents { ... } }` and select it with `@app.core.user: PostgresUserComponents`, as in the main walkthrough. Choose between this configurable bundle arrangement and the fixed namespace bindings above according to what should vary. -Notice that in the example, we still exclude the content filter components from the namespace. This may be useful if we still want to customize the implementation, such as using mocked implementations inside a `TestApp`. +The removed preset constructs and their replacements are: -By using default implementations, CGP allows developers to focus on wirings that truly require variations between application contexts, and allow omitting of wirings that do not change by setting them as default implementations in a given namespace. +| Removed construct | What to use | +| --- | --- | +| `cgp_preset!` | A configuration namespace for shared fixed choices, or an aggregate provider for a selectable group. | +| `#[cgp_inherit]` | A `namespace ...;` statement and explicit path entries inside `delegate_components!`. | +| `#[wrap_provider]` | Explicit aggregate providers and delegation entries. | +| `#[cgp::re_export_imports]` | Ordinary Rust imports for the types used in namespace or delegation tables. | +| `IsPreset` | Remove bounds on the preset marker. Generic code that queries a namespace uses that namespace's generated lookup trait. | -At the same time, the use of namespaces means that developers still have the option to opt out of a given default implementation, by choosing to use a different namespace. +### Update attribute syntax and direct dependencies -#### Caveats with default implementations +The associated-type separator in `#[use_type]` changes from `::` to `.`: -Although default implementations provide the convenience of omitting explicit wirings, the coherence restrictions in Rust makes it tricky to use default implementations as an application grows large. +```rust +// v0.7.0 +#[use_type(HasErrorType::Error)] + +// v0.8.0 +#[use_type(HasErrorType.Error)] +``` -A key caveat is that in most cases, a default implementation assignment would only succeed if the crate owns the namespace and/or the component trait. Otherwise, developers can run into coherence restriction errors, if the constructs are scattered across multiple crates. +Equality imports use the new separator too. Write `#[use_type(HasErrorType.{Error = AppError})]`. The [`#[use_type]` reference](/docs/reference/attributes/use_type) covers both ordinary and equality imports. -Furthermore, once a default implementation is defined, it is not possible to opt out of that particular default from the rest of the bindings in a namespace. This means that opting out even one default implementation requires you to completely opt out of that specific namespace. +The extra-feature macro crates are renamed from `cgp-extra-macro` and `cgp-extra-macro-lib` to `cgp-macro-extra` and `cgp-macro-extra-lib`. Update direct dependencies on those crates. Imports through `cgp::prelude` keep their names. -This means that default implementations is mostly a beginner-oriented feature, where the entire application can fit in one crate, and that the user don't care that much about reusability at the moment. +Self-contained handler-macro expansions may leave imports unused. Remove imports the compiler reports when they existed only for the old expansion. -In such single-crate use cases, CGP do not offer much value. However, with default implementations serving as a bridge, it enables the possibility for one to transition an project from having a single-crate monolithic application into having multiple crates with modular applications. +`#[cgp_auto_dispatch]` rejects attribute arguments and typed receivers such as `self: Box`. It previously ignored the arguments or miscompiled those receivers. + +The new `Struct!` and `Enum!` prelude exports can make a macro name ambiguous. Qualify the call if another glob import provides the same name. + +### Check error-backend behavior + +`cgp-error-eyre` enables eyre's automatic default-handler installation and tracks the caller of `raise_error` and `wrap_error`. + +`cgp-error-std` changes how wrapped errors are displayed. Ordinary `Display` prints only the outer detail, while alternate `Display` and `Debug` include the chain. This avoids duplicated sources when a reporter walks `source()` itself. Update output assertions that depend on the old formatting. + +The minimum anyhow and eyre dependencies rise to 1.0.104 and 0.6.14 respectively. The backend READMEs in the [CGP repository](https://github.com/contextgeneric/cgp/tree/main/crates/standalone/error) describe their use. + +## Try one part of your application + +With v0.8.0, I want to make CGP easier to learn and maintain. cargo-cgp helps explain missing dependencies, and the expanded documentation gives readers somewhere to follow those explanations. As an application grows, namespaces let its wiring show which groups of implementations it selects. + +CGP still has a learning curve, and the tooling and documentation need further work. + +Start with a small example or one part of your existing application. If you already use CGP, try grouping one part of your wiring while keeping its component checks in place. If you are new to CGP, the [Quickstart](/docs/quickstart) provides a smaller starting point. + +I would appreciate hearing where you still struggle to trace an implementation, understand a diagnostic, or follow an explanation. Those examples will help me decide what to improve next. You can share them in [GitHub Discussions](https://github.com/orgs/contextgeneric/discussions). Thank you for reading and trying CGP. + +--- -Default implementations allows such transition to be gradually rolled out, by first refactoring all monolithic code into CGP components with default implementations, without significantly disrupting the original code organization. +*I wrote the draft of this post, and an AI agent revised its prose and checked its code and claims against the CGP knowledge base. See [How AI is used in this project](/docs/ai/disclaimer#blog-posts-and-tutorials).* diff --git a/example-code/README.md b/example-code/README.md index 9b150d5e..e2a2350a 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -26,6 +26,7 @@ pulls in a module tree that mirrors that section's pages: - `tests/comparisons_tests.rs` → `tests/comparisons/`, mirroring `docs/comparisons/` - `tests/tutorials_tests.rs` → `tests/tutorials/`, mirroring `docs/tutorials/` - `tests/compile_fail_tests.rs` → `tests/compile_fail/`, the snippets the pages **reject** (see below) +- `tests/blog_tests.rs` → `tests/blog/`, the current release draft's worked examples **A standalone page gets a test binary of its own instead**, since there is no section tree for it to sit in: `tests/quickstart.rs` answers `docs/quickstart.md`. Use this form only for a page that has no @@ -41,6 +42,7 @@ One file per page, at the matching path with the file name in `snake_case`: | `docs/comparisons/` | complete — one file per page under `tests/comparisons/`; only the CGP side of each page is checked here, since the other language's snippets are compiled against the toolchain the page names | | `docs/tutorials/` | partial — `area-calculation/checking.md`, whose three quoted diagnostics are the reason it is mirrored; the rest is filled in lazily | | `docs/quickstart.md` | complete — `tests/quickstart.rs`, a standalone binary rather than a section tree | +| `blog/2026-05-10-v0.8.0-release.md` | complete — `tests/blog/v0_8_0_release.rs` checks each wiring stage, the default-binding alternatives, and the migrated configuration; the deliberate missing-field error is a compile-fail fixture | | front page, remaining orientation pages | none yet | Within a covered section the mapping is mechanical: `docs/concepts/coherence.md` is answered by diff --git a/example-code/tests/blog/v0_8_0_release.rs b/example-code/tests/blog/v0_8_0_release.rs new file mode 100644 index 00000000..9527836c --- /dev/null +++ b/example-code/tests/blog/v0_8_0_release.rs @@ -0,0 +1,1272 @@ +//! Compiled counterparts of `blog/2026-05-10-v0.8.0-release.md`. +//! Modules follow the walkthrough. Old-version migration snippets are historical input; +//! the missing-height program is a compile-fail fixture under `tests/compile_fail/blog/`. +#![allow(dead_code, unused_variables)] + +mod diagnosing_wiring_with_cargo_cgp { + use cgp::prelude::*; + + #[cgp_component(AreaCalculator)] + pub trait CanCalculateArea { + fn area(&self) -> f64; + } + + #[cgp_impl(new RectangleArea)] + impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } + } + + #[derive(HasField)] + pub struct Rectangle { + pub width: f64, + pub height: f64, + } + + delegate_and_check_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } + } + #[test] + fn repaired_rectangle_has_an_area() { + assert_eq!( + Rectangle { + width: 3.0, + height: 4.0 + } + .area(), + 12.0 + ); + } +} + +mod domain { + pub struct Email(pub String); + + pub struct User; + pub struct UserData; + pub struct UserId; + + pub struct Post; + pub struct PostId; + + pub enum Error { + InvalidUsername, + InvalidMessage, + } + + pub struct PostgresDb; + + #[derive(PartialOrd, PartialEq)] + pub struct Probability(pub f64); + + impl Probability { + pub const fn new(value: f64) -> Self { + Self(value) + } + } +} + +mod start_with_database_only_managers { + use super::domain::*; + use cgp::prelude::*; + + #[cgp_component(UserManager)] + pub trait CanManageUser { + fn create_user(&self, username: &str, email: &Email) -> Result; + + fn get_user(&self, user_id: &UserId) -> Result; + + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; + } + + #[cgp_component(PostManager)] + pub trait CanManagePost { + fn create_post(&self, title: &str, content: &str) -> Result; + + fn get_post(&self, post_id: &PostId) -> Result; + + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; + + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; + } + + #[cgp_impl(new PostgresUserManager)] + impl UserManager { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + todo!() // The page elides the database query. + } + + fn get_user( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + ) -> Result { + todo!() // The page elides the database query. + } + + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() // The page elides the database query. + } + } + + #[cgp_impl(new PostgresPostManager)] + impl PostManager { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + todo!() // The page elides the database query. + } + + fn get_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result { + todo!() // The page elides the database query. + } + + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() // The page elides the database query. + } + + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() // The page elides the database query. + } + } + + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + + delegate_and_check_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + } + } +} + +mod start_with_a_manager_and_add_dependencies { + use cgp::prelude::*; + + use super::domain::*; + + #[cgp_component(UserManager)] + pub trait CanManageUser { + fn create_user(&self, username: &str, email: &Email) -> Result; + + fn get_user(&self, user_id: &UserId) -> Result; + + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; + } + + #[cgp_component(PostManager)] + pub trait CanManagePost { + fn create_post(&self, title: &str, content: &str) -> Result; + + fn get_post(&self, post_id: &PostId) -> Result; + + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; + + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; + } + + #[cgp_component(UsernameCensor)] + pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; + } + + #[cgp_component(SpamMessageDetector)] + pub trait CanDetectSpamMessage { + fn message_is_spam(&self, message: &str) -> Probability; + } + + #[cgp_impl(new PostgresUserManager)] + #[uses(CanCensorUsername)] + impl UserManager { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + todo!() // The page elides the database/filter body. + } + + fn get_user( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + ) -> Result { + todo!() // The page elides the database/filter body. + } + + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new PostgresPostManager)] + #[uses(CanDetectSpamMessage)] + impl PostManager { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + if self.message_is_spam(content) > Probability::new(0.8) { + return Err(Error::InvalidMessage); + } + + todo!() // The page elides the database/filter body. + } + + fn get_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result { + todo!() // The page elides the database/filter body. + } + + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new DummyUserCensor)] + impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new DummySpamMessageDetector)] + impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new AiUserCensor)] + impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() // The page omits the filter implementation. + } + } + #[cgp_impl(new AiSpamMessageDetector)] + impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() // The page omits the filter implementation. + } + } + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + + delegate_components! { + ProductionApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: AiUserCensor, + SpamMessageDetectorComponent: AiSpamMessageDetector, + } + } + + #[derive(HasField)] + pub struct TestApp { + pub database: PostgresDb, + } + + delegate_components! { + TestApp { + UserManagerComponent: PostgresUserManager, + PostManagerComponent: PostgresPostManager, + UsernameCensorComponent: DummyUserCensor, + SpamMessageDetectorComponent: DummySpamMessageDetector, + } + } + check_components! { ProductionApp { UserManagerComponent, PostManagerComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } + check_components! { TestApp { UserManagerComponent, PostManagerComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } +} + +mod separate_filtering_from_database_access { + use cgp::prelude::*; + + use super::domain::*; + + #[cgp_component(UserCreator)] + pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; + } + + #[cgp_component(UserGetter)] + pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; + } + + #[cgp_component(UserUpdater)] + pub trait CanUpdateUser { + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; + } + + #[cgp_component(PostCreator)] + pub trait CanCreatePost { + fn create_post(&self, title: &str, content: &str) -> Result; + } + + #[cgp_component(PostGetter)] + pub trait CanGetPost { + fn get_post(&self, post_id: &PostId) -> Result; + } + + #[cgp_component(PostUpdater)] + pub trait CanUpdatePost { + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; + } + + #[cgp_component(PostDeleter)] + pub trait CanDeletePost { + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; + } + + #[cgp_component(UsernameCensor)] + pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; + } + + #[cgp_component(SpamMessageDetector)] + pub trait CanDetectSpamMessage { + fn message_is_spam(&self, message: &str) -> Probability; + } + + #[cgp_impl(new FilterCensoredUsername)] + #[uses(CanCensorUsername)] + #[use_provider(InnerCreator: UserCreator)] + impl UserCreator { + fn create_user(&self, username: &str, email: &Email) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + InnerCreator::create_user(self, username, email) + } + } + + #[cgp_impl(new CreateUserWithPostgres)] + impl UserCreator { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new GetUserWithPostgres)] + impl UserGetter { + fn get_user( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + ) -> Result { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new UpdateUserWithPostgres)] + impl UserUpdater { + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new FilterSpamMessage)] + #[uses(CanDetectSpamMessage)] + #[use_provider(InnerCreator: PostCreator)] + impl PostCreator { + fn create_post(&self, title: &str, content: &str) -> Result { + if self.message_is_spam(content) > Probability::new(0.8) { + return Err(Error::InvalidMessage); + } + + InnerCreator::create_post(self, title, content) + } + } + + #[cgp_impl(new CreatePostWithPostgres)] + impl PostCreator { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new GetPostWithPostgres)] + impl PostGetter { + fn get_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new UpdatePostWithPostgres)] + impl PostUpdater { + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new DeletePostWithPostgres)] + impl PostDeleter { + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new DummyUserCensor)] + impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new AiUserCensor)] + impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new DummySpamMessageDetector)] + impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new AiSpamMessageDetector)] + impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } +} + +mod split_independently_reusable_operations { + use super::domain::*; + use super::separate_filtering_from_database_access::*; + use cgp::prelude::*; + #[cgp_impl(new CreateUserWithPostgres)] + #[uses(CanCensorUsername)] + impl UserCreator { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + todo!() // The page elides the database query. + } + } + + #[cgp_impl(new GetUserWithPostgres)] + impl UserGetter { + fn get_user( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + ) -> Result { + todo!() // The page elides the database query. + } + } + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + delegate_components! { + ProductionApp { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + PostCreatorComponent: + FilterSpamMessage, + PostGetterComponent: + GetPostWithPostgres, + PostUpdaterComponent: + UpdatePostWithPostgres, + PostDeleterComponent: + DeletePostWithPostgres, + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } + } + check_components! { ProductionApp { UserCreatorComponent, UserGetterComponent, UserUpdaterComponent, PostCreatorComponent, PostGetterComponent, PostUpdaterComponent, PostDeleterComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } +} + +mod count_the_cost_of_the_separation { + use super::domain::*; + use super::separate_filtering_from_database_access::*; + use cgp::prelude::*; + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + delegate_components! { + ProductionApp { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + PostCreatorComponent: + FilterSpamMessage, + PostGetterComponent: + GetPostWithPostgres, + PostUpdaterComponent: + UpdatePostWithPostgres, + PostDeleterComponent: + DeletePostWithPostgres, + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } + } + check_components! { ProductionApp { UserCreatorComponent, UserGetterComponent, UserUpdaterComponent, PostCreatorComponent, PostGetterComponent, PostUpdaterComponent, PostDeleterComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } +} + +mod group_providers_into_bundles { + use super::domain::*; + use super::separate_filtering_from_database_access::*; + use cgp::prelude::*; + delegate_components! { + new PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + } + } + + delegate_components! { + new PostgresPostComponents { + PostCreatorComponent: + FilterSpamMessage, + PostGetterComponent: + GetPostWithPostgres, + PostUpdaterComponent: + UpdatePostWithPostgres, + PostDeleterComponent: + DeletePostWithPostgres, + } + } + + delegate_components! { + new AiContentFilterComponents { + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } + } + + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + delegate_components! { + ProductionApp { + [ + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + ]: + PostgresUserComponents, + [ + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + ]: + PostgresPostComponents, + [ + UsernameCensorComponent, + SpamMessageDetectorComponent, + ]: + AiContentFilterComponents, + } + } + check_components! { ProductionApp { UserCreatorComponent, UserGetterComponent, UserUpdaterComponent, PostCreatorComponent, PostGetterComponent, PostUpdaterComponent, PostDeleterComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } +} + +mod give_component_groups_a_path { + use cgp::prelude::*; + + use super::domain::*; + + #[cgp_component(UserCreator)] + #[prefix(@app.core.user in DefaultNamespace)] + pub trait CanCreateUser { + fn create_user(&self, username: &str, email: &Email) -> Result; + } + + #[cgp_component(UserGetter)] + #[prefix(@app.core.user in DefaultNamespace)] + pub trait CanGetUser { + fn get_user(&self, user_id: &UserId) -> Result; + } + + #[cgp_component(UserUpdater)] + #[prefix(@app.core.user in DefaultNamespace)] + pub trait CanUpdateUser { + fn update_user_data(&self, user_id: &UserId, user_data: &UserData) -> Result<(), Error>; + } + + #[cgp_component(PostCreator)] + #[prefix(@app.core.post in DefaultNamespace)] + pub trait CanCreatePost { + fn create_post(&self, title: &str, content: &str) -> Result; + } + + #[cgp_component(PostGetter)] + #[prefix(@app.core.post in DefaultNamespace)] + pub trait CanGetPost { + fn get_post(&self, post_id: &PostId) -> Result; + } + + #[cgp_component(PostUpdater)] + #[prefix(@app.core.post in DefaultNamespace)] + pub trait CanUpdatePost { + fn update_post(&self, post_id: &PostId, content: &str) -> Result<(), Error>; + } + + #[cgp_component(PostDeleter)] + #[prefix(@app.core.post in DefaultNamespace)] + pub trait CanDeletePost { + fn delete_post(&self, post_id: &PostId) -> Result<(), Error>; + } + + #[cgp_component(UsernameCensor)] + #[prefix(@app.extra.content_filter in DefaultNamespace)] + pub trait CanCensorUsername { + fn username_is_censored(&self, username: &str) -> Probability; + } + + #[cgp_component(SpamMessageDetector)] + #[prefix(@app.extra.content_filter in DefaultNamespace)] + pub trait CanDetectSpamMessage { + fn message_is_spam(&self, message: &str) -> Probability; + } + + #[cgp_impl(new FilterCensoredUsername)] + #[uses(CanCensorUsername)] + #[use_provider(InnerCreator: UserCreator)] + impl UserCreator { + fn create_user(&self, username: &str, email: &Email) -> Result { + if self.username_is_censored(username) > Probability::new(0.8) { + return Err(Error::InvalidUsername); + } + + InnerCreator::create_user(self, username, email) + } + } + + #[cgp_impl(new CreateUserWithPostgres)] + impl UserCreator { + fn create_user( + &self, + #[implicit] database: &PostgresDb, + username: &str, + email: &Email, + ) -> Result { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new GetUserWithPostgres)] + impl UserGetter { + fn get_user( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + ) -> Result { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new UpdateUserWithPostgres)] + impl UserUpdater { + fn update_user_data( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new FilterSpamMessage)] + #[uses(CanDetectSpamMessage)] + #[use_provider(InnerCreator: PostCreator)] + impl PostCreator { + fn create_post(&self, title: &str, content: &str) -> Result { + if self.message_is_spam(content) > Probability::new(0.8) { + return Err(Error::InvalidMessage); + } + + InnerCreator::create_post(self, title, content) + } + } + + #[cgp_impl(new CreatePostWithPostgres)] + impl PostCreator { + fn create_post( + &self, + #[implicit] database: &PostgresDb, + title: &str, + content: &str, + ) -> Result { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new GetPostWithPostgres)] + impl PostGetter { + fn get_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new UpdatePostWithPostgres)] + impl PostUpdater { + fn update_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new DeletePostWithPostgres)] + impl PostDeleter { + fn delete_post( + &self, + #[implicit] database: &PostgresDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new DummyUserCensor)] + impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new AiUserCensor)] + impl UsernameCensor { + fn username_is_censored(&self, username: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new DummySpamMessageDetector)] + impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + #[cgp_impl(new AiSpamMessageDetector)] + impl SpamMessageDetector { + fn message_is_spam(&self, message: &str) -> Probability { + todo!() // The page elides the database/filter body. + } + } + + delegate_components! { + new PostgresUserComponents { + UserCreatorComponent: + FilterCensoredUsername, + UserGetterComponent: + GetUserWithPostgres, + UserUpdaterComponent: + UpdateUserWithPostgres, + } + } + + delegate_components! { + new PostgresPostComponents { + PostCreatorComponent: + FilterSpamMessage, + PostGetterComponent: + GetPostWithPostgres, + PostUpdaterComponent: + UpdatePostWithPostgres, + PostDeleterComponent: + DeletePostWithPostgres, + } + } + + delegate_components! { + new AiContentFilterComponents { + UsernameCensorComponent: + AiUserCensor, + SpamMessageDetectorComponent: + AiSpamMessageDetector, + } + } + + delegate_components! { + new DummyContentFilterComponents { + UsernameCensorComponent: + DummyUserCensor, + SpamMessageDetectorComponent: + DummySpamMessageDetector, + } + } +} + +mod forward_leaf_paths { + use super::domain::*; + use super::give_component_groups_a_path::*; + use cgp::prelude::*; + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + delegate_components! { + ProductionApp { + namespace DefaultNamespace; + + @app.core.user: PostgresUserComponents, + @app.core.post: PostgresPostComponents, + @app.extra.content_filter: AiContentFilterComponents, + } + } + check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } + } +} + +mod group_paths_hierarchically_and_check_the_configuration { + use super::domain::*; + use super::give_component_groups_a_path::*; + use cgp::prelude::*; + delegate_components! { + new PostgresCoreComponents { + namespace DefaultNamespace; + + @app.core.user: PostgresUserComponents, + @app.core.post: PostgresPostComponents, + // other core components + } + } + + delegate_components! { + new ProductionExtraComponents { + namespace DefaultNamespace; + + @app.extra.content_filter: AiContentFilterComponents, + // other extra components + } + } + delegate_components! { + new DummyExtraComponents { + namespace DefaultNamespace; + @app.extra.content_filter: DummyContentFilterComponents, + } + } + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + #[derive(HasField)] + pub struct TestApp { + pub database: PostgresDb, + } + delegate_components! { + ProductionApp { + namespace DefaultNamespace; + + @app.core: PostgresCoreComponents, + @app.extra: ProductionExtraComponents, + } + } + delegate_components! { + TestApp { + namespace DefaultNamespace; + + @app.core: PostgresCoreComponents, + @app.extra: DummyExtraComponents, + } + } + pub struct SqliteDb; + #[derive(HasField)] + pub struct LocalApp { + pub database: SqliteDb, + } + #[cgp_impl(new CreateUserWithSqlite)] + impl UserCreator { + fn create_user( + &self, + #[implicit] database: &SqliteDb, + username: &str, + email: &Email, + ) -> Result { + todo!() // The page omits the hypothetical SQLite implementation. + } + } + #[cgp_impl(new GetUserWithSqlite)] + impl UserGetter { + fn get_user( + &self, + #[implicit] database: &SqliteDb, + user_id: &UserId, + ) -> Result { + todo!() // The page omits the hypothetical SQLite implementation. + } + } + #[cgp_impl(new UpdateUserWithSqlite)] + impl UserUpdater { + fn update_user_data( + &self, + #[implicit] database: &SqliteDb, + user_id: &UserId, + user_data: &UserData, + ) -> Result<(), Error> { + todo!() // The page omits the hypothetical SQLite implementation. + } + } + #[cgp_impl(new CreatePostWithSqlite)] + impl PostCreator { + fn create_post( + &self, + #[implicit] database: &SqliteDb, + title: &str, + content: &str, + ) -> Result { + todo!() // The page omits the hypothetical SQLite implementation. + } + } + #[cgp_impl(new GetPostWithSqlite)] + impl PostGetter { + fn get_post( + &self, + #[implicit] database: &SqliteDb, + post_id: &PostId, + ) -> Result { + todo!() // The page omits the hypothetical SQLite implementation. + } + } + #[cgp_impl(new UpdatePostWithSqlite)] + impl PostUpdater { + fn update_post( + &self, + #[implicit] database: &SqliteDb, + post_id: &PostId, + content: &str, + ) -> Result<(), Error> { + todo!() // The page omits the hypothetical SQLite implementation. + } + } + #[cgp_impl(new DeletePostWithSqlite)] + impl PostDeleter { + fn delete_post( + &self, + #[implicit] database: &SqliteDb, + post_id: &PostId, + ) -> Result<(), Error> { + todo!() // The page omits the hypothetical SQLite implementation. + } + } + delegate_components! { + new SqliteCoreComponents { + UserCreatorComponent: FilterCensoredUsername, + UserGetterComponent: GetUserWithSqlite, + UserUpdaterComponent: UpdateUserWithSqlite, + PostCreatorComponent: FilterSpamMessage, + PostGetterComponent: GetPostWithSqlite, + PostUpdaterComponent: UpdatePostWithSqlite, + PostDeleterComponent: DeletePostWithSqlite, + } + } + delegate_components! { + LocalApp { + namespace DefaultNamespace; + + @app.core: SqliteCoreComponents, + @app.extra: ProductionExtraComponents, + } + } + check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } + } + check_components! { TestApp { UserCreatorComponent, UserGetterComponent, UserUpdaterComponent, PostCreatorComponent, PostGetterComponent, PostUpdaterComponent, PostDeleterComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } + check_components! { LocalApp { UserCreatorComponent, UserGetterComponent, UserUpdaterComponent, PostCreatorComponent, PostGetterComponent, PostUpdaterComponent, PostDeleterComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } +} + +mod sharing_default_implementations { + use super::domain::*; + use super::give_component_groups_a_path::*; + use cgp::prelude::*; + cgp_namespace! { + new DefaultAppComponents: DefaultNamespace + } + #[cgp_impl(new GetUserWithPostgres)] + #[default_impl(@app.core.user.UserGetterComponent in DefaultAppComponents)] + impl UserGetter { + fn get_user( + &self, + #[implicit] database: &PostgresDb, + user_id: &UserId, + ) -> Result { + todo!() // The page elides the database query. + } + } + cgp_namespace! { + DefaultAppComponents { + @app.core.user.UserCreatorComponent: + FilterCensoredUsername, + } + } + cgp_namespace! { + DefaultAppComponents { + @app.core.user.UserUpdaterComponent: UpdateUserWithPostgres, + @app.core.post.PostCreatorComponent: FilterSpamMessage, + @app.core.post.PostGetterComponent: GetPostWithPostgres, + @app.core.post.PostUpdaterComponent: UpdatePostWithPostgres, + @app.core.post.PostDeleterComponent: DeletePostWithPostgres, + } + } + type ContentFilterComponents = AiContentFilterComponents; + + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + delegate_components! { + ProductionApp { + namespace DefaultAppComponents; + + @app.extra.content_filter: ContentFilterComponents, + } + } + check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + PostCreatorComponent, + PostGetterComponent, + PostUpdaterComponent, + PostDeleterComponent, + UsernameCensorComponent, + SpamMessageDetectorComponent, + } + } + #[derive(HasField)] + pub struct TestApp { + pub database: PostgresDb, + } + delegate_components! { + TestApp { + namespace DefaultAppComponents; + @app.extra.content_filter: DummyContentFilterComponents, + } + } + check_components! { TestApp { UserCreatorComponent, UserGetterComponent, UserUpdaterComponent, PostCreatorComponent, PostGetterComponent, PostUpdaterComponent, PostDeleterComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } +} + +mod equivalent_namespace_body_binding { + use super::domain::*; + use super::give_component_groups_a_path::*; + use cgp::prelude::*; + cgp_namespace! { + new DefaultAppComponents: DefaultNamespace + } + cgp_namespace! { + DefaultAppComponents { + @app.core.user.UserGetterComponent: GetUserWithPostgres, + } + } + #[derive(HasField)] + pub struct App { + pub database: PostgresDb, + } + delegate_components! { App { namespace DefaultAppComponents; } } + check_components! { App { UserGetterComponent, } } +} + +mod replace_presets_with_namespace_configuration { + use super::domain::*; + use super::give_component_groups_a_path::*; + use cgp::prelude::*; + cgp_namespace! { + new PostgresAppNamespace: DefaultNamespace { + @app.core.user.UserCreatorComponent: + FilterCensoredUsername, + @app.core.user.UserGetterComponent: GetUserWithPostgres, + @app.core.user.UserUpdaterComponent: UpdateUserWithPostgres, + } + } + #[derive(HasField)] + pub struct ProductionApp { + pub database: PostgresDb, + } + + delegate_components! { + ProductionApp { + namespace PostgresAppNamespace; + + @app.extra.content_filter.UsernameCensorComponent: AiUserCensor, + } + } + + check_components! { + ProductionApp { + UserCreatorComponent, + UserGetterComponent, + UserUpdaterComponent, + UsernameCensorComponent, + } + } +} + +mod update_attribute_syntax { + use cgp::prelude::*; + #[cgp_component(Loader)] + #[use_type(HasErrorType.Error)] + pub trait CanLoad { + fn load(&self) -> Result<(), Error>; + } + #[cgp_impl(new Load)] + #[use_type(HasErrorType.{Error = AppError})] + impl Loader { + fn load(&self) -> Result<(), Error> { + Ok(()) + } + } + #[derive(Debug)] + pub struct AppError; + pub struct App; + impl HasErrorType for App { + type Error = AppError; + } + delegate_and_check_components! { App { LoaderComponent: Load } } +} diff --git a/example-code/tests/blog_tests.rs b/example-code/tests/blog_tests.rs new file mode 100644 index 00000000..59fcb2d0 --- /dev/null +++ b/example-code/tests/blog_tests.rs @@ -0,0 +1,8 @@ +//! Compiled counterparts of blog-post examples. +#[path = "blog/v0_8_0_release.rs"] +mod v0_8_0_release; + +#[test] +fn missing_height_is_rejected() { + trybuild::TestCases::new().compile_fail("tests/compile_fail/blog/v0_8_0_missing_height.rs"); +} diff --git a/example-code/tests/compile_fail/blog/v0_8_0_missing_height.rs b/example-code/tests/compile_fail/blog/v0_8_0_missing_height.rs new file mode 100644 index 00000000..1e4f487e --- /dev/null +++ b/example-code/tests/compile_fail/blog/v0_8_0_missing_height.rs @@ -0,0 +1,27 @@ +use cgp::prelude::*; + +#[cgp_component(AreaCalculator)] +pub trait CanCalculateArea { + fn area(&self) -> f64; +} + +#[cgp_impl(new RectangleArea)] +impl AreaCalculator { + fn area(&self, #[implicit] width: f64, #[implicit] height: f64) -> f64 { + width * height + } +} + +#[derive(HasField)] +pub struct Rectangle { + pub width: f64, + // missing `height` field +} + +delegate_and_check_components! { + Rectangle { + AreaCalculatorComponent: RectangleArea, + } +} + +fn main() {} diff --git a/example-code/tests/compile_fail/blog/v0_8_0_missing_height.stderr b/example-code/tests/compile_fail/blog/v0_8_0_missing_height.stderr new file mode 100644 index 00000000..75f5a5ac --- /dev/null +++ b/example-code/tests/compile_fail/blog/v0_8_0_missing_height.stderr @@ -0,0 +1,28 @@ +error[E0277]: the trait bound `Rectangle: CanUseComponent` is not satisfied + --> tests/compile_fail/blog/v0_8_0_missing_height.rs:23:9 + | +23 | AreaCalculatorComponent: RectangleArea, + | ^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound + | +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>` is implemented for it + --> tests/compile_fail/blog/v0_8_0_missing_height.rs:17:9 + | +17 | pub width: f64, + | ^^^^^ +note: required for `RectangleArea` to implement `IsProviderFor` + --> tests/compile_fail/blog/v0_8_0_missing_height.rs:8:1 + | + 8 | #[cgp_impl(new RectangleArea)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Rectangle` to implement `CanUseComponent` +note: required by a bound in `__CanUseRectangle` + --> tests/compile_fail/blog/v0_8_0_missing_height.rs:21:1 + | +21 | / delegate_and_check_components! { +22 | | Rectangle { +23 | | AreaCalculatorComponent: RectangleArea, +24 | | } +25 | | } + | |_^ required by this bound in `__CanUseRectangle` + = note: this error originates in the attribute macro `cgp_impl` which comes from the expansion of the macro `delegate_and_check_components` (in Nightly builds, run with -Z macro-backtrace for more info) From a012dd9b963989cea6cdc787c24929fda99ae2aa Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 25 Oct 2026 23:27:48 +0100 Subject: [PATCH 179/516] Improve v0.8.0 release post narrative --- blog/2026-05-10-v0.8.0-release.md | 266 ++++++++++++++---------------- 1 file changed, 127 insertions(+), 139 deletions(-) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index 67655040..cbb9702d 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -7,13 +7,13 @@ description: 'CGP v0.8.0 introduces cargo-cgp diagnostics, expanded documentatio # CGP v0.8.0 - cargo-cgp, new documentation, and namespaces -**CGP v0.8.0 has been released with improvements to debugging, documentation, and component wiring.** Alongside the release, cargo-cgp helps explain wiring failures. The website now provides reference material, conceptual explanations, and project walkthroughs, while namespaces let growing applications group related wiring and make configuration differences easier to see. +**CGP v0.8.0 is out!** With this release, I want to make CGP easier to learn and maintain. cargo-cgp helps explain wiring errors, and the expanded documentation gives you somewhere to follow up. For growing applications, namespaces let the wiring show which groups of implementations each configuration selects. -{/* truncate */} + Context-Generic Programming (CGP) is a language extension for Rust, with pluggable trait implementations at compile-time. It is an ordinary library on stable Rust: applications select providers through wiring that resolves to static calls. You can adopt it one component at a time. The [Overview](/docs/overview) explains the model. -You can read the tooling and documentation news before the longer namespace walkthrough. The post starts with cargo-cgp and the new documentation, then develops the namespace feature through a social-media application. Allow about 35 minutes for the full post, including the code, or jump to the section you need: +I'll start with cargo-cgp and the new documentation, then work through namespaces using a social-media application. The namespace walkthrough is the longest part, so you can read the tooling and documentation news on their own if you prefer. Allow about 35 minutes for the full post, including the code, or jump to the section you need: - [Diagnosing wiring with cargo-cgp](#diagnosing-wiring-with-cargo-cgp) - [Expanded documentation and optional agent support](#expanded-documentation-and-optional-agent-support) @@ -24,15 +24,15 @@ You can read the tooling and documentation news before the longer namespace walk ## Diagnosing wiring with cargo-cgp -Verbose and confusing compiler errors have been one of the largest obstacles to adopting CGP since the project began. Even a simple mistake, such as forgetting a field or a component binding, can produce a diagnostic naming generated traits and type-level encodings of fields or paths. CGP uses that machinery to support interchangeable implementations, but the compiler reports errors in terms of the Rust it receives after macro expansion. +Since CGP began, verbose and confusing compiler errors have been one of the largest obstacles to adopting it. Forget a field or a component binding, and the compiler can respond with generated traits and type-level encodings of fields or paths. The compiler checks the Rust produced by macro expansion, so its explanation can be far removed from the code where we made the mistake. -Diagnosing a small mistake can require newcomers to understand advanced Rust traits and generics, together with the internal details of CGP. A developer can understand what their code is supposed to do and still struggle to work out why it does not compile. Better syntax alone does not address that barrier. +For a newcomer, that can mean learning advanced Rust traits and generics, along with CGP's internals, just to diagnose a small mistake. You might understand the program you are trying to write and still have little idea why it does not compile. Better syntax alone cannot address that difficulty. -[cargo-cgp v0.1.0](/docs/cargo-cgp) helps developers find missing dependencies without reconstructing the generated code first. I am introducing this separate tool for checking CGP code and inspecting macro expansions alongside CGP v0.8.0. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. +With [cargo-cgp v0.1.0](/docs/cargo-cgp), I want to make that investigation more approachable. This separate tool checks CGP code and explains missing dependencies in terms of the fields, components, and providers you wrote. It can also show you the generated Rust when you want to look deeper. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. ### Find a missing field -A missing `height` field demonstrates how cargo-cgp explains a wiring failure. In this example from the [area-calculation tutorial](/docs/tutorials/area-calculation/static-dispatch), the context is `Rectangle` itself, the value being operated on. Its area provider needs both `width` and `height`, but the struct supplies only `width`. +Let's try it on a small mistake from the [area-calculation tutorial](/docs/tutorials/area-calculation/static-dispatch). We have an area provider that multiplies `width` by `height`, and a `Rectangle` that supplies only `width`. Here, the rectangle itself is the context: it is the value the operation acts on, and its fields supply the provider's inputs. Save this library example as `src/lib.rs` in a Cargo package using `cgp = "0.8.0"`: @@ -64,7 +64,7 @@ delegate_and_check_components! { } ``` -The wiring check fails because `RectangleArea` requires a field that `Rectangle` lacks. `RectangleArea` reads its implicit arguments from the context's fields, and the wiring selects it for `AreaCalculatorComponent`. `delegate_and_check_components!` checks that the provider's dependencies are satisfied. Running `cargo cgp check` identifies the missing field: +The table selects `RectangleArea`, whose `#[implicit]` arguments read the rectangle's fields. Because we used `delegate_and_check_components!`, the compiler checks those dependencies at the wiring entry. Run `cargo cgp check`, and it points to the field we forgot: ```text error[E0277]: [CGP-E001] missing field `height` on `Rectangle` @@ -81,7 +81,7 @@ error[E0277]: [CGP-E001] missing field `height` on `Rectangle` = help: add the field `height: f64` to `Rectangle` ``` -The rewritten diagnostic names the missing field and the change needed to supply it. Its dependency tree explains why the field is required. Plain `cargo check` reports the same mistake through generated traits and a nested `Symbol` type: +We can go straight from “missing field `height`” to the suggested change, `height: f64`. If we need to understand why the field matters, the dependency tree traces it back through `RectangleArea` to the area operation. For comparison, plain `cargo check` describes the same mistake through generated traits and a nested `Symbol` type:
Compare the output from cargo check @@ -119,7 +119,7 @@ note: required by a bound in `__CanUseRectangle`
-Add the field to repair the program: +Following that suggestion, we add the missing field: ```rust #[derive(HasField)] @@ -129,13 +129,13 @@ pub struct Rectangle { } ``` -Adding `height` makes the wiring check pass. The provider can then read both fields and calculate the area. +The wiring check now passes, and the provider can read both fields to calculate the area. Fixing the mistake did not require decoding the type-level spelling of `height`. -cargo-cgp extracts the root cause through the Rust compiler's API. It wraps a nightly compiler, uses that API to inspect the failed dependencies, and formats their chain. This gives it access to information that would otherwise be difficult to recover from the printed diagnostic alone. +To produce this explanation, cargo-cgp wraps a nightly compiler and uses the Rust compiler's API to inspect the failed dependencies. It can follow their chain using information that would be difficult to recover from the printed diagnostic alone. That access is why the tool has its own compiler-linked driver. ### Try the checker -Install cargo-cgp with cargo and rustup, then run it inside your CGP project. The installation commands build the front-end and provision its compiler-linked driver: +With cargo and rustup available, you can install the tool and set up its compiler-linked driver, then check your own project: ```sh cargo install cargo-cgp @@ -144,7 +144,7 @@ cargo cgp setup cargo cgp check ``` -cargo-cgp's nightly is separate from your application's normal toolchain. `cargo cgp setup` installs the tool's pinned nightly and builds the matching driver for its checks. Your application keeps its normal toolchain for ordinary cargo builds, and CGP itself still compiles on stable Rust. cargo-cgp is optional. +`cargo cgp setup` installs the tool's pinned nightly and builds the matching driver. That nightly is used for cargo-cgp's checks; your application keeps its normal toolchain for ordinary cargo builds, and CGP itself still compiles on stable Rust. You can use CGP without installing cargo-cgp. The tool is tested on Linux. macOS and Windows are untested. @@ -152,64 +152,60 @@ Use plain cargo to build, run, and test applications. cargo-cgp supplies `check` ## Expanded documentation and optional agent support -The lack of documentation has been another long-standing obstacle to learning CGP. Until now, the main explanations lived in blog posts, which introduced features as they were released but did not have room to explain every construct and how the pieces fit together. A reader could learn about a feature in an announcement and still lack the reference material needed to use it independently. +A release post can show you an interesting feature and still leave you unsure how to use it in your own program. For too long, CGP left readers in that position. Most explanations lived in blog posts like this one, with each post introducing features as they arrived. There was little room to explain every construct or give readers a complete account of how the pieces fit together. -My available time has limited how much documentation I could write for CGP. It is a side project, and writing a comparable body of documentation entirely by hand would likely take months of full-time work. I do not expect to have that time for the project in the near future. Waiting until I could write it all myself would leave readers facing the same gaps. +CGP is a side project, and finding the time to fill those gaps has been difficult. Writing a comparable body of documentation entirely by hand would likely take me months of full-time work. I do not expect to have that time in the near future, and waiting would leave readers facing the same gaps. -AI agents made the documentation work practical within my available time. Advances in AI and agentic coding let me build out the material, primarily through Claude Code, over many iterations of planning and revision. The website now gives readers several ways into the same subject: +Advances in AI and agentic coding made it practical to take on that work. Agents, primarily Claude Code, wrote much of the new documentation under my direction, over many iterations of planning and revision. If a blog post leaves you wanting more detail, you can now turn to: -- [Reference](/docs/reference/): accepted syntax, examples, and generated code for CGP constructs. -- [Concepts](/docs/concepts/): explanations of ideas such as provider composition, abstract types, and namespaces. -- [Comparisons](/docs/comparisons/): how CGP relates to similar features in other programming languages and approaches, including the limits of those comparisons. -- [Projects](/docs/projects/): walkthroughs of CGP projects highlighted in earlier blog posts and the patterns their code demonstrates. -- [The `/cgp` skill](/docs/ai/skills/): a foundation for AI assistants working with CGP, described below. -- [The knowledge base](/docs/ai/knowledge-base/): the fuller record used by agents working on CGP itself, including its implementation and documentation. +- [Reference](/docs/reference/): look up a construct's accepted syntax, examples, and generated code. +- [Concepts](/docs/concepts/): work through ideas such as provider composition, abstract types, and namespaces. +- [Comparisons](/docs/comparisons/): connect CGP to approaches you already know from other programming languages, with the limits of each comparison explained. +- [Projects](/docs/projects/): follow the code and patterns of CGP projects highlighted in earlier blog posts. +- [The `/cgp` skill](/docs/ai/skills/): give an AI assistant the foundations to help you read and write CGP, as described below. +- [The knowledge base](/docs/ai/knowledge-base/): explore the fuller record written for agents working on CGP itself, including its implementation and documentation. -The documentation's scale helps explain my estimate of months of full-time writing. The website now contains roughly 330,000 words of documentation prose across more than 340 pages, excluding code blocks and the mirrored skill files. At 300 words per printed page, that is about 1,100 pages before code listings. The actual printed length would depend on the layout. +Across more than 340 pages, the website now contains roughly 330,000 words of documentation prose, excluding code blocks and the mirrored skill files. At 300 words per printed page, that would be about 1,100 pages before code listings, though the actual printed length would depend on the layout. That scale is why I estimate months of full-time work for writing comparable material by hand. -Repeated planning, source checks, and revision are essential to the quality I am aiming for. I understand why readers may be skeptical of AI-written documentation, and I would not expect a one-shot prompt to produce useful documentation at this scale. I encourage you to read it and tell me where an explanation is vague, incorrect, or reads like generic AI output. +I understand why readers may be skeptical of AI-written explanations. A word count says little about their usefulness, and I would not expect a one-shot prompt to produce useful material at this scale. The planning, source checks, and repeated revisions are essential to the quality I am aiming for. I encourage you to read the pages and tell me where an explanation is vague, incorrect, or reads like generic AI output. ### How the documentation is written -The knowledge base gives agents a written account of CGP to work from. It records how CGP works, so an agent can consult it rather than write a page from what it remembers. I direct the work, set the rules, and choose what gets documented. +I direct the work, set the rules, and choose what gets documented. The process starts with the knowledge base, where agents record how CGP works and check claims about syntax and macro expansions against the implementation, tests, and expansion snapshots. That account becomes the basis for the website pages, which agents write and revise against the project's writing guides. -Agents check technical claims against the implementation, tests, and expansion snapshots. Those checks cover syntax and macro expansions. The website pages are then written from the knowledge base and revised against the project's writing guides. - -The written record also supports later revisions without requiring each agent to reconstruct CGP from scratch. That reuse helps me expand the documentation with the time available to me. The [knowledge-base overview](/docs/ai/knowledge-base/) explains the record and its role in the project. +For later revisions, an agent can return to the same record. It does not have to reconstruct CGP from scratch or rely on what it remembers, which makes the work more manageable within the time I have. The [knowledge-base overview](/docs/ai/knowledge-base/) explains how the record supports the project. Human review varies by page. I read the argument-bearing pages in full, including the Concepts explanations and blog posts. Individual reference pages follow their writing guides and receive spot checks. The knowledge base is [still being reviewed](/docs/ai/knowledge-base/#its-current-state), and both source checks and human review can miss errors. I remain responsible for what the project publishes. -[How CGP's Documentation Is Written](/docs/ai/knowledge-base/how-cgp-is-documented) explains how claims are checked and where those checks stop. The [AI disclosure](/docs/ai/disclaimer) describes who writes and reviews the documentation, tooling, and core library. - -I would like to explore the methodology further in a dedicated follow-up post. For now, [the process page](/docs/ai/knowledge-base/how-cgp-is-documented) explains how the documentation is produced and checked. +I would like to explore the methodology further in a dedicated follow-up post. For now, [How CGP's Documentation Is Written](/docs/ai/knowledge-base/how-cgp-is-documented) explains the process and where its checks stop. The [AI disclosure](/docs/ai/disclaimer) describes who writes and reviews the documentation, tooling, and core library. ### Optional help from the `/cgp` skill -The [`/cgp` skill](/docs/ai/skills/) teaches an AI assistant the foundations of reading and writing current CGP code. It covers the consumer/provider model, wiring, dependency declarations, and using cargo-cgp to investigate failures. The skill is a condensed guide for an agent, while the knowledge base supplies the fuller record it can consult. +If you already work with an AI assistant, try exploring a small CGP example together. With the [`/cgp` skill](/docs/ai/skills/) loaded, you can ask it to explain an unfamiliar wiring entry, trace which provider a method uses, or help investigate a compiler error. This gives you a way to explore the internal details as they become relevant, with explanations suited to your Rust experience. -The skill can help you learn CGP through a small example, with explanations suited to your Rust experience. If you are new to CGP and already work with an assistant, load the skill and ask it to explain unfamiliar parts of the example. It can help investigate macro expansions, guide you through installing and using cargo-cgp, and diagnose errors. The goal is to reduce how much you need to learn upfront by exploring the internal details as questions arise. +The skill gives the assistant a condensed guide to current CGP: the consumer/provider model, wiring, dependency declarations, and debugging with cargo-cgp. It can help the assistant investigate macro expansions and guide you through installing and using the checker. For deeper questions, it can consult the fuller knowledge-base record. You still need to review and verify the assistant's suggested code. The [skill instructions](/docs/ai/skills/) explain how to install and use the skill, and [Using the Knowledge Base with Your Agent](/docs/ai/knowledge-base/using-it-with-your-agent) covers deeper investigation. Neither is required to use CGP. ## Grouping component wiring with namespaces -Flat wiring tables can make growing CGP applications difficult to understand. Splitting an application into reusable providers makes dependencies easier to isolate, but each component also needs a routing entry in a flat `delegate_components!` table. As the component count grows, that list can obscure which choices matter and make the application look more complicated than the behavior it implements. +When an application has only a few components, writing out its `delegate_components!` table is straightforward. Each time we split behavior into another component, though, we add a routing entry. Eventually, someone opening the application has to sort through a long list of bindings before they can see which ones belong together. The implementations have become more reusable, but the configuration has become harder to follow. -Provider bundles did not remove repeated component lists from top-level wiring. CGP could already bundle implementations, but applications still had to enumerate the corresponding component keys. The preset system was an earlier attempt to reduce that repetition, with limitations explained below. +I have tried a few ways to address this difficulty. Provider bundles collect implementations, but applications still have to list the components they forward to each bundle. The earlier preset system reduced some repetition too, with limitations I will return to below. -Namespaces let an application select related implementations as a group. In the example below, production and test configurations share a PostgreSQL-backed core and differ in their content filters. A table that lists every component becomes a table selecting those groups, making the difference between configurations visible in one entry. +With namespaces, we can give those groups names and select their implementations together. I'll work through a social-media application whose production and test configurations share a PostgreSQL-backed core but use different content filters. By the end, that difference will be visible in one wiring entry. -You can skip the motivation if you already know why flat wiring tables become difficult to maintain. Jump to [the namespace syntax](#introducing-cgp-namespaces-and-paths), or to [the migration guide](#breaking-changes-and-migration) if you are upgrading an existing application. The walkthrough below builds up the wiring problem before introducing the solution. +If you have already maintained a large wiring table, you may prefer to jump to [the namespace syntax](#introducing-cgp-namespaces-and-paths) or [the migration guide](#breaking-changes-and-migration). Otherwise, let's start with the small application and see how its wiring grows. ### Start with a manager per domain {#an-example-social-media-web-app} -The running example uses an application context to select the operations of a social-media service. It holds a database handle and chooses the implementations for managing users and posts. Here the context represents the service, while the earlier `Rectangle` context was the data being operated on. +Suppose we are building a social-media service that manages users and posts. We need a database handle and a place to choose the implementations the service uses, so our context will represent the application. This is a different role from the earlier `Rectangle`, where the context was the data being operated on. The snippets illustrate wiring rather than a complete web service. They assume `use cgp::prelude::*;` and omit domain type declarations and database query bodies. The [web-app walkthrough](/docs/projects/cgp-examples/web-app) follows the same example, and its [compiling source](https://github.com/contextgeneric/cgp-examples/tree/v0.8.0/web-app) uses placeholder database operations. -Each stage replaces the preceding definitions or wiring. Treat a revised provider or table as a replacement, rather than adding a second implementation beside the previous one. +As we refactor, each stage replaces the preceding definitions or wiring. If you are following along, replace an earlier provider or table when its revised form appears. -The initial design groups user and post operations into a manager trait per domain: +We can begin with a familiar organization: one manager trait for users and another for posts. ```rust #[cgp_component(UserManager)] @@ -233,11 +229,11 @@ pub trait CanManagePost { } ``` -`#[cgp_component]` separates each trait's calling interface from its provider implementations. It turns the ordinary trait into a CGP component, generating a provider trait such as `UserManager` and a wiring key such as `UserManagerComponent`. A provider implements the operations independently of a concrete application, and the application's wiring chooses which provider to use. +The methods describe what the service can do. Adding `#[cgp_component]` lets us write their implementations separately from the application that uses them: it generates a provider trait such as `UserManager` and a wiring key such as `UserManagerComponent`. The application will choose a provider through that key. -Grouping items in a component makes one provider choice decide their implementations together. Component traits can contain multiple methods, associated types, and constants, so grouping the manager methods is a design choice. +Choosing a manager provider chooses all its methods together. That is our design for this first version: a component can contain multiple methods, associated types, and constants, just like an ordinary trait. As the service grows, we will see where choosing those methods together becomes inconvenient. -The database providers can remain independent of any concrete application context: +For the PostgreSQL implementations, each method declares the database handle it needs as an implicit argument. The providers can then work with any application supplying that dependency: ```rust #[cgp_impl(new PostgresUserManager)] @@ -307,9 +303,9 @@ impl PostManager { } ``` -Both providers read a PostgreSQL `database` field through their implicit arguments. Any context supplying that dependency can reuse the implementations. We could also define `SqliteUserManager` and `SqlitePostManager` providers for a SQLite-backed application, without changing the manager interfaces. +Any context with the required PostgreSQL `database` field can reuse these providers. If we wanted a SQLite-backed application, we could write `SqliteUserManager` and `SqlitePostManager` against the same interfaces and select those instead. -The initial production configuration needs only two entries: +For our production application, we supply the database field and choose the PostgreSQL managers: ```rust #[derive(HasField)] @@ -325,11 +321,11 @@ delegate_and_check_components! { } ``` -`ProductionApp` selects both managers without coupling their implementations to that context. At this stage, the database field is their only dependency. +Both managers share one dependency: the database field that `#[derive(HasField)]` makes available to their implicit arguments. The combined delegation-and-check macro verifies that `ProductionApp` can use the selected providers. For now, those two entries cover all the user and post operations. ### Add dependencies as the service grows -Content filtering adds dependencies to the database-backed managers. As the service grows, user creation needs username filtering and post creation needs spam detection, so the managers acquire dependencies on two more components: +Now suppose the service needs to reject censored usernames and spam posts. Before inserting a user or a post, its manager must consult a filter. We can add a component for each check and declare the manager's dependency on its consumer trait with `#[uses]`: ```rust #[cgp_component(UsernameCensor)] @@ -381,9 +377,9 @@ impl PostManager { } ``` -The managers use the filter scores to decide whether to reject a user or post. `CanCensorUsername` and `CanDetectSpamMessage` return the scores compared with the threshold. `#[uses]` declares each trait dependency on the context, while `#[implicit] database` reads its database field. The remaining manager methods are omitted here. +Each manager compares its filter's score with a rejection threshold before writing to the database. The `#[uses]` attribute declares the new trait dependency; `#[implicit] database` still supplies the database handle. The remaining manager methods are omitted here. -Production and tests can share the database providers while choosing different filters. Production filtering may involve an AI model or a cloud service, while tests can use deterministic string matching to exercise the rest of the application more quickly: +In production, filtering might involve an AI model or a cloud service. We would rather not make those calls every time we test the rest of the application. A deterministic string-matching filter lets tests run more quickly while keeping the same PostgreSQL managers: ```rust #[derive(HasField)] @@ -415,21 +411,21 @@ delegate_components! { } ``` -Both contexts reuse the PostgreSQL managers and supply the fields those managers require. Their different filter choices distinguish production from testing. `#[derive(HasField)]` makes each context's `database` field available to the providers' implicit arguments. +Both contexts supply the database field and select the same managers. Only the filter entries differ, so tests can exercise the database implementations with deterministic filtering. These tables record choices without checking all their dependencies. Explicit component checks, shown below, verify that the selected providers can be used. -Adding dependencies also increases the wiring repeated across contexts. CGP lets the application's dependency tree grow as requirements are added, but four component entries on each of two contexts already means eight wiring entries. +The wiring has grown along with the dependency tree. Four component entries on each context already means eight entries to maintain, even in this small service. ### Split independently reusable operations {#fine-grained-traits} -A manager provider makes every operation require all of that provider's dependencies. `get_user` needs the database, but it also requires a context implementing `CanCensorUsername` because that bound belongs to `PostgresUserManager`. The post manager has the same problem with spam detection. As more methods acquire unrelated dependencies, the manager becomes harder to maintain and test. +Adding `CanCensorUsername` to the user manager looked straightforward. But that bound belongs to the whole `PostgresUserManager` implementation, so even `get_user` now requires a context with a censor. Retrieving a user never runs the filter; the dependency arrives because retrieval and creation share a provider. The post manager has the same problem with spam detection, and every unrelated dependency we add makes the managers harder to maintain and test. -Domain names also leave questions about which operations belong together. Should `get_user_profile_picture` be part of the user manager, and should `get_user_posts` belong to the user or post manager? A single domain name does not always identify the right group of operations. +As we add operations, the domain boundaries become less obvious too. `get_user_profile_picture` might fit in the user manager, but it could need an entirely different set of dependencies. `get_user_posts` concerns both users and posts. Naming a manager after an entity does not settle which operations are useful to group together. -Narrower trait bounds let generic code request fewer operations. If a user manager gains a destructive `delete_user` operation, code that only retrieves users should not have to depend on the whole manager interface. Separate bounds let that code require only the operations it needs. +There is also a reason to keep the caller's interface narrow. If we later add `delete_user` to the manager, generic code that only retrieves users would depend on an interface that includes deletion. Giving retrieval its own trait lets that code request exactly the operation it needs. -Fine-grained components, each containing one or a handful of related items, let each provider require only what it uses: +Splitting the managers into smaller components lets each provider declare only the dependencies it uses. For the user operations, that gives us: ```rust #[cgp_component(UserCreator)] @@ -476,11 +472,11 @@ impl UserGetter { } ``` -The dependencies now follow the individual operations. `CreateUserWithPostgres` imports `CanCensorUsername`, while `GetUserWithPostgres` does not. The post manager can be split in the same way into creation, retrieval, update, and deletion components. Generic code bounded by `CanGetUser` can retrieve users without requiring user creation or deletion. +`GetUserWithPostgres` can be used with a database alone, while `CreateUserWithPostgres` keeps its censor dependency. A caller bounded by `CanGetUser` can retrieve users without depending on creation or deletion. The same split gives us separate post-creation, retrieval, update, and deletion components. ### Separate filtering from database access -A filtering wrapper can now add the username check to any user-creation provider: +The username check does not depend on PostgreSQL at all. Now that creation has its own component, we can move the check into a wrapper and apply it to whichever user-creation provider we choose: ```rust #[cgp_impl(new FilterCensoredUsername)] @@ -509,15 +505,15 @@ impl UserCreator { } ``` -`FilterCensoredUsername` is a **higher-order provider**: it takes another provider as a parameter. `#[use_provider]` requires that inner provider to implement user creation for the same context. The wrapper rejects censored names and otherwise calls the inner provider. +The wrapper rejects censored names, then hands an allowed request to `InnerCreator::create_user`. Its `#[use_provider]` attribute requires that inner provider to support user creation for the same context. Because it takes another provider as a parameter, we call `FilterCensoredUsername` a **higher-order provider**. -Filtering is now a wiring choice separate from database access. `CreateUserWithPostgres` can focus on constructing the SQL insert query, while the context chooses either that provider directly or `FilterCensoredUsername`. A local-first application could reuse the wrapper as `FilterCensoredUsername`, without changing the filtering implementation. +`CreateUserWithPostgres` can now focus on constructing the SQL insert query. When wiring the application, we can select it directly or add filtering with `FilterCensoredUsername`. A local-first application could instead select `FilterCensoredUsername` and reuse the same filter. Changing the database would not require copying the username check. `FilterSpamMessage` applies the same separation to post creation. It uses `CanDetectSpamMessage` to reject spam, then forwards an allowed post to its inner `PostCreator`. The wiring can therefore choose `FilterSpamMessage` independently of the database provider's implementation. ### Count the cost of the separation -The smaller components isolate dependencies and make the filtering reusable, but they add wiring. With seven CRUD operations and two filters, the production table becomes: +With dependencies isolated and filters reusable, the individual providers are easier to work with. The production wiring, however, now has to select seven CRUD operations and two filters: ```rust delegate_components! { @@ -544,11 +540,9 @@ delegate_components! { } ``` -The small example now needs nine component entries instead of four. An application with more features can grow to dozens or hundreds of wiring entries. To someone unfamiliar with the code, that list can obscure what `ProductionApp` implements and make adopting CGP look harder than it needs to be. - -Grouping the bindings would let a reader understand one part of the application at a time. The flat table presents too much information at once, so it needs smaller units. +Our small example has gone from four component entries to nine. With more features, an application can reach dozens or hundreds. Each binding has a purpose, but the flat list gives a reader little help in finding which choices belong together. -A provider bundle can collect related bindings into a smaller table: +We can make the list easier to read by collecting the user bindings into their own provider bundle: ```rust delegate_components! { @@ -563,9 +557,9 @@ delegate_components! { } ``` -`new PostgresUserComponents` declares an **aggregate provider**, a provider whose table delegates each operation to another provider. Its three entries can be read independently of the rest of the application. `PostgresPostComponents` can collect the post operations, and `AiContentFilterComponents` can collect the AI-backed filtering providers. +With `new PostgresUserComponents`, we declare an **aggregate provider**: its table delegates each operation to another provider. A reader can examine the user wiring on its own, without the post operations and filters alongside it. We can collect those into `PostgresPostComponents` and `AiContentFilterComponents` in the same way. -Bundles organize the implementations, but without namespaces the application must still enumerate every key when forwarding to them: +Back in the application, we forward the components to their bundles using array keys: ```rust delegate_components! { @@ -592,11 +586,11 @@ delegate_components! { } ``` -Array keys still leave each component group unnamed. They send several components to the same bundle, but the application cannot refer to “all user components” or “all content filters” as a group. Adding a user operation therefore means updating both the bundle and the component list on each application that forwards to it. +The implementations are grouped, yet we still have to spell out every component name here. Adding a user operation means updating the user bundle and then finding every application that lists its keys. We cannot simply tell the application to use `PostgresUserComponents` for “all user components.” The group itself needs a name we can wire. ### Why the earlier grouping approaches were insufficient -The desired configuration would let us name each group once. In pseudocode, it would look like this: +Ideally, the configuration would say something like this, with a key for each group: ```text delegate_components! { @@ -611,9 +605,9 @@ delegate_components! { } ``` -Rust's trait system does not provide an operation that expands a type-level list into a separate implementation for every listed key. CGP therefore needs a way to express the grouping through its own lookup rules or macro expansion. +The missing keys are the difficulty. Rust's trait system does not provide an operation that expands a type-level list into a separate implementation for every listed key. To express this configuration, CGP needs to handle the groups through its own lookup rules or macro expansion. -A macro that expands to a list of component keys might appear to solve the repetition. Another hypothetical form is: +One possibility would be a helper macro that supplied the list of keys for each group. That would let us write a hypothetical table like this: ```text delegate_components! { @@ -628,17 +622,33 @@ delegate_components! { } ``` -The proposed helpers would supply a component list for each group. For example, `all_user_components!()` would expand to `[UserCreatorComponent, UserGetterComponent, UserUpdaterComponent]`, with corresponding lists for posts and filters. These are hypothetical forms, not supported syntax. +Here, `all_user_components!()` would expand to `[UserCreatorComponent, UserGetterComponent, UserUpdaterComponent]`, with corresponding lists for posts and filters. Like the `???` keys above, these helpers are pseudocode rather than supported syntax. -The outer macro cannot inspect a helper's output when it parses the invocation. `delegate_components!` receives `all_user_components!()` before the helper expands, so the component list is unavailable to its parser. Supporting this arrangement would require a different macro-composition mechanism, together with machinery for generating and exporting helpers whose names and imports remain usable across crate boundaries. +Unfortunately, `delegate_components!` receives `all_user_components!()` before the helper expands. When the outer macro parses the table, the component list is not available yet. Supporting this arrangement would require a different macro-composition mechanism, along with a way to generate and export helpers whose names and imports remain usable across crate boundaries. My earlier [preset system](/blog/hypershell-release#cgp-presets) shared wiring but made independent groups difficult to combine. Its inheritance mechanism could supply one preset to a context, while Rust's coherence restrictions prevented a context from inheriting independent user and post presets that way. I also experimented with macro-based composition of multiple presets, but expansion order and the handling of imports and aliases made that approach tedious to use. -Namespaces let an application name a component group and select its implementation bundle without enumerating every key. That is the goal the earlier approaches were trying to meet. Namespaces express it through trait resolution and paths. The [migration section](#replace-presets-with-namespace-configuration) shows how existing preset users can move to them. +Those attempts helped clarify what I wanted from the feature: an application should be able to name a group and choose its implementation bundle without enumerating every key. In v0.8.0, namespaces express that choice through trait resolution and paths. Existing preset users can find the conversion in the [migration section](#replace-presets-with-namespace-configuration). ### Give component groups a path {#introducing-cgp-namespaces-and-paths} -A component can register a path prefix in a namespace. Here, `CanCreateUser` registers its component under `@app.core.user` in the built-in `DefaultNamespace`: +We can now replace the `???` keys with paths that name the user, post, and content-filter groups. With the component prefixes registered, our application table becomes: + +```rust +delegate_components! { + ProductionApp { + namespace DefaultNamespace; + + @app.core.user: PostgresUserComponents, + @app.core.post: PostgresPostComponents, + @app.extra.content_filter: AiContentFilterComponents, + } +} +``` + +The `namespace DefaultNamespace;` statement opts this table into the namespace's registered routes, and each path entry selects a whole bundle. Adding another user operation to the user group no longer requires repeating its component name here. The individual bindings still live in the bundles; the application selects the groups it uses. + +To make this work, we give each component a prefix using `#[prefix]`. For `CanCreateUser`, we register `@app.core.user` in the built-in `DefaultNamespace`: ```rust #[cgp_component(UserCreator)] @@ -648,9 +658,9 @@ pub trait CanCreateUser { } ``` -`#[prefix]` records the route, and CGP appends the component marker to it. A lookup for `UserCreatorComponent` therefore uses the address `@app.core.user.UserCreatorComponent` once a context joins the namespace. +CGP appends the component marker to this prefix. Once a context joins the namespace, a lookup for `UserCreatorComponent` follows the route to `@app.core.user.UserCreatorComponent`. -Several components can share one prefix. The getter below and the updater register under the same user prefix: +The getter and updater belong to that group too, so we register them under the same prefix. For the getter, that means: ```rust #[cgp_component(UserGetter)] @@ -660,7 +670,7 @@ pub trait CanGetUser { } ``` -The post components register under `@app.core.post`: +Post operations get their own `@app.core.post` prefix: ```rust #[cgp_component(PostCreator)] @@ -670,31 +680,15 @@ pub trait CanCreatePost { } ``` -The filter components register under `@app.extra.content_filter`, also in `DefaultNamespace`. These paths describe the groups independently of which providers an application chooses. +Finally, the filter components register under `@app.extra.content_filter`, also in `DefaultNamespace`. These registrations describe the groups independently of the providers an application chooses. -The application joins the namespace and forwards each group to its bundle: +Let's follow one operation through the completed wiring. `create_user` asks for `UserCreatorComponent`, and the namespace redirects it to `@app.core.user.UserCreatorComponent`. The application's `@app.core.user` entry selects `PostgresUserComponents`, whose table selects `FilterCensoredUsername`. Rust resolves the whole chain at compile time, without a runtime lookup table. -```rust -delegate_components! { - ProductionApp { - namespace DefaultNamespace; - - @app.core.user: PostgresUserComponents, - @app.core.post: PostgresPostComponents, - @app.extra.content_filter: AiContentFilterComponents, - } -} -``` - -Namespace routing connects each component lookup to the application's selected provider bundle. The namespace supplies routes, prefixes identify groups, and aggregate providers supply implementations. For example, `create_user` asks for `UserCreatorComponent`, which the namespace redirects to `@app.core.user.UserCreatorComponent`. The `@app.core.user` entry selects `PostgresUserComponents`, and that bundle selects `FilterCensoredUsername` for the component. Rust resolves these steps at compile time, without a runtime lookup table. - -Namespaces are opt-in: `namespace DefaultNamespace;` enables the registered routes for this table. A custom namespace can register components under different prefixes and be selected in the same way. - -The top-level table now has three entries. The individual bindings still live in the bundles, but the application no longer repeats their component names merely to select a group. +A custom namespace could register components under different prefixes. Each table chooses which namespace to join with its `namespace` statement. ### Group paths hierarchically -Parent prefixes can group several domains. The path `@app.core.user` has the parent `@app.core`, which itself sits under `@app`. Both user and post components share `@app.core`, so an intermediate bundle can collect them, with another bundle collecting the extras: +Production and tests both use the PostgreSQL user and post operations. Rather than select those bundles separately in each application, we can collect them under their shared parent, `@app.core`. The paths are hierarchical: `@app.core.user` sits under `@app.core`, which sits under `@app`. An intermediate bundle can therefore gather the core operations, while another gathers the extras: ```rust delegate_components! { @@ -717,7 +711,7 @@ delegate_components! { } ``` -Path-keyed bundles must also join `DefaultNamespace` to resolve the component keys they receive. A bundle receives the bare component key, and its namespace statement redirects that key to the paths inside its own table. Leaf bundles keyed by bare component names do not need a namespace statement. +Notice that these intermediate bundles also join `DefaultNamespace`. When a lookup reaches a bundle, it receives the bare component key; the namespace statement redirects that key to the paths in the bundle's own table. Our earlier leaf bundles use bare component names already, so they do not need that statement. The production configuration now selects two groups: @@ -732,7 +726,7 @@ delegate_components! { } ``` -A test configuration can share the whole PostgreSQL-backed core and change just the extras. Its `DummyExtraComponents` bundle supplies the deterministic filters: +For testing, the core stays the same. Only the extras entry changes, selecting `DummyExtraComponents` for deterministic filtering: ```rust {6} delegate_components! { @@ -745,7 +739,7 @@ delegate_components! { } ``` -A local configuration can instead change the database-backed core while retaining the production filters: +For a local configuration, we could make the other choice: keep the production filters and select a SQLite-backed core: ```rust {5} delegate_components! { @@ -758,15 +752,13 @@ delegate_components! { } ``` -The two variants differ from production in one entry each: `TestApp` changes `@app.extra`, while `LocalApp` changes `@app.core`. - -Each context must still supply the fields and other dependencies its selected providers require. A SQLite core would need its corresponding database handle. +In each case, one entry tells us how the configuration differs from production. `TestApp` changes the extras; `LocalApp` changes the core. With flat tables, we would have to compare the individual component entries, perhaps written in different orders, to reach the same conclusion. We can now read those decisions directly from the wiring. -Named groups make the configuration differences easier to compare. Without namespace grouping, a reader would have to compare the individual component entries across all three contexts. Those entries might appear in different orders, making the differences harder to spot. Grouping shows the shared parts and the parts that change directly. +The selected providers still need their dependencies. Each context must supply the required fields and other traits, and the hypothetical SQLite core would need its corresponding database handle. ### Check the completed configuration -Check each concrete context explicitly to verify its provider dependencies. Wiring records provider choices lazily, so a `delegate_components!` block can compile before any operation forces those dependencies to be checked: +We have organized the provider choices, but we still need to verify that they work together. Wiring is lazy: a `delegate_components!` block can compile before an operation forces the provider dependencies to be checked. A separate check on the concrete application makes that verification explicit: ```rust check_components! { @@ -784,21 +776,21 @@ check_components! { } ``` -`ProductionApp`, `TestApp`, and local variants can use the same nine-component check. Apply the check above to `TestApp` and any local variant as well. For an earlier stage of the walkthrough, check the components used in that stage, such as `UserManagerComponent` and `PostManagerComponent` before the managers are split. +Apply the same nine-component check to `TestApp` and any local variant. Earlier stages need checks matching their components: before splitting the managers, for example, check `UserManagerComponent` and `PostManagerComponent`. -Component checks must still name the operations that need to work. Namespaces remove repeated routing entries, but the dependencies of those operations still need verification. Check aggregate providers through the real contexts that use them, rather than treating a bundle as its own application context. +The list still names the individual operations we expect to work, even though the routing is grouped. Check them through the real application context that supplies their dependencies. An aggregate provider is a bundle of implementations, and checking it as though it were the application would ask it to supply dependencies that belong on the context. The [namespace documentation](/docs/concepts/namespaces) explains the lookup model, and the [`delegate_components!` reference](/docs/reference/macros/delegate_components) covers the path syntax. ## Sharing default implementations {#default-implementations} -A namespace can also bind provider choices shared by all its contexts. The bundles above suit configurations that swap whole implementation groups, such as `SqliteCoreComponents`, `PostgresCoreComponents`, or a `PostgresWithLoggingCoreComponents` variant that adds logging. +So far, we have organized the wiring around choices we might want to change: PostgreSQL or SQLite, production or test filters. Bundles work well for that arrangement. We could add a `PostgresWithLoggingCoreComponents` variant, for example, and select the logging-backed core in the same place. -An early application may not need interchangeable provider bundles. If it only uses PostgreSQL, defining a `PostgresUserComponents` bundle may be more organization than it needs yet. A single chosen implementation, intentionally coupled to its interface within a configuration, can be easier to reason about. +But an application starting out with PostgreSQL may have little reason to define interchangeable database bundles yet. If several contexts should always use the same user and post implementations, making each one select those bundles adds organization without expressing a useful difference. We can instead record those choices once in a namespace and leave only the varying parts to each context. These are **default implementations**. -Default implementations record fixed provider choices within a namespace. If several contexts should always use the same user and post providers, a custom namespace can record those choices once, leaving explicit wiring for the choices that vary. +I see defaults as a way to adopt CGP gradually. Ordinary traits may already be enough for a single-crate application with one implementation of each operation. If that application later needs more modularity, it can move code into CGP components and record its initial provider choices as defaults. Bundles can follow when there are useful groups to swap. -Define a namespace inheriting the component routes from `DefaultNamespace`: +Let's keep the routes we already registered in `DefaultNamespace` and define a configuration namespace that inherits them: ```rust cgp_namespace! { @@ -806,9 +798,9 @@ cgp_namespace! { } ``` -`DefaultAppComponents` inherits the prefixes and any default bindings supplied by `DefaultNamespace`. Its own bindings apply to contexts that select this configuration namespace, without changing what other namespaces select. +`DefaultAppComponents` starts with the prefixes and any default bindings supplied by its parent. We can add our application-specific choices here without changing what other namespaces select. Every context that joins this configuration namespace will share those choices. -Add `#[default_impl]` to the earlier `GetUserWithPostgres` implementation to bind it at the component's full path: +For a simple provider, we can place its binding beside its implementation. Add `#[default_impl]` to our earlier `GetUserWithPostgres` definition: ```rust #[cgp_impl(new GetUserWithPostgres)] @@ -820,7 +812,7 @@ impl UserGetter { } ``` -The attribute registers `GetUserWithPostgres` at that path in `DefaultAppComponents`. It is equivalent to writing the binding separately in a namespace body: +The implementation now declares that `DefaultAppComponents` uses it at `@app.core.user.UserGetterComponent`. If we prefer to collect the bindings in one place, we can write the same choice in the namespace body instead: ```rust cgp_namespace! { @@ -830,17 +822,15 @@ cgp_namespace! { } ``` -Namespace-body entries bind providers for every context that selects the namespace. The body resembles a `delegate_components!` table, but its entries belong to the namespace instead of one context or aggregate provider. The full `@app.core.user.UserGetterComponent` path is required here because the inherited route already maps the bare component marker to that address. +These are alternative ways to register the same binding; writing both would create a conflict. The namespace body looks like a `delegate_components!` table, but its choices apply to every context that joins the namespace. We use the full path because the inherited route already maps the bare component marker to that address. -Use either the attribute or the namespace-body entry for this binding, rather than writing both. +These defaults are fixed choices. Once the namespace binds a provider, a joining context or inheriting namespace cannot override it, even with a more specific entry. A context also cannot disable just one default while retaining the rest of that namespace. Choices that need to vary must stay on destinations the namespace leaves unbound. -A prefixed default registration must live in the crate that owns its namespace, here `DefaultAppComponents`. The key expands to CGP's `PathCons` type, so owning a component marker nested inside it does not satisfy Rust's orphan rules. An unprefixed local component marker has different ownership rules, covered by the [`#[default_impl]` reference](/docs/reference/attributes/default_impl). - -A namespace's fixed bindings cannot be overridden by joining contexts or inheriting namespaces. Adding a more specific entry does not replace a binding, and a context cannot disable just one fixed default while keeping the rest of that same namespace. Keep choices that should vary on paths the namespace leaves unbound. +There is also a constraint on where we write the registration. With a prefixed path, the binding must live in the crate that owns the namespace, here `DefaultAppComponents`. The path expands to CGP's `PathCons` type, and owning a component marker nested inside that type does not satisfy Rust's orphan rules. An unprefixed local component marker has different ownership rules, covered by the [`#[default_impl]` reference](/docs/reference/attributes/default_impl). ### Bind composite providers in the namespace body -A wrapper such as `FilterCensoredUsername` is a complete provider choice, so record it directly in the namespace body: +`FilterCensoredUsername` is generic over its inner provider. For this configuration, we want to choose both the wrapper and its PostgreSQL implementation. We can assemble that complete provider choice directly in the namespace body: ```rust cgp_namespace! { @@ -851,13 +841,13 @@ cgp_namespace! { } ``` -The application only needs to choose its filters once the namespace binds the remaining user and post providers. In this example, `ContentFilterComponents` names the AI-backed filter bundle defined earlier: +After we bind the remaining user and post providers in the same way, the application only needs to choose its filters. For this example, let `ContentFilterComponents` name the AI-backed filter bundle from earlier: ```rust type ContentFilterComponents = AiContentFilterComponents; ``` -The application selects that bundle explicitly: +Our production wiring then becomes: ```rust delegate_components! { @@ -869,31 +859,29 @@ delegate_components! { } ``` -Leaving the filter path unbound lets each context choose its filters. A test context can select `DummyContentFilterComponents` at that same path. Both contexts still need component checks, including the dependencies of providers supplied by defaults. +All the shared user and post choices come from `DefaultAppComponents`. We deliberately left the filter path unbound, so a test context can select `DummyContentFilterComponents` there instead. Both contexts still need component checks, including checks of the dependencies introduced by the defaults. ### Choose how much wiring to share -Separate structural routes from fixed provider choices so configurations can reuse the same routes. Put the routes in a base namespace and fixed choices in a configuration namespace that inherits it. Another configuration can then reuse the routes without inheriting provider choices it needs to replace. - -Choose a namespace that leaves a destination open when you need to replace its fixed default. For example, join the base `DefaultNamespace` and supply the required bindings there. +Keeping the prefixes in `DefaultNamespace` and the provider choices in `DefaultAppComponents` gives us a useful separation. Another configuration can reuse the same routes without inheriting PostgreSQL choices it needs to replace. That is why the structural routes belong in a base namespace and fixed choices in a configuration namespace that inherits it. -`#[default_impl]` is convenient for gradual adoption in a single crate, where the namespace and provider definitions can live together. As providers move into separate crates, namespace-body entries let the namespace's own crate assemble them without requiring registration attributes beside each implementation. The ownership rule still applies to the generated binding. +If we later need to replace one of these fixed defaults, we choose a namespace that leaves its destination open. We could return to the base `DefaultNamespace` and supply the required bindings explicitly, as in the earlier bundle examples. -I see default implementations as a way to move gradually from a single-crate application to a more modular one. Ordinary traits may already be sufficient when a single crate has one implementation of each operation. An application that later needs more modularity can first refactor its monolithic code into CGP components with defaults, without significantly disrupting its organization. It can then introduce explicit bundles and split crates as those needs arise, rather than requiring the full wiring structure at the start. +While the application lives in one crate, `#[default_impl]` is a convenient way to keep a binding beside the implementation. As providers move into separate crates, we can move their bindings into the configuration namespace's body. Its own crate then assembles the providers, respecting the same ownership rule without requiring registration attributes beside each implementation. -Choose the amount of wiring that makes the application's decisions clear. Defaults suit choices every joining context should share, while explicit bundles suit interchangeable implementation groups. Smaller applications can stay with direct wiring until grouping makes their configuration easier to read. +There is room to start with direct wiring, share fixed choices through defaults, and introduce interchangeable bundles as the application needs them. I would choose whichever arrangement makes the current decisions easiest to see, rather than build the full hierarchy in anticipation of future growth. ## Other improvements -The release also adds smaller features that build on the same machinery. Their references cover the full syntax: +Namespaces are the largest change, but several smaller additions also reduce the work of writing and reading CGP. You can use these without following the full application refactoring above: -- **Per-type dispatch with `open`:** choose providers for a generic component directly in a context's table, without declaring a namespace or a nested `UseDelegate` table. See [`delegate_components!`](/docs/reference/macros/delegate_components#choosing-a-provider-per-type-the-open-statement). -- **Importing tables with `for`:** bring entries from another namespace table onto a path, so independently defined groups of defaults can be assembled in one context. See [namespace statements](/docs/reference/macros/delegate_components#the-namespace-statements). -- **Implementation-only generics:** `#[impl_generics]` lets a `#[cgp_fn]` implementation infer a generic type from an implicit field without exposing that type as a trait parameter. See [`#[impl_generics]`](/docs/reference/attributes/impl_generics). -- **Readable data shapes:** [`Struct!`](/docs/reference/macros/struct) and [`Enum!`](/docs/reference/macros/enum) express the field lists of structs and enums using declaration-like syntax. cargo-cgp also uses these forms when displaying shapes. -- **Variants without fields:** the extensible-variant derives accept variants such as `Closed`, `Closed()`, and `Closed {}`, representing their payload as `Nil`. A `no_std` crate using the mutable extractor must have `Box` in scope. +- **Choose a provider per type with `open`.** If a generic component needs one provider for a rectangle and another for a circle, you can put those selections directly in the context's table. You do not need to declare a namespace or a nested `UseDelegate` table. The [`delegate_components!` reference](/docs/reference/macros/delegate_components#choosing-a-provider-per-type-the-open-statement) shows the syntax. +- **Assemble separate tables with `for`.** A backend and an API surface may each have their own table of defaults. You can bring entries from another namespace table onto a path in your context, keeping those concerns independently defined. See [namespace statements](/docs/reference/macros/delegate_components#the-namespace-statements). +- **Keep implementation details out of trait parameters.** Sometimes a `#[cgp_fn]` body needs a generic type only because it reads a field of that type. With [`#[impl_generics]`](/docs/reference/attributes/impl_generics), the implementation can infer the type from the implicit field without adding a parameter to the generated trait. +- **Write data shapes as declarations.** A field list is easier to recognize when it looks like the struct or enum it describes. [`Struct!`](/docs/reference/macros/struct) and [`Enum!`](/docs/reference/macros/enum) provide that notation, and cargo-cgp uses it when displaying shapes too. +- **Use fieldless variants directly.** If an enum contains a state such as `Closed`, you can now use the extensible-variant derives without giving it a placeholder payload. The derives accept `Closed`, `Closed()`, and `Closed {}`, representing the payload as `Nil`. A `no_std` crate using the mutable extractor must have `Box` in scope. -The handler macros also generate self-contained expansions without relying on a prelude import at the call site. The release fixes lifetime handling and supertrait support in `#[cgp_auto_dispatch]`, and improves rejection messages for unsupported function signatures in `#[cgp_computer]` and `#[cgp_producer]`. +There are also fixes for code that previously ran into the limits of the handler macros. Their generated code is now self-contained, so using them does not rely on a prelude import at the call site. `#[cgp_auto_dispatch]` has fixes for lifetime handling and supertrait support, while `#[cgp_computer]` and `#[cgp_producer]` give clearer rejection messages for unsupported function signatures. ## Breaking changes and migration @@ -1013,9 +1001,9 @@ The minimum anyhow and eyre dependencies rise to 1.0.104 and 0.6.14 respectively ## Try one part of your application -With v0.8.0, I want to make CGP easier to learn and maintain. cargo-cgp helps explain missing dependencies, and the expanded documentation gives readers somewhere to follow those explanations. As an application grows, namespaces let its wiring show which groups of implementations it selects. +We started with two manager choices and ended with applications that could share a core, change their filters, or use a different database. Namespaces let the top-level wiring express those choices even as we split the implementations into smaller pieces. I hope that makes similar refactorings easier to follow in your own projects, with cargo-cgp and the new documentation there to help when something is unclear. -CGP still has a learning curve, and the tooling and documentation need further work. +There is still a learning curve, and both the tooling and documentation need further work. You do not need to adopt the whole arrangement in this post to find out whether one part helps. Start with a small example or one part of your existing application. If you already use CGP, try grouping one part of your wiring while keeping its component checks in place. If you are new to CGP, the [Quickstart](/docs/quickstart) provides a smaller starting point. From c23dd28d3ae181c12e5d2eb1212822161982d2b7 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 1 Nov 2026 22:09:33 +0100 Subject: [PATCH 180/516] Fully human review blog post --- blog/2026-05-10-v0.8.0-release.md | 51 ++++++++++++------------------- 1 file changed, 19 insertions(+), 32 deletions(-) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index cbb9702d..a820df01 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -146,11 +146,9 @@ cargo cgp check `cargo cgp setup` installs the tool's pinned nightly and builds the matching driver. That nightly is used for cargo-cgp's checks; your application keeps its normal toolchain for ordinary cargo builds, and CGP itself still compiles on stable Rust. You can use CGP without installing cargo-cgp. -The tool is tested on Linux. macOS and Windows are untested. - Use plain cargo to build, run, and test applications. cargo-cgp supplies `check` for diagnostics and [`expand`](/docs/cargo-cgp/expand) for reading the Rust generated by macros, with CGP's type-level constructs restored to readable notation. The [installation guide](/docs/cargo-cgp/installation) covers setup, updates, and the Nix alternative. -## Expanded documentation and optional agent support +## Expanded documentation and AI agent support A release post can show you an interesting feature and still leave you unsure how to use it in your own program. For too long, CGP left readers in that position. Most explanations lived in blog posts like this one, with each post introducing features as they arrived. There was little room to explain every construct or give readers a complete account of how the pieces fit together. @@ -165,7 +163,7 @@ Advances in AI and agentic coding made it practical to take on that work. Agents - [The `/cgp` skill](/docs/ai/skills/): give an AI assistant the foundations to help you read and write CGP, as described below. - [The knowledge base](/docs/ai/knowledge-base/): explore the fuller record written for agents working on CGP itself, including its implementation and documentation. -Across more than 340 pages, the website now contains roughly 330,000 words of documentation prose, excluding code blocks and the mirrored skill files. At 300 words per printed page, that would be about 1,100 pages before code listings, though the actual printed length would depend on the layout. That scale is why I estimate months of full-time work for writing comparable material by hand. +Across more than 340 pages, the website now contains roughly 330,000 words of documentation prose, excluding code blocks and the mirrored skill files. At 300 words per printed page, that would be about 1,100 pages before code listings. I understand why readers may be skeptical of AI-written explanations. A word count says little about their usefulness, and I would not expect a one-shot prompt to produce useful material at this scale. The planning, source checks, and repeated revisions are essential to the quality I am aiming for. I encourage you to read the pages and tell me where an explanation is vague, incorrect, or reads like generic AI output. @@ -189,11 +187,13 @@ You still need to review and verify the assistant's suggested code. The [skill i ## Grouping component wiring with namespaces +The new release also introduces new features that solve a major pain point in scaling the number of CGP components, by introducing a new concept called [**namespaces**](/docs/concepts/namespaces). We will explore this in detail next. + When an application has only a few components, writing out its `delegate_components!` table is straightforward. Each time we split behavior into another component, though, we add a routing entry. Eventually, someone opening the application has to sort through a long list of bindings before they can see which ones belong together. The implementations have become more reusable, but the configuration has become harder to follow. I have tried a few ways to address this difficulty. Provider bundles collect implementations, but applications still have to list the components they forward to each bundle. The earlier preset system reduced some repetition too, with limitations I will return to below. -With namespaces, we can give those groups names and select their implementations together. I'll work through a social-media application whose production and test configurations share a PostgreSQL-backed core but use different content filters. By the end, that difference will be visible in one wiring entry. +With [**namespaces**](/docs/concepts/namespaces), we can now give those groups names and select their implementations together. I'll work through a social-media application whose production and test configurations share a PostgreSQL-backed core but use different content filters. By the end, that difference will be visible in one wiring entry. If you have already maintained a large wiring table, you may prefer to jump to [the namespace syntax](#introducing-cgp-namespaces-and-paths) or [the migration guide](#breaking-changes-and-migration). Otherwise, let's start with the small application and see how its wiring grows. @@ -203,8 +203,6 @@ Suppose we are building a social-media service that manages users and posts. We The snippets illustrate wiring rather than a complete web service. They assume `use cgp::prelude::*;` and omit domain type declarations and database query bodies. The [web-app walkthrough](/docs/projects/cgp-examples/web-app) follows the same example, and its [compiling source](https://github.com/contextgeneric/cgp-examples/tree/v0.8.0/web-app) uses placeholder database operations. -As we refactor, each stage replaces the preceding definitions or wiring. If you are following along, replace an earlier provider or table when its revised form appears. - We can begin with a familiar organization: one manager trait for users and another for posts. ```rust @@ -385,9 +383,10 @@ In production, filtering might involve an AI model or a cloud service. We would #[derive(HasField)] pub struct ProductionApp { pub database: PostgresDb, + // ... // AI client credentials } -delegate_components! { +delegate_and_check_components! { ProductionApp { UserManagerComponent: PostgresUserManager, PostManagerComponent: PostgresPostManager, @@ -401,7 +400,7 @@ pub struct TestApp { pub database: PostgresDb, } -delegate_components! { +delegate_and_check_components! { TestApp { UserManagerComponent: PostgresUserManager, PostManagerComponent: PostgresPostManager, @@ -413,8 +412,6 @@ delegate_components! { Both contexts supply the database field and select the same managers. Only the filter entries differ, so tests can exercise the database implementations with deterministic filtering. -These tables record choices without checking all their dependencies. Explicit component checks, shown below, verify that the selected providers can be used. - The wiring has grown along with the dependency tree. Four component entries on each context already means eight entries to maintain, even in this small service. ### Split independently reusable operations {#fine-grained-traits} @@ -505,7 +502,7 @@ impl UserCreator { } ``` -The wrapper rejects censored names, then hands an allowed request to `InnerCreator::create_user`. Its `#[use_provider]` attribute requires that inner provider to support user creation for the same context. Because it takes another provider as a parameter, we call `FilterCensoredUsername` a **higher-order provider**. +The wrapper rejects censored names, then hands an allowed request to `InnerCreator::create_user`. Its `#[use_provider]` attribute requires that inner provider to support user creation for the same context. Because it takes another provider as a parameter, we call `FilterCensoredUsername` a [**higher-order provider**](/docs/concepts/higher-order-providers). `CreateUserWithPostgres` can now focus on constructing the SQL insert query. When wiring the application, we can select it directly or add filtering with `FilterCensoredUsername`. A local-first application could instead select `FilterCensoredUsername` and reuse the same filter. Changing the database would not require copying the username check. @@ -557,9 +554,9 @@ delegate_components! { } ``` -With `new PostgresUserComponents`, we declare an **aggregate provider**: its table delegates each operation to another provider. A reader can examine the user wiring on its own, without the post operations and filters alongside it. We can collect those into `PostgresPostComponents` and `AiContentFilterComponents` in the same way. +With `new PostgresUserComponents`, we declare an [**aggregate provider**](/docs/concepts/aggregate-providers): its table delegates each operation to another provider. A reader can examine the user wiring on its own, without the post operations and filters alongside it. We can collect those into `PostgresPostComponents` and `AiContentFilterComponents` in the same way. -Back in the application, we forward the components to their bundles using array keys: +Back in the application, we forward the components to their bundles using [array keys](/docs/reference/macros/delegate_components#the-key-forms): ```rust delegate_components! { @@ -624,7 +621,7 @@ delegate_components! { Here, `all_user_components!()` would expand to `[UserCreatorComponent, UserGetterComponent, UserUpdaterComponent]`, with corresponding lists for posts and filters. Like the `???` keys above, these helpers are pseudocode rather than supported syntax. -Unfortunately, `delegate_components!` receives `all_user_components!()` before the helper expands. When the outer macro parses the table, the component list is not available yet. Supporting this arrangement would require a different macro-composition mechanism, along with a way to generate and export helpers whose names and imports remain usable across crate boundaries. +Unfortunately, `delegate_components!` receives the literal `all_user_components!()` before the helper expands. When the outer macro parses the table, the component list is not available yet. Supporting this arrangement would require a different macro-composition mechanism, along with a way to generate and export helpers whose names and imports remain usable across crate boundaries. My earlier [preset system](/blog/hypershell-release#cgp-presets) shared wiring but made independent groups difficult to combine. Its inheritance mechanism could supply one preset to a context, while Rust's coherence restrictions prevented a context from inheriting independent user and post presets that way. I also experimented with macro-based composition of multiple presets, but expansion order and the handling of imports and aliases made that approach tedious to use. @@ -682,10 +679,6 @@ pub trait CanCreatePost { Finally, the filter components register under `@app.extra.content_filter`, also in `DefaultNamespace`. These registrations describe the groups independently of the providers an application chooses. -Let's follow one operation through the completed wiring. `create_user` asks for `UserCreatorComponent`, and the namespace redirects it to `@app.core.user.UserCreatorComponent`. The application's `@app.core.user` entry selects `PostgresUserComponents`, whose table selects `FilterCensoredUsername`. Rust resolves the whole chain at compile time, without a runtime lookup table. - -A custom namespace could register components under different prefixes. Each table chooses which namespace to join with its `namespace` statement. - ### Group paths hierarchically Production and tests both use the PostgreSQL user and post operations. Rather than select those bundles separately in each application, we can collect them under their shared parent, `@app.core`. The paths are hierarchical: `@app.core.user` sits under `@app.core`, which sits under `@app`. An intermediate bundle can therefore gather the core operations, while another gathers the extras: @@ -790,7 +783,7 @@ But an application starting out with PostgreSQL may have little reason to define I see defaults as a way to adopt CGP gradually. Ordinary traits may already be enough for a single-crate application with one implementation of each operation. If that application later needs more modularity, it can move code into CGP components and record its initial provider choices as defaults. Bundles can follow when there are useful groups to swap. -Let's keep the routes we already registered in `DefaultNamespace` and define a configuration namespace that inherits them: +Let's keep the routes we already registered in `DefaultNamespace` and define a configuration namespace that inherits them using the new [`cgp_namespace!`](/docs/reference/macros/cgp_namespace) macro: ```rust cgp_namespace! { @@ -800,7 +793,7 @@ cgp_namespace! { `DefaultAppComponents` starts with the prefixes and any default bindings supplied by its parent. We can add our application-specific choices here without changing what other namespaces select. Every context that joins this configuration namespace will share those choices. -For a simple provider, we can place its binding beside its implementation. Add `#[default_impl]` to our earlier `GetUserWithPostgres` definition: +For a simple provider, we can place its binding beside its implementation. Add [`#[default_impl]`](/docs/reference/attributes/default_impl) to our earlier `GetUserWithPostgres` definition: ```rust #[cgp_impl(new GetUserWithPostgres)] @@ -822,11 +815,11 @@ cgp_namespace! { } ``` -These are alternative ways to register the same binding; writing both would create a conflict. The namespace body looks like a `delegate_components!` table, but its choices apply to every context that joins the namespace. We use the full path because the inherited route already maps the bare component marker to that address. +These are alternative ways to register the same binding; writing both would create a conflict. The namespace body looks like a [`delegate_components!`](/docs/reference/macros/delegate_components) table, but its choices apply to every context that joins the namespace. We use the full path because the inherited route already maps the bare component marker to that address. These defaults are fixed choices. Once the namespace binds a provider, a joining context or inheriting namespace cannot override it, even with a more specific entry. A context also cannot disable just one default while retaining the rest of that namespace. Choices that need to vary must stay on destinations the namespace leaves unbound. -There is also a constraint on where we write the registration. With a prefixed path, the binding must live in the crate that owns the namespace, here `DefaultAppComponents`. The path expands to CGP's `PathCons` type, and owning a component marker nested inside that type does not satisfy Rust's orphan rules. An unprefixed local component marker has different ownership rules, covered by the [`#[default_impl]` reference](/docs/reference/attributes/default_impl). +There is also a constraint on where we write the registration. With a prefixed path, the binding must live in the crate that owns the namespace, here `DefaultAppComponents`. The path expands to CGP's `PathCons` type, and owning a component marker nested inside that type does not satisfy Rust's [orphan rules](/docs/concepts/coherence). An unprefixed local component marker has different ownership rules, covered by the [`#[default_impl]` reference](/docs/reference/attributes/default_impl). ### Bind composite providers in the namespace body @@ -841,25 +834,19 @@ cgp_namespace! { } ``` -After we bind the remaining user and post providers in the same way, the application only needs to choose its filters. For this example, let `ContentFilterComponents` name the AI-backed filter bundle from earlier: - -```rust -type ContentFilterComponents = AiContentFilterComponents; -``` - -Our production wiring then becomes: +After we bind the remaining user and post providers in the same way, the application only needs to choose its filters. For this example, our production wiring then becomes: ```rust delegate_components! { ProductionApp { namespace DefaultAppComponents; - @app.extra.content_filter: ContentFilterComponents, + @app.extra.content_filter: AiContentFilterComponents, } } ``` -All the shared user and post choices come from `DefaultAppComponents`. We deliberately left the filter path unbound, so a test context can select `DummyContentFilterComponents` there instead. Both contexts still need component checks, including checks of the dependencies introduced by the defaults. +All the shared user and post choices come from `DefaultAppComponents`. We deliberately left the filter path unbound, so a test context can select `DummyContentFilterComponents` there instead. ### Choose how much wiring to share From 532d8932a1e10e0142625cf98e81505d6e78d060 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 1 Nov 2026 23:06:58 +0100 Subject: [PATCH 181/516] Clarify modular error handling with natural prose and examples Use a blanket parser trait to show interchangeable error policies, preserve parse errors in a domain enum, and illustrate wrapping during propagation. Explain conversion requirements and when ordinary error handling is sufficient. --- docs/concepts/modular-error-handling.md | 244 +++++++++++++++--------- 1 file changed, 154 insertions(+), 90 deletions(-) diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index a8795e30..c6ddfacc 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -5,79 +5,93 @@ sidebar_position: 10 # Modular error handling -CGP lets reusable fallible code use an error type chosen by its context. The context selects the -error type, how source errors become that type, and how additional detail is attached. This page -follows a port parser through those choices, then applies the pattern to application-specific errors -and explains its costs. +A port parser may serve several applications, each with its own way of reporting errors. One may +need a message to log, while another needs an enum its callers can match on. With CGP, the parser +can leave that choice to its context and use the same parsing logic in both applications. + +This page follows that parser from detecting a failure to constructing an error, then shows how +other code can attach detail as the error propagates. It also explains how applications can define +their own error-raising operations and where the extra abstraction is useful. ## Separating failure from error representation {#why-the-error-type-is-the-hard-one} -A reusable parser can detect a failure without deciding how every application should represent it. -One application may want a string, another a domain enum, and another an error-library type. Fixing -that choice inside the parser limits where the same implementation can be reused. +Ordinary Rust already offers ways to share parsing logic across applications. A parser can return +a concrete error for callers to convert, take a generic error parameter, or use an associated error +type. In each case, the application can choose how to represent a failure. -Ordinary Rust offers several ways to expose the choice. A function can return a concrete error for -callers to convert, take a generic error parameter, or use an associated error type. CGP combines a -shared associated type with interchangeable providers for constructing and enriching errors. +CGP builds on the associated-type approach by giving a context one shared error type. Operations +that use this type can propagate each other's errors directly. To produce an error in the first +place, reusable code asks the context to convert a source error into the shared type. Other code +can then ask it to attach detail, such as the path of a configuration file. -The built-in components separate these responsibilities: +These choices belong to separate built-in components: - **`HasErrorType`:** Names the context's shared `Error` type, which must implement `Debug`. - **`CanRaiseError`:** Converts a source error into that shared type. - **`CanWrapError`:** Attaches detail to an existing error. -A provider declares the raising and wrapping operations it needs. The context then selects -compatible implementations, so these choices can vary without changing the provider's source. +The context selects providers for these components through wiring. That lets it choose both the +error type and how to construct or enrich it. Reusable code only declares which raising and +wrapping operations it needs. ## A parser with an abstract error type -The parser names its return error abstractly and raises the concrete failures it encounters. -This fragment assumes `cgp::prelude::*` and `core::num::ParseIntError` are imported: +Consider a parser that reads an integer and checks whether it fits in a port number. Either step +can fail, so the parser needs to raise both an integer parse error and a message about an +out-of-range value: ```rust -#[cgp_component(PortParser)] -#[use_type(HasErrorType.Error)] -pub trait CanParsePort { - fn parse_port(&self, raw: &str) -> Result; -} +use cgp::prelude::*; +use core::num::ParseIntError; -#[cgp_impl(new ParsePortFromStr)] +#[cgp_fn(CanParsePort)] #[uses(CanRaiseError, CanRaiseError)] #[use_type(HasErrorType.Error)] -impl PortParser { - fn parse_port(&self, raw: &str) -> Result { - let parsed: u32 = raw.parse().map_err(Self::raise_error)?; - - if parsed > u16::MAX as u32 { - return Err(Self::raise_error(format!("port {parsed} out of range"))); - } +pub fn parse_port(&self, raw: &str) -> Result { + let parsed: u32 = raw.parse().map_err(Self::raise_error)?; - Ok(parsed as u16) + if parsed > u16::MAX as u32 { + return Err(Self::raise_error(format!("port {parsed} out of range"))); } + + Ok(parsed as u16) } ``` -`Error` is the context's [abstract type](./abstract-types.md), imported by `#[use_type]`. -`Self::raise_error` converts either a `ParseIntError` or a `String` into it. The `#[uses]` line -requires those conversions on the implementation; a caller bounded by `CanParsePort` needs only -the parser interface and its shared error type. +The parser names its return error as `Error`, the context's [abstract type](./abstract-types.md) +imported by `#[use_type]`. When a step fails, `Self::raise_error` converts the source into that type, +and ordinary Rust `Result` and `?` handle propagation. The raising method is an associated +function on the context type, so constructing an error does not require a context value. + +The parser still decides which failures to report. For example, `"abc"` produces a `ParseIntError`, +while `"65536"` parses as `u32` but exceeds `u16::MAX` and produces a string message. A number too +large for `u32` fails during parsing instead. Only the conversion of those failures into `Error` +is left to the context. -`raise_error` is an associated function called on the context type. Error construction therefore -uses the context's selected implementation without requiring a context value. +To make this implementation available, [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) generates a +`CanParsePort` trait and a blanket implementation for contexts that satisfy the dependencies in +`#[uses]`. Those raising requirements stay on the implementation. A generic caller can therefore +require `CanParsePort` and use its shared error type without repeating the conversion requirements. +There is only one parsing implementation here; a full component would also let contexts choose +among parsing providers. ## Selecting a strategy for each source -The context can route different source errors through different providers. This table assumes an -`App` context, the error component keys imported from `cgp::core::error`, and `RaiseFrom` and -`DebugError` imported from `cgp::extra::error`: +For an application that reports errors as strings, the context can select `String` and provide the +two conversions the parser needs. Here, `App` stands for the application and carries its +error-handling choices. The port text is passed to the method as an argument: ```rust +use cgp::core::error::{ErrorRaiserComponent, ErrorTypeProviderComponent}; +use cgp::extra::error::{DebugError, RaiseFrom}; + +pub struct App; + delegate_components! { App { open ErrorRaiserComponent; ErrorTypeProviderComponent: UseType, - PortParserComponent: ParsePortFromStr, @ErrorRaiserComponent.String: RaiseFrom, @ErrorRaiserComponent.ParseIntError: DebugError, @@ -85,59 +99,98 @@ delegate_components! { } ``` -`App` uses `String` as its error type. `RaiseFrom` converts a raised `String` through `From`, which -returns the same string here. `DebugError` formats a `ParseIntError` into a string, then calls the -context's `String` raiser. The formatting provider thus relies on the conversion selected by the -context instead of naming the final error type itself. +The `open ErrorRaiserComponent;` statement lets the table choose a provider for each source type. +A raised `String` goes to `RaiseFrom`, which uses `From` and returns the string unchanged. A +`ParseIntError` goes to `DebugError`, which formats it into a string and passes that string to the +same `RaiseFrom` provider. Both paths end in `String`, so `App` can use the parser. -Other providers express different policies. `DisplayError` uses `Display` formatting, -`ReturnError` accepts a source that already has the context's error type, and `RaiseInfallible` -handles `Infallible`. Per-source dispatch lets a context combine these strategies where needed. +This formatting step keeps the parse error's debug output but loses its structure. Callers receive +a message they can log, though they can no longer match on the original `ParseIntError`. If an +application needs that structure, its context can choose a conversion that preserves it. ## Changing the error type -The same parser can return a domain error when another context supplies compatible conversions. -In this fragment, `AppError` must implement `Debug` and `From`: +For example, another application may need to distinguish a parsing failure from a value that +passed parsing but exceeded `u16::MAX`. An error enum can keep the original parse error in one +variant and the range message in another: ```rust +#[derive(Debug)] +pub enum AppError { + InvalidNumber(ParseIntError), + InvalidPort(String), +} + +impl From for AppError { + fn from(error: ParseIntError) -> Self { + Self::InvalidNumber(error) + } +} + +impl From for AppError { + fn from(message: String) -> Self { + Self::InvalidPort(message) + } +} + +pub struct StrictApp; + delegate_components! { StrictApp { - open ErrorRaiserComponent; - ErrorTypeProviderComponent: UseType, - PortParserComponent: ParsePortFromStr, - - @ErrorRaiserComponent.String: RaiseFrom, - @ErrorRaiserComponent.ParseIntError: DebugError, + ErrorRaiserComponent: RaiseFrom, } } ``` -`ParsePortFromStr` can be reused unchanged because it never fixed its return error to `String`. -It still raises a `String` for an out-of-range port, and `RaiseFrom` now converts that message into -`AppError`. Rust checks and monomorphizes the provider for the new context as usual. +Because `AppError` implements `From` for both source types, `StrictApp` can send both to +`RaiseFrom` with a single wiring entry. Parsing `"abc"` now returns an `Err` containing +`AppError::InvalidNumber`, while parsing `"65536"` returns one containing `AppError::InvalidPort`. +A caller that knows this context can match on either variant. -Error-library backends package compatible type providers, raisers, and wrappers. For example, -`cgp-error-anyhow` supplies providers for `anyhow::Error`, while `cgp-error-eyre` supplies the -corresponding `eyre` integration. Choosing a backend keeps those concrete dependencies in the -application's wiring rather than in reusable providers. +The parser itself has not changed. It raises the same source values through the same operations, +but the context preserves them in a different return type. An application can also choose an +error-library backend, such as `cgp-error-anyhow` for `anyhow::Error` or `cgp-error-eyre` for `eyre`. +These optional crates package compatible type providers, raisers, and wrappers. The application +selects them in its wiring, while reusable code continues to use the shared error traits. ## Attaching detail as an error propagates -`CanWrapError` lets a provider enrich an error it did not construct. A caller might attach -the configuration path after a port parser fails. The provider declares the wrapping requirement -and calls `Self::wrap_error(error, detail)`; the context chooses how the detail is stored or formatted. +The parser knows which input failed, but a configuration loader may also know which file it came +from. When the parser returns an error, the loader can use `CanWrapError` to attach the +file path before passing the error to its caller: -Wrapping is separate from raising because a source error and propagation detail serve different -purposes. A source explains what failed, while detail can identify which request or resource was -involved. `DiscardDetail` can deliberately ignore that detail, and a backend wrapper can preserve it. -The parser above only raises errors, so its context does not need a wrapper until another provider -requires one. +```rust +#[cgp_fn(CanParseConfigPort)] +#[uses(CanParsePort, CanWrapError)] +#[use_type(HasErrorType.Error)] +pub fn parse_config_port(&self, raw: &str, path: &str) -> Result { + self.parse_port(raw).map_err(|error| { + Self::wrap_error(error, format!("invalid port in {path}")) + }) +} +``` + +Here, the parser's error already has the type the wrapper expects, because both operations use the +context's shared `Error`. The loader only needs to require `CanParsePort` and a wrapper for strings. +It does not repeat the parser's raising requirements, just as its own caller can require +`CanParseConfigPort` without repeating the loader's dependencies. + +Wrapping adds information to an error that has already been raised. How much of that information +survives depends on the selected provider: a backend wrapper can retain both the error and the file +path, while `DiscardDetail` returns the error unchanged. Neither `App` nor `StrictApp` selects a +wrapper yet. Each would need a compatible `ErrorWrapperComponent` entry to use this loader, even +though both already support the parser. ## An application's own error vocabulary -Application-specific components can express failures that need more structure than a message. -A service can define a raising operation that takes a status marker and detail: +Choosing behavior by source type works well when the type identifies the failure. In `StrictApp`, +for example, every raised `String` becomes `AppError::InvalidPort`. That suits a context where +strings only report port failures, but a web service may use strings to describe many unrelated +problems. It needs more information to choose the right error. + +An application-specific component can supply that information explicitly. For HTTP errors, it can +accept a status marker alongside the detail: ```rust #[cgp_component(HttpErrorRaiser)] @@ -147,43 +200,54 @@ pub trait CanRaiseHttpError { } ``` -Markers such as `ErrUnauthorized` and `ErrNotFound` identify domain failures. Providers map them to -status codes and construct the context's error. A handler requiring the appropriate -`CanRaiseHttpError` implementation can then call: +The status markers can be empty structs such as `ErrUnauthorized` and `ErrNotFound`. A provider +maps them to HTTP status codes and constructs the context's error, so a handler with the +corresponding `CanRaiseHttpError` dependency can write: ```rust -Self::raise_http_error(ErrUnauthorized, "you must first login") +Self::raise_http_error(ErrUnauthorized, "you must log in first") ``` -The handler names the failure and its detail. Its selected provider determines the numeric status -and concrete error representation, just as the built-in raiser determines how a parse error is stored. +The marker identifies the failure even though the detail is a string. As with the port parser, +the handler leaves the concrete error representation to its context; here, the selected provider +also determines the numeric HTTP status. ## What it costs -The selected error type must satisfy every chosen provider's requirements. A formatting route can -lose the original error's structure, and a `From` route requires a suitable conversion. Changing -the type may therefore require changing strategies as well as the type-setting entry. +Leaving error representation to the context moves the conversion choices into wiring. Those +choices still have to agree: the string context needs a provider that can format `ParseIntError`, +while the enum context needs `From` implementations for both sources. Changing the error type may +therefore mean changing the raising providers too. An enum cannot recover the original error if +a formatting provider has already reduced it to text. + +Rust verifies these requirements when they are needed. Calling `App.parse_port(...)` or asserting +`App: CanParsePort` checks the raising dependencies, while checking `CanParseConfigPort` also +checks the wrapper. For components, +[`check_components!`](/docs/reference/macros/check_components) verifies the selected providers +against their contexts. Until then, a context can name an error type while still lacking a +conversion it needs. -Missing raisers and wrappers can remain undetected until the relevant operation is checked or used. -Use [`check_components!`](/docs/reference/macros/check_components) to verify the parser and other -application components against their contexts. Naming an error type alone does not establish that -all required conversions exist. +Sharing the error type through `HasErrorType` lets operations compose, but it also gives each +context a single choice. An application that needs independent error types must use separate type +components or contexts. In either case, useful messages, preserved causes, and matchable variants +still depend on the application's error design. -`HasErrorType` selects one shared error type per context. That makes component errors compose, but -an application needing independent error types must model them with separate type components or -contexts. CGP also leaves error design to the application: useful messages, preserved causes, and -matchable variants depend on the chosen representations and providers. +For a parser that only needs one fixed error type, a concrete `Result` and ordinary conversions +may be enough. The additional traits and wiring are useful when the same parsing logic needs to +work with different error policies, as it does for `App` and `StrictApp`. ## Where to go next -These pages explain the supporting mechanisms and available strategies: +To use the same parser with your own error policy, start with the shared type and the conversions +it needs. These pages explain the supporting mechanisms and available providers: - [Abstract types](./abstract-types.md): How the context selects a shared type. - [Impl-side dependencies](./impl-side-dependencies.md): Why conversion requirements stay on the provider. - [Dispatching](./dispatching.md): Selecting providers by type. - [`HasErrorType`](/docs/reference/components/has_error_type) and - [`CanRaiseError` / `CanWrapError`](/docs/reference/components/can_raise_error): The error interfaces. + [`CanRaiseError`](/docs/reference/components/can_raise_error) / + [`CanWrapError`](/docs/reference/components/can_wrap_error): The error interfaces. - [Error providers](/docs/reference/providers/error): Strategies and their requirements. - [Comparison: Algebraic effects](/docs/comparisons/algebraic-effects): Why raising selects an interpretation while ordinary Rust control flow still propagates the error. From adafc74820da5bf896ec066121c0f05d5e275cc7 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 1 Nov 2026 23:16:29 +0100 Subject: [PATCH 182/516] Explain coherence through provider choices in natural prose Show text and hexadecimal providers encoding the same string before wiring selects a provider for ordinary method calls. Clarify the overlap and orphan rules while preserving the limits on wiring foreign types. --- docs/concepts/coherence.md | 234 +++++++++++++---------- example-code/tests/concepts/coherence.rs | 11 +- 2 files changed, 147 insertions(+), 98 deletions(-) diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 02fc9e9a..695b9c4a 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -5,28 +5,34 @@ sidebar_position: 1 # Bypassing coherence -Rust's coherence rules keep trait implementation selection unambiguous. CGP works within those rules -by giving alternative implementations separate provider types, then letting each context select one. -This page explains what coherence provides, why overlapping [blanket implementations](/docs/reference/glossary#blanket-implementation) are rejected, -and how the provider arrangement allows reuse without ambiguous calls. +A trait bound lets generic code request an implementation without asking its caller to pass one. +Rust's coherence rules make that possible by keeping the choice consistent across the program. +That consistency also limits which implementations can coexist: if several could apply to the +same type, Rust rejects them even when an application knows which behavior it wants. + +This page follows that trade-off from ordinary trait lookup to an encoding example with competing +implementations. It then shows how CGP gives those implementations separate provider types and +connects each value type to its chosen provider, before considering the costs of that arrangement. ## The trait system is already a dependency-injection mechanism -Rust resolves trait dependencies for generic code at compile time. A function can require an -implementation through a bound without asking its caller to pass that implementation explicitly: +Consider a function that formats a value. To request the formatting behavior it needs, the +function only has to name `Display` in a bound: ```rust +use core::fmt::{self, Display, Formatter}; + pub fn describe(value: &T) -> String { format!("{value}") } ``` -Calling `describe(&42)` makes the compiler resolve `i32: Display`. The caller supplies the value; -the type system determines which formatting implementation the function uses. This serves as a form -of dependency injection within ordinary Rust. +Calling `describe(&42)` supplies the value, while the compiler finds the `Display` implementation +for `i32`. The caller never names or passes that implementation. This is a form of dependency +injection already available in ordinary Rust. -Trait resolution also follows an implementation's dependencies. A pair can implement `Display` -whenever both of its fields implement it: +The selected implementation can have dependencies of its own. A pair, for example, can implement +`Display` by asking each of its fields to format itself: ```rust struct Pair(A, B); @@ -38,20 +44,25 @@ impl Display for Pair { } ``` -Calling `describe(&Pair("foo", 42u32))` requires `Pair<&str, u32>: Display`, which in turn requires -`&str: Display` and `u32: Display`. The caller need not list those transitive requirements separately. -If an implementation acquires another dependency, generic callers can retain their existing bounds, -provided the concrete types still satisfy the full chain. +When `describe(&Pair("foo", 42u32))` requires `Pair<&str, u32>: Display`, Rust finds the pair +implementation and follows its bounds to `&str: Display` and `u32: Display`. The `describe` +function still needs only `T: Display`, because the field requirements belong to the pair's +implementation. + +That separation keeps implementation details out of generic callers. An implementation can gain +a dependency while callers retain their existing bounds, provided the concrete types still +satisfy the full chain. ## That only works because every lookup finds the same answer -Coherence gives trait resolution a consistent answer across a program. For a given trait, including -its type arguments, and an implementing type, Rust permits at most one applicable implementation. -Generic code can therefore rely on the same implementation wherever it is called. +As Rust follows these dependencies, each lookup must have a consistent answer wherever it occurs +in the program. Coherence provides that guarantee: for a given trait, its type arguments, and an +implementing type, there can be at most one applicable implementation. -Rust enforces coherence through overlap and orphan rules. The **overlap rule** rejects implementations -that could apply to the same type. These blanket implementations each cover every type satisfying -their bound, so they conflict: +Rust enforces this partly through the **overlap rule**, which rejects implementations that could +apply to the same type. For example, an encoding trait might offer one +[blanket implementation](/docs/reference/glossary#blanket-implementation) for printable values +and another for values that expose bytes: ```rust pub trait CanEncode { @@ -69,13 +80,15 @@ impl> CanEncode for T { } ``` -`String` satisfies both bounds. Both implementations would apply to `String: CanEncode`, and Rust -does not let a call site select one of them. Each blanket implementation is valid alone; defining -both for the same trait causes the conflict. +Both bounds hold for `String`, so Rust would have two answers for `String: CanEncode`. Each +implementation is valid on its own, but a call site has no way to choose between them. The compiler +therefore rejects the pair. -The **orphan rule** restricts implementations involving foreign traits and types. For a trait without -type parameters, your crate must define either the trait or the implementing type. Neither `Display` -nor `Vec` belongs to this crate, so Rust rejects this implementation: +Overlap can also arise when unrelated crates define implementations independently. The +**orphan rule** prevents those crates from supplying conflicting implementations for the same +foreign trait and type. For a trait without type parameters, either the trait or the implementing +type must be local to the crate defining the implementation. Since both `Display` and `Vec` +come from the standard library, the following implementation is rejected: ```rust // error[E0117]: only traits defined in the current crate can be implemented @@ -85,45 +98,48 @@ impl Display for Vec { } ``` -This restriction prevents unrelated crates from independently defining conflicting implementations -for the same foreign trait and type. Traits with type parameters have additional cases involving a -local type in those parameters; the -[Rust Reference](https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules) -specifies the full rule. - -Together, these rules let crates compose without making implementation selection depend on which -crate asks. CGP retains that guarantee while changing how alternative implementations are represented. +A local type in a trait's parameters can allow further implementations under the orphan rule. +The [Rust Reference](https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules) +specifies those cases. Together, the orphan and overlap rules keep trait resolution consistent +as crates are combined into a program. ## What the guarantee costs -The overlap rule prevents the encoding trait from carrying both blanket implementations above. -Even if an application author knows which behavior each type should use, the trait system does not -provide a selection table for those conflicting implementations. Multiple blanket implementations -are allowed when Rust can establish that they do not overlap. +For `CanEncode`, keeping one answer means choosing which of the overlapping blanket +implementations to offer. Several blanket implementations can coexist when Rust can establish +that they do not overlap, but the bounds above do overlap. Knowing which behavior an application +wants for each type does not give the trait a way to record those choices. -A newtype provides an ordinary Rust way to choose a distinct implementation for a foreign type. -The wrapper is local, so it can implement a foreign trait such as `Display`. It also makes the -semantic distinction explicit. Its cost is that callers must use the wrapper, and operations on the -underlying type may need forwarding methods or trait implementations. +In ordinary Rust, a newtype can express a distinct choice by wrapping the value in a locally +defined type. That wrapper satisfies the orphan requirement for a foreign trait such as +`Display`, though its implementations must still avoid overlap. Its name can also make the +different behavior explicit. The cost is that callers must use the wrapper, and operations on +the underlying value may need forwarding methods or trait implementations. -Named helper types provide another way to represent implementation choices. Each helper implements -a trait parameterized by the data type, so the helpers can coexist. CGP uses this pattern and adds -wiring that connects a type's normal method calls to its chosen helper. +Another way to express the choice is to name each implementation with a helper type. Each helper +implements a trait parameterized by the data type, so several helpers can accept the same data. +CGP builds on this pattern and adds wiring that connects ordinary method calls to the chosen +helper. ## The move: make `Self` a type you own -CGP separates the caller's interface from the provider's implementation interface. The -**consumer trait** keeps the method callers use: +For encoding, the interface callers use can remain `CanEncode`. In CGP, this is the +**consumer trait**: ```rust +use cgp::prelude::*; + #[cgp_component(Encoder)] pub trait CanEncode { fn encode(&self) -> Vec; } ``` -`#[cgp_component]` also generates a **provider trait**, `Encoder`. The value being encoded -becomes its `Context` parameter, while each provider supplies a distinct implementing type: +The `#[cgp_component]` macro also generates a **provider trait**, `Encoder`. Moving the +value's type into the `Context` parameter leaves the implementing type available for a provider +struct. With a separate struct for each implementation, the original `Display` and `AsRef<[u8]>` +bounds can describe two providers. Here, the byte-based provider uses hexadecimal encoding, which +makes the difference between their outputs visible: ```rust #[cgp_impl(new EncodeAsText)] @@ -135,70 +151,96 @@ impl Encoder { #[cgp_impl(new EncodeAsHex)] #[uses(AsRef<[u8]>)] impl Encoder { - fn encode(&self) -> Vec { /* hex-encode self.as_ref() */ } + fn encode(&self) -> Vec { + self.as_ref() + .iter() + .flat_map(|byte| format!("{byte:02x}").into_bytes()) + .collect() + } } ``` -`EncodeAsText` and `EncodeAsHex` can both implement `Encoder` because their implementing -types differ. Their context requirements may overlap without the Rust implementations overlapping. -A crate can also implement a foreign provider trait for its own provider type, even when the context -comes from another crate. The generated implementations still satisfy Rust's coherence rules. +The `new` argument declares the `EncodeAsText` and `EncodeAsHex` structs. Inside `#[cgp_impl]`, +`&self` still refers to the value being encoded, and `#[uses(Display)]` requires that value's type +to implement `Display`. The macro turns the receiver into an explicit context argument in the +generated provider implementation. -`#[cgp_impl]` lets provider code retain a familiar `self` receiver. Within that macro's input, -`self` refers to the value being encoded, and `#[uses(Display)]` requires that value's type to -implement `Display`. The macro translates this into a provider implementation with an explicit -context parameter. +The resulting Rust implementations have different `Self` types: `EncodeAsText` implements +`Encoder` where `Context: Display`, while `EncodeAsHex` implements it where +`Context: AsRef<[u8]>`. A context can satisfy both bounds without making the implementations +overlap, because each is implemented for a different provider struct. -## Coherence comes back, one type at a time - -Each type selects one provider for the component through a wiring table: +Since `String` satisfies both bounds, both providers can encode the same value. Calling them +explicitly makes the two choices visible before wiring selects either one: ```rust -delegate_components! { String { EncoderComponent: EncodeAsText } } -delegate_components! { Vec { EncoderComponent: EncodeAsHex } } +let value = String::from("hi"); + +assert_eq!(>::encode(&value), b"hi"); +assert_eq!(>::encode(&value), b"6869"); ``` -`String` implements `CanEncode` through `EncodeAsText`, while `Vec` uses `EncodeAsHex`. -A call to `value.encode()` resolves to the provider selected for that value's type. Both providers -remain available, but each wired type has an unambiguous choice. +The provider struct also gives its crate a local implementing type. Because of that, the crate +can supply a provider even when both the trait and context type are defined elsewhere. Distinct +provider types avoid overlap, and local ownership satisfies the orphan rule, so the generated +code follows both coherence rules. -The component key's ownership still matters when wiring foreign types. Here `EncoderComponent` is -generated in the crate defining `CanEncode`, so that crate can wire it onto `String` and `Vec`. -A downstream crate cannot independently wire that foreign key onto those foreign types. This example -therefore makes one choice per value type across the program. +## Selecting one provider for each type {#coherence-comes-back-one-type-at-a-time} -CGP preserves coherence while making provider selection explicit. Alternative providers can apply -to the same context, and the wiring chooses which one supplies the consumer trait. Defining a second -conflicting entry for the same type and component remains an error. +Naming a provider at the call site makes the choice explicit, but ordinary `value.encode()` calls +still need a single implementation. A wiring table records that choice for each value type: -Separate [application contexts](/docs/reference/glossary#application-context) allow independent choices for the same data type. That arrangement -requires moving the data into a component parameter; [Modularity Hierarchy](./modularity-hierarchy.md) -explains when to use it and how it differs from the value-type wiring shown here. +```rust +delegate_components! { String { EncoderComponent: EncodeAsText } } +delegate_components! { Vec { EncoderComponent: EncodeAsHex } } +``` -## What it costs +With these entries, `value.encode()` uses `EncodeAsText` for a `String` and `EncodeAsHex` for a +`Vec`. The string `"hi"` therefore encodes as `b"hi"`, while the byte vector `b"hi".to_vec()` +encodes as `b"6869"`. Callers can use the `CanEncode` consumer trait and leave provider selection +to the wiring. -A component introduces more declarations than a plain trait: a provider trait, a [component marker](/docs/reference/glossary#component-marker), -and wiring for the types that use it. For a trait with one implementation, a plain trait or -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) may provide the required reuse without wiring. +Ownership determines which crate can record that choice. Here, `EncoderComponent` is generated +in the crate defining `CanEncode`, so that crate can wire it onto foreign types such as `String` +and `Vec`. A downstream crate cannot independently wire that foreign key onto those foreign +types, and a second conflicting entry for a type and component remains an error. The result is +one choice per value type across the program. -Provider selection belongs to CGP's component interface. It does not give an existing trait such as -`Ord` multiple implementations, nor change how standard collections select that trait's behavior. -Use ordinary traits when one consistent implementation per type expresses the intended contract. +Applications that need independent choices for the same data type can wire their own +[application contexts](/docs/reference/glossary#application-context), with the data passed as a +component parameter. [Modularity Hierarchy](./modularity-hierarchy.md) develops that arrangement +and explains when the additional choice is useful. -Explicit wiring adds configuration to read and maintain. In the tables above, each type needs an -entry naming its provider. Shared bundles and namespaces can reduce repetition, but they introduce -further places to inspect when tracing a choice. +## What it costs -Wiring checks are deferred until the trait is checked or used. A table can name a provider -whose requirements the context does not satisfy, and a later call can produce a verbose error. -[`check_components!`](/docs/reference/macros/check_components) verifies requirements beside the -wiring. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it -recognizes, and the tool does not yet reshape every class. -[Checking your wiring](./check-traits.md) shows the diagnostics and their limits. +Separating implementations adds declarations: a provider trait, a +[component marker](/docs/reference/glossary#component-marker), and wiring for the types that use +it. When a trait only needs one implementation, a plain trait or +[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) may provide enough reuse on its own. + +The wiring itself also needs to be read and maintained. In the example, every wired type needs +an entry naming its provider. Shared bundles and namespaces can reduce repetition, but +tracing a choice then means following it through those additional definitions. + +Recording the choice leaves another question open: whether the provider's requirements hold for +the context. Rust checks those requirements when the trait is checked or used, so a table can +compile even though a later call will fail. To check beside the wiring, use +[`check_components!`](/docs/reference/macros/check_components). If the check fails, +[`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, +though it does not yet reshape every class. [Checking your wiring](./check-traits.md) explains +those diagnostics and their limits. + +The choices also apply specifically to the component interface you define. They do not give an +existing trait such as `Ord` multiple implementations or change which ordering standard collections +use. Ordinary traits remain a good fit when one consistent implementation per type expresses the +intended contract. The provider split becomes useful when you need the combination illustrated +here: several reusable implementations and an explicit way to select one for normal method calls. ## Where to go next -Choose the next page according to whether you want to evaluate, understand, or use the arrangement: +To decide how much implementation choice your code needs, start with the modularity hierarchy. +From there, these pages explain the trait split in more detail, show it in use, and compare it +with related approaches: - [Modularity Hierarchy](./modularity-hierarchy.md): When a plain trait is enough and when further provider choices are useful. @@ -209,8 +251,8 @@ Choose the next page according to whether you want to evaluate, understand, or u [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), and [`delegate_components!`](/docs/reference/macros/delegate_components): The constructs used here. - [RustLab 2025 talk](/blog/rustlab-2025-coherence): A longer account of coherence and CGP's approach. -- [Comparison: Type classes](/docs/comparisons/type-classes): the same coherence trade seen from Haskell, Agda, and Lean. -- [Comparison: Rust's own proposals](/docs/comparisons/rust-language-proposals): what Rust itself has considered doing about its coherence rules. +- [Comparison: Type classes](/docs/comparisons/type-classes): How Haskell, Agda, and Lean handle coherence. +- [Comparison: Rust's own proposals](/docs/comparisons/rust-language-proposals): Changes Rust has considered for its coherence rules. --- diff --git a/example-code/tests/concepts/coherence.rs b/example-code/tests/concepts/coherence.rs index 57871310..e0c5cbe9 100644 --- a/example-code/tests/concepts/coherence.rs +++ b/example-code/tests/concepts/coherence.rs @@ -31,7 +31,7 @@ pub mod trait_system_as_dependency_injection { pub mod every_lookup_finds_the_same_answer {} /// ## The move: make `Self` a type you own -/// ## Coherence comes back, one type at a time +/// ## Selecting one provider for each type pub mod the_move { use core::fmt::Display; @@ -53,7 +53,6 @@ pub mod the_move { #[cgp_impl(new EncodeAsHex)] #[uses(AsRef<[u8]>)] impl Encoder { - // The page elides the hexadecimal encoding body. fn encode(&self) -> Vec { self.as_ref() .iter() @@ -75,6 +74,14 @@ pub mod the_move { check_components! { Vec { EncoderComponent } } } + #[test] + fn both_providers_accept_the_same_value() { + let value = String::from("hi"); + + assert_eq!(>::encode(&value), b"hi"); + assert_eq!(>::encode(&value), b"6869"); + } + #[test] fn each_value_type_selects_its_encoding() { assert_eq!("hi".to_owned().encode(), b"hi"); From fc3bdb808979375a52316e4e273f5057b12ce7a4 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 1 Nov 2026 23:33:37 +0100 Subject: [PATCH 183/516] Explain consumer and provider traits through the email example Clarify the generated call chain and the context meaning of Self. Retain provider bounds in the comparison, show a generic consumer, and align the expansion check with the generated supertrait. --- docs/concepts/consumer-and-provider-traits.md | 233 ++++++++++-------- .../concepts/consumer_and_provider_traits.rs | 34 +-- 2 files changed, 150 insertions(+), 117 deletions(-) diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index f1c136d3..ab228f38 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -5,19 +5,21 @@ sidebar_position: 2 # Consumer and provider traits -CGP separates the trait callers use from the trait providers implement. A **consumer trait** exposes -a set of methods on a context, while a **provider trait** lets reusable implementations supply those -methods. This page motivates the split, traces a method call through its wiring, and shows the -generated Rust before discussing the costs. +A production application may send email through SMTP, while a test application records messages +for inspection. Both can expose the same `send_email` method through an ordinary Rust trait. +As more application types need those behaviors, it becomes useful to share each implementation +while letting each application choose which one to use. -## What an ordinary Rust trait does, and where it stops +CGP supports that choice by separating the interface callers use from the interface reusable +implementations target. This page follows the email example through that split, traces a call +through the generated Rust, and shows how the macros connect the pieces. It closes with the +costs and limits of the arrangement. -An ordinary Rust trait connects a type to one implementation of its methods. A `T: Display` bound, -for example, lets the compiler select the formatting implementation for `T`. This is sufficient when -each type needs one implementation and you do not need to choose among reusable alternatives. +## What an ordinary Rust trait does, and where it stops -Separate application types can implement the same trait differently using ordinary Rust. -A production application might send email, while a test application records it: +An ordinary Rust trait already lets the two applications expose the same method with different +behavior. Each application type provides its own implementation of `CanSendEmail`, and callers +use the shared interface: ```rust use core::cell::RefCell; @@ -47,34 +49,34 @@ impl CanSendEmail for TestApp { } ``` -`App` and `TestApp` already provide different behavior without CGP. Each is a context representing -an application and carrying the data its implementation needs. The SMTP body is omitted here; -`TestApp` shows the recording behavior in full. +Here, `App` and `TestApp` are the contexts on which `send_email` operates. Each represents an +application and carries the data its implementation needs. The SMTP body is omitted, while the +test implementation records the recipient and message in a vector. -Overlapping [blanket implementations](/docs/reference/glossary#blanket-implementation) prevent those behaviors from being offered as interchangeable -trait implementations. If the SMTP implementation applies to every type with `HasSmtpConfig`, and -the recording implementation applies to every type with `HasRecordedEmails`, they conflict: +To share each behavior with other application types, it might seem natural to write a +[blanket implementation](/docs/reference/glossary#blanket-implementation). The SMTP implementation +could work for any type with `HasSmtpConfig`, and the recording implementation for any type with +`HasRecordedEmails`. Offering both, however, creates a conflict: ```rust impl CanSendEmail for T { /* over SMTP */ } impl CanSendEmail for T { /* record it */ } // error[E0119] ``` -A type could satisfy both bounds, so Rust rejects the pair. The bodies can still be shared through -helper functions or other composition techniques, but each application must connect its trait -implementation to the chosen behavior. CGP provides a reusable provider interface and wiring for -that choice. +A type could satisfy both bounds, leaving Rust with two implementations of `CanSendEmail` for +that type. The compiler therefore rejects the pair. Helper functions and other composition +techniques can still share the code, with each application connecting its trait implementation +to the behavior it wants. CGP makes that connection through a separate trait for reusable +implementations and a wiring table that selects one. ## Splitting one trait in two -CGP gives callers and implementers separate trait interfaces: +The **consumer trait** keeps the caller's interface, including the original methods and receiver. +The **provider trait** moves the consumer's `Self` into a `Context` parameter. Its methods receive +the context as an explicit argument, leaving the implementing type free to name the behavior. -- The **consumer trait** keeps the original methods, so callers use `app.send_email(..)`. -- The **provider trait** moves the consumer's `Self` into an explicit `Context` parameter and - replaces the receiver with a context argument. - -The simplified pair for email sending looks like this. The provider's generated checking bound is -omitted here and explained below: +The signatures below show the split. They omit a generated checking bound on the provider trait, +which the call trace explains later: ```rust // what callers use @@ -88,55 +90,60 @@ pub trait EmailSender { } ``` -The provider trait lets a named implementation supply behavior for a context. Each implementation -uses its own marker type in the `Self` position: +The implementations can now keep their original context bounds while using separate marker +structs as `Self`. With the method bodies omitted, their declarations look like this: ```rust -impl EmailSender for SendViaSmtp { /* ... */ } -impl EmailSender for RecordEmails { /* ... */ } +pub struct SendViaSmtp; +pub struct RecordEmails; + +impl EmailSender for SendViaSmtp { /* ... */ } +impl EmailSender for RecordEmails { /* ... */ } ``` -The implementations have distinct `Self` types, so they can accept the same contexts without -conflicting with one another. Owning the provider type also lets a crate implement a provider trait -from another crate. These are ordinary coherent Rust implementations; -[Bypassing coherence](./coherence.md) explains the rules behind the arrangement. +Even if a context satisfies both `HasSmtpConfig` and `HasRecordedEmails`, these implementations +have different `Self` types and can coexist. Each local provider struct also lets its crate +implement a provider trait defined elsewhere. The split therefore follows ordinary Rust coherence +rules, as [Bypassing coherence](./coherence.md) explains. -A component can contain several methods, associated types, and constants. The single-method example -keeps the split visible; it is not a restriction imposed by CGP. Group items when one provider choice -should determine their implementation. +The same split applies to a component with several methods, associated types, or constants. Those +items can stay together when one provider choice should determine their implementation; this +example uses a single method to make the relationship easier to see. ## A provider is a name, not a value -A provider such as `SendViaSmtp` or `RecordEmails` is a zero-sized type used to name an implementation. -CGP does not construct a provider value or store state in it. The context supplies the values the -implementation needs. +The structs `SendViaSmtp` and `RecordEmails` serve as names for implementations. They are +zero-sized, and CGP neither constructs values of them nor stores application data in them. +That data stays in the context, while explicit method arguments supply inputs such as the +recipient and message body. -Within [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), `self` and `Self` refer to the context. -The macro rewrites them into the explicit context argument and type parameter shown above. -In a raw Rust provider implementation, `Self` instead has its ordinary meaning: the provider type -following `for`. +Because the state belongs to the context, it helps to distinguish the two meanings of `Self` +when reading provider code. In [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), the method's +`self` receiver refers to the context, and the macro rewrites references to `Self` to the context +type. The provider's own associated types and constants retain their provider meaning. In a raw +Rust provider implementation, `Self` simply names the provider type following `for`. ## How a call finds its provider -A context's wiring selects a provider for each component, much like a settings table whose keys and -values are types. The compiler resolves this table at compile time: +With the behaviors defined, each application needs to choose which provider supplies its +`send_email` method. Wiring records that choice in a table of types that the compiler resolves: ```rust delegate_components! { App { EmailSenderComponent: SendViaSmtp } } delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } ``` -`EmailSenderComponent` is the generated marker used as the key. A **component** groups the consumer -trait, provider trait, and that marker. The wiring maps its key to `SendViaSmtp` for `App` and to -`RecordEmails` for `TestApp`. +The key in both tables is `EmailSenderComponent`, a marker generated alongside the two traits. +Those traits, the marker, and the forwarding implementations form the **component**. The entry +for this key selects `SendViaSmtp` on `App` and `RecordEmails` on `TestApp`. -A method call follows the selected entry. For `app.send_email("a@b.c", "hi")`, the compiler resolves -`App`'s email-sending trait through its table to `SendViaSmtp`, then checks that provider's -requirements against `App`. The call uses static dispatch; the compiled program does not need a -runtime wiring table or provider lookup. +When a caller writes `app.send_email("a@b.c", "hi")`, the compiler follows `App`'s selection to +`SendViaSmtp` and checks whether that provider can work with `App`. This is static dispatch, +so the running program needs neither a wiring table nor a provider lookup. -The generated consumer implementation connects method syntax to the provider interface. Any context -that implements the provider trait for itself gets the consumer trait: +To see how method syntax reaches that selection, consider the two generated blanket +implementations. The consumer implementation supplies `CanSendEmail` whenever the context +implements `EmailSender` for itself: ```rust impl CanSendEmail for Context @@ -149,8 +156,9 @@ where } ``` -The generated delegation implementation then connects a table entry to its selected provider. -`DelegateComponent` represents that entry, and its `Delegate` associated type names the provider: +Satisfying `Context: EmailSender` takes us to the second implementation. It gives a +delegating type the provider trait of the type selected by its table. Here, `DelegateComponent` +represents the table entry, and its `Delegate` associated type names the selected provider: ```rust impl EmailSender for Provider @@ -165,26 +173,30 @@ where } ``` -Together, these implementations resolve `App: CanSendEmail` through `App: EmailSender` to -`SendViaSmtp: EmailSender`. The context remains `App` throughout, so the final provider receives -the application value on which the caller invoked the method. - -[`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for) carries the provider's dependency -bounds for checking. The provider macros generate an implementation with those bounds, and the -provider trait also requires it as a [supertrait](/docs/reference/glossary#supertrait). Explicit component checks use this path to expose -missing requirements that a consumer-trait error can hide. - -The listings simplify generated names for readability. Actual expansions use `__Context__` and -`__Provider__`, and spell the delegate as -`<__Provider__ as DelegateComponent>::Delegate`. The earlier simplified -`EmailSender` declaration also omitted its `IsProviderFor` supertrait. `cargo cgp expand` shows the -full expansion for a concrete example. +For the call on `App`, both `Context` and `Provider` initially stand for `App`. In this +implementation, `Provider` names the type whose table is consulted, so its `Delegate` is +`SendViaSmtp`. As long as `SendViaSmtp` implements `EmailSender`, the delegation gives `App` +its own `EmailSender` implementation, which in turn supplies `CanSendEmail` through the first +blanket implementation. The context stays `App` throughout, so the final provider receives the +same application value on which the caller invoked the method. + +The other bound, [`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for), helps check +that the provider's dependencies hold. Provider macros generate an implementation of this trait +with the provider's bounds, and the provider trait requires it as a +[supertrait](/docs/reference/glossary#supertrait). This is the checking bound omitted from the +earlier `EmailSender` declaration. Explicit component checks use it to expose missing +requirements that a consumer-trait error can hide. + +The listings use shorter names to keep this connection readable. In an actual expansion, the +parameters are `__Context__` and `__Provider__`, and the delegate is spelled as +`<__Provider__ as DelegateComponent>::Delegate`. You can inspect the full +expansion of a concrete component with [`cargo cgp expand`](/docs/cargo-cgp/expand). ## Writing it -The macros generate the trait pair and forwarding implementations from a consumer trait definition. -`#[cgp_component]` creates the component, and `#[cgp_impl]` defines each provider using context-style -method syntax: +The macros generate these connections while letting you write methods from the context's point +of view. `#[cgp_component]` produces the trait pair and forwarding implementations, and +`#[cgp_impl]` lets each provider keep a familiar receiver. For the email example, that gives: ```rust use cgp::prelude::*; @@ -224,41 +236,60 @@ delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } ``` Each `#[implicit]` argument reads a same-named field exposed by the context's `HasField` derive. -The macro removes these arguments from the public signature, so callers still write -`app.send_email(to, body)`. The SMTP body remains a placeholder; the recording provider stores the -message in the test application's vector. +The macro turns it into a local binding and removes it from the public signature, so callers +still write `app.send_email(to, body)`. The SMTP body is still a placeholder; the recording +provider stores the message in the test application's vector. + +The fields differ between providers: `SendViaSmtp` needs `smtp_server`, while `RecordEmails` needs +`sent_emails`. Because these are [impl-side dependencies](./impl-side-dependencies.md), neither +requirement appears in `CanSendEmail`. A caller can therefore use the selected behavior with +that trait bound alone: + +```rust +pub fn send_welcome(app: &impl CanSendEmail, to: &str) { + app.send_email(to, "Welcome!"); +} + +let test_app = TestApp { + sent_emails: RefCell::new(Vec::new()), +}; +send_welcome(&test_app, "a@b.c"); + +assert_eq!(test_app.sent_emails.borrow().as_slice(), ["a@b.c: Welcome!"]); +``` -Each provider declares only the fields it needs. `SendViaSmtp` requires `smtp_server`, while -`RecordEmails` requires `sent_emails`; neither requirement appears in `CanSendEmail`. -These are [impl-side dependencies](./impl-side-dependencies.md), which let implementations have -different requirements without changing the caller's interface. +The same `send_welcome` function accepts `App` as well as `TestApp`. Its bound names only +`CanSendEmail`, so each application's wiring supplies the behavior without the function knowing +the provider or its fields. -A context can also implement the consumer trait directly, using the ordinary Rust form shown at -the start of the page. For that trait it can omit providers and wiring. This allows adoption -one trait at a time, subject to Rust's usual restriction against conflicting implementations. +Because the consumer trait is still an ordinary Rust trait, a context can also implement it +directly and omit providers and wiring, as at the start of the page. This lets an application +adopt components one trait at a time. For a given context, however, a direct implementation would +overlap with a usable wired implementation of the same consumer trait, so it cannot have both. ## What it costs -A component adds declarations and wiring beyond a plain trait. For a trait with one -implementation, use a plain trait or consider [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), which -creates a blanket-implemented trait from a function without component wiring. +For an operation with one implementation, the trait pair and wiring may add more machinery than +you need. Use a plain trait or consider [`#[cgp_fn]`](/docs/reference/macros/cgp_fn), which generates +a trait and blanket implementation from a function without component wiring. -Wiring does not immediately verify the selected provider's requirements. A missing entry or -unsatisfied dependency can remain undetected until a caller needs the trait. -[`check_components!`](/docs/reference/macros/check_components) verifies the requirements where you -place the check, usually beside the table. +When you do use wiring, the compiler checks whether it supplies a usable implementation once +code requires the trait. Until then, a missing entry or unsatisfied provider dependency may remain +undetected. [`check_components!`](/docs/reference/macros/check_components) brings those checks to +a place you choose, usually beside the table. If one fails, [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the classes it recognizes, -and the tool does not yet reshape every class. -[Checking your wiring](./check-traits.md) shows what to expect with and without those tools. +though it does not yet reshape every class. [Checking your wiring](./check-traits.md) explains +those diagnostics and their limits. -Tracing a method call requires following the wiring to its provider. Static dispatch avoids runtime -lookup costs, but a reader still has to find the table entry and the implementation it names. -The separation pays for itself when those implementations are reused or selected differently across -contexts. +Even with static dispatch, a reader tracing the call has to find the table entry and follow it +to the provider. The split is useful when it lets several contexts reuse a provider or select +different behaviors while a caller such as `send_welcome` keeps the same interface. ## Where to go next -These pages develop the trait model and show how to use it: +To apply the same separation in your own code, consider the dependencies each provider needs +and the choices each context must make. These pages develop those ideas and show the component +model in practice: - [Bypassing coherence](./coherence.md): Why distinct provider types permit reusable alternatives. - [Impl-side dependencies](./impl-side-dependencies.md): How a provider states requirements without @@ -268,8 +299,8 @@ These pages develop the trait model and show how to use it: - [`#[cgp_component]`](/docs/reference/macros/cgp_component), [`#[cgp_impl]`](/docs/reference/macros/cgp_impl), and [`delegate_components!`](/docs/reference/macros/delegate_components): Exact syntax and generated code. -- [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch): the wiring table read as a vtable that exists only at compile time. -- [Comparison: Policy-based design](/docs/comparisons/policy-based-design): the same split in C++ policy classes and host templates. +- [Comparison: Dynamic dispatch](/docs/comparisons/dynamic-dispatch): How compile-time wiring compares with a runtime vtable. +- [Comparison: Policy-based design](/docs/comparisons/policy-based-design): The corresponding split in C++ policy classes and host templates. --- diff --git a/example-code/tests/concepts/consumer_and_provider_traits.rs b/example-code/tests/concepts/consumer_and_provider_traits.rs index ecd03b53..b01fb394 100644 --- a/example-code/tests/concepts/consumer_and_provider_traits.rs +++ b/example-code/tests/concepts/consumer_and_provider_traits.rs @@ -1,9 +1,8 @@ //! Code from `docs/concepts/consumer-and-provider-traits.md` — *Consumer and provider traits*. //! -//! Module names follow the page's headings. Code the page **rejects** is carried as a -//! `compile_fail` doctest, and the two listings the page presents as *generated* code are rebuilt by -//! hand in [`how_a_call_finds_its_provider`], which is a weaker check than it looks — see the note -//! there. +//! Module names follow the page's headings. Rejected code lives in trybuild fixtures. The two +//! generated-code listings are assembled by hand in [`how_a_call_finds_its_provider`]; that checks +//! their structure, while macro expansion establishes what the library generates. /// ## What an ordinary Rust trait does, and where it stops /// @@ -59,15 +58,17 @@ pub mod splitting_one_trait_in_two { fn send_email(context: &Context, to: &str, body: &str); } - // The page names these two providers without declaring them. + pub trait HasSmtpConfig {} + pub trait HasRecordedEmails {} + pub struct SendViaSmtp; pub struct RecordEmails; - impl EmailSender for SendViaSmtp { + impl EmailSender for SendViaSmtp { fn send_email(context: &Context, to: &str, body: &str) {} } - impl EmailSender for RecordEmails { + impl EmailSender for RecordEmails { fn send_email(context: &Context, to: &str, body: &str) {} } } @@ -91,7 +92,7 @@ pub mod how_a_call_finds_its_provider { fn send_email(&self, to: &str, body: &str); } - pub trait EmailSender { + pub trait EmailSender: IsProviderFor { fn send_email(context: &Context, to: &str, body: &str); } @@ -109,9 +110,7 @@ pub mod how_a_call_finds_its_provider { fn send_email(context: &Context, to: &str, body: &str) {} } - // Generated for every provider, and not shown on the page, which says only that it is - // "generated, never written by hand". Without it the provider blanket impl below has an - // unsatisfiable bound. + // Provider macros generate these checking implementations with the provider's bounds. impl IsProviderFor for SendViaSmtp {} impl IsProviderFor for RecordEmails {} @@ -208,15 +207,18 @@ pub mod writing_it { check_components! { TestApp { EmailSenderComponent } } } - /// The page's claim that the implicit arguments leave the public signature alone, so - /// `app.send_email(to, body)` still takes two arguments. + pub fn send_welcome(app: &impl CanSendEmail, to: &str) { + app.send_email(to, "Welcome!"); + } + + /// A generic caller needs only the consumer trait, while the selected provider reads its field. #[test] - fn each_provider_reads_a_different_field_and_neither_reaches_the_signature() { + fn generic_caller_uses_the_selected_recording_provider() { let test_app = TestApp { sent_emails: RefCell::new(Vec::new()), }; - test_app.send_email("a@b.c", "hi"); + send_welcome(&test_app, "a@b.c"); - assert_eq!(test_app.sent_emails.borrow().as_slice(), ["a@b.c: hi"]); + assert_eq!(test_app.sent_emails.borrow().as_slice(), ["a@b.c: Welcome!"]); } } From 9a653be1df2780428b04ceaa5ee9d284df68f063 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 1 Nov 2026 23:45:37 +0100 Subject: [PATCH 184/516] Clarify impl-side dependencies and public type requirements Explain which requirements stay on implementations and which callers still need. Show a generic caller using the shared error type, preserve section anchors, and align compiled examples with the explanation. --- docs/concepts/impl-side-dependencies.md | 217 ++++++++++-------- .../tests/concepts/impl_side_dependencies.rs | 32 +-- 2 files changed, 146 insertions(+), 103 deletions(-) diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index 6fa9b44c..91a4b0a9 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -5,15 +5,19 @@ sidebar_position: 3 # Impl-side dependencies -An **impl-side dependency** is a requirement stated on an implementation without being part of its -trait interface. Callers can require the trait they use while the compiler checks the selected -implementation's dependencies. This page starts with ordinary Rust [blanket implementations](/docs/reference/glossary#blanket-implementation), then -shows how CGP providers require traits, field values, and context-selected types. +Building a greeting from a name requires access to that name. A caller that only wants the +resulting greeting, however, may have no reason to retrieve the name itself. Keeping that +requirement on the implementation lets the caller depend on the greeting operation alone. +Such a requirement, present on an implementation but absent from its trait interface, is an +**impl-side dependency**. + +This page develops that separation with ordinary Rust functions and blanket implementations, +then applies it to CGP providers. The examples move from trait requirements to field values and +type choices, including the types that must remain visible in the public interface. ## What a `where` clause costs the callers above it -A generic function exposes its requirements through its signature. This greeting function needs -`HasName` to obtain the name it formats: +A generic greeting function can obtain a name through a `HasName` bound on the context: ```rust pub trait HasName { @@ -28,8 +32,8 @@ where } ``` -A generic caller must establish that requirement too. If it has nothing else that implies -`HasName`, it can add the same bound: +Calling this function from generic code means establishing `HasName` there too. If another bound +does not already imply it, the caller can repeat the requirement: ```rust pub fn greet_twice(context: &Context) -> String @@ -40,15 +44,16 @@ where } ``` -`greet_twice` does not read the name itself, but its calls to `greet` require the bound. -Further generic callers must also supply or imply it. Adding a dependency to `greet` can therefore -require changes to callers that only forward the call. This is straightforward for a small API; -it becomes harder to maintain when many layers repeat implementation-specific requirements. +The calls to `greet` are why `greet_twice` needs `HasName`, even though it never reads the name +itself. Further generic callers must supply or imply the same bound. If `greet` gains another +dependency, those forwarding layers may need new bounds as well. Repeating them is straightforward +in a small API, but maintaining them becomes harder as the chain grows. ## Moving the requirement onto the implementation -A blanket implementation lets callers depend on a trait without naming the dependencies used -to implement it. The trait declares the operation, and the implementation states when it is available: +A trait gives the caller a way to request the greeting operation itself. Its +[blanket implementation](/docs/reference/glossary#blanket-implementation) can supply that operation +for contexts that provide a name: ```rust pub trait CanGreet { @@ -65,9 +70,8 @@ where } ``` -`CanGreet` promises a greeting method without requiring `HasName` as a [supertrait](/docs/reference/glossary#supertrait). The blanket -implementation supplies that method for every context implementing `HasName`. A generic caller -can require only the greeting trait: +Here, the `HasName` bound belongs to the implementation. Since `CanGreet` does not require it as a +[supertrait](/docs/reference/glossary#supertrait), the caller can ask for `CanGreet` alone: ```rust pub fn greet_twice(context: &Context) -> String @@ -78,26 +82,29 @@ where } ``` -The compiler still checks `HasName` when it uses that blanket implementation to establish -`Context: CanGreet` for a concrete type. The requirement remains necessary for the implementation; -it is absent from the caller's trait contract. That separation is the impl-side dependency. +When a concrete type uses this blanket implementation, the compiler still checks `HasName`. +That check makes `CanGreet` available for the type, but the implication only runs one way: a caller +bounded by `CanGreet` cannot use `name()` through that bound. If it needs the name too, it must +establish `HasName` as well. -Keeping the interface stable can protect generic callers from implementation changes. If greeting -later needs another dependency, the blanket implementation can add a bound while `greet_twice` -continues to require only `CanGreet`. Concrete contexts must still satisfy the new requirement, -so this does not make every dependency change backward-compatible. +Keeping the requirement on the implementation also limits how far a change must reach. If the +greeting later needs another dependency, its implementation can add a bound while `greet_twice` +keeps `Context: CanGreet`. The concrete contexts must satisfy the new bound, so some may stop +compiling even though the generic caller's signature stays the same. -Ordinary Rust already supports this technique. CGP adds separate provider types and wiring when -several implementations need to coexist, including implementations whose context requirements overlap. -[Consumer and provider traits](./consumer-and-provider-traits.md) explains that extension. +This separation already works in ordinary Rust. CGP extends it with separate provider types and +wiring when several implementations need to coexist, including ones with overlapping context +bounds. [Consumer and provider traits](./consumer-and-provider-traits.md) explains that extension. ## Two providers, two sets of requirements, one interface -Each CGP provider can require different traits of the context while implementing the same interface. -An email sender might need an SMTP server getter, while a test implementation needs access to a -recording buffer: +For email sending, the useful requirements depend on how the message is handled. An SMTP provider +needs a server address, while a recording provider needs a buffer. Each can request its own getter +without adding that requirement to the shared interface: ```rust +use cgp::prelude::*; + #[cgp_component(EmailSender)] pub trait CanSendEmail { fn send_email(&self, to: &str, body: &str); @@ -120,13 +127,13 @@ impl EmailSender { } ``` -`#[uses(HasSmtpServer)]` adds a context bound to `SendViaSmtp`'s implementation. -`#[uses(HasSentEmails)]` adds a different bound to `RecordEmails`. Here `HasSmtpServer` supplies -`smtp_server()`, and `HasSentEmails` supplies `sent_emails()` as a reference to a mutable recording -buffer. The SMTP body is omitted; the recording body stores each message in that buffer. +Each `#[uses]` attribute adds a context bound to its provider's implementation. The bound +`HasSmtpServer` supplies `smtp_server() -> &str`, while `HasSentEmails` supplies +`sent_emails() -> &RefCell>`. The SMTP body is omitted here, and the recording body +shows how it stores a message in the buffer. -`CanSendEmail` exposes neither dependency. A caller needs only that trait, regardless of which -provider supplies it: +Those getter requirements stay with the providers, so a caller can use either behavior through +`CanSendEmail` alone: ```rust pub fn notify(context: &Context) @@ -138,25 +145,33 @@ where ``` A production `App` can select `SendViaSmtp`, while a `TestApp` selects `RecordEmails`. These contexts -represent applications and supply their chosen provider's dependencies. `notify` accepts either -context through the same bound; the test context does not need an SMTP server merely because -another provider uses one. +represent applications, and each supplies the dependencies of its chosen provider. That lets +`notify` accept both with the same bound. Since the test context selects the recording provider, +it only needs the buffer and has no need for an SMTP server. -## The three things an implementation can ask for +## Traits, values, and types {#the-three-things-an-implementation-can-ask-for} -Provider dependencies commonly describe traits, values, or types. CGP expresses them with -attributes that generate the corresponding Rust bounds: +The email providers ask the context for behavior through getter traits. Other implementations +may need a field value or a type choice. CGP expresses these dependencies with attributes that +generate ordinary Rust bounds: - **Traits:** `#[uses(Trait)]` requires the context to implement a trait. It accepts ordinary Rust traits such as `AsRef<[u8]>` as well as CGP consumer traits. - **Values:** An `#[implicit]` argument reads a field from the context and generates the field-access requirement on the implementation. - **Types:** `#[use_type(Trait.Type)]` names an associated type chosen by the context and adds the - bound needed to use it. Whether that bound belongs in the interface depends on where the type appears. + bound needed to use it. A type used in a public signature also needs to be available through + the interface. -An implicit argument lets the implementation ask for a value without adding a public method argument: +For the greeting example, an implicit argument can request the name value directly from the +context while keeping it out of the public method signature: ```rust +#[cgp_component(Greeter)] +pub trait CanGreet { + fn greet(&self) -> String; +} + #[cgp_impl(new GreetByName)] impl Greeter { fn greet(&self, #[implicit] name: &str) -> String { @@ -165,16 +180,17 @@ impl Greeter { } ``` -`GreetByName` reads `name` through the context's field-access implementation. The macro removes the -implicit argument from the method signature, so callers still use `greet()` without passing a name. -[Implicit arguments](./implicit-arguments.md) explains how field names, types, and borrowing determine -that generated requirement. +The macro turns `name` into a field-access requirement on `GreetByName`'s implementation and a +local binding in its body. It removes the argument from the public signature, so callers still +use `greet()` without supplying a name. The compiler checks that the context supports the access; +the value is read when the method runs. [Implicit arguments](./implicit-arguments.md) explains +how the field name, type, and borrowing determine that requirement. -## Type dependencies, and why they need no parameter +## Keeping type choices on the context {#type-dependencies-and-why-they-need-no-parameter} -Associated types let a context collect type choices that would otherwise be separate generic -parameters. A job runner, for example, might leave its error type, runtime, and storage backend -open. A function interface can expose those choices directly; with its body omitted, it looks like this: +A context can supply types as well as values. To see how that changes an interface, consider a +job runner that accepts a runtime and a storage backend, with a generic error type chosen by its +caller. With the execution body omitted, its signature looks like this: ```rust pub fn run_job(store: &S, runtime: &R) -> Result<(), E> @@ -183,17 +199,17 @@ where R: Runtime, S: Store, { - // This layer touches none of the three. + /* job execution omitted */ } ``` -A generic forwarding function may need to carry `E`, `R`, and `S` and establish the same bounds. -Concrete callers can often infer or fix these types, so the declarations do not necessarily spread -to every caller. The maintenance problem arises where intermediate generic layers must preserve -choices they do not otherwise use. +A generic forwarding function may need to carry `E`, `R`, and `S` and establish their bounds even +if it only passes the values to `run_job`. Concrete callers can often infer or fix these types, +so the declarations do not necessarily spread to every caller. The maintenance work arises in +generic layers that must preserve choices they do not otherwise use. -A context-based interface can expose the operation while letting the context determine its error -type. `HasErrorType` supplies an associated `Error`, which the component imports into its signature: +Putting the error choice on the context changes what those layers need to name. The associated +type `HasErrorType::Error` lets a component describe its result without a separate `E` parameter: ```rust #[cgp_component(JobRunner)] @@ -203,12 +219,12 @@ pub trait CanRunJob { } ``` -`CanRunJob` now has a `HasErrorType` supertrait because its return type names `Error`. -This type dependency is part of the interface, not hidden on the implementation. The runtime and -storage requirements can remain on the job provider if its public methods do not expose their types. +Here, `#[use_type]` imports `Error` into the signature and adds `HasErrorType` as a supertrait of +`CanRunJob`. Because callers receive values of that type, this dependency remains part of the +interface. Runtime and storage requirements can stay on the job provider as long as its public +methods do not expose their types. -A forwarding trait can use that same associated error without introducing a separate `E` -parameter: +An operation that forwards to `run_job` can share that associated error: ```rust #[cgp_fn] @@ -220,40 +236,61 @@ pub fn run_jobs(&self) -> Result<(), Error> { } ``` -`run_jobs` still declares the requirements it uses: `CanRunJob` for calling the job and `HasErrorType` -for naming its result. The `#[use_type]` attribute lets it write `Error` instead of a qualified -associated-type projection. The context determines the concrete error type shared by both operations. +The generated `RunJobs` trait exposes this forwarding operation. Its blanket implementation +requires `CanRunJob` to make the calls, while `#[use_type]` adds `HasErrorType` to both the trait +and the implementation so they can name the result. Code above this layer can use `RunJobs` alone: + +```rust +pub fn run_batch(context: &Context) -> Result<(), Context::Error> +where + Context: RunJobs, +{ + context.run_jobs() +} +``` + +The `RunJobs` bound implies `HasErrorType`, so `run_batch` can name `Context::Error` without another +bound or a separate error parameter. It needs neither `CanRunJob` nor the job provider's runtime +and storage requirements in its signature. Those requirements still have to be satisfied by the +concrete context and its selected provider before the caller can use it. + +The shared error also means one error choice per context. If a caller needs a different result +error, it can convert at the boundary or use another context. By comparison, the earlier generic +`E` parameter leaves that choice open at each call. -A type used only inside a provider can remain an impl-side dependency. A type appearing in a public -argument or result must be available through the interface. Associated types reduce separate type -parameters and tie related choices to the context; they do not eliminate all type dependencies from -signatures. [Abstract types](./abstract-types.md) explains that choice and its limits. +Associated types reduce the separate parameters that callers carry, but types used in public +arguments and results must still be available through the interface. A type used only inside a +provider can remain an impl-side dependency. [Abstract types](./abstract-types.md) develops +that distinction. ## What it costs -The trait interface does not tell a context author everything a selected provider needs. -To assemble a context, follow its wiring to the provider and inspect that provider's requirements. -The smaller caller contract comes with more work when configuring an implementation. +The caller's smaller interface leaves more for the context author to establish. Assembling a +context means following its wiring to the chosen provider and inspecting the dependencies there, +because the trait alone does not describe everything that implementation needs. -Wiring alone does not verify that the context satisfies the provider's dependencies. A missing -trait or field can remain undetected until a check or use requires it. Changing a provider's -bounds can also make an existing context stop compiling even if the consumer trait is unchanged. +Recording the wiring also leaves its requirements to be checked when the trait is used or +explicitly checked. A missing trait or field can remain undetected until then. If a provider gains +a new bound, an existing context may stop compiling even though the consumer trait stays the same. -Errors may refer to generated bounds rather than the requirement as written in the provider. -A missing implicit field, for example, can appear as an unsatisfied `HasField` bound with a -nested type-level field name. [`check_components!`](/docs/reference/macros/check_components) -checks selected components where you place it, usually beside the wiring, and helps expose the -missing dependency. [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause for the -classes it recognizes, and the tool does not yet reshape every class. [Checking your wiring](./check-traits.md) shows the diagnostics and their limits. +The resulting errors can describe generated bounds rather than the dependencies as you wrote them. +For example, an implicit field may appear as a missing `HasField` implementation with a nested +type-level field name. [`check_components!`](/docs/reference/macros/check_components) puts the check +where you choose, usually beside the wiring, and helps expose the missing dependency. For the +classes it recognizes, [`cargo cgp check`](/docs/cargo-cgp/check) leads with the root cause, though +it does not yet reshape every class. [Checking your wiring](./check-traits.md) explains those +diagnostics and their limits. -A component and wiring are unnecessary when one blanket implementation provides all the reuse you -need. Write that implementation in ordinary Rust, or use -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) to generate a trait from a function. A plain generic -function remains suitable when its explicit parameters and bounds are the interface callers should see. +When one blanket implementation gives you enough reuse, ordinary Rust can express it directly, +or [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) can generate it from a function. Components and +wiring are useful when you need alternative providers. A plain generic function is also a good +fit when its explicit parameters and bounds are the interface you want callers to see. ## Where to go next -These pages develop the dependency forms and explain how providers are selected and checked: +To apply this separation, consider which requirements a caller needs to use directly and which +belong to the selected implementation. These pages explain the dependency forms and how to +check them: - [Implicit arguments](./implicit-arguments.md): Reading context values without public method arguments. - [Abstract types](./abstract-types.md): Sharing context-selected types and deciding which reach the interface. @@ -264,8 +301,8 @@ These pages develop the dependency forms and explain how providers are selected [`#[use_type]`](/docs/reference/attributes/use_type): The dependency syntax used here. - [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) and [`#[blanket_trait]`](/docs/reference/macros/blanket_trait): Generating blanket implementations. -- [Comparison: Dependency injection](/docs/comparisons/dependency-injection): impl-side dependencies as constructor parameters, without a container. -- [Comparison: Capabilities](/docs/comparisons/capabilities): requirements on the context read against the several senses of "capability". +- [Comparison: Dependency injection](/docs/comparisons/dependency-injection): How impl-side dependencies compare with constructor parameters and containers. +- [Comparison: Capabilities](/docs/comparisons/capabilities): How context requirements relate to the different meanings of "capability". --- diff --git a/example-code/tests/concepts/impl_side_dependencies.rs b/example-code/tests/concepts/impl_side_dependencies.rs index 01aaf656..5ad39886 100644 --- a/example-code/tests/concepts/impl_side_dependencies.rs +++ b/example-code/tests/concepts/impl_side_dependencies.rs @@ -41,7 +41,7 @@ pub mod moving_the_requirement { } } - // `HasName` is nowhere in this signature, and nothing above it will mention one either. + // Generic callers can require `CanGreet` without repeating `HasName`. pub fn greet_twice(context: &Context) -> String where Context: CanGreet, @@ -135,7 +135,7 @@ pub mod two_providers_two_requirements { } } -/// ## The three things an implementation can ask for +/// ## Traits, values, and types /// /// The value leg. The field requirement is generated from the argument name and lands on the impl. pub mod the_value_leg { @@ -166,10 +166,9 @@ pub mod the_value_leg { } } -/// ## Type dependencies, and why they need no parameter +/// ## Keeping type choices on the context /// -/// The shape a type dependency takes when it is a parameter: an input the caller supplies, so every -/// intermediate signature carries it whether or not it touches one. +/// Generic forwarding functions can carry type parameters and bounds needed by the job runner. pub mod the_type_leg_as_a_parameter { pub trait Store { type Error; @@ -185,11 +184,11 @@ pub mod the_type_leg_as_a_parameter { R: Runtime, S: Store, { - // This layer touches none of the three. + // The page omits the job execution body. Ok(()) } - // And the layer above declares them again, for the same reason: it touches none of them either. + // This generic forwarding layer repeats the job runner's parameters and bounds. pub fn run_jobs(store: &S, runtime: &R) -> Result<(), E> where E: From + From, @@ -200,10 +199,9 @@ pub mod the_type_leg_as_a_parameter { } } -/// ## Type dependencies, and why they need no parameter +/// ## Keeping type choices on the context /// -/// The same dependency as an abstract type: an output the context determines, so it is named where -/// it is used and nowhere else. +/// The context selects the associated error type, which remains part of the public interface. pub mod the_type_leg_as_an_abstract_type { // The error component's wiring key is deliberately not in the prelude. use cgp::core::error::ErrorTypeProviderComponent; @@ -223,7 +221,7 @@ pub mod the_type_leg_as_an_abstract_type { } } - // The intermediate layer names no error type, no runtime, and no store. + // The forwarding operation shares the context's error and requires `CanRunJob` on its impl. #[cgp_fn] #[uses(CanRunJob)] #[use_type(HasErrorType.Error)] @@ -232,6 +230,13 @@ pub mod the_type_leg_as_an_abstract_type { self.run_job() } + pub fn run_batch(context: &Context) -> Result<(), Context::Error> + where + Context: RunJobs, + { + context.run_jobs() + } + pub struct App; delegate_components! { @@ -247,7 +252,8 @@ pub mod the_type_leg_as_an_abstract_type { } #[test] - fn the_context_decides_the_error_type_and_no_layer_names_it() { - assert!(App.run_jobs().is_ok()); + fn the_forwarder_uses_the_contexts_shared_error_type() { + let result: Result<(), String> = run_batch(&App); + assert!(result.is_ok()); } } From 968db85708c8aa5ca0c99367ead92b12f2541a1c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 1 Nov 2026 23:52:39 +0100 Subject: [PATCH 185/516] Lead concept pages with their ideas before introducing examples Keep coherence, the trait split, and impl-side dependencies as the subjects of their introductions. Introduce the running examples in the body and preserve the explanations and code that follow. --- docs/concepts/coherence.md | 17 ++++++------ docs/concepts/consumer-and-provider-traits.md | 26 +++++++++---------- docs/concepts/impl-side-dependencies.md | 18 ++++++------- 3 files changed, 31 insertions(+), 30 deletions(-) diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 695b9c4a..859e5f99 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -5,14 +5,15 @@ sidebar_position: 1 # Bypassing coherence -A trait bound lets generic code request an implementation without asking its caller to pass one. -Rust's coherence rules make that possible by keeping the choice consistent across the program. -That consistency also limits which implementations can coexist: if several could apply to the -same type, Rust rejects them even when an application knows which behavior it wants. - -This page follows that trade-off from ordinary trait lookup to an encoding example with competing -implementations. It then shows how CGP gives those implementations separate provider types and -connects each value type to its chosen provider, before considering the costs of that arrangement. +Rust's coherence rules keep trait lookup consistent across a program. For a given trait, its +type arguments, and an implementing type, at most one implementation applies. Generic code can +therefore rely on trait bounds without asking callers to choose an implementation. The same +guarantee rules out overlapping implementations, even when each would be useful on its own. + +CGP lets alternatives coexist by giving each implementation a separate provider type. A context +then selects its provider through wiring, and the generated code continues to obey Rust's +coherence rules. This page explains why that guarantee matters, how the provider split works +within it, and where ownership and wiring limit the available choices. ## The trait system is already a dependency-injection mechanism diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index ab228f38..d2ea985e 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -5,21 +5,21 @@ sidebar_position: 2 # Consumer and provider traits -A production application may send email through SMTP, while a test application records messages -for inspection. Both can expose the same `send_email` method through an ordinary Rust trait. -As more application types need those behaviors, it becomes useful to share each implementation -while letting each application choose which one to use. +A CGP component connects callers to implementations through two related traits. Callers use the +**consumer trait** to invoke methods on a context, the type receiving the call. Implementers use +the **provider trait** to supply those methods through separate provider types. The context chooses +a provider through wiring, so implementations can vary while callers keep the same interface. -CGP supports that choice by separating the interface callers use from the interface reusable -implementations target. This page follows the email example through that split, traces a call -through the generated Rust, and shows how the macros connect the pieces. It closes with the -costs and limits of the arrangement. +This page follows the connection between the two traits, from a method call through the generated +forwarding implementations to the chosen provider. It then shows how the macros produce those +connections, where application state lives, and what the separation costs. ## What an ordinary Rust trait does, and where it stops -An ordinary Rust trait already lets the two applications expose the same method with different -behavior. Each application type provides its own implementation of `CanSendEmail`, and callers -use the shared interface: +An ordinary Rust trait lets different types expose the same method with different behavior. +For example, a production application may send email through SMTP, while a test application +records messages for inspection. Each type can implement `CanSendEmail`, giving callers a +shared interface: ```rust use core::cell::RefCell; @@ -71,8 +71,8 @@ implementations and a wiring table that selects one. ## Splitting one trait in two -The **consumer trait** keeps the caller's interface, including the original methods and receiver. -The **provider trait** moves the consumer's `Self` into a `Context` parameter. Its methods receive +The consumer trait keeps the caller's interface, including the original methods and receiver. +The provider trait moves the consumer's `Self` into a `Context` parameter. Its methods receive the context as an explicit argument, leaving the implementing type free to name the behavior. The signatures below show the split. They omit a generated checking bound on the provider trait, diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index 91a4b0a9..f48ade12 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -5,19 +5,19 @@ sidebar_position: 3 # Impl-side dependencies -Building a greeting from a name requires access to that name. A caller that only wants the -resulting greeting, however, may have no reason to retrieve the name itself. Keeping that -requirement on the implementation lets the caller depend on the greeting operation alone. -Such a requirement, present on an implementation but absent from its trait interface, is an -**impl-side dependency**. +A trait exposes operations that callers can use, while an implementation may need additional +traits, values, or types to carry them out. A requirement kept on the implementation without +appearing in the trait's interface is an **impl-side dependency**. Callers can then depend on the +trait alone, and the compiler checks the implementation's requirements when resolving that trait +for a context. -This page develops that separation with ordinary Rust functions and blanket implementations, -then applies it to CGP providers. The examples move from trait requirements to field values and -type choices, including the types that must remain visible in the public interface. +This page develops that separation in ordinary Rust blanket implementations, then applies it to +CGP providers. It covers dependencies on traits, field values, and context-selected types, +including why types used in public signatures must remain available through the interface. ## What a `where` clause costs the callers above it -A generic greeting function can obtain a name through a `HasName` bound on the context: +For example, a generic greeting function can obtain a name through a `HasName` bound on the context: ```rust pub trait HasName { From 7b335e94fac98253789e648464bc96d8ccde737f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 1 Nov 2026 23:58:23 +0100 Subject: [PATCH 186/516] Require natural prose for concept pages and clarify error handling Apply natural-writing to new and revised concept pages while keeping each concept central. Introduce modular error handling through context choices and distinguish error construction from Rust propagation. --- AGENTS.md | 10 ++++++++++ docs/concepts/modular-error-handling.md | 20 +++++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 565c4fe5..6c9350c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,6 +111,16 @@ better; naming where a simpler tool is the right choice is an asset, not a conce genuine costs — the learning curve, the verbose diagnostics, the young ecosystem — wherever a reader would look for them, because this audience is unusually good at detecting what is being left out. +## Use natural-writing for concept pages + +When adding or revising a page under `docs/concepts/`, use the natural-writing style of the +`point-first-writing` skill throughout the page. Let sentences build on one another, connect +paragraphs so the reasoning is easy to follow, and vary sentence length. Keep the concept and its +purpose as the subject of the opening, with examples serving as illustrations. + +The knowledge base's [explanation-page writing guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/explanation.md#writing-style) +sets the full style and structure requirements for these pages. + ## Do not rewrite published blog posts A blog post is dated. A release announcement records what a release did at the time, and editing its diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index c6ddfacc..be44c8ed 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -5,19 +5,21 @@ sidebar_position: 10 # Modular error handling -A port parser may serve several applications, each with its own way of reporting errors. One may -need a message to log, while another needs an enum its callers can match on. With CGP, the parser -can leave that choice to its context and use the same parsing logic in both applications. +Modular error handling lets reusable code report failures while each application chooses how to +represent them. In CGP, the context selects a shared error type and providers for converting +source errors into it and attaching detail. Reusable code declares which of those operations it +needs, allowing the same implementation to work with different error policies. -This page follows that parser from detecting a failure to constructing an error, then shows how -other code can attach detail as the error propagates. It also explains how applications can define -their own error-raising operations and where the extra abstraction is useful. +Errors built this way still propagate through ordinary Rust `Result` values and the `?` operator. +This page explains how these choices fit together, how to preserve structured failures, and when +application-specific error operations are useful. It also considers the requirements and costs +of leaving error representation to the context. ## Separating failure from error representation {#why-the-error-type-is-the-hard-one} -Ordinary Rust already offers ways to share parsing logic across applications. A parser can return -a concrete error for callers to convert, take a generic error parameter, or use an associated error -type. In each case, the application can choose how to represent a failure. +Ordinary Rust offers several ways for reusable code to leave error representation to an +application. A parser, for example, can return a concrete source error for callers to convert, +take a generic error parameter, or use an associated error type. CGP builds on the associated-type approach by giving a context one shared error type. Operations that use this type can propagate each other's errors directly. To produce an error in the first From 62cae7af947d7ef6bf4c128d13a0aefb7b0a67c7 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 2 Nov 2026 00:01:56 +0100 Subject: [PATCH 187/516] Require natural-writing for the cargo-cgp pages Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 6c9350c8..39171220 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -121,6 +121,16 @@ purpose as the subject of the opening, with examples serving as illustrations. The knowledge base's [explanation-page writing guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/explanation.md#writing-style) sets the full style and structure requirements for these pages. +## Use natural-writing for cargo-cgp pages + +When adding or revising a page under `docs/cargo-cgp/`, use the same natural-writing style +throughout the page, the lookup pages included. Keep tables, lists, and code blocks where the content +is a set of items or text a reader copies, and let the prose around them follow from one sentence to +the next. + +The knowledge base's [tooling-page writing guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/tooling.md#writing-style) +sets the full style requirements for these pages. + ## Do not rewrite published blog posts A blog post is dated. A release announcement records what a release did at the time, and editing its From 4d910dafad175760609751f374d918d506eff869 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 2 Nov 2026 00:16:47 +0100 Subject: [PATCH 188/516] Rewrite the cargo-cgp pages against the release's output Quote what the tool prints now: headlines that state the cause, `help` lines, and the renumbered codes. The error-codes page gains the codes it lacked and follows the catalog's blocks. State the install's minimum Rust and `--locked`, why a check has its own build directory, how a target directory moves it, and how `expand` fails. The prose follows natural-writing throughout. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/check.md | 136 ++--- docs/cargo-cgp/command-reference.md | 65 +-- docs/cargo-cgp/editor-integration.md | 156 +++--- docs/cargo-cgp/error-codes.md | 736 +++++++++++++++++++-------- docs/cargo-cgp/expand.md | 107 ++-- docs/cargo-cgp/index.md | 108 ++-- docs/cargo-cgp/installation.md | 110 ++-- docs/cargo-cgp/reading-output.md | 215 ++++---- docs/cargo-cgp/troubleshooting.md | 238 +++++---- 9 files changed, 1122 insertions(+), 749 deletions(-) diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index 8a431d90..bf8e7908 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -7,15 +7,16 @@ description: 'Run cargo cgp check in place of cargo check to get CGP compile err # Check -`cargo cgp check` runs `cargo check` on your project and rewrites the CGP errors it recognizes so that -each one leads with its root cause. It is part of [`cargo-cgp`](./index.md), the error toolchain for +When a CGP error is hard to read, the first thing to try is `cargo cgp check`. It runs `cargo check` on +your project and rewrites the CGP errors it recognizes so that each one leads with its root cause. The +command is part of [`cargo-cgp`](./index.md), the error toolchain for [Context-Generic Programming (CGP)](/docs/), and you use it wherever you would use `cargo check`: ```sh cargo cgp check ``` -Run it anywhere inside your package or workspace. Everything after `check` is passed to +You can run it anywhere inside your package or workspace. Everything after `check` is passed to `cargo check`, so the flags you already use work unchanged: ```sh @@ -26,22 +27,22 @@ cargo cgp check --all-targets ## Try it on a deliberate mistake -A small library with one mistake shows what the tool does. Create a package: +A small library with one mistake shows what the tool does. Start by creating a package: ```sh cargo new --lib area-demo cd area-demo ``` -Add CGP to its `Cargo.toml`: +Then add CGP to its `Cargo.toml`: ```toml [dependencies] cgp = "0.8.0" ``` -Then replace `src/lib.rs` with this program. `RectangleArea` reads `width` and `height` through -[`#[implicit]`](/docs/reference/attributes/implicit) arguments, and `Rectangle` has only a `width`: +Now replace `src/lib.rs` with this program. `RectangleArea` reads `width` and `height` through +[`#[implicit]`](/docs/reference/attributes/implicit) arguments, but `Rectangle` has only a `width`: ```rust use cgp::prelude::*; @@ -75,39 +76,40 @@ pub fn print_area(rectangle: &Rectangle) { } ``` -After cargo's progress lines, the check prints this, followed by cargo's one-line summary: +After cargo's progress lines, the check prints this error, followed by cargo's one-line summary: ```text $ cargo cgp check -error[E0599]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` +error[E0599]: [CGP-E001] missing field `height` on `Rectangle` --> src/lib.rs:28:30 | 28 | println!("{}", rectangle.area()); | ^^^^ | - = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + = note: root cause: [CGP-E110] missing field `height` on `Rectangle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` - └─ [CGP-E106] missing field `height` on `Rectangle` + └─ [CGP-E110] missing field `height` on `Rectangle` + = help: add the field `height: f64` to `Rectangle` For more information about this error, try `rustc --explain E0599`. ``` -**Read the `root cause:` line first.** It names the fix: add a `height: f64` field to `Rectangle`, or -wire a provider that does not read one. The tree beneath it is the chain of requirements, read from -the top: `Rectangle` must implement `CanCalculateArea`, so its provider `RectangleArea` must work for -`Rectangle`, so `Rectangle` must have the field. Replace the comment with `pub height: f64,` and the -check passes. Plain `cargo check` reports this same mistake without ever mentioning `height`; the -[overview](./index.md#the-problem-it-solves) shows its output. +The headline already names the problem, and the `help` line offers one fix: add a `height: f64` field to +`Rectangle`. Another fix is to wire a provider that does not read a height, and the tree shows why that +would work too. Read from the top, it says that `Rectangle` must implement `CanCalculateArea`, so its +provider `RectangleArea` must work for `Rectangle`, so `Rectangle` must have the field. Replace the +comment with `pub height: f64,` and the check passes. By contrast, plain `cargo check` reports this same +mistake without ever mentioning `height`, as the [overview](./index.md#the-problem-it-solves) shows. ## Check the wiring where you write it -**Add a [`check_components!`](/docs/reference/macros/check_components) block to move the error from -the call to the wiring.** Wiring is lazy, so without one the error appears wherever the trait is first -used, which in a larger program can be far from the line you need to change. Replace `print_area` in -the program above with: +So far the error has appeared at the call to `area`, because wiring is lazy: without a check, the error +appears wherever the trait is first used. In a larger program, that place can be far from the line you +need to change. A [`check_components!`](/docs/reference/macros/check_components) block moves the error to +the wiring. Replace `print_area` in the program above with: ```rust check_components! { @@ -117,90 +119,90 @@ check_components! { } ``` -The check reports the same cause, now at the entry that asserted it: +The check now reports the same cause at the entry that asserted it: ```text -error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` +error[E0277]: [CGP-E001] missing field `height` on `Rectangle` --> src/lib.rs:29:9 | 29 | AreaCalculatorComponent, | ^^^^^^^^^^^^^^^^^^^^^^^ | - = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + = note: root cause: [CGP-E110] missing field `height` on `Rectangle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` - └─ [CGP-E106] missing field `height` on `Rectangle` + └─ [CGP-E110] missing field `height` on `Rectangle` + = help: add the field `height: f64` to `Rectangle` For more information about this error, try `rustc --explain E0277`. ``` -A check also changes what plain `cargo check` can tell you. With the check in place, stable Rust names -the missing requirement, but spells the field name one character at a time, as a type-level string. -Because it compares that name with the `width` field the struct does have, it also prints the letter -the two share in that position as `_`: +The `check_components!` block also changes what plain `cargo check` can tell you. With the block in place, +stable Rust names the missing requirement, but it spells the field name one character at a time, as a +type-level string. Because it compares that name with the `width` field the struct does have, it also +prints the letter the two share in that position as `_`: ```text -help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` ``` That line is an excerpt from an error of about thirty lines whose headline names -`CanUseComponent`, a trait the macros generated. The tool turns it into the -sentence above. +`CanUseComponent`, a trait the macros generated. The tool turns all of it into +the message above. ## What a check does differently -A check is `cargo check` with three settings the tool chooses for you: +The rewriting is possible because a check is `cargo check` with three settings the tool chooses for you: -- **It compiles under the tool's pinned nightly**, so the compiler inside the driver matches the one - that builds your code. Your project's own toolchain is untouched. -- **It uses Rust's next-generation trait solver**, which works out the missing requirement in the cases - where the default solver only says that a method's bounds were not satisfied. -- **It builds into `target/cgp`** rather than `target`, so a check never invalidates your normal build - cache, and your builds never invalidate its. +- **The pinned nightly:** a check compiles under the tool's own nightly, so the compiler inside the driver + matches the one that builds your code. Your project's toolchain is untouched. +- **The next-generation trait solver:** this solver works out the missing requirement in the cases where + the default solver only says that a method's bounds were not satisfied. +- **Its own build directory:** a check builds into `target/cgp` rather than `target`. Cargo locks a target + directory while it builds there, so a shared one would make each check wait for your other cargo runs + and your editor's, and the reverse. -Because the tool picks these settings, a check is a diagnostic pass rather than a reproduction of your -own build, the way Clippy runs under settings of its own. Your toolchain's `cargo check` remains the -authority on whether the code compiles. +Because the tool picks these settings, a check is a diagnostic pass rather than a reproduction of your own +build, the way Clippy runs under settings of its own. A passing check therefore does not promise a passing +`cargo check`. For example, two namespaces that inherit from each other are rejected by stable Rust but +compile under the tool. Your toolchain's `cargo check` remains the authority on whether the code compiles. -**`target/cgp` sits inside your project's own target directory**, wherever in the project you run the -command, and follows a `build.target-dir` you have configured. Pass `--target-dir`, or set -`CARGO_TARGET_DIR`, to put the artifacts somewhere else. +The `target/cgp` directory sits inside your project's own target directory, wherever in the project you +run the command, so it follows a configured `build.target-dir` or a set `CARGO_TARGET_DIR`. With +`CARGO_TARGET_DIR=/build`, for example, the check builds in `/build/cgp`. To choose the check's directory +exactly, pass `--target-dir`. ## Flags are cargo's, not the tool's -The tool appends your arguments to `cargo check` and lets cargo handle them, which has three -consequences: +The tool appends your arguments to `cargo check` and lets cargo handle them, so every `cargo check` flag +behaves as it normally does. Cargo also validates them, which means an unknown flag produces cargo's +error, `error: unexpected argument '--nope' found`, rather than a message from the tool. In the same way, +`cargo cgp check --help` prints cargo's help for `cargo check` and exits without running a check. For the +tool's own commands, run `cargo cgp --help`. -- **Every `cargo check` flag behaves as it normally does**, because `cargo check` is what runs. -- **cargo validates them, not cargo-cgp.** An unknown flag produces cargo's error, - `error: unexpected argument '--nope' found`, rather than a message from the tool. -- **`cargo cgp check --help` prints cargo's help** for `cargo check` and exits without running a check. - For the tool's own commands, run `cargo cgp --help`. - -The tool reads two of the flags itself, `--target-dir` and `--manifest-path`, and only to decide where -`target/cgp` goes. +The tool reads three of the flags itself, `--target-dir`, `--manifest-path`, and `--config`, and only to +decide where `target/cgp` goes. It still passes all three on to cargo. ## In your editor -rust-analyzer can run `cargo cgp check` every time you save, so the errors your editor underlines lead -with their root cause too. It takes one setting, which +The same check can run in your editor, so the errors you see there lead with their root cause too. +rust-analyzer can run `cargo cgp check` every time you save, and it takes one setting, which [Editor integration](./editor-integration.md) gives for VS Code, along with what the switch changes. ## When it will not help -**A check reports only what your code asks the compiler to prove.** Wiring that nothing uses and -nothing checks produces no error, from this tool or any other. That is why -[`check_components!`](/docs/reference/macros/check_components) is worth adding for every context you -wire. +A check reports only what your code asks the compiler to prove. Wiring that nothing uses and nothing +checks produces no error, from this tool or any other, which is why +[`check_components!`](/docs/reference/macros/check_components) is worth adding for every context you wire. -**Some errors pass through as the compiler wrote them.** `cargo cgp check` leads with the root cause -for the classes it recognizes, and the tool does not yet reshape every class. -[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the ones that do not -change. +Some errors also pass through as the compiler wrote them. `cargo cgp check` leads with the root cause for +the classes it recognizes, and the tool does not yet reshape every class. +[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the ones you are most +likely to meet. -**It reshapes errors in your workspace's own crates only.** A dependency outside the workspace is -compiled normally, so an error inside it arrives as the compiler wrote it. +Finally, the tool reshapes errors in your workspace's own crates only. A dependency outside the workspace +is compiled normally, so an error inside it arrives as the compiler wrote it. If the command itself will not run, see [Troubleshooting](./troubleshooting.md). diff --git a/docs/cargo-cgp/command-reference.md b/docs/cargo-cgp/command-reference.md index 2413c9a9..c5e2ea4f 100644 --- a/docs/cargo-cgp/command-reference.md +++ b/docs/cargo-cgp/command-reference.md @@ -7,9 +7,9 @@ description: 'Every cargo-cgp command and option, the environment variables it r # Command reference -This page lists everything [`cargo-cgp`](./index.md) version 0.1.0 accepts and changes: its commands, -their options, the environment variables it reads and sets, the files it creates, and its exit -status. The other pages in this section explain how to use them. +When you need to look up a flag or a variable, this page lists everything [`cargo-cgp`](./index.md) version +0.1.0 accepts and changes: its commands, their options, the environment variables it reads and sets, the +files it creates, and its exit status. The other pages in this section explain how to use them. ## Running it @@ -44,15 +44,15 @@ The tool has four commands. Two read your code, and two install and update the t cargo cgp check [CARGO CHECK ARGS]... ``` -**Every argument is passed to `cargo check`**, which also validates them, so the command takes every -`cargo check` flag and no flags of its own. `cargo cgp check --help` prints `cargo check`'s help and -does not run a check. Two flags matter more than the rest: +Every argument is passed to `cargo check`, which also validates them, so the command takes every +`cargo check` flag and no flags of its own. `cargo cgp check --help` prints `cargo check`'s help and does not +run a check. Two flags matter more than the rest: -- **`--target-dir
`** sets where the build goes. Without it, and without `CARGO_TARGET_DIR`, the - tool builds into the `cgp` subdirectory of your project's own target directory, which it reads from - `cargo metadata`, so the location is the same wherever in the project you run it. -- **`--message-format=json`** prints the errors as JSON, rewritten the same way as the text output. An - editor needs this form; see [Editor integration](./editor-integration.md). +- **`--target-dir `:** sets exactly where the build goes. Without it, the tool builds into the `cgp` + subdirectory of your project's own target directory, which it reads from `cargo metadata`, so the location + is the same wherever in the project you run it. +- **`--message-format=json`:** prints the errors as JSON, rewritten the same way as the text output. An editor + needs this form, as [Editor integration](./editor-integration.md) explains. ### `expand` @@ -65,8 +65,8 @@ cargo cgp expand [--item ] [CARGO RUSTC ARGS]... | `--item ` | Prints only one module or item instead of the whole target. The path is `::`-separated, names something inside the crate, and may start with `crate::`. A module gives its contents, a type its declaration and every impl written for it, and a trait its definition and every impl of it. | | `-h`, `--help` | Prints the help for `expand`, including `--item`. | -**Every other argument is passed to `cargo rustc`**, so choosing the target, with `--lib`, `--bin`, -`-p`, or `--features`, is cargo's job. A package with more than one target needs `--lib` or +Every other argument is passed to `cargo rustc`, so choosing the target, with `--lib`, `--bin`, `-p`, or +`--features`, is cargo's job. A package with more than one target needs `--lib` or `--bin `. Unless you pass `--profile`, the tool builds under cargo's `check` profile. The expansion goes to standard output, and everything else goes to standard error. @@ -76,10 +76,9 @@ expansion goes to standard output, and everything else goes to standard error. cargo cgp setup ``` -Installs the pinned nightly through rustup, with the `rustc-dev` and `llvm-tools` components, then -builds `cargo-cgp-driver` at the front end's version under that nightly and installs it beside the -front end. Running it again when both are present does no harm. It needs rustup and a network -connection. +This command installs the pinned nightly through rustup, with the `rustc-dev` and `llvm-tools` components, +then builds `cargo-cgp-driver` at the front end's version under that nightly and installs it beside the front +end. Running it again when both are present does no harm. It needs rustup and a network connection. ### `update` @@ -87,11 +86,11 @@ connection. cargo cgp update ``` -Looks up the published versions on crates.io and, if there is a newer one in your release channel, -reinstalls the front end and runs the new version's `setup`. It needs a network connection. +This command looks up the published versions on crates.io and, if there is a newer one in your release +channel, reinstalls the front end and runs the new version's `setup`. It needs a network connection. -**`setup` and `update` take no options.** Each answers `-h` or `--help` with a description of what it -does instead of running, and refuses any other argument with an error naming it. +`setup` and `update` take no options. Each answers `-h` or `--help` with a description of what it does instead +of running, and refuses any other argument with an error naming it. ## Environment variables @@ -102,21 +101,21 @@ install, such as one from a source checkout: |---|---| | `CARGO_CGP_NO_MANAGE` | When set, skips the preflight test of the toolchain and driver, and does not switch to the pinned nightly. The check then runs under whatever toolchain is active, which must be the driver's nightly. | | `CARGO_CGP_DRIVER` | The path of the driver to run, instead of looking beside the front end. | -| `CARGO_CGP_TOOLCHAIN` | A nightly to use in place of the pinned one, for `setup`, `check`, and `expand`. The driver must be built against it. | -| `CARGO_TARGET_DIR` | cargo's own variable. When set, the tool does not add its `target/cgp` directory. | +| `CARGO_CGP_TOOLCHAIN` | A nightly to use in place of the pinned one, for `setup`, `check`, and `expand`. The driver must be built against it. It has no effect when `CARGO_CGP_NO_MANAGE` is set. | +| `CARGO_TARGET_DIR` | cargo's own variable. It moves the project's target directory, and the tool builds in that directory's `cgp` subdirectory. | For the length of a `check` or `expand`, the tool also sets variables for cargo: | Variable | Set to | |---|---| -| `RUSTC_WORKSPACE_WRAPPER` | The driver. This replaces any value you set, so a wrapper of your own given through this variable does not run under the tool. | +| `RUSTC_WORKSPACE_WRAPPER` | The driver. This replaces any value you set, so a wrapper of your own given through this variable does not run under the tool, which prints a warning saying so. | | `RUSTUP_TOOLCHAIN` | The pinned nightly, unless `CARGO_CGP_NO_MANAGE` is set. | | `LD_LIBRARY_PATH` | The `lib` directory of the toolchain the check runs under, added in front of any existing value, so the driver can load the compiler. | ## Files and directories -The tool puts its files in these places. Uninstalling with cargo removes the two binaries but leaves -the toolchain and the build directories; see [Uninstalling](./installation.md#uninstalling): +The tool puts its files in these places. Uninstalling with cargo removes the two binaries but leaves the +toolchain and the build directories, as [Uninstalling](./installation.md#uninstalling) explains: | Path | What it holds | |---|---| @@ -127,21 +126,23 @@ the toolchain and the build directories; see [Uninstalling](./installation.md#un ## Exit status -`check` exits with `cargo check`'s status, so `0` means no errors. `expand` exits with `0` when it -printed an expansion and with a non-zero status when it did not. A failure in the tool itself, such as -a preflight message or an unknown command, exits with `1`. +`check` exits with `cargo check`'s status, so `0` means no errors. `expand` exits with `0` when the compilation +reached the end of macro expansion without an error, which includes a crate that would fail type checking. An +error before that point exits with cargo's status, even when part of an expansion was printed, and a path given to +`--item` that matches nothing exits with `1`. A failure in the tool itself, such as a preflight message or an +unknown command, also exits with `1`. ## The driver -You do not normally run `cargo-cgp-driver` yourself; the front end runs it in place of the compiler. -It answers two queries of its own: +You do not normally run `cargo-cgp-driver` yourself, since the front end runs it in place of the compiler. It +does answer two queries of its own: | Option | Effect | |---|---| | `--version`, `-V` | Prints three lines: its version, the `pinned-toolchain:` it needs, and the `built-against-rustc:` compiler it was built with. | | `--help`, `-h` | Prints a short description of the driver. Running it with no arguments does the same. | -Run directly on the cargo path, it needs the pinned nightly's `lib` directory on `LD_LIBRARY_PATH`; +Run directly on the cargo path, it needs the pinned nightly's `lib` directory on `LD_LIBRARY_PATH`, and [Troubleshooting](./troubleshooting.md#the-driver-cannot-load-the-compiler) shows the command. --- diff --git a/docs/cargo-cgp/editor-integration.md b/docs/cargo-cgp/editor-integration.md index 9652aad3..91cec877 100644 --- a/docs/cargo-cgp/editor-integration.md +++ b/docs/cargo-cgp/editor-integration.md @@ -7,19 +7,18 @@ description: 'Make rust-analyzer run cargo cgp check when you save, so VS Code s # Editor integration -rust-analyzer runs `cargo check` every time you save a file and shows the errors in your editor. One -setting makes it run `cargo cgp check` instead, so the CGP errors VS Code underlines lead with their -root cause, exactly as they do in a terminal. This page covers VS Code with the -[rust-analyzer extension](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). -It is part of [`cargo-cgp`](./index.md), the error toolchain for [CGP](/docs/), and it assumes the -tool is [installed](./installation.md) and that `cargo cgp check` already works in a terminal in your -project. +If you read your errors in an editor, a terminal command only helps so much. rust-analyzer runs +`cargo check` every time you save a file and shows the errors in your editor, and one setting makes it run +`cargo cgp check` instead, so the CGP errors VS Code underlines lead with their root cause, as they do in a +terminal. This page covers VS Code with the +[rust-analyzer extension](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). It +is part of [`cargo-cgp`](./index.md), the error toolchain for [CGP](/docs/), and it assumes the tool is +[installed](./installation.md) and that `cargo cgp check` already works in a terminal in your project. ## Set it up -**Add the setting to your project's workspace settings**, the `.vscode/settings.json` file at the -project's root. Open it with **Preferences: Open Workspace Settings (JSON)** from the command palette, -and add: +The setting goes in your project's workspace settings, the `.vscode/settings.json` file at the project's +root. Open it with **Preferences: Open Workspace Settings (JSON)** from the command palette, and add: ```json { @@ -34,14 +33,14 @@ errors you see do not change, run **rust-analyzer: Restart server** from the com Each part of the command has a job: -- **`cargo cgp check`** is the check itself, the same command you run in a terminal. -- **`--workspace`** checks every crate in the workspace, as rust-analyzer's own check does. -- **`--all-targets`** includes tests, examples, and benchmarks, so an error in a test shows up too. -- **`--message-format=json`** makes cargo print its errors as JSON, which is the only form - rust-analyzer reads. The tool writes its rewritten errors in the same JSON format as the compiler, - so nothing else is needed for them to reach the editor. +- **`cargo cgp check`:** the check itself, the same command you run in a terminal. +- **`--workspace`:** checks every crate in the workspace, as rust-analyzer's own check does. +- **`--all-targets`:** includes tests, examples, and benchmarks, so an error in a test shows up too. +- **`--message-format=json`:** makes cargo print its errors as JSON, which is the only form rust-analyzer + reads. The tool writes its rewritten errors in the same JSON format as the compiler, so nothing else is + needed for them to reach the editor. -**The command goes in `check.overrideCommand`, not `check.command`.** The +You may wonder why the command goes in `check.overrideCommand` rather than `check.command`. The [`check.command`](https://rust-analyzer.github.io/book/configuration.html#check.command) setting takes a single cargo subcommand, such as `clippy`, and rust-analyzer puts its own flags straight after it, so `cgp` would be followed by `--workspace` rather than by `check`. @@ -50,15 +49,15 @@ takes the whole command line and runs it as written. ### Workspace or user settings -**Prefer the workspace settings, so the tool runs only on projects that use CGP.** -[User settings](https://code.visualstudio.com/docs/configure/settings) apply to every project you open. -The tool checks a project without CGP correctly, but it still builds that project a second time under -its pinned nightly, which costs time and disk on a project that has no CGP errors to rewrite. Workspace settings -override user settings, so a project can also turn the check on or off for itself. +Prefer the workspace settings, so the tool runs only on projects that use CGP. +[User settings](https://code.visualstudio.com/docs/configure/settings) apply to every project you open. The +tool checks a project without CGP correctly, but it still builds that project a second time under its pinned +nightly, which costs time and disk on a project that has no CGP errors to rewrite. Workspace settings also +override user settings, so a project can turn the check on or off for itself. -**Commit `.vscode/settings.json` only if everyone who opens the project has the tool.** On a machine -without `cargo-cgp`, the check fails on every save, so that person gets a warning from rust-analyzer -instead of their check errors until they install the tool or remove the setting. +That said, commit `.vscode/settings.json` only if everyone who opens the project has the tool. On a machine +without `cargo-cgp`, the check fails on every save, so that person gets a warning from rust-analyzer instead +of their check errors until they install the tool or remove the setting. ## What the editor shows @@ -69,12 +68,13 @@ the `height` field its area provider reads, the underline sits on `area` in `rec message is the rewritten one: ```text -[CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` -root cause: [CGP-E106] missing field `height` on `Rectangle` +[CGP-E001] missing field `height` on `Rectangle` +root cause: [CGP-E110] missing field `height` on `Rectangle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` - └─ [CGP-E106] missing field `height` on `Rectangle` + └─ [CGP-E110] missing field `height` on `Rectangle` +add the field `height: f64` to `Rectangle` ``` The compiler's own code, `E0599` here, stays attached to the error, as it does in a terminal. @@ -82,26 +82,29 @@ The compiler's own code, `E0599` here, stays attached to the error, as it does i ## What changes when the editor runs the tool -Running the tool in place of `cargo check` changes four things about how rust-analyzer behaves: - -- **The first save is slow.** The check builds into its own `target/cgp` directory under the tool's - pinned nightly, so the first one compiles every dependency again. Later saves reuse that build, and - because it is separate from `target`, your terminal builds and the editor's checks do not undo each - other's work. -- **rust-analyzer's own check options are ignored.** With an override in place, rust-analyzer runs - the command exactly as written, so settings such as - [`check.features`](https://rust-analyzer.github.io/book/configuration.html#check.features), - `check.allTargets`, and `check.extraArgs` do not reach the check. Put the flags you need in the - command itself, for example `"--all-features"` or `"--features", "my-feature"` after - `"--all-targets"`. -- **Two kinds of error appear, and only one is rewritten.** rust-analyzer also analyzes your code as - you type, with its own engine and without running any compiler, and reports some errors of its own. - Those come from rust-analyzer rather than from the check, so they read as they always have. The - rewritten ones are the errors that arrive after a save. -- **The check and your toolchain can disagree.** The check compiles under the tool's pinned nightly - with Rust's next-generation trait solver, so on rare code the editor can show an error your own - `cargo check` does not, or the reverse. Your toolchain's `cargo check` is the authority on whether - the code compiles, as the [Check page](./check.md#what-a-check-does-differently) explains. +Running the tool in place of `cargo check` changes four things about how rust-analyzer behaves, and you +might otherwise blame the tool for them. + +The first save is slow. The check builds into its own `target/cgp` directory under the tool's pinned nightly, +so the first one compiles every dependency again. Later saves reuse that build. Because the directory is +separate from `target`, the editor's checks also do not wait on cargo's lock while your terminal builds, and +your terminal builds do not wait for them. + +rust-analyzer's own check options stop applying. With an override in place, rust-analyzer runs the command +exactly as written, so settings such as +[`check.features`](https://rust-analyzer.github.io/book/configuration.html#check.features), +`check.allTargets`, `check.workspace`, and `check.extraArgs` do not reach the check. Put the flags you need in +the command itself, for example `"--all-features"` or `"--features", "my-feature"` after `"--all-targets"`. + +Two kinds of error appear, and only one is rewritten. rust-analyzer also analyzes your code as you type, with +its own engine and without running any compiler, and reports some errors of its own. Those come from +rust-analyzer rather than from the check, so they read as they always have. The rewritten ones are the errors +that arrive after a save. + +Finally, the check and your toolchain can disagree. The check compiles under the tool's pinned nightly with +Rust's next-generation trait solver, so on rare code the editor can show an error your own `cargo check` does +not, or the reverse. Your toolchain's `cargo check` is the authority on whether the code compiles, as the +[Check page](./check.md#what-a-check-does-differently) explains. ## Turning it off @@ -110,55 +113,56 @@ rust-analyzer goes back to running `cargo check` on save. ## When it does not work -**When the command fails, rust-analyzer says so in a warning.** The warning begins -`cargo check failed to start`, whatever the command is, and ends with what the command printed. A -missing setup, for example, arrives as the tool's own message: +When the command fails, rust-analyzer says so in a warning. The warning begins +`cargo check failed to start`, whatever the command is, and ends with what the command printed. A missing +setup, for example, arrives as the tool's own message: ```text cargo check failed to start: Cargo watcher failed, the command produced no valid metadata (exit code: ExitStatus(unix_wait_status(256))): -cargo-cgp: toolchain `nightly-2026-10-10` is not available (exit status: 1) +error: toolchain `nightly-2026-10-10` is not available: + + error: toolchain 'nightly-2026-10-10-x86_64-unknown-linux-gnu' is not installed + help: run `rustup toolchain install nightly-2026-10-10-x86_64-unknown-linux-gnu` to install it -The pinned toolchain is not installed. Run `cargo cgp setup`. +help: run `cargo cgp setup` ``` -Your message names the nightly your build is pinned to. Look the message up on -[Troubleshooting](./troubleshooting.md), which lists each one with its fix. To tell whether the problem -is the tool or the editor, run the same command in a terminal from the root of the project you opened -in VS Code: +Your message names the nightly your build is pinned to and your own platform. Look the message up on +[Troubleshooting](./troubleshooting.md), which lists each one with its fix. To tell whether the problem is the +tool or the editor, run the same command in a terminal from the root of the project you opened in VS Code: ```sh cargo cgp check --workspace --all-targets ``` -**If the warning ends with cargo's `no such command` error, the editor cannot find the tool:** +If the warning instead ends with cargo's `no such command` error, the editor cannot find the tool: ```text error: no such command: `cgp` ``` -When the terminal command works, VS Code is running with a different `PATH` from your terminal, so the -`cargo` it starts does not see the tool. This happens most often when VS Code is started from a desktop -launcher rather than from a shell, and the tool is installed somewhere only your shell's start-up files -add to `PATH`, as with a Nix profile. Start VS Code from a terminal in which `cargo cgp --version` -works, and save again. +When the terminal command works, VS Code is running with a different `PATH` from your terminal, so the `cargo` +it starts does not see the tool. This happens most often when VS Code is started from a desktop launcher rather +than from a shell, and the tool is installed somewhere only your shell's start-up files add to `PATH`, as with a +Nix profile. To fix it, start VS Code from a terminal in which `cargo cgp --version` works, and save again. -**If only some errors are rewritten**, that is the tool's limit rather than the editor's. -`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet -reshape every class. [Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists -the errors that arrive as the compiler wrote them. +If only some errors are rewritten, you are seeing the tool's limit rather than the editor's. +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape +every class. [Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the errors you +are most likely to see as the compiler wrote them. ## What this does not do -**It changes only the errors from the check that runs on save.** Completion, hover types, -go-to-definition, and rust-analyzer's own as-you-type errors are unaffected, because none of them run -the check. +The setting changes only the errors from the check that runs on save. Completion, hover types, +go-to-definition, and rust-analyzer's own as-you-type errors are unaffected, because none of them run the +check. -**It has been tested on Linux, with the rust-analyzer language server.** The setting was verified by -running the server the way VS Code runs it, saving the program above, and reading what the server -reported: the rewritten error, the warnings quoted above, and the check options it leaves out -under the override. The VS Code window itself was not part of that test. Other editors that use rust-analyzer accept the -same setting, `check.overrideCommand`, in their own configuration format, but none of them has been -tried, and neither have macOS and Windows. +It has also been tested only on Linux, with the rust-analyzer language server. The setting was verified by +running the server the way VS Code runs it, saving the program above, and reading what the server reported: the +rewritten error, the warnings quoted above, and the check options it leaves out under the override. The VS Code +window itself was not part of that test. Other editors that use rust-analyzer accept the same setting, +`check.overrideCommand`, in their own configuration format, but none of them has been tried, and neither have +macOS and Windows. --- diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index a8b39578..ca4242b9 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -7,275 +7,489 @@ description: 'Look up any [CGP-Exxx] code cargo cgp check prints: what the messa # Error codes -`cargo cgp check`, part of the [`cargo-cgp`](./index.md) toolchain for -[Context-Generic Programming (CGP)](/docs/), tags each CGP error it rewrites with a code in square -brackets, such as `[CGP-E001]`. This page lists every code: the message it heads, the mistake it means, -the fix, and the section of the [compile-errors reference](/docs/reference/errors) that explains the -class of mistake in full. [Reading the output](./reading-output.md) shows how the codes sit inside a -complete error. +When `cargo cgp check` rewrites a CGP error, it tags the message with a code in square brackets, such as +`[CGP-E001]`, so you can look up what the message means. The command is part of the +[`cargo-cgp`](./index.md) toolchain for [Context-Generic Programming (CGP)](/docs/). This page lists every +code with the message it heads, the mistake it means, the fix, and the section that explains the class of +mistake in full, usually in the [compile-errors reference](/docs/reference/errors). +[Reading the output](./reading-output.md) shows how the codes sit inside a complete error. ## How the codes work -**A CGP code sits beside the compiler's own code, not in place of it.** In +A CGP code sits beside the compiler's own code rather than in place of it. In `error[E0277]: [CGP-E001] …`, `E0277` is the compiler's code, which `rustc --explain` describes, and -`[CGP-E001]` is the CGP class the tool recognized. A rewritten error restates the compiler's error more -readably and keeps its code, so searching your output for a CGP code finds every error of that class. +`[CGP-E001]` is the CGP class the tool recognized. Because a rewritten error restates the compiler's error +and keeps its code, searching your output for a CGP code finds every error of that class. -The hundreds digit says where in the error a code appears: +The hundreds digit says where in the error a code appears. `CGP-E0xx` codes head the error and classify it +as a whole. `CGP-E1xx` codes label the dependency chain, one per line of the tree beneath a `root cause:` +note. From `CGP-E101` to `CGP-E104` they mark steps along the way, and from `CGP-E110` onward they mark the +cause the chain ends at. -- **`CGP-E0xx` codes head the error.** They classify the whole error: what failed. -- **`CGP-E1xx` codes label the dependency chain**, one per line of the tree beneath a `root cause:` - note. The inner lines are steps along the way, and the last line is the cause. -- **`CGP-E2xx` codes label a `root cause:` line** whose cause has no `CGP-E1xx` code of its own. +In the messages below, a word in angle brackets, such as ``, stands for the name the tool fills in +from your code. -In the messages below, a word in angle brackets, such as ``, stands for the name the tool fills -in from your code. +## A trait the context cannot use -## Headline codes +The first family covers a requirement that fails somewhere under a trait. The tool traces the failure to its +causes, so the error usually carries a `root cause:` note and a dependency chain. ### CGP-E001 -**A context does not implement a consumer trait.** The context cannot use a component it is expected -to use: the component is not wired, or something the wired provider needs is missing, so the context -never gets the consumer trait. +A context cannot use a component it is expected to use. Either the component is not wired, or something the +wired provider needs is missing, so the context never gets the consumer trait. The headline states the cause +in the words of its chain line: ```text -[CGP-E001] the consumer trait `` is not implemented for context `` +[CGP-E001] missing field `height` on `Rectangle` ``` -When one mistake breaks several components, the message names them all: "the consumer traits ``, -``, and `` are not implemented". The compiler's code stays whatever it assigned: `E0277` at a -check, `E0599` at a method call. **Fix:** follow the `root cause:` note, which names the missing field, -derive, wiring entry, or trait bound. Explained in -[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met). +Causes of one kind on one owner are stated together, as in ``missing fields `width` and `height` on +`Rectangle` ``. A list of more than four names the first three and counts the rest. Causes of different kinds +get the class sentence with their count instead: + +```text +[CGP-E001] the consumer trait `` is not implemented for context ``: 2 root causes +``` + +The compiler's code stays whatever it assigned, which is `E0277` at a check and `E0599` at a method call. To +fix it, follow the `root cause:` note, which names the missing field, derive, wiring entry, or trait bound. +[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met) explains the class. ### CGP-E002 -**A provider does not implement its provider trait for the context.** Something the provider requires -does not hold. This is the provider-side face of `[CGP-E001]`, and it is what a -`#[check_providers(...)]` assertion in -[`check_components!`](/docs/reference/macros/check_components) reports. +A provider does not implement its provider trait for the context, because something the provider requires +does not hold. This is the provider-side version of `[CGP-E001]`, and a failing `#[check_providers(...)]` +assertion in [`check_components!`](/docs/reference/macros/check_components) or a call through the provider's +own path reports it. It also states the cause in its headline, with this class sentence for mixed causes: ```text [CGP-E002] the provider trait `` with context `` is not implemented for provider `` ``` -**Fix:** follow the `root cause:` note to what the provider is missing. Explained in -[When the provider is a stack](/docs/reference/errors#when-the-provider-is-a-stack). +To fix it, follow the `root cause:` note to what the provider is missing. +[When the provider is a stack](/docs/reference/errors#when-the-provider-is-a-stack) explains the class. ### CGP-E003 -**A field is present but has the wrong type.** The context has the field and derives `HasField` for it, -but its type is not the one a provider reads. +A trait that is not a CGP component fails because a component it depends on fails. It is the `[CGP-E001]` case +for a trait you wrote by hand over a consumer trait, or for a [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) or +[`#[blanket_trait]`](/docs/reference/macros/blanket_trait) trait, so its class sentence says "the trait" rather +than "the consumer trait": ```text -[CGP-E003] expected a `` field of type `` on ``, but found `` +[CGP-E003] the trait `` is not implemented for context `` ``` -When the required type is written in terms of an abstract type, the message shows both forms, the -written one and what it resolves to: +To fix it, follow the `root cause:` note to the dependency the trait needs. +[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met) explains the class. + +### CGP-E004 + +A field is present but has the wrong type. The context has the field and derives `HasField` for it, but its type +is not the one a provider reads: ```text -[CGP-E003] expected a `database` field of type `Pool<::Db>` (`Pool`) on `App`, but found `Pool` +[CGP-E004] field `` on `` has type ``, but `` is required ``` -The compiler's code is `E0271`. **Fix:** change the -field's type, or change the provider to accept the type the field has. Explained in -[When two decisions disagree about a type](/docs/reference/errors#when-two-decisions-disagree-about-a-type). +When the required type is written in terms of an abstract type, the message shows both the written form and what +it resolves to: -### CGP-E004 +```text +[CGP-E004] field `database` on `App` has type `Pool`, but `Pool<::Db>` (`Pool`) is required +``` + +The compiler's code is `E0271`. To fix it, change the field's type, or change the provider to accept the type the +field has. +[When two decisions disagree about a type](/docs/reference/errors#when-two-decisions-disagree-about-a-type) +explains the class. -**The same key is wired twice.** A wiring table, or a namespace, maps one component or path to two -providers. +### CGP-E005 + +An abstract type is wired one way and required another. The context supplies one type for an associated type, +such as its error type, while a provider requires a different one: ```text -[CGP-E004] duplicate wiring for on `` +[CGP-E005] abstract type `` of `` on `` is ``, but `` is required ``` -The compiler's two carets point at the two entries. **Fix:** remove one of them. Explained in -[Two entries claim one key](/docs/reference/errors#two-entries-claim-one-key). +For a trait that is not a CGP abstract-type component, the message says "associated type" instead. Like +`[CGP-E004]`, it shows a required type in both forms when it is written through another abstract type. The +compiler's code is `E0271`. To fix it, make the two sides agree. For a +[`#[cgp_type]`](/docs/reference/macros/cgp_type) component, the `help` line names the `UseType` entry to wire. +[When two decisions disagree about a type](/docs/reference/errors#when-two-decisions-disagree-about-a-type) +explains the class. -### CGP-E005 +## Conflicting wiring + +These five codes rewrite an `E0119` on a wiring entry, and the compiler's two carets point at the entries that +collide. A `` is worded as what it is, such as `` component `` ``, `` type `String` ``, or `` `@a.b` ``. +[Two entries claim one key](/docs/reference/errors#two-entries-claim-one-key) explains the class. + +### CGP-E010 + +The same key is wired twice, because a wiring table or a namespace maps one component or path to two providers. To +fix it, remove one of the entries. + +```text +[CGP-E010] conflicting wiring: `` wires twice +``` + +### CGP-E011 -**A key is wired that another entry already covers.** The two keys differ but overlap: a generic -entry over a specific one, a path that covers a longer path, or an entry for a key the context's -namespace already binds. +Two different keys overlap, so an entry is wired that another already covers. It may be a generic entry over a +specific one, a path that covers a longer path, or an entry for a key the context's namespace already binds. To fix +it, remove or narrow the overlapping entry. +[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds) +covers the namespace case. ```text -[CGP-E005] `` cannot wire that is already set through +[CGP-E011] conflicting wiring: `` wires , which already covers ``` -**Fix:** remove or narrow the overlapping entry. Explained in -[Two entries claim one key](/docs/reference/errors#two-entries-claim-one-key) and -[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds). +The source is the key that covers the other, whichever comes first. When neither covers the other, the key is the +one they share. -### CGP-E006 +### CGP-E012 -**A context joins more than one namespace.** Each namespace covers every key, so two of them, or a -namespace and a loop over bare keys, conflict. +A context joins more than one namespace. Each namespace covers every key, so two of them, or a namespace and a loop +over bare keys, conflict. To fix it, join one namespace and make it inherit the others. +[Joining more than one namespace](/docs/reference/errors#joining-more-than-one-namespace) explains the class. ```text -[CGP-E006] only one namespace can be used for each target type in `delegate_components!`, but `` uses both `` and `` +[CGP-E012] conflicting wiring: `` joins both `` and ``, but a target type in `delegate_components!` can join only one namespace ``` -**Fix:** join one namespace and make it inherit the others. Explained in -[Joining more than one namespace](/docs/reference/errors#joining-more-than-one-namespace). +### CGP-E013 + +A direct entry collides with a redirect of the same key, such as a component wired by name while an `open` +statement, a `=>` redirect, or a namespace sends it along a path. To fix it, wire the provider under the redirected +path rather than the component name, as the `help` line says. +[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds) +explains the class. + +```text +[CGP-E013] conflicting wiring: `` wires directly, but it is redirected to `` +``` -### CGP-E007 +### CGP-E014 -**A direct entry collides with a redirect of the same key**, such as a component wired by name while an -`open` statement, a `=>` redirect, or a namespace sends it along a path. +The same key is redirected twice, by two `open` statements or `=>` mappings on one context, or by one path registered +twice in a namespace. To fix it, keep one redirect. ```text -[CGP-E007] on `` is redirected to `` +[CGP-E014] conflicting wiring: `` redirects twice, to `` and to `` ``` -A `help` line names the entry to write instead. **Fix:** wire the provider under the redirected path -rather than the component name. Explained in -[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds). +## Structural mistakes + +These codes name a mistake in the shape of what a macro was given, which the compiler rejects through generated items. +Each one uses your program's terms, drops the compiler's suggestions that do not apply, and gives the fix in a `help` +line. -### CGP-E008 +### CGP-E015 -**The same key is redirected twice**, by two `open` statements or `=>` mappings on one context, or by -one path registered twice in a namespace. +A `check_components!` table lists one entry twice. To fix it, remove one of the two. +[The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. ```text -[CGP-E008] duplicate redirect for on `` +[CGP-E015] `check_components!` checks `` twice for `` ``` -**Fix:** keep one redirect. Explained in -[Two entries claim one key](/docs/reference/errors#two-entries-claim-one-key). +### CGP-E016 -### CGP-E009 +Two `check_components!` tables in one module check the same context, so they share a check-trait name. To fix it, merge +the tables, or name one table's check trait with `#[check_trait(...)]`. When two attributes give one name, the message +says so instead. +[The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. -**A trait that is not a CGP component fails because a component it depends on fails.** It is the -`[CGP-E001]` case for a trait you wrote by hand over a consumer trait, or for a -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) or [`#[blanket_trait]`](/docs/reference/macros/blanket_trait) -trait, which is why it says "the trait" rather than "the consumer trait". +```text +[CGP-E016] two `check_components!` tables in one module check `` +``` + +### CGP-E017 + +A `for` loop in the wiring binds a variable its key does not use. To fix it, write the variable in the key where the +type the loop covers goes. +[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. ```text -[CGP-E009] the trait `` is not implemented for context `` +[CGP-E017] the `for` loop in the wiring of `` binds ``, but its key `` does not use it ``` -**Fix:** follow the `root cause:` note to the dependency the trait needs. Explained in -[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met). +### CGP-E018 -### CGP-E010 +A `#[default_impl]` registers a provider whose impl is generic over a parameter the key does not fix. To fix it, write +the impl for that key alone, as the `help` line says. +[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. -**The wiring for a component never resolves**, because looking it up leads back to itself. Almost -always a component is wired to `UseContext` on a context whose only implementation of it is that very -wiring. +```text +[CGP-E018] `#[default_impl]` cannot register `` for ``, because the provider's impl is generic over `` +``` + +### CGP-E019 + +A wiring or namespace entry binds a generic parameter its key does not use. To fix it, write a concrete type in place of +the parameter and remove it from the entry's generic parameters, as the `help` line says. +[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. ```text -[CGP-E010] the wiring for the consumer trait `` on context `` never resolves — the lookup recurses without terminating +[CGP-E019] the entry for `` in the wiring of `` binds ``, but its key does not use it ``` -The compiler's code is `E0275`, and a `help` line names the usual cause. **Fix:** wire the component to -a real provider, or implement the consumer trait directly on the context. Explained in -[A lookup that never terminates](/docs/reference/errors#a-lookup-that-never-terminates). +### CGP-E060 -### CGP-E011 +A check entry names no parameters for a component that takes some, so it checks the component at the unit parameters +`()`, which the provider does not implement. To fix it, check it at the parameters the `help` line offers, with +`#[check_params(...)]` in `delegate_and_check_components!` or `:

` in `check_components!`. +[`check_components!`](/docs/reference/macros/check_components) describes the syntax. -**A crate registers wiring into a namespace it does not own, under a key it does not own either**, -which Rust's orphan rule forbids. +```text +[CGP-E060] the check of `` on `` names no parameters, so it checks the component at the unit parameters `()` +``` + +### CGP-E061 + +Two [`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch) traits in one module declare a method of the same +name, and the macro names its generated items after the method alone. To fix it, rename the method in one trait, or +declare the traits in different modules. ```text -[CGP-E011] cannot register the foreign into the foreign namespace `` +[CGP-E061] two `#[cgp_auto_dispatch]` traits in one module declare the method `` ``` -The compiler's code is `E0210` or `E0117`. **Fix:** own one end, as the `help` line says: key the -registration on a component your crate defines, register it from the crate that owns the namespace, or -define a namespace of your own that inherits the foreign one. Explained in -[Registering into a namespace you do not own](/docs/reference/errors#registering-into-a-namespace-you-do-not-own). +## Wiring that never resolves, and the orphan rule -### CGP-E012 +The next three codes cover wiring that is well formed but cannot work, either because looking it up never ends or because +Rust's coherence rules forbid it. + +### CGP-E020 -**A `#[cgp_fn]` or `#[cgp_impl]` body calls a CGP trait's method on `self` without declaring the trait -as a dependency.** The macro turns the body into an implementation over a generated context type, so a -trait the body uses has to be declared for that type to have it. +Looking up the wiring for a component leads back to itself. The plain case is a component wired to `UseContext` on a +context with no other implementation of it. The compiler's code is `E0275`. To fix it, wire a real provider, or implement +the consumer trait directly on the context. The `help` line names the provider that closes the loop. +[A lookup that never terminates](/docs/reference/errors#a-lookup-that-never-terminates) explains the class. ```text -[CGP-E012] the trait `` is used but not declared as a dependency +[CGP-E020] the wiring for the consumer trait `` on context `` never resolves, because the lookup leads back to itself ``` -The compiler's code is `E0599`. **Fix:** add the trait to `#[uses(...)]`, as the `help` line says. -Explained in -[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare). +### CGP-E021 -### CGP-E013 +Each step of the lookup requires the consumer trait again for a larger type, so nothing repeats, and the compiler stops +at its recursion limit. No limit ends a lookup that grows, so to fix it, wire a provider whose requirements do not grow. +[A lookup that never terminates](/docs/reference/errors#a-lookup-that-never-terminates) explains the class. -**A `#[cgp_impl]` header names the component's consumer trait where its provider trait belongs.** +```text +[CGP-E021] the wiring for the consumer trait `` on context `` never resolves, because each step requires it for a larger type (``, …) +``` + +### CGP-E022 + +A crate registers wiring into a namespace it does not own, under a key it does not own either, which Rust's orphan rule +forbids. The compiler's code is `E0210` or `E0117`. To fix it, own one end, as the `help` line says: key the registration +on a component your crate defines, register it from the crate that owns the namespace, or define a namespace of your own +that inherits the foreign one. +[Registering into a namespace you do not own](/docs/reference/errors#registering-into-a-namespace-you-do-not-own) +explains the class. ```text -[CGP-E013] `` is a consumer trait, but a `#[cgp_impl]` provider must implement its provider trait `` +[CGP-E022] cannot register the foreign into the foreign namespace `` ``` -Without the rewrite, this one mistake produces a burst of unrelated-looking errors. **Fix:** name the -provider trait in the header, as the `help` line says. Explained in -[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component). +## Mistakes in what a macro was given -### CGP-E014 +These codes name a CGP attribute or macro used in a way the generated code cannot compile. Most of them give the fix in a +`help` line. + +### CGP-E030 -**`#[cgp_impl]` is applied to a trait that is not a CGP component at all**, so there is no provider -trait to implement. +A `#[cgp_fn]` or `#[cgp_impl]` body calls a CGP trait's method on `self` or `Self` without declaring the trait as a +dependency. The macro turns the body into an implementation over a generated context type, so a trait the body uses has to +be declared for that type to have it. The compiler's code is `E0599`. To fix it, add the trait to `#[uses(...)]`, as the +`help` line says. +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. ```text -[CGP-E014] `#[cgp_impl]` can only implement a CGP component's provider trait, but `` is not a CGP component +[CGP-E030] the trait `` is used but not declared as a dependency ``` -**Fix:** make the trait a component with -[`#[cgp_component]`](/docs/reference/macros/cgp_component), or drop `#[cgp_impl]` and write an ordinary -`impl`. Explained in -[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component). +### CGP-E031 -### CGP-E015 +A higher-order provider calls an inner provider it never imported, so the inner provider has no provider-trait bound and +the call cannot resolve. To fix it, import it with `#[use_provider(: )]`, as the `help` line says. +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. + +```text +[CGP-E031] the inner provider `` is used but not imported +``` + +### CGP-E032 -**An inner-provider bound names a consumer trait where the provider trait belongs**, most often in -[`#[use_provider]`](/docs/reference/attributes/use_provider). +A `#[cgp_impl]` header names the component's consumer trait where its provider trait belongs. Without the rewrite, this one +mistake produces a burst of unrelated-looking errors. To fix it, name the provider trait in the header, as the `help` line +says. [Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the +class. ```text -[CGP-E015] `` is a consumer trait and cannot bound an inner provider; a higher-order provider imports its provider trait `` +[CGP-E032] `` is a consumer trait, but a `#[cgp_impl]` provider must implement its provider trait `` ``` -**Fix:** name the provider trait, as the `help` line says. Explained in -[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component). +### CGP-E033 -### CGP-E016 +`#[cgp_impl]` is applied to a trait that is not a CGP component at all, so there is no provider trait to implement. To fix +it, make the trait a component with [`#[cgp_component]`](/docs/reference/macros/cgp_component) and implement its provider +trait, or drop `#[cgp_impl]` and write an ordinary `impl`. +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the class. -**A higher-order provider calls an inner provider it never imported**, so the inner provider has no -provider-trait bound and the call cannot resolve. +```text +[CGP-E033] `#[cgp_impl]` can only implement a CGP component's provider trait, but `` is not a CGP component +``` + +### CGP-E034 + +An inner-provider bound names a consumer trait where the provider trait belongs, most often in +[`#[use_provider]`](/docs/reference/attributes/use_provider). To fix it, name the provider trait, as the `help` line says. +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the class. ```text -[CGP-E016] the inner provider `` is used but not imported +[CGP-E034] `` is a consumer trait and cannot bound an inner provider; a higher-order provider imports its provider trait `` ``` -**Fix:** import it with `#[use_provider(: )]`, as the `help` line says. Explained -in [Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare). +### CGP-E035 -### CGP-E017 +A `#[cgp_fn]`, `#[cgp_impl]`, or `#[cgp_component]` definition names an abstract type of the context, as `Self::Error` or a +bare `Error`, without [`#[use_type]`](/docs/reference/attributes/use_type). To fix it, import the type with +`#[use_type(.)]`, as the `help` line says, and write it bare. +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. -**An abstract type is wired one way and required another.** The context supplies one type for an -associated type, such as its error type, while a provider requires a different one. +```text +[CGP-E035] the abstract type `` is used but not imported +``` + +### CGP-E036 + +A component requires a trait of every context, through [`#[extend(...)]`](/docs/reference/attributes/extend) or +`#[use_type(...)]`, and a `#[cgp_impl]` provider does not declare it, even if its body never uses the trait. To fix it, add +the `#[uses(...)]` or `#[use_type(...)]` the `help` line names. +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. ```text -[CGP-E017] expected the abstract type `` of `` on `` to be ``, but found `` +[CGP-E036] the provider trait `` requires `` of the context, but the provider `` does not declare it ``` -For a trait that is not a CGP abstract-type component, the message says "associated type" instead. Like -`[CGP-E003]`, it shows a required type in both forms when it is written through another abstract type. -The compiler's code is `E0271`. **Fix:** make the two sides agree; for a -[`#[cgp_type]`](/docs/reference/macros/cgp_type) component, the `help` line names the `UseType` entry to -wire. Explained in -[When two decisions disagree about a type](/docs/reference/errors#when-two-decisions-disagree-about-a-type). +### CGP-E037 + +[`#[uses]`](/docs/reference/attributes/uses) names a provider trait, but a dependency names its consumer trait. To fix it, +name the consumer trait, as the `help` line says. +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the class. + +```text +[CGP-E037] `` is a provider trait and cannot be a `#[uses]` dependency; a dependency names its consumer trait `` +``` + +### CGP-E038 + +`#[cgp_impl(GreetHello)]` without `new` implements the provider trait for a struct nothing declares. To fix it, write +`#[cgp_impl(new GreetHello)]` so the macro declares it, or declare the struct yourself. A provider declared elsewhere but not +imported keeps the compiler's `E0425` and its import suggestion instead. +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) describes the syntax. -## Dependency-chain codes +```text +[CGP-E038] the provider `` is not declared +``` + +### CGP-E039 -These codes label the lines of the tree beneath a `root cause:` note. The first four are steps along -the way; the rest end the chain, and the cause they state is the one to fix. +A plain `impl` implements a provider trait. The trait has `IsProviderFor` as a supertrait, and only `#[cgp_provider]` or +`#[cgp_impl]` writes the provider's impl of it. To fix it, add one of those macros, as the `help` line says. +[`#[cgp_provider]`](/docs/reference/macros/cgp_provider) describes the macro. + +```text +[CGP-E039] the impl of `` for `` is written without `#[cgp_provider]` +``` + +## Wiring keys and values that do not resolve + +These codes replace a name-resolution error on a wiring entry, for a name the tool can settle. Each applies only when no +type of that name exists in your crate or its dependencies, or when the tool can say which name you meant. +[`delegate_components!`](/docs/reference/macros/delegate_components) describes what a key and a value may be. + +### CGP-E040 + +A wiring key names a consumer trait such as `CanGreet`, where its component marker `GreeterComponent` belongs. To fix it, name +the component, as the `help` line says. + +```text +[CGP-E040] the wiring key `` is a consumer trait, but a key names a component +``` + +### CGP-E041 + +A key names a component that exists but is not imported where the table is written, such as `ErrorTypeProviderComponent`, +which the prelude does not export. To fix it, add the `use` line the `help` line gives. + +```text +[CGP-E041] the component `` is not in scope +``` + +### CGP-E042 + +A key was guessed from a consumer trait's name with `Component` appended, such as `HasScalarTypeComponent`, while the marker +follows the provider trait, as in `ScalarTypeProviderComponent`. To fix it, name the component the `help` line gives. + +```text +[CGP-E042] the wiring key `` names no component +``` + +### CGP-E043 + +A wiring value names a provider struct nothing declares, often a misspelling. To fix it, declare the provider or name one that +exists. A `help` line appears when the component has a provider with a similar name. A provider declared elsewhere but not +imported keeps the compiler's `E0425` and its import suggestion instead. + +```text +[CGP-E043] the provider `` wired for `` is not declared +``` + +### CGP-E044 + +An `@`-path in a key, or in the value of a `=>` redirect, names a type nothing declares. A path segment that is not a lowercase +identifier stays the type it spells, and only a lowercase one becomes a symbol. So to fix it, declare or import the type, or +write the segment in lowercase. A type declared elsewhere but not imported keeps the compiler's `E0425` and its import +suggestion instead. + +```text +[CGP-E044] the type `` in a wiring path is not declared +``` + +## Extensible data + +### CGP-E050 + +A cast, builder, or extractor operation is called on a value whose field or variant is not in the state the operation needs, or +on a type without the data derive it needs. The headline states the cause, and the chain ends at one of the codes from +`[CGP-E118]` to `[CGP-E126]`, at `[CGP-E110]` for a missing field, or at `[CGP-E117]` for an ordinary bound. For example: + +```text +[CGP-E050] missing variant `Bar` on `Big` +``` + +Its class sentence is `` the trait `` is not implemented for `` ``. To fix it, follow the cause: drop a second +setting or extraction, set an unset field, add a missing variant or align a payload type, or add the derive or call the method a +`help` line names. [Extensible variants](/docs/concepts/extensible-variants) and +[extensible records](/docs/concepts/extensible-records) explain what those operations require. + +## Steps of the dependency chain + +The rest of the codes label the lines of the tree beneath a `root cause:` note. These four are steps along the way, and they need +no fix of their own. ### CGP-E101 -**A step through a context's consumer trait.** Usually the first line of the chain. +This line is a step through a context's consumer trait, and it is usually the first line of the chain. A type without wiring of +its own is named plainly, without the word "context". ```text [CGP-E101] consumer trait impl `` for context `` @@ -283,142 +497,234 @@ the way; the rest end the chain, and the cause they state is the one to fix. ### CGP-E102 -**A step through a provider's provider trait**: the context's wiring selected this provider, and the -chain continues with what the provider needs. +This line is a step through a provider's provider trait: the context's wiring selected this provider, and the chain continues with +what the provider needs. Directly above a `[CGP-E115]` line for the same provider, which has no such impl, it reads +`` provider trait `` required of provider `` with context `` ``. ```text [CGP-E102] provider trait impl `` with context `` for provider `` ``` +### CGP-E103 + +This line is a step through a redirected lookup, from an `open` statement or a namespace, naming the table the path is looked up in. + +```text +[CGP-E103] redirect lookup to `@` in `

` +``` + ### CGP-E104 -**A step through a redirected lookup**, from an `open` statement or a namespace, naming the table the -path is looked up in. +This line is a step through any other trait, such as a getter or a blanket trait you wrote. + +```text +[CGP-E104] trait impl `` for `` +``` + +## Where the chain ends + +These codes end the chain, and the cause they state is the one to fix. The `root cause:` line repeats the same code. + +### CGP-E110 + +The chain ends at a field the context does not have. To fix it, add the field, or wire a provider that does not read it. A `help` +line names a similar field when there is one, and otherwise the field to add. +[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met) explains the class. + +```text +[CGP-E110] missing field `` on `` +``` + +### CGP-E111 + +The chain ends at a field that exists but has no `HasField` impl, because the struct does not derive it. To fix it, add +`#[derive(HasField)]` to the struct, as the `help` line says. +[When the derive is missing entirely](/docs/reference/errors#when-the-derive-is-missing-entirely) explains the class. ```text -[CGP-E104] redirect lookup to `@` in `
` +[CGP-E111] `HasField` not derived for field `` of `` ``` -### CGP-E105 +### CGP-E112 -**A step through any other trait**, such as a getter or a blanket trait you wrote. +The chain ends at a field with the wrong type. This is the last line of a `[CGP-E004]` error, with the same wording. ```text -[CGP-E105] trait impl `` for `` +[CGP-E112] field `` on `` has type ``, but `` is required ``` -`CGP-E103` is not assigned. +### CGP-E113 -### CGP-E106 +The chain ends at a component or path the context wires nothing for. To fix it, add the wiring entry the `help` line names. +[Nothing is wired there](/docs/reference/errors#nothing-is-wired-there) explains the class. -**The chain ends at a field the context does not have.** +```text +[CGP-E113] missing wiring for `` on `` +``` + +### CGP-E114 + +The chain ends at a provider's own table that has no entry for a key: a bundle of wiring missing a component, or a provider that +dispatches per type missing the type it was given. To fix it, add the entry to that provider's table, or pass it a type the table +covers. ```text -[CGP-E106] missing field `` on `` +[CGP-E114] missing entry for `` in provider `` ``` -**Fix:** add the field, or wire a provider that does not read it. Explained in -[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met). +### CGP-E115 -### CGP-E107 +The chain ends at a type wired where a provider belongs that is not a provider, such as a value type put in a provider's place. To +fix it, wire an actual provider in that position. A `help` line suggests one when the program supports it: an adapter such as +`WithProvider`, `UseFields` in place of `UseField` on a multi-method getter, an `open` statement in place of `UseDelegate`, or the +right component for a provider of another one. -**The chain ends at a component or path the context wires nothing for.** +```text +[CGP-E115] `` is not a provider of `` +``` + +### CGP-E116 + +The chain ends at an associated type that differs from what was required. This is the last line of a `[CGP-E005]` error, with the +same wording. ```text -[CGP-E107] context `` does not contain any delegate entry for `` +[CGP-E116] abstract type `` of `` on `` is ``, but `` is required ``` -**Fix:** add the wiring entry. Explained in -[Nothing is wired there](/docs/reference/errors#nothing-is-wired-there). +### CGP-E117 + +The chain ends at an ordinary Rust trait bound that does not hold, such as `f64: Eq`, in the compiler's own wording. At a +`check_components!` entry the tool keeps the compiler's headline, which already names the bound. To fix it, use a type that implements +the trait, or a provider that does not require it. +[When the missing bound is an ordinary Rust trait](/docs/reference/errors#when-the-missing-bound-is-an-ordinary-rust-trait) explains the +class. + +```text +[CGP-E117] the trait bound `` is not satisfied +``` -### CGP-E108 +### CGP-E118 -**The chain ends at a field that exists but has no `HasField` impl**, because the struct does not derive -it. +A builder operation needs a field unset, as a second `build_field` or a second merge source does, and the field is already set. To fix +it, drop the second setting. ```text -[CGP-E108] accessor trait `HasField` with field `` is not implemented for `` +[CGP-E118] field `` of `` is already set ``` -**Fix:** add `#[derive(HasField)]` to the struct, as the `help` line says. Explained in -[When the derive is missing entirely](/docs/reference/errors#when-the-derive-is-missing-entirely). +### CGP-E119 -### CGP-E109 +An operation such as a finalize or `take_field` needs one or more fields set, and they are not. To fix it, set them first. -**The chain ends at a field with the wrong type.** It is the last line of a `[CGP-E003]` error. +```text +[CGP-E119] field `` of `` is not set +``` + +### CGP-E120 + +A cast between enums has variants that do not match, or a construction uses a tag the enum lacks. To fix it, add the variant or correct +the name. A `help` line names a similar variant when there is one. ```text -[CGP-E109] field `` on `` has type ``, but `` is required +[CGP-E120] missing variant `` on `` ``` -### CGP-E110 +### CGP-E121 -**The chain ends at a provider's own table that has no entry for a key**: a bundle of wiring missing a -component, or a provider that dispatches per type missing the type it was given. +An extractor is finalized while it may still yield a variant, as a matcher that leaves one out does. To fix it, handle the variant. ```text -[CGP-E110] provider `` does not contain any delegate entry for `` +[CGP-E121] variant `` of `` is not extracted ``` -**Fix:** add the entry to that provider's table, or pass it a type the table covers. +### CGP-E122 -### CGP-E111 +A cast between enums has same-named variants that carry different payloads. To fix it, align the payload types. + +```text +[CGP-E122] variant `` on `` has type ``, but `` is required +``` + +### CGP-E123 -**The chain ends at a type wired where a provider belongs that is not a provider**, such as a value -type put in a provider's place. +A trait only a data derive implements is required of a type that does not have it. To fix it, add the derive the `help` line names. ```text -[CGP-E111] the provider trait `` is not implemented for `` +[CGP-E123] `` does not implement `` ``` -**Fix:** wire an actual provider in that position. +### CGP-E124 -### CGP-E112 +A variant is extracted a second time from an extractor that no longer holds it. The compiler reports this as an `E0308` on the tag +argument. To fix it, drop the second extraction. + +```text +[CGP-E124] variant `` of `` is already extracted +``` + +### CGP-E125 + +An optional builder's operation is called on a field a core builder holds set or unset. To fix it, call `to_optional` on the builder +first, as the `help` line says. -**The chain ends at an associated type that differs from what was required.** It is the last line of a -`[CGP-E017]` error. +```text +[CGP-E125] field `` of `` is not optional +``` + +### CGP-E126 + +A builder or extractor is given to an operation that needs a trait only its struct or enum implements, as `downcast` on the remainder +of a downcast is. To fix it, call the method the `help` line names, such as `downcast_fields`. ```text -[CGP-E112] abstract type `` of `` on `` is ``, but `` is required +[CGP-E126] an extractor of `` does not implement `` ``` -## Root-cause codes +### CGP-E127 -A `root cause:` line normally carries the same code as the last line of its chain. This range covers -the case where that last line has no code. +A provider's impls differ from the wiring in exactly one argument: the context, or a component parameter, as for a pipeline stage that +takes `u64` after one that returns `String`. To fix it, wire a provider for those arguments, or change the type that disagrees. -### CGP-E201 +```text +[CGP-E127] `` implements `` only for ``, not `` +``` -**The chain ends at an ordinary Rust trait bound that does not hold**, such as `f64: Eq`. The last line -of the tree repeats the compiler's own wording without a code, and the `root cause:` line carries this -one. The line appears when the error has a CGP headline, as at a method call; at a -`check_components!` entry the tool keeps the compiler's own headline, which already names the bound, -and adds the chain without a `root cause:` line. +### CGP-E128 + +A hand-written `DelegateComponent` impl lacks the `IsProviderFor` impl `delegate_components!` writes beside each entry, so a check passes +but every consumer call fails. To fix it, replace the impl with `delegate_components!`, as the `help` line says. ```text -root cause: [CGP-E201] the trait bound `` is not satisfied +[CGP-E128] the wiring of `` on `` has no `IsProviderFor` impl ``` -**Fix:** use a type that implements the trait, or a provider that does not require it. Explained in -[When the missing bound is an ordinary Rust trait](/docs/reference/errors#when-the-missing-bound-is-an-ordinary-rust-trait). +### CGP-E129 + +A consumer method is called on a value of a type parameter without the bound. To fix it, add the bound the `help` line names. + +```text +[CGP-E129] the type parameter `` of `` is not bounded by `` +``` ## Rewrites without a code -Some changes make an error easier to read without classifying it, so they carry no code. You may see -them in an error whose headline the tool left as the compiler wrote it: - -- **Type-level names written back as you wrote them**: a field name as `Symbol!("name")`, a list as - `Product![A, B]` or `Sum![A, B]`, and a path as `Path!(@app.Component)`. A list of named or - numbered fields reads as the struct or enum body it describes, such as - [`Struct! { name: String }`](/docs/reference/macros/struct) or - [`Enum! { Circle(f64) }`](/docs/reference/macros/enum), when it has such a spelling. A path that - ends in an unknown part gets a trailing `.*`, which is not real `Path!` syntax. -- **Shorter type names**, with the CGP module paths the compiler prints in front of them removed. -- **A missing-field sentence** in place of an unmet `HasField` requirement inside a note. -- **Consumer and provider trait names** in the compiler's "required for … to implement …" notes, in - place of the generated traits that connect them. -- **Removed advice** that a method call should use associated-function syntax, which the compiler - suggests for CGP's provider methods and which does not fix the mistake. +Some changes make an error easier to read without classifying it, so they carry no code. You may see them in an error whose headline the +tool left as the compiler wrote it: + +- **Type-level names written back as you wrote them:** a field name reads `Symbol!("name")`, a list reads `Product![A, B]` or `Sum![A, B]`, + and a path reads `Path!(@app.Component)`. A list of named or numbered fields reads as the struct or enum body it describes, such as + [`Struct! { name: String }`](/docs/reference/macros/struct) or [`Enum! { Circle(f64) }`](/docs/reference/macros/enum), when it has such a + spelling. +- **Shorter type names:** the module paths the compiler prints in front of a type go, except a qualifier that tells two types apart, such + as `std::io::Error` beside a crate's own `Error`. +- **A missing-field sentence:** an unmet `HasField` requirement inside a note reads as a missing field. +- **Consumer and provider trait names:** the compiler's "required for … to implement …" notes name them in place of the generated traits + that connect them. +- **Removed advice:** the compiler's suggestion that a method call should use associated-function syntax goes, because it does not fix the + mistake for CGP's provider methods. +- **A better rename:** on a misspelled `#[use_type]` import, the compiler's suggestion to respell the name becomes one to rename it in the + import and in each use. --- diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 4c461f5b..0c6151e6 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -7,10 +7,10 @@ description: 'Print the Rust your CGP macros generate, narrowed to one module, t # Expand -`cargo cgp expand` prints your crate as the compiler sees it after macro expansion, so you can read what -a [CGP](/docs/) macro actually generated instead of reasoning about what it probably generated. It is -part of [`cargo-cgp`](./index.md), and it writes CGP's type-level constructs back in the form you wrote -them. +A [CGP](/docs/) macro generates code you never see, and sometimes the answer to a question is in that +code. `cargo cgp expand`, part of [`cargo-cgp`](./index.md), prints your crate as the compiler sees it +after macro expansion, so you can read what a macro actually generated instead of reasoning about what it +probably generated. It also writes CGP's type-level constructs back in the form you wrote them. ```sh cargo cgp expand --lib @@ -18,22 +18,24 @@ cargo cgp expand --lib ## When to use it -Reach for `expand` when the answer is in the generated code rather than in an error message: +Use `expand` when an error message does not answer your question and the generated code might. These +situations come up most often: -- **A diagnostic names a type you did not write**, such as - [`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for), a `PathCons` key, or a - `__Context__` parameter, and you want to see the impl it came from. -- **A wiring table does not resolve**, and you want its actual - [`DelegateComponent`](/docs/reference/traits/wiring/delegate_component) keys and providers rather - than inferring them from the table's syntax. -- **You are unsure what a construct emits**, such as the exact `where` clauses of a provider, or which - field a getter reads. -- **Two forms differ and only one compiles.** Expand both and compare the output. +- **A diagnostic names a type you did not write:** the message mentions + [`IsProviderFor`](/docs/reference/traits/wiring/is_provider_for), a `PathCons` key, or a `__Context__` + parameter, and you want to see the impl it came from. +- **A wiring table does not resolve:** you want its actual + [`DelegateComponent`](/docs/reference/traits/wiring/delegate_component) keys and providers rather than + inferring them from the table's syntax. +- **You are unsure what a construct emits:** you want the exact `where` clauses of a provider, or to see + which field a getter reads. +- **Two forms differ and only one compiles:** you can expand both and compare the output. ## What it looks like -This is the `Rectangle` program from the [Check page](./check.md#check-the-wiring-where-you-write-it) -with its `height` field restored, so the program compiles: +To see what the output looks like, take the `Rectangle` program from the +[Check page](./check.md#check-the-wiring-where-you-write-it) with its `height` field restored, so the +program compiles: ```rust use cgp::prelude::*; @@ -127,21 +129,19 @@ where impl __CheckRectangle for Rectangle {} ``` -Each part of the program is visible in the listing: - -- [`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) produced a pair of field accessors - for each field, keyed by the field's name. -- [`delegate_components!`](/docs/reference/macros/delegate_components) produced the one-line table - entry that selects `RectangleArea`, and an impl that passes the provider's requirements through to - `Rectangle`. -- [`check_components!`](/docs/reference/macros/check_components) produced the last line, the - assertion that `Rectangle` can use the component. +You can find each part of the program in this listing. +[`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) produced a pair of field accessors for +each field, keyed by the field's name. +[`delegate_components!`](/docs/reference/macros/delegate_components) produced the one-line table entry +that selects `RectangleArea`, and an impl that passes the provider's requirements through to `Rectangle`. +Finally, [`check_components!`](/docs/reference/macros/check_components) produced the last line, the +assertion that `Rectangle` can use the component. ## Narrowing with `--item` -**`--item` narrows the output to one module or item.** A whole crate's expansion is long: for this -small program it is 148 lines, against 49 for `Rectangle` alone. The option takes a `::`-separated -path naming something inside the crate, and what you get depends on what it names: +A whole crate's expansion is long: for this small program it is 148 lines, against 49 for `Rectangle` +alone. So `--item` narrows the output to one module or item. The option takes a `::`-separated path naming +something inside the crate, and what you get depends on what it names: ```sh cargo cgp expand --lib --item shapes # a module: its contents @@ -151,8 +151,8 @@ cargo cgp expand --lib --item AreaCalculator # a trait: its definition and e A leading `crate::` is accepted, so `--item crate::shapes` and `--item shapes` are the same request. -**Naming a component's provider trait is usually the most useful form**, because most of a -component's generated items are impls of it. For this program, `--item AreaCalculator` gives the +Naming a component's provider trait is usually the most useful form, because most of a component's +generated items are impls of it. For this program, `--item AreaCalculator` gives the provider trait itself, the blanket impl that lets a context's wiring pick the provider, the impls for the `UseContext` and `RedirectLookup` providers CGP generates for every component, and `RectangleArea`'s own impl, with the `where` clause that requires the two fields. Naming the consumer @@ -175,8 +175,8 @@ error: no expansion was produced; see the errors above ## Choosing a target -`expand` expands exactly one target, and its other arguments are passed to `cargo rustc`, so choosing -the target is cargo's job. A package with both a library and a binary needs to be told which one: +Because `expand` expands exactly one target and passes its other arguments to `cargo rustc`, choosing the +target is cargo's job. A package with both a library and a binary needs to be told which one: ```sh cargo cgp expand --lib @@ -184,7 +184,7 @@ cargo cgp expand --bin my-app cargo cgp expand -p my-crate --lib ``` -Without one, cargo declines, in a message that does not mention `expand`: +Without a choice, cargo declines, in a message that does not mention `expand`: ```text error: extra arguments to `rustc` can only be passed to one target, consider filtering @@ -199,16 +199,16 @@ cargo cgp expand --lib > expanded.rs cargo cgp expand --lib | grep 'Symbol!' ``` -`cargo cgp expand --help` prints the tool's own help for `expand`, which documents `--item`. That is -the one argument `expand` reads itself; for cargo's target-selection options, run `cargo rustc --help`. +`cargo cgp expand --help` prints the tool's own help for `expand`, which documents `--item`. That is the +one argument `expand` reads itself, so for cargo's target-selection options, run `cargo rustc --help`. ## Why not `cargo-expand` [`cargo-expand`](https://github.com/dtolnay/cargo-expand) is the general tool, and it works on CGP code. -The reason to use this one is that CGP's generated code is full of type-level constructs, which a -general expander prints the way the compiler stores them. +The reason to use this one is that CGP's generated code is full of type-level constructs, which a general +expander prints the way the compiler stores them. -**A field name is the clearest case.** CGP encodes it as a +A field name is the clearest case. CGP encodes it as a [type-level string](/docs/reference/glossary#type-level-string), with one type per character. In the compiler's own expansion, which is what a general expander formats, the `height` accessor above begins: @@ -229,25 +229,30 @@ than a chain of `Cons` cells, a derived field list reads [`Struct! { width: f64, height: f64 }`](/docs/reference/macros/struct), and a namespace key reads `Path!(@app.GreeterComponent)`. -`--item` is the other difference. It selects Rust items rather than filtering text: asking for a trait -gives every impl of that trait, wherever it sits in the crate, which is the shape a question about CGP -wiring usually takes. +`--item` is the other difference. It selects Rust items rather than filtering text, so asking for a trait +gives every impl of that trait, wherever it sits in the crate. A question about CGP wiring usually takes +that shape. ## What to expect from the output -**Every macro is expanded, not only CGP's.** `#[derive(Debug)]` and `println!` appear in their generated -form too. What is specific to CGP is how the type-level constructs are written. +Every macro is expanded, not only CGP's, so `#[derive(Debug)]` and `println!` appear in their generated +form too. Only the way the type-level constructs are written is specific to CGP. + +The output is for reading rather than compiling. The tool removes the `cgp::macro_prelude::` prefix the +macros put in front of every CGP name, which makes the listing readable but means it does not compile if +you paste it back into your crate. -**The output is for reading, not compiling.** The tool removes the `cgp::macro_prelude::` prefix the -macros put in front of every CGP name, which makes the listing readable and means it does not compile -if you paste it back into your crate. +`expand` is also not a check. Compilation stops once the macros are expanded, so no type checking runs, a +wiring mistake goes unreported, and the command exits with `0` on a crate that does not type-check. That +makes `expand` useful in the middle of debugging, but for the wiring mistake itself you need +[`cargo cgp check`](./check.md). -**`expand` is not a check.** Compilation stops once the macros are expanded, so no type checking runs -and no wiring error is reported. A malformed macro invocation still fails, because that happens during -expansion. This is what makes `expand` useful in the middle of debugging: it works on a crate that does -not type-check. For the wiring mistake itself, use [`cargo cgp check`](./check.md). +An error reported before that point does fail the command, with cargo's exit status. Most such errors, such +as a CGP macro rejecting its input, still print what expanded. A type defined twice, a `macro_rules!` call +that matches no rule, or an unclosed delimiter prints nothing. A closed pipe is not a failure, so +`cargo cgp expand --lib | head` exits as it normally would. -**It builds the way a check does.** `expand` uses the same pinned nightly and the same `target/cgp` +Finally, `expand` builds the way a check does. It uses the same pinned nightly and the same `target/cgp` directory as `cargo cgp check`, so the notes on the [Check page](./check.md#what-a-check-does-differently) apply to it too. diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index 1a29b52d..41ae20b3 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -8,22 +8,23 @@ description: 'cargo-cgp runs in place of cargo check and reports a CGP compile e # cargo-cgp [Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait -implementations at compile-time. `cargo-cgp` is its error toolchain: a cargo subcommand you run in -place of `cargo check` to read a CGP compile error with its root cause first, and to see the ordinary -Rust your CGP macros generate. +implementations at compile-time. Because its macros expand to ordinary Rust, a mistake in CGP code is +often reported in terms of generated traits you never wrote. `cargo-cgp` is the error toolchain that +helps you read those reports: a cargo subcommand you run in place of `cargo check` to see a CGP compile +error with its root cause first, and to see the ordinary Rust your CGP macros generate. -The tool is optional. CGP is a library on stable Rust, and `cargo check`, `cargo build`, and -`cargo test` work on a CGP project without it. Reach for `cargo-cgp` when an error is hard to read. +The tool is optional. CGP is a library on stable Rust, so `cargo check`, `cargo build`, and `cargo test` +all work on a CGP project without it, and you only need `cargo-cgp` when an error is hard to read. ## The problem it solves -**Some CGP mistakes produce a compiler error that does not contain its cause.** CGP's wiring is lazy: a +Some CGP mistakes produce a compiler error that does not contain its cause. CGP's wiring is lazy: a [`delegate_components!`](/docs/reference/macros/delegate_components) entry selects a provider without checking that the context can give the provider what it needs. That check happens later, where the trait is first used, and from there the compiler often cannot say what went wrong. -In this program, `RectangleArea` reads a `width` and a `height` field through -[`#[implicit]`](/docs/reference/attributes/implicit) arguments, and `Rectangle` has no `height`: +The following program shows the problem. `RectangleArea` reads a `width` and a `height` field through +[`#[implicit]`](/docs/reference/attributes/implicit) arguments, but `Rectangle` has no `height`: ```rust use cgp::prelude::*; @@ -107,94 +108,99 @@ help: use associated function syntax instead For more information about this error, try `rustc --explain E0599`. ``` -The message never mentions `height`. It describes the trait machinery CGP generated, and its closing -suggestion, calling `Rectangle::area()`, fixes a different problem. The cause is not buried in the -output: it is absent, because the compiler set the candidate implementation aside before working out -why it did not apply. +This message never mentions `height`. It describes the trait machinery CGP generated, and its closing +suggestion, calling `Rectangle::area()`, would fix a different problem. So the cause is not buried in +the output. It is absent, because the compiler set the candidate implementation aside before working +out why it did not apply. `cargo cgp check` reports the same mistake like this: ```text -error[E0599]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` +error[E0599]: [CGP-E001] missing field `height` on `Rectangle` --> src/lib.rs:28:30 | 28 | println!("{}", rectangle.area()); | ^^^^ | - = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + = note: root cause: [CGP-E110] missing field `height` on `Rectangle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` - └─ [CGP-E106] missing field `height` on `Rectangle` + └─ [CGP-E110] missing field `height` on `Rectangle` + = help: add the field `height: f64` to `Rectangle` For more information about this error, try `rustc --explain E0599`. ``` -The error code and the position are unchanged. The headline says which trait `Rectangle` fails to -implement, the `root cause:` line names the missing field, and the tree beneath it shows the chain of -requirements that led there. [Reading the output](./reading-output.md) explains each part. +The compiler's error code and the position stay the same, but the headline now states the cause. Below +it, the tree shows the chain of requirements that led from the call to the missing field, and the `help` +line gives the fix. [Reading the output](./reading-output.md) explains each part. ## How it works -**It compiles your code under Rust's next-generation trait solver, which computes the cause the -default solver leaves out.** The default solver stops at "the trait bounds were not satisfied" in the -case above; the next-generation solver works the failed requirement down to the missing -`HasField` bound. That is what gives the tool a root cause to print at all. +Two changes produce that message. The first is that the tool compiles your code under Rust's +next-generation trait solver, which computes the cause the default solver leaves out. In the case above, +the default solver stops at "the trait bounds were not satisfied", while the next-generation solver +works the failed requirement down to the missing `HasField` bound. Without that step, the tool would +have no root cause to print. -**It rewrites the errors it recognizes.** Where the tool knows the shape of a CGP failure, it leads with -the cause, draws the chain of requirements as a tree, and tags the message with a `[CGP-Exxx]` code -naming the class of mistake. The compiler's own code stays in the header, so `rustc --explain` still -works. Errors it does not recognize pass through as the compiler wrote them. +The second change is that the tool rewrites the errors it recognizes. Where it knows the shape of a CGP +failure, it leads with the cause, draws the chain of requirements as a tree, and tags the message with a +`[CGP-Exxx]` code naming the class of mistake. The compiler's own code stays in the header, so +`rustc --explain` still works, and an error the tool does not recognize passes through as the compiler +wrote it. ## The two commands -[**`cargo cgp check`**](./check.md) stands in for `cargo check` when you hit or expect a wiring error. -Everything after `check` is passed to `cargo check`, so the flags you already use work unchanged. +Most of the time you will use [`cargo cgp check`](./check.md), which stands in for `cargo check` when you +hit or expect a wiring error. Everything after `check` is passed to `cargo check`, so the flags you +already use work unchanged. -[**`cargo cgp expand`**](./expand.md) prints the Rust your CGP macros generated, with CGP's type-level -constructs written the way you wrote them: a field name reads `Symbol!("height")` rather than a list of -characters. Use it when you want to know what a macro produced rather than guess. +When you want to know what a macro produced rather than guess, use +[`cargo cgp expand`](./expand.md). It prints the Rust your CGP macros generated, with CGP's type-level +constructs written the way you wrote them, so a field name reads `Symbol!("height")` rather than a list +of characters. ## What it costs -**Installing it takes a nightly toolchain.** The tool embeds the Rust compiler, so it needs one exact -nightly with the compiler's development libraries, which is more than a gigabyte of disk. Setup -downloads that toolchain and builds a driver binary against it. Your project does not switch -toolchains: the nightly is used only for the tool's own check. +Installing the tool takes a nightly toolchain. Because the tool embeds the Rust compiler, it needs one +exact nightly with the compiler's development libraries, which is more than a gigabyte of disk. Setup +downloads that toolchain and builds a driver binary against it. Your project does not switch toolchains, +though, since the tool uses the nightly only for its own check. -**The first check rebuilds your dependencies.** A check builds into its own `target/cgp` directory -under that nightly, so the first run compiles every dependency once more and keeps a second set of -build artifacts beside your normal ones. Later checks reuse them. +The first check also rebuilds your dependencies. A check builds into its own `target/cgp` directory under +that nightly, so the first run compiles every dependency once more and keeps a second set of build +artifacts beside your normal ones. Later checks reuse them. If you work with a coding assistant, [CGP's agent skill](/docs/ai/skills) teaches it to run -`cargo cgp check` and read what comes back. That makes the error output cheaper to work through; it +`cargo cgp check` and read what comes back. That makes the error output cheaper to work through, but it does not replace reading the conclusion yourself. ## What it does not do -**It is not a build tool.** There is no `cargo cgp build`, `run`, or `test`. CGP compiles on stable Rust -1.89 or newer, so build, run, and test with ordinary cargo. +The tool is not a build tool: there is no `cargo cgp build`, `run`, or `test`. CGP compiles on stable Rust +1.89 or newer, so you build, run, and test with ordinary cargo. -**It does not decide whether your code compiles.** A check runs a different compiler and trait solver -from your project's, so treat it as a diagnostic pass, the way Clippy runs under its own settings. -Your own toolchain's `cargo check` is the authority on whether the code builds. +It also does not decide whether your code compiles. A check runs a different compiler and trait solver +from your project's, so treat it as a diagnostic pass, the way Clippy runs under its own settings. Your +own toolchain's `cargo check` is the authority on whether the code builds. -**It does not reshape every error.** `cargo cgp check` leads with the root cause for the classes it +Nor does it improve every error. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. -[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the ones that pass -through, and where to read about them instead. It also reshapes errors only in your workspace's own -crates. +[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the ones you are most +likely to meet and where to read about them instead. The tool also reshapes errors only in your +workspace's own crates. -**It is tested on Linux.** macOS and Windows have not been tested yet. +Finally, the tool is tested on Linux. macOS and Windows have not been tested yet. ## Where to go next -Start with installation, then the page for what you want to do: +Start with installation, then go to the page for what you want to do: - [Installation](./installation.md): installing with cargo or Nix, checking the install, updating, and uninstalling. - [Check](./check.md): running a check, and trying it on a deliberate mistake. -- [Reading the output](./reading-output.md): every shape of error the tool produces, part by part. +- [Reading the output](./reading-output.md): the shapes of error the tool produces, part by part. - [Expand](./expand.md): reading what your CGP macros generated. - [Editor integration](./editor-integration.md): rewritten errors in VS Code, every time you save. - [Troubleshooting](./troubleshooting.md): when the tool itself will not run. diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index 57027162..27f98a57 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -7,13 +7,14 @@ description: 'Install cargo-cgp v0.1.0 with cargo and rustup or with Nix, check # Installation -Install [`cargo-cgp`](./index.md) with cargo if your Rust comes from rustup, or with Nix if you use -Nix. This page covers version 0.1.0 of the tool, which is built for CGP v0.8. - -On the cargo path, installing takes two commands, because the tool comes in two parts. `cargo-cgp` is -the cargo subcommand you type. `cargo-cgp-driver` is the program it runs in place of the compiler, and -it embeds the compiler itself, so it has to be built against one exact nightly toolchain. You never -type that nightly's date, and **your project does not switch to it**: the tool uses the nightly for its +How you install [`cargo-cgp`](./index.md) depends on what your machine already uses: install it with +cargo if your Rust comes from rustup, or with Nix if you use Nix. This page covers version 0.1.0 of the +tool, which is built for CGP v0.8. + +The cargo path takes two commands because the tool comes in two parts. `cargo-cgp` is the cargo +subcommand you type, and `cargo-cgp-driver` is the program it runs in place of the compiler. The driver +embeds the compiler itself, so it has to be built against one exact nightly toolchain. You never type +that nightly's date, and your project does not switch to it, because the tool uses the nightly for its own check only. ## Which path to use @@ -29,33 +30,36 @@ Match what your machine already has to the path for it: ## With cargo +The first command installs the front end, and the second provisions everything else: + ```sh -cargo install cargo-cgp +cargo install --locked cargo-cgp cargo cgp setup ``` -**`cargo install cargo-cgp` installs the front end.** It is an ordinary binary with no compiler -inside, so it builds with whatever toolchain you already have. +The front end is an ordinary binary with no compiler inside, so `cargo install` builds it with the +toolchain you already have, which must be Rust 1.96 or newer. The `--locked` flag keeps the dependency +versions the release was tested with. -**`cargo cgp setup` does the rest.** It asks rustup to install the pinned nightly with the `rustc-dev` -and `llvm-tools` components, then builds `cargo-cgp-driver` at the same version as the front end under -that nightly, and places it beside the front end in `~/.cargo/bin`. It needs rustup and a network -connection, and it takes a while: the toolchain is more than a gigabyte, and the driver is compiled on -your machine. +`cargo cgp setup` then asks rustup to install the pinned nightly with the `rustc-dev` and `llvm-tools` +components. After that, it builds `cargo-cgp-driver` at the same version as the front end under that +nightly and places it beside the front end in `~/.cargo/bin`. This step needs rustup and a network +connection, and it takes a while, since the toolchain is more than a gigabyte and the driver is compiled +on your machine. -Run `setup` once after installing, and again only when the tool tells you to. Before every check the +You run `setup` once after installing, and again only when the tool tells you to. Before every check the front end runs a quick, read-only test of the toolchain and the driver. If either is missing or the two do not match, it stops with a message naming `cargo cgp setup` as the fix, rather than downloading anything on its own. [Troubleshooting](./troubleshooting.md#the-preflight-rejects-the-setup) lists those messages. `setup` and `update` take no options. Each answers `--help` with what it does instead of running, and -refuses any other argument rather than starting an install you did not ask for. +refuses any other argument, so a mistyped flag cannot start an install you did not ask for. ## With Nix The flake builds both binaries against the pinned nightly and wraps them so they find its libraries -without rustup. A machine with only Nix can run the tool this way. +without rustup, which means a machine with only Nix can run the tool: ```sh nix profile install github:contextgeneric/cargo-cgp/v0.1.0 @@ -75,7 +79,7 @@ inputs.cargo-cgp.url = "github:contextgeneric/cargo-cgp/v0.1.0"; ## Without installing To try the tool on a project without installing anything, run the flake's default app from that -project's directory. Everything after `--` is passed to the tool, so this is `cargo cgp check`: +project's directory. Everything after `--` is passed to the tool, so this runs `cargo cgp check`: ```sh cd /path/to/your/project @@ -84,15 +88,14 @@ nix run github:contextgeneric/cargo-cgp/v0.1.0 -- check ## Neither rustup nor Nix -**If your Rust comes from somewhere else, such as an operating system package, neither path works as -it stands.** The driver has to be built against one exact nightly with the compiler's development -libraries, and only rustup or the Nix flake provides that. Installing rustup alongside a packaged Rust -is the usual way forward. CGP itself does not need either: it compiles on any stable Rust 1.89 or -newer. +If your Rust comes from somewhere else, such as an operating system package, neither path works as it +stands. The driver has to be built against one exact nightly with the compiler's development libraries, +and only rustup or the Nix flake provides that. The usual way forward is to install rustup alongside your +packaged Rust. CGP itself needs neither, since it compiles on any stable Rust 1.89 or newer. ## Checking your install -Ask the front end for its version: +To confirm the front end is in place, ask it for its version: ```sh cargo cgp --version @@ -104,24 +107,24 @@ cargo-cgp 0.1.0 `cargo cgp --help` prints the same line first, followed by the list of commands. -The driver has its own version query, and it doubles as a test that the driver can run at all, because -the driver loads the compiler's libraries before printing anything: +The driver has its own version query, which doubles as a test that the driver can run at all, because the +driver loads the compiler's libraries before printing anything: ```sh cargo-cgp-driver --version ``` -On the cargo path that command runs under your default toolchain rather than the pinned nightly, so it -can fail with a library-loading error even when the install is fine: the front end sets up the -library path for the driver every time it runs it. Run the probe the way the front end would: +On the cargo path, that command runs under your default toolchain rather than the pinned nightly, so it +can fail with a library-loading error even when the install is fine. The front end sets up the library +path for the driver every time it runs it, so to probe the driver yourself you need to do the same: ```sh LD_LIBRARY_PATH="$(rustc +nightly-YYYY-MM-DD --print sysroot)/lib" cargo-cgp-driver --version ``` -where `nightly-YYYY-MM-DD` is the pinned nightly, the one `cargo cgp setup` installed and +Here `nightly-YYYY-MM-DD` is the pinned nightly, the one `cargo cgp setup` installed and `rustup toolchain list` now shows. A Nix-installed driver needs no library path and runs as it is. On -success it prints three lines: +success, the driver prints three lines: ```text cargo-cgp-driver 0.1.0 @@ -130,15 +133,15 @@ built-against-rustc: rustc 1.101.0-nightly (32dba69d6 2026-10-09) ``` The second line names the nightly the driver needs, and the third the compiler it was built with. Your -dates may differ from these; the lines are the way to read them. +dates may differ from these, so read them from your own output. ## Supported platforms and CGP versions -**The tool is tested on Linux.** It has not yet been tested on macOS or Windows. +The tool is tested on Linux, and it has not yet been tested on macOS or Windows. -**It is built for CGP v0.8.** The tool recognizes CGP's errors by the names of the traits and crates -CGP defines, so a project on an older CGP version compiles under it as it would under `cargo check`, -but whether its errors are reshaped has not been tested. +It is built for CGP v0.8. The tool recognizes CGP's errors by the names of the traits and crates CGP +defines, so a project on an older CGP version compiles under it as it would under `cargo check`, but +whether its errors are reshaped has not been tested. ## Updating @@ -152,39 +155,41 @@ It looks up the published versions on crates.io and does nothing if you already there is a newer one, it reinstalls the front end and runs the new version's `setup`, so the driver and the pinned nightly move with it. -On the Nix path there is no `cargo cgp update`. Change the version in the flake reference and reinstall +The Nix path has no `cargo cgp update`. Instead, change the version in the flake reference and reinstall the profile, or run `nix flake update cargo-cgp` in a flake that pins the tool as an input. ## Using it in CI -**Keep your own toolchain's `cargo check` as the gate, and add the tool for readable failures.** The -commands are the same as on your machine; pin them so a build does not change under you, either with +Keep your own toolchain's `cargo check` as the gate in CI, and add the tool for readable failures. The +commands are the same as on your machine, but pin them so a build does not change under you, either with `cargo install cargo-cgp --version 0.1.0 --locked` followed by `cargo cgp setup`, or with the tagged Nix reference. -On the cargo path every fresh machine downloads the pinned nightly and compiles the driver, which is -the slowest part of the install. If your CI service can cache directories between runs, caching +On the cargo path, every fresh machine downloads the pinned nightly and compiles the driver, which is the +slowest part of the install. If your CI service can cache directories between runs, caching `~/.cargo/bin` and the pinned nightly under `~/.rustup/toolchains/` avoids repeating that. This page does not cover any particular CI service, and these setups have not been run there. ## Uninstalling -Remove the binaries with whatever placed them; there is no `cargo cgp uninstall`. +There is no `cargo cgp uninstall`, so remove the binaries with whatever placed them: ```sh cargo uninstall cargo-cgp cargo-cgp-driver # cargo path: both, since setup installed the driver nix profile remove cargo-cgp # Nix path ``` -Neither removes the pinned nightly, since another tool may use the same toolchain. Remove it yourself -when nothing else needs it; its name is the `pinned-toolchain:` line of `cargo-cgp-driver --version`: +Neither command removes the pinned nightly, since another tool may use the same toolchain. Remove it +yourself when nothing else needs it. Its name is the `pinned-toolchain:` line of +`cargo-cgp-driver --version`: ```sh rustup toolchain uninstall nightly-YYYY-MM-DD ``` -Neither removes the `target/cgp` directories the tool built in your projects either. Delete them as you -would any build output, for example with `cargo clean --target-dir target/cgp` from the project's root. +The `target/cgp` directories the tool built in your projects also stay behind. Because each one sits +inside its project's target directory, `cargo clean` removes it along with your normal build output. To +remove only the tool's artifacts, run `cargo clean --target-dir target/cgp` from the project's root. ## From source @@ -198,16 +203,17 @@ cargo build ``` Then run the built front end in another project, pointing it at the built driver and turning off the -read-only test, which expects an installed setup: +read-only test, which expects an installed setup. With the test turned off, the tool does not switch to +the pinned nightly for you either, so select it yourself, or the driver will fail to load: ```sh -CARGO_CGP_NO_MANAGE=1 CARGO_CGP_DRIVER=/path/to/cargo-cgp/target/debug/cargo-cgp-driver \ +RUSTUP_TOOLCHAIN=nightly-YYYY-MM-DD CARGO_CGP_NO_MANAGE=1 \ + CARGO_CGP_DRIVER=/path/to/cargo-cgp/target/debug/cargo-cgp-driver \ /path/to/cargo-cgp/target/debug/cargo-cgp check ``` -With the test turned off, the tool does not switch to the pinned nightly for you either, so the project -you check must be using that nightly too, or the driver will fail to load. The Nix flake handles this -for you, so it is usually the easier way to run a checkout: from the project you want to check, run +The pinned nightly is the `channel` in the checkout's `rust-toolchain.toml`. The Nix flake handles all of +this for you, so it is usually the easier way to run a checkout: from the project you want to check, run `nix run /path/to/cargo-cgp -- check`. The [command reference](./command-reference.md#environment-variables) describes both variables. diff --git a/docs/cargo-cgp/reading-output.md b/docs/cargo-cgp/reading-output.md index b191ab43..b1bb39a1 100644 --- a/docs/cargo-cgp/reading-output.md +++ b/docs/cargo-cgp/reading-output.md @@ -7,11 +7,12 @@ description: 'How to read the errors cargo cgp check prints: the headline and it # Reading the output -`cargo cgp check`, part of the [`cargo-cgp`](./index.md) toolchain for -[Context-Generic Programming (CGP)](/docs/), prints ordinary compiler diagnostics, with the CGP errors -it recognizes rewritten into a few fixed shapes. This page takes each shape apart. Every example comes -from running the tool on a complete program; the snippets show the part of it that matters, and the -line numbers in the output refer to the whole file. Every `[CGP-Exxx]` code is listed on +When you hold an error from `cargo cgp check`, you want to know what failed, why, and what to change. The +command, part of the [`cargo-cgp`](./index.md) toolchain for +[Context-Generic Programming (CGP)](/docs/), prints ordinary compiler diagnostics, with the CGP errors it +recognizes rewritten into a few fixed shapes that answer those questions. This page takes each shape +apart. Every example comes from running the tool on a complete program. The snippets show the part of the +program that matters, so the line numbers in the output refer to the whole file. For a single code, see [Error codes](./error-codes.md). ## The parts of a rewritten error @@ -21,47 +22,50 @@ Most errors you will see have the shape of this one, from the lacks the `height` field its area provider reads: ```text -error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` +error[E0277]: [CGP-E001] missing field `height` on `Rectangle` --> src/lib.rs:29:9 | 29 | AreaCalculatorComponent, | ^^^^^^^^^^^^^^^^^^^^^^^ | - = note: root cause: [CGP-E106] missing field `height` on `Rectangle` + = note: root cause: [CGP-E110] missing field `height` on `Rectangle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` - └─ [CGP-E106] missing field `height` on `Rectangle` + └─ [CGP-E110] missing field `height` on `Rectangle` + = help: add the field `height: f64` to `Rectangle` For more information about this error, try `rustc --explain E0277`. ``` -Read it in four parts: +The error has five parts, and you can read them in the order they appear: -- **The compiler's code**, `error[E0277]`, is the one the compiler assigned, and it is always kept. A - rewritten error restates the compiler's error rather than replacing it, so `rustc --explain E0277` +- **The compiler's code:** `error[E0277]` is the code the compiler assigned, and the tool always keeps it. + A rewritten error restates the compiler's error rather than replacing it, so `rustc --explain E0277` still applies. -- **The headline** starts with a CGP code and says what failed, in CGP's terms. Here `[CGP-E001]` means - a context does not implement a consumer trait: `Rectangle` cannot use `CanCalculateArea`. -- **The `root cause:` line** says why, and it is the line that names the fix. Its code describes the - cause; `[CGP-E106]` is a missing field. -- **The dependency chain** shows how the requirement reached the cause, one step per line, read from - the top. `[CGP-E101]` is the context's consumer trait, `[CGP-E102]` is the provider wired for it, and - the last line repeats the root cause where the chain ends. - -The chain matters when the fix is not where the caret points. If the provider in the `[CGP-E102]` line -is not the one you meant to wire, the mistake is in the wiring rather than in the struct. - -The caret stays where the compiler put it: on the `check_components!` entry that asserted the -requirement, or on the call that used the trait when nothing checked it first. The -[Check page](./check.md#try-it-on-a-deliberate-mistake) shows the second case, where the compiler's -own message leaves the cause out entirely. +- **The headline:** it starts with a CGP code and states the cause. Here `[CGP-E001]` means a context + cannot use a consumer trait, and the rest of the line says why. +- **The `root cause:` line:** it repeats the cause under the code of its own kind, so `[CGP-E110]` is a + missing field. When the causes are of different kinds, this line lists them and the headline counts them. +- **The dependency chain:** it shows how the requirement reached the cause, one step per line, read from the + top. `[CGP-E101]` is the context's consumer trait, `[CGP-E102]` is the provider wired for it, and the last + line repeats the root cause where the chain ends. +- **The `help` line:** it names a fix, when the tool can confirm one. + +The chain matters when the fix is not where the caret points. If the provider in the `[CGP-E102]` line is +not the one you meant to wire, the mistake is in the wiring rather than in the struct, and adding the field +would hide it. + +The caret stays where the compiler put it: on the `check_components!` entry that asserted the requirement, +or on the call that used the trait when nothing checked it first. The +[Check page](./check.md#try-it-on-a-deliberate-mistake) shows the second case, where the compiler's own +message leaves the cause out entirely. ## Several causes in one error -When one requirement fails for more than one reason, the tool lists every cause under `root causes:` -and branches the chain to show each one. Here `Rectangle` has a `length` field and neither of the two -the provider reads: +One requirement can fail for more than one reason, and in that case the tool lists every cause under +`root causes:` and branches the chain to show each one. Here `Rectangle` has a `length` field and neither of +the two the provider reads: ```rust #[derive(HasField)] @@ -71,38 +75,39 @@ pub struct Rectangle { ``` ```text -error[E0277]: [CGP-E001] the consumer trait `CanCalculateArea` is not implemented for context `Rectangle` +error[E0277]: [CGP-E001] missing fields `width` and `height` on `Rectangle` --> src/lib.rs:28:9 | 28 | AreaCalculatorComponent, | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: root causes: - - [CGP-E106] missing field `height` on `Rectangle` - - [CGP-E106] missing field `width` on `Rectangle` + - [CGP-E110] missing field `width` on `Rectangle` + - [CGP-E110] missing field `height` on `Rectangle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` - ├─ [CGP-E106] missing field `height` on `Rectangle` - └─ [CGP-E106] missing field `width` on `Rectangle` + ├─ [CGP-E110] missing field `width` on `Rectangle` + └─ [CGP-E110] missing field `height` on `Rectangle` + = help: add the fields `width: f64` and `height: f64` to `Rectangle` For more information about this error, try `rustc --explain E0277`. ``` -Fix every listed cause before checking again. Plain `cargo check` reports only the `width` field for -this program, so fixing what it names would surface `height` on the next run. +Fix every listed cause before checking again. Plain `cargo check` reports only the `width` field for this +program, so fixing what it names would surface `height` on the next run. -The same merging works in the other direction. When several components fail because of one shared -mistake, such as a single missing field that three providers read, the tool reports one error whose -headline names all three consumer traits, rather than three errors with the same cause. +The same merging works in the other direction. When several components fail because of one shared mistake, +such as a single missing field that three providers read, the tool reports one error rather than three. Its +caret marks the first check entry, the other entries are labelled "also required here", and the chain +repeats once for each component. ## A component nothing is wired for -When the context has no wiring entry for a component at all, the chain is short, and its last line -names the entry that is missing. The examples from here on use `App`, a type that stands for an -application and carries its wiring, where the examples above used `Rectangle`, the shape being -measured. The error shapes are the same for both. Here `App` is checked for `FarewellComponent` but -wires only the greeter: +Sometimes the context has no wiring entry for a component at all. The chain is then short, and its last line +names the entry that is missing. The examples from here on use `App`, a type that stands for an application +and carries its wiring, where the examples above used `Rectangle`, the shape being measured. The error +shapes are the same for both. Here `App` is checked for `FarewellComponent` but wires only the greeter: ```rust delegate_components! { @@ -120,29 +125,30 @@ check_components! { ``` ```text -error[E0277]: [CGP-E001] the consumer trait `CanSayGoodbye` is not implemented for context `App` +error[E0277]: [CGP-E001] missing wiring for `FarewellComponent` on `App` --> src/lib.rs:31:9 | 31 | FarewellComponent, | ^^^^^^^^^^^^^^^^^ | - = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `FarewellComponent` + = note: root cause: [CGP-E113] missing wiring for `FarewellComponent` on `App` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanSayGoodbye` for context `App` - └─ [CGP-E107] context `App` does not contain any delegate entry for `FarewellComponent` + └─ [CGP-E113] missing wiring for `FarewellComponent` on `App` + = help: wire `FarewellComponent` to a provider in the wiring of `App` For more information about this error, try `rustc --explain E0277`. ``` -There is no `[CGP-E102]` line, because no provider was selected for the chain to pass through. Add the -entry, or remove the component from the check if the context is not meant to have it. When the -component is routed through a namespace or an `open` statement, the chain gains a `[CGP-E104]` line -naming the path the lookup followed, and the last line names that path rather than the component. +There is no `[CGP-E102]` line, because no provider was selected for the chain to pass through. To fix it, add +the entry, or remove the component from the check if the context is not meant to have it. When the component +is routed through a namespace or an `open` statement, the chain gains a `[CGP-E103]` line naming the path the +lookup followed, and the last line names that path rather than the component. ## A field with the wrong type -When the field exists but has the wrong type, the headline states the whole cause, so the error has -no separate `root cause:` line. Here `height` is a `u32` where the provider reads an `f64`: +A field can also exist but have the wrong type. The headline then states the whole cause, so the error has no +separate `root cause:` line. Here `height` is a `u32` where the provider reads an `f64`: ```rust #[derive(HasField)] @@ -153,7 +159,7 @@ pub struct Rectangle { ``` ```text -error[E0271]: [CGP-E003] expected a `height` field of type `f64` on `Rectangle`, but found `u32` +error[E0271]: [CGP-E004] field `height` on `Rectangle` has type `u32`, but `f64` is required --> src/lib.rs:29:9 | 29 | AreaCalculatorComponent, @@ -162,21 +168,20 @@ error[E0271]: [CGP-E003] expected a `height` field of type `f64` on `Rectangle`, = note: this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `RectangleArea` - └─ [CGP-E109] field `height` on `Rectangle` has type `u32`, but `f64` is required + └─ [CGP-E112] field `height` on `Rectangle` has type `u32`, but `f64` is required For more information about this error, try `rustc --explain E0271`. ``` -The chain still shows which provider needs the type, which tells you whether to change the field or -the provider. An [abstract type](/docs/concepts/abstract-types) wired one way and required another -produces the same shape with `[CGP-E017]`. +The chain still shows which provider needs the type, which tells you whether to change the field or the +provider. An [abstract type](/docs/concepts/abstract-types) wired one way and required another produces the +same shape with `[CGP-E005]`. ## An ordinary Rust trait that does not hold -Not every requirement is a CGP one. When a provider needs an ordinary trait that the wired type does -not implement, the compiler's own headline already states the cause, so the tool keeps it and adds -only the chain. Here `CompareScalars` requires `Scalar: Eq`, and `App` wires the scalar type to -`f64`, which is not `Eq`: +Not every requirement is a CGP one. When a provider needs an ordinary trait that the wired type does not +implement, the compiler's own headline already states the cause, so the tool keeps it and adds only the chain. +Here `CompareScalars` requires `Scalar: Eq`, and `App` wires the scalar type to `f64`, which is not `Eq`: ```rust #[cgp_impl(new CompareScalars)] @@ -208,27 +213,27 @@ error[E0277]: the trait bound `f64: Eq` is not satisfied = note: this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCompareScalars` for context `App` └─ [CGP-E102] provider trait impl `ScalarEquality` with context `App` for provider `CompareScalars` - └─ the trait bound `f64: Eq` is not satisfied + └─ [CGP-E117] the trait bound `f64: Eq` is not satisfied For more information about this error, try `rustc --explain E0277`. ``` -The last line of the chain repeats the compiler's words without a code, since it is not a CGP -requirement. Reached through a method call rather than a check, the same mistake gets a CGP headline -instead, and then the cause line carries `[CGP-E201]`, the code for an ordinary bound: +The last line of the chain repeats the compiler's words under `[CGP-E117]`, the code for an ordinary bound. +Reached through a method call rather than a check, the same mistake gets a CGP headline instead, because the +compiler's own headline there talks about the method: ```text - = note: root cause: [CGP-E201] the trait bound `f64: Eq` is not satisfied +error[E0599]: [CGP-E001] the trait bound `f64: Eq` is not satisfied ``` -The fix is in the types rather than the wiring: wire the scalar type to one that implements the trait, -or relax the provider's bound if it asks for more than it needs. The message names `f64` but not the +The fix is in the types rather than the wiring: wire the scalar type to one that implements the trait, or +relax the provider's bound if it asks for more than it needs. The message names `f64` but not the `UseType` entry that chose it, so that last step is yours. ## Two entries that claim one key -A wiring conflict is reported where it happens, with two carets and no chain. Here one context wires -the same component twice: +A wiring conflict looks different from the errors above, because it is reported where it happens, with two +carets and no chain. Here one context wires the same component twice: ```rust delegate_components! { @@ -240,7 +245,7 @@ delegate_components! { ``` ```text -error[E0119]: [CGP-E004] duplicate wiring for component `GreeterComponent` on `App` +error[E0119]: [CGP-E010] conflicting wiring: `App` wires component `GreeterComponent` twice --> src/lib.rs:27:9 | 26 | GreeterComponent: GreetHello, @@ -251,14 +256,14 @@ error[E0119]: [CGP-E004] duplicate wiring for component `GreeterComponent` on `A For more information about this error, try `rustc --explain E0119`. ``` -The two carets point at the two entries; remove the one you did not mean. The neighbouring codes -`[CGP-E005]` to `[CGP-E008]` cover the other ways two entries can claim one key, such as a path key -that covers a longer one, or an entry that collides with an `open` statement. +The two carets point at the two entries, so you only need to remove the one you did not mean. The neighbouring +codes `[CGP-E011]` to `[CGP-E014]` cover the other ways two entries can claim one key, such as a path key that +covers a longer one, or an entry that collides with an `open` statement. ## A fix in a `help` line -Some mistakes have one right fix, and the tool states it in a `help` line. Here a -[`#[cgp_fn]`](/docs/reference/macros/cgp_fn) function calls another CGP function on `self` without +Some mistakes have one right fix, and for those the `help` line matters more than anything else in the error. +Here a [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) function calls another CGP function on `self` without declaring it as a dependency: ```rust @@ -274,7 +279,7 @@ fn greeting(&self) -> String { ``` ```text -error[E0599]: [CGP-E012] the trait `PersonName` is used but not declared as a dependency +error[E0599]: [CGP-E030] the trait `PersonName` is used but not declared as a dependency --> src/lib.rs:10:32 | 10 | format!("Hello, {}!", self.person_name()) @@ -285,38 +290,40 @@ error[E0599]: [CGP-E012] the trait `PersonName` is used but not declared as a de For more information about this error, try `rustc --explain E0599`. ``` -Adding `#[uses(PersonName)]` under `#[cgp_fn]` on `greeting` fixes it, and the same error and fix -apply to a [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider body. The compiler's own message -for this mistake talks about a method that exists for `&__Context__`, a type parameter the macro -generated, and never names the missing attribute. The codes from `[CGP-E012]` to `[CGP-E016]` all work -this way, each for a different attribute or trait mistake. +Adding `#[uses(PersonName)]` under `#[cgp_fn]` on `greeting` fixes it, and the same error and fix apply to a +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider body. The compiler's own message for this mistake +talks about a method that exists for `&__Context__`, a type parameter the macro generated, and never names the +missing attribute. Most of the codes from `[CGP-E030]` to `[CGP-E044]` work this way, each for a different +mistake in what a macro was given. ## Errors that pass through unchanged -`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet -reshape every class. An error with no `[CGP-Exxx]` code anywhere in it, in the headline or in a -dependency chain beneath it, is one the tool passed through, so read it as the compiler wrote it. -These are the ones you are most likely to meet: +`cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape +every class. An error with no `[CGP-Exxx]` code anywhere in it, in the headline or in a dependency chain beneath +it, is one the tool passed through, so read it as the compiler wrote it. These are the ones you are most likely +to meet: -- **A per-entry generic that never reaches the key**, which the compiler reports as `E0207` twice, with - two suggested fixes of which only the second matches the mistake. See +- **A check on a generic context:** `check_components! { App { … } }` keeps the compiler's headline, though + its notes name the consumer and provider traits. Checking one concrete instance, such as `App`, gets the + usual error. +- **An unconstrained lifetime or blanket key:** a per-entry lifetime the provider uses, or a blanket entry keyed + by its own parameter, keeps the compiler's `E0207`, whose suggested fixes do not compile. See [A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing). -- **Errors in code a macro generated**, such as a shorthand that lowers to an unsized type, or an - imported type name that does not exist. These land on the macro's attribute. See +- **Errors in code a macro generated:** a shorthand that lowers to an unsized type, such as a getter returning + `Option<&Path>`, lands on the macro's attribute. See [A macro lowered something the compiler rejects](/docs/reference/errors#a-macro-lowered-something-the-compiler-rejects). -- **Failures of the extensible-data operations**: casts between enums, builders, extractors, and - dispatch over enum variants. Their errors name generated helper types rather than the variant or - field at fault. [Extensible variants](/docs/concepts/extensible-variants) and - [extensible records](/docs/concepts/extensible-records) explain what those operations require. -- **An undeclared trait called on a generic parameter other than the context**, such as - `value.describe()` on a `value: &Value` argument. The fix is a bound on `Value` rather than an - `#[uses(...)]` attribute, which only bounds the context, so the tool leaves the compiler's message, - which names `Value`, as it is. - -Errors in crates outside your workspace also pass through, because the tool reshapes only your -workspace's own crates. For any error that arrives raw, the -[compile-errors reference](/docs/reference/errors) starts from the compiler's own message and works -back to the mistake. +- **A bare `Error` that nothing explains:** a signature that names `Error` without + [`#[use_type]`](/docs/reference/attributes/use_type) gets the compiler's suggestion of + `std::error::Error`, because you may have meant that type. +- **An undeclared trait called on a generic parameter other than the context:** for `value.describe()` on a + `value: &Value` argument, the fix is a bound on `Value` rather than a `#[uses(...)]` attribute, which only + bounds the context. So the tool leaves the compiler's message, which names `Value`, as it is. +- **A lifetime requirement on a check entry:** a bare `E0477` gives the tool no chain to follow to the bound that + demands `'static`. + +Errors in crates outside your workspace also pass through, because the tool reshapes only your workspace's own +crates. For any error that arrives raw, the [compile-errors reference](/docs/reference/errors) starts from the +compiler's own message and works back to the mistake. --- diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index 8add2bb1..c2638a4a 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -8,13 +8,13 @@ description: 'Match an error from cargo-cgp itself to its cause and fix: the set # Troubleshooting This page is for when [`cargo-cgp`](./index.md) itself will not run, or behaves in a way you did not -expect. For help reading a CGP error the tool printed about your code, see -[Reading the output](./reading-output.md) instead. +expect. If instead you need help reading a CGP error the tool printed about your code, see +[Reading the output](./reading-output.md). -`cargo-cgp` is two programs and one exact nightly toolchain. The `cargo-cgp` front end looks for -`cargo-cgp-driver` in its own directory, and the driver loads the compiler's libraries from the pinned -nightly. Most failures come from one of those three not matching the others. The tool is tested on -Linux, and the library paths on this page are the Linux ones. +Most failures come from one fact about the tool: `cargo-cgp` is two programs and one exact nightly +toolchain, and all three must match. The `cargo-cgp` front end looks for `cargo-cgp-driver` in its own +directory, and the driver loads the compiler's libraries from the pinned nightly. The tool is tested on +Linux, so the library paths on this page are the Linux ones. ## Start with the symptom index @@ -23,151 +23,164 @@ Find the distinctive part of your error in the left column, then read the sectio | Error fragment | Cause | Section | |---|---|---| | `toolchain … is not available` | the pinned nightly is not installed | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | -| `is rustup on PATH?` | no rustup to find the pinned nightly with | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | | `could not run under toolchain` | the driver was built against another nightly | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | | `out of lockstep` | the front end and driver have different versions | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | -| `now provides` | the pinned nightly changed since the driver was built | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | -| `could not parse` … `--version` output | an old or unrelated driver binary | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `was built against` | the pinned nightly changed since the driver was built | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `could not parse the` … `--version` output | an old or unrelated driver binary | [The preflight rejects the setup](#the-preflight-rejects-the-setup) | +| `rustup was not found on PATH` | no rustup for the preflight or `setup` | [The preflight rejects the setup](#the-preflight-rejects-the-setup), [Setup fails](#setup-fails) | | `error while loading shared libraries: librustc_driver-…` | library path unset, or the wrong toolchain | [The driver cannot load the compiler](#the-driver-cannot-load-the-compiler) | -| `failed to run the cargo-cgp-driver at …` | driver missing | [The driver cannot be found](#the-driver-cannot-be-found) | +| `failed to run the cargo-cgp-driver` | driver missing | [The driver cannot be found](#the-driver-cannot-be-found) | | `could not execute process` … `(never executed)` | driver path wrong, with the preflight turned off | [The driver cannot be found](#the-driver-cannot-be-found) | -| `unknown cargo-cgp subcommand` | wrong command name | [The command itself fails](#the-command-itself-fails) | +| `` no such command: `frobnicate` `` with the four commands listed | wrong command name | [The command itself fails](#the-command-itself-fails) | +| `` no such command: `cgp` `` | the tool is not installed, or not on `PATH` | [The command itself fails](#the-command-itself-fails) | | `could not find Cargo.toml` | run outside a cargo package | [The command itself fails](#the-command-itself-fails) | | `unexpected argument` | a flag `cargo check` does not know | [The command itself fails](#the-command-itself-fails) | -| `rustup was not found on PATH` | `setup` needs rustup | [Setup fails](#setup-fails) | +| `is cargo on PATH?` | cargo is not installed, or not on `PATH` | [The command itself fails](#the-command-itself-fails) | +| `RUSTC_WORKSPACE_WRAPPER is set` | a compiler wrapper of your own will not run | [Your own compiler wrapper stopped running](#your-own-compiler-wrapper-stopped-running) | -Some problems print no error at all: a check that disagrees with `cargo check`, a slow first check, -and a compiler wrapper of your own that stopped running. Each has a section near the end of the page. +Some problems print no error at all: a check that disagrees with `cargo check`, and a slow first check. +Each has a section near the end of the page. ## Narrowing it down -**Run the check once more and read the first line of the error.** Before every check, the front end -runs a quick, read-only test of the toolchain and the driver, the preflight. A message beginning with -`cargo-cgp:` and ending with "Run `cargo cgp setup`" comes from that test, and the +If your error is not in the index, run the check once more and read the first line of what it prints. +Before every check, the front end runs a quick, read-only test of the toolchain and the driver, called the +preflight. A message that ends with `` help: run `cargo cgp setup` `` comes from that test, and the [preflight section](#the-preflight-rejects-the-setup) covers each one. -**If the preflight passes, run the check verbosely:** +If the preflight passes, run the check verbosely: ```sh cargo cgp check -v ``` Each `Running` line that shows a `cargo-cgp-driver … rustc …` command is cargo calling the driver for one -crate. An error before those lines is a front-end or setup problem; an error from one of them is a +crate. So an error before those lines is a front-end or setup problem, and an error from one of them is a driver or compiler problem. ## The preflight rejects the setup Almost every message in this section is resolved by running `cargo cgp setup`, which installs the pinned -nightly and rebuilds the driver against it at the front end's version. The messages tell you which part -was wrong. The examples show `nightly-2026-10-10`; yours names the nightly your build is pinned to. +nightly and rebuilds the driver against it at the front end's version. Even so, the messages are worth +reading, because they tell you which part was wrong. The examples show `nightly-2026-10-10`, and yours names +the nightly your build is pinned to. Each message about the driver also names the driver's path and where it +was found: from `CARGO_CGP_DRIVER`, beside `cargo-cgp`, or on `PATH`. -**The pinned nightly is not installed:** +The first thing the preflight checks is that the pinned nightly is installed. When it is not, the preflight +quotes rustup's own reason: ```text -cargo-cgp: toolchain `nightly-2026-10-10` is not available (exit status: 1) +error: toolchain `nightly-2026-10-10` is not available: -The pinned toolchain is not installed. Run `cargo cgp setup`. + error: toolchain 'nightly-2026-10-10-x86_64-unknown-linux-gnu' is not installed + help: run `rustup toolchain install nightly-2026-10-10-x86_64-unknown-linux-gnu` to install it + +help: run `cargo cgp setup` ``` -**There is no rustup to ask.** The front end finds the pinned nightly through rustup, so on a machine -without it the same advice appears with a different first line: +The front end finds the pinned nightly through rustup, so a machine without rustup gets a different message. +Here `setup` cannot help, since it needs rustup too: ```text -cargo-cgp: failed to run `rustc` (is rustup on PATH?) +error: rustup was not found on PATH, and cargo-cgp installs and selects its toolchain `nightly-2026-10-10` through rustup -The pinned toolchain is not installed. Run `cargo cgp setup`. +help: install rustup, or install cargo-cgp through its Nix flake, which needs no rustup ``` -Here `setup` cannot help, since it needs rustup too; install rustup, or use the -[Nix flake](./installation.md#with-nix), which does not run the preflight. +The [Nix flake](./installation.md#with-nix) runs the front end without the preflight. -**The toolchain is installed, but the driver cannot run under it**, almost always because the driver -was built against a different nightly: +Next, the driver has to run under the toolchain. When the toolchain is installed but the driver cannot load +it, the driver was almost always built against a different nightly, and the message keeps the loader's words: ```text -cargo-cgp: the cargo-cgp-driver could not run under toolchain `nightly-2026-10-10` (it was likely built against a different nightly). Run `cargo cgp setup`. +error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) could not run under toolchain `nightly-2026-10-10` (it was likely built against a different nightly): + + /home/you/.cargo/bin/cargo-cgp-driver: error while loading shared libraries: librustc_driver-1a6e695c833ebcd1.so: cannot open shared object file: No such file or directory + +help: run `cargo cgp setup` ``` -**The driver runs, but its version differs from the front end's.** This follows a partial upgrade, or -an older driver found first: +A driver that runs can still be the wrong one. After a partial upgrade, or when an older driver is found first, +its version differs from the front end's: ```text -cargo-cgp: the installed cargo-cgp-driver is version 0.0.9, but this cargo-cgp is 0.1.0 (the two are out of lockstep) +error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) is version 0.0.9, but this cargo-cgp is 0.1.0 (the two are out of lockstep) -Run `cargo cgp setup`. +help: run `cargo cgp setup` ``` -**The driver was built by a different compiler than the pinned nightly now provides.** The driver and -the toolchain the front end expects no longer belong together, even though their versions match: +Even when their versions match, the driver and the toolchain may no longer belong together, if a different +compiler built the driver than the pinned nightly now provides: ```text -cargo-cgp: the cargo-cgp-driver was built against `rustc 1.99.0-nightly (0123abcde 2026-08-01)`, but the pinned toolchain `nightly-2026-10-10` now provides `rustc 1.101.0-nightly (32dba69d6 2026-10-09)` +error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) was built against `rustc 1.99.0-nightly (0000000 2026-01-01)`, but toolchain `nightly-2026-10-10` provides `rustc 1.101.0-nightly (32dba69d6 2026-10-09)` -Run `cargo cgp setup`. +help: run `cargo cgp setup` ``` -**The program found as the driver does not answer like one**, such as an unrelated binary with the +Finally, the program found as the driver may not answer like one at all, such as an unrelated binary with the same name: ```text -cargo-cgp: could not parse `cargo-cgp-driver --version` output. Run `cargo cgp setup`. +error: could not parse the `--version` output of the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) + +help: run `cargo cgp setup` ``` -If you are deliberately running a build that `setup` did not install, from a source checkout for -example, set `CARGO_CGP_NO_MANAGE=1` to skip the preflight. The tool then trusts your environment, and -keeping the toolchain matched is up to you; the next section describes what happens when it is not. +If you are deliberately running a build that `setup` did not install, from a source checkout for example, set +`CARGO_CGP_NO_MANAGE=1` to skip the preflight. The tool then trusts your environment, and keeping the toolchain +matched is up to you. The next section describes what happens when it is not. ## The driver cannot load the compiler -**This failure comes from the operating system's loader, before the driver's own code runs**, which is -why it looks unlike any other message from the tool: +This failure comes from the operating system's loader, before the driver's own code runs, which is why it looks +unlike any other message from the tool: ```text -cargo-cgp-driver: error while loading shared libraries: librustc_driver-61d225838afd1915.so: cannot open shared object file: No such file or directory +cargo-cgp-driver: error while loading shared libraries: librustc_driver-1a6e695c833ebcd1.so: cannot open shared object file: No such file or directory ``` -The driver links `librustc_driver-.so` from the nightly it was built against, and the hash is -fixed when the driver is built, so yours differs from the one above. The loader could not find that -exact library, for one of two reasons. +The driver links `librustc_driver-.so` from the nightly it was built against, and the hash is fixed when +the driver is built, so yours differs from the one above. The loader could not find that exact library, for one +of two reasons. -**You ran the driver yourself, without the library path.** The front end sets the path every time it -runs the driver, so a working install still fails this way when you run `cargo-cgp-driver` directly. -Supply the pinned nightly's `lib` directory: +One reason is that you ran the driver yourself, without the library path. The front end sets the path every time +it runs the driver, so a working install still fails this way when you run `cargo-cgp-driver` directly. To fix +that, supply the pinned nightly's `lib` directory: ```sh LD_LIBRARY_PATH="$(rustc +nightly-YYYY-MM-DD --print sysroot)/lib" cargo-cgp-driver --version ``` -with the pinned nightly in place of `nightly-YYYY-MM-DD`. A driver installed with Nix has the path built -in and does not need this. +Put the pinned nightly in place of `nightly-YYYY-MM-DD`. A driver installed with Nix has the path built in and +does not need this. -**The check ran under a different toolchain from the driver's.** With the preflight turned off, the -tool uses whichever toolchain is active, and when that is not the driver's nightly, cargo's first call +The other reason is that the check ran under a different toolchain from the driver's. With the preflight turned +off, the tool uses whichever toolchain is active, and when that is not the driver's nightly, cargo's first call to the driver fails: ```text error: process didn't exit successfully: `…/cargo-cgp-driver …/stable-…/bin/rustc -vV` (exit status: 127) --- stderr -…/cargo-cgp-driver: error while loading shared libraries: librustc_driver-61d225838afd1915.so: cannot open shared object file: No such file or directory +…/cargo-cgp-driver: error while loading shared libraries: librustc_driver-1a6e695c833ebcd1.so: cannot open shared object file: No such file or directory ``` -Unset `CARGO_CGP_NO_MANAGE` so the tool switches to the pinned nightly itself, or make that nightly the -active toolchain, for example with `RUSTUP_TOOLCHAIN`. Running through the Nix flake also handles it. +In that case, unset `CARGO_CGP_NO_MANAGE` so the tool switches to the pinned nightly itself, or make that nightly +the active toolchain, for example with `RUSTUP_TOOLCHAIN`. Running through the Nix flake also handles it. ## The driver cannot be found -**The front end looks for the driver in its own directory**, unless `CARGO_CGP_DRIVER` names another -path, and looks on your `PATH` only when the driver is not there. When the driver is missing, the preflight reports it: +The front end looks for the driver in its own directory, unless `CARGO_CGP_DRIVER` names another path, and looks +on your `PATH` only when the driver is not there. When it finds no driver at all, the preflight reports it: ```text -cargo-cgp: failed to run the cargo-cgp-driver at /path/to/cargo-cgp-driver: No such file or directory (os error 2) +error: failed to run the cargo-cgp-driver (none is beside cargo-cgp or on PATH): No such file or directory (os error 2) -Run `cargo cgp setup`. +help: run `cargo cgp setup` ``` -With the preflight turned off by `CARGO_CGP_NO_MANAGE`, the missing driver reaches cargo instead, which -reports a compiler wrapper it could not start: +With the preflight turned off by `CARGO_CGP_NO_MANAGE`, the missing driver reaches cargo instead, which reports a +compiler wrapper it could not start: ```text error: could not execute process `/path/to/cargo-cgp-driver …/stable-…/bin/rustc -vV` (never executed) @@ -176,77 +189,100 @@ Caused by: No such file or directory (os error 2) ``` -Either way, make the driver reachable. Run `cargo cgp setup` to install it beside the front end, point -`CARGO_CGP_DRIVER` at the real binary (`target/debug/cargo-cgp-driver` in a source checkout), or run -through the Nix flake, which installs both together. Keep the two in the same directory: if the driver -is missing there, the front end falls back to any `cargo-cgp-driver` on your `PATH`, which may be an -older one. +Either way, the fix is to make the driver reachable. Run `cargo cgp setup` to install it beside the front end, +point `CARGO_CGP_DRIVER` at the real binary (`target/debug/cargo-cgp-driver` in a source checkout), or run through +the Nix flake, which installs both together. Keep the two in the same directory, because when the driver is +missing there, the front end falls back to any `cargo-cgp-driver` on your `PATH`, which may be an older one. ## The command itself fails -These failures happen before the driver is involved. An unknown command is reported with the list the -tool accepts: +Some failures happen before the driver is involved. An unknown command is reported with the list the tool accepts: ```text -cargo-cgp: unknown cargo-cgp subcommand `frobnicate` (expected `check`, `expand`, `setup`, or `update`) +error: no such command: `frobnicate` + +help: the commands are `check`, `expand`, `setup`, and `update` ``` -**Running outside a cargo package** produces cargo's error rather than the tool's, because the tool -runs `cargo check`: +When the unknown command is `cgp` itself, the message comes from cargo rather than the tool. Cargo found no +`cargo-cgp` on `PATH`, so the tool is not installed, or not on this shell's `PATH`: + +```text +error: no such command: `cgp` +``` + +Running outside a cargo package also produces cargo's error rather than the tool's, because the tool runs +`cargo check`: ```text error: could not find `Cargo.toml` in `/some/dir` or any parent directory ``` -**A flag `cargo check` does not know** is rejected by cargo, since every argument after `check` is -passed to it: +Similarly, cargo rejects a flag `cargo check` does not know, since every argument after `check` is passed to it: ```text error: unexpected argument '--nope' found ``` +If cargo itself is not on `PATH`, the front end reports that when it tries to run the check: + +```text +error: failed to run `cargo check` (is cargo on PATH?) + +Caused by: + No such file or directory (os error 2) +``` + ## Setup fails `cargo cgp setup` installs the toolchain through rustup, so without rustup it stops at once: ```text -cargo-cgp: installing toolchain `nightly-2026-10-10` (with rustc-dev, llvm-tools)… -cargo-cgp: rustup was not found on PATH; cargo-cgp requires rustup to manage toolchains + Installing toolchain `nightly-2026-10-10` with rustc-dev and llvm-tools +error: rustup was not found on PATH, and `cargo cgp setup` installs the toolchain `nightly-2026-10-10` through rustup + +help: install rustup, or install cargo-cgp through its Nix flake, which needs no rustup ``` -Install through the [Nix flake](./installation.md#with-nix) instead, which needs no rustup, or install -rustup first. `setup` also downloads the toolchain and the driver's source, so it needs a network -connection; a failure during either step comes from rustup or cargo, and their message says what went -wrong. +As the message says, you can install through the [Nix flake](./installation.md#with-nix) instead, or install +rustup first. `setup` also downloads the toolchain and the driver's source, so it needs a network connection. A +failure during either step comes from rustup or cargo, and their message says what went wrong. ## The check disagrees with `cargo check` -**Your own toolchain's `cargo check` decides whether your code compiles.** A check runs a different -compiler, a pinned nightly, with Rust's next-generation trait solver turned on, so on code that relies -on nightly-only or solver-specific behavior the two can disagree. When they do, trust `cargo check`, -and use the tool for what it is for: reading the CGP errors both of them report. +Your own toolchain's `cargo check` decides whether your code compiles. A check runs a different compiler, a pinned +nightly, with Rust's next-generation trait solver turned on, so on code that relies on nightly-only or +solver-specific behavior the two can disagree. For example, two namespaces that inherit from each other are rejected +by stable Rust and pass the check. When the two disagree, trust `cargo check`, and use the tool for what it is for: +reading the CGP errors both of them report. ## The first check is slow -**The first check in a project builds every dependency once more**, into `target/cgp` inside your -project's target directory, because the check uses its own toolchain and keeps its artifacts apart -from your normal build. Later checks reuse them, from wherever in the project you run them. +The first check in a project builds every dependency once more, into `target/cgp` inside your project's target +directory, because the check uses its own toolchain and keeps its artifacts apart from your normal build. Later +checks reuse them, from wherever in the project you run them. ## Your own compiler wrapper stopped running -**The tool sets cargo's `RUSTC_WORKSPACE_WRAPPER` to its driver for the length of a check**, which -replaces any value you set yourself, so a wrapper you configured through that variable does not run -during `cargo cgp check`. Your normal builds are unaffected. +The tool sets cargo's `RUSTC_WORKSPACE_WRAPPER` to its driver for the length of a check, which replaces any value +you set yourself, so a wrapper you configured through that variable does not run during `cargo cgp check`. The tool +says so when it happens, and your normal builds are unaffected: + +```text +warning: RUSTC_WORKSPACE_WRAPPER is set to `/usr/local/bin/my-wrapper`; cargo-cgp replaces it with its driver for this run, so that wrapper does not run +``` + +A wrapper given through `RUSTC_WRAPPER`, such as `sccache`, does keep running alongside the driver. ## Still stuck -Most of these failures share one root: **the nightly the driver embeds is not the toolchain present -when it runs.** If you are between sections, `cargo cgp setup` puts the expected pair back in place on -the cargo path, and reinstalling the profile does the same on the Nix path. +Most of these failures share one root: the nightly the driver embeds is not the toolchain present when it runs. So +if you are between sections, `cargo cgp setup` puts the expected pair back in place on the cargo path, and reinstalling +the profile does the same on the Nix path. Failures not covered here are worth reporting on the -[issue tracker](https://github.com/contextgeneric/cargo-cgp/issues). Include the output of -`cargo cgp check -v`, `cargo cgp --version`, and the driver's `--version` run as shown +[issue tracker](https://github.com/contextgeneric/cargo-cgp/issues). Include the output of `cargo cgp check -v`, +`cargo cgp --version`, and the driver's `--version` run as shown [above](#the-driver-cannot-load-the-compiler). --- From ba570af4e27a3d0192bbce73c9fd2ede4364f771 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 2 Nov 2026 00:25:02 +0100 Subject: [PATCH 189/516] Bring the site's quotes and claims in line with the release Quote what `cargo cgp check` prints now across the reference, the concept and tutorial pages, and the project pages. Pages describing `cgp` behavior follow the release: no variant name is reserved, a companion keeps only documentation, a provider's `Self::CONST` is its own, and an async default body works. Several mistakes the macros now reject say so with their own message. The example-code crate patches `cgp` to the sibling checkout, since the repository's `main` lacks those changes, and its snapshots are blessed against it. Co-Authored-By: Claude Opus 5.5 --- docs/concepts/check-traits.md | 7 +- .../architecture/dispatch-layers.md | 2 +- .../expression/examples/add-mult-code.md | 4 +- .../expression/examples/add-mult-neg.md | 4 +- .../expression/examples/add-mult.md | 4 +- .../web-app/examples/coarse-grained.md | 4 +- .../web-app/examples/default-impls.md | 2 +- .../web-app/examples/fine-grained.md | 4 +- .../web-app/examples/namespaces.md | 8 +- docs/projects/cgp-serde/examples/events.md | 4 +- docs/projects/cgp-serde/examples/messages.md | 4 +- .../cgp-serde/guides/debugging-wiring.md | 39 ++- .../hypershell/examples/bluesky-websocket.md | 4 +- .../hypershell/examples/hello-name.md | 4 +- .../examples/http-checksum-native.md | 4 +- docs/projects/hypershell/guides/debugging.md | 22 +- docs/reference/attributes/uses.md | 6 +- docs/reference/derives/derive_build_field.md | 22 -- docs/reference/derives/derive_cgp_data.md | 13 +- docs/reference/derives/derive_cgp_record.md | 5 - docs/reference/derives/derive_cgp_variant.md | 15 -- .../reference/derives/derive_extract_field.md | 25 -- docs/reference/derives/derive_from_variant.md | 10 +- docs/reference/derives/derive_has_fields.md | 14 +- docs/reference/derives/index.md | 8 +- docs/reference/errors.md | 233 ++++++++++-------- docs/reference/macros/async_trait.md | 29 ++- docs/reference/macros/cgp_auto_dispatch.md | 5 +- docs/reference/macros/cgp_auto_getter.md | 13 +- docs/reference/macros/cgp_component.md | 30 +-- docs/reference/macros/cgp_computer.md | 8 +- docs/reference/macros/cgp_getter.md | 2 +- docs/reference/macros/cgp_impl.md | 31 +-- docs/reference/macros/cgp_namespace.md | 10 +- docs/reference/macros/cgp_provider.md | 4 +- docs/reference/macros/check_components.md | 5 +- docs/reference/macros/delegate_components.md | 5 +- docs/reference/macros/path.md | 11 - docs/reference/traits/builder/has_builder.md | 5 +- docs/reference/traits/shape/from_fields.md | 4 +- docs/reference/traits/shape/has_fields.md | 4 - docs/reference/traits/shape/has_fields_ref.md | 4 - docs/reference/traits/shape/to_fields.md | 2 +- docs/reference/traits/shape/to_fields_ref.md | 2 +- .../reference/traits/variant/extract_field.md | 3 - docs/reference/traits/variant/from_variant.md | 8 +- .../reference/traits/variant/has_extractor.md | 4 +- .../traits/variant/has_extractor_mut.md | 2 +- .../traits/variant/has_extractor_ref.md | 2 +- docs/reference/types/chars.md | 2 +- docs/resources.md | 2 +- docs/tutorials/area-calculation/checking.md | 15 +- example-code/Cargo.toml | 5 + example-code/README.md | 8 +- example-code/tests/cargo_cgp/mod.rs | 2 +- .../blog/v0_8_0_missing_height.stderr | 4 +- ...check_the_wiring_where_you_write_it.stderr | 4 +- ..._output_several_causes_in_one_error.stderr | 4 +- ...traits_where_the_failure_surfaces_2.stderr | 4 +- ...handlers_plain_composition_is_wrong.stderr | 2 +- ...mpl_common_mistakes_table_parameter.stderr | 2 +- .../use_provider_usage_component_trait.stderr | 2 +- ...use_type_common_mistakes_misspelled.stderr | 2 +- ...ses_common_mistakes_component_trait.stderr | 12 +- ...ommon_mistakes_owned_input_computer.stderr | 4 +- ..._common_mistakes_field_helper_attribute.rs | 14 -- ...mon_mistakes_field_helper_attribute.stderr | 8 - ...ected_build_from_without_has_fields.stderr | 6 +- ...eld_rejected_read_of_an_unset_field.stderr | 6 +- ..._data_rejected_struct_style_variant.stderr | 2 +- ...ariant_common_mistakes_reserved_variant.rs | 13 - ...nt_common_mistakes_reserved_variant.stderr | 20 -- ...riant_rejected_struct_style_variant.stderr | 2 +- ..._field_common_mistakes_reserved_variant.rs | 16 -- ...ld_common_mistakes_reserved_variant.stderr | 20 -- ...ommon_mistakes_variant_helper_attribute.rs | 16 -- ...n_mistakes_variant_helper_attribute.stderr | 12 - ...t_field_rejected_premature_finalize.stderr | 2 +- ...tract_field_rejected_variant_shapes.stderr | 2 +- ...ariant_common_mistakes_reserved_variant.rs | 11 - ...nt_common_mistakes_reserved_variant.stderr | 20 -- ...riant_rejected_struct_style_variant.stderr | 2 +- ...fields_common_mistakes_reserved_variant.rs | 10 - ...ds_common_mistakes_reserved_variant.stderr | 20 -- .../reference/errors_the_fix_1.stderr | 4 +- ...sync_trait_common_mistakes_default_body.rs | 13 - ..._trait_common_mistakes_default_body.stderr | 10 - ...stakes_hand_impl_on_extensible_enum.stderr | 1 - ...atch_common_mistakes_missing_derive.stderr | 4 +- ...ommon_mistakes_missing_variant_impl.stderr | 2 +- ..._common_mistakes_shared_method_name.stderr | 2 +- ...common_mistakes_field_name_mismatch.stderr | 2 +- ...getter_common_mistakes_option_slice.stderr | 33 +-- ...nent_common_mistakes_misplaced_uses.stderr | 12 +- ...t_common_mistakes_unnamed_parameter.stderr | 9 +- ...mmon_mistakes_mismatched_error_type.stderr | 4 +- ..._common_mistakes_missing_error_type.stderr | 2 +- ...mistakes_output_only_type_parameter.stderr | 17 +- ...n_mistakes_use_field_on_two_methods.stderr | 8 +- ...on_mistakes_provider_const_through_self.rs | 22 -- ...istakes_provider_const_through_self.stderr | 16 -- ...ace_common_mistakes_self_inheriting.stderr | 8 +- ...omponents_examples_wrong_field_name.stderr | 4 +- ...th_common_mistakes_letter_digit_segment.rs | 6 - ...ommon_mistakes_letter_digit_segment.stderr | 10 - ...ommon_mistakes_variant_derive_shape.stderr | 2 +- ...tputs_common_mistakes_ref_component.stderr | 2 +- ...dlers_common_mistakes_fallible_slot.stderr | 2 +- ...mon_mistakes_borrowed_fallible_slot.stderr | 2 +- ...ndlers_common_mistakes_struct_input.stderr | 4 +- ...e_from_common_mistakes_missing_from.stderr | 2 +- ...common_mistakes_multi_method_getter.stderr | 8 +- ...es_bare_use_field_on_type_component.stderr | 8 +- ...d_ref_common_mistakes_unsized_value.stderr | 4 +- ...d_field_common_mistakes_build_twice.stderr | 6 +- ...mmon_mistakes_downcast_on_remainder.stderr | 2 +- ..._default_common_mistakes_no_default.stderr | 2 +- ...mon_mistakes_optional_needs_default.stderr | 2 +- ...field_common_mistakes_extract_twice.stderr | 6 +- ...ract_common_mistakes_finalize_early.stderr | 2 +- ...sult_common_mistakes_missing_import.stderr | 2 +- ...sult_common_mistakes_one_step_early.stderr | 2 +- ...ected_build_from_without_has_fields.stderr | 6 +- ...eld_common_mistakes_misspelled_name.stderr | 4 +- ..._common_mistakes_missing_dependency.stderr | 4 +- ...s_common_mistakes_output_not_mapped.stderr | 2 +- ...tional_common_mistakes_core_builder.stderr | 12 +- ...c_string_common_mistakes_bare_chars.stderr | 2 +- ...e_field_common_mistakes_take_absent.stderr | 6 +- ...al_common_mistakes_already_optional.stderr | 2 +- ...ommon_mistakes_missing_source_state.stderr | 4 +- ...ap_fields_common_mistakes_bare_call.stderr | 12 +- ...common_mistakes_marker_not_inferred.stderr | 13 +- ...ld_common_mistakes_undeclared_field.stderr | 6 +- ...on_mistakes_reading_a_missing_field.stderr | 4 +- .../types/life_definition_not_send.stderr | 4 +- ...n_mistakes_match_behind_a_reference.stderr | 2 +- .../area_calculation_checking_miswired.stderr | 4 +- 138 files changed, 434 insertions(+), 840 deletions(-) delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.stderr delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.stderr delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs delete mode 100644 example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr delete mode 100644 example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs delete mode 100644 example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.stderr delete mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs delete mode 100644 example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.stderr delete mode 100644 example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs delete mode 100644 example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.stderr diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index fcef33bd..b1d7dada 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -123,15 +123,14 @@ with readable field names and dependency chains. For this missing-field case, it identifies both the unavailable trait and its cause: ```text -error[E0277]: [CGP-E001] the consumer trait `CanSendEmail` is not implemented - for context `BrokenApp` +error[E0277]: [CGP-E001] missing field `sent_emails` on `BrokenApp` | - = note: root cause: [CGP-E106] missing field `sent_emails` on `BrokenApp` + = note: root cause: [CGP-E110] missing field `sent_emails` on `BrokenApp` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanSendEmail` for context `BrokenApp` └─ [CGP-E102] provider trait impl `EmailSender` with context `BrokenApp` for provider `RecordEmails` - └─ [CGP-E106] missing field `sent_emails` on `BrokenApp` + └─ [CGP-E110] missing field `sent_emails` on `BrokenApp` ``` The root cause is now explicit: `BrokenApp` lacks `sent_emails`, which `RecordEmails` requires. diff --git a/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md b/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md index 5909a94f..e8c21768 100644 --- a/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md +++ b/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md @@ -75,7 +75,7 @@ it for each operand, which is the same question, and it never finishes. With the the wiring never resolves: ```text -error[E0275]: [CGP-E010] the wiring for the consumer trait `CanCompute` on context `Interpreter` never resolves — the lookup recurses without terminating +error[E0275]: [CGP-E020] the wiring for the consumer trait `CanCompute` on context `Interpreter` never resolves, because the lookup leads back to itself ``` The same error follows for `Plus` and `Times`, and two raw overflow errors for the dispatcher diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-code.md b/docs/projects/cgp-examples/expression/examples/add-mult-code.md index 2de5377d..e25150aa 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-code.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-code.md @@ -157,8 +157,8 @@ Remove the conversion entry for `Plus`, the line its key: ```text -error[E0277]: [CGP-E001] the consumer trait `CanComputeRef>` is not implemented for context `Interpreter` - = note: root cause: [CGP-E107] context `Interpreter` does not contain any delegate entry for `@ComputerRefComponent.ToLisp.Plus` +error[E0277]: [CGP-E001] missing wiring for `@ComputerRefComponent.ToLisp.Plus` on `Interpreter` + = note: root cause: [CGP-E113] missing wiring for `@ComputerRefComponent.ToLisp.Plus` on `Interpreter` ``` Evaluating a `Plus` still has its entry, so only conversion is broken. Two more errors point at the diff --git a/docs/projects/cgp-examples/expression/examples/add-mult-neg.md b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md index 4f0fd76b..db144607 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult-neg.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult-neg.md @@ -156,8 +156,8 @@ Run [`cargo cgp check`](/docs/cargo-cgp/check), and the check reports that conve wired: ```text -error[E0277]: [CGP-E001] the consumer trait `CanComputeRef` is not implemented for context `InterpreterPlus` - = note: root cause: [CGP-E107] context `InterpreterPlus` does not contain any delegate entry for `@ComputerRefComponent.ToLisp.MathPlusExpr` +error[E0277]: [CGP-E001] missing wiring for `@ComputerRefComponent.ToLisp.MathPlusExpr` on `InterpreterPlus` + = note: root cause: [CGP-E113] missing wiring for `@ComputerRefComponent.ToLisp.MathPlusExpr` on `InterpreterPlus` ``` Supporting it would be a second group of `ToLisp` entries beside the `Eval` ones, with a provider diff --git a/docs/projects/cgp-examples/expression/examples/add-mult.md b/docs/projects/cgp-examples/expression/examples/add-mult.md index 7ec86354..3729356a 100644 --- a/docs/projects/cgp-examples/expression/examples/add-mult.md +++ b/docs/projects/cgp-examples/expression/examples/add-mult.md @@ -291,8 +291,8 @@ Remove the evaluation entry for `Times`, the line [`cargo cgp check`](/docs/cargo-cgp/check). The check names the missing entry: ```text -error[E0277]: [CGP-E001] the consumer trait `CanCompute>` is not implemented for context `Interpreter` - = note: root cause: [CGP-E107] context `Interpreter` does not contain any delegate entry for `@ComputerComponent.Eval.Times` +error[E0277]: [CGP-E001] missing wiring for `@ComputerComponent.Eval.Times` on `Interpreter` + = note: root cause: [CGP-E113] missing wiring for `@ComputerComponent.Eval.Times` on `Interpreter` ``` A second, longer error points at the wrapper's call to `MatchWithValueHandlers`, because the diff --git a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md index 703dec7c..b73e9c91 100644 --- a/docs/projects/cgp-examples/web-app/examples/coarse-grained.md +++ b/docs/projects/cgp-examples/web-app/examples/coarse-grained.md @@ -153,8 +153,8 @@ Remove the censor's entry, the line `UsernameCensorComponent: DummyUserCensor,`, [`cargo cgp check`](/docs/cargo-cgp/check). The whole user manager fails: ```text -error[E0277]: [CGP-E001] the consumer trait `CanManageUser` is not implemented for context `ProductionApp` - = note: root cause: [CGP-E107] context `ProductionApp` does not contain any delegate entry for `UsernameCensorComponent` +error[E0277]: [CGP-E001] missing wiring for `UsernameCensorComponent` on `ProductionApp` + = note: root cause: [CGP-E113] missing wiring for `UsernameCensorComponent` on `ProductionApp` ``` The context has lost `get_user` and `update_user_data` as well as `create_user`, though neither diff --git a/docs/projects/cgp-examples/web-app/examples/default-impls.md b/docs/projects/cgp-examples/web-app/examples/default-impls.md index 8b3638b0..a6b34865 100644 --- a/docs/projects/cgp-examples/web-app/examples/default-impls.md +++ b/docs/projects/cgp-examples/web-app/examples/default-impls.md @@ -157,7 +157,7 @@ and wire it in `ProductionApp`, beside the namespace line: Run [`cargo cgp check`](/docs/cargo-cgp/check), and the entry is rejected: ```text -error[E0119]: [CGP-E005] `ProductionApp` cannot wire `@app.core.user.UserGetterComponent.*` that is already set through `DefaultAppComponents` +error[E0119]: [CGP-E011] conflicting wiring: `ProductionApp` wires `@app.core.user.UserGetterComponent`, which `DefaultAppComponents` already covers ``` A default a namespace binds is final. The context's entry would be a second answer to the same diff --git a/docs/projects/cgp-examples/web-app/examples/fine-grained.md b/docs/projects/cgp-examples/web-app/examples/fine-grained.md index 06c0df25..e00d9427 100644 --- a/docs/projects/cgp-examples/web-app/examples/fine-grained.md +++ b/docs/projects/cgp-examples/web-app/examples/fine-grained.md @@ -165,8 +165,8 @@ Remove `UsernameCensorComponent` from the last list, so the censor has no entry, [`cargo cgp check`](/docs/cargo-cgp/check). This time only the operation that uses the censor fails: ```text -error[E0277]: [CGP-E001] the consumer traits `CanCreateUser` and `CanCensorUsername` are not implemented for context `ProductionApp` - = note: root cause: [CGP-E107] context `ProductionApp` does not contain any delegate entry for `UsernameCensorComponent` +error[E0277]: [CGP-E001] missing wiring for `UsernameCensorComponent` on `ProductionApp` + = note: root cause: [CGP-E113] missing wiring for `UsernameCensorComponent` on `ProductionApp` ``` Getting and updating users still check, because their providers need only the database. In the diff --git a/docs/projects/cgp-examples/web-app/examples/namespaces.md b/docs/projects/cgp-examples/web-app/examples/namespaces.md index 4a58f61b..931cc282 100644 --- a/docs/projects/cgp-examples/web-app/examples/namespaces.md +++ b/docs/projects/cgp-examples/web-app/examples/namespaces.md @@ -145,10 +145,10 @@ Remove `TestApp`'s `@app.extra` line, and run [`cargo cgp check`](/docs/cargo-cg creators fail, each with the filter its wrapper uses: ```text -error[E0277]: [CGP-E001] the consumer traits `CanCreateUser` and `CanCensorUsername` are not implemented for context `TestApp` - = note: root cause: [CGP-E107] context `TestApp` does not contain any delegate entry for `@app.extra.content_filter.UsernameCensorComponent` -error[E0277]: [CGP-E001] the consumer traits `CanCreatePost` and `CanDetectSpamMessage` are not implemented for context `TestApp` - = note: root cause: [CGP-E107] context `TestApp` does not contain any delegate entry for `@app.extra.content_filter.SpamMessageDetectorComponent` +error[E0277]: [CGP-E001] missing wiring for `@app.extra.content_filter.UsernameCensorComponent` on `TestApp` + = note: root cause: [CGP-E113] missing wiring for `@app.extra.content_filter.UsernameCensorComponent` on `TestApp` +error[E0277]: [CGP-E001] missing wiring for `@app.extra.content_filter.SpamMessageDetectorComponent` on `TestApp` + = note: root cause: [CGP-E113] missing wiring for `@app.extra.content_filter.SpamMessageDetectorComponent` on `TestApp` ``` Each root cause names the full path the namespace routed the lookup to, which says where the entry diff --git a/docs/projects/cgp-serde/examples/events.md b/docs/projects/cgp-serde/examples/events.md index 97140f6b..1a4c7426 100644 --- a/docs/projects/cgp-serde/examples/events.md +++ b/docs/projects/cgp-serde/examples/events.md @@ -178,8 +178,8 @@ fails on the three types that contain an event, and the tool names the missing e cause: ```text -error[E0277]: [CGP-E001] the consumer traits `CanDeserializeValue`, `CanDeserializeValue>`, and `CanDeserializeValue` are not implemented for context `ServerApp` - = note: root cause: [CGP-E107] context `ServerApp` does not contain any delegate entry for `@ValueDeserializerComponent.Nil` +error[E0277]: [CGP-E001] missing wiring for `@ValueDeserializerComponent.Nil` on `ServerApp` + = note: root cause: [CGP-E113] missing wiring for `@ValueDeserializerComponent.Nil` on `ServerApp` ``` `HistoryCleared` carries `Nil`, so reading an event asks the context to read `Nil`, even though no diff --git a/docs/projects/cgp-serde/examples/messages.md b/docs/projects/cgp-serde/examples/messages.md index 957cf302..1609fc4a 100644 --- a/docs/projects/cgp-serde/examples/messages.md +++ b/docs/projects/cgp-serde/examples/messages.md @@ -266,8 +266,8 @@ Remove `i64` from `AppB`'s `UseSerde` entry, leaving `[u64, String]`, and run missing entry as the root cause: ```text -error[E0277]: [CGP-E001] the consumer traits `CanSerializeValue>`, `CanSerializeValue`, `CanSerializeValue`, and `CanSerializeValue` are not implemented for context `AppB` - = note: root cause: [CGP-E107] context `AppB` does not contain any delegate entry for `@ValueSerializerComponent.i64` +error[E0277]: [CGP-E001] missing wiring for `@ValueSerializerComponent.i64` on `AppB` + = note: root cause: [CGP-E113] missing wiring for `@ValueSerializerComponent.i64` on `AppB` ``` Every checked type that contains a date fails, and all for one reason. Below the root cause, the diff --git a/docs/projects/cgp-serde/guides/debugging-wiring.md b/docs/projects/cgp-serde/guides/debugging-wiring.md index 63756767..cc398c5e 100644 --- a/docs/projects/cgp-serde/guides/debugging-wiring.md +++ b/docs/projects/cgp-serde/guides/debugging-wiring.md @@ -51,17 +51,17 @@ check_components! { The check fails on `Payload`, and the tool names the missing entry, then the path that leads to it: ```text -error[E0277]: [CGP-E001] the consumer trait `CanSerializeValue` is not implemented for context `App` - = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `@ValueSerializerComponent.Vec` +error[E0277]: [CGP-E001] missing wiring for `@ValueSerializerComponent.Vec` on `App` + = note: root cause: [CGP-E113] missing wiring for `@ValueSerializerComponent.Vec` on `App` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanSerializeValue` for context `App` - └─ [CGP-E104] redirect lookup to `@ValueSerializerComponent` in `App` + └─ [CGP-E103] redirect lookup to `@ValueSerializerComponent` in `App` └─ [CGP-E102] provider trait impl `ValueSerializer` with context `App` for provider `SerializeRecordFields` - └─ [CGP-E105] trait impl `FieldsSerializer` for `Struct! { quantity: u64, data: Vec }` - └─ [CGP-E105] trait impl `FieldsSerializer` for `Struct! { data: Vec }` + └─ [CGP-E104] trait impl `FieldsSerializer` for `Struct! { quantity: u64, data: Vec }` + └─ [CGP-E104] trait impl `FieldsSerializer` for `Struct! { data: Vec }` └─ [CGP-E101] consumer trait impl `CanSerializeValue>` for context `App` - └─ [CGP-E104] redirect lookup to `@ValueSerializerComponent` in `App` - └─ [CGP-E107] context `App` does not contain any delegate entry for `@ValueSerializerComponent.Vec` + └─ [CGP-E103] redirect lookup to `@ValueSerializerComponent` in `App` + └─ [CGP-E113] missing wiring for `@ValueSerializerComponent.Vec` on `App` ``` The chain reads from the top down: serializing `Payload` goes to `SerializeRecordFields`, which @@ -79,8 +79,8 @@ in the data has the type. because walking the vector by reference yields `&u64`: ```text -error[E0277]: [CGP-E001] the consumer trait `CanSerializeValue>` is not implemented for context `Ctx` - = note: root cause: [CGP-E107] context `Ctx` does not contain any delegate entry for `@ValueSerializerComponent.&u64` +error[E0277]: [CGP-E001] missing wiring for `@ValueSerializerComponent.&u64` on `Ctx` + = note: root cause: [CGP-E113] missing wiring for `@ValueSerializerComponent.&u64` on `Ctx` ``` The fix is the generic reference entry, `@ValueSerializerComponent.<'a, T> &'a T: SerializeDeref`, @@ -98,8 +98,8 @@ context. Hex, base64, and RFC 3339 dates need `String` the same way. The arena example, with the allocator entry removed, the check on the borrowed types reports: ```text -error[E0277]: [CGP-E001] the consumer traits `CanDeserializeValue<&Coord>` and `CanDeserializeValue>` are not implemented for context `App<'_>` - = note: root cause: [CGP-E107] context `App<'_>` does not contain any delegate entry for `AllocatorComponent` +error[E0277]: [CGP-E001] missing wiring for `AllocatorComponent` on `App<'_>` + = note: root cause: [CGP-E113] missing wiring for `AllocatorComponent` on `App<'_>` ``` The fix is the entry `AllocatorComponent: AllocateWithArena`, or another allocation provider; see @@ -158,11 +158,11 @@ Plain `cargo check` reports only that the method exists for `Ctx` but its trait satisfied. `cargo cgp check` names what is missing: ```text -error[E0599]: [CGP-E009] the trait `CanDeserializeJsonString<_>` is not implemented for context `Ctx` +error[E0599]: [CGP-E003] the trait `CanDeserializeJsonString<_>` is not implemented for context `Ctx` = note: root causes: - - [CGP-E107] context `Ctx` does not contain any delegate entry for `@ValueDeserializerComponent` - - [CGP-E107] context `Ctx` does not contain any delegate entry for `ErrorTypeProviderComponent` - - [CGP-E107] context `Ctx` does not contain any delegate entry for `ErrorRaiserComponent` + - [CGP-E113] missing wiring for `@ValueDeserializerComponent` on `Ctx` + - [CGP-E113] missing wiring for `ErrorTypeProviderComponent` on `Ctx` + - [CGP-E113] missing wiring for `ErrorRaiserComponent` on `Ctx` ``` The two error entries are the real causes. The first cause appears because the call failed before @@ -195,12 +195,11 @@ check_components! { The check reports that the wiring never resolves: ```text -error[E0275]: [CGP-E010] the wiring for the consumer trait `CanSerializeValue` on context `Ctx` never resolves — the lookup recurses without terminating +error[E0275]: [CGP-E020] the wiring for the consumer trait `CanSerializeValue` on context `Ctx` never resolves, because the lookup leads back to itself ``` -The help line printed below it suggests a component delegated back to the context itself, as with -`UseContext`, which is the usual cause of this class; here the cycle runs through the provider -instead, and the headline's consumer trait names the type to look at. Without the check, the first +Its help line names the provider to replace, the one that requires the same consumer trait on the same +context again, and the headline's consumer trait names the type to look at. Without the check, the first call reports the compiler's raw overflow error instead, `E0275`, "overflow evaluating the requirement", naming the adapter that was passed to `serde_json`. The fix is a provider for the in-between type that asks for nothing, such as @@ -231,7 +230,7 @@ delegate_components! { ``` ```text -error[E0275]: [CGP-E010] the wiring for the consumer trait `CanSerializeValue` on context `Ctx` never resolves — the lookup recurses without terminating +error[E0275]: [CGP-E020] the wiring for the consumer trait `CanSerializeValue` on context `Ctx` never resolves, because the lookup leads back to itself ``` Serializing a `Node` requires serializing its `Vec`, which requires `&Node`, which requires diff --git a/docs/projects/hypershell/examples/bluesky-websocket.md b/docs/projects/hypershell/examples/bluesky-websocket.md index e433d444..7a30b185 100644 --- a/docs/projects/hypershell/examples/bluesky-websocket.md +++ b/docs/projects/hypershell/examples/bluesky-websocket.md @@ -147,8 +147,8 @@ Remove the error route, keeping the `WebSocket` entry. Checked with `check_compo abridged: ```text -error[E0277]: [CGP-E002] the provider trait `Handler, TokioAsyncReadStream>>` with context `MyApp` is not implemented for provider `ComposeHandlers<…>` - = note: root cause: [CGP-E107] context `MyApp` does not contain any delegate entry for `@cgp.core.error.ErrorRaiserComponent.Error` +error[E0277]: [CGP-E001] missing wiring for `@cgp.core.error.ErrorRaiserComponent.Error` on `MyApp` + = note: root cause: [CGP-E113] missing wiring for `@cgp.core.error.ErrorRaiserComponent.Error` on `MyApp` ``` The path's last segment is the error type the provider raises, written by its own name. That type is diff --git a/docs/projects/hypershell/examples/hello-name.md b/docs/projects/hypershell/examples/hello-name.md index a2b16a1b..1f7bb8f8 100644 --- a/docs/projects/hypershell/examples/hello-name.md +++ b/docs/projects/hypershell/examples/hello-name.md @@ -143,8 +143,8 @@ check_components! { the long types abridged: ```text -error[E0277]: [CGP-E002] the provider trait `Handler, Vec>` with context `HypershellCli` is not implemented for provider `ComposeHandlers<…>` - = note: root cause: [CGP-E106] missing field `name` on `HypershellCli` +error[E0277]: [CGP-E001] missing field `name` on `HypershellCli` + = note: root cause: [CGP-E110] missing field `name` on `HypershellCli` ``` The full output continues with the dependency chain that leads there, from the pipeline through diff --git a/docs/projects/hypershell/examples/http-checksum-native.md b/docs/projects/hypershell/examples/http-checksum-native.md index 67e14365..b143d0ff 100644 --- a/docs/projects/hypershell/examples/http-checksum-native.md +++ b/docs/projects/hypershell/examples/http-checksum-native.md @@ -161,8 +161,8 @@ Checked with `check_components!`, as on the [`hello_name`](./hello-name.md#try-a abridged: ```text -error[E0277]: [CGP-E002] the provider trait `Handler, GenericArray>` with context `MyApp` is not implemented for provider `Call` - = note: root cause: [CGP-E110] provider `HandleToTokioAsyncRead` does not contain any delegate entry for `@HandlerComponent.StreamToStdout.GenericArray` +error[E0277]: [CGP-E001] missing entry for `@HandlerComponent.StreamToStdout.GenericArray` in provider `HandleToTokioAsyncRead` + = note: root cause: [CGP-E114] missing entry for `@HandlerComponent.StreamToStdout.GenericArray` in provider `HandleToTokioAsyncRead` ``` The digest is a `GenericArray`, and `StreamToStdout`'s input dispatcher has no entry for that diff --git a/docs/projects/hypershell/guides/debugging.md b/docs/projects/hypershell/guides/debugging.md index 58833737..527c917f 100644 --- a/docs/projects/hypershell/guides/debugging.md +++ b/docs/projects/hypershell/guides/debugging.md @@ -54,8 +54,8 @@ pub type Program = hypershell! { ``` ```text -error[E0277]: [CGP-E002] the provider trait `Handler, Vec>` with context `HypershellCli` is not implemented for provider `ComposeHandlers<…>` - = note: root cause: [CGP-E106] missing field `name` on `HypershellCli` +error[E0277]: [CGP-E001] missing field `name` on `HypershellCli` + = note: root cause: [CGP-E110] missing field `name` on `HypershellCli` ``` The chain runs through the pipeline, `SimpleExec`, the command's argument list, and the extractor @@ -80,7 +80,7 @@ pub type Program = hypershell! { ``` ```text - = note: root cause: [CGP-E201] the trait bound `TokioAsyncReadStream: AsRef<[u8]>` is not satisfied + = note: root cause: [CGP-E117] the trait bound `TokioAsyncReadStream: AsRef<[u8]>` is not satisfied ``` **Fix:** insert `StreamToBytes` between the two stages. With it, the program compiles and prints @@ -99,7 +99,7 @@ pub type Program = hypershell! { ``` ```text - = note: root cause: [CGP-E110] provider `HandleToTokioAsyncRead` does not contain any delegate entry for `@HandlerComponent.StreamToStdout.GenericArray` + = note: root cause: [CGP-E114] missing entry for `@HandlerComponent.StreamToStdout.GenericArray` in provider `HandleToTokioAsyncRead` ``` The path names the syntax and then the input type, which is exactly what the dispatcher could not @@ -124,8 +124,8 @@ pub type Program = hypershell! { ``` ```text -error[E0277]: [CGP-E001] the consumer trait `CanHandle, Vec>` is not implemented for context `HypershellCli` - = note: root cause: [CGP-E107] context `HypershellCli` does not contain any delegate entry for `@cgp.extra.handler.HandlerComponent.Checksum<…>` +error[E0277]: [CGP-E001] missing wiring for `@cgp.extra.handler.HandlerComponent.Checksum<…>` on `HypershellCli` + = note: root cause: [CGP-E113] missing wiring for `@cgp.extra.handler.HandlerComponent.Checksum<…>` on `HypershellCli` ``` `WebSocket` fails the same way on such a context. **Fix:** add the route, either on a namespace that @@ -176,8 +176,8 @@ delegate_components! { ``` ```text -error[E0277]: [CGP-E001] the consumer trait `CanHandle>` is not implemented for context `App` - = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `@cgp.core.error.ErrorRaiserComponent.TooLong` +error[E0277]: [CGP-E001] missing wiring for `@cgp.core.error.ErrorRaiserComponent.TooLong` on `App` + = note: root cause: [CGP-E113] missing wiring for `@cgp.core.error.ErrorRaiserComponent.TooLong` on `App` ``` The provider requires the context to raise `TooLong` into its error type, and `HypershellNamespace` @@ -222,8 +222,8 @@ delegate_components! { ``` ```text -error[E0277]: [CGP-E002] the provider trait `Handler` with context `App` is not implemented for provider `ShoutText` - = note: root cause: [CGP-E111] the provider trait `Handler` is not implemented for `ShoutText` +error[E0277]: [CGP-E001] `ShoutText` is not a provider of `Handler` + = note: root cause: [CGP-E115] `ShoutText` is not a provider of `Handler` ``` **Fix:** lift the provider into a handler, as `Promote>`, with both imported @@ -246,7 +246,7 @@ delegate_components! { ``` ```text -error[E0119]: [CGP-E005] `App` cannot wire `@cgp.extra.handler.HandlerComponent.SimpleExec.*` that is already set through `HypershellNamespace` +error[E0119]: [CGP-E011] conflicting wiring: `App` wires `@cgp.extra.handler.HandlerComponent.SimpleExec`, which `HypershellNamespace` already covers ``` A namespace that inherits `HypershellNamespace` and binds the same path fails in the same way. diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index 8089147d..c0fcd99e 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -243,8 +243,8 @@ The `__Context__` in that note points to the mistake. Depend on the **consumer** case. Use [`#[use_provider]`](use_provider.md) when you mean a named implementation, and it will supply the missing argument. -**`#[uses]` fails on a component trait.** `#[cgp_component]` does not read the attribute, so it -stays on the trait and the compiler cannot find it: +**`#[uses]` is rejected on a component trait.** It declares the dependencies of a provider, and the macro +says so: ```rust #[cgp_component(Shouter)] @@ -255,7 +255,7 @@ pub trait CanShout { ``` ```text -error: cannot find attribute `uses` in this scope +error: `#[uses]` declares the dependencies of a provider, not of a trait; write `#[extend(CanCalculateArea)]` to make it a supertrait ``` A trait that every implementation of the component needs is a supertrait. Write it with diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index e3137469..f7152af0 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -290,28 +290,6 @@ missing field. attributes. Read a set field through the companion's `HasField` implementation when inspecting a partial value. -**A field attribute that belongs to another derive breaks the build.** The companion copies each -field's attributes but none of the struct's derives, so a helper attribute such as `serde`'s lands on -a struct that does not derive `Serialize`: - -```rust -use serde::Serialize; - -#[derive(Serialize, BuildField)] -pub struct Person { - #[serde(rename = "name")] - pub first_name: String, -} -``` - -```text -error: cannot find attribute `serde` in this scope -``` - -A struct therefore cannot combine `BuildField`, or [`CgpRecord`](./derive_cgp_record.md) or -[`CgpData`](./derive_cgp_data.md), with a derive whose field helper attributes it uses. Plain field -attributes such as `#[doc]` and `#[allow]` are harmless. - **`build_from` needs `HasFields` on its source in addition to `BuildField`.** Deriving only `BuildField` on both structs leaves the source without the field list that the conversion traverses. The error reports an unsatisfied [`HasFields`](./derive_has_fields.md) bound on the source. diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 8902c7a6..5fde73f7 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -154,7 +154,7 @@ All three derives reject unions, since the family models structs and enums. `Cgp The applicable restrictions depend on the input shape. The [record page](./derive_cgp_record.md#common-mistakes) covers cleared companion attributes, positional tuple builders, and the newtype representation. The -[variant page](./derive_cgp_variant.md#common-mistakes) covers payload shapes and reserved names. +[variant page](./derive_cgp_variant.md#common-mistakes) covers payload shapes. The following restrictions apply when choosing the combined derive. **Every enum variant needs one unnamed payload or none.** A variant with no fields has the payload @@ -162,17 +162,6 @@ The following restrictions apply when choosing the combined derive. cannot opt out. [`HasFields`](./derive_has_fields.md) accepts all of these shapes when only a representation and whole-value conversions are needed. -**Seven variant names are reserved on an enum.** `Fields`, `FieldsRef`, `Value`, `Remainder`, -`Extractor`, `ExtractorRef`, and `ExtractorMut` make a generated path ambiguous. The -[variant page](./derive_cgp_variant.md#common-mistakes) explains which collisions name the variant. - -**A field attribute that belongs to another derive breaks the build.** The builder's companion copies -each field's attributes, so a `serde` helper attribute beside `#[derive(Serialize, CgpData)]` lands on a -struct that does not derive `Serialize` and fails with ``cannot find attribute `serde` in this scope``. -The extractor's companion enums copy variant attributes the same way, so a `serde` helper on a variant -fails too. [`#[derive(BuildField)]`](./derive_build_field.md#common-mistakes) and -[`#[derive(ExtractField)]`](./derive_extract_field.md#common-mistakes) show the two cases. - **Record and variant absence use different markers.** `IsNothing` represents a missing record field; `IsVoid` represents a ruled-out variant. An error mentioning the wrong marker usually means record and variant operations have been mixed. diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index c01ca5bf..b4b8b936 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -183,11 +183,6 @@ which this derive inherits. **A fieldless struct has an immediately finalizable builder.** Its companion does not need field-state parameters. -**A field attribute that belongs to another derive breaks the build.** The builder's companion copies -each field's attributes, so a `serde` helper attribute beside `#[derive(Serialize, CgpRecord)]` lands on a -struct that does not derive `Serialize` and fails with ``cannot find attribute `serde` in this scope``. -[`#[derive(BuildField)]`](./derive_build_field.md#common-mistakes) shows the case. - **`CgpRecord` rejects enums.** Use [`CgpVariant`](./derive_cgp_variant.md) or [`CgpData`](./derive_cgp_data.md) for an enum. diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 16be3e26..6a7a081f 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -219,15 +219,6 @@ payload is `Nil`, and an impl of your trait for `Nil` conflicts with the macro's Dispatch such an enum with the [dispatch combinators](/docs/reference/providers/dispatch) and a provider instead. -**Seven variant names are reserved.** Because the generated impls name their associated types through -`Self::…`, a variant called `Fields`, `FieldsRef`, `Value`, `Remainder`, `Extractor`, `ExtractorRef`, or -`ExtractorMut` makes that path ambiguous and the derive fails with `ambiguous associated item`, headlined -at the derive. Whether the message also names the variant depends on which part collided: the -representation and constructor impls are generated for your enum and point a note at the real variant, -while the extractor's are generated for the companion enums and point back at the derive. Renaming the -variant is the fix. Record field names are unaffected, since a field is not in the same namespace as an -associated type. - **The companion enums do not inherit your attributes.** Deriving `Debug` or `PartialEq` on the original enum does not implement them for the extraction remainder. Use `.ok()`, `.is_ok()`, or a `match` to inspect an extraction result instead of comparing the whole result with `assert_eq!`. @@ -238,12 +229,6 @@ variant operations have been mixed. **A variantless enum is accepted.** It produces empty companion enums without field-state parameters. -**A variant attribute that belongs to another derive breaks the build.** The extractor's companion -enums copy each variant's attributes, so a `serde` helper attribute beside -`#[derive(Serialize, CgpVariant)]` lands on an enum that does not derive `Serialize` and fails with -``cannot find attribute `serde` in this scope``. -[`#[derive(ExtractField)]`](./derive_extract_field.md#common-mistakes) shows the case. - **`CgpVariant` rejects structs.** Use [`CgpRecord`](./derive_cgp_record.md) or [`CgpData`](./derive_cgp_data.md) for a struct. diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index a0ba70a9..a078b4ea 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -304,10 +304,6 @@ narrowed remainder to be finalized. The record marker `IsNothing` maps to inhabi serve that purpose. An error naming `IsNothing` usually means record and variant operations have been mixed. -**Reserved variant names make generated associated-type paths ambiguous.** Avoid `Value`, `Remainder`, -`Extractor`, `ExtractorRef`, and `ExtractorMut`. The generated implementations use those names through -`Self::…`, which conflicts with identically named variants and produces `ambiguous associated item`. - Extractor diagnostics may leave the offending variant unnamed. The implementations target generated companion enums, so both the headline and the note can point to the derive. Check the names above and rename the conflicting variant. [`HasFields`](./derive_has_fields.md) also reserves `Fields` and @@ -317,27 +313,6 @@ rename the conflicting variant. [`HasFields`](./derive_has_fields.md) also reser enum does not implement them for the companion. Use `.ok()`, `.is_ok()`, or a `match` to inspect the result instead of printing or comparing the whole `Result`. -**A variant attribute that belongs to another derive breaks the build.** The companion enums copy each -variant's attributes but none of the enum's derives, so a helper attribute such as `serde`'s lands on an -enum that does not derive `Serialize`: - -```rust -use serde::Serialize; - -#[derive(Serialize, ExtractField)] -pub enum Shape { - #[serde(rename = "circle")] - Circle(Circle), -} -``` - -```text -error: cannot find attribute `serde` in this scope -``` - -An enum therefore cannot combine `ExtractField`, or [`CgpVariant`](./derive_cgp_variant.md) or -[`CgpData`](./derive_cgp_data.md), with a derive whose variant helper attributes it uses. - **`FinalizeExtractResult` is not in the prelude.** Import it from `cgp::core::field::traits` to call `finalize_extract_result`. diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 92d9ab88..72f18ecb 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -166,7 +166,7 @@ it produces: impl FromVariant for Shape { type Value = Circle; - fn from_variant(_tag: PhantomData, value: Self::Value) -> Self { + fn from_variant(_tag: PhantomData, value: >::Value) -> Self { Self::Circle(value) } } @@ -174,7 +174,7 @@ impl FromVariant for Shape { impl FromVariant for Shape { type Value = Rectangle; - fn from_variant(_tag: PhantomData, value: Self::Value) -> Self { + fn from_variant(_tag: PhantomData, value: >::Value) -> Self { Self::Rectangle(value) } } @@ -218,12 +218,6 @@ variant produces an unsatisfied `FromVariant` bound. **A variant name is a `Symbol!` of its identifier, matched exactly.** `Symbol!("Circle")` and `Symbol!("circle")` are unrelated types, so a case slip reports as an unsatisfied `FromVariant` bound. -**A variant named `Value` does not compile.** The generated body writes `Self::Value` to name the payload -type, and a variant of that name makes the path ambiguous. The compiler reports -`ambiguous associated item` with its headline on the derive and a note pointing at the offending variant. -`Value` is the only name this derive reserves; the [extractor](./derive_extract_field.md) reserves several -more, so an enum taking both should avoid all of them. Renaming the variant is the fix. - **A variantless enum is accepted without generating implementations.** It has nothing to construct; code requiring a `FromVariant` implementation will fail at that use site. diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index dc134008..9197f0f3 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -222,19 +222,19 @@ The conversion implementations move or borrow values between `Person` and that p ```rust impl ToFields for Person { - fn to_fields(self) -> Self::Fields { + fn to_fields(self) -> ::Fields { Cons(self.name.into(), Cons(self.age.into(), Nil)) } } impl FromFields for Person { - fn from_fields(Cons(name, Cons(age, Nil)): Self::Fields) -> Self { + fn from_fields(Cons(name, Cons(age, Nil)): ::Fields) -> Self { Self { name: name.value, age: age.value } } } impl ToFieldsRef for Person { - fn to_fields_ref<'__a>(&'__a self) -> Self::FieldsRef<'__a> + fn to_fields_ref<'__a>(&'__a self) -> ::FieldsRef<'__a> where Self: '__a, { @@ -298,14 +298,6 @@ for that additional borrow. different orders have different `Fields` types. Structural conversions that match on names cope with that; code written against a literal `Cons` chain does not. -**Variants named `Fields` or `FieldsRef` make generated paths ambiguous.** The implementations use -`Self::Fields` and `Self::FieldsRef`, which conflict with variants of those names. The compiler reports -`ambiguous associated item` at the derive and points to the offending variant in a note. The error -comes from a lint that denies the build by default. -Rename that variant. The [extractor](./derive_extract_field.md) and -[constructor](./derive_from_variant.md) derives reserve additional names, so check their restrictions -when deriving the full family. - **`HasField` and `HasFields` generate different interfaces.** The singular derive provides per-field access for structs. The plural derive provides a whole-type representation for structs and enums. diff --git a/docs/reference/derives/index.md b/docs/reference/derives/index.md index 415bc466..cfb0dbd5 100644 --- a/docs/reference/derives/index.md +++ b/docs/reference/derives/index.md @@ -65,11 +65,9 @@ fields, the latter with the payload `Nil`. This restriction applies to `FromVari every variant shape and provides a structural representation with whole-value conversions, so it can be used with enums whose variants have several or named fields. -The builder and extractor derives also generate companion types that copy each field's or variant's -attributes but not the original type's derives. A helper attribute that belongs to another derive, -such as `serde`'s `#[serde(rename = "…")]`, therefore fails to compile on a type that also derives -`BuildField`, `ExtractField`, or one of the umbrella derives. The -[`BuildField`](./derive_build_field.md#common-mistakes) page shows the error. +The builder and extractor derives also generate companion types. Each field or variant of a companion +keeps only its documentation, so a helper attribute that belongs to another derive, such as `serde`'s +`#[serde(rename = "…")]`, stays on your type and does not reach the companion. --- diff --git a/docs/reference/errors.md b/docs/reference/errors.md index a8969e16..6a994fd0 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -65,12 +65,11 @@ Match the compiler's code and the shape of the message. | `E0428` the name … is defined multiple times | A generated name declared twice | [Two entries claim one key](#two-entries-claim-one-key) | | `E0275` overflow evaluating the requirement | A wiring or inheritance cycle | [A lookup that never terminates](#a-lookup-that-never-terminates) | | `E0210` / `E0117` [orphan rule](/docs/reference/glossary#orphan-rule) | Registering into a namespace you do not own | [Registering into a namespace you do not own](#registering-into-a-namespace-you-do-not-own) | -| `E0207` type parameter is not constrained | A per-entry generic that never reaches the key | [A generic that reaches nothing](#a-generic-that-reaches-nothing) | +| `E0207` type parameter is not constrained, or `[CGP-E019]` | A per-entry generic that never reaches the key | [A generic that reaches nothing](#a-generic-that-reaches-nothing) | | `E0107` trait takes N generic arguments but N+1 supplied | A consumer trait written where a provider trait belongs | [Naming the wrong half of a component](#naming-the-wrong-half-of-a-component) | | `E0433` / `E0425` cannot find type | A name the generated code cannot see | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | | `E0576` cannot find associated type … in trait | A `#[use_type]` import with a wrong name | [An imported type that does not exist](#an-imported-type-that-does-not-exist) | | `E0404` expected trait, found type parameter | An [abstract type](/docs/reference/glossary#abstract-type) named after its own bound | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | -| `error: ambiguous associated item` (without a code) | An enum variant named like a derive's associated type | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | ## A dependency is not met @@ -117,25 +116,26 @@ That block **compiles**. Nothing has asked yet whether `GreetHello` can do its j Through the tool, both routes to the failure give the same answer. Checking it: ```text -error[E0277]: [CGP-E001] the consumer trait `CanGreet` is not implemented for context `Person` - --> src/main.rs:56:9 +error[E0277]: [CGP-E001] missing field `name` on `Person` + --> src/main.rs:34:9 | -56 | GreeterComponent, +34 | GreeterComponent, | ^^^^^^^^^^^^^^^^ | - = note: root cause: [CGP-E106] missing field `name` on `Person` + = note: root cause: [CGP-E110] missing field `name` on `Person` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanGreet` for context `Person` └─ [CGP-E102] provider trait impl `Greeter` with context `Person` for provider `GreetHello` - └─ [CGP-E105] trait impl `HasName` for `Person` - └─ [CGP-E106] missing field `name` on `Person` + └─ [CGP-E104] trait impl `HasName` for `Person` + └─ [CGP-E110] missing field `name` on `Person` + = help: add the field `name: String` to `Person` ``` -**Read the `root cause:` line and stop.** It names the fix. The tree beneath it is the chain of +**Read the headline and stop.** It names the cause, and the `help` line a fix. The tree beneath it is the chain of obligations that demanded it, read top to bottom: the context must implement the consumer trait, so its wired provider must be a provider for that context, so the context must have the field. -Calling `person.greet()` instead of checking produces the identical note under an `E0599`. That recovery +Calling `person.greet()` instead of checking produces the same headline and note under an `E0599`. That recovery is the single largest thing the tool does. ### What the raw compiler says @@ -188,8 +188,19 @@ A variant worth knowing, because the fix differs and the usual landmark disappea accessor for nothing at all, and the tool reports that as one cause rather than one per field: ```text - = help: make sure that `#[derive(HasField)]` is used for `Person` - = note: root cause: [CGP-E108] accessor trait `HasField` with field `name` is not implemented for `Person` +error[E0277]: [CGP-E001] `HasField` not derived for field `name` of `Person` + --> src/main.rs:34:9 + | +34 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E111] `HasField` not derived for field `name` of `Person` + this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanGreet` for context `Person` + └─ [CGP-E102] provider trait impl `Greeter` with context `Person` for provider `GreetHello` + └─ [CGP-E104] trait impl `HasName` for `Person` + └─ [CGP-E111] `HasField` not derived for field `name` of `Person` + = help: add `#[derive(HasField)]` to `Person` ``` In the raw output the tell is an absence. A missing field draws a "but trait @@ -212,10 +223,12 @@ error[E0277]: the trait bound `f64: Eq` is not satisfied = note: this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCompareScalars` for context `App` └─ [CGP-E102] provider trait impl `ScalarEquality` with context `App` for provider `CompareScalars` - └─ the trait bound `f64: Eq` is not satisfied + └─ [CGP-E117] the trait bound `f64: Eq` is not satisfied ``` -This is the one class here without a `[CGP-Exxx]` headline, and the absence is deliberate. +This is the one class here without a `[CGP-Exxx]` headline at a check, and the absence is deliberate. +Reached through a method call, where the compiler's headline talks about the method, the same mistake +reads `[CGP-E001] the trait bound `+"`f64: Eq`"+` is not satisfied`. The fix is not to wire a component or add a field but to satisfy the trait: wire the abstract type to something that implements it, implement it for a type you own, or relax the provider's bound if @@ -229,8 +242,16 @@ that same abstract type to something else. The trait half of the bound still hol reports a projection mismatch rather than a missing impl: ```text -error[E0271]: [CGP-E017] expected the abstract type `Scalar` of `HasScalarType` on `Rectangle` to be `f64`, but found `u32` +error[E0271]: [CGP-E005] abstract type `Scalar` of `HasScalarType` on `Rectangle` is `u32`, but `f64` is required + --> src/main.rs:32:9 + | +32 | AreaCalculatorComponent, + | ^^^^^^^^^^^^^^^^^^^^^^^ | + = note: this is required through the dependency chain: + [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` + └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `FixedArea` + └─ [CGP-E116] abstract type `Scalar` of `HasScalarType` on `Rectangle` is `u32`, but `f64` is required = help: wire `ScalarTypeProviderComponent` to `UseType` in the wiring for `Rectangle`, or change the provider to work with `u32` ``` @@ -249,13 +270,14 @@ With a [higher-order provider](./attributes/use_provider.md) the question is whi tool answers it in the shape of the tree. An inner-layer failure shows **two** provider hops: ```text - = note: root cause: [CGP-E106] missing field `base_area` on `Rectangle` + = note: root cause: [CGP-E110] missing field `base_area` on `Rectangle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `Rectangle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `ScaledArea` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `Rectangle` for provider `BaseArea` - └─ [CGP-E105] trait impl `HasBaseArea` for `Rectangle` - └─ [CGP-E106] missing field `base_area` on `Rectangle` + └─ [CGP-E104] trait impl `HasBaseArea` for `Rectangle` + └─ [CGP-E110] missing field `base_area` on `Rectangle` + = help: add the field `base_area: f64` to `Rectangle` ``` An outer-layer failure shows **one**, with the inner provider never named. Either way the wiring is @@ -268,22 +290,21 @@ missing only from the wrapper fails on its line alone. ### When one mistake prints many errors A dependency several components share, left unmet, fails at every one of them. Raw `cargo check` -prints one block per affected provider (three chained components over one missing field produce -**six**), and only some of them reach the cause. +prints one block per affected provider, and only some of them reach the cause. -The tool collapses the whole cascade into one block naming every affected consumer over a single tree: +The tool collapses the whole cascade into one block over a single cause, marking each affected check entry: ```text -error[E0277]: [CGP-E001] the consumer traits `CanBaz`, `CanBar`, and `CanFoo` are not implemented for context `App` +error[E0277]: [CGP-E001] missing field `name` on `App` | -85 | BazComponent, - | ^^^^^^^^^^^^ -86 | BarComponent, - | ^^^^^^^^^^^^ -87 | FooComponent, - | ^^^^^^^^^^^^ +56 | BazProviderComponent, + | ^^^^^^^^^^^^^^^^^^^^ +57 | BarProviderComponent, + | -------------------- also required here +58 | FooProviderComponent, + | -------------------- also required here | - = note: root cause: [CGP-E106] missing field `name` on `App` + = note: root cause: [CGP-E110] missing field `name` on `App` ``` Fix the one cause and all of it disappears together. @@ -304,14 +325,15 @@ nothing ever binds: a [`#[prefix]`](./attributes/prefix.md) routes the lookup so `#[default_impl]`, namespace entry, or direct wiring puts a provider there: ```text - = note: root cause: [CGP-E107] context `App` does not contain any delegate entry for `@app.GreeterComponent` + = note: root cause: [CGP-E113] missing wiring for `@app.GreeterComponent` on `App` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanGreet` for context `App` - └─ [CGP-E104] redirect lookup to `@app.GreeterComponent` in `App` - └─ [CGP-E107] context `App` does not contain any delegate entry for `@app.GreeterComponent` + └─ [CGP-E103] redirect lookup to `@app.GreeterComponent` in `App` + └─ [CGP-E113] missing wiring for `@app.GreeterComponent` on `App` + = help: wire `@app.GreeterComponent` to a provider in the wiring of `App` ``` -The same `[CGP-E107]` leaf covers a component the context never wired. The path is resugared to its +The same `[CGP-E113]` leaf covers a component the context never wired. The path is resugared to its `@app.GreeterComponent` form, which is the largest readability win here. Raw `rustc` prints it as a `PathCons>, _>` list. @@ -342,18 +364,18 @@ with an explicit mapping, or a provider name declared twice. CGP lowers each blo cannot see the collision, so the compiler catches it: ```text -error[E0119]: [CGP-E004] duplicate wiring for component `GreeterComponent` on `Person` +error[E0119]: [CGP-E010] conflicting wiring: `Person` wires component `GreeterComponent` twice | -31 | GreeterComponent: GreetHello, +22 | GreeterComponent: GreetHello, | ---------------- first implementation here -... -38 | GreeterComponent: GreetGoodbye, +23 | GreeterComponent: GreetGoodbye, | ^^^^^^^^^^^^^^^^ conflicting implementation for `Person` ``` -Two carets, two lines to reconcile. Related codes cover the neighbouring shapes: `[CGP-E005]` for a -path key that covers a longer one, `[CGP-E007]` for an `open` header colliding with an explicit -entry, and `[CGP-E008]` for the same key redirected twice. +Two carets, two lines to reconcile. Related codes cover the neighbouring shapes: `[CGP-E011]` for a +path key that covers a longer one, `[CGP-E013]` for an `open` header colliding with an explicit +entry, and `[CGP-E014]` for the same key redirected twice. A `check_components!` table listing an entry +twice is `[CGP-E015]`, and two tables in one module sharing a check-trait name are `[CGP-E016]`. Two things are worth knowing when reading the raw form. A context-wiring entry generates *two* impls, so one duplicate prints a **pair** of `E0119`s, which is one conflict, not two. And a @@ -361,8 +383,8 @@ blanket-versus-specific collision often carries a "downstream crates may impleme the compiler explaining that [coherence](/docs/reference/glossary#coherence) must allow for impls a future crate could add, not a second problem. -A duplicate **name** rather than a duplicate key is an `E0428` instead, and passes through uncoded, -because it already points precisely at both definitions. +A duplicate **name** of your own, rather than a duplicate key, is an `E0428` instead, and passes through +uncoded, because it already points precisely at both definitions. ### Joining more than one namespace @@ -371,11 +393,11 @@ A context can forward through exactly one namespace. Two `namespace` headers (or every key, and the two overlap: ```text -error[E0119]: [CGP-E006] only one namespace can be used for each target type in `delegate_components!`, but `App` uses both `NamespaceA` and `NamespaceB` +error[E0119]: [CGP-E012] conflicting wiring: `App` joins both `NamespaceA` and `NamespaceB`, but a target type in `delegate_components!` can join only one namespace | -52 | namespace NamespaceA; +15 | namespace NamespaceA; | ---------- first implementation here -53 | namespace NamespaceB; +16 | namespace NamespaceB; | ^^^^^^^^^^ conflicting implementation for `App` ``` @@ -389,11 +411,12 @@ A namespace's entries are defaults, but only a path it *routes to* without *term overridden. A path the namespace itself binds is already covered by its blanket impl: ```text -error[E0119]: [CGP-E005] `App` cannot wire `@app.GreeterComponent.*` that is already set through `AppNamespace` +error[E0119]: [CGP-E011] conflicting wiring: `App` wires `@app.GreeterComponent`, which `AppNamespace` already covers | -55 | namespace AppNamespace; +29 | namespace AppNamespace; | ------------ first implementation here -57 | @app.GreeterComponent: GreetBye, +30 | +31 | @app.GreeterComponent: GreetGoodbye, | ^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `App` ``` @@ -404,7 +427,7 @@ The same mistake one level up, a child namespace redefining a key it inherits, i way: ```text -error[E0119]: [CGP-E005] `ChildNs` cannot wire component `GreeterComponent` that is already set through `BaseNs` +error[E0119]: [CGP-E011] conflicting wiring: `ChildNs` wires component `GreeterComponent`, which `BaseNs` already covers ``` In the raw form, ``conflicting implementations of trait `ChildNs<_>` for type `GreeterComponent` ``, @@ -415,7 +438,7 @@ than binding it, as it does for a component carrying [`#[prefix]`](./attributes/ was written in the wrong form rather than overridden, and the tool says so with a different code: ```text -error[E0119]: [CGP-E007] component `GreeterComponent` on `AppNamespace` is redirected to `@app.GreeterComponent` +error[E0119]: [CGP-E013] conflicting wiring: `AppNamespace` wires component `GreeterComponent` directly, but it is redirected to `@app.GreeterComponent` = help: wire the provider `GreetHello` with the key `@app.GreeterComponent` ``` @@ -425,7 +448,7 @@ Rust's orphan rule forbids implementing a foreign trait for a foreign type, and is exactly such an impl when both the namespace and the key belong to other crates: ```text -error[E0210]: [CGP-E011] cannot register the foreign path `@app.AnnouncerComponent` into the foreign namespace `AppNamespace` +error[E0210]: [CGP-E022] cannot register the foreign path `@app.AnnouncerComponent` into the foreign namespace `AppNamespace` | 26 | #[cgp_impl(new AnnounceQuietly)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -444,23 +467,28 @@ Wiring a component to [`UseContext`](./providers/use_context.md) when the contex component *is* that wiring makes the lookup chase its own tail: ```text -error[E0275]: [CGP-E010] the wiring for the consumer trait `CanGreet` on context `Person` never resolves — the lookup recurses without terminating +error[E0275]: [CGP-E020] the wiring for the consumer trait `CanGreet` on context `Person` never resolves, because the lookup leads back to itself | - = help: a lookup that recurses usually means the component is delegated back to the context itself — e.g. wired to `UseContext` with no direct implementation of the consumer trait — so wire a real provider, or implement the consumer trait directly on the context +18 | GreeterComponent, + | ^^^^^^^^^^^^^^^^ + | + = help: wire a provider in place of `UseContext`, which provides `Greeter` for `Person` by requiring `CanGreet` on `Person` again ``` Raw `rustc` gives an `E0275` overflow with a note chain you can read the loop out of, plus a stock "consider increasing the recursion limit" suggestion. **Ignore that suggestion**: a true cycle does not terminate at any depth, so raising the limit cannot help. -Reached by a method call rather than a check, a cycle does not overflow at all. It hides as the -ordinary `E0599`, and nothing in it says a cycle was the reason. +Reached by a method call rather than a check, the same lookup gets the same `[CGP-E020]` from the tool. In +raw output a cycle reached that way can hide as the ordinary `E0599`, where nothing says a cycle was the +reason. A lookup that requires the consumer trait again for a larger type each time never repeats, so the +tool reports it as `[CGP-E021]`. **A related cycle sits at namespace definitions rather than at a use site.** Namespaces whose parent chain loops (`A: B` with `B: A`) fail *eagerly*, with an `E0275` on each `cgp_namespace!` block, because the cycle lives in the `where` clause of a generated impl the compiler checks on sight. A -namespace that inherits itself (`A: A`) fails differently, with an `E0207` saying the impl's value -parameter is not constrained. Two things are unusual about the mutual cycle. Under +namespace that inherits itself (`A: A`) never reaches the compiler, because `cgp_namespace!` rejects it +with ``the namespace `A` cannot inherit from itself``. Two things are unusual about the mutual cycle. Under `cargo cgp check`'s next-generation solver the code **compiles clean** and nothing is reported, the one class where the tool shows you *less* than plain `cargo check`. And the wiring is wrong regardless: break the loop so the parent chain forms a tree, factoring shared entries into a third @@ -472,16 +500,20 @@ A per-entry generic must reach the *key*, where `DelegateComponent>` bi only in the provider value binds nothing: ```text -error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates +error[E0207]: [CGP-E019] the entry for `GreeterComponent` in the wiring of `App` binds `T`, but its key does not use it + | +21 | GreeterComponent: GreetWith, + | ^ | -39 | GreeterComponent: GreetWith, - | ^ unconstrained type parameter + = help: write a concrete type in place of `T` in `GreetWith`, and remove `T` from the entry's generic parameters ``` -This passes through unrewritten, and it does not need much: the caret is on the parameter. The -message speaks in impl terms, though, where the actionable reading is a wiring one: **the generic -has to appear in the key** (` SomeKey: …`), not only in the value. Expect the same error -twice, once per generated position; both name the same ``. +The message speaks in wiring terms: **the generic has to appear in the key** (` SomeKey: …`), not +only in the value. The compiler's own `E0207` speaks in impl terms and repeats once per generated +position, and the tool reports the mistake once. A `for` loop whose key skips its variable is +`[CGP-E017]`, and a `#[default_impl]` on a provider impl generic over a parameter is `[CGP-E018]`. A +per-entry lifetime the provider uses and a blanket entry keyed by its own parameter still keep the +compiler's `E0207`, whose suggestions do not compile. ## A macro lowered something the compiler rejects @@ -497,15 +529,23 @@ trait declares, so a wrong name is lowered faithfully and caught by name resolut ```text error[E0576]: cannot find associated type `Scalr` in trait `HasScalarType` | -21 | type Scalar; - | ------------ similarly named associated type `Scalar` defined here -... -26 | pub fn get_scalar(&self) -> Scalr { - | ^^^^^ +10 | pub fn get_scalar(&self) -> Scalr { + | ^^^^^ not found in `HasScalarType` + | +note: similarly named associated type `Scalar` defined here + | + 5 | type Scalar; + | ^^^^^^^^^^^^ +note: associated type `Scalar` defined here + | + 5 | type Scalar; + | ^^^^^^^^^^^^ + = help: rename `Scalr` to `Scalar` in the `#[use_type]` import from `HasScalarType` and in each use of `Scalr` ``` The caret lands on the name *you* wrote, because the macro copies the identifier's span onto the -rewritten path, and the `help:` usually supplies the spelling. Nothing needs decoding. +rewritten path. The `help` names the edit that compiles: rename it in the import and in each use. The +compiler's own suggestion respells only the signature, which does not compile. ### A name the generated code cannot see @@ -542,45 +582,31 @@ error[E0404]: expected trait, found type parameter `Database` Both halves are named, so the message explains itself once read. Name them apart: `Db` reads better for an abstract database type anyway. -A third sibling is a defect in the library rather than a mistake of yours. The extensible-data -derives name their own associated types as `Self::Value`, `Self::Remainder`, `Self::Fields`, and so -on, so an enum with a variant of one of those names makes the path ambiguous. The error does not -carry a code: - -```text -error: ambiguous associated item -``` - -and its notes say the name "could refer to the variant defined here" or "could also refer to the -associated type defined here". Under [`#[derive(ExtractField)]`](./derives/derive_extract_field.md) -both notes point at the derive attribute, so nothing names the variant to rename. The seven reserved -names are listed on [`#[derive(CgpVariant)]`](./derives/derive_cgp_variant.md#common-mistakes), and -each derive's own page names the ones it reserves. Rename the variant. - ### A field-type shorthand without a rule The getter and implicit-argument macros recognize a small set of field-type shorthands: -`Option<&T>`, `&[T]`, and `&str`. A *combination* they lack a rule for is lowered by whichever rule -matches first, and the result can be a type that is not well-formed. `Option<&[u8]>` lowers to a -bound naming the unsized `Option<[u8]>`: +`Option<&T>`, `&[T]`, and `&str`. A *combination* they lack a rule for can lower to a type that is not +well-formed. The macros reject an optional reference to a slice or a trait object at expansion, since its +shape shows the referent is unsized. A type named by a path, such as `Option<&Path>`, has a size only the +compiler knows, so it lowers to a bound naming the unsized `Option`: ```text error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - | -18 | #[cgp_auto_getter] - | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` + | +5 | #[cgp_auto_getter] + | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: within `Path`, the trait `Sized` is not implemented for `[u8]` +note: required because it appears within the type `Path` note: required by an implicit `Sized` bound in `Option` ``` Two things make this harder to read than it looks. The caret is on the macro attribute rather than on any type you wrote, because the offending type is synthesized. And a second `E0599` on `as_ref` -usually follows, which is derived noise from the same unsized type and points at nothing new. +follows, which is derived noise from the same unsized type and points at nothing new. -**The fix** is a shape a single shorthand supports: `Option>`, or `Option<&'static [u8]>`, or a -hand-written getter naming whatever type the field actually has. The shorthands compose only where the -result is `Sized`. +**The fix** is a shape a single shorthand supports: `Option`, read as `Option<&PathBuf>`, or a +hand-written getter naming whatever type the field actually has. ## Using something you did not declare @@ -592,9 +618,9 @@ they talk about that generated parameter; the tool names the missing declaration **A trait used without `#[uses]`:** ```text -error[E0599]: [CGP-E012] the trait `GetCount` is used but not declared as a dependency +error[E0599]: [CGP-E030] the trait `GetCount` is used but not declared as a dependency | -44 | format!("{} ({})", self.get_name(), self.get_count()) +16 | format!("{} ({})", self.get_name(), self.get_count()) | ^^^^^^^^^ | = help: declare it as a dependency with `#[uses(GetCount)]` @@ -603,9 +629,9 @@ error[E0599]: [CGP-E012] the trait `GetCount` is used but not declared as a depe **An inner provider used without `#[use_provider]`:** ```text -error[E0599]: [CGP-E016] the inner provider `InnerCalculator` is used but not imported +error[E0599]: [CGP-E031] the inner provider `InnerCalculator` is used but not imported | -22 | InnerCalculator::area(self) * scale_factor * scale_factor +11 | InnerCalculator::area(self) * scale_factor * scale_factor | ^^^^ | = help: import it with `#[use_provider(InnerCalculator: AreaCalculator)]` @@ -621,7 +647,7 @@ where the provider trait belongs gives it one generic argument too many, because context: ```text -error[E0107]: [CGP-E013] `CanCalculateArea` is a consumer trait, but a `#[cgp_impl]` provider must implement its provider trait `AreaCalculator` +error[E0107]: [CGP-E032] `CanCalculateArea` is a consumer trait, but a `#[cgp_impl]` provider must implement its provider trait `AreaCalculator` | 9 | impl CanCalculateArea { | ^^^^^^^^^^^^^^^^ @@ -631,7 +657,8 @@ error[E0107]: [CGP-E013] `CanCalculateArea` is a consumer trait, but a `#[cgp_im Untranslated, this one mistake produces a burst of `E0425`/`E0107`/`E0186`/`E0207` errors plus a downstream check failure, none of which names the cause. Two neighbours share the shape: -`[CGP-E015]` is the same confusion in a `#[use_provider]` bound, and `[CGP-E014]` is `#[cgp_impl]` +`[CGP-E034]` is the same confusion in a `#[use_provider]` bound, `[CGP-E037]` is its mirror in `#[uses]`, +and `[CGP-E033]` is `#[cgp_impl]` applied to a trait that is not a component at all, where the fix is to make it one, or to write a plain `impl`. diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 9f300276..4af19cac 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -199,6 +199,22 @@ A few things to read off it. The `Output` is the original return type verbatim. `Output = ()`. And `sync_method` was left completely alone, which lets a trait mix async and synchronous methods. +**A method with a default body keeps it, wrapped in `async move { … }`,** so the body is the future the method +returns, as the body of an `async fn` is. Each by-value parameter bound to a plain name is rebound inside the +block, so the future owns it, and a `mut` on the parameter moves to the rebinding: + +```rust +// async fn add(&self, mut value: u32, extra: u32) -> u32 { value += extra; value } +fn add(&self, value: u32, extra: u32) -> impl ::core::future::Future { + async move { + let mut value = value; + let extra = extra; + value += extra; + value + } +} +``` + **The macro rewrites only trait definitions.** Applied to anything else, most importantly an `impl` block, it returns the tokens unchanged. This passthrough makes the composition work: an `async fn` is legal in an impl already, so the provider's body stays as written while the trait's declaration carries the future @@ -243,19 +259,6 @@ type directly, and to implement it for each concrete context. That pattern is me unavoidable; the opacity that makes the rewrite zero-cost is the same opacity that hides the auto-traits. -**A default-bodied async method is mishandled.** The macro rewrites the *signature* and never the body, so a -method with a default gets its `async` stripped and its return type changed while the body stays a plain -expression: - -```text -error[E0277]: `{integer}` is not a future -``` - -That error names the body's type rather than the rewrite that caused it. In practice this is rarely hit, -because async trait methods are almost always declarations with the behaviour supplied by a provider. But a -default-bodied `async fn` inside an `#[async_trait]` trait is not supported. Wrap the body in an -`async { … }` block by hand, or move it to a provider. - **Attribute arguments are silently ignored.** `#[async_trait(anything)]` is accepted and discarded rather than rejected, so a typo'd option gives no feedback. Always write it bare. diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index 99ba7092..fc610444 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -303,7 +303,8 @@ the provider after the method alone, so a second trait with an `area` method emi `__compute_area__` and a second `ComputeArea`, and the module fails with ``error[E0428]: the name `__compute_area__` is defined multiple times``, the same error for `ComputeArea`, and `E0119` conflicts between the two providers' impls, followed by `E0277` errors on -the second trait's generated code. Declare such traits in separate modules. +the second trait's generated code. [`cargo cgp check`](/docs/cargo-cgp/error-codes#cgp-e061) reports the pair +as one error on the two method names. Declare such traits in separate modules. **The enum must derive the extensible-data machinery.** Without [`#[derive(CgpData)]`](../derives/derive_cgp_data.md) or the variant derives, the call fails with @@ -317,6 +318,8 @@ error[E0599]: the method `area` exists for reference `&Plain`, but its trait bou `HasArea for Rectangle` does not fail where the impl should have been. It fails where `shape.area()` is called, with the same `E0599` headline, and the notes list unsatisfied bounds on `MatchWithValueHandlersRef` without naming the variant that lacks an impl. +[`cargo cgp check`](/docs/cargo-cgp/check) names the payload instead: +``[CGP-E003] the trait bound `Rectangle: HasArea` is not satisfied``. **The generated impl is a blanket impl over every type that implements `HasExtractor`.** This lets it cover any extensible enum whose payloads implement the trait. A hand-written impl for a type diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index e48650b5..0d7bfc77 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -85,8 +85,8 @@ mirror: `&mut T`, `&mut str` from a `String` via `.as_mut_str()`, `&mut [T]` thr in the return type needs that receiver, and under `&self` the macro rejects it with *&mut self is required for mutable field reference*. -Two combinations fall outside the table. `Option<&[T]>` has no rule of its own, so the `Option<&T>` -rule applies and asks for an unsized `Option<[T]>` field, which the compiler rejects. And a shared +Two combinations fall outside the table. `Option<&[T]>` and `Option<&dyn Trait>` have no rule of their +own, and the macro rejects them, since an `Option<[T]>` field cannot exist. And a shared `Option` return under `&mut self` does not compile, as [Common Mistakes](#common-mistakes) records. The `&str` row is the one most often wanted and least obvious: the context stores a `String` and the @@ -382,13 +382,16 @@ error[E0308]: mismatched types The plain reference, `&str`, slice, and `MRef` forms are unaffected, because a `&mut` result coerces to the shared one. Return `Option<&mut T>` from a `&mut self` getter, or take `&self`. -**`Option<&[T]>` is not a supported return type.** It falls through to the `Option<&T>` rule, which -bounds the field as `Option<[u8]>`: +**`Option<&[T]>` is not a supported return type**, and neither is `Option<&dyn Trait>`. The macro rejects +them, since the field they would read cannot exist: ```text -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time +error: `Option<&[T]>` would read an `Option<[T]>` field, which cannot exist because a slice is unsized; read an `Option>` field as `Option<&Vec>` instead ``` +A type named by a path, such as `Option<&Path>`, has a size only the compiler knows, so it still reaches +the compiler, as an `E0277` on the attribute naming `[u8]`. + From an `Option>` field, return `Option<&Vec>`, or return `&Option>` and convert at the call site. diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 90fb43b5..0d1f4a7b 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -146,8 +146,8 @@ The `open` statement of [`delegate_components!`](./delegate_components.md) super `#[uses(...)]`, `#[extend_where(...)]`, and `#[use_provider(...)]` look like they belong here, but only [`#[cgp_impl]`](./cgp_impl.md) and [`#[cgp_fn]`](./cgp_fn.md) read them. None of them is an -attribute in its own right, so writing one above a component leaves a name nothing can resolve, and -the error is confusing; see [Common Mistakes](#common-mistakes). The equivalent of `#[uses]` on a +attribute in its own right, so the macro rejects one written above a component and names `#[extend]` +instead; see [Common Mistakes](#common-mistakes). The equivalent of `#[uses]` on a component is a supertrait, written with `#[extend]`. ## Examples @@ -515,18 +515,16 @@ CGP's wiring dispatches on types rather than values, so that machinery cannot ho The rule does not affect an associated `const` *item*. `const LIMIT: u64;` as a trait member is an [associated const](https://doc.rust-lang.org/reference/items/associated-items.html), not a generic -parameter, and a provider supplies it in the ordinary way. Naming your own associated const from -*inside* a [`#[cgp_impl]`](./cgp_impl.md) body has one complication of its own, covered in that page's -[Common Mistakes](./cgp_impl.md#common-mistakes). +parameter, and a provider supplies it in the ordinary way. A default method body reading `Self::LIMIT` +reads the provider's own `LIMIT` in the provider trait. **Every method parameter needs a plain name.** The impls the macro generates forward each argument to -the provider by name, so a `_` parameter, which Rust allows in a trait method without a body, or a -destructuring pattern such as `(a, b): (u32, u32)` in a default method fails inside the macro: +the provider by name, so a `_` parameter, which Rust allows in a trait method without a body, or a `ref` +binding, a binding with a subpattern, or a destructuring pattern such as `(a, b): (u32, u32)` in a default +method is rejected. A `mut value` parameter of a default method is accepted and forwarded by its name: ```text -error: expected identifier, found keyword `_` -error: failed to parse internal tokens to type `proc_macro2::Ident`: - _ +error: a component method parameter needs a plain name, since the generated impls forward each argument by name; write a name such as `_value`, and destructure inside a default body ``` Name the parameter instead, as in `_value: u32`, and destructure inside a default method's body. @@ -559,11 +557,13 @@ The [`#[use_type]`](../attributes/use_type.md) page covers both. generates from the trait: the consumer trait, the provider trait, the two blanket impls, and the `UseContext`, `RedirectLookup`, and `UseDelegate` impls. For `#[allow(...)]` or a doc comment, that is what you want. -For `#[uses(HasName)]` written above a component trait, it means a *cannot find attribute `uses` in -this scope* error on the attribute's line, which the compiler reports once because every copy shares -the attribute's span. The compiler may even suggest a built-in attribute with a similar name, such as -`#[used]`. It is the same error a typo in an attribute name gives, so the fix is to move the -attribute rather than to add an import. +A typo in an attribute's name therefore gives a *cannot find attribute* error on the attribute's line, +which the compiler reports once because every copy shares the attribute's span. `#[uses]` is the +exception, because the macro rejects it by name: + +```text +error: `#[uses]` declares the dependencies of a provider, not of a trait; write `#[extend(HasName)]` to make it a supertrait +``` ## Related constructs diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index e1ac8a55..5452571a 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -321,12 +321,12 @@ through the context. the return type with *Computer functions cannot return `impl Trait`*. A parameter's `impl Trait` is shorthand for a generic parameter, so the fix is to write that parameter out. -**A type parameter used only in the return type fails to compile.** The function's generics move -onto the generated impl, which names only the input type, so in -`fn parse(value: String) -> Option` nothing fixes `T` and the compiler rejects it: +**A type parameter used only in the return type is rejected.** The function's generics move onto the +generated impl, which names only the input type, so in +`fn parse(value: String) -> Option` nothing fixes `T`, and the macro says so: ```text -error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates +error: the parameter `T` appears in no argument type, so the generated `Computer` impl cannot determine it; take an argument whose type names `T`, or write the provider by hand as a `Computer` impl on a provider generic over `T` ``` Such a computation needs a `Computer` provider written by hand, whose struct can carry `T`. diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 7882c33f..13df12b5 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -325,7 +325,7 @@ since the tag tells you which field the mismatch is about. **A `&mut self` getter cannot return a shared `Option`, and `Option<&[T]>` is unsupported.** Both come from the method parsing this macro shares with `#[cgp_auto_getter]`, which documents them under [Common Mistakes](./cgp_auto_getter.md#common-mistakes): the first fails with `E0308` in every -generated provider, and the second reaches the compiler as an unsized bound. +generated provider, and the macro rejects the second. ## Related constructs diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index b5af932a..68a50e66 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -398,12 +398,14 @@ component name, the context, and a tuple of any remaining provider-trait paramet so a provider for `ComputerRef` gets `IsProviderFor`. -**An associated type the block declares is exempt.** The macro leaves `Self::Output` alone in a -provider that supplies `type Output`, because it gathers the block's own associated-type names first -and skips any `Self::` path starting with one. In the emitted impl, `Self` is the provider struct, -which is the type that declares `Output`, so the path still resolves. The macro still rewrites every -other `Self` in the block, including one naming an [abstract type](/docs/reference/glossary#abstract-type) the *context* supplies. The exemption -does not cover associated consts; see [Common Mistakes](#common-mistakes). +**An associated type or const the block declares is the provider's own.** The macro leaves +`Self::Output` alone in a provider that supplies `type Output`, because it gathers the block's own +associated-item names first and skips any `Self::` path starting with one. In the emitted impl, `Self` is +the provider struct, which is the type that declares `Output`, so the path still resolves. A +`Self::LIMIT` naming a const the block declares reads that const through its qualified provider path, +even when a [`#[uses]`](../attributes/uses.md) trait declares a const of the same name, and +`::LIMIT` reads the context's. The macro still rewrites every other `Self` in the block, +including one naming an [abstract type](/docs/reference/glossary#abstract-type) the *context* supplies. **The rewrite is scoped to the block's own method bodies.** An item nested *inside* a body, such as a local `struct` with its own impl, a helper `fn`, or an inline `trait`, introduces a fresh `self`/`Self` @@ -430,23 +432,6 @@ defaulting to the provider trait's name plus `Component`. Both are Rust `Type` p ## Common Mistakes -**A provider's own associated const needs a qualified path inside its body**, and this follows -directly from the rewrite. The exemption described above covers associated *types* only. So a provider -that declares `const LIMIT: u64 = 100;` cannot then write `Self::LIMIT` in a method body, because the -macro rewrites that `Self` to the context, which lacks the const. The error reads: - -```text -error[E0599]: no associated function or constant named `LIMIT` found for type parameter `__Context__` in the current scope -``` - -Name it through the provider trait instead, which the rewrite turns into the correct qualified path: - -```rust ->::LIMIT -``` - -The consumer side is unaffected: a wired context reads the same const as `::LIMIT`. - **One nesting case escapes the scoping rule.** An item written inside a `macro!( … )` invocation has its `self`/`Self` rewritten too, because a token-level rewrite cannot see the scope the macro will eventually create. A `self::` *module* path inside a macro invocation is safe: the trailing `::` diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 34df8c28..d392e1da 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -405,7 +405,7 @@ a path. routed under a prefix, `open`, which roots the route at the bare component name, no longer reaches those entries. Write the per-value entries with the full prefixed path instead. -**A cyclic parent chain and a self-inheriting namespace fail differently.** Two namespaces inheriting each +**A cyclic parent chain fails at both definitions, and a self-inheriting namespace at the macro.** Two namespaces inheriting each other make the forwarding impl's `where` clause loop, and the compiler rejects it eagerly at both definitions: @@ -414,15 +414,13 @@ error[E0275]: overflow evaluating the requirement `__Key__: A<__BComponents>` note: required for `__Key__` to implement `B<__AComponents>` ``` -A namespace inheriting *itself*, as in `new A: A {}`, does not overflow. It produces a forwarding impl whose -value parameter nothing can determine: +A namespace inheriting *itself*, as in `new A: A {}`, or another instance of itself, as in +` new A: A {}`, is rejected by the macro, with the caret on the parent's name: ```text -error[E0207]: the type parameter `__Value__` is not constrained by the impl trait, self type, or predicates +error: the namespace `A` cannot inherit from itself; name another namespace as its parent, or omit the parent ``` -Both mean the inheritance chain is not acyclic, but only the first says so recognizably. - **A registered component with no provider bound anywhere still compiles.** If a `#[prefix]` routes a component into a namespace and nothing ever binds a provider at its path, the redirect lands on an empty slot and the context compiles regardless. Only a [`check_components!`](./check_components.md) reports it, and what it diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 83c814f7..8642eb1f 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -382,8 +382,8 @@ error[E0277]: the trait bound `UnitArea: IsProviderFor>` type. The mismatch is reported at the wiring rather than at some later `person.greet()` in another file. [`cargo cgp check`](/docs/cargo-cgp/check) reports the same failure -with the root cause first, as ``[CGP-E106] missing field `name` on `Person` ``. `cargo cgp check` +with the root cause first, as ``[CGP-E110] missing field `name` on `Person` ``. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. @@ -370,7 +370,8 @@ error[E0277]: the trait bound `RectangleArea: IsProviderFor ArrayKey: UseDelegate { … }>` gives diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 6fe3e919..89dd51e4 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -214,17 +214,6 @@ that resolves to nothing, with no hint that the cause was a capital letter. **A lowercase primitive is the type, not a string.** `@u32`, `@bool`, and `@str` name those types. That is almost always what you want, and it means a path segment cannot be the *string* `"u32"` through this syntax. -**The primitive check also catches names that are not primitives.** It treats `char`, `bool`, -`usize`, `isize`, `str`, and any `i`, `u`, or `f` followed only by digits as a primitive, which -includes the bare `i`, `u`, and `f` and names such as `u2`. So `@app.f` keeps `f` as a type instead -of the string `"f"`, and fails unless a type `f` is in scope: - -```text -error[E0425]: cannot find type `f` in this scope -``` - -Avoid one-letter and letter-digit segments of that shape in a path. - **A path needs a segment after the `@` and after every dot.** `@` alone, or a trailing dot as in `@app.`, fails while parsing the missing segment as a type, with a message that lists type tokens: diff --git a/docs/reference/traits/builder/has_builder.md b/docs/reference/traits/builder/has_builder.md index 56148551..706f3254 100644 --- a/docs/reference/traits/builder/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -241,9 +241,8 @@ The [example](#examples) derives both on its `FooBar`. **The partial type cannot be printed or cloned.** The derive drops the original's struct-level attributes, so it lacks `Debug`, `Clone`, and every other derive the record carries. Read a set field through the partial type's [`HasField`](../field-access/has_field.md) impl instead. -Field-level attributes, by contrast, are copied onto the partial type, so a field helper attribute -such as `#[serde(rename = "...")]` breaks the build; see -[`#[derive(BuildField)]`](../../derives/derive_build_field.md#common-mistakes). +Each field keeps only its documentation, so a field helper attribute such as +`#[serde(rename = "...")]` does not reach the partial type. **It neither defaults nor validates.** Presence is all that is tracked. A field with a sensible default still has to be set, unless you reach for the diff --git a/docs/reference/traits/shape/from_fields.md b/docs/reference/traits/shape/from_fields.md index 8da90d1f..b033fae0 100644 --- a/docs/reference/traits/shape/from_fields.md +++ b/docs/reference/traits/shape/from_fields.md @@ -106,7 +106,7 @@ The conversion destructures the `Cons` chain positionally and unwraps each entry ```rust impl FromFields for Config { - fn from_fields(Cons(host, Cons(port, Nil)): Self::Fields) -> Self { + fn from_fields(Cons(host, Cons(port, Nil)): ::Fields) -> Self { Self { host: host.value, port: port.value, @@ -123,7 +123,7 @@ example's `Shape` ends in an empty match on the `Void` terminator: ```rust impl FromFields for Shape { - fn from_fields(rest: Self::Fields) -> Self { + fn from_fields(rest: ::Fields) -> Self { match rest { Either::Left(field) => { let field = field.value; diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index 1e7c18d9..ee9d8a89 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -209,10 +209,6 @@ access and takes only structs. Their derives are likewise distinct. different orders have different `Fields` types. Name-driven conversions cope; code written against a literal `Cons` chain does not. -**Two enum variant names are reserved.** A variant called `Fields` or `FieldsRef` collides with -these associated types and the derive fails; the [derive's page](../../derives/derive_has_fields.md) -lists it with the other reserved names. - **There is no method.** `Fields` is a type. Getting a *value* in that shape is [`ToFields`](./to_fields.md). diff --git a/docs/reference/traits/shape/has_fields_ref.md b/docs/reference/traits/shape/has_fields_ref.md index 5ff4117f..017525cf 100644 --- a/docs/reference/traits/shape/has_fields_ref.md +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -155,10 +155,6 @@ its own.** There is no `#[derive(HasFieldsRef)]`. **Naming the shape is not obtaining it.** [`ToFieldsRef`](./to_fields_ref.md) is the method half; this trait has none. -**Two enum variant names are reserved**, `Fields` and `FieldsRef`, because these associated types -are named through `Self::…` in the generated impls. The [derive's -page](../../derives/derive_has_fields.md) lists them with the others. - ## Related constructs - [`HasFields`](./has_fields.md): the owned shape, and where the family is explained in full. diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index 38fd422a..660275a4 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -109,7 +109,7 @@ field, converting each value into its [`Field`](../../types/field.md) entry with ```rust impl ToFields for Config { - fn to_fields(self) -> Self::Fields { + fn to_fields(self) -> ::Fields { Cons(self.host.into(), Cons(self.port.into(), Nil)) } } diff --git a/docs/reference/traits/shape/to_fields_ref.md b/docs/reference/traits/shape/to_fields_ref.md index d5a19fb5..6bb3f4ef 100644 --- a/docs/reference/traits/shape/to_fields_ref.md +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -101,7 +101,7 @@ declares. `cargo cgp expand` on the example's `Config` shows: ```rust impl ToFieldsRef for Config { - fn to_fields_ref<'__a>(&'__a self) -> Self::FieldsRef<'__a> + fn to_fields_ref<'__a>(&'__a self) -> ::FieldsRef<'__a> where Self: '__a, { diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index 6c86ae69..799f5599 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -260,9 +260,6 @@ be written in any order, but every variant must be tried before the remainder ca **Adding a variant breaks every hand-written chain, by design.** That is the guarantee, and it is the reason to prefer the [dispatch combinators](../../providers/dispatch/index.md). -**Five enum variant names are reserved**, because the generated impls name their associated types through -`Self::…`. The [derive's page](../../derives/derive_extract_field.md) lists them. - ## Related constructs - [`HasExtractor`](./has_extractor.md), [`HasExtractorRef`](./has_extractor_ref.md), and diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index cf8f8b90..c5df2592 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -161,7 +161,7 @@ impl FromVariant for Shape { type Value = Circle; fn from_variant( _tag: ::core::marker::PhantomData, - value: Self::Value, + value: >::Value, ) -> Self { Self::Circle(value) } @@ -170,7 +170,7 @@ impl FromVariant for Shape { type Value = Rectangle; fn from_variant( _tag: ::core::marker::PhantomData, - value: Self::Value, + value: >::Value, ) -> Self { Self::Rectangle(value) } @@ -228,10 +228,6 @@ error[E0119]: conflicting implementations of trait `cgp::prelude::FromVariant; - fn to_extractor(self) -> Self::Extractor { + fn to_extractor(self) -> ::Extractor { match self { Self::Circle(value) => __PartialShape::Circle(value), Self::Rectangle(value) => __PartialShape::Rectangle(value), } } - fn from_extractor(extractor: Self::Extractor) -> Self { + fn from_extractor(extractor: ::Extractor) -> Self { match extractor { __PartialShape::Circle(value) => Self::Circle(value), __PartialShape::Rectangle(value) => Self::Rectangle(value), diff --git a/docs/reference/traits/variant/has_extractor_mut.md b/docs/reference/traits/variant/has_extractor_mut.md index 3aa13b70..2b45611f 100644 --- a/docs/reference/traits/variant/has_extractor_mut.md +++ b/docs/reference/traits/variant/has_extractor_mut.md @@ -129,7 +129,7 @@ impl HasExtractorMut for Shape { type ExtractorMut<'__a__> = __PartialRefShape<'__a__, IsMut, IsPresent, IsPresent> where Self: '__a__; - fn extractor_mut<'__a__>(&'__a__ mut self) -> Self::ExtractorMut<'__a__> { + fn extractor_mut<'__a__>(&'__a__ mut self) -> ::ExtractorMut<'__a__> { match self { Self::Circle(value) => __PartialRefShape::Circle(value), Self::Rectangle(value) => __PartialRefShape::Rectangle(value), diff --git a/docs/reference/traits/variant/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md index 91b38e31..1c0002aa 100644 --- a/docs/reference/traits/variant/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -139,7 +139,7 @@ impl HasExtractorRef for Shape { type ExtractorRef<'__a__> = __PartialRefShape<'__a__, IsRef, IsPresent, IsPresent> where Self: '__a__; - fn extractor_ref<'__a__>(&'__a__ self) -> Self::ExtractorRef<'__a__> { + fn extractor_ref<'__a__>(&'__a__ self) -> ::ExtractorRef<'__a__> { match self { Self::Circle(value) => __PartialRefShape::Circle(value), Self::Rectangle(value) => __PartialRefShape::Rectangle(value), diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index 2c804e80..b5c379ca 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -162,7 +162,7 @@ help: the trait `HasField src/main.rs:61:9 | 61 | AreaCalculatorComponent, | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: root causes: - - [CGP-E106] missing field `height` on `PlainCircle` - - [CGP-E106] missing field `width` on `PlainCircle` + - [CGP-E110] missing field `width` on `PlainCircle` + - [CGP-E110] missing field `height` on `PlainCircle` this is required through the dependency chain: [CGP-E101] consumer trait impl `CanCalculateArea` for context `PlainCircle` └─ [CGP-E102] provider trait impl `AreaCalculator` with context `PlainCircle` for provider `RectangleAreaCalculator` - └─ [CGP-E105] trait impl `RectangleArea` for `PlainCircle` - ├─ [CGP-E106] missing field `height` on `PlainCircle` - └─ [CGP-E106] missing field `width` on `PlainCircle` + └─ [CGP-E104] trait impl `RectangleArea` for `PlainCircle` + ├─ [CGP-E110] missing field `width` on `PlainCircle` + └─ [CGP-E110] missing field `height` on `PlainCircle` + = help: add the fields `width: f64` and `height: f64` to `PlainCircle` ``` This is the same failure a third time, and now it leads with the answer: `PlainCircle` is missing the diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index 4452621f..dc669bb3 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -15,3 +15,8 @@ cap-std = "3" futures = "0.3" serde = { version = "1", features = ["derive"] } trybuild = "1" + +# The site documents the `cgp` release its sibling checkout prepares, which the repository's `main` does +# not hold yet. Remove this once that release is on `main`. +[patch."https://github.com/contextgeneric/cgp.git"] +cgp = { path = "../../cgp/crates/main/cgp" } diff --git a/example-code/README.md b/example-code/README.md index e2a2350a..a5365c03 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -120,6 +120,8 @@ rejected snippet means writing a fixture under `tests/compile_fail/`, blessing i ## The `cgp` version -The crate takes `cgp` from the `cgp` repository's `main`, which is the 0.8.0 release the site -documents, so it checks the pages against that release before it is on crates.io. Once 0.8.0 is -published, pin `cgp = "0.8.0"` from crates.io instead, alongside the version pins in the tutorials. +The crate checks the pages against the 0.8.0 release before it is on crates.io. Its manifest names the +`cgp` repository and patches it to a sibling checkout at `../../cgp`, which holds that release, so `cargo +test` needs that checkout on the release's branch. Once the release is on the repository's `main`, remove +the patch, and once 0.8.0 is published, pin `cgp = "0.8.0"` from crates.io instead, alongside the version +pins in the tutorials. Each step changes the paths in the `.stderr` files, so re-bless them. diff --git a/example-code/tests/cargo_cgp/mod.rs b/example-code/tests/cargo_cgp/mod.rs index 11126f3f..1f4d4c23 100644 --- a/example-code/tests/cargo_cgp/mod.rs +++ b/example-code/tests/cargo_cgp/mod.rs @@ -1,6 +1,6 @@ //! Code from the pages under `docs/cargo-cgp/`. //! -//! Four of the eight pages show Rust: `index.md`, `check.md`, `reading-output.md`, and `expand.md`. +//! Four of the nine pages show Rust: `index.md`, `check.md`, `reading-output.md`, and `expand.md`. //! The rest are shell commands, quoted messages, and tables, so they have no file here. //! //! Almost every program those pages show is broken on purpose, because the point of each is the error diff --git a/example-code/tests/compile_fail/blog/v0_8_0_missing_height.stderr b/example-code/tests/compile_fail/blog/v0_8_0_missing_height.stderr index 75f5a5ac..0ec8595b 100644 --- a/example-code/tests/compile_fail/blog/v0_8_0_missing_height.stderr +++ b/example-code/tests/compile_fail/blog/v0_8_0_missing_height.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Rectangle: CanUseComponent>>>>>>>` is not implemented for `Rectangle` - but trait `HasField>>>>>>` is implemented for it +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>` is implemented for it --> tests/compile_fail/blog/v0_8_0_missing_height.rs:17:9 | 17 | pub width: f64, diff --git a/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr b/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr index a104d06f..c773fd65 100644 --- a/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr +++ b/example-code/tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Rectangle: CanUseComponent>>>>>>>` is not implemented for `Rectangle` - but trait `HasField>>>>>>` is implemented for it +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>` is implemented for it --> tests/compile_fail/cargo_cgp/check_check_the_wiring_where_you_write_it.rs:19:9 | 19 | pub width: f64, diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.stderr index 839505e6..ede4af50 100644 --- a/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.stderr +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Rectangle: CanUseComponent>>>>>>` is not implemented for `Rectangle` - but trait `HasField>>>>>>>` is implemented for it +help: the trait `HasField>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>>` is implemented for it --> tests/compile_fail/cargo_cgp/reading_output_several_causes_in_one_error.rs:19:9 | 19 | pub length: f64, diff --git a/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr index 58cad28f..94e5eccc 100644 --- a/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr +++ b/example-code/tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `BrokenApp: CanUseComponent` 28 | EmailSenderComponent, | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound | -help: the trait `HasField>>>>>>>>>>>>` is not implemented for `BrokenApp` - but trait `HasField>>>>>>>>>>>>` is implemented for it +help: the trait `HasField>>>>>>>>>>>>` is not implemented for `BrokenApp` + but trait `HasField>>>>>>>>>>>>` is implemented for it --> tests/compile_fail/concepts/check_traits_where_the_failure_surfaces_2.rs:20:9 | 20 | pub smtp_server: String, diff --git a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr index b19d2d4b..e3879091 100644 --- a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr +++ b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr @@ -4,7 +4,7 @@ error[E0599]: the associated function or constant `compute` exists for struct `P 12 | let _ = PipeHandlers::::compute(&(), PhantomData::<()>, 1u8); | ^^^^^^^ associated function or constant cannot be called due to unsatisfied trait bounds | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/providers/pipe.rs:7:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/pipe.rs:7:1 | 7 | pub struct PipeHandlers(pub PhantomData); | ---------------------------------- doesn't satisfy `_: Computer<_, _, _>` or `_: IsProviderFor` diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr index 923db29d..15bde5c4 100644 --- a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr @@ -5,7 +5,7 @@ error[E0107]: trait takes 2 generic arguments but 3 generic arguments were suppl | ^^^^^^^^^^^^^ expected 2 generic arguments | note: trait defined here, with 2 generic parameters: `T`, `Components` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-component/src/namespaces.rs:5:11 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-component/src/namespaces.rs:5:11 | 5 | pub trait DefaultImpls1 { | ^^^^^^^^^^^^^ - ---------- diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr index 3cca527f..d417fca6 100644 --- a/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr @@ -4,7 +4,7 @@ error: cannot find attribute `use_provider` in this scope 22 | #[use_provider(RectangleArea: AreaCalculator)] | ^^^^^^^^^^^^ | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/macros/cgp-macro/src/lib.rs:135:1 + ::: /home/soares/development/context-generic/cgp/crates/macros/cgp-macro/src/lib.rs:135:1 | 135 | pub fn cgp_provider(attr: TokenStream, item: TokenStream) -> TokenStream { | ------------------------------------------------------------------------ similarly named attribute macro `cgp_provider` defined here diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr index 04ae1fb0..a51bbe43 100644 --- a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr @@ -4,7 +4,7 @@ error[E0576]: cannot find associated type `Eror` in trait `HasErrorType` 16 | pub fn fail(&self) -> Result<(), Eror> { | ^^^^ | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-error/src/traits/has_error_type.rs:28:5 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-error/src/traits/has_error_type.rs:28:5 | 28 | type Error: Debug; | ----------------- similarly named associated type `Error` defined here diff --git a/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr index 703594fe..b18ac7bc 100644 --- a/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr +++ b/example-code/tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.stderr @@ -1,11 +1,5 @@ -error: cannot find attribute `uses` in this scope - --> tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.rs:10:3 +error: `#[uses]` declares the dependencies of a provider, not of a trait; write `#[extend(CanCalculateArea)]` to make it a supertrait + --> tests/compile_fail/reference/attributes/uses_common_mistakes_component_trait.rs:10:1 | 10 | #[uses(CanCalculateArea)] - | ^^^^ - | -help: a built-in attribute with a similar name exists - | -10 - #[uses(CanCalculateArea)] -10 + #[used(CanCalculateArea)] - | + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.stderr b/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.stderr index f69fc883..08829df9 100644 --- a/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.stderr +++ b/example-code/tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.stderr @@ -36,8 +36,8 @@ error[E0277]: the trait bound `for<'a> Double: IsProviderFor` is not implemented for `Double` - but trait `IsProviderFor` is implemented for it +help: the trait `IsProviderFor` is not implemented for `Double` + but trait `IsProviderFor` is implemented for it --> tests/compile_fail/reference/components/computer_ref_common_mistakes_owned_input_computer.rs:7:1 | 7 | impl Computer for Double { diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs b/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs deleted file mode 100644 index c9d1da41..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs +++ /dev/null @@ -1,14 +0,0 @@ -use cgp::prelude::*; -use serde::Serialize; - -// error: cannot find attribute `serde` in this scope -// -// The companion `__PartialPerson` copies each field's attributes but not the struct's derives, so -// the `serde` helper lands on a struct that does not derive `Serialize`. -#[derive(Serialize, BuildField)] -pub struct Person { - #[serde(rename = "name")] - pub first_name: String, -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.stderr deleted file mode 100644 index df056ca3..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: cannot find attribute `serde` in this scope - --> tests/compile_fail/reference/derives/derive_build_field_common_mistakes_field_helper_attribute.rs:10:7 - | -10 | #[serde(rename = "name")] - | ^^^^^ - | - = note: `serde` is an attribute that can be used by the derive macros `Deserialize` and `Serialize`, you might be missing a `derive` attribute - = note: `serde` is in scope, but it is a crate, not an attribute diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr index 49d94b6e..8ec92ef0 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.stderr @@ -1,10 +1,8 @@ error[E0277]: the trait bound `FooBar: HasFields` is not satisfied - --> tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs:25:21 + --> tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs:25:10 | 25 | .build_from(source) - | ---------- ^^^^^^ unsatisfied trait bound - | | - | required by a bound introduced by this call + | ^^^^^^^^^^ unsatisfied trait bound | help: the trait `HasFields` is not implemented for `FooBar` --> tests/compile_fail/reference/derives/derive_build_field_rejected_build_from_without_has_fields.rs:5:1 diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr index 22203515..f0ee8cf1 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr @@ -6,10 +6,10 @@ error[E0308]: mismatched types | | | arguments to this method are incorrect | - = note: expected struct `std::marker::PhantomData>>>>>>>>>>>` - found struct `std::marker::PhantomData>>>>>>>>>>` + = note: expected struct `PhantomData>>>>>>>>>>>` + found struct `PhantomData>>>>>>>>>>` note: method defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/has_field.rs:49:8 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/has_field.rs:49:8 | 49 | fn get_field(&self, _tag: PhantomData) -> &Self::Value; | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.stderr index ff165eca..6f26cb28 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.stderr @@ -1,4 +1,4 @@ -error: Expected variant to contain exactly one unnamed field +error: Expected variant to contain exactly one unnamed field, or no fields --> tests/compile_fail/reference/derives/derive_cgp_data_rejected_struct_style_variant.rs:5:5 | 5 | Circle { radius: f64 }, diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs deleted file mode 100644 index 1ca479fe..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs +++ /dev/null @@ -1,13 +0,0 @@ -use cgp::prelude::*; - -pub struct Payload; -pub struct Other; - -// error: ambiguous associated item -#[derive(CgpVariant)] -pub enum Slot { - Remainder(Payload), - Other(Other), -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr deleted file mode 100644 index c5b23323..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error: ambiguous associated item - --> tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs:7:10 - | - 7 | #[derive(CgpVariant)] - | ^^^^^^^^^^ - | -note: `Remainder` could refer to the variant defined here - --> tests/compile_fail/reference/derives/derive_cgp_variant_common_mistakes_reserved_variant.rs:7:10 - | - 7 | #[derive(CgpVariant)] - | ^^^^^^^^^^ -note: `Remainder` could also refer to the associated type defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:33:5 - | -33 | type Remainder; - | ^^^^^^^^^^^^^^ - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #57644 - = note: `#[deny(ambiguous_associated_items)]` (part of `#[deny(future_incompatible)]`) on by default - = note: this error originates in the derive macro `CgpVariant` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.stderr index 18bce633..536a3e05 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.stderr @@ -1,4 +1,4 @@ -error: Expected variant to contain exactly one unnamed field +error: Expected variant to contain exactly one unnamed field, or no fields --> tests/compile_fail/reference/derives/derive_cgp_variant_rejected_struct_style_variant.rs:5:5 | 5 | Circle { radius: f64 }, diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs deleted file mode 100644 index ac6a03c6..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs +++ /dev/null @@ -1,16 +0,0 @@ -use cgp::prelude::*; - -pub struct Payload; -pub struct Other; - -// error: ambiguous associated item -// -// Both the headline and the note land on the derive: the colliding variant is the generated -// companion's, whose identifiers carry the derive's span. -#[derive(ExtractField)] -pub enum Slot { - Value(Payload), - Other(Other), -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr deleted file mode 100644 index 5e58a7bc..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error: ambiguous associated item - --> tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs:10:10 - | -10 | #[derive(ExtractField)] - | ^^^^^^^^^^^^ - | -note: `Value` could refer to the variant defined here - --> tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_reserved_variant.rs:10:10 - | -10 | #[derive(ExtractField)] - | ^^^^^^^^^^^^ -note: `Value` could also refer to the associated type defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:31:5 - | -31 | type Value; - | ^^^^^^^^^^ - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #57644 - = note: `#[deny(ambiguous_associated_items)]` (part of `#[deny(future_incompatible)]`) on by default - = note: this error originates in the derive macro `ExtractField` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs deleted file mode 100644 index 7482266d..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs +++ /dev/null @@ -1,16 +0,0 @@ -use cgp::prelude::*; -use serde::Serialize; - -#[derive(Serialize)] -pub struct Circle { - pub radius: f64, -} - -// error: cannot find attribute `serde` in this scope -#[derive(Serialize, ExtractField)] -pub enum Shape { - #[serde(rename = "circle")] - Circle(Circle), -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.stderr deleted file mode 100644 index e08c3bcd..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.stderr +++ /dev/null @@ -1,12 +0,0 @@ -error: cannot find attribute `serde` in this scope - --> tests/compile_fail/reference/derives/derive_extract_field_common_mistakes_variant_helper_attribute.rs:12:7 - | -12 | #[serde(rename = "circle")] - | ^^^^^ - | - = note: `serde` is in scope, but it is a crate, not an attribute -help: `serde` is an attribute that can be used by the derive macros `Deserialize` and `Serialize`, you might be missing a `derive` attribute - | -11 + #[derive(Deserialize, Serialize)] -12 | pub enum Shape { - | diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr index 7ca57677..509a6041 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr @@ -22,7 +22,7 @@ error[E0599]: the method `finalize_extract_result` exists for enum `Result: FinalizeExtract` which is required by `Result>: FinalizeExtractResult` note: the trait `FinalizeExtract` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:38:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:38:1 | 38 | pub trait FinalizeExtract { | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.stderr index 3594ca8c..b8224063 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.stderr @@ -1,4 +1,4 @@ -error: Expected variant to contain exactly one unnamed field +error: Expected variant to contain exactly one unnamed field, or no fields --> tests/compile_fail/reference/derives/derive_extract_field_rejected_variant_shapes.rs:5:5 | 5 | Circle { radius: f64 }, diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs deleted file mode 100644 index 147a1724..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs +++ /dev/null @@ -1,11 +0,0 @@ -use cgp::prelude::*; - -pub struct Payload; - -// error: ambiguous associated item -#[derive(FromVariant)] -pub enum Slot { - Value(Payload), -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr deleted file mode 100644 index 7d66de11..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error: ambiguous associated item - --> tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs:6:10 - | -6 | #[derive(FromVariant)] - | ^^^^^^^^^^^ - | -note: `Value` could refer to the variant defined here - --> tests/compile_fail/reference/derives/derive_from_variant_common_mistakes_reserved_variant.rs:8:5 - | -8 | Value(Payload), - | ^^^^^ -note: `Value` could also refer to the associated type defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/from_variant.rs:4:5 - | -4 | type Value; - | ^^^^^^^^^^ - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #57644 - = note: `#[deny(ambiguous_associated_items)]` (part of `#[deny(future_incompatible)]`) on by default - = note: this error originates in the derive macro `FromVariant` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.stderr index de202c15..fccf1813 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.stderr @@ -1,4 +1,4 @@ -error: Expected variant to contain exactly one unnamed field +error: Expected variant to contain exactly one unnamed field, or no fields --> tests/compile_fail/reference/derives/derive_from_variant_rejected_struct_style_variant.rs:5:5 | 5 | Circle { radius: f64 }, diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs b/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs deleted file mode 100644 index 18fdf92a..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs +++ /dev/null @@ -1,10 +0,0 @@ -use cgp::prelude::*; - -// error: ambiguous associated item -#[derive(HasFields)] -pub enum Message { - Fields(u8), - Other(u16), -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr b/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr deleted file mode 100644 index d67b3d82..00000000 --- a/example-code/tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error: ambiguous associated item - --> tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs:4:10 - | -4 | #[derive(HasFields)] - | ^^^^^^^^^ - | -note: `Fields` could refer to the variant defined here - --> tests/compile_fail/reference/derives/derive_has_fields_common_mistakes_reserved_variant.rs:6:5 - | -6 | Fields(u8), - | ^^^^^^ -note: `Fields` could also refer to the associated type defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/has_fields.rs:2:5 - | -2 | type Fields; - | ^^^^^^^^^^^ - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #57644 - = note: `#[deny(ambiguous_associated_items)]` (part of `#[deny(future_incompatible)]`) on by default - = note: this error originates in the derive macro `HasFields` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr b/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr index 8aad0a3e..b1a89ed8 100644 --- a/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr +++ b/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Person: CanUseComponent` is not 37 | GreeterComponent, | ^^^^^^^^^^^^^^^^ unsatisfied trait bound | -help: the trait `HasField>>>>>` is not implemented for `Person` - but trait `HasField>>>>` is implemented for it +help: the trait `HasField>>>>>` is not implemented for `Person` + but trait `HasField>>>>` is implemented for it --> tests/compile_fail/reference/errors_the_fix_1.rs:23:9 | 23 | pub age: u8, diff --git a/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs b/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs deleted file mode 100644 index b18240e8..00000000 --- a/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! `docs/reference/macros/async_trait.md`, *Common Mistakes*: a default-bodied `async fn` keeps its -//! body while its signature is rewritten. - -use cgp::prelude::*; - -#[async_trait] -pub trait CanCount { - async fn count(&self) -> u32 { - 1 - } -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.stderr b/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.stderr deleted file mode 100644 index 65194138..00000000 --- a/example-code/tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.stderr +++ /dev/null @@ -1,10 +0,0 @@ -error[E0277]: `{integer}` is not a future - --> tests/compile_fail/reference/macros/async_trait_common_mistakes_default_body.rs:6:1 - | -6 | #[async_trait] - | ^^^^^^^^^^^^^^ `{integer}` is not a future -... -9 | 1 - | - return type was inferred to be `{integer}` here - | - = help: the trait `Future` is not implemented for `{integer}` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr index a08b681f..5d83ae95 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_hand_impl_on_extensible_enum.stderr @@ -8,4 +8,3 @@ error[E0119]: conflicting implementations of trait `HasArea` for type `Shape` | ---------------------- first implementation here | = note: upstream crates may add a new impl of trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::MatchWithValueHandlersRef` in future versions - = note: upstream crates may add a new impl of trait `cgp::prelude::IsProviderFor` for type `cgp::prelude::MatchWithValueHandlersRef` in future versions diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr index 3e26f506..cb4bd16d 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr @@ -7,7 +7,7 @@ error[E0599]: the method `area` exists for reference `&Plain`, but its trait bou 36 | shape.area() | ^^^^ method cannot be called on `&Plain` due to unsatisfied trait bounds | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 | 19 | pub struct MatchWithValueHandlersRef(pub PhantomData); | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Plain>>::Output = f64`, `<_ as Computer<(), (), &Plain>>::Output = f64`, `_: Computer<(), (), &&Plain>` or `_: Computer<(), (), &Plain>` @@ -26,7 +26,7 @@ note: the following trait bounds were not satisfied: 25 | pub trait HasArea { | ------- note: the trait `HasExtractor` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:6:1 | 6 | pub trait HasExtractor { | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr index bd873693..0c0ba666 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr @@ -7,7 +7,7 @@ error[E0599]: the method `area` exists for reference `&Shape`, but its trait bou 32 | shape.area() | ^^^^ method cannot be called on `&Shape` due to unsatisfied trait bounds | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 | 19 | pub struct MatchWithValueHandlersRef(pub PhantomData); | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Shape>>::Output = f64`, `<_ as Computer<(), (), &Shape>>::Output = f64`, `_: Computer<(), (), &&Shape>` or `_: Computer<(), (), &Shape>` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr index 509df97a..d3e80782 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr @@ -263,7 +263,7 @@ error[E0277]: the trait bound `for<'__a__> MatchWithHandlersRef<_>: Computer<(), | ---- required by a bound introduced by this call | help: the trait `Computer` is conditionally implemented for `MatchWithHandlersRef` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 | 12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer 13 | | for MatchWithHandlersRef diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr index 54825f49..c56061f8 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr @@ -19,7 +19,7 @@ note: the following trait bounds were not satisfied: 6 | pub trait HasName { | ^^^^^^^ note: the trait `cgp::prelude::HasField` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/has_field.rs:46:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/has_field.rs:46:1 | 46 | pub trait HasField { | ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr index 83c8d941..84569f6e 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr @@ -1,30 +1,5 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs:5:1 +error: `Option<&[T]>` would read an `Option<[T]>` field, which cannot exist because a slice is unsized; read an `Option>` field as `Option<&Vec>` instead + --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs:7:24 | -5 | #[cgp_auto_getter] - | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `Option` - --> $RUST/core/src/option.rs - | - | pub enum Option { - | ^ required by the implicit `Sized` requirement on this type parameter in `Option` - = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0599]: the method `as_ref` exists for reference `&Option<[u8]>`, but its trait bounds were not satisfied - --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs:5:1 - | -5 | #[cgp_auto_getter] - | ^^^^^^^^^^^^^^^^^^ method cannot be called on `&Option<[u8]>` due to unsatisfied trait bounds - | - ::: $RUST/core/src/option.rs - | - | pub enum Option { - | ------------------ doesn't satisfy `Option<[u8]>: AsRef<_>` - | - = note: the following trait bounds were not satisfied: - `[u8]: Sized` - `Option<[u8]>: AsRef<_>` - which is required by `&Option<[u8]>: AsRef<_>` - = note: this error originates in the attribute macro `cgp_auto_getter` (in Nightly builds, run with -Z macro-backtrace for more info) +7 | fn bytes(&self) -> Option<&[u8]>; + | ^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr index 99ce53fd..9d6d8603 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.stderr @@ -1,11 +1,5 @@ -error: cannot find attribute `uses` in this scope - --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs:12:3 +error: `#[uses]` declares the dependencies of a provider, not of a trait; write `#[extend(HasName)]` to make it a supertrait + --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs:12:1 | 12 | #[uses(HasName)] - | ^^^^ - | -help: a built-in attribute with a similar name exists - | -12 - #[uses(HasName)] -12 + #[used(HasName)] - | + | ^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr index d11026b3..19d51afa 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.stderr @@ -1,11 +1,4 @@ -error: expected identifier, found keyword `_` - --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs:8:21 - | -8 | fn count(&self, _: u32) -> u32; - | ^ - -error: failed to parse internal tokens to type `proc_macro2::Ident`: - _ +error: a component method parameter needs a plain name, since the generated impls forward each argument by name; write a name such as `_value`, and destructure inside a default body --> tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs:8:21 | 8 | fn count(&self, _: u32) -> u32; diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr index a36c9d7c..1029a6c0 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr @@ -8,7 +8,7 @@ error[E0271]: type mismatch resolving `::Error == String` = note: 1 redundant requirement hidden = note: required for `CheckedAdd` to implement `IsProviderFor` note: required by a bound in `cgp::prelude::TryComputer::try_compute` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/try_compute.rs:8:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/try_compute.rs:8:1 | 8 | #[cgp_component(TryComputer)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `TryComputer::try_compute` @@ -24,7 +24,7 @@ error[E0277]: the trait bound `TryPromote: TryComputer` is not implemented for `TryPromote` | help: the trait `TryComputer` is conditionally implemented for `TryPromote` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/providers/try_promote.rs:11:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/try_promote.rs:11:1 | 11 | / impl TryComputer 12 | | for TryPromote diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr index e861b739..1de3fe97 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr @@ -51,7 +51,7 @@ error[E0277]: the trait bound `Promote: TryComputer` i | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TryComputer` is not implemented for `Promote` | help: the trait `TryComputer` is conditionally implemented for `Promote` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/providers/promote.rs:23:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/promote.rs:23:1 | 23 | / impl TryComputer for Promote 24 | | where diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr index 0c88b29c..3aa4fc5f 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.stderr @@ -1,18 +1,5 @@ -error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates +error: the parameter `T` appears in no argument type, so the generated `Computer` impl cannot determine it; take an argument whose type names `T`, or write the provider by hand as a `Computer` impl on a provider generic over `T` --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs:7:10 | 7 | fn parse(value: String) -> Option { - | ^ unconstrained type parameter - | -help: use the type parameter `T` in the `Parse` type and use it in the type definition - | -7 | fn parse(value: String) -> Option { - | +++ - -error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates - --> tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs:7:10 - | -6 | #[cgp_computer] - | --------------- help: remove the unused type parameter `T` -7 | fn parse(value: String) -> Option { - | ^ unconstrained type parameter + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr index 6b6f84ff..dc05eedc 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 | 31 | / impl AsyncComputer for UseField 32 | | where @@ -14,7 +14,7 @@ help: the following other types implement trait `IsProviderFor, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:69:1 | 69 | / impl IsProviderFor 70 | | for UseField @@ -22,7 +22,7 @@ help: the following other types implement trait `IsProviderFor, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:29:1 | 29 | / impl Computer for UseField 30 | | where @@ -30,7 +30,7 @@ help: the following other types implement trait `IsProviderFor, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 | 5 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs deleted file mode 100644 index 37e8da95..00000000 --- a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! `docs/reference/macros/cgp_impl.md`, *Common Mistakes*: `Self::LIMIT` naming the provider's own -//! associated const is rewritten to the context, which lacks it. - -use cgp::prelude::*; - -#[cgp_component(RateLimiter)] -pub trait CanRateLimit { - const LIMIT: u64; - - fn allows(&self, count: u64) -> bool; -} - -#[cgp_impl(new AllowUnderLimit)] -impl RateLimiter { - const LIMIT: u64 = 100; - - fn allows(&self, count: u64) -> bool { - count < Self::LIMIT - } -} - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.stderr b/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.stderr deleted file mode 100644 index 6aef11a9..00000000 --- a/example-code/tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.stderr +++ /dev/null @@ -1,16 +0,0 @@ -error[E0599]: no associated function or constant named `LIMIT` found for type parameter `__Context__` in the current scope - --> tests/compile_fail/reference/macros/cgp_impl_common_mistakes_provider_const_through_self.rs:18:23 - | -13 | #[cgp_impl(new AllowUnderLimit)] - | -------------------------------- associated function or constant `LIMIT` not found for this type parameter -... -18 | count < Self::LIMIT - | ^^^^^ associated function or constant cannot be called on `__Context__` due to unsatisfied trait bounds - | - = help: items from traits can only be used if the type parameter is bounded by the trait -help: the following traits define an item `LIMIT`, perhaps you need to restrict type parameter `__Context__` with one of them: - | -13 | #[cgp_impl(new AllowUnderLimit)]: CanRateLimit - | ++++++++++++++ -13 | #[cgp_impl(new AllowUnderLimit)]: RateLimiter - | ++++++++++++++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr index 8a75c1f5..f5b94f58 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr @@ -1,7 +1,5 @@ -error[E0207]: the type parameter `__Value__` is not constrained by the impl trait, self type, or predicates - --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs:5:1 +error: the namespace `A` cannot inherit from itself; name another namespace as its parent, or omit the parent + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs:5:25 | 5 | cgp_namespace! { new A: A {} } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unconstrained type parameter - | - = note: this error originates in the macro `cgp_namespace` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^ diff --git a/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.stderr b/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.stderr index edba1d89..cfc403fb 100644 --- a/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.stderr +++ b/example-code/tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Person: CanUseComponent` is not 29 | GreeterComponent, | ^^^^^^^^^^^^^^^^ unsatisfied trait bound | -help: the trait `HasField>>>>>` is not implemented for `Person` - but trait `HasField>>>>>>>>>>>` is implemented for it +help: the trait `HasField>>>>>` is not implemented for `Person` + but trait `HasField>>>>>>>>>>>` is implemented for it --> tests/compile_fail/reference/macros/check_components_examples_wrong_field_name.rs:17:9 | 17 | pub first_name: String, // GreetHello needs `name` diff --git a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs deleted file mode 100644 index 2dd10215..00000000 --- a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs +++ /dev/null @@ -1,6 +0,0 @@ -use cgp::prelude::*; - -// error[E0425]: the segment `f` is read as a primitive-shaped type, not a symbol -pub type Route = Path!(@app.f); - -fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.stderr b/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.stderr deleted file mode 100644 index af4c3845..00000000 --- a/example-code/tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.stderr +++ /dev/null @@ -1,10 +0,0 @@ -error[E0425]: cannot find type `f` in this scope - --> tests/compile_fail/reference/macros/path_common_mistakes_letter_digit_segment.rs:4:29 - | -4 | pub type Route = Path!(@app.f); - | ^ not found in this scope - | -help: you might be missing a type parameter - | -4 | pub type Route = Path!(@app.f); - | +++ diff --git a/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.stderr b/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.stderr index 1cdb5caf..bbacd3ed 100644 --- a/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.stderr +++ b/example-code/tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.stderr @@ -1,4 +1,4 @@ -error: Expected variant to contain exactly one unnamed field +error: Expected variant to contain exactly one unnamed field, or no fields --> tests/compile_fail/reference/macros/sum_common_mistakes_variant_derive_shape.rs:7:5 | 7 | Rectangle { width: f64, height: f64 }, diff --git a/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr index 8ce68304..3825dac2 100644 --- a/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr +++ b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `BuildWithHandlers` is not implemented for `BuildWithHandlers, Cons, Nil>>>` help: `BuildWithHandlers` implements trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/build_with_handlers.rs:10:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/build_with_handlers.rs:10:1 | 10 | / impl Computer 11 | | for BuildWithHandlers diff --git a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr index 29a3991a..97562fba 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `MatchWithHandlers` is not implemented for `MatchWithHandlers>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` help: `MatchWithHandlers` implements trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 | 12 | / impl Computer 13 | | for MatchWithHandlers diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr index a5444d61..958d32d5 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `MatchWithHandlersRef` is not implemented for `MatchWithHandlersRef>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` help: `MatchWithHandlersRef` implements trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 | 12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer 13 | | for MatchWithHandlersRef diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr index f944f70e..438a87db 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr @@ -5,7 +5,7 @@ error[E0277]: the trait bound `MatchWithHandlers<_>: cgp::prelude::Computer` is not implemented for `MatchWithHandlers<_>` | help: the trait `cgp::prelude::Computer` is conditionally implemented for `MatchWithHandlers` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 | 12 | / impl Computer 13 | | for MatchWithHandlers @@ -37,7 +37,7 @@ error[E0277]: the trait bound `Cons>>` is not implemented for `Cons>>>>>>, Circle>, Cons>>>>>>>>>, Rectangle>, Nil>>` help: the following other types implement trait `dispatch::providers::matchers::to_field_handlers::ToFieldHandlers` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-dispatch/src/providers/matchers/to_field_handlers.rs:25:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/to_field_handlers.rs:25:1 | 25 | / impl ToFieldHandlers for Either, RestFields> 26 | | where diff --git a/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr b/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr index c6d14689..aae8ebea 100644 --- a/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr +++ b/example-code/tests/compile_fail/reference/providers/raise_from_common_mistakes_missing_from.stderr @@ -5,7 +5,7 @@ error[E0277]: the trait bound `RaiseFrom: ErrorRaiser` is no | ^^^^^^^^^^^^^^^^^^^ the trait `ErrorRaiser` is not implemented for `RaiseFrom` | help: the trait `ErrorRaiser` is conditionally implemented for `RaiseFrom` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-error-extra/src/impls/raise_from.rs:5:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-error-extra/src/impls/raise_from.rs:5:1 | 5 | / impl ErrorRaiser for RaiseFrom 6 | | where diff --git a/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr index 027a9953..d3f3d86e 100644 --- a/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr +++ b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 | 31 | / impl AsyncComputer for UseField 32 | | where @@ -14,7 +14,7 @@ help: the following other types implement trait `IsProviderFor, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:69:1 | 69 | / impl IsProviderFor 70 | | for UseField @@ -22,7 +22,7 @@ help: the following other types implement trait `IsProviderFor, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:29:1 | 29 | / impl Computer for UseField 30 | | where @@ -30,7 +30,7 @@ help: the following other types implement trait `IsProviderFor, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 | 5 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` diff --git a/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr index 5f42a92a..8808f50d 100644 --- a/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr +++ b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 | 31 | / impl AsyncComputer for UseField 32 | | where @@ -14,7 +14,7 @@ help: the following other types implement trait `IsProviderFor, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:69:1 | 69 | / impl IsProviderFor 70 | | for UseField @@ -22,7 +22,7 @@ help: the following other types implement trait `IsProviderFor, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:29:1 | 29 | / impl Computer for UseField 30 | | where @@ -30,7 +30,7 @@ help: the following other types implement trait `IsProviderFor, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 | 5 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` diff --git a/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr index a7adbee2..8c8b8c99 100644 --- a/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr +++ b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr @@ -10,7 +10,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t | = help: the trait `Sized` is not implemented for `str` note: required by an implicit `Sized` bound in `UseFieldRef` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_ref.rs:7:29 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_ref.rs:7:29 | 7 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); | ^^^^^ required by the implicit `Sized` requirement on this type parameter in `UseFieldRef` @@ -77,7 +77,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t | = help: the trait `Sized` is not implemented for `str` note: required by an implicit `Sized` bound in `UseFieldRef` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/impls/use_ref.rs:7:29 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_ref.rs:7:29 | 7 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); | ^^^^^ required by the implicit `Sized` requirement on this type parameter in `UseFieldRef` diff --git a/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr index 87be6271..36d039c1 100644 --- a/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr +++ b/example-code/tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.stderr @@ -1,10 +1,8 @@ error[E0271]: type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsPresent>>::Mapper == IsNothing` - --> tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs:13:22 + --> tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs:13:10 | 13 | .build_field(PhantomData::, "Bob".to_owned()); - | ----------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsPresent>>::Mapper == IsNothing` - | | - | required by a bound introduced by this call + | ^^^^^^^^^^^ type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsPresent>>::Mapper == IsNothing` | note: expected this to be `IsNothing` --> tests/compile_fail/reference/traits/build_field_common_mistakes_build_twice.rs:3:10 diff --git a/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr index 8d922512..a81fb9e6 100644 --- a/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr @@ -21,7 +21,7 @@ error[E0599]: the method `downcast` exists for enum `__PartialFooBarBaz: HasExtractor` which is required by `&mut __PartialFooBarBaz: CanDowncast<_>` note: the trait `HasExtractor` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:6:1 | 6 | pub trait HasExtractor { | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr index 283110cd..2b3a423d 100644 --- a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr @@ -28,7 +28,7 @@ error[E0599]: the method `finalize_with_default` exists for struct `__PartialSer `&mut __PartialServer: TransformMapFields` which is required by `&mut __PartialServer: CanFinalizeWithDefault` note: the trait `TransformMapFields` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:12:1 | 12 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr index 7b0260c4..7510884b 100644 --- a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr @@ -27,7 +27,7 @@ error[E0599]: the method `finalize_with_default` exists for struct `__PartialSer `&mut __PartialServer: TransformMapFields` which is required by `&mut __PartialServer: CanFinalizeWithDefault` note: the trait `TransformMapFields` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:12:1 | 12 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr index 3d7c5efa..5088a776 100644 --- a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr @@ -6,10 +6,10 @@ error[E0308]: mismatched types | | | arguments to this method are incorrect | - = note: expected struct `std::marker::PhantomData>>>>>>>>>>` - found struct `std::marker::PhantomData>>>>>>>` + = note: expected struct `PhantomData>>>>>>>>>>` + found struct `PhantomData>>>>>>>` note: method defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:35:8 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:35:8 | 35 | fn extract_field(self, _tag: PhantomData) -> Result; | ^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr index cb81290d..5a8be9b1 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr @@ -8,7 +8,7 @@ error[E0599]: no method named `finalize_extract` found for enum `__PartialShape< | ^^^^^^^^^^^^^^^^ method not found in `__PartialShape` | note: the method `finalize_extract` exists on the type `::Map` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:39:5 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:39:5 | 39 | fn finalize_extract(self) -> T; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr index d3304cce..f104500e 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr @@ -10,7 +10,7 @@ error[E0599]: no method named `finalize_extract_result` found for enum `Result Self::Output; | ----------------------- the method is available for `Result>` here diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr index 4501820a..70a01fa8 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr @@ -22,7 +22,7 @@ error[E0599]: the method `finalize_extract_result` exists for enum `Result: FinalizeExtract` which is required by `Result>: FinalizeExtractResult` note: the trait `FinalizeExtract` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/extract_field.rs:38:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:38:1 | 38 | pub trait FinalizeExtract { | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr index acfe2a78..de3f89ae 100644 --- a/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr +++ b/example-code/tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.stderr @@ -1,10 +1,8 @@ error[E0277]: the trait bound `FooBar: HasFields` is not satisfied - --> tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs:18:21 + --> tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs:18:10 | 18 | .build_from(FooBar { foo: 1 }) - | ---------- ^^^^^^^^^^^^^^^^^ unsatisfied trait bound - | | - | required by a bound introduced by this call + | ^^^^^^^^^^ unsatisfied trait bound | help: the trait `HasFields` is not implemented for `FooBar` --> tests/compile_fail/reference/traits/has_builder_rejected_build_from_without_has_fields.rs:5:1 diff --git a/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr index a2d70c08..85ca57b1 100644 --- a/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr +++ b/example-code/tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Person: cgp::prelude::HasField>>>>>>>>>>>` is not implemented for `Person` - but trait `HasField>>>>>>>>>>` is implemented for it +help: the trait `HasField>>>>>>>>>>>` is not implemented for `Person` + but trait `HasField>>>>>>>>>>` is implemented for it --> tests/compile_fail/reference/traits/has_field_common_mistakes_misspelled_name.rs:14:9 | 14 | pub firstName: String, diff --git a/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.stderr b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.stderr index b7f247d5..d0ff5719 100644 --- a/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.stderr +++ b/example-code/tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Person: CanUseComponent` is not 35 | GreeterComponent, | ^^^^^^^^^^^^^^^^ unsatisfied trait bound | -help: the trait `HasField>>>>>` is not implemented for `Person` - but trait `HasField>>>>>>>>>>>` is implemented for it +help: the trait `HasField>>>>>` is not implemented for `Person` + but trait `HasField>>>>>>>>>>>` is implemented for it --> tests/compile_fail/reference/traits/is_provider_for_common_mistakes_missing_dependency.rs:24:9 | 24 | pub first_name: String, diff --git a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr index bc2f7044..47762a21 100644 --- a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr +++ b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr @@ -4,7 +4,7 @@ error[E0576]: cannot find associated type `Output` in trait `MapFields` 5 | pub type Mapped = >::Output; | ^^^^^^ not found in `MapFields` | - ::: /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/map_fields.rs:5:5 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/map_fields.rs:5:5 | 5 | type Mapped; | ----------- associated type `Mapped` defined here diff --git a/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr b/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr index 165b34cd..bf5339b7 100644 --- a/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr +++ b/example-code/tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.stderr @@ -1,10 +1,8 @@ error[E0271]: type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Mapper == IsOptional` - --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:12:36 + --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:12:32 | 12 | let _ = Context::builder().set(PhantomData::, "foo".to_owned()); - | --- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Mapper == IsOptional` - | | - | required by a bound introduced by this call + | ^^^ type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Mapper == IsOptional` | note: expected this to be `IsOptional` --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:4:10 @@ -15,12 +13,10 @@ note: expected this to be `IsOptional` = note: this error originates in the derive macro `CgpData` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0271]: type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Output == __PartialContext` - --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:12:36 + --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:12:32 | 12 | let _ = Context::builder().set(PhantomData::, "foo".to_owned()); - | --- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Output == __PartialContext` - | | - | required by a bound introduced by this call + | ^^^ type mismatch resolving `<__PartialContext as UpdateField>>>, IsOptional>>::Output == __PartialContext` | note: expected this to be `__PartialContext` --> tests/compile_fail/reference/traits/set_optional_common_mistakes_core_builder.rs:4:10 diff --git a/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr index bd839a7a..c9b380c9 100644 --- a/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr +++ b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr @@ -6,7 +6,7 @@ error[E0277]: the trait bound `cgp::prelude::Chars<'a', cgp::prelude::Nil>: Stat | = help: the trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` is not implemented for `cgp::prelude::Chars<'a', cgp::prelude::Nil>` help: the following other types implement trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/static_string.rs:29:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/static_string.rs:29:1 | 29 | / impl StaticBytes for Symbol 30 | | where diff --git a/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr b/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr index e25a2ac9..4f562418 100644 --- a/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr +++ b/example-code/tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.stderr @@ -1,10 +1,8 @@ error[E0271]: type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsNothing>>::Mapper == IsPresent` - --> tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs:12:42 + --> tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs:12:31 | 12 | let _ = Person::builder().take_field(PhantomData::); - | ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsNothing>>::Mapper == IsPresent` - | | - | required by a bound introduced by this call + | ^^^^^^^^^^ type mismatch resolving `<__PartialPerson as UpdateField>>>>>>>>>>, IsNothing>>::Mapper == IsPresent` | note: expected this to be `IsPresent` --> tests/compile_fail/reference/traits/take_field_common_mistakes_take_absent.rs:4:10 diff --git a/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr index 2477e95b..5131720d 100644 --- a/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr +++ b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr @@ -15,7 +15,7 @@ error[E0599]: the method `to_optional` exists for struct `__PartialContext: TransformMapFields` which is required by `&mut __PartialContext: cgp::cgp_extra::cgp_field_extra::impls::ToOptional` note: the trait `TransformMapFields` must be implemented - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:12:1 | 12 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.stderr b/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.stderr index 3e9aabb5..17216d22 100644 --- a/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.stderr +++ b/example-code/tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.stderr @@ -21,8 +21,8 @@ error[E0277]: the trait bound `OnlyAbsent: TransformMap::transform_map_fields(partial); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound | -help: the trait `TransformMap` is not implemented for `OnlyAbsent` - but trait `TransformMap` is implemented for it +help: the trait `TransformMap` is not implemented for `OnlyAbsent` + but trait `TransformMap` is implemented for it --> tests/compile_fail/reference/traits/transform_map_common_mistakes_missing_source_state.rs:7:1 | 7 | impl TransformMap for OnlyAbsent { diff --git a/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr b/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr index 96332567..ee5d44fd 100644 --- a/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr +++ b/example-code/tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.stderr @@ -12,12 +12,20 @@ error[E0283]: type annotations needed for `__PartialPoint<_>` ToBuildAndMergeHandler TryPromoteProviders cgp::prelude::IsPresent + = note: cannot satisfy `<_ as MapType>::Map == _` + = note: required for `Cons>, u32>, Nil>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialPoint, _, _>` + = note: required for `__PartialPoint` to implement `TransformMapFields<_, _>` +note: required because it appears within the type `__PartialPoint<_>` + --> tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs:13:12 + | +13 | pub struct Point { + | ^^^^^ = note: required for `Cons>, u32>, Nil>` to implement `cgp::cgp_core::cgp_field::traits::transform_map::TransformMapFieldsImpl<__PartialPoint, _, _>` = note: required for `__PartialPoint` to implement `TransformMapFields<_, _>` help: consider giving this pattern a type, where the type for type parameter `TargetMap` is specified | -19 | let _: __PartialPoint<__M2__> = Point { x: 1 }.into_builder().transform_map_fields(); - | ++++++++++++++++++++++++ +19 | let _: __PartialPoint = Point { x: 1 }.into_builder().transform_map_fields(); + | +++++++++++++++++++++++++++ error[E0283]: type annotations needed --> tests/compile_fail/reference/traits/transform_map_fields_common_mistakes_bare_call.rs:19:43 diff --git a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr index 576a579f..0ac41c86 100644 --- a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr @@ -7,7 +7,16 @@ error[E0284]: type annotations needed for `((), __PartialPerson<_, IsNothing>)` | ------------ type must be known at this point | = note: cannot satisfy `<_ as MapType>::Map == String` + = note: the type must also implement `MapType` +note: required by a bound in `update_field` + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/update_field.rs:5:31 + | + 5 | pub trait UpdateField { + | ^^^^^^^ required by this bound in `UpdateField::update_field` +... +12 | fn update_field( + | ------------ required by a bound in this associated function help: consider giving this pattern a type, where the type for type parameter `M` is specified | -11 | let (_old, _partial): (_, __PartialPerson<__M2__, _>) = - | +++++++++++++++++++++++++++++++++ +11 | let (_old, _partial): (_, __PartialPerson) = + | ++++++++++++++++++++++++++++ diff --git a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr index 2cce9860..98790f1f 100644 --- a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.stderr @@ -1,10 +1,8 @@ error[E0277]: the trait bound `__PartialPerson: UpdateField>>>, IsPresent>` is not satisfied - --> tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs:11:43 + --> tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs:11:31 | 11 | let _ = Person::builder().build_field(PhantomData::, 42_u8); - | ----------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound - | | - | required by a bound introduced by this call + | ^^^^^^^^^^^ unsatisfied trait bound | help: the trait `UpdateField>>>, IsPresent>` is not implemented for `__PartialPerson` --> tests/compile_fail/reference/traits/update_field_common_mistakes_undeclared_field.rs:4:1 diff --git a/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.stderr b/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.stderr index 70c335a0..f79dde80 100644 --- a/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.stderr +++ b/example-code/tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Rectangle: CanUseComponent>>>>>>` is not implemented for `Rectangle` - but trait `HasField>>>>>>>` is implemented for it +help: the trait `HasField>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>>` is implemented for it --> tests/compile_fail/reference/types/chars_common_mistakes_reading_a_missing_field.rs:21:9 | 21 | pub height: f64, diff --git a/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr index 6b1c3cfa..4172b598 100644 --- a/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr +++ b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr @@ -11,7 +11,7 @@ note: required because it appears within the type `PhantomData<*mut &'static ()> | pub struct PhantomData; | ^^^^^^^^^^^ note: required because it appears within the type `cgp::prelude::Life<'static>` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/types/life.rs:3:12 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/life.rs:3:12 | 3 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); | ^^^^ @@ -34,7 +34,7 @@ note: required because it appears within the type `PhantomData<*mut &'static ()> | pub struct PhantomData; | ^^^^^^^^^^^ note: required because it appears within the type `cgp::prelude::Life<'static>` - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/types/life.rs:3:12 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/life.rs:3:12 | 3 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); | ^^^^ diff --git a/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr index 4ce370b4..a989295d 100644 --- a/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr +++ b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr @@ -5,7 +5,7 @@ error[E0004]: non-exhaustive patterns: `&cgp::prelude::Either::Right(cgp::prelud | ^^^^^ pattern `&cgp::prelude::Either::Right(cgp::prelude::Either::Right(_))` not covered | note: `cgp::prelude::Either>` defined here - --> /home/soares/.cargo/git/checkouts/cgp-9f04a98e35a2c3c7/52bcaf7/crates/core/cgp-field/src/types/sum.rs:27:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/sum.rs:27:1 | 27 | pub enum Either { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.stderr b/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.stderr index 515e4dda..ec14f22a 100644 --- a/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.stderr +++ b/example-code/tests/compile_fail/tutorials/area_calculation_checking_miswired.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `PlainCircle: CanUseComponent>>>>>>` is not implemented for `PlainCircle` - but trait `HasField>>>>>>>` is implemented for it +help: the trait `HasField>>>>>>` is not implemented for `PlainCircle` + but trait `HasField>>>>>>>` is implemented for it --> tests/compile_fail/tutorials/area_calculation_checking_miswired.rs:49:9 | 49 | pub radius: f64, From a7e0f2f252a397d89d3a8b48e1673bee3dfccdf8 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 2 Nov 2026 00:26:10 +0100 Subject: [PATCH 190/516] Show the extractor's qualified projections in its expansions Co-Authored-By: Claude Opus 5.5 --- docs/reference/derives/derive_extract_field.md | 2 +- docs/reference/macros/cgp_provider.md | 4 ++-- docs/reference/macros/delegate_components.md | 4 ++-- docs/reference/traits/variant/extract_field.md | 5 ++++- docs/tutorials/area-calculation/checking.md | 4 ++-- 5 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index a078b4ea..ad19169b 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -263,7 +263,7 @@ impl<__F1__: MapType> ExtractField for __PartialShape; // Circle ruled out; __F1__ untouched - fn extract_field(self, _: PhantomData) -> Result { + fn extract_field(self, _: PhantomData) -> Result>::Remainder> { match self { __PartialShape::Circle(value) => Ok(value), __PartialShape::Rectangle(value) => Err(__PartialShape::Rectangle(value)), diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 8642eb1f..219bd35b 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -220,8 +220,8 @@ A couple of cases call for writing the raw form yourself: - **You need the inside-out provider-trait shape itself**, not merely a separately-declared struct: a bound `#[cgp_impl]`'s sugar cannot express, or a rare construct its rewrite does not support, whether from a limitation or a bug. This is uncommon. Most bounds that look like they need the raw form are - expressible in `#[cgp_impl]`'s explicit-context form instead (`impl AreaCalculator for - Context`), which reaches a higher-ranked bound such as `for<'a> &'a Context: IntoIterator` and pins + expressible in `#[cgp_impl]`'s explicit-context form instead + (`impl AreaCalculator for Context`), which reaches a higher-ranked bound such as `for<'a> &'a Context: IntoIterator` and pins the provider to a single concrete context with `impl AreaCalculator for Rectangle` alike. A struct that `new` cannot declare, such as one carrying a default generic parameter (`pub struct IterSum(PhantomData);`) or one shared by several impls, is diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index c7504038..2893cf8b 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -773,8 +773,8 @@ end. **Naming a provider struct that does not exist** is easy to do when you wrote a provider with [`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared it separately. The error is `E0425`, ``cannot find type `SquareArea` in this scope``, which names an unresolved type rather -than anything about wiring. When no type of that name exists anywhere, [`cargo cgp -check`](/docs/cargo-cgp/error-codes#cgp-e043) reports it as an undeclared provider, `[CGP-E043]`, and a +than anything about wiring. When no type of that name exists anywhere, +[`cargo cgp check`](/docs/cargo-cgp/error-codes#cgp-e043) reports it as an undeclared provider, `[CGP-E043]`, and a key that does not resolve as one of `[CGP-E040]` to `[CGP-E042]` or `[CGP-E044]`. A name declared elsewhere but not imported keeps the compiler's message and its import suggestion. diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index 799f5599..10a182a7 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -179,7 +179,10 @@ for __PartialShape { fn extract_field( self, _tag: ::core::marker::PhantomData, - ) -> Result { + ) -> Result< + >::Value, + >::Remainder, + > { match self { __PartialShape::Circle(value) => Ok(value), __PartialShape::Rectangle(value) => Err(__PartialShape::Rectangle(value)), diff --git a/docs/tutorials/area-calculation/checking.md b/docs/tutorials/area-calculation/checking.md index 51ff6cee..bffca1bd 100644 --- a/docs/tutorials/area-calculation/checking.md +++ b/docs/tutorials/area-calculation/checking.md @@ -124,8 +124,8 @@ The error now points at **our line**, the one we should be looking at, and the n name the chain: `PlainCircle` was required to implement `RectangleArea`, which was required for `RectangleAreaCalculator` to serve this context. That is the actual story of the mistake. -The cause is in there too, and this is the part that did not improve. That `Symbol<5, Chars<'w', -Chars<'i', ...>>>` is how CGP writes the field name `width` as a type, so that the compiler can +The cause is in there too, and this is the part that did not improve. That +`Symbol<5, Chars<'w', Chars<'i', ...>>>` is how CGP writes the field name `width` as a type, so that the compiler can reason about field names at all. Read character by character it says `width`, and the second one says `radius` — but you have to read it character by character, in the middle of a paragraph of angle brackets, and the compiler abbreviates the display differently depending on how it is invoked. From b7db5d2b9dae40d2ca8e62f41d8bff2c37152aef Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 2 Nov 2026 00:35:03 +0100 Subject: [PATCH 191/516] Correct the site's remaining stale tool and library claims State the canonical tool qualification on the front pages, the codes the tool now gives a cycle and an unchecked component parameter, and the current `Path!` rule. The dispatch page keeps the module paths the real output prints and names what its help lines say. The tutorial explains why its `help` is not the fix, and each error-code entry shows the message before the fix. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/error-codes.md | 311 +++++++++++------- docs/index.md | 4 +- docs/overview.md | 3 +- .../architecture/dispatch-layers.md | 7 +- docs/reference/derives/derive_has_fields.md | 4 +- docs/reference/errors.md | 4 + docs/reference/macros/cgp_provider.md | 3 +- .../macros/delegate_and_check_components.md | 3 +- docs/reference/macros/path.md | 4 +- docs/reference/providers/use_context.md | 3 + docs/tutorials/area-calculation/checking.md | 5 +- 11 files changed, 226 insertions(+), 125 deletions(-) diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index ca4242b9..b12ac2ea 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -129,59 +129,67 @@ collide. A `` is worded as what it is, such as `` component `` ``, ### CGP-E010 -The same key is wired twice, because a wiring table or a namespace maps one component or path to two providers. To -fix it, remove one of the entries. +The same key is wired twice, because a wiring table or a namespace maps one component or path to two providers. ```text [CGP-E010] conflicting wiring: `` wires twice ``` +To fix it, remove one of the entries. + ### CGP-E011 Two different keys overlap, so an entry is wired that another already covers. It may be a generic entry over a -specific one, a path that covers a longer path, or an entry for a key the context's namespace already binds. To fix -it, remove or narrow the overlapping entry. -[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds) -covers the namespace case. +specific one, a path that covers a longer path, or an entry for a key the context's namespace already binds. ```text [CGP-E011] conflicting wiring: `` wires , which already covers ``` +To fix it, remove or narrow the overlapping entry. +[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds) +covers the namespace case. + The source is the key that covers the other, whichever comes first. When neither covers the other, the key is the one they share. ### CGP-E012 A context joins more than one namespace. Each namespace covers every key, so two of them, or a namespace and a loop -over bare keys, conflict. To fix it, join one namespace and make it inherit the others. -[Joining more than one namespace](/docs/reference/errors#joining-more-than-one-namespace) explains the class. +over bare keys, conflict. ```text [CGP-E012] conflicting wiring: `` joins both `` and ``, but a target type in `delegate_components!` can join only one namespace ``` +To fix it, join one namespace and make it inherit the others. +[Joining more than one namespace](/docs/reference/errors#joining-more-than-one-namespace) explains the class. + ### CGP-E013 A direct entry collides with a redirect of the same key, such as a component wired by name while an `open` -statement, a `=>` redirect, or a namespace sends it along a path. To fix it, wire the provider under the redirected -path rather than the component name, as the `help` line says. -[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds) -explains the class. +statement, a `=>` redirect, or a namespace sends it along a path. ```text [CGP-E013] conflicting wiring: `` wires directly, but it is redirected to `` ``` +To fix it, wire the provider under the redirected +path rather than the component name, as the `help` line says. +[Overriding something a namespace already binds](/docs/reference/errors#overriding-something-a-namespace-already-binds) +explains the class. + ### CGP-E014 The same key is redirected twice, by two `open` statements or `=>` mappings on one context, or by one path registered -twice in a namespace. To fix it, keep one redirect. +twice in a namespace. ```text [CGP-E014] conflicting wiring: `` redirects twice, to `` and to `` ``` +To fix it, keep one redirect. + ## Structural mistakes These codes name a mistake in the shape of what a macro was given, which the compiler rejects through generated items. @@ -190,75 +198,89 @@ line. ### CGP-E015 -A `check_components!` table lists one entry twice. To fix it, remove one of the two. -[The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. +A `check_components!` table lists one entry twice. ```text [CGP-E015] `check_components!` checks `` twice for `` ``` +To fix it, remove one of the two. +[The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. + ### CGP-E016 -Two `check_components!` tables in one module check the same context, so they share a check-trait name. To fix it, merge -the tables, or name one table's check trait with `#[check_trait(...)]`. When two attributes give one name, the message -says so instead. -[The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. +Two `check_components!` tables in one module check the same context, so they share a check-trait name. ```text [CGP-E016] two `check_components!` tables in one module check `` ``` +To fix it, merge +the tables, or name one table's check trait with `#[check_trait(...)]`. When two attributes give one name, the message +says so instead. +[The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. + ### CGP-E017 -A `for` loop in the wiring binds a variable its key does not use. To fix it, write the variable in the key where the -type the loop covers goes. -[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. +A `for` loop in the wiring binds a variable its key does not use. ```text [CGP-E017] the `for` loop in the wiring of `` binds ``, but its key `` does not use it ``` +To fix it, write the variable in the key where the +type the loop covers goes. +[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. + ### CGP-E018 -A `#[default_impl]` registers a provider whose impl is generic over a parameter the key does not fix. To fix it, write -the impl for that key alone, as the `help` line says. -[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. +A `#[default_impl]` registers a provider whose impl is generic over a parameter the key does not fix. ```text [CGP-E018] `#[default_impl]` cannot register `` for ``, because the provider's impl is generic over `` ``` +To fix it, write +the impl for that key alone, as the `help` line says. +[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. + ### CGP-E019 -A wiring or namespace entry binds a generic parameter its key does not use. To fix it, write a concrete type in place of -the parameter and remove it from the entry's generic parameters, as the `help` line says. -[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. +A wiring or namespace entry binds a generic parameter its key does not use. ```text [CGP-E019] the entry for `` in the wiring of `` binds ``, but its key does not use it ``` +To fix it, write a concrete type in place of +the parameter and remove it from the entry's generic parameters, as the `help` line says. +[A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing) explains the class. + ### CGP-E060 A check entry names no parameters for a component that takes some, so it checks the component at the unit parameters -`()`, which the provider does not implement. To fix it, check it at the parameters the `help` line offers, with -`#[check_params(...)]` in `delegate_and_check_components!` or `:

` in `check_components!`. -[`check_components!`](/docs/reference/macros/check_components) describes the syntax. +`()`, which the provider does not implement. ```text [CGP-E060] the check of `` on `` names no parameters, so it checks the component at the unit parameters `()` ``` +To fix it, check it at the parameters the `help` line offers, with +`#[check_params(...)]` in `delegate_and_check_components!` or `:

`:** sets exactly where the build goes. Without it, the tool builds into the `cgp` subdirectory of your project's own target directory, which it reads from `cargo metadata`, so the location @@ -65,10 +66,11 @@ cargo cgp expand [--item ] [CARGO RUSTC ARGS]... | `--item ` | Prints only one module or item instead of the whole target. The path is `::`-separated, names something inside the crate, and may start with `crate::`. A module gives its contents, a type its declaration and every impl written for it, and a trait its definition and every impl of it. | | `-h`, `--help` | Prints the help for `expand`, including `--item`. | -Every other argument is passed to `cargo rustc`, so choosing the target, with `--lib`, `--bin`, -`-p`, or `--features`, is cargo's job. A package with more than one target needs `--lib` or -`--bin `. Unless you pass `--profile` or `--release`, the tool builds under cargo's `check` -profile. The expansion goes to standard output, and everything else goes to standard error. +After handling `--item`, `expand` passes the remaining arguments to `cargo rustc`. Select the +package, target, and features through cargo's options such as `-p`, `--lib`, `--bin`, and +`--features`; a package with multiple targets needs `--lib` or `--bin `. The build uses +cargo's `check` profile unless you request `--profile` or `--release`. The expansion is written +to standard output, leaving other messages on standard error. ### `setup` @@ -76,9 +78,9 @@ profile. The expansion goes to standard output, and everything else goes to stan cargo cgp setup ``` -This command installs the pinned nightly through rustup, with the `rustc-dev` and `llvm-tools` components, -then builds `cargo-cgp-driver` at the front end's version under that nightly and installs it beside the front -end. Running it again when both are present does no harm. It needs rustup and a network connection. +Setup uses rustup to install the pinned nightly with `rustc-dev` and `llvm-tools`, then builds +the matching `cargo-cgp-driver` and installs it beside the front end. It needs a network connection +and can be run again when the binaries and toolchain are already present. ### `update` @@ -86,16 +88,18 @@ end. Running it again when both are present does no harm. It needs rustup and a cargo cgp update ``` -This command looks up the published versions on crates.io and, if there is a newer one in your release -channel, reinstalls the front end and runs the new version's `setup`. It needs a network connection. +Update checks crates.io for a newer version in your release channel. If one is available, it +reinstalls the front end and invokes that version's `setup`, keeping the driver in agreement. +The command needs a network connection. `setup` and `update` take no options. Each answers `-h` or `--help` with a description of what it does instead of running, and refuses any other argument with an error naming it. ## Environment variables -The tool reads these variables, which are meant for running a build of the tool that `setup` did not -install, such as one from a source checkout: +When running a build outside the setup-managed installation, such as a source checkout, these +variables select the driver and toolchain environment. `CARGO_TARGET_DIR` also controls where +ordinary project artifacts go: | Variable | Effect | |---|---| @@ -104,7 +108,8 @@ install, such as one from a source checkout: | `CARGO_CGP_TOOLCHAIN` | A nightly to use in place of the pinned one, for `setup`, `check`, and `expand`. The driver must be built against it. It has no effect when `CARGO_CGP_NO_MANAGE` is set. | | `CARGO_TARGET_DIR` | cargo's own variable. It moves the project's target directory, and the tool builds in that directory's `cgp` subdirectory. | -For the length of a `check` or `expand`, the tool also sets variables for cargo: +During `check` and `expand`, the tool passes the following environment to cargo so it uses the +driver and matching compiler libraries: | Variable | Set to | |---|---| @@ -114,8 +119,9 @@ For the length of a `check` or `expand`, the tool also sets variables for cargo: ## Files and directories -The tool puts its files in these places. Uninstalling with cargo removes the two binaries but leaves the -toolchain and the build directories, as [Uninstalling](./installation.md#uninstalling) explains: +Installation and checks create the files listed below. Uninstalling through cargo removes the +two binaries, while the toolchain and build directories remain; [Uninstalling](./installation.md#uninstalling) +explains how to remove those separately. | Path | What it holds | |---|---| @@ -126,24 +132,27 @@ toolchain and the build directories, as [Uninstalling](./installation.md#uninsta ## Exit status -`check` exits with `cargo check`'s status, so `0` means no errors. `expand` exits with `0` when the compilation -reached the end of macro expansion without an error, which includes a crate that would fail type checking. An -error before that point exits with cargo's status, even when part of an expansion was printed, and a path given to -`--item` that matches nothing exits with `1`. A failure in the tool itself, such as a preflight message or an -unknown command, also exits with `1`. +`check` returns the exit status of `cargo check`, with `0` indicating no errors. For `expand`, +success means reaching the end of macro expansion without an error; type checking has not run, +so that result can include a crate that would fail it. + +If an error occurs before expansion completes, the command returns cargo's status even when a +partial listing was printed. The tool returns `1` for an unmatched `--item` path or one of its +own failures, including an unsuccessful preflight or an unknown command. ## The driver -You do not normally run `cargo-cgp-driver` yourself, since the front end runs it in place of the compiler. It -does answer two queries of its own: +The front end normally invokes `cargo-cgp-driver` for you in place of the compiler. When checking +an installation, you can query the driver directly with these options: | Option | Effect | |---|---| | `--version`, `-V` | Prints three lines: its version, the `pinned-toolchain:` it needs, and the `built-against-rustc:` compiler it was built with. | | `--help`, `-h` | Prints a short description of the driver. Running it with no arguments does the same. | -Run directly on the cargo path, it needs the pinned nightly's `lib` directory on `LD_LIBRARY_PATH`, and -[Troubleshooting](./troubleshooting.md#the-driver-cannot-load-the-compiler) shows the command. +With a cargo installation, a direct driver invocation needs the pinned nightly's `lib` directory +on `LD_LIBRARY_PATH`. [Troubleshooting](./troubleshooting.md#the-driver-cannot-load-the-compiler) +shows how to supply it. --- diff --git a/docs/cargo-cgp/editor-integration.md b/docs/cargo-cgp/editor-integration.md index 91cec877..06eb3d7f 100644 --- a/docs/cargo-cgp/editor-integration.md +++ b/docs/cargo-cgp/editor-integration.md @@ -7,18 +7,19 @@ description: 'Make rust-analyzer run cargo cgp check when you save, so VS Code s # Editor integration -If you read your errors in an editor, a terminal command only helps so much. rust-analyzer runs -`cargo check` every time you save a file and shows the errors in your editor, and one setting makes it run -`cargo cgp check` instead, so the CGP errors VS Code underlines lead with their root cause, as they do in a -terminal. This page covers VS Code with the -[rust-analyzer extension](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). It -is part of [`cargo-cgp`](./index.md), the error toolchain for [CGP](/docs/), and it assumes the tool is -[installed](./installation.md) and that `cargo cgp check` already works in a terminal in your project. +You can have rust-analyzer run `cargo cgp check` when you save, bringing the rewritten CGP errors +into your editor. One setting replaces its usual `cargo check` command, so errors from the check +lead with the same root causes as they do in a terminal. + +This page covers VS Code with the +[rust-analyzer extension](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). +Before configuring it, [install](./installation.md) the [`cargo-cgp`](./index.md) toolchain for +[CGP](/docs/) and confirm that `cargo cgp check` works in a terminal inside your project. ## Set it up -The setting goes in your project's workspace settings, the `.vscode/settings.json` file at the project's -root. Open it with **Preferences: Open Workspace Settings (JSON)** from the command palette, and add: +Open the project's `.vscode/settings.json` through **Preferences: Open Workspace Settings (JSON)** +in the command palette. Add the override to this workspace settings file at the project root: ```json { @@ -40,32 +41,32 @@ Each part of the command has a job: reads. The tool writes its rewritten errors in the same JSON format as the compiler, so nothing else is needed for them to reach the editor. -You may wonder why the command goes in `check.overrideCommand` rather than `check.command`. The -[`check.command`](https://rust-analyzer.github.io/book/configuration.html#check.command) setting takes -a single cargo subcommand, such as `clippy`, and rust-analyzer puts its own flags straight after it, -so `cgp` would be followed by `--workspace` rather than by `check`. -[`check.overrideCommand`](https://rust-analyzer.github.io/book/configuration.html#check.overrideCommand) -takes the whole command line and runs it as written. +The full command belongs in +[`check.overrideCommand`](https://rust-analyzer.github.io/book/configuration.html#check.overrideCommand), +which runs it as written. The shorter +[`check.command`](https://rust-analyzer.github.io/book/configuration.html#check.command) setting +accepts only a cargo subcommand such as `clippy`. Giving it `cgp` would put rust-analyzer's flags +directly after `cgp`, where the tool expects `check`. ### Workspace or user settings -Prefer the workspace settings, so the tool runs only on projects that use CGP. -[User settings](https://code.visualstudio.com/docs/configure/settings) apply to every project you open. The -tool checks a project without CGP correctly, but it still builds that project a second time under its pinned -nightly, which costs time and disk on a project that has no CGP errors to rewrite. Workspace settings also -override user settings, so a project can turn the check on or off for itself. +Workspace settings limit this check to the project where you enable it. +[User settings](https://code.visualstudio.com/docs/configure/settings) instead apply across projects, +including ones without CGP. Those projects still check correctly, but incur a separate nightly +build with no CGP diagnostics to rewrite. Since workspace settings override user settings, a +project can also enable or disable the command locally. -That said, commit `.vscode/settings.json` only if everyone who opens the project has the tool. On a machine -without `cargo-cgp`, the check fails on every save, so that person gets a warning from rust-analyzer instead -of their check errors until they install the tool or remove the setting. +Sharing the settings file also makes installation a requirement for collaborators' save checks. +Only commit `.vscode/settings.json` if everyone opening the project has the tool. Otherwise, +rust-analyzer warns on each save instead of showing check errors until they install it or remove +the override. ## What the editor shows -The errors appear where `cargo check`'s errors would: underlined in the file, listed in the Problems -panel, and in the hover over the underline. Their text is what `cargo cgp check` prints in a terminal. -For the program on the [Check page](./check.md#try-it-on-a-deliberate-mistake), where `Rectangle` lacks -the `height` field its area provider reads, the underline sits on `area` in `rectangle.area()`, and the -message is the rewritten one: +Rewritten check errors use the same editor locations as ordinary check errors: file underlines, +the Problems panel, and the hover over an underline. In the +[Check page's program](./check.md#try-it-on-a-deliberate-mistake), the underline marks `area` in +`rectangle.area()`. Its diagnostic identifies the absent `height` field required by the provider: ```text [CGP-E001] missing field `height` on `Rectangle` @@ -82,29 +83,29 @@ The compiler's own code, `E0599` here, stays attached to the error, as it does i ## What changes when the editor runs the tool -Running the tool in place of `cargo check` changes four things about how rust-analyzer behaves, and you -might otherwise blame the tool for them. +The override changes how the check runs as well as the wording of its diagnostics. These +changes explain some differences you may notice after enabling it. -The first save is slow. The check builds into its own `target/cgp` directory under the tool's pinned nightly, -so the first one compiles every dependency again. Later saves reuse that build. Because the directory is -separate from `target`, the editor's checks also do not wait on cargo's lock while your terminal builds, and -your terminal builds do not wait for them. +The first save can take longer because the pinned nightly builds every dependency into its own +`target/cgp` directory. Later saves reuse that build. Keeping it separate also lets the editor +check while ordinary terminal builds use their own target directory, without either waiting on +the other's cargo lock. -rust-analyzer's own check options stop applying. With an override in place, rust-analyzer runs the command -exactly as written, so settings such as -[`check.features`](https://rust-analyzer.github.io/book/configuration.html#check.features), -`check.allTargets`, `check.workspace`, and `check.extraArgs` do not reach the check. Put the flags you need in -the command itself, for example `"--all-features"` or `"--features", "my-feature"` after `"--all-targets"`. +Because the override runs exactly as written, rust-analyzer does not add its usual check options. +Settings such as [`check.features`](https://rust-analyzer.github.io/book/configuration.html#check.features), +`check.allTargets`, `check.workspace`, and `check.extraArgs` therefore need corresponding flags +in the command itself. For example, add `"--all-features"` or `"--features", "my-feature"` after +`"--all-targets"`. -Two kinds of error appear, and only one is rewritten. rust-analyzer also analyzes your code as you type, with -its own engine and without running any compiler, and reports some errors of its own. Those come from -rust-analyzer rather than from the check, so they read as they always have. The rewritten ones are the errors -that arrive after a save. +Alongside the check, rust-analyzer analyzes code as you type using its own engine. Errors from +that analysis do not pass through the tool, so their wording stays the same. The rewritten +compiler diagnostics arrive after saving, when the override command runs. -Finally, the check and your toolchain can disagree. The check compiles under the tool's pinned nightly with -Rust's next-generation trait solver, so on rare code the editor can show an error your own `cargo check` does -not, or the reverse. Your toolchain's `cargo check` is the authority on whether the code compiles, as the -[Check page](./check.md#what-a-check-does-differently) explains. +The separate compiler can also make the editor's result differ from your normal build. +The tool uses its pinned nightly and Rust's next-generation trait solver, which occasionally +accept or reject code differently from your own toolchain. Keep `cargo check` on that toolchain +as the build authority; the [Check page](./check.md#what-a-check-does-differently) explains the +distinction. ## Turning it off @@ -113,9 +114,9 @@ rust-analyzer goes back to running `cargo check` on save. ## When it does not work -When the command fails, rust-analyzer says so in a warning. The warning begins -`cargo check failed to start`, whatever the command is, and ends with what the command printed. A missing -setup, for example, arrives as the tool's own message: +If the check command fails to start, rust-analyzer reports a warning beginning +`cargo check failed to start`, even though you configured a different command. The rest contains +the command's output. For a missing setup, that includes the tool's own diagnostic: ```text cargo check failed to start: Cargo watcher failed, the command produced no valid metadata (exit code: ExitStatus(unix_wait_status(256))): @@ -127,9 +128,9 @@ error: toolchain `nightly-2026-10-10` is not available: help: run `cargo cgp setup` ``` -Your message names the nightly your build is pinned to and your own platform. Look the message up on -[Troubleshooting](./troubleshooting.md), which lists each one with its fix. To tell whether the problem is the -tool or the editor, run the same command in a terminal from the root of the project you opened in VS Code: +The nightly and platform in your warning depend on your installation. +[Troubleshooting](./troubleshooting.md) explains these messages and their fixes. To separate a +tool failure from editor configuration, run the same check in a terminal at the opened project's root: ```sh cargo cgp check --workspace --all-targets @@ -141,10 +142,10 @@ If the warning instead ends with cargo's `no such command` error, the editor can error: no such command: `cgp` ``` -When the terminal command works, VS Code is running with a different `PATH` from your terminal, so the `cargo` -it starts does not see the tool. This happens most often when VS Code is started from a desktop launcher rather -than from a shell, and the tool is installed somewhere only your shell's start-up files add to `PATH`, as with a -Nix profile. To fix it, start VS Code from a terminal in which `cargo cgp --version` works, and save again. +If the terminal command works but the editor reports this missing-command error, compare their +`PATH` environments. A desktop launcher may start VS Code without the shell setup that adds the +tool's location, such as a Nix profile. Starting VS Code from a terminal where +`cargo cgp --version` works lets it inherit that environment. Save again to retry the check. If only some errors are rewritten, you are seeing the tool's limit rather than the editor's. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape @@ -153,16 +154,15 @@ are most likely to see as the compiler wrote them. ## What this does not do -The setting changes only the errors from the check that runs on save. Completion, hover types, -go-to-definition, and rust-analyzer's own as-you-type errors are unaffected, because none of them run the -check. +Only the on-save check uses this command. Completion, hover types, go-to-definition, and +as-you-type diagnostics come from rust-analyzer's own analysis, so this override does not +change them. -It has also been tested only on Linux, with the rust-analyzer language server. The setting was verified by -running the server the way VS Code runs it, saving the program above, and reading what the server reported: the -rewritten error, the warnings quoted above, and the check options it leaves out under the override. The VS Code -window itself was not part of that test. Other editors that use rust-analyzer accept the same setting, -`check.overrideCommand`, in their own configuration format, but none of them has been tried, and neither have -macOS and Windows. +Verification covered the rust-analyzer language server on Linux, started with the configuration +VS Code would pass. Saving the example produced the rewritten diagnostic, the quoted startup +warnings, and the observed omission of rust-analyzer's other check options. The VS Code window +itself was not tested. Other rust-analyzer editors can express `check.overrideCommand` in their +own configuration formats, but those editors, macOS, and Windows have not been tried. --- diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index 5478f65a..299a5c4b 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -7,24 +7,22 @@ description: 'Look up any [CGP-Exxx] code cargo cgp check prints: what the messa # Error codes -When `cargo cgp check` rewrites a CGP error, it tags the message with a code in square brackets, such as -`[CGP-E001]`, so you can look up what the message means. The command is part of the -[`cargo-cgp`](./index.md) toolchain for [Context-Generic Programming (CGP)](/docs/). This page lists every -code with the message it heads, the mistake it means, the fix, and the section that explains the class of -mistake in full, usually in the [compile-errors reference](/docs/reference/errors). -[Reading the output](./reading-output.md) shows how the codes sit inside a complete error. +A code such as `[CGP-E001]` identifies the kind of failure `cargo cgp check` recognized. This page +lists those codes with their message forms, causes, and remedies. The command belongs to the +[`cargo-cgp`](./index.md) toolchain for [Context-Generic Programming (CGP)](/docs/). +[Reading the output](./reading-output.md) places the codes in complete diagnostics, while the +[compile-errors reference](/docs/reference/errors) explains the underlying mistake classes. ## How the codes work -A CGP code sits beside the compiler's own code rather than in place of it. In -`error[E0277]: [CGP-E001] …`, `E0277` is the compiler's code, which `rustc --explain` describes, and -`[CGP-E001]` is the CGP class the tool recognized. Because a rewritten error restates the compiler's error -and keeps its code, searching your output for a CGP code finds every error of that class. +The CGP code supplements the compiler's own code. In `error[E0277]: [CGP-E001] …`, `E0277` still +refers to the explanation available through `rustc --explain`, while `[CGP-E001]` identifies the +CGP failure. Searching for a CGP code therefore collects the rewritten errors of that class. -The hundreds digit says where in the error a code appears. `CGP-E0xx` codes head the error and classify it -as a whole. `CGP-E1xx` codes label the dependency chain, one per line of the tree beneath a `root cause:` -note. From `CGP-E101` to `CGP-E104` they mark steps along the way, and from `CGP-E110` onward they mark the -cause the chain ends at. +The hundreds digit distinguishes whole-error codes from dependency steps. A `CGP-E0xx` code +heads the diagnostic, while a `CGP-E1xx` code labels a line of its dependency tree. Codes +`CGP-E101` through `CGP-E104` describe the path through requirements; codes from `CGP-E110` onward +identify the cause at the end. In the messages below, a word in angle brackets, such as ``, stands for the name the tool fills in from your code. @@ -36,9 +34,9 @@ causes, so the error usually carries a `root cause:` note and a dependency chain ### CGP-E001 -A context cannot use a component it is expected to use. Either the component is not wired, or something the -wired provider needs is missing, so the context never gets the consumer trait. The headline states the cause -in the words of its chain line: +The context cannot obtain the consumer trait, either because the component has no wiring entry +or because the chosen provider lacks a dependency. The headline names the cause using the same +wording as the corresponding dependency-chain line: ```text [CGP-E001] missing field `height` on `Rectangle` @@ -58,10 +56,11 @@ fix it, follow the `root cause:` note, which names the missing field, derive, wi ### CGP-E002 -A provider does not implement its provider trait for the context, because something the provider requires -does not hold. This is the provider-side version of `[CGP-E001]`, and a failing `#[check_providers(...)]` -assertion in [`check_components!`](/docs/reference/macros/check_components) or a call through the provider's -own path reports it. It also states the cause in its headline, with this class sentence for mixed causes: +The selected provider cannot implement its provider trait for this context because one of its +requirements fails. This is the provider-side form of `[CGP-E001]`, reported by a failing +`#[check_providers(...)]` assertion in [`check_components!`](/docs/reference/macros/check_components) +or a call through the provider's own path. Its headline names the cause, using this class sentence +when causes differ: ```text [CGP-E002] the provider trait `` with context `` is not implemented for provider `` @@ -210,17 +209,19 @@ so you see that as [CGP-E010](#cgp-e010) alone. ### CGP-E016 -Two `check_components!` tables, or two `delegate_and_check_components!` tables, in one module check the same context, -so they share a check-trait name. The message names the macro the tables were written with. +Checking the same context in two `check_components!` tables, or two +`delegate_and_check_components!` tables, in one module gives both checks the same generated +trait name. The message identifies the macro used: ```text [CGP-E016] two `check_components!` tables in one module check `` ``` -To fix it, merge -the tables, or name one table's check trait with `#[check_trait(...)]`. When two attributes give one name, the message -says so instead, and for tables of different macros it names each macro and asks you to rename one check trait. -[The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. +Merge the tables or give one check a distinct name with `#[check_trait(...)]`. If two attributes +explicitly choose the same name, the message identifies that conflict instead. For tables from +different macros, it names both and asks you to rename one check trait. +[The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) +covers these cases. ### CGP-E017 @@ -260,8 +261,9 @@ the parameter and remove it from the entry's generic parameters, as the `help` l ### CGP-E060 -A check entry names no parameters for a component that takes some, so it checks the component at the unit parameters -`()`, which the provider does not implement. +Omitting parameters from a check makes it request the component at unit parameters `()`. +If the provider supports a different parameter set, that check cannot establish the intended +implementation: ```text [CGP-E060] the check of `` on `` names no parameters, so it checks the component at the unit parameters `()` @@ -273,8 +275,9 @@ To fix it, check it at the parameters the `help` line offers, with ### CGP-E061 -Two [`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch) traits in one module declare a method of the same -name, and the macro names its generated items after the method alone. +The generated names for [`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch) depend +on the method name. Two traits declaring the same method in one module therefore produce +colliding generated items: ```text [CGP-E061] two `#[cgp_auto_dispatch]` traits in one module declare the method `` @@ -303,9 +306,11 @@ the consumer trait directly on the context. The `help` line names the provider t ### CGP-E021 -Each step of the lookup requires the consumer trait again for a larger type, so nothing repeats, and the compiler stops -at its recursion limit. No limit ends a lookup that grows, so to fix it, wire a provider whose requirements do not grow. -[A lookup that never terminates](/docs/reference/errors#a-lookup-that-never-terminates) explains the class. +The lookup keeps requesting the consumer trait for a larger type. Because each request differs, +Rust eventually reaches its recursion limit without finding an implementation. Raising that +limit cannot terminate an ever-growing lookup; select a provider whose requirements stop growing. +[A lookup that never terminates](/docs/reference/errors#a-lookup-that-never-terminates) +explains this failure. ```text [CGP-E021] the wiring for the consumer trait `` on context `` never resolves, because each step requires it for a larger type (``, …) @@ -313,18 +318,18 @@ at its recursion limit. No limit ends a lookup that grows, so to fix it, wire a ### CGP-E022 -A crate registers wiring into a namespace it does not own, under a key it does not own either, which Rust's orphan rule -forbids. The compiler's code is `E0210` or `E0117`. +The registration belongs to neither end of the lookup: both its namespace and its key come from +other crates. Rust's orphan rule rejects this with `E0210` or `E0117`: ```text [CGP-E022] cannot register the foreign into the foreign namespace `` ``` -To fix it, own one end, as the `help` line says: key the registration -on a component your crate defines, register it from the crate that owns the namespace, or define a namespace of your own -that inherits the foreign one. +Make one end local, as the `help` line suggests. You can use a component defined in your crate, +move the registration into the namespace's crate, or define a local namespace inheriting the +foreign one. [Registering into a namespace you do not own](/docs/reference/errors#registering-into-a-namespace-you-do-not-own) -explains the class. +explains the ownership requirement. ## Mistakes in what a macro was given @@ -333,9 +338,9 @@ These codes name a CGP attribute or macro used in a way the generated code canno ### CGP-E030 -A `#[cgp_fn]` or `#[cgp_impl]` body calls a CGP trait's method on `self` or `Self` without declaring the trait as a -dependency. The macro turns the body into an implementation over a generated context type, so a trait the body uses has to -be declared for that type to have it. The compiler's code is `E0599`. +A `#[cgp_fn]` or `#[cgp_impl]` body can call a CGP method on `self` or `Self` only when its context +bounds include the trait. The macro generates a generic context, so bringing the trait into scope +alone does not establish that requirement. Omitting the dependency produces `E0599`: ```text [CGP-E030] the trait `` is used but not declared as a dependency @@ -347,8 +352,8 @@ To fix it, add the trait to `#[uses(...)]`, as the ### CGP-E031 -A higher-order provider calls an inner provider it never imported, so the inner provider has no provider-trait bound and -the call cannot resolve. +The higher-order provider calls an inner provider without importing its provider-trait bound. +Without that requirement, Rust cannot resolve the inner call: ```text [CGP-E031] the inner provider `` is used but not imported @@ -372,7 +377,8 @@ class. ### CGP-E033 -`#[cgp_impl]` is applied to a trait that is not a CGP component at all, so there is no provider trait to implement. +The trait named by `#[cgp_impl]` is not a CGP component, so it has no provider trait for the macro +to implement: ```text [CGP-E033] `#[cgp_impl]` can only implement a CGP component's provider trait, but `` is not a CGP component @@ -410,8 +416,9 @@ To fix it, import the type with ### CGP-E036 -A component requires a trait of every context, through [`#[extend(...)]`](/docs/reference/attributes/extend) or -`#[use_type(...)]`, and a `#[cgp_impl]` provider does not declare it, even if its body never uses the trait. +A component can require a trait of every context through +[`#[extend(...)]`](/docs/reference/attributes/extend) or `#[use_type(...)]`. Its provider must +declare that requirement too, even if the provider's method bodies never use it: ```text [CGP-E036] the provider trait `` requires `` of the context, but the provider `` does not declare it @@ -435,21 +442,22 @@ name the consumer trait, as the `help` line says. ### CGP-E038 -`#[cgp_impl(GreetHello)]` without `new` implements the provider trait for a struct nothing declares. +The form `#[cgp_impl(GreetHello)]` implements an existing provider struct. If nothing declares +`GreetHello`, that implementation has no type to target: ```text [CGP-E038] the provider `` is not declared ``` -To fix it, write -`#[cgp_impl(new GreetHello)]` so the macro declares it, or declare the struct yourself. A provider declared elsewhere but not -imported keeps the compiler's `E0425` and its import suggestion instead. -[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) describes the syntax. +Use `#[cgp_impl(new GreetHello)]` to declare the struct with the implementation, or declare it +separately. If a provider is declared elsewhere but not imported, the tool instead keeps the +compiler's `E0425` and import suggestion. +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) describes both declaration forms. ### CGP-E039 -A plain `impl` implements a provider trait. The trait has `IsProviderFor` as a supertrait, and only `#[cgp_provider]` or -`#[cgp_impl]` writes the provider's impl of it. +The provider trait requires `IsProviderFor` as a supertrait, but a plain `impl` does not supply +that implementation. `#[cgp_provider]` and `#[cgp_impl]` generate it alongside the provider impl: ```text [CGP-E039] the impl of `` for `` is written without `#[cgp_provider]` @@ -460,25 +468,27 @@ To fix it, add one of those macros, as the `help` line says. ## Wiring keys and values that do not resolve -These codes replace a name-resolution error on a wiring entry, for a name the tool can settle. Each applies only when no -type of that name exists in your crate or its dependencies, or when the tool can say which name you meant. -[`delegate_components!`](/docs/reference/macros/delegate_components) describes what a key and a value may be. +A wiring name may fail to resolve because it is missing, not imported, or the wrong kind of +item. These codes replace the compiler's message only when the tool can establish that no such +type exists in the crate or its dependencies, or can identify the intended name. +[`delegate_components!`](/docs/reference/macros/delegate_components) explains the permitted keys +and values. ### CGP-E040 -A wiring key names a consumer trait such as `CanGreet`, where its component marker `GreeterComponent` belongs. +The table uses a consumer trait such as `CanGreet` as its key. Wiring needs the corresponding +component marker, such as `GreeterComponent`, to select a provider: ```text [CGP-E040] the wiring key `` is a consumer trait, but a key names a component ``` -To fix it, name -the component, as the `help` line says. +Replace the trait with the component marker named by the `help` line. ### CGP-E041 -A key names a component that exists but is not imported where the table is written, such as `ErrorTypeProviderComponent`, -which the prelude does not export. +The component exists, but the table cannot see it. For example, `ErrorTypeProviderComponent` +needs an explicit import because it is not exported by the prelude: ```text [CGP-E041] the component `` is not in scope @@ -488,8 +498,8 @@ To fix it, add the `use` line the `help` line gives. ### CGP-E042 -A key was guessed from a consumer trait's name with `Component` appended, such as `HasScalarTypeComponent`, while the marker -follows the provider trait, as in `ScalarTypeProviderComponent`. +The key uses a consumer trait's name with `Component` appended, such as `HasScalarTypeComponent`. +The actual marker follows the provider trait's name instead, as in `ScalarTypeProviderComponent`: ```text [CGP-E042] the wiring key `` names no component @@ -499,22 +509,23 @@ To fix it, name the component the `help` line gives. ### CGP-E043 -A wiring value names a provider struct nothing declares, often a misspelling. +The table selects a provider struct that has not been declared, often because its name is +misspelled: ```text [CGP-E043] the provider `` wired for `` is not declared ``` -To fix it, declare the provider or name one that -exists. A `help` line appears when the component has a provider with a similar name. A provider declared elsewhere but not -imported keeps the compiler's `E0425` and its import suggestion instead. +Declare the intended provider or select an existing one. When the component has a provider with +a similar name, a `help` line suggests it. A provider that exists elsewhere but is not imported +keeps the compiler's `E0425` and import suggestion instead. ### CGP-E044 -An `@`-path in a key, or in the value of a `=>` redirect, names a type nothing declares. A path segment that is not a lowercase -identifier stays the type it spells, and only a lowercase one becomes a symbol. So to fix it, declare or import the type, or -write the segment in lowercase. A type declared elsewhere but not imported keeps the compiler's `E0425` and its import -suggestion instead. +A segment in an `@` key or `=>` destination names an undeclared type. Lowercase identifiers +become symbols, while other segments retain their spelling as types, so capitalization can +change the lookup's meaning. Declare or import the intended type, or use lowercase for a symbol. +An existing type that is merely unimported keeps the compiler's `E0425` and import suggestion. ```text [CGP-E044] the type `` in a wiring path is not declared @@ -524,18 +535,20 @@ suggestion instead. ### CGP-E050 -A cast, builder, or extractor operation is called on a value whose field or variant is not in the state the operation needs, or -on a type without the data derive it needs. The headline states the cause, and the chain ends at one of the codes from -`[CGP-E118]` to `[CGP-E126]`, at `[CGP-E110]` for a missing field, or at `[CGP-E117]` for an ordinary bound. For example: +The requested cast, build, or extraction cannot operate on the value in its current state, or +the type lacks the needed data derive. The headline identifies that cause. The chain ends at +`[CGP-E118]` through `[CGP-E126]` for data-state failures, `[CGP-E110]` for a missing field, or +`[CGP-E117]` for an ordinary bound. For example: ```text [CGP-E050] missing variant `Bar` on `Big` ``` -Its class sentence is `` the trait `` is not implemented for `` ``. To fix it, follow the cause: drop a second -setting or extraction, set an unset field, add a missing variant or align a payload type, or add the derive or call the method a -`help` line names. [Extensible variants](/docs/concepts/extensible-variants) and -[extensible records](/docs/concepts/extensible-records) explain what those operations require. +The general class sentence is `` the trait `` is not implemented for `` ``. +Follow the reported cause to choose the correction: remove a duplicate setting or extraction, +set a missing field, supply a compatible variant or payload, or use the derive or method named +in `help`. [Extensible variants](/docs/concepts/extensible-variants) and +[extensible records](/docs/concepts/extensible-records) explain the state each operation requires. ## Steps of the dependency chain @@ -544,8 +557,8 @@ no fix of their own. ### CGP-E101 -This line is a step through a context's consumer trait, and it is usually the first line of the chain. A type without wiring of -its own is named plainly, without the word "context". +The chain usually begins with the consumer trait required of the context. If the type has no +wiring of its own, the message names it without the word “context”. ```text [CGP-E101] consumer trait impl `` for context `` @@ -553,9 +566,9 @@ its own is named plainly, without the word "context". ### CGP-E102 -This line is a step through a provider's provider trait: the context's wiring selected this provider, and the chain continues with -what the provider needs. Directly above a `[CGP-E115]` line for the same provider, which has no such impl, it reads -`` provider trait `` required of provider `` with context `` ``. +The wiring selected this provider, so the chain proceeds through its provider-trait requirements. +If the provider lacks the implementation entirely, a `[CGP-E115]` line follows and this step +instead reads `` provider trait `` required of provider `` with context `` ``. ```text [CGP-E102] provider trait impl `` with context `` for provider `` @@ -592,21 +605,22 @@ The chain ends at a field the context does not have. [CGP-E110] missing field `` on `` ``` -To fix it, add the field, or wire a provider that does not read it. A `help` -line names a similar field when there is one, and otherwise the field to add. -[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met) explains the class. +Add the required field or select a provider that does not read it. The `help` line points to a +similar existing field when possible; otherwise, it names the field to add. +[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met) explains this failure. ### CGP-E111 -The chain ends at a field that exists but has no `HasField` impl, because the struct does not derive it. +The field is present, but generic field access is unavailable because the struct has not derived +`HasField`: ```text [CGP-E111] `HasField` not derived for field `` of `` ``` -To fix it, add -`#[derive(HasField)]` to the struct, as the `help` line says. -[When the derive is missing entirely](/docs/reference/errors#when-the-derive-is-missing-entirely) explains the class. +Add `#[derive(HasField)]` to expose the struct's fields, as the `help` line suggests. +[When the derive is missing entirely](/docs/reference/errors#when-the-derive-is-missing-entirely) +explains the missing access implementation. ### CGP-E112 @@ -629,8 +643,8 @@ To fix it, add the wiring entry the `help` line names. ### CGP-E114 -The chain ends at a provider's own table that has no entry for a key: a bundle of wiring missing a component, or a provider that -dispatches per type missing the type it was given. +The context selected a provider, but that provider's table lacks the requested key. For a bundle, +this can mean a missing component; for per-type dispatch, a missing entry for the supplied type: ```text [CGP-E114] missing entry for `` in provider `` @@ -641,15 +655,17 @@ covers. ### CGP-E115 -The chain ends at a type wired where a provider belongs that is not a provider, such as a value type put in a provider's place. +The selected type cannot supply the required provider trait. A common cause is putting a value +type in the table where a provider belongs: ```text [CGP-E115] `` is not a provider of `` ``` -To fix it, wire an actual provider in that position. A `help` line suggests one when the program supports it: -an adapter such as `WithProvider`, `UseFields` in place of `UseField` on a multi-method getter, an `open` -statement in place of `UseDelegate`, or the right component for a provider of another one. +Select a provider for that component. When the program supports a specific correction, `help` +may suggest an adapter such as `WithProvider`, `UseFields` for a multi-method getter instead +of `UseField`, an `open` statement instead of `UseDelegate`, or the component that matches +the provider you selected. ### CGP-E116 @@ -662,8 +678,9 @@ same wording. ### CGP-E117 -The chain ends at an ordinary Rust trait bound that does not hold, such as `f64: Eq`, in the compiler's own wording. At a -`check_components!` entry the tool keeps the compiler's headline, which already names the bound. +An ordinary Rust bound, such as `f64: Eq`, failed at the end of the dependency chain. The line +keeps the compiler's wording. At a `check_components!` entry, the original headline already +identifies this bound, so the tool keeps it too. ```text [CGP-E117] the trait bound `` is not satisfied @@ -676,7 +693,8 @@ class. ### CGP-E118 -A builder operation needs a field unset, as a second `build_field` or a second merge source does, and the field is already set. +A field can be supplied only while it is unset. A second `build_field` call or a merge source +supplying the same field therefore fails once the builder already contains its value: ```text [CGP-E118] field `` of `` is already set @@ -686,7 +704,8 @@ To fix it, drop the second setting. ### CGP-E119 -An operation such as a finalize or `take_field` needs one or more fields set, and they are not. +Finalization and operations such as `take_field` require the relevant fields to be present. +One or more are still unset in this builder: ```text [CGP-E119] field `` of `` is not set @@ -696,7 +715,8 @@ To fix it, set them first. ### CGP-E120 -A cast between enums has variants that do not match, or a construction uses a tag the enum lacks. +An enum conversion cannot find a compatible variant, or construction uses a tag absent from +the target enum: ```text [CGP-E120] missing variant `` on `` @@ -707,7 +727,8 @@ the name. A `help` line names a similar variant when there is one. ### CGP-E121 -An extractor is finalized while it may still yield a variant, as a matcher that leaves one out does. +Finalization requires an extractor with no possible variants remaining. An unhandled case, +such as a missing matcher branch, leaves this variant available: ```text [CGP-E121] variant `` of `` is not extracted @@ -717,7 +738,8 @@ To fix it, handle the variant. ### CGP-E122 -A cast between enums has same-named variants that carry different payloads. +The enums share this variant's name, but disagree on its payload type. That prevents the cast +from transferring the payload: ```text [CGP-E122] variant `` on `` has type ``, but `` is required @@ -737,8 +759,8 @@ To fix it, add the derive the `help` line names. ### CGP-E124 -A variant is extracted a second time from an extractor that no longer holds it. The compiler reports this as an `E0308` on the tag -argument. +The extractor has already excluded this variant, so extracting it again is invalid. Rust reports +the mismatch as `E0308` on the tag argument: ```text [CGP-E124] variant `` of `` is already extracted @@ -759,8 +781,8 @@ first, as the `help` line says. ### CGP-E126 -A builder or extractor is given to an operation that needs a trait only its struct or enum implements, as `downcast` on the remainder -of a downcast is. +The method requires a trait implemented by the original struct or enum, but receives a builder +or extractor instead. Calling `downcast` on a previous downcast's remainder is one example: ```text [CGP-E126] an extractor of `` does not implement `` @@ -770,8 +792,9 @@ To fix it, call the method the `help` line names, such as `downcast_fields`. ### CGP-E127 -A provider's impls differ from the wiring in exactly one argument: the context, or a component parameter, as for a pipeline stage that -takes `u64` after one that returns `String`. +The wiring requests arguments that differ from the provider's implementations in exactly one +position: either the context or a component parameter. For example, a pipeline stage may accept +`u64` while the previous stage returns `String`: ```text [CGP-E127] `` implements `` only for ``, not `` @@ -781,8 +804,9 @@ To fix it, wire a provider for those arguments, or change the type that disagree ### CGP-E128 -A hand-written `DelegateComponent` impl lacks the `IsProviderFor` impl `delegate_components!` writes beside each entry, so a check passes -but every consumer call fails. +Writing `DelegateComponent` by hand can leave out the accompanying `IsProviderFor` implementation +that `delegate_components!` generates. In that case, a component check can pass while every +consumer call fails: ```text [CGP-E128] the wiring of `` on `` has no `IsProviderFor` impl diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 0c6151e6..1b90bde3 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -7,10 +7,10 @@ description: 'Print the Rust your CGP macros generate, narrowed to one module, t # Expand -A [CGP](/docs/) macro generates code you never see, and sometimes the answer to a question is in that -code. `cargo cgp expand`, part of [`cargo-cgp`](./index.md), prints your crate as the compiler sees it -after macro expansion, so you can read what a macro actually generated instead of reasoning about what it -probably generated. It also writes CGP's type-level constructs back in the form you wrote them. +`cargo cgp expand` lets you inspect the Rust generated by a [CGP](/docs/) macro when its expansion +would help explain a requirement or a wiring choice. The command is part of [`cargo-cgp`](./index.md) +and prints the crate after macro expansion. It also writes CGP's type-level constructs back in +the form you used, making the generated code easier to read: ```sh cargo cgp expand --lib @@ -33,9 +33,9 @@ situations come up most often: ## What it looks like -To see what the output looks like, take the `Rectangle` program from the -[Check page](./check.md#check-the-wiring-where-you-write-it) with its `height` field restored, so the -program compiles: +The `Rectangle` program from the [Check page](./check.md#check-the-wiring-where-you-write-it) +gives the expansion a concrete source to compare against. Restore its missing `height` field so +the program compiles: ```rust use cgp::prelude::*; @@ -129,19 +129,18 @@ where impl __CheckRectangle for Rectangle {} ``` -You can find each part of the program in this listing. -[`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) produced a pair of field accessors for -each field, keyed by the field's name. -[`delegate_components!`](/docs/reference/macros/delegate_components) produced the one-line table entry -that selects `RectangleArea`, and an impl that passes the provider's requirements through to `Rectangle`. -Finally, [`check_components!`](/docs/reference/macros/check_components) produced the last line, the -assertion that `Rectangle` can use the component. +You can trace the annotations through the listing. +[`#[derive(HasField)]`](/docs/reference/derives/derive_has_field) generated each field's accessors, +while [`delegate_components!`](/docs/reference/macros/delegate_components) selected `RectangleArea` +and forwarded its requirements. At the end, +[`check_components!`](/docs/reference/macros/check_components) supplied the assertion that +`Rectangle` can use the component. ## Narrowing with `--item` -A whole crate's expansion is long: for this small program it is 148 lines, against 49 for `Rectangle` -alone. So `--item` narrows the output to one module or item. The option takes a `::`-separated path naming -something inside the crate, and what you get depends on what it names: +Even this small crate expands to 148 lines, while the `Rectangle` selection above takes 49. +To keep the relevant code together, `--item` accepts a `::`-separated path to a module or item +inside the crate: ```sh cargo cgp expand --lib --item shapes # a module: its contents @@ -151,16 +150,14 @@ cargo cgp expand --lib --item AreaCalculator # a trait: its definition and e A leading `crate::` is accepted, so `--item crate::shapes` and `--item shapes` are the same request. -Naming a component's provider trait is usually the most useful form, because most of a component's -generated items are impls of it. For this program, `--item AreaCalculator` gives the -provider trait itself, the blanket impl that lets a context's wiring pick the provider, the impls for -the `UseContext` and `RedirectLookup` providers CGP generates for every component, and -`RectangleArea`'s own impl, with the `where` clause that requires the two fields. Naming the consumer -trait instead, as in `--item CanCalculateArea`, gives that trait and the one blanket impl that connects +For a component, selecting the provider trait usually reveals most of the useful generated code. +Here `--item AreaCalculator` includes the trait, its wiring blanket impl, the generated `UseContext` +and `RedirectLookup` impls, and `RectangleArea`'s implementation with its field requirements. +Selecting `CanCalculateArea` instead shows the consumer trait and the blanket impl connecting it to the provider trait. -If the path matches nothing, the tool says so instead of printing the whole crate. Among cargo's -progress lines, it prints: +A path that matches nothing produces an error instead of falling back to the whole crate. +Among cargo's progress lines, you will see: ```text error: no module or item matched `NoSuchThing` @@ -175,8 +172,8 @@ error: no expansion was produced; see the errors above ## Choosing a target -Because `expand` expands exactly one target and passes its other arguments to `cargo rustc`, choosing the -target is cargo's job. A package with both a library and a binary needs to be told which one: +Expansion operates on one target at a time. Since the command forwards target selection to +`cargo rustc`, a package containing both a library and a binary needs an explicit choice: ```sh cargo cgp expand --lib @@ -204,13 +201,13 @@ one argument `expand` reads itself, so for cargo's target-selection options, run ## Why not `cargo-expand` -[`cargo-expand`](https://github.com/dtolnay/cargo-expand) is the general tool, and it works on CGP code. -The reason to use this one is that CGP's generated code is full of type-level constructs, which a general -expander prints the way the compiler stores them. +[`cargo-expand`](https://github.com/dtolnay/cargo-expand) works on CGP code too. The difference +becomes visible in type-level constructs: a general expander formats their compiler representation, +while `cargo cgp expand` recovers CGP's shorthand. -A field name is the clearest case. CGP encodes it as a -[type-level string](/docs/reference/glossary#type-level-string), with one type per character. In the -compiler's own expansion, which is what a general expander formats, the `height` accessor above begins: +For a field name, that compiler representation is a +[type-level string](/docs/reference/glossary#type-level-string) containing a type for each character. +The `height` accessor begins like this before the shorthand is recovered: ```text impl ::cgp::macro_prelude::HasField<::cgp::macro_prelude::Symbol<6, @@ -229,32 +226,33 @@ than a chain of `Cons` cells, a derived field list reads [`Struct! { width: f64, height: f64 }`](/docs/reference/macros/struct), and a namespace key reads `Path!(@app.GreeterComponent)`. -`--item` is the other difference. It selects Rust items rather than filtering text, so asking for a trait -gives every impl of that trait, wherever it sits in the crate. A question about CGP wiring usually takes -that shape. +Selecting by `--item` also keeps the relationships between Rust items together. A trait selection +includes every implementation of that trait in the crate, wherever it was declared. This is useful +when a question about wiring spans several generated implementations. ## What to expect from the output -Every macro is expanded, not only CGP's, so `#[derive(Debug)]` and `println!` appear in their generated -form too. Only the way the type-level constructs are written is specific to CGP. +The command expands the crate's other macros along with CGP's. That means the listing includes +the generated code for `#[derive(Debug)]` and `println!` too; only the formatting of CGP's +type-level constructs is specific to CGP. -The output is for reading rather than compiling. The tool removes the `cgp::macro_prelude::` prefix the -macros put in front of every CGP name, which makes the listing readable but means it does not compile if -you paste it back into your crate. +To keep the listing readable, the tool removes the `cgp::macro_prelude::` qualifiers inserted +by the macros. Those names may then lack the paths needed to resolve in your crate, so the output +is intended for inspection rather than pasting back as compilable source. -`expand` is also not a check. Compilation stops once the macros are expanded, so no type checking runs, a -wiring mistake goes unreported, and the command exits with `0` on a crate that does not type-check. That -makes `expand` useful in the middle of debugging, but for the wiring mistake itself you need -[`cargo cgp check`](./check.md). +Expansion stops before type checking. This lets you inspect a broken program, but it also means +that a wiring mistake can go unreported and the command can exit with `0` for code that does not +type-check. Use [`cargo cgp check`](./check.md) to verify the wiring itself. -An error reported before that point does fail the command, with cargo's exit status. Most such errors, such -as a CGP macro rejecting its input, still print what expanded. A type defined twice, a `macro_rules!` call -that matches no rule, or an unclosed delimiter prints nothing. A closed pipe is not a failure, so -`cargo cgp expand --lib | head` exits as it normally would. +An error before expansion finishes still fails the command with cargo's exit status. Many such +failures, including a CGP macro rejecting its input, leave a partial expansion to read. Others, +such as duplicate type definitions, unmatched `macro_rules!` calls, or unclosed delimiters, +produce no expansion. Piping to a command that closes the stream early is allowed, so +`cargo cgp expand --lib | head` is not treated as a failure. -Finally, `expand` builds the way a check does. It uses the same pinned nightly and the same `target/cgp` -directory as `cargo cgp check`, so the notes on the [Check page](./check.md#what-a-check-does-differently) -apply to it too. +Expansion uses the same pinned nightly and `target/cgp` directory as checking. The +[Check page](./check.md#what-a-check-does-differently) explains the resulting build costs and how +to choose the target directory. --- diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index 41ae20b3..46a240bd 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -7,24 +7,26 @@ description: 'cargo-cgp runs in place of cargo check and reports a CGP compile e # cargo-cgp -[Context-Generic Programming (CGP)](/docs/) is a language extension for Rust, with pluggable trait -implementations at compile-time. Because its macros expand to ordinary Rust, a mistake in CGP code is -often reported in terms of generated traits you never wrote. `cargo-cgp` is the error toolchain that -helps you read those reports: a cargo subcommand you run in place of `cargo check` to see a CGP compile -error with its root cause first, and to see the ordinary Rust your CGP macros generate. +`cargo-cgp` helps you understand compile errors and macro expansions in +[Context-Generic Programming (CGP)](/docs/) code. CGP's macros generate ordinary Rust traits and +implementations, so a compiler error may name that generated machinery while leaving the failed +requirement unclear. Running `cargo cgp check` brings the root cause forward for failures the +tool recognizes. -The tool is optional. CGP is a library on stable Rust, so `cargo check`, `cargo build`, and `cargo test` -all work on a CGP project without it, and you only need `cargo-cgp` when an error is hard to read. +You can keep using ordinary cargo commands alongside it. CGP is a library on stable Rust, so +`cargo check`, `cargo build`, and `cargo test` work without the tool. Reach for `cargo-cgp` when +you need help understanding an error or a macro expansion. ## The problem it solves -Some CGP mistakes produce a compiler error that does not contain its cause. CGP's wiring is lazy: a -[`delegate_components!`](/docs/reference/macros/delegate_components) entry selects a provider without -checking that the context can give the provider what it needs. That check happens later, where the -trait is first used, and from there the compiler often cannot say what went wrong. +A wiring entry can select a provider even when its context lacks a dependency. The +[`delegate_components!`](/docs/reference/macros/delegate_components) table records the choice, +and Rust checks whether it works when the trait is required later. At that later call site, the +compiler can report unsatisfied bounds without exposing the dependency that failed. -The following program shows the problem. `RectangleArea` reads a `width` and a `height` field through -[`#[implicit]`](/docs/reference/attributes/implicit) arguments, but `Rectangle` has no `height`: +For example, this table selects `RectangleArea` for `Rectangle`. The provider obtains `width` +and `height` through [`#[implicit]`](/docs/reference/attributes/implicit) arguments, but the +context supplies only `width`: ```rust use cgp::prelude::*; @@ -108,10 +110,10 @@ help: use associated function syntax instead For more information about this error, try `rustc --explain E0599`. ``` -This message never mentions `height`. It describes the trait machinery CGP generated, and its closing -suggestion, calling `Rectangle::area()`, would fix a different problem. So the cause is not buried in -the output. It is absent, because the compiler set the candidate implementation aside before working -out why it did not apply. +Nothing in this message names `height`. Instead, it reports the generated trait bounds and +suggests calling `Rectangle::area()`, which would address a different problem. The missing field +never reached the diagnostic because the compiler set the candidate implementation aside before +working out why it did not apply. `cargo cgp check` reports the same mistake like this: @@ -132,64 +134,59 @@ error[E0599]: [CGP-E001] missing field `height` on `Rectangle` For more information about this error, try `rustc --explain E0599`. ``` -The compiler's error code and the position stay the same, but the headline now states the cause. Below -it, the tree shows the chain of requirements that led from the call to the missing field, and the `help` -line gives the fix. [Reading the output](./reading-output.md) explains each part. +The rewritten headline identifies `height` immediately. Below it, the tree connects the call +to the provider and its field requirement, followed by a suggested fix. The compiler's code and +source position stay in place, as [Reading the output](./reading-output.md) explains in more detail. ## How it works -Two changes produce that message. The first is that the tool compiles your code under Rust's -next-generation trait solver, which computes the cause the default solver leaves out. In the case above, -the default solver stops at "the trait bounds were not satisfied", while the next-generation solver -works the failed requirement down to the missing `HasField` bound. Without that step, the tool would -have no root cause to print. +To produce this message, the tool first checks the program with Rust's next-generation trait +solver. Where the default solver stops at unsatisfied method bounds, this solver follows the +requirement down to the missing `HasField` bound. That gives the tool a cause it can report. -The second change is that the tool rewrites the errors it recognizes. Where it knows the shape of a CGP -failure, it leads with the cause, draws the chain of requirements as a tree, and tags the message with a -`[CGP-Exxx]` code naming the class of mistake. The compiler's own code stays in the header, so -`rustc --explain` still works, and an error the tool does not recognize passes through as the compiler -wrote it. +The tool then rewrites the failures it recognizes, naming the cause, drawing the dependency chain, +and adding a `[CGP-Exxx]` code for the class of mistake. It retains the compiler's code so +`rustc --explain` still applies. Errors it does not recognize pass through as the compiler wrote them. ## The two commands -Most of the time you will use [`cargo cgp check`](./check.md), which stands in for `cargo check` when you -hit or expect a wiring error. Everything after `check` is passed to `cargo check`, so the flags you -already use work unchanged. +For a wiring error, [`cargo cgp check`](./check.md) is usually the command to reach for. +It accepts the arguments you would pass to `cargo check`, so you can keep the same package, +workspace, and feature selections. -When you want to know what a macro produced rather than guess, use -[`cargo cgp expand`](./expand.md). It prints the Rust your CGP macros generated, with CGP's type-level -constructs written the way you wrote them, so a field name reads `Symbol!("height")` rather than a list -of characters. +If you need to inspect the generated implementation, use [`cargo cgp expand`](./expand.md). +It prints the macro expansion with CGP's type-level constructs in their familiar forms. +For example, a field tag appears as `Symbol!("height")`, making the name readable without +following a list of character types. ## What it costs -Installing the tool takes a nightly toolchain. Because the tool embeds the Rust compiler, it needs one -exact nightly with the compiler's development libraries, which is more than a gigabyte of disk. Setup -downloads that toolchain and builds a driver binary against it. Your project does not switch toolchains, -though, since the tool uses the nightly only for its own check. +To make those diagnostics available, setup downloads one exact nightly and builds the driver +against its compiler libraries. The toolchain occupies more than a gigabyte, so installation +has a cost in both time and disk space. That nightly belongs to the tool's diagnostic pass; +your project keeps its own toolchain. -The first check also rebuilds your dependencies. A check builds into its own `target/cgp` directory under -that nightly, so the first run compiles every dependency once more and keeps a second set of build -artifacts beside your normal ones. Later checks reuse them. +Checking under that nightly also needs a separate build. The tool puts its artifacts in +`target/cgp`, so the first run compiles every dependency again and uses additional disk space. +Later checks reuse those artifacts alongside your normal build output. -If you work with a coding assistant, [CGP's agent skill](/docs/ai/skills) teaches it to run -`cargo cgp check` and read what comes back. That makes the error output cheaper to work through, but it -does not replace reading the conclusion yourself. +[CGP's agent skill](/docs/ai/skills) can help a coding assistant run the check and interpret its +output. You still need to review the diagnosis and proposed change yourself. ## What it does not do -The tool is not a build tool: there is no `cargo cgp build`, `run`, or `test`. CGP compiles on stable Rust -1.89 or newer, so you build, run, and test with ordinary cargo. +For building, running, and testing, keep using ordinary cargo. The tool provides no +`cargo cgp build`, `run`, or `test` commands, and CGP itself compiles on stable Rust 1.89 or newer. -It also does not decide whether your code compiles. A check runs a different compiler and trait solver -from your project's, so treat it as a diagnostic pass, the way Clippy runs under its own settings. Your -own toolchain's `cargo check` is the authority on whether the code builds. +Because this diagnostic pass uses its own compiler and trait solver, its result can differ from +your project's check. Treat it as you would a Clippy run under separate settings, and keep your +own toolchain's `cargo check` as the authority on whether the code builds. -Nor does it improve every error. `cargo cgp check` leads with the root cause for the classes it +Its diagnostic coverage has limits too. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. -[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the ones you are most -likely to meet and where to read about them instead. The tool also reshapes errors only in your -workspace's own crates. +[Reading the output](./reading-output.md#errors-that-pass-through-unchanged) identifies common +cases that pass through and points to their explanations. Rewriting also applies only to crates +inside your workspace. Finally, the tool is tested on Linux. macOS and Windows have not been tested yet. diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index 27f98a57..b013717a 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -7,15 +7,13 @@ description: 'Install cargo-cgp v0.1.0 with cargo and rustup or with Nix, check # Installation -How you install [`cargo-cgp`](./index.md) depends on what your machine already uses: install it with -cargo if your Rust comes from rustup, or with Nix if you use Nix. This page covers version 0.1.0 of the -tool, which is built for CGP v0.8. +To install [`cargo-cgp`](./index.md), choose the path that fits your existing Rust environment: +cargo with rustup, or the Nix flake. This page covers version 0.1.0, built for CGP v0.8. -The cargo path takes two commands because the tool comes in two parts. `cargo-cgp` is the cargo -subcommand you type, and `cargo-cgp-driver` is the program it runs in place of the compiler. The driver -embeds the compiler itself, so it has to be built against one exact nightly toolchain. You never type -that nightly's date, and your project does not switch to it, because the tool uses the nightly for its -own check only. +The cargo path installs the command first, then prepares the compiler it needs. `cargo-cgp` runs +a separate `cargo-cgp-driver`, which embeds the Rust compiler and must match one exact nightly. +Setup chooses that nightly for you. It is used for the tool's checks without changing your +project's toolchain. ## Which path to use @@ -30,43 +28,42 @@ Match what your machine already has to the path for it: ## With cargo -The first command installs the front end, and the second provisions everything else: +Install the front end, then let it prepare the matching driver and nightly: ```sh cargo install --locked cargo-cgp cargo cgp setup ``` -The front end is an ordinary binary with no compiler inside, so `cargo install` builds it with the -toolchain you already have, which must be Rust 1.96 or newer. The `--locked` flag keeps the dependency -versions the release was tested with. +The first command builds an ordinary binary using your existing toolchain, which must be +Rust 1.96 or newer. Its `--locked` flag keeps the dependency versions tested with the release. +The compiler-linked driver is built separately in the setup step. -`cargo cgp setup` then asks rustup to install the pinned nightly with the `rustc-dev` and `llvm-tools` -components. After that, it builds `cargo-cgp-driver` at the same version as the front end under that -nightly and places it beside the front end in `~/.cargo/bin`. This step needs rustup and a network -connection, and it takes a while, since the toolchain is more than a gigabyte and the driver is compiled -on your machine. +During setup, rustup installs the pinned nightly with `rustc-dev` and `llvm-tools`. The tool then +builds the matching version of `cargo-cgp-driver` under that nightly and puts it beside the front +end in `~/.cargo/bin`. Allow time for both the toolchain download, which is more than a gigabyte, +and local driver compilation. This step needs rustup and a network connection. -You run `setup` once after installing, and again only when the tool tells you to. Before every check the -front end runs a quick, read-only test of the toolchain and the driver. If either is missing or the two -do not match, it stops with a message naming `cargo cgp setup` as the fix, rather than downloading -anything on its own. [Troubleshooting](./troubleshooting.md#the-preflight-rejects-the-setup) lists those -messages. +Once setup finishes, ordinary checks only test that the toolchain and driver are present and +match. They do not download or install anything. If that read-only test fails, the message tells +you to run `cargo cgp setup` again; [Troubleshooting](./troubleshooting.md#the-preflight-rejects-the-setup) +explains the possible failures. -`setup` and `update` take no options. Each answers `--help` with what it does instead of running, and -refuses any other argument, so a mistyped flag cannot start an install you did not ask for. +To read what `setup` or `update` will do, pass `--help`. Neither command accepts other options: +an unrecognized argument produces an error before installation begins. ## With Nix -The flake builds both binaries against the pinned nightly and wraps them so they find its libraries -without rustup, which means a machine with only Nix can run the tool: +With Nix, the flake builds both binaries against the pinned nightly and wraps them with the +library paths they need. This supplies the complete setup without rustup: ```sh nix profile install github:contextgeneric/cargo-cgp/v0.1.0 ``` -The `/v0.1.0` suffix pins the install to that release. Without it, the flake tracks the repository's -default branch, which is what you want only if you are following the tool's development. +Including `/v0.1.0` keeps this installation on the documented release. Omitting it selects the +repository's default branch instead, which is appropriate when following development rather +than a release. To pin the tool inside another project's flake, add it as an input and take its default package: @@ -88,10 +85,10 @@ nix run github:contextgeneric/cargo-cgp/v0.1.0 -- check ## Neither rustup nor Nix -If your Rust comes from somewhere else, such as an operating system package, neither path works as it -stands. The driver has to be built against one exact nightly with the compiler's development libraries, -and only rustup or the Nix flake provides that. The usual way forward is to install rustup alongside your -packaged Rust. CGP itself needs neither, since it compiles on any stable Rust 1.89 or newer. +An operating-system Rust package alone does not supply the matching nightly and compiler +libraries the driver needs. The installation paths here obtain those through rustup or the Nix +flake. If you use neither, the usual next step is installing rustup alongside your packaged Rust. +CGP itself still works without either installer on stable Rust 1.89 or newer. ## Checking your install @@ -107,16 +104,16 @@ cargo-cgp 0.1.0 `cargo cgp --help` prints the same line first, followed by the list of commands. -The driver has its own version query, which doubles as a test that the driver can run at all, because the -driver loads the compiler's libraries before printing anything: +To test whether the driver itself can start, ask for its version too. It must load the compiler's +libraries before answering, so this query also tests library loading: ```sh cargo-cgp-driver --version ``` -On the cargo path, that command runs under your default toolchain rather than the pinned nightly, so it -can fail with a library-loading error even when the install is fine. The front end sets up the library -path for the driver every time it runs it, so to probe the driver yourself you need to do the same: +With a cargo installation, running the driver directly uses your default toolchain's environment. +It can therefore fail to load a library even when checks work: the front end normally supplies the +pinned nightly's library path. To supply that path yourself, run: ```sh LD_LIBRARY_PATH="$(rustc +nightly-YYYY-MM-DD --print sysroot)/lib" cargo-cgp-driver --version @@ -132,16 +129,16 @@ pinned-toolchain: nightly-2026-10-10 built-against-rustc: rustc 1.101.0-nightly (32dba69d6 2026-10-09) ``` -The second line names the nightly the driver needs, and the third the compiler it was built with. Your -dates may differ from these, so read them from your own output. +Read the nightly from `pinned-toolchain:` and the compiler identity from `built-against-rustc:` +in your own output. The dates in this example may differ from those in your installation. ## Supported platforms and CGP versions The tool is tested on Linux, and it has not yet been tested on macOS or Windows. -It is built for CGP v0.8. The tool recognizes CGP's errors by the names of the traits and crates CGP -defines, so a project on an older CGP version compiles under it as it would under `cargo check`, but -whether its errors are reshaped has not been tested. +The supported CGP target is v0.8. Recognition depends on CGP's trait and crate names, so older +CGP code is still compiled as it would be under `cargo check`, but rewriting its errors has +not been tested. ## Updating @@ -151,24 +148,23 @@ On the cargo path, one command updates the tool: cargo cgp update ``` -It looks up the published versions on crates.io and does nothing if you already have the newest. When -there is a newer one, it reinstalls the front end and runs the new version's `setup`, so the driver and -the pinned nightly move with it. +The update command checks the published versions on crates.io and leaves an up-to-date install +alone. If it finds a newer version, it reinstalls the front end and runs that version's `setup`, +bringing the driver and pinned nightly into agreement with it. The Nix path has no `cargo cgp update`. Instead, change the version in the flake reference and reinstall the profile, or run `nix flake update cargo-cgp` in a flake that pins the tool as an input. ## Using it in CI -Keep your own toolchain's `cargo check` as the gate in CI, and add the tool for readable failures. The -commands are the same as on your machine, but pin them so a build does not change under you, either with -`cargo install cargo-cgp --version 0.1.0 --locked` followed by `cargo cgp setup`, or with the tagged +In CI, keep your own toolchain's `cargo check` as the build gate and add the tool for readable +diagnostics. Pin its installation so later runs use the same version: either +`cargo install cargo-cgp --version 0.1.0 --locked` followed by `cargo cgp setup`, or the tagged Nix reference. -On the cargo path, every fresh machine downloads the pinned nightly and compiles the driver, which is the -slowest part of the install. If your CI service can cache directories between runs, caching -`~/.cargo/bin` and the pinned nightly under `~/.rustup/toolchains/` avoids repeating that. This page does -not cover any particular CI service, and these setups have not been run there. +A fresh CI machine repeats the nightly download and driver compilation. If the service supports +caching, retaining `~/.cargo/bin` and the pinned nightly in `~/.rustup/toolchains/` avoids that +part of setup on later runs. These instructions have not been tested with a particular CI service. ## Uninstalling @@ -179,17 +175,17 @@ cargo uninstall cargo-cgp cargo-cgp-driver # cargo path: both, since setup in nix profile remove cargo-cgp # Nix path ``` -Neither command removes the pinned nightly, since another tool may use the same toolchain. Remove it -yourself when nothing else needs it. Its name is the `pinned-toolchain:` line of -`cargo-cgp-driver --version`: +Removing the binaries leaves the nightly installed, since other tools may use it. If nothing +else needs it, take the name from the `pinned-toolchain:` line of `cargo-cgp-driver --version` +and remove it with rustup: ```sh rustup toolchain uninstall nightly-YYYY-MM-DD ``` -The `target/cgp` directories the tool built in your projects also stay behind. Because each one sits -inside its project's target directory, `cargo clean` removes it along with your normal build output. To -remove only the tool's artifacts, run `cargo clean --target-dir target/cgp` from the project's root. +Project build artifacts also remain after uninstalling the binaries. A normal `cargo clean` +removes them along with the rest of the project's target directory. To keep the normal build and +remove only the tool's artifacts, run `cargo clean --target-dir target/cgp` from the project root. ## From source @@ -202,9 +198,9 @@ cd cargo-cgp cargo build ``` -Then run the built front end in another project, pointing it at the built driver and turning off the -read-only test, which expects an installed setup. With the test turned off, the tool does not switch to -the pinned nightly for you either, so select it yourself, or the driver will fail to load: +To use that build in another project, point the front end at the built driver and disable the +preflight that expects an installed setup. Disabling management also stops the automatic toolchain +switch, so select the pinned nightly yourself to let the driver load its libraries: ```sh RUSTUP_TOOLCHAIN=nightly-YYYY-MM-DD CARGO_CGP_NO_MANAGE=1 \ diff --git a/docs/cargo-cgp/reading-output.md b/docs/cargo-cgp/reading-output.md index b1bb39a1..5117f136 100644 --- a/docs/cargo-cgp/reading-output.md +++ b/docs/cargo-cgp/reading-output.md @@ -7,13 +7,14 @@ description: 'How to read the errors cargo cgp check prints: the headline and it # Reading the output -When you hold an error from `cargo cgp check`, you want to know what failed, why, and what to change. The -command, part of the [`cargo-cgp`](./index.md) toolchain for -[Context-Generic Programming (CGP)](/docs/), prints ordinary compiler diagnostics, with the CGP errors it -recognizes rewritten into a few fixed shapes that answer those questions. This page takes each shape -apart. Every example comes from running the tool on a complete program. The snippets show the part of the -program that matters, so the line numbers in the output refer to the whole file. For a single code, see -[Error codes](./error-codes.md). +An error from `cargo cgp check` should tell you what failed, why it failed, and what to change. +The command is part of the [`cargo-cgp`](./index.md) toolchain for +[Context-Generic Programming (CGP)](/docs/), and keeps ordinary compiler diagnostics while +rewriting recognized CGP failures into a few recurring forms. + +Each example below was captured from a complete program. The snippets beside it show only the +relevant code, so output line numbers refer to the full file. Read through the examples to learn +the diagnostic forms, or use [Error codes](./error-codes.md) to look up a particular code. ## The parts of a rewritten error @@ -38,7 +39,7 @@ error[E0277]: [CGP-E001] missing field `height` on `Rectangle` For more information about this error, try `rustc --explain E0277`. ``` -The error has five parts, and you can read them in the order they appear: +Read the diagnostic from its headline through the notes and suggested fix: - **The compiler's code:** `error[E0277]` is the code the compiler assigned, and the tool always keeps it. A rewritten error restates the compiler's error rather than replacing it, so `rustc --explain E0277` @@ -52,20 +53,21 @@ The error has five parts, and you can read them in the order they appear: line repeats the root cause where the chain ends. - **The `help` line:** it names a fix, when the tool can confirm one. -The chain matters when the fix is not where the caret points. If the provider in the `[CGP-E102]` line is -not the one you meant to wire, the mistake is in the wiring rather than in the struct, and adding the field -would hide it. +When the caret is far from the cause, follow the chain before applying the suggested fix. +For example, the provider named on the `[CGP-E102]` line may be different from the one you meant +to select. Adding a field would satisfy that provider, but correcting the wiring may be what the +program needs. -The caret stays where the compiler put it: on the `check_components!` entry that asserted the requirement, -or on the call that used the trait when nothing checked it first. The -[Check page](./check.md#try-it-on-a-deliberate-mistake) shows the second case, where the compiler's own -message leaves the cause out entirely. +The caret identifies where Rust was asked to establish the requirement. With `check_components!`, +that is the check entry; otherwise, it may be the first method call that needs the trait. +The [Check page](./check.md#try-it-on-a-deliberate-mistake) shows the call-site failure whose raw +compiler message leaves out the cause. ## Several causes in one error -One requirement can fail for more than one reason, and in that case the tool lists every cause under -`root causes:` and branches the chain to show each one. Here `Rectangle` has a `length` field and neither of -the two the provider reads: +A provider may lack several dependencies at once. In that case, the tool lists them under +`root causes:` and branches the tree to show how each is required. Here the struct supplies +`length`, while its provider reads `width` and `height`: ```rust #[derive(HasField)] @@ -94,20 +96,20 @@ error[E0277]: [CGP-E001] missing fields `width` and `height` on `Rectangle` For more information about this error, try `rustc --explain E0277`. ``` -Fix every listed cause before checking again. Plain `cargo check` reports only the `width` field for this -program, so fixing what it names would surface `height` on the next run. +Both missing fields are visible here, so you can address them together before checking again. +Plain `cargo check` reports only `width` for this program; fixing that alone would expose +`height` on a later run. -The same merging works in the other direction. When several components fail because of one shared mistake, -such as a single missing field that three providers read, the tool reports one error rather than three. Its -caret marks the first check entry, the other entries are labelled "also required here", and the chain -repeats once for each component. +Several components can also fail because of one shared dependency. If three providers read the +same missing field, the tool reports the mistake once. It marks the first check entry with the +caret, labels the others “also required here”, and includes a chain for each component. ## A component nothing is wired for -Sometimes the context has no wiring entry for a component at all. The chain is then short, and its last line -names the entry that is missing. The examples from here on use `App`, a type that stands for an application -and carries its wiring, where the examples above used `Rectangle`, the shape being measured. The error -shapes are the same for both. Here `App` is checked for `FarewellComponent` but wires only the greeter: +When no provider is selected, the dependency chain ends before reaching a provider implementation. +To illustrate this, the next examples switch from the shape context `Rectangle` to `App`, a type +representing an application and its wiring. Both use the same diagnostic forms. Here `App` is +checked for `FarewellComponent`, but selects only a greeter: ```rust delegate_components! { @@ -140,15 +142,16 @@ error[E0277]: [CGP-E001] missing wiring for `FarewellComponent` on `App` For more information about this error, try `rustc --explain E0277`. ``` -There is no `[CGP-E102]` line, because no provider was selected for the chain to pass through. To fix it, add -the entry, or remove the component from the check if the context is not meant to have it. When the component -is routed through a namespace or an `open` statement, the chain gains a `[CGP-E103]` line naming the path the -lookup followed, and the last line names that path rather than the component. +Because no provider was selected, this chain has no `[CGP-E102]` step. Add the missing wiring +entry, or remove the check if the context should not supply this component. If a namespace or +`open` statement routes the lookup, a `[CGP-E103]` step shows that path and the chain ends at the +missing path entry instead. ## A field with the wrong type -A field can also exist but have the wrong type. The headline then states the whole cause, so the error has no -separate `root cause:` line. Here `height` is a `u32` where the provider reads an `f64`: +If the field exists but its type disagrees with the provider, the headline can state that mismatch +directly and needs no separate `root cause:` note. This `height` is a `u32`, while the area +provider expects `f64`: ```rust #[derive(HasField)] @@ -173,15 +176,17 @@ error[E0271]: [CGP-E004] field `height` on `Rectangle` has type `u32`, but `f64` For more information about this error, try `rustc --explain E0271`. ``` -The chain still shows which provider needs the type, which tells you whether to change the field or the -provider. An [abstract type](/docs/concepts/abstract-types) wired one way and required another produces the -same shape with `[CGP-E005]`. +The provider named in the chain tells you where the `f64` requirement came from. Use that to +decide whether the field should change or a different provider should be selected. An +[abstract type](/docs/concepts/abstract-types) that disagrees with a provider's requirement produces +the same form under `[CGP-E005]`. ## An ordinary Rust trait that does not hold -Not every requirement is a CGP one. When a provider needs an ordinary trait that the wired type does not -implement, the compiler's own headline already states the cause, so the tool keeps it and adds only the chain. -Here `CompareScalars` requires `Scalar: Eq`, and `App` wires the scalar type to `f64`, which is not `Eq`: +A provider can also depend on ordinary Rust traits. At a check entry, the compiler already names +a missing ordinary bound in its headline, so the tool keeps that wording and adds a dependency +chain. In this example, `CompareScalars` needs `Scalar: Eq`, while `App` selects `f64`, which +lacks that implementation: ```rust #[cgp_impl(new CompareScalars)] @@ -218,22 +223,23 @@ error[E0277]: the trait bound `f64: Eq` is not satisfied For more information about this error, try `rustc --explain E0277`. ``` -The last line of the chain repeats the compiler's words under `[CGP-E117]`, the code for an ordinary bound. -Reached through a method call rather than a check, the same mistake gets a CGP headline instead, because the -compiler's own headline there talks about the method: +The `[CGP-E117]` line identifies the ordinary bound at the end of the chain, using the compiler's +wording. If the same failure is reached through a method call, the original headline describes +the method instead, so the tool replaces it with a CGP headline: ```text error[E0599]: [CGP-E001] the trait bound `f64: Eq` is not satisfied ``` -The fix is in the types rather than the wiring: wire the scalar type to one that implements the trait, or -relax the provider's bound if it asks for more than it needs. The message names `f64` but not the -`UseType` entry that chose it, so that last step is yours. +To satisfy this requirement, select a scalar type that implements `Eq`, or relax the provider's +bound if its work does not need equality. The message identifies `f64`, but leaves you to trace +that choice back to the `UseType` wiring entry. ## Two entries that claim one key -A wiring conflict looks different from the errors above, because it is reported where it happens, with two -carets and no chain. Here one context wires the same component twice: +When two wiring entries conflict, the error can point directly to them. There is no dependency +chain to follow: the two carets show the competing implementations. For example, this context +selects two providers for the same component: ```rust delegate_components! { @@ -256,15 +262,15 @@ error[E0119]: [CGP-E010] conflicting wiring: `App` wires component `GreeterCompo For more information about this error, try `rustc --explain E0119`. ``` -The two carets point at the two entries, so you only need to remove the one you did not mean. The neighbouring -codes `[CGP-E011]` to `[CGP-E014]` cover the other ways two entries can claim one key, such as a path key that -covers a longer one, or an entry that collides with an `open` statement. +Remove the unintended entry to give this key a single provider. Codes `[CGP-E011]` through +`[CGP-E014]` cover related overlaps, including a path covering a longer path and a direct entry +colliding with an `open` statement. ## A fix in a `help` line -Some mistakes have one right fix, and for those the `help` line matters more than anything else in the error. -Here a [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) function calls another CGP function on `self` without -declaring it as a dependency: +For some failures, the tool can name the missing declaration directly in a `help` line. +This [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) body calls another CGP function on `self` +without declaring the trait it needs: ```rust #[cgp_fn] @@ -290,11 +296,11 @@ error[E0599]: [CGP-E030] the trait `PersonName` is used but not declared as a de For more information about this error, try `rustc --explain E0599`. ``` -Adding `#[uses(PersonName)]` under `#[cgp_fn]` on `greeting` fixes it, and the same error and fix apply to a -[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider body. The compiler's own message for this mistake -talks about a method that exists for `&__Context__`, a type parameter the macro generated, and never names the -missing attribute. Most of the codes from `[CGP-E030]` to `[CGP-E044]` work this way, each for a different -mistake in what a macro was given. +Here adding `#[uses(PersonName)]` beneath `#[cgp_fn]` on `greeting` supplies the missing requirement. +The same remedy applies inside a [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider body. +Without the rewrite, the compiler refers to a method on the generated `&__Context__` parameter +and never names the attribute. Many codes from `[CGP-E030]` through `[CGP-E044]` similarly +identify a mistake in a macro's input and offer a specific correction. ## Errors that pass through unchanged diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index c2638a4a..2ea1fd24 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -7,14 +7,14 @@ description: 'Match an error from cargo-cgp itself to its cause and fix: the set # Troubleshooting -This page is for when [`cargo-cgp`](./index.md) itself will not run, or behaves in a way you did not -expect. If instead you need help reading a CGP error the tool printed about your code, see -[Reading the output](./reading-output.md). +If [`cargo-cgp`](./index.md) will not start or behaves unexpectedly, begin with the symptom index +below. For a tool that runs but reports an unfamiliar CGP error, [Reading the output](./reading-output.md) +explains the diagnostic instead. -Most failures come from one fact about the tool: `cargo-cgp` is two programs and one exact nightly -toolchain, and all three must match. The `cargo-cgp` front end looks for `cargo-cgp-driver` in its own -directory, and the driver loads the compiler's libraries from the pinned nightly. The tool is tested on -Linux, so the library paths on this page are the Linux ones. +Many startup failures involve a mismatch between the front end, `cargo-cgp-driver`, and the pinned +nightly. The front end normally finds the driver beside itself, and the driver loads that nightly's +compiler libraries. The paths and loader messages here are from Linux, the platform on which the +tool has been tested. ## Start with the symptom index @@ -43,10 +43,10 @@ Each has a section near the end of the page. ## Narrowing it down -If your error is not in the index, run the check once more and read the first line of what it prints. -Before every check, the front end runs a quick, read-only test of the toolchain and the driver, called the -preflight. A message that ends with `` help: run `cargo cgp setup` `` comes from that test, and the -[preflight section](#the-preflight-rejects-the-setup) covers each one. +When the index does not identify the problem, rerun the check and look at its first message. +Before checking code, the front end performs a read-only test of the toolchain and driver, called +the preflight. A message ending in `` help: run `cargo cgp setup` `` comes from that test; +the [preflight section](#the-preflight-rejects-the-setup) explains its possible results. If the preflight passes, run the check verbosely: @@ -54,20 +54,22 @@ If the preflight passes, run the check verbosely: cargo cgp check -v ``` -Each `Running` line that shows a `cargo-cgp-driver … rustc …` command is cargo calling the driver for one -crate. So an error before those lines is a front-end or setup problem, and an error from one of them is a -driver or compiler problem. +Once cargo begins compiling crates, the verbose output includes `Running` lines invoking +`cargo-cgp-driver … rustc …`. A failure before those invocations points to the front end or setup. +A failure from an invocation points to the driver or compiler. ## The preflight rejects the setup -Almost every message in this section is resolved by running `cargo cgp setup`, which installs the pinned -nightly and rebuilds the driver against it at the front end's version. Even so, the messages are worth -reading, because they tell you which part was wrong. The examples show `nightly-2026-10-10`, and yours names -the nightly your build is pinned to. Each message about the driver also names the driver's path and where it -was found: from `CARGO_CGP_DRIVER`, beside `cargo-cgp`, or on `PATH`. +Most failures below can be repaired with `cargo cgp setup`, which installs the pinned nightly +and builds a driver matching both that compiler and the front end. Before rerunning setup, +read the diagnostic to identify which part failed. -The first thing the preflight checks is that the pinned nightly is installed. When it is not, the preflight -quotes rustup's own reason: +The examples name `nightly-2026-10-10`; your output names your build's pinned nightly. Driver +messages also show the binary's path and where it was found: through `CARGO_CGP_DRIVER`, beside +the front end, or on `PATH`. + +The preflight begins by checking for the pinned nightly. If rustup cannot find it, the message +includes rustup's explanation: ```text error: toolchain `nightly-2026-10-10` is not available: @@ -89,8 +91,9 @@ help: install rustup, or install cargo-cgp through its Nix flake, which needs no The [Nix flake](./installation.md#with-nix) runs the front end without the preflight. -Next, the driver has to run under the toolchain. When the toolchain is installed but the driver cannot load -it, the driver was almost always built against a different nightly, and the message keeps the loader's words: +Once the nightly is available, the preflight tries to run the driver under it. Failure at this +point usually means the driver was built against another nightly. The diagnostic includes the +loader's message so you can see which library could not be loaded: ```text error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) could not run under toolchain `nightly-2026-10-10` (it was likely built against a different nightly): @@ -100,8 +103,8 @@ error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside car help: run `cargo cgp setup` ``` -A driver that runs can still be the wrong one. After a partial upgrade, or when an older driver is found first, -its version differs from the front end's: +Starting successfully establishes that the driver can load, but not that it matches the front end. +A partial upgrade or an older binary found first can leave their versions out of agreement: ```text error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) is version 0.0.9, but this cargo-cgp is 0.1.0 (the two are out of lockstep) @@ -109,8 +112,9 @@ error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside car help: run `cargo cgp setup` ``` -Even when their versions match, the driver and the toolchain may no longer belong together, if a different -compiler built the driver than the pinned nightly now provides: +Matching version numbers are not sufficient if the compiler has changed since the driver was +built. The preflight compares the build-time compiler with the one the pinned toolchain now +provides and reports a mismatch: ```text error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) was built against `rustc 1.99.0-nightly (0000000 2026-01-01)`, but toolchain `nightly-2026-10-10` provides `rustc 1.101.0-nightly (32dba69d6 2026-10-09)` @@ -118,8 +122,8 @@ error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside car help: run `cargo cgp setup` ``` -Finally, the program found as the driver may not answer like one at all, such as an unrelated binary with the -same name: +The version query can also reveal that the file found as the driver is an unrelated program, +or otherwise does not return the expected version information: ```text error: could not parse the `--version` output of the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) @@ -127,9 +131,9 @@ error: could not parse the `--version` output of the cargo-cgp-driver at /home/y help: run `cargo cgp setup` ``` -If you are deliberately running a build that `setup` did not install, from a source checkout for example, set -`CARGO_CGP_NO_MANAGE=1` to skip the preflight. The tool then trusts your environment, and keeping the toolchain -matched is up to you. The next section describes what happens when it is not. +For a build from a source checkout, `CARGO_CGP_NO_MANAGE=1` lets you bypass the installed-setup +preflight. You must then supply the matching toolchain yourself. If that environment is wrong, +the failure usually comes from library loading, as described below. ## The driver cannot load the compiler @@ -140,13 +144,13 @@ unlike any other message from the tool: cargo-cgp-driver: error while loading shared libraries: librustc_driver-1a6e695c833ebcd1.so: cannot open shared object file: No such file or directory ``` -The driver links `librustc_driver-.so` from the nightly it was built against, and the hash is fixed when -the driver is built, so yours differs from the one above. The loader could not find that exact library, for one -of two reasons. +The driver needs the exact `librustc_driver-.so` it linked against when built. Your hash may +differ from the example, but the failure means the loader could not find that specific library. +The remedy depends on how the driver was started. -One reason is that you ran the driver yourself, without the library path. The front end sets the path every time -it runs the driver, so a working install still fails this way when you run `cargo-cgp-driver` directly. To fix -that, supply the pinned nightly's `lib` directory: +If you invoked `cargo-cgp-driver` directly, its environment may lack the library path that the +front end normally supplies. Even a working installation can fail this way. Retry with the +pinned nightly's `lib` directory on the path: ```sh LD_LIBRARY_PATH="$(rustc +nightly-YYYY-MM-DD --print sysroot)/lib" cargo-cgp-driver --version @@ -155,9 +159,9 @@ LD_LIBRARY_PATH="$(rustc +nightly-YYYY-MM-DD --print sysroot)/lib" cargo-cgp-dri Put the pinned nightly in place of `nightly-YYYY-MM-DD`. A driver installed with Nix has the path built in and does not need this. -The other reason is that the check ran under a different toolchain from the driver's. With the preflight turned -off, the tool uses whichever toolchain is active, and when that is not the driver's nightly, cargo's first call -to the driver fails: +During a check, the same missing-library error can mean the active toolchain differs from the +one the driver needs. Disabling the preflight also disables automatic nightly selection, so cargo +may try to start the driver under another toolchain: ```text error: process didn't exit successfully: `…/cargo-cgp-driver …/stable-…/bin/rustc -vV` (exit status: 127) @@ -170,8 +174,8 @@ the active toolchain, for example with `RUSTUP_TOOLCHAIN`. Running through the N ## The driver cannot be found -The front end looks for the driver in its own directory, unless `CARGO_CGP_DRIVER` names another path, and looks -on your `PATH` only when the driver is not there. When it finds no driver at all, the preflight reports it: +An explicit `CARGO_CGP_DRIVER` selects the driver path. Otherwise, the front end first looks +beside itself and then falls back to `PATH`. If no driver is available, the preflight reports: ```text error: failed to run the cargo-cgp-driver (none is beside cargo-cgp or on PATH): No such file or directory (os error 2) @@ -189,10 +193,10 @@ Caused by: No such file or directory (os error 2) ``` -Either way, the fix is to make the driver reachable. Run `cargo cgp setup` to install it beside the front end, -point `CARGO_CGP_DRIVER` at the real binary (`target/debug/cargo-cgp-driver` in a source checkout), or run through -the Nix flake, which installs both together. Keep the two in the same directory, because when the driver is -missing there, the front end falls back to any `cargo-cgp-driver` on your `PATH`, which may be an older one. +Restore a reachable driver by running `cargo cgp setup`, selecting the actual binary through +`CARGO_CGP_DRIVER` (such as `target/debug/cargo-cgp-driver` in a checkout), or using the Nix flake +that installs both programs together. Keeping the installed binaries side by side avoids the +fallback to a possibly older driver on `PATH`. ## The command itself fails @@ -204,8 +208,8 @@ error: no such command: `frobnicate` help: the commands are `check`, `expand`, `setup`, and `update` ``` -When the unknown command is `cgp` itself, the message comes from cargo rather than the tool. Cargo found no -`cargo-cgp` on `PATH`, so the tool is not installed, or not on this shell's `PATH`: +An unknown `cgp` command comes from cargo itself: it could not find `cargo-cgp` on `PATH`. +Check that the tool is installed and visible in the shell where you invoked cargo: ```text error: no such command: `cgp` @@ -244,29 +248,30 @@ error: rustup was not found on PATH, and `cargo cgp setup` installs the toolchai help: install rustup, or install cargo-cgp through its Nix flake, which needs no rustup ``` -As the message says, you can install through the [Nix flake](./installation.md#with-nix) instead, or install -rustup first. `setup` also downloads the toolchain and the driver's source, so it needs a network connection. A -failure during either step comes from rustup or cargo, and their message says what went wrong. +You can resolve the missing rustup by installing it first or choosing the +[Nix flake](./installation.md#with-nix). Once rustup is available, setup still needs a network +connection for the toolchain and driver source downloads. Errors during those steps come from +rustup or cargo, whose messages identify the failure. ## The check disagrees with `cargo check` -Your own toolchain's `cargo check` decides whether your code compiles. A check runs a different compiler, a pinned -nightly, with Rust's next-generation trait solver turned on, so on code that relies on nightly-only or -solver-specific behavior the two can disagree. For example, two namespaces that inherit from each other are rejected -by stable Rust and pass the check. When the two disagree, trust `cargo check`, and use the tool for what it is for: -reading the CGP errors both of them report. +When the checks disagree, trust your own toolchain's `cargo check` to decide whether the code +compiles. The tool uses a pinned nightly and the next-generation trait solver, so code relying on +nightly-only or solver-specific behavior can produce a different result. Mutually inheriting +namespaces, for example, pass the tool's check but are rejected by stable Rust. Use the tool to +understand CGP failures while retaining the ordinary check as the build authority. ## The first check is slow -The first check in a project builds every dependency once more, into `target/cgp` inside your project's target -directory, because the check uses its own toolchain and keeps its artifacts apart from your normal build. Later -checks reuse them, from wherever in the project you run them. +A check uses its own toolchain and build artifacts, so its first run recompiles the project's +dependencies into `target/cgp` within the project target directory. Subsequent runs reuse that +build wherever inside the project you invoke them. ## Your own compiler wrapper stopped running -The tool sets cargo's `RUSTC_WORKSPACE_WRAPPER` to its driver for the length of a check, which replaces any value -you set yourself, so a wrapper you configured through that variable does not run during `cargo cgp check`. The tool -says so when it happens, and your normal builds are unaffected: +To rewrite workspace diagnostics, the tool assigns its driver to `RUSTC_WORKSPACE_WRAPPER` for +this run. Any wrapper you selected through that variable is therefore replaced, and the tool +prints a warning. Normal builds keep your original setting: ```text warning: RUSTC_WORKSPACE_WRAPPER is set to `/usr/local/bin/my-wrapper`; cargo-cgp replaces it with its driver for this run, so that wrapper does not run @@ -276,9 +281,9 @@ A wrapper given through `RUSTC_WRAPPER`, such as `sccache`, does keep running al ## Still stuck -Most of these failures share one root: the nightly the driver embeds is not the toolchain present when it runs. So -if you are between sections, `cargo cgp setup` puts the expected pair back in place on the cargo path, and reinstalling -the profile does the same on the Nix path. +If the failure suggests a mismatch but does not fit one section exactly, restoring the matching +nightly and driver is a useful next step. On the cargo path, run `cargo cgp setup`; on the Nix +path, reinstall the profile. Failures not covered here are worth reporting on the [issue tracker](https://github.com/contextgeneric/cargo-cgp/issues). Include the output of `cargo cgp check -v`, From 677d62670aee1285dd914c729a57c86d98d178fd Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 7 Nov 2026 00:44:10 +0100 Subject: [PATCH 211/516] Name the new pinned nightly in the cargo-cgp pages The driver now pins `nightly-2026-11-05` (rustc 1.101.0-nightly (2d20b42b8 2026-11-04)), so the installation, editor-integration, and troubleshooting pages name the new toolchain and compiler version. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/cargo-cgp/editor-integration.md | 6 +++--- docs/cargo-cgp/installation.md | 4 ++-- docs/cargo-cgp/troubleshooting.md | 18 +++++++++--------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/cargo-cgp/editor-integration.md b/docs/cargo-cgp/editor-integration.md index 06eb3d7f..c6dbfb30 100644 --- a/docs/cargo-cgp/editor-integration.md +++ b/docs/cargo-cgp/editor-integration.md @@ -120,10 +120,10 @@ the command's output. For a missing setup, that includes the tool's own diagnost ```text cargo check failed to start: Cargo watcher failed, the command produced no valid metadata (exit code: ExitStatus(unix_wait_status(256))): -error: toolchain `nightly-2026-10-10` is not available: +error: toolchain `nightly-2026-11-05` is not available: - error: toolchain 'nightly-2026-10-10-x86_64-unknown-linux-gnu' is not installed - help: run `rustup toolchain install nightly-2026-10-10-x86_64-unknown-linux-gnu` to install it + error: toolchain 'nightly-2026-11-05-x86_64-unknown-linux-gnu' is not installed + help: run `rustup toolchain install nightly-2026-11-05-x86_64-unknown-linux-gnu` to install it help: run `cargo cgp setup` ``` diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index b013717a..b255f1d8 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -125,8 +125,8 @@ success, the driver prints three lines: ```text cargo-cgp-driver 0.1.0 -pinned-toolchain: nightly-2026-10-10 -built-against-rustc: rustc 1.101.0-nightly (32dba69d6 2026-10-09) +pinned-toolchain: nightly-2026-11-05 +built-against-rustc: rustc 1.101.0-nightly (2d20b42b8 2026-11-04) ``` Read the nightly from `pinned-toolchain:` and the compiler identity from `built-against-rustc:` diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index 2ea1fd24..a3456b54 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -64,7 +64,7 @@ Most failures below can be repaired with `cargo cgp setup`, which installs the p and builds a driver matching both that compiler and the front end. Before rerunning setup, read the diagnostic to identify which part failed. -The examples name `nightly-2026-10-10`; your output names your build's pinned nightly. Driver +The examples name `nightly-2026-11-05`; your output names your build's pinned nightly. Driver messages also show the binary's path and where it was found: through `CARGO_CGP_DRIVER`, beside the front end, or on `PATH`. @@ -72,10 +72,10 @@ The preflight begins by checking for the pinned nightly. If rustup cannot find i includes rustup's explanation: ```text -error: toolchain `nightly-2026-10-10` is not available: +error: toolchain `nightly-2026-11-05` is not available: - error: toolchain 'nightly-2026-10-10-x86_64-unknown-linux-gnu' is not installed - help: run `rustup toolchain install nightly-2026-10-10-x86_64-unknown-linux-gnu` to install it + error: toolchain 'nightly-2026-11-05-x86_64-unknown-linux-gnu' is not installed + help: run `rustup toolchain install nightly-2026-11-05-x86_64-unknown-linux-gnu` to install it help: run `cargo cgp setup` ``` @@ -84,7 +84,7 @@ The front end finds the pinned nightly through rustup, so a machine without rust Here `setup` cannot help, since it needs rustup too: ```text -error: rustup was not found on PATH, and cargo-cgp installs and selects its toolchain `nightly-2026-10-10` through rustup +error: rustup was not found on PATH, and cargo-cgp installs and selects its toolchain `nightly-2026-11-05` through rustup help: install rustup, or install cargo-cgp through its Nix flake, which needs no rustup ``` @@ -96,7 +96,7 @@ point usually means the driver was built against another nightly. The diagnostic loader's message so you can see which library could not be loaded: ```text -error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) could not run under toolchain `nightly-2026-10-10` (it was likely built against a different nightly): +error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) could not run under toolchain `nightly-2026-11-05` (it was likely built against a different nightly): /home/you/.cargo/bin/cargo-cgp-driver: error while loading shared libraries: librustc_driver-1a6e695c833ebcd1.so: cannot open shared object file: No such file or directory @@ -117,7 +117,7 @@ built. The preflight compares the build-time compiler with the one the pinned to provides and reports a mismatch: ```text -error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) was built against `rustc 1.99.0-nightly (0000000 2026-01-01)`, but toolchain `nightly-2026-10-10` provides `rustc 1.101.0-nightly (32dba69d6 2026-10-09)` +error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) was built against `rustc 1.99.0-nightly (0000000 2026-01-01)`, but toolchain `nightly-2026-11-05` provides `rustc 1.101.0-nightly (2d20b42b8 2026-11-04)` help: run `cargo cgp setup` ``` @@ -242,8 +242,8 @@ Caused by: `cargo cgp setup` installs the toolchain through rustup, so without rustup it stops at once: ```text - Installing toolchain `nightly-2026-10-10` with rustc-dev and llvm-tools -error: rustup was not found on PATH, and `cargo cgp setup` installs the toolchain `nightly-2026-10-10` through rustup + Installing toolchain `nightly-2026-11-05` with rustc-dev and llvm-tools +error: rustup was not found on PATH, and `cargo cgp setup` installs the toolchain `nightly-2026-11-05` through rustup help: install rustup, or install cargo-cgp through its Nix flake, which needs no rustup ``` From 321864777ed11112a8f2b98bb1e40bd8ef77634b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 7 Nov 2026 13:07:07 +0100 Subject: [PATCH 212/516] Treat the point-first skill as a local skill The knowledge base no longer publishes the skill, so the contributing page and the root AGENTS.md say it is managed locally instead of pointing at the knowledge-base copy. Co-Authored-By: deepseek-v4.1-flash-1017 --- AGENTS.md | 306 ++++++------------ .../contributing-with-an-agent.md | 9 +- 2 files changed, 103 insertions(+), 212 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e642b4af..15e9716f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,215 +1,107 @@ -# AGENTS.md — the CGP website - -This repository is the public website for Context-Generic Programming, published at -. Everything in `docs/`, `blog/`, and `src/pages/` is read by Rust -developers evaluating CGP, most of whom have never heard of the project's internal documentation. That -audience governs every rule below. - -**Before writing or revising any page, read the knowledge base's documentation for it.** This -repository is deliberately thin on context: it holds the published prose and nothing about where that -prose came from, how current it is, or how it should be framed. All of that lives in the -[CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base), whose -[`website/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/website) section carries -one document per page here — one per blog post, one per tutorial series, and one covering the site's -configuration and standalone pages. Find the document for the page you are about to touch, read it, -follow its links, and only then write. - -## Finding the knowledge base - -Look for the checkout at `../cgp-knowledge-base` first; the CGP repositories are expected to sit side -by side under one parent directory, and a local checkout reflects work that has not been pushed. When -it is absent, read the files from - on the `main` branch. - -The sibling repositories worth knowing about are the same ones the knowledge base lists: -[`cgp`](https://github.com/contextgeneric/cgp) is the library and the ground truth for any code claim, -[`cargo-cgp`](https://github.com/contextgeneric/cargo-cgp) is the error toolchain, -[`cgp-skills`](https://github.com/contextgeneric/cgp-skills) is the source of the agent skill this -site publishes under `docs/ai/skills/` through a submodule, and [`hypershell`](https://github.com/contextgeneric/hypershell) and -[`cgp-serde`](https://github.com/contextgeneric/cgp-serde) are the projects built with CGP. - -## Never link from a published page into the knowledge base - -The knowledge base is internal documentation written for AI agents. It records unfinished work, known -defects, and vocabulary that assumes a loaded agent skill, and it is not written for the public. A -link from a page here into it would expose material intended for a different audience and would be -useless to any reader who does not have that repository. - -A published page may link only to public resources: other pages on this site, the -[`cgp` repository](https://github.com/contextgeneric/cgp) and its siblings, -[docs.rs](https://docs.rs/cgp), [crates.io](https://crates.io/crates/cgp), and ordinary external -sources. - -**The CGP Patterns book and the Hermes SDK are legacy resources: no page links, lists, or recommends -either.** Point a reader who wants a first-principles explanation or a real system built with CGP at -this site's Concepts and Projects pages instead. A page that already mentions one is for the author to -change, since an acknowledgement of where CGP came from is the author's to keep or drop. The knowledge -base's [website rules](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/AGENTS.md#leave-legacy-resources-off-public-pages) -state the rule in full. - -**Two hand-written surfaces are sanctioned exceptions, and only two.** `docs/ai/disclaimer.md` links -to the knowledge base repository, because the base is the subject it discloses: the page's argument -is that CGP's documentation is written against a public record whose rules and history a reader can -go and check, and that argument cannot be made while hiding the record. The pages under -`docs/ai/knowledge-base/` link to it because they explain the base and teach readers to point an -agent at it, which cannot be done without naming its files. Neither reason behind the rule applies -to either surface: the links are public GitHub URLs that resolve for anyone, and exposing the -material is the point rather than an accident. - -Each exception has a bound. The disclaimer links the repository's front door and its issue tracker, -where readers report problems in the base. The knowledge-base pages may also link the four top-level -entry files (`README.md`, `summary.md`, `AGENTS.md`, and `sibling-projects.md`), and never a -document inside a section, since a reader following such a link lands in prose written for agents; -they name a section's directory in prose instead. Do not "correct" these links, and do not extend -the exception to any other page. The knowledge base's [website -rules](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/AGENTS.md#the-one-way-link-rule) -are the authority on both bounds. - -This file is the exception, because it is not published — Docusaurus renders `docs/`, `blog/`, and -`src/pages/`, and a repository-root Markdown file is never part of the built site. So it may point at -internal material freely, and that is precisely its job. - -## Verify every code snippet against the current library - -Any Rust that appears on a page must compile against the current `cgp` release. Check it against the -[`cgp` source](https://github.com/contextgeneric/cgp) or its tests, and load the CGP agent skill -before writing CGP code, so that the snippet uses the idioms the library currently prefers rather than -ones that merely still parse. - -**Never copy current syntax out of an existing blog post on this site.** Almost every post predates -the current release, and the drift is not cosmetic — posts from as recently as 2026 show -`#[cgp_context]`, `cgp_preset!`, `#[cgp_inherit]`, `HasCgpProvider`, the `Async` trait, `ProvideType`, -and `symbol!`, none of which exist in the current release, and inside-out `#[cgp_provider]` -implementations, which still compile but are what current code reads rather than writes. The knowledge -base's document for each post lists exactly what is stale in it, and its -[`releases/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/releases) section carries -a removal ledger that dates every renamed or deleted construct in one table. The safest source of -verified snippets is the knowledge base's -[`examples/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/examples) directory, -which exists partly to be quoted. When a page quotes a project built with CGP, such as a crate of -`cgp-examples`, check the snippet against that project's section under -[`projects/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/projects), which records -the project's current code and whether it uses current idioms. - -## Name official versions only - -Every page names official release versions, `cgp` 0.8.0 and `cargo-cgp` 0.1.0, as though they had -already shipped, and never a pre-release such as `0.8.0-alpha` or `0.1.0-alpha`. Pre-releases are -test runs of the crates and the cargo integration before an official release, not versions a reader -is expected to have, so no page names one, explains how one differs, or tells a reader how to move -off one. Command output that names a pre-release version is quoted with the official version. The -rule is the knowledge base's -[rule on versions](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md#document-official-versions-never-pre-releases), -and it yields only to an explicit instruction from the user. - -## Consult the communication strategy before writing public prose - -Everything published here is public writing about CGP, and how CGP is presented is a settled matter -rather than an open one. The knowledge base's -[`communication-strategy/`](https://github.com/contextgeneric/cgp-knowledge-base/tree/main/communication-strategy) -section fixes the audience model, the vocabulary, the framing of each claim, and the playbook for each -kind of artifact — the launch post, the tutorial, the landing page, the talk, the thread, the -comparison. Read the document that matches what you are writing before outlining it, not after -drafting it. - -The rule that governs all of it: **honesty is the strategy**. Never publish an invented benchmark, -adoption number, or quotation. Never disparage another crate, language, or community to make CGP look -better; naming where a simpler tool is the right choice is an asset, not a concession. And concede the -genuine costs — the learning curve, the verbose diagnostics, the young ecosystem — wherever a reader -would look for them, because this audience is unusually good at detecting what is being left out. - -## Use natural-writing for concept pages - -When adding or revising a page under `docs/concepts/`, use the natural-writing style of the -`point-first-writing` skill throughout the page. Let sentences build on one another, connect -paragraphs so the reasoning is easy to follow, and vary sentence length. Keep the concept and its -purpose as the subject of the opening, with examples serving as illustrations. - -The knowledge base's [explanation-page writing guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/explanation.md#writing-style) -sets the full style and structure requirements for these pages. - -## Use natural-writing for cargo-cgp pages - -When adding or revising a page under `docs/cargo-cgp/`, use the same natural-writing style -throughout the page, the lookup pages included. Develop explanations in connected paragraphs; -a lookup page does not require point-first paragraphs or sentence fragments. Short error-code entries -may connect the cause, consequence, and remedy in prose. Keep tables and lists for options and other -sets, and code blocks for commands and quoted output. Preserve code headings and anchors so readers -can still look up an individual diagnostic. - -The knowledge base's [tooling-page writing guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/tooling.md#writing-style) -sets the full style requirements for these pages. - -## Do not rewrite published blog posts - -A blog post is dated. A release announcement records what a release did at the time, and editing its -snippets into current syntax would make it claim that an old version shipped features it did not. Leave -published posts as they stand, even when their code no longer compiles. - -When a post is genuinely misleading, the remedies are a short dated note at the top pointing to current -material, or a new post that supersedes it — both decisions for a human to make, not defaults to apply. -The one exception is a post that was published unfinished; the knowledge base's document for such a -post says so explicitly, and ordinary editing applies to it again. - -Pages under `docs/` are the opposite case. They describe CGP as it is now, carry no date, and should be -corrected in place with no changelog note and no record of what they used to say. - -## How the site is built - -This is a stock [Docusaurus](https://docusaurus.io/) installation, and keeping it stock is a deliberate -decision recorded in the [new-website post](https://contextgeneric.dev/blog/new-website): no plugins, -no React beyond the landing page, so that effort goes into Markdown rather than theming. An agent -adding site machinery is working against a stated policy and should raise it rather than assume it. - -Run `yarn start` for a live-reloading dev server and `yarn build` to produce the static output. Where -`yarn` is not on the path, `node_modules/.bin/docusaurus start` and `node_modules/.bin/docusaurus build` -are the same commands. **Check the build's exit status rather than its output.** A failed build leaves -the previous run's `build/` directory in place, so inspecting the generated files after a failure -reports the old site and reads as success. The likeliest cause is a YAML error in front matter — an -unescaped apostrophe inside a single-quoted `title` or `description` is the one that has actually -happened, and it is escaped by doubling it. Deployment runs from the GitHub Actions workflows in -`.github/`, publishing to GitHub Pages under the domain fixed by `static/CNAME`. - -Three configuration details matter when editing. `onBrokenLinks` is set to `throw`, so a dangling -internal link fails the build — a change that renames or moves a page must fix every reference to it in -the same change. The docs sidebar is autogenerated from the directory tree, so a page's position comes -from its `sidebar_position` front matter and its directory's `_category_.json`, never from a -hand-maintained list. And the **announcement bar** in `docusaurus.config.ts` is hardcoded rather than -derived from the newest post, so it must be updated by hand with every release announcement. +# AGENTS.md: the CGP website + +Read the knowledge base's [website section](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/README.md) +for the page you are about to touch before writing. Find the checkout at `../cgp-knowledge-base`, or +read the file on GitHub when it is absent. + +## Universal rules + +The [knowledge base's AGENTS.md](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/AGENTS.md) +is the canonical wording. Read it first; change a universal rule there first, then update this +block to match. These are the actionable rules here: + +- Prefer the local sibling checkout when reading another project. +- Write a cross-project link as a GitHub URL on `main`. +- Name official release versions only, never a pre-release. +- Commit only when the user explicitly asks, on the current branch. +- Verify a claim against the source before writing it. +- Keep every view of the same truth in sync in the same change. +- Ask the user when a decision is ambiguous. +- Apply point-first writing to internal prose. + +## Versions + +- The site describes `cgp` 0.8.0 and `cargo-cgp` 0.1.0. +- Quote command output with the official version. + +## Links + +- Never link a published page into the knowledge base. +- The two hand-written exceptions are `docs/ai/disclaimer.md` and the pages under + `docs/ai/knowledge-base/`, within the bounds the knowledge base's website rules set. +- The published skill pages under `docs/ai/skills/` may cite the knowledge base by deep GitHub URL; + nobody hand-writes them, and another page must not link there. +- Do not correct these links or extend the exception to another page. +- In the knowledge-base pages, name a section's directory in prose rather than linking a document + inside it. +- Link only public resources: other pages on this site, the `cgp` repository and its siblings, + docs.rs, crates.io, and ordinary external sources. + +## Legacy resources + +- Do not link, list, or recommend the CGP Patterns book or the Hermes SDK. +- Point a reader who wants a first-principles explanation or a real system at this site's Concepts and + Projects pages instead. +- Leave the book's record, the project history, and the blog records that mention them as they are. +- Leave an acknowledgement of where CGP came from to the author. + +## Code + +- Verify every snippet against the current `cgp` release, the `cgp` source, or its tests. +- Invoke the `/cgp` skill before writing CGP code. +- Prefer code already verified in the knowledge base's `examples/` directory. +- Never take current syntax from an existing blog post; read the post's internal document for its + stale parts first. +- Put a page's code in the website repository's `example-code/` crate, except a Projects page, whose + code is checked against the project's repository. +- Use the knowledge base's `releases/` directory to date an unfamiliar construct. + +## Public prose + +- Read the communication strategy before outlining or drafting a page. +- Never publish an invented benchmark, adoption figure, or quotation. +- Never disparage another crate, language, or community; say where a simpler tool is the better choice. +- Concede the learning curve, the verbose diagnostics, and the young ecosystem where a reader looks for + them. +- Use natural-writing for `docs/concepts/` and `docs/cargo-cgp/` pages. + +## Blog posts + +- Do not rewrite a published post; it is a dated artifact. +- Annotate a misleading post, supersede it with a new one, or record the drift in its internal + document, as the author decides. +- Never change a published post's `slug`. +- Correct a page under `docs/` in place, without a changelog note. + +## Build + +- Run `yarn start` for the dev server and `yarn build` for the static output, or the `node_modules` + binaries of the same names. +- Check the build's exit status rather than its output. +- Keep `onBrokenLinks` set to `throw`; fix every reference when a page moves. +- Take a page's position from `sidebar_position` and its directory's `_category_.json`. +- Update the announcement bar in `docusaurus.config.ts` by hand with every release announcement. +- Keep the site stock: do not add plugins, and do not add React beyond the landing page. ## Content conventions -Blog posts live at `blog/-.md`, or in a directory with an `index.md` when the post -carries images. Front matter sets `authors: [soares]`, one or more tags from the fixed set in -`blog/tags.yml` (`release`, `deepdive`, `walkthrough`), and usually an explicit `slug`. A -`{/* truncate */}` marker must separate the excerpt from the body, or the build warns. Note that the -existing release slugs are inconsistent — dash-separated versions through v0.6.1, dotted from v0.7.0 — -so match a new post to its neighbours rather than assuming one rule. - -Docs pages set `sidebar_position` and are grouped by directory, with each directory's label and -position in its `_category_.json`. The pages under `docs/ai/skills/` other than `index.md` are -**symlinks** into the [`cgp-skills`](https://github.com/contextgeneric/cgp-skills) submodule at the -repository root, pinned to one revision. Never edit them, since an edit lands in the submodule's -working tree; correct the skill in `cgp-skills`, and leave the submodule pointer for the author to -advance. - -The `notes/` directory is working material rather than site content: a local mirror of the -[Diátaxis](https://diataxis.fr/) documentation framework, and a research note comparing CGP's implicit -arguments to Scala's implicit parameters. Nothing in it is published, and the Diátaxis material is -third-party text kept for reference — read it for guidance on which of the four documentation kinds a -new page should be, but do not edit it and do not copy from it into a page. +- Name a blog post `blog/-.md`, or a directory with an `index.md` when it carries + images. +- Set `authors`, `tags` from the fixed set, and usually an explicit `slug`; separate the excerpt with + `{/* truncate */}`. +- Match a new release slug to its neighbours rather than assuming one rule. +- Do not edit the symlinks under `docs/ai/skills/`; correct the skill in `cgp-skills`, and leave the + submodule pointer to the author. +- Treat a lagging skill snapshot as normal; it is not a defect and needs no issue or fix. +- Treat `notes/` as working material, not site content; do not edit or copy from it. ## Committing -Make git commits **only when explicitly asked**, and treat each such request as authorizing exactly one -commit of the changes then in the working tree. Do not commit as a side effect of finishing a task, do -not bring commits up unprompted, and do not treat one request as turning on automatic committing. -Always commit on the current branch rather than creating or switching one. +- Commit only when the user explicitly asks, one commit per request, on the current branch. +- Do not commit as a side effect, bring commits up unprompted, or treat a request as standing + authorization. -## Update the knowledge base in the same change +## Knowledge base -A page added or substantially changed here needs its knowledge-base document added or revised in the -same change. That document is the only place a page's provenance is recorded — which internal material -it rests on, how current its code is, and what a future revision must preserve — so a page without one -has no recorded history, and a stale one actively misleads the next agent. When the knowledge-base -checkout is not present, say plainly what needs updating there so the work is not silently dropped. +- Add or revise the page's knowledge-base document in the same change. +- State what needs updating in the knowledge base when its checkout is absent. diff --git a/docs/ai/knowledge-base/contributing-with-an-agent.md b/docs/ai/knowledge-base/contributing-with-an-agent.md index b968864f..21cf60ab 100644 --- a/docs/ai/knowledge-base/contributing-with-an-agent.md +++ b/docs/ai/knowledge-base/contributing-with-an-agent.md @@ -69,9 +69,8 @@ git clone https://github.com/contextgeneric/contextgeneric.dev.git The layout matters in these places: -- **The skills inside `cgp`.** The `cgp` repository includes two skills under `.claude/skills/` as - links to sibling checkouts: the CGP skill from `cgp-skills`, and the `point-first-writing` skill - from the knowledge base. Each link resolves only when its repository is cloned next to `cgp`. +- **The skills your agent loads.** The CGP skill lives in `cgp-skills`. The `point-first-writing` + skill is managed locally with your agent's skills, not in the knowledge base. - **The `cargo-cgp` tests.** Its UI test suite compiles fixtures against a `cgp` checkout at `../cgp`. Work on its compiler driver may also consult the Rust compiler's source, which its `AGENTS.md` expects at `../external/rust`. @@ -108,8 +107,8 @@ they can be reviewed together. The rules also ask your agent to load two skills before it works. The CGP skill lives in [`cgp-skills`](https://github.com/contextgeneric/cgp-skills), and the `point-first-writing` skill, -which the rules name for any prose the agent writes, lives in the knowledge base's `skills/` -directory. Make both available to your agent in the way it loads skills. +which the rules name for any prose the agent writes, is managed locally with your agent's skills. +Make both available to your agent in the way it loads skills. The rules also shape how the agent works with you. It stops and asks you when a choice has more than one defensible answer, such as an unclear intended behavior, rather than guessing. And it creates From fbc48961b5d336dabc1912b85e41b52be8652179 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 7 Nov 2026 21:15:14 +0100 Subject: [PATCH 213/516] Use npm for the website's build commands The repository carries only `package-lock.json` and CI installs with `npm ci`, so the build rule now names `npm ci`, `npm start`, and `npm run build` instead of the yarn commands. --- AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 15e9716f..67fb9f45 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,8 +75,8 @@ block to match. These are the actionable rules here: ## Build -- Run `yarn start` for the dev server and `yarn build` for the static output, or the `node_modules` - binaries of the same names. +- Install with `npm ci`, and run `npm start` for the dev server and `npm run build` for the static + output, or the `node_modules` binaries of the same names. - Check the build's exit status rather than its output. - Keep `onBrokenLinks` set to `throw`; fix every reference when a page moves. - Take a page's position from `sidebar_position` and its directory's `_category_.json`. From f42f10141f77535ff7e78ad81e46ed14dd97e8d5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 7 Nov 2026 21:44:59 +0100 Subject: [PATCH 214/516] Replace the stock README and add the code license The README was the Docusaurus template, so it described nothing of this site. It now covers the site's purpose, the `npm` commands, both workflows, the writing rules, and the license split: Apache-2.0 for the source code, with the published pages staying under CC BY-SA 4.0 as the footer states. --- LICENSE | 202 +++++++++++++++++++++++++++++++++++++++++ README.md | 84 ++++++++++++----- example-code/README.md | 19 ++-- 3 files changed, 275 insertions(+), 30 deletions(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..856b6677 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020-2025 Soares Chen, Informal Systems, and CGP contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index b28211a9..64cd53e3 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,83 @@ -# Website +[![Deploy to GitHub Pages](https://github.com/contextgeneric/contextgeneric.dev/actions/workflows/deploy.yaml/badge.svg)](https://github.com/contextgeneric/contextgeneric.dev/actions/workflows/deploy.yaml) +![License: Apache-2.0 for code](https://img.shields.io/badge/license-Apache_2.0-blue.svg) +![Content: CC BY-SA 4.0](https://img.shields.io/badge/content-CC_BY--SA_4.0-lightgrey.svg) +![Node 20+](https://img.shields.io/badge/node-20+-green.svg) -This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator. +# The CGP website: contextgeneric.dev -## Installation +**The public documentation site for [Context-Generic Programming (CGP)](https://contextgeneric.dev/), +published at [contextgeneric.dev](https://contextgeneric.dev/).** -```bash -yarn +The site is a stock [Docusaurus](https://docusaurus.io/) installation: the quickstart, the tutorials, +the concepts, the construct reference, the comparisons, the project pages, the `cargo-cgp` guide, the +AI section, and the blog. It is deliberately unmodified, without plugins or custom React beyond the landing +page, so a contributor's work is almost entirely writing Markdown. + +## Install + +```sh +npm ci ``` -## Local Development +The repository carries `package-lock.json`, and CI installs with `npm ci`, so use `npm` rather than +another package manager. Node 20 or newer is required. + +## Local development -```bash -yarn start +```sh +npm start ``` -This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. +This starts a local development server and opens a browser window. Most changes are reflected live +without restarting the server. ## Build -```bash -yarn build +```sh +npm run build ``` -This command generates static content into the `build` directory and can be served using any static contents hosting service. +This generates the static site into `build/`, which any static host can serve. The build fails on a +broken internal link, because `onBrokenLinks` is set to `throw`, so a moved page needs every reference +fixed in the same change. ## Deployment -Using SSH: +The site deploys from `main` through GitHub Pages, using the workflow in +[`.github/workflows/deploy.yaml`](.github/workflows/deploy.yaml): a push to `main` builds the site and +publishes it. A pull request runs the same build through +[`.github/workflows/test-deploy.yaml`](.github/workflows/test-deploy.yaml) without deploying. -```bash -USE_SSH=true yarn deploy -``` +## Writing a page -Not using SSH: +Read the knowledge base's [website section](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/README.md) +for the page you are about to touch before writing. It records, for every page the site publishes, +what that page says, which knowledge-base documents own its content, and how far its code has drifted +from the current release. The [writing guides](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/README.md) +say how each kind of page should be written. -```bash -GIT_USER= yarn deploy -``` +The site documents `cgp` v0.8.0 and `cargo-cgp` v0.1.0. Verify every snippet against the current +release, the `cgp` source, or its tests, and prefer code already verified in the knowledge base's +`examples/` directory. The `example-code` crate in this repository compiles the snippets the pages +show, so a page cannot drift from the library without a failing test. + +## Links + +A published page never links into the knowledge base, apart from the two hand-written exceptions the +knowledge base's website rules set: `docs/ai/disclaimer.md` and the pages under +`docs/ai/knowledge-base/`. The published skill pages under `docs/ai/skills/` may cite the knowledge +base by deep GitHub URL, because nobody hand-writes them. + +Link only public resources: other pages on this site, the `cgp` repository and its siblings, docs.rs, +crates.io, and ordinary external sources. + +## License + +The repository's source code is licensed under the Apache License, Version 2.0, the same as `cgp`. The +published pages are licensed under +[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), as the site's footer states. + +## Related repositories -If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. +The [CGP knowledge base](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/sibling-projects.md) +lists every repository in the ecosystem and the revision of each to read. diff --git a/example-code/README.md b/example-code/README.md index 7ef622d8..e7896f0d 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -1,9 +1,10 @@ -# Website example code +# Website example code: compiled counterparts of the site's snippets This crate holds compiled counterparts of the code shown on . **It is not part of the website.** Nothing here is rendered, linked, or served, no page refers to it, and readers are not meant to find it. It exists for the agent revising a documentation page, so that the code on -that page can be checked against something the compiler has agreed to rather than read and hoped for. +that page can be checked against something the compiler has agreed to rather than read and assumed +correct. Run it from this directory: @@ -30,7 +31,7 @@ pulls in a module tree that mirrors that section's pages: **A standalone page gets a test binary of its own instead**, since there is no section tree for it to sit in: `tests/quickstart.rs` answers `docs/quickstart.md`. Use this form only for a page that has no -section — a page inside one belongs in that section's module tree. +section; a page inside one belongs in that section's module tree. One file per page, at the matching path with the file name in `snake_case`: @@ -49,7 +50,7 @@ Within a covered section the mapping is mechanical: `docs/concepts/coherence.md` `tests/concepts/coherence.rs`, and `docs/concepts/consumer-and-provider-traits.md` by `tests/concepts/consumer_and_provider_traits.rs`. -A page that shows no code gets no file — `docs/concepts/modularity-hierarchy.md` is prose and tables, +A page that shows no code gets no file: `docs/concepts/modularity-hierarchy.md` is prose and tables, so it has no module here, and neither does a section index. Inside a file, **one module per heading of the page**, named after that heading and in the page's @@ -68,14 +69,14 @@ correct, and confusing an expected difference for a defect wastes more time than **Expected, and not a defect.** A body the page elides as `/* ... */` is filled in here, and every such fill-in carries a comment saying the page elided it. Imports the page omits are present. -Types the page names without declaring — a provider it has not introduced yet, a context it -introduces two sections later — are declared. `check_components!` assertions are added for every +Types the page names without declaring, such as a provider it has not introduced yet or a context it +introduces two sections later, are declared. `check_components!` assertions are added for every wired context, since that is what proves the wiring resolves rather than merely parses, and pages do not show them. Tests are added where a page quotes an output or makes a claim worth pinning. **A defect, in one or the other.** Anything else: a signature, a trait bound, an attribute, a derive, a wiring line, a provider name, an item that exists on one side and not the other. When they -disagree, find out which is wrong rather than assuming — the crate is checked by the compiler and the +disagree, find out which is wrong rather than assuming: the crate is checked by the compiler and the page is not, so the page is the likelier culprit, but a stale file here is worse than no file. ## Code a page deliberately rejects @@ -87,7 +88,7 @@ that it fails. The harness is `tests/compile_fail_tests.rs`. Each fixture is a **complete program** whose only fault is the intended one: the elided bodies are filled in, an item-only snippet carries a trailing `fn main() {}`, and a snippet with statements is -wrapped in `fn main() { ... }` — the way rustdoc wraps the doctest these were carried as before. +wrapped in `fn main() { ... }`, the way rustdoc wraps the doctest these were carried as before. trybuild compares each fixture's output against a sibling `.stderr` file. **What that genuinely guards is the regression that matters: a snippet the page calls rejected that the compiler has started @@ -106,7 +107,7 @@ writes the new path in. ## Generated code Two of these pages show what a macro *generates*, in simplified form. A hand-rolled rendering of such -a listing — as `concepts::consumer_and_provider_traits::how_a_call_finds_its_provider` carries — is a +a listing, as `concepts::consumer_and_provider_traits::how_a_call_finds_its_provider` carries, is a weaker check than the rest of this crate: it shows the listing is structurally sound, not that its text is current. **The authority on what a macro emits is `cargo cgp expand`**, run against the test target the example lives in (for example `cargo cgp expand --test concepts_tests --item …`). Check the From 6cf0d119a47e629b8350dfc399d3785b66377e98 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 7 Nov 2026 23:48:46 +0100 Subject: [PATCH 215/516] Document the `OptionAsRef` helper An `Option<&str>` implicit argument reads any `Option` whose `U` converts to `&str` through `OptionAsRef`, so the field-access section gains a page for the trait and links it from its index. --- docs/reference/traits/field-access/index.md | 4 + .../traits/field-access/option_as_ref.md | 102 ++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 docs/reference/traits/field-access/option_as_ref.md diff --git a/docs/reference/traits/field-access/index.md b/docs/reference/traits/field-access/index.md index ed075154..2a57d7d1 100644 --- a/docs/reference/traits/field-access/index.md +++ b/docs/reference/traits/field-access/index.md @@ -28,6 +28,10 @@ The **provider-side mirrors** are what a getter component is wired through, by w answers a getter. [`FieldGetter`](field_getter.md) is the read side and [`MutFieldGetter`](mut_field_getter.md) the write side. +[`OptionAsRef`](option_as_ref.md) borrows the value inside an `Option` as a `&T`, which is the bound +an `Option<&str>` implicit argument generates so the field may be a `String`, a `Cow`, or a +`Box`. + The **read-through forms** let generic code and getter providers read a field of a field without a lifetime bound on the intermediate type. [`MapField`](map_field.md) is the consumer side and [`FieldMapper`](field_mapper.md) the provider side, and diff --git a/docs/reference/traits/field-access/option_as_ref.md b/docs/reference/traits/field-access/option_as_ref.md new file mode 100644 index 00000000..8e20bde0 --- /dev/null +++ b/docs/reference/traits/field-access/option_as_ref.md @@ -0,0 +1,102 @@ +--- +title: 'OptionAsRef — borrow the value inside an Option' +sidebar_label: 'OptionAsRef' +sidebar_position: 7 +description: 'Borrow the value inside an Option as a &T, the bound an Option<&str> implicit argument generates so the field may be a String, a Cow, or a Box.' +--- + +# `OptionAsRef` + +`OptionAsRef` borrows the value inside an +[`Option`](https://doc.rust-lang.org/core/option/enum.Option.html) as a `&T`, for any `Option` +whose `U` implements `AsRef`. + +## Overview + +The trait lets an [`#[implicit]`](../../attributes/implicit.md) argument of type `Option<&str>` read +any `Option` whose `U` converts to `&str`. The two obvious bounds do not work: requiring the field +to be an `Option` ties it to one type and pulls in `alloc`, and requiring `Value: AsRef` +fails because `Option` does not implement `AsRef`. `OptionAsRef` names the conversion +instead of the field's concrete type. + +The plain `&str` case does not need such a helper, because `AsRef` already covers a `String`, +a `Cow`, and a `Box` field. + +## Definition + +```rust +pub trait OptionAsRef { + fn option_as_ref(&self) -> Option<&T>; +} + +impl OptionAsRef for Option +where + U: AsRef, +{ + fn option_as_ref(&self) -> Option<&T> { + self.as_ref().map(|value| value.as_ref()) + } +} +``` + +The `?Sized` bound is what lets `T` be `str`, which is unsized. + +## Usage + +An `#[implicit] nickname: Option<&str>` argument generates a bound and a binding: + +```rust +Self: HasField + 'static>, +// ... +let nickname: Option<&str> = OptionAsRef::option_as_ref( + HasField::get_field(self, PhantomData::), +); +``` + +The call is fully qualified, so a local trait with the same method name cannot capture it. + +A getter keeps the `Option` field instead, because its `HasField` bound is also used by the +[`WithProvider`](../../providers/with_provider.md) adapter, which expects the field type itself. + +## Examples + +A context with an `Option` field answers the argument, and so does one with an +`Option>` or an `Option>` field: + +```rust +#[cgp_fn] +pub fn describe(&self, #[implicit] nickname: Option<&str>) -> String { + match nickname { + Some(name) => format!("aka {name}"), + None => "anonymous".to_owned(), + } +} + +#[derive(HasField)] +pub struct App { + pub nickname: Option, +} +``` + +## When to use it + +Reach for it only through an `#[implicit]` argument of type `Option<&str>`. A plain `&str` argument +does not need a helper, because `AsRef` already covers the same field types, and a getter keeps +the +`Option` field. + +## Related constructs + +- [`#[implicit]`](../../attributes/implicit.md): the whole table of argument forms. +- [`HasField`](has_field.md): the trait the bound is stated on. + +## Source + +- [`traits/option_as_ref.rs`](https://github.com/contextgeneric/cgp/blob/main/crates/core/cgp-field/src/traits/option_as_ref.rs): + the trait and its blanket impl + +--- + +*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](/docs/ai/disclaimer#documentation-and-reference-pages).* From b15ffbffd2e967090a756c6199d33e111ed6ca6e Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 11:49:40 +0100 Subject: [PATCH 216/516] Build every branch and test the site's snippets in CI The pull-request workflow built only pull requests into `main`, so a push to the release branch was never built, and nothing compiled the code the pages show. The snippet crate had drifted from the library in two ways that a green build would have caught. `test-deploy.yaml` now builds every branch except `main`, which `deploy.yaml` builds before publishing it, and adds a job that checks out `cgp` beside the site and runs the `example-code` tests. The compile-fail snapshots are skipped there, because each quotes the absolute path of the `cgp` checkout and only matches where it was blessed; the README records that and keeps the full command for local runs. Both workflows read the Node version from a new `.nvmrc`, so a Node release cannot change the build without a commit, and the deploy workflow serializes its runs instead of cancelling one mid-deployment. The snippet crate now enables `cgp`'s `alloc` feature, which the error providers its pages use require, and pins its compiler in `rust-toolchain.toml`. The compile-fail snapshots are re-blessed against that pin and the current `cgp`. --- .github/workflows/deploy.yaml | 20 +++++- .github/workflows/test-deploy.yaml | 67 ++++++++++++++++--- .nvmrc | 1 + README.md | 8 ++- example-code/Cargo.toml | 2 +- example-code/README.md | 7 +- example-code/rust-toolchain.toml | 6 ++ ...reading_output_a_fix_in_a_help_line.stderr | 11 +-- ...ng_a_bundle_asks_the_wrong_question.stderr | 2 +- ...handlers_plain_composition_is_wrong.stderr | 4 +- ...mpl_common_mistakes_table_parameter.stderr | 4 +- .../extend_common_mistakes_on_cgp_impl.stderr | 8 +-- ...mmon_mistakes_provider_without_uses.stderr | 10 +-- ...t_common_mistakes_conflicting_types.stderr | 20 ++++-- .../use_provider_usage_component_trait.stderr | 4 +- ...use_type_common_mistakes_misspelled.stderr | 4 +- ...eld_rejected_read_of_an_unset_field.stderr | 4 +- ...t_field_rejected_premature_finalize.stderr | 9 +-- ...atch_common_mistakes_missing_derive.stderr | 8 +-- ...ommon_mistakes_missing_variant_impl.stderr | 4 +- ..._common_mistakes_shared_method_name.stderr | 16 ++--- ...common_mistakes_field_name_mismatch.stderr | 4 +- ...mmon_mistakes_mismatched_error_type.stderr | 18 ++--- ..._common_mistakes_missing_error_type.stderr | 10 +-- ...n_mistakes_use_field_on_two_methods.stderr | 34 +++++----- ..._common_mistakes_aggregate_provider.stderr | 2 +- ...tputs_common_mistakes_ref_component.stderr | 42 ++++++------ ...dlers_common_mistakes_fallible_slot.stderr | 30 ++++----- ...mon_mistakes_borrowed_fallible_slot.stderr | 30 ++++----- ...ndlers_common_mistakes_struct_input.stderr | 16 ++--- ...common_mistakes_multi_method_getter.stderr | 34 +++++----- ...es_bare_use_field_on_type_component.stderr | 34 +++++----- ...d_ref_common_mistakes_unsized_value.stderr | 8 +-- ...mmon_mistakes_downcast_on_remainder.stderr | 4 +- ..._default_common_mistakes_no_default.stderr | 4 +- ...mon_mistakes_optional_needs_default.stderr | 4 +- ...ield_common_mistakes_compare_result.stderr | 14 ++-- ...field_common_mistakes_extract_twice.stderr | 4 +- ...ract_common_mistakes_finalize_early.stderr | 4 +- ...sult_common_mistakes_missing_import.stderr | 40 +++++------ ...sult_common_mistakes_one_step_early.stderr | 9 +-- ...s_common_mistakes_output_not_mapped.stderr | 28 ++++---- ...c_string_common_mistakes_bare_chars.stderr | 10 +-- ...al_common_mistakes_already_optional.stderr | 4 +- ...common_mistakes_marker_not_inferred.stderr | 6 +- .../types/life_definition_not_send.stderr | 17 ++--- ...n_mistakes_match_behind_a_reference.stderr | 8 +-- 47 files changed, 352 insertions(+), 285 deletions(-) create mode 100644 .nvmrc create mode 100644 example-code/rust-toolchain.toml diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index 113b6d21..c8690d57 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -7,10 +7,23 @@ on: # Review gh actions docs if you want to further define triggers, paths, etc # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on +# Serialize deployments instead of cancelling them: a cancelled deploy can leave +# the Pages environment half-updated, so a newer run waits for the current one. +concurrency: + group: pages + cancel-in-progress: false + +permissions: + contents: read + +# To minimize supply-chain exposure this workflow uses only GitHub's own +# first-party actions. The site is built here and published from `main`; every +# other branch and every pull request is built by `test-deploy.yaml`. jobs: build: name: Build Docusaurus runs-on: ubuntu-latest + timeout-minutes: 20 steps: - uses: actions/checkout@v4 with: @@ -20,7 +33,9 @@ jobs: submodules: recursive - uses: actions/setup-node@v4 with: - node-version: 20 + # `.nvmrc` pins the runtime so a Node release cannot change the build + # without a commit. + node-version-file: .nvmrc cache: npm - name: Install dependencies @@ -48,7 +63,8 @@ jobs: url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest + timeout-minutes: 10 steps: - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@v4 \ No newline at end of file + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/test-deploy.yaml b/.github/workflows/test-deploy.yaml index 285ba682..60a39704 100644 --- a/.github/workflows/test-deploy.yaml +++ b/.github/workflows/test-deploy.yaml @@ -1,16 +1,34 @@ name: Test deployment +# `main` is built by `deploy.yaml`, which also publishes it, so this workflow +# builds every other branch and every pull request instead of duplicating that +# build. + +# Review gh actions docs if you want to further define triggers, paths, etc +# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on on: - pull_request: - branches: + push: + branches-ignore: - main - # Review gh actions docs if you want to further define triggers, paths, etc - # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on + pull_request: {} + +# Cancel in-progress runs when a new commit is pushed to the same PR, branch, or tag. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +permissions: + contents: read + +# To minimize supply-chain exposure this workflow uses only GitHub's own +# first-party actions. Each job runs a check the repository's documentation +# lists: the site build from README.md, and the snippet tests from +# example-code/README.md. jobs: - test-deploy: - name: Test deployment + build: + name: Build the site runs-on: ubuntu-latest + timeout-minutes: 20 steps: - uses: actions/checkout@v4 with: @@ -20,10 +38,43 @@ jobs: submodules: recursive - uses: actions/setup-node@v4 with: - node-version: 20 + # `.nvmrc` pins the runtime so a Node release cannot change the build + # without a commit. + node-version-file: .nvmrc cache: npm - name: Install dependencies run: npm ci - name: Test build website - run: npm run build \ No newline at end of file + run: npm run build + + example-code: + name: Snippet tests + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + CARGO_TERM_COLOR: always + steps: + # `example-code` patches `cgp` to a sibling checkout at `../../cgp`, so the + # two repositories are checked out side by side. + - name: Check out the website + uses: actions/checkout@v4 + with: + path: contextgeneric.dev + - name: Check out cgp beside it + uses: actions/checkout@v4 + with: + repository: contextgeneric/cgp + path: cgp + # `example-code/rust-toolchain.toml` pins the compiler the snapshots are + # blessed with; rustup installs that channel from this directory. + - name: Install the pinned Rust toolchain + working-directory: contextgeneric.dev/example-code + run: rustup toolchain install + # The pages' snippets are compiled here, so a page cannot drift from the + # library without a red build. The compile-fail snapshots are skipped + # because each quotes the absolute path of the `cgp` checkout, which only + # matches where it was blessed; run them locally with `cargo test`. + - name: Run the snippet tests + working-directory: contextgeneric.dev/example-code + run: cargo test -- --skip rejected_snippets_do_not_compile diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000..b74495a0 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +24.22.2 diff --git a/README.md b/README.md index 64cd53e3..4c20b1c2 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,8 @@ npm ci ``` The repository carries `package-lock.json`, and CI installs with `npm ci`, so use `npm` rather than -another package manager. Node 20 or newer is required. +another package manager. Node 20 or newer is required. CI runs the version `.nvmrc` pins, and +`nvm use` selects the same one locally. ## Local development @@ -45,8 +46,9 @@ fixed in the same change. The site deploys from `main` through GitHub Pages, using the workflow in [`.github/workflows/deploy.yaml`](.github/workflows/deploy.yaml): a push to `main` builds the site and -publishes it. A pull request runs the same build through -[`.github/workflows/test-deploy.yaml`](.github/workflows/test-deploy.yaml) without deploying. +publishes it. Every other branch and every pull request runs the same build through +[`.github/workflows/test-deploy.yaml`](.github/workflows/test-deploy.yaml) without deploying, and that +workflow also runs the `example-code` snippet tests. ## Writing a page diff --git a/example-code/Cargo.toml b/example-code/Cargo.toml index dc669bb3..ef8656aa 100644 --- a/example-code/Cargo.toml +++ b/example-code/Cargo.toml @@ -7,7 +7,7 @@ description = "Compiled counterparts of the code shown on contextgeneric.dev. No [dependencies] # The `cgp` release the site documents, taken from the repository until it is on crates.io. -cgp = { git = "https://github.com/contextgeneric/cgp.git" } +cgp = { git = "https://github.com/contextgeneric/cgp.git", features = ["alloc"] } [dev-dependencies] anyhow = "1" diff --git a/example-code/README.md b/example-code/README.md index e7896f0d..56262369 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -16,6 +16,10 @@ cargo test --no-run # the fast check: everything compiles, nothing runs The code lives in **integration tests**, which a plain `cargo check` skips; use `cargo test --no-run` (or `cargo check --tests`) for a compile-only pass. The crate has no library or binary target. +CI runs the same suite with the compile-fail snapshots skipped +(`cargo test -- --skip rejected_snippets_do_not_compile`), because each snapshot quotes the absolute +path of the `cgp` checkout and only matches where it was blessed. Run the full command locally. + ## The layout mirrors `docs/` The code lives under `tests/`, as one integration-test binary per `docs/` section. Each entrypoint @@ -102,7 +106,8 @@ TRYBUILD=overwrite cargo test --test compile_fail_tests A snapshot that quotes a line from the `cgp` checkout carries that checkout's absolute path, since the manifest depends on `cgp` by path. The crate's own files and the standard library are written as `tests/…` and `$RUST/…`, so a checkout elsewhere fails only the snapshots naming `cgp`, and re-blessing -writes the new path in. +writes the new path in. A snapshot also quotes rustc's own wording, so +[`rust-toolchain.toml`](rust-toolchain.toml) pins the compiler and a bump re-blesses the suite. ## Generated code diff --git a/example-code/rust-toolchain.toml b/example-code/rust-toolchain.toml new file mode 100644 index 00000000..f94deb8f --- /dev/null +++ b/example-code/rust-toolchain.toml @@ -0,0 +1,6 @@ +# The compiler the snippet checks and their `.stderr` snapshots are blessed with. +# A snapshot quotes rustc's exact wording, so an unpinned channel would turn a +# toolchain update into a red build. Bump this file and re-bless in one change. +[toolchain] +channel = "1.99.0" +profile = "minimal" diff --git a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr index 401e3a7a..63d24917 100644 --- a/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr +++ b/example-code/tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.stderr @@ -5,16 +5,19 @@ error[E0599]: the method `person_name` exists for reference `&__Context__`, but | ^^^^^^^^^^^ method cannot be called on `&__Context__` due to unsatisfied trait bounds | note: the following trait bounds were not satisfied: - `&__Context__: cgp::prelude::HasField>>>>>` - `<&__Context__ as cgp::prelude::HasField>>>>>>::Value = String` - `<__Context__ as cgp::prelude::HasField>>>>>>::Value = String` - `__Context__: cgp::prelude::HasField>>>>>` + `&__Context__: HasField>>>>>` + `__Context__: HasField>>>>>` --> tests/compile_fail/cargo_cgp/reading_output_a_fix_in_a_help_line.rs:5:1 | 5 | #[cgp_fn] | ^^^^^^^^^ 6 | fn person_name(&self, #[implicit] name: &str) -> String { | ^^^^^^^^^^^ + = note: the following trait bounds were not satisfied: + `<__Context__ as Deref>::Target = _` + which is required by `__Context__: PersonName` + `__Context__: cgp::cgp_core::cgp_field::traits::has_field::DerefMap` + which is required by `__Context__: PersonName` = help: items from traits can only be used if the type parameter is bounded by the trait = note: this error originates in the attribute macro `cgp_fn` (in Nightly builds, run with -Z macro-backtrace for more info) help: the following trait defines an item `person_name`, perhaps you need to restrict type parameter `__Context__` with it: diff --git a/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.stderr b/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.stderr index 8a45d920..e009dc97 100644 --- a/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.stderr +++ b/example-code/tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.stderr @@ -4,7 +4,7 @@ error[E0277]: the trait bound `GeometryComponents: CanUseComponent>>>>>>` is not implemented for `GeometryComponents` +help: the trait `HasField>>>>>>` is not implemented for `GeometryComponents` --> tests/compile_fail/concepts/aggregate_providers_checking_a_bundle_asks_the_wrong_question.rs:17:9 | 17 | new GeometryComponents { diff --git a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr index e3879091..c7b6aa63 100644 --- a/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr +++ b/example-code/tests/compile_fail/concepts/monadic_handlers_plain_composition_is_wrong.stderr @@ -4,9 +4,9 @@ error[E0599]: the associated function or constant `compute` exists for struct `P 12 | let _ = PipeHandlers::::compute(&(), PhantomData::<()>, 1u8); | ^^^^^^^ associated function or constant cannot be called due to unsatisfied trait bounds | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/pipe.rs:7:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/pipe.rs:11:1 | - 7 | pub struct PipeHandlers(pub PhantomData); +11 | pub struct PipeHandlers(pub PhantomData); | ---------------------------------- doesn't satisfy `_: Computer<_, _, _>` or `_: IsProviderFor` | = note: the following trait bounds were not satisfied: diff --git a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr index 15bde5c4..61411514 100644 --- a/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr +++ b/example-code/tests/compile_fail/reference/attributes/default_impl_common_mistakes_table_parameter.stderr @@ -5,7 +5,7 @@ error[E0107]: trait takes 2 generic arguments but 3 generic arguments were suppl | ^^^^^^^^^^^^^ expected 2 generic arguments | note: trait defined here, with 2 generic parameters: `T`, `Components` - --> /home/soares/development/context-generic/cgp/crates/core/cgp-component/src/namespaces.rs:5:11 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-component/src/namespaces.rs:17:11 | - 5 | pub trait DefaultImpls1 { +17 | pub trait DefaultImpls1 { | ^^^^^^^^^^^^^ - ---------- diff --git a/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.stderr b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.stderr index 390be45b..8674f016 100644 --- a/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.stderr +++ b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.stderr @@ -11,10 +11,10 @@ error[E0599]: the method `name` exists for reference `&__Context__`, but its tra | ^^^^ method cannot be called on `&__Context__` due to unsatisfied trait bounds | note: the following trait bounds were not satisfied: - `&__Context__: cgp::prelude::HasField>>>>>` - `<&__Context__ as cgp::prelude::HasField>>>>>>::Value = String` - `<__Context__ as cgp::prelude::HasField>>>>>>::Value = String` - `__Context__: cgp::prelude::HasField>>>>>` + `&__Context__: HasField>>>>>` + `<&__Context__ as HasField>>>>>>::Value = String` + `<__Context__ as HasField>>>>>>::Value = String` + `__Context__: HasField>>>>>` --> tests/compile_fail/reference/attributes/extend_common_mistakes_on_cgp_impl.rs:3:1 | 3 | #[cgp_auto_getter] diff --git a/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr index 269e0615..0f9982cf 100644 --- a/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr +++ b/example-code/tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.stderr @@ -4,7 +4,7 @@ error[E0277]: the trait bound `__Context__: HasName` is not satisfied 15 | #[cgp_impl(new GreetHello)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound | - = help: the trait `cgp::prelude::HasField>>>>>` is not implemented for `__Context__` + = help: the trait `HasField>>>>>` is not implemented for `__Context__` note: required for `__Context__` to implement `HasName` --> tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs:3:1 | @@ -28,10 +28,10 @@ error[E0599]: the method `name` exists for reference `&__Context__`, but its tra | ^^^^ method cannot be called on `&__Context__` due to unsatisfied trait bounds | note: the following trait bounds were not satisfied: - `&__Context__: cgp::prelude::HasField>>>>>` - `<&__Context__ as cgp::prelude::HasField>>>>>>::Value = String` - `<__Context__ as cgp::prelude::HasField>>>>>>::Value = String` - `__Context__: cgp::prelude::HasField>>>>>` + `&__Context__: HasField>>>>>` + `<&__Context__ as HasField>>>>>>::Value = String` + `<__Context__ as HasField>>>>>>::Value = String` + `__Context__: HasField>>>>>` --> tests/compile_fail/reference/attributes/extend_common_mistakes_provider_without_uses.rs:3:1 | 3 | #[cgp_auto_getter] diff --git a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr index 5a394b72..cbf8551f 100644 --- a/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr +++ b/example-code/tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.stderr @@ -1,8 +1,8 @@ -error[E0284]: type annotations needed: cannot satisfy `<__Context__ as cgp::prelude::HasField>>>>>>>::Value == u32` +error[E0284]: type annotations needed: cannot satisfy `<__Context__ as HasField>>>>>>>::Value == u32` --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:16 | 10 | #[cgp_impl(new ReadCount)] - | ^^^^^^^^^ cannot satisfy `<__Context__ as cgp::prelude::HasField>>>>>>>::Value == u32` + | ^^^^^^^^^ cannot satisfy `<__Context__ as HasField>>>>>>>::Value == u32` | note: required for `ReadCount` to implement `Counter<__Context__>` --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:1 @@ -13,11 +13,11 @@ note: required for `ReadCount` to implement `Counter<__Context__>` = note: associated types for the current `impl` cannot be restricted in `where` clauses = note: this error originates in the attribute macro `cgp_impl` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0284]: type annotations needed: cannot satisfy `<__Context__ as cgp::prelude::HasField>>>>>>>::Value == u32` +error[E0284]: type annotations needed: cannot satisfy `<__Context__ as HasField>>>>>>>::Value == u32` --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:16 | 10 | #[cgp_impl(new ReadCount)] - | ^^^^^^^^^ cannot satisfy `<__Context__ as cgp::prelude::HasField>>>>>>>::Value == u32` + | ^^^^^^^^^ cannot satisfy `<__Context__ as HasField>>>>>>>::Value == u32` | note: required for `ReadCount` to implement `IsProviderFor` --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:1 @@ -28,10 +28,18 @@ note: required for `ReadCount` to implement `IsProviderFor>>>>>>>::Value == u32` --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:1 | 10 | #[cgp_impl(new ReadCount)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot satisfy `<__Context__ as HasField>>>>>>>::Value == u32` + | + = note: this error originates in the attribute macro `cgp_impl` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0284]: type annotations needed: cannot satisfy `<__Context__ as HasField>>>>>>>::Value == u64` + --> tests/compile_fail/reference/attributes/implicit_common_mistakes_conflicting_types.rs:10:1 + | +10 | #[cgp_impl(new ReadCount)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot satisfy `<__Context__ as HasField>>>>>>>::Value == u64` | = note: this error originates in the attribute macro `cgp_impl` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr index d417fca6..cc3bfaf7 100644 --- a/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr +++ b/example-code/tests/compile_fail/reference/attributes/use_provider_usage_component_trait.stderr @@ -4,9 +4,9 @@ error: cannot find attribute `use_provider` in this scope 22 | #[use_provider(RectangleArea: AreaCalculator)] | ^^^^^^^^^^^^ | - ::: /home/soares/development/context-generic/cgp/crates/macros/cgp-macro/src/lib.rs:135:1 + ::: /home/soares/development/context-generic/cgp/crates/macros/cgp-macro/src/lib.rs:136:1 | -135 | pub fn cgp_provider(attr: TokenStream, item: TokenStream) -> TokenStream { +136 | pub fn cgp_provider(attr: TokenStream, item: TokenStream) -> TokenStream { | ------------------------------------------------------------------------ similarly named attribute macro `cgp_provider` defined here | help: an attribute macro with a similar name exists diff --git a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr index a51bbe43..7a5d5022 100644 --- a/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr +++ b/example-code/tests/compile_fail/reference/attributes/use_type_common_mistakes_misspelled.stderr @@ -4,9 +4,9 @@ error[E0576]: cannot find associated type `Eror` in trait `HasErrorType` 16 | pub fn fail(&self) -> Result<(), Eror> { | ^^^^ | - ::: /home/soares/development/context-generic/cgp/crates/core/cgp-error/src/traits/has_error_type.rs:28:5 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-error/src/traits/has_error_type.rs:14:5 | -28 | type Error: Debug; +14 | type Error: Debug; | ----------------- similarly named associated type `Error` defined here | help: an associated type with a similar name exists diff --git a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr index f0ee8cf1..b44f29c7 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_build_field_rejected_read_of_an_unset_field.stderr @@ -9,7 +9,7 @@ error[E0308]: mismatched types = note: expected struct `PhantomData>>>>>>>>>>>` found struct `PhantomData>>>>>>>>>>` note: method defined here - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/has_field.rs:49:8 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/has_field.rs:15:8 | -49 | fn get_field(&self, _tag: PhantomData) -> &Self::Value; +15 | fn get_field(&self, _tag: PhantomData) -> &Self::Value; | ^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr index 509a6041..924f94b2 100644 --- a/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr +++ b/example-code/tests/compile_fail/reference/derives/derive_extract_field_rejected_premature_finalize.stderr @@ -13,16 +13,11 @@ error[E0599]: the method `finalize_extract_result` exists for enum `Result { - | --------------------- doesn't satisfy `_: FinalizeExtractResult` - | = note: the following trait bounds were not satisfied: `__PartialShape: FinalizeExtract` which is required by `Result>: FinalizeExtractResult` note: the trait `FinalizeExtract` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:38:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:73:1 | -38 | pub trait FinalizeExtract { +73 | pub trait FinalizeExtract { | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr index cb4bd16d..64c86980 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_derive.stderr @@ -7,9 +7,9 @@ error[E0599]: the method `area` exists for reference `&Plain`, but its trait bou 36 | shape.area() | ^^^^ method cannot be called on `&Plain` due to unsatisfied trait bounds | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:33:1 | -19 | pub struct MatchWithValueHandlersRef(pub PhantomData); +33 | pub struct MatchWithValueHandlersRef(pub PhantomData); | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Plain>>::Output = f64`, `<_ as Computer<(), (), &Plain>>::Output = f64`, `_: Computer<(), (), &&Plain>` or `_: Computer<(), (), &Plain>` | note: the following trait bounds were not satisfied: @@ -26,9 +26,9 @@ note: the following trait bounds were not satisfied: 25 | pub trait HasArea { | ------- note: the trait `HasExtractor` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:10:1 | - 6 | pub trait HasExtractor { +10 | pub trait HasExtractor { | ^^^^^^^^^^^^^^^^^^^^^^ = help: items from traits can only be used if the trait is implemented and in scope note: `HasArea` defines an item `area`, perhaps you need to implement it diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr index 0c0ba666..507cdc37 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_missing_variant_impl.stderr @@ -7,9 +7,9 @@ error[E0599]: the method `area` exists for reference `&Shape`, but its trait bou 32 | shape.area() | ^^^^ method cannot be called on `&Shape` due to unsatisfied trait bounds | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:19:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/matchers/match_with_field_handlers.rs:33:1 | -19 | pub struct MatchWithValueHandlersRef(pub PhantomData); +33 | pub struct MatchWithValueHandlersRef(pub PhantomData); | ----------------------------------------------------------- doesn't satisfy `<_ as Computer<(), (), &&Shape>>::Output = f64`, `<_ as Computer<(), (), &Shape>>::Output = f64`, `_: Computer<(), (), &&Shape>` or `_: Computer<(), (), &Shape>` | note: the following trait bounds were not satisfied: diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr index d3e80782..db2f2987 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_dispatch_common_mistakes_shared_method_name.stderr @@ -263,16 +263,16 @@ error[E0277]: the trait bound `for<'__a__> MatchWithHandlersRef<_>: Computer<(), | ---- required by a bound introduced by this call | help: the trait `Computer` is conditionally implemented for `MatchWithHandlersRef` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:13:1 | -12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer -13 | | for MatchWithHandlersRef -14 | | where -15 | | Input: HasExtractorRef, +13 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer +14 | | for MatchWithHandlersRef +15 | | where +16 | | Input: HasExtractorRef, | | --------------- unsatisfied requirement introduced here: `__Variants__: HasExtractorRef` -16 | | DispatchMatchers: -17 | | Computer, Output = Result>, -18 | | Remainder: FinalizeExtract, +17 | | DispatchMatchers: +18 | | Computer, Output = Result>, +19 | | Remainder: FinalizeExtract, | |_______________________________^ = note: required for `UseInputDelegate>>` to implement `for<'__a__> IsProviderFor` = note: 1 redundant requirement hidden diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr index c56061f8..879d3bdc 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_field_name_mismatch.stderr @@ -19,9 +19,9 @@ note: the following trait bounds were not satisfied: 6 | pub trait HasName { | ^^^^^^^ note: the trait `cgp::prelude::HasField` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/has_field.rs:46:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/has_field.rs:10:1 | -46 | pub trait HasField { +10 | pub trait HasField { | ^^^^^^^^^^^^^^^^^^^^^^^ = help: items from traits can only be used if the trait is implemented and in scope note: `HasName` defines an item `name`, perhaps you need to implement it diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr index 1029a6c0..6e462f38 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_mismatched_error_type.stderr @@ -8,12 +8,12 @@ error[E0271]: type mismatch resolving `::Error == String` = note: 1 redundant requirement hidden = note: required for `CheckedAdd` to implement `IsProviderFor` note: required by a bound in `cgp::prelude::TryComputer::try_compute` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/try_compute.rs:8:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/try_compute.rs:13:1 | - 8 | #[cgp_component(TryComputer)] +13 | #[cgp_component(TryComputer)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `TryComputer::try_compute` ... -16 | fn try_compute(&self, _code: PhantomData, input: Input) -> Result; +23 | fn try_compute(&self, _code: PhantomData, input: Input) -> Result; | ----------- required by a bound in this associated function = note: this error originates in the attribute macro `cgp_component` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -24,13 +24,13 @@ error[E0277]: the trait bound `TryPromote: TryComputer` is not implemented for `TryPromote` | help: the trait `TryComputer` is conditionally implemented for `TryPromote` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/try_promote.rs:11:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/try_promote.rs:15:1 | -11 | / impl TryComputer -12 | | for TryPromote -13 | | where -14 | | Context: HasErrorType, -15 | | Provider: Computer>, +15 | / impl TryComputer +16 | | for TryPromote +17 | | where +18 | | Context: HasErrorType, +19 | | Provider: Computer>, | |______________________________________________---------------------------------------_^ | | | unsatisfied requirement introduced here: `>::Output == Result<_, ::Error>` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr index 1de3fe97..24640c0d 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_missing_error_type.stderr @@ -51,15 +51,15 @@ error[E0277]: the trait bound `Promote: TryComputer` i | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TryComputer` is not implemented for `Promote` | help: the trait `TryComputer` is conditionally implemented for `Promote` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/promote.rs:23:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/providers/promote.rs:27:1 | -23 | / impl TryComputer for Promote -24 | | where -25 | | Context: HasErrorType, +27 | / impl TryComputer for Promote +28 | | where +29 | | Context: HasErrorType, | | ------------ | | | | | unsatisfied requirement introduced here: `App: HasErrorType` | | unsatisfied requirement introduced here: `App: HasErrorType` -26 | | Provider: Computer, +30 | | Provider: Computer, | |______________________________________________________________^ = note: required for `Add` to implement `TryComputer` diff --git a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr index dc05eedc..0425c3eb 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_getter_common_mistakes_use_field_on_two_methods.stderr @@ -6,33 +6,33 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:47:1 | -31 | / impl AsyncComputer for UseField -32 | | where -33 | | Context: HasField, -34 | | Context::Value: CanComputeAsync, +47 | / impl AsyncComputer for UseField +48 | | where +49 | | Context: HasField, +50 | | Context::Value: CanComputeAsync, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:27:1 | -69 | / impl IsProviderFor -70 | | for UseField -71 | | where -72 | | Context: HasField, +27 | / impl IsProviderFor +28 | | for UseField +29 | | where +30 | | Context: HasField, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:42:1 | -29 | / impl Computer for UseField -30 | | where -31 | | Context: HasField, -32 | | Context::Value: CanCompute, +42 | / impl Computer for UseField +43 | | where +44 | | Context: HasField, +45 | | Context::Value: CanCompute, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:9:1 | - 5 | #[cgp_getter] + 9 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` = note: required for `Rectangle` to implement `CanUseComponent` note: required by a bound in `__CheckRectangle` diff --git a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.stderr b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.stderr index 1025f6c5..6955ddad 100644 --- a/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.stderr +++ b/example-code/tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.stderr @@ -4,7 +4,7 @@ error[E0277]: the trait bound `GeometryComponents: CanUseComponent>>>>>>` is not implemented for `GeometryComponents` +help: the trait `HasField>>>>>>` is not implemented for `GeometryComponents` --> tests/compile_fail/reference/macros/check_components_common_mistakes_aggregate_provider.rs:16:9 | 16 | new GeometryComponents { diff --git a/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr index 3825dac2..8503d5e8 100644 --- a/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr +++ b/example-code/tests/compile_fail/reference/providers/build_and_merge_outputs_common_mistakes_ref_component.stderr @@ -6,32 +6,32 @@ error[E0277]: the trait bound `BuildWithHandlers` is not implemented for `BuildWithHandlers, Cons, Nil>>>` help: `BuildWithHandlers` implements trait `IsProviderFor` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/build_with_handlers.rs:10:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/build_with_handlers.rs:16:1 | -10 | / impl Computer -11 | | for BuildWithHandlers -12 | | where -13 | | Output: HasBuilder, -14 | | PipeHandlers: Computer, -15 | | Res: FinalizeBuild, +16 | / impl Computer +17 | | for BuildWithHandlers +18 | | where +19 | | Output: HasBuilder, +20 | | PipeHandlers: Computer, +21 | | Res: FinalizeBuild, | |________________________________________^ `IsProviderFor` ... -25 | / impl TryComputer -26 | | for BuildWithHandlers -27 | | where -28 | | Context: HasErrorType, -29 | | Output: HasBuilder, -30 | | PipeHandlers: TryComputer, -31 | | Res: FinalizeBuild, +31 | / impl TryComputer +32 | | for BuildWithHandlers +33 | | where +34 | | Context: HasErrorType, +35 | | Output: HasBuilder, +36 | | PipeHandlers: TryComputer, +37 | | Res: FinalizeBuild, | |________________________________________^ `IsProviderFor` ... -45 | / impl Handler -46 | | for BuildWithHandlers -47 | | where -48 | | Context: HasErrorType, -49 | | Output: HasBuilder, -50 | | PipeHandlers: Handler, -51 | | Res: FinalizeBuild, +51 | / impl Handler +52 | | for BuildWithHandlers +53 | | where +54 | | Context: HasErrorType, +55 | | Output: HasBuilder, +56 | | PipeHandlers: Handler, +57 | | Res: FinalizeBuild, | |________________________________________^ `IsProviderFor` = note: required for `BuildAndMergeOutputs>>` to implement `IsProviderFor` = note: required for `AppBuilder` to implement `CanUseComponent` diff --git a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr index 97562fba..8071fb57 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_handlers_common_mistakes_fallible_slot.stderr @@ -6,24 +6,24 @@ error[E0277]: the trait bound `MatchWithHandlers` is not implemented for `MatchWithHandlers>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` help: `MatchWithHandlers` implements trait `IsProviderFor` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:18:1 | -12 | / impl Computer -13 | | for MatchWithHandlers -14 | | where -15 | | Input: HasExtractor, -16 | | DispatchMatchers: -17 | | Computer>, -18 | | Remainder: FinalizeExtract, +18 | / impl Computer +19 | | for MatchWithHandlers +20 | | where +21 | | Input: HasExtractor, +22 | | DispatchMatchers: +23 | | Computer>, +24 | | Remainder: FinalizeExtract, | |_______________________________^ `IsProviderFor` ... -28 | / impl AsyncComputer -29 | | for MatchWithHandlers -30 | | where -31 | | Input: HasExtractor, -32 | | DispatchMatchers: -33 | | AsyncComputer>, -34 | | Remainder: FinalizeExtract, +34 | / impl AsyncComputer +35 | | for MatchWithHandlers +36 | | where +37 | | Input: HasExtractor, +38 | | DispatchMatchers: +39 | | AsyncComputer>, +40 | | Remainder: FinalizeExtract, | |_______________________________^ `IsProviderFor` = note: required for `App` to implement `CanUseComponent` note: required by a bound in `__CheckApp` diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr index 958d32d5..eb1a7406 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_borrowed_fallible_slot.stderr @@ -6,24 +6,24 @@ error[E0277]: the trait bound `MatchWithHandlersRef` is not implemented for `MatchWithHandlersRef>>>>>>, HandleFieldValue>, Cons>>>>>>>>>, HandleFieldValue>, Nil>>>` help: `MatchWithHandlersRef` implements trait `IsProviderFor` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers_ref.rs:13:1 | -12 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer -13 | | for MatchWithHandlersRef -14 | | where -15 | | Input: HasExtractorRef, -16 | | DispatchMatchers: -17 | | Computer, Output = Result>, -18 | | Remainder: FinalizeExtract, +13 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> Computer +14 | | for MatchWithHandlersRef +15 | | where +16 | | Input: HasExtractorRef, +17 | | DispatchMatchers: +18 | | Computer, Output = Result>, +19 | | Remainder: FinalizeExtract, | |_______________________________^ `IsProviderFor` ... -28 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> AsyncComputer -29 | | for MatchWithHandlersRef -30 | | where -31 | | Input: HasExtractorRef, -32 | | DispatchMatchers: -33 | | AsyncComputer, Output = Result>, -34 | | Remainder: FinalizeExtract, +29 | / impl<'a, Context, Code, Input, Output, Remainder, Handlers> AsyncComputer +30 | | for MatchWithHandlersRef +31 | | where +32 | | Input: HasExtractorRef, +33 | | DispatchMatchers: +34 | | AsyncComputer, Output = Result>, +35 | | Remainder: FinalizeExtract, | |_______________________________^ `IsProviderFor` = note: required for `UseInputDelegate>>` to implement `IsProviderFor` = note: 1 redundant requirement hidden diff --git a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr index 438a87db..e279b967 100644 --- a/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr +++ b/example-code/tests/compile_fail/reference/providers/match_with_value_handlers_common_mistakes_struct_input.stderr @@ -5,16 +5,16 @@ error[E0277]: the trait bound `MatchWithHandlers<_>: cgp::prelude::Computer` is not implemented for `MatchWithHandlers<_>` | help: the trait `cgp::prelude::Computer` is conditionally implemented for `MatchWithHandlers` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-dispatch/src/providers/with_handlers/match_with_handlers.rs:18:1 | -12 | / impl Computer -13 | | for MatchWithHandlers -14 | | where -15 | | Input: HasExtractor, +18 | / impl Computer +19 | | for MatchWithHandlers +20 | | where +21 | | Input: HasExtractor, | | ------------ unsatisfied requirement introduced here: `Scene: HasExtractor` -16 | | DispatchMatchers: -17 | | Computer>, -18 | | Remainder: FinalizeExtract, +22 | | DispatchMatchers: +23 | | Computer>, +24 | | Remainder: FinalizeExtract, | |_______________________________^ = note: required for `UseInputDelegate>>` to implement `IsProviderFor` = note: required for `App` to implement `CanUseComponent` diff --git a/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr index d3f3d86e..feea619e 100644 --- a/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr +++ b/example-code/tests/compile_fail/reference/providers/use_field_common_mistakes_multi_method_getter.stderr @@ -6,33 +6,33 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:47:1 | -31 | / impl AsyncComputer for UseField -32 | | where -33 | | Context: HasField, -34 | | Context::Value: CanComputeAsync, +47 | / impl AsyncComputer for UseField +48 | | where +49 | | Context: HasField, +50 | | Context::Value: CanComputeAsync, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:27:1 | -69 | / impl IsProviderFor -70 | | for UseField -71 | | where -72 | | Context: HasField, +27 | / impl IsProviderFor +28 | | for UseField +29 | | where +30 | | Context: HasField, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:42:1 | -29 | / impl Computer for UseField -30 | | where -31 | | Context: HasField, -32 | | Context::Value: CanCompute, +42 | / impl Computer for UseField +43 | | where +44 | | Context: HasField, +45 | | Context::Value: CanCompute, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:9:1 | - 5 | #[cgp_getter] + 9 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` = note: required for `App` to implement `CanUseComponent` note: required by a bound in `__CheckApp` diff --git a/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr index 8808f50d..53a275f4 100644 --- a/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr +++ b/example-code/tests/compile_fail/reference/providers/with_field_examples_bare_use_field_on_type_component.stderr @@ -6,33 +6,33 @@ error[E0277]: the trait bound `cgp::prelude::UseField` is not implemented for `cgp::prelude::UseField>>>>>>` help: the following other types implement trait `IsProviderFor` - --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:31:1 + --> /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/async_computer.rs:47:1 | -31 | / impl AsyncComputer for UseField -32 | | where -33 | | Context: HasField, -34 | | Context::Value: CanComputeAsync, +47 | / impl AsyncComputer for UseField +48 | | where +49 | | Context: HasField, +50 | | Context::Value: CanComputeAsync, | |__________________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:69:1 + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_field.rs:27:1 | -69 | / impl IsProviderFor -70 | | for UseField -71 | | where -72 | | Context: HasField, +27 | / impl IsProviderFor +28 | | for UseField +29 | | where +30 | | Context: HasField, | |_______________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:29:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-handler/src/components/computer.rs:42:1 | -29 | / impl Computer for UseField -30 | | where -31 | | Context: HasField, -32 | | Context::Value: CanCompute, +42 | / impl Computer for UseField +43 | | where +44 | | Context: HasField, +45 | | Context::Value: CanCompute, | |_____________________________________________________________^ `cgp::prelude::UseField` implements `IsProviderFor` | - ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:5:1 + ::: /home/soares/development/context-generic/cgp/crates/extra/cgp-runtime/src/traits/has_runtime.rs:9:1 | - 5 | #[cgp_getter] + 9 | #[cgp_getter] | ^^^^^^^^^^^^^ `cgp::prelude::UseField<__Tag__>` implements `IsProviderFor` = note: required for `Rectangle` to implement `CanUseComponent` note: required by a bound in `__CheckRectangle` diff --git a/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr index 8c8b8c99..c6dedb53 100644 --- a/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr +++ b/example-code/tests/compile_fail/reference/providers/with_field_ref_common_mistakes_unsized_value.stderr @@ -10,9 +10,9 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t | = help: the trait `Sized` is not implemented for `str` note: required by an implicit `Sized` bound in `UseFieldRef` - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_ref.rs:7:29 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_ref.rs:11:29 | - 7 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); +11 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); | ^^^^^ required by the implicit `Sized` requirement on this type parameter in `UseFieldRef` = note: this error originates in the macro `delegate_components` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -77,7 +77,7 @@ error[E0277]: the size for values of type `str` cannot be known at compilation t | = help: the trait `Sized` is not implemented for `str` note: required by an implicit `Sized` bound in `UseFieldRef` - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_ref.rs:7:29 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/impls/use_ref.rs:11:29 | - 7 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); +11 | pub struct UseFieldRef(pub PhantomData<(Tag, Value)>); | ^^^^^ required by the implicit `Sized` requirement on this type parameter in `UseFieldRef` diff --git a/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr index a81fb9e6..5cc178aa 100644 --- a/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_downcast_fields_common_mistakes_downcast_on_remainder.stderr @@ -21,9 +21,9 @@ error[E0599]: the method `downcast` exists for enum `__PartialFooBarBaz: HasExtractor` which is required by `&mut __PartialFooBarBaz: CanDowncast<_>` note: the trait `HasExtractor` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:6:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:10:1 | - 6 | pub trait HasExtractor { +10 | pub trait HasExtractor { | ^^^^^^^^^^^^^^^^^^^^^^ = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `downcast`, perhaps you need to implement it: diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr index 2b3a423d..05917335 100644 --- a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_no_default.stderr @@ -28,9 +28,9 @@ error[E0599]: the method `finalize_with_default` exists for struct `__PartialSer `&mut __PartialServer: TransformMapFields` which is required by `&mut __PartialServer: CanFinalizeWithDefault` note: the trait `TransformMapFields` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:22:1 | -12 | pub trait TransformMapFields { +22 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `finalize_with_default`, perhaps you need to implement it: diff --git a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr index 7510884b..c03c3adc 100644 --- a/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr +++ b/example-code/tests/compile_fail/reference/traits/can_finalize_with_default_common_mistakes_optional_needs_default.stderr @@ -27,9 +27,9 @@ error[E0599]: the method `finalize_with_default` exists for struct `__PartialSer `&mut __PartialServer: TransformMapFields` which is required by `&mut __PartialServer: CanFinalizeWithDefault` note: the trait `TransformMapFields` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:22:1 | -12 | pub trait TransformMapFields { +22 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `finalize_with_default`, perhaps you need to implement it: diff --git a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr index c3708b57..dd77393a 100644 --- a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_compare_result.stderr @@ -32,12 +32,9 @@ error[E0277]: `__PartialShape` doesn't implement `Debug` | help: the trait `Debug` is conditionally implemented for `Result` --> $RUST/core/src/result.rs + ::: $RUST/core/src/result.rs | - | #[derive(Copy, Debug, Hash)] - | ^^^^^ -... - | pub enum Result { - | - unsatisfied requirement introduced here: `__PartialShape: Debug` + = note: unsatisfied requirement introduced here: `__PartialShape: Debug` help: consider annotating `__PartialShape` with `#[derive(Debug)]` | 15 + #[derive(Debug)] @@ -55,12 +52,9 @@ error[E0277]: `__PartialShape` doesn't implement `Debug` | help: the trait `Debug` is conditionally implemented for `Result` --> $RUST/core/src/result.rs + ::: $RUST/core/src/result.rs | - | #[derive(Copy, Debug, Hash)] - | ^^^^^ -... - | pub enum Result { - | - unsatisfied requirement introduced here: `__PartialShape: Debug` + = note: unsatisfied requirement introduced here: `__PartialShape: Debug` help: consider annotating `__PartialShape` with `#[derive(Debug)]` | 15 + #[derive(Debug)] diff --git a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr index 5088a776..99c6a36c 100644 --- a/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr +++ b/example-code/tests/compile_fail/reference/traits/extract_field_common_mistakes_extract_twice.stderr @@ -9,7 +9,7 @@ error[E0308]: mismatched types = note: expected struct `PhantomData>>>>>>>>>>` found struct `PhantomData>>>>>>>` note: method defined here - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:35:8 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:65:8 | -35 | fn extract_field(self, _tag: PhantomData) -> Result; +65 | fn extract_field(self, _tag: PhantomData) -> Result; | ^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr index 5a8be9b1..0ebdf69a 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_common_mistakes_finalize_early.stderr @@ -8,9 +8,9 @@ error[E0599]: no method named `finalize_extract` found for enum `__PartialShape< | ^^^^^^^^^^^^^^^^ method not found in `__PartialShape` | note: the method `finalize_extract` exists on the type `::Map` - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:39:5 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:75:5 | -39 | fn finalize_extract(self) -> T; +75 | fn finalize_extract(self) -> T; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `finalize_extract`, perhaps you need to implement it: diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr index f104500e..d6d6df8c 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.stderr @@ -1,22 +1,22 @@ error[E0599]: no method named `finalize_extract_result` found for enum `Result` in the current scope - --> tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.rs:25:10 - | -22 | let _circle = shape - | ___________________- -23 | | .to_extractor() -24 | | .extract_field(PhantomData::) -25 | | .finalize_extract_result(); - | | -^^^^^^^^^^^^^^^^^^^^^^^ method not found in `Result>` - | |_________| - | - | - ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:57:8 - | -57 | fn finalize_extract_result(self) -> Self::Output; - | ----------------------- the method is available for `Result>` here - | - = help: items from traits can only be used if the trait is in scope + --> tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_missing_import.rs:25:10 + | + 22 | let _circle = shape + | ___________________- + 23 | | .to_extractor() + 24 | | .extract_field(PhantomData::) + 25 | | .finalize_extract_result(); + | | -^^^^^^^^^^^^^^^^^^^^^^^ method not found in `Result>` + | |_________| + | + | + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:101:8 + | +101 | fn finalize_extract_result(self) -> Self::Output; + | ----------------------- the method is available for `Result>` here + | + = help: items from traits can only be used if the trait is in scope help: trait `FinalizeExtractResult` which provides `finalize_extract_result` is implemented but not in scope; perhaps you want to import it - | - 1 + use cgp::cgp_core::cgp_field::traits::FinalizeExtractResult; - | + | + 1 + use cgp::cgp_core::cgp_field::traits::FinalizeExtractResult; + | diff --git a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr index 70a01fa8..fea2a0dd 100644 --- a/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr +++ b/example-code/tests/compile_fail/reference/traits/finalize_extract_result_common_mistakes_one_step_early.stderr @@ -13,16 +13,11 @@ error[E0599]: the method `finalize_extract_result` exists for enum `Result { - | --------------------- doesn't satisfy `_: FinalizeExtractResult` - | = note: the following trait bounds were not satisfied: `__PartialShape: FinalizeExtract` which is required by `Result>: FinalizeExtractResult` note: the trait `FinalizeExtract` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:38:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/extract_field.rs:73:1 | -38 | pub trait FinalizeExtract { +73 | pub trait FinalizeExtract { | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr index 47762a21..8f069723 100644 --- a/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr +++ b/example-code/tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.stderr @@ -1,16 +1,16 @@ error[E0576]: cannot find associated type `Output` in trait `MapFields` - --> tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.rs:5:64 - | -5 | pub type Mapped = >::Output; - | ^^^^^^ not found in `MapFields` - | - ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/map_fields.rs:5:5 - | -5 | type Mapped; - | ----------- associated type `Mapped` defined here - | + --> tests/compile_fail/reference/traits/map_fields_common_mistakes_output_not_mapped.rs:5:64 + | + 5 | pub type Mapped = >::Output; + | ^^^^^^ not found in `MapFields` + | + ::: /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/map_fields.rs:10:5 + | +10 | type Mapped; + | ----------- associated type `Mapped` defined here + | help: maybe you meant this associated type - | -5 - pub type Mapped = >::Output; -5 + pub type Mapped = >::Mapped; - | + | + 5 - pub type Mapped = >::Output; + 5 + pub type Mapped = >::Mapped; + | diff --git a/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr index c9b380c9..0d04448e 100644 --- a/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr +++ b/example-code/tests/compile_fail/reference/traits/static_string_common_mistakes_bare_chars.stderr @@ -6,13 +6,13 @@ error[E0277]: the trait bound `cgp::prelude::Chars<'a', cgp::prelude::Nil>: Stat | = help: the trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` is not implemented for `cgp::prelude::Chars<'a', cgp::prelude::Nil>` help: the following other types implement trait `cgp::cgp_core::cgp_field::traits::static_string::StaticBytes` - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/static_string.rs:29:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/static_string.rs:34:1 | -29 | / impl StaticBytes for Symbol -30 | | where -31 | | Chars: MaybeChars, +34 | / impl StaticBytes for Symbol +35 | | where +36 | | Chars: MaybeChars, | |______________________^ `Symbol` ... -36 | impl StaticBytes for Nil { +41 | impl StaticBytes for Nil { | ^^^^^^^^^^^^^^^^^^^^^^^^ `cgp::prelude::Nil` = note: required for `cgp::prelude::Chars<'a', cgp::prelude::Nil>` to implement `StaticString` diff --git a/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr index 5131720d..50b3ab3c 100644 --- a/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr +++ b/example-code/tests/compile_fail/reference/traits/to_optional_common_mistakes_already_optional.stderr @@ -15,9 +15,9 @@ error[E0599]: the method `to_optional` exists for struct `__PartialContext: TransformMapFields` which is required by `&mut __PartialContext: cgp::cgp_extra::cgp_field_extra::impls::ToOptional` note: the trait `TransformMapFields` must be implemented - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:12:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/transform_map.rs:22:1 | -12 | pub trait TransformMapFields { +22 | pub trait TransformMapFields { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `to_optional`, perhaps you need to implement it: diff --git a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr index 0ac41c86..2f946200 100644 --- a/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr +++ b/example-code/tests/compile_fail/reference/traits/update_field_common_mistakes_marker_not_inferred.stderr @@ -9,12 +9,12 @@ error[E0284]: type annotations needed for `((), __PartialPerson<_, IsNothing>)` = note: cannot satisfy `<_ as MapType>::Map == String` = note: the type must also implement `MapType` note: required by a bound in `update_field` - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/update_field.rs:5:31 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/traits/update_field.rs:9:31 | - 5 | pub trait UpdateField { + 9 | pub trait UpdateField { | ^^^^^^^ required by this bound in `UpdateField::update_field` ... -12 | fn update_field( +20 | fn update_field( | ------------ required by a bound in this associated function help: consider giving this pattern a type, where the type for type parameter `M` is specified | diff --git a/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr index 4172b598..8346d11f 100644 --- a/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr +++ b/example-code/tests/compile_fail/reference/types/life_definition_not_send.stderr @@ -7,13 +7,10 @@ error[E0277]: `*mut &'static ()` cannot be sent between threads safely = help: within `cgp::prelude::Life<'static>`, the trait `Send` is not implemented for `*mut &'static ()` note: required because it appears within the type `PhantomData<*mut &'static ()>` --> $RUST/core/src/marker.rs - | - | pub struct PhantomData; - | ^^^^^^^^^^^ note: required because it appears within the type `cgp::prelude::Life<'static>` - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/life.rs:3:12 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/life.rs:7:12 | - 3 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); + 7 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); | ^^^^ note: required by a bound in `require_send` --> tests/compile_fail/reference/types/life_definition_not_send.rs:19:20 @@ -30,19 +27,13 @@ error[E0277]: `*mut &'static ()` cannot be sent between threads safely = help: within `GetName<'static>`, the trait `Send` is not implemented for `*mut &'static ()` note: required because it appears within the type `PhantomData<*mut &'static ()>` --> $RUST/core/src/marker.rs - | - | pub struct PhantomData; - | ^^^^^^^^^^^ note: required because it appears within the type `cgp::prelude::Life<'static>` - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/life.rs:3:12 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/life.rs:7:12 | - 3 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); + 7 | pub struct Life<'a>(pub PhantomData<*mut &'a ()>); | ^^^^ note: required because it appears within the type `PhantomData>` --> $RUST/core/src/marker.rs - | - | pub struct PhantomData; - | ^^^^^^^^^^^ note: required because it appears within the type `GetName<'static>` --> tests/compile_fail/reference/types/life_definition_not_send.rs:12:16 | diff --git a/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr index a989295d..8a15c652 100644 --- a/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr +++ b/example-code/tests/compile_fail/reference/types/void_common_mistakes_match_behind_a_reference.stderr @@ -5,12 +5,12 @@ error[E0004]: non-exhaustive patterns: `&cgp::prelude::Either::Right(cgp::prelud | ^^^^^ pattern `&cgp::prelude::Either::Right(cgp::prelude::Either::Right(_))` not covered | note: `cgp::prelude::Either>` defined here - --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/sum.rs:27:1 + --> /home/soares/development/context-generic/cgp/crates/core/cgp-field/src/types/sum.rs:6:1 | -27 | pub enum Either { + 6 | pub enum Either { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -28 | Left(Head), -29 | Right(Tail), +... +10 | Right(Tail), | ----- | | | not covered From f5a6bf8c25aa66380d641a53e0c1fb642849654d Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 12:31:35 +0100 Subject: [PATCH 217/516] Correct the `alloc` requirement for the error providers Both reference pages said the `alloc` feature is on by default. After the `no_std` change, `cgp` defaults to no features, so a reader copying the snippet with default features could not import either provider. The pages now say the feature is off by default and name how to enable it, which the `example-code` crate already does. --- docs/reference/providers/error/debug_error.md | 7 ++++--- docs/reference/providers/error/display_error.md | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index 27c1db24..cdcd3894 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -28,9 +28,10 @@ provider, often [`RaiseFrom`](raise_from.md), for that key. ## Usage Import the provider from `cgp::extra::error` and the wiring keys from `cgp::core::error`; none of them -is in the prelude. `DebugError` lives behind the crate's `alloc` feature, which is on by default, -because it allocates a `String`. It takes no type parameter and is wired to `ErrorRaiserComponent`, -`ErrorWrapperComponent`, or both, usually per source type with the `open` statement: +is in the prelude. `DebugError` allocates a `String`, so it lives behind an `alloc` feature that is +off by default: enable `features = ["alloc"]` on the `cgp` dependency. It takes no type parameter +and is wired to `ErrorRaiserComponent`, `ErrorWrapperComponent`, or both, usually per source type +with the `open` statement: ```rust use core::num::ParseIntError; diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md index e0c5951c..53a9d231 100644 --- a/docs/reference/providers/error/display_error.md +++ b/docs/reference/providers/error/display_error.md @@ -27,9 +27,10 @@ message rather than its debug representation. ## Usage Import the provider from `cgp::extra::error` and the wiring keys from `cgp::core::error`; none of them -is in the prelude. `DisplayError` lives behind the crate's `alloc` feature, which is on by default, -because it allocates a `String`. It takes no type parameter and is wired to `ErrorRaiserComponent`, -`ErrorWrapperComponent`, or both, usually per source type with the `open` statement: +is in the prelude. `DisplayError` allocates a `String`, so it lives behind an `alloc` feature that is +off by default: enable `features = ["alloc"]` on the `cgp` dependency. It takes no type parameter +and is wired to `ErrorRaiserComponent`, `ErrorWrapperComponent`, or both, usually per source type +with the `open` statement: ```rust use core::num::ParseIntError; From f3727ed4eb63be5fbe3755da3cff083d026d9a8c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 12:42:50 +0100 Subject: [PATCH 218/516] Add the test deployment badge --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4c20b1c2..55022da4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ [![Deploy to GitHub Pages](https://github.com/contextgeneric/contextgeneric.dev/actions/workflows/deploy.yaml/badge.svg)](https://github.com/contextgeneric/contextgeneric.dev/actions/workflows/deploy.yaml) +[![Test deployment](https://github.com/contextgeneric/contextgeneric.dev/actions/workflows/test-deploy.yaml/badge.svg)](https://github.com/contextgeneric/contextgeneric.dev/actions/workflows/test-deploy.yaml) ![License: Apache-2.0 for code](https://img.shields.io/badge/license-Apache_2.0-blue.svg) ![Content: CC BY-SA 4.0](https://img.shields.io/badge/content-CC_BY--SA_4.0-lightgrey.svg) ![Node 20+](https://img.shields.io/badge/node-20+-green.svg) From 18b3deea21a54ec06e4968e8606ec661bdd265f8 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 13:35:10 +0100 Subject: [PATCH 219/516] Raise the website's minimum Node version to 24 Node 20 reached end of life in April 2026, while `.nvmrc` and CI already run 24.22.2, so the README badge, the stated minimum, and `engines` now say 24. Co-Authored-By: deepseek-v4.1-flash-1017 --- README.md | 4 ++-- package-lock.json | 2 +- package.json | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 55022da4..4eaed607 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Test deployment](https://github.com/contextgeneric/contextgeneric.dev/actions/workflows/test-deploy.yaml/badge.svg)](https://github.com/contextgeneric/contextgeneric.dev/actions/workflows/test-deploy.yaml) ![License: Apache-2.0 for code](https://img.shields.io/badge/license-Apache_2.0-blue.svg) ![Content: CC BY-SA 4.0](https://img.shields.io/badge/content-CC_BY--SA_4.0-lightgrey.svg) -![Node 20+](https://img.shields.io/badge/node-20+-green.svg) +![Node 24+](https://img.shields.io/badge/node-24+-green.svg) # The CGP website: contextgeneric.dev @@ -21,7 +21,7 @@ npm ci ``` The repository carries `package-lock.json`, and CI installs with `npm ci`, so use `npm` rather than -another package manager. Node 20 or newer is required. CI runs the version `.nvmrc` pins, and +another package manager. Node 24 or newer is required. CI runs the version `.nvmrc` pins, and `nvm use` selects the same one locally. ## Local development diff --git a/package-lock.json b/package-lock.json index d89b2c65..f6f598cf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,7 +24,7 @@ "typescript": "~5.6.2" }, "engines": { - "node": ">=20.0" + "node": ">=24.0" } }, "node_modules/@algolia/abtesting": { diff --git a/package.json b/package.json index 899a508c..9157e5d3 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,6 @@ ] }, "engines": { - "node": ">=20.0" + "node": ">=24.0" } } From e00aacf01a37705975116bc18718f20a7314667c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 15:17:17 +0100 Subject: [PATCH 220/516] Require the snippet tests and the naming rule for every page A change to a page's code now runs the example-code tests, and each page names Context-Generic Programming and relates a short form of the tag line to its content, following the knowledge base's naming rule. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 67fb9f45..9e66c3c3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,11 +54,17 @@ block to match. These are the actionable rules here: stale parts first. - Put a page's code in the website repository's `example-code/` crate, except a Projects page, whose code is checked against the project's repository. +- Run the `example-code` tests after changing a page's code, as + [example-code/README.md](example-code/README.md) describes. - Use the knowledge base's `releases/` directory to date an unfamiliar construct. ## Public prose - Read the communication strategy before outlining or drafting a page. +- Name Context-Generic Programming in each page's prose and relate a short form of the tag line to its + content, following the knowledge base's + [naming rule](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/communication-strategy/identity.md#the-name-and-the-tag-line-on-every-page); + the skill pages and the published blog posts are exempt. - Never publish an invented benchmark, adoption figure, or quotation. - Never disparage another crate, language, or community; say where a simpler tool is the better choice. - Concede the learning curve, the verbose diagnostics, and the young ecosystem where a reader looks for From fc38528b0c1312bdcee1cb4c78fc3b326f185c02 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 16:20:28 +0100 Subject: [PATCH 221/516] Remove the Introduction's status section The project's maturity belongs to the front page's cost section, which the front-page rebuild writes, so the Introduction keeps its definition and its routing. Co-Authored-By: Claude Opus 5.5 --- docs/index.md | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/docs/index.md b/docs/index.md index 1ed6fd59..1533a571 100644 --- a/docs/index.md +++ b/docs/index.md @@ -25,24 +25,6 @@ implementations or want to reuse an implementation across contexts. The [Overview](/docs/overview) covers those features, along with abstract types, extensible data, and composable handlers. -## Current Status - -CGP is in active development, with a young ecosystem and limited community support. Learning its -patterns takes time, and compiler errors can be difficult to interpret. If you adopt it for a -mission-critical project, expect to investigate problems yourself when the available documentation -and support do not cover your case. - -[cargo-cgp](/docs/cargo-cgp) helps diagnose wiring errors by naming their root cause and showing the -dependency chain. The tool is an early release: `cargo cgp check` leads with the root cause for the classes it recognizes, -and the tool does not yet reshape every class. CGP also publishes an -[agent skill](/docs/ai/skills) to help coding assistants read, write, and debug CGP code. You still -need to review the code an assistant produces. - -Start with a small part of your project whose implementation choices already vary. For a trait -with one implementation, a plain trait may be enough. CGP particularly welcomes -[early adopters and contributors](/docs/contribute) who want to experiment and help improve the -library, tools, and documentation. - ## Getting Started Start with the [Hello World tutorial](/docs/tutorials/hello) for a short working example. Continue From 0eac544fde039513765c20be016e6bd20a080351 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 16:48:29 +0100 Subject: [PATCH 222/516] Enforce valid heading anchors in website builds --- AGENTS.md | 3 ++- docusaurus.config.ts | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 9e66c3c3..891e5abc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,7 +84,8 @@ block to match. These are the actionable rules here: - Install with `npm ci`, and run `npm start` for the dev server and `npm run build` for the static output, or the `node_modules` binaries of the same names. - Check the build's exit status rather than its output. -- Keep `onBrokenLinks` set to `throw`; fix every reference when a page moves. +- Keep `onBrokenLinks` and `onBrokenAnchors` set to `throw`; fix every reference when a page or heading + moves. - Take a page's position from `sidebar_position` and its directory's `_category_.json`. - Update the announcement bar in `docusaurus.config.ts` by hand with every release announcement. - Keep the site stock: do not add plugins, and do not add React beyond the landing page. diff --git a/docusaurus.config.ts b/docusaurus.config.ts index 6b2e1afb..27b3c7e1 100644 --- a/docusaurus.config.ts +++ b/docusaurus.config.ts @@ -26,6 +26,7 @@ const config: Config = { projectName: 'contextgeneric.dev', // Usually your repo name. onBrokenLinks: 'throw', + onBrokenAnchors: 'throw', // Parse `.md` as CommonMark and `.mdx` as MDX, rather than treating every file // as MDX. The skill pages under `docs/ai/skills/` are symlinks into the From 4203e347ef2258e4c3c6d2e149b3a296de681751 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 16:53:06 +0100 Subject: [PATCH 223/516] Update the published CGP skill snapshot --- cgp-skills | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cgp-skills b/cgp-skills index 40ee1f62..034893d7 160000 --- a/cgp-skills +++ b/cgp-skills @@ -1 +1 @@ -Subproject commit 40ee1f622a2396dff8c3d24717c48a1a52ac1f9f +Subproject commit 034893d706b3d8777a6dbebd77b8386a69e4a80b From 69297c974e9a2368f118b899fb5011552e3ec880 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 17:00:39 +0100 Subject: [PATCH 224/516] Add complete programs for serialization diagnostic captures --- example-code/README.md | 11 ++++++++ .../cgp_serde/missing_iterator_reference.rs | 21 +++++++++++++++ .../cgp_serde/missing_json_error_wiring.rs | 19 +++++++++++++ .../cgp_serde/missing_payload_bytes.rs | 27 +++++++++++++++++++ 4 files changed, 78 insertions(+) create mode 100644 example-code/diagnostics/cgp_serde/missing_iterator_reference.rs create mode 100644 example-code/diagnostics/cgp_serde/missing_json_error_wiring.rs create mode 100644 example-code/diagnostics/cgp_serde/missing_payload_bytes.rs diff --git a/example-code/README.md b/example-code/README.md index 56262369..841e4cc2 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -109,6 +109,17 @@ manifest depends on `cgp` by path. The crate's own files and the standard librar writes the new path in. A snapshot also quotes rustc's own wording, so [`rust-toolchain.toml`](rust-toolchain.toml) pins the compiler and a bump re-blesses the suite. +## Diagnostic capture programs + +`diagnostics/cgp_serde/` holds complete programs for the cgp-serde debugging guide's missing +`Vec` entry, missing iterator-reference entry, and absent JSON error wiring. Each program is +intended to fail. The diagnostic capture harness compiles each file as a library with the sibling +`cgp` and `cgp-serde` checkouts, using cargo-cgp's pinned nightly and local driver. + +These files are separate from the integration-test suite because they need the project's own +dependencies. `cargo test` and CI do not compile them; fresh diagnostic captures check their +failures. The remaining Projects examples are checked in their project checkouts. + ## Generated code Two of these pages show what a macro *generates*, in simplified form. A hand-rolled rendering of such diff --git a/example-code/diagnostics/cgp_serde/missing_iterator_reference.rs b/example-code/diagnostics/cgp_serde/missing_iterator_reference.rs new file mode 100644 index 00000000..35722bbe --- /dev/null +++ b/example-code/diagnostics/cgp_serde/missing_iterator_reference.rs @@ -0,0 +1,21 @@ +// From docs/projects/cgp-serde/guides/debugging-wiring.md: an iterator yields references. +// Shows: checking Vec names the missing &u64 serialization entry. +use cgp::prelude::*; +use cgp_serde::components::ValueSerializerComponent; +use cgp_serde::providers::{SerializeIterator, UseSerde}; + +pub struct Ctx; + +delegate_components! { + Ctx { + open ValueSerializerComponent; + @ValueSerializerComponent.u64: UseSerde, + @ValueSerializerComponent.Vec: SerializeIterator, + } +} + +check_components! { + Ctx { + ValueSerializerComponent: Vec, + } +} diff --git a/example-code/diagnostics/cgp_serde/missing_json_error_wiring.rs b/example-code/diagnostics/cgp_serde/missing_json_error_wiring.rs new file mode 100644 index 00000000..05c65b49 --- /dev/null +++ b/example-code/diagnostics/cgp_serde/missing_json_error_wiring.rs @@ -0,0 +1,19 @@ +// From docs/projects/cgp-serde/guides/debugging-wiring.md: JSON error wiring is absent. +// Shows: the failed call reports the error components it requires. +use cgp::prelude::*; +use cgp_serde::components::ValueDeserializerComponent; +use cgp_serde::providers::UseSerde; +use cgp_serde_json::impls::CanDeserializeJsonString; + +pub struct Ctx; + +delegate_components! { + Ctx { + open ValueDeserializerComponent; + @ValueDeserializerComponent.u64: UseSerde, + } +} + +fn main() { + let _r: Result = Ctx.deserialize_json_string("1"); +} diff --git a/example-code/diagnostics/cgp_serde/missing_payload_bytes.rs b/example-code/diagnostics/cgp_serde/missing_payload_bytes.rs new file mode 100644 index 00000000..6c234c04 --- /dev/null +++ b/example-code/diagnostics/cgp_serde/missing_payload_bytes.rs @@ -0,0 +1,27 @@ +// From docs/projects/cgp-serde/guides/debugging-wiring.md: a nested type has no entry. +// Shows: checking Payload names the missing Vec serialization entry. +use cgp::prelude::*; +use cgp_serde::components::ValueSerializerComponent; +use cgp_serde::providers::{SerializeRecordFields, UseSerde}; + +#[derive(CgpData)] +pub struct Payload { + pub quantity: u64, + pub data: Vec, +} + +pub struct App; + +delegate_components! { + App { + open ValueSerializerComponent; + @ValueSerializerComponent.u64: UseSerde, + @ValueSerializerComponent.Payload: SerializeRecordFields, + } +} + +check_components! { + App { + ValueSerializerComponent: [u64, Payload], + } +} From 002d8f12976be558b79a203828e87a0432cc2394 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 17:26:36 +0100 Subject: [PATCH 225/516] Cover parser errors and merged diagnostic captures --- example-code/README.md | 20 ++++--- .../cgp_serde/unparsed_array_key.rs | 14 +++++ .../reference/shared_missing_name.rs | 60 +++++++++++++++++++ 3 files changed, 87 insertions(+), 7 deletions(-) create mode 100644 example-code/diagnostics/cgp_serde/unparsed_array_key.rs create mode 100644 example-code/diagnostics/reference/shared_missing_name.rs diff --git a/example-code/README.md b/example-code/README.md index 841e4cc2..35612922 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -112,13 +112,19 @@ writes the new path in. A snapshot also quotes rustc's own wording, so ## Diagnostic capture programs `diagnostics/cgp_serde/` holds complete programs for the cgp-serde debugging guide's missing -`Vec` entry, missing iterator-reference entry, and absent JSON error wiring. Each program is -intended to fail. The diagnostic capture harness compiles each file as a library with the sibling -`cgp` and `cgp-serde` checkouts, using cargo-cgp's pinned nightly and local driver. - -These files are separate from the integration-test suite because they need the project's own -dependencies. `cargo test` and CI do not compile them; fresh diagnostic captures check their -failures. The remaining Projects examples are checked in their project checkouts. +`Vec` entry, missing iterator-reference entry, absent JSON error wiring, and fixed-size array +key rejected by the macro parser. Each program is intended to fail. The diagnostic capture harness +compiles each file as a library with the sibling `cgp` and `cgp-serde` checkouts, using cargo-cgp's +pinned nightly and local driver. + +`diagnostics/reference/shared_missing_name.rs` reproduces the compile-errors page's merged +diagnostic: three checked components need the same absent field. The capture must show all three +check entries and both secondary labels, so a single call failure cannot substitute for it. + +These programs are checked by the diagnostic capture harness. The cgp-serde cases need the project's +own dependencies, and the reference case checks cargo-cgp's diagnostic merging. `cargo test` and CI +do not compile these files; fresh diagnostic captures check their failures. The remaining Projects +examples are checked in their project checkouts. ## Generated code diff --git a/example-code/diagnostics/cgp_serde/unparsed_array_key.rs b/example-code/diagnostics/cgp_serde/unparsed_array_key.rs new file mode 100644 index 00000000..6bfcd91c --- /dev/null +++ b/example-code/diagnostics/cgp_serde/unparsed_array_key.rs @@ -0,0 +1,14 @@ +// From docs/projects/cgp-serde/guides/debugging-wiring.md: a key does not parse. +// Shows: the macro rejects a fixed-size array written as a list of keys. +use cgp::prelude::*; +use cgp_serde::components::ValueDeserializerComponent; +use cgp_serde::providers::UseSerde; + +pub struct App; + +delegate_components! { + App { + open ValueDeserializerComponent; + @ValueDeserializerComponent.[u8; 32]: UseSerde, + } +} diff --git a/example-code/diagnostics/reference/shared_missing_name.rs b/example-code/diagnostics/reference/shared_missing_name.rs new file mode 100644 index 00000000..4f277155 --- /dev/null +++ b/example-code/diagnostics/reference/shared_missing_name.rs @@ -0,0 +1,60 @@ +// From docs/reference/errors.md: when one mistake prints many errors. +// Shows: three checked components coalesce onto the same missing name field. +use cgp::prelude::*; + +#[cgp_component(FooProvider)] +pub trait CanUseFoo { + fn foo(&self); +} + +#[cgp_component(BarProvider)] +pub trait CanUseBar { + fn bar(&self); +} + +#[cgp_component(BazProvider)] +pub trait CanUseBaz { + fn baz(&self); +} + +pub struct ReadName; + +#[cgp_impl(ReadName)] +impl FooProvider { + fn foo(&self, #[implicit] name: &str) { + let _ = name; + } +} + +#[cgp_impl(ReadName)] +impl BarProvider { + fn bar(&self, #[implicit] name: &str) { + let _ = name; + } +} + +#[cgp_impl(ReadName)] +impl BazProvider { + fn baz(&self, #[implicit] name: &str) { + let _ = name; + } +} + +#[derive(HasField)] +pub struct App { + pub age: u8, +} + +delegate_components! { + App { + [FooProviderComponent, BarProviderComponent, BazProviderComponent]: ReadName, + } +} + +check_components! { + App { + BazProviderComponent, + BarProviderComponent, + FooProviderComponent, + } +} From d9d6092689a7e3df71722893db9d1970047a3791 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 17:54:03 +0100 Subject: [PATCH 226/516] Rewrite stale history wording in reference and tutorial The legacy dispatch, provider-diagnostic, and namespace-routing pages state current behavior instead of comparing it with an earlier release, and the tutorial introduces #[cgp_fn] without attaching it to v0.7.0. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/attributes/derive_delegate.md | 2 +- docs/reference/macros/cgp_namespace.md | 2 +- docs/reference/macros/cgp_provider.md | 2 +- docs/tutorials/area-calculation/context-generic-functions.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 8c8822f3..6c694b5d 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -14,7 +14,7 @@ Generate the `UseDelegate` dispatcher impl for a component. Superseded by the `o ### Legacy: read, don't write `#[derive_delegate]` and the [`UseDelegate`](../providers/use_delegate.md) provider it generates are the -older way to choose an implementation per type. A component no longer needs this attribute to be +older way to choose an implementation per type. A component does not need this attribute to be dispatched on a type parameter: the `open` statement of [`delegate_components!`](../macros/delegate_components.md) does the same job through machinery every component already has, without a separate table or a wrapper. diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 04e2c641..6193ddd6 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -402,7 +402,7 @@ namespace first and join it by its name. The inheritance header and a `for` loop a path. **`open` does not combine with a prefixed component in a joined namespace.** Once a component's lookups are -routed under a prefix, `open`, which roots the route at the bare component name, no longer reaches those +routed under a prefix, `open`, which roots the route at the bare component name, does not reach those entries. Write the per-value entries with the full prefixed path instead. **A cyclic parent chain fails at both definitions, and a self-inheriting namespace at the macro.** Two namespaces inheriting each diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 5cad05e5..b45b9420 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -368,7 +368,7 @@ Which macro you invoke decides whether the struct is declared, so use `#[cgp_new rewrite above finds the context by reading the inner bound's first argument. On a component with a lifetime, that argument is the lifetime, so the macro builds no counterpart and copies the bound as-is. The stack compiles and runs correctly, but it loses the propagation: a dependency unmet inside the -inner provider no longer surfaces at the outer one, and `#[check_providers(...)]` cannot say which +inner provider does not surface at the outer one, and `#[check_providers(...)]` cannot say which layer of such a stack is at fault. Components without lifetime parameters are unaffected. **The macro does not check the component argument against the trait.** Passing a component that does diff --git a/docs/tutorials/area-calculation/context-generic-functions.md b/docs/tutorials/area-calculation/context-generic-functions.md index f4be1c94..bbf0f6c5 100644 --- a/docs/tutorials/area-calculation/context-generic-functions.md +++ b/docs/tutorials/area-calculation/context-generic-functions.md @@ -10,7 +10,7 @@ By the end of this tutorial, we will have defined `rectangle_area`, `scaled_rect ## Introducing `#[cgp_fn]` and `#[implicit]` arguments -CGP v0.7.0 introduces a new `#[cgp_fn]` macro, which we can apply to plain Rust functions and turn them into *context-generic* methods that accept *implicit arguments*. With that, we can rewrite the example `rectangle_area` function as follows: +CGP provides a `#[cgp_fn]` macro, which we can apply to plain Rust functions and turn them into *context-generic* methods that accept *implicit arguments*. With that, we can rewrite the example `rectangle_area` function as follows: ```rust #[cgp_fn] From 7e4508ba30a35d4bc5e92d61ea5807e1a45276d5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:00:22 +0100 Subject: [PATCH 227/516] Add the three concept diagrams and revise two concept pages The coherence page gains a reader-facing title and description, and both it and the trait-split page name Context-Generic Programming in their openings. The diagrams show the wiring table, the trait split, and coherence scoped per provider, so the pages can reuse one drawing each. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/coherence.md | 19 +++++-- docs/concepts/consumer-and-provider-traits.md | 12 +++- static/img/coherence-scoped.svg | 55 +++++++++++++++++++ static/img/consumer-provider-split.svg | 49 +++++++++++++++++ static/img/wiring-table.svg | 42 ++++++++++++++ 5 files changed, 170 insertions(+), 7 deletions(-) create mode 100644 static/img/coherence-scoped.svg create mode 100644 static/img/consumer-provider-split.svg create mode 100644 static/img/wiring-table.svg diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 859e5f99..2a4af854 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -1,19 +1,21 @@ --- +title: 'Blanket implementations: why Rust rejects overlapping ones' sidebar_label: 'Bypassing coherence' sidebar_position: 1 +description: 'Why Rust rejects overlapping blanket implementations, and how CGP lets each context record one provider choice without repealing coherence.' --- # Bypassing coherence Rust's coherence rules keep trait lookup consistent across a program. For a given trait, its type arguments, and an implementing type, at most one implementation applies. Generic code can -therefore rely on trait bounds without asking callers to choose an implementation. The same -guarantee rules out overlapping implementations, even when each would be useful on its own. +therefore rely on trait bounds without asking callers to choose an implementation, but the same +guarantee rules out overlapping implementations even when each would be useful on its own. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations by +giving each implementation a separate provider type, and a context selects one through wiring. -CGP lets alternatives coexist by giving each implementation a separate provider type. A context -then selects its provider through wiring, and the generated code continues to obey Rust's -coherence rules. This page explains why that guarantee matters, how the provider split works -within it, and where ownership and wiring limit the available choices. +This page explains why that guarantee matters, how the provider split works within it, and where +ownership and wiring limit the available choices. ## The trait system is already a dependency-injection mechanism @@ -196,6 +198,11 @@ delegate_components! { String { EncoderComponent: EncodeAsText } } delegate_components! { Vec { EncoderComponent: EncodeAsHex } } ``` +Rust's rule still holds. What changes is where the choice is recorded: coherence is scoped to each +context's provider, so the two applications can encode the same `String` differently. + +![Diagram: Rust checks coherence once against each provider implementation, and CGP scopes the recorded choice to each context. The String value encodes as text in one application and as hexadecimal in another.](/img/coherence-scoped.svg) + With these entries, `value.encode()` uses `EncodeAsText` for a `String` and `EncodeAsHex` for a `Vec`. The string `"hi"` therefore encodes as `b"hi"`, while the byte vector `b"hi".to_vec()` encodes as `b"6869"`. Callers can use the `CanEncode` consumer trait and leave provider selection diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index d2ea985e..fe6aa50a 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -1,11 +1,13 @@ --- sidebar_label: 'Consumer and provider traits' sidebar_position: 2 +description: 'How CGP splits one trait into a consumer trait for callers and a provider trait for implementations, and how wiring connects a call to its provider.' --- # Consumer and provider traits -A CGP component connects callers to implementations through two related traits. Callers use the +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations: a +component connects callers to implementations through two related traits. Callers use the **consumer trait** to invoke methods on a context, the type receiving the call. Implementers use the **provider trait** to supply those methods through separate provider types. The context chooses a provider through wiring, so implementations can vary while callers keep the same interface. @@ -90,6 +92,10 @@ pub trait EmailSender { } ``` +The diagram shows the two roles and the provider structs that implement the second one. + +![Diagram: one trait splits into a consumer trait that callers use and a provider trait that implementations target. Two provider structs implement the provider trait, and the context's wiring selects one of them.](/img/consumer-provider-split.svg) + The implementations can now keep their original context bounds while using separate marker structs as `Self`. With the method bodies omitted, their declarations look like this: @@ -133,6 +139,10 @@ delegate_components! { App { EmailSenderComponent: SendViaSmtp } } delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } ``` +The table maps the same component key to a different provider for each context. + +![Diagram: the wiring table has three columns, context, component key, and provider. App maps EmailSenderComponent to SendViaSmtp, and TestApp maps it to RecordEmails. A call resolves through the table at compile time to a direct call on the selected provider.](/img/wiring-table.svg) + The key in both tables is `EmailSenderComponent`, a marker generated alongside the two traits. Those traits, the marker, and the forwarding implementations form the **component**. The entry for this key selects `SendViaSmtp` on `App` and `RecordEmails` on `TestApp`. diff --git a/static/img/coherence-scoped.svg b/static/img/coherence-scoped.svg new file mode 100644 index 00000000..19050735 --- /dev/null +++ b/static/img/coherence-scoped.svg @@ -0,0 +1,55 @@ + + Coherence scoped to each provider choice + Rust keeps one implementation of a trait for a type by rejecting overlapping impls. CGP keeps that rule but scopes the choice to the provider type: the String value is encoded as text in one context and as hexadecimal in another. + + + + + + + + + + Rust coherence + One implementation per trait and type, + checked for the whole program. + + + impl CanEncode for String + + + + E0119 + + A second overlapping blanket impl is + ambiguous at the call site, so Rust + rejects it. + The answer stays single-valued: + every lookup for String agrees. + + + + CGP: same rule, scoped per provider + Each provider type gets its own impl, so + each context records one choice. + + + String + + + + + + + + + context App + selects EncodeAsText + encode → b"hi" + + + context Firmware + selects EncodeAsHex + encode → b"6869" + + diff --git a/static/img/consumer-provider-split.svg b/static/img/consumer-provider-split.svg new file mode 100644 index 00000000..801aadd3 --- /dev/null +++ b/static/img/consumer-provider-split.svg @@ -0,0 +1,49 @@ + + One trait split into a consumer trait and a provider trait + A caller's trait such as CanSendEmail becomes a consumer trait that callers use and a provider trait parameterized by the context, which two provider structs implement. The context's wiring selects which provider answers the call. + + + + + + + + + one trait: CanSendEmail + + + + + + + + + consumer trait + what callers use + app.send_email(to, body) + + + + provider trait + what implementations target + EmailSender<Context> + + + SendViaSmtp + impl EmailSender + for SendViaSmtp + + + RecordEmails + impl EmailSender + for RecordEmails + + + + + + + the context's wiring + selects one provider + + diff --git a/static/img/wiring-table.svg b/static/img/wiring-table.svg new file mode 100644 index 00000000..a02589ae --- /dev/null +++ b/static/img/wiring-table.svg @@ -0,0 +1,42 @@ + + A wiring table selects a provider for each component + Two contexts, App and TestApp, map the same component key EmailSenderComponent to different provider types. A caller's method call resolves through the table at compile time to a direct call on the selected provider. + + + + + + + + the wiring table + + + context + component key + provider + + + App + EmailSenderComponent + SendViaSmtp + + + + TestApp + EmailSenderComponent + RecordEmails + + The same key, a different choice for each context. + + + resolved at + compile time + + + call site + app.send_email(to, body) + + direct call to + the selected provider + no runtime lookup + From 259b6cb61dfe13c279f69d9f128506674a5c2f45 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:00:48 +0100 Subject: [PATCH 228/516] Name the project and describe the impl-side dependencies page The page opens by naming Context-Generic Programming beside the requirement it explains and carries a written description for search results. Its claims and snippets still match example-code and the knowledge-base document. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/impl-side-dependencies.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index f48ade12..44af3831 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -1,15 +1,17 @@ --- sidebar_label: 'Impl-side dependencies' sidebar_position: 3 +description: 'How a provider keeps its trait, value, and type requirements out of the caller interface, and how CGP checks them when a context selects the provider.' --- # Impl-side dependencies -A trait exposes operations that callers can use, while an implementation may need additional -traits, values, or types to carry them out. A requirement kept on the implementation without -appearing in the trait's interface is an **impl-side dependency**. Callers can then depend on the -trait alone, and the compiler checks the implementation's requirements when resolving that trait -for a context. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations whose +own requirements stay with the implementation. A trait exposes operations that callers can use, +while an implementation may need additional traits, values, or types to carry them out. A +requirement kept on the implementation without appearing in the trait's interface is an +**impl-side dependency**. Callers can then depend on the trait alone, and the compiler checks the +implementation's requirements when resolving that trait for a context. This page develops that separation in ordinary Rust blanket implementations, then applies it to CGP providers. It covers dependencies on traits, field values, and context-selected types, From 4e8b4b391695e54baa9051a2dd0b7f9f5791241e Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:01:29 +0100 Subject: [PATCH 229/516] Correct the implicit argument conversion rules and name the project A &str implicit argument reads any field implementing AsRef through as_ref, not a String field through as_str. The page, its example comment, and the knowledge-base concept now state the current rule, and the page opens with Context-Generic Programming and a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/implicit-arguments.md | 21 +++++++++++-------- .../tests/concepts/implicit_arguments.rs | 2 +- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index 8e47c40c..cb6bacd2 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -1,14 +1,17 @@ --- sidebar_label: 'Implicit arguments' sidebar_position: 4 +description: 'How implicit arguments read context fields through function parameters, how the declared type controls borrowing and cloning, and when a getter trait is the better fit.' --- # Implicit arguments -Implicit arguments let a provider declare the context values it needs as function parameters. -CGP reads those values from the context, so callers pass only the method's explicit arguments. -This page explains the field access behind that shorthand, how argument types control borrowing -and cloning, and when a [getter trait](/docs/reference/glossary#getter-trait) is a better fit. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations whose +providers read context values as if they were parameters. Implicit arguments name the context value +a method needs, and CGP reads it from the context, so callers pass only the method's explicit +arguments. This page explains the field access behind that shorthand, how argument types control +borrowing and cloning, and when a [getter trait](/docs/reference/glossary#getter-trait) is a better +fit. ## Reading a field explicitly @@ -53,7 +56,7 @@ impl Greeter { `#[implicit]` removes `name` from the method's public signature and generates the field bound and read. The body receives a local `name`, while a caller still writes `app.greet()`. Here, `&str` -borrows the contents of a `String` field. +borrows the contents of any field that implements `AsRef`, such as a `String` field. Implicit arguments are the usual choice for reading fields from a provider's own context. They keep each value's name and type beside the method that uses it, while the macro supplies the @@ -90,7 +93,7 @@ pub fn describe( &self, // Cloned from the context's String field. #[implicit] name: String, - // Borrows the contents of the context's String field. + // Borrows any field implementing `AsRef`, such as a String field. #[implicit] title: &str, // Borrows the Vec field directly. #[implicit] tags: &Vec, @@ -100,9 +103,9 @@ pub fn describe( ``` An owned argument calls `.clone()` on the field, leaving the stored value in the context. A `&str` -argument reads a `String` field with `.as_str()`, and `&Vec` borrows the vector directly. -Prefer a borrow when the body only needs to read the value, especially when cloning would allocate -or copy substantial data. +argument reads any field implementing `AsRef` with `.as_ref()`, and `&Vec` borrows the +vector directly. Prefer a borrow when the body only needs to read the value, especially when cloning +would allocate or copy substantial data. The macro supports specific access forms rather than arbitrary conversions between types. The [`#[implicit]` reference](/docs/reference/attributes/implicit) covers options, slices, mutable diff --git a/example-code/tests/concepts/implicit_arguments.rs b/example-code/tests/concepts/implicit_arguments.rs index 81198722..d66cb91c 100644 --- a/example-code/tests/concepts/implicit_arguments.rs +++ b/example-code/tests/concepts/implicit_arguments.rs @@ -111,7 +111,7 @@ pub mod the_declared_type_decides_the_read { &self, // Owned: read by reference and cloned, so the context keeps its field. #[implicit] name: String, - // `&str`: backed by a `String` field, borrowed rather than cloned. + // `&str`: any field implementing `AsRef`, borrowed rather than cloned. #[implicit] title: &str, // Any other borrow: taken as it stands. #[implicit] tags: &Vec, From defff7350cad708de2db69f251dfec2234298591 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:02:23 +0100 Subject: [PATCH 230/516] Name the project and describe the abstract types page The page opens with Context-Generic Programming beside the shared-type idea and carries a written description. Its claims and snippets still match the knowledge-base document and example-code. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/abstract-types.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index df2f55d3..c106e724 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -1,14 +1,16 @@ --- sidebar_label: 'Abstract types' sidebar_position: 5 +description: 'How a context chooses an associated type through wiring, so providers share one scalar, error type, or runtime without adding a parameter at every call.' --- # Abstract types -An **abstract type** gives providers a shared name for a type their context chooses. For example, -providers can return the same error type without deciding whether it is a string or a domain enum, -or carry out calculations using the scalar type their application selects. Rust's associated types -express that relationship, and CGP lets each context make the choice through wiring. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, and +an **abstract type** lets the same wiring choose the types those implementations share. Providers +can return the same error type without deciding whether it is a string or a domain enum, or carry +out calculations using the scalar type their application selects. Rust's associated types express +that relationship, and CGP lets each context make the choice through wiring. ## Rust already has this From 267395c322dd885e68f96f56873270d6ab932ccd Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:02:39 +0100 Subject: [PATCH 231/516] Name the project and describe the wiring check page The page opens with Context-Generic Programming beside the check-trait idea and carries a written description for search results. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/check-traits.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index 3bbd8643..93efbec6 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -1,14 +1,17 @@ --- sidebar_label: 'Checking your wiring' sidebar_position: 6 +description: 'How check traits and check_components! verify a context wiring beside the table, what the raw and rewritten diagnostics show, and what a check does not prove.' --- # Checking your wiring -Check traits let you verify a context's wiring at a location you choose. Wiring itself records -provider choices without immediately checking whether the context meets their requirements, so a -missing dependency can remain unnoticed until a later method call. An explicit check brings that -failure back beside the wiring, where the context and its selected providers are easier to inspect. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, and +a **check trait** verifies that a context can use the providers its wiring selects. Wiring itself +records provider choices without immediately checking whether the context meets their requirements, +so a missing dependency can remain unnoticed until a later method call. An explicit check brings +that failure back beside the wiring, where the context and its selected providers are easier to +inspect. ## A context can be wrong and still compile From 2ada854b0c21e0c9eecf22c381a6288256121412 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:02:49 +0100 Subject: [PATCH 232/516] Name the project and describe the higher-order providers page The page opens with Context-Generic Programming beside the composition idea and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/higher-order-providers.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index e0b771ea..43edb4ac 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -1,14 +1,16 @@ --- sidebar_label: 'Higher-order providers' sidebar_position: 7 +description: 'How a provider takes another provider as a parameter, so a wrapper such as scaling reuses one body with different inner calculations.' --- # Higher-order providers -A **higher-order provider** takes another provider as a type parameter and uses it to perform part -of its work. This separates a reusable transformation, such as scaling a result, from the inner -implementation that produces the result. Wiring can then combine the same wrapper with different -inner providers, while both operate on the same context. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations that +compose. A **higher-order provider** takes another provider as a type parameter and uses it to +perform part of its work. This separates a reusable transformation, such as scaling a result, from +the inner implementation that produces the result. Wiring can then combine the same wrapper with +different inner providers, while both operate on the same context. ## Choosing is not the only thing you can do with a provider From 8ea9a3cdd2bd046978dabd4cf42ccc0d035f8d16 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:02:56 +0100 Subject: [PATCH 233/516] Name the project and describe the aggregate providers page The page opens with Context-Generic Programming beside the bundling idea and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/aggregate-providers.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index 0b94e366..19e25241 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -1,14 +1,16 @@ --- sidebar_label: 'Aggregate providers' sidebar_position: 8 +description: 'How a provider bundle records a group of wiring choices once, why a context delegates to it, and why a bundle must be checked through a real context.' --- # Aggregate providers -An **aggregate provider** collects provider choices into a wiring table that several contexts can -reuse. Each context delegates a group of components to that table, so changing the shared choices -can update them together. The chosen providers still receive the original context and use its data; -the bundle only connects them. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations whose +choices can be bundled. An **aggregate provider** collects provider choices into a wiring table that +several contexts can reuse. Each context delegates a group of components to that table, so changing +the shared choices can update them together. The chosen providers still receive the original context +and use its data; the bundle only connects them. ## A table whose target is not a context From 3bab71478a68bdf71747b430558521bd8d7a0224 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:03:04 +0100 Subject: [PATCH 234/516] Name the project and describe the namespaces page The page opens with Context-Generic Programming and the tag line about keeping the wiring table short, and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/namespaces.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index ff5e861a..8ff87eff 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -1,14 +1,16 @@ --- sidebar_label: 'Namespaces' sidebar_position: 9 +description: 'How a namespace names and routes shared wiring, how contexts inherit it while filling unbound paths, and why an inherited binding cannot be overridden.' --- # Namespaces -Namespaces give shared wiring a name that contexts can inherit. They organize component lookups -under paths, allowing a shared table to bind the choices its contexts have in common and leave other -destinations for each context to fill. The distinction matters: a context can fill an unbound path, -but it cannot replace an inherited binding. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, and +namespaces keep the table that selects them short. Namespaces give shared wiring a name that +contexts can inherit. They organize component lookups under paths, allowing a shared table to bind +the choices its contexts have in common and leave other destinations for each context to fill. The +distinction matters: a context can fill an unbound path, but it cannot replace an inherited binding. ## Repeated wiring obscures the differences From fec69be2a0c44500dafac760e07d6394e49f8e21 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:03:18 +0100 Subject: [PATCH 235/516] Name the project and describe the modular error handling page The page opens with Context-Generic Programming beside the error-type idea and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/modular-error-handling.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index be44c8ed..75f89cac 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -1,14 +1,17 @@ --- sidebar_label: 'Modular error handling' sidebar_position: 10 +description: 'How a context chooses one error type and the providers that raise and wrap it, so reusable code reports failures without fixing their representation.' --- # Modular error handling -Modular error handling lets reusable code report failures while each application chooses how to -represent them. In CGP, the context selects a shared error type and providers for converting -source errors into it and attaching detail. Reusable code declares which of those operations it -needs, allowing the same implementation to work with different error policies. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, +including the implementations that build errors. Modular error handling lets reusable code report +failures while each application chooses how to represent them. The context selects a shared error +type and providers for converting source errors into it and attaching detail. Reusable code declares +which of those operations it needs, allowing the same implementation to work with different error +policies. Errors built this way still propagate through ordinary Rust `Result` values and the `?` operator. This page explains how these choices fit together, how to preserve structured failures, and when From 7828edd58f179ef30c4dad8df2f3eb9474712303 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:03:24 +0100 Subject: [PATCH 236/516] Name the project and describe the handlers page The page opens with Context-Generic Programming beside the computation interface and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/handlers.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 1ce30f1c..63ff799b 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -1,11 +1,13 @@ --- sidebar_label: 'Handlers' sidebar_position: 11 +description: 'How CGP represents computations as components, the synchronous, async, fallible, and borrowed forms, and how a wiring entry composes them into a pipeline.' --- # Handlers -CGP's handler components represent computations through a common input-and-output interface. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, and +its **handler** components represent computations through a common input-and-output interface. Because providers share that interface, a context can select individual computations or compose them into a pipeline through wiring. The family has separate forms for synchronous and async work, fallible results, and owned or borrowed inputs, so a simple computation needs only the requirements From b7ae9c9a75fad397d245434aba7f20f86c34ff35 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:03:37 +0100 Subject: [PATCH 237/516] Name the project and describe the monadic handlers page The page opens with Context-Generic Programming beside the continuation-rule idea and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/monadic-handlers.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index 0af06a37..c8f3ea4a 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -1,14 +1,16 @@ --- sidebar_label: 'Monadic handlers' sidebar_position: 12 +description: 'How monadic handlers put a pipeline continuation rule in a type, the err, ok, and identity monads, and how a monad transformer stacks two result layers.' --- # Monadic handlers -Monadic handlers separate a pipeline's computations from the rule that decides whether another -step should run. The same composition machinery can stop at the first error, stop at the first -success, or pass every output onward. A monad supplies that continuation rule, while the providers -supply the work performed at each step. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, and +monadic handlers make the rule that joins them a choice too. Monadic handlers separate a pipeline's +computations from the rule that decides whether another step should run. The same composition +machinery can stop at the first error, stop at the first success, or pass every output onward. A +monad supplies that continuation rule, while the providers supply the work performed at each step. Ordinary [handler composition](./handlers.md) already connects outputs to inputs. Monadic composition extends that connection to cases where the next step needs a value inside a result, From a28db7f9e5a549234d1524753f3edede29702edc Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:03:48 +0100 Subject: [PATCH 238/516] Name the project and describe the extensible records page The page opens with Context-Generic Programming beside the field-list idea and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/extensible-records.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index 7e1bf7e2..762d86a1 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -1,14 +1,17 @@ --- sidebar_label: 'Extensible records' sidebar_position: 13 +description: 'How a struct field list becomes a type, how a builder records which fields are present, and how independent providers assemble a record the compiler checks.' --- # Extensible records -Extensible records let generic code read and assemble structs through their field names and types. -A provider can contribute fields without knowing the final struct, so several independent providers -can supply parts of a larger value. As those parts are assembled, the builder's type tracks which -fields are present, letting the compiler check that construction is complete. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations whose +providers can contribute fields. Extensible records let generic code read and assemble structs +through their field names and types. A provider can contribute fields without knowing the final +struct, so several independent providers can supply parts of a larger value. As those parts are +assembled, the builder's type tracks which fields are present, letting the compiler check that +construction is complete. ## What a closed struct cannot do From efaa5dcfcae0f09ba4a2e20e5f7bd08fdce65d4f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:03:57 +0100 Subject: [PATCH 239/516] Name the project and describe the extensible variants page The page opens with Context-Generic Programming beside the variant-list idea and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/extensible-variants.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 35aae051..59062db3 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -1,14 +1,16 @@ --- sidebar_label: 'Extensible variants' sidebar_position: 14 +description: 'How an enum variant list becomes a sum type, how extraction proves every variant is handled without a wildcard, and how one handler serves several enums.' --- # Extensible variants -Extensible variants let generic code construct and handle enums through variant names and payload -types. By describing the cases it needs through traits, a handler can work across compatible enums -without depending on any one enum definition. The compiler still checks that every variant is -covered, even when independently written handlers supply the cases. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations whose +handlers can cover enum variants. Extensible variants let generic code construct and handle enums +through variant names and payload types. By describing the cases it needs through traits, a handler +can work across compatible enums without depending on any one enum definition. The compiler still +checks that every variant is covered, even when independently written handlers supply the cases. This uses the same field representation as [extensible records](./extensible-records.md), but an enum contains one alternative at a time. That difference changes how generic code takes a value From 7165e07f582b44bb365dc52b52c09a414ab39f16 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:04:13 +0100 Subject: [PATCH 240/516] Name the project and describe the dispatching page The page opens with Context-Generic Programming beside the routing idea and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/dispatching.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index ac0047ce..756d412a 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -1,14 +1,17 @@ --- sidebar_label: 'Dispatching' sidebar_position: 15 +description: 'How a dispatcher routes record fields and enum variants to the providers that process them, and how the compiler checks coverage and completeness.' --- # Dispatching -Dispatching connects a record's fields or an enum's variants to the providers that process them. -By separating that connection from the individual computations, a generic dispatcher can build -several record types or handle several enum types while each provider implements one part of the -work. The compiler checks that the pieces fit together and cover the required fields or variants. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations that +a dispatcher can route data to. Dispatching connects a record's fields or an enum's variants to the +providers that process them. By separating that connection from the individual computations, a +generic dispatcher can build several record types or handle several enum types while each provider +implements one part of the work. The compiler checks that the pieces fit together and cover the +required fields or variants. [Extensible records](./extensible-records.md) and [extensible variants](./extensible-variants.md) expose data to generic code through field and variant traits. Dispatchers use those traits to run From 100bba4e5d61c9930bbaa770c35b1b73156dcb21 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:04:44 +0100 Subject: [PATCH 241/516] Name the project and describe the type-level DSL page The page opens with Context-Generic Programming beside the type-as-program idea and carries a written description. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/type-level-dsls.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index 2056d60a..503c3d4f 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -1,14 +1,17 @@ --- sidebar_label: 'Type-level DSLs' sidebar_position: 16 +description: 'How Rust types can represent a program, how providers give each syntax form meaning, and how the compiler resolves a whole expression through wiring.' --- # Type-level DSLs -A type-level domain-specific language represents a program as Rust types and gives its operations -meaning through CGP providers. The program's structure can stay the same while different contexts -select different interpretations, and new syntax forms can bring their own providers. Rust checks -and resolves those choices at compile time; the selected operations execute when called. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations that +can interpret a type as a program. A type-level domain-specific language represents a program as +Rust types and gives its operations meaning through CGP providers. The program's structure can stay +the same while different contexts select different interpretations, and new syntax forms can bring +their own providers. Rust checks and resolves those choices at compile time; the selected operations +execute when called. The [handler](./handlers.md) family's `Code` parameter gives the program type a place in a computation's interface. An interpreter can use the structure of that type to choose and combine From 6a42bb85852f8790938232acf9644e2563fa1923 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:04:54 +0100 Subject: [PATCH 242/516] Name the project and describe the Send bounds page The page opens with Context-Generic Programming beside the sendability problem and carries a written description; the tag line is left out because the page is not about choosing an implementation. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/send-bounds.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index d3b63220..a5c5a6e2 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -1,10 +1,12 @@ --- sidebar_label: 'Recovering Send bounds' sidebar_position: 17 +description: 'How a companion trait exposes a sendable future when an async CGP method leaves Send open, and why the forwarding implementation needs a concrete context.' --- # Recovering `Send` bounds +[Context-Generic Programming](/docs/) (CGP) leaves `Send` out of its async trait methods. Recovering a `Send` bound lets generic code require a sendable future from an async interface that leaves that guarantee open. CGP's `#[async_trait]` returns an unboxed future without promising `Send`, so a caller cannot infer sendability from the consumer trait alone. A companion trait can From 5fd79f148b9c670de8932bf55641196e9f8a6430 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:05:01 +0100 Subject: [PATCH 243/516] Name the project and give the modularity hierarchy a reader-facing title The page opens with Context-Generic Programming and the tag line, gains a problem-oriented title and a written description, and keeps its heading and sidebar label. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/modularity-hierarchy.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index 45d9f357..c97c8a07 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -1,14 +1,18 @@ --- +title: 'When to use CGP, and when a plain trait is enough' sidebar_label: 'Modularity Hierarchy' sidebar_position: 18 +description: 'How implementation choice grows from a shared blanket impl to providers selected per context and target, and how to pick the least complex tier your program needs.' --- # Modularity Hierarchy -The modularity hierarchy describes how implementation choices grow from a single shared body to -providers selected independently by context, target type, and enclosing provider. Each tier adds a -place where a program can make a choice, along with the structure needed to express it. The useful -tier is the least complex one that supports the variation your program actually needs. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, and +the modularity hierarchy says how far that choice should go. The hierarchy describes how +implementation choices grow from a single shared body to providers selected independently by +context, target type, and enclosing provider. Each tier adds a place where a program can make a +choice, along with the structure needed to express it. The useful tier is the least complex one +that supports the variation your program actually needs. Encoding illustrates how those choices differ. The examples below omit imports from `cgp::prelude::*`, context structs, and some provider bodies so the implementation choices remain From 05f99a9df459942321a35e8ce19469fb72bed9e1 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:05:14 +0100 Subject: [PATCH 244/516] Name the project and describe the concepts index The index opens with Context-Generic Programming and the tag line, and carries a written description. The category keeps its hand-written index link, so no generated-index description applies. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/index.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 9ccaa54b..4648c1f3 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -1,11 +1,13 @@ --- sidebar_label: 'Overview' sidebar_position: 0 +description: 'The concept pages of Context-Generic Programming: coherence, the consumer and provider split, dependencies, composition, and the applied designs, each with its cost.' --- # Concepts -CGP connects reusable trait implementations to the types that use them through compile-time wiring. +[Context-Generic Programming](/docs/) (CGP) extends Rust with pluggable trait implementations, +connecting reusable implementations to the types that use them through compile-time wiring. Understanding that connection explains how providers obtain dependencies, how contexts choose shared types and values, and how implementations compose into larger operations. These pages develop those ideas alongside their costs. You can read them without running code, with familiarity with Rust From cc9953e0fa0b90071011c4994e456840ae506754 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:08:03 +0100 Subject: [PATCH 245/516] Add the tag line to the cargo-cgp overview opening The overview now relates the short tag line to the tool's subject, wiring code that selects implementations, and its quoted output was re-captured from the missing-height program. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/cargo-cgp/index.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/cargo-cgp/index.md b/docs/cargo-cgp/index.md index 46a240bd..b67bb9ae 100644 --- a/docs/cargo-cgp/index.md +++ b/docs/cargo-cgp/index.md @@ -8,10 +8,10 @@ description: 'cargo-cgp runs in place of cargo check and reports a CGP compile e # cargo-cgp `cargo-cgp` helps you understand compile errors and macro expansions in -[Context-Generic Programming (CGP)](/docs/) code. CGP's macros generate ordinary Rust traits and -implementations, so a compiler error may name that generated machinery while leaving the failed -requirement unclear. Running `cargo cgp check` brings the root cause forward for failures the -tool recognizes. +[Context-Generic Programming (CGP)](/docs/) code. CGP extends Rust with pluggable trait +implementations through macros that generate ordinary Rust traits, so a compiler error may name +that generated machinery while leaving the failed requirement unclear. Running `cargo cgp check` +brings the root cause forward for failures the tool recognizes. You can keep using ordinary cargo commands alongside it. CGP is a library on stable Rust, so `cargo check`, `cargo build`, and `cargo test` work without the tool. Reach for `cargo-cgp` when From 270efdcc1ec84a491d09d3dafba350036dcc0555 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:09:31 +0100 Subject: [PATCH 246/516] Name the project in the cargo-cgp installation opening The installation page now identifies cargo-cgp as the error toolchain for Context-Generic Programming at first mention. Its version, pinned nightly, platform statement, and commands match the repository. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/cargo-cgp/installation.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/cargo-cgp/installation.md b/docs/cargo-cgp/installation.md index b255f1d8..b06e3ae3 100644 --- a/docs/cargo-cgp/installation.md +++ b/docs/cargo-cgp/installation.md @@ -7,8 +7,10 @@ description: 'Install cargo-cgp v0.1.0 with cargo and rustup or with Nix, check # Installation -To install [`cargo-cgp`](./index.md), choose the path that fits your existing Rust environment: -cargo with rustup, or the Nix flake. This page covers version 0.1.0, built for CGP v0.8. +To install [`cargo-cgp`](./index.md), the error toolchain for +[Context-Generic Programming (CGP)](/docs/) code, choose the path that fits your existing Rust +environment: cargo with rustup, or the Nix flake. This page covers version 0.1.0, built for +CGP v0.8. The cargo path installs the command first, then prepares the compiler it needs. `cargo-cgp` runs a separate `cargo-cgp-driver`, which embeds the Rust compiler and must match one exact nightly. From 5ec62b0225975628a32cfc04c51cae55cef292f8 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:11:30 +0100 Subject: [PATCH 247/516] Give every concept page a search-facing title The explanation guide asks each concept page for a problem-oriented title in the reader's words, not only the construct name. The remaining sixteen pages and the index now carry one in front matter, while their headings and sidebar labels stay as they were. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/abstract-types.md | 1 + docs/concepts/aggregate-providers.md | 1 + docs/concepts/check-traits.md | 1 + docs/concepts/consumer-and-provider-traits.md | 1 + docs/concepts/dispatching.md | 1 + docs/concepts/extensible-records.md | 1 + docs/concepts/extensible-variants.md | 1 + docs/concepts/handlers.md | 1 + docs/concepts/higher-order-providers.md | 1 + docs/concepts/impl-side-dependencies.md | 1 + docs/concepts/implicit-arguments.md | 1 + docs/concepts/index.md | 1 + docs/concepts/modular-error-handling.md | 1 + docs/concepts/monadic-handlers.md | 1 + docs/concepts/namespaces.md | 1 + docs/concepts/send-bounds.md | 1 + docs/concepts/type-level-dsls.md | 1 + 17 files changed, 17 insertions(+) diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index c106e724..43f17b66 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -1,4 +1,5 @@ --- +title: 'Let each context choose a shared type' sidebar_label: 'Abstract types' sidebar_position: 5 description: 'How a context chooses an associated type through wiring, so providers share one scalar, error type, or runtime without adding a parameter at every call.' diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index 19e25241..f53ee7fb 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -1,4 +1,5 @@ --- +title: 'Reuse a group of wiring choices as one provider' sidebar_label: 'Aggregate providers' sidebar_position: 8 description: 'How a provider bundle records a group of wiring choices once, why a context delegates to it, and why a bundle must be checked through a real context.' diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index 93efbec6..d48a3840 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -1,4 +1,5 @@ --- +title: 'Check wiring where the choice is written' sidebar_label: 'Checking your wiring' sidebar_position: 6 description: 'How check traits and check_components! verify a context wiring beside the table, what the raw and rewritten diagnostics show, and what a check does not prove.' diff --git a/docs/concepts/consumer-and-provider-traits.md b/docs/concepts/consumer-and-provider-traits.md index fe6aa50a..a9e2b43b 100644 --- a/docs/concepts/consumer-and-provider-traits.md +++ b/docs/concepts/consumer-and-provider-traits.md @@ -1,4 +1,5 @@ --- +title: 'Connect a method call to the provider it selects' sidebar_label: 'Consumer and provider traits' sidebar_position: 2 description: 'How CGP splits one trait into a consumer trait for callers and a provider trait for implementations, and how wiring connects a call to its provider.' diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index 756d412a..55bcd8cf 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -1,4 +1,5 @@ --- +title: 'Route fields and variants to their handlers' sidebar_label: 'Dispatching' sidebar_position: 15 description: 'How a dispatcher routes record fields and enum variants to the providers that process them, and how the compiler checks coverage and completeness.' diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index 762d86a1..97411455 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -1,4 +1,5 @@ --- +title: 'Build a struct field by field, checked at compile time' sidebar_label: 'Extensible records' sidebar_position: 13 description: 'How a struct field list becomes a type, how a builder records which fields are present, and how independent providers assemble a record the compiler checks.' diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 59062db3..29ed4f2d 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -1,4 +1,5 @@ --- +title: 'Handle every enum variant without a wildcard' sidebar_label: 'Extensible variants' sidebar_position: 14 description: 'How an enum variant list becomes a sum type, how extraction proves every variant is handled without a wildcard, and how one handler serves several enums.' diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 63ff799b..c5f221dc 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -1,4 +1,5 @@ --- +title: 'Represent a computation as a selectable component' sidebar_label: 'Handlers' sidebar_position: 11 description: 'How CGP represents computations as components, the synchronous, async, fallible, and borrowed forms, and how a wiring entry composes them into a pipeline.' diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index 43edb4ac..dd3b6467 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -1,4 +1,5 @@ --- +title: 'Compose providers that take other providers' sidebar_label: 'Higher-order providers' sidebar_position: 7 description: 'How a provider takes another provider as a parameter, so a wrapper such as scaling reuses one body with different inner calculations.' diff --git a/docs/concepts/impl-side-dependencies.md b/docs/concepts/impl-side-dependencies.md index 44af3831..c1e891e8 100644 --- a/docs/concepts/impl-side-dependencies.md +++ b/docs/concepts/impl-side-dependencies.md @@ -1,4 +1,5 @@ --- +title: 'Keep provider dependencies out of the caller interface' sidebar_label: 'Impl-side dependencies' sidebar_position: 3 description: 'How a provider keeps its trait, value, and type requirements out of the caller interface, and how CGP checks them when a context selects the provider.' diff --git a/docs/concepts/implicit-arguments.md b/docs/concepts/implicit-arguments.md index cb6bacd2..4b730df7 100644 --- a/docs/concepts/implicit-arguments.md +++ b/docs/concepts/implicit-arguments.md @@ -1,4 +1,5 @@ --- +title: 'Read context values without extra parameters' sidebar_label: 'Implicit arguments' sidebar_position: 4 description: 'How implicit arguments read context fields through function parameters, how the declared type controls borrowing and cloning, and when a getter trait is the better fit.' diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 4648c1f3..0a97608d 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -1,4 +1,5 @@ --- +title: 'CGP concepts, explained with their costs' sidebar_label: 'Overview' sidebar_position: 0 description: 'The concept pages of Context-Generic Programming: coherence, the consumer and provider split, dependencies, composition, and the applied designs, each with its cost.' diff --git a/docs/concepts/modular-error-handling.md b/docs/concepts/modular-error-handling.md index 75f89cac..164703a8 100644 --- a/docs/concepts/modular-error-handling.md +++ b/docs/concepts/modular-error-handling.md @@ -1,4 +1,5 @@ --- +title: 'Choose one error type for the whole context' sidebar_label: 'Modular error handling' sidebar_position: 10 description: 'How a context chooses one error type and the providers that raise and wrap it, so reusable code reports failures without fixing their representation.' diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index c8f3ea4a..9f0f7d3d 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -1,4 +1,5 @@ --- +title: 'Choose how a pipeline continues on a result' sidebar_label: 'Monadic handlers' sidebar_position: 12 description: 'How monadic handlers put a pipeline continuation rule in a type, the err, ok, and identity monads, and how a monad transformer stacks two result layers.' diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index 8ff87eff..cf9cc09b 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -1,4 +1,5 @@ --- +title: 'Share and inherit wiring with namespaces' sidebar_label: 'Namespaces' sidebar_position: 9 description: 'How a namespace names and routes shared wiring, how contexts inherit it while filling unbound paths, and why an inherited binding cannot be overridden.' diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index a5c5a6e2..881df79d 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -1,4 +1,5 @@ --- +title: 'Recover a Send bound from an async CGP method' sidebar_label: 'Recovering Send bounds' sidebar_position: 17 description: 'How a companion trait exposes a sendable future when an async CGP method leaves Send open, and why the forwarding implementation needs a concrete context.' diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index 503c3d4f..b6964f1a 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -1,4 +1,5 @@ --- +title: 'Represent a program as Rust types' sidebar_label: 'Type-level DSLs' sidebar_position: 16 description: 'How Rust types can represent a program, how providers give each syntax form meaning, and how the compiler resolves a whole expression through wiring.' From 20bd312335f9a38245565fd9baf947bfc12dcf52 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:12:37 +0100 Subject: [PATCH 248/516] Match the coherence diagram to the page's value types The diagram showed application contexts that the page does not introduce at its basic tier. It now shows String wired to EncodeAsText and Vec to EncodeAsHex, as the page's own wiring does, and the alt text and lead-in say the same. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/concepts/coherence.md | 4 +-- static/img/coherence-scoped.svg | 48 +++++++++++++++------------------ 2 files changed, 24 insertions(+), 28 deletions(-) diff --git a/docs/concepts/coherence.md b/docs/concepts/coherence.md index 2a4af854..eaeec8bd 100644 --- a/docs/concepts/coherence.md +++ b/docs/concepts/coherence.md @@ -199,9 +199,9 @@ delegate_components! { Vec { EncoderComponent: EncodeAsHex } } ``` Rust's rule still holds. What changes is where the choice is recorded: coherence is scoped to each -context's provider, so the two applications can encode the same `String` differently. +provider type, and each value type names one of them. -![Diagram: Rust checks coherence once against each provider implementation, and CGP scopes the recorded choice to each context. The String value encodes as text in one application and as hexadecimal in another.](/img/coherence-scoped.svg) +![Diagram: Rust rejects the overlapping impls once. CGP gives each encoder its own provider type, so String is wired to EncodeAsText and Vec of bytes to EncodeAsHex, and both impls coexist while each value type names one provider.](/img/coherence-scoped.svg) With these entries, `value.encode()` uses `EncodeAsText` for a `String` and `EncodeAsHex` for a `Vec`. The string `"hi"` therefore encodes as `b"hi"`, while the byte vector `b"hi".to_vec()` diff --git a/static/img/coherence-scoped.svg b/static/img/coherence-scoped.svg index 19050735..fe8d0db0 100644 --- a/static/img/coherence-scoped.svg +++ b/static/img/coherence-scoped.svg @@ -1,6 +1,6 @@ - + Coherence scoped to each provider choice - Rust keeps one implementation of a trait for a type by rejecting overlapping impls. CGP keeps that rule but scopes the choice to the provider type: the String value is encoded as text in one context and as hexadecimal in another. + Rust keeps one implementation of a trait for a type by rejecting overlapping impls. CGP keeps that rule but scopes the choice to the provider type: the String value type is wired to EncodeAsText and the Vec of bytes to EncodeAsHex, so both impls coexist while each value type names one provider. @@ -9,7 +9,7 @@ - + Rust coherence One implementation per trait and type, checked for the whole program. @@ -28,28 +28,24 @@ every lookup for String agrees. - - CGP: same rule, scoped per provider + + CGP: the same rule, per provider Each provider type gets its own impl, so - each context records one choice. - - - String - - - - - - - - - context App - selects EncodeAsText - encode → b"hi" - - - context Firmware - selects EncodeAsHex - encode → b"6869" - + each value type names one provider. + + + String + + + EncodeAsText + encode → b"hi" + + + Vec<u8> + + + EncodeAsHex + encode → b"6869" + + Both impls coexist because their provider types differ. From 2603380628381c48b8310539bc4dc615173db694 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:21:58 +0100 Subject: [PATCH 249/516] Point the writing rule at the reading map The site's prose rule now names the knowledge base reading map, so a writer reads the shared set and the page kind's row rather than the whole strategy. Co-Authored-By: deepseek-v4.1-flash-1017 --- AGENTS.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 891e5abc..bbd99e6f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,7 +60,10 @@ block to match. These are the actionable rules here: ## Public prose -- Read the communication strategy before outlining or drafting a page. +- Read the shared set and the page kind's row of the knowledge base's + [reading map](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/README.md#the-reading-map) + before outlining or drafting a page, and a strategy document whole when the page makes a claim + its row does not cover. - Name Context-Generic Programming in each page's prose and relate a short form of the tag line to its content, following the knowledge base's [naming rule](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/communication-strategy/identity.md#the-name-and-the-tag-line-on-every-page); From e3333de80aa7740a687b01963ef0dce689acf3e2 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:28:54 +0100 Subject: [PATCH 250/516] Name the project and fix the quoted hashes The troubleshooting page names Context-Generic Programming in its opening, and its loader examples use the hash the pinned nightly produces. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/cargo-cgp/troubleshooting.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/cargo-cgp/troubleshooting.md b/docs/cargo-cgp/troubleshooting.md index a3456b54..2a5fd08e 100644 --- a/docs/cargo-cgp/troubleshooting.md +++ b/docs/cargo-cgp/troubleshooting.md @@ -7,9 +7,9 @@ description: 'Match an error from cargo-cgp itself to its cause and fix: the set # Troubleshooting -If [`cargo-cgp`](./index.md) will not start or behaves unexpectedly, begin with the symptom index -below. For a tool that runs but reports an unfamiliar CGP error, [Reading the output](./reading-output.md) -explains the diagnostic instead. +If [`cargo-cgp`](./index.md), the check command for Context-Generic Programming projects, will not +start or behaves unexpectedly, begin with the symptom index below. For a tool that runs but reports +an unfamiliar CGP error, [Reading the output](./reading-output.md) explains the diagnostic instead. Many startup failures involve a mismatch between the front end, `cargo-cgp-driver`, and the pinned nightly. The front end normally finds the driver beside itself, and the driver loads that nightly's @@ -98,7 +98,7 @@ loader's message so you can see which library could not be loaded: ```text error: the cargo-cgp-driver at /home/you/.cargo/bin/cargo-cgp-driver (beside cargo-cgp) could not run under toolchain `nightly-2026-11-05` (it was likely built against a different nightly): - /home/you/.cargo/bin/cargo-cgp-driver: error while loading shared libraries: librustc_driver-1a6e695c833ebcd1.so: cannot open shared object file: No such file or directory + /home/you/.cargo/bin/cargo-cgp-driver: error while loading shared libraries: librustc_driver-a1ed262f84b24882.so: cannot open shared object file: No such file or directory help: run `cargo cgp setup` ``` @@ -141,7 +141,7 @@ This failure comes from the operating system's loader, before the driver's own c unlike any other message from the tool: ```text -cargo-cgp-driver: error while loading shared libraries: librustc_driver-1a6e695c833ebcd1.so: cannot open shared object file: No such file or directory +cargo-cgp-driver: error while loading shared libraries: librustc_driver-a1ed262f84b24882.so: cannot open shared object file: No such file or directory ``` The driver needs the exact `librustc_driver-.so` it linked against when built. Your hash may @@ -166,7 +166,7 @@ may try to start the driver under another toolchain: ```text error: process didn't exit successfully: `…/cargo-cgp-driver …/stable-…/bin/rustc -vV` (exit status: 127) --- stderr -…/cargo-cgp-driver: error while loading shared libraries: librustc_driver-1a6e695c833ebcd1.so: cannot open shared object file: No such file or directory +…/cargo-cgp-driver: error while loading shared libraries: librustc_driver-a1ed262f84b24882.so: cannot open shared object file: No such file or directory ``` In that case, unset `CARGO_CGP_NO_MANAGE` so the tool switches to the pinned nightly itself, or make that nightly From 2863eff7a29f214408882db60111e9b97efe6093 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:31:21 +0100 Subject: [PATCH 251/516] Match the check and expand pages to the tool The check page quotes cargo's summary line, and the expand page names Context-Generic Programming and counts the expansion it now produces. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/cargo-cgp/check.md | 2 ++ docs/cargo-cgp/expand.md | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index f6296102..fb40e6ef 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -95,6 +95,7 @@ error[E0599]: [CGP-E001] missing field `height` on `Rectangle` = help: add the field `height: f64` to `Rectangle` For more information about this error, try `rustc --explain E0599`. +error: could not compile `area-demo` (lib) due to 1 previous error ``` Read the tree to connect the suggested fix to the failing call. `CanCalculateArea` is required, @@ -139,6 +140,7 @@ error[E0277]: [CGP-E001] missing field `height` on `Rectangle` = help: add the field `height: f64` to `Rectangle` For more information about this error, try `rustc --explain E0277`. +error: could not compile `area-demo` (lib) due to 1 previous error ``` That explicit check helps ordinary `cargo check` expose the missing requirement too. Its field diff --git a/docs/cargo-cgp/expand.md b/docs/cargo-cgp/expand.md index 1b90bde3..c35692da 100644 --- a/docs/cargo-cgp/expand.md +++ b/docs/cargo-cgp/expand.md @@ -7,8 +7,9 @@ description: 'Print the Rust your CGP macros generate, narrowed to one module, t # Expand -`cargo cgp expand` lets you inspect the Rust generated by a [CGP](/docs/) macro when its expansion -would help explain a requirement or a wiring choice. The command is part of [`cargo-cgp`](./index.md) +`cargo cgp expand` lets you inspect the Rust generated by a +[Context-Generic Programming (CGP)](/docs/) macro when its expansion would help explain a requirement +or a wiring choice. The command is part of [`cargo-cgp`](./index.md) and prints the crate after macro expansion. It also writes CGP's type-level constructs back in the form you used, making the generated code easier to read: @@ -138,7 +139,7 @@ and forwarded its requirements. At the end, ## Narrowing with `--item` -Even this small crate expands to 148 lines, while the `Rectangle` selection above takes 49. +Even this small crate expands to 156 lines, while the `Rectangle` selection above takes 49. To keep the relevant code together, `--item` accepts a `::`-separated path to a module or item inside the crate: From faf3f96595adab54347bd28e66e5f04926e9a81b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:32:34 +0100 Subject: [PATCH 252/516] Name the project on the last two tool pages The command reference and editor page now name Context-Generic Programming, and the command reference gives the loader variable each platform uses. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/cargo-cgp/command-reference.md | 5 +++-- docs/cargo-cgp/editor-integration.md | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/cargo-cgp/command-reference.md b/docs/cargo-cgp/command-reference.md index 5e8df59c..f4dcf9fc 100644 --- a/docs/cargo-cgp/command-reference.md +++ b/docs/cargo-cgp/command-reference.md @@ -8,7 +8,8 @@ description: 'Every cargo-cgp command and option, the environment variables it r # Command reference This page collects the commands, options, environment variables, files, and exit statuses of -[`cargo-cgp`](./index.md) version 0.1.0. Use it to look up an exact flag or setting; the other +[`cargo-cgp`](./index.md) version 0.1.0, the error toolchain for +[Context-Generic Programming (CGP)](/docs/). Use it to look up an exact flag or setting; the other pages in this section develop working examples. ## Running it @@ -115,7 +116,7 @@ driver and matching compiler libraries: |---|---| | `RUSTC_WORKSPACE_WRAPPER` | The driver. This replaces any value you set, so a wrapper of your own given through this variable does not run under the tool, which prints a warning saying so. | | `RUSTUP_TOOLCHAIN` | The pinned nightly, unless `CARGO_CGP_NO_MANAGE` is set. | -| `LD_LIBRARY_PATH` | The `lib` directory of the toolchain the check runs under, added in front of any existing value, so the driver can load the compiler. | +| `LD_LIBRARY_PATH` | The `lib` directory of the toolchain the check runs under, added in front of any existing value, so the driver can load the compiler. On macOS the tool sets `DYLD_FALLBACK_LIBRARY_PATH` instead, and on Windows it prepends to `PATH`. | ## Files and directories diff --git a/docs/cargo-cgp/editor-integration.md b/docs/cargo-cgp/editor-integration.md index c6dbfb30..cef94647 100644 --- a/docs/cargo-cgp/editor-integration.md +++ b/docs/cargo-cgp/editor-integration.md @@ -14,7 +14,8 @@ lead with the same root causes as they do in a terminal. This page covers VS Code with the [rust-analyzer extension](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). Before configuring it, [install](./installation.md) the [`cargo-cgp`](./index.md) toolchain for -[CGP](/docs/) and confirm that `cargo cgp check` works in a terminal inside your project. +[Context-Generic Programming (CGP)](/docs/) and confirm that `cargo cgp check` works in a terminal +inside your project. ## Set it up From baa146b232ba05bd2d0f4782ca6037761b1d0ae7 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:34:22 +0100 Subject: [PATCH 253/516] Correct the pass-through list and code range The generic-context check is reshaped to CGP-E002, so it is not a pass-through case, and the macro-input codes end at E039. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/cargo-cgp/reading-output.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/docs/cargo-cgp/reading-output.md b/docs/cargo-cgp/reading-output.md index 5117f136..1051b218 100644 --- a/docs/cargo-cgp/reading-output.md +++ b/docs/cargo-cgp/reading-output.md @@ -299,7 +299,7 @@ For more information about this error, try `rustc --explain E0599`. Here adding `#[uses(PersonName)]` beneath `#[cgp_fn]` on `greeting` supplies the missing requirement. The same remedy applies inside a [`#[cgp_impl]`](/docs/reference/macros/cgp_impl) provider body. Without the rewrite, the compiler refers to a method on the generated `&__Context__` parameter -and never names the attribute. Many codes from `[CGP-E030]` through `[CGP-E044]` similarly +and never names the attribute. Many codes from `[CGP-E030]` through `[CGP-E039]` similarly identify a mistake in a macro's input and offer a specific correction. ## Errors that pass through unchanged @@ -309,9 +309,6 @@ every class. An error with no `[CGP-Exxx]` code anywhere in it, in the headline it, is one the tool passed through, so read it as the compiler wrote it. These are the ones you are most likely to meet: -- **A check on a generic context:** `check_components! { App { … } }` keeps the compiler's headline, though - its notes name the consumer and provider traits. Checking one concrete instance, such as `App`, gets the - usual error. - **An unconstrained lifetime or blanket key:** a per-entry lifetime the provider uses, or a blanket entry keyed by its own parameter, keeps the compiler's `E0207`, whose suggested fixes do not compile. See [A generic that reaches nothing](/docs/reference/errors#a-generic-that-reaches-nothing). From e14eb4654ae60cb877d28e346b5391ed263b462e Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:41:00 +0100 Subject: [PATCH 254/516] Correct the index row for E0425 E0425 belongs to the unresolved-wiring-name class, not the generated-name section, so the row now names only E0433. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/errors.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 658f98b7..86234bfd 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -67,7 +67,7 @@ Match the compiler's code and the shape of the message. | `E0210` / `E0117` [orphan rule](/docs/reference/glossary#orphan-rule) | Registering into a namespace you do not own | [Registering into a namespace you do not own](#registering-into-a-namespace-you-do-not-own) | | `E0207` type parameter is not constrained, or `[CGP-E019]` | A per-entry generic that never reaches the key | [A generic that reaches nothing](#a-generic-that-reaches-nothing) | | `E0107` trait takes N generic arguments but N+1 supplied | A consumer trait written where a provider trait belongs | [Naming the wrong half of a component](#naming-the-wrong-half-of-a-component) | -| `E0433` / `E0425` cannot find type | A name the generated code cannot see | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | +| `E0433` cannot find type | A name the generated code cannot see | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | | `E0576` cannot find associated type … in trait | A `#[use_type]` import with a wrong name | [An imported type that does not exist](#an-imported-type-that-does-not-exist) | | `E0404` expected trait, found type parameter | An [abstract type](/docs/reference/glossary#abstract-type) named after its own bound | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | From 48759b059cef25ed9ffa0241b131a08c38848320 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:43:51 +0100 Subject: [PATCH 255/516] Correct two claims in the dependency section The checked output needs a check added at the wiring site, and the raw E0271 points a note at the attribute rather than its caret. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/errors.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 86234bfd..dd828483 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -113,7 +113,8 @@ That block **compiles**. Nothing has asked yet whether `GreetHello` can do its j ### What you see -Through the tool, both routes to the failure give the same answer. Checking it: +Through the tool, both routes to the failure give the same answer. Adding a check at the wiring site +and checking it: ```text error[E0277]: [CGP-E001] missing field `name` on `Person` @@ -256,8 +257,8 @@ error[E0271]: [CGP-E005] abstract type `Scalar` of `HasScalarType` on `Rectangle ``` Both halves of the disagreement are named, and the `help:` names the wiring line to change. The raw -`E0271` is much worse: it states only what was *required*, never what the context supplied, and puts -its caret on the `#[cgp_type]` attribute that declared the type, nowhere near either decision. +`E0271` is much worse: it states only what was *required*, never what the context supplied, and points +a note at the `#[cgp_type]` attribute that declared the type, nowhere near either decision. The same shape appears one level down, when a *field's* type is expressed through an abstract type (`#[implicit] database: &Pool`). The tool then gives the requirement in both forms, From 121e4f93c5d41f934f17218e422132ab23851a1e Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:45:59 +0100 Subject: [PATCH 256/516] Cover the two missing wiring classes The page now explains a wiring name that resolves to nothing and a provider impl written without its macro, with their index rows. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/errors.md | 44 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/docs/reference/errors.md b/docs/reference/errors.md index dd828483..f7763735 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -58,10 +58,12 @@ Match the compiler's code and the shape of the message. | `E0599` no associated function found for type parameter | An inner provider called but never imported | [Using something you did not declare](#using-something-you-did-not-declare) | | `E0277` … `CanUseComponent` is not satisfied | A checked component's provider is missing something | [A dependency is not met](#a-dependency-is-not-met) | | `E0277` the trait bound `f64: Eq` is not satisfied | An ordinary Rust bound on a wired type | [When the missing bound is an ordinary Rust trait](#when-the-missing-bound-is-an-ordinary-rust-trait) | +| `E0277` … `IsProviderFor` is not satisfied | A provider impl written without its macro | [A provider impl written without its macro](#a-provider-impl-written-without-its-macro) | | `E0277` … `PathCons<…>: SomeNamespace<…>` is not satisfied | A namespace path nothing binds | [Nothing is wired there](#nothing-is-wired-there) | | `E0277` the size for values of type `[u8]` cannot be known | A field-type shorthand lowered to an unsized type | [A field-type shorthand without a rule](#a-field-type-shorthand-without-a-rule) | | `E0271` type mismatch resolving `<… as …>::Assoc == …` | A type pinned one way and wired another | [When two decisions disagree about a type](#when-two-decisions-disagree-about-a-type) | | `E0119` conflicting implementations | Two wiring entries claim one key | [The wiring itself does not compile](#the-wiring-itself-does-not-compile) | +| `E0425` / `E0782` a wiring name resolves to nothing | A component or provider named wrongly in a table | [A wiring name that resolves to nothing](#a-wiring-name-that-resolves-to-nothing) | | `E0428` the name … is defined multiple times | A generated name declared twice | [Two entries claim one key](#two-entries-claim-one-key) | | `E0275` overflow evaluating the requirement | A wiring or inheritance cycle | [A lookup that never terminates](#a-lookup-that-never-terminates) | | `E0210` / `E0117` [orphan rule](/docs/reference/glossary#orphan-rule) | Registering into a namespace you do not own | [Registering into a namespace you do not own](#registering-into-a-namespace-you-do-not-own) | @@ -387,6 +389,30 @@ future crate could add, not a second problem. A duplicate **name** of your own, rather than a duplicate key, is an `E0428` instead, and passes through uncoded, because it already points precisely at both definitions. +### A wiring name that resolves to nothing + +A table entry names a component marker and a provider type, and both must exist where the table is +written. A consumer trait in the key, a component that is not imported, a key guessed from a trait's +name, a provider never declared, or a type in an `@`-path that does not exist all fail the same way: +the compiler reports the name itself, with suggestions that do not fit wiring. + +```text +error[E0782]: [CGP-E040] the wiring key `CanGreet` is a consumer trait, but a key names a component + --> src/main.rs:41:9 + | +41 | CanGreet: GreetHello, + | ^^^^^^^^ + | + = help: name its component instead: `GreeterComponent` +``` + +The fix is to name the item the table needs: the component marker (`GreeterComponent`), the import +for a component from another module, the provider struct declared with `new`, or the type in the +path. The tool words each shape with its own code: `[CGP-E040]` for a consumer trait as a key, +`[CGP-E041]` for a component not in scope, `[CGP-E042]` for a key guessed from a trait's name, +`[CGP-E043]` for an undeclared provider, and `[CGP-E044]` for an undeclared type in a path. A +`#[cgp_impl]` provider never declared is `[CGP-E038]`. + ### Joining more than one namespace A context can forward through exactly one namespace. Two `namespace` headers (or one header plus a @@ -667,6 +693,24 @@ and `[CGP-E033]` is `#[cgp_impl]` applied to a trait that is not a component at all, where the fix is to make it one, or to write a plain `impl`. +### A provider impl written without its macro + +A provider trait's `IsProviderFor` supertrait is written by `#[cgp_provider]` or `#[cgp_impl]`. A +plain `impl` of the provider trait has no marker impl, so the compiler rejects it on the supertrait: + +```text +error[E0277]: [CGP-E039] the impl of `Greeter` for `GreetHello` is written without `#[cgp_provider]` + --> src/main.rs:24:36 + | +24 | impl Greeter for GreetHello { + | ^^^^^^^^^^ + | + = help: add `#[cgp_provider]` to the impl of `Greeter`, or write the provider with `#[cgp_impl]` +``` + +Add the attribute, or write the provider with `#[cgp_impl]`, which lowers to it. The raw error lists +the types that do implement `IsProviderFor`, none of which is the fix. + ## The `[CGP-Exxx]` codes A code tags one class of CGP mistake in the output of `cargo cgp check`. The compiler's own code is From 2c32d32870e901b0e5dc6347c07e49b28981311a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:46:35 +0100 Subject: [PATCH 257/516] Cover the extensible-data class The page now explains a bound on a generated partial type, with an index row and the E050 to E059 range. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/errors.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/reference/errors.md b/docs/reference/errors.md index f7763735..8c855675 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -72,6 +72,7 @@ Match the compiler's code and the shape of the message. | `E0433` cannot find type | A name the generated code cannot see | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | | `E0576` cannot find associated type … in trait | A `#[use_type]` import with a wrong name | [An imported type that does not exist](#an-imported-type-that-does-not-exist) | | `E0404` expected trait, found type parameter | An [abstract type](/docs/reference/glossary#abstract-type) named after its own bound | [A name the generated code cannot see](#a-name-the-generated-code-cannot-see) | +| `E0277` / `E0271` a bound on a generated partial type | A builder, extractor, or cast in a state its value does not allow | [Extensible data](#extensible-data) | ## A dependency is not met @@ -711,6 +712,32 @@ error[E0277]: [CGP-E039] the impl of `Greeter` for `GreetHello` is written witho Add the attribute, or write the provider with `#[cgp_impl]`, which lowers to it. The raw error lists the types that do implement `IsProviderFor`, none of which is the fix. +## Extensible data + +A builder, extractor, or cast tracks each field's or variant's state in a type, so the compiler +rejects an operation applied to a value whose state does not allow it, or to a type without the +data derive. A builder field set twice is the clearest case: + +```text +error[E0271]: [CGP-E050] field `first_name` of `Person` is already set + --> src/main.rs:24:22 + | +24 | .build_field(PhantomData::, "Bob".to_owned()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: root cause: [CGP-E118] field `first_name` of `Person` is already set + this is required through the dependency chain: + [CGP-E104] trait impl `BuildField` for the builder of `Person` with `first_name` set + └─ [CGP-E118] field `first_name` of `Person` is already set +``` + +The headline names the field and its state, and the chain names the operation that needed the other +state. **The fix** depends on the operation: set each field once, finalize only once every field is +set, rule out a variant once, or add the derive the type lacks. The same family includes a field the +struct does not declare, a variant extracted twice, an incomplete match, and a cast between shapes +whose variants do not agree. The tool words the operation under `[CGP-E050]` through `[CGP-E059]`, +and the leaf names the state, such as `[CGP-E118]` for a field already set. + ## The `[CGP-Exxx]` codes A code tags one class of CGP mistake in the output of `cargo cgp check`. The compiler's own code is From 0df5faed1d7299d53bd81a998f1f7f963b78d718 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 18:56:06 +0100 Subject: [PATCH 258/516] Drop the reserved E059 from the code range The extensible-data family is the E050 entry with its E118-to-E126 leaves; E059 has no entry. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/errors.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 8c855675..10f21e72 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -735,8 +735,8 @@ The headline names the field and its state, and the chain names the operation th state. **The fix** depends on the operation: set each field once, finalize only once every field is set, rule out a variant once, or add the derive the type lacks. The same family includes a field the struct does not declare, a variant extracted twice, an incomplete match, and a cast between shapes -whose variants do not agree. The tool words the operation under `[CGP-E050]` through `[CGP-E059]`, -and the leaf names the state, such as `[CGP-E118]` for a field already set. +whose variants do not agree. The tool words the operation as `[CGP-E050]`, and the leaf names the +state, such as `[CGP-E118]` for a field already set. ## The `[CGP-Exxx]` codes From 099068c45a7a3606e646c29e1703ddf9c9f9ab02 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:12:03 +0100 Subject: [PATCH 259/516] Name the project on the component macro pages The three pages' Overviews now name Context-Generic Programming and relate the tag line to what the macro does. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/macros/cgp_component.md | 6 ++++-- docs/reference/macros/cgp_impl.md | 4 +++- docs/reference/macros/cgp_provider.md | 4 +++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 1e2a4d95..4e99b47c 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -12,8 +12,10 @@ target, and the key that wires them together. ## Overview -`#[cgp_component]` turns an ordinary Rust trait into a component, so that each type using the trait -chooses which implementation it gets. Applying it takes nothing away. The trait you wrote keeps +`#[cgp_component]` turns an ordinary Rust trait into a component in +[Context-Generic Programming (CGP)](/docs/), so that each type using the trait chooses which +implementation it gets. CGP enables pluggable trait implementations in Rust, and this macro is where +a trait becomes one. Applying it takes nothing away. The trait you wrote keeps working exactly as it did, now under the name CGP calls the **consumer trait**, and every call site that already uses it keeps compiling unchanged. The macro adds a matching **provider trait** for implementations to target, a small marker type called the **component** that names the trait for diff --git a/docs/reference/macros/cgp_impl.md b/docs/reference/macros/cgp_impl.md index 68a50e66..202bcb62 100644 --- a/docs/reference/macros/cgp_impl.md +++ b/docs/reference/macros/cgp_impl.md @@ -12,7 +12,9 @@ already know. ## Overview -A [provider trait](./cgp_component.md) has a different shape from the trait it came from. The +In [Context-Generic Programming (CGP)](/docs/), a [provider trait](./cgp_component.md) has a +different shape from the trait it came from. CGP enables pluggable trait implementations in Rust, and +`#[cgp_impl]` is how you write one in the shape you already know. The original `Self` has moved into an explicit leading type parameter, the implementation targets a small marker type rather than the type the operation acts on, and the method receiver is a plain parameter. Written by hand, with `HasDimensions` standing for a trait that supplies `width()` and `height()`, it diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index b45b9420..b8e188b7 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -12,7 +12,9 @@ declaring the provider struct. ## Overview -A provider trait is not shaped like the trait it came from. [`#[cgp_component]`](./cgp_component.md) +In [Context-Generic Programming (CGP)](/docs/), a provider trait is not shaped like the trait it +came from. CGP enables pluggable trait implementations in Rust, and this macro writes one in the +shape the sugar desugars to. [`#[cgp_component]`](./cgp_component.md) moves the original `Self` into an explicit leading type parameter for the **context**. The context is the type the method runs on, and it supplies the values it needs as its own fields. An implementation targets a small named struct instead. Written out, a provider looks like this: From 0646cab7c3ce71b80f2e620265c2a6748e9ace46 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:15:08 +0100 Subject: [PATCH 260/516] Name the project on three more macro pages The cgp_fn, async_trait, and blanket_trait Overviews now name Context-Generic Programming and link the Introduction. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/macros/async_trait.md | 4 ++-- docs/reference/macros/blanket_trait.md | 3 ++- docs/reference/macros/cgp_fn.md | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/reference/macros/async_trait.md b/docs/reference/macros/async_trait.md index 4af19cac..908e379f 100644 --- a/docs/reference/macros/async_trait.md +++ b/docs/reference/macros/async_trait.md @@ -11,8 +11,8 @@ Rewrite a trait's `async fn` declarations into the lint-clean `-> impl Future` f ## Overview -Writing a bare `async fn` inside a public trait compiles on stable Rust, and the compiler warns -about it. The `async_fn_in_trait` lint fires because the future such a method returns is *opaque*: a +In [Context-Generic Programming (CGP)](/docs/), writing a bare `async fn` inside a public trait +compiles on stable Rust, and the compiler warns about it. The `async_fn_in_trait` lint fires because the future such a method returns is *opaque*: a caller working through the trait cannot name it, so they cannot require anything of it, most importantly that it is `Send`. The hand-written way to silence the lint is to declare the method as a future-returning function instead, which is correct and obscures the intent: diff --git a/docs/reference/macros/blanket_trait.md b/docs/reference/macros/blanket_trait.md index 425937a0..330a4003 100644 --- a/docs/reference/macros/blanket_trait.md +++ b/docs/reference/macros/blanket_trait.md @@ -11,7 +11,8 @@ Generate a blanket impl from a trait with default methods and [supertrait](/docs ## Overview -The pattern CGP is built on is an **extension trait**: a trait with a clean interface whose +The pattern [Context-Generic Programming (CGP)](/docs/) is built on is an **extension trait**: a +trait with a clean interface whose [blanket implementation](https://blog.implrust.com/posts/2025/09/blanket-implementation-in-rust/) carries the real requirements in its `where` clause. A trait declared `FooBar: Foo + Bar` with a default `foo_bar` method exposes only `foo_bar` to callers, while the `Foo + Bar` requirements live on the impl. So any type diff --git a/docs/reference/macros/cgp_fn.md b/docs/reference/macros/cgp_fn.md index 7631968d..ad311d80 100644 --- a/docs/reference/macros/cgp_fn.md +++ b/docs/reference/macros/cgp_fn.md @@ -11,8 +11,8 @@ Define a trait with a single [blanket implementation](/docs/reference/glossary#b ## Overview -`#[cgp_fn]` is the simplest CGP construct that does anything useful. You write a plain function and -mark the values it needs from the **context**. The context is the type the method runs on, +`#[cgp_fn]` is the simplest construct in [Context-Generic Programming (CGP)](/docs/) that does +anything useful. You write a plain function and mark the values it needs from the **context**. The context is the type the method runs on, and it supplies those values as its own fields. The macro turns the function into a trait that every type with those fields gets automatically: From 23d0b890474b11962065f4fb817b94383e7b0540 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:18:01 +0100 Subject: [PATCH 261/516] Name the project and fix the getter conversion The type and getter pages now name Context-Generic Programming, and the getter pages use AsRef::as_ref for the &str form. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/macros/cgp_auto_getter.md | 11 ++++++----- docs/reference/macros/cgp_getter.md | 11 ++++++----- docs/reference/macros/cgp_type.md | 3 ++- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 4a1b5ada..61d94437 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -11,7 +11,8 @@ Define a getter as a blanket impl over `HasField`, keyed by the method name. ## Overview -`#[cgp_auto_getter]` publishes a context field as a named, reusable accessor. You write a trait of getter +In [Context-Generic Programming (CGP)](/docs/), `#[cgp_auto_getter]` publishes a context field as a +named, reusable accessor. You write a trait of getter methods, and the macro implements it for every **context** that happens to carry fields of the matching names. The context is the type the method runs on, and it supplies the values it needs as its own fields. For example: @@ -72,7 +73,7 @@ natural. The field's type is inferred from what you return: | The method returns | The field's type | How it is read | |---|---|---| | `&T` | `T` | by reference, no conversion | -| `&str` | `String` | `.as_str()` | +| `&str` | `String` | `.as_ref()` | | `&[T]` | any `'static` type implementing `AsRef<[T]>` | `.as_ref()` | | `Option<&T>` | `Option` | `.as_ref()` | | `Option<&str>` | `Option` | `.as_deref()` | @@ -80,7 +81,7 @@ natural. The field's type is inferred from what you return: | An owned type (`f64`, `String`, a tuple, an array) | the same type | by reference, then `.clone()` | A `&mut self` receiver reads mutably, through `HasFieldMut`, and each reference form has a mutable -mirror: `&mut T`, `&mut str` from a `String` via `.as_mut_str()`, `&mut [T]` through `AsMut<[T]>`, +mirror: `&mut T`, `&mut str` from a `String` via `.as_mut()`, `&mut [T]` through `AsMut<[T]>`, `Option<&mut T>` via `.as_mut()`, and `Option<&mut str>` via `.as_deref_mut()`. A `&mut` anywhere in the return type needs that receiver, and under `&self` the macro rejects it with *&mut self is required for mutable field reference*. @@ -290,7 +291,7 @@ where __Context__: HasField, { fn name(&self) -> &str { - self.get_field(PhantomData::).as_str() + self.get_field(PhantomData::).as_ref() } } ``` @@ -299,7 +300,7 @@ A few things to recognize. The context parameter is literally `__Context__`, a r cannot collide with one of yours. [`Symbol!("name")`](./symbol.md) is a [type-level string](/docs/reference/glossary#type-level-string) standing for the field name. The compiler prints its expanded `Symbol<4, Chars<'n', …>>` form in errors, and `cargo cgp expand` resugars it back to this. And because the return type is `&str`, the bound asks for a -`String` field and the body appends `.as_str()`, which is the conversion table in action. +`String` field and the body appends `.as_ref()`, which is the conversion table in action. A trait with several methods produces one predicate and one body per field, all in the same impl: diff --git a/docs/reference/macros/cgp_getter.md b/docs/reference/macros/cgp_getter.md index 13df12b5..0f5089bb 100644 --- a/docs/reference/macros/cgp_getter.md +++ b/docs/reference/macros/cgp_getter.md @@ -11,7 +11,8 @@ Define a getter as a full component, so the field it reads is chosen by wiring r ## Overview -[`#[cgp_auto_getter]`](./cgp_auto_getter.md) ties a getter to a field of the same name: declare +In [Context-Generic Programming (CGP)](/docs/), [`#[cgp_auto_getter]`](./cgp_auto_getter.md) ties a +getter to a field of the same name: declare `fn name(&self) -> &str` and every context with a `name` field satisfies it. That is the right tradeoff almost always, and it has one hard limitation: a context that stores the value under a different name cannot use the getter at all. @@ -222,7 +223,7 @@ where __Context__: HasField<__Tag__, Value = String>, { fn name(__context__: &__Context__) -> &str { - __context__.get_field(PhantomData::<__Tag__>).as_str() + __context__.get_field(PhantomData::<__Tag__>).as_ref() } } ``` @@ -231,7 +232,7 @@ where [`#[cgp_auto_getter]`](./cgp_auto_getter.md), whose blanket impl hard-codes the tag to `Symbol!("name")`. Here the tag is whatever the wiring supplies, so `UseField` reads `first_name`. The `&str` shorthand behaves identically in both: the bound asks for a `String` and the -body appends `.as_str()`. +body appends `.as_ref()`. Next is the `UseFields` impl, which is the auto-getter's behaviour expressed as a provider, with the tag fixed to each method's own name: @@ -242,7 +243,7 @@ where __Context__: HasField, { fn name(__context__: &__Context__) -> &str { - __context__.get_field(PhantomData::).as_str() + __context__.get_field(PhantomData::).as_ref() } } ``` @@ -256,7 +257,7 @@ where __Provider__: FieldGetter<__Context__, NameGetterComponent, Value = String>, { fn name(__context__: &__Context__) -> &str { - __Provider__::get_field(__context__, PhantomData::).as_str() + __Provider__::get_field(__context__, PhantomData::).as_ref() } } ``` diff --git a/docs/reference/macros/cgp_type.md b/docs/reference/macros/cgp_type.md index fc02da98..cb7c9975 100644 --- a/docs/reference/macros/cgp_type.md +++ b/docs/reference/macros/cgp_type.md @@ -11,7 +11,8 @@ Define an abstract-type component, whose concrete type each context chooses for ## Overview -Generic code often has to name a type it should not choose. A fallible operation returns *some* error, a +In [Context-Generic Programming (CGP)](/docs/), generic code often has to name a type it should not +choose. A fallible operation returns *some* error, a geometry routine computes in *some* scalar, a storage layer holds *some* connection handle. Code written once for many applications cannot decide which. Rust's answer is an [associated type](https://doc.rust-lang.org/reference/items/associated-items.html): declare From 6aa75f17637f28e530d2fb5c3fe749651325b765 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:18:56 +0100 Subject: [PATCH 262/516] Name the project on the computation macro pages The cgp_computer, cgp_producer, and cgp_auto_dispatch Overviews now name Context-Generic Programming and link the Introduction. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/macros/cgp_auto_dispatch.md | 5 +++-- docs/reference/macros/cgp_computer.md | 5 +++-- docs/reference/macros/cgp_producer.md | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/reference/macros/cgp_auto_dispatch.md b/docs/reference/macros/cgp_auto_dispatch.md index fc610444..0240bdaf 100644 --- a/docs/reference/macros/cgp_auto_dispatch.md +++ b/docs/reference/macros/cgp_auto_dispatch.md @@ -11,8 +11,9 @@ Generate a handler that dispatches over an extensible-data input from a per-type ## Overview -`#[cgp_auto_dispatch]` answers a common shape: **you have a trait with one implementation per type, and you -want it to work on an enum of those types too.** +In [Context-Generic Programming (CGP)](/docs/), `#[cgp_auto_dispatch]` answers a common shape: **you +have a trait with one implementation per type, and you want it to work on an enum of those types +too.** ```rust #[cgp_auto_dispatch] diff --git a/docs/reference/macros/cgp_computer.md b/docs/reference/macros/cgp_computer.md index 5452571a..da3cb88b 100644 --- a/docs/reference/macros/cgp_computer.md +++ b/docs/reference/macros/cgp_computer.md @@ -11,8 +11,9 @@ Define a `Computer` provider from a plain function. ## Overview -CGP models computation as a family of components varying along three axes: synchronous or async, fallible -or not, taking an input or not. A provider in that family is a struct with one or more impls threading a +In [Context-Generic Programming (CGP)](/docs/), computation is modeled as a family of components +varying along three axes: synchronous or async, fallible or not, taking an input or not. CGP enables +pluggable trait implementations in Rust, and this macro builds one from a plain function. A provider in that family is a struct with one or more impls threading a **context** (the type the method runs on, which supplies the values it needs as its fields), a phantom `Code` tag, and an `Input`. Written by hand for a computation as small as "add two numbers", that is far more code than the task needs. diff --git a/docs/reference/macros/cgp_producer.md b/docs/reference/macros/cgp_producer.md index 6dd687b1..e21e56d6 100644 --- a/docs/reference/macros/cgp_producer.md +++ b/docs/reference/macros/cgp_producer.md @@ -11,8 +11,9 @@ Define a `Producer` provider from an input-free function. ## Overview -`#[cgp_producer]` is for the degenerate member of the handler family: a computation that takes no input and -yields a value from nothing. A constant, a default, a seed for a pipeline. It is the input-free sibling of +In [Context-Generic Programming (CGP)](/docs/), `#[cgp_producer]` is for the degenerate member of the +handler family: a computation that takes no input and yields a value from nothing. CGP enables +pluggable trait implementations in Rust, and this macro builds one from an input-free function. A constant, a default, a seed for a pipeline. It is the input-free sibling of [`#[cgp_computer]`](./cgp_computer.md), and like that macro it lets you write a plain function and have the provider synthesized for you: From dcc8abd05c1b7049b4e90c68f565e7bd1d974e3b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:24:50 +0100 Subject: [PATCH 263/516] Name the project on the wiring macro pages The delegate_components, check_components, delegate_and_check_components, and cgp_namespace Overviews now name Context-Generic Programming, and the three wiring pages relate the tag line. The cgp_namespace expansion shows the raw PathCons list the macro emits. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/macros/cgp_namespace.md | 11 +++++++---- docs/reference/macros/check_components.md | 2 +- .../reference/macros/delegate_and_check_components.md | 7 +++++-- docs/reference/macros/delegate_components.md | 9 +++++---- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index 6193ddd6..51e211b5 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -11,12 +11,15 @@ Define a reusable, inheritable wiring table that many contexts can join. ## Overview -With [`delegate_components!`](./delegate_components.md) alone, every **context** (the type the method -runs on, which supplies the values it needs as its fields) spells out its own wiring entry by entry. +In [Context-Generic Programming (CGP)](/docs/), every **context** (the type the method runs on, +which supplies the values it needs as its fields) spells out its own wiring entry by entry with +[`delegate_components!`](./delegate_components.md) alone. Two contexts that should share the same providers repeat the same lines, and a table grows with the number of components until the wiring is the largest thing in the file. -`cgp_namespace!` lifts a table out of any one context and gives it a name, so other contexts can adopt it: +CGP enables pluggable trait implementations in Rust, and a namespace is where a group of those +choices gets a name other contexts can adopt. `cgp_namespace!` lifts a table out of any one context +and gives it that name: ```rust cgp_namespace! { @@ -296,7 +299,7 @@ Each `=>` entry becomes an impl of that trait **for the key**, whose `Delegate` ```rust impl<__Table__> MyNamespace<__Table__> for FooProviderComponent { - type Delegate = RedirectLookup<__Table__, Path!(@MyFooComponent)>; + type Delegate = RedirectLookup<__Table__, PathCons>; } ``` diff --git a/docs/reference/macros/check_components.md b/docs/reference/macros/check_components.md index 14adab95..a2d1b6cd 100644 --- a/docs/reference/macros/check_components.md +++ b/docs/reference/macros/check_components.md @@ -11,7 +11,7 @@ Assert at compile time that a context can actually use each component it wires. ## Overview -**CGP's wiring is lazy, and this macro is the answer to that.** The **context** is the type the +**In [Context-Generic Programming (CGP)](/docs/), wiring is lazy, and this macro is the answer to that.** The **context** is the type the method runs on, and it supplies the values it needs as its own fields. When [`delegate_components!`](./delegate_components.md) records that a context delegates a component to some provider, nothing checks that the provider can do the job. The entry is stored as a type-level fact and diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index 786948c0..9d8c29a7 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -11,14 +11,17 @@ Wire a context and check that wiring in one macro. ## Overview -CGP's wiring is [lazy](./delegate_components.md#common-mistakes): a +In [Context-Generic Programming (CGP)](/docs/), wiring is +[lazy](./delegate_components.md#common-mistakes): a [`delegate_components!`](./delegate_components.md) entry is accepted without verifying that the provider it names can actually satisfy the component, so a **context** (the type the method runs on, which supplies the values it needs as its own fields) can compile while being broken. The fix is a [`check_components!`](./check_components.md) block, and the problem with the fix is that keeping it in step with the wiring is manual. Add a delegation, remember to add its check. -`delegate_and_check_components!` removes that bookkeeping by deriving the checks from the delegations: +CGP enables pluggable trait implementations in Rust, and this macro is where a context picks them +and proves the choice in one step. It removes the bookkeeping by deriving the checks from the +delegations: ```rust delegate_and_check_components! { diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 03fb9d27..3baac4c8 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -11,11 +11,12 @@ Build a context's wiring table, naming the provider that implements each of its ## Overview -[`#[cgp_component]`](./cgp_component.md) separates the trait callers use from the trait -implementations target, which leaves one question open: for a given type, *which* implementation -supplies the behavior? `delegate_components!` answers it. You give it a type and a list of entries, +In [Context-Generic Programming (CGP)](/docs/), [`#[cgp_component]`](./cgp_component.md) separates +the trait callers use from the trait implementations target, which leaves one question open: for a +given type, *which* implementation supplies the behavior? `delegate_components!` answers it. You give it a type and a list of entries, the component name as the key and the chosen provider as the value, and it records that choice on the -type. +type. CGP enables pluggable trait implementations in Rust, and `delegate_components!` is where a +context picks them. ```rust delegate_components! { From b3b69525cc3dfdf59ae1f28fdea8aa5e1f559e3c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:25:44 +0100 Subject: [PATCH 264/516] Name the project on the type-level macro pages The Symbol!, Product!, Sum!, and Path! Overviews now name Context-Generic Programming. The knowledge-base Sum! and Path! documents gained the missing value-level and expansion notes. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/macros/path.md | 3 ++- docs/reference/macros/product.md | 3 ++- docs/reference/macros/sum.md | 3 ++- docs/reference/macros/symbol.md | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/reference/macros/path.md b/docs/reference/macros/path.md index 69b88cfd..0f3c92ff 100644 --- a/docs/reference/macros/path.md +++ b/docs/reference/macros/path.md @@ -11,7 +11,8 @@ A type-level path, used by namespaces and redirected lookups. ## Overview -`Path!(@a.B.c)` builds a type-level **route**: a list of segments naming a way through nested wiring tables. +In [Context-Generic Programming (CGP)](/docs/), `Path!(@a.B.c)` builds a type-level **route**: a list +of segments naming a way through nested wiring tables. Read left to right, each segment narrows a lookup one step: through a namespace, through a prefix, down to a component key. diff --git a/docs/reference/macros/product.md b/docs/reference/macros/product.md index bbcc8a5a..ec074ca3 100644 --- a/docs/reference/macros/product.md +++ b/docs/reference/macros/product.md @@ -11,7 +11,8 @@ A type-level list and its value-level counterpart. ## Overview -`Product![A, B, C]` represents an ordered sequence of types as a single type. CGP uses it to describe the +In [Context-Generic Programming (CGP)](/docs/), `Product![A, B, C]` represents an ordered sequence of +types as a single type. CGP uses it to describe the [*shape*](/docs/reference/glossary#shape) of a struct: the list of its fields, in order, as one type that generic code can reason about. It is sometimes called an anonymous product type, because like a tuple it holds several things at once. The diff --git a/docs/reference/macros/sum.md b/docs/reference/macros/sum.md index b296dbfa..68fcbee7 100644 --- a/docs/reference/macros/sum.md +++ b/docs/reference/macros/sum.md @@ -11,7 +11,8 @@ A type-level sum, the dual of `Product!`. ## Overview -`Sum![A, B, C]` represents a *choice* among several types as a single type. CGP uses it to describe the [shape](/docs/reference/glossary#shape) +In [Context-Generic Programming (CGP)](/docs/), `Sum![A, B, C]` represents a *choice* among several +types as a single type. CGP uses it to describe the [shape](/docs/reference/glossary#shape) of an **enum**, the list of its variants, the way [`Product!`](./product.md) describes the fields of a struct. diff --git a/docs/reference/macros/symbol.md b/docs/reference/macros/symbol.md index 99f2b472..951f49d3 100644 --- a/docs/reference/macros/symbol.md +++ b/docs/reference/macros/symbol.md @@ -11,7 +11,7 @@ A [type-level string](/docs/reference/glossary#type-level-string), used as a fie ## Overview -CGP needs field *names* to be types. Reading a field goes through +In [Context-Generic Programming (CGP)](/docs/), field *names* need to be types. Reading a field goes through [`HasField`](../traits/field-access/has_field.md), where `Tag` identifies which field is meant. So to look up a field called `name`, something has to stand in for the string `"name"` at the type level. From 8b495ccc6e6edd523456d21a4e6f54ec28c831e6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:26:03 +0100 Subject: [PATCH 265/516] Name the project on the shape macro pages The Struct! and Enum! Overviews now name Context-Generic Programming. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/macros/enum.md | 3 ++- docs/reference/macros/struct.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/reference/macros/enum.md b/docs/reference/macros/enum.md index e85414ad..75595e5d 100644 --- a/docs/reference/macros/enum.md +++ b/docs/reference/macros/enum.md @@ -11,7 +11,8 @@ The type-level shape of an enum, written as the body of an enum declaration. ## Overview -Generic code over enums works on an enum's **shape**: one type that lists every variant by name, +In [Context-Generic Programming (CGP)](/docs/), generic code over enums works on an enum's +**shape**: one type that lists every variant by name, which [`#[derive(HasFields)]`](../derives/derive_has_fields.md) generates for an enum as its `Fields` type. Written out by hand, that shape is a [`Sum!`](./sum.md) of [`Field`](../types/field.md) entries that repeats each variant name as a diff --git a/docs/reference/macros/struct.md b/docs/reference/macros/struct.md index b355ca37..41a966c8 100644 --- a/docs/reference/macros/struct.md +++ b/docs/reference/macros/struct.md @@ -11,7 +11,8 @@ The type-level shape of a struct, written as the body of a struct declaration. ## Overview -Generic code over records works on a struct's **shape**: one type that lists every field by name, +In [Context-Generic Programming (CGP)](/docs/), generic code over records works on a struct's +**shape**: one type that lists every field by name, which [`#[derive(HasFields)]`](../derives/derive_has_fields.md) generates for a struct as its `Fields` type. Written out by hand, that shape is a [`Product!`](./product.md) of [`Field`](../types/field.md) entries that repeats each field name as a From 086f9fe8cafcccfe103a32114d47fdfd2dafbde9 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:30:04 +0100 Subject: [PATCH 266/516] Name the project on the attribute pages The ten attribute pages and their index now name Context-Generic Programming, and the four that choose an implementation relate the tag line. The implicit page's access table now matches the code: &str reads any AsRef field, and the mutable forms read AsMut. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/attributes/default_impl.md | 6 +++-- docs/reference/attributes/derive_delegate.md | 4 +++- docs/reference/attributes/extend.md | 5 ++--- docs/reference/attributes/extend_where.md | 5 +++-- docs/reference/attributes/impl_generics.md | 5 +++-- docs/reference/attributes/implicit.md | 23 ++++++++++---------- docs/reference/attributes/index.md | 3 ++- docs/reference/attributes/prefix.md | 6 +++-- docs/reference/attributes/use_provider.md | 7 ++++-- docs/reference/attributes/use_type.md | 3 ++- docs/reference/attributes/uses.md | 5 +++-- 11 files changed, 43 insertions(+), 29 deletions(-) diff --git a/docs/reference/attributes/default_impl.md b/docs/reference/attributes/default_impl.md index ffba56b2..ed5bb640 100644 --- a/docs/reference/attributes/default_impl.md +++ b/docs/reference/attributes/default_impl.md @@ -11,8 +11,10 @@ Register a provider as a namespace's default for a key. ## Overview -`#[default_impl(...)]` lets a *provider* register itself as a [namespace](/docs/concepts/namespaces)'s -default for a key, at the point where the provider is defined. A namespace is a reusable table of default +In [Context-Generic Programming (CGP)](/docs/), `#[default_impl(...)]` lets a *provider* register +itself as a [namespace](/docs/concepts/namespaces)'s default for a key, at the point where the +provider is defined. CGP enables pluggable trait implementations in Rust, and this attribute is where +a provider declares itself the default choice for a key. A namespace is a reusable table of default wirings that a **context** can opt into and then complete with the entries it leaves open. (The context is the type the method runs on.) Ordinarily you write a namespace's entries in its own body. This attribute moves one entry onto the provider: diff --git a/docs/reference/attributes/derive_delegate.md b/docs/reference/attributes/derive_delegate.md index 6c694b5d..6ba23d5b 100644 --- a/docs/reference/attributes/derive_delegate.md +++ b/docs/reference/attributes/derive_delegate.md @@ -28,7 +28,9 @@ attribute once `open` is shown to cover every dispatch case. ## Overview -`#[derive_delegate]` generates the dispatcher for a component that is generic over a type parameter. +In [Context-Generic Programming (CGP)](/docs/), `#[derive_delegate]` generates the dispatcher for a +component that is generic over a type parameter. CGP enables pluggable trait implementations in Rust, +and this attribute is the older way to choose one per type. Such a component usually wants a different implementation per value of the parameter: `Rectangle` handled one way, `Circle` another. Something has to look at the type and pick. Written by hand, that dispatcher is an implementation of the provider trait that reads a lookup table, finds the entry for the diff --git a/docs/reference/attributes/extend.md b/docs/reference/attributes/extend.md index 7a88b00d..d9cd27b5 100644 --- a/docs/reference/attributes/extend.md +++ b/docs/reference/attributes/extend.md @@ -11,9 +11,8 @@ Add a trait as a [supertrait](/docs/reference/glossary#supertrait) of a generate ## Overview -`#[extend]` declares that a trait is part of what a generated trait *guarantees*, rather than -something its -implementation happens to need. Where [`#[uses]`](uses.md) adds a private requirement, `#[extend]` adds a +In [Context-Generic Programming (CGP)](/docs/), `#[extend]` declares that a trait is part of what a +generated trait *guarantees*, rather than something its implementation happens to need. Where [`#[uses]`](uses.md) adds a private requirement, `#[extend]` adds a supertrait. Every **context** implementing the trait, meaning every type the method runs on, must also satisfy it, and every caller may rely on it. diff --git a/docs/reference/attributes/extend_where.md b/docs/reference/attributes/extend_where.md index 4b0ce65c..c75fae98 100644 --- a/docs/reference/attributes/extend_where.md +++ b/docs/reference/attributes/extend_where.md @@ -11,8 +11,9 @@ Add `where` predicates to a generated trait's own definition, not only to its im ## Overview -`#[extend_where]` moves a `where` predicate onto the trait that a [`#[cgp_fn]`](../macros/cgp_fn.md) -generates, so the predicate becomes a condition of naming the trait at all. By default, `#[cgp_fn]` +In [Context-Generic Programming (CGP)](/docs/), `#[extend_where]` moves a `where` predicate onto +the trait that a [`#[cgp_fn]`](../macros/cgp_fn.md) generates, so the predicate becomes a condition of +naming the trait at all. By default, `#[cgp_fn]` treats the `where` clause you write on the function as an implementation detail: the bounds land on the generated implementation and never appear on the generated trait. That default keeps a trait's requirements private to its implementation, and it is almost always right. diff --git a/docs/reference/attributes/impl_generics.md b/docs/reference/attributes/impl_generics.md index 8d9fc699..a34ebcac 100644 --- a/docs/reference/attributes/impl_generics.md +++ b/docs/reference/attributes/impl_generics.md @@ -12,8 +12,9 @@ through a field and callers never name it. ## Overview -`#[impl_generics(...)]` declares a generic parameter on the implementation that a -[`#[cgp_fn]`](../macros/cgp_fn.md) generates, and keeps it off the generated trait. By default, +In [Context-Generic Programming (CGP)](/docs/), `#[impl_generics(...)]` declares a generic parameter +on the implementation that a [`#[cgp_fn]`](../macros/cgp_fn.md) generates, and keeps it off the +generated trait. By default, `#[cgp_fn]` puts every generic parameter you write on the function onto both the trait and its implementation. That is right for a type the caller chooses. But a body often needs a type that nobody chooses: a database handle, a name that only has to be printable, a scalar read from a field. The diff --git a/docs/reference/attributes/implicit.md b/docs/reference/attributes/implicit.md index e0b9ca46..6a379681 100644 --- a/docs/reference/attributes/implicit.md +++ b/docs/reference/attributes/implicit.md @@ -11,8 +11,8 @@ Source a function argument from a same-named field on the context. ## Overview -`#[implicit]` lets a CGP construct read a field value from a generic **context** by naming the field -like an ordinary function argument. The context is the type the method runs on, which supplies the +In [Context-Generic Programming (CGP)](/docs/), `#[implicit]` lets a construct read a field value +from a generic **context** by naming the field like an ordinary function argument. The context is the type the method runs on, which supplies the values it needs as its fields, and the macro hides the implicit argument from the public signature. ```rust @@ -71,20 +71,20 @@ that type. The table below lists every case: |---|---|---| | An owned type (`f64`, `String`, a tuple, an array) | the same type | by reference, then `.clone()` | | `&T` | `T` | by reference, no conversion | -| `&str` | `String` | `.as_str()` | +| `&str` | any `'static` value implementing `AsRef` | `.as_ref()` | | `&[T]` | anything `AsRef<[T]>` | `.as_ref()` | | `Option<&T>` | `Option` | `.as_ref()` | -| `Option<&str>` | `Option` | `.as_deref()` | +| `Option<&str>` | any `'static` `Option` whose `U` implements `AsRef` | `.option_as_ref()` | | `&mut T` | `T` | mutably, no conversion | -| `&mut str` | `String` | `.as_mut_str()` | +| `&mut str` | a field implementing `AsMut` | `.as_mut()` | | `&mut [T]` | anything `AsMut<[T]>` | `.as_mut()` | | `Option<&mut T>` | `Option` | `.as_mut()` | -| `Option<&mut str>` | `Option` | `.as_deref_mut()` | +| `Option<&mut str>` | an `Option` whose `U` derefs mutably to `str` | `.as_deref_mut()` | | [`MRef<'a, T>`](../types/mref.md) | `T` | by reference, wrapped as `MRef::Ref(…)` | The rows for `&str`, for an owned type, and for `MRef` are the ones most often misread. `&str` is the -case most often wanted and least obvious: the field is a `String`, and the argument borrows from it, so -a context never has to store a `&str`. An owned argument *clones* the value. That is cheap for an +case most often wanted and least obvious: the field can be a `String`, a `Cow`, or a `Box`, +and the argument borrows from it, so a context never has to store a `&str`. An owned argument *clones* the value. That is cheap for an `f64` and costly for a large `String`, so take `&str` or `&T` wherever the body only needs to read. And `MRef` is the owned-or-borrowed form. It reads a plain `T` field, gives the body a value that may be either, and is the one reference-shaped row without a mutable counterpart. @@ -247,9 +247,10 @@ field name. The compiler prints its expanded `Symbol<5, Chars<'w', …>>` form i `cargo cgp expand` resugars it back. The context parameter is literally `__Context__`, a reserved name chosen so it cannot collide with one of yours. -The slice rows and the mutable rows generate a different bound from the `Value = T` equality, and it -reads oddly at first. A slice argument bounds the *associated type* instead, so `&[u8]` emits -`HasField + 'static>`. Any field whose value can be viewed as a +The `&str`, slice, and mutable rows generate a different bound from the `Value = T` equality, and it +reads oddly at first. A `&str` argument bounds the *associated type* instead, so it emits +`HasField + 'static>`, and a slice argument does the same, so +`&[u8]` emits `HasField + 'static>`. Any field whose value can be viewed as a `[u8]` then qualifies, rather than one exact type. And every mutable form swaps the trait as well as the accessor: `&mut u64` emits `HasFieldMut` and reads through `get_field_mut`. diff --git a/docs/reference/attributes/index.md b/docs/reference/attributes/index.md index c6829343..9c44fa33 100644 --- a/docs/reference/attributes/index.md +++ b/docs/reference/attributes/index.md @@ -7,7 +7,8 @@ description: 'The modifier attributes that refine what a CGP macro generates: de # Attributes -An attribute here is a modifier, not a macro of its own. Each one is an option that a host macro reads +In [Context-Generic Programming (CGP)](/docs/), an attribute here is a modifier, not a macro of its +own. Each one is an option that a host macro reads to refine the trait or implementation it generates. The hosts are [`#[cgp_impl]`](../macros/cgp_impl.md), [`#[cgp_fn]`](../macros/cgp_fn.md), and [`#[cgp_component]`](../macros/cgp_component.md), together with the macros built on diff --git a/docs/reference/attributes/prefix.md b/docs/reference/attributes/prefix.md index c8b412b3..454cd227 100644 --- a/docs/reference/attributes/prefix.md +++ b/docs/reference/attributes/prefix.md @@ -12,8 +12,10 @@ namespace addresses the component by that path. ## Overview -`#[prefix(...)]` registers a component into a [namespace](/docs/concepts/namespaces) under a path -prefix. Written on the component's trait beside [`#[cgp_component]`](../macros/cgp_component.md), it +In [Context-Generic Programming (CGP)](/docs/), `#[prefix(...)]` registers a component into a +[namespace](/docs/concepts/namespaces) under a path prefix. CGP enables pluggable trait +implementations in Rust, and a prefix is where a component's route into a shared wiring table is +named. Written on the component's trait beside [`#[cgp_component]`](../macros/cgp_component.md), it adds the component's own route to the namespace. A namespace is a reusable wiring table that a **context** joins with one line and then overrides where it needs to. (The context is the type the method runs on.) A namespace answers a lookup by *routing* it: asked for a component, it says diff --git a/docs/reference/attributes/use_provider.md b/docs/reference/attributes/use_provider.md index 192070fc..527966be 100644 --- a/docs/reference/attributes/use_provider.md +++ b/docs/reference/attributes/use_provider.md @@ -11,8 +11,11 @@ Depend on another provider by name, importing the provider trait it must satisfy ## Overview -`#[use_provider]` declares that an implementation depends on *another* implementation, by importing the -[provider trait](../macros/cgp_component.md) the inner provider must satisfy. An implementation with such +In [Context-Generic Programming (CGP)](/docs/), `#[use_provider]` declares that an implementation +depends on *another* implementation, by importing the +[provider trait](../macros/cgp_component.md) the inner provider must satisfy. CGP enables pluggable +trait implementations in Rust, and `#[use_provider]` is how one implementation names another it +builds on. An implementation with such a dependency is a [higher-order provider](/docs/concepts/higher-order-providers): a wrapper that scales whatever an inner calculator produces, or a retry layer over whatever performs a request. diff --git a/docs/reference/attributes/use_type.md b/docs/reference/attributes/use_type.md index 34d432de..e367472f 100644 --- a/docs/reference/attributes/use_type.md +++ b/docs/reference/attributes/use_type.md @@ -11,7 +11,8 @@ Import an abstract associated type and write it as a bare name. ## Overview -`#[use_type]` imports a type from the **context**, the type the code runs against. In CGP a type +In [Context-Generic Programming (CGP)](/docs/), `#[use_type]` imports a type from the **context**, +the type the code runs against. In CGP a type supplied this way is called an [*abstract type*](/docs/concepts/abstract-types): the code names it, and the context chooses what it actually is, at compile time, through its [`delegate_components!`](../macros/delegate_components.md) wiring. diff --git a/docs/reference/attributes/uses.md b/docs/reference/attributes/uses.md index c0fcd99e..e56ff2e8 100644 --- a/docs/reference/attributes/uses.md +++ b/docs/reference/attributes/uses.md @@ -11,8 +11,9 @@ Import the traits an implementation depends on, reading like a `use` statement. ## Overview -`#[uses]` names a [consumer trait](../macros/cgp_component.md), or an ordinary Rust trait, that `Self` -must satisfy, so the body can call it. `Self` here is the **context**, the type the implementation runs +In [Context-Generic Programming (CGP)](/docs/), `#[uses]` names a +[consumer trait](../macros/cgp_component.md), or an ordinary Rust trait, that `Self` must satisfy, so +the body can call it. `Self` here is the **context**, the type the implementation runs against: ```rust From 783b19756002935026b4fa9f414ed92f9bf9c300 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:31:37 +0100 Subject: [PATCH 267/516] Name the project on the derive pages The eight derive pages and their index now name Context-Generic Programming. The ExtractField page and its example module now accept a bare unit variant, whose payload is Nil, instead of claiming it needs a payload struct. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/derives/derive_build_field.md | 3 ++- docs/reference/derives/derive_cgp_data.md | 3 ++- docs/reference/derives/derive_cgp_record.md | 3 ++- docs/reference/derives/derive_cgp_variant.md | 3 ++- docs/reference/derives/derive_extract_field.md | 16 +++++++--------- docs/reference/derives/derive_from_variant.md | 3 ++- docs/reference/derives/derive_has_field.md | 3 ++- docs/reference/derives/derive_has_fields.md | 4 ++-- docs/reference/derives/index.md | 4 ++-- .../reference/derives/derive_extract_field.rs | 18 +++++++----------- 10 files changed, 30 insertions(+), 30 deletions(-) diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index f7152af0..cdc1f2b4 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -11,7 +11,8 @@ description: 'Generate a builder that tracks in its own type which fields of a s ## Overview -A struct literal requires one place to name the concrete type and supply every field. When independent +In [Context-Generic Programming (CGP)](/docs/), a struct literal requires one place to name the +concrete type and supply every field. When independent parts of a program contribute fields, a shared constructor can force each contribution to depend on the whole struct. diff --git a/docs/reference/derives/derive_cgp_data.md b/docs/reference/derives/derive_cgp_data.md index 5fde73f7..e5a399b2 100644 --- a/docs/reference/derives/derive_cgp_data.md +++ b/docs/reference/derives/derive_cgp_data.md @@ -11,7 +11,8 @@ description: 'Generate structural access and the incremental building and extrac ## Overview -Generic code needs traits to access a struct's fields or an enum's variants. A type parameter alone +In [Context-Generic Programming (CGP)](/docs/), generic code needs traits to access a struct's fields +or an enum's variants. A type parameter alone does not let it name a `first_name` field or a `Circle` variant. `#[derive(CgpData)]` supplies those traits by turning the type into **extensible data**. On a struct, diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index b4b8b936..6f036024 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -11,7 +11,8 @@ description: 'Generate field access, a structural representation, and a builder ## Overview -Generic code needs traits to read and assemble fields across different structs. A type parameter alone +In [Context-Generic Programming (CGP)](/docs/), generic code needs traits to read and assemble fields +across different structs. A type parameter alone does not let it refer to a field such as `first_name`. `#[derive(CgpRecord)]` supplies those traits, making the struct an **[extensible record](/docs/reference/glossary#extensible-record)**. It generates diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 6a7a081f..466a27c2 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -11,7 +11,8 @@ description: 'Generate a structural representation, constructors, and an extract ## Overview -Generic code needs traits to construct and handle variants across different enums. A type parameter +In [Context-Generic Programming (CGP)](/docs/), generic code needs traits to construct and handle +variants across different enums. A type parameter alone does not let it name a `Circle` variant or match exhaustively on the concrete enum. `#[derive(CgpVariant)]` supplies those traits, making the enum **extensible data**. It generates a diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index 955bf86e..b45a7931 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -11,7 +11,8 @@ description: 'Generate an extractor that tracks in its own type which variants o ## Overview -Generic code cannot match directly on an enum whose concrete type it does not know. It needs a trait +In [Context-Generic Programming (CGP)](/docs/), generic code cannot match directly on an enum whose +concrete type it does not know. It needs a trait interface that preserves Rust's exhaustiveness checking while handling variants individually. `#[derive(ExtractField)]` provides that interface by tracking the remaining variants in the @@ -64,29 +65,26 @@ opt out. Wrap the payload in a dedicated struct to give each variant a single payload type: ```rust -// rejected: no single payload type +// rejected: `Circle` has named fields, so it has no single payload type pub enum Shape { Circle { radius: f64 }, Empty, } -// accepted +// accepted: `Circle` carries one payload type, and `Empty` carries `Nil` pub struct Circle { pub radius: f64, } -pub struct Empty; - #[derive(ExtractField)] pub enum Shape { Circle(Circle), - Empty(Empty), + Empty, } ``` -Payload structs can derive extensible-data operations themselves. A fieldless case also needs a -payload type, such as the unit struct `Empty` above; a bare `Empty` variant does not meet the -single-field requirement. +Payload structs can derive extensible-data operations themselves. A variant with no fields needs no +payload struct: `Empty` carries `Nil`, and the extractor matches it with braces. [`HasFields`](./derive_has_fields.md) accepts every variant shape when only a structural representation and whole-value conversions are needed. `ExtractField` also accepts a variantless diff --git a/docs/reference/derives/derive_from_variant.md b/docs/reference/derives/derive_from_variant.md index 72f18ecb..c6f4d0cd 100644 --- a/docs/reference/derives/derive_from_variant.md +++ b/docs/reference/derives/derive_from_variant.md @@ -11,7 +11,8 @@ description: 'Let generic code construct an enum variant selected by a type-leve ## Overview -Generic code needs a trait interface to construct a variant selected by a type parameter. +In [Context-Generic Programming (CGP)](/docs/), generic code needs a trait interface to construct a +variant selected by a type parameter. `Shape::Circle(circle)` fixes both the enum and variant at the call site. `#[derive(FromVariant)]` generates a constructor for each variant, keyed by its name as a type-level diff --git a/docs/reference/derives/derive_has_field.md b/docs/reference/derives/derive_has_field.md index 143eb30b..3540fdae 100644 --- a/docs/reference/derives/derive_has_field.md +++ b/docs/reference/derives/derive_has_field.md @@ -11,7 +11,8 @@ description: 'Generate shared and mutable accessors for every field of a struct, ## Overview -A generic implementation cannot access fields with expressions such as `self.name`. It runs against +In [Context-Generic Programming (CGP)](/docs/), a generic implementation cannot access fields with +expressions such as `self.name`. It runs against a **context**, the type that supplies the values it needs as fields, but does not know that context's concrete type. diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 5bc451e6..5ab73c45 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -11,8 +11,8 @@ description: 'Generate a structural representation of a struct or enum and the c ## Overview -Generic serializers, validators, record conversions, and enum dispatchers need a description of the -whole type. Individual field access does not tell them which fields or variants exist or how to +In [Context-Generic Programming (CGP)](/docs/), generic serializers, validators, record conversions, +and enum dispatchers need a description of the whole type. Individual field access does not tell them which fields or variants exist or how to traverse them. `#[derive(HasFields)]` describes that structure through a single associated type, `Fields`. diff --git a/docs/reference/derives/index.md b/docs/reference/derives/index.md index cfb0dbd5..84440810 100644 --- a/docs/reference/derives/index.md +++ b/docs/reference/derives/index.md @@ -7,8 +7,8 @@ description: 'The derives that let generic code access, describe, build and deco # Derives -CGP derives let generic code access, describe, build, and deconstruct structs and enums without naming -their concrete types. Each derive adds trait implementations alongside the original type. Choose one +In [Context-Generic Programming (CGP)](/docs/), derives let generic code access, describe, build, and +deconstruct structs and enums without naming their concrete types. Each derive adds trait implementations alongside the original type. Choose one according to the operations your generic code needs. Start with the [reference overview](/docs/reference/) if you are new to CGP. This page compares the diff --git a/example-code/tests/reference/derives/derive_extract_field.rs b/example-code/tests/reference/derives/derive_extract_field.rs index 3598c4ce..7218eebb 100644 --- a/example-code/tests/reference/derives/derive_extract_field.rs +++ b/example-code/tests/reference/derives/derive_extract_field.rs @@ -49,8 +49,8 @@ pub mod overview { /// ## Usage /// -/// The accepted enum, the payload-struct rewrite the page recommends — including for a case that -/// carries nothing — and the variantless enum the page says degenerates. +/// The accepted enum, the payload-struct rewrite the page recommends, and the variantless enum the +/// page says degenerates. pub mod usage { use cgp::prelude::*; @@ -59,15 +59,11 @@ pub mod usage { pub radius: f64, } - /// The page's point that even a fieldless case needs a payload struct, since a bare `Empty` is a - /// unit variant and would be refused. - #[derive(Debug, PartialEq)] - pub struct Empty; - + /// A unit variant is accepted as it stands: its payload is `Nil`. #[derive(ExtractField, Debug, PartialEq)] pub enum Shape { Circle(Circle), - Empty(Empty), + Empty, } #[derive(ExtractField)] @@ -79,15 +75,15 @@ pub mod usage { } #[test] - fn test_a_payload_struct_stands_in_for_a_unit_variant() { + fn test_a_unit_variant_carries_nil() { // A remainder carries none of the enum's attributes, so it is neither `Debug` nor // `PartialEq` — the result is unwrapped rather than compared whole. - let extracted = Shape::Empty(Empty) + let extracted = Shape::Empty .to_extractor() .extract_field(PhantomData::) .ok(); - assert_eq!(extracted, Some(Empty)); + assert_eq!(extracted, Some(Nil)); } /// `from_extractor` turns an all-present owned extractor back into the enum. From 23cd7fe0b97623f491df1f18efa57551396044e8 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:41:13 +0100 Subject: [PATCH 268/516] Name the project on the component pages The nine component pages, the ten handler-family pages, and their two indexes now name Context-Generic Programming, and the component pages relate the tag line. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/components/can_raise_error.md | 6 ++++-- docs/reference/components/can_wrap_error.md | 4 +++- docs/reference/components/handler/async_computer.md | 4 +++- docs/reference/components/handler/async_computer_ref.md | 8 +++++--- docs/reference/components/handler/computer.md | 4 +++- docs/reference/components/handler/computer_ref.md | 6 ++++-- docs/reference/components/handler/handler.md | 6 ++++-- docs/reference/components/handler/handler_ref.md | 4 +++- docs/reference/components/handler/index.md | 5 +++-- docs/reference/components/handler/producer.md | 4 +++- docs/reference/components/handler/try_computer.md | 4 +++- docs/reference/components/handler/try_computer_ref.md | 5 ++++- docs/reference/components/has_error_type.md | 4 +++- docs/reference/components/has_runtime.md | 4 +++- docs/reference/components/has_runtime_type.md | 6 ++++-- docs/reference/components/has_type.md | 5 +++-- docs/reference/components/index.md | 4 ++-- docs/reference/components/runner.md | 4 +++- docs/reference/components/send_runner.md | 8 +++++--- 19 files changed, 65 insertions(+), 30 deletions(-) diff --git a/docs/reference/components/can_raise_error.md b/docs/reference/components/can_raise_error.md index 91a33b9f..c278d38a 100644 --- a/docs/reference/components/can_raise_error.md +++ b/docs/reference/components/can_raise_error.md @@ -11,8 +11,10 @@ Turn a concrete source error into the context's abstract `Self::Error`. ## Overview -`CanRaiseError` lets generic CGP code produce its context's abstract error from any -concrete error it meets. A provider that calls a fallible operation gets back a specific error type, +In [Context-Generic Programming (CGP)](/docs/), `CanRaiseError` lets generic code +produce its context's abstract error from any concrete error it meets. CGP enables pluggable trait +implementations in Rust, and `CanRaiseError` is the component that lets a context plug in how each +source error becomes its own. A provider that calls a fallible operation gets back a specific error type, a parse error, an I/O error, a string message, but it must return the **context's** abstract `Self::Error`, whose concrete identity it does not know. The context here is the type the implementation runs against, and it decides how each source error maps into its chosen error type. diff --git a/docs/reference/components/can_wrap_error.md b/docs/reference/components/can_wrap_error.md index 5480942d..68217a75 100644 --- a/docs/reference/components/can_wrap_error.md +++ b/docs/reference/components/can_wrap_error.md @@ -11,7 +11,9 @@ Attach a piece of detail to an error the context already holds, enriching it as ## Overview -`CanWrapError` enriches an error as it travels up a call stack. Where +In [Context-Generic Programming (CGP)](/docs/), `CanWrapError` enriches an error as it +travels up a call stack. CGP enables pluggable trait implementations in Rust, and `CanWrapError` is +the component that lets a context plug in how detail is folded into its error. Where [`CanRaiseError`](./can_raise_error.md) converts a *foreign* error into the context's abstract error, `CanWrapError` takes an error the **context** already holds and folds a piece of `Detail` into it, a message, a span, a path, producing an enriched `Self::Error`. The context is the type the diff --git a/docs/reference/components/handler/async_computer.md b/docs/reference/components/handler/async_computer.md index 35b3cd9c..741abc9f 100644 --- a/docs/reference/components/handler/async_computer.md +++ b/docs/reference/components/handler/async_computer.md @@ -12,7 +12,9 @@ awaits. ## Overview -`AsyncComputer` is for computations that must await but still cannot fail. Reading a value that is +In [Context-Generic Programming (CGP)](/docs/), `AsyncComputer` is for computations that must await +but still cannot fail. CGP enables pluggable trait implementations in Rust, and `AsyncComputer` is +the component that lets a context plug in an async computation. Reading a value that is already in memory is a [`Computer`](./computer.md); awaiting a timer, or a channel that always yields a value, is an `AsyncComputer`. It turns an `Input` into an `Output` under a phantom `Code` tag, against a [**context**](/docs/reference/glossary#context) (the type the implementation runs diff --git a/docs/reference/components/handler/async_computer_ref.md b/docs/reference/components/handler/async_computer_ref.md index 51bf9feb..b9afcb03 100644 --- a/docs/reference/components/handler/async_computer_ref.md +++ b/docs/reference/components/handler/async_computer_ref.md @@ -12,9 +12,11 @@ borrows its input. ## Overview -`AsyncComputerRef` combines two of the family's axes: it is asynchronous like -[`AsyncComputer`](./async_computer.md) and takes its input by reference like -[`ComputerRef`](./computer_ref.md). A computation that must await and only *reads* its argument, +In [Context-Generic Programming (CGP)](/docs/), `AsyncComputerRef` combines two of the family's +axes: it is asynchronous like [`AsyncComputer`](./async_computer.md) and takes its input by +reference like [`ComputerRef`](./computer_ref.md). CGP enables pluggable trait implementations in +Rust, and `AsyncComputerRef` is the component that lets a context plug in an async computation that +reads its input. A computation that must await and only *reads* its argument, while still never failing, fits it: its method is `async`, receives `&Input`, and returns the `Output` directly with no failure path. It runs against a [**context**](/docs/reference/glossary#context), the type the implementation runs against. diff --git a/docs/reference/components/handler/computer.md b/docs/reference/components/handler/computer.md index 8c97c68a..0750d20b 100644 --- a/docs/reference/components/handler/computer.md +++ b/docs/reference/components/handler/computer.md @@ -11,7 +11,9 @@ The synchronous, infallible member of the handler family, and the simplest provi ## Overview -`Computer` is for computations that always succeed. Adding two numbers, formatting a value, or +In [Context-Generic Programming (CGP)](/docs/), `Computer` is for computations that always succeed. +CGP enables pluggable trait implementations in Rust, and `Computer` is the component that lets a +context plug in an infallible computation. Adding two numbers, formatting a value, or projecting a field never fails, so returning a `Result` and requiring an error type would be noise. A `Computer` provider names an `Output` type and produces it from the [**context**](/docs/reference/glossary#context) (the type the implementation runs against), a diff --git a/docs/reference/components/handler/computer_ref.md b/docs/reference/components/handler/computer_ref.md index 74bccb5a..6044680d 100644 --- a/docs/reference/components/handler/computer_ref.md +++ b/docs/reference/components/handler/computer_ref.md @@ -11,8 +11,10 @@ The by-reference member of the handler family: a [`Computer`](./computer.md) tha ## Overview -`ComputerRef` is a [`Computer`](./computer.md) that takes its input by reference instead of by -value. A synchronous, infallible computation that only *reads* its argument fits `ComputerRef`, +In [Context-Generic Programming (CGP)](/docs/), `ComputerRef` is a [`Computer`](./computer.md) that +takes its input by reference instead of by value. CGP enables pluggable trait implementations in +Rust, and `ComputerRef` is the component that lets a context plug in a computation that reads its +input. A synchronous, infallible computation that only *reads* its argument fits `ComputerRef`, whose method receives `&Input` where `CanCompute` receives `Input`, so the caller keeps ownership. Everything else is the same: it turns the input into an `Output` under a phantom `Code` tag, against a [**context**](/docs/reference/glossary#context) (the type the implementation runs against), and diff --git a/docs/reference/components/handler/handler.md b/docs/reference/components/handler/handler.md index 265f2053..eef014b9 100644 --- a/docs/reference/components/handler/handler.md +++ b/docs/reference/components/handler/handler.md @@ -12,8 +12,10 @@ The general computation component: asynchronous and fallible. ## Overview -`Handler` is for computations that must both await and fail, such as a call to a remote service, -which awaits the response and must report a failure. It is the corner of the [handler +In [Context-Generic Programming (CGP)](/docs/), `Handler` is for computations that must both await +and fail, such as a call to a remote service, which awaits the response and must report a failure. +CGP enables pluggable trait implementations in Rust, and `Handler` is the component that lets a +context plug in an async, fallible computation. It is the corner of the [handler family](/docs/concepts/handlers) that has both properties: it turns an `Input` into an `Output` under a phantom `Code` tag and returns a `Result` in the abstract error type of the [**context**](/docs/reference/glossary#context), the type the implementation runs against. diff --git a/docs/reference/components/handler/handler_ref.md b/docs/reference/components/handler/handler_ref.md index e6dbc9ca..edeaf1b7 100644 --- a/docs/reference/components/handler/handler_ref.md +++ b/docs/reference/components/handler/handler_ref.md @@ -12,7 +12,9 @@ borrows its input. ## Overview -`HandlerRef` is a [`Handler`](./handler.md) that takes its input by reference. It is asynchronous +In [Context-Generic Programming (CGP)](/docs/), `HandlerRef` is a [`Handler`](./handler.md) that +takes its input by reference. CGP enables pluggable trait implementations in Rust, and `HandlerRef` +is the component that lets a context plug in an async, fallible computation that reads its input. It is asynchronous and fallible like the general handler, so it awaits and may return the abstract error of the [**context**](/docs/reference/glossary#context), the type the implementation runs against, but its method receives `&Input` where `CanHandle` receives `Input`. It suits an async, fallible computation diff --git a/docs/reference/components/handler/index.md b/docs/reference/components/handler/index.md index 56bdf4f6..15ba2fdb 100644 --- a/docs/reference/components/handler/index.md +++ b/docs/reference/components/handler/index.md @@ -6,8 +6,9 @@ sidebar_position: 0 # The handler family -The handler family models a computation as a swappable component, so a pipeline step, an I/O call, -or a type-level interpreter is wired and composed the same way as any other component. Every member +In [Context-Generic Programming (CGP)](/docs/), the handler family models a computation as a +swappable component, so a pipeline step, an I/O call, or a type-level interpreter is wired and +composed the same way as any other component. Every member turns an `Input` into an `Output` under a phantom `Code` tag, against a [**context**](/docs/reference/glossary#context), the type the implementation runs against. The members differ along three axes: synchronous or async, infallible or fallible, and taking the input diff --git a/docs/reference/components/handler/producer.md b/docs/reference/components/handler/producer.md index 14225d0f..0473de2d 100644 --- a/docs/reference/components/handler/producer.md +++ b/docs/reference/components/handler/producer.md @@ -11,7 +11,9 @@ The input-free member of the handler family: a synchronous, infallible source of ## Overview -`Producer` is for computations that take no input and yield a value. A default configuration, a +In [Context-Generic Programming (CGP)](/docs/), `Producer` is for computations that take no input +and yield a value. CGP enables pluggable trait implementations in Rust, and `Producer` is the +component that lets a context plug in an input-free computation. A default configuration, a constant, or a value read entirely from the [**context**](/docs/reference/glossary#context) (the type the implementation runs against) has no `Input` to transform: it needs only the context and a phantom `Code` tag naming which value to produce. The rest of the [handler diff --git a/docs/reference/components/handler/try_computer.md b/docs/reference/components/handler/try_computer.md index 230cd3c5..445f7dad 100644 --- a/docs/reference/components/handler/try_computer.md +++ b/docs/reference/components/handler/try_computer.md @@ -11,7 +11,9 @@ The fallible synchronous member of the handler family: a computer that can retur ## Overview -`TryComputer` is for synchronous computations that can fail. A computation that parses a string, +In [Context-Generic Programming (CGP)](/docs/), `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`](./computer.md) returns its `Output` directly, `TryComputer` returns `Result`, where `Error` is the abstract error type of the diff --git a/docs/reference/components/handler/try_computer_ref.md b/docs/reference/components/handler/try_computer_ref.md index 0d27d744..c4b554cd 100644 --- a/docs/reference/components/handler/try_computer_ref.md +++ b/docs/reference/components/handler/try_computer_ref.md @@ -12,7 +12,10 @@ The by-reference member of the handler family's fallible corner: a ## Overview -`TryComputerRef` is a [`TryComputer`](./try_computer.md) that takes its input by reference. A +In [Context-Generic Programming (CGP)](/docs/), `TryComputerRef` is a +[`TryComputer`](./try_computer.md) that takes its input by reference. CGP enables pluggable trait +implementations in Rust, and `TryComputerRef` is the component that lets a context plug in a +fallible computation that reads its input. A synchronous computation that can fail and only *reads* its argument fits it: its method receives `&Input` and returns `Result`, where `Error` is the abstract error type of the [**context**](/docs/reference/glossary#context), the type the implementation runs against. It diff --git a/docs/reference/components/has_error_type.md b/docs/reference/components/has_error_type.md index 8ea59c71..21651e3d 100644 --- a/docs/reference/components/has_error_type.md +++ b/docs/reference/components/has_error_type.md @@ -11,7 +11,9 @@ Give a context one shared, abstract `Error` type, so fallible generic code never ## Overview -`HasErrorType` lets generic CGP code fail without committing to a concrete error type. A provider +In [Context-Generic Programming (CGP)](/docs/), `HasErrorType` lets generic code fail without +committing to a concrete error type. CGP enables pluggable trait implementations in Rust, and +`HasErrorType` is the component that lets a context plug in its error type. A provider that may error has to produce *some* error, but it runs against a **context**, the type that implements the trait, and it cannot know whether that context wants `anyhow::Error`, `std::io::Error`, or an enum of its own. `HasErrorType` resolves this by giving the context one diff --git a/docs/reference/components/has_runtime.md b/docs/reference/components/has_runtime.md index b2bfab79..9a3c2c43 100644 --- a/docs/reference/components/has_runtime.md +++ b/docs/reference/components/has_runtime.md @@ -11,7 +11,9 @@ Hand out a borrow of the context's runtime value, so effectful code reaches it g ## Overview -`HasRuntime` lets context-generic code obtain the runtime it runs against without naming a concrete one. +In [Context-Generic Programming (CGP)](/docs/), `HasRuntime` lets context-generic code obtain the +runtime it runs against without naming a concrete one. CGP enables pluggable trait implementations +in Rust, and `HasRuntime` is the getter that lets a context plug in its runtime value. A runtime here is whatever object provides the services an application needs at execution time, spawning tasks, sleeping, opening sockets, reading the clock, and different deployments want different runtimes: Tokio in production, a mock in tests, a single-threaded executor in a benchmark. Rather than diff --git a/docs/reference/components/has_runtime_type.md b/docs/reference/components/has_runtime_type.md index d86fedae..9bfe9ef2 100644 --- a/docs/reference/components/has_runtime_type.md +++ b/docs/reference/components/has_runtime_type.md @@ -11,8 +11,10 @@ Declare the abstract runtime *type* a context runs against, chosen per context t ## Overview -`HasRuntimeType` lets context-generic code name the runtime type a context uses without committing -to a concrete one. A runtime is whatever object supplies the services an application needs at +In [Context-Generic Programming (CGP)](/docs/), `HasRuntimeType` lets context-generic code name the +runtime type a context uses without committing to a concrete one. CGP enables pluggable trait +implementations in Rust, and `HasRuntimeType` is the component that lets a context plug in its +runtime type. A runtime is whatever object supplies the services an application needs at execution time, and different deployments want different runtimes: Tokio in production, a mock in tests, an executor in a benchmark. `HasRuntimeType` gives the **context**, the type that implements the trait, an abstract associated `Runtime` type, resolved to a concrete one at wiring time. diff --git a/docs/reference/components/has_type.md b/docs/reference/components/has_type.md index d69c1e6c..d92ed0b8 100644 --- a/docs/reference/components/has_type.md +++ b/docs/reference/components/has_type.md @@ -11,8 +11,9 @@ CGP's tag-indexed abstract-type component: a type per tag that a context resolve ## Overview -`HasType` lets generic code refer to a type that is chosen per context without committing to a -concrete one. An [abstract type](/docs/reference/glossary#abstract-type) in CGP is a +In [Context-Generic Programming (CGP)](/docs/), `HasType` lets generic code refer to a type +that is chosen per context without committing to a concrete one. CGP enables pluggable trait +implementations in Rust, and `HasType` is the component that lets a context plug in a type per tag. An [abstract type](/docs/reference/glossary#abstract-type) in CGP is a [trait](https://doc.rust-lang.org/book/ch10-02-traits.html) with a single [associated type](https://doc.rust-lang.org/reference/items/associated-items.html), and `HasType` is the foundational, tag-indexed instance of that pattern. A **context**, the type that implements the trait, can carry many distinct abstract types, one per `Tag`, and resolve each to a concrete type diff --git a/docs/reference/components/index.md b/docs/reference/components/index.md index 539abe6c..a73f3d0f 100644 --- a/docs/reference/components/index.md +++ b/docs/reference/components/index.md @@ -7,8 +7,8 @@ sidebar_position: 0 # Components -A component is one trait, defined once, that a context can wire to any of several -implementations. The constructs on the other pages of this reference are the tools you use to *build* +In [Context-Generic Programming (CGP)](/docs/), a component is one trait, defined once, that a +context can wire to any of several implementations. The constructs on the other pages of this reference are the tools you use to *build* your own components; the pages in this section document the components CGP already ships. Each is a consumer trait you call, a provider trait an implementation targets, and a wiring key a context delegates, exactly like a component you define yourself, so you wire a built-in error type or runtime diff --git a/docs/reference/components/runner.md b/docs/reference/components/runner.md index 36fdac92..deba31df 100644 --- a/docs/reference/components/runner.md +++ b/docs/reference/components/runner.md @@ -11,7 +11,9 @@ Run a task named at the type level to a `Result<(), Error>`, with the behavior c ## Overview -`CanRun` gives a context a uniform way to *execute a unit of work* selected at the type level. +In [Context-Generic Programming (CGP)](/docs/), `CanRun` gives a context a uniform way to +*execute a unit of work* selected at the type level. CGP enables pluggable trait implementations in +Rust, and `CanRun` is the component that lets a context plug in a task runner per code. The unit of work is identified by a `Code` type parameter, a phantom tag rather than a value, so a single **context**, the type the implementation runs against, can host many distinct tasks, one per `Code`, and dispatch each to its own provider. Running a task here means invoking the provider wired diff --git a/docs/reference/components/send_runner.md b/docs/reference/components/send_runner.md index 9f80530e..34945c00 100644 --- a/docs/reference/components/send_runner.md +++ b/docs/reference/components/send_runner.md @@ -11,9 +11,11 @@ The runner variant whose returned future is `Send`, for work that must cross a t ## Overview -`CanSendRun` is [`CanRun`](./runner.md) with one added guarantee: the future its method returns is -[`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html), so it can be handed to a spawner such as -`tokio::spawn`. It exists to solve a specific Rust limitation. A generic `async fn` over abstract +In [Context-Generic Programming (CGP)](/docs/), `CanSendRun` is [`CanRun`](./runner.md) with +one added guarantee: the future its method returns is +[`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html), so it can be handed to a spawner +such as `tokio::spawn`. CGP enables pluggable trait implementations in Rust, and `CanSendRun` is the +component that lets a context plug in a `Send`-future runner. It exists to solve a specific Rust limitation. A generic `async fn` over abstract **context** types (the context being the type a method runs on that supplies the values an implementation needs as its own fields) cannot promise its future is `Send` without annotating `Send` bounds on every [abstract type](/docs/reference/glossary#abstract-type) in scope, and those bounds pollute every interface. From eb69bca4fdec0a0843e172b3d9a8041ae6e9d708 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:41:44 +0100 Subject: [PATCH 269/516] Name the project on the type pages The twelve type pages now name Context-Generic Programming. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/types/chars.md | 4 ++-- docs/reference/types/cons.md | 4 ++-- docs/reference/types/either.md | 4 ++-- docs/reference/types/field.md | 3 ++- docs/reference/types/index.md | 4 ++-- docs/reference/types/index_type.md | 3 ++- docs/reference/types/life.md | 4 ++-- docs/reference/types/mref.md | 4 ++-- docs/reference/types/nil.md | 3 ++- docs/reference/types/path_cons.md | 3 ++- docs/reference/types/phantom_data.md | 3 ++- docs/reference/types/void.md | 2 +- 12 files changed, 23 insertions(+), 18 deletions(-) diff --git a/docs/reference/types/chars.md b/docs/reference/types/chars.md index b5c379ca..44239657 100644 --- a/docs/reference/types/chars.md +++ b/docs/reference/types/chars.md @@ -12,8 +12,8 @@ the name can be a type. ## Overview -`Chars` encodes a string as a type, so that a field name can take part in trait -resolution. CGP keys field access by a tag type. To read a field called `name`, something must stand for +In [Context-Generic Programming (CGP)](/docs/), `Chars` encodes a string as +a type, so that a field name can take part in trait resolution. CGP keys field access by a tag type. To read a field called `name`, something must stand for the string `"name"` at the type level, so that the compiler can tell one [`HasField`](../traits/field-access/has_field.md) impl from another by the tag alone. A `Chars` chain turns the string into a type, and a `Symbol` that wraps the chain is the tag itself. diff --git a/docs/reference/types/cons.md b/docs/reference/types/cons.md index 36ac325c..7d334f2d 100644 --- a/docs/reference/types/cons.md +++ b/docs/reference/types/cons.md @@ -12,8 +12,8 @@ time. ## Overview -`Cons` represents an ordered sequence of types as a single type, so that generic code can -reason about a collection of fields. A Rust tuple holds several things at once, but generic code cannot +In [Context-Generic Programming (CGP)](/docs/), `Cons` represents an ordered sequence of +types as a single type, so that generic code can reason about a collection of fields. A Rust tuple holds several things at once, but generic code cannot take it apart element by element. A recursive list allows that. `Cons` pairs the first element with the rest of the list, and [`Nil`](nil.md) marks the end. Together they form an *anonymous product type*: a record-shaped value that code can walk without knowing the concrete struct it diff --git a/docs/reference/types/either.md b/docs/reference/types/either.md index 64c119a3..cb28b6ee 100644 --- a/docs/reference/types/either.md +++ b/docs/reference/types/either.md @@ -12,8 +12,8 @@ time. ## Overview -`Either` represents a choice among several types as a single type, so that generic code can -reason about an enum's variants. The [product list](cons.md) holds a value for *every* element at once. +In [Context-Generic Programming (CGP)](/docs/), `Either` represents a choice among +several types as a single type, so that generic code can reason about an enum's variants. The [product list](cons.md) holds a value for *every* element at once. The sum list holds a value for exactly *one* of its branches, which makes it a tagged union, or *anonymous sum type*. `Either` branches at each step, and [`Void`](void.md) marks the end. Together they form a coproduct that code can walk without knowing the concrete enum it came from. diff --git a/docs/reference/types/field.md b/docs/reference/types/field.md index f944f512..f0861051 100644 --- a/docs/reference/types/field.md +++ b/docs/reference/types/field.md @@ -12,7 +12,8 @@ described one entry at a time without naming the concrete type. ## Overview -`Field` carries a field's *name* and its *value* together in one type. A bare +In [Context-Generic Programming (CGP)](/docs/), `Field` carries a field's *name* and its +*value* together in one type. A bare [`Product!`](../macros/product.md) list such as `Product![String, u8]` records the value types and their order, but it cannot tell `name: String` from any other `String`. Wrapping each element in a `Field`, as `Field`, attaches the name as a type, so a struct's [shape](/docs/reference/glossary#shape) describes itself. diff --git a/docs/reference/types/index.md b/docs/reference/types/index.md index 18d9e84f..b866d07d 100644 --- a/docs/reference/types/index.md +++ b/docs/reference/types/index.md @@ -11,8 +11,8 @@ the one ordinary runtime type you return from a getter. ## Overview -Most types on these pages are **type-level building blocks**, and you read them far more often than you -write them. Much of CGP's machinery runs at the type level, where a field name, a variant, a position, or +In [Context-Generic Programming (CGP)](/docs/), most types on these pages are **type-level building +blocks**, and you read them far more often than you write them. Much of CGP's machinery runs at the type level, where a field name, a variant, a position, or a whole record [shape](/docs/reference/glossary#shape) is a *type* rather than a value. These building blocks carry that information. A macro writes almost all of them for you, so you meet them when you read generated code or when a wiring mistake reports a deeply nested type. This section exists to make such a type readable. diff --git a/docs/reference/types/index_type.md b/docs/reference/types/index_type.md index 98fc23c2..0c74d59e 100644 --- a/docs/reference/types/index_type.md +++ b/docs/reference/types/index_type.md @@ -12,7 +12,8 @@ A number lifted into a type, so a tuple-struct field can be named by its positio ## Overview -`Index` encodes a `usize` at the type level. CGP's getter mechanism keys every field by a +In [Context-Generic Programming (CGP)](/docs/), `Index` encodes a `usize` at the +type level. CGP's getter mechanism keys every field by a *type* tag, but a tuple-struct field has only a position and lacks a string name to turn into a [`Symbol!`](../macros/symbol.md). So the position itself becomes a type, and positional fields can use the same trait-resolution machinery as named fields. `Index` is that type. It carries a `usize` as a const diff --git a/docs/reference/types/life.md b/docs/reference/types/life.md index dd4fd755..856b89b8 100644 --- a/docs/reference/types/life.md +++ b/docs/reference/types/life.md @@ -12,8 +12,8 @@ types. ## Overview -`Life<'a>` turns the lifetime `'a` into a type, because CGP's wiring is parameterized by *types* and a CGP -trait may carry a lifetime of its own. The marker that records a provider's dependencies, +In [Context-Generic Programming (CGP)](/docs/), `Life<'a>` turns the lifetime `'a` into a type, +because CGP's wiring is parameterized by *types* and a CGP trait may carry a lifetime of its own. The marker that records a provider's dependencies, [`IsProviderFor`](../traits/wiring/is_provider_for.md), takes a tuple of the trait's generic parameters as one type argument, so that the compiler can match a provider against the exact instantiation asked for. A lifetime cannot sit in that tuple, because a tuple is a type and its members must be types. So a lifetime diff --git a/docs/reference/types/mref.md b/docs/reference/types/mref.md index 152df3b8..e42eaa41 100644 --- a/docs/reference/types/mref.md +++ b/docs/reference/types/mref.md @@ -12,8 +12,8 @@ whichever it has without forcing every implementor to one or the other. ## Overview -`MRef<'a, T>` lets one getter signature serve both the context that already stores a value and the -context that must produce one. Here a **context** is the type the method runs on, which supplies the +In [Context-Generic Programming (CGP)](/docs/), `MRef<'a, T>` lets one getter signature serve both +the context that already stores a value and the context that must produce one. Here a **context** is the type the method runs on, which supplies the values it needs as its fields. A getter that returns `&'a T` forces every context to keep a `T` it can lend. A getter that returns `T` forces every context to give up ownership, and to clone even when it could share a reference. `MRef<'a, T>` avoids both constraints by being either case at run diff --git a/docs/reference/types/nil.md b/docs/reference/types/nil.md index fe8f98d4..c13ce327 100644 --- a/docs/reference/types/nil.md +++ b/docs/reference/types/nil.md @@ -11,7 +11,8 @@ The end marker of the product, string, and path lists: an empty, constructible l ## Overview -`Nil` marks the end of a right-nested type-level list. Where a [`Cons`](cons.md) cell pairs a head with +In [Context-Generic Programming (CGP)](/docs/), `Nil` marks the end of a right-nested type-level +list. Where a [`Cons`](cons.md) cell pairs a head with the rest of the list, `Nil` is the rest when nothing is left, so a list of any length is a `Cons` chain that finishes in `Nil`. On its own, `Nil` is the empty list. diff --git a/docs/reference/types/path_cons.md b/docs/reference/types/path_cons.md index 863be709..5b675277 100644 --- a/docs/reference/types/path_cons.md +++ b/docs/reference/types/path_cons.md @@ -12,7 +12,8 @@ lookup can reach an entry several layers deep. ## Overview -`PathCons` expresses a *route* through nested delegation tables as a single type. A bare +In [Context-Generic Programming (CGP)](/docs/), `PathCons` expresses a *route* through +nested delegation tables as a single type. A bare component name picks one entry out of a context's table. Here the **context** is the type the implementation runs against, and its table records which provider it uses for each component. Sometimes the entry a lookup wants sits behind a layer of indirection: inside a namespace, behind a diff --git a/docs/reference/types/phantom_data.md b/docs/reference/types/phantom_data.md index 34a311ec..926d1a2e 100644 --- a/docs/reference/types/phantom_data.md +++ b/docs/reference/types/phantom_data.md @@ -13,7 +13,8 @@ give a function a type instead of data. ## Overview -`PhantomData` is a standard-library type, not a CGP type. It comes from +In [Context-Generic Programming (CGP)](/docs/), `PhantomData` is a standard-library type, not a CGP +type. It comes from [`core::marker`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html). It has a page here because it appears throughout CGP code and does one specific job. A reader who has only seen it as noise in a struct definition will misread much of what CGP generates. diff --git a/docs/reference/types/void.md b/docs/reference/types/void.md index f716b3a6..a27585d0 100644 --- a/docs/reference/types/void.md +++ b/docs/reference/types/void.md @@ -12,7 +12,7 @@ complete variant match end without a runtime branch. ## Overview -`Void` marks the end of a sum. Unlike the [`Nil`](nil.md) that ends the other lists, it is uninhabited: a +In [Context-Generic Programming (CGP)](/docs/), `Void` marks the end of a sum. Unlike the [`Nil`](nil.md) that ends the other lists, it is uninhabited: a value of `Void` cannot exist. A record, a string, or a path can each be empty and still exist, but an empty *choice* cannot, so the natural terminator for the sum list is a type without values. From 2cbe66094fd68cbe83b0d61d3334013174af070a Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:44:31 +0100 Subject: [PATCH 270/516] Name the project on the wiring trait pages The three wiring trait pages and their index now name Context-Generic Programming, and the trait pages relate the tag line. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/traits/wiring/can_use_component.md | 5 +++-- docs/reference/traits/wiring/delegate_component.md | 6 ++++-- docs/reference/traits/wiring/index.md | 6 +++--- docs/reference/traits/wiring/is_provider_for.md | 8 +++++--- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/reference/traits/wiring/can_use_component.md b/docs/reference/traits/wiring/can_use_component.md index abc487c0..e9885296 100644 --- a/docs/reference/traits/wiring/can_use_component.md +++ b/docs/reference/traits/wiring/can_use_component.md @@ -24,8 +24,9 @@ probing one case. ## Overview -CGP's wiring is lazy: writing a wiring line does not check that the chosen provider's own -requirements are met. That check happens where the trait is first used, usually far from the wiring, +In [Context-Generic Programming (CGP)](/docs/), wiring is lazy: writing a wiring line does not check +that the chosen provider's own requirements are met. CGP enables pluggable trait implementations in +Rust, and `CanUseComponent` is the check that a context's choice is complete. That check happens where the trait is first used, usually far from the wiring, and the error there is poor, because asking whether a [**context**](/docs/reference/glossary#context), the type the implementation runs against, implements the consumer trait makes the compiler report only the outermost unmet bound. The root diff --git a/docs/reference/traits/wiring/delegate_component.md b/docs/reference/traits/wiring/delegate_component.md index b56c3738..3ed03a50 100644 --- a/docs/reference/traits/wiring/delegate_component.md +++ b/docs/reference/traits/wiring/delegate_component.md @@ -24,8 +24,10 @@ an entry, as the [Usage](#usage) section shows. ## Overview -Wiring a [**context**](/docs/reference/glossary#context), the type the implementation runs against, -means recording which provider it uses for each component. `DelegateComponent` is the trait that +In [Context-Generic Programming (CGP)](/docs/), wiring a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, means +recording which provider it uses for each component. CGP enables pluggable trait implementations in +Rust, and `DelegateComponent` is the table that records each choice. `DelegateComponent` is the trait that record is made of, and one impl is one entry: ```rust diff --git a/docs/reference/traits/wiring/index.md b/docs/reference/traits/wiring/index.md index dd3ea627..56a42c70 100644 --- a/docs/reference/traits/wiring/index.md +++ b/docs/reference/traits/wiring/index.md @@ -10,9 +10,9 @@ The three traits every context's wiring rests on, and the ones a wiring error na ## Overview -Wiring a [**context**](/docs/reference/glossary#context), the type the implementation runs against, -records which provider it uses for each component and checks that the provider's own requirements -are met. These traits carry that, and you read them far more often than you write them, because a +In [Context-Generic Programming (CGP)](/docs/), wiring a +[**context**](/docs/reference/glossary#context), the type the implementation runs against, records +which provider it uses for each component and checks that the provider's own requirements are met. These traits carry that, and you read them far more often than you write them, because a [`delegate_components!`](../../macros/delegate_components.md) table generates the first two and a [`check_components!`](../../macros/check_components.md) block asserts the third. diff --git a/docs/reference/traits/wiring/is_provider_for.md b/docs/reference/traits/wiring/is_provider_for.md index eb94bad5..88654ddb 100644 --- a/docs/reference/traits/wiring/is_provider_for.md +++ b/docs/reference/traits/wiring/is_provider_for.md @@ -26,9 +26,11 @@ because this trait is what a missing-dependency error names. ## Overview -A provider states what it needs from its [**context**](/docs/reference/glossary#context), the type -the implementation runs against, in its own `where` clause: a field, an -[abstract type](/docs/reference/glossary#abstract-type), another trait. When one of those +In [Context-Generic Programming (CGP)](/docs/), a provider states what it needs from its +[**context**](/docs/reference/glossary#context), the type the implementation runs against, in its +own `where` clause: a field, an [abstract type](/docs/reference/glossary#abstract-type), another +trait. CGP enables pluggable trait implementations in Rust, and `IsProviderFor` is the marker that +makes a provider's missing dependency show up by name. When one of those requirements is not met, you want the compiler to say which, and left to itself it will not. Asking whether a provider implements its provider trait has two candidate impls in scope, the blanket impl that routes through the wiring table and the one you wrote, and when more than one impl could apply, From 5aa1d01fc2a3e38af6809807e6afbe5b18dcd911 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:45:12 +0100 Subject: [PATCH 271/516] Name the project on the field and shape trait pages The fourteen field-access and shape trait pages now name Context-Generic Programming, and HasField relates the tag line. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/traits/field-access/field_getter.md | 3 ++- docs/reference/traits/field-access/field_mapper.md | 7 ++++--- docs/reference/traits/field-access/has_field.md | 8 +++++--- docs/reference/traits/field-access/has_field_mut.md | 6 +++--- docs/reference/traits/field-access/index.md | 6 +++--- docs/reference/traits/field-access/map_field.md | 3 ++- docs/reference/traits/field-access/mut_field_getter.md | 7 ++++--- docs/reference/traits/field-access/option_as_ref.md | 5 +++-- docs/reference/traits/shape/from_fields.md | 4 ++-- docs/reference/traits/shape/has_fields.md | 4 ++-- docs/reference/traits/shape/has_fields_ref.md | 3 ++- docs/reference/traits/shape/index.md | 5 +++-- docs/reference/traits/shape/to_fields.md | 3 ++- docs/reference/traits/shape/to_fields_ref.md | 3 ++- 14 files changed, 39 insertions(+), 28 deletions(-) diff --git a/docs/reference/traits/field-access/field_getter.md b/docs/reference/traits/field-access/field_getter.md index e810ac98..e95fb46c 100644 --- a/docs/reference/traits/field-access/field_getter.md +++ b/docs/reference/traits/field-access/field_getter.md @@ -24,7 +24,8 @@ yourself is a getter provider whose read no existing provider expresses. ## Overview -[`HasField`](./has_field.md) is a bound an implementation states about its own context. Sometimes +In [Context-Generic Programming (CGP)](/docs/), [`HasField`](./has_field.md) is a bound an +implementation states about its own context. Sometimes the field should instead be **chosen by wiring**, so that each [**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the values it needs as its fields, decides which of its fields answers a getter. That needs the diff --git a/docs/reference/traits/field-access/field_mapper.md b/docs/reference/traits/field-access/field_mapper.md index 7cd55038..1d72b995 100644 --- a/docs/reference/traits/field-access/field_mapper.md +++ b/docs/reference/traits/field-access/field_mapper.md @@ -23,9 +23,10 @@ does. ## Overview -[`MapField`](./map_field.md) reads through a field of a generic -[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the -values it needs as its fields, by handing the borrowed field to a closure rather than returning it. +In [Context-Generic Programming (CGP)](/docs/), [`MapField`](./map_field.md) reads through a field +of a generic [**context**](/docs/reference/glossary#context), the type the method runs on, which +supplies the values it needs as its fields, by handing the borrowed field to a closure rather than +returning it. `FieldMapper` is the same operation in provider shape, with a provider as `Self` and the context as an explicit type argument. This is the form a getter provider needs, because a provider trait's method has its lifetimes fixed by the trait, so a chained read inside it cannot take the lifetime diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index c7e7e6b9..4012356c 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -11,9 +11,11 @@ Reading a field by a type-level name, from a context you cannot name. ## Overview -An implementation written against a [**context**](/docs/reference/glossary#context), the type the -method runs on, which supplies the values it needs as its fields, is generic over that context and -cannot name its concrete type, so it cannot write `self.name`. `HasField` closes the gap: the +In [Context-Generic Programming (CGP)](/docs/), an implementation written against a +[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the +values it needs as its fields, is generic over that context and cannot name its concrete type, so it +cannot write `self.name`. CGP enables pluggable trait implementations in Rust, and `HasField` is the +trait that lets a provider ask for a field by name. `HasField` closes the gap: the field's name becomes a type, and the implementation asks for the field as a trait bound: ```rust diff --git a/docs/reference/traits/field-access/has_field_mut.md b/docs/reference/traits/field-access/has_field_mut.md index 7d34f6c9..676b1e6a 100644 --- a/docs/reference/traits/field-access/has_field_mut.md +++ b/docs/reference/traits/field-access/has_field_mut.md @@ -11,9 +11,9 @@ Mutable tag-keyed field access. ## Overview -[`HasField`](./has_field.md) lets an implementation read a field of a -[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the -values it needs as its fields, by keying on the field's name as a type. `HasFieldMut` is the same +In [Context-Generic Programming (CGP)](/docs/), [`HasField`](./has_field.md) lets an implementation +read a field of a [**context**](/docs/reference/glossary#context), the type the method runs on, +which supplies the values it needs as its fields, by keying on the field's name as a type. `HasFieldMut` is the same access with mutation: it hands back a `&mut` rather than a `&`, so an implementation can change a value in place. diff --git a/docs/reference/traits/field-access/index.md b/docs/reference/traits/field-access/index.md index 2a57d7d1..c97b395b 100644 --- a/docs/reference/traits/field-access/index.md +++ b/docs/reference/traits/field-access/index.md @@ -10,9 +10,9 @@ Reading one field of a context by its type-level name, from code that cannot nam ## Overview -A CGP implementation most often reads a value out of its -[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the -values it needs as its fields, without naming that type. It reads the field by keying on the field's +In [Context-Generic Programming (CGP)](/docs/), an implementation most often reads a value out of +its [**context**](/docs/reference/glossary#context), the type the method runs on, which supplies +the values it needs as its fields, without naming that type. It reads the field by keying on the field's *name as a type*, so any context with a matching field satisfies the bound. These traits are the foundation the ergonomic surface stands on: an [`#[implicit]`](../../attributes/implicit.md) argument, a [`#[cgp_auto_getter]`](../../macros/cgp_auto_getter.md) method, and a diff --git a/docs/reference/traits/field-access/map_field.md b/docs/reference/traits/field-access/map_field.md index 645eae51..10dfd5f6 100644 --- a/docs/reference/traits/field-access/map_field.md +++ b/docs/reference/traits/field-access/map_field.md @@ -11,7 +11,8 @@ Read through a field of a generic context without adding a lifetime bound on its ## Overview -Reading a field of a field looks like two chained reads, and on a concrete type it is. In generic +In [Context-Generic Programming (CGP)](/docs/), reading a field of a field looks like two chained +reads, and on a concrete type it is. In generic code it is not: when a [**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the values it needs as its fields, holds a field of a generic type `Inner`, `context.get_field(..).get_field(..)` returns a borrow that the compiler cannot tie to the context's diff --git a/docs/reference/traits/field-access/mut_field_getter.md b/docs/reference/traits/field-access/mut_field_getter.md index 94d15389..7f3369dd 100644 --- a/docs/reference/traits/field-access/mut_field_getter.md +++ b/docs/reference/traits/field-access/mut_field_getter.md @@ -24,9 +24,10 @@ provider expresses. ## Overview -[`FieldGetter`](./field_getter.md) is field access in provider shape, so that a -[**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the -values it needs as its fields, can choose by wiring which field answers a getter. `MutFieldGetter` +In [Context-Generic Programming (CGP)](/docs/), [`FieldGetter`](./field_getter.md) is field access +in provider shape, so that a [**context**](/docs/reference/glossary#context), the type the method +runs on, which supplies the values it needs as its fields, can choose by wiring which field answers +a getter. `MutFieldGetter` is the same with mutation: it hands back a `&mut` rather than a `&`, for a getter whose method takes `&mut self`. The four field-access traits divide on two axes: diff --git a/docs/reference/traits/field-access/option_as_ref.md b/docs/reference/traits/field-access/option_as_ref.md index 8e20bde0..da4566a3 100644 --- a/docs/reference/traits/field-access/option_as_ref.md +++ b/docs/reference/traits/field-access/option_as_ref.md @@ -13,8 +13,9 @@ whose `U` implements `AsRef`. ## Overview -The trait lets an [`#[implicit]`](../../attributes/implicit.md) argument of type `Option<&str>` read -any `Option` whose `U` converts to `&str`. The two obvious bounds do not work: requiring the field +In [Context-Generic Programming (CGP)](/docs/), the trait lets an +[`#[implicit]`](../../attributes/implicit.md) argument of type `Option<&str>` read any `Option` +whose `U` converts to `&str`. The two obvious bounds do not work: requiring the field to be an `Option` ties it to one type and pulls in `alloc`, and requiring `Value: AsRef` fails because `Option` does not implement `AsRef`. `OptionAsRef` names the conversion instead of the field's concrete type. diff --git a/docs/reference/traits/shape/from_fields.md b/docs/reference/traits/shape/from_fields.md index b033fae0..f0a72612 100644 --- a/docs/reference/traits/shape/from_fields.md +++ b/docs/reference/traits/shape/from_fields.md @@ -11,8 +11,8 @@ Rebuilding a concrete value from its shape. ## Overview -[`ToFields`](./to_fields.md) takes a value apart into an anonymous list of named entries. -`FromFields` is the return journey. It closes the loop for generic code: decompose a value, work on +In [Context-Generic Programming (CGP)](/docs/), [`ToFields`](./to_fields.md) takes a value apart +into an anonymous list of named entries. `FromFields` is the return journey. It closes the loop for generic code: decompose a value, work on the entries without naming the type, and put a concrete value back together at the end. Both directions go through the identical `Fields` type, so **the shapes line up by construction rather than by check**: there is nothing to validate and nothing that can fail. diff --git a/docs/reference/traits/shape/has_fields.md b/docs/reference/traits/shape/has_fields.md index ee9d8a89..a462e17e 100644 --- a/docs/reference/traits/shape/has_fields.md +++ b/docs/reference/traits/shape/has_fields.md @@ -11,8 +11,8 @@ A type's whole shape, as a single type. ## Overview -Some code needs one field of a type. Other code needs the *shape*, every field, its name, and its -type, so it can walk them: a serializer, a validator, a builder that merges two structs, a +In [Context-Generic Programming (CGP)](/docs/), some code needs one field of a type. Other code +needs the *shape*, every field, its name, and its type, so it can walk them: a serializer, a validator, a builder that merges two structs, a dispatcher that routes an enum to a handler per variant. None of those can be written one field at a time, and none can name the concrete type either. diff --git a/docs/reference/traits/shape/has_fields_ref.md b/docs/reference/traits/shape/has_fields_ref.md index 017525cf..0d698fca 100644 --- a/docs/reference/traits/shape/has_fields_ref.md +++ b/docs/reference/traits/shape/has_fields_ref.md @@ -22,7 +22,8 @@ reserved lifetime name that shows up in an error message. ## Overview -[`HasFields`](./has_fields.md) describes a type as a list of named entries holding owned values. +In [Context-Generic Programming (CGP)](/docs/), [`HasFields`](./has_fields.md) describes a type as +a list of named entries holding owned values. Code that only *reads* a value should not have to consume it to walk its shape (a validator, a serializer, a routine that inspects a struct and hands it back), so there is a second description in which every entry holds a borrow instead. diff --git a/docs/reference/traits/shape/index.md b/docs/reference/traits/shape/index.md index fa44c78a..9cc94465 100644 --- a/docs/reference/traits/shape/index.md +++ b/docs/reference/traits/shape/index.md @@ -10,8 +10,9 @@ A type's whole shape as a single type, and the conversions that move a value thr ## Overview -Where [field access](../field-access/index.md) reads one named field, these traits describe a type's -*whole shape* at once, every field, its name, and its type, as a single associated type. That is what +In [Context-Generic Programming (CGP)](/docs/), where [field access](../field-access/index.md) reads +one named field, these traits describe a type's *whole shape* at once, every field, its name, and +its type, as a single associated type. That is what lets generic code walk a struct or an enum it cannot name: a serializer, a validator, a merge, a dispatcher. The impls come from [`#[derive(HasFields)]`](../../derives/derive_has_fields.md). diff --git a/docs/reference/traits/shape/to_fields.md b/docs/reference/traits/shape/to_fields.md index 660275a4..f969929f 100644 --- a/docs/reference/traits/shape/to_fields.md +++ b/docs/reference/traits/shape/to_fields.md @@ -11,7 +11,8 @@ Taking a value apart into its shape. ## Overview -[`HasFields`](./has_fields.md) *names* a type's shape. `ToFields` produces a value in it. +In [Context-Generic Programming (CGP)](/docs/), [`HasFields`](./has_fields.md) *names* a type's +shape. `ToFields` produces a value in it. That lets generic code stop working on a concrete struct and start working on an anonymous list of named entries: the form a serializer walks, a converter rewrites, or a merge consumes. The concrete diff --git a/docs/reference/traits/shape/to_fields_ref.md b/docs/reference/traits/shape/to_fields_ref.md index 6bb3f4ef..5c2c6c53 100644 --- a/docs/reference/traits/shape/to_fields_ref.md +++ b/docs/reference/traits/shape/to_fields_ref.md @@ -11,7 +11,8 @@ Walking a value's shape without consuming it. ## Overview -[`ToFields`](./to_fields.md) takes a value apart into its shape and consumes it in the process. Code +In [Context-Generic Programming (CGP)](/docs/), [`ToFields`](./to_fields.md) takes a value apart +into its shape and consumes it in the process. Code that only reads (a validator, a serializer, a routine that inspects a struct and hands it back) should not have to. `ToFieldsRef` produces the **borrowed** shape instead. The original survives, and every entry in the result holds a reference rather than a value. From abb00d045007189ce548aa7df197077d82c9f2bf Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:45:46 +0100 Subject: [PATCH 272/516] Name the project on the variant and namespace trait pages The twelve variant and namespace trait pages now name Context-Generic Programming, and the namespace pages relate the tag line. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/traits/namespace/default_impls1.md | 5 +++-- docs/reference/traits/namespace/default_impls2.md | 6 ++++-- docs/reference/traits/namespace/default_namespace.md | 6 ++++-- docs/reference/traits/namespace/index.md | 6 ++++-- docs/reference/traits/variant/extract_field.md | 8 +++++--- docs/reference/traits/variant/finalize_extract.md | 3 ++- docs/reference/traits/variant/finalize_extract_result.md | 5 +++-- docs/reference/traits/variant/from_variant.md | 8 +++++--- docs/reference/traits/variant/has_extractor.md | 4 ++-- docs/reference/traits/variant/has_extractor_mut.md | 5 +++-- docs/reference/traits/variant/has_extractor_ref.md | 3 ++- docs/reference/traits/variant/index.md | 5 +++-- 12 files changed, 40 insertions(+), 24 deletions(-) diff --git a/docs/reference/traits/namespace/default_impls1.md b/docs/reference/traits/namespace/default_impls1.md index 985c16ce..6cac8cc1 100644 --- a/docs/reference/traits/namespace/default_impls1.md +++ b/docs/reference/traits/namespace/default_impls1.md @@ -23,8 +23,9 @@ backwards. ## Overview -[`DefaultNamespace`](./default_namespace.md) keys a default on the component alone: one component, one -default provider. `DefaultImpls1` adds a second type to the key, which a **per-type default** +In [Context-Generic Programming (CGP)](/docs/), [`DefaultNamespace`](./default_namespace.md) keys a +default on the component alone: one component, one default provider. CGP enables pluggable trait +implementations in Rust, and `DefaultImpls1` is where a per-type default is registered. `DefaultImpls1` adds a second type to the key, which a **per-type default** needs: the same component resolving differently for `String` than for `u64`. ## Definition diff --git a/docs/reference/traits/namespace/default_impls2.md b/docs/reference/traits/namespace/default_impls2.md index 7e150dc0..85669693 100644 --- a/docs/reference/traits/namespace/default_impls2.md +++ b/docs/reference/traits/namespace/default_impls2.md @@ -22,8 +22,10 @@ page explains what they emit. ## Overview -[`DefaultImpls1`](./default_impls1.md) keys a namespace default on a component plus one type, which a -per-type default needs. `DefaultImpls2` is the same idea under a **pair** of types. +In [Context-Generic Programming (CGP)](/docs/), [`DefaultImpls1`](./default_impls1.md) keys a +namespace default on a component plus one type, which a per-type default needs. CGP enables +pluggable trait implementations in Rust, and `DefaultImpls2` is where a default keyed on a pair of +types is registered. `DefaultImpls2` is the same idea under a **pair** of types. ## Definition diff --git a/docs/reference/traits/namespace/default_namespace.md b/docs/reference/traits/namespace/default_namespace.md index 8eef42f8..9b9a59df 100644 --- a/docs/reference/traits/namespace/default_namespace.md +++ b/docs/reference/traits/namespace/default_namespace.md @@ -24,8 +24,10 @@ one it binds. ## Overview -A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a **context** (the -type the method runs on) can opt into and then complete. Resolving one of those +In [Context-Generic Programming (CGP)](/docs/), a [namespace](/docs/concepts/namespaces) is a +reusable table of default wirings that a **context** (the type the method runs on) can opt into and +then complete. CGP enables pluggable trait implementations in Rust, and a namespace is where a group +of those choices gets a name. Resolving one of those defaults means asking: *for this component, what does the namespace delegate to?* `DefaultNamespace` answers that. It is the simplest of three lookup traits, keyed on the component alone. diff --git a/docs/reference/traits/namespace/index.md b/docs/reference/traits/namespace/index.md index 2184ec5b..b647a466 100644 --- a/docs/reference/traits/namespace/index.md +++ b/docs/reference/traits/namespace/index.md @@ -10,8 +10,10 @@ The lookup traits behind a namespace and a per-type default. ## Overview -A [namespace](/docs/concepts/namespaces) is a reusable table of default wirings that a context opts into -and then completes with the entries the namespace leaves open. Resolving one of those defaults means +In [Context-Generic Programming (CGP)](/docs/), a [namespace](/docs/concepts/namespaces) is a +reusable table of default wirings that a context opts into and then completes with the entries the +namespace leaves open. CGP enables pluggable trait implementations in Rust, and a namespace is where +a group of those choices gets a name. Resolving one of those defaults means asking, for a given key, what the namespace delegates to, and these three traits answer it, differing only in how many types take part in the key. You name them where the syntax requires it: a `namespace` header or a `for … in` loop inside [`delegate_components!`](../../macros/delegate_components.md), and the diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index 10a182a7..f473c90e 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -11,9 +11,11 @@ Pulling one variant out of an extractor, or narrowing what remains. ## Overview -A `match` on a concrete enum is checked for exhaustiveness. Code that is generic over the enum cannot -write one, so it falls back on a wildcard arm and an `unreachable!()`, losing exactly the guarantee you -wanted. +In [Context-Generic Programming (CGP)](/docs/), a `match` on a concrete enum is checked for +exhaustiveness. Code that is generic over the enum cannot write one, so it falls back on a wildcard +arm and an `unreachable!()`, losing exactly the guarantee you wanted. CGP enables pluggable trait +implementations in Rust, and `ExtractField` is the operation that takes one variant out of an +extractor. `ExtractField` is the operation that recovers it. Each attempt either yields the payload or hands back a *remainder* whose type has that variant ruled out, and **the impl exists only while the requested variant diff --git a/docs/reference/traits/variant/finalize_extract.md b/docs/reference/traits/variant/finalize_extract.md index 54dec02a..daf4e1e5 100644 --- a/docs/reference/traits/variant/finalize_extract.md +++ b/docs/reference/traits/variant/finalize_extract.md @@ -11,7 +11,8 @@ Discharging an extractor that has nothing left in it. ## Overview -An [extraction chain](./extract_field.md) ends when every variant has been ruled out. At that point the +In [Context-Generic Programming (CGP)](/docs/), an [extraction chain](./extract_field.md) 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. diff --git a/docs/reference/traits/variant/finalize_extract_result.md b/docs/reference/traits/variant/finalize_extract_result.md index 5d611589..a4f62840 100644 --- a/docs/reference/traits/variant/finalize_extract_result.md +++ b/docs/reference/traits/variant/finalize_extract_result.md @@ -11,8 +11,9 @@ Collapsing the `Result` at the end of an extraction chain. ## Overview -Every step of an [extraction chain](./extract_field.md) 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 +In [Context-Generic Programming (CGP)](/docs/), every step of an +[extraction chain](./extract_field.md) 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`](./finalize_extract.md) is the underlying diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index c5df2592..250c4f7d 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -11,9 +11,11 @@ Generic construction of an enum from a named variant. ## Overview -`Shape::Circle(circle)` names two things: the enum and the variant. That is fine where both are known and -useless to code that knows neither: a routine handed a payload and told which variant to wrap it in cannot -write that expression. +In [Context-Generic Programming (CGP)](/docs/), `Shape::Circle(circle)` names two things: the enum +and the variant. That is fine where both are known and useless to code that knows neither: a routine +handed a payload and told which variant to wrap it in cannot write that expression. CGP enables +pluggable trait implementations in Rust, and `FromVariant` is the operation that constructs a variant +by name. `FromVariant` gives it a way to. The variant is selected by its *name as a type*, so the choice becomes a parameter rather than syntax: diff --git a/docs/reference/traits/variant/has_extractor.md b/docs/reference/traits/variant/has_extractor.md index 51576329..9b76366f 100644 --- a/docs/reference/traits/variant/has_extractor.md +++ b/docs/reference/traits/variant/has_extractor.md @@ -11,8 +11,8 @@ Turning an enum into an extractor, and back. ## Overview -[`ExtractField`](./extract_field.md) narrows an *extractor*, not an enum. `HasExtractor` is where one -comes from. It is the owning member of a group of three, and choosing between them is most of using the +In [Context-Generic Programming (CGP)](/docs/), [`ExtractField`](./extract_field.md) narrows an +*extractor*, not an enum. `HasExtractor` is where one comes from. It is the owning member of a group of three, and choosing between them is most of using the extractor family: | | payloads come out as | the original | diff --git a/docs/reference/traits/variant/has_extractor_mut.md b/docs/reference/traits/variant/has_extractor_mut.md index 2b45611f..04d3f87f 100644 --- a/docs/reference/traits/variant/has_extractor_mut.md +++ b/docs/reference/traits/variant/has_extractor_mut.md @@ -11,8 +11,9 @@ Obtaining an extractor that can change a payload in place. ## Overview -[`HasExtractorRef`](./has_extractor_ref.md) borrows an enum so its variants can be read without consuming -it. `HasExtractorMut` borrows it mutably, so a payload can be **changed in place**. +In [Context-Generic Programming (CGP)](/docs/), [`HasExtractorRef`](./has_extractor_ref.md) borrows +an enum so its variants can be read without consuming it. `HasExtractorMut` borrows it mutably, so a +payload can be **changed in place**. Payloads come out as `&mut T`. The original survives, mutably borrowed for the duration, and the narrowing works exactly as it does for the other two accessors: [`ExtractField`](./extract_field.md) diff --git a/docs/reference/traits/variant/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md index 1c0002aa..48903602 100644 --- a/docs/reference/traits/variant/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -11,7 +11,8 @@ Obtaining an extractor that borrows the value rather than consuming it. ## Overview -[`HasExtractor`](./has_extractor.md) consumes an enum to produce an extractor with owned payloads. Code +In [Context-Generic Programming (CGP)](/docs/), [`HasExtractor`](./has_extractor.md) consumes an +enum to produce an extractor with owned payloads. Code that only *reads* a variant (checking it, measuring it, rendering it) should not have to give up the value. `HasExtractorRef` is the borrowing accessor. diff --git a/docs/reference/traits/variant/index.md b/docs/reference/traits/variant/index.md index b8a449b1..3e8fe362 100644 --- a/docs/reference/traits/variant/index.md +++ b/docs/reference/traits/variant/index.md @@ -10,8 +10,9 @@ Constructing an enum from one named variant, and taking one apart variant by var ## Overview -These traits are the enum counterpart of the [record builder](../builder/index.md): where a record is -a product of named fields, an enum is a sum of named variants, and the same name-driven, decoupled +In [Context-Generic Programming (CGP)](/docs/), these traits are the enum counterpart of the [record +builder](../builder/index.md): where a record is a product of named fields, an enum is a sum of named +variants, and the same name-driven, decoupled treatment applies. They let generic code build and match an enum it cannot name, with exhaustiveness proven in the type rather than by a wildcard arm. The impls come from [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) and From 9e84541cec233d2b00ba15c83a0e51a0bd762979 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:47:12 +0100 Subject: [PATCH 273/516] Keep the tag line to the pages that choose an implementation The HasField, ExtractField, and FromVariant pages no longer carry the tag line, which belongs to the constructs that choose an implementation. The HasField page keeps its glossary link for context. Co-Authored-By: deepseek-v4.1-flash-1017 --- docs/reference/traits/field-access/has_field.md | 3 +-- docs/reference/traits/variant/extract_field.md | 4 +--- docs/reference/traits/variant/from_variant.md | 4 +--- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/docs/reference/traits/field-access/has_field.md b/docs/reference/traits/field-access/has_field.md index 4012356c..e8f636d2 100644 --- a/docs/reference/traits/field-access/has_field.md +++ b/docs/reference/traits/field-access/has_field.md @@ -14,8 +14,7 @@ Reading a field by a type-level name, from a context you cannot name. In [Context-Generic Programming (CGP)](/docs/), an implementation written against a [**context**](/docs/reference/glossary#context), the type the method runs on, which supplies the values it needs as its fields, is generic over that context and cannot name its concrete type, so it -cannot write `self.name`. CGP enables pluggable trait implementations in Rust, and `HasField` is the -trait that lets a provider ask for a field by name. `HasField` closes the gap: the +cannot write `self.name`. `HasField` closes the gap: the field's name becomes a type, and the implementation asks for the field as a trait bound: ```rust diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index f473c90e..fc9b24a3 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -13,9 +13,7 @@ Pulling one variant out of an extractor, or narrowing what remains. In [Context-Generic Programming (CGP)](/docs/), a `match` on a concrete enum is checked for exhaustiveness. Code that is generic over the enum cannot write one, so it falls back on a wildcard -arm and an `unreachable!()`, losing exactly the guarantee you wanted. CGP enables pluggable trait -implementations in Rust, and `ExtractField` is the operation that takes one variant out of an -extractor. +arm and an `unreachable!()`, losing exactly the guarantee you wanted. `ExtractField` is the operation that recovers it. Each attempt either yields the payload or hands back a *remainder* whose type has that variant ruled out, and **the impl exists only while the requested variant diff --git a/docs/reference/traits/variant/from_variant.md b/docs/reference/traits/variant/from_variant.md index 250c4f7d..c5966718 100644 --- a/docs/reference/traits/variant/from_variant.md +++ b/docs/reference/traits/variant/from_variant.md @@ -13,9 +13,7 @@ Generic construction of an enum from a named variant. In [Context-Generic Programming (CGP)](/docs/), `Shape::Circle(circle)` names two things: the enum and the variant. That is fine where both are known and useless to code that knows neither: a routine -handed a payload and told which variant to wrap it in cannot write that expression. CGP enables -pluggable trait implementations in Rust, and `FromVariant` is the operation that constructs a variant -by name. +handed a payload and told which variant to wrap it in cannot write that expression. `FromVariant` gives it a way to. The variant is selected by its *name as a type*, so the choice becomes a parameter rather than syntax: From 6857eeb9df5501efc77f758f21e8d3bcf5dc4f9d Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:55:28 +0100 Subject: [PATCH 274/516] Name the project on the builder and optional-field trait pages The seventeen record-builder and optional-field pages now name Context-Generic Programming in their opening paragraphs. The `HasOptionalBuilder` page no longer says `FinalizeOptional` reports the first missing field, since it names the last unset one; the `TransformOptional` page names both ways the two transform markers differ; and the `HasBuilder` expansion shows the companion's doc line. Co-Authored-By: Claude Opus 5.5 --- docs/reference/traits/builder/build_field.md | 6 ++++-- docs/reference/traits/builder/finalize_build.md | 13 +++++++------ docs/reference/traits/builder/has_builder.md | 9 ++++++--- docs/reference/traits/builder/index.md | 13 +++++++------ docs/reference/traits/builder/into_builder.md | 10 ++++++---- docs/reference/traits/builder/partial_data.md | 12 +++++++----- docs/reference/traits/builder/take_field.md | 10 ++++++---- docs/reference/traits/builder/update_field.md | 11 ++++++----- .../traits/optional/can_build_with_default.md | 1 + .../traits/optional/can_finalize_with_default.md | 9 +++++---- .../traits/optional/finalize_optional.md | 9 +++++---- .../traits/optional/has_optional_builder.md | 12 +++++++----- docs/reference/traits/optional/index.md | 12 +++++++----- docs/reference/traits/optional/set_optional.md | 9 +++++---- docs/reference/traits/optional/to_optional.md | 15 ++++++++------- .../traits/optional/transform_map_default.md | 5 +++-- .../traits/optional/transform_optional.md | 13 ++++++++----- 17 files changed, 98 insertions(+), 71 deletions(-) diff --git a/docs/reference/traits/builder/build_field.md b/docs/reference/traits/builder/build_field.md index ed030bc2..5ffe6756 100644 --- a/docs/reference/traits/builder/build_field.md +++ b/docs/reference/traits/builder/build_field.md @@ -11,8 +11,10 @@ Setting one currently-absent field of a builder. ## Overview -`BuildField` is the direction of the [builder family](./has_builder.md) you write most: take a partial -record with a field absent, supply the value, and get back a [partial record](/docs/reference/glossary#partial-record) with that field present. +When [Context-Generic Programming (CGP)](/docs/) builds a struct one named field at a time, +`BuildField` is the direction of its [builder family](./has_builder.md) you write most: take a +partial record with a field absent, supply the value, and get back a +[partial record](/docs/reference/glossary#partial-record) with that field present. `Output` is a **different type** from `Self` (the same partial record with one marker flipped), which is what makes the compiler track completeness. A chain of `build_field` calls walks through as many distinct diff --git a/docs/reference/traits/builder/finalize_build.md b/docs/reference/traits/builder/finalize_build.md index 8bcee269..5bc5176c 100644 --- a/docs/reference/traits/builder/finalize_build.md +++ b/docs/reference/traits/builder/finalize_build.md @@ -11,10 +11,11 @@ Turning a fully-built [partial record](/docs/reference/glossary#partial-record) ## Overview -`FinalizeBuild` is where a build ends. What makes it the family's safety argument is not the method but -**where the impl exists**. It is -implemented for exactly one configuration of a partial record, the one in which every field is -`IsPresent`, so calling it on an incomplete value is a *missing impl*, not a runtime check that fails: +`FinalizeBuild` is where a build ends when [Context-Generic Programming (CGP)](/docs/) assembles a +struct generically, one named field at a time. What makes it the family's safety argument is not the +method but **where the impl exists**. It is implemented for exactly one configuration of a partial +record, the one in which every field is `IsPresent`, so calling it on an incomplete value is a +*missing impl*, not a runtime check that fails: ```rust let person = Person::builder() @@ -110,8 +111,8 @@ already at the one configuration the impl covers. - **Use [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md)** when unset fields should be filled from `Default` rather than rejected. It re-marks every field to `IsPresent` and then calls this, so the strict check still runs and always passes. -- **Use [`FinalizeOptional`](../optional/finalize_optional.md)** when absence should be *reported* at run time - rather than caught at compile time. It returns a `Result` naming a missing field. +- **Use [`FinalizeOptional`](../optional/finalize_optional.md)** when absence should be *reported* + at run time rather than caught at compile time. It returns a `Result` naming a missing field. - **Stay with `FinalizeBuild`** when every field is genuinely required. Moving to either of the other two gives up the compile-time completeness check, which is the reason the family exists. diff --git a/docs/reference/traits/builder/has_builder.md b/docs/reference/traits/builder/has_builder.md index 706f3254..42d98d8f 100644 --- a/docs/reference/traits/builder/has_builder.md +++ b/docs/reference/traits/builder/has_builder.md @@ -11,9 +11,11 @@ Starting an empty builder for a record. ## Overview -A struct literal supplies every field at once, in one place that names the type. `HasBuilder` is the -entry point for the case where that is impossible: the fields come from several independent places, none -of which should know the whole struct, and the result must still be checked at compile time. +A struct literal supplies every field at once, in one place that names the type. +[Context-Generic Programming (CGP)](/docs/) builds structs generically, by their field names, and +`HasBuilder` is its entry point for the case where a literal is impossible: the fields come from +several independent places, none of which should know the whole struct, and the result must still be +checked at compile time. `builder()` hands back a partial value with **every field absent**. Filling it is [`BuildField`](./build_field.md), and turning it back into the concrete struct is @@ -145,6 +147,7 @@ point. And the enum counterparts are a different family: parameter's projection. `cargo cgp expand` on a two-field `Person` shows it: ```rust +///The partial builder for [`Person`]. pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { pub first_name: <__F0__ as MapType>::Map, pub last_name: <__F1__ as MapType>::Map, diff --git a/docs/reference/traits/builder/index.md b/docs/reference/traits/builder/index.md index 8d98e338..473c17b0 100644 --- a/docs/reference/traits/builder/index.md +++ b/docs/reference/traits/builder/index.md @@ -10,12 +10,13 @@ Assembling a struct one field at a time, with field presence tracked in the type ## Overview -These traits build a record incrementally, where the fields come from several independent places and -the result must still be checked at compile time. The build starts from an empty *partial* value and -adds fields one by one, and each field's presence lives in the type, so finalizing an incomplete -record is a missing impl rather than a runtime panic. The impls come from -[`#[derive(BuildField)]`](../../derives/derive_build_field.md), which also generates the partial -companion type. +[Context-Generic Programming (CGP)](/docs/) builds and reads Rust structs generically, by their +named fields, and these traits are its record builder. They build a record incrementally, where the +fields come from several independent places and the result must still be checked at compile time. +The build starts from an empty *partial* value and adds fields one by one, and each field's presence +lives in the type, so finalizing an incomplete record is a missing impl rather than a runtime panic. +The impls come from [`#[derive(BuildField)]`](../../derives/derive_build_field.md), which also +generates the partial companion type. The family divides into entry points, the update primitive and its two directions, and the finalize step. diff --git a/docs/reference/traits/builder/into_builder.md b/docs/reference/traits/builder/into_builder.md index 736707ac..f4435dde 100644 --- a/docs/reference/traits/builder/into_builder.md +++ b/docs/reference/traits/builder/into_builder.md @@ -11,10 +11,12 @@ Turning a complete record into a partial one, with every field present. ## Overview -[`HasBuilder`](./has_builder.md) starts from nothing: a partial value with every field absent, to be -filled. `IntoBuilder` starts from the other end: `into_builder(self)` consumes an existing value and -hands back a partial one with **every field present**. You reach for it when *redistributing* a struct's -fields rather than assembling one: taking a value apart, moving some fields elsewhere, and rebuilding. +[Context-Generic Programming (CGP)](/docs/) assembles a struct generically through a builder that +tracks each field's presence in its type. [`HasBuilder`](./has_builder.md) starts from nothing: a +partial value with every field absent, to be filled. `IntoBuilder` starts from the other end: +`into_builder(self)` consumes an existing value and hands back a partial one with **every field +present**. You reach for it when *redistributing* a struct's fields rather than assembling one: +taking a value apart, moving some fields elsewhere, and rebuilding. The two entry points differ only in where they begin, and they produce the same kind of value: diff --git a/docs/reference/traits/builder/partial_data.md b/docs/reference/traits/builder/partial_data.md index 087471a8..c50a80c5 100644 --- a/docs/reference/traits/builder/partial_data.md +++ b/docs/reference/traits/builder/partial_data.md @@ -24,12 +24,14 @@ needs the destination type before the value is complete. ## Overview -A [partial record](/docs/reference/glossary#partial-record) is a companion type (`__PartialPerson`), and generic code holding +[Context-Generic Programming (CGP)](/docs/) builds a struct generically through a +[partial record](/docs/reference/glossary#partial-record), a companion type +(`__PartialPerson`) that tracks which fields are set, and generic code holding one often needs to know what it will *become* before it is complete: to name the return type of a -routine, to state a bound, to decide what to do next. `PartialData` answers that: its single `Target` -associated type is the concrete struct or enum the partial value corresponds to. **It is implemented for -every configuration**, complete or not, and that coverage is the point: the destination is knowable from -the first `builder()` call, long before any field is set. +routine, to state a bound, to decide what to do next. `PartialData` answers that: its single +`Target` associated type is the concrete struct or enum the partial value corresponds to. **It is +implemented for every configuration**, complete or not, and that coverage is the point: the +destination is knowable from the first `builder()` call, long before any field is set. That is the division of labour with [`FinalizeBuild`](./finalize_build.md), which is implemented **only** at the all-present configuration. One says where you are going; the other says you have arrived. diff --git a/docs/reference/traits/builder/take_field.md b/docs/reference/traits/builder/take_field.md index 813ba3bb..33297795 100644 --- a/docs/reference/traits/builder/take_field.md +++ b/docs/reference/traits/builder/take_field.md @@ -11,10 +11,12 @@ Removing one currently-present field from a builder. ## Overview -`TakeField` is the reverse of [`BuildField`](./build_field.md): it removes a field that is currently set, -handing back the value and the [partial record](/docs/reference/glossary#partial-record) without it. The value comes out owned, and the remainder is -the partial record with that one field flipped back to absent, so it can no longer be finalized until the -field is put back. +[Context-Generic Programming (CGP)](/docs/) assembles and takes apart structs generically, by their +field names. `TakeField` is the reverse of [`BuildField`](./build_field.md): it removes a field that +is currently set, handing back the value and the +[partial record](/docs/reference/glossary#partial-record) without it. The value comes out owned, and +the remainder is the partial record with that one field flipped back to absent, so it can no longer +be finalized until the field is put back. It pins the `IsPresent → IsNothing` transition of the [`UpdateField`](./update_field.md) primitive, and because it *requires* the starting marker to be `IsPresent`, **taking a field that is absent is a compile diff --git a/docs/reference/traits/builder/update_field.md b/docs/reference/traits/builder/update_field.md index 9b18f3a0..90c5bc75 100644 --- a/docs/reference/traits/builder/update_field.md +++ b/docs/reference/traits/builder/update_field.md @@ -23,11 +23,12 @@ optional-field layer reaches for when neither direction fits. ## Overview -Everything in the [builder family](./has_builder.md) reduces to one operation: change one field's storage -from one [`MapType`](../type-level/map_type.md) marker to another, and hand back what was there before. -`UpdateField` is that operation. [`BuildField`](./build_field.md) and [`TakeField`](./take_field.md) are -library blanket impls over it, each pinning one transition, which is why the derive writes this general -form once per field. +[Context-Generic Programming (CGP)](/docs/) builds a struct generically, one named field at a time, +and everything in its [builder family](./has_builder.md) reduces to one operation: change one +field's storage from one [`MapType`](../type-level/map_type.md) marker to another, and hand back +what was there before. `UpdateField` is that operation. [`BuildField`](./build_field.md) and +[`TakeField`](./take_field.md) are library blanket impls over it, each pinning one transition, which +is why the derive writes this general form once per field. ## Definition diff --git a/docs/reference/traits/optional/can_build_with_default.md b/docs/reference/traits/optional/can_build_with_default.md index 270bf0c5..89c39eef 100644 --- a/docs/reference/traits/optional/can_build_with_default.md +++ b/docs/reference/traits/optional/can_build_with_default.md @@ -11,6 +11,7 @@ Widening one record into another in a single call. ## Overview +[Context-Generic Programming (CGP)](/docs/) can convert between structs that share field names. Turning a narrow record into a wider one whose extra fields have sensible defaults is a three-step motion: start a builder, copy the source's fields, default the rest. `CanBuildWithDefault` is that motion as one call. diff --git a/docs/reference/traits/optional/can_finalize_with_default.md b/docs/reference/traits/optional/can_finalize_with_default.md index f03d0105..774b55e8 100644 --- a/docs/reference/traits/optional/can_finalize_with_default.md +++ b/docs/reference/traits/optional/can_finalize_with_default.md @@ -11,10 +11,11 @@ Finalizing a [partial record](/docs/reference/glossary#partial-record), filling ## Overview -The core [builder family](../builder/has_builder.md) refuses to finalize an incomplete record, which is what -catches a missing field at compile time. For a record where some fields have sensible defaults, that -strictness is the wrong shape. `CanFinalizeWithDefault` relaxes it: every field that is not set becomes -`Default::default()`, and the result is the concrete struct. +The core [builder family](../builder/has_builder.md) of [Context-Generic Programming (CGP)](/docs/), +which assembles a struct generically by its field names, refuses to finalize an incomplete record, +which is what catches a missing field at compile time. For a record where some fields have sensible +defaults, that strictness is the wrong shape. `CanFinalizeWithDefault` relaxes it: every field that +is not set becomes `Default::default()`, and the result is the concrete struct. **The strict presence check still runs, and it always passes**, because the fields are re-marked to `IsPresent` first. That is the layer's whole design in one sentence, and it is why the core diff --git a/docs/reference/traits/optional/finalize_optional.md b/docs/reference/traits/optional/finalize_optional.md index 679aef3d..7e8a8f40 100644 --- a/docs/reference/traits/optional/finalize_optional.md +++ b/docs/reference/traits/optional/finalize_optional.md @@ -11,10 +11,11 @@ Finalizing an optional builder, reporting a missing field. ## Overview -An [optional builder](./has_optional_builder.md) has given up the compile-time completeness check: every -field is `IsOptional`, so the type no longer records what has been set. Something has to check at run -time instead, and `FinalizeOptional` is the strict way to do it: it succeeds only if every field holds a -value, and otherwise reports a missing field by name. +An [optional builder](./has_optional_builder.md) in [Context-Generic Programming (CGP)](/docs/), +which assembles a struct generically by its field names, has given up the compile-time completeness +check: every field is `IsOptional`, so the type no longer records what has been set. Something has +to check at run time instead, and `FinalizeOptional` is the strict way to do it: it succeeds only if +every field holds a value, and otherwise reports a missing field by name. It is one of two endings for an optional builder, and the choice between them is made at the call site rather than when the builder is created: diff --git a/docs/reference/traits/optional/has_optional_builder.md b/docs/reference/traits/optional/has_optional_builder.md index 717ac967..f09fe92a 100644 --- a/docs/reference/traits/optional/has_optional_builder.md +++ b/docs/reference/traits/optional/has_optional_builder.md @@ -11,10 +11,12 @@ Starting a builder in which every field is already optional. ## Overview -The core [builder family](../builder/has_builder.md) is deliberately strict: a field is set exactly once, and a -[partial record](/docs/reference/glossary#partial-record) becomes its concrete struct only when **every** field is present. That strictness is what -catches a missing field at compile time, and it is too rigid for a record whose fields arrive in an -unpredictable order, or more than once. +[Context-Generic Programming (CGP)](/docs/) assembles a struct generically through a +[builder family](../builder/has_builder.md) that is deliberately strict: a field is set exactly +once, and a [partial record](/docs/reference/glossary#partial-record) becomes its concrete struct +only when **every** field is present. That strictness is what catches a missing field at compile +time, and it is too rigid for a record whose fields arrive in an unpredictable order, or more than +once. `HasOptionalBuilder` is the entry point that relaxes it. It hands back a partial value with every field marked `IsOptional` rather than `IsNothing`, so each slot holds an `Option` and **absence becomes a @@ -179,7 +181,7 @@ Conflating them produces an `Option>`. ## Related constructs - [`SetOptional`](./set_optional.md): setting a field on the builder this produces. -- [`FinalizeOptional`](./finalize_optional.md): the strict ending, reporting the first missing field. +- [`FinalizeOptional`](./finalize_optional.md): the strict ending, naming a missing field. - [`CanFinalizeWithDefault`](./can_finalize_with_default.md): the defaulting ending. - [`ToOptional`](./to_optional.md): converting an existing core builder instead of starting fresh. - [`HasBuilder`](../builder/has_builder.md): the core entry point this relaxes. diff --git a/docs/reference/traits/optional/index.md b/docs/reference/traits/optional/index.md index 1da0da7a..deb890b9 100644 --- a/docs/reference/traits/optional/index.md +++ b/docs/reference/traits/optional/index.md @@ -10,11 +10,13 @@ Relaxing the strict record builder, so a field can be set in any order or left u ## Overview -The core [record builder](../builder/index.md) is deliberately strict: a field is set once, and a -[partial record](/docs/reference/glossary#partial-record) becomes its struct only when every field is present. That strictness catches a missing -field at compile time, and it is too rigid for a record whose fields arrive unpredictably or have -sensible defaults. These traits, from `cgp-field-extra`, relax it while reusing the same machinery -underneath. Nothing here is in the prelude. Import each from `cgp::extra::field::impls`. +[Context-Generic Programming (CGP)](/docs/) assembles a struct generically by its field names, and +its core [record builder](../builder/index.md) is deliberately strict: a field is set once, and a +[partial record](/docs/reference/glossary#partial-record) becomes its struct only when every field +is present. That strictness catches a missing field at compile time, and it is too rigid for a +record whose fields arrive unpredictably or have sensible defaults. These traits, from +`cgp-field-extra`, relax it while reusing the same machinery underneath. Nothing here is in the +prelude. Import each from `cgp::extra::field::impls`. The layer divides into entry points, the setter, the two endings, and the transform markers behind them. diff --git a/docs/reference/traits/optional/set_optional.md b/docs/reference/traits/optional/set_optional.md index 725c435d..e35c751e 100644 --- a/docs/reference/traits/optional/set_optional.md +++ b/docs/reference/traits/optional/set_optional.md @@ -11,10 +11,11 @@ Setting one field of an optional builder, as many times as you like. ## Overview -[`BuildField`](../builder/build_field.md) sets an absent field and consumes the slot: the builder's type changes, -and setting the same field twice is a compile error. `SetOptional` is the optional layer's answer, and its -defining property is the opposite: an optional field is settable in any order and as many times as you -like. +When [Context-Generic Programming (CGP)](/docs/) assembles a struct generically, +[`BuildField`](../builder/build_field.md) sets an absent field and consumes the slot: the builder's +type changes, and setting the same field twice is a compile error. `SetOptional` is the optional +layer's answer, and its defining property is the opposite: an optional field is settable in any +order and as many times as you like. ## Definition diff --git a/docs/reference/traits/optional/to_optional.md b/docs/reference/traits/optional/to_optional.md index 80bdb613..b05ff3b6 100644 --- a/docs/reference/traits/optional/to_optional.md +++ b/docs/reference/traits/optional/to_optional.md @@ -11,13 +11,14 @@ Re-marking every field of an existing builder as optional. ## Overview -[`HasOptionalBuilder`](./has_optional_builder.md) starts an all-optional builder from nothing. -`ToOptional` is the conversion for the case where you already hold a partial value and want to relax it. -Every field is re-marked to `IsOptional`, whatever state it was in (a set field becomes `Some(value)`, -an absent one becomes `None`), and from there the value behaves like any other optional builder: -[`SetOptional`](./set_optional.md) applies, and either -[`FinalizeOptional`](./finalize_optional.md) or [`CanFinalizeWithDefault`](./can_finalize_with_default.md) -ends it. +[Context-Generic Programming (CGP)](/docs/) builds a struct generically, and its optional builder +lets the fields arrive in any order. [`HasOptionalBuilder`](./has_optional_builder.md) starts one +from nothing. `ToOptional` is the conversion for the case where you already hold a partial value and +want to relax it. Every field is re-marked to `IsOptional`, whatever state it was in (a set field +becomes `Some(value)`, an absent one becomes `None`), and from there the value behaves like any +other optional builder: [`SetOptional`](./set_optional.md) applies, and either +[`FinalizeOptional`](./finalize_optional.md) or +[`CanFinalizeWithDefault`](./can_finalize_with_default.md) ends it. **It is the conversion `optional_builder()` is built from**, which is the shortest way to describe both: one starts fresh and converts, the other converts something you already have. diff --git a/docs/reference/traits/optional/transform_map_default.md b/docs/reference/traits/optional/transform_map_default.md index d969db2e..7203fa10 100644 --- a/docs/reference/traits/optional/transform_map_default.md +++ b/docs/reference/traits/optional/transform_map_default.md @@ -23,8 +23,9 @@ transform of your own. ## Overview -[`CanFinalizeWithDefault`](./can_finalize_with_default.md) works by re-marking every field of a partial -record to `IsPresent` and then calling the ordinary [`finalize_build`](../builder/finalize_build.md). +[Context-Generic Programming (CGP)](/docs/) tracks each field of a partial record with a type-level +marker, and [`CanFinalizeWithDefault`](./can_finalize_with_default.md) works by re-marking every +field to `IsPresent` and then calling the ordinary [`finalize_build`](../builder/finalize_build.md). `TransformMapDefault` is the marker that carries the per-field conversions making that possible. **You name it only when extending the layer.** Using the defaulting workflow means calling diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index 5f144364..1cf230aa 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -23,9 +23,11 @@ an operation of your own that drives the optional conversion. ## Overview -[`ToOptional`](./to_optional.md) re-marks every field of a [partial record](/docs/reference/glossary#partial-record) to `IsOptional`, so it can then -be set freely and finalized either way. `TransformOptional` is the marker carrying the per-field -conversions that make that possible. +[Context-Generic Programming (CGP)](/docs/) tracks each field of a +[partial record](/docs/reference/glossary#partial-record) with a type-level marker, and +[`ToOptional`](./to_optional.md) re-marks every field to `IsOptional`, so it can then be set freely +and finalized either way. `TransformOptional` is the marker carrying the per-field conversions that +make that possible. **It is the exact mirror of [`TransformMapDefault`](./transform_map_default.md)**, which targets `IsPresent` instead: same walk, different destination. That symmetry is why the defaulted and optional @@ -177,8 +179,9 @@ again; [`ToOptional`](./to_optional.md#common-mistakes) shows the error. **It is a marker, not an operation.** It lacks a method and needs nothing wired. It is named in a bound. -**It requires nothing of the field types**, which is the one place the two markers genuinely differ in -what they can be applied to. +**It requires nothing of the field types**, so it applies to a field type without `Default`, which +[`TransformMapDefault`](./transform_map_default.md) does not. The missing `IsOptional` impl is the +other difference, in the opposite direction. **Converting gives up the compile-time completeness check**, since every field becomes optional whether it was set or not. From 54070da6b865493b7e46cdf19d370b57fdf8c323 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 19:58:50 +0100 Subject: [PATCH 275/516] Name the project on the casting and type-level trait pages The thirteen casting and type-level pages now name Context-Generic Programming in their opening paragraphs. The `MapTypeRef` page no longer says the `: 'a` bound keeps the storage type from outliving the borrow, since it requires the storage to live at least that long. The `TransformMap` title gains its apostrophe, the `MapFields` notice names `BuildAndMergeOutputs` as the dispatch provider it is, and the borrowed companion's expansion shows its doc line. Co-Authored-By: Claude Opus 5.5 --- .../traits/casting/can_build_from.md | 6 +++--- docs/reference/traits/casting/can_downcast.md | 7 ++++--- .../traits/casting/can_downcast_fields.md | 3 ++- docs/reference/traits/casting/can_upcast.md | 8 ++++--- docs/reference/traits/casting/index.md | 13 ++++++------ .../traits/type-level/append_product.md | 11 +++++----- .../traits/type-level/concat_product.md | 7 ++++--- docs/reference/traits/type-level/index.md | 8 ++++--- .../reference/traits/type-level/map_fields.md | 21 +++++++++++-------- docs/reference/traits/type-level/map_type.md | 9 ++++---- .../traits/type-level/map_type_ref.md | 19 ++++++++++------- .../traits/type-level/transform_map.md | 10 +++++---- .../traits/type-level/transform_map_fields.md | 7 ++++--- 13 files changed, 74 insertions(+), 55 deletions(-) diff --git a/docs/reference/traits/casting/can_build_from.md b/docs/reference/traits/casting/can_build_from.md index 5895decb..9e6b501b 100644 --- a/docs/reference/traits/casting/can_build_from.md +++ b/docs/reference/traits/casting/can_build_from.md @@ -11,9 +11,9 @@ Moving every field of one record into another record's builder. ## Overview -Assembling one struct out of several smaller ones means copying each field across by hand: a -line per field, repeated for every pair of types. `CanBuildFrom` derives that copying from the field -names instead. +Assembling one struct out of several smaller ones means copying each field across by hand: a line +per field, repeated for every pair of types. `CanBuildFrom`, one of the structural conversions of +[Context-Generic Programming (CGP)](/docs/), derives that copying from the field names instead. It is the record counterpart of the [variant casts](./can_upcast.md), and it differs from them in one way that shapes how it is written: **it is implemented for a builder rather than for the target diff --git a/docs/reference/traits/casting/can_downcast.md b/docs/reference/traits/casting/can_downcast.md index 5a2bfa29..f4bdea57 100644 --- a/docs/reference/traits/casting/can_downcast.md +++ b/docs/reference/traits/casting/can_downcast.md @@ -11,9 +11,10 @@ Narrowing a wide enum into a smaller one, or handing back what is left. ## Overview -Converting a wide enum into a narrower one is the direction that can fail: the value's current variant -may be one the target does not have. `CanDowncast` attempts that conversion, and it does more than -a fallible `From` because of what it returns on failure. +[Context-Generic Programming (CGP)](/docs/) converts between Rust enums by their variant names, and +converting a wide enum into a narrower one is the direction that can fail: the value's current +variant may be one the target does not have. `CanDowncast` attempts that conversion, and it does +more than a fallible `From` because of what it returns on failure. **A failed downcast hands back a *remainder* rather than an error.** The remainder is the same value with the attempted variants ruled out *in its type*, so it can be tried against another target, and each diff --git a/docs/reference/traits/casting/can_downcast_fields.md b/docs/reference/traits/casting/can_downcast_fields.md index 8db35a68..6affca94 100644 --- a/docs/reference/traits/casting/can_downcast_fields.md +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -11,7 +11,8 @@ Continuing a narrowing chain on a remainder. ## Overview -[`CanDowncast`](./can_downcast.md) narrows an enum and, when it fails, hands back a *remainder*: the +[Context-Generic Programming (CGP)](/docs/) can narrow a Rust enum into a smaller one by its variant +names. [`CanDowncast`](./can_downcast.md) does so and, when it fails, hands back a *remainder*: the same value with the attempted variants ruled out in its type. You then pass that remainder to `CanDowncastFields`, so a value can be tried against a second target, a third, and so on. diff --git a/docs/reference/traits/casting/can_upcast.md b/docs/reference/traits/casting/can_upcast.md index 2b590288..9ba09a33 100644 --- a/docs/reference/traits/casting/can_upcast.md +++ b/docs/reference/traits/casting/can_upcast.md @@ -11,9 +11,11 @@ Widening a narrow enum into a wider one that shares its variants. ## Overview -Two enums defined independently can share variant names, say a small `FooBar` and a larger `FooBarBaz`. -Converting the narrow one into the wide one is a conversion you could write by hand, and it is -pure boilerplate: one `match` arm per variant, rewrapping each payload under the same name. +[Context-Generic Programming (CGP)](/docs/) can convert between Rust enums by their variant names. +Two enums defined independently can share variant names, say a small `FooBar` and a larger +`FooBarBaz`. Converting the narrow one into the wide one is a conversion you could write by hand, +and it is pure boilerplate: one `match` arm per variant, rewrapping each payload under the same +name. `CanUpcast` derives that conversion from the names instead. Once the source exposes its variants as a type-level list and the target can be built one variant at a time, widening is a matter of routing diff --git a/docs/reference/traits/casting/index.md b/docs/reference/traits/casting/index.md index c2be70cf..fcf86259 100644 --- a/docs/reference/traits/casting/index.md +++ b/docs/reference/traits/casting/index.md @@ -11,12 +11,13 @@ conversion. ## Overview -Two types that share a subset of named fields or variants can convert into one another generically, -without a hand-written `From` or `TryFrom`. Because CGP represents each record as a product of named -fields and each enum as a sum of named variants, a conversion becomes a matter of routing each named -entry to the target's slot of the same name. Each side derives the part of the extensible-data -machinery its role needs, and the names are matched at the type level. None of these traits is in -the prelude. Import each from `cgp::core::field::impls`. +In [Context-Generic Programming (CGP)](/docs/), two types that share a subset of named fields or +variants can convert into one another generically, without a hand-written `From` or `TryFrom`. +Because CGP represents each record as a product of named fields and each enum as a sum of named +variants, a conversion becomes a matter of routing each named entry to the target's slot of the same +name. Each side derives the part of the extensible-data machinery its role needs, and the names are +matched at the type level. None of these traits is in the prelude. Import each from +`cgp::core::field::impls`. These traits cover the directions that routing can take. diff --git a/docs/reference/traits/type-level/append_product.md b/docs/reference/traits/type-level/append_product.md index 33530582..c288e059 100644 --- a/docs/reference/traits/type-level/append_product.md +++ b/docs/reference/traits/type-level/append_product.md @@ -11,10 +11,11 @@ Adding one entry to the end of a type-level product list. ## Overview -A struct's [shape](/docs/reference/glossary#shape) in CGP is a type-level list, a [`Product!`](../../macros/product.md) of named -fields. Code that processes such a shape generically sometimes needs to describe a *new* shape -computed from an old one: the shape a routine promises to return after adding a field, say, or a -bound relating an input shape to an output one. +A struct's [shape](/docs/reference/glossary#shape) in [Context-Generic Programming (CGP)](/docs/) is +a type-level list, a [`Product!`](../../macros/product.md) of named fields. Code that processes such +a shape generically sometimes needs to describe a *new* shape computed from an old one: the shape a +routine promises to return after adding a field, say, or a bound relating an input shape to an +output one. `AppendProduct` is that computation for a single entry. It takes a product and an item and names the product with that item added **at the end**. @@ -128,7 +129,7 @@ Because the recursion only ever rebuilds the list, order is structurally preserv appending yields a *different* type from prepending, and why two products with the same entries in different orders are unrelated types. -All of this is resolved during type checking. Nothing on this page is a `fn`. +All of this is resolved during type checking. Neither impl contains a `fn`. ## Common Mistakes diff --git a/docs/reference/traits/type-level/concat_product.md b/docs/reference/traits/type-level/concat_product.md index a76a0b93..acf1f71a 100644 --- a/docs/reference/traits/type-level/concat_product.md +++ b/docs/reference/traits/type-level/concat_product.md @@ -11,9 +11,10 @@ Splicing one type-level product list onto the end of another. ## Overview -Describing the result of combining two records means naming their combined [shape](/docs/reference/glossary#shape), and the shapes are -type-level lists, a [`Product!`](../../macros/product.md) of named fields each. -`ConcatProduct` names the list you get by following one product with another. +In [Context-Generic Programming (CGP)](/docs/), describing the result of combining two records means +naming their combined [shape](/docs/reference/glossary#shape), and the shapes are type-level lists, +a [`Product!`](../../macros/product.md) of named fields each. `ConcatProduct` names the list +you get by following one product with another. It is the general form of [`AppendProduct`](./append_product.md): **append is the single-entry special case of concat**, and that is the shortest way to hold both in mind. Like append, CGP itself diff --git a/docs/reference/traits/type-level/index.md b/docs/reference/traits/type-level/index.md index 5c53e6bf..645e64b0 100644 --- a/docs/reference/traits/type-level/index.md +++ b/docs/reference/traits/type-level/index.md @@ -10,12 +10,14 @@ The per-field state markers and list operations the extensible-data families are ## Overview -These are the least user-facing traits in the reference. They are the type-level layer beneath the +These are the least user-facing traits in the reference of +[Context-Generic Programming (CGP)](/docs/), which builds and reads Rust structs and enums +generically by their field and variant names. They are the type-level layer beneath the [builders](../builder/index.md), [extractors](../variant/index.md), and [casts](../casting/index.md): the markers that record what state one field is in, and the operations that grow and reshape a type's field list. You meet them in an error message from code that walks a -[shape](/docs/reference/glossary#shape) far more often than in code you wrote, and this group exists so that such a message is -legible. Most are not in the prelude. +[shape](/docs/reference/glossary#shape) far more often than in code you wrote, and this group exists +so that such a message is legible. Most are not in the prelude. The group divides into the state markers and the list operations. diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index ef345404..d01066cf 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -15,20 +15,23 @@ Rewriting every entry of a type-level list through one marker. **You are not expected to use `MapFields` directly.** CGP uses it to rewrite lists of providers: [`PipeMonadic`](../../providers/monad/pipe_monadic.md) maps its handler list through a promotion -marker, and the record builder's `BuildAndMergeOutputs` maps its handler list the same way. You will -most likely meet it in an error message from one of those; this page explains what it produces, and -how it differs from the two similarly-named traits beside it. The one case for naming it is generic -code that must describe a uniformly re-wrapped [shape](/docs/reference/glossary#shape). +marker, and the record-building provider +[`BuildAndMergeOutputs`](../../providers/dispatch/build_and_merge_outputs.md) maps its handler list +the same way. You will most likely meet it in an error message from one of those; this page explains +what it produces, and how it differs from the two similarly-named traits beside it. The one case for +naming it is generic code that must describe a uniformly re-wrapped +[shape](/docs/reference/glossary#shape). ::: ## Overview -Some type-level lists need every entry changed the same way: each value wrapped in an `Option`, or -replaced by `()`, or each provider wrapped in an adapter. Describing that as a type means rewriting -every entry of the list uniformly, and `MapFields` is that operation. The partial records and -enums of the extensible-data derives are not computed with it; [`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) -generates those types directly. +[Context-Generic Programming (CGP)](/docs/) describes a type's fields, and a pipeline's providers, +as type-level lists, and some of those lists need every entry changed the same way: each value +wrapped in an `Option`, or replaced by `()`, or each provider wrapped in an adapter. Describing that +as a type means rewriting every entry of the list uniformly, and `MapFields` is that +operation. The partial records and enums of the extensible-data derives are not computed with it; +[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) generates those types directly. The list's length and order never change. Each entry type `T` becomes `Mapper::Map`, where the mapper is a [`MapType`](./map_type.md) marker, so **the marker decides the whole effect**. With `IsPresent` it diff --git a/docs/reference/traits/type-level/map_type.md b/docs/reference/traits/type-level/map_type.md index c2060451..9f89440e 100644 --- a/docs/reference/traits/type-level/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -23,10 +23,11 @@ what each one means. The one case for bounding on the trait is generic code of y ## Overview -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. +[Context-Generic Programming (CGP)](/docs/) 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](../builder/has_builder.md) and [extractor](../variant/extract_field.md) families move a value through intermediate states without diff --git a/docs/reference/traits/type-level/map_type_ref.md b/docs/reference/traits/type-level/map_type_ref.md index 7e879848..0da94861 100644 --- a/docs/reference/traits/type-level/map_type_ref.md +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -22,10 +22,11 @@ explains what each one means and how it composes with the per-field markers. The ## Overview -[`MapType`](./map_type.md) decides whether a field of a partial type holds its value, nothing, or an -uninhabited type. A **borrowed** partial type needs a second decision on top: whether each payload is -held by shared reference, by mutable reference, or by value. That decision brings a lifetime with it, -which is why it needs its own trait. +In [Context-Generic Programming (CGP)](/docs/), a partial struct or enum tracks each field's state +in its type, and [`MapType`](./map_type.md) decides whether a field holds its value, nothing, or an +uninhabited type. A **borrowed** partial type needs a second decision on top: whether each payload +is held by shared reference, by mutable reference, or by value. That decision brings a lifetime with +it, which is why it needs its own trait. **The two families compose rather than compete.** A borrowed extractor carries one outer `MapTypeRef` marker shared across all fields and one [`MapType`](./map_type.md) marker per field, so a field's storage @@ -44,9 +45,10 @@ pub trait MapTypeRef { ``` `Map<'a, T>` is a **generic associated type** over both a lifetime and a type. The `T: 'a` bound -requires the payload to outlive the borrow, and the `: 'a` bound on the result keeps the storage type -from outliving it either. That is more machinery than [`MapType`](./map_type.md)'s single-parameter -`Map`, and it makes the borrowed shape expressible at whatever lifetime a caller has. +requires the payload to outlive the borrow, and the `: 'a` bound on the result requires the storage +type to live at least as long as the borrow too. That is more machinery than +[`MapType`](./map_type.md)'s single-parameter `Map`, and it makes the borrowed shape expressible +at whatever lifetime a caller has. ## Usage @@ -155,6 +157,7 @@ ones, and each payload slot projects through both. `cargo cgp expand` on a `Shape { Circle(Circle), Rectangle(Rectangle) }` deriving `ExtractField` shows it: ```rust +///The borrowed partial extractor for [`Shape`]. pub enum __PartialRefShape<'__a__, __R__: MapTypeRef, __F0__: MapType, __F1__: MapType> { Circle(<__F0__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Circle>>), Rectangle(<__F1__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Rectangle>>), @@ -169,7 +172,7 @@ through an owned value. The `T: 'a` bound and the `: 'a` bound on the associated type are what keep the projection well-formed: a payload cannot be borrowed for longer than it lives, and the resulting storage type -cannot outlive the borrow either. +stays valid for the whole of the borrow. ## Common Mistakes diff --git a/docs/reference/traits/type-level/transform_map.md b/docs/reference/traits/type-level/transform_map.md index 63a20d1b..ba3ba038 100644 --- a/docs/reference/traits/type-level/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -1,5 +1,5 @@ --- -title: 'TransformMap — convert a fields storage' +title: 'TransformMap — convert a field''s storage' sidebar_label: 'TransformMap' sidebar_position: 3 description: 'The per-field function converting a value from one marker''s storage to another''s, and the extension point for a new way to re-mark a record.' @@ -11,9 +11,11 @@ The per-field function that converts a value from one marker's storage to anothe ## Overview -[`MapType`](./map_type.md) only names storage *types*: it says that an `IsNothing` field holds `()` and -an `IsPresent` field holds its value, and nothing about how you get from one to the other. -`TransformMap` carries that missing half: the function that performs the conversion. +[Context-Generic Programming (CGP)](/docs/) tracks each field of a partial record with a type-level +marker, and [`MapType`](./map_type.md) only names each marker's storage *type*: it says that an +`IsNothing` field holds `()` and an `IsPresent` field holds its value, and nothing about how you get +from one to the other. `TransformMap` carries that missing half: the function that performs the +conversion. **This is the extension point of the whole partial-type scheme**, and it is genuinely usable. Defining a new way to re-mark a record means writing one impl per source state and then applying it with diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index 88ab5bd7..cf628718 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -24,9 +24,10 @@ or writing an operation that re-marks a whole record. ## Overview -[`TransformMap`](./transform_map.md) converts *one* field from one marker's storage to another's. -`TransformMapFields` lifts that conversion across an entire partial record, so every field is re-marked -in one call. +In [Context-Generic Programming (CGP)](/docs/), where each field of a partial record carries a +type-level marker, [`TransformMap`](./transform_map.md) converts *one* field from one marker's +storage to another's. `TransformMapFields` lifts that conversion across an entire partial record, so +every field is re-marked in one call. **This is the motion the optional-field layer is made of.** [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) re-marks every field to From 9ac6261700158671b44dbd85f1973b333c948105 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 20:01:44 +0100 Subject: [PATCH 276/516] Name the project on the formatting and monad trait pages The nine formatting and monad pages and the trait section's index now name Context-Generic Programming in their opening paragraphs, and the index relates the tag line to the wiring traits it introduces. The `StaticString` title gains the apostrophe in `&'static`, and the `StaticString` and `ConcatPath` pages no longer call the group three recovery traits, since `ConcatPath` composes paths rather than recovering a string. Co-Authored-By: Claude Opus 5.5 --- docs/reference/traits/formatting/concat_path.md | 14 +++++++------- docs/reference/traits/formatting/index.md | 9 +++++---- docs/reference/traits/formatting/static_format.md | 7 ++++--- docs/reference/traits/formatting/static_string.md | 12 ++++++------ docs/reference/traits/index.md | 10 ++++++---- docs/reference/traits/monad/contains_value.md | 7 ++++--- docs/reference/traits/monad/index.md | 13 +++++++------ docs/reference/traits/monad/lift_value.md | 7 ++++--- docs/reference/traits/monad/monadic_bind.md | 7 ++++--- docs/reference/traits/monad/monadic_trans.md | 3 ++- 10 files changed, 49 insertions(+), 40 deletions(-) diff --git a/docs/reference/traits/formatting/concat_path.md b/docs/reference/traits/formatting/concat_path.md index ff903ea2..326cbf74 100644 --- a/docs/reference/traits/formatting/concat_path.md +++ b/docs/reference/traits/formatting/concat_path.md @@ -25,11 +25,11 @@ writing one out. ## Overview -A [`Path!`](../../macros/path.md) is a type-level list of segments: the route a namespaced or -`open`-dispatched component lookup is redirected along. Composing two such routes means splicing one -list onto the end of another, and `ConcatPath` is that operation. It is the path-level analogue of -[`ConcatProduct`](../type-level/concat_product.md), with the same two-impl recursion over a -different list. +In [Context-Generic Programming (CGP)](/docs/), a [`Path!`](../../macros/path.md) is a type-level +list of segments: the route a namespaced or `open`-dispatched component lookup is redirected along. +Composing two such routes means splicing one list onto the end of another, and `ConcatPath` is that +operation. It is the path-level analogue of [`ConcatProduct`](../type-level/concat_product.md), with +the same two-impl recursion over a different list. ## Definition @@ -50,8 +50,8 @@ nothing runs. ## Usage **`ConcatPath` is in the prelude**: `use cgp::prelude::*;` names it, which makes it the one member -of the type-level recovery group that comes with the prelude. Its two neighbours each need a -different import: [`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and +of this group that comes with the prelude. Its two neighbours each need a different import: +[`StaticString`](./static_string.md) comes from `cgp::core::field::traits`, and [`StaticFormat`](./static_format.md), defined in the same crate as this trait, from `cgp::core::base::traits`. diff --git a/docs/reference/traits/formatting/index.md b/docs/reference/traits/formatting/index.md index 54b39474..1ca6d54d 100644 --- a/docs/reference/traits/formatting/index.md +++ b/docs/reference/traits/formatting/index.md @@ -10,10 +10,11 @@ Recovering a field name or a routing path as runtime data. ## Overview -CGP encodes field and variant names as *types*, so that a name can drive trait resolution. A program -eventually needs those names as ordinary strings, to report a missing field, to build a key, or to render -a path, and these traits are how a name comes back out. They sit in three different homes, which -is the group's sharpest edge: one is in the prelude and the other two each need a different import. +[Context-Generic Programming (CGP)](/docs/) encodes field and variant names as *types*, so that a +name can drive trait resolution. A program eventually needs those names as ordinary strings, to +report a missing field, to build a key, or to render a path, and these traits are how a name comes +back out. They sit in three different homes, which is the group's sharpest edge: one is in the +prelude and the other two each need a different import. - [`StaticString`](static_string.md) decodes a [`Symbol!`](../../macros/symbol.md) into a compile-time `&'static str` constant. This is the one to reach for when you need a name as data. Import it from diff --git a/docs/reference/traits/formatting/static_format.md b/docs/reference/traits/formatting/static_format.md index 6169d10b..107e2ce4 100644 --- a/docs/reference/traits/formatting/static_format.md +++ b/docs/reference/traits/formatting/static_format.md @@ -22,9 +22,10 @@ and the narrow case where bounding on it is the answer. ## Overview -CGP encodes field and variant names as *types*, so a name can drive trait resolution. Printing one means -turning that type back into characters, and `StaticFormat` is the trait that does it **lazily**, by -writing into a formatter rather than producing a value. +[Context-Generic Programming (CGP)](/docs/) encodes field and variant names as *types*, so a name +can drive trait resolution. Printing one means turning that type back into characters, and +`StaticFormat` is the trait that does it **lazily**, by writing into a formatter rather than +producing a value. **It backs the `Display` impls on `Symbol` and `Chars`**, which is how you usually meet it: a type-level string can be printed with `{}` or `to_string()` because of this trait. diff --git a/docs/reference/traits/formatting/static_string.md b/docs/reference/traits/formatting/static_string.md index ae1aa1a0..1b5ff3f2 100644 --- a/docs/reference/traits/formatting/static_string.md +++ b/docs/reference/traits/formatting/static_string.md @@ -1,5 +1,5 @@ --- -title: 'StaticString — a symbol as a &static str' +title: 'StaticString — a symbol as a &''static str' sidebar_label: 'StaticString' sidebar_position: 1 description: 'Decode a Symbol into a compile-time &''static str constant, the eager way to recover a field or variant name as data.' @@ -11,14 +11,14 @@ Recovering a [type-level string](/docs/reference/glossary#type-level-string) as ## Overview -CGP encodes field and variant names as *types* (a [`Symbol!`](../../macros/symbol.md) is a length plus a -character list, one node per character) so that names can drive trait resolution. But a program -eventually needs those names as ordinary strings: to report a missing field, to build a key, to compare -against input. +[Context-Generic Programming (CGP)](/docs/) encodes field and variant names as *types* (a +[`Symbol!`](../../macros/symbol.md) is a length plus a character list, one node per character) so +that names can drive trait resolution. But a program eventually needs those names as ordinary +strings: to report a missing field, to build a key, to compare against input. `StaticString` is how a name comes back out, and it does it **eagerly**. -**This is the one of the three recovery traits to reach for.** Its sibling +**This is the recovery trait to reach for.** Its sibling [`StaticFormat`](./static_format.md) recovers a name lazily by writing into a formatter, which backs `Display`; reach for it only where a value to format is missing and a constant will not do. diff --git a/docs/reference/traits/index.md b/docs/reference/traits/index.md index 7cbaab5d..9eed0df0 100644 --- a/docs/reference/traits/index.md +++ b/docs/reference/traits/index.md @@ -6,10 +6,12 @@ sidebar_position: 0 # Traits -The traits on these pages are the machinery CGP's macros generate and consume. A component definition, -a wiring table, a derive, or a field read all expand into impls of these traits, so you meet the names -here in an expansion or a compiler error far more often than you write them. This section groups the -traits by the job they do, so that a name from a diagnostic has a page to land on. +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, chosen +at compile time, and the traits on these pages are the machinery its macros generate and consume. A +component definition, a wiring table, a derive, or a field read all expand into impls of these +traits, so you meet the names here in an expansion or a compiler error far more often than you write +them. This section groups the traits by the job they do, so that a name from a diagnostic has a page +to land on. If you are new to CGP, start with the [reference overview](/docs/reference/) rather than here. This page is the fuller map for once the essentials are familiar. diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index 3b8fbd3f..91f70235 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -22,9 +22,10 @@ page is here to explain how a step unwraps its input. ## Overview -A step in a [monadic pipeline](/docs/concepts/monadic-handlers) produces a wrapped output, a `Result`, -say, and the next step needs the value *inside* the wrapper for the branch that continues. Which half of -the wrapper that is depends on the monad, so it cannot be hard-coded. +When [Context-Generic Programming (CGP)](/docs/) composes handlers into a +[monadic pipeline](/docs/concepts/monadic-handlers), each step produces a wrapped output, a +`Result`, say, and the next step needs the value *inside* the wrapper for the branch that continues. +Which half of the wrapper that is depends on the monad, so it cannot be hard-coded. `ContainsValue` is where each monad answers it. diff --git a/docs/reference/traits/monad/index.md b/docs/reference/traits/monad/index.md index aa3d2ec5..0c7baabc 100644 --- a/docs/reference/traits/monad/index.md +++ b/docs/reference/traits/monad/index.md @@ -10,13 +10,14 @@ The traits that give a monad marker its meaning for monadic handler composition. ## Overview -A [monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue -or short-circuit, the `?`-style behaviour, expressed as composable providers. A monad in CGP is a +[Context-Generic Programming (CGP)](/docs/) composes handlers into pipelines at compile time, and a +[monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue or +short-circuit, the `?`-style behaviour, expressed as composable providers. A monad in CGP is a zero-sized marker, and these four traits are what give that marker meaning. They are plain traits -rather than CGP components: they lack a generated provider trait and are never wired. The [monad -providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a pipeline -at compile time, so you name a trait here only when defining a monad of your own. Import each from -`cgp::extra::monad::traits`. +rather than CGP components: they lack a generated provider trait and are never wired. The +[monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a +pipeline at compile time, so you name a trait here only when defining a monad of your own. Import +each from `cgp::extra::monad::traits`. They split into the pair that folds the pipeline and the pair that runs one step. diff --git a/docs/reference/traits/monad/lift_value.md b/docs/reference/traits/monad/lift_value.md index 0f778d55..d33e3a24 100644 --- a/docs/reference/traits/monad/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -23,10 +23,11 @@ one. ## Overview -A bind step in a [monadic pipeline](/docs/concepts/monadic-handlers) unwraps a value, runs a +In [Context-Generic Programming (CGP)](/docs/), which composes handlers into pipelines at compile +time, a bind step in a [monadic pipeline](/docs/concepts/monadic-handlers) unwraps a value, runs a continuation or short-circuits, and then has to produce the step's own output. Producing it means -wrapping something back up, and there are **two** things that might need wrapping, so this trait has two -methods rather than one. +wrapping something back up, and there are **two** things that might need wrapping, so this trait has +two methods rather than one. It is the counterpart of [`ContainsValue`](./contains_value.md): that one says how to get *out* of an output type, this one how to get back *in*. Together they run one step; the other two monad traits, diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index 4ff90ab6..0bf10af9 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -22,10 +22,11 @@ otherwise this page is here to explain how a pipeline is assembled. ## Overview -A [monadic pipeline](/docs/concepts/monadic-handlers) chains steps where each may either continue or +[Context-Generic Programming (CGP)](/docs/) composes handlers into pipelines at compile time, and a +[monadic pipeline](/docs/concepts/monadic-handlers) chains steps where each may either continue or short-circuit, the familiar `?`-style behaviour, expressed as composable providers rather than as -syntax. Folding such a pipeline means asking the monad, once per step: *given everything built so far, -what provider runs one bind?* +syntax. Folding such a pipeline means asking the monad, once per step: *given everything built so +far, what provider runs one bind?* `MonadicBind` is that question. diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index 42bc1c0c..640d5ca9 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -22,7 +22,8 @@ a monad of your own a transformer form; otherwise this page is here to explain h ## Overview -A [monadic pipeline](/docs/concepts/monadic-handlers) over a nested output, a `Result` inside a +[Context-Generic Programming (CGP)](/docs/) composes handlers into pipelines at compile time. A +[monadic pipeline](/docs/concepts/monadic-handlers) over a nested output, a `Result` inside a `Result`, needs to peel more than one layer, and hard-coding a depth would give up the composability the design exists for. `MonadicTrans` is how a monad is expressed as a *transformer* over another. From 89719dbe9cbf796d5c05d8e56ab7e79516b04aaf Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 20:07:37 +0100 Subject: [PATCH 277/516] Show the companions' doc lines and spell out the name first Every expansion block on the derive and trait pages now shows the doc line the derives put on each partial companion, as `cargo cgp expand` prints it. Eight trait pages used "CGP" in their generated-machinery notice, above the paragraph that first names Context-Generic Programming; the notices now say "the library". The `TransformOptional` page no longer says `TransformMapDefault` cannot apply to a field type without `Default`, since its `IsPresent` impl needs no bound. Co-Authored-By: Claude Opus 5.5 --- docs/reference/derives/derive_build_field.md | 1 + docs/reference/derives/derive_cgp_record.md | 1 + docs/reference/derives/derive_cgp_variant.md | 1 + docs/reference/derives/derive_extract_field.md | 2 ++ docs/reference/traits/monad/contains_value.md | 6 +++--- docs/reference/traits/monad/lift_value.md | 9 ++++----- docs/reference/traits/monad/monadic_bind.md | 6 +++--- docs/reference/traits/monad/monadic_trans.md | 7 ++++--- docs/reference/traits/optional/transform_optional.md | 6 +++--- docs/reference/traits/type-level/map_fields.md | 2 +- docs/reference/traits/type-level/map_type.md | 12 +++++++----- docs/reference/traits/type-level/map_type_ref.md | 9 +++++---- .../traits/type-level/transform_map_fields.md | 2 +- docs/reference/traits/variant/extract_field.md | 1 + docs/reference/traits/variant/has_extractor_ref.md | 1 + 15 files changed, 38 insertions(+), 28 deletions(-) diff --git a/docs/reference/derives/derive_build_field.md b/docs/reference/derives/derive_build_field.md index cdc1f2b4..6376fb20 100644 --- a/docs/reference/derives/derive_build_field.md +++ b/docs/reference/derives/derive_build_field.md @@ -203,6 +203,7 @@ pub struct Person { The generated companion wraps each field in its corresponding marker: ```rust +///The partial builder for [`Person`]. pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { pub first_name: <__F0__ as MapType>::Map, pub last_name: <__F1__ as MapType>::Map, diff --git a/docs/reference/derives/derive_cgp_record.md b/docs/reference/derives/derive_cgp_record.md index 6f036024..c0b11deb 100644 --- a/docs/reference/derives/derive_cgp_record.md +++ b/docs/reference/derives/derive_cgp_record.md @@ -142,6 +142,7 @@ The builder output adds a companion type, as documented for stores `()`: ```rust +///The partial builder for [`Person`]. pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { pub first_name: <__F0__ as MapType>::Map, pub last_name: <__F1__ as MapType>::Map, diff --git a/docs/reference/derives/derive_cgp_variant.md b/docs/reference/derives/derive_cgp_variant.md index 466a27c2..afe93f2a 100644 --- a/docs/reference/derives/derive_cgp_variant.md +++ b/docs/reference/derives/derive_cgp_variant.md @@ -181,6 +181,7 @@ extraction, as documented for [`#[derive(ExtractField)]`](./derive_extract_field and `IsVoid` maps it to the uninhabited `Void`: ```rust +///The partial extractor for [`Shape`]. pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { Circle(<__F0__ as MapType>::Map), Rectangle(<__F1__ as MapType>::Map), diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index b45a7931..1bd6adec 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -212,11 +212,13 @@ pub enum Shape { The companion enums wrap each payload in the corresponding marker projections: ```rust +///The partial extractor for [`Shape`]. pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { Circle(<__F0__ as MapType>::Map), Rectangle(<__F1__ as MapType>::Map), } +///The borrowed partial extractor for [`Shape`]. pub enum __PartialRefShape<'__a__, __R__: MapTypeRef, __F0__: MapType, __F1__: MapType> { Circle(<__F0__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Circle>>), Rectangle(<__F1__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Rectangle>>), diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index 91f70235..74392a44 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -14,9 +14,9 @@ Naming the value a monad threads forward out of a step's output. ### Generated machinery **You are not expected to name `ContainsValue`.** The -[bind providers](../../providers/monad/index.md) use it while running a step, and the monad markers CGP -ships already implement it. The one case for naming it is defining a monad of your own; otherwise this -page is here to explain how a step unwraps its input. +[bind providers](../../providers/monad/index.md) use it while running a step, and the monad markers +the library ships already implement it. The one case for naming it is defining a monad of your own; +otherwise this page is here to explain how a step unwraps its input. ::: diff --git a/docs/reference/traits/monad/lift_value.md b/docs/reference/traits/monad/lift_value.md index d33e3a24..0eddb866 100644 --- a/docs/reference/traits/monad/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -13,11 +13,10 @@ Putting a value back into a monad's output type, on either branch. ### Generated machinery -**You are not expected to name `LiftValue`.** The -[bind providers](../../providers/monad/index.md) use it while running a step, and the monad markers CGP -ships already implement it. The one case for naming it is defining a monad of your own; otherwise this -page is here to explain how a step produces its output, and why that takes two methods rather than -one. +**You are not expected to name `LiftValue`.** The [bind providers](../../providers/monad/index.md) +use it while running a step, and the monad markers the library ships already implement it. The one +case for naming it is defining a monad of your own; otherwise this page is here to explain how a +step produces its output, and why that takes two methods rather than one. ::: diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index 0bf10af9..e4ad4ca0 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -14,9 +14,9 @@ Turning a continuation into one bind step of a monadic pipeline. ### Generated machinery **You are not expected to name `MonadicBind`.** -[`PipeMonadic`](../../providers/monad/pipe_monadic.md) bounds on it while folding a pipeline, and the monad -markers CGP ships already implement it. The one case for naming it is defining a monad of your own; -otherwise this page is here to explain how a pipeline is assembled. +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) bounds on it while folding a pipeline, and +the monad markers the library ships already implement it. The one case for naming it is defining a +monad of your own; otherwise this page is here to explain how a pipeline is assembled. ::: diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index 640d5ca9..4996e6c9 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -14,9 +14,10 @@ Stacking one monad on top of another. ### Generated machinery **You are not expected to name `MonadicTrans`.** -[`PipeMonadic`](../../providers/monad/pipe_monadic.md) resolves a stacked monad through it before any binding -happens, and the transformer markers CGP ships already implement it. The one case for naming it is giving -a monad of your own a transformer form; otherwise this page is here to explain how monads stack. +[`PipeMonadic`](../../providers/monad/pipe_monadic.md) resolves a stacked monad through it before +any binding happens, and the transformer markers the library ships already implement it. The one +case for naming it is giving a monad of your own a transformer form; otherwise this page is here to +explain how monads stack. ::: diff --git a/docs/reference/traits/optional/transform_optional.md b/docs/reference/traits/optional/transform_optional.md index 1cf230aa..26a205c6 100644 --- a/docs/reference/traits/optional/transform_optional.md +++ b/docs/reference/traits/optional/transform_optional.md @@ -179,9 +179,9 @@ again; [`ToOptional`](./to_optional.md#common-mistakes) shows the error. **It is a marker, not an operation.** It lacks a method and needs nothing wired. It is named in a bound. -**It requires nothing of the field types**, so it applies to a field type without `Default`, which -[`TransformMapDefault`](./transform_map_default.md) does not. The missing `IsOptional` impl is the -other difference, in the opposite direction. +**It requires nothing of the field types**, where +[`TransformMapDefault`](./transform_map_default.md) needs `Default` for every field not already +`IsPresent`. The missing `IsOptional` impl is the other difference, in the opposite direction. **Converting gives up the compile-time completeness check**, since every field becomes optional whether it was set or not. diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index d01066cf..c12f3996 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -13,7 +13,7 @@ Rewriting every entry of a type-level list through one marker. ### Generated machinery -**You are not expected to use `MapFields` directly.** CGP uses it to rewrite lists of providers: +**You are not expected to use `MapFields` directly.** The library uses it to rewrite lists of providers: [`PipeMonadic`](../../providers/monad/pipe_monadic.md) maps its handler list through a promotion marker, and the record-building provider [`BuildAndMergeOutputs`](../../providers/dispatch/build_and_merge_outputs.md) maps its handler list diff --git a/docs/reference/traits/type-level/map_type.md b/docs/reference/traits/type-level/map_type.md index 9f89440e..a238dcfa 100644 --- a/docs/reference/traits/type-level/map_type.md +++ b/docs/reference/traits/type-level/map_type.md @@ -13,11 +13,12 @@ The marker trait that decides how one field of a partial type is stored. ### Generated machinery -**You are not expected to implement `MapType`.** Its four markers are supplied by CGP, -and the partial types parameterized by them are generated by -[`#[derive(CgpData)]`](../../derives/derive_cgp_data.md) 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. +**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)]`](../../derives/derive_cgp_data.md) 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. ::: @@ -162,6 +163,7 @@ Where the function is applied is in a generated partial type. The derive adds on field and wraps each field's declared type in that parameter's projection: ```rust +///The partial builder for [`Person`]. pub struct __PartialPerson<__F0__: MapType, __F1__: MapType> { pub first_name: <__F0__ as MapType>::Map, pub last_name: <__F1__ as MapType>::Map, diff --git a/docs/reference/traits/type-level/map_type_ref.md b/docs/reference/traits/type-level/map_type_ref.md index 0da94861..76d11e4b 100644 --- a/docs/reference/traits/type-level/map_type_ref.md +++ b/docs/reference/traits/type-level/map_type_ref.md @@ -13,10 +13,11 @@ The marker trait deciding how a borrowed partial type holds its payloads. ### Generated machinery -**You are not expected to implement `MapTypeRef`.** Its three markers are supplied -by CGP, and [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) generates the borrowed -companion that carries one. What you do with this trait is recognize its markers in an error; this page -explains what each one means and how it composes with the per-field markers. The one case for bounding on the trait is generic code of your own over a borrowed partial type's outer marker. +**You are not expected to implement `MapTypeRef`.** Its three markers are supplied by the library, +and [`#[derive(ExtractField)]`](../../derives/derive_extract_field.md) generates the borrowed +companion that carries one. What you do with this trait is recognize its markers in an error; this +page explains what each one means and how it composes with the per-field markers. The one case for +bounding on the trait is generic code of your own over a borrowed partial type's outer marker. ::: diff --git a/docs/reference/traits/type-level/transform_map_fields.md b/docs/reference/traits/type-level/transform_map_fields.md index cf628718..3c629e6e 100644 --- a/docs/reference/traits/type-level/transform_map_fields.md +++ b/docs/reference/traits/type-level/transform_map_fields.md @@ -13,7 +13,7 @@ Applying one per-field transform across a whole [partial record](/docs/reference ### Generated machinery -**You are not expected to call `transform_map_fields` for CGP's own conversions.** It is the +**You are not expected to call `transform_map_fields` for the library's own conversions.** It is the recursion the optional-field layer is built from, and [`CanFinalizeWithDefault`](../optional/can_finalize_with_default.md) and [`ToOptional`](../optional/to_optional.md) are what you call. This page explains the walk, which diff --git a/docs/reference/traits/variant/extract_field.md b/docs/reference/traits/variant/extract_field.md index fc9b24a3..96934acf 100644 --- a/docs/reference/traits/variant/extract_field.md +++ b/docs/reference/traits/variant/extract_field.md @@ -161,6 +161,7 @@ variant, each payload wrapped in that parameter's projection. `cargo cgp expand` `Shape` shows it: ```rust +///The partial extractor for [`Shape`]. pub enum __PartialShape<__F0__: MapType, __F1__: MapType> { Circle(<__F0__ as MapType>::Map), Rectangle(<__F1__ as MapType>::Map), diff --git a/docs/reference/traits/variant/has_extractor_ref.md b/docs/reference/traits/variant/has_extractor_ref.md index 48903602..ea7c9184 100644 --- a/docs/reference/traits/variant/has_extractor_ref.md +++ b/docs/reference/traits/variant/has_extractor_ref.md @@ -126,6 +126,7 @@ The borrowing accessors use a **second companion enum**, `__PartialRefShape`, be `__PartialShape`. `cargo cgp expand` on the example's `Shape` shows it: ```rust +///The borrowed partial extractor for [`Shape`]. pub enum __PartialRefShape<'__a__, __R__: MapTypeRef, __F0__: MapType, __F1__: MapType> { Circle(<__F0__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Circle>>), Rectangle(<__F1__ as MapType>::Map<<__R__ as MapTypeRef>::Map<'__a__, Rectangle>>), From d2bd6125810e715c0a2d9a92b93869e2a343a1b2 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 20:25:50 +0100 Subject: [PATCH 278/516] Gloss providers and frame the formatting group exactly The monad pages, `MapFields`, and `TransformMap` now link "provider" and "provider trait" to the glossary on first use. The formatting index and its line in the trait index say that two traits recover a name as runtime data and the third joins type-level paths, since `ConcatPath` computes only a type. The `CanDowncastFields` description no longer says the trait is never used on its own, which its page contradicts. Co-Authored-By: Claude Opus 5.5 --- .../traits/casting/can_downcast_fields.md | 2 +- docs/reference/traits/formatting/index.md | 11 ++++++----- docs/reference/traits/index.md | 2 +- docs/reference/traits/monad/contains_value.md | 4 ++-- docs/reference/traits/monad/index.md | 11 ++++++----- docs/reference/traits/monad/lift_value.md | 4 ++-- docs/reference/traits/monad/monadic_bind.md | 16 ++++++++-------- docs/reference/traits/monad/monadic_trans.md | 8 ++++---- docs/reference/traits/type-level/map_fields.md | 3 ++- .../reference/traits/type-level/transform_map.md | 3 ++- 10 files changed, 34 insertions(+), 30 deletions(-) diff --git a/docs/reference/traits/casting/can_downcast_fields.md b/docs/reference/traits/casting/can_downcast_fields.md index 6affca94..e64b51bc 100644 --- a/docs/reference/traits/casting/can_downcast_fields.md +++ b/docs/reference/traits/casting/can_downcast_fields.md @@ -2,7 +2,7 @@ title: 'CanDowncastFields — continue a narrowing' sidebar_label: 'CanDowncastFields' sidebar_position: 3 -description: 'Continue narrowing on the remainder a failed downcast hands back, so a value can be tried against a second target and a third. Never used on its own.' +description: 'Narrow an extractor into a target enum, most often the remainder a failed downcast hands back, so a value can be tried against a second target and a third.' --- # `CanDowncastFields` diff --git a/docs/reference/traits/formatting/index.md b/docs/reference/traits/formatting/index.md index 1ca6d54d..650bfb9b 100644 --- a/docs/reference/traits/formatting/index.md +++ b/docs/reference/traits/formatting/index.md @@ -1,20 +1,21 @@ --- sidebar_label: 'Overview' sidebar_position: 0 -description: 'The traits that recover type-level names and paths as runtime data: a symbol as a constant string, a symbol written into a formatter, and joined paths.' +description: 'The traits that recover a type-level name as runtime data, as a constant string or written into a formatter, and the one that joins two type-level paths.' --- # Type-level strings and paths -Recovering a field name or a routing path as runtime data. +Recovering a field name as runtime data, and joining the paths a lookup follows. ## Overview [Context-Generic Programming (CGP)](/docs/) encodes field and variant names as *types*, so that a name can drive trait resolution. A program eventually needs those names as ordinary strings, to -report a missing field, to build a key, or to render a path, and these traits are how a name comes -back out. They sit in three different homes, which is the group's sharpest edge: one is in the -prelude and the other two each need a different import. +report a missing field or to build a key, and two of these traits are how a name comes back out, +while the third joins the type-level paths a redirected lookup follows. They sit in three different +homes, which is the group's sharpest edge: one is in the prelude and the other two each need a +different import. - [`StaticString`](static_string.md) decodes a [`Symbol!`](../../macros/symbol.md) into a compile-time `&'static str` constant. This is the one to reach for when you need a name as data. Import it from diff --git a/docs/reference/traits/index.md b/docs/reference/traits/index.md index 9eed0df0..aaf5c37e 100644 --- a/docs/reference/traits/index.md +++ b/docs/reference/traits/index.md @@ -52,7 +52,7 @@ Three smaller groups each serve one area: - [Namespaces and defaults](namespace/index.md) are the lookup traits behind a namespace and a per-type default. -- [Type-level strings and paths](formatting/index.md) recover a field name or a path as runtime data. +- [Type-level strings and paths](formatting/index.md) recover a field name as runtime data and join type-level paths. - [Monad interface](monad/index.md) holds the four traits that give a monad marker its meaning for monadic handler composition. diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index 74392a44..18e290ab 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -34,8 +34,8 @@ It is one of four traits that give a monad marker its meaning, and it pairs with back *in*. The other two, [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline rather than run a step of it. -**This is a plain trait, not a CGP component.** It lacks a generated provider trait and is -never wired. +**This is a plain trait, not a CGP component.** It lacks a generated +[provider trait](/docs/reference/glossary#provider-trait) and is never wired. ## Definition diff --git a/docs/reference/traits/monad/index.md b/docs/reference/traits/monad/index.md index 0c7baabc..cb477b07 100644 --- a/docs/reference/traits/monad/index.md +++ b/docs/reference/traits/monad/index.md @@ -12,11 +12,12 @@ The traits that give a monad marker its meaning for monadic handler composition. [Context-Generic Programming (CGP)](/docs/) composes handlers into pipelines at compile time, and a [monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue or -short-circuit, the `?`-style behaviour, expressed as composable providers. A monad in CGP is a -zero-sized marker, and these four traits are what give that marker meaning. They are plain traits -rather than CGP components: they lack a generated provider trait and are never wired. The -[monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a -pipeline at compile time, so you name a trait here only when defining a monad of your own. Import +short-circuit, the `?`-style behaviour, expressed as composable +[providers](/docs/reference/glossary#provider). A monad in CGP is a zero-sized marker, and these +four traits are what give that marker meaning. They are plain traits rather than CGP components: +they lack a generated [provider trait](/docs/reference/glossary#provider-trait) and are never wired. +The [monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding +a pipeline at compile time, so you name a trait here only when defining a monad of your own. Import each from `cgp::extra::monad::traits`. They split into the pair that folds the pipeline and the pair that runs one step. diff --git a/docs/reference/traits/monad/lift_value.md b/docs/reference/traits/monad/lift_value.md index 0eddb866..2320f812 100644 --- a/docs/reference/traits/monad/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -32,8 +32,8 @@ It is the counterpart of [`ContainsValue`](./contains_value.md): that one says h output type, this one how to get back *in*. Together they run one step; the other two monad traits, [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline instead. -**This is a plain trait, not a CGP component.** It lacks a generated provider trait and is -never wired. +**This is a plain trait, not a CGP component.** It lacks a generated +[provider trait](/docs/reference/glossary#provider-trait) and is never wired. ## Definition diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index e4ad4ca0..04015446 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -24,9 +24,9 @@ monad of your own; otherwise this page is here to explain how a pipeline is asse [Context-Generic Programming (CGP)](/docs/) composes handlers into pipelines at compile time, and a [monadic pipeline](/docs/concepts/monadic-handlers) chains steps where each may either continue or -short-circuit, the familiar `?`-style behaviour, expressed as composable providers rather than as -syntax. Folding such a pipeline means asking the monad, once per step: *given everything built so -far, what provider runs one bind?* +short-circuit, the familiar `?`-style behaviour, expressed as composable +[providers](/docs/reference/glossary#provider) rather than as syntax. Folding such a pipeline means +asking the monad, once per step: *given everything built so far, what provider runs one bind?* `MonadicBind` is that question. @@ -34,11 +34,11 @@ It is one of four traits that give a monad marker its meaning, alongside [`ContainsValue`](./contains_value.md), [`LiftValue`](./lift_value.md), and [`MonadicTrans`](./monadic_trans.md). Keeping them apart lets one marker serve all four roles. -**This is a plain trait, not a CGP component.** It lacks a generated provider trait and a -`…Component` marker, and is never wired through -[`delegate_components!`](../../macros/delegate_components.md): the [monad -providers](../../providers/monad/index.md) consume it as an ordinary trait bound while folding a -pipeline at compile time. +**This is a plain trait, not a CGP component.** It lacks a generated +[provider trait](/docs/reference/glossary#provider-trait) and a `…Component` marker, and is never +wired through [`delegate_components!`](../../macros/delegate_components.md): the +[monad providers](../../providers/monad/index.md) consume it as an ordinary trait bound while +folding a pipeline at compile time. ## Definition diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index 4996e6c9..f241ed49 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -30,11 +30,11 @@ the design exists for. `MonadicTrans` is how a monad is expressed as a *transfor It is one of four traits that give a monad marker its meaning, and it belongs with [`MonadicBind`](./monadic_bind.md) as the pipeline-folding half: those two decide the *shape* of the -composed provider, while [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) run -each step. +composed [provider](/docs/reference/glossary#provider), while [`ContainsValue`](./contains_value.md) +and [`LiftValue`](./lift_value.md) run each step. -**This is a plain trait, not a CGP component.** It lacks a generated provider trait and is -never wired. +**This is a plain trait, not a CGP component.** It lacks a generated +[provider trait](/docs/reference/glossary#provider-trait) and is never wired. ## Definition diff --git a/docs/reference/traits/type-level/map_fields.md b/docs/reference/traits/type-level/map_fields.md index c12f3996..23d1c709 100644 --- a/docs/reference/traits/type-level/map_fields.md +++ b/docs/reference/traits/type-level/map_fields.md @@ -13,7 +13,8 @@ Rewriting every entry of a type-level list through one marker. ### Generated machinery -**You are not expected to use `MapFields` directly.** The library uses it to rewrite lists of providers: +**You are not expected to use `MapFields` directly.** The library uses it to rewrite lists of +[providers](/docs/reference/glossary#provider): [`PipeMonadic`](../../providers/monad/pipe_monadic.md) maps its handler list through a promotion marker, and the record-building provider [`BuildAndMergeOutputs`](../../providers/dispatch/build_and_merge_outputs.md) maps its handler list diff --git a/docs/reference/traits/type-level/transform_map.md b/docs/reference/traits/type-level/transform_map.md index ba3ba038..48577824 100644 --- a/docs/reference/traits/type-level/transform_map.md +++ b/docs/reference/traits/type-level/transform_map.md @@ -49,7 +49,8 @@ use cgp::core::field::traits::TransformMap; ``` The trait is implemented on a **transform marker**, a zero-sized type you declare. It stores nothing -and exists only to name the set of conversions, exactly as a provider does elsewhere in CGP. +and exists only to name the set of conversions, exactly as a +[provider](/docs/reference/glossary#provider) does elsewhere in CGP. **A transform needs an impl for every source marker a field might currently be in.** That rule decides how many impls you write, and getting it wrong is the usual failure, shown in From 22919069258d69bca5682dba885e8ce8cee744f9 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 20:33:08 +0100 Subject: [PATCH 279/516] Gloss "CGP component" on the monad trait pages The monad pages say their traits are not CGP components; that first use now links the glossary's component entry, as "provider" already does. Co-Authored-By: Claude Opus 5.5 --- docs/reference/traits/monad/contains_value.md | 4 ++-- docs/reference/traits/monad/index.md | 9 +++++---- docs/reference/traits/monad/lift_value.md | 4 ++-- docs/reference/traits/monad/monadic_bind.md | 6 +++--- docs/reference/traits/monad/monadic_trans.md | 4 ++-- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/docs/reference/traits/monad/contains_value.md b/docs/reference/traits/monad/contains_value.md index 18e290ab..6abc0c59 100644 --- a/docs/reference/traits/monad/contains_value.md +++ b/docs/reference/traits/monad/contains_value.md @@ -34,8 +34,8 @@ It is one of four traits that give a monad marker its meaning, and it pairs with back *in*. The other two, [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline rather than run a step of it. -**This is a plain trait, not a CGP component.** It lacks a generated -[provider trait](/docs/reference/glossary#provider-trait) and is never wired. +**This is a plain trait, not a [CGP component](/docs/reference/glossary#component).** It lacks a +generated [provider trait](/docs/reference/glossary#provider-trait) and is never wired. ## Definition diff --git a/docs/reference/traits/monad/index.md b/docs/reference/traits/monad/index.md index cb477b07..29267c9d 100644 --- a/docs/reference/traits/monad/index.md +++ b/docs/reference/traits/monad/index.md @@ -14,10 +14,11 @@ The traits that give a monad marker its meaning for monadic handler composition. [monadic pipeline](/docs/concepts/monadic-handlers) chains handlers where each step may continue or short-circuit, the `?`-style behaviour, expressed as composable [providers](/docs/reference/glossary#provider). A monad in CGP is a zero-sized marker, and these -four traits are what give that marker meaning. They are plain traits rather than CGP components: -they lack a generated [provider trait](/docs/reference/glossary#provider-trait) and are never wired. -The [monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding -a pipeline at compile time, so you name a trait here only when defining a monad of your own. Import +four traits are what give that marker meaning. They are plain traits rather than +[CGP components](/docs/reference/glossary#component): they lack a generated +[provider trait](/docs/reference/glossary#provider-trait) and are never wired. The +[monad providers](../../providers/monad/index.md) consume them as ordinary bounds while folding a +pipeline at compile time, so you name a trait here only when defining a monad of your own. Import each from `cgp::extra::monad::traits`. They split into the pair that folds the pipeline and the pair that runs one step. diff --git a/docs/reference/traits/monad/lift_value.md b/docs/reference/traits/monad/lift_value.md index 2320f812..fd89b7cf 100644 --- a/docs/reference/traits/monad/lift_value.md +++ b/docs/reference/traits/monad/lift_value.md @@ -32,8 +32,8 @@ It is the counterpart of [`ContainsValue`](./contains_value.md): that one says h output type, this one how to get back *in*. Together they run one step; the other two monad traits, [`MonadicBind`](./monadic_bind.md) and [`MonadicTrans`](./monadic_trans.md), fold the pipeline instead. -**This is a plain trait, not a CGP component.** It lacks a generated -[provider trait](/docs/reference/glossary#provider-trait) and is never wired. +**This is a plain trait, not a [CGP component](/docs/reference/glossary#component).** It lacks a +generated [provider trait](/docs/reference/glossary#provider-trait) and is never wired. ## Definition diff --git a/docs/reference/traits/monad/monadic_bind.md b/docs/reference/traits/monad/monadic_bind.md index 04015446..348bef17 100644 --- a/docs/reference/traits/monad/monadic_bind.md +++ b/docs/reference/traits/monad/monadic_bind.md @@ -34,9 +34,9 @@ It is one of four traits that give a monad marker its meaning, alongside [`ContainsValue`](./contains_value.md), [`LiftValue`](./lift_value.md), and [`MonadicTrans`](./monadic_trans.md). Keeping them apart lets one marker serve all four roles. -**This is a plain trait, not a CGP component.** It lacks a generated -[provider trait](/docs/reference/glossary#provider-trait) and a `…Component` marker, and is never -wired through [`delegate_components!`](../../macros/delegate_components.md): the +**This is a plain trait, not a [CGP component](/docs/reference/glossary#component).** It lacks a +generated [provider trait](/docs/reference/glossary#provider-trait) and a `…Component` marker, and +is never wired through [`delegate_components!`](../../macros/delegate_components.md): the [monad providers](../../providers/monad/index.md) consume it as an ordinary trait bound while folding a pipeline at compile time. diff --git a/docs/reference/traits/monad/monadic_trans.md b/docs/reference/traits/monad/monadic_trans.md index f241ed49..7654365b 100644 --- a/docs/reference/traits/monad/monadic_trans.md +++ b/docs/reference/traits/monad/monadic_trans.md @@ -33,8 +33,8 @@ It is one of four traits that give a monad marker its meaning, and it belongs wi composed [provider](/docs/reference/glossary#provider), while [`ContainsValue`](./contains_value.md) and [`LiftValue`](./lift_value.md) run each step. -**This is a plain trait, not a CGP component.** It lacks a generated -[provider trait](/docs/reference/glossary#provider-trait) and is never wired. +**This is a plain trait, not a [CGP component](/docs/reference/glossary#component).** It lacks a +generated [provider trait](/docs/reference/glossary#provider-trait) and is never wired. ## Definition From 0448b530b4c486f04445411609514a9674b31c8e Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 20:51:47 +0100 Subject: [PATCH 280/516] Name Context-Generic Programming on the dispatch pages Every dispatch page's overview now names Context-Generic Programming and links the introduction, with a short form of the tag line where the page's construct chooses an implementation. The BuildAndMergeOutputs quote of the ref-component failure now matches its blessed stderr, which prints the implemented components without the crate prefix. --- .../reference/providers/dispatch/build_and_merge.md | 8 +++++--- .../providers/dispatch/build_and_merge_outputs.md | 12 +++++++----- .../providers/dispatch/build_and_set_field.md | 8 +++++--- .../providers/dispatch/build_with_handlers.md | 5 ++++- .../providers/dispatch/downcast_and_handle.md | 4 +++- .../providers/dispatch/extract_field_and_handle.md | 6 ++++-- .../providers/dispatch/handle_field_value.md | 6 ++++-- docs/reference/providers/dispatch/index.md | 13 ++++++++----- .../providers/dispatch/match_first_with_handlers.md | 4 +++- .../providers/dispatch/match_with_field_handlers.md | 4 +++- .../providers/dispatch/match_with_handlers.md | 4 +++- .../providers/dispatch/match_with_value_handlers.md | 8 +++++--- 12 files changed, 54 insertions(+), 28 deletions(-) diff --git a/docs/reference/providers/dispatch/build_and_merge.md b/docs/reference/providers/dispatch/build_and_merge.md index e21b0e2e..d958219f 100644 --- a/docs/reference/providers/dispatch/build_and_merge.md +++ b/docs/reference/providers/dispatch/build_and_merge.md @@ -12,9 +12,11 @@ Build a sub-record and move every one of its fields into the target's builder at ## Overview `BuildAndMerge` is the builder step for a group of fields that one provider produces -together. It runs `Provider` over a reference to the builder to build another record, then copies -each of that record's fields into the builder by name, on a -[**context**](/docs/reference/glossary#context), the type the implementation runs against. A +together. [Context-Generic Programming (CGP)](/docs/) lets a context choose the provider behind +each trait call, and `BuildAndMerge` carries that choice into record assembly: it runs `Provider` +over a reference to the builder to build another record, then copies each of that record's fields +into the builder by name, on a [**context**](/docs/reference/glossary#context), the type the +implementation runs against. A subsystem can therefore contribute its part of a larger record as a struct of its own, with no knowledge of the record it ends up in. `Provider` defaults to [`UseContext`](../use_context.md). Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/dispatch/build_and_merge_outputs.md b/docs/reference/providers/dispatch/build_and_merge_outputs.md index 1e2cefcb..12bdb9a0 100644 --- a/docs/reference/providers/dispatch/build_and_merge_outputs.md +++ b/docs/reference/providers/dispatch/build_and_merge_outputs.md @@ -13,8 +13,10 @@ name. ## Overview `BuildAndMergeOutputs` assembles a record from providers that each build a -sub-record: a database configuration, an HTTP configuration, a logger. It wraps each provider in the -[`BuildAndMerge`](build_and_merge.md) step and runs the list through +sub-record: a database configuration, an HTTP configuration, a logger. [Context-Generic Programming +(CGP)](/docs/) enables pluggable trait implementations in Rust, and this builder applies that at +the subsystem level: the context chooses the provider behind each part. It wraps each provider in +the [`BuildAndMerge`](build_and_merge.md) step and runs the list through [`BuildWithHandlers`](build_with_handlers.md), on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. The providers know nothing of the target record or of each other; the merge matches their fields to the @@ -189,9 +191,9 @@ the list, so `Product![BuildDatabaseConfig, BuildHttpConfig]` becomes and rustc lists the three impls it has: ```text - | |________________________________________^ `IsProviderFor` - | |________________________________________^ `IsProviderFor` - | |________________________________________^ `IsProviderFor` + | |________________________________________^ `IsProviderFor` + | |________________________________________^ `IsProviderFor` + | |________________________________________^ `IsProviderFor` ``` Wire it to the owned-input components only. The builder ignores its input, so a borrowed form would diff --git a/docs/reference/providers/dispatch/build_and_set_field.md b/docs/reference/providers/dispatch/build_and_set_field.md index f596cb5a..1ee9d43c 100644 --- a/docs/reference/providers/dispatch/build_and_set_field.md +++ b/docs/reference/providers/dispatch/build_and_set_field.md @@ -12,9 +12,11 @@ Compute one field's value and set it on a ## Overview -`BuildAndSetField` is the builder step for a single field. It takes the builder, a -partial record with some fields set, runs `Provider` over a reference to it to compute the value of -the field named `Tag`, and returns the builder with that field set, on a +`BuildAndSetField` is the builder step for a single field. +[Context-Generic Programming (CGP)](/docs/) lets a context choose the provider that computes each +field's value, and this step applies one of those choices: it takes the builder, a partial record +with some fields set, runs `Provider` over a reference to it to compute the value of the field +named `Tag`, and returns the builder with that field set, on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. Because `Provider` receives the builder, it can read the fields earlier steps have set as well as anything on the context. `Provider` defaults to [`UseContext`](../use_context.md). Like every CGP provider, diff --git a/docs/reference/providers/dispatch/build_with_handlers.md b/docs/reference/providers/dispatch/build_with_handlers.md index 81861d61..f818cb91 100644 --- a/docs/reference/providers/dispatch/build_with_handlers.md +++ b/docs/reference/providers/dispatch/build_with_handlers.md @@ -13,7 +13,10 @@ is set. ## Overview `BuildWithHandlers` assembles a record whose fields come from separate providers. -It starts from the empty [partial record](/docs/reference/glossary#partial-record) of `Output`, +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and +this builder gives a record that shape: the context chooses the provider that fills each field. The +builder starts from the empty [partial record](/docs/reference/glossary#partial-record) of +`Output`, passes it through a list of builder steps that each set one field or a group of fields, and turns the finished builder into the concrete `Output`, on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. Each diff --git a/docs/reference/providers/dispatch/downcast_and_handle.md b/docs/reference/providers/dispatch/downcast_and_handle.md index f3166bd8..a70c5d4f 100644 --- a/docs/reference/providers/dispatch/downcast_and_handle.md +++ b/docs/reference/providers/dispatch/downcast_and_handle.md @@ -12,7 +12,9 @@ Match a group of variants in one arm, by narrowing the input to a smaller enum. ## Overview `DowncastAndHandle` is the matcher arm for several variants that one provider -handles together. Instead of extracting one variant, it tries to narrow the input to `Inner`, a +handles together. [Context-Generic Programming (CGP)](/docs/) keeps the handler behind a trait call +pluggable, and this arm extends one pluggable choice from a single variant to a group of them. +Instead of extracting one variant, it tries to narrow the input to `Inner`, a smaller enum whose variants are a subset of the input's. When the value is one of those variants, it hands the whole `Inner` value to `Provider` and returns `Ok`; otherwise it returns `Err` of the remainder, with every variant of `Inner` ruled out, on a diff --git a/docs/reference/providers/dispatch/extract_field_and_handle.md b/docs/reference/providers/dispatch/extract_field_and_handle.md index 5c97fcfe..53407aa5 100644 --- a/docs/reference/providers/dispatch/extract_field_and_handle.md +++ b/docs/reference/providers/dispatch/extract_field_and_handle.md @@ -12,8 +12,10 @@ on to the next arm otherwise. ## Overview -`ExtractFieldAndHandle` is one arm of a matcher's list. It takes an extractor, a view -of an enum that can rule variants out one at a time, and tries to extract the variant named `Tag`. +`ExtractFieldAndHandle` is one arm of a matcher's list. [Context-Generic Programming +(CGP)](/docs/) lets a context choose the handler behind each trait call, and +`ExtractFieldAndHandle` is where one such choice meets one variant. It takes an extractor, a view of +an enum that can rule variants out one at a time, and tries to extract the variant named `Tag`. On a match it wraps the payload in a [`Field`](../../types/field.md) and returns `Ok` of what `Provider` computes from it; on a miss it returns `Err` of the remainder, the extractor with that variant ruled out, which the next arm takes as its input. It runs on a diff --git a/docs/reference/providers/dispatch/handle_field_value.md b/docs/reference/providers/dispatch/handle_field_value.md index 7931655e..9f1c8a09 100644 --- a/docs/reference/providers/dispatch/handle_field_value.md +++ b/docs/reference/providers/dispatch/handle_field_value.md @@ -11,8 +11,10 @@ Strip the variant tag from a matched payload and pass the bare value to an inner ## Overview -`HandleFieldValue` sits between a matcher arm and the provider that does the work. An arm -such as [`ExtractFieldAndHandle`](extract_field_and_handle.md) delivers its payload as a +`HandleFieldValue` sits between a matcher arm and the provider that does the work. +[Context-Generic Programming (CGP)](/docs/) keeps the handler behind a trait call pluggable, and +`HandleFieldValue` keeps the payload's handler ordinary: free of the variant tag the arm attaches. +An arm such as [`ExtractFieldAndHandle`](extract_field_and_handle.md) delivers its payload as a [`Field`](../../types/field.md), with the variant name attached as a type. Most payload handlers are ordinary computers over the payload type and know nothing of that tag, so `HandleFieldValue` unwraps the `Field` and passes the bare `Value` to `Provider`, on a diff --git a/docs/reference/providers/dispatch/index.md b/docs/reference/providers/dispatch/index.md index 532ee69a..6b22361e 100644 --- a/docs/reference/providers/dispatch/index.md +++ b/docs/reference/providers/dispatch/index.md @@ -12,11 +12,14 @@ handlers: the matchers take an enum apart, and the builders assemble a record. ## Overview The dispatch combinators handle an enum or a record generically, where the logic for each variant -or field lives in its own provider. A hand-written `match` names every variant in one place. These -combinators drive the extractor and builder traits instead, trying one variant or filling one field -at a time on a [**context**](/docs/reference/glossary#context), the type the implementation runs -against, and they prove at compile time that every variant is matched or every field is set. Like -every CGP provider, each is zero-sized: its type parameters ride in `PhantomData`. +or field lives in its own provider. [Context-Generic Programming (CGP)](/docs/) enables pluggable +trait implementations in Rust, and these combinators extend that to extensible data: the handler +for each variant or field is a provider the context chooses. A hand-written `match` names every +variant in one place. These combinators drive the extractor and builder traits instead, trying one +variant or filling one field at a time on a [**context**](/docs/reference/glossary#context), the +type the implementation runs against. They prove at compile time that every variant is matched or +every field is set. Like every CGP provider, each is zero-sized: its type parameters ride in +`PhantomData`. The two halves implement different members of the handler family. The matchers and their adapters implement [`Computer`](../../components/handler/computer.md) and diff --git a/docs/reference/providers/dispatch/match_first_with_handlers.md b/docs/reference/providers/dispatch/match_first_with_handlers.md index f7b51ffa..2695dd18 100644 --- a/docs/reference/providers/dispatch/match_first_with_handlers.md +++ b/docs/reference/providers/dispatch/match_first_with_handlers.md @@ -13,7 +13,9 @@ Match an enum that arrives together with extra arguments, passing the arguments `MatchFirstWithHandlers` is the matcher for an input of the form `(Input, Args)`: the enum being matched, first, and extra arguments that every per-variant handler needs, such as a scale -factor or a target buffer. It works like [`MatchWithHandlers`](match_with_handlers.md) on a +factor or a target buffer. [Context-Generic Programming (CGP)](/docs/) lets a context choose the +handler for each variant, and `MatchFirstWithHandlers` keeps those per-variant choices while the +arguments ride along. It works like [`MatchWithHandlers`](match_with_handlers.md) on a [**context**](/docs/reference/glossary#context), the type the implementation runs against, except that `Args` travels with the extractor through the loop, so on a miss the next handler still receives the arguments. Like every CGP provider, it carries no runtime value; the handler list rides diff --git a/docs/reference/providers/dispatch/match_with_field_handlers.md b/docs/reference/providers/dispatch/match_with_field_handlers.md index 372e25d4..c9ad90d9 100644 --- a/docs/reference/providers/dispatch/match_with_field_handlers.md +++ b/docs/reference/providers/dispatch/match_with_field_handlers.md @@ -15,7 +15,9 @@ with its variant name attached. `MatchWithFieldHandlers` builds the per-variant list from the input enum's field list, like [`MatchWithValueHandlers`](match_with_value_handlers.md), but hands each payload to `Provider` as a [`Field`](../../types/field.md), where `Tag` is the variant's name as a type-level -string. A provider over `Field` can read that name, so one provider can report or route +string. [Context-Generic Programming (CGP)](/docs/) lets a context choose the handler for each +variant, and this matcher builds that choice into the wiring while keeping the variant's name +attached. A provider over `Field` can read that name, so one provider can report or route on which variant it received, on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. `Provider` defaults to [`UseContext`](../use_context.md). Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/dispatch/match_with_handlers.md b/docs/reference/providers/dispatch/match_with_handlers.md index 5e0d2b94..d0484830 100644 --- a/docs/reference/providers/dispatch/match_with_handlers.md +++ b/docs/reference/providers/dispatch/match_with_handlers.md @@ -12,7 +12,9 @@ Match an enum against a spelled-out list of per-variant handlers, with no wildca ## Overview `MatchWithHandlers` is the matcher for an enum whose variants each have their own handler. -It turns the input into its extractor, a view of the enum that can rule variants out one at a time, +[Context-Generic Programming (CGP)](/docs/) lets a context choose the handler behind each trait +call, and `MatchWithHandlers` runs the list of those choices, one per variant. It turns the input +into its extractor, a view of the enum that can rule variants out one at a time, and runs a list of handlers over it on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. The first handler whose variant matches produces the output. When the list has a handler for every variant, the last miss leaves nothing to match, so the matcher diff --git a/docs/reference/providers/dispatch/match_with_value_handlers.md b/docs/reference/providers/dispatch/match_with_value_handlers.md index d777af91..0dbd458b 100644 --- a/docs/reference/providers/dispatch/match_with_value_handlers.md +++ b/docs/reference/providers/dispatch/match_with_value_handlers.md @@ -13,9 +13,11 @@ as a bare value. ## Overview `MatchWithValueHandlers` is the matcher for the common case, where every variant's -payload goes to one provider. Rather than a spelled-out list, it builds one adapter per variant from -the input enum's own field list, so adding a variant needs no new arm, and it hands -each payload to `Provider` as a bare value on a +payload goes to one provider. [Context-Generic Programming (CGP)](/docs/) enables pluggable trait +implementations in Rust, and `MatchWithValueHandlers` is that pluggability at its plainest: +whichever provider the context wired serves every payload. Rather than a spelled-out list, it +builds one adapter per variant from the input enum's own field list, so adding a variant needs no +new arm. It hands each payload to `Provider` as a bare value on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. That makes it the form for payload handlers that are ordinary computers over the payload type, such as ones from [`#[cgp_computer]`](../../macros/cgp_computer.md). `Provider` defaults to From 9714c16cf09fd7f5f8c4a5a42af3fb38d2540da6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 21:05:15 +0100 Subject: [PATCH 281/516] Name Context-Generic Programming on the handler and monad pages Each handler and monad provider page now opens with Context-Generic Programming linked to the Introduction, before any other "CGP", and most relate the pluggable-provider idea to the page's job. The handler index no longer says its parameters are all inner providers, since `UseInputDelegate` carries a dispatch table. Co-Authored-By: deepseek-v4.1-flash --- .../providers/handler/compose_handlers.md | 3 ++- docs/reference/providers/handler/index.md | 9 +++++---- .../providers/handler/pipe_handlers.md | 1 + docs/reference/providers/handler/promote.md | 1 + .../providers/handler/promote_async.md | 10 ++++++---- .../providers/handler/promote_async_computer.md | 13 +++++++------ .../providers/handler/promote_computer.md | 11 ++++++----- .../providers/handler/promote_handler.md | 13 +++++++------ .../providers/handler/promote_producer.md | 6 ++++-- docs/reference/providers/handler/promote_ref.md | 17 +++++++++-------- .../providers/handler/promote_try_computer.md | 7 ++++--- .../reference/providers/handler/return_input.md | 13 +++++++------ docs/reference/providers/handler/try_promote.md | 1 + .../providers/handler/use_input_delegate.md | 13 +++++++------ docs/reference/providers/monad/bind_err.md | 1 + docs/reference/providers/monad/bind_ok.md | 1 + docs/reference/providers/monad/index.md | 5 +++-- docs/reference/providers/monad/pipe_monadic.md | 1 + 18 files changed, 73 insertions(+), 53 deletions(-) diff --git a/docs/reference/providers/handler/compose_handlers.md b/docs/reference/providers/handler/compose_handlers.md index da6f322e..26a81cb6 100644 --- a/docs/reference/providers/handler/compose_handlers.md +++ b/docs/reference/providers/handler/compose_handlers.md @@ -11,7 +11,8 @@ Run two handlers back to back, feeding the output of the first as the input of t ## Overview -`ComposeHandlers` is the fundamental sequencing combinator. It runs +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and +`ComposeHandlers` is the fundamental sequencing combinator for them. It runs `ProviderA`, then runs `ProviderB` on `ProviderA`'s output, under one [**context**](/docs/reference/glossary#context), the type the implementation runs against, and one `Code` tag. It implements the four owned-input members of the handler family, `Computer`, diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md index 609c365e..3a5d8707 100644 --- a/docs/reference/providers/handler/index.md +++ b/docs/reference/providers/handler/index.md @@ -11,15 +11,16 @@ through a pipeline, returning the input unchanged, and lifting one handler shape ## Overview -The handler combinators exist because the handler family is not one trait but several related ones, -and code is rarely written against all of them at once. A provider author writes a plain synchronous -[`Computer`](../../components/handler/computer.md), a fallible +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and the +handler combinators work across the family of traits that model computation. That family is not one +trait but several related ones, and code is rarely written against all of them at once. A provider +author writes a plain synchronous [`Computer`](../../components/handler/computer.md), a fallible [`TryComputer`](../../components/handler/try_computer.md), or an async [`Handler`](../../components/handler/handler.md), depending on the computation. The combinators let those single-shape providers be wired where a different shape is expected, and let several providers be glued into a larger one, on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. Like every CGP provider, each combinator is zero-sized: its type -parameters are inner providers carried in `PhantomData`. +parameters ride in `PhantomData`. The promotion bundles are in the prelude. Every other combinator here, from `ComposeHandlers` to `UseInputDelegate`, is imported from `cgp::extra::handler`, as are the consumer traits such as diff --git a/docs/reference/providers/handler/pipe_handlers.md b/docs/reference/providers/handler/pipe_handlers.md index cc3679f8..0754db41 100644 --- a/docs/reference/providers/handler/pipe_handlers.md +++ b/docs/reference/providers/handler/pipe_handlers.md @@ -12,6 +12,7 @@ next. ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `PipeHandlers` generalizes [`ComposeHandlers`](compose_handlers.md) from two handlers to a list of them. It takes a [`Product!`](../../macros/product.md) list of providers and folds the whole pipeline into one nested `ComposeHandlers`, so the input flows through each stage in turn, on diff --git a/docs/reference/providers/handler/promote.md b/docs/reference/providers/handler/promote.md index 4a3c8160..f93b53aa 100644 --- a/docs/reference/providers/handler/promote.md +++ b/docs/reference/providers/handler/promote.md @@ -12,6 +12,7 @@ without adding behavior of its own. ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `Promote` re-exposes one inner provider under a more capable member of the handler family. It treats a less capable provider as a more capable one without introducing error or async behavior itself, so the [**context**](/docs/reference/glossary#context), the type the implementation runs diff --git a/docs/reference/providers/handler/promote_async.md b/docs/reference/providers/handler/promote_async.md index 0b9481f5..ec71bfa5 100644 --- a/docs/reference/providers/handler/promote_async.md +++ b/docs/reference/providers/handler/promote_async.md @@ -11,10 +11,12 @@ Lift a synchronous handler into an asynchronous one. ## Overview -`PromoteAsync` runs a synchronous inner provider inside an async method, so a synchronous -handler serves an asynchronous slot on a [**context**](/docs/reference/glossary#context), the type -the implementation runs against. The returned future does all its work when first polled and awaits -nothing, so no actual asynchrony is added. It is usually reached through a promotion bundle such as +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each trait +call, and `PromoteAsync` runs a synchronous inner provider inside an async method, so a +synchronous handler serves an asynchronous slot on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. The +returned future does all its work when first polled and awaits nothing, so no actual asynchrony is +added. It is usually reached through a promotion bundle such as [`PromoteComputer`](promote_computer.md), and it is written by hand when a context wires one slot at a time. Like every CGP provider, it carries no runtime value; the inner provider rides in `PhantomData`. diff --git a/docs/reference/providers/handler/promote_async_computer.md b/docs/reference/providers/handler/promote_async_computer.md index 54f38fb8..612ffa1e 100644 --- a/docs/reference/providers/handler/promote_async_computer.md +++ b/docs/reference/providers/handler/promote_async_computer.md @@ -23,12 +23,13 @@ components through such a provider, or through its `HandlerComponent` entry, whi ## Overview -`PromoteAsyncComputer` starts from a provider that implements `AsyncComputer`, the -asynchronous infallible base, and fills in the other async members of the handler family on a -[**context**](/docs/reference/glossary#context), the type the implementation runs against. It is the -async-base counterpart of [`PromoteComputer`](promote_computer.md), and it fills in only async -members, because the synchronous ones cannot be derived from an async base. Like every CGP provider, -it carries no runtime value. +[Context-Generic Programming (CGP)](/docs/) lets one provider answer several related trait calls +through wiring, and `PromoteAsyncComputer` starts from a provider that implements +`AsyncComputer`, the asynchronous infallible base. It fills in the other async members of the +handler family on a [**context**](/docs/reference/glossary#context), the type the implementation +runs against. It is the async-base counterpart of [`PromoteComputer`](promote_computer.md), and it +fills in only async members, because the synchronous ones cannot be derived from an async base. Like +every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/handler/promote_computer.md b/docs/reference/providers/handler/promote_computer.md index 4749d277..5f1b6e58 100644 --- a/docs/reference/providers/handler/promote_computer.md +++ b/docs/reference/providers/handler/promote_computer.md @@ -24,11 +24,12 @@ bundle emits. ## Overview -`PromoteComputer` starts from a provider that implements `Computer`, the synchronous, -infallible, owned-input base, and fills in every other member of the handler family by promotion, on -a [**context**](/docs/reference/glossary#context), the type the implementation runs against. It is a -delegation table that routes each remaining handler component to the right single-step promotion. -Like every CGP provider, it carries no runtime value. +[Context-Generic Programming (CGP)](/docs/) lets one provider answer several related trait calls +through wiring, and `PromoteComputer` starts from a provider that implements `Computer`, +the synchronous, infallible, owned-input base, and fills in every other member of the handler family +by promotion, on a [**context**](/docs/reference/glossary#context), the type the implementation runs +against. It is a delegation table that routes each remaining handler component to the right +single-step promotion. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/handler/promote_handler.md b/docs/reference/providers/handler/promote_handler.md index 1bf1955e..5ee79ea6 100644 --- a/docs/reference/providers/handler/promote_handler.md +++ b/docs/reference/providers/handler/promote_handler.md @@ -24,12 +24,13 @@ returning `Result`. This page explains what the bundle emits. ## Overview -`PromoteHandler` starts from an `AsyncComputer` whose output is a `Result` over the -context's error type, the base `#[cgp_computer]` builds for an `async fn` returning `Result`, and -fills in the fallible async members on a [**context**](/docs/reference/glossary#context), the type -the implementation runs against. Despite its name, its base is not a `Handler`: it produces the -`Handler` by reading the base's `Result` as the failure path. Like every CGP provider, it carries no -runtime value. +[Context-Generic Programming (CGP)](/docs/) lets one provider answer several related trait calls +through wiring, and `PromoteHandler` starts from an `AsyncComputer` whose output is a +`Result` over the context's error type, the base `#[cgp_computer]` builds for an `async fn` +returning `Result`. It fills in the fallible async members on a +[**context**](/docs/reference/glossary#context), the type the implementation runs against. Despite +its name, its base is not a `Handler`: it produces the `Handler` by reading the base's `Result` as +the failure path. Like every CGP provider, it carries no runtime value. ## Usage diff --git a/docs/reference/providers/handler/promote_producer.md b/docs/reference/providers/handler/promote_producer.md index ca26a92b..ad08b332 100644 --- a/docs/reference/providers/handler/promote_producer.md +++ b/docs/reference/providers/handler/promote_producer.md @@ -23,8 +23,10 @@ sets out. This page explains what the bundle emits. ## Overview -`PromoteProducer` starts from a [`Producer`](../../components/handler/producer.md), a -provider that takes no input, and fills in every input-taking member of the handler family on a +[Context-Generic Programming (CGP)](/docs/) lets one provider answer several related trait calls +through wiring, and `PromoteProducer` starts from a +[`Producer`](../../components/handler/producer.md), a provider that takes no input. It fills in +every input-taking member of the handler family on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. The single produced value flows out of every handler shape regardless of the input, which the promotion discards. Like every CGP provider, it carries no runtime value. diff --git a/docs/reference/providers/handler/promote_ref.md b/docs/reference/providers/handler/promote_ref.md index 7303d621..0309e476 100644 --- a/docs/reference/providers/handler/promote_ref.md +++ b/docs/reference/providers/handler/promote_ref.md @@ -11,14 +11,15 @@ Bridge between by-value handlers and by-reference handlers, in both directions. ## Overview -`PromoteRef` lets a provider written for one input mode serve a slot that uses the other, -without manual dereference code, on a [**context**](/docs/reference/glossary#context), the type the -implementation runs against. It is the most thoroughly implemented promotion: it covers all four -input-taking members of the family, `Computer`, `TryComputer`, `AsyncComputer`, and `Handler`, in -both directions, and the two directions ask different things of the inner provider. Every promotion -bundle routes its `…Ref` slots through it, and it is written by hand when a context wires one slot -at a time. Like every CGP provider, it carries no runtime value; the inner provider rides in -`PhantomData`. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider for each trait +call, and `PromoteRef` lets a provider written for one input mode serve a slot that uses +the other, without manual dereference code, on a [**context**](/docs/reference/glossary#context), +the type the implementation runs against. It is the most thoroughly implemented promotion: it covers +all four input-taking members of the family, `Computer`, `TryComputer`, `AsyncComputer`, and +`Handler`, in both directions, and the two directions ask different things of the inner provider. +Every promotion bundle routes its `…Ref` slots through it, and it is written by hand when a context +wires one slot at a time. Like every CGP provider, it carries no runtime value; the inner provider +rides in `PhantomData`. ## Usage diff --git a/docs/reference/providers/handler/promote_try_computer.md b/docs/reference/providers/handler/promote_try_computer.md index 6ff3af95..2cc70b57 100644 --- a/docs/reference/providers/handler/promote_try_computer.md +++ b/docs/reference/providers/handler/promote_try_computer.md @@ -23,9 +23,10 @@ components through such a provider, or through the entries that serve any base, ## Overview -`PromoteTryComputer` starts from a `Computer` whose output is a `Result` over the -context's error type, the base [`#[cgp_computer]`](../../macros/cgp_computer.md) generates for a -function returning `Result`, and fills in the rest of the handler family on a +[Context-Generic Programming (CGP)](/docs/) lets one provider answer several related trait calls +through wiring, and `PromoteTryComputer` starts from a `Computer` whose output is a +`Result` over the context's error type, the base [`#[cgp_computer]`](../../macros/cgp_computer.md) +generates for a function returning `Result`, and fills in the rest of the handler family on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. It reads that `Result` as the failure path for the fallible slot through [`TryPromote`](try_promote.md), and derives the other members from the computer form through [`PromoteComputer`](promote_computer.md). diff --git a/docs/reference/providers/handler/return_input.md b/docs/reference/providers/handler/return_input.md index 5111173a..8ad9ddcf 100644 --- a/docs/reference/providers/handler/return_input.md +++ b/docs/reference/providers/handler/return_input.md @@ -11,12 +11,13 @@ The identity handler: return the input unchanged as the output. ## Overview -`ReturnInput` ignores the [**context**](/docs/reference/glossary#context), the type the -implementation runs against, and the `Code` tag, and returns its input as its output. It is the -neutral element of handler composition: putting it before or after any other handler leaves that -handler's behavior unchanged. It fills a handler slot where no transformation is wanted and stands -in as a placeholder stage. Like every CGP provider, it carries no runtime value; it is a plain unit -struct. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each trait +call, and `ReturnInput` is the provider that ignores the +[**context**](/docs/reference/glossary#context), the type the implementation runs against, and the +`Code` tag, and returns its input as its output. It is the neutral element of handler composition: +putting it before or after any other handler leaves that handler's behavior unchanged. It fills a +handler slot where no transformation is wanted and stands in as a placeholder stage. Like every CGP +provider, it carries no runtime value; it is a plain unit struct. ## Usage diff --git a/docs/reference/providers/handler/try_promote.md b/docs/reference/providers/handler/try_promote.md index 50617589..e5cf27bc 100644 --- a/docs/reference/providers/handler/try_promote.md +++ b/docs/reference/providers/handler/try_promote.md @@ -11,6 +11,7 @@ Bridge in both directions between a `Result`-valued output and a fallible handle ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `TryPromote` unifies the two ways of expressing fallibility: a handler that *returns* a `Result`, and a genuinely fallible handler trait. It converts between them in both directions on a [**context**](/docs/reference/glossary#context), the type the implementation runs against, and every diff --git a/docs/reference/providers/handler/use_input_delegate.md b/docs/reference/providers/handler/use_input_delegate.md index 6d4cf639..760422dd 100644 --- a/docs/reference/providers/handler/use_input_delegate.md +++ b/docs/reference/providers/handler/use_input_delegate.md @@ -11,12 +11,13 @@ Dispatch a handler to a different inner provider per input type, through a looku ## Overview -`UseInputDelegate` chooses a handler provider by the type of the value being handled. An -ordinary handler component is answered by one provider. `UseInputDelegate` performs a second lookup: -it treats the handler's `Input` type as a key and reads the matching inner provider out of a table, -so a single wiring entry on a [**context**](/docs/reference/glossary#context), the type the -implementation runs against, fans out to many input-specific providers. Like every CGP provider, it -holds no runtime value; the table rides in `PhantomData`. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each trait +call, and `UseInputDelegate` chooses a handler provider by the type of the value being +handled. An ordinary handler component is answered by one provider. `UseInputDelegate` performs a +second lookup: it treats the handler's `Input` type as a key and reads the matching inner provider +out of a table, so a single wiring entry on a [**context**](/docs/reference/glossary#context), the +type the implementation runs against, fans out to many input-specific providers. Like every CGP +provider, it holds no runtime value; the table rides in `PhantomData`. It is the sibling of [`UseDelegate`](../use_delegate.md). Where `UseDelegate` keys on the `Code` parameter of a handler, `UseInputDelegate` keys on the `Input` parameter, so the provider that diff --git a/docs/reference/providers/monad/bind_err.md b/docs/reference/providers/monad/bind_err.md index f30d8947..d07fe49f 100644 --- a/docs/reference/providers/monad/bind_err.md +++ b/docs/reference/providers/monad/bind_err.md @@ -12,6 +12,7 @@ short-circuit on `Err`. ## Overview +Under [Context-Generic Programming (CGP)](/docs/), a pipeline is a sequence of chosen providers, and `BindErr` implements a single bind step of the err monad, the ordinary `?`-style behavior. [`PipeMonadic`](pipe_monadic.md) composes it for you when it folds a pipeline under [`ErrMonadic`](index.md#the-monad-markers), so most code never names it. It is usable directly as a diff --git a/docs/reference/providers/monad/bind_ok.md b/docs/reference/providers/monad/bind_ok.md index c7bfa0af..00206e2e 100644 --- a/docs/reference/providers/monad/bind_ok.md +++ b/docs/reference/providers/monad/bind_ok.md @@ -12,6 +12,7 @@ short-circuit on `Ok`. ## Overview +Under [Context-Generic Programming (CGP)](/docs/), a pipeline is a sequence of chosen providers, and `BindOk` implements a single bind step of the ok monad. [`PipeMonadic`](pipe_monadic.md) composes it for you when it folds a pipeline under [`OkMonadic`](index.md#the-monad-markers), so most code never names it. It is usable directly as a handler provider on a diff --git a/docs/reference/providers/monad/index.md b/docs/reference/providers/monad/index.md index 96d0c735..90bb82c7 100644 --- a/docs/reference/providers/monad/index.md +++ b/docs/reference/providers/monad/index.md @@ -11,8 +11,9 @@ appropriate branch. ## Overview -The monad providers build [monadic handler composition](/docs/concepts/monadic-handlers) on top of -the [`Computer`](../../components/handler/computer.md) family. They let a sequence of handlers whose +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and the +monad providers build [monadic handler composition](/docs/concepts/monadic-handlers) on top of the +[`Computer`](../../components/handler/computer.md) family. They let a sequence of handlers whose outputs carry a "continue" case and a "stop" case be chained without pattern-matching each step by hand: the monad decides which case threads forward and which short-circuits. A built pipeline is itself a provider for `Computer`, `AsyncComputer`, `TryComputer`, and `Handler`, so it wires into a diff --git a/docs/reference/providers/monad/pipe_monadic.md b/docs/reference/providers/monad/pipe_monadic.md index f1c66eba..432854f0 100644 --- a/docs/reference/providers/monad/pipe_monadic.md +++ b/docs/reference/providers/monad/pipe_monadic.md @@ -12,6 +12,7 @@ branch. ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `PipeMonadic` composes a handler list `Providers` under a monad `M` into one short-circuiting handler, on a [**context**](/docs/reference/glossary#context), the type the implementation runs against. Each step runs only on the previous step's continue branch, and the From 9cf199f9ba66728976054079b98cb25f788bc594 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 21:07:11 +0100 Subject: [PATCH 282/516] Name Context-Generic Programming on the error provider pages Each error provider page now opens with Context-Generic Programming linked to the Introduction, before any other "CGP", and relates the pluggable provider choice to the page's job. The error index's description no longer uses the abbreviation before the full name. Co-Authored-By: deepseek-v4.1-flash --- docs/reference/providers/error/debug_error.md | 1 + docs/reference/providers/error/discard_detail.md | 5 +++-- docs/reference/providers/error/display_error.md | 1 + docs/reference/providers/error/index.md | 5 +++-- docs/reference/providers/error/panic_on_error.md | 13 +++++++------ docs/reference/providers/error/raise_from.md | 7 ++++--- docs/reference/providers/error/raise_infallible.md | 13 +++++++------ docs/reference/providers/error/return_error.md | 11 ++++++----- 8 files changed, 32 insertions(+), 24 deletions(-) diff --git a/docs/reference/providers/error/debug_error.md b/docs/reference/providers/error/debug_error.md index cdcd3894..323b8043 100644 --- a/docs/reference/providers/error/debug_error.md +++ b/docs/reference/providers/error/debug_error.md @@ -12,6 +12,7 @@ string handling. ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `DebugError` implements both error components by redirecting through a string. Rather than producing the abstract error directly, it formats the source error or the detail with the `Debug` trait, as `{:?}` would print it, into a `String`, then forwards to the diff --git a/docs/reference/providers/error/discard_detail.md b/docs/reference/providers/error/discard_detail.md index 62599448..3fa4b18d 100644 --- a/docs/reference/providers/error/discard_detail.md +++ b/docs/reference/providers/error/discard_detail.md @@ -11,8 +11,9 @@ Wrap an error by throwing the detail away and returning the error unchanged. ## Overview -`DiscardDetail` is the `ErrorWrapper` provider that ignores whatever detail is attached and returns the -error as it was. It satisfies the `CanWrapError` trait of a +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the wrapper behind each trait +call, and `DiscardDetail` is the `ErrorWrapper` provider that ignores whatever detail is attached +and returns the error as it was. It satisfies the `CanWrapError` trait of a [**context**](/docs/reference/glossary#context), the type the implementation runs against, without enriching the error. This is useful when a context's error type cannot carry extra context, or when the wrapping detail is deliberately not kept. It is the wrapping counterpart of a no-op: the error diff --git a/docs/reference/providers/error/display_error.md b/docs/reference/providers/error/display_error.md index 53a9d231..52d320d5 100644 --- a/docs/reference/providers/error/display_error.md +++ b/docs/reference/providers/error/display_error.md @@ -12,6 +12,7 @@ string handling. ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `DisplayError` implements both error components by redirecting through a string. Rather than producing the abstract error directly, it formats the source error or the detail with the `Display` trait through `to_string()` into a `String`, then forwards to the diff --git a/docs/reference/providers/error/index.md b/docs/reference/providers/error/index.md index 945ec28f..2e3b6722 100644 --- a/docs/reference/providers/error/index.md +++ b/docs/reference/providers/error/index.md @@ -1,5 +1,5 @@ --- -description: 'The seven error providers CGP ships, from RaiseFrom to DisplayError: raising and wrapping strategies generic over the context''s error type.' +description: 'The seven error providers the library ships, from RaiseFrom to DisplayError: raising and wrapping strategies generic over the context''s error type.' sidebar_label: 'Overview' sidebar_position: 0 --- @@ -11,7 +11,8 @@ concrete error type the context chose. ## Overview -The error providers supply common error-handling strategies to any +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and the +error providers supply common error-handling strategies to any [**context**](/docs/reference/glossary#context), the type the implementation runs against. [`CanRaiseError`](../../components/can_raise_error.md) and [`CanWrapError`](../../components/can_wrap_error.md) define *what* a context can do with an error: diff --git a/docs/reference/providers/error/panic_on_error.md b/docs/reference/providers/error/panic_on_error.md index f3edf4ff..dcaf85d7 100644 --- a/docs/reference/providers/error/panic_on_error.md +++ b/docs/reference/providers/error/panic_on_error.md @@ -11,12 +11,13 @@ Abort with the source error's debug output instead of producing an abstract erro ## Overview -`PanicOnError` is the `ErrorRaiser` provider that panics rather than returning an error. When a -[**context**](/docs/reference/glossary#context), the type the implementation runs against, treats an -error as a programming fault that should stop the program, `PanicOnError` raises by calling `panic!` -with the source error's debug representation. Its signature promises to return the abstract error, -but the body never does, because `panic!` diverges. This suits tests and fail-fast tooling. Like every -CGP provider, `PanicOnError` carries no runtime value. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser behind each trait +call, and `PanicOnError` is the `ErrorRaiser` provider that panics rather than returning an error. +When a [**context**](/docs/reference/glossary#context), the type the implementation runs against, +treats an error as a programming fault that should stop the program, `PanicOnError` raises by +calling `panic!` with the source error's debug representation. Its signature promises to return the +abstract error, but the body never does, because `panic!` diverges. This suits tests and fail-fast +tooling. Like every CGP provider, `PanicOnError` carries no runtime value. ## Usage diff --git a/docs/reference/providers/error/raise_from.md b/docs/reference/providers/error/raise_from.md index 823bfe43..4729f7f7 100644 --- a/docs/reference/providers/error/raise_from.md +++ b/docs/reference/providers/error/raise_from.md @@ -11,11 +11,12 @@ Raise a source error by converting it into the context's error type through the ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `RaiseFrom` is the `ErrorRaiser` provider for the common case: the abstract error of the [**context**](/docs/reference/glossary#context), the type the implementation runs against, already -knows how to build itself from the source error through `From`. Wiring it means "convert every source -error the abstract error has a `From` impl for". It is the default choice whenever that `From` impl -exists, which covers most error raising in practice. +knows how to build itself from the source error through `From`. Wiring it means "convert every +source error the abstract error has a `From` impl for". It is the default choice whenever that +`From` impl exists, which covers most error raising in practice. Because the bound is on the abstract error rather than on one source type, a single wiring of `RaiseFrom` covers every source error the context's error can absorb. Like every CGP provider, diff --git a/docs/reference/providers/error/raise_infallible.md b/docs/reference/providers/error/raise_infallible.md index 1079c08f..1186bac1 100644 --- a/docs/reference/providers/error/raise_infallible.md +++ b/docs/reference/providers/error/raise_infallible.md @@ -11,12 +11,13 @@ Absorb `core::convert::Infallible`, the error type that can never be constructed ## Overview -`RaiseInfallible` is the `ErrorRaiser` provider for `core::convert::Infallible`, an error type with no -values. It lets generic code that raises the error of a fallible operation be wired uniformly on a -[**context**](/docs/reference/glossary#context), the type the implementation runs against, even when -the operation chosen for that context cannot fail. Because an `Infallible` value cannot exist, the -raising method is never actually called at runtime. Like every CGP provider, `RaiseInfallible` carries -no runtime value. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser behind each trait +call, and `RaiseInfallible` is the `ErrorRaiser` provider for `core::convert::Infallible`, an error +type with no values. It lets generic code that raises the error of a fallible operation be wired +uniformly on a [**context**](/docs/reference/glossary#context), the type the implementation runs +against, even when the operation chosen for that context cannot fail. Because an `Infallible` value +cannot exist, the raising method is never actually called at runtime. Like every CGP provider, +`RaiseInfallible` carries no runtime value. ## Usage diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md index 85a5745b..5b855338 100644 --- a/docs/reference/providers/error/return_error.md +++ b/docs/reference/providers/error/return_error.md @@ -11,11 +11,12 @@ Raise a source error that already is the context's abstract error, so raising is ## Overview -`ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly the -abstract error the [**context**](/docs/reference/glossary#context) chose, where the context is the -type the implementation runs against. Raising then has nothing to convert: it returns its argument -untouched. A context uses it when generic code raises a value that is already of the context's own -error type. Like every CGP provider, `ReturnError` carries no runtime value. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser behind each trait +call, and `ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly +the abstract error the [**context**](/docs/reference/glossary#context) chose, where the context is +the type the implementation runs against. Raising then has nothing to convert: it returns its +argument untouched. A context uses it when generic code raises a value that is already of the +context's own error type. Like every CGP provider, `ReturnError` carries no runtime value. ## Usage From 89507cec0727401741784c5a4ddef34057364f02 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 21:09:25 +0100 Subject: [PATCH 283/516] Name Context-Generic Programming on the remaining provider pages The sixteen top-level provider pages and their index now open with Context-Generic Programming linked to the Introduction, before any other "CGP", and relate the provider choice to the page's job. The index description and the legacy notice on the UseDelegate page no longer use the abbreviation first. The UseFieldRef pages also state the 'static bound on the mutable borrow. Co-Authored-By: deepseek-v4.1-flash --- docs/reference/providers/chain_getters.md | 19 ++++++++++--------- docs/reference/providers/index.md | 9 +++++---- docs/reference/providers/redirect_lookup.md | 17 +++++++++-------- docs/reference/providers/use_context.md | 1 + docs/reference/providers/use_default.md | 13 +++++++------ docs/reference/providers/use_delegate.md | 4 +++- .../reference/providers/use_delegated_type.md | 5 +++-- docs/reference/providers/use_field.md | 13 +++++++------ docs/reference/providers/use_field_ref.md | 7 ++++--- docs/reference/providers/use_fields.md | 1 + docs/reference/providers/use_type.md | 5 +++-- docs/reference/providers/with_context.md | 12 +++++++----- .../providers/with_delegated_type.md | 10 ++++++---- docs/reference/providers/with_field.md | 1 + docs/reference/providers/with_field_ref.md | 5 +++-- docs/reference/providers/with_provider.md | 5 +++-- docs/reference/providers/with_type.md | 13 +++++++------ 17 files changed, 80 insertions(+), 60 deletions(-) diff --git a/docs/reference/providers/chain_getters.md b/docs/reference/providers/chain_getters.md index 34a10b4d..a98f959d 100644 --- a/docs/reference/providers/chain_getters.md +++ b/docs/reference/providers/chain_getters.md @@ -11,15 +11,16 @@ Compose a list of field getters into one, reaching a field several hops inside a ## Overview -`ChainGetters` reaches a field that does not live directly on the context but several -levels inside it. The [**context**](/docs/reference/glossary#context) is the type the method runs -on, which supplies the values it needs as its fields, and a single [`UseField`](use_field.md) reads -one field of one context. But CGP contexts often nest: a context holds a config, the config holds a -connection, the connection holds a timeout, and a getter may need the innermost value. Writing one -provider that walks the whole path by hand is tedious and couples the getter to the nesting. -`ChainGetters` takes a list of getters, applies them in order, and threads the reference -from each step into the next, so the chain reads like the path it traverses: outer getter, then the -next, ending at the target field. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each getter +call, and `ChainGetters` reaches a field that does not live directly on the context but +several levels inside it. The [**context**](/docs/reference/glossary#context) is the type the method +runs on, which supplies the values it needs as its fields, and a single [`UseField`](use_field.md) +reads one field of one context. But CGP contexts often nest: a context holds a config, the config +holds a connection, the connection holds a timeout, and a getter may need the innermost value. +Writing one provider that walks the whole path by hand is tedious and couples the getter to the +nesting. `ChainGetters` takes a list of getters, applies them in order, and threads the +reference from each step into the next, so the chain reads like the path it traverses: outer getter, +then the next, ending at the target field. `ChainGetters` is a foundational [`FieldGetter`](../traits/field-access/field_getter.md), so it is wired to a getter component through the [`WithProvider`](with_provider.md) adapter rather than named on its own. The list diff --git a/docs/reference/providers/index.md b/docs/reference/providers/index.md index df3c3cb2..d2b9b716 100644 --- a/docs/reference/providers/index.md +++ b/docs/reference/providers/index.md @@ -1,14 +1,15 @@ --- -description: 'The providers CGP ships, grouped by job: context, type, and getter providers, the With… adapters, per-type dispatch, and the handler combinators.' +description: 'The providers the library ships, grouped by job: context, type, and getter providers, the With… adapters, per-type dispatch, and the handler combinators.' sidebar_label: 'Overview' sidebar_position: 0 --- # Providers -A provider is a zero-sized type wired to a component to say how that component is implemented for a -[context](/docs/reference/glossary#context), the type the implementation runs against. Providers -carry no runtime value; they are type-level markers named in a +[Context-Generic Programming (CGP)](/docs/) lets a context choose the provider behind each trait +call, and a provider is a zero-sized type wired to a component to say how that component is +implemented for a [context](/docs/reference/glossary#context), the type the implementation runs +against. Providers carry no runtime value; they are type-level markers named in a [`delegate_components!`](../macros/delegate_components.md) table and resolved at compile time. This page groups the providers CGP ships by the job they do, in roughly the order most CGP code reaches for them. diff --git a/docs/reference/providers/redirect_lookup.md b/docs/reference/providers/redirect_lookup.md index 4ed02549..373aa9e1 100644 --- a/docs/reference/providers/redirect_lookup.md +++ b/docs/reference/providers/redirect_lookup.md @@ -25,14 +25,15 @@ this provider is legible. ## Overview -`RedirectLookup` separates *which key* a component is looked up under from *which -table* answers it. The ordinary provider blanket impl looks a component up in the -[**context**](/docs/reference/glossary#context)'s own delegation table, keyed by the [component -marker](/docs/reference/glossary#component-marker), where the context is the type the implementation -runs against. `RedirectLookup` does the lookup differently: it consults the table `Components` keyed -by a type-level `Path`, then delegates to whatever provider that entry holds. This indirection lets -one component's resolution be redirected to a different key in a different table, which is the basis -for organizing wiring into namespaces. +Under [Context-Generic Programming (CGP)](/docs/), wiring can be organized by paths and namespaces, +and `RedirectLookup` separates *which key* a component is looked up under from +*which table* answers it. The ordinary provider blanket impl looks a component up in the +[**context**](/docs/reference/glossary#context)'s own delegation table, keyed by the +[component marker](/docs/reference/glossary#component-marker), where the context is the type the +implementation runs against. `RedirectLookup` does the lookup differently: it consults the table +`Components` keyed by a type-level `Path`, then delegates to whatever provider that entry holds. +This indirection lets one component's resolution be redirected to a different key in a different +table, which is the basis for organizing wiring into namespaces. The redirection makes namespaces work. A namespace groups a context's components under a path prefix so several related components can be wired in one place and addressed by a shared path. diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index 2865a045..086eb55b 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -11,6 +11,7 @@ Satisfy a provider trait by routing back through the context's own consumer-trai ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `UseContext` turns a context's existing consumer-trait implementation into a provider that other providers can call. The [**context**](/docs/reference/glossary#context) is the type the implementation runs against, and it normally *uses* a provider through its consumer trait. Sometimes diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index 556f4403..aa457ebc 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -11,12 +11,13 @@ Select a component's implementation from the consumer trait's own default method ## Overview -`UseDefault` names the "use the trait's own defaults" choice in wiring. A consumer trait may define -default bodies for its methods, the same way any Rust trait can. When every method of a component has a -usable default, no behavior is left for a provider to supply, and the provider only needs to exist so -the component can be wired. `UseDefault` is that empty provider: wiring a component to `UseDefault` -selects an implementation whose method bodies come from the trait's defaults rather than from a -dedicated provider. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each trait +call, and `UseDefault` names the "use the trait's own defaults" choice in wiring. A consumer trait +may define default bodies for its methods, the same way any Rust trait can. When every method of a +component has a usable default, no behavior is left for a provider to supply, and the provider only +needs to exist so the component can be wired. `UseDefault` is that empty provider: wiring a +component to `UseDefault` selects an implementation whose method bodies come from the trait's +defaults rather than from a dedicated provider. This keeps a default-only component consistent with the rest of wiring. Without it, a component whose methods are all defaulted would still need some provider type and some diff --git a/docs/reference/providers/use_delegate.md b/docs/reference/providers/use_delegate.md index aaf481e7..f1675d41 100644 --- a/docs/reference/providers/use_delegate.md +++ b/docs/reference/providers/use_delegate.md @@ -21,13 +21,15 @@ statement of [`delegate_components!`](../macros/delegate_components.md) does the already has, with no separate table type and no wrapper. **Prefer `open` for anything new.** This page is here because you will meet `UseDelegate` in existing -code and in CGP's own error and handler components, which are still defined with `#[derive_delegate]`. +code and in the library's own error and handler components, which are still defined with +`#[derive_delegate]`. It is expected to be deprecated once `open` is shown to cover every dispatch case. ::: ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `UseDelegate` chooses a provider based on a type argument rather than on the component alone. An ordinary component picks its provider by looking the component name up in the [**context**](/docs/reference/glossary#context)'s delegation table, where the context is the type diff --git a/docs/reference/providers/use_delegated_type.md b/docs/reference/providers/use_delegated_type.md index ec490902..9bd60c33 100644 --- a/docs/reference/providers/use_delegated_type.md +++ b/docs/reference/providers/use_delegated_type.md @@ -11,8 +11,9 @@ Resolve an [abstract type](/docs/reference/glossary#abstract-type) by looking it ## Overview -`UseDelegatedType` is for the case where the concrete type an abstract type resolves to -should itself be decided by a table. The plain [`UseType`](use_type.md) provider binds an +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the types behind its traits, +and `UseDelegatedType` is for the case where the concrete type an abstract type resolves +to should itself be decided by a table. The plain [`UseType`](use_type.md) provider binds an abstract type to one fixed `T`. But sometimes a single provider must answer several abstract-type components at once, or route each type tag to a different concrete type chosen elsewhere, such as when a namespace or a [higher-order provider](/docs/reference/glossary#higher-order-provider) diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index 5a12d333..14c6fb20 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -12,12 +12,13 @@ decision rather than the method name. ## Overview -`UseField` decouples a getter's method name from the field it reads. A getter component defined -with [`#[cgp_getter]`](../macros/cgp_getter.md) describes a value the context can supply, such as -`fn name(&self) -> &str`. The [**context**](/docs/reference/glossary#context) is the type the method -runs on, which supplies the values it needs as its fields. But the context may store the value under -a different field name, say `first_name`, and different contexts may store it under different names. -`UseField` carries the field name as its type parameter, so wiring a getter to +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each trait +call, and `UseField` decouples a getter's method name from the field it reads. A getter +component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes a value the context can +supply, such as `fn name(&self) -> &str`. The [**context**](/docs/reference/glossary#context) is the +type the method runs on, which supplies the values it needs as its fields. But the context may store +the value under a different field name, say `first_name`, and different contexts may store it under +different names. `UseField` carries the field name as its type parameter, so wiring a getter to `UseField` makes it read `first_name` even though the method is `name`. The field name lives in the wiring, not in the trait. diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index 213a238b..d357a2aa 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -12,7 +12,8 @@ stored type differs from the getter's return type. ## Overview -`UseFieldRef` reads the field named by `Tag` from the +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each getter +call, and `UseFieldRef` reads the field named by `Tag` from the [**context**](/docs/reference/glossary#context) (the type the method runs on, which supplies the values it needs as its fields) and borrows it through `AsRef` to produce a `&Value`, where the stored field type implements `AsRef`. It exists for a getter whose return type is reached @@ -74,8 +75,8 @@ field is read at `Tag`. The body reads the field and calls `as_ref()`. The store also be `'static`, so a field holding a borrowed reference cannot be read this way. `UseFieldRef` also implements the mutable getter [`MutFieldGetter`](../traits/field-access/mut_field_getter.md), -requiring the field type to implement both `AsRef` and `AsMut` and returning `&mut Value` -through `as_mut()`. Because these are `FieldGetter` implementations rather than a getter component's own +requiring the field type to implement both `AsRef` and `AsMut` and to be `'static`, +and returning `&mut Value` through `as_mut()`. Because these are `FieldGetter` implementations rather than a getter component's own provider trait, the [`WithProvider`](with_provider.md) adapter behind `WithFieldRef` turns `UseFieldRef` into a provider a getter component can be wired to. Unlike [`UseField`](use_field.md), it does not implement [`TypeProvider`](../components/has_type.md), because its purpose is borrowed field diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 52179753..08806f3a 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -12,6 +12,7 @@ method. ## Overview +[Context-Generic Programming (CGP)](/docs/) enables pluggable trait implementations in Rust, and `UseFields` is the provider form of the convention "the method `name` reads the field `name`." A getter component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes one or more values the **context** can supply, and the most common arrangement is that each value lives in a diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index 6d858e91..a0aed6ac 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -24,8 +24,9 @@ different jobs. ## Overview -`UseType` removes the need to hand-write a provider every time a **context** wants to fix an -abstract type to a concrete one. The context is the +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the concrete type behind each +abstract type through wiring, and `UseType` removes the need to hand-write a provider every +time it wants to fix one. The context is the [type that implements the trait](/docs/reference/glossary#context), and it decides what each abstract type resolves to. An abstract type in CGP is a trait with a single associated type, defined with [`#[cgp_type]`](../macros/cgp_type.md), such as `trait HasScalarType { type Scalar; }`. Generic diff --git a/docs/reference/providers/with_context.md b/docs/reference/providers/with_context.md index 6444e33a..93681c13 100644 --- a/docs/reference/providers/with_context.md +++ b/docs/reference/providers/with_context.md @@ -12,14 +12,16 @@ context's own generic `HasType` or `HasField` entry. ## Overview -`WithContext` is the alias `WithProvider`. It pairs the [`WithProvider`](with_provider.md) -adapter with [`UseContext`](use_context.md), which implements the two foundational traits by asking -the [**context**](/docs/reference/glossary#context), the type the implementation runs against: +Under [Context-Generic Programming (CGP)](/docs/), a named component can take its answer from the +context's own foundational entry, and `WithContext` is the alias `WithProvider`. It +pairs the [`WithProvider`](with_provider.md) adapter with [`UseContext`](use_context.md), which +implements the two foundational traits by asking the +[**context**](/docs/reference/glossary#context), the type the implementation runs against: [`TypeProvider`](../components/has_type.md) through the context's own `HasType`, and [`FieldGetter`](../traits/field-access/field_getter.md) through its own `HasField`. `WithProvider` passes the component's marker as that tag, so wiring a component to `WithContext` -answers it from the context's `HasType` or `HasField` entry keyed by the component itself. Like every -CGP provider, it carries no runtime value. +answers it from the context's `HasType` or `HasField` entry keyed by the component itself. Like +every CGP provider, it carries no runtime value. `WithContext` is distinct from the bare [`UseContext`](use_context.md), and the two are not interchangeable. `UseContext` implements a component's provider trait *directly*, by calling the diff --git a/docs/reference/providers/with_delegated_type.md b/docs/reference/providers/with_delegated_type.md index abda340f..889cf211 100644 --- a/docs/reference/providers/with_delegated_type.md +++ b/docs/reference/providers/with_delegated_type.md @@ -11,10 +11,12 @@ Resolve one or more abstract-type components from a shared table, through the `W ## Overview -`WithDelegatedType` is the alias `WithProvider>`. It -answers a context's abstract-type components by looking each type tag up in the `Components` table, -on a [**context**](/docs/reference/glossary#context), the type that implements the trait, by -adapting the foundational [`UseDelegatedType`](use_delegated_type.md) provider through the +Under [Context-Generic Programming (CGP)](/docs/), several abstract types can be resolved from one +shared table, and `WithDelegatedType` is the alias +`WithProvider>`. It answers a context's abstract-type components by +looking each type tag up in the `Components` table, on a +[**context**](/docs/reference/glossary#context), the type that implements the trait, by adapting the +foundational [`UseDelegatedType`](use_delegated_type.md) provider through the [`WithProvider`](with_provider.md) layer. Like every CGP provider, it carries no runtime value. Unlike [`WithType`](with_type.md), this alias is not an alternative to a directly-wireable provider diff --git a/docs/reference/providers/with_field.md b/docs/reference/providers/with_field.md index 3621cd8b..d01218ee 100644 --- a/docs/reference/providers/with_field.md +++ b/docs/reference/providers/with_field.md @@ -11,6 +11,7 @@ Wire a getter component to a named context field, through the `WithProvider` ada ## Overview +Under [Context-Generic Programming (CGP)](/docs/), a getter can read a field chosen in wiring, and `WithField` is the alias `WithProvider>`. It implements a getter component by reading the context field named by `Tag`, on a [**context**](/docs/reference/glossary#context), the type the method runs on, by adapting the foundational [`UseField`](use_field.md) getter through diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md index 5686e696..c92ff5dd 100644 --- a/docs/reference/providers/with_field_ref.md +++ b/docs/reference/providers/with_field_ref.md @@ -11,6 +11,7 @@ Wire a getter component to a field borrowed through `AsRef`, through the `WithPr ## Overview +Under [Context-Generic Programming (CGP)](/docs/), a getter can borrow a field as another type, and `WithFieldRef` is the alias `WithProvider>`. It implements a getter component by reading the field named by `Tag` from the [**context**](/docs/reference/glossary#context), the type the method runs on, and borrowing it @@ -38,8 +39,8 @@ delegate_components! { ``` `Tag` names the field, as in [`UseField`](use_field.md), and `Value` is the type the getter exposes. The -stored field type must implement `AsRef` (and, for the mutable getter, `AsMut`), and the -getter's return type must be `&Value`. +stored field type must implement `AsRef` and be `'static` (and, for the mutable getter, also +`AsMut`), and the getter's return type must be `&Value`. ## Examples diff --git a/docs/reference/providers/with_provider.md b/docs/reference/providers/with_provider.md index 85f71e53..6250b925 100644 --- a/docs/reference/providers/with_provider.md +++ b/docs/reference/providers/with_provider.md @@ -12,8 +12,9 @@ specific named component. ## Overview -`WithProvider` bridges CGP's two layers of provider trait. Foundational traits like -[`TypeProvider`](../components/has_type.md) and +[Context-Generic Programming (CGP)](/docs/) separates foundational providers from named components +through two layers of provider trait, and `WithProvider` bridges them. Foundational traits +like [`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field-access/field_getter.md) are generic, component-agnostic mechanisms: a `TypeProvider` supplies *some* [abstract type](/docs/reference/glossary#abstract-type) for *some* tag, and a `FieldGetter` reads *some* field for *some* output tag, without either knowing which diff --git a/docs/reference/providers/with_type.md b/docs/reference/providers/with_type.md index a8a445ed..5f1735d7 100644 --- a/docs/reference/providers/with_type.md +++ b/docs/reference/providers/with_type.md @@ -11,12 +11,13 @@ Bind an abstract-type component to a concrete type, through the `WithProvider` a ## Overview -`WithType` is the alias `WithProvider>`. It binds an abstract-type component to the -concrete `Type` on a [**context**](/docs/reference/glossary#context), the type that implements the -trait, by adapting the foundational -[`UseType`](use_type.md) provider through the [`WithProvider`](with_provider.md) layer. It sets -the same [abstract type](/docs/reference/glossary#abstract-type) the plain [`UseType`](use_type.md) provider does, and both are interchangeable in -wiring. Like every CGP provider, it carries no runtime value. +Under [Context-Generic Programming (CGP)](/docs/), an abstract type is chosen through wiring, and +`WithType` is the alias `WithProvider>`. It binds an abstract-type component to +the concrete `Type` on a [**context**](/docs/reference/glossary#context), the type that implements +the trait, by adapting the foundational [`UseType`](use_type.md) provider through the +[`WithProvider`](with_provider.md) layer. It sets the same +[abstract type](/docs/reference/glossary#abstract-type) the plain [`UseType`](use_type.md) provider +does, and both are interchangeable in wiring. Like every CGP provider, it carries no runtime value. ## Usage From a709760908d1e2d1fcdc636eede900aa03d34def Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 21:16:07 +0100 Subject: [PATCH 284/516] Show the AsRef getter conversion and apply the review revisions The &str getter reads a String field and converts it with AsRef::as_ref, so the expansion blocks and prose on the getter provider pages now match `cargo cgp expand`. Six opening sentences name the page's own choice, and the handler index says a list runs in sequence. Co-Authored-By: deepseek-v4.1-flash --- .../providers/error/discard_detail.md | 4 +- .../providers/error/panic_on_error.md | 4 +- .../providers/error/raise_infallible.md | 4 +- .../reference/providers/error/return_error.md | 4 +- docs/reference/providers/handler/index.md | 4 +- docs/reference/providers/use_default.md | 6 +-- docs/reference/providers/use_field.md | 40 ++++++++++--------- docs/reference/providers/use_field_ref.md | 4 +- docs/reference/providers/use_fields.md | 28 ++++++++----- docs/reference/providers/use_type.md | 2 +- docs/reference/providers/with_field_ref.md | 2 +- docs/reference/providers/with_provider.md | 14 ++++--- 12 files changed, 64 insertions(+), 52 deletions(-) diff --git a/docs/reference/providers/error/discard_detail.md b/docs/reference/providers/error/discard_detail.md index 3fa4b18d..b563c0af 100644 --- a/docs/reference/providers/error/discard_detail.md +++ b/docs/reference/providers/error/discard_detail.md @@ -11,8 +11,8 @@ Wrap an error by throwing the detail away and returning the error unchanged. ## Overview -Under [Context-Generic Programming (CGP)](/docs/), a context chooses the wrapper behind each trait -call, and `DiscardDetail` is the `ErrorWrapper` provider that ignores whatever detail is attached +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the wrapper for each detail +type, and `DiscardDetail` is the `ErrorWrapper` provider that ignores whatever detail is attached and returns the error as it was. It satisfies the `CanWrapError` trait of a [**context**](/docs/reference/glossary#context), the type the implementation runs against, without enriching the error. This is useful when a context's error type cannot carry extra context, or when diff --git a/docs/reference/providers/error/panic_on_error.md b/docs/reference/providers/error/panic_on_error.md index dcaf85d7..a82c99f4 100644 --- a/docs/reference/providers/error/panic_on_error.md +++ b/docs/reference/providers/error/panic_on_error.md @@ -11,8 +11,8 @@ Abort with the source error's debug output instead of producing an abstract erro ## Overview -Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser behind each trait -call, and `PanicOnError` is the `ErrorRaiser` provider that panics rather than returning an error. +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser for each source +error, and `PanicOnError` is the `ErrorRaiser` provider that panics rather than returning an error. When a [**context**](/docs/reference/glossary#context), the type the implementation runs against, treats an error as a programming fault that should stop the program, `PanicOnError` raises by calling `panic!` with the source error's debug representation. Its signature promises to return the diff --git a/docs/reference/providers/error/raise_infallible.md b/docs/reference/providers/error/raise_infallible.md index 1186bac1..769d060c 100644 --- a/docs/reference/providers/error/raise_infallible.md +++ b/docs/reference/providers/error/raise_infallible.md @@ -11,8 +11,8 @@ Absorb `core::convert::Infallible`, the error type that can never be constructed ## Overview -Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser behind each trait -call, and `RaiseInfallible` is the `ErrorRaiser` provider for `core::convert::Infallible`, an error +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser for each source +error, and `RaiseInfallible` is the `ErrorRaiser` provider for `core::convert::Infallible`, an error type with no values. It lets generic code that raises the error of a fallible operation be wired uniformly on a [**context**](/docs/reference/glossary#context), the type the implementation runs against, even when the operation chosen for that context cannot fail. Because an `Infallible` value diff --git a/docs/reference/providers/error/return_error.md b/docs/reference/providers/error/return_error.md index 5b855338..b3ed1fef 100644 --- a/docs/reference/providers/error/return_error.md +++ b/docs/reference/providers/error/return_error.md @@ -11,8 +11,8 @@ Raise a source error that already is the context's abstract error, so raising is ## Overview -Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser behind each trait -call, and `ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly +Under [Context-Generic Programming (CGP)](/docs/), a context chooses the raiser for each source +error, and `ReturnError` is the `ErrorRaiser` provider for the case where the source error is exactly the abstract error the [**context**](/docs/reference/glossary#context) chose, where the context is the type the implementation runs against. Raising then has nothing to convert: it returns its argument untouched. A context uses it when generic code raises a value that is already of the diff --git a/docs/reference/providers/handler/index.md b/docs/reference/providers/handler/index.md index 3a5d8707..596bcb86 100644 --- a/docs/reference/providers/handler/index.md +++ b/docs/reference/providers/handler/index.md @@ -6,8 +6,8 @@ sidebar_position: 0 # Handler combinators -The providers that build, sequence, and adapt handlers: composing them end to end, threading a list -through a pipeline, returning the input unchanged, and lifting one handler shape into another. +The providers that build, sequence, and adapt handlers: composing them end to end, running a list in +sequence, returning the input unchanged, and lifting one handler shape into another. ## Overview diff --git a/docs/reference/providers/use_default.md b/docs/reference/providers/use_default.md index aa457ebc..b1db6976 100644 --- a/docs/reference/providers/use_default.md +++ b/docs/reference/providers/use_default.md @@ -11,9 +11,9 @@ Select a component's implementation from the consumer trait's own default method ## Overview -Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each trait -call, and `UseDefault` names the "use the trait's own defaults" choice in wiring. A consumer trait -may define default bodies for its methods, the same way any Rust trait can. When every method of a +Under [Context-Generic Programming (CGP)](/docs/), a component can take its behavior from the +trait's own default bodies, and `UseDefault` names that choice in wiring. A consumer trait may +define default bodies for its methods, the same way any Rust trait can. When every method of a component has a usable default, no behavior is left for a provider to supply, and the provider only needs to exist so the component can be wired. `UseDefault` is that empty provider: wiring a component to `UseDefault` selects an implementation whose method bodies come from the trait's diff --git a/docs/reference/providers/use_field.md b/docs/reference/providers/use_field.md index 14c6fb20..ad285818 100644 --- a/docs/reference/providers/use_field.md +++ b/docs/reference/providers/use_field.md @@ -12,13 +12,13 @@ decision rather than the method name. ## Overview -Under [Context-Generic Programming (CGP)](/docs/), a context chooses the provider behind each trait -call, and `UseField` decouples a getter's method name from the field it reads. A getter -component defined with [`#[cgp_getter]`](../macros/cgp_getter.md) describes a value the context can -supply, such as `fn name(&self) -> &str`. The [**context**](/docs/reference/glossary#context) is the -type the method runs on, which supplies the values it needs as its fields. But the context may store -the value under a different field name, say `first_name`, and different contexts may store it under -different names. `UseField` carries the field name as its type parameter, so wiring a getter to +Under [Context-Generic Programming (CGP)](/docs/), a getter's field is a wiring choice, and +`UseField` decouples the method name from the field it reads. A getter component defined with +[`#[cgp_getter]`](../macros/cgp_getter.md) describes a value the context can supply, such as +`fn name(&self) -> &str`. The [**context**](/docs/reference/glossary#context) is the type the method +runs on, which supplies the values it needs as its fields. But the context may store the value under +a different field name, say `first_name`, and different contexts may store it under different names. +`UseField` carries the field name as its type parameter, so wiring a getter to `UseField` makes it read `first_name` even though the method is `name`. The field name lives in the wiring, not in the trait. @@ -113,12 +113,12 @@ trait at all. Where a [getter trait](/docs/reference/glossary#getter-trait) is g each method on its own name. The [`#[cgp_getter]`](../macros/cgp_getter.md) page works the choice through in full. -`UseField` already handles the common borrowed-view getters: a `-> &str` getter over a `String` field -and a `-> &[u8]` getter over a `Vec` field work through `UseField`, because the generated -implementation borrows through `as_str()` or `as_ref()` based on the return type. Two neighbours cover -the cases it does not. When a getter returns `&T` and the field is stored as a different type that -borrows to `T` through `AsRef`, use [`UseFieldRef`](use_field_ref.md). When the field lives several hops -inside a nested context, use [`ChainGetters`](chain_getters.md). +`UseField` already handles the common borrowed-view getters: a `-> &str` getter over a `String` +field and a `-> &[u8]` getter over a `Vec` field work through `UseField`, because the generated +implementation borrows the field through `AsRef::as_ref` to match the return type. Two neighbours +cover the cases it does not. When a getter returns `&T` and the field is stored as a different type +that borrows to `T` through `AsRef`, use [`UseFieldRef`](use_field_ref.md). When the field lives +several hops inside a nested context, use [`ChainGetters`](chain_getters.md). ## Under the hood @@ -136,7 +136,9 @@ where __Context__: HasField<__Tag__, Value = String>, { fn name(__context__: &__Context__) -> &str { - __context__.get_field(::core::marker::PhantomData::<__Tag__>).as_str() + ::core::convert::AsRef::as_ref( + HasField::get_field(__context__, ::core::marker::PhantomData::<__Tag__>), + ) } } @@ -147,11 +149,11 @@ where {} ``` -The `&str` return reads a `String` field and appends `.as_str()`, the getter macros' return-type -shorthand. The paired [`IsProviderFor`](../traits/wiring/is_provider_for.md) implementation carries -the same `HasField` bound, so a check names a missing field precisely. A getter with more than one -method gets no `UseField` implementation, since one tag cannot name several fields; -[Common Mistakes](#common-mistakes) shows the error. +The `&str` return reads a `String` field and wraps the read in `AsRef::as_ref`, the getter macros' +return-type shorthand. The paired [`IsProviderFor`](../traits/wiring/is_provider_for.md) +implementation carries the same `HasField` bound, so a check names a missing field precisely. A +getter with more than one method gets no `UseField` implementation, since one tag cannot name +several fields; [Common Mistakes](#common-mistakes) shows the error. **The foundational field getters.** `UseField` implements [`FieldGetter`](../traits/field-access/field_getter.md), which reads the field by reference: diff --git a/docs/reference/providers/use_field_ref.md b/docs/reference/providers/use_field_ref.md index d357a2aa..b9856f99 100644 --- a/docs/reference/providers/use_field_ref.md +++ b/docs/reference/providers/use_field_ref.md @@ -28,8 +28,8 @@ component's own provider, so it is wired through its [`WithFieldRef`](with_field Most borrowed-view getters do not need `UseFieldRef` at all, and this is the key thing to know before reaching for it. When a getter's return type is one of the shorthands the getter macros recognize, the generated [`UseField`](use_field.md) implementation already borrows for you: a `&str` -getter reads a `String` field through `.as_str()`, a `&[T]` getter reads any `'static` field -implementing `AsRef<[T]>`, such as a `Vec`, through `.as_ref()`, and an `Option<&T>` or +getter reads a `String` field through `AsRef::as_ref`, a `&[T]` getter reads any `'static` field +implementing `AsRef<[T]>`, such as a `Vec`, through `AsRef::as_ref`, and an `Option<&T>` or `Option<&str>` getter reads an `Option` or `Option` field. Each is wired with a plain `UseField`. `UseFieldRef` is for the remaining case, a getter that returns `&T` for some type `T` the field is not stored as but can be borrowed as. Like every CGP provider, it carries no runtime diff --git a/docs/reference/providers/use_fields.md b/docs/reference/providers/use_fields.md index 08806f3a..10b4e2ce 100644 --- a/docs/reference/providers/use_fields.md +++ b/docs/reference/providers/use_fields.md @@ -51,10 +51,11 @@ delegate_components! { } ``` -Every method of the getter reads the context field whose name equals the method name. The context must -have a `HasField` implementation for each of those names, which -[`#[derive(HasField)]`](../derives/derive_has_field.md) supplies. The return-type shorthands the getter -macros support apply here too, so a `&str` return reads a `String` field and appends `.as_str()`. +Every method of the getter reads the context field whose name equals the method name. The context +must have a `HasField` implementation for each of those names, which +[`#[derive(HasField)]`](../derives/derive_has_field.md) supplies. The return-type shorthands the +getter macros support apply here too, so a `&str` return reads a `String` field and wraps the read +in `AsRef::as_ref`. ## Examples @@ -128,21 +129,26 @@ where __Context__: HasField, { fn foo(__context__: &__Context__) -> &str { - __context__.get_field(::core::marker::PhantomData::).as_str() + ::core::convert::AsRef::as_ref( + HasField::get_field( + __context__, + ::core::marker::PhantomData::, + ), + ) } fn bar(__context__: &__Context__) -> &u8 { - __context__.get_field(::core::marker::PhantomData::) + HasField::get_field(__context__, ::core::marker::PhantomData::) } } ``` Each method becomes a `HasField` bound keyed on the method name as a `Symbol!`, and the body reads -that field. The `&str` return makes the field `Value` a `String` and appends `.as_str()`, the same -shorthand [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) uses. The implementation carries one -`HasField` bound and one body per method, each keyed by its own name. The implementation is paired -with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md), so a check reports a missing -field precisely. +that field. The `&str` return makes the field `Value` a `String` and wraps the read in +`AsRef::as_ref`, the same shorthand [`#[cgp_auto_getter]`](../macros/cgp_auto_getter.md) uses. The +implementation carries one `HasField` bound and one body per method, each keyed by its own name. The +implementation is paired with a matching [`IsProviderFor`](../traits/wiring/is_provider_for.md), so +a check reports a missing field precisely. This is one of three provider implementations `#[cgp_getter]` generates for a getter component, and the only one a getter with several methods gets. The other two, [`UseField`](use_field.md) for a diff --git a/docs/reference/providers/use_type.md b/docs/reference/providers/use_type.md index a0aed6ac..f69265d0 100644 --- a/docs/reference/providers/use_type.md +++ b/docs/reference/providers/use_type.md @@ -26,7 +26,7 @@ different jobs. Under [Context-Generic Programming (CGP)](/docs/), a context chooses the concrete type behind each abstract type through wiring, and `UseType` removes the need to hand-write a provider every -time it wants to fix one. The context is the +time the context wants to fix one. The context is the [type that implements the trait](/docs/reference/glossary#context), and it decides what each abstract type resolves to. An abstract type in CGP is a trait with a single associated type, defined with [`#[cgp_type]`](../macros/cgp_type.md), such as `trait HasScalarType { type Scalar; }`. Generic diff --git a/docs/reference/providers/with_field_ref.md b/docs/reference/providers/with_field_ref.md index c92ff5dd..713bed02 100644 --- a/docs/reference/providers/with_field_ref.md +++ b/docs/reference/providers/with_field_ref.md @@ -135,7 +135,7 @@ error[E0271]: type mismatch resolving `` bridges them. Foundational traits -like [`TypeProvider`](../components/has_type.md) and +[Context-Generic Programming (CGP)](/docs/) has two layers of provider trait, one foundational and +one per named component, and `WithProvider` bridges them. Foundational traits like +[`TypeProvider`](../components/has_type.md) and [`FieldGetter`](../traits/field-access/field_getter.md) are generic, component-agnostic mechanisms: a `TypeProvider` supplies *some* [abstract type](/docs/reference/glossary#abstract-type) for *some* tag, and a `FieldGetter` reads *some* field for *some* output tag, without either knowing which @@ -151,8 +151,12 @@ where __Provider__: FieldGetter<__Context__, NameGetterComponent, Value = String>, { fn name(__context__: &__Context__) -> &str { - __Provider__::get_field(__context__, ::core::marker::PhantomData::) - .as_str() + ::core::convert::AsRef::as_ref( + __Provider__::get_field( + __context__, + ::core::marker::PhantomData::, + ), + ) } } ``` From dcbd155ce0c204a7c803a4672c5a51a2aaf0ff84 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:29:17 +0100 Subject: [PATCH 285/516] Name the project on the comparisons index and order the sidebar The index page opened with the abbreviation and never named Context-Generic Programming, and it stated the whole tag line, which belongs on the pages that present the project. It now names the project in full in its opening, links the Introduction, and relates the short form to the comparisons. C++ policy-based design also moves to sidebar position 2, where the guide and the index table place it, so the sidebar matches the routing order. --- docs/comparisons/index.md | 18 +++++++++--------- docs/comparisons/policy-based-design.md | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/comparisons/index.md b/docs/comparisons/index.md index 2bc26723..7eb720f4 100644 --- a/docs/comparisons/index.md +++ b/docs/comparisons/index.md @@ -1,20 +1,20 @@ --- sidebar_label: 'Overview' sidebar_position: 0 -description: 'Compare CGP with familiar programming models through vocabulary, examples, trade-offs, and limits.' +description: 'Compare Context-Generic Programming with familiar programming models through vocabulary, examples, trade-offs, and limits.' --- # Comparisons -These pages explain CGP through related ideas you may already know: dependency injection, -type classes, effect handlers, dynamic dispatch, and other approaches to reusable implementations. -Each comparison maps the vocabulary, illustrates the mechanisms, and explains the costs and cases -where the other approach fits better. +These pages place [Context-Generic Programming](/docs/) beside the ideas you may already know: +dependency injection, type classes, effect handlers, dynamic dispatch, and other approaches to +reusable implementations. CGP extends Rust with pluggable trait implementations, chosen per context +and resolved at compile time, and each comparison maps one familiar model onto that machinery, then +marks where the correspondence stops. -CGP is a language extension for Rust, with pluggable trait implementations at compile-time. -It is a library on stable Rust, and its consumer traits are ordinary Rust traits. The -[Introduction](/docs/) explains those foundations; the comparisons focus on how they relate to -other programming models. +CGP is a library on stable Rust, and a consumer trait is an ordinary Rust trait. Every page states +that frame, because the comparison is about where the ideas meet rather than about abandoning the +other tool. ## Which page to read diff --git a/docs/comparisons/policy-based-design.md b/docs/comparisons/policy-based-design.md index 59fa9ac0..4e2f7ff6 100644 --- a/docs/comparisons/policy-based-design.md +++ b/docs/comparisons/policy-based-design.md @@ -1,6 +1,6 @@ --- sidebar_label: 'Policy-based design' -sidebar_position: 5 +sidebar_position: 2 description: 'CGP read against C++ policy classes, host templates, CRTP, and concepts, for a reader who composes behavior with templates.' --- From 38679c5ead15fbef1b71d17578e6d523e45e2072 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:30:59 +0100 Subject: [PATCH 286/516] Name the project on the algebraic effects comparison The page opened with the abbreviation and stated the whole tag line, which belongs on the pages that present the project. Its opening now names Context-Generic Programming, links the Introduction, and relates the short form to the comparison, and its description names the project for search. --- docs/comparisons/algebraic-effects.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/comparisons/algebraic-effects.md b/docs/comparisons/algebraic-effects.md index fca7a523..4242d28b 100644 --- a/docs/comparisons/algebraic-effects.md +++ b/docs/comparisons/algebraic-effects.md @@ -1,17 +1,17 @@ --- sidebar_label: 'Algebraic effects' sidebar_position: 6 -description: 'Compare CGP providers with algebraic effect handlers: shared operation interfaces, static selection, and the continuation boundary.' +description: 'Compare Context-Generic Programming providers with algebraic effect handlers: shared operation interfaces, static selection, and the continuation boundary.' --- # Algebraic effects and handlers -CGP separates operations from their implementations, much as algebraic effects separate operations -from handlers, but CGP does not capture continuations. It is a language extension for Rust, with -pluggable trait implementations at compile-time, implemented as a library on stable Rust whose -consumer traits are ordinary Rust traits; the [Introduction](/docs/) covers the basics. For readers -familiar with Koka, OCaml 5, Flix, or Eff, this page develops the correspondence with handlers that -resume in place, its limits, and the costs of each approach. +[Context-Generic Programming](/docs/) separates operations from their implementations, much as +algebraic effects separate operations from handlers, but CGP does not capture continuations. CGP +extends Rust with pluggable trait implementations, chosen per context and resolved at compile time, +as a library on stable Rust whose consumer traits are ordinary Rust traits. For readers familiar +with Koka, OCaml 5, Flix, or Eff, this page develops the correspondence with handlers that resume in +place, its limits, and the costs of each approach. ## In your terms From 4d8039a133610a9f385076d622f3a47f6c664b2d Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:31:53 +0100 Subject: [PATCH 287/516] Name the project on the capabilities comparison The page opened with the abbreviation, so it never introduced Context-Generic Programming to a reader who arrives from a search for "capabilities in Rust". Its opening now names the project, links the Introduction, and relates the short form, and its description names the project for search. --- docs/comparisons/capabilities.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/comparisons/capabilities.md b/docs/comparisons/capabilities.md index fcb4c010..4b2e5014 100644 --- a/docs/comparisons/capabilities.md +++ b/docs/comparisons/capabilities.md @@ -1,17 +1,16 @@ --- sidebar_label: 'Capabilities' sidebar_position: 11 -description: 'Distinguish capability models and compare their guarantees with CGP dependency checks and context fields.' +description: 'Distinguish capability models and compare their guarantees with Context-Generic Programming dependency checks and context fields.' --- # Capabilities -CGP can declare dependencies and carry capability values, but it does not enforce a security -boundary. It is a language extension for Rust, with pluggable trait implementations at -compile-time, implemented as a library on stable Rust whose consumer traits are ordinary Rust -traits; the [Introduction](/docs/) covers the basics. This page separates object capabilities, -effects as capabilities, and other uses of the term, then explains which properties CGP shares -and which must come from another system. +[Context-Generic Programming](/docs/) can declare dependencies and carry capability values, but it +does not enforce a security boundary. CGP extends Rust with pluggable trait implementations, chosen +per context and resolved at compile time, as a library on stable Rust whose consumer traits are +ordinary Rust traits. This page separates object capabilities, effects as capabilities, and other +uses of the term, then explains which properties CGP shares and which must come from another system. ## In your terms From bfd63f452373622cd8d209fae19452fcca904bf6 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:32:28 +0100 Subject: [PATCH 288/516] Name the project on the dependency injection comparison The page opened with the abbreviation and stated the whole tag line. Its opening now names Context-Generic Programming, links the Introduction, and relates the short form to the injection comparison, and its description names the project for search. --- docs/comparisons/dependency-injection.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/comparisons/dependency-injection.md b/docs/comparisons/dependency-injection.md index f858a805..17788080 100644 --- a/docs/comparisons/dependency-injection.md +++ b/docs/comparisons/dependency-injection.md @@ -1,16 +1,16 @@ --- sidebar_label: 'Dependency injection' sidebar_position: 8 -description: 'Compare CGP with Spring, Guice, Dagger, and plain Rust injection: dependency declarations, wiring, validation, and runtime values.' +description: 'Compare Context-Generic Programming with Spring, Guice, Dagger, and plain Rust injection: dependency declarations, wiring, validation, and runtime values.' --- # Dependency injection -CGP supports dependency injection through reusable providers selected by each application. It is a language extension for Rust, with pluggable trait implementations at -compile-time, implemented as a library on stable Rust whose consumer traits are ordinary Rust -traits; the [Introduction](/docs/) explains the basics. For readers familiar with Spring, Guice, -Dagger, or constructor injection, this page compares dependency declarations, wiring, validation, -and the cases that still call for a container. +[Context-Generic Programming](/docs/) supports dependency injection through reusable providers +selected by each application: CGP extends Rust with pluggable trait implementations, chosen per +context and resolved at compile time, as a library on stable Rust whose consumer traits are ordinary +Rust traits. For readers familiar with Spring, Guice, Dagger, or constructor injection, this page +compares dependency declarations, wiring, validation, and the cases that still call for a container. ## In your terms From 3790635e783b030673927d61a1936d4947cd96e4 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:33:14 +0100 Subject: [PATCH 289/516] Name the project on the dynamic dispatch comparison The page opened with the abbreviation and stated the whole tag line. Its opening now names Context-Generic Programming, links the Introduction, and relates the short form to the dispatch comparison, and its description names the project for search. The Sources entry for the MDN prototype-chain guide also pointed at a path MDN does not serve, so it now uses the same URL as the body's link. --- docs/comparisons/dynamic-dispatch.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/comparisons/dynamic-dispatch.md b/docs/comparisons/dynamic-dispatch.md index 7a47275c..8b563fd2 100644 --- a/docs/comparisons/dynamic-dispatch.md +++ b/docs/comparisons/dynamic-dispatch.md @@ -1,17 +1,17 @@ --- sidebar_label: 'Dynamic dispatch' sidebar_position: 9 -description: 'Compare CGP static wiring with dynamic dispatch, duck typing, and prototype delegation, including how trait objects can coexist with CGP.' +description: 'Compare Context-Generic Programming static wiring with dynamic dispatch, duck typing, and prototype delegation, including how trait objects can coexist with CGP.' --- # Dynamic dispatch, dynamic typing, and prototypal inheritance -CGP supports interchangeable implementations and delegation while resolving provider selection at -compile time. It is a language extension for Rust, with pluggable trait implementations at -compile-time, implemented as a library on stable Rust whose consumer traits are ordinary Rust -traits; the [Introduction](/docs/) covers the basics. For readers familiar with objects, messages, -vtables, or prototypes, this page explains the shared structure, the limits of static selection, -and where runtime dispatch remains useful. +[Context-Generic Programming](/docs/) supports interchangeable implementations and delegation while +resolving provider selection at compile time. CGP extends Rust with pluggable trait implementations, +chosen per context and resolved at compile time, as a library on stable Rust whose consumer traits +are ordinary Rust traits. For readers familiar with objects, messages, vtables, or prototypes, this +page explains the shared structure, the limits of static selection, and where runtime dispatch +remains useful. ## In your terms @@ -312,7 +312,7 @@ wired context. This page contains only Rust snippets. - [Wikipedia, *Dynamic dispatch*](https://en.wikipedia.org/wiki/Dynamic_dispatch), [*Virtual method table*](https://en.wikipedia.org/wiki/Virtual_method_table), and [*Duck typing*](https://en.wikipedia.org/wiki/Duck_typing): late binding, the vtable, and usability decided by the methods an object has. - [The Rust Programming Language, *Trait objects*](https://doc.rust-lang.org/book/ch18-02-trait-objects.html) and [geo-ant, *Rust Dyn Trait Objects and Fat Pointers*](https://geo-ant.github.io/blog/2023/rust-dyn-trait-objects-fat-pointers/): Rust's own dynamic dispatch as a fat pointer and a vtable. - [Lieberman, *Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems* (OOPSLA 1986)](https://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html): delegation, and the rule that `self` stays bound to the original receiver. -- [MDN, *Inheritance and the prototype chain*](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain): JavaScript's prototype chain and own-property shadowing. +- [MDN, *Inheritance and the prototype chain*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain): JavaScript's prototype chain and own-property shadowing. - [V8, *Maps (Hidden Classes)*](https://v8.dev/docs/hidden-classes): the engineering that dynamic dispatch's runtime cost demands. - [SitePoint, *Making Ruby Quack*](https://www.sitepoint.com/making-ruby-quack-why-we-love-duck-typing/), [GeeksforGeeks, *Type Systems*](https://www.geeksforgeeks.org/python/type-systemsdynamic-typing-static-typing-duck-typing/), and [DevGex, *Duck Typing*](https://devgex.com/en/article/00035033): community sentiment on what duck typing buys and costs. From 13cfa51e8c14e80f0c2632260f8b3185622b8d56 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:45:36 +0100 Subject: [PATCH 290/516] Name the project on the implicit parameters comparison The page opened with the abbreviation and stated the whole tag line. Its opening now names Context-Generic Programming, links the Introduction, and relates the short form to the implicit-parameter comparison, and its description names the project for search. The Scala syntax note now says that parts of the given syntax changed in 3.6 and that the original form remains accepted for now, which is what the reference says. --- docs/comparisons/implicit-parameters.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/comparisons/implicit-parameters.md b/docs/comparisons/implicit-parameters.md index cfc64954..98b13b9b 100644 --- a/docs/comparisons/implicit-parameters.md +++ b/docs/comparisons/implicit-parameters.md @@ -1,17 +1,17 @@ --- sidebar_label: 'Implicit parameters' sidebar_position: 5 -description: 'Compare CGP context fields and wiring with Scala contextual parameters, Haskell implicit parameters, and type-class selection.' +description: 'Compare Context-Generic Programming context fields and wiring with Scala contextual parameters, Haskell implicit parameters, and type-class selection.' --- # Implicit parameters -CGP supplies implicit arguments from a context's fields and selects implementations through wiring. -It is a language extension for Rust, with pluggable trait implementations at compile-time, -implemented as a library on stable Rust whose consumer traits are ordinary Rust traits; the -[Introduction](/docs/) explains the basics. For readers familiar with Scala's `given` and `using`, -Haskell's `ImplicitParams`, or `Reader`, this page compares how dependencies travel through a -program, how implementations are selected, and what each approach costs. +[Context-Generic Programming](/docs/) supplies implicit arguments from a context's fields and +selects implementations through wiring. CGP extends Rust with pluggable trait implementations, +chosen per context and resolved at compile time, as a library on stable Rust whose consumer traits +are ordinary Rust traits. For readers familiar with Scala's `given` and `using`, Haskell's +`ImplicitParams`, or `Reader`, this page compares how dependencies travel through a program, how +implementations are selected, and what each approach costs. ## In your terms @@ -56,9 +56,9 @@ renderWebsite("/home") // the given Config is supplied automatically Scala uses contextual parameters for type classes as well as configuration values. A `given Comparator[Int]` supplies the implementation required by a `using Comparator[A]` parameter. -Scala 3.6 introduced the colon form for a given with a body; the older -`given Comparator[Int] with` form is also accepted. See the -[Scala reference](https://docs.scala-lang.org/scala3/reference/contextual/givens.html). +Parts of the given syntax changed in Scala 3.6, including the colon form for a given with a body. +The original `given Comparator[Int] with` form remains accepted for now and will be phased out. See +the [Scala reference](https://docs.scala-lang.org/scala3/reference/contextual/givens.html). ```scala trait Comparator[A]: From b462f530e4c918cf799524160e0f11ace9f01e95 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:46:24 +0100 Subject: [PATCH 291/516] Name the project on the ML modules comparison The page opened with the abbreviation and stated the whole tag line in a second paragraph. Its opening now names Context-Generic Programming, links the Introduction, and relates the short form to the module comparison, and its description names the project for search. --- docs/comparisons/ml-modules.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/docs/comparisons/ml-modules.md b/docs/comparisons/ml-modules.md index 3aa87e72..1f94ffb9 100644 --- a/docs/comparisons/ml-modules.md +++ b/docs/comparisons/ml-modules.md @@ -1,20 +1,19 @@ --- sidebar_label: 'ML modules' sidebar_position: 4 -description: 'CGP read against OCaml and Standard ML signatures, structures, functors, and modular implicits.' +description: 'Compare Context-Generic Programming components, providers, and higher-order providers with OCaml and Standard ML signatures, structures, functors, and modular implicits.' --- # ML modules and modular implicits -CGP lets Rust programs assemble named implementations through a context's wiring table. For an -ML programmer, its components, providers, and [higher-order providers](/docs/reference/glossary#higher-order-provider) play roles similar to +[Context-Generic Programming](/docs/) lets Rust programs assemble named implementations through a +context's wiring table. CGP extends Rust with pluggable trait implementations, chosen per context +and resolved at compile time, as a library on stable Rust whose consumer traits are ordinary Rust +traits. For an ML programmer, its components, providers, and +[higher-order providers](/docs/reference/glossary#higher-order-provider) play roles similar to signatures, structures, and functors. The correspondence explains how to compose implementations; -ML's sealing and module type identities need a separate account. - -CGP is a language extension for Rust, with pluggable trait implementations at compile-time. It is -implemented as a library on stable Rust, and its consumer traits are ordinary Rust traits. The -[Introduction](/docs/) covers the basics. This page assumes familiarity with OCaml or Standard ML -modules and also compares the proposed OCaml modular-implicits extension. +ML's sealing and module type identities need a separate account. This page assumes familiarity with +OCaml or Standard ML modules and also compares the proposed OCaml modular-implicits extension. ## In your terms From 9d49cef1edde87f833cc6cc26112970141993dd7 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:47:05 +0100 Subject: [PATCH 292/516] Name the project on the policy-based design comparison The page opened with the abbreviation and stated the whole tag line in a second paragraph. Its opening now names Context-Generic Programming, links the Introduction, and relates the short form to the policy comparison, and its description names the project for search. --- docs/comparisons/policy-based-design.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/docs/comparisons/policy-based-design.md b/docs/comparisons/policy-based-design.md index 4e2f7ff6..66d66f89 100644 --- a/docs/comparisons/policy-based-design.md +++ b/docs/comparisons/policy-based-design.md @@ -1,20 +1,18 @@ --- sidebar_label: 'Policy-based design' sidebar_position: 2 -description: 'CGP read against C++ policy classes, host templates, CRTP, and concepts, for a reader who composes behavior with templates.' +description: 'Compare Context-Generic Programming providers and wiring with C++ policy classes, host templates, CRTP, and concepts.' --- # C++ policy-based design -CGP and C++ policy-based design compose behavior from implementations chosen at compile time. A CGP -provider plays a policy's role, and a context supplies the host's data and implementation choices. -The main differences are how interfaces are declared, how generic bodies are checked, and where -an application records its choices. - -CGP is a language extension for Rust, with pluggable trait implementations at compile-time. It is -implemented as a library on stable Rust, and its consumer traits are ordinary Rust traits. The -[Introduction](/docs/) covers the basics. This page assumes familiarity with policy classes, the -curiously recurring template pattern (CRTP), and C++20 concepts. +[Context-Generic Programming](/docs/) and C++ policy-based design compose behavior from +implementations chosen at compile time. A CGP provider plays a policy's role, and a context supplies +the host's data and implementation choices. CGP extends Rust with pluggable trait implementations, +chosen per context and resolved at compile time, as a library on stable Rust whose consumer traits +are ordinary Rust traits. The main differences are how interfaces are declared, how generic bodies +are checked, and where an application records its choices. This page assumes familiarity with policy +classes, the curiously recurring template pattern (CRTP), and C++20 concepts. ## In your terms From a6f2d3d4bda55c909f5f634e79468f4c50118b2b Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:49:19 +0100 Subject: [PATCH 293/516] Remove spaces before punctuation after code spans and links The three pages put a space before a comma, period, colon, or semicolon that followed an inline code span or a link, which reads as a typo and came from an earlier reflow. The punctuation now sits against the span or link. --- docs/comparisons/row-polymorphism.md | 22 +++++++------- docs/comparisons/rust-language-proposals.md | 32 ++++++++++----------- docs/comparisons/type-classes.md | 22 +++++++------- 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/docs/comparisons/row-polymorphism.md b/docs/comparisons/row-polymorphism.md index 0ef257c2..a2cebc40 100644 --- a/docs/comparisons/row-polymorphism.md +++ b/docs/comparisons/row-polymorphism.md @@ -7,14 +7,14 @@ description: "How CGP expresses field access, record building, and variant opera # Row polymorphism, structural typing, and extensible data types CGP gives Rust structs and enums selected forms of structural reuse through derived field lists and -trait bounds. It is a language extension built as a [stable Rust library](/docs/) , with pluggable +trait bounds. It is a language extension built as a [stable Rust library](/docs/), with pluggable implementations behind ordinary Rust traits. This page compares its field access, builders, and variant operations with PureScript rows and OCaml polymorphic variants. ## In your terms A **context** is the type a CGP method runs on. The examples here operate directly on records and -enums, so their contexts are [value contexts](/docs/reference/glossary#value-context) . Field access +enums, so their contexts are [value contexts](/docs/reference/glossary#value-context). Field access uses derived traits; component-based operations can also use wiring to select providers. The row operations map onto CGP constructs as follows: @@ -48,7 +48,7 @@ nominal identities even when their fields match; CGP adds structural operations Row polymorphism uses a *row variable* to describe the fields a function does not name. The function accepts any record with its required fields, while the variable carries the remaining fields ([Wikipedia, *Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism)). In PureScript a -*row* is "an unordered collection of named types", of kind `Row k` , and a record is a row wrapped +*row* is "an unordered collection of named types", of kind `Row k`, and a record is a row wrapped by `Record` ([PureScript language reference](https://github.com/purescript/documentation/blob/master/language/Types.md)). An open row adds a tail variable after a pipe: @@ -63,7 +63,7 @@ fullName { firstName: "Ada", lastName: "Lovelace" } -- ok fullName { firstName: "Ada", lastName: "Lovelace", age: 36 } -- also ok; age flows through `r` ``` -PureScript checks row operations through the `Prim.Row` classes `Cons` , `Union` , `Nub` , and +PureScript checks row operations through the `Prim.Row` classes `Cons`, `Union`, `Nub`, and `Lacks` ([Pursuit, *Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row)). PureScript's design descends from Wand's row variables (1987), Rémy's principal types for rows (1989), and Leijen's scoped labels (2005), which PureScript adopts directly ([Leijen, *Extensible records with @@ -116,7 +116,7 @@ build values and containment to read them; variants reverse those roles ([Morris The evidence for these relationships can also implement the operation. Evidence that a record contains a field supplies the code that reads it. This connection matters for CGP because its trait implementations both satisfy constraints and perform field access or conversion. Rows also describe -effect sets, as in [Koka](https://arxiv.org/pdf/1406.2061) ; the +effect sets, as in [Koka](https://arxiv.org/pdf/1406.2061); the [algebraic effects](./algebraic-effects.md) page covers that use. ## How CGP expresses it @@ -128,7 +128,7 @@ field and variant requirements that row predicates express in a row system. `#[derive(HasFields)]` gives a struct the type-level equivalent of a closed row, with one `Field` entry per field, each tagged by a -[type-level string](/docs/reference/glossary#type-level-string) : +[type-level string](/docs/reference/glossary#type-level-string): ```rust #[derive(HasField, HasFields)] @@ -145,7 +145,7 @@ pub struct Person { ``` PureScript's `fullName` names its required fields with an open row. A CGP function names them as -[implicit arguments](/docs/concepts/implicit-arguments) , and any context with those fields +[implicit arguments](/docs/concepts/implicit-arguments), and any context with those fields satisfies it: ```rust @@ -195,9 +195,9 @@ row. The [Extensible records](/docs/concepts/extensible-records) page develops t CGP tracks field presence with a flag per field, as Rémy's presence polymorphism does. The flags are [`MapType`](/docs/reference/traits/type-level/map_type) markers on a partial record: `IsPresent` stores the value, `IsNothing` stores nothing, and the -[optional-field extensions](/docs/reference/traits/optional/) add `IsOptional` . A builder starts -with every field marked `IsNothing` , and each step changes one marker. `FinalizeBuild` is -implemented only when every marker is `IsPresent` . On the variant side, `IsVoid` marks a case that +[optional-field extensions](/docs/reference/traits/optional/) add `IsOptional`. A builder starts +with every field marked `IsNothing`, and each step changes one marker. `FinalizeBuild` is +implemented only when every marker is `IsPresent`. On the variant side, `IsVoid` marks a case that extraction has ruled out. ### Widening, narrowing, and handling variants {#an-enum-is-a-row-typed-sum-upcast-and-downcast-are-injection-and-branching} @@ -322,7 +322,7 @@ These pages develop the patterns and the neighbouring comparisons: ## Sources The PureScript snippet was compiled with PureScript 0.15.15 against the prelude and the OCaml -snippet with OCaml 5.5.0. The CGP snippets were compiled against `cgp` `0.8.0` . +snippet with OCaml 5.5.0. The CGP snippets were compiled against `cgp` `0.8.0`. - [Wikipedia, *Structural type system*](https://en.wikipedia.org/wiki/Structural_type_system), [*Nominal type system*](https://en.wikipedia.org/wiki/Nominal_type_system), and [*Row polymorphism*](https://en.wikipedia.org/wiki/Row_polymorphism): the definitions and their contrast. - [PureScript language reference, *Types*](https://github.com/purescript/documentation/blob/master/language/Types.md), [Pursuit, *Prim*](https://pursuit.purescript.org/builtins/docs/Prim), and [*Prim.Row*](https://pursuit.purescript.org/builtins/docs/Prim.Row): rows, records, open-row syntax, and the row type classes. diff --git a/docs/comparisons/rust-language-proposals.md b/docs/comparisons/rust-language-proposals.md index 6d51a45d..452a7f01 100644 --- a/docs/comparisons/rust-language-proposals.md +++ b/docs/comparisons/rust-language-proposals.md @@ -7,7 +7,7 @@ description: 'How CGP compares with Rust proposals for specialization, named imp # Rust's own proposals CGP offers explicit implementation selection and access to context values through a -[stable Rust library](/docs/) . It is a language extension with pluggable implementations behind +[stable Rust library](/docs/). It is a language extension with pluggable implementations behind ordinary Rust traits. This page compares those choices with specialization, named impls, dictionary passing, and contexts and capabilities, including what each language proposal can express beyond CGP. @@ -40,13 +40,13 @@ Reference](https://doc.rust-lang.org/reference/items/implementations.html); [RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html) ). These rules keep trait selection consistent across a program. For example, operations on a -`HashMap` must agree on the hashing and equality implementations for `K` . The +`HashMap` must agree on the hashing and equality implementations for `K`. The [type classes](./type-classes.md) page explains the broader reasons for coherence. ### Specialization RFC 1210 proposes letting two impls overlap when one is *strictly more specific*, with the compiler -choosing the more specific one. Its own example refines a blanket `AddAssign` : +choosing the more specific one. Its own example refines a blanket `AddAssign`: ```rust impl + Clone> AddAssign for T { @@ -62,7 +62,7 @@ The `default` keyword marks an item that a more specific impl may override ([RFC unstable, with soundness problems involving lifetime information that is erased before code generation. The standard library uses the more restricted `min_specialization` feature internally ([tracking issue #31844](https://github.com/rust-lang/rust/issues/31844)). On a stable toolchain the -snippet above fails with `E0658` . +snippet above fails with `E0658`. Specialization cannot choose between overlapping impls when neither is more specific. For example, `T: Display` and `T: AsRef<[u8]>` describe intersecting sets of types, but neither set contains the @@ -172,7 +172,7 @@ A CGP provider corresponds to an impl named with `impl Name = Trait for T` Each implementation has its own zero-sized type. Overlapping implementations of one trait can therefore coexist, because each implements the provider trait for its own type. The encoder pair from the [Introduction](/docs/) shows this. Rust rejects two blanket impls of one trait for -`T: Display` and `T: AsRef<[u8]>` , since `String` satisfies both. Written as providers, both +`T: Display` and `T: AsRef<[u8]>`, since `String` satisfies both. Written as providers, both compile: ```rust @@ -196,15 +196,15 @@ impl> Encoder { } ``` -`EncodeWithDisplay` and `EncodeBytes` play the role of named impls. Both accept `String` , and a +`EncodeWithDisplay` and `EncodeBytes` play the role of named impls. Both accept `String`, and a context selects one. A downstream crate can define another provider even if it owns neither the component nor the value type, because it implements the provider trait for its own marker type. Rust's coherence rules still apply to those generated impls. -The encoded value is the `Value` parameter rather than `Self` , so `Self` can stand for an +The encoded value is the `Value` parameter rather than `Self`, so `Self` can stand for an application. The contexts below are **[environmental contexts](/docs/reference/glossary#environmental-context)**, and the component is -[parameter-targeted](/docs/reference/glossary#parameter-targeted-component) . +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component). ### Selecting implementations on a context {#an-incoherent-bound-resolves-through-the-context-not-at-each-call-site} @@ -231,7 +231,7 @@ delegate_components! { } ``` -Every call through `ApiServer` uses its selected provider for `String` ; `Firmware` has its own +Every call through `ApiServer` uses its selected provider for `String`; `Firmware` has its own choice. This gives consistency per context, component, and dispatch key. Boxy's sketch permits explicit choices at calls, while Cairo can infer them from scope. The [type classes](./type-classes.md) page compares these choices with Haskell's instance resolution. @@ -239,8 +239,8 @@ explicit choices at calls, while Cairo can infer them from scope. The ### Passing providers as type parameters {#passing-an-impl-explicitly-is-a-higher-order-provider} Where the proposals and Cairo let a caller pass an impl as a parameter, CGP uses -[higher-order providers](/docs/concepts/higher-order-providers) . A provider takes another provider -as a type parameter and binds it with `#[use_provider]` , which corresponds to Cairo's +[higher-order providers](/docs/concepts/higher-order-providers). A provider takes another provider +as a type parameter and binds it with `#[use_provider]`, which corresponds to Cairo's `impl TDrop: Drop` written as a Rust generic: ```rust @@ -255,11 +255,11 @@ impl AreaCalculator { Wiring `AreaCalculatorComponent: ScaledArea` selects both the wrapper and its inner implementation. The example assumes an `AreaCalculator` component and a `RectangleArea` provider -that reads `width` and `height` . A `ScaledRectangle` context would supply those fields plus -`scale_factor` . It is a **value context** because the measured value carries the wiring. +that reads `width` and `height`. A `ScaledRectangle` context would supply those fields plus +`scale_factor`. It is a **value context** because the measured value carries the wiring. Higher-order providers let a wrapper fix or parameterize its inner choice. An inner parameter can -also default to [`UseContext`](/docs/reference/providers/use_context) , which delegates that step +also default to [`UseContext`](/docs/reference/providers/use_context), which delegates that step back to the context's selected implementation. ### A `with` clause becomes a context field @@ -267,7 +267,7 @@ back to the context's selected implementation. Mandry's `with arena: &BasicArena` clause declares a value the function needs from its environment. CGP expresses an environmental dependency as an [implicit argument](/docs/concepts/implicit-arguments) read from the context. This fragment assumes -a `Greeter` component whose method returns a `String` : +a `Greeter` component whose method returns a `String`: ```rust #[cgp_impl(new GreetHello)] @@ -379,7 +379,7 @@ These pages develop the constructs and the neighbouring comparisons: The Rust snippets from the proposals are quoted from their authors' posts and the Cairo book. The specialization snippet was compiled against a stable toolchain to confirm it is rejected with -`E0658` ; the CGP snippets were compiled against `cgp` `0.8.0` with a `check_components!` +`E0658`; the CGP snippets were compiled against `cgp` `0.8.0` with a `check_components!` assertion per wired context. - [Rust Reference, *Implementations*](https://doc.rust-lang.org/reference/items/implementations.html) and [RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html): the orphan and overlap rules. diff --git a/docs/comparisons/type-classes.md b/docs/comparisons/type-classes.md index 2116ac19..a6e13faa 100644 --- a/docs/comparisons/type-classes.md +++ b/docs/comparisons/type-classes.md @@ -7,7 +7,7 @@ description: 'How CGP provider selection compares with type classes, coherence, # Type classes CGP lets each context select named implementations at compile time. It is a language extension built -as a [stable Rust library](/docs/) , with ordinary Rust traits as its caller interfaces. This page +as a [stable Rust library](/docs/), with ordinary Rust traits as its caller interfaces. This page compares explicit wiring with type-class resolution in Haskell, Agda, and Lean, and explains when a single canonical implementation is the simpler choice. @@ -62,7 +62,7 @@ from enforcing uniqueness across every separately compiled part of a program ([Y confluence, coherence and global uniqueness*](https://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/)). -Rust enforces coherence through overlap and [orphan rules](/docs/reference/glossary#orphan-rule) . +Rust enforces coherence through overlap and [orphan rules](/docs/reference/glossary#orphan-rule). An impl needs a local trait or a qualifying local type, subject to restrictions on uncovered type parameters ([RFC 2451](https://rust-lang.github.io/rfcs/2451-re-rebalancing-coherence.html)). GHC permits orphan instances and can warn about them. CGP works within Rust's rules; the @@ -194,12 +194,12 @@ delegate_components! { Rectangle { AreaCalculatorComponent: RectangleArea } } ``` Separate provider types let alternative implementations coexist under Rust's coherence rules. The -wiring selects `RectangleArea` for `Rectangle` ; another provider could implement the same provider +wiring selects `RectangleArea` for `Rectangle`; another provider could implement the same provider trait on its own marker type. -This example still makes one choice for `Rectangle` . It is a -[value context](/docs/reference/glossary#value-context) : the measured type also carries the wiring, -and the component is [self-targeted](/docs/reference/glossary#self-targeted-component) . Independent +This example still makes one choice for `Rectangle`. It is a +[value context](/docs/reference/glossary#value-context): the measured type also carries the wiring, +and the component is [self-targeted](/docs/reference/glossary#self-targeted-component). Independent choices for the same value type require moving selection to separate contexts, as the next example does. @@ -241,10 +241,10 @@ These providers accept overlapping inputs: `String` supports display and byte ac distinguish those choices; constraints alone do not make one instance more specific. CGP keeps the choices separate through provider types and records the selection in wiring. -The encoded value is the `Value` parameter rather than `Self` , so the contexts that wire these +The encoded value is the `Value` parameter rather than `Self`, so the contexts that wire these providers are **[environmental contexts](/docs/reference/glossary#environmental-context)**, types that stand for an application. The component is -[parameter-targeted](/docs/reference/glossary#parameter-targeted-component) . +[parameter-targeted](/docs/reference/glossary#parameter-targeted-component). ### Selecting a provider per context and value type {#incoherent-choices-made-explicit-and-local} @@ -274,14 +274,14 @@ delegate_components! { `AppA` encodes `Vec` as hexadecimal, while `AppB` returns its bytes directly. Each choice is fixed for the context, component, and value type. This makes the difference explicit without relaxing Rust's coherence rules. The `open` statement and `@` paths are explained in -[`delegate_components!`](/docs/reference/macros/delegate_components) . +[`delegate_components!`](/docs/reference/macros/delegate_components). ### Providers avoid orphan conflicts and newtypes A downstream crate can define a provider for a foreign component and value type by owning the provider's marker type. This satisfies the orphan rule without wrapping the value in a newtype. Alternative behaviors get their own provider types, rather than wrappers such as Haskell's `Sum` and -`Product` . The [Bypassing coherence](/docs/concepts/coherence) page develops this pattern. +`Product`. The [Bypassing coherence](/docs/concepts/coherence) page develops this pattern. ## What each approach costs @@ -314,7 +314,7 @@ approaches. ## Where coherent type classes are the better choice Coherent type classes fit programs that need one canonical instance per type, such as the `Ord` used -by a `Set` . The compiler keeps generic code consistent without wiring. In Rust, an ordinary trait +by a `Set`. The compiler keeps generic code consistent without wiring. In Rust, an ordinary trait already provides that guarantee. The [Modularity Hierarchy](/docs/concepts/modularity-hierarchy) page starts from this simpler case. From ba126204885ff6815b4008e0a77a4f66894b3290 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sun, 8 Nov 2026 22:50:51 +0100 Subject: [PATCH 294/516] Name the project on the reflection comparison The page opened with the abbreviation and described the project without its name. Its opening now names Context-Generic Programming, links the Introduction, and relates the short form to the reflection comparison, and its description names the project for search. The cgp-serde source links now point at the v0.8.0 branch the page describes, and the project goal link follows its moved URL. Punctuation now sits against the code spans and links it follows. --- docs/comparisons/reflection.md | 56 +++++++++++++++++----------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/docs/comparisons/reflection.md b/docs/comparisons/reflection.md index 90e678f9..ce5e11f2 100644 --- a/docs/comparisons/reflection.md +++ b/docs/comparisons/reflection.md @@ -1,16 +1,16 @@ --- sidebar_label: 'Reflection' sidebar_position: 10 -description: "How CGP compares with runtime reflection, Zig comptime, and Rust compile-time reflection." +description: "Compare Context-Generic Programming type-level shapes with runtime reflection, Zig comptime, and Rust compile-time reflection." --- # Reflection and compile-time introspection -CGP represents a struct's fields as types, letting generic code read them and select behavior at -compile time. It is a language extension built as a [stable Rust library](/docs/) , with pluggable -implementations behind ordinary Rust traits. This page compares that approach with Bevy's runtime -reflection, Zig's `comptime` , and Rust's experimental reflection API through a generic field -writer. +[Context-Generic Programming](/docs/) represents a struct's fields as types, letting generic code +read them and select behavior at compile time. CGP extends Rust with pluggable trait implementations, +chosen per context and resolved at compile time, as a library on stable Rust whose consumer traits +are ordinary Rust traits. This page compares that approach with Bevy's runtime reflection, Zig's +`comptime`, and Rust's experimental reflection API through a generic field writer. ## In your terms @@ -48,7 +48,7 @@ CGP also processes shapes at compile time. Its shape is a type, rather than a co ### Runtime reflection: Bevy Bevy lets code inspect values through a common runtime interface. A type opts in with -`#[derive(Reflect)]` ; code can then access its fields by name or downcast it to a concrete type +`#[derive(Reflect)]`; code can then access its fields by name or downcast it to a concrete type ([`bevy_reflect` documentation](https://docs.rs/bevy_reflect/latest/bevy_reflect/)). `TypeInfo` describes the shape, and a [`TypeRegistry`](https://docs.rs/bevy/latest/bevy/reflect/struct.TypeRegistry.html) associates types @@ -79,7 +79,7 @@ fn jsonStringify(value: anytype, writer: anytype) !void { Zig resolves the loop and field accesses at compile time, without runtime lookup. A generic `comptime` routine is checked for each concrete instantiation, so type-dependent errors appear when it is used. Zig can also construct a new nominal type from a `std.builtin.Type` value through -`@Type` ; CGP does not offer that operation. +`@Type`; CGP does not offer that operation. ### Compile-time reflection comes to Rust @@ -89,8 +89,8 @@ generate serialization implementations that are specialized for each type and se `const SHAPE` descriptor that shared runtime code can inspect, aiming to reduce that duplication. Rust's experimental `type_info` feature supplies metadata directly from the compiler. Under -`#![feature(type_info)]` , `TypeId::of::()` gains query methods that reach a type's variants and -fields in source order. Each `FieldId` answers `name()` , `type_id()` , and `offset()` . The +`#![feature(type_info)]`, `TypeId::of::()` gains query methods that reach a type's variants and +fields in source order. Each `FieldId` answers `name()`, `type_id()`, and `offset()`. The source's own doc tests read: ```rust @@ -106,7 +106,7 @@ assert_eq!(const { TypeId::of::().field(0, 0).type_id() }, TypeId::of::

` in `check_components!`. +[`check_components!`](/docs/reference/macros/check_components) describes the syntax. + ### CGP-E061 Two [`#[cgp_auto_dispatch]`](/docs/reference/macros/cgp_auto_dispatch) traits in one module declare a method of the same -name, and the macro names its generated items after the method alone. To fix it, rename the method in one trait, or -declare the traits in different modules. +name, and the macro names its generated items after the method alone. ```text [CGP-E061] two `#[cgp_auto_dispatch]` traits in one module declare the method `` ``` +To fix it, rename the method in one trait, or +declare the traits in different modules. + ## Wiring that never resolves, and the orphan rule The next three codes cover wiring that is well formed but cannot work, either because looking it up never ends or because @@ -267,14 +289,16 @@ Rust's coherence rules forbid it. ### CGP-E020 Looking up the wiring for a component leads back to itself. The plain case is a component wired to `UseContext` on a -context with no other implementation of it. The compiler's code is `E0275`. To fix it, wire a real provider, or implement -the consumer trait directly on the context. The `help` line names the provider that closes the loop. -[A lookup that never terminates](/docs/reference/errors#a-lookup-that-never-terminates) explains the class. +context with no other implementation of it. The compiler's code is `E0275`. ```text [CGP-E020] the wiring for the consumer trait `` on context `` never resolves, because the lookup leads back to itself ``` +To fix it, wire a real provider, or implement +the consumer trait directly on the context. The `help` line names the provider that closes the loop. +[A lookup that never terminates](/docs/reference/errors#a-lookup-that-never-terminates) explains the class. + ### CGP-E021 Each step of the lookup requires the consumer trait again for a larger type, so nothing repeats, and the compiler stops @@ -288,16 +312,18 @@ at its recursion limit. No limit ends a lookup that grows, so to fix it, wire a ### CGP-E022 A crate registers wiring into a namespace it does not own, under a key it does not own either, which Rust's orphan rule -forbids. The compiler's code is `E0210` or `E0117`. To fix it, own one end, as the `help` line says: key the registration -on a component your crate defines, register it from the crate that owns the namespace, or define a namespace of your own -that inherits the foreign one. -[Registering into a namespace you do not own](/docs/reference/errors#registering-into-a-namespace-you-do-not-own) -explains the class. +forbids. The compiler's code is `E0210` or `E0117`. ```text [CGP-E022] cannot register the foreign into the foreign namespace `` ``` +To fix it, own one end, as the `help` line says: key the registration +on a component your crate defines, register it from the crate that owns the namespace, or define a namespace of your own +that inherits the foreign one. +[Registering into a namespace you do not own](/docs/reference/errors#registering-into-a-namespace-you-do-not-own) +explains the class. + ## Mistakes in what a macro was given These codes name a CGP attribute or macro used in a way the generated code cannot compile. Most of them give the fix in a @@ -307,109 +333,129 @@ These codes name a CGP attribute or macro used in a way the generated code canno A `#[cgp_fn]` or `#[cgp_impl]` body calls a CGP trait's method on `self` or `Self` without declaring the trait as a dependency. The macro turns the body into an implementation over a generated context type, so a trait the body uses has to -be declared for that type to have it. The compiler's code is `E0599`. To fix it, add the trait to `#[uses(...)]`, as the -`help` line says. -[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. +be declared for that type to have it. The compiler's code is `E0599`. ```text [CGP-E030] the trait `` is used but not declared as a dependency ``` +To fix it, add the trait to `#[uses(...)]`, as the +`help` line says. +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. + ### CGP-E031 A higher-order provider calls an inner provider it never imported, so the inner provider has no provider-trait bound and -the call cannot resolve. To fix it, import it with `#[use_provider(: )]`, as the `help` line says. -[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. +the call cannot resolve. ```text [CGP-E031] the inner provider `` is used but not imported ``` +To fix it, import it with `#[use_provider(: )]`, as the `help` line says. +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. + ### CGP-E032 A `#[cgp_impl]` header names the component's consumer trait where its provider trait belongs. Without the rewrite, this one -mistake produces a burst of unrelated-looking errors. To fix it, name the provider trait in the header, as the `help` line -says. [Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the -class. +mistake produces a burst of unrelated-looking errors. ```text [CGP-E032] `` is a consumer trait, but a `#[cgp_impl]` provider must implement its provider trait `` ``` +To fix it, name the provider trait in the header, as the `help` line +says. [Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the +class. + ### CGP-E033 -`#[cgp_impl]` is applied to a trait that is not a CGP component at all, so there is no provider trait to implement. To fix -it, make the trait a component with [`#[cgp_component]`](/docs/reference/macros/cgp_component) and implement its provider -trait, or drop `#[cgp_impl]` and write an ordinary `impl`. -[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the class. +`#[cgp_impl]` is applied to a trait that is not a CGP component at all, so there is no provider trait to implement. ```text [CGP-E033] `#[cgp_impl]` can only implement a CGP component's provider trait, but `` is not a CGP component ``` +To fix it, make the trait a component with [`#[cgp_component]`](/docs/reference/macros/cgp_component) and +implement its provider trait, or drop `#[cgp_impl]` and write an ordinary `impl`. +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains +the class. + ### CGP-E034 An inner-provider bound names a consumer trait where the provider trait belongs, most often in -[`#[use_provider]`](/docs/reference/attributes/use_provider). To fix it, name the provider trait, as the `help` line says. -[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the class. +[`#[use_provider]`](/docs/reference/attributes/use_provider). ```text [CGP-E034] `` is a consumer trait and cannot bound an inner provider; a higher-order provider imports its provider trait `` ``` +To fix it, name the provider trait, as the `help` line says. +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the class. + ### CGP-E035 A `#[cgp_fn]`, `#[cgp_impl]`, or `#[cgp_component]` definition names an abstract type of the context, as `Self::Error` or a -bare `Error`, without [`#[use_type]`](/docs/reference/attributes/use_type). To fix it, import the type with -`#[use_type(.)]`, as the `help` line says, and write it bare. -[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. +bare `Error`, without [`#[use_type]`](/docs/reference/attributes/use_type). ```text [CGP-E035] the abstract type `` is used but not imported ``` +To fix it, import the type with +`#[use_type(.)]`, as the `help` line says, and write it bare. +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. + ### CGP-E036 A component requires a trait of every context, through [`#[extend(...)]`](/docs/reference/attributes/extend) or -`#[use_type(...)]`, and a `#[cgp_impl]` provider does not declare it, even if its body never uses the trait. To fix it, add -the `#[uses(...)]` or `#[use_type(...)]` the `help` line names. -[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. +`#[use_type(...)]`, and a `#[cgp_impl]` provider does not declare it, even if its body never uses the trait. ```text [CGP-E036] the provider trait `` requires `` of the context, but the provider `` does not declare it ``` +To fix it, add +the `#[uses(...)]` or `#[use_type(...)]` the `help` line names. +[Using something you did not declare](/docs/reference/errors#using-something-you-did-not-declare) explains the class. + ### CGP-E037 -[`#[uses]`](/docs/reference/attributes/uses) names a provider trait, but a dependency names its consumer trait. To fix it, -name the consumer trait, as the `help` line says. -[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the class. +[`#[uses]`](/docs/reference/attributes/uses) names a provider trait, but a dependency names its consumer trait. ```text [CGP-E037] `` is a provider trait and cannot be a `#[uses]` dependency; a dependency names its consumer trait `` ``` +To fix it, +name the consumer trait, as the `help` line says. +[Naming the wrong half of a component](/docs/reference/errors#naming-the-wrong-half-of-a-component) explains the class. + ### CGP-E038 -`#[cgp_impl(GreetHello)]` without `new` implements the provider trait for a struct nothing declares. To fix it, write -`#[cgp_impl(new GreetHello)]` so the macro declares it, or declare the struct yourself. A provider declared elsewhere but not -imported keeps the compiler's `E0425` and its import suggestion instead. -[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) describes the syntax. +`#[cgp_impl(GreetHello)]` without `new` implements the provider trait for a struct nothing declares. ```text [CGP-E038] the provider `` is not declared ``` +To fix it, write +`#[cgp_impl(new GreetHello)]` so the macro declares it, or declare the struct yourself. A provider declared elsewhere but not +imported keeps the compiler's `E0425` and its import suggestion instead. +[`#[cgp_impl]`](/docs/reference/macros/cgp_impl) describes the syntax. + ### CGP-E039 A plain `impl` implements a provider trait. The trait has `IsProviderFor` as a supertrait, and only `#[cgp_provider]` or -`#[cgp_impl]` writes the provider's impl of it. To fix it, add one of those macros, as the `help` line says. -[`#[cgp_provider]`](/docs/reference/macros/cgp_provider) describes the macro. +`#[cgp_impl]` writes the provider's impl of it. ```text [CGP-E039] the impl of `` for `` is written without `#[cgp_provider]` ``` +To fix it, add one of those macros, as the `help` line says. +[`#[cgp_provider]`](/docs/reference/macros/cgp_provider) describes the macro. + ## Wiring keys and values that do not resolve These codes replace a name-resolution error on a wiring entry, for a name the tool can settle. Each applies only when no @@ -418,41 +464,49 @@ type of that name exists in your crate or its dependencies, or when the tool can ### CGP-E040 -A wiring key names a consumer trait such as `CanGreet`, where its component marker `GreeterComponent` belongs. To fix it, name -the component, as the `help` line says. +A wiring key names a consumer trait such as `CanGreet`, where its component marker `GreeterComponent` belongs. ```text [CGP-E040] the wiring key `` is a consumer trait, but a key names a component ``` +To fix it, name +the component, as the `help` line says. + ### CGP-E041 A key names a component that exists but is not imported where the table is written, such as `ErrorTypeProviderComponent`, -which the prelude does not export. To fix it, add the `use` line the `help` line gives. +which the prelude does not export. ```text [CGP-E041] the component `` is not in scope ``` +To fix it, add the `use` line the `help` line gives. + ### CGP-E042 A key was guessed from a consumer trait's name with `Component` appended, such as `HasScalarTypeComponent`, while the marker -follows the provider trait, as in `ScalarTypeProviderComponent`. To fix it, name the component the `help` line gives. +follows the provider trait, as in `ScalarTypeProviderComponent`. ```text [CGP-E042] the wiring key `` names no component ``` +To fix it, name the component the `help` line gives. + ### CGP-E043 -A wiring value names a provider struct nothing declares, often a misspelling. To fix it, declare the provider or name one that -exists. A `help` line appears when the component has a provider with a similar name. A provider declared elsewhere but not -imported keeps the compiler's `E0425` and its import suggestion instead. +A wiring value names a provider struct nothing declares, often a misspelling. ```text [CGP-E043] the provider `` wired for `` is not declared ``` +To fix it, declare the provider or name one that +exists. A `help` line appears when the component has a provider with a similar name. A provider declared elsewhere but not +imported keeps the compiler's `E0425` and its import suggestion instead. + ### CGP-E044 An `@`-path in a key, or in the value of a `=>` redirect, names a type nothing declares. A path segment that is not a lowercase @@ -524,27 +578,34 @@ This line is a step through any other trait, such as a getter or a blanket trait ## Where the chain ends These codes end the chain, and the cause they state is the one to fix. The `root cause:` line repeats the same code. +The codes from `[CGP-E118]` to `[CGP-E126]` belong to extensible data, which +[extensible records](/docs/concepts/extensible-records) and [extensible variants](/docs/concepts/extensible-variants) +explain. ### CGP-E110 -The chain ends at a field the context does not have. To fix it, add the field, or wire a provider that does not read it. A `help` -line names a similar field when there is one, and otherwise the field to add. -[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met) explains the class. +The chain ends at a field the context does not have. ```text [CGP-E110] missing field `` on `` ``` +To fix it, add the field, or wire a provider that does not read it. A `help` +line names a similar field when there is one, and otherwise the field to add. +[A dependency is not met](/docs/reference/errors#a-dependency-is-not-met) explains the class. + ### CGP-E111 -The chain ends at a field that exists but has no `HasField` impl, because the struct does not derive it. To fix it, add -`#[derive(HasField)]` to the struct, as the `help` line says. -[When the derive is missing entirely](/docs/reference/errors#when-the-derive-is-missing-entirely) explains the class. +The chain ends at a field that exists but has no `HasField` impl, because the struct does not derive it. ```text [CGP-E111] `HasField` not derived for field `` of `` ``` +To fix it, add +`#[derive(HasField)]` to the struct, as the `help` line says. +[When the derive is missing entirely](/docs/reference/errors#when-the-derive-is-missing-entirely) explains the class. + ### CGP-E112 The chain ends at a field with the wrong type. This is the last line of a `[CGP-E004]` error, with the same wording. @@ -555,34 +616,39 @@ The chain ends at a field with the wrong type. This is the last line of a `[CGP- ### CGP-E113 -The chain ends at a component or path the context wires nothing for. To fix it, add the wiring entry the `help` line names. -[Nothing is wired there](/docs/reference/errors#nothing-is-wired-there) explains the class. +The chain ends at a component or path the context wires nothing for. ```text [CGP-E113] missing wiring for `` on `` ``` +To fix it, add the wiring entry the `help` line names. +[Nothing is wired there](/docs/reference/errors#nothing-is-wired-there) explains the class. + ### CGP-E114 The chain ends at a provider's own table that has no entry for a key: a bundle of wiring missing a component, or a provider that -dispatches per type missing the type it was given. To fix it, add the entry to that provider's table, or pass it a type the table -covers. +dispatches per type missing the type it was given. ```text [CGP-E114] missing entry for `` in provider `` ``` +To fix it, add the entry to that provider's table, or pass it a type the table +covers. + ### CGP-E115 -The chain ends at a type wired where a provider belongs that is not a provider, such as a value type put in a provider's place. To -fix it, wire an actual provider in that position. A `help` line suggests one when the program supports it: an adapter such as -`WithProvider`, `UseFields` in place of `UseField` on a multi-method getter, an `open` statement in place of `UseDelegate`, or the -right component for a provider of another one. +The chain ends at a type wired where a provider belongs that is not a provider, such as a value type put in a provider's place. ```text [CGP-E115] `` is not a provider of `` ``` +To fix it, wire an actual provider in that position. A `help` line suggests one when the program supports it: +an adapter such as `WithProvider`, `UseFields` in place of `UseField` on a multi-method getter, an `open` +statement in place of `UseDelegate`, or the right component for a provider of another one. + ### CGP-E116 The chain ends at an associated type that differs from what was required. This is the last line of a `[CGP-E005]` error, with the @@ -595,118 +661,143 @@ same wording. ### CGP-E117 The chain ends at an ordinary Rust trait bound that does not hold, such as `f64: Eq`, in the compiler's own wording. At a -`check_components!` entry the tool keeps the compiler's headline, which already names the bound. To fix it, use a type that implements -the trait, or a provider that does not require it. -[When the missing bound is an ordinary Rust trait](/docs/reference/errors#when-the-missing-bound-is-an-ordinary-rust-trait) explains the -class. +`check_components!` entry the tool keeps the compiler's headline, which already names the bound. ```text [CGP-E117] the trait bound `` is not satisfied ``` +To fix it, use a type that implements +the trait, or a provider that does not require it. +[When the missing bound is an ordinary Rust trait](/docs/reference/errors#when-the-missing-bound-is-an-ordinary-rust-trait) explains the +class. + ### CGP-E118 -A builder operation needs a field unset, as a second `build_field` or a second merge source does, and the field is already set. To fix -it, drop the second setting. +A builder operation needs a field unset, as a second `build_field` or a second merge source does, and the field is already set. ```text [CGP-E118] field `` of `` is already set ``` +To fix it, drop the second setting. + ### CGP-E119 -An operation such as a finalize or `take_field` needs one or more fields set, and they are not. To fix it, set them first. +An operation such as a finalize or `take_field` needs one or more fields set, and they are not. ```text [CGP-E119] field `` of `` is not set ``` +To fix it, set them first. + ### CGP-E120 -A cast between enums has variants that do not match, or a construction uses a tag the enum lacks. To fix it, add the variant or correct -the name. A `help` line names a similar variant when there is one. +A cast between enums has variants that do not match, or a construction uses a tag the enum lacks. ```text [CGP-E120] missing variant `` on `` ``` +To fix it, add the variant or correct +the name. A `help` line names a similar variant when there is one. + ### CGP-E121 -An extractor is finalized while it may still yield a variant, as a matcher that leaves one out does. To fix it, handle the variant. +An extractor is finalized while it may still yield a variant, as a matcher that leaves one out does. ```text [CGP-E121] variant `` of `` is not extracted ``` +To fix it, handle the variant. + ### CGP-E122 -A cast between enums has same-named variants that carry different payloads. To fix it, align the payload types. +A cast between enums has same-named variants that carry different payloads. ```text [CGP-E122] variant `` on `` has type ``, but `` is required ``` +To fix it, align the payload types. + ### CGP-E123 -A trait only a data derive implements is required of a type that does not have it. To fix it, add the derive the `help` line names. +A trait only a data derive implements is required of a type that does not have it. ```text [CGP-E123] `` does not implement `` ``` +To fix it, add the derive the `help` line names. + ### CGP-E124 A variant is extracted a second time from an extractor that no longer holds it. The compiler reports this as an `E0308` on the tag -argument. To fix it, drop the second extraction. +argument. ```text [CGP-E124] variant `` of `` is already extracted ``` +To fix it, drop the second extraction. + ### CGP-E125 -An optional builder's operation is called on a field a core builder holds set or unset. To fix it, call `to_optional` on the builder -first, as the `help` line says. +An optional builder's operation is called on a field a core builder holds set or unset. ```text [CGP-E125] field `` of `` is not optional ``` +To fix it, call `to_optional` on the builder +first, as the `help` line says. + ### CGP-E126 A builder or extractor is given to an operation that needs a trait only its struct or enum implements, as `downcast` on the remainder -of a downcast is. To fix it, call the method the `help` line names, such as `downcast_fields`. +of a downcast is. ```text [CGP-E126] an extractor of `` does not implement `` ``` +To fix it, call the method the `help` line names, such as `downcast_fields`. + ### CGP-E127 A provider's impls differ from the wiring in exactly one argument: the context, or a component parameter, as for a pipeline stage that -takes `u64` after one that returns `String`. To fix it, wire a provider for those arguments, or change the type that disagrees. +takes `u64` after one that returns `String`. ```text [CGP-E127] `` implements `` only for ``, not `` ``` +To fix it, wire a provider for those arguments, or change the type that disagrees. + ### CGP-E128 A hand-written `DelegateComponent` impl lacks the `IsProviderFor` impl `delegate_components!` writes beside each entry, so a check passes -but every consumer call fails. To fix it, replace the impl with `delegate_components!`, as the `help` line says. +but every consumer call fails. ```text [CGP-E128] the wiring of `` on `` has no `IsProviderFor` impl ``` +To fix it, replace the impl with `delegate_components!`, as the `help` line says. + ### CGP-E129 -A consumer method is called on a value of a type parameter without the bound. To fix it, add the bound the `help` line names. +A consumer method is called on a value of a type parameter without the bound. ```text [CGP-E129] the type parameter `` of `` is not bounded by `` ``` +To fix it, add the bound the `help` line names. + ## Rewrites without a code Some changes make an error easier to read without classifying it, so they carry no code. You may see them in an error whose headline the diff --git a/docs/index.md b/docs/index.md index db991214..42921bb9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -33,8 +33,8 @@ mission-critical project, expect to investigate problems yourself when the avail and support do not cover your case. [cargo-cgp](/docs/cargo-cgp) helps diagnose wiring errors by naming their root cause and showing the -dependency chain. The tool is an early release and rewrites the error classes it recognizes; -other diagnostics retain the compiler's wording. CGP also publishes an +dependency chain. The tool is an early release: `cargo cgp check` leads with the root cause for the classes it recognizes, +and the tool does not yet reshape every class. CGP also publishes an [agent skill](/docs/ai/skills) to help coding assistants read, write, and debug CGP code. You still need to review the code an assistant produces. diff --git a/docs/overview.md b/docs/overview.md index d2ffbc18..bd2f6a86 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -44,7 +44,8 @@ does not force that verification, so use These checks establish that components fit together; they do not prove application logic correct. [cargo-cgp](/docs/cargo-cgp) helps explain wiring failures by showing the root cause and dependency -chain. It is an early release and does not rewrite every kind of compiler error. +chain. It is an early release: `cargo cgp check` leads with the root cause for the classes it +recognizes, and the tool does not yet reshape every class. ### Abstract Over Every Dependency diff --git a/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md b/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md index e8c21768..925eaaa0 100644 --- a/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md +++ b/docs/projects/cgp-examples/expression/architecture/dispatch-layers.md @@ -75,12 +75,13 @@ it for each operand, which is the same question, and it never finishes. With the the wiring never resolves: ```text -error[E0275]: [CGP-E020] the wiring for the consumer trait `CanCompute` on context `Interpreter` never resolves, because the lookup leads back to itself +error[E0275]: [CGP-E020] the wiring for the consumer trait `CanCompute` on context `contexts::add_mult::Interpreter` never resolves, because the lookup leads back to itself ``` The same error follows for `Plus` and `Times`, and two raw overflow errors for the dispatcher -itself. Its help line suggests a component wired back to the context itself, the usual cause of the -class; here the loop runs through the operands instead. +itself. The project names a `MathExpr` and an `Interpreter` in several modules, so the output keeps their +module paths. The help lines name `EvalAdd`, whose requirement closes the loop where the tool's walk met it, +rather than the `MathExpr` entry that needs the wrapper. The wrapper breaks the loop, and the likeliest reason is the shape of its impl: it is written for one concrete context, with a concrete output type and no conditions. The compiler can then accept diff --git a/docs/reference/derives/derive_has_fields.md b/docs/reference/derives/derive_has_fields.md index 9197f0f3..5bc451e6 100644 --- a/docs/reference/derives/derive_has_fields.md +++ b/docs/reference/derives/derive_has_fields.md @@ -286,8 +286,8 @@ adding a second field changes the shape rather than lengthening it. **Named-field and newtype variants have different representations.** `Circle { radius: f64 }` uses a one-entry product, while `Circle(Circle)` uses its payload type directly. -**Only `HasFields` accepts every variant shape in this family.** Unit, multi-field, and struct-style -variants are rejected by `CgpData`, `CgpVariant`, `ExtractField`, and `FromVariant`. Wrap richer +**Only `HasFields` accepts every variant shape in this family.** Multi-field and struct-style variants +with fields are rejected by `CgpData`, `CgpVariant`, `ExtractField`, and `FromVariant`. Wrap richer payloads in dedicated structs to use those derives. **The borrowed shape adds a reference to each field's declared type.** A field of type `&'a Name` diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 6a994fd0..f140ca2d 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -640,6 +640,10 @@ error[E0599]: [CGP-E031] the inner provider `InnerCalculator` is used but not im In both cases rustc's own suggestion is worse than useless: it leaks the generated `__Context__` parameter, and for the second it proposes the *consumer* trait, which is the wrong fix. +Two neighbours share the cause. `[CGP-E035]` is an abstract type of the context named without +[`#[use_type]`](./attributes/use_type.md), and `[CGP-E036]` is a requirement of the component, added through +`#[extend]` or `#[use_type]`, that a provider does not declare. Each `help` names the attribute to add. + ### Naming the wrong half of a component A component has two traits, and a provider implements the *provider* one. Writing the consumer trait diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index 219bd35b..e1808bbe 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -399,8 +399,7 @@ note: candidate #2 is defined in an impl of the trait `CanRateLimit` for the typ ``` Name the provider trait to disambiguate: `>::LIMIT` works here -because `Self` is the provider. The `#[cgp_impl]` form needs -`>::LIMIT` instead, since there `Self` is the context. Either way +because `Self` is the provider. Either way the consumer side is unaffected: a wired context reads `::LIMIT`. ## Related constructs diff --git a/docs/reference/macros/delegate_and_check_components.md b/docs/reference/macros/delegate_and_check_components.md index e65d48e4..786948c0 100644 --- a/docs/reference/macros/delegate_and_check_components.md +++ b/docs/reference/macros/delegate_and_check_components.md @@ -402,7 +402,8 @@ error[E0277]: the trait bound `RectangleArea: IsProviderFor`, `some_mod::Marker`, `&'static str`) | that type | So lowercase segments read as namespace and prefix names, capitalized ones as component keys or marker types, @@ -193,7 +193,7 @@ PathSegment -> Type The leading `` `@` `` is required and at least one segment must follow. Each `PathSegment` is parsed as a Rust `Type`, but its encoding is decided semantically: a single identifier starting with a -lowercase ASCII letter that is not primitive-shaped becomes a `Symbol` type-level string, while +lowercase ASCII letter that is not a primitive's name becomes a `Symbol` type-level string, while every other segment (a capitalized name, a primitive, or any type with a path, generic arguments, or other structure) is kept as the type. [`cgp_namespace!`](./cgp_namespace.md) entries and `#[prefix(...)]` attributes embed this same grammar, where it appears as the `Path` production. diff --git a/docs/reference/providers/use_context.md b/docs/reference/providers/use_context.md index cb3dc439..2865a045 100644 --- a/docs/reference/providers/use_context.md +++ b/docs/reference/providers/use_context.md @@ -194,6 +194,9 @@ would be implemented by delegating to `UseContext`, whose `Encoder` impl in error[E0275]: overflow evaluating the requirement `App: IsProviderFor` ``` +[`cargo cgp check`](/docs/cargo-cgp/error-codes#cgp-e020) reports the same mistake as `[CGP-E020]`, at a check +or at a method call, and names the provider that closes the loop. + `UseContext` belongs where the provider trait resolves to a *different* implementation, such as a wrapper over another trait or a per-type dispatch entry for a different type. The `EncodeVec` example above is safe for exactly that reason: it is wired for `Vec`, but its inner diff --git a/docs/tutorials/area-calculation/checking.md b/docs/tutorials/area-calculation/checking.md index bffca1bd..8b34512c 100644 --- a/docs/tutorials/area-calculation/checking.md +++ b/docs/tutorials/area-calculation/checking.md @@ -164,7 +164,8 @@ error[E0277]: [CGP-E001] missing fields `width` and `height` on `PlainCircle` This is the same failure a third time, and now it leads with the answer: `PlainCircle` is missing the fields `width` and `height`. The tree beneath shows how the requirement arrived — through -`RectangleAreaCalculator`, which is the provider we wired by mistake. +`RectangleAreaCalculator`, which is the provider we wired by mistake. The `help` line offers to add the +fields, which would compile, but a circle has no width or height, so here the tree points at the better fix. One thing to keep in mind as you use it: `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. When you meet an @@ -173,7 +174,7 @@ section is worth understanding rather than skipping. ## Fixing it -The error named the provider, so the fix is the line the error pointed at: +The tree named the provider, so the fix is the line the error pointed at: ```rust delegate_components! { From d5fd5ebc080a2d81c16d907e461792d3c3f49974 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 2 Nov 2026 00:35:56 +0100 Subject: [PATCH 192/516] Bring the release post's install steps and quotes up to date The install command takes `--locked`, and the post states the tool's minimum Rust and tested platform beside it. The contents link names the section's current heading, the raw diagnostic is the one stable Rust prints now, and the post lists the restrictions the release lifts. Co-Authored-By: Claude Opus 5.5 --- blog/2026-05-10-v0.8.0-release.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/blog/2026-05-10-v0.8.0-release.md b/blog/2026-05-10-v0.8.0-release.md index a820df01..5265d229 100644 --- a/blog/2026-05-10-v0.8.0-release.md +++ b/blog/2026-05-10-v0.8.0-release.md @@ -16,7 +16,7 @@ Context-Generic Programming (CGP) is a language extension for Rust, with pluggab I'll start with cargo-cgp and the new documentation, then work through namespaces using a social-media application. The namespace walkthrough is the longest part, so you can read the tooling and documentation news on their own if you prefer. Allow about 35 minutes for the full post, including the code, or jump to the section you need: - [Diagnosing wiring with cargo-cgp](#diagnosing-wiring-with-cargo-cgp) -- [Expanded documentation and optional agent support](#expanded-documentation-and-optional-agent-support) +- [Expanded documentation and AI agent support](#expanded-documentation-and-ai-agent-support) - [Grouping component wiring with namespaces](#grouping-component-wiring-with-namespaces) - [Sharing default implementations](#default-implementations) - [Other improvements](#other-improvements) @@ -93,8 +93,8 @@ error[E0277]: the trait bound `Rectangle: CanUseComponent>>>>>>>` is not implemented for `Rectangle` - but trait `HasField>>>>>>` is implemented for it +help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` + but trait `HasField>>>>>>` is implemented for it --> src/lib.rs:17:9 | 17 | pub width: f64, @@ -135,10 +135,10 @@ To produce this explanation, cargo-cgp wraps a nightly compiler and uses the Rus ### Try the checker -With cargo and rustup available, you can install the tool and set up its compiler-linked driver, then check your own project: +With cargo and rustup available, you can install the tool and set up its compiler-linked driver, then check your own project. The install needs Rust 1.96 or newer, and the tool is tested on Linux only so far: ```sh -cargo install cargo-cgp +cargo install --locked cargo-cgp cargo cgp setup # Run this from your CGP project's directory: cargo cgp check @@ -870,6 +870,8 @@ Namespaces are the largest change, but several smaller additions also reduce the There are also fixes for code that previously ran into the limits of the handler macros. Their generated code is now self-contained, so using them does not rely on a prelude import at the call site. `#[cgp_auto_dispatch]` has fixes for lifetime handling and supertrait support, while `#[cgp_computer]` and `#[cgp_producer]` give clearer rejection messages for unsupported function signatures. +A few restrictions are also gone. The variant derives no longer reserve any names, so an enum can have a variant called `Value` or `Fields`. A derive's helper attribute, such as `#[serde(rename = "...")]`, no longer breaks a type that also derives `BuildField` or `ExtractField`. An `async fn` with a default body now works under `#[async_trait]`, and inside a `#[cgp_impl]` block, `Self::LIMIT` reads a const the block declares. + ## Breaking changes and migration Existing applications need source changes when moving from v0.7.0. The largest change is the removal of presets, which namespaces replace. From 59c55ffbc27a4fd978def5cb80abbb12f9503998 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Mon, 2 Nov 2026 00:36:23 +0100 Subject: [PATCH 193/516] Pin the behaviors that replaced the rejected snippets A provider's `Self::CONST`, an async default body, a primitive-like path segment, a variant named like a generated associated type, and a helper attribute of another derive now have positive tests. Fixture comments state the errors the fixtures print. Co-Authored-By: Claude Opus 5.5 --- example-code/tests/cargo_cgp/mod.rs | 2 +- .../tests/cargo_cgp/reading_output.rs | 2 +- .../reference/errors_the_fix_1.rs | 5 ++-- .../reference/errors_the_fix_1.stderr | 16 ++++++------ ...uto_getter_common_mistakes_option_slice.rs | 2 +- ...omponent_common_mistakes_misplaced_uses.rs | 2 +- ...onent_common_mistakes_unnamed_parameter.rs | 4 +-- ...mon_mistakes_output_only_type_parameter.rs | 2 +- ...mespace_common_mistakes_self_inheriting.rs | 3 +-- ...ace_common_mistakes_self_inheriting.stderr | 4 +-- .../reference/derives/derive_build_field.rs | 13 ++++++++++ .../reference/derives/derive_cgp_variant.rs | 26 +++++++++++++++++++ .../reference/derives/derive_has_fields.rs | 2 +- .../tests/reference/macros/async_trait.rs | 25 ++++++++++++++++++ .../tests/reference/macros/cgp_impl.rs | 4 +-- example-code/tests/reference/macros/path.rs | 13 ++++++++++ 16 files changed, 100 insertions(+), 25 deletions(-) diff --git a/example-code/tests/cargo_cgp/mod.rs b/example-code/tests/cargo_cgp/mod.rs index 1f4d4c23..f558671c 100644 --- a/example-code/tests/cargo_cgp/mod.rs +++ b/example-code/tests/cargo_cgp/mod.rs @@ -7,7 +7,7 @@ //! `cargo cgp check` prints for it. Those programs are `trybuild` fixtures under //! `tests/compile_fail/cargo_cgp/`, one per heading, named `_.rs`. The modules here hold //! the programs the pages say compile: the repaired `Rectangle` that `expand.md` expands, and the -//! repaired `greeting` that `reading-output.md` gives as the fix for `[CGP-E012]`. +//! repaired `greeting` that `reading-output.md` gives as the fix for `[CGP-E030]`. //! //! Neither the fixtures nor these modules check the `cargo cgp check` or `cargo cgp expand` output the //! pages quote. That output was produced by running the tool on exactly these programs, and re-running diff --git a/example-code/tests/cargo_cgp/reading_output.rs b/example-code/tests/cargo_cgp/reading_output.rs index 2f582c6e..7f8dca12 100644 --- a/example-code/tests/cargo_cgp/reading_output.rs +++ b/example-code/tests/cargo_cgp/reading_output.rs @@ -4,7 +4,7 @@ //! `tests/compile_fail/cargo_cgp/reading_output_*.rs`. The one program the page says compiles is the fix //! it gives under *A fix in a help line*: adding `#[uses(PersonName)]` to `greeting`. -/// *A fix in a `help` line* — the program with the attribute the `[CGP-E012]` help names. +/// *A fix in a `help` line* — the program with the attribute the `[CGP-E030]` help names. pub mod a_fix_in_a_help_line { use cgp::prelude::*; diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_1.rs b/example-code/tests/compile_fail/reference/errors_the_fix_1.rs index f4312820..e60965bf 100644 --- a/example-code/tests/compile_fail/reference/errors_the_fix_1.rs +++ b/example-code/tests/compile_fail/reference/errors_the_fix_1.rs @@ -29,9 +29,8 @@ delegate_components! { } } -// error[E0277]: [CGP-E001] the consumer trait `CanGreet` is not implemented for -// context `Person` -// root cause: [CGP-E106] missing field `name` on `Person` +// error[E0277]: [CGP-E001] missing field `name` on `Person` +// root cause: [CGP-E110] missing field `name` on `Person` check_components! { Person { GreeterComponent, diff --git a/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr b/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr index b1a89ed8..6905f200 100644 --- a/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr +++ b/example-code/tests/compile_fail/reference/errors_the_fix_1.stderr @@ -1,7 +1,7 @@ error[E0277]: the trait bound `Person: CanUseComponent` is not satisfied - --> tests/compile_fail/reference/errors_the_fix_1.rs:37:9 + --> tests/compile_fail/reference/errors_the_fix_1.rs:36:9 | -37 | GreeterComponent, +36 | GreeterComponent, | ^^^^^^^^^^^^^^^^ unsatisfied trait bound | help: the trait `HasField>>>>>` is not implemented for `Person` @@ -26,12 +26,12 @@ note: required for `GreetHello` to implement `IsProviderFor` note: required by a bound in `__CheckPerson` - --> tests/compile_fail/reference/errors_the_fix_1.rs:35:1 + --> tests/compile_fail/reference/errors_the_fix_1.rs:34:1 | -35 | / check_components! { -36 | | Person { -37 | | GreeterComponent, -38 | | } -39 | | } +34 | / check_components! { +35 | | Person { +36 | | GreeterComponent, +37 | | } +38 | | } | |_^ required by this bound in `__CheckPerson` = note: this error originates in the attribute macro `cgp_auto_getter` which comes from the expansion of the macro `check_components` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs index 3cec0eb2..5c114619 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs @@ -1,4 +1,4 @@ -//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: `Option<&[T]>` has no rule and reaches the compiler as an unsized bound. +//! `docs/reference/macros/cgp_auto_getter.md`, *Common Mistakes*: the macro rejects `Option<&[T]>`, since the field it would read cannot exist. use cgp::prelude::*; diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs index 786be384..0fd13128 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_misplaced_uses.rs @@ -1,5 +1,5 @@ //! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: `#[uses]` above a component trait -//! is carried onto the generated items and reported once as an unresolved attribute. +//! is rejected by name. use cgp::prelude::*; diff --git a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs index 28b9790a..c58b769a 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs +++ b/example-code/tests/compile_fail/reference/macros/cgp_component_common_mistakes_unnamed_parameter.rs @@ -1,5 +1,5 @@ -//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: a `_` method parameter fails inside -//! the macro, because the generated impls forward each argument by name. +//! `docs/reference/macros/cgp_component.md`, *Common Mistakes*: the macro rejects a `_` method +//! parameter, because the generated impls forward each argument by name. use cgp::prelude::*; diff --git a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs index 63b8e72e..54fbb11e 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs +++ b/example-code/tests/compile_fail/reference/macros/cgp_computer_common_mistakes_output_only_type_parameter.rs @@ -1,5 +1,5 @@ //! `docs/reference/macros/cgp_computer.md`, *Common Mistakes*: a type parameter used only in the -//! return type is not constrained by the generated impl (`E0207`). +//! return type is rejected, since the generated impl cannot determine it. use cgp::prelude::*; diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs index bcf26b83..b0e06b65 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs @@ -1,7 +1,6 @@ use cgp::prelude::*; -// A namespace inheriting itself does not overflow; its forwarding impl has a value parameter -// nothing can determine. +// The macro rejects a namespace inheriting itself. cgp_namespace! { new A: A {} } fn main() {} diff --git a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr index f5b94f58..2e5652ea 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.stderr @@ -1,5 +1,5 @@ error: the namespace `A` cannot inherit from itself; name another namespace as its parent, or omit the parent - --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs:5:25 + --> tests/compile_fail/reference/macros/cgp_namespace_common_mistakes_self_inheriting.rs:4:25 | -5 | cgp_namespace! { new A: A {} } +4 | cgp_namespace! { new A: A {} } | ^ diff --git a/example-code/tests/reference/derives/derive_build_field.rs b/example-code/tests/reference/derives/derive_build_field.rs index 97368674..75465634 100644 --- a/example-code/tests/reference/derives/derive_build_field.rs +++ b/example-code/tests/reference/derives/derive_build_field.rs @@ -230,3 +230,16 @@ pub mod common_mistakes { let _ = Shape::from_variant(PhantomData::, 1.0); } } + +/// A field keeps only its documentation on the companion, so another derive's helper attribute does +/// not reach it. +pub mod helper_attribute_on_a_field { + use cgp::prelude::*; + use serde::Serialize; + + #[derive(Serialize, BuildField)] + pub struct Person { + #[serde(rename = "name")] + pub first_name: String, + } +} diff --git a/example-code/tests/reference/derives/derive_cgp_variant.rs b/example-code/tests/reference/derives/derive_cgp_variant.rs index 244f5de9..59422cc7 100644 --- a/example-code/tests/reference/derives/derive_cgp_variant.rs +++ b/example-code/tests/reference/derives/derive_cgp_variant.rs @@ -103,3 +103,29 @@ pub mod examples { ); } } + +/// No variant name is reserved: the generated impls name their associated types through qualified +/// projections, so a variant may share a name with one of them. Helper attributes of another derive +/// stay on the enum. +pub mod no_reserved_names { + use cgp::prelude::*; + use serde::Serialize; + + #[derive(CgpData, Serialize)] + pub enum Shape { + #[serde(rename = "value")] + Value(u32), + Fields(u32), + FieldsRef(u32), + Remainder(u32), + Extractor(u32), + ExtractorRef(u32), + ExtractorMut(u32), + } + + #[test] + fn a_variant_named_value_is_constructed() { + let shape = Shape::from_variant(PhantomData::, 1); + assert!(matches!(shape, Shape::Value(1))); + } +} diff --git a/example-code/tests/reference/derives/derive_has_fields.rs b/example-code/tests/reference/derives/derive_has_fields.rs index 1425827b..7932e492 100644 --- a/example-code/tests/reference/derives/derive_has_fields.rs +++ b/example-code/tests/reference/derives/derive_has_fields.rs @@ -270,7 +270,7 @@ pub mod under_the_hood { /// ## Common Mistakes /// /// Field order is part of the type: two structs with the same fields in different orders have -/// different shapes. The reserved variant name is a trybuild fixture. +/// different shapes. pub mod common_mistakes { use cgp::prelude::*; diff --git a/example-code/tests/reference/macros/async_trait.rs b/example-code/tests/reference/macros/async_trait.rs index 42cc9b68..20484113 100644 --- a/example-code/tests/reference/macros/async_trait.rs +++ b/example-code/tests/reference/macros/async_trait.rs @@ -169,3 +169,28 @@ pub mod under_the_hood { fn sync_method(&self) -> u8; } } + +/// ## Under the hood: a default body +/// +/// A default body is wrapped in `async move`, so it is the future the method returns. The bound +/// `mut` parameter is rebound inside the block. +pub mod default_body { + use cgp::prelude::*; + + #[async_trait] + pub trait CanAdd { + async fn add(&self, mut value: u32, extra: u32) -> u32 { + value += extra; + value + } + } + + pub struct App; + + impl CanAdd for App {} + + #[test] + fn the_default_body_is_awaited() { + assert_eq!(futures::executor::block_on(App.add(1, 2)), 3); + } +} diff --git a/example-code/tests/reference/macros/cgp_impl.rs b/example-code/tests/reference/macros/cgp_impl.rs index d9e59e8f..5ad29489 100644 --- a/example-code/tests/reference/macros/cgp_impl.rs +++ b/example-code/tests/reference/macros/cgp_impl.rs @@ -638,7 +638,7 @@ pub mod common_mistakes { const LIMIT: u64 = 100; fn allows(&self, count: u64) -> bool { - count < >::LIMIT + count < Self::LIMIT } } @@ -657,7 +657,7 @@ pub mod common_mistakes { } #[test] - fn the_qualified_const_resolves() { + fn the_blocks_own_const_resolves() { assert!(App.allows(99)); assert!(!App.allows(100)); assert_eq!(::LIMIT, 100); diff --git a/example-code/tests/reference/macros/path.rs b/example-code/tests/reference/macros/path.rs index 0ce30c54..1d1b7f2c 100644 --- a/example-code/tests/reference/macros/path.rs +++ b/example-code/tests/reference/macros/path.rs @@ -144,3 +144,16 @@ pub mod under_the_hood { >; } } + +/// A segment that only looks like a primitive's name is a symbol. +pub mod primitive_like_names { + use core::marker::PhantomData; + + use cgp::prelude::*; + + #[test] + fn f_is_a_symbol() { + let _: PhantomData = + PhantomData::>>; + } +} From dfdf0e89f6c0db1991a5ea5543ee34c2e8546241 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Thu, 5 Nov 2026 00:12:40 +0100 Subject: [PATCH 194/516] Fix grammar slips on the knowledge-base pages Co-Authored-By: Claude Opus 5.5 --- docs/ai/knowledge-base/contributing-with-an-agent.md | 2 +- docs/ai/knowledge-base/how-cgp-is-documented.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/ai/knowledge-base/contributing-with-an-agent.md b/docs/ai/knowledge-base/contributing-with-an-agent.md index 17e488a1..b968864f 100644 --- a/docs/ai/knowledge-base/contributing-with-an-agent.md +++ b/docs/ai/knowledge-base/contributing-with-an-agent.md @@ -29,7 +29,7 @@ hallucinate with significant misunderstanding about CGP, or use outdated informa [How CGP's Documentation Is Written](how-cgp-is-documented.md) explains the problem and the process that answers it. -**An AI-assisted pull request or issue must include the prompts that can be used to reproduce similar patch**: +**An AI-assisted pull request or issue must include the prompts that can be used to reproduce a similar patch**: the prompt that verified the issue, or the prompt that applied the fix. The CGP maintainers may run similar prompts themselves rather than merge a pull request directly, so the prompt can be as useful to them as the change. diff --git a/docs/ai/knowledge-base/how-cgp-is-documented.md b/docs/ai/knowledge-base/how-cgp-is-documented.md index 681875cd..2d200889 100644 --- a/docs/ai/knowledge-base/how-cgp-is-documented.md +++ b/docs/ai/knowledge-base/how-cgp-is-documented.md @@ -73,8 +73,8 @@ When the macro's output changes, the snapshot changes with it, and the reference implementation document, and the skill are updated in the same change. When the views disagree, the source decides which one is wrong. -The repeating explanation from different views keeps agents from drifting away from the correct -understand of a given CGP construct. Doing so would require the agent to maintain the same +Repeating the explanation in different views keeps agents from drifting away from the correct +understanding of a given CGP construct. Doing so would require the agent to maintain the same misunderstanding across all views, which is relatively unlikely. ## Written rules From 855e191b0fd23d8ed3574d8adc19101a4d1421ea Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Thu, 5 Nov 2026 00:18:29 +0100 Subject: [PATCH 195/516] Keep the patterns book and the Hermes SDK off the site's pages The guide drops the book from the resources a page may link, and states that both are legacy resources no page links, lists, or recommends. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 39171220..200689b4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,8 +37,15 @@ useless to any reader who does not have that repository. A published page may link only to public resources: other pages on this site, the [`cgp` repository](https://github.com/contextgeneric/cgp) and its siblings, -[docs.rs](https://docs.rs/cgp), [crates.io](https://crates.io/crates/cgp), the -[CGP Patterns book](https://patterns.contextgeneric.dev/), and ordinary external sources. +[docs.rs](https://docs.rs/cgp), [crates.io](https://crates.io/crates/cgp), and ordinary external +sources. + +**The CGP Patterns book and the Hermes SDK are legacy resources: no page links, lists, or recommends +either.** Point a reader who wants a first-principles explanation or a real system built with CGP at +this site's Concepts and Projects pages instead. A page that already mentions one is for the author to +change, since an acknowledgement of where CGP came from is the author's to keep or drop. The knowledge +base's [website rules](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/AGENTS.md#leave-legacy-resources-off-public-pages) +state the rule in full. **Two hand-written surfaces are sanctioned exceptions, and only two.** `docs/ai/disclaimer.md` links to the knowledge base repository, because the base is the subject it discloses: the page's argument From 7b98b56e9071d236adbdf637f55c806a5ee652bc Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Thu, 5 Nov 2026 00:23:31 +0100 Subject: [PATCH 196/516] Remove the patterns book links from two documentation pages Co-Authored-By: Claude Opus 5.5 --- docs/contribute.md | 2 +- docs/index.md | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/docs/contribute.md b/docs/contribute.md index a7725352..6ef9af33 100644 --- a/docs/contribute.md +++ b/docs/contribute.md @@ -14,7 +14,7 @@ Join the conversation on platforms like [**Discord**](https://discord.gg/Hgk3rCw ## Read The Documentation -We encourage you to explore the documentation available on this website, including the [CGP Patterns](https://patterns.contextgeneric.dev) book. Your feedback is invaluable to us—if you encounter anything confusing or unclear, please let us know so we can improve the content and make it more accessible to everyone. +We encourage you to explore the documentation available on this website. Your feedback is invaluable to us—if you encounter anything confusing or unclear, please let us know so we can improve the content and make it more accessible to everyone. ## Publish Your own CGP Components diff --git a/docs/index.md b/docs/index.md index 42921bb9..1ed6fd59 100644 --- a/docs/index.md +++ b/docs/index.md @@ -57,11 +57,8 @@ Use the documentation according to the question you need to answer: - [Glossary](/docs/reference/glossary): short definitions of the terms used across this documentation. - [Resources](/docs/resources): libraries, projects, talks, and further reading. -The [Context-Generic Programming Patterns book](https://patterns.contextgeneric.dev/) develops CGP -from first principles. It is useful for understanding the underlying patterns, but its examples do -not consistently match the current library. Use the maintained tutorials and reference when writing -new code. The [blog](/blog) records releases, design discussions, and talks; older posts describe -the library as it was when they were published. +The [blog](/blog) records releases, design discussions, and talks; older posts describe the library +as it was when they were published. --- From ac7a0089da3b7e203a91c4a42f60b3b643cd9ece Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Thu, 5 Nov 2026 21:34:07 +0100 Subject: [PATCH 197/516] Say that `[CGP-E016]` names the macro of each check table The error-codes page covers two `delegate_and_check_components!` tables for one context, and tables of different macros given one `#[check_trait]` name, whose fix renames one check trait. Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/error-codes.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index b12ac2ea..69f231d9 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -209,7 +209,8 @@ To fix it, remove one of the two. ### CGP-E016 -Two `check_components!` tables in one module check the same context, so they share a check-trait name. +Two `check_components!` tables, or two `delegate_and_check_components!` tables, in one module check the same context, +so they share a check-trait name. The message names the macro the tables were written with. ```text [CGP-E016] two `check_components!` tables in one module check `` @@ -217,7 +218,7 @@ Two `check_components!` tables in one module check the same context, so they sha To fix it, merge the tables, or name one table's check trait with `#[check_trait(...)]`. When two attributes give one name, the message -says so instead. +says so instead, and for tables of different macros it names each macro and asks you to rename one check trait. [The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. ### CGP-E017 From 6598bb87d58506d140ac47650b4bdd65178052c8 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Thu, 5 Nov 2026 21:50:46 +0100 Subject: [PATCH 198/516] Say that a doubled `delegate_and_check` entry reads as `[CGP-E010]` Co-Authored-By: Claude Opus 5.5 --- docs/cargo-cgp/error-codes.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/cargo-cgp/error-codes.md b/docs/cargo-cgp/error-codes.md index 69f231d9..5478f65a 100644 --- a/docs/cargo-cgp/error-codes.md +++ b/docs/cargo-cgp/error-codes.md @@ -204,7 +204,8 @@ A `check_components!` table lists one entry twice. [CGP-E015] `check_components!` checks `` twice for `` ``` -To fix it, remove one of the two. +To fix it, remove one of the two. A `delegate_and_check_components!` table that lists an entry twice also wires it twice, +so you see that as [CGP-E010](#cgp-e010) alone. [The wiring itself does not compile](/docs/reference/errors#the-wiring-itself-does-not-compile) covers this family. ### CGP-E016 From 577405f7cc0952022fad8f578fd608efa1676eab Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 08:38:28 +0100 Subject: [PATCH 199/516] State the self:: parent rejection and its limit The `cgp_namespace!` reference and the errors page say that a namespace naming itself through a `self::` path is rejected like a bare one, and the reference adds that a longer path such as `crate::A` is not checked. Co-Authored-By: Claude Opus 5.5 --- docs/reference/errors.md | 4 ++-- docs/reference/macros/cgp_namespace.md | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/reference/errors.md b/docs/reference/errors.md index f140ca2d..54f1b0d1 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -487,8 +487,8 @@ tool reports it as `[CGP-E021]`. **A related cycle sits at namespace definitions rather than at a use site.** Namespaces whose parent chain loops (`A: B` with `B: A`) fail *eagerly*, with an `E0275` on each `cgp_namespace!` block, because the cycle lives in the `where` clause of a generated impl the compiler checks on sight. A -namespace that inherits itself (`A: A`) never reaches the compiler, because `cgp_namespace!` rejects it -with ``the namespace `A` cannot inherit from itself``. Two things are unusual about the mutual cycle. Under +namespace that inherits itself (`A: A`, or `A: self::A`) never reaches the compiler, because +`cgp_namespace!` rejects it with ``the namespace `A` cannot inherit from itself``. Two things are unusual about the mutual cycle. Under `cargo cgp check`'s next-generation solver the code **compiles clean** and nothing is reported, the one class where the tool shows you *less* than plain `cargo check`. And the wiring is wrong regardless: break the loop so the parent chain forms a tree, factoring shared entries into a third diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index d392e1da..da7ae3df 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -414,13 +414,18 @@ error[E0275]: overflow evaluating the requirement `__Key__: A<__BComponents>` note: required for `__Key__` to implement `B<__AComponents>` ``` -A namespace inheriting *itself*, as in `new A: A {}`, or another instance of itself, as in -` new A: A {}`, is rejected by the macro, with the caret on the parent's name: +A namespace inheriting *itself*, as in `new A: A {}` or `new A: self::A {}`, or another instance of +itself, as in ` new A: A {}`, is rejected by the macro, with the caret on the parent's +name: ```text error: the namespace `A` cannot inherit from itself; name another namespace as its parent, or omit the parent ``` +A parent written through a longer path, such as `crate::A`, is not checked, since the macro cannot +tell which item the path names, so that cycle reaches the compiler as an unconstrained-parameter +error instead. + **A registered component with no provider bound anywhere still compiles.** If a `#[prefix]` routes a component into a namespace and nothing ever binds a provider at its path, the redirect lands on an empty slot and the context compiles regardless. Only a [`check_components!`](./check_components.md) reports it, and what it From b7c6b3e33a9a00980efb2b4ece14c722a044255c Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 08:42:14 +0100 Subject: [PATCH 200/516] Quote the optional-slice rejection with the written type The `#[cgp_auto_getter]` reference quotes the message for `Option<&[u8]>`, which now names the type the getter wrote, and the example crate's compile-fail snapshot is re-blessed to match. Co-Authored-By: Claude Opus 5.5 --- docs/reference/macros/cgp_auto_getter.md | 5 +++-- .../cgp_auto_getter_common_mistakes_option_slice.stderr | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/reference/macros/cgp_auto_getter.md b/docs/reference/macros/cgp_auto_getter.md index 0d7bfc77..4a1b5ada 100644 --- a/docs/reference/macros/cgp_auto_getter.md +++ b/docs/reference/macros/cgp_auto_getter.md @@ -383,10 +383,11 @@ The plain reference, `&str`, slice, and `MRef` forms are unaffected, because a ` coerces to the shared one. Return `Option<&mut T>` from a `&mut self` getter, or take `&self`. **`Option<&[T]>` is not a supported return type**, and neither is `Option<&dyn Trait>`. The macro rejects -them, since the field they would read cannot exist: +them, since the field they would read cannot exist, and names the container to read with the type you +wrote, here for `Option<&[u8]>`: ```text -error: `Option<&[T]>` would read an `Option<[T]>` field, which cannot exist because a slice is unsized; read an `Option>` field as `Option<&Vec>` instead +error: `Option<&[u8]>` would read an `Option<[u8]>` field, which cannot exist because a slice is unsized; read an `Option>` field as `Option<&Vec>` instead ``` A type named by a path, such as `Option<&Path>`, has a size only the compiler knows, so it still reaches diff --git a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr index 84569f6e..c361fbf8 100644 --- a/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr +++ b/example-code/tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.stderr @@ -1,4 +1,4 @@ -error: `Option<&[T]>` would read an `Option<[T]>` field, which cannot exist because a slice is unsized; read an `Option>` field as `Option<&Vec>` instead +error: `Option<&[u8]>` would read an `Option<[u8]>` field, which cannot exist because a slice is unsized; read an `Option>` field as `Option<&Vec>` instead --> tests/compile_fail/reference/macros/cgp_auto_getter_common_mistakes_option_slice.rs:7:24 | 7 | fn bytes(&self) -> Option<&[u8]>; From 9f80572722984f5f4a69c453ed38ad962d637014 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 08:45:51 +0100 Subject: [PATCH 201/516] State that a mut self receiver of a default method is accepted The `#[cgp_component]` reference says a `mut self` receiver of a default method is forwarded like a `mut` parameter, and the sentence moves after the rejection message, which its colon introduced. Co-Authored-By: Claude Opus 5.5 --- docs/reference/macros/cgp_component.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/reference/macros/cgp_component.md b/docs/reference/macros/cgp_component.md index 0d1f4a7b..1e2a4d95 100644 --- a/docs/reference/macros/cgp_component.md +++ b/docs/reference/macros/cgp_component.md @@ -521,13 +521,15 @@ reads the provider's own `LIMIT` in the provider trait. **Every method parameter needs a plain name.** The impls the macro generates forward each argument to the provider by name, so a `_` parameter, which Rust allows in a trait method without a body, or a `ref` binding, a binding with a subpattern, or a destructuring pattern such as `(a, b): (u32, u32)` in a default -method is rejected. A `mut value` parameter of a default method is accepted and forwarded by its name: +method is rejected: ```text error: a component method parameter needs a plain name, since the generated impls forward each argument by name; write a name such as `_value`, and destructure inside a default body ``` -Name the parameter instead, as in `_value: u32`, and destructure inside a default method's body. +Name the parameter instead, as in `_value: u32`, and destructure inside a default method's body. A +`mut value` parameter or a `mut self` receiver of a default method is accepted and forwarded by its +name. **A `name:` parameter must be one of the trait's own.** The marker struct declares the name's parameters while the generated impls name it with the trait's, so the macro rejects a parameter the From e01f88b57fbc7c1520e9e01dd20a3816cae659ac Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 17:18:58 +0100 Subject: [PATCH 202/516] Call an unchecked namespace parent any other path `crate::A` is the same length as `self::A`, so "a longer path" misdescribed the parents the macro leaves unchecked. Co-Authored-By: Claude Opus 5.5 --- docs/reference/macros/cgp_namespace.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/macros/cgp_namespace.md b/docs/reference/macros/cgp_namespace.md index da7ae3df..04e2c641 100644 --- a/docs/reference/macros/cgp_namespace.md +++ b/docs/reference/macros/cgp_namespace.md @@ -422,7 +422,7 @@ name: error: the namespace `A` cannot inherit from itself; name another namespace as its parent, or omit the parent ``` -A parent written through a longer path, such as `crate::A`, is not checked, since the macro cannot +A parent written through any other path, such as `crate::A`, is not checked, since the macro cannot tell which item the path names, so that cycle reaches the compiler as an unconstrained-parameter error instead. From c67ad42bfcc33e629b5be9a249001cf6e1999726 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 23:12:46 +0100 Subject: [PATCH 203/516] Drop a stale reserved-name note and a script's leftovers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The variant derives no longer reserve any name, so the extractor page's advice to check the names and rename a variant that collides with `Fields` or `FieldsRef` sends a reader to a rename they do not need; that advice is gone, and the sentence on diagnostics that leave the variant unnamed stays. The error page's quote of the method-call headline carried the `+"…"+` of the script that wrote it, which broke the code spans, and it now quotes the headline whole. A trailing space in the provider page's paragraph is dropped. Co-Authored-By: deepseek-v4.1-flash --- docs/reference/derives/derive_extract_field.md | 4 +--- docs/reference/errors.md | 2 +- docs/reference/macros/cgp_provider.md | 2 +- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/reference/derives/derive_extract_field.md b/docs/reference/derives/derive_extract_field.md index ad19169b..955bf86e 100644 --- a/docs/reference/derives/derive_extract_field.md +++ b/docs/reference/derives/derive_extract_field.md @@ -305,9 +305,7 @@ serve that purpose. An error naming `IsNothing` usually means record and variant been mixed. Extractor diagnostics may leave the offending variant unnamed. The implementations target generated -companion enums, so both the headline and the note can point to the derive. Check the names above and -rename the conflicting variant. [`HasFields`](./derive_has_fields.md) also reserves `Fields` and -`FieldsRef`, so an enum deriving the full family must avoid those too. +companion enums, so both the headline and the note can point to the derive. **The remainder does not inherit the enum's attributes.** Deriving `Debug` or `PartialEq` on the enum does not implement them for the companion. Use `.ok()`, `.is_ok()`, or a `match` to inspect the diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 54f1b0d1..658f98b7 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -228,7 +228,7 @@ error[E0277]: the trait bound `f64: Eq` is not satisfied This is the one class here without a `[CGP-Exxx]` headline at a check, and the absence is deliberate. Reached through a method call, where the compiler's headline talks about the method, the same mistake -reads `[CGP-E001] the trait bound `+"`f64: Eq`"+` is not satisfied`. +reads `` [CGP-E001] the trait bound `f64: Eq` is not satisfied ``. The fix is not to wire a component or add a field but to satisfy the trait: wire the abstract type to something that implements it, implement it for a type you own, or relax the provider's bound if diff --git a/docs/reference/macros/cgp_provider.md b/docs/reference/macros/cgp_provider.md index e1808bbe..5cad05e5 100644 --- a/docs/reference/macros/cgp_provider.md +++ b/docs/reference/macros/cgp_provider.md @@ -220,7 +220,7 @@ A couple of cases call for writing the raw form yourself: - **You need the inside-out provider-trait shape itself**, not merely a separately-declared struct: a bound `#[cgp_impl]`'s sugar cannot express, or a rare construct its rewrite does not support, whether from a limitation or a bug. This is uncommon. Most bounds that look like they need the raw form are - expressible in `#[cgp_impl]`'s explicit-context form instead + expressible in `#[cgp_impl]`'s explicit-context form instead (`impl AreaCalculator for Context`), which reaches a higher-ranked bound such as `for<'a> &'a Context: IntoIterator` and pins the provider to a single concrete context with `impl AreaCalculator for Rectangle` alike. A struct that `new` cannot declare, such as one carrying a default generic parameter From e4602a6d5d174e3b2445652010e693954886332f Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 23:13:51 +0100 Subject: [PATCH 204/516] Name the case each wiring-name code covers The skill and the website page read the wiring-name codes as covering any key that fails to resolve. In fact `[CGP-E042]` fires only for a key built by appending `Component` to a consumer trait's name, while a misspelled component name keeps rustc's plain `E0425`, as a probe of `GreeterComponnet` shows. Each code now names its own case, and the paragraphs say a key the tool cannot settle keeps the compiler's message. Co-Authored-By: deepseek-v4.1-flash --- docs/reference/macros/delegate_components.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 2893cf8b..13524370 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -771,12 +771,16 @@ Use a bracketed group when the path must continue past the alternatives, and a b end. **Naming a provider struct that does not exist** is easy to do when you wrote a provider with -[`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared it separately. The error -is `E0425`, ``cannot find type `SquareArea` in this scope``, which names an unresolved type rather -than anything about wiring. When no type of that name exists anywhere, -[`cargo cgp check`](/docs/cargo-cgp/error-codes#cgp-e043) reports it as an undeclared provider, `[CGP-E043]`, and a -key that does not resolve as one of `[CGP-E040]` to `[CGP-E042]` or `[CGP-E044]`. A name declared elsewhere -but not imported keeps the compiler's message and its import suggestion. +[`#[cgp_impl]`](./cgp_impl.md) *without* the `new` keyword and never declared it separately. The +error is `E0425`, ``cannot find type `SquareArea` in this scope``, which names an unresolved type +rather than anything about wiring. When no type of that name exists anywhere, +[`cargo cgp check`](/docs/cargo-cgp/error-codes#cgp-e043) reports it as an undeclared provider, +`[CGP-E043]`. A key that names a consumer trait, a component that exists but is not imported, a +component guessed from a consumer trait's name, or a type in an `@`-path nothing declares gets one +of the [wiring-name codes](/docs/cargo-cgp/error-codes#wiring-keys-and-values-that-do-not-resolve), +`[CGP-E040]` to `[CGP-E042]` or `[CGP-E044]`; a key the tool cannot settle, such as a misspelled +component name, keeps the compiler's `E0425`. A value declared elsewhere but not imported keeps the +compiler's message and its import suggestion. **A bare `N` in a nested table's generic list declares a type parameter.** That list declares the inner struct, so ` ArrayKey: UseDelegate { … }>` gives From d2bdd7b91c5bb3533ddffdc8046703981a90d903 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 23:14:13 +0100 Subject: [PATCH 205/516] Correct the command reference's profile and update rows The page said the tool builds under cargo's `check` profile unless `--profile` is passed, though the front-end takes `--release` as a chosen profile too, and the update row promised the newest published version rather than the newest its release channel allows, which the help already says. Co-Authored-By: deepseek-v4.1-flash --- docs/cargo-cgp/command-reference.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/cargo-cgp/command-reference.md b/docs/cargo-cgp/command-reference.md index c5e2ea4f..84ad7932 100644 --- a/docs/cargo-cgp/command-reference.md +++ b/docs/cargo-cgp/command-reference.md @@ -36,7 +36,7 @@ The tool has four commands. Two read your code, and two install and update the t | `check` | Runs `cargo check` and rewrites the CGP errors it recognizes | [Check](./check.md) | | `expand` | Prints the Rust one target's macros generate | [Expand](./expand.md) | | `setup` | Installs the pinned nightly and builds the driver | [Installation](./installation.md#with-cargo) | -| `update` | Upgrades the tool to the newest published version | [Installation](./installation.md#updating) | +| `update` | Upgrades the tool to the newest version its release channel allows | [Installation](./installation.md#updating) | ### `check` @@ -65,10 +65,10 @@ cargo cgp expand [--item ] [CARGO RUSTC ARGS]... | `--item ` | Prints only one module or item instead of the whole target. The path is `::`-separated, names something inside the crate, and may start with `crate::`. A module gives its contents, a type its declaration and every impl written for it, and a trait its definition and every impl of it. | | `-h`, `--help` | Prints the help for `expand`, including `--item`. | -Every other argument is passed to `cargo rustc`, so choosing the target, with `--lib`, `--bin`, `-p`, or -`--features`, is cargo's job. A package with more than one target needs `--lib` or -`--bin `. Unless you pass `--profile`, the tool builds under cargo's `check` profile. The -expansion goes to standard output, and everything else goes to standard error. +Every other argument is passed to `cargo rustc`, so choosing the target, with `--lib`, `--bin`, +`-p`, or `--features`, is cargo's job. A package with more than one target needs `--lib` or +`--bin `. Unless you pass `--profile` or `--release`, the tool builds under cargo's `check` +profile. The expansion goes to standard output, and everything else goes to standard error. ### `setup` From 7e3ba7d08436934b530155bfacc2f82146164ea5 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 23:15:14 +0100 Subject: [PATCH 206/516] Compile the release post's current listings The blog example file still declared `ContentFilterComponents` as an alias of `AiContentFilterComponents` and wired the production context through it, where the post has wired `AiContentFilterComponents` directly since the review pass dropped that alias. Its dependency-growth stage also wired with `delegate_components!` and checked the contexts separately, where the post uses `delegate_and_check_components!` for each. The stages now hold the post's listings, so the crate checks what the page shows. Co-Authored-By: deepseek-v4.1-flash --- example-code/tests/blog/v0_8_0_release.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/example-code/tests/blog/v0_8_0_release.rs b/example-code/tests/blog/v0_8_0_release.rs index 9527836c..0e552f42 100644 --- a/example-code/tests/blog/v0_8_0_release.rs +++ b/example-code/tests/blog/v0_8_0_release.rs @@ -314,7 +314,7 @@ mod start_with_a_manager_and_add_dependencies { pub database: PostgresDb, } - delegate_components! { + delegate_and_check_components! { ProductionApp { UserManagerComponent: PostgresUserManager, PostManagerComponent: PostgresPostManager, @@ -328,7 +328,7 @@ mod start_with_a_manager_and_add_dependencies { pub database: PostgresDb, } - delegate_components! { + delegate_and_check_components! { TestApp { UserManagerComponent: PostgresUserManager, PostManagerComponent: PostgresPostManager, @@ -336,8 +336,6 @@ mod start_with_a_manager_and_add_dependencies { SpamMessageDetectorComponent: DummySpamMessageDetector, } } - check_components! { ProductionApp { UserManagerComponent, PostManagerComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } - check_components! { TestApp { UserManagerComponent, PostManagerComponent, UsernameCensorComponent, SpamMessageDetectorComponent, } } } mod separate_filtering_from_database_access { @@ -1154,8 +1152,6 @@ mod sharing_default_implementations { @app.core.post.PostDeleterComponent: DeletePostWithPostgres, } } - type ContentFilterComponents = AiContentFilterComponents; - #[derive(HasField)] pub struct ProductionApp { pub database: PostgresDb, @@ -1164,7 +1160,7 @@ mod sharing_default_implementations { ProductionApp { namespace DefaultAppComponents; - @app.extra.content_filter: ContentFilterComponents, + @app.extra.content_filter: AiContentFilterComponents, } } check_components! { From 1777aa888458c3ae0f694c1246e19a8281c5c8e2 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 23:15:21 +0100 Subject: [PATCH 207/516] State the example crate's machine-path dependence The snapshots that quote a line from the sibling `cgp` checkout carry that checkout's absolute path, since the manifest depends on `cgp` by path, so they fail on a machine whose checkout sits elsewhere. The re-bless note now says so, beside the command that rewrites them. Co-Authored-By: deepseek-v4.1-flash --- example-code/README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/example-code/README.md b/example-code/README.md index a5365c03..7ef622d8 100644 --- a/example-code/README.md +++ b/example-code/README.md @@ -98,6 +98,11 @@ them after a bump rather than editing them by hand: TRYBUILD=overwrite cargo test --test compile_fail_tests ``` +A snapshot that quotes a line from the `cgp` checkout carries that checkout's absolute path, since the +manifest depends on `cgp` by path. The crate's own files and the standard library are written as +`tests/…` and `$RUST/…`, so a checkout elsewhere fails only the snapshots naming `cgp`, and re-blessing +writes the new path in. + ## Generated code Two of these pages show what a macro *generates*, in simplified form. A hand-rolled rendering of such From 6f64f8e0f6d6f16a75a2bfd7e31c4fc110675679 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Fri, 6 Nov 2026 23:18:56 +0100 Subject: [PATCH 208/516] Keep the pass-through cases to a provider or a type The paragraph's closing sentence said a "name" declared elsewhere but not imported keeps the compiler's message, where a component in that state gets `[CGP-E041]` instead. It now names the provider and the type, the cases the error-codes page leaves to rustc's `E0425`. Co-Authored-By: deepseek-v4.1-flash --- docs/reference/macros/delegate_components.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/macros/delegate_components.md b/docs/reference/macros/delegate_components.md index 13524370..03fb9d27 100644 --- a/docs/reference/macros/delegate_components.md +++ b/docs/reference/macros/delegate_components.md @@ -779,8 +779,8 @@ rather than anything about wiring. When no type of that name exists anywhere, component guessed from a consumer trait's name, or a type in an `@`-path nothing declares gets one of the [wiring-name codes](/docs/cargo-cgp/error-codes#wiring-keys-and-values-that-do-not-resolve), `[CGP-E040]` to `[CGP-E042]` or `[CGP-E044]`; a key the tool cannot settle, such as a misspelled -component name, keeps the compiler's `E0425`. A value declared elsewhere but not imported keeps the -compiler's message and its import suggestion. +component name, keeps the compiler's `E0425`. A provider or a type declared elsewhere but not +imported keeps the compiler's message and its import suggestion. **A bare `N` in a nested table's generic list declares a type parameter.** That list declares the inner struct, so ` ArrayKey: UseDelegate { … }>` gives From 6ffc879be5e23a9fa122106d1938871c3267c084 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 7 Nov 2026 00:23:13 +0100 Subject: [PATCH 209/516] Revise remaining concept pages with natural writing --- docs/concepts/abstract-types.md | 104 ++++++++++--------- docs/concepts/aggregate-providers.md | 95 ++++++++--------- docs/concepts/check-traits.md | 103 ++++++++++--------- docs/concepts/dispatching.md | 107 ++++++++++---------- docs/concepts/extensible-records.md | 98 +++++++++--------- docs/concepts/extensible-variants.md | 110 ++++++++++---------- docs/concepts/handlers.md | 105 +++++++++---------- docs/concepts/higher-order-providers.md | 119 +++++++++++----------- docs/concepts/index.md | 38 ++++--- docs/concepts/modularity-hierarchy.md | 129 ++++++++++++------------ docs/concepts/monadic-handlers.md | 96 +++++++++--------- docs/concepts/namespaces.md | 84 ++++++++------- docs/concepts/send-bounds.md | 83 ++++++++------- docs/concepts/type-level-dsls.md | 102 ++++++++++--------- 14 files changed, 721 insertions(+), 652 deletions(-) diff --git a/docs/concepts/abstract-types.md b/docs/concepts/abstract-types.md index 7969d4c2..df2f55d3 100644 --- a/docs/concepts/abstract-types.md +++ b/docs/concepts/abstract-types.md @@ -5,10 +5,10 @@ sidebar_position: 5 # Abstract types -An **abstract type** lets generic code name a type while each context chooses its concrete form. -Several providers can share the same scalar or error type without taking a separate type parameter -for it. This page starts with Rust's associated types, explains how CGP wires and shares them, and -ends with the limits of that abstraction. +An **abstract type** gives providers a shared name for a type their context chooses. For example, +providers can return the same error type without deciding whether it is a string or a domain enum, +or carry out calculations using the scalar type their application selects. Rust's associated types +express that relationship, and CGP lets each context make the choice through wiring. ## Rust already has this @@ -29,13 +29,15 @@ impl HasScalarType for Embedded { } ``` -Generic code with a `Context: HasScalarType` bound can use `Context::Scalar` without choosing `f32` -or `f64`. The compiler resolves that associated type when the context is known. CGP uses this same -mechanism, and a context can implement an abstract-type trait directly as shown above. +With a `Context: HasScalarType` bound, generic code can use `Context::Scalar` while leaving the +choice between `f32` and `f64` to the context. Once the context is known, Rust resolves the associated +type. CGP builds on this mechanism, so a direct implementation like either one above is also a valid +way to supply an abstract type in a CGP program. -A generic parameter lets a caller choose a type for each use; an associated type ties the choice to -an implementing type. With `HasScalarType`, every use of `HighPrecision::Scalar` means `f64`. -That shared choice becomes useful when several providers need to agree on a type. +The important relationship is between the implementing type and its scalar: every use of +`HighPrecision::Scalar` means `f64`. A separate generic parameter would leave the scalar open to +callers at each use. An associated type instead gives all providers working with `HighPrecision` +the same choice. ## Choosing the type by wiring @@ -66,13 +68,14 @@ delegate_components! { } ``` -`UseType` sets `Scalar` to `f64`. The macro generates the provider implementation that makes -this work, so the context only needs to name the type. Other providers can compute the choice from -further type information, but `UseType` suffices for a fixed choice. +Here `UseType` supplies `f64` as `HighPrecision`'s `Scalar`, using the provider implementation +generated by `#[cgp_type]`. The context therefore names only its chosen type in the table. A provider +could also determine the type from further type information, but a fixed choice needs only +`UseType`. -The selected type must satisfy the associated type's bounds. Here `Scalar: Copy` accepts `f32` and -`f64`, but rejects `String`. Wiring `UseType` would produce a `String: Copy` error when the -component is checked or used. Like other component wiring, the table is +That choice still has to meet the trait's bounds. Because `Scalar` requires `Copy`, choosing `f32` +or `f64` works, while `UseType` produces a `String: Copy` error when checked or used. As with +other wiring, the table alone does not force that check: its requirements are [checked lazily](./check-traits.md). ## One type, agreed on by everything that needs it @@ -88,24 +91,27 @@ pub trait CanCalculateShapeArea { } ``` -Here the context represents an application, while `Shape` is the data being measured. The application -chooses the result type through `HasScalarType`; the shape types do not need to implement that trait. -A fieldless `struct App;` can serve as the context if its providers need only its type choices and wiring. +In this interface, the context is an application and `Shape` is the value it measures. The application +chooses the shared result type through `HasScalarType`, leaving the shape types free of that +requirement. If the providers need only type choices and wiring, even a fieldless `struct App;` can +serve as the context. -Changing the application's wiring from `UseType` to `UseType` changes the declared result -type for every shape. The selected providers must support that choice: a provider restricted to -`Scalar = f64` cannot also serve a context that selects `f32`. Abstracting the result type does not -supply conversions or arithmetic implementations automatically. +If the application switches from `UseType` to `UseType`, every shape calculation's +declared result changes with it. For the same implementations to keep working, they must support +the new choice. A provider restricted to `Scalar = f64` cannot serve an application choosing `f32`, +and the abstraction does not supply arithmetic or conversions for either type. -`#[use_type(HasScalarType.Scalar)]` lets the signature use `Scalar` as a local shorthand for -`::Scalar`. It also adds the required trait bound. On this component, that -bound is part of the interface because its return type depends on it. +The `#[use_type(HasScalarType.Scalar)]` attribute makes that relationship visible in the signature. +It imports `Scalar` as shorthand for `::Scalar` and adds the corresponding +trait bound. Because callers need to name the return type, this bound belongs to the component's +public interface. ## Type dependencies without extra parameters -A context can collect type choices that would otherwise become separate generic parameters. -Code that needs a scalar refers to `Context::Scalar`; it does not need an additional `Scalar` -parameter alongside `Context`. Providers can use the same approach for an error type or a runtime. +This shared choice can also reduce the parameters a provider needs. Once `Context` determines +`Scalar`, code can refer to `Context::Scalar` without taking a second parameter for it. The same +relationship can hold for an error type or runtime, letting the context collect several choices +that generic code needs to use together. An implementation can keep a type dependency out of its caller's interface when the type is used only inside the implementation. If the type appears in a public argument or result, the interface @@ -138,10 +144,10 @@ impl Loader { } ``` -`LoadOrFail` reports an empty path without choosing the application's error representation. -The context supplies both the error type and a provider that converts the source `String` into it. -The resulting type could be `anyhow::Error`, a domain enum, or `String`, provided the selected -conversion supports it. +When the path is empty, `LoadOrFail` reports a `String` through `CanRaiseError`. Its context decides +both the error representation and how to turn that source string into it. The same provider can +therefore return `anyhow::Error`, a domain enum, or `String` wherever the selected conversion supports +that choice. Providers that return this context's `Error` can pass errors between them without converting at every boundary. Errors from external libraries still need conversion into that common type. @@ -149,27 +155,27 @@ every boundary. Errors from external libraries still need conversion into that c ## The provider and the import attribute {#two-things-called-usetype} -`UseType` and `#[use_type(...)]` perform complementary jobs despite their similar names: - -- **`UseType`:** A provider placed in a wiring table to select a concrete type. -- **`#[use_type(...)]`:** An attribute placed on a definition to import an associated type and its bound. - -The wiring chooses the type; the import lets generic code refer to that choice by a short name. +The similar names `UseType` and `#[use_type(...)]` refer to different parts of this connection. +`UseType` is the provider in the wiring table that chooses the concrete type. The attribute +imports an associated type and its bound into a definition so the body can use a shorter name. +For example, a context can select `UseType` while its providers refer to that choice simply +as `Scalar` through `#[use_type(HasScalarType.Scalar)]`. ## What it costs -An abstract type defers the concrete choice without hiding its representation. Code that knows -`HighPrecision` uses `f64` can use the operations available on `f64`. Use Rust's module privacy when -callers must not access a representation. +Knowing the context can reveal the concrete type again. Code that knows +`HighPrecision::Scalar = f64` can use the operations available on `f64`, so an abstract type does +not by itself conceal a representation from callers. Rust's module privacy is still needed when +access to the representation must be restricted. -Generic code can rely only on the bounds available where it uses the type. `Scalar: Copy` permits -copying but does not imply arithmetic or comparison. Those operations need additional bounds on the -associated type or on the code that uses it. Adding a bound to the trait requires every context's -chosen type to satisfy it. +Deferring the concrete choice also limits generic code to the bounds it can see. `Scalar: Copy` +permits copying, but arithmetic and comparison need additional bounds, either on the associated +type or where those operations are used. Putting a bound on the trait makes it available to every +user of the abstract type, while requiring every context's chosen type to satisfy it. -A non-generic abstract-type trait supplies one choice per context. If one context needs distinct -error types for separate purposes, represent those choices with separate components or a tagged -component, or use separate contexts. +Sharing one choice also means that a non-generic abstract-type trait cannot supply different +error types for different purposes within the same context. Those distinctions need their own +representation, through separate components, a tagged component, or separate contexts. An abstract-type component can remain unwired until a use exposes the missing choice. Add [`check_components!`](/docs/reference/macros/check_components) beside the context's wiring to verify diff --git a/docs/concepts/aggregate-providers.md b/docs/concepts/aggregate-providers.md index d6d2ebac..0b94e366 100644 --- a/docs/concepts/aggregate-providers.md +++ b/docs/concepts/aggregate-providers.md @@ -5,10 +5,10 @@ sidebar_position: 8 # Aggregate providers -An **aggregate provider** bundles wiring choices so several contexts can reuse them. Each context -names the bundle for the components it needs, and the bundled providers still operate on that context. -This page explains how delegation preserves the context, where to check the result, and when a -namespace is a better fit. +An **aggregate provider** collects provider choices into a wiring table that several contexts can +reuse. Each context delegates a group of components to that table, so changing the shared choices +can update them together. The chosen providers still receive the original context and use its data; +the bundle only connects them. ## A table whose target is not a context @@ -24,9 +24,9 @@ delegate_components! { } ``` -`GeometryComponents` groups the choices of `RectangleArea` and `RectanglePerimeter` under one name. -It is a zero-sized marker used for delegation; the program does not construct it or store data in it. -The context remains the type whose data those providers use. +The `GeometryComponents` name now stands for the choice of `RectangleArea` and `RectanglePerimeter`. +Its type is a zero-sized marker for delegation, so the program needs no bundle value to construct or +store. The data those providers operate on still belongs to whichever context uses the bundle. A context adopts the group by delegating the relevant components to the bundle: @@ -41,9 +41,9 @@ delegate_components! { } ``` -`Rectangle` gets both traits if it meets the bundled providers' requirements. The provider -choices live in `GeometryComponents`, so changing that table changes the choices for every context -that delegates those components to it. +With these entries, `Rectangle` uses the bundle's choices for both components, provided it meets +their requirements. Another context can delegate the same keys to `GeometryComponents` and share +those choices. Editing the bundle then changes both contexts together. ## The context stays the context @@ -54,13 +54,14 @@ Delegation through a bundle preserves the original context. The compiler resolve 2. `GeometryComponents` delegates the same component to `RectangleArea`. 3. `RectangleArea` calculates the area using `Rectangle` as its context. -When `RectangleArea` reads `width` and `height`, it reads them from `Rectangle`. The bundle selects -the implementation but does not supply the field values. Another context can reuse the bundle if it -satisfies the same provider requirements. +At the end of that chain, `RectangleArea` still reads `width` and `height` from `Rectangle`. +Passing through `GeometryComponents` has changed where the provider choice is recorded, while +leaving the source of its data intact. Another context can use the same chain if it satisfies +the provider's requirements. -Bundles can delegate to other bundles using the same mechanism. The compiler follows each table -while keeping the context argument fixed. It resolves the entire chain at compile time, without a -runtime lookup for each table. +The same delegation can continue through another bundle. At each step, the compiler follows the +next table while keeping the original context argument, until it reaches the provider that performs +the work. It resolves that chain at compile time, so adding a bundle does not add a runtime lookup. ## Checking a bundle asks the wrong question @@ -69,15 +70,14 @@ Checking a bundle as a context does not verify that an application can use it. I type receiving the table. Applied to `GeometryComponents`, it asks whether the bundle itself can supply everything its providers require. -The result depends on those requirements: +If those providers need nothing from their context, this check can pass without saying anything +about the intended application. If they need a field such as `width`, it can fail because the bundle +lacks that field, even though `Rectangle` supplies it. Either way, the check has treated +`GeometryComponents` as the context whose data the providers will use. -- A provider without context dependencies accepts `GeometryComponents` as its context, so the check - passes without checking any application that will use the bundle. -- A provider that needs `width` fails because `GeometryComponents` lacks that field, even if - `Rectangle` supplies it correctly. - -Define bundles with plain [`delegate_components!`](/docs/reference/macros/delegate_components). -Verify their requirements against a context that will actually use them. +Because neither result answers whether an application can use the bundle, define bundles with +plain [`delegate_components!`](/docs/reference/macros/delegate_components) and check their +requirements against a context that will actually use them. ## Verifying one properly @@ -93,8 +93,9 @@ check_components! { } ``` -This verifies the full chain, including nested bundles. A missing requirement fails at the check -site even if the provider requiring it is several tables away. +Because the check starts from `Rectangle`, it follows the delegation chain with the same context +that a method call would use. It can therefore catch a missing requirement even when the provider +that needs it sits several nested bundles away. `#[check_providers]` lets you check the bundle and an individual provider separately against the same context. This helps locate a failure within a chain: @@ -111,35 +112,39 @@ check_components! { } ``` -Each named provider gets its own assertion for `Rectangle`. The bundle is checked in the role it -serves: supplying an implementation for that context. +The separate assertions ask whether `RectangleArea` and `GeometryComponents` can each supply this +component for `Rectangle`. Comparing their failures helps locate the broken layer, while keeping +the bundle in its intended role as a provider for that context. ## When a namespace is the better tool -A bundle suits a small group whose components you want to name explicitly. The entry -`[A, B]: TheBundle` shows which choices the context adopts. As the group grows, each context must -still list every component it takes from the bundle. +With a small group, `[A, B]: TheBundle` makes the adopted choices easy to see at the context's +wiring site. As the group grows, though, every context still has to list the components it takes +from the bundle. Maintaining those lists can become another source of repetition. -A [namespace](./namespaces.md) lets a context inherit shared wiring by joining a named table. -It also organizes lookups under paths, which helps when a library supplies wiring for many components. -Customization requires the namespace to leave the relevant paths unbound; a direct context entry -cannot override a key the inherited namespace already binds. +When those repeated lists become difficult to maintain, a [namespace](./namespaces.md) can let +contexts inherit a shared table instead. Its paths organize the lookups and leave chosen +destinations for applications to fill. To allow that customization, the shared namespace must +leave those paths unbound, since a context cannot override an inherited binding. -Use a bundle for explicit delegation of a group of components. Consider a namespace when many -contexts need a shared table and a path structure that separates fixed wiring from application choices. +A bundle therefore keeps adoption explicit at the context's table, while a namespace can share +the routes themselves. Which form is easier to maintain depends on whether naming each adopted +component is useful or has become repetition. ## What it costs -A bundle adds a table to inspect when tracing a method call. Nested bundles add further tables, even -though the compiler resolves them statically. Keep a bundle when centralizing shared choices is worth -that extra reading. +Centralizing choices gives readers another table to inspect when tracing a call. Nesting bundles +adds further tables to that trace, even though the compiler resolves the chain statically. The +shared choices need to justify this extra reading. -A bundle used by only one context may add little value. Repeated wiring across contexts gives a -clear reason to introduce one; anticipated reuse alone may not justify it. +Repeated wiring across contexts provides a concrete reason to maintain a bundle. With only one +context, however, the bundle may add a name and a delegation step without reducing repetition. +Anticipated reuse alone may not be enough to justify it. -The type system does not distinguish a bundle from a context by declaration. Both can receive a -delegation table, so the author must check the bundle against its intended context. A name such as -`GeometryComponents` helps identify its role, but does not enforce it. +The bundle's role is a convention rather than a separate kind of declaration. Both a context and +a bundle can receive a delegation table, which is why the wrong check can treat the bundle as a +context. Naming it `GeometryComponents` helps readers recognize the distinction, but the checks +still need to use the intended context. ## Where to go next diff --git a/docs/concepts/check-traits.md b/docs/concepts/check-traits.md index b1d7dada..3bbd8643 100644 --- a/docs/concepts/check-traits.md +++ b/docs/concepts/check-traits.md @@ -5,16 +5,16 @@ sidebar_position: 6 # Checking your wiring -CGP wiring records provider choices without checking their requirements immediately. A compile-time -check verifies those requirements at a location you choose and helps expose missing dependencies. -This page follows one broken context from a method-call error through an explicit check and -`cargo cgp check`, then explains what each can and cannot verify. +Check traits let you verify a context's wiring at a location you choose. Wiring itself records +provider choices without immediately checking whether the context meets their requirements, so a +missing dependency can remain unnoticed until a later method call. An explicit check brings that +failure back beside the wiring, where the context and its selected providers are easier to inspect. ## A context can be wrong and still compile -A wiring table can name a provider even when the context lacks a field that provider needs. -In this example, `RecordEmails` implements the `EmailSender` component by recording messages in -`sent_emails`, but `BrokenApp` supplies only `smtp_server`: +Consider a provider that records outgoing email in a `sent_emails` field. Its wiring can still +name a context with only an `smtp_server` field, as this example shows. The fragment imports +CGP's prelude and defines both the `EmailSender` component and the recording provider: ```rust use cgp::prelude::*; @@ -40,14 +40,14 @@ pub struct BrokenApp { delegate_components! { BrokenApp { EmailSenderComponent: RecordEmails } } ``` -The table compiles because it records only the mapping from `EmailSenderComponent` to `RecordEmails`. -The compiler has not yet been asked to prove that `RecordEmails` can send email for `BrokenApp`. -That proof will fail: the `#[implicit]` argument requires a `sent_emails` field. +This table establishes which provider `BrokenApp` selects without proving that it can use that +provider. The missing proof would require the `sent_emails` field read by `RecordEmails`' implicit +argument. Because this fragment never asks for `CanSendEmail` on `BrokenApp`, the missing field has +not yet caused a compilation failure. -This deferred checking lets reusable wiring exist before its final context is known. -An [aggregate provider](./aggregate-providers.md), for example, can group provider choices for -contexts defined elsewhere. Each context must satisfy the providers' requirements when it uses -them, but the bundle does not need to supply those dependencies itself. +Deferring that proof is useful for reusable wiring. An [aggregate provider](./aggregate-providers.md) +can collect choices before the contexts that use it are even defined. Those contexts must eventually +meet the providers' requirements, but the bundle itself needs only to record the choices. ## Where the failure surfaces instead @@ -66,9 +66,10 @@ note: the following trait bounds were not satisfied: `BrokenApp: EmailSender` ``` -The diagnostic reports that `BrokenApp` lacks `CanSendEmail` and `EmailSender`, but does -not identify the missing `sent_emails` field. The failed requirement is hidden behind the generated -trait implementations. The error location may also be far from the wiring, in another module or crate. +The diagnostic stops at the unsatisfied trait implementations: `BrokenApp` lacks `CanSendEmail` +and `EmailSender`. It leaves the missing `sent_emails` field hidden behind the generated +implementations. If the first call occurs in another module or crate, the error can also appear a +long way from the table that selected the provider. ## Asking the question at a line you chose @@ -80,12 +81,12 @@ trait CanUseApp: CanSendEmail {} impl CanUseApp for App {} ``` -The empty implementation compiles only if `App: CanSendEmail` holds. Placing it beside the wiring -catches the failure there, although checking the consumer trait alone can still produce the vague -error shown above. +For Rust to accept the empty implementation, it must establish `App: CanSendEmail` at that line. +Putting it beside the wiring moves a failure there. But the requirement still goes through the +consumer trait, so its diagnostic can remain as vague as the method-call error. -[`check_components!`](/docs/reference/macros/check_components) generates a check that exposes the -selected provider's requirements more directly: +To expose the provider's requirements, the check needs a path through more than the consumer +trait. [`check_components!`](/docs/reference/macros/check_components) generates that check: ```rust check_components! { @@ -95,8 +96,9 @@ check_components! { } ``` -The macro checks `CanUseComponent`, which requires a wiring entry and the selected provider's -dependency bounds for this context. That path makes the missing field visible in the diagnostic: +The generated assertion asks for `CanUseComponent`. Satisfying this bound requires both a wiring +entry and the chosen provider's dependencies for the context being checked. The missing field +therefore appears in the diagnostic: ```text error[E0277]: the trait bound `BrokenApp: CanUseComponent` @@ -111,10 +113,10 @@ note: required for `RecordEmails` to implement `IsProviderFor` ``` -The error now identifies a missing `HasField` implementation and names `RecordEmails` as the -provider requiring it. The expanded field names remain hard to read: `sent_emails` and `smtp_server` -appear as nested character types. The headline also names the generated `CanUseComponent` bound -rather than the public trait. +Following this checking path exposes `RecordEmails`' requirement for a `HasField` implementation. +The cause is closer to the surface, but the field tags still appear as nested character types, +leaving `sent_emails` and `smtp_server` difficult to recognize. The headline also refers to the +generated `CanUseComponent` bound rather than the public trait. ## Reading it through the toolchain @@ -133,8 +135,9 @@ error[E0277]: [CGP-E001] missing field `sent_emails` on `BrokenApp` └─ [CGP-E110] missing field `sent_emails` on `BrokenApp` ``` -The root cause is now explicit: `BrokenApp` lacks `sent_emails`, which `RecordEmails` requires. -The dependency chain connects that missing field to the `CanSendEmail` trait the application needs. +Here the dependency chain connects the application's need for `CanSendEmail` to the provider it +selected and then to the missing `sent_emails` field. This gives the reader both the cause and the +reason that field is required. The tool can also recover causes that ordinary compiler output omits. It uses the compiler's next-generation trait solver for diagnostic recovery, then translates the recognized CGP structures. @@ -160,15 +163,16 @@ check_components! { } ``` -A missing `width` requirement fails both assertions because the wrapper also needs its inner -provider to work. A missing scale factor fails only the wrapper's assertion. Separate diagnostic -locations make that difference easier to see when debugging a -[higher-order provider](./higher-order-providers.md). +If `App` lacks `width`, both assertions fail because the wrapper needs its inner provider to +work. If it lacks only the scale factor, the rectangle assertion passes and the wrapper assertion +fails. Giving each layer its own diagnostic location makes this distinction easier to see when +debugging a [higher-order provider](./higher-order-providers.md). ## What to check, and when to fuse it -Check each context's required components when you define its wiring. This catches missing entries -and unsatisfied dependencies before a later caller happens to exercise them. +Placing checks beside each context's wiring catches missing entries and dependencies before a +caller happens to need them. For basic `Component: Provider` entries, the checks can be part of the +same declaration. [`delegate_and_check_components!`](/docs/reference/macros/delegate_and_check_components) combines wiring and checking for basic `Component: Provider` entries. For generic components, its @@ -187,18 +191,21 @@ context supplies. Neither result verifies the intended application. ## What it costs -Explicit checks cover only the components and parameter sets you list. Add them as you add wiring; -otherwise an omitted component can still fail only when a caller uses it. Generic wiring may need -several checks to cover the concrete uses an application depends on. - -A check can expose a cause without making the diagnostic short. Several invalid entries can produce -several errors, and one shared missing dependency can appear in multiple provider failures. -`cargo cgp check` makes recognized cases easier to read, but raw compiler diagnostics remain verbose. - -Checks verify trait requirements rather than runtime behavior. Ordinary bounds such as `Value: Display` -can still fail as dependencies of a provider, and those traits need ordinary Rust implementations. -They cannot be listed as components in a wiring check unless they have the corresponding CGP component -machinery. Tests remain necessary for behavior such as whether an email was recorded correctly. +An explicit check proves only the components and parameter sets it names. As wiring grows, the +checks need to grow with it, or an omitted component can still fail at a later call site. For a +generic component, this may mean checking several concrete parameter sets that the application +relies on. + +Moving the check does not necessarily shorten its diagnostic. Several broken entries can produce +several errors, and a shared missing dependency may appear once for every provider that needs it. +`cargo cgp check` makes the cases it recognizes easier to follow, while raw compiler output can +remain verbose. + +Even a successful check establishes only the trait requirements. A provider may depend on an +ordinary bound such as `Value: Display`, which still needs an ordinary Rust implementation. Without +the corresponding CGP machinery, that trait cannot itself be listed as a component to check. +And satisfying these bounds says nothing about whether the email body was recorded correctly; +that behavior still needs tests. ## Where to go next diff --git a/docs/concepts/dispatching.md b/docs/concepts/dispatching.md index 4c9f289e..ac0047ce 100644 --- a/docs/concepts/dispatching.md +++ b/docs/concepts/dispatching.md @@ -6,29 +6,29 @@ sidebar_position: 15 # Dispatching Dispatching connects a record's fields or an enum's variants to the providers that process them. -A generic dispatcher can build several record types or handle several enum types while each provider -implements one part of the work. This page explains matching, building, and their compile-time -guarantees, then shows how to derive dispatch from an ordinary trait. +By separating that connection from the individual computations, a generic dispatcher can build +several record types or handle several enum types while each provider implements one part of the +work. The compiler checks that the pieces fit together and cover the required fields or variants. -The examples build on [extensible records](./extensible-records.md) and -[extensible variants](./extensible-variants.md). Those pages explain how CGP exposes fields and -variants to generic code; dispatching chooses and runs the computations that use them. +[Extensible records](./extensible-records.md) and [extensible variants](./extensible-variants.md) +expose data to generic code through field and variant traits. Dispatchers use those traits to run +the computations that build a record or handle the current variant. ## Two directions, one idea -Dispatchers combine generic data operations with a list of handlers. The data traits describe how -to extract a variant or set a field. A handler supplies the computation to perform on the extracted -payload or to produce the field's value. +The data traits used by a dispatcher describe how to extract a variant or set a field. To do +useful work with those operations, the dispatcher also needs handlers: one can process an extracted +payload, while another can produce a value for a field. -Matching and building use these pieces differently: +These operations lead to two forms of dispatch. A matcher tries variants until it finds the +current payload, then runs the corresponding handler. A builder instead runs its handlers in +sequence, adding their results to a [partial record](/docs/reference/glossary#partial-record) +until the record can be finalized. -- **Matching:** Try variants until the current one is found, then run its handler. -- **Building:** Run handlers in sequence, adding their outputs to a [partial record](/docs/reference/glossary#partial-record) until it can be finalized. - -Dispatchers implement the same computation interfaces as other -[handler providers](./handlers.md). They can be selected through context wiring, composed with other -computations, or nested to delegate a group of variants to another matcher. The available interfaces -depend on the dispatcher and the providers it contains. +Because dispatchers implement the same interfaces as other [handler providers](./handlers.md), +they can participate in ordinary context wiring and computation pipelines. A matcher can even +delegate a group of variants to another matcher. The interfaces available to the resulting +composition depend on both the dispatcher and the providers it contains. ## Matching, and why it is exhaustive @@ -56,37 +56,37 @@ extracts the current variant's payload and delegates it through the same context `CircleArea`, and a `Rectangle` reaches `RectangleArea`. The application does not write a `match` over `Shape`. -The matcher tracks unhandled variants through the extractor's remainder type. Each extraction -attempt returns either a payload to handle or a remainder that excludes that variant. The next -attempt receives the narrowed remainder. After every variant has been covered, the remainder is -uninhabited, so finalization can eliminate it without a wildcard or a runtime panic. +To check coverage, the matcher tracks unhandled variants through the extractor's remainder type. +An extraction attempt either finds a payload to handle or passes on a remainder that excludes that +variant. Each miss therefore leaves fewer possibilities for the next attempt. Once every variant +has been covered, the remainder is uninhabited, so finalization can eliminate it without a wildcard +or a runtime panic. -A missing handler prevents the matcher from compiling for that enum. An automatically generated -handler list requires a suitable provider for every payload; an explicit list must leave an -uninhabited remainder. Adding a variant therefore requires either an existing generic handler that -covers it or an additional handler. +If a variant remains uncovered, the matcher cannot compile for that enum. With an automatically +generated handler list, every payload must have a suitable provider; with an explicit list, the +extraction steps must leave an uninhabited remainder. Adding a variant therefore needs either a +new handler or an existing generic handler that already covers it. -The attempts are sequenced by the `OkMonadic` pipeline described in -[monadic handlers](./monadic-handlers.md). A successful extraction stops the search; a miss passes -the remainder onward. Here the `Err` branch means “try another variant,” rather than an application -error. Provider selection and exhaustiveness are checked at compile time, while testing the actual -variant and running its handler happen at runtime. +This sequence of attempts uses the `OkMonadic` pipeline from +[monadic handlers](./monadic-handlers.md). A successful extraction ends the search, while a miss +passes its remainder to the next attempt. In this use of `Result`, `Err` means “try another variant” +rather than an application failure. The compiler checks provider selection and exhaustiveness; +the actual variant tests and handler calls happen when the program runs. ## Building, and why it is complete -A builder dispatcher runs handlers over a partial record and finalizes the result. The partial -record's type tracks which fields are present after each step. `BuildWithHandlers` starts the -builder, passes it through the handler list, and calls `finalize_build` at the end. +Building follows the other direction: handlers supply values until a partial record is complete. +`BuildWithHandlers` starts the builder, passes it through the handler list, and calls `finalize_build`. +After each step, the partial record's type describes the fields supplied so far. -Field adapters let a handler produce either one field or a group of fields. `BuildAndSetField` -computes and sets a named field; `BuildAndMerge` computes a source record and merges its fields. -Both pass the current builder by reference to the inner provider, so a later provider can read -fields an earlier step supplied. +Each step can contribute one field or several. `BuildAndSetField` runs an inner provider and sets +a named field from its output, while `BuildAndMerge` merges the fields of a returned record. Both +lend the current builder to that provider, allowing it to read fields supplied by earlier steps. -Finalization requires every field in the strict builder to be present. Omitting a required field -prevents the pipeline from compiling. Fallible handlers can still return runtime errors while -computing values; completeness guarantees that a successful build supplies every field, not that -construction cannot fail. +As each handler adds fields, the partial record's type records their presence. Finalization +requires every field in the strict builder to be present, so omitting a required field prevents the +pipeline from compiling. Computing those values can still fail at runtime if the handlers are +fallible; the guarantee is that a successful build supplies every field. This supports the [extensible builder pattern](./extensible-records.md): independent providers produce parts of a result, and a dispatcher assembles them into a target record. The handler order @@ -104,10 +104,11 @@ pub trait CanDescribe { } ``` -If `Circle` and `Rectangle` implement `CanDescribe`, a `Shape` enum with the required extensible-data -support gains the trait through a generated [blanket implementation](/docs/reference/glossary#blanket-implementation). A call to `shape.describe()` -forwards to the current payload's implementation without application wiring or a handwritten `match`. -Deriving `CgpData` on `Shape` supplies that data support. +Once `Circle` and `Rectangle` implement `CanDescribe`, the generated +[blanket implementation](/docs/reference/glossary#blanket-implementation) can forward the same +operation from `Shape`. Deriving `CgpData` supplies the enum support it needs, so +`shape.describe()` reaches the current payload's implementation without a handwritten `match` or +application wiring. Explicit dispatch combinators provide more control when the context must choose different handlers or when several variants should be handled as a group. The automatic trait form is a simpler entry @@ -121,14 +122,16 @@ handler. A context-specific wrapper provider can break that cycle by declaring t implementation and calling the matcher inside its method body. Non-recursive `Shape` wiring does not need that extra provider. -Missing handlers can produce errors involving partial-variant types or unsatisfied provider bounds. -An incomplete builder similarly reports bounds involving its partial-record state. These diagnostics -can be longer and less direct than an ordinary non-exhaustive `match` or missing struct field. +When these type-level guarantees fail, the errors can be less direct than an ordinary missing +struct field or non-exhaustive `match`. A missing handler may appear as an unsatisfied provider +bound or a partial-variant type. An incomplete build can similarly report the bounds on its +partial-record state. -Dispatching adds type-level work for each field or variant. The compiler resolves the handler chain -and checks its changing types; wide [shapes](/docs/reference/glossary#shape) and many instantiations can increase that work. Runtime -variant tests and handler calls still occur, and their optimization depends on the generated code -and compiler. Static wiring alone does not guarantee that dispatch has zero runtime cost. +The compiler also has to resolve the handler chain and its changing types for each field or +variant. Wide [shapes](/docs/reference/glossary#shape) and many instantiations can increase that work. +At runtime, variant tests and handler calls still execute, with optimization depending on the +code generated and the compiler. Static wiring removes provider lookup, without promising that +the dispatch operation itself is free. An ordinary `match` or struct literal is usually clearer when one place owns the whole operation. Dispatching becomes useful when generic code must work over different shapes or when independently diff --git a/docs/concepts/extensible-records.md b/docs/concepts/extensible-records.md index 27557c82..7e1bf7e2 100644 --- a/docs/concepts/extensible-records.md +++ b/docs/concepts/extensible-records.md @@ -6,9 +6,9 @@ sidebar_position: 13 # Extensible records Extensible records let generic code read and assemble structs through their field names and types. -Independent providers can contribute fields without knowing the final struct, while the compiler -checks that construction is complete. This page explains the field representation, partial-record -builders, and the limits of matching fields by name. +A provider can contribute fields without knowing the final struct, so several independent providers +can supply parts of a larger value. As those parts are assembled, the builder's type tracks which +fields are present, letting the compiler check that construction is complete. ## What a closed struct cannot do @@ -24,14 +24,14 @@ let app = App { }; ``` -This approach works well when the assembly code should know `App` and its complete set of fields. -The database and HTTP helpers can already be independent of `App`; the constructor connects their -outputs to the application's fields. +The helpers can already be independent of `App`: each returns a value that the constructor puts +in the appropriate field. When one place should know the application's complete structure, this +is a straightforward way to assemble it. -Generic assembly needs a way to make those connections without naming the target struct's fields -in the assembly code. For example, a subsystem might return a small configuration record whose -fields should populate any compatible application. CGP exposes field names and types through traits -so a reusable builder can perform that merge. +To reuse the assembly itself across different targets, however, that connection also needs an +abstraction. A subsystem might return a small configuration record whose fields belong in several +application types. CGP exposes field names and types through traits so a generic builder can merge +that record into any compatible target. ## A struct as a list of named fields @@ -52,19 +52,20 @@ The generated `HasFields::Fields` associated type describes the struct as a prod Product![Field, Field] ``` -Each `Field` pairs a name tag with a value type. `Symbol!("url")` encodes the name as a type, allowing -trait bounds to identify the field during compilation. A product contains every listed field; -this differs from an enum's sum, which contains one variant at a time. +Within the product, each `Field` associates a name tag with a value type. The tag +`Symbol!("url")` represents the name as a type, giving trait bounds a way to identify it during +compilation. The product describes all of these fields together, whereas an enum's sum describes +one alternative at a time. -That list is the struct's **shape**. Code that names a shape itself, in a bound or an impl, can -write it as the struct body it describes: -[`Struct! { url: String, pool_size: u32 }`](/docs/reference/macros/struct) is exactly the type -above, because the macro runs the derive's own encoding. +This field list is the struct's **shape**. When a bound or implementation needs to name it, +[`Struct! { url: String, pool_size: u32 }`](/docs/reference/macros/struct) expresses the same list +using familiar struct syntax. The macro uses the derive's encoding, so both forms produce exactly +the same type. -Generic code can use either the complete field representation or a single-field bound. `HasFields` -describes the whole structure, while `HasField` provides access to one field. The latter is -also the mechanism used by [implicit arguments](./implicit-arguments.md). These operations use -generated Rust implementations rather than inspecting field names at runtime. +An operation does not always need the entire shape. `HasFields` describes the complete structure, +while `HasField` lets code require just one field, as [implicit arguments](./implicit-arguments.md) +do. In either case, generated Rust implementations connect the trait request to the field, so the +program need not inspect names at runtime. ## Built one field at a time, checked all the way @@ -78,14 +79,15 @@ let app: App = App::builder() .finalize_build(); ``` -Here `database` and `http` are smaller records whose fields together supply `App`. `builder()` -creates a partial record with every field absent. Each `build_from` moves the source fields into -matching target fields and returns a builder type that marks those fields present. +Starting with every field absent, `builder()` creates the partial record that will become `App`. +The `database` and `http` records then contribute their fields through `build_from`. Each call moves +the source values into matching target fields and returns a new builder type that records those +fields as present. -Merging requires matching names and value types. Every source field must be accepted by the target -builder; `build_from` does not silently discard fields the target lacks. The source needs the -whole-field and extraction support supplied by `CgpData`, and the target needs the builder support. -The `CanBuildFrom` trait providing the method is imported from `cgp::core::field::impls`. +For a merge to work, both the names and value types must match. Every source field needs a place +in the target builder, so `build_from` cannot silently discard an extra source field. `CgpData` +supplies the source's whole-field and extraction support along with the target's builder support; +the `CanBuildFrom` trait that provides the merge method comes from `cgp::core::field::impls`. `finalize_build` is available only when every field in the strict builder is present. If `App` requires an `http_timeout` field, supplying only the database configuration leaves construction @@ -98,13 +100,13 @@ let app: App = App::builder() .finalize_build(); ``` -That final call fails to compile because the partial record does not implement the required -finalization trait. The error occurs before the program runs, rather than producing a partially -initialized `App` or a runtime failure. +At the final call, the builder still records `http_timeout` as absent. It therefore lacks the +finalization trait, and Rust rejects the call before the program can run. Construction cannot +return a partially initialized `App` through this strict builder. -Independent field contributions can arrive in any order. A provider that reads a previously built -field must still run after the provider that supplies it. The field-state types enforce that -requirement as well as final completeness. +When contributions are independent, their order does not matter. If one provider reads a field +built by another, however, it must run after that field has been supplied. The same types that +track completeness also enforce this dependency between construction steps. ## The pattern this is for @@ -112,9 +114,10 @@ The **extensible builder pattern** assembles a target from independent providers small record. A dispatcher runs the providers, merges their outputs, and finalizes the target. Each provider needs to know its own output fields, but not the final target or the other contributors. -Wiring chooses the target and its contributors. Replacing a subsystem provider changes the assembly -without changing the generic dispatcher, and another application can reuse the same providers for a -different compatible target. The compiler checks that the chosen outputs supply the required fields. +Once the providers are independent of the target, wiring can choose which ones contribute to a +particular application. Replacing a subsystem changes that selection while leaving the generic +dispatcher intact. Another application can reuse the providers for a different compatible record, +and the compiler checks whether their combined fields complete it. [Dispatching](./dispatching.md) explains how `BuildWithHandlers`, `BuildAndSetField`, and `BuildAndMerge` sequence field computations. `BuildAndMergeOutputs` provides the related convenience @@ -126,18 +129,19 @@ Generic construction requires the corresponding traits. Deriving `CgpData` suppl supported struct, but a foreign struct without that support does not become accessible automatically. A local wrapper or explicit conversion may be needed at that boundary. -Field names and types form the contract between contributors and the target. Two subsystems that -use `timeout: u32` for different purposes still describe the same field. The compiler checks type -compatibility and builder state, not the intended meaning. Renaming a required field breaks the -merge or leaves the target incomplete when checked. +Matching names and types is enough for the compiler, so contributors must also agree on what +the fields mean. Two subsystems using `timeout: u32` for unrelated purposes still describe the +same field. Conversely, renaming a required field changes that contract and can break a merge +or leave the target incomplete when checked. -Partial-record types can produce verbose diagnostics. An error may include the target's fields and -presence markers instead of a short message naming the omitted field. Checking smaller assembly -steps can help locate the contribution that is missing or incompatible. +The types that enforce completeness can also make failures harder to read. An error may show the +target's fields and presence markers rather than simply naming an omitted field. When that happens, +checking smaller assembly steps can help locate the missing or incompatible contribution. -The strict builder requires every field, even if an application considers some optional. An -`Option` field still needs a value such as `None`. CGP also provides optional-field and default -extensions, but those use additional conventions beyond the strict construction shown here. +Completeness applies to `Option` fields too. The strict builder needs a value for each one, +even if that value is `None` and the application treats the setting as optional. CGP's optional-field +and default extensions can express other conventions, but they add rules beyond the strict +construction illustrated here. A struct literal or ordinary constructor is simpler when the assembly code can name the target. Extensible construction is useful when a framework builds user-defined records or when several diff --git a/docs/concepts/extensible-variants.md b/docs/concepts/extensible-variants.md index 8fcbc2f9..35aae051 100644 --- a/docs/concepts/extensible-variants.md +++ b/docs/concepts/extensible-variants.md @@ -6,26 +6,28 @@ sidebar_position: 14 # Extensible variants Extensible variants let generic code construct and handle enums through variant names and payload -types. Handlers can be reused across compatible enums, while the compiler still checks that every -variant is covered. This page explains the structural representation, exhaustiveness, and conversions -between enums that share variants. [Extensible records](./extensible-records.md) introduces the -related field representation. +types. By describing the cases it needs through traits, a handler can work across compatible enums +without depending on any one enum definition. The compiler still checks that every variant is +covered, even when independently written handlers supply the cases. + +This uses the same field representation as [extensible records](./extensible-records.md), but an +enum contains one alternative at a time. That difference changes how generic code takes a value +apart and proves that it has handled every possibility. ## The problem a `match` builds in -An exhaustive `match` makes an operation's cases explicit. Adding a variant to an enum makes existing -matches fail to compile unless they already have a pattern that covers it. This is useful when each -operation should be reviewed as the enum changes. +With an exhaustive `match`, an operation lists the enum cases it handles. If a new variant has no +covering pattern, Rust rejects the match, prompting the operation's author to review the new case. +That is useful when the enum and its operations should evolve together. -Reusable per-variant logic does not always need to change with the enum. A circle-area calculation, -for example, can serve several shape enums, including one extended with triangles. Ordinary helper -functions can share that calculation, but each concrete `match` still has to connect its enum's -variants to the helpers. +Some of the work inside those cases may already be reusable. A circle-area calculation can serve +several shape enums, including a larger one that adds triangles. Ordinary helper functions share +that calculation, but each match must still connect its particular enum variants to those helpers. -CGP separates the payload handlers from the generic dispatcher that selects them. An operation can -then support another enum by supplying handlers for its additional payloads, leaving existing -handlers unchanged. The enum definitions remain ordinary closed Rust enums: a downstream crate -extends the design by defining another enum, not by adding variants to an upstream definition. +Separating those helpers from the enum-specific connection is the purpose of CGP's generic +dispatcher. Existing payload handlers can keep working when another enum introduces additional +cases, provided those cases have handlers too. The enums remain ordinary closed Rust types: +a downstream crate defines a new enum rather than adding variants to an upstream definition. ## An enum as a list of named variants @@ -50,30 +52,32 @@ Each `Field` pairs a variant-name tag with its payload type. A sum holds one of where a record's product holds all its fields. Generic code can require an operation on the `Circle` variant without naming `Shape` itself. -That sum is the enum's **shape**. Code that names a shape itself, in a bound or an impl, can write -it as the enum body it describes: -[`Enum! { Circle(Circle), Rectangle(Rectangle) }`](/docs/reference/macros/enum) is exactly the type -above, because the macro runs the derive's own encoding. +This sum is the enum's **shape**. A bound or implementation can name it with +[`Enum! { Circle(Circle), Rectangle(Rectangle) }`](/docs/reference/macros/enum), using the same +syntax as the enum body. Because the macro uses the derive's encoding, that form produces exactly +the sum shown above. -Construction uses the same tags. A `FromVariant` bound lets generic code supply a payload for a -named variant, while the implementing enum determines how to construct the value. Extraction -provides the corresponding operation for taking a payload out. +These name tags also let generic code construct a value. With a `FromVariant` bound, it can supply +a payload for a named variant while leaving the enum's implementation to assemble the value. +Extraction uses the same representation in the other direction, taking a payload back out. ## Exhaustiveness without a wildcard -A **partial variant** tracks which alternatives remain possible during extraction. Converting an -enum value to its extractor starts with every variant possible. Each extraction attempt either -returns the requested payload or returns a remainder whose type excludes that variant. +Extracting one payload leaves a question: what cases are still possible if the extraction misses? +A **partial variant** records that answer in its type. An enum's extractor begins with every case +possible, and each attempt either returns the requested payload or a remainder that excludes +that variant. -An unsuccessful attempt narrows the remainder type without losing the value. For `Shape`, failing -to extract `Circle` leaves only `Rectangle` possible. If every variant has been excluded, the -remainder is uninhabited: its type cannot contain a value. +For `Shape`, an attempt to extract `Circle` either returns its payload or leaves a remainder in +which only `Rectangle` is possible. The value survives a failed attempt, but its type now records +that it cannot be a circle. Continuing this process until every variant has been excluded leaves +an uninhabited remainder: a type that cannot contain a value. -Finalization requires an uninhabited remainder, so the compiler verifies that extraction covers -every variant. The final operation eliminates that impossible remainder without a wildcard arm or -`unreachable!()`. Adding an unhandled variant leaves a possible case and prevents finalization from -compiling. Borrowed and mutable extractor forms preserve the same tracking without consuming the -original enum. +To finish extraction, the remainder must be uninhabited. This requirement is how the compiler +checks coverage: an unhandled variant would leave a possible value and prevent finalization from +compiling. Once coverage is complete, the final operation can eliminate the impossible remainder +without a wildcard arm or `unreachable!()`. Borrowed and mutable extractors track the same cases +while keeping the original enum in place. ## One handler, many enums @@ -97,10 +101,10 @@ delegate_components! { } ``` -Suppose `Reading` contains `Temperature(u64)` and `Label(String)`, while `ExtendedReading` also -contains `Flag(bool)`. The same wiring handles both enums because every payload implements `Display`. -The handler ignores the variant tag and formats its value. An added payload without `Display` would -make this wiring fail to satisfy the enum's computation. +For example, `Reading` might contain `Temperature(u64)` and `Label(String)`, while +`ExtendedReading` adds `Flag(bool)`. Because all those payloads implement `Display`, both enums +can use this wiring. `FieldToString` ignores the variant tag and formats whichever value it +receives. A new payload without `Display` would instead leave the enum's computation unsatisfied. Separate providers can supply different behavior for different payloads. In the **extensible visitor pattern**, those providers remain independent of the full enum, and a dispatcher routes the @@ -108,9 +112,10 @@ current variant to its handler. [Dispatching](./dispatching.md) explains how the ## Converting enums that share variants {#enums-that-share-variants-convert-for-free} -Structural casts convert compatible enums without a handwritten conversion implementation. They -match variant names and payload types; sharing names alone is insufficient. The generated code -selects the current variant and reconstructs it in the target enum at runtime. +The same structural representation supports conversions between compatible enums. A cast matches +both the variant name and its payload type, so sharing a name alone is insufficient. At runtime, +the generated code identifies the current variant and reconstructs it in the target enum, without +a handwritten conversion implementation. Widening always succeeds when the target supports every source variant with the same payload type. For the `Reading` and `ExtendedReading` types above: @@ -126,9 +131,10 @@ target value on success or an extraction remainder on failure: let narrow: Result = wide.downcast(PhantomData::); ``` -`ExtendedReading::Label` can become `Reading::Label`, but `ExtendedReading::Flag` cannot become a -`Reading`. The remainder preserves the unmatched value, and `CanDowncastFields` can try it against -another target. Import the cast traits from `cgp::core::field::impls` when using these methods. +A `Label` value can pass from `ExtendedReading` to `Reading`, because both contain that case. +A `Flag` cannot, so narrowing returns its value in the extraction remainder instead. The remainder +can then be tried against another target with `CanDowncastFields`. These cast methods require +imports from `cgp::core::field::impls`. A provider can also construct a small local enum and widen it into a compatible application enum. The provider then needs to know only the variants it produces, while the application chooses the @@ -136,18 +142,18 @@ complete result type. ## What it costs -The full construction and extraction derives require one unnamed payload or no fields per variant. -A richer case must wrap its fields in a payload type, such as `Circle(Circle)` instead of -`Circle { radius: u64 }`. A variant with no fields carries the payload `Nil`, which has a cost of -its own: a handler that sees only payloads sees every such variant as the same `Nil`, so telling -them apart needs a handler that also receives the variant's name. +Generic construction and extraction also constrain how variants are declared: the full derives +accept one unnamed payload or no fields. A richer case must collect its fields in a payload type, +as in `Circle(Circle)` rather than `Circle { radius: u64 }`. A fieldless variant uses `Nil` as its +payload. Because every fieldless variant has that same payload type, a handler needs the variant's +name as well as its payload to distinguish them. [`#[derive(HasFields)]`](/docs/reference/derives/derive_has_fields) can describe all variant shapes, but that structural description alone does not supply generic constructors or extractors. -An enum must implement the traits used by the generic operation. A foreign enum without them is -not automatically available to the dispatcher, and CGP does not permit adding variants to it. -A local enum with the required support can provide the extensible boundary and convert to other -representations where necessary. +These generic operations are available only where the enum implements the required traits. +A foreign enum without them cannot be dispatched automatically, nor can CGP add variants to its +definition. Where that boundary matters, a supported local enum can provide the extensible +representation and convert to other forms as needed. Unhandled variants can produce long trait errors. The diagnostic may name a missing payload-handler bound or a partial-variant type whose markers describe the remaining cases. This is less direct to diff --git a/docs/concepts/handlers.md b/docs/concepts/handlers.md index 8cfbb39e..1ce30f1c 100644 --- a/docs/concepts/handlers.md +++ b/docs/concepts/handlers.md @@ -5,28 +5,30 @@ sidebar_position: 11 # Handlers -CGP's handler components let a context select and compose computations through wiring. Separate -interfaces describe whether a computation is synchronous or async, returns a fallible result, and -consumes or borrows its input. This page explains those choices, the adapters between them, and how -providers form a pipeline. +CGP's handler components represent computations through a common input-and-output interface. +Because providers share that interface, a context can select individual computations or compose +them into a pipeline through wiring. The family has separate forms for synchronous and async work, +fallible results, and owned or borrowed inputs, so a simple computation needs only the requirements +its work calls for. ## Computation as something a context decides -Handler components provide a common interface for computations that a context can choose. -An application-specific component might expose `send_email` or `load_file`; handlers expose a -uniform input-and-output interface that generic combinators can connect. +An application-specific component gives a name to an operation, such as `send_email` or `load_file`. +A handler gives it a uniform computation interface instead, allowing generic combinators to +connect it to other computations. -An input-taking handler receives a context, a `Code` tag, and an `Input`, then produces an `Output`. -The context supplies dependencies and wiring. The tag identifies the computation, and the input -contains the value being processed. The provider selects `Output` through an associated type. +In that interface, an input-taking handler receives a context, a `Code` tag, and an `Input`. +The context supplies its dependencies and wiring, while the input carries the value being processed. +The provider chooses the resulting `Output` through an associated type. -The `Code` tag lets one context select several computations for the same input type. It is passed -as `PhantomData`, which carries type information without storing a `Code` value. A program -with only one computation can use `()` as its tag. +The tag matters when several computations accept the same input type: `Code` distinguishes them +so the context can select a provider for each. Passing it as `PhantomData` carries that type +information without storing a `Code` value. If there is only one computation, `()` can serve as the +tag. -Different interfaces keep unnecessary requirements out of simple computations. An addition provider -can return its output synchronously without requiring an error type or returning a future. Adapters -can expose that provider through a more general interface when composition requires it. +Not every computation needs the same execution or error behavior. Addition, for example, can +return synchronously without an error type or a future. When it needs to join a more general +pipeline, adapters can expose it through the interface that pipeline uses. ## Three axes, and the names that encode them @@ -40,10 +42,10 @@ callers the corresponding methods: | [`TryComputer`](/docs/reference/components/handler/try_computer) | `try_compute` | Synchronous | `Result` | | [`Handler`](/docs/reference/components/handler/handler) | `handle` | Async | `Result` | -Synchronous methods finish their work before returning; async methods return futures that perform -work when polled. Fallible interfaces use the context's -[abstract error type](./modular-error-handling.md). “Infallible” describes the interface's lack of an -error channel; it does not guarantee that the implementation cannot panic or perform side effects. +A synchronous method completes its work before it returns, while an async method returns a +future that does the work when polled. The fallible forms add an error channel using the context's +[abstract error type](./modular-error-handling.md). An infallible interface simply lacks that +channel; its implementation may still have side effects or panic. Input ownership supplies the other distinction. The base components take `Input` by value, while siblings such as `ComputerRef` and `HandlerRef` take `&Input`. This lets the interface express @@ -55,10 +57,10 @@ Producer adapters can expose that behavior through input-taking interfaces by ig ## Write the simplest suitable provider {#write-the-weakest-one-the-rest-come-free} -Promotion adapters let a provider support another computation interface without duplicating its -body. An infallible result can be wrapped in `Ok`, and synchronous work can be performed inside an -async method. These adaptations preserve the computation; wrapping blocking work in a future does -not make the work nonblocking. +The separate interfaces need not force a provider to repeat its body. Promotion adapters can +wrap an infallible output in `Ok`, or run synchronous work inside an async method. The computation +keeps its original behavior through those adaptations: in particular, putting blocking work in +a future does not make it nonblocking. `#[cgp_computer]` generates a provider and its promotion wiring from a function: @@ -88,9 +90,10 @@ fn checked_add(a: u64, b: u64) -> Result { error type matches `String`. Promotion does not automatically convert an arbitrary source error into another error type. -Borrowed interfaces require a compatible borrowed-input implementation. Promotion does not let a -provider consume an arbitrary value through a shared reference. Likewise, an async provider does -not gain a synchronous implementation merely by being placed in a promotion table. +These adaptations must respect ownership as well. A provider that consumes an arbitrary input +cannot run on a shared reference to it, so the borrowed interfaces need a compatible implementation. +The direction of execution also matters: placing an async provider in a promotion table cannot +give it a synchronous implementation. Choose the simplest interface that expresses the computation, then use the adapters supported by its signature. The function macros generate suitable promotion wiring; a manually implemented @@ -120,14 +123,15 @@ identified by `Tag` and combines it with the input. This `Add` is separate function-generated `Add` in the previous example. The pipeline computes `((5 * foo) + bar) * baz` when given input `5`. -`PipeHandlers` runs the listed providers from left to right. Each stage's output type must satisfy -the next stage's input requirements, and the final stage determines the pipeline's output. The -fallible forms stop on the first error; async forms await each stage in sequence. +To perform that calculation, `PipeHandlers` runs the listed providers from left to right, passing +each output to the next stage. Those types must fit the next stage's input requirements, and the +last stage supplies the pipeline's output. In fallible forms, an error ends the pipeline before +later stages run; in async forms, each stage is awaited before the next begins. -`ComposeHandlers` is the two-stage form: run `A`, then pass its result to `B`. `PipeHandlers` -constructs nested compositions from its provider list. `ReturnInput` passes its input through -unchanged, and the `Promote*` adapters connect compatible interfaces. The -[handler combinator reference](/docs/reference/providers/handler) describes their bounds. +For just two stages, `ComposeHandlers` runs `A` and gives its result to `B`. `PipeHandlers` +builds nested uses of that composition from its list. `ReturnInput` provides a stage that leaves +the value unchanged, while the `Promote*` adapters connect compatible computation interfaces. +Their requirements are described in the [handler combinator reference](/docs/reference/providers/handler). ## Many computations on one context @@ -148,28 +152,27 @@ delegate_components! { `ComputeNegated`. This table names a code tag followed by the input type for each entry, so the compiler can resolve the requested pair. -Dispatch on the input alone uses a generic first segment: `@ComputerComponent. Code.i64` -matches every code and selects by the input type. [Dispatching](./dispatching.md) uses that form to -route an enum and its payloads to different providers. A shorter or generic key covers every key it -matches, so that entry could not share a table with the two above, since it also covers -`@ComputerComponent.Doubled.i64`. The tag can also describe a larger program, as in -[type-level DSLs](./type-level-dsls.md). +If only the input should determine the computation, a generic first segment can match every code: +`@ComputerComponent. Code.i64`. [Dispatching](./dispatching.md) uses this form for an enum +and its payloads. Because that key also covers `@ComputerComponent.Doubled.i64`, it would overlap +the entries above and cannot appear beside them in the same table. Code tags can also carry more +structure, as the programs in [type-level DSLs](./type-level-dsls.md) show. ## What it costs -A handler call needs a type tag even when the application has only one computation. -`PhantomData::<()>` supplies it, but adds syntax compared with an ordinary function call. +Compared with an ordinary function call, even the smallest handler call needs a type tag. +`PhantomData::<()>` fills that role when there is only one computation, but the extra syntax remains. -The family introduces several component and adapter names. The execution, error, and ownership -choices explain their relationships, but reading a pipeline still requires knowing which -interfaces each stage supports. Start with the form the computation needs and consult the adapter -bounds when connecting it to another form. +Larger compositions also require familiarity with the component and adapter family. Execution, +error handling, and ownership explain the names, but a reader must still know which interface each +stage supports. Choosing the simplest form for each computation helps keep those requirements +visible when adapters connect the stages. -Type-level composition makes some failures harder to locate. A mismatched stage can produce a trait -error involving an associated `Output` type rather than a line in a function body. -[Provider checks](./check-traits.md) help isolate the incompatible stage. Runtime debugging remains -possible inside each provider's method body, although the wiring table itself is not executable -code where a breakpoint or log statement can be placed. +Connecting stages through types moves some errors away from the function body. A mismatch can +appear as a trait error involving an associated `Output`, so +[provider checks](./check-traits.md) help isolate the stage whose types do not fit. Once the program +runs, each provider's method body remains available for debugging. The wiring table only selects +those methods, however, so it supplies no executable location for a breakpoint or log statement. Async handler interfaces do not promise that their returned futures are `Send`. Spawning a task on an executor that requires `Send` needs an additional guarantee, described in diff --git a/docs/concepts/higher-order-providers.md b/docs/concepts/higher-order-providers.md index 222c0ec4..e0b771ea 100644 --- a/docs/concepts/higher-order-providers.md +++ b/docs/concepts/higher-order-providers.md @@ -6,15 +6,15 @@ sidebar_position: 7 # Higher-order providers A **higher-order provider** takes another provider as a type parameter and uses it to perform part -of its work. A wrapper can then reuse the same transformation with different inner implementations. -This page explains the inner-provider bound, composition before a context is chosen, and delegation -back to the context through `UseContext`. +of its work. This separates a reusable transformation, such as scaling a result, from the inner +implementation that produces the result. Wiring can then combine the same wrapper with different +inner providers, while both operate on the same context. ## Choosing is not the only thing you can do with a provider -A provider parameter separates a reusable transformation from the calculation it transforms. -For example, scaling an area requires multiplying a base area by a scale factor squared. The -scaling logic can accept any provider that calculates the base area: +Scaling an area illustrates what a wrapper can share. Whatever calculation produces the base area, +the scaling step multiplies it by the scale factor squared. Giving that step a provider parameter +lets it reuse the same body with different base calculations: ```rust #[cgp_impl(new ScaledArea)] @@ -27,9 +27,10 @@ impl AreaCalculator { } ``` -`ScaledArea` requires `Inner` to implement `AreaCalculator` for the same context. -It passes that context to `Inner::area`, then applies the `scale` value read from the context's -field. The wrapper supplies the scaling logic; its type parameter selects the base calculation. +Inside `ScaledArea`, the call to `Inner::area(self)` calculates the base area using the +same context that the wrapper received. The wrapper then reads `scale` from that context and +applies the scaling. Its bound on `Inner` ensures that the selected provider can perform the base +calculation for this context. Wiring chooses the combination for each context. A rectangle and a circle can reuse the wrapper with different inner providers: @@ -39,13 +40,13 @@ delegate_components! { ScaledRectangle { AreaCalculatorComponent: ScaledArea } } ``` -Here `ScaledRectangle` and `ScaledCircle` hold the shape data and the scale factor. Each must -satisfy both the wrapper's field requirement and its selected inner provider's requirements. -`RectangleArea` needs the rectangle's dimensions, while `CircleArea` needs the circle's radius. +Both wired types carry their shape data and a scale factor. They must satisfy the scaling wrapper's +field requirement as well as the inner calculation's requirements: dimensions for `RectangleArea`, +or a radius for `CircleArea`. The wrapper does not need to know which of those calculations it uses. -Provider composition uses types rather than stored provider values. The compiler resolves the -inner call statically, without a runtime provider lookup. The selected methods still execute their -calculations; inlining and other optimizations determine the final machine code. +All of these choices are expressed through types, so the program stores no inner provider value +and performs no runtime provider lookup. The calculations themselves still run as ordinary method +calls, with their final machine code depending on inlining and other compiler optimizations. ## The extra ``, and the attribute that fills it in @@ -66,14 +67,15 @@ where } ``` -[`#[use_provider]`](/docs/reference/attributes/use_provider) generates that bound from the shorter -`Inner: AreaCalculator` form in the first example. It inserts the context argument and adds the -requirement to the implementation's `where` clause. Prefer this form when declaring an inner -provider dependency. +The first example uses [`#[use_provider]`](/docs/reference/attributes/use_provider) to write the +same requirement more briefly. Given `Inner: AreaCalculator`, the attribute inserts the context +argument and adds the completed bound to the implementation's `where` clause. This is the preferred +form for declaring an inner-provider dependency. -The attribute changes bounds, not calls. `Inner::area(self)` invokes the selected inner provider -with the context passed explicitly. A call to `self.area()` would instead use the context's consumer -trait implementation, which may route back to the wrapper rather than to `Inner`. +With that bound in place, the method still calls `Inner::area(self)` explicitly. The attribute +supplies the requirement for that call without rewriting the call itself. Using `self.area()` +would ask the context's consumer trait for an implementation, which may lead back to the wrapper +rather than to `Inner`. ## Composition without a context to name @@ -83,15 +85,14 @@ A type alias can name a provider composition before any context uses it: pub type ScaledScaledRectangleArea = ScaledArea>; ``` -The provider structs carry their dependencies on their trait implementations, so this alias does -not need to repeat those bounds. It names a composition that can be published, reused, and wrapped -again without selecting a context or proving that a particular context satisfies it. +This alias can exist without bounds because the requirements belong to the providers' trait +implementations, rather than their struct declarations. A library can therefore give the composition +a name, publish it, and wrap it again before any application chooses a context for it. -The requirements are checked when code uses the composition or explicitly checks it for a context. -A wiring entry alone does not prove they hold. For this alias, the context needs the dimensions -required by `RectangleArea` and the `scale` field used by both wrappers. Both layers read the same -scale value, so nesting them applies its square twice. For base area `12` and scale `2`, the result -is `192`. +Naming the composition does not prove that a context can use it, and neither does a wiring entry +alone. That proof is required at a use or an explicit check. Here it requires the dimensions read +by `RectangleArea` and the `scale` field read by both wrappers. Because both layers read the same +scale, they apply its square twice: a base area of `12` with scale `2` becomes `192`. ## Falling back to what the context already decided @@ -99,10 +100,10 @@ is `192`. consumer-trait implementation. A default type parameter makes that the wrapper's behavior unless the wiring names another provider. -Summing areas illustrates a useful default because the collection and its elements need different -implementations. In this example, `ShapeAreaCalculator` calculates the area of a -separate `Shape` value. The context represents an application that chooses how to measure each -shape, rather than the shape itself: +A collection provides a useful case for this default: calculating its total area can ask the +context to measure each element. Here the context represents an application, and the shapes are +separate values, unlike the shape contexts in the scaling example. The provider trait +`ShapeAreaCalculator` expresses this separation: ```rust pub struct SumAreas(pub PhantomData); @@ -116,9 +117,9 @@ impl ShapeAreaCalculator> { } ``` -`SumAreas` means `SumAreas` when its type argument is omitted. The wrapper asks the -context to calculate each element's area, then adds the results. An application can select a -rectangle provider and reuse the summing provider for vectors: +Omitting the argument makes `SumAreas` stand for `SumAreas`. Each iteration then asks +the context for the element's area before adding it to the total. Wiring can select the rectangle +calculation once and use the summing provider for vectors: ```rust delegate_components! { @@ -131,14 +132,14 @@ delegate_components! { } ``` -`open ShapeAreaCalculatorComponent;` enables provider selection by the component's shape parameter. -A call for `Vec` selects `SumAreas`. Each inner call then asks for the `Rectangle` -trait and reaches `RectangleArea`. The inner lookup is different from the collection lookup, -so it has an independent implementation to resolve to. +With `open ShapeAreaCalculatorComponent;`, the shape parameter determines the provider. A request +for `Vec` reaches `SumAreas`, whose inner requests are for `Rectangle` and therefore +reach `RectangleArea`. The collection calculation can use `UseContext` safely here because each +inner lookup asks for a different trait instance from the one being computed. -An explicit `SumAreas` uses that provider directly for each element, bypassing -the context's choice for that inner step. It still passes the same context, which must satisfy -`AnotherCalculator`'s requirements. +To choose a different element calculation for this sum alone, the table can name +`SumAreas`. That inner step calls `AnotherCalculator` directly, while continuing +to pass the original context. The context must therefore meet that provider's requirements too. Declare the provider struct explicitly to give its parameter the `UseContext` default. The `#[cgp_impl(SumAreas)]` block implements that existing struct; the `new` form declares a @@ -162,9 +163,10 @@ where } ``` -`GetName` requires the context to supply a `String` field identified by `Tag`. It does not -require `Tag` to implement a provider trait or invoke it as a provider. By contrast, `ScaledArea` -both constrains `Inner` with a provider-trait bound and calls it for the base calculation. +Here `Tag` identifies the `String` field the context must supply. The getter uses it to select +data, without calling it or requiring a provider-trait implementation. `ScaledArea` uses its +parameter differently: `Inner` supplies a calculation, so the wrapper both constrains it with a +provider-trait bound and invokes it. ## What it costs @@ -172,19 +174,20 @@ An inner-provider parameter adds a choice to the API and a bound to the implemen one transformation needs to work with independently selected implementations. A fixed implementation with nothing to vary does not benefit from an extra provider parameter. -`UseContext` can create a resolution cycle if the inner request selects the same wrapper again. -For example, a wrapper wired for a component cannot use that same component as its only base -implementation. The summing example avoids this by requesting the element trait from the -collection provider. Ensure that the inner lookup resolves to an independently available implementation. +The default needs care when an inner request could return to the same wrapper. If the wrapper +asks for the very component instance being resolved, `UseContext` creates a cycle rather than a +base calculation. The sum avoids this because it requests element calculations from a collection +calculation. Other wrappers likewise need an independently available inner implementation. -A nested composition can make failures harder to locate. An error on `ScaledArea` -may not immediately distinguish the scaling requirement from the rectangle requirements. -The [`#[check_providers]`](/docs/reference/macros/check_components) form gives each provider a -separate assertion against the same context, helping identify which layer lacks a dependency. +A failed requirement inside `ScaledArea` can also be difficult to assign to the +right layer. Checking each provider separately against the context with +[`#[check_providers]`](/docs/reference/macros/check_components) helps distinguish a missing scaling +dependency from missing rectangle dimensions. -Deeper compositions add trait-resolution work, especially when instantiated for many contexts. -They also add types and delegation steps for a reader to follow. The explicit `Inner::area(self)` -call makes the inner choice visible, but requires familiarity with provider-style calls. +As compositions grow deeper, both the compiler and the reader have more work to follow. Rust must +resolve the nested bounds for each context that uses them, while a reader traces the provider types +and their delegation steps. The explicit `Inner::area(self)` call helps show the inner choice, once +the reader is familiar with provider-style calls. ## Where to go next diff --git a/docs/concepts/index.md b/docs/concepts/index.md index 9e91caa2..9ccaa54b 100644 --- a/docs/concepts/index.md +++ b/docs/concepts/index.md @@ -5,13 +5,15 @@ sidebar_position: 0 # Concepts -CGP lets a type choose reusable trait implementations through compile-time wiring. These pages -explain why that design works, what you can build with it, and when its costs outweigh the benefits. -They assume familiarity with Rust traits and generic bounds; you can read them without running code. +CGP connects reusable trait implementations to the types that use them through compile-time wiring. +Understanding that connection explains how providers obtain dependencies, how contexts choose shared +types and values, and how implementations compose into larger operations. These pages develop those +ideas alongside their costs. You can read them without running code, with familiarity with Rust +traits and generic bounds as a starting point. -The [tutorials](/docs/tutorials/hello) introduce CGP by building working programs. The -[reference](/docs/reference/) specifies individual constructs and their syntax. Concepts connects -those constructs to the problems they solve, with examples, tradeoffs, and links to both. +If you want to learn by building a program, the [tutorials](/docs/tutorials/hello) introduce the +same ideas through working code. Once you need the syntax or precise behavior of a construct, the +[reference](/docs/reference/) supplies that detail. ## Where to start @@ -24,16 +26,18 @@ Choose an entry point for the question you want answered: - **Should I use CGP?** [Modularity Hierarchy](./modularity-hierarchy.md) compares ordinary traits, blanket implementations, and wired components so you can choose what your problem requires. -If traits and generic bounds are unfamiliar, start with the [tutorials](/docs/tutorials/hello). -They introduce the ideas through working code and provide the background these explanations assume. +If you need more background on traits or generic bounds, the [tutorials](/docs/tutorials/hello) +introduce them in working programs before returning to these explanations. ## The ideas, grouped -The sidebar follows a suggested reading order. The groups below let you find related ideas directly. +The sidebar offers a reading order from the trait model to its applications. The groups below +bring related pages together, so you can also follow a particular question across the section. ### Traits and implementation choices -These pages explain the problem CGP addresses and the mechanism it uses: +The trait pages begin with Rust's rules for choosing implementations, then explain how CGP builds +on them and where that additional structure is useful: - [Bypassing coherence](./coherence.md): Why Rust restricts overlapping implementations and how separate provider types let alternative implementations coexist. @@ -43,18 +47,19 @@ These pages explain the problem CGP addresses and the mechanism it uses: ### Dependencies -A provider can state requirements that its callers do not need to carry. These pages explain the -forms those requirements take: +Once a caller depends on a consumer trait, the chosen provider can have further requirements of +its own. The dependency pages explain how those requirements reach the context as traits, values, +and types: - [Impl-side dependencies](./impl-side-dependencies.md): Traits, values, and types required by an - implementation - without appearing in its public interface. + implementation without appearing in its public interface. - [Implicit arguments](./implicit-arguments.md): Values read from context fields. - [Abstract types](./abstract-types.md): Types selected by a context and shared by generic code. ### Composition and wiring -These pages explain how to combine implementations, share wiring, and verify the result: +As implementations grow, wiring needs to express their relationships and remain practical to +maintain. These pages explain composition, shared tables, and checks on the resulting choices: - [Checking your wiring](./check-traits.md): Why wiring errors can remain undetected until use, and how compile-time checks report missing requirements near the wiring. @@ -64,7 +69,8 @@ These pages explain how to combine implementations, share wiring, and verify the ### Applications of the design -These pages apply the same component model to errors, computations, and data: +The same separation between interfaces, providers, and wiring supports more specialized designs. +These pages follow it into errors, computations, and generic operations on data: - [Modular error handling](./modular-error-handling.md): Choosing an error type and the providers that construct errors and attach detail. diff --git a/docs/concepts/modularity-hierarchy.md b/docs/concepts/modularity-hierarchy.md index c15ae458..45d9f357 100644 --- a/docs/concepts/modularity-hierarchy.md +++ b/docs/concepts/modularity-hierarchy.md @@ -5,14 +5,14 @@ sidebar_position: 18 # Modularity Hierarchy -Choose the least complex implementation model that supports the choices your program needs. -Rust traits and CGP components offer a progression from one shared implementation to providers -selected independently by context, target type, and enclosing provider. Each additional choice -requires more structure. +The modularity hierarchy describes how implementation choices grow from a single shared body to +providers selected independently by context, target type, and enclosing provider. Each tier adds a +place where a program can make a choice, along with the structure needed to express it. The useful +tier is the least complex one that supports the variation your program actually needs. -This page follows encoding through the tiers, then gives a decision guide for choosing among them -and ordinary Rust alternatives. The examples are fragments: imports from `cgp::prelude::*`, context -structs, and some provider bodies are omitted to keep the implementation choices visible. +Encoding illustrates how those choices differ. The examples below omit imports from +`cgp::prelude::*`, context structs, and some provider bodies so the implementation choices remain +visible. The decision guide that follows compares those choices with ordinary Rust alternatives. ## The tiers at a glance @@ -26,9 +26,10 @@ The tiers differ in where a program can select an implementation: | **4** | One provider per target type in each context | A parameter-targeted component and `open` | The interface must separate context from target | | **5** | An inner provider chosen by an enclosing provider | A [higher-order provider](/docs/reference/glossary#higher-order-provider) | The enclosing provider depends on the inner provider interface | -All tiers obey Rust's [coherence](/docs/reference/glossary#coherence) rules. CGP permits reusable alternatives by placing their -implementations on distinct provider types, then using wiring to select one unambiguously. -Tier 5 adds a local composition choice rather than relaxing another coherence rule. +These choices all work within Rust's [coherence](/docs/reference/glossary#coherence) rules. +CGP places alternative implementations on distinct provider types, allowing wiring to select one +unambiguously. The final tier extends that selection into a provider composition, where a wrapper +can choose an inner provider independently of the context's general choice. ## Tier 1: one implementation for matching types @@ -47,13 +48,13 @@ impl> CanEncode for Value { } ``` -Every matching type receives this implementation. A second implementation for a type covered by -that blanket would overlap it and be rejected. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) -expresses the same arrangement from a function and keeps the implementation's bounds off the -consumer interface. +Every type satisfying the bound receives this body, so another implementation for a covered type +would overlap it and be rejected. That is the constraint of this tier: matching types share the +logic. [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) can generate this arrangement from a function, +keeping its implementation bounds off the consumer interface. -Use this tier when matching types should share one implementation. It requires neither named -providers nor wiring. +When that shared body is the desired behavior, this tier needs nothing more. Provider names and +wiring become useful only when the program needs a further choice. ## Tier 2: one implementation per type @@ -78,9 +79,9 @@ impl CanEncode for Vec { } ``` -`u32` encodes as decimal text, while `Vec` copies its bytes. The choice is shared wherever -that trait is used for that type. Blanket implementations remain possible where they do not -overlap other impls; coherence prevents ambiguous combinations. +Now `u32` uses decimal text and `Vec` copies its bytes. Each choice follows its type wherever +this trait is used. A blanket implementation could still cover other types, provided it does not +overlap these implementations or any others. This tier fits behavior that varies by type but does not need an independent choice per application. Rust's [orphan rules](/docs/reference/glossary#orphan-rule) also determine which crate may supply an implementation. @@ -106,9 +107,10 @@ impl SelfEncoder { } ``` -`EncodeSelfAsText` requires the context to implement `Display`. A separate `EncodeSelfAsBytes` -provider can require `AsRef<[u8]>`, even if some types satisfy both bounds. Wiring selects the -provider for a concrete type: +The `EncodeSelfAsText` provider can serve any context implementing `Display`. A separate +`EncodeSelfAsBytes` can support `AsRef<[u8]>` contexts, even when some contexts satisfy both bounds, +because the two implementations belong to distinct provider types. Wiring then chooses which one +a concrete type will use: ```rust delegate_components! { @@ -127,9 +129,9 @@ A table entry alone does not force Rust to verify all of the selected provider's ### Value contexts and application contexts -The wired type can represent either the value being operated on or an application environment. -That distinction changes what “one choice per type” means without necessarily changing the method -signature. +In this example the wired type is the value being encoded. But a type can also represent an +application environment, carrying dependencies and implementation choices for its operations. +Both arrangements fit tier 3, even though “one choice per type” serves a different purpose in each. In the **value-context** arrangement, `Self` is the data, as `u32` is in the encoding example. The provider operates on that value, and wiring selects one provider for it. This arrangement suits @@ -154,13 +156,13 @@ delegate_components! { App { EmailSenderComponent: SendViaSmtp } } delegate_components! { TestApp { EmailSenderComponent: RecordEmails } } ``` -The provider bodies are elided here. An SMTP provider would require connection settings or a client; -a recording provider would require storage for captured messages. `App` and `TestApp` supply those -dependencies and select different providers for the same consumer trait. +The omitted SMTP body would need connection settings or a client, while the recording body would +need storage for captured messages. `App` and `TestApp` supply the appropriate dependencies. Their +separate wiring lets callers use the same consumer trait in either environment. -Application contexts make independent choices possible without parameterizing the trait over a -target value. Both contexts belong to the application, so it can define and wire them separately. -This is a common CGP arrangement for services, test environments, and application operations. +The application owns both context types, so it can wire them independently even though the +consumer trait has no target parameter. This makes tier 3 sufficient for many service operations +and test environments: the selected behavior belongs to the application context itself. Components may group methods, associated types, and consts, just as ordinary traits do. The examples use one method to isolate provider selection; the appropriate grouping depends on which items a @@ -201,10 +203,10 @@ delegate_components! { owning either context can supply that wiring even when it owns neither the component nor `String`. Ownership of the context satisfies Rust's rules for the wiring implementation. -The extra choice requires a compatible interface. An existing self-targeted trait cannot acquire -this context-and-target separation merely by changing wiring. The context must also supply entries -covering the target types it uses, although generic entries can cover families of types. -Use this tier when target behavior must vary independently between contexts. +Making the value a parameter is what enables these independent application choices. A self-targeted +trait cannot gain that separation through wiring alone, because its interface still treats the +context as the value. With the parameter-targeted interface, each context must cover the target +types it uses, although generic entries can supply providers for whole families of targets. ## Tier 5: an inner provider chosen locally @@ -241,9 +243,9 @@ delegate_components! { `EncodeAsText`. `Vec>` explicitly selects `EncodeAsHex` for each inner byte vector, regardless of how the context encodes `Vec` elsewhere. -The local override lets a collection or wrapper impose a specific inner interpretation while -other operations retain the context's general choice. It also adds another provider parameter and -interface dependency. Use it when that local choice is part of the operation's design. +Here the collection specifies how its elements should be interpreted while other operations keep +the context's general choice. Expressing that local decision requires another provider parameter +and an interface dependency, so it earns its place when the wrapper needs that independent choice. ## Choosing a tier @@ -261,14 +263,15 @@ another type. These arrangements answer different needs: | Behavior for a target type that differs by application | Environmental context, parameter-targeted component (tier 4) | One choice per context and target type | | A wrapper needs a particular inner implementation | Higher-order provider (tier 5) | A choice within that provider composition | -An application-level operation does not need a target parameter merely to support testing. -Separate `App` and `TestApp` contexts can select different email providers at tier 3. A target -parameter becomes useful when the operation acts on types whose treatment must vary independently -of those types' own trait implementations. +Testing alone does not require moving to tier 4. At tier 3, `App` and `TestApp` can already select +different providers for an operation such as sending email. A target parameter earns its place +when the operation acts on a separate value whose treatment must vary between applications, +independently of that value's own trait implementations. -Shared wiring is a separate concern from the tier. [Aggregate providers](./aggregate-providers.md) -and [namespaces](./namespaces.md) group repeated selections; they become useful when the shared -table is worth maintaining as a unit. +Whichever tier supplies the needed choices, several contexts may repeat part of their wiring. +[Aggregate providers](./aggregate-providers.md) and [namespaces](./namespaces.md) can collect those +selections once the shared table is useful to maintain as a unit. Sharing a table does not itself +require moving to another tier. ## Comparing ordinary alternatives @@ -299,10 +302,10 @@ An operation with one suitable implementation does not need provider selection. A plain impl, blanket impl, or [`#[cgp_fn]`](/docs/reference/macros/cgp_fn) can express it directly. Likewise, a small closed enum usually needs only a `match` rather than generic variant dispatch. -Some APIs depend on one consistent interpretation of a value. Ordering within a map, for example, -must remain consistent across its operations. Independent provider choices are useful only when -the surrounding design preserves such invariants; they are not a reason to replace a coherent -trait that already expresses the required contract. +For some APIs, variation would weaken a contract the program relies on. A map, for example, +needs a consistent ordering across its operations. Independent provider choices help only when +the surrounding design preserves that invariant, so a coherent trait that already expresses it +may remain the better fit. ## Evaluating a single-context application @@ -322,14 +325,14 @@ If these needs are absent, use a simpler implementation form. ## Representing configuration choices -A separate handwritten context is not required for every combination of settings. -A generic context definition can share structure across backend types, though each concrete -instantiation remains a distinct Rust type. Enums and trait objects can represent choices made -from runtime configuration. +Configuration does not require a handwritten context for every combination of settings. +A generic context can share its structure across backend types, although each concrete instantiation +is still a distinct Rust type. If a choice comes from runtime configuration instead, an enum or +trait object can represent it inside the context. -Use distinct context types where the distinction should be checked statically. For example, -separating a test client from a production client can prevent accidental substitution. Keep other -choices as fields or generic parameters when that gives the program the flexibility it needs. +A distinct context type is useful when Rust should enforce the distinction, such as preventing +a test client from being substituted for a production client. Other settings can stay in fields +or generic parameters, according to how the application needs to choose and share them. Context-generic libraries can also leave backend representation to downstream applications. When providers depend on context traits rather than a fixed backend enum, a downstream crate can @@ -338,9 +341,10 @@ that context satisfies without changing the upstream enum. ## What it costs -Provider selection adds declarations and another step when reading a call. A component generates -consumer and provider traits plus a wiring key; the context's table identifies the provider that -runs. Wrappers and namespaces can add further steps to that trace even though selection is static. +Reading a wired method call requires finding the provider in the context's table as well as the +consumer trait. The component generates that trait, its provider counterpart, and a wiring key; +wrappers and namespaces can add more tables or types to follow. Those steps disappear from runtime +selection, but remain part of understanding the code. Wiring failures can produce verbose diagnostics involving generated types and transitive bounds. [`check_components!`](/docs/reference/macros/check_components) forces selected requirements to be @@ -348,9 +352,10 @@ checked near the wiring. `cargo cgp check` leads with the root cause for the cla and the tool does not yet reshape every class. The [cargo-cgp documentation](/docs/cargo-cgp/) explains the checking workflow. -Macros, trait resolution, and [monomorphization](/docs/reference/glossary#monomorphization) add compile-time work. The effect depends on the -program and should be measured for the codebase being evaluated. Static dispatch removes runtime -provider lookup, but that does not mean every added compilation cost replaces a runtime cost. +The compiler does additional work through macros, trait resolution, and +[monomorphization](/docs/reference/glossary#monomorphization). Its effect needs measuring in the +program being evaluated. Although static dispatch removes runtime provider lookup, compilation +costs do not necessarily correspond to runtime work that the program would otherwise have done. The vocabulary and generated code take time to learn. CGP's [agent skill](https://github.com/contextgeneric/cgp-skills) can help a coding assistant explain diff --git a/docs/concepts/monadic-handlers.md b/docs/concepts/monadic-handlers.md index dda7855b..0af06a37 100644 --- a/docs/concepts/monadic-handlers.md +++ b/docs/concepts/monadic-handlers.md @@ -5,16 +5,20 @@ sidebar_position: 12 # Monadic handlers -Monadic handlers let a pipeline choose whether to continue based on each step's result. A pipeline -can stop at the first error, stop at the first success, or pass every output onward. This page -builds on [handlers](./handlers.md) to explain those choices, how CGP composes them, and when an -ordinary function is simpler. +Monadic handlers separate a pipeline's computations from the rule that decides whether another +step should run. The same composition machinery can stop at the first error, stop at the first +success, or pass every output onward. A monad supplies that continuation rule, while the providers +supply the work performed at each step. + +Ordinary [handler composition](./handlers.md) already connects outputs to inputs. Monadic +composition extends that connection to cases where the next step needs a value inside a result, +or where one branch should end the pipeline. ## When direct composition does not fit -Direct composition through `Computer` passes each step's entire output to the next step. -That does not fit a chain whose steps return `Result` but accept only `T`. Consider this -computer, defined with imports from `cgp::prelude::*`: +When computers compose directly, one step passes its whole output to the next. That works only if +the next computer accepts that type. A fallible increment makes the difficulty visible; this +fragment assumes imports from `cgp::prelude::*`: ```rust #[cgp_computer] @@ -23,21 +27,21 @@ pub fn increment(value: u8) -> Result { } ``` -`Increment` accepts a `u8` and produces a `Result`. Directly composing two copies -through `Computer` fails because the second expects a `u8`, not the complete `Result`. The chain -needs a rule that passes the value inside `Ok` onward and returns an `Err` immediately. +The generated `Increment` computer takes a `u8` but returns `Result`. If a second +copy receives that whole result, its input type does not fit. To connect the two, the pipeline needs +to unpack an `Ok` and continue with its `u8`, or return an `Err` before running the next increment. -The handler interface matters here. Ordinary composition through `TryComputer` or `Handler` -already propagates its outer error with `?`. Monadic composition makes the continuation rule a -separate choice, including when `Result` is the output of a `Computer` or when success should end -the chain. +Composition through `TryComputer` or `Handler` already propagates the interface's outer error with +`?`, so this mismatch is specific to treating the result as a `Computer`'s output value. Monadic +composition lets the pipeline choose that continuation behavior separately. It can reproduce error +propagation here or choose a different rule, such as stopping when an attempt succeeds. ## Choosing the continuation rule -A **monad** describes how to compose computations through a surrounding type. In CGP's result-based -monads, it determines which branch supplies the next input, which branch ends the pipeline, and how -a value is placed into the result type. The identity monad supplies ordinary composition without a -result wrapper. +The continuation rule belongs to a **monad**, which describes how computations compose through a +surrounding type. For CGP's result-based monads, this includes which branch supplies the next input, +which branch stops the pipeline, and how a plain value enters the result type. The identity monad +uses the same idea for ordinary composition, with no result wrapper. `PipeMonadic` combines that choice with a type-level list of providers. This type fragment uses `PipeMonadic` from `cgp::extra::monad::providers` and `ErrMonadic` from @@ -47,10 +51,10 @@ result wrapper. PipeMonadic ``` -`ErrMonadic` passes each `Ok` value to the next `Increment` and stops on `Err`. Starting from `1` -produces `Ok(4)`. Starting from `253` reaches `254`, then `255`, then returns `Err("overflow")`. -Starting from `255` fails in the first step and skips the other two. This is the control flow of -successive `?` expressions, assembled from provider types. +With `ErrMonadic`, each `Ok` supplies the next `Increment` with its contained value, so starting +from `1` produces `Ok(4)`. Starting from `253` reaches `254`, then `255`, before the last increment +returns `Err("overflow")`. An input of `255` fails immediately and skips the remaining steps. +The provider types therefore assemble the same control flow as successive `?` expressions. ## The built-in monads @@ -62,18 +66,18 @@ Choose the marker according to which result should end the pipeline: | `OkMonadic` | The value inside `Err` | `Ok` | | `IdentMonadic` | The complete output | Every step continues | -`OkMonadic` supports a sequence of attempts where the first success wins. Each failed attempt must -return, in `Err`, the input the next attempt needs. For example, variant dispatch can pass the -unmatched remainder onward until one handler accepts it. +For a sequence of attempts, `OkMonadic` reverses the stopping rule: the first success ends the +search. A failed attempt returns the next step's input inside `Err`. Variant dispatch uses this to +pass an unmatched remainder from one attempt to another until a handler accepts it. -`IdentMonadic` lets a pipeline use the same composition interface without short-circuiting. -It forwards the whole output, so the next provider must accept that exact type. Using it with -`Increment` does not resolve the `Result`-versus-`u8` mismatch. +If every step should continue, `IdentMonadic` forwards the complete output without unpacking it. +This keeps the same composition machinery, but requires the next provider to accept that exact +output type. It therefore leaves the `Increment` input mismatch unresolved. -Monad transformers combine continuation rules for nested results. For -`Result, F>`, `OkMonadicTrans` stops on an outer `Err(F)` or an inner -`Ok(T)` and continues with the `E` inside `Ok(Err(E))`. Both result layers affect whether another -step runs; their nesting order determines how the output is interpreted. +When a computation has nested results, monad transformers let both layers participate in the +continuation decision. For `Result, F>`, `OkMonadicTrans` stops on an outer +`Err(F)` or an inner `Ok(T)`. Only `Ok(Err(E))` continues, supplying `E` to the next step. The order +of the nested rules matters because it determines how each result layer is interpreted. ## A pipeline is an ordinary provider @@ -88,14 +92,14 @@ delegate_components! { } ``` -Callers use the ordinary `CanCompute` interface. For this example, the code tag is `()` and the -input is `u8`; the output is `Result`. The context's wiring selects the pipeline, -and its callers do not need a separate monadic interface. +Once wired, the pipeline is available through the ordinary `CanCompute` interface. A caller +supplies the `()` code tag and a `u8`, then receives `Result` without needing to +name a monad. The context's table determines how those increments are composed. -Provider selection happens at compile time, while the increments and result branches execute when -the pipeline runs. The marker and provider list require neither runtime instances nor a runtime -lookup table. `PipeMonadic` also supports the async and fallible handler forms; those forms retain -their own execution and error behavior. +Rust selects the providers from their types at compile time, so the marker and list need no +runtime instances or lookup table. The increments and branches still execute when the pipeline +runs. The same `PipeMonadic` machinery supports async and fallible handler forms, retaining their +execution and error behavior. ## What it costs @@ -103,13 +107,15 @@ A fixed sequence of fallible operations is usually clearer as a function using ` composition is useful when contexts select different sequences or when reusable steps need a continuation rule such as stopping at the first success. -Pipeline errors can be difficult to locate. An incompatible stage can produce a trait-resolution -error involving associated output types and monad traits rather than identifying the stage directly. -Checking a short pipeline before adding more stages narrows the source of a mismatch. +Moving the continuation rule into types can make an incompatible stage harder to identify. +The error may involve associated outputs and monad traits without pointing directly to the stage +that does not fit. Checking a short pipeline before extending it narrows the possible source of a +mismatch. -Nested monads require readers to track each result layer separately. Use a transformer when those -layers express distinct decisions, and document which cases continue. The provider type alone may -not make that behavior obvious to a reader unfamiliar with the chosen transformer. +With nested monads, understanding a call also means following the decision at each result layer. +A transformer is useful when those layers represent distinct choices, but its provider type may +not explain them to a reader. Documenting exactly which cases continue makes that control flow +easier to follow. ## Where to go next diff --git a/docs/concepts/namespaces.md b/docs/concepts/namespaces.md index 066cbab8..ff5e861a 100644 --- a/docs/concepts/namespaces.md +++ b/docs/concepts/namespaces.md @@ -5,15 +5,16 @@ sidebar_position: 9 # Namespaces -Namespaces share wiring across contexts while leaving selected provider choices to each context. -They are useful when related contexts repeat large parts of the same table. This page explains -path-based routing, inherited bindings, and the rule that determines what can vary: a context can -fill an unbound path, but it cannot replace an inherited binding. +Namespaces give shared wiring a name that contexts can inherit. They organize component lookups +under paths, allowing a shared table to bind the choices its contexts have in common and leave other +destinations for each context to fill. The distinction matters: a context can fill an unbound path, +but it cannot replace an inherited binding. ## Repeated wiring obscures the differences -Separate wiring tables can repeat choices that are intended to stay together. These fragments -assume the named components, providers, and context types are defined, with CGP's prelude imported: +When production and test contexts differ in only a few choices, writing their tables separately +repeats the choices they share. These fragments assume the named components, providers, and +contexts are defined, with CGP's prelude imported: ```rust delegate_components! { @@ -33,14 +34,15 @@ delegate_components! { } ``` -Only the greeter differs, but each table repeats the shared farewell and announcer choices. -As the shared portion grows, maintaining the tables requires checking that those entries still -agree. A namespace gives the shared wiring a name that contexts can inherit. +Here the greeter changes, while the farewell and announcer entries must stay in agreement. +A larger shared table would leave more entries to keep synchronized. Giving those entries a +namespace lets both contexts inherit the common choices and state their differences separately. ## Lookups follow a path -A namespace can register a route for a component while leaving the provider at its destination -unspecified. This example registers the greeter under an application path: +For a context to make its own choice, the namespace needs to route a component lookup without +binding its final provider. Registering the greeter under an application path makes that distinction +visible: ```rust cgp_namespace! { new AppNamespace {} } @@ -65,13 +67,15 @@ delegate_components! { } ``` -The namespace supplies the route, and `App` supplies its destination binding. Rust resolves both -at compile time. The context's entry must not overlap an entry the namespace already binds; -joining a namespace does not give local entries priority over inherited ones. +The context entry completes the route declared by `AppNamespace`, and Rust resolves both parts +at compile time. This works because the destination was left unbound. Had the namespace already +bound it, adding a local entry would create an overlap; joining a namespace gives local entries +no priority over inherited ones. -Paths also let wiring redirect a group of related lookups. A shared prefix can route a subsystem -to another prefix, with the remaining path identifying its component and parameters. The -[`cgp_namespace!` reference](/docs/reference/macros/cgp_namespace) specifies that redirection syntax. +The route can also cover a group of components. Redirecting a shared prefix sends the subsystem's +lookups to another prefix, while the rest of each path still identifies the component and its +parameters. The [`cgp_namespace!` reference](/docs/reference/macros/cgp_namespace) gives the syntax +for these grouped redirections. ## Bind shared choices and leave varying paths open @@ -94,8 +98,9 @@ delegate_components! { App { namespace AppDefaults; @app.GreeterComponent: G delegate_components! { TestApp { namespace AppDefaults; @app.GreeterComponent: GreetQuietly } } ``` -Both contexts inherit `SayGoodbye`, and each states its own greeting choice. A library can publish -this shared configuration for applications to use without knowing those applications' context types. +The farewell choice now comes from `AppDefaults`, and only the greeter differs in the two context +tables. Because the shared configuration refers to components rather than particular application +types, a library can publish it for contexts that downstream applications define later. ## A bound entry cannot be overridden @@ -120,9 +125,9 @@ delegate_components! { } ``` -Rust rejects the overlapping implementations. Joining the namespace generates a forwarding -implementation for its keys, and the direct `GreeterComponent` entry would implement the same -lookup again. A child namespace redefining an inherited key has the same problem. +Joining this namespace already generates a forwarding implementation for `GreeterComponent`. +The local entry tries to implement the same lookup again, so Rust rejects the overlap. A child +namespace that redefines an inherited key runs into the same conflict. Keep configurable paths unbound in the shared base. Returning to the path-based example, each configuration can bind the open greeter path in its own child namespace: @@ -132,14 +137,16 @@ cgp_namespace! { new ProductionDefaults: AppDefaults { @app.GreeterComponent: Gr cgp_namespace! { new TestDefaults: AppDefaults { @app.GreeterComponent: GreetQuietly } } ``` -`ProductionDefaults` and `TestDefaults` both inherit the shared farewell choice and supply different -greeters. A context then joins the configuration it needs. Neither child replaces a parent binding. +Both children inherit the farewell choice, while each fills the greeter path that `AppDefaults` +left open. A context can then join the production or test configuration as appropriate. The shared +base remains consistent because each child adds a binding where the parent supplied only a route. ## Presets and per-type dispatch -A namespace can serve as a preset by grouping shared choices and exposing unbound paths for -configuration. Inheritance adds the remaining choices. The distinction between a fixed binding -and an open path determines which parts an application can customize. +This inherit-and-complete arrangement also gives namespaces their role as presets. A library can +bind a shared configuration while leaving paths open for the choices applications make. Child +namespaces fill those paths to produce more specific configurations, subject to the same rule +about inherited bindings. The `open` statement uses related path routing for a smaller task: selecting a provider for each type parameter of one component. This standalone fragment assumes an encoder component without a @@ -155,10 +162,10 @@ delegate_components! { } ``` -`open` roots the route at `EncoderComponent`, and the context supplies entries beneath that root. -It does not require a shared namespace. Once a component is registered through a namespace prefix, -its entries must use that full prefixed route instead; opening the same component at its bare name -does not reach them. +Here `open` starts the lookup path at `EncoderComponent`, and the following entry chooses the +provider for `String`. This uses path routing without requiring a shared namespace. If the +component has a namespace prefix, however, its lookups already follow that prefixed route. Entries +must use the full path, because opening its bare name does not reach them. ## What it costs @@ -166,14 +173,15 @@ Binding a shared key commits every joining context to that choice. If a later co different provider, the namespace design must expose an unbound destination for it. Changing that design can affect existing contexts, so decide which choices vary before publishing the shared table. -Inherited wiring takes more work to trace. An [aggregate provider](./aggregate-providers.md) -lets the context list which components it delegates to a bundle. A namespace can supply those -routes through its registration and parent chain, so finding the selected provider may require -reading several tables. +Inheritance also spreads the explanation of a lookup across tables. With an +[aggregate provider](./aggregate-providers.md), the context lists the components it delegates to the +bundle. With a namespace, registration and the parent chain can supply those routes, so a reader +may need to follow several tables to find the selected provider. -Path types can make diagnostics longer, and joining a namespace does not verify every inherited -component's dependencies. Use separate [`check_components!`](/docs/reference/macros/check_components) -assertions for the components a concrete context needs. +Tracing a failure can involve those paths too, making diagnostics longer. Joining the namespace +also leaves inherited dependencies unchecked until they are required. Separate +[`check_components!`](/docs/reference/macros/check_components) assertions bring the components a +concrete context needs into an explicit check. Small tables often remain clearer when written directly. Namespaces become useful when sharing a configuration or grouping routes reduces enough repetition to justify the inheritance and path diff --git a/docs/concepts/send-bounds.md b/docs/concepts/send-bounds.md index 17c6ba12..d3b63220 100644 --- a/docs/concepts/send-bounds.md +++ b/docs/concepts/send-bounds.md @@ -5,10 +5,11 @@ sidebar_position: 17 # Recovering `Send` bounds -A generic caller needs an explicit guarantee that an async method returns a `Send` future before -it can move that future between threads. CGP's `#[async_trait]` does not add that guarantee. -This page explains the trait-bound gap and a companion-trait workaround, including why it requires -forwarding implementations for concrete context and API pairs. +Recovering a `Send` bound lets generic code require a sendable future from an async interface that +leaves that guarantee open. CGP's `#[async_trait]` returns an unboxed future without promising +`Send`, so a caller cannot infer sendability from the consumer trait alone. A companion trait can +expose the stronger guarantee, with forwarding implementations that verify it for concrete context +and API pairs. ## What the async trait promises @@ -25,24 +26,25 @@ pub trait CanHandleApi { } ``` -The generated return type is `impl Future`. The rewrite adds neither -boxing nor allocation, and it does not promise that the future implements `Send`. A concrete -implementation may return a `Send` future, but the generic bound `App: CanHandleApi` alone -does not establish that fact. +After expansion, `handle_api` returns `impl Future`. The rewrite needs +neither boxing nor allocation, but its signature gives callers no `Send` guarantee. Even if a +particular implementation returns a sendable future, generic code with only +`App: CanHandleApi` cannot rely on that property. -The missing guarantee comes from the trait signature. Opaque return types can explicitly carry -`+ Send`; this particular signature leaves that requirement open so implementations can also use -futures that are not sendable. +Leaving `Send` out of the signature permits implementations whose futures cannot move between +threads. Others may return sendable futures, but generic callers have to support either case. +An explicit `+ Send` in the opaque return type would make the stronger promise available to them. ## Why spawning needs a stronger bound -Spawning APIs may require both the future and its output to be sendable. For example, -[`tokio::spawn`](https://docs.rs/tokio/latest/tokio/task/fn.spawn.html) requires both to be -`Send + 'static`. An async task that awaits `handle_api` needs to satisfy those bounds as a whole. +The distinction becomes relevant when a task must move between threads. For example, +[`tokio::spawn`](https://docs.rs/tokio/latest/tokio/task/fn.spawn.html) requires both the spawned +future and its output to be `Send + 'static`. If that task awaits `handle_api`, the awaited future +must allow the surrounding task to satisfy those requirements. -A generic caller cannot infer the awaited future's `Send` implementation from -`App: CanHandleApi`. Giving `App` itself a `Send` bound does not constrain every future its -methods return. +Adding `App: Send` does not close this gap. That bound allows the application value to move between +threads, but says nothing about the futures its methods return. The caller needs a requirement on +`handle_api`'s return type itself. Return Type Notation would let a caller state the missing requirement directly: @@ -75,9 +77,9 @@ where } ``` -`CanHandleApiSend` is an ordinary trait that adds a stronger method signature. It inherits the -original response type and needs neither a component key nor provider wiring. A generic caller can -require it with these bounds: +The resulting `CanHandleApiSend` is an ordinary trait, so it needs no component key or provider +wiring. By extending the original trait, it reuses its response type while adding a method whose +return type explicitly promises `Send`. Generic callers can request this stronger interface: ```rust where @@ -85,19 +87,22 @@ where App::Response: Send, ``` -The caller must use `handle_api_send` to obtain the advertised future. The companion trait does not -change the signature of `handle_api`. Its response bound is repeated here because a bound on an -associated type in a trait's `where` clause must also be established at the generic use site. +With these bounds, the caller can obtain a future known to be `Send` by calling `handle_api_send`. +Calling the original `handle_api` still gives only the original guarantee. The response bound also +appears at this use site because Rust requires the caller to establish the associated-type bound +from the companion trait's `where` clause. -This trait addresses the future's sendability, not every condition for spawning. The surrounding -task must still satisfy the executor's lifetime and output requirements. A future borrowing a local -`app` is not automatically `'static` merely because it implements `Send`. +The companion method supplies the missing sendability promise, but the task still needs to meet +the executor's other requirements. For example, a future borrowing a local `app` can be `Send` +without being `'static`. The surrounding task's lifetime and output therefore need attention +independently of this bound. ## Why forwarding implementations need concrete types -A blanket forwarding implementation cannot prove `Send` from the original trait bound alone. -Its body would await `self.handle_api(api)`, whose future the original signature does not guarantee -to be sendable. Wrapping that call in another async block preserves the same missing requirement. +It might seem possible to implement this companion trait for every `App: CanHandleApi` by +awaiting `self.handle_api(api)`. But that implementation would still have to prove that the awaited +future is `Send`, and the generic bound supplies no such guarantee. Wrapping the call in another +async block carries the same uncertainty into the wrapper. A concrete context and API let Rust check the actual selected implementation. In this fragment, `MockApp` is wired to a `QueryBalance` provider whose response is `u64` and whose future is sendable: @@ -110,20 +115,20 @@ impl CanHandleApiSend for MockApp { } ``` -The compiler resolves this call through the concrete wiring and checks that the returned future -satisfies the companion trait's `Send` promise. A provider that holds a non-sendable value across -an await can still make this implementation fail. The forwarding method verifies the property; -it does not make an otherwise non-sendable future safe to transfer. +Rust can now follow the concrete wiring and verify the selected provider's future against the +companion method's promise. If the provider holds a non-sendable value across an await, this +implementation can still fail. The forwarding body exposes a verified `Send` property rather than +changing the future's ability to move between threads. ## What it costs -This forwarding pattern needs an implementation for each context and API pair that exposes the -stronger interface. A macro can generate the repetitive bodies, but each generated implementation -still needs to satisfy the bound independently. +Each context and API pair that exposes the stronger interface needs a forwarding implementation. +A macro can generate those repetitive bodies, but Rust must still verify the `Send` requirement +for each pair. -The companion trait adds an interface to maintain. Methods that need the stronger guarantee need -corresponding signatures and forwarding bodies. Other methods can remain available through the -original [supertrait](/docs/reference/glossary#supertrait) without being duplicated. +That also leaves another interface to maintain. Each method needing the stronger guarantee needs +its own signature and forwarding body. Methods without that requirement can remain on the original +[supertrait](/docs/reference/glossary#supertrait), where callers can still use them. A companion trait is useful when the base interface must support both sendable and non-sendable futures. If every implementation must return a `Send` future, an explicit `impl Future + Send` diff --git a/docs/concepts/type-level-dsls.md b/docs/concepts/type-level-dsls.md index c4331b95..2056d60a 100644 --- a/docs/concepts/type-level-dsls.md +++ b/docs/concepts/type-level-dsls.md @@ -5,17 +5,20 @@ sidebar_position: 16 # Type-level DSLs -A type-level domain-specific language represents a program as Rust types and uses CGP wiring to -select implementations for its operations. The compiler checks and resolves the program's structure; -the selected operations run when called. This page develops a small arithmetic language, explains -how its syntax and interpretation can vary independently, and identifies the limits of the approach. -It assumes familiarity with [handlers](./handlers.md). +A type-level domain-specific language represents a program as Rust types and gives its operations +meaning through CGP providers. The program's structure can stay the same while different contexts +select different interpretations, and new syntax forms can bring their own providers. Rust checks +and resolves those choices at compile time; the selected operations execute when called. + +The [handler](./handlers.md) family's `Code` parameter gives the program type a place in a +computation's interface. An interpreter can use the structure of that type to choose and combine +providers for the program's parts. ## A program represented as a type -The handler family's `Code` parameter can describe a whole program. Each syntax form becomes a -marker type, and its parameters describe the program's structure. These fragments assume -`PhantomData` and CGP's prelude are imported: +To describe a language this way, give each syntax form a marker type. Its parameters can then +refer to other forms, allowing expressions to nest. These fragments assume `PhantomData` and CGP's +prelude are imported: ```rust pub struct Literal; @@ -29,14 +32,14 @@ Nesting the markers represents a compound expression: type Program = Multiply, Literal<3>>, Literal<4>>; ``` -`Program` represents `(2 + 3) * 4`. The marker types form the language's **abstract syntax**: -they describe the expression without implementing its evaluation. An evaluator can compute its -value, while a different interpreter could format the same expression as text. +The nesting describes `(2 + 3) * 4`, but the markers themselves do not evaluate it. They form the +language's **abstract syntax**, leaving providers to decide what the expression means. One +interpreter can calculate its value while another formats the same expression as text. -Larger languages can use type-level collections and strings within their syntax. -[`Product!`](/docs/reference/macros/product) can hold a pipeline's stages, and -[`Symbol!`](/docs/reference/macros/symbol) can represent a string in a type position. -These describe the fixed program; handlers can still receive runtime values as their inputs. +As the language grows, its syntax can include type-level collections and strings too. +[`Product!`](/docs/reference/macros/product) can describe a sequence of pipeline stages, while +[`Symbol!`](/docs/reference/macros/symbol) places a string in a type position. These types fix the +program's structure without preventing its handlers from receiving runtime input values. ## Providers give syntax its behavior @@ -56,10 +59,10 @@ impl Computer, ()> { } ``` -`EvalAdd` handles any `Add` whose operands the context can compute as `u64`. -Its requirements describe those computations without naming the providers that perform them. -Calling the context for each operand lets the addition provider work with syntax introduced by -other crates. +The bounds let `EvalAdd` handle any `Add` whose operands the context can compute as +`u64`. The addition provider asks the context for those results rather than selecting their +providers itself. This leaves each operand free to use syntax introduced elsewhere, including by +another crate. The context assembles an interpreter by selecting a provider for each syntax form. This fragment assumes an `Interpreter` context, matching `EvalLiteral` and `EvalMultiply` providers, and an import @@ -77,9 +80,9 @@ delegate_components! { } ``` -Each generic entry covers a family of expressions. The addition entry applies to every -`Add` with unit input, subject to the selected provider's requirements. Running the -program then uses the ordinary consumer method: +The generic entries let this small table cover nested expressions. In particular, the addition +entry applies to any `Add` with unit input once its provider requirements hold. +The complete `Program` can then run through the same consumer method used for other computations: ```rust Interpreter.compute(PhantomData::, ()) // 20 @@ -92,27 +95,27 @@ that multiplication can compute its operands, that addition can compute its oper each literal has an implementation. The resulting calls use static dispatch without a runtime syntax-tree lookup or interpreter dispatch loop. -The computation itself remains ordinary Rust execution. `compute` is not a `const fn`; type -checking does not evaluate its arithmetic. An optimizer may fold this constant example, but the -DSL does not guarantee that. A provider performing I/O or processing runtime input does that work -when the program runs. +Resolving those calls does not execute their bodies. `compute` is an ordinary function rather than +a `const fn`, so type checking does not evaluate its arithmetic. The optimizer may fold this +constant example, but the DSL makes no such guarantee. If a provider performs I/O or processes a +runtime input, that work happens when the program runs. ## Syntax and interpretation can vary independently -Different contexts can assign different meanings to the same program type. One context may -evaluate arithmetic while another pretty-prints it or estimates its cost. Each interpretation -needs providers with mutually compatible input and output types; the syntax stays unchanged. +With the syntax represented independently, another context can interpret the same program by +pretty-printing it or estimating its cost instead of evaluating it. Each interpretation needs +providers whose input and output types fit together, but it can leave the program type unchanged. -An independent crate can extend the syntax by defining another marker and its provider. -A context includes that form by adding wiring, without editing the base language's source. -Existing providers such as `EvalAdd` can accept the new form as an operand when it satisfies their -computation requirements. This addresses the syntax-extension side of the -[expression problem](./extensible-variants.md). +The same separation lets an independent crate introduce another marker and a provider for it. +A context then includes the new syntax through wiring, without changing the base language's source. +Because `EvalAdd` asks only for computations with compatible outputs, the new form can become one +of its operands as soon as it meets those requirements. This is how the design addresses the +syntax-extension side of the [expression problem](./extensible-variants.md). -Namespaces package a language's shared wiring for reuse. A child namespace can add entries for -new forms while inheriting the base language. Alternative interpretations must still respect the -[namespace rule](./namespaces.md#a-bound-entry-cannot-be-overridden): an inherited bound entry -cannot be replaced, so paths that need different providers must remain open in the shared base. +To reuse the interpreter's wiring, a namespace can package its shared entries and a child can +add entries for new forms. Replacing an interpretation requires more planning: under the +[namespace rule](./namespaces.md#a-bound-entry-cannot-be-overridden), a child cannot replace an +inherited binding. Any path whose provider should vary must remain open in the shared base. ## An optional surface syntax @@ -121,10 +124,10 @@ types. For example, it might turn a pipeline expression into nested types or a s `Symbol!`. Interpretation remains in the providers, so handwritten types and macro-generated types use the same implementations. -Separating syntax translation from execution keeps provider changes independent of the macro. -A generic surface syntax may also accept new fragments without a macro change. New grammatical -forms can still require changes to the parser or macro; type-level representation alone does not -make every syntax extension automatic. +Because the macro only translates syntax, changing a provider's behavior need not change the +macro. A sufficiently generic surface syntax may also accept new fragments as they are introduced. +New grammatical forms can still require parser or macro changes, however; representing the program +as types does not by itself make every syntax extension automatic. ## What it costs @@ -132,15 +135,14 @@ The program's type structure must be known at compile time. Runtime inputs and b providers are possible, but an arbitrary script loaded from a file cannot become a new Rust type inside the running binary. Such a script needs a runtime interpreter or a separate compilation step. -Nested program types can produce long trait-resolution errors. Missing wiring or incompatible -operand outputs may appear through several layers of provider bounds. Checking smaller expressions -before combining them helps locate the mismatch. +Nesting those types also nests the requirements Rust must resolve. A missing wiring entry or an +incompatible operand output can therefore produce a long error through several provider layers. +Checking smaller expressions before combining them helps narrow down which requirement failed. -Compilation must resolve the bounds and generate code for the concrete programs used. Large -programs and multiple interpretations can increase compile time and generated code size. The -tradeoff is most useful when reusable, extensible program descriptions justify those costs, such -as fixed build pipelines or protocol descriptions. Direct Rust functions are simpler for a small -set of fixed computations that does not need a language of its own. +Each concrete program and interpretation also gives the compiler bounds to resolve and code to +generate. Larger programs or more interpretations can increase compilation time and code size. +Fixed build pipelines and protocol descriptions may justify that cost through reuse and extensibility. +For a few fixed computations without that need, direct Rust functions are easier to maintain. ## Where to go next From 1d2e99ed581b0389715e896b4f4a798c0a136211 Mon Sep 17 00:00:00 2001 From: Soares Chen Date: Sat, 7 Nov 2026 00:33:18 +0100 Subject: [PATCH 210/516] Revise cargo-cgp pages with natural writing --- AGENTS.md | 8 +- docs/cargo-cgp/check.md | 95 +++++----- docs/cargo-cgp/command-reference.md | 69 ++++---- docs/cargo-cgp/editor-integration.md | 132 +++++++------- docs/cargo-cgp/error-codes.md | 250 +++++++++++++++------------ docs/cargo-cgp/expand.md | 102 ++++++----- docs/cargo-cgp/index.md | 109 ++++++------ docs/cargo-cgp/installation.md | 118 ++++++------- docs/cargo-cgp/reading-output.md | 124 ++++++------- docs/cargo-cgp/troubleshooting.md | 137 ++++++++------- 10 files changed, 592 insertions(+), 552 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 200689b4..e642b4af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,9 +131,11 @@ sets the full style and structure requirements for these pages. ## Use natural-writing for cargo-cgp pages When adding or revising a page under `docs/cargo-cgp/`, use the same natural-writing style -throughout the page, the lookup pages included. Keep tables, lists, and code blocks where the content -is a set of items or text a reader copies, and let the prose around them follow from one sentence to -the next. +throughout the page, the lookup pages included. Develop explanations in connected paragraphs; +a lookup page does not require point-first paragraphs or sentence fragments. Short error-code entries +may connect the cause, consequence, and remedy in prose. Keep tables and lists for options and other +sets, and code blocks for commands and quoted output. Preserve code headings and anchors so readers +can still look up an individual diagnostic. The knowledge base's [tooling-page writing guide](https://github.com/contextgeneric/cgp-knowledge-base/blob/main/website/writing-guides/tooling.md#writing-style) sets the full style requirements for these pages. diff --git a/docs/cargo-cgp/check.md b/docs/cargo-cgp/check.md index bf8e7908..f6296102 100644 --- a/docs/cargo-cgp/check.md +++ b/docs/cargo-cgp/check.md @@ -7,10 +7,10 @@ description: 'Run cargo cgp check in place of cargo check to get CGP compile err # Check -When a CGP error is hard to read, the first thing to try is `cargo cgp check`. It runs `cargo check` on -your project and rewrites the CGP errors it recognizes so that each one leads with its root cause. The -command is part of [`cargo-cgp`](./index.md), the error toolchain for -[Context-Generic Programming (CGP)](/docs/), and you use it wherever you would use `cargo check`: +When a CGP error is hard to read, run `cargo cgp check` where you would normally run `cargo check`. +It checks your project and rewrites recognized CGP errors to lead with their root causes. +The command belongs to [`cargo-cgp`](./index.md), the error toolchain for +[Context-Generic Programming (CGP)](/docs/): ```sh cargo cgp check @@ -27,7 +27,7 @@ cargo cgp check --all-targets ## Try it on a deliberate mistake -A small library with one mistake shows what the tool does. Start by creating a package: +A missing context field provides a small example you can try. Create a library package to hold it: ```sh cargo new --lib area-demo @@ -97,19 +97,22 @@ error[E0599]: [CGP-E001] missing field `height` on `Rectangle` For more information about this error, try `rustc --explain E0599`. ``` -The headline already names the problem, and the `help` line offers one fix: add a `height: f64` field to -`Rectangle`. Another fix is to wire a provider that does not read a height, and the tree shows why that -would work too. Read from the top, it says that `Rectangle` must implement `CanCalculateArea`, so its -provider `RectangleArea` must work for `Rectangle`, so `Rectangle` must have the field. Replace the -comment with `pub height: f64,` and the check passes. By contrast, plain `cargo check` reports this same -mistake without ever mentioning `height`, as the [overview](./index.md#the-problem-it-solves) shows. +Read the tree to connect the suggested fix to the failing call. `CanCalculateArea` is required, +so the chosen `RectangleArea` provider must work for `Rectangle`, which in turn needs `height`. +Adding the `f64` field satisfies that requirement. If the table selected the wrong provider, +however, correcting the wiring may be the intended change. + +In this program, replace the comment with `pub height: f64,` and check again; it passes. +For comparison, the [overview](./index.md#the-problem-it-solves) shows the original `cargo check` +error, which never names the missing field. ## Check the wiring where you write it -So far the error has appeared at the call to `area`, because wiring is lazy: without a check, the error -appears wherever the trait is first used. In a larger program, that place can be far from the line you -need to change. A [`check_components!`](/docs/reference/macros/check_components) block moves the error to -the wiring. Replace `print_area` in the program above with: +The error points to `area` because the call is the first place this program requires the trait. +A wiring entry alone does not verify its provider's dependencies, so in a larger program the first +failure might occur far from that entry. Adding a +[`check_components!`](/docs/reference/macros/check_components) block beside the wiring asks for +the proof there. Replace `print_area` above with: ```rust check_components! { @@ -138,22 +141,23 @@ error[E0277]: [CGP-E001] missing field `height` on `Rectangle` For more information about this error, try `rustc --explain E0277`. ``` -The `check_components!` block also changes what plain `cargo check` can tell you. With the block in place, -stable Rust names the missing requirement, but it spells the field name one character at a time, as a -type-level string. Because it compares that name with the `width` field the struct does have, it also -prints the letter the two share in that position as `_`: +That explicit check helps ordinary `cargo check` expose the missing requirement too. Its field +tag still appears as a type-level string, however, with one type per character. When comparing +`height` with the existing `width` field, Rust also replaces a shared character at the same position +with `_`: ```text help: the trait `HasField>>>>>>>` is not implemented for `Rectangle` ``` -That line is an excerpt from an error of about thirty lines whose headline names -`CanUseComponent`, a trait the macros generated. The tool turns all of it into -the message above. +Even with the cause exposed, the raw diagnostic runs to about thirty lines and leads with the +generated `CanUseComponent` bound. The tool rewrites that report into +the field error and dependency chain shown above. ## What a check does differently -The rewriting is possible because a check is `cargo check` with three settings the tool chooses for you: +To recover and present these causes, the tool runs `cargo check` with its own compiler settings +and build location. The changes work together: - **The pinned nightly:** a check compiles under the tool's own nightly, so the compiler inside the driver matches the one that builds your code. Your project's toolchain is untouched. @@ -163,46 +167,45 @@ The rewriting is possible because a check is `cargo check` with three settings t directory while it builds there, so a shared one would make each check wait for your other cargo runs and your editor's, and the reverse. -Because the tool picks these settings, a check is a diagnostic pass rather than a reproduction of your own -build, the way Clippy runs under settings of its own. A passing check therefore does not promise a passing -`cargo check`. For example, two namespaces that inherit from each other are rejected by stable Rust but -compile under the tool. Your toolchain's `cargo check` remains the authority on whether the code compiles. +Using a separate compiler and solver makes this a diagnostic pass rather than a reproduction +of your project's check. Like Clippy under its own settings, it can give a different result. +Mutually inheriting namespaces, for example, pass this check but are rejected by stable Rust. +Use your own toolchain's `cargo check` to decide whether the code compiles. -The `target/cgp` directory sits inside your project's own target directory, wherever in the project you -run the command, so it follows a configured `build.target-dir` or a set `CARGO_TARGET_DIR`. With -`CARGO_TARGET_DIR=/build`, for example, the check builds in `/build/cgp`. To choose the check's directory -exactly, pass `--target-dir`. +The build location follows the project's target directory rather than the directory you invoke +the command from. A configured `build.target-dir` or `CARGO_TARGET_DIR` therefore moves the tool's +artifacts too: with `CARGO_TARGET_DIR=/build`, they go in `/build/cgp`. Pass `--target-dir` if you +want to choose the check's directory exactly. ## Flags are cargo's, not the tool's -The tool appends your arguments to `cargo check` and lets cargo handle them, so every `cargo check` flag -behaves as it normally does. Cargo also validates them, which means an unknown flag produces cargo's -error, `error: unexpected argument '--nope' found`, rather than a message from the tool. In the same way, -`cargo cgp check --help` prints cargo's help for `cargo check` and exits without running a check. For the -tool's own commands, run `cargo cgp --help`. +Since cargo receives and validates the forwarded flags, an unknown flag produces cargo's own +`error: unexpected argument '--nope' found`. Help follows the same division: `cargo cgp check --help` +displays cargo's help without running a check, while `cargo cgp --help` describes the tool's commands. -The tool reads three of the flags itself, `--target-dir`, `--manifest-path`, and `--config`, and only to -decide where `target/cgp` goes. It still passes all three on to cargo. +Before forwarding the arguments, the tool reads `--target-dir`, `--manifest-path`, and `--config` +to determine the build directory. Cargo still receives all three and handles their usual behavior. ## In your editor -The same check can run in your editor, so the errors you see there lead with their root cause too. -rust-analyzer can run `cargo cgp check` every time you save, and it takes one setting, which -[Editor integration](./editor-integration.md) gives for VS Code, along with what the switch changes. +You can also make rust-analyzer run this command whenever you save. The +[Editor integration](./editor-integration.md) page gives the VS Code setting and explains how the +override affects the editor's checks. ## When it will not help -A check reports only what your code asks the compiler to prove. Wiring that nothing uses and nothing -checks produces no error, from this tool or any other, which is why -[`check_components!`](/docs/reference/macros/check_components) is worth adding for every context you wire. +Neither this tool nor ordinary `cargo check` reports a requirement that the program never asks +to prove. Unused, unchecked wiring can therefore remain invalid without an error. Adding +[`check_components!`](/docs/reference/macros/check_components) for each context makes those +requirements explicit. Some errors also pass through as the compiler wrote them. `cargo cgp check` leads with the root cause for the classes it recognizes, and the tool does not yet reshape every class. [Reading the output](./reading-output.md#errors-that-pass-through-unchanged) lists the ones you are most likely to meet. -Finally, the tool reshapes errors in your workspace's own crates only. A dependency outside the workspace -is compiled normally, so an error inside it arrives as the compiler wrote it. +Errors outside your workspace are another boundary. Dependencies compile normally, so their +errors arrive without the tool's rewrites. If the command itself will not run, see [Troubleshooting](./troubleshooting.md). diff --git a/docs/cargo-cgp/command-reference.md b/docs/cargo-cgp/command-reference.md index 84ad7932..5e8df59c 100644 --- a/docs/cargo-cgp/command-reference.md +++ b/docs/cargo-cgp/command-reference.md @@ -7,9 +7,9 @@ description: 'Every cargo-cgp command and option, the environment variables it r # Command reference -When you need to look up a flag or a variable, this page lists everything [`cargo-cgp`](./index.md) version -0.1.0 accepts and changes: its commands, their options, the environment variables it reads and sets, the -files it creates, and its exit status. The other pages in this section explain how to use them. +This page collects the commands, options, environment variables, files, and exit statuses of +[`cargo-cgp`](./index.md) version 0.1.0. Use it to look up an exact flag or setting; the other +pages in this section develop working examples. ## Running it @@ -29,7 +29,8 @@ Two options stand in for a command: ## Commands -The tool has four commands. Two read your code, and two install and update the tool itself: +Use `check` and `expand` to inspect a project. The other commands, `setup` and `update`, prepare +and maintain the tool's own installation: | Command | Does | Details | |---|---|---| @@ -44,9 +45,9 @@ The tool has four commands. Two read your code, and two install and update the t cargo cgp check [CARGO CHECK ARGS]... ``` -Every argument is passed to `cargo check`, which also validates them, so the command takes every -`cargo check` flag and no flags of its own. `cargo cgp check --help` prints `cargo check`'s help and does not -run a check. Two flags matter more than the rest: +`check` forwards its arguments to `cargo check`, which validates them. It therefore accepts +cargo's check flags without adding flags of its own, and `cargo cgp check --help` displays cargo's +help instead of checking a project. Two options are especially useful when configuring a check: - **`--target-dir